signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def supported_cameras ( ) : """List the names of all cameras supported by libgphoto2 , grouped by the name of their driver ."""
ctx = lib . gp_context_new ( ) abilities_list_p = new_gp_object ( "CameraAbilitiesList" ) lib . gp_abilities_list_load ( abilities_list_p , ctx ) abilities = ffi . new ( "CameraAbilities*" ) out = [ ] for idx in range ( lib . gp_abilities_list_count ( abilities_list_p ) ) : lib . gp_abilities_list_get_abilities ( a...
def _call ( self , x , out = None ) : """Return the constant vector or assign it to ` ` out ` ` ."""
if out is None : return self . range . element ( copy ( self . constant ) ) else : out . assign ( self . constant )
def remove_page ( self , process_id , wit_ref_name , page_id ) : """RemovePage . [ Preview API ] Removes a page from the work item form : param str process _ id : The ID of the process : param str wit _ ref _ name : The reference name of the work item type : param str page _ id : The ID of the page"""
route_values = { } if process_id is not None : route_values [ 'processId' ] = self . _serialize . url ( 'process_id' , process_id , 'str' ) if wit_ref_name is not None : route_values [ 'witRefName' ] = self . _serialize . url ( 'wit_ref_name' , wit_ref_name , 'str' ) if page_id is not None : route_values [ ...
def _coarsenImage ( image , f ) : '''seems to be a more precise ( but slower ) way to down - scale an image'''
from skimage . morphology import square from skimage . filters import rank from skimage . transform . _warps import rescale selem = square ( f ) arri = rank . mean ( image , selem = selem ) return rescale ( arri , 1 / f , order = 0 )
def create_pipeline ( url , auth , json_payload , verify_ssl ) : """Create a new pipeline . Args : url ( str ) : the host url in the form ' http : / / host : port / ' . auth ( tuple ) : a tuple of username , and password . json _ payload ( dict ) : the exported json paylod as a dictionary . verify _ ssl (...
title = json_payload [ 'pipelineConfig' ] [ 'title' ] description = json_payload [ 'pipelineConfig' ] [ 'description' ] params = { 'description' : description , 'autoGeneratePipelineId' : True } logging . info ( 'No destination pipeline ID provided. Creating a new pipeline: ' + title ) put_result = requests . put ( ur...
def p_sens_empty ( self , p ) : 'senslist : empty'
p [ 0 ] = SensList ( ( Sens ( None , 'all' , lineno = p . lineno ( 1 ) ) , ) , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def _reconstruct_data ( values , dtype , original ) : """reverse of _ ensure _ data Parameters values : ndarray dtype : pandas _ dtype original : ndarray - like Returns Index for extension types , otherwise ndarray casted to dtype"""
from pandas import Index if is_extension_array_dtype ( dtype ) : values = dtype . construct_array_type ( ) . _from_sequence ( values ) elif is_datetime64tz_dtype ( dtype ) or is_period_dtype ( dtype ) : values = Index ( original ) . _shallow_copy ( values , name = None ) elif is_bool_dtype ( dtype ) : value...
def tear_down_instances ( self ) : """Tear down all instances"""
self . info_log ( 'Tearing down all instances...' ) for instance in self . alive_instances : instance . tear_down ( ) self . info_log ( '[Done]Tearing down all instances' )
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_peer_fcf_mac ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) fcoe_get_interface = ET . Element ( "fcoe_get_interface" ) config = fcoe_get_interface output = ET . SubElement ( fcoe_get_interface , "output" ) fcoe_intf_list = ET . SubElement ( output , "fcoe-intf-list" ) fcoe_intf_fcoe_port_id_key = ET . SubElement ( fcoe_intf_list , "fcoe-intf-f...
def get_authorization_vault_session ( self ) : """Gets the session for retrieving authorization to vault mappings . return : ( osid . authorization . AuthorizationVaultSession ) - an ` ` AuthorizationVaultSession ` ` raise : OperationFailed - unable to complete request raise : Unimplemented - ` ` supports _...
if not self . supports_authorization_vault ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . AuthorizationVaultSession ( runtime = self . _runtime )
def __get_genestr ( self , itemid ) : """Given a geneid , return the string geneid or a gene symbol ."""
if self . id2symbol is not None : symbol = self . id2symbol . get ( itemid , None ) if symbol is not None : return symbol if isinstance ( itemid , int ) : return str ( itemid ) return itemid
def main ( book_dir = BOOK_PATH , include_tags = None , verbosity = 1 ) : r"""Parse all the asciidoc files in book _ dir , returning a list of 2 - tuples of lists of 2 - tuples ( tagged lines ) > > > main ( BOOK _ PATH , verbosity = 0) [ ( ' . . . / src / nlpia / data / book / Appendix F - - Glossary . asc ' , ...
if verbosity : logger . info ( 'book_dir: {}' . format ( book_dir ) ) logger . info ( 'include_tags: {}' . format ( include_tags ) ) logger . info ( 'verbosity: {}' . format ( verbosity ) ) include_tags = [ include_tags ] if isinstance ( include_tags , str ) else include_tags include_tags = None if not incl...
def generate_certificate ( ctx , slot , management_key , pin , public_key , subject , valid_days ) : """Generate a self - signed X . 509 certificate . A self - signed certificate is generated and written to one of the slots on the YubiKey . A private key need to exist in the slot . SLOT PIV slot where private...
controller = ctx . obj [ 'controller' ] _ensure_authenticated ( ctx , controller , pin , management_key , require_pin_and_key = True ) data = public_key . read ( ) public_key = serialization . load_pem_public_key ( data , default_backend ( ) ) now = datetime . datetime . now ( ) valid_to = now + datetime . timedelta ( ...
def _store16 ( ins ) : """Stores 2nd operand content into address of 1st operand . store16 a , x = > * ( & a ) = x Use ' * ' for indirect store on 1st operand ."""
output = [ ] output = _16bit_oper ( ins . quad [ 2 ] ) try : value = ins . quad [ 1 ] indirect = False if value [ 0 ] == '*' : indirect = True value = value [ 1 : ] value = int ( value ) & 0xFFFF if indirect : output . append ( 'ex de, hl' ) output . append ( 'ld hl, ...
def tri_area ( self , lons , lats ) : """Calculate the area enclosed by 3 points on the unit sphere . Parameters lons : array of floats , shape ( 3) longitudinal coordinates in radians lats : array of floats , shape ( 3) latitudinal coordinates in radians Returns area : float area of triangle on the...
lons , lats = self . _check_integrity ( lons , lats ) # translate to unit sphere x , y , z = _stripack . trans ( lats , lons ) # compute area area = _stripack . areas ( x , y , z ) return area
def remove_child ( self , label ) : """Removes node by label"""
ind = None for i , c in enumerate ( self . children ) : if c . label == label : ind = i if ind is None : logging . warning ( 'No child labeled {}.' . format ( label ) ) return self . children . pop ( ind ) self . _clear_all_leaves ( )
def app_factory ( global_conf , ** local_conf ) : """Returns the Pulsar WSGI application ."""
configuration_file = global_conf . get ( "__file__" , None ) webapp = init_webapp ( ini_path = configuration_file , local_conf = local_conf ) return webapp
def get_vertex_normals ( self , indexed = None ) : """Get vertex normals Parameters indexed : str | None If None , return an ( N , 3 ) array of normal vectors with one entry per unique vertex in the mesh . If indexed is ' faces ' , then the array will contain three normal vectors per face ( and some ver...
if self . _vertex_normals is None : faceNorms = self . get_face_normals ( ) vertFaces = self . get_vertex_faces ( ) self . _vertex_normals = np . empty ( self . _vertices . shape , dtype = np . float32 ) for vindex in xrange ( self . _vertices . shape [ 0 ] ) : faces = vertFaces [ vindex ] ...
def proxify_elt ( elt , bases = None , _dict = None , public = False ) : """Proxify input elt . : param elt : elt to proxify . : param bases : elt class base classes . If None , use elt type . : param dict _ dict : specific elt class content to use . : param bool public : if True ( default False ) , proxify...
# ensure _ dict is a dictionary proxy_dict = { } if _dict is None else _dict . copy ( ) # set of proxified attribute names which are proxified during bases parsing # and avoid to proxify them twice during _ dict parsing proxified_attribute_names = set ( ) # ensure bases is a tuple of types if bases is None : bases ...
def new_deploy ( py_ver : PyVer , release_target : ReleaseTarget ) : """Job for deploying package to pypi"""
cache_file = f'app_{py_ver.name}.tar' template = yaml . safe_load ( f""" machine: image: circleci/classic:201710-02 steps: - attach_workspace: at: {cache_dir} - checkout - run: name: Install prerequisites command: sudo pip install awscli - run: ...
def _transition_stage ( self , step , total_steps , brightness = None , color = None ) : """Get a transition stage at a specific step . : param step : The current step . : param total _ steps : The total number of steps . : param brightness : The brightness to transition to ( 0.0-1.0 ) . : param color : The...
if brightness is not None : self . _assert_is_brightness ( brightness ) brightness = self . _interpolate ( self . brightness , brightness , step , total_steps ) if color is not None : self . _assert_is_color ( color ) color = Color ( * [ self . _interpolate ( self . color [ i ] , color [ i ] , step , to...
def pprint ( self , composites ) : """Print out a nicely indented Mapfile"""
# if only a single composite is used then cast to list # and allow for multiple root composites if composites and not isinstance ( composites , list ) : composites = [ composites ] lines = [ ] for composite in composites : type_ = composite [ "__type__" ] if type_ in ( "metadata" , "validation" ) : # types ...
def get_ips ( v6 = False ) : """Returns all available IPs matching to interfaces , using the windows system . Should only be used as a WinPcapy fallback ."""
res = { } for iface in six . itervalues ( IFACES ) : ips = [ ] for ip in iface . ips : if v6 and ":" in ip : ips . append ( ip ) elif not v6 and ":" not in ip : ips . append ( ip ) res [ iface ] = ips return res
def add_query_occurrence ( self , report ) : """Adds a report to the report aggregation"""
initial_millis = int ( report [ 'parsed' ] [ 'stats' ] [ 'millis' ] ) mask = report [ 'queryMask' ] existing_report = self . _get_existing_report ( mask , report ) if existing_report is not None : self . _merge_report ( existing_report , report ) else : time = None if 'ts' in report [ 'parsed' ] : t...
def close ( self ) : """Logs out and quits the current web driver / selenium session ."""
if not self . driver : return try : self . driver . implicitly_wait ( 1 ) self . driver . find_element_by_id ( 'link-logout' ) . click ( ) except NoSuchElementException : pass self . driver . quit ( ) self . driver = None
def do ( self , fn , message = None , * args , ** kwargs ) : """Add a ' do ' action to the steps . This is a function to execute : param fn : A function : param message : Message indicating what this function does ( used for debugging if assertions fail )"""
self . items . put ( ChainItem ( fn , self . do , message , * args , ** kwargs ) ) return self
def accept ( self , logevent ) : """Process line . Overwrite BaseFilter . accept ( ) and return True if the provided logevent should be accepted ( causing output ) , or False if not ."""
ns = logevent . nscanned nr = logevent . nreturned if ns is not None and nr is not None : if nr == 0 : # avoid division by 0 errors nr = 1 return ( ns > 10000 and ns / nr > 100 ) return False
def _encode_params ( ** kw ) : '''do url - encode parameters > > > _ encode _ params ( a = 1 , b = ' R & D ' ) ' a = 1 & b = R % 26D ' > > > _ encode _ params ( a = u ' \u4e2d \u6587 ' , b = [ ' A ' , ' B ' , 123 ] ) ' a = % E4 % B8 % AD % E6%96%87 & b = A & b = B & b = 123' '''
args = [ ] for k , v in kw . iteritems ( ) : if isinstance ( v , basestring ) : qv = v . encode ( 'utf-8' ) if isinstance ( v , unicode ) else v args . append ( '%s=%s' % ( k , urllib . quote ( qv ) ) ) elif isinstance ( v , collections . Iterable ) : for i in v : qv = i . en...
def delete ( self , filename ) : """Delete a package or script from the distribution server . This method simply finds the Package or Script object from the database with the API GET call and then deletes it . This will remove the file from the database blob . For setups which have file share distribution p...
if is_package ( filename ) : self . connection [ "jss" ] . Package ( filename ) . delete ( ) else : self . connection [ "jss" ] . Script ( filename ) . delete ( )
def _print_app ( self , app , models ) : """Print the models of app , showing them in a package ."""
self . _print ( self . _app_start % app ) self . _print_models ( models ) self . _print ( self . _app_end )
def begin_recording ( self ) : """Open the file and write the metadata header to describe this recording . Called after we establish an end - to - end connection This uses Version 1 of our protocol Version 0 can be seen here : https : / / github . com / openai / universe / blob / f85a7779c3847fa86ec7bb513a1da0d...
logger . info ( "[RewardProxyServer] [%d] Starting recording" , self . id ) if self . _closed : logger . error ( "[RewardProxyServer] [%d] Attempted to start writing although client connection is already closed. Aborting" , self . id ) self . close ( ) return if self . _n_open_files != 0 : logger . erro...
def http_req ( blink , url = 'http://example.com' , data = None , headers = None , reqtype = 'get' , stream = False , json_resp = True , is_retry = False ) : """Perform server requests and check if reauthorization neccessary . : param blink : Blink instance : param url : URL to perform request : param data : ...
if reqtype == 'post' : req = Request ( 'POST' , url , headers = headers , data = data ) elif reqtype == 'get' : req = Request ( 'GET' , url , headers = headers ) else : _LOGGER . error ( "Invalid request type: %s" , reqtype ) raise BlinkException ( ERROR . REQUEST ) prepped = req . prepare ( ) try : ...
def hashes_get ( versions_file , base_path ) : """Gets hashes for currently checked out version . @ param versions _ file : a common . VersionsFile instance to check against . @ param base _ path : where to look for files . e . g . ' . / . update - workspace / silverstripe / ' @ return : checksums { ' file1 '...
files = versions_file . files_get_all ( ) result = { } for f in files : try : result [ f ] = functions . md5_file ( base_path + f ) except IOError : # Not all files exist for all versions . pass return result
def zoom ( self , locator , percent = "200%" , steps = 1 ) : """Zooms in on an element a certain amount ."""
driver = self . _current_application ( ) element = self . _element_find ( locator , True , True ) driver . zoom ( element = element , percent = percent , steps = steps )
def editPlan ( self , plan , new_plan ) : """Edits a plan : param plan : Plan to edit : param new _ plan : New plan : type plan : models . Plan : raises : FBchatException if request failed"""
data = { "event_reminder_id" : plan . uid , "delete" : "false" , "date" : new_plan . time , "location_name" : new_plan . location or "" , "location_id" : new_plan . location_id or "" , "title" : new_plan . title , "acontext" : ACONTEXT , } j = self . _post ( self . req_url . PLAN_CHANGE , data , fix_request = True , as...
def geocode ( * params ) : """遗憾的是拥有GFW的存在 , 导致本代码无法运行和测试 。 : param params : : return :"""
http = HTTP ( ) api = 'https://maps.google.com/maps/api/geocode/xml' headers = { 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' , 'Accept-Encoding' : 'gzip, deflate' , 'Accept-Language' : 'zh-CN,zh;q=0.8,en;q=0.6' , 'Cache-Control' : 'max-age=0' , 'Upgrade-Insecure-Re...
def build_list_marker_log ( parser : str = 'github' , list_marker : str = '.' ) -> list : r"""Create a data structure that holds list marker information . : parameter parser : decides rules on how compute indentations . Defaults to ` ` github ` ` . : parameter list _ marker : a string that contains some of th...
if ( parser == 'github' or parser == 'cmark' or parser == 'gitlab' or parser == 'commonmarker' or parser == 'redcarpet' ) : assert list_marker in md_parser [ parser ] [ 'list' ] [ 'ordered' ] [ 'closing_markers' ] list_marker_log = list ( ) if ( parser == 'github' or parser == 'cmark' or parser == 'gitlab' or parse...
def start_update ( self , draw = None , queues = None ) : """Conduct the formerly registered updates This method conducts the updates that have been registered via the : meth : ` update ` method . You can call this method if the : attr : ` no _ auto _ update ` attribute of this instance and the ` auto _ updat...
if self . plotter is not None : return self . plotter . start_update ( draw = draw , queues = queues )
def task_master ( self ) : """A ` TaskMaster ` object for manipulating work"""
if self . _task_master is None : self . _task_master = build_task_master ( self . config ) return self . _task_master
def write_login ( collector , image , ** kwargs ) : """Login to a docker registry with write permissions"""
docker_api = collector . configuration [ "harpoon" ] . docker_api collector . configuration [ "authentication" ] . login ( docker_api , image , is_pushing = True , global_docker = True )
def read_option_value_from_nibble ( nibble , pos , values ) : """Calculates the value used in the extended option fields . : param nibble : the 4 - bit option header value . : return : the value calculated from the nibble and the extended option value ."""
if nibble <= 12 : return nibble , pos elif nibble == 13 : tmp = struct . unpack ( "!B" , values [ pos ] . to_bytes ( 1 , "big" ) ) [ 0 ] + 13 pos += 1 return tmp , pos elif nibble == 14 : s = struct . Struct ( "!H" ) tmp = s . unpack_from ( values [ pos : ] . to_bytes ( 2 , "big" ) ) [ 0 ] + 269...
def snr ( test , ref , mask = None ) : """Signal - to - Noise Ratio ( SNR ) Calculate the SNR between a test image and a reference image . Parameters ref : np . ndarray the reference image test : np . ndarray the tested image mask : np . ndarray , optional the mask for the ROI Notes Compute the ...
test , ref , mask = _preprocess_input ( test , ref , mask ) if mask is not None : test = mask * test num = np . mean ( np . square ( test ) ) deno = mse ( test , ref ) return 10.0 * np . log10 ( num / deno )
def native ( name , ret , interp = None , send_interp = False ) : """Used as a decorator to add the decorated function to the pfp interpreter so that it can be used from within scripts . : param str name : The name of the function as it will be exposed in template scripts . : param pfp . fields . Field ret : ...
def native_decorator ( func ) : @ functools . wraps ( func ) def native_wrapper ( * args , ** kwargs ) : return func ( * args , ** kwargs ) pfp . interp . PfpInterp . add_native ( name , func , ret , interp = interp , send_interp = send_interp ) return native_wrapper return native_decorator
def resample_image ( arr , max_size = 400 ) : """Resamples a square image to an image of max _ size"""
dim = np . max ( arr . shape [ 0 : 2 ] ) if dim < max_size : max_size = dim x , y , _ = arr . shape sx = int ( np . ceil ( x / max_size ) ) sy = int ( np . ceil ( y / max_size ) ) img = np . zeros ( ( max_size , max_size , 3 ) , dtype = arr . dtype ) arr = arr [ 0 : - 1 : sx , 0 : - 1 : sy , : ] xl = ( max_size - a...
def mongodb_drop_database ( database_name ) : """Drop Database"""
try : mongodb_client_url = getattr ( settings , 'MONGODB_CLIENT' , 'mongodb://localhost:27017/' ) mc = MongoClient ( mongodb_client_url , document_class = OrderedDict ) mc . drop_database ( database_name ) # print " success " return "" except : # error connecting to mongodb # print str ( sys . exc _...
def get ( security_token = None , key = None ) : """Get information about this node"""
if security_token is None : security_token = nago . core . get_my_info ( ) [ 'host_name' ] data = node_data . get ( security_token , { } ) if not key : return data else : return data . get ( key )
def root ( self , names = None , wildcard = None , regex = None ) : """( Re - ) root a tree by creating selecting a existing split in the tree , or creating a new node to split an edge in the tree . Rooting location is selected by entering the tips descendant from one child of the root split ( e . g . , names...
# make a deepcopy of the tree nself = self . copy ( ) # get treenode of the common ancestor of selected tips try : node = fuzzy_match_tipnames ( nself , names , wildcard , regex , True , True ) except ToytreeError : # try reciprocal taxon list tipnames = fuzzy_match_tipnames ( nself , names , wildcard , regex ,...
def predict ( self , X ) : """Predict risk scores . Parameters X : array - like , shape = ( n _ samples , n _ features ) Data matrix . Returns risk _ score : array , shape = ( n _ samples , ) Predicted risk scores ."""
check_is_fitted ( self , "coef_" ) X = numpy . atleast_2d ( X ) return numpy . dot ( X , self . coef_ )
def interp_bin ( self , egy_bins , dtheta , scale_fn = None ) : """Evaluate the bin - averaged PSF model over the energy bins ` ` egy _ bins ` ` . Parameters egy _ bins : array _ like Energy bin edges in MeV . dtheta : array _ like Array of angular separations in degrees . scale _ fn : callable Functi...
npts = 4 egy_bins = np . exp ( utils . split_bin_edges ( np . log ( egy_bins ) , npts ) ) egy = np . exp ( utils . edge_to_center ( np . log ( egy_bins ) ) ) log_energies = np . log10 ( egy ) vals = self . interp ( egy [ None , : ] , dtheta [ : , None ] , scale_fn = scale_fn ) wts = np . exp ( self . _wts_fn ( ( log_en...
def show_fibrechannel_interface_info_input_all ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_fibrechannel_interface_info = ET . Element ( "show_fibrechannel_interface_info" ) config = show_fibrechannel_interface_info input = ET . SubElement ( show_fibrechannel_interface_info , "input" ) all = ET . SubElement ( input , "all" ) callback = kwargs . pop ( 'callback' , self ....
def down_capture ( self , benchmark , threshold = 0.0 , compare_op = "lt" ) : """Downside capture ratio . Measures the performance of ` self ` relative to benchmark conditioned on periods where ` benchmark ` is lt or le to ` threshold ` . Downside capture ratios are calculated by taking the fund ' s month...
slf , bm = self . downmarket_filter ( benchmark = benchmark , threshold = threshold , compare_op = compare_op , include_benchmark = True , ) return slf . geomean ( ) / bm . geomean ( )
def upsert ( self , name , value = None , seq = None ) : """Add one name / value entry to the main context of the rolne , but only if an entry with that name does not already exist . If the an entry with name exists , then the first entry found has it ' s value changed . NOTE : the upsert only updates the F...
for ctr , entry in enumerate ( self . data ) : if entry [ TNAME ] == name : new_tuple = ( name , value , entry [ TLIST ] , entry [ TSEQ ] ) self . data [ ctr ] = new_tuple return False new_tuple = ( name , value , [ ] , lib . _seq ( self , seq ) ) self . data . append ( new_tuple ) return Tr...
def apply_transform ( self , matrix ) : """Apply a transform to the current primitive ( sets self . transform ) Parameters matrix : ( 4,4 ) float , homogenous transformation"""
matrix = np . asanyarray ( matrix , order = 'C' , dtype = np . float64 ) if matrix . shape != ( 4 , 4 ) : raise ValueError ( 'Transformation matrix must be (4,4)!' ) if np . allclose ( matrix , np . eye ( 4 ) ) : log . debug ( 'apply_tranform received identity matrix' ) return new_transform = np . dot ( mat...
def _get_es_version ( self , config ) : """Get the running version of elasticsearch ."""
try : data = self . _get_data ( config . url , config , send_sc = False ) # pre - release versions of elasticearch are suffixed with - rcX etc . . # peel that off so that the map below doesn ' t error out version = data [ 'version' ] [ 'number' ] . split ( '-' ) [ 0 ] version = [ int ( p ) for p in ...
def add_comment ( self , issue , body , visibility = None , is_internal = False ) : """Add a comment from the current authenticated user on the specified issue and return a Resource for it . The issue identifier and comment body are required . : param issue : ID or key of the issue to add the comment to : typ...
data = { 'body' : body , } if is_internal : data . update ( { 'properties' : [ { 'key' : 'sd.public.comment' , 'value' : { 'internal' : is_internal } } ] } ) if visibility is not None : data [ 'visibility' ] = visibility url = self . _get_url ( 'issue/' + str ( issue ) + '/comment' ) r = self . _session . post ...
def rmd160 ( msg_bytes ) : '''byte - like - > bytes'''
h = hashlib . new ( 'ripemd160' ) h . update ( msg_bytes ) return h . digest ( )
def validate_ip ( s ) : """Validate a dotted - quad ip address . The string is considered a valid dotted - quad address if it consists of one to four octets ( 0-255 ) seperated by periods ( . ) . > > > validate _ ip ( ' 127.0.0.1 ' ) True > > > validate _ ip ( ' 127.0 ' ) True > > > validate _ ip ( ' ...
if _DOTTED_QUAD_RE . match ( s ) : quads = s . split ( '.' ) for q in quads : if int ( q ) > 255 : return False return True return False
def submit ( self , func , * args , ** kwargs ) : """Submit a function to the pool , ` self . submit ( function , arg1 , arg2 , arg3 = 3 ) `"""
with self . _shutdown_lock : if self . _shutdown : raise RuntimeError ( "cannot schedule new futures after shutdown" ) callback = kwargs . pop ( "callback" , self . default_callback ) future = NewFuture ( self . _timeout , args , kwargs , callback = callback , catch_exception = self . catch_exceptio...
def dissociate ( self ) : """Dissociate previously associated model from the given parent . : rtype : eloquent . Model"""
self . _parent . set_attribute ( self . _foreign_key , None ) return self . _parent . set_relation ( self . _relation , None )
def namedtuple_storable ( namedtuple , * args , ** kwargs ) : """Storable factory for named tuples ."""
return default_storable ( namedtuple , namedtuple . _fields , * args , ** kwargs )
def path_join ( * args ) : 'Joins ShellQuoted and raw pieces of paths to make a shell - quoted path'
return ShellQuoted ( os . path . join ( * [ raw_shell ( shell_quote ( s ) ) for s in args ] ) )
def fit ( self , analysis , grid_priors ) : """Fit an analysis with a set of grid priors . The grid priors are priors associated with the model mapper of this instance that are replaced by uniform priors for each step of the grid search . Parameters analysis : non _ linear . Analysis An analysis used to det...
grid_priors = list ( set ( grid_priors ) ) results = [ ] lists = self . make_lists ( grid_priors ) results_list = [ list ( map ( self . variable . name_for_prior , grid_priors ) ) + [ "figure_of_merit" ] ] def write_results ( ) : with open ( "{}/results" . format ( self . phase_output_path ) , "w+" ) as f : ...
def _build_sliced_filepath ( filename , slice_count ) : """append slice _ count to the end of a filename"""
root = os . path . splitext ( filename ) [ 0 ] ext = os . path . splitext ( filename ) [ 1 ] new_filepath = '' . join ( ( root , str ( slice_count ) , ext ) ) return _build_filepath_for_phantomcss ( new_filepath )
def ndsname ( self ) : """Name of this channel as stored in the NDS database"""
if self . type not in [ None , 'raw' , 'reduced' , 'online' ] : return '%s,%s' % ( self . name , self . type ) return self . name
def register_response ( self , correlation_id = None ) : """Register the receiving of a RPC response . Will return the given correlation _ id after registering , or if correlation _ id is None , will generate a correlation _ id and return it after registering . If the given correlation _ id has already been used ...
if not correlation_id : correlation_id = str ( uuid . uuid1 ( ) ) if correlation_id in self . responses : raise KeyError ( "Correlation_id {0} was already registered, and therefor not unique." . format ( correlation_id ) ) self . responses [ correlation_id ] = None return correlation_id
def iter_settings ( mixed : Settings ) -> Iterator [ Tuple [ str , Any ] ] : """Iterate over settings values from settings module or dict - like instance . : param mixed : Settings instance to iterate ."""
if isinstance ( mixed , types . ModuleType ) : for attr in dir ( mixed ) : if not is_setting_key ( attr ) : continue yield ( attr , getattr ( mixed , attr ) ) else : yield from filter ( lambda item : is_setting_key ( item [ 0 ] ) , mixed . items ( ) )
def parse_xml_node ( self , node ) : '''Parse an xml . dom Node object representing a component into this object . > > > c = Component ( )'''
self . _reset ( ) # Get the attributes self . id = node . getAttributeNS ( RTS_NS , 'id' ) self . path_uri = node . getAttributeNS ( RTS_NS , 'pathUri' ) if node . hasAttributeNS ( RTS_NS , 'activeConfigurationSet' ) : self . active_configuration_set = node . getAttributeNS ( RTS_NS , 'activeConfigurationSet' ) els...
def memory_data ( ) : """Returns memory data ."""
vm = psutil . virtual_memory ( ) sw = psutil . swap_memory ( ) return { 'virtual' : { 'total' : mark ( vm . total , 'bytes' ) , 'free' : mark ( vm . free , 'bytes' ) , 'percent' : mark ( vm . percent , 'percentage' ) } , 'swap' : { 'total' : mark ( sw . total , 'bytes' ) , 'free' : mark ( sw . free , 'bytes' ) , 'perce...
def _iter_serial_enum_member ( eid , value , bitmask ) : """Iterate serial and CID of enum members with given value and bitmask . Here only valid values are returned , as ` idaapi . BADNODE ` always indicates an invalid member ."""
cid , serial = idaapi . get_first_serial_enum_member ( eid , value , bitmask ) while cid != idaapi . BADNODE : yield cid , serial cid , serial = idaapi . get_next_serial_enum_member ( cid , serial )
def delete ( self , resource , url_prefix , auth , session , send_opts ) : """Deletes the entity described by the given resource . Args : resource ( intern . resource . boss . BossResource ) url _ prefix ( string ) : Protocol + host such as https : / / api . theboss . io auth ( string ) : Token to send in t...
req = self . get_request ( resource , 'DELETE' , 'application/json' , url_prefix , auth ) prep = session . prepare_request ( req ) resp = session . send ( prep , ** send_opts ) if resp . status_code == 204 : return err = ( 'Delete failed on {}, got HTTP response: ({}) - {}' . format ( resource . name , resp . statu...
def ProtoFromTfRecordFiles ( files , max_entries = 10000 , features = None , is_sequence = False , iterator_options = None ) : """Creates a feature statistics proto from a set of TFRecord files . Args : files : A list of dicts describing files for each dataset for the proto . Each entry contains a ' path ' ...
warnings . warn ( 'Use GenericFeatureStatisticsGenerator class method instead.' , DeprecationWarning ) return FeatureStatisticsGenerator ( ) . ProtoFromTfRecordFiles ( files , max_entries , features , is_sequence , iterator_options )
def _tag_ec2 ( self , conn , role ) : """tag the current EC2 instance with a cluster role"""
tags = { 'Role' : role } conn . create_tags ( [ self . instance_id ] , tags )
def makePro ( segID , N , CA , C , O , geo ) : '''Creates a Proline residue'''
# # R - Group CA_CB_length = geo . CA_CB_length C_CA_CB_angle = geo . C_CA_CB_angle N_C_CA_CB_diangle = geo . N_C_CA_CB_diangle CB_CG_length = geo . CB_CG_length CA_CB_CG_angle = geo . CA_CB_CG_angle N_CA_CB_CG_diangle = geo . N_CA_CB_CG_diangle CG_CD_length = geo . CG_CD_length CB_CG_CD_angle = geo . CB_CG_CD_angle CA...
def allskyfinder ( self , figsize = ( 14 , 7 ) , ** kwargs ) : '''Plot an all - sky finder chart . This * does * create a new figure .'''
plt . figure ( figsize = figsize ) scatter = self . plot ( ** kwargs ) plt . xlabel ( r'Right Ascension ($^\circ$)' ) ; plt . ylabel ( r'Declination ($^\circ$)' ) # plt . title ( ' { } in { : . 1f } ' . format ( self . name , epoch ) ) plt . xlim ( 0 , 360 ) plt . ylim ( - 90 , 90 ) return scatter
def parse_example_proto ( example_serialized ) : """Parses an Example proto containing a training example of an image . The output of the build _ image _ data . py image preprocessing script is a dataset containing serialized Example protocol buffers . Each Example proto contains the following fields : imag...
# Dense features in Example proto . feature_map = { 'image/encoded' : tf . FixedLenFeature ( [ ] , dtype = tf . string , default_value = '' ) , 'image/class/label' : tf . FixedLenFeature ( [ 1 ] , dtype = tf . int64 , default_value = - 1 ) , 'image/class/text' : tf . FixedLenFeature ( [ ] , dtype = tf . string , defaul...
async def _send ( self , stream_id , pp_id , user_data , expiry = None , max_retransmits = None , ordered = True ) : """Send data ULP - > stream ."""
if ordered : stream_seq = self . _outbound_stream_seq . get ( stream_id , 0 ) else : stream_seq = 0 fragments = math . ceil ( len ( user_data ) / USERDATA_MAX_LENGTH ) pos = 0 for fragment in range ( 0 , fragments ) : chunk = DataChunk ( ) chunk . flags = 0 if not ordered : chunk . flags = S...
def opensearch_dispatch ( request ) : """OpenSearch wrapper"""
ctx = { 'shortname' : settings . REGISTRY_PYCSW [ 'metadata:main' ] [ 'identification_title' ] , 'description' : settings . REGISTRY_PYCSW [ 'metadata:main' ] [ 'identification_abstract' ] , 'developer' : settings . REGISTRY_PYCSW [ 'metadata:main' ] [ 'contact_name' ] , 'contact' : settings . REGISTRY_PYCSW [ 'metadat...
def getBytes ( self ) -> list : '''Returns the Root layer as list with bytes'''
tmpList = [ ] tmpList . extend ( _FIRST_INDEX ) # first append the high byte from the Flags and Length # high 4 bit : 0x7 then the bits 8-11 ( indexes ) from _ length length = self . length - 16 tmpList . append ( ( 0x7 << 4 ) + ( length >> 8 ) ) # Then append the lower 8 bits from _ length tmpList . append ( length & ...
def update_data ( self ) : """Returns data for all users including shared data files ."""
url = ( 'https://www.openhumans.org/api/direct-sharing/project/' 'members/?access_token={}' . format ( self . master_access_token ) ) results = get_all_results ( url ) self . project_data = dict ( ) for result in results : self . project_data [ result [ 'project_member_id' ] ] = result if len ( result [ 'data' ...
def verify_signature ( key_dict , signature , data ) : """< Purpose > Determine whether the private key belonging to ' key _ dict ' produced ' signature ' . verify _ signature ( ) will use the public key found in ' key _ dict ' , the ' sig ' objects contained in ' signature ' , and ' data ' to complete the ...
# Does ' key _ dict ' have the correct format ? # This check will ensure ' key _ dict ' has the appropriate number # of objects and object types , and that all dict keys are properly named . # Raise ' securesystemslib . exceptions . FormatError ' if the check fails . securesystemslib . formats . ANYKEY_SCHEMA . check_m...
def _sitesettings_files ( ) : """Get a list of sitesettings files settings . py can be prefixed with a subdomain and underscore so with example . com site : sitesettings / settings . py would be the example . com settings file and sitesettings / admin _ settings . py would be the admin . example . com setting...
settings_files = [ ] sitesettings_path = os . path . join ( env . project_package_name , 'sitesettings' ) if os . path . exists ( sitesettings_path ) : sitesettings = os . listdir ( sitesettings_path ) for file in sitesettings : if file == 'settings.py' : settings_files . append ( file ) ...
def convert_surfaces ( self , parent , alpha = False ) : """Convert all images in the data to match the parent : param parent : pygame . Surface : param alpha : preserve alpha channel or not : return : None"""
images = list ( ) for i in self . tmx . images : try : if alpha : images . append ( i . convert_alpha ( parent ) ) else : images . append ( i . convert ( parent ) ) except AttributeError : images . append ( None ) self . tmx . images = images
def init_atropos_wf ( name = 'atropos_wf' , use_random_seed = True , omp_nthreads = None , mem_gb = 3.0 , padding = 10 , in_segmentation_model = list ( ATROPOS_MODELS [ 'T1w' ] . values ( ) ) ) : """Implements supersteps 6 and 7 of ` ` antsBrainExtraction . sh ` ` , which refine the mask previously computed with ...
wf = pe . Workflow ( name ) inputnode = pe . Node ( niu . IdentityInterface ( fields = [ 'in_files' , 'in_mask' , 'in_mask_dilated' ] ) , name = 'inputnode' ) outputnode = pe . Node ( niu . IdentityInterface ( fields = [ 'out_mask' , 'out_segm' , 'out_tpms' ] ) , name = 'outputnode' ) # Run atropos ( core node ) atropo...
def format_field ( self , value , spec ) : """Provide the additional formatters for localization ."""
if spec . startswith ( 'date:' ) : _ , format_ = spec . split ( ':' , 1 ) return self . format_date ( value , format_ ) elif spec . startswith ( 'datetime:' ) : _ , format_ = spec . split ( ':' , 1 ) return self . format_datetime ( value , format_ ) elif spec == 'number' : return self . format_numbe...
def get_vnetwork_hosts_output_vnetwork_hosts_interface_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_vnetwork_hosts = ET . Element ( "get_vnetwork_hosts" ) config = get_vnetwork_hosts output = ET . SubElement ( get_vnetwork_hosts , "output" ) vnetwork_hosts = ET . SubElement ( output , "vnetwork-hosts" ) interface_name = ET . SubElement ( vnetwork_hosts , "interface-name" ) inter...
def remove_constraint ( self , name ) : """Remove a constraint from the problem"""
index = self . _get_constraint_index ( name ) # Remove from matrix self . _A = np . delete ( self . A , index , 0 ) # Remove from upper _ bounds self . upper_bounds = np . delete ( self . upper_bounds , index ) # Remove from constraint list del self . _constraints [ name ] self . _update_constraint_indices ( ) self . _...
def encode ( self , delimiter = ';' ) : """Encode a command string from message ."""
try : return delimiter . join ( [ str ( f ) for f in [ self . node_id , self . child_id , int ( self . type ) , self . ack , int ( self . sub_type ) , self . payload , ] ] ) + '\n' except ValueError : _LOGGER . error ( 'Error encoding message to gateway' )
def pull ( self , dict_name ) : '''Get the entire contents of a single dictionary . This operates without a session lock , but is still atomic . In particular this will run even if someone else holds a session lock and you do not . This is only suitable for " small " dictionaries ; if you have hundreds of...
dict_name = self . _namespace ( dict_name ) conn = redis . Redis ( connection_pool = self . pool ) res = conn . hgetall ( dict_name ) split_res = dict ( [ ( self . _decode ( key ) , self . _decode ( value ) ) for key , value in res . iteritems ( ) ] ) return split_res
def update_col ( self , column_name , series ) : """Add or replace a column in the underlying DataFrame . Parameters column _ name : str Column to add or replace . series : pandas . Series or sequence Column data ."""
logger . debug ( 'updating column {!r} in table {!r}' . format ( column_name , self . name ) ) self . local [ column_name ] = series
def get_return_from ( self , e_handler ) : """Setter of the following attributes : : * exit _ status * output * long _ output * check _ time * execution _ time * perf _ data : param e _ handler : event handler to get data from : type e _ handler : alignak . eventhandler . EventHandler : return : N...
for prop in [ 'exit_status' , 'output' , 'long_output' , 'check_time' , 'execution_time' , 'perf_data' ] : setattr ( self , prop , getattr ( e_handler , prop ) )
def __check_existing ( self , row ) : """Check if row exists in table"""
if self . __update_keys is not None : key = tuple ( row [ key ] for key in self . __update_keys ) if key in self . __bloom : return True self . __bloom . add ( key ) return False return False
def add_user ( name , password = None , runas = None ) : '''Add a rabbitMQ user via rabbitmqctl user _ add < user > < password > CLI Example : . . code - block : : bash salt ' * ' rabbitmq . add _ user rabbit _ user password'''
clear_pw = False if password is None : # Generate a random , temporary password . RabbitMQ requires one . clear_pw = True password = '' . join ( random . SystemRandom ( ) . choice ( string . ascii_uppercase + string . digits ) for x in range ( 15 ) ) if runas is None and not salt . utils . platform . is_windows...
def is_ordered_dict ( d ) : """Predicate checking for ordered dictionaries . OrderedDict is always ordered , and vanilla Python dictionaries are ordered for Python 3.6 +"""
py3_ordered_dicts = ( sys . version_info . major == 3 ) and ( sys . version_info . minor >= 6 ) vanilla_odicts = ( sys . version_info . major > 3 ) or py3_ordered_dicts return isinstance ( d , ( OrderedDict ) ) or ( vanilla_odicts and isinstance ( d , dict ) )
def render ( self , * args , ** data ) : """Render the output of this template as a string . If the template specifies an output encoding , the string will be encoded accordingly , else the output is raw ( raw output uses ` cStringIO ` and can ' t handle multibyte characters ) . A : class : ` . Context ` ob...
return runtime . _render ( self , self . callable_ , args , data )
def _lookup_global ( self , symbol ) : """Helper for lookup _ symbol that only looks up global variables . Args : symbol : Symbol"""
assert symbol . parts namespace = self . namespaces if len ( symbol . parts ) == 1 : # If there is only one part , look in globals . namespace = self . namespaces [ None ] try : # Try to do a normal , global namespace lookup . return self . _lookup_namespace ( symbol , namespace ) except Error as orig_exc : ...
def present ( name , auth = None , ** kwargs ) : '''Ensure domain exists and is up - to - date name Name of the domain enabled Boolean to control if domain is enabled description An arbitrary description of the domain'''
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } kwargs = __utils__ [ 'args.clean_kwargs' ] ( ** kwargs ) __salt__ [ 'keystoneng.setup_clouds' ] ( auth ) domain = __salt__ [ 'keystoneng.domain_get' ] ( name = name ) if not domain : if __opts__ [ 'test' ] : ret [ 'result' ] = None...
def apply_to_type ( input_ , input_type , func ) : """Apply a function on a object of ` input _ type ` or mapping , or sequence of objects of ` input _ type ` ."""
if isinstance ( input_ , input_type ) : return func ( input_ ) elif isinstance ( input_ , string_classes ) : return input_ elif isinstance ( input_ , collections . Mapping ) : return { k : apply_to_type ( sample , input_type , func ) for k , sample in input_ . items ( ) } elif isinstance ( input_ , collecti...
def compose ( func_list ) : """composion of preprocessing functions"""
def f ( G , bim ) : for func in func_list : G , bim = func ( G , bim ) return G , bim return f
def add ( self , parent , obj_type , ** attributes ) : """IXN API add command @ param parent : object parent - object will be created under this parent . @ param object _ type : object type . @ param attributes : additional attributes . @ return : IXN object reference ."""
return self . ixnCommand ( 'add' , parent . obj_ref ( ) , obj_type , get_args_pairs ( attributes ) )
def ReadFile ( self , filename ) : """Reads artifact definitions from a file . Args : filename ( str ) : name of the file to read from . Yields : ArtifactDefinition : an artifact definition ."""
with io . open ( filename , 'r' , encoding = 'utf-8' ) as file_object : for artifact_definition in self . ReadFileObject ( file_object ) : yield artifact_definition