/usr/lib/python3/dist-packages/pybtex/utils.py is in python3-pybtex 0.21-2.
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 | # Copyright (c) 2006-2017 Andrey Golovigin
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Miscellaneous small utils."""
import itertools
from functools import wraps
from collections import deque, Sequence, MutableMapping, MutableSet
from collections import OrderedDict
from types import GeneratorType
def deprecated(since, reason=None):
def decorator(f):
@wraps(f)
def new_f(*args, **kwargs):
import warnings
message = '{0}() is deprecated since {1}'.format(f.__name__, since)
if reason:
message += ': {0}'.format(reason)
warnings.warn(message, DeprecationWarning, stacklevel=2)
return f(*args, **kwargs)
return new_f
return decorator
def memoize(f, capacity=1024):
memory = {}
history = deque()
@wraps(f)
def new_f(*args):
if args not in memory:
if len(history) >= capacity:
del memory[history.popleft()]
memory[args] = f(*args)
history.append(args)
return memory[args]
return new_f
def collect_iterable(f):
@wraps(f)
def new_f(*args, **kwargs):
return list(f(*args, **kwargs))
return new_f
def pairwise(iterable):
a, b = itertools.tee(iterable)
next(b, None)
return itertools.zip_longest(a, b)
class CaseInsensitiveDict(MutableMapping):
"""A dict with case-insensitive lookup.
>>> d = CaseInsensitiveDict(TesT='passed')
>>> d
CaseInsensitiveDict({'TesT': 'passed'})
>>> d.lower()
CaseInsensitiveDict({'test': 'passed'})
>>> print(d['TesT'])
passed
>>> print(d['test'])
passed
>>> print(d['Test'])
passed
>>> print(d.get('test'))
passed
>>> print(d.get('Test'))
passed
>>> d['Test'] = 'passed again'
>>> print(d['test'])
passed again
>>> 'test' in d
True
>>> 'Test' in d
True
>>> print(list(d.keys()))
['Test']
>>> for key in d:
... print(key)
Test
>>> for key, value in d.items():
... print(key, value)
Test passed again
>>> bool(d)
True
>>> len(d)
1
>>> del d['test']
>>> len(d)
0
>>> bool(d)
False
>>> 'test' in d
False
>>> 'Test' in d
False
>>> print(d.get('test'))
None
>>> print(d.get('Test'))
None
>>> print(d.get('Test', 'failed'))
failed
>>> CaseInsensitiveDict(
... (key, value) for key, value in [('a', 'b')]
... )
CaseInsensitiveDict({'a': 'b'})
"""
def __init__(self, *args, **kwargs):
initial = dict(*args, **kwargs)
self._dict = dict((key.lower(), value) for key, value in initial.items())
self._keys = dict((key.lower(), key) for key in initial)
def __len__(self):
return len(self._dict)
def __iter__(self):
return iter(list(self._keys.values()))
def __setitem__(self, key, value):
"""To implement lowercase keys."""
key_lower = key.lower()
self._dict[key_lower] = value
self._keys[key_lower] = key
def __getitem__(self, key):
return self._dict[key.lower()]
def __delitem__(self, key):
key_lower = key.lower()
del self._dict[key_lower]
del self._keys[key_lower]
def __contains__(self, key):
return key.lower() in self._dict
def __repr__(self):
"""A caselessDict version of __repr__ """
dct = dict((key, self[key]) for key in self)
return '{0}({1})'.format(
type(self).__name__, repr(dct),
)
def iteritems_lower(self):
return ((key.lower(), value) for key, value in self.items())
def lower(self):
return type(self)(self.iteritems_lower())
class CaseInsensitiveDefaultDict(CaseInsensitiveDict):
"""CaseInseisitiveDict with default factory, like collections.defaultdict
>>> d = CaseInsensitiveDefaultDict(int)
>>> d['a']
0
>>> d['a'] += 1
>>> d['a']
1
>>> d['A']
1
>>> d['a'] = 3
>>> d['a']
3
>>> d['B'] += 10
>>> d['b']
10
"""
def __init__(self, default_factory):
super(CaseInsensitiveDefaultDict, self).__init__()
self.default_factory = default_factory
def __getitem__(self, key):
try:
return super(CaseInsensitiveDefaultDict, self).__getitem__(key)
except KeyError:
return self.default_factory()
class OrderedCaseInsensitiveDict(CaseInsensitiveDict):
""" An (incomplete) ordered case-insensitive dict.
>>> d = OrderedCaseInsensitiveDict([
... ('Uno', 1),
... ('Dos', 2),
... ('Tres', 3),
... ])
>>> d
OrderedCaseInsensitiveDict([('Uno', 1), ('Dos', 2), ('Tres', 3)])
>>> d.lower()
OrderedCaseInsensitiveDict([('uno', 1), ('dos', 2), ('tres', 3)])
>>> list(d.keys())
['Uno', 'Dos', 'Tres']
>>> list(d.items())
[('Uno', 1), ('Dos', 2), ('Tres', 3)]
>>> list(d.values())
[1, 2, 3]
>>> d['Cuatro'] = 4
>>> list(d.keys())
['Uno', 'Dos', 'Tres', 'Cuatro']
>>> list(d.items())
[('Uno', 1), ('Dos', 2), ('Tres', 3), ('Cuatro', 4)]
>>> list(d.values())
[1, 2, 3, 4]
>>> list(d)
['Uno', 'Dos', 'Tres', 'Cuatro']
>>> list(d.keys()) == list(d.keys())
True
>>> list(d.values()) == list(d.values())
True
>>> list(d.items()) == list(d.items())
True
>>> 'Uno' in d
True
>>> 'uno' in d
True
>>> d['Uno']
1
>>> d['uno']
1
>>> d['UNO']
1
>>> 'Cuatro' in d
True
>>> 'CUATRO' in d
True
>>> d['Cuatro']
4
>>> d['cuatro']
4
>>> d['UNO'] = 'one'
>>> d['uno']
'one'
>>> d['Uno']
'one'
>>> list(d.keys())
['Uno', 'Dos', 'Tres', 'Cuatro']
>>> d['cuatro'] = 'four'
>>> d['Cuatro']
'four'
>>> d['cuatro']
'four'
>>> list(d.keys())
['Uno', 'Dos', 'Tres', 'Cuatro']
"""
def __init__(self, data=()):
if isinstance(data, GeneratorType):
data = list(data)
if isinstance(data, Sequence):
self.order = [key for key, value in data]
else:
self.order = list(data.keys())
super(OrderedCaseInsensitiveDict, self).__init__(data)
def __setitem__(self, key, value):
if key not in self:
self.order.append(key)
super(OrderedCaseInsensitiveDict, self).__setitem__(key, value)
def __delitem__(self, key):
raise NotImplementedError
def __iter__(self):
return iter(self.order)
def __eq__(self, other):
"""
>>> OrderedCaseInsensitiveDict([('a', 1), ('b', 2)]) == OrderedCaseInsensitiveDict([('a', 1), ('b', 2)])
True
>>> OrderedCaseInsensitiveDict([('a', 1), ('b', 2)]) == OrderedCaseInsensitiveDict([('b', 2), ('a', 1)])
False
>>> OrderedCaseInsensitiveDict([('a', 1), ('b', 2)]) == dict([('b', 2), ('a', 1)])
True
>>> OrderedCaseInsensitiveDict([('a', 1), ('B', 2)]) == OrderedCaseInsensitiveDict([('A', 1), ('b', 2)])
False
"""
if isinstance(other, (OrderedCaseInsensitiveDict, OrderedDict)):
return list(self.items()) == list(other.items())
else:
return super(OrderedCaseInsensitiveDict, self).__eq__(other)
def iterkeys(self):
return iter(self.order)
def keys(self):
return self.order
def itervalues(self):
for key in self.order:
yield self[key]
def values(self):
return [self[key] for key in self.order]
def iteritems(self):
for key in self.order:
yield key, self[key]
def items(self):
return [(key, self[key]) for key in self.order]
def __repr__(self):
return '{0}({1})'.format(
type(self).__name__, repr(list(self.items()))
)
class CaseInsensitiveSet(MutableSet):
"""A very basic case-insensitive set.
>>> s = CaseInsensitiveSet()
>>> len(s)
0
>>> 'a' in s
False
>>> list(CaseInsensitiveSet(['aaa', 'Aaa', 'AAA']))
['aaa']
>>> s = CaseInsensitiveSet(['Aaa', 'Bbb'])
>>> s
CaseInsensitiveSet(['Aaa', 'Bbb'])
>>> s.lower()
CaseInsensitiveSet(['aaa', 'bbb'])
>>> len(s)
2
>>> 'aaa' in s
True
>>> 'Aaa' in s
True
>>> 'AAA' in s
True
>>> 'bbb' in s
True
>>> 'Bbb' in s
True
>>> 'abc' in s
False
>>> s.add('ccc')
>>> len(s)
3
>>> 'aaa' in s
True
>>> 'ccc' in s
True
>>> s.remove('AAA')
>>> len(s)
2
>>> 'aaa' in s
False
>>> bool(CaseInsensitiveSet(['a']))
True
>>> bool(CaseInsensitiveSet([]))
False
>>> bool(CaseInsensitiveSet())
False
"""
def __init__(self, iterable=()):
self._set = set()
self._keys = dict()
for item in iterable:
self.add(item)
def __contains__(self, key):
return key.lower() in self._set
def __iter__(self):
return iter(self._set)
def __len__(self):
return len(self._set)
def __repr__(self):
"""A caselessDict version of __repr__ """
return '{0}({1})'.format(
type(self).__name__, repr(sorted(self._keys.values()))
)
def add(self, key):
key_lower = key.lower()
self._set.add(key_lower)
self._keys[key_lower] = key
def discard(self, key):
key_lower = key.lower()
self._set.discard(key_lower)
self._keys.pop(key_lower, None)
def get_canonical_key(self, key):
return self._keys[key.lower()]
def lower(self):
return type(self)(self._set)
|