idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
242,500 | def gaussian1d_moments ( data , mask = None ) : if np . any ( ~ np . isfinite ( data ) ) : data = np . ma . masked_invalid ( data ) warnings . warn ( 'Input data contains input values (e.g. NaNs or infs), ' 'which were automatically masked.' , AstropyUserWarning ) else : data = np . ma . array ( data ) if mask is not N... | Estimate 1D Gaussian parameters from the moments of 1D data . | 251 | 15 |
242,501 | def fit_2dgaussian ( data , error = None , mask = None ) : from . . morphology import data_properties # prevent circular imports data = np . ma . asanyarray ( data ) if mask is not None and mask is not np . ma . nomask : mask = np . asanyarray ( mask ) if data . shape != mask . shape : raise ValueError ( 'data and mask... | Fit a 2D Gaussian plus a constant to a 2D image . | 584 | 15 |
242,502 | def centroid_1dg ( data , error = None , mask = None ) : data = np . ma . asanyarray ( data ) if mask is not None and mask is not np . ma . nomask : mask = np . asanyarray ( mask ) if data . shape != mask . shape : raise ValueError ( 'data and mask must have the same shape.' ) data . mask |= mask if np . any ( ~ np . i... | Calculate the centroid of a 2D array by fitting 1D Gaussians to the marginal x and y distributions of the array . | 572 | 29 |
242,503 | def centroid_sources ( data , xpos , ypos , box_size = 11 , footprint = None , error = None , mask = None , centroid_func = centroid_com ) : xpos = np . atleast_1d ( xpos ) ypos = np . atleast_1d ( ypos ) if xpos . ndim != 1 : raise ValueError ( 'xpos must be a 1D array.' ) if ypos . ndim != 1 : raise ValueError ( 'ypo... | Calculate the centroid of sources at the defined positions . | 647 | 13 |
242,504 | def evaluate ( x , y , constant , amplitude , x_mean , y_mean , x_stddev , y_stddev , theta ) : model = Const2D ( constant ) ( x , y ) + Gaussian2D ( amplitude , x_mean , y_mean , x_stddev , y_stddev , theta ) ( x , y ) return model | Two dimensional Gaussian plus constant function . | 86 | 8 |
242,505 | def evaluate ( self , x , y , flux , x_0 , y_0 ) : # Convert x and y to index arrays x = ( x - x_0 + 0.5 + self . prf_shape [ 1 ] // 2 ) . astype ( 'int' ) y = ( y - y_0 + 0.5 + self . prf_shape [ 0 ] // 2 ) . astype ( 'int' ) # Get subpixel indices y_sub , x_sub = subpixel_indices ( ( y_0 , x_0 ) , self . subsampling ... | Discrete PRF model evaluation . | 283 | 7 |
242,506 | def _reproject ( wcs1 , wcs2 ) : import gwcs forward_origin = [ ] if isinstance ( wcs1 , fitswcs . WCS ) : forward = wcs1 . all_pix2world forward_origin = [ 0 ] elif isinstance ( wcs2 , gwcs . wcs . WCS ) : forward = wcs1 . forward_transform else : raise ValueError ( 'wcs1 must be an astropy.wcs.WCS or ' 'gwcs.wcs.WCS ... | Perform the forward transformation of wcs1 followed by the inverse transformation of wcs2 . | 272 | 19 |
242,507 | def get_version_info ( ) : from astropy import __version__ astropy_version = __version__ from photutils import __version__ photutils_version = __version__ return 'astropy: {0}, photutils: {1}' . format ( astropy_version , photutils_version ) | Return astropy and photutils versions . | 67 | 8 |
242,508 | def calc_total_error ( data , bkg_error , effective_gain ) : data = np . asanyarray ( data ) bkg_error = np . asanyarray ( bkg_error ) inputs = [ data , bkg_error , effective_gain ] has_unit = [ hasattr ( x , 'unit' ) for x in inputs ] use_units = all ( has_unit ) if any ( has_unit ) and not use_units : raise ValueErro... | Calculate a total error array combining a background - only error array with the Poisson noise of sources . | 543 | 22 |
242,509 | def to_sky ( self , wcs , mode = 'all' ) : sky_params = self . _to_sky_params ( wcs , mode = mode ) return SkyRectangularAperture ( * * sky_params ) | Convert the aperture to a SkyRectangularAperture object defined in celestial coordinates . | 50 | 17 |
242,510 | def to_sky ( self , wcs , mode = 'all' ) : sky_params = self . _to_sky_params ( wcs , mode = mode ) return SkyRectangularAnnulus ( * * sky_params ) | Convert the aperture to a SkyRectangularAnnulus object defined in celestial coordinates . | 50 | 17 |
242,511 | def to_pixel ( self , wcs , mode = 'all' ) : pixel_params = self . _to_pixel_params ( wcs , mode = mode ) return RectangularAperture ( * * pixel_params ) | Convert the aperture to a RectangularAperture object defined in pixel coordinates . | 49 | 16 |
242,512 | def to_pixel ( self , wcs , mode = 'all' ) : pixel_params = self . _to_pixel_params ( wcs , mode = mode ) return RectangularAnnulus ( * * pixel_params ) | Convert the aperture to a RectangularAnnulus object defined in pixel coordinates . | 49 | 16 |
242,513 | def _py2intround ( a ) : data = np . asanyarray ( a ) value = np . where ( data >= 0 , np . floor ( data + 0.5 ) , np . ceil ( data - 0.5 ) ) . astype ( int ) if not hasattr ( a , '__iter__' ) : value = np . asscalar ( value ) return value | Round the input to the nearest integer . | 85 | 8 |
242,514 | def _interpolate_missing_data ( data , mask , method = 'cubic' ) : from scipy import interpolate data_interp = np . array ( data , copy = True ) if len ( data_interp . shape ) != 2 : raise ValueError ( 'data must be a 2D array.' ) if mask . shape != data . shape : raise ValueError ( 'mask and data must have the same sh... | Interpolate missing data as identified by the mask keyword . | 286 | 12 |
242,515 | def _fit_star ( self , epsf , star , fitter , fitter_kwargs , fitter_has_fit_info , fit_boxsize ) : if fit_boxsize is not None : try : xcenter , ycenter = star . cutout_center large_slc , small_slc = overlap_slices ( star . shape , fit_boxsize , ( ycenter , xcenter ) , mode = 'strict' ) except ( PartialOverlapError , N... | Fit an ePSF model to a single star . | 821 | 11 |
242,516 | def _init_img_params ( param ) : if param is not None : param = np . atleast_1d ( param ) if len ( param ) == 1 : param = np . repeat ( param , 2 ) return param | Initialize 2D image - type parameters that can accept either a single or two values . | 50 | 18 |
242,517 | def _create_initial_epsf ( self , stars ) : oversampling = self . oversampling shape = self . shape # define the ePSF shape if shape is not None : shape = np . atleast_1d ( shape ) . astype ( int ) if len ( shape ) == 1 : shape = np . repeat ( shape , 2 ) else : x_shape = np . int ( np . ceil ( stars . _max_shape [ 1 ]... | Create an initial EPSFModel object . | 266 | 8 |
242,518 | def _resample_residual ( self , star , epsf ) : # find the integer index of EPSFStar pixels in the oversampled # ePSF grid x = epsf . _oversampling [ 0 ] * star . _xidx_centered y = epsf . _oversampling [ 1 ] * star . _yidx_centered epsf_xcenter , epsf_ycenter = epsf . origin xidx = _py2intround ( x + epsf_xcenter ) yi... | Compute a normalized residual image in the oversampled ePSF grid . | 435 | 16 |
242,519 | def _resample_residuals ( self , stars , epsf ) : shape = ( stars . n_good_stars , epsf . shape [ 0 ] , epsf . shape [ 1 ] ) star_imgs = np . zeros ( shape ) for i , star in enumerate ( stars . all_good_stars ) : star_imgs [ i , : , : ] = self . _resample_residual ( star , epsf ) return star_imgs | Compute normalized residual images for all the input stars . | 110 | 11 |
242,520 | def _smooth_epsf ( self , epsf_data ) : from scipy . ndimage import convolve if self . smoothing_kernel is None : return epsf_data elif self . smoothing_kernel == 'quartic' : # from Polynomial2D fit with degree=4 to 5x5 array of # zeros with 1. at the center # Polynomial2D(4, c0_0=0.04163265, c1_0=-0.76326531, # c2_0=0... | Smooth the ePSF array by convolving it with a kernel . | 789 | 15 |
242,521 | def _recenter_epsf ( self , epsf_data , epsf , centroid_func = centroid_com , box_size = 5 , maxiters = 20 , center_accuracy = 1.0e-4 ) : # Define an EPSFModel for the input data. This EPSFModel will be # used to evaluate the model on a shifted pixel grid to place the # centroid at the array center. epsf = EPSFModel ( ... | Calculate the center of the ePSF data and shift the data so the ePSF center is at the center of the ePSF data array . | 597 | 33 |
242,522 | def _build_epsf_step ( self , stars , epsf = None ) : if len ( stars ) < 1 : raise ValueError ( 'stars must contain at least one EPSFStar or ' 'LinkedEPSFStar object.' ) if epsf is None : # create an initial ePSF (array of zeros) epsf = self . _create_initial_epsf ( stars ) else : # improve the input ePSF epsf = copy .... | A single iteration of improving an ePSF . | 656 | 10 |
242,523 | def build_epsf ( self , stars , init_epsf = None ) : iter_num = 0 center_dist_sq = self . center_accuracy_sq + 1. centers = stars . cutout_center_flat n_stars = stars . n_stars fit_failed = np . zeros ( n_stars , dtype = bool ) dx_dy = np . zeros ( ( n_stars , 2 ) , dtype = np . float ) epsf = init_epsf dt = 0. while (... | Iteratively build an ePSF from star cutouts . | 691 | 12 |
242,524 | def _set_oversampling ( self , value ) : try : value = np . atleast_1d ( value ) . astype ( float ) if len ( value ) == 1 : value = np . repeat ( value , 2 ) except ValueError : raise ValueError ( 'Oversampling factors must be float' ) if np . any ( value <= 0 ) : raise ValueError ( 'Oversampling factors must be greate... | This is a private method because it s used in the initializer by the oversampling | 106 | 18 |
242,525 | def evaluate ( self , x , y , flux , x_0 , y_0 , use_oversampling = True ) : if use_oversampling : xi = self . _oversampling [ 0 ] * ( np . asarray ( x ) - x_0 ) yi = self . _oversampling [ 1 ] * ( np . asarray ( y ) - y_0 ) else : xi = np . asarray ( x ) - x_0 yi = np . asarray ( y ) - y_0 xi += self . _x_origin yi +=... | Evaluate the model on some input variables and provided model parameters . | 264 | 14 |
242,526 | def _find_bounds_1d ( data , x ) : idx = np . searchsorted ( data , x ) if idx == 0 : idx0 = 0 elif idx == len ( data ) : # pragma: no cover idx0 = idx - 2 else : idx0 = idx - 1 return idx0 | Find the index of the lower bound where x should be inserted into a to maintain order . | 77 | 18 |
242,527 | def _bilinear_interp ( xyref , zref , xi , yi ) : if len ( xyref ) != 4 : raise ValueError ( 'xyref must contain only 4 (x, y) pairs' ) if zref . shape [ 0 ] != 4 : raise ValueError ( 'zref must have a length of 4 on the first ' 'axis.' ) xyref = [ tuple ( i ) for i in xyref ] idx = sorted ( range ( len ( xyref ) ) , k... | Perform bilinear interpolation of four 2D arrays located at points on a regular grid . | 439 | 20 |
242,528 | def evaluate ( self , x , y , flux , x_0 , y_0 ) : # NOTE: this is needed because the PSF photometry routines input # length-1 values instead of scalars. TODO: fix the photometry # routines. if not np . isscalar ( x_0 ) : x_0 = x_0 [ 0 ] if not np . isscalar ( y_0 ) : y_0 = y_0 [ 0 ] if ( x_0 < self . _xgrid_min or x_0... | Evaluate the GriddedPSFModel for the input parameters . | 435 | 15 |
242,529 | def evaluate ( self , x , y , flux , x_0 , y_0 , sigma ) : return ( flux / 4 * ( ( self . _erf ( ( x - x_0 + 0.5 ) / ( np . sqrt ( 2 ) * sigma ) ) - self . _erf ( ( x - x_0 - 0.5 ) / ( np . sqrt ( 2 ) * sigma ) ) ) * ( self . _erf ( ( y - y_0 + 0.5 ) / ( np . sqrt ( 2 ) * sigma ) ) - self . _erf ( ( y - y_0 - 0.5 ) / (... | Model function Gaussian PSF model . | 163 | 8 |
242,530 | def evaluate ( self , x , y , flux , x_0 , y_0 ) : if self . xname is None : dx = x - x_0 else : dx = x setattr ( self . psfmodel , self . xname , x_0 ) if self . xname is None : dy = y - y_0 else : dy = y setattr ( self . psfmodel , self . yname , y_0 ) if self . fluxname is None : return ( flux * self . _psf_scale_fa... | The evaluation function for PRFAdapter . | 176 | 8 |
242,531 | def _isophote_list_to_table ( isophote_list ) : properties = OrderedDict ( ) properties [ 'sma' ] = 'sma' properties [ 'intens' ] = 'intens' properties [ 'int_err' ] = 'intens_err' properties [ 'eps' ] = 'ellipticity' properties [ 'ellip_err' ] = 'ellipticity_err' properties [ 'pa' ] = 'pa' properties [ 'pa_err' ] = 'p... | Convert an ~photutils . isophote . IsophoteList instance to a ~astropy . table . QTable . | 271 | 27 |
242,532 | def _compute_fluxes ( self ) : # Compute limits of square array that encloses circle. sma = self . sample . geometry . sma x0 = self . sample . geometry . x0 y0 = self . sample . geometry . y0 xsize = self . sample . image . shape [ 1 ] ysize = self . sample . image . shape [ 0 ] imin = max ( 0 , int ( x0 - sma - 0.5 )... | Compute integrated flux inside ellipse as well as inside a circle defined with the same semimajor axis . | 413 | 23 |
242,533 | def _compute_deviations ( self , sample , n ) : try : coeffs = fit_first_and_second_harmonics ( self . sample . values [ 0 ] , self . sample . values [ 2 ] ) coeffs = coeffs [ 0 ] model = first_and_second_harmonic_function ( self . sample . values [ 0 ] , coeffs ) residual = self . sample . values [ 2 ] - model c = fit... | Compute deviations from a perfect ellipse based on the amplitudes and errors for harmonic n . Note that we first subtract the first and second harmonics from the raw data . | 326 | 36 |
242,534 | def _compute_errors ( self ) : try : coeffs = fit_first_and_second_harmonics ( self . sample . values [ 0 ] , self . sample . values [ 2 ] ) covariance = coeffs [ 1 ] coeffs = coeffs [ 0 ] model = first_and_second_harmonic_function ( self . sample . values [ 0 ] , coeffs ) residual_rms = np . std ( self . sample . valu... | Compute parameter errors based on the diagonal of the covariance matrix of the four harmonic coefficients for harmonics n = 1 and n = 2 . | 454 | 29 |
242,535 | def fix_geometry ( self , isophote ) : self . sample . geometry . eps = isophote . sample . geometry . eps self . sample . geometry . pa = isophote . sample . geometry . pa self . sample . geometry . x0 = isophote . sample . geometry . x0 self . sample . geometry . y0 = isophote . sample . geometry . y0 | Fix the geometry of a problematic isophote to be identical to the input isophote . | 87 | 19 |
242,536 | def get_closest ( self , sma ) : index = ( np . abs ( self . sma - sma ) ) . argmin ( ) return self . _list [ index ] | Return the ~photutils . isophote . Isophote instance that has the closest semimajor axis length to the input semimajor axis . | 42 | 31 |
242,537 | def interpolate_masked_data ( data , mask , error = None , background = None ) : if data . shape != mask . shape : raise ValueError ( 'data and mask must have the same shape' ) data_out = np . copy ( data ) # do not alter input data mask_idx = mask . nonzero ( ) if mask_idx [ 0 ] . size == 0 : raise ValueError ( 'All i... | Interpolate over masked pixels in data and optional error or background images . | 410 | 15 |
242,538 | def ThreadsWithRunningExecServers ( self ) : socket_dir = '/tmp/pyringe_%s' % self . inferior . pid if os . path . isdir ( socket_dir ) : return [ int ( fname [ : - 9 ] ) for fname in os . listdir ( socket_dir ) if fname . endswith ( '.execsock' ) ] return [ ] | Returns a list of tids of inferior threads with open exec servers . | 87 | 14 |
242,539 | def SendToExecSocket ( self , code , tid = None ) : response = self . _SendToExecSocketRaw ( json . dumps ( code ) , tid ) return json . loads ( response ) | Inject python code into exec socket . | 42 | 8 |
242,540 | def CloseExecSocket ( self , tid = None ) : response = self . _SendToExecSocketRaw ( '__kill__' , tid ) if response != '__kill_ack__' : logging . warning ( 'May not have succeeded in closing socket, make sure ' 'using execsocks().' ) | Send closing request to exec socket . | 66 | 7 |
242,541 | def Backtrace ( self , to_string = False ) : if self . inferior . is_running : res = self . inferior . Backtrace ( ) if to_string : return res print res else : logging . error ( 'Not attached to any process.' ) | Get a backtrace of the current position . | 55 | 9 |
242,542 | def ListThreads ( self ) : if self . inferior . is_running : return self . inferior . threads logging . error ( 'Not attached to any process.' ) return [ ] | List the currently running python threads . | 38 | 7 |
242,543 | def extract_filename ( self ) : globals_gdbval = self . _gdbval [ 'f_globals' ] . cast ( GdbCache . DICT ) global_dict = libpython . PyDictObjectPtr ( globals_gdbval ) for key , value in global_dict . iteritems ( ) : if str ( key . proxyval ( set ( ) ) ) == '__file__' : return str ( value . proxyval ( set ( ) ) ) | Alternative way of getting the executed file which inspects globals . | 107 | 13 |
242,544 | def _UnserializableObjectFallback ( self , obj ) : if isinstance ( obj , libpython . PyInstanceObjectPtr ) : # old-style classes use 'classobj'/'instance' # get class attribute dictionary in_class = obj . pyop_field ( 'in_class' ) result_dict = in_class . pyop_field ( 'cl_dict' ) . proxyval ( set ( ) ) # let libpython.... | Handles sanitizing of unserializable objects for Json . | 635 | 14 |
242,545 | def _AcceptRPC ( self ) : request = self . _ReadObject ( ) if request [ 'func' ] == '__kill__' : self . ClearBreakpoints ( ) self . _WriteObject ( '__kill_ack__' ) return False if 'func' not in request or request [ 'func' ] . startswith ( '_' ) : raise RpcException ( 'Not a valid public API function.' ) rpc_result = ge... | Reads RPC request from stdin and processes it writing result to stdout . | 132 | 16 |
242,546 | def _UnpackGdbVal ( self , gdb_value ) : val_type = gdb_value . type . code if val_type == gdb . TYPE_CODE_INT or val_type == gdb . TYPE_CODE_ENUM : return int ( gdb_value ) if val_type == gdb . TYPE_CODE_VOID : return None if val_type == gdb . TYPE_CODE_PTR : return long ( gdb_value ) if val_type == gdb . TYPE_CODE_AR... | Unpacks gdb . Value objects and returns the best - matched python object . | 160 | 16 |
242,547 | def EnsureGdbPosition ( self , pid , tid , frame_depth ) : position = [ pid , tid , frame_depth ] if not pid : return if not self . IsAttached ( ) : try : self . Attach ( position ) except gdb . error as exc : raise PositionUnavailableException ( exc . message ) if gdb . selected_inferior ( ) . pid != pid : self . Deta... | Make sure our position matches the request . | 306 | 8 |
242,548 | def IsSymbolFileSane ( self , position ) : pos = [ position [ 0 ] , None , None ] self . EnsureGdbPosition ( * pos ) try : if GdbCache . DICT and GdbCache . TYPE and GdbCache . INTERP_HEAD : # pylint: disable=pointless-statement tstate = GdbCache . INTERP_HEAD [ 'tstate_head' ] tstate [ 'thread_id' ] frame = tstate [ '... | Performs basic sanity check by trying to look up a bunch of symbols . | 414 | 15 |
242,549 | def Detach ( self ) : # We have to work around the python APIs weirdness :\ if not self . IsAttached ( ) : return None # Gdb doesn't drain any pending SIGINTs it may have sent to the inferior # when it simply detaches. We can do this by letting the inferior continue, # and gdb will intercept any SIGINT that's still to-... | Detaches from the inferior . If not attached this is a no - op . | 211 | 16 |
242,550 | def Call ( self , position , function_call ) : self . EnsureGdbPosition ( position [ 0 ] , None , None ) if not gdb . selected_thread ( ) . is_stopped ( ) : self . Interrupt ( position ) result_value = gdb . parse_and_eval ( function_call ) return self . _UnpackGdbVal ( result_value ) | Perform a function call in the inferior . | 84 | 9 |
242,551 | def ExecuteRaw ( self , position , command ) : self . EnsureGdbPosition ( position [ 0 ] , None , None ) return gdb . execute ( command , to_string = True ) | Send a command string to gdb . | 42 | 8 |
242,552 | def _GetGdbThreadMapping ( self , position ) : if len ( gdb . selected_inferior ( ) . threads ( ) ) == 1 : # gdb's output for info threads changes and only displays PID. We cheat. return { position [ 1 ] : 1 } # example: # 8 Thread 0x7f0a637fe700 (LWP 11894) "test.py" 0x00007f0a69563e63 in # select () from /usr/lib64/l... | Gets a mapping from python tid to gdb thread num . | 251 | 13 |
242,553 | def _Inject ( self , position , call ) : self . EnsureGdbPosition ( position [ 0 ] , position [ 1 ] , None ) self . ClearBreakpoints ( ) self . _AddThreadSpecificBreakpoint ( position ) gdb . parse_and_eval ( '%s = 1' % GdbCache . PENDINGCALLS_TO_DO ) gdb . parse_and_eval ( '%s = 1' % GdbCache . PENDINGBUSY ) try : # W... | Injects evaluation of call in a safe location in the inferior . | 260 | 14 |
242,554 | def _BacktraceFromFramePtr ( self , frame_ptr ) : # expects frame_ptr to be a gdb.Value frame_objs = [ PyFrameObjectPtr ( frame ) for frame in self . _IterateChainedList ( frame_ptr , 'f_back' ) ] # We want to output tracebacks in the same format python uses, so we have to # reverse the stack frame_objs . reverse ( ) t... | Assembles and returns what looks exactly like python s backtraces . | 228 | 15 |
242,555 | def Kill ( self ) : try : if self . is_running : self . Detach ( ) if self . _Execute ( '__kill__' ) == '__kill_ack__' : # acknowledged, let's give it some time to die in peace time . sleep ( 0.1 ) except ( TimeoutError , ProxyError ) : logging . debug ( 'Termination request not acknowledged, killing gdb.' ) if self . ... | Send death pill to Gdb and forcefully kill it if that doesn t work . | 238 | 16 |
242,556 | def Version ( ) : output = subprocess . check_output ( [ 'gdb' , '--version' ] ) . split ( '\n' ) [ 0 ] # Example output (Arch linux): # GNU gdb (GDB) 7.7 # Example output (Debian sid): # GNU gdb (GDB) 7.6.2 (Debian 7.6.2-1) # Example output (Debian wheezy): # GNU gdb (GDB) 7.4.1-debian # Example output (centos 2.6.32)... | Gets the version of gdb as a 3 - tuple . | 327 | 13 |
242,557 | def _JsonDecodeDict ( self , data ) : rv = { } for key , value in data . iteritems ( ) : if isinstance ( key , unicode ) : key = self . _TryStr ( key ) if isinstance ( value , unicode ) : value = self . _TryStr ( value ) elif isinstance ( value , list ) : value = self . _JsonDecodeList ( value ) rv [ key ] = value if '... | Json object decode hook that automatically converts unicode objects . | 135 | 12 |
242,558 | def _Execute ( self , funcname , * args , * * kwargs ) : wait_for_completion = kwargs . get ( 'wait_for_completion' , False ) rpc_dict = { 'func' : funcname , 'args' : args } self . _Send ( json . dumps ( rpc_dict ) ) timeout = TIMEOUT_FOREVER if wait_for_completion else TIMEOUT_DEFAULT result_string = self . _Recv ( t... | Send an RPC request to the gdb - internal python . | 225 | 12 |
242,559 | def _Recv ( self , timeout ) : buf = '' # The messiness of this stems from the "duck-typiness" of this function. # The timeout parameter of poll has different semantics depending on whether # it's <=0, >0, or None. Yay. wait_for_line = timeout is TIMEOUT_FOREVER deadline = time . time ( ) + ( timeout if not wait_for_li... | Receive output from gdb . | 487 | 7 |
242,560 | def needsattached ( func ) : @ functools . wraps ( func ) def wrap ( self , * args , * * kwargs ) : if not self . attached : raise PositionError ( 'Not attached to any process.' ) return func ( self , * args , * * kwargs ) return wrap | Decorator to prevent commands from being used when not attached . | 66 | 13 |
242,561 | def Reinit ( self , pid , auto_symfile_loading = True ) : self . ShutDownGdb ( ) self . __init__ ( pid , auto_symfile_loading , architecture = self . arch ) | Reinitializes the object with a new pid . | 47 | 10 |
242,562 | def InjectString ( self , codestring , wait_for_completion = True ) : if self . inferior . is_running and self . inferior . gdb . IsAttached ( ) : try : self . inferior . gdb . InjectString ( self . inferior . position , codestring , wait_for_completion = wait_for_completion ) except RuntimeError : exc_type , exc_value... | Try to inject python code into current thread . | 139 | 9 |
242,563 | def field ( self , name ) : if self . is_null ( ) : raise NullPyObjectPtr ( self ) if name == 'ob_type' : pyo_ptr = self . _gdbval . cast ( PyObjectPtr . get_gdb_type ( ) ) return pyo_ptr . dereference ( ) [ name ] if name == 'ob_size' : try : # Python 2: return self . _gdbval . dereference ( ) [ name ] except RuntimeE... | Get the gdb . Value for the given field within the PyObject coping with some python 2 versus python 3 differences . | 160 | 24 |
242,564 | def write_repr ( self , out , visited ) : # Default implementation: generate a proxy value and write its repr # However, this could involve a lot of work for complicated objects, # so for derived classes we specialize this return out . write ( repr ( self . proxyval ( visited ) ) ) | Write a string representation of the value scraped from the inferior process to out a file - like object . | 63 | 21 |
242,565 | def from_pyobject_ptr ( cls , gdbval ) : try : p = PyObjectPtr ( gdbval ) cls = cls . subclass_from_type ( p . type ( ) ) return cls ( gdbval , cast_to = cls . get_gdb_type ( ) ) except RuntimeError : # Handle any kind of error e.g. NULL ptrs by simply using the base # class pass return cls ( gdbval ) | Try to locate the appropriate derived class dynamically and cast the pointer accordingly . | 103 | 14 |
242,566 | def proxyval ( self , visited ) : # Guard against infinite loops: if self . as_address ( ) in visited : return ProxyAlreadyVisited ( '<...>' ) visited . add ( self . as_address ( ) ) pyop_attr_dict = self . get_attr_dict ( ) if pyop_attr_dict : attr_dict = pyop_attr_dict . proxyval ( visited ) else : attr_dict = { } tp... | Support for new - style classes . | 145 | 7 |
242,567 | def addr2line ( self , addrq ) : co_lnotab = self . pyop_field ( 'co_lnotab' ) . proxyval ( set ( ) ) # Initialize lineno to co_firstlineno as per PyCode_Addr2Line # not 0, as lnotab_notes.txt has it: lineno = int_from_int ( self . field ( 'co_firstlineno' ) ) addr = 0 for addr_incr , line_incr in zip ( co_lnotab [ : :... | Get the line number for a given bytecode offset | 168 | 10 |
242,568 | def current_line ( self ) : if self . is_optimized_out ( ) : return '(frame information optimized out)' with open ( self . filename ( ) , 'r' ) as f : all_lines = f . readlines ( ) # Convert from 1-based current_line_num to 0-based list offset: return all_lines [ self . current_line_num ( ) - 1 ] | Get the text of the current source line as a string with a trailing newline character | 88 | 17 |
242,569 | def select ( self ) : if not hasattr ( self . _gdbframe , 'select' ) : print ( 'Unable to select frame: ' 'this build of gdb does not expose a gdb.Frame.select method' ) return False self . _gdbframe . select ( ) return True | If supported select this frame and return True ; return False if unsupported | 66 | 13 |
242,570 | def get_index ( self ) : index = 0 # Go down until you reach the newest frame: iter_frame = self while iter_frame . newer ( ) : index += 1 iter_frame = iter_frame . newer ( ) return index | Calculate index of frame starting at 0 for the newest frame within this thread | 51 | 16 |
242,571 | def is_evalframeex ( self ) : if self . _gdbframe . name ( ) == 'PyEval_EvalFrameEx' : ''' I believe we also need to filter on the inline struct frame_id.inline_depth, only regarding frames with an inline depth of 0 as actually being this function So we reject those with type gdb.INLINE_FRAME ''' if self . _gdbframe . ... | Is this a PyEval_EvalFrameEx frame? | 124 | 13 |
242,572 | def get_selected_python_frame ( cls ) : frame = cls . get_selected_frame ( ) while frame : if frame . is_evalframeex ( ) : return frame frame = frame . older ( ) # Not found: return None | Try to obtain the Frame for the python code in the selected frame or None | 55 | 15 |
242,573 | def ListCommands ( self ) : print 'Available commands:' commands = dict ( self . commands ) for plugin in self . plugins : commands . update ( plugin . commands ) for com in sorted ( commands ) : if not com . startswith ( '_' ) : self . PrintHelpTextLine ( com , commands [ com ] ) | Print a list of currently available commands and their descriptions . | 71 | 11 |
242,574 | def StatusLine ( self ) : pid = self . inferior . pid curthread = None threadnum = 0 if pid : if not self . inferior . is_running : logging . warning ( 'Inferior is not running.' ) self . Detach ( ) pid = None else : try : # get a gdb running if it wasn't already. if not self . inferior . attached : self . inferior . S... | Generate the colored line indicating plugin status . | 206 | 9 |
242,575 | def Attach ( self , pid ) : if self . inferior . is_running : answer = raw_input ( 'Already attached to process ' + str ( self . inferior . pid ) + '. Detach? [y]/n ' ) if answer and answer != 'y' and answer != 'yes' : return None self . Detach ( ) # Whatever position we had before will not make any sense now for plugi... | Attach to the process with the given pid . | 107 | 9 |
242,576 | def StartGdb ( self ) : if self . inferior . is_running : self . inferior . ShutDownGdb ( ) program_arg = 'program %d ' % self . inferior . pid else : program_arg = '' os . system ( 'gdb ' + program_arg + ' ' . join ( self . gdb_args ) ) reset_position = raw_input ( 'Reset debugger position? [y]/n ' ) if not reset_posi... | Hands control over to a new gdb process . | 123 | 11 |
242,577 | def __get_node ( self , word ) : node = self . root for c in word : try : node = node . children [ c ] except KeyError : return None return node | Private function retrieving a final node of trie for given word | 39 | 12 |
242,578 | def get ( self , word , default = nil ) : node = self . __get_node ( word ) output = nil if node : output = node . output if output is nil : if default is nil : raise KeyError ( "no key '%s'" % word ) else : return default else : return output | Retrieves output value associated with word . | 66 | 9 |
242,579 | def items ( self ) : L = [ ] def aux ( node , s ) : s = s + node . char if node . output is not nil : L . append ( ( s , node . output ) ) for child in node . children . values ( ) : if child is not node : aux ( child , s ) aux ( self . root , '' ) return iter ( L ) | Generator returning all keys and values stored in a trie . | 81 | 13 |
242,580 | def add_word ( self , word , value ) : if not word : return node = self . root for c in word : try : node = node . children [ c ] except KeyError : n = TrieNode ( c ) node . children [ c ] = n node = n node . output = value | Adds word and associated value . | 65 | 6 |
242,581 | def exists ( self , word ) : node = self . __get_node ( word ) if node : return bool ( node . output != nil ) else : return False | Checks if whole word is present in the trie . | 35 | 12 |
242,582 | def make_automaton ( self ) : queue = deque ( ) # 1. for i in range ( 256 ) : c = chr ( i ) if c in self . root . children : node = self . root . children [ c ] node . fail = self . root # f(s) = 0 queue . append ( node ) else : self . root . children [ c ] = self . root # 2. while queue : r = queue . popleft ( ) for n... | Converts trie to Aho - Corasick automaton . | 157 | 14 |
242,583 | def iter_long ( self , string ) : state = self . root last = None index = 0 while index < len ( string ) : c = string [ index ] if c in state . children : state = state . children [ c ] if state . output is not nil : # save the last node on the path last = ( state . output , index ) index += 1 else : if last : # return... | Generator performs a modified Aho - Corasick search string algorithm which maches only the longest word . | 170 | 22 |
242,584 | def find_all ( self , string , callback ) : for index , output in self . iter ( string ) : callback ( index , output ) | Wrapper on iter method callback gets an iterator result | 30 | 10 |
242,585 | def get_long_description ( ) : import codecs with codecs . open ( 'README.rst' , encoding = 'UTF-8' ) as f : readme = [ line for line in f if not line . startswith ( '.. contents::' ) ] return '' . join ( readme ) | Strip the content index from the long description . | 69 | 10 |
242,586 | def _add_play_button ( self , image_url , image_path ) : try : from PIL import Image from tempfile import NamedTemporaryFile import urllib try : urlretrieve = urllib . request . urlretrieve except ImportError : urlretrieve = urllib . urlretrieve # create temporary files for image operations with NamedTemporaryFile ( su... | Try to add a play button to the screenshot . | 250 | 10 |
242,587 | def process ( self ) : self . modules . sort ( key = lambda x : x . priority ) for module in self . modules : transforms = module . transform ( self . data ) transforms . sort ( key = lambda x : x . linenum , reverse = True ) for transform in transforms : linenum = transform . linenum if isinstance ( transform . data ,... | This method handles the actual processing of Modules and Transforms | 206 | 12 |
242,588 | def _irregular ( singular , plural ) : def caseinsensitive ( string ) : return '' . join ( '[' + char + char . upper ( ) + ']' for char in string ) if singular [ 0 ] . upper ( ) == plural [ 0 ] . upper ( ) : PLURALS . insert ( 0 , ( r"(?i)({}){}$" . format ( singular [ 0 ] , singular [ 1 : ] ) , r'\1' + plural [ 1 : ] ... | A convenience function to add appropriate rules to plurals and singular for irregular words . | 545 | 16 |
242,589 | def camelize ( string , uppercase_first_letter = True ) : if uppercase_first_letter : return re . sub ( r"(?:^|_)(.)" , lambda m : m . group ( 1 ) . upper ( ) , string ) else : return string [ 0 ] . lower ( ) + camelize ( string ) [ 1 : ] | Convert strings to CamelCase . | 78 | 7 |
242,590 | def parameterize ( string , separator = '-' ) : string = transliterate ( string ) # Turn unwanted chars into the separator string = re . sub ( r"(?i)[^a-z0-9\-_]+" , separator , string ) if separator : re_sep = re . escape ( separator ) # No more than one of the separator in a row. string = re . sub ( r'%s{2,}' % re_se... | Replace special characters in a string so that it may be used as part of a pretty URL . | 164 | 20 |
242,591 | def pluralize ( word ) : if not word or word . lower ( ) in UNCOUNTABLES : return word else : for rule , replacement in PLURALS : if re . search ( rule , word ) : return re . sub ( rule , replacement , word ) return word | Return the plural form of a word . | 59 | 8 |
242,592 | def underscore ( word ) : word = re . sub ( r"([A-Z]+)([A-Z][a-z])" , r'\1_\2' , word ) word = re . sub ( r"([a-z\d])([A-Z])" , r'\1_\2' , word ) word = word . replace ( "-" , "_" ) return word . lower ( ) | Make an underscored lowercase form from the expression in the string . | 94 | 14 |
242,593 | def print_all ( msg ) : gc . collect ( ) logger . debug ( msg ) vips_lib . vips_object_print_all ( ) logger . debug ( ) | Print all objects . | 40 | 4 |
242,594 | def get_typeof ( self , name ) : # logger.debug('VipsObject.get_typeof: self = %s, name = %s', # str(self), name) pspec = self . _get_pspec ( name ) if pspec is None : # need to clear any error, this is horrible Error ( '' ) return 0 return pspec . value_type | Get the GType of a GObject property . | 84 | 10 |
242,595 | def get_blurb ( self , name ) : c_str = gobject_lib . g_param_spec_get_blurb ( self . _get_pspec ( name ) ) return _to_string ( c_str ) | Get the blurb for a GObject property . | 52 | 10 |
242,596 | def get ( self , name ) : logger . debug ( 'VipsObject.get: name = %s' , name ) pspec = self . _get_pspec ( name ) if pspec is None : raise Error ( 'Property not found.' ) gtype = pspec . value_type gv = pyvips . GValue ( ) gv . set_type ( gtype ) go = ffi . cast ( 'GObject *' , self . pointer ) gobject_lib . g_object_... | Get a GObject property . | 137 | 6 |
242,597 | def set ( self , name , value ) : logger . debug ( 'VipsObject.set: name = %s, value = %s' , name , value ) gtype = self . get_typeof ( name ) gv = pyvips . GValue ( ) gv . set_type ( gtype ) gv . set ( value ) go = ffi . cast ( 'GObject *' , self . pointer ) gobject_lib . g_object_set_property ( go , _to_bytes ( name ... | Set a GObject property . | 121 | 6 |
242,598 | def set_string ( self , string_options ) : vo = ffi . cast ( 'VipsObject *' , self . pointer ) cstr = _to_bytes ( string_options ) result = vips_lib . vips_object_set_from_string ( vo , cstr ) return result == 0 | Set a series of properties using a string . | 69 | 9 |
242,599 | def get_description ( self ) : vo = ffi . cast ( 'VipsObject *' , self . pointer ) return _to_string ( vips_lib . vips_object_get_description ( vo ) ) | Get the description of a GObject . | 49 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.