signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def show_firmware_version_output_show_firmware_version_os_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_firmware_version = ET . Element ( "show_firmware_version" ) config = show_firmware_version output = ET . SubElement ( show_firmware_version , "output" ) show_firmware_version = ET . SubElement ( output , "show-firmware-version" ) os_name = ET . SubElement ( show_firmware_version ...
def to_latex ( self , buf = None , columns = None , col_space = None , header = True , index = True , na_rep = 'NaN' , formatters = None , float_format = None , sparsify = None , index_names = True , bold_rows = False , column_format = None , longtable = None , escape = None , encoding = None , decimal = '.' , multicol...
# Get defaults from the pandas config if self . ndim == 1 : self = self . to_frame ( ) if longtable is None : longtable = config . get_option ( "display.latex.longtable" ) if escape is None : escape = config . get_option ( "display.latex.escape" ) if multicolumn is None : multicolumn = config . get_opti...
def set_blacklisted_filepaths ( self , filepaths , remove_from_stored = True ) : """Sets internal blacklisted filepaths to filepaths . If ` remove _ from _ stored ` is ` True ` , any ` filepaths ` in ` self . plugin _ filepaths ` will be automatically removed . Recommend passing in absolute filepaths but meth...
filepaths = util . to_absolute_paths ( filepaths ) self . blacklisted_filepaths = filepaths if remove_from_stored : self . plugin_filepaths = util . remove_from_set ( self . plugin_filepaths , filepaths )
def filter_installed_packages ( packages ) : """Return a list of packages that require installation ."""
cache = apt_cache ( ) _pkgs = [ ] for package in packages : try : p = cache [ package ] p . current_ver or _pkgs . append ( package ) except KeyError : log ( 'Package {} has no installation candidate.' . format ( package ) , level = 'WARNING' ) _pkgs . append ( package ) return _...
def leave_command_mode ( self , append_to_history = False ) : """Leave command mode . Focus document window again ."""
self . previewer . restore ( ) self . application . layout . focus_last ( ) self . application . vi_state . input_mode = InputMode . NAVIGATION self . command_buffer . reset ( append_to_history = append_to_history )
def two_factor_login ( self , two_factor_code ) : """Second step of login if 2FA is enabled . Not meant to be used directly , use : meth : ` Instaloader . two _ factor _ login ` . : raises InvalidArgumentException : No two - factor authentication pending . : raises BadCredentialsException : 2FA verification c...
if not self . two_factor_auth_pending : raise InvalidArgumentException ( "No two-factor authentication pending." ) ( session , user , two_factor_id ) = self . two_factor_auth_pending login = session . post ( 'https://www.instagram.com/accounts/login/ajax/two_factor/' , data = { 'username' : user , 'verificationCode...
def update ( self , forecasts , observations ) : """Update the ROC curve with a set of forecasts and observations Args : forecasts : 1D array of forecast values observations : 1D array of observation values ."""
for t , threshold in enumerate ( self . thresholds ) : tp = np . count_nonzero ( ( forecasts >= threshold ) & ( observations >= self . obs_threshold ) ) fp = np . count_nonzero ( ( forecasts >= threshold ) & ( observations < self . obs_threshold ) ) fn = np . count_nonzero ( ( forecasts < threshold ) & ( ob...
def render_template ( template_name , context , format = 'png' , output = None , using = None , ** options ) : """Render a template from django project , and return the file object of the result ."""
# output stream , as required by casperjs _ capture stream = BytesIO ( ) out_f = None # the suffix = . html is a hack for phantomjs which * will * # complain about not being able to open source file # unless it has a ' html ' extension . with NamedTemporaryFile ( suffix = '.html' ) as render_file : template_content...
def to_dict ( self , index = True , ordered = False ) : """Returns a dict where the keys are the data and index names and the values are list of the data and index . : param index : If True then include the index in the dict with the index _ name as the key : param ordered : If True then return an OrderedDict (...
result = OrderedDict ( ) if ordered else dict ( ) if index : result . update ( { self . _index_name : self . _index } ) if ordered : data_dict = [ ( self . _data_name , self . _data ) ] else : data_dict = { self . _data_name : self . _data } result . update ( data_dict ) return result
def toggleMute ( self ) : """mute / unmute player"""
if not self . muted : self . _mute ( ) if self . delay_thread is not None : self . delay_thread . cancel ( ) self . title_prefix = '[Muted] ' self . muted = True self . show_volume = False else : self . _mute ( ) self . title_prefix = '' self . muted = False self . show_volum...
def read_excel ( input_fpath ) : """Reads the excel file . : param input _ fpath : Input file path . : type input _ fpath : str : return : Raw Data . : rtype : dict"""
return { k : v . values for k , v in pd . read_excel ( input_fpath ) . items ( ) }
def fetch_losc_data ( detector , start , end , cls = TimeSeries , ** kwargs ) : """Fetch LOSC data for a given detector This function is for internal purposes only , all users should instead use the interface provided by ` TimeSeries . fetch _ open _ data ` ( and similar for ` StateVector . fetch _ open _ dat...
# format arguments start = to_gps ( start ) end = to_gps ( end ) span = Segment ( start , end ) kwargs . update ( { 'start' : start , 'end' : end , } ) # find URLs ( requires gwopensci ) url_kw = { key : kwargs . pop ( key ) for key in GWOSC_LOCATE_KWARGS if key in kwargs } if 'sample_rate' in url_kw : # format as Hert...
def _save_cache ( self ) : """Save data to the cache file ."""
# Create the cache directory safe_makedirs ( self . cache_dir ) # Create / overwrite the cache file try : with open ( self . cache_file , 'wb' ) as f : pickle . dump ( self . data , f ) except Exception as e : logger . error ( "Cannot write version to cache file {} ({})" . format ( self . cache_file , e...
def lengths_to_mask ( * lengths , ** kwargs ) : """Given a list of lengths , create a batch mask . Example : > > > lengths _ to _ mask ( [ 1 , 2 , 3 ] ) tensor ( [ [ 1 , 0 , 0 ] , [1 , 1 , 0 ] , [1 , 1 , 1 ] ] , dtype = torch . uint8) > > > lengths _ to _ mask ( [ 1 , 2 , 2 ] , [ 1 , 2 , 2 ] ) tensor ...
# Squeeze to deal with random additional dimensions lengths = [ l . squeeze ( ) . tolist ( ) if torch . is_tensor ( l ) else l for l in lengths ] # For cases where length is a scalar , this needs to convert it to a list . lengths = [ l if isinstance ( l , list ) else [ l ] for l in lengths ] assert all ( len ( l ) == l...
def predict_jacobian ( self , Xnew , kern = None , full_cov = False ) : """Compute the derivatives of the posterior of the GP . Given a set of points at which to predict X * ( size [ N * , Q ] ) , compute the mean and variance of the derivative . Resulting arrays are sized : dL _ dX * - - [ N * , Q , D ] , wh...
if kern is None : kern = self . kern mean_jac = np . empty ( ( Xnew . shape [ 0 ] , Xnew . shape [ 1 ] , self . output_dim ) ) for i in range ( self . output_dim ) : mean_jac [ : , : , i ] = kern . gradients_X ( self . posterior . woodbury_vector [ : , i : i + 1 ] . T , Xnew , self . _predictive_variable ) dK_d...
def append ( self , content ) : """Process the specified node and convert the XML document into a I { suds } L { object } . @ param content : The current content being unmarshalled . @ type content : L { Content } @ return : A I { append - result } tuple as : ( L { Object } , I { value } ) @ rtype : I { a...
self . start ( content ) self . append_attributes ( content ) self . append_children ( content ) self . append_text ( content ) self . end ( content ) return self . postprocess ( content )
def search ( obj , glob , yielded = False , separator = "/" , afilter = None , dirs = True ) : """Given a path glob , return a dictionary containing all keys that matched the given glob . If ' yielded ' is true , then a dictionary will not be returned . Instead tuples will be yielded in the form of ( path , v...
def _search_view ( obj , glob , separator , afilter , dirs ) : view = { } globlist = __safe_path__ ( glob , separator ) for path in _inner_search ( obj , globlist , separator , dirs = dirs ) : try : val = dpath . path . get ( obj , path , afilter = afilter , view = True ) mer...
def connections ( self , wait ) : """wait for connections to both rabbitmq and elasticsearch to be made before binding a routing key to a channel and sending messages to elasticsearch"""
while wait : try : params = pika . ConnectionParameters ( host = self . rmq_host , port = self . rmq_port ) connection = pika . BlockingConnection ( params ) self . channel = connection . channel ( ) self . channel . exchange_declare ( exchange = 'topic_recs' , exchange_type = 'topic...
def get ( self , metric_id = None , ** kwargs ) : """https : / / docs . cachethq . io / docs / get - metric - points"""
if metric_id is None : raise AttributeError ( 'metric_id is required to get metric points.' ) return self . _get ( 'metrics/%s/points' % metric_id , data = kwargs )
def extract ( filename_url_filelike_or_htmlstring ) : """An " improved " algorithm over the original eatiht algorithm"""
html_tree = get_html_tree ( filename_url_filelike_or_htmlstring ) subtrees = get_textnode_subtrees ( html_tree ) # [ iterable , cardinality , ttl across iterable , avg across iterable . ] ) # calculate AABSL avg , _ , _ = calcavg_avgstrlen_subtrees ( subtrees ) # " high - pass " filter filtered = [ subtree for subtree ...
def tyn_calus_scaling ( target , DABo , To , mu_o , viscosity = 'pore.viscosity' , temperature = 'pore.temperature' ) : r"""Uses Tyn _ Calus model to adjust a diffusion coeffciient for liquids from reference conditions to conditions of interest Parameters target : OpenPNM Object The object for which these v...
Ti = target [ temperature ] mu_i = target [ viscosity ] value = DABo * ( Ti / To ) * ( mu_o / mu_i ) return value
def eval_jacobian ( self , * args , ** kwargs ) : """: return : Jacobian evaluated at the specified point ."""
eval_jac_dict = self . jacobian_model ( * args , ** kwargs ) . _asdict ( ) # Take zero for component which are not present , happens for Constraints jac = [ [ np . broadcast_to ( eval_jac_dict . get ( D ( var , param ) , 0 ) , eval_jac_dict [ var ] . shape ) for param in self . params ] for var in self ] # Use numpy to...
def _x_format ( self ) : """Return the value formatter for this graph"""
def date_to_str ( x ) : t = seconds_to_time ( x ) return self . x_value_formatter ( t ) return date_to_str
def to_dict ( self ) : """Return a dictionary containing Atom data ."""
data = { 'aid' : self . aid , 'number' : self . number , 'element' : self . element } for coord in { 'x' , 'y' , 'z' } : if getattr ( self , coord ) is not None : data [ coord ] = getattr ( self , coord ) if self . charge is not 0 : data [ 'charge' ] = self . charge return data
def _create_diffuse_src_from_xml ( self , config , src_type = 'FileFunction' ) : """Load sources from an XML file ."""
diffuse_xmls = config . get ( 'diffuse_xml' ) srcs_out = [ ] for diffuse_xml in diffuse_xmls : srcs_out += self . load_xml ( diffuse_xml , coordsys = config . get ( 'coordsys' , 'CEL' ) ) return srcs_out
def cluster_stats ( nodes = None , hosts = None , profile = None ) : '''. . versionadded : : 2017.7.0 Return Elasticsearch cluster stats . nodes List of cluster nodes ( id or name ) to display stats for . Use _ local for connected node , empty for all CLI example : : salt myminion elasticsearch . cluster ...
es = _get_instance ( hosts , profile ) try : return es . cluster . stats ( node_id = nodes ) except elasticsearch . TransportError as e : raise CommandExecutionError ( "Cannot retrieve cluster stats, server returned code {0} with message {1}" . format ( e . status_code , e . error ) )
def update ( self , resource , force = False , timeout = - 1 ) : """Updates the Deployment Server resource . The properties that are omitted ( not included as part of the request body ) are ignored . Args : resource ( dict ) : Object to update . force : If set to true , the operation completes despite any...
return self . _client . update ( resource , timeout = timeout , force = force )
def parse_args ( self ) : """Parse the cli args Returns : args ( namespace ) : The args"""
parser = ArgumentParser ( description = '' , formatter_class = RawTextHelpFormatter ) parser . add_argument ( "--generate" , action = "store" , dest = 'generate' , choices = [ 'command' , 'docker-run' , 'docker-compose' , 'ini' , 'env' , 'kubernetes' , 'readme' , 'drone-plugin' ] , help = "Generate a template " ) parse...
def public ( self , boolean ) : """Pass through helper function for flag function ."""
if ( boolean ) : r = self . flag ( { "flag" : "make_public" } ) else : r = self . flag ( { "flag" : "make_private" } ) return r
def check_dockermachine ( ) -> bool : """Checks that docker - machine is available on the computer : raises FileNotFoundError if docker - machine is not present"""
logger . debug ( "checking docker-machine presence" ) # noinspection PyBroadException try : out = subprocess . check_output ( [ "docker-machine" , "version" ] ) . decode ( "utf-8" ) . replace ( "docker-machine.exe" , "" ) . replace ( "docker-machine" , "" ) . strip ( ) logger . debug ( f"using docker machine ve...
def new_closure ( vals ) : """Build a new closure"""
args = ',' . join ( 'x%i' % i for i in range ( len ( vals ) ) ) f = eval ( "lambda %s:lambda:(%s)" % ( args , args ) ) if sys . version_info [ 0 ] >= 3 : return f ( * vals ) . __closure__ return f ( * vals ) . func_closure
def _consumer_loop ( self ) : """The main consumer loop"""
self . logger . debug ( "running main consumer thread" ) while not self . closed : if self . kafka_connected : self . _process_messages ( ) time . sleep ( self . settings [ 'KAFKA_CONSUMER_SLEEP_TIME' ] )
def _locateConvergencePoint ( stats , minOverlap , maxOverlap ) : """Walk backwards through stats until you locate the first point that diverges from target overlap values . We need this to handle cases where it might get to target values , diverge , and then get back again . We want the last convergence poin...
for i , v in enumerate ( stats [ : : - 1 ] ) : if not ( v >= minOverlap and v <= maxOverlap ) : return len ( stats ) - i + 1 # Never differs - converged in one iteration return 1
def members_entries ( self , all_are_optional : bool = False ) -> List [ Tuple [ str , str ] ] : """Return an ordered list of elements for the _ members section : param all _ are _ optional : True means we ' re in a choice situation so everything is optional : return :"""
rval = [ ] if self . _members : for member in self . _members : rval += member . members_entries ( all_are_optional ) elif self . _choices : for choice in self . _choices : rval += self . _context . reference ( choice ) . members_entries ( True ) else : return [ ] return rval
def outcomes ( self , outcomes ) : """Setter for _ outcomes field See property . : param dict outcomes : Dictionary outcomes [ outcome _ id ] that maps : class : ` int ` outcome _ ids onto values of type : class : ` rafcon . core . state _ elements . logical _ port . Outcome ` : raises exceptions . TypeErro...
if not isinstance ( outcomes , dict ) : raise TypeError ( "outcomes must be of type dict" ) if [ outcome_id for outcome_id , outcome in outcomes . items ( ) if not isinstance ( outcome , Outcome ) ] : raise TypeError ( "element of outcomes must be of type Outcome" ) if [ outcome_id for outcome_id , outcome in o...
def is_me ( self ) : # pragma : no cover , seems not to be used anywhere """Check if parameter name if same than name of this object TODO : is it useful ? : return : true if parameter name if same than this name : rtype : bool"""
logger . info ( "And arbiter is launched with the hostname:%s " "from an arbiter point of view of addr:%s" , self . host_name , socket . getfqdn ( ) ) return self . host_name == socket . getfqdn ( ) or self . host_name == socket . gethostname ( )
def accept ( self , * args ) : '''Consume and return the next token if it has the correct type Multiple token types ( as strings , e . g . ' integer64 ' ) can be given as arguments . If the next token is one of them , consume and return it . If the token type doesn ' t match , return None .'''
token = self . peek ( ) if token is None : return None for arg in args : if token . type == arg : self . position += 1 return token return None
def extract_async ( self , destination , format = 'csv' , csv_delimiter = None , csv_header = True , compress = False ) : """Starts a job to export the table to GCS . Args : destination : the destination URI ( s ) . Can be a single URI or a list . format : the format to use for the exported data ; one of ' cs...
format = format . upper ( ) if format == 'JSON' : format = 'NEWLINE_DELIMITED_JSON' if format == 'CSV' and csv_delimiter is None : csv_delimiter = ',' try : response = self . _api . table_extract ( self . _name_parts , destination , format , compress , csv_delimiter , csv_header ) return self . _init_jo...
def print_codepoint_stream ( codepoint_stream , display_block_count = 8 , no_repr = False ) : """> > > def g ( txt ) : . . . for c in txt : yield ord ( c ) > > > codepoint _ stream = g ( " HELLO ! " ) > > > print _ codepoint _ stream ( codepoint _ stream ) . . . # doctest : + NORMALIZE _ WHITESPACE 6 | 0x...
in_line_count = 0 line = [ ] for no , codepoint in enumerate ( codepoint_stream , 1 ) : r = repr ( chr ( codepoint ) ) if "\\x" in r : # FIXME txt = "%s %i" % ( hex ( codepoint ) , codepoint ) else : txt = "%s %s" % ( hex ( codepoint ) , r ) line . append ( txt . center ( 8 ) ) in_li...
def radio_presets ( self ) -> typing . Iterator [ 'FlyingUnit.RadioPresets' ] : """Returns : generator over unit radio presets"""
raise TypeError ( 'unit #{}: {}' . format ( self . unit_id , self . unit_name ) )
def handle_next_export ( self ) : """Retrieve and fully evaluate the next export task , including resolution of any sub - tasks requested by the import client such as requests for binary data , observation , etc . : return : An instance of ExportStateCache , the ' state ' field contains the state of the expor...
state = None while True : state = self . _handle_next_export_subtask ( export_state = state ) if state is None : return None elif state . export_task is None : return state
def _can ( self , func_name , qualifier_id = None ) : """Tests if the named function is authorized with agent and qualifier . Also , caches authz ' s in a dict . It is expected that this will not grow to big , as there are typically only a small number of qualifier + function combinations to store for the age...
function_id = self . _get_function_id ( func_name ) if qualifier_id is None : qualifier_id = self . _qualifier_id agent_id = self . get_effective_agent_id ( ) try : return self . _authz_cache [ str ( agent_id ) + str ( function_id ) + str ( qualifier_id ) ] except KeyError : authz = self . _authz_session . ...
def _get_journal ( ) : '''Return the active running journal object'''
if 'systemd.journald' in __context__ : return __context__ [ 'systemd.journald' ] __context__ [ 'systemd.journald' ] = systemd . journal . Reader ( ) # get to the end of the journal __context__ [ 'systemd.journald' ] . seek_tail ( ) __context__ [ 'systemd.journald' ] . get_previous ( ) return __context__ [ 'systemd....
def process_documentline ( line , nanopubs_metadata ) : """Process SET DOCUMENT line in BEL script"""
matches = re . match ( 'SET DOCUMENT\s+(\w+)\s+=\s+"?(.*?)"?$' , line ) key = matches . group ( 1 ) val = matches . group ( 2 ) nanopubs_metadata [ key ] = val return nanopubs_metadata
def modules_and_args ( modules = True , states = False , names_only = False ) : '''Walk the Salt install tree and return a dictionary or a list of the functions therein as well as their arguments . : param modules : Walk the modules directory if True : param states : Walk the states directory if True : para...
dirs = [ ] module_dir = os . path . dirname ( os . path . realpath ( __file__ ) ) state_dir = os . path . join ( os . path . dirname ( module_dir ) , 'states' ) if modules : dirs . append ( module_dir ) if states : dirs . append ( state_dir ) ret = _mods_with_args ( dirs ) if names_only : return sorted ( re...
def split_calls ( func ) : """Decorator to split up server calls for methods using url parameters , due to the lenght limitation of the URI in Apache . By default 8190 bytes"""
def wrapper ( * args , ** kwargs ) : # The size limit is 8190 bytes minus url and api to call # For example ( https : / / cmsweb - testbed . cern . ch : 8443 / dbs / prod / global / filechildren ) , so 192 bytes should be safe . size_limit = 8000 encoded_url = urllib . urlencode ( kwargs ) if len ( encoded_...
def _ploadf ( ins ) : """Loads from stack pointer ( SP ) + X , being X 2st parameter . 1st operand must be a SIGNED integer ."""
output = _pload ( ins . quad [ 2 ] , 5 ) output . extend ( _fpush ( ) ) return output
def insert_select_max ( self ) : """SQL statement that inserts records with contiguous IDs , by selecting max ID from indexed table records ."""
if self . _insert_select_max is None : if hasattr ( self . record_class , 'application_name' ) : # Todo : Maybe make it support application _ name without pipeline _ id ? assert hasattr ( self . record_class , 'pipeline_id' ) , self . record_class tmpl = self . _insert_select_max_tmpl + self . _wher...
def fetch_and_convert_dataset ( source_files , target_filename ) : """Decorator applied to a dataset conversion function that converts acquired source files into a dataset file that BatchUp can use . Parameters source _ file : list of ` AbstractSourceFile ` instances A list of files to be acquired target ...
if not isinstance ( target_filename , six . string_types ) and not callable ( target_filename ) : raise TypeError ( 'target_filename must either be a string or be callable (it is ' 'a {})' . format ( type ( target_filename ) ) ) for src in source_files : if not isinstance ( src , AbstractSourceFile ) : ...
def prior_from_config ( cp , variable_params , prior_section , constraint_section ) : """Gets arguments and keyword arguments from a config file . Parameters cp : WorkflowConfigParser Config file parser to read . variable _ params : list List of of model parameter names . prior _ section : str Section...
# get prior distribution for each variable parameter logging . info ( "Setting up priors for each parameter" ) dists = distributions . read_distributions_from_config ( cp , prior_section ) constraints = distributions . read_constraints_from_config ( cp , constraint_section ) return distributions . JointDistribution ( v...
def push ( self , stream_id , timestamp , value ) : """Push a value to a stream . Args : stream _ id ( int ) : The stream we want to push to . timestamp ( int ) : The raw timestamp of the value we want to store . value ( int ) : The 32 - bit integer value we want to push . Returns : int : Packed 32 - ...
stream = DataStream . FromEncoded ( stream_id ) reading = IOTileReading ( stream_id , timestamp , value ) try : self . storage . push ( stream , reading ) return Error . NO_ERROR except StorageFullError : return pack_error ( ControllerSubsystem . SENSOR_LOG , SensorLogError . RING_BUFFER_FULL )
def bind ( self , family , type , proto = 0 ) : """Create ( or recreate ) the actual socket object ."""
self . socket = socket . socket ( family , type , proto ) prevent_socket_inheritance ( self . socket ) self . socket . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 ) if self . nodelay and not isinstance ( self . bind_addr , str ) : self . socket . setsockopt ( socket . IPPROTO_TCP , socket . TCP_NOD...
def decrypt_encoded ( self , encrypted_number , Encoding = None ) : """Return the : class : ` EncodedNumber ` decrypted from * encrypted _ number * . Args : encrypted _ number ( EncryptedNumber ) : an : class : ` EncryptedNumber ` with a public key that matches this private key . Encoding ( class ) : A cl...
if not isinstance ( encrypted_number , EncryptedNumber ) : raise TypeError ( 'Expected encrypted_number to be an EncryptedNumber' ' not: %s' % type ( encrypted_number ) ) if self . public_key != encrypted_number . public_key : raise ValueError ( 'encrypted_number was encrypted against a ' 'different key!' ) if ...
def release ( self , pub_ids = None , email = None , from_schema = 'upload' , to_schema = 'public' ) : """Transfer dataset from one schema to another"""
assert pub_ids or email , "Specify either pub_ids or email" assert not ( pub_ids and email ) , "Specify either pub_ids or email" con = self . connection or self . _connect ( ) cur = con . cursor ( ) assert self . user in [ 'release' , 'catroot' , 'postgres' ] , "You don't have permission to perform this operation" if e...
def _GetEventData ( self , parser_mediator , record_index , evtx_record , recovered = False ) : """Extract data from a Windows XML EventLog ( EVTX ) record . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . record _ index ...
event_data = WinEvtxRecordEventData ( ) try : event_data . record_number = evtx_record . identifier except OverflowError as exception : parser_mediator . ProduceExtractionWarning ( ( 'unable to read record identifier from event record: {0:d} ' 'with error: {1!s}' ) . format ( record_index , exception ) ) try : ...
def CopyFileInZip ( from_zip , from_name , to_zip , to_name = None ) : """Read a file from a ZipFile and write it to a new ZipFile ."""
data = from_zip . read ( from_name ) if to_name is None : to_name = from_name to_zip . writestr ( to_name , data )
def compute_lengths ( sequence_data : mx . sym . Symbol ) -> mx . sym . Symbol : """Computes sequence lengths of PAD _ ID - padded data in sequence _ data . : param sequence _ data : Input data . Shape : ( batch _ size , seq _ len ) . : return : Length data . Shape : ( batch _ size , ) ."""
return mx . sym . sum ( sequence_data != C . PAD_ID , axis = 1 )
def getCtrlConf ( self , msgout = True ) : """get control configurations regarding to the PV names , read PV value : param msgout : print information if True ( by default ) return updated element object list"""
_lattice_eleobjlist_copy = copy . deepcopy ( self . _lattice_eleobjlist ) if self . mode == 'online' : for e in _lattice_eleobjlist_copy : for k in ( set ( e . simukeys ) & set ( e . ctrlkeys ) ) : try : if msgout : print ( "Reading from %s..." % e . ctrlinfo ...
def set_static_dns ( iface , * addrs ) : '''Set static DNS configuration on a Windows NIC Args : iface ( str ) : The name of the interface to set addrs ( * ) : One or more DNS servers to be added . To clear the list of DNS servers pass an empty list ( ` ` [ ] ` ` ) . If undefined or ` ` None ` ` no chan...
if addrs is ( ) or str ( addrs [ 0 ] ) . lower ( ) == 'none' : return { 'Interface' : iface , 'DNS Server' : 'No Changes' } # Clear the list of DNS servers if [ ] is passed if str ( addrs [ 0 ] ) . lower ( ) == '[]' : log . debug ( 'Clearing list of DNS servers' ) cmd = [ 'netsh' , 'interface' , 'ip' , 'set...
def trapz_loglog ( y , x , axis = - 1 , intervals = False ) : """Integrate along the given axis using the composite trapezoidal rule in loglog space . Integrate ` y ` ( ` x ` ) along given axis in loglog space . Parameters y : array _ like Input array to integrate . x : array _ like , optional Indepen...
try : y_unit = y . unit y = y . value except AttributeError : y_unit = 1.0 try : x_unit = x . unit x = x . value except AttributeError : x_unit = 1.0 y = np . asanyarray ( y ) x = np . asanyarray ( x ) slice1 = [ slice ( None ) ] * y . ndim slice2 = [ slice ( None ) ] * y . ndim slice1 [ axis ] ...
def info ( name , ** kwargs ) : '''Return info about a container . . note : : The container must be running for ` ` machinectl ` ` to gather information about it . If the container is stopped , then this function will start it . start : False If ` ` True ` ` , then the container will be started to retri...
kwargs = salt . utils . args . clean_kwargs ( ** kwargs ) start_ = kwargs . pop ( 'start' , False ) if kwargs : salt . utils . args . invalid_kwargs ( kwargs ) if not start_ : _ensure_running ( name ) elif name not in list_running ( ) : start ( name ) # Have to parse ' machinectl status ' here since ' machi...
def grok_keys ( config ) : """Will retrieve a GPG key from either Keybase or GPG directly"""
key_ids = [ ] for key in config [ 'pgp_keys' ] : if key . startswith ( 'keybase:' ) : key_id = from_keybase ( key [ 8 : ] ) LOG . debug ( "Encrypting for keybase user %s" , key [ 8 : ] ) else : if not has_gpg_key ( key ) : raise aomi . exceptions . GPG ( "Do not actually have...
def add_crop ( self , name , left , right , top , bottom , offset , input_names , output_name ) : """Add a cropping layer to the model . The cropping layer have two functional modes : - When it has 1 input blob , it crops the input blob based on the 4 parameters [ left , right , top , bottom ] . - When it h...
spec = self . spec nn_spec = self . nn_spec # Add a new layer spec_layer = nn_spec . layers . add ( ) spec_layer . name = name for input_name in input_names : spec_layer . input . append ( input_name ) spec_layer . output . append ( output_name ) spec_layer_params = spec_layer . crop # Set the parameters offset = [...
def cutoff ( poly , * args ) : """Remove polynomial components with order outside a given interval . Args : poly ( Poly ) : Input data . low ( int ) : The lowest order that is allowed to be included . Defaults to 0. high ( int ) : The upper threshold for the cutoff range . Returns : ( Poly ) : T...
if len ( args ) == 1 : low , high = 0 , args [ 0 ] else : low , high = args [ : 2 ] core_old = poly . A core_new = { } for key in poly . keys : if low <= numpy . sum ( key ) < high : core_new [ key ] = core_old [ key ] return Poly ( core_new , poly . dim , poly . shape , poly . dtype )
def bin_query ( self , table , chrom , start , end ) : """perform an efficient spatial query using the bin column if available . The possible bins are calculated from the ` start ` and ` end ` sent to this function . Parameters table : str or table table to query chrom : str chromosome for the query ...
if isinstance ( table , six . string_types ) : table = getattr ( self , table ) try : tbl = table . _table except AttributeError : tbl = table . column_descriptions [ 0 ] [ 'type' ] . _table q = table . filter ( tbl . c . chrom == chrom ) if hasattr ( tbl . c , "bin" ) : bins = Genome . bins ( start , e...
def catalog_report ( self , catalog , harvest = 'none' , report = None , catalog_id = None , catalog_homepage = None , catalog_org = None ) : """Genera un reporte sobre los datasets de un único catálogo . Args : catalog ( dict , str o unicode ) : Representación externa ( path / URL ) o interna ( dict ) de ...
url = catalog if isinstance ( catalog , string_types ) else None catalog = readers . read_catalog ( catalog ) validation = self . validate_catalog ( catalog ) catalog_validation = validation [ "error" ] [ "catalog" ] datasets_validations = validation [ "error" ] [ "dataset" ] catalog_fields = self . _catalog_report_hel...
def get_filename ( self , index ) : """Return filename associated with * index *"""
if index : return osp . normpath ( to_text_string ( self . fsmodel . filePath ( index ) ) )
def schema_to_index ( schema , index_names = None ) : """Get index / doc _ type given a schema URL . : param schema : The schema name : param index _ names : A list of index name . : returns : A tuple containing ( index , doc _ type ) ."""
parts = schema . split ( '/' ) doc_type = os . path . splitext ( parts [ - 1 ] ) if doc_type [ 1 ] not in { '.json' , } : return ( None , None ) if index_names is None : return ( build_index_name ( current_app , * parts ) , doc_type [ 0 ] ) for start in range ( len ( parts ) ) : index_name = build_index_nam...
def set_ignores ( self , folder , * patterns ) : """Applies ` ` patterns ` ` to ` ` folder ` ` ' s ` ` . stignore ` ` file . Args : folder ( str ) : patterns ( str ) : Returns : dict"""
if not patterns : return { } data = { 'ignore' : list ( patterns ) } return self . post ( 'ignores' , params = { 'folder' : folder } , data = data )
def level ( self ) -> str : """Generate a random level of danger or something else . : return : Level . : Example : critical ."""
levels = self . _data [ 'level' ] return self . random . choice ( levels )
def _convert_extras_requirements ( self ) : """Convert requirements in ` extras _ require ` of the form ` " extra " : [ " barbazquux ; { marker } " ] ` to ` " extra : { marker } " : [ " barbazquux " ] ` ."""
spec_ext_reqs = getattr ( self , 'extras_require' , None ) or { } self . _tmp_extras_require = defaultdict ( list ) for section , v in spec_ext_reqs . items ( ) : # Do not strip empty sections . self . _tmp_extras_require [ section ] for r in pkg_resources . parse_requirements ( v ) : suffix = self . _s...
def route_filter_rule_get ( name , route_filter , resource_group , ** kwargs ) : '''. . versionadded : : 2019.2.0 Get details about a specific route filter rule . : param name : The route filter rule to query . : param route _ filter : The route filter containing the rule . : param resource _ group : The re...
result = { } netconn = __utils__ [ 'azurearm.get_client' ] ( 'network' , ** kwargs ) try : rule = netconn . route_filter_rules . get ( resource_group_name = resource_group , route_filter_name = route_filter , rule_name = name ) result = rule . as_dict ( ) except CloudError as exc : __utils__ [ 'azurearm.log...
def build ( self , X , Y , w = None , edges = None ) : """Assigns data to this object and builds the Morse - Smale Complex @ In , X , an m - by - n array of values specifying m n - dimensional samples @ In , Y , a m vector of values specifying the output responses corresponding to the m samples specified ...
super ( MorseComplex , self ) . build ( X , Y , w , edges ) if self . debug : sys . stdout . write ( "Decomposition: " ) start = time . clock ( ) morse_complex = MorseComplexFloat ( vectorFloat ( self . Xnorm . flatten ( ) ) , vectorFloat ( self . Y ) , str ( self . gradient ) , str ( self . simplification ) , ...
def window_size ( self , window_size ) : """set the render window size"""
BasePlotter . window_size . fset ( self , window_size ) self . app_window . setBaseSize ( * window_size )
def _proc_uri ( self , request , result ) : """Process the URI rules for the request . Both the desired API version and desired content type can be determined from those rules . : param request : The Request object provided by WebOb . : param result : The Result object to store the results in ."""
if result : # Result has already been fully determined return # First , determine the version based on the URI prefix for prefix , version in self . uris : if ( request . path_info == prefix or request . path_info . startswith ( prefix + '/' ) ) : result . set_version ( version ) # Update the re...
def stop ( self ) : """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ . When RabbitMQ confirms the cancellation , on _ cancelok will be invoked by pika , which will then closing the channel and connection . The IOLoop is started again , becuase this method is invoked when...
logger . debug ( 'Stopping' ) self . _closing = True self . stop_consuming ( ) self . _connection . ioloop . start ( ) logger . debug ( 'Stopped' )
def is_mod_class ( mod , cls ) : """Checks if a class in a module was declared in that module . Args : mod : the module cls : the class"""
return inspect . isclass ( cls ) and inspect . getmodule ( cls ) == mod
async def acquire_async ( self ) : """Acquire the : attr : ` lock ` asynchronously"""
r = self . acquire ( blocking = False ) while not r : await asyncio . sleep ( .01 ) r = self . acquire ( blocking = False )
def remove_widget ( self ) : """Removes the Component Widget from the engine . : return : Method success . : rtype : bool"""
LOGGER . debug ( "> Removing '{0}' Component Widget." . format ( self . __class__ . __name__ ) ) self . __engine . removeDockWidget ( self ) self . setParent ( None ) return True
def home ( self , * args , ** kwargs ) : """Home robot ' s head and plunger motors ."""
# Home gantry first to avoid colliding with labware # and to make sure tips are not in the liquid while # homing plungers . Z / A axis will automatically home before X / Y self . poses = self . gantry . home ( self . poses ) # Then plungers self . poses = self . _actuators [ 'left' ] [ 'plunger' ] . home ( self . poses...
def bech32_hrp_expand ( hrp ) : """Expand the HRP into values for checksum computation ."""
return [ ord ( x ) >> 5 for x in hrp ] + [ 0 ] + [ ord ( x ) & 31 for x in hrp ]
def allowed_extension ( * allowed ) : '''refs : http : / / zhuoqiang . me / a / restful - pyramid Custom predict checking if the the file extension of the request URI is in the allowed set .'''
def predicate ( info , request ) : log . debug ( request . path ) ext = os . path . splitext ( request . path ) [ 1 ] request . environ [ 'path_extenstion' ] = ext log . debug ( ext ) return ext in allowed return predicate
def check_arrange_act_spacing ( self ) -> typing . Generator [ AAAError , None , None ] : """* When no spaces found , point error at line above act block * When too many spaces found , point error at 2nd blank line"""
yield from self . check_block_spacing ( LineType . arrange , LineType . act , 'AAA03 expected 1 blank line before Act block, found {}' , )
def is_processing ( self , taskid ) : '''return True if taskid is in processing'''
return taskid in self . processing and self . processing [ taskid ] . taskid
def append_seeding_neighbors ( self , nodes : Union [ BaseEntity , List [ BaseEntity ] , List [ Dict ] ] ) -> Seeding : """Add a seed by neighbors . : returns : seeding container for fluid API"""
return self . seeding . append_neighbors ( nodes )
def transitivity_bu ( A ) : '''Transitivity is the ratio of ' triangles to triplets ' in the network . ( A classical version of the clustering coefficient ) . Parameters A : NxN np . ndarray binary undirected connection matrix Returns T : float transitivity scalar'''
tri3 = np . trace ( np . dot ( A , np . dot ( A , A ) ) ) tri2 = np . sum ( np . dot ( A , A ) ) - np . trace ( np . dot ( A , A ) ) return tri3 / tri2
def view_fullreport ( token , dstore ) : """Display an . rst report about the computation"""
# avoid circular imports from openquake . calculators . reportwriter import ReportWriter return ReportWriter ( dstore ) . make_report ( )
def verify ( self , obj ) : """Verify that the object conforms to this verifier ' s schema Args : obj ( object ) : A python object to verify Raises : ValidationError : If there is a problem verifying the dictionary , a ValidationError is thrown with at least the reason key set indicating the reason for ...
if not isinstance ( obj , str ) : raise ValidationError ( "Object is not a string" , reason = 'object is not a string' , object = obj , type = type ( obj ) , str_type = str ) return obj
def get_indices ( self , src , ridx , mag ) : """: param src : an UCERF source : param ridx : a set of rupture indices : param mag : magnitude to use to compute the integration distance : returns : array with the IDs of the sites close to the ruptures"""
centroids = src . get_centroids ( ridx ) mindistance = min_geodetic_distance ( ( centroids [ : , 0 ] , centroids [ : , 1 ] ) , self . sitecol . xyz ) idist = self . integration_distance ( DEFAULT_TRT , mag ) indices , = ( mindistance <= idist ) . nonzero ( ) return indices
def _normWidth ( self , w , maxw ) : """Helper for calculating percentages"""
if type ( w ) == type ( "" ) : w = ( ( maxw / 100.0 ) * float ( w [ : - 1 ] ) ) elif ( w is None ) or ( w == "*" ) : w = maxw return min ( w , maxw )
def _is_valid_date ( obj , accept_none = True ) : """Check if an object is an instance of , or a subclass deriving from , a ` ` date ` ` . However , it does not consider ` ` datetime ` ` or subclasses thereof as valid dates . : param obj : Object to test as date . : param accept _ none : If True None is con...
if accept_none and obj is None : return True return isinstance ( obj , date ) and not isinstance ( obj , datetime )
def poly2bez ( poly , return_bpoints = False ) : """Converts a cubic or lower order Polynomial object ( or a sequence of coefficients ) to a CubicBezier , QuadraticBezier , or Line object as appropriate . If return _ bpoints = True then this will instead only return the control points of the corresponding Bez...
bpoints = polynomial2bezier ( poly ) if return_bpoints : return bpoints else : return bpoints2bezier ( bpoints )
def run ( logdir , run_name , wave_name , wave_constructor ) : """Generate wave data of the given form . The provided function ` wave _ constructor ` should accept a scalar tensor of type float32 , representing the frequency ( in Hz ) at which to construct a wave , and return a tensor of shape [ 1 , _ samples...
tf . compat . v1 . reset_default_graph ( ) tf . compat . v1 . set_random_seed ( 0 ) # On each step ` i ` , we ' ll set this placeholder to ` i ` . This allows us # to know " what time it is " at each step . step_placeholder = tf . compat . v1 . placeholder ( tf . float32 , shape = [ ] ) # We want to linearly interpolat...
def on_delivery_confirmation ( self , method_frame ) : """Invoked by pika when RabbitMQ responds to a Basic . Publish RPC command , passing in either a Basic . Ack or Basic . Nack frame with the delivery tag of the message that was published . The delivery tag is an integer counter indicating the message numb...
confirmation_type = method_frame . method . NAME . split ( '.' ) [ 1 ] . lower ( ) LOGGER . debug ( 'Received %s for delivery tag: %i' , confirmation_type , method_frame . method . delivery_tag ) if method_frame . method . multiple : confirmed = sorted ( [ msg for msg in self . messages if msg <= method_frame . met...
def to_snake_case ( camel_case_string ) : """Convert a string from camel case to snake case . From example , " someVar " would become " some _ var " . : param camel _ case _ string : Camel - cased string to convert to snake case . : return : Snake - cased version of camel _ case _ string ."""
first_pass = _first_camel_case_regex . sub ( r'\1_\2' , camel_case_string ) return _second_camel_case_regex . sub ( r'\1_\2' , first_pass ) . lower ( )
def concrete_bipartite_as_graph ( self , subjects , patterns ) -> Graph : # pragma : no cover """Returns a : class : ` graphviz . Graph ` representation of this bipartite graph ."""
if Graph is None : raise ImportError ( 'The graphviz package is required to draw the graph.' ) bipartite = self . _build_bipartite ( subjects , patterns ) graph = Graph ( ) nodes_left = { } # type : Dict [ TLeft , str ] nodes_right = { } # type : Dict [ TRight , str ] node_id = 0 for ( left , right ) , value in bip...
def set_bpf_filter_on_all_devices ( filterstr ) : '''Long method name , but self - explanatory . Set the bpf filter on all devices that have been opened .'''
with PcapLiveDevice . _lock : for dev in PcapLiveDevice . _OpenDevices . values ( ) : _PcapFfi . instance ( ) . _set_filter ( dev , filterstr )
def update ( self , * data , ** kwargs ) : """Updates all objects with details given if they match a set of conditions supplied . This method updates each object individually , to fire callback methods and ensure validations are run . Returns the number of objects matched ( which may not be equal to the numbe...
updated_item_count = 0 try : items = self . all ( ) for item in items : item . update ( * data , ** kwargs ) updated_item_count += 1 except Exception : # FIXME Log Exception raise return updated_item_count
def inatoms ( self , reverse = False ) : """Yield the singleton for every non - member ."""
if reverse : return filterfalse ( self . __and__ , reversed ( self . _atoms ) ) return filterfalse ( self . __and__ , self . _atoms )
def convert_seeded_answers ( answers ) : """Convert seeded answers into the format that can be merged into student answers . Args : answers ( list ) : seeded answers Returns : dict : seeded answers with student answers format : ' seeded0 ' : ' rationaleA ' ' seeded1 ' : ' rationaleB '"""
converted = { } for index , answer in enumerate ( answers ) : converted . setdefault ( answer [ 'answer' ] , { } ) converted [ answer [ 'answer' ] ] [ 'seeded' + str ( index ) ] = answer [ 'rationale' ] return converted