<commit_before>import smtplib
from email.mime.text import MIMEText
from main import app, db
from flask import jsonify, request, g
from DB.User import User
from flask_jwt_extended import jwt_required, get_jwt_identity

@app.route('/users')
@jwt_required
def show_users():
    user_id = get_jwt_identity()
    current_user = User.query.get(user_id)
    if not current_user or not current_user.admin:
        return jsonify({"error": "Operation not permitted"}), 403
    users = User.query.all()
    userDict = []
    for user in users:
        userDict.append(user.to_dict())
    return jsonify(userDict)

@app.route('/users/<int:id>', methods=["GET"])
@jwt_required
def show_user(id):
    user = User.query.get(id)
    if user is not None:
        return jsonify(user.to_dict())
    else:
        return jsonify({'error': 'User not found'})

@app.route('/users/<int:id>', methods=["PUT","PATCH"])
@jwt_required
def edit_user(id):
    user_id = get_jwt_identity()
    current_user = User.query.get(user_id)
    if not current_user.admin:
        return jsonify({'error': 'Operation not permitted'}), 403

    user = User.query.get(id)
    if not user:
        return jsonify({'error': 'User not found'}), 404

    try:
        for attribute in request.json:
            if attribute in User.get_all_attributes():
                setattr(user, attribute, request.json[attribute])
        db.session.commit()
        return '', 200
    except Exception as error:
        db.session.rollback()
        return jsonify({"error": "Failed to update user: " + str(error)}), 500

@app.route('/users', methods=["POST"])
def add_user():
    for attribute in User.get_required_attributes():
        if not attribute in request.json:
            return jsonify({'error': attribute + ' is required'}), 400
    data = request.json
    new_user = User(data['username'], data['password'], data['email'])
    db.session.add(new_user)
    db.session.commit()
    send_new_user_mail(new_user)
    return '', 201

@app.route('/users/checkUnique', methods=["GET"])
def check_unique_attribute():
    arguments = request.args
    possible_keys = ['username','email']
    if not 'key' in arguments or not 'value' in arguments:
        return jsonify({'error':'"key" and "value" must be given as query parameters'}), 400
    if not arguments['key'] in possible_keys:
        return jsonify({'error':'"key" can be one of the following: ' + ",".join(possible_keys)}), 400
    kwargs = {arguments['key'] : arguments['value']}
    user = User.query.filter_by(**kwargs).first()
    if not user:
        return jsonify({'unique':True}), 200
    else:
        return jsonify({'unique':False}), 200

def send_new_user_mail(user):
    mail_host = app.config['MAIL_HOST']
    mail_port = app.config['MAIL_PORT']
    mail_user = app.config['MAIL_LOGIN_USER']
    mail_pass = app.config['MAIL_LOGIN_PASS']
    mailer = smtplib.SMTP_SSL(mail_host, mail_port)
    mailer.login(mail_user, mail_pass)
    send_new_user_information_mail(user, mailer)
    send_new_user_activation_request(user, mailer)
    mailer.quit()

def send_new_user_information_mail(user, mailer):
    mail_to = user.email
    mail_from = app.config['MAIL_FROM']
    mail_messaage = "Hello {}\n\nThank you for signing up, your account will be activated soon. You will get another mail confirming the account activation.".format(
        user.username)
    message = MIMEText(mail_messaage)
    message["Subject"] = "SignUp on zermatt.patklaey.ch"
    message["From"] = mail_from
    message["To"] = mail_to
    mailer.sendmail(mail_from, mail_to, message.as_string())

def send_new_user_activation_request(user, mailer):
    mail_to = map(lambda admin_account: admin_account.email, User.get_admin_accounts())
    mail_from = app.config['MAIL_FROM']
    mail_messaage = "Hello admins\n\nA new user with username {} just signed up at zermatt.patklaey.ch. Please verify he is allowed to and activate it's account accordingly.".format(
        user.username)
    message = MIMEText(mail_messaage)
    message["Subject"] = "New user on zermatt.patklaey.ch"
    message["From"] = mail_from
    message["To"] = ", ".join(mail_to)
    mailer.sendmail(mail_from, mail_to, message.as_string())
<commit_msg>Allow password change from update user<commit_after>import smtplib
from email.mime.text import MIMEText
from main import app, db
from flask import jsonify, request, g
from DB.User import User
from flask_jwt_extended import jwt_required, get_jwt_identity

@app.route('/users')
@jwt_required
def show_users():
    user_id = get_jwt_identity()
    current_user = User.query.get(user_id)
    if not current_user or not current_user.admin:
        return jsonify({"error": "Operation not permitted"}), 403
    users = User.query.all()
    userDict = []
    for user in users:
        userDict.append(user.to_dict())
    return jsonify(userDict)

@app.route('/users/<int:id>', methods=["GET"])
@jwt_required
def show_user(id):
    user = User.query.get(id)
    if user is not None:
        return jsonify(user.to_dict())
    else:
        return jsonify({'error': 'User not found'})

@app.route('/users/<int:id>', methods=["PUT","PATCH"])
@jwt_required
def edit_user(id):
    user_id = get_jwt_identity()
    current_user = User.query.get(user_id)
    if not current_user.admin:
        return jsonify({'error': 'Operation not permitted'}), 403

    user = User.query.get(id)
    if not user:
        return jsonify({'error': 'User not found'}), 404

    try:
        if "password" in request.json:
            user.hash_password(request.json["password"])
            del request.json["password"]
        for attribute in request.json:
            if attribute in User.get_all_attributes():
                setattr(user, attribute, request.json[attribute])
        db.session.commit()
        return '', 200
    except Exception as error:
        db.session.rollback()
        return jsonify({"error": "Failed to update user: " + str(error)}), 500

@app.route('/users', methods=["POST"])
def add_user():
    for attribute in User.get_required_attributes():
        if not attribute in request.json:
            return jsonify({'error': attribute + ' is required'}), 400
    data = request.json
    new_user = User(data['username'], data['password'], data['email'])
    db.session.add(new_user)
    db.session.commit()
    send_new_user_mail(new_user)
    return '', 201

@app.route('/users/checkUnique', methods=["GET"])
def check_unique_attribute():
    arguments = request.args
    possible_keys = ['username','email']
    if not 'key' in arguments or not 'value' in arguments:
        return jsonify({'error':'"key" and "value" must be given as query parameters'}), 400
    if not arguments['key'] in possible_keys:
        return jsonify({'error':'"key" can be one of the following: ' + ",".join(possible_keys)}), 400
    kwargs = {arguments['key'] : arguments['value']}
    user = User.query.filter_by(**kwargs).first()
    if not user:
        return jsonify({'unique':True}), 200
    else:
        return jsonify({'unique':False}), 200

def send_new_user_mail(user):
    mail_host = app.config['MAIL_HOST']
    mail_port = app.config['MAIL_PORT']
    mail_user = app.config['MAIL_LOGIN_USER']
    mail_pass = app.config['MAIL_LOGIN_PASS']
    mailer = smtplib.SMTP_SSL(mail_host, mail_port)
    mailer.login(mail_user, mail_pass)
    send_new_user_information_mail(user, mailer)
    send_new_user_activation_request(user, mailer)
    mailer.quit()

def send_new_user_information_mail(user, mailer):
    mail_to = user.email
    mail_from = app.config['MAIL_FROM']
    mail_messaage = "Hello {}\n\nThank you for signing up, your account will be activated soon. You will get another mail confirming the account activation.".format(
        user.username)
    message = MIMEText(mail_messaage)
    message["Subject"] = "SignUp on zermatt.patklaey.ch"
    message["From"] = mail_from
    message["To"] = mail_to
    mailer.sendmail(mail_from, mail_to, message.as_string())

def send_new_user_activation_request(user, mailer):
    mail_to = map(lambda admin_account: admin_account.email, User.get_admin_accounts())
    mail_from = app.config['MAIL_FROM']
    mail_messaage = "Hello admins\n\nA new user with username {} just signed up at zermatt.patklaey.ch. Please verify he is allowed to and activate it's account accordingly.".format(
        user.username)
    message = MIMEText(mail_messaage)
    message["Subject"] = "New user on zermatt.patklaey.ch"
    message["From"] = mail_from
    message["To"] = ", ".join(mail_to)
    mailer.sendmail(mail_from, mail_to, message.as_string())
<|endoftext|>


<commit_before>"""
A testcase which accesses *values* in a dll.
"""

import unittest
from ctypes import *

import _ctypes_test

class ValuesTestCase(unittest.TestCase):

    def test_an_integer(self):
        ctdll = CDLL(_ctypes_test.__file__)
        an_integer = c_int.in_dll(ctdll, "an_integer")
        x = an_integer.value
        self.failUnlessEqual(x, ctdll.get_an_integer())
        an_integer.value *= 2
        self.failUnlessEqual(x*2, ctdll.get_an_integer())

    def test_undefined(self):
        ctdll = CDLL(_ctypes_test.__file__)
        self.assertRaises(ValueError, c_int.in_dll, ctdll, "Undefined_Symbol")

    class Win_ValuesTestCase(unittest.TestCase):
        """This test only works when python itself is a dll/shared library"""

        def test_optimizeflag(self):
            # This test accesses the Py_OptimizeFlag intger, which is
            # exported by the Python dll.

            # It's value is set depending on the -O and -OO flags:
            # if not given, it is 0 and __debug__ is 1.
            # If -O is given, the flag is 1, for -OO it is 2.
            # docstrings are also removed in the latter case.
            opt = c_int.in_dll(pydll, "Py_OptimizeFlag").value
            if __debug__:
                self.failUnlessEqual(opt, 0)
            elif ValuesTestCase.__doc__ is not None:
                self.failUnlessEqual(opt, 1)
            else:
                self.failUnlessEqual(opt, 2)

        def test_frozentable(self):
            # Python exports a PyImport_FrozenModules symbol. This is a
            # pointer to an array of struct _frozen entries.  The end of the
            # array is marked by an entry containing a NULL name and zero
            # size.

            # In standard Python, this table contains a __hello__
            # module, and a __phello__ package containing a spam
            # module.
            class struct_frozen(Structure):
                _fields_ = [("name", c_char_p),
                            ("code", POINTER(c_ubyte)),
                            ("size", c_int)]
            FrozenTable = POINTER(struct_frozen)

            ft = FrozenTable.in_dll(pydll, "PyImport_FrozenModules")
            # ft is a pointer to the struct_frozen entries:
            items = []
            for entry in ft:
                # This is dangerous. We *can* iterate over a pointer, but
                # the loop will not terminate (maybe with an access
                # violation;-) because the pointer instance has no size.
                if entry.name is None:
                    break
                items.append((entry.name, entry.size))
            import sys
            if sys.version_info[:2] >= (2, 3):
                expected = [("__hello__", 104), ("__phello__", -104), ("__phello__.spam", 104)]
            else:
                expected = [("__hello__", 100), ("__phello__", -100), ("__phello__.spam", 100)]
            self.failUnlessEqual(items, expected)

            from ctypes import _pointer_type_cache
            del _pointer_type_cache[struct_frozen]

        def test_undefined(self):
            self.assertRaises(ValueError, c_int.in_dll, pydll, "Undefined_Symbol")

if __name__ == '__main__':
    unittest.main()
<commit_msg>This test checks and modifies the value of an integer stored in a dll. Restore the original value after modifying it so that subsequent tests will not fail.  Fixes the failure in issue 1597.<commit_after>"""
A testcase which accesses *values* in a dll.
"""

import unittest
from ctypes import *

import _ctypes_test

class ValuesTestCase(unittest.TestCase):

    def test_an_integer(self):
        ctdll = CDLL(_ctypes_test.__file__)
        an_integer = c_int.in_dll(ctdll, "an_integer")
        x = an_integer.value
        self.failUnlessEqual(x, ctdll.get_an_integer())
        an_integer.value *= 2
        self.failUnlessEqual(x*2, ctdll.get_an_integer())
        an_integer.value = x
        self.failUnlessEqual(x, ctdll.get_an_integer())

    def test_undefined(self):
        ctdll = CDLL(_ctypes_test.__file__)
        self.assertRaises(ValueError, c_int.in_dll, ctdll, "Undefined_Symbol")

    class Win_ValuesTestCase(unittest.TestCase):
        """This test only works when python itself is a dll/shared library"""

        def test_optimizeflag(self):
            # This test accesses the Py_OptimizeFlag intger, which is
            # exported by the Python dll.

            # It's value is set depending on the -O and -OO flags:
            # if not given, it is 0 and __debug__ is 1.
            # If -O is given, the flag is 1, for -OO it is 2.
            # docstrings are also removed in the latter case.
            opt = c_int.in_dll(pydll, "Py_OptimizeFlag").value
            if __debug__:
                self.failUnlessEqual(opt, 0)
            elif ValuesTestCase.__doc__ is not None:
                self.failUnlessEqual(opt, 1)
            else:
                self.failUnlessEqual(opt, 2)

        def test_frozentable(self):
            # Python exports a PyImport_FrozenModules symbol. This is a
            # pointer to an array of struct _frozen entries.  The end of the
            # array is marked by an entry containing a NULL name and zero
            # size.

            # In standard Python, this table contains a __hello__
            # module, and a __phello__ package containing a spam
            # module.
            class struct_frozen(Structure):
                _fields_ = [("name", c_char_p),
                            ("code", POINTER(c_ubyte)),
                            ("size", c_int)]
            FrozenTable = POINTER(struct_frozen)

            ft = FrozenTable.in_dll(pydll, "PyImport_FrozenModules")
            # ft is a pointer to the struct_frozen entries:
            items = []
            for entry in ft:
                # This is dangerous. We *can* iterate over a pointer, but
                # the loop will not terminate (maybe with an access
                # violation;-) because the pointer instance has no size.
                if entry.name is None:
                    break
                items.append((entry.name, entry.size))
            import sys
            if sys.version_info[:2] >= (2, 3):
                expected = [("__hello__", 104), ("__phello__", -104), ("__phello__.spam", 104)]
            else:
                expected = [("__hello__", 100), ("__phello__", -100), ("__phello__.spam", 100)]
            self.failUnlessEqual(items, expected)

            from ctypes import _pointer_type_cache
            del _pointer_type_cache[struct_frozen]

        def test_undefined(self):
            self.assertRaises(ValueError, c_int.in_dll, pydll, "Undefined_Symbol")

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


<commit_before>#
# Author    : Manuel Bernal Llinares
# Project   : trackhub-creator
# Timestamp : 03-07-2017 16:50
# ---
# © 2017 Manuel Bernal Llinares <mbdebian@gmail.com>
# All rights reserved.
#

"""
This module contains Ensembl models used as Entities and DAO/Services
"""

import config_manager

class Species:
    def __init__(self, ensembl_species_entry):
        self.__ensembl_species_entry = ensembl_species_entry
        self.__logger = config_manager.get_app_config_manager().get_logger_for(__name__)

    def _get_logger(self):
        return self.__logger

    def get_division(self):
        # TODO
        pass

    def get_ncbi_taxonomy_id(self):
        # TODO
        pass

    def get_name(self):
        # TODO
        pass

    def get_ensembl_release(self):
        # TODO
        pass

    def get_display_name(self):
        # TODO
        pass

    def get_assembly_accession(self):
        # TODO
        pass

    def get_strain_collection(self):
        # TODO
        pass

    def get_common_name(self):
        # TODO
        pass

class SpeciesService:
    # TODO
    pass
<commit_msg>get strain, placeholder<commit_after>#
# Author    : Manuel Bernal Llinares
# Project   : trackhub-creator
# Timestamp : 03-07-2017 16:50
# ---
# © 2017 Manuel Bernal Llinares <mbdebian@gmail.com>
# All rights reserved.
#

"""
This module contains Ensembl models used as Entities and DAO/Services
"""

import config_manager

class Species:
    def __init__(self, ensembl_species_entry):
        self.__ensembl_species_entry = ensembl_species_entry
        self.__logger = config_manager.get_app_config_manager().get_logger_for(__name__)

    def _get_logger(self):
        return self.__logger

    def get_division(self):
        # TODO
        pass

    def get_ncbi_taxonomy_id(self):
        # TODO
        pass

    def get_name(self):
        # TODO
        pass

    def get_ensembl_release(self):
        # TODO
        pass

    def get_display_name(self):
        # TODO
        pass

    def get_assembly_accession(self):
        # TODO
        pass

    def get_strain_collection(self):
        # TODO
        pass

    def get_common_name(self):
        # TODO
        pass

    def get_strain(self):
        # TODO
        pass

class SpeciesService:
    # TODO
    pass
<|endoftext|>


<commit_before>"""
The test suite is developed to be environment and format
agnostic. Environment developers only need to implement
a function that provides objects for testing and a simple
Python script that sends the function to the test suite.

##########################
Environment Implementation
##########################

The main thing that an environment needs to implement is
the test object generator. This should create an object
for the requested class identifier. ::

  def MyAppObjectGenerator(cls):
    obj = myApp.foo.bar.something.hi(cls)
    return obj

The class identifiers are as follows:

* font
* info
* groups
* kerning
* features
* lib
* layer
* glyph
* contour
* segment
* bpoint
* point
* component
* anchor
* image
* guideline

If an environment does not allow orphan objects, it is up
to the environment to retain any necessary parent objects
during testing.

Once an environment has developed this function, all that
remains is to pass the function to the test runner::

  from fontParts.test import testEnvironment

  if __name__ == "__main__":
    testEnvironment(MyAppObjectGenerator)

This can then be executed and the report will be printed.

==============
Important Note
==============

It is up to each environment to ensure that the bridge from
the environment's native objects to the fontParts wrappers
is working properly. This has to be done on an environment
by environment basis since the native objects are not
consistently implemented.

###################
Test Implementation
###################

The test cases are located in ``fontParts.test.test_*``.

==============
Test Structure
==============

::

import unittest
from fontParts.base import FontPartsError

class TestFoo(unittest.TestObject):

    # --------------
    # Section Header
    # --------------

    def getFoo_generic(self):
      # code for building the object

    def test_bar(self):
        # Code for testing the bar attribute.

    def test_changeSomething(self):
        # Code for testing the changeSomething method.

================
Test Definitions
================

The test definitions should be developed by following
the `FontParts API documentation <http://fontparts.readthedocs.io/en/latest/index.html>`.
These break down into two categories.

#. attributes
#. methods

These will be covered in detail below. In general follow
these guidelines when developing

#. Keep the test focused on what is relevant to what
   is being tested. Don't test file saving within an
   attribute test in a sub-sub-sub-sub object.
#. Make the tests as atomic as possible. Don't modify
   lots of parts of an object during a single test.
   That makes the tests very hard to debug.
#. Keep the code clear and concise so that it is easy
   to see what is being tested. Add documentation
   to clarify anything that is ambiguious. Try to
   imagine someone trying to debug a failure of this
   test five years from now. Will they be able to
   tell what is going on in the code?
#. If testing an edge case, make notes defining where
   this situation is happening, why it is important
   and so on. Edge case tests often are hyper-specific
   to one version of one environment and thus have
   a limited lifespan. This needs to be made clear
   for future reference.
#. Test valid and invalid input. The base implementation's
   validators define what is valid and invalid. Use this
   as a reference.

Testing Attributes
------------------

Attribute testing uses the method name structure ``test_attributeName``.
If more than one method is needed due to length or
complexity, the additional methods use the name
structure ``test_attributeNameDescriptionOfWhatThisTests``.

::

    def test_bar(self):
        foo, unrequested = self.getFoo_generic()
        # get
        self.assertEqual(
            foo.bar,
            "barbarbar"
        )
        # set: valid data
        foo.bar = "heyheyhey"
        self.assertEqual(
            foo.bar,
            "heyheyhey"
        )
        # set: invalid data
        with self.assertRaises(FontPartsError):
            foo.bar = 123

    def test_barSettingNoneShouldFail(self):
        foo, unrequested = self.getFoo_barNontShouldFail()
        with self.assertRaises(FontPartsError):
            foo.bar = None

Getting
^^^^^^^

When testing getting an attribute, test the following:

* All valid return data types. Use the case definitions
  to specify these.
* (How should invalid types be handled? Is that completely
  the responsibility of the environment?)

Setting
^^^^^^^

When testing setting an attribute, test the following:

* All valid input data types. For example if setting
  accepts a number, test int and float. If pos/neg
  values are allowed, test both.
* A representative sample of invalid data types/values.

If an attribute does not support setting, it should
be tested to make sure that an attempt to set raises
the appropriate error.

Testing Methods
---------------

Testing methods should be done atomically, modifying
a single argument at a time. For example, if a method
takes x and y arguments, test each of these as
independently as possible. The following should be
tested for each argument:

* All valid input data types. For example if setting
  accepts a number, test int and float. If pos/neg
  values are allowed, test both.
* A representative sample of invalid data types/values.

::

    def test_changeSomething(self):
        bar, unrequested = self.getBar_something()
        bar.changeSomething(x=100, y=100)
        self.assertEqual(
            bar.thing,
            (100, 100)
        )
        with self.assertRaises(FontPartsError):
           bar.changeSomething(x=None, y=100)
        with self.assertRaises(FontPartsError):
           bar.changeSomething(x=100, y=None)

===================
Objects for Testing
===================

Objects for testing are defined in methods with the name
structure ``getFoo_description``. The base object will be
generated by the environment by calling
``self.objectGenerator("classIdentifier")``. This will return
a fontParts wrapped object ready for population and testing.
It will also return a list of objects that were/are required
for generating/retaining the requested object. For example,
if an environment doesn't support orphan glyphs, the
unrequested list may contain a parent font. The objects
in the unrequested list must not be used within tests.

::

  def getFoo_generic(self):
    foo = self.objectGenerator("foo")
    foo.bar = "barbarbar"
    return foo, []

=====
To Do
=====

- Establish tests for pen protocol in test_glyph.

"""

from __future__ import print_function
import unittest
from fontParts.test import test_font
from fontParts.test import test_info
from fontParts.test import test_groups
from fontParts.test import test_kerning
from fontParts.test import test_features
from fontParts.test import test_layer
from fontParts.test import test_glyph
from fontParts.test import test_contour
from fontParts.test import test_segment
from fontParts.test import test_bPoint
from fontParts.test import test_point
from fontParts.test import test_component
from fontParts.test import test_anchor
from fontParts.test import test_image
from fontParts.test import test_guideline

def testEnvironment(objectGenerator):
    modules = [
        test_font,
        test_info,
        test_groups,
        test_kerning,
        test_features,
        test_layer,
        test_glyph,
        test_contour,
        test_segment,
        test_bPoint,
        test_point,
        test_component,
        test_anchor,
        test_image,
        test_guideline
    ]
    loader = unittest.TestLoader()
    for module in modules:
        print()
        print()
        moduleName = module.__name__
        print(moduleName)
        print("-" * 70)
        suite = loader.loadTestsFromModule(module)
        _setObjectGenerator(suite, objectGenerator)
        runner = unittest.TextTestRunner()
        runner.run(suite)

def _setObjectGenerator(suite, objectGenerator):
    for i in suite:
        if isinstance(i, unittest.TestSuite):
            _setObjectGenerator(i, objectGenerator)
        else:
            i.objectGenerator = objectGenerator
<commit_msg>Consolidate the module tests so that the output is more readable.<commit_after>"""
The test suite is developed to be environment and format
agnostic. Environment developers only need to implement
a function that provides objects for testing and a simple
Python script that sends the function to the test suite.

##########################
Environment Implementation
##########################

The main thing that an environment needs to implement is
the test object generator. This should create an object
for the requested class identifier. ::

  def MyAppObjectGenerator(cls):
    obj = myApp.foo.bar.something.hi(cls)
    return obj

The class identifiers are as follows:

* font
* info
* groups
* kerning
* features
* lib
* layer
* glyph
* contour
* segment
* bpoint
* point
* component
* anchor
* image
* guideline

If an environment does not allow orphan objects, it is up
to the environment to retain any necessary parent objects
during testing.

Once an environment has developed this function, all that
remains is to pass the function to the test runner::

  from fontParts.test import testEnvironment

  if __name__ == "__main__":
    testEnvironment(MyAppObjectGenerator)

This can then be executed and the report will be printed.

==============
Important Note
==============

It is up to each environment to ensure that the bridge from
the environment's native objects to the fontParts wrappers
is working properly. This has to be done on an environment
by environment basis since the native objects are not
consistently implemented.

###################
Test Implementation
###################

The test cases are located in ``fontParts.test.test_*``.

==============
Test Structure
==============

::

import unittest
from fontParts.base import FontPartsError

class TestFoo(unittest.TestObject):

    # --------------
    # Section Header
    # --------------

    def getFoo_generic(self):
      # code for building the object

    def test_bar(self):
        # Code for testing the bar attribute.

    def test_changeSomething(self):
        # Code for testing the changeSomething method.

================
Test Definitions
================

The test definitions should be developed by following
the `FontParts API documentation <http://fontparts.readthedocs.io/en/latest/index.html>`.
These break down into two categories.

#. attributes
#. methods

These will be covered in detail below. In general follow
these guidelines when developing

#. Keep the test focused on what is relevant to what
   is being tested. Don't test file saving within an
   attribute test in a sub-sub-sub-sub object.
#. Make the tests as atomic as possible. Don't modify
   lots of parts of an object during a single test.
   That makes the tests very hard to debug.
#. Keep the code clear and concise so that it is easy
   to see what is being tested. Add documentation
   to clarify anything that is ambiguious. Try to
   imagine someone trying to debug a failure of this
   test five years from now. Will they be able to
   tell what is going on in the code?
#. If testing an edge case, make notes defining where
   this situation is happening, why it is important
   and so on. Edge case tests often are hyper-specific
   to one version of one environment and thus have
   a limited lifespan. This needs to be made clear
   for future reference.
#. Test valid and invalid input. The base implementation's
   validators define what is valid and invalid. Use this
   as a reference.

Testing Attributes
------------------

Attribute testing uses the method name structure ``test_attributeName``.
If more than one method is needed due to length or
complexity, the additional methods use the name
structure ``test_attributeNameDescriptionOfWhatThisTests``.

::

    def test_bar(self):
        foo, unrequested = self.getFoo_generic()
        # get
        self.assertEqual(
            foo.bar,
            "barbarbar"
        )
        # set: valid data
        foo.bar = "heyheyhey"
        self.assertEqual(
            foo.bar,
            "heyheyhey"
        )
        # set: invalid data
        with self.assertRaises(FontPartsError):
            foo.bar = 123

    def test_barSettingNoneShouldFail(self):
        foo, unrequested = self.getFoo_barNontShouldFail()
        with self.assertRaises(FontPartsError):
            foo.bar = None

Getting
^^^^^^^

When testing getting an attribute, test the following:

* All valid return data types. Use the case definitions
  to specify these.
* (How should invalid types be handled? Is that completely
  the responsibility of the environment?)

Setting
^^^^^^^

When testing setting an attribute, test the following:

* All valid input data types. For example if setting
  accepts a number, test int and float. If pos/neg
  values are allowed, test both.
* A representative sample of invalid data types/values.

If an attribute does not support setting, it should
be tested to make sure that an attempt to set raises
the appropriate error.

Testing Methods
---------------

Testing methods should be done atomically, modifying
a single argument at a time. For example, if a method
takes x and y arguments, test each of these as
independently as possible. The following should be
tested for each argument:

* All valid input data types. For example if setting
  accepts a number, test int and float. If pos/neg
  values are allowed, test both.
* A representative sample of invalid data types/values.

::

    def test_changeSomething(self):
        bar, unrequested = self.getBar_something()
        bar.changeSomething(x=100, y=100)
        self.assertEqual(
            bar.thing,
            (100, 100)
        )
        with self.assertRaises(FontPartsError):
           bar.changeSomething(x=None, y=100)
        with self.assertRaises(FontPartsError):
           bar.changeSomething(x=100, y=None)

===================
Objects for Testing
===================

Objects for testing are defined in methods with the name
structure ``getFoo_description``. The base object will be
generated by the environment by calling
``self.objectGenerator("classIdentifier")``. This will return
a fontParts wrapped object ready for population and testing.
It will also return a list of objects that were/are required
for generating/retaining the requested object. For example,
if an environment doesn't support orphan glyphs, the
unrequested list may contain a parent font. The objects
in the unrequested list must not be used within tests.

::

  def getFoo_generic(self):
    foo = self.objectGenerator("foo")
    foo.bar = "barbarbar"
    return foo, []

=====
To Do
=====

- Establish tests for pen protocol in test_glyph.

"""

from __future__ import print_function
import unittest
from fontParts.test import test_font
from fontParts.test import test_info
from fontParts.test import test_groups
from fontParts.test import test_kerning
from fontParts.test import test_features
from fontParts.test import test_layer
from fontParts.test import test_glyph
from fontParts.test import test_contour
from fontParts.test import test_segment
from fontParts.test import test_bPoint
from fontParts.test import test_point
from fontParts.test import test_component
from fontParts.test import test_anchor
from fontParts.test import test_image
from fontParts.test import test_guideline

def testEnvironment(objectGenerator):
    modules = [
        test_font,
        test_info,
        test_groups,
        test_kerning,
        test_features,
        test_layer,
        test_glyph,
        test_contour,
        test_segment,
        test_bPoint,
        test_point,
        test_component,
        test_anchor,
        test_image,
        test_guideline
    ]
    globalSuite = unittest.TestSuite()
    loader = unittest.TestLoader()
    for module in modules:
        suite = loader.loadTestsFromModule(module)
        _setObjectGenerator(suite, objectGenerator)
        globalSuite.addTest(suite)
    runner = unittest.TextTestRunner()
    runner.run(globalSuite)

def _setObjectGenerator(suite, objectGenerator):
    for i in suite:
        if isinstance(i, unittest.TestSuite):
            _setObjectGenerator(i, objectGenerator)
        else:
            i.objectGenerator = objectGenerator
<|endoftext|>


<commit_before>from test.test_support import run_unittest, open_urlresource
import unittest

import sys
import os
from unicodedata import normalize

TESTDATAFILE = "NormalizationTest" + os.extsep + "txt"
TESTDATAURL = "http://www.unicode.org/Public/5.1.0/ucd/" + TESTDATAFILE

class RangeError(Exception):
    pass

def NFC(str):
    return normalize("NFC", str)

def NFKC(str):
    return normalize("NFKC", str)

def NFD(str):
    return normalize("NFD", str)

def NFKD(str):
    return normalize("NFKD", str)

def unistr(data):
    data = [int(x, 16) for x in data.split(" ")]
    for x in data:
        if x > sys.maxunicode:
            raise RangeError
    return u"".join([unichr(x) for x in data])

class NormalizationTest(unittest.TestCase):
    def test_main(self):
        part1_data = {}
        for line in open_urlresource(TESTDATAURL):
            if '#' in line:
                line = line.split('#')[0]
            line = line.strip()
            if not line:
                continue
            if line.startswith("@Part"):
                part = line.split()[0]
                continue
            if part == "@Part3":
                # XXX we don't support PRI #29 yet, so skip these tests for now
                continue
            try:
                c1,c2,c3,c4,c5 = [unistr(x) for x in line.split(';')[:-1]]
            except RangeError:
                # Skip unsupported characters;
                # try atleast adding c1 if we are in part1
                if part == "@Part1":
                    try:
                        c1 = unistr(line.split(';')[0])
                    except RangeError:
                        pass
                    else:
                        part1_data[c1] = 1
                continue

            # Perform tests
            self.failUnless(c2 ==  NFC(c1) ==  NFC(c2) ==  NFC(c3), line)
            self.failUnless(c4 ==  NFC(c4) ==  NFC(c5), line)
            self.failUnless(c3 ==  NFD(c1) ==  NFD(c2) ==  NFD(c3), line)
            self.failUnless(c5 ==  NFD(c4) ==  NFD(c5), line)
            self.failUnless(c4 == NFKC(c1) == NFKC(c2) == \
                            NFKC(c3) == NFKC(c4) == NFKC(c5),
                            line)
            self.failUnless(c5 == NFKD(c1) == NFKD(c2) == \
                            NFKD(c3) == NFKD(c4) == NFKD(c5),
                            line)

            # Record part 1 data
            if part == "@Part1":
                part1_data[c1] = 1

        # Perform tests for all other data
        for c in range(sys.maxunicode+1):
            X = unichr(c)
            if X in part1_data:
                continue
            self.failUnless(X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X), c)

    def test_bug_834676(self):
        # Check for bug 834676
        normalize('NFC', u'\ud55c\uae00')

def test_main():
    # Hit the exception early
    open_urlresource(TESTDATAURL)
    run_unittest(NormalizationTest)

if __name__ == "__main__":
    test_main()
<commit_msg>Read unidata_version from unicodedata module. Delete old NormalizationTest.txt if it doesn't match unidata_version.<commit_after>from test.test_support import run_unittest, open_urlresource
import unittest

import sys
import os
from unicodedata import normalize, unidata_version

TESTDATAFILE = "NormalizationTest" + os.extsep + "txt"
TESTDATAURL = "http://www.unicode.org/Public/" + unidata_version + "/ucd/" + TESTDATAFILE

if os.path.exists(TESTDATAFILE):
    f = open(TESTDATAFILE)
    l = f.readline()
    f.close()
    if not unidata_version in l:
        os.unlink(TESTDATAFILE)

class RangeError(Exception):
    pass

def NFC(str):
    return normalize("NFC", str)

def NFKC(str):
    return normalize("NFKC", str)

def NFD(str):
    return normalize("NFD", str)

def NFKD(str):
    return normalize("NFKD", str)

def unistr(data):
    data = [int(x, 16) for x in data.split(" ")]
    for x in data:
        if x > sys.maxunicode:
            raise RangeError
    return u"".join([unichr(x) for x in data])

class NormalizationTest(unittest.TestCase):
    def test_main(self):
        part1_data = {}
        for line in open_urlresource(TESTDATAURL):
            if '#' in line:
                line = line.split('#')[0]
            line = line.strip()
            if not line:
                continue
            if line.startswith("@Part"):
                part = line.split()[0]
                continue
            if part == "@Part3":
                # XXX we don't support PRI #29 yet, so skip these tests for now
                continue
            try:
                c1,c2,c3,c4,c5 = [unistr(x) for x in line.split(';')[:-1]]
            except RangeError:
                # Skip unsupported characters;
                # try atleast adding c1 if we are in part1
                if part == "@Part1":
                    try:
                        c1 = unistr(line.split(';')[0])
                    except RangeError:
                        pass
                    else:
                        part1_data[c1] = 1
                continue

            # Perform tests
            self.failUnless(c2 ==  NFC(c1) ==  NFC(c2) ==  NFC(c3), line)
            self.failUnless(c4 ==  NFC(c4) ==  NFC(c5), line)
            self.failUnless(c3 ==  NFD(c1) ==  NFD(c2) ==  NFD(c3), line)
            self.failUnless(c5 ==  NFD(c4) ==  NFD(c5), line)
            self.failUnless(c4 == NFKC(c1) == NFKC(c2) == \
                            NFKC(c3) == NFKC(c4) == NFKC(c5),
                            line)
            self.failUnless(c5 == NFKD(c1) == NFKD(c2) == \
                            NFKD(c3) == NFKD(c4) == NFKD(c5),
                            line)

            # Record part 1 data
            if part == "@Part1":
                part1_data[c1] = 1

        # Perform tests for all other data
        for c in range(sys.maxunicode+1):
            X = unichr(c)
            if X in part1_data:
                continue
            self.failUnless(X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X), c)

    def test_bug_834676(self):
        # Check for bug 834676
        normalize('NFC', u'\ud55c\uae00')

def test_main():
    # Hit the exception early
    open_urlresource(TESTDATAURL)
    run_unittest(NormalizationTest)

if __name__ == "__main__":
    test_main()
<|endoftext|>


<commit_before># media-service-demo
#
# Copyright (C) 2012 Intel Corporation. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU Lesser General Public License,
# version 2.1, as published by the Free Software Foundation.
#
# This program is distributed in the hope it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
#
# Mark Ryan <mark.d.ryan@intel.com>
#

import pygtk
pygtk.require('2.0')
import glib
import gtk
import pygst
pygst.require("0.10")
import gst
import datetime

from msd_utils import *

class PlayWindowBase(object):

    def __init__(self, name, url, close_window):
        self.__name = name
        self.__url  = url
        self.__close_window = close_window

        self.__container = gtk.VBox(False, 0)
        self.drawing_area = gtk.DrawingArea()
        self.private_area = gtk.VBox(True, 0)
        self.ok_button = gtk.Button("Close")
        self.ok_button.connect("clicked", self.quit)
        self.__container.pack_start(self.drawing_area, True, True, 0)
        self.__container.pack_start(self.private_area, False, False, 0)
        self.__container.pack_start(self.ok_button, False, False, 0)

    def quit(self, button):
        self.__close_window()

    def get_container(self):
        return self.__container

    def cancel_playback(self):
        pass

    def draw_image(self, image):
        x = 0
        y = 0
        gc = self.drawing_area.get_style().fg_gc[gtk.STATE_NORMAL]
        rect = self.drawing_area.get_allocation()
        width_scale = image.get_width() / float(rect.width)
        height_scale = image.get_height() / float(rect.height)
        if ((width_scale < 1.0 and height_scale < 1.0) or
            (width_scale >= 1.0 and height_scale >= 1.0)):
            if width_scale < height_scale:
                divisor = height_scale
                x = (rect.width - int(image.get_width() / divisor)) / 2
            else:
                divisor = width_scale
                y = (rect.height - int(image.get_height() / divisor)) / 2
        elif width_scale > 1.0:
            divisor = width_scale
            y = (rect.height - int(image.get_height() / divisor)) / 2
        else:
            divisor = height_scale
            x = (rect.width - int(image.get_width() / divisor)) / 2

        scaled_image = image.scale_simple(int(image.get_width() / divisor),
                                          int(image.get_height() / divisor),
                                          gtk.gdk.INTERP_BILINEAR)
        self.drawing_area.window.draw_pixbuf(gc, scaled_image, 0, 0, x,
                                             y, -1, -1)

class PlayWindowImage(PlayWindowBase):

    def __init__(self, name, url, close_window):
        PlayWindowBase.__init__(self, name, url, close_window)
        try:
            image = image_from_file(url)
            self.__image = image.get_pixbuf()
            self.drawing_area.connect("expose-event", self.__draw)
        except Exception:
            pass

        self.get_container().show_all()

    def __draw(self, area, event):
        self.draw_image(self.__image)
        return True

class GStreamerWindow(PlayWindowBase):

    def __init__(self, name, url, close_window):
        PlayWindowBase.__init__(self, name, url, close_window)

        self.player = gst.element_factory_make("playbin2", "player")
        gsbus = self.player.get_bus()
        gsbus.add_signal_watch()
        gsbus.connect("message", self.gs_message_cb)

        self.player.set_property("uri", url)

        button_bar = gtk.HBox(True, 0)

        self.__play_pause_button = gtk.Button()
        self.__play_pause_button.connect("clicked", self.__play_pause)
        self.__play_pause_image = gtk.Image()
        self.__play_pause_image.set_from_stock(gtk.STOCK_MEDIA_PAUSE,
                                               gtk.ICON_SIZE_BUTTON)
        self.__play_pause_button.add(self.__play_pause_image)

        self.__scale = gtk.HScale()

        button_bar.pack_start(self.__play_pause_button, True, False, 0)

        self.private_area.pack_start(self.__scale, False, False, 0)
        self.private_area.pack_start(button_bar, False, False, 0)

        self.get_container().show_all()
        self.__scale.hide()
        self.__duration = -1
        self.__update_pos_id = 0
        self.__adjustment = None
        self.__state = gst.STATE_NULL
        self.player.set_state(gst.STATE_PLAYING)

    def __play_pause(self, button):
        if (self.__state == gst.STATE_PLAYING):
            self.player.set_state(gst.STATE_PAUSED)
        else:
            self.player.set_state(gst.STATE_PLAYING)

    def __update_pos(self, user_data):
        try:
            pos = self.player.query_position(gst.FORMAT_TIME, None)[0]
            if pos != -1:
                pos = pos / 1000000000.0
                self.__adjustment.set_value(pos)
        except Exception:
            pass
        return True

    def cancel_playback(self):
        self.player.set_state(gst.STATE_NULL)

    def quit(self, button):
        self.player.set_state(gst.STATE_NULL)
        PlayWindowBase.quit(self, button)

    def __adjusted(self, adjustment):
        (ret, state, pending) = self.player.get_state()
        if state != gst.STATE_PLAYING:
            seek_pos = adjustment.get_value() * 1000000000
            self.player.seek_simple(gst.FORMAT_TIME, gst.SEEK_FLAG_FLUSH,
                                      seek_pos)

    def __format_time(self, scale, value):
        pos = int(self.__adjustment.get_value())
        return str(datetime.timedelta(seconds=pos))

    def __update_ui(self):
        if self.__duration == -1 and (self.__state == gst.STATE_PLAYING or
                                      self.__state == gst.STATE_PAUSED):
           try:
               duration = self.player.query_duration(gst.FORMAT_TIME,
                                    None)[0]
               if duration != -1:
                   self.__duration  = duration / 1000000000
                   self.__adjustment = gtk.Adjustment(0, 0,
                                                      self.__duration,
                                                      .5, .5, 0)
                   self.__scale.set_adjustment(self.__adjustment)
                   self.__scale.set_sensitive(False)
                   self.__adjustment.connect("value-changed",
                                             self.__adjusted)
                   self.__scale.connect("format-value", self.__format_time)
                   self.__scale.show()
           except Exception:
               pass

        if self.__state == gst.STATE_PLAYING:
            self.__play_pause_image.set_from_stock(gtk.STOCK_MEDIA_PAUSE,
                                                   gtk.ICON_SIZE_BUTTON)
            self.__scale.set_sensitive(False)
            if self.__update_pos_id == 0:
                self.__update_pos_id = glib.timeout_add(500,
                                                        self.__update_pos,
                                                        None)
        else:
            self.__play_pause_image.set_from_stock(gtk.STOCK_MEDIA_PLAY,
                                                   gtk.ICON_SIZE_BUTTON)
            self.__scale.set_sensitive(True)
            if self.__update_pos_id != 0:
                glib.source_remove(self.__update_pos_id)
                self.__update_pos_id = 0

    def gs_message_cb(self, bus, message):
        if message.type == gst.MESSAGE_STATE_CHANGED:
            (old, state, pending) =  message.parse_state_changed()
            if self.__state == state:
                return

            self.__state = state
            self.__update_ui ()

class PlayWindowAudio(GStreamerWindow):

    def __init__(self, name, url, album_art_url, close_window):
        GStreamerWindow.__init__(self, name, url, close_window)

        if album_art_url:
            try:
                image = image_from_file(album_art_url)
                self.__image = image.get_pixbuf()
                self.drawing_area.connect("expose-event", self.__draw)
            except Exception:
                pass

    def __draw(self, area, event):
        self.draw_image(self.__image)
        return True

class PlayWindowVideo(GStreamerWindow):

    def __init__(self, name, url, close_window):
        GStreamerWindow.__init__(self, name, url, close_window)

        gsbus = self.player.get_bus()
        gsbus.enable_sync_message_emission()
        gsbus.connect("sync-message::element", self.gs_sync_message_cb)

    def gs_sync_message_cb(self, bus, message):
        if message.structure != None and (message.structure.get_name() ==
                                          "prepare-xwindow-id"):
            message.src.set_property("force-aspect-ratio", True)
            gtk.gdk.threads_enter()
            message.src.set_xwindow_id(self.drawing_area.window.xid)
            gtk.gdk.threads_leave()
<commit_msg>[Player] Fix seeking<commit_after># media-service-demo
#
# Copyright (C) 2012 Intel Corporation. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU Lesser General Public License,
# version 2.1, as published by the Free Software Foundation.
#
# This program is distributed in the hope it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
#
# Mark Ryan <mark.d.ryan@intel.com>
#

import pygtk
pygtk.require('2.0')
import glib
import gtk
import pygst
pygst.require("0.10")
import gst
import datetime

from msd_utils import *

class PlayWindowBase(object):

    def __init__(self, name, url, close_window):
        self.__name = name
        self.__url  = url
        self.__close_window = close_window

        self.__container = gtk.VBox(False, 0)
        self.drawing_area = gtk.DrawingArea()
        self.private_area = gtk.VBox(True, 0)
        self.ok_button = gtk.Button("Close")
        self.ok_button.connect("clicked", self.quit)
        self.__container.pack_start(self.drawing_area, True, True, 0)
        self.__container.pack_start(self.private_area, False, False, 0)
        self.__container.pack_start(self.ok_button, False, False, 0)

    def quit(self, button):
        self.__close_window()

    def get_container(self):
        return self.__container

    def cancel_playback(self):
        pass

    def draw_image(self, image):
        x = 0
        y = 0
        gc = self.drawing_area.get_style().fg_gc[gtk.STATE_NORMAL]
        rect = self.drawing_area.get_allocation()
        width_scale = image.get_width() / float(rect.width)
        height_scale = image.get_height() / float(rect.height)
        if ((width_scale < 1.0 and height_scale < 1.0) or
            (width_scale >= 1.0 and height_scale >= 1.0)):
            if width_scale < height_scale:
                divisor = height_scale
                x = (rect.width - int(image.get_width() / divisor)) / 2
            else:
                divisor = width_scale
                y = (rect.height - int(image.get_height() / divisor)) / 2
        elif width_scale > 1.0:
            divisor = width_scale
            y = (rect.height - int(image.get_height() / divisor)) / 2
        else:
            divisor = height_scale
            x = (rect.width - int(image.get_width() / divisor)) / 2

        scaled_image = image.scale_simple(int(image.get_width() / divisor),
                                          int(image.get_height() / divisor),
                                          gtk.gdk.INTERP_BILINEAR)
        self.drawing_area.window.draw_pixbuf(gc, scaled_image, 0, 0, x,
                                             y, -1, -1)

class PlayWindowImage(PlayWindowBase):

    def __init__(self, name, url, close_window):
        PlayWindowBase.__init__(self, name, url, close_window)
        try:
            image = image_from_file(url)
            self.__image = image.get_pixbuf()
            self.drawing_area.connect("expose-event", self.__draw)
        except Exception:
            pass

        self.get_container().show_all()

    def __draw(self, area, event):
        self.draw_image(self.__image)
        return True

class GStreamerWindow(PlayWindowBase):

    def __init__(self, name, url, close_window):
        PlayWindowBase.__init__(self, name, url, close_window)

        self.player = gst.element_factory_make("playbin2", "player")
        gsbus = self.player.get_bus()
        gsbus.add_signal_watch()
        gsbus.connect("message", self.gs_message_cb)

        self.player.set_property("uri", url)

        button_bar = gtk.HBox(True, 0)

        self.__play_pause_button = gtk.Button()
        self.__play_pause_button.connect("clicked", self.__play_pause)
        self.__play_pause_image = gtk.Image()
        self.__play_pause_image.set_from_stock(gtk.STOCK_MEDIA_PAUSE,
                                               gtk.ICON_SIZE_BUTTON)
        self.__play_pause_button.add(self.__play_pause_image)

        self.__scale = gtk.HScale()

        button_bar.pack_start(self.__play_pause_button, True, False, 0)

        self.private_area.pack_start(self.__scale, False, False, 0)
        self.private_area.pack_start(button_bar, False, False, 0)

        self.get_container().show_all()
        self.__scale.hide()
        self.__duration = -1
        self.__update_pos_id = 0
        self.__adjustment = None
        self.__state = gst.STATE_NULL
        self.player.set_state(gst.STATE_PLAYING)

    def __play_pause(self, button):
        if (self.__state == gst.STATE_PLAYING):
            self.player.set_state(gst.STATE_PAUSED)
        else:
            self.player.set_state(gst.STATE_PLAYING)

    def __update_pos(self, user_data):
        try:
            pos = self.player.query_position(gst.FORMAT_TIME, None)[0]
            if pos != -1:
                pos = pos / 1000000000.0
                self.__adjustment.handler_block_by_func(self.__adjusted)
                self.__adjustment.set_value(pos)
                self.__adjustment.handler_unblock_by_func(self.__adjusted)
        except Exception:
            pass
        return True

    def cancel_playback(self):
        self.player.set_state(gst.STATE_NULL)

    def quit(self, button):
        self.player.set_state(gst.STATE_NULL)
        PlayWindowBase.quit(self, button)

    def __adjusted(self, adjustment):
        seek_pos = adjustment.get_value() * 1000000000.0
        self.player.seek(1.0, gst.FORMAT_TIME, gst.SEEK_FLAG_FLUSH,
                         gst.SEEK_TYPE_SET, seek_pos,
                         gst.SEEK_TYPE_NONE, -1.0)

    def __format_time(self, scale, value):
        pos = int(self.__adjustment.get_value())
        return str(datetime.timedelta(seconds=pos))

    def __update_ui(self):
        if self.__duration == -1 and (self.__state == gst.STATE_PLAYING or
                                      self.__state == gst.STATE_PAUSED):
           try:
               duration = self.player.query_duration(gst.FORMAT_TIME,
                                    None)[0]
               if duration != -1:
                   self.__duration  = duration / 1000000000
                   self.__adjustment = gtk.Adjustment(0, 0,
                                                      self.__duration,
                                                      .5, .5, 0)
                   self.__scale.set_adjustment(self.__adjustment)
                   self.__adjustment.connect("value-changed",
                                             self.__adjusted)
                   self.__scale.connect("format-value", self.__format_time)
                   self.__scale.show()
           except Exception:
               pass

        if self.__state == gst.STATE_PLAYING:
            self.__play_pause_image.set_from_stock(gtk.STOCK_MEDIA_PAUSE,
                                                   gtk.ICON_SIZE_BUTTON)
            if self.__update_pos_id == 0:
                self.__update_pos_id = glib.timeout_add(500,
                                                        self.__update_pos,
                                                        None)
        else:
            self.__play_pause_image.set_from_stock(gtk.STOCK_MEDIA_PLAY,
                                                   gtk.ICON_SIZE_BUTTON)
            if self.__update_pos_id != 0:
                glib.source_remove(self.__update_pos_id)
                self.__update_pos_id = 0

    def gs_message_cb(self, bus, message):
        if message.type == gst.MESSAGE_STATE_CHANGED:
            (old, state, pending) =  message.parse_state_changed()
            if self.__state == state:
                return

            self.__state = state
            self.__update_ui ()

class PlayWindowAudio(GStreamerWindow):

    def __init__(self, name, url, album_art_url, close_window):
        GStreamerWindow.__init__(self, name, url, close_window)

        if album_art_url:
            try:
                image = image_from_file(album_art_url)
                self.__image = image.get_pixbuf()
                self.drawing_area.connect("expose-event", self.__draw)
            except Exception:
                pass

    def __draw(self, area, event):
        self.draw_image(self.__image)
        return True

class PlayWindowVideo(GStreamerWindow):

    def __init__(self, name, url, close_window):
        GStreamerWindow.__init__(self, name, url, close_window)

        gsbus = self.player.get_bus()
        gsbus.enable_sync_message_emission()
        gsbus.connect("sync-message::element", self.gs_sync_message_cb)

    def gs_sync_message_cb(self, bus, message):
        if message.structure != None and (message.structure.get_name() ==
                                          "prepare-xwindow-id"):
            message.src.set_property("force-aspect-ratio", True)
            gtk.gdk.threads_enter()
            message.src.set_xwindow_id(self.drawing_area.window.xid)
            gtk.gdk.threads_leave()
<|endoftext|>


<commit_before># -*- utf-8 -*-
from __future__ import print_function, unicode_literals, division, absolute_import

import os.path

import pkg_resources
import regex as re

from . import cedict
from . import rules
from epitran.ligaturize import ligaturize

class MissingData(Exception):
    pass

class Epihan(object):
    punc = [(u'\uff0c', u','),
            (u'\uff01', u'!'),
            (u'\uff1f', u'?'),
            (u'\uff1b', u';'),
            (u'\uff1a', u':'),
            (u'\uff08', u'('),
            (u'\uff09', u')'),
            (u'\uff3b', u'['),
            (u'\uff3d', u']'),
            (u'\u3010', u'['),
            (u'\u3011', u']'),
            ]

    def __init__(self, ligatures=False, cedict_file=None,
                 rules_file='pinyin-to-ipa.txt'):
        """Construct epitran object for Chinese

        Args:
            ligatures (bool): if True, use ligatures instead of standard IPA
            cedict_file (str): path to CC-CEDict dictionary file
            rules_file (str): name of file with rules for converting pinyin to
                              IPA
        """
        # If no cedict_file is specified, raise and error
        if not cedict_file:
            raise MissingData('Please specify a location ' +
                              'for the CC-CEDict file.')
        rules_file = os.path.join('data', 'rules', rules_file)
        rules_file = pkg_resources.resource_filename(__name__, rules_file)
        self.cedict = cedict.CEDictTrie(cedict_file)
        self.rules = rules.Rules([rules_file])
        self.regexp = re.compile(r'\p{Han}')

    def normalize_punc(self, text):
        """Normalize punctutation in a string

        Args:
            text (unicode): an orthographic string

        Return:
            unicode: an orthographic string with punctation normalized to
                     Western equivalents
        """
        for a, b in self.punc:
            text = text.replace(a, b)
        return text

    def transliterate(self, text, normpunc=False, ligatures=False):
        """Transliterates/transcribes a word into IPA

        Args:
            word (str): word to transcribe; unicode string
            normpunc (bool): normalize punctuation
            ligatures (bool): use precomposed ligatures instead of standard IPA

        Returns:
            unicode: IPA string
        """
        tokens = self.cedict.tokenize(text)
        ipa_tokens = []
        for token in tokens:
            if token in self.cedict.hanzi:
                (pinyin, _) = self.cedict.hanzi[token]
                pinyin = u''.join(pinyin).lower()
                ipa = self.rules.apply(pinyin)
                ipa_tokens.append(ipa.replace(u',', u''))
            else:
                if normpunc:
                    token = self.normalize_punc(token)
                ipa_tokens.append(token)
            ipa_tokens = map(ligaturize, ipa_tokens)\
                if ligatures else ipa_tokens
        return u''.join(ipa_tokens)

    def strict_trans(self, text, normpunc=False, ligatures=False):
        return self.transliterate(text, normpunc, ligatures)

class EpihanTraditional(Epihan):
    def __init__(self, ligatures=False, cedict_file=None, rules_file='pinyin-to-ipa.txt'):
        """Construct epitran object for Traditional Chinese

        Args:
            ligatures (bool): if True, use ligatures instead of standard IPA
            cedict_file (str): path to CC-CEDict dictionary file
            rules_file (str): name of file with rules for converting pinyin to
                              IPA
        """
        if not cedict_file:
            raise MissingData('Please specify a location for the CC-CEDict file.')
        rules_file = os.path.join('data', 'rules', rules_file)
        rules_file = pkg_resources.resource_filename(__name__, rules_file)
        self.cedict = cedict.CEDictTrie(cedict_file, traditional=True)
        self.rules = rules.Rules([rules_file])
        self.regexp = re.compile(r'\p{Han}')
<commit_msg>Added tone option<commit_after># -*- utf-8 -*-
from __future__ import print_function, unicode_literals, division, absolute_import

import os.path

import pkg_resources
import regex as re

from . import cedict
from . import rules
from epitran.ligaturize import ligaturize

class MissingData(Exception):
    pass

class Epihan(object):
    punc = [(u'\uff0c', u','),
            (u'\uff01', u'!'),
            (u'\uff1f', u'?'),
            (u'\uff1b', u';'),
            (u'\uff1a', u':'),
            (u'\uff08', u'('),
            (u'\uff09', u')'),
            (u'\uff3b', u'['),
            (u'\uff3d', u']'),
            (u'\u3010', u'['),
            (u'\u3011', u']'),
            ]

    def __init__(self, ligatures=False, cedict_file=None,
                 rules_file='pinyin-to-ipa.txt', tones=False):
        """Construct epitran object for Chinese

        Args:
            ligatures (bool): if True, use ligatures instead of standard IPA
            cedict_file (str): path to CC-CEDict dictionary file
            rules_file (str): name of file with rules for converting pinyin to
                              IPA
            tones (bool): if True, output tones as Chao tone numbers
        """
        # If no cedict_file is specified, raise and error
        if not cedict_file:
            raise MissingData('Please specify a location ' +
                              'for the CC-CEDict file.')
        rules_file = os.path.join('data', 'rules', rules_file)
        rules_file = pkg_resources.resource_filename(__name__, rules_file)
        self.cedict = cedict.CEDictTrie(cedict_file)
        self.rules = rules.Rules([rules_file])
        self.regexp = re.compile(r'\p{Han}')

    def normalize_punc(self, text):
        """Normalize punctutation in a string

        Args:
            text (unicode): an orthographic string

        Return:
            unicode: an orthographic string with punctation normalized to
                     Western equivalents
        """
        for a, b in self.punc:
            text = text.replace(a, b)
        return text

    def transliterate(self, text, normpunc=False, ligatures=False):
        """Transliterates/transcribes a word into IPA

        Args:
            word (str): word to transcribe; Unicode string
            normpunc (bool): normalize punctuation
            ligatures (bool): use precomposed ligatures instead of standard IPA

        Returns:
            str: Unicode IPA string
        """
        tokens = self.cedict.tokenize(text)
        ipa_tokens = []
        for token in tokens:
            if token in self.cedict.hanzi:
                (pinyin, _) = self.cedict.hanzi[token]
                pinyin = u''.join(pinyin).lower()
                ipa = self.rules.apply(pinyin)
                ipa_tokens.append(ipa.replace(u',', u''))
            else:
                if normpunc:
                    token = self.normalize_punc(token)
                ipa_tokens.append(token)
            ipa_tokens = map(ligaturize, ipa_tokens)\
                if ligatures else ipa_tokens
        return u''.join(ipa_tokens)

    def strict_trans(self, text, normpunc=False, ligatures=False):
        return self.transliterate(text, normpunc, ligatures)

class EpihanTraditional(Epihan):
    def __init__(self, ligatures=False, cedict_file=None, rules_file='pinyin-to-ipa.txt'):
        """Construct epitran object for Traditional Chinese

        Args:
            ligatures (bool): if True, use ligatures instead of standard IPA
            cedict_file (str): path to CC-CEDict dictionary file
            rules_file (str): name of file with rules for converting pinyin to
                              IPA
        """
        if not cedict_file:
            raise MissingData('Please specify a location for the CC-CEDict file.')
        rules_file = os.path.join('data', 'rules', rules_file)
        rules_file = pkg_resources.resource_filename(__name__, rules_file)
        self.cedict = cedict.CEDictTrie(cedict_file, traditional=True)
        self.rules = rules.Rules([rules_file])
        self.regexp = re.compile(r'\p{Han}')
<|endoftext|>


<commit_before>from __future__ import unicode_literals
import sys

from pip import get_installed_distributions
from pkgtools.pypi import PyPIXmlRpc
try:
    import termcolor
    USE_TERMCOLOR = True
except ImportError:
    USE_TERMCOLOR = False

api = PyPIXmlRpc()

DEFAULT_STREAM = sys.stdout

GOOD_LICENSES = set([
    "Apache Software License",
    "Apache",
    "BSD License",
    "BSD",
    "MIT License",
    "MIT",
    # ...
])

def format_license(license, ok=True):
    if USE_TERMCOLOR:
        return termcolor.colored(
            license, ok and "green" or "red", attrs=["bold"])
    return (ok and "\033[92m" or "\033[91m") + license + "\033[0m"

def get_license_line(name, version, license):
    ok = license in GOOD_LICENSES
    return ''.join([
        "%s==%s #" % (name, version),
        format_license(license, ok),
    ])

def display(name, version, license, stream=None):
    stream = stream or DEFAULT_STREAM
    line = get_license_line(name, version, license)
    stream.write(line)
    stream.write('\n')

def display_dist(dist):
    name, version = dist.project_name, dist.version

    info = api.release_data(name, version)
    license = info.get("license", "UNKNOWN").strip()

    display(name, version, license)

def main():
    for dist in get_installed_distributions():
        display_dist(dist)

if __name__ == '__main__':
    main()

<commit_msg>Decided on using only termcolor for color output.<commit_after>from __future__ import unicode_literals
import sys

from pip import get_installed_distributions
from pkgtools.pypi import PyPIXmlRpc
try:
    import termcolor
    USE_TERMCOLOR = True
except ImportError:
    USE_TERMCOLOR = False

api = PyPIXmlRpc()

DEFAULT_STREAM = sys.stdout

GOOD_LICENSES = set([
    "Apache Software License",
    "Apache",
    "BSD License",
    "BSD",
    "MIT License",
    "MIT",
    # ...
])

def format_license(license, ok=True):
    if USE_TERMCOLOR:
        return termcolor.colored(
            license, ok and "green" or "red", attrs=["bold"])
    return license

def get_license_line(name, version, license):
    ok = license in GOOD_LICENSES

    return ''.join([
        "%s==%s #" % (name, version),
        format_license(license, ok),
    ])

def display(name, version, license, stream=None):
    stream = stream or DEFAULT_STREAM
    line = get_license_line(name, version, license)
    stream.write(line)
    stream.write('\n')

def display_dist(dist):
    name, version = dist.project_name, dist.version

    info = api.release_data(name, version)
    license = info.get("license", "UNKNOWN").strip()

    display(name, version, license)

def main():
    for dist in get_installed_distributions():
        display_dist(dist)

if __name__ == '__main__':
    main()

<|endoftext|>


<commit_before>import array

import scipy.sparse as sp

class IncrementalCOOMatrix(object):

    def __init__(self, shape, dtype):

        if dtype is np.int32:
            type_flag = 'i'
        elif dtype is np.int64:
            type_flag = 'l'
        elif dtype is np.float32:
            type_flag = 'f'
        elif dtype is np.float64:
            type_flag = 'd'
        else:
            raise Exception('Dtype not supported.')

        self.shape = shape
        self.dtype = dtype

        self.rows = array.array('i')
        self.cols = array.array('i')
        self.data = array.array(type_flag)

    def append(self, i, j, v):

        m, n = self.shape

        if (i >= m or j >= n):
            raise Exception('Index out of bounds')

        self.rows.append(i)
        self.cols.append(j)
        self.data.append(v)

    def tocoo(self):

        rows = np.frombuffer(self.rows, dtype=np.int32)
        cols = np.frombuffer(self.cols, dtype=np.int32)
        data = np.frombuffer(self.data, dtype=self.dtype)

        return sp.coo_matrix((data, (rows, cols)),
                             shape=self.shape)

    def __len__(self):

        return len(self.data)

class ImplicitInteractions(object):

    def __init__(self, user_identity_features=True, item_identity_features=True):

        self._user_identity_features = user_identity_features
        self._item_identity_features = item_identity_features

        self._user_id_mapping = {}
        self._item_id_mapping = {}

    def _initialise_features(self):

        self._user_feature_mapping = {}
        self._item_feature_mapping = {}

        self._user_features_row = array.array('i')
        self._user_features_col = array.array('i')
        self._user_features_value = array.array('f')

        self._item_features_row = array.array('i')
        self._item_features_col = array.array('i')
        self._item_features_value = array.array('f')

    def _unpack_datum(self, datum):

        if len(datum) == 3:
            (user_id, item_id, weight) = datum
        elif len(datum) == 2:
            (user_id, item_id) = datum
            weight = 1.0
        else:
            raise ValueError('Expecting tuples of (user_id, item_id, weight) '
                             'or (user_id, item_id). Got {}'.format(datum))

        user_idx = self._user_id_mapping.get(user_id)
        item_idx = self._item_id_mapping.get(item_id)

        if user_idx is None:
            raise ValueError('User id {} not in user id mapping. Make sure '
                             'you call the fit method.'.format(user_id))
        if item_idx is None:
            raise ValueError('Item id {} not in item id mapping. Make sure '
                             'you call the fit method.'.format(item_id))

        return (user_idx, item_idx, weight)

    def _check_fitted(self):

        if not self._user_id_mapping or not self._item_id_mapping:
            raise ValueError('You must call fit first to build the item and user '
                             'id mappings.')

    def fit_user_mapping(self, data):

        self._user_id_mapping = {}

        for user_id in data:
            self._user_id_mapping.setdefault(user_id, len(self._user_id_mapping))

    def fit_item_mapping(self, data):

        self._item_id_mapping = {}

        for item_id in data:
            self._item_id_mapping.setdefault(item_id, len(self._item_id_mapping))

    def _unpack_feature(self, datum):

        if len(datum) != 2:
            raise ValueError('Expected tuples of (user_id, features), '
                             'got {}.'.format(datum))

        return datum

    def _iter_features(self, features):

        if isinstance(features, dict):
            for entry in dict.items():
                yield entry
        else:
            for feature_name in features:
                yield (feature_name, 1.0)

    def fit_user_feature_mapping(self, data):

        self._user_feature_mapping = {}

        for datum in data:
            user_id, features = self._unpack_feature(datum)

            if user_id not in self._user_id_mapping:
                raise ValueError('User id {} not in user id mapping. '
                                 'Make sure you call fit_user_id_mapping '
                                 'first.'.format(user_id))

            for (feature_name, _) in self._iter_features(features):
                self._user_feature_mapping.setdefault(feature_name,
                                                      len(self._user_feature_mapping))

    def fit_item_feature_mapping(self, data):

        self._item_feature_mapping = {}

        for datum in data:
            item_id, features = self._unpack_feature(datum)

            if item_id not in self._item_id_mapping:
                raise ValueError('Item id {} not in item id mapping. '
                                 'Make sure you call fit_item_id_mapping '
                                 'first.'.format(item_id))

            for (feature_name, _) in self._iter_features(features):
                self._item_feature_mapping.setdefault(feature_name,
                                                      len(self._item_feature_mapping))

    def build_interactions_matrix(self, data):

        interactions = IncrementalCOOMatrix(self.interactions_shape(), np.int32)
        weights = IncrementalCOOMatrix(self.interactions_shape(), np.float32)

        for datum in data:
            user_idx, item_idx, weight = self._unpack_datum(datum)

            interactions.append(user_idx, item_idx, 1.0)
            weights.append(user_idx, item_idx, weight)

        return (interactions.tocoo(),
                weights.tocoo())

    def interactions_shape(self):

        self._check_fitted()

        return (len(self._user_id_mapping),
                len(self._item_id_mapping))

    def _process_features(self, datum):

        if len(datum) != 2:
            raise ValueError('Expected tuples of (user_id, features), '
                             'got {}.'.format(datum))

        user_id, features = datum

        if user_id not in self._user_id_mapping:
            raise ValueError('User id {} not in user id mappings.'
                             .format(user_id))

        user_idx = self._user_id_mapping[user_id]

    def build_user_features(self, data):

        self._initialise_features()

        for (user_id, features) in data:
<commit_msg>Try to clean up the interface.<commit_after>import array

import numpy as np
import scipy.sparse as sp

class IncrementalCOOMatrix(object):

    def __init__(self, shape, dtype):

        if dtype is np.int32:
            type_flag = 'i'
        elif dtype is np.int64:
            type_flag = 'l'
        elif dtype is np.float32:
            type_flag = 'f'
        elif dtype is np.float64:
            type_flag = 'd'
        else:
            raise Exception('Dtype not supported.')

        self.shape = shape
        self.dtype = dtype

        self.rows = array.array('i')
        self.cols = array.array('i')
        self.data = array.array(type_flag)

    def append(self, i, j, v):

        m, n = self.shape

        if (i >= m or j >= n):
            raise Exception('Index out of bounds')

        self.rows.append(i)
        self.cols.append(j)
        self.data.append(v)

    def tocoo(self):

        rows = np.frombuffer(self.rows, dtype=np.int32)
        cols = np.frombuffer(self.cols, dtype=np.int32)
        data = np.frombuffer(self.data, dtype=self.dtype)

        return sp.coo_matrix((data, (rows, cols)),
                             shape=self.shape)

    def __len__(self):

        return len(self.data)

class ImplicitInteractions(object):

    def __init__(self, user_identity_features=True, item_identity_features=True):

        self._user_identity_features = user_identity_features
        self._item_identity_features = item_identity_features

        self._user_id_mapping = {}
        self._item_id_mapping = {}
        self._user_feature_mapping = {}
        self._item_feature_mapping = {}

    def _check_fitted(self):

        if not self._user_id_mapping or not self._item_id_mapping:
            raise ValueError('You must call fit first to build the item and user '
                             'id mappings.')

    def fit(self, users, items, user_features=None, item_features=None):

        self._user_id_mapping = {}
        self._item_id_mapping = {}
        self._user_feature_mapping = {}
        self._item_feature_mapping = {}

        self.fit_partial(users, items, user_features, item_features)

    def fit_partial(self, users, items, user_features=None, item_features=None):

        for user_id in users:
            self._user_id_mapping.setdefault(user_id, len(self._user_id_mapping))

            if self._user_identity_features:
                self._user_feature_mapping.setdefault(user_id, len(self._user_feature_mapping))

        for item_id in items:
            self._item_id_mapping.setdefault(item_id, len(self._item_id_mapping))

            if self._item_identity_features:
                self._item_feature_mapping.setdefault(item_id, len(self._item_feature_mapping))

        if user_features is not None:
            for user_feature in user_features:
                self._user_feature_mapping.setdefault(user_feature, len(self._user_feature_mapping))

        if item_features is not None:
            for item_feature in item_features:
                self._item_feature_mapping.setdefault(item_feature, len(self._item_feature_mapping))

    def _unpack_datum(self, datum):

        if len(datum) == 3:
            (user_id, item_id, weight) = datum
        elif len(datum) == 2:
            (user_id, item_id) = datum
            weight = 1.0
        else:
            raise ValueError('Expecting tuples of (user_id, item_id, weight) '
                             'or (user_id, item_id). Got {}'.format(datum))

        user_idx = self._user_id_mapping.get(user_id)
        item_idx = self._item_id_mapping.get(item_id)

        if user_idx is None:
            raise ValueError('User id {} not in user id mapping. Make sure '
                             'you call the fit method.'.format(user_id))
        if item_idx is None:
            raise ValueError('Item id {} not in item id mapping. Make sure '
                             'you call the fit method.'.format(item_id))

        return (user_idx, item_idx, weight)

    def interactions_shape(self):

        return (len(self._user_id_mapping),
                len(self._item_id_mapping))

    def build_interactions_matrix(self, data):

        interactions = IncrementalCOOMatrix(self.interactions_shape(), np.int32)
        weights = IncrementalCOOMatrix(self.interactions_shape(), np.float32)

        for datum in data:
            user_idx, item_idx, weight = self._unpack_datum(datum)

            interactions.append(user_idx, item_idx, 1.0)
            weights.append(user_idx, item_idx, weight)

        return (interactions.tocoo(),
                weights.tocoo())

    def _iter_features(self, features):

        if isinstance(features, dict):
            for entry in dict.items():
                yield entry
        else:
            for feature_name in features:
                yield (feature_name, 1.0)

    def _process_user_features(self, datum):

        if len(datum) != 2:
            raise ValueError('Expected tuples of (user_id, features), '
                             'got {}.'.format(datum))

        user_id, features = datum

        if user_id not in self._user_id_mapping:
            raise ValueError('User id {} not in user id mappings.'
                             .format(user_id))

        user_idx = self._user_id_mapping[user_id]

        for (feature, weight) in self._iter_features(features):
            if feature not in self._user_feature_mapping:
                raise ValueError('Feature {} not in user feature mapping. '
                                 'Call fit first.'.format(feature))

            feature_idx = self._user_feature_mapping[feature]

            yield (user_idx, feature_idx, weight)

    def user_features_shape(self):

        return (len(self._user_id_mapping),
                len(self._user_feature_mapping))

    def build_user_features(self, data):

        features = IncrementalCOOMatrix(self.user_features_shape(), np.float32)

        for datum in data:
            for (user_idx, feature_idx, weight) in self._process_user_features(datum):
                features.append(user_idx, feature_idx, weight)

        return features.tocoo()
<|endoftext|>


<commit_before>import asyncio
import dateutil
import datetime
import sqlalchemy

from common.config import config
from common import rpc
from common import googlecalendar
from common import time
from common import utils
from common import twitch

import logging
log = logging.getLogger('eris.autotopic')

class Autotopic:
	def __init__(self, eris, signals, engine, metadata):
		self.eris = eris
		self.signals = signals
		self.engine = engine
		self.metadata = metadata

		self.timer_scheduled = False
		self.signals.signal('ready').connect(self.schedule_timer)

	# Simplified copy of `lrrbot.commands.misc.uptime_msg`.
	def uptime_msg(self):
		stream_info = twitch.get_info()
		if stream_info and stream_info.get("stream_created_at"):
			start = dateutil.parser.parse(stream_info["stream_created_at"])
			now = datetime.datetime.now(datetime.timezone.utc)
			return "The stream has been live for %s." % time.nice_duration(now - start, 0)
		elif stream_info and stream_info.get('live'):
			return "Twitch won't tell me when the stream went live."
		else:
			return "The stream is not live."

	@utils.swallow_errors
	async def update_topic(self):
		channel = self.eris.get_server(config['discord_serverid']).default_channel
		header = await rpc.bot.get_header_info()
		messages = []

		if header['is_live']:
			shows = self.metadata.tables["shows"]
			games = self.metadata.tables["games"]
			game_per_show_data = self.metadata.tables["game_per_show_data"]
			with self.engine.begin() as conn:
				if header.get('current_game'):
					game = conn.execute(sqlalchemy.select([
						sqlalchemy.func.coalesce(game_per_show_data.c.display_name, games.c.name)
					]).select_from(
						games.outerjoin(game_per_show_data,
							(game_per_show_data.c.game_id == games.c.id) &
								(game_per_show_data.c.show_id == header['current_show']['id']))
					).where(games.c.id == header['current_game']['id'])).first()
					if game is not None:
						game, = game
				else:
					game = None

				if header.get('current_show'):
					show = conn.execute(sqlalchemy.select([shows.c.name])
						.where(shows.c.id == header['current_show']['id'])
						.where(shows.c.string_id != "")).first()
					if show is not None:
						show, = show
				else:
					show = None

			if game and show:
				messages.append("Stream currently live: playing %s on %s." % (game, show))
			elif game:
				messages.append("Stream currently live: playing %s." % game)
			elif show:
				messages.append("Stream currently live: showing %s." % show)
			messages.append(self.uptime_msg())
		else:
			messages.append(googlecalendar.get_next_event_text(googlecalendar.CALENDAR_LRL))
		messages = ["DESERT BUS!"]
		if header.get('advice'):
			messages.append(header['advice'])
		await self.eris.edit_channel(channel, topic=" ".join(messages))

	def schedule_update_topic(self):
		asyncio.ensure_future(self.update_topic(), loop=self.eris.loop).add_done_callback(utils.check_exception)
		self.eris.loop.call_later(60, self.schedule_update_topic)

	def schedule_timer(self, eris):
		if not self.timer_scheduled:
			self.timer_scheduled = True
			self.schedule_update_topic()
<commit_msg>Desert Bus is over.<commit_after>import asyncio
import dateutil
import datetime
import sqlalchemy

from common.config import config
from common import rpc
from common import googlecalendar
from common import time
from common import utils
from common import twitch

import logging
log = logging.getLogger('eris.autotopic')

class Autotopic:
	def __init__(self, eris, signals, engine, metadata):
		self.eris = eris
		self.signals = signals
		self.engine = engine
		self.metadata = metadata

		self.timer_scheduled = False
		self.signals.signal('ready').connect(self.schedule_timer)

	# Simplified copy of `lrrbot.commands.misc.uptime_msg`.
	def uptime_msg(self):
		stream_info = twitch.get_info()
		if stream_info and stream_info.get("stream_created_at"):
			start = dateutil.parser.parse(stream_info["stream_created_at"])
			now = datetime.datetime.now(datetime.timezone.utc)
			return "The stream has been live for %s." % time.nice_duration(now - start, 0)
		elif stream_info and stream_info.get('live'):
			return "Twitch won't tell me when the stream went live."
		else:
			return "The stream is not live."

	@utils.swallow_errors
	async def update_topic(self):
		channel = self.eris.get_server(config['discord_serverid']).default_channel
		header = await rpc.bot.get_header_info()
		messages = []

		if header['is_live']:
			shows = self.metadata.tables["shows"]
			games = self.metadata.tables["games"]
			game_per_show_data = self.metadata.tables["game_per_show_data"]
			with self.engine.begin() as conn:
				if header.get('current_game'):
					game = conn.execute(sqlalchemy.select([
						sqlalchemy.func.coalesce(game_per_show_data.c.display_name, games.c.name)
					]).select_from(
						games.outerjoin(game_per_show_data,
							(game_per_show_data.c.game_id == games.c.id) &
								(game_per_show_data.c.show_id == header['current_show']['id']))
					).where(games.c.id == header['current_game']['id'])).first()
					if game is not None:
						game, = game
				else:
					game = None

				if header.get('current_show'):
					show = conn.execute(sqlalchemy.select([shows.c.name])
						.where(shows.c.id == header['current_show']['id'])
						.where(shows.c.string_id != "")).first()
					if show is not None:
						show, = show
				else:
					show = None

			if game and show:
				messages.append("Stream currently live: playing %s on %s." % (game, show))
			elif game:
				messages.append("Stream currently live: playing %s." % game)
			elif show:
				messages.append("Stream currently live: showing %s." % show)
			messages.append(self.uptime_msg())
		else:
			messages.append(googlecalendar.get_next_event_text(googlecalendar.CALENDAR_LRL))
		if header.get('advice'):
			messages.append(header['advice'])
		await self.eris.edit_channel(channel, topic=" ".join(messages))

	def schedule_update_topic(self):
		asyncio.ensure_future(self.update_topic(), loop=self.eris.loop).add_done_callback(utils.check_exception)
		self.eris.loop.call_later(60, self.schedule_update_topic)

	def schedule_timer(self, eris):
		if not self.timer_scheduled:
			self.timer_scheduled = True
			self.schedule_update_topic()
<|endoftext|>


<commit_before>import datetime

def sparql_escape(obj):
    if type(obj) is str:
        return '"' + obj.replace('\\\\"\'', '\\') + '"'
    elif type(obj) is datetime.time:
        return '"' + obj.isoformat() + '"^^xsd:dateTime'
    elif type(obj) is datetime.date:
        return '"' + obj.isoformat() + '"^^xsd:date'
    elif type(obj) is int:
        return '"' + str(obj) + '"^^xsd:integer'
    elif type(obj) is float:
        return '"' + str(obj) + '"^^xsd:float'
    elif type(obj) is bool:
        return '"' + str(obj) + '"^^xsd:boolean'
    else:
        return ""
<commit_msg>fix sparql string escaping (using regex)<commit_after>import datetime
import re

def sparql_escape(obj):
    if type(obj) is str:
        def replacer(a):
            return "\\"+a.group(0)
        return '"' + re.sub(r'[\\"]', replacer, obj) + '"'
    elif type(obj) is datetime.time:
        return '"' + obj.isoformat() + '"^^xsd:dateTime'
    elif type(obj) is datetime.date:
        return '"' + obj.isoformat() + '"^^xsd:date'
    elif type(obj) is int:
        return '"' + str(obj) + '"^^xsd:integer'
    elif type(obj) is float:
        return '"' + str(obj) + '"^^xsd:float'
    elif type(obj) is bool:
        return '"' + str(obj) + '"^^xsd:boolean'
    else:
        return ""
<|endoftext|>


<commit_before>from django.conf import settings

def get_setting(name, default):
    """ Get setting by name.
    """
    return getattr(settings, 'ADJAX_{0}'.format(name.upper()), default)

TEMPLATE = get_setting('template', 'adjax/interface')
DATA = get_setting('data', {})
CONTENT_TYPE = get_setting('content_type', 'application/javascript')
VIEWS_MODULE_NAME = get_setting('module_name', 'ajax')
TYPES_MODULE_NAME = get_setting('module_name', 'types')
<commit_msg>Fix module name settings<commit_after>from django.conf import settings

def get_setting(name, default):
    """ Get setting by name.
    """
    return getattr(settings, 'ADJAX_{0}'.format(name.upper()), default)

TEMPLATE = get_setting('template', 'adjax/interface')
DATA = get_setting('data', {})
CONTENT_TYPE = get_setting('content_type', 'application/javascript')
VIEWS_MODULE_NAME = get_setting('views_module_name', 'ajax')
TYPES_MODULE_NAME = get_setting('types_module_name', 'types')
<|endoftext|>