Completed
Push — master ( 9ee029...d17eb3 )
by Chris
01:31
created

css_selector()   A

Complexity

Conditions 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
1
"""Standard filters."""
2
3
from string import ascii_lowercase
4
5
6
def css_selector(string, lowercase=True):
7
    """Convert a string to a css selector friendly format.
8
9
    Args:
10
        word (string): The string to format.
11
12
    Returns:
13
        word (string): The formatted word.
14
    """
15
    if not isinstance(string, str):
16
        return string
17
    string = string.replace(' ', '_')
18
    if not lowercase:
19
        return string
20
    return string.lower()
21
22
23
def title(word, capitalize=False):
24
    """Convert a string to a title format, where the words are capitalized.
25
26
    Args:
27
        word (string): The string to format.
28
29
    Returns:
30
        word (string): The formatted word.
31
    """
32
    def _capitalize(w):
33
        return '{0}{1}'.format(w[0].upper(), w[1:])
34
35
    if word is None:
36
        return ''
37
    words = word.split(' ')
38
    for i, word in enumerate(words):
39
        if i == 0 or capitalize:
40
            words[i] = _capitalize(word)
41
    return ' '.join(words)
42
43
44
def firstof(seq):
45
    """Return the first item that is truthy in a sequence.
46
47
    Equivalent to Djangos' firstof.
48
49
    Args:
50
        seq (list): A list of values.
51
52
    Returns:
53
        value (mixed): The output, depending on the truthiness of the input.
54
    """
55
    if not any(seq):
56
        return ''
57
    if all(seq):
58
        return seq[0]
59
    while seq:
60
        item = seq.pop(0)
61
        if item:
62
            return item
63
    return ''
64
65
66
def questionize_label(word):
67
    """Convert a word to a true/false style question format.
68
69
    If a user follows the convention of using `is_something`, or
70
    `has_something`, for a boolean value, the *property* text will
71
    automatically be converted into a more human-readable
72
    format, e.g. 'Something?' for is_ and Has Something? for has_.
73
74
    Args:
75
        word (string): The string to format.
76
77
    Returns:
78
        word (string): The formatted word.
79
    """
80
    if word is None:
81
        return ''
82
    if word.startswith('is_'):
83
        return '{0}?'.format(word[3:])
84
    elif word.startswith('has_'):
85
        return '{0}?'.format(word[4:])
86
    return word
87
88
89
def add(lst, arg):
90
    """Add an item to a list.
91
92
    Equivalent to Djangos' add.
93
94
    Args:
95
        lst (list): A list.
96
        arg (mixed): Any value to append to the list.
97
98
    Returns:
99
        list: The updated list.
100
    """
101
    lst.append(arg)
102
    return lst
103
104
105
def cut(val, removals):
106
    """Remove some value from a string.
107
108
    Similar to Djangos' cut, but accepts N arguments to remove, in turn.
109
110
    Args:
111
        val (str): A string.
112
        removals (list): Alist of values to remove in turn, from the value.
113
114
    Returns:
115
        str: The updated string.
116
    """
117
    def _cut(val, tocut):
118
        return val.replace(tocut, '')
119
    for r in removals:
120
        val = _cut(val, r)
121
    return val
122
123
124
def addslashes(val):
125
    """Add slashes before all single quotes in a given string.
126
127
    Equivalent to Djangos' addslashes.
128
129
    Args:
130
        val (str): A string.
131
132
    Returns:
133
        str: The updated string.
134
    """
135
    return val.replace("'", "\\'")
136
137
138
def default(val, default):
139
    """Default to a given value if another given value is falsy.
140
141
    Equivalent to Djangos' default.
142
143
    Args:
144
        val (mixed): A mixed value that is truthy or falsy.
145
        default (mixed): A default replacement value.
146
147
    Returns:
148
        mixed: The default given value, or the original value.
149
    """
150
    return default if not val else val
151
152
153
def default_if_none(val, default):
154
    """Default to a given value if another given value is None.
155
156
    Equivalent to Djangos' default_if_none.
157
158
    Args:
159
        val (mixed): A mixed value that may or may not be None.
160
        default (mixed): A default replacement value.
161
162
    Returns:
163
        mixed: The default given value, or the original value.
164
    """
165
    return default if val is None else val
166
167
168
def get_digit(val, index):
169
    """Return the digit of a value specified by an index.
170
171
    Equivalent to Djangos' get_digit.
172
173
    Args
174
        val (int): An integer.
175
        index (int): The index to check against.
176
177
    Returns:
178
        int: The original integer if index is invalid, otherwise the digit
179
        at the specified index.
180
    """
181
    digits = reversed(list(str(val)))
182
    for k, digit in enumerate(digits):
183
        if k + 1 == int(index):
184
            return int(digit)
185
    return val
186
187
188
def length_is(val, length):
189
    """Return True if the length of a given value matches a given length.
190
191
    Equivalent to Djangos' length_is.
192
193
    Args:
194
        val (mixed): A value to check the length of.
195
        length (int): The length to check.
196
197
    Returns:
198
        bool: The value of checking the length against length.
199
    """
200
    return len(val) == length
201
202
203
def is_url(val):
204
    """Return true if a value is a url string, otherwise false.
205
206
    Args:
207
        val (mixed): The value to check.
208
209
    Returns:
210
        bool: True if the value is an http string, False if not.
211
    """
212
    if isinstance(val, (str, unicode)):
213
        return val.startswith('http://') or val.startswith('https://')
214
    return False
215
216
217
def ljust(string, amt):
218
    """Left-align the value by the amount specified.
219
220
    Equivalent to Djangos' ljust.
221
222
    Args:
223
        string (str): The string to adjust.
224
        amt (int): The amount of space to adjust by.
225
226
    Returns:
227
        str: The padded string.
228
    """
229
    return string.ljust(amt)
230
231
232
def rjust(string, amt):
233
    """Right-align the value by the amount specified.
234
235
    Equivalent to Djangos' rjust.
236
237
    Args:
238
        string (str): The string to adjust.
239
        amt (int): The amount of space to adjust by.
240
241
    Returns:
242
        str: The padded string.
243
    """
244
    return string.rjust(amt)
245
246
247
def make_list(val, coerce_numbers=True):
248
    """Make a list from a given value.
249
250
    Roughly equivalent to Djangos' make_list, with some enhancements.
251
252
    Args:
253
        val (mixed): The value to convert.
254
        coerce_numbers (bool, optional): Whether or not string number
255
            should be coerced back to their original values.
256
257
    Returns:
258
        mixed: If dict is given, return d.items(). If list is given, return it.
259
            If integers given, return a list of digits.
260
            Otherwise, return a list of characters.
261
    """
262
    if isinstance(val, dict):
263
        return val.items()
264
    if isinstance(val, list):
265
        return val
266
    vals = list(str(val))
267
    if coerce_numbers and isinstance(val, str):
268
        lst = []
269
        for v in vals:
270
            try:
271
                lst.append(int(v))
272
            except ValueError:
273
                lst.append(v)
274
        return lst
275
    return vals
276
277
278
def phone2numeric(phoneword):
279
    """Convert a phoneword string into the translated number equivalent.
280
281
    Roughly equivalent to Djangos' phone2numeric.
282
283
    Args:
284
        phoneword (str): The phoneword string.
285
286
    Returns:
287
        str: The converted string digits.
288
    """
289
    two, three = ['a', 'b', 'c'], ['d', 'e', 'f']
290
    four, five = ['g', 'h', 'i'], ['j', 'k', 'l']
291
    six, seven = ['m', 'n', 'o'], ['p', 'q', 'r', 's']
292
    eight, nine = ['t', 'u', 'v'], ['w', 'x', 'y', 'z']
293
    newdigits = ''
294
    for digit in list(phoneword.lower()):
295
        if digit in two:
296
            newdigits += '2'
297
        elif digit in three:
298
            newdigits += '3'
299
        elif digit in four:
300
            newdigits += '4'
301
        elif digit in five:
302
            newdigits += '5'
303
        elif digit in six:
304
            newdigits += '6'
305
        elif digit in seven:
306
            newdigits += '7'
307
        elif digit in eight:
308
            newdigits += '8'
309
        elif digit in nine:
310
            newdigits += '9'
311
        else:
312
            newdigits += digit
313
    return newdigits
314
315
316
def pagetitle(string, remove_first=False, divider=' > '):
317
    """Convert a string of characters to page-title format.
318
319
    Args:
320
        string (str): The string to conert.
321
        remove_first (bool, optional): Remove the first instance of the
322
            delimiter of the newly formed title.
323
324
    Returns:
325
        str: The converted string.
326
    """
327
    _title = divider.join(string.split('/'))
328
    if remove_first:
329
        _title = _title.replace(divider, '', 1)
330
    return _title
331
332
333
def slugify(string):
334
    """Convert a string of characters to URL slug format.
335
336
    All characters replacing all characters with hyphens if invalid.
337
    Roughly equivalent to Djangos' slugify.
338
339
    Args:
340
        string (str): The string to slugify.
341
342
    Returns:
343
        str: The slugified string.
344
    """
345
    slug = ''
346
    accepted = ['-', '_'] + list(ascii_lowercase) + list('01234567890')
347
    end = len(string) - 1
348
    for k, char in enumerate(string.lower().strip()):
349
        if char not in accepted:
350
            # Forget about the last char if it would get replaced.
351
            if k < end:
352
                slug += '-'
353
        else:
354
            slug += char
355
    return slug
356
357
358
def greet(name, greeting='Hello'):
359
    """Add a greeting to a given name.
360
361
    Args:
362
        name (str): The name to greet.
363
        greeting (str, optional): An optional greeting override.
364
365
    Returns:
366
        str: The updated greeting string.
367
    """
368
    return '{0}, {1}!'.format(greeting, name)
369
370
371
def islist(item):
372
    """Check if an is item is a list - not just a sequence.
373
374
    Args:
375
        item (mixed): The item to check as a list.
376
377
    Returns:
378
        result (bool): True if the item is a list, False if not.
379
380
    """
381
    return isinstance(item, list)
382
383
384
def sql2dict(queryset):
385
    """Return a SQL alchemy style query result into a list of dicts.
386
387
    Args:
388
        queryset (object): The SQL alchemy result.
389
390
    Returns:
391
        result (list): The converted query set.
392
393
    """
394
    if queryset is None:
395
        return []
396
    return [record.__dict__ for record in queryset]
397