signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def write ( source_mapping , output_stream = sys . stdout ) : """This method writes a Python module respresenting all the keys and values known to configman ."""
# a set of classes , modules and / or functions that are values in # configman options . These values will have to be imported in the # module that this method is writing . set_of_classes_needing_imports = set ( ) # once symbols are imported , they are in the namespace of the module , # but that ' s not where we want t...
def size ( ) : """Determines the height and width of the console window Returns : tuple of int : The height in lines , then width in characters"""
try : assert os != 'nt' and sys . stdout . isatty ( ) rows , columns = os . popen ( 'stty size' , 'r' ) . read ( ) . split ( ) except ( AssertionError , AttributeError , ValueError ) : # in case of failure , use dimensions of a full screen 13 " laptop rows , columns = DEFAULT_HEIGHT , DEFAULT_WIDTH return i...
def create ( cls , model = None , parent = None , autoCommit = True , defaults = None , title = '' ) : """Prompts the user to create a new record . : param model | < subclass of orb . Table > parent | < QWidget > autoCommit | < bool > defaults | < dict > | | None : return < orb . Table > | | None"""
if model is None : model = cls . tableType ( ) if model is None : return None dlg = cls . getDialog ( 'create' , parent ) # create dialog if not title : title = 'Create {0}' . format ( type ( model ) . __name__ ) dlg . setWindowTitle ( title ) widget = dlg . _mainwidget widget . setRecord ( model ( ...
def urlEncodeAndJoin ( self , seq , sepr = ',' ) : '''sepr . join ( urlencode ( seq ) ) Args : seq : string list to be urlencoded sepr : join seq with sepr Returns : str'''
try : from urllib . parse import quote_plus as encode return sepr . join ( [ encode ( x , encoding = CHARSET_UTF8 ) for x in seq ] ) except ImportError : from urllib import quote as encode return sepr . join ( [ i for i in map ( lambda x : encode ( x ) , seq ) ] )
def start_compress ( codec , image , stream ) : """Wraps openjp2 library function opj _ start _ compress . Start to compress the current image . Parameters codec : CODEC _ TYPE Compressor handle . image : pointer to ImageType Input filled image . stream : STREAM _ TYPE _ P Input stream . Raises ...
OPENJP2 . opj_start_compress . argtypes = [ CODEC_TYPE , ctypes . POINTER ( ImageType ) , STREAM_TYPE_P ] OPENJP2 . opj_start_compress . restype = check_error OPENJP2 . opj_start_compress ( codec , image , stream )
def _add_minimization_vars ( self ) : """Add variables and constraints for L1 norm minimization ."""
self . _z = self . _prob . namespace ( self . _model . reactions , lower = 0 ) # Define constraints v = self . _v . set ( self . _model . reactions ) z = self . _z . set ( self . _model . reactions ) self . _prob . add_linear_constraints ( z >= v , v >= - z )
def fit_text ( self , font_family = 'Calibri' , max_size = 18 , bold = False , italic = False , font_file = None ) : """Fit text - frame text entirely within bounds of its shape . Make the text in this text frame fit entirely within the bounds of its shape by setting word wrap on and applying the " best - fit "...
# - - - no - op when empty as fit behavior not defined for that case - - - if self . text == '' : return font_size = self . _best_fit_font_size ( font_family , max_size , bold , italic , font_file ) self . _apply_fit ( font_family , font_size , bold , italic )
def F ( self , x ) : """Classic NFW function in terms of arctanh and arctan : param x : r / Rs : return :"""
if isinstance ( x , np . ndarray ) : nfwvals = np . ones_like ( x ) inds1 = np . where ( x < 1 ) inds2 = np . where ( x > 1 ) nfwvals [ inds1 ] = ( 1 - x [ inds1 ] ** 2 ) ** - .5 * np . arctanh ( ( 1 - x [ inds1 ] ** 2 ) ** .5 ) nfwvals [ inds2 ] = ( x [ inds2 ] ** 2 - 1 ) ** - .5 * np . arctan ( ( ...
def storage ( self ) : """get the counter storage"""
annotation = get_portal_annotation ( ) if annotation . get ( NUMBER_STORAGE ) is None : annotation [ NUMBER_STORAGE ] = OIBTree ( ) return annotation [ NUMBER_STORAGE ]
def convert_cityscapes_instance_only ( data_dir , out_dir ) : """Convert from cityscapes format to COCO instance seg format - polygons"""
sets = [ 'gtFine_val' , 'gtFine_train' , 'gtFine_test' , # ' gtCoarse _ train ' , # ' gtCoarse _ val ' , # ' gtCoarse _ train _ extra ' ] ann_dirs = [ 'gtFine_trainvaltest/gtFine/val' , 'gtFine_trainvaltest/gtFine/train' , 'gtFine_trainvaltest/gtFine/test' , # ' gtCoarse / train ' , # ' gtCoarse / train _ extra ' , # '...
def find_prepositions ( chunked ) : """The input is a list of [ token , tag , chunk ] - items . The output is a list of [ token , tag , chunk , preposition ] - items . PP - chunks followed by NP - chunks make up a PNP - chunk ."""
# Tokens that are not part of a preposition just get the O - tag . for ch in chunked : ch . append ( "O" ) for i , chunk in enumerate ( chunked ) : if chunk [ 2 ] . endswith ( "PP" ) and chunk [ - 1 ] == "O" : # Find PP followed by other PP , NP with nouns and pronouns , VP with a gerund . if i < len ( ...
def saveFiles ( fileName1 , fileName2 , songs , artist , album , trackNum ) : """Save songs to files"""
songs [ 0 ] . export ( fileName1 , format = detectFormat ( fileName1 ) , tags = { 'artist' : artist , 'album' : album , 'track' : trackNum } ) songs [ 1 ] . export ( fileName2 , format = detectFormat ( fileName2 ) , tags = { 'artist' : artist , 'album' : album , 'track' : str ( int ( trackNum ) + 1 ) } )
def add_filter ( self , filter_expr , connector = AND , negate = False , trim = False , can_reuse = None , process_extras = True , force_having = False ) : """Copied from add _ filter to generate WHERES for translation fields ."""
if force_having : import warnings warnings . warn ( "multilingual-ng doesn't support force_having (see Django ticket #11293)" ) arg , value = filter_expr parts = arg . split ( LOOKUP_SEP ) if not parts : raise FieldError ( "Cannot parse keyword query %r" % arg ) # Work out the lookup type and remove it from...
def create_dat_file ( self ) : """Create and write empty data file in the data directory"""
output = "## {}\n" . format ( self . name ) try : kwargs_items = self . kwargs . iteritems ( ) except AttributeError : kwargs_items = self . kwargs . items ( ) for key , val in kwargs_items : if val is "l" : output += "#l {}=\n" . format ( str ( key ) ) elif val is "f" or True : output +...
def _add_submenu ( self , parent , data ) : """Adds items in data as a submenu to parent"""
for item in data : obj = item [ 0 ] if obj == wx . Menu : try : __ , menuname , submenu , menu_id = item except ValueError : __ , menuname , submenu = item menu_id = - 1 menu = obj ( ) self . _add_submenu ( menu , submenu ) if parent ==...
def peek ( self , lpBaseAddress , nSize ) : """Reads the memory of the process . @ see : L { read } @ type lpBaseAddress : int @ param lpBaseAddress : Memory address to begin reading . @ type nSize : int @ param nSize : Number of bytes to read . @ rtype : str @ return : Bytes read from the process mem...
# XXX TODO # + Maybe change page permissions before trying to read ? # + Maybe use mquery instead of get _ memory _ map ? # ( less syscalls if we break out of the loop earlier ) data = '' if nSize > 0 : try : hProcess = self . get_handle ( win32 . PROCESS_VM_READ | win32 . PROCESS_QUERY_INFORMATION ) ...
def create ( self , max_wait = 180 , ** kwargs ) : """Create an instance of the Predix Cache Service with they typical starting settings . : param max _ wait : service is created asynchronously , so will only wait this number of seconds before giving up ."""
# Will need to wait for the service to be provisioned before can add # service keys and get env details . self . service . create ( async = True , create_keys = False ) while self . _create_in_progress ( ) and max_wait > 0 : time . sleep ( 1 ) max_wait -= 1 # Now get the service env ( via service keys ) cfg = s...
def _map_intent_to_view_func ( self , intent ) : """Provides appropiate parameters to the intent functions ."""
if intent . name in self . _intent_view_funcs : view_func = self . _intent_view_funcs [ intent . name ] elif self . _default_intent_view_func is not None : view_func = self . _default_intent_view_func else : raise NotImplementedError ( 'Intent "{}" not found and no default intent specified.' . format ( inte...
def resource_factory ( self , name , schema , resource_cls = None ) : """Registers a new resource with a given schema . The schema must not have any unresolved references ( such as ` { " $ ref " : " # " } ` for self - references , or otherwise ) . A subclass of : class : ` Resource ` may be provided to add spec...
cls = type ( str ( upper_camel_case ( name ) ) , ( resource_cls or Resource , collections . MutableMapping ) , { '__doc__' : schema . get ( 'description' , '' ) } ) cls . _schema = schema cls . _client = self cls . _links = links = { } for link_schema in schema [ 'links' ] : link = Link ( self , rel = link_schema [...
def run_searchlight ( self , voxel_fn , pool_size = None ) : """Perform a function at each voxel which is set to True in the user - provided mask . The mask passed to the searchlight function will be further masked by the user - provided searchlight shape . Parameters voxel _ fn : function to apply at each ...
extra_block_fn_params = ( voxel_fn , self . shape , self . min_active_voxels_proportion ) block_fn_result = self . run_block_function ( _singlenode_searchlight , extra_block_fn_params , pool_size ) return block_fn_result
def _cost_method ( self , * args , ** kwargs ) : """Calculate positivity component of the cost This method returns 0 as the posivituty does not contribute to the cost . Returns float zero"""
if 'verbose' in kwargs and kwargs [ 'verbose' ] : print ( ' - Min (X):' , np . min ( args [ 0 ] ) ) return 0.0
def search_gallery ( self , q ) : """Search the gallery with the given query string ."""
url = self . _base_url + "/3/gallery/search?q={0}" . format ( q ) resp = self . _send_request ( url ) return [ _get_album_or_image ( thing , self ) for thing in resp ]
def get ( self , path , ** kwargs ) : """Perform an HTTP GET request of the specified path in Device Cloud Make an HTTP GET request against Device Cloud with this accounts credentials and base url . This method uses the ` requests < http : / / docs . python - requests . org / en / latest / > ` _ library ` r...
url = self . _make_url ( path ) return self . _make_request ( "GET" , url , ** kwargs )
def _update_field ( self , uri , field ) : '''Updates a field with the provided attributes . Args : keyreqiured identifier for the pipeline or box fieldStreakField object kwargs { name , type } see StreakField for details return ( status code , field dict )'''
# req sanity check payload = None if type ( field ) is not StreakField : return requests . codes . bad_request , None payload = field . to_dict ( rw = True ) # print ( new _ pl . attributes ) # print ( new _ pl . to _ dict ( ) ) # raw _ input ( ) try : uri = '/' . join ( [ uri , field . attributes [ 'key' ] ] )...
def __find_processes_by_filename ( self , filename ) : """Internally used by L { find _ processes _ by _ filename } ."""
found = list ( ) filename = filename . lower ( ) if PathOperations . path_is_absolute ( filename ) : for aProcess in self . iter_processes ( ) : imagename = aProcess . get_filename ( ) if imagename and imagename . lower ( ) == filename : found . append ( ( aProcess , imagename ) ) else :...
def subscribe ( self , topic , protocol , endpoint ) : """Subscribe to a Topic . : type topic : string : param topic : The name of the new topic . : type protocol : string : param protocol : The protocol used to communicate with the subscriber . Current choices are : email | email - json | http | https ...
params = { 'ContentType' : 'JSON' , 'TopicArn' : topic , 'Protocol' : protocol , 'Endpoint' : endpoint } response = self . make_request ( 'Subscribe' , params , '/' , 'GET' ) body = response . read ( ) if response . status == 200 : return json . loads ( body ) else : boto . log . error ( '%s %s' % ( response . ...
def helpdefault ( self , cmd , known ) : """Hook called to handle help on a command for which there is no help handler . " cmd " is the command name on which help was requested . " known " is a boolean indicating if this command is known ( i . e . if there is a handler for it ) . Returns a return code .""...
if known : msg = self . _str ( self . nohelp % ( cmd , ) ) if self . cmdlooping : self . stderr . write ( msg + '\n' ) else : self . stderr . write ( "%s: %s\n" % ( self . name , msg ) ) else : msg = self . unknowncmd % ( cmd , ) if self . cmdlooping : self . stderr . write (...
def intranges_from_list ( list_ ) : """Represent a list of integers as a sequence of ranges : ( ( start _ 0 , end _ 0 ) , ( start _ 1 , end _ 1 ) , . . . ) , such that the original integers are exactly those x such that start _ i < = x < end _ i for some i . Ranges are encoded as single integers ( start < < 3...
sorted_list = sorted ( list_ ) ranges = [ ] last_write = - 1 for i in range ( len ( sorted_list ) ) : if i + 1 < len ( sorted_list ) : if sorted_list [ i ] == sorted_list [ i + 1 ] - 1 : continue current_range = sorted_list [ last_write + 1 : i + 1 ] ranges . append ( _encode_range ( cur...
def create_pvsm_file ( vtk_files , pvsm_filename , relative_paths = True ) : """Create paraview status file ( . pvsm ) based on input vtk files . : param vtk _ files : : param pvsm _ filename : : param relative _ paths : : return :"""
from xml . etree . ElementTree import Element , SubElement , Comment import os . path as op top = Element ( 'ParaView' ) comment = Comment ( 'Generated for PyMOTW' ) top . append ( comment ) numberi = 4923 # vtk _ file = " C : \ Users \ miros \ lisa _ data \ 83779720_2 _ liver . vtk " sms = SubElement ( top , "ServerMa...
def suggest_accumulation_rate ( chron ) : """From core age - depth data , suggest mean accumulation rate ( cm / y )"""
# Follow ' s Bacon ' s method @ Bacon . R ln 30 - 44 # Suggested round vals . sugg = np . tile ( [ 1 , 2 , 5 ] , ( 4 , 1 ) ) * np . reshape ( np . repeat ( [ 0.1 , 1.0 , 10 , 100 ] , 3 ) , ( 4 , 3 ) ) # Get ballpark accumulation rates , uncalibrated dates . ballpacc = stats . linregress ( x = chron . depth , y = chron ...
def normalize_flags ( self , flags ) : """normalize the flags to make sure needed values are there after this method is called self . flags is available : param flags : the flags that will be normalized"""
flags [ 'type' ] = flags . get ( 'type' , None ) paction = flags . get ( 'action' , 'store' ) if paction == 'store_false' : flags [ 'default' ] = True flags [ 'type' ] = bool elif paction == 'store_true' : flags [ 'default' ] = False flags [ 'type' ] = bool prequired = False if 'default' in flags else f...
def disconnect ( self ) : """We are no more interested in this remote process"""
try : os . kill ( - self . pid , signal . SIGKILL ) except OSError : # The process was already dead , no problem pass self . read_buffer = b'' self . write_buffer = b'' self . set_enabled ( False ) if self . read_in_state_not_started : self . print_lines ( self . read_in_state_not_started ) self . read_...
def __print_step_by_console ( self , step ) : """print the step by console if the show variable is enabled : param step : step text"""
step_list = step . split ( u'\n' ) for s in step_list : self . logger . by_console ( u' %s' % repr ( s ) . replace ( "u'" , "" ) . replace ( "'" , "" ) )
def remove_path_dirname ( path ) : """Removes file paths directory if the directory is empty : param path : Filepath"""
dir_to_remove = os . path . dirname ( path ) if not os . listdir ( dir_to_remove ) : shutil . rmtree ( dir_to_remove ) else : if len ( os . listdir ( dir_to_remove ) ) == 1 : if os . listdir ( dir_to_remove ) [ 0 ] . startswith ( '.' ) : shutil . rmtree ( dir_to_remove )
def _run_ids ( runner , pcap ) : """Runs the specified IDS runner . : param runner : Runner instance to use : param pcap : File path to pcap for analysis : returns : dict of run metadata / alerts"""
run = { 'name' : runner . conf . get ( 'name' ) , 'module' : runner . conf . get ( 'module' ) , 'ruleset' : runner . conf . get ( 'ruleset' , 'default' ) , 'status' : STATUS_FAILED , } try : run_start = datetime . now ( ) version , alerts = runner . run ( pcap ) run [ 'version' ] = version or 'Unknown' ...
def _set_isis_system_info ( self , v , load = False ) : """Setter method for isis _ system _ info , mapped from YANG variable / isis _ state / router _ isis _ config / isis _ system _ info ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ isis _ system _ inf...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = isis_system_info . isis_system_info , is_container = 'container' , presence = False , yang_name = "isis-system-info" , rest_name = "isis-system-info" , parent = self , path_helper = self . _path_helper , extmethods = self . _...
def show ( self , wait = 1.2 , scale = 10 , module_color = ( 0 , 0 , 0 , 255 ) , background = ( 255 , 255 , 255 , 255 ) , quiet_zone = 4 ) : """Displays this QR code . This method is mainly intended for debugging purposes . This method saves the output of the : py : meth : ` png ` method ( with a default scal...
import os import time import tempfile import webbrowser try : # Python 2 from urlparse import urljoin from urllib import pathname2url except ImportError : # Python 3 from urllib . parse import urljoin from urllib . request import pathname2url f = tempfile . NamedTemporaryFile ( 'wb' , suffix = '.png' , ...
def serialize ( text : TransText ) : """Takes as input either a string to translate either an actual string and transforms it into a JSON - serializable structure that can be reconstructed using ` unserialize ( ) ` ."""
if isinstance ( text , str ) : return { 'type' : 'string' , 'value' : text , } elif isinstance ( text , StringToTranslate ) : return { 'type' : 'trans' , 'key' : text . key , 'count' : text . count , 'params' : text . params , } else : raise ValueError ( 'Cannot accept type "{}"' . format ( text . __class__...
def send_messages ( self , request , queryset , bulk = False , data = False ) : """Provides error handling for DeviceAdmin send _ message and send _ bulk _ message methods ."""
ret = [ ] errors = [ ] total_failure = 0 for device in queryset : if bulk : if data : response = queryset . send_message ( data = { "Nick" : "Mario" } ) else : response = queryset . send_message ( title = "Test notification" , body = "Test bulk notification" ) else : ...
def set ( self , instance , value , ** kw ) : # noqa """Set the value of the refernce field"""
ref = [ ] # The value is an UID if api . is_uid ( value ) : ref . append ( api . get_object_by_uid ( value ) ) # The value is already an object if api . is_at_content ( value ) : ref . append ( value ) # The value is a dictionary # - > handle it like a catalog query if u . is_dict ( value ) : results = api ...
def listen ( obj , name , func ) : """Arrange for ` func ( * args , * * kwargs ) ` to be invoked when the named signal is fired by ` obj ` ."""
signals = vars ( obj ) . setdefault ( '_signals' , { } ) signals . setdefault ( name , [ ] ) . append ( func )
def update_resources ( self , data , type_ , names = None , languages = None ) : """Update or add resource data . type _ = resource type to update names = a list of resource names to update ( None = all ) languages = a list of resource languages to update ( None = all )"""
UpdateResources ( self . filename , data , type_ , names , languages )
def _readrows ( self ) : """Internal method _ readrows , see readrows ( ) for description"""
# Read in the Bro Headers offset , self . field_names , self . field_types , self . type_converters = self . _parse_bro_header ( self . _filepath ) # Use parent class to yield each row as a dictionary for line in self . readlines ( offset = offset ) : # Check for # close if line . startswith ( '#close' ) : ...
def uptodate ( ) : '''Call the REST endpoint to see if the packages on the " server " are up to date .'''
DETAILS = _load_state ( ) for p in DETAILS [ 'packages' ] : version_float = float ( DETAILS [ 'packages' ] [ p ] ) version_float = version_float + 1.0 DETAILS [ 'packages' ] [ p ] = six . text_type ( version_float ) return DETAILS [ 'packages' ]
def p_block_statements ( self , p ) : 'block _ statements : block _ statements block _ statement'
p [ 0 ] = p [ 1 ] + ( p [ 2 ] , ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) : """See : meth : ` superclass method < . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > ` for spec of input and result values ."""
# extracting dictionary of coefficients C = self . COEFFS [ imt ] mag = self . _convert_magnitude ( rup . mag ) # computing the magnitude term . Equation 19 , page 2291 f1 = self . _compute_magnitude_scaling_term ( C , mag ) # computing the geometrical spreading term . Equation 20 , page 2291 f2 = self . _compute_geome...
def create_hall_to_link_mapping ( self ) : """: return : Mapping from hall name to associated link in SUDS . Creates inverted index from id to hall ."""
laundry_path = pkg_resources . resource_filename ( "penn" , "data/laundry.csv" ) with open ( laundry_path , "r" ) as f : reader = csv . reader ( f ) for row in reader : hall_id , hall_name , location , uuid = row hall_id = int ( hall_id ) self . hall_to_link [ hall_name ] = ALL_URL + uui...
def __send_receive_buffer ( self ) : """Performs a send of self . _ _ out _ buffer and then an immediate read into self . _ _ in _ buffer : return : None"""
self . __clear_in_buffer ( ) self . __send_buffer ( ) read_string = self . serial . read ( len ( self . __in_buffer ) ) if self . DEBUG_MODE : print ( "Read: '{}'" . format ( binascii . hexlify ( read_string ) ) ) if len ( read_string ) != len ( self . __in_buffer ) : raise IOError ( "{} bytes received for inpu...
def validate ( self , value ) : """Validates that the input is in self . choices ."""
super ( ChoicesField , self ) . validate ( value ) if value and not self . valid_value ( value ) : self . _on_invalid_value ( value )
def make_headers ( worksheet ) : """Make headers from worksheet"""
headers = { } cell_idx = 0 while cell_idx < worksheet . ncols : cell_type = worksheet . cell_type ( 0 , cell_idx ) if cell_type == 1 : header = slughifi ( worksheet . cell_value ( 0 , cell_idx ) ) if not header . startswith ( "_" ) : headers [ cell_idx ] = header cell_idx += 1 re...
def _lval_add_towards_polarity ( x , polarity ) : """Compute the appropriate Lval " kind " for the limit of value ` x ` towards ` polarity ` . Either ' toinf ' or ' pastzero ' depending on the sign of ` x ` and the infinity direction of polarity ."""
if x < 0 : if polarity < 0 : return Lval ( 'toinf' , x ) return Lval ( 'pastzero' , x ) elif polarity > 0 : return Lval ( 'toinf' , x ) return Lval ( 'pastzero' , x )
def _get_custom_models ( models ) : """Returns CustomModels for models with a custom ` _ _ implementation _ _ `"""
if models is None : models = Model . model_class_reverse_map . values ( ) custom_models = OrderedDict ( ) for cls in models : impl = getattr ( cls , "__implementation__" , None ) if impl is not None : model = CustomModel ( cls ) custom_models [ model . full_name ] = model if not custom_model...
def make_list_threads_message ( self , py_db , seq ) : """returns thread listing as XML"""
try : threads = get_non_pydevd_threads ( ) cmd_text = [ "<xml>" ] append = cmd_text . append for thread in threads : if is_thread_alive ( thread ) : append ( self . _thread_to_xml ( thread ) ) append ( "</xml>" ) return NetCommand ( CMD_RETURN , seq , '' . join ( cmd_text ) )...
def get_bibtex ( doi ) : """Get a BibTeX entry for a given DOI . . . note : : Adapted from https : / / gist . github . com / jrsmith3/5513926. : param doi : The canonical DOI to get BibTeX from . : returns : A BibTeX string or ` ` None ` ` . > > > get _ bibtex ( ' 10.1209/0295-5075/111/40005 ' ) ' @ art...
try : request = requests . get ( to_url ( doi ) , headers = { "accept" : "application/x-bibtex" } ) request . raise_for_status ( ) assert request . headers . get ( "content-type" ) == "application/x-bibtex" return request . text except ( RequestException , AssertionError ) : return None
def msgurls ( msg , urlidx = 1 ) : """Main entry function for urlscan . py"""
# Written as a generator so I can easily choose only # one subpart in the future ( e . g . , for # multipart / alternative ) . Actually , I might even add # a browser for the message structure ? enc = get_charset ( msg ) if msg . is_multipart ( ) : for part in msg . get_payload ( ) : for chunk in msgurls ( ...
def build_container_vm ( self , container , disk , zone = "us-east1-b" , tags = None , preemptible = True ) : """Build kwargs for a container VM . : param container : Container declaration . : type container : ` ` dict ` ` : param disk : Disk definition structure . : type disk : ` ` dict ` ` : param zone ...
if tags is None : tags = [ ] if container is None : raise ComputeEngineManagerException ( "Container declaration must not be None." ) if disk is None : raise ComputeEngineManagerException ( "Disk structure must not be None." ) return { 'ex_metadata' : { "gce-container-declaration" : container , "google-logg...
def calibration_cache_path ( self ) : """Determine the path to the correct calibration cache file to use ."""
if self . __ifo and self . __start > 0 : cal_path = self . job ( ) . get_config ( 'calibration' , 'path' ) # check if this is S2 : split calibration epochs if ( self . __LHO2k . match ( self . __ifo ) and ( self . __start >= 729273613 ) and ( self . __start <= 734367613 ) ) : if self . __start < int...
def _parse_tokens ( tokens ) : """Parse the tokens . This converts the tokens into a form where we can manipulate them more easily ."""
index = 0 parsed_tokens = [ ] num_tokens = len ( tokens ) while index < num_tokens : tok = Token ( * tokens [ index ] ) assert tok . token_type != token . INDENT if tok . token_type == tokenize . NEWLINE : # There ' s only one newline and it ' s at the end . break if tok . token_string in '([{' ...
def info ( self ) : """return info about configuration"""
uri = ',' . join ( x [ 'hostname' ] for x in self . routers ) mongodb_uri = 'mongodb://' + uri result = { 'id' : self . id , 'shards' : self . members , 'configsvrs' : self . configsvrs , 'routers' : self . routers , 'mongodb_uri' : mongodb_uri , 'orchestration' : 'sharded_clusters' } if self . login : result [ 'mo...
def _get_assignments_in ( self , filterlist , symbol = "" ) : """Returns a list of code elements whose names are in the specified object . : arg filterlist : the list of symbols to check agains the assignments . : arg symbol : when specified , return true if that symbol has its value changed via an assignment...
if symbol != "" : lsymbol = symbol for assign in self . _assignments : target = assign . split ( "%" ) [ 0 ] . lower ( ) if target == lsymbol : return True else : result = [ ] for assign in self . _assignments : target = assign . split ( "%" ) [ 0 ] . lower ( ) ...
def atlasdb_sync_zonefiles ( db , start_block , zonefile_dir , atlas_state , validate = True , end_block = None , path = None , con = None ) : """Synchronize atlas DB with name db NOT THREAD SAFE"""
ret = None with AtlasDBOpen ( con = con , path = path ) as dbcon : ret = atlasdb_queue_zonefiles ( dbcon , db , start_block , zonefile_dir , validate = validate , end_block = end_block ) atlasdb_cache_zonefile_info ( con = dbcon ) if atlas_state : # it could have been the case that a zone file we already have w...
def get_available_languages ( self , obj ) : """Fetching the available languages as queryset ."""
if obj : return obj . get_available_languages ( ) else : return self . model . _parler_meta . root_model . objects . none ( )
def create_vfs_explorer ( self , uri ) : """Returns a : py : class : ` IVFSExplorer ` object for the given URI . in uri of type str The URI describing the file system to use . return explorer of type : class : ` IVFSExplorer `"""
if not isinstance ( uri , basestring ) : raise TypeError ( "uri can only be an instance of type basestring" ) explorer = self . _call ( "createVFSExplorer" , in_p = [ uri ] ) explorer = IVFSExplorer ( explorer ) return explorer
def deBruijn ( n , k ) : """An implementation of the FKM algorithm for generating the de Bruijn sequence containing all k - ary strings of length n , as described in " Combinatorial Generation " by Frank Ruskey ."""
a = [ 0 ] * ( n + 1 ) def gen ( t , p ) : if t > n : for v in a [ 1 : p + 1 ] : yield v else : a [ t ] = a [ t - p ] for v in gen ( t + 1 , p ) : yield v for j in range ( a [ t - p ] + 1 , k ) : a [ t ] = j for v in gen ( t + 1 , t ...
def _GetAnalysisPlugins ( self , analysis_plugins_string ) : """Retrieves analysis plugins . Args : analysis _ plugins _ string ( str ) : comma separated names of analysis plugins to enable . Returns : list [ AnalysisPlugin ] : analysis plugins ."""
if not analysis_plugins_string : return [ ] analysis_plugins_list = [ name . strip ( ) for name in analysis_plugins_string . split ( ',' ) ] analysis_plugins = self . _analysis_manager . GetPluginObjects ( analysis_plugins_list ) return analysis_plugins . values ( )
def fill_inputs ( values ) : """Callback called when the data is received . Basically translator from the REST names to locally used names ."""
name_map = { # TODO : get rid of this crap "title_tags" : "title" , "subtitle_tags" : "subtitle" , "place_tags" : "place" , "lang_tags" : "language" , "keyword_tags" : "keywords" , "author_tags" : "author" , "publisher_tags" : "publisher" , "annotation_tags" : "annotation" , "creation_dates" : "creation_date" , } for r...
def from_multi_segment_list ( cls , description , segmentlists , names , ifos , seg_summ_lists = None , ** kwargs ) : """Initialize a SegFile object from a list of segmentlists . Parameters description : string ( required ) See File . _ _ init _ _ segmentlists : List of ligo . segments . segmentslist List...
seglistdict = segments . segmentlistdict ( ) for name , ifo , segmentlist in zip ( names , ifos , segmentlists ) : seglistdict [ ifo + ':' + name ] = segmentlist if seg_summ_lists is not None : seg_summ_dict = segments . segmentlistdict ( ) for name , ifo , seg_summ_list in zip ( names , ifos , seg_summ_lis...
def volume_attach ( name , server_name , device = '/dev/xvdb' , ** kwargs ) : '''Attach block volume'''
conn = get_conn ( ) return conn . volume_attach ( name , server_name , device , timeout = 300 )
def delocate_path ( tree_path , lib_path , lib_filt_func = None , copy_filt_func = filter_system_libs ) : """Copy required libraries for files in ` tree _ path ` into ` lib _ path ` Parameters tree _ path : str Root path of tree to search for required libraries lib _ path : str Directory into which we cop...
if lib_filt_func == "dylibs-only" : lib_filt_func = _dylibs_only if not exists ( lib_path ) : os . makedirs ( lib_path ) lib_dict = tree_libs ( tree_path , lib_filt_func ) if not copy_filt_func is None : lib_dict = dict ( ( key , value ) for key , value in lib_dict . items ( ) if copy_filt_func ( key ) ) co...
def add ( self , quantity ) : """Adds an angle to the value"""
newvalue = self . _value + quantity self . set ( newvalue . deg )
def _raise_or_extract ( self , response ) : """Raises an exception if the response indicates an API error . Otherwise returns the object at the ' data ' key of the API response ."""
try : data = response . json ( ) except ValueError : raise JoeException ( "The server responded with an unexpected format ({}). Is the API url correct?" . format ( response . status_code ) ) try : if response . ok : return data [ 'data' ] else : error = data [ 'errors' ] [ 0 ] ra...
def _generate_filenames ( sources ) : """Generate filenames . : param tuple sources : Sequence of strings representing path to file ( s ) . : return : Path to file ( s ) . : rtype : : py : class : ` str `"""
for source in sources : if os . path . isdir ( source ) : for path , dirlist , filelist in os . walk ( source ) : for fname in filelist : if nmrstarlib . VERBOSE : print ( "Processing file: {}" . format ( os . path . abspath ( fname ) ) ) if Ge...
async def SetMetricCredentials ( self , creds ) : '''creds : typing . Sequence [ ~ ApplicationMetricCredential ] Returns - > typing . Sequence [ ~ ErrorResult ]'''
# map input types to rpc msg _params = dict ( ) msg = dict ( type = 'Application' , request = 'SetMetricCredentials' , version = 4 , params = _params ) _params [ 'creds' ] = creds reply = await self . rpc ( msg ) return reply
def chromiumContext ( self , url , extra_tid = None ) : '''Return a active chromium context , useable for manual operations directly against chromium . The WebRequest user agent and other context is synchronized into the chromium instance at startup , and changes are flushed back to the webrequest instance ...
assert url is not None , "You need to pass a URL to the contextmanager, so it can dispatch to the correct tab!" if extra_tid is True : extra_tid = threading . get_ident ( ) return self . _chrome_context ( url , extra_tid = extra_tid )
def make_table ( file_dict ) : """Build and return an ` astropy . table . Table ` to store ` FileHandle `"""
col_key = Column ( name = 'key' , dtype = int ) col_path = Column ( name = 'path' , dtype = 'S256' ) col_creator = Column ( name = 'creator' , dtype = int ) col_timestamp = Column ( name = 'timestamp' , dtype = int ) col_status = Column ( name = 'status' , dtype = int ) col_flags = Column ( name = 'flags' , dtype = int...
def _recall_prec ( self , record , count ) : """get recall and precision from internal records"""
record = np . delete ( record , np . where ( record [ : , 1 ] . astype ( int ) == 0 ) [ 0 ] , axis = 0 ) sorted_records = record [ record [ : , 0 ] . argsort ( ) [ : : - 1 ] ] tp = np . cumsum ( sorted_records [ : , 1 ] . astype ( int ) == 1 ) fp = np . cumsum ( sorted_records [ : , 1 ] . astype ( int ) == 2 ) if count...
def intervention ( self , commit , conf ) : """Ask the user if they want to commit this container and run sh in it"""
if not conf . harpoon . interactive or conf . harpoon . no_intervention : yield return hp . write_to ( conf . harpoon . stdout , "!!!!\n" ) hp . write_to ( conf . harpoon . stdout , "It would appear building the image failed\n" ) hp . write_to ( conf . harpoon . stdout , "Do you want to run {0} where the build ...
def schedule_job ( date , callable_name , content_object = None , expires = '7d' , args = ( ) , kwargs = { } ) : """Schedule a job . ` date ` may be a datetime . datetime or a datetime . timedelta . The callable to be executed may be specified in two ways : - set ` callable _ name ` to an identifier ( ' mypac...
# TODO : allow to pass in a real callable , but check that it ' s a global assert callable_name and isinstance ( callable_name , basestring ) , callable_name if isinstance ( date , basestring ) : date = parse_timedelta ( date ) if isinstance ( date , datetime . timedelta ) : date = datetime . datetime . now ( )...
def check_dispatch ( self ) : # pylint : disable = too - many - branches """Check that all active satellites have a configuration dispatched A DispatcherError exception is raised if no configuration is dispatched ! : return : None"""
if not self . arbiter_link : raise DispatcherError ( "Dispatcher configuration problem: no valid arbiter link!" ) if not self . first_dispatch_done : raise DispatcherError ( "Dispatcher cannot check the dispatching, " "because no configuration is dispatched!" ) # We check for configuration parts to be dispatche...
def _scalar_coef_op_right ( func ) : """decorator for operator overloading when ScalarCoef is on the right"""
@ wraps ( func ) def verif ( self , scoef ) : if isinstance ( scoef , numbers . Number ) : return ScalarCoefs ( func ( self , self . _vec , scoef ) , self . nmax , self . mmax ) else : raise TypeError ( err_msg [ 'no_combi_SC' ] ) return verif
def dump_begin ( self , selector_id ) : """Start dumping a stream . Args : selector _ id ( int ) : The buffered stream we want to dump . Returns : ( int , int , int ) : Error code , second error code , number of available readings"""
if self . dump_walker is not None : self . storage . destroy_walker ( self . dump_walker ) selector = DataStreamSelector . FromEncoded ( selector_id ) self . dump_walker = self . storage . create_walker ( selector , skip_all = False ) return Error . NO_ERROR , Error . NO_ERROR , self . dump_walker . count ( )
def AddScanNode ( self , path_spec , parent_scan_node ) : """Adds a scan node for a certain path specification . Args : path _ spec ( PathSpec ) : path specification . parent _ scan _ node ( SourceScanNode ) : parent scan node or None . Returns : SourceScanNode : scan node . Raises : KeyError : if the...
scan_node = self . _scan_nodes . get ( path_spec , None ) if scan_node : raise KeyError ( 'Scan node already exists.' ) scan_node = SourceScanNode ( path_spec ) if parent_scan_node : if parent_scan_node . path_spec not in self . _scan_nodes : raise RuntimeError ( 'Parent scan node not present.' ) sc...
def _check_timedeltalike_freq_compat ( self , other ) : """Arithmetic operations with timedelta - like scalars or array ` other ` are only valid if ` other ` is an integer multiple of ` self . freq ` . If the operation is valid , find that integer multiple . Otherwise , raise because the operation is invalid ...
assert isinstance ( self . freq , Tick ) # checked by calling function own_offset = frequencies . to_offset ( self . freq . rule_code ) base_nanos = delta_to_nanoseconds ( own_offset ) if isinstance ( other , ( timedelta , np . timedelta64 , Tick ) ) : nanos = delta_to_nanoseconds ( other ) elif isinstance ( other ...
def node_insert_before ( self , node , new_node ) : """Insert the new node before node ."""
assert ( not self . node_is_on_list ( new_node ) ) assert ( node is not new_node ) prev = self . node_prev ( node ) assert ( prev is not None ) self . node_set_prev ( node , new_node ) self . node_set_next ( new_node , node ) self . node_set_prev ( new_node , prev ) self . node_set_next ( prev , new_node )
def _cartesian_to_keplerian ( cls , coord , center ) : """Conversion from cartesian ( position and velocity ) to keplerian The keplerian form is * a : semi - major axis * e : eccentricity * i : inclination * Ω : right - ascension of ascending node * ω : Argument of perigee * ν : True anomaly"""
r , v = coord [ : 3 ] , coord [ 3 : ] h = np . cross ( r , v ) # angular momentum vector h_norm = np . linalg . norm ( h ) r_norm = np . linalg . norm ( r ) v_norm = np . linalg . norm ( v ) K = v_norm ** 2 / 2 - center . µ / r_norm # specific energy a = - center . µ / ( 2 * K ) # semi - major axis e = sqrt ( 1 - h_nor...
def _make_sj_out_dict ( fns , jxns = None , define_sample_name = None ) : """Read multiple sj _ outs , return dict with keys as sample names and values as sj _ out dataframes . Parameters fns : list of strs of filenames or file handles List of filename of the SJ . out . tab files to read in jxns : set I...
if define_sample_name == None : define_sample_name = lambda x : x else : assert len ( set ( [ define_sample_name ( x ) for x in fns ] ) ) == len ( fns ) sj_outD = dict ( ) for fn in fns : sample = define_sample_name ( fn ) df = read_sj_out_tab ( fn ) # Remove any junctions that don ' t have any uniq...
def interpret_waveform ( fileContent , RelativeChannelNo ) : """Extracts the data for just 1 channel and computes the corresponding time array ( in seconds ) starting from 0. Important Note : RelativeChannelNo is NOT the channel number on the Saleae data logger it is the relative number of the channel that wa...
( ChannelData , LenOf1Channel , NumOfChannels , SampleTime ) = read_data_from_bytes ( fileContent ) if RelativeChannelNo > NumOfChannels - 1 : raise ValueError ( "There are {} channels saved, you attempted to read relative channel number {}. Pick a relative channel number between {} and {}" . format ( NumOfChannels...
def __learn_oneself ( self ) : """calculate cardinality , total and average string length"""
if not self . __parent_path or not self . __text_nodes : raise Exception ( "This error occurred because the step constructor\ had insufficient textnodes or it had empty string\ for its parent xpath" ) # Iterate through text nodes and sum up text length # TOD...
def update_bank ( self , bank_form ) : """Updates an existing bank . arg : bank _ form ( osid . assessment . BankForm ) : the form containing the elements to be updated raise : IllegalState - ` ` bank _ form ` ` already used in an update transaction raise : InvalidArgument - the form contains an invalid v...
# Implemented from template for # osid . resource . BinAdminSession . update _ bin _ template if self . _catalog_session is not None : return self . _catalog_session . update_catalog ( catalog_form = bank_form ) collection = JSONClientValidated ( 'assessment' , collection = 'Bank' , runtime = self . _runtime ) if n...
def write ( self , b : bytes ) -> None : """Add bytes to internal bytes buffer and if echo is True , echo contents to inner stream ."""
if not isinstance ( b , bytes ) : raise TypeError ( 'a bytes-like object is required, not {}' . format ( type ( b ) ) ) if not self . std_sim_instance . pause_storage : self . byte_buf += b if self . std_sim_instance . echo : self . std_sim_instance . inner_stream . buffer . write ( b ) # Since StdSim w...
def make_retrigger_request ( repo_name , request_id , auth , count = DEFAULT_COUNT_NUM , priority = DEFAULT_PRIORITY , dry_run = True ) : """Retrigger a request using buildapi self - serve . Returns a request . Buildapi documentation : POST / self - serve / { branch } / request Rebuild ` request _ id ` , whic...
url = '{}/{}/request' . format ( SELF_SERVE , repo_name ) payload = { 'request_id' : request_id } if count != DEFAULT_COUNT_NUM or priority != DEFAULT_PRIORITY : payload . update ( { 'count' : count , 'priority' : priority } ) if dry_run : LOG . info ( 'We would make a POST request to %s with the payload: %s' %...
def when_values ( self , ** criteria ) : """By default , ` ` Behold ` ` objects call ` ` str ( ) ` ` on all variables before sending them to the output stream . This method enables you to filter on those extracted string representations . The syntax is exactly like that of the ` ` when _ context ( ) ` ` metho...
criteria = { k : str ( v ) for k , v in criteria . items ( ) } self . _add_value_filters ( ** criteria ) return self
def peek ( self , size = 1 ) : """Looks C { size } bytes ahead in the stream , returning what it finds , returning the stream pointer to its initial position . @ param size : Default is 1. @ type size : C { int } @ raise ValueError : Trying to peek backwards . @ return : Bytes ."""
if size == - 1 : return self . peek ( len ( self ) - self . tell ( ) ) if size < - 1 : raise ValueError ( "Cannot peek backwards" ) bytes = '' pos = self . tell ( ) while not self . at_eof ( ) and len ( bytes ) != size : bytes += self . read ( 1 ) self . seek ( pos ) return bytes
def _assemble_and_send_request ( self ) : """Fires off the Fedex request . @ warning : NEVER CALL THIS METHOD DIRECTLY . CALL send _ request ( ) , WHICH RESIDES ON FedexBaseService AND IS INHERITED ."""
client = self . client # Fire off the query . return client . service . track ( WebAuthenticationDetail = self . WebAuthenticationDetail , ClientDetail = self . ClientDetail , TransactionDetail = self . TransactionDetail , Version = self . VersionId , SelectionDetails = self . SelectionDetails , ProcessingOptions = sel...
def project_dev_requirements ( ) : """List requirements for peltak commands configured for the project . This list is dynamic and depends on the commands you have configured in your project ' s pelconf . yaml . This will be the combined list of packages needed to be installed in order for all the configured c...
from peltak . core import conf from peltak . core import shell for dep in sorted ( conf . requirements ) : shell . cprint ( dep )
def json_to_initkwargs ( record_type , json_struct , kwargs = None ) : """This function converts a JSON dict ( json _ struct ) to a set of init keyword arguments for the passed Record ( or JsonRecord ) . It is called by the JsonRecord constructor . This function takes a JSON data structure and returns a keywo...
if kwargs is None : kwargs = { } if json_struct is None : json_struct = { } if not isinstance ( json_struct , dict ) : raise exc . JsonRecordCoerceError ( passed = json_struct , recordtype = record_type , ) unknown_keys = set ( json_struct . keys ( ) ) for propname , prop in record_type . properties . iteri...
def clean_value ( self , val ) : """val = : param dict val : { " content " : " " , " name " : " " , " ext " : " " , " type " : " " } : return :"""
if isinstance ( val , dict ) : if self . random_name : val [ 'random_name' ] = self . random_name if 'file_name' in val . keys ( ) : val [ 'name' ] = val . pop ( 'file_name' ) val [ 'content' ] = val . pop ( 'file_content' ) return self . file_manager ( ) . store_file ( ** val ) # If...
def get_and_save_value ( self , name , default = None ) : """Get value from request / session and save value to session"""
if getattr ( self , name , None ) : return getattr ( self , name ) value = self . get_session_value ( name , default ) value = self . request . POST . get ( name , value ) self . save_value ( name , value ) return value
def login ( self , email = None , password = None ) : """Login to establish a valid session ."""
auth_url = self . url ( 'auth' ) email = email or self . _config . get ( 'email' ) password = password or self . _config . get ( 'password' ) if password and not email : raise Exception ( 'Email must be provided when password is.' ) while True : if not email : sys . stdout . write ( 'Email: ' ) ...
def _reset_internal ( self ) : """Resets simulation internal configurations ."""
# instantiate simulation from MJCF model self . _load_model ( ) self . mjpy_model = self . model . get_model ( mode = "mujoco_py" ) self . sim = MjSim ( self . mjpy_model ) self . initialize_time ( self . control_freq ) # create visualization screen or renderer if self . has_renderer and self . viewer is None : sel...