signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_default_config_help ( self ) : """Returns the help text for the configuration options for this handler"""
config = super ( rmqHandler , self ) . get_default_config_help ( ) config . update ( { 'server' : '' , 'rmq_exchange' : '' , } ) return config
def getEndpoint ( self ) : """Retrieve the NS1 API Endpoint URL that will be used for requests . : return : URL of the NS1 API that will be used for requests"""
port = '' endpoint = '' keyConfig = self . getKeyConfig ( ) if 'port' in keyConfig : port = ':' + keyConfig [ 'port' ] elif self . _data [ 'port' ] != self . PORT : port = ':' + self . _data [ 'port' ] if 'endpoint' in keyConfig : endpoint = keyConfig [ 'endpoint' ] else : endpoint = self . _data [ 'end...
def join_json_files ( prefix ) : """Join different REACH output JSON files into a single JSON object . The output of REACH is broken into three files that need to be joined before processing . Specifically , there will be three files of the form : ` < prefix > . uaz . < subcategory > . json ` . Parameters ...
try : with open ( prefix + '.uaz.entities.json' , 'rt' ) as f : entities = json . load ( f ) with open ( prefix + '.uaz.events.json' , 'rt' ) as f : events = json . load ( f ) with open ( prefix + '.uaz.sentences.json' , 'rt' ) as f : sentences = json . load ( f ) except IOError as e...
def ReadApprovalRequests ( self , requestor_username , approval_type , subject_id = None , include_expired = False , cursor = None ) : """Reads approval requests of a given type for a given user ."""
query = """ SELECT ar.approval_id, UNIX_TIMESTAMP(ar.timestamp), ar.approval_request, u.username, UNIX_TIMESTAMP(ag.timestamp) FROM approval_request ar LEFT JOIN approval_grant AS ag USING (username_hash, approval_id) LEFT JOIN ...
def yoffset ( self , value ) : """gets / sets the yoffset"""
if self . _yoffset != value and isinstance ( value , ( int , float , long ) ) : self . _yoffset = value
def timer ( name , reservoir_type = "uniform" , * reservoir_args , ** reservoir_kwargs ) : """Time - measuring context manager : the time spent in the wrapped block if measured and added to the named metric ."""
hmetric = get_or_create_histogram ( name , reservoir_type , * reservoir_args , ** reservoir_kwargs ) t1 = time . time ( ) yield t2 = time . time ( ) hmetric . notify ( t2 - t1 )
def generate_unique_key ( master_key_path , url ) : """Input1 : Path to the BD2K Master Key ( for S3 Encryption ) Input2 : S3 URL ( e . g . https : / / s3 - us - west - 2 . amazonaws . com / cgl - driver - projects - encrypted / wcdt / exome _ bams / DTB - 111 - N . bam ) Returns : 32 - byte unique key generate...
with open ( master_key_path , 'r' ) as f : master_key = f . read ( ) assert len ( master_key ) == 32 , 'Invalid Key! Must be 32 characters. ' 'Key: {}, Length: {}' . format ( master_key , len ( master_key ) ) new_key = hashlib . sha256 ( master_key + url ) . digest ( ) assert len ( new_key ) == 32 , 'New key is inv...
def append ( self , box ) : """Append a JP2 box to the file in - place . Parameters box : Jp2Box Instance of a JP2 box . Only UUID and XML boxes can currently be appended ."""
if self . _codec_format == opj2 . CODEC_J2K : msg = "Only JP2 files can currently have boxes appended to them." raise IOError ( msg ) if not ( ( box . box_id == 'xml ' ) or ( box . box_id == 'uuid' and box . uuid == UUID ( 'be7acfcb-97a9-42e8-9c71-999491e3afac' ) ) ) : msg = ( "Only XML boxes and XMP UUID b...
def group_experiments ( experiments : TomographyExperiment , method : str = 'greedy' ) -> TomographyExperiment : """Group experiments that are diagonal in a shared tensor product basis ( TPB ) to minimize number of QPU runs . Background Given some PauliTerm operator , the ' natural ' tensor product basis to ...
allowed_methods = [ 'greedy' , 'clique-removal' ] assert method in allowed_methods , f"'method' should be one of {allowed_methods}." if method == 'greedy' : return group_experiments_greedy ( experiments ) elif method == 'clique-removal' : return group_experiments_clique_removal ( experiments )
def refresh ( self , credentials = False ) : """GET / : login / machines / : id : param credentials : whether to return machine passwords : type credentials : : py : class : ` bool ` Fetch the existing state and values for the : py : class : ` smartdc . machine . Machine ` from the datacenter and commit the...
data = self . datacenter . raw_machine_data ( self . id , credentials = credentials ) self . _save ( data )
def libvlc_media_list_player_set_media_list ( p_mlp , p_mlist ) : '''Set the media list associated with the player . @ param p _ mlp : media list player instance . @ param p _ mlist : list of media .'''
f = _Cfunctions . get ( 'libvlc_media_list_player_set_media_list' , None ) or _Cfunction ( 'libvlc_media_list_player_set_media_list' , ( ( 1 , ) , ( 1 , ) , ) , None , None , MediaListPlayer , MediaList ) return f ( p_mlp , p_mlist )
def handle_topic ( self , params ) : """Handle a topic command ."""
channel_name , sep , topic = params . partition ( ' ' ) channel = self . server . channels . get ( channel_name ) if not channel : raise IRCError . from_name ( 'nosuchnick' , 'PRIVMSG :%s' % channel_name ) if channel . name not in self . channels : # The user isn ' t in the channel . raise IRCError . from_name ...
def get_osdp ( self , id_or_uri ) : """Retrieves facts about Server Profiles and Server Profile Templates that are using Deployment Plan based on the ID or URI provided . Args : id _ or _ uri : ID or URI of the Deployment Plan . Returns : dict : Server Profiles and Server Profile Templates"""
uri = self . _client . build_subresource_uri ( resource_id_or_uri = id_or_uri , subresource_path = "osdp" ) return self . _client . get ( uri )
def switch_name_style ( self , http_protocol_version ) : """Return object copy with header names saved as it is described in the given protocol version see : meth : ` . WHTTPHeaders . normalize _ name ` : param http _ protocol _ version : target HTTP protocol version : return : WHTTPHeaders"""
new_headers = WHTTPHeaders ( ) new_headers . __normalization_mode = http_protocol_version names = self . headers ( ) for name in names : new_headers . add_headers ( name , * self . get_headers ( name ) ) for cookie_name in self . __set_cookies . cookies ( ) : new_headers . __set_cookies . add_cookie ( self . __...
def queue_exists ( name , region , opts = None , user = None ) : '''Returns True or False on whether the queue exists in the region name Name of the SQS queue to search for region Name of the region to search for the queue in opts : None Any additional options to add to the command line user : None ...
output = list_queues ( region , opts , user ) return name in _parse_queue_list ( output )
def request_forward_agent ( self , handler ) : """Request for a forward SSH Agent on this channel . This is only valid for an ssh - agent from OpenSSH ! ! ! : param handler : a required callable handler to use for incoming SSH Agent connections : return : True if we are ok , else False ( at that time we...
m = Message ( ) m . add_byte ( cMSG_CHANNEL_REQUEST ) m . add_int ( self . remote_chanid ) m . add_string ( "auth-agent-req@openssh.com" ) m . add_boolean ( False ) self . transport . _send_user_message ( m ) self . transport . _set_forward_agent_handler ( handler ) return True
def resolve_dep_from_path ( self , depname ) : """If we can find the dep in the PATH , then we consider it to be a system dependency that we should not bundle in the package"""
if is_system_dep ( depname ) : return True for d in self . _path : name = os . path . join ( d , depname ) if os . path . exists ( name ) : return True return False
def state ( name , tgt , ssh = False , tgt_type = 'glob' , ret = '' , ret_config = None , ret_kwargs = None , highstate = None , sls = None , top = None , saltenv = None , test = None , pillar = None , pillarenv = None , expect_minions = True , fail_minions = None , allow_fail = 0 , exclude = None , concurrent = False ...
cmd_kw = { 'arg' : [ ] , 'kwarg' : { } , 'ret' : ret , 'timeout' : timeout } if ret_config : cmd_kw [ 'ret_config' ] = ret_config if ret_kwargs : cmd_kw [ 'ret_kwargs' ] = ret_kwargs state_ret = { 'name' : name , 'changes' : { } , 'comment' : '' , 'result' : True } try : allow_fail = int ( allow_fail ) exce...
def signal_stop ( self , action , c_name , ** kwargs ) : """Stops a container , either using the default client stop method , or sending a custom signal and waiting for the container to stop . : param action : Action configuration . : type action : dockermap . map . runner . ActionConfig : param c _ name : ...
client = action . client sig = action . config . stop_signal stop_kwargs = self . get_container_stop_kwargs ( action , c_name , kwargs = kwargs ) if not sig or sig == 'SIGTERM' or sig == signal . SIGTERM : try : client . stop ( ** stop_kwargs ) except Timeout : log . warning ( "Container %s did ...
def get_schema_path ( self , schemas_folder ) : """Return a file protocol URI e . g . file : / / / D : / mappyfile / mappyfile / schemas / on Windows and file : / / / / home / user / mappyfile / mappyfile / schemas / on Linux"""
# replace any Windows path back slashes with forward slashes schemas_folder = schemas_folder . replace ( "\\" , "/" ) # HACK Python 2.7 on Linux seems to remove the root slash # so add this back in if schemas_folder . startswith ( "/" ) : schemas_folder = "/" + schemas_folder host = "" root_schema_path = "file://{}...
def get_typecast ( self ) : """Returns the typecast or ` ` None ` ` of this object as a string ."""
midx , marker = self . token_next_by ( m = ( T . Punctuation , '::' ) ) nidx , next_ = self . token_next ( midx , skip_ws = False ) return next_ . value if next_ else None
def m21_to_stream ( score , synth = ks_synth , beat = 90 , fdur = 2. , pad_dur = .5 , rate = lz . DEFAULT_SAMPLE_RATE ) : """Converts Music21 data to a Stream object . Parameters score : A Music21 data , usually a music21 . stream . Score instance . synth : A function that receives a frequency as input an...
# Configuration s , Hz = lz . sHz ( rate ) step = 60. / beat * s # Creates a score from the music21 data score = reduce ( operator . concat , [ [ ( pitch . frequency * Hz , # Note note . offset * step , # Starting time note . quarterLength * step , # Duration Fermata in note . expressions ) for pitch in note . pitches ...
def getTemplateInstruments ( self ) : """Returns worksheet templates as JSON"""
items = dict ( ) templates = self . _get_worksheet_templates_brains ( ) for template in templates : template_obj = api . get_object ( template ) uid_template = api . get_uid ( template_obj ) instrument = template_obj . getInstrument ( ) uid_instrument = "" if instrument : uid_instrument = ap...
def timeout ( delay , call , * args , ** kwargs ) : """Run a function call for ` delay ` seconds , and raise a RuntimeError if the operation didn ' t complete ."""
return_value = None def target ( ) : nonlocal return_value return_value = call ( * args , ** kwargs ) t = Thread ( target = target ) t . start ( ) t . join ( delay ) if t . is_alive ( ) : raise RuntimeError ( "Operation did not complete within time." ) return return_value
def fit_transform_table ( self , table , table_meta , transformer_dict = None , transformer_list = None , missing = None ) : """Create , apply and store the specified transformers for ` table ` . Args : table ( pandas . DataFrame ) : Contents of the table to be transformed . table _ meta ( dict ) : Metadata f...
if missing is None : missing = self . missing else : self . missing = missing warnings . warn ( DEPRECATION_MESSAGE . format ( 'fit_transform_table' ) , DeprecationWarning ) result = pd . DataFrame ( ) table_name = table_meta [ 'name' ] for field in table_meta [ 'fields' ] : col_name = field [ 'name' ] ...
def get ( self , key ) : """Return the value of a field . Take a string argument representing a field name , return the value of that field at the time of this TimeMachine . When restoring a ForeignKey - pointer object that doesn ' t exist , raise DisciplineException"""
modcommit = self . _get_modcommit ( key ) if not modcommit : return None # If this isn ' t a ForeignKey , then just return the value if key not in self . foreignkeys : return cPickle . loads ( str ( modcommit . value ) ) # If it is , then return the object instance try : return TimeMachine ( uid = modcommit...
def notify ( self , name , job ) : """Concrete method of Subject . notify ( ) . Notify to change the status of Subject for observer . This method call Observer . update ( ) . In this program , ConfigReader . notify ( ) call JobObserver . update ( ) . For exmaple , register threads . redis . ConcreateJob to ...
for observer in self . _observers : observer . update ( name , job )
def get_flux ( self , reaction ) : """Get resulting flux value for reaction ."""
return self . _prob . result . get_value ( self . _v ( reaction ) )
def convrt ( x , inunit , outunit ) : """Take a measurement X , the units associated with X , and units to which X should be converted ; return Y the value of the measurement in the output units . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / convrt _ c . html : param x : N...
inunit = stypes . stringToCharP ( inunit ) outunit = stypes . stringToCharP ( outunit ) y = ctypes . c_double ( ) if hasattr ( x , "__iter__" ) : outArray = [ ] for n in x : libspice . convrt_c ( n , inunit , outunit , ctypes . byref ( y ) ) outArray . append ( y . value ) return outArray x ...
def buscar ( self ) : """Faz a busca das informações do objeto no Postmon . Retorna um ` ` bool ` ` indicando se a busca foi bem sucedida ."""
headers = { 'User-Agent' : self . user_agent } try : self . _response = requests . get ( self . url , headers = headers ) except requests . RequestException : logger . exception ( "%s.buscar() falhou: GET %s" % ( self . __class__ . __name__ , self . url ) ) return False if self . _response . ok : self ....
def _parse_forces ( line , lines ) : """Parse the forces block , including individual terms ( e . g . Hubbard )"""
units = line . split ( ) [ 4 ] . rstrip ( ":" ) next ( lines ) newline = next ( lines ) total = [ ] ; non_local = [ ] ; ionic = [ ] ; local = [ ] ; core_correction = [ ] hubbard = [ ] ; scf = [ ] ; types = [ ] while ( not "The non-local contrib." in newline ) and len ( newline . split ( ) ) > 0 : if "=" in newline ...
def to_url ( self , obj ) : """Reconstruct the URL from level name , code or datagouv id and slug ."""
level_name = getattr ( obj , 'level_name' , None ) if not level_name : raise ValueError ( 'Unable to serialize "%s" to url' % obj ) code = getattr ( obj , 'code' , None ) slug = getattr ( obj , 'slug' , None ) validity = getattr ( obj , 'validity' , None ) if code and slug : return '{level_name}/{code}@{start_d...
def _indexes ( arr ) : """Returns the list of all indexes of the given array . Currently works for one and two - dimensional arrays"""
myarr = np . array ( arr ) if myarr . ndim == 1 : return list ( range ( len ( myarr ) ) ) elif myarr . ndim == 2 : return tuple ( itertools . product ( list ( range ( arr . shape [ 0 ] ) ) , list ( range ( arr . shape [ 1 ] ) ) ) ) else : raise NotImplementedError ( 'Only supporting arrays of dimension 1 an...
def sort_matrix ( a , n = 0 ) : """This will rearrange the array a [ n ] from lowest to highest , and rearrange the rest of a [ i ] ' s in the same way . It is dumb and slow . Returns a numpy array ."""
a = _n . array ( a ) return a [ : , a [ n , : ] . argsort ( ) ]
def process_bulk_vm_event ( self , msg , phy_uplink ) : """Process the VM bulk event usually after a restart ."""
LOG . info ( "In processing Bulk VM Event status %s" , msg ) time . sleep ( 3 ) if ( not self . uplink_det_compl or phy_uplink not in self . ovs_vdp_obj_dict ) : # This condition shouldn ' t be hit as only when uplink is obtained , # save _ uplink is called and that in turns calls this process _ bulk . LOG . error ...
def filter ( self , * filter , ** kw ) : # @ ReservedAssignment """Filter results for specific element type . keyword arguments can be used to specify a match against the elements attribute directly . It ' s important to note that if the search filter contains a / or - , the SMC will only search the name an...
iexact = None if filter : _filter = filter [ 0 ] exact_match = kw . pop ( 'exact_match' , False ) case_sensitive = kw . pop ( 'case_sensitive' , True ) if kw : _ , value = next ( iter ( kw . items ( ) ) ) _filter = value iexact = kw # Only strip metachars from network and address range if not exact_matc...
def parse_dimension ( self , node ) : """Parses < Dimension > @ param node : Node containing the < Dimension > element @ type node : xml . etree . Element @ raise ParseError : When the name is not a string or if the dimension is not a signed integer ."""
try : name = node . lattrib [ 'name' ] except : self . raise_error ( '<Dimension> must specify a name' ) description = node . lattrib . get ( 'description' , '' ) dim = dict ( ) for d in [ 'l' , 'm' , 't' , 'i' , 'k' , 'c' , 'n' ] : dim [ d ] = int ( node . lattrib . get ( d , 0 ) ) self . model . add_dimen...
def getVariantAnnotationId ( self , gaVariant , gaAnnotation ) : """Produces a stringified compoundId representing a variant annotation . : param gaVariant : protocol . Variant : param gaAnnotation : protocol . VariantAnnotation : return : compoundId String"""
md5 = self . hashVariantAnnotation ( gaVariant , gaAnnotation ) compoundId = datamodel . VariantAnnotationCompoundId ( self . getCompoundId ( ) , gaVariant . reference_name , str ( gaVariant . start ) , md5 ) return str ( compoundId )
def next_frame_id ( self ) : """Gets a byte of the next valid frame ID ( 1 - 255 ) , increments the internal _ frame _ id counter and wraps it back to 1 if necessary ."""
# Python 2/3 compatible way of converting 1 to " \ x01 " in py2 or b " \ x01" # in py3. fid = bytes ( bytearray ( ( self . _frame_id , ) ) ) self . _frame_id += 1 if self . _frame_id > 0xFF : self . _frame_id = 1 try : del self . _rx_frames [ fid ] except KeyError : pass return fid
def response_as_single ( self , copy = 0 ) : """convert the response map to a single data frame with Multi - Index columns"""
arr = [ ] for sid , frame in self . response . iteritems ( ) : if copy : frame = frame . copy ( ) 'security' not in frame and frame . insert ( 0 , 'security' , sid ) arr . append ( frame . reset_index ( ) . set_index ( [ 'date' , 'security' ] ) ) return concat ( arr ) . unstack ( )
def send ( self , record , message , resource = None , labels = None , trace = None , span_id = None ) : """Overrides transport . send ( ) . : type record : : class : ` logging . LogRecord ` : param record : Python log record that the handler was called with . : type message : str : param message : The mess...
info = { "message" : message , "python_logger" : record . name } self . logger . log_struct ( info , severity = record . levelname , resource = resource , labels = labels , trace = trace , span_id = span_id , )
def set_resubscription_params ( self , addresses = None , bind_to = None ) : """You can specify a dgram address ( udp or unix ) on which all of the subscriptions request will be forwarded to ( obviously changing the node address to the router one ) . The system could be useful to build ' federated ' setup . *...
self . _set_aliased ( 'resubscribe' , addresses , multi = True ) self . _set_aliased ( 'resubscribe-bind' , bind_to ) return self
def scan_dir ( self , path ) : r"""Scan a directory on disk for color table files and add them to the registry . Parameters path : str The path to the directory with the color tables"""
for fname in glob . glob ( os . path . join ( path , '*' + TABLE_EXT ) ) : if os . path . isfile ( fname ) : with open ( fname , 'r' ) as fobj : try : self . add_colortable ( fobj , os . path . splitext ( os . path . basename ( fname ) ) [ 0 ] ) log . debug ( 'Add...
def collective_dr_squared ( self ) : """Squared sum of total displacements for these atoms . Args : None Returns : ( Float ) : The square of the summed total displacements for these atoms ."""
return sum ( np . square ( sum ( [ atom . dr for atom in self . atoms ] ) ) )
def getEstimatedNodeCounts ( self , queuedJobShapes , currentNodeCounts ) : """Given the resource requirements of queued jobs and the current size of the cluster , returns a dict mapping from nodeShape to the number of nodes we want in the cluster right now ."""
nodesToRunQueuedJobs = binPacking ( jobShapes = queuedJobShapes , nodeShapes = self . nodeShapes , goalTime = self . targetTime ) estimatedNodeCounts = { } for nodeShape in self . nodeShapes : nodeType = self . nodeShapeToType [ nodeShape ] logger . debug ( "Nodes of type %s to run queued jobs = " "%s" % ( node...
def search_name ( self , name , dom = None ) : """name find function abbreviation"""
if dom is None : dom = self . browser return expect ( dom . find_by_name , args = [ name ] )
def thresh ( data , threshold , threshold_type = 'hard' ) : r"""Threshold data This method perfoms hard or soft thresholding on the input data Parameters data : np . ndarray , list or tuple Input data array threshold : float or np . ndarray Threshold level ( s ) threshold _ type : str { ' hard ' , ' s...
data = np . array ( data ) if threshold_type not in ( 'hard' , 'soft' ) : raise ValueError ( 'Invalid threshold type. Options are "hard" or' '"soft"' ) if threshold_type == 'soft' : return np . around ( np . maximum ( ( 1.0 - threshold / np . maximum ( np . finfo ( np . float64 ) . eps , np . abs ( data ) ) ) ,...
def pretty_call ( ctx , fn , * args , ** kwargs ) : """Returns a Doc that represents a function call to : keyword : ` fn ` with the remaining positional and keyword arguments . You can only use this function on Python 3.6 + . On Python 3.5 , the order of keyword arguments is not maintained , and you have to u...
return pretty_call_alt ( ctx , fn , args , kwargs )
def load ( self , value : Any , type_ : Type [ T ] , * , annotation : Optional [ Annotation ] = None ) -> T : """Loads value into the typed data structure . TypeError is raised if there is no known way to treat type _ , otherwise all errors raise a ValueError ."""
try : index = self . index ( type_ ) except ValueError : raise TypedloadTypeError ( 'Cannot deal with value of type %s' % type_ , value = value , type_ = type_ ) # Add type to known types , to resolve ForwardRef later on if self . frefs is not None and hasattr ( type_ , '__name__' ) : tname = type_ . __name...
def from_blob ( cls , s ) : """Construct a molecular graph from the blob representation"""
atom_str , edge_str = s . split ( ) numbers = np . array ( [ int ( s ) for s in atom_str . split ( "," ) ] ) edges = [ ] orders = [ ] for s in edge_str . split ( "," ) : i , j , o = ( int ( w ) for w in s . split ( "_" ) ) edges . append ( ( i , j ) ) orders . append ( o ) return cls ( edges , numbers , np ...
def _updateHiddenStateTrajectories ( self ) : """Sample a new set of state trajectories from the conditional distribution P ( S | T , E , O )"""
self . model . hidden_state_trajectories = list ( ) for trajectory_index in range ( self . nobs ) : hidden_state_trajectory = self . _sampleHiddenStateTrajectory ( self . observations [ trajectory_index ] ) self . model . hidden_state_trajectories . append ( hidden_state_trajectory ) return
def _munch_off_batch ( self , queue ) : r"""Take a batch of sequences off the queue , and return pairs _ to _ run . The queue given as a parameter is affected"""
# if the number of CPUs used = = 1 , just pop one off ( which = = below ) # elif the the number of things in the queue is 1 , use all the CPUs and just that hmm if len ( queue ) == 1 or self . _num_cpus == 1 : pairs_to_run = [ [ queue . pop ( 0 ) , self . _num_cpus ] ] else : # else share out CPUs among hmmers ...
def long2ip ( l ) : """Convert a network byte order 32 - bit integer to a dotted quad ip address . > > > long2ip ( 2130706433) '127.0.0.1' > > > long2ip ( MIN _ IP ) '0.0.0.0' > > > long2ip ( MAX _ IP ) '255.255.255.255' > > > long2ip ( None ) # doctest : + IGNORE _ EXCEPTION _ DETAIL Traceback ( ...
if MAX_IP < l or l < MIN_IP : raise TypeError ( "expected int between %d and %d inclusive" % ( MIN_IP , MAX_IP ) ) return '%d.%d.%d.%d' % ( l >> 24 & 255 , l >> 16 & 255 , l >> 8 & 255 , l & 255 )
def ovsdb_server_method ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) ovsdb_server = ET . SubElement ( config , "ovsdb-server" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" ) name_key = ET . SubElement ( ovsdb_server , "name" ) name_key . text = kwargs . pop ( 'name' ) method = ET . SubElement ( ovsdb_server , "method" ) method . text = kwargs . pop ...
def flex_flow ( self ) : """: rtype : twilio . rest . flex _ api . v1 . flex _ flow . FlexFlowList"""
if self . _flex_flow is None : self . _flex_flow = FlexFlowList ( self ) return self . _flex_flow
def _cull ( self ) : """Remove calls more than 1 second old from the queue ."""
right_now = time . time ( ) cull_from = - 1 for index in range ( len ( self . _call_times ) ) : if right_now - self . _call_times [ index ] . time >= 1.0 : cull_from = index self . _outstanding_calls -= self . _call_times [ index ] . num_calls else : break if cull_from > - 1 : self ....
def loop ( self , value ) : """Indicates whether the playback should loop . Parameters value : bool True if playback should loop , False if not ."""
if not type ( value ) == bool : raise TypeError ( "can only be True or False" ) self . _loop = value
def format_cmdline ( args , maxwidth = 80 ) : '''Format args into a shell - quoted command line . The result will be wrapped to maxwidth characters where possible , not breaking a single long argument .'''
# Leave room for the space and backslash at the end of each line maxwidth -= 2 def lines ( ) : line = '' for a in ( shell_quote ( a ) for a in args ) : # If adding this argument will make the line too long , # yield the current line , and start a new one . if len ( line ) + len ( a ) + 1 > maxwidth ...
def peek ( self , n = None , constructor = list ) : """Sees / peeks the next few items in the Stream , without removing them . Besides that this functions keeps the Stream items , it ' s the same to the ` ` Stream . take ( ) ` ` method . See Also Stream . take : Returns the n first elements from the Strea...
return self . copy ( ) . take ( n = n , constructor = constructor )
def from_serializable_dict ( x ) : """Reconstruct a dictionary by recursively reconstructing all its keys and values . This is the most hackish part since we rely on key names such as _ _ name _ _ , _ _ class _ _ , _ _ module _ _ as metadata about how to reconstruct an object . TODO : It would be cleaner ...
if "__name__" in x : return _lookup_value ( x . pop ( "__module__" ) , x . pop ( "__name__" ) ) non_string_key_objects = [ from_json ( serialized_key ) for serialized_key in x . pop ( SERIALIZED_DICTIONARY_KEYS_FIELD , [ ] ) ] converted_dict = type ( x ) ( ) for k , v in x . items ( ) : serialized_key_index = p...
def _set_up_context ( cls ) : """Create context to keep all needed variables in ."""
cls . context = AttributeDict ( ) cls . context . new_meta = { } cls . context . new_transitions = { } cls . context . new_methods = { }
def _output_path ( self , ufo_or_font_name , ext , is_instance = False , interpolatable = False , autohinted = False , is_variable = False , output_dir = None , suffix = None , ) : """Generate output path for a font file with given extension ."""
if isinstance ( ufo_or_font_name , basestring ) : font_name = ufo_or_font_name elif ufo_or_font_name . path : font_name = os . path . splitext ( os . path . basename ( os . path . normpath ( ufo_or_font_name . path ) ) ) [ 0 ] else : font_name = self . _font_name ( ufo_or_font_name ) if output_dir is None :...
def _cleanup ( self ) : # pragma : no cover """cleans up data that ' s been in the cache for a while should be called from an async OS call like release ? to not impact user : return :"""
need_to_delete = [ ] # can ' t delete from a dict while iterating with self . attr_lock : now_time = time ( ) for path in self . cache : if now_time - self . attr [ path ] [ TIMESTAMP_KEY ] >= MAX_CACHE_TIME : need_to_delete . append ( path ) for path in need_to_delete : del self...
def mset ( self , args ) : """mset wrapper that batches keys per shard and execute as few msets as necessary to set the keys in all the shards involved . This method should be invoked on a TwemRedis instance as if it were being invoked directly on a StrictRedis instance ."""
key_map = collections . defaultdict ( dict ) result_count = 0 for key in args . keys ( ) : value = args [ key ] shard_num = self . get_shard_num_by_key ( key ) key_map [ shard_num ] [ key ] = value # TODO : parallelize for shard_num in key_map . keys ( ) : shard = self . get_shard_by_num ( shard_num ) ...
def AddArguments ( cls , argument_group ) : """Adds command line arguments to an argument group . This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports . Args : argument _ group ( argparse . _ ArgumentGroup | argparse . Argument...
argument_group . add_argument ( '--slice' , metavar = 'DATE' , dest = 'slice' , type = str , default = '' , action = 'store' , help = ( 'Create a time slice around a certain date. This parameter, if ' 'defined will display all events that happened X minutes before ' 'and after the defined date. X is controlled by the p...
def adjust_for_isolated ( self ) : """Remove certain plugins in order to handle the " isolated build " scenario ."""
if self . user_params . isolated . value : remove_plugins = [ ( "prebuild_plugins" , "check_and_set_rebuild" ) , ( "prebuild_plugins" , "stop_autorebuild_if_disabled" ) ] for when , which in remove_plugins : self . pt . remove_plugin ( when , which , 'removed from isolated build request' )
def calculate_boundingbox ( lng , lat , miles ) : """Given a latitude , longitude and a distance in miles , calculate the co - ordinates of the bounding box 2 * miles on long each side with the given co - ordinates at the center ."""
latChange = change_in_latitude ( miles ) latSouth = lat - latChange latNorth = lat + latChange lngChange = change_in_longitude ( lat , miles ) lngWest = lng + lngChange lngEast = lng - lngChange return ( lngWest , latSouth , lngEast , latNorth )
def _create_delegate_handler ( delegate ) : """Creates a handler function that creates a co - routine that can yield once with the given positional arguments to the delegate as a transition . Args : delegate ( Coroutine ) : The co - routine to delegate to . Returns : A : class : ` callable ` handler that ...
@ coroutine def handler ( * args ) : yield yield delegate . send ( Transition ( args , delegate ) ) return handler
def set_relay_ip_list ( addresses = None , server = _DEFAULT_SERVER ) : '''Set the RelayIpList list for the SMTP virtual server . Due to the unusual way that Windows stores the relay IPs , it is advisable to retrieve the existing list you wish to set from a pre - configured server . For example , setting ' 12...
setting = 'RelayIpList' formatted_addresses = list ( ) current_addresses = get_relay_ip_list ( server ) if list ( addresses ) == current_addresses : _LOG . debug ( '%s already contains the provided addresses.' , setting ) return True if addresses : # The WMI input data needs to be in the format used by RelayIpL...
def restoreSettings ( self , settings ) : """Restores properties for this tree widget from the inputed XML . : param xml | < xml . etree . ElementTree . Element > : return < bool > success"""
self . setUpdatesEnabled ( False ) self . blockSignals ( True ) # restore order data headerState = unwrapVariant ( settings . value ( 'headerState' ) ) if headerState is not None : state = QtCore . QByteArray . fromBase64 ( str ( headerState ) ) self . header ( ) . restoreState ( state ) sortingEnabled = unwrap...
def set ( self , key_or_attrs , value = None , unset = False ) : """在当前对象此字段上赋值 : param key _ or _ attrs : 字段名 , 或者一个包含 字段名 / 值的 dict : type key _ or _ attrs : string _ types or dict : param value : 字段值 : param unset : : return : 当前对象 , 供链式调用"""
if isinstance ( key_or_attrs , dict ) and value is None : attrs = key_or_attrs keys = attrs . keys ( ) for k in keys : if isinstance ( attrs [ k ] , LocalProxy ) : attrs [ k ] = attrs [ k ] . _get_current_object ( ) else : key = key_or_attrs if isinstance ( value , LocalProxy ) :...
def build ( self , grad_list , get_opt_fn ) : """Reduce the gradients , apply them with the optimizer , and set self . grads to # GPU number of lists of ( g , v ) , containing the all - reduced gradients on each device . Args : grad _ list ( [ [ ( grad , var ) , . . . ] , . . . ] ) : # GPU lists to be reduced...
assert len ( grad_list ) == len ( self . towers ) raw_devices = [ '/gpu:{}' . format ( k ) for k in self . towers ] DataParallelBuilder . _check_grad_list ( grad_list ) dtypes = set ( [ x [ 0 ] . dtype . base_dtype for x in grad_list [ 0 ] ] ) dtypes_nccl_supported = [ tf . float32 , tf . float64 ] if get_tf_version_tu...
def inverse ( self , vector , duration = None ) : '''Inverse vector transformer'''
ann = jams . Annotation ( namespace = self . namespace , duration = duration ) if duration is None : duration = 0 ann . append ( time = 0 , duration = duration , value = vector ) return ann
def _setup_chassis ( self ) : """Sets up the router with the corresponding chassis ( create slots and insert default adapters ) ."""
# With 1751 and 1760 , WICs in WIC slot 1 show up as in slot 1 , not 0 # e . g . s1/0 not s0/2 if self . _chassis in [ '1751' , '1760' ] : self . _create_slots ( 2 ) self . _slots [ 1 ] = C1700_MB_WIC1 ( ) else : self . _create_slots ( 1 ) self . _slots [ 0 ] = C1700_MB_1FE ( )
def create ( cls , name , database = SYSTEM_DATABASE , type = 2 ) : """Creates collection : param name Collection name : param database Database name in which it is created : param type Collection type ( 2 = document / 3 = edge ) : returns Collection"""
client = Client . instance ( ) api = client . api if client . database != database : database = client . database collection_data = { 'name' : name , 'type' : type , } data = api . collection . post ( data = collection_data ) collection = Collection ( name = name , database = database , api_resource = api . collect...
def return_concordance_word ( self , word : str , width : int = 150 , lines : int = 1000000 ) -> List [ str ] : """Makes concordance for ` ` word ` ` with the specified context window . Returns a list of concordance lines for the given input word . : param word : The target word : type word : str : param wi...
return_list = [ ] # type : List [ str ] half_width = ( width - len ( word ) - 2 ) // 2 # type : int context = width // 4 # type : int # approx number of words of context offsets = self . offsets ( word ) # type : List [ int ] if offsets : lines = min ( lines , len ( offsets ) ) while lines : for i in of...
def create_initial_tree ( channel ) : """create _ initial _ tree : Create initial tree structure Args : channel ( Channel ) : channel to construct Returns : tree manager to run rest of steps"""
# Create channel manager with channel data config . LOGGER . info ( " Setting up initial channel structure... " ) tree = ChannelManager ( channel ) # Make sure channel structure is valid config . LOGGER . info ( " Validating channel structure..." ) channel . print_tree ( ) tree . validate ( ) config . LOGGER . info...
def parse_size ( self , size = None ) : """Parse the size component of the path . / full / - > self . size _ full = True / max / - > self . size _ mac = True ( 2.1 and up ) / w , / - > self . size _ wh = ( w , None ) / , h / - > self . size _ wh = ( None , h ) / w , h / - > self . size _ wh = ( w , h ) ...
if ( size is not None ) : self . size = size self . size_pct = None self . size_bang = False self . size_full = False self . size_wh = ( None , None ) if ( self . size is None or self . size == 'full' ) : self . size_full = True return elif ( self . size == 'max' and self . api_version >= '2.1' ) : self...
def parse_polygonal_poi ( coords , response ) : """Parse areal POI way polygons from OSM node coords . Parameters coords : dict dict of node IDs and their lat , lon coordinates Returns dict of POIs containing each ' s nodes , polygon geometry , and osmid"""
if 'type' in response and response [ 'type' ] == 'way' : nodes = response [ 'nodes' ] try : polygon = Polygon ( [ ( coords [ node ] [ 'lon' ] , coords [ node ] [ 'lat' ] ) for node in nodes ] ) poi = { 'nodes' : nodes , 'geometry' : polygon , 'osmid' : response [ 'id' ] } if 'tags' in re...
def serve ( path = None , host = None , port = None , user_content = False , context = None , username = None , password = None , render_offline = False , render_wide = False , render_inline = False , api_url = None , title = None , autorefresh = True , browser = False , quiet = None , grip_class = None ) : """Star...
app = create_app ( path , user_content , context , username , password , render_offline , render_wide , render_inline , api_url , title , None , autorefresh , quiet , grip_class ) app . run ( host , port , open_browser = browser )
def read_csv ( self , csv_location , csv_configs = None ) : # type : ( str , Dict [ str , int ] ) - > List [ List [ str ] ] """Read the csv file"""
csv_configs = self . _generate_configs_from_default ( csv_configs ) with open ( csv_location , 'r' ) as csv_file : csv_reader = csv . reader ( csv_file ) self . csv_data = list ( csv_reader ) self . csv_data = self . csv_data [ csv_configs [ 'HEADER_COLUMNS_TO_SKIP' ] : ] return self . csv_data
def set_parameters ( self , parameters ) : """Sets solver parameters . Parameters parameters : dict"""
for key , value in list ( parameters . items ( ) ) : if key in self . parameters : self . parameters [ key ] = value
def URLRabbitmqBroker ( url , * , middleware = None ) : """Alias for the RabbitMQ broker that takes a connection URL as a positional argument . Parameters : url ( str ) : A connection string . middleware ( list [ Middleware ] ) : The middleware to add to this broker ."""
warnings . warn ( "Use RabbitmqBroker with the 'url' parameter instead of URLRabbitmqBroker." , DeprecationWarning , stacklevel = 2 , ) return RabbitmqBroker ( url = url , middleware = middleware )
def refresh ( self ) : """* Refreshs this documents ' s attributesd * * * Usage : * * To refresh the taskpaper document : . . code - block : : python doc . refresh"""
self . projects = self . _get_object ( regex = re . compile ( r'((?<=\n)|(?<=^))(?P<title>(?!\[Searches\]|- )\S.*?:(?!\S)) *(?P<tagString>( *?@[^(\s]+(\([^)]*\))?)+)?(?P<content>(\n(( |\t)+\S.*)|\n( |\t)*|\n)+)' , re . UNICODE ) , objectType = "project" , content = None ) self . tasks = self . _get_object ( regex = re ...
def import_image ( image_path , os_version ) : """Import image . Input parameters : : image _ path : Image file path : os _ version : Operating system version . e . g . rhel7.2"""
image_name = os . path . basename ( image_path ) print ( "Checking if image %s exists or not, import it if not exists" % image_name ) image_info = sdk_client . send_request ( 'image_query' , imagename = image_name ) if 'overallRC' in image_info and image_info [ 'overallRC' ] : print ( "Importing image %s ..." % ima...
def systemInformationType1 ( ) : """SYSTEM INFORMATION TYPE 1 Section 9.1.31"""
a = L2PseudoLength ( l2pLength = 0x15 ) b = TpPd ( pd = 0x6 ) c = MessageType ( mesType = 0x19 ) # 00011001 d = CellChannelDescription ( ) e = RachControlParameters ( ) f = Si1RestOctets ( ) packet = a / b / c / d / e / f return packet
def md5 ( self ) : """Get an MD5 reflecting everything in the DataStore . Returns md5 : str , MD5 in hexadecimal"""
hasher = hashlib . md5 ( ) for key in sorted ( self . data . keys ( ) ) : hasher . update ( self . data [ key ] . md5 ( ) . encode ( 'utf-8' ) ) md5 = hasher . hexdigest ( ) return md5
async def connect ( self ) : """Perform ICE handshake . This coroutine returns if a candidate pair was successfuly nominated and raises an exception otherwise ."""
if not self . _local_candidates_end : raise ConnectionError ( 'Local candidates gathering was not performed' ) if ( self . remote_username is None or self . remote_password is None ) : raise ConnectionError ( 'Remote username or password is missing' ) # 5.7.1 . Forming Candidate Pairs for remote_candidate in se...
def _scobit_transform_deriv_shape ( systematic_utilities , alt_IDs , rows_to_alts , shape_params , output_array = None , * args , ** kwargs ) : """Parameters systematic _ utilities : 1D ndarray . All elements should be ints , floats , or longs . Should contain the systematic utilities of each observation per ...
# Note the np . exp is needed because the raw curvature params are the log # of the ' natural ' curvature params . This is to ensure the natural shape # params are always positive . curve_shapes = np . exp ( shape_params ) curve_shapes [ np . isposinf ( curve_shapes ) ] = max_comp_value long_curve_shapes = rows_to_alts...
def commit ( self , registerID , checksum = None ) : """Once a multipart upload is completed , the files need to be merged together . The commit ( ) does just that . Inputs : registerID - unique identifier of the registered item . checksum - upload id . output : dictionary"""
parts = "," . join ( self . parts ( registerID = registerID ) ) url = self . _url + "/%s/commit" params = { "f" : "json" , "parts" : parts } if checksum is not None : params [ 'checksum' ] = checksum return self . _post ( url = url , param_dict = params , securityHandler = self . _securityHandler , proxy_url = self...
def get_vhost_permissions ( self , vname ) : """: returns : list of dicts , or an empty list if there are no permissions . : param string vname : Name of the vhost to set perms on ."""
vname = quote ( vname , '' ) path = Client . urls [ 'vhost_permissions_get' ] % ( vname , ) conns = self . _call ( path , 'GET' ) return conns
def xmlinfo ( self , id ) : """Return the XML info record for the given item"""
self . _update_index ( ) for package in self . _index . findall ( 'packages/package' ) : if package . get ( 'id' ) == id : return package for collection in self . _index . findall ( 'collections/collection' ) : if collection . get ( 'id' ) == id : return collection raise ValueError ( 'Package %r...
def activate ( self , title , switchDesktop = False , matchClass = False ) : """Activate the specified window , giving it input focus Usage : C { window . activate ( title , switchDesktop = False , matchClass = False ) } If switchDesktop is False ( default ) , the window will be moved to the current desktop a...
if switchDesktop : args = [ "-a" , title ] else : args = [ "-R" , title ] if matchClass : args += [ "-x" ] self . _run_wmctrl ( args )
def add ( self , lines , message ) : """Adds a lint issue to the report . The first arg should be [ ] of lines on which the issue is present . The second arg should be the error message ."""
error = Error ( message ) if error not in self . errors : self . errors [ error ] = [ ] self . errors [ error ] . extend ( lines )
def ssize ( newsize , cell ) : """Set the size ( maximum cardinality ) of a CSPICE cell of any data type . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / ssize _ c . html : param newsize : Size ( maximum cardinality ) of the cell . : type newsize : int : param cell : The cel...
assert isinstance ( cell , stypes . SpiceCell ) newsize = ctypes . c_int ( newsize ) libspice . ssize_c ( newsize , ctypes . byref ( cell ) ) return cell
def _update_cache ( self , course , taskid ) : """Updates the cache : param course : a Course object : param taskid : a ( valid ) task id : raise InvalidNameException , TaskNotFoundException , TaskUnreadableException"""
if not id_checker ( taskid ) : raise InvalidNameException ( "Task with invalid name: " + taskid ) task_fs = self . get_task_fs ( course . get_id ( ) , taskid ) last_modif , translation_fs , task_content = self . _get_last_updates ( course , taskid , task_fs , True ) self . _cache [ ( course . get_id ( ) , taskid ) ...
def set_dtreat_interp_indch ( self , indch = None ) : """Set the indices of the channels for which to interpolate data The index can be provided as : - A 1d np . ndarray of boolean or int indices of channels = > interpolate data at these channels for all times - A dict with : * keys = int indices of times...
lC = [ indch is None , type ( indch ) in [ np . ndarray , list ] , type ( indch ) is dict ] assert any ( lC ) if lC [ 2 ] : lc = [ type ( k ) is int and k < self . _ddataRef [ 'nt' ] for k in indch . keys ( ) ] assert all ( lc ) for k in indch . keys ( ) : assert hasattr ( indch [ k ] , '__iter__' )...
def parse_excel ( file_path : str , entrez_id_header , log_fold_change_header , adjusted_p_value_header , entrez_delimiter , base_mean_header = None ) -> List [ Gene ] : """Read an excel file on differential expression values as Gene objects . : param str file _ path : The path to the differential expression file...
logger . info ( "In parse_excel()" ) df = pd . read_excel ( file_path ) return handle_dataframe ( df , entrez_id_name = entrez_id_header , log2_fold_change_name = log_fold_change_header , adjusted_p_value_name = adjusted_p_value_header , entrez_delimiter = entrez_delimiter , base_mean = base_mean_header , )
def setParams ( self , minSupport = 0.3 , minConfidence = 0.8 , itemsCol = "items" , predictionCol = "prediction" , numPartitions = None ) : """setParams ( self , minSupport = 0.3 , minConfidence = 0.8 , itemsCol = " items " , predictionCol = " prediction " , numPartitions = None )"""
kwargs = self . _input_kwargs return self . _set ( ** kwargs )
def bridge_and_sniff ( if1 , if2 , count = 0 , store = 1 , offline = None , prn = None , lfilter = None , L2socket = None , timeout = None , stop_filter = None , stop_callback = None , * args , ** kargs ) : """Forward traffic between two interfaces and sniff packets exchanged bridge _ and _ sniff ( [ count = 0 , ...
c = 0 if L2socket is None : L2socket = conf . L2socket s1 = L2socket ( iface = if1 ) s2 = L2socket ( iface = if2 ) peerof = { s1 : s2 , s2 : s1 } label = { s1 : if1 , s2 : if2 } lst = [ ] if timeout is not None : stoptime = time . time ( ) + timeout remain = None try : while True : if timeout is not...