text:
DS_FUNCTION_TABLE(get_device_list,    dsCommand::getDeviceListCmd)
DS_FUNCTION_TABLE(get_region_list,    dsCommand::getRegionListCmd)
DS_FUNCTION_TABLE(get_interface_list, dsCommand::getRegionListCmd)
DS_FUNCTION_TABLE(get_contact_list,   dsCommand::getRegionListCmd)
DS_FUNCTION_TABLE(get_element_node_list, dsCommand::getElementNodeListCmd)
// Material Commands
DS_FUNCTION_TABLE(set_parameter,      dsCommand::getParameterCmd)
DS_FUNCTION_TABLE(get_parameter,      dsCommand::getParameterCmd)
DS_FUNCTION_TABLE(get_parameter_list, dsCommand::getParameterCmd)
DS_FUNCTION_TABLE(set_material,       dsCommand::getParameterCmd)
DS_FUNCTION_TABLE(get_material,       dsCommand::getParameterCmd)
DS_FUNCTION_TABLE(create_db,          dsCommand::openDBCmd)
DS_FUNCTION_TABLE(open_db,            dsCommand::openDBCmd)
DS_FUNCTION_TABLE(close_db,           dsCommand::openDBCmd)
DS_FUNCTION_TABLE(save_db,            dsCommand::openDBCmd)
DS_FUNCTION_TABLE(add_db_entry,       dsCommand::addDBEntryCmd)
DS_FUNCTION_TABLE(get_db_entry,       dsCommand::getDBEntryCmd)
DS_FUNCTION_TABLE(get_dimension,      dsCommand::getParameterCmd)
// Model Commands
DS_FUNCTION_TABLE(contact_edge_model,         dsCommand::createContactNodeModelCmd)
DS_FUNCTION_TABLE(contact_node_model,         dsCommand::createContactNodeModelCmd)
DS_FUNCTION_TABLE(debug_triangle_models,      dsCommand::debugTriangleCmd)
DS_FUNCTION_TABLE(delete_edge_model,          dsCommand::printEdgeValuesCmd)
DS_FUNCTION_TABLE(delete_element_model,       dsCommand::printElementEdgeValuesCmd)
DS_FUNCTION_TABLE(delete_interface_model,     dsCommand::getInterfaceValuesCmd)
DS_FUNCTION_TABLE(delete_node_model,          dsCommand::printNodeValuesCmd)
DS_FUNCTION_TABLE(edge_from_node_model,       dsCommand::createEdgeFromNodeModelCmd)
DS_FUNCTION_TABLE(edge_average_model,         dsCommand::createEdgeAverageModelCmd)
DS_FUNCTION_TABLE(edge_model,                 dsCommand::createNodeModelCmd)
DS_FUNCTION_TABLE(element_from_edge_model,    dsCommand::createTriangleFromEdgeModelCmd)
DS_FUNCTION_TABLE(element_pair_from_edge_model,    dsCommand::createTriangleFromEdgeModelCmd)
DS_FUNCTION_TABLE(element_from_node_model,    dsCommand::createEdgeFromNodeModelCmd)
DS_FUNCTION_TABLE(vector_element_model,       dsCommand::createVectorElementModelCmd)
DS_FUNCTION_TABLE(element_model,              dsCommand::createNodeModelCmd)
DS_FUNCTION_TABLE(get_edge_model_list,        dsCommand::getNodeModelListCmd)
DS_FUNCTION_TABLE(get_edge_model_values,      dsCommand::printEdgeValuesCmd)
DS_FUNCTION_TABLE(get_element_model_list,     dsCommand::getNodeModelListCmd)
DS_FUNCTION_TABLE(get_element_model_values,   dsCommand::printElementEdgeValuesCmd)
DS_FUNCTION_TABLE(get_interface_model_list,   dsCommand::getInterfaceModelListCmd)
DS_FUNCTION_TABLE(get_interface_model_values, dsCommand::getInterfaceValuesCmd)
DS_FUNCTION_TABLE(get_node_model_list,        dsCommand::getNodeModelListCmd)
DS_FUNCTION_TABLE(get_node_model_values,      dsCommand::printNodeValuesCmd)
DS_FUNCTION_TABLE(interface_model,            dsCommand::createInterfaceNodeModelCmd)
DS_FUNCTION_TABLE(interface_normal_model,     dsCommand::createInterfaceNormalModelCmd)
DS_FUNCTION_TABLE(node_model,                 dsCommand::createNodeModelCmd)
DS_FUNCTION_TABLE(node_solution,              dsCommand::createNodeSolutionCmd)
DS_FUNCTION_TABLE(edge_solution,              dsCommand::createNodeSolutionCmd)
DS_FUNCTION_TABLE(element_solution,           dsCommand::createNodeSolutionCmd)
DS_FUNCTION_TABLE(print_edge_values,          dsCommand::printEdgeValuesCmd)
DS_FUNCTION_TABLE(print_element_values,       dsCommand::printElementEdgeValuesCmd)
DS_FUNCTION_TABLE(print_node_values,          dsCommand::printNodeValuesCmd)
DS_FUNCTION_TABLE(register_function,          dsCommand::registerFunctionCmd)
DS_FUNCTION_TABLE(set_node_values,            dsCommand::setNodeValuesCmd)
DS_FUNCTION_TABLE(set_node_value,             dsCommand::setNodeValueCmd)
DS_FUNCTION_TABLE(set_edge_values,            dsCommand::setNodeValuesCmd)
DS_FUNCTION_TABLE(set_element_values,         dsCommand::setNodeValuesCmd)
DS_FUNCTION_TABLE(symdiff,                    dsCommand::symdiffCmd)
DS_FUNCTION_TABLE(vector_gradient,            dsCommand::createEdgeFromNodeModelCmd)
DS_FUNCTION_TABLE(cylindrical_edge_couple,    dsCommand::createCylindricalCmd)
DS_FUNCTION_TABLE(cylindrical_node_volume,    dsCommand::createCylindricalCmd)
DS_FUNCTION_TABLE(cylindrical_surface_area,   dsCommand::createCylindricalCmd)
// Math Commands
DS_FUNCTION_TABLE(get_contact_current,        dsCommand::getContactCurrentCmd)
DS_FUNCTION_TABLE(get_contact_charge,         dsCommand::getContactCurrentCmd)
DS_FUNCTION_TABLE(solve,                      dsCommand::solveCmd)
DS_FUNCTION_TABLE(get_matrix_and_rhs,         dsCommand::getMatrixAndRHSCmd)
DS_FUNCTION_TABLE(set_initial_condition,      dsCommand::setInitialConditionCmd)
// Equation Commands
DS_FUNCTION_TABLE(equation,                       dsCommand::createEquationCmd)
DS_FUNCTION_TABLE(interface_equation,             dsCommand::createInterfaceEquationCmd)
DS_FUNCTION_TABLE(contact_equation,               dsCommand::createContactEquationCmd)
DS_FUNCTION_TABLE(custom_equation,                dsCommand::createCustomEquationCmd)
DS_FUNCTION_TABLE(get_equation_numbers,           dsCommand::getEquationNumbersCmd)
DS_FUNCTION_TABLE(get_equation_list,              dsCommand::getEquationListCmd)
DS_FUNCTION_TABLE(get_interface_equation_list,    dsCommand::getInterfaceEquationListCmd)
DS_FUNCTION_TABLE(get_contact_equation_list,      dsCommand::getContactEquationListCmd)
DS_FUNCTION_TABLE(delete_equation,                dsCommand::deleteEquationCmd)
DS_FUNCTION_TABLE(delete_interface_equation,      dsCommand::deleteInterfaceEquationCmd)
DS_FUNCTION_TABLE(delete_contact_equation,        dsCommand::deleteContactEquationCmd)
DS_FUNCTION_TABLE(get_equation_command,           dsCommand::deleteEquationCmd)
DS_FUNCTION_TABLE(get_contact_equation_command,   dsCommand::deleteContactEquationCmd)
DS_FUNCTION_TABLE(get_interface_equation_command, dsCommand::deleteInterfaceEquationCmd)
// Meshing Commands
DS_FUNCTION_TABLE(add_1d_contact,                dsCommand::add1dContactCmd)
DS_FUNCTION_TABLE(add_1d_interface,              dsCommand::add1dInterfaceCmd)
DS_FUNCTION_TABLE(add_1d_mesh_line,              dsCommand::add1dMeshLineCmd)
DS_FUNCTION_TABLE(add_1d_region,                 dsCommand::add1dRegionCmd)
DS_FUNCTION_TABLE(add_2d_contact,                dsCommand::add2dContactCmd)
DS_FUNCTION_TABLE(add_2d_interface,              dsCommand::add2dInterfaceCmd)
DS_FUNCTION_TABLE(add_2d_mesh_line,              dsCommand::add2dMeshLineCmd)
DS_FUNCTION_TABLE(add_2d_region,                 dsCommand::add2dRegionCmd)
DS_FUNCTION_TABLE(add_gmsh_contact,              dsCommand::addGmshContactCmd)
DS_FUNCTION_TABLE(add_gmsh_interface,            dsCommand::addGmshInterfaceCmd)
DS_FUNCTION_TABLE(add_gmsh_region,               dsCommand::addGmshRegionCmd)
DS_FUNCTION_TABLE(create_1d_mesh,                dsCommand::create1dMeshCmd)
DS_FUNCTION_TABLE(create_2d_mesh,                dsCommand::create1dMeshCmd)
DS_FUNCTION_TABLE(create_contact_from_interface, dsCommand::createContactFromInterfaceCmd)
DS_FUNCTION_TABLE(create_device,                 dsCommand::createDeviceCmd)
DS_FUNCTION_TABLE(create_gmsh_mesh,              dsCommand::createGmshMeshCmd)
DS_FUNCTION_TABLE(create_interface_from_nodes,   dsCommand::createInterfaceFromNodesCmd)
DS_FUNCTION_TABLE(delete_device,                 dsCommand::deleteDeviceCmd)
DS_FUNCTION_TABLE(delete_mesh,                   dsCommand::deleteMeshCmd)
DS_FUNCTION_TABLE(finalize_mesh,                 dsCommand::finalizeMeshCmd)
DS_FUNCTION_TABLE(load_devices,                  dsCommand::loadDevicesCmd)
DS_FUNCTION_TABLE(write_devices,                 dsCommand::writeDevicesCmd)
// Circuit Commands
DS_FUNCTION_TABLE(add_circuit_node,            dsCommand::addCircuitNodeCmd)
DS_FUNCTION_TABLE(circuit_element,             dsCommand::circuitElementCmd)
DS_FUNCTION_TABLE(circuit_alter,               dsCommand::circuitAlterCmd)
DS_FUNCTION_TABLE(circuit_node_alias,          dsCommand::circuitNodeAliasCmd)
DS_FUNCTION_TABLE(get_circuit_node_list,       dsCommand::circuitGetCircuitNodeListCmd)
DS_FUNCTION_TABLE(get_circuit_solution_list,   dsCommand::circuitGetCircuitSolutionListCmd)
DS_FUNCTION_TABLE(get_circuit_node_value,      dsCommand::circuitGetCircuitNodeValueCmd)
DS_FUNCTION_TABLE(set_circuit_node_value,      dsCommand::circuitGetCircuitNodeValueCmd)
DS_FUNCTION_TABLE(get_circuit_equation_number, dsCommand::circuitGetCircuitEquationNumberCmd)


text:
package org.elasticsearch.search.aggregations.metrics.scripted;

import org.apache.lucene.index.AtomicReaderContext;
import org.elasticsearch.script.*;
import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.search.SearchParseException;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.metrics.MetricsAggregator;
import org.elasticsearch.search.aggregations.support.AggregationContext;
import org.elasticsearch.search.internal.SearchContext;

import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;

public class ScriptedMetricAggregator extends MetricsAggregator {

    private final String scriptLang;
    private final SearchScript mapScript;
    private final ExecutableScript combineScript;
    private final String reduceScript;
    // initial parameters for same shard scripts {init, map, combine}
    // state can be passed in params between them too
    private final Map<String, Object> params;
    // initial parameters for {reduce}
    private final Map<String, Object> reduceParams;
    private final ScriptType reduceScriptType;

    protected ScriptedMetricAggregator(String name, String scriptLang, ScriptType initScriptType, String initScript,
            ScriptType mapScriptType, String mapScript, ScriptType combineScriptType, String combineScript, ScriptType reduceScriptType,
            String reduceScript, Map<String, Object> params, Map<String, Object> reduceParams, AggregationContext context, Aggregator parent) {
            super(name, 1, BucketAggregationMode.PER_BUCKET, context, parent);
        this.scriptLang = scriptLang;
        this.reduceScriptType = reduceScriptType;
        if (params == null) {
            this.params = new HashMap<>();
            this.params.put("_agg", new HashMap<>());
        } else {
            this.params = new HashMap<>(params);
        }
        if (reduceParams == null) {
            this.reduceParams = new HashMap<>();
        } else {
            this.reduceParams = reduceParams;
        }
        ScriptService scriptService = context.searchContext().scriptService();
        if (initScript != null) {
            scriptService.executable(scriptLang, initScript, initScriptType, ScriptContext.Standard.AGGS, this.params).run();
        }
        this.mapScript = scriptService.search(context.searchContext().lookup(), scriptLang, mapScript, mapScriptType, ScriptContext.Standard.AGGS, this.params);
        if (combineScript != null) {
            this.combineScript = scriptService.executable(scriptLang, combineScript, combineScriptType, ScriptContext.Standard.AGGS, this.params);
        } else {
            this.combineScript = null;
        }
        this.reduceScript = reduceScript;
    }

    @Override
    public boolean shouldCollect() {
        return true;
    }

    @Override
    public void setNextReader(AtomicReaderContext reader) {
        mapScript.setNextReader(reader);
    }

    @Override
    public void collect(int docId, long bucketOrdinal) throws IOException {
        mapScript.setNextDocId(docId);
        mapScript.run();
    }

    @Override
    public InternalAggregation buildAggregation(long owningBucketOrdinal) {
        Object aggregation;
        if (combineScript != null) {
            aggregation = combineScript.run();
        } else {
            aggregation = params.get("_agg");
        }
        return new InternalScriptedMetric(name, aggregation, scriptLang, reduceScriptType, reduceScript, reduceParams);
    }

    @Override
    public InternalAggregation buildEmptyAggregation() {
        return new InternalScriptedMetric(name, null, scriptLang, reduceScriptType, reduceScript, reduceParams);
    }

    public static class Factory extends AggregatorFactory {

        private String scriptLang;
        private ScriptType initScriptType;
        private ScriptType mapScriptType;
        private ScriptType combineScriptType;
        private ScriptType reduceScriptType;
        private String initScript;
        private String mapScript;
        private String combineScript;
        private String reduceScript;
        private Map<String, Object> params;
        private Map<String, Object> reduceParams;

        public Factory(String name, String scriptLang, ScriptType initScriptType, String initScript, ScriptType mapScriptType, String mapScript, ScriptType combineScriptType, String combineScript, ScriptType reduceScriptType, String reduceScript,
                Map<String, Object> params, Map<String, Object> reduceParams) {
            super(name, InternalScriptedMetric.TYPE.name());
            this.scriptLang = scriptLang;
            this.initScriptType = initScriptType;
            this.mapScriptType = mapScriptType;
            this.combineScriptType = combineScriptType;
            this.reduceScriptType = reduceScriptType;
            this.initScript = initScript;
            this.mapScript = mapScript;
            this.combineScript = combineScript;
            this.reduceScript = reduceScript;
            this.params = params;
            this.reduceParams = reduceParams;
        }

        @Override
        public Aggregator create(AggregationContext context, Aggregator parent, long expectedBucketsCount) {
            Map<String, Object> params = null;
            if (this.params != null) {
                params = deepCopyParams(this.params, context.searchContext());
            }
            Map<String, Object> reduceParams = null;
            if (this.reduceParams != null) {
                reduceParams = deepCopyParams(this.reduceParams, context.searchContext());
            }
            return new ScriptedMetricAggregator(name, scriptLang, initScriptType, initScript, mapScriptType, mapScript, combineScriptType,
                    combineScript, reduceScriptType, reduceScript, params, reduceParams, context, parent);
        }

        @SuppressWarnings({ "unchecked" })
        private static <T> T deepCopyParams(T original, SearchContext context) {
            T clone;
            if (original instanceof Map) {
                Map<?, ?> originalMap = (Map<?, ?>) original;
                Map<Object, Object> clonedMap = new HashMap<>();
                for (Entry<?, ?> e : originalMap.entrySet()) {
                    clonedMap.put(deepCopyParams(e.getKey(), context), deepCopyParams(e.getValue(), context));
                }
                clone = (T) clonedMap;
            } else if (original instanceof List) {
                List<?> originalList = (List<?>) original;
                List<Object> clonedList = new ArrayList<Object>();
                for (Object o : originalList) {
                    clonedList.add(deepCopyParams(o, context));
                }
                clone = (T) clonedList;
            } else if (original instanceof String || original instanceof Integer || original instanceof Long || original instanceof Short
                    || original instanceof Byte || original instanceof Float || original instanceof Double || original instanceof Character
                    || original instanceof Boolean) {
                clone = original;
            } else {
                throw new SearchParseException(context, "Can only clone primitives, String, ArrayList, and HashMap. Found: "
                        + original.getClass().getCanonicalName());
            }
            return clone;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
class SubscriptionsController < ApplicationController
  load_resource :find_by => :email_key
  skip_load_resource :only => [:create, :new]
  skip_authorization_check
  skip_before_action :authenticate_user!

  def unsubscribe
    @subscription.unsubscribe!
    redirect_to subscription_path(@subscription.mail_key)
  end

  def subscribe
    @subscription.subscribe!
    redirect_to subscription_path(@subscription.mail_key)
  end

  def confirm
    @subscription.update_attributes(confirmed: true)
    @subscription.send_welcome_email
    redirect_to subscription_path(@subscription.mail_key)
  end

  def show
  end

  def create
    @subscription = Subscription.find_or_initialize_by(:email => subscription_params.delete(:email))
    @subscription.attributes = subscription_params
    @subscription.subscribed = true

    if @subscription.save
      if @subscription.id_changed?
        flash[:notice] = 'You are subscribed. Please check your e-mail to confirm your address (we will not smart e-mailing you until you have done this).'
      else
        flash[:notice] = 'Your subscription has been updated'
      end
    else
      render :new
    end
  end

  def new
    @subscription = Subscription.new(params[:subscription])
  end

  private
    def subscription_params
      params[:subscription].permit(:email, :name, :mailing_list_ids => [])
    end

end


text:
function [yr,Y]= pullseg1(x,yrx,len,offset)
% pullseg1: ovlapping len-year segments of time series x
% [yr,Y]= pullseg1(x,yrx,len,offset);
%
% D. Meko 12-13-93
%
%
%****************************  INPUT ARGS
%
% x (mx x 1) time series
% yrx (mx x 1) corresponding years for the time series x
% len (1 x 1) desired length of the segments (# of years)
% offset (1 x 1) each segment offset this many years from the previous
%
%
%********** OUTPUT ARGS *********************************
%
% yr (1 x ?) ending year of each len-year segment
% Y (mY x nY) each col is a time series segment, nY total segments
%     mY and nY computed in function
%
%
%*******  USER-WRITTEN FUNCTIONS NEEDED --- none
%
%
%******* GLOBALS   -- none
%
%
%******* NOTES *************************************
%
% A low level function to be used with rwlook and other functions. First
% written for rwlook to set up data for computation of Kendall's tau on
% different segments of time series of transformed ring width.

% Preallocate and size.
mx = length(x);  % number of years in input time series

% Compute number of possible segments of the specified length and overlap
nseg1 = mx - len +1;
rs = mx:-offset:len;  % row subscript of last years of segments
nseg2 = length(rs);  % number of possible segments

g = [len-1:-1:0]';  % cv to be duped
G = g(:,ones(nseg2,1));  % dupe cv g
RS = rs(ones(len,1),:);  % dupe rv rs

I = RS - G;  % index to rows of x

yr = rs + yrx(1) - 1;  % rv of ending years of segments
X = x(:,ones(nseg2,1));  % dupe time series cv into matrix
Y = X(I); % pull out desired rows into  cols of Y
yr=fliplr(yr);  % make leftmost ending year the earliest segment
Y=fliplr(Y);  % likewise for the cols of Y


text:
<?php

namespace UthandoContact\InputFilter;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Class ContactInputFilterFactory
 *
 * @package UthandoContact\ServiceManager
 */
class ContactInputFilterFactory implements FactoryInterface
{
    /**
     * @param ServiceLocatorInterface $serviceLocator
     * @return ContactInputFilter
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config         = $serviceLocator->getServiceLocator()->get('config');
        /* @var $request \Zend\Http\PhpEnvironment\Request */
        $request        = $serviceLocator->getServiceLocator()->get('Request');
        $akismetOptions = $config['uthando_common']['akismet'] ?? [];
        $options        = $config['uthando_contact']['form'] ?? [];
        $inputFilter    = new ContactInputFilter();

        $inputFilter->setAkismetEnabled($options['enable_akismet'] ?? false);
        $inputFilter->setAkismetOptions([
            'api_key'       => $akismetOptions['api_key'] ?? null,
            'blog'          => $akismetOptions['blog'] ?? null,
            'user_agent'    => $request->getServer('HTTP_USER_AGENT'),
            'user_ip'       => $request->getServer('REMOTE_ADDR'),
        ]);

        return $inputFilter;
    }
}


text:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

class SugarWidgetFieldNum extends SugarWidgetFieldInt
{

}

?>


text:
package design

import (
	d "github.com/goadesign/goa/design"
	a "github.com/goadesign/goa/design/apidsl"
)

// fieldType is the datatype of a single field in a work item type
var fieldType = a.Type("fieldType", func() {
	a.Description("A fieldType describes the values a particular field can hold")
	a.Attribute("kind", d.String, "The constant indicating the kind of type, for example 'string' or 'enum' or 'instant'")
	a.Attribute("componentType", d.String, "The kind of type of the individual elements for a list type. Required for list types. Must be a simple type, not  enum or list")
	a.Attribute("baseType", d.String, "The kind of type of the enumeration values for an enum type. Required for enum types. Must be a simple type, not  enum or list")
	a.Attribute("values", a.ArrayOf(d.Any), "The possible values for an enum type. The values must be of a type convertible to the base type")
	a.Attribute("defaultValue", d.Any, "Optional default value (if any)")
	a.Required("kind")
})

// fieldDefinition defines the possible values for a field in a work item type
var fieldDefinition = a.Type("fieldDefinition", func() {
	a.Description("A fieldDefinition aggregates a fieldType and additional field metadata")
	a.Attribute("required", d.Boolean)
	a.Attribute("type", fieldType)
	a.Attribute("label", d.String, "A label for the field that is shown in the UI", func() {
		a.Example("Iteration")
		a.MinLength(1)
	})
	a.Attribute("description", d.String, "A description for the field", func() {
		a.Example("The iteration field tells to which iteration a work item belongs.")
		a.MinLength(1)
	})
	a.Required("required", "type", "label", "description")
})

var workItemTypeAttributes = a.Type("WorkItemTypeAttributes", func() {
	a.Description("A work item type describes the values a work item type instance can hold.")
	a.Attribute("version", d.Integer, "Version for optimistic concurrency control")
	a.Attribute("created-at", d.DateTime, "timestamp of entity creation")
	a.Attribute("updated-at", d.DateTime, "timestamp of last entity update")
	a.Attribute("name", d.String, "The human readable name of the work item type", nameValidationFunction)
	a.Attribute("description", d.String, "A human readable description for the work item type", func() {
		a.Example(`A user story encapsulates the action of one function making it possible for software developers to create a vertical slice of their work.`)
	})
	a.Attribute("can-construct", d.Boolean, "Whether or not this work item type is supposed to be used for creating work items directly.")
	a.Attribute("fields", a.HashOf(d.String, fieldDefinition), "Definitions of fields in this work item type", func() {
		a.Example(map[string]interface{}{
			"system.administrator": map[string]interface{}{
				"type": map[string]interface{}{
					"kind": "string",
				},
				"required": true,
			},
		})
		a.MinLength(1)
	})

	// TODO: Maybe this needs to be abandoned at some point
	a.Attribute("extendedTypeName", d.UUID, "If newly created type extends any existing type (This is never present in any response and is only optional when creating.)")

	a.Attribute("icon", d.String, "CSS class string for an icon to use. See http://fontawesome.io/icons/ or http://www.patternfly.org/styles/icons/#_ for examples.", func() {
		a.Example("fa-bug")
		a.MinLength(1)
	})

	//a.Required("version")
	a.Required("fields")
	a.Required("name")
	a.Required("icon")
})

var workItemTypeRelationships = a.Type("WorkItemTypeRelationships", func() {
	a.Attribute("space", relationSpaces, "(OBSOLETE) This defines the owning space of this work item type.")
	a.Attribute("space_template", spaceTemplateRelation, "This defines the owning space template of this work item type.")
	a.Attribute("guidedChildTypes", relationGenericList, "List of work item types that shall be proposed when creating a child of a work item of this type.")
})

var workItemTypeData = a.Type("WorkItemTypeData", func() {
	a.Attribute("type", d.String, func() {
		a.Enum("workitemtypes")
	})
	a.Attribute("id", d.UUID, "ID of work item type (optional during creation)")
	a.Attribute("attributes", workItemTypeAttributes)
	a.Attribute("links", genericLinks)
	a.Attribute("relationships", workItemTypeRelationships)
	a.Required("type", "attributes", "relationships")
})

// workItemTypeLinks has `self` as of now according to http://jsonapi.org/format/#fetching-resources
var workItemTypeLinks = a.Type("WorkItemTypeLinks", func() {
	a.Attribute("self", d.String, func() {
		a.Example("http://api.openshift.io/api/workitemtypes/bug")
	})
	a.Required("self")
})

var workItemTypeListMeta = a.Type("WorkItemTypeListMeta", func() {
	a.Attribute("totalCount", d.Integer)
	a.Required("totalCount")
})

// workItemTypeList contains paged results for listing work item types and paging links
var workItemTypeList = JSONList(
	"WorkItemType", "Holds the paginated response to a work item type list request",
	workItemTypeData,
	pagingLinks,
	workItemTypeListMeta)

// workItemTypeSingle is the media type for for a single work item type
var workItemTypeSingle = JSONSingle(
	"WorkItemType", "A work item type describes the values a work item type instance can hold.",
	workItemTypeData,
	workItemTypeLinks)

var _ = a.Resource("workitemtype", func() {
	a.BasePath("/workitemtypes")

	a.Action("show", func() {
		a.Routing(
			a.GET("/:witID"),
		)
		a.Description("Retrieve work item type with given ID.")
		a.Params(func() {
			a.Param("witID", d.UUID, "ID of the work item type")
		})
		a.UseTrait("conditional")
		a.Response(d.OK, workItemTypeSingle)
		a.Response(d.NotModified)
		a.Response(d.BadRequest, JSONAPIErrors)
		a.Response(d.NotFound, JSONAPIErrors)
		a.Response(d.InternalServerError, JSONAPIErrors)
	})
})

var _ = a.Resource("workitemtypes", func() {
	a.Parent("space_template")
	a.BasePath("/workitemtypes")

	a.Action("list", func() {
		a.Routing(
			a.GET(""),
		)
		a.Description("List work item types.")
		a.UseTrait("conditional")
		a.Response(d.OK, workItemTypeList)
		a.Response(d.NotModified)
		a.Response(d.BadRequest, JSONAPIErrors)
		a.Response(d.NotFound, JSONAPIErrors)
		a.Response(d.InternalServerError, JSONAPIErrors)
	})
})


text:
package science.wasabi.tini.bot

import scala.collection.immutable.Iterable

import akka.NotUsed
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Sink, Source}

import science.wasabi.tini._
import science.wasabi.tini.bot.commands._
import science.wasabi.tini.bot.discord.ingestion.{AkkaCordIngestion, Ingestion}
import science.wasabi.tini.bot.kafka.KafkaStreams
import science.wasabi.tini.config.Config

object BotMain extends App {
  println(Helper.greeting)

  implicit val config = Config.conf
  CommandRegistry.configure(config.bot.commands)

  case class Ping(override val args: String) extends Command(args) {}
  case class NoOp(override val args: String) extends Command(args) {}

  val ingestion: Ingestion = new AkkaCordIngestion

  import scala.concurrent.ExecutionContext.Implicits.global
  implicit val system = akka.actor.ActorSystem("kafka")
  implicit val materializer = ActorMaterializer()

  val kafka = new KafkaStreams

  // pipe to kafka
  def string2command(string: String): Iterable[Command] = CommandRegistry.getCommandsFor(string)
  val commandStream: Source[Command, NotUsed] = ingestion.source.mapConcat[Command](dmsg => string2command(dmsg.content))
  val commandTopicStream = commandStream.map(kafka.toCommandTopic)
  commandTopicStream
    .runWith(kafka.sink)
    .foreach(_ => println("Done Producing"))

  // read from kafka
  val commandStreamFromKafka = kafka.sourceFromCommandTopic()
  commandStreamFromKafka
    .map(command => println("out: " + command))
    .runWith(Sink.ignore)
    .foreach(_ => println("Done Consuming"))

  // TODO: add the reply steam thingy
}


text:
declare module "node-gcm" {

    export interface IMessageOptions {
        collapseKey?: string;
        delayWhileIdle?: boolean;
        timeToLive?: number;
        dryRun?: boolean;
    }

    export class Message {
        constructor(options?: IMessageOptions);
        collapseKey: string;
        delayWhileIdle: boolean;
        timeToLive: number;
        dryRun: boolean;

        addData(key: string, value: string): void;
        addData(data: any): void;
    }

    export interface ISenderOptions {
        proxy?: any;
        maxSockets?: number;
        timeout?: number;
    }
    export interface ISenderSendOptions {
        retries?: number;
        backoff?: number;
    }

    export class Sender {
        constructor(key: string, options?: ISenderOptions);
        key: string;
        options: ISenderOptions;

        send(message: Message, registrationIds: string|string[], callback: (err: any, resJson: IResponseBody) => void): void;
        send(message: Message, registrationIds: string|string[], retries: number, callback: (err: any, resJson: IResponseBody) => void): void;
        send(message: Message, registrationIds: string|string[], options: ISenderSendOptions, callback: (err: any, resJson: IResponseBody) => void): void;
        sendNoRetry(message: Message, registrationIds: string|string[], callback: (err: any, resJson: IResponseBody) => void): void;
    }

    export interface IResponseBody {
        success: number;
        failure: number;
        canonical_ids: number;
        multicast_id?: number;
        results?: {
            message_id?: string;
            registration_id?: string;
            error?: string;
        }[];
    }

}


text:
package com.thinkbiganalytics.feedmgr.rest.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.thinkbiganalytics.feedmgr.rest.model.ImportComponentOption;
import com.thinkbiganalytics.feedmgr.rest.model.ImportFeedOptions;
import com.thinkbiganalytics.feedmgr.rest.model.ImportTemplateOptions;
import com.thinkbiganalytics.feedmgr.rest.model.UploadProgress;
import com.thinkbiganalytics.feedmgr.service.MetadataService;
import com.thinkbiganalytics.feedmgr.service.UploadProgressService;
import com.thinkbiganalytics.feedmgr.service.feed.ExportImportFeedService;
import com.thinkbiganalytics.feedmgr.service.template.ExportImportTemplateService;
import com.thinkbiganalytics.feedmgr.util.ImportUtil;
import com.thinkbiganalytics.json.ObjectMapperSerializer;
import com.thinkbiganalytics.rest.model.RestResponseStatus;

import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;

import java.io.InputStream;
import java.util.Set;

import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;

/**
 * REST API for administrative functions.
 */
@Api(tags = "Feed Manager - Administration", produces = "application/json")
@Path(AdminControllerV2.BASE)
@SwaggerDefinition(tags = @Tag(name = "Feed Manager - Administration", description = "administrator operations"))
public class AdminControllerV2 {

    public static final String BASE = "/v2/feedmgr/admin";
    public static final String IMPORT_TEMPLATE = "/import-template";
    public static final String IMPORT_FEED = "/import-feed";

    @Inject
    ExportImportTemplateService exportImportTemplateService;

    @Inject
    ExportImportFeedService exportImportFeedService;

    @Inject
    UploadProgressService uploadProgressService;

    /**
     * Feed manager metadata service
     */
    @Inject
    MetadataService metadataService;

    @GET
    @Path("/upload-status/{key}")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation("Gets thet status of a given upload/import.")
    @ApiResponses({
                      @ApiResponse(code = 200, message = "Returns the upload status")
                  })
    public Response uploadStatus(@NotNull @PathParam("key") String key) {
        UploadProgress uploadProgress = uploadProgressService.getUploadStatus(key);
        if (uploadProgress != null) {
            uploadProgress.checkAndIncrementPercentage();
            return Response.ok(uploadProgress).build();
        } else {
            return Response.ok(uploadProgress).build();
        }
    }

    @POST
    @Path(IMPORT_FEED)
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation("Imports a feed zip file.")
    @ApiResponses({
                      @ApiResponse(code = 200, message = "Returns the feed metadata.", response = ExportImportFeedService.ImportFeed.class),
                      @ApiResponse(code = 500, message = "There was a problem importing the feed.", response = RestResponseStatus.class)
                  })
    public Response uploadFeed(@NotNull @FormDataParam("file") InputStream fileInputStream,
                               @NotNull @FormDataParam("file") FormDataContentDisposition fileMetaData,
                               @NotNull @FormDataParam("uploadKey") String uploadKey,
                               @FormDataParam("categorySystemName") String categorySystemName,
                               @FormDataParam("disableFeedUponImport") @DefaultValue("false") boolean disableFeedUponImport,
                               @FormDataParam("importComponents") String importComponents)
        throws Exception {
        ImportFeedOptions options = new ImportFeedOptions();
        options.setUploadKey(uploadKey);
        options.setDisableUponImport(disableFeedUponImport);
        ExportImportFeedService.ImportFeed importFeed = null;

        options.setCategorySystemName(categorySystemName);

        boolean overwriteFeed = true;
        boolean overwriteTemplate = true;
        uploadProgressService.newUpload(uploadKey);

        if (importComponents == null) {
            byte[] content = ImportUtil.streamToByteArray(fileInputStream);
            importFeed = exportImportFeedService.validateFeedForImport(fileMetaData.getFileName(), content, options);
            importFeed.setSuccess(false);
        } else {
            options.setImportComponentOptions(ObjectMapperSerializer.deserialize(importComponents, new TypeReference<Set<ImportComponentOption>>() {
            }));
            byte[] content = ImportUtil.streamToByteArray(fileInputStream);
            importFeed = exportImportFeedService.importFeed(fileMetaData.getFileName(), content, options);
        }
        uploadProgressService.removeUpload(uploadKey);
        return Response.ok(importFeed).build();
    }

    @POST
    @Path(IMPORT_TEMPLATE)
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation("Imports a template xml or zip file.")
    @ApiResponses({
                      @ApiResponse(code = 200, message = "Returns the template metadata.", response = ExportImportTemplateService.ImportTemplate.class),
                      @ApiResponse(code = 500, message = "There was a problem importing the template.", response = RestResponseStatus.class)
                  })
    public Response uploadTemplate(@NotNull @FormDataParam("file") InputStream fileInputStream,
                                   @NotNull @FormDataParam("file") FormDataContentDisposition fileMetaData,
                                   @NotNull @FormDataParam("uploadKey") String uploadKey,
                                   @FormDataParam("importComponents") String importComponents)
        throws Exception {
        ImportTemplateOptions options = new ImportTemplateOptions();
        options.setUploadKey(uploadKey);
        ExportImportTemplateService.ImportTemplate importTemplate = null;
        byte[] content = ImportUtil.streamToByteArray(fileInputStream);

        uploadProgressService.newUpload(uploadKey);

        if (importComponents == null) {
            importTemplate = exportImportTemplateService.validateTemplateForImport(fileMetaData.getFileName(), content, options);
            importTemplate.setSuccess(false);
        } else {
            options.setImportComponentOptions(ObjectMapperSerializer.deserialize(importComponents, new TypeReference<Set<ImportComponentOption>>() {
            }));
            importTemplate = exportImportTemplateService.importTemplate(fileMetaData.getFileName(), content, options);
        }
        return Response.ok(importTemplate).build();
    }

}


text:
/**
 * @url www.couchfriends.com
 * Tutorial: How to create a real-time multiplayer game in less than 30 minutes
 **/

/**
 * Basic class for all game sprites
 * @constructor
 */
var Sprite = function() {

    this.name = '';
    this.visible = true;
    this.color = '#000000';
    this.size = {
        width: 10,
        height: 10
    };
    this.position = {
        x: 0,
        y: 0
    };
    this.collisionList = [];
};

Sprite.prototype = {

    update: function(time) {
        if (this.visible == false) {
            return false;
        }
        if (this.collisionList.length > 0) {
            for (var i = 0; i < GameObjects.length; i++) {
                if (this.collisionList.indexOf(GameObjects[i].name) > -1 &&
                    this.checkCollision(GameObjects[i])) {
                    this.collide(GameObjects[i]);
                }
            }
        }
        return true;
    },

    draw: function() {

        if (this.visible == true) {
            ctx.beginPath();
            ctx.rect(this.position.x, this.position.y, this.size.width, this.size.width);
            ctx.fillStyle = this.color;
            ctx.fill();
        }
    },

    add: function() {
        GameObjects.push(this);
    },

    remove: function() {

        var indexOf = GameObjects.indexOf(this);
        GameObjects.splice(indexOf, 1);

    },

    collide: function (target) {

    },

    checkCollision: function(target) {
        if (this.position.x < target.position.x + target.size.width &&
            this.position.x + this.size.width > target.position.x &&
            this.position.y < target.position.y + target.size.height &&
            this.size.height + this.position.y > target.position.y) {
            return true;
        }
        return false;
    }

};

/**
 * Obstacle that can collide with players
 * @constructor
 */
Obstacle = function () {

    Sprite.call(this);
    this.name = 'obstacle';
    this.color = '#ff0000';
    this.size = {
        width: 50,
        height: 50
    }

};

Obstacle.prototype = Object.create(Sprite.prototype);
Obstacle.prototype.constructor = Obstacle;

Obstacle.prototype.update = function(time) {

    if (!Sprite.prototype.update.call(this, time)) {
        return false;
    }

    this.position.y += 1;

    if (this.position.y > (game.height+this.size.height)) {
        this.position.x = Math.random() * game.width;
        this.position.y = -(this.size.height);
    }

};

Player = function () {

    Sprite.call(this);
    this.name = 'player';
    this.color = '#0000ff';
    this.size = {
        width: 50,
        height: 50
    };
    this.speed = {
        x: 0,
        y: 0
    };
    this.position.x = game.width / 2;
    this.position.y = game.height - 60;
    this.collisionList = ['obstacle'];

};

Player.prototype = Object.create(Sprite.prototype);
Player.prototype.constructor = Player;

Player.prototype.update = function(time) {

    if (!Sprite.prototype.update.call(this, time)) {
        return false;
    }

    if (this.speed.x < -10) {
        this.speed.x = -10;
    }
    else if (this.speed.x > 10) {
        this.speed.x = 10;
    }

    this.position.x += this.speed.x;
    if (this.position.x < 0) {
        this.position.x = 0;
    }
    else if (this.position.x > (game.width-this.size.width)) {
        this.position.x = (game.width-this.size.width);
    }

    this.speed.x *= .95;

    game.score++;

};

Player.prototype.collide = function(target) {

    Sprite.prototype.collide.call(this, target);
    game.score = 0;

};


text:
var express = require('express');

var http = require('http');
var path = require('path');
var url = require('url');

var bodyParser = require('body-parser');
var levelup = require('levelup');

var app = express();

app.set('port', process.env.PORT || 3000);

app.use(bodyParser.json());

var db = levelup('./contact', {valueEncoding: 'json'});

app.get('/contacts/:number', function (request, response) {
  db.get(request.params.number, function (error, data) {
    if (error) {
      response.writeHead(404, {'Content-Type': 'text/plain'});
      response.end('Not Found');
    } else {
      response.setHeader('content-type', 'application/json');
      response.send(data);
    }
  });
});

app.post('/contacts/:number', function (request, response) {
  db.put(request.params.number, request.body, function (error) {
    if (error) {
      response.writeHead(500, {'Content-Type' : 'text/plain'});
      response.end('Internal server error');
    } else {
      response.send(request.params.number + ' successfully inserted');
    }
  });
});

app.del('/contacts/:number', function (request, response) {
  db.del(request.params.number, function (error) {
    if (error) {
      response.writeHead(500, {'Content-Type' : 'text/plain'});
      response.end('Internal server error');
    } else {
      response.send(request.params.number + ' successfully deleted');
    }
  });
});

app.get('/contacts', function (request, response) {
  var isFirst = true;
  response.setHeader('content-type', 'application/json');

  db.createReadStream()
    .on('data', function (data) {
      if (isFirst == true) {
        response.write('[');
      } else {
        response.write(',');
      }

      response.write(JSON.stringify(data.value));
      isFirst = false;
    })
    .on('error', function (error) {
      console.log('Error while reading', error)
    })
    .on('close', function () {
      console.log('Closing dbstream');
    })
    .on('end', function () {
      console.log('Db stream closed');
      response.end(']');
    })
});

http.createServer(app).listen(app.get('port'));


text:
#ifndef DIRENT_IMPL_H_
#define DIRENT_IMPL_H_

#include <sys/types.h>
#include <sys/cdefs.h>

#include <fs/dvfs.h>

struct DIR_struct {
	struct dirent dirent;
	struct dir_ctx ctx;
	struct dentry *dir_dentry;
	struct dentry *prv_dentry;
};

#endif /* DIRENT_IMPL_H_ */


text:
//
//  ClosetCollectionHeaderView.m
//  Wearit
//
//  Created by Ajeet Pratap on 30/05/15.
//  Copyright (c) 2015 Ajeet Pratap. All rights reserved.
//

#import "ClosetCollectionHeaderView.h"

@implementation ClosetCollectionHeaderView
@synthesize addClothBtn;
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end


text:
<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:clickable="true"
            android:onClick="buttonPressed"
            android:src="@drawable/parse_extras_button_close"
            android:id="@+id/button_close" />

    <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center">

        <FrameLayout
                android:layout_marginBottom="@dimen/parse_extras_screen_margin"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

            <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/parse_extras_login_title"
                    android:id="@+id/title_text"
                    android:textSize="40sp"
                    android:gravity="center"/>

            <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:id="@+id/title_image"/>
        </FrameLayout>

        <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

            <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="@dimen/parse_extras_screen_margin"
                    android:layout_marginTop="@dimen/parse_extras_half_edittext_height"
                    android:layout_height="wrap_content"
                    android:gravity="right">

                <com.nextfaze.android.parse_extras.widget.VerticalButton
                        android:background="@drawable/parse_extras_button_forgot_background"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/parse_extras_forgot"
                        android:id="@+id/button_forgot"
                        android:onClick="buttonPressed"
                        android:textColor="@android:color/white"
                        android:paddingLeft="5sp"
                        android:paddingRight="5sp"
                        android:paddingTop="2sp"
                        android:paddingBottom="2sp"
                        android:textSize="10sp"
                        android:layout_marginRight="2px"
                        android:gravity="bottom|right" />

            </LinearLayout>

            <LinearLayout
                    android:orientation="vertical"
                    android:layout_marginRight="@dimen/parse_extras_screen_margin"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                <EditText
                        style="@style/ParseExtrasEditText"
                        android:id="@+id/username"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/parse_extras_username"
                        android:inputType="textNoSuggestions"/>
                <EditText
                        style="@style/ParseExtrasEditText"
                        android:id="@+id/password"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/parse_extras_password"
                        android:inputType="textPassword"/>

                <Button
                        style="@style/ParseExtrasButton"
                        android:background="@drawable/parse_extras_button_login_background"
                        android:onClick="buttonPressed"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/parse_extras_button_login"
                        android:id="@+id/button_log_in"
                        android:layout_gravity="center_horizontal"/>

                <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/parse_extras_login_extras"
                        android:layout_marginTop="20dip"
                        android:gravity="center"/>
                <Button
                        style="@style/ParseExtrasButton"
                        android:background="@drawable/parse_extras_button_facebook_background"
                        android:drawableLeft="@drawable/parse_extras_facebook_logo"
                        android:drawablePadding="-20sp"
                        android:onClick="buttonPressed"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/parse_extras_button_facebook"
                        android:id="@+id/button_facebook"
                        android:layout_gravity="center_horizontal"/>

                <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/parse_extras_no_account_yet"
                        android:layout_marginTop="20dip"
                        android:gravity="center"/>
                <Button
                        style="@style/ParseExtrasButton"
                        android:background="@drawable/parse_extras_button_sign_up_background"
                        android:onClick="buttonPressed"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/parse_extras_button_sign_up"
                        android:id="@+id/button_sign_up"
                        android:layout_gravity="center_horizontal"/>

            </LinearLayout>
        </LinearLayout>

    </LinearLayout>
</FrameLayout>


text:
#include <lk/err.h>
#include <dev/class/netif.h>

status_t class_netif_set_state(struct device *dev, struct netstack_state *state) {
    struct netif_ops *ops = device_get_driver_ops(dev, struct netif_ops, std);
    if (!ops)
        return ERR_NOT_CONFIGURED;

    if (ops->set_state)
        return ops->set_state(dev, state);
    else
        return ERR_NOT_SUPPORTED;
}

ssize_t class_netif_get_hwaddr(struct device *dev, void *buf, size_t max_len) {
    struct netif_ops *ops = device_get_driver_ops(dev, struct netif_ops, std);
    if (!ops)
        return ERR_NOT_CONFIGURED;

    if (ops->get_hwaddr)
        return ops->get_hwaddr(dev, buf, max_len);
    else
        return ERR_NOT_SUPPORTED;
}

ssize_t class_netif_get_mtu(struct device *dev) {
    struct netif_ops *ops = device_get_driver_ops(dev, struct netif_ops, std);
    if (!ops)
        return ERR_NOT_CONFIGURED;

    if (ops->get_mtu)
        return ops->get_mtu(dev);
    else
        return ERR_NOT_SUPPORTED;
}

status_t class_netif_set_status(struct device *dev, bool up) {
    struct netif_ops *ops = device_get_driver_ops(dev, struct netif_ops, std);
    if (!ops)
        return ERR_NOT_CONFIGURED;

    if (ops->set_status)
        return ops->set_status(dev, up);
    else
        return ERR_NOT_SUPPORTED;
}

status_t class_netif_output(struct device *dev, struct pbuf *p) {
    struct netif_ops *ops = device_get_driver_ops(dev, struct netif_ops, std);
    if (!ops)
        return ERR_NOT_CONFIGURED;

    if (ops->output)
        return ops->output(dev, p);
    else
        return ERR_NOT_SUPPORTED;
}

status_t class_netif_mcast_filter(struct device *dev, const uint8_t *mac, int action) {
    struct netif_ops *ops = device_get_driver_ops(dev, struct netif_ops, std);
    if (!ops)
        return ERR_NOT_CONFIGURED;

    if (ops->mcast_filter)
        return ops->mcast_filter(dev, mac, action);
    else
        return ERR_NOT_SUPPORTED;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">SmallWeather</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

    <string name="getting_weather_info">正在获取天气数据,请稍后...</string>
    <string name="base_url">http://m.weather.com.cn/data/sk/</string>

</resources>


text:
/**
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 **/

#include "stateengine/AtomicState.h"
#include "stateengine/Defines.h"
//--------------------------------------------------------------------
// TAtomicState
//--------------------------------------------------------------------
//--------------------------------------------------------------------

namespace donut
{
	typedef void (*TUpdaterFunction)(const TStateEngineId&, double);
	typedef void (*TStateCallBack)(const TStateEngineId&, TStateData *);
	//--------------------------------------------------------------------
 	TAtomicState::TAtomicState(TStateEngineId parStateEngineId, TStateId parId, TStateData (* parTStateData), void (* parEnterCallBack), void (* parLeaveCallBack), void (* parUpdater))
 	: FStateEngineId (parStateEngineId)
 	{
 		FEnterCallBack = parEnterCallBack;

 		FLeaveCallBack = parLeaveCallBack;

 		FStateData = parTStateData;

 		FUpdater = parUpdater;

 		FId = parId;
 	}

 	TAtomicState::~TAtomicState()
 	{
 		// assert_msg_NO_RELEASE(FStateData!=NULL, "The state data has been already deleted. you do not need to.")
 		delete FStateData;
 	}

	void TAtomicState::AddTransition(TTransitionId parId, TTransition * parTransition)
 	{
 		FOutTransitions[parId] = parTransition;
 	}

 	#if _DEBUG
 	void TAtomicState::AddInTransition(const TTransition * parTransition)
 	{
 		// FInTransitions.push_back(parTransition)
 	}
	#endif

	void TAtomicState::Update(double parDt)
	{
		void (*updater)( const TStateEngineId&, double) = *((TUpdaterFunction*) (&FUpdater));
		updater(FStateEngineId , parDt);
	}

	void TAtomicState::Enter()
	{
		void (*enter)(const TStateEngineId&, TStateData *) = *((TStateCallBack*) (&FEnterCallBack));
		enter(FStateEngineId, FStateData);

	}

	void TAtomicState::Leave()
	{
		void (*leave)(const TStateEngineId&, TStateData *) = *((TStateCallBack*) (&FLeaveCallBack));
		leave(FStateEngineId, FStateData);
	}

	void TAtomicState::TransitionCallBack()
	{

	}

} // End namestate StateEngine


text:
import * as ev from 'events';
import * as readline from 'readline';
import * as chalk from 'chalk';

/**
 * Progress bar
 */
export default class extends ev.EventEmitter {
	public max: number;
	public value: number;
	public text: string;
	private indicator: number;

	constructor(max: number, text: string = null) {
		super();
		this.max = max;
		this.value = 0;
		this.text = text;
		this.indicator = 0;
		this.draw();

		const iclock = setInterval(() => {
			this.indicator = (this.indicator + 1) % 4;
			this.draw();
		}, 200);

		this.on('complete', () => {
			clearInterval(iclock);
		});
	}

	public increment(): void {
		this.value++;
		this.draw();

		// Check if it is fulfilled
		if (this.value === this.max) {
			this.indicator = null;

			cll();
			process.stdout.write(`${this.render()} -> ${chalk.bold('Complete')}\n`);

			this.emit('complete');
		}
	}

	public draw(): void {
		const str = this.render();
		cll();
		process.stdout.write(str);
	}

	private render(): string {
		const width = 30;
		const t = this.text ? `${this.text} ` : '';

		const v = Math.floor((this.value / this.max) * width);
		const vs = new Array(v + 1).join('*');

		const p = width - v;
		const ps = new Array(p + 1).join(' ');

		const percentage = Math.floor((this.value / this.max) * 100);
		const percentages = chalk.gray(`(${percentage} %)`);

		let i: string;
		switch (this.indicator) {
			case 0: i = '-'; break;
			case 1: i = '\\'; break;
			case 2: i = '|'; break;
			case 3: i = '/'; break;
			case null: i = '+'; break;
		}

		return `${i} ${t}[${vs}${ps}] ${this.value} / ${this.max} ${percentages}`;
	}
}

/**
 * Clear current line
 */
function cll(): void {
	readline.clearLine(process.stdout, 0); // Clear current text
	readline.cursorTo(process.stdout, 0, null); // Move cursor to the head of line
}


text:
<?php

namespace Oro\Bundle\ApiBundle\Request;

/**
 * API version related utilities.
 */
final class Version
{
    /** a string that can be used to reference the latest API version */
    public const LATEST = 'latest';

    /**
     * Normalizes a given API version.
     * If the given version is NULL, the "latest" version will be returned.
     * If the given version number contains meaningless prefix, e.g. "v", it will be removed.
     *
     * @param string|null $version
     *
     * @return string
     */
    public static function normalizeVersion(?string $version): string
    {
        if (null === $version) {
            $version = self::LATEST;
        } elseif (0 === \strpos($version, 'v')) {
            $version = \substr($version, 1);
        }

        return $version;
    }
}


text:
package org.pentaho.mongo;

import java.net.UnknownHostException;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;

import org.pentaho.di.core.Const;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.steps.mongodbinput.MongoDbInputData;
import org.pentaho.di.trans.steps.mongodbinput.MongoDbInputMeta;
import org.pentaho.di.trans.steps.mongodboutput.MongoDbOutputMeta;
import org.pentaho.mongo.KerberosUtil.JaasAuthenticationMode;

import com.mongodb.BasicDBList;
import com.mongodb.CommandResult;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.TaggableReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.util.JSON;

/**
 * Static utility routines for MongoDB. Initialize and configure a connection,
 * retrieve replica set member info from the system.replset collection, retrieve
 * tag sets defined for replica set members, get any custom getLastErrorModes
 * etc.
 *
 * @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
 */
public class MongoUtils {

  private static Class<?> PKG = MongoUtils.class;

  public static final int MONGO_DEFAULT_PORT = 27017;

  public static final String LOCAL_DB = "local"; //$NON-NLS-1$
  public static final String REPL_SET_COLLECTION = "system.replset"; //$NON-NLS-1$
  public static final String REPL_SET_SETTINGS = "settings"; //$NON-NLS-1$
  public static final String REPL_SET_LAST_ERROR_MODES = "getLastErrorModes"; //$NON-NLS-1$
  public static final String REPL_SET_MEMBERS = "members"; //$NON-NLS-1$

  /**
   * Create a credentials object
   *
   * @param username the username to use
   * @param password the password to use (normal authentication only)
   * @param dbName the database to authenticate against (normal authentication
   *          only)
   * @param kerberos true if Kerberos authentication is to be used
   * @return a configured MongoCredential object
   */
  public static MongoCredential createCredentials(String username,
      String password, String dbName, boolean kerberos) {
    MongoCredential cred = null;

    if (kerberos) {
      if (!Const.isEmpty(username)) {
        cred = MongoCredential.createGSSAPICredential(username);
      }
    } else {
      // standard authentication
      if (!Const.isEmpty(username) || !Const.isEmpty(password)) {
        cred = MongoCredential.createMongoCRCredential(username, dbName,
            password.toCharArray());
      }
    }

    return cred;
  }

  /**
   * Create a credentials object
   *
   * @param meta MongoDBOutputMeta to use for getting username, password etc.
   * @param vars for resolving environment variables
   * @return a configured MongoCredential object
   */
  public static MongoCredential createCredentials(MongoDbOutputMeta meta,
      VariableSpace vars) {
    String realUser = vars.environmentSubstitute(meta.getUsername());
    String realPass = Encr.decryptPasswordOptionallyEncrypted(vars
        .environmentSubstitute(meta.getPassword()));

    return createCredentials(realUser, realPass, meta.getDBName(),
        meta.getUseKerberosAuthentication());
  }

  /**
   * Create a credentials object
   *
   * @param meta MongoDBInputMeta to use for getting username, password etc.
   * @param vars for resolving environment variables
   * @return a configured MongoCredential object
   */
  public static MongoCredential createCredentials(MongoDbInputMeta meta,
      VariableSpace vars) {
    String realUser = vars.environmentSubstitute(meta.getAuthenticationUser());
    String realPass = Encr.decryptPasswordOptionallyEncrypted(vars
        .environmentSubstitute(meta.getAuthenticationPassword()));

    return createCredentials(realUser, realPass, meta.getDbName(),
        meta.getUseKerberosAuthentication());
  }

  /**
   * Utility method to configure Mongo connection options
   *
   * @param optsBuilder an options builder
   * @param connTimeout the connection timeout to use (can be null)
   * @param socketTimeout the socket timeout to use (can be null)
   * @param readPreference the read preference to use (can be null)
   * @param writeConcern the writeConcern to use (can be null)
   * @param wTimeout the w timeout to use (can be null)
   * @param journaled whether to use journaled writes
   * @param tagSet the tag set to use in conjunction with the read preference
   *          (can be null)
   * @param vars variables to use
   * @param log for logging
   * @throws KettleException if a problem occurs
   */
  public static void configureConnectionOptions(
      MongoClientOptions.Builder optsBuilder, String connTimeout,
      String socketTimeout, String readPreference, String writeConcern,
      String wTimeout, boolean journaled, List<String> tagSet,
      VariableSpace vars, LogChannelInterface log) throws KettleException {

    // connection timeout
    if (!Const.isEmpty(connTimeout)) {
      String connS = vars.environmentSubstitute(connTimeout);
      try {
        int cTimeout = Integer.parseInt(connS);
        if (cTimeout > 0) {
          optsBuilder.connectTimeout(cTimeout);
        }
      } catch (NumberFormatException n) {
        throw new KettleException(n);
      }
    }

    // socket timeout
    if (!Const.isEmpty(socketTimeout)) {
      String sockS = vars.environmentSubstitute(socketTimeout);
      try {
        int sockTimeout = Integer.parseInt(sockS);
        if (sockTimeout > 0) {
          optsBuilder.socketTimeout(sockTimeout);
        }
      } catch (NumberFormatException n) {
        throw new KettleException(n);
      }
    }

    if (log != null) {
      String rpLogSetting = NamedReadPreference.PRIMARY.getName();

      if (!Const.isEmpty(readPreference)) {
        rpLogSetting = readPreference;
      }
      log.logBasic(BaseMessages.getString(PKG,
          "MongoUtils.Message.UsingReadPreference", rpLogSetting)); //$NON-NLS-1$
    }
    DBObject firstTagSet = null;
    DBObject[] remainingTagSets = new DBObject[0];
    if (tagSet != null && tagSet.size() > 0) {
      if (tagSet.size() > 1) {
        remainingTagSets = new DBObject[tagSet.size() - 1];
      }

      firstTagSet = (DBObject) JSON.parse(tagSet.get(0).trim());
      for (int i = 1; i < tagSet.size(); i++) {
        remainingTagSets[i - 1] = (DBObject) JSON.parse(tagSet.get(i).trim());
      }
      if (log != null
          && (!Const.isEmpty(readPreference) && !readPreference
              .equalsIgnoreCase(NamedReadPreference.PRIMARY.getName()))) {
        StringBuilder builder = new StringBuilder();
        for (String s : tagSet) {
          builder.append(s).append(" "); //$NON-NLS-1$
        }
        log.logBasic(BaseMessages
            .getString(
                PKG,
                "MongoUtils.Message.UsingReadPreferenceTagSets", builder.toString())); //$NON-NLS-1$
      }
    } else {
      if (log != null) {
        log.logBasic(BaseMessages.getString(PKG,
            "MongoUtils.Message.NoReadPreferenceTagSetsDefined")); //$NON-NLS-1$
      }
    }

    // read preference
    if (!Const.isEmpty(readPreference)) {

      String rp = vars.environmentSubstitute(readPreference);

      NamedReadPreference preference = NamedReadPreference.byName(rp);

      if ((firstTagSet != null)
          && (preference.getPreference() instanceof TaggableReadPreference)) {
        optsBuilder.readPreference(preference.getTaggableReadPreference(
            firstTagSet, remainingTagSets));
      } else {
        optsBuilder.readPreference(preference.getPreference());
      }

    }

    // write concern
    writeConcern = vars.environmentSubstitute(writeConcern);
    wTimeout = vars.environmentSubstitute(wTimeout);

    WriteConcern concern = null;

    if (Const.isEmpty(writeConcern) && Const.isEmpty(wTimeout) && !journaled) {
      // all defaults - timeout 0, journal = false, w = 1
      concern = new WriteConcern();
      concern.setWObject(new Integer(1));

      if (log != null) {
        log.logBasic(BaseMessages.getString(PKG,
            "MongoUtils.Message.ConfiguringWithDefaultWriteConcern"));
      }
    } else {
      int wt = 0;
      if (!Const.isEmpty(wTimeout)) {
        try {
          wt = Integer.parseInt(wTimeout);
        } catch (NumberFormatException n) {
          throw new KettleException(n);
        }
      }

      if (!Const.isEmpty(writeConcern)) {
        // try parsing as a number first
        try {
          int wc = Integer.parseInt(writeConcern);
          concern = new WriteConcern(wc, wt, false, journaled);

          if (log != null) {
            String lwc = "w = " + writeConcern + ", wTimeout = " + wt
                + ", journaled = " + (new Boolean(journaled).toString());
            log.logBasic(BaseMessages.getString(PKG,
                "MongoUtils.Message.ConfiguringWithWriteConcern", lwc));
          }
        } catch (NumberFormatException n) {
          // assume its a valid string - e.g. "majority" or a custom
          // getLastError label associated with a tag set
          concern = new WriteConcern(writeConcern, wt, false, journaled);

          if (log != null) {
            String lwc = "w = " + writeConcern + ", wTimeout = " + wt
                + ", journaled = " + (new Boolean(journaled).toString());
            log.logBasic(BaseMessages.getString(PKG,
                "MongoUtils.Message.ConfiguringWithWriteConcern", lwc));
          }
        }
      } else {
        concern = new WriteConcern(1, wt, false, journaled);

        if (log != null) {
          String lwc = "w = 1" + ", wTimeout = " + wt + ", journaled = "
              + (new Boolean(journaled).toString());
          log.logBasic(BaseMessages.getString(PKG,
              "MongoUtils.Message.ConfiguringWithWriteConcern", lwc));
        }
      }
    }
    optsBuilder.writeConcern(concern);
  }

  public static MongoClient initConnection(String hostsPorts,
      String singlePort, MongoCredential cred, boolean useAllReplicaSetMembers,
      String connTimeout, String socketTimeout, String readPreference,
      String writeConcern, String wTimeout, boolean journaled,
      List<String> tagSet, VariableSpace vars, LogChannelInterface log)
      throws KettleException {

    hostsPorts = vars.environmentSubstitute(hostsPorts);
    singlePort = vars.environmentSubstitute(singlePort);
    int singlePortI = -1;

    try {
      singlePortI = Integer.parseInt(singlePort);
    } catch (NumberFormatException n) {
      // don't complain
    }

    if (Const.isEmpty(hostsPorts)) {
      throw new KettleException(BaseMessages.getString(PKG,
          "MongoUtils.Message.Error.EmptyHostsString")); //$NON-NLS-1$
    }

    List<ServerAddress> repSet = new ArrayList<ServerAddress>();

    // if (useAllReplicaSetMembers) {
    // repSet = getReplicaSetMembers(hostsPorts, singlePort, cred, vars, log);
    //
    // if (repSet.size() == 0) {
    // useAllReplicaSetMembers = false; // drop back and just configure using
    // // what we've been given
    // } else {
    // if (log != null) {
    // StringBuilder builder = new StringBuilder();
    // for (ServerAddress s : repSet) {
    // builder.append(s.toString()).append(" ");
    // }
    // log.logBasic(BaseMessages.getString(PKG,
    // "MongoUtils.Message.UsingTheFollowingReplicaSetMembers")
    // + " "
    // + builder.toString());
    // }
    // }
    // }

    // if (!useAllReplicaSetMembers) {
    String[] parts = hostsPorts.trim().split(","); //$NON-NLS-1$
    for (String part : parts) {
      // host:port?
      int port = singlePortI != -1 ? singlePortI : MONGO_DEFAULT_PORT;
      String[] hp = part.split(":"); //$NON-NLS-1$
      if (hp.length > 2) {
        throw new KettleException(BaseMessages.getString(PKG,
            "MongoUtils.Message.Error.MalformedHost", part)); //$NON-NLS-1$
      }

      String host = hp[0];
      if (hp.length == 2) {
        // non-default port
        try {
          port = Integer.parseInt(hp[1].trim());
        } catch (NumberFormatException n) {
          throw new KettleException(BaseMessages.getString(PKG,
              "MongoUtils.Message.Error.UnableToParsePortNumber", hp[1])); //$NON-NLS-1$
        }
      }

      try {
        ServerAddress s = new ServerAddress(host, port);
        repSet.add(s);
      } catch (UnknownHostException u) {
        throw new KettleException(u);
      }
    }
    // }

    MongoClientOptions.Builder mongoOptsBuilder = new MongoClientOptions.Builder();

    configureConnectionOptions(mongoOptsBuilder, connTimeout, socketTimeout,
        readPreference, writeConcern, wTimeout, journaled, tagSet, vars, log);

    MongoClientOptions opts = mongoOptsBuilder.build();
    try {
      // Mongo's java driver will discover all replica set or shard
      // members (Mongos) automatically when MongoClient is constructed
      // using a list of ServerAddresses. The javadocs state that MongoClient
      // should be constructed using a SingleServer address instance (rather
      // than a list) when connecting to a stand-alone host - this is why
      // we differentiate here between a list containing one ServerAddress
      // and a single ServerAddress instance via the useAllReplicaSetMembers
      // flag.

      if (cred == null) {
        return (repSet.size() > 1
            || (useAllReplicaSetMembers && repSet.size() >= 1) ? new MongoClient(
            repSet, opts) : (repSet.size() == 1 ? new MongoClient(
            repSet.get(0), opts) : new MongoClient(new ServerAddress(
            "localhost"), opts))); //$NON-NLS-1$
      }

      List<MongoCredential> credList = new ArrayList<MongoCredential>();
      credList.add(cred);
      return (repSet.size() > 1
          || (useAllReplicaSetMembers && repSet.size() >= 1) ? new MongoClient(
          repSet, credList, opts) : (repSet.size() == 1 ? new MongoClient(
          repSet.get(0), credList, opts) : new MongoClient(new ServerAddress(
          "localhost"), credList, opts))); //$NON-NLS-1$
    } catch (UnknownHostException u) {
      throw new KettleException(u);
    }
  }

  /**
   * Create a connection to a Mongo server based on parameters supplied in the
   * step meta data
   *
   * @param meta the step meta data
   * @param vars variables to use
   * @param log for logging
   * @return a configured MongoClient object
   * @throws KettleException if a problem occurs
   */
  public static MongoClient initConnection(MongoDbOutputMeta meta,
      VariableSpace vars, MongoCredential cred, LogChannelInterface log)
      throws KettleException {

    String hostsPorts = meta.getHostnames();
    String singlePort = meta.getPort();
    String username = meta.getUsername();
    String password = meta.getPassword();
    String connTimeout = meta.getConnectTimeout();
    String sockTimeout = meta.getSocketTimeout();
    String readPreference = meta.getReadPreference();
    String writeConcern = meta.getWriteConcern();
    String wTimeout = meta.getWTimeout();
    boolean journaled = meta.getJournal();
    // no read preference tag sets in the output step
    List<String> tagSet = null;

    boolean useAllReplicaSetMembers = meta.getUseAllReplicaSetMembers();

    return initConnection(hostsPorts, singlePort, cred,
        useAllReplicaSetMembers, connTimeout, sockTimeout, readPreference,
        writeConcern, wTimeout, journaled, tagSet, vars, log);
  }

  /**
   * Create a connection to a Mongo server based on parameters supplied in the
   * step meta data
   *
   * @param meta the step meta data
   * @param vars variables to use
   * @param cred a configured MongoCredential for authentication (or null for no
   *          authentication)
   * @param log for logging
   * @return a configured MongoClient object
   * @throws KettleException if a problem occurs
   */
  public static MongoClient initConnection(MongoDbInputMeta meta,
      VariableSpace vars, MongoCredential cred, LogChannelInterface log)
      throws KettleException {
    String hostsPorts = meta.getHostnames();
    String singlePort = meta.getPort();
    String username = meta.getAuthenticationUser();
    String password = meta.getAuthenticationPassword();
    String connTimeout = meta.getConnectTimeout();
    String sockTimeout = meta.getSocketTimeout();
    String readPreference = meta.getReadPreference();
    String writeConcern = null;
    String wTimeout = null;
    boolean journaled = false;
    List<String> tagSet = meta.getReadPrefTagSets();
    boolean useAllReplicaSetMembers = meta.getUseAllReplicaSetMembers();

    return initConnection(hostsPorts, singlePort, cred,
        useAllReplicaSetMembers, connTimeout, sockTimeout, readPreference,
        writeConcern, wTimeout, journaled, tagSet, vars, log);
  }

  /**
   * Return a list of custom "lastErrorModes" (if any) defined in the replica
   * set configuration object on the server. These can be used as the "w"
   * setting for the write concern in addition to the standard "w" values of
   * <number> or "majority".
   *
   * @param hostsPorts the hosts to use
   * @param singlePort the default port to use if no ports are given in the
   *          hostsPorts spec
   * @param username the username for authentication
   * @param password the password for authentication
   * @param vars the environment variables to use
   * @param log for logging
   * @return a list of the names of any custom "lastErrorModes"
   * @throws KettleException if a problem occurs
   */
  public static List<String> getLastErrorModes(String hostsPorts,
      String singlePort, MongoCredential cred, VariableSpace vars,
      LogChannelInterface log) throws KettleException {

    List<String> customLastErrorModes = new ArrayList<String>();

    MongoClient mongo = null;
    try {
      if (cred != null
          && cred.getMechanism().equals(MongoCredential.MONGODB_CR_MECHANISM)) {
        // need to make a new credential that specifies the local database
        cred = MongoCredential.createMongoCRCredential(cred.getUserName(),
            LOCAL_DB, cred.getPassword());
      }
      mongo = initConnection(hostsPorts, singlePort, cred, false, null, null,
          null, null, null, false, null, vars, log);

      DB local = mongo.getDB(LOCAL_DB);
      if (local != null) {

        DBCollection replset = local.getCollection(REPL_SET_COLLECTION);
        if (replset != null) {
          DBObject config = replset.findOne();

          extractLastErrorModes(config, customLastErrorModes);
        }
      }
    } finally {
      if (mongo != null) {
        mongo.close();
      }
    }

    return customLastErrorModes;
  }

  protected static void extractLastErrorModes(DBObject config,
      List<String> customLastErrorModes) {
    if (config != null) {
      Object settings = config.get(REPL_SET_SETTINGS);

      if (settings != null) {
        Object getLastErrModes = ((DBObject) settings)
            .get(REPL_SET_LAST_ERROR_MODES);

        if (getLastErrModes != null) {
          for (String m : ((DBObject) getLastErrModes).keySet()) {
            customLastErrorModes.add(m);
          }
        }
      }
    }
  }

  /**
   * Connect to mongo and retrieve any custom getLastError modes defined in the
   * local.system.replset collection
   *
   * @param meta the MongoDbOutputMeta containing settings to use
   * @param vars environment variables
   * @param log for logging
   * @return a list containing any custom getLastError modes
   * @throws KettleException if a connection or authentication error occurs
   */
  public static List<String> getLastErrorModes(MongoDbOutputMeta meta,
      VariableSpace vars, MongoCredential cred, LogChannelInterface log)
      throws KettleException {

    return getLastErrorModes(meta.getHostnames(), meta.getPort(), cred, vars,
        log);
  }

  protected static String quote(String string) {
    if (string.indexOf('"') >= 0) {

      if (string.indexOf('"') >= 0) {
        string = string.replace("\"", "\\\""); //$NON-NLS-1$ //$NON-NLS-2$
      }
    }

    string = ("\"" + string + "\""); //$NON-NLS-1$ //$NON-NLS-2$

    return string;
  }

  /**
   * Get a list of all tagName : tagValue pairs that occur in the tag sets
   * defined across the replica set.
   *
   * @param meta the MongoDbInput containing settings to use
   * @param vars environment variables to use
   * @param log for logging
   * @return a list of tags that occur in the replica set configuration
   * @throws KettleException if a problem occurs
   */
  public static List<String> getAllTags(MongoDbInputMeta meta,
      VariableSpace vars, MongoCredential cred, LogChannelInterface log)
      throws KettleException {
    return getAllTags(meta.getHostnames(), meta.getPort(), cred, vars, log);
  }

  /**
   * Get a list of all tagName : tagValue pairs that occur in the tag sets
   * defined across the replica set.
   *
   * @param hostsPorts the hosts to use
   * @param singlePort the default port to use if no ports specified in
   *          hostsPorts spec
   * @param username the username to authenticate with
   * @param password the password to authenticate with
   * @param vars environment variables to use
   * @param log for logging
   * @return a list of tags that occur in the replica set configuration
   * @throws KettleException if an error occurs
   */
  public static List<String> getAllTags(String hostsPorts, String singlePort,
      MongoCredential cred, VariableSpace vars, LogChannelInterface log)
      throws KettleException {

    List<String> allTags = new ArrayList<String>();

    BasicDBList members = getRepSetMemberRecords(hostsPorts, singlePort, cred,
        vars, log);

    setupAllTags(members, allTags);

    return allTags;
  }

  protected static void setupAllTags(BasicDBList members, List<String> allTags) {
    HashSet<String> tempTags = new HashSet<String>();

    if (members != null && members.size() > 0) {
      for (int i = 0; i < members.size(); i++) {
        Object m = members.get(i);

        if (m != null) {
          DBObject tags = (DBObject) ((DBObject) m).get("tags"); //$NON-NLS-1$
          if (tags == null) {
            continue;
          }

          for (String tagName : tags.keySet()) {
            String tagVal = tags.get(tagName).toString();
            String combined = quote(tagName) + " : " + quote(tagVal); //$NON-NLS-1$
            tempTags.add(combined);
          }
        }
      }
    }

    for (String s : tempTags) {
      allTags.add(s);
    }
  }

  /**
   * Return a list of replica set members whos tags satisfy the supplied list of
   * tag set. It is assumed that members satisfy according to an OR relationship
   * = i.e. a member satisfies if it satisfies at least one of the tag sets in
   * the supplied list.
   *
   * @param tagSets the list of tag sets to match against
   * @param meta MongoDbInput meta
   * @param vars environment variables to use
   * @param log for logging
   * @return a list of replica set members who's tags satisfy the supplied list
   *         of tag sets
   * @throws KettleException if a problem occurs
   */
  public static List<DBObject> getReplicaSetMembersThatSatisfyTagSets(
      List<DBObject> tagSets, MongoDbInputMeta meta, VariableSpace vars,
      MongoCredential cred, LogChannelInterface log) throws KettleException {
    return getReplicaSetMembersThatSatisfyTagSets(tagSets, meta.getHostnames(),
        meta.getPort(), cred, vars, log);
  }

  /**
   * Return a list of replica set members whos tags satisfy the supplied list of
   * tag set. It is assumed that members satisfy according to an OR relationship
   * = i.e. a member satisfies if it satisfies at least one of the tag sets in
   * the supplied list.
   *
   * @param tagSets the list of tag sets to match against
   * @param hostsPorts the hosts to use
   * @param singlePort the default port to use, if no ports are given in the
   *          hostsPorts spec
   * @param username the username for authentication
   * @param password the password for authentication
   * @param vars environment variables to use
   * @param log for logging
   * @return a list of replica set members who's tags satisfy the supplied list
   *         of tag sets
   * @throws KettleException if a problem occurs
   */
  public static List<DBObject> getReplicaSetMembersThatSatisfyTagSets(
      List<DBObject> tagSets, String hostsPorts, String singlePort,
      MongoCredential cred, VariableSpace vars, LogChannelInterface log)
      throws KettleException {

    List<DBObject> satisfy = new ArrayList<DBObject>();

    BasicDBList members = getRepSetMemberRecords(hostsPorts, singlePort, cred,
        vars, log);

    checkForReplicaSetMembersThatSatisfyTagSets(tagSets, satisfy, members);

    return satisfy;
  }

  protected static void checkForReplicaSetMembersThatSatisfyTagSets(
      List<DBObject> tagSets, List<DBObject> satisfy, BasicDBList members) {
    if (members != null && members.size() > 0) {
      for (int i = 0; i < members.size(); i++) {
        Object m = members.get(i);

        if (m != null) {
          DBObject tags = (DBObject) ((DBObject) m).get("tags"); //$NON-NLS-1$
          if (tags == null) {
            continue;
          }

          for (int j = 0; j < tagSets.size(); j++) {
            boolean match = true;
            DBObject toMatch = tagSets.get(j);

            for (String tagName : toMatch.keySet()) {
              String tagValue = toMatch.get(tagName).toString();

              // does replica set member m's tags contain this tag?
              Object matchVal = tags.get(tagName);

              if (matchVal == null) {
                match = false; // doesn't match this particular tag set
                // no need to check any other keys in toMatch
                break;
              }

              if (!matchVal.toString().equals(tagValue)) {
                // rep set member m's tags has this tag, but it's value does not
                // match
                match = false;

                // no need to check any other keys in toMatch
                break;
              }
            }

            if (match) {
              // all tag/values present and match - add this member (only if its
              // not already there)
              if (!satisfy.contains(m)) {
                satisfy.add((DBObject) m);
              }
            }
          }
        }
      }
    }
  }

  protected static BasicDBList getRepSetMemberRecords(String hostsPorts,
      String singlePort, MongoCredential cred, VariableSpace vars,
      LogChannelInterface log) throws KettleException {

    MongoClient mongo = null;
    BasicDBList setMembers = null;
    try {
      if (cred != null
          && cred.getMechanism().equals(MongoCredential.MONGODB_CR_MECHANISM)) {
        // need to make a new credential that specifies the local database
        cred = MongoCredential.createMongoCRCredential(cred.getUserName(),
            LOCAL_DB, cred.getPassword());
      }
      mongo = initConnection(hostsPorts, singlePort, cred, false, null, null,
          null, null, null, false, null, vars, log);

      DB local = mongo.getDB(LOCAL_DB);
      if (local != null) {

        DBCollection replset = local.getCollection(REPL_SET_COLLECTION);
        if (replset != null) {
          DBObject config = replset.findOne();

          if (config != null) {
            Object members = config.get(REPL_SET_MEMBERS);

            if (members instanceof BasicDBList) {
              if (((BasicDBList) members).size() == 0) {
                // log that there are no replica set members defined
                if (log != null) {
                  log.logBasic(BaseMessages.getString(PKG,
                      "MongoUtils.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$
                }
              } else {
                setMembers = (BasicDBList) members;
              }

            } else {
              // log that there are no replica set members defined
              if (log != null) {
                log.logBasic(BaseMessages.getString(PKG,
                    "MongoUtils.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$
              }
            }
          } else {
            // log that there are no replica set members defined
            if (log != null) {
              log.logBasic(BaseMessages.getString(PKG,
                  "MongoUtils.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$
            }
          }
        } else {
          // log that the replica set collection is not available
          if (log != null) {
            log.logBasic(BaseMessages.getString(PKG,
                "MongoUtils.Message.Warning.ReplicaSetCollectionUnavailable")); //$NON-NLS-1$
          }
        }
      } else {
        // log that the local database is not available!!
        if (log != null) {
          log.logBasic(BaseMessages.getString(PKG,
              "MongoUtils.Message.Warning.LocalDBNotAvailable")); //$NON-NLS-1$
        }
      }
    } catch (Exception ex) {
      throw new KettleException(ex);
    } finally {
      if (mongo != null) {
        mongo.close();
      }
    }

    return setMembers;
  }

  /**
   * Connect to mongo and retrieve any replica set members defined in the
   * local.system.replset collection. Note that this method is not actually
   * needed for configuring a connection to a replica set or sharded mongo
   * cluster (mongos) as the driver will determine this automatically.
   *
   * @param hostsPorts the host(s) and port(s) to use for initiating the
   *          connection
   * @param singlePort default port to use if none specified in the hostsPorts
   *          string
   * @param username username to use for authenticating
   * @param password password to use for authenticating
   * @param vars environment variables
   * @param log for logging
   * @return a list of replica set ServerAddresses
   * @throws KettleException if a problem occurs
   */
  public static List<ServerAddress> getReplicaSetMembers(String hostsPorts,
      String singlePort, MongoCredential cred, VariableSpace vars,
      LogChannelInterface log) throws KettleException {
    List<ServerAddress> replSetMembers = new ArrayList<ServerAddress>();

    if (log != null) {
      log.logBasic(BaseMessages.getString(PKG,
          "MongoUtils.Message.QueryingForReplicaSetMembers", hostsPorts));
    }
    BasicDBList members = getRepSetMemberRecords(hostsPorts, singlePort, cred,
        vars, log);

    try {
      if (members != null && members.size() > 0) {
        for (int i = 0; i < members.size(); i++) {
          Object m = members.get(i);

          if (m != null) {
            String hostPort = ((DBObject) m).get("host").toString(); //$NON-NLS-1$
            if (!Const.isEmpty(hostPort)) {
              String[] parts = hostPort.split(":"); //$NON-NLS-1$
              if (parts.length == 2) {
                ServerAddress address = new ServerAddress(parts[0].trim(),
                    Integer.parseInt(parts[1].trim()));
                replSetMembers.add(address);
              } else {
                ServerAddress address = new ServerAddress(parts[0].trim());
                replSetMembers.add(address);
              }
            }
          }
        }
      }
    } catch (Exception ex) {
      throw new KettleException(ex);
    }

    return replSetMembers;
  }

  /**
   * Creates an authenticated context for the MongoDb Input step.
   *
   * @param meta
   * @param varSpace
   * @return
   * @throws KettleException Error logging in as the provided user.
   */
  public static AuthContext createAuthContext(MongoDbInputMeta meta, VariableSpace varSpace) throws KettleException {
    return createAuthContext(varSpace, meta.getUseKerberosAuthentication(), varSpace.environmentSubstitute(meta.getAuthenticationUser()));
  }

  /**
   * Creates an authenticated context for the MongoDb Output step.
   *
   * @param meta
   * @param varSpace
   * @return
   * @throws KettleException Error logging in as the provided user.
   */
  public static AuthContext createAuthContext(MongoDbOutputMeta meta, VariableSpace varSpace)  throws KettleException {
    return createAuthContext(varSpace, meta.getUseKerberosAuthentication(), varSpace.environmentSubstitute(meta.getUsername()));
  }

  private static AuthContext createAuthContext(VariableSpace varSpace, boolean useKerberosAuth, String principal) throws KettleException {
    LoginContext context = null;
    if (useKerberosAuth) {
      context = KettleKerberosHelper.login(varSpace, principal);
    }
    return new AuthContext(context);
  }

  /**
   * Retrieve all database names found in MongoDB as visible by the
   * authenticated user.
   *
   * @param meta
   *          Input meta with connection information
   * @param varSpace
   *          Variable space to substitute variables with
   * @return A list of database names found in MongoDB
   * @throws KettleException
   */
  public static List<String> getDatabaseNames(final MongoDbInputMeta meta, final VariableSpace varSpace) throws KettleException {
    try {
      AuthContext context = MongoUtils.createAuthContext(meta, varSpace);
      return context.doAs(new PrivilegedExceptionAction<List<String>>() {

        @Override
        public List<String> run() throws Exception {
          MongoClient conn = null;
          try {
            conn = MongoDbInputData.initConnection(meta, varSpace, null);
            return conn.getDatabaseNames();
          } finally {
            if (conn != null) {
              conn.close();
            }
          }
        }
      });
    } catch (PrivilegedActionException ex) {
      if (ex.getCause() instanceof KettleException) {
        throw (KettleException) ex.getCause();
      } else {
        throw new KettleException("Unable to retrieve database names from MongoDB", ex.getCause());
      }
    }
  }

  /**
   * Get the set of collections for a MongoDB database.
   *
   * @param meta
   *          Input meta with connection information
   * @param varSpace
   *          Variable space to substitute variables with
   * @param dB
   *          Name of database
   * @param username
   *          Username to request collections on behalf of
   * @param realPass
   *          Password of user
   * @return Set of collections in the database requested.
   * @throws KettleException
   *           If an error occurs.
   */
  public static Set<String> getCollectionsNames(final MongoDbInputMeta meta, final TransMeta varSpace, final String dB,
      final String username, final String realPass) throws KettleException {
    try {
      AuthContext context = MongoUtils.createAuthContext(meta, varSpace);
      return context.doAs(new PrivilegedExceptionAction<Set<String>>() {
        @Override
        public Set<String> run() throws Exception {
          MongoClient conn = null;
          try {
            conn = MongoDbInputData.initConnection(meta, varSpace, null);
            DB theDB = conn.getDB(dB);

            if (!Const.isEmpty(username) || !Const.isEmpty(realPass)) {
              CommandResult comResult = theDB.authenticateCommand(username, realPass.toCharArray());
              if (!comResult.ok()) {
                throw new Exception(BaseMessages.getString(PKG, "MongoDbInput.ErrorAuthenticating.Exception", //$NON-NLS-1$
                    comResult.getErrorMessage()));
              }
            }

            return theDB.getCollectionNames();
          } finally {
            if (conn != null) {
              conn.close();
            }
          }
        }
      });
    } catch (PrivilegedActionException ex) {
      if (ex.getCause() instanceof KettleException) {
        throw (KettleException) ex.getCause();
      } else {
        throw new KettleException("Unable to retrieve collection names for database " + dB + " from MongoDB", ex.getCause());
      }
    }
  }

  public static void main(String[] args) {
    try {
      String hostPort = args[0];
      String defaultPort = args[1];
      Variables vars = new Variables();

      List<String> repSetTags = MongoUtils.getAllTags(hostPort, defaultPort,
          null, vars, null);

      System.out.println("Number of tags: " + repSetTags.size()); //$NON-NLS-1$
      for (String tag : repSetTags) {
        System.out.println(tag);
      }

      List<ServerAddress> repSetMembers = MongoUtils.getReplicaSetMembers(
          hostPort, defaultPort, null, vars, null);
      System.out.println("Number of replica set members: "
          + repSetMembers.size());
      for (ServerAddress s : repSetMembers) {
        System.out.println(s.toString());
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

}