idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
248,300
def numpy_binning ( data , bins = 10 , range = None , * args , * * kwargs ) -> NumpyBinning : if isinstance ( bins , int ) : if range : bins = np . linspace ( range [ 0 ] , range [ 1 ] , bins + 1 ) else : start = data . min ( ) stop = data . max ( ) bins = np . linspace ( start , stop , bins + 1 ) elif np . iterable ( bins ) : bins = np . asarray ( bins ) else : # Some numpy edge case _ , bins = np . histogram ( data , bins , * * kwargs ) return NumpyBinning ( bins )
Construct binning schema compatible with numpy . histogram
152
11
248,301
def human_binning ( data = None , bin_count : Optional [ int ] = None , * , range = None , * * kwargs ) -> FixedWidthBinning : subscales = np . array ( [ 0.5 , 1 , 2 , 2.5 , 5 , 10 ] ) # TODO: remove colliding kwargs if data is None and range is None : raise RuntimeError ( "Cannot guess optimum bin width without data." ) if bin_count is None : bin_count = ideal_bin_count ( data ) min_ = range [ 0 ] if range else data . min ( ) max_ = range [ 1 ] if range else data . max ( ) bw = ( max_ - min_ ) / bin_count power = np . floor ( np . log10 ( bw ) ) . astype ( int ) best_index = np . argmin ( np . abs ( np . log ( subscales * ( 10.0 ** power ) / bw ) ) ) bin_width = ( 10.0 ** power ) * subscales [ best_index ] return fixed_width_binning ( bin_width = bin_width , data = data , range = range , * * kwargs )
Construct fixed - width ninning schema with bins automatically optimized to human - friendly widths .
264
18
248,302
def quantile_binning ( data = None , bins = 10 , * , qrange = ( 0.0 , 1.0 ) , * * kwargs ) -> StaticBinning : if np . isscalar ( bins ) : bins = np . linspace ( qrange [ 0 ] * 100 , qrange [ 1 ] * 100 , bins + 1 ) bins = np . percentile ( data , bins ) return static_binning ( bins = make_bin_array ( bins ) , includes_right_edge = True )
Binning schema based on quantile ranges .
114
9
248,303
def static_binning ( data = None , bins = None , * * kwargs ) -> StaticBinning : return StaticBinning ( bins = make_bin_array ( bins ) , * * kwargs )
Construct static binning with whatever bins .
47
8
248,304
def integer_binning ( data = None , * * kwargs ) -> StaticBinning : if "range" in kwargs : kwargs [ "range" ] = tuple ( r - 0.5 for r in kwargs [ "range" ] ) return fixed_width_binning ( data = data , bin_width = kwargs . pop ( "bin_width" , 1 ) , align = True , bin_shift = 0.5 , * * kwargs )
Construct fixed - width binning schema with bins centered around integers .
107
13
248,305
def fixed_width_binning ( data = None , bin_width : Union [ float , int ] = 1 , * , range = None , includes_right_edge = False , * * kwargs ) -> FixedWidthBinning : result = FixedWidthBinning ( bin_width = bin_width , includes_right_edge = includes_right_edge , * * kwargs ) if range : result . _force_bin_existence ( range [ 0 ] ) result . _force_bin_existence ( range [ 1 ] , includes_right_edge = True ) if not kwargs . get ( "adaptive" ) : return result # Otherwise we want to adapt to data if data is not None and data . shape [ 0 ] : # print("Jo, tady") result . _force_bin_existence ( [ np . min ( data ) , np . max ( data ) ] , includes_right_edge = includes_right_edge ) return result
Construct fixed - width binning schema .
207
8
248,306
def exponential_binning ( data = None , bin_count : Optional [ int ] = None , * , range = None , * * kwargs ) -> ExponentialBinning : if bin_count is None : bin_count = ideal_bin_count ( data ) if range : range = ( np . log10 ( range [ 0 ] ) , np . log10 ( range [ 1 ] ) ) else : range = ( np . log10 ( data . min ( ) ) , np . log10 ( data . max ( ) ) ) log_width = ( range [ 1 ] - range [ 0 ] ) / bin_count return ExponentialBinning ( log_min = range [ 0 ] , log_width = log_width , bin_count = bin_count , * * kwargs )
Construct exponential binning schema .
171
6
248,307
def calculate_bins ( array , _ = None , * args , * * kwargs ) -> BinningBase : if array is not None : if kwargs . pop ( "check_nan" , True ) : if np . any ( np . isnan ( array ) ) : raise RuntimeError ( "Cannot calculate bins in presence of NaN's." ) if kwargs . get ( "range" , None ) : # TODO: re-consider the usage of this parameter array = array [ ( array >= kwargs [ "range" ] [ 0 ] ) & ( array <= kwargs [ "range" ] [ 1 ] ) ] if _ is None : bin_count = 10 # kwargs.pop("bins", ideal_bin_count(data=array)) - same as numpy binning = numpy_binning ( array , bin_count , * args , * * kwargs ) elif isinstance ( _ , BinningBase ) : binning = _ elif isinstance ( _ , int ) : binning = numpy_binning ( array , _ , * args , * * kwargs ) elif isinstance ( _ , str ) : # What about the ranges??? if _ in bincount_methods : bin_count = ideal_bin_count ( array , method = _ ) binning = numpy_binning ( array , bin_count , * args , * * kwargs ) elif _ in binning_methods : method = binning_methods [ _ ] binning = method ( array , * args , * * kwargs ) else : raise RuntimeError ( "No binning method {0} available." . format ( _ ) ) elif callable ( _ ) : binning = _ ( array , * args , * * kwargs ) elif np . iterable ( _ ) : binning = static_binning ( array , _ , * args , * * kwargs ) else : raise RuntimeError ( "Binning {0} not understood." . format ( _ ) ) return binning
Find optimal binning from arguments .
451
7
248,308
def ideal_bin_count ( data , method : str = "default" ) -> int : n = data . size if n < 1 : return 1 if method == "default" : if n <= 32 : return 7 else : return ideal_bin_count ( data , "sturges" ) elif method == "sqrt" : return int ( np . ceil ( np . sqrt ( n ) ) ) elif method == "sturges" : return int ( np . ceil ( np . log2 ( n ) ) + 1 ) elif method == "doane" : if n < 3 : return 1 from scipy . stats import skew sigma = np . sqrt ( 6 * ( n - 2 ) / ( n + 1 ) * ( n + 3 ) ) return int ( np . ceil ( 1 + np . log2 ( n ) + np . log2 ( 1 + np . abs ( skew ( data ) ) / sigma ) ) ) elif method == "rice" : return int ( np . ceil ( 2 * np . power ( n , 1 / 3 ) ) )
A theoretically ideal bin count .
240
6
248,309
def as_binning ( obj , copy : bool = False ) -> BinningBase : if isinstance ( obj , BinningBase ) : if copy : return obj . copy ( ) else : return obj else : bins = make_bin_array ( obj ) return StaticBinning ( bins )
Ensure that an object is a binning
62
9
248,310
def to_dict ( self ) -> OrderedDict : result = OrderedDict ( ) result [ "adaptive" ] = self . _adaptive result [ "binning_type" ] = type ( self ) . __name__ self . _update_dict ( result ) return result
Dictionary representation of the binning schema .
63
9
248,311
def is_regular ( self , rtol : float = 1.e-5 , atol : float = 1.e-8 ) -> bool : return np . allclose ( np . diff ( self . bins [ 1 ] - self . bins [ 0 ] ) , 0.0 , rtol = rtol , atol = atol )
Whether all bins have the same width .
76
8
248,312
def is_consecutive ( self , rtol : float = 1.e-5 , atol : float = 1.e-8 ) -> bool : if self . inconsecutive_allowed : if self . _consecutive is None : if self . _numpy_bins is not None : self . _consecutive = True self . _consecutive = is_consecutive ( self . bins , rtol , atol ) return self . _consecutive else : return True
Whether all bins are in a growing order .
110
9
248,313
def adapt ( self , other : 'BinningBase' ) : # TODO: in-place arg if np . array_equal ( self . bins , other . bins ) : return None , None elif not self . is_adaptive ( ) : raise RuntimeError ( "Cannot adapt non-adaptive binning." ) else : return self . _adapt ( other )
Adapt this binning so that it contains all bins of another binning .
80
15
248,314
def numpy_bins ( self ) -> np . ndarray : if self . _numpy_bins is None : self . _numpy_bins = to_numpy_bins ( self . bins ) return self . _numpy_bins
Bins in the numpy format
58
7
248,315
def numpy_bins_with_mask ( self ) -> Tuple [ np . ndarray , np . ndarray ] : bwm = to_numpy_bins_with_mask ( self . bins ) if not self . includes_right_edge : bwm [ 0 ] . append ( np . inf ) return bwm
Bins in the numpy format including the gaps in inconsecutive binnings .
74
18
248,316
def as_static ( self , copy : bool = True ) -> 'StaticBinning' : if copy : return StaticBinning ( bins = self . bins . copy ( ) , includes_right_edge = self . includes_right_edge ) else : return self
Convert binning to a static form .
56
9
248,317
def histogram1d ( data , bins = None , * args , * * kwargs ) : import dask if not hasattr ( data , "dask" ) : data = dask . array . from_array ( data , chunks = int ( data . shape [ 0 ] / options [ "chunk_split" ] ) ) if not kwargs . get ( "adaptive" , True ) : raise RuntimeError ( "Only adaptive histograms supported for dask (currently)." ) kwargs [ "adaptive" ] = True def block_hist ( array ) : return original_h1 ( array , bins , * args , * * kwargs ) return _run_dask ( name = "dask_adaptive1d" , data = data , compute = kwargs . pop ( "compute" , True ) , method = kwargs . pop ( "dask_method" , "threaded" ) , func = block_hist )
Facade function to create one - dimensional histogram using dask .
210
14
248,318
def histogram2d ( data1 , data2 , bins = None , * args , * * kwargs ) : # TODO: currently very unoptimized! for non-dasks import dask if "axis_names" not in kwargs : if hasattr ( data1 , "name" ) and hasattr ( data2 , "name" ) : kwargs [ "axis_names" ] = [ data1 . name , data2 . name ] if not hasattr ( data1 , "dask" ) : data1 = dask . array . from_array ( data1 , chunks = data1 . size ( ) / 100 ) if not hasattr ( data2 , "dask" ) : data2 = dask . array . from_array ( data2 , chunks = data2 . size ( ) / 100 ) data = dask . array . stack ( [ data1 , data2 ] , axis = 1 ) kwargs [ "dim" ] = 2 return histogramdd ( data , bins , * args , * * kwargs )
Facade function to create 2D histogram using dask .
230
13
248,319
def all_subclasses ( cls : type ) -> Tuple [ type , ... ] : subclasses = [ ] for subclass in cls . __subclasses__ ( ) : subclasses . append ( subclass ) subclasses . extend ( all_subclasses ( subclass ) ) return tuple ( subclasses )
All subclasses of a class .
64
7
248,320
def find_subclass ( base : type , name : str ) -> type : class_candidates = [ klass for klass in all_subclasses ( base ) if klass . __name__ == name ] if len ( class_candidates ) == 0 : raise RuntimeError ( "No \"{0}\" subclass of \"{1}\"." . format ( base . __name__ , name ) ) elif len ( class_candidates ) > 1 : raise RuntimeError ( "Multiple \"{0}\" subclasses of \"{1}\"." . format ( base . __name__ , name ) ) return class_candidates [ 0 ]
Find a named subclass of a base class .
140
9
248,321
def add ( self , histogram : Histogram1D ) : if self . binning and not self . binning == histogram . binning : raise ValueError ( "Cannot add histogram with different binning." ) self . histograms . append ( histogram )
Add a histogram to the collection .
58
8
248,322
def normalize_bins ( self , inplace : bool = False ) -> "HistogramCollection" : col = self if inplace else self . copy ( ) sums = self . sum ( ) . frequencies for h in col . histograms : h . set_dtype ( float ) h . _frequencies /= sums h . _errors2 /= sums ** 2 # TODO: Does this make sense? return col
Normalize each bin in the collection so that the sum is 1 . 0 for each bin .
91
19
248,323
def multi_h1 ( cls , a_dict : Dict [ str , Any ] , bins = None , * * kwargs ) -> "HistogramCollection" : from physt . binnings import calculate_bins mega_values = np . concatenate ( list ( a_dict . values ( ) ) ) binning = calculate_bins ( mega_values , bins , * * kwargs ) title = kwargs . pop ( "title" , None ) name = kwargs . pop ( "name" , None ) collection = HistogramCollection ( binning = binning , title = title , name = name ) for key , value in a_dict . items ( ) : collection . create ( key , value ) return collection
Create a collection from multiple datasets .
163
7
248,324
def to_json ( self , path : Optional [ str ] = None , * * kwargs ) -> str : from . io import save_json return save_json ( self , path , * * kwargs )
Convert to JSON representation .
47
6
248,325
def _get_axis ( self , name_or_index : AxisIdentifier ) -> int : # TODO: Add unit test if isinstance ( name_or_index , int ) : if name_or_index < 0 or name_or_index >= self . ndim : raise ValueError ( "No such axis, must be from 0 to {0}" . format ( self . ndim - 1 ) ) return name_or_index elif isinstance ( name_or_index , str ) : if name_or_index not in self . axis_names : named_axes = [ name for name in self . axis_names if name ] raise ValueError ( "No axis with such name: {0}, available names: {1}. In most places, you can also use numbers." . format ( name_or_index , ", " . join ( named_axes ) ) ) return self . axis_names . index ( name_or_index ) else : raise TypeError ( "Argument of type {0} not understood, int or str expected." . format ( type ( name_or_index ) ) )
Get a zero - based index of an axis and check its existence .
242
14
248,326
def shape ( self ) -> Tuple [ int , ... ] : return tuple ( bins . bin_count for bins in self . _binnings )
Shape of histogram s data .
32
7
248,327
def set_dtype ( self , value , check : bool = True ) : # TODO? Deal with unsigned types value , type_info = self . _eval_dtype ( value ) if value == self . _dtype : return if self . dtype is None or np . can_cast ( self . dtype , value ) : pass # Ok elif check : if np . issubdtype ( value , np . integer ) : if self . dtype . kind == "f" : for array in ( self . _frequencies , self . _errors2 ) : if np . any ( array % 1.0 ) : raise RuntimeError ( "Data contain non-integer values." ) for array in ( self . _frequencies , self . _errors2 ) : if np . any ( ( array > type_info . max ) | ( array < type_info . min ) ) : raise RuntimeError ( "Data contain values outside the specified range." ) self . _dtype = value self . _frequencies = self . _frequencies . astype ( value ) self . _errors2 = self . _errors2 . astype ( value ) self . _missed = self . _missed . astype ( value )
Change data type of the bin contents .
268
8
248,328
def _coerce_dtype ( self , other_dtype ) : if self . _dtype is None : new_dtype = np . dtype ( other_dtype ) else : new_dtype = np . find_common_type ( [ self . _dtype , np . dtype ( other_dtype ) ] , [ ] ) if new_dtype != self . dtype : self . set_dtype ( new_dtype )
Possibly change the bin content type to allow correct operations with other operand .
101
16
248,329
def normalize ( self , inplace : bool = False , percent : bool = False ) -> "HistogramBase" : if inplace : self /= self . total * ( .01 if percent else 1 ) return self else : return self / self . total * ( 100 if percent else 1 )
Normalize the histogram so that the total weight is equal to 1 .
63
15
248,330
def _change_binning ( self , new_binning , bin_map : Iterable [ Tuple [ int , int ] ] , axis : int = 0 ) : axis = int ( axis ) if axis < 0 or axis >= self . ndim : raise RuntimeError ( "Axis must be in range 0..(ndim-1)" ) self . _reshape_data ( new_binning . bin_count , bin_map , axis ) self . _binnings [ axis ] = new_binning
Set new binnning and update the bin contents according to a map .
112
15
248,331
def _reshape_data ( self , new_size , bin_map , axis = 0 ) : if bin_map is None : return else : new_shape = list ( self . shape ) new_shape [ axis ] = new_size new_frequencies = np . zeros ( new_shape , dtype = self . _frequencies . dtype ) new_errors2 = np . zeros ( new_shape , dtype = self . _frequencies . dtype ) self . _apply_bin_map ( old_frequencies = self . _frequencies , new_frequencies = new_frequencies , old_errors2 = self . _errors2 , new_errors2 = new_errors2 , bin_map = bin_map , axis = axis ) self . _frequencies = new_frequencies self . _errors2 = new_errors2
Reshape data to match new binning schema .
196
11
248,332
def _apply_bin_map ( self , old_frequencies , new_frequencies , old_errors2 , new_errors2 , bin_map , axis = 0 ) : if old_frequencies is not None and old_frequencies . shape [ axis ] > 0 : if isinstance ( bin_map , int ) : new_index = [ slice ( None ) for i in range ( self . ndim ) ] new_index [ axis ] = slice ( bin_map , bin_map + old_frequencies . shape [ axis ] ) new_frequencies [ tuple ( new_index ) ] += old_frequencies new_errors2 [ tuple ( new_index ) ] += old_errors2 else : for ( old , new ) in bin_map : # Generic enough new_index = [ slice ( None ) for i in range ( self . ndim ) ] new_index [ axis ] = new old_index = [ slice ( None ) for i in range ( self . ndim ) ] old_index [ axis ] = old new_frequencies [ tuple ( new_index ) ] += old_frequencies [ tuple ( old_index ) ] new_errors2 [ tuple ( new_index ) ] += old_errors2 [ tuple ( old_index ) ]
Fill new data arrays using a map .
283
8
248,333
def has_same_bins ( self , other : "HistogramBase" ) -> bool : if self . shape != other . shape : return False elif self . ndim == 1 : return np . allclose ( self . bins , other . bins ) elif self . ndim > 1 : for i in range ( self . ndim ) : if not np . allclose ( self . bins [ i ] , other . bins [ i ] ) : return False return True
Whether two histograms share the same binning .
101
10
248,334
def copy ( self , include_frequencies : bool = True ) -> "HistogramBase" : if include_frequencies : frequencies = np . copy ( self . frequencies ) missed = self . _missed . copy ( ) errors2 = np . copy ( self . errors2 ) stats = self . _stats or None else : frequencies = np . zeros_like ( self . _frequencies ) errors2 = np . zeros_like ( self . _errors2 ) missed = np . zeros_like ( self . _missed ) stats = None a_copy = self . __class__ . __new__ ( self . __class__ ) a_copy . _binnings = [ binning . copy ( ) for binning in self . _binnings ] a_copy . _dtype = self . dtype a_copy . _frequencies = frequencies a_copy . _errors2 = errors2 a_copy . _meta_data = self . _meta_data . copy ( ) a_copy . keep_missed = self . keep_missed a_copy . _missed = missed a_copy . _stats = stats return a_copy
Copy the histogram .
256
5
248,335
def to_dict ( self ) -> OrderedDict : result = OrderedDict ( ) result [ "histogram_type" ] = type ( self ) . __name__ result [ "binnings" ] = [ binning . to_dict ( ) for binning in self . _binnings ] result [ "frequencies" ] = self . frequencies . tolist ( ) result [ "dtype" ] = str ( np . dtype ( self . dtype ) ) # TODO: Optimize for _errors == _frequencies result [ "errors2" ] = self . errors2 . tolist ( ) result [ "meta_data" ] = self . _meta_data result [ "missed" ] = self . _missed . tolist ( ) result [ "missed_keep" ] = self . keep_missed self . _update_dict ( result ) return result
Dictionary with all data in the histogram .
197
10
248,336
def _merge_meta_data ( cls , first : "HistogramBase" , second : "HistogramBase" ) -> dict : keys = set ( first . _meta_data . keys ( ) ) keys = keys . union ( set ( second . _meta_data . keys ( ) ) ) return { key : ( first . _meta_data . get ( key , None ) if first . _meta_data . get ( key , None ) == second . _meta_data . get ( key , None ) else None ) for key in keys }
Merge meta data of two histograms leaving only the equal values .
120
14
248,337
def mean ( self ) -> Optional [ float ] : if self . _stats : # TODO: should be true always? if self . total > 0 : return self . _stats [ "sum" ] / self . total else : return np . nan else : return None
Statistical mean of all values entered into histogram .
57
11
248,338
def std ( self ) -> Optional [ float ] : #, ddof=0): # TODO: Add DOF if self . _stats : return np . sqrt ( self . variance ( ) ) else : return None
Standard deviation of all values entered into histogram .
47
10
248,339
def variance ( self ) -> Optional [ float ] : #, ddof: int = 0) -> float: # TODO: Add DOF # http://stats.stackexchange.com/questions/6534/how-do-i-calculate-a-weighted-standard-deviation-in-excel if self . _stats : if self . total > 0 : return ( self . _stats [ "sum2" ] - self . _stats [ "sum" ] ** 2 / self . total ) / self . total else : return np . nan else : return None
Statistical variance of all values entered into histogram .
129
11
248,340
def find_bin ( self , value ) : ixbin = np . searchsorted ( self . bin_left_edges , value , side = "right" ) if ixbin == 0 : return - 1 elif ixbin == self . bin_count : if value <= self . bin_right_edges [ - 1 ] : return ixbin - 1 else : return self . bin_count elif value < self . bin_right_edges [ ixbin - 1 ] : return ixbin - 1 elif ixbin == self . bin_count : return self . bin_count else : return None
Index of bin corresponding to a value .
137
8
248,341
def fill ( self , value , weight = 1 ) : self . _coerce_dtype ( type ( weight ) ) if self . _binning . is_adaptive ( ) : map = self . _binning . force_bin_existence ( value ) self . _reshape_data ( self . _binning . bin_count , map ) ixbin = self . find_bin ( value ) if ixbin is None : self . overflow = np . nan self . underflow = np . nan elif ixbin == - 1 and self . keep_missed : self . underflow += weight elif ixbin == self . bin_count and self . keep_missed : self . overflow += weight else : self . _frequencies [ ixbin ] += weight self . _errors2 [ ixbin ] += weight ** 2 if self . _stats : self . _stats [ "sum" ] += weight * value self . _stats [ "sum2" ] += weight * value ** 2 return ixbin
Update histogram with a new value .
225
8
248,342
def fill_n ( self , values , weights = None , dropna : bool = True ) : # TODO: Unify with HistogramBase values = np . asarray ( values ) if dropna : values = values [ ~ np . isnan ( values ) ] if self . _binning . is_adaptive ( ) : map = self . _binning . force_bin_existence ( values ) self . _reshape_data ( self . _binning . bin_count , map ) if weights : weights = np . asarray ( weights ) self . _coerce_dtype ( weights . dtype ) ( frequencies , errors2 , underflow , overflow , stats ) = calculate_frequencies ( values , self . _binning , dtype = self . dtype , weights = weights , validate_bins = False ) self . _frequencies += frequencies self . _errors2 += errors2 # TODO: check that adaptive does not produce under-/over-flows? if self . keep_missed : self . underflow += underflow self . overflow += overflow if self . _stats : for key in self . _stats : self . _stats [ key ] += stats . get ( key , 0.0 )
Update histograms with a set of values .
266
9
248,343
def to_xarray ( self ) -> "xarray.Dataset" : import xarray as xr data_vars = { "frequencies" : xr . DataArray ( self . frequencies , dims = "bin" ) , "errors2" : xr . DataArray ( self . errors2 , dims = "bin" ) , "bins" : xr . DataArray ( self . bins , dims = ( "bin" , "x01" ) ) } coords = { } attrs = { "underflow" : self . underflow , "overflow" : self . overflow , "inner_missed" : self . inner_missed , "keep_missed" : self . keep_missed } attrs . update ( self . _meta_data ) # TODO: Add stats return xr . Dataset ( data_vars , coords , attrs )
Convert to xarray . Dataset
201
9
248,344
def from_xarray ( cls , arr : "xarray.Dataset" ) -> "Histogram1D" : kwargs = { 'frequencies' : arr [ "frequencies" ] , 'binning' : arr [ "bins" ] , 'errors2' : arr [ "errors2" ] , 'overflow' : arr . attrs [ "overflow" ] , 'underflow' : arr . attrs [ "underflow" ] , 'keep_missed' : arr . attrs [ "keep_missed" ] } # TODO: Add stats return cls ( * * kwargs )
Convert form xarray . Dataset
142
9
248,345
def set_default_backend ( name : str ) : global _default_backend if name == "bokeh" : raise RuntimeError ( "Support for bokeh has been discontinued. At some point, we may return to support holoviews." ) if not name in backends : raise RuntimeError ( "Backend {0} is not supported and cannot be set as default." . format ( name ) ) _default_backend = name
Choose a default backend .
97
5
248,346
def _get_backend ( name : str = None ) : if not backends : raise RuntimeError ( "No plotting backend available. Please, install matplotlib (preferred) or bokeh (limited)." ) if not name : name = _default_backend if name == "bokeh" : raise RuntimeError ( "Support for bokeh has been discontinued. At some point, we may return to support holoviews." ) backend = backends . get ( name ) if not backend : raise RuntimeError ( "Backend {0} does not exist. Use one of the following: {1}" . format ( name , ", " . join ( backends . keys ( ) ) ) ) return name , backends [ name ]
Get a plotting backend .
159
5
248,347
def plot ( histogram : HistogramBase , kind : Optional [ str ] = None , backend : Optional [ str ] = None , * * kwargs ) : backend_name , backend = _get_backend ( backend ) if kind is None : kinds = [ t for t in backend . types if histogram . ndim in backend . dims [ t ] ] if not kinds : raise RuntimeError ( "No plot type is supported for {0}" . format ( histogram . __class__ . __name__ ) ) kind = kinds [ 0 ] if kind in backend . types : method = getattr ( backend , kind ) return method ( histogram , * * kwargs ) else : raise RuntimeError ( "Histogram type error: {0} missing in backend {1}" . format ( kind , backend_name ) )
Universal plotting function .
177
4
248,348
def enable_inline_view ( f ) : @ wraps ( f ) def wrapper ( hist , write_to = None , write_format = "auto" , display = "auto" , indent = 2 , * * kwargs ) : vega_data = f ( hist , * * kwargs ) if display is True and not VEGA_IPYTHON_PLUGIN_ENABLED : raise RuntimeError ( "Cannot display vega plot: {0}" . format ( VEGA_ERROR ) ) if display == "auto" : display = write_to is None if write_to : write_vega ( vega_data , hist . title , write_to , write_format , indent ) return display_vega ( vega_data , display ) return wrapper
Decorator to enable in - line viewing in Python and saving to external file .
170
17
248,349
def write_vega ( vega_data , * , title : Optional [ str ] , write_to : str , write_format : str = "auto" , indent : int = 2 ) : spec = json . dumps ( vega_data , indent = indent ) if write_format == "html" or write_format is "auto" and write_to . endswith ( ".html" ) : output = HTML_TEMPLATE . replace ( "{{ title }}" , title or "Histogram" ) . replace ( "{{ spec }}" , spec ) elif write_format == "json" or write_format is "auto" and write_to . endswith ( ".json" ) : output = spec else : raise RuntimeError ( "Format not understood." ) with codecs . open ( write_to , "w" , encoding = "utf-8" ) as out : out . write ( output )
Write vega dictionary to an external file .
200
9
248,350
def display_vega ( vega_data : dict , display : bool = True ) -> Union [ 'Vega' , dict ] : if VEGA_IPYTHON_PLUGIN_ENABLED and display : from vega3 import Vega return Vega ( vega_data ) else : return vega_data
Optionally display vega dictionary .
70
7
248,351
def bar ( h1 : Histogram1D , * * kwargs ) -> dict : # TODO: Enable collections # TODO: Enable legend vega = _create_figure ( kwargs ) _add_title ( h1 , vega , kwargs ) _create_scales ( h1 , vega , kwargs ) _create_axes ( h1 , vega , kwargs ) data = get_data ( h1 , kwargs . pop ( "density" , None ) , kwargs . pop ( "cumulative" , None ) ) . tolist ( ) lefts = h1 . bin_left_edges . astype ( float ) . tolist ( ) rights = h1 . bin_right_edges . astype ( float ) . tolist ( ) vega [ "data" ] = [ { "name" : "table" , "values" : [ { "x" : lefts [ i ] , "x2" : rights [ i ] , "y" : data [ i ] , } for i in range ( h1 . bin_count ) ] } ] alpha = kwargs . pop ( "alpha" , 1 ) # hover_alpha = kwargs.pop("hover_alpha", alpha) vega [ "marks" ] = [ { "type" : "rect" , "from" : { "data" : "table" } , "encode" : { "enter" : { "x" : { "scale" : "xscale" , "field" : "x" } , "x2" : { "scale" : "xscale" , "field" : "x2" } , "y" : { "scale" : "yscale" , "value" : 0 } , "y2" : { "scale" : "yscale" , "field" : "y" } , # "stroke": {"scale": "color", "field": "c"}, "strokeWidth" : { "value" : kwargs . pop ( "lw" , 2 ) } } , "update" : { "fillOpacity" : [ # {"test": "datum === tooltip", "value": hover_alpha}, { "value" : alpha } ] } , } } ] _create_tooltips ( h1 , vega , kwargs ) return vega
Bar plot of 1D histogram .
516
8
248,352
def scatter ( h1 : Histogram1D , * * kwargs ) -> dict : shape = kwargs . pop ( "shape" , DEFAULT_SCATTER_SHAPE ) # size = kwargs.pop("size", DEFAULT_SCATTER_SIZE) mark_template = [ { "type" : "symbol" , "from" : { "data" : "series" } , "encode" : { "enter" : { "x" : { "scale" : "xscale" , "field" : "x" } , "y" : { "scale" : "yscale" , "field" : "y" } , "shape" : { "value" : shape } , # "size": {"value": size}, "fill" : { "scale" : "series" , "field" : "c" } , } , } } ] vega = _scatter_or_line ( h1 , mark_template = mark_template , kwargs = kwargs ) return vega
Scatter plot of 1D histogram values .
229
10
248,353
def line ( h1 : Histogram1D , * * kwargs ) -> dict : lw = kwargs . pop ( "lw" , DEFAULT_STROKE_WIDTH ) mark_template = [ { "type" : "line" , "encode" : { "enter" : { "x" : { "scale" : "xscale" , "field" : "x" } , "y" : { "scale" : "yscale" , "field" : "y" } , "stroke" : { "scale" : "series" , "field" : "c" } , "strokeWidth" : { "value" : lw } } } , "from" : { "data" : "series" } , } ] vega = _scatter_or_line ( h1 , mark_template = mark_template , kwargs = kwargs ) return vega
Line plot of 1D histogram values .
203
9
248,354
def _create_figure ( kwargs : Mapping [ str , Any ] ) -> dict : return { "$schema" : "https://vega.github.io/schema/vega/v3.json" , "width" : kwargs . pop ( "width" , DEFAULT_WIDTH ) , "height" : kwargs . pop ( "height" , DEFAULT_HEIGHT ) , "padding" : kwargs . pop ( "padding" , DEFAULT_PADDING ) }
Create basic dictionary object with figure properties .
115
8
248,355
def _create_scales ( hist : HistogramBase , vega : dict , kwargs : dict ) : if hist . ndim == 1 : bins0 = hist . bins . astype ( float ) else : bins0 = hist . bins [ 0 ] . astype ( float ) xlim = kwargs . pop ( "xlim" , "auto" ) ylim = kwargs . pop ( "ylim" , "auto" ) if xlim is "auto" : nice_x = True else : nice_x = False if ylim is "auto" : nice_y = True else : nice_y = False # TODO: Unify xlim & ylim parameters with matplotlib # TODO: Apply xscale & yscale parameters vega [ "scales" ] = [ { "name" : "xscale" , "type" : "linear" , "range" : "width" , "nice" : nice_x , "zero" : None , "domain" : [ bins0 [ 0 , 0 ] , bins0 [ - 1 , 1 ] ] if xlim == "auto" else [ float ( xlim [ 0 ] ) , float ( xlim [ 1 ] ) ] , # "domain": {"data": "table", "field": "x"} } , { "name" : "yscale" , "type" : "linear" , "range" : "height" , "nice" : nice_y , "zero" : True if hist . ndim == 1 else None , "domain" : { "data" : "table" , "field" : "y" } if ylim == "auto" else [ float ( ylim [ 0 ] ) , float ( ylim [ 1 ] ) ] } ] if hist . ndim >= 2 : bins1 = hist . bins [ 1 ] . astype ( float ) vega [ "scales" ] [ 1 ] [ "domain" ] = [ bins1 [ 0 , 0 ] , bins1 [ - 1 , 1 ] ]
Find proper scales for axes .
440
6
248,356
def _create_axes ( hist : HistogramBase , vega : dict , kwargs : dict ) : xlabel = kwargs . pop ( "xlabel" , hist . axis_names [ 0 ] ) ylabel = kwargs . pop ( "ylabel" , hist . axis_names [ 1 ] if len ( hist . axis_names ) >= 2 else None ) vega [ "axes" ] = [ { "orient" : "bottom" , "scale" : "xscale" , "title" : xlabel } , { "orient" : "left" , "scale" : "yscale" , "title" : ylabel } ]
Create axes in the figure .
146
6
248,357
def _create_tooltips ( hist : Histogram1D , vega : dict , kwargs : dict ) : if kwargs . pop ( "tooltips" , False ) : vega [ "signals" ] = vega . get ( "signals" , [ ] ) vega [ "signals" ] . append ( { "name" : "tooltip" , "value" : { } , "on" : [ { "events" : "rect:mouseover" , "update" : "datum" } , { "events" : "rect:mouseout" , "update" : "{}" } ] } ) font_size = kwargs . get ( "fontsize" , DEFAULT_FONTSIZE ) vega [ "marks" ] = vega . get ( "marks" , [ ] ) vega [ "marks" ] . append ( { "type" : "text" , "encode" : { "enter" : { "align" : { "value" : "center" } , "baseline" : { "value" : "bottom" } , "fill" : { "value" : "#333" } , "fontSize" : { "value" : font_size } } , "update" : { "x" : { "scale" : "xscale" , "signal" : "(tooltip.x + tooltip.x2) / 2" , "band" : 0.5 } , "y" : { "scale" : "yscale" , "signal" : "tooltip.y" , "offset" : - 2 } , "text" : { "signal" : "tooltip.y" } , "fillOpacity" : [ { "test" : "datum === tooltip" , "value" : 0 } , { "value" : 1 } ] } } } )
In one - dimensional plots show values above the value on hover .
410
13
248,358
def _add_title ( hist : HistogramBase , vega : dict , kwargs : dict ) : title = kwargs . pop ( "title" , hist . title ) if title : vega [ "title" ] = { "text" : title }
Display plot title if available .
58
6
248,359
def _prepare_data ( data , transformed , klass , * args , * * kwargs ) : # TODO: Maybe include in the class itself? data = np . asarray ( data ) if not transformed : data = klass . transform ( data ) dropna = kwargs . get ( "dropna" , False ) if dropna : data = data [ ~ np . isnan ( data ) . any ( axis = 1 ) ] return data
Transform data for binning .
99
6
248,360
def polar_histogram ( xdata , ydata , radial_bins = "numpy" , phi_bins = 16 , transformed = False , * args , * * kwargs ) : dropna = kwargs . pop ( "dropna" , True ) data = np . concatenate ( [ xdata [ : , np . newaxis ] , ydata [ : , np . newaxis ] ] , axis = 1 ) data = _prepare_data ( data , transformed = transformed , klass = PolarHistogram , dropna = dropna ) if isinstance ( phi_bins , int ) : phi_range = ( 0 , 2 * np . pi ) if "phi_range" in "kwargs" : phi_range = kwargs [ "phi_range" ] elif "range" in "kwargs" : phi_range = kwargs [ "range" ] [ 1 ] phi_range = list ( phi_range ) + [ phi_bins + 1 ] phi_bins = np . linspace ( * phi_range ) bin_schemas = binnings . calculate_bins_nd ( data , [ radial_bins , phi_bins ] , * args , check_nan = not dropna , * * kwargs ) weights = kwargs . pop ( "weights" , None ) frequencies , errors2 , missed = histogram_nd . calculate_frequencies ( data , ndim = 2 , binnings = bin_schemas , weights = weights ) return PolarHistogram ( binnings = bin_schemas , frequencies = frequencies , errors2 = errors2 , missed = missed )
Facade construction function for the PolarHistogram .
375
10
248,361
def spherical_histogram ( data = None , radial_bins = "numpy" , theta_bins = 16 , phi_bins = 16 , transformed = False , * args , * * kwargs ) : dropna = kwargs . pop ( "dropna" , True ) data = _prepare_data ( data , transformed = transformed , klass = SphericalHistogram , dropna = dropna ) if isinstance ( theta_bins , int ) : theta_range = ( 0 , np . pi ) if "theta_range" in "kwargs" : theta_range = kwargs [ "theta_range" ] elif "range" in "kwargs" : theta_range = kwargs [ "range" ] [ 1 ] theta_range = list ( theta_range ) + [ theta_bins + 1 ] theta_bins = np . linspace ( * theta_range ) if isinstance ( phi_bins , int ) : phi_range = ( 0 , 2 * np . pi ) if "phi_range" in "kwargs" : phi_range = kwargs [ "phi_range" ] elif "range" in "kwargs" : phi_range = kwargs [ "range" ] [ 2 ] phi_range = list ( phi_range ) + [ phi_bins + 1 ] phi_bins = np . linspace ( * phi_range ) bin_schemas = binnings . calculate_bins_nd ( data , [ radial_bins , theta_bins , phi_bins ] , * args , check_nan = not dropna , * * kwargs ) weights = kwargs . pop ( "weights" , None ) frequencies , errors2 , missed = histogram_nd . calculate_frequencies ( data , ndim = 3 , binnings = bin_schemas , weights = weights ) return SphericalHistogram ( binnings = bin_schemas , frequencies = frequencies , errors2 = errors2 , missed = missed )
Facade construction function for the SphericalHistogram .
474
11
248,362
def cylindrical_histogram ( data = None , rho_bins = "numpy" , phi_bins = 16 , z_bins = "numpy" , transformed = False , * args , * * kwargs ) : dropna = kwargs . pop ( "dropna" , True ) data = _prepare_data ( data , transformed = transformed , klass = CylindricalHistogram , dropna = dropna ) if isinstance ( phi_bins , int ) : phi_range = ( 0 , 2 * np . pi ) if "phi_range" in "kwargs" : phi_range = kwargs [ "phi_range" ] elif "range" in "kwargs" : phi_range = kwargs [ "range" ] [ 1 ] phi_range = list ( phi_range ) + [ phi_bins + 1 ] phi_bins = np . linspace ( * phi_range ) bin_schemas = binnings . calculate_bins_nd ( data , [ rho_bins , phi_bins , z_bins ] , * args , check_nan = not dropna , * * kwargs ) weights = kwargs . pop ( "weights" , None ) frequencies , errors2 , missed = histogram_nd . calculate_frequencies ( data , ndim = 3 , binnings = bin_schemas , weights = weights ) return CylindricalHistogram ( binnings = bin_schemas , frequencies = frequencies , errors2 = errors2 , missed = missed )
Facade construction function for the CylindricalHistogram .
362
13
248,363
def projection ( self , * axes , * * kwargs ) : axes , _ = self . _get_projection_axes ( * axes ) axes = tuple ( sorted ( axes ) ) if axes in self . _projection_class_map : klass = self . _projection_class_map [ axes ] return HistogramND . projection ( self , * axes , type = klass , * * kwargs ) else : return HistogramND . projection ( self , * axes , * * kwargs )
Projection to lower - dimensional histogram . The inheriting class should implement the _projection_class_map class attribute to suggest class for the projection . If the arguments don t match any of the map keys HistogramND is used .
113
49
248,364
def enable_collection ( f ) : @ wraps ( f ) def new_f ( h : AbstractHistogram1D , * * kwargs ) : from physt . histogram_collection import HistogramCollection if isinstance ( h , HistogramCollection ) : return f ( h , * * kwargs ) else : return f ( HistogramCollection ( h ) , * * kwargs ) return new_f
Call the wrapped function with a HistogramCollection as argument .
90
12
248,365
def bar ( h : Histogram2D , * , barmode : str = DEFAULT_BARMODE , alpha : float = DEFAULT_ALPHA , * * kwargs ) : get_data_kwargs = pop_many ( kwargs , "density" , "cumulative" , "flatten" ) data = [ go . Bar ( x = histogram . bin_centers , y = get_data ( histogram , * * get_data_kwargs ) , width = histogram . bin_widths , name = histogram . name , opacity = alpha , * * kwargs ) for histogram in h ] layout = go . Layout ( barmode = barmode ) _add_ticks ( layout . xaxis , h [ 0 ] , kwargs ) figure = go . Figure ( data = data , layout = layout ) return figure
Bar plot .
191
3
248,366
def _bins_to_json ( h2 ) : south = h2 . get_bin_left_edges ( 0 ) north = h2 . get_bin_right_edges ( 0 ) west = h2 . get_bin_left_edges ( 1 ) east = h2 . get_bin_right_edges ( 1 ) return { "type" : "FeatureCollection" , "features" : [ { "type" : "Feature" , "geometry" : { "type" : "Polygon" , # Note that folium and GeoJson have them swapped "coordinates" : [ [ [ east [ j ] , south [ i ] ] , [ east [ j ] , north [ i ] ] , [ west [ j ] , north [ i ] ] , [ west [ j ] , south [ i ] ] , [ east [ j ] , south [ i ] ] ] ] , } , "properties" : { "count" : float ( h2 . frequencies [ i , j ] ) } } for i in range ( h2 . shape [ 0 ] ) for j in range ( h2 . shape [ 1 ] ) ] }
Create GeoJSON representation of histogram bins
251
8
248,367
def geo_map ( h2 , map = None , tiles = 'stamenterrain' , cmap = "wk" , alpha = 0.5 , lw = 1 , fit_bounds = None , layer_name = None ) : if not map : latitude = h2 . get_bin_centers ( 0 ) . mean ( ) longitude = h2 . get_bin_centers ( 1 ) . mean ( ) zoom_start = 10 map = folium . Map ( location = [ latitude , longitude ] , tiles = tiles ) if fit_bounds == None : fit_bounds = True geo_json = _bins_to_json ( h2 ) if not layer_name : layer_name = h2 . name from branca . colormap import LinearColormap color_map = LinearColormap ( cmap , vmin = h2 . frequencies . min ( ) , vmax = h2 . frequencies . max ( ) ) # legend = folium.Html("<div>Legend</div>") # legend_div = folium.Div("20%", "20%", "75%", "5%") # # legend_div.add_to(map) # legend_div.add_child(legend) #xx = h2.frequencies.max() def styling_function ( bin ) : count = bin [ "properties" ] [ "count" ] return { "fillColor" : color_map ( count ) , "color" : "black" , "fillOpacity" : alpha if count > 0 else 0 , "weight" : lw , # "strokeWidth": lw, "opacity" : alpha if count > 0 else 0 , } # .update(styling) layer = folium . GeoJson ( geo_json , style_function = styling_function , name = layer_name ) layer . add_to ( map ) if fit_bounds : map . fit_bounds ( layer . get_bounds ( ) ) return map
Show rectangular grid over a map .
440
7
248,368
def load_csv ( path ) : meta = [ ] data = [ ] with codecs . open ( path , encoding = "ASCII" ) as in_file : for line in in_file : if line . startswith ( "#" ) : key , value = line [ 1 : ] . strip ( ) . split ( " " , 1 ) meta . append ( ( key , value ) ) # TODO: There are duplicit entries :-() else : try : data . append ( [ float ( frag ) for frag in line . split ( "," ) ] ) except : pass data = np . asarray ( data ) ndim = int ( _get ( meta , "dimension" ) ) if ndim == 1 : return _create_h1 ( data , meta ) elif ndim == 2 : return _create_h2 ( data , meta )
Loads a histogram as output from Geant4 analysis tools in CSV format .
184
17
248,369
def _get ( pseudodict , key , single = True ) : matches = [ item [ 1 ] for item in pseudodict if item [ 0 ] == key ] if single : return matches [ 0 ] else : return matches
Helper method for getting values from multi - dict s
48
10
248,370
def queryURL ( self , xri , service_type = None ) : # Trim off the xri:// prefix. The proxy resolver didn't accept it # when this code was written, but that may (or may not) change for # XRI Resolution 2.0 Working Draft 11. qxri = toURINormal ( xri ) [ 6 : ] hxri = self . proxy_url + qxri args = { # XXX: If the proxy resolver will ensure that it doesn't return # bogus CanonicalIDs (as per Steve's message of 15 Aug 2006 # 11:13:42), then we could ask for application/xrd+xml instead, # which would give us a bit less to process. '_xrd_r' : 'application/xrds+xml' , } if service_type : args [ '_xrd_t' ] = service_type else : # Don't perform service endpoint selection. args [ '_xrd_r' ] += ';sep=false' query = _appendArgs ( hxri , args ) return query
Build a URL to query the proxy resolver .
235
10
248,371
def query ( self , xri , service_types ) : # FIXME: No test coverage! services = [ ] # Make a seperate request to the proxy resolver for each service # type, as, if it is following Refs, it could return a different # XRDS for each. canonicalID = None for service_type in service_types : url = self . queryURL ( xri , service_type ) response = fetchers . fetch ( url ) if response . status not in ( 200 , 206 ) : # XXX: sucks to fail silently. # print "response not OK:", response continue et = etxrd . parseXRDS ( response . body ) canonicalID = etxrd . getCanonicalID ( xri , et ) some_services = list ( iterServices ( et ) ) services . extend ( some_services ) # TODO: # * If we do get hits for multiple service_types, we're almost # certainly going to have duplicated service entries and # broken priority ordering. return canonicalID , services
Resolve some services for an XRI .
222
9
248,372
def generateAcceptHeader ( * elements ) : parts = [ ] for element in elements : if type ( element ) is str : qs = "1.0" mtype = element else : mtype , q = element q = float ( q ) if q > 1 or q <= 0 : raise ValueError ( 'Invalid preference factor: %r' % q ) qs = '%0.1f' % ( q , ) parts . append ( ( qs , mtype ) ) parts . sort ( ) chunks = [ ] for q , mtype in parts : if q == '1.0' : chunks . append ( mtype ) else : chunks . append ( '%s; q=%s' % ( mtype , q ) ) return ', ' . join ( chunks )
Generate an accept header value
167
6
248,373
def parseAcceptHeader ( value ) : chunks = [ chunk . strip ( ) for chunk in value . split ( ',' ) ] accept = [ ] for chunk in chunks : parts = [ s . strip ( ) for s in chunk . split ( ';' ) ] mtype = parts . pop ( 0 ) if '/' not in mtype : # This is not a MIME type, so ignore the bad data continue main , sub = mtype . split ( '/' , 1 ) for ext in parts : if '=' in ext : k , v = ext . split ( '=' , 1 ) if k == 'q' : try : q = float ( v ) break except ValueError : # Ignore poorly formed q-values pass else : q = 1.0 accept . append ( ( q , main , sub ) ) accept . sort ( ) accept . reverse ( ) return [ ( main , sub , q ) for ( q , main , sub ) in accept ]
Parse an accept header ignoring any accept - extensions
203
10
248,374
def getAcceptable ( accept_header , have_types ) : accepted = parseAcceptHeader ( accept_header ) preferred = matchTypes ( accepted , have_types ) return [ mtype for ( mtype , _ ) in preferred ]
Parse the accept header and return a list of available types in preferred order . If a type is unacceptable it will not be in the resulting list .
49
30
248,375
def fromPostArgs ( cls , args ) : self = cls ( ) # Partition into "openid." args and bare args openid_args = { } for key , value in args . items ( ) : if isinstance ( value , list ) : raise TypeError ( "query dict must have one value for each key, " "not lists of values. Query is %r" % ( args , ) ) try : prefix , rest = key . split ( '.' , 1 ) except ValueError : prefix = None if prefix != 'openid' : self . args [ ( BARE_NS , key ) ] = value else : openid_args [ rest ] = value self . _fromOpenIDArgs ( openid_args ) return self
Construct a Message containing a set of POST arguments .
160
10
248,376
def getKey ( self , namespace , ns_key ) : namespace = self . _fixNS ( namespace ) if namespace == BARE_NS : return ns_key ns_alias = self . namespaces . getAlias ( namespace ) # No alias is defined, so no key can exist if ns_alias is None : return None if ns_alias == NULL_NAMESPACE : tail = ns_key else : tail = '%s.%s' % ( ns_alias , ns_key ) return 'openid.' + tail
Get the key for a particular namespaced argument
114
9
248,377
def getArg ( self , namespace , key , default = None ) : namespace = self . _fixNS ( namespace ) args_key = ( namespace , key ) try : return self . args [ args_key ] except KeyError : if default is no_default : raise KeyError ( ( namespace , key ) ) else : return default
Get a value for a namespaced key .
70
9
248,378
def add ( self , namespace_uri ) : # See if this namespace is already mapped to an alias alias = self . namespace_to_alias . get ( namespace_uri ) if alias is not None : return alias # Fall back to generating a numerical alias i = 0 while True : alias = 'ext' + str ( i ) try : self . addAlias ( namespace_uri , alias ) except KeyError : i += 1 else : return alias assert False , "Not reached"
Add this namespace URI to the mapping without caring what alias it ends up with
100
15
248,379
def findHTMLMeta ( stream ) : parser = YadisHTMLParser ( ) chunks = [ ] while 1 : chunk = stream . read ( CHUNK_SIZE ) if not chunk : # End of file break chunks . append ( chunk ) try : parser . feed ( chunk ) except HTMLParseError , why : # HTML parse error, so bail chunks . append ( stream . read ( ) ) break except ParseDone , why : uri = why [ 0 ] if uri is None : # Parse finished, but we may need the rest of the file chunks . append ( stream . read ( ) ) break else : return uri content = '' . join ( chunks ) raise MetaNotFound ( content )
Look for a meta http - equiv tag with the YADIS header name .
149
17
248,380
def toTypeURIs ( namespace_map , alias_list_s ) : uris = [ ] if alias_list_s : for alias in alias_list_s . split ( ',' ) : type_uri = namespace_map . getNamespaceURI ( alias ) if type_uri is None : raise KeyError ( 'No type is defined for attribute name %r' % ( alias , ) ) else : uris . append ( type_uri ) return uris
Given a namespace mapping and a string containing a comma - separated list of namespace aliases return a list of type URIs that correspond to those aliases .
101
29
248,381
def add ( self , attribute ) : if attribute . type_uri in self . requested_attributes : raise KeyError ( 'The attribute %r has already been requested' % ( attribute . type_uri , ) ) self . requested_attributes [ attribute . type_uri ] = attribute
Add an attribute to this attribute exchange request .
61
9
248,382
def addValue ( self , type_uri , value ) : try : values = self . data [ type_uri ] except KeyError : values = self . data [ type_uri ] = [ ] values . append ( value )
Add a single value for the given attribute type to the message . If there are already values specified for this type this value will be sent in addition to the values already specified .
48
35
248,383
def getSingle ( self , type_uri , default = None ) : values = self . data . get ( type_uri ) if not values : return default elif len ( values ) == 1 : return values [ 0 ] else : raise AXError ( 'More than one value present for %r' % ( type_uri , ) )
Get a single value for an attribute . If no value was sent for this attribute use the supplied default . If there is more than one value for this attribute this method will fail .
71
36
248,384
def getExtensionArgs ( self ) : aliases = NamespaceMap ( ) zero_value_types = [ ] if self . request is not None : # Validate the data in the context of the request (the # same attributes should be present in each, and the # counts in the response must be no more than the counts # in the request) for type_uri in self . data : if type_uri not in self . request : raise KeyError ( 'Response attribute not present in request: %r' % ( type_uri , ) ) for attr_info in self . request . iterAttrs ( ) : # Copy the aliases from the request so that reading # the response in light of the request is easier if attr_info . alias is None : aliases . add ( attr_info . type_uri ) else : aliases . addAlias ( attr_info . type_uri , attr_info . alias ) try : values = self . data [ attr_info . type_uri ] except KeyError : values = [ ] zero_value_types . append ( attr_info ) if ( attr_info . count != UNLIMITED_VALUES ) and ( attr_info . count < len ( values ) ) : raise AXError ( 'More than the number of requested values were ' 'specified for %r' % ( attr_info . type_uri , ) ) kv_args = self . _getExtensionKVArgs ( aliases ) # Add the KV args into the response with the args that are # unique to the fetch_response ax_args = self . _newArgs ( ) # For each requested attribute, put its type/alias and count # into the response even if no data were returned. for attr_info in zero_value_types : alias = aliases . getAlias ( attr_info . type_uri ) kv_args [ 'type.' + alias ] = attr_info . type_uri kv_args [ 'count.' + alias ] = '0' update_url = ( ( self . request and self . request . update_url ) or self . update_url ) if update_url : ax_args [ 'update_url' ] = update_url ax_args . update ( kv_args ) return ax_args
Serialize this object into arguments in the attribute exchange namespace
495
11
248,385
def fromSuccessResponse ( cls , success_response , signed = True ) : self = cls ( ) ax_args = success_response . extensionResponse ( self . ns_uri , signed ) try : self . parseExtensionArgs ( ax_args ) except NotAXMessage , err : return None else : return self
Construct a FetchResponse object from an OpenID library SuccessResponse object .
68
15
248,386
def parseExtensionArgs ( self , args , strict = False ) : for list_name in [ 'required' , 'optional' ] : required = ( list_name == 'required' ) items = args . get ( list_name ) if items : for field_name in items . split ( ',' ) : try : self . requestField ( field_name , required , strict ) except ValueError : if strict : raise self . policy_url = args . get ( 'policy_url' )
Parse the unqualified simple registration request parameters and add them to this object .
106
16
248,387
def requestField ( self , field_name , required = False , strict = False ) : checkFieldName ( field_name ) if strict : if field_name in self . required or field_name in self . optional : raise ValueError ( 'That field has already been requested' ) else : if field_name in self . required : return if field_name in self . optional : if required : self . optional . remove ( field_name ) else : return if required : self . required . append ( field_name ) else : self . optional . append ( field_name )
Request the specified field from the OpenID user
122
9
248,388
def requestFields ( self , field_names , required = False , strict = False ) : if isinstance ( field_names , basestring ) : raise TypeError ( 'Fields should be passed as a list of ' 'strings (not %r)' % ( type ( field_names ) , ) ) for field_name in field_names : self . requestField ( field_name , required , strict = strict )
Add the given list of fields to the request
90
9
248,389
def getExtensionArgs ( self ) : args = { } if self . required : args [ 'required' ] = ',' . join ( self . required ) if self . optional : args [ 'optional' ] = ',' . join ( self . optional ) if self . policy_url : args [ 'policy_url' ] = self . policy_url return args
Get a dictionary of unqualified simple registration arguments representing this request .
78
13
248,390
def get ( self , field_name , default = None ) : checkFieldName ( field_name ) return self . data . get ( field_name , default )
Like dict . get except that it checks that the field name is defined by the simple registration specification
35
19
248,391
def returnToMatches ( allowed_return_to_urls , return_to ) : for allowed_return_to in allowed_return_to_urls : # A return_to pattern works the same as a realm, except that # it's not allowed to use a wildcard. We'll model this by # parsing it as a realm, and not trying to match it if it has # a wildcard. return_realm = TrustRoot . parse ( allowed_return_to ) if ( # Parses as a trust root return_realm is not None and # Does not have a wildcard not return_realm . wildcard and # Matches the return_to that we passed in with it return_realm . validateURL ( return_to ) ) : return True # No URL in the list matched return False
Is the return_to URL under one of the supplied allowed return_to URLs?
175
17
248,392
def getAllowedReturnURLs ( relying_party_url ) : ( rp_url_after_redirects , return_to_urls ) = services . getServiceEndpoints ( relying_party_url , _extractReturnURL ) if rp_url_after_redirects != relying_party_url : # Verification caused a redirect raise RealmVerificationRedirected ( relying_party_url , rp_url_after_redirects ) return return_to_urls
Given a relying party discovery URL return a list of return_to URLs .
110
15
248,393
def verifyReturnTo ( realm_str , return_to , _vrfy = getAllowedReturnURLs ) : realm = TrustRoot . parse ( realm_str ) if realm is None : # The realm does not parse as a URL pattern return False try : allowable_urls = _vrfy ( realm . buildDiscoveryURL ( ) ) except RealmVerificationRedirected , err : logging . exception ( str ( err ) ) return False if returnToMatches ( allowable_urls , return_to ) : return True else : logging . error ( "Failed to validate return_to %r for realm %r, was not " "in %s" % ( return_to , realm_str , allowable_urls ) ) return False
Verify that a return_to URL is valid for the given realm .
159
15
248,394
def validateURL ( self , url ) : url_parts = _parseURL ( url ) if url_parts is None : return False proto , host , port , path = url_parts if proto != self . proto : return False if port != self . port : return False if '*' in host : return False if not self . wildcard : if host != self . host : return False elif ( ( not host . endswith ( self . host ) ) and ( '.' + host ) != self . host ) : return False if path != self . path : path_len = len ( self . path ) trust_prefix = self . path [ : path_len ] url_prefix = path [ : path_len ] # must be equal up to the length of the path, at least if trust_prefix != url_prefix : return False # These characters must be on the boundary between the end # of the trust root's path and the start of the URL's # path. if '?' in self . path : allowed = '&' else : allowed = '?/' return ( self . path [ - 1 ] in allowed or path [ path_len ] in allowed ) return True
Validates a URL against this trust root .
251
9
248,395
def checkSanity ( cls , trust_root_string ) : trust_root = cls . parse ( trust_root_string ) if trust_root is None : return False else : return trust_root . isSane ( )
str - > bool
51
4
248,396
def checkURL ( cls , trust_root , url ) : tr = cls . parse ( trust_root ) return tr is not None and tr . validateURL ( url )
quick func for validating a url against a trust root . See the TrustRoot class if you need more control .
38
23
248,397
def buildDiscoveryURL ( self ) : if self . wildcard : # Use "www." in place of the star assert self . host . startswith ( '.' ) , self . host www_domain = 'www' + self . host return '%s://%s%s' % ( self . proto , www_domain , self . path ) else : return self . unparsed
Return a discovery URL for this realm .
84
8
248,398
def next ( self ) : try : self . _current = self . services . pop ( 0 ) except IndexError : raise StopIteration else : return self . _current
Return the next service
36
4
248,399
def getNextService ( self , discover ) : manager = self . getManager ( ) if manager is not None and not manager : self . destroyManager ( ) if not manager : yadis_url , services = discover ( self . url ) manager = self . createManager ( services , yadis_url ) if manager : service = manager . next ( ) manager . store ( self . session ) else : service = None return service
Return the next authentication service for the pair of user_input and session . This function handles fallback .
91
21