<commit_before># Settings for www.djangoproject.com

import os
import platform
from unipath import FSPath as Path

# The full path to the django_website directory.
BASE = Path(__file__).absolute().ancestor(2)

# Far too clever trick to know if we're running on the deployment server.
PRODUCTION = ('DJANGOPROJECT_DEBUG' not in os.environ) and ("djangoproject" in platform.node())

ADMINS = (('Adrian Holovaty','holovaty@gmail.com'),('Jacob Kaplan-Moss', 'jacob@jacobian.org'))
MANAGERS = (('Jacob Kaplan-Moss','jacob@jacobian.org'),)
TIME_ZONE = 'America/Chicago'
SERVER_EMAIL = 'root@djangoproject.com'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'djangoproject',
        'USER': 'djangoproject'
    }
}

USE_I18N = False
USE_L10N = False

TEMPLATE_DIRS = [BASE.child('templates')]
MEDIA_ROOT = BASE.parent.child('media')

if PRODUCTION:
    DEBUG = False
    PREPEND_WWW = True
    CACHE_BACKEND = 'memcached://127.0.0.1:11211/'
    MEDIA_URL = "http://www.djangoproject.com.com/m/"
    ADMIN_MEDIA_PREFIX = "http://www.djangoproject.com.com/m/admin/"
else:
    DEBUG = True
    PREPEND_WWW = False
    CACHE_BACKEND = "dummy:///"
    MEDIA_URL = "/media/"
    ADMIN_MEDIA_PREFIX = '/admin_media/'
    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

SITE_ID = 1
ROOT_URLCONF = 'django_website.urls.www'
INSTALLED_APPS = (
    'django.contrib.sites',
    'django.contrib.auth',
    'django.contrib.admin',
    'django.contrib.comments',
    'django.contrib.contenttypes',
    'django.contrib.flatpages',
    'django.contrib.humanize',
    'django.contrib.redirects',
    'django.contrib.sessions',
    'django.contrib.sitemaps',
    'django_website.blog',
    'django_website.aggregator',
    'django_website.docs',
    'registration',
)

CACHE_MIDDLEWARE_SECONDS = 60 * 5 # 5 minutes
CACHE_MIDDLEWARE_KEY_PREFIX = 'djangoproject'
CACHE_MIDDLEWARE_GZIP = True
CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True

MIDDLEWARE_CLASSES = (
    'django.middleware.cache.UpdateCacheMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
    'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',
)
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
)
TEMPLATE_CONTEXT_PROCESSORS = [
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
]

DEFAULT_FROM_EMAIL = "noreply@djangoproject.com"

# django-registration settings
ACCOUNT_ACTIVATION_DAYS = 3

# comment_utils settings
AKISMET_API_KEY = "c892e4962244"

# setting for documentation root path
DJANGO_DOCUMENT_ROOT_PATH = "/home/html/djangoproject.com/docs/"
DJANGO_TESTS_PATH = "/home/html/djangoproject.com/tests/"

# XXX What's this for?
DJANGO_SVN_ROOT = "http://code.djangoproject.com/svn/django/"
<commit_msg>Temporarily change the media URLs for the new server.<commit_after># Settings for www.djangoproject.com

import os
import platform
from unipath import FSPath as Path

# The full path to the django_website directory.
BASE = Path(__file__).absolute().ancestor(2)

# Far too clever trick to know if we're running on the deployment server.
PRODUCTION = ('DJANGOPROJECT_DEBUG' not in os.environ) and ("djangoproject" in platform.node())

ADMINS = (('Adrian Holovaty','holovaty@gmail.com'),('Jacob Kaplan-Moss', 'jacob@jacobian.org'))
MANAGERS = (('Jacob Kaplan-Moss','jacob@jacobian.org'),)
TIME_ZONE = 'America/Chicago'
SERVER_EMAIL = 'root@djangoproject.com'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'djangoproject',
        'USER': 'djangoproject'
    }
}

USE_I18N = False
USE_L10N = False

TEMPLATE_DIRS = [BASE.child('templates')]
MEDIA_ROOT = BASE.parent.child('media')

if PRODUCTION:
    DEBUG = False
    PREPEND_WWW = True
    CACHE_BACKEND = 'memcached://127.0.0.1:11211/'
    MEDIA_URL = "http://www.ve.djangoproject.com/m/"
    ADMIN_MEDIA_PREFIX = "http://www.ve.djangoproject.com/m/admin/"
else:
    DEBUG = True
    PREPEND_WWW = False
    CACHE_BACKEND = "dummy:///"
    MEDIA_URL = "/media/"
    ADMIN_MEDIA_PREFIX = '/admin_media/'
    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

SITE_ID = 1
ROOT_URLCONF = 'django_website.urls.www'
INSTALLED_APPS = (
    'django.contrib.sites',
    'django.contrib.auth',
    'django.contrib.admin',
    'django.contrib.comments',
    'django.contrib.contenttypes',
    'django.contrib.flatpages',
    'django.contrib.humanize',
    'django.contrib.redirects',
    'django.contrib.sessions',
    'django.contrib.sitemaps',
    'django_website.blog',
    'django_website.aggregator',
    'django_website.docs',
    'registration',
)

CACHE_MIDDLEWARE_SECONDS = 60 * 5 # 5 minutes
CACHE_MIDDLEWARE_KEY_PREFIX = 'djangoproject'
CACHE_MIDDLEWARE_GZIP = True
CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True

MIDDLEWARE_CLASSES = (
    'django.middleware.cache.UpdateCacheMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
    'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',
)
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
)
TEMPLATE_CONTEXT_PROCESSORS = [
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
]

DEFAULT_FROM_EMAIL = "noreply@djangoproject.com"

# django-registration settings
ACCOUNT_ACTIVATION_DAYS = 3

# comment_utils settings
AKISMET_API_KEY = "c892e4962244"

# setting for documentation root path
DJANGO_DOCUMENT_ROOT_PATH = "/home/html/djangoproject.com/docs/"
DJANGO_TESTS_PATH = "/home/html/djangoproject.com/tests/"

# XXX What's this for?
DJANGO_SVN_ROOT = "http://code.djangoproject.com/svn/django/"
<|endoftext|>


<commit_before>import logging
import urllib

from django.conf import settings
from django.core.context_processors import csrf
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse
from django.shortcuts import redirect
from mitxmako.shortcuts import render_to_response, render_to_string
#from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.cache import cache_control

from lxml import etree

from module_render import render_module, make_track_function
from models import StudentModule
from student.models import UserProfile

import courseware.content_parser as content_parser
import courseware.modules

import courseware.grades as grades

log = logging.getLogger("mitx.courseware")

etree.set_default_parser(etree.XMLParser(dtd_validation=False, load_dtd=False,
                                         remove_comments = True))

template_imports={'urllib':urllib}

@cache_control(no_cache=True, no_store=True, must_revalidate=True)
def gradebook(request):
    if 'course_admin' not in content_parser.user_groups(request.user):
        raise Http404
    student_objects = User.objects.all()[:100]
    student_info = [{'username' :s.username,
                     'id' : s.id,
                     'email': s.email,
                     'grade_info' : grades.grade_sheet(s),
                     'realname' : UserProfile.objects.get(user = s).name
                     } for s in student_objects]

    return render_to_response('gradebook.html',{'students':student_info})

@login_required
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
def profile(request, student_id = None):
    ''' User profile. Show username, location, etc, as well as grades .
        We need to allow the user to change some of these settings .'''

    if student_id == None:
        student = request.user
    else:
        print content_parser.user_groups(request.user)
        if 'course_admin' not in content_parser.user_groups(request.user):
            raise Http404
        student = User.objects.get( id = int(student_id))

    user_info = UserProfile.objects.get(user=student) # request.user.profile_cache #

    context={'name':user_info.name,
             'username':student.username,
             'location':user_info.location,
             'language':user_info.language,
             'email':student.email,
             'format_url_params' : content_parser.format_url_params,
             'csrf':csrf(request)['csrf_token']
             }
    context.update(grades.grade_sheet(student))

    return render_to_response('profile.html', context)

def render_accordion(request,course,chapter,section):
    ''' Draws navigation bar. Takes current position in accordion as
        parameter. Returns (initialization_javascript, content)'''
    if not course:
        course = "6.002 Spring 2012"

    toc=content_parser.toc_from_xml(content_parser.course_file(request.user), chapter, section)
    active_chapter=1
    for i in range(len(toc)):
        if toc[i]['active']:
            active_chapter=i
    context=dict([['active_chapter',active_chapter],
                  ['toc',toc],
                  ['course_name',course],
                  ['format_url_params',content_parser.format_url_params],
                  ['csrf',csrf(request)['csrf_token']]] + \
                     template_imports.items())
    return render_to_string('accordion.html',context)

@cache_control(no_cache=True, no_store=True, must_revalidate=True)
def render_section(request, section):
    ''' TODO: Consolidate with index
    '''
    user = request.user
    if not settings.COURSEWARE_ENABLED:
        return redirect('/')

#    try:
    dom = content_parser.section_file(user, section)
    #except:
     #   raise Http404

    accordion=render_accordion(request, '', '', '')

    module_ids = dom.xpath("//@id")

    if user.is_authenticated():
        module_object_preload = list(StudentModule.objects.filter(student=user,
                                                                  module_id__in=module_ids))
    else:
        module_object_preload = []

    module=render_module(user, request, dom, module_object_preload)

    if 'init_js' not in module:
        module['init_js']=''

    context={'init':module['init_js'],
             'accordion':accordion,
             'content':module['content'],
             'csrf':csrf(request)['csrf_token']}

    result = render_to_response('courseware.html', context)
    return result

@cache_control(no_cache=True, no_store=True, must_revalidate=True)
def index(request, course="6.002 Spring 2012", chapter="Using the System", section="Hints"):
    ''' Displays courseware accordion, and any associated content.
    '''
    user = request.user
    if not settings.COURSEWARE_ENABLED:
        return redirect('/')

    # Fixes URLs -- we don't get funny encoding characters from spaces
    # so they remain readable
    ## TODO: Properly replace underscores
    course=course.replace("_"," ")
    chapter=chapter.replace("_"," ")
    section=section.replace("_"," ")

    # HACK: Force course to 6.002 for now
    # Without this, URLs break
    if course!="6.002 Spring 2012":
        return redirect('/')

    #import logging
    #log = logging.getLogger("mitx")
    #log.info(  "DEBUG: "+str(user) )

    dom = content_parser.course_file(user)
    dom_module = dom.xpath("//course[@name=$course]/chapter[@name=$chapter]//section[@name=$section]/*[1]",
                           course=course, chapter=chapter, section=section)
    if len(dom_module) == 0:
        module = None
    else:
        module = dom_module[0]

    accordion=render_accordion(request, course, chapter, section)

    module_ids = dom.xpath("//course[@name=$course]/chapter[@name=$chapter]//section[@name=$section]//@id",
                           course=course, chapter=chapter, section=section)

    if user.is_authenticated():
        module_object_preload = list(StudentModule.objects.filter(student=user,
                                                                  module_id__in=module_ids))
    else:
        module_object_preload = []

    module=render_module(user, request, module, module_object_preload)

    if 'init_js' not in module:
        module['init_js']=''

    context={'init':module['init_js'],
             'accordion':accordion,
             'content':module['content'],
             'csrf':csrf(request)['csrf_token']}

    result = render_to_response('courseware.html', context)
    return result

def modx_dispatch(request, module=None, dispatch=None, id=None):
    ''' Generic view for extensions. '''
    if not request.user.is_authenticated():
        return redirect('/')

    # Grab the student information for the module from the database
    s = StudentModule.objects.filter(student=request.user,
                                     module_id=id)
    #s = StudentModule.get_with_caching(request.user, id)
    if len(s) == 0 or s is None:
        log.debug("Couldnt find module for user and id " + str(module) + " " + str(request.user) + " "+ str(id))
        raise Http404
    s = s[0]

    oldgrade = s.grade
    oldstate = s.state

    dispatch=dispatch.split('?')[0]

    ajax_url = settings.MITX_ROOT_URL + '/modx/'+module+'/'+id+'/'

    # Grab the XML corresponding to the request from course.xml
    xml = content_parser.module_xml(request.user, module, 'id', id)

    # Create the module
    system = I4xSystem(track_function = make_track_function(request),
                       render_function = None,
                       ajax_url = ajax_url,
                       filestore = None
                       )
    instance=courseware.modules.get_module_class(module)(system,
                                                         xml,
                                                         id,
                                                         state=oldstate)
    # Let the module handle the AJAX
    ajax_return=instance.handle_ajax(dispatch, request.POST)
    # Save the state back to the database
    s.state=instance.get_state()
    if instance.get_score():
        s.grade=instance.get_score()['score']
    if s.grade != oldgrade or s.state != oldstate:
        s.save()
    # Return whatever the module wanted to return to the client/caller
    return HttpResponse(ajax_return)
<commit_msg>Fixed bad merge between Cale and Piotr/I4xSystem missing reference<commit_after>import logging
import urllib

from django.conf import settings
from django.core.context_processors import csrf
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse
from django.shortcuts import redirect
from mitxmako.shortcuts import render_to_response, render_to_string
#from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.cache import cache_control

from lxml import etree

from module_render import render_module, make_track_function, I4xSystem
from models import StudentModule
from student.models import UserProfile

import courseware.content_parser as content_parser
import courseware.modules

import courseware.grades as grades

log = logging.getLogger("mitx.courseware")

etree.set_default_parser(etree.XMLParser(dtd_validation=False, load_dtd=False,
                                         remove_comments = True))

template_imports={'urllib':urllib}

@cache_control(no_cache=True, no_store=True, must_revalidate=True)
def gradebook(request):
    if 'course_admin' not in content_parser.user_groups(request.user):
        raise Http404
    student_objects = User.objects.all()[:100]
    student_info = [{'username' :s.username,
                     'id' : s.id,
                     'email': s.email,
                     'grade_info' : grades.grade_sheet(s),
                     'realname' : UserProfile.objects.get(user = s).name
                     } for s in student_objects]

    return render_to_response('gradebook.html',{'students':student_info})

@login_required
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
def profile(request, student_id = None):
    ''' User profile. Show username, location, etc, as well as grades .
        We need to allow the user to change some of these settings .'''

    if student_id == None:
        student = request.user
    else:
        print content_parser.user_groups(request.user)
        if 'course_admin' not in content_parser.user_groups(request.user):
            raise Http404
        student = User.objects.get( id = int(student_id))

    user_info = UserProfile.objects.get(user=student) # request.user.profile_cache #

    context={'name':user_info.name,
             'username':student.username,
             'location':user_info.location,
             'language':user_info.language,
             'email':student.email,
             'format_url_params' : content_parser.format_url_params,
             'csrf':csrf(request)['csrf_token']
             }
    context.update(grades.grade_sheet(student))

    return render_to_response('profile.html', context)

def render_accordion(request,course,chapter,section):
    ''' Draws navigation bar. Takes current position in accordion as
        parameter. Returns (initialization_javascript, content)'''
    if not course:
        course = "6.002 Spring 2012"

    toc=content_parser.toc_from_xml(content_parser.course_file(request.user), chapter, section)
    active_chapter=1
    for i in range(len(toc)):
        if toc[i]['active']:
            active_chapter=i
    context=dict([['active_chapter',active_chapter],
                  ['toc',toc],
                  ['course_name',course],
                  ['format_url_params',content_parser.format_url_params],
                  ['csrf',csrf(request)['csrf_token']]] + \
                     template_imports.items())
    return render_to_string('accordion.html',context)

@cache_control(no_cache=True, no_store=True, must_revalidate=True)
def render_section(request, section):
    ''' TODO: Consolidate with index
    '''
    user = request.user
    if not settings.COURSEWARE_ENABLED:
        return redirect('/')

#    try:
    dom = content_parser.section_file(user, section)
    #except:
     #   raise Http404

    accordion=render_accordion(request, '', '', '')

    module_ids = dom.xpath("//@id")

    if user.is_authenticated():
        module_object_preload = list(StudentModule.objects.filter(student=user,
                                                                  module_id__in=module_ids))
    else:
        module_object_preload = []

    module=render_module(user, request, dom, module_object_preload)

    if 'init_js' not in module:
        module['init_js']=''

    context={'init':module['init_js'],
             'accordion':accordion,
             'content':module['content'],
             'csrf':csrf(request)['csrf_token']}

    result = render_to_response('courseware.html', context)
    return result

@cache_control(no_cache=True, no_store=True, must_revalidate=True)
def index(request, course="6.002 Spring 2012", chapter="Using the System", section="Hints"):
    ''' Displays courseware accordion, and any associated content.
    '''
    user = request.user
    if not settings.COURSEWARE_ENABLED:
        return redirect('/')

    # Fixes URLs -- we don't get funny encoding characters from spaces
    # so they remain readable
    ## TODO: Properly replace underscores
    course=course.replace("_"," ")
    chapter=chapter.replace("_"," ")
    section=section.replace("_"," ")

    # HACK: Force course to 6.002 for now
    # Without this, URLs break
    if course!="6.002 Spring 2012":
        return redirect('/')

    #import logging
    #log = logging.getLogger("mitx")
    #log.info(  "DEBUG: "+str(user) )

    dom = content_parser.course_file(user)
    dom_module = dom.xpath("//course[@name=$course]/chapter[@name=$chapter]//section[@name=$section]/*[1]",
                           course=course, chapter=chapter, section=section)
    if len(dom_module) == 0:
        module = None
    else:
        module = dom_module[0]

    accordion=render_accordion(request, course, chapter, section)

    module_ids = dom.xpath("//course[@name=$course]/chapter[@name=$chapter]//section[@name=$section]//@id",
                           course=course, chapter=chapter, section=section)

    if user.is_authenticated():
        module_object_preload = list(StudentModule.objects.filter(student=user,
                                                                  module_id__in=module_ids))
    else:
        module_object_preload = []

    module=render_module(user, request, module, module_object_preload)

    if 'init_js' not in module:
        module['init_js']=''

    context={'init':module['init_js'],
             'accordion':accordion,
             'content':module['content'],
             'csrf':csrf(request)['csrf_token']}

    result = render_to_response('courseware.html', context)
    return result

def modx_dispatch(request, module=None, dispatch=None, id=None):
    ''' Generic view for extensions. '''
    if not request.user.is_authenticated():
        return redirect('/')

    # Grab the student information for the module from the database
    s = StudentModule.objects.filter(student=request.user,
                                     module_id=id)
    #s = StudentModule.get_with_caching(request.user, id)
    if len(s) == 0 or s is None:
        log.debug("Couldnt find module for user and id " + str(module) + " " + str(request.user) + " "+ str(id))
        raise Http404
    s = s[0]

    oldgrade = s.grade
    oldstate = s.state

    dispatch=dispatch.split('?')[0]

    ajax_url = settings.MITX_ROOT_URL + '/modx/'+module+'/'+id+'/'

    # Grab the XML corresponding to the request from course.xml
    xml = content_parser.module_xml(request.user, module, 'id', id)

    # Create the module
    system = I4xSystem(track_function = make_track_function(request),
                       render_function = None,
                       ajax_url = ajax_url,
                       filestore = None
                       )
    instance=courseware.modules.get_module_class(module)(system,
                                                         xml,
                                                         id,
                                                         state=oldstate)
    # Let the module handle the AJAX
    ajax_return=instance.handle_ajax(dispatch, request.POST)
    # Save the state back to the database
    s.state=instance.get_state()
    if instance.get_score():
        s.grade=instance.get_score()['score']
    if s.grade != oldgrade or s.state != oldstate:
        s.save()
    # Return whatever the module wanted to return to the client/caller
    return HttpResponse(ajax_return)
<|endoftext|>


<commit_before>import os
import re
import subprocess

from dmoj.cptbox.sandbox import X86, X64, can_debug
from dmoj.error import CompileError
from dmoj.executors.base_executor import CompiledExecutor
from dmoj.judgeenv import env

refeatures = re.compile('^[#;@|!]\s*features:\s*([\w\s,]+)', re.M)
feature_split = re.compile('[\s,]+').split

class ASMExecutor(CompiledExecutor):
    arch = None
    ld_m = None
    as_name = None
    ld_name = None
    qemu_path = None
    dynamic_linker = None
    crt_pre = None
    crt_post = None
    platform_prefixes = None

    name = 'ASM'
    ext = '.asm'

    def __init__(self, problem_id, source_code, *args, **kwargs):
        self.use_qemu = self.qemu_path is not None and os.path.isfile(self.qemu_path)
        self.features = self.find_features(source_code)

        super(ASMExecutor, self).__init__(problem_id, source_code + '\n', *args, **kwargs)

    def find_features(self, source_code):
        features = refeatures.search(source_code)
        if features is not None:
            return set(filter(None, feature_split(features.group(1))))
        return set()

    @classmethod
    def get_as_path(cls):
        return cls.runtime_dict.get(cls.as_name)

    @classmethod
    def get_ld_path(cls):
        return cls.runtime_dict.get(cls.ld_name)

    def get_as_args(self, object):
        raise NotImplementedError()

    def assemble(self):
        object = self._file('%s.o' % self.problem)
        process = subprocess.Popen(self.get_as_args(object), cwd=self._dir, stderr=subprocess.PIPE)
        as_output = process.communicate()[1]
        if process.returncode != 0:
            raise CompileError(as_output)

        return as_output, [object]

    def compile(self):
        as_output, to_link = self.assemble()

        if 'libc' in self.features:
            to_link = ['-dynamic-linker', self.dynamic_linker] + self.crt_pre + ['-lc'] + to_link + self.crt_post

        executable = self._file(self.problem)
        process = self.TimedPopen([self.get_ld_path(), '-s', '-o', executable, '-m', self.ld_m] + to_link,
                                  cwd=self._dir, stderr=subprocess.PIPE, preexec_fn=self.create_executable_fslimit(),
                                  time_limit=self.compiler_time_limit)
        ld_output = process.communicate()[1]
        if process.returncode != 0 or (hasattr(process, '_killed') and process._killed):
            raise CompileError(ld_output)

        self.warning = ('%s\n%s' % (as_output, ld_output)).strip()
        return executable

    def get_cmdline(self):
        if self.use_qemu:
            return [self.qemu_path, self._executable]
        return super(ASMExecutor, self).get_cmdline()

    def get_executable(self):
        if self.use_qemu:
            return self.qemu_path
        return super(ASMExecutor, self).get_executable()

    def get_fs(self):
        fs = super(ASMExecutor, self).get_fs()
        if self.use_qemu:
            fs += ['/proc/sys/vm/mmap_min_addr$', '/etc/qemu-binfmt/', self._executable]
        return fs

    def get_address_grace(self):
        grace = super(ASMExecutor, self).get_address_grace()
        if self.use_qemu:
            grace += 65536
        return grace

    @classmethod
    def initialize(cls, sandbox=True):
        if cls.qemu_path is None and not can_debug(cls.arch):
            return False
        if any(i is None for i in
               (cls.get_as_path(), cls.get_ld_path(), cls.dynamic_linker, cls.crt_pre, cls.crt_post)):
            return False
        if any(not os.path.isfile(i) for i in (cls.get_as_path(), cls.get_ld_path(), cls.dynamic_linker)):
            return False
        if any(not os.path.isfile(i) for i in cls.crt_pre) or any(not os.path.isfile(i) for i in cls.crt_post):
            return False
        return cls.run_self_test(sandbox)

    @classmethod
    def get_versionable_commands(cls):
        for runtime in cls.get_find_first_mapping().keys():
            yield runtime, cls.runtime_dict[runtime]

    @classmethod
    def autoconfig(cls):
        if not can_debug(cls.arch):
            return {}, False, 'Unable to natively debug'
        return super(ASMExecutor, cls).autoconfig()

class GASExecutor(ASMExecutor):
    name = 'GAS'

    def get_as_args(self, object):
        return [self.get_as_path(), '-o', object, self._code]

    def assemble(self):
        object = self._file('%s.o' % self.problem)
        process = subprocess.Popen([self.get_as_path(), '-o', object, self._code],
                                   cwd=self._dir, stderr=subprocess.PIPE)
        as_output = process.communicate()[1]
        if process.returncode != 0:
            raise CompileError(as_output)

        return as_output, [object]

    @classmethod
    def get_find_first_mapping(cls):
        if cls.platform_prefixes is None:
            return None
        return {cls.as_name: ['%s-as' % i for i in cls.platform_prefixes],
                cls.ld_name: ['%s-ld' % i for i in cls.platform_prefixes] + ['ld']}

class NASMExecutor(ASMExecutor):
    name = 'NASM'
    as_name = 'nasm'
    nasm_format = None

    def find_features(self, source_code):
        features = super(NASMExecutor, self).find_features(source_code)
        if source_code.startswith('; libc'):
            features.add('libc')
        return features

    def get_as_args(self, object):
        return [self.get_as_path(), '-f', self.nasm_format, self._code, '-o', object]

    @classmethod
    def get_version_flags(cls, command):
        return ['-version'] if command == cls.as_name else super(NASMExecutor, cls).get_version_flags(command)

    @classmethod
    def get_find_first_mapping(cls):
        if cls.platform_prefixes is None:
            return None
        return {cls.ld_name: ['%s-ld' % i for i in cls.platform_prefixes] + ['ld'], 'nasm': ['nasm']}

class PlatformX86Mixin(object):
    arch = X86
    ld_name = 'ld_x86'
    ld_m = 'elf_i386'
    platform_prefixes = ['i586-linux-gnu']

    qemu_path = env.runtime.qemu_x86
    dynamic_linker = env.runtime['ld.so_x86'] or '/lib/ld-linux.so.2'

    if env.runtime.crt_x86_in_lib32:
        crt_pre = env.runtime.crt_pre_x86 or ['/usr/lib32/crt1.o', '/usr/lib32/crti.o']
        crt_post = env.runtime.crt_post_x86 or ['/usr/lib32/crtn.o']
    else:
        crt_pre = env.runtime.crt_pre_x86 or ['/usr/lib/i386-linux-gnu/crt1.o', '/usr/lib/i386-linux-gnu/crti.o']
        crt_post = env.runtime.crt_post_x86 or ['/usr/lib/i386-linux-gnu/crtn.o']

class PlatformX64Mixin(object):
    arch = X64
    ld_name = 'ld_x64'
    ld_m = 'elf_x86_64'
    platform_prefixes = ['x86_64-linux-gnu']

    qemu_path = env.runtime.qemu_x64
    dynamic_linker = env.runtime['ld.so_x64'] or '/lib64/ld-linux-x86-64.so.2'
    crt_pre = env.runtime.crt_pre_x64 or ['/usr/lib/x86_64-linux-gnu/crt1.o', '/usr/lib/x86_64-linux-gnu/crti.o']
    crt_post = env.runtime.crt_post_x64 or ['/usr/lib/x86_64-linux-gnu/crtn.o']
<commit_msg>Allow plain as, which is used on some platforms; #208<commit_after>import os
import re
import subprocess

from dmoj.cptbox.sandbox import X86, X64, can_debug
from dmoj.error import CompileError
from dmoj.executors.base_executor import CompiledExecutor
from dmoj.judgeenv import env

refeatures = re.compile('^[#;@|!]\s*features:\s*([\w\s,]+)', re.M)
feature_split = re.compile('[\s,]+').split

class ASMExecutor(CompiledExecutor):
    arch = None
    ld_m = None
    as_name = None
    ld_name = None
    qemu_path = None
    dynamic_linker = None
    crt_pre = None
    crt_post = None
    platform_prefixes = None

    name = 'ASM'
    ext = '.asm'

    def __init__(self, problem_id, source_code, *args, **kwargs):
        self.use_qemu = self.qemu_path is not None and os.path.isfile(self.qemu_path)
        self.features = self.find_features(source_code)

        super(ASMExecutor, self).__init__(problem_id, source_code + '\n', *args, **kwargs)

    def find_features(self, source_code):
        features = refeatures.search(source_code)
        if features is not None:
            return set(filter(None, feature_split(features.group(1))))
        return set()

    @classmethod
    def get_as_path(cls):
        return cls.runtime_dict.get(cls.as_name)

    @classmethod
    def get_ld_path(cls):
        return cls.runtime_dict.get(cls.ld_name)

    def get_as_args(self, object):
        raise NotImplementedError()

    def assemble(self):
        object = self._file('%s.o' % self.problem)
        process = subprocess.Popen(self.get_as_args(object), cwd=self._dir, stderr=subprocess.PIPE)
        as_output = process.communicate()[1]
        if process.returncode != 0:
            raise CompileError(as_output)

        return as_output, [object]

    def compile(self):
        as_output, to_link = self.assemble()

        if 'libc' in self.features:
            to_link = ['-dynamic-linker', self.dynamic_linker] + self.crt_pre + ['-lc'] + to_link + self.crt_post

        executable = self._file(self.problem)
        process = self.TimedPopen([self.get_ld_path(), '-s', '-o', executable, '-m', self.ld_m] + to_link,
                                  cwd=self._dir, stderr=subprocess.PIPE, preexec_fn=self.create_executable_fslimit(),
                                  time_limit=self.compiler_time_limit)
        ld_output = process.communicate()[1]
        if process.returncode != 0 or (hasattr(process, '_killed') and process._killed):
            raise CompileError(ld_output)

        self.warning = ('%s\n%s' % (as_output, ld_output)).strip()
        return executable

    def get_cmdline(self):
        if self.use_qemu:
            return [self.qemu_path, self._executable]
        return super(ASMExecutor, self).get_cmdline()

    def get_executable(self):
        if self.use_qemu:
            return self.qemu_path
        return super(ASMExecutor, self).get_executable()

    def get_fs(self):
        fs = super(ASMExecutor, self).get_fs()
        if self.use_qemu:
            fs += ['/proc/sys/vm/mmap_min_addr$', '/etc/qemu-binfmt/', self._executable]
        return fs

    def get_address_grace(self):
        grace = super(ASMExecutor, self).get_address_grace()
        if self.use_qemu:
            grace += 65536
        return grace

    @classmethod
    def initialize(cls, sandbox=True):
        if cls.qemu_path is None and not can_debug(cls.arch):
            return False
        if any(i is None for i in
               (cls.get_as_path(), cls.get_ld_path(), cls.dynamic_linker, cls.crt_pre, cls.crt_post)):
            return False
        if any(not os.path.isfile(i) for i in (cls.get_as_path(), cls.get_ld_path(), cls.dynamic_linker)):
            return False
        if any(not os.path.isfile(i) for i in cls.crt_pre) or any(not os.path.isfile(i) for i in cls.crt_post):
            return False
        return cls.run_self_test(sandbox)

    @classmethod
    def get_versionable_commands(cls):
        for runtime in cls.get_find_first_mapping().keys():
            yield runtime, cls.runtime_dict[runtime]

    @classmethod
    def autoconfig(cls):
        if not can_debug(cls.arch):
            return {}, False, 'Unable to natively debug'
        return super(ASMExecutor, cls).autoconfig()

class GASExecutor(ASMExecutor):
    name = 'GAS'
    as_platform_flag = None

    def get_as_args(self, object):
        as_args = [self.get_as_path(), '-o', object, self._code]
        if os.path.basename(self.get_as_path()) == 'as' and self.as_platform_flag:
            as_args += [self.as_platform_flag]
        return as_args

    def assemble(self):
        object = self._file('%s.o' % self.problem)
        process = subprocess.Popen([self.get_as_path(), '-o', object, self._code],
                                   cwd=self._dir, stderr=subprocess.PIPE)
        as_output = process.communicate()[1]
        if process.returncode != 0:
            raise CompileError(as_output)

        return as_output, [object]

    @classmethod
    def get_find_first_mapping(cls):
        if cls.platform_prefixes is None:
            return None
        return {cls.as_name: ['%s-as' % i for i in cls.platform_prefixes] + ['as'],
                cls.ld_name: ['%s-ld' % i for i in cls.platform_prefixes] + ['ld']}

class NASMExecutor(ASMExecutor):
    name = 'NASM'
    as_name = 'nasm'
    nasm_format = None

    def find_features(self, source_code):
        features = super(NASMExecutor, self).find_features(source_code)
        if source_code.startswith('; libc'):
            features.add('libc')
        return features

    def get_as_args(self, object):
        return [self.get_as_path(), '-f', self.nasm_format, self._code, '-o', object]

    @classmethod
    def get_version_flags(cls, command):
        return ['-version'] if command == cls.as_name else super(NASMExecutor, cls).get_version_flags(command)

    @classmethod
    def get_find_first_mapping(cls):
        if cls.platform_prefixes is None:
            return None
        return {cls.ld_name: ['%s-ld' % i for i in cls.platform_prefixes] + ['ld'], 'nasm': ['nasm']}

class PlatformX86Mixin(object):
    arch = X86
    ld_name = 'ld_x86'
    ld_m = 'elf_i386'
    platform_prefixes = ['i586-linux-gnu']
    as_platform_flag = '--32'

    qemu_path = env.runtime.qemu_x86
    dynamic_linker = env.runtime['ld.so_x86'] or '/lib/ld-linux.so.2'

    if env.runtime.crt_x86_in_lib32:
        crt_pre = env.runtime.crt_pre_x86 or ['/usr/lib32/crt1.o', '/usr/lib32/crti.o']
        crt_post = env.runtime.crt_post_x86 or ['/usr/lib32/crtn.o']
    else:
        crt_pre = env.runtime.crt_pre_x86 or ['/usr/lib/i386-linux-gnu/crt1.o', '/usr/lib/i386-linux-gnu/crti.o']
        crt_post = env.runtime.crt_post_x86 or ['/usr/lib/i386-linux-gnu/crtn.o']

class PlatformX64Mixin(object):
    arch = X64
    ld_name = 'ld_x64'
    ld_m = 'elf_x86_64'
    platform_prefixes = ['x86_64-linux-gnu']
    as_platform_flag = '--64'

    qemu_path = env.runtime.qemu_x64
    dynamic_linker = env.runtime['ld.so_x64'] or '/lib64/ld-linux-x86-64.so.2'
    crt_pre = env.runtime.crt_pre_x64 or ['/usr/lib/x86_64-linux-gnu/crt1.o', '/usr/lib/x86_64-linux-gnu/crti.o']
    crt_post = env.runtime.crt_post_x64 or ['/usr/lib/x86_64-linux-gnu/crtn.o']
<|endoftext|>


<commit_before>import os
import re
from collections import deque

from dmoj.judgeenv import env
from dmoj.result import Result
from dmoj.utils.unicode import utf8bytes, utf8text
from .base_executor import CompiledExecutor

GCC_ENV = env.runtime.gcc_env or {}
GCC_COMPILE = os.environ.copy()
IS_ARM = hasattr(os, 'uname') and os.uname()[4].startswith('arm')

if os.name == 'nt':
    GCC_COMPILE.update((k.encode('mbcs'), v.encode('mbcs')) for k, v in
                       (env.runtime.gcc_compile or GCC_ENV).iteritems())
    GCC_ENV = dict((k.encode('mbcs'), v.encode('mbcs')) for k, v in GCC_ENV.iteritems())
else:
    GCC_COMPILE.update(env.runtime.gcc_compile or {})

recppexc = re.compile(br"terminate called after throwing an instance of \'([A-Za-z0-9_:]+)\'\r?$", re.M)

class GCCExecutor(CompiledExecutor):
    defines = []
    flags = []
    name = 'GCC'
    arch = 'gcc_target_arch'
    has_color = False

    def create_files(self, problem_id, main_source, **kwargs):
        aux_sources = kwargs.get('aux_sources', {})
        fds = kwargs.get('fds', None)
        writable = kwargs.get('writable', (1, 2))
        aux_sources[problem_id + self.ext] = main_source

        sources = []
        for name, source in aux_sources.items():
            if '.' not in name:
                name += self.ext
            with open(self._file(name), 'wb') as fo:
                fo.write(utf8bytes(source))
            sources.append(name)
        self.sources = sources
        self._fds = fds
        self._writable = writable
        self.defines = kwargs.get('defines', [])

    def get_ldflags(self):
        if os.name == 'nt':
            return ['-Wl,--stack,67108864']
        return []

    def get_flags(self):
        return self.flags

    def get_defines(self):
        defines = ['-DONLINE_JUDGE'] + self.defines
        if os.name == 'nt':
            defines.append('-DWIN32')
        return defines

    def get_compile_args(self):
        return ([self.get_command(), '-Wall'] + (['-fdiagnostics-color=always'] if self.has_color else []) +
                self.sources + self.get_defines() + ['-O2', '-lm'] + [self.get_march_flag()]) +
                self.get_flags() + self.get_ldflags() + ['-s', '-o', self.get_compiled_file()])

    def get_compile_env(self):
        return GCC_COMPILE

    def get_security(self, launch_kwargs=None):
        from dmoj.cptbox import CHROOTSecurity
        return self._add_syscalls(
            CHROOTSecurity(self.get_fs(), writable=self._writable,
                           io_redirects=launch_kwargs.get('io_redirects', None))
        )

    def get_env(self):
        env = super(GCCExecutor, self).get_env() or {}
        env.update(GCC_ENV)
        return env

    def get_feedback(self, stderr, result, process):
        if not result.result_flag & Result.RTE or not stderr or len(stderr) > 2048:
            return ''
        match = deque(recppexc.finditer(stderr), maxlen=1)
        if not match:
            return ''
        exception = match[0].group(1)
        return '' if len(exception) > 40 else utf8text(exception, 'replace')

    @classmethod
    def get_march_flag(cls):
        conf_arch = cls.runtime_dict.get(cls.arch, 'native')
        if conf_arch:
            return '-march=%s' % conf_arch
        # arch must've been explicitly disabled
        return ''

    @classmethod
    def get_version_flags(cls, command):
        return ['-dumpversion']

    @classmethod
    def autoconfig(cls):
        return super(GCCExecutor, cls).autoconfig()

    @classmethod
    def initialize(cls, sandbox=True):
        res = super(CompiledExecutor, cls).initialize(sandbox=sandbox)
        if res:
            cls.has_color = cls.get_runtime_versions()[0][1] > (4, 9)
        return res
<commit_msg>Fix trailing ); #300<commit_after>import os
import re
from collections import deque

from dmoj.judgeenv import env
from dmoj.result import Result
from dmoj.utils.unicode import utf8bytes, utf8text
from .base_executor import CompiledExecutor

GCC_ENV = env.runtime.gcc_env or {}
GCC_COMPILE = os.environ.copy()
IS_ARM = hasattr(os, 'uname') and os.uname()[4].startswith('arm')

if os.name == 'nt':
    GCC_COMPILE.update((k.encode('mbcs'), v.encode('mbcs')) for k, v in
                       (env.runtime.gcc_compile or GCC_ENV).iteritems())
    GCC_ENV = dict((k.encode('mbcs'), v.encode('mbcs')) for k, v in GCC_ENV.iteritems())
else:
    GCC_COMPILE.update(env.runtime.gcc_compile or {})

recppexc = re.compile(br"terminate called after throwing an instance of \'([A-Za-z0-9_:]+)\'\r?$", re.M)

class GCCExecutor(CompiledExecutor):
    defines = []
    flags = []
    name = 'GCC'
    arch = 'gcc_target_arch'
    has_color = False

    def create_files(self, problem_id, main_source, **kwargs):
        aux_sources = kwargs.get('aux_sources', {})
        fds = kwargs.get('fds', None)
        writable = kwargs.get('writable', (1, 2))
        aux_sources[problem_id + self.ext] = main_source

        sources = []
        for name, source in aux_sources.items():
            if '.' not in name:
                name += self.ext
            with open(self._file(name), 'wb') as fo:
                fo.write(utf8bytes(source))
            sources.append(name)
        self.sources = sources
        self._fds = fds
        self._writable = writable
        self.defines = kwargs.get('defines', [])

    def get_ldflags(self):
        if os.name == 'nt':
            return ['-Wl,--stack,67108864']
        return []

    def get_flags(self):
        return self.flags

    def get_defines(self):
        defines = ['-DONLINE_JUDGE'] + self.defines
        if os.name == 'nt':
            defines.append('-DWIN32')
        return defines

    def get_compile_args(self):
        return ([self.get_command(), '-Wall'] + (['-fdiagnostics-color=always'] if self.has_color else []) +
                self.sources + self.get_defines() + ['-O2', '-lm'] + [self.get_march_flag()] +
                self.get_flags() + self.get_ldflags() + ['-s', '-o', self.get_compiled_file()])

    def get_compile_env(self):
        return GCC_COMPILE

    def get_security(self, launch_kwargs=None):
        from dmoj.cptbox import CHROOTSecurity
        return self._add_syscalls(
            CHROOTSecurity(self.get_fs(), writable=self._writable,
                           io_redirects=launch_kwargs.get('io_redirects', None))
        )

    def get_env(self):
        env = super(GCCExecutor, self).get_env() or {}
        env.update(GCC_ENV)
        return env

    def get_feedback(self, stderr, result, process):
        if not result.result_flag & Result.RTE or not stderr or len(stderr) > 2048:
            return ''
        match = deque(recppexc.finditer(stderr), maxlen=1)
        if not match:
            return ''
        exception = match[0].group(1)
        return '' if len(exception) > 40 else utf8text(exception, 'replace')

    @classmethod
    def get_march_flag(cls):
        conf_arch = cls.runtime_dict.get(cls.arch, 'native')
        if conf_arch:
            return '-march=%s' % conf_arch
        # arch must've been explicitly disabled
        return ''

    @classmethod
    def get_version_flags(cls, command):
        return ['-dumpversion']

    @classmethod
    def autoconfig(cls):
        return super(GCCExecutor, cls).autoconfig()

    @classmethod
    def initialize(cls, sandbox=True):
        res = super(CompiledExecutor, cls).initialize(sandbox=sandbox)
        if res:
            cls.has_color = cls.get_runtime_versions()[0][1] > (4, 9)
        return res
<|endoftext|>


<commit_before>"""
byceps.services.orga.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from typing import Dict, Iterator, Optional, Sequence, Tuple

from ...database import db
from ...typing import BrandID, UserID

from ..brand.models.brand import Brand
from ..user.models.user import User

from .models import OrgaFlag

def get_brands_with_person_counts() -> Iterator[Tuple[Brand, int]]:
    """Yield (brand, person count) pairs."""
    brands = Brand.query.all()

    person_counts_by_brand_id = get_person_count_by_brand_id()

    for brand in brands:
        person_count = person_counts_by_brand_id[brand.id]
        yield brand, person_count

def get_person_count_by_brand_id() -> Dict[BrandID, int]:
    """Return organizer count (including 0) per brand, indexed by brand ID."""
    dbrand_ids_and_orga_flag_counts = b.session \
        .query(
            Brand.id,
            db.func.count(OrgaFlag.brand_id)
        ) \
        .outerjoin(OrgaFlag) \
        .group_by(Brand.id) \
        .all()

    return dict(brand_ids_and_orga_flag_counts)

def get_orgas_for_brand(brand_id: BrandID) -> Sequence[User]:
    """Return all users flagged as organizers for the brand."""
    return User.query \
        .join(OrgaFlag).filter(OrgaFlag.brand_id == brand_id) \
        .options(db.joinedload('detail')) \
        .all()

def count_orgas() -> int:
    """Return the number of organizers with the organizer flag set."""
    return User.query \
        .distinct(User.id) \
        .join(OrgaFlag) \
        .count()

def count_orgas_for_brand(brand_id: BrandID) -> int:
    """Return the number of organizers with the organizer flag set for
    that brand.
    """
    return User.query \
        .distinct(User.id) \
        .join(OrgaFlag).filter(OrgaFlag.brand_id == brand_id) \
        .count()

def create_orga_flag(brand_id: BrandID, user_id: UserID) -> OrgaFlag:
    """Create an orga flag for a user for brand."""
    orga_flag = OrgaFlag(brand_id, user_id)

    db.session.add(orga_flag)
    db.session.commit()

    return orga_flag

def delete_orga_flag(orga_flag: OrgaFlag) -> None:
    """Delete the orga flag."""
    db.session.delete(orga_flag)
    db.session.commit()

def find_orga_flag(brand_id: BrandID, user_id: UserID) -> Optional[OrgaFlag]:
    """Return the orga flag for that brand and user, or `None` if not found."""
    return OrgaFlag.query \
        .filter_by(brand_id=brand_id) \
        .filter_by(user_id=user_id) \
        .first()

def is_user_orga(user_id: UserID) -> bool:
    """Return `True` if the user is an organizer."""
    flag_count = OrgaFlag.query \
        .filter_by(user_id=user_id) \
        .count()

    return flag_count > 0
<commit_msg>Fix refactoring mistake<commit_after>"""
byceps.services.orga.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from typing import Dict, Iterator, Optional, Sequence, Tuple

from ...database import db
from ...typing import BrandID, UserID

from ..brand.models.brand import Brand
from ..user.models.user import User

from .models import OrgaFlag

def get_brands_with_person_counts() -> Iterator[Tuple[Brand, int]]:
    """Yield (brand, person count) pairs."""
    brands = Brand.query.all()

    person_counts_by_brand_id = get_person_count_by_brand_id()

    for brand in brands:
        person_count = person_counts_by_brand_id[brand.id]
        yield brand, person_count

def get_person_count_by_brand_id() -> Dict[BrandID, int]:
    """Return organizer count (including 0) per brand, indexed by brand ID."""
    brand_ids_and_orga_flag_counts = db.session \
        .query(
            Brand.id,
            db.func.count(OrgaFlag.brand_id)
        ) \
        .outerjoin(OrgaFlag) \
        .group_by(Brand.id) \
        .all()

    return dict(brand_ids_and_orga_flag_counts)

def get_orgas_for_brand(brand_id: BrandID) -> Sequence[User]:
    """Return all users flagged as organizers for the brand."""
    return User.query \
        .join(OrgaFlag).filter(OrgaFlag.brand_id == brand_id) \
        .options(db.joinedload('detail')) \
        .all()

def count_orgas() -> int:
    """Return the number of organizers with the organizer flag set."""
    return User.query \
        .distinct(User.id) \
        .join(OrgaFlag) \
        .count()

def count_orgas_for_brand(brand_id: BrandID) -> int:
    """Return the number of organizers with the organizer flag set for
    that brand.
    """
    return User.query \
        .distinct(User.id) \
        .join(OrgaFlag).filter(OrgaFlag.brand_id == brand_id) \
        .count()

def create_orga_flag(brand_id: BrandID, user_id: UserID) -> OrgaFlag:
    """Create an orga flag for a user for brand."""
    orga_flag = OrgaFlag(brand_id, user_id)

    db.session.add(orga_flag)
    db.session.commit()

    return orga_flag

def delete_orga_flag(orga_flag: OrgaFlag) -> None:
    """Delete the orga flag."""
    db.session.delete(orga_flag)
    db.session.commit()

def find_orga_flag(brand_id: BrandID, user_id: UserID) -> Optional[OrgaFlag]:
    """Return the orga flag for that brand and user, or `None` if not found."""
    return OrgaFlag.query \
        .filter_by(brand_id=brand_id) \
        .filter_by(user_id=user_id) \
        .first()

def is_user_orga(user_id: UserID) -> bool:
    """Return `True` if the user is an organizer."""
    flag_count = OrgaFlag.query \
        .filter_by(user_id=user_id) \
        .count()

    return flag_count > 0
<|endoftext|>


<commit_before>"""
Test the printing of anonymous and named namespace variables.
"""

from __future__ import print_function

import os, time
import lldb
from lldbsuite.test.lldbtest import *
import lldbsuite.test.lldbutil as lldbutil

class NamespaceLookupTestCase(TestBase):

    mydir = TestBase.compute_mydir(__file__)

    def setUp(self):
        # Call super's setUp().
        TestBase.setUp(self)
        # Break inside different scopes and evaluate value
        self.line_break_global_scope = line_number('ns.cpp', '// BP_global_scope')
        self.line_break_file_scope = line_number('ns2.cpp', '// BP_file_scope')
        self.line_break_ns_scope = line_number('ns2.cpp', '// BP_ns_scope')
        self.line_break_nested_ns_scope = line_number('ns2.cpp', '// BP_nested_ns_scope')
        self.line_break_nested_ns_scope_after_using = line_number('ns2.cpp', '// BP_nested_ns_scope_after_using')
        self.line_break_before_using_directive = line_number('ns3.cpp', '// BP_before_using_directive')
        self.line_break_after_using_directive = line_number('ns3.cpp', '// BP_after_using_directive')

    def runToBkpt(self, command):
        self.runCmd(command, RUN_SUCCEEDED)
        # The stop reason of the thread should be breakpoint.
        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
            substrs = ['stopped',
                       'stop reason = breakpoint'])

    @expectedFailureFreeBSD("llvm.org/pr25819")
    @expectedFailureLinux("llvm.org/pr25819")
    def test_scope_lookup_with_run_command(self):
        """Test scope lookup of functions in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns.cpp", self.line_break_global_scope, num_expected_locations=1, loc_exact=False)
        lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_ns_scope, num_expected_locations=1, loc_exact=False)
        lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope, num_expected_locations=1, loc_exact=False)
        lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope_after_using, num_expected_locations=1, loc_exact=False)
        lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_before_using_directive, num_expected_locations=1, loc_exact=False)
        lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_after_using_directive, num_expected_locations=1, loc_exact=False)

        # Run to BP_global_scope at global scope
        self.runToBkpt("run")
        # Evaluate func() - should call ::func()
        self.expect("expr -- func()", startstr = "(int) $0 = 1")
        # Evaluate A::B::func() - should call A::B::func()
        self.expect("expr -- A::B::func()", startstr = "(int) $1 = 4")
        # Evaluate func(10) - should call ::func(int)
        self.expect("expr -- func(10)", startstr = "(int) $2 = 11")
        # Evaluate ::func() - should call A::func()
        self.expect("expr -- ::func()", startstr = "(int) $3 = 1")
        # Evaluate A::foo() - should call A::foo()
        self.expect("expr -- A::foo()", startstr = "(int) $4 = 42")

        # Continue to BP_ns_scope at ns scope
        self.runToBkpt("continue")
        # Evaluate func(10) - should call A::func(int)
        self.expect("expr -- func(10)", startstr = "(int) $5 = 13")
        # Evaluate B::func() - should call B::func()
        self.expect("expr -- B::func()", startstr = "(int) $6 = 4")
        # Evaluate func() - should call A::func()
        self.expect("expr -- func()", startstr = "(int) $7 = 3")

        # Continue to BP_nested_ns_scope at nested ns scope
        self.runToBkpt("continue")
        # Evaluate func() - should call A::B::func()
        self.expect("expr -- func()", startstr = "(int) $8 = 4")
        # Evaluate A::func() - should call A::func()
        self.expect("expr -- A::func()", startstr = "(int) $9 = 3")

        # Evaluate func(10) - should call A::func(10)
        # NOTE: Under the rules of C++, this test would normally get an error
        # because A::B::func() hides A::func(), but lldb intentionally
        # disobeys these rules so that the intended overload can be found
        # by only removing duplicates if they have the same type.
        self.expect("expr -- func(10)", startstr = "(int) $10 = 13")

        # Continue to BP_nested_ns_scope_after_using at nested ns scope after using declaration
        self.runToBkpt("continue")
        # Evaluate A::func(10) - should call A::func(int)
        self.expect("expr -- A::func(10)", startstr = "(int) $11 = 13")

        # Continue to BP_before_using_directive at global scope before using declaration
        self.runToBkpt("continue")
        # Evaluate ::func() - should call ::func()
        self.expect("expr -- ::func()", startstr = "(int) $12 = 1")
        # Evaluate B::func() - should call B::func()
        self.expect("expr -- B::func()", startstr = "(int) $13 = 4")

        # Continue to BP_after_using_directive at global scope after using declaration
        self.runToBkpt("continue")
        # Evaluate ::func() - should call ::func()
        self.expect("expr -- ::func()", startstr = "(int) $14 = 1")
        # Evaluate B::func() - should call B::func()
        self.expect("expr -- B::func()", startstr = "(int) $15 = 4")

    @unittest2.expectedFailure("lldb scope lookup of functions bugs")
    def test_function_scope_lookup_with_run_command(self):
        """Test scope lookup of functions in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns.cpp", self.line_break_global_scope, num_expected_locations=1, loc_exact=False)
        lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_ns_scope, num_expected_locations=1, loc_exact=False)

        # Run to BP_global_scope at global scope
        self.runToBkpt("run")
        # Evaluate foo() - should call ::foo()
        # FIXME: lldb finds Y::foo because lookup for variables is done
        # before functions.
        self.expect("expr -- foo()", startstr = "(int) $0 = 42")
        # Evaluate ::foo() - should call ::foo()
        # FIXME: lldb finds Y::foo because lookup for variables is done
        # before functions and :: is ignored.
        self.expect("expr -- ::foo()", startstr = "(int) $1 = 42")

        # Continue to BP_ns_scope at ns scope
        self.runToBkpt("continue")
        # Evaluate foo() - should call A::foo()
        # FIXME: lldb finds Y::foo because lookup for variables is done
        # before functions.
        self.expect("expr -- foo()", startstr = "(int) $2 = 42")

    @unittest2.expectedFailure("lldb file scope lookup bugs")
    def test_file_scope_lookup_with_run_command(self):
        """Test file scope lookup in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_file_scope, num_expected_locations=1, loc_exact=False)

        # Run to BP_file_scope at file scope
        self.runToBkpt("run")
        # Evaluate func() - should call static ns2.cpp:func()
        # FIXME: This test fails because lldb doesn't know about file scopes so
        # finds the global ::func().
        self.expect("expr -- func()", startstr = "(int) $0 = 2")

    @expectedFailureLinux("llvm.org/pr25819")
    def test_scope_lookup_before_using_with_run_command(self):
        """Test scope lookup before using in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_before_using_directive, num_expected_locations=1, loc_exact=False)

        # Run to BP_before_using_directive at global scope before using declaration
        self.runToBkpt("run")
        # Evaluate func() - should call ::func()
        self.expect("expr -- func()", startstr = "(int) $0 = 1")

    # NOTE: this test may fail on older systems that don't emit import
    # emtries in DWARF - may need to add checks for compiler versions here.
    @expectedFailureFreeBSD("llvm.org/pr25819")
    @expectedFailureLinux("llvm.org/pr25819")
    def test_scope_after_using_directive_lookup_with_run_command(self):
        """Test scope lookup after using directive in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_after_using_directive, num_expected_locations=1, loc_exact=False)

        # Run to BP_after_using_directive at global scope after using declaration
        self.runToBkpt("run")
        # Evaluate func2() - should call A::func2()
        self.expect("expr -- func2()", startstr = "(int) $0 = 3")

    @unittest2.expectedFailure("lldb scope lookup after using declaration bugs")
    # NOTE: this test may fail on older systems that don't emit import
    # emtries in DWARF - may need to add checks for compiler versions here.
    def test_scope_after_using_declaration_lookup_with_run_command(self):
        """Test scope lookup after using declaration in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope_after_using, num_expected_locations=1, loc_exact=False)

        # Run to BP_nested_ns_scope_after_using at nested ns scope after using declaration
        self.runToBkpt("run")
        # Evaluate func() - should call A::func()
        self.expect("expr -- func()", startstr = "(int) $0 = 3")

    @unittest2.expectedFailure("lldb scope lookup ambiguity after using bugs")
    def test_scope_ambiguity_after_using_lookup_with_run_command(self):
        """Test scope lookup ambiguity after using in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_after_using_directive, num_expected_locations=1, loc_exact=False)

        # Run to BP_after_using_directive at global scope after using declaration
        self.runToBkpt("run")
        # Evaluate func() - should get error: ambiguous
        # FIXME: This test fails because lldb removes duplicates if they have
        # the same type.
        self.expect("expr -- func()", startstr = "error")

    @expectedFailureFreeBSD("llvm.org/pr25819")
    @expectedFailureLinux("llvm.org/pr25819")
    def test_scope_lookup_shadowed_by_using_with_run_command(self):
        """Test scope lookup shadowed by using in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope, num_expected_locations=1, loc_exact=False)

        # Run to BP_nested_ns_scope at nested ns scope
        self.runToBkpt("run")
        # Evaluate func(10) - should call A::func(10)
        # NOTE: Under the rules of C++, this test would normally get an error
        # because A::B::func() shadows A::func(), but lldb intentionally
        # disobeys these rules so that the intended overload can be found
        # by only removing duplicates if they have the same type.
        self.expect("expr -- func(10)", startstr = "(int) $0 = 13")

<commit_msg>XFail TestNamespaceLookup tests on Windows.<commit_after>"""
Test the printing of anonymous and named namespace variables.
"""

from __future__ import print_function

import os, time
import lldb
from lldbsuite.test.lldbtest import *
import lldbsuite.test.lldbutil as lldbutil

class NamespaceLookupTestCase(TestBase):

    mydir = TestBase.compute_mydir(__file__)

    def setUp(self):
        # Call super's setUp().
        TestBase.setUp(self)
        # Break inside different scopes and evaluate value
        self.line_break_global_scope = line_number('ns.cpp', '// BP_global_scope')
        self.line_break_file_scope = line_number('ns2.cpp', '// BP_file_scope')
        self.line_break_ns_scope = line_number('ns2.cpp', '// BP_ns_scope')
        self.line_break_nested_ns_scope = line_number('ns2.cpp', '// BP_nested_ns_scope')
        self.line_break_nested_ns_scope_after_using = line_number('ns2.cpp', '// BP_nested_ns_scope_after_using')
        self.line_break_before_using_directive = line_number('ns3.cpp', '// BP_before_using_directive')
        self.line_break_after_using_directive = line_number('ns3.cpp', '// BP_after_using_directive')

    def runToBkpt(self, command):
        self.runCmd(command, RUN_SUCCEEDED)
        # The stop reason of the thread should be breakpoint.
        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
            substrs = ['stopped',
                       'stop reason = breakpoint'])

    @expectedFailureFreeBSD("llvm.org/pr25819")
    @expectedFailureLinux("llvm.org/pr25819")
    @expectedFailureWindows("llvm.org/pr25819")
    def test_scope_lookup_with_run_command(self):
        """Test scope lookup of functions in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns.cpp", self.line_break_global_scope, num_expected_locations=1, loc_exact=False)
        lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_ns_scope, num_expected_locations=1, loc_exact=False)
        lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope, num_expected_locations=1, loc_exact=False)
        lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope_after_using, num_expected_locations=1, loc_exact=False)
        lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_before_using_directive, num_expected_locations=1, loc_exact=False)
        lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_after_using_directive, num_expected_locations=1, loc_exact=False)

        # Run to BP_global_scope at global scope
        self.runToBkpt("run")
        # Evaluate func() - should call ::func()
        self.expect("expr -- func()", startstr = "(int) $0 = 1")
        # Evaluate A::B::func() - should call A::B::func()
        self.expect("expr -- A::B::func()", startstr = "(int) $1 = 4")
        # Evaluate func(10) - should call ::func(int)
        self.expect("expr -- func(10)", startstr = "(int) $2 = 11")
        # Evaluate ::func() - should call A::func()
        self.expect("expr -- ::func()", startstr = "(int) $3 = 1")
        # Evaluate A::foo() - should call A::foo()
        self.expect("expr -- A::foo()", startstr = "(int) $4 = 42")

        # Continue to BP_ns_scope at ns scope
        self.runToBkpt("continue")
        # Evaluate func(10) - should call A::func(int)
        self.expect("expr -- func(10)", startstr = "(int) $5 = 13")
        # Evaluate B::func() - should call B::func()
        self.expect("expr -- B::func()", startstr = "(int) $6 = 4")
        # Evaluate func() - should call A::func()
        self.expect("expr -- func()", startstr = "(int) $7 = 3")

        # Continue to BP_nested_ns_scope at nested ns scope
        self.runToBkpt("continue")
        # Evaluate func() - should call A::B::func()
        self.expect("expr -- func()", startstr = "(int) $8 = 4")
        # Evaluate A::func() - should call A::func()
        self.expect("expr -- A::func()", startstr = "(int) $9 = 3")

        # Evaluate func(10) - should call A::func(10)
        # NOTE: Under the rules of C++, this test would normally get an error
        # because A::B::func() hides A::func(), but lldb intentionally
        # disobeys these rules so that the intended overload can be found
        # by only removing duplicates if they have the same type.
        self.expect("expr -- func(10)", startstr = "(int) $10 = 13")

        # Continue to BP_nested_ns_scope_after_using at nested ns scope after using declaration
        self.runToBkpt("continue")
        # Evaluate A::func(10) - should call A::func(int)
        self.expect("expr -- A::func(10)", startstr = "(int) $11 = 13")

        # Continue to BP_before_using_directive at global scope before using declaration
        self.runToBkpt("continue")
        # Evaluate ::func() - should call ::func()
        self.expect("expr -- ::func()", startstr = "(int) $12 = 1")
        # Evaluate B::func() - should call B::func()
        self.expect("expr -- B::func()", startstr = "(int) $13 = 4")

        # Continue to BP_after_using_directive at global scope after using declaration
        self.runToBkpt("continue")
        # Evaluate ::func() - should call ::func()
        self.expect("expr -- ::func()", startstr = "(int) $14 = 1")
        # Evaluate B::func() - should call B::func()
        self.expect("expr -- B::func()", startstr = "(int) $15 = 4")

    @unittest2.expectedFailure("lldb scope lookup of functions bugs")
    def test_function_scope_lookup_with_run_command(self):
        """Test scope lookup of functions in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns.cpp", self.line_break_global_scope, num_expected_locations=1, loc_exact=False)
        lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_ns_scope, num_expected_locations=1, loc_exact=False)

        # Run to BP_global_scope at global scope
        self.runToBkpt("run")
        # Evaluate foo() - should call ::foo()
        # FIXME: lldb finds Y::foo because lookup for variables is done
        # before functions.
        self.expect("expr -- foo()", startstr = "(int) $0 = 42")
        # Evaluate ::foo() - should call ::foo()
        # FIXME: lldb finds Y::foo because lookup for variables is done
        # before functions and :: is ignored.
        self.expect("expr -- ::foo()", startstr = "(int) $1 = 42")

        # Continue to BP_ns_scope at ns scope
        self.runToBkpt("continue")
        # Evaluate foo() - should call A::foo()
        # FIXME: lldb finds Y::foo because lookup for variables is done
        # before functions.
        self.expect("expr -- foo()", startstr = "(int) $2 = 42")

    @unittest2.expectedFailure("lldb file scope lookup bugs")
    def test_file_scope_lookup_with_run_command(self):
        """Test file scope lookup in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_file_scope, num_expected_locations=1, loc_exact=False)

        # Run to BP_file_scope at file scope
        self.runToBkpt("run")
        # Evaluate func() - should call static ns2.cpp:func()
        # FIXME: This test fails because lldb doesn't know about file scopes so
        # finds the global ::func().
        self.expect("expr -- func()", startstr = "(int) $0 = 2")

    @expectedFailureLinux("llvm.org/pr25819")
    @expectedFailureWindows("llvm.org/pr25819")
    def test_scope_lookup_before_using_with_run_command(self):
        """Test scope lookup before using in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_before_using_directive, num_expected_locations=1, loc_exact=False)

        # Run to BP_before_using_directive at global scope before using declaration
        self.runToBkpt("run")
        # Evaluate func() - should call ::func()
        self.expect("expr -- func()", startstr = "(int) $0 = 1")

    # NOTE: this test may fail on older systems that don't emit import
    # entries in DWARF - may need to add checks for compiler versions here.
    @expectedFailureFreeBSD("llvm.org/pr25819")
    @expectedFailureLinux("llvm.org/pr25819")
    @expectedFailureWindows("llvm.org/pr25819")
    def test_scope_after_using_directive_lookup_with_run_command(self):
        """Test scope lookup after using directive in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_after_using_directive, num_expected_locations=1, loc_exact=False)

        # Run to BP_after_using_directive at global scope after using declaration
        self.runToBkpt("run")
        # Evaluate func2() - should call A::func2()
        self.expect("expr -- func2()", startstr = "(int) $0 = 3")

    @unittest2.expectedFailure("lldb scope lookup after using declaration bugs")
    # NOTE: this test may fail on older systems that don't emit import
    # emtries in DWARF - may need to add checks for compiler versions here.
    def test_scope_after_using_declaration_lookup_with_run_command(self):
        """Test scope lookup after using declaration in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope_after_using, num_expected_locations=1, loc_exact=False)

        # Run to BP_nested_ns_scope_after_using at nested ns scope after using declaration
        self.runToBkpt("run")
        # Evaluate func() - should call A::func()
        self.expect("expr -- func()", startstr = "(int) $0 = 3")

    @unittest2.expectedFailure("lldb scope lookup ambiguity after using bugs")
    def test_scope_ambiguity_after_using_lookup_with_run_command(self):
        """Test scope lookup ambiguity after using in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_after_using_directive, num_expected_locations=1, loc_exact=False)

        # Run to BP_after_using_directive at global scope after using declaration
        self.runToBkpt("run")
        # Evaluate func() - should get error: ambiguous
        # FIXME: This test fails because lldb removes duplicates if they have
        # the same type.
        self.expect("expr -- func()", startstr = "error")

    @expectedFailureFreeBSD("llvm.org/pr25819")
    @expectedFailureLinux("llvm.org/pr25819")
    @expectedFailureWindows("llvm.org/pr25819")
    def test_scope_lookup_shadowed_by_using_with_run_command(self):
        """Test scope lookup shadowed by using in lldb."""
        self.build()
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope, num_expected_locations=1, loc_exact=False)

        # Run to BP_nested_ns_scope at nested ns scope
        self.runToBkpt("run")
        # Evaluate func(10) - should call A::func(10)
        # NOTE: Under the rules of C++, this test would normally get an error
        # because A::B::func() shadows A::func(), but lldb intentionally
        # disobeys these rules so that the intended overload can be found
        # by only removing duplicates if they have the same type.
        self.expect("expr -- func(10)", startstr = "(int) $0 = 13")

<|endoftext|>