text:
package org.hisp.dhis.webapi.webdomain.form;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import org.hisp.dhis.common.DxfNamespaces;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
@JacksonXmlRootElement( localName = "form", namespace = DxfNamespaces.DXF_2_0 )
public class Form
{
    private String label;

    private String subtitle;

    private List<Group> groups = new ArrayList<>();

    private Map<String, Object> options = new HashMap<>();

    public Form()
    {
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getLabel()
    {
        return label;
    }

    public void setLabel( String label )
    {
        this.label = label;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getSubtitle()
    {
        return subtitle;
    }

    public void setSubtitle( String subtitle )
    {
        this.subtitle = subtitle;
    }

    @JsonProperty( value = "groups" )
    @JacksonXmlElementWrapper( localName = "groups", namespace = DxfNamespaces.DXF_2_0 )
    @JacksonXmlProperty( localName = "group", namespace = DxfNamespaces.DXF_2_0 )
    public List<Group> getGroups()
    {
        return groups;
    }

    public void setGroups( List<Group> groups )
    {
        this.groups = groups;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public Map<String, Object> getOptions()
    {
        return options;
    }

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

    @Override
    public String toString()
    {
        return "Form{" +
            "label='" + label + '\'' +
            ", groups=" + groups +
            '}';
    }
}


text:
module Autoparts
  module Packages
    class Leiningen < Package
      name 'leiningen'
      version '2.5.0'
      description 'Leiningen: A build automation and dependency management tool for Clojure'
      category Category::PROGRAMMING_LANGUAGES

      source_url 'https://github.com/technomancy/leiningen/releases/download/2.5.0/leiningen-2.5.0-standalone.jar'
      source_sha1 '7514d137f0f4ff226c0171df47a3422b1ecfa80a'
      source_filetype 'jar'

      def install
        prefix_path.mkpath
        execute 'mv', archive_filename, prefix_path

        puts "=> Downloading the lein script..."
        download 'https://raw.github.com/technomancy/leiningen/2.5.0/bin/lein-pkg', tmp_lein_script_path, '70853aaf12735e6b468f42e0a119f9991c73cfe6'

        bin_path.mkpath
        execute 'mv', tmp_lein_script_path, lein_executable_path
        execute 'chmod', '0755', lein_executable_path
      end

      def post_install
        execute 'sed', '-i', "s|^LEIN_JAR=.*\.jar|LEIN_JAR=#{prefix_path}/leiningen-#{version}.jar|g", lein_executable_path
      end

      def tmp_lein_script_path
        Path.tmp + "lein-pkg"
      end

      def lein_executable_path
        bin_path + "lein"
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
#include "Token.h"
#include "misc/IntervalSet.h"

#include "atn/SetTransition.h"

using namespace antlr4;
using namespace antlr4::atn;

SetTransition::SetTransition(ATNState *target, const misc::IntervalSet &aSet)
  : Transition(target), set(aSet.isEmpty() ? misc::IntervalSet::of(Token::INVALID_TYPE) : aSet) {
}

Transition::SerializationType SetTransition::getSerializationType() const {
  return SET;
}

misc::IntervalSet SetTransition::label() const {
  return set;
}

bool SetTransition::matches(size_t symbol, size_t /*minVocabSymbol*/, size_t /*maxVocabSymbol*/) const {
  return set.contains(symbol);
}

std::string SetTransition::toString() const {
  return "SET " + Transition::toString() + " { set: " + set.toString() + "}";
}


text:
require 'spec/spec_helper'

describe NoHeroku do
  before(:each) do
    @app = Object.new
    @middleware = NoHeroku.new(@app)
  end

  describe "call" do
    it "should redirect to non heroku domain" do
      env = {'HTTP_HOST' => 'draw.heroku.com'}
      url = "http://#{env['HTTP_HOST']}/test?param"
      rack_request = Object.new
      rack_request.should_receive(:url).and_return(url)
      Rack::Request.should_receive(:new).with(env).and_return(rack_request)

      @middleware.call(env).should == [301, { 'Location' => 'http://drawbang.com/test?param' }, ['Redirecting...']]
    end

    it "should execute call on @app if no www is found" do
      env = {'HTTP_HOST' => 'example.com'}

      @app.should_receive(:call).with(env)

      @middleware.call(env)
    end
  end
end


text:
function initializeAjaxForm(successMessage, messageHolderSelector) {
    $("#reviewForm").submit(function(e) {
        e.preventDefault();
        var form = $(this);

        $.ajax({
            type: "POST",
            url: form.attr('action'),
            data: parseFormToJson(form),
            dataType: "json",
            accept: "application/json",
            success: function(data, textStatus, xhr) {
                completeRequest(form);
                appendFlash(successMessage, messageHolderSelector);
            },
            error: function(xhr, textStatus, errorThrown) {
                renderErrors(xhr, form);
            }
        });
    });
}

function renderErrors(xhr, form) {
    clearErrors(form);

    $.each(xhr.responseJSON.errors.errors, function(key, value) {
        $('div.panel-body').addClass('has-error').prepend('' + value + '');
    });
}

function clearErrors(form) {
    form.find('.form-error').remove();
    form.find('.has-error').removeClass('has-error');
}

function parseFormToJson(form) {
    var formJson = {};
    $.each(form.serializeArray(), function(index, field) {
        var name = field.name.replace('sylius_product_review[', '').replace(']', '');
        formJson[name] = field.value || '';
    });

    return formJson;
}

function appendFlash(successMessage, messageHolderSelector) {
    messageHolderSelector = messageHolderSelector ? messageHolderSelector : '#flashes-container';

    $(messageHolderSelector).html('
×' + successMessage + '
');
}

function completeRequest(form) {
    form[0].reset();
    clearErrors(form);
    $("html, body").animate({ scrollTop: 0 }, "slow");
}


text:
package org.apache.giraph.debugger.mock;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Set;

import org.apache.giraph.utils.WritableUtils;
import org.apache.hadoop.io.BooleanWritable;
import org.apache.hadoop.io.ByteWritable;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;

/**
 * Utility class to help format some of the strings used in the generated unit
 * test. E.g., if an a float is initialized to 1.3 and we read that from
 * a protocolbuffer and write it again, it will be written as 1.299999....
 * So we need to truncate it when we generate the unittest and this class
 * contains such methods.
 */
public class FormatHelper {

  /**
   * {@link DecimalFormat} to use when formatting decimals.
   */
  private final DecimalFormat decimalFormat = new DecimalFormat("#.#####");

  /**
   * A set of complex writable object, i.e., user-defined ones that are not like
   * IntWritable, FloatWritable, etc..used by this compute function.
   */
  @SuppressWarnings("rawtypes")
  private Set<Class> complexWritables;

  /**
   * Default constructor.
   */
  public FormatHelper() {
  }

  /**
   * @param complexWritables complex writable objects to register.
   */
  @SuppressWarnings("rawtypes")
  public FormatHelper(Set<Class> complexWritables) {
    registerComplexWritableClassList(complexWritables);
  }

  /**
   * @param complexWritables complex writable objects to register.
   */
  @SuppressWarnings("rawtypes")
  public void registerComplexWritableClassList(Set<Class> complexWritables) {
    this.complexWritables = complexWritables;
  }

  /**
   * Generates the line that constructs the given writable.
   * @param writable writable object to construct in the unit test.
   * @return string generating the line that constructs the given writable.
   */
  public String formatWritable(Writable writable) {
    if (writable instanceof NullWritable) {
      return "NullWritable.get()";
    } else if (writable instanceof BooleanWritable) {
      return String.format("new BooleanWritable(%s)",
        format(((BooleanWritable) writable).get()));
    } else if (writable instanceof ByteWritable) {
      return String.format("new ByteWritable(%s)",
        format(((ByteWritable) writable).get()));
    } else if (writable instanceof IntWritable) {
      return String.format("new IntWritable(%s)",
        format(((IntWritable) writable).get()));
    } else if (writable instanceof LongWritable) {
      return String.format("new LongWritable(%s)",
        format(((LongWritable) writable).get()));
    } else if (writable instanceof FloatWritable) {
      return String.format("new FloatWritable(%s)",
        format(((FloatWritable) writable).get()));
    } else if (writable instanceof DoubleWritable) {
      return String.format("new DoubleWritable(%s)",
        format(((DoubleWritable) writable).get()));
    } else if (writable instanceof Text) {
      return String.format("new Text(%s)", ((Text) writable).toString());
    } else {
      if (complexWritables != null) {
        complexWritables.add(writable.getClass());
      }
      String str = toByteArrayString(WritableUtils.writeToByteArray(writable));
      return String.format("(%s)read%sFromByteArray(new byte[] {%s})", writable
        .getClass().getSimpleName(), writable.getClass().getSimpleName(), str);
    }
  }

  /**
   * Generates the line that constructs the given object, which can be
   * an int, boolean, char, byte, short, etc.
   * @param input object to construct in the unit test.
   * @return string generating the line that constructs the given object.
   */
  public String format(Object input) {
    if (input instanceof Boolean || input instanceof Byte ||
      input instanceof Character || input instanceof Short ||
      input instanceof Integer) {
      return input.toString();
    } else if (input instanceof Long) {
      return input.toString() + "l";
    } else if (input instanceof Float) {
      return decimalFormat.format(input) + "f";
    } else if (input instanceof Double) {
      double val = ((Double) input).doubleValue();
      if (val == Double.MAX_VALUE) {
        return "Double.MAX_VALUE";
      } else if (val == Double.MIN_VALUE) {
        return "Double.MIN_VALUE";
      } else {
        BigDecimal bd = new BigDecimal(val);
        return bd.toEngineeringString() + "d";
      }
    } else {
      return input.toString();
    }
  }

  /**
   * Generates a line constructing a byte array.
   * @param byteArray byte array to construct in the unit test.
   * @return string generating the line that constructs the given byte array.
   */
  private String toByteArrayString(byte[] byteArray) {
    StringBuilder strBuilder = new StringBuilder();
    for (int i = 0; i < byteArray.length; i++) {
      if (i != 0) {
        strBuilder.append(',');
      }
      strBuilder.append(Byte.toString(byteArray[i]));
    }
    return strBuilder.toString();
  }

}


text:
package org.radargun.service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.infinispan.Cache;
import org.infinispan.distexec.mapreduce.Collator;
import org.infinispan.distexec.mapreduce.MapReduceTask;
import org.infinispan.distexec.mapreduce.Mapper;
import org.infinispan.distexec.mapreduce.Reducer;
import org.radargun.traits.MapReducer;
import org.radargun.utils.ClassLoadHelper;
import org.radargun.utils.Utils;

public class InfinispanMapReduce<KIn, VIn, KOut, VOut, R> implements MapReducer<KOut, VOut, R> {

   protected Infinispan51EmbeddedService service;

   protected boolean distributeReducePhase;
   protected boolean useIntermediateSharedCache;
   protected long timeout = 0;
   protected TimeUnit unit = TimeUnit.MILLISECONDS;

   protected Map<String, String> mapperParameters;
   protected Map<String, String> reducerParameters;
   protected Map<String, String> combinerParameters;
   protected Map<String, String> collatorParameters;

   protected String combinerFqn = null;

   public InfinispanMapReduce(Infinispan51EmbeddedService service) {
      this.service = service;
   }

   @SuppressWarnings("unchecked")
   @Override
   public R executeMapReduceTask(ClassLoadHelper classLoadHelper, String mapperFqn, String reducerFqn,
         String collatorFqn) {
      MapReduceTask<KIn, VIn, KOut, VOut> t = mapReduceTaskFactory();

      Mapper<KIn, VIn, KOut, VOut> mapper = null;
      Reducer<KOut, VOut> reducer = null;
      Collator<KOut, VOut, R> collator = null;

      R result = null;

      try {
         mapper = (Mapper<KIn, VIn, KOut, VOut>) classLoadHelper.createInstance(mapperFqn);
         t = t.mappedWith(mapper);
      } catch (Exception e) {
         throw (new IllegalArgumentException("Could not instantiate Mapper class: " + mapperFqn, e));
      }

      try {
         reducer = (Reducer<KOut, VOut>) classLoadHelper.createInstance(reducerFqn);
         t = t.reducedWith(reducer);
      } catch (Exception e) {
         throw (new IllegalArgumentException("Could not instantiate Reducer class: " + reducerFqn, e));
      }

      setCombiner(t, classLoadHelper, combinerFqn);

      try {
         collator = (Collator<KOut, VOut, R>) classLoadHelper.createInstance(collatorFqn);
      } catch (Exception e) {
         throw (new IllegalArgumentException("Could not instantiate Collator class: " + collatorFqn, e));
      }

      if (mapper != null && reducer != null && collator != null) {
         Utils.invokeMethodWithString(mapper, this.mapperParameters);
         Utils.invokeMethodWithString(reducer, this.reducerParameters);
         Utils.invokeMethodWithString(collator, this.collatorParameters);
         result = t.execute(collator);
      }
      return result;
   }

   @SuppressWarnings("unchecked")
   @Override
   public Map<KOut, VOut> executeMapReduceTask(ClassLoadHelper classLoadHelper, String mapperFqn, String reducerFqn) {
      MapReduceTask<KIn, VIn, KOut, VOut> t = mapReduceTaskFactory();

      Mapper<KIn, VIn, KOut, VOut> mapper = null;
      Reducer<KOut, VOut> reducer = null;

      Map<KOut, VOut> result = null;

      try {
         mapper = (Mapper<KIn, VIn, KOut, VOut>) classLoadHelper.createInstance(mapperFqn);
         t = t.mappedWith(mapper);
      } catch (Exception e) {
         throw (new IllegalArgumentException("Could not instantiate Mapper class: " + mapperFqn, e));
      }

      try {
         reducer = (Reducer<KOut, VOut>) classLoadHelper.createInstance(reducerFqn);
         t = t.reducedWith(reducer);
      } catch (Exception e) {
         throw (new IllegalArgumentException("Could not instantiate Reducer class: " + reducerFqn, e));
      }

      if (mapper != null && reducer != null) {
         Utils.invokeMethodWithString(mapper, this.mapperParameters);
         Utils.invokeMethodWithString(reducer, this.reducerParameters);
         result = t.execute();
      }

      return result;
   }

   @Override
   public boolean setDistributeReducePhase(boolean distributeReducePhase) {
      return false;
   }

   @Override
   public boolean setUseIntermediateSharedCache(boolean useIntermediateSharedCache) {
      return false;
   }

   @Override
   public boolean setTimeout(long timeout, TimeUnit unit) {
      return false;
   }

   @Override
   public void setParameters(Map<String, String> mapperParameters, Map<String, String> reducerParameters,
         Map<String, String> combinerParameters, Map<String, String> collatorParameters) {
      this.mapperParameters = mapperParameters;
      this.reducerParameters = reducerParameters;
      this.combinerParameters = combinerParameters;
      this.collatorParameters = collatorParameters;
   }

   @Override
   public boolean setCombiner(String combinerFqn) {
      return false;
   }

   /**
    *
    * Factory method to create a MapReduceTask class. Infinispan 5.1 executed the reduce phase on a
    * single node. Infinispan 5.2 added the option to distribute the reduce phase and share
    * intermediate results. These options are controlled by the {@link #distributeReducePhase} and
    * {@link #useIntermediateSharedCache} properties.
    *
    * @return a MapReduceTask object that executes against on the default cache
    */
   protected MapReduceTask<KIn, VIn, KOut, VOut> mapReduceTaskFactory() {
      Cache<KIn, VIn> cache = service.cacheManager.getCache(null);
      return new MapReduceTask<KIn, VIn, KOut, VOut>(cache);
   }

   /**
    *
    * Method to set the combiner on a MapReduceTask object. Infinispan 5.2 added the option to
    * perform a combine phase on the local node before executing the global reduce phase.
    *
    * @param task
    *           the MapReduceTask object to modify
    * @param classLoadHelper
    *           a ClassLoadHelper used to instantiate the classes
    * @param combinerFqn
    *           the fully qualified class name for the org.infinispan.distexec.mapreduce.Reducer
    *           implementation. The implementation must have a no argument constructor.
    *
    * @return the MapReduceTask with the combiner set if the CacheWrapper supports it
    */
   protected MapReduceTask<KIn, VIn, KOut, VOut> setCombiner(MapReduceTask<KIn, VIn, KOut, VOut> task,
         ClassLoadHelper classLoadHelper, String combinerFqn) {
      return task;
   }

}


text:
TEST_CASE("Generate Parentheses") {
    GenerateParentheses s;
    SECTION("Sample test") {
        vector<string> expected = {
                "((()))", "(()())", "(())()", "()(())", "()()()"
        };
        vector<string> results = s.generateParenthesis(3);
        REQUIRE(results.size() == 5);

        for (auto p : expected)
            REQUIRE_FALSE(find(results.begin(), results.end(), p) == results.end());
    }
}


text:
package ir.bama.services

import javax.inject.{Inject, Singleton}

import ir.bama.models.CarModel
import ir.bama.repositories.CarModelRepo

import scala.concurrent.{ExecutionContext, Future}

/**
  * @author ahmad
  */
@Singleton
class CarModelService @Inject()(modelRepo: CarModelRepo)(implicit ec: ExecutionContext) extends BaseService[CarModel, CarModelRepo](modelRepo) {

  import repo.dbConfig._

  def listByBrandId(brandId: Long, range: Option[Range]): Future[Seq[CarModel]] =
    db.run(repo.listByBrandId(brandId, range))

  def searchByBrandIdAndName(brandId: Long, name: String, range: Option[Range]): Future[Seq[CarModel]] =
    db.run(repo.searchByBrandIdAndName(brandId, name, range))

}


text:
var exists = node_fs.existsSync ?
    function (file) {
        return node_fs.existsSync(file);
    } :

    // if node -v <= 0.6, there's no fs.existsSync method.
    function (file) {
        try {
            node_fs.statSync(file);
            return true;
        } catch(e) {
            return false;
        }
    };

// @returns {boolean} true if the file path exists.
sync.exists = function() {
    var filepath = node_path.join.apply(node_path, arguments);
    return exists(filepath);
};

//@returns true if the file is a symbolic link.
sync.isLink = function() {
      var filepath = node_path.join.apply(node_path, arguments);
      return exists(filepath) && node_fs.lstatSync(filepath).isSymbolicLink();
};

// @returns {boolean} true if the path is a directory.
sync.isDir = function() {
      var filepath = node_path.join.apply(node_path, arguments);
      return exists(filepath) && node_fs.statSync(filepath).isDirectory();
};

// @returns {boolean} true if the path is a file.
sync.isFile = function() {
    var filepath = node_path.join.apply(node_path, arguments);
      return exists(filepath) && node_fs.statSync(filepath).isFile();
};

sync.isPathAbsolute = function() {
      var filepath = node_path.join.apply(node_path, arguments);
      return node_path.resolve(filepath) === filepath.replace(/[\/\\]+$/, '');
};


text:
package io.mstream.trader.datafeed.stocks.quandl;

import io.mstream.trader.commons.config.model.DownstreamService;

import javax.inject.Inject;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.net.URI;
import java.util.function.Supplier;

class QuandlSslEngineSupplier
        implements Supplier<SSLEngine> {

    private final Supplier<DownstreamService> configSupplier;

    @Inject
    public QuandlSslEngineSupplier(
            @Quandl
                    Supplier<DownstreamService> configSupplier
    ) {

        this.configSupplier = configSupplier;
    }

    @Override
    public SSLEngine get() {

        String url = configSupplier
                .get()
                .getUrl()
                .url();

        try {
            URI uri = new URI(url);

            String host = uri.getHost();
            int port = uri.getPort();

            SSLContext sslContext = SSLContext.getDefault();
            SSLEngine sslEngine = sslContext.createSSLEngine(host, port);

            sslEngine.setUseClientMode(true);

            return sslEngine;

        } catch (Exception e) {
            throw new RuntimeException("can't create a SSL engine", e);
        }
    }
}


text:
package com.qihoo360.replugin.ext.parser.struct.xml;

/**
 * @author dongliu
 */
public class XmlNodeStartTag {
    private String namespace;
    private String name;

    // Byte offset from the start of this structure where the attributes start. uint16
    //public int attributeStart;
    // Size of the ResXMLTree_attribute structures that follow. unit16
    //public int attributeSize;
    // Number of attributes associated with an ELEMENT. uint 16
    // These are available as an array of ResXMLTree_attribute structures immediately following this node.
    //public int attributeCount;
    // Index (1-based) of the "id" attribute. 0 if none. uint16
    //public short idIndex;
    // Index (1-based) of the "style" attribute. 0 if none. uint16
    //public short styleIndex;

    private Attributes attributes;

    public String getNamespace() {
        return namespace;
    }

    public void setNamespace(String namespace) {
        this.namespace = namespace;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Attributes getAttributes() {
        return attributes;
    }

    public void setAttributes(Attributes attributes) {
        this.attributes = attributes;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append('<');
        if (namespace != null) {
            sb.append(namespace).append(":");
        }
        sb.append(name);
        sb.append('>');
        return sb.toString();
    }
}


text:
<?php

/**
 * The base class for all PHP_CodeSniffer documentation generators.
 *
 * Documentation generators are used to print documentation about code sniffs
 * in a standard.
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @author    Marc McIntyre <mmcintyre@squiz.net>
 * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */
class PHP_CodeSniffer_DocGenerators_Generator
{

    /**
     * The name of the coding standard we are generating docs for.
     *
     * @var string
     */
    private $_standard = '';

    /**
     * An array of sniffs that we are limiting the generated docs to.
     *
     * If this array is empty, docs are generated for all sniffs in the
     * supplied coding standard.
     *
     * @var string
     */
    private $_sniffs = array();

    /**
     * Constructs a PHP_CodeSniffer_DocGenerators_Generator object.
     *
     * @param string $standard The name of the coding standard to generate
     *                         docs for.
     * @param array  $sniffs   An array of sniffs that we are limiting the
     *                         generated docs to.
     *
     * @see generate()
     */
    public function __construct($standard, array $sniffs=array())
    {
        $this->_standard = $standard;
        $this->_sniffs   = $sniffs;

    }//end __construct()

    /**
     * Retrieves the title of the sniff from the DOMNode supplied.
     *
     * @param DOMNode $doc The DOMNode object for the sniff.
     *                     It represents the "documentation" tag in the XML
     *                     standard file.
     *
     * @return string
     */
    protected function getTitle(DOMNode $doc)
    {
        return $doc->getAttribute('title');

    }//end getTitle()

    /**
     * Retrieves the name of the standard we are generating docs for.
     *
     * @return string
     */
    protected function getStandard()
    {
        return $this->_standard;

    }//end getStandard()

    /**
     * Generates the documentation for a standard.
     *
     * It's probably wise for doc generators to override this method so they
     * have control over how the docs are produced. Otherwise, the processSniff
     * method should be overridden to output content for each sniff.
     *
     * @return void
     * @see    processSniff()
     */
    public function generate()
    {
        $standardFiles = $this->getStandardFiles();

        foreach ($standardFiles as $standard) {
            $doc = new DOMDocument();
            $doc->load($standard);
            $documentation = $doc->getElementsByTagName('documentation')->item(0);
            $this->processSniff($documentation);
        }

    }//end generate()

    /**
     * Returns a list of paths to XML standard files for all sniffs in a standard.
     *
     * Any sniffs that do not have an XML standard file are obviously not included
     * in the returned array. If documentation is only being generated for some
     * sniffs (ie. $this->_sniffs is not empty) then all others sniffs will
     * be filtered from the results as well.
     *
     * @return string[]
     */
    protected function getStandardFiles()
    {
        $phpcs = new PHP_CodeSniffer();
        $phpcs->process(array(), $this->_standard);
        $sniffs = $phpcs->getSniffs();

        $standardFiles = array();
        foreach ($sniffs as $className => $sniffClass) {
            $object = new ReflectionObject($sniffClass);
            $sniff  = $object->getFilename();
            if (empty($this->_sniffs) === false) {
                // We are limiting the docs to certain sniffs only, so filter
                // out any unwanted sniffs.
                $parts     = explode('_', $className);
                $sniffName = $parts[0].'.'.$parts[2].'.'.substr($parts[3], 0, -5);
                if (in_array($sniffName, $this->_sniffs) === false) {
                    continue;
                }
            }

            $standardFile = str_replace(
                DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR,
                DIRECTORY_SEPARATOR.'Docs'.DIRECTORY_SEPARATOR,
                $sniff
            );
            $standardFile = str_replace('Sniff.php', 'Standard.xml', $standardFile);

            if (is_file($standardFile) === true) {
                $standardFiles[] = $standardFile;
            }
        }//end foreach

        return $standardFiles;

    }//end getStandardFiles()

    /**
     * Process the documentation for a single sniff.
     *
     * Doc generators should override this function to produce output.
     *
     * @param DOMNode $doc The DOMNode object for the sniff.
     *                     It represents the "documentation" tag in the XML
     *                     standard file.
     *
     * @return void
     * @see    generate()
     */
    protected function processSniff(DOMNode $doc)
    {

    }//end processSniff()

}//end class


text:
import { NativeScriptCommonModule } from "nativescript-angular/common";
import { NativeScriptFormsModule } from "nativescript-angular/forms";
import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { groceriesRouting } from "./groceries.routing";
import { GroceriesComponent } from "./groceries.component";
import { GroceryListComponent } from "./grocery-list/grocery-list.component";
import { ItemStatusPipe } from "./grocery-list/item-status.pipe";

@NgModule({
  imports: [
    NativeScriptFormsModule,
    NativeScriptCommonModule,
    groceriesRouting,
  ],
  declarations: [
    GroceriesComponent,
    GroceryListComponent,
    ItemStatusPipe
  ],
  schemas: [NO_ERRORS_SCHEMA]
})
export class GroceriesModule {}


text:
{-# LANGUAGE NamedFieldPuns #-}

module Javran.MaxFlow.Algorithm.TestPack where

import Control.Monad
import qualified Data.ByteString as BS
import Data.Either
import Data.Text.Encoding (decodeUtf8)
import Javran.MaxFlow.Common
import Javran.MaxFlow.Parser
import Javran.MaxFlow.TestData
import Javran.MaxFlow.Verify
import Test.Hspec

mkPackSpec :: MaxFlowSolver -> String -> [(FilePath, BS.ByteString)] -> Spec
mkPackSpec runMaxFlow desc pack = do
  describe desc $
    forM_ pack $ \(fPath, raw) -> do
      let Right nrPre = parseFromRaw (decodeUtf8 raw)
          nn = normalize nrPre
          NetworkRep {nrSource, nrSink} = getNR nn
      specify fPath $ do
        let (result, _logs) = runMaxFlow nn
        result `shouldSatisfy` isRight
        let Right (_v, arcs, cMap) = result
        verify nrSource nrSink cMap arcs `shouldSatisfy` isRight

allPackSpec :: MaxFlowSolver -> Spec
allPackSpec runMaxFlow =
  forM_
    [ ("simple", packSimple)
    , ("handmade", packHandmade)
    , ("genetic", packGenetic)
    , ("random-best", packRandomBest)
    ]
    $ \(desc, pack) ->
      mkPackSpec runMaxFlow desc pack


text:
module KaExtUsers
	module Generators
		class InstallGenerator < Rails::Generators::Base
			source_root File.expand_path("../templates", __FILE__)

			desc 'Creates the config file in the main application and mounts the engine on a route.'

			def copy_config
				config_file = "config/ka_ext_users.yml"
				if !File.exists?(config_file)
					copy_file 'config.yml', config_file
				end
			end

			def setup_route
				route "mount KaExtUsers::Engine => '/extusers/'"
			end

			def self.source_root
				File.expand_path("../templates", __FILE__)
			end
		end
	end
end


text:
package org.factcast.core.util;

import static org.assertj.core.api.Assertions.assertThat;
import static org.factcast.core.TestHelper.expectNPE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

public class FactCastJsonTest {

    @Test
    void testCopyNull() {
        Assertions.assertThrows(NullPointerException.class, () -> {
            FactCastJson.copy(null);
        });
    }

    @Test
    void testCopy() {
        final Foo foo = new Foo("bar", "baz");
        Foo copy = FactCastJson.copy(foo);
        assertNotSame(foo, copy);
        assertNotEquals(foo, copy);
        assertEquals(foo.bar(), copy.bar());
        assertNull(copy.baz());
    }

    @AllArgsConstructor
    @Data
    @NoArgsConstructor
    static class Foo {

        @JsonProperty
        String bar;

        @JsonIgnore
        String baz;
    }

    @Test
    void testReadValueNull() {
        expectNPE(() -> FactCastJson.readValue(null, ""));
        expectNPE(() -> FactCastJson.readValue(null, (String) null));
        expectNPE(() -> FactCastJson.readValue(FactCastJson.class, (String) null));
        expectNPE(() -> FactCastJson.readValue(null, (InputStream) null));
        expectNPE(() -> FactCastJson.readValue(FactCastJson.class, (InputStream) null));
    }

    public static class X {
        String foo;

        int bar;
    }

    @Test
    void testReadValueFromInputStream() {

        X x = FactCastJson.readValue(X.class, new ByteArrayInputStream("{\"foo\":\"baz\",\"bar\":7}"
                .getBytes()));
        assertThat(x.foo).isEqualTo("baz");
        assertThat(x.bar).isEqualTo(7);
    }

    @Test
    void testWriteValueNull() {
        expectNPE(() -> FactCastJson.writeValueAsString(null));
    }

    @Test
    void testNewObjectNode() {
        assertNotNull(FactCastJson.newObjectNode());
        assertTrue(FactCastJson.newObjectNode() instanceof ObjectNode);
    }

    @Test
    void testToObjectNodeNonJson() {
        Assertions.assertThrows(RuntimeException.class, () -> {
            FactCastJson.toObjectNode("no-json");
        });
    }

    @Test
    void testToObjectNode() {
        ObjectNode objectNode = FactCastJson.toObjectNode("{\"x\":1}");
        JsonNode jsonNode = objectNode.get("x");
        assertEquals(1, jsonNode.asInt());
        assertNull(objectNode.get("y"));
    }

    @Test
    void testWriteValueAsPrettyString() {
        String json = "{\"a\":1}";
        String pretty = FactCastJson.writeValueAsPrettyString(FactCastJson.toObjectNode(json));
        assertTrue(pretty.contains("\n"));
        assertTrue(pretty.contains(" "));
    }

    @Test
    void testWriteValueAsPrettyFromObject() {
        @Data
        class TestObject {
            String foo = "bar";
        }

        String pretty = FactCastJson.writeValueAsPrettyString(new TestObject());
        System.out.println(pretty);
        assertTrue(pretty.contains("\"foo\" : \"bar\""));
    }
}


text:
<?php

/**
 * smarty_function_geturl
 *
 * Функция Smarty - type_media
 * Определим тип медиа пр. потоковое или нет?
 *
 * @uses
 * @package    Module-Default
 * @subpackage Views.Plugins
 */

/**
 * Определить вид медиа из набора обьектов
 *
 * @param array $medias
 * @param string $type
 * @param int $result
 * @return void
 */
function smarty_function_type_media($params, $smarty) {
    extract($params);// Преобразуем массив параметров в переменные
    $count = 0;
    foreach ($medias as $media) {
        if($type == 'streaming'){
            if($media->type == 'url-rtmp' || $media->type == 'url-pseudostreaming' || $media->type == 'url-httpstreaming'){
                $count ++;
            }
        }

        if($type == 'no_streaming'){
            if(! ($media->type == 'url-rtmp' || $media->type == 'url-pseudostreaming' || $media->type == 'url-httpstreaming')){
                $count ++;
            }
        }
    }
    $smarty->assign($assign, $count);
}

?>


text:
import os

import numpy as np
import pytest

import pandas as pd
import pandas.util.testing as tm

from pandas.io.sas.sasreader import read_sas

# CSV versions of test xpt files were obtained using the R foreign library

# Numbers in a SAS xport file are always float64, so need to convert
# before making comparisons.

def numeric_as_float(data):
    for v in data.columns:
        if data[v].dtype is np.dtype("int64"):
            data[v] = data[v].astype(np.float64)

class TestXport:
    @pytest.fixture(autouse=True)
    def setup_method(self, datapath):
        self.dirpath = datapath("io", "sas", "data")
        self.file01 = os.path.join(self.dirpath, "DEMO_G.xpt")
        self.file02 = os.path.join(self.dirpath, "SSHSV1_A.xpt")
        self.file03 = os.path.join(self.dirpath, "DRXFCD_G.xpt")
        self.file04 = os.path.join(self.dirpath, "paxraw_d_short.xpt")

    def test1_basic(self):
        # Tests with DEMO_G.xpt (all numeric file)

        # Compare to this
        data_csv = pd.read_csv(self.file01.replace(".xpt", ".csv"))
        numeric_as_float(data_csv)

        # Read full file
        data = read_sas(self.file01, format="xport")
        tm.assert_frame_equal(data, data_csv)
        num_rows = data.shape[0]

        # Test reading beyond end of file
        reader = read_sas(self.file01, format="xport", iterator=True)
        data = reader.read(num_rows + 100)
        assert data.shape[0] == num_rows
        reader.close()

        # Test incremental read with `read` method.
        reader = read_sas(self.file01, format="xport", iterator=True)
        data = reader.read(10)
        reader.close()
        tm.assert_frame_equal(data, data_csv.iloc[0:10, :])

        # Test incremental read with `get_chunk` method.
        reader = read_sas(self.file01, format="xport", chunksize=10)
        data = reader.get_chunk()
        reader.close()
        tm.assert_frame_equal(data, data_csv.iloc[0:10, :])

        # Test read in loop
        m = 0
        reader = read_sas(self.file01, format="xport", chunksize=100)
        for x in reader:
            m += x.shape[0]
        reader.close()
        assert m == num_rows

        # Read full file with `read_sas` method
        data = read_sas(self.file01)
        tm.assert_frame_equal(data, data_csv)

    def test1_index(self):
        # Tests with DEMO_G.xpt using index (all numeric file)

        # Compare to this
        data_csv = pd.read_csv(self.file01.replace(".xpt", ".csv"))
        data_csv = data_csv.set_index("SEQN")
        numeric_as_float(data_csv)

        # Read full file
        data = read_sas(self.file01, index="SEQN", format="xport")
        tm.assert_frame_equal(data, data_csv, check_index_type=False)

        # Test incremental read with `read` method.
        reader = read_sas(self.file01, index="SEQN", format="xport", iterator=True)
        data = reader.read(10)
        reader.close()
        tm.assert_frame_equal(data, data_csv.iloc[0:10, :], check_index_type=False)

        # Test incremental read with `get_chunk` method.
        reader = read_sas(self.file01, index="SEQN", format="xport", chunksize=10)
        data = reader.get_chunk()
        reader.close()
        tm.assert_frame_equal(data, data_csv.iloc[0:10, :], check_index_type=False)

    def test1_incremental(self):
        # Test with DEMO_G.xpt, reading full file incrementally

        data_csv = pd.read_csv(self.file01.replace(".xpt", ".csv"))
        data_csv = data_csv.set_index("SEQN")
        numeric_as_float(data_csv)

        reader = read_sas(self.file01, index="SEQN", chunksize=1000)

        all_data = [x for x in reader]
        data = pd.concat(all_data, axis=0)

        tm.assert_frame_equal(data, data_csv, check_index_type=False)

    def test2(self):
        # Test with SSHSV1_A.xpt

        # Compare to this
        data_csv = pd.read_csv(self.file02.replace(".xpt", ".csv"))
        numeric_as_float(data_csv)

        data = read_sas(self.file02)
        tm.assert_frame_equal(data, data_csv)

    def test_multiple_types(self):
        # Test with DRXFCD_G.xpt (contains text and numeric variables)

        # Compare to this
        data_csv = pd.read_csv(self.file03.replace(".xpt", ".csv"))

        data = read_sas(self.file03, encoding="utf-8")
        tm.assert_frame_equal(data, data_csv)

    def test_truncated_float_support(self):
        # Test with paxraw_d_short.xpt, a shortened version of:
        # http://wwwn.cdc.gov/Nchs/Nhanes/2005-2006/PAXRAW_D.ZIP
        # This file has truncated floats (5 bytes in this case).

        # GH 11713

        data_csv = pd.read_csv(self.file04.replace(".xpt", ".csv"))

        data = read_sas(self.file04, format="xport")
        tm.assert_frame_equal(data.astype("int64"), data_csv)


text:
package org.wso2.carbon.apimgt.api;

public interface LoginPostExecutor {

    /**
     * get organization id related to user for the purpose of sharing applications and subscriptions in an organization
     *
     * @param response login response
     * @return organization identifier
     */
    String getGroupingIdentifiers(String response);
}


text:
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.XWPF.UserModel;

namespace NPOI.OOXML.XWPF.Util
{
    public class DocumentStylesBuilder
    {
        private XWPFStyles documentStyles;
        private CT_Styles ctStyles;

        public DocumentStylesBuilder()
        {
            documentStyles = new XWPFStyles();
            ctStyles = new CT_Styles();
        }

        public DocumentStylesBuilder(XWPFDocument docxDocument)
        {
            documentStyles = docxDocument.CreateStyles();
            ctStyles = new CT_Styles();
        }

        /// <summary>
        /// Sets default font, size for text in the document.
        /// </summary>
        public void AddDefaultStyle()
        {
            CT_DocDefaults docDefaults = ctStyles.AddNewDocDefaults();
            CT_RPrDefault rprDefault = docDefaults.AddNewRPrDefault();
            CT_RPr rpr = rprDefault.AddNewRPr();
            rpr.AddNewSz().val = 24;
            rpr.AddNewSzCs().val = 24;
            var font = rpr.AddNewRFonts();
            font.asciiTheme = ST_Theme.minorAscii;
            font.cstheme = ST_Theme.minorBidi;
            font.eastAsiaTheme = ST_Theme.minorHAnsi;
            font.hAnsiTheme = ST_Theme.minorHAnsi;
        }

        public void AddCustomHeadingStyle(string name, int headingLevel, int outlineLevel, int ptSize = 12)
        {

            CT_Style ctStyle = ctStyles.AddNewStyle();
            ctStyle.styleId = (name);

            CT_String styleName = new CT_String();
            styleName.val = (name);
            ctStyle.name = (styleName);

            CT_DecimalNumber indentNumber = new CT_DecimalNumber();
            indentNumber.val = headingLevel.ToString();

            // lower number > style is more prominent in the formats bar
            ctStyle.uiPriority = (indentNumber);

            CT_OnOff onoffnull = new CT_OnOff();
            ctStyle.unhideWhenUsed = (onoffnull);

            // style shows up in the formats bar
            ctStyle.qFormat = (onoffnull);

            // style defines a heading of the given level
            CT_PPr ppr = new CT_PPr();
            ppr.outlineLvl = new CT_DecimalNumber() { val = outlineLevel.ToString() };
            ctStyle.pPr = (ppr);

            CT_RPr rpr = new CT_RPr();
            rpr.AddNewSz().val = (ulong)ptSize * 2;
            ctStyle.rPr = rpr;
        }

        public CT_Styles Build()
        {
            documentStyles.SetStyles(ctStyles);
            return ctStyles;
        }

        /// <summary>
        /// Builds the styles required for rendering & handling
        /// Table of Contents (TOC).
        ///
        /// Please set paragraph style to "Heading{#}" in order to
        /// have it rendered in the TOC.
        /// </summary>
        /// <param name="doc">the document to set styles</param>
        public static CT_Styles BuildStylesForTOC(XWPFDocument doc = null)
        {
            DocumentStylesBuilder builder;

            if (doc != null)
            {
                builder = new DocumentStylesBuilder(doc);
            }
            else
            {
                builder = new DocumentStylesBuilder();
            }

            builder.AddDefaultStyle();
            builder.AddCustomHeadingStyle("TOCHeading", 1, 9);
            builder.AddCustomHeadingStyle("TOC1", 2, 0);
            builder.AddCustomHeadingStyle("TOC2", 3, 0);
            builder.AddCustomHeadingStyle("Heading1", 4, 0);
            builder.AddCustomHeadingStyle("Heading2", 5, 1);
            return builder.Build();
        }
    }

}


text:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <title>OpenLayers Buffer Example</title>
        <link rel="stylesheet" href="../theme/default/style.css" type="text/css">
        <link rel="stylesheet" href="style.css" type="text/css">

Buffer Example

            buffer, performance, tile

            This example shows the use of the buffer layer option for any layer that inherits from OpenLayers.Layer.Grid.

            Use the buffer property to control how many tiles are included
            outside the visible map area. Default is 2.


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

<title>org.jivesoftware.openfire.webdav (Openfire 3.10.2 Javadoc)</title>
<meta name="date" content="2015-06-22">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.jivesoftware.openfire.webdav

Classes

WebDAVLiteServlet


text:
/**
 * Cope with selection in various configurations.
 *
 * (1) When user selects a case in the *population* data set,
 *      select relevant cases, if any, in the *records* data set.
 *      Note how this could begin by selection on a map.
 * (2) When the user selects in the *records* data set, select in the *population.*
 *
 * The right strategy is not obvious initially.
 * One possiblity is to get the selected set in a new CODAP request.
 *
 * @type {{processCodapCaseSelection: clinic.selectionManager.processCodapCaseSelection}}
 */
clinic.selectionManager = {

    processCodapCaseSelection: function (iCommand, iCallback) {
        console.log("clinic.selectionManager.processCodapNotification: enter handler.");
        var tResourceString = iCommand.resource;
        tParsedResourceSelector = codapInterface.parseResourceSelector(tResourceString);
        tDataContextName = tParsedResourceSelector.dataContextChangeNotice;

        var tCases = (iCommand.values.result.cases) ? pluginHelper.arrayify(iCommand.values.result.cases) : [];
        console.log("Selection! " + tCases.length + " cases.");

        if (tDataContextName === clinic.constants.kPopulationDataSetName) {
            /*
             The selection is in the population dataset
             Loop through and select all corresponding cases in the records.
             */
            var tRecordsSearches = [];      //  will contain promises
            var tSelectionList = [];        //  will contain CODAP caseIDs.

            tCases.forEach(function (iCase) {
                var tOnePatientID = iCase.values.id;    //  this is the patient ID, e.g., SFP0056

                //  search for that patient ID in the records...

                //  create the message to search for this single patientID in the records data set
                var tSearchMessage = {
                    "action": "get",
                    "resource": "dataContext[" + clinic.constants.kRecordsDataSetName + "].collection["
                    + clinic.constants.kRecordsPatientsCollectionName + "].caseSearch[id==" + tOnePatientID + "]"
                };

                //  execute the search

                var tRecordsSearch = codapInterface.sendRequest(tSearchMessage).then(
                    function (iResponse) {
                        iResponse.values.forEach(function (v) {     //  loop over all cases fro that ID
                                tSelectionList.push(v.id);          //  add their case IDs to the selection list
                            }
                        )
                    }
                );

                tRecordsSearches.push(tRecordsSearch)      //  add to array of Promises, so we can tell when they're all done.

            });

            //  Only when all the records searches are done will we select the cases by caseID.

            Promise.all(tRecordsSearches).then( function(iResult) {
                //  now we have all the CODAP caseIDs associated with all the patient IDs
                //  so make the selection
                clinic.selectionManager.selectTheseCaseIDs( tSelectionList, clinic.constants.kRecordsDataSetName);
            });

        } else {
            /*  the selection is in the records dataset, somewhere. Don't know which collection.
                for now, assume it's in the patients collection because that's where the PatientID is.
             */
            /*
             Loop through and select all corresponding cases in the population.
             */
            var tPopulationSearches = [];      //  will contain promises
            var tSelectionList = [];        //  will contain CODAP caseIDs.

            //  we have a list of cases that are selected in records. Loop thorugh them, look at each one...

            tCases.forEach(function (iCase) {
                var tOnePatientID = iCase.values.id;    //  this is the patient ID, e.g., SFP0056

                //  if the ID exists at this level, search for that patient ID in the population...

                if (true) {
                    //  create the message to search for this single patientID in the population data set
                    //  goal: find all of their case IDs.
                    //  stash them in tSelectionList

                    var tSearchMessage = {
                        "action": "get",
                        "resource": "dataContext[" + clinic.constants.kPopulationDataSetName
                        + "].collection[" + clinic.constants.kPopulationCollectionName
                        + "].caseSearch[id==" + tOnePatientID + "]"
                    };

                    //  execute the search

                    var tPopulationSearch = codapInterface.sendRequest(tSearchMessage).then(
                        function (iResponse) {
                            iResponse.values.forEach(function (v) {     //  loop over all cases from that ID
                                    tSelectionList.push(v.id);          //  add their case IDs to the selection list
                                }
                            )
                        }
                    );

                    tPopulationSearches.push(tPopulationSearch)      //  add to array of Promises, so we can tell when they're all done.
                }

            });

            //  Only when all the records searches are done will we select the cases by caseID.

            Promise.all(tPopulationSearches).then( function(iResult) {
                //  now we have all the CODAP caseIDs associated with all the patient IDs
                //  so make the selection
                clinic.selectionManager.selectTheseCaseIDs( tSelectionList, clinic.constants.kPopulationDataSetName);
            });
        }
    },

    selectTheseCaseIDs : function( iList, iDataContextName ) {
        iList = pluginHelper.arrayify( iList );

        var tSelectionMessage = {
            "action": "create",
            "resource": "dataContext[" + iDataContextName + "].selectionList",
            "values": iList
        };
        codapInterface.sendRequest( tSelectionMessage );    //  do the (multiple) selection

    },

    selectThisPersonInAllDataSets : function(iPerson ) {
        var tOnePatientID = iPerson.patientID;

        var tRecordsSearchMessage = {
            "action": "get",
            "resource": "dataContext[" + clinic.constants.kRecordsDataSetName + "].collection["
            + clinic.constants.kRecordsPatientsCollectionName + "].caseSearch[id==" + tOnePatientID + "]"
        };

        var tPopulationSearchMessage = {
            "action": "get",
            "resource": "dataContext[" + clinic.constants.kPopulationDataSetName + "].collection["
            + clinic.constants.kPopulationCollectionName + "].caseSearch[id==" + tOnePatientID + "]"
        };

        var tCaseID = 0;
        codapInterface.sendRequest( tRecordsSearchMessage ).then(
            function (iResponse) {
                if (iResponse.success && iResponse.values.length > 0) {
                    tCaseID = iResponse.values[0].id;          //  get the first IDs to the selection list
                    clinic.selectionManager.selectTheseCaseIDs(tCaseID, clinic.constants.kRecordsDataSetName);
                }
            }
        );
        codapInterface.sendRequest( tPopulationSearchMessage ).then(
            function (iResponse) {
                if (iResponse.success && iResponse.values.length > 0) {
                    tCaseID = iResponse.values[0].id;          //  get the first IDs to the selection list
                    clinic.selectionManager.selectTheseCaseIDs(tCaseID, clinic.constants.kPopulationDataSetName);
                }
            }
        );
    }

};

/*
{
    "success"
:
    true,
        "values"
:
    [
        {
            "id": 1161,
            "parent": null,
            "collection": {
                "name": "population",
                "id": 19
            },
            "values": {
                "name": "JENIFER WANG",
                "age": 47,
                "sex": "female",
                "address": "5800 3rd Street #1310",
                "lat": 37.725305449737945,
                "long": -122.39425714443917,
                "last": "WANG",
                "first": "JENIFER",
                "id": "SFP1133"
            }
        },
*/


text:
require 'spec_helper'

describe 'Client-Side Encryption' do
  describe 'Prose tests: KMS TLS Options Tests' do
    require_libmongocrypt
    require_enterprise
    min_server_fcv '4.2'

    include_context 'define shared FLE helpers'

    let(:client) do
      new_local_client(
        SpecConfig.instance.addresses,
        SpecConfig.instance.test_options
      )
    end

    let(:client_encryption_no_client_cert) do
      Mongo::ClientEncryption.new(
        client,
        {
          kms_providers: {
            aws: {
              access_key_id: SpecConfig.instance.fle_aws_key,
              secret_access_key: SpecConfig.instance.fle_aws_secret
            },
            azure: {
              tenant_id: SpecConfig.instance.fle_azure_tenant_id,
              client_id: SpecConfig.instance.fle_azure_client_id,
              client_secret: SpecConfig.instance.fle_azure_client_secret,
              identity_platform_endpoint: "127.0.0.1:8002"
            },
            gcp: {
              email: SpecConfig.instance.fle_gcp_email,
              private_key: SpecConfig.instance.fle_gcp_private_key,
              endpoint: "127.0.0.1:8002"
            },
            kmip: {
              endpoint: "127.0.0.1:5698"
            }
          },
          kms_tls_options: {
            aws: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file
            },
            azure: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file
            },
            gcp: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file
            },
            kmip: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file
            }
          },
          key_vault_namespace: 'keyvault.datakeys',
        },
      )
    end

    let(:client_encryption_with_tls) do
      Mongo::ClientEncryption.new(
        client,
        {
          kms_providers: {
            aws: {
              access_key_id: SpecConfig.instance.fle_aws_key,
              secret_access_key: SpecConfig.instance.fle_aws_secret
            },
            azure: {
              tenant_id: SpecConfig.instance.fle_azure_tenant_id,
              client_id: SpecConfig.instance.fle_azure_client_id,
              client_secret: SpecConfig.instance.fle_azure_client_secret,
              identity_platform_endpoint: "127.0.0.1:8002"
            },
            gcp: {
              email: SpecConfig.instance.fle_gcp_email,
              private_key: SpecConfig.instance.fle_gcp_private_key,
              endpoint: "127.0.0.1:8002"
            },
            kmip: {
              endpoint: "127.0.0.1:5698"
            }
          },
          kms_tls_options: {
            aws: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file,
              ssl_cert: SpecConfig.instance.fle_kmip_tls_certificate_key_file,
              ssl_key: SpecConfig.instance.fle_kmip_tls_certificate_key_file,
            },
            azure: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file,
              ssl_cert: SpecConfig.instance.fle_kmip_tls_certificate_key_file,
              ssl_key: SpecConfig.instance.fle_kmip_tls_certificate_key_file,
            },
            gcp: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file,
              ssl_cert: SpecConfig.instance.fle_kmip_tls_certificate_key_file,
              ssl_key: SpecConfig.instance.fle_kmip_tls_certificate_key_file,
            },
            kmip: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file,
              ssl_cert: SpecConfig.instance.fle_kmip_tls_certificate_key_file,
              ssl_key: SpecConfig.instance.fle_kmip_tls_certificate_key_file,
            }
          },
          key_vault_namespace: 'keyvault.datakeys',
        },
      )
    end

    let(:client_encryption_expired) do
      Mongo::ClientEncryption.new(
        client,
        {
          kms_providers: {
            aws: {
              access_key_id: SpecConfig.instance.fle_aws_key,
              secret_access_key: SpecConfig.instance.fle_aws_secret
            },
            azure: {
              tenant_id: SpecConfig.instance.fle_azure_tenant_id,
              client_id: SpecConfig.instance.fle_azure_client_id,
              client_secret: SpecConfig.instance.fle_azure_client_secret,
              identity_platform_endpoint: "127.0.0.1:8000"
            },
            gcp: {
              email: SpecConfig.instance.fle_gcp_email,
              private_key: SpecConfig.instance.fle_gcp_private_key,
              endpoint: "127.0.0.1:8000"
            },
            kmip: {
              endpoint: "127.0.0.1:8000"
            }
          },
          kms_tls_options: {
            aws: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file
            },
            azure: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file
            },
            gcp: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file
            },
            kmip: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file
            }
          },
          key_vault_namespace: 'keyvault.datakeys',
        },
      )
    end

    let(:client_encryption_invalid_hostname) do
      Mongo::ClientEncryption.new(
        client,
        {
          kms_providers: {
            aws: {
              access_key_id: SpecConfig.instance.fle_aws_key,
              secret_access_key: SpecConfig.instance.fle_aws_secret
            },
            azure: {
              tenant_id: SpecConfig.instance.fle_azure_tenant_id,
              client_id: SpecConfig.instance.fle_azure_client_id,
              client_secret: SpecConfig.instance.fle_azure_client_secret,
              identity_platform_endpoint: "127.0.0.1:8001"
            },
            gcp: {
              email: SpecConfig.instance.fle_gcp_email,
              private_key: SpecConfig.instance.fle_gcp_private_key,
              endpoint: "127.0.0.1:8001"
            },
            kmip: {
              endpoint: "127.0.0.1:8001"
            }
          },
          kms_tls_options: {
            aws: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file
            },
            azure: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file
            },
            gcp: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file
            },
            kmip: {
              ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file
            }
          },
          key_vault_namespace: 'keyvault.datakeys',
        },
      )
    end

    # We do noy use shared examples for AWS because of the way we pass endpoint.
    context 'AWS' do
      let(:master_key_template) do
        {
          region: "us-east-1",
          key: "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0",
        }
      end

      context 'with no client certificate' do
        it 'TLS handshake failed' do
          expect do
            client_encryption_no_client_cert.create_data_key(
              'aws',
              {
                master_key: master_key_template.merge({endpoint: "127.0.0.1:8002"})
              }
            )
          end.to raise_error(Mongo::Error::KmsError, /(certificate_required|SocketError|ECONNRESET)/)
        end
      end

      context 'with valid certificate' do
        it 'TLS handshake passes' do
          expect do
            client_encryption_with_tls.create_data_key(
              'aws',
              {
                master_key: master_key_template.merge({endpoint: "127.0.0.1:8002"})
             }
            )
          end.to raise_error(Mongo::Error::KmsError, /libmongocrypt error code/)
        end
      end

      context 'with expired server certificate' do
        let(:error_regex) do
          if BSON::Environment.jruby?
            /certificate verify failed/
          else
            /certificate has expired/
          end
        end

        it 'TLS handshake failed' do
          expect do
            client_encryption_expired.create_data_key(
              'aws',
              {
                master_key: master_key_template.merge({endpoint: "127.0.0.1:8000"})
              }
            )
          end.to raise_error(Mongo::Error::KmsError, error_regex)
        end
      end

      context 'with server certificate with invalid hostname' do
        let(:error_regex) do
          if BSON::Environment.jruby?
            /TLS handshake failed due to a hostname mismatch/
          else
            /certificate verify failed/
          end
        end

        it 'TLS handshake failed' do
          expect do
            client_encryption_invalid_hostname.create_data_key(
              'aws',
              {
                master_key: master_key_template.merge({endpoint: "127.0.0.1:8001"})
              }
            )
          end.to raise_error(Mongo::Error::KmsError, error_regex)
        end
      end
    end

    shared_examples 'it respect KMS TLS options' do
      context 'with no client certificate' do
        it 'TLS handshake failed' do
          expect do
            client_encryption_no_client_cert.create_data_key(
              kms_provider,
              {
                master_key: master_key
             }
            )
          end.to raise_error(Mongo::Error::KmsError, /(certificate_required|SocketError|ECONNRESET)/)
        end
      end

      context 'with valid certificate' do
        it 'TLS handshake passes' do
          if should_raise_with_tls
            expect do
              client_encryption_with_tls.create_data_key(
                kms_provider,
                {
                  master_key: master_key
              }
              )
            end.to raise_error(Mongo::Error::KmsError, /libmongocrypt error code/)
          else
            expect do
              client_encryption_with_tls.create_data_key(
                kms_provider,
                {
                  master_key: master_key
              }
              )
            end.not_to raise_error
          end
        end

        it 'raises KmsError directly without wrapping CryptError' do
          if should_raise_with_tls
            begin
              client_encryption_with_tls.create_data_key(
                kms_provider,
                {
                  master_key: master_key
              }
              )
            rescue Mongo::Error::KmsError => exc
              exc.message.should =~ /Error when connecting to KMS provider/
              exc.message.should =~ /libmongocrypt error code/
              exc.message.should_not =~ /CryptError/
            else
              fail 'Expected to raise KmsError'
            end
          end
        end
      end

      context 'with expired server certificate' do
        let(:error_regex) do
          if BSON::Environment.jruby?
            /certificate verify failed/
          else
            /certificate has expired/
          end
        end

        it 'TLS handshake failed' do
          expect do
            client_encryption_expired.create_data_key(
              kms_provider,
              {
                master_key: master_key
            }
            )
          end.to raise_error(Mongo::Error::KmsError, error_regex)
        end
      end

      context 'with server certificate with invalid hostname' do
        let(:error_regex) do
          if BSON::Environment.jruby?
            /TLS handshake failed due to a hostname mismatch/
          else
            /certificate verify failed/
          end
        end

        it 'TLS handshake failed' do
          expect do
            client_encryption_invalid_hostname.create_data_key(
              kms_provider,
              {
                master_key: master_key
              }
            )
          end.to raise_error(Mongo::Error::KmsError, error_regex)
        end
      end
    end

    context 'Azure' do
      let(:kms_provider) do
        'azure'
      end

      let(:master_key) do
        {
          key_vault_endpoint: 'doesnotexist.local',
          key_name: 'foo'
        }
      end

      let(:should_raise_with_tls) do
        true
      end

      it_behaves_like 'it respect KMS TLS options'
    end

    context 'GCP' do
      let(:kms_provider) do
        'gcp'
      end

      let(:master_key) do
        {
          project_id: 'foo',
          location: 'bar',
          key_ring: 'baz',
          key_name: 'foo'
        }
      end

      let(:should_raise_with_tls) do
        true
      end

      it_behaves_like 'it respect KMS TLS options'
    end

    context 'KMIP' do
      let(:kms_provider) do
        'kmip'
      end

      let(:master_key) do
        {}
      end

      let(:should_raise_with_tls) do
        false
      end

      it_behaves_like 'it respect KMS TLS options'
    end

  end
end


text:
from flask import Flask, render_template_string, redirect
from flask_login import UserMixin, LoginManager, login_user, logout_user
from flask_blogging import BloggingEngine
from flask_blogging.dynamodbstorage import DynamoDBStorage
from flask_fileupload.storage.s3storage import S3Storage
from flask_fileupload import FlaskFileUpload

app = Flask(__name__)
app.config["SECRET_KEY"] = "secret"  # for WTF-forms and login
app.config["BLOGGING_URL_PREFIX"] = "/blog"
app.config["BLOGGING_DISQUS_SITENAME"] = "test"
app.config["BLOGGING_SITEURL"] = ""
app.config["BLOGGING_SITENAME"] = "My Site"
app.config["BLOGGING_ALLOW_FILEUPLOAD"] = True
app.config["FILEUPLOAD_S3_BUCKET"]='quandldata'
app.config["FILEUPLOAD_PREFIX"] = "/upload"
app.config["FILEUPLOAD_ALLOWED_EXTENSIONS"] = ["png", "jpg", "jpeg", "gif"]

# extensions
s3storage = S3Storage(app)
file_upload = FlaskFileUpload(app, storage=s3storage)

dyn_storage = DynamoDBStorage(endpoint_url='http://localhost:8000')
blog_engine = BloggingEngine(app, dyn_storage, file_upload=file_upload)
login_manager = LoginManager(app)

class User(UserMixin):
    def __init__(self, user_id):
        self.id = user_id

    def get_name(self):
        return "Paul Dirac"  # typically the user's name

@login_manager.user_loader
@blog_engine.user_loader
def load_user(user_id):
    return User(user_id)

index_template = """
<!DOCTYPE html>

        {% if current_user.is_authenticated %}
             Logout
        {% else %}
             Login
        {% endif %}
        &nbsp&nbsp Blog
        &nbsp&nbspSitemap
        &nbsp&nbspATOM

"""

@app.route("/")
def index():
    return render_template_string(index_template)

@app.route("/login/")
def login():
    user = User("testuser")
    login_user(user)
    return redirect("/blog")

@app.route("/logout/")
def logout():
    logout_user()
    return redirect("/")

if __name__ == "__main__":
    app.run(debug=True, port=8001, use_reloader=True)


text:
import logging

from preggy import expect
from mock import Mock, patch

from octopus import TornadoOctopus
from octopus.cache import Cache
from tests import TestCase

class TestTornadoOctopus(TestCase):
    def setUp(self):
        self.response = None
        self.url = None
        self.responses = {}

    def get_response(self, request=None):
        if request is None:
            request = Mock(
                headers={
                    'Cookie': 'foo=bar'
                },
            )

        return Mock(
            request=request,
            headers={
                'baz': 'foo'
            },
            code=200,
            body='body',
            effective_url='http://www.google.com/',
            error='error',
            request_time=2.1
        )

    def test_can_create_tornado_otto(self):
        otto = TornadoOctopus()

        expect(otto.concurrency).to_equal(10)
        expect(otto.auto_start).to_be_false()
        expect(otto.cache).to_be_false()

        expect(otto.response_cache).not_to_be_null()
        expect(otto.response_cache).to_be_instance_of(Cache)
        expect(otto.response_cache.expiration_in_seconds).to_equal(30)

        expect(otto.request_timeout_in_seconds).to_equal(10)
        expect(otto.connect_timeout_in_seconds).to_equal(5)
        expect(otto.ignore_pycurl).to_be_false()

        expect(otto.running_urls).to_equal(0)
        expect(otto.url_queue).to_be_empty()

    def test_can_create_tornado_otto_with_custom_values(self):
        otto = TornadoOctopus(
            concurrency=20, auto_start=True, cache=True,
            expiration_in_seconds=60, request_timeout_in_seconds=20,
            connect_timeout_in_seconds=10, ignore_pycurl=True

        )

        expect(otto.concurrency).to_equal(20)
        expect(otto.auto_start).to_be_true()
        expect(otto.cache).to_be_true()

        expect(otto.response_cache).not_to_be_null()
        expect(otto.response_cache).to_be_instance_of(Cache)
        expect(otto.response_cache.expiration_in_seconds).to_equal(60)

        expect(otto.request_timeout_in_seconds).to_equal(20)
        expect(otto.connect_timeout_in_seconds).to_equal(10)
        expect(otto.ignore_pycurl).to_be_true()

        expect(otto.running_urls).to_equal(0)
        expect(otto.url_queue).to_be_empty()

    def test_can_get_queue_info(self):
        otto = TornadoOctopus()

        expect(otto.queue_size).to_equal(0)
        expect(otto.is_empty).to_be_true()

    def test_can_get_response_from_tornado_response(self):
        response = self.get_response()

        otto_response = TornadoOctopus.from_tornado_response('http://www.google.com', response)

        expect(otto_response.url).to_equal('http://www.google.com')
        expect(otto_response.headers).to_be_like(response.headers)
        expect(otto_response.cookies).to_be_like({
            'foo': 'bar'
        })
        expect(otto_response.text).to_equal('body')
        expect(otto_response.error).to_equal('error')
        expect(otto_response.request_time).to_equal(2.1)

    def test_can_get_response_from_tornado_response_when_no_cookies(self):
        response = self.get_response(request=Mock(headers={}))

        otto_response = TornadoOctopus.from_tornado_response('http://www.google.com', response)

        expect(otto_response.url).to_equal('http://www.google.com')
        expect(otto_response.headers).to_be_like(response.headers)
        expect(otto_response.cookies).to_be_empty()
        expect(otto_response.text).to_equal('body')
        expect(otto_response.error).to_equal('error')
        expect(otto_response.request_time).to_equal(2.1)

    def test_can_enqueue_url(self):
        otto = TornadoOctopus(cache=False, concurrency=0)

        otto.enqueue('http://www.google.com', None, method='GET', something="else")

        expect(otto.url_queue).to_length(1)

    @patch.object(TornadoOctopus, 'fetch')
    def test_can_enqueue_url_and_fetch(self, fetch_mock):
        otto = TornadoOctopus(cache=True)

        otto.enqueue('http://www.google.com', None, method='GET', something="else")

        expect(otto.url_queue).to_be_empty()
        fetch_mock.assert_called_once_with('http://www.google.com', None, 'GET', something='else')

    def test_can_enqueue_and_get_from_cache(self):
        mock_response = Mock()
        otto = TornadoOctopus(cache=True)
        otto.response_cache.put('http://www.google.com', mock_response)

        def response(url, response):
            self.url = url
            self.response = response

        otto.enqueue('http://www.google.com', response, method='GET')

        expect(otto.url_queue).to_be_empty()
        expect(self.response).not_to_be_null()
        expect(self.response).to_equal(mock_response)

    def test_can_enqueue_and_get_when_cache_miss(self):
        otto = TornadoOctopus(cache=True, auto_start=True)

        def response(url, response):
            self.url = url
            self.response = response

        otto.enqueue('http://www.google.com', response, method='GET')
        otto.wait(2)

        expect(otto.url_queue).to_be_empty()
        expect(self.response).not_to_be_null()

    def test_can_fetch(self):
        otto = TornadoOctopus(cache=False, auto_start=True)
        otto.response_cache.put('http://www.google.com', Mock())

        http_client_mock = Mock()
        otto.http_client = http_client_mock

        otto.fetch('http://www.google.com', None, 'GET')

        expect(otto.running_urls).to_equal(1)
        expect(http_client_mock.fetch.called).to_be_true()

    def test_fetch_gets_the_response_from_cache_if_available(self):
        otto = TornadoOctopus(cache=True, auto_start=True)
        response_mock = Mock()
        otto.response_cache.put('http://www.google.com', response_mock)

        http_client_mock = Mock()
        otto.http_client = http_client_mock

        callback = Mock()

        otto.fetch('http://www.google.com', callback, 'GET')

        expect(otto.running_urls).to_equal(0)
        expect(http_client_mock.fetch.called).to_be_false()
        callback.assert_called_once_with('http://www.google.com', response_mock)

    @patch.object(TornadoOctopus, 'stop')
    def test_handle_request(self, stop_mock):
        otto = TornadoOctopus(cache=False, auto_start=True)

        response = self.get_response()

        callback = Mock()

        handle_request = otto.handle_request('some url', callback)

        handle_request(response)

        expect(otto.running_urls).to_equal(-1)
        expect(callback.called).to_be_true()
        expect(stop_mock.called).to_be_true()

    @patch.object(TornadoOctopus, 'stop')
    def test_handle_request_when_queue_has_no_items(self, stop_mock):
        otto = TornadoOctopus(cache=True, auto_start=True)
        otto.response_cache = Mock()

        response = self.get_response()

        callback = Mock()

        handle_request = otto.handle_request('some url', callback)

        handle_request(response)

        expect(otto.running_urls).to_equal(-1)
        expect(callback.called).to_be_true()
        expect(stop_mock.called).to_be_true()
        expect(otto.response_cache.put.called).to_be_true()

    def test_handle_request_when_queue_has_no_items_but_running_urls(self):
        otto = TornadoOctopus(cache=True, auto_start=True)
        otto.response_cache = Mock()
        otto.running_urls = 10

        response = self.get_response()

        callback = Mock()

        handle_request = otto.handle_request('some url', callback)

        handle_request(response)

        expect(otto.running_urls).to_equal(9)
        expect(callback.called).to_be_true()
        expect(otto.response_cache.put.called).to_be_true()

    @patch.object(TornadoOctopus, 'fetch')
    def test_handle_request_when_queue_has_items(self, fetch_mock):
        otto = TornadoOctopus(cache=False, auto_start=True)

        handler_mock = Mock()

        otto.url_queue.append(
            ('other url', handler_mock, 'POST', {'foo': 'bar'})
        )

        response = self.get_response()
        callback = Mock()

        handle_request = otto.handle_request('some url', callback)
        handle_request(response)

        expect(otto.running_urls).to_equal(-1)
        expect(otto.url_queue).to_be_empty()
        expect(callback.called).to_be_true()
        fetch_mock.assert_called_once_with('other url', handler_mock, 'POST', foo='bar')

    def test_can_handle_wait_timeout(self):
        otto = TornadoOctopus(cache=False, auto_start=True)
        otto.ioloop = Mock()

        otto.handle_wait_timeout(1, None)

        expect(otto.ioloop.stop.called).to_be_true()

    def test_can_stop(self):
        otto = TornadoOctopus(cache=False, auto_start=True)
        otto.ioloop = Mock()

        otto.stop()

        expect(otto.ioloop.stop.called).to_be_true()

    @patch.object(logging, 'debug')
    def test_can_wait_when_no_urls(self, logging_mock):
        otto = TornadoOctopus(cache=False, auto_start=True)

        otto.wait()

        logging_mock.assert_calls('No urls to wait for. Returning immediately.')

    def test_can_wait_when_urls_and_timeout(self):
        otto = TornadoOctopus(cache=False, auto_start=True)
        otto.ioloop = Mock()
        otto.running_urls = 10

        otto.wait()

        expect(otto.ioloop.set_blocking_signal_threshold.called)

    @patch.object(logging, 'debug')
    def test_can_wait_when_urls_and_no_timeout(self, logging_mock):
        otto = TornadoOctopus(cache=False, auto_start=True)
        otto.ioloop = Mock()
        otto.running_urls = 10

        otto.wait(0)

        logging_mock.assert_calls('Waiting for urls to be retrieved.')

    def test_can_get_many_urls(self):
        urls = [
            'http://www.globo.com',
            'http://www.twitter.com',
            'http://www.facebook.com'
        ]
        otto = TornadoOctopus(concurrency=4, auto_start=True)

        def handle_url_response(url, response):
            self.responses[url] = response

        for url in urls:
            otto.enqueue(url, handle_url_response)

        otto.wait(2)

        expect(self.responses).to_length(3)

        for url in urls:
            expect(self.responses).to_include(url)
            expect(self.responses[url].status_code).to_equal(200)

    def test_can_handle_invalid_urls(self):
        url = 'http://kagdjdkjgka.fk'
        otto = TornadoOctopus(concurrency=1, auto_start=True)

        def handle_url_response(url, response):
            self.response = response

        otto.enqueue(url, handle_url_response)

        otto.wait(5)

        expect(self.response).not_to_be_null()
        expect(self.response.status_code).to_equal(599)
        expect(self.response.text).to_be_null()
        expect(self.response.error).not_to_be_null()

    def test_can_handle_timeouts(self):
        url = 'http://baidu.com'
        otto = TornadoOctopus(concurrency=1, request_timeout_in_seconds=0.1, auto_start=True)

        def handle_url_response(url, response):
            self.response = response

        otto.enqueue(url, handle_url_response)

        otto.wait(5)

        expect(self.response.status_code).to_equal(599)
        expect(self.response.text).to_be_null()
        expect(self.response.error).not_to_be_null()

    @patch.object(logging, 'exception')
    def test_can_handle_exception(self, log_mock):
        url = 'http://www.globo.com'

        otto = TornadoOctopus(concurrency=4, auto_start=True)

        def handle_url_response(url, response):
            raise RuntimeError(url)

        otto.enqueue(url, handle_url_response)

        otto.wait(2)

        log_mock.assert_called_once_with('Error calling callback for http://www.globo.com.')