signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def generate_raml_docs ( module , fields , shared_types , user = None , title = "My API" , version = "v1" , api_root = "api" , base_uri = "http://mysite.com/{version}" ) : """Return a RAML file of a Pale module ' s documentation as a string . The user argument is optional . If included , it expects the user to be...
output = StringIO ( ) # Add the RAML header info output . write ( '#%RAML 1.0 \n' ) output . write ( 'title: ' + title + ' \n' ) output . write ( 'baseUri: ' + base_uri + ' \n' ) output . write ( 'version: ' + version + '\n' ) output . write ( 'mediaType: application/json\n\n' ) output . write ( 'documentation:\n' ) ou...
def logging_subsystem ( self ) : """A collection of logging subsystem statuses : rtype : Status"""
for item in self : if item . name . startswith ( 'Logging' ) : for s in item_status ( item ) : yield s
def maybe_reverse_features ( self , feature_map ) : """Reverse features between inputs and targets if the problem is ' _ rev ' ."""
if not self . _was_reversed : return inputs = feature_map . pop ( "inputs" , None ) targets = feature_map . pop ( "targets" , None ) inputs_seg = feature_map . pop ( "inputs_segmentation" , None ) targets_seg = feature_map . pop ( "targets_segmentation" , None ) inputs_pos = feature_map . pop ( "inputs_position" , ...
def delete_local_docker_cache ( docker_tag ) : """Delete the local docker cache for the entire docker image chain : param docker _ tag : Docker tag : return : None"""
history_cmd = [ 'docker' , 'history' , '-q' , docker_tag ] try : image_ids_b = subprocess . check_output ( history_cmd ) image_ids_str = image_ids_b . decode ( 'utf-8' ) . strip ( ) layer_ids = [ id . strip ( ) for id in image_ids_str . split ( '\n' ) if id != '<missing>' ] delete_cmd = [ 'docker' , 'im...
def get_version_url ( self , version ) : """Retrieve the URL for the designated version of the hive ."""
for each_version in self . other_versions ( ) : if version == each_version [ 'version' ] and 'location' in each_version : return each_version . get ( 'location' ) raise VersionNotInHive ( version )
def _add_keyword ( self , collection_id , name , doc , args ) : """Insert data into the keyword table ' args ' should be a list , but since we can ' t store a list in an sqlite database we ' ll make it json we can can convert it back to a list later ."""
argstring = json . dumps ( args ) self . db . execute ( """ INSERT INTO keyword_table (collection_id, name, doc, args) VALUES (?,?,?,?) """ , ( collection_id , name , doc , argstring ) )
def publish_server_closed ( self , server_address , topology_id ) : """Publish a ServerClosedEvent to all server listeners . : Parameters : - ` server _ address ` : The address ( host / port pair ) of the server . - ` topology _ id ` : A unique identifier for the topology this server is a part of ."""
event = ServerClosedEvent ( server_address , topology_id ) for subscriber in self . __server_listeners : try : subscriber . closed ( event ) except Exception : _handle_exception ( )
def _add_initial_value ( self , data_id , value , initial_dist = 0.0 , fringe = None , check_cutoff = None , no_call = None ) : """Add initial values updating workflow , seen , and fringe . : param fringe : Heapq of closest available nodes . : type fringe : list [ ( float | int , bool , ( str , Dispatcher ) ]...
# Namespace shortcuts for speed . nodes , seen , edge_weight = self . nodes , self . seen , self . _edge_length wf_remove_edge , check_wait_in = self . _wf_remove_edge , self . check_wait_in wf_add_edge , dsp_in = self . _wf_add_edge , self . _set_sub_dsp_node_input update_view = self . _update_meeting if fringe is Non...
def set_record ( self , name , record_id , record ) : """Save a record into the cache . Args : name ( string ) : The name to save the model under . record _ id ( int ) : The record id . record ( : class : ` cinder _ data . model . CinderModel ` ) : The model"""
if name not in self . _cache : self . _cache [ name ] = { } self . _cache [ name ] [ record_id ] = record
def use_setuptools ( version = DEFAULT_VERSION , download_base = DEFAULT_URL , to_dir = DEFAULT_SAVE_DIR , download_delay = 15 ) : """Ensure that a setuptools version is installed . Return None . Raise SystemExit if the requested version or later cannot be installed ."""
to_dir = os . path . abspath ( to_dir ) # prior to importing , capture the module state for # representative modules . rep_modules = 'pkg_resources' , 'setuptools' imported = set ( sys . modules ) . intersection ( rep_modules ) try : import pkg_resources pkg_resources . require ( "setuptools>=" + version ) ...
def locate_file ( filename , env_var = '' , directory = '' ) : """Locates a file given an environment variable or directory : param filename : filename to search for : param env _ var : environment variable to look under : param directory : directory to look in : return : ( string ) absolute path to filenam...
f = locate_by_env ( filename , env_var ) or locate_by_dir ( filename , directory ) return os . path . abspath ( f ) if can_locate ( f ) else None
def get_previous_tag ( cls , el ) : """Get previous sibling tag ."""
sibling = el . previous_sibling while not cls . is_tag ( sibling ) and sibling is not None : sibling = sibling . previous_sibling return sibling
def split_if_nodes ( graph ) : """Split IfNodes in two nodes , the first node is the header node , the second one is only composed of the jump condition ."""
node_map = { n : n for n in graph } to_update = set ( ) for node in graph . nodes [ : ] : if node . type . is_cond : if len ( node . get_ins ( ) ) > 1 : pre_ins = node . get_ins ( ) [ : - 1 ] last_ins = node . get_ins ( ) [ - 1 ] pre_node = StatementBlock ( '%s-pre' % nod...
def dispatch ( self , * args , ** kwargs ) : """This decorator sets this view to have restricted permissions ."""
return super ( AnimalList , self ) . dispatch ( * args , ** kwargs )
def _get_lowstate ( self ) : '''Format the incoming data into a lowstate object'''
if not self . request . body : return data = self . deserialize ( self . request . body ) self . request_payload = copy ( data ) if data and 'arg' in data and not isinstance ( data [ 'arg' ] , list ) : data [ 'arg' ] = [ data [ 'arg' ] ] if not isinstance ( data , list ) : lowstate = [ data ] else : low...
def sign_execute_cancellation ( cancellation_params , private_key ) : """Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange . Execution of this function is as follows : : sign _ execute _ cancellation ( cancellation _ params = signable _ params , private _ key = ...
cancellation_sha256 = cancellation_params [ 'transaction' ] [ 'sha256' ] signed_sha256 = binascii . hexlify ( Account . signHash ( cancellation_sha256 , private_key = private_key ) [ 'signature' ] ) . decode ( ) return { 'signature' : '0x' + signed_sha256 }
def validate ( cls , mapper_spec ) : """Validate mapper specification . Args : mapper _ spec : an instance of model . MapperSpec . Raises : BadWriterParamsError : if the specification is invalid for any reason such as missing the bucket name or providing an invalid bucket name ."""
writer_spec = cls . get_params ( mapper_spec , allow_old = False ) # Bucket Name is required if cls . BUCKET_NAME_PARAM not in writer_spec : raise errors . BadWriterParamsError ( "%s is required for Google Cloud Storage" % cls . BUCKET_NAME_PARAM ) try : cloudstorage . validate_bucket_name ( writer_spec [ cls ....
def iter_surrounding ( self , center_key ) : """Iterate over all bins surrounding the given bin"""
for shift in self . neighbor_indexes : key = tuple ( np . add ( center_key , shift ) . astype ( int ) ) if self . integer_cell is not None : key = self . wrap_key ( key ) bin = self . _bins . get ( key ) if bin is not None : yield key , bin
def accept ( self ) : """Process the layer for multi buffering and generate a new layer . . . note : : This is called on OK click ."""
# set parameter from dialog input_layer = self . layer . currentLayer ( ) output_path = self . output_form . text ( ) radius = self . get_classification ( ) # monkey patch keywords so layer works on multi buffering function input_layer . keywords = { 'inasafe_fields' : { } } # run multi buffering self . output_layer = ...
def render_before_sections ( self ) : """Render the form up to the first section . This will open the form tag but not close it ."""
return Markup ( env . get_template ( 'form.html' ) . render ( form = self , render_open_tag = True , render_close_tag = False , render_before = True , render_sections = False , render_after = False , generate_csrf_token = None if self . action else _csrf_generation_function ) )
def _read_ent ( ent_file ) : """Read notes stored in . ent file . This is a basic implementation , that relies on turning the information in the string in the dict format , and then evaluate it . It ' s not very flexible and it might not read some notes , but it ' s fast . I could not implement a nice , rec...
with ent_file . open ( 'rb' ) as f : f . seek ( 352 ) # end of header note_hdr_length = 16 allnote = [ ] while True : note = { } note [ 'type' ] , = unpack ( '<i' , f . read ( 4 ) ) note [ 'length' ] , = unpack ( '<i' , f . read ( 4 ) ) note [ 'prev_length' ] , = unpa...
def contains_exclusive ( self , x , y ) : """Return True if the given point is contained within the bounding box , where the bottom and right boundaries are considered exclusive ."""
left , bottom , right , top = self . _aarect . lbrt ( ) return ( left <= x < right ) and ( bottom < y <= top )
def _add ( self , codeobj ) : """Add a child ( variable ) to this object ."""
assert isinstance ( codeobj , CodeVariable ) self . variables . append ( codeobj )
def _get_place_details ( place_id , api_key , sensor = False , language = lang . ENGLISH ) : """Gets a detailed place response . keyword arguments : place _ id - - The unique identifier for the required place ."""
url , detail_response = _fetch_remote_json ( GooglePlaces . DETAIL_API_URL , { 'placeid' : place_id , 'sensor' : str ( sensor ) . lower ( ) , 'key' : api_key , 'language' : language } ) _validate_response ( url , detail_response ) return detail_response [ 'result' ]
def get_auth_token ( self , is_retry = False ) : """Retrieve the authentication token from Blink ."""
if not isinstance ( self . _username , str ) : raise BlinkAuthenticationException ( ERROR . USERNAME ) if not isinstance ( self . _password , str ) : raise BlinkAuthenticationException ( ERROR . PASSWORD ) login_urls = [ LOGIN_URL , OLD_LOGIN_URL , LOGIN_BACKUP_URL ] response = self . login_request ( login_urls...
def multiply ( a , col ) : """Multiply a matrix by one column ."""
a = a . reshape ( 4 , 4 , 4 ) col = col . reshape ( 4 , 8 ) return fcat ( rowxcol ( a [ 0 ] , col ) , rowxcol ( a [ 1 ] , col ) , rowxcol ( a [ 2 ] , col ) , rowxcol ( a [ 3 ] , col ) , )
def from_dict ( cls , data , model ) : """Generate map of ` fieldName : clsInstance ` from dict . : param data : Dict where keys are field names and values are new values of field . : param model : Model class to which fields from : data : belong ."""
model_provided = model is not None result = { } for name , new_value in data . items ( ) : kwargs = { 'name' : name , 'new_value' : new_value , } if model_provided : kwargs [ 'params' ] = model . get_field_params ( name ) result [ name ] = cls ( ** kwargs ) return result
def replace_launch_config ( self , scaling_group , launch_config_type , server_name , image , flavor , disk_config = None , metadata = None , personality = None , networks = None , load_balancers = None , key_name = None ) : """Replace an existing launch configuration . All of the attributes must be specified . I...
return self . _manager . replace_launch_config ( scaling_group , launch_config_type , server_name , image , flavor , disk_config = disk_config , metadata = metadata , personality = personality , networks = networks , load_balancers = load_balancers , key_name = key_name )
def install ( name = None , refresh = False , fromrepo = None , pkgs = None , sources = None , ** kwargs ) : '''Install the passed package name The name of the package to be installed . refresh Whether or not to refresh the package database before installing . fromrepo Specify a package repository to in...
try : pkg_params , pkg_type = __salt__ [ 'pkg_resource.parse_targets' ] ( name , pkgs , sources , ** kwargs ) except MinionError as exc : raise CommandExecutionError ( exc ) # Support old " repo " argument repo = kwargs . get ( 'repo' , '' ) if not fromrepo and repo : fromrepo = repo if not pkg_params : ...
def tilt ( poly ) : """Tilt of a polygon poly"""
num = len ( poly ) - 1 vec = unit_normal ( poly [ 0 ] , poly [ 1 ] , poly [ num ] ) vec_alt = np . array ( [ vec [ 0 ] , vec [ 1 ] , vec [ 2 ] ] ) vec_z = np . array ( [ 0 , 0 , 1 ] ) # return ( 90 - angle2vecs ( vec _ alt , vec _ z ) ) # update by Santosh return angle2vecs ( vec_alt , vec_z )
def add_application ( self , application , sync = True ) : """add an application to this OS instance . : param application : the application to add on this OS instance : param sync : If sync = True ( default ) synchronize with Ariane server . If sync = False , add the application object on list to be added on...
LOGGER . debug ( "OSInstance.add_application" ) if not sync : self . application_2_add . append ( application ) else : if application . id is None : application . save ( ) if self . id is not None and application . id is not None : params = { 'id' : self . id , 'applicationID' : application ...
def translate_rhumb ( ra , dec , r , theta ) : """Translate a given point a distance r in the ( initial ) direction theta , along a Rhumb line . Parameters ra , dec : float The initial point of interest ( degrees ) . r , theta : float The distance and initial direction to translate ( degrees ) . Returns...
# verified against website to give correct results # with the help of http : / / williams . best . vwh . net / avform . htm # Rhumb delta = np . radians ( r ) phi1 = np . radians ( dec ) phi2 = phi1 + delta * np . cos ( np . radians ( theta ) ) dphi = phi2 - phi1 if abs ( dphi ) < 1e-9 : q = np . cos ( phi1 ) else ...
def get_package_dir ( nb_path ) : """Return the package directory for a Notebook that has an embeded Metatab doc , * not * for notebooks that are part of a package"""
doc = get_metatab_doc ( nb_path ) doc . update_name ( force = True , create_term = True ) pkg_name = doc [ 'Root' ] . get_value ( 'Root.Name' ) assert pkg_name return ensure_source_package_dir ( nb_path , pkg_name ) , pkg_name
def get_file_type_map ( ) : """Map file types ( extensions ) to strategy types ."""
file_type_map = { } for strategy_type in get_strategy_types ( ) : for ext in strategy_type . file_types : if ext in file_type_map : raise KeyError ( 'File type {ext} already registered to {file_type_map[ext]}' . format ( ** locals ( ) ) ) file_type_map [ ext ] = strategy_type return file...
def energy ( self ) : """Calculate state ' s energy ."""
arr = self . src . copy ( ) arr = self . apply_color ( arr , self . state ) scores = [ histogram_distance ( self . ref [ i ] , arr [ i ] ) for i in range ( 3 ) ] # Important : scale by 100 for readability return sum ( scores ) * 100
def SNR ( img1 , img2 = None , bg = None , noise_level_function = None , constant_noise_level = False , imgs_to_be_averaged = False ) : '''Returns a signal - to - noise - map uses algorithm as described in BEDRICH 2016 JPV ( not jet published ) : param constant _ noise _ level : True , to assume noise to be con...
# dark current subtraction : img1 = np . asfarray ( img1 ) if bg is not None : img1 = img1 - bg # SIGNAL : if img2 is not None : img2_exists = True img2 = np . asfarray ( img2 ) - bg # signal as average on both images signal = 0.5 * ( img1 + img2 ) else : img2_exists = False signal = img1 # ...
def _decompose_ ( self , qubits ) : """A quantum circuit ( QFT _ inv ) with the following structure . - - - - - @ ^ - 0.5 - - + - - - - - + - - - - - H - - @ - - - - - @ - - - - - - - - - - @ ^ - 0.25 - - + - - - - - @ ^ - 0.5 - - + - - - - - H - - @ - - - - - - - - - - @ ^ - 0.125 - - - - - @ ^ - 0.25 - - - ...
qubits = list ( qubits ) while len ( qubits ) > 0 : q_head = qubits . pop ( 0 ) yield cirq . H ( q_head ) for i , qubit in enumerate ( qubits ) : yield ( cirq . CZ ** ( - 1 / 2.0 ** ( i + 1 ) ) ) ( qubit , q_head )
def _to_ctfile_atom_block ( self , key ) : """Create atom block in ` CTfile ` format . : param str key : Ctab atom block key . : return : Ctab atom block . : rtype : : py : class : ` str `"""
counter = OrderedCounter ( Atom . atom_block_format ) ctab_atom_block = '\n' . join ( [ '' . join ( [ str ( value ) . rjust ( spacing ) for value , spacing in zip ( atom . _ctab_data . values ( ) , counter . values ( ) ) ] ) for atom in self [ key ] ] ) return '{}\n' . format ( ctab_atom_block )
def kpl_set_on_mask ( self , address , group , mask ) : """Get the status of a KPL button ."""
addr = Address ( address ) device = self . plm . devices [ addr . id ] device . states [ group ] . set_on_mask ( mask )
def deleteNetworkVisualProp ( self , networkId , viewId , visualProperty , verbose = None ) : """Deletes the bypass Visual Property specificed by the ` visualProperty ` , ` viewId ` , and ` networkId ` parameters . When this is done , the Visual Property will be defined by the Visual Style Additional details on c...
response = api ( url = self . ___url + 'networks/' + str ( networkId ) + '/views/' + str ( viewId ) + '/network/' + str ( visualProperty ) + '/bypass' , method = "DELETE" , verbose = verbose ) return response
def get_area ( self ) : """: returns : The area of the surface . . . warning : : The area is computed as the sum of the areas of all the polygons minus the sum of the areas of all the holes ."""
polys = sum ( [ polygon . get_area ( ) for polygon in self ] ) holes = sum ( [ hole . get_area ( ) for hole in self . holes ] ) return polys - holes
def init_goid2color ( self ) : """Set colors of GO terms ."""
goid2color = { } # 1 . User - specified colors for each GO term if 'go2color' in self . kws : for goid , color in self . kws [ 'go2color' ] . items ( ) : goid2color [ goid ] = color # 2 . colors based on p - value override colors based on source GO if self . objgoea is not None : self . objgoea . set_go...
def latitude ( self , value = 0.0 ) : """Corresponds to IDD Field ` latitude ` + is North , - is South , degree minutes represented in decimal ( i . e . 30 minutes is . 5) Args : value ( float ) : value for IDD Field ` latitude ` Unit : deg Default value : 0.0 value > = - 90.0 value < = 90.0 if ` va...
if value is not None : try : value = float ( value ) except ValueError : raise ValueError ( 'value {} need to be of type float ' 'for field `latitude`' . format ( value ) ) if value < - 90.0 : raise ValueError ( 'value need to be greater or equal -90.0 ' 'for field `latitude`' ) ...
def start ( self ) : """Restart the listener"""
if not event . contains ( self . field , 'set' , self . __validate ) : self . __create_event ( )
def _get_module_via_pkgutil ( self , fullname ) : """Attempt to fetch source code via pkgutil . In an ideal world , this would be the only required implementation of get _ module ( ) ."""
try : # Pre - ' import spec ' this returned None , in Python3.6 it raises # ImportError . loader = pkgutil . find_loader ( fullname ) except ImportError : e = sys . exc_info ( ) [ 1 ] LOG . debug ( '%r._get_module_via_pkgutil(%r): %s' , self , fullname , e ) return None IOLOG . debug ( '%r._get_module_v...
def sigfig_round ( values , sigfig = 1 ) : """Round a single value to a specified number of significant figures . Parameters values : float , value to be rounded sigfig : int , number of significant figures to reduce to Returns rounded : values , but rounded to the specified number of significant figures ...
as_int , multiplier = sigfig_int ( values , sigfig ) rounded = as_int * ( 10 ** multiplier ) return rounded
def from_histogram ( cls , histogram , bin_edges , axis_names = None ) : """Make a Hist1D from a numpy bin _ edges + histogram pair : param histogram : Initial histogram : param bin _ edges : Bin edges of histogram . Must be one longer than length of histogram : param axis _ names : Ignored . Sorry : - ) : ...
if len ( bin_edges ) != len ( histogram ) + 1 : raise ValueError ( "Bin edges must be of length %d, you gave %d!" % ( len ( histogram ) + 1 , len ( bin_edges ) ) ) self = cls ( bins = bin_edges ) self . histogram = np . array ( histogram ) return self
def mutual_info_score ( self , reference_clusters ) : """Calculates the MI ( mutual information ) w . r . t . the reference clusters ( explicit evaluation ) : param reference _ clusters : Clusters that are to be used as reference : return : The resulting MI score ."""
return mutual_info_score ( self . get_labels ( self ) , self . get_labels ( reference_clusters ) )
def inspect ( self , w ) : """Get the value of a wirevector in the last simulation cycle . : param w : the name of the WireVector to inspect ( passing in a WireVector instead of a name is deprecated ) : return : value of w in the current step of simulation Will throw KeyError if w is not being tracked in th...
try : return self . context [ self . _to_name ( w ) ] except AttributeError : raise PyrtlError ( "No context available. Please run a simulation step in " "order to populate values for wires" )
def _handle_init_list ( self , node , scope , ctxt , stream ) : """Handle InitList nodes ( e . g . when initializing a struct ) : node : TODO : scope : TODO : ctxt : TODO : stream : TODO : returns : TODO"""
self . _dlog ( "handling init list" ) res = [ ] for _ , init_child in node . children ( ) : init_field = self . _handle_node ( init_child , scope , ctxt , stream ) res . append ( init_field ) return res
def distribution_for_instance ( self , inst ) : """Peforms a prediction , returning the cluster distribution . : param inst : the Instance to get the cluster distribution for : type inst : Instance : return : the cluster distribution : rtype : float [ ]"""
pred = self . __distribution ( inst . jobject ) return javabridge . get_env ( ) . get_double_array_elements ( pred )
def add_init_service_checks ( nrpe , services , unit_name , immediate_check = True ) : """Add checks for each service in list : param NRPE nrpe : NRPE object to add check to : param list services : List of services to check : param str unit _ name : Unit name to use in check description : param bool immedia...
for svc in services : # Don ' t add a check for these services from neutron - gateway if svc in [ 'ext-port' , 'os-charm-phy-nic-mtu' ] : next upstart_init = '/etc/init/%s.conf' % svc sysv_init = '/etc/init.d/%s' % svc if host . init_is_systemd ( ) : nrpe . add_check ( shortname = svc , ...
def edit ( self , id_ , text ) : """Login required . Sends POST to change selftext or comment text to ` ` text ` ` . Returns : class : ` things . Comment ` or : class : ` things . Link ` object depending on what ' s being edited . Raises : class : ` UnexpectedResponse ` if neither is returned . URL : ` ` http : /...
data = dict ( thing_id = id_ , text = text ) j = self . post ( 'api' , 'editusertext' , data = data ) try : return self . _thingify ( j [ 'json' ] [ 'data' ] [ 'things' ] [ 0 ] ) except Exception : raise UnexpectedResponse ( j )
def upload ( self , cmd : str , meta : dict ) : """Push the current state of the registry to Git ."""
index = os . path . join ( self . cached_repo , self . INDEX_FILE ) if os . path . exists ( index ) : os . remove ( index ) self . _log . info ( "Writing the new index.json ..." ) with open ( index , "w" ) as _out : json . dump ( self . contents , _out ) git . add ( self . cached_repo , [ index ] ) message = se...
def _validate_attrs ( dataset ) : """` attrs ` must have a string key and a value which is either : a number , a string , an ndarray or a list / tuple of numbers / strings ."""
def check_attr ( name , value ) : if isinstance ( name , str ) : if not name : raise ValueError ( 'Invalid name for attr: string must be ' 'length 1 or greater for serialization to ' 'netCDF files' ) else : raise TypeError ( "Invalid name for attr: {} must be a string for " "serializ...
def calc_avgstrlen_pathstextnodes ( pars_tnodes , dbg = False ) : """In the effort of not using external libraries ( like scipy , numpy , etc ) , I ' ve written some harmless code for basic statistical calculations"""
ttl = 0 for _ , tnodes in pars_tnodes : ttl += tnodes [ 3 ] # index # 3 holds the avg strlen crd = len ( pars_tnodes ) avg = ttl / crd if dbg is True : print ( avg ) # avg = ttl / crd return ( avg , ttl , crd )
def __handle_request ( self , request , * args , ** kw ) : """Intercept the request and response . This function lets ` HttpStatusCodeError ` s fall through . They are caught and transformed into HTTP responses by the caller . : return : ` ` HttpResponse ` `"""
self . _authenticate ( request ) self . _check_permission ( request ) method = self . _get_method ( request ) data = self . _get_input_data ( request ) data = self . _clean_input_data ( data , request ) response = self . _exec_method ( method , request , data , * args , ** kw ) return self . _process_response ( respons...
def _join_index_objects ( self , axis , other_index , how , sort = True ) : """Joins a pair of index objects ( columns or rows ) by a given strategy . Args : axis : The axis index object to join ( 0 for columns , 1 for index ) . other _ index : The other _ index to join on . how : The type of join to join t...
if isinstance ( other_index , list ) : joined_obj = self . columns if not axis else self . index # TODO : revisit for performance for obj in other_index : joined_obj = joined_obj . join ( obj , how = how ) return joined_obj if not axis : return self . columns . join ( other_index , how = how...
def split_args_text_to_list ( self , args_text ) : """Split the text including multiple arguments to list . This function uses a comma to separate arguments and ignores a comma in brackets ans quotes ."""
args_list = [ ] idx_find_start = 0 idx_arg_start = 0 try : pos_quote = self . _find_quote_position ( args_text ) pos_round = self . _find_bracket_position ( args_text , '(' , ')' , pos_quote ) pos_curly = self . _find_bracket_position ( args_text , '{' , '}' , pos_quote ) pos_square = self . _find_brack...
def completion ( ) : """Output completion ( to be eval ' d ) . For bash or zsh , add the following to your . bashrc or . zshrc : eval " $ ( doitlive completion ) " For fish , add the following to ~ / . config / fish / completions / doitlive . fish : eval ( doitlive completion )"""
shell = env . get ( "SHELL" , None ) if env . get ( "SHELL" , None ) : echo ( click_completion . get_code ( shell = shell . split ( os . sep ) [ - 1 ] , prog_name = "doitlive" ) ) else : echo ( "Please ensure that the {SHELL} environment " "variable is set." . format ( SHELL = style ( "SHELL" , bold = True ) ) ...
def setProfile ( self , profile ) : """Sets the profile linked with this action . : param profile | < projexui . widgets . xviewwidget . XViewProfile >"""
self . _profile = profile # update the interface self . setIcon ( profile . icon ( ) ) self . setText ( profile . name ( ) ) self . setToolTip ( profile . description ( ) )
def _split_generators ( self , dl_manager ) : """Returns SplitGenerators ."""
# Download the full MNIST Database filenames = { "train_data" : _MNIST_TRAIN_DATA_FILENAME , "train_labels" : _MNIST_TRAIN_LABELS_FILENAME , "test_data" : _MNIST_TEST_DATA_FILENAME , "test_labels" : _MNIST_TEST_LABELS_FILENAME , } mnist_files = dl_manager . download_and_extract ( { k : urllib . parse . urljoin ( self ....
def merge_modified_section_data ( self ) : """Update the PE image content with any individual section data that has been modified ."""
for section in self . sections : section_data_start = adjust_FileAlignment ( section . PointerToRawData , self . OPTIONAL_HEADER . FileAlignment ) section_data_end = section_data_start + section . SizeOfRawData if section_data_start < len ( self . __data__ ) and section_data_end < len ( self . __data__ ) : ...
def create_from_binary ( cls , binary_view ) : '''Creates a new object DataRuns from a binary stream . The binary stream can be represented by a byte string , bytearray or a memoryview of the bytearray . Args : binary _ view ( memoryview of bytearray ) - A binary stream with the information of the attribu...
nw_obj = cls ( ) offset = 0 previous_dr_offset = 0 header_size = cls . _INFO . size # " header " of a data run is always a byte while binary_view [ offset ] != 0 : # the runlist ends with an 0 as the " header " header = cls . _INFO . unpack ( binary_view [ offset : offset + header_size ] ) [ 0 ] length_len = he...
def render_template ( template_name , info , out_path = None ) : """Render a template using the variables in info . You can optionally render to a file by passing out _ path . Args : template _ name ( str ) : The name of the template to load . This must be a file in config / templates inside this package ...
env = Environment ( loader = PackageLoader ( 'iotile.build' , 'config/templates' ) , trim_blocks = True , lstrip_blocks = True ) template = env . get_template ( template_name ) result = template . render ( info ) if out_path is not None : with open ( out_path , 'wb' ) as outfile : outfile . write ( result ....
def client_key_loader ( self , f ) : """Registers a function to be called to find a client key . Function you set has to take a client id and return a client key : : @ hawk . client _ key _ loader def get _ client _ key ( client _ id ) : if client _ id = = ' Alice ' : return ' werxhqb98rpaxn39848xrunpaw34...
@ wraps ( f ) def wrapped_f ( client_id ) : client_key = f ( client_id ) return { 'id' : client_id , 'key' : client_key , 'algorithm' : current_app . config [ 'HAWK_ALGORITHM' ] } self . _client_key_loader_func = wrapped_f return wrapped_f
def yield_nanopub ( assertions , annotations , line_num ) : """Yield nanopub object"""
if not assertions : return { } anno = copy . deepcopy ( annotations ) evidence = anno . pop ( "evidence" , None ) stmt_group = anno . pop ( "statement_group" , None ) citation = anno . pop ( "citation" , None ) anno_list = [ ] for anno_type in anno : if isinstance ( anno [ anno_type ] , ( list , tuple ) ) : ...
def assert_no_404_errors ( self , multithreaded = True ) : """Assert no 404 errors from page links obtained from : " a " - > " href " , " img " - > " src " , " link " - > " href " , and " script " - > " src " ."""
links = self . get_unique_links ( ) if multithreaded : from multiprocessing . dummy import Pool as ThreadPool pool = ThreadPool ( 10 ) pool . map ( self . assert_link_status_code_is_not_404 , links ) pool . close ( ) pool . join ( ) else : for link in links : self . assert_link_status_co...
def validate_fields_only_with_permissions ( self , val , caller_permissions ) : """To pass field validation , no required field should be missing . This method assumes that the contents of each field have already been validated on assignment , so it ' s merely a presence check . Should only be called for call...
self . validate_fields_only ( val ) # check if type has been patched for extra_permission in caller_permissions . permissions : all_field_names = '_all_{}_field_names_' . format ( extra_permission ) for field_name in getattr ( self . definition , all_field_names , set ( ) ) : if not hasattr ( val , fiel...
def skip ( cb , msg , attributes ) : """Skips applying transforms if data is not geographic ."""
if not all ( a in msg for a in attributes ) : return True plot = get_cb_plot ( cb ) return ( not getattr ( plot , 'geographic' , False ) or not hasattr ( plot . current_frame , 'crs' ) )
def getAnalogActionData ( self , action , unActionDataSize , ulRestrictToDevice ) : """Reads the state of an analog action given its handle . This will return VRInputError _ WrongType if the type of action is something other than analog"""
fn = self . function_table . getAnalogActionData pActionData = InputAnalogActionData_t ( ) result = fn ( action , byref ( pActionData ) , unActionDataSize , ulRestrictToDevice ) return result , pActionData
def list ( ) : """List all events"""
entries = lambder . list_events ( ) for e in entries : click . echo ( str ( e ) )
def entrez ( args ) : """% prog entrez < filename | term > ` filename ` contains a list of terms to search . Or just one term . If the results are small in size , e . g . " - - format = acc " , use " - - batchsize = 100 " to speed the download ."""
p = OptionParser ( entrez . __doc__ ) allowed_databases = { "fasta" : [ "genome" , "nuccore" , "nucgss" , "protein" , "nucest" ] , "asn.1" : [ "genome" , "nuccore" , "nucgss" , "protein" , "gene" ] , "xml" : [ "genome" , "nuccore" , "nucgss" , "nucest" , "gene" ] , "gb" : [ "genome" , "nuccore" , "nucgss" ] , "est" : [...
def decode_tuple ( data , encoding = None , errors = 'strict' , keep = False , normalize = False , preserve_dict_class = False , to_str = False ) : '''Decode all string values to Unicode . Optionally use to _ str = True to ensure strings are str types and not unicode on Python 2.'''
return tuple ( decode_list ( data , encoding , errors , keep , normalize , preserve_dict_class , True , to_str ) )
def is_sequence_match ( pattern : list , instruction_list : list , index : int ) -> bool : """Checks if the instructions starting at index follow a pattern . : param pattern : List of lists describing a pattern , e . g . [ [ " PUSH1 " , " PUSH2 " ] , [ " EQ " ] ] where [ " PUSH1 " , " EQ " ] satisfies pattern :...
for index , pattern_slot in enumerate ( pattern , start = index ) : try : if not instruction_list [ index ] [ "opcode" ] in pattern_slot : return False except IndexError : return False return True
def set_attribute_id ( self , el , objid ) : '''set id attribute Paramters : el - - MessageInterface representing the element objid - - ID type , unique id'''
if self . unique is False : el . setAttributeNS ( None , 'id' , "%s" % objid )
def gnomonicSphereToImage ( lon , lat ) : """Gnomonic projection ( deg ) ."""
# Convert angle to [ - 180 , 180 ] interval lon = lon - 360. * ( lon > 180 ) lon = np . radians ( lon ) lat = np . radians ( lat ) r_theta = ( 180. / np . pi ) / np . tan ( lat ) x = r_theta * np . cos ( lon ) y = r_theta * np . sin ( lon ) return x , y
def ng_get_ctrl_property ( self , element , prop ) : """: Description : Will return value of property of element ' s controller . : Warning : This will only work for angular . js 1 . x . : Warning : Requires angular debugging to be enabled . : param element : Element for browser instance to target . : type ...
return self . browser . execute_script ( 'return angular.element(arguments[0]).controller()%s;' % self . __d2b_notation ( prop = prop ) , element )
def get_compositions_by_repository ( self , repository_id ) : """Gets the list of ` ` Compositions ` ` associated with a ` ` Repository ` ` . arg : repository _ id ( osid . id . Id ) : ` ` Id ` ` of the ` ` Repository ` ` return : ( osid . repository . CompositionList ) - list of related compositions raise ...
# Implemented from template for # osid . resource . ResourceBinSession . get _ resources _ by _ bin mgr = self . _get_provider_manager ( 'REPOSITORY' , local = True ) lookup_session = mgr . get_composition_lookup_session_for_repository ( repository_id , proxy = self . _proxy ) lookup_session . use_isolated_repository_v...
def matchPreviousExpr ( expr ) : """Helper to define an expression that is indirectly defined from the tokens matched in a previous expression , that is , it looks for a ' repeat ' of a previous expression . For example : : first = Word ( nums ) second = matchPreviousExpr ( first ) matchExpr = first + " :...
rep = Forward ( ) e2 = expr . copy ( ) rep <<= e2 def copyTokenToRepeater ( s , l , t ) : matchTokens = _flatten ( t . asList ( ) ) def mustMatchTheseTokens ( s , l , t ) : theseTokens = _flatten ( t . asList ( ) ) if theseTokens != matchTokens : raise ParseException ( "" , 0 , "" ) ...
def get_page_by_id_text ( self , project , wiki_identifier , id , recursion_level = None , include_content = None , ** kwargs ) : """GetPageByIdText . [ Preview API ] Gets metadata or content of the wiki page for the provided page id . Content negotiation is done based on the ` Accept ` header sent in the request...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if wiki_identifier is not None : route_values [ 'wikiIdentifier' ] = self . _serialize . url ( 'wiki_identifier' , wiki_identifier , 'str' ) if id is not None : route_values [ 'id...
def get_content_descendants ( self , content_id , expand = None , callback = None ) : """Returns a map of the descendants of a piece of Content . Content can have multiple types of descendants - for example a Page can have descendants that are also Pages , but it can also have Comments and Attachments . The { @...
params = { } if expand : params [ "expand" ] = expand return self . _service_get_request ( "rest/api/content/{id}/descendant" . format ( id = content_id ) , params = params , callback = callback )
def import_class ( class_path ) : """Returns class from the given path . For example , in order to get class located at ` ` mypackage . subpackage . MyClass ` ` : try : hgrepo = import _ class ( ' mypackage . subpackage . MyClass ' ) except ImportError : # hadle error"""
splitted = class_path . split ( '.' ) mod_path = '.' . join ( splitted [ : - 1 ] ) class_name = splitted [ - 1 ] # import may throw ImportError class_mod = __import__ ( mod_path , { } , { } , [ class_name ] ) try : cls = getattr ( class_mod , class_name ) except AttributeError : raise ImportError ( "Couldn't im...
def proc_response ( self , resp , startidx = None ) : """Post - process a response through all processors in the stack , in reverse order . For convenience , returns the response passed to the method . The startidx argument is an internal interface only used by the proc _ request ( ) and proc _ exception ( ...
# If we ' re empty , bail out early if not self : return resp # Select appropriate starting index if startidx is None : startidx = len ( self ) for idx in range ( startidx , - 1 , - 1 ) : _safe_call ( self [ idx ] , 'proc_response' , resp ) # Return the response we were passed return resp
def _get_interpreter_info ( interpreter = None ) : """Return the interpreter ' s full path using pythonX . Y format ."""
if interpreter is None : # If interpreter is None by default returns the current interpreter data . major , minor = sys . version_info [ : 2 ] executable = sys . executable else : args = [ interpreter , '-c' , SHOW_VERSION_CMD ] try : requested_interpreter_info = logged_exec ( args ) except ...
def get_matching_symbols_pairs ( self , cursor , opening_symbol , closing_symbol , backward = False ) : """Returns the cursor for matching given symbols pairs . : param cursor : Cursor to match from . : type cursor : QTextCursor : param opening _ symbol : Opening symbol . : type opening _ symbol : unicode ...
if cursor . hasSelection ( ) : start_position = cursor . selectionEnd ( ) if backward else cursor . selectionStart ( ) else : start_position = cursor . position ( ) flags = QTextDocument . FindFlags ( ) if backward : flags = flags | QTextDocument . FindBackward start_cursor = previous_start_cursor = cursor ...
def reload ( self ) : """Function reload Sync the full object"""
self . load ( self . api . get ( self . objName , self . key ) )
def _create_authority_file ( self , file_path ) : """Create a new LSID authority file at the indicated location : param file _ path : location of LSID authority file"""
parent_dir = os . path . dirname ( os . path . realpath ( file_path ) ) # Create the parent directory if it does not exist if not os . path . exists ( parent_dir ) : os . makedirs ( parent_dir ) # Create blank LSID authority structure blank = self . _create_blank_authority ( ) # Write blank structure to new authori...
def _fracRoiSparse ( self ) : """Calculate an approximate pixel coverage fraction from the two masks . We have no way to know a priori how much the coverage of the two masks overlap in a give pixel . For example , masks that each have frac = 0.5 could have a combined frac = [ 0.0 to 0.5 ] . The limits will ...
self . frac_roi_sparse = np . min ( [ self . mask_1 . frac_roi_sparse , self . mask_2 . frac_roi_sparse ] , axis = 0 ) return self . frac_roi_sparse
def rename_models ( cr , model_spec ) : """Rename models . Typically called in the pre script . : param model _ spec : a list of tuples ( old model name , new model name ) . Use case : if a model changes name , but still implements equivalent functionality you will want to update references in for instance ...
for ( old , new ) in model_spec : logger . info ( "model %s: renaming to %s" , old , new ) _old = old . replace ( '.' , '_' ) _new = new . replace ( '.' , '_' ) logged_query ( cr , 'UPDATE ir_model SET model = %s ' 'WHERE model = %s' , ( new , old , ) , ) logged_query ( cr , 'UPDATE ir_model_data SE...
def fwdl_status_output_fwdl_entries_date_and_time_info ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) fwdl_status = ET . Element ( "fwdl_status" ) config = fwdl_status output = ET . SubElement ( fwdl_status , "output" ) fwdl_entries = ET . SubElement ( output , "fwdl-entries" ) date_and_time_info = ET . SubElement ( fwdl_entries , "date-and-time-info" ) date_and_time_info . text = kwa...
def murmur3_x86_32 ( data : Union [ bytes , bytearray ] , seed : int = 0 ) -> int : """Pure 32 - bit Python implementation of MurmurHash3 ; see http : / / stackoverflow . com / questions / 13305290 / is - there - a - pure - python - implementation - of - murmurhash . Args : data : data to hash seed : seed ...
# noqa c1 = 0xcc9e2d51 c2 = 0x1b873593 length = len ( data ) h1 = seed rounded_end = ( length & 0xfffffffc ) # round down to 4 byte block for i in range ( 0 , rounded_end , 4 ) : # little endian load order # RNC : removed ord ( ) calls k1 = ( data [ i ] & 0xff ) | ( ( data [ i + 1 ] & 0xff ) << 8 ) | ( ( data [ i +...
def update_user ( self , user , attributes , attribute_mapping , force_save = False ) : """Update a user with a set of attributes and returns the updated user . By default it uses a mapping defined in the settings constant SAML _ ATTRIBUTE _ MAPPING . For each attribute , if the user object has that field def...
if not attribute_mapping : return user user_modified = False for saml_attr , django_attrs in attribute_mapping . items ( ) : attr_value_list = attributes . get ( saml_attr ) if not attr_value_list : logger . debug ( 'Could not find value for "%s", not updating fields "%s"' , saml_attr , django_attrs...
def disable_glut ( self ) : """Disable event loop integration with glut . This sets PyOS _ InputHook to NULL and set the display function to a dummy one and set the timer to a dummy timer that will be triggered very far in the future ."""
import OpenGL . GLUT as glut # @ UnresolvedImport from glut_support import glutMainLoopEvent # @ UnresolvedImport glut . glutHideWindow ( ) # This is an event to be processed below glutMainLoopEvent ( ) self . clear_inputhook ( )
def _add_colorbar ( self , m , CS , ax , name ) : '''Add colorbar to the map instance'''
cb = m . colorbar ( CS , "right" , size = "5%" , pad = "2%" ) cb . set_label ( name , size = 34 ) cb . ax . tick_params ( labelsize = 18 )
def markdown_imgur_uploader ( request ) : """Makdown image upload for uploading to imgur . com and represent as json to markdown editor ."""
if request . method == 'POST' and request . is_ajax ( ) : if 'markdown-image-upload' in request . FILES : image = request . FILES [ 'markdown-image-upload' ] data = imgur_uploader ( image ) return HttpResponse ( data , content_type = 'application/json' ) return HttpResponse ( _ ( 'Invali...
def clip_ellipsis ( self , x , y , radius , ratio = 1.0 ) : """Create an elliptical clip region . You must call endclip ( ) after you completed drawing . See also the ellipsis method ."""
self . gsave ( ) self . newpath ( ) self . moveto ( xscale ( x ) + nscale ( radius ) , yscale ( y ) ) self . path_arc ( xscale ( x ) , yscale ( y ) , nscale ( radius ) , ratio , 0 , 360 ) self . closepath ( ) self . __clip_stack . append ( self . __clip_box ) self . clip_sub ( )
def dir_list ( saltenv = 'base' , backend = None ) : '''Return a list of directories in the given environment saltenv : base The salt fileserver environment to be listed backend Narrow fileserver backends to a subset of the enabled ones . If all passed backends start with a minus sign ( ` ` - ` ` ) , then...
fileserver = salt . fileserver . Fileserver ( __opts__ ) load = { 'saltenv' : saltenv , 'fsbackend' : backend } return fileserver . dir_list ( load = load )
def get_path ( self , appendix = None , by_name = False ) : """Recursively create the path of the state . The path is generated in bottom up method i . e . from the nested child states to the root state . The method concatenates either State . state _ id ( always unique ) or State . name ( maybe not unique but ...
if by_name : state_identifier = self . name else : state_identifier = self . state_id if not self . is_root_state : if appendix is None : return self . parent . get_path ( state_identifier , by_name ) else : return self . parent . get_path ( state_identifier + PATH_SEPARATOR + appendix ,...
def clean_builds ( self , _args ) : """Delete all build caches for each recipe , python - install , java code and compiled libs collection . This does * not * delete the package download cache or the final distributions . You can also use clean _ recipe _ build to delete the build of a specific recipe ."""
ctx = self . ctx if exists ( ctx . build_dir ) : shutil . rmtree ( ctx . build_dir ) if exists ( ctx . python_installs_dir ) : shutil . rmtree ( ctx . python_installs_dir ) libs_dir = join ( self . ctx . build_dir , 'libs_collections' ) if exists ( libs_dir ) : shutil . rmtree ( libs_dir )