signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def pop ( string , encoding = None ) : """pop ( string , encoding = None ) - > ( object , remain ) This function parses a tnetstring into a python object . It returns a tuple giving the parsed object and a string containing any unparsed data from the end of the string ."""
# Parse out data length , type and remaining string . try : ( dlen , rest ) = string . split ( ":" , 1 ) dlen = int ( dlen ) except ValueError : raise ValueError ( "not a tnetstring: missing or invalid length prefix" ) try : ( data , type , remain ) = ( rest [ : dlen ] , rest [ dlen ] , rest [ dlen + 1 ...
def _encode_string ( string ) : """Return a byte string , encoding Unicode with UTF - 8."""
if not isinstance ( string , bytes ) : string = string . encode ( 'utf8' ) return ffi . new ( 'char[]' , string )
def _neg ( node ) : """Return the inverse of * node * ."""
if node is BDDNODEZERO : return BDDNODEONE elif node is BDDNODEONE : return BDDNODEZERO else : return _bddnode ( node . root , _neg ( node . lo ) , _neg ( node . hi ) )
def facets_on_hull ( self ) : """Find which facets of the mesh are on the convex hull . Returns on _ hull : ( len ( mesh . facets ) , ) bool is A facet on the meshes convex hull or not"""
# facets plane , origin and normal normals = self . facets_normal origins = self . facets_origin # ( n , 3 ) convex hull vertices convex = self . convex_hull . vertices . view ( np . ndarray ) . copy ( ) # boolean mask for which facets are on convex hull on_hull = np . zeros ( len ( self . facets ) , dtype = np . bool ...
def get_job_status ( self , job_id ) : """Retrieve task statuses from ECS API : param job _ id ( str ) : AWS Batch job uuid Returns one of { SUBMITTED | PENDING | RUNNABLE | STARTING | RUNNING | SUCCEEDED | FAILED }"""
response = self . _client . describe_jobs ( jobs = [ job_id ] ) # Error checking status_code = response [ 'ResponseMetadata' ] [ 'HTTPStatusCode' ] if status_code != 200 : msg = 'Job status request received status code {0}:\n{1}' raise Exception ( msg . format ( status_code , response ) ) return response [ 'job...
def children ( self , recursive = False ) : """Returns the list of child nodes for this item . : return [ < QtGui . QTreeWidgetItem > , . . ]"""
for i in xrange ( self . childCount ( ) ) : child = self . child ( i ) yield child if recursive : for subchild in child . children ( recursive = True ) : yield subchild
def _download ( self , fmfile , destination , overwrite , callback ) : """The actual downloader streaming content from Filemail . : param fmfile : to download : param destination : destination path : param overwrite : replace existing files ? : param callback : callback function that will receive total file...
fullpath = os . path . join ( destination , fmfile . get ( 'filename' ) ) path , filename = os . path . split ( fullpath ) if os . path . exists ( fullpath ) : msg = 'Skipping existing file: {filename}' logger . info ( msg . format ( filename = filename ) ) return filesize = fmfile . get ( 'filesize' ) if n...
def agent_color ( self , val ) : """gets a colour for agent 0 - 9"""
if val == '0' : colour = 'blue' elif val == '1' : colour = 'navy' elif val == '2' : colour = 'firebrick' elif val == '3' : colour = 'blue' elif val == '4' : colour = 'blue2' elif val == '5' : colour = 'blue4' elif val == '6' : colour = 'gray22' elif val == '7' : colour = 'gray57' elif va...
def process_response ( self , request , response ) : """Convert HttpResponseRedirect to HttpResponse if request is via ajax to allow ajax request to redirect url"""
if request . is_ajax ( ) and hasattr ( request , 'horizon' ) : queued_msgs = request . horizon [ 'async_messages' ] if type ( response ) == http . HttpResponseRedirect : # Drop our messages back into the session as per usual so they # don ' t disappear during the redirect . Not that we explicitly # use ...
def auth_required ( self , view_func ) : """Decorator that provides an access to view function for authenticated users only . Note that we don ' t run authentication when ` HAWK _ ENABLED ` is ` False ` ."""
@ wraps ( view_func ) def wrapped_view_func ( * args , ** kwargs ) : if current_app . config [ 'HAWK_ENABLED' ] : if current_app . config [ 'HAWK_ALLOW_COOKIE_AUTH' ] and session : self . _auth_by_cookie ( ) else : self . _auth_by_signature ( ) return view_func ( * args ,...
def compute_srec_checksum ( srec ) : """Compute the checksum byte of a given S - Record Returns : The checksum as a string hex byte ( ex : " 0C " )"""
# Get the summable data from srec # start at 2 to remove the S * record entry data = srec [ 2 : len ( srec ) ] sum = 0 # For each byte , convert to int and add . # ( step each two character to form a byte ) for position in range ( 0 , len ( data ) , 2 ) : current_byte = data [ position : position + 2 ] int_valu...
def build_imputation_loyers_proprietaires ( temporary_store = None , year = None ) : """Build menage consumption by categorie fiscale dataframe"""
assert temporary_store is not None assert year is not None # Load data bdf_survey_collection = SurveyCollection . load ( collection = 'budget_des_familles' , config_files_directory = config_files_directory ) survey = bdf_survey_collection . get_survey ( 'budget_des_familles_{}' . format ( year ) ) if year == 1995 : ...
def run_commands ( self , commands ) : """Only useful for EOS"""
if "eos" in self . profile : return list ( self . parent . cli ( commands ) . values ( ) ) [ 0 ] else : raise AttributeError ( "MockedDriver instance has not attribute '_rpc'" )
def copy ( self ) : """Returns a copy of the context ."""
other = ContextModel ( self . _context , self . parent ( ) ) other . _stale = self . _stale other . _modified = self . _modified other . request = self . request [ : ] other . packages_path = self . packages_path other . implicit_packages = self . implicit_packages other . package_filter = self . package_filter other ....
def update_with_zero_body ( self , uri = None , timeout = - 1 , custom_headers = None ) : """Makes a PUT request to update a resource when no request body is required . Args : uri : Allows to use a different URI other than resource URI timeout : Timeout in seconds . Wait for task completion by default . The...
if not uri : uri = self . data [ 'uri' ] logger . debug ( 'Update with zero length body (uri = %s)' % uri ) resource_data = self . _helper . do_put ( uri , None , timeout , custom_headers ) return resource_data
def doi ( self ) : '''Returns ISBN number with segment hypenation Data obtained from https : / / www . isbn - international . org / https : / / www . isbn - international . org / export _ rangemessage . xml @ return : ISBN formated as ISBN13 with hyphens'''
if not ISBN . hyphenRange : ISBN . hyphenRange = hyphen . ISBNRange ( ) seg = ISBN . hyphenRange . hyphensegments ( self . _id ) return '10.' + self . _id [ 0 : 3 ] + '.' + self . _id [ 3 : - ( 1 + seg [ 3 ] ) ] + '/' + self . _id [ - ( 1 + seg [ 3 ] ) : ]
def unpacktar ( tarfile , destdir ) : """Unpack given tarball into the specified dir"""
nullfd = open ( os . devnull , "w" ) tarfile = cygpath ( os . path . abspath ( tarfile ) ) log . debug ( "unpack tar %s into %s" , tarfile , destdir ) try : check_call ( [ TAR , '-xzf' , tarfile ] , cwd = destdir , stdout = nullfd , preexec_fn = _noumask ) except Exception : log . exception ( "Error unpacking t...
def ascii_listing2program_dump ( self , basic_program_ascii , program_start = None ) : """convert a ASCII BASIC program listing into tokens . This tokens list can be used to insert it into the Emulator RAM ."""
if program_start is None : program_start = self . DEFAULT_PROGRAM_START basic_lines = self . ascii_listing2basic_lines ( basic_program_ascii , program_start ) program_dump = self . listing . basic_lines2program_dump ( basic_lines , program_start ) assert isinstance ( program_dump , bytearray ) , ( "is type: %s and ...
def _handle_retry ( self , resp ) : """Handle any exceptions during API request or parsing its response status code . Parameters : resp : requests . Response instance obtained during concerning request or None , when request failed Returns : True if should retry our request or raises original Exception"""
exc_t , exc_v , exc_tb = sys . exc_info ( ) if exc_t is None : raise TypeError ( 'Must be called in except block.' ) retry_on_exc = tuple ( ( x for x in self . _retry_on if inspect . isclass ( x ) ) ) retry_on_codes = tuple ( ( x for x in self . _retry_on if isinstance ( x , int ) ) ) if issubclass ( exc_t , Zendes...
def get_attached_pipettes ( self ) : """Mimic the behavior of robot . get _ attached _ pipettes"""
api = object . __getattribute__ ( self , '_api' ) instrs = { } for mount , data in api . attached_instruments . items ( ) : instrs [ mount . name . lower ( ) ] = { 'model' : data . get ( 'name' , None ) , 'id' : data . get ( 'pipette_id' , None ) , 'mount_axis' : Axis . by_mount ( mount ) , 'plunger_axis' : Axis . ...
def param_docstrings ( self , info , max_col_len = 100 , only_changed = False ) : """Build a string to that presents all of the parameter docstrings in a clean format ( alternating red and blue for readability ) ."""
( params , val_dict , changed ) = info contents = [ ] displayed_params = { } for name , p in params . items ( ) : if only_changed and not ( name in changed ) : continue displayed_params [ name ] = p right_shift = max ( len ( name ) for name in displayed_params . keys ( ) ) + 2 for i , name in enumerate ...
def delete ( self , docids ) : """Delete documents from the current session ."""
self . check_session ( ) result = self . session . delete ( docids ) if self . autosession : self . commit ( ) return result
def construct ( self , mapping : dict , ** kwargs ) : """Construct an object from a mapping : param mapping : the constructor definition , with ` ` _ _ type _ _ ` ` name and keyword arguments : param kwargs : additional keyword arguments to pass to the constructor"""
assert '__type__' not in kwargs and '__args__' not in kwargs mapping = { ** mapping , ** kwargs } factory_fqdn = mapping . pop ( '__type__' ) factory = self . load_name ( factory_fqdn ) args = mapping . pop ( '__args__' , [ ] ) return factory ( * args , ** mapping )
async def jsk_debug ( self , ctx : commands . Context , * , command_string : str ) : """Run a command timing execution and catching exceptions ."""
alt_ctx = await copy_context_with ( ctx , content = ctx . prefix + command_string ) if alt_ctx . command is None : return await ctx . send ( f'Command "{alt_ctx.invoked_with}" is not found' ) start = time . perf_counter ( ) async with ReplResponseReactor ( ctx . message ) : with self . submit ( ctx ) : ...
def get_pv_args ( name , session = None , call = None ) : '''Get PV arguments for a VM . . code - block : : bash salt - cloud - a get _ pv _ args xenvm01'''
if call == 'function' : raise SaltCloudException ( 'This function must be called with -a or --action.' ) if session is None : log . debug ( 'New session being created' ) session = _get_session ( ) vm = _get_vm ( name , session = session ) pv_args = session . xenapi . VM . get_PV_args ( vm ) if pv_args : ...
def _count_async ( self , limit = None , ** q_options ) : """Internal version of count _ async ( ) ."""
# TODO : Support offset by incorporating it to the limit . if 'offset' in q_options : raise NotImplementedError ( '.count() and .count_async() do not support ' 'offsets at present.' ) if 'limit' in q_options : raise TypeError ( 'Cannot specify limit as a non-keyword argument and as a ' 'keyword argument simulta...
def color_range ( startcolor , goalcolor , steps ) : """wrapper for interpolate _ tuple that accepts colors as html ( " # CCCCC " and such )"""
start_tuple = make_color_tuple ( startcolor ) goal_tuple = make_color_tuple ( goalcolor ) return interpolate_tuple ( start_tuple , goal_tuple , steps )
def add ( self , key , val , minutes ) : """Store an item in the cache if it does not exist . : param key : The cache key : type key : str : param val : The cache value : type val : mixed : param minutes : The lifetime in minutes of the cached value : type minutes : int : rtype : bool"""
return self . _memcache . add ( self . _prefix + key , val , minutes * 60 )
def parameterstep ( timestep = None ) : """Define a parameter time step size within a parameter control file . Argument : * timestep ( | Period | ) : Time step size . Function parameterstep should usually be be applied in a line immediately behind the model import . Defining the step size of time dependen...
if timestep is not None : parametertools . Parameter . parameterstep ( timestep ) namespace = inspect . currentframe ( ) . f_back . f_locals model = namespace . get ( 'model' ) if model is None : model = namespace [ 'Model' ] ( ) namespace [ 'model' ] = model if hydpy . pub . options . usecython and 'cy...
def decode ( self , data , erase_pos = None , only_erasures = False ) : '''Repair a message , whatever its size is , by using chunking'''
# erase _ pos is a list of positions where you know ( or greatly suspect at least ) there is an erasure ( ie , wrong character but you know it ' s at this position ) . Just input the list of all positions you know there are errors , and this method will automatically split the erasures positions to attach to the corres...
def sample ( generator , min = - 1 , max = 1 , width = SAMPLE_WIDTH ) : '''Convert audio waveform generator into packed sample generator .'''
# select signed char , short , or in based on sample width fmt = { 1 : '<B' , 2 : '<h' , 4 : '<i' } [ width ] return ( struct . pack ( fmt , int ( sample ) ) for sample in normalize ( hard_clip ( generator , min , max ) , min , max , - 2 ** ( width * 8 - 1 ) , 2 ** ( width * 8 - 1 ) - 1 ) )
def files ( self ) : """Return the names of files to be created ."""
files_description = [ [ self . project_name , self . project_name + '.tex' , 'LaTeXBookFileTemplate' ] , [ self . project_name , 'references.bib' , 'BibTeXFileTemplate' ] , [ self . project_name , 'Makefile' , 'LaTeXMakefileFileTemplate' ] , ] return files_description
def getrefs ( self , reflist ) : """reflist is got from getobjectref in parse _ idd . py getobjectref returns a dictionary . reflist is an item in the dictionary getrefs gathers all the fields refered by reflist"""
alist = [ ] for element in reflist : if element [ 0 ] . upper ( ) in self . dt : for elm in self . dt [ element [ 0 ] . upper ( ) ] : alist . append ( elm [ element [ 1 ] ] ) return alist
def find ( self , name , menu = None ) : """Finds a menu item by name and returns it . : param name : The menu item name ."""
menu = menu or self . menu for i in menu : if i . name == name : return i else : if i . childs : ret_item = self . find ( name , menu = i . childs ) if ret_item : return ret_item
def edges ( word : str , lang : str = "th" ) : """Get edges from ConceptNet API : param str word : word : param str lang : language"""
obj = requests . get ( f"http://api.conceptnet.io/c/{lang}/{word}" ) . json ( ) return obj [ "edges" ]
def get_by ( self , prop , val , raise_exc = False ) : '''Retrieve an item from the dictionary with the given metadata properties . If there is no such item , None will be returned , if there are multiple such items , the first will be returned .'''
try : val = self . serialize ( val ) return self . _meta [ prop ] [ val ] [ 0 ] except ( KeyError , IndexError ) : if raise_exc : raise else : return None
def get_document ( self , document_id ) : """: param document _ id : Document unique identifier . : returns : a dictionary containing the document content and any associated metadata ."""
key = 'doc.%s.%s' % ( self . name , decode ( document_id ) ) return decode_dict ( self . db . hgetall ( key ) )
def load_setuptools_entrypoints ( self , group , name = None ) : """Load modules from querying the specified setuptools ` ` group ` ` . : param str group : entry point group to load plugins : param str name : if given , loads only plugins with the given ` ` name ` ` . : rtype : int : return : return the num...
from pkg_resources import ( iter_entry_points , DistributionNotFound , VersionConflict , ) count = 0 for ep in iter_entry_points ( group , name = name ) : # is the plugin registered or blocked ? if self . get_plugin ( ep . name ) or self . is_blocked ( ep . name ) : continue try : plugin = ep . ...
def subprocess_output ( command , raise_on_empty_output ) : """This is a stub to allow a check requiring ` Popen ` to run without an Agent ( e . g . during tests or development ) , it ' s not supposed to be used anywhere outside the ` datadog _ checks . utils ` package ."""
# Use tempfile , allowing a larger amount of memory . The subprocess . Popen # docs warn that the data read is buffered in memory . They suggest not to # use subprocess . PIPE if the data size is large or unlimited . with tempfile . TemporaryFile ( ) as stdout_f , tempfile . TemporaryFile ( ) as stderr_f : proc = s...
def main ( argv ) : """This function sets up a command - line option parser and then calls fetch _ and _ write _ mrca to do all of the real work ."""
import argparse description = 'Uses Open Tree of Life web services to the MRCA for a set of OTT IDs.' parser = argparse . ArgumentParser ( prog = 'ot-tree-of-life-mrca' , description = description ) parser . add_argument ( 'ottid' , nargs = '*' , type = int , help = 'OTT IDs' ) parser . add_argument ( '--subtree' , act...
def validate ( self , value ) : """Accepts : float , int , long , str , unicode Returns : float"""
if isinstance ( value , ( str , unicode , int , long ) ) : value = float ( value ) value = super ( Float , self ) . validate ( value ) if not isinstance ( value , ( float ) ) : raise ValueError ( "Not an float: %r" % ( value , ) ) return value
def delete ( self , ** options ) : """Permanently delete this blob from Blobstore . Args : * * options : Options for create _ rpc ( ) ."""
fut = delete_async ( self . key ( ) , ** options ) fut . get_result ( )
def adjust ( color , attribute , percent ) : """Adjust an attribute of color by a percent"""
r , g , b , a , type = parse_color ( color ) r , g , b = hsl_to_rgb ( * _adjust ( rgb_to_hsl ( r , g , b ) , attribute , percent ) ) return unparse_color ( r , g , b , a , type )
def git_clone ( target_dir , repo_location , branch_or_tag = None , verbose = True ) : """Clone repo at repo _ location to target _ dir and checkout branch _ or _ tag . If branch _ or _ tag is not specified , the HEAD of the primary branch of the cloned repo is checked out ."""
target_dir = pipes . quote ( target_dir ) command = [ 'git' , 'clone' ] if verbose : command . append ( '--verbose' ) if os . path . isdir ( repo_location ) : command . append ( '--no-hardlinks' ) command . extend ( [ pipes . quote ( repo_location ) , target_dir ] ) if branch_or_tag : command . extend ( [ '...
def replace_header ( self , header_text ) : """Replace pip - compile header with custom text"""
with open ( self . outfile , 'rt' ) as fp : _ , body = self . split_header ( fp ) with open ( self . outfile , 'wt' ) as fp : fp . write ( header_text ) fp . writelines ( body )
def parse_pgurl ( self , url ) : """Given a Postgres url , return a dict with keys for user , password , host , port , and database ."""
parsed = urlsplit ( url ) return { 'user' : parsed . username , 'password' : parsed . password , 'database' : parsed . path . lstrip ( '/' ) , 'host' : parsed . hostname , 'port' : parsed . port or 5432 , }
def get ( key , default = - 1 ) : """Backport support for original codes ."""
if isinstance ( key , int ) : return TransType ( key ) if key not in TransType . _member_map_ : extend_enum ( TransType , key , default ) return TransType [ key ]
def text_badness ( text ) : u'''Look for red flags that text is encoded incorrectly : Obvious problems : - The replacement character \ufffd , indicating a decoding error - Unassigned or private - use Unicode characters Very weird things : - Adjacent letters from two different scripts - Letters in script...
assert isinstance ( text , str ) errors = 0 very_weird_things = 0 weird_things = 0 prev_letter_script = None unicodedata_name = unicodedata . name unicodedata_category = unicodedata . category for char in text : index = ord ( char ) if index < 256 : # Deal quickly with the first 256 characters . weird_t...
def _handle_attribute ( self , start ) : """Handle a case where a tag attribute is at the head of the tokens ."""
name = quotes = None self . _push ( ) while self . _tokens : token = self . _tokens . pop ( ) if isinstance ( token , tokens . TagAttrEquals ) : name = self . _pop ( ) self . _push ( ) elif isinstance ( token , tokens . TagAttrQuote ) : quotes = token . char elif isinstance ( tok...
def process_service_check_result ( self , service , return_code , plugin_output ) : """Process service check result Format of the line that triggers function call : : PROCESS _ SERVICE _ CHECK _ RESULT ; < host _ name > ; < service _ description > ; < return _ code > ; < plugin _ output > : param service : se...
now = time . time ( ) cls = service . __class__ # If globally disabled OR service disabled , do not launch . . if not cls . accept_passive_checks or not service . passive_checks_enabled : return try : plugin_output = plugin_output . decode ( 'utf8' , 'ignore' ) logger . debug ( '%s > Passive service check p...
def slugs_configuration_camera_send ( self , target , idOrder , order , force_mavlink1 = False ) : '''Control for camara . target : The system setting the commands ( uint8 _ t ) idOrder : ID 0 : brightness 1 : aperture 2 : iris 3 : ICR 4 : backlight ( uint8 _ t ) order : 1 : up / on 2 : down / off 3 : auto / ...
return self . send ( self . slugs_configuration_camera_encode ( target , idOrder , order ) , force_mavlink1 = force_mavlink1 )
def _parse_seq_preheader ( line ) : """$ 3 = 227(209 ) :"""
match = re . match ( r"\$ (\d+) = (\d+) \( (\d+) \):" , line , re . VERBOSE ) if not match : raise ValueError ( "Unparseable header: " + line ) index , this_len , query_len = match . groups ( ) return map ( int , ( index , this_len , query_len ) )
def plot_predict ( self , h = 5 , past_values = 20 , intervals = True , ** kwargs ) : """Plots forecast with the estimated model Parameters h : int ( default : 5) How many steps ahead would you like to forecast ? past _ values : int ( default : 20) How many past observations to show on the forecast graph ...
import matplotlib . pyplot as plt import seaborn as sns figsize = kwargs . get ( 'figsize' , ( 10 , 7 ) ) if self . latent_variables . estimated is False : raise Exception ( "No latent variables estimated!" ) else : predictions , variance , lower , upper = self . _construct_predict ( self . latent_variables . g...
def enable_job ( name , ** kwargs ) : '''Enable a job in the minion ' s schedule CLI Example : . . code - block : : bash salt ' * ' schedule . enable _ job job1'''
ret = { 'comment' : [ ] , 'result' : True } if not name : ret [ 'comment' ] = 'Job name is required.' ret [ 'result' ] = False if 'test' in __opts__ and __opts__ [ 'test' ] : ret [ 'comment' ] = 'Job: {0} would be enabled in schedule.' . format ( name ) else : persist = True if 'persist' in kwargs :...
def get_context_from_gdoc ( self ) : """Wrap getting context from Google sheets in a simple caching mechanism ."""
try : start = int ( time . time ( ) ) if not self . data or start > self . expires : self . data = self . _get_context_from_gdoc ( self . project . SPREADSHEET_KEY ) end = int ( time . time ( ) ) ttl = getattr ( self . project , 'SPREADSHEET_CACHE_TTL' , SPREADSHEET_CACHE_TTL ) s...
def delete ( self , using = None ) : """Deletes the post instance ."""
if self . is_alone : # The default way of operating is to trigger the deletion of the associated topic # only if the considered post is the only post embedded in the topic self . topic . delete ( ) else : super ( AbstractPost , self ) . delete ( using ) self . topic . update_trackers ( )
def map_weights ( self ) : """Reshaped weights for visualization . The weights are reshaped as ( W . shape [ 0 ] , prod ( W . shape [ 1 : - 1 ] ) , W . shape [ 2 ] ) . This allows one to easily see patterns , even for hyper - dimensional soms . For one - dimensional SOMs , the returned array is of shape ...
first_dim = self . map_dimensions [ 0 ] if len ( self . map_dimensions ) != 1 : second_dim = np . prod ( self . map_dimensions [ 1 : ] ) else : second_dim = 1 # Reshape to appropriate dimensions return self . weights . reshape ( ( first_dim , second_dim , self . data_dimensionality ) )
def add_final_live ( self , print_progress = True , print_func = None ) : """* * A wrapper that executes the loop adding the final live points . * * Adds the final set of live points to the pre - existing sequence of dead points from the current nested sampling run . Parameters print _ progress : bool , opt...
# Initialize quantities / if print_func is None : print_func = print_fn # Add remaining live points to samples . ncall = self . ncall it = self . it - 1 for i , results in enumerate ( self . add_live_points ( ) ) : ( worst , ustar , vstar , loglstar , logvol , logwt , logz , logzvar , h , nc , worst_it , boundi...
def marksheet ( self ) : """Returns an pandas empty dataframe object containing rows and columns for marking . This can then be passed to a google doc that is distributed to markers for editing with the mark for each section ."""
columns = [ 'Number' , 'Question' , 'Correct (a fraction)' , 'Max Mark' , 'Comments' ] mark_sheet = pd . DataFrame ( ) for qu_number , question in enumerate ( self . answers ) : part_no = 0 for number , part in enumerate ( question ) : if number > 0 : if part [ 2 ] > 0 : part...
def remotes ( cwd , user = None , password = None , redact_auth = True , ignore_retcode = False , output_encoding = None ) : '''Get fetch and push URLs for each remote in a git checkout cwd The path to the git checkout user User under which to run the git command . By default , the command is run by the u...
cwd = _expand_path ( cwd , user ) command = [ 'git' , 'remote' , '--verbose' ] ret = { } output = _git_run ( command , cwd = cwd , user = user , password = password , ignore_retcode = ignore_retcode , output_encoding = output_encoding ) [ 'stdout' ] for remote_line in salt . utils . itertools . split ( output , '\n' ) ...
def train ( cls , data , lambda_ = 1.0 ) : """Train a Naive Bayes model given an RDD of ( label , features ) vectors . This is the Multinomial NB ( U { http : / / tinyurl . com / lsdw6p } ) which can handle all kinds of discrete data . For example , by converting documents into TF - IDF vectors , it can be ...
first = data . first ( ) if not isinstance ( first , LabeledPoint ) : raise ValueError ( "`data` should be an RDD of LabeledPoint" ) labels , pi , theta = callMLlibFunc ( "trainNaiveBayesModel" , data , lambda_ ) return NaiveBayesModel ( labels . toArray ( ) , pi . toArray ( ) , numpy . array ( theta ) )
def main ( ) : """Run all relevant aspects of ok . py ."""
args = parse_input ( ) log . setLevel ( logging . DEBUG if args . debug else logging . ERROR ) log . debug ( args ) # Checking user ' s Python bit version bit_v = ( 8 * struct . calcsize ( "P" ) ) log . debug ( "Python {} ({}bit)" . format ( sys . version , bit_v ) ) if args . version : print ( "okpy=={}" . format ...
def count_above ( errors , epsilon ) : """Count number of errors and continuous sequences above epsilon . Continuous sequences are counted by shifting and counting the number of positions where there was a change and the original value was true , which means that a sequence started at that position ."""
above = errors > epsilon total_above = len ( errors [ above ] ) above = pd . Series ( above ) shift = above . shift ( 1 ) change = above != shift total_consecutive = sum ( above & change ) return total_above , total_consecutive
def add_ppas_from_file ( file_name , update = True ) : """Add personal package archive from a file list ."""
for ppa in _read_lines_from_file ( file_name ) : add_ppa ( ppa , update = False ) if update : update_apt_sources ( )
def request ( self , command_string ) : """Request"""
self . send ( command_string ) if self . debug : print ( "Telnet Request: %s" % ( command_string ) ) while True : response = urllib . parse . unquote ( self . tn . read_until ( b"\n" ) . decode ( ) ) if "success" in response : # Normal successful reply break if "huh" in response : # Something w...
def check_and_update_resources ( num_cpus , num_gpus , resources ) : """Sanity check a resource dictionary and add sensible defaults . Args : num _ cpus : The number of CPUs . num _ gpus : The number of GPUs . resources : A dictionary mapping resource names to resource quantities . Returns : A new resou...
if resources is None : resources = { } resources = resources . copy ( ) assert "CPU" not in resources assert "GPU" not in resources if num_cpus is not None : resources [ "CPU" ] = num_cpus if num_gpus is not None : resources [ "GPU" ] = num_gpus if "CPU" not in resources : # By default , use the number of h...
def validate_layout_display ( self , table , display_condition ) : """Check to see if the display condition passes . Args : table ( str ) : The name of the DB table which hold the App data . display _ condition ( str ) : The " where " clause of the DB SQL statement . Returns : bool : True if the row count...
display = False if display_condition is None : display = True else : display_query = 'select count(*) from {} where {}' . format ( table , display_condition ) try : cur = self . db_conn . cursor ( ) cur . execute ( display_query . replace ( '"' , '' ) ) rows = cur . fetchall ( ) ...
def releaseInterface ( self ) : r"""Release an interface previously claimed with claimInterface ."""
util . release_interface ( self . dev , self . __claimed_interface ) self . __claimed_interface = - 1
def _listen ( self , uuid = None , session = None ) : """Listen a connection uuid"""
if self . url is None : raise Exception ( "NURESTPushCenter needs to have a valid URL. please use setURL: before starting it." ) events_url = "%s/events" % self . url if uuid : events_url = "%s?uuid=%s" % ( events_url , uuid ) request = NURESTRequest ( method = 'GET' , url = events_url ) # Force async to False ...
def count_tokens ( tokens , to_lower = False , counter = None ) : r"""Counts tokens in the specified string . For token _ delim = ' ( td ) ' and seq _ delim = ' ( sd ) ' , a specified string of two sequences of tokens may look like : : ( td ) token1 ( td ) token2 ( td ) token3 ( td ) ( sd ) ( td ) token4 ( td...
if to_lower : tokens = [ t . lower ( ) for t in tokens ] if counter is None : return Counter ( tokens ) else : counter . update ( tokens ) return counter
def get_rendition_url ( self , width = 0 , height = 0 ) : '''get the rendition URL for a specified size if the renditions does not exists it will be created'''
if width == 0 and height == 0 : return self . get_master_url ( ) target_width , target_height = self . get_rendition_size ( width , height ) key = '%sx%s' % ( target_width , target_height ) if not self . renditions : self . renditions = { } rendition_name = self . renditions . get ( key , False ) if not renditi...
def sharded_cluster_link ( rel , cluster_id = None , shard_id = None , router_id = None , self_rel = False ) : """Helper for getting a ShardedCluster link document , given a rel ."""
clusters_href = '/v1/sharded_clusters' link = _SHARDED_CLUSTER_LINKS [ rel ] . copy ( ) link [ 'href' ] = link [ 'href' ] . format ( ** locals ( ) ) link [ 'rel' ] = 'self' if self_rel else rel return link
def toggle_quick_open_command_line_sensitivity ( self , chk ) : """When the user unchecks ' enable quick open ' , the command line should be disabled"""
self . get_widget ( 'quick_open_command_line' ) . set_sensitive ( chk . get_active ( ) ) self . get_widget ( 'quick_open_in_current_terminal' ) . set_sensitive ( chk . get_active ( ) )
def get_user_policy ( self , user_name , policy_name ) : """Retrieves the specified policy document for the specified user . : type user _ name : string : param user _ name : The name of the user the policy is associated with . : type policy _ name : string : param policy _ name : The policy document to get...
params = { 'UserName' : user_name , 'PolicyName' : policy_name } return self . get_response ( 'GetUserPolicy' , params , verb = 'POST' )
def get_neighbourhood ( self , force , id , ** attrs ) : """Get a specific neighbourhood . Uses the neighbourhood _ API call . . . _ neighbourhood : https : / / data . police . uk / docs / method / neighbourhood / : param force : The force within which the neighbourhood resides ( either by ID or : class : ` f...
if not isinstance ( force , Force ) : force = Force ( self , id = force , ** attrs ) return Neighbourhood ( self , force = force , id = id , ** attrs )
def run_server ( cls , args = None , ** kwargs ) : """Run the class as a device server . It is based on the tango . server . run method . The difference is that the device class and server name are automatically given . Args : args ( iterable ) : args as given in the tango . server . run method without ...
if args is None : args = sys . argv [ 1 : ] args = [ cls . __name__ ] + list ( args ) green_mode = getattr ( cls , 'green_mode' , None ) kwargs . setdefault ( "green_mode" , green_mode ) return run ( ( cls , ) , args , ** kwargs )
def get_local_config_file ( cls , filename ) : """Find local file to setup default values . There is a pre - fixed logic on how the search of the configuration file is performed . If the highes priority configuration file is found , there is no need to search for the next . From highest to lowest priority :...
if os . path . isfile ( filename ) : # Local has priority return filename else : try : # Project . If not in a git repo , this will not exist . config_repo = _get_repo ( ) if len ( config_repo ) == 0 : raise Exception ( ) config_repo = os . path . join ( config_repo , filenam...
def encode_to_py3bytes_or_py2str ( s ) : """takes anything and attempts to return a py2 string or py3 bytes . this is typically used when creating command + arguments to be executed via os . exec *"""
fallback_encoding = "utf8" if IS_PY3 : # if we ' re already bytes , do nothing if isinstance ( s , bytes ) : pass else : s = str ( s ) try : s = bytes ( s , DEFAULT_ENCODING ) except UnicodeEncodeError : s = bytes ( s , fallback_encoding ) else : # attempt...
def Page_searchInResource ( self , frameId , url , query , ** kwargs ) : """Function path : Page . searchInResource Domain : Page Method name : searchInResource WARNING : This function is marked ' Experimental ' ! Parameters : Required arguments : ' frameId ' ( type : FrameId ) - > Frame id for resource...
assert isinstance ( url , ( str , ) ) , "Argument 'url' must be of type '['str']'. Received type: '%s'" % type ( url ) assert isinstance ( query , ( str , ) ) , "Argument 'query' must be of type '['str']'. Received type: '%s'" % type ( query ) if 'caseSensitive' in kwargs : assert isinstance ( kwargs [ 'caseSensiti...
def refresh ( self ) : """Refreshes the status information ."""
if self . status == 'executing' and self . array : new_result = 0 for array_job in self . array : if array_job . status == 'failure' and new_result is not None : new_result = array_job . result elif array_job . status not in ( 'success' , 'failure' ) : new_result = None ...
def angle2d ( self ) : """determine the angle of this point on a circle , measured in radians ( presume values represent a Vector )"""
if self . x == 0 : if self . y < 0 : return math . pi / 2.0 * 3 elif self . y > 0 : return math . pi / 2.0 else : return 0 elif self . y == 0 : if self . x < 0 : return math . pi # elif self . x > 0 : return 0 else : return 0 ans = math . atan ( self . y /...
def fieldAlphaHistogram ( self , name , q = '*:*' , fq = None , nbins = 10 , includequeries = True ) : """Generates a histogram of values from a string field . Output is : [ [ low , high , count , query ] , . . . ] Bin edges is determined by equal division of the fields"""
oldpersist = self . persistent self . persistent = True bins = [ ] qbin = [ ] fvals = [ ] try : # get total number of values for the field # TODO : this is a slow mechanism to retrieve the number of distinct values # Need to replace this with something more efficient . # # Can probably replace with a range of alpha cha...
def rollback ( self ) : """Ignore all changes made in the latest session ( terminate the session ) ."""
if self . session is not None : logger . info ( "rolling back transaction in %s" % self ) self . session . close ( ) self . session = None self . lock_update . release ( ) else : logger . warning ( "rollback called but there's no open session in %s" % self )
def transform_locus ( region , window_center , window_size ) : """transform an input genomic region into one suitable for the profile . : param region : input region to transform . : param window _ center : which part of the input region to center on . : param window _ size : how large the resultant region sh...
if window_center == CENTRE : region . transform_center ( window_size ) else : raise ValueError ( "Don't know how to do this transformation: " + window_center )
def _write_pickle ( filepath , data , kwargs ) : """See documentation of mpu . io . write ."""
if 'protocol' not in kwargs : kwargs [ 'protocol' ] = pickle . HIGHEST_PROTOCOL with open ( filepath , 'wb' ) as handle : pickle . dump ( data , handle , ** kwargs ) return data
def make_serviceitem_description ( description , condition = 'contains' , negate = False , preserve_case = False ) : """Create a node for ServiceItem / description : return : A IndicatorItem represented as an Element node"""
document = 'ServiceItem' search = 'ServiceItem/description' content_type = 'string' content = description ii_node = ioc_api . make_indicatoritem_node ( condition , document , search , content_type , content , negate = negate , preserve_case = preserve_case ) return ii_node
def pretty_print_model ( devicemodel ) : """Prints out a device model in the terminal by parsing dict ."""
PRETTY_PRINT_MODEL = """Device Model ID: %(deviceModelId)s Project ID: %(projectId)s Device Type: %(deviceType)s""" logging . info ( PRETTY_PRINT_MODEL % devicemodel ) if 'traits' in devicemodel : for trait in devicemodel [ 'traits' ] : logging . info ( ' Trait %s' % trait ) else : ...
def add_comment ( self , text ) : """Comment on the submission using the specified text . : returns : A Comment object for the newly created comment ."""
# pylint : disable = W0212 response = self . reddit_session . _add_comment ( self . fullname , text ) # pylint : enable = W0212 self . reddit_session . evict ( self . _api_link ) # pylint : disable = W0212 return response
def update_agent_pool ( self , pool , pool_id ) : """UpdateAgentPool . [ Preview API ] Update properties on an agent pool : param : class : ` < TaskAgentPool > < azure . devops . v5_1 . task _ agent . models . TaskAgentPool > ` pool : Updated agent pool details : param int pool _ id : The agent pool to update...
route_values = { } if pool_id is not None : route_values [ 'poolId' ] = self . _serialize . url ( 'pool_id' , pool_id , 'int' ) content = self . _serialize . body ( pool , 'TaskAgentPool' ) response = self . _send ( http_method = 'PATCH' , location_id = 'a8c47e17-4d56-4a56-92bb-de7ea7dc65be' , version = '5.1-previe...
def get_reviews_summary ( self , pub_name , ext_name , before_date = None , after_date = None ) : """GetReviewsSummary . [ Preview API ] Returns a summary of the reviews : param str pub _ name : Name of the publisher who published the extension : param str ext _ name : Name of the extension : param datetime...
route_values = { } if pub_name is not None : route_values [ 'pubName' ] = self . _serialize . url ( 'pub_name' , pub_name , 'str' ) if ext_name is not None : route_values [ 'extName' ] = self . _serialize . url ( 'ext_name' , ext_name , 'str' ) query_parameters = { } if before_date is not None : query_param...
def RemoveMethod ( self , function ) : """Removes the specified function ' s MethodWrapper from the added _ methods list , so we don ' t re - bind it when making a clone ."""
self . added_methods = [ dm for dm in self . added_methods if not dm . method is function ]
def setup_suspend ( self ) : """Setup debugger to " suspend " execution"""
self . frame_calling = None self . frame_stop = None self . frame_return = None self . frame_suspend = True self . pending_stop = True self . enable_tracing ( ) return
def transform_sequence ( f ) : """A decorator to take a function operating on a point and turn it into a function returning a callable operating on a sequence . The functions passed to this decorator must define a kwarg called " point " , or have point be the last positional argument"""
@ wraps ( f ) def wrapper ( * args , ** kwargs ) : # The arguments here are the arguments passed to the transform , # ie , there will be no " point " argument # Send a function to seq . map _ points with all of its arguments applied except # point return lambda seq : seq . map_points ( partial ( f , * args , ** kwa...
def calculate_acl ( data , m = 5 , dtype = int ) : r"""Calculates the autocorrelation length ( ACL ) . Given a normalized autocorrelation function : math : ` \ rho [ i ] ` ( by normalized , we mean that : math : ` \ rho [ 0 ] = 1 ` ) , the ACL : math : ` \ tau ` is : . . math : : \ tau = 1 + 2 \ sum _ { i =...
# sanity check output data type if dtype not in [ int , float ] : raise ValueError ( "The dtype must be either int or float." ) # if we have only a single point , just return 1 if len ( data ) < 2 : return 1 # calculate ACF that is normalized by the zero - lag value acf = calculate_acf ( data ) cacf = 2 * acf ....
def search ( self , ** kwargs ) : """Method to search equipments based on extends search . : param search : Dict containing QuerySets to find equipments . : param include : Array containing fields to include on response . : param exclude : Array containing fields to exclude on response . : param fields : Ar...
return super ( ApiEquipment , self ) . get ( self . prepare_url ( 'api/v3/equipment/' , kwargs ) )
def get_custom_implementations ( self ) : """Retrieve a list of cutom implementations . Yields : ( str , str , ImplementationProperty ) tuples : The name of the attribute an implementation lives at , the name of the related transition , and the related implementation ."""
for trname in self . custom_implems : attr = self . transitions_at [ trname ] implem = self . implementations [ trname ] yield ( trname , attr , implem )
def _add_deflection ( position , observer , deflector , rmass ) : """Correct a position vector for how one particular mass deflects light . Given the ICRS ` position ` [ x , y , z ] of an object ( AU ) together with the positions of an ` observer ` and a ` deflector ` of reciprocal mass ` rmass ` , this funct...
# Construct vector ' pq ' from gravitating body to observed object and # construct vector ' pe ' from gravitating body to observer . pq = observer + position - deflector pe = observer - deflector # Compute vector magnitudes and unit vectors . pmag = length_of ( position ) qmag = length_of ( pq ) emag = length_of ( pe )...
def create_ondemand_streaming_locator ( access_token , encoded_asset_id , pid , starttime = None ) : '''Create Media Service OnDemand Streaming Locator . Args : access _ token ( str ) : A valid Azure authentication token . encoded _ asset _ id ( str ) : A Media Service Encoded Asset ID . pid ( str ) : A Med...
path = '/Locators' endpoint = '' . join ( [ ams_rest_endpoint , path ] ) if starttime is None : body = '{ \ "AccessPolicyId":"' + pid + '", \ "AssetId":"' + encoded_asset_id + '", \ "Type": "2" \ }' else : body = '{ \ "AccessPolicyId":"' + pid + '", \ "AssetId":"' + encoded_asset_id + '", \ ...
def _fill_request ( self , request , rdata ) : """Fills request with data from the jsonrpc call ."""
if not isinstance ( rdata , dict ) : raise InvalidRequestError request [ 'jsonrpc' ] = self . _get_jsonrpc ( rdata ) request [ 'id' ] = self . _get_id ( rdata ) request [ 'method' ] = self . _get_method ( rdata ) request [ 'params' ] = self . _get_params ( rdata )
def last_kstp_from_kper ( hds , kper ) : """function to find the last time step ( kstp ) for a give stress period ( kper ) in a modflow head save file . Parameters hds : flopy . utils . HeadFile kper : int the zero - index stress period number Returns kstp : int the zero - based last time step durin...
# find the last kstp with this kper kstp = - 1 for kkstp , kkper in hds . kstpkper : if kkper == kper + 1 and kkstp > kstp : kstp = kkstp if kstp == - 1 : raise Exception ( "kstp not found for kper {0}" . format ( kper ) ) kstp -= 1 return kstp