id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
2,600
permissions.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/auth/tests/permissions.py
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.contrib.auth.management import create_permissions from django.contrib.auth import models as auth_models from django.contrib.contenttypes import models as contenttypes_models from django.core.management import call_command from django.test import TestCase class TestAuthPermissions(TestCase): def tearDown(self): # These tests mess with content types, but content type lookups # are cached, so we need to make sure the effects of this test # are cleaned up. contenttypes_models.ContentType.objects.clear_cache() def test_permission_register_order(self): """Test that the order of registered permissions doesn't break""" # Changeset 14413 introduced a regression in the ordering of # newly created permissions for objects. When loading a fixture # after the initial creation (such as during unit tests), the # expected IDs for the permissions may not match up, leading to # SQL errors. This is ticket 14731 # Start with a clean slate and build the permissions as we # expect to see them in the fixtures. auth_models.Permission.objects.all().delete() contenttypes_models.ContentType.objects.all().delete() create_permissions(auth_models, [], verbosity=0) create_permissions(contenttypes_models, [], verbosity=0) stderr = StringIO() call_command('loaddata', 'test_permissions.json', verbosity=0, commit=False, stderr=stderr) self.assertEqual(stderr.getvalue(), '')
1,654
Python
.py
32
44.59375
73
0.720916
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,601
decorators.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/auth/tests/decorators.py
from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.auth.tests.views import AuthViewsTestCase class LoginRequiredTestCase(AuthViewsTestCase): """ Tests the login_required decorators """ urls = 'django.contrib.auth.tests.urls' def testCallable(self): """ Check that login_required is assignable to callable objects. """ class CallableView(object): def __call__(self, *args, **kwargs): pass login_required(CallableView()) def testView(self): """ Check that login_required is assignable to normal views. """ def normal_view(request): pass login_required(normal_view) def testLoginRequired(self, view_url='/login_required/', login_url=settings.LOGIN_URL): """ Check that login_required works on a simple view wrapped in a login_required decorator. """ response = self.client.get(view_url) self.assertEqual(response.status_code, 302) self.assertTrue(login_url in response['Location']) self.login() response = self.client.get(view_url) self.assertEqual(response.status_code, 200) def testLoginRequiredNextUrl(self): """ Check that login_required works on a simple view wrapped in a login_required decorator with a login_url set. """ self.testLoginRequired(view_url='/login_required_login_url/', login_url='/somewhere/')
1,562
Python
.py
41
30.04878
91
0.653034
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,602
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/auth/tests/forms.py
from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, PasswordChangeForm, SetPasswordForm, UserChangeForm, PasswordResetForm from django.test import TestCase class UserCreationFormTest(TestCase): fixtures = ['authtestdata.json'] def test_user_already_exists(self): data = { 'username': 'testclient', 'password1': 'test123', 'password2': 'test123', } form = UserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form["username"].errors, [u'A user with that username already exists.']) def test_invalid_data(self): data = { 'username': 'jsmith!', 'password1': 'test123', 'password2': 'test123', } form = UserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form["username"].errors, [u'This value may contain only letters, numbers and @/./+/-/_ characters.']) def test_password_verification(self): # The verification password is incorrect. data = { 'username': 'jsmith', 'password1': 'test123', 'password2': 'test', } form = UserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form["password2"].errors, [u"The two password fields didn't match."]) def test_both_passwords(self): # One (or both) passwords weren't given data = {'username': 'jsmith'} form = UserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form['password1'].errors, [u'This field is required.']) self.assertEqual(form['password2'].errors, [u'This field is required.']) data['password2'] = 'test123' form = UserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form['password1'].errors, [u'This field is required.']) def test_success(self): # The success case. data = { 'username': '[email protected]', 'password1': 'test123', 'password2': 'test123', } form = UserCreationForm(data) self.assertTrue(form.is_valid()) u = form.save() self.assertEqual(repr(u), '<User: [email protected]>') class AuthenticationFormTest(TestCase): fixtures = ['authtestdata.json'] def test_invalid_username(self): # The user submits an invalid username. data = { 'username': 'jsmith_does_not_exist', 'password': 'test123', } form = AuthenticationForm(None, data) self.assertFalse(form.is_valid()) self.assertEqual(form.non_field_errors(), [u'Please enter a correct username and password. Note that both fields are case-sensitive.']) def test_inactive_user(self): # The user is inactive. data = { 'username': 'inactive', 'password': 'password', } form = AuthenticationForm(None, data) self.assertFalse(form.is_valid()) self.assertEqual(form.non_field_errors(), [u'This account is inactive.']) def test_success(self): # The success case data = { 'username': 'testclient', 'password': 'password', } form = AuthenticationForm(None, data) self.assertTrue(form.is_valid()) self.assertEqual(form.non_field_errors(), []) class SetPasswordFormTest(TestCase): fixtures = ['authtestdata.json'] def test_password_verification(self): # The two new passwords do not match. user = User.objects.get(username='testclient') data = { 'new_password1': 'abc123', 'new_password2': 'abc', } form = SetPasswordForm(user, data) self.assertFalse(form.is_valid()) self.assertEqual(form["new_password2"].errors, [u"The two password fields didn't match."]) def test_success(self): user = User.objects.get(username='testclient') data = { 'new_password1': 'abc123', 'new_password2': 'abc123', } form = SetPasswordForm(user, data) self.assertTrue(form.is_valid()) class PasswordChangeFormTest(TestCase): fixtures = ['authtestdata.json'] def test_incorrect_password(self): user = User.objects.get(username='testclient') data = { 'old_password': 'test', 'new_password1': 'abc123', 'new_password2': 'abc123', } form = PasswordChangeForm(user, data) self.assertFalse(form.is_valid()) self.assertEqual(form["old_password"].errors, [u'Your old password was entered incorrectly. Please enter it again.']) def test_password_verification(self): # The two new passwords do not match. user = User.objects.get(username='testclient') data = { 'old_password': 'password', 'new_password1': 'abc123', 'new_password2': 'abc', } form = PasswordChangeForm(user, data) self.assertFalse(form.is_valid()) self.assertEqual(form["new_password2"].errors, [u"The two password fields didn't match."]) def test_success(self): # The success case. user = User.objects.get(username='testclient') data = { 'old_password': 'password', 'new_password1': 'abc123', 'new_password2': 'abc123', } form = PasswordChangeForm(user, data) self.assertTrue(form.is_valid()) def test_field_order(self): # Regression test - check the order of fields: user = User.objects.get(username='testclient') self.assertEqual(PasswordChangeForm(user, {}).fields.keys(), ['old_password', 'new_password1', 'new_password2']) class UserChangeFormTest(TestCase): fixtures = ['authtestdata.json'] def test_username_validity(self): user = User.objects.get(username='testclient') data = {'username': 'not valid'} form = UserChangeForm(data, instance=user) self.assertFalse(form.is_valid()) self.assertEqual(form['username'].errors, [u'This value may contain only letters, numbers and @/./+/-/_ characters.']) def test_bug_14242(self): # A regression test, introduce by adding an optimization for the # UserChangeForm. class MyUserForm(UserChangeForm): def __init__(self, *args, **kwargs): super(MyUserForm, self).__init__(*args, **kwargs) self.fields['groups'].help_text = 'These groups give users different permissions' class Meta(UserChangeForm.Meta): fields = ('groups',) # Just check we can create it form = MyUserForm({}) class PasswordResetFormTest(TestCase): fixtures = ['authtestdata.json'] def create_dummy_user(self): """creates a user and returns a tuple (user_object, username, email) """ username = 'jsmith' email = '[email protected]' user = User.objects.create_user(username, email, 'test123') return (user, username, email) def test_invalid_email(self): data = {'email':'not valid'} form = PasswordResetForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form['email'].errors, [u'Enter a valid e-mail address.']) def test_nonexistant_email(self): # Test nonexistant email address data = {'email':'[email protected]'} form = PasswordResetForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {'email': [u"That e-mail address doesn't have an associated user account. Are you sure you've registered?"]}) def test_cleaned_data(self): # Regression test (user, username, email) = self.create_dummy_user() data = {'email': email} form = PasswordResetForm(data) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['email'], email) def test_bug_5605(self): # bug #5605, preserve the case of the user name (before the @ in the # email address) when creating a user. user = User.objects.create_user('forms_test2', '[email protected]', 'test') self.assertEqual(user.email, '[email protected]') user = User.objects.create_user('forms_test3', 'tesT', 'test') self.assertEqual(user.email, 'tesT') def test_inactive_user(self): #tests that inactive user cannot #receive password reset email (user, username, email) = self.create_dummy_user() user.is_active = False user.save() form = PasswordResetForm({'email': email}) self.assertFalse(form.is_valid())
9,283
Python
.py
218
32.082569
147
0.591368
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,603
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/auth/tests/views.py
import os import re import urllib from django.conf import settings from django.contrib.auth import SESSION_KEY, REDIRECT_FIELD_NAME from django.contrib.auth.forms import AuthenticationForm from django.contrib.sites.models import Site, RequestSite from django.contrib.auth.models import User from django.test import TestCase from django.core import mail from django.core.urlresolvers import reverse from django.http import QueryDict class AuthViewsTestCase(TestCase): """ Helper base class for all the follow test cases. """ fixtures = ['authtestdata.json'] urls = 'django.contrib.auth.tests.urls' def setUp(self): self.old_LANGUAGES = settings.LANGUAGES self.old_LANGUAGE_CODE = settings.LANGUAGE_CODE settings.LANGUAGES = (('en', 'English'),) settings.LANGUAGE_CODE = 'en' self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS settings.TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), ) def tearDown(self): settings.LANGUAGES = self.old_LANGUAGES settings.LANGUAGE_CODE = self.old_LANGUAGE_CODE settings.TEMPLATE_DIRS = self.old_TEMPLATE_DIRS def login(self, password='password'): response = self.client.post('/login/', { 'username': 'testclient', 'password': password } ) self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith(settings.LOGIN_REDIRECT_URL)) self.assertTrue(SESSION_KEY in self.client.session) class PasswordResetTest(AuthViewsTestCase): def test_email_not_found(self): "Error is raised if the provided email address isn't currently registered" response = self.client.get('/password_reset/') self.assertEqual(response.status_code, 200) response = self.client.post('/password_reset/', {'email': '[email protected]'}) self.assertContains(response, "That e-mail address doesn&#39;t have an associated user account") self.assertEqual(len(mail.outbox), 0) def test_email_found(self): "Email is sent if a valid email address is provided for password reset" response = self.client.post('/password_reset/', {'email': '[email protected]'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertTrue("http://" in mail.outbox[0].body) self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email) def test_email_found_custom_from(self): "Email is sent if a valid email address is provided for password reset when a custom from_email is provided." response = self.client.post('/password_reset_from_email/', {'email': '[email protected]'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertEqual("[email protected]", mail.outbox[0].from_email) def _test_confirm_start(self): # Start by creating the email response = self.client.post('/password_reset/', {'email': '[email protected]'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) return self._read_signup_email(mail.outbox[0]) def _read_signup_email(self, email): urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body) self.assertTrue(urlmatch is not None, "No URL found in sent email") return urlmatch.group(), urlmatch.groups()[0] def test_confirm_valid(self): url, path = self._test_confirm_start() response = self.client.get(path) # redirect to a 'complete' page: self.assertEqual(response.status_code, 200) self.assertTrue("Please enter your new password" in response.content) def test_confirm_invalid(self): url, path = self._test_confirm_start() # Let's munge the token in the path, but keep the same length, # in case the URLconf will reject a different length. path = path[:-5] + ("0"*4) + path[-1] response = self.client.get(path) self.assertEqual(response.status_code, 200) self.assertTrue("The password reset link was invalid" in response.content) def test_confirm_invalid_user(self): # Ensure that we get a 200 response for a non-existant user, not a 404 response = self.client.get('/reset/123456-1-1/') self.assertEqual(response.status_code, 200) self.assertTrue("The password reset link was invalid" in response.content) def test_confirm_overflow_user(self): # Ensure that we get a 200 response for a base36 user id that overflows int response = self.client.get('/reset/zzzzzzzzzzzzz-1-1/') self.assertEqual(response.status_code, 200) self.assertTrue("The password reset link was invalid" in response.content) def test_confirm_invalid_post(self): # Same as test_confirm_invalid, but trying # to do a POST instead. url, path = self._test_confirm_start() path = path[:-5] + ("0"*4) + path[-1] response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2':' anewpassword'}) # Check the password has not been changed u = User.objects.get(email='[email protected]') self.assertTrue(not u.check_password("anewpassword")) def test_confirm_complete(self): url, path = self._test_confirm_start() response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'}) # It redirects us to a 'complete' page: self.assertEqual(response.status_code, 302) # Check the password has been changed u = User.objects.get(email='[email protected]') self.assertTrue(u.check_password("anewpassword")) # Check we can't use the link again response = self.client.get(path) self.assertEqual(response.status_code, 200) self.assertTrue("The password reset link was invalid" in response.content) def test_confirm_different_passwords(self): url, path = self._test_confirm_start() response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2':' x'}) self.assertEqual(response.status_code, 200) self.assertTrue("The two password fields didn&#39;t match" in response.content) class ChangePasswordTest(AuthViewsTestCase): def fail_login(self, password='password'): response = self.client.post('/login/', { 'username': 'testclient', 'password': password } ) self.assertEqual(response.status_code, 200) self.assertTrue("Please enter a correct username and password. Note that both fields are case-sensitive." in response.content) def logout(self): response = self.client.get('/logout/') def test_password_change_fails_with_invalid_old_password(self): self.login() response = self.client.post('/password_change/', { 'old_password': 'donuts', 'new_password1': 'password1', 'new_password2': 'password1', } ) self.assertEqual(response.status_code, 200) self.assertTrue("Your old password was entered incorrectly. Please enter it again." in response.content) def test_password_change_fails_with_mismatched_passwords(self): self.login() response = self.client.post('/password_change/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'donuts', } ) self.assertEqual(response.status_code, 200) self.assertTrue("The two password fields didn&#39;t match." in response.content) def test_password_change_succeeds(self): self.login() response = self.client.post('/password_change/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'password1', } ) self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith('/password_change/done/')) self.fail_login() self.login(password='password1') class LoginTest(AuthViewsTestCase): def test_current_site_in_context_after_login(self): response = self.client.get(reverse('django.contrib.auth.views.login')) self.assertEqual(response.status_code, 200) if Site._meta.installed: site = Site.objects.get_current() self.assertEqual(response.context['site'], site) self.assertEqual(response.context['site_name'], site.name) else: self.assertIsInstance(response.context['site'], RequestSite) self.assertTrue(isinstance(response.context['form'], AuthenticationForm), 'Login form is not an AuthenticationForm') def test_security_check(self, password='password'): login_url = reverse('django.contrib.auth.views.login') # Those URLs should not pass the security check for bad_url in ('http://example.com', 'https://example.com', 'ftp://exampel.com', '//example.com'): nasty_url = '%(url)s?%(next)s=%(bad_url)s' % { 'url': login_url, 'next': REDIRECT_FIELD_NAME, 'bad_url': urllib.quote(bad_url) } response = self.client.post(nasty_url, { 'username': 'testclient', 'password': password, } ) self.assertEqual(response.status_code, 302) self.assertFalse(bad_url in response['Location'], "%s should be blocked" % bad_url) # These URLs *should* still pass the security check for good_url in ('/view/?param=http://example.com', '/view/?param=https://example.com', '/view?param=ftp://exampel.com', 'view/?param=//example.com', 'https:///', '//testserver/', '/url%20with%20spaces/', # see ticket #12534 ): safe_url = '%(url)s?%(next)s=%(good_url)s' % { 'url': login_url, 'next': REDIRECT_FIELD_NAME, 'good_url': urllib.quote(good_url) } response = self.client.post(safe_url, { 'username': 'testclient', 'password': password, } ) self.assertEqual(response.status_code, 302) self.assertTrue(good_url in response['Location'], "%s should be allowed" % good_url) class LoginURLSettings(AuthViewsTestCase): urls = 'django.contrib.auth.tests.urls' def setUp(self): super(LoginURLSettings, self).setUp() self.old_LOGIN_URL = settings.LOGIN_URL def tearDown(self): super(LoginURLSettings, self).tearDown() settings.LOGIN_URL = self.old_LOGIN_URL def get_login_required_url(self, login_url): settings.LOGIN_URL = login_url response = self.client.get('/login_required/') self.assertEqual(response.status_code, 302) return response['Location'] def test_standard_login_url(self): login_url = '/login/' login_required_url = self.get_login_required_url(login_url) querystring = QueryDict('', mutable=True) querystring['next'] = '/login_required/' self.assertEqual(login_required_url, 'http://testserver%s?%s' % (login_url, querystring.urlencode('/'))) def test_remote_login_url(self): login_url = 'http://remote.example.com/login' login_required_url = self.get_login_required_url(login_url) querystring = QueryDict('', mutable=True) querystring['next'] = 'http://testserver/login_required/' self.assertEqual(login_required_url, '%s?%s' % (login_url, querystring.urlencode('/'))) def test_https_login_url(self): login_url = 'https:///login/' login_required_url = self.get_login_required_url(login_url) querystring = QueryDict('', mutable=True) querystring['next'] = 'http://testserver/login_required/' self.assertEqual(login_required_url, '%s?%s' % (login_url, querystring.urlencode('/'))) def test_login_url_with_querystring(self): login_url = '/login/?pretty=1' login_required_url = self.get_login_required_url(login_url) querystring = QueryDict('pretty=1', mutable=True) querystring['next'] = '/login_required/' self.assertEqual(login_required_url, 'http://testserver/login/?%s' % querystring.urlencode('/')) def test_remote_login_url_with_next_querystring(self): login_url = 'http://remote.example.com/login/' login_required_url = self.get_login_required_url('%s?next=/default/' % login_url) querystring = QueryDict('', mutable=True) querystring['next'] = 'http://testserver/login_required/' self.assertEqual(login_required_url, '%s?%s' % (login_url, querystring.urlencode('/'))) class LogoutTest(AuthViewsTestCase): urls = 'django.contrib.auth.tests.urls' def confirm_logged_out(self): self.assertTrue(SESSION_KEY not in self.client.session) def test_logout_default(self): "Logout without next_page option renders the default template" self.login() response = self.client.get('/logout/') self.assertEqual(200, response.status_code) self.assertTrue('Logged out' in response.content) self.confirm_logged_out() def test_14377(self): # Bug 14377 self.login() response = self.client.get('/logout/') self.assertTrue('site' in response.context) def test_logout_with_overridden_redirect_url(self): # Bug 11223 self.login() response = self.client.get('/logout/next_page/') self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith('/somewhere/')) response = self.client.get('/logout/next_page/?next=/login/') self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith('/login/')) self.confirm_logged_out() def test_logout_with_next_page_specified(self): "Logout with next_page option given redirects to specified resource" self.login() response = self.client.get('/logout/next_page/') self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith('/somewhere/')) self.confirm_logged_out() def test_logout_with_redirect_argument(self): "Logout with query string redirects to specified resource" self.login() response = self.client.get('/logout/?next=/login/') self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith('/login/')) self.confirm_logged_out() def test_logout_with_custom_redirect_argument(self): "Logout with custom query string redirects to specified resource" self.login() response = self.client.get('/logout/custom_query/?follow=/somewhere/') self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith('/somewhere/')) self.confirm_logged_out() def test_security_check(self, password='password'): logout_url = reverse('django.contrib.auth.views.logout') # Those URLs should not pass the security check for bad_url in ('http://example.com', 'https://example.com', 'ftp://exampel.com', '//example.com' ): nasty_url = '%(url)s?%(next)s=%(bad_url)s' % { 'url': logout_url, 'next': REDIRECT_FIELD_NAME, 'bad_url': urllib.quote(bad_url) } self.login() response = self.client.get(nasty_url) self.assertEqual(response.status_code, 302) self.assertFalse(bad_url in response['Location'], "%s should be blocked" % bad_url) self.confirm_logged_out() # These URLs *should* still pass the security check for good_url in ('/view/?param=http://example.com', '/view/?param=https://example.com', '/view?param=ftp://exampel.com', 'view/?param=//example.com', 'https:///', '//testserver/', '/url%20with%20spaces/', # see ticket #12534 ): safe_url = '%(url)s?%(next)s=%(good_url)s' % { 'url': logout_url, 'next': REDIRECT_FIELD_NAME, 'good_url': urllib.quote(good_url) } self.login() response = self.client.get(safe_url) self.assertEqual(response.status_code, 302) self.assertTrue(good_url in response['Location'], "%s should be allowed" % good_url) self.confirm_logged_out()
17,770
Python
.py
356
38.724719
134
0.610244
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,604
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/auth/management/__init__.py
""" Creates permissions for all installed apps that need permissions. """ from django.contrib.auth import models as auth_app from django.db.models import get_models, signals def _get_permission_codename(action, opts): return u'%s_%s' % (action, opts.object_name.lower()) def _get_all_permissions(opts): "Returns (codename, name) for all permissions in the given opts." perms = [] for action in ('add', 'change', 'delete'): perms.append((_get_permission_codename(action, opts), u'Can %s %s' % (action, opts.verbose_name_raw))) return perms + list(opts.permissions) def create_permissions(app, created_models, verbosity, **kwargs): from django.contrib.contenttypes.models import ContentType app_models = get_models(app) # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for klass in app_models: ctype = ContentType.objects.get_for_model(klass) ctypes.add(ctype) for perm in _get_all_permissions(klass._meta): searched_perms.append((ctype, perm)) # Find all the Permissions that have a context_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set(auth_app.Permission.objects.filter( content_type__in=ctypes, ).values_list( "content_type", "codename" )) for ctype, (codename, name) in searched_perms: # If the permissions exists, move on. if (ctype.pk, codename) in all_perms: continue p = auth_app.Permission.objects.create( codename=codename, name=name, content_type=ctype ) if verbosity >= 2: print "Adding permission '%s'" % p def create_superuser(app, created_models, verbosity, **kwargs): from django.core.management import call_command if auth_app.User in created_models and kwargs.get('interactive', True): msg = ("\nYou just installed Django's auth system, which means you " "don't have any superusers defined.\nWould you like to create one " "now? (yes/no): ") confirm = raw_input(msg) while 1: if confirm not in ('yes', 'no'): confirm = raw_input('Please enter either "yes" or "no": ') continue if confirm == 'yes': call_command("createsuperuser", interactive=True) break signals.post_syncdb.connect(create_permissions, dispatch_uid = "django.contrib.auth.management.create_permissions") signals.post_syncdb.connect(create_superuser, sender=auth_app, dispatch_uid = "django.contrib.auth.management.create_superuser")
2,854
Python
.py
63
37.936508
110
0.661627
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,605
changepassword.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/auth/management/commands/changepassword.py
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User import getpass class Command(BaseCommand): help = "Change a user's password for django.contrib.auth." requires_model_validation = False def _get_pass(self, prompt="Password: "): p = getpass.getpass(prompt=prompt) if not p: raise CommandError("aborted") return p def handle(self, *args, **options): if len(args) > 1: raise CommandError("need exactly one or zero arguments for username") if args: username, = args else: username = getpass.getuser() try: u = User.objects.get(username=username) except User.DoesNotExist: raise CommandError("user '%s' does not exist" % username) print "Changing password for user '%s'" % u.username MAX_TRIES = 3 count = 0 p1, p2 = 1, 2 # To make them initially mismatch. while p1 != p2 and count < MAX_TRIES: p1 = self._get_pass() p2 = self._get_pass("Password (again): ") if p1 != p2: print "Passwords do not match. Please try again." count = count + 1 if count == MAX_TRIES: raise CommandError("Aborting password change for user '%s' after %s attempts" % (username, count)) u.set_password(p1) u.save() return "Password changed successfully for user '%s'" % u.username
1,527
Python
.py
37
31.756757
110
0.601758
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,606
createsuperuser.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/auth/management/commands/createsuperuser.py
""" Management utility to create superusers. """ import getpass import re import sys from optparse import make_option from django.contrib.auth.models import User from django.core import exceptions from django.core.management.base import BaseCommand, CommandError from django.utils.translation import ugettext as _ RE_VALID_USERNAME = re.compile('[\w.@+-]+$') EMAIL_RE = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"' # quoted-string r')@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$', re.IGNORECASE) # domain def is_valid_email(value): if not EMAIL_RE.search(value): raise exceptions.ValidationError(_('Enter a valid e-mail address.')) class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--username', dest='username', default=None, help='Specifies the username for the superuser.'), make_option('--email', dest='email', default=None, help='Specifies the email address for the superuser.'), make_option('--noinput', action='store_false', dest='interactive', default=True, help=('Tells Django to NOT prompt the user for input of any kind. ' 'You must use --username and --email with --noinput, and ' 'superusers created with --noinput will not be able to log ' 'in until they\'re given a valid password.')), ) help = 'Used to create a superuser.' def handle(self, *args, **options): username = options.get('username', None) email = options.get('email', None) interactive = options.get('interactive') verbosity = int(options.get('verbosity', 1)) # Do quick and dirty validation if --noinput if not interactive: if not username or not email: raise CommandError("You must use --username and --email with --noinput.") if not RE_VALID_USERNAME.match(username): raise CommandError("Invalid username. Use only letters, digits, and underscores") try: is_valid_email(email) except exceptions.ValidationError: raise CommandError("Invalid email address.") # If not provided, create the user with an unusable password password = None # Try to determine the current system user's username to use as a default. try: default_username = getpass.getuser().replace(' ', '').lower() except (ImportError, KeyError): # KeyError will be raised by os.getpwuid() (called by getuser()) # if there is no corresponding entry in the /etc/passwd file # (a very restricted chroot environment, for example). default_username = '' # Determine whether the default username is taken, so we don't display # it as an option. if default_username: try: User.objects.get(username=default_username) except User.DoesNotExist: pass else: default_username = '' # Prompt for username/email/password. Enclose this whole thing in a # try/except to trap for a keyboard interrupt and exit gracefully. if interactive: try: # Get a username while 1: if not username: input_msg = 'Username' if default_username: input_msg += ' (Leave blank to use %r)' % default_username username = raw_input(input_msg + ': ') if default_username and username == '': username = default_username if not RE_VALID_USERNAME.match(username): sys.stderr.write("Error: That username is invalid. Use only letters, digits and underscores.\n") username = None continue try: User.objects.get(username=username) except User.DoesNotExist: break else: sys.stderr.write("Error: That username is already taken.\n") username = None # Get an email while 1: if not email: email = raw_input('E-mail address: ') try: is_valid_email(email) except exceptions.ValidationError: sys.stderr.write("Error: That e-mail address is invalid.\n") email = None else: break # Get a password while 1: if not password: password = getpass.getpass() password2 = getpass.getpass('Password (again): ') if password != password2: sys.stderr.write("Error: Your passwords didn't match.\n") password = None continue if password.strip() == '': sys.stderr.write("Error: Blank passwords aren't allowed.\n") password = None continue break except KeyboardInterrupt: sys.stderr.write("\nOperation cancelled.\n") sys.exit(1) User.objects.create_superuser(username, email, password) if verbosity >= 1: self.stdout.write("Superuser created successfully.\n")
5,814
Python
.py
121
33.495868
120
0.539017
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,607
ca_provinces.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/ca/ca_provinces.py
""" An alphabetical list of provinces and territories for use as `choices` in a formfield., and a mapping of province misspellings/abbreviations to normalized abbreviations Source: http://www.canada.gc.ca/othergov/prov_e.html This exists in this standalone file so that it's only imported into memory when explicitly needed. """ import warnings warnings.warn( 'There have been recent changes to the CA localflavor. See the release notes for details', RuntimeWarning ) PROVINCE_CHOICES = ( ('AB', 'Alberta'), ('BC', 'British Columbia'), ('MB', 'Manitoba'), ('NB', 'New Brunswick'), ('NL', 'Newfoundland and Labrador'), ('NT', 'Northwest Territories'), ('NS', 'Nova Scotia'), ('NU', 'Nunavut'), ('ON', 'Ontario'), ('PE', 'Prince Edward Island'), ('QC', 'Quebec'), ('SK', 'Saskatchewan'), ('YT', 'Yukon') ) PROVINCES_NORMALIZED = { 'ab': 'AB', 'alberta': 'AB', 'bc': 'BC', 'b.c.': 'BC', 'british columbia': 'BC', 'mb': 'MB', 'manitoba': 'MB', 'nb': 'NB', 'new brunswick': 'NB', 'nf': 'NL', 'nl': 'NL', 'newfoundland': 'NL', 'newfoundland and labrador': 'NL', 'nt': 'NT', 'northwest territories': 'NT', 'ns': 'NS', 'nova scotia': 'NS', 'nu': 'NU', 'nunavut': 'NU', 'on': 'ON', 'ontario': 'ON', 'pe': 'PE', 'pei': 'PE', 'p.e.i.': 'PE', 'prince edward island': 'PE', 'qc': 'QC', 'quebec': 'QC', 'sk': 'SK', 'saskatchewan': 'SK', 'yk': 'YT', 'yt': 'YT', 'yukon': 'YT', 'yukon territory': 'YT', }
1,603
Python
.py
63
21.047619
94
0.562134
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,608
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/ca/forms.py
""" Canada-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re phone_digits_re = re.compile(r'^(?:1-?)?(\d{3})[-\.]?(\d{3})[-\.]?(\d{4})$') sin_re = re.compile(r"^(\d{3})-(\d{3})-(\d{3})$") class CAPostalCodeField(RegexField): """ Canadian postal code field. Validates against known invalid characters: D, F, I, O, Q, U Additionally the first character cannot be Z or W. For more info see: http://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp#1402170 """ default_error_messages = { 'invalid': _(u'Enter a postal code in the format XXX XXX.'), } def __init__(self, *args, **kwargs): super(CAPostalCodeField, self).__init__(r'^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ] \d[ABCEGHJKLMNPRSTVWXYZ]\d$', max_length=None, min_length=None, *args, **kwargs) class CAPhoneNumberField(Field): """Canadian phone number field.""" default_error_messages = { 'invalid': u'Phone numbers must be in XXX-XXX-XXXX format.', } def clean(self, value): """Validate a phone number. """ super(CAPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\(|\)|\s+)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3)) raise ValidationError(self.error_messages['invalid']) class CAProvinceField(Field): """ A form field that validates its input is a Canadian province name or abbreviation. It normalizes the input to the standard two-leter postal service abbreviation for the given province. """ default_error_messages = { 'invalid': u'Enter a Canadian province or territory.', } def clean(self, value): from ca_provinces import PROVINCES_NORMALIZED super(CAProvinceField, self).clean(value) if value in EMPTY_VALUES: return u'' try: value = value.strip().lower() except AttributeError: pass else: try: return PROVINCES_NORMALIZED[value.strip().lower()].decode('ascii') except KeyError: pass raise ValidationError(self.error_messages['invalid']) class CAProvinceSelect(Select): """ A Select widget that uses a list of Canadian provinces and territories as its choices. """ def __init__(self, attrs=None): from ca_provinces import PROVINCE_CHOICES # relative import super(CAProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES) class CASocialInsuranceNumberField(Field): """ A Canadian Social Insurance Number (SIN). Checks the following rules to determine whether the number is valid: * Conforms to the XXX-XXX-XXX format. * Passes the check digit process "Luhn Algorithm" See: http://en.wikipedia.org/wiki/Social_Insurance_Number """ default_error_messages = { 'invalid': _('Enter a valid Canadian Social Insurance number in XXX-XXX-XXX format.'), } def clean(self, value): super(CASocialInsuranceNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' match = re.match(sin_re, value) if not match: raise ValidationError(self.error_messages['invalid']) number = u'%s-%s-%s' % (match.group(1), match.group(2), match.group(3)) check_number = u'%s%s%s' % (match.group(1), match.group(2), match.group(3)) if not self.luhn_checksum_is_valid(check_number): raise ValidationError(self.error_messages['invalid']) return number def luhn_checksum_is_valid(self, number): """ Checks to make sure that the SIN passes a luhn mod-10 checksum See: http://en.wikipedia.org/wiki/Luhn_algorithm """ sum = 0 num_digits = len(number) oddeven = num_digits & 1 for count in range(0, num_digits): digit = int(number[count]) if not (( count & 1 ) ^ oddeven ): digit = digit * 2 if digit > 9: digit = digit - 9 sum = sum + digit return ( (sum % 10) == 0 )
4,523
Python
.py
112
32.714286
125
0.628845
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,609
util.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/uy/util.py
# -*- coding: utf-8 -*- def get_validation_digit(number): """ Calculates the validation digit for the given number. """ sum = 0 dvs = [4, 3, 6, 7, 8, 9, 2] number = str(number) for i in range(0, len(number)): sum = (int(number[-1 - i]) * dvs[i] + sum) % 10 return (10-sum) % 10
313
Python
.py
9
29.888889
65
0.55814
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,610
uy_departaments.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/uy/uy_departaments.py
# -*- coding: utf-8 -*- """A list of Urguayan departaments as `choices` in a formfield.""" DEPARTAMENT_CHOICES = ( ('G', u'Artigas'), ('A', u'Canelones'), ('E', u'Cerro Largo'), ('L', u'Colonia'), ('Q', u'Durazno'), ('N', u'Flores'), ('O', u'Florida'), ('P', u'Lavalleja'), ('B', u'Maldonado'), ('S', u'Montevideo'), ('I', u'Paysandú'), ('J', u'Río Negro'), ('F', u'Rivera'), ('C', u'Rocha'), ('H', u'Salto'), ('M', u'San José'), ('K', u'Soriano'), ('R', u'Tacuarembó'), ('D', u'Treinta y Tres'), )
580
Python
.py
23
20.695652
66
0.476449
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,611
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/uy/forms.py
# -*- coding: utf-8 -*- """ UY-specific form helpers. """ import re from django.core.validators import EMPTY_VALUES from django.forms.fields import Select, RegexField from django.forms import ValidationError from django.utils.translation import ugettext_lazy as _ from django.contrib.localflavor.uy.util import get_validation_digit class UYDepartamentSelect(Select): """ A Select widget that uses a list of Uruguayan departaments as its choices. """ def __init__(self, attrs=None): from uy_departaments import DEPARTAMENT_CHOICES super(UYDepartamentSelect, self).__init__(attrs, choices=DEPARTAMENT_CHOICES) class UYCIField(RegexField): """ A field that validates Uruguayan 'Cedula de identidad' (CI) numbers. """ default_error_messages = { 'invalid': _("Enter a valid CI number in X.XXX.XXX-X," "XXXXXXX-X or XXXXXXXX format."), 'invalid_validation_digit': _("Enter a valid CI number."), } def __init__(self, *args, **kwargs): super(UYCIField, self).__init__(r'(?P<num>(\d{6,7}|(\d\.)?\d{3}\.\d{3}))-?(?P<val>\d)', *args, **kwargs) def clean(self, value): """ Validates format and validation digit. The official format is [X.]XXX.XXX-X but usually dots and/or slash are omitted so, when validating, those characters are ignored if found in the correct place. The three typically used formats are supported: [X]XXXXXXX, [X]XXXXXX-X and [X.]XXX.XXX-X. """ value = super(UYCIField, self).clean(value) if value in EMPTY_VALUES: return u'' match = self.regex.match(value) if not match: raise ValidationError(self.error_messages['invalid']) number = int(match.group('num').replace('.', '')) validation_digit = int(match.group('val')) if not validation_digit == get_validation_digit(number): raise ValidationError(self.error_messages['invalid_validation_digit']) return value
2,083
Python
.py
48
35.875
95
0.644093
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,612
ch_states.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/ch/ch_states.py
# -*- coding: utf-8 -* from django.utils.translation import ugettext_lazy as _ STATE_CHOICES = ( ('AG', _('Aargau')), ('AI', _('Appenzell Innerrhoden')), ('AR', _('Appenzell Ausserrhoden')), ('BS', _('Basel-Stadt')), ('BL', _('Basel-Land')), ('BE', _('Berne')), ('FR', _('Fribourg')), ('GE', _('Geneva')), ('GL', _('Glarus')), ('GR', _('Graubuenden')), ('JU', _('Jura')), ('LU', _('Lucerne')), ('NE', _('Neuchatel')), ('NW', _('Nidwalden')), ('OW', _('Obwalden')), ('SH', _('Schaffhausen')), ('SZ', _('Schwyz')), ('SO', _('Solothurn')), ('SG', _('St. Gallen')), ('TG', _('Thurgau')), ('TI', _('Ticino')), ('UR', _('Uri')), ('VS', _('Valais')), ('VD', _('Vaud')), ('ZG', _('Zug')), ('ZH', _('Zurich')) )
808
Python
.py
30
22.433333
55
0.423423
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,613
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/ch/forms.py
""" Swiss-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re id_re = re.compile(r"^(?P<idnumber>\w{8})(?P<pos9>(\d{1}|<))(?P<checksum>\d{1})$") phone_digits_re = re.compile(r'^0([1-9]{1})\d{8}$') class CHZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a zip code in the format XXXX.'), } def __init__(self, *args, **kwargs): super(CHZipCodeField, self).__init__(r'^\d{4}$', max_length=None, min_length=None, *args, **kwargs) class CHPhoneNumberField(Field): """ Validate local Swiss phone number (not international ones) The correct format is '0XX XXX XX XX'. '0XX.XXX.XX.XX' and '0XXXXXXXXX' validate but are corrected to '0XX XXX XX XX'. """ default_error_messages = { 'invalid': 'Phone numbers must be in 0XX XXX XX XX format.', } def clean(self, value): super(CHPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\.|\s|/|-)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: return u'%s %s %s %s' % (value[0:3], value[3:6], value[6:8], value[8:10]) raise ValidationError(self.error_messages['invalid']) class CHStateSelect(Select): """ A Select widget that uses a list of CH states as its choices. """ def __init__(self, attrs=None): from ch_states import STATE_CHOICES # relative import super(CHStateSelect, self).__init__(attrs, choices=STATE_CHOICES) class CHIdentityCardNumberField(Field): """ A Swiss identity card number. Checks the following rules to determine whether the number is valid: * Conforms to the X1234567<0 or 1234567890 format. * Included checksums match calculated checksums Algorithm is documented at http://adi.kousz.ch/artikel/IDCHE.htm """ default_error_messages = { 'invalid': _('Enter a valid Swiss identity or passport card number in X1234567<0 or 1234567890 format.'), } def has_valid_checksum(self, number): given_number, given_checksum = number[:-1], number[-1] new_number = given_number calculated_checksum = 0 fragment = "" parameter = 7 first = str(number[:1]) if first.isalpha(): num = ord(first.upper()) - 65 if num < 0 or num > 8: return False new_number = str(num) + new_number[1:] new_number = new_number[:8] + '0' if not new_number.isdigit(): return False for i in range(len(new_number)): fragment = int(new_number[i])*parameter calculated_checksum += fragment if parameter == 1: parameter = 7 elif parameter == 3: parameter = 1 elif parameter ==7: parameter = 3 return str(calculated_checksum)[-1] == given_checksum def clean(self, value): super(CHIdentityCardNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' match = re.match(id_re, value) if not match: raise ValidationError(self.error_messages['invalid']) idnumber, pos9, checksum = match.groupdict()['idnumber'], match.groupdict()['pos9'], match.groupdict()['checksum'] if idnumber == '00000000' or \ idnumber == 'A0000000': raise ValidationError(self.error_messages['invalid']) all_digits = "%s%s%s" % (idnumber, pos9, checksum) if not self.has_valid_checksum(all_digits): raise ValidationError(self.error_messages['invalid']) return u'%s%s%s' % (idnumber, pos9, checksum)
3,951
Python
.py
95
33.842105
122
0.625
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,614
cz_regions.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/cz/cz_regions.py
""" Czech regions, translations get from http://www.crwflags.com/fotw/Flags/cz-re.html """ from django.utils.translation import ugettext_lazy as _ REGION_CHOICES = ( ('PR', _('Prague')), ('CE', _('Central Bohemian Region')), ('SO', _('South Bohemian Region')), ('PI', _('Pilsen Region')), ('CA', _('Carlsbad Region')), ('US', _('Usti Region')), ('LB', _('Liberec Region')), ('HK', _('Hradec Region')), ('PA', _('Pardubice Region')), ('VY', _('Vysocina Region')), ('SM', _('South Moravian Region')), ('OL', _('Olomouc Region')), ('ZL', _('Zlin Region')), ('MS', _('Moravian-Silesian Region')), )
653
Python
.py
20
28.75
82
0.559429
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,615
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/cz/forms.py
""" Czech-specific form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Select, RegexField, Field from django.utils.translation import ugettext_lazy as _ import re birth_number = re.compile(r'^(?P<birth>\d{6})/?(?P<id>\d{3,4})$') ic_number = re.compile(r'^(?P<number>\d{7})(?P<check>\d)$') class CZRegionSelect(Select): """ A select widget widget with list of Czech regions as choices. """ def __init__(self, attrs=None): from cz_regions import REGION_CHOICES super(CZRegionSelect, self).__init__(attrs, choices=REGION_CHOICES) class CZPostalCodeField(RegexField): """ A form field that validates its input as Czech postal code. Valid form is XXXXX or XXX XX, where X represents integer. """ default_error_messages = { 'invalid': _(u'Enter a postal code in the format XXXXX or XXX XX.'), } def __init__(self, *args, **kwargs): super(CZPostalCodeField, self).__init__(r'^\d{5}$|^\d{3} \d{2}$', max_length=None, min_length=None, *args, **kwargs) def clean(self, value): """ Validates the input and returns a string that contains only numbers. Returns an empty string for empty values. """ v = super(CZPostalCodeField, self).clean(value) return v.replace(' ', '') class CZBirthNumberField(Field): """ Czech birth number field. """ default_error_messages = { 'invalid_format': _(u'Enter a birth number in the format XXXXXX/XXXX or XXXXXXXXXX.'), 'invalid_gender': _(u'Invalid optional parameter Gender, valid values are \'f\' and \'m\''), 'invalid': _(u'Enter a valid birth number.'), } def clean(self, value, gender=None): super(CZBirthNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' match = re.match(birth_number, value) if not match: raise ValidationError(self.error_messages['invalid_format']) birth, id = match.groupdict()['birth'], match.groupdict()['id'] # Three digits for verification number were used until 1. january 1954 if len(id) == 3: return u'%s' % value # Birth number is in format YYMMDD. Females have month value raised by 50. # In case that all possible number are already used (for given date), # the month field is raised by 20. if gender is not None: import warnings warnings.warn( "Support for validating the gender of a CZ Birth number has been deprecated.", PendingDeprecationWarning) if gender == 'f': female_const = 50 elif gender == 'm': female_const = 0 else: raise ValidationError(self.error_messages['invalid_gender']) month = int(birth[2:4]) - female_const if (not 1 <= month <= 12): if (not 1 <= (month - 20) <= 12): raise ValidationError(self.error_messages['invalid']) day = int(birth[4:6]) if not (1 <= day <= 31): raise ValidationError(self.error_messages['invalid']) # Fourth digit has been added since 1. January 1954. # It is modulo of dividing birth number and verification number by 11. # If the modulo were 10, the last number was 0 (and therefore, the whole # birth number wasn't divisable by 11. These number are no longer used (since 1985) # and the condition 'modulo == 10' can be removed in 2085. modulo = int(birth + id[:3]) % 11 if (modulo == int(id[-1])) or (modulo == 10 and id[-1] == '0'): return u'%s' % value else: raise ValidationError(self.error_messages['invalid']) class CZICNumberField(Field): """ Czech IC number field. """ default_error_messages = { 'invalid': _(u'Enter a valid IC number.'), } def clean(self, value): super(CZICNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' match = re.match(ic_number, value) if not match: raise ValidationError(self.error_messages['invalid']) number, check = match.groupdict()['number'], int(match.groupdict()['check']) sum = 0 weight = 8 for digit in number: sum += int(digit)*weight weight -= 1 remainder = sum % 11 # remainder is equal: # 0 or 10: last digit is 1 # 1: last digit is 0 # in other case, last digin is 11 - remainder if (not remainder % 10 and check == 1) or \ (remainder == 1 and check == 0) or \ (check == (11 - remainder)): return u'%s' % value raise ValidationError(self.error_messages['invalid'])
4,929
Python
.py
116
33.862069
100
0.602843
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,616
es_provinces.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/es/es_provinces.py
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ PROVINCE_CHOICES = ( ('01', _('Arava')), ('02', _('Albacete')), ('03', _('Alacant')), ('04', _('Almeria')), ('05', _('Avila')), ('06', _('Badajoz')), ('07', _('Illes Balears')), ('08', _('Barcelona')), ('09', _('Burgos')), ('10', _('Caceres')), ('11', _('Cadiz')), ('12', _('Castello')), ('13', _('Ciudad Real')), ('14', _('Cordoba')), ('15', _('A Coruna')), ('16', _('Cuenca')), ('17', _('Girona')), ('18', _('Granada')), ('19', _('Guadalajara')), ('20', _('Guipuzkoa')), ('21', _('Huelva')), ('22', _('Huesca')), ('23', _('Jaen')), ('24', _('Leon')), ('25', _('Lleida')), ('26', _('La Rioja')), ('27', _('Lugo')), ('28', _('Madrid')), ('29', _('Malaga')), ('30', _('Murcia')), ('31', _('Navarre')), ('32', _('Ourense')), ('33', _('Asturias')), ('34', _('Palencia')), ('35', _('Las Palmas')), ('36', _('Pontevedra')), ('37', _('Salamanca')), ('38', _('Santa Cruz de Tenerife')), ('39', _('Cantabria')), ('40', _('Segovia')), ('41', _('Seville')), ('42', _('Soria')), ('43', _('Tarragona')), ('44', _('Teruel')), ('45', _('Toledo')), ('46', _('Valencia')), ('47', _('Valladolid')), ('48', _('Bizkaia')), ('49', _('Zamora')), ('50', _('Zaragoza')), ('51', _('Ceuta')), ('52', _('Melilla')), )
1,482
Python
.py
56
21.714286
55
0.390449
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,617
es_regions.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/es/es_regions.py
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ REGION_CHOICES = ( ('AN', _('Andalusia')), ('AR', _('Aragon')), ('O', _('Principality of Asturias')), ('IB', _('Balearic Islands')), ('PV', _('Basque Country')), ('CN', _('Canary Islands')), ('S', _('Cantabria')), ('CM', _('Castile-La Mancha')), ('CL', _('Castile and Leon')), ('CT', _('Catalonia')), ('EX', _('Extremadura')), ('GA', _('Galicia')), ('LO', _('La Rioja')), ('M', _('Madrid')), ('MU', _('Region of Murcia')), ('NA', _('Foral Community of Navarre')), ('VC', _('Valencian Community')), )
650
Python
.py
21
26.619048
55
0.496013
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,618
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/es/forms.py
# -*- coding: utf-8 -*- """ Spanish-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import RegexField, Select from django.utils.translation import ugettext_lazy as _ import re class ESPostalCodeField(RegexField): """ A form field that validates its input as a spanish postal code. Spanish postal code is a five digits string, with two first digits between 01 and 52, assigned to provinces code. """ default_error_messages = { 'invalid': _('Enter a valid postal code in the range and format 01XXX - 52XXX.'), } def __init__(self, *args, **kwargs): super(ESPostalCodeField, self).__init__( r'^(0[1-9]|[1-4][0-9]|5[0-2])\d{3}$', max_length=None, min_length=None, *args, **kwargs) class ESPhoneNumberField(RegexField): """ A form field that validates its input as a Spanish phone number. Information numbers are ommited. Spanish phone numbers are nine digit numbers, where first digit is 6 (for cell phones), 8 (for special phones), or 9 (for landlines and special phones) TODO: accept and strip characters like dot, hyphen... in phone number """ default_error_messages = { 'invalid': _('Enter a valid phone number in one of the formats 6XXXXXXXX, 8XXXXXXXX or 9XXXXXXXX.'), } def __init__(self, *args, **kwargs): super(ESPhoneNumberField, self).__init__(r'^(6|8|9)\d{8}$', max_length=None, min_length=None, *args, **kwargs) class ESIdentityCardNumberField(RegexField): """ Spanish NIF/NIE/CIF (Fiscal Identification Number) code. Validates three diferent formats: NIF (individuals): 12345678A CIF (companies): A12345678 NIE (foreigners): X12345678A according to a couple of simple checksum algorithms. Value can include a space or hyphen separator between number and letters. Number length is not checked for NIF (or NIE), old values start with a 1, and future values can contain digits greater than 8. The CIF control digit can be a number or a letter depending on company type. Algorithm is not public, and different authors have different opinions on which ones allows letters, so both validations are assumed true for all types. """ default_error_messages = { 'invalid': _('Please enter a valid NIF, NIE, or CIF.'), 'invalid_only_nif': _('Please enter a valid NIF or NIE.'), 'invalid_nif': _('Invalid checksum for NIF.'), 'invalid_nie': _('Invalid checksum for NIE.'), 'invalid_cif': _('Invalid checksum for CIF.'), } def __init__(self, only_nif=False, *args, **kwargs): self.only_nif = only_nif self.nif_control = 'TRWAGMYFPDXBNJZSQVHLCKE' self.cif_control = 'JABCDEFGHI' self.cif_types = 'ABCDEFGHKLMNPQS' self.nie_types = 'XT' id_card_re = re.compile(r'^([%s]?)[ -]?(\d+)[ -]?([%s]?)$' % (self.cif_types + self.nie_types, self.nif_control + self.cif_control), re.IGNORECASE) super(ESIdentityCardNumberField, self).__init__(id_card_re, max_length=None, min_length=None, error_message=self.default_error_messages['invalid%s' % (self.only_nif and '_only_nif' or '')], *args, **kwargs) def clean(self, value): super(ESIdentityCardNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' nif_get_checksum = lambda d: self.nif_control[int(d)%23] value = value.upper().replace(' ', '').replace('-', '') m = re.match(r'^([%s]?)[ -]?(\d+)[ -]?([%s]?)$' % (self.cif_types + self.nie_types, self.nif_control + self.cif_control), value) letter1, number, letter2 = m.groups() if not letter1 and letter2: # NIF if letter2 == nif_get_checksum(number): return value else: raise ValidationError(self.error_messages['invalid_nif']) elif letter1 in self.nie_types and letter2: # NIE if letter2 == nif_get_checksum(number): return value else: raise ValidationError(self.error_messages['invalid_nie']) elif not self.only_nif and letter1 in self.cif_types and len(number) in [7, 8]: # CIF if not letter2: number, letter2 = number[:-1], int(number[-1]) checksum = cif_get_checksum(number) if letter2 in (checksum, self.cif_control[checksum]): return value else: raise ValidationError(self.error_messages['invalid_cif']) else: raise ValidationError(self.error_messages['invalid']) class ESCCCField(RegexField): """ A form field that validates its input as a Spanish bank account or CCC (Codigo Cuenta Cliente). Spanish CCC is in format EEEE-OOOO-CC-AAAAAAAAAA where: E = entity O = office C = checksum A = account It's also valid to use a space as delimiter, or to use no delimiter. First checksum digit validates entity and office, and last one validates account. Validation is done multiplying every digit of 10 digit value (with leading 0 if necessary) by number in its position in string 1, 2, 4, 8, 5, 10, 9, 7, 3, 6. Sum resulting numbers and extract it from 11. Result is checksum except when 10 then is 1, or when 11 then is 0. TODO: allow IBAN validation too """ default_error_messages = { 'invalid': _('Please enter a valid bank account number in format XXXX-XXXX-XX-XXXXXXXXXX.'), 'checksum': _('Invalid checksum for bank account number.'), } def __init__(self, *args, **kwargs): super(ESCCCField, self).__init__(r'^\d{4}[ -]?\d{4}[ -]?\d{2}[ -]?\d{10}$', max_length=None, min_length=None, *args, **kwargs) def clean(self, value): super(ESCCCField, self).clean(value) if value in EMPTY_VALUES: return u'' control_str = [1, 2, 4, 8, 5, 10, 9, 7, 3, 6] m = re.match(r'^(\d{4})[ -]?(\d{4})[ -]?(\d{2})[ -]?(\d{10})$', value) entity, office, checksum, account = m.groups() get_checksum = lambda d: str(11 - sum([int(digit) * int(control) for digit, control in zip(d, control_str)]) % 11).replace('10', '1').replace('11', '0') if get_checksum('00' + entity + office) + get_checksum(account) == checksum: return value else: raise ValidationError(self.error_messages['checksum']) class ESRegionSelect(Select): """ A Select widget that uses a list of spanish regions as its choices. """ def __init__(self, attrs=None): from es_regions import REGION_CHOICES super(ESRegionSelect, self).__init__(attrs, choices=REGION_CHOICES) class ESProvinceSelect(Select): """ A Select widget that uses a list of spanish provinces as its choices. """ def __init__(self, attrs=None): from es_provinces import PROVINCE_CHOICES super(ESProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES) def cif_get_checksum(number): s1 = sum([int(digit) for pos, digit in enumerate(number) if int(pos) % 2]) s2 = sum([sum([int(unit) for unit in str(int(digit) * 2)]) for pos, digit in enumerate(number) if not int(pos) % 2]) return (10 - ((s1 + s2) % 10)) % 10
7,537
Python
.py
155
40.464516
160
0.627176
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,619
no_municipalities.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/no/no_municipalities.py
# -*- coding: utf-8 -*- """ An alphabetical list of Norwegian municipalities (fylker) fro use as `choices` in a formfield. This exists in this standalone file so that it's on ly imported into memory when explicitly needed. """ MUNICIPALITY_CHOICES = ( ('akershus', u'Akershus'), ('austagder', u'Aust-Agder'), ('buskerud', u'Buskerud'), ('finnmark', u'Finnmark'), ('hedmark', u'Hedmark'), ('hordaland', u'Hordaland'), ('janmayen', u'Jan Mayen'), ('moreogromsdal', u'Møre og Romsdal'), ('nordtrondelag', u'Nord-Trøndelag'), ('nordland', u'Nordland'), ('oppland', u'Oppland'), ('oslo', u'Oslo'), ('rogaland', u'Rogaland'), ('sognogfjordane', u'Sogn og Fjordane'), ('svalbard', u'Svalbard'), ('sortrondelag', u'Sør-Trøndelag'), ('telemark', u'Telemark'), ('troms', u'Troms'), ('vestagder', u'Vest-Agder'), ('vestfold', u'Vestfold'), ('ostfold', u'Østfold') )
946
Python
.py
30
27.5
78
0.625963
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,620
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/no/forms.py
""" Norwegian-specific Form helpers """ import re, datetime from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ class NOZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a zip code in the format XXXX.'), } def __init__(self, *args, **kwargs): super(NOZipCodeField, self).__init__(r'^\d{4}$', max_length=None, min_length=None, *args, **kwargs) class NOMunicipalitySelect(Select): """ A Select widget that uses a list of Norwegian municipalities (fylker) as its choices. """ def __init__(self, attrs=None): from no_municipalities import MUNICIPALITY_CHOICES super(NOMunicipalitySelect, self).__init__(attrs, choices=MUNICIPALITY_CHOICES) class NOSocialSecurityNumber(Field): """ Algorithm is documented at http://no.wikipedia.org/wiki/Personnummer """ default_error_messages = { 'invalid': _(u'Enter a valid Norwegian social security number.'), } def clean(self, value): super(NOSocialSecurityNumber, self).clean(value) if value in EMPTY_VALUES: return u'' if not re.match(r'^\d{11}$', value): raise ValidationError(self.error_messages['invalid']) day = int(value[:2]) month = int(value[2:4]) year2 = int(value[4:6]) inum = int(value[6:9]) self.birthday = None try: if 000 <= inum < 500: self.birthday = datetime.date(1900+year2, month, day) if 500 <= inum < 750 and year2 > 54: self.birthday = datetime.date(1800+year2, month, day) if 500 <= inum < 1000 and year2 < 40: self.birthday = datetime.date(2000+year2, month, day) if 900 <= inum < 1000 and year2 > 39: self.birthday = datetime.date(1900+year2, month, day) except ValueError: raise ValidationError(self.error_messages['invalid']) sexnum = int(value[8]) if sexnum % 2 == 0: self.gender = 'F' else: self.gender = 'M' digits = map(int, list(value)) weight_1 = [3, 7, 6, 1, 8, 9, 4, 5, 2, 1, 0] weight_2 = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2, 1] def multiply_reduce(aval, bval): return sum([(a * b) for (a, b) in zip(aval, bval)]) if multiply_reduce(digits, weight_1) % 11 != 0: raise ValidationError(self.error_messages['invalid']) if multiply_reduce(digits, weight_2) % 11 != 0: raise ValidationError(self.error_messages['invalid']) return value
2,761
Python
.py
67
32.880597
87
0.606943
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,621
nl_provinces.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/nl/nl_provinces.py
from django.utils.translation import ugettext_lazy as _ PROVINCE_CHOICES = ( ('DR', _('Drenthe')), ('FL', _('Flevoland')), ('FR', _('Friesland')), ('GL', _('Gelderland')), ('GR', _('Groningen')), ('LB', _('Limburg')), ('NB', _('Noord-Brabant')), ('NH', _('Noord-Holland')), ('OV', _('Overijssel')), ('UT', _('Utrecht')), ('ZE', _('Zeeland')), ('ZH', _('Zuid-Holland')), )
421
Python
.py
15
23.8
55
0.481481
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,622
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/nl/forms.py
""" NL-specific Form helpers """ import re from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, Select from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode pc_re = re.compile('^\d{4}[A-Z]{2}$') sofi_re = re.compile('^\d{9}$') numeric_re = re.compile('^\d+$') class NLZipCodeField(Field): """ A Dutch postal code field. """ default_error_messages = { 'invalid': _('Enter a valid postal code'), } def clean(self, value): super(NLZipCodeField, self).clean(value) if value in EMPTY_VALUES: return u'' value = value.strip().upper().replace(' ', '') if not pc_re.search(value): raise ValidationError(self.error_messages['invalid']) if int(value[:4]) < 1000: raise ValidationError(self.error_messages['invalid']) return u'%s %s' % (value[:4], value[4:]) class NLProvinceSelect(Select): """ A Select widget that uses a list of provinces of the Netherlands as its choices. """ def __init__(self, attrs=None): from nl_provinces import PROVINCE_CHOICES super(NLProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES) class NLPhoneNumberField(Field): """ A Dutch telephone number field. """ default_error_messages = { 'invalid': _('Enter a valid phone number'), } def clean(self, value): super(NLPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' phone_nr = re.sub('[\-\s\(\)]', '', smart_unicode(value)) if len(phone_nr) == 10 and numeric_re.search(phone_nr): return value if phone_nr[:3] == '+31' and len(phone_nr) == 12 and \ numeric_re.search(phone_nr[3:]): return value raise ValidationError(self.error_messages['invalid']) class NLSoFiNumberField(Field): """ A Dutch social security number (SoFi/BSN) field. http://nl.wikipedia.org/wiki/Sofinummer """ default_error_messages = { 'invalid': _('Enter a valid SoFi number'), } def clean(self, value): super(NLSoFiNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' if not sofi_re.search(value): raise ValidationError(self.error_messages['invalid']) if int(value) == 0: raise ValidationError(self.error_messages['invalid']) checksum = 0 for i in range(9, 1, -1): checksum += int(value[9-i]) * i checksum -= int(value[-1]) if checksum % 11 != 0: raise ValidationError(self.error_messages['invalid']) return value
2,796
Python
.py
78
28.820513
79
0.621521
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,623
pe_region.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/pe/pe_region.py
# -*- coding: utf-8 -*- """ A list of Peru regions as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ REGION_CHOICES = ( ('AMA', u'Amazonas'), ('ANC', u'Ancash'), ('APU', u'Apurímac'), ('ARE', u'Arequipa'), ('AYA', u'Ayacucho'), ('CAJ', u'Cajamarca'), ('CAL', u'Callao'), ('CUS', u'Cusco'), ('HUV', u'Huancavelica'), ('HUC', u'Huánuco'), ('ICA', u'Ica'), ('JUN', u'Junín'), ('LAL', u'La Libertad'), ('LAM', u'Lambayeque'), ('LIM', u'Lima'), ('LOR', u'Loreto'), ('MDD', u'Madre de Dios'), ('MOQ', u'Moquegua'), ('PAS', u'Pasco'), ('PIU', u'Piura'), ('PUN', u'Puno'), ('SAM', u'San Martín'), ('TAC', u'Tacna'), ('TUM', u'Tumbes'), ('UCA', u'Ucayali'), )
839
Python
.py
33
21.212121
74
0.5225
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,624
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/pe/forms.py
# -*- coding: utf-8 -*- """ PE-specific Form helpers. """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import RegexField, CharField, Select from django.utils.translation import ugettext_lazy as _ class PERegionSelect(Select): """ A Select widget that uses a list of Peruvian Regions as its choices. """ def __init__(self, attrs=None): from pe_region import REGION_CHOICES super(PERegionSelect, self).__init__(attrs, choices=REGION_CHOICES) class PEDNIField(CharField): """ A field that validates `Documento Nacional de Identidad≈Ω (DNI) numbers. """ default_error_messages = { 'invalid': _("This field requires only numbers."), 'max_digits': _("This field requires 8 digits."), } def __init__(self, *args, **kwargs): super(PEDNIField, self).__init__(max_length=8, min_length=8, *args, **kwargs) def clean(self, value): """ Value must be a string in the XXXXXXXX formats. """ value = super(PEDNIField, self).clean(value) if value in EMPTY_VALUES: return u'' if not value.isdigit(): raise ValidationError(self.error_messages['invalid']) if len(value) != 8: raise ValidationError(self.error_messages['max_digits']) return value class PERUCField(RegexField): """ This field validates a RUC (Registro Unico de Contribuyentes). A RUC is of the form XXXXXXXXXXX. """ default_error_messages = { 'invalid': _("This field requires only numbers."), 'max_digits': _("This field requires 11 digits."), } def __init__(self, *args, **kwargs): super(PERUCField, self).__init__(max_length=11, min_length=11, *args, **kwargs) def clean(self, value): """ Value must be an 11-digit number. """ value = super(PERUCField, self).clean(value) if value in EMPTY_VALUES: return u'' if not value.isdigit(): raise ValidationError(self.error_messages['invalid']) if len(value) != 11: raise ValidationError(self.error_messages['max_digits']) return value
2,272
Python
.py
62
29.548387
78
0.626818
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,625
be_provinces.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/be/be_provinces.py
from django.utils.translation import ugettext_lazy as _ # ISO codes PROVINCE_CHOICES = ( ('VAN', _('Antwerp')), ('BRU', _('Brussels')), ('VOV', _('East Flanders')), ('VBR', _('Flemish Brabant')), ('WHT', _('Hainaut')), ('WLG', _('Liege')), ('VLI', _('Limburg')), ('WLX', _('Luxembourg')), ('WNA', _('Namur')), ('WBR', _('Walloon Brabant')), ('VWV', _('West Flanders')) )
416
Python
.py
15
23.733333
55
0.5075
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,626
be_regions.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/be/be_regions.py
from django.utils.translation import ugettext_lazy as _ # ISO codes REGION_CHOICES = ( ('BRU', _('Brussels Capital Region')), ('VLG', _('Flemish Region')), ('WAL', _('Wallonia')) )
194
Python
.py
7
24.857143
55
0.634409
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,627
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/be/forms.py
""" Belgium-specific Form helpers """ import re from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import RegexField, Select from django.utils.translation import ugettext_lazy as _ class BEPostalCodeField(RegexField): """ A form field that validates its input as a belgium postal code. Belgium postal code is a 4 digits string. The first digit indicates the province (except for the 3ddd numbers that are shared by the eastern part of Flemish Brabant and Limburg and the and 1ddd that are shared by the Brussels Capital Region, the western part of Flemish Brabant and Walloon Brabant) """ default_error_messages = { 'invalid': _( 'Enter a valid postal code in the range and format 1XXX - 9XXX.'), } def __init__(self, *args, **kwargs): super(BEPostalCodeField, self).__init__(r'^[1-9]\d{3}$', max_length=None, min_length=None, *args, **kwargs) class BEPhoneNumberField(RegexField): """ A form field that validates its input as a belgium phone number. Landlines have a seven-digit subscriber number and a one-digit area code, while smaller cities have a six-digit subscriber number and a two-digit area code. Cell phones have a six-digit subscriber number and a two-digit area code preceeded by the number 4. 0d ddd dd dd, 0d/ddd.dd.dd, 0d.ddd.dd.dd, 0dddddddd - dialling a bigger city 0dd dd dd dd, 0dd/dd.dd.dd, 0dd.dd.dd.dd, 0dddddddd - dialling a smaller city 04dd ddd dd dd, 04dd/ddd.dd.dd, 04dd.ddd.dd.dd, 04ddddddddd - dialling a mobile number """ default_error_messages = { 'invalid': _('Enter a valid phone number in one of the formats ' '0x xxx xx xx, 0xx xx xx xx, 04xx xx xx xx, ' '0x/xxx.xx.xx, 0xx/xx.xx.xx, 04xx/xx.xx.xx, ' '0x.xxx.xx.xx, 0xx.xx.xx.xx, 04xx.xx.xx.xx, ' '0xxxxxxxx or 04xxxxxxxx.'), } def __init__(self, *args, **kwargs): super(BEPhoneNumberField, self).__init__(r'^[0]\d{1}[/. ]?\d{3}[. ]\d{2}[. ]?\d{2}$|^[0]\d{2}[/. ]?\d{2}[. ]?\d{2}[. ]?\d{2}$|^[0][4]\d{2}[/. ]?\d{2}[. ]?\d{2}[. ]?\d{2}$', max_length=None, min_length=None, *args, **kwargs) class BERegionSelect(Select): """ A Select widget that uses a list of belgium regions as its choices. """ def __init__(self, attrs=None): from be_regions import REGION_CHOICES super(BERegionSelect, self).__init__(attrs, choices=REGION_CHOICES) class BEProvinceSelect(Select): """ A Select widget that uses a list of belgium provinces as its choices. """ def __init__(self, attrs=None): from be_provinces import PROVINCE_CHOICES super(BEProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES)
2,885
Python
.py
62
39.951613
180
0.650178
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,628
in_states.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/in_/in_states.py
""" A mapping of state misspellings/abbreviations to normalized abbreviations, and an alphabetical list of states for use as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ STATE_CHOICES = ( ('KA', 'Karnataka'), ('AP', 'Andhra Pradesh'), ('KL', 'Kerala'), ('TN', 'Tamil Nadu'), ('MH', 'Maharashtra'), ('UP', 'Uttar Pradesh'), ('GA', 'Goa'), ('GJ', 'Gujarat'), ('RJ', 'Rajasthan'), ('HP', 'Himachal Pradesh'), ('JK', 'Jammu and Kashmir'), ('AR', 'Arunachal Pradesh'), ('AS', 'Assam'), ('BR', 'Bihar'), ('CG', 'Chattisgarh'), ('HR', 'Haryana'), ('JH', 'Jharkhand'), ('MP', 'Madhya Pradesh'), ('MN', 'Manipur'), ('ML', 'Meghalaya'), ('MZ', 'Mizoram'), ('NL', 'Nagaland'), ('OR', 'Orissa'), ('PB', 'Punjab'), ('SK', 'Sikkim'), ('TR', 'Tripura'), ('UA', 'Uttarakhand'), ('WB', 'West Bengal'), # Union Territories ('AN', 'Andaman and Nicobar'), ('CH', 'Chandigarh'), ('DN', 'Dadra and Nagar Haveli'), ('DD', 'Daman and Diu'), ('DL', 'Delhi'), ('LD', 'Lakshadweep'), ('PY', 'Pondicherry'), ) STATES_NORMALIZED = { 'ka': 'KA', 'karnatka': 'KA', 'tn': 'TN', 'tamilnad': 'TN', 'tamilnadu': 'TN', 'andra pradesh': 'AP', 'andrapradesh': 'AP', 'andhrapradesh': 'AP', 'maharastra': 'MH', 'mh': 'MH', 'ap': 'AP', 'dl': 'DL', 'dd': 'DD', 'br': 'BR', 'ar': 'AR', 'sk': 'SK', 'kl': 'KL', 'ga': 'GA', 'rj': 'RJ', 'rajastan': 'RJ', 'rajasthan': 'RJ', 'hp': 'HP', 'ua': 'UA', 'up': 'UP', 'mp': 'MP', 'mz': 'MZ', 'bengal': 'WB', 'westbengal': 'WB', 'mizo': 'MZ', 'orisa': 'OR', 'odisa': 'OR', 'or': 'OR', 'ar': 'AR', }
1,859
Python
.py
79
18.974684
78
0.492958
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,629
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/in_/forms.py
""" India-specific Form helpers. """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.encoding import smart_unicode from django.utils.translation import gettext import re class INZipCodeField(RegexField): default_error_messages = { 'invalid': gettext(u'Enter a zip code in the format XXXXXXX.'), } def __init__(self, *args, **kwargs): super(INZipCodeField, self).__init__(r'^\d{6}$', max_length=None, min_length=None, *args, **kwargs) class INStateField(Field): """ A form field that validates its input is a Indian state name or abbreviation. It normalizes the input to the standard two-letter vehicle registration abbreviation for the given state or union territory """ default_error_messages = { 'invalid': u'Enter a Indian state or territory.', } def clean(self, value): from in_states import STATES_NORMALIZED super(INStateField, self).clean(value) if value in EMPTY_VALUES: return u'' try: value = value.strip().lower() except AttributeError: pass else: try: return smart_unicode(STATES_NORMALIZED[value.strip().lower()]) except KeyError: pass raise ValidationError(self.error_messages['invalid']) class INStateSelect(Select): """ A Select widget that uses a list of Indian states/territories as its choices. """ def __init__(self, attrs=None): from in_states import STATE_CHOICES super(INStateSelect, self).__init__(attrs, choices=STATE_CHOICES)
1,741
Python
.py
48
29.604167
78
0.668249
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,630
de_states.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/de/de_states.py
# -*- coding: utf-8 -* from django.utils.translation import ugettext_lazy as _ STATE_CHOICES = ( ('BW', _('Baden-Wuerttemberg')), ('BY', _('Bavaria')), ('BE', _('Berlin')), ('BB', _('Brandenburg')), ('HB', _('Bremen')), ('HH', _('Hamburg')), ('HE', _('Hessen')), ('MV', _('Mecklenburg-Western Pomerania')), ('NI', _('Lower Saxony')), ('NW', _('North Rhine-Westphalia')), ('RP', _('Rhineland-Palatinate')), ('SL', _('Saarland')), ('SN', _('Saxony')), ('ST', _('Saxony-Anhalt')), ('SH', _('Schleswig-Holstein')), ('TH', _('Thuringia')), )
602
Python
.py
20
25.85
55
0.497418
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,631
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/de/forms.py
""" DE-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ import re id_re = re.compile(r"^(?P<residence>\d{10})(?P<origin>\w{1,3})[-\ ]?(?P<birthday>\d{7})[-\ ]?(?P<validity>\d{7})[-\ ]?(?P<checksum>\d{1})$") class DEZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a zip code in the format XXXXX.'), } def __init__(self, *args, **kwargs): super(DEZipCodeField, self).__init__(r'^\d{5}$', max_length=None, min_length=None, *args, **kwargs) class DEStateSelect(Select): """ A Select widget that uses a list of DE states as its choices. """ def __init__(self, attrs=None): from de_states import STATE_CHOICES super(DEStateSelect, self).__init__(attrs, choices=STATE_CHOICES) class DEIdentityCardNumberField(Field): """ A German identity card number. Checks the following rules to determine whether the number is valid: * Conforms to the XXXXXXXXXXX-XXXXXXX-XXXXXXX-X format. * No group consists entirely of zeroes. * Included checksums match calculated checksums Algorithm is documented at http://de.wikipedia.org/wiki/Personalausweis """ default_error_messages = { 'invalid': _('Enter a valid German identity card number in XXXXXXXXXXX-XXXXXXX-XXXXXXX-X format.'), } def has_valid_checksum(self, number): given_number, given_checksum = number[:-1], number[-1] calculated_checksum = 0 fragment = "" parameter = 7 for i in range(len(given_number)): fragment = str(int(given_number[i]) * parameter) if fragment.isalnum(): calculated_checksum += int(fragment[-1]) if parameter == 1: parameter = 7 elif parameter == 3: parameter = 1 elif parameter ==7: parameter = 3 return str(calculated_checksum)[-1] == given_checksum def clean(self, value): super(DEIdentityCardNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' match = re.match(id_re, value) if not match: raise ValidationError(self.error_messages['invalid']) gd = match.groupdict() residence, origin = gd['residence'], gd['origin'] birthday, validity, checksum = gd['birthday'], gd['validity'], gd['checksum'] if residence == '0000000000' or birthday == '0000000' or validity == '0000000': raise ValidationError(self.error_messages['invalid']) all_digits = u"%s%s%s%s" % (residence, birthday, validity, checksum) if not self.has_valid_checksum(residence) or not self.has_valid_checksum(birthday) or \ not self.has_valid_checksum(validity) or not self.has_valid_checksum(all_digits): raise ValidationError(self.error_messages['invalid']) return u'%s%s-%s-%s-%s' % (residence, origin, birthday, validity, checksum)
3,163
Python
.py
68
38.455882
140
0.639169
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,632
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/il/forms.py
""" Israeli-specific form helpers """ import re from django.core.exceptions import ValidationError from django.core.validators import EMPTY_VALUES from django.forms.fields import RegexField, Field, EMPTY_VALUES from django.utils.checksums import luhn from django.utils.translation import ugettext_lazy as _ # Israeli ID numbers consist of up to 8 digits followed by a checksum digit. # Numbers which are shorter than 8 digits are effectively left-zero-padded. # The checksum digit is occasionally separated from the number by a hyphen, # and is calculated using the luhn algorithm. # # Relevant references: # # (hebrew) http://he.wikipedia.org/wiki/%D7%9E%D7%A1%D7%A4%D7%A8_%D7%96%D7%94%D7%95%D7%AA_(%D7%99%D7%A9%D7%A8%D7%90%D7%9C) # (hebrew) http://he.wikipedia.org/wiki/%D7%A1%D7%A4%D7%A8%D7%AA_%D7%91%D7%99%D7%A7%D7%95%D7%A8%D7%AA id_number_re = re.compile(r'^(?P<number>\d{1,8})-?(?P<check>\d)$') class ILPostalCodeField(RegexField): """ A form field that validates its input as an Israeli postal code. Valid form is XXXXX where X represents integer. """ default_error_messages = { 'invalid': _(u'Enter a postal code in the format XXXXX'), } def __init__(self, *args, **kwargs): super(ILPostalCodeField, self).__init__(r'^\d{5}$', *args, **kwargs) def clean(self, value): if value not in EMPTY_VALUES: value = value.replace(" ", "") return super(ILPostalCodeField, self).clean(value) class ILIDNumberField(Field): """ A form field that validates its input as an Israeli identification number. Valid form is per the Israeli ID specification. """ default_error_messages = { 'invalid': _(u'Enter a valid ID number.'), } def clean(self, value): value = super(ILIDNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' match = id_number_re.match(value) if not match: raise ValidationError(self.error_messages['invalid']) value = match.group('number') + match.group('check') if not luhn(value): raise ValidationError(self.error_messages['invalid']) return value
2,192
Python
.py
52
36.961538
122
0.686736
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,633
ro_counties.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/ro/ro_counties.py
# -*- coding: utf-8 -*- """ A list of Romanian counties as `choices` in a formfield. This exists as a standalone file so that it's only imported into memory when explicitly needed. """ COUNTIES_CHOICES = ( ('AB', u'Alba'), ('AR', u'Arad'), ('AG', u'Argeş'), ('BC', u'Bacău'), ('BH', u'Bihor'), ('BN', u'Bistriţa-Năsăud'), ('BT', u'Botoşani'), ('BV', u'Braşov'), ('BR', u'Brăila'), ('B', u'Bucureşti'), ('BZ', u'Buzău'), ('CS', u'Caraş-Severin'), ('CL', u'Călăraşi'), ('CJ', u'Cluj'), ('CT', u'Constanţa'), ('CV', u'Covasna'), ('DB', u'Dâmboviţa'), ('DJ', u'Dolj'), ('GL', u'Galaţi'), ('GR', u'Giurgiu'), ('GJ', u'Gorj'), ('HR', u'Harghita'), ('HD', u'Hunedoara'), ('IL', u'Ialomiţa'), ('IS', u'Iaşi'), ('IF', u'Ilfov'), ('MM', u'Maramureş'), ('MH', u'Mehedinţi'), ('MS', u'Mureş'), ('NT', u'Neamţ'), ('OT', u'Olt'), ('PH', u'Prahova'), ('SM', u'Satu Mare'), ('SJ', u'Sălaj'), ('SB', u'Sibiu'), ('SV', u'Suceava'), ('TR', u'Teleorman'), ('TM', u'Timiş'), ('TL', u'Tulcea'), ('VS', u'Vaslui'), ('VL', u'Vâlcea'), ('VN', u'Vrancea'), )
1,231
Python
.py
50
19.68
76
0.476563
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,634
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/ro/forms.py
# -*- coding: utf-8 -*- """ Romanian specific form helpers. """ import re from django.core.validators import EMPTY_VALUES from django.forms import ValidationError, Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ class ROCIFField(RegexField): """ A Romanian fiscal identity code (CIF) field For CIF validation algorithm see http://www.validari.ro/cui.html """ default_error_messages = { 'invalid': _("Enter a valid CIF."), } def __init__(self, *args, **kwargs): super(ROCIFField, self).__init__(r'^(RO)?[0-9]{2,10}', max_length=10, min_length=2, *args, **kwargs) def clean(self, value): """ CIF validation """ value = super(ROCIFField, self).clean(value) if value in EMPTY_VALUES: return u'' # strip RO part if value[0:2] == 'RO': value = value[2:] key = '753217532'[::-1] value = value[::-1] key_iter = iter(key) checksum = 0 for digit in value[1:]: checksum += int(digit) * int(key_iter.next()) checksum = checksum * 10 % 11 if checksum == 10: checksum = 0 if checksum != int(value[0]): raise ValidationError(self.error_messages['invalid']) return value[::-1] class ROCNPField(RegexField): """ A Romanian personal identity code (CNP) field For CNP validation algorithm see http://www.validari.ro/cnp.html """ default_error_messages = { 'invalid': _("Enter a valid CNP."), } def __init__(self, *args, **kwargs): super(ROCNPField, self).__init__(r'^[1-9][0-9]{12}', max_length=13, min_length=13, *args, **kwargs) def clean(self, value): """ CNP validations """ value = super(ROCNPField, self).clean(value) if value in EMPTY_VALUES: return u'' # check birthdate digits import datetime try: datetime.date(int(value[1:3]),int(value[3:5]),int(value[5:7])) except: raise ValidationError(self.error_messages['invalid']) # checksum key = '279146358279' checksum = 0 value_iter = iter(value) for digit in key: checksum += int(digit) * int(value_iter.next()) checksum %= 11 if checksum == 10: checksum = 1 if checksum != int(value[12]): raise ValidationError(self.error_messages['invalid']) return value class ROCountyField(Field): """ A form field that validates its input is a Romanian county name or abbreviation. It normalizes the input to the standard vehicle registration abbreviation for the given county WARNING: This field will only accept names written with diacritics; consider using ROCountySelect if this behavior is unnaceptable for you Example: ArgeÅŸ => valid Arges => invalid """ default_error_messages = { 'invalid': u'Enter a Romanian county code or name.', } def clean(self, value): from ro_counties import COUNTIES_CHOICES super(ROCountyField, self).clean(value) if value in EMPTY_VALUES: return u'' try: value = value.strip().upper() except AttributeError: pass # search for county code for entry in COUNTIES_CHOICES: if value in entry: return value # search for county name normalized_CC = [] for entry in COUNTIES_CHOICES: normalized_CC.append((entry[0],entry[1].upper())) for entry in normalized_CC: if entry[1] == value: return entry[0] raise ValidationError(self.error_messages['invalid']) class ROCountySelect(Select): """ A Select widget that uses a list of Romanian counties (judete) as its choices. """ def __init__(self, attrs=None): from ro_counties import COUNTIES_CHOICES super(ROCountySelect, self).__init__(attrs, choices=COUNTIES_CHOICES) class ROIBANField(RegexField): """ Romanian International Bank Account Number (IBAN) field For Romanian IBAN validation algorithm see http://validari.ro/iban.html """ default_error_messages = { 'invalid': _('Enter a valid IBAN in ROXX-XXXX-XXXX-XXXX-XXXX-XXXX format'), } def __init__(self, *args, **kwargs): super(ROIBANField, self).__init__(r'^[0-9A-Za-z\-\s]{24,40}$', max_length=40, min_length=24, *args, **kwargs) def clean(self, value): """ Strips - and spaces, performs country code and checksum validation """ value = super(ROIBANField, self).clean(value) if value in EMPTY_VALUES: return u'' value = value.replace('-','') value = value.replace(' ','') value = value.upper() if value[0:2] != 'RO': raise ValidationError(self.error_messages['invalid']) numeric_format = '' for char in value[4:] + value[0:4]: if char.isalpha(): numeric_format += str(ord(char) - 55) else: numeric_format += char if int(numeric_format) % 97 != 1: raise ValidationError(self.error_messages['invalid']) return value class ROPhoneNumberField(RegexField): """Romanian phone number field""" default_error_messages = { 'invalid': _('Phone numbers must be in XXXX-XXXXXX format.'), } def __init__(self, *args, **kwargs): super(ROPhoneNumberField, self).__init__(r'^[0-9\-\(\)\s]{10,20}$', max_length=20, min_length=10, *args, **kwargs) def clean(self, value): """ Strips -, (, ) and spaces. Checks the final length. """ value = super(ROPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = value.replace('-','') value = value.replace('(','') value = value.replace(')','') value = value.replace(' ','') if len(value) != 10: raise ValidationError(self.error_messages['invalid']) return value class ROPostalCodeField(RegexField): """Romanian postal code field.""" default_error_messages = { 'invalid': _('Enter a valid postal code in the format XXXXXX'), } def __init__(self, *args, **kwargs): super(ROPostalCodeField, self).__init__(r'^[0-9][0-8][0-9]{4}$', max_length=6, min_length=6, *args, **kwargs)
6,640
Python
.py
182
28.186813
83
0.587193
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,635
cl_regions.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/cl/cl_regions.py
# -*- coding: utf-8 -*- """ A list of Chilean regions as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ REGION_CHOICES = ( ('RM', u'Región Metropolitana de Santiago'), ('I', u'Región de Tarapacá'), ('II', u'Región de Antofagasta'), ('III', u'Región de Atacama'), ('IV', u'Región de Coquimbo'), ('V', u'Región de Valparaíso'), ('VI', u'Región del Libertador Bernardo O\'Higgins'), ('VII', u'Región del Maule'), ('VIII',u'Región del Bío Bío'), ('IX', u'Región de la Araucanía'), ('X', u'Región de los Lagos'), ('XI', u'Región de Aysén del General Carlos Ibáñez del Campo'), ('XII', u'Región de Magallanes y la Antártica Chilena'), ('XIV', u'Región de Los Ríos'), ('XV', u'Región de Arica-Parinacota'), )
884
Python
.py
23
33.652174
74
0.628297
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,636
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/cl/forms.py
""" Chile specific form helpers. """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import RegexField, Select from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode class CLRegionSelect(Select): """ A Select widget that uses a list of Chilean Regions (Regiones) as its choices. """ def __init__(self, attrs=None): from cl_regions import REGION_CHOICES super(CLRegionSelect, self).__init__(attrs, choices=REGION_CHOICES) class CLRutField(RegexField): """ Chilean "Rol Unico Tributario" (RUT) field. This is the Chilean national identification number. Samples for testing are available from https://palena.sii.cl/cvc/dte/ee_empresas_emisoras.html """ default_error_messages = { 'invalid': _('Enter a valid Chilean RUT.'), 'strict': _('Enter a valid Chilean RUT. The format is XX.XXX.XXX-X.'), 'checksum': _('The Chilean RUT is not valid.'), } def __init__(self, *args, **kwargs): if 'strict' in kwargs: del kwargs['strict'] super(CLRutField, self).__init__(r'^(\d{1,2}\.)?\d{3}\.\d{3}-[\dkK]$', error_message=self.default_error_messages['strict'], *args, **kwargs) else: # In non-strict mode, accept RUTs that validate but do not exist in # the real world. super(CLRutField, self).__init__(r'^[\d\.]{1,11}-?[\dkK]$', *args, **kwargs) def clean(self, value): """ Check and clean the Chilean RUT. """ super(CLRutField, self).clean(value) if value in EMPTY_VALUES: return u'' rut, verificador = self._canonify(value) if self._algorithm(rut) == verificador: return self._format(rut, verificador) else: raise ValidationError(self.error_messages['checksum']) def _algorithm(self, rut): """ Takes RUT in pure canonical form, calculates the verifier digit. """ suma = 0 multi = 2 for r in rut[::-1]: suma += int(r) * multi multi += 1 if multi == 8: multi = 2 return u'0123456789K0'[11 - suma % 11] def _canonify(self, rut): """ Turns the RUT into one normalized format. Returns a (rut, verifier) tuple. """ rut = smart_unicode(rut).replace(' ', '').replace('.', '').replace('-', '') return rut[:-1], rut[-1].upper() def _format(self, code, verifier=None): """ Formats the RUT from canonical form to the common string representation. If verifier=None, then the last digit in 'code' is the verifier. """ if verifier is None: verifier = code[-1] code = code[:-1] while len(code) > 3 and '.' not in code[:3]: pos = code.find('.') if pos == -1: new_dot = -3 else: new_dot = pos - 3 code = code[:new_dot] + '.' + code[new_dot:] return u'%s-%s' % (code, verifier)
3,196
Python
.py
84
29.535714
88
0.575621
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,637
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/generic/forms.py
from django import forms DEFAULT_DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%d/%m/%Y', '%d/%m/%y', # '2006-10-25', '25/10/2006', '25/10/06' '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ) DEFAULT_DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%d/%m/%y', # '25/10/06' ) class DateField(forms.DateField): """ A date input field which uses non-US date input formats by default. """ def __init__(self, input_formats=None, *args, **kwargs): input_formats = input_formats or DEFAULT_DATE_INPUT_FORMATS super(DateField, self).__init__(input_formats=input_formats, *args, **kwargs) class DateTimeField(forms.DateTimeField): """ A date and time input field which uses non-US date and time input formats by default. """ def __init__(self, input_formats=None, *args, **kwargs): input_formats = input_formats or DEFAULT_DATETIME_INPUT_FORMATS super(DateTimeField, self).__init__(input_formats=input_formats, *args, **kwargs) class SplitDateTimeField(forms.SplitDateTimeField): """ Split date and time input fields which use non-US date and time input formats by default. """ def __init__(self, input_date_formats=None, input_time_formats=None, *args, **kwargs): input_date_formats = input_date_formats or DEFAULT_DATE_INPUT_FORMATS super(SplitDateTimeField, self).__init__(input_date_formats=input_date_formats, input_time_formats=input_time_formats, *args, **kwargs)
2,160
Python
.py
43
44.255814
104
0.554451
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,638
pl_administrativeunits.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/pl/pl_administrativeunits.py
# -*- coding: utf-8 -*- """ Polish administrative units as in http://pl.wikipedia.org/wiki/Podzia%C5%82_administracyjny_Polski """ ADMINISTRATIVE_UNIT_CHOICES = ( ('wroclaw', u'Wrocław'), ('jeleniagora', u'Jelenia Góra'), ('legnica', u'Legnica'), ('boleslawiecki', u'bolesławiecki'), ('dzierzoniowski', u'dzierżoniowski'), ('glogowski', u'głogowski'), ('gorowski', u'górowski'), ('jaworski', u'jaworski'), ('jeleniogorski', u'jeleniogórski'), ('kamiennogorski', u'kamiennogórski'), ('klodzki', u'kłodzki'), ('legnicki', u'legnicki'), ('lubanski', u'lubański'), ('lubinski', u'lubiński'), ('lwowecki', u'lwówecki'), ('milicki', u'milicki'), ('olesnicki', u'oleśnicki'), ('olawski', u'oławski'), ('polkowicki', u'polkowicki'), ('strzelinski', u'strzeliński'), ('sredzki', u'średzki'), ('swidnicki', u'świdnicki'), ('trzebnicki', u'trzebnicki'), ('walbrzyski', u'wałbrzyski'), ('wolowski', u'wołowski'), ('wroclawski', u'wrocławski'), ('zabkowicki', u'ząbkowicki'), ('zgorzelecki', u'zgorzelecki'), ('zlotoryjski', u'złotoryjski'), ('bydgoszcz', u'Bydgoszcz'), ('torun', u'Toruń'), ('wloclawek', u'Włocławek'), ('grudziadz', u'Grudziądz'), ('aleksandrowski', u'aleksandrowski'), ('brodnicki', u'brodnicki'), ('bydgoski', u'bydgoski'), ('chelminski', u'chełmiński'), ('golubsko-dobrzynski', u'golubsko-dobrzyński'), ('grudziadzki', u'grudziądzki'), ('inowroclawski', u'inowrocławski'), ('lipnowski', u'lipnowski'), ('mogilenski', u'mogileński'), ('nakielski', u'nakielski'), ('radziejowski', u'radziejowski'), ('rypinski', u'rypiński'), ('sepolenski', u'sępoleński'), ('swiecki', u'świecki'), ('torunski', u'toruński'), ('tucholski', u'tucholski'), ('wabrzeski', u'wąbrzeski'), ('wloclawski', u'wrocławski'), ('zninski', u'źniński'), ('lublin', u'Lublin'), ('biala-podlaska', u'Biała Podlaska'), ('chelm', u'Chełm'), ('zamosc', u'Zamość'), ('bialski', u'bialski'), ('bilgorajski', u'biłgorajski'), ('chelmski', u'chełmski'), ('hrubieszowski', u'hrubieszowski'), ('janowski', u'janowski'), ('krasnostawski', u'krasnostawski'), ('krasnicki', u'kraśnicki'), ('lubartowski', u'lubartowski'), ('lubelski', u'lubelski'), ('leczynski', u'łęczyński'), ('lukowski', u'łukowski'), ('opolski', u'opolski'), ('parczewski', u'parczewski'), ('pulawski', u'puławski'), ('radzynski', u'radzyński'), ('rycki', u'rycki'), ('swidnicki', u'świdnicki'), ('tomaszowski', u'tomaszowski'), ('wlodawski', u'włodawski'), ('zamojski', u'zamojski'), ('gorzow-wielkopolski', u'Gorzów Wielkopolski'), ('zielona-gora', u'Zielona Góra'), ('gorzowski', u'gorzowski'), ('krosnienski', u'krośnieński'), ('miedzyrzecki', u'międzyrzecki'), ('nowosolski', u'nowosolski'), ('slubicki', u'słubicki'), ('strzelecko-drezdenecki', u'strzelecko-drezdenecki'), ('sulecinski', u'suleńciński'), ('swiebodzinski', u'świebodziński'), ('wschowski', u'wschowski'), ('zielonogorski', u'zielonogórski'), ('zaganski', u'żagański'), ('zarski', u'żarski'), ('lodz', u'Łódź'), ('piotrkow-trybunalski', u'Piotrków Trybunalski'), ('skierniewice', u'Skierniewice'), ('belchatowski', u'bełchatowski'), ('brzezinski', u'brzeziński'), ('kutnowski', u'kutnowski'), ('laski', u'łaski'), ('leczycki', u'łęczycki'), ('lowicki', u'łowicki'), ('lodzki wschodni', u'łódzki wschodni'), ('opoczynski', u'opoczyński'), ('pabianicki', u'pabianicki'), ('pajeczanski', u'pajęczański'), ('piotrkowski', u'piotrkowski'), ('poddebicki', u'poddębicki'), ('radomszczanski', u'radomszczański'), ('rawski', u'rawski'), ('sieradzki', u'sieradzki'), ('skierniewicki', u'skierniewicki'), ('tomaszowski', u'tomaszowski'), ('wielunski', u'wieluński'), ('wieruszowski', u'wieruszowski'), ('zdunskowolski', u'zduńskowolski'), ('zgierski', u'zgierski'), ('krakow', u'Kraków'), ('tarnow', u'Tarnów'), ('nowy-sacz', u'Nowy Sącz'), ('bochenski', u'bocheński'), ('brzeski', u'brzeski'), ('chrzanowski', u'chrzanowski'), ('dabrowski', u'dąbrowski'), ('gorlicki', u'gorlicki'), ('krakowski', u'krakowski'), ('limanowski', u'limanowski'), ('miechowski', u'miechowski'), ('myslenicki', u'myślenicki'), ('nowosadecki', u'nowosądecki'), ('nowotarski', u'nowotarski'), ('olkuski', u'olkuski'), ('oswiecimski', u'oświęcimski'), ('proszowicki', u'proszowicki'), ('suski', u'suski'), ('tarnowski', u'tarnowski'), ('tatrzanski', u'tatrzański'), ('wadowicki', u'wadowicki'), ('wielicki', u'wielicki'), ('warszawa', u'Warszawa'), ('ostroleka', u'Ostrołęka'), ('plock', u'Płock'), ('radom', u'Radom'), ('siedlce', u'Siedlce'), ('bialobrzeski', u'białobrzeski'), ('ciechanowski', u'ciechanowski'), ('garwolinski', u'garwoliński'), ('gostyninski', u'gostyniński'), ('grodziski', u'grodziski'), ('grojecki', u'grójecki'), ('kozienicki', u'kozenicki'), ('legionowski', u'legionowski'), ('lipski', u'lipski'), ('losicki', u'łosicki'), ('makowski', u'makowski'), ('minski', u'miński'), ('mlawski', u'mławski'), ('nowodworski', u'nowodworski'), ('ostrolecki', u'ostrołęcki'), ('ostrowski', u'ostrowski'), ('otwocki', u'otwocki'), ('piaseczynski', u'piaseczyński'), ('plocki', u'płocki'), ('plonski', u'płoński'), ('pruszkowski', u'pruszkowski'), ('przasnyski', u'przasnyski'), ('przysuski', u'przysuski'), ('pultuski', u'pułtuski'), ('radomski', u'radomski'), ('siedlecki', u'siedlecki'), ('sierpecki', u'sierpecki'), ('sochaczewski', u'sochaczewski'), ('sokolowski', u'sokołowski'), ('szydlowiecki', u'szydłowiecki'), ('warszawski-zachodni', u'warszawski zachodni'), ('wegrowski', u'węgrowski'), ('wolominski', u'wołomiński'), ('wyszkowski', u'wyszkowski'), ('zwolenski', u'zwoleński'), ('zurominski', u'żuromiński'), ('zyrardowski', u'żyrardowski'), ('opole', u'Opole'), ('brzeski', u'brzeski'), ('glubczycki', u'głubczyski'), ('kedzierzynsko-kozielski', u'kędzierzyński-kozielski'), ('kluczborski', u'kluczborski'), ('krapkowicki', u'krapkowicki'), ('namyslowski', u'namysłowski'), ('nyski', u'nyski'), ('oleski', u'oleski'), ('opolski', u'opolski'), ('prudnicki', u'prudnicki'), ('strzelecki', u'strzelecki'), ('rzeszow', u'Rzeszów'), ('krosno', u'Krosno'), ('przemysl', u'Przemyśl'), ('tarnobrzeg', u'Tarnobrzeg'), ('bieszczadzki', u'bieszczadzki'), ('brzozowski', u'brzozowski'), ('debicki', u'dębicki'), ('jaroslawski', u'jarosławski'), ('jasielski', u'jasielski'), ('kolbuszowski', u'kolbuszowski'), ('krosnienski', u'krośnieński'), ('leski', u'leski'), ('lezajski', u'leżajski'), ('lubaczowski', u'lubaczowski'), ('lancucki', u'łańcucki'), ('mielecki', u'mielecki'), ('nizanski', u'niżański'), ('przemyski', u'przemyski'), ('przeworski', u'przeworski'), ('ropczycko-sedziszowski', u'ropczycko-sędziszowski'), ('rzeszowski', u'rzeszowski'), ('sanocki', u'sanocki'), ('stalowowolski', u'stalowowolski'), ('strzyzowski', u'strzyżowski'), ('tarnobrzeski', u'tarnobrzeski'), ('bialystok', u'Białystok'), ('lomza', u'Łomża'), ('suwalki', u'Suwałki'), ('augustowski', u'augustowski'), ('bialostocki', u'białostocki'), ('bielski', u'bielski'), ('grajewski', u'grajewski'), ('hajnowski', u'hajnowski'), ('kolnenski', u'kolneński'), ('łomzynski', u'łomżyński'), ('moniecki', u'moniecki'), ('sejnenski', u'sejneński'), ('siemiatycki', u'siematycki'), ('sokolski', u'sokólski'), ('suwalski', u'suwalski'), ('wysokomazowiecki', u'wysokomazowiecki'), ('zambrowski', u'zambrowski'), ('gdansk', u'Gdańsk'), ('gdynia', u'Gdynia'), ('slupsk', u'Słupsk'), ('sopot', u'Sopot'), ('bytowski', u'bytowski'), ('chojnicki', u'chojnicki'), ('czluchowski', u'człuchowski'), ('kartuski', u'kartuski'), ('koscierski', u'kościerski'), ('kwidzynski', u'kwidzyński'), ('leborski', u'lęborski'), ('malborski', u'malborski'), ('nowodworski', u'nowodworski'), ('gdanski', u'gdański'), ('pucki', u'pucki'), ('slupski', u'słupski'), ('starogardzki', u'starogardzki'), ('sztumski', u'sztumski'), ('tczewski', u'tczewski'), ('wejherowski', u'wejcherowski'), ('katowice', u'Katowice'), ('bielsko-biala', u'Bielsko-Biała'), ('bytom', u'Bytom'), ('chorzow', u'Chorzów'), ('czestochowa', u'Częstochowa'), ('dabrowa-gornicza', u'Dąbrowa Górnicza'), ('gliwice', u'Gliwice'), ('jastrzebie-zdroj', u'Jastrzębie Zdrój'), ('jaworzno', u'Jaworzno'), ('myslowice', u'Mysłowice'), ('piekary-slaskie', u'Piekary Śląskie'), ('ruda-slaska', u'Ruda Śląska'), ('rybnik', u'Rybnik'), ('siemianowice-slaskie', u'Siemianowice Śląskie'), ('sosnowiec', u'Sosnowiec'), ('swietochlowice', u'Świętochłowice'), ('tychy', u'Tychy'), ('zabrze', u'Zabrze'), ('zory', u'Żory'), ('bedzinski', u'będziński'), ('bielski', u'bielski'), ('bierunsko-ledzinski', u'bieruńsko-lędziński'), ('cieszynski', u'cieszyński'), ('czestochowski', u'częstochowski'), ('gliwicki', u'gliwicki'), ('klobucki', u'kłobucki'), ('lubliniecki', u'lubliniecki'), ('mikolowski', u'mikołowski'), ('myszkowski', u'myszkowski'), ('pszczynski', u'pszczyński'), ('raciborski', u'raciborski'), ('rybnicki', u'rybnicki'), ('tarnogorski', u'tarnogórski'), ('wodzislawski', u'wodzisławski'), ('zawiercianski', u'zawierciański'), ('zywiecki', u'żywiecki'), ('kielce', u'Kielce'), ('buski', u'buski'), ('jedrzejowski', u'jędrzejowski'), ('kazimierski', u'kazimierski'), ('kielecki', u'kielecki'), ('konecki', u'konecki'), ('opatowski', u'opatowski'), ('ostrowiecki', u'ostrowiecki'), ('pinczowski', u'pińczowski'), ('sandomierski', u'sandomierski'), ('skarzyski', u'skarżyski'), ('starachowicki', u'starachowicki'), ('staszowski', u'staszowski'), ('wloszczowski', u'włoszczowski'), ('olsztyn', u'Olsztyn'), ('elblag', u'Elbląg'), ('bartoszycki', u'bartoszycki'), ('braniewski', u'braniewski'), ('dzialdowski', u'działdowski'), ('elblaski', u'elbląski'), ('elcki', u'ełcki'), ('gizycki', u'giżycki'), ('goldapski', u'gołdapski'), ('ilawski', u'iławski'), ('ketrzynski', u'kętrzyński'), ('lidzbarski', u'lidzbarski'), ('mragowski', u'mrągowski'), ('nidzicki', u'nidzicki'), ('nowomiejski', u'nowomiejski'), ('olecki', u'olecki'), ('olsztynski', u'olsztyński'), ('ostrodzki', u'ostródzki'), ('piski', u'piski'), ('szczycienski', u'szczycieński'), ('wegorzewski', u'węgorzewski'), ('poznan', u'Poznań'), ('kalisz', u'Kalisz'), ('konin', u'Konin'), ('leszno', u'Leszno'), ('chodzieski', u'chodziejski'), ('czarnkowsko-trzcianecki', u'czarnkowsko-trzcianecki'), ('gnieznienski', u'gnieźnieński'), ('gostynski', u'gostyński'), ('grodziski', u'grodziski'), ('jarocinski', u'jarociński'), ('kaliski', u'kaliski'), ('kepinski', u'kępiński'), ('kolski', u'kolski'), ('koninski', u'koniński'), ('koscianski', u'kościański'), ('krotoszynski', u'krotoszyński'), ('leszczynski', u'leszczyński'), ('miedzychodzki', u'międzychodzki'), ('nowotomyski', u'nowotomyski'), ('obornicki', u'obornicki'), ('ostrowski', u'ostrowski'), ('ostrzeszowski', u'ostrzeszowski'), ('pilski', u'pilski'), ('pleszewski', u'pleszewski'), ('poznanski', u'poznański'), ('rawicki', u'rawicki'), ('slupecki', u'słupecki'), ('szamotulski', u'szamotulski'), ('sredzki', u'średzki'), ('sremski', u'śremski'), ('turecki', u'turecki'), ('wagrowiecki', u'wągrowiecki'), ('wolsztynski', u'wolsztyński'), ('wrzesinski', u'wrzesiński'), ('zlotowski', u'złotowski'), ('bialogardzki', u'białogardzki'), ('choszczenski', u'choszczeński'), ('drawski', u'drawski'), ('goleniowski', u'goleniowski'), ('gryficki', u'gryficki'), ('gryfinski', u'gryfiński'), ('kamienski', u'kamieński'), ('kolobrzeski', u'kołobrzeski'), ('koszalinski', u'koszaliński'), ('lobeski', u'łobeski'), ('mysliborski', u'myśliborski'), ('policki', u'policki'), ('pyrzycki', u'pyrzycki'), ('slawienski', u'sławieński'), ('stargardzki', u'stargardzki'), ('szczecinecki', u'szczecinecki'), ('swidwinski', u'świdwiński'), ('walecki', u'wałecki'), )
13,194
Python
.py
382
28.950262
98
0.604473
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,639
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/pl/forms.py
""" Polish-specific form helpers """ import re from django.forms import ValidationError from django.forms.fields import Select, RegexField from django.utils.translation import ugettext_lazy as _ from django.core.validators import EMPTY_VALUES class PLProvinceSelect(Select): """ A select widget with list of Polish administrative provinces as choices. """ def __init__(self, attrs=None): from pl_voivodeships import VOIVODESHIP_CHOICES super(PLProvinceSelect, self).__init__(attrs, choices=VOIVODESHIP_CHOICES) class PLCountySelect(Select): """ A select widget with list of Polish administrative units as choices. """ def __init__(self, attrs=None): from pl_administrativeunits import ADMINISTRATIVE_UNIT_CHOICES super(PLCountySelect, self).__init__(attrs, choices=ADMINISTRATIVE_UNIT_CHOICES) class PLPESELField(RegexField): """ A form field that validates as Polish Identification Number (PESEL). Checks the following rules: * the length consist of 11 digits * has a valid checksum The algorithm is documented at http://en.wikipedia.org/wiki/PESEL. """ default_error_messages = { 'invalid': _(u'National Identification Number consists of 11 digits.'), 'checksum': _(u'Wrong checksum for the National Identification Number.'), } def __init__(self, *args, **kwargs): super(PLPESELField, self).__init__(r'^\d{11}$', max_length=None, min_length=None, *args, **kwargs) def clean(self,value): super(PLPESELField, self).clean(value) if value in EMPTY_VALUES: return u'' if not self.has_valid_checksum(value): raise ValidationError(self.error_messages['checksum']) return u'%s' % value def has_valid_checksum(self, number): """ Calculates a checksum with the provided algorithm. """ multiple_table = (1, 3, 7, 9, 1, 3, 7, 9, 1, 3, 1) result = 0 for i in range(len(number)): result += int(number[i]) * multiple_table[i] return result % 10 == 0 class PLNIPField(RegexField): """ A form field that validates as Polish Tax Number (NIP). Valid forms are: XXX-XXX-YY-YY or XX-XX-YYY-YYY. Checksum algorithm based on documentation at http://wipos.p.lodz.pl/zylla/ut/nip-rego.html """ default_error_messages = { 'invalid': _(u'Enter a tax number field (NIP) in the format XXX-XXX-XX-XX or XX-XX-XXX-XXX.'), 'checksum': _(u'Wrong checksum for the Tax Number (NIP).'), } def __init__(self, *args, **kwargs): super(PLNIPField, self).__init__(r'^\d{3}-\d{3}-\d{2}-\d{2}$|^\d{2}-\d{2}-\d{3}-\d{3}$', max_length=None, min_length=None, *args, **kwargs) def clean(self,value): super(PLNIPField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub("[-]", "", value) if not self.has_valid_checksum(value): raise ValidationError(self.error_messages['checksum']) return u'%s' % value def has_valid_checksum(self, number): """ Calculates a checksum with the provided algorithm. """ multiple_table = (6, 5, 7, 2, 3, 4, 5, 6, 7) result = 0 for i in range(len(number)-1): result += int(number[i]) * multiple_table[i] result %= 11 if result == int(number[-1]): return True else: return False class PLREGONField(RegexField): """ A form field that validates its input is a REGON number. Valid regon number consists of 9 or 14 digits. See http://www.stat.gov.pl/bip/regon_ENG_HTML.htm for more information. """ default_error_messages = { 'invalid': _(u'National Business Register Number (REGON) consists of 9 or 14 digits.'), 'checksum': _(u'Wrong checksum for the National Business Register Number (REGON).'), } def __init__(self, *args, **kwargs): super(PLREGONField, self).__init__(r'^\d{9,14}$', max_length=None, min_length=None, *args, **kwargs) def clean(self,value): super(PLREGONField, self).clean(value) if value in EMPTY_VALUES: return u'' if not self.has_valid_checksum(value): raise ValidationError(self.error_messages['checksum']) return u'%s' % value def has_valid_checksum(self, number): """ Calculates a checksum with the provided algorithm. """ weights = ( (8, 9, 2, 3, 4, 5, 6, 7, -1), (2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8, -1), (8, 9, 2, 3, 4, 5, 6, 7, -1, 0, 0, 0, 0, 0), ) weights = [table for table in weights if len(table) == len(number)] for table in weights: checksum = sum([int(n) * w for n, w in zip(number, table)]) if checksum % 11 % 10: return False return bool(weights) class PLPostalCodeField(RegexField): """ A form field that validates as Polish postal code. Valid code is XX-XXX where X is digit. """ default_error_messages = { 'invalid': _(u'Enter a postal code in the format XX-XXX.'), } def __init__(self, *args, **kwargs): super(PLPostalCodeField, self).__init__(r'^\d{2}-\d{3}$', max_length=None, min_length=None, *args, **kwargs)
5,444
Python
.py
134
33.014925
102
0.611279
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,640
pl_voivodeships.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/pl/pl_voivodeships.py
""" Polish voivodeship as in http://en.wikipedia.org/wiki/Poland#Administrative_division """ from django.utils.translation import ugettext_lazy as _ VOIVODESHIP_CHOICES = ( ('lower_silesia', _('Lower Silesia')), ('kuyavia-pomerania', _('Kuyavia-Pomerania')), ('lublin', _('Lublin')), ('lubusz', _('Lubusz')), ('lodz', _('Lodz')), ('lesser_poland', _('Lesser Poland')), ('masovia', _('Masovia')), ('opole', _('Opole')), ('subcarpatia', _('Subcarpatia')), ('podlasie', _('Podlasie')), ('pomerania', _('Pomerania')), ('silesia', _('Silesia')), ('swietokrzyskie', _('Swietokrzyskie')), ('warmia-masuria', _('Warmia-Masuria')), ('greater_poland', _('Greater Poland')), ('west_pomerania', _('West Pomerania')), )
773
Python
.py
22
31.136364
84
0.596796
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,641
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/us/models.py
from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.db.models.fields import CharField from django.contrib.localflavor.us.us_states import STATE_CHOICES from django.contrib.localflavor.us.us_states import USPS_CHOICES class USStateField(CharField): description = _("U.S. state (two uppercase letters)") def __init__(self, *args, **kwargs): kwargs['choices'] = STATE_CHOICES kwargs['max_length'] = 2 super(USStateField, self).__init__(*args, **kwargs) class USPostalCodeField(CharField): description = _("U.S. postal code (two uppercase letters)") def __init__(self, *args, **kwargs): kwargs['choices'] = USPS_CHOICES kwargs['max_length'] = 2 super(USPostalCodeField, self).__init__(*args, **kwargs) class PhoneNumberField(CharField): description = _("Phone number") def __init__(self, *args, **kwargs): kwargs['max_length'] = 20 super(PhoneNumberField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): from django.contrib.localflavor.us.forms import USPhoneNumberField defaults = {'form_class': USPhoneNumberField} defaults.update(kwargs) return super(PhoneNumberField, self).formfield(**defaults)
1,294
Python
.py
27
41.962963
74
0.69292
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,642
us_states.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/us/us_states.py
""" A mapping of state misspellings/abbreviations to normalized abbreviations, and alphabetical lists of US states, territories, military mail regions and non-US states to which the US provides postal service. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ # The 48 contiguous states, plus the District of Columbia. CONTIGUOUS_STATES = ( ('AL', 'Alabama'), ('AZ', 'Arizona'), ('AR', 'Arkansas'), ('CA', 'California'), ('CO', 'Colorado'), ('CT', 'Connecticut'), ('DE', 'Delaware'), ('DC', 'District of Columbia'), ('FL', 'Florida'), ('GA', 'Georgia'), ('ID', 'Idaho'), ('IL', 'Illinois'), ('IN', 'Indiana'), ('IA', 'Iowa'), ('KS', 'Kansas'), ('KY', 'Kentucky'), ('LA', 'Louisiana'), ('ME', 'Maine'), ('MD', 'Maryland'), ('MA', 'Massachusetts'), ('MI', 'Michigan'), ('MN', 'Minnesota'), ('MS', 'Mississippi'), ('MO', 'Missouri'), ('MT', 'Montana'), ('NE', 'Nebraska'), ('NV', 'Nevada'), ('NH', 'New Hampshire'), ('NJ', 'New Jersey'), ('NM', 'New Mexico'), ('NY', 'New York'), ('NC', 'North Carolina'), ('ND', 'North Dakota'), ('OH', 'Ohio'), ('OK', 'Oklahoma'), ('OR', 'Oregon'), ('PA', 'Pennsylvania'), ('RI', 'Rhode Island'), ('SC', 'South Carolina'), ('SD', 'South Dakota'), ('TN', 'Tennessee'), ('TX', 'Texas'), ('UT', 'Utah'), ('VT', 'Vermont'), ('VA', 'Virginia'), ('WA', 'Washington'), ('WV', 'West Virginia'), ('WI', 'Wisconsin'), ('WY', 'Wyoming'), ) # All 50 states, plus the District of Columbia. US_STATES = ( ('AL', 'Alabama'), ('AK', 'Alaska'), ('AZ', 'Arizona'), ('AR', 'Arkansas'), ('CA', 'California'), ('CO', 'Colorado'), ('CT', 'Connecticut'), ('DE', 'Delaware'), ('DC', 'District of Columbia'), ('FL', 'Florida'), ('GA', 'Georgia'), ('HI', 'Hawaii'), ('ID', 'Idaho'), ('IL', 'Illinois'), ('IN', 'Indiana'), ('IA', 'Iowa'), ('KS', 'Kansas'), ('KY', 'Kentucky'), ('LA', 'Louisiana'), ('ME', 'Maine'), ('MD', 'Maryland'), ('MA', 'Massachusetts'), ('MI', 'Michigan'), ('MN', 'Minnesota'), ('MS', 'Mississippi'), ('MO', 'Missouri'), ('MT', 'Montana'), ('NE', 'Nebraska'), ('NV', 'Nevada'), ('NH', 'New Hampshire'), ('NJ', 'New Jersey'), ('NM', 'New Mexico'), ('NY', 'New York'), ('NC', 'North Carolina'), ('ND', 'North Dakota'), ('OH', 'Ohio'), ('OK', 'Oklahoma'), ('OR', 'Oregon'), ('PA', 'Pennsylvania'), ('RI', 'Rhode Island'), ('SC', 'South Carolina'), ('SD', 'South Dakota'), ('TN', 'Tennessee'), ('TX', 'Texas'), ('UT', 'Utah'), ('VT', 'Vermont'), ('VA', 'Virginia'), ('WA', 'Washington'), ('WV', 'West Virginia'), ('WI', 'Wisconsin'), ('WY', 'Wyoming'), ) # Non-state territories. US_TERRITORIES = ( ('AS', 'American Samoa'), ('GU', 'Guam'), ('MP', 'Northern Mariana Islands'), ('PR', 'Puerto Rico'), ('VI', 'Virgin Islands'), ) # Military postal "states". Note that 'AE' actually encompasses # Europe, Canada, Africa and the Middle East. ARMED_FORCES_STATES = ( ('AA', 'Armed Forces Americas'), ('AE', 'Armed Forces Europe'), ('AP', 'Armed Forces Pacific'), ) # Non-US locations serviced by USPS (under Compact of Free # Association). COFA_STATES = ( ('FM', 'Federated States of Micronesia'), ('MH', 'Marshall Islands'), ('PW', 'Palau'), ) # Obsolete abbreviations (no longer US territories/USPS service, or # code changed). OBSOLETE_STATES = ( ('CM', 'Commonwealth of the Northern Mariana Islands'), # Is now 'MP' ('CZ', 'Panama Canal Zone'), # Reverted to Panama 1979 ('PI', 'Philippine Islands'), # Philippine independence 1946 ('TT', 'Trust Territory of the Pacific Islands'), # Became the independent COFA states + Northern Mariana Islands 1979-1994 ) # All US states and territories plus DC and military mail. STATE_CHOICES = tuple(sorted(US_STATES + US_TERRITORIES + ARMED_FORCES_STATES, key=lambda obj: obj[1])) # All US Postal Service locations. USPS_CHOICES = tuple(sorted(US_STATES + US_TERRITORIES + ARMED_FORCES_STATES + COFA_STATES, key=lambda obj: obj[1])) STATES_NORMALIZED = { 'ak': 'AK', 'al': 'AL', 'ala': 'AL', 'alabama': 'AL', 'alaska': 'AK', 'american samao': 'AS', 'american samoa': 'AS', 'ar': 'AR', 'ariz': 'AZ', 'arizona': 'AZ', 'ark': 'AR', 'arkansas': 'AR', 'as': 'AS', 'az': 'AZ', 'ca': 'CA', 'calf': 'CA', 'calif': 'CA', 'california': 'CA', 'co': 'CO', 'colo': 'CO', 'colorado': 'CO', 'conn': 'CT', 'connecticut': 'CT', 'ct': 'CT', 'dc': 'DC', 'de': 'DE', 'del': 'DE', 'delaware': 'DE', 'deleware': 'DE', 'district of columbia': 'DC', 'fl': 'FL', 'fla': 'FL', 'florida': 'FL', 'ga': 'GA', 'georgia': 'GA', 'gu': 'GU', 'guam': 'GU', 'hawaii': 'HI', 'hi': 'HI', 'ia': 'IA', 'id': 'ID', 'idaho': 'ID', 'il': 'IL', 'ill': 'IL', 'illinois': 'IL', 'in': 'IN', 'ind': 'IN', 'indiana': 'IN', 'iowa': 'IA', 'kan': 'KS', 'kans': 'KS', 'kansas': 'KS', 'kentucky': 'KY', 'ks': 'KS', 'ky': 'KY', 'la': 'LA', 'louisiana': 'LA', 'ma': 'MA', 'maine': 'ME', 'marianas islands': 'MP', 'marianas islands of the pacific': 'MP', 'marinas islands of the pacific': 'MP', 'maryland': 'MD', 'mass': 'MA', 'massachusetts': 'MA', 'massachussetts': 'MA', 'md': 'MD', 'me': 'ME', 'mi': 'MI', 'mich': 'MI', 'michigan': 'MI', 'minn': 'MN', 'minnesota': 'MN', 'miss': 'MS', 'mississippi': 'MS', 'missouri': 'MO', 'mn': 'MN', 'mo': 'MO', 'mont': 'MT', 'montana': 'MT', 'mp': 'MP', 'ms': 'MS', 'mt': 'MT', 'n d': 'ND', 'n dak': 'ND', 'n h': 'NH', 'n j': 'NJ', 'n m': 'NM', 'n mex': 'NM', 'nc': 'NC', 'nd': 'ND', 'ne': 'NE', 'neb': 'NE', 'nebr': 'NE', 'nebraska': 'NE', 'nev': 'NV', 'nevada': 'NV', 'new hampshire': 'NH', 'new jersey': 'NJ', 'new mexico': 'NM', 'new york': 'NY', 'nh': 'NH', 'nj': 'NJ', 'nm': 'NM', 'nmex': 'NM', 'north carolina': 'NC', 'north dakota': 'ND', 'northern mariana islands': 'MP', 'nv': 'NV', 'ny': 'NY', 'oh': 'OH', 'ohio': 'OH', 'ok': 'OK', 'okla': 'OK', 'oklahoma': 'OK', 'or': 'OR', 'ore': 'OR', 'oreg': 'OR', 'oregon': 'OR', 'pa': 'PA', 'penn': 'PA', 'pennsylvania': 'PA', 'pr': 'PR', 'puerto rico': 'PR', 'rhode island': 'RI', 'ri': 'RI', 's dak': 'SD', 'sc': 'SC', 'sd': 'SD', 'sdak': 'SD', 'south carolina': 'SC', 'south dakota': 'SD', 'tenn': 'TN', 'tennessee': 'TN', 'territory of hawaii': 'HI', 'tex': 'TX', 'texas': 'TX', 'tn': 'TN', 'tx': 'TX', 'us virgin islands': 'VI', 'usvi': 'VI', 'ut': 'UT', 'utah': 'UT', 'va': 'VA', 'vermont': 'VT', 'vi': 'VI', 'viginia': 'VA', 'virgin islands': 'VI', 'virgina': 'VA', 'virginia': 'VA', 'vt': 'VT', 'w va': 'WV', 'wa': 'WA', 'wash': 'WA', 'washington': 'WA', 'west virginia': 'WV', 'wi': 'WI', 'wis': 'WI', 'wisc': 'WI', 'wisconsin': 'WI', 'wv': 'WV', 'wva': 'WV', 'wy': 'WY', 'wyo': 'WY', 'wyoming': 'WY', }
7,655
Python
.py
315
19.711111
133
0.488607
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,643
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/us/forms.py
""" USA-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select, CharField from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re phone_digits_re = re.compile(r'^(?:1-?)?(\d{3})[-\.]?(\d{3})[-\.]?(\d{4})$') ssn_re = re.compile(r"^(?P<area>\d{3})[-\ ]?(?P<group>\d{2})[-\ ]?(?P<serial>\d{4})$") class USZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a zip code in the format XXXXX or XXXXX-XXXX.'), } def __init__(self, *args, **kwargs): super(USZipCodeField, self).__init__(r'^\d{5}(?:-\d{4})?$', max_length=None, min_length=None, *args, **kwargs) class USPhoneNumberField(CharField): default_error_messages = { 'invalid': _('Phone numbers must be in XXX-XXX-XXXX format.'), } def clean(self, value): super(USPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\(|\)|\s+)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3)) raise ValidationError(self.error_messages['invalid']) class USSocialSecurityNumberField(Field): """ A United States Social Security number. Checks the following rules to determine whether the number is valid: * Conforms to the XXX-XX-XXXX format. * No group consists entirely of zeroes. * The leading group is not "666" (block "666" will never be allocated). * The number is not in the promotional block 987-65-4320 through 987-65-4329, which are permanently invalid. * The number is not one known to be invalid due to otherwise widespread promotional use or distribution (e.g., the Woolworth's number or the 1962 promotional number). """ default_error_messages = { 'invalid': _('Enter a valid U.S. Social Security number in XXX-XX-XXXX format.'), } def clean(self, value): super(USSocialSecurityNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' match = re.match(ssn_re, value) if not match: raise ValidationError(self.error_messages['invalid']) area, group, serial = match.groupdict()['area'], match.groupdict()['group'], match.groupdict()['serial'] # First pass: no blocks of all zeroes. if area == '000' or \ group == '00' or \ serial == '0000': raise ValidationError(self.error_messages['invalid']) # Second pass: promotional and otherwise permanently invalid numbers. if area == '666' or \ (area == '987' and group == '65' and 4320 <= int(serial) <= 4329) or \ value == '078-05-1120' or \ value == '219-09-9999': raise ValidationError(self.error_messages['invalid']) return u'%s-%s-%s' % (area, group, serial) class USStateField(Field): """ A form field that validates its input is a U.S. state name or abbreviation. It normalizes the input to the standard two-leter postal service abbreviation for the given state. """ default_error_messages = { 'invalid': _('Enter a U.S. state or territory.'), } def clean(self, value): from us_states import STATES_NORMALIZED super(USStateField, self).clean(value) if value in EMPTY_VALUES: return u'' try: value = value.strip().lower() except AttributeError: pass else: try: return STATES_NORMALIZED[value.strip().lower()].decode('ascii') except KeyError: pass raise ValidationError(self.error_messages['invalid']) class USStateSelect(Select): """ A Select widget that uses a list of U.S. states/territories as its choices. """ def __init__(self, attrs=None): from us_states import STATE_CHOICES super(USStateSelect, self).__init__(attrs, choices=STATE_CHOICES) class USPSSelect(Select): """ A Select widget that uses a list of US Postal Service codes as its choices. """ def __init__(self, attrs=None): from us_states import USPS_CHOICES super(USPSSelect, self).__init__(attrs, choices=USPS_CHOICES)
4,495
Python
.py
106
34.867925
112
0.625886
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,644
za_provinces.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/za/za_provinces.py
from django.utils.translation import gettext_lazy as _ PROVINCE_CHOICES = ( ('EC', _('Eastern Cape')), ('FS', _('Free State')), ('GP', _('Gauteng')), ('KN', _('KwaZulu-Natal')), ('LP', _('Limpopo')), ('MP', _('Mpumalanga')), ('NC', _('Northern Cape')), ('NW', _('North West')), ('WC', _('Western Cape')), )
344
Python
.py
12
24.583333
54
0.501511
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,645
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/za/forms.py
""" South Africa-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField from django.utils.checksums import luhn from django.utils.translation import gettext as _ import re from datetime import date id_re = re.compile(r'^(?P<yy>\d\d)(?P<mm>\d\d)(?P<dd>\d\d)(?P<mid>\d{4})(?P<end>\d{3})') class ZAIDField(Field): """A form field for South African ID numbers -- the checksum is validated using the Luhn checksum, and uses a simlistic (read: not entirely accurate) check for the birthdate """ default_error_messages = { 'invalid': _(u'Enter a valid South African ID number'), } def clean(self, value): super(ZAIDField, self).clean(value) if value in EMPTY_VALUES: return u'' # strip spaces and dashes value = value.strip().replace(' ', '').replace('-', '') match = re.match(id_re, value) if not match: raise ValidationError(self.error_messages['invalid']) g = match.groupdict() try: # The year 2000 is conveniently a leapyear. # This algorithm will break in xx00 years which aren't leap years # There is no way to guess the century of a ZA ID number d = date(int(g['yy']) + 2000, int(g['mm']), int(g['dd'])) except ValueError: raise ValidationError(self.error_messages['invalid']) if not luhn(value): raise ValidationError(self.error_messages['invalid']) return value class ZAPostCodeField(RegexField): default_error_messages = { 'invalid': _(u'Enter a valid South African postal code'), } def __init__(self, *args, **kwargs): super(ZAPostCodeField, self).__init__(r'^\d{4}$', max_length=None, min_length=None, *args, **kwargs)
1,908
Python
.py
46
34.521739
88
0.641775
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,646
au_states.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/au/au_states.py
""" An alphabetical list of states for use as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ STATE_CHOICES = ( ('ACT', 'Australian Capital Territory'), ('NSW', 'New South Wales'), ('NT', 'Northern Territory'), ('QLD', 'Queensland'), ('SA', 'South Australia'), ('TAS', 'Tasmania'), ('VIC', 'Victoria'), ('WA', 'Western Australia'), )
449
Python
.py
15
26.666667
74
0.645833
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,647
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/au/forms.py
""" Australian-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re PHONE_DIGITS_RE = re.compile(r'^(\d{10})$') class AUPostCodeField(RegexField): """Australian post code field.""" default_error_messages = { 'invalid': _('Enter a 4 digit post code.'), } def __init__(self, *args, **kwargs): super(AUPostCodeField, self).__init__(r'^\d{4}$', max_length=None, min_length=None, *args, **kwargs) class AUPhoneNumberField(Field): """Australian phone number field.""" default_error_messages = { 'invalid': u'Phone numbers must contain 10 digits.', } def clean(self, value): """ Validate a phone number. Strips parentheses, whitespace and hyphens. """ super(AUPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\(|\)|\s+|-)', '', smart_unicode(value)) phone_match = PHONE_DIGITS_RE.search(value) if phone_match: return u'%s' % phone_match.group(1) raise ValidationError(self.error_messages['invalid']) class AUStateSelect(Select): """ A Select widget that uses a list of Australian states/territories as its choices. """ def __init__(self, attrs=None): from au_states import STATE_CHOICES super(AUStateSelect, self).__init__(attrs, choices=STATE_CHOICES)
1,629
Python
.py
43
32.069767
76
0.663078
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,648
br_states.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/br/br_states.py
# -*- coding: utf-8 -*- """ An alphabetical list of Brazilian states for use as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ STATE_CHOICES = ( ('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', u'Amapá'), ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', u'Ceará'), ('DF', 'Distrito Federal'), ('ES', u'Espírito Santo'), ('GO', u'Goiás'), ('MA', u'Maranhão'), ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'), ('PA', u'Pará'), ('PB', u'Paraíba'), ('PR', u'Paraná'), ('PE', 'Pernambuco'), ('PI', u'Piauí'), ('RJ', 'Rio de Janeiro'), ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'), ('RO', u'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'), ('SP', u'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins'), )
939
Python
.py
35
22.371429
77
0.52413
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,649
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/br/forms.py
# -*- coding: utf-8 -*- """ BR-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, CharField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re phone_digits_re = re.compile(r'^(\d{2})[-\.]?(\d{4})[-\.]?(\d{4})$') class BRZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a zip code in the format XXXXX-XXX.'), } def __init__(self, *args, **kwargs): super(BRZipCodeField, self).__init__(r'^\d{5}-\d{3}$', max_length=None, min_length=None, *args, **kwargs) class BRPhoneNumberField(Field): default_error_messages = { 'invalid': _('Phone numbers must be in XX-XXXX-XXXX format.'), } def clean(self, value): super(BRPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\(|\)|\s+)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3)) raise ValidationError(self.error_messages['invalid']) class BRStateSelect(Select): """ A Select widget that uses a list of Brazilian states/territories as its choices. """ def __init__(self, attrs=None): from br_states import STATE_CHOICES super(BRStateSelect, self).__init__(attrs, choices=STATE_CHOICES) class BRStateChoiceField(Field): """ A choice field that uses a list of Brazilian states as its choices. """ widget = Select default_error_messages = { 'invalid': _(u'Select a valid brazilian state. That state is not one of the available states.'), } def __init__(self, required=True, widget=None, label=None, initial=None, help_text=None): super(BRStateChoiceField, self).__init__(required, widget, label, initial, help_text) from br_states import STATE_CHOICES self.widget.choices = STATE_CHOICES def clean(self, value): value = super(BRStateChoiceField, self).clean(value) if value in EMPTY_VALUES: value = u'' value = smart_unicode(value) if value == u'': return value valid_values = set([smart_unicode(k) for k, v in self.widget.choices]) if value not in valid_values: raise ValidationError(self.error_messages['invalid']) return value def DV_maker(v): if v >= 2: return 11 - v return 0 class BRCPFField(CharField): """ This field validate a CPF number or a CPF string. A CPF number is compounded by XXX.XXX.XXX-VD. The two last digits are check digits. More information: http://en.wikipedia.org/wiki/Cadastro_de_Pessoas_F%C3%ADsicas """ default_error_messages = { 'invalid': _("Invalid CPF number."), 'max_digits': _("This field requires at most 11 digits or 14 characters."), 'digits_only': _("This field requires only numbers."), } def __init__(self, *args, **kwargs): super(BRCPFField, self).__init__(max_length=14, min_length=11, *args, **kwargs) def clean(self, value): """ Value can be either a string in the format XXX.XXX.XXX-XX or an 11-digit number. """ value = super(BRCPFField, self).clean(value) if value in EMPTY_VALUES: return u'' orig_value = value[:] if not value.isdigit(): value = re.sub("[-\.]", "", value) try: int(value) except ValueError: raise ValidationError(self.error_messages['digits_only']) if len(value) != 11: raise ValidationError(self.error_messages['max_digits']) orig_dv = value[-2:] new_1dv = sum([i * int(value[idx]) for idx, i in enumerate(range(10, 1, -1))]) new_1dv = DV_maker(new_1dv % 11) value = value[:-2] + str(new_1dv) + value[-1] new_2dv = sum([i * int(value[idx]) for idx, i in enumerate(range(11, 1, -1))]) new_2dv = DV_maker(new_2dv % 11) value = value[:-1] + str(new_2dv) if value[-2:] != orig_dv: raise ValidationError(self.error_messages['invalid']) return orig_value class BRCNPJField(Field): default_error_messages = { 'invalid': _("Invalid CNPJ number."), 'digits_only': _("This field requires only numbers."), 'max_digits': _("This field requires at least 14 digits"), } def clean(self, value): """ Value can be either a string in the format XX.XXX.XXX/XXXX-XX or a group of 14 characters. """ value = super(BRCNPJField, self).clean(value) if value in EMPTY_VALUES: return u'' orig_value = value[:] if not value.isdigit(): value = re.sub("[-/\.]", "", value) try: int(value) except ValueError: raise ValidationError(self.error_messages['digits_only']) if len(value) != 14: raise ValidationError(self.error_messages['max_digits']) orig_dv = value[-2:] new_1dv = sum([i * int(value[idx]) for idx, i in enumerate(range(5, 1, -1) + range(9, 1, -1))]) new_1dv = DV_maker(new_1dv % 11) value = value[:-2] + str(new_1dv) + value[-1] new_2dv = sum([i * int(value[idx]) for idx, i in enumerate(range(6, 1, -1) + range(9, 1, -1))]) new_2dv = DV_maker(new_2dv % 11) value = value[:-1] + str(new_2dv) if value[-2:] != orig_dv: raise ValidationError(self.error_messages['invalid']) return orig_value
5,803
Python
.py
142
32.830986
104
0.596277
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,650
se_counties.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/se/se_counties.py
# -*- coding: utf-8 -*- """ An alphabetical list of Swedish counties, sorted by codes. http://en.wikipedia.org/wiki/Counties_of_Sweden This exists in this standalone file so that it's only imported into memory when explicitly needed. """ from django.utils.translation import ugettext_lazy as _ COUNTY_CHOICES = ( ('AB', _(u'Stockholm')), ('AC', _(u'Västerbotten')), ('BD', _(u'Norrbotten')), ('C', _(u'Uppsala')), ('D', _(u'Södermanland')), ('E', _(u'Östergötland')), ('F', _(u'Jönköping')), ('G', _(u'Kronoberg')), ('H', _(u'Kalmar')), ('I', _(u'Gotland')), ('K', _(u'Blekinge')), ('M', _(u'Skåne')), ('N', _(u'Halland')), ('O', _(u'Västra Götaland')), ('S', _(u'Värmland')), ('T', _(u'Örebro')), ('U', _(u'Västmanland')), ('W', _(u'Dalarna')), ('X', _(u'Gävleborg')), ('Y', _(u'Västernorrland')), ('Z', _(u'Jämtland')), )
928
Python
.py
31
25.580645
74
0.537058
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,651
utils.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/se/utils.py
import re import datetime def id_number_checksum(gd): """ Calculates a Swedish ID number checksum, using the "Luhn"-algoritm """ n = s = 0 for c in (gd['year'] + gd['month'] + gd['day'] + gd['serial']): tmp = ((n % 2) and 1 or 2) * int(c) if tmp > 9: tmp = sum([int(i) for i in str(tmp)]) s += tmp n += 1 if (s % 10) == 0: return 0 return (((s / 10) + 1) * 10) - s def validate_id_birthday(gd, fix_coordination_number_day=True): """ Validates the birth_day and returns the datetime.date object for the birth_day. If the date is an invalid birth day, a ValueError will be raised. """ today = datetime.date.today() day = int(gd['day']) if fix_coordination_number_day and day > 60: day -= 60 if gd['century'] is None: # The century was not specified, and need to be calculated from todays date current_year = today.year year = int(today.strftime('%Y')) - int(today.strftime('%y')) + int(gd['year']) if ('%s%s%02d' % (gd['year'], gd['month'], day)) > today.strftime('%y%m%d'): year -= 100 # If the person is older than 100 years if gd['sign'] == '+': year -= 100 else: year = int(gd['century'] + gd['year']) # Make sure the year is valid # There are no swedish personal identity numbers where year < 1800 if year < 1800: raise ValueError # ValueError will be raise for invalid dates birth_day = datetime.date(year, int(gd['month']), day) # birth_day must not be in the future if birth_day > today: raise ValueError return birth_day def format_personal_id_number(birth_day, gd): # birth_day.strftime cannot be used, since it does not support dates < 1900 return unicode(str(birth_day.year) + gd['month'] + gd['day'] + gd['serial'] + gd['checksum']) def format_organisation_number(gd): if gd['century'] is None: century = '' else: century = gd['century'] return unicode(century + gd['year'] + gd['month'] + gd['day'] + gd['serial'] + gd['checksum']) def valid_organisation(gd): return gd['century'] in (None, 16) and \ int(gd['month']) >= 20 and \ gd['sign'] in (None, '-') and \ gd['year'][0] in ('2', '5', '7', '8', '9') # group identifier
2,398
Python
.py
62
31.83871
98
0.579084
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,652
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/se/forms.py
# -*- coding: utf-8 -*- """ Swedish specific Form helpers """ import re from django import forms from django.utils.translation import ugettext_lazy as _ from django.core.validators import EMPTY_VALUES from django.contrib.localflavor.se.utils import (id_number_checksum, validate_id_birthday, format_personal_id_number, valid_organisation, format_organisation_number) __all__ = ('SECountySelect', 'SEOrganisationNumberField', 'SEPersonalIdentityNumberField', 'SEPostalCodeField') SWEDISH_ID_NUMBER = re.compile(r'^(?P<century>\d{2})?(?P<year>\d{2})(?P<month>\d{2})(?P<day>\d{2})(?P<sign>[\-+])?(?P<serial>\d{3})(?P<checksum>\d)$') SE_POSTAL_CODE = re.compile(r'^[1-9]\d{2} ?\d{2}$') class SECountySelect(forms.Select): """ A Select form widget that uses a list of the Swedish counties (län) as its choices. The cleaned value is the official county code -- see http://en.wikipedia.org/wiki/Counties_of_Sweden for a list. """ def __init__(self, attrs=None): from se_counties import COUNTY_CHOICES super(SECountySelect, self).__init__(attrs=attrs, choices=COUNTY_CHOICES) class SEOrganisationNumberField(forms.CharField): """ A form field that validates input as a Swedish organisation number (organisationsnummer). It accepts the same input as SEPersonalIdentityField (for sole proprietorships (enskild firma). However, co-ordination numbers are not accepted. It also accepts ordinary Swedish organisation numbers with the format NNNNNNNNNN. The return value will be YYYYMMDDXXXX for sole proprietors, and NNNNNNNNNN for other organisations. """ default_error_messages = { 'invalid': _('Enter a valid Swedish organisation number.'), } def clean(self, value): value = super(SEOrganisationNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' match = SWEDISH_ID_NUMBER.match(value) if not match: raise forms.ValidationError(self.error_messages['invalid']) gd = match.groupdict() # Compare the calculated value with the checksum if id_number_checksum(gd) != int(gd['checksum']): raise forms.ValidationError(self.error_messages['invalid']) # First: check if this is a real organisation_number if valid_organisation(gd): return format_organisation_number(gd) # Is this a single properitor (enskild firma)? try: birth_day = validate_id_birthday(gd, False) return format_personal_id_number(birth_day, gd) except ValueError: raise forms.ValidationError(self.error_messages['invalid']) class SEPersonalIdentityNumberField(forms.CharField): """ A form field that validates input as a Swedish personal identity number (personnummer). The correct formats are YYYYMMDD-XXXX, YYYYMMDDXXXX, YYMMDD-XXXX, YYMMDDXXXX and YYMMDD+XXXX. A + indicates that the person is older than 100 years, which will be taken into consideration when the date is validated. The checksum will be calculated and checked. The birth date is checked to be a valid date. By default, co-ordination numbers (samordningsnummer) will be accepted. To only allow real personal identity numbers, pass the keyword argument coordination_number=False to the constructor. The cleaned value will always have the format YYYYMMDDXXXX. """ def __init__(self, coordination_number=True, *args, **kwargs): self.coordination_number = coordination_number super(SEPersonalIdentityNumberField, self).__init__(*args, **kwargs) default_error_messages = { 'invalid': _('Enter a valid Swedish personal identity number.'), 'coordination_number': _('Co-ordination numbers are not allowed.'), } def clean(self, value): value = super(SEPersonalIdentityNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' match = SWEDISH_ID_NUMBER.match(value) if match is None: raise forms.ValidationError(self.error_messages['invalid']) gd = match.groupdict() # compare the calculated value with the checksum if id_number_checksum(gd) != int(gd['checksum']): raise forms.ValidationError(self.error_messages['invalid']) # check for valid birthday try: birth_day = validate_id_birthday(gd) except ValueError: raise forms.ValidationError(self.error_messages['invalid']) # make sure that co-ordination numbers do not pass if not allowed if not self.coordination_number and int(gd['day']) > 60: raise forms.ValidationError(self.error_messages['coordination_number']) return format_personal_id_number(birth_day, gd) class SEPostalCodeField(forms.RegexField): """ A form field that validates input as a Swedish postal code (postnummer). Valid codes consist of five digits (XXXXX). The number can optionally be formatted with a space after the third digit (XXX XX). The cleaned value will never contain the space. """ default_error_messages = { 'invalid': _('Enter a Swedish postal code in the format XXXXX.'), } def __init__(self, *args, **kwargs): super(SEPostalCodeField, self).__init__(SE_POSTAL_CODE, *args, **kwargs) def clean(self, value): return super(SEPostalCodeField, self).clean(value).replace(' ', '')
5,623
Python
.py
117
40.452991
150
0.685772
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,653
fi_municipalities.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/fi/fi_municipalities.py
# -*- coding: utf-8 -*- """ An alphabetical list of Finnish municipalities for use as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ MUNICIPALITY_CHOICES = ( ('akaa', u"Akaa"), ('alajarvi', u"Alajärvi"), ('alavieska', u"Alavieska"), ('alavus', u"Alavus"), ('artjarvi', u"Artjärvi"), ('asikkala', u"Asikkala"), ('askola', u"Askola"), ('aura', u"Aura"), ('brando', u"Brändö"), ('eckero', u"Eckerö"), ('enonkoski', u"Enonkoski"), ('enontekio', u"Enontekiö"), ('espoo', u"Espoo"), ('eura', u"Eura"), ('eurajoki', u"Eurajoki"), ('evijarvi', u"Evijärvi"), ('finstrom', u"Finström"), ('forssa', u"Forssa"), ('foglo', u"Föglö"), ('geta', u"Geta"), ('haapajarvi', u"Haapajärvi"), ('haapavesi', u"Haapavesi"), ('hailuoto', u"Hailuoto"), ('halsua', u"Halsua"), ('hamina', u"Hamina"), ('hammarland', u"Hammarland"), ('hankasalmi', u"Hankasalmi"), ('hanko', u"Hanko"), ('harjavalta', u"Harjavalta"), ('hartola', u"Hartola"), ('hattula', u"Hattula"), ('haukipudas', u"Haukipudas"), ('hausjarvi', u"Hausjärvi"), ('heinola', u"Heinola"), ('heinavesi', u"Heinävesi"), ('helsinki', u"Helsinki"), ('hirvensalmi', u"Hirvensalmi"), ('hollola', u"Hollola"), ('honkajoki', u"Honkajoki"), ('huittinen', u"Huittinen"), ('humppila', u"Humppila"), ('hyrynsalmi', u"Hyrynsalmi"), ('hyvinkaa', u"Hyvinkää"), ('hameenkoski', u"Hämeenkoski"), ('hameenkyro', u"Hämeenkyrö"), ('hameenlinna', u"Hämeenlinna"), ('ii', u"Ii"), ('iisalmi', u"Iisalmi"), ('iitti', u"Iitti"), ('ikaalinen', u"Ikaalinen"), ('ilmajoki', u"Ilmajoki"), ('ilomantsi', u"Ilomantsi"), ('imatra', u"Imatra"), ('inari', u"Inari"), ('inkoo', u"Inkoo"), ('isojoki', u"Isojoki"), ('isokyro', u"Isokyrö"), ('jalasjarvi', u"Jalasjärvi"), ('janakkala', u"Janakkala"), ('joensuu', u"Joensuu"), ('jokioinen', u"Jokioinen"), ('jomala', u"Jomala"), ('joroinen', u"Joroinen"), ('joutsa', u"Joutsa"), ('juankoski', u"Juankoski"), ('juuka', u"Juuka"), ('juupajoki', u"Juupajoki"), ('juva', u"Juva"), ('jyvaskyla', u"Jyväskylä"), ('jamijarvi', u"Jämijärvi"), ('jamsa', u"Jämsä"), ('jarvenpaa', u"Järvenpää"), ('kaarina', u"Kaarina"), ('kaavi', u"Kaavi"), ('kajaani', u"Kajaani"), ('kalajoki', u"Kalajoki"), ('kangasala', u"Kangasala"), ('kangasniemi', u"Kangasniemi"), ('kankaanpaa', u"Kankaanpää"), ('kannonkoski', u"Kannonkoski"), ('kannus', u"Kannus"), ('karijoki', u"Karijoki"), ('karjalohja', u"Karjalohja"), ('karkkila', u"Karkkila"), ('karstula', u"Karstula"), ('karttula', u"Karttula"), ('karvia', u"Karvia"), ('kaskinen', u"Kaskinen"), ('kauhajoki', u"Kauhajoki"), ('kauhava', u"Kauhava"), ('kauniainen', u"Kauniainen"), ('kaustinen', u"Kaustinen"), ('keitele', u"Keitele"), ('kemi', u"Kemi"), ('kemijarvi', u"Kemijärvi"), ('keminmaa', u"Keminmaa"), ('kemionsaari', u"Kemiönsaari"), ('kempele', u"Kempele"), ('kerava', u"Kerava"), ('kerimaki', u"Kerimäki"), ('kesalahti', u"Kesälahti"), ('keuruu', u"Keuruu"), ('kihnio', u"Kihniö"), ('kiikoinen', u"Kiikoinen"), ('kiiminki', u"Kiiminki"), ('kinnula', u"Kinnula"), ('kirkkonummi', u"Kirkkonummi"), ('kitee', u"Kitee"), ('kittila', u"Kittilä"), ('kiuruvesi', u"Kiuruvesi"), ('kivijarvi', u"Kivijärvi"), ('kokemaki', u"Kokemäki"), ('kokkola', u"Kokkola"), ('kolari', u"Kolari"), ('konnevesi', u"Konnevesi"), ('kontiolahti', u"Kontiolahti"), ('korsnas', u"Korsnäs"), ('koskitl', u"Koski Tl"), ('kotka', u"Kotka"), ('kouvola', u"Kouvola"), ('kristiinankaupunki', u"Kristiinankaupunki"), ('kruunupyy', u"Kruunupyy"), ('kuhmalahti', u"Kuhmalahti"), ('kuhmo', u"Kuhmo"), ('kuhmoinen', u"Kuhmoinen"), ('kumlinge', u"Kumlinge"), ('kuopio', u"Kuopio"), ('kuortane', u"Kuortane"), ('kurikka', u"Kurikka"), ('kustavi', u"Kustavi"), ('kuusamo', u"Kuusamo"), ('kylmakoski', u"Kylmäkoski"), ('kyyjarvi', u"Kyyjärvi"), ('karkola', u"Kärkölä"), ('karsamaki', u"Kärsämäki"), ('kokar', u"Kökar"), ('koylio', u"Köyliö"), ('lahti', u"Lahti"), ('laihia', u"Laihia"), ('laitila', u"Laitila"), ('lapinjarvi', u"Lapinjärvi"), ('lapinlahti', u"Lapinlahti"), ('lappajarvi', u"Lappajärvi"), ('lappeenranta', u"Lappeenranta"), ('lapua', u"Lapua"), ('laukaa', u"Laukaa"), ('lavia', u"Lavia"), ('lemi', u"Lemi"), ('lemland', u"Lemland"), ('lempaala', u"Lempäälä"), ('leppavirta', u"Leppävirta"), ('lestijarvi', u"Lestijärvi"), ('lieksa', u"Lieksa"), ('lieto', u"Lieto"), ('liminka', u"Liminka"), ('liperi', u"Liperi"), ('lohja', u"Lohja"), ('loimaa', u"Loimaa"), ('loppi', u"Loppi"), ('loviisa', u"Loviisa"), ('luhanka', u"Luhanka"), ('lumijoki', u"Lumijoki"), ('lumparland', u"Lumparland"), ('luoto', u"Luoto"), ('luumaki', u"Luumäki"), ('luvia', u"Luvia"), ('lansi-turunmaa', u"Länsi-Turunmaa"), ('maalahti', u"Maalahti"), ('maaninka', u"Maaninka"), ('maarianhamina', u"Maarianhamina"), ('marttila', u"Marttila"), ('masku', u"Masku"), ('merijarvi', u"Merijärvi"), ('merikarvia', u"Merikarvia"), ('miehikkala', u"Miehikkälä"), ('mikkeli', u"Mikkeli"), ('muhos', u"Muhos"), ('multia', u"Multia"), ('muonio', u"Muonio"), ('mustasaari', u"Mustasaari"), ('muurame', u"Muurame"), ('mynamaki', u"Mynämäki"), ('myrskyla', u"Myrskylä"), ('mantsala', u"Mäntsälä"), ('mantta-vilppula', u"Mänttä-Vilppula"), ('mantyharju', u"Mäntyharju"), ('naantali', u"Naantali"), ('nakkila', u"Nakkila"), ('nastola', u"Nastola"), ('nilsia', u"Nilsiä"), ('nivala', u"Nivala"), ('nokia', u"Nokia"), ('nousiainen', u"Nousiainen"), ('nummi-pusula', u"Nummi-Pusula"), ('nurmes', u"Nurmes"), ('nurmijarvi', u"Nurmijärvi"), ('narpio', u"Närpiö"), ('oravainen', u"Oravainen"), ('orimattila', u"Orimattila"), ('oripaa', u"Oripää"), ('orivesi', u"Orivesi"), ('oulainen', u"Oulainen"), ('oulu', u"Oulu"), ('oulunsalo', u"Oulunsalo"), ('outokumpu', u"Outokumpu"), ('padasjoki', u"Padasjoki"), ('paimio', u"Paimio"), ('paltamo', u"Paltamo"), ('parikkala', u"Parikkala"), ('parkano', u"Parkano"), ('pedersore', u"Pedersöre"), ('pelkosenniemi', u"Pelkosenniemi"), ('pello', u"Pello"), ('perho', u"Perho"), ('pertunmaa', u"Pertunmaa"), ('petajavesi', u"Petäjävesi"), ('pieksamaki', u"Pieksämäki"), ('pielavesi', u"Pielavesi"), ('pietarsaari', u"Pietarsaari"), ('pihtipudas', u"Pihtipudas"), ('pirkkala', u"Pirkkala"), ('polvijarvi', u"Polvijärvi"), ('pomarkku', u"Pomarkku"), ('pori', u"Pori"), ('pornainen', u"Pornainen"), ('porvoo', u"Porvoo"), ('posio', u"Posio"), ('pudasjarvi', u"Pudasjärvi"), ('pukkila', u"Pukkila"), ('punkaharju', u"Punkaharju"), ('punkalaidun', u"Punkalaidun"), ('puolanka', u"Puolanka"), ('puumala', u"Puumala"), ('pyhtaa', u"Pyhtää"), ('pyhajoki', u"Pyhäjoki"), ('pyhajarvi', u"Pyhäjärvi"), ('pyhanta', u"Pyhäntä"), ('pyharanta', u"Pyhäranta"), ('palkane', u"Pälkäne"), ('poytya', u"Pöytyä"), ('raahe', u"Raahe"), ('raasepori', u"Raasepori"), ('raisio', u"Raisio"), ('rantasalmi', u"Rantasalmi"), ('ranua', u"Ranua"), ('rauma', u"Rauma"), ('rautalampi', u"Rautalampi"), ('rautavaara', u"Rautavaara"), ('rautjarvi', u"Rautjärvi"), ('reisjarvi', u"Reisjärvi"), ('riihimaki', u"Riihimäki"), ('ristiina', u"Ristiina"), ('ristijarvi', u"Ristijärvi"), ('rovaniemi', u"Rovaniemi"), ('ruokolahti', u"Ruokolahti"), ('ruovesi', u"Ruovesi"), ('rusko', u"Rusko"), ('raakkyla', u"Rääkkylä"), ('saarijarvi', u"Saarijärvi"), ('salla', u"Salla"), ('salo', u"Salo"), ('saltvik', u"Saltvik"), ('sastamala', u"Sastamala"), ('sauvo', u"Sauvo"), ('savitaipale', u"Savitaipale"), ('savonlinna', u"Savonlinna"), ('savukoski', u"Savukoski"), ('seinajoki', u"Seinäjoki"), ('sievi', u"Sievi"), ('siikainen', u"Siikainen"), ('siikajoki', u"Siikajoki"), ('siikalatva', u"Siikalatva"), ('siilinjarvi', u"Siilinjärvi"), ('simo', u"Simo"), ('sipoo', u"Sipoo"), ('siuntio', u"Siuntio"), ('sodankyla', u"Sodankylä"), ('soini', u"Soini"), ('somero', u"Somero"), ('sonkajarvi', u"Sonkajärvi"), ('sotkamo', u"Sotkamo"), ('sottunga', u"Sottunga"), ('sulkava', u"Sulkava"), ('sund', u"Sund"), ('suomenniemi', u"Suomenniemi"), ('suomussalmi', u"Suomussalmi"), ('suonenjoki', u"Suonenjoki"), ('sysma', u"Sysmä"), ('sakyla', u"Säkylä"), ('taipalsaari', u"Taipalsaari"), ('taivalkoski', u"Taivalkoski"), ('taivassalo', u"Taivassalo"), ('tammela', u"Tammela"), ('tampere', u"Tampere"), ('tarvasjoki', u"Tarvasjoki"), ('tervo', u"Tervo"), ('tervola', u"Tervola"), ('teuva', u"Teuva"), ('tohmajarvi', u"Tohmajärvi"), ('toholampi', u"Toholampi"), ('toivakka', u"Toivakka"), ('tornio', u"Tornio"), ('turku', u"Turku"), ('tuusniemi', u"Tuusniemi"), ('tuusula', u"Tuusula"), ('tyrnava', u"Tyrnävä"), ('toysa', u"Töysä"), ('ulvila', u"Ulvila"), ('urjala', u"Urjala"), ('utajarvi', u"Utajärvi"), ('utsjoki', u"Utsjoki"), ('uurainen', u"Uurainen"), ('uusikaarlepyy', u"Uusikaarlepyy"), ('uusikaupunki', u"Uusikaupunki"), ('vaala', u"Vaala"), ('vaasa', u"Vaasa"), ('valkeakoski', u"Valkeakoski"), ('valtimo', u"Valtimo"), ('vantaa', u"Vantaa"), ('varkaus', u"Varkaus"), ('varpaisjarvi', u"Varpaisjärvi"), ('vehmaa', u"Vehmaa"), ('vesanto', u"Vesanto"), ('vesilahti', u"Vesilahti"), ('veteli', u"Veteli"), ('vierema', u"Vieremä"), ('vihanti', u"Vihanti"), ('vihti', u"Vihti"), ('viitasaari', u"Viitasaari"), ('vimpeli', u"Vimpeli"), ('virolahti', u"Virolahti"), ('virrat', u"Virrat"), ('vardo', u"Vårdö"), ('vahakyro', u"Vähäkyrö"), ('voyri-maksamaa', u"Vöyri-Maksamaa"), ('yli-ii', u"Yli-Ii"), ('ylitornio', u"Ylitornio"), ('ylivieska', u"Ylivieska"), ('ylojarvi', u"Ylöjärvi"), ('ypaja', u"Ypäjä"), ('ahtari', u"Ähtäri"), ('aanekoski', u"Äänekoski") )
10,822
Python
.py
351
25.547009
74
0.563522
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,654
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/fi/forms.py
""" FI-specific Form helpers """ import re from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ class FIZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a zip code in the format XXXXX.'), } def __init__(self, *args, **kwargs): super(FIZipCodeField, self).__init__(r'^\d{5}$', max_length=None, min_length=None, *args, **kwargs) class FIMunicipalitySelect(Select): """ A Select widget that uses a list of Finnish municipalities as its choices. """ def __init__(self, attrs=None): from fi_municipalities import MUNICIPALITY_CHOICES super(FIMunicipalitySelect, self).__init__(attrs, choices=MUNICIPALITY_CHOICES) class FISocialSecurityNumber(Field): default_error_messages = { 'invalid': _('Enter a valid Finnish social security number.'), } def clean(self, value): super(FISocialSecurityNumber, self).clean(value) if value in EMPTY_VALUES: return u'' checkmarks = "0123456789ABCDEFHJKLMNPRSTUVWXY" result = re.match(r"""^ (?P<date>([0-2]\d|3[01]) (0\d|1[012]) (\d{2})) [A+-] (?P<serial>(\d{3})) (?P<checksum>[%s])$""" % checkmarks, value, re.VERBOSE | re.IGNORECASE) if not result: raise ValidationError(self.error_messages['invalid']) gd = result.groupdict() checksum = int(gd['date'] + gd['serial']) if checkmarks[checksum % len(checkmarks)] == gd['checksum'].upper(): return u'%s' % value.upper() raise ValidationError(self.error_messages['invalid'])
1,803
Python
.py
45
32.888889
87
0.634703
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,655
util.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/it/util.py
from django.utils.encoding import smart_str, smart_unicode def ssn_check_digit(value): "Calculate Italian social security number check digit." ssn_even_chars = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25 } ssn_odd_chars = { '0': 1, '1': 0, '2': 5, '3': 7, '4': 9, '5': 13, '6': 15, '7': 17, '8': 19, '9': 21, 'A': 1, 'B': 0, 'C': 5, 'D': 7, 'E': 9, 'F': 13, 'G': 15, 'H': 17, 'I': 19, 'J': 21, 'K': 2, 'L': 4, 'M': 18, 'N': 20, 'O': 11, 'P': 3, 'Q': 6, 'R': 8, 'S': 12, 'T': 14, 'U': 16, 'V': 10, 'W': 22, 'X': 25, 'Y': 24, 'Z': 23 } # Chars from 'A' to 'Z' ssn_check_digits = [chr(x) for x in range(65, 91)] ssn = value.upper() total = 0 for i in range(0, 15): try: if i % 2 == 0: total += ssn_odd_chars[ssn[i]] else: total += ssn_even_chars[ssn[i]] except KeyError: msg = "Character '%(char)s' is not allowed." % {'char': ssn[i]} raise ValueError(msg) return ssn_check_digits[total % 26] def vat_number_check_digit(vat_number): "Calculate Italian VAT number check digit." normalized_vat_number = smart_str(vat_number).zfill(10) total = 0 for i in range(0, 10, 2): total += int(normalized_vat_number[i]) for i in range(1, 11, 2): quotient , remainder = divmod(int(normalized_vat_number[i]) * 2, 10) total += quotient + remainder return smart_unicode((10 - total % 10) % 10)
1,807
Python
.py
41
36.463415
79
0.465683
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,656
it_region.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/it/it_region.py
# -*- coding: utf-8 -* REGION_CHOICES = ( ('ABR', 'Abruzzo'), ('BAS', 'Basilicata'), ('CAL', 'Calabria'), ('CAM', 'Campania'), ('EMR', 'Emilia-Romagna'), ('FVG', 'Friuli-Venezia Giulia'), ('LAZ', 'Lazio'), ('LIG', 'Liguria'), ('LOM', 'Lombardia'), ('MAR', 'Marche'), ('MOL', 'Molise'), ('PMN', 'Piemonte'), ('PUG', 'Puglia'), ('SAR', 'Sardegna'), ('SIC', 'Sicilia'), ('TOS', 'Toscana'), ('TAA', 'Trentino-Alto Adige'), ('UMB', 'Umbria'), ('VAO', u'Valle d’Aosta'), ('VEN', 'Veneto'), )
569
Python
.py
23
20.217391
37
0.475229
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,657
it_province.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/it/it_province.py
# -*- coding: utf-8 -* PROVINCE_CHOICES = ( ('AG', 'Agrigento'), ('AL', 'Alessandria'), ('AN', 'Ancona'), ('AO', 'Aosta'), ('AR', 'Arezzo'), ('AP', 'Ascoli Piceno'), ('AT', 'Asti'), ('AV', 'Avellino'), ('BA', 'Bari'), ('BT', 'Barletta-Andria-Trani'), # active starting from 2009 ('BL', 'Belluno'), ('BN', 'Benevento'), ('BG', 'Bergamo'), ('BI', 'Biella'), ('BO', 'Bologna'), ('BZ', 'Bolzano/Bozen'), ('BS', 'Brescia'), ('BR', 'Brindisi'), ('CA', 'Cagliari'), ('CL', 'Caltanissetta'), ('CB', 'Campobasso'), ('CI', 'Carbonia-Iglesias'), ('CE', 'Caserta'), ('CT', 'Catania'), ('CZ', 'Catanzaro'), ('CH', 'Chieti'), ('CO', 'Como'), ('CS', 'Cosenza'), ('CR', 'Cremona'), ('KR', 'Crotone'), ('CN', 'Cuneo'), ('EN', 'Enna'), ('FM', 'Fermo'), # active starting from 2009 ('FE', 'Ferrara'), ('FI', 'Firenze'), ('FG', 'Foggia'), ('FC', 'Forlì-Cesena'), ('FR', 'Frosinone'), ('GE', 'Genova'), ('GO', 'Gorizia'), ('GR', 'Grosseto'), ('IM', 'Imperia'), ('IS', 'Isernia'), ('SP', 'La Spezia'), ('AQ', u'L’Aquila'), ('LT', 'Latina'), ('LE', 'Lecce'), ('LC', 'Lecco'), ('LI', 'Livorno'), ('LO', 'Lodi'), ('LU', 'Lucca'), ('MC', 'Macerata'), ('MN', 'Mantova'), ('MS', 'Massa-Carrara'), ('MT', 'Matera'), ('VS', 'Medio Campidano'), ('ME', 'Messina'), ('MI', 'Milano'), ('MO', 'Modena'), ('MB', 'Monza e Brianza'), # active starting from 2009 ('NA', 'Napoli'), ('NO', 'Novara'), ('NU', 'Nuoro'), ('OG', 'Ogliastra'), ('OT', 'Olbia-Tempio'), ('OR', 'Oristano'), ('PD', 'Padova'), ('PA', 'Palermo'), ('PR', 'Parma'), ('PV', 'Pavia'), ('PG', 'Perugia'), ('PU', 'Pesaro e Urbino'), ('PE', 'Pescara'), ('PC', 'Piacenza'), ('PI', 'Pisa'), ('PT', 'Pistoia'), ('PN', 'Pordenone'), ('PZ', 'Potenza'), ('PO', 'Prato'), ('RG', 'Ragusa'), ('RA', 'Ravenna'), ('RC', 'Reggio Calabria'), ('RE', 'Reggio Emilia'), ('RI', 'Rieti'), ('RN', 'Rimini'), ('RM', 'Roma'), ('RO', 'Rovigo'), ('SA', 'Salerno'), ('SS', 'Sassari'), ('SV', 'Savona'), ('SI', 'Siena'), ('SR', 'Siracusa'), ('SO', 'Sondrio'), ('TA', 'Taranto'), ('TE', 'Teramo'), ('TR', 'Terni'), ('TO', 'Torino'), ('TP', 'Trapani'), ('TN', 'Trento'), ('TV', 'Treviso'), ('TS', 'Trieste'), ('UD', 'Udine'), ('VA', 'Varese'), ('VE', 'Venezia'), ('VB', 'Verbano Cusio Ossola'), ('VC', 'Vercelli'), ('VR', 'Verona'), ('VV', 'Vibo Valentia'), ('VI', 'Vicenza'), ('VT', 'Viterbo'), )
2,740
Python
.py
113
19.318584
64
0.433473
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,658
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/it/forms.py
""" IT-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode from django.contrib.localflavor.it.util import ssn_check_digit, vat_number_check_digit import re class ITZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a valid zip code.'), } def __init__(self, *args, **kwargs): super(ITZipCodeField, self).__init__(r'^\d{5}$', max_length=None, min_length=None, *args, **kwargs) class ITRegionSelect(Select): """ A Select widget that uses a list of IT regions as its choices. """ def __init__(self, attrs=None): from it_region import REGION_CHOICES super(ITRegionSelect, self).__init__(attrs, choices=REGION_CHOICES) class ITProvinceSelect(Select): """ A Select widget that uses a list of IT provinces as its choices. """ def __init__(self, attrs=None): from it_province import PROVINCE_CHOICES super(ITProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES) class ITSocialSecurityNumberField(RegexField): """ A form field that validates Italian Social Security numbers (codice fiscale). For reference see http://www.agenziaentrate.it/ and search for 'Informazioni sulla codificazione delle persone fisiche'. """ default_error_messages = { 'invalid': _(u'Enter a valid Social Security number.'), } def __init__(self, *args, **kwargs): super(ITSocialSecurityNumberField, self).__init__(r'^\w{3}\s*\w{3}\s*\w{5}\s*\w{5}$', max_length=None, min_length=None, *args, **kwargs) def clean(self, value): value = super(ITSocialSecurityNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('\s', u'', value).upper() try: check_digit = ssn_check_digit(value) except ValueError: raise ValidationError(self.error_messages['invalid']) if not value[15] == check_digit: raise ValidationError(self.error_messages['invalid']) return value class ITVatNumberField(Field): """ A form field that validates Italian VAT numbers (partita IVA). """ default_error_messages = { 'invalid': _(u'Enter a valid VAT number.'), } def clean(self, value): value = super(ITVatNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' try: vat_number = int(value) except ValueError: raise ValidationError(self.error_messages['invalid']) vat_number = str(vat_number).zfill(11) check_digit = vat_number_check_digit(vat_number[0:10]) if not vat_number[10] == check_digit: raise ValidationError(self.error_messages['invalid']) return smart_unicode(vat_number)
3,027
Python
.py
75
33.8
93
0.663269
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,659
mx_states.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/mx/mx_states.py
# -*- coding: utf-8 -*- """ A list of Mexican states for use as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ from django.utils.translation import ugettext_lazy as _ STATE_CHOICES = ( ('AGU', _(u'Aguascalientes')), ('BCN', _(u'Baja California')), ('BCS', _(u'Baja California Sur')), ('CAM', _(u'Campeche')), ('CHH', _(u'Chihuahua')), ('CHP', _(u'Chiapas')), ('COA', _(u'Coahuila')), ('COL', _(u'Colima')), ('DIF', _(u'Distrito Federal')), ('DUR', _(u'Durango')), ('GRO', _(u'Guerrero')), ('GUA', _(u'Guanajuato')), ('HID', _(u'Hidalgo')), ('JAL', _(u'Jalisco')), ('MEX', _(u'Estado de México')), ('MIC', _(u'Michoacán')), ('MOR', _(u'Morelos')), ('NAY', _(u'Nayarit')), ('NLE', _(u'Nuevo León')), ('OAX', _(u'Oaxaca')), ('PUE', _(u'Puebla')), ('QUE', _(u'Querétaro')), ('ROO', _(u'Quintana Roo')), ('SIN', _(u'Sinaloa')), ('SLP', _(u'San Luis Potosí')), ('SON', _(u'Sonora')), ('TAB', _(u'Tabasco')), ('TAM', _(u'Tamaulipas')), ('TLA', _(u'Tlaxcala')), ('VER', _(u'Veracruz')), ('YUC', _(u'Yucatán')), ('ZAC', _(u'Zacatecas')), )
1,251
Python
.py
41
26.146341
74
0.511667
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,660
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/mx/forms.py
""" Mexican-specific form helpers. """ from django.forms.fields import Select class MXStateSelect(Select): """ A Select widget that uses a list of Mexican states as its choices. """ def __init__(self, attrs=None): from mx_states import STATE_CHOICES super(MXStateSelect, self).__init__(attrs, choices=STATE_CHOICES)
351
Python
.py
11
27.727273
73
0.700297
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,661
ar_provinces.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/ar/ar_provinces.py
# -*- coding: utf-8 -*- """ A list of Argentinean provinces and autonomous cities as `choices` in a formfield. From http://www.argentina.gov.ar/argentina/portal/paginas.dhtml?pagina=425 This exists in this standalone file so that it's only imported into memory when explicitly needed. """ PROVINCE_CHOICES = ( ('B', u'Buenos Aires'), ('K', u'Catamarca'), ('H', u'Chaco'), ('U', u'Chubut'), ('C', u'Ciudad Autónoma de Buenos Aires'), ('X', u'Córdoba'), ('W', u'Corrientes'), ('E', u'Entre Ríos'), ('P', u'Formosa'), ('Y', u'Jujuy'), ('L', u'La Pampa'), ('F', u'La Rioja'), ('M', u'Mendoza'), ('N', u'Misiones'), ('Q', u'Neuquén'), ('R', u'Río Negro'), ('A', u'Salta'), ('J', u'San Juan'), ('D', u'San Luis'), ('Z', u'Santa Cruz'), ('S', u'Santa Fe'), ('G', u'Santiago del Estero'), ('V', u'Tierra del Fuego, Antártida e Islas del Atlántico Sur'), ('T', u'Tucumán'), )
973
Python
.py
34
24.5
74
0.565124
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,662
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/ar/forms.py
# -*- coding: utf-8 -*- """ AR-specific Form helpers. """ from django.forms import ValidationError from django.core.validators import EMPTY_VALUES from django.forms.fields import RegexField, CharField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ class ARProvinceSelect(Select): """ A Select widget that uses a list of Argentinean provinces/autonomous cities as its choices. """ def __init__(self, attrs=None): from ar_provinces import PROVINCE_CHOICES super(ARProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES) class ARPostalCodeField(RegexField): """ A field that accepts a 'classic' NNNN Postal Code or a CPA. See http://www.correoargentino.com.ar/consulta_cpa/home.php """ default_error_messages = { 'invalid': _("Enter a postal code in the format NNNN or ANNNNAAA."), } def __init__(self, *args, **kwargs): super(ARPostalCodeField, self).__init__(r'^\d{4}$|^[A-HJ-NP-Za-hj-np-z]\d{4}\D{3}$', min_length=4, max_length=8, *args, **kwargs) def clean(self, value): value = super(ARPostalCodeField, self).clean(value) if value in EMPTY_VALUES: return u'' if len(value) not in (4, 8): raise ValidationError(self.error_messages['invalid']) if len(value) == 8: return u'%s%s%s' % (value[0].upper(), value[1:5], value[5:].upper()) return value class ARDNIField(CharField): """ A field that validates 'Documento Nacional de Identidad' (DNI) numbers. """ default_error_messages = { 'invalid': _("This field requires only numbers."), 'max_digits': _("This field requires 7 or 8 digits."), } def __init__(self, *args, **kwargs): super(ARDNIField, self).__init__(max_length=10, min_length=7, *args, **kwargs) def clean(self, value): """ Value can be a string either in the [X]X.XXX.XXX or [X]XXXXXXX formats. """ value = super(ARDNIField, self).clean(value) if value in EMPTY_VALUES: return u'' if not value.isdigit(): value = value.replace('.', '') if not value.isdigit(): raise ValidationError(self.error_messages['invalid']) if len(value) not in (7, 8): raise ValidationError(self.error_messages['max_digits']) return value class ARCUITField(RegexField): """ This field validates a CUIT (Código Único de Identificación Tributaria). A CUIT is of the form XX-XXXXXXXX-V. The last digit is a check digit. """ default_error_messages = { 'invalid': _('Enter a valid CUIT in XX-XXXXXXXX-X or XXXXXXXXXXXX format.'), 'checksum': _("Invalid CUIT."), } def __init__(self, *args, **kwargs): super(ARCUITField, self).__init__(r'^\d{2}-?\d{8}-?\d$', *args, **kwargs) def clean(self, value): """ Value can be either a string in the format XX-XXXXXXXX-X or an 11-digit number. """ value = super(ARCUITField, self).clean(value) if value in EMPTY_VALUES: return u'' value, cd = self._canon(value) if self._calc_cd(value) != cd: raise ValidationError(self.error_messages['checksum']) return self._format(value, cd) def _canon(self, cuit): cuit = cuit.replace('-', '') return cuit[:-1], cuit[-1] def _calc_cd(self, cuit): mults = (5, 4, 3, 2, 7, 6, 5, 4, 3, 2) tmp = sum([m * int(cuit[idx]) for idx, m in enumerate(mults)]) return str(11 - tmp % 11) def _format(self, cuit, check_digit=None): if check_digit == None: check_digit = cuit[-1] cuit = cuit[:-1] return u'%s-%s-%s' % (cuit[:2], cuit[2:], check_digit)
3,903
Python
.py
98
32.336735
92
0.604227
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,663
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/pt/forms.py
""" PT-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re phone_digits_re = re.compile(r'^(\d{9}|(00|\+)\d*)$') class PTZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a zip code in the format XXXX-XXX.'), } def __init__(self, *args, **kwargs): super(PTZipCodeField, self).__init__(r'^(\d{4}-\d{3}|\d{7})$', max_length=None, min_length=None, *args, **kwargs) def clean(self,value): cleaned = super(PTZipCodeField, self).clean(value) if len(cleaned) == 7: return u'%s-%s' % (cleaned[:4],cleaned[4:]) else: return cleaned class PTPhoneNumberField(Field): """ Validate local Portuguese phone number (including international ones) It should have 9 digits (may include spaces) or start by 00 or + (international) """ default_error_messages = { 'invalid': _('Phone numbers must have 9 digits, or start by + or 00.'), } def clean(self, value): super(PTPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\.|\s)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: return u'%s' % value raise ValidationError(self.error_messages['invalid'])
1,561
Python
.py
40
32.675
84
0.643854
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,664
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/kw/forms.py
""" Kuwait-specific Form helpers """ import re from datetime import date from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField from django.utils.translation import gettext as _ id_re = re.compile(r'^(?P<initial>\d{1})(?P<yy>\d\d)(?P<mm>\d\d)(?P<dd>\d\d)(?P<mid>\d{4})(?P<checksum>\d{1})') class KWCivilIDNumberField(Field): """ Kuwaiti Civil ID numbers are 12 digits, second to seventh digits represents the person's birthdate. Checks the following rules to determine the validty of the number: * The number consist of 12 digits. * The birthdate of the person is a valid date. * The calculated checksum equals to the last digit of the Civil ID. """ default_error_messages = { 'invalid': _('Enter a valid Kuwaiti Civil ID number'), } def has_valid_checksum(self, value): weight = (2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2) calculated_checksum = 0 for i in range(11): calculated_checksum += int(value[i]) * weight[i] remainder = calculated_checksum % 11 checkdigit = 11 - remainder if checkdigit != int(value[11]): return False return True def clean(self, value): super(KWCivilIDNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' if not re.match(r'^\d{12}$', value): raise ValidationError(self.error_messages['invalid']) match = re.match(id_re, value) if not match: raise ValidationError(self.error_messages['invalid']) gd = match.groupdict() try: d = date(int(gd['yy']), int(gd['mm']), int(gd['dd'])) except ValueError: raise ValidationError(self.error_messages['invalid']) if not self.has_valid_checksum(value): raise ValidationError(self.error_messages['invalid']) return value
1,988
Python
.py
49
33.163265
111
0.637922
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,665
ie_counties.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/ie/ie_counties.py
""" Sources: Irish Counties: http://en.wikipedia.org/wiki/Counties_of_Ireland """ from django.utils.translation import ugettext_lazy as _ IE_COUNTY_CHOICES = ( ('antrim', _('Antrim')), ('armagh', _('Armagh')), ('carlow', _('Carlow')), ('cavan', _('Cavan')), ('clare', _('Clare')), ('cork', _('Cork')), ('derry', _('Derry')), ('donegal', _('Donegal')), ('down', _('Down')), ('dublin', _('Dublin')), ('fermanagh', _('Fermanagh')), ('galway', _('Galway')), ('kerry', _('Kerry')), ('kildare', _('Kildare')), ('kilkenny', _('Kilkenny')), ('laois', _('Laois')), ('leitrim', _('Leitrim')), ('limerick', _('Limerick')), ('longford', _('Longford')), ('louth', _('Louth')), ('mayo', _('Mayo')), ('meath', _('Meath')), ('monaghan', _('Monaghan')), ('offaly', _('Offaly')), ('roscommon', _('Roscommon')), ('sligo', _('Sligo')), ('tipperary', _('Tipperary')), ('tyrone', _('Tyrone')), ('waterford', _('Waterford')), ('westmeath', _('Westmeath')), ('wexford', _('Wexford')), ('wicklow', _('Wicklow')), )
1,127
Python
.py
39
24.384615
72
0.48942
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,666
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/ie/forms.py
""" UK-specific Form helpers """ from django.forms.fields import Select class IECountySelect(Select): """ A Select widget that uses a list of Irish Counties as its choices. """ def __init__(self, attrs=None): from ie_counties import IE_COUNTY_CHOICES super(IECountySelect, self).__init__(attrs, choices=IE_COUNTY_CHOICES)
356
Python
.py
11
28.272727
78
0.702624
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,667
at_states.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/at/at_states.py
# -*- coding: utf-8 -* from django.utils.translation import ugettext_lazy as _ STATE_CHOICES = ( ('BL', _('Burgenland')), ('KA', _('Carinthia')), ('NO', _('Lower Austria')), ('OO', _('Upper Austria')), ('SA', _('Salzburg')), ('ST', _('Styria')), ('TI', _('Tyrol')), ('VO', _('Vorarlberg')), ('WI', _('Vienna')), )
350
Python
.py
13
23.153846
55
0.486647
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,668
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/at/forms.py
""" AT-specific Form helpers """ import re from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ re_ssn = re.compile(r'^\d{4} \d{6}') class ATZipCodeField(RegexField): """ A form field that validates its input is an Austrian postcode. Accepts 4 digits. """ default_error_messages = { 'invalid': _('Enter a zip code in the format XXXX.'), } def __init__(self, *args, **kwargs): super(ATZipCodeField, self).__init__(r'^\d{4}$', max_length=None, min_length=None, *args, **kwargs) class ATStateSelect(Select): """ A Select widget that uses a list of AT states as its choices. """ def __init__(self, attrs=None): from django.contrib.localflavor.at.at_states import STATE_CHOICES super(ATStateSelect, self).__init__(attrs, choices=STATE_CHOICES) class ATSocialSecurityNumberField(Field): """ Austrian Social Security numbers are composed of a 4 digits and 6 digits field. The latter represents in most cases the person's birthdate while the first 4 digits represent a 3-digits counter and a one-digit checksum. The 6-digits field can also differ from the person's birthdate if the 3-digits counter suffered an overflow. This code is based on information available on http://de.wikipedia.org/wiki/Sozialversicherungsnummer#.C3.96sterreich """ default_error_messages = { 'invalid': _(u'Enter a valid Austrian Social Security Number in XXXX XXXXXX format.'), } def clean(self, value): value = super(ATSocialSecurityNumberField, self).clean(value) if value in EMPTY_VALUES: return u"" if not re_ssn.search(value): raise ValidationError(self.error_messages['invalid']) sqnr, date = value.split(" ") sqnr, check = (sqnr[:3], (sqnr[3])) if int(sqnr) < 100: raise ValidationError(self.error_messages['invalid']) res = int(sqnr[0])*3 + int(sqnr[1])*7 + int(sqnr[2])*9 \ + int(date[0])*5 + int(date[1])*8 + int(date[2])*4 \ + int(date[3])*2 + int(date[4])*1 + int(date[5])*6 res = res % 11 if res != int(check): raise ValidationError(self.error_messages['invalid']) return u'%s%s %s'%(sqnr, check, date,)
2,446
Python
.py
57
36.508772
94
0.658393
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,669
jp_prefectures.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/jp/jp_prefectures.py
from django.utils.translation import ugettext_lazy JP_PREFECTURES = ( ('hokkaido', ugettext_lazy('Hokkaido'),), ('aomori', ugettext_lazy('Aomori'),), ('iwate', ugettext_lazy('Iwate'),), ('miyagi', ugettext_lazy('Miyagi'),), ('akita', ugettext_lazy('Akita'),), ('yamagata', ugettext_lazy('Yamagata'),), ('fukushima', ugettext_lazy('Fukushima'),), ('ibaraki', ugettext_lazy('Ibaraki'),), ('tochigi', ugettext_lazy('Tochigi'),), ('gunma', ugettext_lazy('Gunma'),), ('saitama', ugettext_lazy('Saitama'),), ('chiba', ugettext_lazy('Chiba'),), ('tokyo', ugettext_lazy('Tokyo'),), ('kanagawa', ugettext_lazy('Kanagawa'),), ('yamanashi', ugettext_lazy('Yamanashi'),), ('nagano', ugettext_lazy('Nagano'),), ('niigata', ugettext_lazy('Niigata'),), ('toyama', ugettext_lazy('Toyama'),), ('ishikawa', ugettext_lazy('Ishikawa'),), ('fukui', ugettext_lazy('Fukui'),), ('gifu', ugettext_lazy('Gifu'),), ('shizuoka', ugettext_lazy('Shizuoka'),), ('aichi', ugettext_lazy('Aichi'),), ('mie', ugettext_lazy('Mie'),), ('shiga', ugettext_lazy('Shiga'),), ('kyoto', ugettext_lazy('Kyoto'),), ('osaka', ugettext_lazy('Osaka'),), ('hyogo', ugettext_lazy('Hyogo'),), ('nara', ugettext_lazy('Nara'),), ('wakayama', ugettext_lazy('Wakayama'),), ('tottori', ugettext_lazy('Tottori'),), ('shimane', ugettext_lazy('Shimane'),), ('okayama', ugettext_lazy('Okayama'),), ('hiroshima', ugettext_lazy('Hiroshima'),), ('yamaguchi', ugettext_lazy('Yamaguchi'),), ('tokushima', ugettext_lazy('Tokushima'),), ('kagawa', ugettext_lazy('Kagawa'),), ('ehime', ugettext_lazy('Ehime'),), ('kochi', ugettext_lazy('Kochi'),), ('fukuoka', ugettext_lazy('Fukuoka'),), ('saga', ugettext_lazy('Saga'),), ('nagasaki', ugettext_lazy('Nagasaki'),), ('kumamoto', ugettext_lazy('Kumamoto'),), ('oita', ugettext_lazy('Oita'),), ('miyazaki', ugettext_lazy('Miyazaki'),), ('kagoshima', ugettext_lazy('Kagoshima'),), ('okinawa', ugettext_lazy('Okinawa'),), )
2,089
Python
.py
50
37
50
0.602061
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,670
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/jp/forms.py
""" JP-specific Form helpers """ from django.forms import ValidationError from django.utils.translation import ugettext_lazy as _ from django.forms.fields import RegexField, Select class JPPostalCodeField(RegexField): """ A form field that validates its input is a Japanese postcode. Accepts 7 digits, with or without a hyphen. """ default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXXXX or XXX-XXXX.'), } def __init__(self, *args, **kwargs): super(JPPostalCodeField, self).__init__(r'^\d{3}-\d{4}$|^\d{7}$', max_length=None, min_length=None, *args, **kwargs) def clean(self, value): """ Validates the input and returns a string that contains only numbers. Returns an empty string for empty values. """ v = super(JPPostalCodeField, self).clean(value) return v.replace('-', '') class JPPrefectureSelect(Select): """ A Select widget that uses a list of Japanese prefectures as its choices. """ def __init__(self, attrs=None): from jp_prefectures import JP_PREFECTURES super(JPPrefectureSelect, self).__init__(attrs, choices=JP_PREFECTURES)
1,211
Python
.py
31
33.354839
79
0.668654
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,671
is_postalcodes.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/is_/is_postalcodes.py
# -*- coding: utf-8 -*- IS_POSTALCODES = ( ('101', u'101 Reykjavík'), ('103', u'103 Reykjavík'), ('104', u'104 Reykjavík'), ('105', u'105 Reykjavík'), ('107', u'107 Reykjavík'), ('108', u'108 Reykjavík'), ('109', u'109 Reykjavík'), ('110', u'110 Reykjavík'), ('111', u'111 Reykjavík'), ('112', u'112 Reykjavík'), ('113', u'113 Reykjavík'), ('116', u'116 Kjalarnes'), ('121', u'121 Reykjavík'), ('123', u'123 Reykjavík'), ('124', u'124 Reykjavík'), ('125', u'125 Reykjavík'), ('127', u'127 Reykjavík'), ('128', u'128 Reykjavík'), ('129', u'129 Reykjavík'), ('130', u'130 Reykjavík'), ('132', u'132 Reykjavík'), ('150', u'150 Reykjavík'), ('155', u'155 Reykjavík'), ('170', u'170 Seltjarnarnes'), ('172', u'172 Seltjarnarnes'), ('190', u'190 Vogar'), ('200', u'200 Kópavogur'), ('201', u'201 Kópavogur'), ('202', u'202 Kópavogur'), ('203', u'203 Kópavogur'), ('210', u'210 Garðabær'), ('212', u'212 Garðabær'), ('220', u'220 Hafnarfjörður'), ('221', u'221 Hafnarfjörður'), ('222', u'222 Hafnarfjörður'), ('225', u'225 Álftanes'), ('230', u'230 Reykjanesbær'), ('232', u'232 Reykjanesbær'), ('233', u'233 Reykjanesbær'), ('235', u'235 Keflavíkurflugvöllur'), ('240', u'240 Grindavík'), ('245', u'245 Sandgerði'), ('250', u'250 Garður'), ('260', u'260 Reykjanesbær'), ('270', u'270 Mosfellsbær'), ('300', u'300 Akranes'), ('301', u'301 Akranes'), ('302', u'302 Akranes'), ('310', u'310 Borgarnes'), ('311', u'311 Borgarnes'), ('320', u'320 Reykholt í Borgarfirði'), ('340', u'340 Stykkishólmur'), ('345', u'345 Flatey á Breiðafirði'), ('350', u'350 Grundarfjörður'), ('355', u'355 Ólafsvík'), ('356', u'356 Snæfellsbær'), ('360', u'360 Hellissandur'), ('370', u'370 Búðardalur'), ('371', u'371 Búðardalur'), ('380', u'380 Reykhólahreppur'), ('400', u'400 Ísafjörður'), ('401', u'401 Ísafjörður'), ('410', u'410 Hnífsdalur'), ('415', u'415 Bolungarvík'), ('420', u'420 Súðavík'), ('425', u'425 Flateyri'), ('430', u'430 Suðureyri'), ('450', u'450 Patreksfjörður'), ('451', u'451 Patreksfjörður'), ('460', u'460 Tálknafjörður'), ('465', u'465 Bíldudalur'), ('470', u'470 Þingeyri'), ('471', u'471 Þingeyri'), ('500', u'500 Staður'), ('510', u'510 Hólmavík'), ('512', u'512 Hólmavík'), ('520', u'520 Drangsnes'), ('522', u'522 Kjörvogur'), ('523', u'523 Bær'), ('524', u'524 Norðurfjörður'), ('530', u'530 Hvammstangi'), ('531', u'531 Hvammstangi'), ('540', u'540 Blönduós'), ('541', u'541 Blönduós'), ('545', u'545 Skagaströnd'), ('550', u'550 Sauðárkrókur'), ('551', u'551 Sauðárkrókur'), ('560', u'560 Varmahlíð'), ('565', u'565 Hofsós'), ('566', u'566 Hofsós'), ('570', u'570 Fljót'), ('580', u'580 Siglufjörður'), ('600', u'600 Akureyri'), ('601', u'601 Akureyri'), ('602', u'602 Akureyri'), ('603', u'603 Akureyri'), ('610', u'610 Grenivík'), ('611', u'611 Grímsey'), ('620', u'620 Dalvík'), ('621', u'621 Dalvík'), ('625', u'625 Ólafsfjörður'), ('630', u'630 Hrísey'), ('640', u'640 Húsavík'), ('641', u'641 Húsavík'), ('645', u'645 Fosshóll'), ('650', u'650 Laugar'), ('660', u'660 Mývatn'), ('670', u'670 Kópasker'), ('671', u'671 Kópasker'), ('675', u'675 Raufarhöfn'), ('680', u'680 Þórshöfn'), ('681', u'681 Þórshöfn'), ('685', u'685 Bakkafjörður'), ('690', u'690 Vopnafjörður'), ('700', u'700 Egilsstaðir'), ('701', u'701 Egilsstaðir'), ('710', u'710 Seyðisfjörður'), ('715', u'715 Mjóifjörður'), ('720', u'720 Borgarfjörður eystri'), ('730', u'730 Reyðarfjörður'), ('735', u'735 Eskifjörður'), ('740', u'740 Neskaupstaður'), ('750', u'750 Fáskrúðsfjörður'), ('755', u'755 Stöðvarfjörður'), ('760', u'760 Breiðdalsvík'), ('765', u'765 Djúpivogur'), ('780', u'780 Höfn í Hornafirði'), ('781', u'781 Höfn í Hornafirði'), ('785', u'785 Öræfi'), ('800', u'800 Selfoss'), ('801', u'801 Selfoss'), ('802', u'802 Selfoss'), ('810', u'810 Hveragerði'), ('815', u'815 Þorlákshöfn'), ('820', u'820 Eyrarbakki'), ('825', u'825 Stokkseyri'), ('840', u'840 Laugarvatn'), ('845', u'845 Flúðir'), ('850', u'850 Hella'), ('851', u'851 Hella'), ('860', u'860 Hvolsvöllur'), ('861', u'861 Hvolsvöllur'), ('870', u'870 Vík'), ('871', u'871 Vík'), ('880', u'880 Kirkjubæjarklaustur'), ('900', u'900 Vestmannaeyjar'), ('902', u'902 Vestmannaeyjar') )
4,913
Python
.py
150
26.573333
43
0.544163
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,672
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/is_/forms.py
""" Iceland specific form helpers. """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import RegexField from django.forms.widgets import Select from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode class ISIdNumberField(RegexField): """ Icelandic identification number (kennitala). This is a number every citizen of Iceland has. """ default_error_messages = { 'invalid': _('Enter a valid Icelandic identification number. The format is XXXXXX-XXXX.'), 'checksum': _(u'The Icelandic identification number is not valid.'), } def __init__(self, *args, **kwargs): kwargs['min_length'],kwargs['max_length'] = 10,11 super(ISIdNumberField, self).__init__(r'^\d{6}(-| )?\d{4}$', *args, **kwargs) def clean(self, value): value = super(ISIdNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = self._canonify(value) if self._validate(value): return self._format(value) else: raise ValidationError(self.error_messages['checksum']) def _canonify(self, value): """ Returns the value as only digits. """ return value.replace('-', '').replace(' ', '') def _validate(self, value): """ Takes in the value in canonical form and checks the verifier digit. The method is modulo 11. """ check = [3, 2, 7, 6, 5, 4, 3, 2, 1, 0] return sum([int(value[i]) * check[i] for i in range(10)]) % 11 == 0 def _format(self, value): """ Takes in the value in canonical form and returns it in the common display format. """ return smart_unicode(value[:6]+'-'+value[6:]) class ISPhoneNumberField(RegexField): """ Icelandic phone number. Seven digits with an optional hyphen or space after the first three digits. """ def __init__(self, *args, **kwargs): kwargs['min_length'], kwargs['max_length'] = 7,8 super(ISPhoneNumberField, self).__init__(r'^\d{3}(-| )?\d{4}$', *args, **kwargs) def clean(self, value): value = super(ISPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' return value.replace('-', '').replace(' ', '') class ISPostalCodeSelect(Select): """ A Select widget that uses a list of Icelandic postal codes as its choices. """ def __init__(self, attrs=None): from is_postalcodes import IS_POSTALCODES super(ISPostalCodeSelect, self).__init__(attrs, choices=IS_POSTALCODES)
2,706
Python
.py
68
32.985294
98
0.632101
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,673
id_choices.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/id/id_choices.py
import warnings from django.utils.translation import ugettext_lazy as _ # Reference: http://id.wikipedia.org/wiki/Daftar_provinsi_Indonesia # Indonesia does not have an official Province code standard. # I decided to use unambiguous and consistent (some are common) 3-letter codes. warnings.warn( 'There have been recent changes to the ID localflavor. See the release notes for details', RuntimeWarning ) PROVINCE_CHOICES = ( ('ACE', _('Aceh')), ('BLI', _('Bali')), ('BTN', _('Banten')), ('BKL', _('Bengkulu')), ('DIY', _('Yogyakarta')), ('JKT', _('Jakarta')), ('GOR', _('Gorontalo')), ('JMB', _('Jambi')), ('JBR', _('Jawa Barat')), ('JTG', _('Jawa Tengah')), ('JTM', _('Jawa Timur')), ('KBR', _('Kalimantan Barat')), ('KSL', _('Kalimantan Selatan')), ('KTG', _('Kalimantan Tengah')), ('KTM', _('Kalimantan Timur')), ('BBL', _('Kepulauan Bangka-Belitung')), ('KRI', _('Kepulauan Riau')), ('LPG', _('Lampung')), ('MLK', _('Maluku')), ('MUT', _('Maluku Utara')), ('NTB', _('Nusa Tenggara Barat')), ('NTT', _('Nusa Tenggara Timur')), ('PPA', _('Papua')), ('PPB', _('Papua Barat')), ('RIU', _('Riau')), ('SLB', _('Sulawesi Barat')), ('SLS', _('Sulawesi Selatan')), ('SLT', _('Sulawesi Tengah')), ('SLR', _('Sulawesi Tenggara')), ('SLU', _('Sulawesi Utara')), ('SMB', _('Sumatera Barat')), ('SMS', _('Sumatera Selatan')), ('SMU', _('Sumatera Utara')), ) LICENSE_PLATE_PREFIX_CHOICES = ( ('A', _('Banten')), ('AA', _('Magelang')), ('AB', _('Yogyakarta')), ('AD', _('Surakarta - Solo')), ('AE', _('Madiun')), ('AG', _('Kediri')), ('B', _('Jakarta')), ('BA', _('Sumatera Barat')), ('BB', _('Tapanuli')), ('BD', _('Bengkulu')), ('BE', _('Lampung')), ('BG', _('Sumatera Selatan')), ('BH', _('Jambi')), ('BK', _('Sumatera Utara')), ('BL', _('Nanggroe Aceh Darussalam')), ('BM', _('Riau')), ('BN', _('Kepulauan Bangka Belitung')), ('BP', _('Kepulauan Riau')), ('CC', _('Corps Consulate')), ('CD', _('Corps Diplomatic')), ('D', _('Bandung')), ('DA', _('Kalimantan Selatan')), ('DB', _('Sulawesi Utara Daratan')), ('DC', _('Sulawesi Barat')), ('DD', _('Sulawesi Selatan')), ('DE', _('Maluku')), ('DG', _('Maluku Utara')), ('DH', _('NTT - Timor')), ('DK', _('Bali')), ('DL', _('Sulawesi Utara Kepulauan')), ('DM', _('Gorontalo')), ('DN', _('Sulawesi Tengah')), ('DR', _('NTB - Lombok')), ('DS', _('Papua dan Papua Barat')), ('DT', _('Sulawesi Tenggara')), ('E', _('Cirebon')), ('EA', _('NTB - Sumbawa')), ('EB', _('NTT - Flores')), ('ED', _('NTT - Sumba')), ('F', _('Bogor')), ('G', _('Pekalongan')), ('H', _('Semarang')), ('K', _('Pati')), ('KB', _('Kalimantan Barat')), ('KH', _('Kalimantan Tengah')), ('KT', _('Kalimantan Timur')), ('L', _('Surabaya')), ('M', _('Madura')), ('N', _('Malang')), ('P', _('Jember')), ('R', _('Banyumas')), ('RI', _('Federal Government')), ('S', _('Bojonegoro')), ('T', _('Purwakarta')), ('W', _('Sidoarjo')), ('Z', _('Garut')), )
3,217
Python
.py
102
26.921569
94
0.489711
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,674
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/id/forms.py
""" ID-specific Form helpers """ import re import time from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, Select from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode postcode_re = re.compile(r'^[1-9]\d{4}$') phone_re = re.compile(r'^(\+62|0)[2-9]\d{7,10}$') plate_re = re.compile(r'^(?P<prefix>[A-Z]{1,2}) ' + \ r'(?P<number>\d{1,5})( (?P<suffix>([A-Z]{1,3}|[1-9][0-9]{,2})))?$') nik_re = re.compile(r'^\d{16}$') class IDPostCodeField(Field): """ An Indonesian post code field. http://id.wikipedia.org/wiki/Kode_pos """ default_error_messages = { 'invalid': _('Enter a valid post code'), } def clean(self, value): super(IDPostCodeField, self).clean(value) if value in EMPTY_VALUES: return u'' value = value.strip() if not postcode_re.search(value): raise ValidationError(self.error_messages['invalid']) if int(value) < 10110: raise ValidationError(self.error_messages['invalid']) # 1xxx0 if value[0] == '1' and value[4] != '0': raise ValidationError(self.error_messages['invalid']) return u'%s' % (value, ) class IDProvinceSelect(Select): """ A Select widget that uses a list of provinces of Indonesia as its choices. """ def __init__(self, attrs=None): from id_choices import PROVINCE_CHOICES super(IDProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES) class IDPhoneNumberField(Field): """ An Indonesian telephone number field. http://id.wikipedia.org/wiki/Daftar_kode_telepon_di_Indonesia """ default_error_messages = { 'invalid': _('Enter a valid phone number'), } def clean(self, value): super(IDPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' phone_number = re.sub(r'[\-\s\(\)]', '', smart_unicode(value)) if phone_re.search(phone_number): return smart_unicode(value) raise ValidationError(self.error_messages['invalid']) class IDLicensePlatePrefixSelect(Select): """ A Select widget that uses a list of vehicle license plate prefix code of Indonesia as its choices. http://id.wikipedia.org/wiki/Tanda_Nomor_Kendaraan_Bermotor """ def __init__(self, attrs=None): from id_choices import LICENSE_PLATE_PREFIX_CHOICES super(IDLicensePlatePrefixSelect, self).__init__(attrs, choices=LICENSE_PLATE_PREFIX_CHOICES) class IDLicensePlateField(Field): """ An Indonesian vehicle license plate field. http://id.wikipedia.org/wiki/Tanda_Nomor_Kendaraan_Bermotor Plus: "B 12345 12" """ default_error_messages = { 'invalid': _('Enter a valid vehicle license plate number'), } def clean(self, value): super(IDLicensePlateField, self).clean(value) if value in EMPTY_VALUES: return u'' plate_number = re.sub(r'\s+', ' ', smart_unicode(value.strip())).upper() matches = plate_re.search(plate_number) if matches is None: raise ValidationError(self.error_messages['invalid']) # Make sure prefix is in the list of known codes. from id_choices import LICENSE_PLATE_PREFIX_CHOICES prefix = matches.group('prefix') if prefix not in [choice[0] for choice in LICENSE_PLATE_PREFIX_CHOICES]: raise ValidationError(self.error_messages['invalid']) # Only Jakarta (prefix B) can have 3 letter suffix. suffix = matches.group('suffix') if suffix is not None and len(suffix) == 3 and prefix != 'B': raise ValidationError(self.error_messages['invalid']) # RI plates don't have suffix. if prefix == 'RI' and suffix is not None and suffix != '': raise ValidationError(self.error_messages['invalid']) # Number can't be zero. number = matches.group('number') if number == '0': raise ValidationError(self.error_messages['invalid']) # CD, CC and B 12345 12 if len(number) == 5 or prefix in ('CD', 'CC'): # suffix must be numeric and non-empty if re.match(r'^\d+$', suffix) is None: raise ValidationError(self.error_messages['invalid']) # Known codes range is 12-124 if prefix in ('CD', 'CC') and not (12 <= int(number) <= 124): raise ValidationError(self.error_messages['invalid']) if len(number) == 5 and not (12 <= int(suffix) <= 124): raise ValidationError(self.error_messages['invalid']) else: # suffix must be non-numeric if suffix is not None and re.match(r'^[A-Z]{,3}$', suffix) is None: raise ValidationError(self.error_messages['invalid']) return plate_number class IDNationalIdentityNumberField(Field): """ An Indonesian national identity number (NIK/KTP#) field. http://id.wikipedia.org/wiki/Nomor_Induk_Kependudukan xx.xxxx.ddmmyy.xxxx - 16 digits (excl. dots) """ default_error_messages = { 'invalid': _('Enter a valid NIK/KTP number'), } def clean(self, value): super(IDNationalIdentityNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub(r'[\s.]', '', smart_unicode(value)) if not nik_re.search(value): raise ValidationError(self.error_messages['invalid']) if int(value) == 0: raise ValidationError(self.error_messages['invalid']) def valid_nik_date(year, month, day): try: t1 = (int(year), int(month), int(day), 0, 0, 0, 0, 0, -1) d = time.mktime(t1) t2 = time.localtime(d) if t1[:3] != t2[:3]: return False else: return True except (OverflowError, ValueError): return False year = int(value[10:12]) month = int(value[8:10]) day = int(value[6:8]) current_year = time.localtime().tm_year if year < int(str(current_year)[-2:]): if not valid_nik_date(2000 + int(year), month, day): raise ValidationError(self.error_messages['invalid']) elif not valid_nik_date(1900 + int(year), month, day): raise ValidationError(self.error_messages['invalid']) if value[:6] == '000000' or value[12:] == '0000': raise ValidationError(self.error_messages['invalid']) return '%s.%s.%s.%s' % (value[:2], value[2:6], value[6:12], value[12:])
6,834
Python
.py
160
33.96875
80
0.610297
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,675
uk_regions.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/uk/uk_regions.py
""" Sources: English regions: http://www.statistics.gov.uk/geography/downloads/31_10_01_REGION_names_and_codes_12_00.xls Northern Ireland regions: http://en.wikipedia.org/wiki/List_of_Irish_counties_by_area Welsh regions: http://en.wikipedia.org/wiki/Preserved_counties_of_Wales Scottish regions: http://en.wikipedia.org/wiki/Regions_and_districts_of_Scotland """ from django.utils.translation import ugettext_lazy as _ ENGLAND_REGION_CHOICES = ( ("Bedfordshire", _("Bedfordshire")), ("Buckinghamshire", _("Buckinghamshire")), ("Cambridgeshire", ("Cambridgeshire")), ("Cheshire", _("Cheshire")), ("Cornwall and Isles of Scilly", _("Cornwall and Isles of Scilly")), ("Cumbria", _("Cumbria")), ("Derbyshire", _("Derbyshire")), ("Devon", _("Devon")), ("Dorset", _("Dorset")), ("Durham", _("Durham")), ("East Sussex", _("East Sussex")), ("Essex", _("Essex")), ("Gloucestershire", _("Gloucestershire")), ("Greater London", _("Greater London")), ("Greater Manchester", _("Greater Manchester")), ("Hampshire", _("Hampshire")), ("Hertfordshire", _("Hertfordshire")), ("Kent", _("Kent")), ("Lancashire", _("Lancashire")), ("Leicestershire", _("Leicestershire")), ("Lincolnshire", _("Lincolnshire")), ("Merseyside", _("Merseyside")), ("Norfolk", _("Norfolk")), ("North Yorkshire", _("North Yorkshire")), ("Northamptonshire", _("Northamptonshire")), ("Northumberland", _("Northumberland")), ("Nottinghamshire", _("Nottinghamshire")), ("Oxfordshire", _("Oxfordshire")), ("Shropshire", _("Shropshire")), ("Somerset", _("Somerset")), ("South Yorkshire", _("South Yorkshire")), ("Staffordshire", _("Staffordshire")), ("Suffolk", _("Suffolk")), ("Surrey", _("Surrey")), ("Tyne and Wear", _("Tyne and Wear")), ("Warwickshire", _("Warwickshire")), ("West Midlands", _("West Midlands")), ("West Sussex", _("West Sussex")), ("West Yorkshire", _("West Yorkshire")), ("Wiltshire", _("Wiltshire")), ("Worcestershire", _("Worcestershire")), ) NORTHERN_IRELAND_REGION_CHOICES = ( ("County Antrim", _("County Antrim")), ("County Armagh", _("County Armagh")), ("County Down", _("County Down")), ("County Fermanagh", _("County Fermanagh")), ("County Londonderry", _("County Londonderry")), ("County Tyrone", _("County Tyrone")), ) WALES_REGION_CHOICES = ( ("Clwyd", _("Clwyd")), ("Dyfed", _("Dyfed")), ("Gwent", _("Gwent")), ("Gwynedd", _("Gwynedd")), ("Mid Glamorgan", _("Mid Glamorgan")), ("Powys", _("Powys")), ("South Glamorgan", _("South Glamorgan")), ("West Glamorgan", _("West Glamorgan")), ) SCOTTISH_REGION_CHOICES = ( ("Borders", _("Borders")), ("Central Scotland", _("Central Scotland")), ("Dumfries and Galloway", _("Dumfries and Galloway")), ("Fife", _("Fife")), ("Grampian", _("Grampian")), ("Highland", _("Highland")), ("Lothian", _("Lothian")), ("Orkney Islands", _("Orkney Islands")), ("Shetland Islands", _("Shetland Islands")), ("Strathclyde", _("Strathclyde")), ("Tayside", _("Tayside")), ("Western Isles", _("Western Isles")), ) UK_NATIONS_CHOICES = ( ("England", _("England")), ("Northern Ireland", _("Northern Ireland")), ("Scotland", _("Scotland")), ("Wales", _("Wales")), ) UK_REGION_CHOICES = ENGLAND_REGION_CHOICES + NORTHERN_IRELAND_REGION_CHOICES + WALES_REGION_CHOICES + SCOTTISH_REGION_CHOICES
3,504
Python
.py
90
34.522222
125
0.603757
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,676
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/uk/forms.py
""" UK-specific Form helpers """ import re from django.forms.fields import CharField, Select from django.forms import ValidationError from django.utils.translation import ugettext_lazy as _ class UKPostcodeField(CharField): """ A form field that validates its input is a UK postcode. The regular expression used is sourced from the schema for British Standard BS7666 address types: http://www.govtalk.gov.uk/gdsc/schemas/bs7666-v2-0.xsd The value is uppercased and a space added in the correct place, if required. """ default_error_messages = { 'invalid': _(u'Enter a valid postcode.'), } outcode_pattern = '[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW])' incode_pattern = '[0-9][ABD-HJLNP-UW-Z]{2}' postcode_regex = re.compile(r'^(GIR 0AA|%s %s)$' % (outcode_pattern, incode_pattern)) space_regex = re.compile(r' *(%s)$' % incode_pattern) def clean(self, value): value = super(UKPostcodeField, self).clean(value) if value == u'': return value postcode = value.upper().strip() # Put a single space before the incode (second part). postcode = self.space_regex.sub(r' \1', postcode) if not self.postcode_regex.search(postcode): raise ValidationError(self.error_messages['invalid']) return postcode class UKCountySelect(Select): """ A Select widget that uses a list of UK Counties/Regions as its choices. """ def __init__(self, attrs=None): from uk_regions import UK_REGION_CHOICES super(UKCountySelect, self).__init__(attrs, choices=UK_REGION_CHOICES) class UKNationSelect(Select): """ A Select widget that uses a list of UK Nations as its choices. """ def __init__(self, attrs=None): from uk_regions import UK_NATIONS_CHOICES super(UKNationSelect, self).__init__(attrs, choices=UK_NATIONS_CHOICES)
1,943
Python
.py
45
37.466667
104
0.674074
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,677
sk_regions.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/sk/sk_regions.py
""" Slovak regions according to http://sk.wikipedia.org/wiki/Administrat%C3%ADvne_%C4%8Dlenenie_Slovenska """ from django.utils.translation import ugettext_lazy as _ REGION_CHOICES = ( ('BB', _('Banska Bystrica region')), ('BA', _('Bratislava region')), ('KE', _('Kosice region')), ('NR', _('Nitra region')), ('PO', _('Presov region')), ('TN', _('Trencin region')), ('TT', _('Trnava region')), ('ZA', _('Zilina region')), )
458
Python
.py
14
29.285714
101
0.604072
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,678
sk_districts.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/sk/sk_districts.py
""" Slovak districts according to http://sk.wikipedia.org/wiki/Administrat%C3%ADvne_%C4%8Dlenenie_Slovenska """ from django.utils.translation import ugettext_lazy as _ DISTRICT_CHOICES = ( ('BB', _('Banska Bystrica')), ('BS', _('Banska Stiavnica')), ('BJ', _('Bardejov')), ('BN', _('Banovce nad Bebravou')), ('BR', _('Brezno')), ('BA1', _('Bratislava I')), ('BA2', _('Bratislava II')), ('BA3', _('Bratislava III')), ('BA4', _('Bratislava IV')), ('BA5', _('Bratislava V')), ('BY', _('Bytca')), ('CA', _('Cadca')), ('DT', _('Detva')), ('DK', _('Dolny Kubin')), ('DS', _('Dunajska Streda')), ('GA', _('Galanta')), ('GL', _('Gelnica')), ('HC', _('Hlohovec')), ('HE', _('Humenne')), ('IL', _('Ilava')), ('KK', _('Kezmarok')), ('KN', _('Komarno')), ('KE1', _('Kosice I')), ('KE2', _('Kosice II')), ('KE3', _('Kosice III')), ('KE4', _('Kosice IV')), ('KEO', _('Kosice - okolie')), ('KA', _('Krupina')), ('KM', _('Kysucke Nove Mesto')), ('LV', _('Levice')), ('LE', _('Levoca')), ('LM', _('Liptovsky Mikulas')), ('LC', _('Lucenec')), ('MA', _('Malacky')), ('MT', _('Martin')), ('ML', _('Medzilaborce')), ('MI', _('Michalovce')), ('MY', _('Myjava')), ('NO', _('Namestovo')), ('NR', _('Nitra')), ('NM', _('Nove Mesto nad Vahom')), ('NZ', _('Nove Zamky')), ('PE', _('Partizanske')), ('PK', _('Pezinok')), ('PN', _('Piestany')), ('PT', _('Poltar')), ('PP', _('Poprad')), ('PB', _('Povazska Bystrica')), ('PO', _('Presov')), ('PD', _('Prievidza')), ('PU', _('Puchov')), ('RA', _('Revuca')), ('RS', _('Rimavska Sobota')), ('RV', _('Roznava')), ('RK', _('Ruzomberok')), ('SB', _('Sabinov')), ('SC', _('Senec')), ('SE', _('Senica')), ('SI', _('Skalica')), ('SV', _('Snina')), ('SO', _('Sobrance')), ('SN', _('Spisska Nova Ves')), ('SL', _('Stara Lubovna')), ('SP', _('Stropkov')), ('SK', _('Svidnik')), ('SA', _('Sala')), ('TO', _('Topolcany')), ('TV', _('Trebisov')), ('TN', _('Trencin')), ('TT', _('Trnava')), ('TR', _('Turcianske Teplice')), ('TS', _('Tvrdosin')), ('VK', _('Velky Krtis')), ('VT', _('Vranov nad Toplou')), ('ZM', _('Zlate Moravce')), ('ZV', _('Zvolen')), ('ZC', _('Zarnovica')), ('ZH', _('Ziar nad Hronom')), ('ZA', _('Zilina')), )
2,453
Python
.py
85
24.117647
103
0.434066
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,679
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/sk/forms.py
""" Slovak-specific form helpers """ from django.forms.fields import Select, RegexField from django.utils.translation import ugettext_lazy as _ class SKRegionSelect(Select): """ A select widget widget with list of Slovak regions as choices. """ def __init__(self, attrs=None): from sk_regions import REGION_CHOICES super(SKRegionSelect, self).__init__(attrs, choices=REGION_CHOICES) class SKDistrictSelect(Select): """ A select widget with list of Slovak districts as choices. """ def __init__(self, attrs=None): from sk_districts import DISTRICT_CHOICES super(SKDistrictSelect, self).__init__(attrs, choices=DISTRICT_CHOICES) class SKPostalCodeField(RegexField): """ A form field that validates its input as Slovak postal code. Valid form is XXXXX or XXX XX, where X represents integer. """ default_error_messages = { 'invalid': _(u'Enter a postal code in the format XXXXX or XXX XX.'), } def __init__(self, *args, **kwargs): super(SKPostalCodeField, self).__init__(r'^\d{5}$|^\d{3} \d{2}$', max_length=None, min_length=None, *args, **kwargs) def clean(self, value): """ Validates the input and returns a string that contains only numbers. Returns an empty string for empty values. """ v = super(SKPostalCodeField, self).clean(value) return v.replace(' ', '')
1,439
Python
.py
37
33.081081
79
0.66404
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,680
fr_department.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/fr/fr_department.py
# -*- coding: utf-8 -*- DEPARTMENT_ASCII_CHOICES = ( ('01', '01 - Ain'), ('02', '02 - Aisne'), ('03', '03 - Allier'), ('04', '04 - Alpes-de-Haute-Provence'), ('05', '05 - Hautes-Alpes'), ('06', '06 - Alpes-Maritimes'), ('07', '07 - Ardeche'), ('08', '08 - Ardennes'), ('09', '09 - Ariege'), ('10', '10 - Aube'), ('11', '11 - Aude'), ('12', '12 - Aveyron'), ('13', '13 - Bouches-du-Rhone'), ('14', '14 - Calvados'), ('15', '15 - Cantal'), ('16', '16 - Charente'), ('17', '17 - Charente-Maritime'), ('18', '18 - Cher'), ('19', '19 - Correze'), ('21', '21 - Cote-d\'Or'), ('22', '22 - Cotes-d\'Armor'), ('23', '23 - Creuse'), ('24', '24 - Dordogne'), ('25', '25 - Doubs'), ('26', '26 - Drome'), ('27', '27 - Eure'), ('28', '28 - Eure-et-Loire'), ('29', '29 - Finistere'), ('2A', '2A - Corse-du-Sud'), ('2B', '2B - Haute-Corse'), ('30', '30 - Gard'), ('31', '31 - Haute-Garonne'), ('32', '32 - Gers'), ('33', '33 - Gironde'), ('34', '34 - Herault'), ('35', '35 - Ille-et-Vilaine'), ('36', '36 - Indre'), ('37', '37 - Indre-et-Loire'), ('38', '38 - Isere'), ('39', '39 - Jura'), ('40', '40 - Landes'), ('41', '41 - Loir-et-Cher'), ('42', '42 - Loire'), ('43', '43 - Haute-Loire'), ('44', '44 - Loire-Atlantique'), ('45', '45 - Loiret'), ('46', '46 - Lot'), ('47', '47 - Lot-et-Garonne'), ('48', '48 - Lozere'), ('49', '49 - Maine-et-Loire'), ('50', '50 - Manche'), ('51', '51 - Marne'), ('52', '52 - Haute-Marne'), ('53', '53 - Mayenne'), ('54', '54 - Meurthe-et-Moselle'), ('55', '55 - Meuse'), ('56', '56 - Morbihan'), ('57', '57 - Moselle'), ('58', '58 - Nievre'), ('59', '59 - Nord'), ('60', '60 - Oise'), ('61', '61 - Orne'), ('62', '62 - Pas-de-Calais'), ('63', '63 - Puy-de-Dome'), ('64', '64 - Pyrenees-Atlantiques'), ('65', '65 - Hautes-Pyrenees'), ('66', '66 - Pyrenees-Orientales'), ('67', '67 - Bas-Rhin'), ('68', '68 - Haut-Rhin'), ('69', '69 - Rhone'), ('70', '70 - Haute-Saone'), ('71', '71 - Saone-et-Loire'), ('72', '72 - Sarthe'), ('73', '73 - Savoie'), ('74', '74 - Haute-Savoie'), ('75', '75 - Paris'), ('76', '76 - Seine-Maritime'), ('77', '77 - Seine-et-Marne'), ('78', '78 - Yvelines'), ('79', '79 - Deux-Sevres'), ('80', '80 - Somme'), ('81', '81 - Tarn'), ('82', '82 - Tarn-et-Garonne'), ('83', '83 - Var'), ('84', '84 - Vaucluse'), ('85', '85 - Vendee'), ('86', '86 - Vienne'), ('87', '87 - Haute-Vienne'), ('88', '88 - Vosges'), ('89', '89 - Yonne'), ('90', '90 - Territoire de Belfort'), ('91', '91 - Essonne'), ('92', '92 - Hauts-de-Seine'), ('93', '93 - Seine-Saint-Denis'), ('94', '94 - Val-de-Marne'), ('95', '95 - Val-d\'Oise'), ('971', '971 - Guadeloupe'), ('972', '972 - Martinique'), ('973', '973 - Guyane'), ('974', '974 - La Reunion'), ('975', '975 - Saint-Pierre-et-Miquelon'), ('976', '976 - Mayotte'), ('984', '984 - Terres Australes et Antarctiques'), ('986', '986 - Wallis et Futuna'), ('987', '987 - Polynesie Francaise'), ('988', '988 - Nouvelle-Caledonie'), )
3,326
Python
.py
109
25.614679
54
0.442475
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,681
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/fr/forms.py
""" FR-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re phone_digits_re = re.compile(r'^0\d(\s|\.)?(\d{2}(\s|\.)?){3}\d{2}$') class FRZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a zip code in the format XXXXX.'), } def __init__(self, *args, **kwargs): super(FRZipCodeField, self).__init__(r'^\d{5}$', max_length=None, min_length=None, *args, **kwargs) class FRPhoneNumberField(Field): """ Validate local French phone number (not international ones) The correct format is '0X XX XX XX XX'. '0X.XX.XX.XX.XX' and '0XXXXXXXXX' validate but are corrected to '0X XX XX XX XX'. """ default_error_messages = { 'invalid': _('Phone numbers must be in 0X XX XX XX XX format.'), } def clean(self, value): super(FRPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\.|\s)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: return u'%s %s %s %s %s' % (value[0:2], value[2:4], value[4:6], value[6:8], value[8:10]) raise ValidationError(self.error_messages['invalid']) class FRDepartmentSelect(Select): """ A Select widget that uses a list of FR departments as its choices. """ def __init__(self, attrs=None): from fr_department import DEPARTMENT_ASCII_CHOICES super(FRDepartmentSelect, self).__init__(attrs, choices=DEPARTMENT_ASCII_CHOICES)
1,747
Python
.py
43
35.069767
100
0.65566
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,682
tr_provinces.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/tr/tr_provinces.py
# -*- coding: utf-8 -*- """ This exists in this standalone file so that it's only imported into memory when explicitly needed. """ PROVINCE_CHOICES = ( ('01', ('Adana')), ('02', ('Adıyaman')), ('03', ('Afyonkarahisar')), ('04', ('Ağrı')), ('68', ('Aksaray')), ('05', ('Amasya')), ('06', ('Ankara')), ('07', ('Antalya')), ('75', ('Ardahan')), ('08', ('Artvin')), ('09', ('Aydın')), ('10', ('Balıkesir')), ('74', ('Bartın')), ('72', ('Batman')), ('69', ('Bayburt')), ('11', ('Bilecik')), ('12', ('Bingöl')), ('13', ('Bitlis')), ('14', ('Bolu')), ('15', ('Burdur')), ('16', ('Bursa')), ('17', ('Çanakkale')), ('18', ('Çankırı')), ('19', ('Çorum')), ('20', ('Denizli')), ('21', ('Diyarbakır')), ('81', ('Düzce')), ('22', ('Edirne')), ('23', ('Elazığ')), ('24', ('Erzincan')), ('25', ('Erzurum')), ('26', ('Eskişehir')), ('27', ('Gaziantep')), ('28', ('Giresun')), ('29', ('Gümüşhane')), ('30', ('Hakkari')), ('31', ('Hatay')), ('76', ('Iğdır')), ('32', ('Isparta')), ('33', ('Mersin')), ('34', ('İstanbul')), ('35', ('İzmir')), ('78', ('Karabük')), ('36', ('Kars')), ('37', ('Kastamonu')), ('38', ('Kayseri')), ('39', ('Kırklareli')), ('40', ('Kırşehir')), ('41', ('Kocaeli')), ('42', ('Konya')), ('43', ('Kütahya')), ('44', ('Malatya')), ('45', ('Manisa')), ('46', ('Kahramanmaraş')), ('70', ('Karaman')), ('71', ('Kırıkkale')), ('79', ('Kilis')), ('47', ('Mardin')), ('48', ('Muğla')), ('49', ('Muş')), ('50', ('Nevşehir')), ('51', ('Niğde')), ('52', ('Ordu')), ('80', ('Osmaniye')), ('53', ('Rize')), ('54', ('Sakarya')), ('55', ('Samsun')), ('56', ('Siirt')), ('57', ('Sinop')), ('58', ('Sivas')), ('73', ('Şırnak')), ('59', ('Tekirdağ')), ('60', ('Tokat')), ('61', ('Trabzon')), ('62', ('Tunceli')), ('63', ('Şanlıurfa')), ('64', ('Uşak')), ('65', ('Van')), ('77', ('Yalova')), ('66', ('Yozgat')), ('67', ('Zonguldak')), )
2,191
Python
.py
88
19.727273
74
0.390291
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,683
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/localflavor/tr/forms.py
""" TR-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select, CharField from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re phone_digits_re = re.compile(r'^(\+90|0)? ?(([1-9]\d{2})|\([1-9]\d{2}\)) ?([2-9]\d{2} ?\d{2} ?\d{2})$') class TRPostalCodeField(RegexField): default_error_messages = { 'invalid': _(u'Enter a postal code in the format XXXXX.'), } def __init__(self, *args, **kwargs): super(TRPostalCodeField, self).__init__(r'^\d{5}$', max_length=5, min_length=5, *args, **kwargs) def clean(self, value): value = super(TRPostalCodeField, self).clean(value) if value in EMPTY_VALUES: return u'' if len(value) != 5: raise ValidationError(self.error_messages['invalid']) province_code = int(value[:2]) if province_code == 0 or province_code > 81: raise ValidationError(self.error_messages['invalid']) return value class TRPhoneNumberField(CharField): default_error_messages = { 'invalid': _(u'Phone numbers must be in 0XXX XXX XXXX format.'), } def clean(self, value): super(TRPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\(|\)|\s+)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: return u'%s%s' % (m.group(2), m.group(4)) raise ValidationError(self.error_messages['invalid']) class TRIdentificationNumberField(Field): """ A Turkey Identification Number number. See: http://tr.wikipedia.org/wiki/T%C3%BCrkiye_Cumhuriyeti_Kimlik_Numaras%C4%B1 Checks the following rules to determine whether the number is valid: * The number is 11-digits. * First digit is not 0. * Conforms to the following two formula: (sum(1st, 3rd, 5th, 7th, 9th)*7 - sum(2nd,4th,6th,8th)) % 10 = 10th digit sum(1st to 10th) % 10 = 11th digit """ default_error_messages = { 'invalid': _(u'Enter a valid Turkish Identification number.'), 'not_11': _(u'Turkish Identification number must be 11 digits.'), } def clean(self, value): super(TRIdentificationNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' if len(value) != 11: raise ValidationError(self.error_messages['not_11']) if not re.match(r'^\d{11}$', value): raise ValidationError(self.error_messages['invalid']) if int(value[0]) == 0: raise ValidationError(self.error_messages['invalid']) chksum = (sum([int(value[i]) for i in xrange(0,9,2)])*7- sum([int(value[i]) for i in xrange(1,9,2)])) % 10 if chksum != int(value[9]) or \ (sum([int(value[i]) for i in xrange(10)]) % 10) != int(value[10]): raise ValidationError(self.error_messages['invalid']) return value class TRProvinceSelect(Select): """ A Select widget that uses a list of provinces in Turkey as its choices. """ def __init__(self, attrs=None): from tr_provinces import PROVINCE_CHOICES super(TRProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES)
3,430
Python
.py
78
36.333333
103
0.625936
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,684
signals.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/comments/signals.py
""" Signals relating to comments. """ from django.dispatch import Signal # Sent just before a comment will be posted (after it's been approved and # moderated; this can be used to modify the comment (in place) with posting # details or other such actions. If any receiver returns False the comment will be # discarded and a 403 (not allowed) response. This signal is sent at more or less # the same time (just before, actually) as the Comment object's pre-save signal, # except that the HTTP request is sent along with this signal. comment_will_be_posted = Signal(providing_args=["comment", "request"]) # Sent just after a comment was posted. See above for how this differs # from the Comment object's post-save signal. comment_was_posted = Signal(providing_args=["comment", "request"]) # Sent after a comment was "flagged" in some way. Check the flag to see if this # was a user requesting removal of a comment, a moderator approving/removing a # comment, or some other custom user flag. comment_was_flagged = Signal(providing_args=["comment", "flag", "created", "request"])
1,079
Python
.py
18
58.777778
86
0.769376
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,685
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/comments/models.py
import datetime from django.contrib.auth.models import User from django.contrib.comments.managers import CommentManager from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.db import models from django.core import urlresolvers from django.utils.translation import ugettext_lazy as _ from django.conf import settings COMMENT_MAX_LENGTH = getattr(settings,'COMMENT_MAX_LENGTH',3000) class BaseCommentAbstractModel(models.Model): """ An abstract base class that any custom comment models probably should subclass. """ # Content-object field content_type = models.ForeignKey(ContentType, verbose_name=_('content type'), related_name="content_type_set_for_%(class)s") object_pk = models.TextField(_('object ID')) content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk") # Metadata about the comment site = models.ForeignKey(Site) class Meta: abstract = True def get_content_object_url(self): """ Get a URL suitable for redirecting to the content object. """ return urlresolvers.reverse( "comments-url-redirect", args=(self.content_type_id, self.object_pk) ) class Comment(BaseCommentAbstractModel): """ A user comment about some object. """ # Who posted this comment? If ``user`` is set then it was an authenticated # user; otherwise at least user_name should have been set and the comment # was posted by a non-authenticated user. user = models.ForeignKey(User, verbose_name=_('user'), blank=True, null=True, related_name="%(class)s_comments") user_name = models.CharField(_("user's name"), max_length=50, blank=True) user_email = models.EmailField(_("user's email address"), blank=True) user_url = models.URLField(_("user's URL"), blank=True) comment = models.TextField(_('comment'), max_length=COMMENT_MAX_LENGTH) # Metadata about the comment submit_date = models.DateTimeField(_('date/time submitted'), default=None) ip_address = models.IPAddressField(_('IP address'), blank=True, null=True) is_public = models.BooleanField(_('is public'), default=True, help_text=_('Uncheck this box to make the comment effectively ' \ 'disappear from the site.')) is_removed = models.BooleanField(_('is removed'), default=False, help_text=_('Check this box if the comment is inappropriate. ' \ 'A "This comment has been removed" message will ' \ 'be displayed instead.')) # Manager objects = CommentManager() class Meta: db_table = "django_comments" ordering = ('submit_date',) permissions = [("can_moderate", "Can moderate comments")] verbose_name = _('comment') verbose_name_plural = _('comments') def __unicode__(self): return "%s: %s..." % (self.name, self.comment[:50]) def save(self, *args, **kwargs): if self.submit_date is None: self.submit_date = datetime.datetime.now() super(Comment, self).save(*args, **kwargs) def _get_userinfo(self): """ Get a dictionary that pulls together information about the poster safely for both authenticated and non-authenticated comments. This dict will have ``name``, ``email``, and ``url`` fields. """ if not hasattr(self, "_userinfo"): self._userinfo = { "name" : self.user_name, "email" : self.user_email, "url" : self.user_url } if self.user_id: u = self.user if u.email: self._userinfo["email"] = u.email # If the user has a full name, use that for the user name. # However, a given user_name overrides the raw user.username, # so only use that if this comment has no associated name. if u.get_full_name(): self._userinfo["name"] = self.user.get_full_name() elif not self.user_name: self._userinfo["name"] = u.username return self._userinfo userinfo = property(_get_userinfo, doc=_get_userinfo.__doc__) def _get_name(self): return self.userinfo["name"] def _set_name(self, val): if self.user_id: raise AttributeError(_("This comment was posted by an authenticated "\ "user and thus the name is read-only.")) self.user_name = val name = property(_get_name, _set_name, doc="The name of the user who posted this comment") def _get_email(self): return self.userinfo["email"] def _set_email(self, val): if self.user_id: raise AttributeError(_("This comment was posted by an authenticated "\ "user and thus the email is read-only.")) self.user_email = val email = property(_get_email, _set_email, doc="The email of the user who posted this comment") def _get_url(self): return self.userinfo["url"] def _set_url(self, val): self.user_url = val url = property(_get_url, _set_url, doc="The URL given by the user who posted this comment") def get_absolute_url(self, anchor_pattern="#c%(id)s"): return self.get_content_object_url() + (anchor_pattern % self.__dict__) def get_as_text(self): """ Return this comment as plain text. Useful for emails. """ d = { 'user': self.user or self.name, 'date': self.submit_date, 'comment': self.comment, 'domain': self.site.domain, 'url': self.get_absolute_url() } return _('Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s') % d class CommentFlag(models.Model): """ Records a flag on a comment. This is intentionally flexible; right now, a flag could be: * A "removal suggestion" -- where a user suggests a comment for (potential) removal. * A "moderator deletion" -- used when a moderator deletes a comment. You can (ab)use this model to add other flags, if needed. However, by design users are only allowed to flag a comment with a given flag once; if you want rating look elsewhere. """ user = models.ForeignKey(User, verbose_name=_('user'), related_name="comment_flags") comment = models.ForeignKey(Comment, verbose_name=_('comment'), related_name="flags") flag = models.CharField(_('flag'), max_length=30, db_index=True) flag_date = models.DateTimeField(_('date'), default=None) # Constants for flag types SUGGEST_REMOVAL = "removal suggestion" MODERATOR_DELETION = "moderator deletion" MODERATOR_APPROVAL = "moderator approval" class Meta: db_table = 'django_comment_flags' unique_together = [('user', 'comment', 'flag')] verbose_name = _('comment flag') verbose_name_plural = _('comment flags') def __unicode__(self): return "%s flag of comment ID %s by %s" % \ (self.flag, self.comment_id, self.user.username) def save(self, *args, **kwargs): if self.flag_date is None: self.flag_date = datetime.datetime.now() super(CommentFlag, self).save(*args, **kwargs)
7,636
Python
.py
161
38.378882
97
0.619476
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,686
feeds.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/comments/feeds.py
from django.conf import settings from django.contrib.syndication.views import Feed from django.contrib.sites.models import Site from django.contrib import comments from django.utils.translation import ugettext as _ class LatestCommentFeed(Feed): """Feed of latest comments on the current site.""" def title(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return _("%(site_name)s comments") % dict(site_name=self._site.name) def link(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return "http://%s/" % (self._site.domain) def description(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return _("Latest comments on %(site_name)s") % dict(site_name=self._site.name) def items(self): qs = comments.get_model().objects.filter( site__pk = settings.SITE_ID, is_public = True, is_removed = False, ) if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None): where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)'] params = [settings.COMMENTS_BANNED_USERS_GROUP] qs = qs.extra(where=where, params=params) return qs.order_by('-submit_date')[:40] def item_pubdate(self, item): return item.submit_date
1,439
Python
.py
32
36.90625
97
0.635261
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,687
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/comments/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns('django.contrib.comments.views', url(r'^post/$', 'comments.post_comment', name='comments-post-comment'), url(r'^posted/$', 'comments.comment_done', name='comments-comment-done'), url(r'^flag/(\d+)/$', 'moderation.flag', name='comments-flag'), url(r'^flagged/$', 'moderation.flag_done', name='comments-flag-done'), url(r'^delete/(\d+)/$', 'moderation.delete', name='comments-delete'), url(r'^deleted/$', 'moderation.delete_done', name='comments-delete-done'), url(r'^approve/(\d+)/$', 'moderation.approve', name='comments-approve'), url(r'^approved/$', 'moderation.approve_done', name='comments-approve-done'), ) urlpatterns += patterns('', url(r'^cr/(\d+)/(.+)/$', 'django.contrib.contenttypes.views.shortcut', name='comments-url-redirect'), )
941
Python
.py
14
63.5
105
0.601081
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,688
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/comments/__init__.py
from django.conf import settings from django.core import urlresolvers from django.core.exceptions import ImproperlyConfigured from django.contrib.comments.models import Comment from django.contrib.comments.forms import CommentForm from django.utils.importlib import import_module DEFAULT_COMMENTS_APP = 'django.contrib.comments' def get_comment_app(): """ Get the comment app (i.e. "django.contrib.comments") as defined in the settings """ # Make sure the app's in INSTALLED_APPS comments_app = get_comment_app_name() if comments_app not in settings.INSTALLED_APPS: raise ImproperlyConfigured("The COMMENTS_APP (%r) "\ "must be in INSTALLED_APPS" % settings.COMMENTS_APP) # Try to import the package try: package = import_module(comments_app) except ImportError: raise ImproperlyConfigured("The COMMENTS_APP setting refers to "\ "a non-existing package.") return package def get_comment_app_name(): """ Returns the name of the comment app (either the setting value, if it exists, or the default). """ return getattr(settings, 'COMMENTS_APP', DEFAULT_COMMENTS_APP) def get_model(): """ Returns the comment model class. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_model"): return get_comment_app().get_model() else: return Comment def get_form(): """ Returns the comment ModelForm class. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_form"): return get_comment_app().get_form() else: return CommentForm def get_form_target(): """ Returns the target URL for the comment form submission view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_form_target"): return get_comment_app().get_form_target() else: return urlresolvers.reverse("django.contrib.comments.views.comments.post_comment") def get_flag_url(comment): """ Get the URL for the "flag this comment" view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_flag_url"): return get_comment_app().get_flag_url(comment) else: return urlresolvers.reverse("django.contrib.comments.views.moderation.flag", args=(comment.id,)) def get_delete_url(comment): """ Get the URL for the "delete this comment" view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_delete_url"): return get_comment_app().get_delete_url(comment) else: return urlresolvers.reverse("django.contrib.comments.views.moderation.delete", args=(comment.id,)) def get_approve_url(comment): """ Get the URL for the "approve this comment from moderation" view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_approve_url"): return get_comment_app().get_approve_url(comment) else: return urlresolvers.reverse("django.contrib.comments.views.moderation.approve", args=(comment.id,))
3,333
Python
.py
80
34.55
104
0.663171
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,689
admin.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/comments/admin.py
from django.contrib import admin from django.contrib.comments.models import Comment from django.utils.translation import ugettext_lazy as _, ungettext from django.contrib.comments import get_model from django.contrib.comments.views.moderation import perform_flag, perform_approve, perform_delete class CommentsAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('content_type', 'object_pk', 'site')} ), (_('Content'), {'fields': ('user', 'user_name', 'user_email', 'user_url', 'comment')} ), (_('Metadata'), {'fields': ('submit_date', 'ip_address', 'is_public', 'is_removed')} ), ) list_display = ('name', 'content_type', 'object_pk', 'ip_address', 'submit_date', 'is_public', 'is_removed') list_filter = ('submit_date', 'site', 'is_public', 'is_removed') date_hierarchy = 'submit_date' ordering = ('-submit_date',) raw_id_fields = ('user',) search_fields = ('comment', 'user__username', 'user_name', 'user_email', 'user_url', 'ip_address') actions = ["flag_comments", "approve_comments", "remove_comments"] def get_actions(self, request): actions = super(CommentsAdmin, self).get_actions(request) # Only superusers should be able to delete the comments from the DB. if not request.user.is_superuser and 'delete_selected' in actions: actions.pop('delete_selected') if not request.user.has_perm('comments.can_moderate'): if 'approve_comments' in actions: actions.pop('approve_comments') if 'remove_comments' in actions: actions.pop('remove_comments') return actions def flag_comments(self, request, queryset): self._bulk_flag(request, queryset, perform_flag, lambda n: ungettext('flagged', 'flagged', n)) flag_comments.short_description = _("Flag selected comments") def approve_comments(self, request, queryset): self._bulk_flag(request, queryset, perform_approve, lambda n: ungettext('approved', 'approved', n)) approve_comments.short_description = _("Approve selected comments") def remove_comments(self, request, queryset): self._bulk_flag(request, queryset, perform_delete, lambda n: ungettext('removed', 'removed', n)) remove_comments.short_description = _("Remove selected comments") def _bulk_flag(self, request, queryset, action, done_message): """ Flag, approve, or remove some comments from an admin action. Actually calls the `action` argument to perform the heavy lifting. """ n_comments = 0 for comment in queryset: action(request, comment) n_comments += 1 msg = ungettext(u'1 comment was successfully %(action)s.', u'%(count)s comments were successfully %(action)s.', n_comments) self.message_user(request, msg % {'count': n_comments, 'action': done_message(n_comments)}) # Only register the default admin if the model is the built-in comment model # (this won't be true if there's a custom comment app). if get_model() is Comment: admin.site.register(Comment, CommentsAdmin)
3,299
Python
.py
64
42.6875
112
0.636392
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,690
moderation.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/comments/moderation.py
""" A generic comment-moderation system which allows configuration of moderation options on a per-model basis. To use, do two things: 1. Create or import a subclass of ``CommentModerator`` defining the options you want. 2. Import ``moderator`` from this module and register one or more models, passing the models and the ``CommentModerator`` options class you want to use. Example ------- First, we define a simple model class which might represent entries in a Weblog:: from django.db import models class Entry(models.Model): title = models.CharField(maxlength=250) body = models.TextField() pub_date = models.DateField() enable_comments = models.BooleanField() Then we create a ``CommentModerator`` subclass specifying some moderation options:: from django.contrib.comments.moderation import CommentModerator, moderator class EntryModerator(CommentModerator): email_notification = True enable_field = 'enable_comments' And finally register it for moderation:: moderator.register(Entry, EntryModerator) This sample class would apply two moderation steps to each new comment submitted on an Entry: * If the entry's ``enable_comments`` field is set to ``False``, the comment will be rejected (immediately deleted). * If the comment is successfully posted, an email notification of the comment will be sent to site staff. For a full list of built-in moderation options and other configurability, see the documentation for the ``CommentModerator`` class. """ import datetime from django.conf import settings from django.core.mail import send_mail from django.contrib.comments import signals from django.db.models.base import ModelBase from django.template import Context, loader from django.contrib import comments from django.contrib.sites.models import Site class AlreadyModerated(Exception): """ Raised when a model which is already registered for moderation is attempting to be registered again. """ pass class NotModerated(Exception): """ Raised when a model which is not registered for moderation is attempting to be unregistered. """ pass class CommentModerator(object): """ Encapsulates comment-moderation options for a given model. This class is not designed to be used directly, since it doesn't enable any of the available moderation options. Instead, subclass it and override attributes to enable different options:: ``auto_close_field`` If this is set to the name of a ``DateField`` or ``DateTimeField`` on the model for which comments are being moderated, new comments for objects of that model will be disallowed (immediately deleted) when a certain number of days have passed after the date specified in that field. Must be used in conjunction with ``close_after``, which specifies the number of days past which comments should be disallowed. Default value is ``None``. ``auto_moderate_field`` Like ``auto_close_field``, but instead of outright deleting new comments when the requisite number of days have elapsed, it will simply set the ``is_public`` field of new comments to ``False`` before saving them. Must be used in conjunction with ``moderate_after``, which specifies the number of days past which comments should be moderated. Default value is ``None``. ``close_after`` If ``auto_close_field`` is used, this must specify the number of days past the value of the field specified by ``auto_close_field`` after which new comments for an object should be disallowed. Default value is ``None``. ``email_notification`` If ``True``, any new comment on an object of this model which survives moderation will generate an email to site staff. Default value is ``False``. ``enable_field`` If this is set to the name of a ``BooleanField`` on the model for which comments are being moderated, new comments on objects of that model will be disallowed (immediately deleted) whenever the value of that field is ``False`` on the object the comment would be attached to. Default value is ``None``. ``moderate_after`` If ``auto_moderate_field`` is used, this must specify the number of days past the value of the field specified by ``auto_moderate_field`` after which new comments for an object should be marked non-public. Default value is ``None``. Most common moderation needs can be covered by changing these attributes, but further customization can be obtained by subclassing and overriding the following methods. Each method will be called with three arguments: ``comment``, which is the comment being submitted, ``content_object``, which is the object the comment will be attached to, and ``request``, which is the ``HttpRequest`` in which the comment is being submitted:: ``allow`` Should return ``True`` if the comment should be allowed to post on the content object, and ``False`` otherwise (in which case the comment will be immediately deleted). ``email`` If email notification of the new comment should be sent to site staff or moderators, this method is responsible for sending the email. ``moderate`` Should return ``True`` if the comment should be moderated (in which case its ``is_public`` field will be set to ``False`` before saving), and ``False`` otherwise (in which case the ``is_public`` field will not be changed). Subclasses which want to introspect the model for which comments are being moderated can do so through the attribute ``_model``, which will be the model class. """ auto_close_field = None auto_moderate_field = None close_after = None email_notification = False enable_field = None moderate_after = None def __init__(self, model): self._model = model def _get_delta(self, now, then): """ Internal helper which will return a ``datetime.timedelta`` representing the time between ``now`` and ``then``. Assumes ``now`` is a ``datetime.date`` or ``datetime.datetime`` later than ``then``. If ``now`` and ``then`` are not of the same type due to one of them being a ``datetime.date`` and the other being a ``datetime.datetime``, both will be coerced to ``datetime.date`` before calculating the delta. """ if now.__class__ is not then.__class__: now = datetime.date(now.year, now.month, now.day) then = datetime.date(then.year, then.month, then.day) if now < then: raise ValueError("Cannot determine moderation rules because date field is set to a value in the future") return now - then def allow(self, comment, content_object, request): """ Determine whether a given comment is allowed to be posted on a given object. Return ``True`` if the comment should be allowed, ``False otherwise. """ if self.enable_field: if not getattr(content_object, self.enable_field): return False if self.auto_close_field and self.close_after is not None: close_after_date = getattr(content_object, self.auto_close_field) if close_after_date is not None and self._get_delta(datetime.datetime.now(), close_after_date).days >= self.close_after: return False return True def moderate(self, comment, content_object, request): """ Determine whether a given comment on a given object should be allowed to show up immediately, or should be marked non-public and await approval. Return ``True`` if the comment should be moderated (marked non-public), ``False`` otherwise. """ if self.auto_moderate_field and self.moderate_after is not None: moderate_after_date = getattr(content_object, self.auto_moderate_field) if moderate_after_date is not None and self._get_delta(datetime.datetime.now(), moderate_after_date).days >= self.moderate_after: return True return False def email(self, comment, content_object, request): """ Send email notification of a new comment to site staff when email notifications have been requested. """ if not self.email_notification: return recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS] t = loader.get_template('comments/comment_notification_email.txt') c = Context({ 'comment': comment, 'content_object': content_object }) subject = '[%s] New comment posted on "%s"' % (Site.objects.get_current().name, content_object) message = t.render(c) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True) class Moderator(object): """ Handles moderation of a set of models. An instance of this class will maintain a list of one or more models registered for comment moderation, and their associated moderation classes, and apply moderation to all incoming comments. To register a model, obtain an instance of ``Moderator`` (this module exports one as ``moderator``), and call its ``register`` method, passing the model class and a moderation class (which should be a subclass of ``CommentModerator``). Note that both of these should be the actual classes, not instances of the classes. To cease moderation for a model, call the ``unregister`` method, passing the model class. For convenience, both ``register`` and ``unregister`` can also accept a list of model classes in place of a single model; this allows easier registration of multiple models with the same ``CommentModerator`` class. The actual moderation is applied in two phases: one prior to saving a new comment, and the other immediately after saving. The pre-save moderation may mark a comment as non-public or mark it to be removed; the post-save moderation may delete a comment which was disallowed (there is currently no way to prevent the comment being saved once before removal) and, if the comment is still around, will send any notification emails the comment generated. """ def __init__(self): self._registry = {} self.connect() def connect(self): """ Hook up the moderation methods to pre- and post-save signals from the comment models. """ signals.comment_will_be_posted.connect(self.pre_save_moderation, sender=comments.get_model()) signals.comment_was_posted.connect(self.post_save_moderation, sender=comments.get_model()) def register(self, model_or_iterable, moderation_class): """ Register a model or a list of models for comment moderation, using a particular moderation class. Raise ``AlreadyModerated`` if any of the models are already registered. """ if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model in self._registry: raise AlreadyModerated("The model '%s' is already being moderated" % model._meta.module_name) self._registry[model] = moderation_class(model) def unregister(self, model_or_iterable): """ Remove a model or a list of models from the list of models whose comments will be moderated. Raise ``NotModerated`` if any of the models are not currently registered for moderation. """ if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model not in self._registry: raise NotModerated("The model '%s' is not currently being moderated" % model._meta.module_name) del self._registry[model] def pre_save_moderation(self, sender, comment, request, **kwargs): """ Apply any necessary pre-save moderation steps to new comments. """ model = comment.content_type.model_class() if model not in self._registry: return content_object = comment.content_object moderation_class = self._registry[model] # Comment will be disallowed outright (HTTP 403 response) if not moderation_class.allow(comment, content_object, request): return False if moderation_class.moderate(comment, content_object, request): comment.is_public = False def post_save_moderation(self, sender, comment, request, **kwargs): """ Apply any necessary post-save moderation steps to new comments. """ model = comment.content_type.model_class() if model not in self._registry: return self._registry[model].email(comment, comment.content_object, request) # Import this instance in your own code to use in registering # your models for moderation. moderator = Moderator()
13,528
Python
.py
283
40.166078
141
0.682381
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,691
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/comments/forms.py
import time import datetime from django import forms from django.forms.util import ErrorDict from django.conf import settings from django.contrib.contenttypes.models import ContentType from models import Comment from django.utils.crypto import salted_hmac, constant_time_compare from django.utils.encoding import force_unicode from django.utils.hashcompat import sha_constructor from django.utils.text import get_text_list from django.utils.translation import ungettext, ugettext_lazy as _ COMMENT_MAX_LENGTH = getattr(settings,'COMMENT_MAX_LENGTH', 3000) class CommentSecurityForm(forms.Form): """ Handles the security aspects (anti-spoofing) for comment forms. """ content_type = forms.CharField(widget=forms.HiddenInput) object_pk = forms.CharField(widget=forms.HiddenInput) timestamp = forms.IntegerField(widget=forms.HiddenInput) security_hash = forms.CharField(min_length=40, max_length=40, widget=forms.HiddenInput) def __init__(self, target_object, data=None, initial=None): self.target_object = target_object if initial is None: initial = {} initial.update(self.generate_security_data()) super(CommentSecurityForm, self).__init__(data=data, initial=initial) def security_errors(self): """Return just those errors associated with security""" errors = ErrorDict() for f in ["honeypot", "timestamp", "security_hash"]: if f in self.errors: errors[f] = self.errors[f] return errors def clean_security_hash(self): """Check the security hash.""" security_hash_dict = { 'content_type' : self.data.get("content_type", ""), 'object_pk' : self.data.get("object_pk", ""), 'timestamp' : self.data.get("timestamp", ""), } expected_hash = self.generate_security_hash(**security_hash_dict) actual_hash = self.cleaned_data["security_hash"] if not constant_time_compare(expected_hash, actual_hash): # Fallback to Django 1.2 method for compatibility # PendingDeprecationWarning <- here to remind us to remove this # fallback in Django 1.5 expected_hash_old = self._generate_security_hash_old(**security_hash_dict) if not constant_time_compare(expected_hash_old, actual_hash): raise forms.ValidationError("Security hash check failed.") return actual_hash def clean_timestamp(self): """Make sure the timestamp isn't too far (> 2 hours) in the past.""" ts = self.cleaned_data["timestamp"] if time.time() - ts > (2 * 60 * 60): raise forms.ValidationError("Timestamp check failed") return ts def generate_security_data(self): """Generate a dict of security data for "initial" data.""" timestamp = int(time.time()) security_dict = { 'content_type' : str(self.target_object._meta), 'object_pk' : str(self.target_object._get_pk_val()), 'timestamp' : str(timestamp), 'security_hash' : self.initial_security_hash(timestamp), } return security_dict def initial_security_hash(self, timestamp): """ Generate the initial security hash from self.content_object and a (unix) timestamp. """ initial_security_dict = { 'content_type' : str(self.target_object._meta), 'object_pk' : str(self.target_object._get_pk_val()), 'timestamp' : str(timestamp), } return self.generate_security_hash(**initial_security_dict) def generate_security_hash(self, content_type, object_pk, timestamp): """ Generate a HMAC security hash from the provided info. """ info = (content_type, object_pk, timestamp) key_salt = "django.contrib.forms.CommentSecurityForm" value = "-".join(info) return salted_hmac(key_salt, value).hexdigest() def _generate_security_hash_old(self, content_type, object_pk, timestamp): """Generate a (SHA1) security hash from the provided info.""" # Django 1.2 compatibility info = (content_type, object_pk, timestamp, settings.SECRET_KEY) return sha_constructor("".join(info)).hexdigest() class CommentDetailsForm(CommentSecurityForm): """ Handles the specific details of the comment (name, comment, etc.). """ name = forms.CharField(label=_("Name"), max_length=50) email = forms.EmailField(label=_("Email address")) url = forms.URLField(label=_("URL"), required=False) comment = forms.CharField(label=_('Comment'), widget=forms.Textarea, max_length=COMMENT_MAX_LENGTH) def get_comment_object(self): """ Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user`` or ``ip_address``). """ if not self.is_valid(): raise ValueError("get_comment_object may only be called on valid forms") CommentModel = self.get_comment_model() new = CommentModel(**self.get_comment_create_data()) new = self.check_for_duplicate_comment(new) return new def get_comment_model(self): """ Get the comment model to create with this form. Subclasses in custom comment apps should override this, get_comment_create_data, and perhaps check_for_duplicate_comment to provide custom comment models. """ return Comment def get_comment_create_data(self): """ Returns the dict of data to be used to create a comment. Subclasses in custom comment apps that override get_comment_model can override this method to add extra fields onto a custom comment model. """ return dict( content_type = ContentType.objects.get_for_model(self.target_object), object_pk = force_unicode(self.target_object._get_pk_val()), user_name = self.cleaned_data["name"], user_email = self.cleaned_data["email"], user_url = self.cleaned_data["url"], comment = self.cleaned_data["comment"], submit_date = datetime.datetime.now(), site_id = settings.SITE_ID, is_public = True, is_removed = False, ) def check_for_duplicate_comment(self, new): """ Check that a submitted comment isn't a duplicate. This might be caused by someone posting a comment twice. If it is a dup, silently return the *previous* comment. """ possible_duplicates = self.get_comment_model()._default_manager.using( self.target_object._state.db ).filter( content_type = new.content_type, object_pk = new.object_pk, user_name = new.user_name, user_email = new.user_email, user_url = new.user_url, ) for old in possible_duplicates: if old.submit_date.date() == new.submit_date.date() and old.comment == new.comment: return old return new def clean_comment(self): """ If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST. """ comment = self.cleaned_data["comment"] if settings.COMMENTS_ALLOW_PROFANITIES == False: bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()] if bad_words: plural = len(bad_words) > 1 raise forms.ValidationError(ungettext( "Watch your mouth! The word %s is not allowed here.", "Watch your mouth! The words %s are not allowed here.", plural) % \ get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in bad_words], 'and')) return comment class CommentForm(CommentDetailsForm): honeypot = forms.CharField(required=False, label=_('If you enter anything in this field '\ 'your comment will be treated as spam')) def clean_honeypot(self): """Check that nothing's been entered into the honeypot.""" value = self.cleaned_data["honeypot"] if value: raise forms.ValidationError(self.fields["honeypot"].label) return value
8,730
Python
.py
182
38.384615
106
0.62412
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,692
managers.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/comments/managers.py
from django.db import models from django.contrib.contenttypes.models import ContentType from django.utils.encoding import force_unicode class CommentManager(models.Manager): def in_moderation(self): """ QuerySet for all comments currently in the moderation queue. """ return self.get_query_set().filter(is_public=False, is_removed=False) def for_model(self, model): """ QuerySet for all comments for a particular model (either an instance or a class). """ ct = ContentType.objects.get_for_model(model) qs = self.get_query_set().filter(content_type=ct) if isinstance(model, models.Model): qs = qs.filter(object_pk=force_unicode(model._get_pk_val())) return qs
778
Python
.py
19
33.684211
79
0.67328
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,693
comments.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/comments/templatetags/comments.py
from django import template from django.template.loader import render_to_string from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib import comments from django.utils.encoding import smart_unicode register = template.Library() class BaseCommentNode(template.Node): """ Base helper class (abstract) for handling the get_comment_* template tags. Looks a bit strange, but the subclasses below should make this a bit more obvious. """ #@classmethod def handle_token(cls, parser, token): """Class method to parse get_comment_list/count/form and return a Node.""" tokens = token.contents.split() if tokens[1] != 'for': raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) # {% get_whatever for obj as varname %} if len(tokens) == 5: if tokens[3] != 'as': raise template.TemplateSyntaxError("Third argument in %r must be 'as'" % tokens[0]) return cls( object_expr = parser.compile_filter(tokens[2]), as_varname = tokens[4], ) # {% get_whatever for app.model pk as varname %} elif len(tokens) == 6: if tokens[4] != 'as': raise template.TemplateSyntaxError("Fourth argument in %r must be 'as'" % tokens[0]) return cls( ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr = parser.compile_filter(tokens[3]), as_varname = tokens[5] ) else: raise template.TemplateSyntaxError("%r tag requires 4 or 5 arguments" % tokens[0]) handle_token = classmethod(handle_token) #@staticmethod def lookup_content_type(token, tagname): try: app, model = token.split('.') return ContentType.objects.get(app_label=app, model=model) except ValueError: raise template.TemplateSyntaxError("Third argument in %r must be in the format 'app.model'" % tagname) except ContentType.DoesNotExist: raise template.TemplateSyntaxError("%r tag has non-existant content-type: '%s.%s'" % (tagname, app, model)) lookup_content_type = staticmethod(lookup_content_type) def __init__(self, ctype=None, object_pk_expr=None, object_expr=None, as_varname=None, comment=None): if ctype is None and object_expr is None: raise template.TemplateSyntaxError("Comment nodes must be given either a literal object or a ctype and object pk.") self.comment_model = comments.get_model() self.as_varname = as_varname self.ctype = ctype self.object_pk_expr = object_pk_expr self.object_expr = object_expr self.comment = comment def render(self, context): qs = self.get_query_set(context) context[self.as_varname] = self.get_context_value_from_queryset(context, qs) return '' def get_query_set(self, context): ctype, object_pk = self.get_target_ctype_pk(context) if not object_pk: return self.comment_model.objects.none() qs = self.comment_model.objects.filter( content_type = ctype, object_pk = smart_unicode(object_pk), site__pk = settings.SITE_ID, ) # The is_public and is_removed fields are implementation details of the # built-in comment model's spam filtering system, so they might not # be present on a custom comment model subclass. If they exist, we # should filter on them. field_names = [f.name for f in self.comment_model._meta.fields] if 'is_public' in field_names: qs = qs.filter(is_public=True) if getattr(settings, 'COMMENTS_HIDE_REMOVED', True) and 'is_removed' in field_names: qs = qs.filter(is_removed=False) return qs def get_target_ctype_pk(self, context): if self.object_expr: try: obj = self.object_expr.resolve(context) except template.VariableDoesNotExist: return None, None return ContentType.objects.get_for_model(obj), obj.pk else: return self.ctype, self.object_pk_expr.resolve(context, ignore_failures=True) def get_context_value_from_queryset(self, context, qs): """Subclasses should override this.""" raise NotImplementedError class CommentListNode(BaseCommentNode): """Insert a list of comments into the context.""" def get_context_value_from_queryset(self, context, qs): return list(qs) class CommentCountNode(BaseCommentNode): """Insert a count of comments into the context.""" def get_context_value_from_queryset(self, context, qs): return qs.count() class CommentFormNode(BaseCommentNode): """Insert a form for the comment model into the context.""" def get_form(self, context): ctype, object_pk = self.get_target_ctype_pk(context) if object_pk: return comments.get_form()(ctype.get_object_for_this_type(pk=object_pk)) else: return None def render(self, context): context[self.as_varname] = self.get_form(context) return '' class RenderCommentFormNode(CommentFormNode): """Render the comment form directly""" #@classmethod def handle_token(cls, parser, token): """Class method to parse render_comment_form and return a Node.""" tokens = token.contents.split() if tokens[1] != 'for': raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) # {% render_comment_form for obj %} if len(tokens) == 3: return cls(object_expr=parser.compile_filter(tokens[2])) # {% render_comment_form for app.models pk %} elif len(tokens) == 4: return cls( ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr = parser.compile_filter(tokens[3]) ) handle_token = classmethod(handle_token) def render(self, context): ctype, object_pk = self.get_target_ctype_pk(context) if object_pk: template_search_list = [ "comments/%s/%s/form.html" % (ctype.app_label, ctype.model), "comments/%s/form.html" % ctype.app_label, "comments/form.html" ] context.push() formstr = render_to_string(template_search_list, {"form" : self.get_form(context)}, context) context.pop() return formstr else: return '' class RenderCommentListNode(CommentListNode): """Render the comment list directly""" #@classmethod def handle_token(cls, parser, token): """Class method to parse render_comment_list and return a Node.""" tokens = token.contents.split() if tokens[1] != 'for': raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) # {% render_comment_list for obj %} if len(tokens) == 3: return cls(object_expr=parser.compile_filter(tokens[2])) # {% render_comment_list for app.models pk %} elif len(tokens) == 4: return cls( ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr = parser.compile_filter(tokens[3]) ) handle_token = classmethod(handle_token) def render(self, context): ctype, object_pk = self.get_target_ctype_pk(context) if object_pk: template_search_list = [ "comments/%s/%s/list.html" % (ctype.app_label, ctype.model), "comments/%s/list.html" % ctype.app_label, "comments/list.html" ] qs = self.get_query_set(context) context.push() liststr = render_to_string(template_search_list, { "comment_list" : self.get_context_value_from_queryset(context, qs) }, context) context.pop() return liststr else: return '' # We could just register each classmethod directly, but then we'd lose out on # the automagic docstrings-into-admin-docs tricks. So each node gets a cute # wrapper function that just exists to hold the docstring. #@register.tag def get_comment_count(parser, token): """ Gets the comment count for the given params and populates the template context with a variable containing that value, whose name is defined by the 'as' clause. Syntax:: {% get_comment_count for [object] as [varname] %} {% get_comment_count for [app].[model] [object_id] as [varname] %} Example usage:: {% get_comment_count for event as comment_count %} {% get_comment_count for calendar.event event.id as comment_count %} {% get_comment_count for calendar.event 17 as comment_count %} """ return CommentCountNode.handle_token(parser, token) #@register.tag def get_comment_list(parser, token): """ Gets the list of comments for the given params and populates the template context with a variable containing that value, whose name is defined by the 'as' clause. Syntax:: {% get_comment_list for [object] as [varname] %} {% get_comment_list for [app].[model] [object_id] as [varname] %} Example usage:: {% get_comment_list for event as comment_list %} {% for comment in comment_list %} ... {% endfor %} """ return CommentListNode.handle_token(parser, token) #@register.tag def render_comment_list(parser, token): """ Render the comment list (as returned by ``{% get_comment_list %}``) through the ``comments/list.html`` template Syntax:: {% render_comment_list for [object] %} {% render_comment_list for [app].[model] [object_id] %} Example usage:: {% render_comment_list for event %} """ return RenderCommentListNode.handle_token(parser, token) #@register.tag def get_comment_form(parser, token): """ Get a (new) form object to post a new comment. Syntax:: {% get_comment_form for [object] as [varname] %} {% get_comment_form for [app].[model] [object_id] as [varname] %} """ return CommentFormNode.handle_token(parser, token) #@register.tag def render_comment_form(parser, token): """ Render the comment form (as returned by ``{% render_comment_form %}``) through the ``comments/form.html`` template. Syntax:: {% render_comment_form for [object] %} {% render_comment_form for [app].[model] [object_id] %} """ return RenderCommentFormNode.handle_token(parser, token) #@register.simple_tag def comment_form_target(): """ Get the target URL for the comment form. Example:: <form action="{% comment_form_target %}" method="post"> """ return comments.get_form_target() #@register.simple_tag def get_comment_permalink(comment, anchor_pattern=None): """ Get the permalink for a comment, optionally specifying the format of the named anchor to be appended to the end of the URL. Example:: {{ get_comment_permalink comment "#c%(id)s-by-%(user_name)s" }} """ if anchor_pattern: return comment.get_absolute_url(anchor_pattern) return comment.get_absolute_url() register.tag(get_comment_count) register.tag(get_comment_list) register.tag(get_comment_form) register.tag(render_comment_form) register.simple_tag(comment_form_target) register.simple_tag(get_comment_permalink) register.tag(render_comment_list)
11,845
Python
.py
270
35.57037
127
0.638377
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,694
utils.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/comments/views/utils.py
""" A few bits of helper functions for comment views. """ import urllib import textwrap from django.http import HttpResponseRedirect from django.core import urlresolvers from django.shortcuts import render_to_response from django.template import RequestContext from django.core.exceptions import ObjectDoesNotExist from django.contrib import comments def next_redirect(data, default, default_view, **get_kwargs): """ Handle the "where should I go next?" part of comment views. The next value could be a kwarg to the function (``default``), or a ``?next=...`` GET arg, or the URL of a given view (``default_view``). See the view modules for examples. Returns an ``HttpResponseRedirect``. """ next = data.get("next", default) if next is None: next = urlresolvers.reverse(default_view) if get_kwargs: if '#' in next: tmp = next.rsplit('#', 1) next = tmp[0] anchor = '#' + tmp[1] else: anchor = '' joiner = ('?' in next) and '&' or '?' next += joiner + urllib.urlencode(get_kwargs) + anchor return HttpResponseRedirect(next) def confirmation_view(template, doc="Display a confirmation view."): """ Confirmation view generator for the "comment was posted/flagged/deleted/approved" views. """ def confirmed(request): comment = None if 'c' in request.GET: try: comment = comments.get_model().objects.get(pk=request.GET['c']) except (ObjectDoesNotExist, ValueError): pass return render_to_response(template, {'comment': comment}, context_instance=RequestContext(request) ) confirmed.__doc__ = textwrap.dedent("""\ %s Templates: `%s`` Context: comment The posted comment """ % (doc, template) ) return confirmed
1,947
Python
.py
57
27.122807
79
0.628055
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,695
comments.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/comments/views/comments.py
from django import http from django.conf import settings from utils import next_redirect, confirmation_view from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.db import models from django.shortcuts import render_to_response from django.template import RequestContext from django.template.loader import render_to_string from django.utils.html import escape from django.views.decorators.http import require_POST from django.contrib import comments from django.contrib.comments import signals from django.views.decorators.csrf import csrf_protect class CommentPostBadRequest(http.HttpResponseBadRequest): """ Response returned when a comment post is invalid. If ``DEBUG`` is on a nice-ish error message will be displayed (for debugging purposes), but in production mode a simple opaque 400 page will be displayed. """ def __init__(self, why): super(CommentPostBadRequest, self).__init__() if settings.DEBUG: self.content = render_to_string("comments/400-debug.html", {"why": why}) @csrf_protect @require_POST def post_comment(request, next=None, using=None): """ Post a comment. HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are errors a preview template, ``comments/preview.html``, will be rendered. """ # Fill out some initial data fields from an authenticated user, if present data = request.POST.copy() if request.user.is_authenticated(): if not data.get('name', ''): data["name"] = request.user.get_full_name() or request.user.username if not data.get('email', ''): data["email"] = request.user.email # Check to see if the POST data overrides the view's next argument. next = data.get("next", next) # Look up the object we're trying to comment about ctype = data.get("content_type") object_pk = data.get("object_pk") if ctype is None or object_pk is None: return CommentPostBadRequest("Missing content_type or object_pk field.") try: model = models.get_model(*ctype.split(".", 1)) target = model._default_manager.using(using).get(pk=object_pk) except TypeError: return CommentPostBadRequest( "Invalid content_type value: %r" % escape(ctype)) except AttributeError: return CommentPostBadRequest( "The given content-type %r does not resolve to a valid model." % \ escape(ctype)) except ObjectDoesNotExist: return CommentPostBadRequest( "No object matching content-type %r and object PK %r exists." % \ (escape(ctype), escape(object_pk))) except (ValueError, ValidationError), e: return CommentPostBadRequest( "Attempting go get content-type %r and object PK %r exists raised %s" % \ (escape(ctype), escape(object_pk), e.__class__.__name__)) # Do we want to preview the comment? preview = "preview" in data # Construct the comment form form = comments.get_form()(target, data=data) # Check security information if form.security_errors(): return CommentPostBadRequest( "The comment form failed security verification: %s" % \ escape(str(form.security_errors()))) # If there are errors or if we requested a preview show the comment if form.errors or preview: template_list = [ # These first two exist for purely historical reasons. # Django v1.0 and v1.1 allowed the underscore format for # preview templates, so we have to preserve that format. "comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.module_name), "comments/%s_preview.html" % model._meta.app_label, # Now the usual directory based template heirarchy. "comments/%s/%s/preview.html" % (model._meta.app_label, model._meta.module_name), "comments/%s/preview.html" % model._meta.app_label, "comments/preview.html", ] return render_to_response( template_list, { "comment" : form.data.get("comment", ""), "form" : form, "next": next, }, RequestContext(request, {}) ) # Otherwise create the comment comment = form.get_comment_object() comment.ip_address = request.META.get("REMOTE_ADDR", None) if request.user.is_authenticated(): comment.user = request.user # Signal that the comment is about to be saved responses = signals.comment_will_be_posted.send( sender = comment.__class__, comment = comment, request = request ) for (receiver, response) in responses: if response == False: return CommentPostBadRequest( "comment_will_be_posted receiver %r killed the comment" % receiver.__name__) # Save the comment and signal that it was saved comment.save() signals.comment_was_posted.send( sender = comment.__class__, comment = comment, request = request ) return next_redirect(data, next, comment_done, c=comment._get_pk_val()) comment_done = confirmation_view( template = "comments/posted.html", doc = """Display a "comment was posted" success page.""" )
5,359
Python
.py
120
37.158333
93
0.661114
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,696
moderation.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/comments/views/moderation.py
from django import template from django.conf import settings from django.shortcuts import get_object_or_404, render_to_response from django.contrib.auth.decorators import login_required, permission_required from utils import next_redirect, confirmation_view from django.contrib import comments from django.contrib.comments import signals from django.views.decorators.csrf import csrf_protect @csrf_protect @login_required def flag(request, comment_id, next=None): """ Flags a comment. Confirmation on GET, action on POST. Templates: `comments/flag.html`, Context: comment the flagged `comments.comment` object """ comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) # Flag on POST if request.method == 'POST': perform_flag(request, comment) return next_redirect(request.POST.copy(), next, flag_done, c=comment.pk) # Render a form on GET else: return render_to_response('comments/flag.html', {'comment': comment, "next": next}, template.RequestContext(request) ) @csrf_protect @permission_required("comments.can_moderate") def delete(request, comment_id, next=None): """ Deletes a comment. Confirmation on GET, action on POST. Requires the "can moderate comments" permission. Templates: `comments/delete.html`, Context: comment the flagged `comments.comment` object """ comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) # Delete on POST if request.method == 'POST': # Flag the comment as deleted instead of actually deleting it. perform_delete(request, comment) return next_redirect(request.POST.copy(), next, delete_done, c=comment.pk) # Render a form on GET else: return render_to_response('comments/delete.html', {'comment': comment, "next": next}, template.RequestContext(request) ) @csrf_protect @permission_required("comments.can_moderate") def approve(request, comment_id, next=None): """ Approve a comment (that is, mark it as public and non-removed). Confirmation on GET, action on POST. Requires the "can moderate comments" permission. Templates: `comments/approve.html`, Context: comment the `comments.comment` object for approval """ comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) # Delete on POST if request.method == 'POST': # Flag the comment as approved. perform_approve(request, comment) return next_redirect(request.POST.copy(), next, approve_done, c=comment.pk) # Render a form on GET else: return render_to_response('comments/approve.html', {'comment': comment, "next": next}, template.RequestContext(request) ) # The following functions actually perform the various flag/aprove/delete # actions. They've been broken out into seperate functions to that they # may be called from admin actions. def perform_flag(request, comment): """ Actually perform the flagging of a comment from a request. """ flag, created = comments.models.CommentFlag.objects.get_or_create( comment = comment, user = request.user, flag = comments.models.CommentFlag.SUGGEST_REMOVAL ) signals.comment_was_flagged.send( sender = comment.__class__, comment = comment, flag = flag, created = created, request = request, ) def perform_delete(request, comment): flag, created = comments.models.CommentFlag.objects.get_or_create( comment = comment, user = request.user, flag = comments.models.CommentFlag.MODERATOR_DELETION ) comment.is_removed = True comment.save() signals.comment_was_flagged.send( sender = comment.__class__, comment = comment, flag = flag, created = created, request = request, ) def perform_approve(request, comment): flag, created = comments.models.CommentFlag.objects.get_or_create( comment = comment, user = request.user, flag = comments.models.CommentFlag.MODERATOR_APPROVAL, ) comment.is_removed = False comment.is_public = True comment.save() signals.comment_was_flagged.send( sender = comment.__class__, comment = comment, flag = flag, created = created, request = request, ) # Confirmation views. flag_done = confirmation_view( template = "comments/flagged.html", doc = 'Displays a "comment was flagged" success page.' ) delete_done = confirmation_view( template = "comments/deleted.html", doc = 'Displays a "comment was deleted" success page.' ) approve_done = confirmation_view( template = "comments/approved.html", doc = 'Displays a "comment was approved" success page.' )
5,037
Python
.py
138
30.507246
95
0.676097
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,697
handlers.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/staticfiles/handlers.py
import urllib from urlparse import urlparse from django.conf import settings from django.core.handlers.wsgi import WSGIHandler from django.contrib.staticfiles import utils from django.contrib.staticfiles.views import serve class StaticFilesHandler(WSGIHandler): """ WSGI middleware that intercepts calls to the static files directory, as defined by the STATIC_URL setting, and serves those files. """ def __init__(self, application, base_dir=None): self.application = application if base_dir: self.base_dir = base_dir else: self.base_dir = self.get_base_dir() self.base_url = urlparse(self.get_base_url()) super(StaticFilesHandler, self).__init__() def get_base_dir(self): return settings.STATIC_ROOT def get_base_url(self): utils.check_settings() return settings.STATIC_URL def _should_handle(self, path): """ Checks if the path should be handled. Ignores the path if: * the host is provided as part of the base_url * the request's path isn't under the media path (or equal) """ return (self.base_url[2] != path and path.startswith(self.base_url[2]) and not self.base_url[1]) def file_path(self, url): """ Returns the relative path to the media file on disk for the given URL. """ relative_url = url[len(self.base_url[2]):] return urllib.url2pathname(relative_url) def serve(self, request): """ Actually serves the request path. """ return serve(request, self.file_path(request.path), insecure=True) def get_response(self, request): from django.http import Http404 if self._should_handle(request.path): try: return self.serve(request) except Http404, e: if settings.DEBUG: from django.views import debug return debug.technical_404_response(request, e) return super(StaticFilesHandler, self).get_response(request) def __call__(self, environ, start_response): if not self._should_handle(environ['PATH_INFO']): return self.application(environ, start_response) return super(StaticFilesHandler, self).__call__(environ, start_response)
2,359
Python
.py
57
32.877193
80
0.646725
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,698
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/staticfiles/urls.py
from django.conf import settings from django.conf.urls.static import static urlpatterns = [] def staticfiles_urlpatterns(prefix=None): """ Helper function to return a URL pattern for serving static files. """ if prefix is None: prefix = settings.STATIC_URL return static(prefix, view='django.contrib.staticfiles.views.serve') # Only append if urlpatterns are empty if settings.DEBUG and not urlpatterns: urlpatterns += staticfiles_urlpatterns()
480
Python
.py
13
33.230769
72
0.760776
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,699
utils.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/staticfiles/utils.py
import os import fnmatch from django.conf import settings from django.core.exceptions import ImproperlyConfigured def is_ignored(path, ignore_patterns=[]): """ Return True or False depending on whether the ``path`` should be ignored (if it matches any pattern in ``ignore_patterns``). """ for pattern in ignore_patterns: if fnmatch.fnmatchcase(path, pattern): return True return False def get_files(storage, ignore_patterns=[], location=''): """ Recursively walk the storage directories yielding the paths of all files that should be copied. """ directories, files = storage.listdir(location) for fn in files: if is_ignored(fn, ignore_patterns): continue if location: fn = os.path.join(location, fn) yield fn for dir in directories: if is_ignored(dir, ignore_patterns): continue if location: dir = os.path.join(location, dir) for fn in get_files(storage, ignore_patterns, dir): yield fn def check_settings(): """ Checks if the staticfiles settings have sane values. """ if not settings.STATIC_URL: raise ImproperlyConfigured( "You're using the staticfiles app " "without having set the required STATIC_URL setting.") if settings.MEDIA_URL == settings.STATIC_URL: raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL " "settings must have different values") if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and (settings.MEDIA_ROOT == settings.STATIC_ROOT)): raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT " "settings must have different values")
1,802
Python
.py
47
30.148936
73
0.645346
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)