signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def del_unused_keyframes ( self ) : """Scans through list of keyframes in the channel and removes those which are not in self . key _ frame _ list ."""
skl = self . key_frame_list . sorted_key_list ( ) unused_keys = [ k for k in self . dct [ 'keys' ] if k not in skl ] for k in unused_keys : del self . dct [ 'keys' ] [ k ]
def get ( self , key , default = None ) : u"""Возвращает значение с указанным ключем Пример вызова : value = self . get ( ' system . database . name ' ) : param key : Имя параметра : param default : Значение , возвращаемое по умолчанию : return : mixed"""
segments = key . split ( '.' ) result = reduce ( lambda dct , k : dct and dct . get ( k ) or None , segments , self . data ) return result or default
def fetchRootJob ( self ) : """Fetches the root job from the jobStore that provides context for all other jobs . Exactly the same as the jobStore . loadRootJob ( ) function , but with a different exit message if the root job is not found ( indicating the workflow ran successfully to completion and certain sta...
try : return self . jobStore . loadRootJob ( ) except JobException : print ( 'Root job is absent. The workflow may have completed successfully.' , file = sys . stderr ) raise
def from_barset ( cls , barset , name = None , delay = None , use_wrapper = True , wrapper = None ) : """Copy a BarSet ' s frames to create a new FrameSet . Arguments : barset : An existing BarSet object to copy frames from . name : A name for the new FrameSet . delay : Delay for the animation . use _ wra...
if wrapper : data = tuple ( barset . wrap_str ( s , wrapper = wrapper ) for s in barset ) elif use_wrapper : data = tuple ( barset . wrap_str ( s ) for s in barset ) else : data = barset . data return cls ( data , name = name , delay = delay )
def tag ( collector , image , artifact , ** kwargs ) : """Tag an image !"""
if artifact in ( None , "" , NotSpecified ) : raise BadOption ( "Please specify a tag using the artifact option" ) if image . image_index in ( None , "" , NotSpecified ) : raise BadOption ( "Please specify an image with an image_index option" ) tag = image . image_name if collector . configuration [ "harpoon" ]...
def _query ( self , path : str , method : str , data : Dict [ str , Any ] = None , expected_status : int = 200 ) -> Union [ List [ Dict [ str , Any ] ] , Dict [ str , Any ] , None ] : """Make an HTTP request Args : path : the URI path ( not including the base url , start with the first uri segment , like ' us...
url = Pycord . url_base + path self . logger . debug ( f'Making {method} request to "{url}"' ) if method == 'GET' : r = requests . get ( url , headers = self . _build_headers ( ) ) elif method == 'POST' : r = requests . post ( url , headers = self . _build_headers ( ) , json = data ) r = requests . get ( ur...
def serv ( args ) : """Serve a rueckenwind application"""
if not args . no_debug : tornado . autoreload . start ( ) extra = [ ] if sys . stdout . isatty ( ) : # set terminal title sys . stdout . write ( '\x1b]2;rw: {}\x07' . format ( ' ' . join ( sys . argv [ 2 : ] ) ) ) if args . cfg : extra . append ( os . path . abspath ( args . cfg ) ) listen = ( int ( args . ...
def point_at ( self , horizontal_distance , vertical_increment , azimuth ) : """Compute the point with given horizontal , vertical distances and azimuth from this point . : param horizontal _ distance : Horizontal distance , in km . : type horizontal _ distance : float : param vertical _ increment : V...
lon , lat = geodetic . point_at ( self . longitude , self . latitude , azimuth , horizontal_distance ) return Point ( lon , lat , self . depth + vertical_increment )
def _get_selected_library_state ( self ) : """Returns the LibraryState which was selected in the LibraryTree : return : selected state in TreeView : rtype : LibraryState"""
library_os_path , library_path , library_name , item_key = self . extract_library_properties_from_selected_row ( ) if library_path is None : return None logger . debug ( "Link library state '{0}' (with library tree path: {2} and file system path: {1}) into state " "machine." . format ( str ( item_key ) , library_os...
def reverse_dict ( dict_obj ) : """Reverse a dict , so each value in it maps to a sorted list of its keys . Parameters dict _ obj : dict A key - value dict . Returns dict A dict where each value maps to a sorted list of all the unique keys that mapped to it . Example > > > dicti = { ' a ' : 1 , ' ...
new_dict = { } for key in dict_obj : add_to_dict_val_set ( dict_obj = new_dict , key = dict_obj [ key ] , val = key ) for key in new_dict : new_dict [ key ] = sorted ( new_dict [ key ] , reverse = False ) return new_dict
def find_file ( name , path = os . getcwd ( ) , deep = False , partial = False ) : """Searches for a file and returns its path upon finding it . Searches for a file with the given ` name ` in the list of directories mentioned in ` path ` . It also supports ` deep ` search ( recursive ) and ` partial ` search ...
paths = path . split ( os . pathsep ) if type ( path ) is str else path for p in paths : ret = __find_file ( name , p , deep , partial ) if ret : return ret
def get_default_config ( self ) : """Returns the default collector settings"""
config = super ( ElbCollector , self ) . get_default_config ( ) config . update ( { 'path' : 'elb' , 'regions' : [ 'us-west-1' ] , 'interval' : 60 , 'format' : '$zone.$elb_name.$metric_name' , } ) return config
def analysis ( self ) : """The list of analysis of ` ` words ` ` layer elements ."""
if not self . is_tagged ( ANALYSIS ) : self . tag_analysis ( ) return [ word [ ANALYSIS ] for word in self . words ]
def detunings_code ( Neu , Nl , pairs , omega_levelu , iu0 , ju0 ) : r"""Get the code to calculate the simplified detunings . > > > Ne = 6 > > > Nl = 2 > > > omega _ level = [ 0.0 , 100.0 , 100.0 , 200.0 , 200.0 , 300.0] > > > xi = np . zeros ( ( Nl , Ne , Ne ) ) > > > coup = [ [ ( 1 , 0 ) , ( 2 , 0 ) ] ,...
code_det = "" for l in range ( Nl ) : for pair in pairs [ l ] : iu , ju = pair code_det += " delta" + str ( l + 1 ) code_det += "_" + str ( iu + 1 ) code_det += "_" + str ( ju + 1 ) code_det += " = detuning_knob[" + str ( l ) + "]" corr = - omega_levelu [ iu ] + om...
def _handle_response ( self , response ) : """Handle the HTTP response by memoing the headers and then delivering bytes ."""
self . client . status = response . code self . response_headers = response . headers # XXX This workaround ( which needs to be improved at that ) for possible # bug in Twisted with new client : # http : / / twistedmatrix . com / trac / ticket / 5476 if self . _method . upper ( ) == 'HEAD' or response . code == NO_CONT...
def register_retinotopy ( hemi , model = 'benson17' , model_hemi = Ellipsis , polar_angle = None , eccentricity = None , weight = None , pRF_radius = None , weight_min = 0.1 , eccentricity_range = None , partial_voluming_correction = False , radius_weight = 1 , field_sign_weight = 1 , invert_rh_field_sign = False , sca...
# create the imap m = retinotopy_registration ( cortex = hemi , model_argument = model , model_hemi = model_hemi , polar_angle = polar_angle , eccentricity = eccentricity , weight = weight , pRF_radius = pRF_radius , weight_min = weight_min , eccentricity_range = eccentricity_range , partial_voluming_correction = parti...
def evaluate_barycentric ( self , lambda1 , lambda2 , lambda3 , _verify = True ) : r"""Compute a point on the surface . Evaluates : math : ` B \ left ( \ lambda _ 1 , \ lambda _ 2 , \ lambda _ 3 \ right ) ` . . . image : : . . / . . / images / surface _ evaluate _ barycentric . png : align : center . . test...
if _verify : self . _verify_barycentric ( lambda1 , lambda2 , lambda3 ) return _surface_helpers . evaluate_barycentric ( self . _nodes , self . _degree , lambda1 , lambda2 , lambda3 )
def fbank ( signal , samplerate = 16000 , winlen = 0.025 , winstep = 0.01 , nfilt = 26 , nfft = 512 , lowfreq = 0 , highfreq = None , preemph = 0.97 , winfunc = lambda x : numpy . ones ( ( x , ) ) ) : """Compute Mel - filterbank energy features from an audio signal . : param signal : the audio signal from which t...
highfreq = highfreq or samplerate / 2 signal = sigproc . preemphasis ( signal , preemph ) frames = sigproc . framesig ( signal , winlen * samplerate , winstep * samplerate , winfunc ) pspec = sigproc . powspec ( frames , nfft ) energy = numpy . sum ( pspec , 1 ) # this stores the total energy in each frame energy = num...
def get_args ( tp , evaluate = None ) : """Get type arguments with all substitutions performed . For unions , basic simplifications used by Union constructor are performed . On versions prior to 3.7 if ` evaluate ` is False ( default ) , report result as nested tuple , this matches the internal representati...
if NEW_TYPING : if evaluate is not None and not evaluate : raise ValueError ( 'evaluate can only be True in Python 3.7' ) if isinstance ( tp , _GenericAlias ) : res = tp . __args__ if get_origin ( tp ) is collections . abc . Callable and res [ 0 ] is not Ellipsis : res = ( li...
def estimateDeltaStaeckel ( pot , R , z , no_median = False ) : """NAME : estimateDeltaStaeckel PURPOSE : Estimate a good value for delta using eqn . ( 9 ) in Sanders ( 2012) INPUT : pot - Potential instance or list thereof R , z - coordinates ( if these are arrays , the median estimated delta is return...
if isinstance ( R , nu . ndarray ) : delta2 = nu . array ( [ ( z [ ii ] ** 2. - R [ ii ] ** 2. # eqn . ( 9 ) has a sign error + ( 3. * R [ ii ] * _evaluatezforces ( pot , R [ ii ] , z [ ii ] ) - 3. * z [ ii ] * _evaluateRforces ( pot , R [ ii ] , z [ ii ] ) + R [ ii ] * z [ ii ] * ( evaluateR2derivs ( pot , R [...
def encode ( self , data : mx . sym . Symbol , data_length : Optional [ mx . sym . Symbol ] , seq_len : int ) -> Tuple [ mx . sym . Symbol , mx . sym . Symbol , int ] : """Encodes data given sequence lengths of individual examples and maximum sequence length . : param data : Input data . : param data _ length :...
factor_embeddings = [ ] # type : List [ mx . sym . Symbol ] if self . is_source : data , * data_factors = mx . sym . split ( data = data , num_outputs = self . config . num_factors , axis = 2 , squeeze_axis = True , name = self . prefix + "factor_split" ) if self . config . factor_configs is not None : ...
def overlap_matrix ( hdf5_file_name , consensus_labels , cluster_runs ) : """Writes on disk ( in an HDF5 file whose handle is provided as the first argument to this function ) a stack of matrices , each describing for a particular run the overlap of cluster ID ' s that are matching each of the cluster ID ' s ...
if reduce ( operator . mul , cluster_runs . shape , 1 ) == max ( cluster_runs . shape ) : cluster_runs = cluster_runs . reshape ( 1 , - 1 ) N_runs , N_samples = cluster_runs . shape N_consensus_labels = np . unique ( consensus_labels ) . size indices_consensus_adjacency = np . empty ( 0 , dtype = np . int32 ) indpt...
def theo1 ( data , rate = 1.0 , data_type = "phase" , taus = None ) : """PRELIMINARY - REQUIRES FURTHER TESTING . Theo1 is a two - sample variance with improved confidence and extended averaging factor range . . . math : : \\ sigma ^ 2 _ { THEO1 } ( m \\ tau _ 0 ) = { 1 \\ over ( m \\ tau _ 0 ) ^ 2 ( N - m ...
phase = input_to_phase ( data , rate , data_type ) tau0 = 1.0 / rate ( phase , ms , taus_used ) = tau_generator ( phase , rate , taus , even = True ) devs = np . zeros_like ( taus_used ) deverrs = np . zeros_like ( taus_used ) ns = np . zeros_like ( taus_used ) N = len ( phase ) for idx , m in enumerate ( ms ) : m ...
def index_search ( right_eigenvectors ) : """Find simplex structure in eigenvectors to begin PCCA + . Parameters right _ eigenvectors : ndarray Right eigenvectors of transition matrix Returns index : ndarray Indices of simplex"""
num_micro , num_eigen = right_eigenvectors . shape index = np . zeros ( num_eigen , 'int' ) # first vertex : row with largest norm index [ 0 ] = np . argmax ( [ norm ( right_eigenvectors [ i ] ) for i in range ( num_micro ) ] ) ortho_sys = right_eigenvectors - np . outer ( np . ones ( num_micro ) , right_eigenvectors [...
def get_chunks ( source , chunk_len ) : """Returns an iterator over ' chunk _ len ' chunks of ' source '"""
return ( source [ i : i + chunk_len ] for i in range ( 0 , len ( source ) , chunk_len ) )
def releases ( self , owner , module ) : """Fetch the releases of a module ."""
resource = self . RRELEASES params = { self . PMODULE : owner + '-' + module , self . PLIMIT : self . max_items , self . PSHOW_DELETED : 'true' , self . PSORT_BY : self . VRELEASE_DATE , } for page in self . _fetch ( resource , params ) : yield page
def _handle_posix ( self , i , result , end_range ) : """Handle posix classes ."""
last_posix = False m = i . match ( RE_POSIX ) if m : last_posix = True # Cannot do range with posix class # so escape last ` - ` if we think this # is the end of a range . if end_range and i . index - 1 >= end_range : result [ - 1 ] = '\\' + result [ - 1 ] posix_type = uniprops . POSIX_B...
def put ( self , src , dst ) : '''Upload a file to HDFS This will take a file from the ` ` testfiles _ path ` ` supplied in the constuctor .'''
src = "%s%s" % ( self . _testfiles_path , src ) return self . _getStdOutCmd ( [ self . _hadoop_cmd , 'fs' , '-put' , src , self . _full_hdfs_path ( dst ) ] , True )
def init ( ) : """Execute init tasks for all components ( virtualenv , pip ) ."""
print ( yellow ( "# Setting up environment...\n" , True ) ) virtualenv . init ( ) virtualenv . update_requirements ( ) print ( green ( "\n# DONE." , True ) ) print ( green ( "Type " ) + green ( "activate" , True ) + green ( " to enable your virtual environment." ) )
def get_savepath ( self , url , savepath = None ) : """Evaluates the savepath with the help of the given url . : param str url : url to evaluate the savepath with : return str : the evaluated savepath for the given url"""
timestamp = int ( time . time ( ) ) if not savepath : savepath = self . cfg_savepath # lambda is used for lazy evaluation savepath = re . sub ( re_working_path , lambda match : self . working_path , savepath ) savepath = re . sub ( re_time_dl , lambda match : SavepathParser . time_replacer ( match , timestamp ) , s...
def get_contacts_of_client_per_page ( self , client_id , per_page = 1000 , page = 1 ) : """Get contacts of client per page : param client _ id : the client id : param per _ page : How many objects per page . Default : 1000 : param page : Which page . Default : 1 : return : list"""
return self . _get_resource_per_page ( resource = CONTACTS , per_page = per_page , page = page , params = { 'client_id' : client_id } , )
def get_client_history ( self , client ) : """Returns the history for a client ."""
data = self . _request ( 'GET' , '/clients/{}/history' . format ( client ) ) return data . json ( )
def load ( self , filename = None ) : """Loads file and registers filename as attribute ."""
assert not self . __flag_loaded , "File can be loaded only once" if filename is None : filename = self . default_filename assert filename is not None , "{0!s} class has no default filename" . format ( self . __class__ . __name__ ) # Convention : trying to open empty file is an error , # because it could be of ( alm...
def dump_json ( d : dict ) -> None : """Dump json when using tuples for dictionary keys Have to convert tuples to strings to dump out as json"""
import json k = d . keys ( ) v = d . values ( ) k1 = [ str ( i ) for i in k ] return json . dumps ( dict ( zip ( * [ k1 , v ] ) ) , indent = 4 )
def get_stored_procs ( db_connection ) : """: param db _ connection : : return :"""
sql = "SHOW PROCEDURE STATUS;" procs = execute_sql ( sql , db_connection ) return [ x [ 1 ] for x in procs ]
def ncoef_fmap ( order ) : """Expected number of coefficients in a 2D transformation of a given order . Parameters order : int Order of the 2D polynomial transformation . Returns ncoef : int Expected number of coefficients ."""
ncoef = 0 for i in range ( order + 1 ) : for j in range ( i + 1 ) : ncoef += 1 return ncoef
def create ( self , weight , priority , enabled , friendly_name , sip_url ) : """Create a new OriginationUrlInstance : param unicode weight : The value that determines the relative load the URI should receive compared to others with the same priority : param unicode priority : The relative importance of the URI...
data = values . of ( { 'Weight' : weight , 'Priority' : priority , 'Enabled' : enabled , 'FriendlyName' : friendly_name , 'SipUrl' : sip_url , } ) payload = self . _version . create ( 'POST' , self . _uri , data = data , ) return OriginationUrlInstance ( self . _version , payload , trunk_sid = self . _solution [ 'trunk...
def append_change_trust_op ( self , asset_code , asset_issuer , limit = None , source = None ) : """Append a : class : ` ChangeTrust < stellar _ base . operation . ChangeTrust > ` operation to the list of operations . : param str asset _ issuer : The issuer address for the asset . : param str asset _ code : T...
asset = Asset ( asset_code , asset_issuer ) op = operation . ChangeTrust ( asset , limit , source ) return self . append_op ( op )
def _convert_py_number ( value ) : """Convert a Python integer value into equivalent C object . Will attempt to use the smallest possible conversion , starting with int , then long then double ."""
try : return c_uamqp . int_value ( value ) except OverflowError : pass try : return c_uamqp . long_value ( value ) except OverflowError : pass return c_uamqp . double_value ( value )
def Registry ( address = 'https://index.docker.io' , ** kwargs ) : """: return :"""
registry = None try : try : registry = V1 ( address , ** kwargs ) registry . ping ( ) except RegistryException : registry = V2 ( address , ** kwargs ) registry . ping ( ) except OSError : logger . warning ( 'Was unable to verify certs for a registry @ {0}. ' 'Will not be able...
def _get_timeout ( self , timeout ) : """Helper that always returns a : class : ` urllib3 . util . Timeout `"""
if timeout is _Default : return self . timeout . clone ( ) if isinstance ( timeout , Timeout ) : return timeout . clone ( ) else : # User passed us an int / float . This is for backwards compatibility , # can be removed later return Timeout . from_float ( timeout )
def get_default_config_help ( self ) : """Help text"""
config = super ( DatadogHandler , self ) . get_default_config_help ( ) config . update ( { 'api_key' : 'Datadog API key' , 'queue_size' : 'Number of metrics to queue before send' , } ) return config
def uni_to_beta ( text ) : """Convert unicode text to a betacode equivalent . This method can handle tónos or oxeîa characters in the input . Args : text : The text to convert to betacode . This text does not have to all be Greek polytonic text , and only Greek characters will be converted . Note that i...
u = _UNICODE_MAP transform = [ ] for ch in text : try : conv = u [ ch ] except KeyError : conv = ch transform . append ( conv ) converted = '' . join ( transform ) return converted
def enable_cloud_integration ( self , id , ** kwargs ) : # noqa : E501 """Enable a specific cloud integration # noqa : E501 # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . enable _ cloud _ inte...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . enable_cloud_integration_with_http_info ( id , ** kwargs ) # noqa : E501 else : ( data ) = self . enable_cloud_integration_with_http_info ( id , ** kwargs ) # noqa : E501 return data
def wrap_parser_error ( self , data , renderer_context ) : """Convert parser errors to the JSON API Error format Parser errors have a status code of 400 , like field errors , but have the same native format as generic errors . Also , the detail message is often specific to the input , so the error is listed a...
response = renderer_context . get ( "response" , None ) status_code = response and response . status_code if status_code != 400 : raise WrapperNotApplicable ( 'Status code must be 400.' ) if list ( data . keys ( ) ) != [ 'detail' ] : raise WrapperNotApplicable ( 'Data must only have "detail" key.' ) # Probably ...
def get_next_valid_day ( self , timestamp ) : """Get next valid day for timerange : param timestamp : time we compute from : type timestamp : int : return : timestamp of the next valid day ( midnight ) in LOCAL time . : rtype : int | None"""
if self . get_next_future_timerange_valid ( timestamp ) is None : # this day is finish , we check for next period ( start_time , _ ) = self . get_start_and_end_time ( get_day ( timestamp ) + 86400 ) else : ( start_time , _ ) = self . get_start_and_end_time ( timestamp ) if timestamp <= start_time : return g...
def _init_setup_console_data ( self , order : str = "C" ) -> None : """Setup numpy arrays over libtcod data buffers ."""
global _root_console self . _key_color = None if self . console_c == ffi . NULL : _root_console = self self . _console_data = lib . TCOD_ctx . root else : self . _console_data = ffi . cast ( "struct TCOD_Console*" , self . console_c ) self . _tiles = np . frombuffer ( ffi . buffer ( self . _console_data . t...
def upload ( self ) : '''一般上传模式 . 使用这种方式上传 , 不可以中断上传过程 , 但因为只用它来上传小的文件 , 所以 最终的影响不会很大 .'''
info = pcs . upload ( self . cookie , self . row [ SOURCEPATH_COL ] , self . row [ PATH_COL ] , self . upload_mode ) if info : self . emit ( 'uploaded' , self . row [ FID_COL ] ) else : self . emit ( 'network-error' , self . row [ FID_COL ] )
def _valid_choices ( cla55 : type ) -> Dict [ str , str ] : """Return a mapping { registered _ name - > subclass _ name } for the registered subclasses of ` cla55 ` ."""
valid_choices : Dict [ str , str ] = { } if cla55 not in Registrable . _registry : raise ValueError ( f"{cla55} is not a known Registrable class" ) for name , subclass in Registrable . _registry [ cla55 ] . items ( ) : # These wrapper classes need special treatment if isinstance ( subclass , ( _Seq2SeqWrapper ,...
def _reset ( self ) : """This method is for use by tests only !"""
self . bundles = AttrDict ( ) self . _bundles = _DeferredBundleFunctionsStore ( ) self . babel_bundle = None self . env = None self . extensions = AttrDict ( ) self . services = AttrDict ( ) self . _deferred_functions = [ ] self . _initialized = False self . _models_initialized = False self . _services_initialized = Fa...
def scoped ( self , func ) : """Decorator to switch scopes ."""
@ wraps ( func ) def wrapper ( * args , ** kwargs ) : scope = kwargs . get ( "scope" , self . __factory__ . default_scope ) with self . scoped_to ( scope ) : return func ( * args , ** kwargs ) return wrapper
def _operator_norms ( L ) : """Get operator norms if needed . Parameters L : sequence of ` Operator ` or float The operators or the norms of the operators that are used in the ` douglas _ rachford _ pd ` method . For ` Operator ` entries , the norm is computed with ` ` Operator . norm ( estimate = True ) ...
L_norms = [ ] for Li in L : if np . isscalar ( Li ) : L_norms . append ( float ( Li ) ) elif isinstance ( Li , Operator ) : L_norms . append ( Li . norm ( estimate = True ) ) else : raise TypeError ( 'invalid entry {!r} in `L`' . format ( Li ) ) return L_norms
def display ( self ) : """Whether this object should be displayed in documentation . This attribute depends on the configuration options given in : confval : ` autoapi _ options ` . : type : bool"""
if self . is_undoc_member and "undoc-members" not in self . options : return False if self . is_private_member and "private-members" not in self . options : return False if self . is_special_member and "special-members" not in self . options : return False return True
def auth ( self ) : """tuple of ( username , password ) . if use _ keyring is set to true the password will be queried from the local keyring instead of taken from the configuration file ."""
username = self . _settings [ "username" ] if not username : raise ValueError ( "Username was not configured in %s" % CONFIG_FILE ) if self . _settings [ "use_keyring" ] : password = self . keyring_get_password ( username ) if not password : self . keyring_set_password ( username ) password ...
def discover ( service = "ssdp:all" , timeout = 1 , retries = 2 , ipAddress = "239.255.255.250" , port = 1900 ) : """Discovers UPnP devices in the local network . Try to discover all devices in the local network which do support UPnP . The discovery process can fail for various reasons and it is recommended to ...
socket . setdefaulttimeout ( timeout ) messages = [ ] if isinstance ( service , str ) : services = [ service ] elif isinstance ( service , list ) : services = service for service in services : message = 'M-SEARCH * HTTP/1.1\r\nMX: 5\r\nMAN: "ssdp:discover"\r\nHOST: ' + ipAddress + ':' + str ( port ) + '\r\n...
def _format_ase2clusgeo ( obj , all_atomtypes = None ) : """Takes an ase Atoms object and returns numpy arrays and integers which are read by the internal clusgeo . Apos is currently a flattened out numpy array Args : obj ( ) : all _ atomtypes ( ) : sort ( ) :"""
# atoms metadata totalAN = len ( obj ) if all_atomtypes is not None : atomtype_set = set ( all_atomtypes ) else : atomtype_set = set ( obj . get_atomic_numbers ( ) ) atomtype_lst = np . sort ( list ( atomtype_set ) ) n_atoms_per_type_lst = [ ] pos_lst = [ ] for atomtype in atomtype_lst : condition = obj . g...
def load_file_or_hdu ( filename ) : """Load a file from disk and return an HDUList If filename is already an HDUList return that instead Parameters filename : str or HDUList File or HDU to be loaded Returns hdulist : HDUList"""
if isinstance ( filename , fits . HDUList ) : hdulist = filename else : hdulist = fits . open ( filename , ignore_missing_end = True ) return hdulist
def placeOrder ( self , contract : Contract , order : Order ) -> Trade : """Place a new order or modify an existing order . Returns a Trade that is kept live updated with status changes , fills , etc . Args : contract : Contract to use for order . order : The order to be placed ."""
orderId = order . orderId or self . client . getReqId ( ) self . client . placeOrder ( orderId , contract , order ) now = datetime . datetime . now ( datetime . timezone . utc ) key = self . wrapper . orderKey ( self . wrapper . clientId , orderId , order . permId ) trade = self . wrapper . trades . get ( key ) if trad...
def GetAttributes ( self , urns , age = NEWEST_TIME ) : """Retrieves all the attributes for all the urns ."""
urns = set ( [ utils . SmartUnicode ( u ) for u in urns ] ) to_read = { urn : self . _MakeCacheInvariant ( urn , age ) for urn in urns } # Urns not present in the cache we need to get from the database . if to_read : for subject , values in data_store . DB . MultiResolvePrefix ( to_read , AFF4_PREFIXES , timestamp ...
def swipe_right ( self , width : int = 1080 , length : int = 1920 ) -> None : '''Swipe right .'''
self . swipe ( 0.2 * width , 0.5 * length , 0.8 * width , 0.5 * length )
def compare_csv_timeseries_files ( file1 , file2 , header = True ) : """This function compares two csv files"""
return compare_csv_decimal_files ( file1 , file2 , header , True )
def _prepare_sets ( self , sets ) : """Return all sets in self . _ lazy _ collection [ ' sets ' ] to be ready to be used to intersect them . Called by _ get _ final _ set , to use in subclasses . Must return a tuple with a set of redis set keys , and another with new temporary keys to drop at the end of _ get...
final_sets = set ( ) tmp_keys = set ( ) for set_ in sets : if isinstance ( set_ , str ) : final_sets . add ( set_ ) elif isinstance ( set_ , ParsedFilter ) : for index_key , key_type , is_tmp in set_ . index . get_filtered_keys ( set_ . suffix , accepted_key_types = self . _accepted_key_types , ...
def from_json ( json_data ) : """Returns a pyalveo . OAuth2 given a json string built from the oauth . to _ json ( ) method ."""
# If we have a string , then decode it , otherwise assume it ' s already decoded if isinstance ( json_data , str ) : data = json . loads ( json_data ) else : data = json_data oauth = Cache ( cache_dir = data . get ( 'cache_dir' , None ) , max_age = data . get ( 'max_age' , None ) ) return oauth
def ArcSin ( input_vertex : vertex_constructor_param_types , label : Optional [ str ] = None ) -> Vertex : """Takes the inverse sin of a vertex , Arcsin ( vertex ) : param input _ vertex : the vertex"""
return Double ( context . jvm_view ( ) . ArcSinVertex , label , cast_to_double_vertex ( input_vertex ) )
def read_persistent_volume ( self , name , ** kwargs ) : """read the specified PersistentVolume This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . read _ persistent _ volume ( name , async _ req = True ) > > > ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . read_persistent_volume_with_http_info ( name , ** kwargs ) else : ( data ) = self . read_persistent_volume_with_http_info ( name , ** kwargs ) return data
def document ( self , result ) : """Build dict for MongoDB , expanding result keys as we go ."""
self . _add_meta ( result ) walker = JsonWalker ( JsonWalker . value_json , JsonWalker . dict_expand ) r = walker . walk ( result ) return r
def print_locale_info ( out = stderr ) : """Print locale info ."""
for key in ( "LANGUAGE" , "LC_ALL" , "LC_CTYPE" , "LANG" ) : print_env_info ( key , out = out ) print ( _ ( "Default locale:" ) , i18n . get_locale ( ) , file = out )
def jdbc_connection_pool ( self , name , res_type , ds_classname , props ) : """Domain JDBC connection pool . : param str name : Resource name . : param str res _ type : Resource type . : param str ds _ classname : Data source class name . : param dict props : Connection pool properties . : rtype ...
return JDBCConnectionPool ( self . __endpoint , name , res_type , ds_classname , props )
def set_membind ( nodemask ) : """Sets the memory allocation mask . The thread will only allocate memory from the nodes set in nodemask . @ param nodemask : node mask @ type nodemask : C { set }"""
mask = set_to_numa_nodemask ( nodemask ) tmp = bitmask_t ( ) tmp . maskp = cast ( byref ( mask ) , POINTER ( c_ulong ) ) tmp . size = sizeof ( nodemask_t ) * 8 libnuma . numa_set_membind ( byref ( tmp ) )
def get_os_dist_info ( ) : """Returns the distribution info"""
distribution = platform . dist ( ) dist_name = distribution [ 0 ] . lower ( ) dist_version_str = distribution [ 1 ] if dist_name and dist_version_str : return dist_name , dist_version_str else : return None , None
def det_refpoint ( self , angle ) : """Return the detector reference point position at ` ` angle ` ` . For an angle ` ` phi ` ` , the detector position is given by : : det _ ref ( phi ) = translation + rot _ matrix ( phi ) * ( det _ rad * src _ to _ det _ init ) + ( offset _ along _ axis + pitch * phi ) * a...
squeeze_out = ( np . shape ( angle ) == ( ) ) angle = np . array ( angle , dtype = float , copy = False , ndmin = 1 ) rot_matrix = self . rotation_matrix ( angle ) extra_dims = angle . ndim # Initial vector from center of rotation to detector . # It can be computed this way since source and detector are at # maximum di...
def log ( self , msg , error = False ) : """Log message helper ."""
output = self . stdout if error : output = self . stderr output . write ( msg ) output . write ( '\n' )
def load_models ( * chain , ** kwargs ) : """Decorator to load a chain of models from the given parameters . This works just like : func : ` load _ model ` and accepts the same parameters , with some small differences . : param chain : The chain is a list of tuples of ( ` ` model ` ` , ` ` attributes ` ` , ` ` ...
def inner ( f ) : @ wraps ( f ) def decorated_function ( * args , ** kw ) : permissions = None permission_required = kwargs . get ( 'permission' ) url_check_attributes = kwargs . get ( 'urlcheck' , [ ] ) if isinstance ( permission_required , six . string_types ) : per...
def get_snapshot_by_version ( obj , version = 0 ) : """Get a snapshot by version Snapshot versions begin with ` 0 ` , because this is the first index of the storage , which is a list . : param obj : Content object : param version : The index position of the snapshot in the storage : returns : Snapshot at ...
if version < 0 : return None snapshots = get_snapshots ( obj ) if version > len ( snapshots ) - 1 : return None return snapshots [ version ]
def finish ( self ) : """Parse the buffered response body , rewrite its URLs , write the result to the wrapped request , and finish the wrapped request ."""
stylesheet = '' . join ( self . _buffer ) parser = CSSParser ( ) css = parser . parseString ( stylesheet ) replaceUrls ( css , self . _replace ) self . request . write ( css . cssText ) return self . request . finish ( )
def key_tuple_value_nested_generator ( dict_obj ) : """Recursively iterate over key - tuple - value pairs of nested dictionaries . Parameters dict _ obj : dict The outer - most dict to iterate on . Returns generator A generator over key - tuple - value pairs in all nested dictionaries . Example > > ...
for key , value in dict_obj . items ( ) : if isinstance ( value , dict ) : for nested_key , value in key_tuple_value_nested_generator ( value ) : yield tuple ( [ key ] ) + nested_key , value else : yield tuple ( [ key ] ) , value
def get_short_status ( self , hosts , services ) : """Get the short status of this host : return : " O " , " W " , " C " , " U ' , or " n / a " based on service state _ id or business _ rule state : rtype : str"""
mapping = { 0 : "O" , 1 : "W" , 2 : "C" , 3 : "U" , 4 : "N" , } if self . got_business_rule : return mapping . get ( self . business_rule . get_state ( hosts , services ) , "n/a" ) return mapping . get ( self . state_id , "n/a" )
def load_rf ( freq = "M" ) : """Build a risk - free rate return series using 3 - month US T - bill yields . The 3 - Month Treasury Bill : Secondary Market Rate from the Federal Reserve ( a yield ) is convert to a total return . See ' Methodology ' for details . The time series should closely mimic returns of ...
freqs = "DWMQA" freq = freq . upper ( ) if freq not in freqs : raise ValueError ( "`freq` must be either a single element or subset" " from %s, case-insensitive" % freqs ) # Load daily 3 - Month Treasury Bill : Secondary Market Rate . # Note that this is on discount basis and will be converted to BEY . # Periodicit...
def touch ( self , mode = 0o666 , exist_ok = True ) : """Create this file with the given access mode , if it doesn ' t exist . Based on : https : / / github . com / python / cpython / blob / master / Lib / pathlib . py )"""
if exist_ok : # First try to bump modification time # Implementation note : GNU touch uses the UTIME _ NOW option of # the utimensat ( ) / futimens ( ) functions . try : os . utime ( self , None ) except OSError : # Avoid exception chaining pass else : return flags = os . O_CREAT | o...
def ast2expr ( ast ) : """Convert an abstract syntax tree to an Expression ."""
if ast [ 0 ] == 'const' : return _CONSTS [ ast [ 1 ] ] elif ast [ 0 ] == 'var' : return exprvar ( ast [ 1 ] , ast [ 2 ] ) else : xs = [ ast2expr ( x ) for x in ast [ 1 : ] ] return ASTOPS [ ast [ 0 ] ] ( * xs , simplify = False )
def discover_package_doc_dir ( initial_dir ) : """Discover the ` ` doc / ` ` dir of a package given an initial directory . Parameters initial _ dir : ` str ` The inititial directory to search from . In practice , this is often the directory that the user is running the package - docs CLI from . This direc...
# Create an absolute Path to work with initial_dir = pathlib . Path ( initial_dir ) . resolve ( ) # Check if this is the doc / dir already with a conf . py if _has_conf_py ( initial_dir ) : return str ( initial_dir ) # Search for a doc / directory in cwd ( this covers the case of running # the CLI from the root of ...
def list_upgrades ( refresh = True , ** kwargs ) : '''Check whether or not an upgrade is available for all packages CLI Example : . . code - block : : bash salt ' * ' pkg . list _ upgrades'''
# sample output of ' xbps - install - un ' : # fuse - 2.9.4_4 update i686 http : / / repo . voidlinux . eu / current 298133 91688 # xtools - 0.34_1 update noarch http : / / repo . voidlinux . eu / current 21424 10752 refresh = salt . utils . data . is_true ( refresh ) # Refresh repo index before checking for latest ver...
def tile_status ( self ) : """Get the current status of this tile"""
stat = self . status ( ) flags = stat [ 'status' ] # FIXME : This needs to stay in sync with lib _ common : cdb _ status . h status = { } status [ 'debug_mode' ] = bool ( flags & ( 1 << 3 ) ) status [ 'configured' ] = bool ( flags & ( 1 << 1 ) ) status [ 'app_running' ] = bool ( flags & ( 1 << 0 ) ) status [ 'trapped' ...
def status ( self ) : """Get the status of Alerting Service : return : Status object"""
orig_dict = self . _get ( self . _service_url ( 'status' ) ) orig_dict [ 'implementation_version' ] = orig_dict . pop ( 'Implementation-Version' ) orig_dict [ 'built_from_git_sha1' ] = orig_dict . pop ( 'Built-From-Git-SHA1' ) return Status ( orig_dict )
def _makeUniqueFilename ( taken_names , name ) : """Helper function . Checks if name is in the set ' taken _ names ' . If so , attepts to form up an untaken name ( by adding numbered suffixes ) . Adds name to taken _ names ."""
if name in taken_names : # try to form up new name basename , ext = os . path . splitext ( name ) num = 1 name = "%s-%d%s" % ( basename , num , ext ) while name in taken_names : num += 1 name = "%s-%d%s" % ( basename , num , ext ) # finally , enter name into set taken_names . add ( name ...
def inferTM ( self , bottomUp , externalInput ) : """Run inference and return the set of predicted cells"""
self . reset ( ) # print > > sys . stderr , " Bottom up : " , bottomUp # print > > sys . stderr , " ExternalInput : " , externalInput self . tm . compute ( bottomUp , basalInput = externalInput , learn = False ) # print > > sys . stderr , ( " new active cells " + str ( self . tm . getActiveCells ( ) ) ) # print > > sys...
def name ( self ) : # type : ( ) - > bytes '''Generate a string that contains all components of the symlink . Parameters : None Returns : String containing all components of the symlink .'''
if not self . _initialized : raise pycdlibexception . PyCdlibInternalError ( 'SL record not yet initialized!' ) outlist = [ ] # type : List [ bytes ] continued = False for comp in self . symlink_components : name = comp . name ( ) if name == b'/' : outlist = [ ] continued = False nam...
def _decorate_axes ( ax , freq , kwargs ) : """Initialize axes for time - series plotting"""
if not hasattr ( ax , '_plot_data' ) : ax . _plot_data = [ ] ax . freq = freq xaxis = ax . get_xaxis ( ) xaxis . freq = freq if not hasattr ( ax , 'legendlabels' ) : ax . legendlabels = [ kwargs . get ( 'label' , None ) ] else : ax . legendlabels . append ( kwargs . get ( 'label' , None ) ) ax . view_interv...
def merge_bibtex_collections ( citednames , maindict , extradicts , allow_missing = False ) : """There must be a way to be efficient and stream output instead of loading everything into memory at once , but , meh . Note that we augment ` citednames ` with all of the names in ` maindict ` . The intention is th...
allrecords = { } for ed in extradicts : allrecords . update ( ed ) allrecords . update ( maindict ) missing = [ ] from collections import OrderedDict records = OrderedDict ( ) from itertools import chain wantednames = sorted ( chain ( citednames , six . viewkeys ( maindict ) ) ) for name in wantednames : rec = ...
def get_enricher ( config , metrics , ** kwargs ) : """Get a GCEEnricher client . A factory function that validates configuration and returns an enricher client ( : interface : ` gordon . interfaces . IMessageHandler ` ) provider . Args : config ( dict ) : Google Compute Engine API related configuration ....
builder = enricher . GCEEnricherBuilder ( config , metrics , ** kwargs ) return builder . build_enricher ( )
def write_json ( self , ** kwargs ) : """Write an JSON object on a single line . The keyword arguments are interpreted as a single JSON object . It ' s not possible with this method to write non - objects ."""
self . stdout . write ( json . dumps ( kwargs ) + "\n" ) self . stdout . flush ( )
def get_files ( self ) : """stub"""
files_map = { } try : files_map [ 'choices' ] = self . get_choices_file_urls_map ( ) try : files_map . update ( self . get_file_urls_map ( ) ) except IllegalState : pass except Exception : files_map [ 'choices' ] = self . get_choices_files_map ( ) try : files_map . update ( s...
def xdg_config_dir ( ) : '''Check xdg locations for config files'''
xdg_config = os . getenv ( 'XDG_CONFIG_HOME' , os . path . expanduser ( '~/.config' ) ) xdg_config_directory = os . path . join ( xdg_config , 'salt' ) return xdg_config_directory
def collect_results ( rule , max_results = 500 , result_stream_args = None ) : """Utility function to quickly get a list of tweets from a ` ` ResultStream ` ` without keeping the object around . Requires your args to be configured prior to using . Args : rule ( str ) : valid powertrack rule for your account...
if result_stream_args is None : logger . error ( "This function requires a configuration dict for the " "inner ResultStream object." ) raise KeyError rs = ResultStream ( rule_payload = rule , max_results = max_results , ** result_stream_args ) return list ( rs . stream ( ) )
def create_keypair ( kwargs = None , call = None ) : '''Create an SSH keypair'''
if call != 'function' : log . error ( 'The create_keypair function must be called with -f or --function.' ) return False if not kwargs : kwargs = { } if 'keyname' not in kwargs : log . error ( 'A keyname is required.' ) return False params = { 'Action' : 'CreateKeyPair' , 'KeyName' : kwargs [ 'keyna...
def prep ( link ) : '''Prepare a statement into a triple ready for rdflib'''
s , p , o = link [ : 3 ] s = URIRef ( s ) p = URIRef ( p ) o = URIRef ( o ) if isinstance ( o , I ) else Literal ( o ) return s , p , o
def _getLocalWhen ( self , date_from , num_days = 1 ) : """Returns a string describing when the event occurs ( in the local time zone ) ."""
dateFrom , timeFrom = getLocalDateAndTime ( date_from , self . time_from , self . tz , dt . time . min ) if num_days > 1 or self . time_to is not None : daysDelta = dt . timedelta ( days = self . num_days - 1 ) dateTo , timeTo = getLocalDateAndTime ( date_from + daysDelta , self . time_to , self . tz ) else : ...
def _load_lib ( ) : """Load libary by searching possible path ."""
lib_path = _find_lib_path ( ) lib = ctypes . cdll . LoadLibrary ( lib_path [ 0 ] ) # DMatrix functions lib . MXGetLastError . restype = ctypes . c_char_p return lib
def parse_octal ( self , text , i ) : """Parse octal value ."""
value = int ( text , 8 ) if value > 0xFF and self . is_bytes : # Re fails on octal greater than ` 0o377 ` or ` 0xFF ` raise ValueError ( "octal escape value outside of range 0-0o377!" ) else : single = self . get_single_stack ( ) if self . span_stack : text = self . convert_case ( chr ( value ) , se...
def summary ( ) : """Summarize the participants ' status codes ."""
exp = Experiment ( session ) state = { "status" : "success" , "summary" : exp . log_summary ( ) , "completed" : exp . is_complete ( ) , } unfilled_nets = ( models . Network . query . filter ( models . Network . full != true ( ) ) . with_entities ( models . Network . id , models . Network . max_size ) . all ( ) ) workin...