idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
232,700 | def visit_ListComp ( self , node ) : for generator in node . generators : self . visit_comprehension ( generator ) self . visit ( node . elt ) return self . add ( node ) | A comprehension is not abstracted in any way |
232,701 | def visit_FunctionDef ( self , node ) : self . aliases = IntrinsicAliases . copy ( ) self . aliases . update ( ( f . name , { f } ) for f in self . global_declarations . values ( ) ) self . aliases . update ( ( arg . id , { arg } ) for arg in node . args . args ) self . generic_visit ( node ) if Aliases . RetId in self... | Initialise aliasing default value before visiting . |
232,702 | def visit_For ( self , node ) : iter_aliases = self . visit ( node . iter ) if all ( isinstance ( x , ContainerOf ) for x in iter_aliases ) : target_aliases = set ( ) for iter_alias in iter_aliases : target_aliases . add ( iter_alias . containee ) else : target_aliases = { node . target } self . add ( node . target , t... | For loop creates aliasing between the target and the content of the iterator |
232,703 | def prepare ( self , node ) : super ( ArgumentReadOnce , self ) . prepare ( node ) for n in self . global_declarations . values ( ) : fe = ArgumentReadOnce . FunctionEffects ( n ) self . node_to_functioneffect [ n ] = fe self . result . add ( fe ) def save_effect ( module ) : for intr in module . values ( ) : if isinst... | Initialise arguments effects as this analysis in inter - procedural . |
232,704 | def ds9_objects_to_string ( regions , coordsys = 'fk5' , fmt = '.6f' , radunit = 'deg' ) : shapelist = to_shape_list ( regions , coordsys ) return shapelist . to_ds9 ( coordsys , fmt , radunit ) | Converts a list of ~regions . Region to DS9 region string . |
232,705 | def write_ds9 ( regions , filename , coordsys = 'fk5' , fmt = '.6f' , radunit = 'deg' ) : output = ds9_objects_to_string ( regions , coordsys , fmt , radunit ) with open ( filename , 'w' ) as fh : fh . write ( output ) | Converts a list of ~regions . Region to DS9 string and write to file . |
232,706 | def crtf_objects_to_string ( regions , coordsys = 'fk5' , fmt = '.6f' , radunit = 'deg' ) : shapelist = to_shape_list ( regions , coordsys ) return shapelist . to_crtf ( coordsys , fmt , radunit ) | Converts a list of ~regions . Region to CRTF region string . |
232,707 | def write_crtf ( regions , filename , coordsys = 'fk5' , fmt = '.6f' , radunit = 'deg' ) : output = crtf_objects_to_string ( regions , coordsys , fmt , radunit ) with open ( filename , 'w' ) as fh : fh . write ( output ) | Converts a list of ~regions . Region to CRTF string and write to file . |
232,708 | def corners ( self ) : corners = [ ( - self . width / 2 , - self . height / 2 ) , ( self . width / 2 , - self . height / 2 ) , ( self . width / 2 , self . height / 2 ) , ( - self . width / 2 , self . height / 2 ) , ] rotmat = [ [ np . cos ( self . angle ) , np . sin ( self . angle ) ] , [ - np . sin ( self . angle ) , ... | Return the x y coordinate pairs that define the corners |
232,709 | def to_polygon ( self ) : x , y = self . corners . T vertices = PixCoord ( x = x , y = y ) return PolygonPixelRegion ( vertices = vertices , meta = self . meta , visual = self . visual ) | Return a 4 - cornered polygon equivalent to this rectangle |
232,710 | def _lower_left_xy ( self ) : hw = self . width / 2. hh = self . height / 2. sint = np . sin ( self . angle ) cost = np . cos ( self . angle ) dx = ( hh * sint ) - ( hw * cost ) dy = - ( hh * cost ) - ( hw * sint ) x = self . center . x + dx y = self . center . y + dy return x , y | Compute lower left xy position . |
232,711 | def _make_annulus_path ( patch_inner , patch_outer ) : import matplotlib . path as mpath path_inner = patch_inner . get_path ( ) transform_inner = patch_inner . get_transform ( ) path_inner = transform_inner . transform_path ( path_inner ) path_outer = patch_outer . get_path ( ) transform_outer = patch_outer . get_tran... | Defines a matplotlib annulus path from two patches . |
232,712 | def read_fits_region ( filename , errors = 'strict' ) : regions = [ ] hdul = fits . open ( filename ) for hdu in hdul : if hdu . name == 'REGION' : table = Table . read ( hdu ) wcs = WCS ( hdu . header , keysel = [ 'image' , 'binary' , 'pixel' ] ) regions_list = FITSRegionParser ( table , errors ) . shapes . to_regions... | Reads a FITS region file and scans for any fits regions table and converts them into Region objects . |
232,713 | def to_shape_list ( region_list , coordinate_system = 'fk5' ) : shape_list = ShapeList ( ) for region in region_list : coord = [ ] if isinstance ( region , SkyRegion ) : reg_type = region . __class__ . __name__ [ : - 9 ] . lower ( ) else : reg_type = region . __class__ . __name__ [ : - 11 ] . lower ( ) for val in regio... | Converts a list of regions into a regions . ShapeList object . |
232,714 | def to_ds9_meta ( shape_meta ) : valid_keys = [ 'symbol' , 'include' , 'tag' , 'line' , 'comment' , 'name' , 'select' , 'highlite' , 'fixed' , 'label' , 'text' , 'edit' , 'move' , 'rotate' , 'delete' , 'source' , 'background' ] valid_keys += [ 'color' , 'dash' , 'linewidth' , 'font' , 'dashlist' , 'fill' , 'textangle' ... | Makes the meta data DS9 compatible by filtering and mapping the valid keys |
232,715 | def _to_io_meta ( shape_meta , valid_keys , key_mappings ) : meta = dict ( ) for key in shape_meta : if key in valid_keys : meta [ key_mappings . get ( key , key ) ] = shape_meta [ key ] return meta | This is used to make meta data compatible with a specific io by filtering and mapping to it s valid keys |
232,716 | def convert_coords ( self ) : if self . coordsys in [ 'image' , 'physical' ] : coords = self . _convert_pix_coords ( ) else : coords = self . _convert_sky_coords ( ) if self . region_type == 'line' : coords = [ coords [ 0 ] [ 0 ] , coords [ 0 ] [ 1 ] ] if self . region_type == 'text' : coords . append ( self . meta [ '... | Process list of coordinates |
232,717 | def _convert_sky_coords ( self ) : parsed_angles = [ ( x , y ) for x , y in zip ( self . coord [ : - 1 : 2 ] , self . coord [ 1 : : 2 ] ) if ( isinstance ( x , coordinates . Angle ) and isinstance ( y , coordinates . Angle ) ) ] frame = coordinates . frame_transform_graph . lookup_name ( self . coordsys ) lon , lat = z... | Convert to sky coordinates |
232,718 | def _convert_pix_coords ( self ) : if self . region_type in [ 'polygon' , 'line' ] : coords = [ PixCoord ( self . coord [ 0 : : 2 ] , self . coord [ 1 : : 2 ] ) ] else : temp = [ _ . value for _ in self . coord ] coord = PixCoord ( temp [ 0 ] , temp [ 1 ] ) coords = [ coord ] + temp [ 2 : ] if self . region_type in [ '... | Convert to pixel coordinates regions . PixCoord |
232,719 | def to_region ( self ) : coords = self . convert_coords ( ) log . debug ( coords ) viz_keywords = [ 'color' , 'dash' , 'dashlist' , 'width' , 'font' , 'symsize' , 'symbol' , 'symsize' , 'fontsize' , 'fontstyle' , 'usetex' , 'labelpos' , 'labeloff' , 'linewidth' , 'linestyle' , 'point' , 'textangle' , 'fontweight' ] if ... | Converts to region regions . Region object |
232,720 | def check_crtf ( self ) : if self . region_type not in regions_attributes : raise ValueError ( "'{0}' is not a valid region type in this package" "supported by CRTF" . format ( self . region_type ) ) if self . coordsys not in valid_coordsys [ 'CRTF' ] : raise ValueError ( "'{0}' is not a valid coordinate reference fram... | Checks for CRTF compatibility . |
232,721 | def check_ds9 ( self ) : if self . region_type not in regions_attributes : raise ValueError ( "'{0}' is not a valid region type in this package" "supported by DS9" . format ( self . region_type ) ) if self . coordsys not in valid_coordsys [ 'DS9' ] : raise ValueError ( "'{0}' is not a valid coordinate reference frame "... | Checks for DS9 compatibility . |
232,722 | def _validate ( self ) : if self . region_type not in regions_attributes : raise ValueError ( "'{0}' is not a valid region type in this package" . format ( self . region_type ) ) if self . coordsys not in valid_coordsys [ 'DS9' ] + valid_coordsys [ 'CRTF' ] : raise ValueError ( "'{0}' is not a valid coordinate referenc... | Checks whether all the attributes of this object is valid . |
232,723 | def read_crtf ( filename , errors = 'strict' ) : with open ( filename ) as fh : if regex_begin . search ( fh . readline ( ) ) : region_string = fh . read ( ) parser = CRTFParser ( region_string , errors ) return parser . shapes . to_regions ( ) else : raise CRTFRegionParserError ( 'Every CRTF Region must start with "#C... | Reads a CRTF region file and returns a list of region objects . |
232,724 | def parse_line ( self , line ) : if line == '' : return if regex_comment . search ( line ) : return global_parameters = regex_global . search ( line ) if global_parameters : self . parse_global_meta ( global_parameters . group ( 'parameters' ) ) return crtf_line = regex_line . search ( line ) if crtf_line : region = re... | Parses a single line . |
232,725 | def parse ( self ) : self . convert_meta ( ) self . coordsys = self . meta . get ( 'coord' , 'image' ) . lower ( ) self . set_coordsys ( ) self . convert_coordinates ( ) self . make_shape ( ) | Starting point to parse the CRTF region string . |
232,726 | def set_coordsys ( self ) : if self . coordsys . lower ( ) in self . coordsys_mapping : self . coordsys = self . coordsys_mapping [ self . coordsys . lower ( ) ] | Mapping to astropy s coordinate system name |
232,727 | def convert_coordinates ( self ) : coord_list_str = regex_coordinate . findall ( self . reg_str ) + regex_length . findall ( self . reg_str ) coord_list = [ ] if self . region_type == 'poly' : if len ( coord_list_str ) < 4 : self . _raise_error ( 'Not in proper format: {} polygon should have > 4 coordinates' . format (... | Convert coordinate string to ~astropy . coordinates . Angle or ~astropy . units . quantity . Quantity objects |
232,728 | def convert_meta ( self ) : if self . meta_str : self . meta_str = regex_meta . findall ( self . meta_str + ',' ) if self . meta_str : for par in self . meta_str : if par [ 0 ] is not '' : val1 = par [ 0 ] val2 = par [ 1 ] else : val1 = par [ 2 ] val2 = par [ 3 ] val1 = val1 . strip ( ) val2 = val2 . strip ( ) if val1 ... | Parses the meta_str to python dictionary and stores in meta attribute . |
232,729 | def fits_region_objects_to_table ( regions ) : for reg in regions : if isinstance ( reg , SkyRegion ) : raise TypeError ( 'Every region must be a pixel region' . format ( reg ) ) shape_list = to_shape_list ( regions , coordinate_system = 'image' ) return shape_list . to_fits ( ) | Converts list of regions to FITS region table . |
232,730 | def write_fits_region ( filename , regions , header = None ) : output = fits_region_objects_to_table ( regions ) bin_table = fits . BinTableHDU ( data = output , header = header ) bin_table . writeto ( filename ) | Converts list of regions to FITS region table and write to a file . |
232,731 | def make_example_dataset ( data = 'simulated' , config = None ) : if data == 'simulated' : return ExampleDatasetSimulated ( config = config ) elif data == 'fermi' : return ExampleDatasetFermi ( config = config ) else : raise ValueError ( 'Invalid selection data: {}' . format ( data ) ) | Make example dataset . |
232,732 | def _table_to_bintable ( table ) : data = table . as_array ( ) header = fits . Header ( ) header . update ( table . meta ) name = table . meta . pop ( 'name' , None ) return fits . BinTableHDU ( data , header , name = name ) | Convert ~astropy . table . Table to astropy . io . fits . BinTable . |
232,733 | def read_ds9 ( filename , errors = 'strict' ) : with open ( filename ) as fh : region_string = fh . read ( ) parser = DS9Parser ( region_string , errors = errors ) return parser . shapes . to_regions ( ) | Read a DS9 region file in as a list of ~regions . Region objects . |
232,734 | def set_coordsys ( self , coordsys ) : if coordsys in self . coordsys_mapping : self . coordsys = self . coordsys_mapping [ coordsys ] else : self . coordsys = coordsys | Transform coordinate system |
232,735 | def run ( self ) : for line_ in self . region_string . split ( '\n' ) : for line in line_ . split ( ";" ) : self . parse_line ( line ) log . debug ( 'Global state: {}' . format ( self ) ) | Run all steps |
232,736 | def parse_meta ( meta_str ) : keys_vals = [ ( x , y ) for x , _ , y in regex_meta . findall ( meta_str . strip ( ) ) ] extra_text = regex_meta . split ( meta_str . strip ( ) ) [ - 1 ] result = OrderedDict ( ) for key , val in keys_vals : val = val . strip ( ) . strip ( "'" ) . strip ( '"' ) if key == 'text' : val = val... | Parse the metadata for a single ds9 region string . |
232,737 | def parse_region ( self , include , region_type , region_end , line ) : if self . coordsys is None : raise DS9RegionParserError ( "No coordinate system specified and a" " region has been found." ) else : helper = DS9RegionParser ( coordsys = self . coordsys , include = include , region_type = region_type , region_end =... | Extract a Shape from a region string |
232,738 | def parse ( self ) : log . debug ( self ) self . parse_composite ( ) self . split_line ( ) self . convert_coordinates ( ) self . convert_meta ( ) self . make_shape ( ) log . debug ( self ) | Convert line to shape object |
232,739 | def split_line ( self ) : hash_or_end = self . line . find ( "#" ) temp = self . line [ self . region_end : hash_or_end ] . strip ( " |" ) self . coord_str = regex_paren . sub ( "" , temp ) if hash_or_end >= 0 : self . meta_str = self . line [ hash_or_end : ] else : self . meta_str = "" | Split line into coordinates and meta string |
232,740 | def convert_coordinates ( self ) : coord_list = [ ] elements = [ x for x in regex_splitter . split ( self . coord_str ) if x ] element_parsers = self . language_spec [ self . region_type ] for ii , ( element , element_parser ) in enumerate ( zip ( elements , element_parsers ) ) : if element_parser is coordinate : unit ... | Convert coordinate string to objects |
232,741 | def convert_meta ( self ) : meta_ = DS9Parser . parse_meta ( self . meta_str ) self . meta = copy . deepcopy ( self . global_meta ) self . meta . update ( meta_ ) self . include = self . meta . get ( 'include' , True ) if self . include == '' else self . include != '-' self . meta [ 'include' ] = self . include | Convert meta string to dict |
232,742 | def _validate ( val , name , expected = 'any' ) : if not isinstance ( val , PixCoord ) : raise TypeError ( '{} must be a PixCoord' . format ( name ) ) if expected == 'any' : pass elif expected == 'scalar' : if not val . isscalar : raise ValueError ( '{} must be a scalar PixCoord' . format ( name ) ) elif expected == 'n... | Validate that a given object is an appropriate PixCoord . |
232,743 | def to_sky ( self , wcs , origin = _DEFAULT_WCS_ORIGIN , mode = _DEFAULT_WCS_MODE ) : return SkyCoord . from_pixel ( xp = self . x , yp = self . y , wcs = wcs , origin = origin , mode = mode , ) | Convert this PixCoord to ~astropy . coordinates . SkyCoord . |
232,744 | def from_sky ( cls , skycoord , wcs , origin = _DEFAULT_WCS_ORIGIN , mode = _DEFAULT_WCS_MODE ) : x , y = skycoord . to_pixel ( wcs = wcs , origin = origin , mode = mode ) return cls ( x = x , y = y ) | Create PixCoord from ~astropy . coordinates . SkyCoord . |
232,745 | def separation ( self , other ) : r dx = other . x - self . x dy = other . y - self . y return np . hypot ( dx , dy ) | r Separation to another pixel coordinate . |
232,746 | def skycoord_to_pixel_scale_angle ( skycoord , wcs , small_offset = 1 * u . arcsec ) : x , y = skycoord_to_pixel ( skycoord , wcs , mode = skycoord_to_pixel_mode ) pixcoord = PixCoord ( x = x , y = y ) r_old = skycoord . represent_as ( 'unitspherical' ) dlat = small_offset r_new = UnitSphericalRepresentation ( r_old . ... | Convert a set of SkyCoord coordinates into pixel coordinates pixel scales and position angles . |
232,747 | def assert_angle ( name , q ) : if isinstance ( q , u . Quantity ) : if q . unit . physical_type == 'angle' : pass else : raise ValueError ( "{0} should have angular units" . format ( name ) ) else : raise TypeError ( "{0} should be a Quantity instance" . format ( name ) ) | Check that q is an angular ~astropy . units . Quantity . |
232,748 | def _silence ( ) : old_stdout = sys . stdout old_stderr = sys . stderr sys . stdout = _DummyFile ( ) sys . stderr = _DummyFile ( ) exception_occurred = False try : yield except : exception_occurred = True sys . stdout = old_stdout sys . stderr = old_stderr raise if not exception_occurred : sys . stdout = old_stdout sys... | A context manager that silences sys . stdout and sys . stderr . |
232,749 | def use_astropy_helpers ( ** kwargs ) : global BOOTSTRAPPER config = BOOTSTRAPPER . config config . update ( ** kwargs ) BOOTSTRAPPER = _Bootstrapper ( ** config ) BOOTSTRAPPER . run ( ) | Ensure that the astropy_helpers module is available and is importable . This supports automatic submodule initialization if astropy_helpers is included in a project as a git submodule or will download it from PyPI if necessary . |
232,750 | def config ( self ) : return dict ( ( optname , getattr ( self , optname ) ) for optname , _ in CFG_OPTIONS if hasattr ( self , optname ) ) | A dict containing the options this _Bootstrapper was configured with . |
232,751 | def get_local_directory_dist ( self ) : if not os . path . isdir ( self . path ) : return log . info ( 'Attempting to import astropy_helpers from {0} {1!r}' . format ( 'submodule' if self . is_submodule else 'directory' , self . path ) ) dist = self . _directory_import ( ) if dist is None : log . warn ( 'The requested ... | Handle importing a vendored package from a subdirectory of the source distribution . |
232,752 | def get_local_file_dist ( self ) : if not os . path . isfile ( self . path ) : return log . info ( 'Attempting to unpack and import astropy_helpers from ' '{0!r}' . format ( self . path ) ) try : dist = self . _do_download ( find_links = [ self . path ] ) except Exception as e : if DEBUG : raise log . warn ( 'Failed to... | Handle importing from a source archive ; this also uses setup_requires but points easy_install directly to the source archive . |
232,753 | def _directory_import ( self ) : path = os . path . abspath ( self . path ) ws = pkg_resources . WorkingSet ( [ ] ) ws . add_entry ( path ) dist = ws . by_key . get ( DIST_NAME ) if dist is None : setup_py = os . path . join ( path , 'setup.py' ) if os . path . isfile ( setup_py ) : sp . check_output ( [ sys . executab... | Import astropy_helpers from the given path which will be added to sys . path . |
232,754 | def _check_submodule ( self ) : if ( self . path is None or ( os . path . exists ( self . path ) and not os . path . isdir ( self . path ) ) ) : return False if self . use_git : return self . _check_submodule_using_git ( ) else : return self . _check_submodule_no_git ( ) | Check if the given path is a git submodule . |
232,755 | def sdot ( U , V ) : nu = U . ndim return np . tensordot ( U , V , axes = ( nu - 1 , 0 ) ) | Computes the tensorproduct reducing last dimensoin of U with first dimension of V . For matrices it is equal to regular matrix product . |
232,756 | def set_values ( self , x ) : x = numpy . atleast_2d ( x ) x = x . real C_inv = self . __C_inv__ theta = numpy . dot ( x , C_inv ) self . theta = theta return theta | Updates self . theta parameter . No returns values |
232,757 | def tauchen ( N , mu , rho , sigma , m = 2 ) : Z = np . zeros ( ( N , 1 ) ) Zprob = np . zeros ( ( N , N ) ) a = ( 1 - rho ) * mu Z [ - 1 ] = m * math . sqrt ( sigma ** 2 / ( 1 - ( rho ** 2 ) ) ) Z [ 0 ] = - 1 * Z [ - 1 ] zstep = ( Z [ - 1 ] - Z [ 0 ] ) / ( N - 1 ) for i in range ( 1 , N ) : Z [ i ] = Z [ 0 ] + zstep *... | Approximate an AR1 process by a finite markov chain using Tauchen s method . |
232,758 | def rouwenhorst ( rho , sigma , N ) : from numpy import sqrt , linspace , array , zeros sigma = float ( sigma ) if N == 1 : nodes = array ( [ 0.0 ] ) transitions = array ( [ [ 1.0 ] ] ) return [ nodes , transitions ] p = ( rho + 1 ) / 2 q = p nu = sqrt ( ( N - 1 ) / ( 1 - rho ** 2 ) ) * sigma nodes = linspace ( - nu , ... | Approximate an AR1 process by a finite markov chain using Rouwenhorst s method . |
232,759 | def tensor_markov ( * args ) : if len ( args ) > 2 : m1 = args [ 0 ] m2 = args [ 1 ] tail = args [ 2 : ] prod = tensor_markov ( m1 , m2 ) return tensor_markov ( prod , tail ) elif len ( args ) == 2 : m1 , m2 = args n1 , t1 = m1 n2 , t2 = m2 n1 = np . array ( n1 , dtype = float ) n2 = np . array ( n2 , dtype = float ) t... | Computes the product of two independent markov chains . |
232,760 | def dynare_import ( filename , full_output = False , debug = False ) : import os basename = os . path . basename ( filename ) fname = re . compile ( '(.*)\.(.*)' ) . match ( basename ) . group ( 1 ) f = open ( filename ) txt = f . read ( ) model = parse_dynare_text ( txt , full_output = full_output , debug = debug ) mo... | Imports model defined in specified file |
232,761 | def _shocks_to_epsilons ( model , shocks , T ) : n_e = len ( model . calibration [ 'exogenous' ] ) if isinstance ( shocks , pd . DataFrame ) : shocks = { k : shocks [ k ] . tolist ( ) for k in shocks . columns } if isinstance ( shocks , dict ) : epsilons = np . zeros ( ( T + 1 , n_e ) ) for ( i , k ) in enumerate ( mod... | Helper function to support input argument shocks being one of many different data types . Will always return a T n_e matrix . |
232,762 | def clear_all ( ) : frame = inspect . currentframe ( ) . f_back try : if frame . f_globals . get ( 'variables_order' ) : del frame . f_globals [ 'variables_order' ] if frame . f_globals . get ( 'parameters_order' ) : del frame . f_globals [ 'parameters_order' ] finally : del frame | Clears all parameters variables and shocks defined previously |
232,763 | def nonlinear_system ( model , initial_dr = None , maxit = 10 , tol = 1e-8 , grid = { } , distribution = { } , verbose = True ) : if verbose : headline = '|{0:^4} | {1:10} | {2:8} |' headline = headline . format ( 'N' , ' Error' , 'Time' ) stars = '-' * len ( headline ) print ( stars ) print ( headline ) print ( stars ... | Finds a global solution for model by solving one large system of equations using a simple newton algorithm . |
232,764 | def gauss_hermite_nodes ( orders , sigma , mu = None ) : if isinstance ( orders , int ) : orders = [ orders ] import numpy if mu is None : mu = numpy . array ( [ 0 ] * sigma . shape [ 0 ] ) herms = [ hermgauss ( i ) for i in orders ] points = [ h [ 0 ] * numpy . sqrt ( 2 ) for h in herms ] weights = [ h [ 1 ] / numpy .... | Computes the weights and nodes for Gauss Hermite quadrature . |
232,765 | def newton ( f , x , verbose = False , tol = 1e-6 , maxit = 5 , jactype = 'serial' ) : if verbose : print = lambda txt : old_print ( txt ) else : print = lambda txt : None it = 0 error = 10 converged = False maxbacksteps = 30 x0 = x if jactype == 'sparse' : from scipy . sparse . linalg import spsolve as solve elif jact... | Solve nonlinear system using safeguarded Newton iterations |
232,766 | def qzordered ( A , B , crit = 1.0 ) : "Eigenvalues bigger than crit are sorted in the top-left." TOL = 1e-10 def select ( alpha , beta ) : return alpha ** 2 > crit * beta ** 2 [ S , T , alpha , beta , U , V ] = ordqz ( A , B , output = 'real' , sort = select ) eigval = abs ( numpy . diag ( S ) / numpy . diag ( T ) ) r... | Eigenvalues bigger than crit are sorted in the top - left . |
232,767 | def ordqz ( A , B , sort = 'lhp' , output = 'real' , overwrite_a = False , overwrite_b = False , check_finite = True ) : import warnings import numpy as np from numpy import asarray_chkfinite from scipy . linalg . misc import LinAlgError , _datacopied from scipy . linalg . lapack import get_lapack_funcs from scipy . _l... | QZ decomposition for a pair of matrices with reordering . |
232,768 | def parameterized_expectations_direct ( model , verbose = False , initial_dr = None , pert_order = 1 , grid = { } , distribution = { } , maxit = 100 , tol = 1e-8 ) : t1 = time . time ( ) g = model . functions [ 'transition' ] d = model . functions [ 'direct_response' ] h = model . functions [ 'expectation' ] parms = mo... | Finds a global solution for model using parameterized expectations function . Requires the model to be written with controls as a direct function of the model objects . |
232,769 | def numdiff ( fun , args ) : epsilon = 1e-8 args = list ( args ) v0 = fun ( * args ) N = v0 . shape [ 0 ] l_v = len ( v0 ) dvs = [ ] for i , a in enumerate ( args ) : l_a = ( a ) . shape [ 1 ] dv = numpy . zeros ( ( N , l_v , l_a ) ) nargs = list ( args ) for j in range ( l_a ) : xx = args [ i ] . copy ( ) xx [ : , j ]... | Vectorized numerical differentiation |
232,770 | def bandpass_filter ( data , k , w1 , w2 ) : data = np . asarray ( data ) low_w = np . pi * 2 / w2 high_w = np . pi * 2 / w1 bweights = np . zeros ( 2 * k + 1 ) bweights [ k ] = ( high_w - low_w ) / np . pi j = np . arange ( 1 , int ( k ) + 1 ) weights = 1 / ( np . pi * j ) * ( sin ( high_w * j ) - sin ( low_w * j ) ) ... | This function will apply a bandpass filter to data . It will be kth order and will select the band between w1 and w2 . |
232,771 | def dprint ( s ) : import inspect frameinfo = inspect . stack ( ) [ 1 ] callerframe = frameinfo . frame d = callerframe . f_locals if ( isinstance ( s , str ) ) : val = eval ( s , d ) else : val = s cc = frameinfo . code_context [ 0 ] import re regex = re . compile ( "dprint\((.*)\)" ) res = regex . search ( cc ) s = r... | Prints s with additional debugging informations |
232,772 | def non_decreasing_series ( n , size ) : if size == 1 : return [ [ a ] for a in range ( n ) ] else : lc = non_decreasing_series ( n , size - 1 ) ll = [ ] for l in lc : last = l [ - 1 ] for i in range ( last , n ) : e = l + [ i ] ll . append ( e ) return ll | Lists all combinations of 0 ... n - 1 in increasing order |
232,773 | def higher_order_diff ( eqs , syms , order = 2 ) : import numpy eqs = list ( [ sympy . sympify ( eq ) for eq in eqs ] ) syms = list ( [ sympy . sympify ( s ) for s in syms ] ) neq = len ( eqs ) p = len ( syms ) D = [ numpy . array ( eqs ) ] orders = [ ] for i in range ( 1 , order + 1 ) : par = D [ i - 1 ] mat = numpy .... | Takes higher order derivatives of a list of equations w . r . t a list of paramters |
232,774 | def get_ranked_players ( ) : rankings_page = requests . get ( RANKINGS_URL ) root = etree . HTML ( rankings_page . text ) player_rows = root . xpath ( '//div[@id="ranked"]//tr' ) for row in player_rows [ 1 : ] : player_row = row . xpath ( 'td[@class!="country"]//text()' ) yield _Player ( name = player_row [ 1 ] , count... | Get the list of the first 100 ranked players . |
232,775 | def difference ( cls , first , second ) : first , second = cls ( first ) , cls ( second ) rank_list = list ( cls ) return abs ( rank_list . index ( first ) - rank_list . index ( second ) ) | Tells the numerical difference between two ranks . |
232,776 | def make_random ( cls ) : self = object . __new__ ( cls ) self . rank = Rank . make_random ( ) self . suit = Suit . make_random ( ) return self | Returns a random Card instance . |
232,777 | def twoplustwo_player ( username ) : from . website . twoplustwo import ForumMember , AmbiguousUserNameError , UserNotFoundError try : member = ForumMember ( username ) except UserNotFoundError : raise click . ClickException ( 'User "%s" not found!' % username ) except AmbiguousUserNameError as e : click . echo ( 'Got ... | Get profile information about a Two plus Two Forum member given the username . |
232,778 | def p5list ( num ) : from . website . pocketfives import get_ranked_players format_str = '{:>4.4} {!s:<15.13}{!s:<18.15}{!s:<9.6}{!s:<10.7}' '{!s:<14.11}{!s:<12.9}{!s:<12.9}{!s:<12.9}{!s:<4.4}' click . echo ( format_str . format ( 'Rank' , 'Player name' , 'Country' , 'Triple' , 'Monthly' , 'Biggest cash' , 'PLB score... | List pocketfives ranked players max 100 if no NUM or NUM if specified . |
232,779 | def psstatus ( ) : from . website . pokerstars import get_status _print_header ( 'PokerStars status' ) status = get_status ( ) _print_values ( ( 'Info updated' , status . updated ) , ( 'Tables' , status . tables ) , ( 'Players' , status . players ) , ( 'Active tournaments' , status . active_tournaments ) , ( 'Total tou... | Shows PokerStars status such as number of players tournaments . |
232,780 | def notes ( self ) : return tuple ( self . _get_note_data ( note ) for note in self . root . iter ( 'note' ) ) | Tuple of notes .. |
232,781 | def labels ( self ) : return tuple ( _Label ( label . get ( 'id' ) , label . get ( 'color' ) , label . text ) for label in self . root . iter ( 'label' ) ) | Tuple of labels . |
232,782 | def add_note ( self , player , text , label = None , update = None ) : if label is not None and ( label not in self . label_names ) : raise LabelNotFoundError ( 'Invalid label: {}' . format ( label ) ) if update is None : update = datetime . utcnow ( ) update = update . strftime ( '%s' ) label_id = self . _get_label_id... | Add a note to the xml . If update param is None it will be the current time . |
232,783 | def append_note ( self , player , text ) : note = self . _find_note ( player ) note . text += text | Append text to an already existing note . |
232,784 | def prepend_note ( self , player , text ) : note = self . _find_note ( player ) note . text = text + note . text | Prepend text to an already existing note . |
232,785 | def get_label ( self , name ) : label_tag = self . _find_label ( name ) return _Label ( label_tag . get ( 'id' ) , label_tag . get ( 'color' ) , label_tag . text ) | Find the label by name . |
232,786 | def add_label ( self , name , color ) : color_upper = color . upper ( ) if not self . _color_re . match ( color_upper ) : raise ValueError ( 'Invalid color: {}' . format ( color ) ) labels_tag = self . root [ 0 ] last_id = int ( labels_tag [ - 1 ] . get ( 'id' ) ) new_id = str ( last_id + 1 ) new_label = etree . Elemen... | Add a new label . It s id will automatically be calculated . |
232,787 | def del_label ( self , name ) : labels_tag = self . root [ 0 ] labels_tag . remove ( self . _find_label ( name ) ) | Delete a label by name . |
232,788 | def save ( self , filename ) : with open ( filename , 'w' ) as fp : fp . write ( str ( self ) ) | Save the note XML to a file . |
232,789 | def board ( self ) : board = [ ] if self . flop : board . extend ( self . flop . cards ) if self . turn : board . append ( self . turn ) if self . river : board . append ( self . river ) return tuple ( board ) if board else None | Calculates board from flop turn and river . |
232,790 | def _parse_date ( self , date_string ) : date = datetime . strptime ( date_string , self . _DATE_FORMAT ) self . date = self . _TZ . localize ( date ) . astimezone ( pytz . UTC ) | Parse the date_string and return a datetime object as UTC . |
232,791 | def _split_raw ( self ) : self . _splitted = self . _split_re . split ( self . raw ) self . _sections = [ ind for ind , elem in enumerate ( self . _splitted ) if not elem ] | Split hand history by sections . |
232,792 | def _get_timezone ( self , root ) : tz_str = root . xpath ( '//div[@class="smallfont" and @align="center"]' ) [ 0 ] . text hours = int ( self . _tz_re . search ( tz_str ) . group ( 1 ) ) return tzoffset ( tz_str , hours * 60 ) | Find timezone informatation on bottom of the page . |
232,793 | def get_current_tournaments ( ) : schedule_page = requests . get ( TOURNAMENTS_XML_URL ) root = etree . XML ( schedule_page . content ) for tour in root . iter ( '{*}tournament' ) : yield _Tournament ( start_date = tour . findtext ( '{*}start_date' ) , name = tour . findtext ( '{*}name' ) , game = tour . findtext ( '{*... | Get the next 200 tournaments from pokerstars . |
232,794 | def _filter_file ( src , dest , subst ) : substre = re . compile ( r'\$(%s)' % '|' . join ( subst . keys ( ) ) ) def repl ( m ) : return subst [ m . group ( 1 ) ] with open ( src , "rt" ) as sf , open ( dest , "wt" ) as df : while True : l = sf . readline ( ) if not l : break df . write ( re . sub ( substre , repl , l ... | Copy src to dest doing substitutions on the fly . |
232,795 | def _fixup_graphql_error ( self , data ) : original_data = data errors = data . get ( 'errors' ) original_errors = errors if not isinstance ( errors , list ) : self . logger . warning ( 'data["errors"] is not a list! Fix up data=%r' , data ) data = data . copy ( ) data [ 'errors' ] = [ { 'message' : str ( errors ) } ] ... | Given a possible GraphQL error payload make sure it s in shape . |
232,796 | def snippet ( code , locations , sep = ' | ' , colmark = ( '-' , '^' ) , context = 5 ) : if not locations : return [ ] lines = code . split ( '\n' ) offset = int ( len ( lines ) / 10 ) + 1 linenofmt = '%{}d' . format ( offset ) s = [ ] for loc in locations : line = max ( 0 , loc . get ( 'line' , 1 ) - 1 ) column = max ... | Given a code and list of locations convert to snippet lines . |
232,797 | def _create_non_null_wrapper ( name , t ) : 'creates type wrapper for non-null of given type' def __new__ ( cls , json_data , selection_list = None ) : if json_data is None : raise ValueError ( name + ' received null value' ) return t ( json_data , selection_list ) def __to_graphql_input__ ( value , indent = 0 , indent... | creates type wrapper for non - null of given type |
232,798 | def _create_list_of_wrapper ( name , t ) : 'creates type wrapper for list of given type' def __new__ ( cls , json_data , selection_list = None ) : if json_data is None : return None return [ t ( v , selection_list ) for v in json_data ] def __to_graphql_input__ ( value , indent = 0 , indent_string = ' ' ) : r = [ ] fo... | creates type wrapper for list of given type |
232,799 | def add_query_to_url ( url , extra_query ) : split = urllib . parse . urlsplit ( url ) merged_query = urllib . parse . parse_qsl ( split . query ) if isinstance ( extra_query , dict ) : for k , v in extra_query . items ( ) : if not isinstance ( v , ( tuple , list ) ) : merged_query . append ( ( k , v ) ) else : for cv ... | Adds an extra query to URL returning the new URL . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.