signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def weighted ( self ) : """This method creates a weighted copy of the internal formula . As a result , an object of class : class : ` WCNF ` is returned . Every clause of the CNF formula is * soft * in the new WCNF formula and its weight is equal to ` ` 1 ` ` . The set of hard clauses of the formula is empty ...
wcnf = WCNF ( ) wcnf . nv = self . nv wcnf . hard = [ ] wcnf . soft = copy . deepcopy ( self . clauses ) wcnf . wght = [ 1 for cl in wcnf . soft ] self . topw = len ( wcnf . wght ) + 1 wcnf . comments = self . comments [ : ] return wcnf
def _lsb_release_info ( self ) : """Get the information items from the lsb _ release command output . Returns : A dictionary containing all information items ."""
if not self . include_lsb : return { } with open ( os . devnull , 'w' ) as devnull : try : cmd = ( 'lsb_release' , '-a' ) stdout = subprocess . check_output ( cmd , stderr = devnull ) except OSError : # Command not found return { } content = stdout . decode ( sys . getfilesystemencod...
def do_chunked_gzip ( infh , outfh , filename ) : """A memory - friendly way of compressing the data ."""
import gzip gzfh = gzip . GzipFile ( 'rawlogs' , mode = 'wb' , fileobj = outfh ) if infh . closed : infh = open ( infh . name , 'r' ) else : infh . seek ( 0 ) readsize = 0 sys . stdout . write ( 'Gzipping {0}: ' . format ( filename ) ) if os . stat ( infh . name ) . st_size : infh . seek ( 0 ) progressb...
def no_counterpart_found ( string , options , rc_so_far ) : """Takes action determined by options . else _ action . Unless told to raise an exception , this function returns the errno that is supposed to be returned in this case . : param string : The lookup string . : param options : ArgumentParser or equi...
logger . debug ( "options.else_action: %s" , options . else_action ) if options . else_action == "passthrough" : format_list = [ string ] output_fd = sys . stdout elif options . else_action == "exception" : raise KeyError ( "No counterpart found for: %s" % ( string ) ) elif options . else_action == "error" ...
def count_in_date ( x = 'date_time' , filter_dict = None , model = DEFAULT_MODEL , app = DEFAULT_APP , sort = True , limit = 100000 ) : """Count the number of records for each discrete ( categorical ) value of a field and return a dict of two lists , the field values and the counts . > > > from django . db import...
sort = sort_prefix ( sort ) model = get_model ( model , app ) filter_dict = filter_dict or { } x = fuzzy . extractOne ( str ( x ) , model . _meta . get_all_field_names ( ) ) [ 0 ] objects = model . objects . filter ( ** filter_dict ) objects = objects . extra ( { 'date_bin_for_counting' : 'date(%s)' % x } ) objects = o...
def remove_event_handler ( self , handler , event_name ) : """Remove event handler ` handler ` from registered handlers of the engine Args : handler ( callable ) : the callable event handler that should be removed event _ name : The event the handler attached to ."""
if event_name not in self . _event_handlers : raise ValueError ( "Input event name '{}' does not exist" . format ( event_name ) ) new_event_handlers = [ ( h , args , kwargs ) for h , args , kwargs in self . _event_handlers [ event_name ] if h != handler ] if len ( new_event_handlers ) == len ( self . _event_handler...
def compile_fund ( workbook , sheet , row , col ) : """Compile funding entries . Iter both rows at the same time . Keep adding entries until both cells are empty . : param obj workbook : : param str sheet : : param int row : : param int col : : return list of dict : l"""
logger_excel . info ( "enter compile_fund" ) l = [ ] temp_sheet = workbook . sheet_by_name ( sheet ) while col < temp_sheet . ncols : col += 1 try : # Make a dictionary for this funding entry . _curr = { 'agency' : temp_sheet . cell_value ( row , col ) , 'grant' : temp_sheet . cell_value ( row + 1 , col...
def tar_archive ( context ) : """Archive specified path to a tar archive . Args : context : dictionary - like . context is mandatory . context [ ' tar ' ] [ ' archive ' ] must exist . It ' s a dictionary . keys are the paths to archive . values are the destination output paths . Example : tar : arch...
logger . debug ( "start" ) mode = get_file_mode_for_writing ( context ) for item in context [ 'tar' ] [ 'archive' ] : # value is the destination tar . Allow string interpolation . destination = context . get_formatted_string ( item [ 'out' ] ) # key is the source to archive source = context . get_formatted_...
def asym ( scatterer , h_pol = True ) : """Asymmetry parameter for the current setup , with polarization . Args : scatterer : a Scatterer instance . h _ pol : If True ( default ) , use horizontal polarization . If False , use vertical polarization . Returns : The asymmetry parameter ."""
if scatterer . psd_integrator is not None : return scatterer . psd_integrator . get_angular_integrated ( scatterer . psd , scatterer . get_geometry ( ) , "asym" ) old_geom = scatterer . get_geometry ( ) cos_t0 = np . cos ( scatterer . thet0 * deg_to_rad ) sin_t0 = np . sin ( scatterer . thet0 * deg_to_rad ) p0 = sc...
def gmres_prolongation_smoothing ( A , T , B , BtBinv , Sparsity_Pattern , maxiter , tol , weighting = 'local' , Cpt_params = None ) : """Use GMRES to smooth T by solving A T = 0 , subject to nullspace and sparsity constraints . Parameters A : csr _ matrix , bsr _ matrix SPD sparse NxN matrix Should be at l...
# For non - SPD system , apply GMRES with Diagonal Preconditioning # Preallocate space for new search directions uones = np . zeros ( Sparsity_Pattern . data . shape , dtype = T . dtype ) AV = sparse . bsr_matrix ( ( uones , Sparsity_Pattern . indices , Sparsity_Pattern . indptr ) , shape = ( Sparsity_Pattern . shape )...
def push_results ( self , results , scheduler_name ) : """Send a HTTP request to the satellite ( POST / put _ results ) Send actions results to the satellite : param results : Results list to send : type results : list : param scheduler _ name : Scheduler name : type scheduler _ name : uuid : return : T...
logger . debug ( "Pushing %d results" , len ( results ) ) result = self . con . post ( 'put_results' , { 'results' : results , 'from' : scheduler_name } , wait = True ) return result
def obfn_g ( self , Y ) : r"""Compute : math : ` g ( \ mathbf { y } ) = g _ 0 ( \ mathbf { y } _ 0 ) + g _ 1 ( \ mathbf { y } _ 1 ) ` component of ADMM objective function ."""
return self . obfn_g0 ( self . obfn_g0var ( ) ) + self . obfn_g1 ( self . obfn_g1var ( ) )
def ranked_attributes ( self ) : """Returns the matrix of ranked attributes from the last run . : return : the Numpy matrix : rtype : ndarray"""
matrix = javabridge . call ( self . jobject , "rankedAttributes" , "()[[D" ) if matrix is None : return None else : return typeconv . double_matrix_to_ndarray ( matrix )
def read ( self , ** keys ) : """read data from this HDU By default , all data are read . send columns = and rows = to select subsets of the data . Table data are read into a recarray ; use read _ column ( ) to get a single column as an ordinary array . You can alternatively use slice notation fits = fits...
columns = keys . get ( 'columns' , None ) rows = keys . get ( 'rows' , None ) if columns is not None : if 'columns' in keys : del keys [ 'columns' ] data = self . read_columns ( columns , ** keys ) elif rows is not None : if 'rows' in keys : del keys [ 'rows' ] data = self . read_rows ( ...
def get ( self , collection_id , content = None , ** kwargs ) : """Syntactic sugar around to make it easier to get fine - grained access to the parts of a file without composing a PhyloSchema object . Possible invocations include : w . get ( ' pg _ 10 ' ) w . get ( ' pg _ 10 ' , ' trees ' ) w . get ( ' pg...
assert COLLECTION_ID_PATTERN . match ( collection_id ) r = self . get_collection ( collection_id ) if isinstance ( r , dict ) and ( 'data' in r ) : return r [ 'data' ] return r
def start_user_session ( self , username , domain , resource , ** kwargs ) : """Method to add a user session for debugging . Accepted parameters are the same as to the constructor of : py : class : ` ~ xmpp _ backends . base . UserSession ` ."""
kwargs . setdefault ( 'uptime' , pytz . utc . localize ( datetime . utcnow ( ) ) ) kwargs . setdefault ( 'priority' , 0 ) kwargs . setdefault ( 'status' , 'online' ) kwargs . setdefault ( 'status_text' , '' ) kwargs . setdefault ( 'connection_type' , CONNECTION_XMPP ) kwargs . setdefault ( 'encrypted' , True ) kwargs ....
def wait ( self , status = None , locked = None , wait_interval = None , wait_time = None ) : """Poll the server periodically until the droplet has reached some final state . If ` ` status ` ` is non - ` None ` , ` ` wait ` ` will wait for the droplet ' s ` ` status ` ` field to equal the given value . If ` ` l...
return next ( self . doapi_manager . wait_droplets ( [ self ] , status , locked , wait_interval , wait_time ) )
def GetPattern ( self ) : """Return a tuple of Stop objects , in the order visited"""
stoptimes = self . GetStopTimes ( ) return tuple ( st . stop for st in stoptimes )
def strip_required_prefix ( string , prefix ) : """> > > strip _ required _ prefix ( ' abcdef ' , ' abc ' ) ' def ' > > > strip _ required _ prefix ( ' abcdef ' , ' 123 ' ) Traceback ( most recent call last ) : AssertionError : String starts with ' abc ' , not ' 123'"""
if string . startswith ( prefix ) : return string [ len ( prefix ) : ] raise AssertionError ( 'String starts with %r, not %r' % ( string [ : len ( prefix ) ] , prefix ) )
def read_feature ( self , dataset , fid ) : """Retrieves ( reads ) a feature in a dataset . Parameters dataset : str The dataset id . fid : str The feature id . Returns request . Response The response contains a GeoJSON representation of the feature ."""
uri = URITemplate ( self . baseuri + '/{owner}/{did}/features/{fid}' ) . expand ( owner = self . username , did = dataset , fid = fid ) return self . session . get ( uri )
def set_white ( self , brightness , colourtemp ) : """Set white coloured theme of an rgb bulb . Args : brightness ( int ) : Value for the brightness ( 25-255 ) . colourtemp ( int ) : Value for the colour temperature ( 0-255 ) ."""
if not 25 <= brightness <= 255 : raise ValueError ( "The brightness needs to be between 25 and 255." ) if not 0 <= colourtemp <= 255 : raise ValueError ( "The colour temperature needs to be between 0 and 255." ) payload = self . generate_payload ( SET , { self . DPS_INDEX_MODE : self . DPS_MODE_WHITE , self . D...
def update_instrument_config ( instrument , measured_center ) -> Tuple [ Point , float ] : """Update config and pose tree with instrument ' s x and y offsets and tip length based on delta between probe center and measured _ center , persist updated config and return it"""
from copy import deepcopy from opentrons . trackers . pose_tracker import update robot = instrument . robot config = robot . config instrument_offset = deepcopy ( config . instrument_offset ) dx , dy , dz = array ( measured_center ) - config . tip_probe . center log . debug ( "This is measured probe center dx {}" . for...
def _connect_sudo ( spec ) : """Return ContextService arguments for sudo as a become method ."""
return { 'method' : 'sudo' , 'enable_lru' : True , 'kwargs' : { 'username' : spec . become_user ( ) , 'password' : spec . become_pass ( ) , 'python_path' : spec . python_path ( ) , 'sudo_path' : spec . become_exe ( ) , 'connect_timeout' : spec . timeout ( ) , 'sudo_args' : spec . sudo_args ( ) , 'remote_name' : get_rem...
def hwvtep_activate_hwvtep ( self , ** kwargs ) : """Activate the hwvtep Args : name ( str ) : overlay _ gateway name callback ( function ) : A function executed upon completion of the method . Returns : Return value of ` callback ` . Raises : None"""
name = kwargs . pop ( 'name' ) name_args = dict ( name = name ) method_name = 'overlay_gateway_activate' method_class = self . _brocade_tunnels gw_attr = getattr ( method_class , method_name ) config = gw_attr ( ** name_args ) output = self . _callback ( config ) return output
def revoke ( self , auth , codetype , code , defer = False ) : """Given an activation code , the associated entity is revoked after which the activation code can no longer be used . Args : auth : Takes the owner ' s cik codetype : The type of code to revoke ( client | share ) code : Code specified by < co...
return self . _call ( 'revoke' , auth , [ codetype , code ] , defer )
def register ( self , func , singleton = False , threadlocal = False , name = None ) : """Register a dependency function"""
func . _giveme_singleton = singleton func . _giveme_threadlocal = threadlocal if name is None : name = func . __name__ self . _registered [ name ] = func return func
def rsa_base64_sign_str ( self , plain , b64 = True ) : """对 msg rsa 签名 , 然后使用 base64 encode 编码数据"""
with open ( self . key_file ) as fp : key_ = RSA . importKey ( fp . read ( ) ) # h = SHA . new ( plain if sys . version _ info < ( 3 , 0 ) else plain . encode ( ' utf - 8 ' ) ) plain = helper . to_bytes ( plain ) # if hasattr ( plain , ' encode ' ) : # plain = plain . encode ( ) h = SHA . new ( ...
def _compute_anom_data_using_window ( self ) : """Compute anomaly scores using a lagging window ."""
anom_scores = { } values = self . time_series . values stdev = numpy . std ( values ) for i , ( timestamp , value ) in enumerate ( self . time_series_items ) : if i < self . lag_window_size : anom_score = self . _compute_anom_score ( values [ : i + 1 ] , value ) else : anom_score = self . _compu...
def relpath ( path , start = None ) : """Return a relative file path to path either from the current directory or from an optional start directory . For storage objects , " path " and " start " are relative to storage root . " / " are not stripped on storage objects path . The ending slash is required on ...
relative = get_instance ( path ) . relpath ( path ) if start : # Storage relative path # Replaces " \ " by " / " for Windows . return os_path_relpath ( relative , start = start ) . replace ( '\\' , '/' ) return relative
def is_compliant ( self , path ) : """Checks if the directory is compliant . Used to determine if the path specified and all of its children directories are in compliance with the check itself . : param path : the directory path to check : returns : True if the directory tree is compliant , otherwise False ...
if not os . path . isdir ( path ) : log ( 'Path specified %s is not a directory.' % path , level = ERROR ) raise ValueError ( "%s is not a directory." % path ) if not self . recursive : return super ( DirectoryPermissionAudit , self ) . is_compliant ( path ) compliant = True for root , dirs , _ in os . walk...
def update_object ( self , form , obj ) : """Saves the new value to the target object ."""
field_name = form . cleaned_data [ 'name' ] value = form . cleaned_data [ 'value' ] setattr ( obj , field_name , value ) save_kwargs = { } if CAN_UPDATE_FIELDS : save_kwargs [ 'update_fields' ] = [ field_name ] obj . save ( ** save_kwargs ) data = json . dumps ( { 'status' : 'success' , } ) return HttpResponse ( da...
def getMemoryStats ( self ) : """Return JVM Memory Stats for Apache Tomcat Server . @ return : Dictionary of memory utilization stats ."""
if self . _statusxml is None : self . initStats ( ) node = self . _statusxml . find ( 'jvm/memory' ) memstats = { } if node is not None : for ( key , val ) in node . items ( ) : memstats [ key ] = util . parse_value ( val ) return memstats
def recurseforumcontents ( parser , token ) : """Iterates over the content nodes and renders the contained forum block for each node ."""
bits = token . contents . split ( ) forums_contents_var = template . Variable ( bits [ 1 ] ) template_nodes = parser . parse ( ( 'endrecurseforumcontents' , ) ) parser . delete_first_token ( ) return RecurseTreeForumVisibilityContentNode ( template_nodes , forums_contents_var )
def attitude_target_send ( self , time_boot_ms , type_mask , q , body_roll_rate , body_pitch_rate , body_yaw_rate , thrust , force_mavlink1 = False ) : '''Reports the current commanded attitude of the vehicle as specified by the autopilot . This should match the commands sent in a SET _ ATTITUDE _ TARGET messag...
return self . send ( self . attitude_target_encode ( time_boot_ms , type_mask , q , body_roll_rate , body_pitch_rate , body_yaw_rate , thrust ) , force_mavlink1 = force_mavlink1 )
def get_last ( self , table = None ) : """Just the last entry ."""
if table is None : table = self . main_table query = 'SELECT * FROM "%s" ORDER BY ROWID DESC LIMIT 1;' % table return self . own_cursor . execute ( query ) . fetchone ( )
def as_boxes ( self , solid = False ) : """A rough Trimesh representation of the voxels with a box for each filled voxel . Parameters solid : bool , if True return boxes for sparse _ solid Returns mesh : Trimesh object made up of one box per filled cell ."""
if solid : filled = self . sparse_solid else : filled = self . sparse_surface # center points of voxels centers = indices_to_points ( indices = filled , pitch = self . pitch , origin = self . origin ) mesh = multibox ( centers = centers , pitch = self . pitch ) return mesh
def read ( self , payloadType , elsClient ) : """Fetches the latest data for this entity from api . elsevier . com . Returns True if successful ; else , False ."""
if elsClient : self . _client = elsClient ; elif not self . client : raise ValueError ( '''Entity object not currently bound to elsClient instance. Call .read() with elsClient argument or set .client attribute.''' ) try : api_response = self . client . exec_request ( self . uri ) if isinstance ( api_res...
def layout_deck ( self , i ) : """Stack the cards , starting at my deck ' s foundation , and proceeding by ` ` card _ pos _ hint ` `"""
def get_dragidx ( cards ) : j = 0 for card in cards : if card . dragging : return j j += 1 # Put a None in the card list in place of the card you ' re # hovering over , if you ' re dragging another card . This will # result in an empty space where the card will go if you drop # it no...
def _set_group ( self , v , load = False ) : """Setter method for group , mapped from YANG variable / snmp _ server / group ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ group is considered as a private method . Backends looking to populate this variable sh...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "group_name group_version" , group . group , yang_name = "group" , rest_name = "group" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'group-nam...
def _get_program_dir ( name , config ) : """Retrieve directory for a program ( local installs / java jars ) ."""
if config is None : raise ValueError ( "Could not find directory in config for %s" % name ) elif isinstance ( config , six . string_types ) : return config elif "dir" in config : return expand_path ( config [ "dir" ] ) else : raise ValueError ( "Could not find directory in config for %s" % name )
def _delete_request ( self , url , headers , data = None ) : """Issue a DELETE request to the specified endpoint with the data provided . : param url : str : pararm headers : dict : param data : dict"""
return self . _session . delete ( url , headers = headers , data = data )
def connect ( self , coro ) : """The coroutine ` coro ` is connected to the signal . The coroutine must return a true value , unless it wants to be disconnected from the signal . . . note : : This is different from the return value convention with : attr : ` AdHocSignal . STRONG ` and : attr : ` AdHocSign...
self . logger . debug ( "connecting %r" , coro ) return self . _connect ( coro )
def generate_random_nhs_number ( ) -> int : """Returns a random valid NHS number , as an ` ` int ` ` ."""
check_digit = 10 # NHS numbers with this check digit are all invalid while check_digit == 10 : digits = [ random . randint ( 1 , 9 ) ] # don ' t start with a zero digits . extend ( [ random . randint ( 0 , 9 ) for _ in range ( 8 ) ] ) # . . . length now 9 check_digit = nhs_check_digit ( digits ) # n...
def check_undelivered ( to = None ) : """Sends a notification email if any undelivered dispatches . Returns undelivered ( failed ) dispatches count . : param str | unicode to : Recipient address . If not set Django ADMINS setting is used . : rtype : int"""
failed_count = Dispatch . objects . filter ( dispatch_status = Dispatch . DISPATCH_STATUS_FAILED ) . count ( ) if failed_count : from sitemessage . shortcuts import schedule_email from sitemessage . messages . email import EmailTextMessage if to is None : admins = settings . ADMINS if admins...
def load_trace ( path , * args , ** kwargs ) : """Read a packet trace file , return a : class : ` wltrace . common . WlTrace ` object . This function first reads the file ' s magic ( first ` ` FILE _ TYPE _ HANDLER ` ` bytes ) , and automatically determine the file type , and call appropriate handler to proce...
with open ( path , 'rb' ) as f : magic = f . read ( MAGIC_LEN ) if magic not in FILE_TYPE_HANDLER : raise Exception ( 'Unknown file magic: %s' % ( binascii . hexlify ( magic ) ) ) return FILE_TYPE_HANDLER [ magic ] ( path , * args , ** kwargs )
def to_base64 ( self , skip = ( ) ) : """Construct from base64 - encoded JSON ."""
return base64 . b64encode ( ensure_bytes ( self . to_json ( skip = skip ) , encoding = 'utf-8' , ) )
def update_history ( self ) -> None : """Update messaging history on disk . : returns : None"""
self . log . debug ( f"Saving history. History is: \n{self.history}" ) jsons = [ ] for item in self . history : json_item = item . __dict__ # Convert sub - entries into JSON as well . json_item [ "output_records" ] = self . _parse_output_records ( item ) jsons . append ( json_item ) if not path . isfile...
def _kl_divergence ( self , summary_freq , doc_freq ) : """Note : Could import scipy . stats and use scipy . stats . entropy ( doc _ freq , summary _ freq ) but this gives equivalent value without the import"""
sum_val = 0 for w in summary_freq : frequency = doc_freq . get ( w ) if frequency : # missing or zero = no frequency sum_val += frequency * math . log ( frequency / summary_freq [ w ] ) return sum_val
def _legislator_objects ( self ) : '''A cache of dereferenced legislator objects .'''
kwargs = { } id_getter = operator . itemgetter ( 'leg_id' ) ids = [ ] for k in ( 'yes' , 'no' , 'other' ) : ids . extend ( map ( id_getter , self [ k + '_votes' ] ) ) objs = db . legislators . find ( { '_all_ids' : { '$in' : ids } } , ** kwargs ) # Handy to keep a reference to the vote on each legislator . objs = l...
def append_data ( self , name , initial_content , size , readonly = False , sort = "unknown" ) : # pylint : disable = unused - argument """Append a new data entry into the binary with specific name , content , and size . : param str name : Name of the data entry . Will be used as the label . : param bytes initi...
if readonly : section_name = ".rodata" else : section_name = '.data' if initial_content is None : initial_content = b"" initial_content = initial_content . ljust ( size , b"\x00" ) data = Data ( self , memory_data = None , section_name = section_name , name = name , initial_content = initial_content , size ...
def client_details ( self , * args ) : """Display known details about a given client"""
self . log ( _ ( 'Client details:' , lang = 'de' ) ) client = self . _clients [ args [ 0 ] ] self . log ( 'UUID:' , client . uuid , 'IP:' , client . ip , 'Name:' , client . name , 'User:' , self . _users [ client . useruuid ] , pretty = True )
def NOAJS_metric ( bpmn_graph ) : """Returns the value of the NOAJS metric ( Number of Activities , joins and splits ) for the BPMNDiagramGraph instance . : param bpmn _ graph : an instance of BpmnDiagramGraph representing BPMN model ."""
activities_count = all_activities_count ( bpmn_graph ) gateways_count = all_gateways_count ( bpmn_graph ) return activities_count + gateways_count
def upload_part_copy ( Bucket = None , CopySource = None , CopySourceIfMatch = None , CopySourceIfModifiedSince = None , CopySourceIfNoneMatch = None , CopySourceIfUnmodifiedSince = None , CopySourceRange = None , Key = None , PartNumber = None , UploadId = None , SSECustomerAlgorithm = None , SSECustomerKey = None , S...
pass
def set_location ( self , uri , size , checksum , storage_class = None ) : """Set only URI location of for object . Useful to link files on externally controlled storage . If a file instance has already been set , this methods raises an ` ` FileInstanceAlreadySetError ` ` exception . : param uri : Full URI ...
self . file = FileInstance ( ) self . file . set_uri ( uri , size , checksum , storage_class = storage_class ) db . session . add ( self . file ) return self
def delete ( python_data : LdapObject , database : Optional [ Database ] = None ) -> None : """Delete a LdapObject from the database ."""
dn = python_data . get_as_single ( 'dn' ) assert dn is not None database = get_database ( database ) connection = database . connection connection . delete ( dn )
def listItem ( node ) : """An item in a list"""
o = nodes . list_item ( ) for n in MarkDown ( node ) : o += n return o
def get_releasetype ( self , ) : """Return the currently selected releasetype : returns : the selected releasetype : rtype : str : raises : None"""
for rt , rb in self . _releasetype_button_mapping . items ( ) : if rb . isChecked ( ) : return rt
def check_hierarchy ( rdf , break_cycles , keep_related , mark_top_concepts , eliminate_redundancy ) : """Check for , and optionally fix , problems in the skos : broader hierarchy using a recursive depth first search algorithm . : param Graph rdf : An rdflib . graph . Graph object . : param bool fix _ cycles ...
starttime = time . time ( ) if check . hierarchy_cycles ( rdf , break_cycles ) : logging . info ( "Some concepts not reached in initial cycle detection. " "Re-checking for loose concepts." ) setup_top_concepts ( rdf , mark_top_concepts ) check . disjoint_relations ( rdf , not keep_related ) check . hierarchical...
def initialize ( cls ) : """Initialize the TLS / SSL platform to prepare it for making AMQP requests . This only needs to happen once ."""
if cls . initialized : _logger . debug ( "Platform already initialized." ) else : _logger . debug ( "Initializing platform." ) c_uamqp . platform_init ( ) cls . initialized = True
def id_by_index ( index , resources ) : """Helper method to fetch the id or address of a resource by its index Args : resources ( list of objects ) : The resources to be paginated index ( integer ) : The index of the target resource Returns : str : The address or header _ signature of the resource , ret...
if index < 0 or index >= len ( resources ) : return '' try : return resources [ index ] . header_signature except AttributeError : return resources [ index ] . address
def visit_ImportFrom ( self , node ) : """Register imported modules and usage symbols ."""
module_path = tuple ( node . module . split ( '.' ) ) self . imports . add ( module_path [ 0 ] ) for alias in node . names : path = module_path + ( alias . name , ) self . symbols [ alias . asname or alias . name ] = path self . update = True return None
def slice_time ( begin , end = None , duration = datetime . timedelta ( days = 2 ) ) : """: param begin : datetime : param end : datetime : param duration : timedelta : return : a generator for a set of timeslices of the given duration"""
duration_ms = int ( duration . total_seconds ( ) * 1000 ) previous = int ( unix_time ( begin ) * 1000 ) next = previous + duration_ms now_ms = unix_time ( datetime . datetime . now ( ) ) * 1000 end_slice = now_ms if not end else min ( now_ms , int ( unix_time ( end ) * 1000 ) ) while next < end_slice : yield TimeSl...
def extend ( self , cli_api , command_prefix = "" , sub_command = "" , ** kwargs ) : """Extends this CLI api with the commands present in the provided cli _ api object"""
if sub_command and command_prefix : raise ValueError ( 'It is not currently supported to provide both a command_prefix and sub_command' ) if sub_command : self . commands [ sub_command ] = cli_api else : for name , command in cli_api . commands . items ( ) : self . commands [ "{}{}" . format ( comma...
def estimategaps ( args ) : """% prog estimategaps input . bed Estimate sizes of inter - scaffold gaps . The AGP file generated by path ( ) command has unknown gap sizes with a generic number of Ns ( often 100 Ns ) . The AGP file ` input . chr . agp ` will be modified in - place ."""
p = OptionParser ( estimategaps . __doc__ ) p . add_option ( "--minsize" , default = 100 , type = "int" , help = "Minimum gap size" ) p . add_option ( "--maxsize" , default = 500000 , type = "int" , help = "Maximum gap size" ) p . add_option ( "--links" , default = 10 , type = "int" , help = "Only use linkage grounds w...
def plot_confidence ( self , lower = 2.5 , upper = 97.5 , plot_limits = None , fixed_inputs = None , resolution = None , plot_raw = False , apply_link = False , visible_dims = None , which_data_ycols = 'all' , label = 'gp confidence' , predict_kw = None , ** kwargs ) : """Plot the confidence interval between the pe...
canvas , kwargs = pl ( ) . new_canvas ( ** kwargs ) ycols = get_which_data_ycols ( self , which_data_ycols ) X = get_x_y_var ( self ) [ 0 ] helper_data = helper_for_plot_data ( self , X , plot_limits , visible_dims , fixed_inputs , resolution ) helper_prediction = helper_predict_with_model ( self , helper_data [ 2 ] , ...
def bfd ( items , targets , ** kwargs ) : """Best - Fit Decreasing Complexity O ( n ^ 2)"""
sizes = zip ( items , weight ( items , ** kwargs ) ) sizes = sorted ( sizes , key = operator . itemgetter ( 1 ) , reverse = True ) items = map ( operator . itemgetter ( 0 ) , sizes ) return bf ( items , targets , ** kwargs )
def key_diff ( key_bundle , key_defs ) : """Creates a difference dictionary with keys that should added and keys that should be deleted from a Key Bundle to get it updated to a state that mirrors What is in the key _ defs specification . : param key _ bundle : The original KeyBundle : param key _ defs : A s...
keys = key_bundle . get ( ) diff = { } # My own sorted copy key_defs = order_key_defs ( key_defs ) [ : ] used = [ ] for key in keys : match = False for kd in key_defs : if key . use not in kd [ 'use' ] : continue if key . kty != kd [ 'type' ] : continue if key . k...
def _match_cubes ( ccube_clean , ccube_dirty , bexpcube_clean , bexpcube_dirty , hpx_order ) : """Match the HEALPIX scheme and order of all the input cubes return a dictionary of cubes with the same HEALPIX scheme and order"""
if hpx_order == ccube_clean . hpx . order : ccube_clean_at_order = ccube_clean else : ccube_clean_at_order = ccube_clean . ud_grade ( hpx_order , preserve_counts = True ) if hpx_order == ccube_dirty . hpx . order : ccube_dirty_at_order = ccube_dirty else : ccube_dirty_at_order = ccube_dirty . ud_grade (...
def create_event ( self , register = False ) : """Create an asyncio . Event inside the emulation loop . This method exists as a convenience to create an Event object that is associated with the correct EventLoop ( ) . If you pass register = True , then the event will be registered as an event that must be set...
event = asyncio . Event ( loop = self . _loop ) if register : self . _events . add ( event ) return event
def delete ( path , version = - 1 , recursive = False , profile = None , hosts = None , scheme = None , username = None , password = None , default_acl = None ) : '''Delete znode path path to znode version only delete if version matches ( Default : - 1 ( always matches ) ) profile Configured Zookeeper p...
conn = _get_zk_conn ( profile = profile , hosts = hosts , scheme = scheme , username = username , password = password , default_acl = default_acl ) return conn . delete ( path , version , recursive )
def unicode ( self , b , encoding = None ) : """Convert a byte string to unicode , using string _ encoding and decode _ errors . Arguments : b : a byte string . encoding : the name of an encoding . Defaults to the string _ encoding attribute for this instance . Raises : TypeError : Because this method c...
if encoding is None : encoding = self . string_encoding # TODO : Wrap UnicodeDecodeErrors with a message about setting # the string _ encoding and decode _ errors attributes . return unicode ( b , encoding , self . decode_errors )
def setCheckedRecords ( self , records , column = 0 , parent = None ) : """Sets the checked items based on the inputed list of records . : param records | [ < orb . Table > , . . ] parent | < QTreeWidgetItem > | | None"""
if parent is None : for i in range ( self . topLevelItemCount ( ) ) : item = self . topLevelItem ( i ) try : has_record = item . record ( ) in records except AttributeError : has_record = False if has_record : item . setCheckState ( column , Qt . C...
def get_tree ( ident_hash , baked = False ) : """Return a tree structure of the Collection"""
id , version = get_id_n_version ( ident_hash ) stmt = _get_sql ( 'get-tree.sql' ) args = dict ( id = id , version = version , baked = baked ) with db_connect ( ) as db_conn : with db_conn . cursor ( ) as cursor : cursor . execute ( stmt , args ) try : tree = cursor . fetchone ( ) [ 0 ] ...
def __collapse_stranded ( s , proc_strands , names = False , verbose = False ) : """Get the union of a set of genomic intervals . given a list of genomic intervals with chromosome , start , end and strand fields , collapse those intervals with strand in the set < proc _ strands > into a set of non - overlappi...
def get_first_matching_index ( s , proc_strands ) : for i in range ( 0 , len ( s ) ) : if s [ i ] . strand in proc_strands : return i return None if proc_strands not in [ set ( "+" ) , set ( "-" ) , set ( [ "+" , "-" ] ) ] : raise GenomicIntervalError ( "failed collapsing intervals on st...
def synchronize_switch ( self , switch_ip , expected_acls , expected_bindings ) : """Update ACL config on a switch to match expected config This is done as follows : 1 . Get switch ACL config using show commands 2 . Update expected bindings based on switch LAGs 3 . Get commands to synchronize switch ACLs ...
# Get ACL rules and interface mappings from the switch switch_acls , switch_bindings = self . _get_dynamic_acl_info ( switch_ip ) # Adjust expected bindings for switch LAG config expected_bindings = self . adjust_bindings_for_lag ( switch_ip , expected_bindings ) # Get synchronization commands switch_cmds = list ( ) sw...
def perform_experiment ( self , engine_list ) : """Performs nearest neighbour experiments with custom vector data for all engines in the specified list . Returns self . result contains list of ( distance _ ratio , search _ time ) tuple . All are the averaged values over all request vectors . search _ time i...
# We will fill this array with measures for all the engines . result = [ ] # For each engine , first index vectors and then retrieve neighbours for engine in engine_list : print ( 'Engine %d / %d' % ( engine_list . index ( engine ) , len ( engine_list ) ) ) # Clean storage engine . clean_all_buckets ( ) ...
def get_metric_statistics ( Namespace = None , MetricName = None , Dimensions = None , StartTime = None , EndTime = None , Period = None , Statistics = None , ExtendedStatistics = None , Unit = None ) : """Gets statistics for the specified metric . Amazon CloudWatch retains metric data as follows : Note that Cl...
pass
def recv ( self , topic , payload , qos ) : """Receive a MQTT message . Call this method when a message is received from the MQTT broker ."""
data = self . _parse_mqtt_to_message ( topic , payload , qos ) if data is None : return _LOGGER . debug ( 'Receiving %s' , data ) self . add_job ( self . logic , data )
def make_limited_stream ( stream , limit ) : """Makes a stream limited ."""
if not isinstance ( stream , LimitedStream ) : if limit is None : raise TypeError ( 'stream not limited and no limit provided.' ) stream = LimitedStream ( stream , limit ) return stream
def _recv_internal ( self , timeout = None ) : """Read a message from kvaser device and return whether filtering has taken place ."""
arb_id = ctypes . c_long ( 0 ) data = ctypes . create_string_buffer ( 64 ) dlc = ctypes . c_uint ( 0 ) flags = ctypes . c_uint ( 0 ) timestamp = ctypes . c_ulong ( 0 ) if timeout is None : # Set infinite timeout # http : / / www . kvaser . com / canlib - webhelp / group _ _ _ c _ a _ n . html # ga2edd785a87cc16b49ece89...
def load_gene_exp_to_df ( inst_path ) : '''Loads gene expression data from 10x in sparse matrix format and returns a Pandas dataframe'''
import pandas as pd from scipy import io from scipy import sparse from ast import literal_eval as make_tuple # matrix Matrix = io . mmread ( inst_path + 'matrix.mtx' ) mat = Matrix . todense ( ) # genes filename = inst_path + 'genes.tsv' f = open ( filename , 'r' ) lines = f . readlines ( ) f . close ( ) # # add unique...
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) : """See : meth : ` superclass method < . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > ` for spec of input and result values ."""
# extracting dictionary of coefficients specific to required # intensity measure type . C = self . COEFFS [ imt ] # intensity on a reference soil is used for both mean # and stddev calculations . ln_y_ref = self . _get_ln_y_ref ( rup , dists , C ) # exp1 and exp2 are parts of eq . 7 exp1 = np . exp ( C [ 'phi3' ] * ( s...
def delete_workspace_config ( namespace , workspace , cnamespace , config ) : """Delete method configuration in workspace . Args : namespace ( str ) : project to which workspace belongs workspace ( str ) : Workspace name mnamespace ( str ) : Method namespace method ( str ) : Method name Swagger : http...
uri = "workspaces/{0}/{1}/method_configs/{2}/{3}" . format ( namespace , workspace , cnamespace , config ) return __delete ( uri )
def read_epw ( self ) : """Section 2 - Read EPW file properties : self . climateDataPath self . newPathName self . _ header # header data self . epwinput # timestep data for weather self . lat # latitude self . lon # longitude self . GMT # GMT self . nSoil # Number of soil depths self . Tsoil # ...
# Make dir path to epw file self . climateDataPath = os . path . join ( self . epwDir , self . epwFileName ) # Open epw file and feed csv data to climate _ data try : climate_data = utilities . read_csv ( self . climateDataPath ) except Exception as e : raise Exception ( "Failed to read epw file! {}" . format (...
def traverse_postorder ( self , leaves = True , internal = True ) : '''Perform a postorder traversal starting at this ` ` Node ` ` object Args : ` ` leaves ` ` ( ` ` bool ` ` ) : ` ` True ` ` to include leaves , otherwise ` ` False ` ` ` ` internal ` ` ( ` ` bool ` ` ) : ` ` True ` ` to include internal nodes...
s1 = deque ( ) ; s2 = deque ( ) ; s1 . append ( self ) while len ( s1 ) != 0 : n = s1 . pop ( ) ; s2 . append ( n ) ; s1 . extend ( n . children ) while len ( s2 ) != 0 : n = s2 . pop ( ) if ( leaves and n . is_leaf ( ) ) or ( internal and not n . is_leaf ( ) ) : yield n
def getErrorResponse ( self , errorCode , errorDescr ) : """This methods sets error attributes of an external method object ."""
self . errorCode = errorCode self . errorDescr = errorDescr self . response = "yes" return self
def adjacency_plot_und ( A , coor , tube = False ) : '''This function in matlab is a visualization helper which translates an adjacency matrix and an Nx3 matrix of spatial coordinates , and plots a 3D isometric network connecting the undirected unweighted nodes using a specific plotting format . Including the...
from mayavi import mlab n = len ( A ) nr_edges = ( n * n - 1 ) // 2 # starts = np . zeros ( ( nr _ edges , 3 ) ) # vecs = np . zeros ( ( nr _ edges , 3 ) ) # adjdat = np . zeros ( ( nr _ edges , ) ) ixes , = np . where ( np . triu ( np . ones ( ( n , n ) ) , 1 ) . flat ) # i = 0 # for r2 in xrange ( n ) : # for r1 in x...
def _zscore ( a ) : """Calculating z - score of data on the first axis . If the numbers in any column are all equal , scipy . stats . zscore will return NaN for this column . We shall correct them all to be zeros . Parameters a : numpy array Returns zscore : numpy array The z - scores of input " a "...
assert a . ndim > 1 , 'a must have more than one dimensions' zscore = scipy . stats . zscore ( a , axis = 0 ) zscore [ : , np . logical_not ( np . all ( np . isfinite ( zscore ) , axis = 0 ) ) ] = 0 return zscore
def _load_sequences_to_strain ( self , strain_id , force_rerun = False ) : """Load strain GEMPRO with functional genes defined , load sequences to it , save as new GEMPRO"""
gp_seqs_path = op . join ( self . model_dir , '{}_gp_withseqs.pckl' . format ( strain_id ) ) if ssbio . utils . force_rerun ( flag = force_rerun , outfile = gp_seqs_path ) : gp_noseqs = ssbio . io . load_pickle ( self . strain_infodict [ strain_id ] [ 'gp_noseqs_path' ] ) strain_sequences = SeqIO . index ( self...
def analytics ( account = None , * args , ** kwargs ) : """Simple Google Analytics integration . First looks for an ` ` account ` ` parameter . If not supplied , uses Django ` ` GOOGLE _ ANALYTICS _ ACCOUNT ` ` setting . If account not set , raises ` ` TemplateSyntaxError ` ` . : param account : Google An...
if not account : try : account = settings . GOOGLE_ANALYTICS_ACCOUNT except : raise template . TemplateSyntaxError ( "Analytics account could not found either " "in tag parameters or settings" ) return { 'account' : account , 'params' : kwargs }
def _to_solr ( self , data ) : '''Sends data to a Solr instance .'''
return self . _dest . index_json ( self . _dest_coll , json . dumps ( data , sort_keys = True ) )
def trifurcate_base ( cls , newick ) : """Rewrites a newick string so that the base is a trifurcation ( usually means an unrooted tree )"""
t = cls ( newick ) t . _tree . deroot ( ) return t . newick
def likelihood ( self , outcomes , modelparams , expparams ) : """Calculates the likelihood function at the states specified by modelparams and measurement specified by expparams . This is given by the Born rule and is the probability of outcomes given the state and measurement operator ."""
# By calling the superclass implementation , we can consolidate # call counting there . super ( MultiQubitStatePauliModel , self ) . likelihood ( outcomes , modelparams , expparams ) # Note that expparams [ ' axis ' ] has shape ( n _ exp , 3 ) . pr0 = 0.5 * ( 1 + modelparams [ : , expparams [ 'pauli' ] ] ) # Use the fo...
def create_box ( self , orientation = Gtk . Orientation . HORIZONTAL , spacing = 0 ) : """Function creates box . Based on orientation it can be either HORIZONTAL or VERTICAL"""
h_box = Gtk . Box ( orientation = orientation , spacing = spacing ) h_box . set_homogeneous ( False ) return h_box
def local ( ) : """Load local requirements file ."""
logger . info ( "Loading requirements from local file." ) with open ( REQUIREMENTS_FILE , 'r' ) as f : requirements = parse ( f ) for r in requirements : logger . debug ( "Creating new package: %r" , r ) create_package_version ( r )
def _data_from_response ( self , resp_body , key = None ) : """This works for most API responses , but some don ' t structure their listing responses the same way , so overriding this method allows subclasses to handle extraction for those outliers ."""
if key : data = resp_body . get ( key ) else : data = resp_body . get ( self . plural_response_key , resp_body ) # NOTE ( ja ) : some services , such as keystone returns values as list as # { " values " : [ . . . ] } unlike other services which just return the # list . if isinstance ( data , dict ) : try : ...
def deactivate ( self , plugins = [ ] ) : """Deactivates given plugins . A given plugin must be activated , otherwise it is ignored and no action takes place ( no signals are fired , no deactivate functions are called . ) A deactivated plugin is still loaded and initialised and can be reactivated by calling :...
self . _log . debug ( "Plugins Deactivation started" ) if not isinstance ( plugins , list ) : raise AttributeError ( "plugins must be a list, not %s" % type ( plugins ) ) self . _log . debug ( "Plugins to deactivate: %s" % ", " . join ( plugins ) ) plugins_deactivated = [ ] for plugin_name in plugins : if not i...
def post_event_unpublish ( self , id , ** data ) : """POST / events / : id / unpublish / Unpublishes an event . In order for a free event to be unpublished , it must not have any pending or completed orders , even if the event is in the past . In order for a paid event to be unpublished , it must not have any p...
return self . post ( "/events/{0}/unpublish/" . format ( id ) , data = data )
def _set_dst_vtep_ip_any ( self , v , load = False ) : """Setter method for dst _ vtep _ ip _ any , mapped from YANG variable / overlay / access _ list / type / vxlan / standard / seq / dst _ vtep _ ip _ any ( empty ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ dst ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGBool , is_leaf = True , yang_name = "dst-vtep-ip-any" , rest_name = "dst-vtep-ip-any" , parent = self , choice = ( u'choice-dst-vtep-ip' , u'case-dst-vtep-ip-any' ) , path_helper = self . _path_helper , extmethods = self ...
def sff ( args ) : """% prog sff sffiles Convert reads formatted as 454 SFF file , and convert to CA frg file . Turn - - nodedup on if another deduplication mechanism is used ( e . g . CD - HIT - 454 ) . See assembly . sff . deduplicate ( ) ."""
p = OptionParser ( sff . __doc__ ) p . add_option ( "--prefix" , dest = "prefix" , default = None , help = "Output frg filename prefix" ) p . add_option ( "--nodedup" , default = False , action = "store_true" , help = "Do not remove duplicates [default: %default]" ) p . set_size ( ) opts , args = p . parse_args ( args ...