idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
243,500 | 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 . |
243,501 | 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 . |
243,502 | 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 . |
243,503 | 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 . |
243,504 | def _create_initial_epsf ( self , stars ) : oversampling = self . oversampling shape = self . 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 ] * oversampling [ 0 ] ) ... | Create an initial EPSFModel object . |
243,505 | def _resample_residual ( self , star , epsf ) : 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 ) yidx = _py2intround ( y + epsf_ycenter ) mask = np . logical_and ( np . logic... | Compute a normalized residual image in the oversampled ePSF grid . |
243,506 | 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 . |
243,507 | 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' : kernel = np . array ( [ [ + 0.041632 , - 0.080816 , 0.078368 , - 0.080816 , + 0.041632 ] , [ - 0.080816 , - 0.019592 , 0.200816 , - 0.019592 , - ... | Smooth the ePSF array by convolving it with a kernel . |
243,508 | def _recenter_epsf ( self , epsf_data , epsf , centroid_func = centroid_com , box_size = 5 , maxiters = 20 , center_accuracy = 1.0e-4 ) : epsf = EPSFModel ( data = epsf_data , origin = epsf . origin , normalize = False , oversampling = epsf . oversampling ) epsf . fill_value = 0.0 xcenter , ycenter = epsf . origin dx_t... | Calculate the center of the ePSF data and shift the data so the ePSF center is at the center of the ePSF data array . |
243,509 | 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 : epsf = self . _create_initial_epsf ( stars ) else : epsf = copy . deepcopy ( epsf ) residuals = self . _resample_residuals ( stars ,... | A single iteration of improving an ePSF . |
243,510 | 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 . |
243,511 | 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 |
243,512 | 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 . |
243,513 | def _find_bounds_1d ( data , x ) : idx = np . searchsorted ( data , x ) if idx == 0 : idx0 = 0 elif idx == len ( data ) : 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 . |
243,514 | 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 . |
243,515 | def evaluate ( self , x , y , flux , x_0 , y_0 ) : 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 > self . _xgrid_max or y_0 < self . _ygrid_min or y_0 > self . _ygrid_max ) : self . _ref_indices = np . argsort ( np . hypot ( self . _gri... | Evaluate the GriddedPSFModel for the input parameters . |
243,516 | 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 . |
243,517 | 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 . |
243,518 | 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 . |
243,519 | def _compute_fluxes ( self ) : 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 ) - 1 ) jmin = max ( 0 , int ( y0 - sma - 0.5 ) - 1 ) im... | Compute integrated flux inside ellipse as well as inside a circle defined with the same semimajor axis . |
243,520 | 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 . |
243,521 | 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 . |
243,522 | 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 . |
243,523 | 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 . |
243,524 | 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 ) mask_idx = mask . nonzero ( ) if mask_idx [ 0 ] . size == 0 : raise ValueError ( 'All items in data are masked' )... | Interpolate over masked pixels in data and optional error or background images . |
243,525 | 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 . |
243,526 | def SendToExecSocket ( self , code , tid = None ) : response = self . _SendToExecSocketRaw ( json . dumps ( code ) , tid ) return json . loads ( response ) | Inject python code into exec socket . |
243,527 | 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 . |
243,528 | 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 . |
243,529 | 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 . |
243,530 | 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 . |
243,531 | def _UnserializableObjectFallback ( self , obj ) : if isinstance ( obj , libpython . PyInstanceObjectPtr ) : in_class = obj . pyop_field ( 'in_class' ) result_dict = in_class . pyop_field ( 'cl_dict' ) . proxyval ( set ( ) ) instanceproxy = obj . proxyval ( set ( ) ) result_dict . update ( instanceproxy . attrdict ) re... | Handles sanitizing of unserializable objects for Json . |
243,532 | 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 . |
243,533 | 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 . |
243,534 | 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 . |
243,535 | def IsSymbolFileSane ( self , position ) : pos = [ position [ 0 ] , None , None ] self . EnsureGdbPosition ( * pos ) try : if GdbCache . DICT and GdbCache . TYPE and GdbCache . INTERP_HEAD : tstate = GdbCache . INTERP_HEAD [ 'tstate_head' ] tstate [ 'thread_id' ] frame = tstate [ 'frame' ] frame_attrs = [ 'f_back' , 'f... | Performs basic sanity check by trying to look up a bunch of symbols . |
243,536 | def Detach ( self ) : if not self . IsAttached ( ) : return None pid = gdb . selected_inferior ( ) . pid self . Interrupt ( [ pid , None , None ] ) self . Continue ( [ pid , None , None ] ) result = gdb . execute ( 'detach' , to_string = True ) if not result : return None return result | Detaches from the inferior . If not attached this is a no - op . |
243,537 | 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 . |
243,538 | def ExecuteRaw ( self , position , command ) : self . EnsureGdbPosition ( position [ 0 ] , None , None ) return gdb . execute ( command , to_string = True ) | Send a command string to gdb . |
243,539 | def _GetGdbThreadMapping ( self , position ) : if len ( gdb . selected_inferior ( ) . threads ( ) ) == 1 : return { position [ 1 ] : 1 } thread_line_regexp = r'\s*\**\s*([0-9]+)\s+[a-zA-Z]+\s+([x0-9a-fA-F]+)\s.*' output = gdb . execute ( 'info threads' , to_string = True ) matches = [ re . match ( thread_line_regexp , ... | Gets a mapping from python tid to gdb thread num . |
243,540 | 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 : sel... | Injects evaluation of call in a safe location in the inferior . |
243,541 | def _BacktraceFromFramePtr ( self , frame_ptr ) : frame_objs = [ PyFrameObjectPtr ( frame ) for frame in self . _IterateChainedList ( frame_ptr , 'f_back' ) ] frame_objs . reverse ( ) tb_strings = [ 'Traceback (most recent call last):' ] for frame in frame_objs : line_string = ( ' File "%s", line %s, in %s' % ( frame ... | Assembles and returns what looks exactly like python s backtraces . |
243,542 | def Kill ( self ) : try : if self . is_running : self . Detach ( ) if self . _Execute ( '__kill__' ) == '__kill_ack__' : time . sleep ( 0.1 ) except ( TimeoutError , ProxyError ) : logging . debug ( 'Termination request not acknowledged, killing gdb.' ) if self . is_running : os . kill ( self . _process . pid , signal ... | Send death pill to Gdb and forcefully kill it if that doesn t work . |
243,543 | def Version ( ) : output = subprocess . check_output ( [ 'gdb' , '--version' ] ) . split ( '\n' ) [ 0 ] major = None minor = None micro = None for potential_versionstring in output . split ( ) : version = re . split ( '[^0-9]' , potential_versionstring ) try : major = int ( version [ 0 ] ) except ( IndexError , ValueEr... | Gets the version of gdb as a 3 - tuple . |
243,544 | 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 . |
243,545 | 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 ( ti... | Send an RPC request to the gdb - internal python . |
243,546 | def _Recv ( self , timeout ) : buf = '' wait_for_line = timeout is TIMEOUT_FOREVER deadline = time . time ( ) + ( timeout if not wait_for_line else 0 ) def TimeLeft ( ) : return max ( 1000 * ( deadline - time . time ( ) ) , 0 ) continue_reading = True while continue_reading : poll_timeout = None if wait_for_line else T... | Receive output from gdb . |
243,547 | 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 . |
243,548 | 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 . |
243,549 | 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 . |
243,550 | 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 : return self . _gdbval . dereference ( ) [ name ] except RuntimeError : retur... | Get the gdb . Value for the given field within the PyObject coping with some python 2 versus python 3 differences . |
243,551 | def write_repr ( self , out , visited ) : 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 . |
243,552 | 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 : pass return cls ( gdbval ) | Try to locate the appropriate derived class dynamically and cast the pointer accordingly . |
243,553 | def proxyval ( self , visited ) : 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_name = self . safe_tp_name ( ) ... | Support for new - style classes . |
243,554 | def addr2line ( self , addrq ) : co_lnotab = self . pyop_field ( 'co_lnotab' ) . proxyval ( set ( ) ) lineno = int_from_int ( self . field ( 'co_firstlineno' ) ) addr = 0 for addr_incr , line_incr in zip ( co_lnotab [ : : 2 ] , co_lnotab [ 1 : : 2 ] ) : addr += ord ( addr_incr ) if addr > addrq : return lineno lineno +... | Get the line number for a given bytecode offset |
243,555 | 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 ( ) return all_lines [ self . current_line_num ( ) - 1 ] | Get the text of the current source line as a string with a trailing newline character |
243,556 | 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 |
243,557 | def get_index ( self ) : index = 0 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 |
243,558 | def is_evalframeex ( self ) : if self . _gdbframe . name ( ) == 'PyEval_EvalFrameEx' : if self . _gdbframe . type ( ) == gdb . NORMAL_FRAME : return True return False | Is this a PyEval_EvalFrameEx frame? |
243,559 | def get_selected_python_frame ( cls ) : frame = cls . get_selected_frame ( ) while frame : if frame . is_evalframeex ( ) : return frame frame = frame . older ( ) return None | Try to obtain the Frame for the python code in the selected frame or None |
243,560 | 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 . |
243,561 | 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 : if not self . inferior . attached : self . inferior . StartGdb ( ) curthread = self . inferior . ... | Generate the colored line indicating plugin status . |
243,562 | 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 ( ) for plugin in self . plugins : plugin . position = None self . inferior... | Attach to the process with the given pid . |
243,563 | 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 . |
243,564 | 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 |
243,565 | 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 . |
243,566 | 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 . |
243,567 | 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 . |
243,568 | 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 . |
243,569 | def make_automaton ( self ) : queue = deque ( ) for i in range ( 256 ) : c = chr ( i ) if c in self . root . children : node = self . root . children [ c ] node . fail = self . root queue . append ( node ) else : self . root . children [ c ] = self . root while queue : r = queue . popleft ( ) for node in r . children .... | Converts trie to Aho - Corasick automaton . |
243,570 | 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 : last = ( state . output , index ) index += 1 else : if last : yield last index = last [ 1 ] + 1 state =... | Generator performs a modified Aho - Corasick search string algorithm which maches only the longest word . |
243,571 | 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 |
243,572 | 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 . |
243,573 | 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 with NamedTemporaryFile ( suffix = ".jpg" ) as screenshot_img : with Named... | Try to add a play button to the screenshot . |
243,574 | 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 |
243,575 | 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 . |
243,576 | 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 . |
243,577 | def parameterize ( string , separator = '-' ) : string = transliterate ( string ) string = re . sub ( r"(?i)[^a-z0-9\-_]+" , separator , string ) if separator : re_sep = re . escape ( separator ) string = re . sub ( r'%s{2,}' % re_sep , separator , string ) string = re . sub ( r"(?i)^{sep}|{sep}$" . format ( sep = re_s... | Replace special characters in a string so that it may be used as part of a pretty URL . |
243,578 | 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 . |
243,579 | 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 . |
243,580 | def print_all ( msg ) : gc . collect ( ) logger . debug ( msg ) vips_lib . vips_object_print_all ( ) logger . debug ( ) | Print all objects . |
243,581 | def get_typeof ( self , name ) : pspec = self . _get_pspec ( name ) if pspec is None : Error ( '' ) return 0 return pspec . value_type | Get the GType of a GObject property . |
243,582 | 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 . |
243,583 | 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 . |
243,584 | 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 . |
243,585 | 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 . |
243,586 | 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 . |
243,587 | def generate_sphinx_all ( ) : all_nicknames = [ ] def add_nickname ( gtype , a , b ) : nickname = nickname_find ( gtype ) try : Operation . generate_sphinx ( nickname ) all_nicknames . append ( nickname ) except Error : pass type_map ( gtype , add_nickname ) return ffi . NULL type_map ( type_from_name ( 'VipsOperation'... | Generate sphinx documentation . |
243,588 | def new ( image ) : pointer = vips_lib . vips_region_new ( image . pointer ) if pointer == ffi . NULL : raise Error ( 'unable to make region' ) return pyvips . Region ( pointer ) | Make a region on an image . |
243,589 | def fetch ( self , x , y , w , h ) : if not at_least_libvips ( 8 , 8 ) : raise Error ( 'libvips too old' ) psize = ffi . new ( 'size_t *' ) pointer = vips_lib . vips_region_fetch ( self . pointer , x , y , w , h , psize ) if pointer == ffi . NULL : raise Error ( 'unable to fetch from region' ) pointer = ffi . gc ( poin... | Fill a region with pixel data . |
243,590 | def gtype_to_python ( gtype ) : fundamental = gobject_lib . g_type_fundamental ( gtype ) if gtype in GValue . _gtype_to_python : return GValue . _gtype_to_python [ gtype ] if fundamental in GValue . _gtype_to_python : return GValue . _gtype_to_python [ fundamental ] return '<unknown type>' | Map a gtype to the name of the Python type we use to represent it . |
243,591 | def to_enum ( gtype , value ) : if isinstance ( value , basestring if _is_PY2 else str ) : enum_value = vips_lib . vips_enum_from_nick ( b'pyvips' , gtype , _to_bytes ( value ) ) if enum_value < 0 : raise Error ( 'no value {0} in gtype {1} ({2})' . format ( value , type_name ( gtype ) , gtype ) ) else : enum_value = va... | Turn a string into an enum value ready to be passed into libvips . |
243,592 | def from_enum ( gtype , enum_value ) : pointer = vips_lib . vips_enum_nick ( gtype , enum_value ) if pointer == ffi . NULL : raise Error ( 'value not in enum' ) return _to_string ( pointer ) | Turn an int back into an enum string . |
243,593 | def set ( self , value ) : gtype = self . gvalue . g_type fundamental = gobject_lib . g_type_fundamental ( gtype ) if gtype == GValue . gbool_type : gobject_lib . g_value_set_boolean ( self . gvalue , value ) elif gtype == GValue . gint_type : gobject_lib . g_value_set_int ( self . gvalue , int ( value ) ) elif gtype =... | Set a GValue . |
243,594 | def get ( self ) : gtype = self . gvalue . g_type fundamental = gobject_lib . g_type_fundamental ( gtype ) result = None if gtype == GValue . gbool_type : result = bool ( gobject_lib . g_value_get_boolean ( self . gvalue ) ) elif gtype == GValue . gint_type : result = gobject_lib . g_value_get_int ( self . gvalue ) eli... | Get the contents of a GValue . |
243,595 | def to_polar ( image ) : xy = pyvips . Image . xyz ( image . width , image . height ) xy -= [ image . width / 2.0 , image . height / 2.0 ] scale = min ( image . width , image . height ) / float ( image . width ) xy *= 2.0 / scale index = xy . polar ( ) index *= [ 1 , image . height / 360.0 ] return image . mapim ( inde... | Transform image coordinates to polar . |
243,596 | def to_rectangular ( image ) : xy = pyvips . Image . xyz ( image . width , image . height ) xy *= [ 1 , 360.0 / image . height ] index = xy . rect ( ) scale = min ( image . width , image . height ) / float ( image . width ) index *= scale / 2.0 index += [ image . width / 2.0 , image . height / 2.0 ] return image . mapi... | Transform image coordinates to rectangular . |
243,597 | def _to_string ( x ) : if x == ffi . NULL : x = 'NULL' else : x = ffi . string ( x ) if isinstance ( x , byte_type ) : x = x . decode ( 'utf-8' ) return x | Convert to a unicode string . |
243,598 | def new ( name ) : vi = vips_lib . vips_interpolate_new ( _to_bytes ( name ) ) if vi == ffi . NULL : raise Error ( 'no such interpolator {0}' . format ( name ) ) return Interpolate ( vi ) | Make a new interpolator by name . |
243,599 | def _run_cmplx ( fn , image ) : original_format = image . format if image . format != 'complex' and image . format != 'dpcomplex' : if image . bands % 2 != 0 : raise Error ( 'not an even number of bands' ) if image . format != 'float' and image . format != 'double' : image = image . cast ( 'float' ) if image . format =... | Run a complex function on a non - complex image . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.