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 ( ... | 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."... | 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_r... | 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 ( ra... | 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 ( ) ) ... | 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... | 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 ( ... | 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 : retur... | 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 f... | 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" )... | 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... | 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 =... | 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_ind... | 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 . d... | 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... | 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 ) se... | 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_ma... | 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 Fals... | 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 ... | 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 ) ) # TO... | 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_da... | 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 ) /... | 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... | 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 .... | 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 . _bi... | 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" : s... | 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... | 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 ... | 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 re... | 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 t... | 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_ERR... | 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 }}" ,... | 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 ( "cum... | 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" : { "sca... | 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" } , "strokeW... | 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 = F... | 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" : xlabe... | 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... | 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 d... | 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... | 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 , ... | 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 , ... | 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 Histogram... | 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_width... | 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 GeoJ... | 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 ... | 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... | 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 r... | 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 , ser... | 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 ... | 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 . ... | 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 ... | 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... | 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 ) ... | 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 P... | 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 . ... | 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... | 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 .... | 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 = s... | 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 =... | 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_r... | 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 ... | 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 ( ( no... | 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 ( ... | Return the next authentication service for the pair of user_input and session . This function handles fallback . | 91 | 21 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.