rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
for i in xrange(0, l - 2):
for i in xrange(0, l-1):
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise. EXAMPLES:: sage: W = Words('123') sage: W('12312').is_square_free() True sage: W('31212').is_square_free() False sage: W().is_square_free() True """ l = self.length() if l < 2: return True suff = self for i in xrange(0,...
except:
except MIPSolverException:
def edge_coloring(g, value_only=False, vizing=False, hex_colors=False, log=0): r""" Properly colors the edges of a graph. See the URL http://en.wikipedia.org/wiki/Edge_coloring for further details on edge coloring. INPUT: - ``g`` -- a graph. - ``value_only`` -- (default: ``False``): - When set to ``True``, only the...
"""
r"""
def eigenvalues(self,extend=True): """ Returns a list with the eigenvalues of the endomorphism of vector spaces. If the option extend is set to True (default), then eigenvalues in extensions of the base field are considered. EXAMPLES: We compute the eigenvalues of an endomorphism of QQ^3:: sage: V=QQ^3 sage: H=V.en...
If the option extend is set to True (default), then eigenvalues in extensions of the base field are considered.
INPUT: - ``extend`` -- boolean (default: True) decides if base field extensions should be considered or not.
def eigenvalues(self,extend=True): """ Returns a list with the eigenvalues of the endomorphism of vector spaces. If the option extend is set to True (default), then eigenvalues in extensions of the base field are considered. EXAMPLES: We compute the eigenvalues of an endomorphism of QQ^3:: sage: V=QQ^3 sage: H=V.en...
We compute the eigenvalues of an endomorphism of QQ^3::
We compute the eigenvalues of an endomorphism of `\QQ^3`::
def eigenvalues(self,extend=True): """ Returns a list with the eigenvalues of the endomorphism of vector spaces. If the option extend is set to True (default), then eigenvalues in extensions of the base field are considered. EXAMPLES: We compute the eigenvalues of an endomorphism of QQ^3:: sage: V=QQ^3 sage: H=V.en...
Note the effect of the extend option::
Note the effect of the ``extend`` option::
def eigenvalues(self,extend=True): """ Returns a list with the eigenvalues of the endomorphism of vector spaces. If the option extend is set to True (default), then eigenvalues in extensions of the base field are considered. EXAMPLES: We compute the eigenvalues of an endomorphism of QQ^3:: sage: V=QQ^3 sage: H=V.en...
- extend (True) decides if base field extensions should be considered or not.
- ``extend`` -- boolean (default: True) decides if base field extensions should be considered or not.
def eigenvectors(self,extend=True): """ Computes the subspace of eigenvectors of a given eigenvalue. INPUT: - extend (True) decides if base field extensions should be considered or not. OUTPUT: A sequence of tuples. Each tuple contains an eigenvalue, a list with a basis of the corresponding subspace of eigenvectors...
A sequence of tuples. Each tuple contains an eigenvalue, a list with a basis of the corresponding subspace of eigenvectors, and the algebraic multiplicity of the eigenvalue.
A sequence of tuples. Each tuple contains an eigenvalue, a sequence with a basis of the corresponding subspace of eigenvectors, and the algebraic multiplicity of the eigenvalue.
def eigenvectors(self,extend=True): """ Computes the subspace of eigenvectors of a given eigenvalue. INPUT: - extend (True) decides if base field extensions should be considered or not. OUTPUT: A sequence of tuples. Each tuple contains an eigenvalue, a list with a basis of the corresponding subspace of eigenvectors...
svectors=map(lambda j: V(j * V.basis_matrix()),i[1]) resu.append(tuple([i[0],svectors,i[2]]))
svectors=Sequence(map(lambda j: V(j * V.basis_matrix()),i[1]), cr=True) resu.append((i[0],svectors,i[2]))
def eigenvectors(self,extend=True): """ Computes the subspace of eigenvectors of a given eigenvalue. INPUT: - extend (True) decides if base field extensions should be considered or not. OUTPUT: A sequence of tuples. Each tuple contains an eigenvalue, a list with a basis of the corresponding subspace of eigenvectors...
- ``var`` - string (default: 'x') a variable
- ``var`` - string (default: 'x') a variable name
def minpoly(self,var='x'): """ Computes the minimal polynomial. INPUT: - ``var`` - string (default: 'x') a variable OUTPUT: polynomial in var - the minimal polynomial of the endomorphism. EXAMPLES: Compute the minimal polynomial, and check it :: sage: V=GF(7)^3 sage: H=V.Hom(V)([[0,1,2],[-1,0,3],[2,4,1]]) sage:...
.. [CB07] Nicolas T\. Courtois, Gregory V\. Bard *Algebraic Cryptanalysis of the Data Encryption Standard*; Cryptography and Coding -- 11th IMA International Conference; 2007; available at http://eprint.iacr.org/2006/402
.. [CBJ07] Gregory V\. Bard, and Nicolas T\. Courtois, and Chris Jefferson. *Efficient Methods for Conversion and Solution of Sparse Systems of Low-Degree Multivariate Polynomials over GF(2) via SAT-Solvers*. Cryptology ePrint Archive: Report 2007/024. available at http://eprint.iacr.org/2007/024
def eliminate_linear_variables(self, maxlength=3, skip=lambda lm,tail: False): """ Return a new system where "linear variables" are eliminated.
This is called "massaging" in [CB07]_.
This is called "massaging" in [CBJ07]_.
def eliminate_linear_variables(self, maxlength=3, skip=lambda lm,tail: False): """ Return a new system where "linear variables" are eliminated.
Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``.
Return a list of the associated primes of primary ideals of which the intersection is `I` = ``self``.
def associated_primes(self, algorithm='sy'): r""" Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``. An ideal `Q` is called primary if it is a proper ideal of the ring `R` and if whenever `ab \in Q` and `a \not\in Q` then `b^n \in Q` for some `n \in \ZZ`. If ...
- ``list`` - a list of primary ideals and their associated primes [(primary ideal, associated prime), ...]
- ``list`` - a list of associated primes
def associated_primes(self, algorithm='sy'): r""" Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``. An ideal `Q` is called primary if it is a proper ideal of the ring `R` and if whenever `ab \in Q` and `a \not\in Q` then `b^n \in Q` for some `n \in \ZZ`. If ...
f_l_dict = {(None,None):[(tuple([x]),tuple(self._vertex_face_indexset([x])))
f_l_dict = {(None,tuple(range(self.n_Hrepresentation()))):[(tuple([x]),tuple(self._vertex_face_indexset([x])))
def face_lattice(self): """ Computes the face-lattice poset. Elements are tuples of (vertices, facets) - i.e. this keeps track of both the vertices in each face, and all the facets containing them.
tuple(range(self.n_Hrepresentation()))))
None))
def face_lattice(self): """ Computes the face-lattice poset. Elements are tuples of (vertices, facets) - i.e. this keeps track of both the vertices in each face, and all the facets containing them.
if len(xi) != n:
if len(yi) != n:
def cnf(self, xi=None, yi=None, format=None): """ Return a representation of this S-Box in conjunctive normal form.
x = self.to_bits(e)
x = self.to_bits(e, m)
def cnf(self, xi=None, yi=None, format=None): """ Return a representation of this S-Box in conjunctive normal form.
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain. Use ``self.defining_ideal().i...
def is_integral_domain(self, proof=True): r""" With ``proof`` equal to ``True`` (the default), this function may raise a ``NotImplementedError``. When ``proof`` is ``False``, if ``True`` is returned, then self is definitely an integral domain. If the function returns ``False``, then either self is not an integral do...
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain. Use ``self.defining_ideal().i...
sage: R.<a,b,c> = ZZ['a','b','c'] sage: I = R.ideal(a,b) sage: Q = R.quotient_ring(I)
sage: R.quo(x^2 - y^2).is_integral_domain(proof=False) False sage: R.<a,b,c> = ZZ[] sage: Q = R.quotient_ring([a, b])
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain. Use ``self.defining_ideal().i...
return self.defining_ideal.is_prime() except AttributeError: return False
return self.defining_ideal().is_prime()
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain. Use ``self.defining_ideal().i...
xy_data_arrays = map(lambda g: [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)], g) xy_data_array = map(lambda *rows: map(lambda *vals: mangle_neg(vals), *rows), *xy_data_arrays)
xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in g],dtype=float) xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0)) neg_indices = (xy_data_arrays<0).all(axis=0) xy_data_array[neg_indices]=-xy_data_array...
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ym...
def mangle_neg(vals): """ Returns the product of all values in vals, with the result nonnegative if any of the values is nonnegative. EXAMPLES:: sage: from sage.plot.contour_plot import mangle_neg sage: mangle_neg([-1.2, -0.74, -2.56, -1.01]) -2.29601280000000 sage: mangle_neg([-1.2, 0.0, -2.56]) 0.000000000000000 sa...
def equify(f): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x^2 - 2 sage: equify(x^2 > 2) -x^2 + 2 sage: equify(x*y > 1) -x*y + 1 sage: equify(...
- ``e`` - A Composition
- ``e`` - a composition
def LyndonWords(e=None, k=None): """ Returns the combinatorial class of Lyndon words. A Lyndon word `w` is a word that is lexicographically less than all of its rotations. Equivalently, whenever `w` is split into two non-empty substrings, `w` is lexicographically less than the right substring. INPUT: - no input at ...
A combinatorial class of Lyndon words
A combinatorial class of Lyndon words.
def LyndonWords(e=None, k=None): """ Returns the combinatorial class of Lyndon words. A Lyndon word `w` is a word that is lexicographically less than all of its rotations. Equivalently, whenever `w` is split into two non-empty substrings, `w` is lexicographically less than the right substring. INPUT: - no input at ...
verification that the input data represent a lyndon word.
verification that the input data represent a Lyndon word.
def __init__(self, data, check=True): r""" Construction of a Lyndon word.
a lyndon word
A Lyndon word.
def __init__(self, data, check=True): r""" Construction of a Lyndon word.
sage: browse_sage_doc(identity_matrix, 'rst')[:9] '**File:**' sage: browse_sage_doc(identity_matrix, 'rst')[-60:] 'MatrixSpace of 3 by 3 sparse matrices over Integer Ring\n ' sage: browse_sage_doc(identity_matrix, 'html', False)[:59] '<div class="docstring">\n \n <p><strong>File:</strong> /v'
sage: browse_sage_doc(identity_matrix, 'rst') "...**File:**...**Type:**...**Definition:** identity_matrix..." sage: identity_matrix.__doc__.replace('\\','\\\\') in browse_sage_doc(identity_matrix, 'rst') True sage: browse_sage_doc(identity_matrix, 'html', False) '...div...File:...Type:...Definition:...identity_matrix.....
def __call__(self, obj, output='html', view=True): r""" Return the documentation for ``obj``.
return (self._sublattice_polytope.facet_constant(i) - self.facet_normal(i) * self._shift_vector)
return (self._sublattice_polytope.facet_constant(i) * self._dual_embedding_scale - self.facet_normal(i) * self._shift_vector )
def facet_constant(self, i): r""" Return the constant in the ``i``-th facet inequality of this polytope. The i-th facet inequality is given by self.facet_normal(i) * X + self.facet_constant(i) >= 0. INPUT: - ``i`` - integer, the index of the facet OUTPUT: - integer -- the constant in the ``i``-th facet inequality....
return (self._embedding_matrix * self._sublattice_polytope.facet_normal(i))
return ( self._sublattice_polytope.facet_normal(i) * self._dual_embedding_matrix )
def facet_normal(self, i): r""" Return the inner normal to the ``i``-th facet of this polytope. If this polytope is not full-dimensional, facet normals will be parallel to the affine subspace spanned by this polytope. INPUT: - ``i`` -- integer, the index of the facet OUTPUT: - vectors -- the inner normal of the ``...
from optparse import OptionParser parser = OptionParser() parser.add_option("-y", "--ymin", dest="ymin", default="0", help="minimum y value") parser.add_option("-Y", "--ymax", dest="ymax", default="10", help="maximum y value") parser.add_option("-N", "--Names", dest="hosts", nargs=2, default=None, help="host list for ...
def main(): # Right now there are no command line arguments # we just open every file we're given # and read the packets from it. files = [] for filename in sys.argv[1:]: pcap = pcs.PcapConnector(filename) trace = {} done = False while not done: try: packet = pcap.readpkt() except: done = True if packet.data == Non...
for filename in sys.argv[1:]:
for filename in options.hosts:
def main(): # Right now there are no command line arguments # we just open every file we're given # and read the packets from it. files = [] for filename in sys.argv[1:]: pcap = pcs.PcapConnector(filename) trace = {} done = False while not done: try: packet = pcap.readpkt() except: done = True if packet.data == Non...
for i in range(0,len(files[0])):
plotter = Gnuplot.Gnuplot(debug=1) plotter.set_range('yrange', [options.ymin, options.ymax]) graph = [] for i in range(options.start,options.start + len(files[0])):
def main(): # Right now there are no command line arguments # we just open every file we're given # and read the packets from it. files = [] for filename in sys.argv[1:]: pcap = pcs.PcapConnector(filename) trace = {} done = False while not done: try: packet = pcap.readpkt() except: done = True if packet.data == Non...
if files[0][i] == files[1][i]: print "0:00:00.000000" continue
delta = abs(files[1][i] - files[0][i])
def main(): # Right now there are no command line arguments # we just open every file we're given # and read the packets from it. files = [] for filename in sys.argv[1:]: pcap = pcs.PcapConnector(filename) trace = {} done = False while not done: try: packet = pcap.readpkt() except: done = True if packet.data == Non...
if files[0][i] < files[1][i]: print files[1][i] - files[0][i] else: print files[0][i] - files[1][i]
def main(): # Right now there are no command line arguments # we just open every file we're given # and read the packets from it. files = [] for filename in sys.argv[1:]: pcap = pcs.PcapConnector(filename) trace = {} done = False while not done: try: packet = pcap.readpkt() except: done = True if packet.data == Non...
self.file = socket(AF_INET6, SOCK_RAW, IPPROTO_IP)
self.file = socket(AF_INET6, SOCK_RAW, IPPROTO_IPV6)
def __init__(self, name = None): """initialize an IPPConnector class for raw IPv6 access""" try: self.file = socket(AF_INET6, SOCK_RAW, IPPROTO_IP) except: raise
m = pcs.Field("m", 4)
m = pcs.Field("m", 1)
def __init__(self, bytes = None, timestamp = None, **kv): v = pcs.Field("v", 2) # version p = pcs.Field("p", 1) # padded x = pcs.Field("x", 1) # extended cc = pcs.Field("cc", 4) # csrc count m = pcs.Field("m", 4) # m-bit pt = pcs.Field("pt", 7, discriminator=True) # payload type seq = pcs.Field("seq", 16) # sequen...
pcs.Packet.__init__(self, [v, p, x, cc, m, pt, seq, ssrc, opt], \
pcs.Packet.__init__(self, [v, p, x, cc, m, pt, seq, ts, ssrc, opt], \
def __init__(self, bytes = None, timestamp = None, **kv): v = pcs.Field("v", 2) # version p = pcs.Field("p", 1) # padded x = pcs.Field("x", 1) # extended cc = pcs.Field("cc", 4) # csrc count m = pcs.Field("m", 4) # m-bit pt = pcs.Field("pt", 7, discriminator=True) # payload type seq = pcs.Field("seq", 16) # sequen...
if packet.data is not None:
if packet.data not in [None, packet]:
def chain(self): """Return the packet and its next packets as a chain.""" chain = Chain([]) packet = self done = False while not done: packet._head = chain chain.append(packet) if packet.data is not None: packet = packet.data else: done = True return chain
* simtype (string='DP'): The simulator type """
* simtype (string='Python'): The simulator type """
def __init__(self, nsd=2, time=None, space_symbs=None, simtype="Python", **kwargs): """Constructor. Arguments are: * nsd (int=2) : The number of space dimensions for the PDE * time (symbol=None): The symbol for time * space_symbs (symbol=None): List of existing symbols. * simtype (string='DP'): The simulator type """ i...
the symbolic.expression v, that returns float
the Symbolic.expression v, that returns float
def _vValue(self, point, time): """This is the point eval of the analytical solution. Pass the point to the symbolic.expression v, that returns float """ try: retVal = self.v.eval(*(point+(time, ))) except: raise FammsError, "Could not evaluate the analytical solution" return retVal
def listfiles(archive): pin = os.popen("tar ztf %s | sort" % (archive), "r") files = map(lambda x: x.strip(), pin.readlines()) pin.close() cleanedfiles = [] for file in files: slashpos = file.find("/") if slashpos != -1: cleanedname = file[slashpos+1:] else: cleanedname = file if cleanedname.find(".cache.html") != ...
def listfiles(archive): pin = os.popen("tar ztf %s | sort" % (archive), "r") files = map(lambda x: x.strip(), pin.readlines()) pin.close() cleanedfiles = [] for file in files: # Remove archive file name from the file names slashpos = file.find("/") if slashpos != -1: cleanedname = file[slashpos+1:] else: cleanedname =...
def listTarVaadinJarFiles(tarfile, vaadinversion): jarfile = "vaadin-linux-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "tar zOxf %s %s > %s " % (tarfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) comma...
def listJarFiles(jarfile): # Read the jar content listing pin = os.popen("unzip -ql %s" % jarfile, "r") lines = map(lambda x: x[:-1], pin.readlines()) pin.close() # Determine the position of file names namepos = lines[0].find("Name") files = [] for i in xrange(2, len(lines)-2): filename = lines[i][namepos:] files.appe...
tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd)
zipcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (zipcmd)
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("r...
filename = "vaadin-%s.tar.gz" % (latestversion) package = latestURL + filename localpackage = "/tmp/%s" % (filename)
latestfilename = "vaadin-%s.zip" % (latestversion) latestpackage = latestURL + latestfilename locallatestpackage = "/tmp/%s" % (latestfilename)
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("r...
os.stat(localpackage) print "Latest package already exists in %s" % (localpackage)
os.stat(locallatestpackage) print "Latest package already exists in %s" % (locallatestpackage)
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("r...
print "Downloading package %s to %s" % (package, localpackage) wgetcmd = "wget -q -O %s %s" % (localpackage, package)
print "Downloading latest release package %s to %s" % (latestpackage, locallatestpackage) wgetcmd = "wget -q -O %s %s" % (locallatestpackage, latestpackage)
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("r...
latestfiles = listfiles(localpackage)
latestfiles = listZipFiles(locallatestpackage)
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("r...
print "\n--------------------------------------------------------------------------------\nVaadin TAR differences"
print "\n--------------------------------------------------------------------------------\nVaadin ZIP differences"
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("r...
latestJarFiles = listTarVaadinJarFiles(localpackage, latestversion) builtJarFiles = listZipVaadinJarFiles(builtpackage, builtversion)
latestJarFiles = listZipVaadinJarFiles(locallatestpackage, latestversion) builtJarFiles = listZipVaadinJarFiles(builtpackage, builtversion)
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("r...
command("rm %s" % (localpackage))
command("rm %s" % (locallatestpackage))
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("r...
"""Enter an infinite "monitoring" loop. The argument, callback, defines the function to call when an ExitNotifyThread has terminated. That function is called with a single argument -- the ExitNotifyThread that has terminated. The monitor will not continue to monitor for other threads until the function returns, so if...
"""An infinite "monitoring" loop watching for finished ExitNotifyThread's. :param callback: the function to call when a thread terminated. That function is called with a single argument -- the ExitNotifyThread that has terminated. The monitor will not continue to monitor for other threads until 'callback' returns, so ...
def exitnotifymonitorloop(callback): """Enter an infinite "monitoring" loop. The argument, callback, defines the function to call when an ExitNotifyThread has terminated. That function is called with a single argument -- the ExitNotifyThread that has terminated. The monitor will not continue to monitor for other thre...
while 1: try: thrd = exitthreads.get(False)
while 1: try: thrd = exitthreads.get(True, 60)
def exitnotifymonitorloop(callback): """Enter an infinite "monitoring" loop. The argument, callback, defines the function to call when an ExitNotifyThread has terminated. That function is called with a single argument -- the ExitNotifyThread that has terminated. The monitor will not continue to monitor for other thre...
time.sleep(1)
pass
def exitnotifymonitorloop(callback): """Enter an infinite "monitoring" loop. The argument, callback, defines the function to call when an ExitNotifyThread has terminated. That function is called with a single argument -- the ExitNotifyThread that has terminated. The monitor will not continue to monitor for other thre...
abortsleep = s.sleeping(1, sleepsecs) sleepsecs -= 1
abortsleep = s.sleeping(10, sleepsecs) sleepsecs -= 10
def sleep(s, sleepsecs, siglistener): """This function does not actually output anything, but handles the overall sleep, dealing with updates as necessary. It will, however, call sleeping() which DOES output something.
s._msg("Next refresh in %d seconds" % remainingsecs)
def sleeping(s, sleepsecs, remainingsecs): """Sleep for sleepsecs, remainingsecs to go. If sleepsecs is 0, indicates we're done sleeping.
def warn(s, msg, minor):
def warn(s, msg, minor = 0):
def warn(s, msg, minor): s._printData('warn', '%s\n%d' % (msg, int(minor)))
flagmap = {'\\seen': 'S', '\\answered': 'R', '\\flagged': 'F', '\\deleted': 'T', '\\draft': 'D'}
def flagsimap2maildir(flagstring): flagmap = {'\\seen': 'S', '\\answered': 'R', '\\flagged': 'F', '\\deleted': 'T', '\\draft': 'D'} retval = [] imapflaglist = [x.lower() for x in flagstring[1:-1].split()] for imapflag in imapflaglist: if flagmap.has_key(imapflag): retval.append(flagmap[imapflag]) retval.sort() return r...
for imapflag in imapflaglist: if flagmap.has_key(imapflag): retval.append(flagmap[imapflag])
for imapflag, maildirflag in flagmap: if imapflag.lower() in imapflaglist: retval.append(maildirflag)
def flagsimap2maildir(flagstring): flagmap = {'\\seen': 'S', '\\answered': 'R', '\\flagged': 'F', '\\deleted': 'T', '\\draft': 'D'} retval = [] imapflaglist = [x.lower() for x in flagstring[1:-1].split()] for imapflag in imapflaglist: if flagmap.has_key(imapflag): retval.append(flagmap[imapflag]) retval.sort() return r...
def flagsmaildir2imap(list): flagmap = {'S': '\\Seen', 'R': '\\Answered', 'F': '\\Flagged', 'T': '\\Deleted', 'D': '\\Draft'} retval = [] for mdflag in list: if flagmap.has_key(mdflag): retval.append(flagmap[mdflag])
def flagsmaildir2imap(maildirflaglist): retval = [] for imapflag, maildirflag in flagmap: if maildirflag in maildirflaglist: retval.append(imapflag)
def flagsmaildir2imap(list): flagmap = {'S': '\\Seen', 'R': '\\Answered', 'F': '\\Flagged', 'T': '\\Deleted', 'D': '\\Draft'} retval = [] for mdflag in list: if flagmap.has_key(mdflag): retval.append(flagmap[mdflag]) retval.sort() return '(' + ' '.join(retval) + ')'
import profile
try: import cProfile as profile except ImportError: import profile
def run(self): global exitthreads, profiledir self.threadid = thread.get_ident() try: if not profiledir: # normal case Thread.run(self) else: import profile prof = profile.Profile() try: prof = prof.runctx("Thread.run(self)", globals(), locals()) except SystemExit: pass prof.dump_stats( \ profiledir + "/" + st...
repo = setup['repo']
self.datastore = setup['repo']
def __call__(self, args): Bcfg2.Server.Admin.MetadataCore.__call__(self, args) # Get Bcfg2 repo directory opts = {'repo': Bcfg2.Options.SERVER_REPOSITORY} setup = Bcfg2.Options.OptionParser(opts) setup.parse(sys.argv[1:]) repo = setup['repo']
out = tarfile.open(filename, mode=mode) content = os.listdir(os.getcwd())
out = tarfile.open(self.datastore + '/' + filename, mode=mode) content = os.listdir(self.datastore)
def __call__(self, args): Bcfg2.Server.Admin.MetadataCore.__call__(self, args) # Get Bcfg2 repo directory opts = {'repo': Bcfg2.Options.SERVER_REPOSITORY} setup = Bcfg2.Options.OptionParser(opts) setup.parse(sys.argv[1:]) repo = setup['repo']
print "Archive %s was stored.\nLocation: %s" % (filename, datastore)
print "Archive %s was stored.\nLocation: %s" % (filename, self.datastore)
def __call__(self, args): Bcfg2.Server.Admin.MetadataCore.__call__(self, args) # Get Bcfg2 repo directory opts = {'repo': Bcfg2.Options.SERVER_REPOSITORY} setup = Bcfg2.Options.OptionParser(opts) setup.parse(sys.argv[1:]) repo = setup['repo']
data = raw_input("What is the server's hostname: [%s]" % socket.getfqdn())
data = raw_input("What is the server's hostname: [%s]: " % socket.getfqdn())
def _prompt_hostname(self): """Ask for the server hostname.""" data = raw_input("What is the server's hostname: [%s]" % socket.getfqdn()) if data != '': self.shostname = data else: self.shostname = socket.getfqdn()
os.makedirs(path) self._init_plugins() print "Repository created successfuly in %s" % (self.repopath)
try: os.makedirs(path) self._init_plugins() print "Repository created successfuly in %s" % (self.repopath) except OSError: print("Failed to create %s." % path)
def init_repo(self): """Setup a new repo and create the content of the configuration file.""" keypath = os.path.dirname(os.path.abspath(self.configfile)) confdata = config % ( self.repopath, ','.join(self.opts['plugins']), self.opts['sendmail'], self.opts['proto'], self.password, keypath, 'bcfg2.crt', keypath, 'bcfg2.k...
data = raw_input("What is the server's hostname: [%s]: " % socket.getfqdn())
data = raw_input("What is the server's hostname [%s]: " % socket.getfqdn())
def _prompt_hostname(self): """Ask for the server hostname.""" data = raw_input("What is the server's hostname: [%s]: " % socket.getfqdn()) if data != '': self.shostname = data else: self.shostname = socket.getfqdn()
if resolved == client:
if resolved.lower() == client.lower():
def validate_client_address(self, client, addresspair): '''Check address against client''' address = addresspair[0] if client in self.floating: self.debug_log("Client %s is floating" % client) return True if address in self.addresses: if client in self.addresses[address]: self.debug_log("Client %s matches address %s" %...
try: os.stat('/etc/init.d/%s' % entry.get('name')) except OSError: self.logger.debug("Init script for service %s does not exist" % entry.get('name')) return False
def VerifyService(self, entry, _): ''' Verify Service status for entry. Assumes we run in the "default" runlevel. ''' # check if init script exists try: os.stat('/etc/init.d/%s' % entry.get('name')) except OSError: self.logger.debug("Init script for service %s does not exist" % entry.get('name')) return False # check ...
cmd = '/etc/init.d/%s status | grep started'
cmd = '/sbin/rc-update show default | grep %s'
def VerifyService(self, entry, _): ''' Verify Service status for entry. Assumes we run in the "default" runlevel. ''' # check if init script exists try: os.stat('/etc/init.d/%s' % entry.get('name')) except OSError: self.logger.debug("Init script for service %s does not exist" % entry.get('name')) return False # check ...
cmd = '/bin/rc-status -s | grep %s | grep started'
cmd = '/etc/init.d/%s status | grep started'
def VerifyService(self, entry, _): ''' Verify Service status for entry. Assumes we run in the "default" runlevel. ''' # check if init script exists try: os.stat('/etc/init.d/%s' % entry.get('name')) except OSError: self.logger.debug("Init script for service %s does not exist" % entry.get('name')) return False # check ...
self.logger.info("Installing Service %s" % entry.get('name'))
self.logger.info('Installing Service %s' % entry.get('name'))
def InstallService(self, entry): ''' Install Service entry In supervised mode we also take care it's (not) running ''' # check if init script exists try: os.stat('/etc/init.d/%s' % entry.get('name')) except OSError: self.logger.debug('Init script for service %s does not exist' % entry.get('name')) return False
self.__important__ = [e.get('name') for struct in config for entry in struct \
self.__important__ = [entry.get('name') for struct in config for entry in struct \
def __init__(self, logger, setup, config): Bcfg2.Client.Tools.RPMng.RPMng.__init__(self, logger, setup, config) self.__important__ = [e.get('name') for struct in config for entry in struct \ if entry.tag in ['Path', 'ConfigFile'] and \ e.get('name').startswith('/etc/yum.d') or e.get('name') == '/etc/yum.conf'] self.yum...
e.get('name').startswith('/etc/yum.d') or e.get('name') == '/etc/yum.conf']
entry.get('name').startswith('/etc/yum.d') or entry.get('name') == '/etc/yum.conf']
def __init__(self, logger, setup, config): Bcfg2.Client.Tools.RPMng.RPMng.__init__(self, logger, setup, config) self.__important__ = [e.get('name') for struct in config for entry in struct \ if entry.tag in ['Path', 'ConfigFile'] and \ e.get('name').startswith('/etc/yum.d') or e.get('name') == '/etc/yum.conf'] self.yum...
status = (len(onlevels) > 0 )
status = (len(onlevels) > 0) command = 'start'
def VerifyService(self, entry, _): '''Verify Service status for entry''' try: cmd = "/sbin/chkconfig --list %s " % (entry.get('name')) raw = self.cmd.run(cmd)[1] patterns = ["error reading information", "unknown service"] srvdata = [line.split() for line in raw for pattern in patterns \ if pattern not in line][0] excep...
pstatus, pout = self.cmd.run('/sbin/service %s status' % \ entry.get('name')) if pstatus: self.cmd.run('/sbin/service %s start' % (entry.get('name'))) pstatus, pout = self.cmd.run('/sbin/service %s status' % \ entry.get('name'))
pstatus = self.cmd.run('/sbin/service %s status' % \ entry.get('name'))[0] needs_modification = ((command == 'start' and pstatus) or \ (command == 'stop' and not pstatus)) if not(self.setup.get('dryrun')) and needs_modification: self.cmd.run('/sbin/service %s %s' % (entry.get('name'), command)) pstatus = self.cmd.run('...
def VerifyService(self, entry, _): '''Verify Service status for entry''' try: cmd = "/sbin/chkconfig --list %s " % (entry.get('name')) raw = self.cmd.run(cmd)[1] patterns = ["error reading information", "unknown service"] srvdata = [line.split() for line in raw for pattern in patterns \ if pattern not in line][0] excep...
files.append(item.split()[5])
if item.split()[5] not in self.nonexistent: files.append(item.split()[5])
def VerifyDebsums(self, entry, modlist): output = self.cmd.run("%s -as %s" % (DEBSUMS, entry.get('name')))[1] if len(output) == 1 and "no md5sums for" in output[0]: self.logger.info("Package %s has no md5sums. Cannot verify" % \ entry.get('name')) entry.set('qtext', "Reinstall Package %s-%s to setup md5sums? (y/N) " \ ...
start_sequence = int(entry.get('sequence')) kill_sequence = 100 - start_sequence
if (deb_version in DEBIAN_OLD_STYLE_BOOT_SEQUENCE): start_sequence = int(entry.get('sequence')) kill_sequence = 100 - start_sequence else: self.logger.warning("Your debian version boot sequence is dependency based \"sequence\" attribute wil be ignored.")
def VerifyService(self, entry, _): """Verify Service status for entry.""" rawfiles = glob.glob("/etc/rc*.d/[SK]*%s" % (entry.get('name'))) files = [] if entry.get('sequence'): start_sequence = int(entry.get('sequence')) kill_sequence = 100 - start_sequence else: start_sequence = None
source.setup_data(force_update)
if not self.disableMetaData: source.setup_data(force_update)
def _load_config(self, force_update=False): ''' Load the configuration data and setup sources
pass
deps = set()
def resolve_requirement(self, metadata, requirement, packages, debug=False): '''Resolve requirement to packages and or additional requirements
node.append(newstat)
node.append(copy.deepcopy(newstat))
def updateStats(self, xml, client): '''Updates the statistics of a current node with new data'''
fpath = "%s/etc/statistics.xml" % datastore self.data_file = StatisticsStore(fpath)
self.fpath = "%s/etc/statistics.xml" % datastore self.terminate = core.terminate self.work_queue = Queue.Queue() self.worker = threading.Thread(target=self.process_statistics_loop) self.worker.start() def process_statistics_loop(self): self.data_file = StatisticsStore(self.fpath) while not (self.terminate.isSet() and...
def __init__(self, core, datastore): Bcfg2.Server.Plugin.Plugin.__init__(self, core, datastore) Bcfg2.Server.Plugin.Statistics.__init__(self) Bcfg2.Server.Plugin.PullSource.__init__(self) fpath = "%s/etc/statistics.xml" % datastore self.data_file = StatisticsStore(fpath)
self.data_file.updateStats(copy.deepcopy(xdata), client.hostname)
self.work_queue.put((copy.deepcopy(xdata), client.hostname))
def process_statistics(self, client, xdata): self.data_file.updateStats(copy.deepcopy(xdata), client.hostname)
chksum = md5.new()
if py24compat: chksum = md5.new() else: chksum = hashlib.md5()
def prelink_md5_check(filename): """ Checks if a file is prelinked. If it is run it through prelink -y to get the unprelinked md5 and file size. Return 0 if the file was not prelinked, otherwise return the file size. Always return the md5. """ prelink = False try: plf = open(filename, "rb") except IOError: return Fa...
if source.is_pkg(meta, current):
if source.is_package(meta, current):
def complete(self, meta, input_requirements, debug=False): '''Build the transitive closure of all package dependencies
if xsource.find('Recommended').text == 'true':
if xsource.find('Recommended').text in ['True', 'true']:
def source_from_xml(xsource): ret = dict([('rawurl', False), ('url', False)]) for key, tag in [('groups', 'Group'), ('components', 'Component'), ('arches', 'Arch'), ('blacklist', 'Blacklist')]: ret[key] = [item.text for item in xsource.findall(tag)] # version and component need to both contain data for sources to work ...
cmd = "git archive --format=tar --prefix=%s-%s v%s | gzip > %s" % \
cmd = "git archive --format=tar --prefix=%s-%s/ v%s | gzip > %s" % \
def run(command): return Popen(command, shell=True, stdout=PIPE).communicate()
('arches', 'Arch'), ('blacklist', 'Blacklist')]:
('arches', 'Arch'), ('blacklist', 'Blacklist'), ('whitelist', 'Whitelist')]:
def source_from_xml(xsource): ret = dict([('rawurl', False), ('url', False)]) for key, tag in [('groups', 'Group'), ('components', 'Component'), ('arches', 'Arch'), ('blacklist', 'Blacklist')]: ret[key] = [item.text for item in xsource.findall(tag)] # version and component need to both contain data for sources to work ...
blacklist, recommended):
blacklist, whitelist, recommended):
def __init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended): self.basepath = basepath self.version = version self.components = components self.url = url self.rawurl = rawurl self.groups = groups self.arches = arches self.deps = dict() self.provides = dict() self.blacklist = se...
if requirement in self.blacklist:
if requirement in self.blacklist or \ (len(self.whitelist) > 0 and requirement not in self.whitelist):
def resolve_requirement(self, metadata, requirement, packages, debug=False): '''Resolve requirement to packages and or additional requirements
rawurl, blacklist, recommended):
rawurl, blacklist, whitelist, recommended):
def __init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended): Source.__init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended) if not self.rawurl: self.baseurl = self.url + '%(version)s/%(component)s/%(arch)s/' else: self.baseurl = self....
groups, rawurl, blacklist, recommended)
groups, rawurl, blacklist, whitelist, recommended)
def __init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended): Source.__init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended) if not self.rawurl: self.baseurl = self.url + '%(version)s/%(component)s/%(arch)s/' else: self.baseurl = self....
rawurl, blacklist, recommended):
rawurl, blacklist, whitelist, recommended):
def __init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended): Source.__init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended) if not self.rawurl: self.cachefile = self.escape_url(self.url + '@' + self.version) + '.data' else: self.cache...
rawurl, blacklist, recommended)
rawurl, blacklist, whitelist, recommended)
def __init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended): Source.__init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended) if not self.rawurl: self.cachefile = self.escape_url(self.url + '@' + self.version) + '.data' else: self.cache...
path = context['request'].path
path = context['request'].META['PATH_INFO']
def page_navigator(context): """ Creates paginated links. Expects the context to be a RequestContext and views.prepare_paginated_list() to have populated page information. """ fragment = dict() try: path = context['request'].path total_pages = int(context['total_pages']) records_per_page = int(context['records_per_pag...
path = context['request'].path
path = context['request'].META['PATH_INFO']
def filter_navigator(context): try: path = context['request'].path view, args, kwargs = resolve(path) # Strip any page limits and numbers if 'page_number' in kwargs: del kwargs['page_number'] if 'page_limit' in kwargs: del kwargs['page_limit'] filters = [] for filter in filter_list: if filter in kwargs: myargs = kwar...
path = context['request'].path
path = context['request'].META['PATH_INFO']
def render(self, context): link = '#' try: path = context['request'].path view, args, kwargs = resolve(path) filter_value = self.filter_value.resolve(context, True) if filter_value: filter_name = smart_str(self.filter_name) filter_value = smart_unicode(filter_value) kwargs[filter_name] = filter_value # These two don't ...
if res == cert + ": OK\n"
if res == cert + ": OK\n":
def verify_cert(self, filename, entry): """ check that a certificate validates against the ca cert, and that it has not expired. """ chaincert = self.CAs[self.cert_specs[entry.get('name')]['ca']].get('chaincert') cert = self.data + filename cmd = "openssl verify -CAfile %s %s" % (chaincert, cert) res = Popen(cmd, shell...
for alias in metadata.aliases: cp.set('alt_names', 'DNS.'+str(x), alias)
altnames = list(metadata.aliases) altnames.append(metadata.hostname) for altname in altnames: cp.set('alt_names', 'DNS.'+str(x), altname)
def build_req_config(self, entry, metadata): """ generates a temporary openssl configuration file that is used to generate the required certificate request """ # create temp request config file conffile = open(tempfile.mkstemp()[1], 'w') cp = ConfigParser({}) cp.optionxform = str defaults = { 'req': { 'default_md': 'sh...
except Exception as e:
except Exception, e:
def Install(self, packages, states): ''' Pacman Install ''' pkgline = "" for pkg in packages: pkgline += " " + pkg.get('name')