rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
:it: number of iterations, | :niter: number of iterations, | def __init__(self, g, **kwargs): """ Solve the quadratic trust-region subproblem |
self.dir = None $ Direction of infinity descent | self.dir = None | def __init__( self, c, **kwargs ): """ Solve the equality-constrained quadratic programming problem |
if self.nrangeB > 0: write('Two-Sided bounds: %s\n' + self.rangeB) | if self.nrangeB > 0: write('Two-Sided bounds: %s\n' % self.rangeB) | def display_basic_info(self): """ Display vital statistics about the current model. """ import sys write = sys.stderr.write write('Problem Name: %s\n' % self.name) write('Number of Variables: %d\n' % self.n) write('Number of Bound Constraints: %d' % self.nbounds) write(' (%d lower, %d upper, %d two-sided)\n' % (self.nl... |
self.hformat = '%-5s %8s %7s %5s %8s %8s %4s\n' | self.hformat = '%-5s %8s %7s %5s %8s %8s %4s' | def __init__(self, nlp, TR, TrSolver, **kwargs): |
self.hline = '-' * self.hlen + '\n' self.format = '%-5d %8.1e %7.1e %5d %8.1e %8.1e %4s\n' self.format0= '%-5d %8.1e %7.1e %5s %8s %8.1e %4s\n' | self.hline = '-' * self.hlen self.format = '%-5d %8.1e %7.1e %5d %8.1e %8.1e %4s' self.format0= '%-5d %8.1e %7.1e %5s %8s %8.1e %4s' | def __init__(self, nlp, TR, TrSolver, **kwargs): |
:s: final step, | :step: final step, | def __init__(self, g, **kwargs): """ Solve the quadratic trust-region subproblem |
:snorm: Euclidian norm of the step. | :stepNorm: Euclidian norm of the step. | def __init__(self, g, **kwargs): """ Solve the quadratic trust-region subproblem |
if __name__ == '__main__': from pysparse.sparse import spmatrix import precon from nlpy_timing import cputime t_setup = cputime() H = spmatrix.ll_mat_from_mtx('1138bus.mtx') n = H.shape[0] e = np.ones(n, 'd') g = np.empty(n, 'd') H.matvec(e, g) K = precon.DiagonalPreconditioner(H) t_setup = cputime() - t_setup t_... | def H_prod(H, v): # For simulation purposes only n = H.shape[0] Hv = np.zeros(n, 'd') H.matvec(v, Hv) return Hv | |
Optional keyword arguments are given in the following table. +----------+-------------------------------------------------+---------+ | Keyword | Description | Default | +==========+=================================================+=========+ | A | the matrix defining linear... | :keywords: :A: the matrix defining linear equality constraints (None) :rhs: a nonzero right-hand side of the constraints (None) :H: the explicit matrix H (with matvec method) (None) :matvec: a method to compute H-vector products (None) :precon: a preconditioner G (given explicitly) (Identity) :Proj: an existing factori... | def __init__( self, c, **kwargs ): """ Solve the equality-constrained quadratic programming problem |
stepMax = sqrt(xw*xw + ww*(radius*radius - xnorm*xnorm)) - xw stepMax /= ww if t1 > stepMax: | roots = roots_quadratic(ww, 2*xw, xnorm*xnorm - radius*radius) stepMax = max([abs(r) for r in roots if r*t1 > 0]) if abs(t1) > abs(stepMax): | def solve(self, rhs, itnlim=0, damp=0.0, atol=1.0e-9, btol=1.0e-9, conlim=1.0e+8, radius=None, show=False, wantvar=False): """ Solve the linear system, linear least-squares problem or regularized linear least-squares problem with specified parameters. All return values below are stored in members of the same name. |
q = v | q = v.copy() | def matvec(self, iter, v): """ Compute a matrix-vector product between the current limited-memory positive-definite approximation to the inverse Hessian matrix and the vector v using the LBFGS two-loop recursion formula. The 'iter' argument is the current iteration number. When the inner product <y,s> of one of the pa... |
self.atol = kwargs.get('abstol', 1.0e-6) self.rtol = kwargs.get('reltol', self.nlp.stop_d) | self.abstol = kwargs.get('abstol', 1.0e-6) self.reltol = kwargs.get('reltol', self.nlp.stop_d) | def __init__(self, nlp, **kwargs): |
self.dFeas = max(0.0, dFeas) self.pFeas = max(0.0, pFeas) self.bFeas = max(0.0, bFeas) self.gComp = max(0.0, gComp) self.bComp = max(0.0, bComp) | self.dFeas = dFeas self.pFeas = pFeas self.bFeas = bFeas self.gComp = gComp self.bComp = bComp | def __init__(self, dFeas, pFeas, bFeas, gComp, bComp, **kwargs): """ :parameters: dFeas: dual feasibility residual pFeas: primal feasibility residual, taking into account constraints that are not bound constraints, bFeas: primal feasibility with respect to bounds, gComp: complementarity residual with respect to constra... |
if self.is_scaling: | if self._is_scaling: | def set_scaling(self, scaling, **kwargs): "Assign scaling values. `scaling` must be a `KKTresidual` instance." if self.is_scaling: raise ValueError, 'instance represents scaling factors.' if not isinstance(scaling, KKTresidual): raise ValueError, 'scaling must be a KKTresidual instance.' self.scaling = scaling self.sca... |
self.x0 = numpy.zeros(self.n, 'd') | self.x0 = np.zeros(self.n, 'd') | def __init__(self, n=0, m=0, name='Generic', **kwargs): self.n = n # Number of variables self.m = m # Number of general constraints self.name = name # Problem name |
self.pi0 = numpy.zeros(self.m, 'd') | self.pi0 = np.zeros(self.m, 'd') | def __init__(self, n=0, m=0, name='Generic', **kwargs): self.n = n # Number of variables self.m = m # Number of general constraints self.name = name # Problem name |
self.Lvar = self.negInfinity * numpy.ones(self.n, 'd') | self.Lvar = self.negInfinity * np.ones(self.n, 'd') | def __init__(self, n=0, m=0, name='Generic', **kwargs): self.n = n # Number of variables self.m = m # Number of general constraints self.name = name # Problem name |
self.Uvar = self.Infinity * numpy.ones(self.n, 'd') | self.Uvar = self.Infinity * np.ones(self.n, 'd') | def __init__(self, n=0, m=0, name='Generic', **kwargs): self.n = n # Number of variables self.m = m # Number of general constraints self.name = name # Problem name |
self.Lcon = self.negInfinity * numpy.ones(self.m, 'd') | self.Lcon = self.negInfinity * np.ones(self.m, 'd') | def __init__(self, n=0, m=0, name='Generic', **kwargs): self.n = n # Number of variables self.m = m # Number of general constraints self.name = name # Problem name |
self.Ucon = self.Infinity * numpy.ones(self.m, 'd') | self.Ucon = self.Infinity * np.ones(self.m, 'd') | def __init__(self, n=0, m=0, name='Generic', **kwargs): self.n = n # Number of variables self.m = m # Number of general constraints self.name = name # Problem name |
self.xNorm2 = xNorm2 | self.xNorm2 = self.stepNorm = xNorm2 | def Solve(self): if self.A is not None: if self.factorize and not self.factorized: self.Factorize() if self.b is not None: self.FindFeasible() |
if self.gnorm <= self.stoptol: | if self.gnorm <= stoptol: | def Solve(self, **kwargs): |
self.A = PysparseLinearOperator(A) | self.A = PysparseLinearOperator(A, transposed=False) | def __init__(self, A, **kwargs): m, n = A.shape LinearOperator.__init__(self, n, m, **kwargs) if isinstance(A, LinearOperator): self.A = A else: self.A = PysparseLinearOperator(A) self.symmetric = True self.transpose = kwargs.get('transpose', False) if self.transpose: self.shape = (n, n) self.__mul__ = self._rmul else:... |
self.transpose = kwargs.get('transpose', False) if self.transpose: | if self.transposed: self.shape = (m, m) self.__mul__ = self._rmul else: | def __init__(self, A, **kwargs): m, n = A.shape LinearOperator.__init__(self, n, m, **kwargs) if isinstance(A, LinearOperator): self.A = A else: self.A = PysparseLinearOperator(A) self.symmetric = True self.transpose = kwargs.get('transpose', False) if self.transpose: self.shape = (n, n) self.__mul__ = self._rmul else:... |
self.__mul__ = self._rmul else: self.shape = (m, m) | def __init__(self, A, **kwargs): m, n = A.shape LinearOperator.__init__(self, n, m, **kwargs) if isinstance(A, LinearOperator): self.A = A else: self.A = PysparseLinearOperator(A) self.symmetric = True self.transpose = kwargs.get('transpose', False) if self.transpose: self.shape = (n, n) self.__mul__ = self._rmul else:... | |
self.solver = LSQRFramework(n, n, self.matvec) | op = SimpleLinearOperator(n, n, lambda u: np.asarray(u * self.K)[0], matvec_transp=lambda u: np.asarray(u * self.K.T)[0], symmetric=False) self.solver = LSQRFramework(op) | def setsolver(self): n = self.n self.solver = LSQRFramework(n, n, self.matvec) |
def matvec(self, mode, m, n, u): if mode == 1: v = u * self.K elif mode == 2: v = u * self.K.T return np.asarray(v)[0] | def matvec(self, mode, m, n, u): if mode == 1: v = u * self.K elif mode == 2: v = u * self.K.T return np.asarray(v)[0] | |
self.solver = Minres(self.matvec, check=True, show=True, shift=9.94334578e-01) | n = self.n op = SimpleLinearOperator(n, n, lambda u: u * self.K, symmetric=True) self.solver = Minres(op, check=True, show=True, shift=9.94334578e-01) | def setsolver(self): self.solver = Minres(self.matvec, check=True, show=True, shift=9.94334578e-01) |
def matvec(self, x, y): "y <- Ax" y = x * self.K return | def matvec(self, x, y): "y <- Ax" y = x * self.K return | |
self.solver = Minres(self.matvec, check=True, show=True) | n = self.n op = SimpleLinearOperator(n, n, self.matvec, symmetric=True) self.solver = Minres(op, check=True, show=True) | def setsolver(self): self.solver = Minres(self.matvec, check=True, show=True) |
def matvec(self, x, y): | def matvec(self, x): | def matvec(self, x, y): "y <- Ax" (m,n) = self.K.shape y[:m] = x[:m] + np.asarray(x[m:] * self.K)[0] y[m:] = np.asarray(x[:m] * self.K.T)[0] - self.reg * x[m:] return |
(m,n) = self.K.shape | (m,n) = self.K.shape ; y = np.empty(n+m) | def matvec(self, x, y): "y <- Ax" (m,n) = self.K.shape y[:m] = x[:m] + np.asarray(x[m:] * self.K)[0] y[m:] = np.asarray(x[:m] * self.K.T)[0] - self.reg * x[m:] return |
return | return y | def matvec(self, x, y): "y <- Ax" (m,n) = self.K.shape y[:m] = x[:m] + np.asarray(x[m:] * self.K)[0] y[m:] = np.asarray(x[:m] * self.K.T)[0] - self.reg * x[m:] return |
m = self.m | n = self.n ; on = self.original_n m = self.m ; om = self.original_m | def cons(self, x): """ Evaluate the vector of general constraints for the modified problem. Constraints are stored in the order in which they appear in the original problem. If constraint i is a range constraint, c[i] will be the constraint that has the slack on the lower bound on c[i]. The constraint with the slack on... |
mslow = self.original_n + self.nrangeC + self.n_con_low | mslow = on + self.n_con_low | def cons(self, x): """ Evaluate the vector of general constraints for the modified problem. Constraints are stored in the order in which they appear in the original problem. If constraint i is a range constraint, c[i] will be the constraint that has the slack on the lower bound on c[i]. The constraint with the slack on... |
s_low = x[self.original_n + self.nrangeC:mslow] s_up = x[mslow:msup] | s_low = x[on:mslow] s_up = x[mslow:msup] | def cons(self, x): """ Evaluate the vector of general constraints for the modified problem. Constraints are stored in the order in which they appear in the original problem. If constraint i is a range constraint, c[i] will be the constraint that has the slack on the lower bound on c[i]. The constraint with the slack on... |
c[:self.original_m] = AmplModel.cons(self, x[:self.original_n]) c[self.original_m:self.original_m + self.nrangeC] = c[rangeC] | c[:om] = AmplModel.cons(self, x[:on]) c[om:om+nrangeC] = c[rangeC] | def cons(self, x): """ Evaluate the vector of general constraints for the modified problem. Constraints are stored in the order in which they appear in the original problem. If constraint i is a range constraint, c[i] will be the constraint that has the slack on the lower bound on c[i]. The constraint with the slack on... |
c[self.original_m:self.original_m+self.nrangeC] -= self.Ucon[rangeC] c[self.original_m:self.original_m+self.nrangeC] *= -1 c[self.original_m:self.original_m+self.nrangeC] -= s_up[nupperC:] | c[om:om+nrangeC] -= self.Ucon[rangeC] c[om:om+nrangeC] *= -1 c[om:om+nrangeC] -= s_up[nupperC:] | def cons(self, x): """ Evaluate the vector of general constraints for the modified problem. Constraints are stored in the order in which they appear in the original problem. If constraint i is a range constraint, c[i] will be the constraint that has the slack on the lower bound on c[i]. The constraint with the slack on... |
nt = self.original_n + self.n_con_low + self.n_con_up | nt = on + self.n_con_low + self.n_con_up | def cons(self, x): """ Evaluate the vector of general constraints for the modified problem. Constraints are stored in the order in which they appear in the original problem. If constraint i is a range constraint, c[i] will be the constraint that has the slack on the lower bound on c[i]. The constraint with the slack on... |
b = c[self.original_m+self.nrangeC:] | b = c[om+nrangeC:] | def cons(self, x): """ Evaluate the vector of general constraints for the modified problem. Constraints are stored in the order in which they appear in the original problem. If constraint i is a range constraint, c[i] will be the constraint that has the slack on the lower bound on c[i]. The constraint with the slack on... |
n = self.n t_low = x[msup:mtlow] t_up = x[mtlow:] | n = self.n ; on = self.original_n mslow = on + nrangeC + self.n_con_low msup = mslow + self.n_con_up nt = self.original_n + self.n_con_low + self.n_con_up ntlow = nt + self.n_var_low t_low = x[msup:ntlow] t_up = x[ntlow:] | def Bounds(self, x): """ Evaluate the vector of equality constraints corresponding to bounds on the variables in the original problem. """ lowerB = self.lowerB ; nlowerB = self.nlowerB upperB = self.upperB ; nupperB = self.nupperB rangeB = self.rangeB ; nrangeB = self.nrangeB |
base, field, = rel.split(LOOKUP_SEP) | base, field = rel.split(LOOKUP_SEP)[0:2] | def add_fields(to_fields, to_field, bind_fields): if not (to_field in to_fields): to_fields[to_field] = set() to_fields[to_field].update(bind_fields) |
url(r'choices/(?:(?P<object_id>\w+)/)?$', | url(r'(?:add|(?P<object_id>\w+))/choices/$', | def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) |
url = '/admin/%s/%s/choices/' % (app_name, model_name) | def add_fields(to_fields, to_field, bind_fields): if not (to_field in to_fields): to_fields[to_field] = set() to_fields[to_field].update(bind_fields) | |
self.field = field | super(GroupedModelChoiceIterator, self).__init__(field) | def __init__(self, field): self.field = field self.groups = field._groups |
class Record(models.Model): id = models.IntegerField(primary_key=True) domain = models.ForeignKey(Domains) name = models.CharField(max_length=255) | class Record(models.Model): id = models.IntegerField(primary_key=True) domain = models.ForeignKey(Domain) name = models.CharField(max_length=255) | def __unicode__(self): return self.name |
name = models.CharField(max_length=255) type = models.CharField(max_length=6) content = models.CharField(max_length=255) ttl = models.IntegerField() prio = models.IntegerField() change_date = models.IntegerField() | name = models.CharField(max_length=255, blank=True, null=True) type = models.CharField(max_length=6, blank=True, null=True) content = models.CharField(max_length=255, blank=True, null=True) ttl = models.IntegerField(blank=True, null=True) prio = models.IntegerField(blank=True, null=True) change_date = models.IntegerFie... | def __unicode__(self): return self.name |
account = models.CharField(max_length=40) | account = models.CharField(max_length=40, blank=True, null=True) | def __unicode__(self): return self.name |
self.name = self.name.lower() self.type = self.type.upper() | if self.name: self.name = self.name.lower() if self.type: self.type = self.type.upper() | def clean(self): if self.type == 'A': validate_ipv4_address(self.content) if self.type == 'AAAA': validate_ipv6_address(self.content) self.name = self.name.lower() # Get rid of CAPs before saving self.type = self.type.upper() # CAPITALISE before saving |
capture_flag_codes= {\ "CAPTURE_FLAGS_CHANNEL_ALLOC" : 0x00000001,\ "CAPTURE_FLAGS_BANDWIDTH_ALLOC" : 0x00000002,\ "CAPTURE_FLAGS_DEFAULT" : 0x00000004,\ "CAPTURE_FLAGS_AUTO_ISO" : 0x00000008 | capture_flag_codes = { "CAPTURE_FLAGS_CHANNEL_ALLOC": 0x00000001, "CAPTURE_FLAGS_BANDWIDTH_ALLOC": 0x00000002, "CAPTURE_FLAGS_DEFAULT": 0x00000004, "CAPTURE_FLAGS_AUTO_ISO": 0x00000008, | def invert_dict( to_invert ): return dict((j, i) for i, j in to_invert.iteritems()) |
_dll.dc1394_format7_get_roi.argtypes = [ POINTER(camera_t), video_mode_t, color_coding_t,\ POINTER(c_int32), POINTER(c_int32), POINTER(c_int32),\ POINTER(c_int32), POINTER(c_int32) ] | _dll.dc1394_format7_get_roi.argtypes = [ POINTER(camera_t), video_mode_t, POINTER(color_coding_t), POINTER(c_int32), POINTER(c_int32), POINTER(c_int32), POINTER(c_int32), POINTER(c_int32) ] | def _errcheck( rtype, func, arg ): """This function checks for the errortypes declared by the error_t above. Use it for functions with restype=error_t to receive correct error messages from the library. """ if rtype != 0: e = DC1394Error() e.function = func e.arguments = arg e.errval = rtype raise e return rtype |
self._h = _dll.dc1394_new() self.cameralist = self.enumerate_cameras() | self.h = _dll.dc1394_new() if self.h == None: raise RuntimeError("DC1394 Library not found") | def __init__( self ): # we cache the dll, so it gets not deleted before we cleanup self._dll = _dll self._h = _dll.dc1394_new() self.cameralist = self.enumerate_cameras() |
def h(self): "The handle to the library context." return self._h | def cameralist(self): "list of available cameras and IDs" return self.enumerate_cameras() | def h(self): "The handle to the library context." return self._h |
if self._h is not None: self._dll.dc1394_free( self._h ) self._h = None | if self.h is not None: self._dll.dc1394_free( self.h ) self.h = None | def close( self ): if self._h is not None: self._dll.dc1394_free( self._h ) self._h = None self.cameralist = [] |
value /= 1000. | val /= 1000. | def fset(self, value): if self._name == "white_balance": #white has its own call since it returns 2 values blue, red = value self._dll.dc1394_feature_whitebalance_set_value( self._cam._cam, blue, red ) else: if self._absolute_capable: val = float(value) # We want shutter in ms if self._name == "shutter": value /= 1000.... |
if self._name == "shutter": min.value *=1000 max.value *=1000 | def range(self): "The RO foo property." if self._absolute_capable: min, max = c_float(), c_float() self._dll.dc1394_feature_get_absolute_boundaries( self._cam._cam,\ self._id, byref(min),byref(max)) # We want shutter in ms if self._name == "shutter": min.value *=1000 max.value *=1000 #end if name else: min, max = c_uin... | |
def power(self, on=True): self._dll.dc1394_camera_set_power(self._cam, on) | def __del__(self): self.close() | |
if not frame: | if not bool(frame): | def flush(self): """ flush the DMA buffer """ frame = POINTER(video_frame_t)() while True: self._dll.dc1394_capture_dequeue(self._cam, CAPTURE_POLICY_POLL, byref(frame)) if not frame: break self._dll.dc1394_capture_enqueue(self._cam, frame) |
if frame.contents.image == 0: | if not bool(frame): | def capture(self, poll=False): frame = POINTER(video_frame_t)() policy = poll and CAPTURE_POLICY_POLL or CAPTURE_POLICY_WAIT self._dll.dc1394_capture_dequeue(self._cam, policy, byref(frame)) if frame.contents.image == 0: return if self._dll.dc1394_capture_is_frame_corrupt(self._cam, frame): print "frame %s corrupt" % f... |
return 1.0/fi.value | return (1.0/fi.value if fi.value else 0) | def fget(self): if 'FORMAT7' not in self.mode[-1].upper(): ft = framerate_t() self._dll.dc1394_video_get_framerate( self._cam, byref(ft)) return framerate_vals[ ft.value ] else: fi = c_float() self._dll.dc1394_format7_get_frame_interval(self._cam,\ self._wanted_mode, byref(fi)) #this should be corrected: return 1.0/fi... |
self.cameralist = [] | def close( self ): if self.h is not None: self._dll.dc1394_free( self.h ) self.h = None self.cameralist = [] | |
def start(self, queue=0): | def start(self, queue=0, mark_corrupt=True): | def start(self, queue=0): """ Start the handling of acquired frames. |
img.enqueue() | if self.mark_corrupt: img_copy.corruption_marker = img.corrupt img.enqueue() img = img_copy | def run(self): """ Called in the acquisition thread. |
self.current = img_copy | self.current = img | def run(self): """ Called in the acquisition thread. |
self.queue.put_nowait(self.current) | try: self.queue.put_nowait(self.current) except Full: pass | def run(self): """ Called in the acquisition thread. |
Price in DB are like '50.00' or '50.00/70.00' | Price in DB are like '' or '50.00' or '50.00/70.00' | def filterByPrice(self, results, tarifMin, tarifMax): """ Price in DB are like '50.00' or '50.00/70.00' This method parses this field and compare values to search criteria """ if tarifMax is None: tarifMax = 1e10 #tarif max infini, plus rapide pour les comparaison def isRangePricedHeb(heb): hebTarifs = heb.heb_tarif_c... |
hebergementType = data.get('hebergementType') communesLocalites = data.get('commune') | def action_search(self, action, data): wrapper = getSAWrapper('gites_wallons') session = wrapper.session hebergementTable = wrapper.getMapper('hebergement') proprioTable = wrapper.getMapper('proprio') reservationsTable = wrapper.getMapper('reservation_proprio') communeTable = wrapper.getMapper('commune') episTable = wr... | |
if communeLocalite and communeLocalite != '-1': | if communeLocalite and str(communeLocalite) != '-1': | def action_search(self, action, data): wrapper = getSAWrapper('gites_wallons') session = wrapper.session hebergementTable = wrapper.getMapper('hebergement') proprioTable = wrapper.getMapper('proprio') reservationsTable = wrapper.getMapper('reservation_proprio') communeTable = wrapper.getMapper('commune') episTable = wr... |
if classification and classification != -1: | if classification and str(classification) != '-1': | def action_search(self, action, data): wrapper = getSAWrapper('gites_wallons') session = wrapper.session hebergementTable = wrapper.getMapper('hebergement') proprioTable = wrapper.getMapper('proprio') reservationsTable = wrapper.getMapper('reservation_proprio') communeTable = wrapper.getMapper('commune') episTable = wr... |
if tarif and tarif != '-1': | if tarif and str(tarif) != '-1': | def action_search(self, action, data): wrapper = getSAWrapper('gites_wallons') session = wrapper.session hebergementTable = wrapper.getMapper('hebergement') proprioTable = wrapper.getMapper('proprio') reservationsTable = wrapper.getMapper('reservation_proprio') communeTable = wrapper.getMapper('commune') episTable = wr... |
overlay = Tooltip(urwid.LineBox(tooltiptext), listbox, 'left', ('relative', 100), ('fixed top', 0), None) | overlay = Tooltip(urwid.Filler(urwid.LineBox(tooltiptext)), listbox, 'left', ('relative', 100), ('fixed top', 0), ('relative', 50)) | def main(args=None, locals_=None, banner=None): # Err, somewhat redundant. There is a call to this buried in urwid.util. # That seems unfortunate though, so assume that's going away... locale.setlocale(locale.LC_ALL, '') # TODO: maybe support displays other than raw_display? config, options, exec_args = bpargs.parse(a... |
def echo(self, s): s = s.rstrip('\n') | def echo(self, orig_s): s = orig_s.rstrip('\n') | def echo(self, s): s = s.rstrip('\n') if s: text = urwid.Text(('output', s)) if self.edit is None: self.listbox.body.append(text) else: self.listbox.body.insert(-1, text) # The edit widget should be focused and *stay* focused. # XXX TODO: make sure the cursor stays in the same spot. self.listbox.set_focus(len(self.list... |
text = urwid.Text(('output', s)) if self.edit is None: self.listbox.body.append(text) | if self.current_output is None: self.current_output = urwid.Text(('output', s)) if self.edit is None: self.listbox.body.append(self.current_output) else: self.listbox.body.insert(-1, self.current_output) self.listbox.set_focus(len(self.listbox.body) - 1) | def echo(self, s): s = s.rstrip('\n') if s: text = urwid.Text(('output', s)) if self.edit is None: self.listbox.body.append(text) else: self.listbox.body.insert(-1, text) # The edit widget should be focused and *stay* focused. # XXX TODO: make sure the cursor stays in the same spot. self.listbox.set_focus(len(self.list... |
self.listbox.body.insert(-1, text) self.listbox.set_focus(len(self.listbox.body) - 1) | self.current_output.set_text( ('output', self.current_output.text + s)) if orig_s.endswith('\n'): self.current_output = None | def echo(self, s): s = s.rstrip('\n') if s: text = urwid.Text(('output', s)) if self.edit is None: self.listbox.body.append(text) else: self.listbox.body.insert(-1, text) # The edit widget should be focused and *stay* focused. # XXX TODO: make sure the cursor stays in the same spot. self.listbox.set_focus(len(self.list... |
return repl.getstdout() | return clirepl.getstdout() | def main_curses(scr, args, config, interactive=True, locals_=None, banner=None): """main function for the curses convenience wrapper Initialise the two main objects: the interpreter and the repl. The repl does what a repl does and lots of other cool stuff like syntax highlighting and stuff. I've tried to keep it well ... |
return self.statusbar.prompt(q).lower().startswith('y') | try: reply = self.statusbar.prompt(q) except ValueError: return False return reply.lower() in ('y', 'yes') | def confirm(self, q): """Ask for yes or no and return boolean""" return self.statusbar.prompt(q).lower().startswith('y') |
continue if c == 27: | elif c == 10: break elif c == 27: | def bs(s): y, x = self.win.getyx() if x == ix: return s s = s[:-1] self.win.delch(y, x - 1) self.win.move(y, x - 1) return s |
if not c or c < 0 or c > 127: continue c = chr(c) if c == '\n': break self.win.addstr(c, get_colpair(self.config, 'prompt')) o += c | elif 0 <= c < 127: c = chr(c) self.win.addstr(c, get_colpair(self.config, 'prompt')) o += c | def bs(s): y, x = self.win.getyx() if x == ix: return s s = s[:-1] self.win.delch(y, x - 1) self.win.move(y, x - 1) return s |
config.load_theme(struct, TEST_THEME_PATH, "test.ini", defaults) | config.load_gtk_theme(struct, TEST_THEME_PATH, "test.ini", defaults) | def test_load_gtk_scheme(self): struct = config.Struct() config.load_gtk_theme(struct, TEST_THEME_PATH, "test.ini", dict()) expected = {"keyword": "y"} self.assertEquals(struct.color_gtk_scheme, expected) |
self.tooltip = urwid.ListBox(urwid.SimpleListWalker([ urwid.Text(''), urwid.Text(''), urwid.Text('')])) self.tooltip.set_focus(1) | self.tooltip = urwid.ListBox(urwid.SimpleListWalker([])) self.tooltip.grid = None | def __init__(self, event_loop, palette, interpreter, config): repl.Repl.__init__(self, interpreter, config) |
widget_list[1] = urwid.Text('') | while widget_list: widget_list.pop() | def _populate_completion(self): widget_list = self.tooltip.body widget_list[1] = urwid.Text('') # This is just me flailing around wildly. TODO: actually write. if self.complete(): if self.argspec: # This is mostly just stolen from the cli module. func_name, args, is_bound, in_arg = self.argspec args, varargs, varkw, de... |
else: markup = '' widget_list[0].set_text(markup) | widget_list.append(urwid.Text(markup)) | def _populate_completion(self): widget_list = self.tooltip.body widget_list[1] = urwid.Text('') # This is just me flailing around wildly. TODO: actually write. if self.complete(): if self.argspec: # This is mostly just stolen from the cli module. func_name, args, is_bound, in_arg = self.argspec args, varargs, varkw, de... |
widget_list[1] = gridflow | widget_list.append(gridflow) self.tooltip.grid = gridflow | def _populate_completion(self): widget_list = self.tooltip.body widget_list[1] = urwid.Text('') # This is just me flailing around wildly. TODO: actually write. if self.complete(): if self.argspec: # This is mostly just stolen from the cli module. func_name, args, is_bound, in_arg = self.argspec args, varargs, varkw, de... |
else: docstring = '' widget_list[2].set_text(('comment', docstring)) | widget_list.append(urwid.Text(('comment', docstring))) | def _populate_completion(self): widget_list = self.tooltip.body widget_list[1] = urwid.Text('') # This is just me flailing around wildly. TODO: actually write. if self.complete(): if self.argspec: # This is mostly just stolen from the cli module. func_name, args, is_bound, in_arg = self.argspec args, varargs, varkw, de... |
self.tooltip.body[1].set_focus(self.matches_iter.index) | if self.tooltip.grid: self.tooltip.grid.set_focus(self.matches_iter.index) | def tab(self, back=False): """Process the tab key being hit. |
parser = OptionParser(usage='Usage: %prog [options] [file [args]]\n' 'NOTE: If bpython sees an argument it does ' 'not know, execution falls back to the ' 'regular Python interpreter.') | parser = RaisingOptionParser( usage='Usage: %prog [options] [file [args]]\n' 'NOTE: If bpython sees an argument it does ' 'not know, execution falls back to the ' 'regular Python interpreter.') parser.disable_interspersed_args() | def parse(args, extras=None): """Receive an argument list - if None, use sys.argv - parse all args and take appropriate action. Also receive optional extra options: this should be a tuple of (title, description, options) title: The title for the option group description: A full description of the option gro... |
all_args = set(parser._short_opt.keys() + parser._long_opt.keys()) if args and not all_args.intersection(arg.split('=')[0] for arg in args): | try: options, args = parser.parse_args(args) except OptionParserFailed: | def parse(args, extras=None): """Receive an argument list - if None, use sys.argv - parse all args and take appropriate action. Also receive optional extra options: this should be a tuple of (title, description, options) title: The title for the option group description: A full description of the option gro... |
else: real_args = list(takewhile(lambda arg: arg.split('=')[0] in all_args, args)) exec_args = args[len(real_args):] options, args = parser.parse_args(real_args) | def parse(args, extras=None): """Receive an argument list - if None, use sys.argv - parse all args and take appropriate action. Also receive optional extra options: this should be a tuple of (title, description, options) title: The title for the option group description: A full description of the option gro... | |
return config, options, exec_args | return config, options, args | def parse(args, extras=None): """Receive an argument list - if None, use sys.argv - parse all args and take appropriate action. Also receive optional extra options: this should be a tuple of (title, description, options) title: The title for the option group description: A full description of the option gro... |
self.index = (self.index - 1) % len(self.matches) | if self.index <= 0: self.index = len(self.matches) self.index -= 1 | def previous(self): self.index = (self.index - 1) % len(self.matches) return self.matches[self.index] |
if not path: path = os.curdir | if not p: p = os.curdir | def find_all_modules(path=None): """Return a list with all modules in `path`, which should be a list of directory names. If path is not given, sys.path will be used.""" if path is None: modules.update(sys.builtin_module_names) path = sys.path for p in path: if not path: path = os.curdir for module in find_modules(p): ... |
indent = next_indentation(self.s, self.config.tab_length) | indent = repl.next_indentation(self.s, self.config.tab_length) | def reevaluate(self): """Clear the buffer, redraw the screen and re-evaluate the history""" |
from bpython.args import parse class TestRepl(unittest.TestCase): def setUp(self): config = parse(args=[])[0] self.interp = repl.Interpreter() self.repl = repl.Repl(self.interp, config) def test_attr_matches(self): self.assertEqual(self.repl.attr_matches('str.s'), ['str.%s' % x for x in dir(str) if x.startswith('s'... | def test_update(self): slice = islice(self.matches_iterator, 0, 3) self.assertEqual(list(slice), self.matches) | |
return self.statusbar.prompt(q).lower().startswith('y') | try: reply = self.statusbar.prompt(q) except ValueError: return False return reply.lower() in ('y', 'yes') | def ask_confirmation(self, q): """Ask for yes or no and return boolean""" return self.statusbar.prompt(q).lower().startswith('y') |
max_y = min(self.iy + len(self.s) // width + 1, height) | max_y = min(self.iy + (self.ix + len(self.s)) // width + 1, height) | def clear_wrapped_lines(self): """Clear the wrapped lines of the current input.""" # curses does not handle this on its own. Sad. height, width = self.scr.getmaxyx() max_y = min(self.iy + len(self.s) // width + 1, height) for y in xrange(self.iy + 1, max_y): self.scr.move(y, 0) self.scr.clrtoeol() |
if not self.f_strings: for k, v in theme_map.iteritems(): self.f_strings[k] = '\x01%s' % (color_scheme[v],) if k is Parenthesis: self.f_strings[k] += 'I' | self.f_strings = {} for k, v in theme_map.iteritems(): self.f_strings[k] = '\x01%s' % (color_scheme[v],) if k is Parenthesis: self.f_strings[k] += 'I' | def __init__(self, color_scheme, **options): if not self.f_strings: for k, v in theme_map.iteritems(): self.f_strings[k] = '\x01%s' % (color_scheme[v],) if k is Parenthesis: # FIXME: Find a way to make this the inverse of the current # background colour self.f_strings[k] += 'I' Formatter.__init__(self, **options) |
if not py3: | if py3: key = key.encode('latin-1').decode(getpreferredencoding()) else: | def get_key(self): key = '' while True: try: key += self.scr.getkey() if not py3: key = key.decode(getpreferredencoding()) self.scr.nodelay(False) except UnicodeDecodeError: |
yield self | return self | def __iter__(self): yield self |
try: sys.stdout = myrepl sys.stderr = myrepl def start(main_loop, user_data): if exec_args: bpargs.exec_code(interpreter, exec_args) if not options.interactive: raise urwid.ExitMainLoop() if not exec_args: sys.path.insert(0, '') filename = os.environ.get('PYTHONSTARTUP') if filename and os.path.isfile(filen... | def run_with_screen_before_mainloop(): try: sys.stdin = None sys.stdout = myrepl sys.stderr = myrepl loop.set_alarm_in(0, start) while True: try: loop.run() except KeyboardInterrupt: loop.set_alarm_in( 0, lambda *args: myrepl.keyboard_interrupt()) continue break if config.hist_length: histfilename = os.path.e... | def sigint(*args): reactor.callFromThread(myrepl.keyboard_interrupt) |
self.text_buffer.insert_with_tags_by_name(self.get_cursor_iter(), text, 'prompt') iter_ = self.move_cursor(len(text)) | iter_ = self.get_cursor_iter() self.text_buffer.insert_with_tags_by_name(iter_, text, 'prompt') iter_.forward_chars(4) | def prompt(self, more): """ Show the appropriate Python prompt. """ if more: text = '... ' else: text = '>>> ' with self.editing: self.text_buffer.insert_with_tags_by_name(self.get_cursor_iter(), text, 'prompt') iter_ = self.move_cursor(len(text)) mark = self.text_buffer.create_mark('line_start', iter_, True) self.text... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.