text:
package io.gravitee.gateway.handlers.api.processor.error.templates;

import io.gravitee.common.http.HttpHeaders;
import io.gravitee.common.http.HttpStatusCode;
import io.gravitee.common.http.MediaType;
import io.gravitee.definition.model.ResponseTemplate;
import io.gravitee.gateway.api.ExecutionContext;
import io.gravitee.gateway.api.Request;
import io.gravitee.gateway.api.Response;
import io.gravitee.gateway.api.handler.Handler;
import io.gravitee.gateway.core.processor.ProcessorFailure;
import io.gravitee.reporter.api.http.Metrics;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static org.mockito.Mockito.*;

/**
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author GraviteeSource Team
 */
public class ResponseTemplateBasedFailureProcessorTest {

    private ResponseTemplateBasedFailureProcessor processor;

    @Mock
    private ExecutionContext context;

    @Mock
    private Request request;

    @Mock
    private Response response;

    @Mock
    private HttpHeaders requestHeaders;

    @Mock
    private HttpHeaders responseHeaders;

    @Mock
    private Handler<ExecutionContext> next;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        when(request.metrics()).thenReturn(Metrics.on(System.currentTimeMillis()).build());
        when(request.headers()).thenReturn(requestHeaders);
        when(response.headers()).thenReturn(responseHeaders);
        when(context.request()).thenReturn(request);
        when(context.response()).thenReturn(response);
    }

    @Test
    public void shouldFallbackToDefaultHandler_noProcessorFailureKey() {
        ResponseTemplate template = new ResponseTemplate();
        template.setStatusCode(HttpStatusCode.BAD_REQUEST_400);

        Map<String, ResponseTemplate> mapTemplates = new HashMap<>();
        mapTemplates.put(ResponseTemplateBasedFailureProcessor.WILDCARD_CONTENT_TYPE, template);

        Map<String, Map<String, ResponseTemplate>> templates = new HashMap<>();
        templates.put("POLICY_ERROR_KEY", mapTemplates);

        processor = new ResponseTemplateBasedFailureProcessor(templates);
        processor.handler(next);

        // Set failure
        DummyProcessorFailure failure = new DummyProcessorFailure();
        failure.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500);
        when(context.getAttribute(ExecutionContext.ATTR_PREFIX + "failure")).thenReturn(failure);

        processor.handle(context);

        verify(response, times(1)).status(HttpStatusCode.INTERNAL_SERVER_ERROR_500);
    }

    @Test
    public void shouldFallbackToDefaultHandler_withProcessorFailureKey() {
        ResponseTemplate template = new ResponseTemplate();
        template.setStatusCode(HttpStatusCode.BAD_REQUEST_400);

        Map<String, ResponseTemplate> mapTemplates = new HashMap<>();
        mapTemplates.put(ResponseTemplateBasedFailureProcessor.WILDCARD_CONTENT_TYPE, template);

        Map<String, Map<String, ResponseTemplate>> templates = new HashMap<>();
        templates.put("POLICY_ERROR_KEY", mapTemplates);

        processor = new ResponseTemplateBasedFailureProcessor(templates);
        processor.handler(next);

        // Set failure
        DummyProcessorFailure failure = new DummyProcessorFailure();
        failure.setKey("POLICY_ERROR_KEY");
        failure.setStatusCode(HttpStatusCode.BAD_REQUEST_400);

        when(context.getAttribute(ExecutionContext.ATTR_PREFIX + "failure")).thenReturn(failure);

        processor.handle(context);

        verify(response, times(1)).status(HttpStatusCode.BAD_REQUEST_400);
    }

    @Test
    public void shouldFallbackToDefaultHandler_withProcessorFailureKey_fallbackToDefault() {
        ResponseTemplate template = new ResponseTemplate();
        template.setStatusCode(HttpStatusCode.BAD_REQUEST_400);

        Map<String, ResponseTemplate> mapTemplates = new HashMap<>();
        mapTemplates.put(ResponseTemplateBasedFailureProcessor.WILDCARD_CONTENT_TYPE, template);

        Map<String, Map<String, ResponseTemplate>> templates = new HashMap<>();
        templates.put("DEFAULT", mapTemplates);

        processor = new ResponseTemplateBasedFailureProcessor(templates);
        processor.handler(next);

        // Set failure
        DummyProcessorFailure failure = new DummyProcessorFailure();
        failure.setKey("POLICY_ERROR_KEY");
        failure.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500);

        when(context.getAttribute(ExecutionContext.ATTR_PREFIX + "failure")).thenReturn(failure);

        processor.handle(context);

        verify(response, times(1)).status(HttpStatusCode.BAD_REQUEST_400);
    }

    @Test
    public void shouldFallbackToDefaultHandler_withProcessorFailureKey_unmappedAcceptHeader() {
        ResponseTemplate template = new ResponseTemplate();
        template.setStatusCode(HttpStatusCode.BAD_REQUEST_400);

        Map<String, ResponseTemplate> mapTemplates = new HashMap<>();
        mapTemplates.put(MediaType.APPLICATION_JSON, template);

        Map<String, Map<String, ResponseTemplate>> templates = new HashMap<>();
        templates.put("POLICY_ERROR_KEY", mapTemplates);

        processor = new ResponseTemplateBasedFailureProcessor(templates);
        processor.handler(next);

        // Set failure
        DummyProcessorFailure failure = new DummyProcessorFailure();
        failure.setKey("POLICY_ERROR_KEY");
        failure.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500);

        when(requestHeaders.getAccept()).thenReturn(Collections.singletonList(MediaType.MEDIA_APPLICATION_XML));
        when(context.getAttribute(ExecutionContext.ATTR_PREFIX + "failure")).thenReturn(failure);

        processor.handle(context);

        verify(response, times(1)).status(HttpStatusCode.INTERNAL_SERVER_ERROR_500);
    }

    @Test
    public void shouldFallbackToDefaultHandler_withProcessorFailureKey_unmappedAcceptHeader_fallbackToWildcard() {
        ResponseTemplate template = new ResponseTemplate();
        template.setStatusCode(HttpStatusCode.BAD_REQUEST_400);

        ResponseTemplate wildcardTemplate = new ResponseTemplate();
        wildcardTemplate.setStatusCode(HttpStatusCode.BAD_GATEWAY_502);

        Map<String, ResponseTemplate> mapTemplates = new HashMap<>();
        mapTemplates.put(MediaType.APPLICATION_JSON, template);
        mapTemplates.put(ResponseTemplateBasedFailureProcessor.WILDCARD_CONTENT_TYPE, wildcardTemplate);

        Map<String, Map<String, ResponseTemplate>> templates = new HashMap<>();
        templates.put("POLICY_ERROR_KEY", mapTemplates);

        processor = new ResponseTemplateBasedFailureProcessor(templates);
        processor.handler(next);

        // Set failure
        DummyProcessorFailure failure = new DummyProcessorFailure();
        failure.setKey("POLICY_ERROR_KEY");
        failure.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500);

        when(requestHeaders.getAccept()).thenReturn(Collections.singletonList(MediaType.MEDIA_APPLICATION_XML));
        when(context.getAttribute(ExecutionContext.ATTR_PREFIX + "failure")).thenReturn(failure);

        processor.handle(context);

        verify(response, times(1)).status(HttpStatusCode.BAD_GATEWAY_502);
    }

    @Test
    public void shouldFallbackToDefaultHandler_withProcessorFailureKey_acceptHeader() {
        ResponseTemplate jsonTemplate = new ResponseTemplate();
        jsonTemplate.setStatusCode(HttpStatusCode.BAD_REQUEST_400);

        Map<String, ResponseTemplate> mapTemplates = new HashMap<>();
        mapTemplates.put(MediaType.APPLICATION_JSON, jsonTemplate);

        Map<String, Map<String, ResponseTemplate>> templates = new HashMap<>();
        templates.put("POLICY_ERROR_KEY", mapTemplates);

        processor = new ResponseTemplateBasedFailureProcessor(templates);
        processor.handler(next);

        // Set failure
        DummyProcessorFailure failure = new DummyProcessorFailure();
        failure.setKey("POLICY_ERROR_KEY");
        failure.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500);

        when(requestHeaders.getAccept()).thenReturn(Collections.singletonList(MediaType.MEDIA_APPLICATION_JSON));
        when(context.getAttribute(ExecutionContext.ATTR_PREFIX + "failure")).thenReturn(failure);

        processor.handle(context);

        verify(response, times(1)).status(HttpStatusCode.BAD_REQUEST_400);
    }

    @Test
    public void shouldFallbackToDefaultHandler_withProcessorFailureKey_acceptHeader_fallbackToNextMediaType() {
        ResponseTemplate jsonTemplate = new ResponseTemplate();
        jsonTemplate.setStatusCode(HttpStatusCode.BAD_REQUEST_400);

        Map<String, ResponseTemplate> mapTemplates = new HashMap<>();
        mapTemplates.put(MediaType.APPLICATION_JSON, jsonTemplate);

        Map<String, Map<String, ResponseTemplate>> templates = new HashMap<>();
        templates.put("POLICY_ERROR_KEY", mapTemplates);

        processor = new ResponseTemplateBasedFailureProcessor(templates);
        processor.handler(next);

        // Set failure
        DummyProcessorFailure failure = new DummyProcessorFailure();
        failure.setKey("POLICY_ERROR_KEY");
        failure.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500);

        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.ACCEPT, "text/html, application/json, */*;q=0.8, application/xml;q=0.9");
        when(request.headers()).thenReturn(headers);
        when(context.getAttribute(ExecutionContext.ATTR_PREFIX + "failure")).thenReturn(failure);

        processor.handle(context);

        verify(response, times(1)).status(HttpStatusCode.BAD_REQUEST_400);
    }

    static class DummyProcessorFailure implements ProcessorFailure {

        private int statusCode;
        private String message;
        private String key;
        private Map<String, Object> parameters;
        private String contentType;

        @Override
        public int statusCode() {
            return this.statusCode;
        }

        @Override
        public String message() {
            return this.message;
        }

        @Override
        public String key() {
            return this.key;
        }

        @Override
        public Map<String, Object> parameters() {
            return this.parameters;
        }

        @Override
        public String contentType() {
            return this.contentType;
        }

        public void setStatusCode(int statusCode) {
            this.statusCode = statusCode;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public void setParameters(Map<String, Object> parameters) {
            this.parameters = parameters;
        }

        public void setContentType(String contentType) {
            this.contentType = contentType;
        }
    }
}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * @author Ivan Tcholakov <ivantcholakov@gmail.com>, 2013
 * @license The MIT License, http://opensource.org/licenses/MIT
 *
 * Put this widget within a view in the following way:
 * echo Modules::run('contact_map_widget/index');
 */

class Contact_map_widget_controller extends MY_Controller {

    public function __construct() {

        parent::__construct();

        $this->load
            ->library('settings')
            ->helper('language')
            ->helper('url')
            ->helper('asset')
            ->language('contact')
        ;
    }

    public function _remap() {

        show_404();
    }

    public function index() {

        $data = $this->settings->get(array(
            'contact_map',
        ));

        $this->load->view('contact_map_widget', $data, false, 'i18n');
    }

}

redpajama_set_name: RedPajamaGithub


text:
namespace Fixtures.Azure.AcceptanceTestsLro.Models
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Microsoft.Rest.Azure;

    /// <summary>
    /// Defines headers for deleteAsyncNoHeaderInRetry operation.
    /// </summary>
    public partial class LROsDeleteAsyncNoHeaderInRetryHeaders
    {
        /// <summary>
        /// Initializes a new instance of the
        /// LROsDeleteAsyncNoHeaderInRetryHeaders class.
        /// </summary>
        public LROsDeleteAsyncNoHeaderInRetryHeaders() { }

        /// <summary>
        /// Initializes a new instance of the
        /// LROsDeleteAsyncNoHeaderInRetryHeaders class.
        /// </summary>
        /// <param name="location">Location to poll for result status: will be set to /lro/put/noheader/202/204/operationresults</param>
        public LROsDeleteAsyncNoHeaderInRetryHeaders(string location = default(string))
        {
            Location = location;
        }

        /// <summary>
        /// Gets or sets location to poll for result status: will be set to
        /// /lro/put/noheader/202/204/operationresults
        /// </summary>
        [JsonProperty(PropertyName = "Location")]
        public string Location { get; set; }

    }
}


text:
// The chatlogs retrieval service

var dbname = 'MdbChatLogBot';
var mdbServer = '127.0.0.1:27017';

function error(res, err, callback) {
  res.setHeader('Content-Type', 'application/json');
  console.log('ERROR: ' + err);
  if (err.stack) {
    console.log('Stack: ' + err.stack);
  }
  var json = JSON.stringify({ "error": String(err) });
  if (callback) {
    json = callback + '(' + json + ')';
  }
  res.end(json);
}

function search(res, qstr) {
  var MongoClient = require('mongodb').MongoClient;
  var format = require('util').format;
  var async = require('async');

  var murl = 'mongodb://' + mdbServer + '/' + dbname;
  console.dir('Connecting: ' + murl);
  MongoClient.connect(murl, function(err, db) {
    var callback = qstr['callback'];

    try {
      if (err) throw err;

      if (!qstr['room']) {
        throw 'No room specified';
      }
      var collname = qstr['room'];

      var query = {};
      if (qstr['regexp']) {
        query['message'] = new RegExp(
          qstr['regexp'], qstr['regexpopts']);
      }
      if (qstr['startdt'] && qstr['enddt']) {
        startdt = new Date(Date.parse(qstr['startdt']))
        enddt = new Date(Date.parse(qstr['enddt']));
        query['timestamp'] = { $gte: startdt, $lt: enddt };
      }
      else if (qstr['startdt']) {
        startdt = new Date(Date.parse(qstr['startdt']));
        query['timestamp'] = { $gte: startdt };
      }
      else if (qstr['enddt']) {
        enddt = new Date(Date.parse(qstr['enddt']));
        query['timestamp'] = { $lt: enddt };
      }
      var pretty = qstr['pretty'] && qstr['pretty'] == 1;
      var projection = { timestamp: 1, nick: 1, message: 1, _id: 0 };

      console.dir(query);

      // The timestamp of the most recent entry
      lastq = { '$group': { '_id': '', 'lastdt': { '$max':'$timestamp' }}};

      var coll = db.collection(collname);
      async.parallel({
        'query': function(cb) {
          coll.find(query, projection).sort({ timestamp: 1 }).toArray(cb);
        },
        'latest': function(cb) {
          coll.aggregate(lastq, cb);
        }},
        function(err, results) {
          if (err) {
            error(res, err, callback);
            return;
          }
          console.dir(results);
          if (results.latest.length == 0) {
            error(res, 'Invalid room', callback);
            return;
          }
          var r = {
            'chatlogs': results.query,
            'lastdt': results.latest[0].lastdt
          };
          res.setHeader('Content-Type', 'application/json');
          var json;
          if (pretty) {
            json = JSON.stringify(r, null, 3);
          }
          else {
            json = JSON.stringify(r);
          }
          if (callback) {
            json = callback + '(' + json + ')';
          }
          res.end(json);
          db.close();
        });
    }
    catch (err) {
      error(res, err, callback);
    }
  });
};

function page(res, qstr) {
  var MongoClient = require('mongodb').MongoClient;
  var format = require('util').format;
  var async = require('async');

  var murl = 'mongodb://' + mdbServer + '/' + dbname;
  console.dir('Connecting: ' + murl);
  MongoClient.connect(murl, function(err, db) {
    var callback = qstr['callback'];

    try {
      if (err) throw err;

      if (!qstr['room']) {
        throw 'No room specified';
      }
      var collname = qstr['room'];

      if (!qstr['dt']) {
        throw 'No datetime specified';
      }
      var dt = new Date(Date.parse(qstr['dt']))
      var prevn = 0;
      var nextn = 0;
      if (qstr['prevn']) {
        prevn = parseInt(qstr['prevn']);
      }
      if (qstr['nextn']) {
        nextn = parseInt(qstr['nextn']);
      }
      if (prevn < 1 && nextn < 1) {
        throw 'Either prevn and/or nextn must be >= 1';
      }
      var pretty = qstr['pretty'] && qstr['pretty'] == 1;
      var projection = { timestamp: 1, nick: 1, message: 1, _id: 0 };

      // The timestamp of the most recent entry
      lastq = { '$group': { '_id': '', 'lastdt': { '$max':'$timestamp' }}};

      var coll = db.collection(collname);
      async.parallel({
        'prev': function(cb) {
          if (prevn > 0) {
            coll.find({timestamp: { $lt: dt }}, projection).
              sort({ timestamp: -1 }).limit(prevn).toArray(cb);
          }
          else {
            cb();
          }
        },
        'next': function(cb) {
          if (nextn > 0) {
            coll.find({timestamp: { $gte: dt }}, projection).
              sort({ timestamp: 1 }).limit(nextn).toArray(cb);
          }
          else {
            cb();
          }
        },
        'latest': function(cb) {
          coll.aggregate(lastq, cb);
        }},
        function(err, results) {
          if (err) {
            error(res, err, callback);
            return;
          }
          console.dir(results);
          if (results.latest.length == 0) {
            error(res, 'Invalid room', callback);
            return;
          }
          var r = {
            'prevlogs': results.prev ? results.prev.reverse() : results.prev,
            'nextlogs': results.next
          };
          if (r.prev) {
            r.prev = r.prev.reverse();
          }
          res.setHeader('Content-Type', 'application/json');
          var json;
          if (pretty) {
            json = JSON.stringify(r, null, 3);
          }
          else {
            json = JSON.stringify(r);
          }
          if (callback) {
            json = callback + '(' + json + ')';
          }
          res.end(json);
          db.close();
        });
    }
    catch (err) {
      error(res, err, callback);
    }
  });
};

var Search = function() {
  var handleRequest = function(req, res) {
    var url = require('url');
    var parts = url.parse(req.url, true);
    // Split into components, remove empty elements
    var comps = parts.pathname.split('/').filter(function(x) { return x; });
    var qstr = parts.query;
    try {
      if (comps.length != 2 || comps[0] != 'api') {
        throw 'Invalid API call';
      }
      if (comps[1] == 'search') {
        search(res, qstr);
      }
      else if (comps[1] == 'page') {
        page(res, qstr);
      }
      else {
        throw 'Invalid API call'
      }
    }
    catch (err) {
      error(res, err);
    }
  };

  return {
    handleRequest: handleRequest
  }
}();

module.exports = Search;

/*
var http = require('http');

var app = http.createServer(function(req, res) {
  var url = require('url');
  qstr = url.parse(req.url, true).query;
  try {
    search(res, qstr);
  }
  catch (err) {
    error(res, err);
  }
});
app.listen(18888, '0.0.0.0');
*/
// TODO
//coll.ensureIndex({ timestamp: 1 })

process.on('uncaughtException', function (err) {
  console.log('Caught exception: ' + err);
  if (err.stack) {
    console.log('Stack: ' + err.stack);
  }
});


text:
package com.orientechnologies.orient.etl;

import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.etl.extractor.OAbstractExtractor;

import java.io.Reader;
import java.util.Random;

/**
 * ETL stub  OAbstractExtractor to check the result in tests.
 *
 * @author Luca Garulli on 27/11/14.
 */
public class OETLStubRandomExtractor extends OAbstractExtractor {
  private int  fields;
  private long items;
  private int  delay   = 0;

  @Override
  public void configure(OETLProcessor iProcessor, ODocument iConfiguration, OCommandContext iContext) {
    super.configure(iProcessor, iConfiguration, iContext);

    if (iConfiguration.containsField("items"))
      items = ((Number) iConfiguration.field("items")).longValue();
    if (iConfiguration.containsField("fields"))
      fields = iConfiguration.field("fields");
    if (iConfiguration.containsField("delay"))
      delay = iConfiguration.field("delay");
  }

  @Override
  public void extract(final Reader iReader) {
  }

  @Override
  public String getUnit() {
    return "row";
  }

  @Override
  public boolean hasNext() {
    return current < items;
  }

  @Override
  public OExtractedItem next() {
    final ODocument doc = new ODocument();

    for (int i = 0; i < fields; ++i) {
      doc.field("field" + i, "value_" + new Random().nextInt(30));
    }

    if (delay > 0)
      // SIMULATE A SLOW DOWN
      try {
        Thread.sleep(delay);
      } catch (InterruptedException e) {
      }

    return new OExtractedItem(current++, doc);
  }

  @Override
  public String getName() {
    return "random";
  }
}


text:
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic.hpp>
#include <iostream>
#include <stack>

#include "seqdb.h"

bool parse_file(const char* cs, seq_db &rdb);

struct push_string
{
	push_string(std::stack<std::string>& st) : my_stack(st) { }

	template<typename It> void operator() ( It first, It last) const
	{
		my_stack.push(std::string(first, last));
		//std::cout << "Pushed " << std::string(first, last) << std::endl;
	}

	std::stack<std::string>& my_stack;
};

inline void trim_string(std::string &ss, const char *ch = " \n\t\r\v\f")
{
	std::string::size_type sz = ss.find_last_not_of(ch);
	if(sz != std::string::npos) ss.erase(sz+1);
	sz = ss.find_first_not_of(ch);
	if(sz != std::string::npos) ss.erase(0, sz);
}

inline void sanitize_string(std::string &ss, const char *ch = " \n\t\r\v\f")
{
	std::string::size_type sz = ss.find_first_of(ch);
	while(sz != std::string::npos)
	{
		ss.erase(sz, 1);
		sz = ss.find_first_of(ch, sz);
	}
}

struct pop_sequence
{
	pop_sequence(std::stack<std::string>& st, seq_db& db) : my_stack(st), rdb(db) { }

	template<typename It> void operator() ( It first, It last) const
	{
		std::string seq(my_stack.top());
		my_stack.pop();
		std::string name(my_stack.top());
		my_stack.pop();
		trim_string(name);
		sanitize_string(seq);

		rdb.add(name, seq);
	}

	std::stack<std::string>& my_stack;
	seq_db &rdb;
};

using namespace boost::spirit::classic;

struct seq_grammar : public grammar<seq_grammar>
{
	seq_grammar(std::stack<std::string>& st, seq_db& db ) : string_stack(st), rdb(db) {}

	template <typename ScannerT> struct definition
	{
		definition(seq_grammar const& self)
		{
			file_format =
					(*space_p) >>
					fasta_format
//				|	clustal
//				|	phylip
				;
			fasta_format =
					*fasta_seq
				;
			fasta_seq =
				(	fasta_seq_head
				>>	fasta_seq_body
				)	[pop_sequence(self.string_stack, self.rdb)]
					;
			fasta_seq_head =
					ch_p('>')
				>>	(+(graph_p|blank_p))[push_string(self.string_stack)]
				>>	eol_p
				;
			fasta_seq_body =
					(+(~ch_p('>')))[push_string(self.string_stack)]
				;

		}

		rule<ScannerT> file_format;
		rule<ScannerT> fasta_format;
		rule<ScannerT> fasta_seq;
		rule<ScannerT> fasta_seq_head;
		rule<ScannerT> fasta_seq_body;
		rule<ScannerT> const& start() const { return file_format; }
	};

	std::stack<std::string> &string_stack;
	seq_db &rdb;
};


text:
#ifndef TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED
#define TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED

// Don't #include any Catch headers here - we can assume they are already
// included before this header.
// This is not good practice in general but is necessary in this case so this
// file can be distributed as a single header that works with the main
// Catch single header.

#include <cstring>

#ifdef __clang__
#   pragma clang diagnostic push
#   pragma clang diagnostic ignored "-Wpadded"
#   pragma clang diagnostic ignored "-Wc++98-compat"
#   pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
#endif

namespace Catch {

    struct TeamCityReporter : StreamingReporterBase {
        TeamCityReporter( ReporterConfig const& _config )
        :   StreamingReporterBase( _config ),
            m_headerPrintedForThisSection( false )
        {
            m_reporterPrefs.shouldRedirectStdOut = true;
        }

        static std::string escape( std::string const& str ) {
            std::string escaped = str;
            replaceInPlace( escaped, "|", "||" );
            replaceInPlace( escaped, "'", "|'" );
            replaceInPlace( escaped, "\n", "|n" );
            replaceInPlace( escaped, "\r", "|r" );
            replaceInPlace( escaped, "[", "|[" );
            replaceInPlace( escaped, "]", "|]" );
            return escaped;
        }
        virtual ~TeamCityReporter() CATCH_OVERRIDE;

        static std::string getDescription() {
            return "Reports test results as TeamCity service messages";
        }

        virtual void skipTest( TestCaseInfo const& /* testInfo */ ) CATCH_OVERRIDE {
        }

        virtual void noMatchingTestCases( std::string const& /* spec */ ) CATCH_OVERRIDE {}

        virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE {
            StreamingReporterBase::testGroupStarting( groupInfo );
            stream << "##teamcity[testSuiteStarted name='"
                << escape( groupInfo.name ) << "']\n";
        }
        virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE {
            StreamingReporterBase::testGroupEnded( testGroupStats );
            stream << "##teamcity[testSuiteFinished name='"
                << escape( testGroupStats.groupInfo.name ) << "']\n";
        }

        virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {
        }

        virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE {
            AssertionResult const& result = assertionStats.assertionResult;
            if( !result.isOk() ) {

                std::ostringstream msg;
                if( !m_headerPrintedForThisSection )
                    printSectionHeader( msg );
                m_headerPrintedForThisSection = true;

                msg << result.getSourceInfo() << "\n";

                switch( result.getResultType() ) {
                    case ResultWas::ExpressionFailed:
                        msg << "expression failed";
                        break;
                    case ResultWas::ThrewException:
                        msg << "unexpected exception";
                        break;
                    case ResultWas::FatalErrorCondition:
                        msg << "fatal error condition";
                        break;
                    case ResultWas::DidntThrowException:
                        msg << "no exception was thrown where one was expected";
                        break;
                    case ResultWas::ExplicitFailure:
                        msg << "explicit failure";
                        break;

                    // We shouldn't get here because of the isOk() test
                    case ResultWas::Ok:
                    case ResultWas::Info:
                    case ResultWas::Warning:

                    // These cases are here to prevent compiler warnings
                    case ResultWas::Unknown:
                    case ResultWas::FailureBit:
                    case ResultWas::Exception:
                        CATCH_NOT_IMPLEMENTED;
                }
                if( assertionStats.infoMessages.size() == 1 )
                    msg << " with message:";
                if( assertionStats.infoMessages.size() > 1 )
                    msg << " with messages:";
                for( std::vector<MessageInfo>::const_iterator
                        it = assertionStats.infoMessages.begin(),
                        itEnd = assertionStats.infoMessages.end();
                    it != itEnd;
                    ++it )
                    msg << "\n  \"" << it->message << "\"";

                if( result.hasExpression() ) {
                    msg <<
                        "\n  " << result.getExpressionInMacro() << "\n"
                        "with expansion:\n" <<
                        "  " << result.getExpandedExpression() << "\n";
                }

                if( currentTestCaseInfo->okToFail() ) {
                    msg << "- failure ignore as test marked as 'ok to fail'\n";
                    stream << "##teamcity[testIgnored"
                           << " name='" << escape( currentTestCaseInfo->name )<< "'"
                           << " message='" << escape( msg.str() ) << "'"
                           << "]\n";
                }
                else {
                    stream << "##teamcity[testFailed"
                           << " name='" << escape( currentTestCaseInfo->name )<< "'"
                           << " message='" << escape( msg.str() ) << "'"
                           << "]\n";
                }
            }
            return true;
        }

        virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE {
            m_headerPrintedForThisSection = false;
            StreamingReporterBase::sectionStarting( sectionInfo );
        }

        virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE {
            StreamingReporterBase::testCaseStarting( testInfo );
            stream << "##teamcity[testStarted name='"
                << escape( testInfo.name ) << "']\n";
        }

        virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE {
            StreamingReporterBase::testCaseEnded( testCaseStats );
            if( !testCaseStats.stdOut.empty() )
                stream << "##teamcity[testStdOut name='"
                    << escape( testCaseStats.testInfo.name )
                    << "' out='" << escape( testCaseStats.stdOut ) << "']\n";
            if( !testCaseStats.stdErr.empty() )
                stream << "##teamcity[testStdErr name='"
                    << escape( testCaseStats.testInfo.name )
                    << "' out='" << escape( testCaseStats.stdErr ) << "']\n";
            stream << "##teamcity[testFinished name='"
                << escape( testCaseStats.testInfo.name ) << "']\n";
        }

    private:
        void printSectionHeader( std::ostream& os ) {
            assert( !m_sectionStack.empty() );

            if( m_sectionStack.size() > 1 ) {
                os << getLineOfChars<'-'>() << "\n";

                std::vector<SectionInfo>::const_iterator
                it = m_sectionStack.begin()+1, // Skip first section (test case)
                itEnd = m_sectionStack.end();
                for( ; it != itEnd; ++it )
                    printHeaderString( os, it->name );
                os << getLineOfChars<'-'>() << "\n";
            }

            SourceLineInfo lineInfo = m_sectionStack.front().lineInfo;

            if( !lineInfo.empty() )
                os << lineInfo << "\n";
            os << getLineOfChars<'.'>() << "\n\n";
        }

        // if string has a : in first line will set indent to follow it on
        // subsequent lines
        void printHeaderString( std::ostream& os, std::string const& _string, std::size_t indent = 0 ) {
            std::size_t i = _string.find( ": " );
            if( i != std::string::npos )
                i+=2;
            else
                i = 0;
            os << Text( _string, TextAttributes()
                           .setIndent( indent+i)
                           .setInitialIndent( indent ) ) << "\n";
        }
    private:
        bool m_headerPrintedForThisSection;
    };

#ifdef CATCH_IMPL
    TeamCityReporter::~TeamCityReporter() {}
#endif

    INTERNAL_CATCH_REGISTER_REPORTER( "teamcity", TeamCityReporter )

} // end namespace Catch

#ifdef __clang__
#   pragma clang diagnostic pop
#endif

#endif // TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED


text:
package kilim.analysis;

import kilim.Constants;
import kilim.mirrors.ClassMirror;
import kilim.mirrors.ClassMirrorNotFoundException;
import kilim.mirrors.Detector;
import kilim.mirrors.MethodMirror;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.MethodInsnNode;

/**
 * {@code SAMweaver} generates code to support functional interfaces (also known
 * as SAM, for Single Abstract Method), where the SAM method is pausable. What
 * makes SAM interfaces special compared to regular interfaces is that they can
 * represent a lambda function in java8. More on this later.
 *
 * Imagine that a class called X uses a I of the
 * following form:
 *
 *

 * interface I {
 *     int foo(double d) throws Pausable;
 * }
 *

 *
 * Since I is a SAM, {@code CallWeaver} replaces all
 * invokeinterface I.foo(double) with a static invocation of a tiny
 * wrapper method ('shim') in X like this:
 *
 *

 *      invokestatic X.$shim$2(I callee, double d, Fiber f)
 *

 *
 * The shim method in turn turns around and calls I.foo(double):
 *
 *

 *     private static int X.$shim$2(I callee, double d, Fiber f) {
 *        int ret = callee.f(d, f);
 *        f.setCallee(callee); // this is the purpose of the shim
 *        return ret;
 *     }
 *

 *
 * The purpose of {@code SAMweaver} is to generate the shim above.
 *
 *
Why?

 *

 * Ordinarily, all hand-written code is modified by the weaver if it contains
 * definitions or invocations of pausable methods. Lambda expressions however
 * rely on the VM generating a class at run-time, which implements the
 * functional interface (I in the example). The problem is that
 * this class needs to be woven to support kilim Fibers, but we don't have an
 * easy portable hook to weave it at run-time.
 *

 * As it turns out, practically all the weaving work is already complete at
 * compile time. This is because, the body of the lambda expression is already
 * available to the weaver as an ordinary method in the host class
 * X, and is treated like any another pausable method. In other
 * words, the transformations at the calling site and in the body of the called
 * method are as usual.
 *
 * All that this is left for the shim to do is to capture the object's reference
 * (f.setCallee); the fiber needs it while resuming. The call to
 * setCallee is redundant for ordinary hand-written implementations of SAM
 * interfaces, but is necessary if the implementation happens to be generated by
 * the VM as described above.
 *
 *

 * Of course, all this applies only if the functional method is pausable.
 */

public class SAMweaver implements Constants {
    String  interfaceName;
    String  methodName;
    String  desc;
    boolean itf;
    int     index = -1;

    public SAMweaver(String interfaceName, String methodName, String desc,
            boolean itf) {
        this.interfaceName = interfaceName;
        this.methodName = methodName;
        this.desc = desc;
        this.itf = itf;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public boolean equals(Object obj) {
        if (obj instanceof SAMweaver) {
            SAMweaver that = (SAMweaver) obj;
            return desc.equals(that.desc) && methodName.equals(that.methodName)
                    && interfaceName.equals(that.interfaceName);
        }
        return false;
    }

    public String toString() {
        return interfaceName+"."+methodName+desc + " ->" +getShimMethodName();
    }

    public int hashCode() {
        return methodName.hashCode() ^ desc.hashCode();
    }

    String getShimMethodName() {
        assert index >= 0;
        return "$shim$" + index;
    }

    String getShimDesc() {
        return this.desc.replace("(", "(" + TypeDesc.getInterned(this.interfaceName))
                .replace(")", Constants.D_FIBER_LAST_ARG);
    }

    /**
     * Generate a method like this:
     *
     *

     * private static $shim$1 (I callee, ...args..., f fiber) {
     *    load each arg
     *    call interface.method
     *    f.setCallee(arg0)
     *    xret
     * }
     *

     *
     * @param cv
     */
    public void accept(ClassVisitor cv) {
        String shimDesc = getShimDesc();
        MethodVisitor mv = cv.visitMethod(ACC_STATIC | ACC_PRIVATE, getShimMethodName(), shimDesc, null,
                getExceptions());
        // load arguments
        int ivar = 0;
        for (String argType : TypeDesc.getArgumentTypes(shimDesc)) {
            int vmt = VMType.toVmType(argType);
            mv.visitVarInsn(VMType.loadInsn[vmt], ivar);
            ivar += VMType.category[vmt]; // register width = 2 if double or
                                          // long, 1 otherwise
        }
        int fiberVar = ivar - 1;

        // invoke interface
        String fiberDesc = desc.replace(")", Constants.D_FIBER + ")");
        mv.visitMethodInsn(INVOKEINTERFACE, interfaceName, methodName, fiberDesc);

        // store callee object reference in fiber
        mv.visitVarInsn(ALOAD, fiberVar);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKEVIRTUAL, FIBER_CLASS, "setCallee",
                "(" + D_OBJECT + ")V");

        // return .. RETURN (if void) or ARETURN, IRETURN, etc.
        String retDesc = TypeDesc.getReturnTypeDesc(shimDesc);
        if (retDesc.charAt(0) == 'V') {
            mv.visitInsn(RETURN);
        } else {
            int vmt = VMType.toVmType(retDesc);
            mv.visitInsn(VMType.retInsn[vmt]);
        }
        mv.visitMaxs(0, 0); // maxLocals and maxStackDepth will be computed by asm's MethodWriter
        mv.visitEnd();
    }

    private String[] getExceptions() {
        try {
            ClassMirror cm = Detector.getDetector().classForName(interfaceName);
            for (MethodMirror m : cm.getDeclaredMethods()) {
                if (m.getName().equals(this.methodName)
                        && m.getMethodDescriptor().equals(this.desc)) {
                    // Convert dots to slashes.
                    String[] ret = m.getExceptionTypes();
                    if (ret != null) {
                        for (int i = 0; i < ret.length; i++) {
                            ret[i] = ret[i].replace('.', '/');
                        }
                        return ret;
                    }
                    break;
                }
            }
        } catch (ClassMirrorNotFoundException cmnfe) {
        }

        // Should not happen at this stage. If this class weren't found, it
        // would have created a
        // problem much earlier on.
        assert false : "Class Mirror not found for interface " + interfaceName;
        return new String[0];
    }
}


text:
{% extends "notification/base.html" %}

{% load i18n %}

{% block head_title %}{% trans "Notification Settings" %}{% endblock %}

{% block body %}

{% trans "Notification Settings" %}

        {% url acct_email as email_url %}
        {% if user.email %}

                {% trans "Primary email" %}:

                {{ user.email }}

                ({% blocktrans %}change under Account{% endblocktrans %})

        {% else %}

                {% trans "Note" %}:
                {% blocktrans %}You do not have a verified email address to which notices can be sent. You can add one by going to Account.{% endblocktrans %}

        {% endif %}

        <form method="POST" action=""> {# doubt this easy to do in uni-form #}
            {% csrf_token %}

                    {% trans "Notification Type" %}
                    {% for header in notice_settings.column_headers %}
                        {{ header }}
                    {% endfor %}

                {% for row in notice_settings.rows %}

                        {% trans row.notice_type.display %}

                            {% trans row.notice_type.description %}

                        {% for cell in row.cells %}

                                <input type="checkbox" name="{{ cell.0 }}" {% if cell.1 %}checked="yes"{% endif %}/>

                        {% endfor %}

                {% endfor %}

                    <input type="submit" value="{% trans "Change" %}" />

        </form>

{% endblock %}


text: .. include:: ../../en/api/csvtools.rst


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Logara.Models;
using System.Diagnostics;

namespace Logara.Controllers
{
    public class HomeController : Controller
    {
        // go home
        public ActionResult Index() {
            return View();
        }

        // get all logs
        public JsonResult GetAllLogs() {
            using (LogaraDBContext contextObj = new LogaraDBContext()) {
                var logList = contextObj.log.ToList(); // dobavlja logove u listu
                return Json(logList, JsonRequestBehavior.AllowGet);
            }
        }

        // get log by ID
        public JsonResult GetLogByID(string ID) {
            using (LogaraDBContext contextObj = new LogaraDBContext()) {
                var logID = Convert.ToInt32(ID);
                var getLogByID = contextObj.log.Find(logID);
                return Json(getLogByID, JsonRequestBehavior.AllowGet);
            }
        }

        // update log
        public string UpdateLog(Log log) {
            if (log != null) {
                using (LogaraDBContext contextObj = new LogaraDBContext()) {
                    int logID = Convert.ToInt32(log.ID);
                    Log _log = contextObj.log.Where(b => b.ID == logID).FirstOrDefault();
                    System.Diagnostics.Debug.Write("DATE:" + log.START);
                    _log.START = log.START;
                    _log.STOP = log.STOP;
                    _log.NOTE = log.NOTE;
                    contextObj.SaveChanges();
                    return "Log record updated";
                }
            }
            else {
                return "Invalid log record";
            }
        }

        // add log
        public string AddLog(Log log) {
            if (log != null) {
                using (LogaraDBContext contextObj = new LogaraDBContext()) {
                    contextObj.log.Add(log);
                    contextObj.SaveChanges();
                    return "Log record added";
                }
            }
            else {
                return "Invalid log record";
            }
        }

        // delete log
        public string DeleteLog(string logID) {

            if (!String.IsNullOrEmpty(logID)) {
                try {
                    int _logID = Int32.Parse(logID);
                    using (LogaraDBContext contextObj = new LogaraDBContext()) {
                        var _log = contextObj.log.Find(_logID);
                        contextObj.log.Remove(_log);
                        contextObj.SaveChanges();
                        return "Selected log record deleted";
                    }
                }
                catch (Exception) {
                    return "Log details not found";
                }
            }
            else {
                return "Invalid operation";
            }
        }
    }
}


text:
module DocumentsHelper
  # Convert plain text to HTML by cwaddingAdd <p> tags around paragraphs
  def to_html(text)
    return '' if text.blank?
    text.split("\n").collect { |p| "<p>#{p}</p>"}.join("\n").html_safe
  end

  def document_path(document)
    document.is_a?(Document) ? document.permalink : super(document)
  end
end


text:
import html from 'ui/timepicker/timepicker.html';
import _ from 'lodash';
import dateMath from '@elastic/datemath';
import moment from 'moment';
import Notifier from 'ui/notify/notifier';
import 'ui/timepicker/timepicker.less';
import 'ui/directives/input_datetime';
import 'ui/directives/inequality';
import 'ui/timepicker/quick_ranges';
import 'ui/timepicker/refresh_intervals';
import 'ui/timepicker/time_units';
import 'ui/timepicker/kbn_global_timepicker';
import uiModules from 'ui/modules';
let module = uiModules.get('ui/timepicker');
let notify = new Notifier({
  location: 'timepicker',
});

module.directive('kbnTimepicker', function (quickRanges, timeUnits, refreshIntervals) {
  return {
    restrict: 'E',
    scope: {
      from: '=',
      to: '=',
      mode: '=',
      interval: '=',
      activeTab: '='
    },
    template: html,
    controller: function ($scope) {
      $scope.format = 'MMMM Do YYYY, HH:mm:ss.SSS';
      $scope.modes = ['quick', 'relative', 'absolute'];
      $scope.activeTab = $scope.activeTab || 'filter';

      if (_.isUndefined($scope.mode)) $scope.mode = 'quick';

      $scope.quickLists = _(quickRanges).groupBy('section').values().value();
      $scope.refreshLists = _(refreshIntervals).groupBy('section').values().value();

      $scope.relative = {
        count: 1,
        unit: 'm',
        preview: undefined,
        round: false
      };

      $scope.absolute = {
        from: moment(),
        to: moment()
      };

      $scope.units = timeUnits;

      $scope.relativeOptions = [
        {text: 'Seconds ago', value: 's'},
        {text: 'Minutes ago', value: 'm'},
        {text: 'Hours ago', value: 'h'},
        {text: 'Days ago', value: 'd'},
        {text: 'Weeks ago', value: 'w'},
        {text: 'Months ago', value: 'M'},
        {text: 'Years ago', value: 'y'},
      ];

      $scope.$watch('from', function (date) {
        if (moment.isMoment(date) && $scope.mode === 'absolute') {
          $scope.absolute.from = date;
        }
      });

      $scope.$watch('to', function (date) {
        if (moment.isMoment(date) && $scope.mode === 'absolute') {
          $scope.absolute.to = date;
        }
      });

      $scope.$watch('absolute.from', function (date) {
        if (_.isDate(date)) $scope.absolute.from = moment(date);
      });

      $scope.$watch('absolute.to', function (date) {
        if (_.isDate(date)) $scope.absolute.to = moment(date);
      });

      $scope.setMode = function (thisMode) {
        switch (thisMode) {
          case 'quick':
            break;
          case 'relative':
            let fromParts = $scope.from.toString().split('-');
            let relativeParts = [];

            // Try to parse the relative time, if we can't use moment duration to guestimate
            if ($scope.to.toString() === 'now' && fromParts[0] === 'now' && fromParts[1]) {
              relativeParts = fromParts[1].match(/([0-9]+)([smhdwMy]).*/);
            }
            if (relativeParts[1] && relativeParts[2]) {
              $scope.relative.count = parseInt(relativeParts[1], 10);
              $scope.relative.unit = relativeParts[2];
            } else {
              let duration = moment.duration(moment().diff(dateMath.parse($scope.from)));
              let units = _.pluck(_.clone($scope.relativeOptions).reverse(), 'value');
              if ($scope.from.toString().split('/')[1]) $scope.relative.round = true;
              for (let i = 0; i < units.length; i++) {
                let as = duration.as(units[i]);
                if (as > 1) {
                  $scope.relative.count = Math.round(as);
                  $scope.relative.unit = units[i];
                  break;
                }
              }
            }

            if ($scope.from.toString().split('/')[1]) $scope.relative.round = true;
            $scope.formatRelative();

            break;
          case 'absolute':
            $scope.absolute.from = dateMath.parse($scope.from || moment().subtract(15, 'minutes'));
            $scope.absolute.to = dateMath.parse($scope.to || moment(), true);
            break;
        }

        $scope.mode = thisMode;
      };

      $scope.setQuick = function (from, to) {
        $scope.from = from;
        $scope.to = to;
      };

      $scope.setToNow = function () {
        $scope.absolute.to = moment();
      };

      $scope.formatRelative = function () {
        let parsed = dateMath.parse(getRelativeString());
        $scope.relative.preview =  parsed ? parsed.format($scope.format) : undefined;
        return parsed;
      };

      $scope.applyRelative = function () {
        $scope.from = getRelativeString();
        $scope.to = 'now';
      };

      function getRelativeString() {
        return 'now-' + $scope.relative.count + $scope.relative.unit + ($scope.relative.round ? '/' + $scope.relative.unit : '');
      }

      $scope.applyAbsolute = function () {
        $scope.from = moment($scope.absolute.from);
        $scope.to = moment($scope.absolute.to);
      };

      $scope.setRefreshInterval = function (interval) {
        interval = _.clone(interval || {});
        notify.log('before: ' + interval.pause);
        interval.pause = (interval.pause == null || interval.pause === false) ? false : true;

        notify.log('after: ' + interval.pause);

        $scope.interval = interval;
      };

      $scope.setMode($scope.mode);
    }
  };
});


text:
from geoscript.util import deprecated
from geoscript.style import util
from geoscript.style.expression import Expression
from geoscript.style.font import Font
from geoscript.style.fill import Fill
from geoscript.style.halo import Halo
from geoscript.style.color import Color
from geoscript.style.icon import Icon
from geoscript.style.property import Property
from geoscript.style.symbolizer import Symbolizer
from org.geotools.styling import TextSymbolizer

class Label(Symbolizer):
  """
  Symbolizer for labelling a geometry.

  The ``property`` argument specifies the field or attribute with which to generate labels from.

  The ``font`` and ``color`` arguments specify the label font and color
  respectively.

  >>> Label('foo')
  Label(property=foo)
  """

  def __init__(self, property, font=None, color=None, priority=None,
               options=None):
    Symbolizer.__init__(self)
    self.property = Property(property)
    self.color = Color(color) if color else None
    self.priority = Property(priority) if priority else None
    self.options = options if options else {}
    self._font = Font(font) if font else None
    self._halo = None
    self._icon = None
    self._placement = None

  def font(self, font):
    """
    Sets the font for this label. The ``font`` argument is a string describing the
    font attributes. See :class:`Font <geoscript.style.font.Font>` for supported
    syntax.

    >>> label = Label('foo').font('italic bold 12px "Times New Roman"')
    """

    self._font = Font(font)
    return self

  def halo(self, fill=None, radius=None):
    """
    Generates a halo for this label.

    The ``fill`` and ``radius`` arguments specify the :class:`Fill` and radius to
    use for the halo.

    >>> from geoscript.style import Fill
    >>> label = Label('foo').halo(Fill('#ffffff'), 2)
    """
    self._halo = Halo(fill, radius)
    return self

  def point(self, anchor=(0.5,0.5), displace=(0,0), rotate=0):
    """
    Sets the label placement relative to a point.

    The ``anchor`` argument is a tuple that specifies how the label should be
    anchored along an xy axis relative to the geometry being labeled. Allowable
    values range from (0,0) to (1,1) ordered from the bottom left corner to the top
    right corner of the label.

    The ``displacement`` argument is a tuple that specifies how the label should be
    displaced along an xy axis.

    The ``rotate`` argument specifies in degrees the angle at which to rotate the
    label.

    >>> label = Label('foo').point((0.5,0), (0,5))
    """
    self._placement = self._pointPlacement(anchor, displace, rotate)
    return self

  def icon(self, url, format=None, size=None):
    """
    Composes this label as an :class:`Icon <geoscript.style.icon.Icon>`.

    The ``url`` argument is the url/file containing the image. The ``format`` argument
    is the format or mime type of the image.
    """
    self._icon = Icon(url, format, size)
    return self

  @deprecated
  def linear(self, offset=0, gap=None, igap=None, align=False, follow=False,
             group=False, displace=None, repeat=None):
    """Use :func:`geoscript.style.Label.line`"""

    return self.line(offset, gap, igap, align, follow, group, displace, repeat)

  def line(self, offset=0, gap=None, igap=None, align=False, follow=False,
             group=False, displace=None, repeat=None):
    """
    Sets the label placement relative to a line.

    The ``offset`` argument specifies the perpindicular distance from the line at
    which to position the label.

    The ``align`` argument specifies whether to align the label along the line. The
    ``follow`` argument specifies whether to curve the label in order to force it
    to follow the line.

    >>> label = Label('foo').linear(align=True, follow=True)
    """
    f = self.factory
    lp = f.createLinePlacement(Expression(offset).expr)
    lp.setAligned(align)
    #lp.setRepeated(repeat)
    if gap:
      lp.setGap(Expression(gap).expr)
    if igap:
      lp.setInitialGap(Expression(igap).expr)
    self._placement = lp

    self.options['followLine'] = follow
    self.options['group'] = group
    if displace:
      self.options['maxDisplacement'] = displace
    if repeat:
      self.options['repeat'] = repeat
    return self

  def polygon(self, anchor=(0.5,0.5), displace=(0,0), rotate=0, wrap=None):
    self._placement = self._pointPlacement(anchor, displace, rotate)
    if wrap:
      self.options['autoWrap'] = wrap
    return self

  def _pointPlacement(self, anchor, displace, rotate):
    f = self.factory
    ap = f.createAnchorPoint(
      Expression(anchor[0]).expr,Expression(anchor[1]).expr)
    dp = f.createDisplacement(
      Expression(displace[0]).expr, Expression(displace[1]).expr)
    return f.createPointPlacement(ap, dp, Expression(rotate).expr)

  def _prepare(self, rule):
    syms = util.symbolizers(rule, TextSymbolizer)
    for sym in syms:
      self._apply(sym)

  def _apply(self, sym):
    Symbolizer._apply(self, sym)
    sym.setLabel(self.property.expr)

    if self._font:
      self._font._apply(sym)
    if self._halo:
      self._halo._apply(sym)
    if self._icon:
      self._icon._apply(sym)

    if self.color:
      sym.setFill(Fill(self.color)._fill())

    if self.priority:
      sym.setPriority(self.priority.expr)

    if self._placement:
      sym.setLabelPlacement(self._placement)
    else:
      sym.setLabelPlacement(None)

  def __repr__(self):
    return self._repr('property')


text:
A little library to help with animating lines and circles with the HTML canvas API.

An example of some stuff you can do with it: https://tbaldw.in/map

```
var Drawer = require('drawer');
var drawer = new Drawer(document.querySelector('.container'));

drawer.circle([150, 150], 25, Math.PI * 0.5, 2000, '#333333').then(function() {
    console.log('I just drew a circle!');
});
```

`Drawer`'s constructor takes a DOM Element which it uses as a container for a
canvas element it creates. The canvas dimensions are set to the height and width
of the container. The canvas resolution is doubled to support retina screens. All
values passed to the `Drawer`'s methods take care of doubling the values to fit
the resolution.

## Instance properties

### drawer.canvas
The canvas the instance renders to.

### drawer.ctx
The canvas' 2D rendering context.

## Instance methods

### drawer.circle(center, radius, startAngle, duration, color, width=1)
The `circle` method requires `center`, `radius`, `startAngle`, `duration`, and
`color`. `center` is a 2-element array of integers marking the center of the
circle. `radius` is an integer. `startAngle` is a float between `0` and
`Math.PI * 2`. `duration` is an integer indicating the duration of the animation
in milliseconds. `color` is a string representing the color of the line. And
`width` is an optional argument used for setting the line thickness. The default
`width` is `1`.

(This should probably also take `endAngle`, an optional easing method, and an
optional `counterclockwise` flag.)

### drawer.line(start, end, duration, color, width=1)
The `line` method requires `start`, `end`, `duration`, and `color`. `start` is a
2-element array of integers marking the starting point of the line. `end` is a
2-element array of integers marking the ending point of the line. `duration` is
an integer indicating the duration of the animation in milliseconds. `color` is
a string representing the color of the line. And `width` is an optional argument
used for setting the line thickness. The default `width` is `1`.

(This should probably also take an optional easing method.)

### drawer.arc(arc, duration, color, width=1)
The `arc` method might be a bit of a misnomer. It borrows its name from the
TopoJSON spec and refers to a multi-point line. The method requires `arc`,
`duration`, and `color`. `arc` is an array of points, each of which is a 2-
element array defining the coordinates for the point. `duration` is an integer
indicating the duration of the animation in milliseconds. `color` is a string
representing the color of the line. And `width` is an optional argument used for
setting the line thickness. The default `width` is `1`.

(This should probably also take an optional easing method.)

### drawer.clear()
Takes no arguments and simply clears the canvas.

### drawer.stop()
Takes no arguments and simply stops all animation. Note: currently, the
animation promises do not get resolved or rejected, and the canvas does not get
cleared.


text:
package com.banco.domain;

public class Cliente {
	private String nombre;
	private String apellido;
	private Cuenta cuenta;

	public Cliente(String nombre, String apellido) {
		super();
		this.nombre = nombre;
		this.apellido = apellido;
	}

	public String getNombre() {
		return nombre;
	}

	public void setNombre(String nombre) {
		this.nombre = nombre;
	}

	public String getApellido() {
		return apellido;
	}

	public void setApellido(String apellido) {
		this.apellido = apellido;
	}

	public Cuenta getCuenta() {
		return cuenta;
	}

	public void setCuenta(Cuenta cuenta) {
		this.cuenta = cuenta;
	}

	@Override
	public String toString() {
		return "Cliente [nombre=" + nombre + ", apellido=" + apellido
				+ ", cuenta=" + cuenta + "]";
	}

}


text:
/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version. See also the license.txt file for *
 *   additional informations.                                              *
 *                                                                         *
 ***************************************************************************/

//*************************************************************************//
// History of changes:
//
// 2004/04/04 - Pete
// - changed plugin to emulate PS2 spu
//
// 2002/05/15 - Pete
// - generic cleanup for the Peops release
//
//*************************************************************************//

void SetupTimer(void);
void RemoveTimer(void);
EXPORT_GCC void CALLBACK SPU2playADPCMchannel(xa_decode_t *xap);

EXPORT_GCC long CALLBACK SPU2init(void);
EXPORT_GCC long CALLBACK SPU2open(void *pDsp);
EXPORT_GCC void CALLBACK SPU2async(unsigned long cycle);
EXPORT_GCC void CALLBACK SPU2close(void);


text:
require_relative 'helper'

class TestCheersIntegration < MiniTest::Unit::TestCase

  def test_no_input_help_message
    output = `./cheers`
    expected = <<EOS
I'd cheer for you, if only I knew who you were :(
Try again with `./cheers.rb [Name] [MM/DD Birthday]`
EOS
    assert_equal expected, output
  end

  def test_one_valid_name
    output = `./cheers Abby`
    expected = <<EOS
Give me an... A
Give me a... B
Give me a... B
Give me a... Y
Abby's just GRAND!

I would wish you a Happy Birthday, if I knew when that was!
EOS
    #expected.chomp!
    assert_equal expected, output
  end

  def test_one_valid_name_with_hyphen
    output = `./cheers Abby-Sue`
    expected = <<EOS
Give me an... A
Give me a... B
Give me a... B
Give me a... Y
Give me an... S
Give me a... U
Give me an... E
Abby-Sue's just GRAND!

I would wish you a Happy Birthday, if I knew when that was!
EOS
    assert_equal expected, output
  end

  def test_one_valid_name_with_space
    output = `./cheers "Abby Sue"`
    expected = <<EOS
Give me an... A
Give me a... B
Give me a... B
Give me a... Y
Give me an... S
Give me a... U
Give me an... E
Abby Sue's just GRAND!

I would wish you a Happy Birthday, if I knew when that was!
EOS
    assert_equal expected, output
  end

  def test_one_valid_birthday
    output = `./cheers 03/15`
    expected = <<EOS
I'd cheer for you, if only I knew who you were :(
Try again with `./cheers.rb [Name] [MM/DD Birthday]`
EOS

    assert_equal expected, output
  end

  def test_one_arg_all_non_word_characters
    output = `./cheers $@^@`
    expected = <<EOS
I'd cheer for you, if only I knew who you were :(
Try again with `./cheers.rb [Name] [MM/DD Birthday]`
EOS

    assert_equal expected, output
  end

  def test_one_arg_empty_string
    output = `./cheers ""`
    expected = <<EOS
I'd cheer for you, if only I knew who you were :(
Try again with `./cheers.rb [Name] [MM/DD Birthday]`
EOS

    assert_equal expected, output
  end

  def test_one_arg_empty_string_with_whitespace
    output = `./cheers " "`
    expected = <<EOS
I'd cheer for you, if only I knew who you were :(
Try again with `./cheers.rb [Name] [MM/DD Birthday]`
EOS

    assert_equal expected, output
  end

  def test_valid_name_mmyy_birthday
    output = `./cheers Abby 08/25`
    expected = <<EOS
Give me an... A
Give me a... B
Give me a... B
Give me a... Y
Abby's just GRAND!

Awesome! Your birthday is in 125 days! Happy Birthday in advance!
EOS
    assert_equal expected, output
  end

  def test_two_invalid_arguments
    output = `./cheers 2344 afsae`
    expected = <<EOS
I'd cheer for you, if only I knew who you were :(
Try again with `./cheers.rb [Name] [MM/DD Birthday]`
EOS

    assert_equal expected, output
  end

  def test_two_args_valid_name_invalid_birthday
    output = `./cheers Luke @/23a`
    expected = <<EOS
I'd cheer for you, if only I knew who you were :(
Try again with `./cheers.rb [Name] [MM/DD Birthday]`
EOS
    assert_equal expected, output
  end

  def test_two_args_invalid_name_valid_birthday
    output = `./cheers #25 12/23`
    expected = <<EOS
I'd cheer for you, if only I knew who you were :(
Try again with `./cheers.rb [Name] [MM/DD Birthday]`
EOS

    assert_equal expected, output
  end

  def test_myy_birthday
    output = `./cheers Abby 8/25`
    expected = <<EOS
Give me an... A
Give me a... B
Give me a... B
Give me a... Y
Abby's just GRAND!

Awesome! Your birthday is in 125 days! Happy Birthday in advance!
EOS
    assert_equal expected, output
  end

  def test_birthday_already_passed
    output = `./cheers Abby 3/25`
    expected = <<EOS
Give me an... A
Give me a... B
Give me a... B
Give me a... Y
Abby's just GRAND!

Awesome! Your birthday was 28 days ago! Happy belated birthday!
EOS
    assert_equal expected, output
  end

  def test_birthday_instead_of_name
    output = `./cheers 3/35 3/25`
    expected = <<EOS
I'd cheer for you, if only I knew who you were :(
Try again with `./cheers.rb [Name] [MM/DD Birthday]`
EOS
    assert_equal expected, output
  end

  def test_invalid_date_ddmm
    output = `./cheers Abby 15/03`
    expected = <<EOS
I'd cheer for you, if only I knew who you were :(
Try again with `./cheers.rb [Name] [MM/DD Birthday]`
EOS
    assert_equal expected, output
  end

  def test_invalid_date
    output = `./cheers Abby 15/55`
    expected = <<EOS
I'd cheer for you, if only I knew who you were :(
Try again with `./cheers.rb [Name] [MM/DD Birthday]`
EOS
    assert_equal expected, output
  end

  def test_invalid_date_ddmmyy
    output = `./cheers Abby 15/03/1987`
    expected = <<EOS
I'd cheer for you, if only I knew who you were :(
Try again with `./cheers.rb [Name] [MM/DD Birthday]`
EOS
    assert_equal expected, output
  end

  def test_ignore_more_than_two_arguments
    output = `./cheers Abby 12/12 Joe`
    expected = <<EOS
Give me an... A
Give me a... B
Give me a... B
Give me a... Y
Abby's just GRAND!

Awesome! Your birthday is in 234 days! Happy Birthday in advance!
EOS
    assert_equal expected, output
  end
end


text:
require_relative 'spec_helper'

describe HashParams do
  let(:v) { HashParams }

  it 'raises error if required and missing' do
    proc {
      v.validate(nil, nil, required: true)
    }.must_raise HashParams::Validator::ValidationError
  end

  it 'runs multiple coersions' do
    v.validate('1aaa2', Float, coerce: [lambda { |o| o.gsub('a', '') }, :to_i]).must_equal(12.0)
  end

  it 'defaults missing values' do
    v.validate(nil, Integer, default: 1).must_equal(1)
    v.validate(nil, Integer, default: lambda { 2 * 5 }).must_equal(10)
  end

  it 'validates with lambdas' do
    v.validate(nil, Integer, :validate => lambda { |v| v = 60 * 60 }).must_equal(60 * 60)
  end

  it 'validates with procs' do
    v.validate('is_this_valid?', String) do |v|
      v = 'Validated with Proc'
    end.must_equal('Validated with Proc')
  end

  it 'verifies numbers with common params' do
    v.validate(122, Integer, min: 120, max: 500, in: (100..200), is: 122).must_equal(122)
  end

  it 'verifies strings with common params' do
    v.validate('this is a test string', String, min_length: 21, max_length: 30, format: /^t.*g$/).must_equal 'this is a test string'
  end

  it 'coerces true' do
    v.validate('t', :boolean).must_equal true
    v.validate('true', :boolean).must_equal true
    v.validate('yes', :boolean).must_equal true
    v.validate('1', :boolean).must_equal true
    v.validate(1, :boolean).must_equal true
  end

  it 'coerces false' do
    v.validate('f', :boolean).must_equal false
    v.validate('false', :boolean).must_equal false
    v.validate('no', :boolean).must_equal false
    v.validate('0', :boolean).must_equal false
    v.validate(0, :boolean).must_equal false
  end

  it 'coerces array' do
    v.validate('1|2|3', Array, delimiter: '|').must_equal ["1", "2", "3"]
  end

  it 'coerces hash' do
    v.validate('{a => 1,b => 2,c => d}', Hash, delimiter: ',', separator: '=>').must_equal({"a" => "1", "b" => "2", "c" => "d"})
  end

  it 'validates a hash using a block' do
    h = {
        ignored:           "this will be ignored because it's not mentioned",
        to_be_renamed:     :renamed_value,
        'integer_coercion': "1",
        proc_validation:   "is_this_valid?",
        recursive:         {}
    }
    r = v.validate(h, Hash, symbolize_keys: true) do
      key :doesnt_exist, nil, required: true
      key :to_be_renamed, Symbol, as: :renamed
      #Default Lambdas take no parameters
      key :proc_default, Integer, default: lambda { 1 * 5 }
      key :proc_validation, String, validate: lambda { |v| v = 'Validated in proc' }
      #recursive
      key :recursive, Hash do
        key :wasnt_here_before, :boolean, default: true
      end
    end

    (r.valid?).must_equal false
    r[:ignored].must_be_nil
    # r[:proc_default].must_equal 5
    r[:renamed].must_equal :renamed_value
    #recursive checking
    r[:recursive][:wasnt_here_before].must_equal true

    #failed items don't show up
    r[:doesnt_exist].must_be_nil
    r[:proc_validation].must_equal 'Validated in proc'

    r.validation_errors.size.must_equal 1
    r.validation_errors[0].must_equal "Error processing key 'doesnt_exist': Required Parameter missing and has no default specified"

  end

  it 'validates variables in the local binding' do

    x='10'
    y='this is a test string'
    z={}
    will_be_int='100'

    HashParams.with_binding do
      var :x, Integer, min: 10, max: 100
      var :y, String, min_length: 21, max_length: 30, format: /^t.*g$/
      var :z, Hash, raise_errors: true, symbolize_keys: true, make_methods: true do
        key :blah, String, default: 1
      end
      var :will_be_int, :to_i
    end
    x.must_equal 10
    y.must_equal 'this is a test string'
    z[:blah].must_equal '1'
    z.blah.must_equal '1'
    will_be_int.must_equal 100
  end

end


text:
name: "📃 Documentation Bug"
about: You want to report something that is wrong or missing from the documentation.
title: 'Docs:'
labels: 'Type: Docs'

---


text:
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>DocsByReflection</name>
    </assembly>
    <members>
        <member name="T:DocsByReflection.DocsService">
            <summary>
            Utility class to provide documentation for various types where available with the assembly
            </summary>
        </member>
        <member name="F:DocsByReflection.DocsService.s_cache">
            <summary>
            A cache used to remember Xml documentation for assemblies
            </summary>
        </member>
        <member name="F:DocsByReflection.DocsService.s_failCache">
            <summary>
            A cache used to store failure exceptions for assembly lookups
            </summary>
        </member>
        <member name="M:DocsByReflection.DocsService.GetXmlFromMember(System.Reflection.MethodBase,System.Boolean)">
            <summary>
            Provides the documentation comments for a specific method
            </summary>
            <param name="method">The MethodInfo (reflection data ) of the member to find documentation for</param>
            <param name="throwError">If should throw error when documentation is not found. Default is true.</param>
            <returns>The XML fragment describing the method</returns>
        </member>
        <member name="M:DocsByReflection.DocsService.GetXmlFromMember(System.Reflection.MemberInfo,System.Boolean)">
            <summary>
            Provides the documentation comments for a specific member.
            </summary>
            <param name="member">The MemberInfo (reflection data) or the member to find documentation for</param>
            <param name="throwError">If should throw error when documentation is not found. Default is true.</param>
            <returns>The XML fragment describing the member</returns>
        </member>
        <member name="M:DocsByReflection.DocsService.GetXmlFromParameter(System.Reflection.ParameterInfo,System.Boolean)">
            <summary>
            Provides the documentation comments for a specific parameter.
            </summary>
            <param name="parameter">The ParameterInfo (reflection data) to find documentation for.</param>
            <param name="throwError">If should throw error when documentation is not found. Default is true.</param>
            <returns>The XML fragment describing the paramter.</returns>
        </member>
        <member name="M:DocsByReflection.DocsService.GetXmlFromType(System.Type,System.Boolean)">
            <summary>
            Provides the documentation comments for a specific type
            </summary>
            <param name="type">Type to find the documentation for</param>
            <param name="throwError">If should throw error when documentation is not found. Default is true.</param>
            <returns>The XML fragment that describes the type</returns>
        </member>
        <member name="M:DocsByReflection.DocsService.GetXmlFromAssembly(System.Reflection.Assembly,System.Boolean)">
            <summary>
            Obtains the documentation file for the specified assembly
            </summary>
            <param name="assembly">The assembly to find the XML document for</param>
            <param name="throwError">If should throw error when documentation is not found. Default is true.</param>
            <returns>The XML document</returns>
            <remarks>This version uses a cache to preserve the assemblies, so that
            the XML file is not loaded and parsed on every single lookup</remarks>
        </member>
        <member name="M:DocsByReflection.DocsService.GetXmlFromName(System.Type,System.Char,System.String,System.Boolean)">
            <summary>
            Obtains the XML Element that describes a reflection element by searching the
            members for a member that has a name that describes the element.
            </summary>
            <param name="type">The type or parent type, used to fetch the assembly</param>
            <param name="prefix">The prefix as seen in the name attribute in the documentation XML</param>
            <param name="name">Where relevant, the full name qualifier for the element</param>
            <param name="throwError">If should throw error when documentation is not found. Default is true.</param>
            <returns>The member that has a name that describes the specified reflection element</returns>
        </member>
        <member name="M:DocsByReflection.DocsService.GetXmlFromAssemblyNonCached(System.Reflection.Assembly)">
            <summary>
            Loads and parses the documentation file for the specified assembly
            </summary>
            <param name="assembly">The assembly to find the XML document for</param>
            <returns>The XML document</returns>
        </member>
        <member name="M:DocsByReflection.DocsService.GetTypeFullNameForXmlDoc(System.Type,System.Boolean)">
            <summary>
            Gets the type's full name prepared for xml documentation format.
            </summary>
            <param name="type">The type.</param>
            <param name="isMethodParameter">If the type is being used has a method parameter.</param>
            <returns>The full name.</returns>
        </member>
        <member name="T:DocsByReflection.DocsByReflectionException">
            <summary>
            An exception thrown by the DocsByReflection library
            </summary>
        </member>
        <member name="M:DocsByReflection.DocsByReflectionException.#ctor">
            <summary>
            Initializes a new <see cref="T:DocsByReflection.DocsByReflectionException"/> class.
            </summary>
        </member>
        <member name="M:DocsByReflection.DocsByReflectionException.#ctor(System.String)">
            <summary>
            Initializes a new <see cref="T:DocsByReflection.DocsByReflectionException"/> class.
            </summary>
            <param name="message">The error message that explains the reason for the exception.</param>
        </member>
        <member name="M:DocsByReflection.DocsByReflectionException.#ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)">
            <summary>
            Initializes a new <see cref="T:DocsByReflection.DocsByReflectionException"/> class.
            </summary>
            <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
            <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
            <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> parameter is null. </exception>
            <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0). </exception>
        </member>
        <member name="M:DocsByReflection.DocsByReflectionException.#ctor(System.String,System.Exception)">
            <summary>
            Initializes a new exception instance with the specified
            error message and a reference to the inner exception that is the cause of
            this exception.
            </summary>
            <param name="message">The error message that explains the reason for the exception.</param>
            <param name="innerException">The exception that is the cause of the current exception, or null if none.</param>
        </member>
        <member name="T:DocsByReflection.PathHelper">
            <summary>
            Internal path helper.
            </summary>
        </member>
        <member name="M:DocsByReflection.PathHelper.GetAssemblyDocFileNameFromCodeBase(System.String)">
            <summary>
            Gets the assembly document file name from code base.
            </summary>
            <returns>The assembly document file name from code base.</returns>
            <param name="assemblyCodeBase">Assemby code base.</param>
        </member>
    </members>
</doc>


text:
$(function() {
    var $collectionHolder;

    $collectionHolder = $('.contacts');

    $collectionHolder.data('index', $collectionHolder.find(':input').length);

    $(document).on('click', '.btn-add', function (e) {
        e.preventDefault();

        // Get the data-prototype explained earlier
        var prototype = $collectionHolder.data('prototype');

        // get the new index
        var index = $collectionHolder.data('index');

        // Replace '__name__' in the prototype's HTML to
        // instead be a number based on how many items we have
        var newForm = prototype.replace(/__name__/g, index);

        // increase the index with one for the next item
        $collectionHolder.data('index', index + 1);

        var controlForm = $('.controls form .contacts:first'),
            currentEntry = $(this).parents('.entry:first'),
            newEntry = $(newForm).appendTo(controlForm);

        newEntry.find('input').val('');
        controlForm.find('.entry:not(:last) .btn-add')
            .removeClass('btn-add').addClass('btn-remove')
            .removeClass('btn-success').addClass('btn-danger')
            .html('');

    }).on('click', '.btn-remove', function (e) {
        $(this).parents('.entry:first').remove();

        e.preventDefault();
        return false;
    });

});


text:
#include "internal/abstract-rendering-api_private.hpp"

namespace skland {
namespace gui {

AbstractRenderingAPI::AbstractRenderingAPI() {

}

AbstractRenderingAPI::~AbstractRenderingAPI() {
  destroyed_.Emit();
}

void AbstractRenderingAPI::Setup(Surface *surface) {
  if (surface->p_->rendering_api == this) return;

  if (nullptr != surface->p_->rendering_api) {
    AbstractRenderingAPI *orig = surface->p_->rendering_api;
    surface->p_->rendering_api = nullptr;
    orig->OnRelease(surface);
  }

  surface->p_->rendering_api = this;

  OnSetup(surface);
}

void AbstractRenderingAPI::Release(Surface *surface) {
  if (surface->p_->rendering_api != this) return;

  surface->p_->rendering_api = nullptr;
  OnRelease(surface);
}

} // namespace gui
} // namespace skland


text:
package mimir.algebra;

import org.specs2.specification._

import mimir.algebra._
import mimir.util._
import mimir.test._

object SamplingSpec
  extends SQLTestSpecification("Sampling")
  with BeforeAll
{
  def beforeAll =
  {
    loadCSV(
      targetTable = "DATA",
      sourceFile = "test/data/Bestbuy_raw.csv",
      detectHeaders = true
    )
  }

  "The Mimir Sampler" >> {

    "draw uniform samples correctly" >> {

      val query = db.table("DATA")
          .sampleUniformly(0.1, seed = Some(42l))
          .count()

      val count =
        db.query(query) { result =>
          val row = result.next()
          row(ID("COUNT")).asLong.toInt
        }

      // 345 rows in the input file.  10% sampling rate ~= 34-35 rows.
      count should beCloseTo(34, 10)

      val recount =
        db.query(query) { result =>
          val row = result.next()
          row(ID("COUNT")).asLong.toInt
        }

      // With an identical seed, the sample sets should be IDENTICAL
      recount must be equalTo(count)

    }

    "draw stratified samples correctly" >> {

      val stratificationColumn = "MANUFACTURER"
      schemaLookup("DATA").map { _._1 } must contain(ID(stratificationColumn))

      val query = db.table("DATA")
        .stratifiedSample(
          stratificationColumn,
          TInt(),
          Map(
            IntPrimitive(0) -> 1.0,
            IntPrimitive(1) -> 0.1
          ),
          seed = Some(42l)
        )
        .groupBy(Var(ID(stratificationColumn)))(
          AggFunction(ID("count"), false, Seq(), ID("COUNT"))
        )

      val counts =
        db.query(query) { result =>
          result.map { row =>
            row(ID("MANUFACTURER")).asLong.toInt ->
              row(ID("COUNT")).asLong.toInt
          }.toIndexedSeq.toMap
        }

      // All unspecified strata must be empty
      counts.size must be equalTo(2)
      // 33 rows have a manufacturer of '0'
      counts(0) must be equalTo(33)
      // 77 rows have a manufacturer of '1' (@10% ~= 8)
      counts(1) must beCloseTo(8, 4)

    }

    "create named samples" >> {

      update("CREATE SAMPLE VIEW sample FROM data WITH FRACTION 0.5;")
      update("CREATE SAMPLE VIEW stratified FROM data WITH STRATIFIED ON manufacturer (0 ~ 1.0, 1 ~ 0.1);")
      update("CREATE OR REPLACE SAMPLE VIEW sample FROM data WITH FRACTION 0.1;")

      val count =
        db.query(db.table("SAMPLE").count()) { result =>
          val row = result.next()
          row(ID("COUNT")).asLong.toInt
        }
      // 345 rows in the input file.  10% sampling rate ~= 34-35 rows.
      count should beCloseTo(34, 10)
    }
  }
}


text:
<!DOCTYPE html >

          <title></title>
          <meta name="description" content="" />
          <meta name="keywords" content="" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../lib/ref-index.css" media="screen" type="text/css" rel="stylesheet" />

BLACK

RGBColor

BORDER_BOTTOM_DEFAULT

VisualizationConfig

BORDER_LEFT_DEFAULT

VisualizationConfig

BORDER_RIGHT_DEFAULT

VisualizationConfig PieChartConfig

BORDER_TOP_DEFAULT

VisualizationConfig PieChartConfig

BOTTOM

PositionType

BarChart

BarChartConfig

BarChartConfig

barChart

BarElement

visualizations

BigDecimalColumn

dsl

BigIntColumn

dsl

BlobColumn

dsl

BlueColorScheme

util

BoolEncodable

visualizations

BooleanColumn

dsl

Border

param

ByteStringColumn

dsl

barChart

visualizations

blue

RGBColor

border

VisualizationConfig

borderJsonFormat

DataJsonProtocol

bottom

Border OptBorder

bottomToTop

VerticalAxis

boundaryHigh

Resolution

boundaryLow

Resolution

byCluster

Clustering


text:
import {ITEMS_PER_PAGE, NUM_PAGE_BUTTONS} from './AppSettings.js'

class PageBatch {
    constructor(pagesInBatch, itemPerPage) {
        this.pagesInBatch = pagesInBatch || NUM_PAGE_BUTTONS;
        this.itemPerPage = itemPerPage || ITEMS_PER_PAGE;
        this.pageToItems = {}
        this.hasMore = false;
    }

    clearData() {
        this.pageToItems = {}
        this.hasMore = false;
    }

    setItems(batchPageNum, items, hasMore) {
        this.hasMore = hasMore;
        this.pageToItems = {}
        let pageNum = (batchPageNum - 1)* this.pagesInBatch;
        for (let i = 0; i < this.pagesInBatch; i++) {
            let idx = (i * this.itemPerPage);
            let endIdx = idx + this.itemPerPage;
            pageNum += 1;
            let pageItems = [];
            if (endIdx >= items.length) {
                pageItems = items.slice(idx)
            } else {
                pageItems = items.slice(idx, endIdx)
            }
            this.pageToItems[pageNum] = pageItems;
        }
    }

    getItems(pageNum) {
        return this.pageToItems[pageNum];
    }

    hasPage(pageNum) {
        return pageNum in this.pageToItems;
    }

    isPageEmpty(pageNum) {
        return this.getItems(pageNum).length == 0;
    }

    getBatchPageNum(page) {
        if (page == -1) {
            return page;
        }
        return parseInt((page - 1)/ this.pagesInBatch) + 1;
    }

    getItemsPerBatch() {
        return this.pagesInBatch * this.itemPerPage;
    }

    getPageNums() {
        return Object.keys(this.pageToItems);
    }

    getStartPage() {
        return this.getPageNums()[0];
    }

    getEndPage() {
        let pageNums = this.getPageNums();
        let lastPage = pageNums[0];
        for (let i = 1; i < pageNums.length; i++) {
            let somePage = pageNums[i];
            if (!this.isPageEmpty(somePage)) {
                lastPage = somePage;
            }
        }
        return lastPage;
    }

    canNext(page) {
        if (page == -1) {
            return false;
        }
        let nextPage = page + 1;
        if (this.hasPage(nextPage + 1)) {
            if (this.isPageEmpty(nextPage)) {
                return false;
            } else {
                return true;
            }
        } else {
            return this.hasMore;
        }
    }

    getStartAndEndPages(page) {
        let numPages = this.pagesInBatch;
        let startPage = parseInt((page - 1)/ numPages) * numPages + 1;
        let endPage = startPage + numPages - 1;
        return {
            startPage: startPage,
            endPage: endPage
        }
    }
}

export default PageBatch;


text:
package tutorial.colorchooser_demo2;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.colorchooser.*;

/* Used by ColorChooserDemo2.java. */
public class CrayonPanel extends AbstractColorChooserPanel
                         implements ActionListener {
    JToggleButton redCrayon;
    JToggleButton yellowCrayon;
    JToggleButton greenCrayon;
    JToggleButton blueCrayon;

    public void updateChooser() {
        Color color = getColorFromModel();
        if (Color.red.equals(color)) {
            redCrayon.setSelected(true);
        } else if (Color.yellow.equals(color)) {
            yellowCrayon.setSelected(true);
        } else if (Color.green.equals(color)) {
            greenCrayon.setSelected(true);
        } else if (Color.blue.equals(color)) {
            blueCrayon.setSelected(true);
        }
    }

    protected JToggleButton createCrayon(String name,
                                         Border normalBorder) {
        JToggleButton crayon = new JToggleButton();
        crayon.setActionCommand(name);
        crayon.addActionListener(this);

        //Set the image or, if that's invalid, equivalent text.
        ImageIcon icon = createImageIcon("images/" + name + ".gif");
        if (icon != null) {
            crayon.setIcon(icon);
            crayon.setToolTipText("The " + name + " crayon");
            crayon.setBorder(normalBorder);
        } else {
            crayon.setText("Image not found. This is the "
                           + name + " button.");
            crayon.setFont(crayon.getFont().deriveFont(Font.ITALIC));
            crayon.setHorizontalAlignment(JButton.HORIZONTAL);
            crayon.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        }

        return crayon;
    }

    protected void buildChooser() {
        setLayout(new GridLayout(0, 1));

        ButtonGroup boxOfCrayons = new ButtonGroup();
        Border border = BorderFactory.createEmptyBorder(4,4,4,4);

        redCrayon = createCrayon("red", border);
        boxOfCrayons.add(redCrayon);
        add(redCrayon);

        yellowCrayon = createCrayon("yellow", border);
        boxOfCrayons.add(yellowCrayon);
        add(yellowCrayon);

        greenCrayon = createCrayon("green", border);
        boxOfCrayons.add(greenCrayon);
        add(greenCrayon);

        blueCrayon = createCrayon("blue", border);
        boxOfCrayons.add(blueCrayon);
        add(blueCrayon);
    }

    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = CrayonPanel.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

    public void actionPerformed(ActionEvent e) {
        Color newColor = null;
        String command = ((JToggleButton)e.getSource()).getActionCommand();
        if ("green".equals(command))
            newColor = Color.green;
        else if ("red".equals(command))
            newColor = Color.red;
        else if ("yellow".equals(command))
            newColor = Color.yellow;
        else if ("blue".equals(command))
            newColor = Color.blue;
        getColorSelectionModel().setSelectedColor(newColor);
    }

    public String getDisplayName() {
        return "Crayons";
    }

    public Icon getSmallDisplayIcon() {
        return null;
    }

    public Icon getLargeDisplayIcon() {
        return null;
    }
}


text:
Customizing Grids
=================

.. note::

    We assume that you are familiar with grids. If not check the documentation of the :doc:`Grid Bundle </bundles/SyliusGridBundle/index>`
    and :doc:`Grid Component </components/Grid/index>` first.

Why would you customize grids?
------------------------------

When you would like to change how the index view of an entity looks like in the administration panel,
then you have to override its grid.

* remove a field from a grid
* change a field of a grid
* reorder fields
* override an entire grid

How to customize grids?
-----------------------

.. tip::

    One way to change anything in any grid in **Sylius** is to create a special file in the ``app/config/`` directory:
    ``app/config/grids.yml`` which has to be imported in the ``app/config/config.yml``.

.. code-block:: yaml

    # app/config/config.yml
    imports:
        - { resource: "grids.yml" }

How to customize fields of a grid?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

How to remove a field from a grid?
''''''''''''''''''''''''''''''''''

If you would like to remove a field from an existing Sylius grid, you will need to disable it in the ``app/config/grids.yml``.

Let's imagine that we would like to hide the **title of product review** field on the ``sylius_admin_product_review`` grid.

.. code-block:: yaml

    # app/config/grids.yml
    sylius_grid:
        grids:
            sylius_admin_product_review:
                fields:
                    title:
                        enabled: false

That's all. Now the ``title`` field will be disabled (invisible).

How to modify a field of a grid?
''''''''''''''''''''''''''''''''

If you would like to modify for instance a label of any field from a grid, that's what you need to do:

.. code-block:: yaml

    # app/config/grids.yml
    sylius_grid:
        grids:
            sylius_admin_product_review:
                fields:
                    date:
                        label: "When was it added?"

How to customize filters of a grid?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

How to remove a filter from a grid?
'''''''''''''''''''''''''''''''''''

If you would like to remove a filter from an existing Sylius grid, you will need to disable it in the ``app/config/grids.yml``.

Let's imagine that we would like to hide the **titles filter of product reviews** on the ``sylius_admin_product_review`` grid.

.. code-block:: yaml

    # app/config/grids.yml
    sylius_grid:
        grids:
            sylius_admin_product_review:
                filters:
                    title:
                        enabled: false

That's all. Now the ``title`` filter will be disabled.

How to customize actions of a grid?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

How to remove an action from a grid?
''''''''''''''''''''''''''''''''''''

If you would like to disable some actions in any grid, you just need to set its ``enabled`` option to ``false`` like below:

.. code-block:: yaml

    # app/config/grids.yml
    sylius_grid:
        grids:
            sylius_admin_product_review:
                actions:
                    item:
                        delete:
                            type: delete
                            enabled: false

How to modify an action of a grid?
''''''''''''''''''''''''''''''''''

If you would like to change the link to which an action button is redirecting, this is what you have to do:

.. warning::

    The ``show`` button does not exist in the ``sylius_admin_product`` grid by default.
    It is assumed that you already have it customized, and your grid has the ``show`` action.

.. code-block:: yaml

    # app/config/grids.yml
    sylius_grid:
        grids:
            sylius_admin_product:
                actions:
                    item:
                        show:
                            type: show
                            label: Show in the shop
                            options:
                                link:
                                    route: sylius_shop_product_show
                                    parameters:
                                        slug: resource.slug

The above grid modification will change the redirect of the ``show`` action to redirect to the shop, instead of admin show.
Also the label was changed here.

How to modify positions of fields, filters and actions in a grid?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For fields, filters and actions it is possible to easily change the order in which they are displayed in the grid.

See an example of fields order modification on the ``sylius_admin_product_review`` grid below:

.. code-block:: yaml

    # app/config/grids.yml
    sylius_grid:
        grids:
            sylius_admin_product_review:
                fields:
                    date:
                        position: 5
                    title:
                        position: 6
                    rating:
                        position: 3
                    status:
                        position: 1
                    reviewSubject:
                        position: 2
                    author:
                        position: 4

Customizing grids by events
---------------------------

There is also another way to customize grids: **via events**.
Every grid configuration dispatches an event when its definition is being converted.

For example, **sylius_admin_product** grid dispatches such an event:

.. code-block:: php

    sylius.grid.admin_product # For the grid of products in admin

To show you an example of a grid customization using events, we will remove a field from a grid using that method.
Here are the steps, that you need to take:

**1.** In order to remove fields from the product grid in **Sylius** you have to create a ``AppBundle\Grid\AdminProductsGridListener`` class.

In the example below we are removing the ``images`` field from the ``sylius_admin_product`` grid.

.. code-block:: php

    <?php

    namespace AppBundle\Grid;

    use Sylius\Component\Grid\Event\GridDefinitionConverterEvent;

    final class AdminProductsGridListener
    {
        /**
         * @param GridDefinitionConverterEvent $event
         */
        public function removeImageField(GridDefinitionConverterEvent $event)
        {
            $grid = $event->getGrid();

            $grid->removeField('image');
        }
    }

**2.** After creating your class with a proper method for the grid customizations you need, subscribe your
listener to the ``sylius.grid.admin_product`` event in the ``AppBundle/Resources/config/services.yml``.

.. code-block:: yaml

    # AppBundle/Resources/config/services.yml
    services:
        app.listener.admin.products_grid:
            class: AppBundle\Grid\AdminProductsGridListener
            tags:
                - { name: kernel.event_listener, event: sylius.grid.admin_product, method: removeImageField }

**3.** Result:

After these two steps your admin product grid should not have the image field.

How to override an entire grid?
-------------------------------

.. tip::

    This is the other way to customize grids. If you need to change more, than just slight adjustments we do recommend
    to override an entire grid file in the ``app/Resources/`` directory.

Let's assume that you would like to modify the ``shipping_categories`` grid by removing filters and the delete action from it.

* To achieve that you need to create the ``app/Resources/SyliusAdminBundle/config/grids/shipping_category.yml`` file.

* Then into the created file copy the content of ``Sylius/Bundle/AdminBundle/Resources/config/grids/shipping_category.yml``.

* And modify it to your needs:

.. code-block:: yaml

    # app/Resources/SyliusAdminBundle/config/grids/shipping_category.yml
    sylius_grid:
        grids:
            sylius_admin_shipping_category:
                driver:
                    name: doctrine/orm
                    options:
                        class: "%sylius.model.shipping_category.class%"
                        repository:
                            method: createListQueryBuilder
                fields:
                    code:
                        type: string
                        label: sylius.ui.code
                    name:
                        type: string
                        label: sylius.ui.name
                    createdAt:
                        type: datetime
                        label: sylius.ui.creation_date
                        options:
                            format: d-m-Y H:i
                    updatedAt:
                        type: datetime
                        label: sylius.ui.updating_date
                        options:
                            format: d-m-Y H:i
                actions:
                    main:
                        create:
                            type: create
                    item:
                        update:
                            type: update

In the above example the ``delete`` action and the filters section have been removed.

* That's it! The grid has been modified and it will look like that:

.. image:: ../_images/overriding_grids.png
    :align: center

Learn more
----------

* :doc:`Grid - Component Documentation </components/Grid/index>`
* :doc:`Grid - Bundle Documentation </bundles/SyliusGridBundle/index>`


text:
@lombok.Builder @lombok.Value
public class Test {
	String hello;
	int world;
}