django.utils.six.moves.map

Here are the examples of the python api django.utils.six.moves.map taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

38 Examples 7

Example 1

Project: pycontw2016
Source File: conftest.py
View license
    def to_list(self, qs, transform=repr):
        """Convert a queryset to list.

        This uses a similar algorithm to Django's `assertQuerySetEqual` to
        convert the queryset, but leave the asserting part to pytest.
        """
        items = six.moves.map(transform, qs)
        return list(items)

Example 2

Project: pycontw2016
Source File: conftest.py
View license
    def to_counter(self, qs, transform=repr):
        """Convert a queryset to a `collections.Counter`.

        This uses a similar algorithm to Django's `assertQuerySetEqual` to
        convert the queryset, but leave the asserting part to pytest.
        """
        items = six.moves.map(transform, qs)
        return collections.Counter(items)

Example 3

Project: django-sundial
Source File: zones.py
View license
def _group_choices(zones):
    groups = groupby(six.moves.map(lambda z: z.split('/'), zones), lambda z: z[0])
    for group, regions in groups:
        choices = list(
            ('/'.join(region), _lazy_label_zone(region)) for region in regions
        )
        yield _(group), choices

Example 4

Project: hue
Source File: testcases.py
View license
    def assertQuerysetEqual(self, qs, values, transform=repr, ordered=True):
        items = six.moves.map(transform, qs)
        if not ordered:
            return self.assertEqual(set(items), set(values))
        values = list(values)
        # For example qs.iterator() could be passed as qs, but it does not
        # have 'ordered' attribute.
        if len(values) > 1 and hasattr(qs, 'ordered') and not qs.ordered:
            raise ValueError("Trying to compare non-ordered queryset "
                             "against more than one ordered values")
        return self.assertEqual(list(items), values)

Example 5

Project: patchwork
Source File: parsemail.py
View license
def clean_header(header):
    """ Decode (possibly non-ascii) headers """

    def decode(fragment):
        (frag_str, frag_encoding) = fragment
        if frag_encoding:
            return frag_str.decode(frag_encoding)
        elif isinstance(frag_str, six.binary_type):  # python 2
            return frag_str.decode()
        return frag_str

    fragments = list(map(decode, decode_header(header)))

    return normalise_space(u' '.join(fragments))

Example 6

Project: patchwork
Source File: test_person.py
View license
    def setUp(self):
        self.people = [
            Person(name="Test Name", email="[email protected]"),
            Person(email="[email protected]"),
        ]
        list(map(lambda p: p.save(), self.people))

Example 7

Project: mapit
Source File: shortcuts.py
View license
def output_html(request, title, areas, **kwargs):
    kwargs['json_url'] = request.get_full_path().replace('.html', '')
    kwargs['title'] = title
    tpl = loader.render_to_string('mapit/data.html', kwargs, request=request)
    wraps = tpl.split('!!!DATA!!!')

    indent_areas = kwargs.get('indent_areas', False)
    item_tpl = loader.get_template('mapit/areas_item.html')
    areas = map(lambda area: item_tpl.render({'area': area, 'indent_areas': indent_areas}), areas)
    areas = defaultiter(areas, '<li>' + _('No matching areas found.') + '</li>')
    content = itertools.chain(wraps[0:1], areas, wraps[1:])

    return http.StreamingHttpResponse(content)

Example 8

Project: mapit
Source File: shortcuts.py
View license
def output_html(request, title, areas, **kwargs):
    kwargs['json_url'] = request.get_full_path().replace('.html', '')
    kwargs['title'] = title
    tpl = loader.render_to_string('mapit/data.html', kwargs, request=request)
    wraps = tpl.split('!!!DATA!!!')

    indent_areas = kwargs.get('indent_areas', False)
    item_tpl = loader.get_template('mapit/areas_item.html')
    areas = map(lambda area: item_tpl.render({'area': area, 'indent_areas': indent_areas}), areas)
    areas = defaultiter(areas, '<li>' + _('No matching areas found.') + '</li>')
    content = itertools.chain(wraps[0:1], areas, wraps[1:])

    return http.StreamingHttpResponse(content)

Example 9

View license
    def _build_name2cls(self, dotted_paths):
        self.name2cls = OrderedDict(
            (cls.__name__, cls)
            for cls in six.moves.map(self._to_cls, dotted_paths)
        )
        if len(self.name2cls) != len(dotted_paths):
            raise DuplicateNamesError()

Example 10

Project: GAE-Bulk-Mailer
Source File: response.py
View license
    @property
    def streaming_content(self):
        return map(self.make_bytes, self._iterator)

Example 11

Project: GAE-Bulk-Mailer
Source File: testcases.py
View license
    def assertQuerysetEqual(self, qs, values, transform=repr, ordered=True):
        items = six.moves.map(transform, qs)
        if not ordered:
            return self.assertEqual(set(items), set(values))
        return self.assertEqual(list(items), values)

Example 12

Project: PyClassLessons
Source File: response.py
View license
    @property
    def streaming_content(self):
        return map(self.make_bytes, self._iterator)

Example 13

View license
    @property
    def streaming_content(self):
        return map(self.make_bytes, self._iterator)

Example 14

Project: splunk-webframework
Source File: response.py
View license
    @property
    def streaming_content(self):
        return map(self.make_bytes, self._iterator)

Example 15

Project: splunk-webframework
Source File: testcases.py
View license
    def assertQuerysetEqual(self, qs, values, transform=repr, ordered=True):
        items = six.moves.map(transform, qs)
        if not ordered:
            return self.assertEqual(set(items), set(values))
        return self.assertEqual(list(items), values)

Example 16

Project: cgstudiomap
Source File: response.py
View license
    @property
    def streaming_content(self):
        return map(self.make_bytes, self._iterator)

Example 17

Project: hue
Source File: response.py
View license
    @property
    def streaming_content(self):
        return map(self.make_bytes, self._iterator)

Example 18

Project: decode-Django
Source File: response.py
View license
    @property
    def streaming_content(self):
        return map(self.make_bytes, self._iterator)

Example 19

Project: decode-Django
Source File: testcases.py
View license
    def assertQuerysetEqual(self, qs, values, transform=repr, ordered=True):
        items = six.moves.map(transform, qs)
        if not ordered:
            return self.assertEqual(set(items), set(values))
        return self.assertEqual(list(items), values)

Example 20

Project: django-cms
Source File: django_load.py
View license
def iterload_objects(import_paths):
    """
    Load a list of objects.
    """
    return map(load_object, import_paths)

Example 21

Project: django-cms
Source File: django_load.py
View license
def get_subclasses(c):
    """
    Get all subclasses of a given class
    """
    return c.__subclasses__() + sum(map(get_subclasses, c.__subclasses__()), [])

Example 22

Project: django
Source File: response.py
View license
    @property
    def streaming_content(self):
        return map(self.make_bytes, self._iterator)

Example 23

Project: django-oscar
Source File: widgets.py
View license
def datetime_format_to_js_input_mask(format):
    # taken from
    # http://stackoverflow.com/questions/15175142/how-can-i-do-multiple-substitutions-using-regex-in-python  # noqa
    def multiple_replace(dict, text):
        # Create a regular expression  from the dictionary keys
        regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))

        # For each match, look-up corresponding value in dictionary
        return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)

    replacements = {
        '%Y': 'y',
        '%y': '99',
        '%m': 'm',
        '%d': 'd',
        '%H': 'h',
        '%I': 'h',
        '%M': 's',
        '%S': 's',
    }
    return multiple_replace(replacements, format).strip()

Example 24

Project: django-oscar
Source File: widgets.py
View license
    def format_value(self, value):
        if value:
            return ','.join(map(six.text_type, filter(bool, value)))
        else:
            return ''

Example 25

Project: django-oscar
Source File: generic.py
View license
    def post(self, request, *args, **kwargs):
        # Dynamic dispatch pattern - we forward POST requests onto a method
        # designated by the 'action' parameter.  The action has to be in a
        # whitelist to avoid security issues.
        action = request.POST.get(self.action_param, '').lower()
        if not self.actions or action not in self.actions:
            messages.error(self.request, _("Invalid action"))
            return redirect(self.get_error_url(request))

        ids = request.POST.getlist(
            'selected_%s' % self.get_checkbox_object_name())
        ids = list(map(int, ids))
        if not ids:
            messages.error(
                self.request,
                _("You need to select some %ss")
                % self.get_checkbox_object_name())
            return redirect(self.get_error_url(request))

        objects = self.get_objects(ids)
        return getattr(self, action)(request, objects)

Example 26

Project: patchwork
Source File: parser.py
View license
def parse_patch(text):
    patchbuf = ''
    commentbuf = ''
    buf = ''

    # state specified the line we just saw, and what to expect next
    state = 0
    # 0: text
    # 1: suspected patch header (diff, ====, Index:)
    # 2: patch header line 1 (---)
    # 3: patch header line 2 (+++)
    # 4: patch hunk header line (@@ line)
    # 5: patch hunk content
    # 6: patch meta header (rename from/rename to)
    #
    # valid transitions:
    #  0 -> 1 (diff, ===, Index:)
    #  0 -> 2 (---)
    #  1 -> 2 (---)
    #  2 -> 3 (+++)
    #  3 -> 4 (@@ line)
    #  4 -> 5 (patch content)
    #  5 -> 1 (run out of lines from @@-specifed count)
    #  1 -> 6 (rename from / rename to)
    #  6 -> 2 (---)
    #  6 -> 1 (other text)
    #
    # Suspected patch header is stored into buf, and appended to
    # patchbuf if we find a following hunk. Otherwise, append to
    # comment after parsing.

    # line counts while parsing a patch hunk
    lc = (0, 0)
    hunk = 0

    for line in text.split('\n'):
        line += '\n'

        if state == 0:
            if line.startswith('diff ') or line.startswith('===') \
                    or line.startswith('Index: '):
                state = 1
                buf += line

            elif line.startswith('--- '):
                state = 2
                buf += line

            else:
                commentbuf += line

        elif state == 1:
            buf += line
            if line.startswith('--- '):
                state = 2

            if line.startswith(('rename from ', 'rename to ')):
                state = 6

        elif state == 2:
            if line.startswith('+++ '):
                state = 3
                buf += line

            elif hunk:
                state = 1
                buf += line

            else:
                state = 0
                commentbuf += buf + line
                buf = ''

        elif state == 3:
            match = _hunk_re.match(line)
            if match:

                def fn(x):
                    if not x:
                        return 1
                    return int(x)

                lc = list(map(fn, match.groups()))

                state = 4
                patchbuf += buf + line
                buf = ''

            elif line.startswith('--- '):
                patchbuf += buf + line
                buf = ''
                state = 2

            elif hunk and line.startswith('\ No newline at end of file'):
                # If we had a hunk and now we see this, it's part of the patch,
                # and we're still expecting another @@ line.
                patchbuf += line

            elif hunk:
                state = 1
                buf += line

            else:
                state = 0
                commentbuf += buf + line
                buf = ''

        elif state == 4 or state == 5:
            if line.startswith('-'):
                lc[0] -= 1
            elif line.startswith('+'):
                lc[1] -= 1
            elif line.startswith('\ No newline at end of file'):
                # Special case: Not included as part of the hunk's line count
                pass
            else:
                lc[0] -= 1
                lc[1] -= 1

            patchbuf += line

            if lc[0] <= 0 and lc[1] <= 0:
                state = 3
                hunk += 1
            else:
                state = 5

        elif state == 6:
            if line.startswith(('rename to ', 'rename from ')):
                patchbuf += buf + line
                buf = ''

            elif line.startswith('--- '):
                patchbuf += buf + line
                buf = ''
                state = 2

            else:
                buf += line
                state = 1

        else:
            raise Exception("Unknown state %d! (line '%s')" % (state, line))

    commentbuf += buf

    if patchbuf == '':
        patchbuf = None

    if commentbuf == '':
        commentbuf = None

    return (patchbuf, commentbuf)

Example 27

Project: patchwork
Source File: parser.py
View license
def hash_patch(str):
    # normalise spaces
    str = str.replace('\r', '')
    str = str.strip() + '\n'

    prefixes = ['-', '+', ' ']
    hash = hashlib.sha1()

    for line in str.split('\n'):

        if len(line) <= 0:
            continue

        hunk_match = _hunk_re.match(line)
        filename_match = _filename_re.match(line)

        if filename_match:
            # normalise -p1 top-directories
            if filename_match.group(1) == '---':
                filename = 'a/'
            else:
                filename = 'b/'
            filename += '/'.join(filename_match.group(2).split('/')[1:])

            line = filename_match.group(1) + ' ' + filename

        elif hunk_match:
            # remove line numbers, but leave line counts
            def fn(x):
                if not x:
                    return 1
                return int(x)
            line_nos = list(map(fn, hunk_match.groups()))
            line = '@@ -%d +%d @@' % tuple(line_nos)

        elif line[0] in prefixes:
            # if we have a +, - or context line, leave as-is
            pass

        else:
            # other lines are ignored
            continue

        hash.update((line + '\n').encode('utf-8'))

    return hash

Example 28

Project: patchwork
Source File: xmlrpc.py
View license
@xmlrpc_method()
def project_list(search_str=None, max_count=0):
    """List projects matching a given linkname filter.

    Filter projects by linkname. Projects are compared to the search
    string via a case-insensitive containment test, a.k.a. a partial
    match.

    Args:
        search_str: The string to compare project names against. If
            blank, all projects will be returned.
        max_count (int): The maximum number of projects to return.

    Returns:
        A serialized list of projects matching filter, if any. A list
        of all projects if no filter given.
    """
    try:
        if search_str:
            projects = Project.objects.filter(linkname__icontains=search_str)
        else:
            projects = Project.objects.all()

        if max_count > 0:
            return list(map(project_to_dict, projects[:max_count]))
        elif max_count < 0:
            query = projects.reverse()[:-max_count]
            return [project_to_dict(project) for project in reversed(query)]
        else:
            return list(map(project_to_dict, projects))
    except Project.DoesNotExist:
        return []

Example 29

Project: patchwork
Source File: xmlrpc.py
View license
@xmlrpc_method()
def person_list(search_str=None, max_count=0):
    """List persons matching a given name or email filter.

    Filter persons by name and email. Persons are compared to the
    search string via a case-insensitive containment test, a.k.a. a
    partial match.

    Args:
        search_str: The string to compare person names or emails
            against. If blank, all persons will be returned.
        max_count (int): The maximum number of persons to return.

    Returns:
        A serialized list of persons matching filter, if any. A list
        of all persons if no filter given.
    """
    try:
        if search_str:
            people = (Person.objects.filter(name__icontains=search_str) |
                      Person.objects.filter(email__icontains=search_str))
        else:
            people = Person.objects.all()

        if max_count > 0:
            return list(map(person_to_dict, people[:max_count]))
        elif max_count < 0:
            query = people.reverse()[:-max_count]
            return [person_to_dict(person) for person in reversed(query)]
        else:
            return list(map(person_to_dict, people))
    except Person.DoesNotExist:
        return []

Example 30

Project: patchwork
Source File: xmlrpc.py
View license
@xmlrpc_method()
def patch_list(filt=None):
    """List patches matching all of a given set of filters.

    Filter patches by one or more of the below fields:

     * id
     * name
     * project_id
     * submitter_id
     * delegate_id
     * archived
     * state_id
     * date
     * commit_ref
     * hash
     * msgid

    It is also possible to specify the number of patches returned via
    a ``max_count`` filter.

     * max_count

    With the exception of ``max_count``, the specified field of the
    patches are compared to the search string using a provided
    field lookup type, which can be one of:

     * iexact
     * contains
     * icontains
     * gt
     * gte
     * lt
     * in
     * startswith
     * istartswith
     * endswith
     * iendswith
     * range
     * year
     * month
     * day
     * isnull

    Please refer to the Django documentation for more information on
    these field lookup types.

    An example filter would look like so:

    {
        'name__icontains': 'Joe Bloggs',
        'max_count': 1,
    }

    Args:
        filt (dict): The filters specifying the field to compare, the
            lookup type and the value to compare against. Keys are of
            format ``[FIELD_NAME]`` or ``[FIELD_NAME]__[LOOKUP_TYPE]``.
            Example: ``name__icontains``. Values are plain strings to
            compare against.

    Returns:
        A serialized list of patches matching filters, if any. A list
        of all patches if no filter given.
    """
    if filt is None:
        filt = {}

    try:
        # We allow access to many of the fields.  But, some fields are
        # filtered by raw object so we must lookup by ID instead over
        # XML-RPC.
        ok_fields = [
            'id',
            'name',
            'project_id',
            'submitter_id',
            'delegate_id',
            'archived',
            'state_id',
            'date',
            'commit_ref',
            'hash',
            'msgid',
            'max_count',
        ]

        dfilter = {}
        max_count = 0

        for key in filt:
            parts = key.split('__')
            if parts[0] not in ok_fields:
                # Invalid field given
                return []
            if len(parts) > 1:
                if LOOKUP_TYPES.count(parts[1]) == 0:
                    # Invalid lookup type given
                    return []

            if parts[0] == 'project_id':
                dfilter['project'] = Project.objects.filter(id=filt[key])[0]
            elif parts[0] == 'submitter_id':
                dfilter['submitter'] = Person.objects.filter(id=filt[key])[0]
            elif parts[0] == 'delegate_id':
                dfilter['delegate'] = Person.objects.filter(id=filt[key])[0]
            elif parts[0] == 'state_id':
                dfilter['state'] = State.objects.filter(id=filt[key])[0]
            elif parts[0] == 'max_count':
                max_count = filt[key]
            else:
                dfilter[key] = filt[key]

        patches = Patch.objects.filter(**dfilter)

        if max_count > 0:
            return list(map(patch_to_dict, patches[:max_count]))
        elif max_count < 0:
            query = patches.reverse()[:-max_count]
            return [patch_to_dict(patch) for patch in reversed(query)]
        else:
            return list(map(patch_to_dict, patches))
    except Patch.DoesNotExist:
        return []

Example 31

Project: patchwork
Source File: xmlrpc.py
View license
@xmlrpc_method()
def state_list(search_str=None, max_count=0):
    """List states matching a given name filter.

    Filter states by name. States are compared to the search string
    via a case-insensitive containment test, a.k.a. a partial match.

    Args:
        search_str: The string to compare state names against. If
            blank, all states will be returned.
        max_count (int): The maximum number of states to return.

    Returns:
        A serialized list of states matching filter, if any. A list
        of all states if no filter given.
    """
    try:
        if search_str:
            states = State.objects.filter(name__icontains=search_str)
        else:
            states = State.objects.all()

        if max_count > 0:
            return list(map(state_to_dict, states[:max_count]))
        elif max_count < 0:
            query = states.reverse()[:-max_count]
            return [state_to_dict(state) for state in reversed(query)]
        else:
            return list(map(state_to_dict, states))
    except State.DoesNotExist:
        return []

Example 32

Project: HealthStarter
Source File: response.py
View license
    @property
    def streaming_content(self):
        return map(self.make_bytes, self._iterator)

Example 33

Project: golismero
Source File: response.py
View license
    @property
    def streaming_content(self):
        return map(self.make_bytes, self._iterator)

Example 34

Project: golismero
Source File: testcases.py
View license
    def assertQuerysetEqual(self, qs, values, transform=repr, ordered=True):
        items = six.moves.map(transform, qs)
        if not ordered:
            return self.assertEqual(set(items), set(values))
        return self.assertEqual(list(items), values)

Example 35

Project: mapit
Source File: shortcuts.py
View license
def output_json(out, code=200):
    if code != 200:
        out['code'] = code
    indent = None
    if settings.DEBUG:
        if isinstance(out, dict):
            out['debug_db_queries'] = connection.queries
        indent = 4
    encoder = GEOS_JSONEncoder(ensure_ascii=False, indent=indent)
    content = encoder.iterencode(out)

    # We don't want a generator function (iterencode) to be passed to an
    # HttpResponse, as it won't cache due to its close() function adding it to
    # an instance attribute.
    content = map(lambda x: x, content)

    types = {
        400: http.HttpResponseBadRequest,
        404: http.HttpResponseNotFound,
        500: http.HttpResponseServerError,
    }
    response_type = types.get(code, http.StreamingHttpResponse)

    response = response_type(content_type='application/json; charset=utf-8')
    response['Access-Control-Allow-Origin'] = '*'
    response['Cache-Control'] = 'max-age=2419200'  # 4 weeks
    attr = 'streaming_content' if getattr(response, 'streaming', None) else 'content'
    setattr(response, attr, content)
    return response

Example 36

Project: mapit
Source File: shortcuts.py
View license
def output_json(out, code=200):
    if code != 200:
        out['code'] = code
    indent = None
    if settings.DEBUG:
        if isinstance(out, dict):
            out['debug_db_queries'] = connection.queries
        indent = 4
    encoder = GEOS_JSONEncoder(ensure_ascii=False, indent=indent)
    content = encoder.iterencode(out)

    # We don't want a generator function (iterencode) to be passed to an
    # HttpResponse, as it won't cache due to its close() function adding it to
    # an instance attribute.
    content = map(lambda x: x, content)

    types = {
        400: http.HttpResponseBadRequest,
        404: http.HttpResponseNotFound,
        500: http.HttpResponseServerError,
    }
    response_type = types.get(code, http.StreamingHttpResponse)

    response = response_type(content_type='application/json; charset=utf-8')
    response['Access-Control-Allow-Origin'] = '*'
    response['Cache-Control'] = 'max-age=2419200'  # 4 weeks
    attr = 'streaming_content' if getattr(response, 'streaming', None) else 'content'
    setattr(response, attr, content)
    return response

Example 37

Project: oh-mainline
Source File: response.py
View license
    @property
    def streaming_content(self):
        return map(self.make_bytes, self._iterator)

Example 38

Project: oh-mainline
Source File: testcases.py
View license
    def assertQuerysetEqual(self, qs, values, transform=repr, ordered=True):
        items = six.moves.map(transform, qs)
        if not ordered:
            return self.assertEqual(set(items), set(values))
        return self.assertEqual(list(items), values)