text:
import json
from datetime import datetime, timedelta

from django.conf import settings
from django.contrib.sites.models import Site
from django.test.utils import override_settings

import mock
from nose.tools import eq_
from pyquery import PyQuery as pq

from kitsune.products.models import Product, Topic
from kitsune.products.tests import product
from kitsune.questions.models import (
    Question, QuestionVote, AnswerVote, Answer)
from kitsune.questions.tests import answer, question, TestCaseBase
from kitsune.questions.views import parse_troubleshooting
from kitsune.search.tests.test_es import ElasticTestCase
from kitsune.sumo.helpers import urlparams
from kitsune.sumo.tests import (
    get, MobileTestCase, LocalizingClient, eq_msg)
from kitsune.sumo.urlresolvers import reverse
from kitsune.products.tests import topic
from kitsune.users.tests import user, add_permission
from kitsune.wiki.tests import document, revision

class AAQTests(ElasticTestCase):
    client_class = LocalizingClient

    def test_bleaching(self):
        """Tests whether summaries are bleached"""
        q = question(
            title=u'cupcakes',
            content=u'<unbleached>Cupcakes are the best</unbleached',
            save=True)
        q.tags.add(u'desktop')
        q.save()
        self.refresh()

        url = urlparams(
            reverse('questions.aaq_step4', args=['desktop', 'd1']),
            search='cupcakes')

        response = self.client.get(url, follow=True)

        assert '<unbleached>' not in response.content

    # TODO: test whether when _search_suggetions fails with a handled
    # error that the user can still ask a question.

    def test_search_suggestions_questions(self):
        """Verifies the view doesn't kick up an HTTP 500"""
        p = product(slug=u'firefox', save=True)
        topic(title='Fix problems', slug='fix-problems', product=p, save=True)
        q = question(title=u'CupcakesQuestion cupcakes', save=True)
        q.products.add(p)

        d = document(title=u'CupcakesKB cupcakes', category=10, save=True)
        d.products.add(p)

        revision(document=d, is_approved=True, save=True)

        self.refresh()

        url = urlparams(
            reverse('questions.aaq_step4', args=['desktop', 'fix-problems']),
            search='cupcakes')

        response = self.client.get(url, follow=True)
        eq_(200, response.status_code)

        assert 'CupcakesQuestion' in response.content
        assert 'CupcakesKB' in response.content

        # Verify that archived articles and questions aren't shown...
        # Archive both and they shouldn't appear anymore.
        q.is_archived = True
        q.save()
        d.is_archived = True
        d.save()

        self.refresh()

        response = self.client.get(url, follow=True)
        eq_(200, response.status_code)

        assert 'CupcakesQuestion' not in response.content
        assert 'CupcakesKB' not in response.content

    @override_settings(AAQ_LANGUAGES=['en-US', 'pt-BR', 'de'])
    def test_search_suggestion_questions_locale(self):
        """Verifies the right languages show up in search suggestions."""
        p = product(slug=u'firefox', save=True)
        topic(title='Fix problems', slug='fix-problems', product=p, save=True)

        q1 = question(title='question cupcakes?', save=True, locale='en-US')
        q1.products.add(p)
        q2 = question(title='question donuts?', save=True, locale='en-US')
        q2.products.add(p)
        q3 = question(title='question pies?', save=True, locale='pt-BR')
        q3.products.add(p)
        q4 = question(title='question pastries?', save=True, locale='de')
        q4.products.add(p)

        self.refresh()

        def sub_test(locale, *titles):
            url = urlparams(reverse('questions.aaq_step4',
                                    args=['desktop', 'fix-problems'],
                                    locale=locale),
                            search='question')
            response = self.client.get(url, follow=True)
            doc = pq(response.content)
            eq_msg(len(doc('.result.question')), len(titles),
                   'Wrong number of results for {0}'.format(locale))
            for substr in titles:
                assert substr in doc('.result.question h3 a').text()

        sub_test('en-US', 'cupcakes?', 'donuts?')
        sub_test('pt-BR', 'cupcakes?', 'donuts?', 'pies?')
        sub_test('de', 'cupcakes?', 'donuts?', 'pastries?')

    def test_ratelimit(self):
        """Make sure posting new questions is ratelimited"""
        data = {'title': 'A test question',
                'content': 'I have this question that I hope...',
                'sites_affected': 'http://example.com',
                'ff_version': '3.6.6',
                'os': 'Intel Mac OS X 10.6',
                'plugins': '* Shockwave Flash 10.1 r53',
                'useragent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X '
                             '10.6; en-US; rv:1.9.2.6) Gecko/20100625 '
                             'Firefox/3.6.6'}
        p = product(slug='firefox', save=True)
        topic(slug='fix-problems', product=p, save=True)
        url = urlparams(
            reverse('questions.aaq_step5', args=['desktop', 'fix-problems']),
            search='A test question')

        u = user(save=True)
        self.client.login(username=u.username, password='testpass')

        for i in range(0, 5):
            self.client.post(url, data, follow=True)

        response = self.client.post(url, data, follow=True)
        eq_(403, response.status_code)

    def test_first_step(self):
        """Make sure the first step doesn't blow up

        Oddly, none of the other tests cover this simple case.
        """
        url = reverse('questions.aaq_step1')
        res = self.client.get(url)
        eq_(200, res.status_code)

    def test_redirect_bad_locales(self):
        """Non-AAQ locales should redirect."""
        url_fr = reverse('questions.aaq_step1', locale='fr')
        url_en = reverse('questions.aaq_step1', locale='en-US')
        res = self.client.get(url_fr)
        eq_(302, res.status_code)
        # This has some http://... stuff at the beginning. Ignore that.
        assert res['location'].endswith(url_en)

class MobileAAQTests(MobileTestCase):
    client_class = LocalizingClient
    data = {'title': 'A test question',
            'content': 'I have this question that I hope...',
            'sites_affected': 'http://example.com',
            'ff_version': '3.6.6',
            'os': 'Intel Mac OS X 10.6',
            'plugins': '* Shockwave Flash 10.1 r53',
            'useragent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X '
                         '10.6; en-US; rv:1.9.2.6) Gecko/20100625 '
                         'Firefox/3.6.6'}

    def _new_question(self, post_it=False):
        """Post a new question and return the response."""
        p = product(slug='mobile', save=True)
        t = topic(slug='fix-problems', product=p, save=True)
        url = urlparams(
            reverse('questions.aaq_step5', args=[p.slug, t.slug]),
            search='A test question')
        if post_it:
            return self.client.post(url, self.data, follow=True)
        return self.client.get(url, follow=True)

    def test_logged_out(self):
        """New question is posted through mobile."""
        response = self._new_question()
        eq_(200, response.status_code)
        self.assertTemplateUsed(response,
                                'questions/mobile/new_question_login.html')

    @mock.patch.object(Site.objects, 'get_current')
    def test_logged_in_get(self, get_current):
        """New question is posted through mobile."""
        get_current.return_value.domain = 'testserver'

        u = user(save=True)
        self.client.login(username=u.username, password='testpass')

        response = self._new_question()
        eq_(200, response.status_code)
        self.assertTemplateUsed(response,
                                'questions/mobile/new_question.html')

    @mock.patch.object(Site.objects, 'get_current')
    def test_logged_in_post(self, get_current):
        """New question is posted through mobile."""
        get_current.return_value.domain = 'testserver'

        u = user(save=True)
        self.client.login(username=u.username, password='testpass')

        response = self._new_question(post_it=True)
        eq_(200, response.status_code)
        assert Question.objects.filter(title='A test question')

    @mock.patch.object(Site.objects, 'get_current')
    def test_aaq_new_question_inactive(self, get_current):
        """New question is posted through mobile."""
        get_current.return_value.domain = 'testserver'

        # Log in first.
        u = user(save=True)
        self.client.login(username=u.username, password='testpass')

        # Then become inactive.
        u.is_active = False
        u.save()

        # Set 'in-aaq' for the session. It isn't already set because this
        # test doesn't do a GET of the form first.
        s = self.client.session
        s['in-aaq'] = True
        s.save()

        response = self._new_question(post_it=True)
        eq_(200, response.status_code)
        self.assertTemplateUsed(response,
                                'questions/mobile/confirm_email.html')

    def test_aaq_login_form(self):
        """The AAQ authentication forms contain the identifying fields.

        Added this test because it is hard to debug what happened when this
        fields somehow go missing.
        """
        res = self._new_question()
        doc = pq(res.content)
        eq_(1, len(doc('#login-form input[name=login]')))
        eq_(1, len(doc('#register-form input[name=register]')))

class TestQuestionUpdates(TestCaseBase):
    """Tests that questions are only updated in the right cases."""
    client_class = LocalizingClient

    date_format = '%Y%M%d%H%m%S'

    def setUp(self):
        super(TestQuestionUpdates, self).setUp()
        self.u = user(is_superuser=True, save=True)
        self.client.login(username=self.u.username, password='testpass')

        self.q = question(updated=datetime(2012, 7, 9, 9, 0, 0), save=True)
        self.a = answer(question=self.q, save=True)

        # Get the question from the database so we have a consistent level of
        # precision during the test.
        self.q = Question.objects.get(pk=self.q.id)

    def tearDown(self):
        self.client.logout()
        self.u.delete()
        self.q.delete()

    def _request_and_no_update(self, url, req_type='POST', data={}):
        updated = self.q.updated

        if req_type == 'POST':
            self.client.post(url, data, follow=True)
        elif req_type == 'GET':
            self.client.get(url, data, follow=True)
        else:
            raise ValueError('req_type must be either "GET" or "POST"')

        self.q = Question.objects.get(pk=self.q.id)
        eq_(updated.strftime(self.date_format),
            self.q.updated.strftime(self.date_format))

    def test_no_update_edit(self):
        url = urlparams(reverse('questions.edit_question', args=[self.q.id]))
        self._request_and_no_update(url, req_type='POST', data={
            'title': 'A new title.',
            'content': 'Some new content.'
        })

    def test_no_update_solve(self):
        url = urlparams(reverse('questions.solve',
                        args=[self.q.id, self.a.id]))
        self._request_and_no_update(url)

    def test_no_update_unsolve(self):
        url = urlparams(reverse('questions.unsolve',
                                args=[self.q.id, self.a.id]))
        self._request_and_no_update(url)

    def test_no_update_vote(self):
        url = urlparams(reverse('questions.vote', args=[self.q.id]))
        self._request_and_no_update(url, req_type='POST')

    def test_no_update_lock(self):
        url = urlparams(reverse('questions.lock', args=[self.q.id]))
        self._request_and_no_update(url, req_type='POST')
        # Now unlock
        self._request_and_no_update(url, req_type='POST')

    def test_no_update_tagging(self):
        url = urlparams(reverse('questions.add_tag', args=[self.q.id]))
        self._request_and_no_update(url, req_type='POST', data={
            'tag-name': 'foo'
        })

        url = urlparams(reverse('questions.remove_tag', args=[self.q.id]))
        self._request_and_no_update(url, req_type='POST', data={
            'remove-tag-foo': 1
        })

class TroubleshootingParsingTests(TestCaseBase):

    def test_empty_troubleshooting_info(self):
        """Test a troubleshooting value that is valid JSON, but junk.
        This should trigger the parser to return None, which should not
        cause a 500.
        """
        q = question(save=True)
        q.add_metadata(troubleshooting='{"foo": "bar"}')

        # This case should not raise an error.
        response = get(self.client, 'questions.details', args=[q.id])
        eq_(200, response.status_code)

    def test_weird_list_troubleshooting_info(self):
        """Test the corner case in which 'modifiedPReferences' is in a
        list in troubleshooting data. This is weird, but caused a bug."""
        q = question(save=True)
        q.add_metadata(troubleshooting='["modifiedPreferences"]')

        # This case should not raise an error.
        response = get(self.client, 'questions.details', args=[q.id])
        eq_(200, response.status_code)

    def test_string_keys_troubleshooting(self):
        """Test something that looks like troubleshooting data, but
        isn't formatted quite right. The parser should return None to
        indicate that something isn't right."""
        troubleshooting = '''{
            "accessibility": {
                "isActive": true
            },
            "application": {
                "name": "Firefox",
                "supportURL": "Some random url.",
                "userAgent": "A user agent.",
                "version": "42.2"
            },
            "extensions": [],
            "graphics": "This really should not be a string."
            "javaScript": {},
            "modifiedPreferences": {},
            "userJS": {
                "exists": False
            }
        }'''

        assert parse_troubleshooting(troubleshooting) is None

    def test_troubleshooting_parser(self):
        """Test that the troubleshooting parser likes good data."""
        troubleshooting = '''
            {
                "accessibility": {
                    "isActive": true
                },
                "application": {
                    "name": "Firefox",
                    "supportURL": "Some random url.",
                    "userAgent": "A user agent.",
                    "version": "42.2"
                },
                "extensions": [],
                "graphics": {},
                "javaScript": {},
                "modifiedPreferences": {},
                "userJS": {
                    "exists": false
                }
            }'''

        assert parse_troubleshooting(troubleshooting) is not None

class TestQuestionList(TestCaseBase):

    @override_settings(AAQ_LANGUAGES=['en-US', 'pt-BR'])
    def test_locale_filter(self):
        """Only questions for the current locale should be shown on the
        questions front page for AAQ locales."""

        eq_(Question.objects.count(), 0)
        p = product(slug=u'firefox', save=True)
        topic(title='Fix problems', slug='fix-problems', product=p, save=True)

        q1 = question(title='question cupcakes?', save=True, locale='en-US')
        q1.products.add(p)
        q2 = question(title='question donuts?', save=True, locale='en-US')
        q2.products.add(p)
        q3 = question(title='question pies?', save=True, locale='pt-BR')
        q3.products.add(p)
        q4 = question(title='question pastries?', save=True, locale='de')
        q4.products.add(p)

        def sub_test(locale, *titles):
            url = urlparams(reverse(
                'questions.list', args=['all'], locale=locale))
            response = self.client.get(url, follow=True)
            doc = pq(response.content)
            eq_msg(len(doc('section[id^=question]')), len(titles),
                   'Wrong number of results for {0}'.format(locale))
            for substr in titles:
                assert substr in doc('.questions section .content h2 a').text()

        # en-US and pt-BR are both in AAQ_LANGUAGES, so should be filtered.
        sub_test('en-US', 'cupcakes?', 'donuts?')
        sub_test('pt-BR', 'pies?')
        # de is not in AAQ_LANGUAGES, so should show en-US, but not pt-BR
        sub_test('de', 'cupcakes?', 'donuts?', 'pastries?')

class TestQuestionReply(TestCaseBase):
    def setUp(self):
        u = user(save=True)
        self.client.login(username=u.username, password='testpass')
        self.question = question(save=True)

    def test_needs_info(self):
        eq_(self.question.needs_info, False)

        res = self.client.post(
            reverse('questions.reply', args=[self.question.id]),
            {'content': 'More info please', 'needsinfo': ''})
        eq_(res.status_code, 302)

        q = Question.objects.get(id=self.question.id)
        eq_(q.needs_info, True)

    def test_clear_needs_info(self):
        self.question.set_needs_info()
        eq_(self.question.needs_info, True)

        res = self.client.post(
            reverse('questions.reply', args=[self.question.id]),
            {'content': 'More info please', 'clear_needsinfo': ''})
        eq_(res.status_code, 302)

        q = Question.objects.get(id=self.question.id)
        eq_(q.needs_info, False)

class TestRateLimiting(TestCaseBase):
    client_class = LocalizingClient

    def _check_question_vote(self, q, ignored):
        """Try and vote on `q`. If `ignored` is false, assert the
        request worked. If `ignored` is True, assert the request didn't
        do anything."""
        url = reverse('questions.vote', args=[q.id], locale='en-US')
        votes = QuestionVote.objects.filter(question=q).count()

        res = self.client.post(url, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        eq_(res.status_code, 200)

        data = json.loads(res.content)
        eq_(data.get('ignored', False), ignored)

        if ignored:
            eq_(QuestionVote.objects.filter(question=q).count(), votes)
        else:
            eq_(QuestionVote.objects.filter(question=q).count(), votes + 1)

    def _check_answer_vote(self, q, a, ignored):
        """Try and vote on `a`. If `ignored` is false, assert the
        request worked. If `ignored` is True, assert the request didn't
        do anything."""
        url = reverse('questions.answer_vote', args=[q.id, a.id],
                      locale='en-US')
        votes = AnswerVote.objects.filter(answer=a).count()

        res = self.client.post(url, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        eq_(res.status_code, 200)

        data = json.loads(res.content)
        eq_(data.get('ignored', False), ignored)

        if ignored:
            eq_(AnswerVote.objects.filter(answer=a).count(), votes)
        else:
            eq_(AnswerVote.objects.filter(answer=a).count(), votes + 1)

    def test_question_vote_limit(self):
        """Test that an anonymous user's votes are ignored after 10
        question votes."""
        questions = [question(save=True) for _ in range(11)]

        # The rate limit is 10 per day. So make 10 requests. (0 through 9)
        for i in range(10):
            self._check_question_vote(questions[i], False)

        # Now make another, it should fail.
        self._check_question_vote(questions[10], True)

    def test_answer_vote_limit(self):
        """Test that an anonymous user's votes are ignored after 10
        answer votes."""
        q = question(save=True)
        answers = [answer(question=q, save=True) for _ in range(11)]

        # The rate limit is 10 per day. So make 10 requests. (0 through 9)
        for i in range(10):
            self._check_answer_vote(q, answers[i], False)

        # Now make another, it should fail.
        self._check_answer_vote(q, answers[10], True)

    def test_question_vote_logged_in(self):
        """This exhausts the rate limit, then logs in, and exhausts it
        again."""
        questions = [question(save=True) for _ in range(11)]
        u = user(password='testpass', save=True)

        # The rate limit is 10 per day. So make 10 requests. (0 through 9)
        for i in range(10):
            self._check_question_vote(questions[i], False)
        # The rate limit has been hit, so this fails.
        self._check_question_vote(questions[10], True)

        # Login.
        self.client.login(username=u.username, password='testpass')
        for i in range(10):
            self._check_question_vote(questions[i], False)

        # Now the user has hit the rate limit too, so this should fail.
        self._check_question_vote(questions[10], True)

        # Logging out out won't help
        self.client.logout()
        self._check_question_vote(questions[10], True)

    def test_answer_vote_logged_in(self):
        """This exhausts the rate limit, then logs in, and exhausts it
        again."""
        q = question(save=True)
        answers = [answer(question=q, save=True) for _ in range(12)]
        u = user(password='testpass', save=True)

        # The rate limit is 10 per day. So make 10 requests. (0 through 9)
        for i in range(10):
            self._check_answer_vote(q, answers[i], False)
        # The ratelimit has been hit, so the next request will fail.
        self._check_answer_vote(q, answers[11], True)

        # Login.
        self.client.login(username=u.username, password='testpass')
        for i in range(10):
            self._check_answer_vote(q, answers[i], False)

        # Now the user has hit the rate limit too, so this should fail.
        self._check_answer_vote(q, answers[10], True)

        # Logging out out won't help
        self.client.logout()
        self._check_answer_vote(q, answers[11], True)

    def test_answers_limit(self):
        """Only four answers per minute can be posted."""
        # Login
        u = user(password='testpass', save=True)
        self.client.login(username=u.username, password='testpass')

        q = question(save=True)
        content = 'lorem ipsum dolor sit amet'
        url = reverse('questions.reply', args=[q.id])
        for i in range(7):
            self.client.post(url, {'content': content})

        eq_(4, Answer.uncached.count())

class TestStats(ElasticTestCase):
    client_class = LocalizingClient

    def test_stats(self):
        """Tests questions/dashboard/metrics view"""
        p = product(save=True)
        t = topic(title='Websites', slug='websites', product=p, save=True)

        q = question(
            title=u'cupcakes',
            content=u'Cupcakes rock!',
            created=datetime.now() - timedelta(days=1),
            save=True)
        q.topics.add(t)
        q.save()

        self.refresh()

        response = self.client.get(reverse('questions.metrics'))
        eq_(200, response.status_code)

        # If there's histogram data, this is probably good enough to
        # denote its existence.
        assert ' data-graph="[' in response.content

class TestEditDetails(TestCaseBase):
    def setUp(self):
        u = user(save=True)
        add_permission(u, Question, 'change_question')
        self.user = u

        p = product(save=True)
        t = topic(product=p, save=True)

        q = question(save=True)
        q.products.add(p)
        q.topics.add(t)
        q.save()

        self.product = p
        self.topic = t
        self.question = q

    def _request(self, user=None, data=None):
        """Make a request to edit details"""
        if user is None:
            user = self.user
        self.client.login(username=user.username, password='testpass')
        url = reverse('questions.edit_details',
                      kwargs={'question_id': self.question.id})
        return self.client.post(url, data=data)

    def test_permissions(self):
        """Test that the new permission works"""
        data = {
            'product': self.product.id,
            'topic': self.topic.id,
            'locale': self.question.locale
        }

        u = user(save=True)
        response = self._request(u, data=data)
        eq_(403, response.status_code)

        response = self._request(data=data)
        eq_(302, response.status_code)

    def test_missing_data(self):
        """Test for missing data"""
        data = {
            'product': self.product.id,
            'locale': self.question.locale
        }
        response = self._request(data=data)
        eq_(400, response.status_code)

        data = {
            'topic': self.topic.id,
            'locale': self.question.locale
        }
        response = self._request(data=data)
        eq_(400, response.status_code)

        data = {
            'product': self.product.id,
            'topic': self.topic.id
        }
        response = self._request(data=data)
        eq_(400, response.status_code)

    def test_bad_data(self):
        """Test for bad data"""
        data = {
            'product': product(save=True).id,
            'topic': topic(save=True).id,
            'locale': self.question.locale
        }
        response = self._request(data=data)
        eq_(400, response.status_code)

        data = {
            'product': self.product.id,
            'topic': self.topic.id,
            'locale': 'zu'
        }
        response = self._request(data=data)
        eq_(400, response.status_code)

    def test_change_topic(self):
        """Test changing the topic"""
        t_new = topic(product=self.product, save=True)

        data = {
            'product': self.product.id,
            'topic': t_new.id,
            'locale': self.question.locale
        }

        assert t_new.id != self.topic.id

        response = self._request(data=data)
        eq_(302, response.status_code)

        q = Question.objects.get(id=self.question.id)

        eq_(1, len(q.topics.all()))
        eq_(t_new.id, q.topics.all()[0].id)

    def test_change_product(self):
        """Test changing the product"""
        t_new = topic(save=True)
        p_new = t_new.product

        assert self.topic.id != t_new.id
        assert self.product.id != p_new.id

        data = {
            'product': p_new.id,
            'topic': t_new.id,
            'locale': self.question.locale
        }

        response = self._request(data=data)
        eq_(302, response.status_code)

        p = Product.uncached.get(question=self.question)
        t = Topic.uncached.get(question=self.question)

        eq_(p_new.id, p.id)
        eq_(t_new.id, t.id)

    def test_change_locale(self):
        locale = 'hu'

        assert locale in settings.AAQ_LANGUAGES
        assert locale != self.question.locale

        data = {
            'product': self.product.id,
            'topic': self.topic.id,
            'locale': locale
        }

        response = self._request(data=data)
        eq_(302, response.status_code)

        q = Question.objects.get(id=self.question.id)
        eq_(q.locale, locale)


text:
.mdl-radio {
  position: relative;
  font-size: 16px;
  line-height: 24px;
  display: inline-block;
  box-sizing: border-box;
  margin: 0;
  padding-left: 0; }
.mdl-radio.is-upgraded {
  padding-left: 24px; }

.mdl-radio__button {
  line-height: 24px; }
.mdl-radio.is-upgraded .mdl-radio__button {
  position: absolute;
  width: 0;
  height: 0;
  margin: 0;
  padding: 0;
  opacity: 0;
  -ms-appearance: none;
  -moz-appearance: none;
  -webkit-appearance: none;
  appearance: none;
  border: none; }

.mdl-radio__outer-circle {
  position: absolute;
  top: 4px;
  left: 0;
  display: inline-block;
  box-sizing: border-box;
  width: 16px;
  height: 16px;
  margin: 0;
  cursor: pointer;
  border: 2px solid rgba(0,0,0, 0.54);
  border-radius: 50%;
  z-index: 2; }
.mdl-radio.is-checked .mdl-radio__outer-circle {
  border: 2px solid rgb(63,81,181); }
.mdl-radio__outer-circle fieldset[disabled] .mdl-radio,
.mdl-radio.is-disabled .mdl-radio__outer-circle {
  border: 2px solid rgba(0,0,0, 0.26);
  cursor: auto; }

.mdl-radio__inner-circle {
  position: absolute;
  z-index: 1;
  margin: 0;
  top: 8px;
  left: 4px;
  box-sizing: border-box;
  width: 8px;
  height: 8px;
  cursor: pointer;
  transition-duration: 0.28s;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-property: -webkit-transform;
  transition-property: transform;
  transition-property: transform, -webkit-transform;
  -webkit-transform: scale3d(0, 0, 0);
  transform: scale3d(0, 0, 0);
  border-radius: 50%;
  background: rgb(63,81,181); }
.mdl-radio.is-checked .mdl-radio__inner-circle {
  -webkit-transform: scale3d(1, 1, 1);
  transform: scale3d(1, 1, 1); }
fieldset[disabled] .mdl-radio .mdl-radio__inner-circle,
.mdl-radio.is-disabled .mdl-radio__inner-circle {
  background: rgba(0,0,0, 0.26);
  cursor: auto; }
.mdl-radio.is-focused .mdl-radio__inner-circle {
  box-shadow: 0 0 0 10px rgba(0, 0, 0, 0.1); }

.mdl-radio__label {
  cursor: pointer; }
fieldset[disabled] .mdl-radio .mdl-radio__label,
.mdl-radio.is-disabled .mdl-radio__label {
  color: rgba(0,0,0, 0.26);
  cursor: auto; }

.mdl-radio__ripple-container {
  position: absolute;
  z-index: 2;
  top: -9px;
  left: -13px;
  box-sizing: border-box;
  width: 42px;
  height: 42px;
  border-radius: 50%;
  cursor: pointer;
  overflow: hidden;
  -webkit-mask-image: -webkit-radial-gradient(circle, white, black); }
.mdl-radio__ripple-container .mdl-ripple {
  background: rgb(63,81,181); }
fieldset[disabled] .mdl-radio .mdl-radio__ripple-container,
.mdl-radio.is-disabled .mdl-radio__ripple-container {
  cursor: auto; }
fieldset[disabled] .mdl-radio .mdl-radio__ripple-container .mdl-ripple,
.mdl-radio.is-disabled .mdl-radio__ripple-container .mdl-ripple {
  background: transparent; }

redpajama_set_name: RedPajamaGithub


text:
require 'hanami/utils/class_attribute'
require 'hanami/http/status'
require 'hanami/action/rack/errors'

module Hanami
  module Action
    # Throw API
    #
    # @since 0.1.0
    #
    # @see Hanami::Action::Throwable::ClassMethods#handle_exception
    # @see Hanami::Action::Throwable#halt
    # @see Hanami::Action::Throwable#status
    module Throwable
      # @since 0.1.0
      # @api private
      def self.included(base)
        base.extend ClassMethods
      end

      # Throw API class methods
      #
      # @since 0.1.0
      # @api private
      module ClassMethods
        private

        # Handle the given exception with an HTTP status code.
        #
        # When the exception is raise during #call execution, it will be
        # translated into the associated HTTP status.
        #
        # This is a fine grained control, for a global configuration see
        # Hanami::Action.handled_exceptions
        #
        # @param exception [Hash] the exception class must be the key and the
        #   HTTP status the value of the hash
        #
        # @since 0.1.0
        #
        # @see Hanami::Action.handled_exceptions
        #
        # @example
        #   require 'hanami/controller'
        #
        #   class Show
        #     include Hanami::Action
        #     handle_exception RecordNotFound => 404
        #
        #     def call(params)
        #       # ...
        #       raise RecordNotFound.new
        #     end
        #   end
        #
        #   Show.new.call({id: 1}) # => [404, {}, ['Not Found']]
        def handle_exception(exception)
          configuration.handle_exception(exception)
        end
      end

      protected

      # Halt the action execution with the given HTTP status code and message.
      #
      # When used, the execution of a callback or of an action is interrupted
      # and the control returns to the framework, that decides how to handle
      # the event.
      #
      # If a message is provided, it sets the response body with the message.
      # Otherwise, it sets the response body with the default message associated
      # to the code (eg 404 will set `"Not Found"`).
      #
      # @param code [Integer] a valid HTTP status code
      # @param message [String] the response body
      #
      # @since 0.2.0
      #
      # @see Hanami::Controller#handled_exceptions
      # @see Hanami::Action::Throwable#handle_exception
      # @see Hanami::Http::Status:ALL
      #
      # @example Basic usage
      #   require 'hanami/controller'
      #
      #   class Show
      #     def call(params)
      #       halt 404
      #     end
      #   end
      #
      #   # => [404, {}, ["Not Found"]]
      #
      # @example Custom message
      #   require 'hanami/controller'
      #
      #   class Show
      #     def call(params)
      #       halt 404, "This is not the droid you're looking for."
      #     end
      #   end
      #
      #   # => [404, {}, ["This is not the droid you're looking for."]]
      def halt(code, message = nil)
        message ||= Http::Status.message_for(code)
        status(code, message)

        throw :halt
      end

      # Sets the given code and message for the response
      #
      # @param code [Integer] a valid HTTP status code
      # @param message [String] the response body
      #
      # @since 0.1.0
      # @see Hanami::Http::Status:ALL
      def status(code, message)
        self.status = code
        self.body   = message
      end

      private
      # @since 0.1.0
      # @api private
      def _rescue
        catch :halt do
          begin
            yield
          rescue => exception
            _reference_in_rack_errors(exception)
            _handle_exception(exception)
          end
        end
      end

      # @since 0.2.0
      # @api private
      def _reference_in_rack_errors(exception)
        return if configuration.handled_exception?(exception)

        Hanami::Action::Rack::Errors.set(@_env, exception)
      end

      # @since 0.1.0
      # @api private
      def _handle_exception(exception)
        raise unless configuration.handle_exceptions

        instance_exec(
          exception,
          &_exception_handler(exception)
        )
      end

      # @since 0.3.0
      # @api private
      def _exception_handler(exception)
        handler = configuration.exception_handler(exception)

        if respond_to?(handler.to_s, true)
          method(handler)
        else
          ->(ex) { halt handler }
        end
      end
    end
  end
end


text:
/**
 * @class Ext.util.MixedCollection
 *

 * Represents a collection of a set of key and value pairs. Each key in the MixedCollection
 * must be unique, the same key cannot exist twice. This collection is ordered, items in the
 * collection can be accessed by index  or via the key. Newly added items are added to
 * the end of the collection. This class is similar to {@link Ext.util.HashMap} however it
 * is heavier and provides more functionality. Sample usage:
 *

var coll = new Ext.util.MixedCollection();
coll.add('key1', 'val1');
coll.add('key2', 'val2');
coll.add('key3', 'val3');

console.log(coll.get('key1')); // prints 'val1'
console.log(coll.indexOfKey('key3')); // prints 2
 *

 *
 *

 * The MixedCollection also has support for sorting and filtering of the values in the collection.
 *

var coll = new Ext.util.MixedCollection();
coll.add('key1', 100);
coll.add('key2', -100);
coll.add('key3', 17);
coll.add('key4', 0);
var biggerThanZero = coll.filterBy(function(value){
    return value > 0;
});
console.log(biggerThanZero.getCount()); // prints 2
 *

 *

 */
Ext.define('Ext.util.MixedCollection', {
    extend: 'Ext.util.AbstractMixedCollection',
    mixins: {
        sortable: 'Ext.util.Sortable'
    },

    /**
     * Creates new MixedCollection.
     * @param {Boolean} allowFunctions Specify <tt>true</tt> if the {@link #addAll}
     * function should add function references to the collection. Defaults to
     * <tt>false</tt>.
     * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
     * and return the key value for that item.  This is used when available to look up the key on items that
     * were passed without an explicit key parameter to a MixedCollection method.  Passing this parameter is
     * equivalent to providing an implementation for the {@link #getKey} method.
     */
    constructor: function() {
        var me = this;
        me.callParent(arguments);
        me.addEvents('sort');
        me.mixins.sortable.initSortable.call(me);
    },

    doSort: function(sorterFn) {
        this.sortBy(sorterFn);
    },

    /**
     * @private
     * Performs the actual sorting based on a direction and a sorting function. Internally,
     * this creates a temporary array of all items in the MixedCollection, sorts it and then writes
     * the sorted array data back into this.items and this.keys
     * @param {String} property Property to sort by ('key', 'value', or 'index')
     * @param {String} dir (optional) Direction to sort 'ASC' or 'DESC'. Defaults to 'ASC'.
     * @param {Function} fn (optional) Comparison function that defines the sort order.
     * Defaults to sorting by numeric value.
     */
    _sort : function(property, dir, fn){
        var me = this,
            i, len,
            dsc   = String(dir).toUpperCase() == 'DESC' ? -1 : 1,

            //this is a temporary array used to apply the sorting function
            c     = [],
            keys  = me.keys,
            items = me.items;

        //default to a simple sorter function if one is not provided
        fn = fn || function(a, b) {
            return a - b;
        };

        //copy all the items into a temporary array, which we will sort
        for(i = 0, len = items.length; i < len; i++){
            c[c.length] = {
                key  : keys[i],
                value: items[i],
                index: i
            };
        }

        //sort the temporary array
        Ext.Array.sort(c, function(a, b){
            var v = fn(a[property], b[property]) * dsc;
            if(v === 0){
                v = (a.index < b.index ? -1 : 1);
            }
            return v;
        });

        //copy the temporary array back into the main this.items and this.keys objects
        for(i = 0, len = c.length; i < len; i++){
            items[i] = c[i].value;
            keys[i]  = c[i].key;
        }

        me.fireEvent('sort', me);
    },

    /**
     * Sorts the collection by a single sorter function
     * @param {Function} sorterFn The function to sort by
     */
    sortBy: function(sorterFn) {
        var me     = this,
            items  = me.items,
            keys   = me.keys,
            length = items.length,
            temp   = [],
            i;

        //first we create a copy of the items array so that we can sort it
        for (i = 0; i < length; i++) {
            temp[i] = {
                key  : keys[i],
                value: items[i],
                index: i
            };
        }

        Ext.Array.sort(temp, function(a, b) {
            var v = sorterFn(a.value, b.value);
            if (v === 0) {
                v = (a.index < b.index ? -1 : 1);
            }

            return v;
        });

        //copy the temporary array back into the main this.items and this.keys objects
        for (i = 0; i < length; i++) {
            items[i] = temp[i].value;
            keys[i]  = temp[i].key;
        }

        me.fireEvent('sort', me, items, keys);
    },

    /**
     * Reorders each of the items based on a mapping from old index to new index. Internally this
     * just translates into a sort. The 'sort' event is fired whenever reordering has occured.
     * @param {Object} mapping Mapping from old item index to new item index
     */
    reorder: function(mapping) {
        var me = this,
            items = me.items,
            index = 0,
            length = items.length,
            order = [],
            remaining = [],
            oldIndex;

        me.suspendEvents();

        //object of {oldPosition: newPosition} reversed to {newPosition: oldPosition}
        for (oldIndex in mapping) {
            order[mapping[oldIndex]] = items[oldIndex];
        }

        for (index = 0; index < length; index++) {
            if (mapping[index] == undefined) {
                remaining.push(items[index]);
            }
        }

        for (index = 0; index < length; index++) {
            if (order[index] == undefined) {
                order[index] = remaining.shift();
            }
        }

        me.clear();
        me.addAll(order);

        me.resumeEvents();
        me.fireEvent('sort', me);
    },

    /**
     * Sorts this collection by keys.
     * @param {String} direction (optional) 'ASC' or 'DESC'. Defaults to 'ASC'.
     * @param {Function} fn (optional) Comparison function that defines the sort order.
     * Defaults to sorting by case insensitive string.
     */
    sortByKey : function(dir, fn){
        this._sort('key', dir, fn || function(a, b){
            var v1 = String(a).toUpperCase(), v2 = String(b).toUpperCase();
            return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
        });
    }
});


text:
#include "fileio.h"
#include <stdio.h>

/** Read a `char` matrix from a binary file.
 *
 * \param filename Filename.
 * \param m Number of rows.
 * \param n Number of columns.
 * \param A Matrix pointer.
 * \param ldA Leading dimension.
 * \param info Error status, 0 on success.
 */
void readfile(const char *filename, const int *m, const int *n, char *A, const int *ldA, int *info) {
    *info = 0;
    FILE *fin = fopen(filename, "rb");
    if (!fin) {
        *info = -1;
        return;
    }
    int j;
    for (j = 0; j < *n; j++)
        if (fread(A + *m + *n * *ldA, sizeof(char), (size_t) *m, fin) != (size_t) *m) {
            *info = j;
            return;
        }
}

/** Read an integer matrix from a binary file.
 *
 * \param filename Filename.
 * \param m Number of rows.
 * \param n Number of columns.
 * \param A Matrix pointer.
 * \param ldA Leading dimension.
 * \param info Error status, 0 on success.
 */
void ireadfile(const char *filename, const int *m, const int *n, int *A, const int *ldA, int *info) {
    int cm = *m * (int) (sizeof(int) / sizeof(char));
    int cldA = *ldA * (int) (sizeof(int) / sizeof(char));
    readfile(filename, &cm, n, (char *) A, &cldA, info);
}

/** Read a single precision matrix from a binary file.
 *
 * \param filename Filename.
 * \param m Number of rows.
 * \param n Number of columns.
 * \param A Matrix pointer.
 * \param ldA Leading dimension.
 * \param info Error status, 0 on success.
 */
void sreadfile(const char *filename, const int *m, const int *n, float *A, const int *ldA, int *info) {
    int cm = *m * (int) (sizeof(float) / sizeof(char));
    int cldA = *ldA * (int) (sizeof(float) / sizeof(char));
    readfile(filename, &cm, n, (char *) A, &cldA, info);
}

/** Read a double precision matrix from a binary file.
 *
 * \param filename Filename.
 * \param m Number of rows.
 * \param n Number of columns.
 * \param A Matrix pointer.
 * \param ldA Leading dimension.
 * \param info Error status, 0 on success.
 */
void dreadfile(const char *filename, const int *m, const int *n, double *A, const int *ldA, int *info) {
    int cm = *m * (int) (sizeof(double) / sizeof(char));
    int cldA = *ldA * (int) (sizeof(double) / sizeof(char));
    readfile(filename, &cm, n, (char *) A, &cldA, info);
}

/** Read a single precision complex matrix from a binary file.
 *
 * \param filename Filename.
 * \param m Number of rows.
 * \param n Number of columns.
 * \param A Matrix pointer.
 * \param ldA Leading dimension.
 * \param info Error status, 0 on success.
 */
void creadfile(const char *filename, const int *m, const int *n, float *A, const int *ldA, int *info) {
    int cm = *m * (int) (2 * sizeof(float) / sizeof(char));
    int cldA = *ldA * (int) (2 * sizeof(float) / sizeof(char));
    readfile(filename, &cm, n, (char *) A, &cldA, info);
}

/** Read a double precision complex matrix from a binary file.
 *
 * \param filename Filename.
 * \param m Number of rows.
 * \param n Number of columns.
 * \param A Matrix pointer.
 * \param ldA Leading dimension.
 * \param info Error status, 0 on success.
 */
void zreadfile(const char *filename, const int *m, const int *n, double *A, const int *ldA, int *info) {
    int cm = *m * (int) (2 * sizeof(double) / sizeof(char));
    int cldA = *ldA * (int) (2 * sizeof(double) / sizeof(char));
    readfile(filename, &cm, n, (char *) A, &cldA, info);
}

/** Write a `char` matrix to a binary file.
 *
 * \param filename Filename.
 * \param m Number of rows.
 * \param n Number of columns.
 * \param A Matrix pointer.
 * \param ldA Leading dimension.
 * \param info Error status, 0 on success.
 */
void writefile(const char *filename, const int *m, const int *n, const char *A, const int *ldA, int *info) {
    *info = 0;
    FILE *fin = fopen(filename, "wb");
    if (!fin) {
        *info = -1;
        return;
    }
    int j;
    for (j = 0; j < *n; j++)
        if (fwrite(A + *m + *n * *ldA, sizeof(char), (size_t) *m, fin) != (size_t) *m) {
            *info = j;
            return;
        }
}

/** Write an integer matrix to a binary file.
 *
 * \param filename Filename.
 * \param m Number of rows.
 * \param n Number of columns.
 * \param A Matrix pointer.
 * \param ldA Leading dimension.
 * \param info Error status, 0 on success.
 */
void iwritefile(const char *filename, const int *m, const int *n, const int *A, const int *ldA, int *info) {
    int cm = *m * (int) (sizeof(int) / sizeof(char));
    int cldA = *ldA * (int) (sizeof(int) / sizeof(char));
    writefile(filename, &cm, n, (const char *) A, &cldA, info);
}

/** Write a single precision matrix to a binary file.
 *
 * \param filename Filename.
 * \param m Number of rows.
 * \param n Number of columns.
 * \param A Matrix pointer.
 * \param ldA Leading dimension.
 * \param info Error status, 0 on success.
 */
void swritefile(const char *filename, const int *m, const int *n, const float *A, const int *ldA, int *info) {
    int cm = *m * (int) (sizeof(float) / sizeof(char));
    int cldA = *ldA * (int) (sizeof(float) / sizeof(char));
    writefile(filename, &cm, n, (const char *) A, &cldA, info);
}

/** Write a double precision matrix to a binary file.
 *
 * \param filename Filename.
 * \param m Number of rows.
 * \param n Number of columns.
 * \param A Matrix pointer.
 * \param ldA Leading dimension.
 * \param info Error status, 0 on success.
 */
void dwritefile(const char *filename, const int *m, const int *n, const double *A, const int *ldA, int *info) {
    int cm = *m * (int) (sizeof(double) / sizeof(char));
    int cldA = *ldA * (int) (sizeof(double) / sizeof(char));
    writefile(filename, &cm, n, (const char *) A, &cldA, info);
}

/** Write a single precision complex matrix to a binary file.
 *
 * \param filename Filename.
 * \param m Number of rows.
 * \param n Number of columns.
 * \param A Matrix pointer.
 * \param ldA Leading dimension.
 * \param info Error status, 0 on success.
 */
void cwritefile(const char *filename, const int *m, const int *n, const float *A, const int *ldA, int *info) {
    int cm = *m * (int) (2 * sizeof(float) / sizeof(char));
    int cldA = *ldA * (int) (2 * sizeof(float) / sizeof(char));
    writefile(filename, &cm, n, (const char *) A, &cldA, info);
}

/** Write a double precision complex matrix to a binary file.
 *
 * \param filename Filename.
 * \param m Number of rows.
 * \param n Number of columns.
 * \param A Matrix pointer.
 * \param ldA Leading dimension.
 * \param info Error status, 0 on success.
 */
void zwritefile(const char *filename, const int *m, const int *n, const double *A, const int *ldA, int *info) {
    int cm = *m * (int) (2 * sizeof(double) / sizeof(char));
    int cldA = *ldA * (int) (2 * sizeof(double) / sizeof(char));
    writefile(filename, &cm, n, (const char *) A, &cldA, info);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.WebSockets.Server;

namespace SessionLib
{
    public sealed class Sessions
    {
        RequestDelegate next;
        public Sessions(RequestDelegate next)
        {
            this.next = next;
        }

        public Task Invoke(HttpContext context, IServerSession session)
        {
            if (session == null)
                return this.next(context);

            return session.WaitAsync();
        }
    }
}


text:
import { __decorate } from "tslib";
import { customElement, bindable, observable, useView } from 'aurelia-framework';
import { DOM, PLATFORM } from 'aurelia-pal';
import { bindingMode } from 'aurelia-binding';
import { inject } from 'aurelia-dependency-injection';
import { StyleEngine } from '@aurelia-ux/core';
let UxChip = /** @class */ (() => {
    let UxChip = class UxChip {
        constructor(element, styleEngine) {
            this.element = element;
            this.styleEngine = styleEngine;
            this.variant = 'filled';
            this.selectedIcon = 'check';
            this.focused = false;
            this.selected = undefined;
        }
        bind() {
            this.themeChanged(this.theme);
            if (this.element.hasAttribute('deletable')) {
                this.element.removeAttribute('deletable');
                this.element.classList.add('ux-chip--deletable');
            }
        }
        attached() {
            this.isFocused = () => {
                this.focused = document.activeElement === this.element;
            };
            window.addEventListener('focus', this.isFocused, true);
            window.addEventListener('blur', this.isFocused, true);
        }
        detached() {
            window.removeEventListener('focus', this.isFocused, true);
            window.removeEventListener('blur', this.isFocused, true);
        }
        themeChanged(newValue) {
            if (newValue != null && newValue.themeKey == null) {
                newValue.themeKey = 'chip';
            }
            this.styleEngine.applyTheme(newValue, this.element);
        }
        closeChip(event) {
            if (event) {
                event.stopPropagation();
            }
            const closeEvent = DOM.createCustomEvent('close', { bubbles: false });
            this.element.dispatchEvent(closeEvent);
        }
    };
    __decorate([
        bindable
    ], UxChip.prototype, "theme", void 0);
    __decorate([
        bindable
    ], UxChip.prototype, "variant", void 0);
    __decorate([
        bindable
    ], UxChip.prototype, "selectedIcon", void 0);
    __decorate([
        observable
    ], UxChip.prototype, "focused", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.twoWay })
    ], UxChip.prototype, "selected", void 0);
    UxChip = __decorate([
        inject(Element, StyleEngine),
        customElement('ux-chip'),
        useView(PLATFORM.moduleName('./ux-chip.html'))
    ], UxChip);
    return UxChip;
})();
export { UxChip };
//# sourceMappingURL=ux-chip.js.map


text:
<?php

namespace Membro\Controller;

use Base\Controller\AbstractController;

class ComissaoController extends AbstractController
{

    public function __construct() {
        $this->entity = "Membro\Entity\Comissao";
        $this->service = "Membro\Service\ComissaoService";
        $this->form = "Membro\Form\ComissaoForm";
        $this->controller = "comissao";
        $this->route = "membro/default";
    }
}


text:
package org.apache.bigtop.itest.hadoop.hdfs;

import java.io.File;

import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.FsShell;
import org.apache.hadoop.cli.CLITestHelper;
import org.apache.hadoop.cli.util.CLICommand;
import org.apache.hadoop.cli.util.CLICommandFS;
import org.apache.hadoop.cli.util.CommandExecutor;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.HdfsConfiguration;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * Tests for the Command Line Interface (CLI)
 */
public class TestCLI extends CLITestHelper {
  public static final String TEST_DIR_ABSOLUTE = "/tmp/testcli";
  private String nn;
  private String sug;

  @Before
  @Override
  public void setUp() throws Exception {
    readTestConfigFile();
    conf = new HdfsConfiguration();
    conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION,
                    true);
    clitestDataDir =
      new File(TEST_CACHE_DATA_DIR).toURI().toString().replace(' ', '+');
    nn = conf.get(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY);
    sug = conf.get(DFSConfigKeys.DFS_PERMISSIONS_SUPERUSERGROUP_KEY);
    // Many of the tests expect a replication value of 1 in the output
    conf.setInt("dfs.replication", 1);
  }

  @After
  @Override
  public void tearDown() throws Exception {
    super.tearDown();
  }

  @Override
  protected String getTestFile() {
    return "testConf.xml";
  }

  @Test
  @Override
  public void testAll() {
    super.testAll();
  }

  @Override
  protected String expandCommand(final String cmd) {
    String expCmd = super.expandCommand(cmd);
    String testcliDir = TEST_DIR_ABSOLUTE;
    expCmd = expCmd.replaceAll("TEST_DIR_ABSOLUTE", testcliDir);
    expCmd = expCmd.replaceAll("SUPERGROUP", sug);
    return expCmd;
  }

  @Override
  protected CommandExecutor.Result execute(CLICommand cmd) throws Exception {
    if (cmd.getType() instanceof CLICommandFS) {
      CommandExecutor cmdExecutor = new FSCmdExecutor(nn, new FsShell(conf));
      return cmdExecutor.executeCommand(cmd.getCmd());
    } else {
      throw new IllegalArgumentException("Unknown type of test command: " + cmd.getType());
    }
  }
}


text:
My stupid rule to avoid extends some SuperClass

Noncompliant Code Example

TO DO

Compliant Solution

TO DO


text:
package anagram.server.json

import anagram.core.models.AnagramResult
import spray.json.DefaultJsonProtocol
//import anagram.core.models.AnagramResult

/**
 * Created by Random on 12/24/2014.
 */
case class AnagramRequest(
                         text: String,
                         count: Int = 10

  ) {

}

/*case class AnagramResult(
                        text: String,
                        score: Int
                          )
*/
object MyJsonProtocol extends DefaultJsonProtocol {
  implicit val anagramRequestFormat = jsonFormat2(AnagramRequest)
  implicit val anagramResultFormat = jsonFormat2(AnagramResult)
}


text:
This is the Rieke Lab common package for [Symphony](http://symphony-das.github.io/).

## Clone

`git clone https://github.com/Rieke-Lab/riekelab-package.git --recursive`

**Note:** You must use the `--recursive` option to recursively clone all submodules.

## Directory Structure

The project directory structure generally follows the [Maven Standard Directory Layout](https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html).

## License

Licensed under the [MIT License](https://opensource.org/licenses/MIT), which is an [open source license](https://opensource.org/docs/osd).


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <padding android:top="0dp" android:right="0dp" android:bottom="1dp" android:left="0dp" />
            <solid android:color="#00CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#10CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="0dp" android:right="1dp" android:bottom="0dp" android:left="0dp" />
            <solid android:color="#20CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="0dp" android:right="0dp" android:bottom="1dp" android:left="0dp" />
            <solid android:color="#30CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="0dp" android:right="0dp" android:bottom="1dp" android:left="0dp" />
            <solid android:color="#50CCCCCC" />
        </shape>
    </item>

    <!-- Background -->
    <item>
        <shape>
            <solid android:color="@color/white" />
            <corners android:radius="1dp" />
        </shape>
    </item>
</layer-list>


text:
<?php

/**
 * @file
 * Contains \Drupal\aggregator\Tests\Migrate\d6\MigrateAggregatorItemTest.
 */

namespace Drupal\aggregator\Tests\Migrate\d6;

use Drupal\aggregator\Entity\Item;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;

/**
 * Upgrade aggregator items.
 *
 * @group aggregator
 */
class MigrateAggregatorItemTest extends MigrateDrupal6TestBase {

  static $modules = array('aggregator');

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->installEntitySchema('aggregator_feed');
    $this->installEntitySchema('aggregator_item');

    // Add some id mappings for the dependant migrations.
    $id_mappings = array(
      'd6_aggregator_feed' => array(
        array(array(5), array(5)),
      ),
    );
    $this->prepareMigrations($id_mappings);

    $entity = entity_create('aggregator_feed', array(
      'fid' => 5,
      'title' => 'Drupal Core',
      'url' => 'https://groups.drupal.org/not_used/167169',
      'refresh' => 900,
      'checked' => 1389919932,
      'description' => 'Drupal Core Group feed',
    ));
    $entity->enforceIsNew();
    $entity->save();
    $this->loadDumps(['AggregatorItem.php']);
    $this->executeMigration('d6_aggregator_item');
  }

  /**
   * Test Drupal 6 aggregator item migration to Drupal 8.
   */
  public function testAggregatorItem() {
    /** @var Item $item */
    $item = Item::load(1);
    $this->assertIdentical('1', $item->id());
    $this->assertIdentical('5', $item->getFeedId());
    $this->assertIdentical('This (three) weeks in Drupal Core - January 10th 2014', $item->label());
    $this->assertIdentical('larowlan', $item->getAuthor());
    $this->assertIdentical("
What's new with Drupal 8?
", $item->getDescription());
    $this->assertIdentical('https://groups.drupal.org/node/395218', $item->getLink());
    $this->assertIdentical('1389297196', $item->getPostedTime());
    $this->assertIdentical('en', $item->language()->getId());
    $this->assertIdentical('395218 at https://groups.drupal.org', $item->getGuid());

  }

}


text:
/**
 * Logging package.
 */
package org.gazzax.labs.solrdf.log;


text:
'use strict';

angular.module('app')
	.controller('SidebarCtrl', ['$scope', '$http', 'localStorageService', function($scope, $http, localStorageService) {
		$scope.user = localStorageService.get('currentUser');
	}]);


text:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals

from contextlib import contextmanager
import functools
import os
import pkgutil
import posixpath
import re
import io
import sys
import tempfile
import unittest

import six
from six.moves import urllib
from six.moves import cStringIO

import boto
import crcmod
import mock_storage_service  # From boto/tests/integration/s3

from gslib.cloud_api import ResumableDownloadException
from gslib.cloud_api import ResumableUploadException
from gslib.lazy_wrapper import LazyWrapper
import gslib.tests as gslib_tests
from gslib.utils.boto_util import UsingCrcmodExtension, HasUserSpecifiedGsHost
from gslib.utils.constants import UTF8
from gslib.utils.encryption_helper import Base64Sha256FromBase64EncryptionKey
from gslib.utils.posix_util import GetDefaultMode
from gslib.utils.system_util import IS_WINDOWS
from gslib.utils.unit_util import MakeHumanReadable

# pylint: disable=g-import-not-at-top, g-long-lambda
if not IS_WINDOWS:
  import grp
  import pwd

  def GetInvalidGid():
    # Get a list of all GIDs on the system for quick reference.
    all_gid = sorted([group.gr_gid for group in grp.getgrall()])
    # gid - Current GID being tested, 2k is close to a large empty span on most
    # unix systems and a good starting point.
    gid = 2000
    # OverflowError should prevent loop from reaching 5b, but adding a number
    # to the loop ensures that infinite loop does not occur
    while gid < 5000000000:
      if gid in all_gid:
        # Shortcut check; if gid is in list then the group exists.
        gid += 1
        continue
      try:
        # Testing for expected behaviour while testing POSIX permissions.
        # For more on grp see:
        # https://docs.python.org/3.7/library/grp.html
        grp.getgrgid(gid)
        gid += 1
      except KeyError:
        # This is the target exception for invalid GID and the behaviour needed
        # for testing.
        return gid
      except OverflowError:
        # Limit reached without a usable GID found.
        break
    raise Exception("Unable to generate GID for ")

  def GetNonPrimaryGid():
    # Select a group for the current user that is not the user's primary group.
    # If the length of the user's groups is 1, then we must use the primary
    # group.  Otherwise put all of the user's groups (except the primary group)
    # in a list, and use the first element. This guarantees us a group that is
    # not the user's primary group (unless the user is only a member of one
    # group).
    primary_gid = GetPrimaryGid()
    user_groups = GetUserGroups()
    if len(user_groups) == 1:
      return primary_gid
    return [g for g in list(user_groups) if g != primary_gid][0]

  def GetPrimaryGid():
    return os.getgid()

  def GetUserGroups():
    return set([GetPrimaryGid()] +
               [g.gr_gid for g in grp.getgrall() if USER_NAME() in g.gr_mem])

  DEFAULT_MODE = int(GetDefaultMode(), 8)
  USER_ID = os.getuid()
  USER_NAME = LazyWrapper(lambda: pwd.getpwuid(USER_ID).pw_name)
  # Take the current user's UID and increment it by one, this counts as an
  # invalid UID, as the metric used is if the UID matches the current user's,
  # exactly.
  INVALID_UID = LazyWrapper(
      lambda: sorted([user.pw_uid for user in pwd.getpwall()])[-1] + 1)

  # Note that because the system's GID mapping can change mid-test, tests that
  # check for specific errors should always re-fetch these GID-related values,
  # rather than reusing these LazyWrapper values.
  INVALID_GID = LazyWrapper(lambda: GetInvalidGid())
  # Get a list of all groups on the system where the current username is listed
  # as a member of the group in the gr_mem group attribute. Make this a list of
  # all group IDs and cast as a set for more efficient lookup times.
  USER_GROUPS = LazyWrapper(lambda: GetUserGroups())

# 256-bit base64 encryption keys used for testing AES256 customer-supplied
# encryption. These are public and open-source, so don't ever use them for
# real data.
TEST_ENCRYPTION_KEY1 = b'iMSM9eeXliDZHSBJZO71R98tfeW/+87VXTpk5chGd6Y='
TEST_ENCRYPTION_KEY1_SHA256_B64 = Base64Sha256FromBase64EncryptionKey(
    TEST_ENCRYPTION_KEY1)

TEST_ENCRYPTION_KEY2 = b'4TSaQ3S4U+5oxAbByA7HgIigD51zfzGed/c03Ts2TXc='
TEST_ENCRYPTION_KEY2_SHA256_B64 = Base64Sha256FromBase64EncryptionKey(
    TEST_ENCRYPTION_KEY2)

TEST_ENCRYPTION_KEY3 = b'HO4Q2X28N/6SmuAJ1v1CTuJjf5emQcXf7YriKzT1gj0='
TEST_ENCRYPTION_KEY3_SHA256_B64 = Base64Sha256FromBase64EncryptionKey(
    TEST_ENCRYPTION_KEY3)

TEST_ENCRYPTION_KEY4 = b'U6zIErjZCK/IpIeDS0pJrDayqlZurY8M9dvPJU0SXI8='
TEST_ENCRYPTION_KEY4_SHA256_B64 = Base64Sha256FromBase64EncryptionKey(
    TEST_ENCRYPTION_KEY4)

TEST_ENCRYPTION_CONTENT1 = b'bar'
TEST_ENCRYPTION_CONTENT1_MD5 = 'N7UdGUp1E+RbVvZSTy1R8g=='
TEST_ENCRYPTION_CONTENT1_CRC32C = 'CrcTMQ=='
TEST_ENCRYPTION_CONTENT2 = b'bar2'
TEST_ENCRYPTION_CONTENT2_MD5 = 'Ik4lOfUiA+szcorNIotEMg=='
TEST_ENCRYPTION_CONTENT2_CRC32C = 'QScXtg=='
TEST_ENCRYPTION_CONTENT3 = b'bar3'
TEST_ENCRYPTION_CONTENT3_MD5 = '9iW6smjfu9hm0A//VQTQfw=='
TEST_ENCRYPTION_CONTENT3_CRC32C = 's0yUtQ=='
TEST_ENCRYPTION_CONTENT4 = b'bar4'
TEST_ENCRYPTION_CONTENT4_MD5 = 'kPCx6uZiUOU7W6E+cDCZFg=='
TEST_ENCRYPTION_CONTENT4_CRC32C = 'Z4bwXg=='
TEST_ENCRYPTION_CONTENT5 = b'bar5'
TEST_ENCRYPTION_CONTENT5_MD5 = '758XbXQOVkp8fTKMm83NXA=='
TEST_ENCRYPTION_CONTENT5_CRC32C = 'le1zXQ=='

# Flags for running different types of tests.
RUN_INTEGRATION_TESTS = True
RUN_UNIT_TESTS = True
RUN_S3_TESTS = False
USE_MULTIREGIONAL_BUCKETS = False

PARALLEL_COMPOSITE_UPLOAD_TEST_CONFIG = '/tmp/.boto.parallel_upload_test_config'

ORPHANED_FILE = ('This sync will orphan file(s), please fix their permissions '
                 'before trying again.')

POSIX_MODE_ERROR = 'Mode for %s won\'t allow read access.'
POSIX_GID_ERROR = 'GID for %s doesn\'t exist on current system.'
POSIX_UID_ERROR = 'UID for %s doesn\'t exist on current system.'
POSIX_INSUFFICIENT_ACCESS_ERROR = 'Insufficient access with uid/gid/mode for %s'

def BuildErrorRegex(obj, err_str):
  """Builds a regex to match a file name for a file that would be orphaned.

  Args:
    obj: Object uri.
    err_str: The error string to search for.

  Returns:
    A regex that will match the file name and with the error text for a file
    that would be orphaned.
  """
  return re.compile(err_str % ObjectToURI(obj))

def TailSet(start_point, listing):
  """Returns set of object name tails.

  Tails can be compared between source and dest, past the point at which the
  command was done. For example if test ran {cp,mv,rsync}
  gs://bucket1/dir gs://bucket2/dir2, the tails for listings from bucket1
  would start after "dir", while the tails for listings from bucket2 would
  start after "dir2".

  Args:
    start_point: The target of the cp command, e.g., for the above command it
                 would be gs://bucket1/dir for the bucket1 listing results and
                 gs://bucket2/dir2 for the bucket2 listing results.
    listing: The listing over which to compute tail.

  Returns:
    Object name tails.
  """
  return set(l[len(start_point):] for l in listing.strip().split('\n'))

HAS_S3_CREDS = (boto.config.get('Credentials', 'aws_access_key_id', None) and
                boto.config.get('Credentials', 'aws_secret_access_key', None))

HAS_NON_DEFAULT_GS_HOST = HasUserSpecifiedGsHost()

HAS_GS_HOST = boto.config.get('Credentials', 'gs_host', None) is not None

HAS_GS_PORT = boto.config.get('Credentials', 'gs_port', None) is not None

USING_JSON_API = boto.config.get('GSUtil', 'prefer_api',
                                 'json').upper() != 'XML'

def _ArgcompleteAvailable():
  argcomplete = None
  if not IS_WINDOWS:
    try:
      # pylint: disable=g-import-not-at-top
      import argcomplete
    except ImportError:
      pass
  return argcomplete is not None

ARGCOMPLETE_AVAILABLE = _ArgcompleteAvailable()

def _NormalizeURI(uri):
  """Normalizes the path component of a URI.

  Args:
    uri: URI to normalize.

  Returns:
    Normalized URI.

  Examples:
    gs://foo//bar -> gs://foo/bar
    gs://foo/./bar -> gs://foo/bar
  """
  # Note: we have to do this dance of changing gs:// to file:// because on
  # Windows, the urlparse function won't work with URL schemes that are not
  # known. urlparse('gs://foo/bar') on Windows turns into:
  #     scheme='gs', netloc='', path='//foo/bar'
  # while on non-Windows platforms, it turns into:
  #     scheme='gs', netloc='foo', path='/bar'
  uri = uri.replace('gs://', 'file://')
  parsed = list(urllib.parse.urlparse(uri))
  parsed[2] = posixpath.normpath(parsed[2])
  if parsed[2].startswith('//'):
    # The normpath function doesn't change '//foo' -> '/foo' by design.
    parsed[2] = parsed[2][1:]
  unparsed = urllib.parse.urlunparse(parsed)
  unparsed = unparsed.replace('file://', 'gs://')
  return unparsed

def GenerationFromURI(uri):
  """Returns a the generation for a StorageUri.

  Args:
    uri: boto.storage_uri.StorageURI object to get the URI from.

  Returns:
    Generation string for the URI.
  """
  if not (uri.generation or uri.version_id):
    if uri.scheme == 's3':
      return 'null'
  return uri.generation or uri.version_id

def ObjectToURI(obj, *suffixes):
  """Returns the storage URI string for a given StorageUri or file object.

  Args:
    obj: The object to get the URI from. Can be a file object, a subclass of
         boto.storage_uri.StorageURI, or a string. If a string, it is assumed to
         be a local on-disk path.
    *suffixes: Suffixes to append. For example, ObjectToUri(bucketuri, 'foo')
               would return the URI for a key name 'foo' inside the given
               bucket.

  Returns:
    Storage URI string.
  """
  if is_file(obj):
    return 'file://{}'.format(os.path.abspath(os.path.join(obj.name,
                                                           *suffixes)))
  if isinstance(obj, six.string_types):
    return 'file://{}'.format(os.path.join(obj, *suffixes))
  uri = six.ensure_text(obj.uri)
  if suffixes:
    suffixes_list = [six.ensure_text(suffix) for suffix in suffixes]
    uri = _NormalizeURI('/'.join([uri] + suffixes_list))

  # Storage URIs shouldn't contain a trailing slash.
  if uri.endswith('/'):
    uri = uri[:-1]
  return uri

class GSMockConnection(mock_storage_service.MockConnection):

  def __init__(self, *args, **kwargs):
    kwargs['provider'] = 'gs'
    self.debug = 0
    super(GSMockConnection, self).__init__(*args, **kwargs)

mock_connection = GSMockConnection()

class GSMockBucketStorageUri(mock_storage_service.MockBucketStorageUri):

  def connect(self, access_key_id=None, secret_access_key=None):
    return mock_connection

  def compose(self, components, headers=None):
    """Dummy implementation to allow parallel uploads with tests."""
    return self.new_key()

  def get_location(self, headers=None):
    return 'US'

  def get_cors(self, headers=None):
    return boto.gs.cors.Cors()

  def get_encryption_config(self, headers=None):
    return boto.gs.encryptionconfig.EncryptionConfig()

  def get_lifecycle_config(self, headers=None):
    return None

  def get_website_config(self, headers=None):
    return None

  def get_versioning_config(self, headers=None):
    return None

TEST_BOTO_REMOVE_SECTION = 'TestRemoveSection'

def _SetBotoConfig(section, name, value, revert_list):
  """Sets boto configuration temporarily for testing.

  SetBotoConfigForTest should be called by tests instead of this function.
  This will ensure that the configuration is reverted to its original setting
  using _RevertBotoConfig.

  Args:
    section: Boto config section to set
    name: Boto config name to set
    value: Value to set
    revert_list: List for tracking configs to revert.
  """
  prev_value = boto.config.get(section, name, None)
  if not boto.config.has_section(section):
    revert_list.append((section, TEST_BOTO_REMOVE_SECTION, None))
    boto.config.add_section(section)
  revert_list.append((section, name, prev_value))
  if value is None:
    boto.config.remove_option(section, name)
  else:
    boto.config.set(section, name, value)

def _RevertBotoConfig(revert_list):
  """Reverts boto config modifications made by _SetBotoConfig.

  Args:
    revert_list: List of boto config modifications created by calls to
                 _SetBotoConfig.
  """
  sections_to_remove = []
  for section, name, value in revert_list:
    if value is None:
      if name == TEST_BOTO_REMOVE_SECTION:
        sections_to_remove.append(section)
      else:
        boto.config.remove_option(section, name)
    else:
      boto.config.set(section, name, value)
  for section in sections_to_remove:
    boto.config.remove_section(section)

def SequentialAndParallelTransfer(func):
  """Decorator for tests that perform file to object transfers, or vice versa.

  This forces the test to run once normally, and again with special boto
  config settings that will ensure that the test follows the parallel composite
  upload and/or sliced object download code paths.

  Args:
    func: Function to wrap.

  Returns:
    Wrapped function.
  """

  @functools.wraps(func)
  def Wrapper(*args, **kwargs):
    # Run the test normally once.
    func(*args, **kwargs)

    if not RUN_S3_TESTS and UsingCrcmodExtension():
      # Try again, forcing parallel upload and sliced download.
      with SetBotoConfigForTest([
          ('GSUtil', 'parallel_composite_upload_threshold', '1'),
          ('GSUtil', 'sliced_object_download_threshold', '1'),
          ('GSUtil', 'sliced_object_download_max_components', '3'),
          ('GSUtil', 'check_hashes', 'always')
      ]):
        func(*args, **kwargs)

  return Wrapper

def _SectionDictFromConfigList(boto_config_list):
  """Converts the input config list to a dict that is easy to write to a file.

  This is used to reset the boto config contents for a test instead of
  preserving the existing values.

  Args:
    boto_config_list: list of tuples of:
        (boto config section to set, boto config name to set, value to set)
        If value to set is None, no entry is created.

  Returns:
    Dictionary of {section: {keys: values}} for writing to the file.
  """
  sections = {}
  for config_entry in boto_config_list:
    section, key, value = (config_entry[0], config_entry[1], config_entry[2])
    if section not in sections:
      sections[section] = {}
    if value is not None:
      sections[section][key] = value

  return sections

def _WriteSectionDictToFile(section_dict, tmp_filename):
  """Writes a section dict from _SectionDictFromConfigList to tmp_filename."""
  with open(tmp_filename, 'w') as tmp_file:
    for section, key_value_pairs in six.iteritems(section_dict):
      tmp_file.write('[%s]\n' % section)
      for key, value in six.iteritems(key_value_pairs):
        tmp_file.write('%s = %s\n' % (key, value))

@contextmanager
def SetDummyProjectForUnitTest():
  """Sets a dummy project in boto config for the duration of a 'with' clause."""
  # Listing buckets requires a project ID, but unit tests should run
  # regardless of whether one is specified in config.
  with SetBotoConfigForTest([('GSUtil', 'default_project_id', 'dummy_proj')]):
    yield

@contextmanager
def SetBotoConfigForTest(boto_config_list, use_existing_config=True):
  """Sets the input list of boto configs for the duration of a 'with' clause.

  This preserves any existing boto configuration unless it is overwritten in
  the provided boto_config_list.

  Args:
    boto_config_list: list of tuples of:
        (boto config section to set, boto config name to set, value to set)
    use_existing_config: If True, apply boto_config_list to the existing
        configuration, preserving any original values unless they are
        overwritten. Otherwise, apply boto_config_list to a blank configuration.

  Yields:
    Once after config is set.
  """
  revert_configs = []
  tmp_filename = None
  try:
    tmp_fd, tmp_filename = tempfile.mkstemp(prefix='gsutil-temp-cfg')
    os.close(tmp_fd)
    if use_existing_config:
      for boto_config in boto_config_list:
        boto_value = boto_config[2]
        if six.PY3:
          if isinstance(boto_value, bytes):
            boto_value = boto_value.decode(UTF8)
        _SetBotoConfig(boto_config[0], boto_config[1], boto_value,
                       revert_configs)
      with open(tmp_filename, 'w') as tmp_file:
        boto.config.write(tmp_file)
    else:
      _WriteSectionDictToFile(_SectionDictFromConfigList(boto_config_list),
                              tmp_filename)

    with _SetBotoConfigFileForTest(tmp_filename):
      yield
  finally:
    _RevertBotoConfig(revert_configs)
    if tmp_filename:
      try:
        os.remove(tmp_filename)
      except OSError:
        pass

@contextmanager
def SetEnvironmentForTest(env_variable_dict):
  """Sets OS environment variables for a single test."""

  def _ApplyDictToEnvironment(dict_to_apply):
    for k, v in six.iteritems(dict_to_apply):
      old_values[k] = os.environ.get(k)
      if v is not None:
        os.environ[k] = v
      elif k in os.environ:
        del os.environ[k]

  old_values = {}
  for k in env_variable_dict:
    old_values[k] = os.environ.get(k)

  try:
    _ApplyDictToEnvironment(env_variable_dict)
    yield
  finally:
    _ApplyDictToEnvironment(old_values)

@contextmanager
def _SetBotoConfigFileForTest(boto_config_path):
  """Sets a given file as the boto config file for a single test.

  This function applies only the configuration in boto_config_path and will
  ignore existing configuration. It should not be called directly by tests;
  instead, use SetBotoConfigForTest.

  Args:
    boto_config_path: Path to config file to use.

  Yields:
    When configuration has been applied, and again when reverted.
  """
  # Setup for entering "with" block.
  try:
    old_boto_config_env_variable = os.environ['BOTO_CONFIG']
    boto_config_was_set = True
  except KeyError:
    boto_config_was_set = False
  os.environ['BOTO_CONFIG'] = boto_config_path

  try:
    yield
  finally:
    # Teardown for exiting "with" block.
    if boto_config_was_set:
      os.environ['BOTO_CONFIG'] = old_boto_config_env_variable
    else:
      os.environ.pop('BOTO_CONFIG', None)

def GetTestNames():
  """Returns a list of the names of the test modules in gslib.tests."""
  matcher = re.compile(r'^test_(?P<name>.*)$')
  names = []
  for _, modname, _ in pkgutil.iter_modules(gslib_tests.__path__):
    m = matcher.match(modname)
    if m:
      names.append(m.group('name'))
  return names

def is_file(obj):
  if six.PY2:
    return isinstance(obj, file)  # pylint: disable=undefined-variable
  return isinstance(obj, io.IOBase)

def MakeBucketNameValid(name):
  """Returns a copy of the given name with any invalid characters replaced.

  Args:
    name Union[str, unicode, bytes]: The bucket name to transform into a valid name.

  Returns:
    Union[str, unicode, bytes] The version of the bucket name containing only
      valid characters.
  """
  # Neither underscores nor uppercase letters are valid characters for a
  # bucket name. Replace those with hyphens and lowercase characters.
  if isinstance(name, (six.text_type, six.binary_type)):
    return name.replace('_', '-').lower()
  else:
    raise TypeError('Unable to format name. Incorrect Type: {0}'.format(
        type(name)))

@contextmanager
def WorkingDirectory(new_working_directory):
  """Changes the working directory for the duration of a 'with' call.

  Args:
    new_working_directory: The directory to switch to before executing wrapped
      code. A None value indicates that no switching is necessary.

  Yields:
    Once after working directory has been changed.
  """
  prev_working_directory = None
  try:
    prev_working_directory = os.getcwd()
  except OSError:
    # This can happen if the current working directory no longer exists.
    pass

  if new_working_directory:
    os.chdir(new_working_directory)

  try:
    yield
  finally:
    if new_working_directory and prev_working_directory:
      os.chdir(prev_working_directory)

def InvokedFromParFile():
  loader = globals().get('__loader__', None)
  if not loader:
    return False
  return 'zipimport' in loader.__class__.__module__

def SkipForParFile(reason):
  if InvokedFromParFile():
    return unittest.skip(reason)
  else:
    return lambda func: func

# Custom test callbacks must be pickleable, and therefore at global scope.
class HaltingCopyCallbackHandler(object):
  """Test callback handler for intentionally stopping a resumable transfer."""

  def __init__(self, is_upload, halt_at_byte):
    self._is_upload = is_upload
    self._halt_at_byte = halt_at_byte

  # pylint: disable=invalid-name
  def call(self, total_bytes_transferred, total_size):
    """Forcibly exits if the transfer has passed the halting point.

    Note that this function is only called when the conditions in
    gslib.progress_callback.ProgressCallbackWithTimeout.Progress are met, so
    self._halt_at_byte is only precise if it's divisible by
    gslib.progress_callback._START_BYTES_PER_CALLBACK.
    """
    if total_bytes_transferred >= self._halt_at_byte:
      sys.stderr.write(
          'Halting transfer after byte %s. %s/%s transferred.\r\n' %
          (self._halt_at_byte, MakeHumanReadable(total_bytes_transferred),
           MakeHumanReadable(total_size)))
      if self._is_upload:
        raise ResumableUploadException('Artifically halting upload.')
      else:
        raise ResumableDownloadException('Artifically halting download.')

class HaltOneComponentCopyCallbackHandler(object):
  """Test callback handler for stopping part of a sliced download."""

  def __init__(self, halt_at_byte):
    self._last_progress_byte = None
    self._halt_at_byte = halt_at_byte

  # pylint: disable=invalid-name
  # pylint: disable=unused-argument
  def call(self, current_progress_byte, total_size_unused):
    """Forcibly exits if the passed the halting point since the last call."""
    if (self._last_progress_byte is not None and
        self._last_progress_byte < self._halt_at_byte < current_progress_byte):
      sys.stderr.write('Halting transfer.\r\n')
      raise ResumableDownloadException('Artifically halting download.')
    self._last_progress_byte = current_progress_byte

class TestParams(object):
  """Allows easier organization of test parameters.

  This class allows grouping of test parameters, which include args and kwargs
  to be used, as well as the expected result based on those arguments.

  For example, to test an Add function, one might do:

  params = TestParams(args=(1, 2, 3), expected=6)
  self.assertEqual(Add(*(params.args)), params.expected)
  """

  def __init__(self, args=None, kwargs=None, expected=None):
    self.args = tuple() if args is None else args
    self.kwargs = dict() if kwargs is None else kwargs
    self.expected = expected

    if not isinstance(args, (tuple, list)):
      raise TypeError('TestParam args must be a tuple or list.')
    if not isinstance(self.kwargs, dict):
      raise TypeError('TestParam kwargs must be a dict.')

class CaptureStdout(list):
  """Context manager.

  For example, this function has the lines printed by the function call
  stored as a list in output:

  with CaptureStdout() as output:
    function(input_to_function)
  """

  def __enter__(self):
    self._stdout = sys.stdout
    sys.stdout = self._stringio = cStringIO()
    return self

  def __exit__(self, *args):
    self.extend(self._stringio.getvalue().splitlines())
    del self._stringio
    sys.stdout = self._stdout


text:
package kneelnrise.warp10scala.constants

object CharsetConstants {
  val `UTF-8` = "UTF-8"
}


text:
package uniqueElements;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Main {

	public static void main(final String[] args) throws IOException {

		final BufferedReader in = new BufferedReader(new FileReader(new File(
				args[0])));
		String line;

		while ((line = in.readLine()) != null) {
			final String[] number = line.split(",");
			final StringBuilder output = new StringBuilder();
			Integer prevNumber = null;

			for (int i = 0; i < number.length; i++) {

				final int currentElement = Integer.parseInt(number[i]);
				if (prevNumber == null || currentElement > prevNumber) {

					output.append(currentElement);
					prevNumber = currentElement;

					if (!number[i].equals(number[number.length - 1])) {
						output.append(",");
					}
				}
			}
			System.out.println(output.toString());
		}
		in.close();
	}
}


text: Uniform logging messages in golang


text:
package org.eclipse.jgit.lib;

import java.io.IOException;

public class TreeIteratorLeafOnlyTest extends RepositoryTestCase {

	/** Empty tree */
	public void testEmpty() {
		Tree tree = new Tree(db);
		TreeIterator i = makeIterator(tree);
		assertFalse(i.hasNext());
	}

	/**
	 * one file
	 *
	 * @throws IOException
	 */
	public void testSimpleF1() throws IOException {
		Tree tree = new Tree(db);
		tree.addFile("x");
		TreeIterator i = makeIterator(tree);
		assertTrue(i.hasNext());
		assertEquals("x", i.next().getName());
	}

	/**
	 * two files
	 *
	 * @throws IOException
	 */
	public void testSimpleF2() throws IOException {
		Tree tree = new Tree(db);
		tree.addFile("a");
		tree.addFile("x");
		TreeIterator i = makeIterator(tree);
		assertTrue(i.hasNext());
		assertEquals("a", i.next().getName());
		assertEquals("x", i.next().getName());
	}

	/**
	 * Empty tree
	 *
	 * @throws IOException
	 */
	public void testSimpleT() throws IOException {
		Tree tree = new Tree(db);
		tree.addTree("a");
		TreeIterator i = makeIterator(tree);
		assertFalse(i.hasNext());
	}

	public void testTricky() throws IOException {
		Tree tree = new Tree(db);
		tree.addFile("a.b");
		tree.addFile("a.c");
		tree.addFile("a/b.b/b");
		tree.addFile("a/b");
		tree.addFile("a/c");
		tree.addFile("a=c");
		tree.addFile("a=d");

		TreeIterator i = makeIterator(tree);
		assertTrue(i.hasNext());
		assertEquals("a.b", i.next().getFullName());
		assertTrue(i.hasNext());
		assertEquals("a.c", i.next().getFullName());
		assertTrue(i.hasNext());
		assertEquals("a/b", i.next().getFullName());
		assertTrue(i.hasNext());
		assertEquals("a/b.b/b", i.next().getFullName());
		assertTrue(i.hasNext());
		assertEquals("a/c", i.next().getFullName());
		assertTrue(i.hasNext());
		assertEquals("a=c", i.next().getFullName());
		assertTrue(i.hasNext());
		assertEquals("a=d", i.next().getFullName());
		assertFalse(i.hasNext());
	}

	private TreeIterator makeIterator(Tree tree) {
		return new TreeIterator(tree);
	}
}


text:
<html>
<body bgcolor="#ffffff">
Support classes for the Ukrainian DSTU standard.
</body>
</html>