home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / hplip / base / utils.py < prev    next >
Encoding:
Python Source  |  2007-04-04  |  38.8 KB  |  1,344 lines

  1. # -*- coding: utf-8 -*-
  2. #
  3. # (c) Copyright 2001-2007 Hewlett-Packard Development Company, L.P.
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
  18. #
  19. # Author: Don Welch
  20. #
  21. # Thanks to Henrique M. Holschuh <hmh@debian.org> for various security patches
  22. #
  23.  
  24. from __future__ import generators
  25.  
  26. # Std Lib
  27. import sys, os, fnmatch, tempfile, socket, struct, select, time
  28. import fcntl, errno, stat, string, commands
  29. import cStringIO, re
  30. import xml.parsers.expat as expat
  31. import getpass
  32.  
  33. # Local
  34. from g import *
  35. from codes import *
  36. import pexpect
  37.  
  38. xml_basename_pat = re.compile(r"""HPLIP-(\d*)_(\d*)_(\d*).xml""", re.IGNORECASE)
  39.  
  40.  
  41. def Translator(frm='', to='', delete='', keep=None):
  42.     allchars = string.maketrans('','')
  43.  
  44.     if len(to) == 1:
  45.         to = to * len(frm)
  46.     trans = string.maketrans(frm, to)
  47.  
  48.     if keep is not None:
  49.         delete = allchars.translate(allchars, keep.translate(allchars, delete))
  50.  
  51.     def callable(s):
  52.         return s.translate(trans, delete)
  53.  
  54.     return callable
  55.  
  56. # For pidfile locking (must be "static" and global to the whole app)
  57. prv_pidfile = None
  58. prv_pidfile_name = ""
  59.  
  60.  
  61. def get_pidfile_lock (a_pidfile_name=""):
  62.     """ Call this to either lock the pidfile, or to update it after a fork()
  63.         Credit: Henrique M. Holschuh <hmh@debian.org>
  64.     """
  65.     global prv_pidfile
  66.     global prv_pidfile_name
  67.     if prv_pidfile_name == "":
  68.         try:
  69.             prv_pidfile_name = a_pidfile_name
  70.             prv_pidfile = os.fdopen(os.open(prv_pidfile_name, os.O_RDWR | os.O_CREAT, 0644), 'r+')
  71.             fcntl.fcntl(prv_pidfile.fileno(), fcntl.F_SETFD, fcntl.FD_CLOEXEC)
  72.             while 1:
  73.                 try:
  74.                     fcntl.flock(prv_pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
  75.                 except (OSError, IOError), e:
  76.                     if e.errno == errno.EINTR:
  77.                         continue
  78.                     elif e.errno == errno.EWOULDBLOCK:
  79.                         try:
  80.                             prv_pidfile.seek(0)
  81.                             otherpid = int(prv_pidfile.readline(), 10)
  82.                             sys.stderr.write ("can't lock %s, running daemon's pid may be %d\n" % (prv_pidfile_name, otherpid))
  83.                         except (OSError, IOError), e:
  84.                             sys.stderr.write ("error reading pidfile %s: (%d) %s\n" % (prv_pidfile_name, e.errno, e.strerror))
  85.  
  86.                         sys.exit(1)
  87.                     sys.stderr.write ("can't lock %s: (%d) %s\n" % (prv_pidfile_name, e.errno, e.strerror))
  88.                     sys.exit(1)
  89.                 break
  90.         except (OSError, IOError), e:
  91.             sys.stderr.write ("can't open pidfile %s: (%d) %s\n" % (prv_pidfile_name, e.errno, e.strerror))
  92.             sys.exit(1)
  93.     try:
  94.         prv_pidfile.seek(0)
  95.         prv_pidfile.write("%d\n" % (os.getpid()))
  96.         prv_pidfile.flush()
  97.         prv_pidfile.truncate()
  98.     except (OSError, IOError), e:
  99.         log.error("can't update pidfile %s: (%d) %s\n" % (prv_pidfile_name, e.errno, e.strerror))
  100.  
  101.  
  102.  
  103. def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
  104.     """
  105.     Credit: J├╝rgen Hermann, Andy Gimblett, and Noah Spurrier
  106.             http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012
  107.  
  108.     Proper pidfile support: Henrique M. Holschuh <hmh@debian.org>
  109.     """
  110.     # Try to lock pidfile if not locked already
  111.     if prv_pidfile_name != '' or prv_pidfile_name != "":
  112.         get_pidfile_lock(prv_pidfile_name)
  113.  
  114.     # Do first fork.
  115.     try:
  116.         pid = os.fork()
  117.         if pid > 0:
  118.             sys.exit(0) # Exit first parent.
  119.     except OSError, e:
  120.         sys.stderr.write ("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
  121.         sys.exit(1)
  122.  
  123.     # Decouple from parent environment.
  124.     os.chdir("/")
  125.     os.umask(0)
  126.     os.setsid()
  127.  
  128.     # Do second fork.
  129.     try:
  130.         pid = os.fork()
  131.         if pid > 0:
  132.             sys.exit(0) # Exit second parent.
  133.     except OSError, e:
  134.         sys.stderr.write ("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
  135.         sys.exit(1)
  136.  
  137.     if prv_pidfile_name != "":
  138.         get_pidfile_lock()
  139.  
  140.     # Now I am a daemon!
  141.  
  142.     # Redirect standard file descriptors.
  143.     si = file(stdin, 'r')
  144.     so = file(stdout, 'a+')
  145.     se = file(stderr, 'a+', 0)
  146.     os.dup2(si.fileno(), sys.stdin.fileno())
  147.     os.dup2(so.fileno(), sys.stdout.fileno())
  148.     os.dup2(se.fileno(), sys.stderr.fileno())
  149.  
  150.  
  151.  
  152. def ifelse(cond, t, f):
  153.     if cond: return t
  154.     else: return f
  155.  
  156. def to_bool_str(s, default='0'):
  157.     """ Convert an arbitrary 0/1/T/F/Y/N string to a normalized string 0/1."""
  158.     if isinstance(s, str) and s:
  159.         if s[0].lower() in ['1', 't', 'y']:
  160.             return '1'
  161.         elif s[0].lower() in ['0', 'f', 'n']:
  162.             return '0'
  163.  
  164.     return default
  165.  
  166. def to_bool(s, default=False):
  167.     """ Convert an arbitrary 0/1/T/F/Y/N string to a boolean True/False value."""
  168.     if isinstance(s, str) and s:
  169.         if s[0].lower() in ['1', 't', 'y']:
  170.             return True
  171.         elif s[0].lower() in ['0', 'f', 'n']:
  172.             return False
  173.     elif isinstance(s, bool):
  174.         return s
  175.  
  176.     return default
  177.  
  178. def path_exists_safely(path):
  179.     """ Returns True if path exists, and points to a file with permissions at least as strict as 0755.
  180.         Credit: Contributed by Henrique M. Holschuh <hmh@debian.org>"""
  181.     try:
  182.         pathmode = os.stat(path)[stat.ST_MODE]
  183.         if pathmode & 0022 != 0:
  184.             return False
  185.     except (IOError,OSError):
  186.         return False
  187.     return True
  188.  
  189.  
  190. def walkFiles(root, recurse=True, abs_paths=False, return_folders=False, pattern='*', path=None):
  191.     if path is None:
  192.         path = root
  193.  
  194.     try:
  195.         names = os.listdir(root)
  196.     except os.error:
  197.         raise StopIteration
  198.  
  199.     pattern = pattern or '*'
  200.     pat_list = pattern.split(';')
  201.  
  202.     for name in names:
  203.         fullname = os.path.normpath(os.path.join(root, name))
  204.  
  205.         for pat in pat_list:
  206.             if fnmatch.fnmatch(name, pat):
  207.                 if return_folders or not os.path.isdir(fullname):
  208.                     if abs_paths:
  209.                         yield fullname
  210.                     else:
  211.                         try:
  212.                             yield os.path.basename(fullname)
  213.                         except ValueError:
  214.                             yield fullname
  215.  
  216.         if os.path.islink(fullname):
  217.             fullname = os.path.realpath(os.readlink(fullname))
  218.  
  219.         if recurse and os.path.isdir(fullname) or os.path.islink(fullname):
  220.             for f in walkFiles(fullname, recurse, abs_paths, return_folders, pattern, path):
  221.                 yield f
  222.  
  223.  
  224. def is_path_writable(path):
  225.     if os.path.exists(path):
  226.         s = os.stat(path)
  227.         mode = s[stat.ST_MODE] & 0777
  228.  
  229.         if mode & 02:
  230.             return True
  231.         elif s[stat.ST_GID] == os.getgid() and mode & 020:
  232.             return True
  233.         elif s[stat.ST_UID] == os.getuid() and mode & 0200:
  234.             return True
  235.  
  236.     return False
  237.  
  238.  
  239. # Provides the TextFormatter class for formatting text into columns.
  240. # Original Author: Hamish B Lawson, 1999
  241. # Modified by: Don Welch, 2003
  242. class TextFormatter:
  243.  
  244.     LEFT  = 0
  245.     CENTER = 1
  246.     RIGHT  = 2
  247.  
  248.     def __init__(self, colspeclist):
  249.         self.columns = []
  250.         for colspec in colspeclist:
  251.             self.columns.append(Column(**colspec))
  252.  
  253.     def compose(self, textlist, add_newline=False):
  254.         numlines = 0
  255.         textlist = list(textlist)
  256.         if len(textlist) != len(self.columns):
  257.             log.error("Formatter: Number of text items does not match columns")
  258.             return
  259.         for text, column in map(None, textlist, self.columns):
  260.             column.wrap(text)
  261.             numlines = max(numlines, len(column.lines))
  262.         complines = [''] * numlines
  263.         for ln in range(numlines):
  264.             for column in self.columns:
  265.                 complines[ln] = complines[ln] + column.getline(ln)
  266.         if add_newline:
  267.             return '\n'.join(complines) + '\n'
  268.         else:
  269.             return '\n'.join(complines)
  270.  
  271.     def bold(text):
  272.         return ''.join(["\033[1m", text, "\033[0m"])
  273.  
  274.     bold = staticmethod(bold)
  275.  
  276.  
  277. class Column:
  278.  
  279.     def __init__(self, width=78, alignment=TextFormatter.LEFT, margin=0):
  280.         self.width = width
  281.         self.alignment = alignment
  282.         self.margin = margin
  283.         self.lines = []
  284.  
  285.     def align(self, line):
  286.         if self.alignment == TextFormatter.CENTER:
  287.             return line.center(self.width)
  288.         elif self.alignment == TextFormatter.RIGHT:
  289.             return line.rjust(self.width)
  290.         else:
  291.             return line.ljust(self.width)
  292.  
  293.     def wrap(self, text):
  294.         self.lines = []
  295.         words = []
  296.         for word in text.split():
  297.             if word <= self.width:
  298.                 words.append(word)
  299.             else:
  300.                 for i in range(0, len(word), self.width):
  301.                     words.append(word[i:i+self.width])
  302.         if not len(words): return
  303.         current = words.pop(0)
  304.         for word in words:
  305.             increment = 1 + len(word)
  306.             if len(current) + increment > self.width:
  307.                 self.lines.append(self.align(current))
  308.                 current = word
  309.             else:
  310.                 current = current + ' ' + word
  311.         self.lines.append(self.align(current))
  312.  
  313.     def getline(self, index):
  314.         if index < len(self.lines):
  315.             return ' '*self.margin + self.lines[index]
  316.         else:
  317.             return ' ' * (self.margin + self.width)
  318.  
  319.  
  320. class Stack:
  321.     def __init__(self):
  322.         self.stack = []
  323.  
  324.     def pop(self):
  325.         return self.stack.pop()
  326.  
  327.     def push(self, value):
  328.         self.stack.append(value)
  329.  
  330.     def as_list(self):
  331.         return self.stack
  332.  
  333.     def clear(self):
  334.         self.stack = []
  335.  
  336.  
  337. # RingBuffer class
  338. # Source: Python Cookbook 1st Ed., sec. 5.18, pg. 201
  339. # Credit: Sebastien Keim
  340. # License: Modified BSD
  341. class RingBuffer:
  342.     def __init__(self,size_max=50):
  343.         self.max = size_max
  344.         self.data = []
  345.     
  346.     def append(self,x):
  347.         """append an element at the end of the buffer"""
  348.         self.data.append(x)
  349.         
  350.         if len(self.data) == self.max:
  351.             self.cur = 0
  352.             self.__class__ = RingBufferFull
  353.             
  354.     def replace(self, x):
  355.         """replace the last element instead off appending"""
  356.         self.data[-1] = x
  357.     
  358.     def get(self):
  359.         """ return a list of elements from the oldest to the newest"""
  360.         return self.data
  361.  
  362.  
  363. class RingBufferFull:
  364.     def __init__(self,n):
  365.         #raise "you should use RingBuffer"
  366.         pass
  367.     
  368.     def append(self,x):
  369.         self.data[self.cur] = x
  370.         self.cur = (self.cur+1) % self.max
  371.         
  372.     def replace(self, x):
  373.         # back up 1 position to previous location
  374.         self.cur = (self.cur-1) % self.max
  375.         self.data[self.cur] = x
  376.         # setup for next item
  377.         self.cur = (self.cur+1) % self.max
  378.     
  379.     def get(self):
  380.         return self.data[self.cur:] + self.data[:self.cur]
  381.  
  382. def sort_dict_by_value(d):
  383.     """ Returns the keys of dictionary d sorted by their values """
  384.     items=d.items()
  385.     backitems=[[v[1],v[0]] for v in items]
  386.     backitems.sort()
  387.     return [backitems[i][1] for i in range(0,len(backitems))]
  388.  
  389.  
  390. # Copied from Gentoo Portage output.py
  391. # Copyright 1998-2003 Daniel Robbins, Gentoo Technologies, Inc.
  392. # Distributed under the GNU Public License v2
  393.  
  394. codes={}
  395. codes["reset"]="\x1b[0m"
  396. codes["bold"]="\x1b[01m"
  397.  
  398. codes["teal"]="\x1b[36;06m"
  399. codes["turquoise"]="\x1b[36;01m"
  400.  
  401. codes["fuscia"]="\x1b[35;01m"
  402. codes["purple"]="\x1b[35;06m"
  403.  
  404. codes["blue"]="\x1b[34;01m"
  405. codes["darkblue"]="\x1b[34;06m"
  406.  
  407. codes["green"]="\x1b[32;01m"
  408. codes["darkgreen"]="\x1b[32;06m"
  409.  
  410. codes["yellow"]="\x1b[33;01m"
  411. codes["brown"]="\x1b[33;06m"
  412.  
  413. codes["red"]="\x1b[31;01m"
  414. codes["darkred"]="\x1b[31;06m"
  415.  
  416.  
  417. def bold(text):
  418.     return codes["bold"]+text+codes["reset"]
  419.  
  420. def white(text):
  421.     return bold(text)
  422.  
  423. def teal(text):
  424.     return codes["teal"]+text+codes["reset"]
  425.  
  426. def turquoise(text):
  427.     return codes["turquoise"]+text+codes["reset"]
  428.  
  429. def darkteal(text):
  430.     return turquoise(text)
  431.  
  432. def fuscia(text):
  433.     return codes["fuscia"]+text+codes["reset"]
  434.  
  435. def purple(text):
  436.     return codes["purple"]+text+codes["reset"]
  437.  
  438. def blue(text):
  439.     return codes["blue"]+text+codes["reset"]
  440.  
  441. def darkblue(text):
  442.     return codes["darkblue"]+text+codes["reset"]
  443.  
  444. def green(text):
  445.     return codes["green"]+text+codes["reset"]
  446.  
  447. def darkgreen(text):
  448.     return codes["darkgreen"]+text+codes["reset"]
  449.  
  450. def yellow(text):
  451.     return codes["yellow"]+text+codes["reset"]
  452.  
  453. def brown(text):
  454.     return codes["brown"]+text+codes["reset"]
  455.  
  456. def darkyellow(text):
  457.     return brown(text)
  458.  
  459. def red(text):
  460.     return codes["red"]+text+codes["reset"]
  461.  
  462. def darkred(text):
  463.     return codes["darkred"]+text+codes["reset"]
  464.  
  465.  
  466. def commafy(val):
  467.     return val < 0 and '-' + commafy(abs(val)) \
  468.         or val < 1000 and str(val) \
  469.         or '%s,%03d' % (commafy(val / 1000), (val % 1000))
  470.  
  471.  
  472. def format_bytes(s, show_bytes=False):
  473.     if s < 1024:
  474.         return ''.join([commafy(s), ' B'])
  475.     elif 1024 < s < 1048576:
  476.         if show_bytes:
  477.             return ''.join([str(round(s/1024.0, 1)) , ' KB (',  commafy(s), ')'])
  478.         else:
  479.             return ''.join([str(round(s/1024.0, 1)) , ' KB'])
  480.     else:
  481.         if show_bytes:
  482.             return ''.join([str(round(s/1048576.0, 1)), ' MB (',  commafy(s), ')'])
  483.         else:
  484.             return ''.join([str(round(s/1048576.0, 1)), ' MB'])
  485.  
  486.  
  487.  
  488. try:
  489.     make_temp_file = tempfile.mkstemp # 2.3+
  490. except AttributeError:
  491.     def make_temp_file(suffix='', prefix='', dir='', text=False): # pre-2.3
  492.         path = tempfile.mktemp(suffix)
  493.         fd = os.open(path, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700)
  494.         #os.unlink( path ) # TODO... make this secure
  495.         return ( os.fdopen( fd, 'w+b' ), path )
  496.         #return (fd, path)
  497.  
  498. def log_title(program_name, version):
  499.     log.info("")
  500.     log.info(bold("HP Linux Imaging and Printing System (ver. %s)" % prop.version))
  501.     log.info(bold("%s ver. %s" % (program_name, version)))
  502.     log.info("")
  503.     log.info("Copyright (c) 2001-7 Hewlett-Packard Development Company, LP")
  504.     log.info("This software comes with ABSOLUTELY NO WARRANTY.")
  505.     log.info("This is free software, and you are welcome to distribute it")
  506.     log.info("under certain conditions. See COPYING file for more details.")
  507.     log.info("")
  508.  
  509.  
  510. def which(command, return_full_path=False):
  511.     path = os.getenv('PATH').split(':')
  512.  
  513.     # Add these paths for Fedora
  514.     path.append('/sbin')
  515.     path.append('/usr/sbin')
  516.     path.append('/usr/local/sbin')
  517.  
  518.     found_path = ''
  519.     for p in path:
  520.         try:
  521.             files = os.listdir(p)
  522.         except:
  523.             continue
  524.         else:
  525.             if command in files:
  526.                 found_path = p
  527.                 break
  528.  
  529.     if return_full_path:
  530.         if found_path:
  531.             return os.path.join(found_path, command)
  532.         else:
  533.             return ''
  534.     else:
  535.         return found_path
  536.  
  537.  
  538. def deviceDefaultFunctions():
  539.     cmd_print, cmd_copy, cmd_fax, \
  540.         cmd_pcard, cmd_scan, cmd_fab = \
  541.         '', '', '', '', '', ''
  542.  
  543.     # Print
  544.     path = which('hp-print')
  545.  
  546.     if len(path) > 0:
  547.         cmd_print = 'hp-print -p%PRINTER%'
  548.     else:
  549.         path = which('kprinter')
  550.  
  551.         if len(path) > 0:
  552.             cmd_print = 'kprinter -P%PRINTER% --system cups'
  553.         else:
  554.             path = which('gtklp')
  555.  
  556.             if len(path) > 0:
  557.                 cmd_print = 'gtklp -P%PRINTER%'
  558.  
  559.             else:
  560.                 path = which('xpp')
  561.  
  562.                 if len(path) > 0:
  563.                     cmd_print = 'xpp -P%PRINTER%'
  564.  
  565.     # Scan
  566.     path = which('xsane')
  567.  
  568.     if len(path) > 0:
  569.         cmd_scan = 'xsane -V %SANE_URI%'
  570.     else:
  571.         path = which('kooka')
  572.  
  573.         if len(path)>0:
  574.             #cmd_scan = 'kooka -d "%SANE_URI%"'
  575.             cmd_scan = 'kooka'
  576.  
  577.         else:
  578.             path = which('xscanimage')
  579.  
  580.             if len(path)>0:
  581.                 cmd_scan = 'xscanimage'
  582.  
  583.     # Photo Card
  584.     path = which('hp-unload')
  585.  
  586.     if len(path):
  587.         cmd_pcard = 'hp-unload -d %DEVICE_URI%'
  588.  
  589.     else:
  590.         cmd_pcard = 'python %HOME%/unload.py -d %DEVICE_URI%'
  591.  
  592.     # Copy
  593.     path = which('hp-makecopies')
  594.  
  595.     if len(path):
  596.         cmd_copy = 'hp-makecopies -d %DEVICE_URI%'
  597.  
  598.     else:
  599.         cmd_copy = 'python %HOME%/makecopies.py -d %DEVICE_URI%'
  600.  
  601.     # Fax
  602.     path = which('hp-sendfax')
  603.  
  604.     if len(path):
  605.         cmd_fax = 'hp-sendfax -d %FAX_URI%'
  606.  
  607.     else:
  608.         cmd_fax = 'python %HOME%/sendfax.py -d %FAX_URI%'
  609.  
  610.     # Fax Address Book
  611.     path = which('hp-fab')
  612.  
  613.     if len(path):
  614.         cmd_fab = 'hp-fab'
  615.  
  616.     else:
  617.         cmd_fab = 'python %HOME%/fab.py'
  618.  
  619.     return cmd_print, cmd_scan, cmd_pcard, \
  620.            cmd_copy, cmd_fax, cmd_fab
  621.  
  622.  
  623. def no_qt_message_gtk():
  624.     try:
  625.         import gtk
  626.         w = gtk.Window()
  627.         dialog = gtk.MessageDialog(w, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
  628.                                    gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, 
  629.                                    "PyQt not installed. GUI not available. Install \"python-qt3\" with the Synaptic Package Manager (Menu: System -> Administration -> Synaptic Package Manager) or run the command \"sudo apt-get install python-qt3\" in a terminal window.")
  630.         dialog.run()
  631.         dialog.destroy()
  632.  
  633.     except ImportError:
  634.         pass
  635.  
  636. def checkPyQtImport():
  637.     # PyQt
  638.     try:
  639.         import qt
  640.     except ImportError:
  641.         if os.getenv('DISPLAY') and os.getenv('STARTED_FROM_MENU'):
  642.             no_qt_message_gtk()
  643.  
  644.         log.error("PyQt not installed. GUI not available. Exiting.")
  645.         return False
  646.  
  647.     # check version of Qt
  648.     qtMajor = int(qt.qVersion().split('.')[0])
  649.  
  650.     if qtMajor < MINIMUM_QT_MAJOR_VER:
  651.  
  652.         log.error("Incorrect version of Qt installed. Ver. 3.0.0 or greater required.")
  653.         return False
  654.  
  655.     #check version of PyQt
  656.     try:
  657.         pyqtVersion = qt.PYQT_VERSION_STR
  658.     except:
  659.         pyqtVersion = qt.PYQT_VERSION
  660.  
  661.     while pyqtVersion.count('.') < 2:
  662.         pyqtVersion += '.0'
  663.  
  664.     (maj_ver, min_ver, pat_ver) = pyqtVersion.split('.')
  665.  
  666.     if pyqtVersion.find('snapshot') >= 0:
  667.         log.warning("A non-stable snapshot version of PyQt is installed.")
  668.     else:
  669.         try:
  670.             maj_ver = int(maj_ver)
  671.             min_ver = int(min_ver)
  672.             pat_ver = int(pat_ver)
  673.         except ValueError:
  674.             maj_ver, min_ver, pat_ver = 0, 0, 0
  675.  
  676.         if maj_ver < MINIMUM_PYQT_MAJOR_VER or \
  677.             (maj_ver == MINIMUM_PYQT_MAJOR_VER and min_ver < MINIMUM_PYQT_MINOR_VER):
  678.             log.error("This program may not function properly with the version of PyQt that is installed (%d.%d.%d)." % (maj_ver, min_ver, pat_ver))
  679.             log.error("Incorrect version of pyQt installed. Ver. %d.%d or greater required." % (MINIMUM_PYQT_MAJOR_VER, MINIMUM_PYQT_MINOR_VER))
  680.             log.error("This program will continue, but you may experience errors, crashes or other problems.")
  681.             return True
  682.  
  683.     return True
  684.  
  685.  
  686. def loadTranslators(app, user_config):
  687.     #from qt import *
  688.     import qt
  689.     loc = None
  690.  
  691.     if os.path.exists(user_config):
  692.         # user_config contains executables we will run, so we
  693.         # must make sure it is a safe file, and refuse to run
  694.         # otherwise.
  695.         if not path_exists_safely(user_config):
  696.             log.warning("File %s has insecure permissions! File ignored." % user_config)
  697.         else:
  698.             config = ConfigParser.ConfigParser()
  699.             config.read(user_config)
  700.  
  701.             if config.has_section("ui"):
  702.                 loc = config.get("ui", "loc")
  703.  
  704.                 if not loc:
  705.                     loc = None
  706.  
  707.     if loc is not None:
  708.  
  709.         if loc.lower() == 'system':
  710.             loc = str(qt.QTextCodec.locale())
  711.  
  712.         if loc.lower() != 'c':
  713.  
  714.             log.debug("Trying to load .qm file for %s locale." % loc)
  715.  
  716.             dirs = [prop.home_dir, prop.data_dir, prop.i18n_dir]
  717.  
  718.             trans = qt.QTranslator(None)
  719.  
  720.             for dir in dirs:
  721.                 qm_file = 'hplip_%s' % loc
  722.                 loaded = trans.load(qm_file, dir)
  723.  
  724.                 if loaded:
  725.                     app.installTranslator(trans)
  726.                     break
  727.         else:
  728.             loc = None
  729.  
  730.     if loc is None:
  731.         log.debug("Using default 'C' locale")
  732.     else:
  733.         log.debug("Using locale: %s" % loc)
  734.  
  735.     return loc
  736.  
  737. try:
  738.     from string import Template # will fail in Python <= 2.3
  739. except ImportError:
  740.     # Code from Python 2.4 string.py
  741.     #import re as _re
  742.  
  743.     class _multimap:
  744.         """Helper class for combining multiple mappings.
  745.  
  746.         Used by .{safe_,}substitute() to combine the mapping and keyword
  747.         arguments.
  748.         """
  749.         def __init__(self, primary, secondary):
  750.             self._primary = primary
  751.             self._secondary = secondary
  752.  
  753.         def __getitem__(self, key):
  754.             try:
  755.                 return self._primary[key]
  756.             except KeyError:
  757.                 return self._secondary[key]
  758.  
  759.  
  760.     class _TemplateMetaclass(type):
  761.         pattern = r"""
  762.         %(delim)s(?:
  763.           (?P<escaped>%(delim)s) |   # Escape sequence of two delimiters
  764.           (?P<named>%(id)s)      |   # delimiter and a Python identifier
  765.           {(?P<braced>%(id)s)}   |   # delimiter and a braced identifier
  766.           (?P<invalid>)              # Other ill-formed delimiter exprs
  767.         )
  768.         """
  769.  
  770.         def __init__(cls, name, bases, dct):
  771.             super(_TemplateMetaclass, cls).__init__(name, bases, dct)
  772.             if 'pattern' in dct:
  773.                 pattern = cls.pattern
  774.             else:
  775.                 pattern = _TemplateMetaclass.pattern % {
  776.                     'delim' : re.escape(cls.delimiter),
  777.                     'id'    : cls.idpattern,
  778.                     }
  779.             cls.pattern = re.compile(pattern, re.IGNORECASE | re.VERBOSE)
  780.  
  781.  
  782.     class Template:
  783.         """A string class for supporting $-substitutions."""
  784.         __metaclass__ = _TemplateMetaclass
  785.  
  786.         delimiter = '$'
  787.         idpattern = r'[_a-z][_a-z0-9]*'
  788.  
  789.         def __init__(self, template):
  790.             self.template = template
  791.  
  792.         # Search for $$, $identifier, ${identifier}, and any bare $'s
  793.  
  794.         def _invalid(self, mo):
  795.             i = mo.start('invalid')
  796.             lines = self.template[:i].splitlines(True)
  797.             if not lines:
  798.                 colno = 1
  799.                 lineno = 1
  800.             else:
  801.                 colno = i - len(''.join(lines[:-1]))
  802.                 lineno = len(lines)
  803.             raise ValueError('Invalid placeholder in string: line %d, col %d' %
  804.                              (lineno, colno))
  805.  
  806.         def substitute(self, *args, **kws):
  807.             if len(args) > 1:
  808.                 raise TypeError('Too many positional arguments')
  809.             if not args:
  810.                 mapping = kws
  811.             elif kws:
  812.                 mapping = _multimap(kws, args[0])
  813.             else:
  814.                 mapping = args[0]
  815.             # Helper function for .sub()
  816.             def convert(mo):
  817.                 # Check the most common path first.
  818.                 named = mo.group('named') or mo.group('braced')
  819.                 if named is not None:
  820.                     val = mapping[named]
  821.                     # We use this idiom instead of str() because the latter will
  822.                     # fail if val is a Unicode containing non-ASCII characters.
  823.                     return '%s' % val
  824.                 if mo.group('escaped') is not None:
  825.                     return self.delimiter
  826.                 if mo.group('invalid') is not None:
  827.                     self._invalid(mo)
  828.                 raise ValueError('Unrecognized named group in pattern',
  829.                                  self.pattern)
  830.             return self.pattern.sub(convert, self.template)
  831.  
  832.         def safe_substitute(self, *args, **kws):
  833.             if len(args) > 1:
  834.                 raise TypeError('Too many positional arguments')
  835.             if not args:
  836.                 mapping = kws
  837.             elif kws:
  838.                 mapping = _multimap(kws, args[0])
  839.             else:
  840.                 mapping = args[0]
  841.             # Helper function for .sub()
  842.             def convert(mo):
  843.                 named = mo.group('named')
  844.                 if named is not None:
  845.                     try:
  846.                         # We use this idiom instead of str() because the latter
  847.                         # will fail if val is a Unicode containing non-ASCII
  848.                         return '%s' % mapping[named]
  849.                     except KeyError:
  850.                         return self.delimiter + named
  851.                 braced = mo.group('braced')
  852.                 if braced is not None:
  853.                     try:
  854.                         return '%s' % mapping[braced]
  855.                     except KeyError:
  856.                         return self.delimiter + '{' + braced + '}'
  857.                 if mo.group('escaped') is not None:
  858.                     return self.delimiter
  859.                 if mo.group('invalid') is not None:
  860.                     return self.delimiter
  861.                 raise ValueError('Unrecognized named group in pattern',
  862.                                  self.pattern)
  863.             return self.pattern.sub(convert, self.template)
  864.  
  865.  
  866.  
  867. cat = lambda _ : Template(_).substitute(sys._getframe(1).f_globals, **sys._getframe(1).f_locals)
  868. identity = string.maketrans('','')
  869. unprintable = identity.translate(identity, string.printable)
  870.  
  871. def printable(s):
  872.     return s.translate(identity, unprintable)
  873.  
  874.  
  875. def any(S,f=lambda x:x):
  876.     for x in S:
  877.         if f(x): return True
  878.     return False
  879.  
  880. def all(S,f=lambda x:x):
  881.     for x in S:
  882.         if not f(x): return False
  883.     return True
  884.  
  885. def openURL(url):
  886.     browsers = ['firefox', 'mozilla', 'konqueror', 'galeon', 'skipstone'] # in preferred order
  887.     browser_opt = {'firefox': '-new-window', 'mozilla' : '', 'konqueror': '', 'galeon': '-w', 'skipstone': ''}
  888.  
  889.     for b in browsers:
  890.         if which(b):
  891.             cmd = """%s %s "%s" &""" % (b, browser_opt[b], url)
  892.             log.debug(cmd)
  893.             os.system(cmd)
  894.             break
  895.     else:
  896.         log.warn("Unable to open URL: %s" % url)
  897.  
  898.  
  899. def uniqueList(input):
  900.     temp = []
  901.     [temp.append(i) for i in input if not temp.count(i)]
  902.     return temp
  903.  
  904.  
  905. def list_move_up(l, m):
  906.     for i in range(1, len(l)):
  907.         if l[i] == m:
  908.             l[i-1],l[i] = l[i],l[i-1]
  909.  
  910.  
  911. def list_move_down(l, m):
  912.     for i in range(len(l) - 2, 0, -1):
  913.         if l[i] == m:
  914.             l[i],l[i+1] = l[i+1],l[i] 
  915.  
  916.  
  917.  
  918. class XMLToDictParser:
  919.     def __init__(self):
  920.         self.stack = []
  921.         self.data = {}
  922.  
  923.     def startElement(self, name, attrs):
  924.         self.stack.append(str(name).lower())
  925.  
  926.         if len(attrs):
  927.             for a in attrs:
  928.                 self.stack.append(str(a).lower())
  929.                 self.addData(attrs[a])
  930.                 self.stack.pop()
  931.  
  932.     def endElement(self, name):
  933.         self.stack.pop()
  934.  
  935.     def charData(self, data):
  936.         data = str(data).strip()
  937.  
  938.         if data and self.stack:
  939.             self.addData(data)
  940.  
  941.     def addData(self, data):
  942.         try:
  943.             data = int(data)
  944.         except ValueError:
  945.             data = str(data)
  946.  
  947.         stack_str = '-'.join(self.stack)
  948.         stack_str_0 = '-'.join([stack_str, '0'])
  949.  
  950.         try:
  951.             self.data[stack_str]
  952.         except KeyError:
  953.             try:
  954.                 self.data[stack_str_0]
  955.             except KeyError:
  956.                 self.data[stack_str] = data
  957.             else:
  958.                 j = 2
  959.                 while True:
  960.                     try:
  961.                         self.data['-'.join([stack_str, str(j)])]
  962.                     except KeyError:
  963.                         self.data['-'.join([stack_str, str(j)])] = data
  964.                         break
  965.                     j += 1                    
  966.  
  967.         else:
  968.             self.data[stack_str_0] = self.data[stack_str]
  969.             self.data['-'.join([stack_str, '1'])] = data
  970.             del self.data[stack_str]
  971.  
  972.  
  973.     def parseXML(self, text):
  974.         parser = expat.ParserCreate()
  975.         parser.StartElementHandler = self.startElement
  976.         parser.EndElementHandler = self.endElement
  977.         parser.CharacterDataHandler = self.charData
  978.         parser.Parse(text, True)
  979.         return self.data
  980.  
  981.  
  982.  # ------------------------- Usage Help
  983.  
  984. USAGE_OPTIONS = ("[OPTIONS]", "", "heading", False)
  985. USAGE_LOGGING1 = ("Set the logging level:", "-l<level> or --logging=<level>", 'option', False)
  986. USAGE_LOGGING2 = ("", "<level>: none, info\*, error, warn, debug (\*default)", "option", False)
  987. USAGE_LOGGING3 = ("Run in debug mode:", "-g (same as option: -ldebug)", "option", False)
  988. USAGE_ARGS = ("[PRINTER|DEVICE-URI] (See Notes)", "", "heading", False)
  989. USAGE_DEVICE = ("To specify a device-URI:", "-d<device-uri> or --device=<device-uri>", "option", False)
  990. USAGE_PRINTER = ("To specify a CUPS printer:", "-p<printer> or --printer=<printer>", "option", False)
  991. USAGE_BUS1 = ("Bus to probe (if device not specified):", "-b<bus> or --bus=<bus>", "option", False)
  992. USAGE_BUS2 = ("", "<bus>: cups\*, usb\*, net, bt, fw, par\* (\*defaults) (Note: bt and fw not supported in this release.)", 'option', False)
  993. USAGE_HELP = ("This help information:", "-h or --help", "option", True)
  994. USAGE_SPACE = ("", "", "space", False)
  995. USAGE_EXAMPLES = ("Examples:", "", "heading", False)
  996. USAGE_NOTES = ("Notes:", "", "heading", False)
  997. USAGE_STD_NOTES1 = ("1. If device or printer is not specified, the local device bus is probed and the program enters interactive mode.", "", "note", False)
  998. USAGE_STD_NOTES2 = ("2. If -p\* is specified, the default CUPS printer will be used.", "", "note", False)
  999. USAGE_SEEALSO = ("See Also:", "", "heading", False)
  1000.  
  1001. def ttysize():
  1002.     ln1 = commands.getoutput('stty -a').splitlines()[0]
  1003.     vals = {'rows':None, 'columns':None}
  1004.     for ph in ln1.split(';'):
  1005.         x = ph.split()
  1006.         if len(x) == 2:
  1007.             vals[x[0]] = x[1]
  1008.             vals[x[1]] = x[0]
  1009.     try:
  1010.         rows, cols = int(vals['rows']), int(vals['columns'])
  1011.     except TypeError:
  1012.         rows, cols = 25, 80
  1013.  
  1014.     return rows, cols
  1015.  
  1016.  
  1017. def usage_formatter(override=0):
  1018.     rows, cols = ttysize()
  1019.  
  1020.     if override:
  1021.         col1 = override
  1022.         col2 = cols - col1 - 8
  1023.     else:
  1024.         col1 = int(cols / 3) - 8
  1025.         col2 = cols - col1 - 8
  1026.  
  1027.     return TextFormatter(({'width': col1, 'margin' : 2},
  1028.                             {'width': col2, 'margin' : 2},))
  1029.  
  1030.  
  1031. def format_text(text_list, typ='text', title='', crumb='', version=''):
  1032.     """
  1033.     Format usage text in multiple formats:
  1034.         text: for --help in the console
  1035.         rest: for conversion with rst2web for the website
  1036.         man: for manpages
  1037.     """
  1038.     if typ == 'text':
  1039.         formatter = usage_formatter()
  1040.  
  1041.         for line in text_list:
  1042.             text1, text2, format, trailing_space = line
  1043.  
  1044.             # remove any reST/man escapes
  1045.             text1 = text1.replace("\\", "")
  1046.             text2 = text2.replace("\\", "")
  1047.  
  1048.             if format == 'summary':
  1049.                 log.info(bold(text1))
  1050.                 log.info("")
  1051.  
  1052.             elif format in ('para', 'name', 'seealso'):
  1053.                 log.info(text1)
  1054.  
  1055.                 if trailing_space:
  1056.                     log.info("")
  1057.  
  1058.             elif format in ('heading', 'header'):
  1059.                 log.info(bold(text1))
  1060.  
  1061.             elif format in ('option', 'example'):
  1062.                 log.info(formatter.compose((text1, text2), trailing_space))
  1063.  
  1064.             elif format == 'note':
  1065.                 if text1.startswith(' '):
  1066.                     log.info('\t' + text1.lstrip())
  1067.                 else:
  1068.                     log.info(text1)
  1069.  
  1070.             elif format == 'space':
  1071.                 log.info("")
  1072.  
  1073.         log.info("")
  1074.  
  1075.  
  1076.     elif typ == 'rest':
  1077.         colwidth1, colwidth2 = 0, 0
  1078.         for line in text_list:
  1079.             text1, text2, format, trailing_space = line
  1080.  
  1081.             if format in ('option', 'example', 'note'):
  1082.                 colwidth1 = max(len(text1), colwidth1)
  1083.                 colwidth2 = max(len(text2), colwidth2)
  1084.  
  1085.         colwidth1 += 3
  1086.         tablewidth = colwidth1 + colwidth2
  1087.  
  1088.         # write the rst2web header
  1089.         log.info("""restindex
  1090. page-title: %s
  1091. crumb: %s
  1092. format: rest
  1093. file-extension: html
  1094. encoding: utf8
  1095. /restindex\n""" % (title, crumb))
  1096.  
  1097.         log.info("%s: %s (ver. %s)" % (crumb, title, version))
  1098.         log.info("="*80)
  1099.         log.info("")
  1100.  
  1101.         links = []
  1102.  
  1103.         for line in text_list:
  1104.             text1, text2, format, trailing_space = line
  1105.  
  1106.             if format == 'seealso':
  1107.                 links.append(text1)
  1108.                 text1 = "`%s`_" % text1
  1109.  
  1110.             len1, len2 = len(text1), len(text2)
  1111.  
  1112.             if format == 'summary':
  1113.                 log.info(''.join(["**", text1, "**"]))
  1114.                 log.info("")
  1115.  
  1116.             elif format in ('para', 'name'):
  1117.                 log.info("")
  1118.                 log.info(text1)
  1119.                 log.info("")
  1120.  
  1121.             elif format in ('heading', 'header'):
  1122.  
  1123.                 log.info("")
  1124.                 log.info("**" + text1 + "**")
  1125.                 log.info("")
  1126.                 log.info(".. class:: borderless")
  1127.                 log.info("")
  1128.                 log.info(''.join(["+", "-"*colwidth1, "+", "-"*colwidth2, "+"]))
  1129.  
  1130.             elif format in ('option', 'example', 'seealso'):
  1131.  
  1132.                 if text1 and '`_' not in text1:
  1133.                     log.info(''.join(["| *", text1, '*', " "*(colwidth1-len1-3), "|", text2, " "*(colwidth2-len2), "|"]))
  1134.                 elif text1:
  1135.                     log.info(''.join(["|", text1, " "*(colwidth1-len1), "|", text2, " "*(colwidth2-len2), "|"]))
  1136.                 else:
  1137.                     log.info(''.join(["|", " "*(colwidth1), "|", text2, " "*(colwidth2-len2), "|"]))
  1138.  
  1139.                 log.info(''.join(["+", "-"*colwidth1, "+", "-"*colwidth2, "+"]))
  1140.  
  1141.             elif format == 'note':
  1142.                 if text1.startswith(' '):
  1143.                     log.info(''.join(["|", " "*(tablewidth+1), "|"]))
  1144.  
  1145.                 log.info(''.join(["|", text1, " "*(tablewidth-len1+1), "|"]))
  1146.                 log.info(''.join(["+", "-"*colwidth1, "+", "-"*colwidth2, "+"]))
  1147.  
  1148.             elif format == 'space':
  1149.                 log.info("")
  1150.  
  1151.         for l in links:
  1152.             log.info("\n.. _`%s`: %s.html\n" % (l, l.replace('hp-', '')))
  1153.  
  1154.         log.info("")
  1155.  
  1156.     elif typ == 'man':
  1157.         log.info('.TH "%s" 1 "%s" Linux "User Manuals"' % (title, version))
  1158.  
  1159.         for line in text_list:
  1160.             text1, text2, format, trailing_space = line
  1161.  
  1162.             text1 = text1.replace("\\*", "*")
  1163.             text2 = text2.replace("\\*", "*")            
  1164.  
  1165.             len1, len2 = len(text1), len(text2)
  1166.  
  1167.             if format == 'summary':
  1168.                 log.info(".SH SYNOPSIS")
  1169.                 log.info(".B %s" % text1)
  1170.  
  1171.             elif format == 'name':
  1172.                 log.info(".SH NAME\n%s" % text1)
  1173.  
  1174.             elif format in ('option', 'example', 'note'):
  1175.                 if text1:
  1176.                     log.info('.IP "%s"\n%s' % (text1, text2))
  1177.                 else:
  1178.                     log.info(text2)
  1179.  
  1180.             elif format in ('header', 'heading'):
  1181.                 log.info(".SH %s" % text1.upper().replace(':', '').replace('[', '').replace(']', ''))
  1182.  
  1183.             elif format in ('seealso, para'):
  1184.                 log.info(text1)
  1185.  
  1186.         log.info("")
  1187.  
  1188.  
  1189. def dquote(s):
  1190.     return ''.join(['"', s, '"'])
  1191.  
  1192. # Python 2.2 compatibility functions (strip() family with char argument)
  1193. def xlstrip(s, chars=' '):
  1194.     i = 0
  1195.     for c, i in zip(s, range(len(s))):
  1196.         if c not in chars:
  1197.             break
  1198.  
  1199.     return s[i:]
  1200.  
  1201. def xrstrip(s, chars=' '):
  1202.     return xreverse(xlstrip(xreverse(s), chars))
  1203.  
  1204. def xreverse(s):
  1205.     l = list(s)
  1206.     l.reverse()
  1207.     return ''.join(l)
  1208.  
  1209. def xstrip(s, chars=' '):
  1210.     return xreverse(xlstrip(xreverse(xlstrip(s, chars)), chars))
  1211.  
  1212.  
  1213.  
  1214. def getBitness():
  1215.     try:
  1216.         import platform
  1217.     except ImportError:
  1218.         return struct.calcsize("P") << 3
  1219.     else:
  1220.         return int(platform.architecture()[0][:-3])
  1221.  
  1222.  
  1223. BIG_ENDIAN = 0
  1224. LITTLE_ENDIAN = 1
  1225.  
  1226. def getEndian():
  1227.     if struct.pack("@I", 0x01020304)[0] == '\x01':
  1228.         return BIG_ENDIAN
  1229.     else:
  1230.         return LITTLE_ENDIAN
  1231.  
  1232.  
  1233. def get_password():
  1234.     return getpass.getpass("Enter password: ")
  1235.  
  1236. def run(cmd, log_output=True, password_func=get_password, timeout=1):
  1237.     output = cStringIO.StringIO()
  1238.  
  1239.     try:
  1240.         child = pexpect.spawn(cmd, timeout=timeout)
  1241.     except pexpect.ExceptionPexpect:
  1242.         return -1, ''
  1243.  
  1244.     try:
  1245.         while True:
  1246.             update_spinner()
  1247.             i = child.expect(["[pP]assword:", pexpect.EOF, pexpect.TIMEOUT])
  1248.  
  1249.             if child.before:
  1250.                 log.debug(child.before)
  1251.                 output.write(child.before)
  1252.  
  1253.             if i == 0: # Password:
  1254.                 if password_func is not None:
  1255.                     child.sendline(password_func())
  1256.                 else:
  1257.                     child.sendline(get_password())
  1258.  
  1259.             elif i == 1: # EOF
  1260.                 break
  1261.  
  1262.             elif i == 2: # TIMEOUT
  1263.                 continue
  1264.  
  1265.  
  1266.     except Exception, e:
  1267.         print "Exception", e
  1268.  
  1269.     cleanup_spinner()
  1270.     child.close()
  1271.  
  1272.     return child.exitstatus, output.getvalue()
  1273.  
  1274.  
  1275. def expand_range(ns): # ns -> string repr. of numeric range, e.g. "1-4, 7, 9-12"
  1276.     """Credit: Jean Brouwers, comp.lang.python 16-7-2004
  1277.        Convert a string representation of a set of ranges into a 
  1278.        list of ints, e.g.
  1279.        "1-4, 7, 9-12" --> [1,2,3,4,7,9,10,11,12]
  1280.     """
  1281.     fs = []
  1282.     for n in ns.split(','):
  1283.         n = n.strip()
  1284.         r = n.split('-')
  1285.         if len(r) == 2:  # expand name with range
  1286.             h = r[0].rstrip('0123456789')  # header
  1287.             r[0] = r[0][len(h):]
  1288.              # range can't be empty
  1289.             if not (r[0] and r[1]):
  1290.                 raise ValueError, 'empty range: ' + n
  1291.              # handle leading zeros
  1292.             if r[0] == '0' or r[0][0] != '0':
  1293.                 h += '%d'
  1294.             else:
  1295.                 w = [len(i) for i in r]
  1296.                 if w[1] > w[0]:
  1297.                    raise ValueError, 'wide range: ' + n
  1298.                 h += '%%0%dd' % max(w)
  1299.              # check range
  1300.             r = [int(i, 10) for i in r]
  1301.             if r[0] > r[1]:
  1302.                raise ValueError, 'bad range: ' + n
  1303.             for i in range(r[0], r[1]+1):
  1304.                 fs.append(h % i)
  1305.         else:  # simple name
  1306.             fs.append(n)
  1307.  
  1308.      # remove duplicates
  1309.     fs = dict([(n, i) for i, n in enumerate(fs)]).keys()
  1310.      # convert to ints and sort
  1311.     fs = [int(x) for x in fs if x]
  1312.     fs.sort()
  1313.  
  1314.     return fs
  1315.  
  1316.  
  1317. def collapse_range(x): # x --> sorted list of ints
  1318.     """ Convert a list of integers into a string
  1319.         range representation: 
  1320.         [1,2,3,4,7,9,10,11,12] --> "1-4, 7, 9-12"
  1321.     """
  1322.     if not x:
  1323.         return ""
  1324.  
  1325.     s, c, r = [str(x[0])], x[0], False
  1326.  
  1327.     for i in x[1:]:
  1328.         if i == (c+1):
  1329.             r = True
  1330.         else:
  1331.             if r:
  1332.                 s.append('-%s, %s' % (c,i))
  1333.                 r = False
  1334.             else:
  1335.                 s.append(', %s' % i)
  1336.  
  1337.         c = i
  1338.  
  1339.     if r:
  1340.         s.append('-%s' % i)
  1341.  
  1342.     return ''.join(s)
  1343.  
  1344.