<commit_before>"""Template tags used to render pages."""

from django import template
from django.utils.safestring import mark_safe

from cms.apps.pages.models import Page
from cms.apps.pages.templatetags import PatternNode
from cms.apps.pages.templatetags.permalinks import expand_permalinks
from cms.apps.pages.templatetags.thumbnails import generate_thumbnails

register = template.Library()

# HTML processing.

@register.filter
def html(text):
    """
    Processes HTML text.

    The text is checked for permalinks embedded in <a> tags, expanding the
    permalinks to their referenced URL. Images containing a permalink source
    are checked for size and thumbnailed as appropriate.
    """
    if not text:
        return ""
    text = expand_permalinks(text)
    text = generate_thumbnails(text)
    return mark_safe(text)

@register.tag
def content(parser, token):
    """
    Renders the named content area of the current page.

    For example, to render the content area called 'content_primary'::

        {% content "content_primary" %}

    If you use the 'inherit' keyword, and the page content area is blank, then
    the parent page content area will be rendered instead::

        {% content "content_primary" inherited %}

    """
    def handler(context, content_area, inherited=False):
        page = context["page"]
        content = ""
        while not content:
            content_obj = page.content
            content = getattr(content_obj, content_area, "")
            if not inherited:
                break
            if page.parent:
                page = page.parent
        return html(content)
    return PatternNode(parser, token, handler, ("{content_area} [inherited]", "{content_area}"))

# Page linking.

class PageUrlNode(template.Node):

    """Renders the page_url tag."""

    def __init__(self, page, view_func, args, kwargs, varname):
        """Initializes the PageUrlNode."""
        self.page = page
        self.view_func = view_func
        self.args = args
        self.kwargs = kwargs
        self.varname = varname

    def render(self, context):
        """Renders the PageUrlNode."""
        page = self.page.resolve(context)
        # Get the page URL.
        try:
            page = Page.objects.get_page(page)
        except Page.DoesNotExist:
            url = "#"
        else:
            args = [arg.resolve(context) for arg in self.args]
            kwargs = dict((key, value.resolve(context)) for key, value in self.kwargs.items())
            url = page.content.reverse(self.view_func, *args, **kwargs)
        # Return the value, or set as a context variable as appropriate.
        if self.varname:
            context[self.varname] = url
            return ""
        else:
            return url

@register.tag
def page_url(parser, token):
    """Renders the URL of the given view func in the given page."""
    contents = token.split_contents()
    tag_name = contents[0]
    contents = contents[1:]
    # Attempt to parse the varname.
    try:
        if contents.index("as") == len(contents) - 2:
            varname = contents[-1]
            contents = contents[:-2]
        else:
            raise template.TemplateSyntaxError, "%s tag expects only one argument after 'as' statement" % tag_name
    except ValueError:
        # No varname was specified.
        varname = None
    # Attempt to parse the page.
    try:
        page = parser.compile_filter(contents[0])
    except IndexError:
        raise template.TemplateSyntaxError, "No page specified in %s tag" % tag_name
    # Attempt to parse the view func.
    try:
        view_func = contents[1]
    except IndexError:
        view_func = "index"
    # Parse all remaining token as arguments.
    args = []
    kwargs = {}
    for argument in "".join(contents[2:]).split(","):
        if "=" in argument:
            key, value = argument.split("=")
            kwargs[key.strip()] = parser.compile_filter(value.strip())
        else:
            args.append(parser.compile_filter(argument.strip()))
    # Create the node.
    return PageUrlNode(page, view_func, args, kwargs, varname)

# Page widgets.

@register.tag
def meta_description(parser, token):
    """
    Renders the content of the meta description tag for the current page::

        {% meta_description %}

    You can override the meta description by setting a context variable called
    'meta_description'::

        {% with "foo" as meta_description %}
            {% meta_description %}
        {% endwith %}

    You can also provide the meta description as an argument to this tag::

        {% meta_description "foo" %}

    """
    def handler(context, description=None):
        page = context["page"]
        description = description or context.get("meta_description", "")
        while not description and page:
            description = page.meta_description
            page = page.parent
        return description
    return PatternNode(parser, token, handler, ("{description}", "",))

@register.tag
def meta_keywords(parser, token):
    """
    Renders the content of the meta keywords tag for the current page::

        {% meta_keywords %}

    You can override the meta keywords by setting a context variable called
    'meta_keywords'::

        {% with "foo" as meta_keywords %}
            {% meta_keywords %}
        {% endwith %}

    You can also provide the meta keywords as an argument to this tag::

        {% meta_keywords "foo" %}

    """
    def handler(context, keywords=None):
        page = context["page"]
        keywords = keywords or context.get("meta_keywords", "")
        while not keywords and page:
            keywords = page.meta_keywords
            page = page.parent
        return keywords
    return PatternNode(parser, token, handler, ("{keywords}", "",))

@register.tag
def meta_robots(parser, token):
    """
    Renders the content of the meta robots tag for the current page::

        {% meta_keywords %}

    You can override the meta robots by setting boolean context variables called
    'robots_index', 'robots_archive' and 'robots_follow'::

        {% with 1 as robots_follow %}
            {% meta_robots %}
        {% endwith %}

    You can also provide the meta robots as three boolean arguments to this
    tag in the order 'index', 'archive' and 'follow'::

        {% meta_robots 1 1 1 %}

    """
    def handler(context, index=None, archive=None, follow=None):
        page = context["page"]
        index = index or context.get("robots_index", None)
        archive = archive or context.get("robots_archive", None)
        follow = index or context.get("robots_follow", None)
        # Follow the page ancestry, looking for robots flags.
        while page:
            if index is None and page.robots_index != None:
                index = page.robots_index
            if archive is None and page.robots_archive != None:
                archive = page.robots_archive
            if follow is None and page.robots_follow != None:
                follow = page.robots_follow
            page = page.parent
        # If no page specified robots, then default to True.
        if index is None:
            index = True
        if archive is None:
            archive = True
        if follow is None:
            follow = True
        # Generate the meta content.
        return ", ".join((index and "INDEX" or "NOINDEX", follow and "FOLLOW" or "NOFOLLOW", archive and "ARCHIVE" or "NOARCHIVE"))
    return PatternNode(parser, token, handler, ("{index} {archive} {follow}", "",))

@register.tag
def title(parser, token):
    """
    Renders the title of the current page::

        {% title %}

    You can override the title by setting a context variable called 'title'::

        {% with "foo" as title %}
            {% title %}
        {% endwith %}

    You can also provide the title as an argument to this tag::

        {% title "foo" %}

    """
    def handler(context, title=None):
        page = context["page"]
        homepage = page.homepage
        # Render the title template.
        context.push()
        try:
            context.update({"title": title or context.get("title", "") or page.browser_title or page.title,
                            "site_title": homepage.browser_title or homepage.title})
            return template.loader.render_to_string("title.html", context)
        finally:
            context.pop()
    return PatternNode(parser, token, handler, ("{title}", "",))

def nav_context(page, request):
    """
    Generates a dictionary of variables related to the page, for use in page
    navigation.
    """
    page_url = page.get_absolute_url()
    return {"title": page.short_title or page.title,
            "url": page_url,
            "here": request.path.startswith(page_url),
            "page": page}

def nav_context_exact(page, request):
    """
    Generates a dictionary of variables related to the page, for use in page
    navigation.

    This differs to nav_context in that the page URL is matched exactly to the
    request path for determining whether the page should be considered 'here'.
    """
    page_url = page.get_absolute_url()
    return {"title": page.short_title or page.title,
            "url": page_url,
            "here": request.path == page_url,
            "page": page}

@register.tag
def nav_primary(parser, token):
    """
    Renders the primary navigation of the current page::

        {% nav_primary %}

    """
    def handler(context):
        page = context["page"]
        request = context["request"]
        homepage = page.homepage
        navigation = []
        if homepage.in_navigation:
            navigation.append(nav_context_exact(homepage, request))
        for entry in homepage.navigation:
            navigation.append(nav_context(entry, request))
        context.push()
        try:
            context.update({"navigation": navigation})
            return template.loader.render_to_string("nav_primary.html", context)
        finally:
            context.pop()
    return PatternNode(parser, token, handler, ("",))

@register.tag
def nav_secondary(parser, token):
    """
    Renders the secondary navigation of the current page::

        {% nav_secondary %}

    """
    def handler(context):
        page = context["page"]
        request = context["request"]
        navigation = []
        try:
            section = page.breadcrumbs[1]
        except IndexError:
            pass
        else:
            if section.in_navigation:
                navigation.append(nav_context_exact(section, request))
            for entry in section.navigation:
                navigation.append(nav_context(entry, request))
        context.push()
        try:
            context.update({"navigation": navigation})
            return template.loader.render_to_string("nav_secondary.html", context)
        finally:
            context.pop()
    return PatternNode(parser, token, handler, ("",))

@register.tag
def nav_tertiary(parser, token):
    """
    Renders the tertiary navigation of the current page::

        {% nav_tertiary %}

    """
    def handler(context):
        page = context["page"]
        request = context["request"]
        navigation = []
        try:
            subsection = page.breadcrumbs[2]
        except IndexError:
            pass
        else:
            if subsection.in_navigation:
                navigation.append(nav_context_exact(subsection, request))
            for entry in subsection.navigation:
                navigation.append(nav_context(entry, request))
        context.push()
        try:
            context.update({"navigation": navigation})
            return template.loader.render_to_string("nav_tertiary.html", context)
        finally:
            context.pop()
    return PatternNode(parser, token, handler, ("",))

@register.tag
def breadcrumbs(parser, token):
    """
    Renders the breadcrumbs trail for the current page::

        {% breadcrumbs %}

    To override and extend the breadcrumb trail within page applications, add
    the 'extended' flag to the tag and add your own breadcrumbs underneath::

        {% breadcrumbs extended %}

    """
    def handler(context, extended=False):
        page = context["page"]
        breadcrumbs = [{"title": breadcrumb.title,
                        "url": breadcrumb.get_absolute_url(),
                        "last": False,
                        "page": breadcrumb}
                       for breadcrumb in page.breadcrumbs]
        if not extended:
            if len(breadcrumbs) == 1:
                # Display no breadcrumbs on the homepage.
                breadcrumbs = []
            else:
                breadcrumbs[-1]["last"] = True
        # Render the breadcrumbs.
        context.push()
        try:
            context.update({"breadcrumbs": breadcrumbs,})
            return template.loader.render_to_string("breadcrumbs.html", context)
        finally:
            context.pop()
    return PatternNode(parser, token, handler, ("[extended]", ""))

@register.tag
def header(parser, token):
    """
    Renders the header for the current page::

        {% header %}

    You can override the page header by providing a 'header' or 'title' context
    variable. If both are present, then 'header' overrides 'title'::

        {% with "foo" as header %}
            {% header %}
        {% endwith %}

    You can also provide the header as an argument to this tag::

        {% header "foo" %}

    """
    def handler(context, header=None):
        page = context["page"]
        header = header or context.get("header", "") or page.title
        context.push()
        try:
            context.update({"header": header})
            return template.loader.render_to_string("header.html", context)
        finally:
            context.pop()
    return PatternNode(parser, token, handler, ("{header}", "",))

    <commit_msg>Fixed error in breadcrumbs tag.<commit_after>"""Template tags used to render pages."""

from django import template
from django.utils.safestring import mark_safe

from cms.apps.pages.models import Page
from cms.apps.pages.templatetags import PatternNode
from cms.apps.pages.templatetags.permalinks import expand_permalinks
from cms.apps.pages.templatetags.thumbnails import generate_thumbnails

register = template.Library()

# HTML processing.

@register.filter
def html(text):
    """
    Processes HTML text.

    The text is checked for permalinks embedded in <a> tags, expanding the
    permalinks to their referenced URL. Images containing a permalink source
    are checked for size and thumbnailed as appropriate.
    """
    if not text:
        return ""
    text = expand_permalinks(text)
    text = generate_thumbnails(text)
    return mark_safe(text)

@register.tag
def content(parser, token):
    """
    Renders the named content area of the current page.

    For example, to render the content area called 'content_primary'::

        {% content "content_primary" %}

    If you use the 'inherit' keyword, and the page content area is blank, then
    the parent page content area will be rendered instead::

        {% content "content_primary" inherited %}

    """
    def handler(context, content_area, inherited=False):
        page = context["page"]
        content = ""
        while not content:
            content_obj = page.content
            content = getattr(content_obj, content_area, "")
            if not inherited:
                break
            if page.parent:
                page = page.parent
        return html(content)
    return PatternNode(parser, token, handler, ("{content_area} [inherited]", "{content_area}"))

# Page linking.

class PageUrlNode(template.Node):

    """Renders the page_url tag."""

    def __init__(self, page, view_func, args, kwargs, varname):
        """Initializes the PageUrlNode."""
        self.page = page
        self.view_func = view_func
        self.args = args
        self.kwargs = kwargs
        self.varname = varname

    def render(self, context):
        """Renders the PageUrlNode."""
        page = self.page.resolve(context)
        # Get the page URL.
        try:
            page = Page.objects.get_page(page)
        except Page.DoesNotExist:
            url = "#"
        else:
            args = [arg.resolve(context) for arg in self.args]
            kwargs = dict((key, value.resolve(context)) for key, value in self.kwargs.items())
            url = page.content.reverse(self.view_func, *args, **kwargs)
        # Return the value, or set as a context variable as appropriate.
        if self.varname:
            context[self.varname] = url
            return ""
        else:
            return url

@register.tag
def page_url(parser, token):
    """Renders the URL of the given view func in the given page."""
    contents = token.split_contents()
    tag_name = contents[0]
    contents = contents[1:]
    # Attempt to parse the varname.
    try:
        if contents.index("as") == len(contents) - 2:
            varname = contents[-1]
            contents = contents[:-2]
        else:
            raise template.TemplateSyntaxError, "%s tag expects only one argument after 'as' statement" % tag_name
    except ValueError:
        # No varname was specified.
        varname = None
    # Attempt to parse the page.
    try:
        page = parser.compile_filter(contents[0])
    except IndexError:
        raise template.TemplateSyntaxError, "No page specified in %s tag" % tag_name
    # Attempt to parse the view func.
    try:
        view_func = contents[1]
    except IndexError:
        view_func = "index"
    # Parse all remaining token as arguments.
    args = []
    kwargs = {}
    for argument in "".join(contents[2:]).split(","):
        if "=" in argument:
            key, value = argument.split("=")
            kwargs[key.strip()] = parser.compile_filter(value.strip())
        else:
            args.append(parser.compile_filter(argument.strip()))
    # Create the node.
    return PageUrlNode(page, view_func, args, kwargs, varname)

# Page widgets.

@register.tag
def meta_description(parser, token):
    """
    Renders the content of the meta description tag for the current page::

        {% meta_description %}

    You can override the meta description by setting a context variable called
    'meta_description'::

        {% with "foo" as meta_description %}
            {% meta_description %}
        {% endwith %}

    You can also provide the meta description as an argument to this tag::

        {% meta_description "foo" %}

    """
    def handler(context, description=None):
        page = context["page"]
        description = description or context.get("meta_description", "")
        while not description and page:
            description = page.meta_description
            page = page.parent
        return description
    return PatternNode(parser, token, handler, ("{description}", "",))

@register.tag
def meta_keywords(parser, token):
    """
    Renders the content of the meta keywords tag for the current page::

        {% meta_keywords %}

    You can override the meta keywords by setting a context variable called
    'meta_keywords'::

        {% with "foo" as meta_keywords %}
            {% meta_keywords %}
        {% endwith %}

    You can also provide the meta keywords as an argument to this tag::

        {% meta_keywords "foo" %}

    """
    def handler(context, keywords=None):
        page = context["page"]
        keywords = keywords or context.get("meta_keywords", "")
        while not keywords and page:
            keywords = page.meta_keywords
            page = page.parent
        return keywords
    return PatternNode(parser, token, handler, ("{keywords}", "",))

@register.tag
def meta_robots(parser, token):
    """
    Renders the content of the meta robots tag for the current page::

        {% meta_keywords %}

    You can override the meta robots by setting boolean context variables called
    'robots_index', 'robots_archive' and 'robots_follow'::

        {% with 1 as robots_follow %}
            {% meta_robots %}
        {% endwith %}

    You can also provide the meta robots as three boolean arguments to this
    tag in the order 'index', 'archive' and 'follow'::

        {% meta_robots 1 1 1 %}

    """
    def handler(context, index=None, archive=None, follow=None):
        page = context["page"]
        index = index or context.get("robots_index", None)
        archive = archive or context.get("robots_archive", None)
        follow = index or context.get("robots_follow", None)
        # Follow the page ancestry, looking for robots flags.
        while page:
            if index is None and page.robots_index != None:
                index = page.robots_index
            if archive is None and page.robots_archive != None:
                archive = page.robots_archive
            if follow is None and page.robots_follow != None:
                follow = page.robots_follow
            page = page.parent
        # If no page specified robots, then default to True.
        if index is None:
            index = True
        if archive is None:
            archive = True
        if follow is None:
            follow = True
        # Generate the meta content.
        return ", ".join((index and "INDEX" or "NOINDEX", follow and "FOLLOW" or "NOFOLLOW", archive and "ARCHIVE" or "NOARCHIVE"))
    return PatternNode(parser, token, handler, ("{index} {archive} {follow}", "",))

@register.tag
def title(parser, token):
    """
    Renders the title of the current page::

        {% title %}

    You can override the title by setting a context variable called 'title'::

        {% with "foo" as title %}
            {% title %}
        {% endwith %}

    You can also provide the title as an argument to this tag::

        {% title "foo" %}

    """
    def handler(context, title=None):
        page = context["page"]
        homepage = page.homepage
        # Render the title template.
        context.push()
        try:
            context.update({"title": title or context.get("title", "") or page.browser_title or page.title,
                            "site_title": homepage.browser_title or homepage.title})
            return template.loader.render_to_string("title.html", context)
        finally:
            context.pop()
    return PatternNode(parser, token, handler, ("{title}", "",))

def nav_context(page, request):
    """
    Generates a dictionary of variables related to the page, for use in page
    navigation.
    """
    page_url = page.get_absolute_url()
    return {"title": page.short_title or page.title,
            "url": page_url,
            "here": request.path.startswith(page_url),
            "page": page}

def nav_context_exact(page, request):
    """
    Generates a dictionary of variables related to the page, for use in page
    navigation.

    This differs to nav_context in that the page URL is matched exactly to the
    request path for determining whether the page should be considered 'here'.
    """
    page_url = page.get_absolute_url()
    return {"title": page.short_title or page.title,
            "url": page_url,
            "here": request.path == page_url,
            "page": page}

@register.tag
def nav_primary(parser, token):
    """
    Renders the primary navigation of the current page::

        {% nav_primary %}

    """
    def handler(context):
        page = context["page"]
        request = context["request"]
        homepage = page.homepage
        navigation = []
        if homepage.in_navigation:
            navigation.append(nav_context_exact(homepage, request))
        for entry in homepage.navigation:
            navigation.append(nav_context(entry, request))
        context.push()
        try:
            context.update({"navigation": navigation})
            return template.loader.render_to_string("nav_primary.html", context)
        finally:
            context.pop()
    return PatternNode(parser, token, handler, ("",))

@register.tag
def nav_secondary(parser, token):
    """
    Renders the secondary navigation of the current page::

        {% nav_secondary %}

    """
    def handler(context):
        page = context["page"]
        request = context["request"]
        navigation = []
        try:
            section = page.breadcrumbs[1]
        except IndexError:
            pass
        else:
            if section.in_navigation:
                navigation.append(nav_context_exact(section, request))
            for entry in section.navigation:
                navigation.append(nav_context(entry, request))
        context.push()
        try:
            context.update({"navigation": navigation})
            return template.loader.render_to_string("nav_secondary.html", context)
        finally:
            context.pop()
    return PatternNode(parser, token, handler, ("",))

@register.tag
def nav_tertiary(parser, token):
    """
    Renders the tertiary navigation of the current page::

        {% nav_tertiary %}

    """
    def handler(context):
        page = context["page"]
        request = context["request"]
        navigation = []
        try:
            subsection = page.breadcrumbs[2]
        except IndexError:
            pass
        else:
            if subsection.in_navigation:
                navigation.append(nav_context_exact(subsection, request))
            for entry in subsection.navigation:
                navigation.append(nav_context(entry, request))
        context.push()
        try:
            context.update({"navigation": navigation})
            return template.loader.render_to_string("nav_tertiary.html", context)
        finally:
            context.pop()
    return PatternNode(parser, token, handler, ("",))

@register.tag
def breadcrumbs(parser, token):
    """
    Renders the breadcrumbs trail for the current page::

        {% breadcrumbs %}

    To override and extend the breadcrumb trail within page applications, add
    the 'extended' flag to the tag and add your own breadcrumbs underneath::

        {% breadcrumbs extended %}

    """
    def handler(context, extended=False):
        page = context["page"]
        breadcrumbs = [{"title": breadcrumb.short_title or breadcrumb.title,
                        "url": breadcrumb.get_absolute_url(),
                        "last": False,
                        "page": breadcrumb}
                       for breadcrumb in page.breadcrumbs]
        if not extended:
            if len(breadcrumbs) == 1:
                # Display no breadcrumbs on the homepage.
                breadcrumbs = []
            else:
                breadcrumbs[-1]["last"] = True
        # Render the breadcrumbs.
        context.push()
        try:
            context.update({"breadcrumbs": breadcrumbs,})
            return template.loader.render_to_string("breadcrumbs.html", context)
        finally:
            context.pop()
    return PatternNode(parser, token, handler, ("[extended]", ""))

@register.tag
def header(parser, token):
    """
    Renders the header for the current page::

        {% header %}

    You can override the page header by providing a 'header' or 'title' context
    variable. If both are present, then 'header' overrides 'title'::

        {% with "foo" as header %}
            {% header %}
        {% endwith %}

    You can also provide the header as an argument to this tag::

        {% header "foo" %}

    """
    def handler(context, header=None):
        page = context["page"]
        header = header or context.get("header", "") or page.title
        context.push()
        try:
            context.update({"header": header})
            return template.loader.render_to_string("header.html", context)
        finally:
            context.pop()
    return PatternNode(parser, token, handler, ("{header}", "",))

    <|endoftext|>


<commit_before>#!/usr/bin/env python

import myriadeploy

import subprocess
import sys

def get_host_port_path(node, default_path):
    if len(node) == 2:
        (hostname, port) = node
        if default_path is None:
            raise Exception("Path not specified for node %s" % str(node))
        else:
            path = default_path
    else:
        (hostname, port, path) = node
    return (hostname, port, path)

def remote_rm(hostname, dirname, username):
    print hostname
    if hostname != 'localhost':
        args = ["ssh", "%s@%s" % (username, hostname), "rm", "-rf", dirname]
    else:
        args = ["rm", "-rf", dirname]
    return subprocess.call(args)

def rm_deployment(config):
    """Copies the master and worker catalogs to the remote hosts."""
    description = config['description']
    default_path = config['path']
    master = config['master']
    workers = config['workers']
    username = config['username']

    # Remove directories on master
    (hostname, _, path) = get_host_port_path(master, default_path)
    if remote_rm(hostname, "%s/%s-files" \
            % (path, description), username):
        raise Exception("Error removing directory on master %s" \
                % (hostname,))

    for (i, worker) in enumerate(workers):
        # Workers are numbered from 1, not 0
        worker_id = i + 1

        # Remove directories on the worker
        (hostname, _, path) = get_host_port_path(worker, default_path)
        if remote_rm(hostname, "%s/%s-files" \
                % (path, description), username):
            raise Exception("Error removing directory on worker %d %s" \
                    % (worker_id, hostname))

def main(argv):
    # Usage
    if len(argv) != 2:
        print >> sys.stderr, "Usage: %s <deployment.cfg>" % (argv[0])
        print >> sys.stderr, "       deployment.cfg: a configuration file modeled after deployment.cfg.sample"
        sys.exit(1)

    config = myriadeploy.read_config_file(argv[1])
    rm_deployment(config)

if __name__ == "__main__":
    main(sys.argv)
<commit_msg>Fix remove_deployment.py<commit_after>#!/usr/bin/env python

import myriadeploy

import subprocess
import sys

def get_host_port_path(node, default_path):
    if len(node) == 2:
        (hostname, port) = node
        if default_path is None:
            raise Exception("Path not specified for node %s" % str(node))
        else:
            path = default_path
    else:
        (hostname, port, path, _) = node
    return (hostname, port, path)

def remote_rm(hostname, dirname, username):
    print hostname
    if hostname != 'localhost':
        args = ["ssh", "%s@%s" % (username, hostname), "rm", "-rf", dirname]
    else:
        args = ["rm", "-rf", dirname]
    return subprocess.call(args)

def rm_deployment(config):
    """Copies the master and worker catalogs to the remote hosts."""
    description = config['description']
    default_path = config['path']
    master = config['master']
    workers = config['workers']
    username = config['username']

    # Remove directories on master
    (hostname, _, path) = get_host_port_path(master, default_path)
    if remote_rm(hostname, "%s/%s-files" \
            % (path, description), username):
        raise Exception("Error removing directory on master %s" \
                % (hostname,))

    for (i, worker) in enumerate(workers):
        # Workers are numbered from 1, not 0
        worker_id = i + 1

        # Remove directories on the worker
        (hostname, _, path) = get_host_port_path(worker, default_path)
        if remote_rm(hostname, "%s/%s-files" \
                % (path, description), username):
            raise Exception("Error removing directory on worker %d %s" \
                    % (worker_id, hostname))

def main(argv):
    # Usage
    if len(argv) != 2:
        print >> sys.stderr, "Usage: %s <deployment.cfg>" % (argv[0])
        print >> sys.stderr, "       deployment.cfg: a configuration file modeled after deployment.cfg.sample"
        sys.exit(1)

    config = myriadeploy.read_config_file(argv[1])
    rm_deployment(config)

if __name__ == "__main__":
    main(sys.argv)
<|endoftext|>


<commit_before>"""
This Blueprint implements Blog related views.
"""
from flask import Blueprint, render_template, abort, request, redirect
from flask_misaka import markdown
from flask_login import login_required, current_user
from flask_wtf import Form
import wtforms

from models import Post, Tag
from extensions import db

blog = Blueprint('blog', __name__)

@blog.route('/')
def blog_index():
    all_posts = Post.query.all()
    all_posts = sorted(all_posts, key=lambda p: p.created_at, reverse=True)
    all_tags = Tag.query.all()
    all_tags = sorted(all_tags, key=lambda t: t.name)
    return render_template('blog_list.html', posts=all_posts, tags=all_tags)

@blog.route('/post/<post_url>')
def blog_post(post_url):
    post = Post.query.filter_by(url=post_url).first()
    if post is None:
        abort(404)
    md_text = post.content
    html = markdown(md_text, fenced_code=True, math=True)
    # https://flask-misaka.readthedocs.io/en/latest/
    # http://misaka.61924.nl/#
    if post.published_at:
        time_str = post.published_at.strftime('%Y-%m-%d %H:%M')
    else:
        time_str = 'not published yet'
    return render_template('blog_post.html', title=post.title, content=html, posted_at=time_str, tags=post.tags)

@blog.route('/tag/<tag_name>')
def blog_tag(tag_name):
    tag = Tag.query.filter_by(name=tag_name).first()
    return render_template('blog_tag.html', tag=tag, posts=tag.posts)

class BlogEditForm(Form):
    title = wtforms.StringField('Title', validators=[wtforms.validators.DataRequired()])
    url = wtforms.StringField('Url', validators=[wtforms.validators.DataRequired()])
    content = wtforms.TextAreaField('Content', validators=[wtforms.validators.DataRequired()])
    submit = wtforms.SubmitField('Save')

@blog.route('/new')
@login_required
def new_post():
    post = Post(title='Untitled', content='', author_id=current_user.id)
    db.session.add(post)
    db.session.commit()
    return redirect('/blog/edit/{}'.format(post.id))

@blog.route('/edit/<int:post_id>', methods=['GET', 'POST'])
@login_required
def edit_post(post_id):
    if request.method == 'POST':
        form = BlogEditForm(request.form)
        return 'posted
request.form["title"]: {}
form.title: {}'.format(request.form['title'], form.title)
    post = Post.query.filter_by(id=post_id).first()
    form = BlogEditForm(title=post.title, content=post.content)
    form = BlogEditForm(title=post.title, content=post.content, url=post.url)
    return render_template('blog_edit.html', form=form, post=post)
<commit_msg>helper function to generate unique url's<commit_after>"""
This Blueprint implements Blog related views.
"""
from flask import Blueprint, render_template, abort, request, redirect
from flask_misaka import markdown
from flask_login import login_required, current_user
from flask_wtf import Form
import wtforms

from models import Post, Tag
from extensions import db

blog = Blueprint('blog', __name__)

@blog.route('/')
def blog_index():
    all_posts = Post.query.all()
    all_posts = sorted(all_posts, key=lambda p: p.created_at, reverse=True)
    all_tags = Tag.query.all()
    all_tags = sorted(all_tags, key=lambda t: t.name)
    return render_template('blog_list.html', posts=all_posts, tags=all_tags)

@blog.route('/post/<post_url>')
def blog_post(post_url):
    post = Post.query.filter_by(url=post_url).first()
    if post is None:
        abort(404)
    md_text = post.content
    html = markdown(md_text, fenced_code=True, math=True)
    # https://flask-misaka.readthedocs.io/en/latest/
    # http://misaka.61924.nl/#
    if post.published_at:
        time_str = post.published_at.strftime('%Y-%m-%d %H:%M')
    else:
        time_str = 'not published yet'
    return render_template('blog_post.html', title=post.title, content=html, posted_at=time_str, tags=post.tags)

@blog.route('/tag/<tag_name>')
def blog_tag(tag_name):
    tag = Tag.query.filter_by(name=tag_name).first()
    return render_template('blog_tag.html', tag=tag, posts=tag.posts)

class BlogEditForm(Form):
    title = wtforms.StringField('Title', validators=[wtforms.validators.DataRequired()])
    url = wtforms.StringField('Url', validators=[wtforms.validators.DataRequired()])
    content = wtforms.TextAreaField('Content', validators=[wtforms.validators.DataRequired()])
    submit = wtforms.SubmitField('Save')

@blog.route('/new')
@login_required
def new_post():
    post = Post(title='Untitled', content='', author_id=current_user.id)
    db.session.add(post)
    db.session.commit()
    return redirect('/blog/edit/{}'.format(post.id))

@blog.route('/edit/<int:post_id>', methods=['GET', 'POST'])
@login_required
def edit_post(post_id):
    if request.method == 'POST':
        form = BlogEditForm(request.form)
        return 'posted
request.form["title"]: {}
form.title: {}'.format(request.form['title'], form.title)
    post = Post.query.filter_by(id=post_id).first()
    form = BlogEditForm(title=post.title, content=post.content)
    form = BlogEditForm(title=post.title, content=post.content, url=post.url)
    return render_template('blog_edit.html', form=form, post=post)

def make_url_unique(url):
    """Append "_" to URL until no matches are in Post table."""
    while True:
        is_unique = Post.query.filter_by(url=url).count() < 2
        if is_unique:
            break
        url += '_'
    return url
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

import calendar
from jinja2 import Environment, FileSystemLoader

class Mbrmau:

    def __init__(self, year, month):
        first_weekday, last_day = calendar.monthrange(year, month)
        days = map(lambda n: n+1, range(last_day))
        weekdays = map(lambda n: (first_weekday+n) % 7, range(last_day))
        workdays = filter(lambda n: n[1] < 5, zip(days, weekdays))
        self.__workdays =\
            list(map(lambda n: '%d/%d/%d' % (year, month, n[0]), workdays))

    def message(self):
        env = Environment(loader=FileSystemLoader('./', encoding='utf8'))
        tpl = env.get_template('mbrmau/message.tpl')

        tpl_variables = {
                "days": self.__workdays
                }

        message = tpl.render(tpl_variables)

        return message

if __name__ == '__main__':
    print(Mbrmau(2016, 12).message())
<commit_msg>test PackageLoader<commit_after># -*- coding: utf-8 -*-

import calendar
from jinja2 import Environment, PackageLoader

class Mbrmau:

    def __init__(self, year, month):
        first_weekday, last_day = calendar.monthrange(year, month)
        days = map(lambda n: n+1, range(last_day))
        weekdays = map(lambda n: (first_weekday+n) % 7, range(last_day))
        workdays = filter(lambda n: n[1] < 5, zip(days, weekdays))
        self.__workdays =\
            list(map(lambda n: '%d/%d/%d' % (year, month, n[0]), workdays))

    def message(self):
        pl = PackageLoader('mbrmau', './', encoding='utf8')
        env = Environment(loader=pl)
        tpl = env.get_template('message.tpl')

        tpl_variables = {
                "days": self.__workdays
                }

        message = tpl.render(tpl_variables)

        return message

if __name__ == '__main__':
    print(Mbrmau(2016, 12).message())
<|endoftext|>


<commit_before>import json
from _testcapi import raise_exception
from itertools import chain
import requests
from django.contrib.auth.models import User
from django.core import exceptions as django_exceptions
from django.http import QueryDict
from django.shortcuts import get_object_or_404
from requests.auth import HTTPBasicAuth
from rest_framework import generics, permissions, response, status, views
from rest_framework import viewsets
from rest_framework.decorators import detail_route
import uuid

from . import permissions as my_permissions
from .models import Author, FriendRequest, Node, PostVisibility
from .serializers import FullAuthorSerializer, AuthenticateSerializer, \
	UpdateAuthorSerializer, AuthorNetworkSerializer, AuthorSerializer, \
	FriendRequestSerializer, RemoteRequestSerializer, AuthorFriendListSerializer, AuthorFriendSpecialListSerializer

class AuthorListView(generics.ListAPIView):
	queryset = Author.objects.all()
	serializer_class = AuthorSerializer
	permission_classes = [permissions.IsAuthenticated, my_permissions.IsAdminOrIsLocalUser]

class AuthorCreateView(generics.CreateAPIView):
	queryset = Author.objects.all()
	serializer_class = FullAuthorSerializer
	permission_classes = [permissions.AllowAny]

class AuthorUpdateView(generics.UpdateAPIView):
	queryset = Author.objects.all()
	serializer_class = UpdateAuthorSerializer
	permission_classes = [permissions.IsAuthenticated, my_permissions.IsOwnerForModifyAuthor]

class AuthorRetrieveView(generics.RetrieveAPIView):
	queryset = Author.objects.all()
	serializer_class = AuthorSerializer
	permission_classes = [permissions.IsAuthenticated]

class AuthorAuthenticationView(views.APIView):
	queryset = Author.objects.all()
	serializer_class = AuthenticateSerializer

	def post(self, request):
		data = request.data
		serializer = AuthenticateSerializer(data=data)
		if serializer.is_valid(raise_exception=True):
			new_data = serializer.data
			return response.Response(new_data, status=status.HTTP_200_OK)
		return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class AuthorNetworkView(generics.RetrieveAPIView):
	queryset = Author.objects.all()
	serializer_class = AuthorNetworkSerializer

class AuthorFriendListView(viewsets.ModelViewSet):
	queryset = Author.objects.all()
	serializer_class = AuthorFriendListSerializer

	def retrieve(self, request, *args, **kwargs):
		self.serializer_class = AuthorFriendListSerializer
		instance = self.get_object()
		serializer = self.get_serializer(instance)
		data = serializer.data
		data['query'] = 'friends'
		return response.Response(data, status=status.HTTP_200_OK)

	def is_friend(self,request, *args, **kwargs):
		self.serializer_class = AuthorFriendSpecialListSerializer
		instance = self.get_object()
		serializer = self.get_serializer(instance)
		to_be_removed = []
		data = request.data
		count = 0
		for aid in data['authors']:
			is_friend = False
			for friend in instance.authors.all():
				if aid == str(friend.id):
					print aid + " is equals to " + str(friend.id)
					is_friend = True
				else:
					print aid + " is not equals to " + str(friend.id)

			if not is_friend:
				print aid + " and " + str(instance.id) + " are not friends at all."
				to_be_removed.append(count)
			count += 1
		for i in reversed(to_be_removed):
			print i
			data['authors'].pop(i)
		return response.Response(data['authors'], status=status.HTTP_200_OK)

class SendFriendRequestView(viewsets.ModelViewSet):
	serializer_class = AuthorNetworkSerializer

	def get_queryset(self):
		result_list = FriendRequest.objects.filter(receiver=self.request.user.author)
		return result_list

	@detail_route(methods=['post'])
	def send_request(self, request, **kwargs):
		try:
			author = request.user.author
			receiver = get_object_or_404(Author, id=kwargs['pk'])
			try:
				FriendRequest.objects.get(sender=author, receiver=author)
				return response.Response(status=status.HTTP_400_BAD_REQUEST)
			except django_exceptions.ObjectDoesNotExist:
				pass
			friendRequest = FriendRequest.objects.create(sender=author, receiver=receiver)
			friendRequest.save()
			return response.Response(status=status.HTTP_202_ACCEPTED)
		except AttributeError:
			return response.Response(status=status.HTTP_400_BAD_REQUEST)

class SendRemoteFriendRequestView(viewsets.ViewSet):
	serializer_class = RemoteRequestSerializer
	queryset = FriendRequest.objects.all()
	permission_classes = [permissions.IsAuthenticated]

	def send_to_remote(self, url, data, node):
		r = requests.post(url, json=data, auth=(node.rcred_username, node.rcred_password))
		return r

	def makeAuthor(self, data, node_url):
		print "Making author"
		id = data['id']
		displayNamesplit = data['displayName'].split(" ")
		username = displayNamesplit[0] + id[0:7]
		first_name = username
		last_name = username
		email = username + "@nousageemail.com"
		try:
			user = User.objects.create(username=username,
			                           first_name=first_name, last_name=last_name, email=email)
		except:
			return User.objects.get(username=username)
		author = Author.objects.create(user=user, id=uuid.UUID(id),
		                               displayName=str(data['displayName']), github="noGitHUB",
		                               host=node_url, url=node_url+"/author/"+id)
		return author

	@detail_route(methods=['post'])
	def send_request(self, request):
		# check if node is allowed. if not, 403
		try:
			try :
				data = json.loads(json.dumps(request.data))
				print data
				author_host = data['author']['host']
				friend_host = data['friend']['host']
				is_json = True
			except:
				author_host = str(request.data['author.host'])
				friend_host = str(request.data['friend.host'])
			try:
				author_host = author_host.split("/", 3)[2]
				friend_host = friend_host.split("/", 3)[2]
			except:
				pass
			node_author = Node.objects.get(node_url="http://"+author_host)
			node_friend = Node.objects.get(node_url="http://"+friend_host)
		except django_exceptions.ObjectDoesNotExist:
			return response.Response(status=status.HTTP_403_FORBIDDEN)
		# check if json is ok. if yes, get authors that are trying to be friends
		serializer = RemoteRequestSerializer(data=request.data)
		if serializer.is_valid(raise_exception=True):
			data = serializer.data
			try:
				author = Author.objects.get(id=data['author']['id'])
			except django_exceptions.ObjectDoesNotExist:
				author = self.makeAuthor(data['author'], node_author.node_url)
			try:
				friend = Author.objects.get(id=data['friend']['id'])
			except django_exceptions.ObjectDoesNotExist:
				friend = self.makeAuthor(data['friend'], node_friend.node_url)
			#check if there its for accept or not. if not, add the friend request
			try:
				friendRequest = FriendRequest.objects.get(sender=author, receiver=friend)
				friendRequest.delete()
				author.authors.add(friend)
				post_visibilities = PostVisibility.objects.filter(post__author=receiver)
				for pv in post_visibilities:
					if pv.post.visibility == 'FRIENDS' or pv.post.visibility == 'FOAF':
						PostVisibility.objects.create(post=pv.post, author=friend)
						if pv.post.visibility == 'FOAF':
							for f in friend.authors:
								PostVisibility.objects.create(post=pv.post, author=f)
				return response.Response(status=status.HTTP_202_ACCEPTED)
			except django_exceptions.ObjectDoesNotExist:
				try:
					FriendRequest.objects.get(sender=friend, receiver=author)
				except django_exceptions.ObjectDoesNotExist:
					FriendRequest.objects.create(sender=friend, receiver=author)
			try:
				data['query'] = 'friendrequest'
				res = self.send_to_remote(node_author.node_url+'/friendrequest', data, node_author)
				return response.Response(res, status=status.HTTP_200_OK)

			except:
				return response.Response("REMOTE SERVER ERROR", status=status.HTTP_503_SERVICE_UNAVAILABLE)

class FriendRequestByAuthorView(generics.ListAPIView):
	serializer_class = FriendRequestSerializer
	permission_classes = [permissions.IsAuthenticated]

	def get_queryset(self):
		result_list = FriendRequest.objects.filter(receiver=self.request.user.author)
		result_list = list(chain(result_list, FriendRequest.objects.filter(sender=self.request.user.author)))
		return result_list

class AcceptFriendRequestView(viewsets.ModelViewSet):
	serializer_class = AuthorNetworkSerializer
	permission_classes = [permissions.IsAuthenticated, my_permissions.IsOwnerForAccessAuthor]

	def get_queryset(self):
		result_list = FriendRequest.objects.filter(receiver=self.request.user.author)
		return result_list

	@detail_route(methods=['post'])
	def accept_request(self, request, **kwargs):
		receiver = request.user.author
		sender = get_object_or_404(Author, id=kwargs['pk'])
		friend_req = get_object_or_404(FriendRequest, sender=sender)
		friend_req.delete()
		receiver.authors.add(sender)
		post_visibilities = PostVisibility.objects.filter(post__author=receiver)
		for pv in post_visibilities:
			if pv.post.visibility == 'FRIENDS' or pv.post.visibility == 'FOAF':
				PostVisibility.objects.create(post=pv.post, author=sender)
				if pv.post.visibility == 'FOAF':
					for f in sender.authors:
						PostVisibility.objects.create(post=pv.post, author=f)
		return response.Response(status=status.HTTP_202_ACCEPTED)

	@detail_route(methods=['delete'])
	def reject_request(self, request, **kwargs):
		receiver = request.user.author
		sender = get_object_or_404(Author, id=kwargs['pk'])
		friend_req = get_object_or_404(FriendRequest, sender=sender)
		friend_req.delete()
		return response.Response(status=status.HTTP_202_ACCEPTED)

class UnfriendView(viewsets.ModelViewSet):
	serializer_class = AuthorNetworkSerializer
	permission_classes = [permissions.IsAuthenticated, my_permissions.IsOwnerForAccessAuthor]

	def get_queryset(self):
		result_list = FriendRequest.objects.filter(receiver=self.request.user.author)
		return result_list

	@detail_route(methods=['delete'])
	def unfriend(self, request, **kwargs):
		unfriender = request.user.author
		unfriended = get_object_or_404(Author, id=kwargs['pk'])
		unfriender.authors.remove(unfriended)
		return response.Response(status=status.HTTP_202_ACCEPTED)

class AuthorIsFriendListView(viewsets.ModelViewSet):
	queryset = Author.objects.all()
	serializer_class = AuthorFriendListSerializer

	def is_friend(self,request, *args, **kwargs):
		author1 = get_object_or_404(Author, id=kwargs['pk1'])
		author2 = get_object_or_404(Author, id=kwargs['pk2'])
		is_friend = False
		for friend in author1.authors.all():
			if str(friend.id) == str(author2.id):
				is_friend = True
		res = {
			'query': "friends",
			'authors': [str(author1.id), str(author2.id)],
			'friends': is_friend
		}
		return response.Response(res, status=status.HTTP_200_OK)
<commit_msg>all visibility cases are working<commit_after>import json
from _testcapi import raise_exception
from itertools import chain
import requests
from django.contrib.auth.models import User
from django.core import exceptions as django_exceptions
from django.http import QueryDict
from django.shortcuts import get_object_or_404
from requests.auth import HTTPBasicAuth
from rest_framework import generics, permissions, response, status, views
from rest_framework import viewsets
from rest_framework.decorators import detail_route
import uuid

from . import permissions as my_permissions
from .models import Author, FriendRequest, Node, PostVisibility
from .serializers import FullAuthorSerializer, AuthenticateSerializer, \
	UpdateAuthorSerializer, AuthorNetworkSerializer, AuthorSerializer, \
	FriendRequestSerializer, RemoteRequestSerializer, AuthorFriendListSerializer, AuthorFriendSpecialListSerializer

class AuthorListView(generics.ListAPIView):
	queryset = Author.objects.all()
	serializer_class = AuthorSerializer
	permission_classes = [permissions.IsAuthenticated, my_permissions.IsAdminOrIsLocalUser]

class AuthorCreateView(generics.CreateAPIView):
	queryset = Author.objects.all()
	serializer_class = FullAuthorSerializer
	permission_classes = [permissions.AllowAny]

class AuthorUpdateView(generics.UpdateAPIView):
	queryset = Author.objects.all()
	serializer_class = UpdateAuthorSerializer
	permission_classes = [permissions.IsAuthenticated, my_permissions.IsOwnerForModifyAuthor]

class AuthorRetrieveView(generics.RetrieveAPIView):
	queryset = Author.objects.all()
	serializer_class = AuthorSerializer
	permission_classes = [permissions.IsAuthenticated]

class AuthorAuthenticationView(views.APIView):
	queryset = Author.objects.all()
	serializer_class = AuthenticateSerializer

	def post(self, request):
		data = request.data
		serializer = AuthenticateSerializer(data=data)
		if serializer.is_valid(raise_exception=True):
			new_data = serializer.data
			return response.Response(new_data, status=status.HTTP_200_OK)
		return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class AuthorNetworkView(generics.RetrieveAPIView):
	queryset = Author.objects.all()
	serializer_class = AuthorNetworkSerializer

class AuthorFriendListView(viewsets.ModelViewSet):
	queryset = Author.objects.all()
	serializer_class = AuthorFriendListSerializer

	def retrieve(self, request, *args, **kwargs):
		self.serializer_class = AuthorFriendListSerializer
		instance = self.get_object()
		serializer = self.get_serializer(instance)
		data = serializer.data
		data['query'] = 'friends'
		return response.Response(data, status=status.HTTP_200_OK)

	def is_friend(self,request, *args, **kwargs):
		self.serializer_class = AuthorFriendSpecialListSerializer
		instance = self.get_object()
		serializer = self.get_serializer(instance)
		to_be_removed = []
		data = request.data
		count = 0
		for aid in data['authors']:
			is_friend = False
			for friend in instance.authors.all():
				if aid == str(friend.id):
					print aid + " is equals to " + str(friend.id)
					is_friend = True
				else:
					print aid + " is not equals to " + str(friend.id)

			if not is_friend:
				print aid + " and " + str(instance.id) + " are not friends at all."
				to_be_removed.append(count)
			count += 1
		for i in reversed(to_be_removed):
			print i
			data['authors'].pop(i)
		return response.Response(data['authors'], status=status.HTTP_200_OK)

class SendFriendRequestView(viewsets.ModelViewSet):
	serializer_class = AuthorNetworkSerializer

	def get_queryset(self):
		result_list = FriendRequest.objects.filter(receiver=self.request.user.author)
		return result_list

	@detail_route(methods=['post'])
	def send_request(self, request, **kwargs):
		try:
			author = request.user.author
			receiver = get_object_or_404(Author, id=kwargs['pk'])
			try:
				FriendRequest.objects.get(sender=author, receiver=author)
				return response.Response(status=status.HTTP_400_BAD_REQUEST)
			except django_exceptions.ObjectDoesNotExist:
				pass
			friendRequest = FriendRequest.objects.create(sender=author, receiver=receiver)
			friendRequest.save()
			return response.Response(status=status.HTTP_202_ACCEPTED)
		except AttributeError:
			return response.Response(status=status.HTTP_400_BAD_REQUEST)

class SendRemoteFriendRequestView(viewsets.ViewSet):
	serializer_class = RemoteRequestSerializer
	queryset = FriendRequest.objects.all()
	permission_classes = [permissions.IsAuthenticated]

	def send_to_remote(self, url, data, node):
		r = requests.post(url, json=data, auth=(node.rcred_username, node.rcred_password))
		return r

	def makeAuthor(self, data, node_url):
		print "Making author"
		id = data['id']
		displayNamesplit = data['displayName'].split(" ")
		username = displayNamesplit[0] + id[0:7]
		first_name = username
		last_name = username
		email = username + "@nousageemail.com"
		try:
			user = User.objects.create(username=username,
			                           first_name=first_name, last_name=last_name, email=email)
		except:
			return User.objects.get(username=username)
		author = Author.objects.create(user=user, id=uuid.UUID(id),
		                               displayName=str(data['displayName']), github="noGitHUB",
		                               host=node_url, url=node_url+"/author/"+id)
		return author

	@detail_route(methods=['post'])
	def send_request(self, request):
		# check if node is allowed. if not, 403
		try:
			try :
				data = json.loads(json.dumps(request.data))
				print data
				author_host = data['author']['host']
				friend_host = data['friend']['host']
				is_json = True
			except:
				author_host = str(request.data['author.host'])
				friend_host = str(request.data['friend.host'])
			try:
				author_host = author_host.split("/", 3)[2]
				friend_host = friend_host.split("/", 3)[2]
			except:
				pass
			node_author = Node.objects.get(node_url="http://"+author_host)
			node_friend = Node.objects.get(node_url="http://"+friend_host)
		except django_exceptions.ObjectDoesNotExist:
			return response.Response(status=status.HTTP_403_FORBIDDEN)
		# check if json is ok. if yes, get authors that are trying to be friends
		serializer = RemoteRequestSerializer(data=request.data)
		if serializer.is_valid(raise_exception=True):
			data = serializer.data
			try:
				author = Author.objects.get(id=data['author']['id'])
			except django_exceptions.ObjectDoesNotExist:
				author = self.makeAuthor(data['author'], node_author.node_url)
			try:
				friend = Author.objects.get(id=data['friend']['id'])
			except django_exceptions.ObjectDoesNotExist:
				friend = self.makeAuthor(data['friend'], node_friend.node_url)
			#check if there its for accept or not. if not, add the friend request
			try:
				friendRequest = FriendRequest.objects.get(sender=author, receiver=friend)
				friendRequest.delete()
				author.authors.add(friend)
				post_visibilities = PostVisibility.objects.filter(post__author=author)
				for pv in post_visibilities:
					if pv.post.visibility == 'FRIENDS' or pv.post.visibility == 'FOAF':
						PostVisibility.objects.create(post=pv.post, author=friend)
						if pv.post.visibility == 'FOAF':
							for f in friend.authors:
								PostVisibility.objects.create(post=pv.post, author=f)
				return response.Response(status=status.HTTP_202_ACCEPTED)
			except django_exceptions.ObjectDoesNotExist:
				try:
					FriendRequest.objects.get(sender=friend, receiver=author)
				except django_exceptions.ObjectDoesNotExist:
					FriendRequest.objects.create(sender=friend, receiver=author)
			try:
				data['query'] = 'friendrequest'
				res = self.send_to_remote(node_author.node_url+'/friendrequest', data, node_author)
				return response.Response(res, status=status.HTTP_200_OK)

			except:
				return response.Response("REMOTE SERVER ERROR", status=status.HTTP_503_SERVICE_UNAVAILABLE)

class FriendRequestByAuthorView(generics.ListAPIView):
	serializer_class = FriendRequestSerializer
	permission_classes = [permissions.IsAuthenticated]

	def get_queryset(self):
		result_list = FriendRequest.objects.filter(receiver=self.request.user.author)
		result_list = list(chain(result_list, FriendRequest.objects.filter(sender=self.request.user.author)))
		return result_list

class AcceptFriendRequestView(viewsets.ModelViewSet):
	serializer_class = AuthorNetworkSerializer
	permission_classes = [permissions.IsAuthenticated, my_permissions.IsOwnerForAccessAuthor]

	def get_queryset(self):
		result_list = FriendRequest.objects.filter(receiver=self.request.user.author)
		return result_list

	@detail_route(methods=['post'])
	def accept_request(self, request, **kwargs):
		receiver = request.user.author
		sender = get_object_or_404(Author, id=kwargs['pk'])
		friend_req = get_object_or_404(FriendRequest, sender=sender)
		friend_req.delete()
		receiver.authors.add(sender)
		post_visibilities = PostVisibility.objects.filter(post__author=receiver)
		for pv in post_visibilities:
			if pv.post.visibility == 'FRIENDS' or pv.post.visibility == 'FOAF':
				PostVisibility.objects.create(post=pv.post, author=sender)
				if pv.post.visibility == 'FOAF':
					for f in sender.authors:
						PostVisibility.objects.create(post=pv.post, author=f)
		return response.Response(status=status.HTTP_202_ACCEPTED)

	@detail_route(methods=['delete'])
	def reject_request(self, request, **kwargs):
		receiver = request.user.author
		sender = get_object_or_404(Author, id=kwargs['pk'])
		friend_req = get_object_or_404(FriendRequest, sender=sender)
		friend_req.delete()
		return response.Response(status=status.HTTP_202_ACCEPTED)

class UnfriendView(viewsets.ModelViewSet):
	serializer_class = AuthorNetworkSerializer
	permission_classes = [permissions.IsAuthenticated, my_permissions.IsOwnerForAccessAuthor]

	def get_queryset(self):
		result_list = FriendRequest.objects.filter(receiver=self.request.user.author)
		return result_list

	@detail_route(methods=['delete'])
	def unfriend(self, request, **kwargs):
		unfriender = request.user.author
		unfriended = get_object_or_404(Author, id=kwargs['pk'])
		unfriender.authors.remove(unfriended)
		return response.Response(status=status.HTTP_202_ACCEPTED)

class AuthorIsFriendListView(viewsets.ModelViewSet):
	queryset = Author.objects.all()
	serializer_class = AuthorFriendListSerializer

	def is_friend(self,request, *args, **kwargs):
		author1 = get_object_or_404(Author, id=kwargs['pk1'])
		author2 = get_object_or_404(Author, id=kwargs['pk2'])
		is_friend = False
		for friend in author1.authors.all():
			if str(friend.id) == str(author2.id):
				is_friend = True
		res = {
			'query': "friends",
			'authors': [str(author1.id), str(author2.id)],
			'friends': is_friend
		}
		return response.Response(res, status=status.HTTP_200_OK)
<|endoftext|>


<commit_before># vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Deal with the handling of tags for vimiv."""

import os

from gi.repository import Gtk, GLib
from vimiv.helpers import read_file, error_message

class TagHandler(object):
    """Handle tags.

    Attributes:
        app: The main vimiv application to interact with.
        directory: Directory in which tags are stored.
        last: Last tag that was loaded.
    """

    def __init__(self, app):
        """Create the necessary objects.

        Args:
            app: The main vimiv application to interact with.
        """
        self.app = app
        # Create tags directory
        self.directory = os.path.join(GLib.get_user_data_dir(), "vimiv", "Tags")
        os.makedirs(self.directory, exist_ok=True)
        # If there are tags in the old location, move them to the new one
        # TODO remove this in a new version, assigned for 0.10
        old_directory = os.path.expanduser("~/.vimiv/Tags")
        if os.path.isdir(old_directory):
            old_tags = os.listdir(old_directory)
            for f in old_tags:
                old_path = os.path.join(old_directory, f)
                new_path = os.path.join(self.directory, f)
                os.rename(old_path, new_path)
            message = "Moved tags from the old directory %s " \
                "to the new location %s." % (old_directory, self.directory)
            error_message(message, running_tests=self.app.running_tests)
            os.rmdir(old_directory)
        self.last = ""

    def read(self, tagname):
        """Read a tag and return the images in it.

        Args:
            tagname: Name of tag to operate on.

        Return:
            List of images in the tag called tagname.
        """
        tagfile_name = os.path.join(self.directory, tagname)
        tagged_images = read_file(tagfile_name)
        return tagged_images

    def write(self, imagelist, tagname):
        """Add a list of images to a tag.

        Args:
            imagelist: List of images to write to the tag.
            tagname: Name of tag to operate on.
        """
        # Backup required for tests
        imagelist = imagelist if imagelist else self.app["mark"].marked
        tagfile_name = os.path.join(self.directory, tagname)
        tagged_images = self.read(tagname)
        with open(tagfile_name, "a") as tagfile:
            for image in imagelist:
                if image not in tagged_images:
                    tagfile.write(image + "\n")

    def remove(self, tagname):
        """Remove a tag showing an error if the tag doesn't exist.

        Args:
            tagname: Name of tag to operate on.
        """
        tagfile_name = os.path.join(self.directory, tagname)
        if os.path.isfile(tagfile_name):
            os.remove(tagfile_name)
        else:
            err = "Tagfile '%s' does not exist" % (tagname)
            self.app["statusbar"].message(err, "error")

    def load(self, tagname):
        """Load all images in a tag as current filelist.

        Args:
            tagname: Name of tag to operate on.
        """
        os.chdir(self.directory)
        # Read file and get all tagged images as list
        tagged_images = self.read(tagname)
        # Populate filelist
        self.app.populate(tagged_images)
        if self.app.paths:
            self.app["main_window"].show()
            self.app["library"].set_hexpand(False)
            self.app["image"].load()
            # Focus in library if it is open
            if self.app["library"].grid.is_visible():
                self.app["library"].reload(self.directory)
                tag_pos = self.app["library"].files.index(tagname)
                self.app["library"].set_cursor(Gtk.TreePath(tag_pos),
                                               None, False)
            # Remember last tag selected
            self.last = tagname
        else:
            message = "Tagfile '%s' has no valid images" % (tagname)
            self.app["statusbar"].message(message, "error")
            self.last = ""
<commit_msg>Rework tags concerning private and public<commit_after># vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Deal with the handling of tags for vimiv."""

import os

from gi.repository import Gtk, GLib
from vimiv.helpers import read_file, error_message

class TagHandler(object):
    """Handle tags.

    Attributes:
        directory: Directory in which tags are stored.
        last: Last tag that was loaded.

        _app: The main vimiv application to interact with.
    """

    def __init__(self, app):
        """Create the necessary objects.

        Args:
            app: The main vimiv application to interact with.
        """
        self._app = app
        # Create tags directory
        self.directory = os.path.join(GLib.get_user_data_dir(), "vimiv", "Tags")
        os.makedirs(self.directory, exist_ok=True)
        # If there are tags in the old location, move them to the new one
        # TODO remove this in a new version, assigned for 0.10
        old_directory = os.path.expanduser("~/.vimiv/Tags")
        if os.path.isdir(old_directory):
            old_tags = os.listdir(old_directory)
            for f in old_tags:
                old_path = os.path.join(old_directory, f)
                new_path = os.path.join(self.directory, f)
                os.rename(old_path, new_path)
            message = "Moved tags from the old directory %s " \
                "to the new location %s." % (old_directory, self.directory)
            error_message(message, running_tests=self._app.running_tests)
            os.rmdir(old_directory)
        self.last = ""

    def write(self, imagelist, tagname):
        """Add a list of images to a tag.

        Args:
            imagelist: List of images to write to the tag.
            tagname: Name of tag to operate on.
        """
        # Backup required for tests
        imagelist = imagelist if imagelist else self._app["mark"].marked
        tagfile_name = os.path.join(self.directory, tagname)
        tagged_images = self._read(tagname)
        with open(tagfile_name, "a") as tagfile:
            for image in imagelist:
                if image not in tagged_images:
                    tagfile.write(image + "\n")

    def remove(self, tagname):
        """Remove a tag showing an error if the tag doesn't exist.

        Args:
            tagname: Name of tag to operate on.
        """
        tagfile_name = os.path.join(self.directory, tagname)
        if os.path.isfile(tagfile_name):
            os.remove(tagfile_name)
        else:
            err = "Tagfile '%s' does not exist" % (tagname)
            self._app["statusbar"].message(err, "error")

    def load(self, tagname):
        """Load all images in a tag as current filelist.

        Args:
            tagname: Name of tag to operate on.
        """
        os.chdir(self.directory)
        # Read file and get all tagged images as list
        tagged_images = self._read(tagname)
        # Populate filelist
        self._app.populate(tagged_images)
        if self._app.paths:
            self._app["main_window"].show()
            self._app["library"].set_hexpand(False)
            self._app["image"].load()
            # Focus in library if it is open
            if self._app["library"].grid.is_visible():
                self._app["library"].reload(self.directory)
                tag_pos = self._app["library"].files.index(tagname)
                self._app["library"].set_cursor(Gtk.TreePath(tag_pos),
                                                None, False)
            # Remember last tag selected
            self.last = tagname
        else:
            message = "Tagfile '%s' has no valid images" % (tagname)
            self._app["statusbar"].message(message, "error")
            self.last = ""

    def _read(self, tagname):
        """Read a tag and return the images in it.

        Args:
            tagname: Name of tag to operate on.

        Return:
            List of images in the tag called tagname.
        """
        tagfile_name = os.path.join(self.directory, tagname)
        tagged_images = read_file(tagfile_name)
        return tagged_images
<|endoftext|>


<commit_before>from typing import Dict

from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.tasks.metadata_etl import MetadataSingleEntityTransformTask
from cumulusci.utils.xml.metadata_tree import MetadataElement
from cumulusci.core.utils import process_bool_arg, process_list_arg

class AddPicklistEntries(MetadataSingleEntityTransformTask):
    entity = "CustomObject"
    task_options = {
        "picklists": {
            "description": "List of picklists to affect, in Object__c.Field__c form.",
            "required": True,
        },
        "entries": {
            "description": "Array of picklist values to insert. "
            "Each value should contain the keys 'fullName', the API name of the entry, "
            "and 'label', the user-facing label. Optionally, specify 'default` on exactly one "
            "entry to make that value the default.",
            "required": True,
        },
        "record_types": {
            "description": "List of Record Type developer names for which the new values "
            "should be available. Any Record Types not present in the target org will be "
            "ignored, and * is a wildcard. Default behavior is to do nothing."
        },
        "sort_values": {"description": "Sort the picklist values alphabetically."},
        "force_last": {
            "description": "Require a specific value to appear last in the list."
        },
        **MetadataSingleEntityTransformTask.task_options,
    }

    def _init_options(self, kwargs):
        self.task_config.options["api_names"] = "dummy"
        super()._init_options(kwargs)

        self.picklists = {}
        for pl in self.options["picklists"]:
            obj, field = pl.split(".")
            if None in [obj, field]:
                raise TaskOptionsError(
                    f"Picklist {pl} is not a valid Object.Field reference"
                )
            if not field.endswith("__c"):
                raise TaskOptionsError(
                    "This task only supports custom fields. To modify "
                    "Standard Value Sets, use the add_standard_value_set_entries task."
                )

            self.picklists.setdefault(self._inject_namespace(obj), []).append(
                self._inject_namespace(field)
            )

        if not all(["fullName" in entry for entry in self.options["entries"]]):
            raise TaskOptionsError(
                "The 'fullName' key is required on all picklist values."
            )

        if (
            len(
                list(
                    x
                    for x in self.options["entries"]
                    if process_bool_arg(x.get("default", False))
                )
            )
            > 1
        ):
            raise TaskOptionsError("Only one default picklist value is allowed.")

        self.options["sort_values"] = process_bool_arg(
            self.options.get("sort_values", False)
        )
        self.options["record_types"] = process_list_arg(
            self.options.get("record_types", [])
        )

        self.api_names = set(self.picklists.keys())

    def _deploy(self):
        raise Exception

    def _transform_entity(self, metadata: MetadataElement, api_name: str):
        for pl in self.picklists[api_name]:
            self._modify_picklist(metadata, api_name, pl)

    def _modify_picklist(self, metadata: MetadataElement, api_name: str, picklist: str):
        # Locate the <fields> entry for this picklist.
        field = metadata.find("fields", fullName=picklist)

        if not field:
            raise TaskOptionsError(f"The field {api_name}.{picklist} was not found.")

        vsd = field.valueSet.valueSetDefinition  # TODO: clamp API > 38

        for entry in self.options["entries"]:
            self._add_picklist_field_entry(vsd, api_name, picklist, entry)

            if self.options["record_types"]:
                self._add_record_type_entries(metadata, api_name, picklist, entry)

        if self.options["sort_values"] and not self.options.get("force_last"):
            vsd.sorted.text = "true"
        elif self.options["sort_values"]:
            # Manually sort values so that we can apply force_last
            pass  # TODO

    def _add_picklist_field_entry(
        self, vsd: MetadataElement, api_name: str, picklist: str, entry: Dict
    ):
        fullName = entry["fullName"]
        label = entry.get("label") or fullName
        default = entry.get("default", False)

        if vsd.find("value", fullName=fullName):
            self.logger.warning(
                f"Picklist entry with fullName {fullName} already exists on picklist {picklist}"
            )
        else:
            entry_element = vsd.append("value")
            entry_element.append("fullName", text=fullName)
            entry_element.append("label", text=label)
            entry_element.append(
                "default", text=str(default).lower()
            )  # TODO: enforce one default value

    def _add_record_type_entries(
        self, metadata: MetadataElement, api_name: str, picklist: str, entry: Dict
    ):
        for record_type in self.options["record_types"]:
            rt_element = metadata.find("recordTypes", fullName=record_type)

            # Silently ignore record types that don't exist in the target org.
            if rt_element:
                # Locate, or add, the root picklistValues element for this picklist.
                picklist_element = rt_element.find(
                    "picklistValues", picklist=picklist
                ) or rt_element.append("picklistValues")
                if not picklist_element.find("picklist", text=picklist):
                    picklist_element.append("picklist", text=picklist)

                # If this picklist value entry is not already present, add it.
                if not picklist_element.find("values", fullName=entry["fullName"]):
                    values = picklist_element.append("values")
                    values.append("fullName", text=entry["fullName"])

                # If this picklist value needs to be made default, do so, and remove any existing default.
                if process_bool_arg(entry.get("default", False)):
                    # Find existing default and remove it.

                    for value in picklist_element.values:
                        value.default.text = (
                            "false"
                            if value.fullName.text != entry["fullName"]
                            else "true"
                        )
<commit_msg>Complete Picklist Values ETL task<commit_after>from typing import Dict

from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.tasks.metadata_etl import MetadataSingleEntityTransformTask
from cumulusci.utils.xml.metadata_tree import MetadataElement
from cumulusci.core.utils import process_bool_arg, process_list_arg

class AddPicklistEntries(MetadataSingleEntityTransformTask):
    entity = "CustomObject"
    task_options = {
        "picklists": {
            "description": "List of picklists to affect, in Object__c.Field__c form.",
            "required": True,
        },
        "entries": {
            "description": "Array of picklist values to insert. "
            "Each value should contain the keys 'fullName', the API name of the entry, "
            "and 'label', the user-facing label. Optionally, specify 'default` on exactly one "
            "entry to make that value the default.",
            "required": True,
        },
        "record_types": {
            "description": "List of Record Type developer names for which the new values "
            "should be available. Any Record Types not present in the target org will be "
            "ignored, and * is a wildcard. Default behavior is to do nothing."
        },
        "sorted": {"description": "Sort the picklist values alphabetically."},
        **MetadataSingleEntityTransformTask.task_options,
    }

    def _init_options(self, kwargs):
        self.task_config.options["api_names"] = "dummy"
        super()._init_options(kwargs)

        try:
            if float(self.api_version) < 38.0:
                raise TaskOptionsError("This task requires API version 38.0 or later.")
        except ValueError:
            raise TaskOptionsError(f"Invalid API version {self.api_version}")

        self.picklists = {}
        for pl in process_list_arg(self.options["picklists"]):
            try:
                obj, field = pl.split(".")
            except ValueError:
                raise TaskOptionsError(
                    f"Picklist {pl} is not a valid Object.Field reference"
                )
            if not field.endswith("__c"):
                raise TaskOptionsError(
                    "This task only supports custom fields. To modify "
                    "Standard Value Sets, use the add_standard_value_set_entries task."
                )

            self.picklists.setdefault(self._inject_namespace(obj), []).append(
                self._inject_namespace(field)
            )

        if not all(["fullName" in entry for entry in self.options["entries"]]):
            raise TaskOptionsError(
                "The 'fullName' key is required on all picklist values."
            )

        if (
            sum(
                1
                for x in self.options["entries"]
                if process_bool_arg(x.get("default", False))
            )
            > 1
        ):
            raise TaskOptionsError("Only one default picklist value is allowed.")

        self.options["sorted"] = process_bool_arg(self.options.get("sorted", False))
        self.options["record_types"] = [
            self._inject_namespace(x)
            for x in process_list_arg(self.options.get("record_types", []))
        ]

        self.api_names = set(self.picklists.keys())

    def _transform_entity(self, metadata: MetadataElement, api_name: str):
        for pl in self.picklists[api_name]:
            self._modify_picklist(metadata, api_name, pl)

        return metadata

    def _modify_picklist(self, metadata: MetadataElement, api_name: str, picklist: str):
        # Locate the <fields> entry for this picklist.
        field = metadata.find("fields", fullName=picklist)

        if not field:
            raise TaskOptionsError(f"The field {api_name}.{picklist} was not found.")

        vsd = field.valueSet.valueSetDefinition

        # Update each entry in this picklist, and also add to all record types.
        for entry in self.options["entries"]:
            self._add_picklist_field_entry(vsd, api_name, picklist, entry)

            if self.options["record_types"]:
                self._add_record_type_entries(metadata, api_name, picklist, entry)

        # Set the sorted value for this picklist
        if self.options["sorted"]:
            sorted_elem = vsd.find("sorted") or vsd.append("sorted")
            sorted_elem.text = "true"

    def _add_picklist_field_entry(
        self, vsd: MetadataElement, api_name: str, picklist: str, entry: Dict
    ):
        fullName = entry["fullName"]
        label = entry.get("label") or fullName
        default = entry.get("default", False)

        if vsd.find("value", fullName=fullName):
            self.logger.warning(
                f"Picklist entry with fullName {fullName} already exists on picklist {picklist}"
            )
        else:
            entry_element = vsd.append("value")
            entry_element.append("fullName", text=fullName)
            entry_element.append("label", text=label)
            entry_element.append("default", text=str(default).lower())

        # If we're setting this as the default, unset all of the other entries.
        if default:
            for value in vsd.findall("value"):
                default = value.find("default")
                if default:
                    default.text = (
                        "false" if value.fullName.text != fullName else "true"
                    )

    def _add_record_type_entries(
        self, metadata: MetadataElement, api_name: str, picklist: str, entry: Dict
    ):
        if "*" in self.options["record_types"]:
            rt_list = metadata.findall("recordTypes")
        else:
            rt_list = [
                metadata.find("recordTypes", fullName=record_type)
                for record_type in self.options["record_types"]
            ]

        for rt_element in rt_list:
            # Silently ignore record types that don't exist in the target org.
            if rt_element:
                self._add_single_record_type_entries(
                    rt_element, api_name, picklist, entry
                )

    def _add_single_record_type_entries(
        self, rt_element: MetadataElement, api_name: str, picklist: str, entry: Dict
    ):
        # Locate, or add, the root picklistValues element for this picklist.
        picklist_element = rt_element.find(
            "picklistValues", picklist=picklist
        ) or rt_element.append("picklistValues")
        if not picklist_element.find("picklist", text=picklist):
            picklist_element.append("picklist", text=picklist)

        # If this picklist value entry is not already present, add it.
        if not picklist_element.find("values", fullName=entry["fullName"]):
            values = picklist_element.append("values")
            values.append("fullName", text=entry["fullName"])

        # If this picklist value needs to be made default, do so, and remove any existing default.
        if process_bool_arg(entry.get("default", False)):
            # Find existing default and remove it.

            for value in picklist_element.values:
                default = value.find("default")
                if default:
                    default.text = (
                        "false" if value.fullName.text != entry["fullName"] else "true"
                    )
<|endoftext|>


<commit_before>from django.test import TestCase
from corehq.apps.commtrack.tests.util import bootstrap_domain, make_loc
from custom.ewsghana.handler import handle
from custom.ewsghana.utils import bootstrap_user

TEST_DOMAIN = 'ews-handler-test'

class HandlerTest(TestCase):

    def setUp(self):
        super(HandlerTest, self).setUp()
        domain = bootstrap_domain(TEST_DOMAIN)
        loc = make_loc(code="garms", name="Test RMS", type="Regional Medical Store", domain=domain.name)
        self.user = bootstrap_user(username='testuser', phone_number='323232', domain=domain.name, home_loc=loc)

    def test_not_ews_domain(self):
        self.assertFalse(handle(self.user.get_verified_number(), "soh dp 40.0", None))
        self.assertFalse(handle(self.user.get_verified_number(), "dp 40.0", None))
<commit_msg>Fix test<commit_after>from corehq.apps.commtrack.tests.util import bootstrap_domain, make_loc
from corehq.apps.domain.models import Domain
from corehq.apps.sms.api import incoming
from corehq.apps.sms.tests.util import delete_domain_phone_numbers, BaseSMSTest, setup_default_sms_test_backend
from custom.ewsghana.handler import handle
from custom.ewsghana.utils import bootstrap_user
from mock import patch

def get_handle_wrapper(result_dict):
    def inner(*args, **kwargs):
        result_dict['result'] = handle(*args, **kwargs)
        return result_dict['result']

    return inner

class HandlerTest(BaseSMSTest):

    def setUp(self):
        super(HandlerTest, self).setUp()
        self.backend, self.backend_mapping = setup_default_sms_test_backend()
        self.domain = 'ews-handler-test'
        bootstrap_domain(self.domain)
        self.create_account_and_subscription(self.domain)
        self.domain_obj = Domain.get_by_name(self.domain)
        self.loc = make_loc(code="garms", name="Test RMS", type="Regional Medical Store", domain=self.domain)
        self.user = bootstrap_user(username='testuser', phone_number='323232', domain=self.domain, home_loc=self.loc)

    def tearDown(self):
        delete_domain_phone_numbers(self.domain)
        self.backend.delete()
        self.backend_mapping.delete()
        super(HandlerTest, self).tearDown()

    def _test_pass_through_ews_handler(self, phone_number, message):
        result_dict = {}
        with patch('custom.ewsghana.handler.handle', new=get_handle_wrapper(result_dict)):
            incoming(phone_number, message, 'TEST')
            self.assertFalse(result_dict['result'])

    def test_non_ews_traffic(self):
        # Test that messages from numbers registered to non-ews domains do not get processed by ews
        self._test_pass_through_ews_handler('323232', 'soh dp 40.0')
        self._test_pass_through_ews_handler('323232', 'dp 40.0')
<|endoftext|>


<commit_before>#!/usr/bin/env python3

import os, sys
import json

ref, output = sys.argv[1:]
if not ref.startswith('refs/heads/'):
  print(ref, 'is not a branch')
  sys.exit(0)
branch = ref.split('/')[-1]

print('loaded', branch, '=>', output)

loaded = []
for job in [1, 2]:
  job = f'logs/loaded-zotero-{job}-{branch}.json'
  if not os.path.exists(job):
    print('not found:', job)
    sys.exit(0)
  loaded += json.load(job)

with open(output, 'w') as f:
  json.dump(sorted(loaded), f, indent='  ')
print(f"::set-output name=loaded::{output}")
<commit_msg>x perm<commit_after>#!/usr/bin/env python3

import os, sys
import json

ref, output = sys.argv[1:]
if not ref.startswith('refs/heads/'):
  print(ref, 'is not a branch')
  sys.exit(0)
branch = ref.split('/')[-1]

print('loaded', branch, '=>', output)

loaded = []
for job in [1, 2]:
  job = f'logs/loaded-zotero-{job}-{branch}.json'
  if not os.path.exists(job):
    print('not found:', job)
    sys.exit(0)
  loaded += json.load(job)

with open(output, 'w') as f:
  json.dump(sorted(loaded), f, indent='  ')
print(f"::set-output name=loaded::{output}")
<|endoftext|>


<commit_before>import requests
import time as Time
import threading

from forecastio.models import Forecast

def load_forecast(key, inLat, inLong, time=None, units="auto", lazy=False,
                  callback=None):
    """
        This function builds the request url and loads some or all of the
        needed json depending on lazy is True

        inLat:  The latitude of the forecast
        inLong: The longitude of the forecast
        time:   A datetime.datetime object representing the desired time of
                the forecast
        units:  A string of the preferred units of measurement, "auto" id
                default. also us,ca,uk,si is available
        lazy:   Defaults to false.  The function will only request the json
                data as it is needed. Results in more requests, but
                probably a faster response time (I haven't checked)
    """

    lat = inLat
    lng = inLong
    time = time

    if time is None:
        url = 'https://api.forecast.io/forecast/%s/%s,%s' \
              '?units=%s' % (key, lat, lng, units,)
    else:
        url_time = str(int(Time.mktime(time.timetuple())))
        url = 'https://api.forecast.io/forecast/%s/%s,%s,%s' \
              '?units=%s' % (key, lat, lng, url_time,
              units,)

    if lazy is True:
        baseURL = "%s&exclude=%s" % (url,
                                     'minutely,currently,hourly,'
                                     'daily,alerts,flags')
    else:
        baseURL = url

    return manual(baseURL, callback=callback)

def manual(requestURL, callback=None):
    if callback is None:
        return get_forecast(requestURL)
    else:
        thread = threading.Thread(target=load_async,
                                  args=(requestURL, callback))
        thread.start()

def get_forecast(requestURL):
    forecastio_reponse = requests.get(requestURL)

    json = forecastio_reponse.json()
    headers = forecastio_reponse.headers

    return Forecast(json, forecastio_reponse, headers)

def load_async(url, callback):
    callback(get_forecast(url))
<commit_msg>Removed useless code.<commit_after>import requests
import time as Time
import threading

from forecastio.models import Forecast

def load_forecast(key, lat, lng, time=None, units="auto", lazy=False,
                  callback=None):
    """
        This function builds the request url and loads some or all of the
        needed json depending on lazy is True

        inLat:  The latitude of the forecast
        inLong: The longitude of the forecast
        time:   A datetime.datetime object representing the desired time of
                the forecast
        units:  A string of the preferred units of measurement, "auto" id
                default. also us,ca,uk,si is available
        lazy:   Defaults to false.  The function will only request the json
                data as it is needed. Results in more requests, but
                probably a faster response time (I haven't checked)
    """

    if time is None:
        url = 'https://api.forecast.io/forecast/%s/%s,%s' \
              '?units=%s' % (key, lat, lng, units,)
    else:
        url_time = str(int(Time.mktime(time.timetuple())))
        url = 'https://api.forecast.io/forecast/%s/%s,%s,%s' \
              '?units=%s' % (key, lat, lng, url_time,
              units,)

    if lazy is True:
        baseURL = "%s&exclude=%s" % (url,
                                     'minutely,currently,hourly,'
                                     'daily,alerts,flags')
    else:
        baseURL = url

    return manual(baseURL, callback=callback)

def manual(requestURL, callback=None):
    if callback is None:
        return get_forecast(requestURL)
    else:
        thread = threading.Thread(target=load_async,
                                  args=(requestURL, callback))
        thread.start()

def get_forecast(requestURL):
    forecastio_reponse = requests.get(requestURL)

    json = forecastio_reponse.json()
    headers = forecastio_reponse.headers

    return Forecast(json, forecastio_reponse, headers)

def load_async(url, callback):
    callback(get_forecast(url))
<|endoftext|>