text:
import warnings
try:
    from mock import patch, call
except ImportError:
    from unittest.mock import patch, call

from .helpers import *

class TestClient(ClientTestCase):

    def test_version_values(self):
        values = self.client._version_values()
        self.assertEqual('Python', values['language'])
        self.assertRegexpMatches(values['version'], r'[0-9]+[.][0-9]+[.][0-9]+')
        self.assertSetEqual(
            {'language', 'version', 'language_version', 'os', 'os_version'},
            set(values.keys()))

    def test_version_header(self):
        self.assertRegexpMatches(
            self.client._version_header(), r'language=Python')

    def test_default_headers(self):
        self.client.headers['key'] = 'value'
        responses.add(GET, 'http://app/users/me', status=200, body='{"data":{}}')
        self.client.users.me()
        self.assertLessEqual(
            set({'key': 'value'}.items()),
            set(responses.calls[0].request.headers.items())
        )

    def test_request_headers(self):
        responses.add(GET, 'http://app/users/me', status=200, body='{"data":{}}')
        self.client.users.me(headers={'key': 'value'})
        self.assertLessEqual(
            set({'key': 'value'}.items()),
            set(responses.calls[0].request.headers.items())
        )

    def test_overriding_headers(self):
        self.client.headers['key'] = 'value'
        self.client.headers['key2'] = 'value2'
        responses.add(GET, 'http://app/users/me', status=200, body='{"data":{}}')
        self.client.users.me(headers={'key2': 'value3'})
        self.assertLessEqual(
            set({'key': 'value', 'key2': 'value3'}.items()),
            set(responses.calls[0].request.headers.items())
        )

    def test_content_type_headers(self):
        self.client.headers['key'] = 'value'
        responses.add(POST, 'http://app/tasks/123/addProject', status=200,
                      body='{"data":{}}')
        self.client.tasks.add_project(123, project=456, headers={'key2': 'value2'})
        self.assertLessEqual(
            set({'content-type': 'application/json'}.items()),
            set(responses.calls[0].request.headers.items())
        )

    def test_users_me_not_authorized(self):
        res = {
            "errors": [
                { "message": "Not Authorized" }
            ]
        }
        responses.add(GET, 'http://app/users/me', status=401, body=json.dumps(res), match_querystring=True)
        self.assertRaises(asana.error.NoAuthorizationError, self.client.users.me)

    def test_tasks_find_all_invalid_request(self):
        res = {
            "errors": [
                { "message": "workspace: Missing input" }
            ]
        }
        responses.add(GET, 'http://app/tasks', status=400, body=json.dumps(res), match_querystring=True)
        self.assertRaises(asana.error.InvalidRequestError, self.client.tasks.find_all)

    def test_users_me_server_error(self):
        res = {
            "errors": [
                {
                    "message": "Server Error",
                    "phrase": "6 sad squid snuggle softly"
                }
            ]
        }
        responses.add(GET, 'http://app/users/me', status=500, body=json.dumps(res), match_querystring=True)
        self.assertRaises(asana.error.ServerError, self.client.users.me, max_retries=0)

    def test_users_me_unfriendly_server_error(self):
        res = "Crappy Response"
        responses.add(GET, 'http://app/users/me', status=504, body=res, match_querystring=True)
        self.assertRaises(asana.error.ServerError, self.client.users.me, max_retries=0)

    def test_users_find_by_id_not_found(self):
        res = {
            "errors": [
                { "message": "user: Unknown object: 1234124312341" }
            ]
        }
        responses.add(GET, 'http://app/users/1234', status=404, body=json.dumps(res), match_querystring=True)
        self.assertRaises(asana.error.NotFoundError, self.client.users.find_by_id, (1234))

    def test_users_find_by_id_forbidden(self):
        res = {
            "errors": [
                { "message": "user: Forbidden" }
            ]
        }
        responses.add(GET, 'http://app/users/1234', status=403, body=json.dumps(res), match_querystring=True)
        self.assertRaises(asana.error.ForbiddenError, self.client.users.find_by_id, (1234))

    def test_option_pretty(self):
        res = {
            "data": { "email": "sanchez@...", "id": 999, "name": "Greg Sanchez" }
        }
        responses.add(GET, 'http://app/users/me?opt_pretty=true', status=200, body=json.dumps(res), match_querystring=True)
        self.assertEqual(self.client.users.me(pretty=True), res['data'])

    def test_option_fields(self):
        res = {
            "data": { "name": "Make a list", "notes": "Check it twice!", "id": 1224 }
        }
        responses.add(GET, 'http://app/tasks/1224?opt_fields=name%2Cnotes', status=200, body=json.dumps(res), match_querystring=True)
        self.assertEqual(self.client.tasks.find_by_id(1224, fields=['name','notes']), res['data'])

    def test_option_expand(self):
        req = {
            'data': { 'assignee': 1234 },
            'options': { 'expand' : ['projects'] }
        }
        res = {
            "data": {
                "id": 1001,
                "projects": [
                    {
                        "archived": false,
                        "created_at": "",
                        "followers": [],
                        "modified_at": "",
                        "notes": "",
                        "id": 1331,
                        "name": "Things to buy"
                    }
                ]
                # ...
            }
        }
        responses.add(PUT, 'http://app/tasks/1001', status=200, body=json.dumps(res), match_querystring=True)
        # -d "assignee=1234" \
        # -d "options.expand=%2Aprojects%2A"
        self.assertEqual(self.client.tasks.update(1001, req['data'], expand=['projects']), res['data'])
        self.assertEqual(json.loads(responses.calls[0].request.body), req)

    def test_pagination(self):
        res = {
            "data": [
                { "id": 1000, "name": "Task 1" }
            ],
            "next_page": {
                "offset": "yJ0eXAiOiJKV1QiLCJhbGciOiJIRzI1NiJ9",
                "path": "/tasks?project=1337&limit=5&offset=yJ0eXAiOiJKV1QiLCJhbGciOiJIRzI1NiJ9",
                "uri": "https://app.asana.com/api/1.0/tasks?project=1337&limit=5&offset=yJ0eXAiOiJKV1QiLCJhbGciOiJIRzI1NiJ9"
            }
        }
        responses.add(GET, 'http://app/projects/1337/tasks?limit=5&offset=eyJ0eXAiOJiKV1iQLCJhbGciOiJIUzI1NiJ9', status=200, body=json.dumps(res), match_querystring=True)

        self.assertEqual(self.client.tasks.find_by_project(1337, { 'limit': 5, 'offset': 'eyJ0eXAiOJiKV1iQLCJhbGciOiJIUzI1NiJ9'}), res['data'])

    @unittest.skip("iterator_type='pages' disabled")
    def test_page_iterator_item_limit_lt_items(self):
        responses.add(GET, 'http://app/projects/1337/tasks?limit=2', status=200, body=json.dumps({ 'data': ['a', 'b'], 'next_page': { 'offset': 'a', 'path': '/projects/1337/tasks?limit=2&offset=a' } }), match_querystring=True)
        responses.add(GET, 'http://app/projects/1337/tasks?limit=2&offset=a', status=200, body=json.dumps({ 'data': ['c'], 'next_page': null }), match_querystring=True)

        iterator = self.client.tasks.find_by_project(1337, item_limit=2, page_size=2, iterator_type='pages')
        self.assertEqual(next(iterator), ['a', 'b'])
        self.assertRaises(StopIteration, next, (iterator))

    @unittest.skip("iterator_type='pages' disabled")
    def test_page_iterator_item_limit_eq_items(self):
        responses.add(GET, 'http://app/projects/1337/tasks?limit=2', status=200, body=json.dumps({ 'data': ['a', 'b'], 'next_page': { 'offset': 'a', 'path': '/projects/1337/tasks?limit=2&offset=a' } }), match_querystring=True)
        responses.add(GET, 'http://app/projects/1337/tasks?limit=1&offset=a', status=200, body=json.dumps({ 'data': ['c'], 'next_page': null }), match_querystring=True)

        iterator = self.client.tasks.find_by_project(1337, item_limit=3, page_size=2, iterator_type='pages')
        self.assertEqual(next(iterator), ['a', 'b'])
        self.assertEqual(next(iterator), ['c'])
        self.assertRaises(StopIteration, next, (iterator))

    @unittest.skip("iterator_type='pages' disabled")
    def test_page_iterator_item_limit_gt_items(self):
        responses.add(GET, 'http://app/projects/1337/tasks?limit=2', status=200, body=json.dumps({ 'data': ['a', 'b'], 'next_page': { 'offset': 'a', 'path': '/projects/1337/tasks?limit=2&offset=a' } }), match_querystring=True)
        responses.add(GET, 'http://app/projects/1337/tasks?limit=2&offset=a', status=200, body=json.dumps({ 'data': ['c'], 'next_page': null }), match_querystring=True)

        iterator = self.client.tasks.find_by_project(1337, item_limit=4, page_size=2, iterator_type='pages')
        self.assertEqual(next(iterator), ['a', 'b'])
        self.assertEqual(next(iterator), ['c'])
        self.assertRaises(StopIteration, next, (iterator))

    def test_item_iterator_item_limit_lt_items(self):
        responses.add(GET, 'http://app/projects/1337/tasks?limit=2', status=200, body=json.dumps({ 'data': ['a', 'b'], 'next_page': { 'offset': 'a', 'path': '/projects/1337/tasks?limit=2&offset=a' } }), match_querystring=True)

        iterator = self.client.tasks.find_by_project(1337, item_limit=2, page_size=2, iterator_type='items')
        self.assertEqual(next(iterator), 'a')
        self.assertEqual(next(iterator), 'b')
        self.assertRaises(StopIteration, next, (iterator))

    def test_item_iterator_item_limit_eq_items(self):
        responses.add(GET, 'http://app/projects/1337/tasks?limit=2', status=200, body=json.dumps({ 'data': ['a', 'b'], 'next_page': { 'offset': 'a', 'path': '/projects/1337/tasks?limit=2&offset=a' } }), match_querystring=True)
        responses.add(GET, 'http://app/projects/1337/tasks?limit=1&offset=a', status=200, body=json.dumps({ 'data': ['c'], 'next_page': null }), match_querystring=True)

        iterator = self.client.tasks.find_by_project(1337, item_limit=3, page_size=2, iterator_type='items')
        self.assertEqual(next(iterator), 'a')
        self.assertEqual(next(iterator), 'b')
        self.assertEqual(next(iterator), 'c')
        self.assertRaises(StopIteration, next, (iterator))

    def test_item_iterator_item_limit_gt_items(self):
        responses.add(GET, 'http://app/projects/1337/tasks?limit=2', status=200, body=json.dumps({ 'data': ['a', 'b'], 'next_page': { 'offset': 'a', 'path': '/projects/1337/tasks?limit=2&offset=a' } }), match_querystring=True)
        responses.add(GET, 'http://app/projects/1337/tasks?limit=2&offset=a', status=200, body=json.dumps({ 'data': ['c'], 'next_page': null }), match_querystring=True)

        iterator = self.client.tasks.find_by_project(1337, item_limit=4, page_size=2, iterator_type='items')
        self.assertEqual(next(iterator), 'a')
        self.assertEqual(next(iterator), 'b')
        self.assertEqual(next(iterator), 'c')
        self.assertRaises(StopIteration, next, (iterator))

    def test_item_iterator_preserve_opt_fields(self):
        responses.add(GET, 'http://app/projects/1337/tasks?limit=2&opt_fields=foo', status=200, body=json.dumps({ 'data': ['a', 'b'], 'next_page': { 'offset': 'a', 'path': '/projects/1337/tasks?limit=2&offset=a' } }), match_querystring=True)
        responses.add(GET, 'http://app/projects/1337/tasks?limit=1&opt_fields=foo&offset=a', status=200, body=json.dumps({ 'data': ['c'], 'next_page': null }), match_querystring=True)

        iterator = self.client.tasks.find_by_project(1337, item_limit=3, page_size=2, fields=['foo'], iterator_type='items')
        self.assertEqual(next(iterator), 'a')
        self.assertEqual(next(iterator), 'b')
        self.assertEqual(next(iterator), 'c')
        self.assertRaises(StopIteration, next, (iterator))

    @patch('time.sleep')
    def test_rate_limiting(self, time_sleep):
        res = [
            (429, { 'Retry-After': '10' }, '{}'),
            (200, {}, json.dumps({ 'data': 'me' }))
        ]
        responses.add_callback(responses.GET, 'http://app/users/me', callback=lambda r: res.pop(0), content_type='application/json')

        self.assertEqual(self.client.users.me(), 'me')
        self.assertEqual(len(responses.calls), 2)
        self.assertEqual(time_sleep.mock_calls, [call(10.0)])

    @patch('time.sleep')
    def test_rate_limited_twice(self, time_sleep):
        res = [
            (429, { 'Retry-After': '10' }, '{}'),
            (429, { 'Retry-After': '1' }, '{}'),
            (200, {}, json.dumps({ 'data': 'me' }))
        ]
        responses.add_callback(responses.GET, 'http://app/users/me', callback=lambda r: res.pop(0), content_type='application/json')

        self.assertEqual(self.client.users.me(), 'me')
        self.assertEqual(len(responses.calls), 3)
        self.assertEqual(time_sleep.mock_calls, [call(10.0), call(1.0)])

    @patch('time.sleep')
    def test_server_error_retry(self, time_sleep):
        res = [
            (500, {}, '{}'),
            (500, {}, '{}'),
            (500, {}, '{}'),
            (200, {}, json.dumps({ 'data': 'me' }))
        ]
        responses.add_callback(responses.GET, 'http://app/users/me', callback=lambda r: res.pop(0), content_type='application/json')

        self.assertRaises(asana.error.ServerError, self.client.users.me, max_retries=2)
        self.assertEqual(time_sleep.mock_calls, [call(1.0), call(2.0)])

    @patch('time.sleep')
    def test_server_error_retry_backoff(self, time_sleep):
        res = [
            (500, {}, '{}'),
            (500, {}, '{}'),
            (500, {}, '{}'),
            (200, {}, json.dumps({ 'data': 'me' }))
        ]
        responses.add_callback(responses.GET, 'http://app/users/me', callback=lambda r: res.pop(0), content_type='application/json')

        self.assertEqual(self.client.users.me(), 'me')
        self.assertEqual(time_sleep.mock_calls, [call(1.0), call(2.0), call(4.0)])

    def test_get_named_parameters(self):
        responses.add(GET, 'http://app/tasks?workspace=14916&assignee=me', status=200, body=json.dumps({ 'data': 'dummy data' }), match_querystring=True)

        self.assertEqual(self.client.tasks.find_all(workspace=14916, assignee="me"), 'dummy data')

    def test_post_named_parameters(self):
        responses.add(POST, 'http://app/tasks', status=201, body='{ "data": "dummy data" }', match_querystring=True)

        self.assertEqual(self.client.tasks.create(assignee=1235, followers=[5678], name="Hello, world."), 'dummy data')
        self.assertEqual(json.loads(responses.calls[0].request.body), {
            "data": {
                "assignee": 1235,
                "followers": [5678],
                "name": "Hello, world."
            }
        })

    def test_put_named_parameters(self):
        responses.add(PUT, 'http://app/tasks/1001', status=200, body='{ "data": "dummy data" }', match_querystring=True)

        self.assertEqual(self.client.tasks.update(1001, assignee=1235, followers=[5678], name="Hello, world."), 'dummy data')
        self.assertEqual(json.loads(responses.calls[0].request.body), {
            "data": {
                "assignee": 1235,
                "followers": [5678],
                "name": "Hello, world."
            }
        })

    def test_asana_change_header_logging(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")

            requestHeaders = {}
            responseHeaders = {
                'asana-change': 'name=string_ids;info=something;affected=true'
            }
            self.client._log_asana_change_header(requestHeaders, responseHeaders)

            assert len(w) == 1

    def test_asana_change_header_logging_turned_off(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")

            requestHeaders = {}
            responseHeaders = {
                'asana-change': 'name=string_ids;info=something;affected=true'
            }
            self.client.LOG_ASANA_CHANGE_WARNINGS = false
            self.client._log_asana_change_header(requestHeaders, responseHeaders)

            assert len(w) == 0

    def test_asana_change_header_ignore_case(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")

            requestHeaders = {}
            responseHeaders = {
                'asANa-chANge': 'name=string_ids;info=something;affected=true'
            }
            self.client._log_asana_change_header(requestHeaders, responseHeaders)

            assert len(w) == 1

    def test_asana_change_header_enable(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")

            requestHeaders = {
                'asana-enable': 'string_ids'
            }
            responseHeaders = {
                'asana-change': 'name=string_ids;info=something;affected=true'
            }
            self.client._log_asana_change_header(requestHeaders, responseHeaders)

            assert len(w) == 0

    def test_asana_change_header_disable(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")

            requestHeaders = {
                'asana-disable': 'string_ids'
            }
            responseHeaders = {
                'asana-change': 'name=string_ids;info=something;affected=true'
            }
            self.client._log_asana_change_header(requestHeaders, responseHeaders)

            assert len(w) == 0

    def test_asana_change_header_multiple(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")

            requestHeaders = {}
            responseHeaders = {
                'asana-change': 'name=string_ids;info=something;affected=true,name=new_sections;info=something;affected=true'
            }
            self.client._log_asana_change_header(requestHeaders, responseHeaders)

            assert len(w) == 2

    def test_asana_change_header_multiple_disable(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")

            requestHeaders = {
                'asana-disable': 'string_ids,new_sections'
            }
            responseHeaders = {
                'asana-change': 'name=string_ids;info=something;affected=true,name=new_sections;info=something;affected=true'
            }
            self.client._log_asana_change_header(requestHeaders, responseHeaders)

            assert len(w) == 0


text:
package com.codepath.instagram.models;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class InstagramPost implements Serializable {
    public String mediaId;
    public InstagramUser user;
    public InstagramImage image;
    public List<InstagramComment> comments;
    public String caption;
    public int likesCount;
    public List<InstagramUser> likers;
    public int commentsCount;
    public long createdTime;

    public void appendComment(InstagramComment comment) {
        if (comments == null) {
            comments = new ArrayList<>();
        }
        comments.add(comment);
    }

    public static InstagramPost fromJson(JSONObject jsonObject) {
        if (jsonObject == null) {
            return null;
        }

        InstagramPost post = new InstagramPost();

        try {
            post.mediaId = jsonObject.getString("id");
            post.user = InstagramUser.fromJson(jsonObject.getJSONObject("user"));

            JSONObject imagesJson = jsonObject.optJSONObject("images");
            if (imagesJson != null) {
                post.image = InstagramImage.fromJson(imagesJson.optJSONObject("standard_resolution"));
            }

            post.caption = jsonObject.optJSONObject("caption") != null ?
                    jsonObject.getJSONObject("caption").getString("text") : null;

            JSONObject likesJson = jsonObject.optJSONObject("likes");
            post.likesCount = likesJson != null ? likesJson.optInt("count") : 0;
            JSONArray likersJson = likesJson != null ? likesJson.optJSONArray("data") : null;
            post.likers = likersJson != null ? InstagramUser.fromJson(likersJson) : null;

            JSONObject commentsJson = jsonObject.optJSONObject("comments");
            post.commentsCount = commentsJson != null ? commentsJson.optInt("count") : 0;
            post.comments = commentsJson != null ? InstagramComment.fromJson(commentsJson.optJSONArray("data")) : null;

            post.createdTime = jsonObject.getLong("created_time");

        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
        return post;
    }

    public static List<InstagramPost> fromJson(JSONArray jsonArray) {
        if (jsonArray == null) {
            return null;
        }

        List<InstagramPost> posts = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject;
            try {
                jsonObject = jsonArray.getJSONObject(i);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            InstagramPost post = InstagramPost.fromJson(jsonObject);
            if (post != null) {
                posts.add(post);
            }
        }
        return posts;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.sling.rewriter.impl;

import java.io.IOException;
import java.io.PrintWriter;

import org.apache.sling.rewriter.Generator;
import org.apache.sling.rewriter.PipelineConfiguration;
import org.apache.sling.rewriter.ProcessingComponentConfiguration;
import org.apache.sling.rewriter.ProcessingContext;
import org.apache.sling.rewriter.Processor;
import org.apache.sling.rewriter.ProcessorConfiguration;
import org.apache.sling.rewriter.Serializer;
import org.apache.sling.rewriter.Transformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

/**
 * The PipelineImpl is the heart of the pipeline
 * processing. It uses the configured pipeline components,
 * assembles a pipeline and runs the pipeline.
 */
public class PipelineImpl implements Processor {

    private static Logger LOGGER = LoggerFactory.getLogger(PipelineImpl.class);

    /** Empty array of transformers. */
    private static final Transformer[] EMPTY_TRANSFORMERS = new Transformer[0];

    /** The starting point of the pipeline. */
    private Generator generator;

    /** The transformers. */
    private Transformer[] transformers;

    /** The end point. */
    private Serializer serializer;

    /** The first component in the pipeline after the generator */
    private ContentHandler firstContentHandler;

    /** The factory cache. */
    private final FactoryCache factoryCache;

    /**
     * Setup this pipeline.
     */
    public PipelineImpl(final FactoryCache factoryCache) {
        this.factoryCache = factoryCache;
    }

    /**
     * @see org.apache.sling.rewriter.Processor#init(org.apache.sling.rewriter.ProcessingContext, org.apache.sling.rewriter.ProcessorConfiguration)
     */
    public void init(ProcessingContext processingContext,
                     ProcessorConfiguration c)
    throws IOException {
        LOGGER.debug("Setting up pipeline...");
        final PipelineConfiguration config = (PipelineConfiguration)c;
        final ProcessingComponentConfiguration[] transformerConfigs = config.getTransformerConfigurations();

        // create components and initialize them

        // lets get custom rewriter transformers
        final Transformer[][] rewriters = this.factoryCache.getGlobalTransformers(processingContext);

        final ProcessingComponentConfiguration generatorConfig = config.getGeneratorConfiguration();
        this.generator = this.getPipelineComponent(Generator.class, generatorConfig.getType(), false);
        LOGGER.debug("Using generator type {}: {}.", generatorConfig.getType(), generator);
        generator.init(processingContext, generatorConfig);

        final int transformerCount = (transformerConfigs == null ? 0 : transformerConfigs.length) + rewriters[0].length + rewriters[1].length;
        int index = 0;
        if ( transformerCount > 0 ) {
            // add all pre rewriter transformers
            transformers = new Transformer[transformerCount];
            for(int i=0; i< rewriters[0].length; i++) {
                transformers[index] = rewriters[0][i];
                LOGGER.debug("Using pre transformer: {}.", transformers[index]);
                transformers[index].init(processingContext, ProcessingComponentConfigurationImpl.EMPTY);
                index++;
            }
            if ( transformerConfigs != null ) {
                for(int i=0; i< transformerConfigs.length;i++) {
                    transformers[index] = this.getPipelineComponent(Transformer.class, transformerConfigs[i].getType(),
                            transformerConfigs[i].getConfiguration().get(ProcessingComponentConfiguration.CONFIGURATION_COMPONENT_OPTIONAL, false));
                    if ( transformers[index] != null ) {
                        LOGGER.debug("Using transformer type {}: {}.", transformerConfigs[i].getType(), transformers[index]);
                        transformers[index].init(processingContext, transformerConfigs[i]);
                        index++;
                    } else {
                        LOGGER.debug("Skipping missing optional transformer of type {}", transformerConfigs[i].getType());
                    }
                }
            }
            for(int i=0; i< rewriters[1].length; i++) {
                transformers[index] = rewriters[1][i];
                LOGGER.debug("Using post transformer: {}.", transformers[index]);
                transformers[index].init(processingContext, ProcessingComponentConfigurationImpl.EMPTY);
                index++;
            }
        } else {
            transformers = EMPTY_TRANSFORMERS;
        }

        final ProcessingComponentConfiguration serializerConfig = config.getSerializerConfiguration();
        this.serializer = this.getPipelineComponent(Serializer.class, serializerConfig.getType(), false);
        LOGGER.debug("Using serializer type {}: {}.", serializerConfig.getType(), serializer);
        serializer.init(processingContext, serializerConfig);

        ContentHandler pipelineComponent = serializer;
        // now chain pipeline
        for(int i=index; i>0; i--) {
            transformers[i-1].setContentHandler(pipelineComponent);
            pipelineComponent = transformers[i-1];
        }

        this.firstContentHandler = pipelineComponent;
        generator.setContentHandler(this.firstContentHandler);
        LOGGER.debug("Finished pipeline setup.");
    }

    /**
     * Lookup a pipeline component.
     */
    @SuppressWarnings("unchecked")
    private <ComponentType> ComponentType getPipelineComponent(final Class<ComponentType> typeClass,
                                                               final String type,
                                                               final boolean optional)
    throws IOException {
        final ComponentType component;
        if ( typeClass == Generator.class ) {
            component = (ComponentType)this.factoryCache.getGenerator(type);
        } else if ( typeClass == Transformer.class ) {
            component = (ComponentType)this.factoryCache.getTransformer(type);
        } else if ( typeClass == Serializer.class ) {
            component = (ComponentType)this.factoryCache.getSerializer(type);
        } else {
            component = null;
        }

        if ( component == null && !optional ) {
            throw new IOException("Unable to get component of class '" + typeClass + "' with type '" + type + "'.");
        }

        return component;
    }

    /**
     * @see org.apache.sling.rewriter.Processor#getWriter()
     */
    public PrintWriter getWriter() {
        return this.generator.getWriter();
    }

    /**
     * @see org.apache.sling.rewriter.Processor#getContentHandler()
     */
    public ContentHandler getContentHandler() {
        return this.firstContentHandler;
    }

    /**
     * @see org.apache.sling.rewriter.Processor#finished(boolean)
     */
    public void finished(final boolean errorOccured) throws IOException {
        try {
            // if an error occurred, we only clean up
            if ( !errorOccured ) {
                try {
                    this.generator.finished();
                } catch (final SAXException se) {
                    if ( se.getCause() != null && se.getCause() instanceof IOException ) {
                        throw (IOException)se.getCause();
                    } else {
                        final IOException ioe = new IOException("Pipeline exception: " + se.getMessage());
                        ioe.initCause(se);
                        throw ioe;
                    }
                }
            }
        } finally {
            // dispose components
            if ( this.generator != null ) {
                this.generator.dispose();
            }
            if ( this.transformers != null ) {
                for(final Transformer transformer : this.transformers ) {
                    if ( transformer != null ) {
                        transformer.dispose();
                    }
                }
            }
            if ( this.serializer != null ) {
                this.serializer.dispose();
            }
        }
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("Pipeline Processor (");
        sb.append(super.toString());
        sb.append(") : ");
        sb.append("generator: ");
        sb.append(this.generator != null ? this.generator : "-");
        sb.append(", transformers: [");
        if ( this.transformers != null && this.transformers.length > 0 ) {
            boolean first = true;
            for(final Transformer t : this.transformers ) {
                if ( !first ) {
                    sb.append(", ");
                }
                first = false;
                sb.append(t);
            }
            sb.append("]");
        } else {
            sb.append("-");
        }
        sb.append(", serializer: ");
        sb.append(this.serializer != null ? this.serializer : "-");
        return sb.toString();
    }
}


text:
package dyvilx.tools.compiler.ast.expression.operator;

import dyvilx.tools.compiler.ast.expression.access.MethodCall;
import dyvilx.tools.compiler.ast.context.IContext;
import dyvilx.tools.compiler.ast.expression.ColonOperator;
import dyvilx.tools.compiler.ast.expression.IValue;
import dyvilx.tools.compiler.ast.header.IClassCompilableList;
import dyvilx.tools.compiler.ast.header.ICompilableList;
import dyvilx.tools.compiler.ast.parameter.ArgumentList;
import dyvilx.tools.compiler.ast.statement.IfStatement;
import dyvilx.tools.compiler.ast.type.IType;
import dyvilx.tools.compiler.ast.type.builtin.Types;
import dyvilx.tools.compiler.backend.method.MethodWriter;
import dyvilx.tools.compiler.backend.exception.BytecodeException;
import dyvilx.tools.compiler.transform.Names;
import dyvil.lang.Name;
import dyvilx.tools.parsing.marker.MarkerList;
import dyvil.source.position.SourcePosition;

public class InfixCallChain extends OperatorStack<IValue> implements IValue
{
	@Override
	public int valueTag()
	{
		return OPERATOR_CHAIN;
	}

	@Override
	public void setPosition(SourcePosition position)
	{
	}

	@Override
	public SourcePosition getPosition()
	{
		return null;
	}

	@Override
	public boolean isResolved()
	{
		return false;
	}

	@Override
	public IType getType()
	{
		return Types.UNKNOWN;
	}

	@Override
	public void resolveTypes(MarkerList markers, IContext context)
	{
		for (int i = 0; i <= this.operatorCount; i++)
		{
			((IValue) this.operands[i]).resolveTypes(markers, context);
		}

		this.resolveOperators(markers, context);
	}

	@Override
	public IValue resolve(MarkerList markers, IContext context)
	{
		return this.treeify(markers).resolve(markers, context);
	}

	@Override
	protected IValue binaryOp(IValue lhs, OperatorElement operator, IValue rhs)
	{
		final Name name = operator.name;

		if (name == Names.$colon)
		{
			return new ColonOperator(operator.position, lhs, rhs);
		}
		if (name == Names.$eq)
		{
			final IValue assignment = lhs.toAssignment(rhs, operator.position);
			if (assignment != null)
			{
				return assignment;
			}
		}

		return new InfixCall(operator.position, lhs, name, rhs);
	}

	@Override
	protected IValue ternaryOp(IValue lhs, OperatorElement operator1, IValue center, OperatorElement operator2,
		                          IValue rhs)
	{
		if (operator1.name == Names.$qmark && operator2.name == Names.$colon)
		{
			return new IfStatement(lhs, center, rhs);
		}

		return new MethodCall(operator1.position, lhs, operator1.name, new ArgumentList(center, rhs));
	}

	@Override
	public void checkTypes(MarkerList markers, IContext context)
	{
	}

	@Override
	public void check(MarkerList markers, IContext context)
	{
	}

	@Override
	public IValue foldConstants()
	{
		return this;
	}

	@Override
	public IValue cleanup(ICompilableList compilableList, IClassCompilableList classCompilableList)
	{
		return this;
	}

	@Override
	public void writeExpression(MethodWriter writer, IType type) throws BytecodeException
	{
		type.writeDefaultValue(writer);
	}
}


text:
require 'spec_helper'

describe Cassette::Authentication do
  let(:cache) { instance_double(Cassette::Authentication::Cache) }
  let(:http)  { class_double(Cassette) }

  subject do
    Cassette::Authentication.new(cache: cache, http_client: http)
  end

  describe '#ticket_user' do
    context 'when cached' do
      it 'returns the cached value when cached' do
        cached = double('cached')

        expect(cache).to receive(:fetch_authentication) do |ticket, &block|
          expect(ticket).to eql('ticket')
          expect(block).to be_present
          cached
        end

        expect(subject.ticket_user('ticket')).to eql(cached)
      end
    end

    context 'when not cached' do
      before do
        expect(cache).to receive(:fetch_authentication) do |_ticket, &block|
          block.call
        end
      end

      it 'raises a Forbidden exception on any exceptions' do
        allow(http).to receive(:post).with(anything, anything).and_raise(Cassette::Errors::BadRequest)
        expect { subject.ticket_user('ticket') }.to raise_error(Cassette::Errors::Forbidden)
      end

      context 'with a failed CAS response' do
        before do
          allow(http).to receive(:post).with(anything, anything)
            .and_return(OpenStruct.new(body: fixture('cas/fail.xml')))
        end

        it 'returns nil' do
          expect(subject.ticket_user('ticket')).to be_nil
        end
      end

      context 'with a successful CAS response' do
        before do
          allow(http).to receive(:post).with(anything, anything)
            .and_return(OpenStruct.new(body: fixture('cas/success.xml')))
        end

        it 'returns an User' do
          expect(subject.ticket_user('ticket')).to be_instance_of(Cassette::Authentication::User)
        end
      end
    end
  end

  describe '#validate_ticket' do
    it 'raises a authorization required error when no ticket is provided' do
      expect { subject.validate_ticket(nil) }.to raise_error(Cassette::Errors::AuthorizationRequired)
    end

    it 'raises a authorization required error when ticket is blank' do
      expect { subject.validate_ticket('') }.to raise_error(Cassette::Errors::AuthorizationRequired)
    end

    it 'raises a forbidden error when the associated user is not found' do
      expect(subject).to receive(:ticket_user).with('ticket', Cassette.config.service).and_return(nil)
      expect { subject.validate_ticket('ticket') }.to raise_error(Cassette::Errors::Forbidden)
    end

    it 'returns the associated user' do
      user = double('User')
      expect(subject).to receive(:ticket_user).with('ticket', Cassette.config.service).and_return(user)
      expect(subject.validate_ticket('ticket')).to eql(user)
    end
  end
end


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Camping extends CI_Controller{
	public function _construct(){
		parent::_construct();
		$this->load->helper('url');
		$this->load->helper('html');
		}

	public function index(){
		$info = array('title' => 'Cắm Trại');
		$this->load->view('vi/camping', $info);
		}
	}

?>


text:
<link rel="import" href="../bower_components/polymer/polymer.html">

<polymer-element name="my-channel" attributes="min max value channelId display change">
  <template>
    <link href="channel.css" rel="stylesheet">
    {{channelId}}: {{ display }} <input type="range" min="{{min}}" max="{{max}}" value="{{value}}"/> <strong>{{value}}</strong>
  </template>
  <script>
    Polymer("my-channel", {
      valueChanged: function () {
        this.fire('change', { id: this.channelId, value: this.value });
        var bgOffset = (((this.value - this.min) * (this.webkitShadowRoot.children[1].offsetWidth - 0)) / (this.max - this.min)) + 0;
        this.webkitShadowRoot.children[1].style.backgroundImage = "-webkit-linear-gradient(left, #4989d8 0px, #3069ab " + bgOffset+"px, rgba(0,0,0,.25) " + bgOffset+"px, rgba(0,0,0,.25) 16px)";
      }
    });
  </script>
</polymer-element>


text:
    <form class="col s12">

Sign Up

          <input ng-model="firstName" id="firstName" type="text" class="validate">
          First Name

          <input ng-model="lastName" id="lastName" type="text" class="validate">
          Last Name

          <input ng-model="email" id="email" type="email" class="validate">
          Email Address

          <input ng-model="password" id="password" type="password" class="validate">
          Password

          <input ng-model="passwordConfirm" id="reenterpassword" type="password" class="validate">
          Confirm Password

      Register
    </form>


text:
ActiveRecord::Schema.define(:version => 20120308032336) do

  create_table "japanese_local_goverments", :primary_key => "code", :force => true do |t|
    t.string "type",       :limit => 40, :null => false
    t.string "prefecture", :limit => 12, :null => false
    t.string "city",       :limit => 21
    t.string "ward",       :limit => 21
  end

  add_index "japanese_local_goverments", ["code"], :name => "sqlite_autoindex_japanese_local_goverments_1", :unique => true
  add_index "japanese_local_goverments", ["prefecture", "city", "ward"], :name => "sqlite_autoindex_japanese_local_goverments_2", :unique => true

end


text:
"""Read VCF files"""

import sys
import re
import vcf

import cnavg.avg.graph as avg
import breakendGraph

###############################################
## Parsing the chromosome lengths
###############################################

def _parseChromLengths(file):
	res = dict()
	for line in open(file):
		items = line.strip().split()
		res[items[0]] = int(items[1])
	return res

###############################################
## Parsing the VCF file
###############################################

def _parseVCFBreakend(breakends, record):
	if record.FILTER != 'PASS':
		return breakends

	if "SVTYPE" not in record.INFO or record.INFO["SVTYPE"] != "BND":
		return breakends

	assert len(record.ALT) > 0
	assert all(X.reconnects for X in record.ALT)
	breakend = breakendGraph.Breakend(record.CHROM, record.POS, record.ALT[0].orientation, record.ID)
	breakend.remoteChr = [X.chr for X in record.ALT]
	breakend.remotePos = [X.pos for X in record.ALT]
	breakend.remoteOrientation = [X.remoteOrientation for X in record.ALT]
	breakend.adjacency_cov = [ 0 for x in breakend.remoteChr]
	breakend.adjacency_cov.append(0)

	if "MATEID" in record.INFO:
		breakend.mates = record.INFO["MATEID"]
	if "PARID" in record.INFO:
		breakend.partner = record.INFO['PARID']

	assert len(record.samples) > 1

	depths = sampleData[format['BDP']]
	for allele in genotypes:
		breakend.adjacency_cov[genotypes[allele]] += float(depths[allele])

	breakend.segment_cov = int(sampleData[format['DP']])

	breakends[breakend.ID] = breakend
	return breakends

def _parseVCFFile(vcffile):
	return reduce(_parseVCFBreakend, vcf.Reader(open(vcffile)), dict())

########################################################
## Replace name by pointers
########################################################

def _ConsolidateBreakend(breakend, breakends):
	if breakend.partner is not None:
		breakend.partner = breakends[breakend.partner]

	if breakend.mates is not None:
		breakend.mates = map(lambda X: breakends[X], breakend.mates)

def _AlignPointers(breakends):
	map(lambda X: _ConsolidateBreakend(breakends[X], breakends), breakends)

########################################################
## Master function
########################################################

def parse(vcffile, lengthsFile):
	"""Produce breakend graph from VCF file"""
	breakends = _parseVCFFile(vcffile)
	_AlignPointers(breakends)
	graph = breakendGraph.BreakendGraph(sorted(breakends.values()))
	graph.consolidate()
	graph.validate()
	graph.lengths = _parseChromLengths(lengthsFile)
	return graph

########################################################
## Test function
########################################################
def main():
	breakends = parse('../data/test.vcf', '../data/toto.lengths')
	print breakends

if __name__ == "__main__":
	main()


text:
package com.jjoe64.graphview_demos.examples;

import android.graphics.Color;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.LegendRenderer;
import com.jjoe64.graphview.series.BarGraphSeries;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview_demos.FullscreenActivity;
import com.jjoe64.graphview_demos.R;

/**
 * Created by jonas on 10.09.16.
 */
public class SimpleLineGraph extends BaseExample {
    @Override
    public void onCreate(FullscreenActivity activity) {
        GraphView graph = (GraphView) activity.findViewById(R.id.graph);
        initGraph(graph);
    }

    @Override
    public void initGraph(GraphView graph) {
        LineGraphSeries<DataPoint> series = new LineGraphSeries<>(new DataPoint[] {
                new DataPoint(0, 1),
                new DataPoint(1, 5),
                new DataPoint(2, 3),
                new DataPoint(3, 2),
                new DataPoint(4, 6)
        });
        graph.addSeries(series);
    }
}


text:
<?php

use yii\db\Migration;

class m160305_145940_create_user extends Migration
{
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
        $this->execute("
            CREATE TABLE IF NOT EXISTS `evrnt_user` (
              `id` INT NOT NULL AUTO_INCREMENT COMMENT '',
              `username` VARCHAR(128) NOT NULL COMMENT '',
              `name` VARCHAR(45) NOT NULL COMMENT '',
              `surname` VARCHAR(45) NOT NULL COMMENT '',
              `password` VARCHAR(255) NOT NULL COMMENT '',
              `salt` VARCHAR(255) NOT NULL COMMENT '',
              `access_token` VARCHAR(255) NULL DEFAULT NULL COMMENT '',
              `create_date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '',
              PRIMARY KEY (`id`)  COMMENT '',
              UNIQUE INDEX `username_UNIQUE` (`username` ASC)  COMMENT '',
              UNIQUE INDEX `access_token_UNIQUE` (`access_token` ASC)  COMMENT '')
            ENGINE = InnoDB CHARACTER SET UTF8
        ");
    }

    public function safeDown()
    {
        $this->execute("
            DROP TABLE IF EXISTS `evrnt_user`;
        ");
    }
}


text:
'use strict';

var VirtualizedSectionListMethods$ReactNative = require("./VirtualizedSectionListMethods.bs.js");

VirtualizedSectionListMethods$ReactNative.Make({});

/*  Not a pure module */


text:
def create_webmail_users
  return if Webmail::User.where(uid: 'admin').exists?

  g00 = SS::Group.create! name: "シラサギ市", order: 10
  g10 = SS::Group.create! name: "シラサギ市/企画政策部", order: 20
  g11 = SS::Group.create! name: "シラサギ市/企画政策部/政策課", order: 30

  admin_role = create(:webmail_role_admin, name: I18n.t('webmail.roles.admin'))
  user_role = create(:webmail_role_admin, name: I18n.t('webmail.roles.user'))

  adm = Webmail::User.create! name: "webmail-admin", uid: "admin", email: "admin@example.jp", in_password: "pass",
    group_ids: [g11.id], webmail_role_ids: [admin_role.id],
    organization_id: g00.id, organization_uid: "org-admin"
  user = Webmail::User.create! name: "webmail-user", uid: "user", email: "user@example.jp", in_password: "pass",
    group_ids: [g11.id], webmail_role_ids: [user_role.id],
    organization_id: g00.id, organization_uid: "org-user"
  if SS.config.webmail.test_user.present?
    imap = Webmail::User.create! name: "webmail-imap", uid: "imap",
      email: "imap@example.jp", in_password: SS.config.webmail.test_pass || "pass",
      group_ids: [g11.id], webmail_role_ids: [user_role.id],
      organization_id: g00.id, organization_uid: "org-imap"

    conf = SS.config.webmail.test_user || {}

    setting = Webmail::ImapSetting.default
    setting[:imap_host] = conf['host'] || 'localhost'
    setting[:imap_account] = conf['account'] || 'email'
    setting[:in_imap_password] = conf['password'] || 'pass'
    setting.set_imap_password

    imap.imap_settings = Webmail::Extensions::ImapSettings.new([setting])
    imap.save!
  end
end

def webmail_user
  create_webmail_users
  user = Webmail::User.find_by(uid: 'user')
  user.in_password = user.decrypted_password = 'pass'
  user
end

def webmail_imap
  raise "not supported in imap: false" if SS.config.webmail.test_user.blank?

  create_webmail_users
  user = Webmail::User.find_by(uid: 'imap')
  user.in_password = user.decrypted_password = SS.config.webmail.test_pass || 'pass'
  user
end

def webmail_admin
  create_webmail_users
  user = Webmail::User.find_by(uid: 'admin')
  user.in_password = user.decrypted_password = 'pass'
  user
end

def webmail_admin_role
  create_webmail_users
  Webmail::Role.find_by(name: I18n.t('webmail.roles.admin'))
end

def webmail_user_role
  create_webmail_users
  Webmail::Role.find_by(name: I18n.t('webmail.roles.user'))
end

def login_webmail_user
  login_user webmail_user
end

def login_webmail_imap
  raise "not supported in imap: false" if SS.config.webmail.test_user.blank?
  login_user webmail_imap
end

def login_webmail_admin
  login_user webmail_admin
end


text:
Goals
=====

The phpDocumentor project has the following goal:

    *"Provide PHP Developers with all the tools and resources necessary to write
    effective and comprehensive documentation with as little effort possible."*

It tries to achieve this goal by:

* Maintaining the `PHPDoc Standard`_ for describing source code meta-information
  using DocBlocks
* Providing the application `phpDocumentor`_ to

  * Generate API Documentation
  * Create reports on errors in your DocBlocks, deprecated elements and TODOs
  * Generate graphs to help understand how your project is coupled

* Providing the application `Scrybe`_ to

  * Generate Reference Documentation
  * Generate User manuals

* Providing a comprehensive documentation regarding the PHPDoc Standard, how to
  effectively write your source documentation and how each of the applications
  work.
* Providing templates_ to change the look and feel of both phpDocumentor and
  Scrybe.
* Enabling PHP Developers to extend the functionality and/or integrate these
  tools into your own application using plugins.

.. _`PHPDoc Standard`: https://github.com/phpDocumentor/phpDocumentor2/blob/develop/docs/PSR.md
.. _phpDocumentor:     https://github.com/phpDocumentor/phpDocumentor2
.. _Scrybe:            https://github.com/phpDocumentor/Scrybe
.. _templates:         http://www.phpdoc.org/templates


text:
<?php

namespace OFFLINE\SnipcartShop\Classes;

use Cms\Classes\Controller;
use OFFLINE\SnipcartShop\Models\GeneralSettings;
use OFFLINE\SnipcartShop\Models\Product;

class DataAttributes
{
    /**
     * @var Product
     */
    protected $product;

    /**
     * @var Settings
     */
    protected $settings;

    /**
     * @var array
     */
    protected $attributes = [];

    public function __construct(Product $product, GeneralSettings $settings = null)
    {
        $this->product  = $product;
        $this->settings = $settings ?: new GeneralSettings();

        $this->generate();
    }

    public function attributes()
    {
        return $this->attributes;
    }

    protected function generate()
    {
        $this->baseData();
        $this->description();
        $this->image();
        $this->shippingProperties();
        $this->quantities();
        $this->price();
        $this->taxes();
        $this->url();
        $this->customFields();

        return $this->attributes;
    }

    protected function baseData()
    {
        $this->applyAttribute('id');
        $this->applyAttribute('name');
    }

    protected function description()
    {
        $this->setAttribute('description', $this->product->description_short);
    }

    protected function image()
    {
        if ($this->product->image) {
            $this->setAttribute('image', url($this->product->image->getThumb(50, 50, 'crop')));
        }
    }

    protected function shippingProperties()
    {
        $this->applyAttribute('weight');
        $this->applyAttribute('width');
        $this->applyAttribute('length');
        $this->applyAttribute('height');
        $this->setAttribute('shippable', $this->product->shippable ? 'true' : 'false');
    }

    protected function quantities()
    {
        $default = $this->product->quantity_default;
        if ($default !== null) {
            $this->setAttribute('quantity', (int)$default);
        }

        $min = $this->product->quantity_min;
        if ($min !== null) {
            $this->setAttribute('min-quantity', (int)$min);
        }

        $max = $this->product->quantity_max;
        if ($max !== null) {
            $this->setAttribute('max-quantity', (int)$max);
        }
    }

    protected function price()
    {
        $price = $this->product->price;

        if (count($price) === 1) {
            // Single currency
            $price = array_values($price)[0]['price'];
        } else {
            $price = [];
            foreach ($this->product->price as $entry) {
                $price[$entry['currency']] = (float)$entry['price'];
            }
        }

        $this->setAttribute('price', $price);
    }

    protected function taxes()
    {
        $this->setAttribute('taxable', $this->product->taxable ? 'true' : 'false');
    }

    protected function url()
    {
        $controller = new Controller();

        $slug = $this->settings->get('product_page_slug', 'slug');
        // The setting was saved empty (use default)
        if ($slug === '') {
            $slug = 'slug';
        }

        if ( ! $this->settings->get('product_page')) {
            throw new \InvalidArgumentException(
                'SnipcartShop: Please select a product page via the backend settings.'
            );
        }

        $url = $controller->pageUrl(
            $this->settings->get('product_page'),
            [$slug => $this->product->slug]
        );

        $this->setAttribute('url', $url);
    }

    protected function customFields()
    {
        $fields = $this->product->custom_fields()->with('options')->get()->map(function ($field) {
            $key = 'custom' . $field->id;
            $set = [
                $key . '-name'     => $field->name,
                $key . '-required' => $field->required ? 'true' : 'false',
            ];

            if ($field->type === 'textarea') {
                $set[$key . '-type'] = 'textarea';
            }

            if ($options = $field->dataAttributeString) {
                $set[$key . '-options'] = $options;
            }

            return collect($set);
        });

        $fields->each(function ($field) {
            $field->each(function ($value, $name) {
                $this->setAttribute($name, $value);
            });
        });
    }

    /**
     * Copies a attribute of $product into $attributes.
     *
     * @param $attribute
     *
     * @return DataAttributes
     */
    protected function applyAttribute($attribute)
    {
        $value = $this->product->{$attribute};
        if ($value === '' || $value === null) {
            return $this;
        }

        return $this->setAttribute($attribute, $value);
    }

    /**
     * Sets an attribute on the attributes array.
     *
     * @param $name
     * @param $value
     *
     * @return $this
     */
    protected function setAttribute($name, $value)
    {
        $this->attributes[$name] = $value;

        return $this;
    }

    /**
     * Returns the attributes as html string.
     *
     * @return string
     */
    public function __toString()
    {
        $attributes = [];
        foreach ($this->attributes as $key => $value) {
            // Make sure to transform arrays to json and esacpe the
            // output accordingly so we don't mess up the markup
            $value = is_array($value) ? json_encode($value) : e($value);

            $attributes[] = sprintf("data-item-%s='%s'", $key, $value);
        }

        return implode(" ", $attributes);
    }
}


text:
<[options.title]>

  <colgroup>
    <col span="1" style="width: 75%;">
    <col span="1" style="width: 10%;">
    <col span="1" style="width: 15%;">
  </colgroup>

    <[options.column_headers[0]]>
    <[options.column_headers[1]]>
    Addressed specifically?

    <[row.answer]>
    <[row.frequency]>

      Yes
      No


text:
package outboundbot

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// JobGroup is a nested struct in outboundbot response
type JobGroup struct {
	ScriptName           string         `json:"ScriptName" xml:"ScriptName"`
	JobGroupId           string         `json:"JobGroupId" xml:"JobGroupId"`
	ModifyTime           string         `json:"ModifyTime" xml:"ModifyTime"`
	MinConcurrency       int64          `json:"MinConcurrency" xml:"MinConcurrency"`
	JobGroupName         string         `json:"JobGroupName" xml:"JobGroupName"`
	TotalCallNum         int            `json:"TotalCallNum" xml:"TotalCallNum"`
	JobGroupDescription  string         `json:"JobGroupDescription" xml:"JobGroupDescription"`
	Id                   string         `json:"Id" xml:"Id"`
	RingingDuration      int64          `json:"RingingDuration" xml:"RingingDuration"`
	CreationTime         int64          `json:"CreationTime" xml:"CreationTime"`
	Priority             string         `json:"Priority" xml:"Priority"`
	ScenarioId           string         `json:"ScenarioId" xml:"ScenarioId"`
	ScriptVersion        string         `json:"ScriptVersion" xml:"ScriptVersion"`
	ScriptId             string         `json:"ScriptId" xml:"ScriptId"`
	JobDataParsingTaskId string         `json:"JobDataParsingTaskId" xml:"JobDataParsingTaskId"`
	JobFilePath          string         `json:"JobFilePath" xml:"JobFilePath"`
	Status               string         `json:"Status" xml:"Status"`
	CallingNumbers       []string       `json:"CallingNumbers" xml:"CallingNumbers"`
	Progress             Progress       `json:"Progress" xml:"Progress"`
	ExportProgress       ExportProgress `json:"ExportProgress" xml:"ExportProgress"`
	RecallStrategy       RecallStrategy `json:"RecallStrategy" xml:"RecallStrategy"`
	Strategy             Strategy       `json:"Strategy" xml:"Strategy"`
	Result               Result         `json:"Result" xml:"Result"`
}


text:
<template>
    <require from="./elements/build-type-label"></require>

                <build-type-label build-types-grouped-by-label.bind="buildTypesGroupedByLabel"></build-type-label>

</template>


text:
"""
    lantz.ui.qapp
    ~~~~~~~~~~~~

    Example backend and frontend for 2 different applications.

    :copyright: 2015 by Lantz Authors, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""

import time

import numpy as np

# This is a plotting library that we are using. You could also use Matplotlib.
import pyqtgraph as pg

from lantz import Q_

# Import Qt modules from lantz (pyside and pyqt compatible)
from lantz.utils.qt import QtGui, QtCore

# These classes simplify application development
from lantz.ui.app import Frontend, Backend, InstrumentSlot

class AmplitudeScanner(Backend):
    """A simple application that requires a function generator and an
    oscilloscope.
    """

    # Enumerate drivers required by the backend marking them with InstrumentSlot
    fungen = InstrumentSlot
    osci = InstrumentSlot

    def scan_amplitude(self, amplitudes):
        """For each amplitude:
        - scan the amplitude of the function generator.
        - sleeps .3 seconds.
        - measures the trace of the oscilloscope.
        - yields amplitude, data for each amplitude.

        :param amplitudes: iterable of amplitudes.
        """
        for amplitude in amplitudes:
            self.fungen.amplitude = amplitude
            time.sleep(.3)
            data = self.osci.measure()
            yield amplitude, data

    def _scan_amplitude(self, amplitudes):
        """Because scan_amplitude is a generator, this helper functions is used
        to iterate over all the items.
        """
        return list(self.scan_amplitude(amplitudes))

    def default_scan(self):
        """A linear scan from 1 to 19 Volts.
        """
        return list(self.scan_amplitude(Q_(list(range(1, 20)), 'volt')))

class AmplitudeScannerUi(Frontend):
    """A frontend for the AmplitudeScanner backend.

    Provides controls to select the scan range and to start and stop de scanning.
    """

    # a declarative way to indicate the user interface file to use.
    # The file must be located next to the python file where this class
    # is defined.
    gui = 'amplitude_scanner.ui'

    # connect widgets to instruments using connect_setup automatically.
    auto_connect = True

    # amplitudes
    request_start = QtCore.Signal(object)

    def _scan(self):
        start, stop, steps = (getattr(self.widget, name).value()
                              for name in ('start', 'stop', 'steps'))
        amplitudes = Q_(np.linspace(start, stop, steps), 'volt')
        self.request_start.emit(amplitudes)

    def connect_backend(self):

        # This method is called after gui has been loaded (referenced in self.widget)
        # and the backend is connected to the frontend (referenced in self.backend).
        # In this case, we use it to connect the scan button, to the scan method
        # and the request_start signal to the _scan_amplitude
        self.widget.scan_amplitudes.clicked.connect(self._scan)
        self.request_start.connect(self.backend._scan_amplitude)

class AmplitudeScannerShutter(Backend):
    """A complex application that requires a function generator, an
    oscilloscope and a shutter.

    We could subclass AmplitudeScanner, but we have chosen to embed it instead.
    """

    # Enumerate drivers required by the backend marking them with InstrumentSlot
    osci = InstrumentSlot
    fungen = InstrumentSlot
    shutter = InstrumentSlot

    # Embedded apps (Notice we embed the backend, not the Frontend)
    scanner = AmplitudeScanner

    # This signal will be emited when new data is available.
    new_data = QtCore.Signal(object, object)

    def scan_amplitude(self, amplitudes):
        """Open the shutter an then for each amplitude:
        - scan the amplitude of the function generator.
        - sleeps .3 seconds.
        - measures the trace of the oscilloscope.
        - yields amplitude, data for each amplitude.

        Finally, close the shutter.

        :param amplitudes: iterable of amplitudes.
        """
        self.shutter.opened = True

        # We use the embedded app to perform the actual operation.
        # Notice that we have not explicitly instantiated the AmplitudeScanner
        # nor provided the instruments. Lantz has done this in the back
        # connecting InstrumentsSlots by name.
        # i.e. self.osci is self.scanner.osci
        for amplitude, data in self.scanner.scan_amplitude(amplitudes):
            self.new_data.emit(amplitude, data)
            yield amplitude, data

        self.shutter.opened = False

    def _scan_amplitude(self, amplitudes):
        """Because scan_amplitude is a generator, this helper functions is used
        to iterate over all the items.
        """
        return list(self.scan_amplitude(amplitudes))

    def default_scan(self):
        """A linear scan from 1 to 19 Volts.
        """
        return list(self.scan_amplitude(Q_(list(range(1, 20)), 'volt')))

class AmplitudeScannerShutterUi(Frontend):
    """A frontend for the AmplitudeScannerShutter backend.

    Provides controls to select the scan range and to start and stop the scanning.
    """

    # a declarative way to indicate the user interface file to use.
    # The file must be located next to the python file where this class
    # is defined.
    gui = 'scanner_shutter.ui'

    # connect widgets to instruments using connect_setup automatically.
    auto_connect = True

    def setupUi(self):

        # This method is called after gui has been loaded (referenced in self.widget)
        # to customize gui building. In this case, we are adding a plot widget.
        self.pw = pg.PlotWidget()
        self.curve = self.pw.plot(pen='y')
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.pw)
        self.widget.plotParent.setLayout(layout)
        self.scannerUi = AmplitudeScannerUi()

        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.scannerUi.widget)
        self.widget.scanner_widget.setLayout(layout)

    def connect_backend(self):

        # This method is called after gui has been loaded (referenced in self.widget)
        # and the backend is connected to the frontend (referenced in self.backend).
        # In this case, we use it to connect the scan button, to the default_scan
        # method in the backend, and the signal to the plot function.
        self.scannerUi.widget.scan_amplitudes.clicked.connect(self.scannerUi._scan)
        self.scannerUi.request_start.connect(self.backend._scan_amplitude)
        self.backend.new_data.connect(self.plot)

    def plot(self, x, y):
        self.curve.setData(y)


text:
TerraJump
===

This is a repo of TerraJump plugin for TShock