signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def is_boostable ( self , node ) : """alot of times the first paragraph might be the caption under an image so we ' ll want to make sure if we ' re going to boost a parent node that it should be connected to other paragraphs , at least for the first n paragraphs so we ' ll want to make sure that the next si...
para = "p" steps_away = 0 minimum_stopword_count = 5 max_stepsaway_from_node = 3 nodes = self . walk_siblings ( node ) for current_node in nodes : current_node_tag = self . parser . getTag ( current_node ) if current_node_tag == para : if steps_away >= max_stepsaway_from_node : return False ...
def unregister ( self , recipe ) : """Unregisters a given recipe class ."""
recipe = self . get_recipe_instance_from_class ( recipe ) if recipe . slug in self . _registry : del self . _registry [ recipe . slug ]
def held_time ( self ) : """The length of time ( in seconds ) that the device has been held for . This is counted from the first execution of the : attr : ` when _ held ` event rather than when the device activated , in contrast to : attr : ` ~ EventsMixin . active _ time ` . If the device is not currently he...
if self . _held_from is not None : return self . pin_factory . ticks_diff ( self . pin_factory . ticks ( ) , self . _held_from ) else : return None
def call ( self , ** kwargs ) : """Call all the functions that have previously been added to the dependency graph in topological and lexicographical order , and then return variables in a ` ` dict ` ` . You may provide variable values with keyword arguments . These values will be written and can satisfy dep...
if not hasattr ( self , 'funcs' ) : raise StartupError ( 'startup cannot be called again' ) for name , var in self . variables . items ( ) : var . name = name self . variable_values . update ( kwargs ) for name in self . variable_values : self . variables [ name ] . name = name queue = Closure . sort ( self...
def short_alg ( algebraic_string , input_color , position ) : """Converts a string written in short algebraic form , the color of the side whose turn it is , and the corresponding position into a complete move that can be played . If no moves match , None is returned . Examples : e4 , Nf3 , exd5 , Qxf3 , 00...
return make_legal ( incomplete_alg ( algebraic_string , input_color , position ) , position )
def get_alert_version ( self , id , version , ** kwargs ) : # noqa : E501 """Get a specific historical version of a specific alert # noqa : E501 # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . get_alert_version_with_http_info ( id , version , ** kwargs ) # noqa : E501 else : ( data ) = self . get_alert_version_with_http_info ( id , version , ** kwargs ) # noqa : E501 return data
def preload_top ( meta ) : """Load one topology file into memory . This function checks to make sure there ' s only one topology file in play . When sampling frames , you have to have all the same topology to concatenate . Parameters meta : pd . DataFrame The DataFrame of metadata with a column named ' ...
top_fns = set ( meta [ 'top_fn' ] ) if len ( top_fns ) != 1 : raise ValueError ( "More than one topology is used in this project!" ) return md . load_topology ( top_fns . pop ( ) )
def add_tandems ( mcscanfile , tandemfile ) : """add tandem genes to anchor genes in mcscan file"""
tandems = [ f . strip ( ) . split ( "," ) for f in file ( tandemfile ) ] fw = must_open ( mcscanfile + ".withtandems" , "w" ) fp = must_open ( mcscanfile ) seen = set ( ) for i , row in enumerate ( fp ) : if row [ 0 ] == '#' : continue anchorslist = row . strip ( ) . split ( "\t" ) anchors = set ( [...
def maybe_base_expanded_node_name ( self , node_name ) : """Expand the base name if there are node names nested under the node . For example , if there are two nodes in the graph , " a " and " a / read " , then calling this function on " a " will give " a / ( a ) " , a form that points at a leaf node in the n...
with self . _node_name_lock : # Lazily populate the map from original node name to base - expanded ones . if self . _maybe_base_expanded_node_names is None : self . _maybe_base_expanded_node_names = dict ( ) # Sort all the node names . sorted_names = sorted ( node . name for node in self . _...
def write ( self , file_or_path , append = False , timeout = 10 ) : """Write Smother results to a file . Parameters fiile _ or _ path : str Path to write report to append : bool If True , read an existing smother report from ` outpath ` and combine it with this file before writing . timeout : int Ti...
if isinstance ( file_or_path , six . string_types ) : if self . coverage : file_or_path = get_smother_filename ( file_or_path , self . coverage . config . parallel ) outfile = Lock ( file_or_path , mode = 'a+' , timeout = timeout , fail_when_locked = False ) else : outfile = noclose ( file_or_path )...
def create_NT_hashed_password_v2 ( passwd , user , domain ) : "create NT hashed password"
digest = create_NT_hashed_password_v1 ( passwd ) return hmac . new ( digest , ( user . upper ( ) + domain ) . encode ( 'utf-16le' ) ) . digest ( )
def get_machine_id ( machine , cwd ) : '''returns the salt _ id name of the Vagrant VM : param machine : the Vagrant machine name : param cwd : the path to Vagrantfile : return : salt _ id name'''
name = __utils__ [ 'sdb.sdb_get' ] ( _build_machine_uri ( machine , cwd ) , __opts__ ) return name
def add_container_to_pose_tracker ( self , location , container : Container ) : """Add container and child wells to pose tracker . Sets container . parent ( slot ) as pose tracker parent"""
self . poses = pose_tracker . add ( self . poses , container , container . parent , pose_tracker . Point ( * container . _coordinates ) ) for well in container : center_x , center_y , center_z = well . top ( ) [ 1 ] offset_x , offset_y , offset_z = well . _coordinates center_z = 0 self . poses = pose_tr...
def run_main ( ) : """run _ main"""
# max _ messages _ to _ send = 200 max_messages_to_send = 1000000 end_time = None num_logs_per_batch = 0.0 num_logs = 0.0 running_time = 0.0 start_time = datetime . datetime . utcnow ( ) checkpoint = datetime . datetime . utcnow ( ) last_checkpoint = datetime . datetime . utcnow ( ) try : while True : log ....
def unlock ( self , key , cas ) : """Unlock a Locked Key in Couchbase . This unlocks an item previously locked by : meth : ` lock ` : param key : The key to unlock : param cas : The cas returned from : meth : ` lock ` ' s : class : ` . Result ` object . See : meth : ` lock ` for an example . : raise : :...
return _Base . unlock ( self , key , cas = cas )
def size ( self , units = "MiB" ) : """Returns the volume group size in the given units . Default units are MiB . * Args : * * units ( str ) : Unit label ( ' MiB ' , ' GiB ' , etc . . . ) . Default is MiB ."""
self . open ( ) size = lvm_vg_get_size ( self . handle ) self . close ( ) return size_convert ( size , units )
def paths_list ( ) : """Gets a folder list of possibly available QEMU binaries on the host . : returns : List of folders where Qemu binaries MAY reside ."""
paths = set ( ) try : paths . add ( os . getcwd ( ) ) except FileNotFoundError : log . warning ( "The current working directory doesn't exist" ) if "PATH" in os . environ : paths . update ( os . environ [ "PATH" ] . split ( os . pathsep ) ) else : log . warning ( "The PATH environment variable doesn't e...
def generate_xliff ( entry_dict ) : """Given a dictionary with keys = ids and values equals to strings generates and xliff file to send to unbabel . Example : { " 123 " : " This is blue car " , "234 " : " This house is yellow " returns < xliff version = " 1.2 " > < file original = " " source - langu...
entries = "" for key , value in entry_dict . iteritems ( ) : entries += create_trans_unit ( key , value ) . strip ( ) + "\n" xliff_str = get_head_xliff ( ) . strip ( ) + "\n" + entries + get_tail_xliff ( ) . strip ( ) return xliff_str
def context_export ( zap_helper , name , file_path ) : """Export a given context to a file ."""
with zap_error_handler ( ) : result = zap_helper . zap . context . export_context ( name , file_path ) if result != 'OK' : raise ZAPError ( 'Exporting context to file failed: {}' . format ( result ) ) console . info ( 'Exported context {0} to {1}' . format ( name , file_path ) )
def activation_requirements_help_text ( res , ep_id ) : """Given an activation requirements document and an endpoint _ id returns a string of help text for how to activate the endpoint"""
methods = supported_activation_methods ( res ) lines = [ "This endpoint supports the following activation methods: " , ", " . join ( methods ) . replace ( "_" , " " ) , "\n" , ( "For web activation use:\n" "'globus endpoint activate --web {}'\n" . format ( ep_id ) if "web" in methods else "" ) , ( "For myproxy activati...
def base_url ( self ) : """Protocol + hostname"""
if self . location in self . known_locations : return self . known_locations [ self . location ] elif '.' in self . location or self . location == 'localhost' : return 'https://' + self . location else : return 'https://' + self . location + API_HOST_SUFFIX
def get_folder_by_id ( self , folder_id ) : """Get folder details for a folder id . : param folder _ id : str : uuid of the folder : return : Folder"""
return self . _create_item_response ( self . data_service . get_folder ( folder_id ) , Folder )
def to_elembase ( self ) : """Convert parameters back to element base . This function calls the ` ` ` data _ to _ elem _ base ` ` ` function . Returns None"""
if self . config . base : for item in self . devman . devices : self . __dict__ [ item ] . data_to_elem_base ( )
def gene_ids_of_gene_name ( self , gene_name ) : """What are the gene IDs associated with a given gene name ? ( due to copy events , there might be multiple genes per name )"""
results = self . _query_gene_ids ( "gene_name" , gene_name ) if len ( results ) == 0 : raise ValueError ( "Gene name not found: %s" % gene_name ) return results
def parse ( self , file_obj , parsed_files = None ) : '''Read an OpenSSH config from the given file object . : param file _ obj : a file - like object to read the config file from'''
host = { 'host' : [ '*' ] , 'config' : { } } for line in file_obj : # Strip any leading or trailing whitespace from the line . # Refer to https : / / github . com / paramiko / paramiko / issues / 499 line = line . strip ( ) if not line or line . startswith ( '#' ) : continue match = re . match ( sel...
def overlapping_spheres ( shape : List [ int ] , radius : int , porosity : float , iter_max : int = 10 , tol : float = 0.01 ) : r"""Generate a packing of overlapping mono - disperse spheres Parameters shape : list The size of the image to generate in [ Nx , Ny , Nz ] where Ni is the number of voxels in the ...
shape = sp . array ( shape ) if sp . size ( shape ) == 1 : shape = sp . full ( ( 3 , ) , int ( shape ) ) ndim = ( shape != 1 ) . sum ( ) s_vol = ps_disk ( radius ) . sum ( ) if ndim == 2 else ps_ball ( radius ) . sum ( ) bulk_vol = sp . prod ( shape ) N = int ( sp . ceil ( ( 1 - porosity ) * bulk_vol / s_vol ) ) im...
def gpg_download_key ( key_id , key_server , config_dir = None ) : """Download a GPG key from a key server . Do not import it into any keyrings . Return the ASCII - armored key"""
config_dir = get_config_dir ( config_dir ) tmpdir = make_gpg_tmphome ( prefix = "download" , config_dir = config_dir ) gpg = gnupg . GPG ( homedir = tmpdir ) recvdat = gpg . recv_keys ( key_server , key_id ) fingerprint = None try : assert recvdat . count == 1 assert len ( recvdat . fingerprints ) == 1 fing...
def endless_permutations ( N , random_state = None ) : """Generate an endless sequence of random integers from permutations of the set [ 0 , . . . , N ) . If we call this N times , we will sweep through the entire set without replacement , on the ( N + 1 ) th call a new permutation will be created , etc . P...
generator = check_random_state ( random_state ) while True : batch_inds = generator . permutation ( N ) for b in batch_inds : yield b
def process_request ( self , session ) : """Process single request from the given session : param session : session for reading requests and writing responses : return : None"""
debugger = self . debugger ( ) debugger_session_id = debugger . session_id ( ) if debugger is not None else None try : request = session . read_request ( ) if debugger_session_id is not None : debugger . request ( debugger_session_id , request , session . protocol_version ( ) , session . protocol ( ) ) ...
def sorter ( expr ) : """This is a sorting function generator that takes an expression optionally prefixed with a " + " ( ascending , the default ) or " - " ( descending ) character . > > > sorted ( [ { ' a ' : 12 } , { ' a ' : 1 } , { ' a ' : 4 } ] , sorter ( " + a " ) ) [ { ' a ' : 1 } , { ' a ' : 4 } , { '...
order = ascending if not callable ( expr ) : if ',' in expr : sorts = map ( sorter , expr . split ( ',' ) ) return multisorter ( * sorts ) if expr [ 0 ] == '-' : order = descending expr = expr [ 1 : ] elif expr [ 0 ] == '+' : expr = expr [ 1 : ] expr = expression ...
def posterior_samples ( self , X , size = 10 , Y_metadata = None , likelihood = None , ** predict_kwargs ) : """Samples the posterior GP at the points X . : param X : the points at which to take the samples . : type X : np . ndarray ( Nnew x self . input _ dim . ) : param size : the number of a posteriori sam...
fsim = self . posterior_samples_f ( X , size , ** predict_kwargs ) if likelihood is None : likelihood = self . likelihood if fsim . ndim == 3 : for d in range ( fsim . shape [ 1 ] ) : fsim [ : , d ] = likelihood . samples ( fsim [ : , d ] , Y_metadata = Y_metadata ) else : fsim = likelihood . sample...
def adopt ( self , grab ) : """Copy the state of another ` Grab ` instance . Use case : create backup of current state to the cloned instance and then restore the state from it ."""
self . load_config ( grab . config ) self . doc = grab . doc . copy ( new_grab = self ) for key in self . clonable_attributes : setattr ( self , key , getattr ( grab , key ) ) self . cookies = deepcopy ( grab . cookies )
def get_context_data ( self , ** kwargs ) : '''Adds to the context all issues , conditions and treatments .'''
context = super ( VeterinaryHome , self ) . get_context_data ( ** kwargs ) context [ 'medical_issues' ] = MedicalIssue . objects . all ( ) context [ 'medical_conditions' ] = MedicalCondition . objects . all ( ) context [ 'medical_treatments' ] = MedicalTreatment . objects . all ( ) return context
def convert_mass_to_atomic_fractions ( mass_fractions ) : """Converts a mass fraction : class : ` dict ` to an atomic fraction : class : ` dict ` . Args : mass _ fractions ( dict ) : mass fraction : class : ` dict ` . The composition is specified by a dictionary . The keys are atomic numbers and the values ...
atomic_fractions = { } for z , mass_fraction in mass_fractions . items ( ) : atomic_fractions [ z ] = mass_fraction / pyxray . element_atomic_weight ( z ) total_fraction = sum ( atomic_fractions . values ( ) ) for z , fraction in atomic_fractions . items ( ) : try : atomic_fractions [ z ] = fraction / t...
def update ( self , modifier , dest_dir = None , ** kwargs ) : """Update the contents of a wheel in a generic way . The modifier should be a callable which expects a dictionary argument : its keys are archive - entry paths , and its values are absolute filesystem paths where the contents the corresponding arc...
def get_version ( path_map , info_dir ) : version = path = None key = '%s/%s' % ( info_dir , METADATA_FILENAME ) if key not in path_map : key = '%s/PKG-INFO' % info_dir if key in path_map : path = path_map [ key ] version = Metadata ( path = path ) . version return version , ...
def _load ( self ) : """load all icons found in path , subdirs ' icons / appname '"""
# loop over system path if self . _loaded : return icon_paths = [ '/usr/local/share/meqtrees' ] + sys . path for path in icon_paths : path = path or '.' # for each entry , try < entry > / icons / < appname > ' for a , b in [ ( 'icons' , self . _appname ) , ( self . _appname , 'icons' ) ] : trydi...
def generate_sample ( self , initial_pos , num_adapt , num_samples , stepsize = None ) : """Returns a generator type object whose each iteration yields a sample Parameters initial _ pos : A 1d array like object Vector representing values of parameter position , the starting state in markov chain . num _ a...
initial_pos = _check_1d_array_object ( initial_pos , 'initial_pos' ) _check_length_equal ( initial_pos , self . model . variables , 'initial_pos' , 'model.variables' ) if stepsize is None : stepsize = self . _find_reasonable_stepsize ( initial_pos ) if num_adapt <= 1 : # return sample generated using Simple HMC alg...
def is_native_xmon_gate ( gate : ops . Gate ) -> bool : """Check if a gate is a native xmon gate . Args : gate : Input gate . Returns : True if the gate is native to the xmon , false otherwise ."""
return isinstance ( gate , ( ops . CZPowGate , ops . MeasurementGate , ops . PhasedXPowGate , ops . XPowGate , ops . YPowGate , ops . ZPowGate ) )
def add_rebuild ( subparsers ) : """Rebuild Pipeline subcommands ."""
rebuild_parser = subparsers . add_parser ( 'rebuild' , help = runner . rebuild_pipelines . __doc__ , formatter_class = argparse . ArgumentDefaultsHelpFormatter ) rebuild_parser . set_defaults ( func = runner . rebuild_pipelines ) rebuild_parser . add_argument ( '-a' , '--all' , action = 'store_true' , help = 'Rebuild a...
def thumbnail_source_for_display_item ( self , ui , display_item : DisplayItem . DisplayItem ) -> ThumbnailSource : """Returned ThumbnailSource must be closed ."""
with self . __lock : thumbnail_source = self . __thumbnail_sources . get ( display_item ) if not thumbnail_source : thumbnail_source = ThumbnailSource ( ui , display_item ) self . __thumbnail_sources [ display_item ] = thumbnail_source def will_delete ( thumbnail_source ) : d...
def interact ( self , client , location , interaction_required_err ) : '''Implement Interactor . interact by obtaining obtaining a macaroon from the discharger , discharging it with the local private key using the discharged macaroon as a discharge token'''
p = interaction_required_err . interaction_method ( 'agent' , InteractionInfo ) if p . login_url is None or p . login_url == '' : raise httpbakery . InteractionError ( 'no login-url field found in agent interaction method' ) agent = self . _find_agent ( location ) if not location . endswith ( '/' ) : location +...
def _checkBlankLineBeforeEpytext ( self , node_type , node , linenoDocstring ) : """Check whether there is a blank line before epytext . @ param node _ type : type of node @ param node : current node of pylint @ param linenoDocstring : linenumber of docstring"""
# Check whether there is a blank line before epytext markups . patternEpytext = ( r"\n *@(param|type|return|returns|rtype|ivar|cvar" r"|raises|raise)" r"\s*[a-zA-Z0-9_]*\s*\:" ) matchedEpytext = re . search ( patternEpytext , node . doc ) if matchedEpytext : # This docstring have epytext markups , # then check the blan...
def select_warp_gates ( action , action_space , select_add ) : """Select all warp gates ."""
del action_space action . action_ui . select_warp_gates . selection_add = select_add
def read_config_multiline_options ( obj : Any , parser : ConfigParser , section : str , options : Iterable [ str ] ) -> None : """This is to : func : ` read _ config _ string _ options ` as : func : ` get _ config _ multiline _ option ` is to : func : ` get _ config _ string _ option ` ."""
for o in options : setattr ( obj , o , get_config_multiline_option ( parser , section , o ) )
def get_size ( self_or_cls , plot ) : """Return the display size associated with a plot before rendering to any particular format . Used to generate appropriate HTML display . Returns a tuple of ( width , height ) in pixels ."""
if isinstance ( plot , Plot ) : plot = plot . state elif not isinstance ( plot , Model ) : raise ValueError ( 'Can only compute sizes for HoloViews ' 'and bokeh plot objects.' ) return compute_plot_size ( plot )
def clog2 ( num : int ) -> int : r"""Return the ceiling log base two of an integer : math : ` \ ge 1 ` . This function tells you the minimum dimension of a Boolean space with at least N points . For example , here are the values of ` ` clog2 ( N ) ` ` for : math : ` 1 \ le N < 18 ` : > > > [ clog2 ( n ) for...
if num < 1 : raise ValueError ( "expected num >= 1" ) accum , shifter = 0 , 1 while num > shifter : shifter <<= 1 accum += 1 return accum
def HtmlToRgb ( html ) : '''Convert the HTML color to ( r , g , b ) . Parameters : : html : the HTML definition of the color ( # RRGGBB or # RGB or a color name ) . Returns : The color as an ( r , g , b ) tuple in the range : r [ 0 . . . 1 ] , g [ 0 . . . 1 ] , b [ 0 . . . 1] Throws : : ValueErr...
html = html . strip ( ) . lower ( ) if html [ 0 ] == '#' : html = html [ 1 : ] elif html in Color . NAMED_COLOR : html = Color . NAMED_COLOR [ html ] [ 1 : ] if len ( html ) == 6 : rgb = html [ : 2 ] , html [ 2 : 4 ] , html [ 4 : ] elif len ( html ) == 3 : rgb = [ '%c%c' % ( v , v ) for v in html ] else...
def real_filename_complete ( self , text , line , begidx , endidx ) : """Figure out what filenames match the completion ."""
# line contains the full command line that ' s been entered so far . # text contains the portion of the line that readline is trying to complete # text should correspond to line [ begidx : endidx ] # The way the completer works text will start after one of the characters # in DELIMS . So if the filename entered so far ...
def plot ( * args , legend = None , title = None , x_axis_label = "Time (s)" , y_axis_label = None , grid_plot = False , grid_lines = None , grid_columns = None , hor_lines = None , hor_lines_leg = None , vert_lines = None , vert_lines_leg = None , apply_opensignals_style = True , show_plot = True , warn_print = False ...
# Generation of the HTML file where the plot will be stored . # file _ name = _ generate _ bokeh _ file ( file _ name ) # Data conversion for ensuring that the function only works with lists . if len ( args ) == 1 : time = numpy . linspace ( 1 , len ( args [ 0 ] ) + 1 , len ( args [ 0 ] ) ) data = args [ 0 ] el...
def verify ( self , string_version = None ) : """Check that the version information is consistent with the VCS before doing a release . If supplied with a string version , this is also checked against the current version . Should be called from setup . py with the declared package version before releasing t...
if string_version and string_version != str ( self ) : raise Exception ( "Supplied string version does not match current version." ) if self . dirty : raise Exception ( "Current working directory is dirty." ) if self . release != self . expected_release : raise Exception ( "Declared release does not match c...
def define ( self , * names , ** kwargs ) : """Define a variable in the problem . Variables must be defined before they can be accessed by var ( ) or set ( ) . This function takes keyword arguments lower and upper to define the bounds of the variable ( default : - inf to inf ) . The keyword argument types c...
names = tuple ( names ) for name in names : if name in self . _variables : raise ValueError ( 'Variable already defined: {!r}' . format ( name ) ) lower = kwargs . get ( 'lower' , None ) upper = kwargs . get ( 'upper' , None ) vartype = kwargs . get ( 'types' , None ) # Repeat values if a scalar is given if...
def xgroup_setid ( self , name , groupname , id ) : """Set the consumer group last delivered ID to something else . name : name of the stream . groupname : name of the consumer group . id : ID of the last item in the stream to consider already delivered ."""
return self . execute_command ( 'XGROUP SETID' , name , groupname , id )
def _matching_qubo ( G , edge_mapping , magnitude = 1. ) : """Generates a QUBO that induces a matching on the given graph G . The variables in the QUBO are the edges , as given my edge _ mapping . ground _ energy = 0 infeasible _ gap = magnitude"""
Q = { } # We wish to enforce the behavior that no node has two colored edges for node in G : # for each pair of edges that contain node for edge0 , edge1 in itertools . combinations ( G . edges ( node ) , 2 ) : v0 = edge_mapping [ edge0 ] v1 = edge_mapping [ edge1 ] # penalize both being Tru...
def outdir ( self , acc = None ) : """Return the outdir for the given account . Attempts to create the directory if it does not exist ."""
rootdir = self . rootdir ( ) outdir = self . get ( 'outdir' , acc = acc ) dir = os . path . join ( rootdir , outdir ) if rootdir and outdir else None if not os . path . exists ( dir ) : os . makedirs ( dir ) return dir
def to_str ( cls , values , callback = None ) : """Convert many records ' s values to str"""
if callback and callable ( callback ) : if isinstance ( values , dict ) : return callback ( _es . to_str ( values ) ) return [ callback ( _es . to_str ( i ) ) for i in values ] return _es . to_str ( values )
def sequencebank ( self ) : """List of namedtuples representing biological entities defined or mentioned in the text , in the form ( name , sequence _ number , type ) ."""
path = [ 'enhancement' , 'sequencebanks' , 'sequencebank' ] items = listify ( chained_get ( self . _head , path , [ ] ) ) bank = namedtuple ( 'Sequencebank' , 'name sequence_number type' ) out = [ ] for item in items : numbers = listify ( item [ 'sequence-number' ] ) for number in numbers : new = bank (...
def extension ( network , session , version , scn_extension , start_snapshot , end_snapshot , ** kwargs ) : """Function that adds an additional network to the existing network container . The new network can include every PyPSA - component ( e . g . buses , lines , links ) . To connect it to the existing networ...
if version is None : ormcls_prefix = 'EgoGridPfHvExtension' else : ormcls_prefix = 'EgoPfHvExtension' # Adding overlay - network to existing network scenario = NetworkScenario ( session , version = version , prefix = ormcls_prefix , method = kwargs . get ( 'method' , 'lopf' ) , start_snapshot = start_snapshot ,...
def generate_prepare_subparser ( subparsers ) : """Adds a sub - command parser to ` subparsers ` to prepare source XML files for stripping ."""
parser = subparsers . add_parser ( 'prepare' , description = constants . PREPARE_DESCRIPTION , epilog = constants . PREPARE_EPILOG , formatter_class = ParagraphFormatter , help = constants . PREPARE_HELP ) parser . set_defaults ( func = prepare_xml ) utils . add_common_arguments ( parser ) parser . add_argument ( '-s' ...
def transform_annotation ( self , ann , duration ) : '''Apply the vector transformation . Parameters ann : jams . Annotation The input annotation duration : number > 0 The duration of the track Returns data : dict data [ ' vector ' ] : np . ndarray , shape = ( dimension , ) Raises DataError If...
_ , values = ann . to_interval_values ( ) vector = np . asarray ( values [ 0 ] , dtype = self . dtype ) if len ( vector ) != self . dimension : raise DataError ( 'vector dimension({:0}) ' '!= self.dimension({:1})' . format ( len ( vector ) , self . dimension ) ) return { 'vector' : vector }
def format_text_as_docstr ( text ) : r"""CommandLine : python ~ / local / vim / rc / pyvim _ funcs . py - - test - format _ text _ as _ docstr Example : > > > # DISABLE _ DOCTEST > > > from pyvim _ funcs import * # NOQA > > > text = testdata _ text ( ) > > > formated _ text = format _ text _ as _ docstr...
import utool as ut import re min_indent = ut . get_minimum_indentation ( text ) indent_ = ' ' * min_indent formated_text = re . sub ( '^' + indent_ , '' + indent_ + '>>> ' , text , flags = re . MULTILINE ) formated_text = re . sub ( '^$' , '' + indent_ + '>>> #' , formated_text , flags = re . MULTILINE ) return formate...
def _in_qtconsole ( ) -> bool : """A small utility function which determines if we ' re running in QTConsole ' s context ."""
try : from IPython import get_ipython try : from ipykernel . zmqshell import ZMQInteractiveShell shell_object = ZMQInteractiveShell except ImportError : from IPython . kernel . zmq import zmqshell shell_object = zmqshell . ZMQInteractiveShell return isinstance ( get_ipyth...
def _compress_with ( input_filename , output_filename , compressors ) : """Helper function to compress an image with several compressors . In case the compressors do not improve the filesize or in case the resulting image is not equivalent to the source , then the output will be a copy of the input ."""
with _temporary_filenames ( len ( compressors ) ) as temp_filenames : results = [ ] for compressor , temp_filename in zip ( compressors , temp_filenames ) : results . append ( _process ( compressor , input_filename , temp_filename ) ) best_result = min ( results ) os . rename ( best_result . fil...
def not_allowed ( subset = None , show_ip = False , show_ipv4 = None ) : '''. . versionadded : : 2015.8.0 . . versionchanged : : 2019.2.0 The ' show _ ipv4 ' argument has been renamed to ' show _ ip ' as it now includes IPv6 addresses for IPv6 - connected minions . Print a list of all minions that are NOT u...
show_ip = _show_ip_migration ( show_ip , show_ipv4 ) return list_not_state ( subset = subset , show_ip = show_ip )
def create_dhcp_options ( domain_name = None , domain_name_servers = None , ntp_servers = None , netbios_name_servers = None , netbios_node_type = None , dhcp_options_name = None , tags = None , vpc_id = None , vpc_name = None , region = None , key = None , keyid = None , profile = None ) : '''Given valid DHCP opti...
try : if vpc_id or vpc_name : vpc_id = check_vpc ( vpc_id , vpc_name , region , key , keyid , profile ) if not vpc_id : return { 'created' : False , 'error' : { 'message' : 'VPC {0} does not exist.' . format ( vpc_name or vpc_id ) } } r = _create_resource ( 'dhcp_options' , name = dh...
def nlargest ( self , n = None ) : """List the n most common elements and their counts . List is from the most common to the least . If n is None , the list all element counts . Run time should be O ( m log m ) where m is len ( self ) Args : n ( int ) : The number of elements to return"""
if n is None : return sorted ( self . counts ( ) , key = itemgetter ( 1 ) , reverse = True ) else : return heapq . nlargest ( n , self . counts ( ) , key = itemgetter ( 1 ) )
def get_calendars ( self , calendar_id = None , body = None , params = None ) : """: arg calendar _ id : The ID of the calendar to fetch : arg body : The from and size parameters optionally sent in the body : arg from _ : skips a number of calendars : arg size : specifies a max number of calendars to get"""
return self . transport . perform_request ( "GET" , _make_path ( "_ml" , "calendars" , calendar_id ) , params = params , body = body )
def _adopt_notifications ( self , state ) : '''Part of the " monitor " restart strategy . The pending notifications from descriptor of dead agent are imported to our pending list .'''
def iterator ( ) : it = state . descriptor . pending_notifications . iteritems ( ) for _ , nots in it : for x in nots : yield x to_adopt = list ( iterator ( ) ) self . info ( "Will adopt %d pending notifications." , len ( to_adopt ) ) return state . sender . notify ( to_adopt )
def _ParseFileData ( self , knowledge_base , file_object ) : """Parses file content ( data ) for user account preprocessing attributes . Args : knowledge _ base ( KnowledgeBase ) : to fill with preprocessing information . file _ object ( dfvfs . FileIO ) : file - like object that contains the artifact value...
line_reader = line_reader_file . BinaryLineReader ( file_object ) try : reader = line_reader_file . BinaryDSVReader ( line_reader , b':' ) except csv . Error as exception : raise errors . PreProcessFail ( 'Unable to read: {0:s} with error: {1!s}' . format ( self . ARTIFACT_DEFINITION_NAME , exception ) ) for ro...
def _zip_flatten ( x , ys ) : '''intersperse x into ys , with an extra element at the beginning .'''
return itertools . chain . from_iterable ( zip ( itertools . repeat ( x ) , ys ) )
def highlight ( self , message , * values , ** colors ) : '''Highlighter works the way that message parameter is a template , the " values " is a list of arguments going one after another as values there . And so the " colors " should designate either highlight color or alternate for each . Example : highli...
m_color = colors . get ( '_main' , self . _default_color ) h_color = colors . get ( '_highlight' , self . _default_hl_color ) _values = [ ] for value in values : _values . append ( '{p}{c}{r}' . format ( p = self . _colors [ colors . get ( value , h_color ) ] , c = value , r = self . _colors [ m_color ] ) ) self . ...
def process_subprotocol ( self , headers : Headers , available_subprotocols : Optional [ Sequence [ Subprotocol ] ] ) -> Optional [ Subprotocol ] : """Handle the Sec - WebSocket - Protocol HTTP request header . Return Sec - WebSocket - Protocol HTTP response header , which is the same as the selected subprotoco...
subprotocol : Optional [ Subprotocol ] = None header_values = headers . get_all ( "Sec-WebSocket-Protocol" ) if header_values and available_subprotocols : parsed_header_values : List [ Subprotocol ] = sum ( [ parse_subprotocol ( header_value ) for header_value in header_values ] , [ ] ) subprotocol = self . sel...
def decode_list ( self , node , cache , as_map_key ) : """Special case decodes map - as - array . Otherwise lists are treated as Python lists . Arguments follow the same convention as the top - level ' decode ' function ."""
if node : if node [ 0 ] == MAP_AS_ARR : # key must be decoded before value for caching to work . returned_dict = { } for k , v in pairs ( node [ 1 : ] ) : key = self . _decode ( k , cache , True ) val = self . _decode ( v , cache , as_map_key ) returned_dict [ key...
def is_acquired ( self ) : """Check if this lock is currently acquired ."""
uuid , _ = self . etcd_client . get ( self . key ) if uuid is None : return False return uuid == self . uuid
def mark ( self , value = 1 ) : """Updates the dictionary ."""
self [ 'count' ] += value for m in self . _meters : m . update ( value )
def _init_ns2nt ( rcntobj ) : """Save depth - 00 GO terms ordered using descendants cnt ."""
go2dcnt = rcntobj . go2dcnt ntobj = cx . namedtuple ( "NtD1" , "D1 dcnt goobj" ) d0s = rcntobj . depth2goobjs [ 0 ] ns_nt = [ ( o . namespace , ntobj ( D1 = "" , dcnt = go2dcnt [ o . id ] , goobj = o ) ) for o in d0s ] return cx . OrderedDict ( ns_nt )
def fit_to_cols ( what , indent = '' , cols = 79 ) : """Wrap the given text to the columns , prepending the indent to each line . Args : what ( str ) : text to wrap . indent ( str ) : indentation to use . cols ( int ) : colt to wrap to . Returns : str : Wrapped text"""
lines = [ ] while what : what , next_line = split_line ( what = what , cols = cols , indent = indent , ) lines . append ( next_line ) return '\n' . join ( lines )
def find_closest_match ( target_track , tracks ) : """Return closest match to target track"""
track = None # Get a list of ( track , artist match ratio , name match ratio ) tracks_with_match_ratio = [ ( track , get_similarity ( target_track . artist , track . artist ) , get_similarity ( target_track . name , track . name ) , ) for track in tracks ] # Sort by artist then by title sorted_tracks = sorted ( tracks_...
def get_pickled_ontology ( filename ) : """try to retrieve a cached ontology"""
pickledfile = ONTOSPY_LOCAL_CACHE + "/" + filename + ".pickle" if GLOBAL_DISABLE_CACHE : printDebug ( "WARNING: DEMO MODE cache has been disabled in __init__.py ==============" , "red" ) if os . path . isfile ( pickledfile ) and not GLOBAL_DISABLE_CACHE : try : return cPickle . load ( open ( pickledfile...
def delete_subnet ( self , subnet ) : '''Deletes the specified subnet'''
subnet_id = self . _find_subnet_id ( subnet ) ret = self . network_conn . delete_subnet ( subnet = subnet_id ) return ret if ret else True
def get_token_stream ( source : str ) -> CommonTokenStream : """Get the antlr token stream ."""
lexer = LuaLexer ( InputStream ( source ) ) stream = CommonTokenStream ( lexer ) return stream
def templates_match ( self , path ) : """Determines if the template files are the same . The template file equality is determined by the hashsum of the template files themselves . If there is no hashsum , then the content cannot be sure to be the same so treat it as if they changed . Otherwise , return whet...
template_path = get_template_path ( self . template_dir , path ) key = 'hardening:template:%s' % template_path template_checksum = file_hash ( template_path ) kv = unitdata . kv ( ) stored_tmplt_checksum = kv . get ( key ) if not stored_tmplt_checksum : kv . set ( key , template_checksum ) kv . flush ( ) lo...
def clear ( self ) : """Clear the set ."""
self . _set . clear ( ) del self . _headers [ : ] if self . on_update is not None : self . on_update ( self )
def calc_x ( Z , Y ) : """Calculate the industry output x from the Z and Y matrix Parameters Z : pandas . DataFrame or numpy . array Symmetric input output table ( flows ) Y : pandas . DataFrame or numpy . array final demand with categories ( 1 . order ) for each country ( 2 . order ) Returns pandas ....
x = np . reshape ( np . sum ( np . hstack ( ( Z , Y ) ) , 1 ) , ( - 1 , 1 ) ) if type ( Z ) is pd . DataFrame : x = pd . DataFrame ( x , index = Z . index , columns = [ 'indout' ] ) if type ( x ) is pd . Series : x = pd . DataFrame ( x ) if type ( x ) is pd . DataFrame : x . columns = [ 'indout' ] return x
def _initialise_action_states ( self ) : """Some menu actions have on / off states that have to be initialised . Perform all non - trivial action state initialisations . Trivial ones ( i . e . setting to some constant ) are done in the Qt UI file , so only perform those that require some run - time state or c...
self . action_enable_monitoring . setChecked ( self . app . service . is_running ( ) ) self . action_enable_monitoring . setEnabled ( not self . app . serviceDisabled )
def compute_schedules ( courses = None , excluded_times = ( ) , free_sections_only = True , problem = None , return_generator = False , section_constraint = None ) : """Returns all possible schedules for the given courses ."""
s = Scheduler ( free_sections_only , problem , constraint = section_constraint ) s . exclude_times ( * tuple ( excluded_times ) ) return s . find_schedules ( courses , return_generator )
def setup ( self , helper = None , ** run_kwargs ) : """Creates the container , starts it , and waits for it to completely start . : param helper : The resource helper to use , if one was not provided when this container definition was created . : param * * run _ kwargs : Keyword arguments passed to : meth ...
if self . created : return self . set_helper ( helper ) self . run ( ** run_kwargs ) self . wait_for_start ( ) return self
def sar ( computation : BaseComputation ) -> None : """Arithmetic bitwise right shift"""
shift_length , value = computation . stack_pop ( num_items = 2 , type_hint = constants . UINT256 ) value = unsigned_to_signed ( value ) if shift_length >= 256 : result = 0 if value >= 0 else constants . UINT_255_NEGATIVE_ONE else : result = ( value >> shift_length ) & constants . UINT_256_MAX computation . stac...
def compare ( left : Optional [ L ] , right : Optional [ R ] ) -> 'Comparison[L, R]' : """Calculate the comparison of two entities . | left | right | Return Type | | file | file | FileComparison | | file | directory | FileDirectoryComparison | | file | None | FileComparison | | directory | file | Director...
if isinstance ( left , File ) and isinstance ( right , Directory ) : return FileDirectoryComparison ( left , right ) if isinstance ( left , Directory ) and isinstance ( right , File ) : return DirectoryFileComparison ( left , right ) if isinstance ( left , File ) or isinstance ( right , File ) : return File...
def changed_get ( self , start_time , nick = None , page_size = 200 , page_no = 1 ) : '''taobao . simba . creativeids . changed . get 获取修改的创意ID'''
request = TOPRequest ( 'taobao.simba.creativeids.changed.get' ) request [ 'start_time' ] = start_time request [ 'page_size' ] = page_size request [ 'page_no' ] = page_no if nick != None : request [ 'nick' ] = nick self . create ( self . execute ( request ) , models = { 'result' : INCategory } ) return self . result
def compile_intermediate_cpfs ( self , scope : Dict [ str , TensorFluent ] , batch_size : Optional [ int ] = None , noise : Optional [ Noise ] = None ) -> List [ CPFPair ] : '''Compiles the intermediate fluent CPFs given the current ` state ` and ` action ` scope . Args : scope ( Dict [ str , : obj : ` rddl2tf ...
interm_fluents = [ ] with self . graph . as_default ( ) : with tf . name_scope ( 'intermediate_cpfs' ) : for cpf in self . rddl . domain . intermediate_cpfs : cpf_noise = noise . get ( cpf . name , None ) if noise is not None else None name_scope = utils . identifier ( cpf . name ) ...
def _ssid_inventory ( self , inventory , ssid ) : """Filters an inventory to only return servers matching ssid"""
matching_hosts = { } for host in inventory : if inventory [ host ] [ 'comment' ] == ssid : matching_hosts [ host ] = inventory [ host ] return matching_hosts
async def _encoder_data ( self , data ) : """This is a private message handler method . It handles encoder data messages . : param data : encoder data : returns : None - but update is saved in the digital pins structure"""
# strip off sysex start and end data = data [ 1 : - 1 ] pin = data [ 0 ] if not self . hall_encoder : val = int ( ( data [ PrivateConstants . MSB ] << 7 ) + data [ PrivateConstants . LSB ] ) # set value so that it shows positive and negative values if val > 8192 : val -= 16384 # if this value is...
def asdict ( self , name , _type = None , _set = False ) : """Turn this ' a : 2 , b : blabla , c : True , a : ' d ' to { a : [ 2 , ' d ' ] , b : ' blabla ' , c : True }"""
if _type is None : _type = lambda t : t dict_str = self . pop ( name , None ) if not dict_str : return { } _dict = { } for item in split_strip ( dict_str ) : key , _ , val = item . partition ( ':' ) val = _type ( val ) if key in _dict : if isinstance ( _dict [ key ] , list ) : _d...
def fill_package ( app_name , build_dir = None , install_dir = None ) : """Creates the theme package ( . zip ) from templates and optionally assets installed in the ` ` build _ dir ` ` ."""
zip_path = os . path . join ( install_dir , '%s.zip' % app_name ) with zipfile . ZipFile ( zip_path , 'w' ) as zip_file : fill_package_zip ( zip_file , os . path . dirname ( build_dir ) , prefix = app_name ) return zip_path
def refresh_db ( ** kwargs ) : '''Update the homebrew package repository . CLI Example : . . code - block : : bash salt ' * ' pkg . refresh _ db'''
# Remove rtag file to keep multiple refreshes from happening in pkg states salt . utils . pkg . clear_rtag ( __opts__ ) cmd = 'update' if _call_brew ( cmd ) [ 'retcode' ] : log . error ( 'Failed to update' ) return False return True
def create_git_tree ( self , tree , base_tree = github . GithubObject . NotSet ) : """: calls : ` POST / repos / : owner / : repo / git / trees < http : / / developer . github . com / v3 / git / trees > ` _ : param tree : list of : class : ` github . InputGitTreeElement . InputGitTreeElement ` : param base _ tr...
assert all ( isinstance ( element , github . InputGitTreeElement ) for element in tree ) , tree assert base_tree is github . GithubObject . NotSet or isinstance ( base_tree , github . GitTree . GitTree ) , base_tree post_parameters = { "tree" : [ element . _identity for element in tree ] , } if base_tree is not github ...
def preTranslate ( self , tx , ty ) : """Calculate pre translation and replace current matrix ."""
self . e += tx * self . a + ty * self . c self . f += tx * self . b + ty * self . d return self
def create ( self , comment , mentions = ( ) ) : """create comment : param comment : : param mentions : list of pair of code and type ( " USER " , " GROUP " , and so on ) : return :"""
data = { "app" : self . app_id , "record" : self . record_id , "comment" : { "text" : comment , } } if len ( mentions ) > 0 : _mentions = [ ] for m in mentions : if isinstance ( m , ( list , tuple ) ) : if len ( m ) == 2 : _mentions . append ( { "code" : m [ 0 ] , "type" : m ...
def _get ( self , url , query = None , ** kwargs ) : """Wrapper for the HTTP GET request ."""
return self . _request ( 'get' , url , query , ** kwargs )
def identify ( self ) : """Update client metadata on the server and negotiate features . : returns : nsqd response data if there was feature negotiation , otherwise ` ` None ` `"""
self . send ( nsq . identify ( { # nsqd 0.2.28 + 'client_id' : self . client_id , 'hostname' : self . hostname , # nsqd 0.2.19 + 'feature_negotiation' : True , 'heartbeat_interval' : self . heartbeat_interval , # nsqd 0.2.21 + 'output_buffer_size' : self . output_buffer_size , 'output_buffer_timeout' : self . output_bu...