signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _g ( self , h , xp , s ) : """Density function for blow and hop moves"""
nphi = sum ( self . phi ) return ( nphi / 2.0 ) * log ( 2 * pi ) + nphi * log ( s ) + 0.5 * sum ( ( h - xp ) ** 2 ) / ( s ** 2 )
def siblings ( self ) : """Returns all the siblings of this element as a list ."""
return list ( filter ( lambda x : id ( x ) != id ( self ) , self . parent . childs ) )
def send_messages ( self , access_token , messages , timeout , current ) : """Send messages to server , along with user authentication ."""
is_submit = current and self . args . submit and not self . args . revise is_revision = current and self . args . revise data = { 'assignment' : self . assignment . endpoint , 'messages' : messages , 'submit' : is_submit } if is_revision : address = self . REVISION_ENDPOINT . format ( server = self . assignment . s...
def _keys_via_value_nonrecur ( d , v ) : '''# non - recursive d = { 1 : ' a ' , 2 : ' b ' , 3 : ' a ' } _ keys _ via _ value _ nonrecur ( d , ' a ' )'''
rslt = [ ] for key in d : if ( d [ key ] == v ) : rslt . append ( key ) return ( rslt )
def get_build_container_tag ( self ) : """Return the build container tag"""
if self . __prefix : return "{0}-{1}-{2}" . format ( self . __prefix , self . __branch , self . __version ) else : return "{0}-{1}" . format ( self . __branch , self . __version )
def verify ( x , t , y , pi , errorOnFail = True ) : """Verifies a zero - knowledge proof where p \ in G1. @ errorOnFail : Raise an exception if the proof does not hold ."""
# Unpack the proof p , c , u = pi # Verify types assertType ( x , G1Element ) assertType ( y , GtElement ) assertType ( p , G1Element ) assertScalarType ( c ) assertScalarType ( u ) # TODO : beta can be pre - computed while waiting for a server response . Q = generatorG1 ( ) beta = pair ( x , hashG2 ( t ) ) # Recompute...
def multicore ( function , cores , multiargs , ** singleargs ) : """wrapper for multicore process execution Parameters function individual function to be applied to each process item cores : int the number of subprocesses started / CPUs used ; this value is reduced in case the number of subprocesses is ...
tblib . pickling_support . install ( ) # compare the function arguments with the multi and single arguments and raise errors if mismatches occur if sys . version_info >= ( 3 , 0 ) : check = inspect . getfullargspec ( function ) varkw = check . varkw else : check = inspect . getargspec ( function ) varkw...
def hmac_md5 ( s , salt ) : """获取一个字符串的 使用 salt 加密的 hmac MD5 值 : param : * s : ( string ) 需要进行 hash 的字符串 * salt : ( string ) 随机字符串 : return : * result : ( string ) 32位小写 MD5 值"""
hmac_md5 = hmac . new ( salt . encode ( 'utf-8' ) , s . encode ( 'utf-8' ) , digestmod = hashlib . md5 ) . hexdigest ( ) return hmac_md5
def parse ( argv ) : """Parse cli args ."""
args = docopt ( __doc__ , argv = argv ) try : call ( sys . argv [ 2 ] , args ) except KytosException as exception : print ( "Error parsing args: {}" . format ( exception ) ) exit ( )
def items_lower ( self ) : '''Returns a generator iterating over keys and values , with the keys all being lowercase .'''
return ( ( key , val [ 1 ] ) for key , val in six . iteritems ( self . _data ) )
def start_delta_string ( self ) : """A convenient string representation of how long after the run started we started . : API : public"""
delta = int ( self . start_time ) - int ( self . root ( ) . start_time ) return '{:02}:{:02}' . format ( int ( delta / 60 ) , delta % 60 )
def cancel_spot_requests ( self , requests ) : """Cancel one or more EC2 spot instance requests . : param requests : List of EC2 spot instance request IDs . : type requests : list"""
ec2_requests = self . retry_on_ec2_error ( self . ec2 . get_all_spot_instance_requests , request_ids = requests ) for req in ec2_requests : req . cancel ( )
def Copy_to_Clipboard ( self , event = None ) : "copy bitmap of canvas to system clipboard"
bmp_obj = wx . BitmapDataObject ( ) bmp_obj . SetBitmap ( self . bitmap ) if not wx . TheClipboard . IsOpened ( ) : open_success = wx . TheClipboard . Open ( ) if open_success : wx . TheClipboard . SetData ( bmp_obj ) wx . TheClipboard . Close ( ) wx . TheClipboard . Flush ( )
def setValues ( self , values ) : """Set the tuples in this set . Valid only for non - indexed sets . Args : values : A list of tuples or a : class : ` ~ amplpy . DataFrame ` . In the case of a : class : ` ~ amplpy . DataFrame ` , the number of indexing columns of the must be equal to the arity of the set ....
if isinstance ( values , ( list , set ) ) : if any ( isinstance ( value , basestring ) for value in values ) : values = list ( map ( str , values ) ) self . _impl . setValuesStr ( values , len ( values ) ) elif all ( isinstance ( value , Real ) for value in values ) : values = list ( map...
def mouseMoveEvent ( self , event ) : """Sets the value for the slider at the event position . : param event | < QMouseEvent >"""
self . setValue ( self . valueAt ( event . pos ( ) . x ( ) ) )
def get_variables_path ( export_dir ) : """Returns the path for storing variables checkpoints ."""
return os . path . join ( tf . compat . as_bytes ( export_dir ) , tf . compat . as_bytes ( tf_v1 . saved_model . constants . VARIABLES_DIRECTORY ) , tf . compat . as_bytes ( tf_v1 . saved_model . constants . VARIABLES_FILENAME ) )
def _parse_args ( func , variables , annotations = None ) : """Return a list of arguments with the variable it reads . NOTE : Multiple arguments may read the same variable ."""
arg_read_var = [ ] for arg_name , anno in ( annotations or func . __annotations__ ) . items ( ) : if arg_name == 'return' : continue var , read = _parse_arg ( func , variables , arg_name , anno ) arg = Argument ( name = arg_name , read = read ) arg_read_var . append ( ( arg , var ) ) return arg_...
def speed_of_gait ( self , x , wavelet_type = 'db3' , wavelet_level = 6 ) : """This method assess the speed of gait following : cite : ` g - MartinSB11 ` . It extracts the gait speed from the energies of the approximation coefficients of wavelet functions . Prefferably you should use the magnitude of x , y and ...
coeffs = wavedec ( x . values , wavelet = wavelet_type , level = wavelet_level ) energy = [ sum ( coeffs [ wavelet_level - i ] ** 2 ) / len ( coeffs [ wavelet_level - i ] ) for i in range ( wavelet_level ) ] WEd1 = energy [ 0 ] / ( 5 * np . sqrt ( 2 ) ) WEd2 = energy [ 1 ] / ( 4 * np . sqrt ( 2 ) ) WEd3 = energy [ 2 ] ...
def _close_and_clean ( self , cleanup ) : """Closes the project , and cleanup the disk if cleanup is True : param cleanup : Whether to delete the project directory"""
tasks = [ ] for node in self . _nodes : tasks . append ( asyncio . async ( node . manager . close_node ( node . id ) ) ) if tasks : done , _ = yield from asyncio . wait ( tasks ) for future in done : try : future . result ( ) except ( Exception , GeneratorExit ) as e : ...
def open ( self , connection = None ) : """Open the client . The client can create a new Connection or an existing Connection can be passed in . This existing Connection may have an existing CBS authentication Session , which will be used for this client as well . Otherwise a new Session will be created . ...
# pylint : disable = protected - access if self . _session : return # already open . _logger . debug ( "Opening client connection." ) if connection : _logger . debug ( "Using existing connection." ) self . _auth = connection . auth self . _ext_connection = True self . _connection = connection or sel...
def load ( self , df , centerings ) : """Call ` load ` method with ` centerings ` filtered to keys in ` self . filter _ ` ."""
return super ( ) . load ( df , { key : value for key , value in centerings . items ( ) if key in self . filter_ } )
def items ( self , prefix = None , delimiter = None ) : """Get an iterator for the items within this bucket . Args : prefix : an optional prefix to match items . delimiter : an optional string to simulate directory - like semantics . The returned items will be those whose names do not contain the delimiter ...
return _item . Items ( self . _name , prefix , delimiter , context = self . _context )
def ncp_bcd ( X , rank , random_state = None , init = 'rand' , ** options ) : """Fits nonnegative CP Decomposition using the Block Coordinate Descent ( BCD ) Method . Parameters X : ( I _ 1 , . . . , I _ N ) array _ like A real array with nonnegative entries and ` ` X . ndim > = 3 ` ` . rank : integer T...
# Check inputs . optim_utils . _check_cpd_inputs ( X , rank ) # Store norm of X for computing objective function . N = X . ndim # Initialize problem . U , normX = optim_utils . _get_initial_ktensor ( init , X , rank , random_state ) result = FitResult ( U , 'NCP_BCD' , ** options ) # Block coordinate descent Um = U . c...
def _parse_deaths ( self , rows ) : """Parses the character ' s recent deaths Parameters rows : : class : ` list ` of : class : ` bs4 . Tag ` A list of all rows contained in the table ."""
for row in rows : cols = row . find_all ( 'td' ) death_time_str = cols [ 0 ] . text . replace ( "\xa0" , " " ) . strip ( ) death_time = parse_tibia_datetime ( death_time_str ) death = str ( cols [ 1 ] ) . replace ( "\xa0" , " " ) death_info = death_regexp . search ( death ) if death_info : ...
def qteKillMiniApplet ( self ) : """Remove the mini applet . If a different applet is to be restored / focused then call ` ` qteMakeAppletActive ` ` for that applet * after * calling this method . | Args | * * * None * * | Returns | * * * None * * | Raises | * * * None * *"""
# Sanity check : is the handle valid ? if self . _qteMiniApplet is None : return # Sanity check : is it really a mini applet ? if not self . qteIsMiniApplet ( self . _qteMiniApplet ) : msg = ( 'Mini applet does not have its mini applet flag set.' ' Ignored.' ) self . qteLogger . warning ( msg ) if self . _q...
def search_prospects ( self , search_type , query , offset = None , orgoffset = None ) : """Supports doing a search for prospects by city , reion , or country . search _ type should be one of ' city ' ' region ' ' country ' . This method is intended to be called with one of the outputs from the get _ options ...
params = { 'q' : query } if offset and orgoffset : params [ 'orgOffset' ] = orgoffset params [ 'timeOffset' ] = offset return self . _call ( 'search/%s' % search_type , params )
def list_domains ( container_id = None ) : '''List domains that CertCentral knows about . You can filter by container _ id ( also known as " Division " ) by passing a container _ id . CLI Example : . . code - block : : bash salt - run digicert . list _ domains'''
if container_id : url = '{0}/domain?{1}' . format ( _base_url ( ) , container_id ) else : url = '{0}/domain' . format ( _base_url ( ) ) orgs = _paginate ( url , "domains" , method = 'GET' , decode = True , decode_type = 'json' , header_dict = { 'X-DC-DEVKEY' : _api_key ( ) , 'Content-Type' : 'application/json' ...
def get_queue ( self ) : """获取新闻标题候选队列 Return : queue - - 新闻标题候选队列 , list类型"""
queue = [ ] for i in range ( 0 , self . index ) : unit = self . unit_raw [ i ] c = CDM ( unit ) # 过滤 if c . get_alpha ( ) > 0 and c . PTN in range ( self . title_min , self . title_max ) : queue . append ( unit ) if queue == [ ] : pass else : log ( 'debug' , '\n获取标题候选队列成功:【{}】\n' . forma...
def _sendTo ( self , proto ) : """When sent , call the C { startProtocol } method on the virtual transport object . @ see : L { vertex . ptcp . PTCP . startProtocol } @ see : L { vertex . q2q . VirtualTransport . startProtocol } @ param proto : the AMP protocol that this is being sent on ."""
# XXX This is overriding a private interface super ( ConnectionStartBox , self ) . _sendTo ( proto ) self . virtualTransport . startProtocol ( )
def array_keys ( self ) : """Return an iterator over member names for arrays only . Examples > > > import zarr > > > g1 = zarr . group ( ) > > > g2 = g1 . create _ group ( ' foo ' ) > > > g3 = g1 . create _ group ( ' bar ' ) > > > d1 = g1 . create _ dataset ( ' baz ' , shape = 100 , chunks = 10) > > >...
for key in sorted ( listdir ( self . _store , self . _path ) ) : path = self . _key_prefix + key if contains_array ( self . _store , path ) : yield key
def monitor_key_get ( service , key ) : """Gets the value of an existing key in the monitor cluster . : param service : six . string _ types . The Ceph user name to run the command under : param key : six . string _ types . The key to search for . : return : Returns the value of that key or None if not found ...
try : output = check_output ( [ 'ceph' , '--id' , service , 'config-key' , 'get' , str ( key ) ] ) . decode ( 'UTF-8' ) return output except CalledProcessError as e : log ( "Monitor config-key get failed with message: {}" . format ( e . output ) ) return None
def V_horiz_guppy ( D , L , a , h , headonly = False ) : r'''Calculates volume of a tank with guppy heads , according to [ 1 ] _ . . . math : : V _ f = A _ fL + \ frac { 2aR ^ 2 } { 3 } \ cos ^ { - 1 } \ left ( 1 - \ frac { h } { R } \ right ) + \ frac { 2a } { 9R } \ sqrt { 2Rh - h ^ 2 } ( 2h - 3R ) ( h + R ...
R = 0.5 * D Af = R * R * acos ( ( R - h ) / R ) - ( R - h ) * ( 2. * R * h - h * h ) ** 0.5 Vf = 2. * a * R * R / 3. * acos ( 1. - h / R ) + 2. * a / 9. / R * ( 2 * R * h - h ** 2 ) ** 0.5 * ( 2 * h - 3 * R ) * ( h + R ) if headonly : Vf = Vf / 2. else : Vf += Af * L return Vf
def get_field_names ( self , declared_fields , info ) : """We override the parent to omit explicity defined meta fields ( such as SerializerMethodFields ) from the list of declared fields"""
meta_fields = getattr ( self . Meta , 'meta_fields' , [ ] ) declared = OrderedDict ( ) for field_name in set ( declared_fields . keys ( ) ) : field = declared_fields [ field_name ] if field_name not in meta_fields : declared [ field_name ] = field fields = super ( ModelSerializer , self ) . get_field_na...
def init_write_line ( self ) : """init _ write _ line ( ) initializes fields relevant to output generation"""
format_list = self . _format_list output_info = self . gen_output_fmt ( format_list ) self . _output_fmt = "" . join ( [ sub [ 0 ] for sub in output_info ] ) self . _out_gen_fmt = [ sub [ 1 ] for sub in output_info if sub [ 1 ] is not None ] self . _out_widths = [ sub [ 2 ] for sub in output_info if sub [ 2 ] is not No...
def connectChunk ( key , chunk ) : """Parse Card Chunk Method"""
upLinks = [ ] schunk = chunk [ 0 ] . strip ( ) . split ( ) for idx in range ( 4 , len ( schunk ) ) : upLinks . append ( schunk [ idx ] ) result = { 'link' : schunk [ 1 ] , 'downLink' : schunk [ 2 ] , 'numUpLinks' : schunk [ 3 ] , 'upLinks' : upLinks } return result
def convert ( schema ) : """Convert a voluptuous schema to a dictionary ."""
# pylint : disable = too - many - return - statements , too - many - branches if isinstance ( schema , vol . Schema ) : schema = schema . schema if isinstance ( schema , Mapping ) : val = [ ] for key , value in schema . items ( ) : description = None if isinstance ( key , vol . Marker ) : ...
def setup_user_manager ( app ) : """Setup flask - user manager ."""
from flask_user import SQLAlchemyAdapter from rio . models import User init = dict ( db_adapter = SQLAlchemyAdapter ( db , User ) , ) user_manager . init_app ( app , ** init )
def load_ply ( file_obj , resolver = None , fix_texture = True , * args , ** kwargs ) : """Load a PLY file from an open file object . Parameters file _ obj : an open file - like object Source data , ASCII or binary PLY resolver : trimesh . visual . resolvers . Resolver Object which can resolve assets fi...
# OrderedDict which is populated from the header elements , is_ascii , image_name = parse_header ( file_obj ) # functions will fill in elements from file _ obj if is_ascii : ply_ascii ( elements , file_obj ) else : ply_binary ( elements , file_obj ) # try to load the referenced image image = None if image_name ...
def message ( self , text ) : """Public message ."""
self . client . publish ( self . keys . external , '{}: {}' . format ( self . resource , text ) )
def _parse_from_table ( html_chunk , what ) : """Go thru table data in ` html _ chunk ` and try to locate content of the neighbor cell of the cell containing ` what ` . Returns : str : Table data or None ."""
ean_tag = html_chunk . find ( "tr" , fn = must_contain ( "th" , what , "td" ) ) if not ean_tag : return None return get_first_content ( ean_tag [ 0 ] . find ( "td" ) )
def get_sonos_favorites ( self , start = 0 , max_items = 100 ) : """Get Sonos favorites . See : meth : ` get _ favorite _ radio _ shows ` for return type and remarks ."""
message = 'The output type of this method will probably change in ' 'the future to use SoCo data structures' warnings . warn ( message , stacklevel = 2 ) return self . __get_favorites ( SONOS_FAVORITES , start , max_items )
def derive_field_name ( self , field_name ) : """Derives a new event from this one setting the ` ` field _ name ` ` attribute . Args : field _ name ( Union [ amazon . ion . symbols . SymbolToken , unicode ] ) : The field name to set . Returns : IonEvent : The newly generated event ."""
cls = type ( self ) # We use ordinals to avoid thunk materialization . return cls ( self [ 0 ] , self [ 1 ] , self [ 2 ] , field_name , self [ 4 ] , self [ 5 ] )
def send_heartbeats ( heartbeats , args , configs , use_ntlm_proxy = False ) : """Send heartbeats to WakaTime API . Returns ` SUCCESS ` when heartbeat was sent , otherwise returns an error code ."""
if len ( heartbeats ) == 0 : return SUCCESS api_url = args . api_url if not api_url : api_url = 'https://api.wakatime.com/api/v1/users/current/heartbeats.bulk' log . debug ( 'Sending heartbeats to api at %s' % api_url ) timeout = args . timeout if not timeout : timeout = 60 data = [ h . sanitize ( ) . dict ...
def IFFT_filter ( Signal , SampleFreq , lowerFreq , upperFreq , PyCUDA = False ) : """Filters data using fft - > zeroing out fft bins - > ifft Parameters Signal : ndarray Signal to be filtered SampleFreq : float Sample frequency of signal lowerFreq : float Lower frequency of bandpass to allow through ...
if PyCUDA == True : Signalfft = calc_fft_with_PyCUDA ( Signal ) else : print ( "starting fft" ) Signalfft = scipy . fftpack . fft ( Signal ) print ( "starting freq calc" ) freqs = _np . fft . fftfreq ( len ( Signal ) ) * SampleFreq print ( "starting bin zeroing" ) Signalfft [ _np . where ( freqs < lowerFreq...
def check ( state_engine , nameop , block_id , checked_ops ) : """Revoke a name - - make it available for registration . * it must be well - formed * its namespace must be ready . * the name must be registered * it must be sent by the name owner NAME _ REVOKE isn ' t allowed during an import , so the name...
name = nameop [ 'name' ] sender = nameop [ 'sender' ] namespace_id = get_namespace_from_name ( name ) # name must be well - formed if not is_b40 ( name ) or "+" in name or name . count ( "." ) > 1 : log . warning ( "Malformed name '%s': non-base-38 characters" % name ) return False # name must exist name_rec = ...
def requiv_contact_max ( b , component , solve_for = None , ** kwargs ) : """Create a constraint to determine the critical ( at L2/3 ) value of requiv at which a constact will overflow . This will only be used for contacts for requiv _ max : parameter b : the : class : ` phoebe . frontend . bundle . Bundle ` ...
hier = b . get_hierarchy ( ) if not len ( hier . get_value ( ) ) : # TODO : change to custom error type to catch in bundle . add _ component # TODO : check whether the problem is 0 hierarchies or more than 1 raise NotImplementedError ( "constraint for requiv_contact_max requires hierarchy" ) component_ps = _get_sys...
def get_filters_params ( self , params = None ) : """Returns all params except IGNORED _ PARAMS"""
if not params : params = self . params lookup_params = params . copy ( ) # a dictionary of the query string # Remove all the parameters that are globally and systematically # ignored . for ignored in IGNORED_PARAMS : if ignored in lookup_params : del lookup_params [ ignored ] return lookup_params
def _save_cache ( self , filename , section_number_of_pages , page_references ) : """Save the current state of the page references to ` < filename > . rtc `"""
cache_path = Path ( filename ) . with_suffix ( self . CACHE_EXTENSION ) with cache_path . open ( 'wb' ) as file : cache = ( section_number_of_pages , page_references ) pickle . dump ( cache , file )
def snyder_ac ( self , structure ) : """Calculates Snyder ' s acoustic sound velocity ( in SI units ) Args : structure : pymatgen structure object Returns : Snyder ' s acoustic sound velocity ( in SI units )"""
nsites = structure . num_sites volume = structure . volume natoms = structure . composition . num_atoms num_density = 1e30 * nsites / volume tot_mass = sum ( [ e . atomic_mass for e in structure . species ] ) avg_mass = 1.6605e-27 * tot_mass / natoms return 0.38483 * avg_mass * ( ( self . long_v ( structure ) + 2. * se...
def upload ( self ) : """上传操作"""
self . blockStatus = [ ] if config . get_default ( 'default_zone' ) . up_host : host = config . get_default ( 'default_zone' ) . up_host else : host = config . get_default ( 'default_zone' ) . get_up_host_by_token ( self . up_token ) offset = self . recovery_from_record ( ) for block in _file_iter ( self . inpu...
def labels ( self ) : """Returns the list of labels that will be used to represent this axis ' information . : return [ < str > , . . ]"""
if self . _labels is None : self . _labels = map ( self . labelFormat ( ) . format , self . values ( ) ) return self . _labels
def split_and_operate ( self , mask , f , inplace ) : """split the block per - column , and apply the callable f per - column , return a new block for each . Handle masking which will not change a block unless needed . Parameters mask : 2 - d boolean mask f : callable accepting ( 1d - mask , 1d values , i...
if mask is None : mask = np . ones ( self . shape , dtype = bool ) new_values = self . values def make_a_block ( nv , ref_loc ) : if isinstance ( nv , Block ) : block = nv elif isinstance ( nv , list ) : block = nv [ 0 ] else : # Put back the dimension that was taken from it and make ...
def current_timestamp ( self ) -> datetime : """Get the current state timestamp ."""
timestamp = DB . get_hash_value ( self . _key , 'current_timestamp' ) return datetime_from_isoformat ( timestamp )
def create_folder ( self , uri , recursive = False ) : """Create folder . uri - - MediaFire URI Keyword arguments : recursive - - set to True to create intermediate folders ."""
logger . info ( "Creating %s" , uri ) # check that folder exists already try : resource = self . get_resource_by_uri ( uri ) if isinstance ( resource , Folder ) : return resource else : raise NotAFolderError ( uri ) except ResourceNotFoundError : pass location = self . _parse_uri ( uri )...
def gbest_idx ( swarm ) : """gbest Neighbourhood topology function . Args : swarm : list : The list of particles . Returns : int : The index of the gbest particle ."""
best = 0 cmp = comparator ( swarm [ best ] . best_fitness ) for ( idx , particle ) in enumerate ( swarm ) : if cmp ( particle . best_fitness , swarm [ best ] . best_fitness ) : best = idx return best
def get_internal_ip ( ) : """Get the local IP addresses ."""
nics = { } for interface_name in interfaces ( ) : addresses = ifaddresses ( interface_name ) try : nics [ interface_name ] = { 'ipv4' : addresses [ AF_INET ] , 'link_layer' : addresses [ AF_LINK ] , 'ipv6' : addresses [ AF_INET6 ] , } except KeyError : pass return nics
def load_reader ( reader_configs , ** reader_kwargs ) : """Import and setup the reader from * reader _ info * ."""
reader_info = read_reader_config ( reader_configs ) reader_instance = reader_info [ 'reader' ] ( config_files = reader_configs , ** reader_kwargs ) return reader_instance
def wait_for_close ( raiden : 'RaidenService' , payment_network_id : PaymentNetworkID , token_address : TokenAddress , channel_ids : List [ ChannelID ] , retry_timeout : float , ) -> None : """Wait until all channels are closed . Note : This does not time out , use gevent . Timeout ."""
return wait_for_channel_in_states ( raiden = raiden , payment_network_id = payment_network_id , token_address = token_address , channel_ids = channel_ids , retry_timeout = retry_timeout , target_states = CHANNEL_AFTER_CLOSE_STATES , )
def id_ ( reset = False ) : '''. . versionadded : : 2016.3.0 Return monit unique id . reset : False Reset current id and generate a new id when it ' s True . CLI Example : . . code - block : : bash salt ' * ' monit . id [ reset = True ]'''
if reset : id_pattern = re . compile ( r'Monit id (?P<id>[^ ]+)' ) cmd = 'echo y|monit -r' out = __salt__ [ 'cmd.run_all' ] ( cmd , python_shell = True ) ret = id_pattern . search ( out [ 'stdout' ] ) . group ( 'id' ) return ret if ret else False else : cmd = 'monit -i' out = __salt__ [ 'cmd...
def save_button_clicked ( self , classification ) : """Action for save button clicked . : param classification : The classification that being edited . : type classification : dict"""
# Save current edit if self . layer_mode == layer_mode_continuous : thresholds = self . get_threshold ( ) classification_class = { 'classes' : thresholds , 'active' : True } if self . thresholds . get ( self . active_exposure [ 'key' ] ) : # Set other class to not active for current_classification i...
def saturation ( self , value ) : """Volume of water to volume of voids"""
value = clean_float ( value ) if value is None : return try : unit_moisture_weight = self . unit_moist_weight - self . unit_dry_weight unit_moisture_volume = unit_moisture_weight / self . _pw saturation = unit_moisture_volume / self . _calc_unit_void_volume ( ) if saturation is not None and not ct ....
def snapshot_create ( repository , snapshot , body = None , hosts = None , profile = None ) : '''. . versionadded : : 2017.7.0 Create snapshot in specified repository by supplied definition . repository Repository name snapshot Snapshot name body Snapshot definition as in https : / / www . elastic . c...
es = _get_instance ( hosts , profile ) try : response = es . snapshot . create ( repository = repository , snapshot = snapshot , body = body ) return response . get ( 'accepted' , False ) except elasticsearch . TransportError as e : raise CommandExecutionError ( "Cannot create snapshot {0} in repository {1}...
def _remote ( self , name ) : """Return a remote for which ' name ' matches the short _ name or url"""
from ambry . orm import Remote from sqlalchemy import or_ from ambry . orm . exc import NotFoundError from sqlalchemy . orm . exc import NoResultFound , MultipleResultsFound if not name . strip ( ) : raise NotFoundError ( "Empty remote name" ) try : try : r = self . database . session . query ( Remote )...
def validate_source ( ident , comment = None ) : '''Validate a source for automatic harvesting'''
source = get_source ( ident ) source . validation . on = datetime . now ( ) source . validation . comment = comment source . validation . state = VALIDATION_ACCEPTED if current_user . is_authenticated : source . validation . by = current_user . _get_current_object ( ) source . save ( ) schedule ( ident , cron = cur...
def inline_query ( self ) : """The query ` ` str ` ` for : tl : ` KeyboardButtonSwitchInline ` objects ."""
if isinstance ( self . button , types . KeyboardButtonSwitchInline ) : return self . button . query
def check_running ( self , role , number ) : """Check that a certain number of instances in a role are running ."""
instances = self . get_instances_in_role ( role , "running" ) if len ( instances ) != number : print "Expected %s instances in role %s, but was %s %s" % ( number , role , len ( instances ) , instances ) return False else : return instances
def scan_volumes ( cryst , lo = 0.98 , hi = 1.02 , n = 5 , scale_volumes = True ) : '''Provide set of crystals along volume axis from lo to hi ( inclusive ) . No volume cell optimization is performed . Bounds are specified as fractions ( 1.10 = 10 % increase ) . If scale _ volumes = = False the scalling is ap...
scale = linspace ( lo , hi , num = n ) if scale_volumes : scale **= ( 1.0 / 3.0 ) uc = cryst . get_cell ( ) systems = [ Atoms ( cryst ) for s in scale ] for n , s in enumerate ( scale ) : systems [ n ] . set_cell ( s * uc , scale_atoms = True ) return systems
def show_firmware_version_output_show_firmware_version_control_processor_vendor ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_firmware_version = ET . Element ( "show_firmware_version" ) config = show_firmware_version output = ET . SubElement ( show_firmware_version , "output" ) show_firmware_version = ET . SubElement ( output , "show-firmware-version" ) control_processor_vendor = ET . SubElement ( show_...
def get_all_groups ( path_prefix = '/' , region = None , key = None , keyid = None , profile = None ) : '''Get and return all IAM group details , starting at the optional path . . . versionadded : : 2016.3.0 CLI Example : salt - call boto _ iam . get _ all _ groups'''
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) if not conn : return None _groups = conn . get_all_groups ( path_prefix = path_prefix ) groups = _groups . list_groups_response . list_groups_result . groups marker = getattr ( _groups . list_groups_response . list_groups_result , ...
def margin_area_LinesNumbers_widget ( self , value ) : """Setter for * * self . _ _ margin _ area _ LinesNumbers _ widget * * attribute . : param value : Attribute value . : type value : LinesNumbers _ QWidget"""
if value is not None : assert type ( value ) is LinesNumbers_QWidget , "'{0}' attribute: '{1}' type is not 'LinesNumbers_QWidget'!" . format ( "checked" , value ) self . __margin_area_LinesNumbers_widget = value
def plot_signal_sum ( ax , params , fname = 'LFPsum.h5' , unit = 'mV' , scaling_factor = 1. , ylabels = True , scalebar = True , vlimround = None , T = [ 800 , 1000 ] , ylim = [ - 1500 , 0 ] , color = 'k' , fancy = False , label = '' , transient = 200 , clip_on = False , rasterized = True , ** kwargs ) : '''on axes...
if type ( fname ) == str and os . path . isfile ( fname ) : f = h5py . File ( fname ) # load data data = f [ 'data' ] . value tvec = np . arange ( data . shape [ 1 ] ) * 1000. / f [ 'srate' ] . value # for mean subtraction datameanaxis1 = f [ 'data' ] . value [ : , tvec >= transient ] . mean ( a...
def getOverlayTransformType ( self , ulOverlayHandle ) : """Returns the transform type of this overlay ."""
fn = self . function_table . getOverlayTransformType peTransformType = VROverlayTransformType ( ) result = fn ( ulOverlayHandle , byref ( peTransformType ) ) return result , peTransformType
def from_rollup_json ( cls , stream , json_data ) : """Rollup json data from the server looks slightly different : param DataStream stream : The : class : ` ~ DataStream ` out of which this data is coming : param dict json _ data : Deserialized JSON data from Device Cloud about this device : raises ValueError...
dp = cls . from_json ( stream , json_data ) # Special handling for timestamp timestamp = isoformat ( dc_utc_timestamp_to_dt ( int ( json_data . get ( "timestamp" ) ) ) ) # Special handling for data , all rollup data is float type type_converter = _get_decoder_method ( stream . get_data_type ( ) ) data = type_converter ...
def create_mbed_detector ( ** kwargs ) : """! Factory used to create host OS specific mbed - lstools object : param kwargs : keyword arguments to pass along to the constructors @ return Returns MbedLsTools object or None if host OS is not supported"""
host_os = platform . system ( ) if host_os == "Windows" : from . windows import StlinkDetectWindows return StlinkDetectWindows ( ** kwargs ) elif host_os == "Linux" : from . linux import StlinkDetectLinuxGeneric return StlinkDetectLinuxGeneric ( ** kwargs ) elif host_os == "Darwin" : from . darwin i...
def repl_main ( args ) : """replacer main"""
pattern = args . pattern repl = args . replacement regexp = re . compile ( pattern ) def repl_action ( f ) : return replace_in_file ( args , f , regexp , repl ) if args . paths : for f in args . paths : repl_action ( f ) else : root = os . getcwd ( ) walk_files ( args , root , root , repl_action...
def dump ( module , stream , cls = PVLEncoder , ** kwargs ) : """Serialize ` ` module ` ` as a pvl module to the provided ` ` stream ` ` . : param module : a ` ` ` PVLModule ` ` ` or ` ` ` dict ` ` ` like object to serialize : param stream : a ` ` . write ( ) ` ` - supporting file - like object to serialize the...
if isinstance ( stream , six . string_types ) : with open ( stream , 'wb' ) as fp : return cls ( ** kwargs ) . encode ( module , fp ) cls ( ** kwargs ) . encode ( module , stream )
def addbusdays ( self , date , offset ) : """Add business days to a given date , taking holidays into consideration . Note : By definition , a zero offset causes the function to return the initial date , even it is not a business date . An offset of 1 represents the next business date , regardless of date b...
date = parsefun ( date ) if offset == 0 : return date dateoffset = self . addworkdays ( date , offset ) holidays = self . holidays # speed up if not holidays : return dateoffset weekdaymap = self . weekdaymap # speed up datewk = dateoffset . weekday ( ) if offset > 0 : # i is the index of first holiday > date #...
def facets ( mesh , engine = None ) : """Find the list of parallel adjacent faces . Parameters mesh : trimesh . Trimesh engine : str Which graph engine to use : ( ' scipy ' , ' networkx ' , ' graphtool ' ) Returns facets : sequence of ( n , ) int Groups of face indexes of parallel adjacent faces ....
# what is the radius of a circle that passes through the perpendicular # projection of the vector between the two non - shared vertices # onto the shared edge , with the face normal from the two adjacent faces radii = mesh . face_adjacency_radius # what is the span perpendicular to the shared edge span = mesh . face_ad...
def _callable_once ( func ) : """Returns a function that is only callable once ; any other call will do nothing"""
def once ( * args , ** kwargs ) : if not once . called : once . called = True return func ( * args , ** kwargs ) once . called = False return once
def reboot ( env , identifier , hard ) : """Reboot an active server ."""
hardware_server = env . client [ 'Hardware_Server' ] mgr = SoftLayer . HardwareManager ( env . client ) hw_id = helpers . resolve_id ( mgr . resolve_ids , identifier , 'hardware' ) if not ( env . skip_confirmations or formatting . confirm ( 'This will power off the server with id %s. ' 'Continue?' % hw_id ) ) : rai...
def create_product ( cls , product , ** kwargs ) : """Create Product Create a new Product This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . create _ product ( product , async = True ) > > > result = thread . get (...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _create_product_with_http_info ( product , ** kwargs ) else : ( data ) = cls . _create_product_with_http_info ( product , ** kwargs ) return data
def export_to_csv ( table , filename_or_fobj = None , encoding = "utf-8" , dialect = unicodecsv . excel , batch_size = 100 , callback = None , * args , ** kwargs ) : """Export a ` rows . Table ` to a CSV file . If a file - like object is provided it MUST be in binary mode , like in ` open ( filename , mode = ' ...
# TODO : will work only if table . fields is OrderedDict # TODO : should use fobj ? What about creating a method like json . dumps ? return_data , should_close = False , None if filename_or_fobj is None : filename_or_fobj = BytesIO ( ) return_data = should_close = True source = Source . from_file ( filename_or_...
def inflate_plugin_list ( plugin_list , inflate_plugin ) : """Inflate a list of strings / dictionaries to a list of plugin instances . Args : plugin _ list ( list ) : a list of str / dict . inflate _ plugin ( method ) : the method to inflate the plugin . Returns : list : a plugin instances list . Raises...
plugins = [ ] for plugin_def in plugin_list : if isinstance ( plugin_def , str ) : try : plugins . append ( inflate_plugin ( plugin_def ) ) except PluginNotFoundError as e : logger . error ( 'Could not import plugin identified by %s. ' 'Exception: %s.' , plugin_def , e ) ...
def fft_propagate ( fftfield , d , nm , res , method = "helmholtz" , ret_fft = False ) : """Propagates a 1D or 2D Fourier transformed field Parameters fftfield : 1 - dimensional or 2 - dimensional ndarray Fourier transform of 1D Electric field component d : float Distance to be propagated in pixels ( nega...
fshape = len ( fftfield . shape ) assert fshape in [ 1 , 2 ] , "Dimension of `fftfield` must be 1 or 2." if fshape == 1 : func = fft_propagate_2d else : func = fft_propagate_3d names = func . __code__ . co_varnames [ : func . __code__ . co_argcount ] loc = locals ( ) vardict = dict ( ) for name in names : v...
def omgprepare ( args ) : """% prog omgprepare ploidy anchorsfile blastfile Prepare to run Sankoff ' s OMG algorithm to get orthologs ."""
from jcvi . formats . blast import cscore from jcvi . formats . base import DictFile p = OptionParser ( omgprepare . __doc__ ) p . add_option ( "--norbh" , action = "store_true" , help = "Disable RBH hits [default: %default]" ) p . add_option ( "--pctid" , default = 0 , type = "int" , help = "Percent id cutoff for RBH ...
def setdefault ( obj , field , default ) : """Set an object ' s field to default if it doesn ' t have a value"""
setattr ( obj , field , getattr ( obj , field , default ) )
def create_model ( modelname , fields , indexes = None , basemodel = None , ** props ) : """Create model dynamically : param fields : Just format like [ { ' name ' : name , ' type ' : type , . . . } , type should be a string , eg . ' str ' , ' int ' , etc kwargs will be passed to Property . _ _ init _ _ ( )...
assert not props or isinstance ( props , dict ) assert not indexes or isinstance ( indexes , list ) props = SortedDict ( props or { } ) props [ '__dynamic__' ] = True props [ '__config__' ] = False for p in fields : kwargs = p . copy ( ) name = kwargs . pop ( 'name' ) _type = kwargs . pop ( 'type' ) # i...
def filter_step_asarray ( G , covY , pred , yt ) : """Filtering step of Kalman filter : array version . Parameters G : ( dy , dx ) numpy array mean of Y _ t | X _ t is G * X _ t covX : ( dx , dx ) numpy array covariance of Y _ t | X _ t pred : MeanAndCov object predictive distribution at time t Retu...
pm = pred . mean [ : , np . newaxis ] if pred . mean . ndim == 1 else pred . mean new_pred = MeanAndCov ( mean = pm , cov = pred . cov ) filt , logpyt = filter_step ( G , covY , new_pred , yt ) if pred . mean . ndim == 1 : filt . mean . squeeze ( ) return filt , logpyt
def publish ( self , message_type = ON_SEND , client_id = None , client_storage = None , * args , ** kwargs ) : """Publishes a message"""
self . publisher . publish ( message_type , client_id , client_storage , * args , ** kwargs )
def _get_bundles_by_type ( self , type ) : """Get a dictionary of bundles for requested type . Args : type : ' javascript ' or ' css '"""
bundles = { } bundle_definitions = self . config . get ( type ) if bundle_definitions is None : return bundles # bundle name : common for bundle_name , paths in bundle_definitions . items ( ) : bundle_files = [ ] # path : static / js / vendor / * . js for path in paths : # pattern : / tmp / static / js ...
def distributeParams ( self , param_name , param_count , center , spread , dist_type ) : '''Distributes heterogeneous values of one parameter to the AgentTypes in self . agents . Parameters param _ name : string Name of the parameter to be assigned . param _ count : int Number of different values the para...
# Get a list of discrete values for the parameter if dist_type == 'uniform' : # If uniform , center is middle of distribution , spread is distance to either edge param_dist = approxUniform ( N = param_count , bot = center - spread , top = center + spread ) elif dist_type == 'lognormal' : # If lognormal , center is ...
def qn_to_qubo ( expr ) : """Convert Sympy ' s expr to QUBO . Args : expr : Sympy ' s quadratic expression with variable ` q0 ` , ` q1 ` , . . . Returns : [ [ float ] ] : Returns QUBO matrix ."""
try : import sympy except ImportError : raise ImportError ( "This function requires sympy. Please install it." ) assert type ( expr ) == sympy . Add to_i = lambda s : int ( str ( s ) [ 1 : ] ) max_i = max ( map ( to_i , expr . free_symbols ) ) + 1 qubo = [ [ 0. ] * max_i for _ in range ( max_i ) ] for arg in ex...
def reindex_multifiles ( portal ) : """Reindex Multifiles to be searchable by the catalog"""
logger . info ( "Reindexing Multifiles ..." ) brains = api . search ( dict ( portal_type = "Multifile" ) , "bika_setup_catalog" ) total = len ( brains ) for num , brain in enumerate ( brains ) : if num % 100 == 0 : logger . info ( "Reindexing Multifile: {0}/{1}" . format ( num , total ) ) obj = api . ge...
def description ( self ) : """string or None if unknown"""
name = None try : name = self . _TYPE_NAMES [ self . audioObjectType ] except IndexError : pass if name is None : return if self . sbrPresentFlag == 1 : name += "+SBR" if self . psPresentFlag == 1 : name += "+PS" return text_type ( name )
def find ( self , path , all = False ) : '''Looks for files in the app directories .'''
found = os . path . join ( settings . STATIC_ROOT , path ) if all : return [ found ] else : return found
def _get_arch ( ) : """Determines the current processor architecture . @ rtype : str @ return : On error , returns : - L { ARCH _ UNKNOWN } ( C { " unknown " } ) meaning the architecture could not be detected or is not known to WinAppDbg . On success , returns one of the following values : - L { ARCH _ ...
try : si = GetNativeSystemInfo ( ) except Exception : si = GetSystemInfo ( ) try : return _arch_map [ si . id . w . wProcessorArchitecture ] except KeyError : return ARCH_UNKNOWN
def start_process ( self , lpCmdLine , ** kwargs ) : """Starts a new process for instrumenting ( or debugging ) . @ type lpCmdLine : str @ param lpCmdLine : Command line to execute . Can ' t be an empty string . @ type bConsole : bool @ keyword bConsole : True to inherit the console of the debugger . Defa...
# Get the flags . bConsole = kwargs . pop ( 'bConsole' , False ) bDebug = kwargs . pop ( 'bDebug' , False ) bFollow = kwargs . pop ( 'bFollow' , False ) bSuspended = kwargs . pop ( 'bSuspended' , False ) bInheritHandles = kwargs . pop ( 'bInheritHandles' , False ) dwParentProcessId = kwargs . pop ( 'dwParentProcessId' ...
def dump ( self , stream , progress = None , lower = None , upper = None , incremental = False , deltas = False ) : """Dump the repository to a dumpfile stream . : param stream : A file stream to which the dumpfile is written : param progress : A file stream to which progress is written : param lower : Must b...
cmd = [ SVNADMIN , 'dump' , '.' ] if progress is None : cmd . append ( '-q' ) if lower is not None : cmd . append ( '-r' ) if upper is None : cmd . append ( str ( int ( lower ) ) ) else : cmd . append ( '%d:%d' % ( int ( lower ) , int ( upper ) ) ) if incremental : cmd . append ( '--...
def connect ( self , broker , port = 1883 , client_id = "" , clean_session = True ) : """Connect to an MQTT broker . This is a pre - requisite step for publish and subscribe keywords . ` broker ` MQTT broker host ` port ` broker port ( default 1883) ` client _ id ` if not specified , a random id is generate...
logger . info ( 'Connecting to %s at port %s' % ( broker , port ) ) self . _connected = False self . _unexpected_disconnect = False self . _mqttc = mqtt . Client ( client_id , clean_session ) # set callbacks self . _mqttc . on_connect = self . _on_connect self . _mqttc . on_disconnect = self . _on_disconnect if self . ...
def download ( self , localfile : str , remotefile : str , overwrite : bool = True , ** kwargs ) : """This method downloads a remote file from the SAS servers file system . localfile - path to the local file to create or overwrite remotefile - path to remote file tp dpwnload overwrite - overwrite the output f...
logf = '' logn = self . _logcnt ( ) logcodei = "%put E3969440A681A24088859985" + logn + ";" logcodeo = "\nE3969440A681A24088859985" + logn logcodeb = logcodeo . encode ( ) valid = self . _sb . file_info ( remotefile , quiet = True ) if valid is None : return { 'Success' : False , 'LOG' : "File " + str ( remotefile ...