~azzar1/unity/add-show-desktop-key

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
# IVLE - Informatics Virtual Learning Environment
# Copyright (C) 2007-2008 The University of Melbourne
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

# Module: util
# Author: Matt Giuca
# Date: 12/12/2007

# Contains common utility functions.

import os
import sys
import stat

class IVLEError(Exception):
    """Legacy general IVLE exception.

    This is the old "standard" exception class for IVLE errors. It is only
    used in fileservice, and should not be used in any new code.
    """

    message = None

    def __init__(self, httpcode, message=None):
        self.httpcode = httpcode
        self.message = message
        self.args = (httpcode, message)

class IVLEJailError(Exception):
    """Exception proxying an in-jail error.

    This exception indicates an error that occurred inside an IVLE CGI script
    inside the jail. It should never be raised directly - only by the 
    interpreter.

    Information will be retrieved from it, and then treated as a normal
    error.
    """
    def __init__(self, type_str, message, info):
        self.type_str = type_str
        self.message = message
        self.info = info

class FakeObject(object):
    """ A representation of an object that can't be Pickled """
    def __init__(self, type, name, attrib={}):
        self.type = type
        self.name = name
        self.attrib = attrib

    def __repr__(self):
        return "<Fake %s %s>"%(self.type, self.name)

def split_path(path):
    """Given a path, returns a tuple consisting of the top-level directory in
    the path, and the rest of the path. Note that both items in the tuple will
    NOT begin with a slash, regardless of whether the original path did. Also
    normalises the path.

    Always returns a pair of strings, except for one special case, in which
    the path is completely empty (or just a single slash). In this case the
    return value will be (None, ''). But still always returns a pair.

    Examples:

    >>> split_path("")
    (None, '')
    >>> split_path("/")
    (None, '')
    >>> split_path("home")
    ('home', '')
    >>> split_path("home/docs/files")
    ('home', 'docs/files')
    >>> split_path("//home/docs/files")
    ('', 'home/docs/files')
    """
    path = os.path.normpath(path)
    # Ignore the opening slash
    if path.startswith(os.sep):
        path = path[len(os.sep):]
    if path == '' or path == '.':
        return (None, '')
    splitpath = path.split(os.sep, 1)
    if len(splitpath) == 1:
        return (splitpath[0], '')
    else:
        return tuple(splitpath)

def relpath(path, start=os.path.curdir):
    """Return a relative version of a path.
    XXX Backported from Python 2.6 posixpath.py.
    """

    if not path:
        raise ValueError("no path specified")

    start_list = os.path.abspath(start).split(os.path.sep)
    path_list = os.path.abspath(path).split(os.path.sep)

    # Work out how much of the filepath is shared by start and path.
    i = len(os.path.commonprefix([start_list, path_list]))

    rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:]
    if not rel_list:
        return os.path.curdir
    return os.path.join(*rel_list)

def incomplete_utf8_sequence(byteseq):
    """Calculate the completeness of a UTF-8 encoded string.

    Given a UTF-8-encoded byte sequence (str), returns the number of bytes at
    the end of the string which comprise an incomplete UTF-8 character
    sequence.

    If the string is empty or ends with a complete character OR INVALID
    sequence, returns 0.
    Otherwise, returns 1-3 indicating the number of bytes in the final
    incomplete (but valid) character sequence.

    Does not check any bytes before the final sequence for correctness.

    >>> incomplete_utf8_sequence("")
    0
    >>> incomplete_utf8_sequence("xy")
    0
    >>> incomplete_utf8_sequence("xy\xc3\xbc")
    0
    >>> incomplete_utf8_sequence("\xc3")
    1
    >>> incomplete_utf8_sequence("\xbc\xc3")
    1
    >>> incomplete_utf8_sequence("xy\xbc\xc3")
    1
    >>> incomplete_utf8_sequence("xy\xe0\xa0")
    2
    >>> incomplete_utf8_sequence("xy\xf4")
    1
    >>> incomplete_utf8_sequence("xy\xf4\x8f")
    2
    >>> incomplete_utf8_sequence("xy\xf4\x8f\xa0")
    3
    """
    count = 0
    expect = None
    for b in byteseq[::-1]:
        b = ord(b)
        count += 1
        if b & 0x80 == 0x0:
            # 0xxxxxxx (single-byte character)
            expect = 1
            break
        elif b & 0xc0 == 0x80:
            # 10xxxxxx (subsequent byte)
            pass
        elif b & 0xe0 == 0xc0:
            # 110xxxxx (start of 2-byte sequence)
            expect = 2
            break
        elif b & 0xf0 == 0xe0:
            # 1110xxxx (start of 3-byte sequence)
            expect = 3
            break
        elif b & 0xf8 == 0xf0:
            # 11110xxx (start of 4-byte sequence)
            expect = 4
            break
        else:
            # Invalid byte
            return 0

        if count >= 4:
            # Seen too many "subsequent bytes", invalid
            return 0

    if expect is None:
        # We never saw a "first byte", invalid
        return 0

    # We now know expect and count
    if count >= expect:
        # Complete, or we saw an invalid sequence
        return 0
    elif count < expect:
        # Incomplete
        return count

def safe_rmtree(path, ignore_errors=False, onerror=None):
    """Recursively delete a directory tree.

    Copied from shutil.rmtree from Python 2.6, which does not follow symbolic
    links (it is otherwise unsafe to call as root on untrusted directories; do
    not use shutil.rmtree in this case, as you may be running Python 2.5).

    If ignore_errors is set, errors are ignored; otherwise, if onerror
    is set, it is called to handle the error with arguments (func,
    path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
    path is the argument to that function that caused it to fail; and
    exc_info is a tuple returned by sys.exc_info().  If ignore_errors
    is false and onerror is None, an exception is raised.

    """
    if ignore_errors:
        def onerror(*args):
            pass
    elif onerror is None:
        def onerror(*args):
            raise
    try:
        if os.path.islink(path):
            # symlinks to directories are forbidden, see bug #1669
            raise OSError("Cannot call safe_rmtree on a symbolic link")
    except OSError:
        onerror(os.path.islink, path, sys.exc_info())
        # can't continue even if onerror hook returns
        return
    names = []
    try:
        names = os.listdir(path)
    except os.error, err:
        onerror(os.listdir, path, sys.exc_info())
    for name in names:
        fullname = os.path.join(path, name)
        try:
            mode = os.lstat(fullname).st_mode
        except os.error:
            mode = 0
        if stat.S_ISDIR(mode):
            safe_rmtree(fullname, ignore_errors, onerror)
        else:
            try:
                os.remove(fullname)
            except os.error, err:
                onerror(os.remove, fullname, sys.exc_info())
    try:
        os.rmdir(path)
    except os.error:
        onerror(os.rmdir, path, sys.exc_info())

def format_submission_principal(user, principal):
    """Render a list of users to fit in the offering project listing.

    Given a user and a list of submitters, returns 'solo' if the
    only submitter is the user, or a string of the form
    'with A, B and C' if there are any other submitters.

    If submitters is None, we assume that the list of members could
    not be determined, so we just return 'group'.
    """
    if principal is None:
        return 'group'

    if principal is user:
        return 'solo'

    display_names = sorted(
        member.display_name for member in principal.members
        if member is not user)

    if len(display_names) == 0:
        return 'solo (%s)' % principal.name
    elif len(display_names) == 1:
        return 'with %s (%s)' % (display_names[0], principal.name)
    elif len(display_names) > 5:
        return 'with %d others (%s)' % (len(display_names), principal.name)
    else:
        return 'with %s and %s (%s)' % (', '.join(display_names[:-1]),
                                        display_names[-1], principal.name)