idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
21,900 | def code ( self , value ) : if value not in list ( defines . Codes . LIST . keys ( ) ) and value is not None : raise AttributeError self . _code = value | Set the code of the message . |
21,901 | def acknowledged ( self , value ) : assert ( isinstance ( value , bool ) ) self . _acknowledged = value if value : self . _timeouted = False self . _rejected = False self . _cancelled = False | Marks this message as acknowledged . |
21,902 | def rejected ( self , value ) : assert ( isinstance ( value , bool ) ) self . _rejected = value if value : self . _timeouted = False self . _acknowledged = False self . _cancelled = True | Marks this message as rejected . |
21,903 | def _already_in ( self , option ) : for opt in self . _options : if option . number == opt . number : return True return False | Check if an option is already in the message . |
21,904 | def add_option ( self , option ) : assert isinstance ( option , Option ) repeatable = defines . OptionRegistry . LIST [ option . number ] . repeatable if not repeatable : ret = self . _already_in ( option ) if ret : raise TypeError ( "Option : %s is not repeatable" , option . name ) else : self . _options . append ( op... | Add an option to the message . |
21,905 | def del_option ( self , option ) : assert isinstance ( option , Option ) while option in list ( self . _options ) : self . _options . remove ( option ) | Delete an option from the message |
21,906 | def del_option_by_name ( self , name ) : for o in list ( self . _options ) : assert isinstance ( o , Option ) if o . name == name : self . _options . remove ( o ) | Delete an option from the message by name |
21,907 | def del_option_by_number ( self , number ) : for o in list ( self . _options ) : assert isinstance ( o , Option ) if o . number == number : self . _options . remove ( o ) | Delete an option from the message by number |
21,908 | def etag ( self ) : value = [ ] for option in self . options : if option . number == defines . OptionRegistry . ETAG . number : value . append ( option . value ) return value | Get the ETag option of the message . |
21,909 | def etag ( self , etag ) : if not isinstance ( etag , list ) : etag = [ etag ] for e in etag : option = Option ( ) option . number = defines . OptionRegistry . ETAG . number if not isinstance ( e , bytes ) : e = bytes ( e , "utf-8" ) option . value = e self . add_option ( option ) | Add an ETag option to the message . |
21,910 | def content_type ( self ) : value = 0 for option in self . options : if option . number == defines . OptionRegistry . CONTENT_TYPE . number : value = int ( option . value ) return value | Get the Content - Type option of a response . |
21,911 | def content_type ( self , content_type ) : option = Option ( ) option . number = defines . OptionRegistry . CONTENT_TYPE . number option . value = int ( content_type ) self . add_option ( option ) | Set the Content - Type option of a response . |
21,912 | def observe ( self ) : for option in self . options : if option . number == defines . OptionRegistry . OBSERVE . number : if option . value is None : return 0 return option . value return None | Check if the request is an observing request . |
21,913 | def observe ( self , ob ) : option = Option ( ) option . number = defines . OptionRegistry . OBSERVE . number option . value = ob self . del_option_by_number ( defines . OptionRegistry . OBSERVE . number ) self . add_option ( option ) | Add the Observe option . |
21,914 | def block1 ( self ) : value = None for option in self . options : if option . number == defines . OptionRegistry . BLOCK1 . number : value = parse_blockwise ( option . value ) return value | Get the Block1 option . |
21,915 | def block1 ( self , value ) : option = Option ( ) option . number = defines . OptionRegistry . BLOCK1 . number num , m , size = value if size > 512 : szx = 6 elif 256 < size <= 512 : szx = 5 elif 128 < size <= 256 : szx = 4 elif 64 < size <= 128 : szx = 3 elif 32 < size <= 64 : szx = 2 elif 16 < size <= 32 : szx = 1 el... | Set the Block1 option . |
21,916 | def block2 ( self ) : value = None for option in self . options : if option . number == defines . OptionRegistry . BLOCK2 . number : value = parse_blockwise ( option . value ) return value | Get the Block2 option . |
21,917 | def block2 ( self , value ) : option = Option ( ) option . number = defines . OptionRegistry . BLOCK2 . number num , m , size = value if size > 512 : szx = 6 elif 256 < size <= 512 : szx = 5 elif 128 < size <= 256 : szx = 4 elif 64 < size <= 128 : szx = 3 elif 32 < size <= 64 : szx = 2 elif 16 < size <= 32 : szx = 1 el... | Set the Block2 option . |
21,918 | def line_print ( self ) : inv_types = { v : k for k , v in defines . Types . items ( ) } if self . _code is None : self . _code = defines . Codes . EMPTY . number msg = "From {source}, To {destination}, {type}-{mid}, {code}-{token}, [" . format ( source = self . _source , destination = self . _destination , type = inv_... | Return the message as a one - line string . |
21,919 | def pretty_print ( self ) : msg = "Source: " + str ( self . _source ) + "\n" msg += "Destination: " + str ( self . _destination ) + "\n" inv_types = { v : k for k , v in defines . Types . items ( ) } msg += "Type: " + str ( inv_types [ self . _type ] ) + "\n" msg += "MID: " + str ( self . _mid ) + "\n" if self . _code ... | Return the message as a formatted string . |
21,920 | def interp_box ( x , y , z , box , values ) : val = 0 norm = 0 for i in range ( 8 ) : distance = sqrt ( ( x - box [ i , 0 ] ) ** 2 + ( y - box [ i , 1 ] ) ** 2 + ( z - box [ i , 2 ] ) ** 2 ) if distance == 0 : val = values [ i ] norm = 1. break w = 1. / distance val += w * values [ i ] norm += w return val / norm | box is 8x3 array though not really a box |
21,921 | def get_photometry ( self , brightest = False , min_unc = 0.02 , convert = True ) : if brightest : row = self . brightest else : row = self . closest if not hasattr ( self , 'conversions' ) : convert = False if convert : bands = self . conversions else : bands = self . bands . keys ( ) d = { } for b in bands : if conve... | Returns dictionary of photometry of closest match |
21,922 | def get_ichrone ( models , bands = None , default = False , ** kwargs ) : if isinstance ( models , Isochrone ) : return models def actual ( bands , ictype ) : if bands is None : return list ( ictype . default_bands ) elif default : return list ( set ( bands ) . union ( set ( ictype . default_bands ) ) ) else : return b... | Gets Isochrone Object by name or type with the right bands |
21,923 | def delta_nu ( self , * args ) : return 134.88 * np . sqrt ( self . mass ( * args ) / self . radius ( * args ) ** 3 ) | Returns asteroseismic delta_nu in uHz |
21,924 | def nu_max ( self , * args ) : return 3120. * ( self . mass ( * args ) / ( self . radius ( * args ) ** 2 * np . sqrt ( self . Teff ( * args ) / 5777. ) ) ) | Returns asteroseismic nu_max in uHz |
21,925 | def agerange ( self , m , feh = 0.0 ) : ages = np . arange ( self . minage , self . maxage , 0.01 ) rs = self . radius ( m , ages , feh ) w = np . where ( np . isfinite ( rs ) ) [ 0 ] return ages [ w [ 0 ] ] , ages [ w [ - 1 ] ] | For a given mass and feh returns the min and max allowed ages . |
21,926 | def evtrack ( self , m , feh = 0.0 , minage = None , maxage = None , dage = 0.02 , return_df = True ) : if minage is None : minage = self . minage if maxage is None : maxage = self . maxage ages = np . arange ( minage , maxage , dage ) Ms = self . mass ( m , ages , feh ) Rs = self . radius ( m , ages , feh ) logLs = se... | Returns evolution track for a single initial mass and feh . |
21,927 | def isochrone ( self , age , feh = 0.0 , minm = None , maxm = None , dm = 0.02 , return_df = True , distance = None , AV = 0.0 ) : if minm is None : minm = self . minmass if maxm is None : maxm = self . maxmass ms = np . arange ( minm , maxm , dm ) ages = np . ones ( ms . shape ) * age Ms = self . mass ( ms , ages , fe... | Returns stellar models at constant age and feh for a range of masses |
21,928 | def random_points ( self , n , minmass = None , maxmass = None , minage = None , maxage = None , minfeh = None , maxfeh = None ) : if minmass is None : minmass = self . minmass if maxmass is None : maxmass = self . maxmass if minage is None : minage = self . minage if maxage is None : maxage = self . maxage if minfeh i... | Returns n random mass age feh points none of which are out of range . |
21,929 | def _parse_band ( cls , kw ) : m = re . search ( '([a-zA-Z0-9]+)(_\d+)?' , kw ) if m : if m . group ( 1 ) in cls . _not_a_band : return None else : return m . group ( 1 ) | Returns photometric band from inifile keyword |
21,930 | def _build_obs ( self , ** kwargs ) : logging . debug ( 'Building ObservationTree...' ) tree = ObservationTree ( ) for k , v in kwargs . items ( ) : if k in self . ic . bands : if np . size ( v ) != 2 : logging . warning ( '{}={} ignored.' . format ( k , v ) ) v = [ v , np . nan ] o = Observation ( '' , k , 99 ) s = So... | Builds ObservationTree out of keyword arguments |
21,931 | def _add_properties ( self , ** kwargs ) : for k , v in kwargs . items ( ) : if k == 'parallax' : self . obs . add_parallax ( v ) elif k in [ 'Teff' , 'logg' , 'feh' , 'density' ] : par = { k : v } self . obs . add_spectroscopy ( ** par ) elif re . search ( '_' , k ) : m = re . search ( '^(\w+)_(\w+)$' , k ) prop = m .... | Adds non - photometry properties to ObservationTree |
21,932 | def mnest_basename ( self ) : if not hasattr ( self , '_mnest_basename' ) : s = self . labelstring if s == '0_0' : s = 'single' elif s == '0_0-0_1' : s = 'binary' elif s == '0_0-0_1-0_2' : s = 'triple' s = '{}-{}' . format ( self . ic . name , s ) self . _mnest_basename = os . path . join ( 'chains' , s + '-' ) if os .... | Full path to basename |
21,933 | def samples ( self ) : if not hasattr ( self , 'sampler' ) and self . _samples is None : raise AttributeError ( 'Must run MCMC (or load from file) ' + 'before accessing samples' ) if self . _samples is not None : df = self . _samples else : self . _make_samples ( ) df = self . _samples return df | Dataframe with samples drawn from isochrone according to posterior |
21,934 | def random_samples ( self , n ) : samples = self . samples inds = rand . randint ( len ( samples ) , size = int ( n ) ) newsamples = samples . iloc [ inds ] newsamples . reset_index ( inplace = True ) return newsamples | Returns a random sampling of given size from the existing samples . |
21,935 | def corner_observed ( self , ** kwargs ) : tot_mags = [ ] names = [ ] truths = [ ] rng = [ ] for n in self . obs . get_obs_nodes ( ) : labels = [ l . label for l in n . get_model_nodes ( ) ] band = n . band mags = [ self . samples [ '{}_mag_{}' . format ( band , l ) ] for l in labels ] tot_mag = addmags ( * mags ) if n... | Makes corner plot for each observed node magnitude |
21,936 | def _get_df ( self ) : grids = { } df = pd . DataFrame ( ) for bnd in self . bands : s , b = self . get_band ( bnd , ** self . kwargs ) logging . debug ( 'loading {} band from {}' . format ( b , s ) ) if s not in grids : grids [ s ] = self . get_hdf ( s ) if self . common_columns [ 0 ] not in df : df [ list ( self . co... | Returns stellar model grid with desired bandpasses and with standard column names |
21,937 | def extract_master_tarball ( cls ) : if not os . path . exists ( cls . master_tarball_file ) : cls . download_grids ( ) with tarfile . open ( os . path . join ( ISOCHRONES , cls . master_tarball_file ) ) as tar : logging . info ( 'Extracting {}...' . format ( cls . master_tarball_file ) ) tar . extractall ( ISOCHRONES ... | Unpack tarball of tarballs |
21,938 | def df_all ( self , phot ) : df = pd . concat ( [ self . to_df ( f ) for f in self . get_filenames ( phot ) ] ) return df | Subclasses may want to sort this |
21,939 | def get_band ( cls , b , ** kwargs ) : phot = None if b in [ 'u' , 'g' , 'r' , 'i' , 'z' ] : phot = 'SDSS' band = 'SDSS_{}' . format ( b ) elif b in [ 'U' , 'B' , 'V' , 'R' , 'I' ] : phot = 'UBVRIplus' band = 'Bessell_{}' . format ( b ) elif b in [ 'J' , 'H' , 'Ks' ] : phot = 'UBVRIplus' band = '2MASS_{}' . format ( b ... | Defines what a shortcut band name refers to . Returns phot_system band |
21,940 | def remove_child ( self , label ) : ind = None for i , c in enumerate ( self . children ) : if c . label == label : ind = i if ind is None : logging . warning ( 'No child labeled {}.' . format ( label ) ) return self . children . pop ( ind ) self . _clear_all_leaves ( ) | Removes node by label |
21,941 | def select_leaves ( self , name ) : if self . is_leaf : return [ self ] if re . search ( name , self . label ) else [ ] else : leaves = [ ] if re . search ( name , self . label ) : for c in self . children : leaves += c . _get_leaves ( ) else : for c in self . children : leaves += c . select_leaves ( name ) return leav... | Returns all leaves under all nodes matching name |
21,942 | def get_obs_leaves ( self ) : obs_leaves = [ ] for n in self : if n . is_leaf : if isinstance ( n , ModelNode ) : l = n . parent else : l = n if l not in obs_leaves : obs_leaves . append ( l ) return obs_leaves | Returns the last obs nodes that are leaves |
21,943 | def distance ( self , other ) : return distance ( ( self . separation , self . pa ) , ( other . separation , other . pa ) ) | Coordinate distance from another ObsNode |
21,944 | def Nstars ( self ) : if self . _Nstars is None : N = { } for n in self . get_model_nodes ( ) : if n . index not in N : N [ n . index ] = 1 else : N [ n . index ] += 1 self . _Nstars = N return self . _Nstars | dictionary of number of stars per system |
21,945 | def add_model ( self , ic , N = 1 , index = 0 ) : if type ( index ) in [ list , tuple ] : if len ( index ) != N : raise ValueError ( 'If a list, index must be of length N.' ) else : index = [ index ] * N for idx in index : existing = self . get_system ( idx ) tag = len ( existing ) self . add_child ( ModelNode ( ic , i... | Should only be able to do this to a leaf node . |
21,946 | def model_mag ( self , pardict , use_cache = True ) : if pardict == self . _cache_key and use_cache : return self . _cache_val self . _cache_key = pardict p = [ ] for l in self . leaf_labels : p . extend ( pardict [ l ] ) assert len ( p ) == self . n_params tot = np . inf for i , m in enumerate ( self . leaves ) : mag ... | pardict is a dictionary of parameters for all leaves gets converted back to traditional parameter vector |
21,947 | def lnlike ( self , pardict , use_cache = True ) : mag , dmag = self . value if np . isnan ( dmag ) : return 0 if self . relative : if self . reference is None : return 0 mod = ( self . model_mag ( pardict , use_cache = use_cache ) - self . reference . model_mag ( pardict , use_cache = use_cache ) ) mag -= self . refer... | returns log - likelihood of this observation |
21,948 | def from_df ( cls , df , ** kwargs ) : tree = cls ( ** kwargs ) for ( n , b ) , g in df . groupby ( [ 'name' , 'band' ] ) : sources = [ Source ( ** s [ [ 'mag' , 'e_mag' , 'separation' , 'pa' , 'relative' ] ] ) for _ , s in g . iterrows ( ) ] obs = Observation ( n , b , g . resolution . mean ( ) , sources = sources , r... | DataFrame must have the right columns . |
21,949 | def to_df ( self ) : df = pd . DataFrame ( ) name = [ ] band = [ ] resolution = [ ] mag = [ ] e_mag = [ ] separation = [ ] pa = [ ] relative = [ ] for o in self . _observations : for s in o . sources : name . append ( o . name ) band . append ( o . band ) resolution . append ( o . resolution ) mag . append ( s . mag ) ... | Returns DataFrame with photometry from observations organized . |
21,950 | def save_hdf ( self , filename , path = '' , overwrite = False , append = False ) : if os . path . exists ( filename ) : store = pd . HDFStore ( filename ) if path in store : store . close ( ) if overwrite : os . remove ( filename ) elif not append : raise IOError ( '{} in {} exists. Set either overwrite or append opt... | Writes all info necessary to recreate object to HDF file |
21,951 | def load_hdf ( cls , filename , path = '' , ic = None ) : store = pd . HDFStore ( filename ) try : samples = store [ path + '/df' ] attrs = store . get_storer ( path + '/df' ) . attrs except : store . close ( ) raise df = store [ path + '/df' ] new = cls . from_df ( df ) if ic is None : ic = get_ichrone ( 'mist' ) new ... | Loads stored ObservationTree from file . |
21,952 | def add_observation ( self , obs ) : if len ( self . _observations ) == 0 : self . _observations . append ( obs ) else : res = obs . resolution ind = 0 for o in self . _observations : if res > o . resolution : break ind += 1 self . _observations . insert ( ind , obs ) self . _build_tree ( ) self . _clear_cache ( ) | Adds an observation to observation list keeping proper order |
21,953 | def add_limit ( self , label = '0_0' , ** props ) : if label not in self . leaf_labels : raise ValueError ( 'No model node named {} (must be in {}). Maybe define models first?' . format ( label , self . leaf_labels ) ) for k , v in props . items ( ) : if k not in self . spec_props : raise ValueError ( 'Illegal property... | Define limits to spectroscopic property of particular stars . |
21,954 | def define_models ( self , ic , leaves = None , N = 1 , index = 0 ) : self . clear_models ( ) if leaves is None : leaves = self . _get_leaves ( ) elif type ( leaves ) == type ( '' ) : leaves = self . select_leaves ( leaves ) if np . isscalar ( N ) : N = ( np . ones ( len ( leaves ) ) * N ) N = np . array ( N ) . astype... | N index are either integers or lists of integers . |
21,955 | def _fix_labels ( self ) : for s in self . systems : mag0 = np . inf n0 = None for n in self . get_system ( s ) : if isinstance ( n . parent , DummyObsNode ) : continue mag , _ = n . parent . value if mag < mag0 : mag0 = mag n0 = n if n0 is not None and n0 . tag != 0 : n_other = self . get_leaf ( '{}_{}' . format ( s ,... | For each system make sure tag _0 is the brightest and make sure system 0 contains the brightest star in the highest - resolution image |
21,956 | def select_observations ( self , name ) : return [ n for n in self . get_obs_nodes ( ) if n . obsname == name ] | Returns nodes whose instrument - band matches name |
21,957 | def trim ( self ) : return for l in self . _levels [ - 2 : : - 1 ] : for n in l : if n . is_leaf : n . parent . remove_child ( n . label ) self . _clear_all_leaves ( ) | Trims leaves from tree that are not observed at highest - resolution level |
21,958 | def p2pardict ( self , p ) : d = { } N = self . Nstars i = 0 for s in self . systems : age , feh , dist , AV = p [ i + N [ s ] : i + N [ s ] + 4 ] for j in xrange ( N [ s ] ) : l = '{}_{}' . format ( s , j ) mass = p [ i + j ] d [ l ] = [ mass , age , feh , dist , AV ] i += N [ s ] + 4 return d | Given leaf labels turns parameter vector into pardict |
21,959 | def lnlike ( self , p , use_cache = True ) : if use_cache and self . _cache_key is not None and np . all ( p == self . _cache_key ) : return self . _cache_val self . _cache_key = p pardict = self . p2pardict ( p ) lnl = 0 for n in self : if n is not self : lnl += n . lnlike ( pardict , use_cache = use_cache ) if not np... | takes parameter vector constructs pardict returns sum of lnlikes of non - leaf nodes |
21,960 | def _find_closest ( self , n0 ) : dmin = np . inf nclose = None ds = [ ] nodes = [ ] ds . append ( np . inf ) nodes . append ( self ) for n in self : if n is n0 : continue try : if n . _in_same_observation ( n0 ) : continue ds . append ( n . distance ( n0 ) ) nodes . append ( n ) except AttributeError : pass inds = np ... | returns the node in the tree that is closest to n0 but not in the same observation |
21,961 | def q_prior ( q , m = 1 , gamma = 0.3 , qmin = 0.1 ) : if q < qmin or q > 1 : return 0 C = 1 / ( 1 / ( gamma + 1 ) * ( 1 - qmin ** ( gamma + 1 ) ) ) return C * q ** gamma | Default prior on mass ratio q ~ q^gamma |
21,962 | def _clean_props ( self ) : remove = [ ] for p in self . properties . keys ( ) : if not hasattr ( self . ic , p ) and p not in self . ic . bands and p not in [ 'parallax' , 'feh' , 'age' , 'mass_B' , 'mass_C' ] and not re . search ( 'delta_' , p ) : remove . append ( p ) for p in remove : del self . properties [ p ] if... | Makes sure all properties are legit for isochrone . |
21,963 | def add_props ( self , ** kwargs ) : for kw , val in kwargs . iteritems ( ) : self . properties [ kw ] = val | Adds observable properties to self . properties . |
21,964 | def remove_props ( self , * args ) : for arg in args : if arg in self . properties : del self . properties [ arg ] | Removes desired properties from self . properties . |
21,965 | def fit_for_distance ( self ) : for prop in self . properties . keys ( ) : if prop in self . ic . bands : return True return False | True if any of the properties are apparent magnitudes . |
21,966 | def lnlike ( self , p ) : if not self . _props_cleaned : self . _clean_props ( ) if not self . use_emcee : fit_for_distance = True mass , age , feh , dist , AV = ( p [ 0 ] , p [ 1 ] , p [ 2 ] , p [ 3 ] , p [ 4 ] ) else : if len ( p ) == 5 : fit_for_distance = True mass , age , feh , dist , AV = p elif len ( p ) == 3 : ... | Log - likelihood of model at given parameters |
21,967 | def lnprior ( self , mass , age , feh , distance = None , AV = None , use_local_fehprior = True ) : mass_prior = salpeter_prior ( mass ) if mass_prior == 0 : mass_lnprior = - np . inf else : mass_lnprior = np . log ( mass_prior ) if np . isnan ( mass_lnprior ) : logging . warning ( 'mass prior is nan at {}' . format ( ... | log - prior for model parameters |
21,968 | def triangle_plots ( self , basename = None , format = 'png' , ** kwargs ) : if self . fit_for_distance : fig1 = self . triangle ( plot_datapoints = False , params = [ 'mass' , 'radius' , 'Teff' , 'logg' , 'feh' , 'age' , 'distance' , 'AV' ] , ** kwargs ) else : fig1 = self . triangle ( plot_datapoints = False , params... | Returns two triangle plots one with physical params one observational |
21,969 | def prop_triangle ( self , ** kwargs ) : truths = [ ] params = [ ] for p in self . properties : try : val , err = self . properties [ p ] except : continue if p in self . ic . bands : params . append ( '{}_mag' . format ( p ) ) truths . append ( val ) elif p == 'parallax' : params . append ( 'distance' ) truths . appen... | Makes corner plot of only observable properties . |
21,970 | def prop_samples ( self , prop , return_values = True , conf = 0.683 ) : samples = self . samples [ prop ] . values if return_values : sorted = np . sort ( samples ) med = np . median ( samples ) n = len ( samples ) lo_ind = int ( n * ( 0.5 - conf / 2 ) ) hi_ind = int ( n * ( 0.5 + conf / 2 ) ) lo = med - sorted [ lo_i... | Returns samples of given property based on MCMC sampling |
21,971 | def plot_samples ( self , prop , fig = None , label = True , histtype = 'step' , bins = 50 , lw = 3 , ** kwargs ) : setfig ( fig ) samples , stats = self . prop_samples ( prop ) fig = plt . hist ( samples , bins = bins , normed = True , histtype = histtype , lw = lw , ** kwargs ) plt . xlabel ( prop ) plt . ylabel ( 'N... | Plots histogram of samples of desired property . |
21,972 | def get_band ( cls , b , ** kwargs ) : phot = None if b in [ 'u' , 'g' , 'r' , 'i' , 'z' ] : phot = 'SDSSugriz' band = 'sdss_{}' . format ( b ) elif b in [ 'U' , 'B' , 'V' , 'R' , 'I' , 'J' , 'H' , 'Ks' ] : phot = 'UBVRIJHKsKp' band = b elif b == 'K' : phot = 'UBVRIJHKsKp' band = 'Ks' elif b in [ 'kep' , 'Kepler' , 'Kp... | Defines what a shortcut band name refers to . |
21,973 | def searchsorted ( arr , N , x ) : L = 0 R = N - 1 done = False m = ( L + R ) // 2 while not done : if arr [ m ] < x : L = m + 1 elif arr [ m ] > x : R = m - 1 elif arr [ m ] == x : done = True m = ( L + R ) // 2 if L > R : done = True return L | N is length of arr |
21,974 | def wrap_flask_restful_resource ( fun : Callable , flask_restful_api : FlaskRestfulApi , injector : Injector ) -> Callable : @ functools . wraps ( fun ) def wrapper ( * args : Any , ** kwargs : Any ) -> Any : resp = fun ( * args , ** kwargs ) if isinstance ( resp , Response ) : return resp data , code , headers = flask... | This is needed because of how flask_restful views are registered originally . |
21,975 | def complete_url ( self , url ) : if self . base_url : return urlparse . urljoin ( self . base_url , url ) else : return url | Completes a given URL with this instance s URL base . |
21,976 | def interact ( self , ** local ) : import code code . interact ( local = dict ( sess = self , ** local ) ) | Drops the user into an interactive Python session with the sess variable set to the current session instance . If keyword arguments are supplied these names will also be available within the session . |
21,977 | def wait_for ( self , condition , interval = DEFAULT_WAIT_INTERVAL , timeout = DEFAULT_WAIT_TIMEOUT ) : start = time . time ( ) while True : res = condition ( ) if res : return res if time . time ( ) - start > timeout : break time . sleep ( interval ) raise WaitTimeoutError ( "wait_for timed out" ) | Wait until a condition holds by checking it in regular intervals . Raises WaitTimeoutError on timeout . |
21,978 | def wait_while ( self , condition , * args , ** kw ) : return self . wait_for ( lambda : not condition ( ) , * args , ** kw ) | Wait while a condition holds . |
21,979 | def at_css ( self , css , timeout = DEFAULT_AT_TIMEOUT , ** kw ) : return self . wait_for_safe ( lambda : super ( WaitMixin , self ) . at_css ( css ) , timeout = timeout , ** kw ) | Returns the first node matching the given CSSv3 expression or None if a timeout occurs . |
21,980 | def at_xpath ( self , xpath , timeout = DEFAULT_AT_TIMEOUT , ** kw ) : return self . wait_for_safe ( lambda : super ( WaitMixin , self ) . at_xpath ( xpath ) , timeout = timeout , ** kw ) | Returns the first node matching the given XPath 2 . 0 expression or None if a timeout occurs . |
21,981 | def switch_axis_limits ( ax , which_axis ) : for a in which_axis : assert a in ( 'x' , 'y' ) ax_limits = ax . axis ( ) if a == 'x' : ax . set_xlim ( ax_limits [ 1 ] , ax_limits [ 0 ] ) else : ax . set_ylim ( ax_limits [ 3 ] , ax_limits [ 2 ] ) | Switch the axis limits of either x or y . Or both! |
21,982 | def remove_chartjunk ( ax , spines , grid = None , ticklabels = None , show_ticks = False , xkcd = False ) : all_spines = [ 'top' , 'bottom' , 'right' , 'left' , 'polar' ] for spine in spines : try : ax . spines [ spine ] . set_visible ( False ) except KeyError : pass if not xkcd : for spine in set ( all_spines ) . dif... | Removes chartjunk such as extra lines of axes and tick marks . |
21,983 | def maybe_get_ax ( * args , ** kwargs ) : if 'ax' in kwargs : ax = kwargs . pop ( 'ax' ) elif len ( args ) == 0 : fig = plt . gcf ( ) ax = plt . gca ( ) elif isinstance ( args [ 0 ] , mpl . axes . Axes ) : ax = args [ 0 ] args = args [ 1 : ] else : ax = plt . gca ( ) return ax , args , dict ( kwargs ) | It used to be that the first argument of prettyplotlib had to be the ax object but that s not the case anymore . |
21,984 | def maybe_get_fig_ax ( * args , ** kwargs ) : if 'ax' in kwargs : ax = kwargs . pop ( 'ax' ) if 'fig' in kwargs : fig = kwargs . pop ( 'fig' ) else : fig = plt . gcf ( ) elif len ( args ) == 0 : fig = plt . gcf ( ) ax = plt . gca ( ) elif isinstance ( args [ 0 ] , mpl . figure . Figure ) and isinstance ( args [ 1 ] , m... | It used to be that the first argument of prettyplotlib had to be the ax object but that s not the case anymore . This is specially made for pcolormesh . |
21,985 | def scatter ( * args , ** kwargs ) : ax , args , kwargs = utils . maybe_get_ax ( * args , ** kwargs ) if 'color' not in kwargs : color_cycle = ax . _get_lines . color_cycle kwargs [ 'color' ] = next ( color_cycle ) kwargs . setdefault ( 'edgecolor' , almost_black ) kwargs . setdefault ( 'alpha' , 0.5 ) lw = utils . may... | This will plot a scatterplot of x and y iterating over the ColorBrewer Set2 color cycle unless a color is specified . The symbols produced are empty circles with the outline in the color specified by either color or edgecolor . If you want to fill the circle specify facecolor . |
21,986 | def boxplot ( * args , ** kwargs ) : ax , args , kwargs = maybe_get_ax ( * args , ** kwargs ) xticklabels = kwargs . pop ( 'xticklabels' , None ) fontsize = kwargs . pop ( 'fontsize' , 10 ) kwargs . setdefault ( 'widths' , 0.15 ) bp = ax . boxplot ( * args , ** kwargs ) if xticklabels : ax . xaxis . set_ticklabels ( xt... | Create a box - and - whisker plot showing the mean 25th percentile and 75th percentile . The difference from matplotlib is only the left axis line is shown and ticklabels labeling each category of data can be added . |
21,987 | def hist ( * args , ** kwargs ) : ax , args , kwargs = maybe_get_ax ( * args , ** kwargs ) color_cycle = ax . _get_lines . color_cycle if iterable ( args [ 0 ] ) : if isinstance ( args [ 0 ] , list ) : ncolors = len ( args [ 0 ] ) else : if len ( args [ 0 ] . shape ) == 2 : ncolors = args [ 0 ] . shape [ 1 ] else : nco... | Plots a histogram of the provided data . Can provide optional argument grid = x or grid = y to draw a white grid over the histogram . Almost like erasing some of the plot but it adds more information! |
21,988 | def beeswarm ( * args , ** kwargs ) : ax , args , kwargs = maybe_get_ax ( * args , ** kwargs ) xticklabels = kwargs . pop ( 'xticklabels' , None ) colors = kwargs . pop ( 'colors' , None ) fontsize = kwargs . pop ( 'fontsize' , 10 ) gray = _colors . set1 [ 8 ] red = _colors . set1 [ 0 ] blue = kwargs . pop ( 'color' , ... | Create a R - like beeswarm plot showing the mean and datapoints . The difference from matplotlib is only the left axis line is shown and ticklabels labeling each category of data can be added . |
21,989 | def tags ( self ) : if self . _tags is None : LOG . debug ( 'need to build tags' ) self . _tags = { } if hasattr ( self . Meta , 'tags_spec' ) and ( self . Meta . tags_spec is not None ) : LOG . debug ( 'have a tags_spec' ) method , path , param_name , param_value = self . Meta . tags_spec [ : 4 ] kwargs = { } filter_t... | Convert the ugly Tags JSON into a real dictionary and memorize the result . |
21,990 | def get_metric_data ( self , metric_name = None , metric = None , days = None , hours = 1 , minutes = None , statistics = None , period = None ) : if not statistics : statistics = [ 'Average' ] if days : delta = datetime . timedelta ( days = days ) elif hours : delta = datetime . timedelta ( hours = hours ) else : delt... | Get metric data for this resource . You can specify the time frame for the data as either the number of days or number of hours . The maximum window is 14 days . Based on the time frame this method will calculate the correct period to return the maximum number of data points up to the CloudWatch max of 1440 . |
21,991 | def fit ( self ) : r for distribution in self . distributions : try : dist = eval ( "scipy.stats." + distribution ) param = self . _timed_run ( dist . fit , distribution , args = self . _data ) pdf_fitted = dist . pdf ( self . x , * param ) self . fitted_param [ distribution ] = param [ : ] self . fitted_pdf [ distribu... | r Loop over distributions and find best parameter to fit the data for each |
21,992 | def plot_pdf ( self , names = None , Nbest = 5 , lw = 2 ) : assert Nbest > 0 if Nbest > len ( self . distributions ) : Nbest = len ( self . distributions ) if isinstance ( names , list ) : for name in names : pylab . plot ( self . x , self . fitted_pdf [ name ] , lw = lw , label = name ) elif names : pylab . plot ( sel... | Plots Probability density functions of the distributions |
21,993 | def get_best ( self ) : name = self . df_errors . sort_values ( 'sumsquare_error' ) . iloc [ 0 ] . name params = self . fitted_param [ name ] return { name : params } | Return best fitted distribution and its parameters |
21,994 | def summary ( self , Nbest = 5 , lw = 2 , plot = True ) : if plot : pylab . clf ( ) self . hist ( ) self . plot_pdf ( Nbest = Nbest , lw = lw ) pylab . grid ( True ) Nbest = min ( Nbest , len ( self . distributions ) ) try : names = self . df_errors . sort_values ( by = "sumsquare_error" ) . index [ 0 : Nbest ] except ... | Plots the distribution of the data and Nbest distribution |
21,995 | def _timed_run ( self , func , distribution , args = ( ) , kwargs = { } , default = None ) : class InterruptableThread ( threading . Thread ) : def __init__ ( self ) : threading . Thread . __init__ ( self ) self . result = default self . exc_info = ( None , None , None ) def run ( self ) : try : self . result = func ( ... | This function will spawn a thread and run the given function using the args kwargs and return the given default value if the timeout is exceeded . |
21,996 | def compute_avg_adj_deg ( G ) : r return np . sum ( np . dot ( G . A , G . A ) , axis = 1 ) / ( np . sum ( G . A , axis = 1 ) + 1. ) | r Compute the average adjacency degree for each node . |
21,997 | def compute_spectrogram ( G , atom = None , M = 100 , ** kwargs ) : r if not atom : def atom ( x ) : return np . exp ( - M * ( x / G . lmax ) ** 2 ) scale = np . linspace ( 0 , G . lmax , M ) spectr = np . empty ( ( G . N , M ) ) for shift_idx in range ( M ) : shift_filter = filters . Filter ( G , lambda x : atom ( x -... | r Compute the norm of the Tig for all nodes with a kernel shifted along the spectral axis . |
21,998 | def evaluate ( self , x ) : r x = np . asanyarray ( x ) y = np . empty ( [ self . Nf ] + list ( x . shape ) ) for i , kernel in enumerate ( self . _kernels ) : y [ i ] = kernel ( x ) return y | r Evaluate the kernels at given frequencies . |
21,999 | def estimate_frame_bounds ( self , x = None ) : r if x is None : x = np . linspace ( 0 , self . G . lmax , 1000 ) else : x = np . asanyarray ( x ) sum_filters = np . sum ( self . evaluate ( x ) ** 2 , axis = 0 ) return sum_filters . min ( ) , sum_filters . max ( ) | r Estimate lower and upper frame bounds . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.