signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def oneImageNLF ( img , img2 = None , signal = None ) : '''Estimate the NLF from one or two images of the same kind'''
x , y , weights , signal = calcNLF ( img , img2 , signal ) _ , fn , _ = _evaluate ( x , y , weights ) return fn , signal
def run ( self ) : """Run message thread ."""
while not self . stopped : try : # grab a message from queue message = self . gc100_client . queue . get ( True , 5 ) except queue . Empty : _LOGGER . debug ( "message thread: no messages" ) continue _LOGGER . debug ( "message thread: " + str ( message ) ) # parse message spl...
def _set_as_path ( self , v , load = False ) : """Setter method for as _ path , mapped from YANG variable / rbridge _ id / ip / as _ path ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ as _ path is considered as a private method . Backends looking to po...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = as_path . as_path , is_container = 'container' , presence = False , yang_name = "as-path" , rest_name = "as-path" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True ,...
def search ( self , CorpNum , JobID , TradeType , TradeUsage , Page , PerPage , Order , UserID = None ) : """수집 결과 조회 args CorpNum : 팝빌회원 사업자번호 JobID : 작업아이디 TradeType : 문서형태 배열 , N - 일반 현금영수증 , C - 취소 현금영수증 TradeUsage : 거래구분 배열 , P - ᄉ...
if JobID == None or len ( JobID ) != 18 : raise PopbillException ( - 99999999 , "작업아이디(jobID)가 올바르지 않습니다." ) uri = '/HomeTax/Cashbill/' + JobID uri += '?TradeType=' + ',' . join ( TradeType ) uri += '&TradeUsage=' + ',' . join ( TradeUsage ) uri += '&Page=' + str ( Page ) uri += '&PerPage=' + str ( PerPage ) uri +=...
def process_direct_map ( self , root , state ) -> List [ Dict ] : """Handles tags that are mapped directly from xml to IR with no additional processing other than recursive translation of any child nodes ."""
val = { "tag" : root . tag , "args" : [ ] } for node in root : val [ "args" ] += self . parseTree ( node , state ) return [ val ]
def set_level_for_logger_and_its_handlers ( log : logging . Logger , level : int ) -> None : """Set a log level for a log and all its handlers . Args : log : log to modify level : log level to set"""
log . setLevel ( level ) for h in log . handlers : # type : logging . Handler h . setLevel ( level )
def getCameraErrorNameFromEnum ( self , eCameraError ) : """Returns a string for an error"""
fn = self . function_table . getCameraErrorNameFromEnum result = fn ( eCameraError ) return result
def initrepo ( repopath , bare , shared ) : """Initialize an activegit repo . Default makes base shared repo that should be cloned for users"""
ag = activegit . ActiveGit ( repopath , bare = bare , shared = shared )
def _update_shared_response ( X , S , W , features ) : """Update the shared response ` R ` . Parameters X : list of 2D arrays , element i has shape = [ voxels _ i , timepoints ] Each element in the list contains the fMRI data for alignment of one subject . S : list of array , element i has shape = [ voxel...
subjs = len ( X ) TRs = X [ 0 ] . shape [ 1 ] R = np . zeros ( ( features , TRs ) ) # Project the subject data with the individual component removed into # the shared subspace and average over all subjects . for i in range ( subjs ) : R += W [ i ] . T . dot ( X [ i ] - S [ i ] ) R /= subjs return R
def SavGol ( y , win = 49 ) : '''Subtracts a second order Savitsky - Golay filter with window size ` win ` and returns the result . This acts as a high pass filter .'''
if len ( y ) >= win : return y - savgol_filter ( y , win , 2 ) + np . nanmedian ( y ) else : return y
def _get_mean ( self , vs30 , mag , rrup , imt , scale_fac ) : """Compute and return mean"""
C_HR , C_BC , C_SR , SC = self . _extract_coeffs ( imt ) rrup = self . _clip_distances ( rrup ) f0 = self . _compute_f0_factor ( rrup ) f1 = self . _compute_f1_factor ( rrup ) f2 = self . _compute_f2_factor ( rrup ) pga_bc = self . _get_pga_bc ( f0 , f1 , f2 , SC , mag , rrup , vs30 , scale_fac ) # compute mean values ...
def _clear ( self ) : """Clear all references ( called by its bundle activator )"""
self . __names . clear ( ) self . __queue . clear ( ) self . __context = None
def _stringify_row ( self , row_index ) : '''Stringifies an entire row , filling in blanks with prior titles as they are found .'''
table_row = self . table [ row_index ] prior_cell = None for column_index in range ( self . start [ 1 ] , self . end [ 1 ] ) : cell , changed = self . _check_interpret_cell ( table_row [ column_index ] , prior_cell , row_index , column_index ) if changed : table_row [ column_index ] = cell prior_cel...
def last_written_time ( self ) : """dfdatetime . DateTimeValues : last written time or None ."""
if not self . _registry_key and self . _registry : self . _GetKeyFromRegistry ( ) if not self . _registry_key : return None return self . _registry_key . last_written_time
def multivisit_mosaic_product_filename_generator ( obs_info , nn ) : """Generate image and sourcelist filenames for multi - visit mosaic products Parameters obs _ info : list list of items that will be used to generate the filenames : group _ id , instrument , detector , and filter nn : string the singl...
group_num = obs_info [ 0 ] instrument = obs_info [ 1 ] detector = obs_info [ 2 ] filter = obs_info [ 3 ] product_filename_dict = { } product_filename_dict [ "image" ] = "hst_mos_{}_{}_{}_{}.fits" . format ( group_num , instrument , detector , filter ) product_filename_dict [ "source catalog" ] = product_filename_dict [...
async def get_requests ( connection : Connection ) -> dict : """Example : msg _ id = ' 1' phone _ number = ' 8019119191' connection = await Connection . create ( source _ id ) await connection . connect ( phone _ number ) disclosed _ proof = await DisclosedProof . create _ with _ msgid ( source _ id , con...
if not hasattr ( DisclosedProof . get_requests , "cb" ) : DisclosedProof . get_requests . cb = create_cb ( CFUNCTYPE ( None , c_uint32 , c_uint32 , c_char_p ) ) c_connection_handle = c_uint32 ( connection . handle ) data = await do_call ( 'vcx_disclosed_proof_get_requests' , c_connection_handle , DisclosedProof . g...
def calc_circuit_breaker_position ( self , debug = False ) : """Calculates the optimal position of a circuit breaker on route . Parameters debug : bool , defaults to False If True , prints process information . Returns int position of circuit breaker on route ( index of last node on 1st half - ring prec...
# TODO : add references ( Tao ) # set init value demand_diff_min = 10e6 # check possible positions in route for ctr in range ( len ( self . _nodes ) ) : # split route and calc demand difference route_demand_part1 = sum ( [ node . demand ( ) for node in self . _nodes [ 0 : ctr ] ] ) route_demand_part2 = sum ( [ ...
def get_site_by_id ( self , id ) : """Looks up a site by ID and returns a TSquareSite representing that object , or throws an exception if no such site is found . @ param id - The entityID of the site to look up @ returns A TSquareSite object"""
response = self . _session . get ( BASE_URL_TSQUARE + '/site/{}.json' . format ( id ) ) response . raise_for_status ( ) site_data = response . json ( ) return TSquareSite ( ** site_data )
def _get_stddevs ( self , C , stddev_types , stddev_shape ) : """Returns the standard deviations given in Table 2"""
stddevs = [ ] for stddev_type in stddev_types : assert stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const . StdDev . TOTAL : stddevs . append ( C [ "sigtot" ] + np . zeros ( stddev_shape ) ) elif stddev_type == const . StdDev . INTRA_EVENT : stddevs . append (...
def bars ( n = 3 , n_categories = 3 , prefix = 'category' , columns = None , mode = 'abc' ) : """Returns a DataFrame with the required format for a bar plot Parameters : n : int Number of points for each trace n _ categories : int Number of categories for each point prefix : string Name for each cat...
categories = [ ] if not columns : columns = getName ( n , mode = mode ) for i in range ( n_categories ) : categories . extend ( [ prefix + str ( i + 1 ) ] ) data = dict ( [ ( x , np . random . randint ( 1 , 100 , n_categories ) ) for x in columns ] ) return pd . DataFrame ( data , index = categories )
def create_unassociated ( self , attachment , inline = False , file_name = None , content_type = None ) : """You can use this endpoint for bulk imports . It lets you upload a file without associating it to an article until later . Check Zendesk documentation ` important notes < https : / / developer . zendesk...
return HelpdeskAttachmentRequest ( self ) . post ( self . endpoint . create_unassociated , attachments = attachment , inline = inline , file_name = file_name , content_type = content_type )
def derivatives ( self , ** kwargs ) : """Evaluates the derivatives at the input parameter ."""
# Call parent method super ( CurveEvaluator2 , self ) . derivatives ( ** kwargs ) param = kwargs . get ( 'parameter' ) deriv_order = kwargs . get ( 'deriv_order' , 0 ) degree = kwargs . get ( 'degree' ) knotvector = kwargs . get ( 'knotvector' ) ctrlpts = kwargs . get ( 'ctrlpts' ) dimension = kwargs . get ( 'dimension...
def pprint ( self , * args , ** kwargs ) : """Pretty - printer for parsed results as a list , using the ` pprint < https : / / docs . python . org / 3 / library / pprint . html > ` _ module . Accepts additional positional or keyword args as defined for ` pprint . pprint < https : / / docs . python . org / 3 /...
pprint . pprint ( self . asList ( ) , * args , ** kwargs )
def deliver ( self , timeout = None ) : """If fail _ on _ error was set to False , a list of ( success , response ) tuples will be returned . If success is False , response will be an Exception . Otherwise , response will be the normal query response . If fail _ on _ error was left as True and one of the requ...
self . event . wait ( timeout ) if self . error : raise self . error elif not self . event . is_set ( ) : raise OperationTimedOut ( ) else : return self . responses
def add_help_to_file ( item : str , outfile : TextIO , is_command : bool ) -> None : """Write help text for commands and topics to the output file : param item : what is having its help text saved : param outfile : file being written to : param is _ command : tells if the item is a command and not just a help...
if is_command : label = "COMMAND" else : label = "TOPIC" header = '{}\n{}: {}\n{}\n' . format ( ASTERISKS , label , item , ASTERISKS ) outfile . write ( header ) result = app ( 'help {}' . format ( item ) ) outfile . write ( result . stdout )
def update ( self , z , R = None , UT = None , hx = None , ** hx_args ) : """Update the UKF with the given measurements . On return , self . x and self . P contain the new mean and covariance of the filter . Parameters z : numpy . array of shape ( dim _ z ) measurement vector R : numpy . array ( ( dim _ z...
if z is None : self . z = np . array ( [ [ None ] * self . _dim_z ] ) . T self . x_post = self . x . copy ( ) self . P_post = self . P . copy ( ) return if hx is None : hx = self . hx if UT is None : UT = unscented_transform if R is None : R = self . R elif isscalar ( R ) : R = eye ( sel...
def new_template ( template_name : str , ordering : int , formatting : dict = None , ** kwargs ) : """Templates have no unique ID . : param template _ name : : param ordering : : param formatting : : param kwargs : : return :"""
if formatting is not None : kwargs . update ( formatting ) template = dict ( [ ( 'name' , template_name ) , ( 'qfmt' , DEFAULT_TEMPLATE [ 'qfmt' ] ) , ( 'did' , None ) , ( 'bafmt' , DEFAULT_TEMPLATE [ 'bafmt' ] ) , ( 'afmt' , DEFAULT_TEMPLATE [ 'afmt' ] ) , ( 'ord' , ordering ) , ( 'bqfmt' , DEFAULT_TEMPLATE [ 'bqf...
def get_neighborhood_network ( self , node_name : str , order : int = 1 ) -> Graph : """Get the neighborhood graph of a node . : param str node _ name : Node whose neighborhood graph is requested . : return Graph : Neighborhood graph"""
logger . info ( "In get_neighborhood_graph()" ) neighbors = list ( self . get_neighbor_names ( node_name , order ) ) neighbor_network = self . graph . copy ( ) neighbor_network . delete_vertices ( self . graph . vs . select ( name_notin = neighbors ) ) return neighbor_network
def public_decrypt ( pub , message ) : '''Verify an M2Crypto - compatible signature : param Crypto . PublicKey . RSA . _ RSAobj key : The RSA public key object : param str message : The signed message to verify : rtype : str : return : The message ( or digest ) recovered from the signature , or an empty s...
if HAS_M2 : return pub . public_decrypt ( message , salt . utils . rsax931 . RSA_X931_PADDING ) else : verifier = salt . utils . rsax931 . RSAX931Verifier ( pub . exportKey ( 'PEM' ) ) return verifier . verify ( message )
def lcm ( * a ) : """Least common multiple . Usage : lcm ( [ 3 , 4 , 5 ] ) or : lcm ( 3 , 4 , 5 )"""
if len ( a ) > 1 : return reduce ( lcm2 , a ) if hasattr ( a [ 0 ] , "__iter__" ) : return reduce ( lcm2 , a [ 0 ] ) return a [ 0 ]
def _getFieldsInDB ( self , tablename ) : """get all the fields from a specific table"""
SQL = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME="%s"' % tablename array_data = self . execQuery ( SQL ) return [ x [ 0 ] for x in array_data ]
def normframe ( I : np . ndarray , Clim : tuple ) -> np . ndarray : """inputs : I : 2 - D Numpy array of grayscale image data Clim : length 2 of tuple or numpy 1 - D array specifying lowest and highest expected values in grayscale image"""
Vmin = Clim [ 0 ] Vmax = Clim [ 1 ] # stretch to [ 0,1] return ( I . astype ( np . float32 ) . clip ( Vmin , Vmax ) - Vmin ) / ( Vmax - Vmin )
def get_thumbnail_paths ( self ) : """Helper function used to avoid processing thumbnail files during ` os . walk ` ."""
thumbnail_path_tuples = [ ] # channel thumbnail channel_info = self . get_channel_info ( ) chthumbnail_path = channel_info . get ( 'thumbnail_chan_path' , None ) if chthumbnail_path : chthumbnail_path_tuple = path_to_tuple ( chthumbnail_path , windows = self . winpaths ) thumbnail_path_tuples . append ( chthumb...
def detach_zone ( organization_id_or_slug ) : '''Detach the zone of a given < organization > .'''
organization = Organization . objects . get_by_id_or_slug ( organization_id_or_slug ) if not organization : exit_with_error ( 'No organization found for {0}' . format ( organization_id_or_slug ) ) log . info ( 'Detaching {organization} from {organization.zone}' . format ( organization = organization ) ) organizatio...
def _iter_over_selections ( obj , dim , values ) : """Iterate over selections of an xarray object in the provided order ."""
from . groupby import _dummy_copy dummy = None for value in values : try : obj_sel = obj . sel ( ** { dim : value } ) except ( KeyError , IndexError ) : if dummy is None : dummy = _dummy_copy ( obj ) obj_sel = dummy yield obj_sel
def take_screeshot ( self ) : '''Take a screenshot of the virtual viewport content . Return value is a png image as a bytestring .'''
resp = self . Page_captureScreenshot ( ) assert 'result' in resp assert 'data' in resp [ 'result' ] imgdat = base64 . b64decode ( resp [ 'result' ] [ 'data' ] ) return imgdat
def today ( self ) : """Return the Day for the current day"""
today = timezone . now ( ) . date ( ) try : return Day . objects . get ( date = today ) except Day . DoesNotExist : return None
def __get_image ( conn , vm_ ) : '''The get _ image for GCE allows partial name matching and returns a libcloud object .'''
img = config . get_cloud_config_value ( 'image' , vm_ , __opts__ , default = 'debian-7' , search_global = False ) return conn . ex_get_image ( img )
def yaw ( b , component , solve_for = None , ** kwargs ) : """Create a constraint for the inclination of a star relative to its parent orbit : parameter b : the : class : ` phoebe . frontend . bundle . Bundle ` : parameter str component : the label of the star in which this constraint should be built : para...
hier = b . get_hierarchy ( ) if not len ( hier . get_value ( ) ) : # TODO : change to custom error type to catch in bundle . add _ component # TODO : check whether the problem is 0 hierarchies or more than 1 raise NotImplementedError ( "constraint for yaw requires hierarchy" ) component_ps = _get_system_ps ( b , co...
def sparse_segment ( cords ) : r"""Create a segment of a sparse grid . Convert a ol - index to sparse grid coordinates on ` ` [ 0 , 1 ] ^ N ` ` hyper - cube . A sparse grid of order ` ` D ` ` coencide with the set of sparse _ segments where ` ` | | cords | | _ 1 < = D ` ` . More specifically , a segment of ...
cords = np . array ( cords ) + 1 slices = [ ] for cord in cords : slices . append ( slice ( 1 , 2 ** cord + 1 , 2 ) ) grid = np . mgrid [ slices ] indices = grid . reshape ( len ( cords ) , np . prod ( grid . shape [ 1 : ] ) ) . T sgrid = indices * 2. ** - cords return sgrid
def create_307_response ( self ) : """Creates a 307 " Temporary Redirect " response including a HTTP Warning header with code 299 that contains the user message received during processing the request ."""
request = get_current_request ( ) msg_mb = UserMessageMember ( self . message ) coll = request . root [ '_messages' ] coll . add ( msg_mb ) # Figure out the new location URL . qs = self . __get_new_query_string ( request . query_string , self . message . slug ) resubmit_url = "%s?%s" % ( request . path_url , qs ) heade...
def guess_type ( self , path ) : """Guess the type of a file . Argument is a PATH ( a filename ) . Return value is a string of the form type / subtype , usable for a MIME Content - type header . The default implementation looks the file ' s extension up in the table self . extensions _ map , using applica...
base , ext = posixpath . splitext ( path ) if ext in self . extensions_map : return self . extensions_map [ ext ] ext = ext . lower ( ) if ext in self . extensions_map : return self . extensions_map [ ext ] else : return self . extensions_map [ '' ]
def main ( args ) : """Main function which runs worker ."""
title = '## Starting evaluation of round {0} ##' . format ( args . round_name ) logging . info ( '\n' + '#' * len ( title ) + '\n' + '#' * len ( title ) + '\n' + '##' + ' ' * ( len ( title ) - 2 ) + '##' + '\n' + title + '\n' + '#' * len ( title ) + '\n' + '#' * len ( title ) + '\n' + '##' + ' ' * ( len ( title ) - 2 )...
def from_file ( self , filename ) : """Uploads a file from a filename on your system . : param filename : Path to file on your system . Example : > > > myimage . from _ file ( ' / path / to / dinner . png ' )"""
mimetype = mimetypes . guess_type ( filename ) [ 0 ] or "application/octal-stream" headers = { "Content-Type" : mimetype , "Content-Length" : str ( os . path . getsize ( filename ) ) , } # upload file file_data = self . _pump . request ( "/api/user/{0}/uploads" . format ( self . _pump . client . nickname ) , method = "...
def extract_lookups ( value ) : """Recursively extracts any stack lookups within the data structure . Args : value ( one of str , list , dict ) : a structure that contains lookups to output values Returns : list : list of lookups if any"""
lookups = set ( ) if isinstance ( value , basestring ) : lookups = lookups . union ( extract_lookups_from_string ( value ) ) elif isinstance ( value , list ) : for v in value : lookups = lookups . union ( extract_lookups ( v ) ) elif isinstance ( value , dict ) : for v in value . values ( ) : ...
def infer_hasattr ( node , context = None ) : """Understand hasattr calls This always guarantees three possible outcomes for calling hasattr : Const ( False ) when we are sure that the object doesn ' t have the intended attribute , Const ( True ) when we know that the object has the attribute and Uninferabl...
try : obj , attr = _infer_getattr_args ( node , context ) if ( obj is util . Uninferable or attr is util . Uninferable or not hasattr ( obj , "getattr" ) ) : return util . Uninferable obj . getattr ( attr , context = context ) except UseInferenceDefault : # Can ' t infer something from this function...
def isfieldvalue ( bunchdt , data , commdct , idfobj , fieldname , value , places = 7 ) : """test if idfobj . field = = value"""
# do a quick type check # if type ( idfobj [ fieldname ] ) ! = type ( value ) : # return False # takes care of autocalculate and real # check float thiscommdct = getfieldcomm ( bunchdt , data , commdct , idfobj , fieldname ) if 'type' in thiscommdct : if thiscommdct [ 'type' ] [ 0 ] in ( 'real' , 'integer' ) : # te...
def from_json ( cls , file_path = None ) : """Create collection from a JSON file ."""
with io . open ( file_path , encoding = text_type ( 'utf-8' ) ) as stream : try : users_json = json . load ( stream ) except ValueError : raise ValueError ( 'No JSON object could be decoded' ) return cls . construct_user_list ( raw_users = users_json . get ( 'users' ) )
def fqname_to_id ( self , fq_name , type ) : """Return uuid for fq _ name : param fq _ name : resource fq name : type fq _ name : FQName : param type : resource type : type type : str : rtype : UUIDv4 str : raises HttpError : fq _ name not found"""
data = { "type" : type , "fq_name" : list ( fq_name ) } return self . post_json ( self . make_url ( "/fqname-to-id" ) , data ) [ "uuid" ]
def _serialize ( xp_ast ) : '''Generate token strings which , when joined together , form a valid XPath serialization of the AST .'''
if hasattr ( xp_ast , '_serialize' ) : for tok in xp_ast . _serialize ( ) : yield tok elif isinstance ( xp_ast , string_types ) : # strings in serialized xpath needed to be quoted # ( e . g . for use in paths , comparisons , etc ) # using repr to quote them ; for unicode , the leading # u ( u ' ' ) needs to...
def _remove_data_dir_path ( self , inp = None ) : # import string """Remove the data directory path from filenames"""
# need to add a check in here to make sure data _ dir path is actually in # the filename if inp is not None : split_str = os . path . join ( self . data_path , '' ) return inp . apply ( lambda x : x . split ( split_str ) [ - 1 ] )
def get_breakpoint_graph ( stream , merge_edges = True ) : """Taking a file - like object transforms supplied gene order data into the language of : param merge _ edges : a flag that indicates if parallel edges in produced breakpoint graph shall be merged or not : type merge _ edges : ` ` bool ` ` : param str...
result = BreakpointGraph ( ) current_genome = None fragment_data = { } for line in stream : line = line . strip ( ) if len ( line ) == 0 : # empty lines are omitted continue if GRIMMReader . is_genome_declaration_string ( data_string = line ) : # is we have a genome declaration , we must update curr...
def incremental_value ( self , slip_moment , mmax , mag_value , bbar , dbar ) : """Returns the incremental rate of earthquakes with M = mag _ value"""
delta_m = mmax - mag_value dirac_term = np . zeros_like ( mag_value ) dirac_term [ np . fabs ( delta_m ) < 1.0E-12 ] = 1.0 a_1 = self . _get_a1 ( bbar , dbar , slip_moment , mmax ) return a_1 * ( bbar * np . exp ( bbar * delta_m ) * ( delta_m > 0.0 ) ) + a_1 * dirac_term
def add_dependency ( self , address ) : """Add a dependency to this target . This will deduplicate existing dependencies ."""
if address in self . _dependencies_by_address : if self . _dependencies_by_address [ address ] . has_comment ( ) : logger . warn ( 'BuildFileManipulator would have added {address} as a dependency of ' '{target_address}, but that dependency was already forced with a comment.' . format ( address = address . s...
def _tmpfile ( self , cache_key , use ) : """Allocate tempfile on same device as cache with a suffix chosen to prevent collisions"""
with temporary_file ( suffix = cache_key . id + use , root_dir = self . _cache_root , permissions = self . _permissions ) as tmpfile : yield tmpfile
def delete_set ( set = None , family = 'ipv4' ) : '''. . versionadded : : 2014.7.0 Delete ipset set . CLI Example : . . code - block : : bash salt ' * ' ipset . delete _ set custom _ set IPv6: salt ' * ' ipset . delete _ set custom _ set family = ipv6'''
if not set : return 'Error: Set needs to be specified' cmd = '{0} destroy {1}' . format ( _ipset_cmd ( ) , set ) out = __salt__ [ 'cmd.run' ] ( cmd , python_shell = False ) if not out : out = True return out
def get_connect_redirect_url ( self , request , socialaccount ) : """Returns the default URL to redirect to after successfully connecting a social account ."""
assert request . user . is_authenticated url = reverse ( 'socialaccount_connections' ) return url
def plot_powerlaw ( exp , startx , starty , width = None , ** kwargs ) : r'''Plot a power - law . : arguments : * * exp * * ( ` ` float ` ` ) The power - law exponent . * * startx , starty * * ( ` ` float ` ` ) Start coordinates . : options : * * width , height , endx , endy * * ( ` ` float ` ` ) De...
# get options / defaults endx = kwargs . pop ( 'endx' , None ) endy = kwargs . pop ( 'endy' , None ) height = kwargs . pop ( 'height' , None ) units = kwargs . pop ( 'units' , 'relative' ) axis = kwargs . pop ( 'axis' , plt . gca ( ) ) # check if axis . get_xscale ( ) != 'log' or axis . get_yscale ( ) != 'log' : ra...
def with_config ( f ) : """Add config to function ."""
# keep it . @ click . pass_context def new_func ( ctx , * args , ** kwargs ) : # Invoked with custom config : if 'config' in kwargs : return ctx . invoke ( f , * args , ** kwargs ) if ctx . obj is None : ctx . obj = { } config = ctx . obj [ 'config' ] project_enabled = not ctx . obj . ge...
def _do_request ( method , url , headers , data = None , query_params = None , timeout = 20 ) : """Performs an HTTP request : param method : A unicode string of ' POST ' or ' PUT ' : param url ; A unicode string of the URL to request : param headers : A dict of unicode strings , where keys are header na...
if query_params : url += '?' + urlencode ( query_params ) . replace ( '+' , '%20' ) if isinstance ( data , dict ) : data_bytes = { } for key in data : data_bytes [ key . encode ( 'utf-8' ) ] = data [ key ] . encode ( 'utf-8' ) data = urlencode ( data_bytes ) headers [ 'Content-Type' ] = 'app...
def user_courses ( self ) : '''Returns the list of courses this user is subscribed for , or owning , or tutoring . This leads to the fact that tutors and owners don ' t need course membership .'''
registered = self . courses . filter ( active__exact = True ) . distinct ( ) return ( self . tutor_courses ( ) | registered ) . distinct ( )
def _write_pidfile ( self ) : """Write the pid file out with the process number in the pid file"""
LOGGER . debug ( 'Writing pidfile: %s' , self . pidfile_path ) with open ( self . pidfile_path , "w" ) as handle : handle . write ( str ( os . getpid ( ) ) )
def _read_results ( self , memory ) : """Read back the probed results . Returns str A string of " 0 " s and " 1 " s , one for each millisecond of simulation ."""
# Seek to the simulation data and read it all back memory . seek ( 8 ) bits = bitarray ( endian = "little" ) bits . frombytes ( memory . read ( ) ) self . recorded_data = bits . to01 ( )
def has_namespace ( self , namespace ) : """tests to see if the namespace exists args : namespace : the name of the namespace"""
result = requests . get ( self . _make_url ( namespace ) ) if result . status_code == 200 : return True elif result . status_code == 404 : return False
def mask_image ( image : SpatialImage , mask : np . ndarray , data_type : type = None ) -> np . ndarray : """Mask image after optionally casting its type . Parameters image Image to mask . Can include time as the last dimension . mask Mask to apply . Must have the same shape as the image data . data _ t...
image_data = image . get_data ( ) if image_data . shape [ : 3 ] != mask . shape : raise ValueError ( "Image data and mask have different shapes." ) if data_type is not None : cast_data = image_data . astype ( data_type ) else : cast_data = image_data return cast_data [ mask ]
def _set_vc_link_init ( self , v , load = False ) : """Setter method for vc _ link _ init , mapped from YANG variable / interface / fc _ port / vc _ link _ init ( fc - vc - link - init - cfg - type ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ vc _ link _ init is co...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'idle' : { 'value' : 0 } , u'arb' : { 'value' : 1 } } , ) , default = unicode ( "idle" ) , is_leaf = True , yang_name = "vc-link...
def obfuscation_machine ( use_unicode = False , identifier_length = 1 ) : """A generator that returns short sequential combinations of lower and upper - case letters that will never repeat . If * use _ unicode * is ` ` True ` ` , use nonlatin cryllic , arabic , and syriac letters instead of the usual ABCs . ...
# This generates a list of the letters a - z : lowercase = list ( map ( chr , range ( 97 , 123 ) ) ) # Same thing but ALL CAPS : uppercase = list ( map ( chr , range ( 65 , 90 ) ) ) if use_unicode : # Python 3 lets us have some * real * fun : allowed_categories = ( 'LC' , 'Ll' , 'Lu' , 'Lo' , 'Lu' ) # All the f...
def run_filter ( vrn_file , align_bam , ref_file , data , items ) : """Filter and annotate somatic VCFs with damage / bias artifacts on low frequency variants . Moves damage estimation to INFO field , instead of leaving in FILTER ."""
if not should_filter ( items ) or not vcfutils . vcf_has_variants ( vrn_file ) : return data else : raw_file = "%s-damage.vcf" % utils . splitext_plus ( vrn_file ) [ 0 ] out_plot_files = [ "%s%s" % ( utils . splitext_plus ( raw_file ) [ 0 ] , ext ) for ext in [ "_seq_bias_simplified.pdf" , "_pcr_bias_simpli...
def stream_emit ( self , record , source_name ) : """Emit a record . If a formatter is specified , it is used to format the record . The record is then written to the stream with a trailing newline . If exception information is present , it is formatted using traceback . print _ exception and appended to th...
if not source_name in self . output_streams : out_path = os . path . abspath ( "./logs" ) logpath = ansi_escape . sub ( '' , source_name . replace ( "/" , ";" ) . replace ( ":" , ";" ) . replace ( "?" , "-" ) ) filename = "log {path}.txt" . format ( path = logpath ) print ( "Opening output log file for ...
def walk ( self ) : """Walks around and returns all objects which needs migration It does exactly the same as the original method , but add some progress loggers . : return : objects ( with acquisition wrapper ) that needs migration : rtype : generator"""
catalog = self . catalog query = self . additionalQuery . copy ( ) query [ 'portal_type' ] = self . src_portal_type query [ 'meta_type' ] = self . src_meta_type if HAS_LINGUA_PLONE and 'Language' in catalog . indexes ( ) : query [ 'Language' ] = 'all' brains = catalog ( query ) limit = getattr ( self , 'limit' , Fa...
def run_project ( project_directory : str , output_directory : str = None , logging_path : str = None , reader_path : str = None , reload_project_libraries : bool = False , ** kwargs ) -> ExecutionResult : """Runs a project as a single command directly within the current Python interpreter . : param project _ d...
from cauldron . cli import batcher return batcher . run_project ( project_directory = project_directory , output_directory = output_directory , log_path = logging_path , reader_path = reader_path , reload_project_libraries = reload_project_libraries , shared_data = kwargs )
def preferred_width ( self , cli , max_available_width ) : """Return the preferred width for this control . That is the width of the longest line ."""
text = token_list_to_text ( self . _get_tokens_cached ( cli ) ) line_lengths = [ get_cwidth ( l ) for l in text . split ( '\n' ) ] return max ( line_lengths )
def setLoggerLevel ( self , logger , level ) : """Sets the level to log the inputed logger at . : param logger | < str > level | < int >"""
if logger == 'root' : _log = logging . getLogger ( ) else : _log = logging . getLogger ( logger ) _log . setLevel ( level ) if level == logging . NOTSET : self . _loggerLevels . pop ( logger , None ) else : self . _loggerLevels [ logger ] = level
def run ( cls , routes , * args , ** kwargs ) : # pragma : no cover """Run a web application . : param cls : Application class : param routes : list of routes : param args : additional arguments : param kwargs : additional keyword arguments : return : None"""
app = init ( cls , routes , * args , ** kwargs ) HOST = os . getenv ( 'HOST' , '0.0.0.0' ) PORT = int ( os . getenv ( 'PORT' , 8000 ) ) aiohttp . web . run_app ( app , port = PORT , host = HOST )
def spm_hrf ( tr , oversampling = 50 , time_length = 32. , onset = 0. ) : """Implementation of the SPM hrf model Parameters tr : float scan repeat time , in seconds oversampling : int , optional temporal oversampling factor time _ length : float , optional hrf kernel length , in seconds onset : floa...
return _gamma_difference_hrf ( tr , oversampling , time_length , onset )
def value ( self , key , default = None ) : """Returns the value for the given key for this settings instance . : return < variant >"""
if self . _customFormat : return self . _customFormat . value ( key , default ) else : return unwrapVariant ( super ( XSettings , self ) . value ( key ) )
def get ( self , key , func = None , args = ( ) , kwargs = None , ** opts ) : """Manually retrieve a value from the cache , calculating as needed . Params : key - > string to store / retrieve value from . func - > callable to generate value if it does not exist , or has expired . args - > positional argum...
kwargs = kwargs or { } key , store = self . _expand_opts ( key , opts ) # Resolve the etag . opts [ 'etag' ] = call_or_pass ( opts . get ( 'etag' ) or opts . get ( 'etagger' ) , args , kwargs ) if not isinstance ( key , str ) : raise TypeError ( 'non-string key of type %s' % type ( key ) ) data = store . get ( key ...
def set_custom_metrics_for_course_key ( course_key ) : """Set monitoring custom metrics related to a course key . This is not cached , and only support reporting to New Relic Insights ."""
if not newrelic : return newrelic . agent . add_custom_parameter ( 'course_id' , six . text_type ( course_key ) ) newrelic . agent . add_custom_parameter ( 'org' , six . text_type ( course_key . org ) )
def _maybe_wrap ( attribute ) : """Helper for ` Asynchronous ` ."""
if iscoroutinefunction ( attribute ) : return asynchronous ( attribute ) if isinstance ( attribute , ( classmethod , staticmethod ) ) : if iscoroutinefunction ( attribute . __func__ ) : return attribute . __class__ ( asynchronous ( attribute . __func__ ) ) return attribute
def open ( self , mode = 'r' , version = None , bumpversion = None , prerelease = None , dependencies = None , metadata = None , message = None , * args , ** kwargs ) : '''Opens a file for read / write Parameters mode : str Specifies the mode in which the file is opened ( default ' r ' ) version : str Ver...
if metadata is None : metadata = { } latest_version = self . get_latest_version ( ) version = _process_version ( self , version ) version_hash = self . get_version_hash ( version ) if self . versioned : if latest_version is None : latest_version = BumpableVersion ( ) next_version = latest_version . ...
def remove ( self , username , user_api , filename = None , force = False ) : """Remove specified SSH public key from specified user ."""
self . keys = API . __get_keys ( filename ) self . username = username user = user_api . find ( username ) [ 0 ] if not force : # pragma : no cover self . __confirm ( ) for key in self . __delete_keys ( ) : operation = { 'sshPublicKey' : [ ( ldap3 . MODIFY_DELETE , [ key ] ) ] } self . client . modify ( use...
def getNumberOfJobsIssued ( self , preemptable = None ) : """Gets number of jobs that have been added by issueJob ( s ) and not removed by removeJob : param None or boolean preemptable : If none , return all types of jobs . If true , return just the number of preemptable jobs . If false , return just the nu...
if preemptable is None : return len ( self . jobBatchSystemIDToIssuedJob ) elif preemptable : return self . preemptableJobsIssued else : assert len ( self . jobBatchSystemIDToIssuedJob ) >= self . preemptableJobsIssued return len ( self . jobBatchSystemIDToIssuedJob ) - self . preemptableJobsIssued
def _estimate_r2 ( self , X = None , y = None , mu = None , weights = None ) : """estimate some pseudo R ^ 2 values currently only computes explained deviance . results are stored Parameters y : array - like of shape ( n _ samples , ) output data vector mu : array - like of shape ( n _ samples , ) exp...
if mu is None : mu = self . predict_mu ( X = X ) if weights is None : weights = np . ones_like ( y ) . astype ( 'float64' ) null_mu = y . mean ( ) * np . ones_like ( y ) . astype ( 'float64' ) null_d = self . distribution . deviance ( y = y , mu = null_mu , weights = weights ) full_d = self . distribution . dev...
def set_hsv ( self , sel_color ) : """Put cursor on sel _ color given in HSV . : param sel _ color : color in HSV format : type sel _ color : sequence ( int )"""
width = self . winfo_width ( ) height = self . winfo_height ( ) h , s , v = sel_color self . set_hue ( h ) x = v / 100. y = ( 1 - s / 100. ) self . coords ( 'cross_h' , 0 , y * height , width , y * height ) self . coords ( 'cross_v' , x * width , 0 , x * width , height )
def begin ( self ) : """Begin a read - only transaction on the database . : rtype : bytes : returns : the ID for the newly - begun transaction . : raises ValueError : if the transaction is already begun , committed , or rolled back ."""
if not self . _multi_use : raise ValueError ( "Cannot call 'begin' on single-use snapshots" ) if self . _transaction_id is not None : raise ValueError ( "Read-only transaction already begun" ) if self . _read_request_count > 0 : raise ValueError ( "Read-only transaction already pending" ) database = self . ...
def record ( self ) : # type : ( ) - > bytes '''A method to generate the string representing this UDF Implementation Use Volume Descriptor Implementation Use field . Parameters : None . Returns : A string representing this UDF Implementation Use Volume Descriptor .'''
if not self . _initialized : raise pycdlibexception . PyCdlibInternalError ( 'UDF Implementation Use Volume Descriptor Implementation Use field not initialized' ) return struct . pack ( self . FMT , self . char_set , self . log_vol_ident , self . lv_info1 , self . lv_info2 , self . lv_info3 , self . impl_ident . re...
def tt_qr ( X , left_to_right = True ) : """Orthogonalizes a TT tensor from left to right or from right to left . : param : X - thensor to orthogonalise : param : direction - direction . May be ' lr / LR ' or ' rl / RL ' for left / right orthogonalization : return : X _ orth , R - orthogonal tensor and ri...
# Get rid of redundant ranks ( they cause technical difficulties ) . X = X . round ( eps = 0 ) numDims = X . d coresX = tt . tensor . to_list ( X ) if left_to_right : # Left to right orthogonalization of the X cores . for dim in xrange ( 0 , numDims - 1 ) : coresX = cores_orthogonalization_step ( coresX , d...
def _collapse_column ( current , pc ) : """Collapse the column data and : param current : : param pc : : return :"""
_tmp_column = { } try : for k , v in current . items ( ) : try : # We do not want to store these table keys at the column level . if not any ( i in k for i in [ "tableName" , "google" , "filename" , "md5" , "MD5" ] ) : # [ ' paleoData ' , ' key ' ] m = k . split ( '_' ) ...
def deferFunction ( self , callable ) : """Schedule a function handler to be called just before completion . This is used for handling function bodies , which must be deferred because code later in the file might modify the global scope . When ` callable ` is called , the scope at the time this is called will...
self . _deferredFunctions . append ( ( callable , self . scopeStack [ : ] , self . offset ) )
def new ( self , bootstrap_with = None , use_timer = False ) : """Actual constructor of the solver ."""
if not self . minicard : self . minicard = pysolvers . minicard_new ( ) if bootstrap_with : for clause in bootstrap_with : self . add_clause ( clause ) self . use_timer = use_timer self . call_time = 0.0 # time spent for the last call to oracle self . accu_time = 0.0
def ValidateKey ( cls , key_path ) : """Validates this key against supported key names . Args : key _ path ( str ) : path of a Windows Registry key . Raises : FormatError : when key is not supported ."""
for prefix in cls . VALID_PREFIXES : if key_path . startswith ( prefix ) : return # TODO : move check to validator . if key_path . startswith ( 'HKEY_CURRENT_USER\\' ) : raise errors . FormatError ( 'HKEY_CURRENT_USER\\ is not supported instead use: ' 'HKEY_USERS\\%%users.sid%%\\' ) raise errors . Forma...
def connect ( cls , * args , ** kwargs ) : """connect ( username = None , password = None , endpoint = None , admin = False ) Configures the Panoptes client for use . Note that there is no need to call this unless you need to pass one or more of the below arguments . By default , the client will connect to ...
cls . _local . panoptes_client = cls ( * args , ** kwargs ) cls . _local . panoptes_client . login ( ) return cls . _local . panoptes_client
def stroke ( self ) : """Property for strokes ."""
if not hasattr ( self , '_stroke' ) : self . _stroke = None stroke = self . tagged_blocks . get_data ( 'VECTOR_STROKE_DATA' ) if stroke : self . _stroke = Stroke ( stroke ) return self . _stroke
def getinputfiles ( self , outputfile , loadmetadata = True , client = None , requiremetadata = False ) : """Iterates over all input files for the specified outputfile ( you may pass a CLAMOutputFile instance or a filename string ) . Yields ( CLAMInputFile , str : inputtemplate _ id ) tuples . The last three argume...
if isinstance ( outputfile , CLAMOutputFile ) : outputfilename = str ( outputfile ) . replace ( os . path . join ( self . projectpath , 'output/' ) , '' ) else : outputfilename = outputfile outputtemplate , inputfiles = self [ outputfilename ] for inputfilename , inputtemplate in inputfiles . items ( ) : yi...
def validate ( self ) : """Using the SCHEMA property , validate the attributes of this instance . If any attributes are missing or invalid , raise a ValidationException ."""
validator = Draft7Validator ( self . SCHEMA ) errors = set ( ) # make errors a set to avoid duplicates for error in validator . iter_errors ( self . serialize ( ) ) : errors . add ( '.' . join ( list ( map ( str , error . path ) ) + [ error . message ] ) ) if errors : raise JSONValidationException ( type ( self...
async def unpack ( self , ciphertext : bytes ) -> ( str , str , str ) : """Unpack a message . Return triple with cleartext , sender verification key , and recipient verification key . Raise AbsentMessage for missing ciphertext , or WalletState if wallet is closed . Raise AbsentRecord if wallet has no key to unp...
LOGGER . debug ( 'Wallet.unpack >>> ciphertext: %s' , ciphertext ) if not ciphertext : LOGGER . debug ( 'Wallet.pack <!< No ciphertext to unpack' ) raise AbsentMessage ( 'No ciphertext to unpack' ) try : unpacked = json . loads ( await crypto . unpack_message ( self . handle , ciphertext ) ) except IndyErro...
def color ( self , value ) : """gets / sets the color"""
if self . _color != value and isinstance ( value , Color ) : self . _color = value
def open ( self , mode = 'read' ) : """Open the file ."""
if self . file : self . close ( ) raise 'Close file before opening.' if mode == 'write' : self . file = open ( self . path , 'w' ) elif mode == 'overwrite' : # Delete file if exist . self . file = open ( self . path , 'w+' ) else : # Open for reading . self . file = open ( self . path , 'r' ) self ....
def GetRaw ( self , name , context = None , default = utils . NotAValue ) : """Get the raw value without interpolations ."""
if context is None : context = self . context # Getting a raw value is pretty cheap so we wont bother with the cache here . _ , value = self . _GetValue ( name , context , default = default ) return value
def parse_matchup ( self ) : """Parse the banner matchup meta info for the game . : returns : ` ` self ` ` on success or ` ` None ` `"""
lx_doc = self . html_doc ( ) try : if not self . matchup : self . matchup = self . _fill_meta ( lx_doc ) return self except : return None