text:
import datetime

from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.utils.timezone import get_current_timezone

from rest_framework import status
from rest_framework.test import APIRequestFactory, force_authenticate

from resolwe.flow.models import (
    Collection,
    Data,
    DescriptorSchema,
    Entity,
    Process,
    Relation,
    RelationType,
)
from resolwe.flow.views import (
    CollectionViewSet,
    DataViewSet,
    DescriptorSchemaViewSet,
    EntityViewSet,
    ProcessViewSet,
)
from resolwe.permissions.models import Permission, get_anonymous_user
from resolwe.test import TestCase

factory = APIRequestFactory()

class BaseViewSetFiltersTest(TestCase):
    @classmethod
    def setUpTestData(cls):
        user_model = get_user_model()
        cls.admin = user_model.objects.create_superuser(
            username="admin",
            email="admin@test.com",
            password="admin",
            first_name="James",
            last_name="Smith",
        )
        cls.contributor = user_model.objects.create_user(
            username="contributor",
            email="contributor@test.com",
            first_name="Joe",
            last_name="Miller",
        )
        cls.user = user_model.objects.create_user(
            username="normal_user",
            email="user@test.com",
            first_name="John",
            last_name="Williams",
        )
        cls.group = Group.objects.create(name="Test group")

    def setUp(self):
        self.viewset = self.viewset_class.as_view(
            actions={
                "get": "list",
            }
        )

    def _check_filter(
        self, query_args, expected, expected_status_code=status.HTTP_200_OK, user=None
    ):
        """Check that query_args filter to expected queryset."""
        request = factory.get("/", query_args, format="json")
        force_authenticate(request, user or self.admin)
        response = self.viewset(request)

        if status.is_success(response.status_code):
            self.assertEqual(len(response.data), len(expected))
            self.assertCountEqual(
                [item.pk for item in expected],
                [item["id"] for item in response.data],
            )
        else:
            self.assertEqual(response.status_code, expected_status_code)
            response.render()

        return response

class CollectionViewSetFiltersTest(BaseViewSetFiltersTest):
    @classmethod
    def setUpTestData(cls):
        super().setUpTestData()

        cls.descriptor_schema = DescriptorSchema.objects.create(
            slug="test-schema",
            version="1.0.0",
            contributor=cls.contributor,
            schema=[
                {
                    "name": "company",
                    "group": [
                        {
                            "name": "name",
                            "type": "basic:string:",
                            "required": False,
                        },
                        {
                            "name": "departments",
                            "type": "list:basic:string:",
                            "required": False,
                        },
                    ],
                }
            ],
        )

        cls.collections = [
            Collection.objects.create(
                name="Test collection 0",
                slug="test-collection-0",
                contributor=cls.contributor,
                description="My description!",
                descriptor_schema=cls.descriptor_schema,
                descriptor={
                    "company": {
                        "name": "Genialis",
                        "departments": ["engineering", "operations"],
                    }
                },
                tags=["first-tag"],
            ),
            Collection.objects.create(
                name="Test collection 1",
                slug="test-collection-1",
                contributor=cls.contributor,
                description="My favourite test collection",
                descriptor_schema=cls.descriptor_schema,
                tags=["first-tag", "second-tag"],
            ),
            Collection.objects.create(
                name="User test collection",
                slug="user-collection",
                contributor=cls.user,
                description="User's description",
                tags=["second-tag"],
            ),
            Collection.objects.create(
                name="Public test collection",
                slug="public-collection",
                contributor=cls.admin,
            ),
        ]

        cls.entity1 = Entity.objects.create(
            contributor=cls.contributor, collection=cls.collections[1]
        )
        cls.entity2 = Entity.objects.create(
            contributor=cls.contributor, collection=cls.collections[2]
        )
        cls.entity3 = Entity.objects.create(
            contributor=cls.contributor, collection=cls.collections[2]
        )
        cls.entity1.save()
        cls.entity2.save()
        cls.entity3.save()

        tzone = get_current_timezone()
        cls.collections[0].created = datetime.datetime(2016, 7, 30, 0, 59, tzinfo=tzone)
        cls.collections[0].save()
        cls.collections[1].created = datetime.datetime(2016, 7, 30, 1, 59, tzinfo=tzone)
        cls.collections[1].save()
        cls.collections[2].created = datetime.datetime(2016, 7, 30, 2, 59, tzinfo=tzone)
        cls.collections[2].save()

        cls.collections[0].set_permission(Permission.OWNER, cls.admin)
        cls.collections[0].set_permission(Permission.VIEW, cls.user)
        cls.collections[1].set_permission(Permission.OWNER, cls.admin)
        cls.collections[1].set_permission(Permission.VIEW, cls.user)
        cls.collections[2].set_permission(Permission.OWNER, cls.user)
        cls.collections[2].set_permission(Permission.OWNER, cls.group)
        cls.collections[3].set_permission(Permission.VIEW, get_anonymous_user())

        cls.viewset_class = CollectionViewSet

    def test_filter_id(self):
        self._check_filter({"id": self.collections[0].pk}, [self.collections[0]])
        self._check_filter({"id": "420"}, [])
        self._check_filter(
            {"id__in": "{},{}".format(self.collections[0].pk, self.collections[1].pk)},
            self.collections[:2],
        )
        self._check_filter({"id__gt": self.collections[0].pk}, self.collections[1:])

    def test_filter_slug(self):
        self._check_filter({"slug": "test-collection-0"}, [self.collections[0]])
        self._check_filter(
            {"slug__in": "test-collection-1,user-collection"}, self.collections[1:3]
        )

    def test_filter_name(self):
        self._check_filter({"name": "Test collection 1"}, [self.collections[1]])
        self._check_filter({"name": "Test collection"}, [])

        self._check_filter({"name__iexact": "test collection 1"}, [self.collections[1]])

        self._check_filter(
            {"name__startswith": "Test collection"}, self.collections[:2]
        )
        self._check_filter(
            {"name__istartswith": "test collection"}, self.collections[:2]
        )

        self._check_filter({"name__contains": "test"}, self.collections[2:])
        self._check_filter({"name__icontains": "test"}, self.collections)

    def test_filter_description(self):
        self._check_filter(
            {"description__icontains": "Favourite"}, [self.collections[1]]
        )
        self._check_filter({"description__contains": "Favourite"}, [])
        self._check_filter({"description__contains": 420}, [])

    def test_filter_descriptor_schema(self):
        self._check_filter(
            {"descriptor_schema": str(self.descriptor_schema.pk)}, self.collections[:2]
        )
        self._check_filter({"descriptor_schema": "999999"}, [])

    def test_filter_tags(self):
        self._check_filter({"tags": "first-tag"}, self.collections[:2])
        self._check_filter({"tags": "first-tag,second-tag"}, [self.collections[1]])

    def test_filter_contributor(self):
        self._check_filter(
            {"contributor": str(self.contributor.pk)}, self.collections[:2]
        )
        self._check_filter(
            {"contributor__in": "{},{}".format(self.contributor.pk, self.user.pk)},
            self.collections[:3],
        )

    def test_filter_owners(self):
        self._check_filter({"owners": str(self.admin.pk)}, self.collections[:2])
        self._check_filter({"owners": "999999"}, [])

    def test_filter_contributor_name(self):
        # Filter by first name.
        self._check_filter({"contributor_name": "Joe"}, self.collections[:2])
        # Filter by last name.
        self._check_filter({"contributor_name": "Miller"}, self.collections[:2])
        # Filter by username.
        self._check_filter({"contributor_name": "contributor"}, self.collections[:2])
        # Filter by combination of first and last name.
        self._check_filter({"contributor_name": "John Williams"}, [self.collections[2]])

    def test_filter_owners_name(self):
        # Filter by first name.
        self._check_filter({"owners_name": "James"}, self.collections[:2])
        # Filter by last name.
        self._check_filter({"owners_name": "Smith"}, self.collections[:2])
        # Filter by username.
        self._check_filter({"owners_name": "admin"}, self.collections[:2])
        # Filter by combination of first and last name.
        self._check_filter({"owners_name": "John Williams"}, [self.collections[2]])

    def test_filter_permission(self):
        self._check_filter(
            {"permission": "edit"}, [self.collections[2]], user=self.user
        )
        self._check_filter(
            {"permission": "view"},
            self.collections,
            user=self.user,
        )
        self._check_filter(
            {"permission": "owner"}, [self.collections[2]], user=self.user
        )

    def test_filter_created(self):
        self._check_filter({"created": "2016-07-30T00:59:00"}, self.collections[:1])
        self._check_filter({"created__gt": "2016-07-30T01:59:00"}, self.collections[2:])
        self._check_filter(
            {"created__gte": "2016-07-30T01:59:00"}, self.collections[1:]
        )
        self._check_filter({"created__lt": "2016-07-30T01:59:00"}, self.collections[:1])
        self._check_filter(
            {"created__lte": "2016-07-30T01:59:00"}, self.collections[:2]
        )

    def test_filter_modified(self):
        self._check_filter(
            {"modified": self.collections[0].modified.isoformat()}, self.collections[:1]
        )
        self._check_filter(
            {"modified__gt": self.collections[1].modified.isoformat()},
            self.collections[2:3],
        )
        self._check_filter(
            {"modified__gte": self.collections[1].modified.isoformat()},
            self.collections[1:3],
        )
        self._check_filter(
            {"modified__lt": self.collections[1].modified.isoformat()},
            self.collections[:1] + [self.collections[3]],
        )
        self._check_filter(
            {"modified__lte": self.collections[1].modified.isoformat()},
            self.collections[:2] + [self.collections[3]],
        )

    def test_filter_text(self):
        # By name.
        self._check_filter({"text": "Test collection 1"}, [self.collections[1]])
        self._check_filter({"text": "Test"}, self.collections)
        self._check_filter({"text": "test"}, self.collections)
        self._check_filter({"text": "user"}, [self.collections[2]])

        # By contributor.
        self._check_filter({"text": "joe"}, self.collections[:2])
        self._check_filter({"text": "Miller"}, self.collections[:2])

        # By owner.
        self._check_filter(
            {"text": "james"}, self.collections[:2] + [self.collections[3]]
        )
        self._check_filter(
            {"text": "Smith"}, self.collections[:2] + [self.collections[3]]
        )

        # By description.
        self._check_filter(
            {"text": "description"}, [self.collections[0], self.collections[2]]
        )
        self._check_filter({"text": "my"}, self.collections[:2])
        self._check_filter({"text": "my description"}, [self.collections[0]])
        self._check_filter({"text": "user"}, [self.collections[2]])

        # By descriptor.
        self._check_filter({"text": "genialis"}, [self.collections[0]])
        self._check_filter({"text": "engineering"}, [self.collections[0]])

        # By mixed fields.
        self._check_filter({"text": "test joe"}, self.collections[:2])
        self._check_filter({"text": "joe my description"}, [self.collections[0]])

        # Check that changes are applied immediately.
        self.collections[0].name = "Awesome new name"
        self.collections[0].save()

        self._check_filter({"text": "awesome"}, [self.collections[0]])

    def test_filter_mixed(self):
        self._check_filter(
            {"name": "Test collection 0", "owners_name": "James Smith"},
            [self.collections[0]],
        )
        self._check_filter(
            {"text": "collection 0", "owners_name": "James Smith"},
            [self.collections[0]],
        )

    def test_order_by_relevance(self):
        result = self._check_filter({"text": "test collection"}, self.collections)
        self.assertEqual(result.data[0]["id"], self.collections[1].pk)

        # Make another collection more important.
        collection = self.collections[2]
        collection.description = "This is test collection. My test collection rocks."
        collection.save()

        result = self._check_filter({"text": "test collection"}, self.collections)
        self.assertEqual(result.data[0]["id"], self.collections[2].pk)

        # Check that ordering can be overriden.
        result = self._check_filter(
            {"text": "test collection", "ordering": "id"}, self.collections
        )
        self.assertEqual(result.data[0]["id"], self.collections[0].pk)

    def test_filter_entity_count(self):
        self._check_filter(
            {"entity_count": 0}, [self.collections[0], self.collections[3]]
        )
        self._check_filter({"entity_count": 2}, [self.collections[2]])
        self._check_filter({"entity_count__gt": 1}, [self.collections[2]])
        self._check_filter(
            {"entity_count__lt": 1}, [self.collections[0], self.collections[3]]
        )
        self._check_filter(
            {"entity_count__gte": 1}, [self.collections[1], self.collections[2]]
        )
        self._check_filter(
            {"entity_count__lte": 1},
            [self.collections[0], self.collections[1], self.collections[3]],
        )

    def test_filter_group(self):
        self._check_filter({"group": self.group.pk}, [self.collections[2]])

    def test_filter_shared_with_me(self):
        self._check_filter(
            {"shared_with_me": True}, self.collections[:3], user=self.user
        )
        self._check_filter(
            {"shared_with_me": False}, [self.collections[3]], user=self.user
        )

class EntityViewSetFiltersTest(BaseViewSetFiltersTest):
    @classmethod
    def setUpTestData(cls):
        super().setUpTestData()

        cls.descriptor_schema = DescriptorSchema.objects.create(
            slug="test-schema",
            version="1.0.0",
            contributor=cls.contributor,
            schema=[
                {
                    "name": "company",
                    "group": [
                        {
                            "name": "name",
                            "type": "basic:string:",
                            "required": False,
                        },
                        {
                            "name": "departments",
                            "type": "list:basic:string:",
                            "required": False,
                        },
                    ],
                }
            ],
        )

        cls.collection1 = Collection.objects.create(
            name="My collection",
            slug="my-collection",
            contributor=cls.contributor,
        )

        cls.collection2 = Collection.objects.create(
            name="Other collection",
            slug="other-collection",
            contributor=cls.contributor,
        )

        cls.entities = [
            Entity.objects.create(
                name="Test entity 0",
                slug="test-entity-0",
                contributor=cls.contributor,
                collection=cls.collection1,
                description="My description!",
                descriptor_schema=cls.descriptor_schema,
                descriptor={
                    "company": {
                        "name": "Genialis",
                        "departments": ["engineering", "operations"],
                    }
                },
                tags=["first-tag"],
            ),
            Entity.objects.create(
                name="Test entity 1",
                slug="test-entity-1",
                contributor=cls.contributor,
                collection=cls.collection2,
                description="My favourite test entity",
                descriptor_schema=cls.descriptor_schema,
                tags=["first-tag", "second-tag"],
            ),
            Entity.objects.create(
                name="User test entity",
                slug="user-entity",
                contributor=cls.user,
                description="User's description",
                tags=["second-tag"],
            ),
            Entity.objects.create(
                name="Public test entity",
                slug="public-entity",
                contributor=cls.user,
            ),
        ]

        cls.rel_type = RelationType.objects.create(name="series", ordered=True)
        cls.relation1 = Relation.objects.create(
            type=cls.rel_type, collection=cls.collection1, contributor=cls.contributor
        )
        cls.relation1.entities.set(cls.entities[:1])
        cls.relation1.save()
        cls.relation2 = Relation.objects.create(
            type=cls.rel_type, collection=cls.collection2, contributor=cls.contributor
        )
        cls.relation2.entities.set(cls.entities[1:])
        cls.relation2.save()

        tzone = get_current_timezone()
        cls.entities[0].created = datetime.datetime(2016, 7, 30, 0, 59, tzinfo=tzone)
        cls.entities[0].save()
        cls.entities[1].created = datetime.datetime(2016, 7, 30, 1, 59, tzinfo=tzone)
        cls.entities[1].save()
        cls.entities[2].created = datetime.datetime(2016, 7, 30, 2, 59, tzinfo=tzone)
        cls.entities[2].save()

        cls.collection1.set_permission(Permission.OWNER, cls.admin)
        cls.collection1.set_permission(Permission.VIEW, cls.user)
        cls.collection2.set_permission(Permission.OWNER, cls.admin)
        cls.collection2.set_permission(Permission.VIEW, cls.user)
        cls.entities[2].set_permission(Permission.OWNER, cls.user)
        cls.entities[2].set_permission(Permission.VIEW, cls.group)
        cls.entities[3].set_permission(Permission.VIEW, get_anonymous_user())

        cls.viewset_class = EntityViewSet

    def test_filter_id(self):
        self._check_filter({"id": self.entities[0].pk}, [self.entities[0]])
        self._check_filter({"id": "420"}, [])
        self._check_filter(
            {"id__in": "{},{}".format(self.entities[0].pk, self.entities[1].pk)},
            self.entities[:2],
        )
        self._check_filter({"id__gt": str(self.entities[0].pk)}, self.entities[1:])

    def test_filter_slug(self):
        self._check_filter({"slug": "test-entity-0"}, [self.entities[0]])
        self._check_filter(
            {"slug__in": "test-entity-1,user-entity"}, self.entities[1:3]
        )

    def test_filter_name(self):
        self._check_filter({"name": "Test entity 1"}, [self.entities[1]])
        self._check_filter({"name": "Test entity"}, [])

        self._check_filter({"name__iexact": "test entity 1"}, [self.entities[1]])

        self._check_filter({"name__startswith": "Test entity"}, self.entities[:2])
        self._check_filter({"name__istartswith": "test entity"}, self.entities[:2])

        self._check_filter({"name__contains": "test"}, self.entities[2:])
        self._check_filter({"name__icontains": "test"}, self.entities)

    def test_filter_description(self):
        self._check_filter({"description__icontains": "Favourite"}, [self.entities[1]])
        self._check_filter({"description__contains": "Favourite"}, [])
        self._check_filter({"description__contains": "420"}, [])

    def test_filter_descriptor_schema(self):
        self._check_filter(
            {"descriptor_schema": str(self.descriptor_schema.pk)}, self.entities[:2]
        )
        self._check_filter({"descriptor_schema": "999999"}, [])

    def test_filter_tags(self):
        self._check_filter({"tags": "first-tag"}, self.entities[:2])
        self._check_filter({"tags": "first-tag,second-tag"}, [self.entities[1]])

    def test_filter_contributor(self):
        self._check_filter({"contributor": str(self.contributor.pk)}, self.entities[:2])
        self._check_filter(
            {"contributor__in": "{},{}".format(self.contributor.pk, self.user.pk)},
            self.entities,
        )

    def test_filter_owners(self):
        self._check_filter({"owners": str(self.admin.pk)}, self.entities[:2])
        self._check_filter({"owners": "999999"}, [])

    def test_filter_contributor_name(self):
        # Filter by first name.
        self._check_filter({"contributor_name": "Joe"}, self.entities[:2])
        # Filter by last name.
        self._check_filter({"contributor_name": "Miller"}, self.entities[:2])
        # Filter by username.
        self._check_filter({"contributor_name": "contributor"}, self.entities[:2])
        # Filter by combination of first and last name.
        self._check_filter({"contributor_name": "John Williams"}, self.entities[2:])

    def test_filter_owners_name(self):
        # Filter by first name.
        self._check_filter({"owners_name": "James"}, self.entities[:2])
        # Filter by last name.
        self._check_filter({"owners_name": "Smith"}, self.entities[:2])
        # Filter by username.
        self._check_filter({"owners_name": "admin"}, self.entities[:2])
        # Filter by combination of first and last name.
        self._check_filter({"owners_name": "John Williams"}, [self.entities[2]])

    def test_filter_permission(self):
        self._check_filter({"permission": "edit"}, [self.entities[2]], user=self.user)
        self._check_filter(
            {"permission": "view"},
            self.entities,
            user=self.user,
        )
        self._check_filter({"permission": "owner"}, [self.entities[2]], user=self.user)

    def test_filter_created(self):
        self._check_filter({"created": "2016-07-30T00:59:00"}, self.entities[:1])
        self._check_filter({"created__gt": "2016-07-30T01:59:00"}, self.entities[2:])
        self._check_filter({"created__gte": "2016-07-30T01:59:00"}, self.entities[1:])
        self._check_filter({"created__lt": "2016-07-30T01:59:00"}, self.entities[:1])
        self._check_filter({"created__lte": "2016-07-30T01:59:00"}, self.entities[:2])

    def test_filter_modified(self):
        self._check_filter(
            {"modified": self.entities[0].modified.isoformat()}, self.entities[:1]
        )
        self._check_filter(
            {"modified__gt": self.entities[1].modified.isoformat()}, [self.entities[2]]
        )
        self._check_filter(
            {"modified__gte": self.entities[1].modified.isoformat()}, self.entities[1:3]
        )
        self._check_filter(
            {"modified__lt": self.entities[1].modified.isoformat()},
            self.entities[:1] + [self.entities[3]],
        )
        self._check_filter(
            {"modified__lte": self.entities[1].modified.isoformat()},
            self.entities[:2] + [self.entities[3]],
        )

    def test_filter_collection(self):
        self._check_filter({"collection": str(self.collection1.pk)}, [self.entities[0]])
        self._check_filter(
            {
                "collection__in": "{},{}".format(
                    self.collection1.pk, self.collection2.pk
                )
            },
            self.entities[:2],
        )
        self._check_filter({"collection": "999999"}, [])
        self._check_filter(
            {"collection__in": "{},{}".format(self.collection1.pk, "999999")},
            self.entities[:1],
        )
        self._check_filter(
            {"collection__isnull": True},
            self.entities[2:],
        )

    def test_filter_collection_name(self):
        self._check_filter({"collection__name": "My collection"}, [self.entities[0]])
        self._check_filter(
            {"collection__name__icontains": "Collection"}, self.entities[:2]
        )

    def test_filter_collection_slug(self):
        self._check_filter({"collection__slug": "my-collection"}, [self.entities[0]])
        self._check_filter(
            {"collection__slug__in": "my-collection,other-collection"},
            self.entities[:2],
        )

    def test_filter_text(self):
        # By name.
        self._check_filter({"text": "Test entity 1"}, [self.entities[1]])
        self._check_filter({"text": "Test"}, self.entities)
        self._check_filter({"text": "test"}, self.entities)
        self._check_filter({"text": "user"}, self.entities[2:])

        # By contributor.
        self._check_filter({"text": "joe"}, self.entities[:2])
        self._check_filter({"text": "Miller"}, self.entities[:2])

        # By owner.
        self._check_filter({"text": "james"}, self.entities[:2])
        self._check_filter({"text": "Smith"}, self.entities[:2])

        # By description.
        self._check_filter(
            {"text": "description"}, [self.entities[0], self.entities[2]]
        )
        self._check_filter({"text": "my"}, self.entities[:2])
        self._check_filter({"text": "my description"}, [self.entities[0]])
        self._check_filter({"text": "user"}, self.entities[2:])

        # By descriptor.
        self._check_filter({"text": "genialis"}, [self.entities[0]])
        self._check_filter({"text": "engineering"}, [self.entities[0]])

        # By mixed fields.
        self._check_filter({"text": "test joe"}, self.entities[:2])
        self._check_filter({"text": "joe my description"}, [self.entities[0]])

        # Check that changes are applied immediately.
        self.entities[0].name = "Awesome new name"
        self.entities[0].save()

        self._check_filter({"text": "awesome"}, [self.entities[0]])

    def test_filter_mixed(self):
        self._check_filter(
            {"name": "Test entity 0", "owners_name": "James Smith"}, [self.entities[0]]
        )
        self._check_filter(
            {"text": "entity 0", "owners_name": "James Smith"}, [self.entities[0]]
        )

    def test_order_by_relevance(self):
        result = self._check_filter({"text": "test entity"}, self.entities)
        self.assertEqual(result.data[0]["id"], self.entities[1].pk)

        # Make another entity more important.
        entity = self.entities[2]
        entity.description = "This is test entity. My test entity rocks."
        entity.save()

        result = self._check_filter({"text": "test entity"}, self.entities)
        self.assertEqual(result.data[0]["id"], self.entities[2].pk)

        # Check that ordering can be overriden.
        result = self._check_filter(
            {"text": "test entity", "ordering": "id"}, self.entities
        )
        self.assertEqual(result.data[0]["id"], self.entities[0].pk)

    def test_filter_by_relation(self):
        self._check_filter({"relation_id": self.relation1.id}, self.entities[:1])
        self._check_filter({"relation_id": self.relation2.id}, self.entities[1:])
        self._check_filter({"relation_id": 42}, [])

    def test_filter_group(self):
        self._check_filter({"group": self.group.pk}, [self.entities[2]])

    def test_filter_shared_with_me(self):
        self._check_filter({"shared_with_me": True}, self.entities[:3], user=self.user)
        self._check_filter(
            {"shared_with_me": False}, [self.entities[3]], user=self.user
        )

class DataViewSetFiltersTest(BaseViewSetFiltersTest):
    @classmethod
    def setUpTestData(cls):
        super().setUpTestData()
        tzone = get_current_timezone()

        descriptor_schema = DescriptorSchema.objects.create(
            slug="test-schema",
            version="1.0.0",
            contributor=cls.contributor,
            schema=[
                {
                    "name": "company",
                    "group": [
                        {
                            "name": "name",
                            "type": "basic:string:",
                            "required": False,
                        },
                        {
                            "name": "departments",
                            "type": "list:basic:string:",
                            "required": False,
                        },
                    ],
                }
            ],
        )

        cls.collection1 = Collection.objects.create(
            name="My collection",
            slug="my-collection",
            contributor=cls.contributor,
        )

        cls.collection2 = Collection.objects.create(
            name="Other collection",
            slug="other-collection",
            contributor=cls.contributor,
        )

        cls.entity1 = Entity.objects.create(
            name="My entity",
            slug="my-entity",
            collection=cls.collection1,
            contributor=cls.contributor,
        )

        cls.entity2 = Entity.objects.create(
            name="Other entity",
            slug="other-entity",
            collection=cls.collection2,
            contributor=cls.contributor,
        )

        cls.proc1 = Process.objects.create(
            type="data:test:process1:",
            name="First process",
            slug="test-process-1",
            version="1.0.0",
            contributor=cls.contributor,
            input_schema=[
                {"name": "input_data", "type": "data:test:", "required": False}
            ],
        )

        cls.proc2 = Process.objects.create(
            type="data:test:process2:",
            name="Second process",
            slug="test-process-2",
            version="1.0.0",
            contributor=cls.contributor,
            input_schema=[
                {"name": "input_data", "type": "data:test:", "required": False}
            ],
        )

        cls.data = [
            Data.objects.create(
                name="Data 0",
                slug="dataslug-0",
                contributor=cls.contributor,
                collection=cls.collection1,
                entity=cls.entity1,
                process=cls.proc1,
                status=Data.STATUS_RESOLVING,
                started=datetime.datetime(2016, 7, 31, 0, 0, tzinfo=tzone),
                finished=datetime.datetime(2016, 7, 31, 0, 30, tzinfo=tzone),
                tags=["first-tag"],
                descriptor_schema=descriptor_schema,
                descriptor={
                    "company": {
                        "name": "Genialis",
                        "departments": ["engineering", "operations"],
                    }
                },
            ),
            Data.objects.create(
                name="Data 1",
                slug="dataslug-1",
                contributor=cls.contributor,
                collection=cls.collection2,
                entity=cls.entity2,
                process=cls.proc1,
                status=Data.STATUS_DONE,
                started=datetime.datetime(2016, 7, 31, 1, 0, tzinfo=tzone),
                finished=datetime.datetime(2016, 7, 31, 1, 30, tzinfo=tzone),
                tags=["first-tag", "second-tag", "data"],
            ),
            Data.objects.create(
                name="User data",
                slug="dataslug-2",
                contributor=cls.user,
                process=cls.proc2,
                status=Data.STATUS_DONE,
                started=datetime.datetime(2016, 7, 31, 2, 0, tzinfo=tzone),
                finished=datetime.datetime(2016, 7, 31, 2, 30, tzinfo=tzone),
                tags=["second-tag"],
            ),
            Data.objects.create(
                name="Public data",
                slug="public-data",
                contributor=cls.user,
                process=cls.proc2,
                status=Data.STATUS_DONE,
                started=datetime.datetime(2016, 7, 31, 2, 0, tzinfo=tzone),
                finished=datetime.datetime(2016, 7, 31, 2, 30, tzinfo=tzone),
            ),
        ]

        cls.rel_type = RelationType.objects.create(name="series", ordered=True)
        cls.relation1 = Relation.objects.create(
            type=cls.rel_type, collection=cls.collection1, contributor=cls.contributor
        )
        cls.relation1.entities.set([cls.entity1, cls.entity2])
        cls.relation1.save()
        cls.relation2 = Relation.objects.create(
            type=cls.rel_type, collection=cls.collection2, contributor=cls.contributor
        )
        cls.relation2.entities.set([cls.entity2])
        cls.relation2.save()

        cls.data[0].created = datetime.datetime(2016, 7, 30, 0, 59, tzinfo=tzone)
        cls.data[0].save()
        cls.data[1].created = datetime.datetime(2016, 7, 30, 1, 59, tzinfo=tzone)
        cls.data[1].save()
        cls.data[2].created = datetime.datetime(2016, 7, 30, 2, 59, tzinfo=tzone)
        cls.data[2].save()

        cls.collection1.set_permission(Permission.OWNER, cls.admin)
        cls.collection1.set_permission(Permission.VIEW, cls.user)
        cls.collection2.set_permission(Permission.OWNER, cls.admin)
        cls.collection2.set_permission(Permission.VIEW, cls.user)
        cls.data[2].set_permission(Permission.OWNER, cls.user)
        cls.data[2].set_permission(Permission.VIEW, cls.group)
        cls.data[3].set_permission(Permission.VIEW, get_anonymous_user())

        cls.viewset_class = DataViewSet

    def test_filter_id(self):
        self._check_filter({"id": str(self.data[0].pk)}, [self.data[0]])
        self._check_filter({"id": 420}, [])
        self._check_filter(
            {"id__in": "{},{}".format(self.data[0].pk, self.data[2].pk)},
            [self.data[0], self.data[2]],
        )

    def test_filter_slug(self):
        self._check_filter({"slug": "dataslug-1"}, [self.data[1]])
        self._check_filter(
            {"slug__in": "dataslug-1,dataslug-2"}, [self.data[1], self.data[2]]
        )

    def test_filter_name(self):
        self._check_filter({"name": "Data 1"}, [self.data[1]])
        self._check_filter({"name": "Data"}, [])

        self._check_filter({"name__iexact": "data 1"}, [self.data[1]])

        self._check_filter({"name__startswith": "Data"}, self.data[:2])
        self._check_filter({"name__istartswith": "data"}, self.data[:2])

        self._check_filter({"name__contains": "Data"}, self.data[:2])
        self._check_filter({"name__icontains": "Data"}, self.data)

    def test_filter_tags(self):
        self._check_filter({"tags": "first-tag"}, self.data[:2])
        self._check_filter({"tags": "first-tag,second-tag"}, [self.data[1]])

    def test_filter_contributor(self):
        self._check_filter({"contributor": str(self.contributor.pk)}, self.data[:2])
        self._check_filter(
            {"contributor__in": "{},{}".format(self.contributor.pk, self.user.pk)},
            self.data,
        )

    def test_filter_owners(self):
        self._check_filter({"owners": str(self.admin.pk)}, self.data[:2])
        self._check_filter({"owners": "999999"}, [])

    def test_filter_contributor_name(self):
        # Filter by first name.
        self._check_filter({"contributor_name": "Joe"}, self.data[:2])
        # Filter by last name.
        self._check_filter({"contributor_name": "Miller"}, self.data[:2])
        # Filter by username.
        self._check_filter({"contributor_name": "contributor"}, self.data[:2])
        # Filter by combination of first and last name.
        self._check_filter({"contributor_name": "John Williams"}, self.data[2:])

    def test_filter_owners_name(self):
        # Filter by first name.
        self._check_filter({"owners_name": "James"}, self.data[:2])
        # Filter by last name.
        self._check_filter({"owners_name": "Smith"}, self.data[:2])
        # Filter by username.
        self._check_filter({"owners_name": "admin"}, self.data[:2])
        # Filter by combination of first and last name.
        self._check_filter({"owners_name": "John Williams"}, self.data[2:])

    def test_filter_permission(self):
        self._check_filter({"permission": "edit"}, self.data[2:], user=self.user)
        self._check_filter(
            {"permission": "view"},
            self.data,
            user=self.user,
        )
        self._check_filter({"permission": "owner"}, self.data[2:], user=self.user)

    def test_filter_created(self):
        self._check_filter({"created": "2016-07-30T00:59:00"}, [self.data[0]])
        self._check_filter({"created__gt": "2016-07-30T01:59:00"}, self.data[2:])
        self._check_filter({"created__gte": "2016-07-30T01:59:00"}, self.data[1:])
        self._check_filter({"created__lt": "2016-07-30T01:59:00"}, self.data[:1])
        self._check_filter({"created__lte": "2016-07-30T01:59:00"}, self.data[:2])

    def test_filter_modified(self):
        self._check_filter(
            {"modified": self.data[0].modified.isoformat()}, [self.data[0]]
        )
        self._check_filter(
            {"modified__gt": self.data[1].modified.isoformat()}, [self.data[2]]
        )
        self._check_filter(
            {"modified__gte": self.data[1].modified.isoformat()}, self.data[1:3]
        )
        self._check_filter(
            {"modified__lt": self.data[1].modified.isoformat()},
            self.data[:1] + [self.data[3]],
        )
        self._check_filter(
            {"modified__lte": self.data[1].modified.isoformat()},
            self.data[:2] + [self.data[3]],
        )

    def test_filter_started(self):
        self._check_filter({"started": "2016-07-31T00:00:00"}, [self.data[0]])
        self._check_filter({"started__gt": "2016-07-31T01:00:00"}, self.data[2:])
        self._check_filter({"started__gte": "2016-07-31T01:00:00"}, self.data[1:])
        self._check_filter({"started__lt": "2016-07-31T01:00:00"}, self.data[:1])
        self._check_filter({"started__lte": "2016-07-31T01:00:00"}, self.data[:2])

    def test_filter_finished(self):
        self._check_filter({"finished": "2016-07-31T00:30:00"}, [self.data[0]])
        self._check_filter({"finished__gt": "2016-07-31T01:30:00"}, self.data[2:])
        self._check_filter({"finished__gte": "2016-07-31T01:30:00"}, self.data[1:])
        self._check_filter({"finished__lt": "2016-07-31T01:30:00"}, self.data[:1])
        self._check_filter({"finished__lte": "2016-07-31T01:30:00"}, self.data[:2])

    def test_filter_collection(self):
        self._check_filter({"collection": str(self.collection1.pk)}, [self.data[0]])
        self._check_filter(
            {
                "collection__in": "{},{}".format(
                    self.collection1.pk, self.collection2.pk
                )
            },
            self.data[:2],
        )
        self._check_filter({"collection": "999999"}, [])
        self._check_filter(
            {"collection__in": "{},{}".format(self.collection1.pk, "999999")},
            self.data[:1],
        )
        self._check_filter(
            {"collection__isnull": True},
            self.data[2:],
        )

    def test_filter_collection_name(self):
        self._check_filter({"collection__name": "My collection"}, [self.data[0]])
        self._check_filter({"collection__name__icontains": "Collection"}, self.data[:2])

    def test_filter_collection_slug(self):
        self._check_filter({"collection__slug": "my-collection"}, [self.data[0]])
        self._check_filter(
            {"collection__slug__in": "my-collection,other-collection"}, self.data[:2]
        )

    def test_filter_entity(self):
        self._check_filter({"entity": str(self.entity1.pk)}, [self.data[0]])
        self._check_filter(
            {"entity__in": "{},{}".format(self.entity1.pk, self.entity2.pk)},
            self.data[:2],
        )
        self._check_filter({"entity": "999999"}, [])
        self._check_filter(
            {"entity__in": "{},{}".format(self.entity1.pk, "999999")},
            [self.data[0]],
        )
        self._check_filter(
            {"entity__in": "{},{}".format(self.entity1.pk, self.entity2.pk)},
            self.data[:2],
        )
        self._check_filter(
            {"entity__isnull": True},
            self.data[2:],
        )

    def test_filter_entity_name(self):
        self._check_filter({"entity__name": "My entity"}, [self.data[0]])
        self._check_filter({"entity__name__icontains": "Entity"}, self.data[:2])

    def test_filter_entity_slug(self):
        self._check_filter({"entity__slug": "my-entity"}, [self.data[0]])
        self._check_filter(
            {"entity__slug__in": "my-entity,other-entity"}, self.data[:2]
        )

    def test_filter_type(self):
        self._check_filter({"type": "data:"}, self.data)
        self._check_filter({"type": "data:test:"}, self.data)
        self._check_filter({"type": "data:test:process1"}, self.data[:2])
        self._check_filter({"type": "data:test:process1:"}, self.data[:2])
        self._check_filter({"type__exact": "data:test"}, [])
        self._check_filter({"type__exact": "data:test:process1:"}, self.data[:2])

    def test_filter_status(self):
        self._check_filter({"status": "OK"}, self.data[1:])
        self._check_filter({"status": "RE"}, [self.data[0]])
        self._check_filter({"status__in": "OK,RE"}, self.data)

    def test_filter_process(self):
        self._check_filter({"process": str(self.proc1.pk)}, self.data[:2])
        self._check_filter({"process": str(self.proc2.pk)}, self.data[2:])
        self._check_filter({"process": "999999"}, [])

    def test_filter_process_name(self):
        self._check_filter({"process__name": "First process"}, self.data[:2])
        self._check_filter({"process__name__iexact": "first process"}, self.data[:2])
        self._check_filter({"process__name__startswith": "First"}, self.data[:2])
        self._check_filter({"process__name": "first process"}, [])

    def test_filter_process_slug(self):
        self._check_filter({"process__slug": "test-process-1"}, self.data[:2])
        self._check_filter({"process__slug": "test-process-2"}, self.data[2:])
        self._check_filter({"process__slug": "test-process"}, [])

    def test_filter_text(self):
        # By name.
        self._check_filter({"text": "Data 1"}, [self.data[1]])
        self._check_filter({"text": "Data"}, self.data)
        self._check_filter({"text": "data"}, self.data)

        # By contributor.
        self._check_filter({"text": "joe"}, self.data[:2])
        self._check_filter({"text": "Miller"}, self.data[:2])

        # By owner.
        self._check_filter({"text": "james"}, self.data[:2])
        self._check_filter({"text": "Smith"}, self.data[:2])

        # By process name.
        self._check_filter({"text": "first"}, self.data[:2])
        self._check_filter({"text": "process"}, self.data)

        # By descriptor.
        self._check_filter({"text": "genialis"}, [self.data[0]])
        self._check_filter({"text": "engineering"}, [self.data[0]])

        # By mixed fields.
        self._check_filter({"text": "data joe"}, self.data[:2])
        self._check_filter({"text": "joe first"}, self.data[:2])

        # Check that changes are applied immediately.
        self.data[0].name = "Awesome new name"
        self.data[0].save()

        self._check_filter({"text": "awesome"}, [self.data[0]])

    def test_filter_mixed(self):
        self._check_filter(
            {"name": "Data 0", "owners_name": "James Smith"}, [self.data[0]]
        )
        self._check_filter(
            {"text": "Data 0", "owners_name": "James Smith"}, [self.data[0]]
        )

    def test_order_by_relevance(self):
        result = self._check_filter({"text": "data"}, self.data)
        self.assertEqual(result.data[0]["id"], self.data[1].pk)

        # Make another entity more important.
        data = self.data[2]
        data.name = "Data data data"
        data.save()

        result = self._check_filter({"text": "data"}, self.data)
        self.assertEqual(result.data[0]["id"], self.data[2].pk)

        # Check that ordering can be overriden.
        result = self._check_filter({"text": "data", "ordering": "id"}, self.data)
        self.assertEqual(result.data[0]["id"], self.data[0].pk)

    def test_nonexisting_parameter(self):
        response = self._check_filter({"foo": "bar"}, [], expected_status_code=400)

        self.assertRegex(
            str(response.data["__all__"]),
            r"Unsupported parameter\(s\): foo. Please use a combination of: .*",
        )

    def test_filter_by_relation(self):
        self._check_filter(
            {"relation_id": self.relation1.id}, [self.data[0], self.data[1]]
        )
        self._check_filter({"relation_id": self.relation2.id}, [self.data[1]])
        self._check_filter({"relation_id": 42}, [])

    def test_filter_group(self):
        self._check_filter({"group": self.group.pk}, [self.data[2]])

    def test_filter_shared_with_me(self):
        self._check_filter({"shared_with_me": True}, self.data[:3], user=self.user)
        self._check_filter({"shared_with_me": False}, [self.data[3]], user=self.user)

class DescriptorSchemaViewSetFiltersTest(BaseViewSetFiltersTest):
    def setUp(self):
        self.viewset_class = DescriptorSchemaViewSet
        super().setUp()

        tzone = get_current_timezone()

        self.ds1 = DescriptorSchema.objects.create(
            contributor=self.user, slug="slug1", name="ds1"
        )
        self.ds1.created = datetime.datetime(2015, 7, 28, 11, 57, tzinfo=tzone)
        self.ds1.save()

        self.ds2 = DescriptorSchema.objects.create(
            contributor=self.user, slug="slug2", name="ds2"
        )
        self.ds2.created = datetime.datetime(2016, 8, 29, 12, 58, 0, tzinfo=tzone)
        self.ds2.save()

        self.ds3 = DescriptorSchema.objects.create(
            contributor=self.admin, slug="slug3", name="ds3"
        )
        self.ds3.created = datetime.datetime(2017, 9, 30, 13, 59, 0, tzinfo=tzone)
        self.ds3.save()

    def test_id(self):
        self._check_filter({"id": self.ds1.pk}, [self.ds1])
        self._check_filter({"id": self.ds2.pk}, [self.ds2])
        self._check_filter({"id__in": self.ds2.pk}, [self.ds2])
        self._check_filter(
            {"id__in": "{},{}".format(self.ds1.pk, self.ds2.pk)}, [self.ds1, self.ds2]
        )
        self._check_filter({"id__gt": self.ds1.pk}, [self.ds2, self.ds3])

    def test_slug(self):
        self._check_filter({"slug": "slug1"}, [self.ds1])
        self._check_filter({"slug": "slug2"}, [self.ds2])
        self._check_filter({"slug__in": "slug"}, [])
        self._check_filter({"slug__in": "slug2,slug"}, [self.ds2])

    def test_name(self):
        self._check_filter({"name": "ds1"}, [self.ds1])
        self._check_filter({"name": "ds2"}, [self.ds2])
        self._check_filter({"name__startswith": "ds"}, [self.ds1, self.ds2, self.ds3])
        self._check_filter({"name__startswith": "ds2"}, [self.ds2])
        self._check_filter({"name__startswith": "dsx"}, [])
        self._check_filter({"name__icontains": "2"}, [self.ds2])
        self._check_filter({"name__icontains": "DS"}, [self.ds1, self.ds2, self.ds3])

    def test_contributor(self):
        self._check_filter({"contributor": self.user.pk}, [self.ds1, self.ds2])
        self._check_filter({"contributor": self.admin.pk}, [self.ds3])
        self._check_filter({"contributor": "999999"}, [])
        self._check_filter({"contributor__in": self.admin.pk}, [self.ds3])
        self._check_filter(
            {"contributor__in": "999999,{}".format(self.admin.pk)}, [self.ds3]
        )
        self._check_filter(
            {"contributor__in": "{},{}".format(self.user.pk, self.admin.pk)},
            [self.ds1, self.ds2, self.ds3],
        )

    def test_created(self):
        self._check_filter({"created": "2015-07-28T11:57:00"}, [self.ds1])
        self._check_filter({"created": "2016-08-29T12:58:00.000000"}, [self.ds2])
        self._check_filter({"created": "2017-09-30T13:59:00.000000Z"}, [self.ds3])
        self._check_filter({"created": "2017-09-30T13:59:00.000000+0000"}, [self.ds3])
        self._check_filter({"created": "2017-09-30T13:59:00.000000+0000"}, [self.ds3])

        self._check_filter({"created__date": "2016-08-29"}, [self.ds2])
        self._check_filter({"created__time": "12:58:00"}, [self.ds2])

    def test_modified(self):
        now = self.ds1.modified
        self._check_filter(
            {"modified": now.strftime("%Y-%m-%dT%H:%M:%S.%f%z")}, [self.ds1]
        )

    def test_nonexisting_parameter(self):
        response = self._check_filter(
            {"foo": "bar"}, [self.ds1], expected_status_code=400
        )

        self.assertRegex(
            str(response.data["__all__"][0]),
            r"Unsupported parameter\(s\): foo. Please use a combination of: .*",
        )

class ProcessViewSetFiltersTest(BaseViewSetFiltersTest):
    @classmethod
    def setUpTestData(cls):
        super().setUpTestData()

        cls.proc_1 = Process.objects.create(
            contributor=cls.contributor,
            type="data:alignment:bam:",
            category="analyses:alignment:",
            scheduling_class="BA",
        )

        cls.proc_2 = Process.objects.create(
            contributor=cls.contributor,
            type="data:expression:",
            category="analyses:",
            scheduling_class="IN",
        )

        cls.viewset_class = ProcessViewSet

    def test_category(self):
        self._check_filter({"category": "analyses:"}, [self.proc_1, self.proc_2])
        self._check_filter({"category": "analyses:alignment"}, [self.proc_1])

    def test_type(self):
        self._check_filter({"type": "data:"}, [self.proc_1, self.proc_2])
        self._check_filter({"type": "data:alignment:bam"}, [self.proc_1])
        self._check_filter({"type": "data:expression"}, [self.proc_2])

    def test_scheduling_class(self):
        self._check_filter({"scheduling_class": "BA"}, [self.proc_1])
        self._check_filter({"scheduling_class": "IN"}, [self.proc_2])

    def test_is_active(self):
        self._check_filter({"is_active": "true"}, [self.proc_1, self.proc_2])
        self._check_filter({"is_active": "false"}, [])

        self.proc_1.is_active = False
        self.proc_1.save()

        self._check_filter({"is_active": "true"}, [self.proc_2])
        self._check_filter({"is_active": "false"}, [self.proc_1])


text:
import javax.swing.JOptionPane;

public class EntradaEjemploII {

	public static void main(String[] args) {
		String nombre_usuario = JOptionPane.showInputDialog("Ingresa tu nombre:");
		String edad = JOptionPane.showInputDialog("Ingresa tu edad:");
		int edad_usuario = Integer.parseInt(edad);
		edad_usuario++;

		System.out.println("Hola " + nombre_usuario + " tienes " + edad_usuario + " annios");
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2;

/**
 * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2
 * @xmlType MaximumQuantityType
 * @xmlName MaximumQuantity
 * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\MaximumQuantity
 */
class MaximumQuantity extends MaximumQuantityType
{
} // end class MaximumQuantity


text:
// Copyright (c) Aurora Studio. All rights reserved.
//
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Aurora.Music.ViewModels;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

//https://go.microsoft.com/fwlink/?LinkId=234236 上介绍了"用户控件"项模板

namespace Aurora.Music.Controls.ListItems
{
    public sealed partial class LyricItem : UserControl
    {
        public LyricItem()
        {
            this.InitializeComponent();
        }

        public LrcContent Data
        {
            get { return (LrcContent)GetValue(DataProperty); }
            set { SetValue(DataProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register("Data", typeof(LrcContent), typeof(LyricItem), new PropertyMetadata(null));

    }

    public class LyricTrigger : StateTriggerBase
    {

        public bool IsCurrent
        {
            get { return (bool)GetValue(IsCurrentProperty); }
            set { SetValue(IsCurrentProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsCurrent.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsCurrentProperty =
            DependencyProperty.Register("IsCurrent", typeof(bool), typeof(LyricTrigger), new PropertyMetadata(false, OnIsCurrentChanged));

        private static void OnIsCurrentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is LyricTrigger l)
            {
                l.SetActive((bool)e.NewValue);
            }
        }
    }
}


text:
class Answer < ActiveRecord::Base
	belongs_to :user
	belongs_to :question
end


text:
module IdentityPlugin
  class IdentityMailer < ActionMailer::Base
    def password_reset(identity, url)
      @from = Config.hash[:mail_sender]
      @identity = identity
      @url = url
      mail from: @from, to: identity.email, subject: 'Password Reset'
    end
  end
end


text:
package common.exceptions.join;

import java.io.Serializable;

import common.exceptions.CustomBaseException;

public class MaximumPlayerExceededException extends CustomBaseException implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 7976493500538138798L;

}


text:
import os
import re
import subprocess
import sys
import warnings

import setuptools
import setuptools.command.build_ext
import wheel.bdist_wheel

_this_dir = os.path.dirname(os.path.abspath(__file__))
_clib_dir = os.path.join(_this_dir, 'python', 'opencc', 'clib')
_build_dir = os.path.join(_this_dir, 'build', 'python')

_cmake_file = os.path.join(_this_dir, 'CMakeLists.txt')
_author_file = os.path.join(_this_dir, 'AUTHORS')
_readme_file = os.path.join(_this_dir, 'README.md')

try:
    sys.path.insert(0, os.path.join(_this_dir, 'python'))

    import opencc  # noqa
    _libopencc_built = True
except ImportError:
    _libopencc_built = False

def get_version_info():
    version_info = ['1', '0', '0']
    version_pattern = re.compile(
        r'OPENCC_VERSION_(MAJOR|MINOR|REVISION) (\d+)')
    with open(_cmake_file, 'rb') as f:
        for l in f:
            match = version_pattern.search(l.decode('utf-8'))
            if not match:
                continue
            if match.group(1) == 'MAJOR':
                version_info[0] = match.group(2)
            elif match.group(1) == 'MINOR':
                version_info[1] = match.group(2)
            elif match.group(1) == 'REVISION':
                version_info[2] = match.group(2)
    version = '.'.join(version_info)
    return version

def get_author_info():
    if not os.path.isfile(_author_file):
        return 'BYVoid', 'byvoid@byvoid.com'

    authors = []
    emails = []
    author_pattern = re.compile(r'(.+) <(.+)>')
    with open(_author_file, 'rb') as f:
        for line in f:
            match = author_pattern.search(line.decode('utf-8'))
            if not match:
                continue
            authors.append(match.group(1))
            emails.append(match.group(2))

    if len(authors) == 0:
        return 'BYVoid', 'byvoid@byvoid.com'

    return ', '.join(authors), ', '.join(emails)

def get_long_description():
    with open(_readme_file, 'rb') as f:
        return f.read().decode('utf-8')

def build_libopencc():
    if _libopencc_built:
        return  # Skip building binary file
    print('building libopencc into %s' % _build_dir)

    is_windows = sys.platform == 'win32'

    # Make build directories
    if is_windows:
        subprocess.call('md {}'.format(_build_dir), shell=True)
        subprocess.call('md {}'.format(_clib_dir), shell=True)
    else:
        subprocess.call('mkdir -p {}'.format(_build_dir), shell=True)
        subprocess.call('mkdir -p {}'.format(_clib_dir), shell=True)

    # Configure
    cmake_args = [
        '-DBUILD_DOCUMENTATION:BOOL=OFF',
        '-DBUILD_SHARED_LIBS:BOOL=OFF',
        '-DENABLE_GTEST:BOOL=OFF',
        '-DENABLE_BENCHMARK:BOOL=OFF',
        '-DBUILD_PYTHON:BOOL=ON',
        '-DCMAKE_BUILD_TYPE=Release',
        '-DCMAKE_INSTALL_PREFIX={}'.format(_clib_dir),
        '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={}'.format(_clib_dir),
        '-DPYTHON_EXECUTABLE={}'.format(sys.executable),
    ]

    if is_windows:
        cmake_args += \
            ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE={}'.format(_clib_dir)]
        if sys.maxsize > 2**32:
            cmake_args += ['-A', 'x64']

    cmd = ['cmake', '-B', _build_dir] + cmake_args
    errno = subprocess.call(cmd)
    assert errno == 0, 'Configure failed'

    # Build
    cmd = [
        'cmake', '--build', _build_dir,
        '--config', 'Release',
        '--target', 'install'
    ]
    errno = subprocess.call(cmd)
    assert errno == 0, 'Build failed'

    # Empty __init__.py file has to be created
    # to make opencc.clib a module
    with open('{}/__init__.py'.format(_clib_dir), 'w'):
        pass

class OpenCCExtension(setuptools.Extension, object):
    def __init__(self, name, sourcedir=''):
        setuptools.Extension.__init__(self, name, sources=[])
        self.sourcedir = os.path.abspath(sourcedir)

class BuildExtCommand(setuptools.command.build_ext.build_ext, object):
    def build_extension(self, ext):
        if isinstance(ext, OpenCCExtension):
            build_libopencc()
        else:
            super(BuildExtCommand, self).build_extension(ext)

class BDistWheelCommand(wheel.bdist_wheel.bdist_wheel, object):
    """Custom bdsit_wheel command that will change
    default plat-name based on PEP 425 and PEP 513
    """

    @staticmethod
    def _determine_platform_tag():
        if sys.platform == 'win32':
            if 'amd64' in sys.version.lower():
                return 'win-amd64'
            return sys.platform

        if sys.platform == 'darwin':
            _, _, _, _, machine = os.uname()
            if machine == 'x86_64':
                return 'macosx-10.9-{}'.format(machine)
            if machine == 'arm64':
                return 'macosx-11.0-{}'.format(machine)
            else:
                raise NotImplementedError

        if os.name == 'posix':
            _, _, _, _, machine = os.uname()
            return 'manylinux1-{}'.format(machine)

        warnings.warn(
            'Windows macos and linux are all not detected, '
            'Proper distribution name cannot be determined.')
        from distutils.util import get_platform
        return get_platform()

    def initialize_options(self):
        super(BDistWheelCommand, self).initialize_options()
        self.plat_name = self._determine_platform_tag()

packages = ['opencc', 'opencc.clib']

version_info = get_version_info()
author_info = get_author_info()

setuptools.setup(
    name='OpenCC',
    version=version_info,
    author=author_info[0],
    author_email=author_info[1],
    description=" Conversion between Traditional and Simplified Chinese",
    long_description=get_long_description(),
    long_description_content_type="text/markdown",
    url="https://github.com/BYVoid/OpenCC",

    packages=packages,
    package_dir={'opencc': 'python/opencc'},
    package_data={str('opencc'): [
        'clib/opencc_clib*',
        'clib/share/opencc/*',
    ]},
    ext_modules=[OpenCCExtension('opencc.clib.opencc_clib', 'python')],
    cmdclass={
        'build_ext': BuildExtCommand,
        'bdist_wheel': BDistWheelCommand
    },

    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'Natural Language :: Chinese (Simplified)',
        'Natural Language :: Chinese (Traditional)',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'License :: OSI Approved :: Apache Software License',
        'Topic :: Scientific/Engineering',
        'Topic :: Software Development',
        'Topic :: Software Development :: Libraries',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Software Development :: Localization',
        'Topic :: Text Processing :: Linguistic',
    ],
    license='Apache License 2.0',
    keywords=['opencc', 'convert', 'chinese']
)


text:
package net.maritimecloud.common.cqrs.contract;

/**
 * This interface describes the interface to the ServiceRegitry in terms of Commands and Events. Whereas the commands are explicitly being
 * the published interface, the description of the events are more like a convenience as they in most cases share the properties of the
 * commands.
 *

 * Events may inherit their properties from corresponding commands, and may extend those properties, as would be needed to make room for
 * enrichment.
 *

 * The generator will take each method defined in the interface and create a corresponding class of the same name (capitalized first
 * letter). The class will be supplied with a constructor with the same signature and properties and getters and setters will be defined for
 * each of the arguments using the names of the arguments. The first argument MUST be the aggregate identity, and the names of the arguments
 * will be used for serialization when serializing to JSON.
 *

 * @author Christoffer Børrild
 */
public interface CqrsContract {

}


text:
<?php

namespace Hal\Metrics\Complexity\Text\Halstead;
use Hal\Component\Result\ExportableInterface;

/**
 * Representation of Halstead complexity
 *
 * @author Jean-François Lépine <https://twitter.com/Halleck45>
 */
class Result implements ExportableInterface {
    /**
     * Length of a program
     *
     * @var integer
     */
    private $length;

    /**
     * Vocabulary
     *
     * @var integer
     */
    private $vocabulary;

    /**
     * Volume
     *
     * @var integer
     */
    private $volume;

    /**
     * Difficulty
     *
     * @var float
     */
    private $difficulty;

    /**
     * Effort
     *
     * @var float
     */
    private $effort;

    /**
     * Bugs expected
     *
     * @var float
     */
    private $bugs;

    /**
     * Time
     *
     * @var integer
     */
    private $time;

    /**
     * Intelligent content
     *
     * @var integer
     */
    private $intelligentContent;

    /**
     * @var
     */
    private $level;

    /**
     * @var
     */
    private $numberOfOperators;

    /**
     * @var
     */
    private $numberOfUniqueOperators;

    /**
     * @var
     */
    private $numberOfOperands;

    /**
     * @var
     */
    private $numberOfUniqueOperands;
    /**
     * @inheritdoc
     */
    public function asArray() {
        return array(
            'volume' => $this->getVolume()
            ,'length' => $this->getLength()
            ,'vocabulary' => $this->getVocabulary()
            ,'effort' => $this->getEffort()
            ,'difficulty' => (string) $this->getDifficulty()
            ,'time' => $this->getTime()
            ,'bugs' => round($this->getBugs(), 2)
            ,'intelligentContent' => $this->getIntelligentContent()
        );
    }

    /**
     * @param float $bugs
     * @return $this
     */
    public function setBugs($bugs)
    {
        $this->bugs = $bugs;
        return $this;
    }

    /**
     * @return float
     */
    public function getBugs()
    {
        return $this->bugs;
    }

    /**
     * @param float $difficulty
     * @return $this
     */
    public function setDifficulty($difficulty)
    {
        $this->difficulty = $difficulty;
        return $this;
    }

    /**
     * @return float
     */
    public function getDifficulty()
    {
        return $this->difficulty;
    }

    /**
     * @param float $effort
     * @return $this
     */
    public function setEffort($effort)
    {
        $this->effort = $effort;
        return $this;
    }

    /**
     * @return float
     */
    public function getEffort()
    {
        return $this->effort;
    }

    /**
     * @param int $length
     * @return $this
     */
    public function setLength($length)
    {
        $this->length = $length;
        return $this;
    }

    /**
     * @return int
     */
    public function getLength()
    {
        return $this->length;
    }

    /**
     * @param int $time
     * @return $this
     */
    public function setTime($time)
    {
        $this->time = $time;
        return $this;
    }

    /**
     * @return int
     */
    public function getTime()
    {
        return $this->time;
    }

    /**
     * @param int $vocabulary
     * @return $this
     */
    public function setVocabulary($vocabulary)
    {
        $this->vocabulary = $vocabulary;
        return $this;
    }

    /**
     * @return int
     */
    public function getVocabulary()
    {
        return $this->vocabulary;
    }

    /**
     * @param int $volume
     * @return $this
     */
    public function setVolume($volume)
    {
        $this->volume = $volume;
        return $this;
    }

    /**
     * @return int
     */
    public function getVolume()
    {
        return $this->volume;
    }

    /**
     * @return integer
     */
    public function getIntelligentContent() {
        return $this->intelligentContent;
    }

    /**
     * @param float $intelligentContent
     * @return $this
     */
    public function setIntelligentContent($intelligentContent)
    {
        $this->intelligentContent = $intelligentContent;
        return $this;
    }

    /**
     * @param int $numberOfOperands
     * @return $this
     */
    public function setNumberOfOperands($numberOfOperands)
    {
        $this->numberOfOperands = (int) $numberOfOperands;
        return $this;
    }

    /**
     * @return int
     */
    public function getNumberOfOperands()
    {
        return $this->numberOfOperands;
    }

    /**
     * @param int $numberOfOperators
     * @return $this
     */
    public function setNumberOfOperators($numberOfOperators)
    {
        $this->numberOfOperators = (int) $numberOfOperators;
        return $this;
    }

    /**
     * @return int
     */
    public function getNumberOfOperators()
    {
        return $this->numberOfOperators;
    }

    /**
     * @param int $numberOfUniqueOperands
     * @return $this
     */
    public function setNumberOfUniqueOperands($numberOfUniqueOperands)
    {
        $this->numberOfUniqueOperands = (int) $numberOfUniqueOperands;
        return $this;
    }

    /**
     * @return int
     */
    public function getNumberOfUniqueOperands()
    {
        return $this->numberOfUniqueOperands;
    }

    /**
     * @param int $numberOfUniqueOperators
     * @return $this
     */
    public function setNumberOfUniqueOperators($numberOfUniqueOperators)
    {
        $this->numberOfUniqueOperators = $numberOfUniqueOperators;
        return $this;
    }

    /**
     * @return int
     */
    public function getNumberOfUniqueOperators()
    {
        return $this->numberOfUniqueOperators;
    }

    /**
     * @param double $level
     * @return $this
     */
    public function setLevel($level)
    {
        $this->level = $level;
        return $this;
    }

    /**
     * @return double
     */
    public function getLevel()
    {
        return $this->level;
    }

}


text:
/**
 * @author Roman I. Chernyatchik
 */
package javax.swing.text;

import java.io.Serializable;

import org.apache.harmony.misc.HashCode;

public class TabStop implements Serializable {
    public static final int ALIGN_LEFT = 0;
    public static final int ALIGN_RIGHT = 1;
    public static final int ALIGN_CENTER = 2;
    public static final int ALIGN_DECIMAL = 4;
    public static final int ALIGN_BAR = 5;

    public static final int LEAD_NONE = 0;
    public static final int LEAD_DOTS = 1;
    public static final int LEAD_HYPHENS = 2;
    public static final int LEAD_UNDERLINE = 3;
    public static final int LEAD_THICKLINE = 4;
    public static final int LEAD_EQUALS = 5;

    private final int alignment;
    private final int leader;
    private final float position;

    public TabStop(final float position) {
        this(position, ALIGN_LEFT, LEAD_NONE);
    }

    public TabStop(final float position, final int align, final int leader) {
        this.position = position;
        this.alignment = align;
        this.leader = leader;
    }

    public int getAlignment() {
        return alignment;
    }

    public int getLeader() {
        return leader;
    }

    public float getPosition() {
        return position;
    }

    public boolean equals(final Object other) {
        if (!(other instanceof TabStop)) {
            return false;
        }

        final TabStop tabStop = (TabStop)other;
        return tabStop.alignment == alignment
               && tabStop.leader == leader
               && tabStop.position == position;
    }

    public int hashCode() {
        HashCode hash = new HashCode();

        hash.append(position);
        hash.append(alignment);
        hash.append(leader);

        return hash.hashCode();
    }

    public String toString() {
        final StringBuilder result = new StringBuilder();
        switch (alignment) {
            case ALIGN_RIGHT:
                result.append("right ");
                break;
            case ALIGN_CENTER:
                result.append("center ");
                break;
            case ALIGN_DECIMAL:
                result.append("decimal ");
                break;
            case ALIGN_BAR:
                result.append("bar ");
                break;
        }
        result.append("tab @").append(position);

        if (leader != LEAD_NONE) {
            result.append(" (w/leaders)");
        }

        return result.toString();
    }
}


text:
<!DOCTYPE html>

		<title>Nash Bridges - Série (1996) - Carlton Cuse - SensCritique</title>

				<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
							<meta name="description" content="Nash Bridges est inspecteur au sein de la police de San Francisco.... Série américaine de Carlton Cuse (1996). Nash Bridges (Nash Bridges). Action, Drame, Policier." />
									<meta property="og:image" content="http://media.senscritique.com/media/000006504127/1200/Nash_Bridges.jpg" />

		<link rel="publisher" href="https://plus.google.com/+senscritique">

		<link rel="apple-touch-icon" sizes="57x57" href="http://static.senscritique.com/img/favicon/apple-touch-icon-57x57.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="60x60" href="http://static.senscritique.com/img/favicon/apple-touch-icon-60x60.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="72x72" href="http://static.senscritique.com/img/favicon/apple-touch-icon-72x72.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="76x76" href="http://static.senscritique.com/img/favicon/apple-touch-icon-76x76.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="114x114" href="http://static.senscritique.com/img/favicon/apple-touch-icon-114x114.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="120x120" href="http://static.senscritique.com/img/favicon/apple-touch-icon-120x120.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="144x144" href="http://static.senscritique.com/img/favicon/apple-touch-icon-144x144.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="152x152" href="http://static.senscritique.com/img/favicon/apple-touch-icon-152x152.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="180x180" href="http://static.senscritique.com/img/favicon/apple-touch-icon-180x180.png?v=eELP384vde">
		<link rel="icon" type="image/png" href="http://static.senscritique.com/img/favicon/favicon-32x32.png?v=eELP384vde" sizes="32x32">
		<link rel="icon" type="image/png" href="http://static.senscritique.com/img/favicon/favicon-194x194.png?v=eELP384vde" sizes="194x194">
		<link rel="icon" type="image/png" href="http://static.senscritique.com/img/favicon/favicon-96x96.png?v=eELP384vde" sizes="96x96">
		<link rel="icon" type="image/png" href="http://static.senscritique.com/img/favicon/android-chrome-192x192.png?v=eELP384vde" sizes="192x192">
		<link rel="icon" type="image/png" href="http://static.senscritique.com/img/favicon/favicon-16x16.png?v=eELP384vde" sizes="16x16">
		<link rel="manifest" href="http://static.senscritique.com/img/favicon/manifest.json?v=eELP384vde">
		<link rel="shortcut icon" href="http://static.senscritique.com/img/favicon/favicon.ico?v=eELP384vde">

						<link rel="stylesheet" type="text/css" href="http://static.senscritique.com/lib/optimized_ln/fdf8f64f5bf9f78145e6a2b51f1dd63f.css"/>

	<link rel="stylesheet" type="text/css" href="http://static.senscritique.com/lib/optimized_ln/02e3bc4f88ff14314f5e83299344ad07.css"/>

		<link rel="apple-touch-icon" href="/img/favicon/57.png">
		<link rel="apple-touch-icon" sizes="72x72" href="/img/favicon/72.png">
		<link rel="apple-touch-icon" sizes="114x114" href="/img/favicon/114.png">
		<link rel="publisher" href="https://plus.google.com/+senscritique">

							<button type="button" data-rel="btn-register" data-scmodal-type="login" class="d-link-alt">Déjà inscrit</button> ?
							<form action="/" method="POST" class="lahe-userSubmenu lahe-signin" data-rel="sc-headerSignin">

Connectez-vous avec

								Facebook
								Twitter

ou

								<input type="text" class="lahe-signin-field" name="email" placeholder="Adresse email" data-rel="sc-headerSignin-email" />
								<input type="password" class="lahe-signin-field" name="password" placeholder="Mot de passe" data-rel="sc-headerSignin-password" />
								Mot de passe oublié ?
								<fieldset class="lahe-signin-clear">

									<input type="submit" class="d-button lahe-signin-confirm" value="Connexion" />
								</fieldset>
							</form>

						<button type="button" data-rel="btn-register" data-scmodal-type="register" class="lahe-userMenu-connect">Créer mon compte</button>

					SensCritique

							Films

Au cinéma

																																														Sorties de la semaine
															À l'affiche
															Mes cinémas
															Meilleurs films 2015

TV / VOD

																																														EveryMovie
															A la télé
															En VOD

Guide

																																														Vos films préférés
															Top 111 films
															Sondages

							Séries

Actualité

																																														Séries du moment
															Meilleures séries 2015

Guide

																																														Vos séries préférées
															Top 111 séries
															Sondages

							Jeux

Actualité

																																														Jeux du moment
															Agenda
															Jeux les plus attendus
															Meilleurs jeux 2015

Guide

																																														Vos jeux préférés
															Top 111 jeux
															Sondages

							Livres

Actualité

																																														Livres du moment
															Meilleures ventes
															Meilleurs livres 2015
															Prix littéraires 2014

Guide

																																														Vos livres préférés
															Top 111 livres
															Sondages

							BD

Actualité

																																														Franco-belge
															Comics
															Mangas
															Meilleures BD 2015

Guide

																																														Vos BD préférées
															Top 111 BD
															Sondages

							Musique

Actualité

																																														Albums du moment
															Prochaines sorties
															Meilleurs albums 2015

Guide

																																														Vos albums préférés
															Top 111 albums
															Sondages

						Posts

			<form action="/recherche?" method="GET" class="lahe-searchBar-content" data-rel="sc-headerSearch">

					 Chercher une œuvre, un artiste, une liste, un cinéma ou un membre

						Tout

Tout

Films

Séries

Livres

BD

Jeux vidéo

Albums de musique

Morceaux de musique

Listes d'oeuvres

Sondages

Sagas

Artistes et sociétés

Membres

Cinémas

					<input type="text" name="query" value="" class="unfocus lahe-searchBar-query" data-rel="sc-headerSearch-query" />
					<button type="button" class="lahe-searchBar-close" data-rel="sc-headerSearch-close">

					</button>

			</form>

SensCritique

Séries

Action

Nash Bridges

				Bande-annonce

							Nash Bridges

																								(1996)

Nash Bridges

12345678910

																															<button type="button" data-sc-action="current"
									data-sc-product-id="169031"
									data-sc-tooltip="true"
									title="Je suis cette série"
									class="d-button pvi-product-scaction ">

								En cours
							</button>

												<button type="button" data-sc-action="recommend"
								data-sc-product-id="169031"
								class="d-button pvi-product-scaction "
								style="display:none;">
							 Coup de coeur
						</button>
																			<button type="button" data-rel="bt-review sc-button-modal-sc"
									data-sc-product-id="169031"
									data-scmodal-type="review"
									class="d-button pvi-product-scaction"
									style="display:none;">
								 Critiquer
							</button>

												<button type="button" data-sc-action="wish-list"
								data-sc-product-id="169031"
								class="d-button pvi-product-scaction "
								>

								Envie de la voir

						</button>

												<button type="button" data-rel="sc-button"
								data-sc-product-id="169031"
								class="d-button pvi-product-contextmenu">

						</button>

															4.6

							10
							1
							474
							1

30

47

70

100

96

75

37

13

3

3

					30

30

					1

					47

47

					2

					70

70

					3

					100

100

					4

					96

96

					5

					75

75

					6

					37

37

					7

					13

13

					8

					3

3

					9

					3

3

					10

									474

									9

									7

										3

					<button type="button" class="pco-social-action" data-rel="sc-share-tooltip" data-sc-product-id="169031">Partager</button>

					<button type="button" class="pco-social-action" data-rel="sc-buy-tooltip" data-sc-product-id="169031">Acheter</button>

					Accueil

					Critiques

					Listes

				Casting

					Vidéos

					Photos

Série

					 de   Carlton Cuse

							Action,

							drame et

							policier

											6 saisons
																(arrêté)

					CBS

					1 h

<time datetime="1996-03-29" >29 mars 1996</time>

Nash Bridges est inspecteur au sein de la police de San Francisco. Décontracté, sauf s'il s'agit de sa voiture, il est tout dévoué à son travail, épaulé dans sa tâche par Joe Dominguez, son meilleur ami et excellent limier, Harvey, un ancien hippie reconverti en expert de l'informatique et Evan,...					<button type="button" class="d-link" data-rel="sc-btn-more-storyline" data-sc-product-id="169031">Lire la suite</button>

					<button type="button" class="d-link" data-rel="sc-btn-close-storyline" data-sc-product-id="169031">Fermer</button>

					PostsNash Bridges

				Vous avez une anecdote, une vidéo/photo ou une simple question sur cette série ?

				<button type="button" data-rel="js-link" data-sc-link="/post/169031" class="d-button-success-xl d-more pvi-emptyTopic-btn">
					Créer un post
				</button>
				<button type="button" data-rel="js-link" data-sc-link="/posts" class="d-button-xl d-more pvi-emptyTopic-btn">
					Tous les posts
				</button>

				Casting : acteurs principauxNash Bridges

					Tracey Walter
											Angel

					Don Johnson
											Nash Bridges

					Cheech Marin
											Joe Dominguez

					Jaime Gomez
											Evan Cortez

					Jodi Lyn O'Keefe
											Cassidy Bridges

			 Casting complet de la série Nash Bridges

Bande-annonce

				Nash Bridges

			<div class="" data-rel="external-video" data-sc-no-preroll="" data-sc-video-mode="player" data-sc-video-start="{:start_at}" data-sc-video-id="mUFOIPt9VH8" data-sc-param-index-id="274940204" data-sc-video-type="1" data-sc-video-width="700" data-sc-video-height="484" data-sc-video-poster="http://media.senscritique.com/media/000006504132/1200/Nash_Bridges.jpg" data-sc-video-autoplay="" data-sc-video-disablerebound="" data-sc-video-delay="{:delay}" data-sc-video-hidecontrols="" data-sc-video-mute="{:mute}">

				Sélection de listesNash Bridges

			Les séries dont le titre contient le nom du héros [ Liste...

Un de mes éclaireurs à crée une liste avec le nom des films qui ont pour titre le nom du héros, je reprend donc ce même thème et...

				 22

			Mais ça se passe où en fait?

Une liste pour situer où est censée se dérouler l'action des séries en question.
Certaines villes sont fictives, si c'est le...

				 8

			Caisses mythiques des séries TV

				Avec :
															Supernatural,
																				Starsky & Hutch,
																				Nash Bridges,
																				Las Vegas,
																				Shérif, fais-moi peur !

				 2

			Top Shawn Ryan

Cet homme est MAUDIT.

				 2

			Mes doublages préférés

				Avec :
															Loving,
																				Being Ian,
																				Dog House,
																				Magnum,
																				Arabesque

				 2

			 Toutes les listes

				InfosNash Bridges

										Scénaristes

								Carlton Cuse

								Reed Steiner

								John Wirth

								Jed Seidel

								Shawn Ryan

								Michael Norell

								Glen Mazzara

										Producteurs

								Greg Beeman

								Burt Bluestein

								Don Johnson

			Vous pourriez également aimer...

		5.7

					Magnum (1980)

		5.2

					Highlander (1992)

		5.1

					K2000 (1982)

		3.3

					Alerte à Malibu (1989)

		3.7

					Le Rebelle (1992)

		6.0

					L'agence tous risques (1983)

		4.8

					JAG (1995)

		6.1

					MacGyver (1985)

		4.2

					Sydney Fox, l'aventurière (1999)

		6.3

					Le Prince de Bel-Air (1990)

				Dernières actions sur cette série

			Nash Bridges

		 Plus d'actualité

				Le bouche à oreille

L'avis de vos amis en 1 clic

				S'inscrire avec FB

										Dans les Tops

					Présent dans 3 tops 10

				Lab

				Changelog

				À propos

				Aide

				Blog

				Publicité

				Emploi

				Conditions d'utilisation

Séances de cinéma

Programme TV ce soir

Programme TV aujourd'hui

Programme TV demain

Programme TV cette semaine

					Avis films

					Avis séries

					Avis livres

					Avis BD

					Avis jeux vidéo

					Avis musique

		© 2015 SensCritique


text:
""" Interface to the C++ Murtagh hierarchic clustering code

"""
from rdkit.ML.Cluster import Clusters
from rdkit.ML.Cluster.Clustering import MurtaghCluster,MurtaghDistCluster
import numpy

# constants to select the clustering algorithm
WARDS=1
SLINK=2
CLINK=3
UPGMA=4
MCQUITTY=5
GOWER=6
CENTROID=7

# descriptions of the methods:
methods = [
  ("Ward's Minimum Variance",WARDS,"Ward's Minimum Variance"),
  ('Average Linkage',UPGMA,'Group Average Linkage (UPGMA)'),
  ('Single Linkage',SLINK,'Single Linkage (SLINK)'),
  ('Complete Linkage',CLINK,'Complete Linkage (CLINK)'),
#  ("McQuitty",MCQUITTY,"McQuitty's method"),
#  ("Gower",GOWER,"Gower's median method"),
  ("Centroid",CENTROID,"Centroid method"),
  ]

def _LookupDist(dists,i,j,n):
  """ *Internal Use Only*

   returns the distance between points i and j in the symmetric
   distance matrix _dists_

  """
  if i==j: return 0.0
  if i > j: i,j=j,i
  return dists[j*(j-1)/2+i]

def _ToClusters(data,nPts,ia,ib,crit,isDistData=0):
  """ *Internal Use Only*

    Converts the results of the Murtagh clustering code into
    a cluster tree, which is returned in a single-entry list

  """
  cs = [None]*nPts
  for i in range(nPts):
    cs[i] = Clusters.Cluster(metric=0.0,data=i,index=(i+1))

  nClus = len(ia)-1
  for i in range(nClus):
    idx1 = ia[i]-1
    idx2 = ib[i]-1
    c1 = cs[idx1]
    c2 = cs[idx2]
    newClust = Clusters.Cluster(metric=crit[i],children=[c1,c2],
                                index=nPts+i+1)
    cs[idx1] = newClust

  return [newClust]

def ClusterData(data,nPts,method,isDistData=0):
  """  clusters the data points passed in and returns the cluster tree

    **Arguments**

      - data: a list of lists (or array, or whatever) with the input
        data (see discussion of _isDistData_ argument for the exception)

      - nPts: the number of points to be used

      - method: determines which clustering algorithm should be used.
          The defined constants for these are:
          'WARDS, SLINK, CLINK, UPGMA'

      - isDistData: set this toggle when the data passed in is a
          distance matrix.  The distance matrix should be stored
          symmetrically so that _LookupDist (above) can retrieve
          the results:
            for i<j: d_ij = dists[j*(j-1)/2 + i]

    **Returns**

      - a single entry list with the cluster tree
  """
  data = numpy.array(data)
  if not isDistData:
    sz = data.shape[1]
    ia,ib,crit = MurtaghCluster(data,nPts,sz,method)
  else:
    ia,ib,crit = MurtaghDistCluster(data,nPts,method)
  c = _ToClusters(data,nPts,ia,ib,crit,isDistData=isDistData)

  return c


text:
using namespace fsn;

DirectedComponent::DirectedComponent(Token type)
: Component(type) {}

DirectedComponent::~DirectedComponent() {

}


text:
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "llvm/Pass.h"
#include "llvm/IR/Function.h"

using namespace llvm;

namespace {

  class TestLLVMPass : public FunctionPass {

  public:

    static char ID;
    TestLLVMPass() : FunctionPass(ID) { }

    bool runOnFunction(Function &F) override;

    StringRef getPassName() const override {
      return "Some LLVM pass";
    }

  };

}

bool TestLLVMPass::runOnFunction(Function &F) {
  // A couple examples of operations that previously caused segmentation faults
  // https://github.com/rust-lang/rust/issues/31067

  for (auto N = F.begin(); N != F.end(); ++N) {
    /* code */
  }

  LLVMContext &C = F.getContext();
  IntegerType *Int8Ty  = IntegerType::getInt8Ty(C);
  PointerType::get(Int8Ty, 0);
  return true;
}

char TestLLVMPass::ID = 0;

static RegisterPass<TestLLVMPass> RegisterAFLPass(
  "some-llvm-function-pass", "Some LLVM pass");


text:
TEST(Plane, ConstructorAndProperties_test) {
  const re::vec3 dir(1.0, 0.0, 0.0);
  const reFloat offset = 10.0;

  const char* desc[3] = {
    "origin + direction",
    "origin + offset",
    "copy"
  };

  const re::Plane planes[3] = {
    Plane(dir * 100, re::vec3(offset, 50.0, -130.0)),
    Plane(dir * 30, offset),
    Plane(Plane(dir, offset))
  };

  for (int i = 0; i < 2; i++) {
    const re::Plane& plane = planes[i];

    ASSERT_FLOAT_EQ(re::length(plane.normal()), 1.0) <<
      "should have a unit vector as its normal @" << desc[i];

    ASSERT_FLOAT_EQ(re::length(plane.normal() - dir), 0.0) <<
      "should be facing the right direction @" << desc[i];

    ASSERT_FLOAT_EQ(plane.offset(), offset) <<
      "should have the correct offset @" << desc[i];

    ASSERT_TRUE(plane.type() == reShape::PLANE) <<
      "should have the correct type assigned @" << desc[i];

    ASSERT_EQ(plane.numVerts(), 0) <<
      "should have no reportable vertex @" << desc[i];

    ASSERT_FLOAT_EQ(plane.volume(), 0.0) <<
      "should have zero volume @" << desc[i];

    ASSERT_LE(re::length(plane.center() - dir * offset), RE_FP_TOLERANCE) <<
      "should report the center as being the closest point to the origin @" << desc[i];
  }
}

TEST(Plane, randomPoint_test) {
  for (unsigned int i = 0; i < NUM_REPEATS; i++) {
    const re::Plane plane(re::vec3::rand(), re::randf(100.0));
    for (unsigned int j = 0; j < NUM_REPEATS; j++) {
      ASSERT_LE(re::abs(re::dot(plane.normal(), plane.randomPoint()) - plane.offset()), RE_FP_TOLERANCE) <<
        "should generate random points on the plane";
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Interface org.apache.commons.lang.mutable.Mutable (Commons Lang 2.6 API)
</TITLE>

<META NAME="date" CONTENT="2011-01-13">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
org.apache.commons.lang.mutable.Mutable

Packages that use Mutable

org.apache.commons.lang.mutable
Provides typed mutable wrappers to primitive values and Object.

Uses of Mutable in org.apache.commons.lang.mutable

Classes in org.apache.commons.lang.mutable that implement Mutable

 class
MutableBoolean

          A mutable boolean wrapper.

 class
MutableByte

          A mutable byte wrapper.

 class
MutableDouble

          A mutable double wrapper.

 class
MutableFloat

          A mutable float wrapper.

 class
MutableInt

          A mutable int wrapper.

 class
MutableLong

          A mutable long wrapper.

 class
MutableObject

          A mutable Object wrapper.

 class
MutableShort

          A mutable short wrapper.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2001-2011 The Apache Software Foundation. All Rights Reserved.


text:
package com.amazonaws.services.ec2.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceResult;

/**
 *

 * Contains the output for CancelImportTask.
 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CancelImportTaskResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The ID of the task being canceled.
     *

     */
    private String importTaskId;
    /**
     *

     * The current state of the task being canceled.
     *

     */
    private String state;
    /**
     *

     * The current state of the task being canceled.
     *

     */
    private String previousState;

    /**
     *

     * The ID of the task being canceled.
     *

     *
     * @param importTaskId
     *        The ID of the task being canceled.
     */

    public void setImportTaskId(String importTaskId) {
        this.importTaskId = importTaskId;
    }

    /**
     *

     * The ID of the task being canceled.
     *

     *
     * @return The ID of the task being canceled.
     */

    public String getImportTaskId() {
        return this.importTaskId;
    }

    /**
     *

     * The ID of the task being canceled.
     *

     *
     * @param importTaskId
     *        The ID of the task being canceled.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CancelImportTaskResult withImportTaskId(String importTaskId) {
        setImportTaskId(importTaskId);
        return this;
    }

    /**
     *

     * The current state of the task being canceled.
     *

     *
     * @param state
     *        The current state of the task being canceled.
     */

    public void setState(String state) {
        this.state = state;
    }

    /**
     *

     * The current state of the task being canceled.
     *

     *
     * @return The current state of the task being canceled.
     */

    public String getState() {
        return this.state;
    }

    /**
     *

     * The current state of the task being canceled.
     *

     *
     * @param state
     *        The current state of the task being canceled.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CancelImportTaskResult withState(String state) {
        setState(state);
        return this;
    }

    /**
     *

     * The current state of the task being canceled.
     *

     *
     * @param previousState
     *        The current state of the task being canceled.
     */

    public void setPreviousState(String previousState) {
        this.previousState = previousState;
    }

    /**
     *

     * The current state of the task being canceled.
     *

     *
     * @return The current state of the task being canceled.
     */

    public String getPreviousState() {
        return this.previousState;
    }

    /**
     *

     * The current state of the task being canceled.
     *

     *
     * @param previousState
     *        The current state of the task being canceled.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CancelImportTaskResult withPreviousState(String previousState) {
        setPreviousState(previousState);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getImportTaskId() != null)
            sb.append("ImportTaskId: ").append(getImportTaskId()).append(",");
        if (getState() != null)
            sb.append("State: ").append(getState()).append(",");
        if (getPreviousState() != null)
            sb.append("PreviousState: ").append(getPreviousState());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof CancelImportTaskResult == false)
            return false;
        CancelImportTaskResult other = (CancelImportTaskResult) obj;
        if (other.getImportTaskId() == null ^ this.getImportTaskId() == null)
            return false;
        if (other.getImportTaskId() != null && other.getImportTaskId().equals(this.getImportTaskId()) == false)
            return false;
        if (other.getState() == null ^ this.getState() == null)
            return false;
        if (other.getState() != null && other.getState().equals(this.getState()) == false)
            return false;
        if (other.getPreviousState() == null ^ this.getPreviousState() == null)
            return false;
        if (other.getPreviousState() != null && other.getPreviousState().equals(this.getPreviousState()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getImportTaskId() == null) ? 0 : getImportTaskId().hashCode());
        hashCode = prime * hashCode + ((getState() == null) ? 0 : getState().hashCode());
        hashCode = prime * hashCode + ((getPreviousState() == null) ? 0 : getPreviousState().hashCode());
        return hashCode;
    }

    @Override
    public CancelImportTaskResult clone() {
        try {
            return (CancelImportTaskResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }
}


text:
//
//  CloudViewController.h
//  LionAndLamb
//
//  Created by Peter Jensen on 4/24/15.
//  Copyright (c) 2015 Peter Christian Jensen.
//
// 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 UIKit;

/**
 A key to the user's preferred (cloud) source

 @note This is the bible, the old or new testament, or a specific bible book
 */
extern NSString * const kLALuserSettingsSourceKey;
/**
 A key to the user's preferred (bible) version
 */
extern NSString * const kLALuserSettingsVersionKey;
/**
 A key to an LALSettingsFont enum of the user's preferred (cloud) font
 */
extern NSString * const kLALuserSettingsFontKey;
/**
 A key to an LALSettingsColor enum of the user's preferred (cloud) color
 */
extern NSString * const kLALuserSettingsColorKey;
/**
 A key to the user's preferred stopwords setting

 @note Stopwords never appear in the cloud, but can be toggled for the statistics
 */
extern NSString * const kLALuserSettingsStopwordsKey;
/**
 A key to a BOOL indicating whether the tap gesture hint should be shown
 */
extern NSString * const kLALshowHintCloudTapKey;
/**
 A key to a BOOL indicating whether the swipe gesture hint should be shown
 */
extern NSString * const kLALshowHintCloudSwipeKey;
/**
 A key to a BOOL indicating whether the cloud title animation should be shown
 */
extern NSString * const kLALshowAnimationCloudTitleKey;

@interface CloudViewController : UIViewController

@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;

- (IBAction)layoutCloudWordsAgain:(UITapGestureRecognizer *)sender;
- (IBAction)previousSource:(UISwipeGestureRecognizer *)sender;
- (IBAction)nextSource:(UISwipeGestureRecognizer *)sender;
- (IBAction)showActionSheet:(UIButton *)sender;

@end