signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def dump_all_handler_stats ( self ) : '''Return handler capture statistics Return a dictionary of capture handler statistics of the form : . . code - block : : none ' name ' : The handler ' s name , ' reads ' : The number of packet reads this handler has received ' data _ read _ length ' : The total lengt...
stats = [ ] for h in self . capture_handlers : now = calendar . timegm ( time . gmtime ( ) ) rot_time = calendar . timegm ( h [ 'log_rot_time' ] ) time_delta = now - rot_time approx_data_rate = '{} bytes/second' . format ( h [ 'data_read' ] / float ( time_delta ) ) stats . append ( { 'name' : h [ 'n...
def gen_remote_driver ( executor , capabilities ) : '''Generate remote drivers with desired capabilities ( self . _ _ caps ) and command _ executor @ param executor : command executor for selenium remote driver @ param capabilities : A dictionary of capabilities to request when starting the browser session . ...
# selenium requires browser ' s driver and PATH env . Firefox ' s driver is required for selenium3.0 firefox_profile = capabilities . pop ( "firefox_profile" , None ) return webdriver . Remote ( executor , desired_capabilities = capabilities , browser_profile = firefox_profile )
def _set_mpls_traffic_fecs ( self , v , load = False ) : """Setter method for mpls _ traffic _ fecs , mapped from YANG variable / telemetry / profile / mpls _ traffic _ fec / mpls _ traffic _ fecs ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ mpls _ traffic _...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "mpls_traffic_fec_address" , mpls_traffic_fecs . mpls_traffic_fecs , yang_name = "mpls-traffic-fecs" , rest_name = "fec" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _pa...
def fill_holes ( self , hole_size , inplace = False ) : # pragma : no cover """Fill holes in a vtki . PolyData or vtk . vtkPolyData object . Holes are identified by locating boundary edges , linking them together into loops , and then triangulating the resulting loops . Note that you can specify an approximat...
logging . warning ( 'vtki.pointset.PolyData.fill_holes is known to segfault. ' + 'Use at your own risk' ) fill = vtk . vtkFillHolesFilter ( ) fill . SetHoleSize ( hole_size ) fill . SetInputData ( self ) fill . Update ( ) mesh = _get_output ( fill ) if inplace : self . overwrite ( mesh ) else : return mesh
def _add_query_parameters ( base_url , name_value_pairs ) : """Add one query parameter to a base URL . : type base _ url : string : param base _ url : Base URL ( may already contain query parameters ) : type name _ value _ pairs : list of ( string , string ) tuples . : param name _ value _ pairs : Names and...
if len ( name_value_pairs ) == 0 : return base_url scheme , netloc , path , query , frag = urlsplit ( base_url ) query = parse_qsl ( query ) query . extend ( name_value_pairs ) return urlunsplit ( ( scheme , netloc , path , urlencode ( query ) , frag ) )
def setup_multiifo_interval_coinc ( workflow , hdfbank , trig_files , stat_files , veto_files , veto_names , out_dir , pivot_ifo , fixed_ifo , tags = None ) : """This function sets up exact match multiifo coincidence"""
if tags is None : tags = [ ] make_analysis_dir ( out_dir ) logging . info ( 'Setting up coincidence' ) if len ( hdfbank ) != 1 : raise ValueError ( 'Must use exactly 1 bank file for this coincidence ' 'method, I got %i !' % len ( hdfbank ) ) hdfbank = hdfbank [ 0 ] ifos , _ = trig_files . categorize_by_attr ( '...
def get ( self , * , txid , headers = None ) : """Get the block that contains the given transaction id ( ` ` txid ` ` ) else return ` ` None ` ` Args : txid ( str ) : Transaction id . headers ( dict ) : Optional headers to pass to the request . Returns : : obj : ` list ` of : obj : ` int ` : List of blo...
block_list = self . transport . forward_request ( method = 'GET' , path = self . path , params = { 'transaction_id' : txid } , headers = headers , ) return block_list [ 0 ] if len ( block_list ) else None
def add_experiment ( experiment ) : """Adds a new experiment"""
redis = oz . redis . create_connection ( ) oz . bandit . add_experiment ( redis , experiment )
def ofp_ofctl_field_name_to_ryu ( field ) : """Convert an ovs - ofctl field name to ryu equivalent ."""
mapped = _OXM_FIELD_OFCTL_ALIASES . get ( field ) if mapped : return mapped if field . endswith ( "_dst" ) : mapped = _OXM_FIELD_OFCTL_ALIASES . get ( field [ : - 3 ] + "src" ) if mapped : return mapped [ : - 3 ] + "dst" return field
def analyze ( self , time : int = None ) -> typing . Tuple [ float , float , int , int ] : """Determine noise , curvature , range , and domain of specified array . : param : pixel to inch ratio : param : time ( column ) to use . : return : curvature : return : noise : return : range : return : domain"""
if not time : time = int ( len ( self . times ) / 2 ) if self . domains [ time ] == 0 : yhat , residuals , mean_residual , error = self . _get_fit ( time ) yhat_p = self . ddiff ( yhat ) yhat_pp = self . ddiff ( yhat_p ) noise = self . _get_noise ( residuals ) curvature = ( 1 / self . ratio ) * ...
def _load_from_environ ( metadata , value_func = None ) : """Load configuration from environment variables . Any environment variable prefixed with the metadata ' s name will be used to recursively set dictionary keys , splitting on ' _ _ ' . : param value _ func : a mutator for the envvar ' s value ( if any ...
# We ' ll match the ennvar name against the metadata ' s name . The ennvar # name must be uppercase and hyphens in names converted to underscores . # | envar | name | matches ? | # | FOO _ BAR | foo | yes | # | FOO _ BAR | bar | no | # | foo _ bar | bar | no | # | FOO _ BAR _ BAZ | foo _ bar | yes | # | FOO _ BAR _ BAZ...
def apply_plugin_settings ( self , options ) : """Apply configuration file ' s plugin settings"""
color_scheme_n = 'color_scheme_name' color_scheme_o = self . get_color_scheme ( ) font_n = 'plugin_font' font_o = self . get_plugin_font ( ) wrap_n = 'wrap' wrap_o = self . get_option ( wrap_n ) self . wrap_action . setChecked ( wrap_o ) linenb_n = 'line_numbers' linenb_o = self . get_option ( linenb_n ) for editor in ...
def help ( cls , task = None ) : """Describe available tasks or one specific task"""
if task is None : usage_list = [ ] for task in iter ( cls . _tasks ) : task_func = getattr ( cls , task ) usage_string = " %s %s" % ( cls . _prog , task_func . usage ) desc = task_func . __doc__ . splitlines ( ) [ 0 ] usage_list . append ( ( usage_string , desc ) ) max_len =...
def imap_unordered ( self , func , iterable , chunksize = 1 ) : """The same as imap ( ) except that the ordering of the results from the returned iterator should be considered arbitrary . ( Only when there is only one worker process is the order guaranteed to be " correct " . )"""
collector = UnorderedResultCollector ( ) self . _create_sequences ( func , iterable , chunksize , collector ) return iter ( collector )
def default ( self , value ) : """Change of resolver name . : param value : new default value to use . : type value : str or callable : raises : KeyError if value is a string not already registered ."""
if value is None : if self : value = list ( self . keys ( ) ) [ 0 ] elif not isinstance ( value , string_types ) : value = register ( exprresolver = value , reg = self ) elif value not in self : raise KeyError ( '{0} not registered in {1}' . format ( value , self ) ) self . _default = value
def streamed_request ( self , command , event_stream_type , message = None ) : """Send command request and collect and return all emitted events . : param command : command to send : type command : str : param event _ stream _ type : event type emitted on command execution : type event _ stream _ type : str...
result = [ ] if message is not None : message = Message . serialize ( message ) # subscribe to event stream packet = Packet . register_event ( event_stream_type ) response = self . _communicate ( packet ) if response . response_type != Packet . EVENT_CONFIRM : raise SessionException ( "Unexpected response type ...
def send_location ( self , chat_id : Union [ int , str ] , latitude : float , longitude : float , disable_notification : bool = None , reply_to_message_id : int = None , reply_markup : Union [ "pyrogram.InlineKeyboardMarkup" , "pyrogram.ReplyKeyboardMarkup" , "pyrogram.ReplyKeyboardRemove" , "pyrogram.ForceReply" ] = N...
r = self . send ( functions . messages . SendMedia ( peer = self . resolve_peer ( chat_id ) , media = types . InputMediaGeoPoint ( geo_point = types . InputGeoPoint ( lat = latitude , long = longitude ) ) , message = "" , silent = disable_notification or None , reply_to_msg_id = reply_to_message_id , random_id = self ....
def distance_matrix ( trains1 , trains2 , cos , tau ) : """Return the * bipartite * ( rectangular ) distance matrix between the observations in the first and the second list . Convenience function ; equivalent to ` ` dissimilarity _ matrix ( trains1 , trains2 , cos , tau , " distance " ) ` ` . Refer to : func : `...
return dissimilarity_matrix ( trains1 , trains2 , cos , tau , "distance" )
def plot_gc ( poles , color = 'g' , fignum = 1 ) : """plots a great circle on an equal area projection Parameters _ _ _ _ _ Input fignum : number of matplotlib object poles : nested list of [ Dec , Inc ] pairs of poles color : color of lower hemisphere dots for great circle - must be in form : ' g ' , '...
for pole in poles : pmagplotlib . plot_circ ( fignum , pole , 90. , color )
def current_day ( ) : """Most recent day , if it ' s during the Advent of Code . Happy Holidays ! Day 1 is assumed , otherwise ."""
aoc_now = datetime . datetime . now ( tz = AOC_TZ ) if aoc_now . month != 12 : log . warning ( "current_day is only available in December (EST)" ) return 1 day = min ( aoc_now . day , 25 ) return day
def get_labels ( ids_find ) : """Labels to make Cannon model spectra"""
a = pyfits . open ( "%s/lamost_catalog_full.fits" % LAB_DIR ) data = a [ 1 ] . data a . close ( ) id_all = data [ 'lamost_id' ] id_all = np . array ( id_all ) id_all = np . array ( [ val . strip ( ) for val in id_all ] ) snr_all = data [ 'cannon_snrg' ] chisq_all = data [ 'cannon_chisq' ] teff = data [ 'cannon_teff' ] ...
def AnalyzeClient ( self , client ) : """Finds the client _ id and keywords for a client . Args : client : A VFSGRRClient record to find keywords for . Returns : A tuple ( client _ id , keywords ) where client _ id is the client identifier and keywords is a list of keywords related to client ."""
client_id = self . _ClientIdFromURN ( client . urn ) # Start with both the client id itself , and a universal keyword , used to # find all clients . # TODO ( user ) : Remove the universal keyword once we have a better way # to do this , i . e . , once we have a storage library which can list all # clients directly . ke...
async def populate_projects ( self , force = False ) : """Download the ` ` projects . yml ` ` file and populate ` ` self . projects ` ` . This only sets it once , unless ` ` force ` ` is set . Args : force ( bool , optional ) : Re - run the download , even if ` ` self . projects ` ` is already defined . Def...
if force or not self . projects : with tempfile . TemporaryDirectory ( ) as tmpdirname : self . projects = await load_json_or_yaml_from_url ( self , self . config [ 'project_configuration_url' ] , os . path . join ( tmpdirname , 'projects.yml' ) )
def updateLicenseManager ( self , licenseManagerInfo ) : """ArcGIS License Server Administrator works with your portal and enforces licenses for ArcGIS Pro . This operation allows you to change the license server connection information for your portal . When you import entitlements into portal using the Impor...
url = self . _url + "/licenses/updateLicenseManager" params = { "f" : "json" , "licenseManagerInfo" : licenseManagerInfo } return self . _post ( url = url , param_dict = params , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port )
def get_beta_list ( queue , * args ) : """获取调整后的风险因子列表 , 用于归一化风险因子系数 Keyword arguments : queue - - 标题候选队列 * args - - 强化ef , 客串如多个list Return : beta _ list - - 所有候选标题的beta , list类型"""
beta_list = [ ] for i in queue : c = CDM ( i ) beta_list . append ( c . get_alpha ( * args ) ) return beta_list
def splitlines ( self , keepends = False ) : """Return a list of the lines in the string , breaking at line boundaries . Line breaks are not included in the resulting list unless keepends is given and True . : param bool keepends : Include linebreaks ."""
return [ self . __class__ ( l ) for l in self . value_colors . splitlines ( keepends ) ]
def tcpdump ( pktlist , dump = False , getfd = False , args = None , prog = None , getproc = False , quiet = False , use_tempfile = None , read_stdin_opts = None , linktype = None , wait = True ) : """Run tcpdump or tshark on a list of packets . When using ` ` tcpdump ` ` on OSX ( ` ` prog = = conf . prog . tcpdu...
getfd = getfd or getproc if prog is None : prog = [ conf . prog . tcpdump ] _prog_name = "windump()" if WINDOWS else "tcpdump()" elif isinstance ( prog , six . string_types ) : _prog_name = "{}()" . format ( prog ) prog = [ prog ] else : raise ValueError ( "prog must be a string" ) # Build Popen arg...
def update_tunnel_context ( self , context_id , friendly_name = None , remote_peer = None , preshared_key = None , phase1_auth = None , phase1_crypto = None , phase1_dh = None , phase1_key_ttl = None , phase2_auth = None , phase2_crypto = None , phase2_dh = None , phase2_forward_secrecy = None , phase2_key_ttl = None )...
context = self . get_tunnel_context ( context_id ) if friendly_name is not None : context [ 'friendlyName' ] = friendly_name if remote_peer is not None : context [ 'customerPeerIpAddress' ] = remote_peer if preshared_key is not None : context [ 'presharedKey' ] = preshared_key if phase1_auth is not None : ...
def classical_damage ( fragility_functions , hazard_imls , hazard_poes , investigation_time , risk_investigation_time ) : """: param fragility _ functions : a list of fragility functions for each damage state : param hazard _ imls : Intensity Measure Levels : param hazard _ poes : hazard curve : param i...
spi = fragility_functions . steps_per_interval if spi and spi > 1 : # interpolate imls = numpy . array ( fragility_functions . interp_imls ) min_val , max_val = hazard_imls [ 0 ] , hazard_imls [ - 1 ] assert min_val > 0 , hazard_imls # sanity check numpy . putmask ( imls , imls < min_val , min_val )...
def CleanString ( s ) : """Cleans up string . Doesn ' t catch everything , appears to sometimes allow double underscores to occur as a result of replacements ."""
punc = ( ' ' , '-' , '\'' , '.' , '&amp;' , '&' , '+' , '@' ) pieces = [ ] for part in s . split ( ) : part = part . strip ( ) for p in punc : part = part . replace ( p , '_' ) part = part . strip ( '_' ) part = part . lower ( ) pieces . append ( part ) return '_' . join ( pieces )
def times ( self , factor ) : """Return a new set with each element ' s multiplicity multiplied with the given scalar factor . > > > ms = Multiset ( ' aab ' ) > > > sorted ( ms . times ( 2 ) ) [ ' a ' , ' a ' , ' a ' , ' a ' , ' b ' , ' b ' ] You can also use the ` ` * ` ` operator for the same effect : >...
if factor == 0 : return self . __class__ ( ) if factor < 0 : raise ValueError ( 'The factor must no be negative.' ) result = self . __copy__ ( ) _elements = result . _elements for element in _elements : _elements [ element ] *= factor result . _total *= factor return result
def load ( cls , path , fmt = None , backend = None ) : r"""Load a graph from a file . Edge weights are retrieved as an edge attribute named " weight " . Signals are retrieved from node attributes , and stored in the : attr : ` signals ` dictionary under the attribute name . ` N ` - dimensional signals that...
if fmt is None : fmt = os . path . splitext ( path ) [ 1 ] [ 1 : ] if fmt not in [ 'graphml' , 'gml' , 'gexf' ] : raise ValueError ( 'Unsupported format {}.' . format ( fmt ) ) def load_networkx ( path , fmt ) : nx = _import_networkx ( ) load = getattr ( nx , 'read_' + fmt ) graph = load ( path ) ...
def contains ( array , ty , string ) : """Checks if given string is contained in each string in the array . Output is a vec of booleans . Args : array ( WeldObject / Numpy . ndarray ) : Input array start ( int ) : starting index size ( int ) : length to truncate at ty ( WeldType ) : Type of each element...
weld_obj = WeldObject ( encoder_ , decoder_ ) string_obj = weld_obj . update ( string ) if isinstance ( string , WeldObject ) : string_obj = string . obj_id weld_obj . dependencies [ string_obj ] = string array_var = weld_obj . update ( array ) if isinstance ( array , WeldObject ) : array_var = array . obj_...
def main ( ) : """NAME zeq _ magic . py DESCRIPTION reads in a MagIC measurements formatted file , makes plots of remanence decay during demagnetization experiments . Reads in prior interpretations saved in a specimens formatted file interpretations in a specimens file . interpretations are saved in the...
if '-h' in sys . argv : print ( main . __doc__ ) return dir_path = pmag . get_named_arg ( "-WD" , default_val = os . getcwd ( ) ) meas_file = pmag . get_named_arg ( "-f" , default_val = "measurements.txt" ) spec_file = pmag . get_named_arg ( "-fsp" , default_val = "specimens.txt" ) specimen = pmag . get_named_a...
def shuffle_song ( self , song , * , num_songs = 100 , only_library = False , recently_played = None ) : """Get a listing of song shuffle / mix songs . Parameters : song ( dict ) : A song dict . num _ songs ( int , Optional ) : The maximum number of songs to return from the station . Default : ` ` 100 ` ` ...
station_info = { 'num_entries' : num_songs , 'library_content_only' : only_library } if 'storeId' in song : station_info [ 'seed' ] = { 'trackId' : song [ 'storeId' ] , 'seedType' : StationSeedType . store_track . value } else : station_info [ 'seed' ] = { 'trackLockerId' : song [ 'id' ] , 'seedType' : StationS...
def p_ty_funty_complex ( self , p ) : "ty : ' ( ' maybe _ arg _ types ' ) ' ARROW ty"
argument_types = p [ 2 ] return_type = p [ 5 ] # Check here whether too many kwarg or vararg types are present # Each item in the list uses the dictionary encoding of tagged variants arg_types = [ argty [ 'arg_type' ] for argty in argument_types if 'arg_type' in argty ] vararg_types = [ argty [ 'vararg_type' ] for argt...
def _find_particle_image ( self , query , match , all_particles ) : """Find particle with the same index as match in a neighboring tile ."""
_ , idxs = self . particle_kdtree . query ( query . pos , k = 10 ) neighbors = all_particles [ idxs ] for particle in neighbors : if particle . index == match . index : return particle raise MBuildError ( 'Unable to find matching particle image while' ' stitching bonds.' )
def download ( self , path , args = [ ] , filepath = None , opts = { } , compress = True , ** kwargs ) : """Makes a request to the IPFS daemon to download a file . Downloads a file or files from IPFS into the current working directory , or the directory given by ` ` filepath ` ` . Raises ~ ipfsapi . excepti...
url = self . base + path wd = filepath or '.' params = [ ] params . append ( ( 'stream-channels' , 'true' ) ) params . append ( ( 'archive' , 'true' ) ) if compress : params . append ( ( 'compress' , 'true' ) ) for opt in opts . items ( ) : params . append ( opt ) for arg in args : params . append ( ( 'arg'...
def _set_process ( self , v , load = False ) : """Setter method for process , mapped from YANG variable / rbridge _ id / resource _ monitor / process ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ process is considered as a private method . Backends loo...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = process . process , is_container = 'container' , presence = False , yang_name = "process" , rest_name = "process" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True ,...
def get_content_type ( obj , field_name = False ) : """Returns the content type of an object . : param obj : A model instance . : param field _ name : Field of the object to return ."""
content_type = ContentType . objects . get_for_model ( obj ) if field_name : return getattr ( content_type , field_name , '' ) return content_type
def delete ( self , id ) : '''Unfollow an object given its ID'''
model = self . model . objects . only ( 'id' ) . get_or_404 ( id = id ) follow = Follow . objects . get_or_404 ( follower = current_user . id , following = model , until = None ) follow . until = datetime . now ( ) follow . save ( ) count = Follow . objects . followers ( model ) . count ( ) return { 'followers' : count...
def _set_hello_padding_point_to_point ( self , v , load = False ) : """Setter method for hello _ padding _ point _ to _ point , mapped from YANG variable / routing _ system / router / isis / router _ isis _ cmds _ holder / router _ isis _ attributes / hello / padding / hello _ padding _ point _ to _ point ( contain...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = hello_padding_point_to_point . hello_padding_point_to_point , is_container = 'container' , presence = False , yang_name = "hello-padding-point-to-point" , rest_name = "point-to-point" , parent = self , path_helper = self . _p...
def _type_string ( label , case = None ) : """Shortcut for string like fields"""
return label , abstractSearch . in_string , lambda s : abstractRender . default ( s , case = case ) , ""
def database_download ( self , output_file , target_url , database_path , complete = False ) : """Check to see if the download has previously been completed . Run the download if necessary . Create the completefile if required : param output _ file : Name and path of local copy of downloaded target : param ta...
# Create a file to store the logs ; it will be used to determine if the database was downloaded and set - up completefile = os . path . join ( database_path , 'complete' ) if not os . path . isfile ( completefile ) : self . url_request ( target_url = target_url , output_file = output_file ) if complete : # Crea...
def add_properties ( props , mol ) : """apply properties to the molecule object Returns : None ( alter molecule object directly )"""
if not props : return # The properties supersedes all charge and radical values in the atom block for _ , atom in mol . atoms_iter ( ) : atom . charge = 0 atom . multi = 1 atom . mass = None for prop in props . get ( "CHG" , [ ] ) : mol . atom ( prop [ 0 ] ) . charge = prop [ 1 ] for prop in props ....
def visitValueType ( self , ctx : jsgParser . ValueTypeContext ) : """valueType : idref | nonRefValueType"""
if ctx . idref ( ) : self . _typeid = as_token ( ctx ) else : self . visitChildren ( ctx )
def save ( self ) : """Save the session for later retrieval : raises : IOError"""
try : with open ( self . _filename , 'wb' ) as session_file : session_file . write ( self . dumps ( ) ) except IOError as error : LOGGER . error ( 'Session file error: %s' , error ) raise error
def activate_nsxcontroller ( self , ** kwargs ) : """Activate NSX Controller Args : name ( str ) : nsxcontroller name callback ( function ) : A function executed upon completion of the method . Returns : Return value of ` callback ` . Raises : None"""
name = kwargs . pop ( 'name' ) name_args = dict ( name = name ) method_name = 'nsx_controller_activate' method_class = self . _brocade_tunnels nsxcontroller_attr = getattr ( method_class , method_name ) config = nsxcontroller_attr ( ** name_args ) output = self . _callback ( config ) return output
def clear ( name ) : '''Clear the namespace from the register USAGE : . . code - block : : yaml clearns : reg . clear : - name : myregister'''
ret = { 'name' : name , 'changes' : { } , 'comment' : '' , 'result' : True } if name in __reg__ : __reg__ [ name ] . clear ( ) return ret
def weighted_std ( values , weights ) : """Calculate standard deviation weighted by errors"""
average = np . average ( values , weights = weights ) variance = np . average ( ( values - average ) ** 2 , weights = weights ) return np . sqrt ( variance )
def loader ( filepath , logger = None , ** kwargs ) : """Load an object from an ASDF file . See : func : ` ginga . util . loader ` for more info . TODO : kwargs may contain info about what part of the file to load"""
# see ginga . util . loader module # TODO : return an AstroTable if loading a table , etc . # for now , assume always an image from ginga import AstroImage image = AstroImage . AstroImage ( logger = logger ) with asdf . open ( filepath ) as asdf_f : # image . load _ asdf ( asdf _ f , * * kwargs ) image . load_asdf ...
def what_if_I_upgrade ( conn , pkg_name = 'openquake.server.db.schema.upgrades' , extract_scripts = 'extract_upgrade_scripts' ) : """: param conn : a DB API 2 connection : param str pkg _ name : the name of the package with the upgrade scripts : param extract _ scripts : name of the method to extract the ...
msg_safe_ = '\nThe following scripts can be applied safely:\n%s' msg_slow_ = '\nPlease note that the following scripts could be slow:\n%s' msg_danger_ = ( '\nPlease note that the following scripts are potentially ' 'dangerous and could destroy your data:\n%s' ) upgrader = UpgradeManager . instance ( conn , pkg_name ) a...
def _request_xml ( sport ) : """Request XML data from scorespro . com : param sport : sport being played : type sport : string : return : XML data : rtype : string"""
url = 'http://www.scorespro.com/rss2/live-{}.xml' . format ( sport ) r = requests . get ( url ) if r . ok : return _load_xml ( r . content ) else : raise errors . SportError ( sport )
def relative_deviation ( h1 , h2 ) : # 18 us @ array , 42 us @ list \ w 100 bins r"""Calculate the deviation between two histograms . The relative deviation between two histograms : math : ` H ` and : math : ` H ' ` of size : math : ` m ` is defined as : . . math : : d _ { rd } ( H , H ' ) = \ frac { \ ...
h1 , h2 = __prepare_histogram ( h1 , h2 ) numerator = math . sqrt ( scipy . sum ( scipy . square ( h1 - h2 ) ) ) denominator = ( math . sqrt ( scipy . sum ( scipy . square ( h1 ) ) ) + math . sqrt ( scipy . sum ( scipy . square ( h2 ) ) ) ) / 2. return numerator / denominator
def explicit_start_marker ( self , source ) : """Does the python representation of this cell requires an explicit start of cell marker ?"""
if not self . use_cell_markers : return False if self . metadata : return True if self . cell_marker_start : start_code_re = re . compile ( '^' + self . comment + r'\s*' + self . cell_marker_start + r'\s*(.*)$' ) end_code_re = re . compile ( '^' + self . comment + r'\s*' + self . cell_marker_end + r'\s*...
def thread_data ( name , value = NOTHING , ct = None ) : '''Set or retrieve an attribute ` ` name ` ` from thread ` ` ct ` ` . If ` ` ct ` ` is not given used the current thread . If ` ` value ` ` is None , it will get the value otherwise it will set the value .'''
ct = ct or current_thread ( ) if is_mainthread ( ct ) : loc = process_data ( ) elif not hasattr ( ct , '_pulsar_local' ) : ct . _pulsar_local = loc = { } else : loc = ct . _pulsar_local if value is not NOTHING : if name in loc : if loc [ name ] is not value : raise RuntimeError ( '%s...
def add ( self , roles ) : """: param roles : _ rolerepresentation array keycloak api"""
return self . _client . post ( url = self . _client . get_full_url ( self . get_path ( 'single' , realm = self . _realm_name , id = self . _user_id ) ) , data = json . dumps ( roles , sort_keys = True ) )
def temporal_segmentation ( segments , min_time ) : """Segments based on time distant points Args : segments ( : obj : ` list ` of : obj : ` list ` of : obj : ` Point ` ) : segment points min _ time ( int ) : minimum required time for segmentation"""
final_segments = [ ] for segment in segments : final_segments . append ( [ ] ) for point in segment : if point . dt > min_time : final_segments . append ( [ ] ) final_segments [ - 1 ] . append ( point ) return final_segments
def is_valid_variable_name ( string_to_check ) : """Returns whether the provided name is a valid variable name in Python : param string _ to _ check : the string to be checked : return : True or False"""
try : parse ( '{} = None' . format ( string_to_check ) ) return True except ( SyntaxError , ValueError , TypeError ) : return False
def ifind_first_object ( self , ObjectClass , ** kwargs ) : """Retrieve the first object of type ` ` ObjectClass ` ` , matching the specified filters in ` ` * * kwargs ` ` - - case insensitive . | If USER _ IFIND _ MODE is ' nocase _ collation ' this method maps to find _ first _ object ( ) . | If USER _ IFIN...
# Call regular find ( ) if USER _ IFIND _ MODE is nocase _ collation if self . user_manager . USER_IFIND_MODE == 'nocase_collation' : return self . find_first_object ( ObjectClass , ** kwargs ) # Convert . . . ( email = value ) to . . . ( email _ _ iexact = value ) iexact_kwargs = { } for key , value in kwargs . it...
def enable_beacon ( name , ** kwargs ) : '''Enable a beacon on the minion . Args : name ( str ) : Name of the beacon to enable . Returns : dict : Boolean and status message on success or failure of enable . CLI Example : . . code - block : : bash salt ' * ' beacons . enable _ beacon ps'''
ret = { 'comment' : [ ] , 'result' : True } if not name : ret [ 'comment' ] = 'Beacon name is required.' ret [ 'result' ] = False return ret if 'test' in kwargs and kwargs [ 'test' ] : ret [ 'comment' ] = 'Beacon {0} would be enabled.' . format ( name ) else : _beacons = list_ ( return_yaml = False ...
def read_neb ( self , reverse = True , terminate_on_match = True ) : """Reads NEB data . This only works with OUTCARs from both normal VASP NEB calculations or from the CI NEB method implemented by Henkelman et al . Args : reverse ( bool ) : Read files in reverse . Defaults to false . Useful for large fil...
patterns = { "energy" : r"energy\(sigma->0\)\s+=\s+([\d\-\.]+)" , "tangent_force" : r"(NEB: projections on to tangent \(spring, REAL\)\s+\S+|tangential force \(eV/A\))\s+([\d\-\.]+)" } self . read_pattern ( patterns , reverse = reverse , terminate_on_match = terminate_on_match , postprocess = str ) self . data [ "energ...
def is_pushdown ( self ) : """Tests whether machine is a pushdown automaton ."""
return ( self . num_stores == 3 and self . state == 0 and self . has_cell ( 0 ) and self . input == 1 and self . has_input ( 1 ) and self . has_stack ( 2 ) )
def _connect ( self ) : """Connect to server ."""
self . _soc = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) self . _soc . connect ( ( self . _ipaddr , self . _port ) ) self . _soc . send ( _build_request ( { 'cmd' : cmd . CMD_MESSAGE_PASSWORD , 'sha' : self . _password } ) )
def check_no_self_dependency ( cls , dap ) : '''Check that the package does not depend on itself . Return a list of problems .'''
problems = list ( ) if 'package_name' in dap . meta and 'dependencies' in dap . meta : dependencies = set ( ) for dependency in dap . meta [ 'dependencies' ] : if 'dependencies' in dap . _badmeta and dependency in dap . _badmeta [ 'dependencies' ] : continue # No version specified ...
def whois_domains ( self , domains ) : """Calls WHOIS domain end point Args : domains : An enumerable of domains Returns : A dict of { domain : domain _ result }"""
api_name = 'opendns-whois-domain' fmt_url_path = u'whois/{0}' return self . _multi_get ( api_name , fmt_url_path , domains )
def _multi_lines ( self , strands , permutation ) : '''Prepares lines to write to file for pfunc command input . : param strand : Strand input ( cr . DNA or cr . RNA ) . : type strand : cr . DNA or cr . DNA : param permutation : Permutation ( e . g . [ 1 , 2 , 3 , 4 ] ) of the type used by pfunc _ multi . ...
lines = [ ] # Write the total number of distinct strands lines . append ( str ( len ( strands ) ) ) # Write the distinct strands lines += [ str ( strand ) for strand in strands ] # Write the permutation lines . append ( ' ' . join ( str ( p ) for p in permutation ) ) return lines
def get_path_completion_type ( cwords , cword , opts ) : """Get the type of path completion ( ` ` file ` ` , ` ` dir ` ` , ` ` path ` ` or None ) : param cwords : same as the environmental variable ` ` COMP _ WORDS ` ` : param cword : same as the environmental variable ` ` COMP _ CWORD ` ` : param opts : The ...
if cword < 2 or not cwords [ cword - 2 ] . startswith ( '-' ) : return for opt in opts : if opt . help == optparse . SUPPRESS_HELP : continue for o in str ( opt ) . split ( '/' ) : if cwords [ cword - 2 ] . split ( '=' ) [ 0 ] == o : if not opt . metavar or any ( x in ( 'path' , ...
def fetch_timeline_history_files ( self , max_timeline ) : """Copy all timeline history files found on the server without checking if we have them or not . The history files are very small so reuploading them should not matter ."""
while max_timeline > 1 : self . c . execute ( "TIMELINE_HISTORY {}" . format ( max_timeline ) ) timeline_history = self . c . fetchone ( ) history_filename = timeline_history [ 0 ] history_data = timeline_history [ 1 ] . tobytes ( ) self . log . debug ( "Received timeline history: %s for timeline %r...
def gene_id_of_associated_transcript ( effect ) : """Ensembl gene ID of transcript associated with effect , returns None if effect does not have transcript ."""
return apply_to_transcript_if_exists ( effect = effect , fn = lambda t : t . gene_id , default = None )
def validateDayOfMonth ( value , year , month , blank = False , strip = None , allowlistRegexes = None , blocklistRegexes = None , excMsg = None ) : """Raises ValidationException if value is not a day of the month , from 1 to 28 , 29 , 30 , or 31 depending on the month and year . Returns value . * value ( str...
try : daysInMonth = calendar . monthrange ( year , month ) [ 1 ] except : raise PySimpleValidateException ( 'invalid arguments for year and/or month' ) try : return validateInt ( value , blank = blank , strip = strip , allowlistRegexes = allowlistRegexes , blocklistRegexes = blocklistRegexes , min = 1 , max...
def _to_upper ( self ) : """Convert sequences to upper case ."""
self . exon_seq = self . exon_seq . upper ( ) self . three_prime_seq = [ s . upper ( ) for s in self . three_prime_seq ] self . five_prime_seq = [ s . upper ( ) for s in self . five_prime_seq ]
def _build_one_pep517 ( self , req , tempd , python_tag = None ) : """Build one InstallRequirement using the PEP 517 build process . Returns path to wheel if successfully built . Otherwise , returns None ."""
assert req . metadata_directory is not None try : req . spin_message = 'Building wheel for %s (PEP 517)' % ( req . name , ) logger . debug ( 'Destination directory: %s' , tempd ) wheel_name = req . pep517_backend . build_wheel ( tempd , metadata_directory = req . metadata_directory ) if python_tag : # G...
def get_resource_areas ( self , enterprise_name = None , organization_name = None ) : """GetResourceAreas . [ Preview API ] : param str enterprise _ name : : param str organization _ name : : rtype : [ ResourceAreaInfo ]"""
query_parameters = { } if enterprise_name is not None : query_parameters [ 'enterpriseName' ] = self . _serialize . query ( 'enterprise_name' , enterprise_name , 'str' ) if organization_name is not None : query_parameters [ 'organizationName' ] = self . _serialize . query ( 'organization_name' , organization_na...
def unblock_by_identifier ( self , identifier ) : """Unblocks by identifier Args : identifier ( str ) : Should be any of : username , phone _ number , email . See : https : / / auth0 . com / docs / api / management / v2 # ! / User _ Blocks / delete _ user _ blocks"""
params = { 'identifier' : identifier } return self . client . delete ( self . _url ( ) , params = params )
def int2baseTwo ( x ) : """x is a positive integer . Convert it to base two as a list of integers in reverse order as a list ."""
# repeating x > > = 1 and x & 1 will do the trick assert x >= 0 bitInverse = [ ] while x != 0 : bitInverse . append ( x & 1 ) x >>= 1 return bitInverse
def percent_covered ( self , src_path ) : """Return a float percent of lines covered for the source in ` src _ path ` . If we have no coverage information for ` src _ path ` , returns None"""
diff_violations = self . _diff_violations ( ) . get ( src_path ) if diff_violations is None : return None # Protect against a divide by zero num_measured = len ( diff_violations . measured_lines ) if num_measured > 0 : num_uncovered = len ( diff_violations . lines ) return 100 - float ( num_uncovered ) / nu...
def cluster_row_and_col ( net , dist_type = 'cosine' , linkage_type = 'average' , dendro = True , run_clustering = True , run_rank = True , ignore_cat = False , calc_cat_pval = False , links = False ) : '''cluster net . dat and make visualization json , net . viz . optionally leave out dendrogram colorbar groups ...
import scipy from copy import deepcopy from scipy . spatial . distance import pdist from . import categories , make_viz , cat_pval dm = { } for inst_rc in [ 'row' , 'col' ] : tmp_mat = deepcopy ( net . dat [ 'mat' ] ) dm [ inst_rc ] = calc_distance_matrix ( tmp_mat , inst_rc , dist_type ) # save directly to...
def _broadcasting_elementwise_op ( op , a , b ) : r"""Apply binary operation ` op ` to every pair in tensors ` a ` and ` b ` . : param op : binary operator on tensors , e . g . tf . add , tf . substract : param a : tf . Tensor , shape [ n _ 1 , . . . , n _ a ] : param b : tf . Tensor , shape [ m _ 1 , . . . ,...
flatres = op ( tf . reshape ( a , [ - 1 , 1 ] ) , tf . reshape ( b , [ 1 , - 1 ] ) ) return tf . reshape ( flatres , tf . concat ( [ tf . shape ( a ) , tf . shape ( b ) ] , 0 ) )
def find_field_meta ( obj , value ) : """In a model , finds the attribute meta connected to the last object when a chain of connected objects is given in a string separated with double underscores ."""
if "__" in value : value_list = value . split ( "__" ) child_obj = obj . _meta . get_field ( value_list [ 0 ] ) . rel . to return find_field_meta ( child_obj , "__" . join ( value_list [ 1 : ] ) ) return obj . _meta . get_field ( value )
def get_contacts ( self ) : """Use this method to get contacts from your Telegram address book . Returns : On success , a list of : obj : ` User ` objects is returned . Raises : : class : ` RPCError < pyrogram . RPCError > ` in case of a Telegram RPC error ."""
while True : try : contacts = self . send ( functions . contacts . GetContacts ( hash = 0 ) ) except FloodWait as e : log . warning ( "get_contacts flood: waiting {} seconds" . format ( e . x ) ) time . sleep ( e . x ) else : log . info ( "Total contacts: {}" . format ( len (...
def os_function_mapper ( map ) : """When called with an open connection , this function uses the conn . guess _ os ( ) function to guess the operating system of the connected host . It then uses the given map to look up a function name that corresponds to the operating system , and calls it . Example : : ...
def decorated ( job , host , conn , * args , ** kwargs ) : os = conn . guess_os ( ) func = map . get ( os ) if func is None : raise Exception ( 'No handler for %s found.' % os ) return func ( job , host , conn , * args , ** kwargs ) return decorated
def update ( self , cluster_template_id , name = NotUpdated , plugin_name = NotUpdated , plugin_version = NotUpdated , description = NotUpdated , cluster_configs = NotUpdated , node_groups = NotUpdated , anti_affinity = NotUpdated , net_id = NotUpdated , default_image_id = NotUpdated , use_autoconfig = NotUpdated , sha...
data = { } self . _copy_if_updated ( data , name = name , plugin_name = plugin_name , plugin_version = plugin_version , description = description , cluster_configs = cluster_configs , node_groups = node_groups , anti_affinity = anti_affinity , neutron_management_network = net_id , default_image_id = default_image_id , ...
def str_lsnode ( self , astr_path = "" ) : """Print / return the set of nodes branching from current node as string"""
self . sCore . reset ( ) str_cwd = self . cwd ( ) if len ( astr_path ) : self . cdnode ( astr_path ) for node in self . snode_current . d_nodes . keys ( ) : self . sCore . write ( '%s\n' % node ) str_ls = self . sCore . strget ( ) if len ( astr_path ) : self . cdnode ( str_cwd ) return str_ls
def execute_no_results ( self , sock_info , generator ) : """Execute all operations , returning no results ( w = 0 ) ."""
# Cannot have both unacknowledged write and bypass document validation . if self . bypass_doc_val and sock_info . max_wire_version >= 4 : raise OperationFailure ( "Cannot set bypass_document_validation with" " unacknowledged write concern" ) coll = self . collection # If ordered is True we have to send GLE or use w...
def _add_node ( self , node ) : """Add a node to the workflow : param node : The node object : type node : Node : return : None"""
self . nodes [ node . node_id ] = node logging . info ( "Added node with id {} containing {} streams" . format ( node . node_id , len ( node . streams ) ) )
def train_all ( ctx , output ) : """Train POS tagger on WSJ , GENIA , and both . With and without cluster features ."""
click . echo ( 'chemdataextractor.pos.train_all' ) click . echo ( 'Output: %s' % output ) ctx . invoke ( train , output = '%s_wsj_nocluster.pickle' % output , corpus = 'wsj' , clusters = False ) ctx . invoke ( train , output = '%s_wsj.pickle' % output , corpus = 'wsj' , clusters = True ) ctx . invoke ( train , output =...
def non_fluent_size ( self ) -> Sequence [ Sequence [ int ] ] : '''The size of each non - fluent in canonical order . Returns : Sequence [ Sequence [ int ] ] : A tuple of tuple of integers representing the shape and size of each non - fluent .'''
fluents = self . domain . non_fluents ordering = self . domain . non_fluent_ordering return self . _fluent_size ( fluents , ordering )
def _write_config ( self ) : """Write this component ' s configuration back to the database"""
if not self . config : self . log ( "Unable to write non existing configuration" , lvl = error ) return self . config . save ( ) self . log ( "Configuration stored." )
def _get_grouper ( self , obj , validate = True ) : """Parameters obj : the subject object validate : boolean , default True if True , validate the grouper Returns a tuple of binner , grouper , obj ( possibly sorted )"""
self . _set_grouper ( obj ) self . grouper , exclusions , self . obj = _get_grouper ( self . obj , [ self . key ] , axis = self . axis , level = self . level , sort = self . sort , validate = validate ) return self . binner , self . grouper , self . obj
def expand_action ( data ) : """From one document or action definition passed in by the user extract the action / data lines needed for elasticsearch ' s : meth : ` ~ elasticsearch . Elasticsearch . bulk ` api . : return es format to bulk doc"""
# when given a string , assume user wants to index raw json if isinstance ( data , string_types ) : return '{"index": {}}' , data # make sure we don ' t alter the action data = data . copy ( ) op_type = data . pop ( EsBulk . OP_TYPE , EsBulk . INDEX ) action = ActionParser . _get_relevant_action_params ( data , op_...
def _get_date_time_format ( dt_string ) : '''Copied from win _ system . py ( _ get _ date _ time _ format ) Function that detects the date / time format for the string passed . : param str dt _ string : A date / time string : return : The format of the passed dt _ string : rtype : str'''
valid_formats = [ '%I:%M:%S %p' , '%I:%M %p' , '%H:%M:%S' , '%H:%M' , '%Y-%m-%d' , '%m-%d-%y' , '%m-%d-%Y' , '%m/%d/%y' , '%m/%d/%Y' , '%Y/%m/%d' ] for dt_format in valid_formats : try : datetime . strptime ( dt_string , dt_format ) return dt_format except ValueError : continue return Fa...
def download_and_compile_igraph ( self ) : """Downloads and compiles the C core of igraph ."""
print ( "We will now try to download and compile the C core from scratch." ) print ( "Version number of the C core: %s" % self . c_core_versions [ 0 ] ) if len ( self . c_core_versions ) > 1 : print ( "We will also try: %s" % ", " . join ( self . c_core_versions [ 1 : ] ) ) print ( "" ) igraph_builder = IgraphCCore...
def qth_survival_times ( q , survival_functions , cdf = False ) : """Find the times when one or more survival functions reach the qth percentile . Parameters q : float or array a float between 0 and 1 that represents the time when the survival function hits the qth percentile . survival _ functions : a ( n ...
# pylint : disable = cell - var - from - loop , misplaced - comparison - constant , no - else - return q = pd . Series ( q ) if not ( ( q <= 1 ) . all ( ) and ( 0 <= q ) . all ( ) ) : raise ValueError ( "q must be between 0 and 1" ) survival_functions = pd . DataFrame ( survival_functions ) if survival_functions . ...
def main ( ) : """pyqode - console main function ."""
global program , args , ret print ( os . getcwd ( ) ) ret = 0 if '--help' in sys . argv or '-h' in sys . argv or len ( sys . argv ) == 1 : print ( __doc__ ) else : program = sys . argv [ 1 ] args = sys . argv [ 2 : ] if args : ret = subprocess . call ( [ program ] + args ) else : ret...
def _isSetter ( node_type , node ) : """Determine whether the given node is a setter property . @ param node _ type : The type of the node to inspect . @ param node : The L { logilab . astng . bases . NodeNG } to inspect . @ return : a boolean indicating if the given node is a setter ."""
if node_type not in [ 'function' , 'method' ] : return False for name in _getDecoratorsName ( node ) : if '.setter' in name : return True return False
def create_response ( self , message = None , end_session = False , card_obj = None , reprompt_message = None , is_ssml = None ) : """message - text message to be spoken out by the Echo end _ session - flag to determine whether this interaction should end the session card _ obj = JSON card object to substitute ...
response = dict ( self . base_response ) if message : response [ 'response' ] = self . create_speech ( message , is_ssml ) response [ 'response' ] [ 'shouldEndSession' ] = end_session if card_obj : response [ 'response' ] [ 'card' ] = card_obj if reprompt_message : response [ 'response' ] [ 'reprompt' ] = s...
def import_env ( * envs ) : 'import environment variables from host'
for env in envs : parts = env . split ( ':' , 1 ) if len ( parts ) == 1 : export_as = env else : env , export_as = parts env_val = os . environ . get ( env ) if env_val is not None : yield '{}={}' . format ( export_as , shlex . quote ( env_val ) )
def update_qa ( quietly = False ) : """Merge code from develop to qa"""
switch ( 'dev' ) switch ( 'qa' ) local ( 'git merge --no-edit develop' ) local ( 'git push' ) if not quietly : print ( red ( 'PLEASE DEPLOY CODE: fab deploy:all' ) )
def update_power_state ( self , id_or_uri , power_state ) : """Sets the power state of the specified power delivery device . The device must be an HP Intelligent Outlet . Args : id _ or _ uri : Can be either the power device id or the uri power _ state : { " powerState " : " On | Off " } Returns : str...
uri = self . _client . build_uri ( id_or_uri ) + "/powerState" return self . _client . update ( power_state , uri )