desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Compile the data into a QR Code array. :param fit: If ``True`` (or if a size has not been provided), find the best fit for the data to avoid data overflow errors.'
def make(self, fit=True):
if (fit or (self.version is None)): self.best_fit(start=self.version) self.makeImpl(False, self.best_mask_pattern())
'Find the minimum size required to fit in the data.'
def best_fit(self, start=None):
if (start is None): start = 1 _check_version(start) mode_sizes = util.mode_sizes_for_version(start) buffer = util.BitBuffer() for data in self.data_list: buffer.put(data.mode, 4) buffer.put(len(data), mode_sizes[data.mode]) data.write(buffer) needed_bits = len(buf...
'Find the most efficient mask pattern.'
def best_mask_pattern(self):
min_lost_point = 0 pattern = 0 for i in range(8): self.makeImpl(True, i) lost_point = util.lost_point(self.modules) if ((i == 0) or (min_lost_point > lost_point)): min_lost_point = lost_point pattern = i return pattern
'Output the QR Code only using TTY colors. If the data has not been compiled yet, make it first.'
def print_tty(self, out=None):
if (out is None): import sys out = sys.stdout if (not out.isatty()): raise OSError('Not a tty') if (self.data_cache is None): self.make() modcount = self.modules_count out.write((('\x1b[1;47m' + (' ' * ((modcount * 2) + 4))) + '\x1b[0m\n')) for r in range...
'Output the QR Code using ASCII characters. :param tty: use fixed TTY color codes (forces invert=True) :param invert: invert the ASCII characters (solid <-> transparent)'
def print_ascii(self, out=None, tty=False, invert=False):
if (out is None): import sys if (sys.version_info < (2, 7)): import codecs out = codecs.getwriter(sys.stdout.encoding)(sys.stdout) else: out = sys.stdout if (tty and (not out.isatty())): raise OSError('Not a tty') if (self.data_cache ...
'Make an image from the QR Code data. If the data has not been compiled yet, make it first.'
def make_image(self, image_factory=None, **kwargs):
_check_box_size(self.box_size) if (self.data_cache is None): self.make() if (image_factory is not None): assert issubclass(image_factory, BaseImage) else: image_factory = self.image_factory if (image_factory is None): from qrcode.image.pil import PilImage ...
'Return the QR Code as a multidimensonal array, including the border. To return the array without a border, set ``self.border`` to 0 first.'
def get_matrix(self):
if (self.data_cache is None): self.make() if (not self.border): return self.modules width = (len(self.modules) + (self.border * 2)) code = ([([False] * width)] * self.border) x_border = ([False] * self.border) for module in self.modules: code.append(((x_border + module) +...
'Draw a single rectangle of the QR code.'
def drawrect(self, row, col):
raise NotImplementedError('BaseImage.drawrect')
'Save the image file.'
def save(self, stream, kind=None):
raise NotImplementedError('BaseImage.save')
'A helper method for pixel-based image generators that specifies the four pixel coordinates for a single rect.'
def pixel_box(self, row, col):
x = ((col + self.border) * self.box_size) y = ((row + self.border) * self.box_size) return [(x, y), (((x + self.box_size) - 1), ((y + self.box_size) - 1))]
'Build the image class. Subclasses should return the class created.'
def new_image(self, **kwargs):
return None
'Return the image class for further processing.'
def get_image(self, **kwargs):
return self._img
'Get the image type.'
def check_kind(self, kind, transform=None):
if (kind is None): kind = self.kind allowed = ((not self.allowed_kinds) or (kind in self.allowed_kinds)) if transform: kind = transform(kind) if (not allowed): allowed = (kind in self.allowed_kinds) if (not allowed): raise ValueError(('Cannot set %s t...
'A box_size of 10 (default) equals 1mm.'
def units(self, pixels, text=True):
units = (Decimal(pixels) / 10) if (not text): return units return ('%smm' % units)
'Generates individual QR points as subpaths'
def _generate_subpaths(self):
rect_size = self.units(self.box_size, text=False) for point in self._points: x_base = self.units(((point[0] + self.border) * self.box_size), text=False) y_base = self.units(((point[1] + self.border) * self.box_size), text=False) (yield ('M %(x0)s %(y0)s L %(x0)s %(y1)s ...
'Register PNG with pymaging.'
def __init__(self, *args, **kwargs):
registry.formats = [] registry.names = {} registry._populate() registry.register(PNG) super(PymagingImage, self).__init__(*args, **kwargs)
'pymaging (pymaging_png at least) uses lower case for the type.'
def check_kind(self, kind, transform=None, **kwargs):
if (transform is None): transform = (lambda x: x.lower()) return super(PymagingImage, self).check_kind(kind, transform=transform, **kwargs)
'Return a ctypeid-objpk string for value.'
def prepare_value(self, value):
if (not value): return '' if isinstance(value, six.string_types): return value return ('%s-%s' % (ContentType.objects.get_for_model(value).pk, value.pk))
'Run the parent\'s method for each value.'
def prepare_value(self, value):
if (not value): return [] return [super(ContentTypeModelMultipleFieldMixin, self).prepare_value(v) for v in value]
'Set the attribute, for FutureModelForm.'
def save_object_data(self, instance, name, value):
setattr(instance, name, value)
'Get the attribute, for FutureModelForm.'
def value_from_object(self, instance, name):
return getattr(instance, name)
'Wait for scripts to be loaded and ready to work.'
def wait_script(self):
tries = 100 while tries: try: return self.browser.evaluate_script('$.select2') except: time.sleep(0.15) tries -= 1 raise Exception('$.select2 was not defined after 15 seconds.')
'Remove the "remove" character used in select2.'
def clean_label(self, label):
return label.replace('\xd7', '')
'Use a list to generate choices in a ChoiceField. .. py:param choice_list: The list to use to generate choices or a function that returns a list.'
def __init__(self, choice_list=None, required=True, widget=None, label=None, initial=None, help_text='', *args, **kwargs):
choice_list = (choice_list or []) if callable(choice_list): choices = (lambda : [(choice, choice) for choice in choice_list()]) else: choices = [(choice, choice) for choice in choice_list] super(Select2ListChoiceField, self).__init__(choices=choices, required=required, widget=widget, lab...
'Do not validate choices but check for empty.'
def validate(self, value):
super(ChoiceField, self).validate(value)
'Automatically set data-tags=1.'
def build_attrs(self, *args, **kwargs):
attrs = super(TagSelect2, self).build_attrs(*args, **kwargs) attrs.setdefault('data-tags', 1) return attrs
'Return a comma-separated list of options. This is needed because Select2 uses a multiple select even in tag mode, and the model field expects a comma-separated list of tags.'
def value_from_datadict(self, data, files, name):
values = super(TagSelect2, self).value_from_datadict(data, files, name) return six.text_type(',').join(values)
'Return the HTML option value attribute for a value.'
def option_value(self, value):
return value
'Return the list of HTML option values for a form field value.'
def format_value(self, value):
if (not isinstance(value, (tuple, list))): value = [value] values = set() for v in value: if (not v): continue if isinstance(v, six.string_types): for t in v.split(','): values.add(self.option_value(t)) else: for t in v: ...
'Return only select options.'
def options(self, name, value, attrs=None):
if isinstance(value, six.text_type): value = value.split(',') for v in value: if (not v): continue real_values = (v.split(',') if hasattr(v, 'split') else v) for rv in real_values: (yield self.option_value(rv))
'Return a list of one optgroup and selected values.'
def optgroups(self, name, value, attrs=None):
default = (None, [], 0) groups = [default] for (i, v) in enumerate(self.options(name, value, attrs)): default[1].append(self.create_option(v, v, v, True, i)) return groups
'Register select2_submodule_check.'
def ready(self):
checks.register(select2_submodule_check)
'Return data for the \'results\' key of the response.'
def get_results(self, context):
return [{'id': self.get_result_value(result), 'text': self.get_result_label(result)} for result in context['object_list']]
'Form the correct create_option to append to results.'
def get_create_option(self, context, q):
create_option = [] display_create_option = False if (self.create_field and q): page_obj = context.get('page_obj', None) if ((page_obj is None) or (page_obj.number == 1)): display_create_option = True if (display_create_option and self.has_add_permission(self.request)): ...
'Return a JSON response in Select2 format.'
def render_to_response(self, context):
q = self.request.GET.get('q', None) create_option = self.get_create_option(context, q) return http.HttpResponse(json.dumps({'results': (self.get_results(context) + create_option), 'pagination': {'more': self.has_more(context)}}), content_type='application/json')
'"Return the list strings from which to autocomplete.'
def get_list(self):
return []
'"Return option list json response.'
def get(self, request, *args, **kwargs):
results = self.get_list() create_option = [] if self.q: results = [x for x in results if (self.q.lower() in x.lower())] if hasattr(self, 'create'): create_option = [{'id': self.q, 'text': ('Create "%s"' % self.q), 'create_id': True}] return http.HttpResponse(json.dumps({'r...
'"Add an option to the autocomplete list. If \'text\' is not defined in POST or self.create(text) fails, raises bad request. Raises ImproperlyConfigured if self.create if not defined.'
def post(self, request):
if (not hasattr(self, 'create')): raise ImproperlyConfigured('Missing "create()"') text = request.POST.get('text', None) if (text is None): return http.HttpResponseBadRequest() text = self.create(text) if (text is None): return http.HttpResponseBadRequest() return http...
'"Return option list with children(s) json response.'
def get(self, request, *args, **kwargs):
results_dict = {} results = self.get_list() if results: flat_results = [(group, item) for entry in results for (group, items) in self.get_item_as_group(entry) for item in items] if self.q: q = self.q.lower() flat_results = [(g, x) for (g, x) in flat_results if (q in x...
'Return a list of results usable by Select2. It will render as a list of one <optgroup> per different content type containing a list of one <option> per model.'
def get_results(self, context):
groups = {} for result in context['object_list']: groups.setdefault(type(result), []) groups[type(result)].append(result) return [{'id': None, 'text': capfirst(self.get_model_name(model)), 'children': [{'id': self.get_result_value(result), 'text': six.text_type(result)} for result in results...
'Handle multi-word tag. Insure there\'s a comma when there\'s only a single multi-word tag, or tag "Multi word" would end up as "Multi" and "word".'
def value_from_datadict(self, data, files, name):
value = super(TaggitSelect2, self).value_from_datadict(data, files, name) if (value and (',' not in value)): value = ('%s,' % value) return value
'Return tag.name attribute of value.'
def option_value(self, value):
return (value.tag.name if hasattr(value, 'tag') else value)
'Render only selected tags. Remove when Django < 1.10 support is dropped.'
def render_options(self, *args):
selected_choices_arg = (1 if (VERSION < (1, 10)) else 0) selected_choices = args[selected_choices_arg] if isinstance(selected_choices, six.text_type): choices = [c.strip() for c in selected_choices.split(',')] else: choices = [c.tag.name for c in selected_choices if c] options = [('<...
'Instanciate a widget with a URL and a list of fields to forward.'
def __init__(self, url=None, forward=None, *args, **kwargs):
self.url = url self.forward = (forward or []) self.placeholder = kwargs.get('attrs', {}).get('data-placeholder') super(WidgetMixin, self).__init__(*args, **kwargs)
'Build HTML attributes for the widget.'
def build_attrs(self, *args, **kwargs):
attrs = super(WidgetMixin, self).build_attrs(*args, **kwargs) if (self.url is not None): attrs['data-autocomplete-light-url'] = self.url autocomplete_function = getattr(self, 'autocomplete_function', None) if autocomplete_function: attrs.setdefault('data-autocomplete-light-function', aut...
'Replace self.choices with selected_choices.'
def filter_choices_to_render(self, selected_choices):
self.choices = [c for c in self.choices if (six.text_type(c[0]) in selected_choices)]
'Convert forward declaration to a dictionary. A returned dictionary will be dumped to JSON while rendering widget.'
@staticmethod def _make_forward_dict(f):
if isinstance(f, six.string_types): return forward.Field(f).to_dict() elif isinstance(f, forward.Forward): return f.to_dict() else: raise TypeError('Cannot use {} as forwarded value'.format(f))
'Render forward configuration for the field.'
def render_forward_conf(self, id):
if self.forward: return (((('<div style="display:none" class="dal-forward-conf" ' + 'id="dal-forward-conf-for-{id}"'.format(id=id)) + '><script type="text/dal-forward-conf">') + json.dumps([self._make_forward_dict(f) for f in self.forward])) + '</script></div>') else: return ''
'Django-compatibility method for option rendering. Should only render selected options, by setting self.choices before calling the parent method. Remove this code when dropping support for Django<1.10.'
def render_options(self, *args):
selected_choices_arg = (1 if (VERSION < (1, 10)) else 0) selected_choices = [six.text_type(c) for c in args[selected_choices_arg] if c] all_choices = copy.copy(self.choices) if self.url: self.filter_choices_to_render(selected_choices) elif (not self.allow_multiple_selected): if self....
'Exclude unselected self.choices before calling the parent method. Used by Django>=1.10.'
def optgroups(self, name, value, attrs=None):
selected_choices = [six.text_type(c) for c in value if c] all_choices = copy.copy(self.choices) if self.url: self.filter_choices_to_render(selected_choices) elif self.placeholder: self.choices.insert(0, (None, '')) result = super(WidgetMixin, self).optgroups(name, value, attrs) s...
'Calling Django render together with `render_forward_conf`.'
def render(self, name, value, attrs=None):
widget = super(WidgetMixin, self).render(name, value, attrs) conf = self.render_forward_conf(attrs['id']) return mark_safe((widget + conf))
'Filter out un-selected choices if choices is a QuerySet.'
def filter_choices_to_render(self, selected_choices):
self.choices.queryset = self.choices.queryset.filter(pk__in=[c for c in selected_choices if c])
'Instanciate a browser for the whole test session.'
@classmethod def setUpClass(cls):
global GLOBAL_BROWSER if (GLOBAL_BROWSER is None): GLOBAL_BROWSER = Browser(os.environ.get('BROWSER', 'firefox')) cls.browser = GLOBAL_BROWSER super(AutocompleteTestCase, cls).setUpClass()
'Open a URL.'
def get(self, url):
self.browser.visit(('%s%s' % (self.live_server_url, url))) if ('/admin/login/' in self.browser.url): self.browser.find_by_value('Log in').first.click() self.wait_script()
'Click an element by css selector.'
def click(self, selector):
self.browser.find_by_css(selector).first.click()
'Enter text in an element by css selector.'
def enter_text(self, selector, text):
self.browser.find_by_css(selector).first.value = '' self.browser.find_by_css(selector).first.type(text)
'Assert an element is not visible by css selector.'
def assert_not_visible(self, selector):
e = self.browser.find_by_css(selector) assert ((not e) or (e.first.visible is False))
'Assert an element is visible by css selector.'
def assert_visible(self, selector):
e = self.browser.find_by_css(selector).first assert (e.visible is True)
'Return a modeladmin url for a model and action.'
def get_modeladmin_url(self, action, **kwargs):
return reverse(('admin:%s_%s_%s' % (self.model._meta.app_label, self.model._meta.model_name, action)), kwargs=kwargs)
'Fill in the name input.'
def fill_name(self):
i = self.id() half = int(len(i)) not_id = (i[half:] + i[:half]) self.browser.fill('name', not_id)
'Create a unique option from self.model into self.option.'
def create_option(self):
unique_name = six.text_type(uuid.uuid1()) if (VERSION < (1, 10)): unique_name = unique_name.replace('-', '') (option, created) = self.model.objects.get_or_create(name=unique_name) return option
'Return option, content type.'
def create_option(self):
option = super(ContentTypeOptionMixin, self).create_option() ctype = ContentType.objects.get_for_model(option) return (option, ctype)
'Preset a model name, ie. \'auth.user\'.'
def __init__(self, model_name=None):
self.model_name = model_name
'Return either the preset model, either the sender\'s TestModel.'
def get_model(self, sender):
if (self.model_name is None): return sender.get_model('TModel') else: return apps.get_model(self.model_name)
'Callback function, calls install_fixtures.'
def __call__(self, sender, **kwargs):
model = self.get_model(sender) self.install_fixtures(model)
'Install fixtures for model.'
def install_fixtures(self, model):
for n in range(1, 50): try: model.objects.get(pk=n) except model.DoesNotExist: model.objects.create(name=('test %s' % n), pk=n)
'Install owners and fixtures.'
def install_fixtures(self, model):
if (not self.installed_auth): User = apps.get_model('auth.user') (self.test, c) = User.objects.get_or_create(username='test', is_staff=True, is_superuser=True) self.test.set_password('test') self.test.save() (self.other, c) = User.objects.get_or_create(username='other') ...
'If any kwarg is None, get it from case attributes.'
def __init__(self, case, clear_selector=None, dropdown_selector=None, field_name=None, input_selector=None, label_selector=None, labels_selector=None, model=None, option_selector=None, widget_selector=None):
self.case = case self.clear_selector = (clear_selector or self.case.clear_selector) self.dropdown_selector = (dropdown_selector or self.case.dropdown_selector) self.field_name = (field_name or self.case.field_name) self.input_selector = (input_selector or self.case.input_selector) self.label_sel...
'Incremental sleep until option appeared.'
@tenacity.retry(stop=tenacity.stop_after_delay(3)) def find_option(self, text):
options = self.case.browser.find_by_css(self.option_selector) for option in options: if (text in option.text): return option raise Exception((u'Option %s not found' % text))
'Return CSS selector for field option label.'
def get_field_label_selector(self):
return (u'%s %s' % (self.field_container_selector, self.label_selector))
'Clean child nodes before checking (ie. clear option).'
def clean_label_from_remove_buton(self):
self.case.browser.execute_script((u'$("%s *").remove()' % self.get_field_label_selector()))
'Return autocomplete widget label.'
def get_label(self):
label = self.case.browser.find_by_css(self.get_field_label_selector()) self.clean_label_from_remove_buton() return self.clean_label(six.text_type(label.text))
'Given an option text, return the actual label.'
def clean_label(self, label):
return label
'Assert that the autocomplete label matches text.'
@tenacity.retry(stop=tenacity.stop_after_delay(3)) def assert_label(self, text):
assert (six.text_type(text) == six.text_type(self.get_label()))
'Return the autocomplete field value.'
def get_value(self):
field = self.case.browser.find_by_css(self.field_selector) return field[u'value']
'Assart that the actual field value matches value.'
@tenacity.retry(stop=tenacity.stop_after_delay(3)) def assert_value(self, value):
assert (self.get_value() == six.text_type(value))
'Assert value is selected and has the given label.'
def assert_selection(self, value, label):
self.assert_label(label) self.assert_value(value)
'Assert value and lebel, submit the form and assert again.'
def assert_selection_persists(self, value, label):
self.assert_selection(value, label) self.submit() self.assert_label(label) self.assert_value(value)
'Retrying assert that suggestions match expected labels.'
@tenacity.retry(stop=tenacity.stop_after_delay(3)) def assert_suggestion_labels_are(self, expected):
assert (sorted(expected) == sorted(self.get_suggestions_labels()))
'Switch to popup window.'
def switch_to_popup(self):
self.case.browser.windows.current = self.case.browser.windows[1] self.in_popup = True
'Switch back to main window.'
def switch_to_main(self):
self.case.browser.windows.current = self.case.browser.windows[0] self.in_popup = False
'Submit the form.'
def submit(self):
sel = u'input[type=submit]' if (not self.in_popup): sel += u'[name=_continue]' el = self.case.browser.find_by_css(sel).first el.click() tries = 100 while tries: if ((len(self.case.browser.windows) == 1) and self.in_popup): break try: el.visible ...
'Open the autocomplete dropdown.'
def toggle_autocomplete(self):
self.case.click((u'%s %s' % (self.field_container_selector, self.widget_selector)))
'Re-open the autocomplete box.'
def refresh_autocomplete(self):
self.toggle_autocomplete() self.case.browser.is_element_not_present_by_css(self.option_selector) self.toggle_autocomplete()
'Return the list of suggestions in the autocomplete box.'
def get_suggestions(self):
def get_options(): return self.case.browser.find_by_css(self.option_selector) def is_searching(options): try: return (u'Searching' in options[0].text) except StaleElementReferenceException: return True except IndexError: return True options...
'Return labels for suggestions in the autocomplete box.'
def get_suggestions_labels(self):
return [o[1] for o in self.get_suggestions()]
'Assert that selecting option "text" sets input\'s value.'
def select_option(self, text):
dropdown = self.case.browser.find_by_css(self.dropdown_selector) if ((not len(dropdown)) or (not dropdown.visible)): self.toggle_autocomplete() self.case.assert_visible(self.dropdown_selector) self.case.enter_text(self.input_selector, text) self.find_option(text).click()
'Clear current option.'
def clear_option(self):
self.case.click(self.field_clear_selector)
'Same as UserCanSelectOption, in inline inline_number. Where inline_related_name should be the related_name option for the foreign key used for the InlineModelAdmin.'
def __init__(self, case, inline_number, inline_related_name=None, **kwargs):
self.inline_number = inline_number self.inline_related_name = (inline_related_name or case.inline_related_name) super(InlineSelectOption, self).__init__(case, **kwargs) self.field_container_selector = (u'#%s-%s .field-%s' % (self.inline_related_name, self.inline_number, self.field_name)) self.fie...
'Click the change button and rename in the popup.'
def rename_option(self, current_name, add_keys):
self.case.click((u'#change_id_%s' % self.field_name)) self.switch_to_popup() name_input = self.case.browser.find_by_id(u'id_name') self.case.assertEquals(name_input[u'value'], current_name) self.case.enter_text(u'#id_name', add_keys) self.submit() self.switch_to_main()
'Click the add button and add another option in the popup.'
def add_another(self, name):
self.case.browser.find_by_id((u'add_id_%s' % self.field_name)).click() self.switch_to_popup() self.case.enter_text(u'#id_name', name) self.submit() self.switch_to_main()
'Select the only option after typing name and submit. name should be unique.'
def create_option(self, name):
self.toggle_autocomplete() self.case.enter_text(self.input_selector, name) self.case.browser.is_element_present_by_text(name) self.case.click(self.option_selector) self.case.browser.is_element_not_present_by_css(u'.select2-results__options')
'Return CSS selector for field option label.'
def get_field_labels_selector(self):
return (u'%s %s' % (self.field_container_selector, self.labels_selector))
'Clean child nodes before checking (ie. clear option).'
def clean_label_from_remove_buton(self):
self.case.browser.execute_script((u'$("%s span").remove()' % self.get_field_labels_selector()))
'Return autocomplete widget label.'
def get_labels(self):
self.clean_label_from_remove_buton() labels = self.case.browser.find_by_css(self.get_field_labels_selector()) return [self.clean_label(six.text_type(label.text)) for label in labels]
'Return the autocomplete field value.'
def get_values(self):
script = (u"\n window.GET_VALUES = [];\n $('%s option:selected').each(function() {\n GET_VALUES.push($(this).attr('value'));\n });\n ...
'Assert that all labels match texts.'
def assert_labels(self, texts):
labels = self.get_labels() for text in texts: self.case.assertIn(text, labels) self.case.assertEquals(len(texts), len(labels))
'Assart that the actual field values matches values.'
def assert_values(self, values):
text_values = [six.text_type(v) for v in values] actual_values = self.get_values() for actual_value in actual_values: self.case.assertIn(actual_value, text_values) self.case.assertEquals(len(values), len(actual_values))
'Assert selections have values and labels.'
def assert_selection(self, values, labels):
self.assert_labels(labels) self.assert_values(values)
'Same as above, but also submits the form and check again.'
def assert_selection_persists(self, values, labels):
self.assert_selection(values, labels) self.submit() self.assert_labels(labels) self.assert_values(values)