signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def set_deplyment_vcenter_params ( vcenter_resource_model , deploy_params ) : """Sets the vcenter parameters if not already set at the deployment option : param deploy _ params : vCenterVMFromTemplateResourceModel or vCenterVMFromImageResourceModel : type vcenter _ resource _ model : VMwarevCenterResourceModel"...
# Override attributes deploy_params . vm_cluster = deploy_params . vm_cluster or vcenter_resource_model . vm_cluster deploy_params . vm_storage = deploy_params . vm_storage or vcenter_resource_model . vm_storage deploy_params . vm_resource_pool = deploy_params . vm_resource_pool or vcenter_resource_model . vm_resource_...
def from_indra_statements ( stmts , name : Optional [ str ] = None , version : Optional [ str ] = None , description : Optional [ str ] = None , authors : Optional [ str ] = None , contact : Optional [ str ] = None , license : Optional [ str ] = None , copyright : Optional [ str ] = None , disclaimer : Optional [ str ]...
from indra . assemblers . pybel import PybelAssembler pba = PybelAssembler ( stmts = stmts , name = name , version = version , description = description , authors = authors , contact = contact , license = license , copyright = copyright , disclaimer = disclaimer , ) graph = pba . make_model ( ) return graph
def zoom_in ( self , incr = 1.0 ) : """Zoom in a level . Also see : meth : ` zoom _ to ` . Parameters incr : float ( optional , defaults to 1) The value to increase the zoom level"""
level = self . zoom . calc_level ( self . t_ [ 'scale' ] ) self . zoom_to ( level + incr )
def on_ctcp ( self , connection , event ) : """Default handler for ctcp events . Replies to VERSION and PING requests and relays DCC requests to the on _ dccchat method ."""
nick = event . source . nick if event . arguments [ 0 ] == "VERSION" : connection . ctcp_reply ( nick , "VERSION " + self . get_version ( ) ) elif event . arguments [ 0 ] == "PING" : if len ( event . arguments ) > 1 : connection . ctcp_reply ( nick , "PING " + event . arguments [ 1 ] ) elif ( event . ar...
def _isstring ( dtype ) : """Given a numpy dtype , determines whether it is a string . Returns True if the dtype is string or unicode ."""
return dtype . type == numpy . unicode_ or dtype . type == numpy . string_
def QA_util_date_int2str ( int_date ) : """类型datetime . datatime : param date : int 8位整数 : return : 类型str"""
date = str ( int_date ) if len ( date ) == 8 : return str ( date [ 0 : 4 ] + '-' + date [ 4 : 6 ] + '-' + date [ 6 : 8 ] ) elif len ( date ) == 10 : return date
def summary ( x , rm_nan = False , debug = False ) : """Compute basic statistical parameters . Parameters x : 1d numpy array , float Input array with values which statistical properties are requested . rm _ nan : bool If True , filter out NaN values before computing statistics . debug : bool If True...
# protections if type ( x ) is np . ndarray : xx = np . copy ( x ) else : if type ( x ) is list : xx = np . array ( x ) else : raise ValueError ( 'x=' + str ( x ) + ' must be a numpy.ndarray' ) if xx . ndim is not 1 : raise ValueError ( 'xx.dim=' + str ( xx . ndim ) + ' must be 1' ) # fi...
def drawBackground ( self , painter , opt , rect , brush ) : """Make sure the background extends to 0 for the first item . : param painter | < QtGui . QPainter > rect | < QtCore . QRect > brush | < QtGui . QBrush >"""
if not brush : return painter . setPen ( QtCore . Qt . NoPen ) painter . setBrush ( brush ) painter . drawRect ( rect )
def _ReadStructureDataTypeDefinition ( self , definitions_registry , definition_values , definition_name , is_member = False ) : """Reads a structure data type definition . Args : definitions _ registry ( DataTypeDefinitionsRegistry ) : data type definitions registry . definition _ values ( dict [ str , obj...
if is_member : error_message = 'data type not supported as member' raise errors . DefinitionReaderError ( definition_name , error_message ) return self . _ReadDataTypeDefinitionWithMembers ( definitions_registry , definition_values , data_types . StructureDefinition , definition_name , supports_conditions = Tru...
def calc_hazard_curves ( groups , ss_filter , imtls , gsim_by_trt , truncation_level = None , apply = sequential_apply , filter_distance = 'rjb' , reqv = None ) : """Compute hazard curves on a list of sites , given a set of seismic source groups and a dictionary of ground shaking intensity models ( one per tect...
# This is ensuring backward compatibility i . e . processing a list of # sources if not isinstance ( groups [ 0 ] , SourceGroup ) : # sent a list of sources odic = groupby ( groups , operator . attrgetter ( 'tectonic_region_type' ) ) groups = [ SourceGroup ( trt , odic [ trt ] , 'src_group' , 'indep' , 'indep' ...
def _scan_file ( filename , sentinel , source_type = 'import' ) : '''Generator that performs the actual scanning of files . Yeilds a tuple containing import type , import path , and an extra file that should be scanned . Extra file scans should be the file or directory that relates to the import name .'''
filename = os . path . abspath ( filename ) real_filename = os . path . realpath ( filename ) if os . path . getsize ( filename ) <= max_file_size : if real_filename not in sentinel and os . path . isfile ( filename ) : sentinel . add ( real_filename ) basename = os . path . basename ( filename ) ...
def DeletePendingNotification ( self , timestamp ) : """Deletes the pending notification with the given timestamp . Args : timestamp : The timestamp of the notification . Assumed to be unique . Raises : UniqueKeyError : Raised if multiple notifications have the timestamp ."""
shown_notifications = self . Get ( self . Schema . SHOWN_NOTIFICATIONS ) if not shown_notifications : shown_notifications = self . Schema . SHOWN_NOTIFICATIONS ( ) pending = self . Get ( self . Schema . PENDING_NOTIFICATIONS ) if not pending : return # Remove all notifications with the given timestamp from pend...
def upsert_document_acl_trigger ( plpy , td ) : """Trigger for filling in acls when legacy publishes . A compatibility trigger to upsert authorization control entries ( ACEs ) for legacy publications ."""
modified_state = "OK" uuid_ = td [ 'new' ] [ 'uuid' ] authors = td [ 'new' ] [ 'authors' ] and td [ 'new' ] [ 'authors' ] or [ ] maintainers = td [ 'new' ] [ 'maintainers' ] and td [ 'new' ] [ 'maintainers' ] or [ ] is_legacy_publication = td [ 'new' ] [ 'version' ] is not None if not is_legacy_publication : return...
def get_gan_loss ( self , true_frames , gen_frames , name ) : """Get the discriminator + generator loss at every step . This performs an 1:1 update of the discriminator and generator at every step . Args : true _ frames : 5 - D Tensor of shape ( num _ steps , batch _ size , H , W , C ) Assumed to be groun...
# D - STEP with tf . variable_scope ( "%s_discriminator" % name , reuse = tf . AUTO_REUSE ) : gan_d_loss , _ , fake_logits_stop = self . d_step ( true_frames , gen_frames ) # G - STEP with tf . variable_scope ( "%s_discriminator" % name , reuse = True ) : gan_g_loss_pos_d , gan_g_loss_neg_d = self . g_step ( ge...
def to_string ( self , indentLevel = 1 , title = True , tags = None , projects = None , tasks = None , notes = None ) : """* convert this taskpaper object to a string * * * Key Arguments : * * - ` ` indentLevel ` ` - - the level of the indent for this object . Default * 1 * . - ` ` title ` ` - - print the tit...
indent = indentLevel * "\t" objectString = "" if title : try : # NONE DOCUMENT OBJECTS objectString += self . title except : pass try : if tags : tagString = ( " @" ) . join ( tags ) else : tagString = ( " @" ) . join ( self . tags ) if len ( t...
def json_to_numpy ( string_like , dtype = None ) : # type : ( str ) - > np . array """Convert a JSON object to a numpy array . Args : string _ like ( str ) : JSON string . dtype ( dtype , optional ) : Data type of the resulting array . If None , the dtypes will be determined by the contents of each column ,...
data = json . loads ( string_like ) return np . array ( data , dtype = dtype )
def set_position ( self , val ) : """Set the devive OPEN LEVEL ."""
if val == 0 : self . close ( ) else : setlevel = 255 if val < 1 : setlevel = val * 100 elif val <= 0xff : setlevel = val set_command = StandardSend ( self . _address , COMMAND_LIGHT_ON_0X11_NONE , cmd2 = setlevel ) self . _send_method ( set_command , self . _open_message_received...
def filepath_to_uri ( path ) : """Convert an file system path to a URI portion that is suitable for inclusion in a URL . We are assuming input is either UTF - 8 or unicode already . This method will encode certain chars that would normally be recognized as special chars for URIs . Note that this method does...
if path is None : return path # I know about ` os . sep ` and ` os . altsep ` but I want to leave # some flexibility for hardcoding separators . return urllib . quote ( path . replace ( "\\" , "/" ) , safe = b"/~!*()'" )
def final ( arg ) : """Mark a class or method as _ final _ . Final classes are those that end the inheritance chain , i . e . forbid further subclassing . A final class can thus be only instantiated , not inherited from . Similarly , methods marked as final in a superclass cannot be overridden in any of t...
if inspect . isclass ( arg ) : if not isinstance ( arg , ObjectMetaclass ) : raise ValueError ( "@final can only be applied to a class " "that is a subclass of Object" ) elif not is_method ( arg ) : raise TypeError ( "@final can only be applied to classes or methods" ) method = arg . method if isinstanc...
def show_wbridges ( self ) : """Visualizes water bridges"""
grp = self . getPseudoBondGroup ( "Water Bridges-%i" % self . tid , associateWith = [ self . model ] ) grp . lineWidth = 3 for i , wbridge in enumerate ( self . plcomplex . waterbridges ) : c = grp . newPseudoBond ( self . atoms [ wbridge . water_id ] , self . atoms [ wbridge . acc_id ] ) c . color = self . col...
def _filter ( self , blacklist = None , newest_only = False , type_filter = None , ** kwargs ) : """Args : blacklist ( tuple ) : Iterable of of BlacklistEntry objects newest _ only ( bool ) : Only the newest version of each plugin is returned type ( str ) : Plugin type to retrieve name ( str ) : Plugin name...
plugins = DictWithDotNotation ( ) filtered_name = kwargs . get ( self . _key_attr , None ) for key , val in self . _items ( type_filter , filtered_name ) : plugin_blacklist = None skip = False if blacklist : # Assume blacklist is correct format since it is checked by PluginLoade plugin_blacklist = [...
def request ( cls , method , url , ** kwargs ) : """Make a http call to a remote API and return a json response ."""
user_agent = 'gandi.cli/%s' % __version__ headers = { 'User-Agent' : user_agent , 'Content-Type' : 'application/json; charset=utf-8' } if kwargs . get ( 'headers' ) : headers . update ( kwargs . pop ( 'headers' ) ) try : response = requests . request ( method , url , headers = headers , ** kwargs ) response...
def write_line ( self , message ) : """Unbuffered printing to stdout ."""
self . out . write ( message + "\n" ) self . out . flush ( )
def execute ( self , env , args ) : """Prints task information . ` env ` Runtime ` ` Environment ` ` instance . ` args ` Arguments object from arg parser ."""
start = self . _fuzzy_time_parse ( args . start ) if not start : raise errors . FocusError ( u'Invalid start period provided' ) stats = self . _get_stats ( env . task , start ) self . _print_stats ( env , stats )
def refill ( self , sess ) : """Clears the current queue and then refills it with new data ."""
sess . run ( self . _clear_queue ) # Run until full . while sess . run ( self . _fill_queue ) : pass
def _finalize ( self , dtype = np . uint8 ) : """Finalize the image , that is put it in RGB mode , and set the channels in unsigned 8bit format ( [ 0,255 ] range ) ( if the * dtype * doesn ' t say otherwise ) ."""
channels = [ ] if self . mode == "P" : self . convert ( "RGB" ) if self . mode == "PA" : self . convert ( "RGBA" ) for chn in self . channels : if isinstance ( chn , np . ma . core . MaskedArray ) : final_data = chn . data . clip ( 0 , 1 ) * np . iinfo ( dtype ) . max else : final_data =...
def setup ( self , app ) : """Setup the plugin and prepare application ."""
super ( Plugin , self ) . setup ( app ) if 'jinja2' not in app . plugins : raise PluginException ( 'The plugin requires Muffin-Jinja2 plugin installed.' ) self . cfg . prefix = self . cfg . prefix . rstrip ( '/' ) + '/' self . cfg . exclude . append ( self . cfg . prefix ) # Setup debugtoolbar templates app . ps . ...
def is_reserved ( self ) : """Test if the address is otherwise IETF reserved . Returns : A boolean , True if the address is within one of the reserved IPv6 Network ranges ."""
reserved_nets = [ IPv6Network ( u'::/8' ) , IPv6Network ( u'100::/8' ) , IPv6Network ( u'200::/7' ) , IPv6Network ( u'400::/6' ) , IPv6Network ( u'800::/5' ) , IPv6Network ( u'1000::/4' ) , IPv6Network ( u'4000::/3' ) , IPv6Network ( u'6000::/3' ) , IPv6Network ( u'8000::/3' ) , IPv6Network ( u'A000::/3' ) , IPv6Networ...
def update_model_connector ( self , model_id , connector ) : """Update the connector information for a given model . Returns None if the specified model not exist . Parameters model _ id : string Unique model identifier connector : dict New connection information Returns ModelHandle"""
# Validate the given connector information self . validate_connector ( connector ) # Connector information is valid . Ok to update the model . return self . registry . update_connector ( model_id , connector )
def read ( self , amount : int = - 1 ) -> bytes : '''Read data .'''
assert self . _state == ConnectionState . created , 'Expect conn created. Got {}.' . format ( self . _state ) data = yield from self . run_network_operation ( self . reader . read ( amount ) , close_timeout = self . _timeout , name = 'Read' ) return data
def diff ( a , b ) : """Compares JSON objects : param a : : param b : : return : difference object a vs b"""
delta = diff ( a , b ) if not a : return delta for item in delta : if isinstance ( a [ item ] , list ) : if delta [ item ] == [ ] : delta [ item ] = { JSONUtils . DIFF_DELETE : a [ item ] } elif isinstance ( delta [ item ] , dict ) : for key in delta [ item ] . keys ( ) :...
def getList ( self ) : """查询敏感词列表方法 方法 @ return code : 返回码 , 200 为正常 。 @ return word : 敏感词内容 。 @ return errorMessage : 错误信息 。"""
desc = { "name" : "ListWordfilterReslut" , "desc" : "listWordfilter返回结果" , "fields" : [ { "name" : "code" , "type" : "Integer" , "desc" : "返回码,200 为正常。" } , { "name" : "word" , "type" : "String" , "desc" : "敏感词内容。" } , { "name" : "errorMessage" , "type" : "String" , "desc" : "错误信息。" } ] } r = self . call_api ( method =...
def oneday_weather_forecast ( location = 'Portland, OR' , inputs = ( 'Min Temperature' , 'Mean Temperature' , 'Max Temperature' , 'Max Humidity' , 'Mean Humidity' , 'Min Humidity' , 'Max Sea Level Pressure' , 'Mean Sea Level Pressure' , 'Min Sea Level Pressure' , 'Wind Direction' ) , outputs = ( 'Min Temperature' , 'Me...
date = make_date ( date or datetime . datetime . now ( ) . date ( ) ) num_years = int ( num_years or 10 ) years = range ( date . year - num_years , date . year + 1 ) df = weather . daily ( location , years = years , use_cache = use_cache , verbosity = verbosity ) . sort ( ) # because up - to - date weather history was ...
def _generate_storage_broker_lookup ( ) : """Return dictionary of available storage brokers ."""
storage_broker_lookup = dict ( ) for entrypoint in iter_entry_points ( "dtool.storage_brokers" ) : StorageBroker = entrypoint . load ( ) storage_broker_lookup [ StorageBroker . key ] = StorageBroker return storage_broker_lookup
def render_query ( dataset , tables , select = None , conditions = None , groupings = None , having = None , order_by = None , limit = None ) : """Render a query that will run over the given tables using the specified parameters . Parameters dataset : str The BigQuery dataset to query data from tables : U...
if None in ( dataset , tables ) : return None query = "%s %s %s %s %s %s %s" % ( _render_select ( select ) , _render_sources ( dataset , tables ) , _render_conditions ( conditions ) , _render_groupings ( groupings ) , _render_having ( having ) , _render_order ( order_by ) , _render_limit ( limit ) ) return query
def media_update ( self , id , description = None , focus = None ) : """Update the metadata of the media file with the given ` id ` . ` description ` and ` focus ` are as in ` media _ post ( ) ` _ . Returns the updated ` media dict ` _ ."""
id = self . __unpack_id ( id ) if focus != None : focus = str ( focus [ 0 ] ) + "," + str ( focus [ 1 ] ) params = self . __generate_params ( locals ( ) , [ 'id' ] ) return self . __api_request ( 'PUT' , '/api/v1/media/{0}' . format ( str ( id ) ) , params )
def StartTag ( self , name , attrs ) : '''A method which is called by the SAX parser when a new tag is encountered : param name : name of the tag : param attrs : the tag ' s attributes : return : none , side effect of modifying bits of the current class'''
if name not in self . excluded : if name in self . structure . keys ( ) : self . handler = self . structure [ name ] self . tags . append ( name ) if attrs is not None : self . attribs [ name ] = attrs self . isDynamic = CheckDynamics ( name ) if self . isDynamic and "dynamics" in se...
def load ( self ) : """This loads the variables and attributes simultaneously . A centralized loading function makes it easier to create data stores that do automatic encoding / decoding . For example : : class SuffixAppendingDataStore ( AbstractDataStore ) : def load ( self ) : variables , attributes =...
variables = FrozenOrderedDict ( ( _decode_variable_name ( k ) , v ) for k , v in self . get_variables ( ) . items ( ) ) attributes = FrozenOrderedDict ( self . get_attrs ( ) ) return variables , attributes
def importdb ( indir ) : """Import a previously exported anchore DB"""
ecode = 0 try : imgdir = os . path . join ( indir , "images" ) feeddir = os . path . join ( indir , "feeds" ) storedir = os . path . join ( indir , "storedfiles" ) for d in [ indir , imgdir , feeddir , storedir ] : if not os . path . exists ( d ) : raise Exception ( "specified direct...
def get_F_y ( fname = 'binzegger_connectivity_table.json' , y = [ 'p23' ] ) : '''Extract frequency of occurrences of those cell types that are modeled . The data set contains cell types that are not modeled ( TCs etc . ) The returned percentages are renormalized onto modeled cell - types , i . e . they sum up t...
# Load data from json dictionary f = open ( fname , 'r' ) data = json . load ( f ) f . close ( ) occurr = [ ] for cell_type in y : occurr += [ data [ 'data' ] [ cell_type ] [ 'occurrence' ] ] return list ( np . array ( occurr ) / np . sum ( occurr ) )
def iter_list ( self , id , * args , ** kwargs ) : """Get a list of attachments . Whereas ` ` list ` ` fetches a single page of attachments according to its ` ` limit ` ` and ` ` page ` ` arguments , ` ` iter _ list ` ` returns all attachments by internally making successive calls to ` ` list ` ` . : param ...
l = partial ( self . list , id ) return self . service . iter_list ( l , * args , ** kwargs )
def get_trending_daily ( lang = "" ) : """Fetches repos in " Trending Daily " Github section : param lang : Coding language : return : List of GithubUserRepository"""
url = "https://github.com/trending/" url += str ( lang ) . lower ( ) . replace ( " " , "" ) + "?since=daily" api_content_request = urllib . request . Request ( url ) api_content_response = urllib . request . urlopen ( api_content_request ) . read ( ) . decode ( "utf-8" ) # parse response soup = BeautifulSoup ( api_cont...
def apply_range ( self , sampfrom = 0 , sampto = None ) : """Filter the annotation attributes to keep only items between the desired sample values"""
sampto = sampto or self . sample [ - 1 ] kept_inds = np . intersect1d ( np . where ( self . sample >= sampfrom ) , np . where ( self . sample <= sampto ) ) for field in [ 'sample' , 'label_store' , 'subtype' , 'chan' , 'num' ] : setattr ( self , field , getattr ( self , field ) [ kept_inds ] ) self . aux_note = [ s...
def demo_usage ( n_data = 50 , n_fit = 537 , nhead = 5 , ntail = 5 , plot = False , alt = 0 ) : """Plots a noisy sine curve and the fitting to it . Also presents the error and the error in the approximation of its first derivative ( cosine curve ) Usage example for benchmarking : $ time python sine . py - -...
x0 , xend = 0 , 5 # shaky linspace - 5 % to + 5 % noise x_data = ( np . linspace ( x0 , xend , n_data ) + np . random . rand ( n_data ) * ( xend - x0 ) / n_data / 1.5 ) y_data = np . sin ( x_data ) * ( 1.0 + 0.1 * ( np . random . rand ( n_data ) - 0.5 ) ) x_fit = np . linspace ( x0 , xend , n_fit ) # Edges behave badly...
def rename_script ( rename = None ) : # noqa : E501 """Rename a script Rename a script # noqa : E501 : param rename : The data needed to save this script : type rename : dict | bytes : rtype : Response"""
if connexion . request . is_json : rename = Rename . from_dict ( connexion . request . get_json ( ) ) # noqa : E501 if ( not hasAccess ( ) ) : return redirectUnauthorized ( ) driver = LoadedDrivers . getDefaultDriver ( ) if ( not driver . renameScript ( rename . original . name , rename . new . name ) ) : r...
def radial_symmetry ( mesh ) : """Check whether a mesh has rotational symmetry . Returns symmetry : None or str None No rotational symmetry ' radial ' Symmetric around an axis ' spherical ' Symmetric around a point axis : None or ( 3 , ) float Rotation axis or point section : None or ( 3 , 2 ) float...
# if not a volume this is meaningless if not mesh . is_volume : return None , None , None # the sorted order of the principal components of inertia ( 3 , ) float order = mesh . principal_inertia_components . argsort ( ) # we are checking if a geometry has radial symmetry # if 2 of the PCI are equal , it is a revolv...
def log_warn ( message , args ) : """Logs a warning message using the default logger ."""
get_logger ( DEFAULT_LOGGER , log_creation = False ) . log ( logging . WARNING , message , * args )
def bspline_to_nurbs ( obj ) : """Converts non - rational parametric shapes to rational ones . : param obj : B - Spline shape : type obj : BSpline . Curve , BSpline . Surface or BSpline . Volume : return : NURBS shape : rtype : NURBS . Curve , NURBS . Surface or NURBS . Volume : raises : TypeError"""
# B - Spline - > NURBS if isinstance ( obj , BSpline . Curve ) : return _convert . convert_curve ( obj , NURBS ) elif isinstance ( obj , BSpline . Surface ) : return _convert . convert_surface ( obj , NURBS ) elif isinstance ( obj , BSpline . Volume ) : return _convert . convert_volume ( obj , NURBS ) else ...
def kernel_integrity ( attrs = None , where = None ) : '''Return kernel _ integrity information from osquery CLI Example : . . code - block : : bash salt ' * ' osquery . kernel _ integrity'''
if __grains__ [ 'os_family' ] in [ 'RedHat' , 'Debian' ] : return _osquery_cmd ( table = 'kernel_integrity' , attrs = attrs , where = where ) return { 'result' : False , 'comment' : 'Only available on Red Hat or Debian based systems.' }
def generate_data ( dim = 40 , num_samples = 30000 , num_bins = 10 , sparse = False ) : """Generates data following appendix V of ( Poirazi & Mel , 2001 ) . Positive and negative examples are drawn from the same distribution , but are multiplied by different square matrices , one of them uniform on [ - 1 , 1 ...
positives , negatives = [ ] , [ ] positive , negative = generate_matrices ( dim ) for i in range ( num_samples ) : phase_1 = generate_phase_1 ( dim ) phase_2 = generate_phase_2 ( phase_1 , dim ) if i < num_samples / 2 : positives . append ( numpy . dot ( positive , phase_2 ) ) else : neg...
def compatible ( self , a , b ) : """Return ` True ` if type * a * is compatible with type * b * ."""
return len ( set ( [ a ] + self . descendants ( a ) ) . intersection ( [ b ] + self . descendants ( b ) ) ) > 0
def _set_where ( self ) : """Set the where clause for the relation query . : return : self : rtype : BelongsToMany"""
foreign = self . get_foreign_key ( ) self . _query . where ( foreign , "=" , self . _parent . get_key ( ) ) return self
def as_dict ( self ) : """turns attribute filter object into python dictionary"""
output_dictionary = dict ( ) for key , value in iter ( self . _key_map . items ( ) ) : if isinstance ( value , bool ) : output_dictionary [ key ] = value elif isinstance ( value , self . __class__ ) : output_dictionary [ key ] = value . as_dict ( ) return output_dictionary
def deepvalidation ( self ) : """Perform deep validation of this element . Raises : : class : ` DeepValidationError `"""
if self . doc and self . doc . deepvalidation and self . parent . set and self . parent . set [ 0 ] != '_' : try : self . doc . setdefinitions [ self . parent . set ] . testsubclass ( self . parent . cls , self . subset , self . cls ) except KeyError as e : if self . parent . cls and not self . ...
def get_categories ( blog_id , username , password ) : """metaWeblog . getCategories ( blog _ id , username , password ) = > category structure [ ]"""
authenticate ( username , password ) site = Site . objects . get_current ( ) return [ category_structure ( category , site ) for category in Category . objects . all ( ) ]
def i2c_config ( self , read_delay_time = 0 ) : """This method configures Arduino i2c with an optional read delay time . : param read _ delay _ time : firmata i2c delay time : returns : No return value"""
task = asyncio . ensure_future ( self . core . i2c_config ( read_delay_time ) ) self . loop . run_until_complete ( task )
def nice ( self , work_spec_name , nice ) : '''Change the priority of an existing work spec .'''
with self . registry . lock ( identifier = self . worker_id ) as session : session . update ( NICE_LEVELS , dict ( work_spec_name = nice ) )
def _families_and_addresses ( self , hostname , port ) : """Yield pairs of address families and addresses to try for connecting . : param str hostname : the server to connect to : param int port : the server port to connect to : returns : Yields an iterable of ` ` ( family , address ) ` ` tuples"""
guess = True addrinfos = socket . getaddrinfo ( hostname , port , socket . AF_UNSPEC , socket . SOCK_STREAM ) for ( family , socktype , proto , canonname , sockaddr ) in addrinfos : if socktype == socket . SOCK_STREAM : yield family , sockaddr guess = False # some OS like AIX don ' t indicate SOCK _...
def _write_directory_records ( self , vd , outfp , progress ) : # type : ( headervd . PrimaryOrSupplementaryVD , BinaryIO , PyCdlib . _ Progress ) - > None '''An internal method to write out the directory records from a particular Volume Descriptor . Parameters : vd - The Volume Descriptor to write the Direct...
log_block_size = vd . logical_block_size ( ) le_ptr_offset = 0 be_ptr_offset = 0 dirs = collections . deque ( [ vd . root_directory_record ( ) ] ) while dirs : curr = dirs . popleft ( ) curr_dirrecord_offset = 0 if curr . is_dir ( ) : if curr . ptr is None : raise pycdlibexception . PyCd...
def _remove_unlistened_nets ( block ) : """Removes all nets that are not connected to an output wirevector"""
listened_nets = set ( ) listened_wires = set ( ) prev_listened_net_count = 0 def add_to_listened ( net ) : listened_nets . add ( net ) listened_wires . update ( net . args ) for a_net in block . logic : if a_net . op == '@' : add_to_listened ( a_net ) elif any ( isinstance ( destW , Output ) for...
def connect_command ( self ) : '''Generates a JSON string with the params to be used when sending CONNECT to the server . - > > CONNECT { " verbose " : false , " pedantic " : false , " lang " : " python2 " }'''
options = { "verbose" : self . options [ "verbose" ] , "pedantic" : self . options [ "pedantic" ] , "lang" : __lang__ , "version" : __version__ , "protocol" : PROTOCOL } if "auth_required" in self . _server_info : if self . _server_info [ "auth_required" ] == True : # In case there is no password , then consider ha...
def _operator ( self , op , close_group = False ) : """Add an operator between terms . There must be a term added before using this method . All operators have helpers , so this method is usually not necessary to directly invoke . Arguments : op ( str ) : The operator to add . Must be in the OP _ LIST . c...
op = op . upper ( ) . strip ( ) if op not in OP_LIST : raise ValueError ( "Error: '{}' is not a valid operator." . format ( op ) ) else : if close_group : op = ") " + op + " (" else : op = " " + op + " " self . __query [ "q" ] += op return self
def is_intent_name ( name ) : # type : ( str ) - > Callable [ [ HandlerInput ] , bool ] """A predicate function returning a boolean , when name matches the name in Intent Request . The function can be applied on a : py : class : ` ask _ sdk _ core . handler _ input . HandlerInput ` , to check if the input i...
def can_handle_wrapper ( handler_input ) : # type : ( HandlerInput ) - > bool return ( isinstance ( handler_input . request_envelope . request , IntentRequest ) and handler_input . request_envelope . request . intent . name == name ) return can_handle_wrapper
def OnMoreSquareToggle ( self , event ) : """Toggle the more - square view ( better looking , but more likely to filter records )"""
self . squareMap . square_style = not self . squareMap . square_style self . squareMap . Refresh ( ) self . moreSquareViewItem . Check ( self . squareMap . square_style )
def _load_calib ( self ) : """Load and compute intrinsic and extrinsic calibration parameters ."""
# We ' ll build the calibration parameters as a dictionary , then # convert it to a namedtuple to prevent it from being modified later data = { } # Load the calibration file calib_filepath = os . path . join ( self . sequence_path , 'calib.txt' ) filedata = utils . read_calib_file ( calib_filepath ) # Create 3x4 projec...
def find_repositories_by_walking_without_following_symlinks ( path ) : """Walk a tree and return a sequence of ( directory , dotdir ) pairs ."""
repos = [ ] for dirpath , dirnames , filenames in os . walk ( path , followlinks = False ) : for dotdir in set ( dirnames ) & DOTDIRS : repos . append ( ( dirpath , dotdir ) ) return repos
def PintPars ( datablock , araiblock , zijdblock , start , end , accept , ** kwargs ) : """calculate the paleointensity magic parameters make some definitions"""
if 'version' in list ( kwargs . keys ( ) ) and kwargs [ 'version' ] == 3 : meth_key = 'method_codes' beta_key = 'int_b_beta' temp_key , min_key , max_key = 'treat_temp' , 'meas_step_min' , 'meas_step_max' dc_theta_key , dc_phi_key = 'treat_dc_field_theta' , 'treat_dc_field_phi' # convert dataframe t...
def _escalation_rules_to_string ( escalation_rules ) : 'convert escalation _ rules dict to a string for comparison'
result = '' for rule in escalation_rules : result += 'escalation_delay_in_minutes: {0} ' . format ( rule [ 'escalation_delay_in_minutes' ] ) for target in rule [ 'targets' ] : result += '{0}:{1} ' . format ( target [ 'type' ] , target [ 'id' ] ) return result
def update_extent_location ( self , extent_loc ) : # type : ( int ) - > None '''A method to update the extent location for this Path Table Record . Parameters : extent _ loc - The new extent location . Returns : Nothing .'''
if not self . _initialized : raise pycdlibexception . PyCdlibInternalError ( 'Path Table Record not yet initialized' ) self . extent_location = extent_loc
def processor ( ctx , processor_cls , process_time_limit , enable_stdout_capture = True , get_object = False ) : """Run Processor ."""
g = ctx . obj Processor = load_cls ( None , None , processor_cls ) processor = Processor ( projectdb = g . projectdb , inqueue = g . fetcher2processor , status_queue = g . status_queue , newtask_queue = g . newtask_queue , result_queue = g . processor2result , enable_stdout_capture = enable_stdout_capture , process_tim...
def add_apt_source ( source , key = None , update = True ) : """Adds source url to apt sources . list . Optional to pass the key url ."""
# Make a backup of list source_list = u'/etc/apt/sources.list' sudo ( "cp %s{,.bak}" % source_list ) files . append ( source_list , source , use_sudo = True ) if key : # Fecth key from url and add sudo ( u"wget -q %s -O - | sudo apt-key add -" % key ) if update : update_apt_sources ( )
def add_iterative_predicate ( self , key , values_list ) : """add an iterative predicate with a key and set of values which it can be equal to in and or function . The individual predicates are specified with the type ` ` equals ` ` and combined with a type ` ` or ` ` . The main reason for this addition is ...
values = self . _extract_values ( values_list ) predicate = { 'type' : 'equals' , 'key' : key , 'value' : None } predicates = [ ] while values : predicate [ 'value' ] = values . pop ( ) predicates . append ( predicate . copy ( ) ) self . predicates . append ( { 'type' : 'or' , 'predicates' : predicates } )
def get_git_info ( ) : """Get a dict with useful git info ."""
start_dir = abspath ( curdir ) try : chdir ( dirname ( abspath ( __file__ ) ) ) re_patt_str = ( r'commit\s+(?P<commit_hash>\w+).*?Author:\s+' r'(?P<author_name>.*?)\s+<(?P<author_email>.*?)>\s+Date:\s+' r'(?P<date>.*?)\n\s+(?P<commit_msg>.*?)(?:\ndiff.*?)?$' ) show_out = check_output ( [ 'git' , 'show' ] ) ...
def construct_error_generator_middleware ( error_generators ) : """Constructs a middleware which intercepts requests for any method found in the provided mapping of endpoints to generator functions , returning whatever error message the generator function returns . Callbacks must be functions with the signatu...
def error_generator_middleware ( make_request , web3 ) : def middleware ( method , params ) : if method in error_generators : error_msg = error_generators [ method ] ( method , params ) return { 'error' : error_msg } else : return make_request ( method , params ) ...
def _ConvertFieldValuePair ( self , js , message ) : """Convert field value pairs into regular message . Args : js : A JSON object to convert the field value pairs . message : A regular protocol message to record the data . Raises : ParseError : In case of problems converting ."""
names = [ ] message_descriptor = message . DESCRIPTOR fields_by_json_name = dict ( ( f . json_name , f ) for f in message_descriptor . fields ) for name in js : try : field = fields_by_json_name . get ( name , None ) if not field : field = message_descriptor . fields_by_name . get ( name...
def _merge_a_into_b_simple ( self , a , b ) : """Merge config dictionary a into config dictionary b , clobbering the options in b whenever they are also specified in a . Do not do any checking ."""
for k , v in a . items ( ) : b [ k ] = v return b
def load ( self , file , name = None ) : """Load a file . The format name can be specified explicitly or inferred from the file extension ."""
if name is None : name = self . format_from_extension ( op . splitext ( file ) [ 1 ] ) file_format = self . file_type ( name ) if file_format == 'text' : return _read_text ( file ) elif file_format == 'json' : return _read_json ( file ) else : load_function = self . _formats [ name ] . get ( 'load' , No...
def get_workflow_id_and_project ( path ) : ''': param path : a path or ID to a workflow object : type path : string : returns : tuple of ( workflow ID , project ID ) Returns the workflow and project IDs from the given path if available ; otherwise , exits with an appropriate error message .'''
project , _folderpath , entity_result = try_call ( resolve_existing_path , path , expected = 'entity' ) try : if entity_result is None or not entity_result [ 'id' ] . startswith ( 'workflow-' ) : raise DXCLIError ( 'Could not resolve "' + path + '" to a workflow object' ) except : err_exit ( ) return en...
def check_path ( filename , reporter = modReporter . Default , settings_path = None , ** setting_overrides ) : """Check the given path , printing out any warnings detected ."""
try : with open ( filename , 'U' ) as f : codestr = f . read ( ) + '\n' except UnicodeError : reporter . unexpected_error ( filename , 'problem decoding source' ) return 1 except IOError : msg = sys . exc_info ( ) [ 1 ] reporter . unexpected_error ( filename , msg . args [ 1 ] ) return 1...
def _poll ( self ) : """Poll Trusted Advisor ( Support ) API for limit checks . Return a dict of service name ( string ) keys to nested dict vals , where each key is a limit name and each value the current numeric limit . e . g . : ' EC2 ' : { ' SomeLimit ' : 10,"""
logger . info ( "Beginning TrustedAdvisor poll" ) tmp = self . _get_limit_check_id ( ) if not self . have_ta : logger . info ( 'TrustedAdvisor.have_ta is False; not polling TA' ) return { } if tmp is None : logger . critical ( "Unable to find 'Service Limits' Trusted Advisor " "check; not using Trusted Advi...
def union_rectangles ( R ) : """Area of union of rectangles : param R : list of rectangles defined by ( x1 , y1 , x2 , y2) where ( x1 , y1 ) is top left corner and ( x2 , y2 ) bottom right corner : returns : area : complexity : : math : ` O ( n ^ 2 ) `"""
if R == [ ] : return 0 X = [ ] Y = [ ] for j in range ( len ( R ) ) : ( x1 , y1 , x2 , y2 ) = R [ j ] assert x1 <= x2 and y1 <= y2 X . append ( x1 ) X . append ( x2 ) Y . append ( ( y1 , + 1 , j ) ) # generate events Y . append ( ( y2 , - 1 , j ) ) X . sort ( ) Y . sort ( ) X2i = { X [ i...
def destroy ( self , request , project , pk = None ) : """Delete bug - job - map entry . pk is a composite key in the form bug _ id - job _ id"""
job_id , bug_id = map ( int , pk . split ( "-" ) ) job = Job . objects . get ( repository__name = project , id = job_id ) BugJobMap . objects . filter ( job = job , bug_id = bug_id ) . delete ( ) return Response ( { "message" : "Bug job map deleted" } )
def scan ( self ) : """Scan for bluetooth devices ."""
try : res = subprocess . check_output ( [ "hcitool" , "scan" , "--flush" ] , stderr = subprocess . STDOUT ) except subprocess . CalledProcessError : raise BackendError ( "'hcitool scan' returned error. Make sure " "your bluetooth device is powered up with " "'hciconfig hciX up'." ) devices = [ ] res = res . spl...
def character_from_structure ( motivation ) : """Find a character for a given structure ."""
assert len ( motivation ) == 3 _c = { "+" : "⿰" , "-" : "⿱" , '>' : "⿱" , "手" : "扌" , "人" : "亻" , "刀" : "刂" , "丝" : "糹" , "水" : "氵" , "0" : "⿴" , } structure = '' . join ( [ _c . get ( x , x ) for x in motivation ] ) return _cd . IDS . get ( structure , '?' )
def get_absolute_url_link ( self , text = None , cls = None , icon_class = None , ** attrs ) : """Gets the html link for the object ."""
if text is None : text = self . get_link_text ( ) return build_link ( href = self . get_absolute_url ( ) , text = text , cls = cls , icon_class = icon_class , ** attrs )
def smooth ( df , window_len = 11 , window = "hanning" ) : """Smooth the data using a window with requested size ."""
if isinstance ( df , pd . Series ) : new_df = _smooth ( df , window_len = window_len , window = window ) else : new_df = df . apply ( _smooth , window_len = window_len , window = window ) return new_df
def update_statistics ( Y , P , beta = 0.9 ) : """Args 2d array whose columns encode the activity of the output units 2d array encoding the pairwise average activity of the output units Returns The updated average activities"""
( n , d ) = Y . shape A = np . expand_dims ( Y , axis = 1 ) * np . expand_dims ( Y , axis = 0 ) assert ( A . shape == ( n , n , d ) ) Q = np . mean ( A , axis = 2 ) Q [ np . where ( Q == 0. ) ] = 0.000001 assert ( P . shape == Q . shape ) return beta * P + ( 1 - beta ) * Q
def walk_and_clean ( data ) : """Recursively walks list of dicts ( which may themselves embed lists and dicts ) , transforming namedtuples to OrderedDicts and using ` ` clean _ key _ name ( k ) ` ` to make keys into SQL - safe column names > > > data = [ { ' a ' : 1 } , [ { ' B ' : 2 } , { ' B ' : 3 } ] , { '...
# transform namedtuples to OrderedDicts if hasattr ( data , '_fields' ) : data = OrderedDict ( ( k , v ) for ( k , v ) in zip ( data . _fields , data ) ) # Recursively clean up child dicts and lists if hasattr ( data , 'items' ) and hasattr ( data , '__setitem__' ) : for ( key , val ) in data . items ( ) : ...
def task_view_user ( self , ) : """View the user that is currently selected : returns : None : rtype : None : raises : None"""
if not self . cur_task : return i = self . task_user_tablev . currentIndex ( ) item = i . internalPointer ( ) if item : user = item . internal_data ( ) self . view_user ( user )
def right_click ( self , data , event_button , event_time ) : """Right click handler"""
self . menu ( event_button , event_time , data )
def sub ( self , * args , ** kwargs ) : """sub ( other , rho = 0 , inplace = True ) Subtracts an * other * number instance . The correlation coefficient * rho * can be configured per uncertainty when passed as a dict . When * inplace * is * False * , a new instance is returned ."""
return self . _apply ( operator . sub , * args , ** kwargs )
def hook_key ( key , callback , suppress = False ) : """Hooks key up and key down events for a single key . Returns the event handler created . To remove a hooked key use ` unhook _ key ( key ) ` or ` unhook _ key ( handler ) ` . Note : this function shares state with hotkeys , so ` clear _ all _ hotkeys ` ...
_listener . start_if_necessary ( ) store = _listener . blocking_keys if suppress else _listener . nonblocking_keys scan_codes = key_to_scan_codes ( key ) for scan_code in scan_codes : store [ scan_code ] . append ( callback ) def remove_ ( ) : del _hooks [ callback ] del _hooks [ key ] del _hooks [ remo...
def copy ( self , dst , ** kwargs ) : """Copy file to a new destination . Returns JSON Patch with proposed change pointing to new copy ."""
_fs , filename = opener . parse ( self . uri ) _fs_dst , filename_dst = opener . parse ( dst ) copyfile ( _fs , filename , _fs_dst , filename_dst , ** kwargs ) return [ { 'op' : 'replace' , 'path' : self . pointer , 'value' : dst } ]
def _read_para_from ( self , code , cbit , clen , * , desc , length , version ) : """Read HIP FROM parameter . Structure of HIP FROM parameter [ RFC 8004 ] : 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 | Type | Length | | Address | Octets Bits Name Description 0 0 from . ty...
if clen != 16 : raise ProtocolError ( f'HIPv{version}: [Parano {code}] invalid format' ) _addr = self . _read_fileng ( 16 ) from_ = dict ( type = desc , critical = cbit , length = clen , ip = ipaddress . ip_address ( _addr ) , ) return from_
def getattrd ( obj , name , default = sentinel ) : """Same as getattr ( ) , but allows dot notation lookup Source : http : / / stackoverflow . com / a / 14324459"""
try : return functools . reduce ( getattr , name . split ( "." ) , obj ) except AttributeError as e : if default is not sentinel : return default raise
def msg_curse ( self , args = None , max_width = None ) : """Return the dict to display in the curse interface ."""
# Init the return message ret = [ ] # Only process if stats exist and display plugin enable . . . if not self . stats or self . is_disable ( ) : return ret # Max size for the interface name name_max_width = max_width - 12 # Header msg = '{:{width}}' . format ( 'SENSORS' , width = name_max_width ) ret . append ( sel...
def toDict ( self ) : """Get information about the titles alignments as a dictionary . @ return : A C { dict } representation of the titles aligments ."""
return { 'scoreClass' : self . scoreClass . __name__ , 'titles' : dict ( ( title , titleAlignments . toDict ( ) ) for title , titleAlignments in self . items ( ) ) , }
def register_recipe ( cls , recipe ) : """Registers a dftimewolf recipe . Args : recipe : imported python module representing the recipe ."""
recipe_name = recipe . contents [ 'name' ] cls . _recipe_classes [ recipe_name ] = ( recipe . contents , recipe . args , recipe . __doc__ )
def _linux_skype_status ( status , message ) : """Updates status and message for Skype IM application on Linux . ` status ` Status type . ` message ` Status message ."""
try : iface = _dbus_get_interface ( 'com.Skype.API' , '/com/Skype' , 'com.Skype.API' ) if iface : # authenticate if iface . Invoke ( 'NAME focus' ) != 'OK' : msg = 'User denied authorization' raise dbus . exceptions . DbusException ( msg ) iface . Invoke ( 'PROTOCOL 5' ) ...
def common_mean_watson ( Data1 , Data2 , NumSims = 5000 , print_result = True , plot = 'no' , save = False , save_folder = '.' , fmt = 'svg' ) : """Conduct a Watson V test for a common mean on two directional data sets . This function calculates Watson ' s V statistic from input files through Monte Carlo simula...
pars_1 = pmag . fisher_mean ( Data1 ) pars_2 = pmag . fisher_mean ( Data2 ) cart_1 = pmag . dir2cart ( [ pars_1 [ "dec" ] , pars_1 [ "inc" ] , pars_1 [ "r" ] ] ) cart_2 = pmag . dir2cart ( [ pars_2 [ 'dec' ] , pars_2 [ 'inc' ] , pars_2 [ "r" ] ] ) Sw = pars_1 [ 'k' ] * pars_1 [ 'r' ] + pars_2 [ 'k' ] * pars_2 [ 'r' ] #...