signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def nearest_loc_forecast ( self , lat , lon , step ) : """Work out nearest possible site to lat & lon coordinates and return its forecast data for the given time step . lat : float or int . Latitude . lon : float or int . Longitude . step : metoffer . DAILY Returns daily forecasts metoffer . THREE _ HOU...
sitelist = self . loc_forecast ( SITELIST , step ) sites = parse_sitelist ( sitelist ) site = get_nearest_site ( sites , lat , lon ) return self . loc_forecast ( site , step )
def topng ( images , path , prefix = "image" , overwrite = False , credentials = None ) : """Write out PNG files for 2d image data . See also thunder . data . images . topng"""
value_shape = images . value_shape if not len ( value_shape ) in [ 2 , 3 ] : raise ValueError ( "Only 2D or 3D images can be exported to png, " "images are %d-dimensional." % len ( value_shape ) ) from scipy . misc import imsave from io import BytesIO from thunder . writers import get_parallel_writer def tobuffer (...
def get_urls_from_onetab ( onetab ) : """Get video urls from a link to the onetab shared page . Args : onetab ( str ) : Link to a onetab shared page . Returns : list : List of links to the videos ."""
html = requests . get ( onetab ) . text soup = BeautifulSoup ( html , 'lxml' ) divs = soup . findAll ( 'div' , { 'style' : 'padding-left: 24px; ' 'padding-top: 8px; ' 'position: relative; ' 'font-size: 13px;' } ) return [ div . find ( 'a' ) . attrs [ 'href' ] for div in divs ]
def _make_request ( self , path , method = 'GET' , params_ = None ) : """Make a request to the API"""
uri = self . api_root + path if params_ : params_ [ 'text_format' ] = self . response_format else : params_ = { 'text_format' : self . response_format } # Make the request response = None try : response = self . _session . request ( method , uri , timeout = self . timeout , params = params_ ) except Timeout...
def pstdev ( data ) : """Calculates the population standard deviation ."""
# : http : / / stackoverflow . com / a / 27758326 n = len ( data ) if n < 2 : raise ValueError ( 'variance requires at least two data points' ) ss = _ss ( data ) pvar = ss / n # the population variance return pvar ** 0.5
def gps_velocity_old ( GPS_RAW_INT ) : '''return GPS velocity vector'''
return Vector3 ( GPS_RAW_INT . vel * 0.01 * cos ( radians ( GPS_RAW_INT . cog * 0.01 ) ) , GPS_RAW_INT . vel * 0.01 * sin ( radians ( GPS_RAW_INT . cog * 0.01 ) ) , 0 )
def isASLREnabled ( self ) : """Determines if the current L { PE } instance has the DYNAMICBASE ( Use address space layout randomization ) flag enabled . @ see : U { http : / / msdn . microsoft . com / en - us / library / bb384887 . aspx } @ rtype : bool @ return : Returns C { True } if the current L { PE } i...
return self . ntHeaders . optionalHeader . dllCharacteristics . value & consts . IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE == consts . IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE
def get_xref_graph ( ont ) : """Creates a basic graph object corresponding to a remote ontology"""
g = networkx . MultiGraph ( ) for ( c , x ) in fetchall_xrefs ( ont ) : g . add_edge ( c , x , source = c ) return g
def total ( usaf , field = 'GHI (W/m^2)' ) : """total annual insolation , defaults to GHI ."""
running_total = 0 usafdata = data ( usaf ) for record in usafdata : running_total += float ( record [ field ] ) return running_total / 1000.
def get_class_name_from_frame ( fr : FrameType ) -> Optional [ str ] : """A frame contains information about a specific call in the Python call stack ; see https : / / docs . python . org / 3 / library / inspect . html . If the call was to a member function of a class , this function attempts to read the clas...
# http : / / stackoverflow . com / questions / 2203424 / python - how - to - retrieve - class - information - from - a - frame - object # noqa args , _ , _ , value_dict = inspect . getargvalues ( fr ) # we check the first parameter for the frame function is named ' self ' if len ( args ) and args [ 0 ] == 'self' : # in...
def message ( self ) : """The message contents"""
if self . type == 'cleartext' : return self . bytes_to_text ( self . _message ) if self . type == 'literal' : return self . _message . contents if self . type == 'encrypted' : return self . _message
def open_fake_page ( self , page_text , url = None , soup_config = None ) : """Mock version of : func : ` open ` . Behave as if opening a page whose text is ` ` page _ text ` ` , but do not perform any network access . If ` ` url ` ` is set , pretend it is the page ' s URL . Useful mainly for testing ."""
soup_config = soup_config or self . soup_config self . __state = _BrowserState ( page = bs4 . BeautifulSoup ( page_text , ** soup_config ) , url = url )
def keys_at ( self , x ) : """Return a list of the keys for the segment lists that contain x . Example : > > > x = segmentlistdict ( ) > > > x [ " H1 " ] = segmentlist ( [ segment ( 0 , 10 ) ] ) > > > x [ " H2 " ] = segmentlist ( [ segment ( 5 , 15 ) ] ) > > > x . keys _ at ( 12) [ ' H2 ' ]"""
return [ key for key , segs in self . items ( ) if x in segs ]
def _all_reachable_tables ( t ) : """A generator that provides all the names of tables that can be reached via merges starting at the given target table ."""
for k , v in t . items ( ) : for tname in _all_reachable_tables ( v ) : yield tname yield k
def install_scripts ( distributions ) : """Regenerate the entry _ points console _ scripts for the named distribution ."""
try : if "__PEX_UNVENDORED__" in __import__ ( "os" ) . environ : from setuptools . command import easy_install # vendor : skip else : from pex . third_party . setuptools . command import easy_install if "__PEX_UNVENDORED__" in __import__ ( "os" ) . environ : import pkg_resour...
def temporary_object_path ( self , name ) : """Returns the path to a temporary object , before we know its hash ."""
return os . path . join ( self . _path , self . TMP_OBJ_DIR , name )
def find_object ( self , object_type ) : """Finds the closest object of a given type ."""
node = self while node is not None : if isinstance ( node . obj , object_type ) : return node . obj node = node . parent
def parse_negation_operation ( operation : str ) -> Tuple [ bool , str ] : """Parse the negation modifier in an operation ."""
_operation = operation . strip ( ) if not _operation : raise QueryParserException ( 'Operation is not valid: {}' . format ( operation ) ) negation = False if _operation [ 0 ] == '~' : negation = True _operation = _operation [ 1 : ] return negation , _operation . strip ( )
def pprint ( self , file_ = sys . stdout ) : """Print the code block to stdout . Does syntax highlighting if possible ."""
code = [ ] if self . _deps : code . append ( "# dependencies:" ) for k , v in _compat . iteritems ( self . _deps ) : code . append ( "# %s: %r" % ( k , v ) ) code . append ( str ( self ) ) code = "\n" . join ( code ) if file_ . isatty ( ) : try : from pygments import highlight from pygment...
def matvec ( a , b , compression = False ) : """Matrix - vector product in TT format ."""
acrs = _vector . vector . to_list ( a . tt ) bcrs = _vector . vector . to_list ( b ) ccrs = [ ] d = b . d def get_core ( i ) : acr = _np . reshape ( acrs [ i ] , ( a . tt . r [ i ] , a . n [ i ] , a . m [ i ] , a . tt . r [ i + 1 ] ) , order = 'F' ) acr = acr . transpose ( [ 3 , 0 , 1 , 2 ] ) # a ( R _ { i ...
def getExperiments ( uuid : str ) : """list active ( running or completed ) experiments"""
return jsonify ( [ x . deserialize ( ) for x in Experiment . query . all ( ) ] )
def _get_tau ( self , C , mag ) : """Returns magnitude dependent inter - event standard deviation ( tau ) ( equation 14)"""
if mag < 6.5 : return C [ "tau1" ] elif mag < 7. : return C [ "tau1" ] + ( C [ "tau2" ] - C [ "tau1" ] ) * ( ( mag - 6.5 ) / 0.5 ) else : return C [ "tau2" ]
def log_est_complete ( est_complete ) : """Log the relative time remaining for this est _ complete datetime object ."""
if not est_complete : print ( 'could not determine an estimated completion time' ) return remaining = est_complete - datetime . utcnow ( ) message = 'this task should be complete in %s' if remaining . total_seconds ( ) < 0 : message = 'this task exceeds estimate by %s' log_delta ( message , remaining )
def backward ( self , diff_x , influences , activations , ** kwargs ) : """Backward pass through the network , including update . Parameters diff _ x : numpy array A matrix containing the differences between the input and neurons . influences : numpy array A matrix containing the influence each neuron has...
diff_y = kwargs [ 'diff_y' ] bmu = self . _get_bmu ( activations ) influence = influences [ bmu ] # Update x_update = np . multiply ( diff_x , influence ) y_update = np . multiply ( diff_y , influence ) return x_update , y_update
def rmtree_or_file ( path , ignore_errors = False , onerror = None ) : """rmtree fails on files or symlinks . This removes the target , whatever it is ."""
# TODO : Could add an rsync - based delete , as in # https : / / github . com / vivlabs / instaclone / blob / master / instaclone / instaclone . py # L127 - L143 if ignore_errors and not os . path . exists ( path ) : return if os . path . isdir ( path ) and not os . path . islink ( path ) : shutil . rmtree ( pa...
def Publish ( self , request , context ) : """Dispatches the request to the plugins publish method"""
LOG . debug ( "Publish called" ) try : self . plugin . publish ( [ Metric ( pb = m ) for m in request . Metrics ] , ConfigMap ( pb = request . Config ) ) return ErrReply ( ) except Exception as err : msg = "message: {}\n\nstack trace: {}" . format ( err , traceback . format_exc ( ) ) return ErrReply ( e...
def lksprob ( alam ) : """Computes a Kolmolgorov - Smirnov t - test significance level . Adapted from Numerical Recipies . Usage : lksprob ( alam )"""
fac = 2.0 sum = 0.0 termbf = 0.0 a2 = - 2.0 * alam * alam for j in range ( 1 , 201 ) : term = fac * math . exp ( a2 * j * j ) sum = sum + term if math . fabs ( term ) <= ( 0.001 * termbf ) or math . fabs ( term ) < ( 1.0e-8 * sum ) : return sum fac = - fac termbf = math . fabs ( term ) retur...
def members ( self , uid = "*" , objects = False ) : """members ( ) issues an ldap query for all users , and returns a dict for each matching entry . This can be quite slow , and takes roughly 3s to complete . You may optionally restrict the scope by specifying a uid , which is roughly equivalent to a search ...
entries = self . search ( uid = '*' ) if objects : return self . memberObjects ( entries ) result = [ ] for entry in entries : result . append ( entry [ 1 ] ) return result
def NEW_DEBUG_FRAME ( self , requestHeader ) : """Initialize a debug frame with requestHeader Frame count is updated and will be attached to respond header The structure of a frame : [ requestHeader , statusCode , responseHeader , raw _ data ] Some of them may be None"""
if self . DEBUG_FLAG : # pragma no branch ( Flag always set in tests ) new_frame = [ requestHeader , None , None , None ] if self . _frameCount < self . DEBUG_FRAME_BUFFER_SIZE - 1 : # pragma no branch ( Should be covered ) self . _frameBuffer . append ( new_frame ) else : self . _frameBuffe...
def main ( ) : """Main"""
bands = OLI_BAND_NAMES . values ( ) bands . sort ( ) for platform_name in [ 'Landsat-8' , ] : tohdf5 ( OliRSR , platform_name , bands )
def _has_tag ( version , debug = False ) : """Determine a version is a local git tag name or not . : param version : A string containing the branch / tag / sha to be determined . : param debug : An optional bool to toggle debug output . : return : bool"""
cmd = sh . git . bake ( 'show-ref' , '--verify' , '--quiet' , "refs/tags/{}" . format ( version ) ) try : util . run_command ( cmd , debug = debug ) return True except sh . ErrorReturnCode : return False
def set_element_focus ( self , locator ) : """Sets focus on the element identified by ` locator ` . Should be used with elements meant to have focus only , such as text fields . This keywords also waits for the focus to be active by calling the ` Wait Until Element Has Focus ` keyword . | * Argument * | * D...
self . _info ( "Setting focus on element '%s'" % ( locator ) ) element = self . _element_find ( locator , True , True ) element . send_keys ( Keys . NULL ) self . _wait_until_no_error ( None , self . _check_element_focus , True , locator )
def mass_3d ( self , r , rho0 , gamma ) : """mass enclosed a 3d sphere or radius r : param r : : param a : : param s : : return :"""
mass_3d = 4 * np . pi * rho0 / ( - gamma + 3 ) * r ** ( - gamma + 3 ) return mass_3d
def generate_ucsm_handle ( hostname , username , password ) : """Creates UCS Manager handle object and establishes a session with UCS Manager . : param hostname : UCS Manager hostname or IP - address : param username : Username to login to UCS Manager : param password : Login user password : raises UcsCon...
ucs_handle = UcsHandle ( ) try : success = ucs_handle . Login ( hostname , username , password ) except UcsException as e : print ( "Cisco client exception %(msg)s" % ( e . message ) ) raise exception . UcsConnectionError ( message = e . message ) return success , ucs_handle
def save_direction ( self , rootpath , raw = False , as_int = False ) : """Saves the direction of the slope to a file"""
self . save_array ( self . direction , None , 'ang' , rootpath , raw , as_int = as_int )
def rank_dict ( dict , key = lambda t : t [ 1 ] , as_tuple = False ) : """Sorts a # dict by a given key , optionally returning it as a # tuple . By default , the @ dict is sorted by it ' s value . @ dict : the # dict you wish to sorts @ key : the # sorted key to use @ as _ tuple : returns result as a # tupl...
sorted_list = sorted ( dict . items ( ) , key = key ) return OrderedDict ( sorted_list ) if not as_tuple else tuple ( sorted_list )
def gen ( sc , asset , expire ) : '''Database population function . What we are doing here is trying to interpret the output of plugin ID 20811 and use that information to help populate the database with individualized entries of the software that is installed on the host . This information will later be us...
# The following regex patters are used to pull out the needed fields from # Plugin ID 20811 redate = re . compile ( r'\[installed on (\d{4})/(\d{1,2})/(\d{1,2})\]' ) reinvdate = re . compile ( r'\[installed on (\d{1,2})/(\d{1,2})/(\d{4})\]' ) rever = re . compile ( r'\[version (.*?)\]' ) resw = re . compile ( r'^([\w\s...
def ip_to_int ( ip ) : '''Converts an IP address to an integer'''
ret = 0 for octet in ip . split ( '.' ) : ret = ret * 256 + int ( octet ) return ret
def deactivate_mfa_device ( self , user_name , serial_number ) : """Deactivates the specified MFA device and removes it from association with the user . : type user _ name : string : param user _ name : The username of the user : type serial _ number : string : param seriasl _ number : The serial number w...
params = { 'UserName' : user_name , 'SerialNumber' : serial_number } return self . get_response ( 'DeactivateMFADevice' , params )
def compile_python_files ( self , dir ) : '''Compile the python files ( recursively ) for the python files inside a given folder . . . note : : python2 compiles the files into extension . pyo , but in python3 , and as of Python 3.5 , the . pyo filename extension is no longer used . . . uses . pyc ( https : ...
args = [ self . ctx . hostpython ] if self . ctx . python_recipe . name == 'python3' : args += [ '-OO' , '-m' , 'compileall' , '-b' , '-f' , dir ] else : args += [ '-OO' , '-m' , 'compileall' , '-f' , dir ] subprocess . call ( args )
def append ( self , text : str ) : """Undo safe wrapper for the native ` ` append ` ` method . | Args | * ` ` text ` ` ( * * str * * ) : text to insert at the specified position . | Returns | * * None * * | Raises | * * * QtmacsArgumentError * * if at least one argument has an invalid type ."""
pos = self . getCursorPosition ( ) line , col = self . getNumLinesAndColumns ( ) undoObj = UndoInsertAt ( self , text , line , col ) self . qteUndoStack . push ( undoObj ) self . setCursorPosition ( * pos )
def _child ( details ) : """Child A private function to figure out the child node type Arguments : details { dict } - - A dictionary describing a data point Returns : _ NodeInterface"""
# If the details are a list if isinstance ( details , list ) : # Create a list of options for the key return OptionsNode ( details ) # Else if we got a dictionary elif isinstance ( details , dict ) : # If array is present if '__array__' in details : return ArrayNode ( details ) # Else if we have a h...
def add_named_metadata ( self , name , element = None ) : """Add a named metadata node to the module , if it doesn ' t exist , or return the existing node . If * element * is given , it will append a new element to the named metadata node . If * element * is a sequence of values ( rather than a metadata val...
if name in self . namedmetadata : nmd = self . namedmetadata [ name ] else : nmd = self . namedmetadata [ name ] = values . NamedMetaData ( self ) if element is not None : if not isinstance ( element , values . Value ) : element = self . add_metadata ( element ) if not isinstance ( element . typ...
def _write_file_network ( data , filename ) : '''Writes a file to disk'''
with salt . utils . files . fopen ( filename , 'w' ) as fp_ : fp_ . write ( salt . utils . stringutils . to_str ( data ) )
def get_matches ( self , word ) : """Get a list of filenames with match * word * ."""
matches = self . gen_matches ( word ) # defend this against bad user input for regular expression patterns try : matches = self . exclude_matches ( matches ) except Exception : sys . stderr . write ( traceback . format_exc ( ) ) return None else : if self . use_suffix : matches = [ self . inflec...
def sign_file ( self , message_file , key_id = None , passphrase = None , clearsign = True , detach = False , binary = False ) : '''Make a signature . : param message _ file : File - like object for sign : param key _ id : Key for signing , default will be used if null : param passphrase : Key password : pa...
args = [ '-s' if binary else '-sa' ] if detach : args . append ( '--detach-sign' ) if clearsign : args . append ( '--clearsign' ) if key_id : # args + = ( ' - - default - key ' , key _ id ) args += ( '--local-user' , key_id ) return self . execute ( SignResult ( ) , args , passphrase , message_file , True )
def equirectangular_distance ( self , other ) : """Return the approximate equirectangular when the location is close to the center of the cluster . For small distances , Pythagoras ’ theorem can be used on an equirectangular projection . Equirectangular formula : : x = Δλ ⋅ cos φm y = Δφ d = R ⋅ √ ( x...
x = math . radians ( other . longitude - self . longitude ) * math . cos ( math . radians ( other . latitude + self . latitude ) / 2 ) ; y = math . radians ( other . latitude - self . latitude ) ; return math . sqrt ( x * x + y * y ) * GeoPoint . EARTH_RADIUS_METERS ;
def commit ( self , timeout = None , metadata = None , credentials = None ) : """Commits the transaction ."""
if not self . _common_commit ( ) : return new_metadata = self . _dg . add_login_metadata ( metadata ) try : self . _dc . commit_or_abort ( self . _ctx , timeout = timeout , metadata = new_metadata , credentials = credentials ) except Exception as error : if util . is_jwt_expired ( error ) : self . _...
def are_ilx ( self , ilx_ids ) : '''Checks list of objects to see if they are usable ILX IDs'''
total_data = [ ] for ilx_id in ilx_ids : ilx_id = ilx_id . replace ( 'http' , '' ) . replace ( '.' , '' ) . replace ( '/' , '' ) data , success = self . get_data_from_ilx ( ilx_id ) if success : total_data . append ( data [ 'data' ] ) else : total_data . append ( { } ) return total_data
def register_route_command ( self , command , title = None , group = None ) : '''Register route command . Add route plugin command to context menu .'''
commands = self . route_commands . setdefault ( group , OrderedDict ( ) ) if title is None : title = ( command [ : 1 ] . upper ( ) + command [ 1 : ] ) . replace ( '_' , ' ' ) commands [ command ] = title
def report ( self , item_id , report_format = "json" ) : """Retrieves the specified report for the analyzed item , referenced by item _ id . Available formats include : json . : type item _ id : str : param item _ id : File ID number : type report _ format : str : param report _ format : Return format :...
if report_format == "html" : return "Report Unavailable" # else we try JSON response = self . _request ( "/submissions/results/{file_id}?info_level=extended" . format ( file_id = item_id ) ) # if response is JSON , return it as an object try : return response . json ( ) except ValueError : pass # otherwise ...
def uncheck_all ( self , name ) : """Remove the * checked * - attribute of all input elements with a * name * - attribute given by ` ` name ` ` ."""
for option in self . form . find_all ( "input" , { "name" : name } ) : if "checked" in option . attrs : del option . attrs [ "checked" ]
def measure ( self ) -> np . ndarray : """Measure the state in the computational basis . Returns : A [ 2 ] * bits array of qubit states , either 0 or 1"""
# TODO : Can we do this within backend ? probs = np . real ( bk . evaluate ( self . probabilities ( ) ) ) indices = np . asarray ( list ( np . ndindex ( * [ 2 ] * self . qubit_nb ) ) ) res = np . random . choice ( probs . size , p = probs . ravel ( ) ) res = indices [ res ] return res
def _save ( self , data ) : """Take the data from a dict and commit them to appropriate attributes ."""
self . name = data . get ( 'name' ) self . type = data . get ( 'type' ) self . state = data . get ( 'state' ) self . dataset = data . get ( 'dataset' ) self . memory = data . get ( 'memory' ) self . disk = data . get ( 'disk' ) self . _ips = data . get ( 'ips' , [ ] ) self . metadata = data . get ( 'metadata' , { } ) i...
def get_root_gradebooks ( self ) : """Gets the root gradebooks in this gradebook hierarchy . return : ( osid . grading . GradebookList ) - the root gradebooks raise : OperationFailed - unable to complete request raise : PermissionDenied - authorization failure * compliance : mandatory - - This method is mus...
# Implemented from template for # osid . resource . BinHierarchySession . get _ root _ bins if self . _catalog_session is not None : return self . _catalog_session . get_root_catalogs ( ) return GradebookLookupSession ( self . _proxy , self . _runtime ) . get_gradebooks_by_ids ( list ( self . get_root_gradebook_ids...
def _log_request ( self , request ) : """Log the most important parts of this request . : param request : Object representing the current request . : type request : : class : ` webob . Request `"""
msg = [ ] for d in self . LOG_DATA : val = getattr ( request , d ) if val : msg . append ( d + ': ' + repr ( val ) ) for d in self . LOG_HEADERS : if d in request . headers and request . headers [ d ] : msg . append ( d + ': ' + repr ( request . headers [ d ] ) ) logger . info ( "Request inf...
def get_notebook_tab_title ( notebook , page_num ) : """Helper function that gets a notebook ' s tab title given its page number : param notebook : The GTK notebook : param page _ num : The page number of the tab , for which the title is required : return : The title of the tab"""
child = notebook . get_nth_page ( page_num ) tab_label_eventbox = notebook . get_tab_label ( child ) return get_widget_title ( tab_label_eventbox . get_tooltip_text ( ) )
def parcor_stable ( filt ) : """Tests whether the given filter is stable or not by using the partial correlation coefficients ( reflection coefficients ) of the given filter . Parameters filt : A LTI filter as a LinearFilter object . Returns A boolean that is true only when all correlation coefficients ...
try : return all ( abs ( k ) < 1 for k in parcor ( ZFilter ( filt . denpoly ) ) ) except ParCorError : return False
def tally ( self , name , value ) : """Adds to the " used " metric for the given quota ."""
value = value or 0 # Protection against None . # Start at 0 if this is the first value . if 'used' not in self . usages [ name ] : self . usages [ name ] [ 'used' ] = 0 # Increment our usage and update the " available " metric . self . usages [ name ] [ 'used' ] += int ( value ) # Fail if can ' t coerce to int . se...
def on_post ( self , req , resp , rid ) : """Deserialize the file upload & save it to S3 File uploads are associated with a model of some kind . Ensure the associating model exists first & foremost ."""
signals . pre_req . send ( self . model ) signals . pre_req_upload . send ( self . model ) props = req . deserialize ( self . mimetypes ) model = find ( self . model , rid ) signals . pre_upload . send ( self . model , model = model ) try : conn = s3_connect ( self . key , self . secret ) path = self . _gen_s3_...
def index_pix_in_pixels ( pix , pixels , sort = False , outside = - 1 ) : """Find the indices of a set of pixels into another set of pixels . ! ! ! ASSUMES SORTED PIXELS ! ! ! Parameters : pix : set of search pixels pixels : set of reference pixels Returns : index : index into the reference pixels"""
# ADW : Not really safe to set index = - 1 ( accesses last entry ) ; # - np . inf would be better , but breaks other code . . . # ADW : Are the pixels always sorted ? Is there a quick way to check ? if sort : pixels = np . sort ( pixels ) # Assumes that ' pixels ' is pre - sorted , otherwise . . . ? ? ? index = np ...
def R_isrk ( self , k ) : """Function returns the inverse square root of R matrix on step k ."""
ind = int ( self . index [ self . R_time_var_index , k ] ) R = self . R [ : , : , ind ] if ( R . shape [ 0 ] == 1 ) : # 1 - D case handle simplier . No storage # of the result , just compute it each time . inv_square_root = np . sqrt ( 1.0 / R ) else : if self . svd_each_time : ( U , S , Vh ) = sp . lin...
def parse_request ( ) : """Parse request endpoint and return ( resource , action )"""
find = None if request . endpoint is not None : find = PATTERN_ENDPOINT . findall ( request . endpoint ) if not find : raise ValueError ( "invalid endpoint %s" % request . endpoint ) __ , resource , action_name = find [ 0 ] if action_name : action = request . method . lower ( ) + "_" + action_name else : ...
def shot_open_callback ( self , * args , ** kwargs ) : """Callback for the shot open button : returns : None : rtype : None : raises : None"""
tf = self . browser . get_current_selection ( 1 ) if not tf : return if not os . path . exists ( tf . path ) : msg = 'The selected shot does not exist: %s' % tf . path log . error ( msg ) self . statusbar . showMessage ( msg ) return js = JukeboxSignals . get ( ) js . before_open_shot . emit ( tf ) ...
def addUser ( self , username , password , firstname , lastname , email , role ) : """adds a user to the invitation list"""
self . _invites . append ( { "username" : username , "password" : password , "firstname" : firstname , "lastname" : lastname , "fullname" : "%s %s" % ( firstname , lastname ) , "email" : email , "role" : role } )
def match_attribute_name ( self , el , attr , prefix ) : """Match attribute name and return value if it exists ."""
value = None if self . supports_namespaces ( ) : value = None # If we have not defined namespaces , we can ' t very well find them , so don ' t bother trying . if prefix : ns = self . namespaces . get ( prefix ) if ns is None and prefix != '*' : return None else : ns ...
def closeEvent ( self , event ) : """Saves dirty editors on close and cancel the event if the user choosed to continue to work . : param event : close event"""
dirty_widgets = [ ] for w in self . widgets ( include_clones = False ) : if w . dirty : dirty_widgets . append ( w ) filenames = [ ] for w in dirty_widgets : if os . path . exists ( w . file . path ) : filenames . append ( w . file . path ) else : filenames . append ( w . documentTit...
def format_date_string ( self , date_tuple ) : """Receives a date _ tuple object , and outputs a string for placement in the article content ."""
months = [ '' , 'January' , 'February' , 'March' , 'April' , 'May' , 'June' , 'July' , 'August' , 'September' , 'October' , 'November' , 'December' ] date_string = '' if date_tuple . season : return '{0}, {1}' . format ( date_tuple . season , date_tuple . year ) else : if not date_tuple . month and not date_tup...
def reftrack_type_data ( rt , role ) : """Return the data for the type ( e . g . Asset , Alembic , Camera etc ) : param rt : the : class : ` jukeboxcore . reftrack . Reftrack ` holds the data : type rt : : class : ` jukeboxcore . reftrack . Reftrack ` : param role : item data role : type role : QtCore . Qt ...
if role == QtCore . Qt . DisplayRole or role == QtCore . Qt . EditRole : return rt . get_typ ( ) elif role == QtCore . Qt . DecorationRole : return rt . get_typ_icon ( )
def constructor ( self ) : '''Return the contract ' s immediate constructor . If there is no immediate constructor , returns the first constructor executed , following the c3 linearization Return None if there is no constructor .'''
cst = self . constructor_not_inherited if cst : return cst for inherited_contract in self . inheritance : cst = inherited_contract . constructor_not_inherited if cst : return cst return None
def _env_is_exposed ( env ) : '''Check if an environment is exposed by comparing it against a whitelist and blacklist .'''
if __opts__ [ 'svnfs_env_whitelist' ] : salt . utils . versions . warn_until ( 'Neon' , 'The svnfs_env_whitelist config option has been renamed to ' 'svnfs_saltenv_whitelist. Please update your configuration.' ) whitelist = __opts__ [ 'svnfs_env_whitelist' ] else : whitelist = __opts__ [ 'svnfs_saltenv_whit...
def exception ( self ) : """The exception that occured while the job executed . The value is # None if no exception occurred . # Raises InvalidState : If the job is # PENDING or # RUNNING ."""
if self . __state in ( Job . PENDING , Job . RUNNING ) : raise self . InvalidState ( 'job is {0}' . format ( self . __state ) ) elif self . __state == Job . ERROR : assert self . __exception is not None return self . __exception elif self . __state in ( Job . RUNNING , Job . SUCCESS , Job . CANCELLED ) : ...
def db ( self ) : """Return the correct KV store for this execution ."""
if self . _db is None : if self . tcex . default_args . tc_playbook_db_type == 'Redis' : from . tcex_redis import TcExRedis self . _db = TcExRedis ( self . tcex . default_args . tc_playbook_db_path , self . tcex . default_args . tc_playbook_db_port , self . tcex . default_args . tc_playbook_db_conte...
def sumvalues ( self , q = 0 ) : """Sum of top q passowrd frequencies"""
if q == 0 : return self . _totalf else : return - np . partition ( - self . _freq_list , q ) [ : q ] . sum ( )
def flush_body ( self ) -> bool : """发送内容体"""
if self . _body is None : return False elif isinstance ( self . _body , bytes ) : self . write ( self . _body ) return True return False
def p ( name = "" , ** kwargs ) : '''really quick and dirty profiling you start a profile by passing in name , you stop the top profiling by not passing in a name . You can also call this method using a with statement This is for when you just want to get a really back of envelope view of how your fast your...
with Reflect . context ( ** kwargs ) as r : if name : instance = P_CLASS ( r , stream , name , ** kwargs ) else : instance = P_CLASS . pop ( r ) instance ( ) return instance
def _setup ( self ) : """Prepare the system for using ` ` ansible - galaxy ` ` and returns None . : return : None"""
role_directory = os . path . join ( self . _config . scenario . directory , self . options [ 'roles-path' ] ) if not os . path . isdir ( role_directory ) : os . makedirs ( role_directory )
def ReadHuntOutputPluginLogEntries ( self , hunt_id , output_plugin_id , offset , count , with_type = None ) : """Reads hunt output plugin log entries ."""
all_entries = [ ] for flow_obj in self . _GetHuntFlows ( hunt_id ) : for entry in self . ReadFlowOutputPluginLogEntries ( flow_obj . client_id , flow_obj . flow_id , output_plugin_id , 0 , sys . maxsize , with_type = with_type ) : all_entries . append ( rdf_flow_objects . FlowOutputPluginLogEntry ( hunt_id ...
def set_point_geometry ( w , src ) : """Set point location as shapefile geometry ."""
assert "pointSource" in src . tag geometry_node = src . nodes [ get_taglist ( src ) . index ( "pointGeometry" ) ] point_attrs = parse_point_geometry ( geometry_node ) w . point ( point_attrs [ "point" ] [ 0 ] , point_attrs [ "point" ] [ 1 ] )
def get_log ( self ) : """Gets the ` ` Log ` ` at this node . return : ( osid . logging . Log ) - the log represented by this node * compliance : mandatory - - This method must be implemented . *"""
if self . _lookup_session is None : mgr = get_provider_manager ( 'LOGGING' , runtime = self . _runtime , proxy = self . _proxy ) self . _lookup_session = mgr . get_log_lookup_session ( proxy = getattr ( self , "_proxy" , None ) ) return self . _lookup_session . get_log ( Id ( self . _my_map [ 'id' ] ) )
def _run_paired ( paired ) : """Run somatic variant calling pipeline ."""
from bcbio . structural import titancna work_dir = _sv_workdir ( paired . tumor_data ) seg_files = model_segments ( tz . get_in ( [ "depth" , "bins" , "normalized" ] , paired . tumor_data ) , work_dir , paired ) call_file = call_copy_numbers ( seg_files [ "seg" ] , work_dir , paired . tumor_data ) out = [ ] if paired ....
def user_sentiments ( self , username = None ) : """This function returns a list of all sentiments of the tweets of a specified user ."""
try : return [ tweet . sentiment for tweet in self if tweet . username == username ] except : log . error ( "error -- possibly no username specified" ) return None
async def open ( self ) -> 'NodePool' : """Explicit entry . Opens pool as configured , for later closure via close ( ) . For use when keeping pool open across multiple calls . Raise any IndyError causing failure to create ledger configuration . : return : current object"""
LOGGER . debug ( 'NodePool.open >>>' ) try : await pool . set_protocol_version ( 2 ) # 1 for indy - node 1.3 , 2 for indy - node 1.4 await pool . create_pool_ledger_config ( self . name , json . dumps ( { 'genesis_txn' : str ( self . genesis_txn_path ) } ) ) except IndyError as x_indy : if x_indy . erro...
def all_capabilities ( ** kwargs ) : '''Return the host and domain capabilities in a single call . . . versionadded : : Neon : param connection : libvirt connection URI , overriding defaults : param username : username to connect with , overriding defaults : param password : password to connect with , overr...
conn = __get_conn ( ** kwargs ) result = { } try : host_caps = ElementTree . fromstring ( conn . getCapabilities ( ) ) domains = [ [ ( guest . get ( 'arch' , { } ) . get ( 'name' , None ) , key ) for key in guest . get ( 'arch' , { } ) . get ( 'domains' , { } ) . keys ( ) ] for guest in [ _parse_caps_guest ( gu...
def format_results ( self , results ) : """Format the ldap results object into somthing that is reasonable"""
if not results : return None userdn = results [ 0 ] [ 0 ] userobj = results [ 0 ] [ 1 ] userobj [ 'dn' ] = userdn keymap = self . config . get ( 'KEY_MAP' ) if keymap : return { key : scalar ( userobj . get ( value ) ) for key , value in keymap . items ( ) if _is_utf8 ( scalar ( userobj . get ( value ) ) ) } el...
def table_gsis ( table_name ) : """Returns a list of GSIs for the given table : type table _ name : str : param table _ name : Name of the DynamoDB table : returns : list - - List of GSI names"""
try : desc = DYNAMODB_CONNECTION . describe_table ( table_name ) [ u'Table' ] except JSONResponseError : raise if u'GlobalSecondaryIndexes' in desc : return desc [ u'GlobalSecondaryIndexes' ] return [ ]
def traversal ( root ) : '''Tree traversal function that generates nodes . For each subtree , the deepest node is evaluated first . Then , the next - deepest nodes are evaluated until all the nodes in the subtree are generated .'''
stack = [ root ] while len ( stack ) > 0 : node = stack . pop ( ) if hasattr ( node , 'children' ) : if node . children == set ( ) : try : stack [ - 1 ] . children . remove ( node ) except : pass yield ( node , stack ) else : ...
def create_product ( name , abbreviation , ** kwargs ) : """Create a new Product"""
data = create_product_raw ( name , abbreviation , ** kwargs ) if data : return utils . format_json ( data )
def makeGlyphsBoundingBoxes ( self ) : """Make bounding boxes for all the glyphs , and return a dictionary of BoundingBox ( xMin , xMax , yMin , yMax ) namedtuples keyed by glyph names . The bounding box of empty glyphs ( without contours or components ) is set to None . Float values are rounded to integers...
def getControlPointBounds ( glyph ) : pen . init ( ) glyph . draw ( pen ) return pen . bounds glyphBoxes = { } pen = ControlBoundsPen ( self . allGlyphs ) for glyphName , glyph in self . allGlyphs . items ( ) : bounds = None if glyph or glyph . components : bounds = getControlPointBounds ( g...
def safe_eval ( source , * args , ** kwargs ) : """eval without import"""
source = source . replace ( 'import' , '' ) # import is not allowed return eval ( source , * args , ** kwargs )
def get_scenario_data ( scenario_id , ** kwargs ) : """Get all the datasets from the group with the specified name @ returns a list of dictionaries"""
user_id = kwargs . get ( 'user_id' ) scenario_data = db . DBSession . query ( Dataset ) . filter ( Dataset . id == ResourceScenario . dataset_id , ResourceScenario . scenario_id == scenario_id ) . options ( joinedload_all ( 'metadata' ) ) . distinct ( ) . all ( ) for sd in scenario_data : if sd . hidden == 'Y' : ...
def _transport_ready_handler ( self , fd , cb_condition ) : """Wrapper for calling user callback routine to notify when transport data is ready to read"""
if ( self . user_cb ) : self . user_cb ( self . user_arg ) return True
def rollback ( self , project_id , transaction ) : """Perform a ` ` rollback ` ` request . : type project _ id : str : param project _ id : The project to connect to . This is usually your project name in the cloud console . : type transaction : bytes : param transaction : The transaction ID to rollback ....
request_pb = _datastore_pb2 . RollbackRequest ( project_id = project_id , transaction = transaction ) # Response is empty ( i . e . no fields ) but we return it anyway . return _rpc ( self . client . _http , project_id , "rollback" , self . client . _base_url , request_pb , _datastore_pb2 . RollbackResponse , )
def c ( source , libraries = [ ] ) : r"""> > > c ( ' int add ( int a , int b ) { return a + b ; } ' ) . add ( 40 , 2) 42 > > > sqrt = c ( ' ' ' . . . # include < math . h > . . . double _ sqrt ( double x ) { return sqrt ( x ) ; } . . . ' ' ' , [ ' m ' ] ) . _ sqrt > > > sqrt . restype = ctypes . c _ dou...
path = _cc_build_shared_lib ( source , '.c' , libraries ) return ctypes . cdll . LoadLibrary ( path )
def __match_l ( self , k , _set ) : """Method for searching subranges from ` _ set ` that overlap on ` k ` range . Parameters k : tuple or list or range Range for which we search overlapping subranges from ` _ set ` . _ set : set Subranges set . Returns matched : set Set of subranges from ` _ set ` ...
return { r for r in _set if k [ 0 ] in range ( * r ) or k [ 1 ] in range ( * r ) or ( k [ 0 ] < r [ 0 ] and k [ 1 ] >= r [ 1 ] ) }
def get_brizo_url ( config ) : """Return the Brizo component url . : param config : Config : return : Url , str"""
brizo_url = 'http://localhost:8030' if config . has_option ( 'resources' , 'brizo.url' ) : brizo_url = config . get ( 'resources' , 'brizo.url' ) or brizo_url brizo_path = '/api/v1/brizo' return f'{brizo_url}{brizo_path}'
def _get_coordinates_for_dataset_key ( self , dsid ) : """Get the coordinate dataset keys for * dsid * ."""
ds_info = self . ids [ dsid ] cids = [ ] for cinfo in ds_info . get ( 'coordinates' , [ ] ) : if not isinstance ( cinfo , dict ) : cinfo = { 'name' : cinfo } cinfo [ 'resolution' ] = ds_info [ 'resolution' ] if 'polarization' in ds_info : cinfo [ 'polarization' ] = ds_info [ 'polarization' ]...
def save_files ( self ) : """Saves all output from LINTools run in a single directory named after the output name ."""
while True : try : os . mkdir ( self . output_name ) except Exception as e : self . output_name = raw_input ( "This directory already exists - please enter a new name:" ) else : break self . workdir = os . getcwd ( ) os . chdir ( self . workdir + "/" + self . output_name )
def swo_read ( self , offset , num_bytes , remove = False ) : """Reads data from the SWO buffer . The data read is not automatically removed from the SWO buffer after reading unless ` ` remove ` ` is ` ` True ` ` . Otherwise the callee must explicitly remove the data by calling ` ` . swo _ flush ( ) ` ` . A...
buf_size = ctypes . c_uint32 ( num_bytes ) buf = ( ctypes . c_uint8 * num_bytes ) ( 0 ) self . _dll . JLINKARM_SWO_Read ( buf , offset , ctypes . byref ( buf_size ) ) # After the call , ` ` buf _ size ` ` has been modified to be the actual # number of bytes that was read . buf_size = buf_size . value if remove : se...
def _exec_cmd ( command ) : """Call a CMD command and return the output and returncode"""
proc = sp . Popen ( command , stdout = sp . PIPE , shell = True ) if six . PY2 : res = proc . communicate ( ) [ 0 ] else : res = proc . communicate ( timeout = 5 ) [ 0 ] return res , proc . returncode