<commit_before>
import sublime, sublime_plugin
from LuaAutocomplete.locals import LocalsFinder

class ExampleCommand(sublime_plugin.TextCommand):
	def run(self, edit):
		self.view.insert(edit, 0, "Hello, World!")

class LuaAutocomplete(sublime_plugin.EventListener):
	def on_query_completions(self, view, prefix, locations):
		if view.settings().get("syntax") != "Packages/Lua/Lua.tmLanguage":
			# Not Lua, don't do anything.
			return

		location = locations[0] # TODO: Better multiselect behavior?
		src = view.substr(sublime.Region(0, view.size()))

		localsfinder = LocalsFinder(src)
		varz = localsfinder.run(location)

		return [(name+"\t"+data.vartype,name) for name, data in varz.items()], sublime.INHIBIT_WORD_COMPLETIONS
<commit_msg>Defer to ST3's autocomplete when indexing variables, since that's too complex to do at the moment.<commit_after>
import sublime, sublime_plugin
from LuaAutocomplete.locals import LocalsFinder

def is_indexing(view, location):
	"""
	Returns true if indexing a value; that is, there is a period or colon to the left of the autocompleting word
	"""
	pos = view.find_by_class(location, False, sublime.CLASS_WORD_START)
	if pos == 0:
		return False
	char = view.substr(pos-1)
	return char == "." or char == ":"

class LuaAutocomplete(sublime_plugin.EventListener):
	def on_query_completions(self, view, prefix, locations):
		if view.settings().get("syntax") != "Packages/Lua/Lua.tmLanguage":
			# Not Lua, don't do anything.
			return

		location = locations[0] # TODO: Better multiselect behavior?

		if is_indexing(view, location):
			# Don't bother trying to autocomplete value indexing.
			return

		src = view.substr(sublime.Region(0, view.size()))

		localsfinder = LocalsFinder(src)
		varz = localsfinder.run(location)

		return [(name+"\t"+data.vartype,name) for name, data in varz.items()], sublime.INHIBIT_WORD_COMPLETIONS
<|endoftext|>


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

"""This module defines the "%scd" magic command in an IPython session.
The %scd or smart-cd command can find and change to any directory,
without having to know its exact path.  In addition, this module updates
the %cd, %popd, %pushd magic commands so that they record the visited
directory in the scd index file.

The scd executable script must be in the system PATH or the
ipy_scd.scd_executable  must be set to its full path.

To define the %scd magic in every ipython session in
IPython 0.10 or earlier, import this module from the
~/.ipython/ipy_user_conf.py file.

For IPython 0.11 or later, add this module to the
c.InteractiveShellApp.extensions list in the
IPYTHON/profile_default/ipython_config.py file.
"""

import re
import IPython

ipyversion = map(int, re.split(r'(\d+)', IPython.__version__)[1::2])
isipython010 = ipyversion < [0, 11]
isipython012 = (ipyversion < [0, 13]) and not isipython010
isipython013 = not (ipyversion < [0, 13])

class _cdcommands:
    cd = None
    pushd = None
    popd = None
    if isipython013:
        from IPython.core.magics import OSMagics
        cd_doc = OSMagics.cd.__doc__
        pushd_doc = OSMagics.pushd.__doc__
        popd_doc = OSMagics.popd.__doc__
    else:
        if isipython010:
            from IPython.Magic import Magic
        else:
            from IPython.core.magic import Magic
        cd_doc = Magic.magic_cd.__doc__
        pushd_doc = Magic.magic_pushd.__doc__
        popd_doc = Magic.magic_popd.__doc__
    pass

def whereisexecutable(program):
    '''Return a list of files in the system PATH executable by the user.

    program  -- command name that is looked for in the PATH

    Return a list of absolute paths to the program.  When program
    contains any path components, just check if that file is executable.
    '''
    import os
    isexecutable = lambda f: os.access(f, os.X_OK) and os.path.isfile(f)
    ppath, pname = os.path.split(program)
    rv = []
    if ppath:
        rv += [program]
    else:
        rv += [os.path.join(d, program)
                for d in os.environ['PATH'].split(os.pathsep)]
    rv = [os.path.abspath(f) for f in rv if isexecutable(f)]
    return rv

# full path to the scd_executable or an empty string when not found
scd_executable = (whereisexecutable('scd') + [''])[0]

def do_scd(self, arg):
    '''scd -- smart change to a recently used directory
    usage: scd [options] [pattern1 pattern2 ...]
    Go to a directory path that contains all fixed string patterns.  Prefer
    recent or frequently visited directories as found in the directory index.
    Display a selection menu in case of multiple matches.

    Options:
    -a, --add         add current or specified directories to the index.
    --unindex         remove current or specified directories from the index.
    -r, --recursive   apply options --add or --unindex recursively.
    --alias=ALIAS     create alias for the current or specified directory and
                      store it in ~/.scdalias.zsh.
    --unalias         remove ALIAS definition for the current or specified
                      directory from ~/.scdalias.zsh.
    -A, --all         include all matching directories.  Disregard matching by
                      directory alias and filtering of less likely paths.
    --list            show matching directories and exit.
    -v, --verbose     display directory rank in the selection menu.
    -h, --help        display this message and exit.
    '''
    import os
    import subprocess
    import tempfile
    import shlex
    scdfile = tempfile.NamedTemporaryFile('r')
    env = dict(os.environ)
    env['SCD_SCRIPT'] = scdfile.name
    args = [scd_executable] + shlex.split(str(arg))
    retcode = subprocess.call(args, env=env)
    cmd = scdfile.read()
    if retcode == 0 and cmd.startswith('cd '):
        _cdcommands.cd(cmd[3:])
        cwd = shlex.split(cmd[3:])[0]
        _scd_record_cwd(cwd)
    return

def do_cd(self, arg):
    rv = _cdcommands.cd(arg)
    _scd_record_cwd()
    return rv
do_cd.__doc__ = _cdcommands.cd_doc

def do_pushd(self, arg):
    rv = _cdcommands.pushd(arg)
    _scd_record_cwd()
    return rv
do_pushd.__doc__ = _cdcommands.pushd_doc

def do_popd(self, arg):
    rv = _cdcommands.popd(arg)
    _scd_record_cwd()
    return rv
do_popd.__doc__ = _cdcommands.popd_doc

# Function for loading the scd magic with the 0.11 or later API

def load_ipython_extension(ipython):
    '''Define the scd command and overloads of cd, pushd, popd that record
    new visited paths to the scdhistory file.

    When flag is False, revert to the default behavior.
    '''
    _raiseIfNoExecutable()
    if _cdcommands.cd is None:
        if isipython013:
            _cdcommands.cd = ipython.find_magic('cd')
            _cdcommands.pushd = ipython.find_magic('pushd')
            _cdcommands.popd = ipython.find_magic('popd')
        else:
            _cdcommands.cd = ipython.magic_cd
            _cdcommands.pushd = ipython.magic_pushd
            _cdcommands.popd = ipython.magic_popd
    ipython.define_magic('scd', do_scd)
    ipython.define_magic('cd', do_cd)
    ipython.define_magic('pushd', do_pushd)
    ipython.define_magic('popd', do_popd)
    global _scd_active
    _scd_active = True
    return

def unload_ipython_extension(ipython):
    if hasattr(ipython, 'magic_scd'):
        delattr(ipython, 'magic_scd')
    global _scd_active
    _scd_active = False
    return

# This function activates or disables scd magic in IPython 0.10

def scdactivate(flag):
    '''Define the scd command and overloads of cd, pushd, popd that record
    new visited paths to the scdhistory file.

    When flag is False, undefine the scd command and revert all
    cd-related commands to their default behavior.
    '''
    global _scd_active
    import IPython.ipapi
    ip = IPython.ipapi.get()
    if _cdcommands.cd is None:
        _cdcommands.cd = ip.IP.magic_cd
        _cdcommands.pushd = ip.IP.magic_pushd
        _cdcommands.popd = ip.IP.magic_popd
    if flag:
        _raiseIfNoExecutable()
        ip.expose_magic('scd', do_scd)
        ip.expose_magic('cd', do_cd)
        ip.expose_magic('pushd', do_pushd)
        ip.expose_magic('popd', do_popd)
        _scd_active = True
    else:
        ipshell = ip.IP
        if hasattr(ipshell, 'magic_scd'):
            delattr(ipshell, 'magic_scd')
        _scd_active = False
    return
_scd_active = False

# Disable for later ipython versions
if not isipython010:
    del scdactivate

def _scd_record_cwd(cwd=None):
    if not _scd_active:  return
    import os
    import subprocess
    global _scd_last_directory
    if cwd is None:
        cwd = os.getcwd()
    if cwd == _scd_last_directory:
        return
    _scd_last_directory = cwd
    args = [scd_executable, '--add', cwd]
    subprocess.call(args)
    return
_scd_last_directory = ''

def _raiseIfNoExecutable():
    emsg = ("scd executable not found.  Place it to a directory in the "
            "PATH or define the ipy_scd.scd_executable variable.")
    if not scd_executable:
        raise RuntimeError(emsg)
    return

if isipython010 and scd_executable:
    scdactivate(True)
<commit_msg>Make the IPython extension compatible with Python 3.<commit_after>#!/usr/bin/env python

"""This module defines the "%scd" magic command in an IPython session.
The %scd or smart-cd command can find and change to any directory,
without having to know its exact path.  In addition, this module updates
the %cd, %popd, %pushd magic commands so that they record the visited
directory in the scd index file.

The scd executable script must be in the system PATH or the
ipy_scd.scd_executable  must be set to its full path.

To define the %scd magic in every ipython session in
IPython 0.10 or earlier, import this module from the
~/.ipython/ipy_user_conf.py file.

For IPython 0.11 or later, add this module to the
c.InteractiveShellApp.extensions list in the
IPYTHON/profile_default/ipython_config.py file.
"""

import re
import IPython

ipyversion = list(map(int, re.split(r'(\d+)', IPython.__version__)[1::2]))
isipython010 = ipyversion < [0, 11]
isipython012 = (ipyversion < [0, 13]) and not isipython010
isipython013 = not (ipyversion < [0, 13])

class _cdcommands:
    cd = None
    pushd = None
    popd = None
    if isipython013:
        from IPython.core.magics import OSMagics
        cd_doc = OSMagics.cd.__doc__
        pushd_doc = OSMagics.pushd.__doc__
        popd_doc = OSMagics.popd.__doc__
    else:
        if isipython010:
            from IPython.Magic import Magic
        else:
            from IPython.core.magic import Magic
        cd_doc = Magic.magic_cd.__doc__
        pushd_doc = Magic.magic_pushd.__doc__
        popd_doc = Magic.magic_popd.__doc__
    pass

def whereisexecutable(program):
    '''Return a list of files in the system PATH executable by the user.

    program  -- command name that is looked for in the PATH

    Return a list of absolute paths to the program.  When program
    contains any path components, just check if that file is executable.
    '''
    import os
    isexecutable = lambda f: os.access(f, os.X_OK) and os.path.isfile(f)
    ppath, pname = os.path.split(program)
    rv = []
    if ppath:
        rv += [program]
    else:
        rv += [os.path.join(d, program)
                for d in os.environ['PATH'].split(os.pathsep)]
    rv = [os.path.abspath(f) for f in rv if isexecutable(f)]
    return rv

# full path to the scd_executable or an empty string when not found
scd_executable = (whereisexecutable('scd') + [''])[0]

def do_scd(self, arg):
    '''scd -- smart change to a recently used directory
    usage: scd [options] [pattern1 pattern2 ...]
    Go to a directory path that contains all fixed string patterns.  Prefer
    recent or frequently visited directories as found in the directory index.
    Display a selection menu in case of multiple matches.

    Options:
    -a, --add         add current or specified directories to the index.
    --unindex         remove current or specified directories from the index.
    -r, --recursive   apply options --add or --unindex recursively.
    --alias=ALIAS     create alias for the current or specified directory and
                      store it in ~/.scdalias.zsh.
    --unalias         remove ALIAS definition for the current or specified
                      directory from ~/.scdalias.zsh.
    -A, --all         include all matching directories.  Disregard matching by
                      directory alias and filtering of less likely paths.
    --list            show matching directories and exit.
    -v, --verbose     display directory rank in the selection menu.
    -h, --help        display this message and exit.
    '''
    import os
    import subprocess
    import tempfile
    import shlex
    scdfile = tempfile.NamedTemporaryFile('r')
    env = dict(os.environ)
    env['SCD_SCRIPT'] = scdfile.name
    args = [scd_executable] + shlex.split(str(arg))
    retcode = subprocess.call(args, env=env)
    cmd = scdfile.read()
    if retcode == 0 and cmd.startswith('cd '):
        _cdcommands.cd(cmd[3:])
        cwd = shlex.split(cmd[3:])[0]
        _scd_record_cwd(cwd)
    return

def do_cd(self, arg):
    rv = _cdcommands.cd(arg)
    _scd_record_cwd()
    return rv
do_cd.__doc__ = _cdcommands.cd_doc

def do_pushd(self, arg):
    rv = _cdcommands.pushd(arg)
    _scd_record_cwd()
    return rv
do_pushd.__doc__ = _cdcommands.pushd_doc

def do_popd(self, arg):
    rv = _cdcommands.popd(arg)
    _scd_record_cwd()
    return rv
do_popd.__doc__ = _cdcommands.popd_doc

# Function for loading the scd magic with the 0.11 or later API

def load_ipython_extension(ipython):
    '''Define the scd command and overloads of cd, pushd, popd that record
    new visited paths to the scdhistory file.

    When flag is False, revert to the default behavior.
    '''
    _raiseIfNoExecutable()
    if _cdcommands.cd is None:
        if isipython013:
            _cdcommands.cd = ipython.find_magic('cd')
            _cdcommands.pushd = ipython.find_magic('pushd')
            _cdcommands.popd = ipython.find_magic('popd')
        else:
            _cdcommands.cd = ipython.magic_cd
            _cdcommands.pushd = ipython.magic_pushd
            _cdcommands.popd = ipython.magic_popd
    ipython.define_magic('scd', do_scd)
    ipython.define_magic('cd', do_cd)
    ipython.define_magic('pushd', do_pushd)
    ipython.define_magic('popd', do_popd)
    global _scd_active
    _scd_active = True
    return

def unload_ipython_extension(ipython):
    if hasattr(ipython, 'magic_scd'):
        delattr(ipython, 'magic_scd')
    global _scd_active
    _scd_active = False
    return

# This function activates or disables scd magic in IPython 0.10

def scdactivate(flag):
    '''Define the scd command and overloads of cd, pushd, popd that record
    new visited paths to the scdhistory file.

    When flag is False, undefine the scd command and revert all
    cd-related commands to their default behavior.
    '''
    global _scd_active
    import IPython.ipapi
    ip = IPython.ipapi.get()
    if _cdcommands.cd is None:
        _cdcommands.cd = ip.IP.magic_cd
        _cdcommands.pushd = ip.IP.magic_pushd
        _cdcommands.popd = ip.IP.magic_popd
    if flag:
        _raiseIfNoExecutable()
        ip.expose_magic('scd', do_scd)
        ip.expose_magic('cd', do_cd)
        ip.expose_magic('pushd', do_pushd)
        ip.expose_magic('popd', do_popd)
        _scd_active = True
    else:
        ipshell = ip.IP
        if hasattr(ipshell, 'magic_scd'):
            delattr(ipshell, 'magic_scd')
        _scd_active = False
    return
_scd_active = False

# Disable for later ipython versions
if not isipython010:
    del scdactivate

def _scd_record_cwd(cwd=None):
    if not _scd_active:  return
    import os
    import subprocess
    global _scd_last_directory
    if cwd is None:
        cwd = os.getcwd()
    if cwd == _scd_last_directory:
        return
    _scd_last_directory = cwd
    args = [scd_executable, '--add', cwd]
    subprocess.call(args)
    return
_scd_last_directory = ''

def _raiseIfNoExecutable():
    emsg = ("scd executable not found.  Place it to a directory in the "
            "PATH or define the ipy_scd.scd_executable variable.")
    if not scd_executable:
        raise RuntimeError(emsg)
    return

if isipython010 and scd_executable:
    scdactivate(True)
<|endoftext|>


<commit_before># Copyright (C) 2014 by Alex Brandt <alunduil@alunduil.com>
#
# etest is freely distributable under the terms of an MIT-style license.
# See COPYING or http://www.opensource.org/licenses/mit-license.php.

import functools
import logging
import os
import re

from etest.lexers.bash import BashLexer
from etest.parsers.bash import BashParser

logger = logging.getLogger(__name__)

class Ebuild(object):
    def __init__(self, path, overlay):
        self.path = path
        self.overlay = overlay

    @property
    @functools.lru_cache(1)
    def name(self):
        return os.path.dirname(self.path)

    @property
    @functools.lru_cache(1)
    def cpv(self):
        return '=' + self.name + '-' + self.version

    @property
    @functools.lru_cache(1)
    def version(self):
        _ = self.path.replace('.ebuild', '')
        _ = re.sub(r'.*?' + self.name.split('/')[-1] + '-', '', _)

        return _

    @property
    @functools.lru_cache(1)
    def compat(self):
        return { k.replace('_COMPAT', '').lower(): v for k, v in self.parse().items() if '_COMPAT' in k }

    @property
    @functools.lru_cache(1)
    def restrictions(self):
        return self.parse().get('RESTRICT', '').split()

    @property
    @functools.lru_cache(1)
    def use_flags(self):
        return self.parse()['IUSE'].split()

    @functools.lru_cache(1)
    def parse(self):
        '''Convert ebuild file into a dictionary, mapping variables to values.

        Parses the ebuild file and constructs a dictionary that maps the
        variables to their values.

        Returns
        -------

        Dictionary whose keys are variables in the associated ebuild.

        '''

        parser = BashParser()
        parser.build()

        lexer = BashLexer()
        lexer.build()

        with open(os.path.join(self.overlay.directory, self.path), 'r') as fh:
            parser.parser.parse(
                input = fh.read(),
                lexer = lexer.lexer,
            )

        return parser.symbols
<commit_msg>escape ebuild name in version calculation<commit_after># Copyright (C) 2014 by Alex Brandt <alunduil@alunduil.com>
#
# etest is freely distributable under the terms of an MIT-style license.
# See COPYING or http://www.opensource.org/licenses/mit-license.php.

import functools
import logging
import os
import re

from etest.lexers.bash import BashLexer
from etest.parsers.bash import BashParser

logger = logging.getLogger(__name__)

class Ebuild(object):
    def __init__(self, path, overlay):
        self.path = path
        self.overlay = overlay

    @property
    @functools.lru_cache(1)
    def name(self):
        return os.path.dirname(self.path)

    @property
    @functools.lru_cache(1)
    def cpv(self):
        return '=' + self.name + '-' + self.version

    @property
    @functools.lru_cache(1)
    def version(self):
        _ = self.path.replace('.ebuild', '')
        _ = re.sub(r'.*?' + re.escape(self.name.split('/')[-1]) + '-', '', _)

        return _

    @property
    @functools.lru_cache(1)
    def compat(self):
        return { k.replace('_COMPAT', '').lower(): v for k, v in self.parse().items() if '_COMPAT' in k }

    @property
    @functools.lru_cache(1)
    def restrictions(self):
        return self.parse().get('RESTRICT', '').split()

    @property
    @functools.lru_cache(1)
    def use_flags(self):
        return self.parse()['IUSE'].split()

    @functools.lru_cache(1)
    def parse(self):
        '''Convert ebuild file into a dictionary, mapping variables to values.

        Parses the ebuild file and constructs a dictionary that maps the
        variables to their values.

        Returns
        -------

        Dictionary whose keys are variables in the associated ebuild.

        '''

        parser = BashParser()
        parser.build()

        lexer = BashLexer()
        lexer.build()

        with open(os.path.join(self.overlay.directory, self.path), 'r') as fh:
            parser.parser.parse(
                input = fh.read(),
                lexer = lexer.lexer,
            )

        return parser.symbols
<|endoftext|>


<commit_before><commit_msg>add repo name in the init file<commit_after>name = "etk"<|endoftext|>


<commit_before>VERSION = (2, 5, 0)

def get_version():
    return '.'.join(map(str, VERSION))
<commit_msg>2.5.1<commit_after>VERSION = (2, 5, 1)

def get_version():
    return '.'.join(map(str, VERSION))
<|endoftext|>


<commit_before># Copyright (c) 2016. Mount Sinai School of Medicine
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function, division, absolute_import

__version__ = "0.3.0"
<commit_msg>version bump<commit_after># Copyright (c) 2016. Mount Sinai School of Medicine
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function, division, absolute_import

__version__ = "0.3.1"
<|endoftext|>


<commit_before>import os
from pyivle.pyivle import Pyivle
from models import User, Module
import datetime
import html_stripper
import userstr

API_KEY = os.environ['API_KEY']
auth_token = None
IVLE = Pyivle(API_KEY)

MODULE_ID_NULL_STRING='00000000-0000-0000-0000-000000000000'

async def do(auth_token, func, params={}):
    IVLE.set_auth_token(auth_token)
    try:
        response = IVLE.validate()
        if not response.Success:
            return userstr.validate_false, False
    except:
        return userstr.validate_false, False
    return func(**params)

def setup_user(user, auth_token):
    try:
        response = IVLE.validate()
        if response.Success:
            user.auth_token = auth_token
            user.save()
        return (userstr.validate_true, True) if response.Success else (userstr.setup_validate_false, False)
    except Exception as e:
        print(e)
        return (userstr.setup_validate_false, False)

def setup_modules():
    try:
        response = IVLE.modules(includeAllInfo=False)
        module_list = []
        for module in response.Results:
            mod, _ = Module.get_or_create(module_code=module.CourseCode, acad_year=module.CourseAcadYear, semester=int(module.CourseSemester[-1]), defaults={'module_id': module.ID})
            if mod.module_id is None or mod.module_id == '':
                mod.module_id = MODULE_ID_NULL_STRING
            mod.save()
        return (userstr.setup_modules_true, True)
    except Exception as e:
        print(e)
        return (userstr.setup_modules_false, False)

def get_gradebook(module_code, module_id):
    try:
        response = IVLE.gradebook_view_items(module_id)
        gradebook_items = {}
        for category in response.Results:
            processed_category = ''.join(map(__process_gradebook_item, category.Items))
            title = category.CategoryTitle + '\n##########\n'
            gradebook_items[title] = processed_category
        result = []
        for category, v in gradebook_items.items():
            result.append(category)
            result.append(v)
        success = 'Here are your grades for {}:\n\n'.format(module_code) + ''.join(result)
        return (success, True)
    except Exception as e:
        print(e)
        return (userstr.gradebook_false, False)

def __process_gradebook_item(item):
    result = []
    if not item.MarksObtained and not item.Grade:
        return ''
    grade = item.MarksObtained if item.MarksObtained else item.Grade
    result.append(item.ItemName + ': ' + grade + '\n')
    result.append('Highest-Lowest: ' + item.HighestLowestMarks + '\n')
    result.append('Average-Median: ' + item.AverageMedianMarks + '\n')
    result.append('Percentile: ' + item.Percentile + '\n')
    return ''.join(result) + '\n'

def get_timetable(modules):
    try:
        all_module_timetables = get_unformatted_timetable(modules)
        all_module_timetables = list(map(strf_timetable, all_module_timetables))
        success = ''.join(all_module_timetables)
        return (success, True) if success else (userstr.timetable_none, True)
    except Exception as e:
        print(e)
        return (userstr.gradebook_false, False)

def get_unformatted_timetable(modules, merged=False):
    try:
        result = []
        for m_id in modules:
            module_timetable = IVLE.timetable_student_module(m_id).Results
            if merged:
                result.extend(module_timetable)
            else:
                result.append(module_timetable)
        return result
    except Exception as e:
        print(e)
        return []

def strf_timetable(module_timetable):
    result = []
    if module_timetable:
        result.append(module_timetable[0].ModuleCode + ':\n')
        for lesson in module_timetable:
            result.append(lesson.DayText + ' ')
            result.append(lesson.LessonType.lower() + ' from ')
            result.append(lesson.StartTime + ' to ')
            result.append(lesson.EndTime + ' at ')
            result.append(lesson.Venue + '\n')
        result.append('\n')
    return ''.join(result)

def get_exam_timetable(modules):
    try:
        all_module_timetables = []
        for m_id in modules:
            timetables = IVLE.timetable_module_exam(m_id).Results
            all_module_timetables.append(strf_exam_timetable(timetables))
        success = ''.join(all_module_timetables)
        return (success, True) if len(success) else (userstr.module_no_exams, True)
    except Exception as e:
        print(e)
        return (userstr.exam_timetable_false, False)

def strf_exam_timetable(module_timetable):
    if not module_timetable:
        return ''
    result = []
    result.append(module_timetable[0].ModuleCode + '\'s exam is on ')
    exam_dates = set()
    for exam in module_timetable:
        exam_dates.add(exam.ExamInfo + '\n')
    for exam in exam_dates:
        result.append(exam)
    result.append('\n')
    return ''.join(result)

def get_next_class():
    try:
        simplified_lessons, result = _sort_lessons(_get_all_lessons())
        idx = _get_next_class(simplified_lessons)
        if idx is not None:
            lesson = result[idx]
            success = 'Your next class is: ' + strf_lesson(lesson)
            return (success, True)
        return (userstr.nextclass_false, False)
    except Exception as e:
        print(e)
        return (userstr.nextclass_false, False)

def _get_all_lessons():
    results = IVLE.modules(includeAllInfo=False).Results
    module_ids = list(map(lambda mod: mod.ID, results))
    return get_unformatted_timetable(module_ids, merged=True)

def _sort_lessons(all_lessons):
    today = datetime.date.today().isoweekday()
    lessons = []
    for i in range(len(all_lessons)):
        l = all_lessons[i]
        lesson_day = int(l.DayCode)
        lesson_day = lesson_day if lesson_day >= today else lesson_day + 7
        triplet = (lesson_day, l.StartTime, i)
        lessons.append(triplet)
    lessons = sorted(lessons, key=lambda l: l[1])
    lessons = sorted(lessons, key=lambda l: l[0])
    result = []
    for l in lessons:
        result.append(all_lessons[l[2]])
    return (lessons, result)

def _get_next_class(lesson_triplets):
    for i in range(len(lesson_triplets)):
        today = datetime.date.today().isoweekday()
        time_now = datetime.datetime.now().strftime('%H%M')
        lesson = lesson_triplets[i]
        day, time = lesson[0], lesson[1]
        if (day == today and int(time) >= int(time_now)) or (day > today):
            return i
    return None

def strf_lesson(lesson):
    result = []
    result.append(lesson.ModuleCode + ' ')
    result.append(lesson.LessonType.lower() + ' at ')
    result.append(lesson.Venue + ' on ')
    result.append(lesson.DayText + ', ')
    result.append(lesson.StartTime)
    return ''.join(result)

def get_classes_tomorrow():
    today = datetime.date.today().isoweekday()
    if today == 5:
        return ('TGIF! No classes!', True)
    elif today == 6:
        return ('It\'s the weekend...', True)
    try:
        tomorrow = (today + 1) % 7
        classes_tomorrow = '\n'.join(map(strf_lesson, filter(lambda l: int(l.DayCode) == tomorrow, _get_all_lessons())))
        return (userstr.classes_tomorrow_describe + classes_tomorrow, True) if classes_tomorrow else (userstr.classes_tomorrow_none, True)
    except Exception as e:
        print(e)
        return (failure, False)

def get_unread_ann():
    try:
        results = {}
        res = IVLE.announcements_unread().Results
        for r in res:
            results[r.CourseCode] = (strf_announcements(r.Announcements, True))
        return (results, True) if results else (userstr.unread_ann_none, True)
    except Exception as e:
        print(e)
        return (userstr.unread_ann_false, False)

def strf_announcements(announcements, mark_read=False):
    results = []
    for i in range(len(announcements)):
        if mark_read:
            IVLE.announcements_add_log(announcements[i].ID)
        results.append('#{}: '.format(i+1) + datetime.datetime.strptime(announcements[i].CreatedDate_js, '%Y-%m-%dT%H:%M:%S').strftime('%H:%M on %a, %d-%m-%y \n') + announcements[i].Title + '\n' + html_stripper.strip_tags(announcements[i].Description))
    return '\n'.join(results)

def get_recent_ann(module_code, count, duration=0):
    try:
        course_id = Module.select(Module.module_id). \
        where(Module.module_code.contains(module_code)). \
        order_by(Module.acad_year.desc(), Module.semester.desc()). \
        get().module_id

        results = strf_announcements(IVLE.announcements(courseId=course_id, duration=duration).Results[:count])
        return (results, True) if results else ('There are no announcements for {}'.format(module_code), True)
    except Exception as e:
        print(e)
        return (userstr.recent_ann_false, False)
<commit_msg>Return all possible next classes if multiple classes are in the same time slot<commit_after>import os
from pyivle.pyivle import Pyivle
from models import User, Module
import datetime
import html_stripper
import userstr

API_KEY = os.environ['API_KEY']
auth_token = None
IVLE = Pyivle(API_KEY)

MODULE_ID_NULL_STRING='00000000-0000-0000-0000-000000000000'

async def do(auth_token, func, params={}):
    IVLE.set_auth_token(auth_token)
    try:
        response = IVLE.validate()
        if not response.Success:
            return userstr.validate_false, False
    except:
        return userstr.validate_false, False
    return func(**params)

def setup_user(user, auth_token):
    try:
        response = IVLE.validate()
        if response.Success:
            user.auth_token = auth_token
            user.save()
        return (userstr.validate_true, True) if response.Success else (userstr.setup_validate_false, False)
    except Exception as e:
        print(e)
        return (userstr.setup_validate_false, False)

def setup_modules():
    try:
        response = IVLE.modules(includeAllInfo=False)
        module_list = []
        for module in response.Results:
            mod, _ = Module.get_or_create(module_code=module.CourseCode, acad_year=module.CourseAcadYear, semester=int(module.CourseSemester[-1]), defaults={'module_id': module.ID})
            if mod.module_id is None or mod.module_id == '':
                mod.module_id = MODULE_ID_NULL_STRING
            mod.save()
        return (userstr.setup_modules_true, True)
    except Exception as e:
        print(e)
        return (userstr.setup_modules_false, False)

def get_gradebook(module_code, module_id):
    try:
        response = IVLE.gradebook_view_items(module_id)
        gradebook_items = {}
        for category in response.Results:
            processed_category = ''.join(map(__process_gradebook_item, category.Items))
            title = category.CategoryTitle + '\n##########\n'
            gradebook_items[title] = processed_category
        result = []
        for category, v in gradebook_items.items():
            result.append(category)
            result.append(v)
        success = 'Here are your grades for {}:\n\n'.format(module_code) + ''.join(result)
        return (success, True)
    except Exception as e:
        print(e)
        return (userstr.gradebook_false, False)

def __process_gradebook_item(item):
    result = []
    if not item.MarksObtained and not item.Grade:
        return ''
    grade = item.MarksObtained if item.MarksObtained else item.Grade
    result.append(item.ItemName + ': ' + grade + '\n')
    result.append('Highest-Lowest: ' + item.HighestLowestMarks + '\n')
    result.append('Average-Median: ' + item.AverageMedianMarks + '\n')
    result.append('Percentile: ' + item.Percentile + '\n')
    return ''.join(result) + '\n'

def get_timetable(modules):
    try:
        all_module_timetables = get_unformatted_timetable(modules)
        all_module_timetables = list(map(strf_timetable, all_module_timetables))
        success = ''.join(all_module_timetables)
        return (success, True) if success else (userstr.timetable_none, True)
    except Exception as e:
        print(e)
        return (userstr.gradebook_false, False)

def get_unformatted_timetable(modules, merged=False):
    try:
        result = []
        for m_id in modules:
            module_timetable = IVLE.timetable_student_module(m_id).Results
            if merged:
                result.extend(module_timetable)
            else:
                result.append(module_timetable)
        return result
    except Exception as e:
        print(e)
        return []

def strf_timetable(module_timetable):
    result = []
    if module_timetable:
        result.append(module_timetable[0].ModuleCode + ':\n')
        for lesson in module_timetable:
            result.append(lesson.DayText + ' ')
            result.append(lesson.LessonType.lower() + ' from ')
            result.append(lesson.StartTime + ' to ')
            result.append(lesson.EndTime + ' at ')
            result.append(lesson.Venue + '\n')
        result.append('\n')
    return ''.join(result)

def get_exam_timetable(modules):
    try:
        all_module_timetables = []
        for m_id in modules:
            timetables = IVLE.timetable_module_exam(m_id).Results
            all_module_timetables.append(strf_exam_timetable(timetables))
        success = ''.join(all_module_timetables)
        return (success, True) if len(success) else (userstr.module_no_exams, True)
    except Exception as e:
        print(e)
        return (userstr.exam_timetable_false, False)

def strf_exam_timetable(module_timetable):
    if not module_timetable:
        return ''
    result = []
    result.append(module_timetable[0].ModuleCode + '\'s exam is on ')
    exam_dates = set()
    for exam in module_timetable:
        exam_dates.add(exam.ExamInfo + '\n')
    for exam in exam_dates:
        result.append(exam)
    result.append('\n')
    return ''.join(result)

def get_next_class():
    try:
        simplified_lessons, result = _sort_lessons(_get_all_lessons())
        classesIdx = _get_next_classes(simplified_lessons)
        if not classesIdx:
            lessons = map(strf_lesson, map(lambda idx: result[idx], classesIdx))
            if len(lessons) == 1:
                success = 'Your next class is: ' + lessons[0]
            else:
                success = 'Your next classes are: ' + '\n'.join(lessons)
            return (success, True)
        return (userstr.nextclass_false, False)
    except Exception as e:
        print(e)
        return (userstr.nextclass_false, False)

def _get_all_lessons():
    results = IVLE.modules(includeAllInfo=False).Results
    module_ids = list(map(lambda mod: mod.ID, results))
    return get_unformatted_timetable(module_ids, merged=True)

def _sort_lessons(all_lessons):
    today = datetime.date.today().isoweekday()
    lessons = []
    for i in range(len(all_lessons)):
        l = all_lessons[i]
        lesson_day = int(l.DayCode)
        lesson_day = lesson_day if lesson_day >= today else lesson_day + 7
        triplet = (lesson_day, l.StartTime, i)
        lessons.append(triplet)
    lessons = sorted(lessons, key=lambda l: l[1])
    lessons = sorted(lessons, key=lambda l: l[0])
    result = []
    for l in lessons:
        result.append(all_lessons[l[2]])
    return (lessons, result)

def _get_next_classes(lesson_triplets):
    candidateClassesIdx = []
    day_next_class = None
    time_next_class = None
    for i in range(len(lesson_triplets)):
        today = datetime.date.today().isoweekday()
        time_now = datetime.datetime.now().strftime('%H%M')
        lesson = lesson_triplets[i]
        day, time = lesson[0], lesson[1]
        if (day == today and int(time) >= int(time_now)) or (day > today):
            if not candidateClassesIdx:
                candidateClassesIdx.append(i)
                day_next_class = day
                time_next_class = time
            elif day == day_next_class and time == time_next_class:
                candidateClassesIdx.append(i)
            else:
                break
    return candidateClassesIdx

def strf_lesson(lesson):
    result = []
    result.append(lesson.ModuleCode + ' ')
    result.append(lesson.LessonType.lower() + ' at ')
    result.append(lesson.Venue + ' on ')
    result.append(lesson.DayText + ', ')
    result.append(lesson.StartTime)
    return ''.join(result)

def get_classes_tomorrow():
    today = datetime.date.today().isoweekday()
    if today == 5:
        return ('TGIF! No classes!', True)
    elif today == 6:
        return ('It\'s the weekend...', True)
    try:
        tomorrow = (today + 1) % 7
        classes_tomorrow = '\n'.join(map(strf_lesson, filter(lambda l: int(l.DayCode) == tomorrow, _get_all_lessons())))
        return (userstr.classes_tomorrow_describe + classes_tomorrow, True) if classes_tomorrow else (userstr.classes_tomorrow_none, True)
    except Exception as e:
        print(e)
        return (failure, False)

def get_unread_ann():
    try:
        results = {}
        res = IVLE.announcements_unread().Results
        for r in res:
            results[r.CourseCode] = (strf_announcements(r.Announcements, True))
        return (results, True) if results else (userstr.unread_ann_none, True)
    except Exception as e:
        print(e)
        return (userstr.unread_ann_false, False)

def strf_announcements(announcements, mark_read=False):
    results = []
    for i in range(len(announcements)):
        if mark_read:
            IVLE.announcements_add_log(announcements[i].ID)
        results.append('#{}: '.format(i+1) + datetime.datetime.strptime(announcements[i].CreatedDate_js, '%Y-%m-%dT%H:%M:%S').strftime('%H:%M on %a, %d-%m-%y \n') + announcements[i].Title + '\n' + html_stripper.strip_tags(announcements[i].Description))
    return '\n'.join(results)

def get_recent_ann(module_code, count, duration=0):
    try:
        course_id = Module.select(Module.module_id). \
        where(Module.module_code.contains(module_code)). \
        order_by(Module.acad_year.desc(), Module.semester.desc()). \
        get().module_id

        results = strf_announcements(IVLE.announcements(courseId=course_id, duration=duration).Results[:count])
        return (results, True) if results else ('There are no announcements for {}'.format(module_code), True)
    except Exception as e:
        print(e)
        return (userstr.recent_ann_false, False)
<|endoftext|>


<commit_before># =================================================================
#
# Terms and Conditions of Use
#
# Unless otherwise noted, computer program source code of this
# distribution is covered under Crown Copyright, Government of
# Canada, and is distributed under the MIT License.
#
# The Canada wordmark and related graphics associated with this
# distribution are protected under trademark law and copyright law.
# No permission is granted to use them outside the parameters of
# the Government of Canada's corporate identity program. For
# more information, see
# http://www.tbs-sct.gc.ca/fip-pcim/index-eng.asp
#
# Copyright title to all 3rd party software distributed with this
# software is held by the respective copyright holders as noted in
# those files. Users are asked to read the 3rd Party Licenses
# referenced with those assets.
#
# Copyright (c) 2020 Government of Canada
# Copyright (c) 2020, IBL Software Engineering spol. s r. o.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# =================================================================

import os
import unittest

from lxml import etree
from pywcmp.ats import TestSuiteError, WMOCoreMetadataProfileTestSuite13
from pywcmp.kpi import WMOCoreMetadataProfileKeyPerformanceIndicators

def get_test_file_path(filename):
    """helper function to open test file safely"""

    if os.path.isfile(filename):
        return filename
    else:
        return f'tests/{filename}'

class WCMPATSTest(unittest.TestCase):
    """WCMP ATS tests of tests"""

    def setUp(self):
        """setup test fixtures, etc."""
        pass

    def tearDown(self):
        """return to pristine state"""
        pass

    def test_jma_raise(self):
        """Simple JMA Tests"""
        exml = etree.parse(get_test_file_path('data/md-WTPQ50RJTD-gmd.xml'))
        ts = WMOCoreMetadataProfileTestSuite13(exml)
        with self.assertRaises(TestSuiteError):
            ts.run_tests()

    def test_jma_inspect_errors(self):
        """Simple JMA Tests"""
        exml = etree.parse(get_test_file_path('data/md-SMJP01RJTD-gmd.xml'))
        ts = WMOCoreMetadataProfileTestSuite13(exml)
        try:
            ts.run_tests()
        except TestSuiteError as err:
            self.assertEqual(3, len(err.errors))

class WCMPKPITest(unittest.TestCase):
    """WCMP KPI tests of tests"""

    def setUp(self):
        """setup test fixtures, etc."""
        pass

    def tearDown(self):
        """return to pristine state"""
        pass

    def test_kpi_evaluate(self):
        exml = etree.parse(get_test_file_path('data/urn:x-wmo:md:int.wmo.wis::ca.gc.ec.msc-1.1.5.6.xml'))  # noqa

        kpis = WMOCoreMetadataProfileKeyPerformanceIndicators(exml)

        results = kpis.evaluate()

        self.assertEqual(results['summary']['total'], 46)
        self.assertEqual(results['summary']['score'], 28)
        self.assertEqual(results['summary']['percentage'], 60.870)

if __name__ == '__main__':
    unittest.main()
<commit_msg>update tests<commit_after># =================================================================
#
# Terms and Conditions of Use
#
# Unless otherwise noted, computer program source code of this
# distribution is covered under Crown Copyright, Government of
# Canada, and is distributed under the MIT License.
#
# The Canada wordmark and related graphics associated with this
# distribution are protected under trademark law and copyright law.
# No permission is granted to use them outside the parameters of
# the Government of Canada's corporate identity program. For
# more information, see
# http://www.tbs-sct.gc.ca/fip-pcim/index-eng.asp
#
# Copyright title to all 3rd party software distributed with this
# software is held by the respective copyright holders as noted in
# those files. Users are asked to read the 3rd Party Licenses
# referenced with those assets.
#
# Copyright (c) 2020 Government of Canada
# Copyright (c) 2020, IBL Software Engineering spol. s r. o.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# =================================================================

import os
import unittest

from lxml import etree
from pywcmp.ats import TestSuiteError, WMOCoreMetadataProfileTestSuite13
from pywcmp.kpi import WMOCoreMetadataProfileKeyPerformanceIndicators

def get_test_file_path(filename):
    """helper function to open test file safely"""

    if os.path.isfile(filename):
        return filename
    else:
        return f'tests/{filename}'

class WCMPATSTest(unittest.TestCase):
    """WCMP ATS tests of tests"""

    def setUp(self):
        """setup test fixtures, etc."""
        pass

    def tearDown(self):
        """return to pristine state"""
        pass

    def test_jma_raise(self):
        """Simple JMA Tests"""
        exml = etree.parse(get_test_file_path('data/md-WTPQ50RJTD-gmd.xml'))
        ts = WMOCoreMetadataProfileTestSuite13(exml)
        with self.assertRaises(TestSuiteError):
            ts.run_tests()

    def test_jma_inspect_errors(self):
        """Simple JMA Tests"""
        exml = etree.parse(get_test_file_path('data/md-SMJP01RJTD-gmd.xml'))
        ts = WMOCoreMetadataProfileTestSuite13(exml)
        try:
            ts.run_tests()
        except TestSuiteError as err:
            self.assertEqual(3, len(err.errors))

class WCMPKPITest(unittest.TestCase):
    """WCMP KPI tests of tests"""

    def setUp(self):
        """setup test fixtures, etc."""
        pass

    def tearDown(self):
        """return to pristine state"""
        pass

    def test_kpi_evaluate(self):
        exml = etree.parse(get_test_file_path('data/urn:x-wmo:md:int.wmo.wis::ca.gc.ec.msc-1.1.5.6.xml'))  # noqa

        kpis = WMOCoreMetadataProfileKeyPerformanceIndicators(exml)

        results = kpis.evaluate()

        self.assertEqual(results['summary']['total'], 46)
        self.assertEqual(results['summary']['score'], 29)
        self.assertEqual(results['summary']['percentage'], 63.043)

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>#!/usr/bin/env python
# Copyright 2018 The Amber Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import base64
import difflib
import optparse
import os
import platform
import re
import subprocess
import sys
import tempfile

SUPPRESSIONS = {
  "Darwin": [
    # No geometry shader on MoltenVK
    "draw_triangle_list_using_geom_shader.vkscript",
    # No tessellation shader on MoltenVK
    "draw_triangle_list_using_tessellation.vkscript"
  ]
}

class TestCase:
  def __init__(self, input_path, parse_only):
    self.input_path = input_path
    self.parse_only = parse_only

    self.results = {}

  def IsExpectedFail(self):
    fail_re = re.compile('^.+[.]expect_fail[.][amber|vkscript]')
    return fail_re.match(self.GetInputPath())

  def IsSuppressed(self):
    system = platform.system()
    if system in SUPPRESSIONS.keys():
      return os.path.basename(self.input_path) in SUPPRESSIONS[system]
    return False

  def IsParseOnly(self):
    return self.parse_only

  def GetInputPath(self):
    return self.input_path

  def GetResult(self, fmt):
    return self.results[fmt]

class TestRunner:
  def RunTest(self, tc):
    print "Testing %s" % tc.GetInputPath()

    cmd = [self.options.test_prog_path, '-q']
    if tc.IsParseOnly():
      cmd += ['-p']
    cmd += [tc.GetInputPath()]

    try:
      err = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
      if err != "" and not tc.IsExpectedFail() and not tc.IsSuppressed():
        sys.stdout.write(err)
        return False

    except Exception as e:
      print e.output
      if not tc.IsExpectedFail() and not tc.IsSuppressed():
        print e
      return False

    return True

  def RunTests(self):
    for tc in self.test_cases:
      result = self.RunTest(tc)

      if tc.IsSuppressed():
        self.suppressed.append(tc.GetInputPath())
      else:
        if not tc.IsExpectedFail() and not result:
          self.failures.append(tc.GetInputPath())
        elif tc.IsExpectedFail() and result:
          print("Expected: " + tc.GetInputPath() + " to fail but passed.")
          self.failures.append(tc.GetInputPath())

  def SummarizeResults(self):
    if len(self.failures) > 0:
      self.failures.sort()

      print '\nSummary of Failures:'
      for failure in self.failures:
        print failure

    if len(self.suppressed) > 0:
      self.suppressed.sort()

      print '\nSummary of Suppressions:'
      for suppression in self.suppressed:
        print suppression

    print
    print 'Test cases executed: %d' % len(self.test_cases)
    print '  Successes:  %d' % (len(self.test_cases) - len(self.suppressed) - len(self.failures))
    print '  Failures:   %d' % len(self.failures)
    print '  Suppressed: %d' % len(self.suppressed)
    print

  def Run(self):
    base_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))

    usage = 'usage: %prog [options] (file)'
    parser = optparse.OptionParser(usage=usage)
    parser.add_option('--build-dir',
                      default=os.path.join(base_path, 'out', 'Debug'),
                      help='path to build directory')
    parser.add_option('--test-dir',
                      default=os.path.join(os.path.dirname(__file__), 'cases'),
                      help='path to directory containing test files')
    parser.add_option('--test-prog-path', default=None,
                      help='path to program to test')
    parser.add_option('--parse-only',
                      action="store_true", default=False,
                      help='only parse test cases; do not execute')

    self.options, self.args = parser.parse_args()

    if self.options.test_prog_path == None:
      test_prog = os.path.abspath(os.path.join(self.options.build_dir, 'amber'))
      if not os.path.isfile(test_prog):
        print "Cannot find test program %s" % test_prog
        return 1

      self.options.test_prog_path = test_prog

    if not os.path.isfile(self.options.test_prog_path):
      print "--test-prog-path must point to an executable"
      return 1

    input_file_re = re.compile('^.+[.][amber|vkscript]')
    self.test_cases = []

    if self.args:
      for filename in self.args:
        input_path = os.path.join(self.options.test_dir, filename)
        if not os.path.isfile(input_path):
          print "Cannot find test file '%s'" % filename
          return 1

        self.test_cases.append(TestCase(input_path, self.options.parse_only))

    else:
      for file_dir, _, filename_list in os.walk(self.options.test_dir):
        for input_filename in filename_list:
          if input_file_re.match(input_filename):
            input_path = os.path.join(file_dir, input_filename)
            if os.path.isfile(input_path):
              self.test_cases.append(
                  TestCase(input_path, self.options.parse_only))

    self.failures = []
    self.suppressed = []

    self.RunTests()
    self.SummarizeResults()

    return len(self.failures) != 0

def main():
  runner = TestRunner()
  return runner.Run()

if __name__ == '__main__':
  sys.exit(main())
<commit_msg>[vulkan] More MoltenVK suppressions (#378)<commit_after>#!/usr/bin/env python
# Copyright 2018 The Amber Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import base64
import difflib
import optparse
import os
import platform
import re
import subprocess
import sys
import tempfile

SUPPRESSIONS = {
  "Darwin": [
    # No geometry shader on MoltenVK
    "draw_triangle_list_using_geom_shader.vkscript",
    # No tessellation shader on MoltenVK
    "draw_triangle_list_using_tessellation.vkscript",
    # No std140 support for matrices in SPIRV-Cross
    "compute_mat2x2.vkscript",
    "compute_mat3x2.vkscript",
    # Metal vertex shaders cannot simultaneously write to a buffer and return
    # a value to the rasterizer rdar://48348476
    # https://github.com/KhronosGroup/MoltenVK/issues/527
    "multiple_ssbo_update_with_graphics_pipeline.vkscript",
    "multiple_ubo_update_with_graphics_pipeline.vkscript"
  ]
}

class TestCase:
  def __init__(self, input_path, parse_only):
    self.input_path = input_path
    self.parse_only = parse_only

    self.results = {}

  def IsExpectedFail(self):
    fail_re = re.compile('^.+[.]expect_fail[.][amber|vkscript]')
    return fail_re.match(self.GetInputPath())

  def IsSuppressed(self):
    system = platform.system()
    if system in SUPPRESSIONS.keys():
      return os.path.basename(self.input_path) in SUPPRESSIONS[system]
    return False

  def IsParseOnly(self):
    return self.parse_only

  def GetInputPath(self):
    return self.input_path

  def GetResult(self, fmt):
    return self.results[fmt]

class TestRunner:
  def RunTest(self, tc):
    print "Testing %s" % tc.GetInputPath()

    cmd = [self.options.test_prog_path, '-q']
    if tc.IsParseOnly():
      cmd += ['-p']
    cmd += [tc.GetInputPath()]

    try:
      err = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
      if err != "" and not tc.IsExpectedFail() and not tc.IsSuppressed():
        sys.stdout.write(err)
        return False

    except Exception as e:
      print e.output
      if not tc.IsExpectedFail() and not tc.IsSuppressed():
        print e
      return False

    return True

  def RunTests(self):
    for tc in self.test_cases:
      result = self.RunTest(tc)

      if tc.IsSuppressed():
        self.suppressed.append(tc.GetInputPath())
      else:
        if not tc.IsExpectedFail() and not result:
          self.failures.append(tc.GetInputPath())
        elif tc.IsExpectedFail() and result:
          print("Expected: " + tc.GetInputPath() + " to fail but passed.")
          self.failures.append(tc.GetInputPath())

  def SummarizeResults(self):
    if len(self.failures) > 0:
      self.failures.sort()

      print '\nSummary of Failures:'
      for failure in self.failures:
        print failure

    if len(self.suppressed) > 0:
      self.suppressed.sort()

      print '\nSummary of Suppressions:'
      for suppression in self.suppressed:
        print suppression

    print
    print 'Test cases executed: %d' % len(self.test_cases)
    print '  Successes:  %d' % (len(self.test_cases) - len(self.suppressed) - len(self.failures))
    print '  Failures:   %d' % len(self.failures)
    print '  Suppressed: %d' % len(self.suppressed)
    print

  def Run(self):
    base_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))

    usage = 'usage: %prog [options] (file)'
    parser = optparse.OptionParser(usage=usage)
    parser.add_option('--build-dir',
                      default=os.path.join(base_path, 'out', 'Debug'),
                      help='path to build directory')
    parser.add_option('--test-dir',
                      default=os.path.join(os.path.dirname(__file__), 'cases'),
                      help='path to directory containing test files')
    parser.add_option('--test-prog-path', default=None,
                      help='path to program to test')
    parser.add_option('--parse-only',
                      action="store_true", default=False,
                      help='only parse test cases; do not execute')

    self.options, self.args = parser.parse_args()

    if self.options.test_prog_path == None:
      test_prog = os.path.abspath(os.path.join(self.options.build_dir, 'amber'))
      if not os.path.isfile(test_prog):
        print "Cannot find test program %s" % test_prog
        return 1

      self.options.test_prog_path = test_prog

    if not os.path.isfile(self.options.test_prog_path):
      print "--test-prog-path must point to an executable"
      return 1

    input_file_re = re.compile('^.+[.][amber|vkscript]')
    self.test_cases = []

    if self.args:
      for filename in self.args:
        input_path = os.path.join(self.options.test_dir, filename)
        if not os.path.isfile(input_path):
          print "Cannot find test file '%s'" % filename
          return 1

        self.test_cases.append(TestCase(input_path, self.options.parse_only))

    else:
      for file_dir, _, filename_list in os.walk(self.options.test_dir):
        for input_filename in filename_list:
          if input_file_re.match(input_filename):
            input_path = os.path.join(file_dir, input_filename)
            if os.path.isfile(input_path):
              self.test_cases.append(
                  TestCase(input_path, self.options.parse_only))

    self.failures = []
    self.suppressed = []

    self.RunTests()
    self.SummarizeResults()

    return len(self.failures) != 0

def main():
  runner = TestRunner()
  return runner.Run()

if __name__ == '__main__':
  sys.exit(main())
<|endoftext|>


<commit_before>from celery.task.schedules import crontab
from celery.decorators import periodic_task
from celery.utils.log import get_task_logger

from rapidsms.models import Connection
from rapidsms.router import send

logger = get_task_logger(__name__)

@periodic_task(
    run_every=(crontab(minute='*/1')),
    name="send messages to contacts that become eligible for general event.",
    ignore_result=True
)
def send_msg_general_events():
    """
    Send messages to contacts that become eligible for general events.
    """
    # Test
    conn_obj = Connection.objects.all()[0]
    send("Hello", conn_obj)
<commit_msg>Periodic tasks for general and scheduled events<commit_after>from celery.task.schedules import crontab
from celery.decorators import periodic_task
from celery.utils.log import get_task_logger

from datetime import date

from rapidsms.router import send
from rapidsms.models import Connection
from rapidsms.models import Contact

from events.models import GeneralEvent, ScheduledEvent

logger = get_task_logger(__name__)

@periodic_task(
    run_every=(crontab(minute='*/1')),
    name="send messages to contacts that become eligible for general events.",
    ignore_result=True
)
def send_msg_general_events():
    """
    Send messages to contacts that become eligible for general events.
    """

    contact_all = Contact.objects.all()
    gen_events_all = GeneralEvent.objects.all()

    connections_to_send = Connection.objects.none()

    curr_date = date.today()

    for event in gen_events_all:
        connections_to_send = Connection.objects.none()
        for contact in contact_all:
            if (curr_date - contact.date_of_birth).days == event.days:
                contact_conn = Connection.objects.filter(contact=contact)
                connections_to_send = connections_to_send | contact_conn

        for conn in connections_to_send:
            send(event.msg_to_send, conn)

@periodic_task(
    run_every=(crontab(minute='*/1')),
    name="send messages to contacts that are eligible for scheduled events.",
    ignore_result=True
)
def send_msg_scheduled_events():
    """
    Send messages to contacts that are eligible for scheduled events.
    """

    contact_all = Contact.objects.all()
    scheduled_events_all = ScheduledEvent.objects.all()

    connections_to_send = Connection.objects.none()

    for event in scheduled_events_all:
        connections_to_send = Connection.objects.none()
        for contact in contact_all:
            if (event.event_date - contact.date_of_birth).days >= event.days:
                contact_conn = Connection.objects.filter(contact=contact)
                connections_to_send = connections_to_send | contact_conn

        for conn in connections_to_send:
            send(event.msg_to_send, conn)
<|endoftext|>


<commit_before>from django.utils import unittest
from django import template

from models import Tree, TreeItem
from sitetreeapp import SiteTree, SiteTreeError

class MockRequest(object):

    def __init__(self, path, user_authorized):
        self.path = path
        self.user = MockUser(user_authorized)

class MockUser(object):

    def __init__(self, authorized):
        self.authorized = authorized

    def is_authenticated(self):
        return self.authorized

def get_mock_context(app=None, path=None, user_authorized=False):
    return template.Context({'request': MockRequest(path, user_authorized), 't2_root2_title': 'my_real_title', 'art_id': 10}, current_app=app)

class TreeModelTest(unittest.TestCase):

    def test_create_rename_delete(self):
        tree = Tree(alias='mytree')
        tree.save(force_insert=True)
        self.assertIsNotNone(tree.id)
        self.assertEqual(tree.alias, 'mytree')
        tree.alias = 'not_mytree'
        tree.save(force_update=True)
        self.assertEqual(tree.alias, 'not_mytree')
        tree.delete()
        self.assertIsNone(tree.id)

    def test_unique_aliases(self):
        tree1 = Tree(alias='mytree')
        tree1.save(force_insert=True)
        tree2 = Tree(alias='mytree')
        self.assertRaises(Exception, tree2.save)

class TreeItemModelTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.sitetree = SiteTree()

        t1 = Tree(alias='tree1')
        t1.save(force_insert=True)

        t1_root = TreeItem(title='root', tree=t1, url='/')
        t1_root.save(force_insert=True)

        t1_root_child1 = TreeItem(title='child1', tree=t1, parent=t1_root, url='/about/')
        t1_root_child1.save(force_insert=True)

        t1_root_child2 = TreeItem(title='child2', tree=t1, parent=t1_root, url='articles-list', urlaspattern=True)
        t1_root_child2.save(force_insert=True)

        t1_root_child2_sub1 = TreeItem(title='subchild1', tree=t1, parent=t1_root_child2, url='articles-detailed art_id', urlaspattern=True)
        t1_root_child2_sub1.save(force_insert=True)

        t1_root_child2_sub2 = TreeItem(title='subchild2', tree=t1, parent=t1_root_child2, url='/not_articles/10/')
        t1_root_child2_sub2.save(force_insert=True)

        t2 = Tree(alias='tree2')
        t2.save(force_insert=True)

        t2_root1 = TreeItem(title='{{ t2_root1_title }}', tree=t2, url='/')
        t2_root1.save(force_insert=True)

        t2_root2 = TreeItem(title='put {{ t2_root2_title }} inside', tree=t2, url='/sub/')
        t2_root2.save(force_insert=True)

        t2_root3 = TreeItem(title='for logged in only', tree=t2, url='/some/', access_loggedin=True)
        t2_root3.save(force_insert=True)

        cls.t1 = t1
        cls.t1_root = t1_root
        cls.t1_root_child1 = t1_root_child1
        cls.t1_root_child2 = t1_root_child2
        cls.t1_root_child2_sub1 = t1_root_child2_sub1
        cls.t1_root_child2_sub2 = t1_root_child2_sub2

        cls.t2 = t2
        cls.t2_root1 = t2_root1
        cls.t2_root2 = t2_root2
        cls.t2_root3 = t2_root3

    def test_no_tree(self):
        ti = TreeItem(title='notree_item')
        self.assertRaises(Exception, ti.save)

    def test_create_rename_delete(self):
        ti1 = TreeItem(title='new_root_item', tree=self.t1)
        ti1.save(force_insert=True)
        self.assertIsNotNone(ti1.id)
        self.assertEqual(ti1.title, 'new_root_item')
        ti1.title = 'not_new_root_item'
        ti1.save(force_update=True)
        self.assertEqual(ti1.title, 'not_new_root_item')
        ti1.delete()
        self.assertIsNone(ti1.id)

    def test_context_proc_required(self):
        context = template.Context()
        self.assertRaises(SiteTreeError, self.sitetree.menu, 'tree1', 'trunk', context)

    def test_menu(self):
        menu = self.sitetree.menu('tree1', 'trunk', get_mock_context(path='/'))
        self.assertEqual(len(menu), 1)
        self.assertEqual(menu[0].id, self.t1_root.id)
        self.assertEqual(menu[0].is_current, True)
        self.assertEqual(menu[0].depth, 0)
        self.assertEqual(menu[0].has_children, True)

        menu = self.sitetree.menu('tree2', 'trunk', get_mock_context(path='/sub/'))
        self.assertEqual(len(menu), 2)
        self.assertEqual(menu[0].id, self.t2_root1.id)
        self.assertEqual(menu[1].id, self.t2_root2.id)
        self.assertEqual(menu[0].is_current, False)
        self.assertEqual(menu[1].is_current, True)
        self.assertEqual(menu[0].depth, 0)
        self.assertEqual(menu[1].depth, 0)
        self.assertEqual(menu[0].has_children, False)
        self.assertEqual(menu[1].has_children, False)

    def test_breadcrumbs(self):
        bc1 = self.sitetree.breadcrumbs('tree1', get_mock_context(path='/not_articles/10/'))

        self.assertEqual(len(bc1), 3)

        self.assertEqual(bc1[0].id, self.t1_root.id)
        self.assertEqual(bc1[1].id, self.t1_root_child2.id)
        self.assertEqual(bc1[1].url_resolved, '#unresolved')
        self.assertEqual(bc1[2].id, self.t1_root_child2_sub2.id)

        self.assertEqual(bc1[0].is_current, False)
        self.assertEqual(bc1[1].is_current, False)
        self.assertEqual(bc1[2].is_current, True)

        self.assertEqual(bc1[0].has_children, True)
        self.assertEqual(bc1[1].has_children, True)
        self.assertEqual(bc1[2].has_children, False)

        self.assertEqual(bc1[0].depth, 0)
        self.assertEqual(bc1[1].depth, 1)
        self.assertEqual(bc1[2].depth, 2)

    def test_sitetree(self):
        st1 = self.sitetree.tree('tree1', get_mock_context(path='/articles/'))
        self.assertEqual(len(st1), 1)
        self.assertEqual(st1[0].id, self.t1_root.id)
        self.assertEqual(st1[0].is_current, False)
        self.assertEqual(st1[0].depth, 0)
        self.assertEqual(st1[0].has_children, True)

        st2 = self.sitetree.tree('tree2', get_mock_context(path='/'))
        self.assertEqual(len(st2), 3)
        self.assertEqual(st2[0].id, self.t2_root1.id)
        self.assertEqual(st2[1].id, self.t2_root2.id)

        self.assertEqual(self.t2_root1.access_loggedin, False)
        self.assertEqual(self.t2_root2.access_loggedin, False)
        self.assertEqual(self.t2_root3.access_loggedin, True)

        self.assertEqual(st2[0].title, '{{ t2_root1_title }}')
        self.assertEqual(st2[1].title, 'put {{ t2_root2_title }} inside')

        self.assertEqual(st2[0].title_resolved, '')
        self.assertEqual(st2[1].title_resolved, 'put my_real_title inside')

        self.assertEqual(st2[0].is_current, True)
        self.assertEqual(st2[1].is_current, False)
        self.assertEqual(st2[0].depth, 0)
        self.assertEqual(st2[1].depth, 0)
        self.assertEqual(st2[0].has_children, False)
        self.assertEqual(st2[1].has_children, False)
<commit_msg>* Added tests for 'get_current_page_title' .<commit_after>from django.utils import unittest
from django import template

from models import Tree, TreeItem
from sitetreeapp import SiteTree, SiteTreeError

class MockRequest(object):

    def __init__(self, path, user_authorized):
        self.path = path
        self.user = MockUser(user_authorized)

class MockUser(object):

    def __init__(self, authorized):
        self.authorized = authorized

    def is_authenticated(self):
        return self.authorized

def get_mock_context(app=None, path=None, user_authorized=False):
    return template.Context({'request': MockRequest(path, user_authorized), 't2_root2_title': 'my_real_title', 'art_id': 10}, current_app=app)

class TreeModelTest(unittest.TestCase):

    def test_create_rename_delete(self):
        tree = Tree(alias='mytree')
        tree.save(force_insert=True)
        self.assertIsNotNone(tree.id)
        self.assertEqual(tree.alias, 'mytree')
        tree.alias = 'not_mytree'
        tree.save(force_update=True)
        self.assertEqual(tree.alias, 'not_mytree')
        tree.delete()
        self.assertIsNone(tree.id)

    def test_unique_aliases(self):
        tree1 = Tree(alias='mytree')
        tree1.save(force_insert=True)
        tree2 = Tree(alias='mytree')
        self.assertRaises(Exception, tree2.save)

class TreeItemModelTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.sitetree = SiteTree()

        t1 = Tree(alias='tree1')
        t1.save(force_insert=True)

        t1_root = TreeItem(title='root', tree=t1, url='/')
        t1_root.save(force_insert=True)

        t1_root_child1 = TreeItem(title='child1', tree=t1, parent=t1_root, url='/about/')
        t1_root_child1.save(force_insert=True)

        t1_root_child2 = TreeItem(title='child2', tree=t1, parent=t1_root, url='articles_list', urlaspattern=True)
        t1_root_child2.save(force_insert=True)

        t1_root_child2_sub1 = TreeItem(title='subchild1', tree=t1, parent=t1_root_child2, url='articles_detailed art_id', urlaspattern=True)
        t1_root_child2_sub1.save(force_insert=True)

        t1_root_child2_sub2 = TreeItem(title='subchild2', tree=t1, parent=t1_root_child2, url='/not_articles/10/')
        t1_root_child2_sub2.save(force_insert=True)

        t2 = Tree(alias='tree2')
        t2.save(force_insert=True)

        t2_root1 = TreeItem(title='{{ t2_root1_title }}', tree=t2, url='/')
        t2_root1.save(force_insert=True)

        t2_root2 = TreeItem(title='put {{ t2_root2_title }} inside', tree=t2, url='/sub/')
        t2_root2.save(force_insert=True)

        t2_root3 = TreeItem(title='for logged in only', tree=t2, url='/some/', access_loggedin=True)
        t2_root3.save(force_insert=True)

        cls.t1 = t1
        cls.t1_root = t1_root
        cls.t1_root_child1 = t1_root_child1
        cls.t1_root_child2 = t1_root_child2
        cls.t1_root_child2_sub1 = t1_root_child2_sub1
        cls.t1_root_child2_sub2 = t1_root_child2_sub2

        cls.t2 = t2
        cls.t2_root1 = t2_root1
        cls.t2_root2 = t2_root2
        cls.t2_root3 = t2_root3

    def test_no_tree(self):
        ti = TreeItem(title='notree_item')
        self.assertRaises(Exception, ti.save)

    def test_create_rename_delete(self):
        ti1 = TreeItem(title='new_root_item', tree=self.t1)
        ti1.save(force_insert=True)
        self.assertIsNotNone(ti1.id)
        self.assertEqual(ti1.title, 'new_root_item')
        ti1.title = 'not_new_root_item'
        ti1.save(force_update=True)
        self.assertEqual(ti1.title, 'not_new_root_item')
        ti1.delete()
        self.assertIsNone(ti1.id)

    def test_context_proc_required(self):
        context = template.Context()
        self.assertRaises(SiteTreeError, self.sitetree.menu, 'tree1', 'trunk', context)

    def test_menu(self):
        menu = self.sitetree.menu('tree1', 'trunk', get_mock_context(path='/'))
        self.assertEqual(len(menu), 1)
        self.assertEqual(menu[0].id, self.t1_root.id)
        self.assertEqual(menu[0].is_current, True)
        self.assertEqual(menu[0].depth, 0)
        self.assertEqual(menu[0].has_children, True)

        menu = self.sitetree.menu('tree2', 'trunk', get_mock_context(path='/sub/'))
        self.assertEqual(len(menu), 2)
        self.assertEqual(menu[0].id, self.t2_root1.id)
        self.assertEqual(menu[1].id, self.t2_root2.id)
        self.assertEqual(menu[0].is_current, False)
        self.assertEqual(menu[1].is_current, True)
        self.assertEqual(menu[0].depth, 0)
        self.assertEqual(menu[1].depth, 0)
        self.assertEqual(menu[0].has_children, False)
        self.assertEqual(menu[1].has_children, False)

    def test_breadcrumbs(self):
        bc1 = self.sitetree.breadcrumbs('tree1', get_mock_context(path='/not_articles/10/'))

        self.assertEqual(len(bc1), 3)

        self.assertEqual(bc1[0].id, self.t1_root.id)
        self.assertEqual(bc1[1].id, self.t1_root_child2.id)
        self.assertEqual(bc1[1].url_resolved, '/articles/')
        self.assertEqual(bc1[2].id, self.t1_root_child2_sub2.id)

        self.assertEqual(bc1[0].is_current, False)
        self.assertEqual(bc1[1].is_current, False)
        self.assertEqual(bc1[2].is_current, True)

        self.assertEqual(bc1[0].has_children, True)
        self.assertEqual(bc1[1].has_children, True)
        self.assertEqual(bc1[2].has_children, False)

        self.assertEqual(bc1[0].depth, 0)
        self.assertEqual(bc1[1].depth, 1)
        self.assertEqual(bc1[2].depth, 2)

    def test_page_title(self):
        title = self.sitetree.get_current_page_title('tree1', get_mock_context(path='/articles/'))
        self.assertEqual(title, self.t1_root_child2.title)

        title = self.sitetree.get_current_page_title('tree1', get_mock_context(path='/not_articles/'))
        self.assertEqual(title, '')

    def test_sitetree(self):
        st1 = self.sitetree.tree('tree1', get_mock_context(path='/articles/'))
        self.assertEqual(len(st1), 1)
        self.assertEqual(st1[0].id, self.t1_root.id)
        self.assertEqual(st1[0].is_current, False)
        self.assertEqual(st1[0].depth, 0)
        self.assertEqual(st1[0].has_children, True)

        st2 = self.sitetree.tree('tree2', get_mock_context(path='/'))
        self.assertEqual(len(st2), 3)
        self.assertEqual(st2[0].id, self.t2_root1.id)
        self.assertEqual(st2[1].id, self.t2_root2.id)

        self.assertEqual(self.t2_root1.access_loggedin, False)
        self.assertEqual(self.t2_root2.access_loggedin, False)
        self.assertEqual(self.t2_root3.access_loggedin, True)

        self.assertEqual(st2[0].title, '{{ t2_root1_title }}')
        self.assertEqual(st2[1].title, 'put {{ t2_root2_title }} inside')

        self.assertEqual(st2[0].title_resolved, '')
        self.assertEqual(st2[1].title_resolved, 'put my_real_title inside')

        self.assertEqual(st2[0].is_current, True)
        self.assertEqual(st2[1].is_current, False)
        self.assertEqual(st2[0].depth, 0)
        self.assertEqual(st2[1].depth, 0)
        self.assertEqual(st2[0].has_children, False)
        self.assertEqual(st2[1].has_children, False)
<|endoftext|>


<commit_before>from .models import Event, EventParticipant, EventActivity
from .serializers import EventSerializer, EventSimpleSerializer
from .serializers import EventActivitySerializer
from employees.models import Employee
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.pagination import PageNumberPagination
from rest_framework. permissions import IsAuthenticated
from rest_framework.response import Response

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def my_upcoming_events(request, employee_id):
    """
    Returns the full upcoming events list for employee
    ---
    serializer: events.serializers.EventSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    events = []
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        records = EventParticipant.objects.filter(participant=employee)

        for record in records:
            event = Event.objects.get(pk=record.event.id)
            if event.is_active and event.is_upcoming:
                events.append(event)

        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(events, request)
        serializer = EventSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def local_events(request, employee_id):
    """
    Returns the full upcoming events list for employee location
    ---
    serializer: events.serializers.EventSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        events = Event.objects.filter(location=employee.location, is_active=True, is_upcoming=True)
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(events, request)
        serializer = EventSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def other_location_events(request, employee_id):
    """
    Returns the full upcoming events list for employee location
    ---
    serializer: events.serializers.EventSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    events = []
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        events_list = Event.objects.filter(is_active=True, is_upcoming=True)

        for event in events_list:
            if event.location != employee.location:
                events.append(event)

        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(events, request)
        serializer = EventSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def event_detail(request, employee_id, event_id):
    """
    Return event detail according employee perspective
    ---
    serializer: events.serializers.EventSimpleSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        event = get_object_or_404(Event, pk=event_id)
        employee_registered = EventParticipant.objects.filter(event=event, participant=employee)

        if employee_registered:
            is_registered = True
        else:
            is_registered = False

        data = {"pk": event.id,
                "name": event.name,
                "image": event.image,
                "datetime": event.datetime,
                "address": event.address,
                "description": event.description,
                "is_registered": is_registered}

        serializer = EventSimpleSerializer(data=data)
        if serializer.is_valid():
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['PATCH', ])
@permission_classes((IsAuthenticated,))
def employee_event_registration(request, employee_id, event_id, action):
    """
    Register / unregister employee to event, action could be true or false
    ---
    response_serializer: employees.serializers.EmployeeSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    if request.method == 'PATCH':
        employee = get_object_or_404(Employee, pk=employee_id)
        event = get_object_or_404(Event, pk=event_id)

        employee_registration = EventParticipant.objects.filter(event=event, participant=employee)
        is_registered = False

        if employee_registration:
            if action == 'true':
                is_registered = True
            elif action == 'false':
                employee_registration.delete()
                is_registered = False
            else:
                pass
        else:
            if action == 'true':
                EventParticipant.objects.create(event=event, participant=employee)
                is_registered = True
            else:
                pass

        data = {"pk": event.id,
                "name": event.name,
                "image": event.image,
                "datetime": event.datetime,
                "address": event.address,
                "description": event.description,
                "is_registered": is_registered}

        serializer = EventSimpleSerializer(data=data)
        if serializer.is_valid():
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def event_activities(request, event_id):
    """
    Returns activity list for event
    ---
    serializer: events.serializers.EventActivitySerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        event = get_object_or_404(Event, pk=event_id)
        activities = EventActivity.objects.filter(event=event)
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(activities, request)
        serializer = EventActivitySerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)
<commit_msg>Change serializer on swagger documentation for register / unregister event endpoint<commit_after>from .models import Event, EventParticipant, EventActivity
from .serializers import EventSerializer, EventSimpleSerializer
from .serializers import EventActivitySerializer
from employees.models import Employee
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.pagination import PageNumberPagination
from rest_framework. permissions import IsAuthenticated
from rest_framework.response import Response

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def my_upcoming_events(request, employee_id):
    """
    Returns the full upcoming events list for employee
    ---
    serializer: events.serializers.EventSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    events = []
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        records = EventParticipant.objects.filter(participant=employee)

        for record in records:
            event = Event.objects.get(pk=record.event.id)
            if event.is_active and event.is_upcoming:
                events.append(event)

        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(events, request)
        serializer = EventSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def local_events(request, employee_id):
    """
    Returns the full upcoming events list for employee location
    ---
    serializer: events.serializers.EventSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        events = Event.objects.filter(location=employee.location, is_active=True, is_upcoming=True)
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(events, request)
        serializer = EventSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def other_location_events(request, employee_id):
    """
    Returns the full upcoming events list for employee location
    ---
    serializer: events.serializers.EventSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    events = []
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        events_list = Event.objects.filter(is_active=True, is_upcoming=True)

        for event in events_list:
            if event.location != employee.location:
                events.append(event)

        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(events, request)
        serializer = EventSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def event_detail(request, employee_id, event_id):
    """
    Return event detail according employee perspective
    ---
    serializer: events.serializers.EventSimpleSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        event = get_object_or_404(Event, pk=event_id)
        employee_registered = EventParticipant.objects.filter(event=event, participant=employee)

        if employee_registered:
            is_registered = True
        else:
            is_registered = False

        data = {"pk": event.id,
                "name": event.name,
                "image": event.image,
                "datetime": event.datetime,
                "address": event.address,
                "description": event.description,
                "is_registered": is_registered}

        serializer = EventSimpleSerializer(data=data)
        if serializer.is_valid():
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['PATCH', ])
@permission_classes((IsAuthenticated,))
def employee_event_registration(request, employee_id, event_id, action):
    """
    Register / unregister employee to event, action could be true or false
    ---
    response_serializer: events.serializers.EventSimpleSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    if request.method == 'PATCH':
        employee = get_object_or_404(Employee, pk=employee_id)
        event = get_object_or_404(Event, pk=event_id)

        employee_registration = EventParticipant.objects.filter(event=event, participant=employee)
        is_registered = False

        if employee_registration:
            if action == 'true':
                is_registered = True
            elif action == 'false':
                employee_registration.delete()
                is_registered = False
            else:
                pass
        else:
            if action == 'true':
                EventParticipant.objects.create(event=event, participant=employee)
                is_registered = True
            else:
                pass

        data = {"pk": event.id,
                "name": event.name,
                "image": event.image,
                "datetime": event.datetime,
                "address": event.address,
                "description": event.description,
                "is_registered": is_registered}

        serializer = EventSimpleSerializer(data=data)
        if serializer.is_valid():
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def event_activities(request, event_id):
    """
    Returns activity list for event
    ---
    serializer: events.serializers.EventActivitySerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        event = get_object_or_404(Event, pk=event_id)
        activities = EventActivity.objects.filter(event=event)
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(activities, request)
        serializer = EventActivitySerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)
<|endoftext|>