signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def detect ( self , G ) : """Detect a single core - periphery pair using the Borgatti - Everett algorithm . Parameters G : NetworkX graph object Examples > > > import networkx as nx > > > import cpalgorithm as cpa > > > G = nx . karate _ club _ graph ( ) # load the karate club network . > > > spr = cp...
nodes = G . nodes ( ) N = len ( nodes ) Cbest = np . zeros ( N ) qbest = 0 for it in range ( self . num_runs ) : C , q = self . _detect ( G ) if q < qbest : Cbest = C qbest = q # Post process self . c_ = dict ( zip ( nodes , np . zeros ( N ) . astype ( int ) ) ) self . x_ = dict ( zip ( nodes , ...
def reduce_axis ( data , reducer , block_reducer , mapper = None , axis = None , blen = None , storage = None , create = 'array' , ** kwargs ) : """Apply an operation to ` data ` that reduces over one or more axes ."""
# setup storage = _util . get_storage ( storage ) blen = _util . get_blen_array ( data , blen ) length = len ( data ) # normalise axis arg if isinstance ( axis , int ) : axis = ( axis , ) # deal with ' out ' kwarg if supplied , can arise if a chunked array is # passed as an argument to numpy . sum ( ) , see also # ...
def on_okButton ( self , event ) : """grab user input values , format them , and run huji _ magic . py with the appropriate flags"""
os . chdir ( self . WD ) options = { } HUJI_file = self . bSizer0 . return_value ( ) if not HUJI_file : pw . simple_warning ( "You must select a HUJI format file" ) return False options [ 'magfile' ] = HUJI_file dat_file = self . bSizer0A . return_value ( ) if os . path . isfile ( dat_file ) : options [ 'da...
def convert_mfdist ( self , node ) : """Convert the given node into a Magnitude - Frequency Distribution object . : param node : a node of kind incrementalMFD or truncGutenbergRichterMFD : returns : a : class : ` openquake . hazardlib . mfd . EvenlyDiscretizedMFD . ` or : class : ` openquake . hazardlib . m...
with context ( self . fname , node ) : [ mfd_node ] = [ subnode for subnode in node if subnode . tag . endswith ( ( 'incrementalMFD' , 'truncGutenbergRichterMFD' , 'arbitraryMFD' , 'YoungsCoppersmithMFD' , 'multiMFD' ) ) ] if mfd_node . tag . endswith ( 'incrementalMFD' ) : return mfd . EvenlyDiscretize...
def _assemble_lsid ( self , module_number ) : """Return an assembled LSID based off the provided module number and the authority ' s base LSID . Note : Never includes the module ' s version number . : param module _ number : : return : string"""
if self . base_lsid is None : raise Exception ( "Base LSID in LSID authority not initialized" ) return self . base_lsid + ":" + str ( module_number )
def andrews_curves ( data , class_column , samples = 200 , alpha = None , width = 450 , height = 300 , ** kwds ) : """Generates an Andrews curves visualization for visualising clusters of multivariate data . Andrews curves have the functional form : f ( t ) = x _ 1 / sqrt ( 2 ) + x _ 2 sin ( t ) + x _ 3 cos (...
if kwds : warnings . warn ( "Unrecognized keywords in pdvega.andrews_curves(): {0}" "" . format ( list ( kwds . keys ( ) ) ) ) t = np . linspace ( - np . pi , np . pi , samples ) vals = data . drop ( class_column , axis = 1 ) . values . T curves = np . outer ( vals [ 0 ] , np . ones_like ( t ) ) for i in range ( 1 ...
def set_core_connections_per_host ( self , host_distance , core_connections ) : """Sets the minimum number of connections per Session that will be opened for each host with : class : ` ~ . HostDistance ` equal to ` host _ distance ` . The default is 2 for : attr : ` ~ HostDistance . LOCAL ` and 1 for : attr :...
if self . protocol_version >= 3 : raise UnsupportedOperation ( "Cluster.set_core_connections_per_host() only has an effect " "when using protocol_version 1 or 2." ) old = self . _core_connections_per_host [ host_distance ] self . _core_connections_per_host [ host_distance ] = core_connections if old < core_connecti...
def averageAbove ( requestContext , seriesList , n ) : """Takes one metric or a wildcard seriesList followed by an integer N . Out of all metrics passed , draws only the metrics with an average value above N for the time period specified . Example : : & target = averageAbove ( server * . instance * . thread...
results = [ ] for series in seriesList : val = safeAvg ( series ) if val is not None and val >= n : results . append ( series ) return results
def wait_pid ( pid , timeout = None , callback = None ) : """Wait for process with pid ' pid ' to terminate and return its exit status code as an integer . If pid is not a children of os . getpid ( ) ( current process ) just waits until the process disappears and return None . If pid does not exist at all r...
def check_timeout ( delay ) : if timeout is not None : if time . time ( ) >= stop_at : if callback : callback ( pid ) else : raise TimeoutExpired time . sleep ( delay ) return min ( delay * 2 , 0.04 ) if timeout is not None : waitcall = lam...
def check_for_duplicates ( input_array ) : """This function checks whether if the provided list of integers contains any duplicate values . > > > check _ for _ duplicates ( [ 1 , 2 , 3 , 4 , 5 ] ) False > > > check _ for _ duplicates ( [ 1 , 2 , 3 , 4 , 4 ] ) True > > > check _ for _ duplicates ( [ 1 , 1 ...
unique_elements = set ( input_array ) return len ( input_array ) != len ( unique_elements )
def attr_exists ( self , attr ) : """Returns True if at least on instance of the attribute is found"""
gen = self . attr_gen ( attr ) n_instances = len ( list ( gen ) ) if n_instances > 0 : return True else : return False
def get_parent ( port_id ) : """Get trunk subport ' s parent port"""
session = db . get_reader_session ( ) res = dict ( ) with session . begin ( ) : subport_model = trunk_models . SubPort trunk_model = trunk_models . Trunk subport = ( session . query ( subport_model ) . filter ( subport_model . port_id == port_id ) . first ( ) ) if subport : trunk = ( session . q...
def ffill ( iterable ) : """Forward fill non None values in some iterable . Parameters iterable : iterable The iterable to forward fill . Yields e : any The last non None value or None if there has not been a non None value ."""
it = iter ( iterable ) previous = next ( it ) yield previous for e in it : if e is None : yield previous else : previous = e yield e
def AddAnalysisReport ( self , analysis_report ) : """Adds an analysis report . Args : analysis _ report ( AnalysisReport ) : analysis report . Raises : IOError : when the storage writer is closed . OSError : when the storage writer is closed ."""
self . _RaiseIfNotWritable ( ) self . _storage_file . AddAnalysisReport ( analysis_report ) report_identifier = analysis_report . plugin_name self . _session . analysis_reports_counter [ 'total' ] += 1 self . _session . analysis_reports_counter [ report_identifier ] += 1 self . number_of_analysis_reports += 1
async def patch_entries ( self , entry , ** kwargs ) : """PATCH / api / entries / { entry } . { _ format } Change several properties of an entry : param entry : the entry to ' patch ' / update : param kwargs : can contain one of the following title : string tags : a list of tags tag1 , tag2 , tag3 archi...
# default values params = { 'access_token' : self . token , 'title' : '' , 'tags' : [ ] } if 'title' in kwargs : params [ 'title' ] = kwargs [ 'title' ] if 'tags' in kwargs and isinstance ( kwargs [ 'tags' ] , list ) : params [ 'tags' ] = ', ' . join ( kwargs [ 'tags' ] ) params [ 'archive' ] = self . __get_att...
def get_actions ( self , request , view ) : """Return metadata for resource - specific actions , such as start , stop , unlink"""
metadata = OrderedDict ( ) actions = self . get_resource_actions ( view ) resource = view . get_object ( ) for action_name , action in actions . items ( ) : if action_name == 'update' : view . request = clone_request ( request , 'PUT' ) else : view . action = action_name data = ActionSeriali...
def load_installed_plugins ( self ) : """: rtype : list of Plugin"""
result = [ ] plugin_dirs = [ d for d in os . listdir ( self . plugin_path ) if os . path . isdir ( os . path . join ( self . plugin_path , d ) ) ] settings = constants . SETTINGS for d in plugin_dirs : if d == "__pycache__" : continue try : class_module = self . load_plugin ( d ) plugin ...
def _fetch_size ( self , request : Request ) -> int : '''Return size of file . Coroutine .'''
try : size = yield from self . _commander . size ( request . file_path ) return size except FTPServerError : return
def CorrectEmail ( self , email ) : '''Returns a Corrected email USER INPUT REQUIRED'''
print ( "Wrong Email : " + email ) contents = email . split ( '@' ) if len ( contents ) == 2 : domain_data = contents [ 1 ] . split ( '.' ) for vemail in self . valid : alters = perms ( vemail . split ( '.' , 1 ) [ 0 ] ) if domain_data [ 0 ] in alters and qyn . query_yes_no ( "Did you mean : " +...
def get_class ( fullClassName , parentClass = None ) : """Load a module and retrieve a class ( NOT an instance ) . If the parentClass is supplied , className must be of parentClass or a subclass of parentClass ( or None is returned ) ."""
aClass = get_func ( fullClassName ) # Assert that the class is a subclass of parentClass . if parentClass is not None : if not issubclass ( aClass , parentClass ) : raise TypeError ( u"%s is not a subclass of %s" % ( fullClassName , parentClass ) ) # Return a reference to the class itself , not an instantia...
def get_subgraph_by_annotation_value ( graph , annotation , values ) : """Induce a sub - graph over all edges whose annotations match the given key and value . : param pybel . BELGraph graph : A BEL graph : param str annotation : The annotation to group by : param values : The value ( s ) for the annotation ...
if isinstance ( values , str ) : values = { values } return get_subgraph_by_annotations ( graph , { annotation : values } )
def _batchify ( self , data_source ) : """Load data from underlying arrays , internal use only ."""
assert self . cursor < self . num_data , 'DataIter needs reset.' # first batch of next epoch with ' roll _ over ' if self . last_batch_handle == 'roll_over' and - self . batch_size < self . cursor < 0 : assert self . _cache_data is not None or self . _cache_label is not None , 'next epoch should have cached data' ...
def __import_file ( self , f ) : """Import the specified file and return the imported module : param f : the file to import : type f : str : returns : The imported module : rtype : module : raises : None"""
directory , module_name = os . path . split ( f ) module_name = os . path . splitext ( module_name ) [ 0 ] path = list ( sys . path ) sys . path . insert ( 0 , directory ) module = __import__ ( module_name ) return module
def data ( self , index , role = QtCore . Qt . UserRole , mode = BuildMode ) : """Used by the view to determine data to present See : qtdoc : ` QAbstractItemModel < QAbstractItemModel . data > ` , and : qtdoc : ` subclassing < qabstractitemmodel . subclassing > `"""
if role == CursorRole : if index . isValid ( ) : if mode == BuildMode : return cursors . openHand ( ) elif mode == AutoParamMode : return cursors . pointyHand ( ) else : raise ValueError ( "Invalid stimulus edit mode" ) else : return QtGui . QC...
def mean_hub_height ( self ) : r"""Calculates the mean hub height of the wind turbine cluster . The mean hub height of a wind turbine cluster is necessary for power output calculations with an aggregated wind turbine cluster power curve . Hub heights of wind farms with higher nominal power weigh more than o...
self . hub_height = np . exp ( sum ( np . log ( wind_farm . hub_height ) * wind_farm . get_installed_power ( ) for wind_farm in self . wind_farms ) / self . get_installed_power ( ) ) return self
def _assertField ( self , name ) : """Raise AttributeError when PacketHistory has no field with the given name ."""
if name not in self . _names : msg = 'PacketHistory "%s" has no field "%s"' values = self . _defn . name , name raise AttributeError ( msg % values )
def handle_unhandled_exception ( exc_type , exc_value , exc_traceback ) : """Handler for unhandled exceptions that will write to the logs"""
if issubclass ( exc_type , KeyboardInterrupt ) : # call the default excepthook saved at _ _ excepthook _ _ sys . __excepthook__ ( exc_type , exc_value , exc_traceback ) return logger = logging . getLogger ( __name__ ) # type : ignore logger . critical ( "Unhandled exception" , exc_info = ( exc_type , exc_value ...
def process ( filename , args , detector_classes , printer_classes ) : """The core high - level code for running Slither static analysis . Returns : list ( result ) , int : Result list and number of contracts analyzed"""
ast = '--ast-compact-json' if args . legacy_ast : ast = '--ast-json' args . filter_paths = parse_filter_paths ( args ) slither = Slither ( filename , ast_format = ast , ** vars ( args ) ) return _process ( slither , detector_classes , printer_classes )
def rectify_ajax_form_data ( self , data ) : """If a widget was converted and the Form data was submitted through an Ajax request , then these data fields must be converted to suit the Django Form validation"""
for name , field in self . base_fields . items ( ) : try : data [ name ] = field . convert_ajax_data ( data . get ( name , { } ) ) except AttributeError : pass return data
def prime_check ( n ) : """Return True if n is a prime number Else return False ."""
if n <= 1 : return False if n == 2 or n == 3 : return True if n % 2 == 0 or n % 3 == 0 : return False j = 5 while j * j <= n : if n % j == 0 or n % ( j + 2 ) == 0 : return False j += 6 return True
def _set_ospf_route_map ( self , v , load = False ) : """Setter method for ospf _ route _ map , mapped from YANG variable / routing _ system / router / isis / router _ isis _ cmds _ holder / address _ family / ipv6 / af _ ipv6 _ unicast / af _ ipv6 _ attributes / af _ common _ attributes / redistribute / ospf / osp...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_dict = { 'length' : [ u'1..63' ] } ) , is_leaf = True , yang_name = "ospf-route-map" , rest_name = "route-map" , parent = self , path_helper = self . _path_helper , extm...
def to_sax ( walker , handler ) : """Call SAX - like content handler based on treewalker walker : arg walker : the treewalker to use to walk the tree to convert it : arg handler : SAX handler to use"""
handler . startDocument ( ) for prefix , namespace in prefix_mapping . items ( ) : handler . startPrefixMapping ( prefix , namespace ) for token in walker : type = token [ "type" ] if type == "Doctype" : continue elif type in ( "StartTag" , "EmptyTag" ) : attrs = AttributesNSImpl ( token...
def add ( self , itm , ** options ) : """Convenience method to add an item together with a series of options . : param itm : The item to add : param options : keyword arguments which will be placed in the item ' s option entry . If the item already exists , it ( and its options ) will be overidden . Use :...
if not options : options = None self . _d [ itm ] = options
def patCircles ( s0 ) : '''make circle array'''
arr = np . zeros ( ( s0 , s0 ) , dtype = np . uint8 ) col = 255 for rad in np . linspace ( s0 , s0 / 7. , 10 ) : cv2 . circle ( arr , ( 0 , 0 ) , int ( round ( rad ) ) , color = col , thickness = - 1 , lineType = cv2 . LINE_AA ) if col : col = 0 else : col = 255 return arr . astype ( float )
def remove_attributes ( self , session_key , attribute_keys ) : """: type attribute _ keys : a list of strings"""
session = self . _lookup_required_session ( session_key ) removed = session . remove_attributes ( attribute_keys ) if removed : self . session_handler . on_change ( session ) return removed
def edge_has_annotation ( edge_data : EdgeData , key : str ) -> Optional [ Any ] : """Check if an edge has the given annotation . : param edge _ data : The data dictionary from a BELGraph ' s edge : param key : An annotation key : return : If the annotation key is present in the current data dictionary For ...
annotations = edge_data . get ( ANNOTATIONS ) if annotations is None : return None return annotations . get ( key )
def compare ( ver1 , ver2 ) : """Compare two versions : param ver1 : version string 1 : param ver2 : version string 2 : return : The return value is negative if ver1 < ver2, zero if ver1 = = ver2 and strictly positive if ver1 > ver2 : rtype : int > > > import semver > > > semver . compare ( " 1.0.0 " ...
v1 , v2 = parse ( ver1 ) , parse ( ver2 ) return _compare_by_keys ( v1 , v2 )
def _write_method ( schema ) : """Add a write method for named schema to a class ."""
def method ( self , filename = None , schema = schema , taxon_col = 'uid' , taxon_annotations = [ ] , node_col = 'uid' , node_annotations = [ ] , branch_lengths = True , ** kwargs ) : # Use generic write class to write data . return _write ( self . _data , filename = filename , schema = schema , taxon_col = taxon_c...
def get_char_input ( data , char_dict , max_char_length ) : '''Get char input .'''
batch_size = len ( data ) sequence_length = max ( len ( d ) for d in data ) char_id = np . zeros ( ( max_char_length , sequence_length , batch_size ) , dtype = np . int32 ) char_lengths = np . zeros ( ( sequence_length , batch_size ) , dtype = np . float32 ) for batch_idx in range ( 0 , min ( len ( data ) , batch_size ...
def _validate_integer ( self , key , axis ) : """Check that ' key ' is a valid position in the desired axis . Parameters key : int Requested position axis : int Desired axis Returns None Raises IndexError If ' key ' is not a valid position in axis ' axis '"""
len_axis = len ( self . obj . _get_axis ( axis ) ) if key >= len_axis or key < - len_axis : raise IndexError ( "single positional indexer is out-of-bounds" )
def sign_message ( data_to_sign , digest_alg , sign_key , use_signed_attributes = True ) : """Function signs the data and returns the generated ASN . 1 : param data _ to _ sign : A byte string of the data to be signed . : param digest _ alg : The digest algorithm to be used for generating the signature . : ...
if use_signed_attributes : digest_func = hashlib . new ( digest_alg ) digest_func . update ( data_to_sign ) message_digest = digest_func . digest ( ) class SmimeCapability ( core . Sequence ) : _fields = [ ( '0' , core . Any , { 'optional' : True } ) , ( '1' , core . Any , { 'optional' : True } ...
def _get_datapath ( self ) : """Get a valid datapath , else raise an exception ."""
if self . _datapath is None : raise OSError ( errno . ENOENT , "You didn't provide any datapath for %r" % self . filename ) return self . _datapath
def _rebuild_fields ( self ) : '''We take the original fields and create subsets of them , each subset will be set into a container . all the resulted containers will then replace the original _ fields , since we inherit from OneOf each time only one of them will be mutated and used . This is super ugly and dan...
# generate new lists new_field_lists = [ ] field_list_len = self . min_elements while not field_list_len > self . max_elements : how_many = self . max_elements + 1 - field_list_len i = 0 while i < how_many : current = self . random . sample ( self . _fields , field_list_len ) if current not ...
def decode ( self , data , password = None ) : """Decode GNTP Message : param string data :"""
self . password = password self . raw = gntp . shim . u ( data ) parts = self . raw . split ( '\r\n\r\n' ) self . info = self . _parse_info ( self . raw ) self . headers = self . _parse_dict ( parts [ 0 ] )
def getFormat ( self , formatId , vendorSpecific = None ) : """See Also : getFormatResponse ( ) Args : formatId : vendorSpecific : Returns :"""
response = self . getFormatResponse ( formatId , vendorSpecific ) return self . _read_dataone_type_response ( response , 'ObjectFormat' )
def remove_platform ( name , server_url ) : '''To remove specified ASAM platform from the Novell Fan - Out Driver CLI Example : . . code - block : : bash salt - run asam . remove _ platform my - test - vm prov1 . domain . com'''
config = _get_asam_configuration ( server_url ) if not config : return False url = config [ 'platform_config_url' ] data = { 'manual' : 'false' , } auth = ( config [ 'username' ] , config [ 'password' ] ) try : html_content = _make_post_request ( url , data , auth , verify = False ) except Exception as exc : ...
def check_requirements ( to_populate , prompts , helper = False ) : '''Iterates through required values , checking to _ populate for required values If a key in prompts is missing in to _ populate and ` ` helper = = True ` ` , prompts the user using the values in to _ populate . Otherwise , raises an error . ...
for kw , prompt in prompts . items ( ) : if helper : if kw not in to_populate : to_populate [ kw ] = click . prompt ( prompt ) else : msg = ( 'Required value "{}" not found. ' 'Use helper=True or the --helper ' 'flag for assistance.' . format ( kw ) ) assert kw in to_populate...
def op_cmd ( self , command , req_format = 'text' , xpath_expr = "" ) : """Execute an operational mode command . Purpose : Used to send an operational mode command to the connected | device . This requires and uses a paramiko . SSHClient ( ) as | the handler so that we can easily pass and allow all pipe | c...
if not command : raise InvalidCommandError ( "Parameter 'command' cannot be empty" ) if req_format . lower ( ) == 'xml' or xpath_expr : command = command . strip ( ) + ' | display xml' command = command . strip ( ) + ' | no-more\n' out = '' # when logging in as root , we use _ shell to get the response . if sel...
def readlines ( self , timeout = 1 ) : """read all lines that are available . abort after timeout when no more data arrives ."""
lines = [ ] while 1 : line = self . readline ( timeout = timeout ) if line : lines . append ( line ) if not line or line [ - 1 : ] != '\n' : break return lines
def _from_sql ( self , soql ) : """Create Force . com SOQL tree structure from SOQL"""
# pylint : disable = too - many - branches , too - many - nested - blocks assert not self . soql , "Don't use _from_sql method directly" self . soql = soql soql , self . subqueries = split_subquery ( soql ) match_parse = re . match ( r'SELECT (.*) FROM (\w+)\b(.*)$' , soql , re . I ) if not match_parse : raise Prog...
def isValid ( cntxt : Context , m : FixedShapeMap ) -> Tuple [ bool , List [ str ] ] : """` 5.2 Validation Definition < http : / / shex . io / shex - semantics / # validation > ` _ The expression isValid ( G , m ) indicates that for every nodeSelector / shapeLabel pair ( n , s ) in m , s has a corresponding sha...
if not cntxt . is_valid : return False , cntxt . error_list parse_nodes = [ ] for nodeshapepair in m : n = nodeshapepair . nodeSelector if not isinstance_ ( n , Node ) : return False , [ f"{n}: Triple patterns are not implemented" ] # The third test below is because the spec asserts that complet...
def curse ( rest ) : "Curse the day !"
if rest : cursee = rest else : cursee = 'the day' karma . Karma . store . change ( cursee , - 1 ) return "/me curses %s!" % cursee
def walk_tree ( self , top = None ) : """Navigate all the groups in the file starting from top . If top is None , the root group is used ."""
if top is None : top = self . rootgrp values = top . groups . values ( ) yield values for value in top . groups . values ( ) : for children in self . walk_tree ( value ) : yield children
def _keep_this ( self , name ) : """Return True if there are to be no modifications to name ."""
for keep_name in self . keep : if name == keep_name : return True return False
def from_api_repr ( cls , resource ) : """Factory : construct parameter from JSON resource . : type resource : dict : param resource : JSON mapping of parameter : rtype : : class : ` ~ google . cloud . bigquery . query . ArrayQueryParameter ` : returns : instance"""
array_type = resource [ "parameterType" ] [ "arrayType" ] [ "type" ] if array_type == "STRUCT" : return cls . _from_api_repr_struct ( resource ) return cls . _from_api_repr_scalar ( resource )
def enable_websocket ( self , enable = True ) : """Enable or disable the support for websocket . Websocket is enabled automatically if websocket routes are added to the application ."""
if not self . websocket_enabled : # if the server is stopped , we want to cancel any ongoing # websocket tasks , to allow the server to exit promptly @ self . listener ( "before_server_stop" ) def cancel_websocket_tasks ( app , loop ) : for task in self . websocket_tasks : task . cancel ( ) ...
def is_ancestor_of_vault ( self , id_ , vault_id ) : """Tests if an ` ` Id ` ` is an ancestor of a vault . arg : id ( osid . id . Id ) : an ` ` Id ` ` arg : vault _ id ( osid . id . Id ) : the ` ` Id ` ` of a vault return : ( boolean ) - ` ` true ` ` if this ` ` id ` ` is an ancestor of ` ` vault _ id , ` `...
# Implemented from template for # osid . resource . BinHierarchySession . is _ ancestor _ of _ bin if self . _catalog_session is not None : return self . _catalog_session . is_ancestor_of_catalog ( id_ = id_ , catalog_id = vault_id ) return self . _hierarchy_session . is_ancestor ( id_ = id_ , ancestor_id = vault_i...
def removecolkeyword ( self , columnname , keyword ) : """Remove a column keyword . It is similar to : func : ` removekeyword ` ."""
if isinstance ( keyword , str ) : self . _removekeyword ( columnname , keyword , - 1 ) else : self . _removekeyword ( columnname , '' , keyword )
def load_from_stream ( self , stream , container , ** kwargs ) : """Load config from given stream ' stream ' . : param stream : Config file or file - like object : param container : callble to make a container object later : param kwargs : optional keyword parameters to be sanitized : : dict : return : Dict...
return self . load_from_string ( stream . read ( ) , container , ** kwargs )
def start_instance ( self , key_name , public_key_path , private_key_path , security_group , flavor , image_id , image_userdata , username = None , node_name = None ) : """Starts a new instance on the cloud using the given properties . Multiple instances might be started in different threads at the same time . ...
pass
def effective_entries ( self ) : """Number of effective entries in this bin . The number of unweighted entries this bin would need to contain in order to have the same statistical power as this bin with possibly weighted entries , estimated by : ( sum of weights ) * * 2 / ( sum of squares of weights )"""
sum_w2 = self . sum_w2 if sum_w2 == 0 : return abs ( self . value ) return ( self . value ** 2 ) / sum_w2
def run ( self ) : """Interact with the blockchain peer , until we get a socket error or we exit the loop explicitly . Return True on success Raise on error"""
self . handshake ( ) try : self . loop ( ) except socket . error , se : if self . finished : return True else : raise
def GroupDecoder ( field_number , is_repeated , is_packed , key , new_default ) : """Returns a decoder for a group field ."""
end_tag_bytes = encoder . TagBytes ( field_number , wire_format . WIRETYPE_END_GROUP ) end_tag_len = len ( end_tag_bytes ) assert not is_packed if is_repeated : tag_bytes = encoder . TagBytes ( field_number , wire_format . WIRETYPE_START_GROUP ) tag_len = len ( tag_bytes ) def DecodeRepeatedField ( buffer ,...
def removeAttribute ( self , attrName ) : '''removeAttribute - Removes an attribute , by name . @ param attrName < str > - The attribute name'''
attrName = attrName . lower ( ) # Delete provided attribute name ( # attrName ) from attributes map try : del self . _attributes [ attrName ] except KeyError : pass
def asum ( data , axis = None , mapper = None , blen = None , storage = None , create = 'array' , ** kwargs ) : """Compute the sum ."""
return reduce_axis ( data , axis = axis , reducer = np . sum , block_reducer = np . add , mapper = mapper , blen = blen , storage = storage , create = create , ** kwargs )
def transfer ( self , transfer_payload = None , * , from_user , to_user ) : """Transfer this entity to another owner on the backing persistence layer Args : transfer _ payload ( dict ) : Payload for the transfer from _ user ( any ) : A user based on the model specified by the persistence layer to _ user...
if self . persist_id is None : raise EntityNotYetPersistedError ( ( 'Entities cannot be transferred ' 'until they have been ' 'persisted' ) ) return self . plugin . transfer ( self . persist_id , transfer_payload , from_user = from_user , to_user = to_user )
def _example_number_anywhere_for_type ( num_type ) : """Gets a valid number for the specified number type ( it may belong to any country ) . Arguments : num _ type - - The type of number that is needed . Returns a valid number for the specified type . Returns None when the metadata does not contain such inf...
for region_code in SUPPORTED_REGIONS : example_numobj = example_number_for_type ( region_code , num_type ) if example_numobj is not None : return example_numobj # If there wasn ' t an example number for a region , try the non - geographical entities . for country_calling_code in COUNTRY_CODES_FOR_NON_GE...
def translate ( env , func , * args , ** kwargs ) : """Given a shellcode environment , a function and its parameters , translate the function to a list of shellcode operations ready to be compiled or assembled using : meth : ` ~ pwnypack . shellcode . base . BaseEnvironment . compile ` or : meth : ` ~ pwnypac...
func_code = six . get_function_code ( func ) func_globals = dict ( __builtins__ ) func_globals . update ( six . get_function_globals ( func ) ) ops = bc . disassemble ( func_code . co_code ) program = [ ] f_args = inspect . getcallargs ( func , * args , ** kwargs ) variables = dict ( ( func_code . co_varnames . index (...
async def on_raw_authenticate ( self , message ) : """Received part of the authentication challenge ."""
# Cancel timeout timer . if self . _sasl_timer : self . _sasl_timer . cancel ( ) self . _sasl_timer = None # Add response data . response = ' ' . join ( message . params ) if response != EMPTY_MESSAGE : self . _sasl_challenge += base64 . b64decode ( response ) # If the response ain ' t exactly SASL _ RESPON...
def use_token ( self , token = None ) : """Function to use static AUTH _ TOKEN as auth for the constructor instead of full login process . * * Parameters : * * : - * * token * * : Static AUTH _ TOKEN * * Returns : * * Bool on success or failure . In addition the function will mutate the ` cloudgenix . API ` ...
api_logger . info ( 'use_token function:' ) # check token is a string . if not isinstance ( token , ( text_type , binary_type ) ) : api_logger . debug ( '"token" was not a text-style string: {}' . format ( text_type ( token ) ) ) return False # Start setup of constructor . session = self . _parent_class . expos...
def payment_begin ( self , wallet ) : """Begin a new payment session . Searches wallet for an account that ' s marked as available and has a 0 balance . If one is found , the account number is returned and is marked as unavailable . If no account is found , a new account is created , placed in the wallet , an...
wallet = self . _process_value ( wallet , 'wallet' ) payload = { "wallet" : wallet } resp = self . call ( 'payment_begin' , payload ) return resp [ 'account' ]
def display_grid ( self ) : """Display grid on x - axis and y - axis ."""
window_start = self . parent . value ( 'window_start' ) window_length = self . parent . value ( 'window_length' ) window_end = window_start + window_length if self . parent . value ( 'grid_x' ) : x_tick = self . parent . value ( 'grid_xtick' ) x_ticks = arange ( window_start , window_end + x_tick , x_tick ) ...
def _Delta ( a , b ) : """Compute the delta for b - a . Even / odd and odd / even are handled specially , as described above ."""
if a + 1 == b : if a % 2 == 0 : return 'EvenOdd' else : return 'OddEven' if a == b + 1 : if a % 2 == 0 : return 'OddEven' else : return 'EvenOdd' return b - a
def _set_vibration_nix ( self , left_motor , right_motor , duration ) : """Control the motors on Linux . Duration is in miliseconds ."""
code = self . __get_vibration_code ( left_motor , right_motor , duration ) secs , msecs = convert_timeval ( time . time ( ) ) outer_event = struct . pack ( EVENT_FORMAT , secs , msecs , 0x15 , code , 1 ) self . _write_device . write ( outer_event ) self . _write_device . flush ( )
def logtrick_minimizer ( minimizer ) : r"""Log - Trick decorator for optimizers . This decorator implements the " log trick " for optimizing positive bounded variables . It will apply this trick for any variables that correspond to a Positive ( ) bound . Examples > > > from scipy . optimize import minimiz...
@ wraps ( minimizer ) def new_minimizer ( fun , x0 , jac = True , bounds = None , ** minimizer_kwargs ) : if bounds is None : return minimizer ( fun , x0 , jac = jac , bounds = bounds , ** minimizer_kwargs ) logx , expx , gradx , bounds = _logtrick_gen ( bounds ) # Intercept gradient if callable...
def primitive_type ( schema ) : """Get schema type for the primitive argument . Note : it does treats markers & schemas as callables ! : param schema : Value of a primitive type : type schema : * : return : const . COMPILED _ TYPE . * : rtype : str | None"""
schema_type = type ( schema ) # Literal if schema_type in const . literal_types : return const . COMPILED_TYPE . LITERAL # Enum elif Enum is not None and isinstance ( schema , ( EnumMeta , Enum ) ) : return const . COMPILED_TYPE . ENUM # Type elif issubclass ( schema_type , six . class_types ) : return cons...
def _get_left ( cls ) : # type : ( _ MetaRule ) - > List [ object ] """Get left part of the rule . : param cls : Rule for which return the left side . : return : Symbols on the left side of the array . : raise RuleNotDefinedException : If the rule is not defined . : raise CantCreateSingleRuleException : If ...
if cls . _traverse : return [ cls . fromSymbol ] if len ( cls . rules ) > 1 : raise CantCreateSingleRuleException ( cls ) return cls . rules [ 0 ] [ 0 ]
def read_playlist_file ( self , stationFile = '' ) : """Read a csv file Returns : number x - number of stations or -1 - playlist is malformed -2 - playlist not found"""
prev_file = self . stations_file prev_format = self . new_format self . new_format = False ret = 0 stationFile , ret = self . _get_playlist_abspath_from_data ( stationFile ) if ret < 0 : return ret self . _reading_stations = [ ] with open ( stationFile , 'r' ) as cfgfile : try : for row in csv . reader ...
def retrieve_sources ( ) : """Retrieve sources using spectool"""
spectool = find_executable ( 'spectool' ) if not spectool : log . warn ( 'spectool is not installed' ) return try : specfile = spec_fn ( ) except Exception : return cmd = [ spectool , "-g" , specfile ] output = subprocess . check_output ( ' ' . join ( cmd ) , shell = True ) log . warn ( output )
def process_corpus_online ( self , corpus , output_path , frame_size = 400 , hop_size = 160 , chunk_size = 1 , buffer_size = 5760000 ) : """Process all utterances of the given corpus and save the processed features in a feature - container . The utterances are processed in * * online * * mode , so chunk by chunk ...
def processing_func ( utterance , feat_container , frame_size , hop_size , corpus , sr ) : for chunk in self . process_utterance_online ( utterance , frame_size = frame_size , hop_size = hop_size , corpus = corpus , chunk_size = chunk_size , buffer_size = buffer_size ) : feat_container . append ( utterance ...
def path ( self ) : """str : URL path for the model ' s APIs ."""
return "/projects/%s/datasets/%s/models/%s" % ( self . _proto . project_id , self . _proto . dataset_id , self . _proto . model_id , )
def main ( ) : """The main script"""
from docopt import docopt args = docopt ( __doc__ , version = kp . version ) kp . logger . set_level ( "km3pipe" , args [ '-d' ] ) pipe = kp . Pipeline ( ) pipe . attach ( kp . io . ch . CHPump , host = args [ 'SOURCE_IP' ] , port = int ( args [ '-p' ] ) , tags = args [ '-m' ] , timeout = int ( args [ '-x' ] ) , max_qu...
def _get_next_version ( self , revisions ) : """Calculates new version number based on existing numeric ones ."""
versions = [ 0 ] for v in revisions : if v . isdigit ( ) : versions . append ( int ( v ) ) return six . text_type ( sorted ( versions ) [ - 1 ] + 1 )
def clear_adb_log ( self ) : """Clears cached adb content ."""
try : self . _ad . adb . logcat ( '-c' ) except adb . AdbError as e : # On Android O , the clear command fails due to a known bug . # Catching this so we don ' t crash from this Android issue . if b'failed to clear' in e . stderr : self . _ad . log . warning ( 'Encountered known Android error to clear l...
def no_cache ( asset_url ) : """Removes query parameters"""
pos = asset_url . rfind ( '?' ) if pos > 0 : asset_url = asset_url [ : pos ] return asset_url
def print_mso_auto_shape_type_constants ( ) : """print symbolic constant definitions for msoAutoShapeType"""
auto_shape_types = MsoAutoShapeTypeCollection . load ( sort = 'const_name' ) out = render_mso_auto_shape_type_constants ( auto_shape_types ) print out
def logarithm ( requestContext , seriesList , base = 10 ) : """Takes one metric or a wildcard seriesList , a base , and draws the y - axis in logarithmic format . If base is omitted , the function defaults to base 10. Example : : & target = log ( carbon . agents . hostname . avgUpdateTime , 2)"""
results = [ ] for series in seriesList : newValues = [ ] for val in series : if val is None : newValues . append ( None ) elif val <= 0 : newValues . append ( None ) else : newValues . append ( math . log ( val , base ) ) newName = "log(%s, %s)" % ...
def run ( self ) : """Run flux variability command"""
# Load compound information def compound_name ( id ) : if id not in self . _model . compounds : return id return self . _model . compounds [ id ] . properties . get ( 'name' , id ) reaction = self . _get_objective ( ) if not self . _mm . has_reaction ( reaction ) : self . fail ( 'Specified reaction ...
def setup ( hosts , default_keyspace , consistency = ConsistencyLevel . ONE , lazy_connect = False , retry_connect = False , ** kwargs ) : """Records the hosts and connects to one of them : param hosts : list of hosts , see http : / / datastax . github . io / python - driver / api / cassandra / cluster . html :...
global cluster , session , default_consistency_level , lazy_connect_args if 'username' in kwargs or 'password' in kwargs : raise CQLEngineException ( "Username & Password are now handled by using the native driver's auth_provider" ) if not default_keyspace : raise UndefinedKeyspaceException ( ) from cqlengine i...
def _split_hostport ( self , hostport , default_port = None ) : """Split a string in the format of ' < host > : < port > ' into it ' s component parts default _ port will be used if a port is not included in the string Args : str ( ' < host > ' or ' < host > : < port > ' ) : A string to split into it ' s part...
try : ( host , port ) = hostport . split ( ':' , 1 ) except ValueError : # no colon in the string so make our own port host = hostport if default_port is None : raise ValueError ( 'No port found in hostport, and default_port not provided.' ) port = default_port try : port = int ( port ) ...
def ex_best_offers_overrides ( best_prices_depth = None , rollup_model = None , rollup_limit = None , rollup_liability_threshold = None , rollup_liability_factor = None ) : """Create filter to specify whether to accumulate market volume info , how deep a book to return and rollup methods if accumulation is select...
args = locals ( ) return { to_camel_case ( k ) : v for k , v in args . items ( ) if v is not None }
def _unpickle_method ( func_name , obj , cls ) : """Unpickle methods properly , including class methods ."""
if obj is None : return cls . __dict__ [ func_name ] . __get__ ( obj , cls ) for cls in cls . __mro__ : try : func = cls . __dict__ [ func_name ] except KeyError : pass else : break return func . __get__ ( obj , cls )
def _set_SFM ( self , v , load = False ) : """Setter method for SFM , mapped from YANG variable / system _ monitor / SFM ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ SFM is considered as a private method . Backends looking to populate this variable sh...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = SFM . SFM , is_container = 'container' , presence = False , yang_name = "SFM" , rest_name = "SFM" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions = { ...
def exif_orientation ( im ) : """Rotate and / or flip an image to respect the image ' s EXIF orientation data ."""
try : exif = im . _getexif ( ) except Exception : # There are many ways that _ getexif fails , we ' re just going to blanket # cover them all . exif = None if exif : orientation = exif . get ( 0x0112 ) if orientation == 2 : im = im . transpose ( Image . FLIP_LEFT_RIGHT ) elif orientation == ...
def enum ( enum_type = 'enum' , base_classes = None , methods = None , ** attrs ) : """Generates a enumeration with the given attributes ."""
# Enumerations can not be initalized as a new instance def __init__ ( instance , * args , ** kwargs ) : raise RuntimeError ( '%s types can not be initialized.' % enum_type ) if base_classes is None : base_classes = ( ) if methods is None : methods = { } base_classes = base_classes + ( object , ) for k , v i...
def run_query ( method , params , ** kwargs ) : '''Send Zabbix API call Args : method : actual operation to perform via the API params : parameters required for specific method optional kwargs : _ connection _ user : zabbix user ( can also be set in opts or pillar , see module ' s docstring ) _ connecti...
conn_args = _login ( ** kwargs ) ret = { } try : if conn_args : method = method params = params params = _params_extend ( params , ** kwargs ) ret = _query ( method , params , conn_args [ 'url' ] , conn_args [ 'auth' ] ) if isinstance ( ret [ 'result' ] , bool ) : ...
def check_dependencies ( model , model_queue , avaliable_models ) : """Check that all the depenedencies for this model are already in the queue ."""
# A list of allowed links : existing fields , itself and the special case ContentType allowed_links = [ m . model . __name__ for m in model_queue ] + [ model . __name__ , 'ContentType' ] # For each ForeignKey or ManyToMany field , check that a link is possible for field in model . _meta . fields : if not field . re...
def connect_async ( self , conn_id , connection_string , callback ) : """Asynchronously connect to a device ."""
future = self . _loop . launch_coroutine ( self . _adapter . connect ( conn_id , connection_string ) ) future . add_done_callback ( lambda x : self . _callback_future ( conn_id , x , callback ) )
def pause ( self ) : """Sends a " play " command to the player ."""
msg = cr . Message ( ) msg . type = cr . PAUSE self . send_message ( msg )
def create ( self , agent_cls = None , n_agents = 10 , agent_kwargs = { } , env_cls = Environment , env_kwargs = { } , callback = None , conns = 0 , log_folder = None ) : """A convenience function to create simple simulations . Method first creates environment , then instantiates agents into it with give argume...
if not issubclass ( env_cls , Environment ) : raise TypeError ( "Environment class must be derived from ({}" . format ( Environment . __class__ . __name__ ) ) if callback is not None and not hasattr ( callback , '__call__' ) : raise TypeError ( "Callback must be callable." ) if hasattr ( agent_cls , '__iter__' ...