This file is indexed.

/usr/share/pyshared/fabio/fabioutils.py is in python-fabio 0.1.4-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
#!/usr/bin/env python
#coding: utf8

"""
General purpose utilities functions for fabio
"""
# get ready for python3
from __future__ import with_statement, print_function
import re, os, logging, threading, sys
import StringIO as stringIO
logger = logging.getLogger("fabioutils")
from .compression import bz2, gzip
import traceback
from math import ceil



FILETYPES = {
    # extension NNNimage fabioclass
    # type consistency - always use a list if one case is
    'edf'    : ['edf'],
    'cor'    : ['edf'],
    'pnm'    : ['pnm'],
    'pgm'    : ['pnm'],
    'pbm'    : ['pnm'],
    'tif'    : ['tif'],
    'tiff'   : ['tif'],
    'img'    : ['adsc', 'OXD', 'HiPiC', 'raxis'],
    'mccd'   : ['marccd'],
    'mar2300': ['mar345'],
    'sfrm'   : ['bruker100'],
    'msk'    : ['fit2dmask'],
    'spr'    : ['fit2dspreadsheet'],
    'dm3'    : ['dm3'],
    'kcd'    : ['kcd'],
    'cbf'    : ['cbf'],
    'xml'    : ["xsd"],
    'xsd'    : ["xsd"],
             }

# Add bzipped and gzipped
for key in FILETYPES.keys():
    FILETYPES[key + ".bz2"] = FILETYPES[key]
    FILETYPES[key + ".gz"] = FILETYPES[key]


# Compressors

COMPRESSORS = {}


dictAscii = {None:[chr(i) for i in range(32, 127)],
           }

try:
    lines = os.popen("gzip -h 2>&1").read()
    # Looking for "usage"
    if "sage" in lines:
        COMPRESSORS['.gz'] = 'gzip -dc '
    else:
        COMPRESSORS['.gz'] = None
except Exception:
    COMPRESSORS['.gz'] = None

try:
    lines = os.popen("bzip2 -h 2>&1").read()
    # Looking for "usage"
    if "sage" in lines:
        COMPRESSORS['.bz2'] = 'bzip2 -dc '
    else:
        COMPRESSORS['.bz2'] = None
except Exception:
    COMPRESSORS['.bz2'] = None

def deprecated(func):
    """
    used to deprecate a function/method: prints a lot of warning messages to enforce the modifaction of the code
    """
    def wrapper(*arg, **kw):
        """
        decorator that deprecates the use of a function
        """
        logger.warning("%s is Deprecated !!! %s" % (func.func_name, os.linesep.join([""] + traceback.format_stack()[:-1])))
        return func(*arg, **kw)
    return wrapper

def pad(mystr, pattern=" ", size=80):
    """
    Performs the padding of the string to the right size with the right pattern
    """
    size = int(size)
    padded_size = int(ceil(float(len(mystr)) / size) * size)
    if len(pattern) == 1:
        return mystr.ljust(padded_size, pattern)
    else:
        return (mystr + pattern * int(ceil(float(padded_size - len(mystr)) / len(pattern))))[:padded_size]


def getnum(name):
    """
    # try to figure out a file number
    # guess it starts at the back
    """
    stem , num, post_num = numstem(name)
    try:
        return int(num)
    except ValueError:
        return None

class FilenameObject(object):
    """
    The 'meaning' of a filename ...
    """
    def __init__(self, stem=None,
            num=None,
            directory=None,
            format=None,
            extension=None,
            postnum=None,
            digits=4,
            filename=None):
        """
        This class can either be instanciated by a set of parameters like  directory, prefix, num, extension, ...

        @param stem: the stem is a kind of prefix (str)
        @param num: image number in the serie (int)
        @param directory: name of the directory (str)
        @param format: ??
        @param extension:
        @param postnum:
        @param digits: Number of digits used to print num

        Alternative constructor:

        @param filename: fullpath of an image file to be deconstructed into directory, prefix, num, extension, ...

        """


        self.stem = stem
        self.num = num
        self.format = format
        self.extension = extension
        self.digits = digits
        self.postnum = postnum
        self.directory = directory
        self.compressed = None
        if filename is not None:
            self.deconstruct_filename(filename)


    def str(self):
        """ Return a string representation """
        fmt = "stem %s, num %s format %s extension %s " + \
                "postnum = %s digits %s dir %s"
        return fmt % tuple([str(x) for x in [
                    self.stem ,
                    self.num ,
                    self.format ,
                    self.extension ,
                    self.postnum ,
                    self.digits ,
                    self.directory ] ])
    __repr__ = str

    def tostring(self):
        """
        convert yourself to a string
        """
        name = self.stem
        if self.digits is not None and self.num is not None:
            fmt = "%0" + str(self.digits) + "d"
            name += fmt % self.num
        if self.postnum is not None:
            name += self.postnum
        if self.extension is not None:
            name += self.extension
        if self.directory is not None:
            name = os.path.join(self.directory, name)
        return name


    def deconstruct_filename(self, filename):
        """
        Break up a filename to get image type and number
        """
        direc, name = os.path.split(filename)
        direc = direc or None
        parts = name.split(".")
        compressed = False
        stem = parts[0]
        extn = ""
        postnum = ""
        ndigit = 4
        num = None
        typ = None
        if parts[-1] in ["gz", "bz2"]:
            extn = "." + parts[-1]
            parts = parts[:-1]
            compressed = True
        if parts[-1] in FILETYPES.keys():
            typ = FILETYPES[parts[-1]]
            extn = "." + parts[-1] + extn
            try:
                stem, numstring, postnum = numstem(".".join(parts[:-1]))
                num = int(numstring)
                ndigit = len(numstring)
            except Exception, err:
                # There is no number - hence make num be None, not 0
                logger.debug("l176: %s" % err)
                num = None
                stem = "".join(parts[:-1])
        else:
            # Probably two type left
            if len(parts) == 1:
                # Probably GE format stem_numb
                parts2 = parts[0].split("_")
                if parts2[-1].isdigit():
                    num = int(parts2[-1])
                    ndigit = len(parts2[-1])
                    typ = ['GE']
                    stem = "_".join(parts2[:-1]) + "_"
            else:
                try:
                    num = int(parts[-1])
                    ndigit = len(parts[-1])
                    typ = ['bruker']
                    stem = ".".join(parts[:-1]) + "."
                except Exception, err:
                    logger.debug("l196: %s" % err)
                    typ = None
                    extn = "." + parts[-1] + extn
                    numstring = ""
                    try:
                        stem , numstring, postnum = numstem(".".join(parts[:-1]))
                    except Exception, err:
                        logger.debug("l202: %s" % err)
                        raise
                    if numstring.isdigit():
                        num = int(numstring)
                        ndigit = len(numstring)
                #            raise Exception("Cannot decode "+filename)

        self.stem = stem
        self.num = num
        self.directory = direc
        self.format = typ
        self.extension = extn
        self.postnum = postnum
        self.digits = ndigit
        self.compressed = compressed

def numstem(name):
    """ cant see how to do without reversing strings
    Match 1 or more digits going backwards from the end of the string
    """
    reg = re.compile(r"^(.*?)(-?[0-9]{0,9})(\D*)$")
    #reg = re.compile("""(\D*)(\d\d*)(\w*)""")
    try:
        res = reg.match(name).groups()
        #res = reg.match(name[::-1]).groups()
        #return [ r[::-1] for r in res[::-1]]
        if len(res[0]) == len(res[1]) == 0: # Hack for file without number
            return [res[2], '', '']
        return [ r for r in res]
    except AttributeError: # no digits found
        return [name, "", ""]

#@deprecated
def deconstruct_filename(filename):
    """
    Function for backward compatibility.
    Deprecated
    """
    return FilenameObject(filename=filename)

def construct_filename(filename, frame=None):
    "Try to construct the filename for a given frame"
    fobj = FilenameObject(filename=filename)
    if frame is not None:
        fobj.num = frame
    return fobj.tostring()

def next_filename(name, padding=True):
    """ increment number """
    fobj = FilenameObject(filename=name)
    fobj.num += 1
    if not padding:
        fobj.digits = 0
    return fobj.tostring()

def previous_filename(name, padding=True):
    """ decrement number """
    fobj = FilenameObject(filename=name)
    fobj.num -= 1
    if not padding:
        fobj.digits = 0
    return fobj.tostring()

def jump_filename(name, num, padding=True):
    """ jump to number """
    fobj = FilenameObject(filename=name)
    fobj.num = num
    if not padding:
        fobj.digits = 0
    return fobj.tostring()


def extract_filenumber(name):
    """ extract file number """
    fobj = FilenameObject(filename=name)
    return fobj.num

def isAscii(name, listExcluded=None):
    """
    @param name: string to check
    @param listExcluded: list of char or string excluded.
    @return: True of False whether  name is pure ascii or not
    """
    isascii = None
    try:
        name.decode("ascii")
    except UnicodeDecodeError:
        isascii = False
    else:
        if listExcluded:
            isascii = not(any(bad in  name for bad in listExcluded))
        else:
            isascii = True
    return isascii

def toAscii(name, excluded=None):
    """
    @param name: string to check
    @param excluded: tuple of char or string excluded (not list: they are mutable).
    @return: the name with all non valid char removed
    """
    if excluded not in dictAscii:
        ascii = dictAscii[None][:]
        for i in excluded:
            if i in ascii:
                ascii.remove(i)
            else:
                logger.error("toAscii: % not in ascii table" % i)
        dictAscii[excluded] = ascii
    else:
        ascii = dictAscii[excluded]
    out = [i for i in str(name) if i in ascii]
    return "".join(out)

def nice_int(s):
    """
    Workaround that int('1.0') raises an exception

    @param s: string to be converted to integer
    """
    try:
        return int(s)
    except ValueError:
        return int(float(s))


class StringIO(stringIO.StringIO):
    """
    just an interface providing the name and mode property to a StringIO

    BugFix for MacOSX mainly
    """
    def __init__(self, data, fname=None, mode="r"):
        stringIO.StringIO.__init__(self, data)
        self.closed = False
        if fname == None:
            self.name = "fabioStream"
        else:
            self.name = fname
        self.mode = mode
        self.lock = threading.Semaphore()
        self.__size = None

    def getSize(self):
        if self.__size is None:
            logger.debug("Measuring size of %s" % self.name)
            with self.lock:
                pos = self.tell()
                self.seek(0, os.SEEK_END)
                self.__size = self.tell()
                self.seek(pos)
        return self.__size
    def setSize(self, size):
        self.__size = size
    size = property(getSize, setSize)

class File(file):
    """
    wrapper for "file" with locking
    """
    def __init__(self, name, mode="rb", buffering=0):
        """file(name[, mode[, buffering]]) -> file object

        Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),
        writing or appending.  The file will be created if it doesn't exist
        when opened for writing or appending; it will be truncated when
        opened for writing.  Add a 'b' to the mode for binary files.
        Add a '+' to the mode to allow simultaneous reading and writing.
        If the buffering argument is given, 0 means unbuffered, 1 means line
        buffered, and larger numbers specify the buffer size.  The preferred way
        to open a file is with the builtin open() function.
        Add a 'U' to mode to open the file for input with universal newline
        support.  Any line ending in the input file will be seen as a '\n'
        in Python.  Also, a file so opened gains the attribute 'newlines';
        the value for this attribute is one of None (no newline read yet),
        '\r', '\n', '\r\n' or a tuple containing all the newline types seen.

        'U' cannot be combined with 'w' or '+' mode.
        """
        file.__init__(self, name, mode, buffering)
        self.lock = threading.Semaphore()
        self.__size = None
    def getSize(self):
        if self.__size is None:
            logger.debug("Measuring size of %s" % self.name)
            with self.lock:
                pos = self.tell()
                self.seek(0, os.SEEK_END)
                self.__size = self.tell()
                self.seek(pos)
        return self.__size
    def setSize(self, size):
        self.__size = size
    def __exit__(self, *args, **kwargs):
        """
        Close the file.
        """
        return file.close(self)
    def __enter__(self, *args, **kwargs):
        return self
    size = property(getSize, setSize)


class UnknownCompressedFile(File):
    """
    wrapper for "File" with locking
    """
    def __init__(self, name, mode="rb", buffering=0):
        logger.warning("No decompressor found for this type of file (are gzip anf bz2 installed ???")
        File.__init__(self, name, mode, buffering)

if gzip is None:
    GzipFile = UnknownCompressedFile
else:
    class GzipFile(gzip.GzipFile):
        """
        Just a wrapper forgzip.GzipFile providing the correct seek capabilities for python 2.5
        """
        def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None):
            """
            Wrapper with locking for constructor for the GzipFile class.

            At least one of fileobj and filename must be given a
            non-trivial value.

            The new class instance is based on fileobj, which can be a regular
            file, a StringIO object, or any other object which simulates a file.
            It defaults to None, in which case filename is opened to provide
            a file object.

            When fileobj is not None, the filename argument is only used to be
            included in the gzip file header, which may includes the original
            filename of the uncompressed file.  It defaults to the filename of
            fileobj, if discernible; otherwise, it defaults to the empty string,
            and in this case the original filename is not included in the header.

            The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb',
            depending on whether the file will be read or written.  The default
            is the mode of fileobj if discernible; otherwise, the default is 'rb'.
            Be aware that only the 'rb', 'ab', and 'wb' values should be used
            for cross-platform portability.

            The compresslevel argument is an integer from 1 to 9 controlling the
            level of compression; 1 is fastest and produces the least compression,
            and 9 is slowest and produces the most compression.  The default is 9.
            """
            gzip.GzipFile.__init__(self, filename, mode, compresslevel, fileobj)
            self.lock = threading.Semaphore()
            self.__size = None
#            self.getSize()

        def __repr__(self):
            return "fabio." + gzip.GzipFile.__repr__(self)

        def getSize(self):
            if self.mode == gzip.WRITE:
                return self.size
            if self.__size is None:
                with self.lock:
                    if self.__size is None:
                        pos = self.offset
                        end_pos = len(gzip.GzipFile.read(self)) + pos
                        self.seek(pos)
                        logger.debug("Measuring size of %s: %s @ %s == %s" % (self.name, end_pos, pos, self.offset))
                        self.__size = end_pos
            return self.__size
        if sys.version_info < (2, 7):
            def setSize(self, value):
                self.__size = value
            size = property(getSize, setSize)
            @property
            def closed(self):
                return self.fileobj is None

            def seek(self, offset, whence=os.SEEK_SET):
                """
                Move to new file position.

                Argument offset is a byte count.  Optional argument whence defaults to
                0 (offset from start of file, offset should be >= 0); other values are 1
                (move relative to current position, positive or negative), and 2 (move
                relative to end of file, usually negative, although many platforms allow
                seeking beyond the end of a file).  If the file is opened in text mode,
                only offsets returned by tell() are legal.  Use of other offsets causes
                undefined behavior.

                This is a wrapper for seek to ensure compatibility with old python 2.5

                Warning: Seek from end is not supported (works only for single blocks !!!)
                This implemtents a hack
                """
                if whence == os.SEEK_SET:
                    gzip.GzipFile.seek(self, offset)
                elif whence == os.SEEK_CUR:
                    gzip.GzipFile.seek(self, offset + self.tell())
                elif whence == os.SEEK_END:
                    gzip.GzipFile.seek(self, offset + self.getSize())

            def __enter__(self, *args, **kwargs):
                return self
            def __exit__(self, *args, **kwargs):
                """
                Close the file.
                """
                return gzip.GzipFile.close(self)

if bz2 is None:
    BZ2File = UnknownCompressedFile
else:
    class BZ2File(bz2.BZ2File):
        "Wrapper with lock"
        def __init__(self, name , mode='r', buffering=0, compresslevel=9):
            """
            BZ2File(name [, mode='r', buffering=0, compresslevel=9]) -> file object

            Open a bz2 file. The mode can be 'r' or 'w', for reading (default) or
            writing. When opened for writing, the file will be created if it doesn't
            exist, and truncated otherwise. If the buffering argument is given, 0 means
            unbuffered, and larger numbers specify the buffer size. If compresslevel
            is given, must be a number between 1 and 9.

            Add a 'U' to mode to open the file for input with universal newline
            support. Any line ending in the input file will be seen as a '\n' in
            Python. Also, a file so opened gains the attribute 'newlines'; the value
            for this attribute is one of None (no newline read yet), '\r', '\n',
            '\r\n' or a tuple containing all the newline types seen. Universal
            newlines are available only when reading.
            """
            bz2.BZ2File.__init__(self, name , mode, buffering, compresslevel)
            self.lock = threading.Semaphore()
            self.__size = None
        def getSize(self):
            if self.__size is None:
                logger.debug("Measuring size of %s" % self.name)
                with self.lock:
                    pos = self.tell()
                    all = self.read()
                    self.__size = self.tell()
                    self.seek(pos)
            return self.__size
        def setSize(self, value):
            self.__size = value
        size = property(getSize, setSize)
        def __exit__(self, *args, **kwargs):
                """
                Close the file.
                """
                return bz2.BZ2File.close(self)
        def __enter__(self, *args, **kwargs):
            return self



class DebugSemaphore(threading._Semaphore):
    """
    threading.Semaphore like class with helper for fighting dead-locks
    """
    write_lock = threading._Semaphore()
    blocked = []
    def __init__(self, *arg, **kwarg):
        threading._Semaphore.__init__(self, *arg, **kwarg)


    def acquire(self, *arg, **kwarg):
        if self._Semaphore__value == 0:
            with self.write_lock:
                self.blocked.append(id(self))
                sys.stderr.write(os.linesep.join(["Blocking sem %s" % id(self)] + \
                                        traceback.format_stack()[:-1] + [""]))

        return threading._Semaphore.acquire(self, *arg, **kwarg)

    def release(self, *arg, **kwarg):
        with self.write_lock:
            uid = id(self)
            if uid in self.blocked:
                self.blocked.remove(uid)
                sys.stderr.write("Released sem %s %s" % (uid, os.linesep))
        threading._Semaphore.release(self, *arg, **kwarg)

    def __enter__(self):
        self.acquire()
        return self

    def __exit__(self, *arg, **kwarg):
        self.release()