text:
package org.apache.geronimo.jee.deployment;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *
 *                 Refers to either another module running in the server, or
 *                 an entry in the server's Repository.  In either case this effectively uses a
 *                 URI.
 *
 *                 When this is pointing to a repository entry, the URI must have a form
 *                 acceptable to the repository, which is currently a URI consisting of
 *                 Maven-style identifiers separated by slashes (groupId/artifactId/version/type,
 *                 for example, the URI "postgresql/postgresql-8.0-jdbc/313/jar" for a file like
 *                 "repository/postgresql/postgresql-8.0-jdbc-313.jar").
 *
 *                 When this is pointing to a module, the URI should match the
 *                 module's moduleId.  This also looks
 *                 like a Maven-style URI discussed above.
 *
 *                 The artifactType element can take either a straight URI (as in the examples
 *                 above), or maven-style identifier fragments (groupId, type, artifactId, and
 *                 version), which it will compose into a URI by adding up the fragments with
 *                 slashes in between.
 *
 *                 There is a correspondence between the xml format and a URI.  For example, the URI
 *
 *                 postgresql/postgresql-8.0-jdbc/313/jar
 *
 *                 corresponds to the xml:
 *
 *                 <groupId>postgresql</groupId>
 *                 <artifactId>postgresql-8.0-jdbc</artifactId>
 *                 <version>313</version>
 *                 <type>jar</type>
 *
 *
 *
 *
Java class for artifactType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="artifactType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="groupId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="artifactId" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="version" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 * @version $Rev$ $Date$
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "artifactType", propOrder = {
    "groupId",
    "artifactId",
    "version",
    "type"
})
public class Artifact
    implements Serializable
{

    private final static long serialVersionUID = 12343L;
    protected String groupId;
    @XmlElement(required = true)
    protected String artifactId;
    protected String version;
    protected String type;

    /**
     * Gets the value of the groupId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getGroupId() {
        return groupId;
    }

    /**
     * Sets the value of the groupId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setGroupId(String value) {
        this.groupId = value;
    }

    /**
     * Gets the value of the artifactId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getArtifactId() {
        return artifactId;
    }

    /**
     * Sets the value of the artifactId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setArtifactId(String value) {
        this.artifactId = value;
    }

    /**
     * Gets the value of the version property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getVersion() {
        return version;
    }

    /**
     * Sets the value of the version property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setVersion(String value) {
        if (value == null || value.length() == 0)
            this.version = null;
        else
            this.version = value;
    }

    /**
     * Gets the value of the type property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getType() {
        return type;
    }

    /**
     * Sets the value of the type property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setType(String value) {
        if (value == null || value.length() == 0)
            this.type = null;
        else
            this.type = value;
    }

    /**
     *
     * @return String representation of Artifact
     */
    public String toString() {
        StringBuffer buffer = new StringBuffer();

        if (groupId != null) {
            buffer.append(groupId);
        }
        buffer.append("/");

        if (artifactId != null) {
            buffer.append(artifactId);
        }
        buffer.append("/");

        if (version != null) {
            buffer.append(version);
        }
        buffer.append("/");

        if (type != null) {
            buffer.append(type);
        }
        return buffer.toString();
    }

    /**
     *
     */
    public boolean equals(Object o) {

        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        final Artifact that = (Artifact) o;

        if (groupId != null ? !groupId.equals(that.groupId) : that.groupId != null) return false;
        if (artifactId != null ? !artifactId.equals(that.artifactId) : that.artifactId != null) return false;
        if (version != null ? !version.equals(that.version) : that.version != null) return false;
        if (type != null ? !type.equals(that.type) : that.type != null) return false;

        return true;
    }

    /**
     *
     */
    public int hashCode() {
        int result;
        result = (groupId != null ? groupId.hashCode() : 0);
        result = 29 * result + (artifactId != null? artifactId.hashCode() : 0);
        result = 29 * result + (version != null ? version.hashCode() : 0);
        result = 29 * result + (type != null ? type.hashCode() : 0);
        return result;
    }

}


text:
package rest

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric/common/tools/configtxlator/sanitycheck"
	"github.com/hyperledger/fabric/common/tools/configtxlator/update"
	cb "github.com/hyperledger/fabric/protos/common"
)

func fieldBytes(fieldName string, r *http.Request) ([]byte, error) {
	fieldFile, _, err := r.FormFile(fieldName)
	if err != nil {
		return nil, err
	}
	defer fieldFile.Close()

	return ioutil.ReadAll(fieldFile)
}

func fieldConfigProto(fieldName string, r *http.Request) (*cb.Config, error) {
	fieldBytes, err := fieldBytes(fieldName, r)
	if err != nil {
		return nil, fmt.Errorf("error reading field bytes: %s", err)
	}

	config := &cb.Config{}
	err = proto.Unmarshal(fieldBytes, config)
	if err != nil {
		return nil, fmt.Errorf("error unmarshaling field bytes: %s", err)
	}

	return config, nil
}

func ComputeUpdateFromConfigs(w http.ResponseWriter, r *http.Request) {
	originalConfig, err := fieldConfigProto("original", r)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "Error with field 'original': %s\n", err)
		return
	}

	updatedConfig, err := fieldConfigProto("updated", r)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "Error with field 'updated': %s\n", err)
		return
	}

	configUpdate, err := update.Compute(originalConfig, updatedConfig)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "Error computing update: %s\n", err)
		return
	}

	configUpdate.ChannelId = r.FormValue("channel")

	encoded, err := proto.Marshal(configUpdate)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "Error marshaling config update: %s\n", err)
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "application/octet-stream")
	w.Write(encoded)
}

func SanityCheckConfig(w http.ResponseWriter, r *http.Request) {
	buf, err := ioutil.ReadAll(r.Body)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintln(w, err)
		return
	}

	config := &cb.Config{}
	err = proto.Unmarshal(buf, config)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "Error unmarshaling data to common.Config': %s\n", err)
		return
	}

	fmt.Printf("Sanity checking %+v\n", config)
	sanityCheckMessages, err := sanitycheck.Check(config)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "Error performing sanity check: %s\n", err)
		return
	}

	resBytes, err := json.Marshal(sanityCheckMessages)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "Error marshaling result to JSON: %s\n", err)
		return
	}
	w.WriteHeader(http.StatusOK)
	w.Write(resBytes)
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.causeway.core.metamodel.facets.object.value.vsp;

import org.apache.causeway.applib.value.semantics.ValueSemanticsProvider;
import org.apache.causeway.commons.collections.Can;
import org.apache.causeway.core.metamodel.facetapi.FacetHolder;
import org.apache.causeway.core.metamodel.facets.object.value.ValueFacetAbstract;

public class ValueFacetUsingSemanticsProvider<T>
extends ValueFacetAbstract<T> {

    public static <T> ValueFacetUsingSemanticsProvider<T> create(
            final Class<T> valueClass,
            final Can<ValueSemanticsProvider<T>> valueSemantics,
            final FacetHolder holder) {
        return new ValueFacetUsingSemanticsProvider<T>(valueClass, valueSemantics, holder);
    }

    protected ValueFacetUsingSemanticsProvider(
            final Class<T> valueClass,
            final Can<ValueSemanticsProvider<T>> valueSemantics,
            final FacetHolder holder) {
        super(valueClass, valueSemantics, holder, Precedence.DEFAULT);
    }

}


text:
module RocketPants
  # Makes it easier to both throw named exceptions (corresponding to
  # error states in the response) and to then process the response into
  # something useable in the response.
  module ErrorHandling
    extend ActiveSupport::Concern

    included do
      rescue_from RocketPants::Error, :with => :render_error
      class_attribute :error_mapping
      self.error_mapping = {}
    end

    module ClassMethods

      # Declares that a given error class (e.g. ActiveRecord::RecordNotFound)
      # should map to a second value - either an Exception class Or, more usefully,
      # a callable object.
      # @param [Class] from the exception class to map from.
      # @param [Class, #call] to the callable to map to, or a callback block.
      def map_error!(from, to = nil, &blk)
        to = (to || blk)
        raise ArgumentError, "Either an option must be provided or a block given." unless to
        error_mapping[from] = (to || blk)
        rescue_from from, :with => :render_error
      end

    end

    # Dynamically looks up and then throws the error given by a symbolic name.
    # Optionally takes a string message argument and a hash of 'context'.
    # @overload error!(name, context = {})
    #   @param [Symbol] name the name of the exception, looked up using RocketPants::Errors
    #   @param [Hash{Symbol => Object}] context the options passed to the error message translation.
    # @overload error!(name, message, context = {})
    #   @param [Symbol] name the name of the exception, looked up using RocketPants::Errors
    #   @param [String] message an optional message describing the error
    #   @param [Hash{Symbol => Object}] context the options passed to the error message translation.
    # @raise [RocketPants::Error] the error from the given options
    def error!(name, *args)
      context   = args.extract_options!
      klass     = Errors[name] || Error
      exception = klass.new(*args).tap { |e| e.context = context }
      raise exception
    end

    # From a given exception, gets the corresponding error message using I18n.
    # It will use context (if defined) on the exception for the I18n context base and
    # will use either the result of Error#error_name (if present) or :system for
    # the name of the error.
    # @param [StandardError] exception the exception to get the message from
    # @return [String] the found error message.
    def lookup_error_message(exception)
      # TODO: Add in notification hooks for non-standard exceptions.
      name    = lookup_error_name(exception)
      message = default_message_for_exception exception
      context = lookup_error_context(exception).reverse_merge(:scope => :"rocket_pants.errors", :default => message)
      I18n.t name, context.except(:metadata)
    end

    def default_message_for_exception(exception)
      if !RocketPants.show_exception_message? || exception.message == exception.class.name
        'An unknown error has occurred.'
      else
        exception.message
      end
    end

    # Lookup error name will automatically handle translating errors to a
    # simpler, symbol representation. It's implemented like this to make it
    # possible to override to a simple format.
    # @param [StandardError] exception the exception to find the name for
    # @return [Symbol] the name of the given error
    def lookup_error_name(exception)
      if exception.respond_to?(:error_name)
        exception.error_name
      else
        :system
      end
    end

    # Returns the error status code for a given exception.
    # @param [StandardError] exception the exception to find the status for
    # @return [Symbol] the name of the given error
    def lookup_error_status(exception)
      exception.respond_to?(:http_status) ? exception.http_status : 500
    end

    # Returns the i18n context for a given exception.
    # @param [StandardError] exception the exception to find the context for
    # @param [Hash] the i18n translation context.
    def lookup_error_context(exception)
      exception.respond_to?(:context) ? exception.context : {}
    end

    def lookup_error_extras(exception)
      {}
    end

    # Returns extra error details for a given object, making it useable
    # for hooking in external exceptions.
    def lookup_error_metadata(exception)
      context = lookup_error_context exception
      context.fetch(:metadata, {}).merge lookup_error_extras(exception)
    end

    # Renders an exception as JSON using a nicer version of the error name and
    # error message, following the typically error standard as laid out in the JSON
    # api design.
    # @param [StandardError] exception the error to render a response for.
    def render_error(exception)
      logger.debug "Rendering error for #{exception.class.name}: #{exception.message}" if logger
      # When a normalised class is present, make sure we
      # convert it to a useable error class.
      normalised_class = exception.class.ancestors.detect do |klass|
        klass < StandardError and error_mapping.has_key?(klass)
      end
      if normalised_class
        mapped = error_mapping[normalised_class]
        if mapped.respond_to?(:call)
          exception = mapped.call(exception)
        else
          exception = mapped.new exception.message
        end
      end
      self.status = lookup_error_status(exception)
      render_json({
        :error             => lookup_error_name(exception).to_s,
        :error_description => lookup_error_message(exception)
      }.merge(lookup_error_metadata(exception)))
    end

  end
end


text:
#include <assert.h>
#include <ctype.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <yara/error.h>
#include <yara/exec.h>
#include <yara/globals.h>
#include <yara/mem.h>
#include <yara/object.h>
#include <yara/utils.h>

////////////////////////////////////////////////////////////////////////////////
// Creates a new object with the given type and identifier. If a parent is
// specified the new object is owned by the parent and it will be destroyed when
// the parent is destroyed. You must not call yr_object_destroy on an objected
// that has a parent, you should destroy the parent instead.
//
int yr_object_create(
    int8_t type,
    const char* identifier,
    YR_OBJECT* parent,
    YR_OBJECT** object)
{
  YR_OBJECT* obj;
  size_t object_size = 0;

  assert(parent != NULL || object != NULL);
  assert(identifier != NULL);

  switch (type)
  {
  case OBJECT_TYPE_STRUCTURE:
    object_size = sizeof(YR_OBJECT_STRUCTURE);
    break;
  case OBJECT_TYPE_ARRAY:
    object_size = sizeof(YR_OBJECT_ARRAY);
    break;
  case OBJECT_TYPE_DICTIONARY:
    object_size = sizeof(YR_OBJECT_DICTIONARY);
    break;
  case OBJECT_TYPE_INTEGER:
    object_size = sizeof(YR_OBJECT);
    break;
  case OBJECT_TYPE_FLOAT:
    object_size = sizeof(YR_OBJECT);
    break;
  case OBJECT_TYPE_STRING:
    object_size = sizeof(YR_OBJECT);
    break;
  case OBJECT_TYPE_FUNCTION:
    object_size = sizeof(YR_OBJECT_FUNCTION);
    break;
  default:
    assert(false);
  }

  obj = (YR_OBJECT*) yr_malloc(object_size);

  if (obj == NULL)
    return ERROR_INSUFFICIENT_MEMORY;

  obj->type = type;
  obj->identifier = yr_strdup(identifier);
  obj->parent = parent;
  obj->data = NULL;

  switch (type)
  {
  case OBJECT_TYPE_INTEGER:
    obj->value.i = YR_UNDEFINED;
    break;
  case OBJECT_TYPE_FLOAT:
    obj->value.d = NAN;
    break;
  case OBJECT_TYPE_STRING:
    obj->value.ss = NULL;
    break;
  case OBJECT_TYPE_STRUCTURE:
    object_as_structure(obj)->members = NULL;
    break;
  case OBJECT_TYPE_ARRAY:
    object_as_array(obj)->items = NULL;
    object_as_array(obj)->prototype_item = NULL;
    break;
  case OBJECT_TYPE_DICTIONARY:
    object_as_dictionary(obj)->items = NULL;
    object_as_dictionary(obj)->prototype_item = NULL;
    break;
  case OBJECT_TYPE_FUNCTION:
    object_as_function(obj)->return_obj = NULL;
    for (int i = 0; i < YR_MAX_OVERLOADED_FUNCTIONS; i++)
    {
      object_as_function(obj)->prototypes[i].arguments_fmt = NULL;
      object_as_function(obj)->prototypes[i].code = NULL;
    }
    break;
  }

  if (obj->identifier == NULL)
  {
    yr_free(obj);
    return ERROR_INSUFFICIENT_MEMORY;
  }

  if (parent != NULL)
  {
    assert(
        parent->type == OBJECT_TYPE_STRUCTURE ||
        parent->type == OBJECT_TYPE_ARRAY ||
        parent->type == OBJECT_TYPE_DICTIONARY ||
        parent->type == OBJECT_TYPE_FUNCTION);

    // Objects with a parent take the canary from it.
    obj->canary = parent->canary;

    switch (parent->type)
    {
    case OBJECT_TYPE_STRUCTURE:
      FAIL_ON_ERROR_WITH_CLEANUP(yr_object_structure_set_member(parent, obj), {
        yr_free((void*) obj->identifier);
        yr_free(obj);
      });
      break;

    case OBJECT_TYPE_ARRAY:
      object_as_array(parent)->prototype_item = obj;
      break;

    case OBJECT_TYPE_DICTIONARY:
      object_as_dictionary(parent)->prototype_item = obj;
      break;

    case OBJECT_TYPE_FUNCTION:
      object_as_function(parent)->return_obj = obj;
      break;
    }
  }

  if (object != NULL)
    *object = obj;

  return ERROR_SUCCESS;
}

void yr_object_set_canary(YR_OBJECT* object, int canary)
{
  object->canary = canary;
}

int yr_object_function_create(
    const char* identifier,
    const char* arguments_fmt,
    const char* return_fmt,
    YR_MODULE_FUNC code,
    YR_OBJECT* parent,
    YR_OBJECT** function)
{
  YR_OBJECT* return_obj;
  YR_OBJECT* o = NULL;
  YR_OBJECT_FUNCTION* f = NULL;

  int8_t return_type;

  // The parent of a function must be a structure.
  assert(parent != NULL && parent->type == OBJECT_TYPE_STRUCTURE);

  switch (*return_fmt)
  {
  case 'i':
    return_type = OBJECT_TYPE_INTEGER;
    break;
  case 's':
    return_type = OBJECT_TYPE_STRING;
    break;
  case 'f':
    return_type = OBJECT_TYPE_FLOAT;
    break;
  default:
    return ERROR_INVALID_FORMAT;
  }

  // Try to find if the structure already has a function
  // with that name. In that case this is a function overload.
  f = object_as_function(yr_object_lookup_field(parent, identifier));

  // Overloaded functions must have the same return type.
  if (f != NULL && return_type != f->return_obj->type)
    return ERROR_WRONG_RETURN_TYPE;

  if (f == NULL)  // Function doesn't exist yet
  {
    FAIL_ON_ERROR(
        yr_object_create(OBJECT_TYPE_FUNCTION, identifier, parent, &o));

    // In case of failure while creating return_obj we don't need to free the
    // previously created "o" object, as it is already associated with its
    // parent and will be destroyed when the parent is destroyed.
    FAIL_ON_ERROR(yr_object_create(return_type, "result", o, &return_obj));

    f = object_as_function(o);
  }

  for (int i = 0; i < YR_MAX_OVERLOADED_FUNCTIONS; i++)
  {
    if (f->prototypes[i].arguments_fmt == NULL)
    {
      f->prototypes[i].arguments_fmt = arguments_fmt;
      f->prototypes[i].code = code;

      break;
    }
  }

  if (function != NULL)
    *function = (YR_OBJECT*) f;

  return ERROR_SUCCESS;
}

int yr_object_from_external_variable(
    YR_EXTERNAL_VARIABLE* external,
    YR_OBJECT** object)
{
  YR_OBJECT* obj;
  int result;
  uint8_t obj_type = 0;

  switch (external->type)
  {
  case EXTERNAL_VARIABLE_TYPE_INTEGER:
  case EXTERNAL_VARIABLE_TYPE_BOOLEAN:
    obj_type = OBJECT_TYPE_INTEGER;
    break;

  case EXTERNAL_VARIABLE_TYPE_FLOAT:
    obj_type = OBJECT_TYPE_FLOAT;
    break;

  case EXTERNAL_VARIABLE_TYPE_STRING:
  case EXTERNAL_VARIABLE_TYPE_MALLOC_STRING:
    obj_type = OBJECT_TYPE_STRING;
    break;

  default:
    assert(false);
  }

  result = yr_object_create(obj_type, external->identifier, NULL, &obj);

  if (result == ERROR_SUCCESS)
  {
    switch (external->type)
    {
    case EXTERNAL_VARIABLE_TYPE_INTEGER:
    case EXTERNAL_VARIABLE_TYPE_BOOLEAN:
      result = yr_object_set_integer(external->value.i, obj, NULL);
      break;

    case EXTERNAL_VARIABLE_TYPE_FLOAT:
      result = yr_object_set_float(external->value.f, obj, NULL);
      break;

    case EXTERNAL_VARIABLE_TYPE_STRING:
    case EXTERNAL_VARIABLE_TYPE_MALLOC_STRING:
      result = yr_object_set_string(
          external->value.s, strlen(external->value.s), obj, NULL);
      break;
    }

    if (result == ERROR_SUCCESS)
    {
      *object = obj;
    }
    else
    {
      yr_object_destroy(obj);
    }
  }

  return result;
}

////////////////////////////////////////////////////////////////////////////////
// Destroy an objects, and any other object that is a child of it. For example,
// destroying a struct will destroy all its members.
//
void yr_object_destroy(YR_OBJECT* object)
{
  YR_STRUCTURE_MEMBER* member;
  YR_STRUCTURE_MEMBER* next_member;
  YR_ARRAY_ITEMS* array_items;
  YR_DICTIONARY_ITEMS* dict_items;

  if (object == NULL)
    return;

  switch (object->type)
  {
  case OBJECT_TYPE_STRUCTURE:
    member = object_as_structure(object)->members;

    while (member != NULL)
    {
      next_member = member->next;
      yr_object_destroy(member->object);
      yr_free(member);
      member = next_member;
    }
    break;

  case OBJECT_TYPE_STRING:
    if (object->value.ss != NULL)
      yr_free(object->value.ss);
    break;

  case OBJECT_TYPE_ARRAY:
    if (object_as_array(object)->prototype_item != NULL)
      yr_object_destroy(object_as_array(object)->prototype_item);

    array_items = object_as_array(object)->items;

    if (array_items != NULL)
    {
      for (int i = 0; i < array_items->length; i++)
        if (array_items->objects[i] != NULL)
          yr_object_destroy(array_items->objects[i]);
    }

    yr_free(array_items);
    break;

  case OBJECT_TYPE_DICTIONARY:
    if (object_as_dictionary(object)->prototype_item != NULL)
      yr_object_destroy(object_as_dictionary(object)->prototype_item);

    dict_items = object_as_dictionary(object)->items;

    if (dict_items != NULL)
    {
      for (int i = 0; i < dict_items->used; i++)
      {
        if (dict_items->objects[i].key != NULL)
          yr_free(dict_items->objects[i].key);

        if (dict_items->objects[i].obj != NULL)
          yr_object_destroy(dict_items->objects[i].obj);
      }
    }

    yr_free(dict_items);
    break;

  case OBJECT_TYPE_FUNCTION:
    yr_object_destroy(object_as_function(object)->return_obj);
    break;
  }

  yr_free((void*) object->identifier);
  yr_free(object);
}

YR_OBJECT* yr_object_lookup_field(YR_OBJECT* object, const char* field_name)
{
  YR_STRUCTURE_MEMBER* member;

  assert(object != NULL);
  assert(object->type == OBJECT_TYPE_STRUCTURE);

  member = object_as_structure(object)->members;

  while (member != NULL)
  {
    if (strcmp(member->object->identifier, field_name) == 0)
      return member->object;

    member = member->next;
  }

  return NULL;
}

static YR_OBJECT* _yr_object_lookup(
    YR_OBJECT* object,
    int flags,
    const char* pattern,
    va_list args)
{
  YR_OBJECT* obj = object;

  const char* p = pattern;
  const char* key = NULL;

  char str[256];

  int i;
  int index = -1;

  while (obj != NULL)
  {
    i = 0;

    while (*p != '\0' && *p != '.' && *p != '[' && i < sizeof(str) - 1)
    {
      str[i++] = *p++;
    }

    str[i] = '\0';

    if (obj->type != OBJECT_TYPE_STRUCTURE)
      return NULL;

    obj = yr_object_lookup_field(obj, str);

    if (obj == NULL)
      return NULL;

    if (*p == '[')
    {
      p++;

      if (*p == '%')
      {
        p++;

        switch (*p++)
        {
        case 'i':
          index = va_arg(args, int);
          break;
        case 's':
          key = va_arg(args, const char*);
          break;

        default:
          return NULL;
        }
      }
      else if (*p >= '0' && *p <= '9')
      {
        index = (int) strtol(p, (char**) &p, 10);
      }
      else if (*p == '"')
      {
        i = 0;
        p++;  // skip the opening quotation mark

        while (*p != '"' && *p != '\0' && i < sizeof(str) - 1) str[i++] = *p++;

        str[i] = '\0';
        p++;  // skip the closing quotation mark
        key = str;
      }
      else
      {
        return NULL;
      }

      assert(*p == ']');
      p++;
      assert(*p == '.' || *p == '\0');

      switch (obj->type)
      {
      case OBJECT_TYPE_ARRAY:
        assert(index != -1);
        obj = yr_object_array_get_item(obj, flags, index);
        break;

      case OBJECT_TYPE_DICTIONARY:
        assert(key != NULL);
        obj = yr_object_dict_get_item(obj, flags, key);
        break;
      }
    }

    if (*p == '\0')
      break;

    p++;
  }

  return obj;
}

YR_OBJECT* yr_object_lookup(
    YR_OBJECT* object,
    int flags,
    const char* pattern,
    ...)
{
  YR_OBJECT* result;

  va_list args;
  va_start(args, pattern);

  result = _yr_object_lookup(object, flags, pattern, args);

  va_end(args);

  return result;
}

int yr_object_copy(YR_OBJECT* object, YR_OBJECT** object_copy)
{
  YR_OBJECT* copy;
  YR_OBJECT* o;

  YR_STRUCTURE_MEMBER* structure_member;

  *object_copy = NULL;

  FAIL_ON_ERROR(
      yr_object_create(object->type, object->identifier, NULL, &copy));

  copy->canary = object->canary;

  switch (object->type)
  {
  case OBJECT_TYPE_INTEGER:
    copy->value.i = object->value.i;
    break;

  case OBJECT_TYPE_FLOAT:
    copy->value.d = object->value.d;
    break;

  case OBJECT_TYPE_STRING:

    if (object->value.ss != NULL)
      copy->value.ss = ss_dup(object->value.ss);
    else
      copy->value.ss = NULL;

    break;

  case OBJECT_TYPE_FUNCTION:

    FAIL_ON_ERROR_WITH_CLEANUP(
        yr_object_copy(
            object_as_function(object)->return_obj,
            &object_as_function(copy)->return_obj),
        // cleanup
        yr_object_destroy(copy));

    for (int i = 0; i < YR_MAX_OVERLOADED_FUNCTIONS; i++)
      object_as_function(copy)->prototypes[i] =
          object_as_function(object)->prototypes[i];

    break;

  case OBJECT_TYPE_STRUCTURE:

    structure_member = object_as_structure(object)->members;

    while (structure_member != NULL)
    {
      FAIL_ON_ERROR_WITH_CLEANUP(
          yr_object_copy(structure_member->object, &o),
          yr_object_destroy(copy));

      FAIL_ON_ERROR_WITH_CLEANUP(yr_object_structure_set_member(copy, o),
                                 // cleanup
                                 yr_free(o);
                                 yr_object_destroy(copy));

      structure_member = structure_member->next;
    }

    break;

  case OBJECT_TYPE_ARRAY:

    FAIL_ON_ERROR_WITH_CLEANUP(
        yr_object_copy(object_as_array(object)->prototype_item, &o),
        yr_object_destroy(copy));

    object_as_array(copy)->prototype_item = o;

    break;

  case OBJECT_TYPE_DICTIONARY:

    FAIL_ON_ERROR_WITH_CLEANUP(
        yr_object_copy(object_as_dictionary(object)->prototype_item, &o),
        yr_object_destroy(copy));

    object_as_dictionary(copy)->prototype_item = o;

    break;

  default:
    assert(false);
  }

  *object_copy = copy;

  return ERROR_SUCCESS;
}

int yr_object_structure_set_member(YR_OBJECT* object, YR_OBJECT* member)
{
  YR_STRUCTURE_MEMBER* sm;

  assert(object->type == OBJECT_TYPE_STRUCTURE);

  // Check if the object already have a member with the same identifier

  if (yr_object_lookup_field(object, member->identifier) != NULL)
    return ERROR_DUPLICATED_STRUCTURE_MEMBER;

  sm = (YR_STRUCTURE_MEMBER*) yr_malloc(sizeof(YR_STRUCTURE_MEMBER));

  if (sm == NULL)
    return ERROR_INSUFFICIENT_MEMORY;

  member->parent = object;
  sm->object = member;
  sm->next = object_as_structure(object)->members;

  object_as_structure(object)->members = sm;

  return ERROR_SUCCESS;
}

int yr_object_array_length(YR_OBJECT* object)
{
  YR_OBJECT_ARRAY* array;

  assert(object->type == OBJECT_TYPE_ARRAY);
  array = object_as_array(object);

  if (array->items == NULL)
    return 0;

  return array->items->length;
}

YR_OBJECT* yr_object_array_get_item(YR_OBJECT* object, int flags, int index)
{
  YR_OBJECT* result = NULL;
  YR_OBJECT_ARRAY* array;

  assert(object->type == OBJECT_TYPE_ARRAY);

  if (index < 0)
    return NULL;

  array = object_as_array(object);

  if (array->items != NULL && array->items->capacity > index)
    result = array->items->objects[index];

  if (result == NULL && flags & OBJECT_CREATE)
  {
    yr_object_copy(array->prototype_item, &result);

    if (result != NULL)
      yr_object_array_set_item(object, result, index);
  }

  return result;
}

int yr_object_array_set_item(YR_OBJECT* object, YR_OBJECT* item, int index)
{
  YR_OBJECT_ARRAY* array;

  int capacity;

  assert(index >= 0);
  assert(object->type == OBJECT_TYPE_ARRAY);

  array = object_as_array(object);

  if (array->items == NULL)
  {
    capacity = 64;

    while (capacity <= index) capacity *= 2;

    array->items = (YR_ARRAY_ITEMS*) yr_malloc(
        sizeof(YR_ARRAY_ITEMS) + capacity * sizeof(YR_OBJECT*));

    if (array->items == NULL)
      return ERROR_INSUFFICIENT_MEMORY;

    memset(array->items->objects, 0, capacity * sizeof(YR_OBJECT*));

    array->items->capacity = capacity;
    array->items->length = 0;
  }
  else if (index >= array->items->capacity)
  {
    capacity = array->items->capacity * 2;

    while (capacity <= index) capacity *= 2;

    array->items = (YR_ARRAY_ITEMS*) yr_realloc(
        array->items, sizeof(YR_ARRAY_ITEMS) + capacity * sizeof(YR_OBJECT*));

    if (array->items == NULL)
      return ERROR_INSUFFICIENT_MEMORY;

    for (int i = array->items->capacity; i < capacity; i++)
      array->items->objects[i] = NULL;

    array->items->capacity = capacity;
  }

  item->parent = object;
  array->items->objects[index] = item;

  if (index >= array->items->length)
    array->items->length = index + 1;

  return ERROR_SUCCESS;
}

YR_OBJECT* yr_object_dict_get_item(
    YR_OBJECT* object,
    int flags,
    const char* key)
{
  YR_OBJECT* result = NULL;
  YR_OBJECT_DICTIONARY* dict;

  assert(object->type == OBJECT_TYPE_DICTIONARY);

  dict = object_as_dictionary(object);

  if (dict->items != NULL)
  {
    for (int i = 0; i < dict->items->used; i++)
    {
      if (strcmp(dict->items->objects[i].key->c_string, key) == 0)
        result = dict->items->objects[i].obj;
    }
  }

  if (result == NULL && flags & OBJECT_CREATE)
  {
    yr_object_copy(dict->prototype_item, &result);

    if (result != NULL)
      yr_object_dict_set_item(object, result, key);
  }

  return result;
}

int yr_object_dict_set_item(YR_OBJECT* object, YR_OBJECT* item, const char* key)
{
  YR_OBJECT_DICTIONARY* dict;

  int count;

  assert(object->type == OBJECT_TYPE_DICTIONARY);

  dict = object_as_dictionary(object);

  if (dict->items == NULL)
  {
    count = 64;

    dict->items = (YR_DICTIONARY_ITEMS*) yr_malloc(
        sizeof(YR_DICTIONARY_ITEMS) + count * sizeof(dict->items->objects[0]));

    if (dict->items == NULL)
      return ERROR_INSUFFICIENT_MEMORY;

    memset(dict->items->objects, 0, count * sizeof(dict->items->objects[0]));

    dict->items->free = count;
    dict->items->used = 0;
  }
  else if (dict->items->free == 0)
  {
    count = dict->items->used * 2;
    dict->items = (YR_DICTIONARY_ITEMS*) yr_realloc(
        dict->items,
        sizeof(YR_DICTIONARY_ITEMS) + count * sizeof(dict->items->objects[0]));

    if (dict->items == NULL)
      return ERROR_INSUFFICIENT_MEMORY;

    for (int i = dict->items->used; i < count; i++)
    {
      dict->items->objects[i].key = NULL;
      dict->items->objects[i].obj = NULL;
    }

    dict->items->free = dict->items->used;
  }

  item->parent = object;

  dict->items->objects[dict->items->used].key = ss_new(key);
  dict->items->objects[dict->items->used].obj = item;

  dict->items->used++;
  dict->items->free--;

  return ERROR_SUCCESS;
}

bool yr_object_has_undefined_value(YR_OBJECT* object, const char* field, ...)
{
  YR_OBJECT* field_obj;

  va_list args;
  va_start(args, field);

  if (field != NULL)
    field_obj = _yr_object_lookup(object, 0, field, args);
  else
    field_obj = object;

  va_end(args);

  if (field_obj == NULL)
    return true;

  switch (field_obj->type)
  {
  case OBJECT_TYPE_FLOAT:
    return yr_isnan(field_obj->value.d);
  case OBJECT_TYPE_STRING:
    return field_obj->value.ss == NULL;
  case OBJECT_TYPE_INTEGER:
    return field_obj->value.i == YR_UNDEFINED;
  }

  return false;
}

int64_t yr_object_get_integer(YR_OBJECT* object, const char* field, ...)
{
  YR_OBJECT* integer_obj;

  va_list args;
  va_start(args, field);

  if (field != NULL)
    integer_obj = _yr_object_lookup(object, 0, field, args);
  else
    integer_obj = object;

  va_end(args);

  if (integer_obj == NULL)
    return YR_UNDEFINED;

  assertf(
      integer_obj->type == OBJECT_TYPE_INTEGER,
      "type of \"%s\" is not integer\n",
      field);

  return integer_obj->value.i;
}

double yr_object_get_float(YR_OBJECT* object, const char* field, ...)
{
  YR_OBJECT* double_obj;

  va_list args;
  va_start(args, field);

  if (field != NULL)
    double_obj = _yr_object_lookup(object, 0, field, args);
  else
    double_obj = object;

  va_end(args);

  if (double_obj == NULL)
    return NAN;

  assertf(
      double_obj->type == OBJECT_TYPE_FLOAT,
      "type of \"%s\" is not double\n",
      field);

  return double_obj->value.d;
}

SIZED_STRING* yr_object_get_string(YR_OBJECT* object, const char* field, ...)
{
  YR_OBJECT* string_obj;

  va_list args;
  va_start(args, field);

  if (field != NULL)
    string_obj = _yr_object_lookup(object, 0, field, args);
  else
    string_obj = object;

  va_end(args);

  if (string_obj == NULL)
    return NULL;

  assertf(
      string_obj->type == OBJECT_TYPE_STRING,
      "type of \"%s\" is not string\n",
      field);

  return string_obj->value.ss;
}

int yr_object_set_integer(
    int64_t value,
    YR_OBJECT* object,
    const char* field,
    ...)
{
  YR_OBJECT* integer_obj;

  va_list args;
  va_start(args, field);

  if (field != NULL)
    integer_obj = _yr_object_lookup(object, OBJECT_CREATE, field, args);
  else
    integer_obj = object;

  va_end(args);

  if (integer_obj == NULL)
  {
    if (field != NULL)
      return ERROR_INSUFFICIENT_MEMORY;
    else
      return ERROR_INVALID_ARGUMENT;
  }

  assert(integer_obj->type == OBJECT_TYPE_INTEGER);

  integer_obj->value.i = value;

  return ERROR_SUCCESS;
}

int yr_object_set_float(double value, YR_OBJECT* object, const char* field, ...)
{
  YR_OBJECT* double_obj;

  va_list args;
  va_start(args, field);

  if (field != NULL)
    double_obj = _yr_object_lookup(object, OBJECT_CREATE, field, args);
  else
    double_obj = object;

  va_end(args);

  if (double_obj == NULL)
  {
    if (field != NULL)
      return ERROR_INSUFFICIENT_MEMORY;
    else
      return ERROR_INVALID_ARGUMENT;
  }

  assert(double_obj->type == OBJECT_TYPE_FLOAT);

  double_obj->value.d = value;

  return ERROR_SUCCESS;
}

int yr_object_set_string(
    const char* value,
    size_t len,
    YR_OBJECT* object,
    const char* field,
    ...)
{
  YR_OBJECT* string_obj;

  va_list args;
  va_start(args, field);

  if (field != NULL)
    string_obj = _yr_object_lookup(object, OBJECT_CREATE, field, args);
  else
    string_obj = object;

  va_end(args);

  if (string_obj == NULL)
  {
    if (field != NULL)
      return ERROR_INSUFFICIENT_MEMORY;
    else
      return ERROR_INVALID_ARGUMENT;
  }

  assert(string_obj->type == OBJECT_TYPE_STRING);

  if (string_obj->value.ss != NULL)
    yr_free(string_obj->value.ss);

  if (value != NULL)
  {
    string_obj->value.ss = (SIZED_STRING*) yr_malloc(
        len + sizeof(SIZED_STRING));

    if (string_obj->value.ss == NULL)
      return ERROR_INSUFFICIENT_MEMORY;

    string_obj->value.ss->length = (uint32_t) len;
    string_obj->value.ss->flags = 0;

    memcpy(string_obj->value.ss->c_string, value, len);
    string_obj->value.ss->c_string[len] = '\0';
  }
  else
  {
    string_obj->value.ss = NULL;
  }

  return ERROR_SUCCESS;
}

YR_OBJECT* yr_object_get_root(YR_OBJECT* object)
{
  YR_OBJECT* o = object;

  while (o->parent != NULL) o = o->parent;

  return o;
}

YR_API void yr_object_print_data(
    YR_OBJECT* object,
    int indent,
    int print_identifier)
{
  YR_DICTIONARY_ITEMS* dict_items;
  YR_STRUCTURE_MEMBER* member;

  char indent_spaces[32];

  indent = yr_min(indent, sizeof(indent_spaces) - 1);

  memset(indent_spaces, '\t', indent);
  indent_spaces[indent] = '\0';

  if (print_identifier && object->type != OBJECT_TYPE_FUNCTION)
    printf("%s%s", indent_spaces, object->identifier);

  switch (object->type)
  {
  case OBJECT_TYPE_FLOAT:
    if (object->value.i != YR_UNDEFINED)
      printf(" = %f", object->value.d);
    else
      printf(" = YR_UNDEFINED");

    break;

  case OBJECT_TYPE_INTEGER:

    if (object->value.i != YR_UNDEFINED)
      printf(" = %" PRId64, object->value.i);
    else
      printf(" = YR_UNDEFINED");

    break;

  case OBJECT_TYPE_STRING:

    if (object->value.ss != NULL)
    {
      printf(" = \"");

      for (size_t l = 0; l < object->value.ss->length; l++)
      {
        char c = object->value.ss->c_string[l];

        if (isprint((unsigned char) c))
          printf("%c", c);
        else
          printf("\\x%02x", (unsigned char) c);
      }

      printf("\"");
    }
    else
    {
      printf(" = YR_UNDEFINED");
    }

    break;

  case OBJECT_TYPE_STRUCTURE:

    member = object_as_structure(object)->members;

    while (member != NULL)
    {
      if (member->object->type != OBJECT_TYPE_FUNCTION)
      {
        printf("\n");
        yr_object_print_data(member->object, indent + 1, 1);
      }
      member = member->next;
    }

    break;

  case OBJECT_TYPE_ARRAY:
    for (int i = 0; i < yr_object_array_length(object); i++)
    {
      YR_OBJECT* o = yr_object_array_get_item(object, 0, i);

      if (o != NULL)
      {
        printf("\n%s\t[%d]", indent_spaces, i);
        yr_object_print_data(o, indent + 1, 0);
      }
    }
    break;

  case OBJECT_TYPE_DICTIONARY:

    dict_items = object_as_dictionary(object)->items;

    if (dict_items != NULL)
    {
      for (int i = 0; i < dict_items->used; i++)
      {
        printf("\n%s\t%s", indent_spaces, dict_items->objects[i].key->c_string);

        yr_object_print_data(dict_items->objects[i].obj, indent + 1, 0);
      }
    }

    break;
  }
}


text:
var appc = require('../index');

global.should = null;
global.should = require('should');

function MockConfig() {
	this.get = function (s, d) {
		return d;
	};
}

describe('jdk', function () {
	it('namespace exists', function () {
		appc.should.have.property('jdk');
		appc.jdk.should.be.an.Object;
	});

	describe('#detect()', function () {
		it('should return valid result without specifying a config or options', function (done) {
			this.timeout(5000);

			function checkJDK(jdk) {
				should(jdk).be.an.Object;
				should(jdk).have.properties('home', 'version', 'build', 'executables', 'architecture');
				should(jdk.home).be.a.String;
				should(jdk.version).be.a.String;
				should(jdk.version).match(/^(\d+\.)?(\d+\.)?(\*|\d+)$/);
				should(jdk.build).be.a.String;
				should(jdk.build).match(/^\d+$/);
				should(jdk.executables).be.a.Object;
				should(jdk.architecture).be.a.String;
				should(jdk.architecture).match(/^(32|64)bit/);
			}

			appc.jdk.detect(function (result) {
				should(result).be.an.Object;

				should(result).have.keys('jdks', 'home', 'version', 'build', 'executables', 'issues', 'architecture');

				should(result.jdks).be.an.Object;
				Object.keys(result.jdks).forEach(function (jdk) {
					checkJDK(result.jdks[jdk]);
				});

				checkJDK(result);

				if (result.issues !== null) {
					result.issues.should.be.an.Array;
				}

				done();
			});
		});

		it('should return valid result with a config and without specifying options', function (done) {
			this.timeout(5000);

			appc.jdk.detect(new MockConfig, function (result) {
				result.should.be.an.Object;
				done();
			});
		});

		it('should return valid result with a config and options', function (done) {
			this.timeout(5000);

			appc.jdk.detect(new MockConfig, { bypassCache: true }, function (result) {
				result.should.be.an.Object;
				done();
			});
		});
	});
});


text:
Spinnaker
---------

Spinnaker is an open source, multi-cloud continuous delivery platform
that helps you release software updates with high velocity and
confidence. It provides two core features: cluster management to view
and manage your resources in the cloud and deployment management to
construct and manage continuous delivery
workflows [@hid-sp18-602-www-spinnaker-io]. The main advantage of
Spinnaker is it holds a modern software development concept of
continuous delivery that is application updates should be delivered when
they are ready, instead of on a fixed schedule. Also, it improves the
speed, stability of application deployment processes along with
supporting deployments across different platforms by several different
cloud providers.

Although the project Spinnaker first started out with Netflix and then
google joined in 2014, the Spinnaker community now includes dozens of
organizations such as Microsoft, Oracle, Target, Veritas, Schibsted,
Armory and Kenzan [@hid-sp18-602-www-spinnaker-gc].


text:
Change source language

            <form role="form">
                Language:

                <select size="6" ng-model="selected.lang"
                        ng-options="lang as info['name'] for (lang, info) in appinfo.translations"
                        class="form-control">
                </select>
            </form>

    <button class="btn btn-success" ng-click="ok()">OK</button>
    <button class="btn btn-warning" ng-click="cancel()">Cancel</button>


text:
package org.rostlab.gemudb.service;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.biojava3.core.sequence.ProteinSequence;
import org.biojava3.core.sequence.io.FastaReaderHelper;
import org.rostlab.gemudb.dao.MutationDao;
import org.rostlab.gemudb.dao.SequenceDao;
import org.rostlab.gemudb.dom.Mutation;
import org.rostlab.gemudb.dom.MutationType;
import org.rostlab.gemudb.dom.Sequence;
import org.rostlab.gemudb.util.AminoLookup;
import org.rostlab.gemudb.util.ExtentionFilenameFilter;

public class MutationImportServiceImpl implements MutationImportService {
	private MutationDao mutationDao;
	private SequenceDao sequenceDao;

	@Override
	public void importMutation(File pathToDir) {
		if (pathToDir.exists() == false || pathToDir.isDirectory() == false) {
			new IllegalArgumentException(
					"File dosn't exist or is not a Directory");
		} else {
			for (File file : pathToDir.listFiles(new ExtentionFilenameFilter(
					new String[] { "tar.gz", "tar" }))) {
				// read fasta
				String archiveName = FilenameUtils.removeExtension(file
						.getName());
				archiveName = FilenameUtils.removeExtension(archiveName);
				final File pathToFasta = new File(pathToDir.getAbsoluteFile(),
						"/fasta/" + archiveName + ".fasta");
				if (pathToFasta.exists() == false) {
					System.err.println("File dosn't exist: "
							+ pathToFasta.getAbsolutePath());
				}
				final Sequence sequence = parseFastaFile(pathToFasta);
				sequenceDao.create(sequence);
				// read mutation
				InputStream fileIn = null;
				TarArchiveInputStream tarFileIn = null;

				try {
					fileIn = new FileInputStream(file);
					tarFileIn = new TarArchiveInputStream(
							new GzipCompressorInputStream(fileIn));
					TarArchiveEntry entry = null;
					while ((entry = tarFileIn.getNextTarEntry()) != null) {
						if (entry.getName().endsWith(".snap2")) {
							final List<Mutation> mutList = parseSnapMutationFile(
									unpackEntry(entry, new File(pathToDir,
											sequence.getRefId() + ".snap2"),
											tarFileIn), sequence);
							if (mutList.size() > 0)
								mutationDao.insertBatch(mutList);
						}
						if (entry.getName().endsWith(".SIFTprediction")) {
							final List<Mutation> mutList = parseSiftMutationFile(
									unpackEntry(entry, new File(pathToDir,
											sequence.getRefId()
													+ ".SIFTprediction"),
											tarFileIn), sequence);
							if (mutList.size() > 0)
								mutationDao.insertBatch(mutList);
						}
					}
				} catch (FileNotFoundException e) {
					throw new RuntimeException(e);
				} catch (IOException e) {
					throw new RuntimeException(e);
				} finally {
					try {
						tarFileIn.close();
					} catch (Exception e) {
						throw new RuntimeException(e);
					}
				}
			}
		}
	}

	public List<Mutation> parseSiftMutationFile(File file, Sequence sequence) {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String line = null;
			Mutation mutation = null;
			int currPos = 0;
			final List<Mutation> listToAdd = new ArrayList<Mutation>();
			while ((line = reader.readLine()) != null) {
				if (line.startsWith("WARNING") == true)
					continue;
				final String[] lineArray = line.split("\\t");
				if (lineArray.length == 1)
					continue;
				final String orgPosMut = lineArray[0];
				final String effectStr = lineArray[1];

				if (effectStr.equals("NOT SCORED") == true) {
					continue;
				}
				final int pos = Integer.parseInt(orgPosMut.substring(1,
						orgPosMut.length() - 1));
				final char org = orgPosMut.charAt(0);
				if (pos != currPos) {
					currPos = pos;
					if (mutation != null)
						listToAdd.add(mutation);
					mutation = new Mutation();
					mutation.setLsequenceid(sequence.getId());
					mutation.setPos(currPos);
					mutation.setType(MutationType.SIFT);
					mutation.getMutReliability()[AminoLookup
							.lookupAAtoIndex(org)] = 255;
					mutation.getMutEffect()[AminoLookup.lookupAAtoIndex(org)] = false;
				}
				final char mut = orgPosMut.charAt(orgPosMut.length() - 1);
				final Boolean effect = effectStr.equals("DELETERIOUS");
				final Integer accuracy = (int) (Float.parseFloat(lineArray[2]
						.substring(0, lineArray[3].length() - 1)) * 100f);
				mutation.getMutReliability()[AminoLookup.lookupAAtoIndex(mut)] = accuracy;
				mutation.getMutEffect()[AminoLookup.lookupAAtoIndex(mut)] = effect;
			}
			if (mutation != null)
				listToAdd.add(mutation);
			return listToAdd;
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				reader.close();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}

	public File unpackEntry(TarArchiveEntry entry, final File outputFile,
			final TarArchiveInputStream tarFileIn) {

		try {
			BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(
					outputFile));

			byte[] content = new byte[(int) entry.getSize()];

			tarFileIn.read(content);

			if (content.length > 0) {
				IOUtils.copy(new ByteArrayInputStream(content), outputStream);
				IOUtils.closeQuietly(outputStream);
				return outputFile;
			}
			outputStream.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return null;
	}

	public Sequence parseFastaFile(File pathToFasta) {
		LinkedHashMap<String, ProteinSequence> a;
		final Sequence sequence = new Sequence();
		try {
			a = FastaReaderHelper.readFastaProteinSequence(pathToFasta);
			// FastaReaderHelper.readFastaDNASequence for DNA sequences
			String header = null;
			for (Entry<String, ProteinSequence> entry : a.entrySet()) {
				if (header == null
						|| entry.getValue().getOriginalHeader()
								.contains(header) == false) {
					header = entry.getValue().getOriginalHeader();
					final String refIdWithVersion = header.split("\\|")[3];
					final String[] refid_array = refIdWithVersion.split("\\.");
					final String refId = refid_array[0];
					final Integer version;
					if (refid_array.length > 1)
						version = Integer.parseInt(refid_array[1]);
					else
						version = new Integer(1);

					if (refId == null)
						throw new RuntimeException("no refid found");
					sequence.setRefId(refId);
					sequence.setVersion(version);
					sequence.setSequence(entry.getValue().getSequenceAsString());
				}
			}
			return sequence;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public List<Mutation> parseSnapMutationFile(File file, Sequence sequence) {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String line = null;
			Mutation mutation = null;
			int currPos = 0;
			final List<Mutation> listToAdd = new ArrayList<Mutation>();
			while ((line = reader.readLine()) != null) {
				final String[] lineArray = line.split("\\t");
				final String orgPosMut = lineArray[0];
				final String effectStr = lineArray[1];

				final int pos = Integer.parseInt(orgPosMut.substring(1,
						orgPosMut.length() - 1));
				final char org = orgPosMut.charAt(0);
				if (pos != currPos) {
					currPos = pos;
					if (mutation != null)
						listToAdd.add(mutation);
					mutation = new Mutation();
					mutation.setLsequenceid(sequence.getId());
					mutation.setPos(currPos);
					mutation.setType(MutationType.SNAP);
					mutation.getMutReliability()[AminoLookup
							.lookupAAtoIndex(org)] = 255;
					mutation.getMutEffect()[AminoLookup.lookupAAtoIndex(org)] = false;
				}
				final char mut = orgPosMut.charAt(orgPosMut.length() - 1);
				final Boolean effect = effectStr.equals("Non-neutral");
				final Integer accuracy = Integer.parseInt(lineArray[3]
						.substring(0, lineArray[3].length() - 1));
				mutation.getMutReliability()[AminoLookup.lookupAAtoIndex(mut)] = accuracy;
				mutation.getMutEffect()[AminoLookup.lookupAAtoIndex(mut)] = effect;
			}
			if (mutation != null)
				listToAdd.add(mutation);
			return listToAdd;
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				reader.close();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}

	public MutationDao getMutationDao() {
		return mutationDao;
	}

	public void setMutationDao(MutationDao mutationDao) {
		this.mutationDao = mutationDao;
	}

	public SequenceDao getSequenceDao() {
		return sequenceDao;
	}

	public void setSequenceDao(SequenceDao sequenceDao) {
		this.sequenceDao = sequenceDao;
	}

}


text:
#region License
// Copyright (c) 2017 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

#if HAVE_ASYNC

using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Bson.Utilities;

namespace Newtonsoft.Json.Bson
{
    public partial class BsonDataWriter
    {
        private readonly bool _safeAsync;
        private bool _finishingAsync;

        /// <summary>
        /// Asynchronously flushes whatever is in the buffer to the destination and also flushes the destination.
        /// </summary>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <remarks>Because BSON documents are written as a single unit, only <see cref="FlushAsync"/>,
        /// <see cref="CloseAsync"/> and the final <see cref="WriteEndAsync(CancellationToken)"/>,
        /// <see cref="WriteEndArrayAsync"/> or <see cref="WriteEndObjectAsync"/>
        /// that finishes writing the document will write asynchronously. Derived classes will not write asynchronously.</remarks>
        public override Task FlushAsync(CancellationToken cancellationToken = new CancellationToken())
        {
            return _safeAsync ? _writer.FlushAsync(cancellationToken) : base.FlushAsync(cancellationToken);
        }

        /// <summary>
        /// Asynchronously writes the end of the current JSON object or array.
        /// </summary>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <remarks>Because BSON documents are written as a single unit, only <see cref="FlushAsync"/>,
        /// <see cref="CloseAsync"/> and the final <see cref="WriteEndAsync(CancellationToken)"/>,
        /// <see cref="WriteEndArrayAsync"/> or <see cref="WriteEndObjectAsync"/>
        /// that finishes writing the document will write asynchronously. Derived classes will not write asynchronously.</remarks>
        public override Task WriteEndAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            return _safeAsync && Top == 1 ? CompleteAsync(cancellationToken) : base.WriteEndAsync(cancellationToken);
        }

        private bool WillCloseAll(BsonType type)
        {
            if (type != _root.Type)
            {
                return false;
            }

            for (var token = _parent; token != _root; token = token.Parent)
            {
                if (token.Type == type) // Will only close as far as here.
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Asynchronously writes the end of an array.
        /// </summary>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <remarks>Because BSON documents are written as a single unit, only <see cref="FlushAsync"/>,
        /// <see cref="CloseAsync"/> and the final <see cref="WriteEndAsync(CancellationToken)"/>,
        /// <see cref="WriteEndArrayAsync"/> or <see cref="WriteEndObjectAsync"/>
        /// that finishes writing the document will write asynchronously. Derived classes will not write asynchronously.</remarks>
        public override Task WriteEndArrayAsync(CancellationToken cancellationToken = new CancellationToken())
        {
            return _safeAsync && WillCloseAll(BsonType.Array) ? CompleteAsync(cancellationToken) : base.WriteEndArrayAsync(cancellationToken);
        }

        /// <summary>
        /// Asynchronously writes the end of a JSON object.
        /// </summary>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <remarks>Because BSON documents are written as a single unit, only <see cref="FlushAsync"/>,
        /// <see cref="CloseAsync"/> and the final <see cref="WriteEndAsync(CancellationToken)"/>,
        /// <see cref="WriteEndArrayAsync"/> or <see cref="WriteEndObjectAsync"/>
        /// that finishes writing the document will write asynchronously. Derived classes will not write asynchronously.</remarks>
        public override Task WriteEndObjectAsync(CancellationToken cancellationToken = new CancellationToken())
        {
            return _safeAsync && WillCloseAll(BsonType.Object) ? CompleteAsync(cancellationToken) : base.WriteEndObjectAsync(cancellationToken);
        }

        /// <summary>
        /// Asynchronously closes this writer.
        /// If <see cref="JsonWriter.CloseOutput"/> is set to <c>true</c>, the destination is also closed.
        /// </summary>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <remarks>Because BSON documents are written as a single unit, only <see cref="FlushAsync"/>,
        /// <see cref="CloseAsync"/> and the final <see cref="WriteEndAsync(CancellationToken)"/>,
        /// <see cref="WriteEndArrayAsync"/> or <see cref="WriteEndObjectAsync"/>
        /// that finishes writing the document will write asynchronously. Derived classes will not write asynchronously.</remarks>
        public override Task CloseAsync(CancellationToken cancellationToken = new CancellationToken())
        {
            if (_safeAsync)
            {
                if (AutoCompleteOnClose)
                {
                    if (CloseOutput)
                    {
                        return CompleteAndCloseOutputAsync(cancellationToken);
                    }

                    return CompleteAsync(cancellationToken);
                }

                if (CloseOutput)
                {
                    _writer?.Close();
                }

                return AsyncUtils.CompletedTask;
            }

            return base.CloseAsync(cancellationToken);
        }

        private Task CompleteAsync(CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return cancellationToken.FromCanceled();
            }

            int top = Top;
            if (top == 0)
            {
                return AsyncUtils.CompletedTask;
            }

            _finishingAsync = true;
            try
            {
                while (top-- != 0)
                {
                    WriteEnd();
                }
            }
            finally
            {
                _finishingAsync = false;
            }

            return _writer.WriteTokenAsync(_root, cancellationToken);
        }

        private async Task CompleteAndCloseOutputAsync(CancellationToken cancellationToken)
        {
            await CompleteAsync(cancellationToken).ConfigureAwait(false);
            _writer?.Close();
        }
    }
}

#endif


text:
function BlogSearch() {
    var SEARCH_CLOSE_KEY_CODE = 27;
    var MIN_WORD_LENGTH = 3;

    var self = this;
    var $body = $('body');
    var $searchOverlay = $('#search');
    var $searchInput = $('#blog-search');
    var $resultContainer = $('#search-results');
    var $toggleLink = $('a.search-toggle');

    this.posts = null;

    this.search = function(phrase) {
        if (!self.posts) {
            self.getPosts();

            return [];
        }

        phrase = _(phrase.split(' ')).compact();
        var matches = _(self.posts).filter(function(element) {
            return _(phrase).every(function(phrasePart) {
                return _(element.words).some(function(word) {
                    return (
                        word == phrasePart
                        || 0 === word.indexOf(phrasePart)
                    );
                });
            });
        });

        return matches;
    };

    this.getPosts = function() {
        $.ajax({
            url: '/search.json',
            dataType: 'json',
            success: function(response, status, request) {
                self.posts = _(response).map(function(post) {
                    post.words = [];

                    if (post.title) {
                        post.words = (post.title).toLowerCase().split(' ');
                    }
                    if (post.tags) {
                        post.tags = _(post.tags)
                            .map(function(tag) {
                                tag = tag.toLowerCase();

                                return tag;
                            });

                        post.words = _.union(post.words, post.tags);
                    }

                    return post;
                });

                $searchInput.trigger('keyup');
            }
        });
    };

    this.bindControls = function() {
        $toggleLink.click(function(e) {
            e.preventDefault();

            // Add the noscroll class to body before showing the overlay.
            if ($searchOverlay.is(':hidden')) {
                $body.addClass('noscroll');
            }

            $searchOverlay.fadeToggle(
                400,
                function() {
                    if ($(this).is(':visible')) {
                        $searchInput.focus();
                    }
                    else {
                        $body.removeClass('noscroll');
                    }
                }
            );
        });

        $(document).keyup(function(e) {
            if (SEARCH_CLOSE_KEY_CODE == e.keyCode) {
                $searchOverlay.fadeOut(
                    400,
                    function() {
                        $body.removeClass('noscroll');
                    }
                );
            }
        });
    };

    this.bindSearch = function() {
        $searchInput.keyup(_(function() {
            var $resultList = $('ul', $resultContainer);

            var phrase = $(this).val();
            if (phrase.length >= MIN_WORD_LENGTH) {
                $resultList.empty();

                var matches = self.search(phrase.toLowerCase());
                if (!matches || !matches.length) {
                    $resultList.append('
No results found
');

                    return false;
                }

                $.each(matches, function(index, match) {
                    $resultList.append(
                        '
 \
                            ' + match.date + ' \
                            ' + match.title + ' \

'
                    );
                });

                return true;
            }
        }).debounce(100));
    };
}


text:
/** Detect free variable `global` from Node.js. */
const freeGlobal =
  typeof global == 'object' && global !== null && global.Object === Object && global

export default freeGlobal


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace Microsoft.CodeAnalysis.Wrapping.SeparatedSyntaxList
{
    internal enum WrappingStyle
    {
        /// <summary>
        /// Wraps first item.  Subsequent items, if wrapped, will be aligned with that first item:
        ///      MethodName(
        ///          int a, int b, int c, int d, int e,
        ///          int f, int g, int h, int i, int j)
        /// </summary>
        WrapFirst_IndentRest,

        /// <summary>
        /// Unwraps first item.  Subsequent items, if wrapped, will be aligned with that first item:
        ///      MethodName(int a, int b, int c, int d, int e,
        ///                 int f, int g, int h, int i, int j)
        /// </summary>
        UnwrapFirst_AlignRest,

        /// <summary>
        /// Unwraps first item.  Subsequent items, if wrapped, will be indented:
        ///      MethodName(int a, int b, int c, int d, int e,
        ///          int f, int g, int h, int i, int j)
        /// </summary>
        UnwrapFirst_IndentRest,
    }
}


text:
Author: Xin Pan (xpan@google.com, github: panyx0718), Jon Shlens, Yao Zhang

Consultants: Jon Shlens, Pete Warden

###Major Features

1.  Measure model parameters, float operations, tensor shapes.
2.  Profile op execution times, requested memory size and device placement.
3.  Inspect checkpoint tensors' shapes and their values.
4.  Selectively group, filter, account and order ops.

####tfprof supports 3 views to organize TensorFlow model profiles

    *  code view: Stats are associated your Python codes and organized as call stacks.
    *  scope view: Stats are organized as name scope hierarchies.
    *  graph view: Stats are organized as Tensorflow Op graph.

####For each view, there are 3 ways to display outputs:

    *  stdout: Results are written to stdout.
    *  timeline: Visualized in chrome browser as time series.
    *  file: Results are dumped to file.


text:
from datetime import datetime

from sqlalchemy import (Column, Integer, String, DateTime, ForeignKey,
                        PrimaryKeyConstraint, Index)
from sqlalchemy.orm import relation, deferred, backref
from sqlalchemy.sql import and_

from aquilon.aqdb.model import (Base, Network, Location, ARecord,
                                DnsEnvironment, Fqdn)
from aquilon.aqdb.model.a_record import dns_fqdn_mapper
from aquilon.aqdb.column_types import IPV4

_TN = "router_address"

class RouterAddress(Base):
    """ Represents a router address on a network. """

    __tablename__ = _TN
    _class_label = 'Router Address'
    _instance_label = 'ip'

    ip = Column(IPV4, nullable=False)

    # With the introduction of network environments, the IP alone is not enough
    # to uniquely identify the router
    network_id = Column(Integer, ForeignKey('network.id',
                                            name='%s_network_fk' % _TN),
                        nullable=False)

    dns_environment_id = Column(Integer, ForeignKey('dns_environment.id',
                                                    name='%s_dns_env_fk' % _TN),
                                nullable=False)

    # We don't want deleting a location to disrupt networking, so use "ON DELETE
    # SET NULL" here
    location_id = Column(Integer, ForeignKey('location.id',
                                             name='%s_location_fk' % _TN,
                                             ondelete="SET NULL"),
                         nullable=True)

    creation_date = deferred(Column(DateTime, default=datetime.now,
                                    nullable=False))

    comments = deferred(Column(String(255), nullable=True))

    network = relation(Network, innerjoin=True,
                       backref=backref('routers', cascade="all, delete-orphan",
                                       order_by=[ip]))

    dns_environment = relation(DnsEnvironment)

    location = relation(Location)

    dns_records = relation(dns_fqdn_mapper, uselist=True,
                           primaryjoin=and_(network_id == ARecord.network_id,
                                            ip == ARecord.ip,
                                            dns_environment_id == Fqdn.dns_environment_id),
                           foreign_keys=[ARecord.ip, Fqdn.dns_environment_id],
                           viewonly=True)

    __table_args__ = (PrimaryKeyConstraint(network_id, ip),
                      Index("%s_dns_env_idx" % _TN, dns_environment_id),
                      Index("%s_location_idx" % _TN, location_id))

rtaddr = RouterAddress.__table__  # pylint: disable=C0103
rtaddr.info['unique_fields'] = ['ip', 'network']
rtaddr.info['extra_search_fields'] = ['dns_environment']


text:
/*
 * (C) 2003-2016 Anope Team
 * Contact us at team@anope.org
 *
 * Please read COPYING and README for further details.
 */

#include "modules/httpd.h"

namespace WebCPanel
{

class Index : public WebPanelPage
{
 public:
	Index(const Anope::string &u) : WebPanelPage(u) { }

	bool OnRequest(HTTPProvider *, const Anope::string &, HTTPClient *, HTTPMessage &, HTTPReply &) anope_override;
};

}


text:
package org.gradle.plugin.use.resolve.service.internal;

import com.google.common.escape.Escaper;
import com.google.common.net.UrlEscapers;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.Nullable;
import org.gradle.authentication.Authentication;
import org.gradle.internal.Actions;
import org.gradle.internal.resource.ResourceExceptions;
import org.gradle.internal.resource.transport.http.*;
import org.gradle.plugin.use.internal.PluginRequest;
import org.gradle.util.GradleVersion;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;

public class HttpPluginResolutionServiceClient implements PluginResolutionServiceClient {
    private static final Escaper PATH_SEGMENT_ESCAPER = UrlEscapers.urlPathSegmentEscaper();
    private static final String CLIENT_REQUEST_BASE = String.format("%s", PATH_SEGMENT_ESCAPER.escape(GradleVersion.current().getVersion()));
    private static final String PLUGIN_USE_REQUEST_URL = "/plugin/use/%s/%s";
    private static final String JSON = "application/json";

    public static final String CLIENT_STATUS_CHECKSUM_HEADER = "X-Gradle-Client-Status-Checksum";

    private final SslContextFactory sslContextFactory;
    private HttpResourceAccessor resourceAccessor;

    public HttpPluginResolutionServiceClient(SslContextFactory sslContextFactory) {
        this(sslContextFactory, null);
    }

    public HttpPluginResolutionServiceClient(SslContextFactory sslContextFactory, HttpResourceAccessor resourceAccessor) {
        this.sslContextFactory = sslContextFactory;
        this.resourceAccessor = resourceAccessor;
    }

    @Nullable
    public Response<PluginUseMetaData> queryPluginMetadata(String portalUrl, boolean shouldValidate, final PluginRequest pluginRequest) {
        String escapedId = PATH_SEGMENT_ESCAPER.escape(pluginRequest.getId().toString());
        String escapedPluginVersion = PATH_SEGMENT_ESCAPER.escape(pluginRequest.getVersion());
        final String requestUrl = toRequestUrl(portalUrl, String.format(PLUGIN_USE_REQUEST_URL, escapedId, escapedPluginVersion));
        return request(requestUrl, PluginUseMetaData.class, new Action<PluginUseMetaData>() {
            public void execute(PluginUseMetaData pluginUseMetaData) {
                validate(requestUrl, pluginUseMetaData);
            }
        });
    }

    public Response<ClientStatus> queryClientStatus(String portalUrl, boolean shouldValidate, String checksum) {
        final String requestUrl = toRequestUrl(portalUrl, "");
        return request(requestUrl, ClientStatus.class, Actions.doNothing());
    }

    private String toRequestUrl(String portalUrl, String path) {
        return String.format("%s/%s%s", portalUrl, CLIENT_REQUEST_BASE, path);
    }

    private <T> Response<T> request(final String requestUrl, final Class<T> type, final Action<? super T> validator) {
        final URI requestUri = toUri(requestUrl, "plugin request");

        try {
            HttpResponseResource response = getResourceAccessor().getRawResource(requestUri);
            try {
                final int statusCode = response.getStatusCode();
                String contentType = response.getContentType();
                if (contentType == null || !contentType.equalsIgnoreCase(JSON)) {
                    final String message = String.format("content type is '%s', expected '%s' (status code: %s)", contentType == null ? "" : contentType, JSON, statusCode);
                    throw new OutOfProtocolException(requestUrl, message);
                }

                final String clientStatusChecksum = response.getHeaderValue(CLIENT_STATUS_CHECKSUM_HEADER);
                Reader reader = new InputStreamReader(response.openStream(), "utf-8");
                try {
                    if (statusCode == 200) {
                        T payload = new Gson().fromJson(reader, type);
                        validator.execute(payload);
                        return new SuccessResponse<T>(payload, statusCode, requestUrl, clientStatusChecksum);
                    } else if (statusCode >= 400 && statusCode < 600) {
                        ErrorResponse errorResponse = validate(requestUrl, new Gson().fromJson(reader, ErrorResponse.class));
                        return new ErrorResponseResponse<T>(errorResponse, statusCode, requestUrl, clientStatusChecksum);
                    } else {
                        throw new OutOfProtocolException(requestUrl, "unexpected HTTP response status " + statusCode);
                    }
                } catch (JsonSyntaxException e) {
                    throw new OutOfProtocolException(requestUrl, "could not parse response JSON", e);
                } catch (JsonIOException e) {
                    throw new OutOfProtocolException(requestUrl, "could not parse response JSON", e);
                }
            } finally {
                response.close();
            }
        } catch (IOException e) {
            throw ResourceExceptions.getFailed(requestUri, e);
        }
    }

    public void close() {

    }

    private PluginUseMetaData validate(String url, PluginUseMetaData pluginUseMetaData) {
        if (pluginUseMetaData.implementationType == null) {
            throw new OutOfProtocolException(url, "invalid plugin metadata - no implementation type specified");
        }
        if (!pluginUseMetaData.implementationType.equals(PluginUseMetaData.M2_JAR)) {
            throw new OutOfProtocolException(url, String.format("invalid plugin metadata - unsupported implementation type '%s'", pluginUseMetaData.implementationType));
        }
        if (pluginUseMetaData.implementation == null) {
            throw new OutOfProtocolException(url, "invalid plugin metadata - no implementation specified");
        }
        if (pluginUseMetaData.implementation.get("gav") == null) {
            throw new OutOfProtocolException(url, "invalid plugin metadata - no module coordinates specified");
        }
        if (pluginUseMetaData.implementation.get("repo") == null) {
            throw new OutOfProtocolException(url, "invalid plugin metadata - no module repository specified");
        }

        return pluginUseMetaData;
    }

    private ErrorResponse validate(String url, ErrorResponse errorResponse) {
        if (errorResponse.errorCode == null) {
            throw new OutOfProtocolException(url, "invalid error response - no error code specified");
        }

        if (errorResponse.message == null) {
            throw new OutOfProtocolException(url, "invalid error response - no message specified");
        }

        return errorResponse;
    }

    private URI toUri(String url, String kind) {
        try {
            return new URI(url);
        } catch (URISyntaxException e) {
            throw new GradleException(String.format("Invalid %s URL: %s", kind, url), e);
        }
    }

    private HttpResourceAccessor getResourceAccessor() {
        if (resourceAccessor == null) {
            resourceAccessor = new HttpResourceAccessor(new HttpClientHelper(new DefaultHttpSettings(Collections.<Authentication>emptyList(), sslContextFactory)));
        }
        return resourceAccessor;
    }

    private static class OutOfProtocolException extends GradleException {
        private OutOfProtocolException(String requestUrl, String message) {
            super(toMessage(requestUrl, message));
        }

        private OutOfProtocolException(String requestUrl, String message, Throwable cause) {
            super(toMessage(requestUrl, message), cause);
        }

        private static String toMessage(String requestUrl, String message) {
            return String.format("The response from %s was not a valid response from a Gradle Plugin Resolution Service: %s", requestUrl, message);
        }
    }
}


text:
import urllib, urllib2, cookielib
from urllib2 import HTTPBasicAuthHandler

try:
    f = urllib2.urlopen("http://www.python.org")
    print f.read()
    f.close()
except HTTPError, e:
    print "Ocurrio un error"
    print e.code
except URLError, e:
    print "Ocurrio un error"
    print e.reason

params = urllib.urlencode({"usuario": "manuel",
                           "password": "contrasenya"})
# f = urllib2.urlopen("http://ejemplo.com/login", params)

# La funcion urlretrieve toma como parametros la URL a descargar
# y, opcionalmente, un parametro filename con la ruta local en la
# que guardar el archivo, un parametro data similar al de urlopen y
# un parametro reporthook con una funcion que utilizar para informar
# del progreso.

params = urllib.urlencode({"usuario": "manuel",
                           "password": "contrasenya"})

#f = urllib2.urlopen("http://ejemplo.com/login" + "?" + params)

# La clase Request define objetos que encapsular toda la informacion
# relativa a una peticion. A traves de este objetos podemos realizar
# peticiones mas complejas, incluyendo nuestras propias cabeceras, como
# el User-Agent

# Por defecto urllib2 se identifica como "Python-urllib/2.5"; si
# quisieramos identificarnos como un Linux corriendo Konqueror por
# ejemplo:

ua = "Mozilla/5.0 (compatible; Konqueror/3.5.8; Linux)"
h = {"User-Agent": ua}
r = urllib2.Request("http://www.python.org", headers=h)
f = urllib2.urlopen(r)
print f.read()

# Para personalizar la forma en que trabaja urllib2 podemos instalar un
# grupo de manejadores (handlers) agrupados en un objeto de la clase
# OpenerDirector (opener), que sera el que se utilice a partir de ese
# momento al llamar a urlopen

aut_h = urllib2.HTTPBasicAuthHandler()
aut_h.add_password("realm", "host", "usuario", "password")

opener = urllib2.build_opener(aut_h)
urllib2.install_opener(opener)

f = urllib2.urlopen("http://www.python.org")

# Si quisieramos especificar un proxy en el codigo tendriamos que
# utilizar un opener que contuviera el manejador ProxyHandler

proxy_h = urllib2.ProxyHandler({"http" : "http://miproxy.net:123"})

opener = urllib2.build_opener(proxy_h)

urllib2.install_opener(opener)

#f = urllib2.urlopen("http://www.python.org")

# Para que se guarden las cookies que manda HTTP utilizamos el manejador
# HTTPCookieProcessor

cookie_h = urllib2.HTTPCookieProcessor()

opener = urllib2.build_opener(cookie_h)

urllib2.install_opener(opener)

f = urllib2.urlopen("http://www.python.org")

# Si queremos acceder a estas cookies o poder mandar nuestras propias
# cookies, podemos pasarle como parametro al inicializador de
# HTTPCookiProcessor un objeto de tipo CookiJar del modulo cookielib

# Para leer las cookies mandadas basta con crear un objeto iterabe a partir
# del CookieJar

cookie_j = cookielib.CookieJar()

cookie_h = urllib2.HTTPCookieProcessor(cookie_j)

opener = urllib2.build_opener(cookie_h)

opener.open("http://www.python.org")

for num, cookie in enumerate(cookie_j):
    print num, cookie.name
    print cookie.value
    print


text:
package com.hkamran.mocking.servers;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletException;
import javax.websocket.DeploymentException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.websocket.jsr356.server.ServerContainer;
import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.json.JSONObject;

import com.hkamran.mocking.Filter;
import com.hkamran.mocking.Proxies;
import com.hkamran.mocking.Proxy;
import com.hkamran.mocking.Tape;

@Path("/")
public class HTTPServer {

	private final static Logger log = LogManager.getLogger(HTTPServer.class);
	private static Proxies proxies;

	public static void setProxyManager(Proxies proxies) {
		HTTPServer.proxies = proxies;
	}

	/**
	 * Get the Tape
	 */
	@GET
	@Path("/{proxyId}/tape")
	@Produces({ MediaType.APPLICATION_JSON })
	public Response getTape(@PathParam("proxyId") Integer proxyName) {
		log.info("Requesting tape information for " + proxyName);

		Proxy proxy = proxies.get(proxyName);
		Filter filter = proxy.getFilter();
		Tape tape = filter.getTape();
		JSONObject tapeJSON = tape.toJSON();

		return Response
				.status(200)
				.entity(tapeJSON.toString(2))
				.header("Access-Control-Allow-Origin", "*")
				.header("Access-Control-Allow-Methods",
						"GET, POST, DELETE, PUT")
				.header("Content-Disposition", "attachment; filename=tape.json")
				.allow("OPTIONS").build();
	}

	public void start(Integer port) throws ServletException, DeploymentException {
		log.info("Starting HTTP Server at " + port);

		//Set Jersey Classes
		ResourceConfig config = new ResourceConfig();
		Set<Class<?>> s = new HashSet<Class<?>>();
        s.add(HTTPServer.class);
        s.add(WebSocket.class);
		config.registerClasses(s);

		Server server = new Server(port);

		//Create Jersey Handler (function is to handle REST)
		ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(config));
		ServletContextHandler restHandler = new ServletContextHandler(server, "/rest");
		restHandler.addServlet(jerseyServlet, "/*");

		//Create WS
		ServletHolder wsServlet = new ServletHolder(new DefaultServlet());
		ServletContextHandler wsHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
		wsHandler.setContextPath("/ws");
		wsHandler.addServlet(wsServlet, "/*");

		//Create Static Handler (Function is to serve HTML/JS/CSS
	    ResourceHandler staticHandler = new ResourceHandler();
	    staticHandler.setWelcomeFiles(new String[]{ "index.html" });
	    String dir = HTTPServer.class.getClassLoader().getResource("web").toExternalForm();
	    staticHandler.setResourceBase(dir);

	    HandlerList handlers = new HandlerList();
	    handlers.setHandlers(new Handler[] {
	    		wsHandler, staticHandler, restHandler
	    });

	    server.setHandler(handlers);

        ServerContainer container = WebSocketServerContainerInitializer.configureContext(wsHandler);
        container.addEndpoint(WebSocket.class);

		try {
            server.start();
            server.join();
        } catch (Exception e) {
			e.printStackTrace();
		} finally {
        	server.destroy();
        }
	}

}


text:
using UnityEngine;
using System.Collections;

namespace EA4S.Db
{
    public class PhraseDatabase : ScriptableObject
    {
        [SerializeField]
        public PhraseTable table;
    }

}


text:
<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		Model::unguard();

		$this->call('UsersTableSeeder');
		$this->call('LeaguesTableSeeder');
		$this->call('SeasonsTableSeeder');
		$this->call('TeamsTableSeeder');

		if (env('APP_ENV') == 'development') {
			$this->call('DevSeeder');
		}

	}

}


text:
package eu.toolchain.scribe.jackson.encoding;

import eu.toolchain.scribe.Context;
import eu.toolchain.scribe.Encoder;
import eu.toolchain.scribe.jackson.JsonNode;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.ArrayList;
import java.util.List;

@Data
@EqualsAndHashCode(callSuper = true)
public class ListEncoder<ElementSource> extends AbstractEncoder<List<ElementSource>> {
  private final Encoder<JsonNode, ElementSource> value;

  @Override
  public JsonNode encode(final Context path, final List<ElementSource> instance) {
    final List<JsonNode> result = new ArrayList<>(instance.size());

    int index = 0;

    for (final ElementSource value : instance) {
      final Context p = path.push(index++);
      this.value.encodeOptionally(p, value, result::add);
    }

    return new JsonNode.ListJsonNode(result);
  }
}


text:
import {BaseDevice, getRenderHostInstance} from 'flipper-frontend-core';
import {reportPlatformFailures} from 'flipper-common';
import {getFlipperLib, path} from 'flipper-plugin';
import {assertNotNull} from './assertNotNull';

export function getCaptureLocation() {
  return (
    getRenderHostInstance().serverConfig.processConfig.screenCapturePath ||
    getRenderHostInstance().serverConfig.paths.desktopPath
  );
}

// TODO: refactor so this doesn't need to be exported
export function getFileName(extension: 'png' | 'mp4'): string {
  // Windows does not like `:` in its filenames. Yes, I know ...
  return `screencap-${new Date().toISOString().replace(/:/g, '')}.${extension}`;
}

export async function capture(device: BaseDevice): Promise<string> {
  if (!device.connected.get()) {
    console.info('Skipping screenshot for disconnected device');
    return '';
  }
  const pngPath = path.join(getCaptureLocation(), getFileName('png'));
  return reportPlatformFailures(
    // TODO: there is no reason to read the screenshot first, grab it over the websocket, than send it back
    // again to write in a file, probably easier to change screenshot api to `device.screenshot(): path`
    device
      .screenshot()
      .then((buffer) => {
        assertNotNull(
          buffer,
          `Device ${device.description.deviceType}:${device.description.os} does not support taking screenshots`,
        );
        return getFlipperLib().remoteServerContext.fs.writeFileBinary(
          pngPath,
          buffer,
        );
      })
      .then(() => pngPath),
    'captureScreenshot',
  );
}


text:
module Args
        ( parseArgs
        , configDefault)
where
import Config
import Model
import Data.Array.Repa                  as R
import Data.Array.Repa.Algorithms.Pixel as R
import Data.Array.Repa.IO.BMP           as R
import qualified Data.Vector.Unboxed    as U
import Prelude                          as P
import System.Exit
import Data.Char

parseArgs :: [String] -> Config -> IO Config
parseArgs args config
        | []    <- args
        = return config

        | "-batch" : rest        <- args
        = parseArgs rest
        $ config { configBatchMode      = True }

        | "-frames" : path : rest <- args
        = parseArgs rest
        $ config { configFramesMode     = Just path
                 , configBatchMode      = True }

        | "-max" : num : rest   <- args
        , all isDigit num
        = parseArgs rest
        $ config { configMaxSteps       = read num }

        | "-size" : width : height : rest <- args
        , all isDigit width
        , all isDigit height
        , width'        <- read width
        , height'       <- read height
        = parseArgs rest
        $ config { configModelSize       = (width', height')
                 , configInitialDensity  = makeDensField_empty width' height'
                 , configInitialVelocity = makeVeloField_empty width' height' }

        | "-unstable" : rest    <- args
        = parseArgs rest
        $ config { configUnstable       = True }

        | "-iters" : num : rest <- args
        , all isDigit num
        = parseArgs rest
        $ config { configIters          = read num }

        | "-scale" : int : rest <- args
        = parseArgs rest
        $ config { configScale          = (read int, read int) }

        | "-rate" : int : rest <- args
        = parseArgs rest
        $ config { configRate           = read int }

        | "-delta" : float : rest <- args
        = parseArgs rest
        $ config { configDelta          = read float }

        | "-diff" : float : rest <- args
        = parseArgs rest
        $ config { configDiff           = read float }

        | "-diff-after" : int : rest <- args
        , all isDigit int
        = parseArgs rest
        $ config { configDiffAfter      = read int }

        | "-visc" : float : rest <- args
        = parseArgs rest
        $ config { configVisc           = read float }

        | "-user-dens" : float : rest <- args
        = parseArgs rest
        $ config { configDensity        = read float }

        | "-user-velo" : float : rest <- args
        = parseArgs rest
        $ config { configVisc           = read float }

        -- Initial Confditions ----------------------------------------------------
        | "-dens-bmp" : filePath : rest <- args
        = do    dens    <- loadDensBMP  filePath
                let Z :. height :. width = extent dens
                parseArgs rest
                 $ config { configInitialDensity  = dens
                          , configModelSize       = (width, height) }

        | "-velo-bmp" : filePath : rest <- args
        = do    velo    <- loadVeloBMP filePath
                let Z :. height :. width = extent velo
                parseArgs rest
                 $ config { configInitialVelocity = velo
                          , configModelSize       = (width, height) }

        | "-init-checks" : rest <- args
        = do    let (width, height)     = configModelSize config
                parseArgs rest
                 $ config { configInitialDensity  = makeDensField_checks width height
                          , configInitialVelocity = makeVeloField_empty  width height }

        | "-init-man" : rest <- args
        = do    let (width, height)     = configModelSize config
                parseArgs rest
                 $ config { configInitialDensity   = makeDensField_checks width height
                          , configInitialVelocity  = makeVeloField_man    width height }

        | "-init-elk" : rest <- args
        = do    let (width, height)     = configModelSize config
                parseArgs rest
                 $ config { configInitialDensity   = makeDensField_checks width height
                          , configInitialVelocity  = makeVeloField_elk    width height }

        | otherwise
        = do    printUsage
                exitWith ExitSuccess

printUsage :: IO ()
printUsage
 = putStr
 $ unlines
        [ "gloss-fluid [flags]"
        , "  -batch                  Run a fixed number of steps instead of displaying in a window."
        , "  -frames     <PATH.bmp>  Dump all frames to .bmp files (implies -batch)"
        , "  -max        <INT>       Quit after this number of steps."
        , "  -size       <INT> <INT> Size of simulation.                  (100)"
        , "  -unstable               Use the unstable linear solver       (False)"
        , "  -iters      <INT>       Iterations for the linear solver.    (40)"
        , "  -scale      <INT>       Width of a cell in the window.       (5)"
        , "  -rate       <INT>       Frame rate.                          (30)"
        , "  -delta      <FLOAT>     Length of time step.                 (0.1)"
        , "  -diff       <FLOAT>     Diffusion rate for the density.      (0)"
        , "  -diff-after <INT>       Trigger diffusion after this step.   (0)"
        , "  -visc       <FLOAT>     Diffusion rate for the velocity.     (0)"
        , "  -user-dens  <FLOAT>     Magnitude of user inserted density.  (100)"
        , "  -user-velo  <FLOAT>     Magnitude of user inserted velocity. (20)"
        , "  -bmp-dens   <FILE.bmp>  File for initial fluid density."
        , "  -bmp-velo   <FILE.bmp>  File for initial fluid velocity."
        , ""
        , "  Run this with   +RTS -N -qa -qg   to enable threads."
        , "" ]

configDefault :: Config
configDefault
 = let  modelW  = 100
        modelH  = 100
   in Config
        { configRate            = 30
        , configMaxSteps        = 0
        , configBatchMode       = False
        , configFramesMode      = Nothing
        , configModelSize       = (modelW, modelH)
        , configScale           = (5, 5)
        , configUnstable        = False
        , configIters           = 40
        , configDelta           = 0.1
        , configDiff            = 0
        , configDiffAfter       = 0
        , configVisc            = 0
        , configDensity         = 100
        , configVelocity        = (20, 20)
        , configInitialDensity  = makeDensField_empty modelW modelH
        , configInitialVelocity = makeVeloField_empty modelW modelH }

-- | Load a density field from a BMP file.
loadDensBMP :: FilePath -> IO DensityField
loadDensBMP filePath
 = do   result   <- readImageFromBMP filePath
        let arr = case result of
                        Right arr'      -> arr'
                        Left  err       -> error $ show err

        density  <- computeUnboxedP
                 $ R.map floatLuminanceOfRGB8 arr

        return density

-- | Load velocity field from a BMP file.
loadVeloBMP :: FilePath -> IO VelocityField
loadVeloBMP filePath
 = do   result  <- readImageFromBMP filePath
        let arr  = case result of
                        Right arr'      -> arr'
                        Left err        -> error $ show err

        let {-# INLINE conv #-}
            conv (r, g, _b)
             = let r'   = fromIntegral (-128 + fromIntegral r :: Int)
                   g'   = fromIntegral (-128 + fromIntegral g :: Int)
               in  (r' * 0.0001, g' * 0.0001)

        velocity  <- computeUnboxedP $ R.map conv arr

        return velocity

-------------------------------------------------------------------------------
makeDensField_empty :: Int -> Int -> Array U DIM2 Float
makeDensField_empty width height
        = R.fromUnboxed (Z :. height :. width)
        $ U.replicate (width * height) 0

makeDensField_checks :: Int -> Int -> DensityField
makeDensField_checks width height
 = let  height' = fromIntegral height
        xc      = fromIntegral (width  `div` 2)
        yc      = fromIntegral (height `div` 2)

   in   R.fromListUnboxed (Z :. height :. width)
         $ [ let x'      = fromIntegral (x - 1)
                 y'      = fromIntegral (y - 1)
                 tx      = 10 * (x' - xc) / height'
                 ty      = 10 * (y' - yc) / height'
                 xk1     = if abs tx > 3*pi/2 then 0 else cos tx
                 yk1     = if abs ty > 3*pi/2 then 0 else cos ty
                 d1      = xk1 * yk1
             in  if (d1 < 0) then 0 else d1
                        | y     <- [1 .. height]
                        , x     <- [1 .. width] ]

-------------------------------------------------------------------------------
makeVeloField_empty :: Int -> Int -> Array U DIM2 (Float, Float)
makeVeloField_empty width height
        = R.fromUnboxed (Z :. height :. width)
        $ U.replicate (width * height) (0, 0)

makeVeloField_man :: Int -> Int -> VelocityField
makeVeloField_man width height
 = let  height' = fromIntegral height
        xc      = fromIntegral (width  `div` 2)
        yc      = fromIntegral (height `div` 2)

   in   R.fromListUnboxed (Z :. height :. width)
         $ [ let x'      = fromIntegral x
                 y'      = fromIntegral y
                 xk2     = cos (19 * (x' - xc) / height')
                 yk2     = cos (17 * (y' - yc) / height')
                 d2      = xk2 * yk2 / 5
             in  (0, d2)
                        | y     <- [0..height - 1]
                        , x     <- [0..width  - 1] ]

makeVeloField_elk :: Int -> Int -> VelocityField
makeVeloField_elk width height
 = let  height' = fromIntegral height
        xc      = fromIntegral (width  `div` 2)
        yc      = fromIntegral (height `div` 2)

   in   R.fromListUnboxed (Z :. height :. width)
         $ [ let x'      = fromIntegral x
                 y'      = fromIntegral y
                 tx      = 12 * (x' - xc) / height'
                 ty      = 12 * (y' - yc) / height'
                 xk2     =  cos tx
                 yk2     = -cos ty
                 d2      = xk2 * yk2 / 5
             in  (0, d2)
                        | y     <- [0 .. height - 1]
                        , x     <- [0 .. width  - 1] ]


text:
function extractFromClassInfo(hp, classInfo)
    if ischar(classInfo)
        [classInfo, hp.fullTopic] = classInheritance.helpUtils.splitClassInformation(classInfo, '', false);
        if isempty(classInfo)
            return;
        end
    end
    hp.topic = classInfo.minimalPath;
    hp.isDir = classInfo.isPackage;

    hp.objectSystemName = classInfo.fullTopic;
    if ~isempty(classInfo.getDocTopic(true))
        hp.docTopic = hp.objectSystemName;
    end
end

%   Copyright 2007 The MathWorks, Inc.
%   $Revision: 1.1.6.4 $  $Date: 2012/09/05 07:24:34 $