How to use pluralise method in Contexts

Best Python code snippet using Contexts

Run Contexts automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

textsupport.py

Source: textsupport.py Github

copy
1"""
2This module is supposed to do useful things in the area of text formatting.
3"""
4
5import StringIO
6
7
8def hcolumns(strings, width=80, marginSize=1, leftMarginSize=2, columnSize=None):
9    if columnSize is None:
10        columnSize = max(len(s) for s in strings)
11    columnSize += marginSize
12
13    sio = StringIO.StringIO()
14    sio.write(leftMarginSize * " ")
15    currentWidth = leftMarginSize
16    for s in strings:
17        if currentWidth + columnSize > width:
18            sio.write((width - currentWidth) * " ")
19            sio.write(leftMarginSize * " ")
20            currentWidth = leftMarginSize
21        sio.write(s)
22        sio.write((columnSize - len(s)) * " ")
23        currentWidth += columnSize
24    return sio.getvalue()
25
26
27def number_to_words(number):
28    if number < 20:
29        return [
30            "none", "one", "two", "three", "four", "five", "six", "seven", "eight",
31            "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
32            "sixteen", "seventeen", "eighteen", "nineteen"
33        ][number]
34
35    if number < 100:
36        factor = (number / 10) - 2
37        remainder = number % 10
38        remainderString = ""
39        if remainder:
40            remainderString = " "+ number_to_words(remainder)
41        return [
42            "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"
43        ][factor] + remainderString
44
45    if number < 1000:
46        factor = (number / 100)
47        remainder = number % 100
48        parts = [ number_to_words(factor) +" hundred" ]
49        if remainder:
50            parts.append(number_to_words(remainder))
51        return " and ".join(parts)
52
53    if number < 1000000:
54        factor = number / 1000
55        remainder = number % 1000
56        parts = [ number_to_words(factor) +" thousand" ]
57        if remainder:
58            parts.append(number_to_words(remainder))
59        if remainder < 100:
60            return " and ".join(parts)
61        return ", ".join(parts)            
62
63    factor = number / 1000000
64    remainder = number % 1000000
65    parts = [ number_to_words(factor) +" million" ]
66    if remainder:
67        parts.append(number_to_words(remainder))
68    if remainder < 100:
69        return " and ".join(parts)
70    return ", ".join(parts)            
71
72
73def pluralise(noun):
74    plural = {
75        "bison": "bison",
76        "goose": "geese",  # Irregular nouns
77        "moose": "moose",
78        "mouse": "mice",
79        "ox":    "oxen",
80        "sheep": "sheep",
81        "foot":  "feet",
82        "tooth": "teeth",
83        "man":   "men",
84        "woman": "women",
85        "child": "children",
86    }.get(noun, None)
87    if plural is not None:
88        return plural
89
90    sEnding = noun[-2:]
91    pEnding = {
92        "ss": "sses",   # moss     -> mosses
93        "zz": "zzes",   # ?
94        "sh": "shes",   # bush     -> bushes
95        "ch": "ches",   # branch   -> branches
96        "fe": "ves",    # knife    -> knives
97        "ff": "ffs",    # cliff    -> cliffs
98
99        "ay": "ays",    # <vowel>y -> <vowel>ys
100        "ey": "eys",    #
101        "iy": "iys",    #
102        "oy": "oys",    #
103        "uy": "uys",    #
104    }.get(sEnding, None)
105    if pEnding is not None:
106        return noun[:-2] + pEnding
107
108    sEnding = noun[-1]
109    pEnding = {
110        "y": "ies",     # family   -> families
111        "f": "ves",     # loaf     -> loaves
112    }.get(sEnding, None)
113    if pEnding is not None:
114        return noun[:-1] + pEnding
115
116    pEnding = {
117        "s": "",        # pants    -> pants
118        "x": "es",      # fox      -> foxes
119    }.get(sEnding, None)
120    if pEnding is not None:
121        return noun + pEnding
122
123    # Fallback case.
124    return noun +"s"
125
126pluralize = pluralise   # American <- English
127
128if __name__ == "__main__":    
129    import unittest
130
131    class NumberWordificationTests(unittest.TestCase):
132        def testLessThanOneHundred(self):
133            self.failUnlessEqual(number_to_words(0), "none")
134            self.failUnlessEqual(number_to_words(1), "one")
135            self.failUnlessEqual(number_to_words(5), "five")
136            self.failUnlessEqual(number_to_words(10), "ten")
137            self.failUnlessEqual(number_to_words(15), "fifteen")
138            self.failUnlessEqual(number_to_words(20), "twenty")
139            self.failUnlessEqual(number_to_words(21), "twenty one")
140            self.failUnlessEqual(number_to_words(50), "fifty")
141
142        def testHundreds(self):
143            self.failUnlessEqual(number_to_words(100), "one hundred")
144            self.failUnlessEqual(number_to_words(101), "one hundred and one")
145            self.failUnlessEqual(number_to_words(111), "one hundred and eleven")
146            self.failUnlessEqual(number_to_words(199), "one hundred and ninety nine")
147            self.failUnlessEqual(number_to_words(999), "nine hundred and ninety nine")
148
149        def testThousands(self):
150            self.failUnlessEqual(number_to_words(1000), "one thousand")
151            self.failUnlessEqual(number_to_words(1001), "one thousand and one")
152            self.failUnlessEqual(number_to_words(1099), "one thousand and ninety nine")
153            self.failUnlessEqual(number_to_words(1100), "one thousand, one hundred")
154            self.failUnlessEqual(number_to_words(1101), "one thousand, one hundred and one")
155            self.failUnlessEqual(number_to_words(11101), "eleven thousand, one hundred and one")
156            self.failUnlessEqual(number_to_words(100101), "one hundred thousand, one hundred and one")
157            self.failUnlessEqual(number_to_words(101101), "one hundred and one thousand, one hundred and one")
158            
159        def testMillions(self):
160            self.failUnlessEqual(number_to_words(1000000), "one million")
161            self.failUnlessEqual(number_to_words(1000001), "one million and one")
162            self.failUnlessEqual(number_to_words(1900000), "one million, nine hundred thousand")
163            self.failUnlessEqual(number_to_words(1900001), "one million, nine hundred thousand and one")
164
165    class PluralisationTests(unittest.TestCase):
166        def testSelectionOfCases(self):
167            # One of the irregular nouns.    
168            self.failUnlessEqual(pluralise("man"), "men")
169            # Something other cases.
170            self.failUnlessEqual(pluralise("moss"), "mosses")
171            self.failUnlessEqual(pluralise("cliff"), "cliffs")    
172            self.failUnlessEqual(pluralise("knife"), "knives")
173            self.failUnlessEqual(pluralise("boy"), "boys")
174            self.failUnlessEqual(pluralise("grey"), "greys")
175            self.failUnlessEqual(pluralise("gray"), "grays")
176            self.failUnlessEqual(pluralise("nappy"), "nappies")
177            self.failUnlessEqual(pluralise("pants"), "pants")
178            self.failUnlessEqual(pluralise("fox"), "foxes")
179            # The fallback case.
180            self.failUnlessEqual(pluralise("chest"), "chests")
181
182    unittest.main()
183
Full Screen

filters.py

Source: filters.py Github

copy
1import validators
2
3from application.filter.raw_template import get_jinja_template_raw
4from application.filter.organisation_mapper import map_organisation_id_filter
5
6
7def slash_to_dash(text):
8    """
9    Given a string replace / with -
10    useful for making urls from strings with /s
11    e.g. 2020/06/04 becomes 2020-06-04
12    """
13    return text.replace("/", "-")
14
15
16def reduce_url_to_parent(url):
17	if url.count("/") > 1:
18		return url.rsplit('/',1)[0]
19	return url
20
21
22def commanum(v):
23    """
24    Returns readable number
25
26    For example, 1827942 => 1,827,942
27    """
28    return "{:,}".format(v)
29
30
31def float_to_int(v):
32    """
33    Returns integer from float
34    """
35    if v:
36        return int(float(v))
37    return None
38
39
40def is_valid_uri(uri):
41    """
42    Check whether uri is valid, useful for links
43    """
44    if validators.url(uri):
45        return True
46    return False
47
48
49def pluralise(str, count, str_on='s', str_off=""):
50    """
51    Return string with plural suffix if count is not 1.
52    By default use 's' as the suffix.
53
54    * If count is 0, vote{{ "resource"|pluralise(count) }} display "resources".
55    * If count is 1, vote{{ "resource"|pluralise(count) }} display "resource".
56    * If count is 2, vote{{ "resource"|pluralise(count) }} display "resources".
57
58    Can provide args to customise plural suffix
59
60    * If count is 0, vote{{ "country"|pluralise(count, "ies", "y") }} display "countries".
61    * If count is 1, vote{{ "country"|pluralise(count, "ies", "y") }} display "country".
62    * If count is 2, vote{{ "country"|pluralise(count, "ies", "y") }} display "countries".
63    """
64    if not count == 1:
65        strip_count = -1*len(str_off) if len(str_off) > 0 else len(str)
66        return str[:strip_count]+str_on
67    else:
68        return str
69
70
71###################
72# Heatmap         #
73###################
74
75def extract_day(date_str):
76    if date_str:
77        return int(date_str.split("-")[2])
78    return None
79
80
81def extract_month(date_str):
82    if date_str:
83        return date_str.split("-")[1]
84    return None
85
86
87def map_month(num):
88    month_map = {
89        "01": "Jan",
90        "02": "Feb",
91        "03": "Mar",
92        "04": "Apr",
93        "05": "May",
94        "06": "Jun",
95        "07": "Jul",
96        "08": "Aug",
97        "09": "Sep",
98        "10": "Oct",
99        "11": "Nov",
100        "12": "Dec",
101    }
102    if num and num in month_map.keys():
103        return month_map[num]
104    return None
105
Full Screen

__init__.py

Source: __init__.py Github

copy
1import os
2from datetime import datetime
3import math
4import string
5import random
6
7import inflect
8
9from flask import current_app
10from jinja2 import select_autoescape
11
12
13class ConsoleFormat:
14    Reset = "\033[0m"
15
16    Red = "\033[31m"
17    Yellow = "\033[33m"
18    Green = "\033[32m"
19    Blue = "\033[34m"
20    Magenta = "\033[35m"
21
22    Bold = "\033[1m"
23    Italic = "\033[3m"
24    Underline = "\033[4m"
25
26    Tab = "\t"
27    Newline = "\n"
28
29
30def enableAutoescape(app):
31    app.jinja_env.autoescape = select_autoescape(default_for_string=True, default=True)
32
33
34def pluralise(word, n):
35    if abs(n) != 1:
36        i = inflect.engine()
37        return i.plural(word)
38    else:
39        return word
40
41
42def timeAgo(then):
43    # FUTURE: switch from using seconds to proper timedelta attributes
44    now = datetime.utcnow()
45    diff = (now - then).total_seconds()
46
47    if diff < 60:
48        seconds = math.floor(diff)
49        return f"{ seconds } { pluralise('second', seconds) } ago"
50
51    elif diff < 3600:
52        minutes = math.floor(diff / 60)
53        return f"{ minutes } { pluralise('minute', minutes) } ago"
54
55    elif diff < 86400:
56        hours = math.floor(diff / 60 / 60)
57        return f"{ hours } { pluralise('hour', hours) } ago"
58
59    else:
60        days = math.floor(diff / 60 / 60 / 24)
61        return f"{ days } { pluralise('day', days) } ago"
62
63
64def getFileExtension(filename):
65    return filename.rsplit(".", 1)[1].lower()
66
67
68def randomKey(length):
69    numbers = string.digits
70    return "".join(random.choice(numbers) for x in range(length))
71
72
73def randomString(length):
74    letters = string.ascii_letters
75    return "".join(random.choice(letters) for x in range(length))
76
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Contexts on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)