text:
package org.springframework.context.support;

import java.io.IOException;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

/**
 * Convenient abstract superclass for ApplicationContext implementations,
 * drawing configuration from XML documents containing bean definitions
 * understood by an XmlBeanDefinitionParser.
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see org.springframework.beans.factory.xml.XmlBeanDefinitionParser
 */
public abstract class AbstractXmlApplicationContext extends AbstractApplicationContext  {

	/** Bean factory for this context */
	private ConfigurableListableBeanFactory beanFactory;

	/**
	 * Create a new AbstractXmlApplicationContext with no parent.
	 */
	public AbstractXmlApplicationContext() {
	}

	/**
	 * Create a new AbstractXmlApplicationContext with the given parent context.
	 * @param parent the parent context
	 */
	public AbstractXmlApplicationContext(ApplicationContext parent) {
		super(parent);
	}

	/**
	 * 刷新bean工厂,用来执行真正的加载配置
	 * @throws BeansException
	 */
	protected final void refreshBeanFactory() throws BeansException {
		try {
			//创建BeanFactory
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			//实例化一个XmlBeanDefinitionReader,用来从xml中读取、解析、注册BeanDefinition
			XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
			beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
			//初始化BeanDefinitionReader,默认实现为空
			initBeanDefinitionReader(beanDefinitionReader);
			//使用给定的XmlBeanDefinitionReader来加载BeanDefinition
			loadBeanDefinitions(beanDefinitionReader);
			this.beanFactory = beanFactory;
			if (logger.isInfoEnabled()) {
				logger.info("Bean factory for application context [" + getDisplayName() + "]: " + beanFactory);
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException(
					"I/O error parsing XML document for application context [" + getDisplayName() + "]", ex);
		}
	}

	public final ConfigurableListableBeanFactory getBeanFactory() {
		return beanFactory;
	}

	/**
	 * Create the bean factory for this context.
	 *
Default implementation creates a DefaultListableBeanFactory with the
	 * internal bean factory of this context's parent as parent bean factory.
	 *
Can be overridden in subclasses.
	 * @return the bean factory for this context
	 * @see org.springframework.beans.factory.support.DefaultListableBeanFactory
	 * @see #getInternalParentBeanFactory
	 */
	protected DefaultListableBeanFactory createBeanFactory() {
		return new DefaultListableBeanFactory(getInternalParentBeanFactory());
	}

	/**
	 * Initialize the bean definition reader used for loading the bean
	 * definitions of this context. Default implementation is empty.
	 *
Can be overridden in subclasses, e.g. for turning off XML validation
	 * or using a different XmlBeanDefinitionParser implementation.
	 * @param beanDefinitionReader the bean definition reader used by this context
	 * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader#setValidating
	 * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader#setParserClass
	 */
	protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {
	}

	/**
	 * Load the bean definitions with the given XmlBeanDefinitionReader.
	 *
The lifecycle of the bean factory is handled by the refreshBeanFactory method;
	 * therefore this method is just supposed to load and/or register bean definitions.
	 *
Delegates to a ResourcePatternResolver for resolving location patterns
	 * into Resource instances.
	 * @throws BeansException in case of bean registration errors
	 * @throws IOException if the required XML document isn't found
	 * @see #refreshBeanFactory
	 * @see #getConfigLocations
	 * @see #getResourcePatternResolver
	 * 加载BeanDefinition
	 */
	protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
		//获取配置文件路径,子类来实现
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
			ResourcePatternResolver resourcePatternResolver = getResourcePatternResolver();
			for (int i = 0; i < configLocations.length; i++) {
				//获取Resource
				Resource[] configResources = resourcePatternResolver.getResources(configLocations[i]);
				for (int j = 0; j < configResources.length; j++) {
					//使用XmlBeanDefinitionReader来解析配置文件
					reader.loadBeanDefinitions(configResources[j]);
				}
			}
		}
	}

	/**
	 * Return the ResourcePatternResolver to use for resolving location patterns
	 * into Resource instances. Default is PathMatchingResourcePatternResolver,
	 * supporting Ant-style location patterns.
	 * @see org.springframework.core.io.support.PathMatchingResourcePatternResolver
	 */
	protected ResourcePatternResolver getResourcePatternResolver() {
		return new PathMatchingResourcePatternResolver(this);
	}

	/**
	 * Return an array of resource locations, referring to the XML bean
	 * definition files that this context should be built with.
	 * @return an array of resource locations, or null if none
	 */
	protected abstract String[] getConfigLocations();

}


text:
package com.kubukoz.scala99

import scala.annotation.tailrec

/**
  * P02 (*) Find the last but one element of a list.
  * Example:
  * scala> penultimate(List(1, 1, 2, 3, 5, 8))
  * res0: Option[Int] = Some(5)
  **/
object P02 {
  /**
    * Implemented with pattern matching.
    * Pretty straightforward, similar to [[P01.last]].
    **/
  @tailrec
  def penultimate[T](list: List[T]): Option[T] = list match {
    case h :: t :: Nil => Some(h)
    case _ :: t => penultimate(t)
    case Nil => None
  }
}

redpajama_set_name: RedPajamaGithub


text:
using SimpleTwitchBot.Lib.Models;
using System;

namespace SimpleTwitchBot.Lib.Events
{
    public class ChannelHostingStartedEventArgs : EventArgs
    {
        public TwitchChannelHost ChannelHost { get; }

        public ChannelHostingStartedEventArgs(TwitchChannelHost channelHost)
        {
            ChannelHost = channelHost;
        }
    }
}


text:
package ch.chuv.lren.woken.config

import akka.http.scaladsl.model.Uri
import cats.data.NonEmptyList
import com.typesafe.config.Config
import ch.chuv.lren.woken.cromwell.core.ConfigUtil._
import ch.chuv.lren.woken.messages.datasets.{ AnonymisationLevel, Dataset, DatasetId, TableId }
import ch.chuv.lren.woken.messages.remoting.{ BasicAuthentication, RemoteLocation }
import cats.data.Validated._
import cats.implicits._

object DatasetsConfiguration {

  // Seems useful as Scala enumeration and Cats mapN don't appear to work together well
  private[this] def createDataset(dataset: String,
                                  label: String,
                                  description: String,
                                  tables: List[TableId],
                                  anonymisationLevel: String,
                                  location: Option[RemoteLocation]): Dataset = Dataset(
    DatasetId(dataset),
    label,
    description,
    tables,
    AnonymisationLevel.withName(anonymisationLevel),
    location
  )

  def read(config: Config, path: List[String], database: DatabaseId): Validation[Dataset] = {

    val datasetConfig = config.validateConfig(path.mkString("."))

    datasetConfig.andThen { f =>
      val dataset: Validation[String] =
        path.lastOption.map(_.validNel[String]).getOrElse("Empty path".invalidNel[String])
      val label       = f.validateString("label")
      val description = f.validateString("description")
      val tables: Validation[List[TableId]] = f
        .validateStringList("tables")
        .map(l => l.map(t => TableId(database.code, t)))
      val location: Validation[Option[RemoteLocation]] = f
        .validateConfig("location")
        .andThen { cl =>
          val url: Validation[Uri] = cl.validateString("url").map(Uri.apply)
          val credentials: Validation[Option[BasicAuthentication]] = cl
            .validateConfig("basicAuth")
            .andThen { cc =>
              val user     = cc.validateString("user")
              val password = cc.validateString("password")

              (user, password) mapN BasicAuthentication
            }
            .map(_.some)
            .orElse(Option.empty[BasicAuthentication].validNel[String])

          (url, credentials) mapN RemoteLocation
        }
        .map(_.some)
        .orElse(Option.empty[RemoteLocation].validNel[String])
      val anonymisationLevel: Validation[String] = f
        .validateString("anonymisationLevel")
        .ensure(
          throw new IllegalArgumentException(
            "anonymisationLevel: valid values are " + AnonymisationLevel.values.mkString(",")
          )
        ) { s =>
          AnonymisationLevel.withName(s); true
        }

      (dataset, label, description, tables, anonymisationLevel, location) mapN createDataset
    }

  }

  def factory(config: Config, defaultDatabase: DatabaseId): DatasetId => Validation[Dataset] =
    dataset => read(config, List("datasets", dataset.code), defaultDatabase)

  def datasetNames(config: Config): Validation[Set[DatasetId]] =
    config.validateConfig("datasets").map(_.keys.map(DatasetId))

  def datasets(config: Config, defaultDatabase: DatabaseId): Validation[Map[DatasetId, Dataset]] = {
    val datasetFactory = factory(config, defaultDatabase)
    datasetNames(config)
      .andThen { names: Set[DatasetId] =>
        val m: List[Validation[(DatasetId, Dataset)]] =
          names.toList
            .map { datasetId =>
              val datasetIdV: Validation[DatasetId] = datasetId.validNel[String]
              datasetIdV -> datasetFactory(datasetId)
            }
            .map(_.tupled)
        val t: Validation[List[(DatasetId, Dataset)]] = m.sequence[Validation, (DatasetId, Dataset)]
        t.map(_.toMap)
      }
      .ensure(NonEmptyList("No datasets are configured", Nil))(_.nonEmpty)
  }

}


text:
package org.apache.ibatis.mapping;

import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * @author Clinton Begin
 * 一个对象中的属性的映射 这个属性可能是简单的类型比如 int(数值型) boolean String 等也可能是自定义的对象类型
 * 简单的类型 比如一个 int 属性对应着结果集中的一个列字段
 * 复杂的自定义类型 比如一个 clerkAddress 对应着一个嵌套结果集的 id <association/> <collection/> <case/>
 */
public class ResultMapping {

  private Configuration configuration;
  private String property;
  private String column;
  private Class<?> javaType;
  private JdbcType jdbcType;
  private TypeHandler<?> typeHandler;
  // 嵌套结果集 id ,如果有 resultMap 属性的话,则是 resultMap 属性的值,否则则可能是是在 association 或 collection 或 case 对应的结果集的 id
  private String nestedResultMapId;
  // 嵌套查询 id ,一般是在 association 或 collection 或 <constructor><arg select=""></arg></constructor> 对应的 select 的 id
  private String nestedQueryId;
  private Set<String> notNullColumns;
  private String columnPrefix;
  // 在 Mapper 的 @Arg 中如果是主键的话 List<ResultFlag> 中有两种值 ID 和 CONSTRUCTOR,如果是非主键的话则只有 CONSTRUCTOR
  private List<ResultFlag> flags;
  // 只有<association> 和 <collection> <onstruct><arg column></arg></construct> 中才可能会用到 组合列 column ,并且 组合列 column 总是和 select 属性一起出现的,它出现的目的就是为 select 语句中传参数
  // 不知道还有没在其他情况下也出现 column 的情况,但 column 一定是和 select 一起出现的,一般是在构造一个对象的过程中,会引用到另外一个对象,这个被引用的对象需要再次从数据库中查询出来,
  // 所以 column 和 select 一般是成对儿出现的
  // 可以参考:http://mybatis-user.963551.n3.nabble.com/resultsMap-association-as-component-of-compound-key-td4013936.html
  // 组合列 column 和 select 是成对儿出现的,当他们出现的时候 <select id="selectClerkAddress" resultMap="clerkAddressResultMap"> 标签中是不需要参数的,
  // 因为参数实际上是由 column 传递过来的。
  private List<ResultMapping> composites;
  // todo 这是干啥的???? 只有在存储过程中才会出现 resultSet
  private String resultSet;
  private String foreignColumn; // 只有在存储过程中出现的时候才会用到 需要 foreignColumn 和 column 配合使用 column 代表的是 父对象的主键名称(如果没有主键的话则是查询语句中所有列的名称)foreginColumn 代表的是子对象中关联父对象的外键列名
  private boolean lazy;

  ResultMapping() {
  }

  public static class Builder {
    private ResultMapping resultMapping = new ResultMapping();

    public Builder(Configuration configuration, String property, String column, TypeHandler<?> typeHandler) {
      this(configuration, property);
      resultMapping.column = column;
      resultMapping.typeHandler = typeHandler;
    }

    public Builder(Configuration configuration, String property, String column, Class<?> javaType) {
      this(configuration, property);
      resultMapping.column = column;
      resultMapping.javaType = javaType;
    }

    public Builder(Configuration configuration, String property) {
      resultMapping.configuration = configuration;
      resultMapping.property = property;
      resultMapping.flags = new ArrayList<ResultFlag>();
      resultMapping.composites = new ArrayList<ResultMapping>();
      resultMapping.lazy = configuration.isLazyLoadingEnabled();
    }

    public Builder javaType(Class<?> javaType) {
      resultMapping.javaType = javaType;
      return this;
    }

    public Builder jdbcType(JdbcType jdbcType) {
      resultMapping.jdbcType = jdbcType;
      return this;
    }

    public Builder nestedResultMapId(String nestedResultMapId) {
      resultMapping.nestedResultMapId = nestedResultMapId;
      return this;
    }

    public Builder nestedQueryId(String nestedQueryId) {
      resultMapping.nestedQueryId = nestedQueryId;
      return this;
    }

    public Builder resultSet(String resultSet) {
      resultMapping.resultSet = resultSet;
      return this;
    }

    public Builder foreignColumn(String foreignColumn) {
      resultMapping.foreignColumn = foreignColumn;
      return this;
    }

    public Builder notNullColumns(Set<String> notNullColumns) {
      resultMapping.notNullColumns = notNullColumns;
      return this;
    }

    public Builder columnPrefix(String columnPrefix) {
      resultMapping.columnPrefix = columnPrefix;
      return this;
    }

    public Builder flags(List<ResultFlag> flags) {
      resultMapping.flags = flags;
      return this;
    }

    public Builder typeHandler(TypeHandler<?> typeHandler) {
      resultMapping.typeHandler = typeHandler;
      return this;
    }

    public Builder composites(List<ResultMapping> composites) {
      resultMapping.composites = composites;
      return this;
    }

    public Builder lazy(boolean lazy) {
      resultMapping.lazy = lazy;
      return this;
    }

    public ResultMapping build() {
      // lock down collections
      resultMapping.flags = Collections.unmodifiableList(resultMapping.flags);
      resultMapping.composites = Collections.unmodifiableList(resultMapping.composites);
      resolveTypeHandler(); // 怎样解析 typeHandler 如果 resultMapping 对应的是一个复杂的 collection or association
      validate();
      return resultMapping;
    }

    private void validate() {
      // Issue #697: cannot define both nestedQueryId and nestedResultMapId
      if (resultMapping.nestedQueryId != null && resultMapping.nestedResultMapId != null) {
        throw new IllegalStateException("Cannot define both nestedQueryId and nestedResultMapId in property " + resultMapping.property);
      }
      // Issue #5: there should be no mappings without typehandler
      if (resultMapping.nestedQueryId == null && resultMapping.nestedResultMapId == null && resultMapping.typeHandler == null) {
        throw new IllegalStateException("No typehandler found for property " + resultMapping.property);
      }
      // Issue #4 and GH #39: column is optional only in nested resultmaps but not in the rest
      if (resultMapping.nestedResultMapId == null && resultMapping.column == null && resultMapping.composites.isEmpty()) {
        throw new IllegalStateException("Mapping is missing column attribute for property " + resultMapping.property);
      }
      if (resultMapping.getResultSet() != null) {
        int numColums = 0;
        if (resultMapping.column != null) {
          numColums = resultMapping.column.split(",").length;
        }
        int numForeignColumns = 0;
        if (resultMapping.foreignColumn != null) {
          numForeignColumns = resultMapping.foreignColumn.split(",").length;
        }
        if (numColums != numForeignColumns) {
          throw new IllegalStateException("There should be the same number of columns and foreignColumns in property " + resultMapping.property);
        }
      }
    }

    private void resolveTypeHandler() {
      if (resultMapping.typeHandler == null && resultMapping.javaType != null) {
        Configuration configuration = resultMapping.configuration;
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        resultMapping.typeHandler = typeHandlerRegistry.getTypeHandler(resultMapping.javaType, resultMapping.jdbcType);
      }
    }

    public Builder column(String column) {
      resultMapping.column = column;
      return this;
    }
  }

  public String getProperty() {
    return property;
  }

  public String getColumn() {
    return column;
  }

  public Class<?> getJavaType() {
    return javaType;
  }

  public JdbcType getJdbcType() {
    return jdbcType;
  }

  public TypeHandler<?> getTypeHandler() {
    return typeHandler;
  }

  public String getNestedResultMapId() {
    return nestedResultMapId;
  }

  public String getNestedQueryId() {
    return nestedQueryId;
  }

  public Set<String> getNotNullColumns() {
    return notNullColumns;
  }

  public String getColumnPrefix() {
    return columnPrefix;
  }

  public List<ResultFlag> getFlags() {
    return flags;
  }

  public List<ResultMapping> getComposites() {
    return composites;
  }

  public boolean isCompositeResult() {
    return this.composites != null && !this.composites.isEmpty();
  }

  public String getResultSet() {
    return this.resultSet;
  }

  public String getForeignColumn() {
    return foreignColumn;
  }

  public void setForeignColumn(String foreignColumn) {
    this.foreignColumn = foreignColumn;
  }

  public boolean isLazy() {
    return lazy;
  }

  public void setLazy(boolean lazy) {
    this.lazy = lazy;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    ResultMapping that = (ResultMapping) o;

    if (property == null || !property.equals(that.property)) {
      return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    if (property != null) {
      return property.hashCode();
    } else if (column != null) {
      return column.hashCode();
    } else {
      return 0;
    }
  }

  @Override
  public String toString() {
    final StringBuilder sb = new StringBuilder("ResultMapping{");
    //sb.append("configuration=").append(configuration); // configuration doesn't have a useful .toString()
    sb.append("property='").append(property).append('\'');
    sb.append(", column='").append(column).append('\'');
    sb.append(", javaType=").append(javaType);
    sb.append(", jdbcType=").append(jdbcType);
    //sb.append(", typeHandler=").append(typeHandler); // typeHandler also doesn't have a useful .toString()
    sb.append(", nestedResultMapId='").append(nestedResultMapId).append('\'');
    sb.append(", nestedQueryId='").append(nestedQueryId).append('\'');
    sb.append(", notNullColumns=").append(notNullColumns);
    sb.append(", columnPrefix='").append(columnPrefix).append('\'');
    sb.append(", flags=").append(flags);
    sb.append(", composites=").append(composites);
    sb.append(", resultSet='").append(resultSet).append('\'');
    sb.append(", foreignColumn='").append(foreignColumn).append('\'');
    sb.append(", lazy=").append(lazy);
    sb.append('}');
    return sb.toString();
  }

}


text:
import _ from 'lodash';

import Type from './type';
import Parameter from './parameter';

import { resolve } from './type-registry';

import {
  defineStagingProperty,
  defineConstProperty
} from '../util/meta';

class CallableType extends Type {
  constructor(options) {
    super(options);
    defineStagingProperty(this, 'returnType', options.returnType, resolve);
    defineConstProperty(this, 'parameters', {});
    _.forEach(options.parameters, (p) => {
      defineConstProperty(this.parameters, p.name, new Parameter(p));
    });
  }
}

export default CallableType;


text:
package sql

import (
	"bytes"
	"fmt"
	"reflect"
	"strconv"

	"golang.org/x/net/context"

	"github.com/cockroachdb/cockroach/pkg/sql/parser"
	"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
	"github.com/cockroachdb/cockroach/pkg/util"
)

// planObserver is the interface to implement by components that need
// to visit a planNode tree.
// Used mainly by EXPLAIN, but also for the collector of back-references
// for view definitions.
type planObserver struct {
	// enterNode is invoked upon entering a tree node. It can return false to
	// stop the recursion at this node.
	enterNode func(ctx context.Context, nodeName string, plan planNode) bool

	// expr is invoked for each expression field in each node.
	expr func(nodeName, fieldName string, n int, expr parser.Expr)

	// attr is invoked for non-expression metadata in each node.
	attr func(nodeName, fieldName, attr string)

	// leaveNode is invoked upon leaving a tree node.
	leaveNode func(nodeName string)

	// subqueryNode is invoked for each sub-query node. It can return
	// an error to stop the recursion entirely.
	subqueryNode func(ctx context.Context, sq *subquery) error
}

// walkPlan performs a depth-first traversal of the plan given as
// argument, informing the planObserver of the node details at each
// level.
func walkPlan(ctx context.Context, plan planNode, observer planObserver) error {
	v := makePlanVisitor(ctx, observer)
	v.visit(plan)
	return v.err
}

// planVisitor is the support structure for walkPlan().
type planVisitor struct {
	observer planObserver
	ctx      context.Context

	// subplans is a temporary accumulator array used when collecting
	// sub-query plans at each planNode.
	subplans []planNode
	err      error
}

// makePlanVisitor creates a planVisitor instance.
// ctx will be stored in the planVisitor and used when visiting planNode's and
// expressions..
func makePlanVisitor(ctx context.Context, observer planObserver) planVisitor {
	return planVisitor{observer: observer, ctx: ctx}
}

// visit is the recursive function that supports walkPlan().
func (v *planVisitor) visit(plan planNode) {
	if v.err != nil {
		return
	}

	name := nodeName(plan)
	recurse := true
	if v.observer.enterNode != nil {
		recurse = v.observer.enterNode(v.ctx, name, plan)
	}
	if v.observer.leaveNode != nil {
		defer v.observer.leaveNode(name)
	}

	if !recurse {
		return
	}

	switch n := plan.(type) {
	case *valuesNode:
		if v.observer.attr != nil {
			suffix := "not yet populated"
			if n.rows != nil {
				suffix = fmt.Sprintf("%d row%s",
					n.rows.Len(), util.Pluralize(int64(n.rows.Len())))
			} else if n.tuples != nil {
				suffix = fmt.Sprintf("%d row%s",
					len(n.tuples), util.Pluralize(int64(len(n.tuples))))
			}
			description := fmt.Sprintf("%d column%s, %s",
				len(n.columns), util.Pluralize(int64(len(n.columns))), suffix)
			v.observer.attr(name, "size", description)
		}

		var subplans []planNode
		for i, tuple := range n.tuples {
			for j, expr := range tuple {
				if n.columns[j].Omitted {
					continue
				}
				var fieldName string
				if v.observer.attr != nil {
					fieldName = fmt.Sprintf("row %d, expr", i)
				}
				subplans = v.expr(name, fieldName, j, expr, subplans)
			}
		}
		v.subqueries(name, subplans)

	case *valueGenerator:
		subplans := v.expr(name, "expr", -1, n.expr, nil)
		v.subqueries(name, subplans)

	case *scanNode:
		if v.observer.attr != nil {
			v.observer.attr(name, "table", fmt.Sprintf("%s@%s", n.desc.Name, n.index.Name))
			if n.noIndexJoin {
				v.observer.attr(name, "hint", "no index join")
			}
			if n.specifiedIndex != nil {
				v.observer.attr(name, "hint", fmt.Sprintf("force index @%s", n.specifiedIndex.Name))
			}
			spans := sqlbase.PrettySpans(n.spans, 2)
			if spans != "" {
				if spans == "-" {
					spans = "ALL"
				}
				v.observer.attr(name, "spans", spans)
			}
			if n.hardLimit > 0 && isFilterTrue(n.filter) {
				v.observer.attr(name, "limit", fmt.Sprintf("%d", n.hardLimit))
			}
		}
		subplans := v.expr(name, "filter", -1, n.filter, nil)
		v.subqueries(name, subplans)

	case *filterNode:
		subplans := v.expr(name, "filter", -1, n.filter, nil)
		if n.explain != explainNone && v.observer.attr != nil {
			v.observer.attr(name, "mode", explainStrings[n.explain])
		}
		v.subqueries(name, subplans)
		v.visit(n.source.plan)

	case *renderNode:
		var subplans []planNode
		for i, r := range n.render {
			subplans = v.expr(name, "render", i, r, subplans)
		}
		v.subqueries(name, subplans)
		v.visit(n.source.plan)

	case *indexJoinNode:
		v.visit(n.index)
		v.visit(n.table)

	case *joinNode:
		if v.observer.attr != nil {
			jType := ""
			switch n.joinType {
			case joinTypeInner:
				jType = "inner"
				if len(n.pred.leftColNames) == 0 && n.pred.onCond == nil {
					jType = "cross"
				}
			case joinTypeLeftOuter:
				jType = "left outer"
			case joinTypeRightOuter:
				jType = "right outer"
			case joinTypeFullOuter:
				jType = "full outer"
			}
			v.observer.attr(name, "type", jType)

			if len(n.pred.leftColNames) > 0 {
				var buf bytes.Buffer
				buf.WriteByte('(')
				n.pred.leftColNames.Format(&buf, parser.FmtSimple)
				buf.WriteString(") = (")
				n.pred.rightColNames.Format(&buf, parser.FmtSimple)
				buf.WriteByte(')')
				v.observer.attr(name, "equality", buf.String())
			}
		}
		subplans := v.expr(name, "pred", -1, n.pred.onCond, nil)
		v.subqueries(name, subplans)
		v.visit(n.left.plan)
		v.visit(n.right.plan)

	case *limitNode:
		subplans := v.expr(name, "count", -1, n.countExpr, nil)
		subplans = v.expr(name, "offset", -1, n.offsetExpr, subplans)
		v.subqueries(name, subplans)
		v.visit(n.plan)

	case *distinctNode:
		if n.columnsInOrder != nil && v.observer.attr != nil {
			var buf bytes.Buffer
			prefix := ""
			columns := n.Columns()
			for i, key := range n.columnsInOrder {
				if key {
					buf.WriteString(prefix)
					buf.WriteString(columns[i].Name)
					prefix = ", "
				}
			}
			v.observer.attr(name, "key", buf.String())
		}
		v.visit(n.plan)

	case *sortNode:
		if v.observer.attr != nil {
			var columns sqlbase.ResultColumns
			if n.plan != nil {
				columns = n.plan.Columns()
			}
			// We use n.ordering and not plan.Ordering() because
			// plan.Ordering() does not include the added sort columns not
			// present in the output.
			order := orderingInfo{ordering: n.ordering}
			v.observer.attr(name, "order", order.AsString(columns))
			switch ss := n.sortStrategy.(type) {
			case *iterativeSortStrategy:
				v.observer.attr(name, "strategy", "iterative")
			case *sortTopKStrategy:
				v.observer.attr(name, "strategy", fmt.Sprintf("top %d", ss.topK))
			}
		}
		v.visit(n.plan)

	case *groupNode:
		var subplans []planNode
		for i, agg := range n.funcs {
			subplans = v.expr(name, "aggregate", i, agg.expr, subplans)
		}
		for i, rexpr := range n.render {
			subplans = v.expr(name, "render", i, rexpr, subplans)
		}
		subplans = v.expr(name, "having", -1, n.having, subplans)
		v.subqueries(name, subplans)
		v.visit(n.plan)

	case *windowNode:
		var subplans []planNode
		for i, agg := range n.funcs {
			subplans = v.expr(name, "window", i, agg.expr, subplans)
		}
		for i, rexpr := range n.windowRender {
			subplans = v.expr(name, "render", i, rexpr, subplans)
		}
		v.subqueries(name, subplans)
		v.visit(n.plan)

	case *unionNode:
		v.visit(n.left)
		v.visit(n.right)

	case *splitNode:
		v.visit(n.rows)

	case *relocateNode:
		v.visit(n.rows)

	case *insertNode:
		if v.observer.attr != nil {
			var buf bytes.Buffer
			buf.WriteString(n.tableDesc.Name)
			buf.WriteByte('(')
			for i, col := range n.insertCols {
				if i > 0 {
					buf.WriteString(", ")
				}
				buf.WriteString(col.Name)
			}
			buf.WriteByte(')')
			v.observer.attr(name, "into", buf.String())
		}

		var subplans []planNode
		for i, dexpr := range n.defaultExprs {
			subplans = v.expr(name, "default", i, dexpr, subplans)
		}
		for i, cexpr := range n.checkHelper.exprs {
			subplans = v.expr(name, "check", i, cexpr, subplans)
		}
		for i, rexpr := range n.rh.exprs {
			subplans = v.expr(name, "returning", i, rexpr, subplans)
		}
		n.tw.walkExprs(func(d string, i int, e parser.TypedExpr) {
			subplans = v.expr(name, d, i, e, subplans)
		})
		v.subqueries(name, subplans)
		v.visit(n.run.rows)

	case *updateNode:
		if v.observer.attr != nil {
			v.observer.attr(name, "table", n.tableDesc.Name)
			if len(n.tw.ru.UpdateCols) > 0 {
				var buf bytes.Buffer
				for i, col := range n.tw.ru.UpdateCols {
					if i > 0 {
						buf.WriteString(", ")
					}
					buf.WriteString(col.Name)
				}
				v.observer.attr(name, "set", buf.String())
			}
		}
		var subplans []planNode
		for i, rexpr := range n.rh.exprs {
			subplans = v.expr(name, "returning", i, rexpr, subplans)
		}
		n.tw.walkExprs(func(d string, i int, e parser.TypedExpr) {
			subplans = v.expr(name, d, i, e, subplans)
		})
		v.subqueries(name, subplans)
		v.visit(n.run.rows)

	case *deleteNode:
		if v.observer.attr != nil {
			v.observer.attr(name, "from", n.tableDesc.Name)
		}
		var subplans []planNode
		for i, rexpr := range n.rh.exprs {
			subplans = v.expr(name, "returning", i, rexpr, subplans)
		}
		n.tw.walkExprs(func(d string, i int, e parser.TypedExpr) {
			subplans = v.expr(name, d, i, e, subplans)
		})
		v.subqueries(name, subplans)
		v.visit(n.run.rows)

	case *createTableNode:
		if n.n.As() {
			v.visit(n.sourcePlan)
		}

	case *createViewNode:
		if v.observer.attr != nil {
			v.observer.attr(name, "query", n.sourceQuery)
		}
		v.visit(n.sourcePlan)

	case *delayedNode:
		if v.observer.attr != nil {
			v.observer.attr(name, "source", n.name)
		}
		if n.plan != nil {
			v.visit(n.plan)
		}

	case *explainDebugNode:
		v.visit(n.plan)

	case *explainDistSQLNode:
		v.visit(n.plan)

	case *ordinalityNode:
		v.visit(n.source)

	case *explainTraceNode:
		v.visit(n.plan)

	case *explainPlanNode:
		if v.observer.attr != nil {
			v.observer.attr(name, "expanded", strconv.FormatBool(n.expanded))
		}
		v.visit(n.plan)
	}
}

// subqueries informs the observer that the following sub-plans are
// for sub-queries.
func (v *planVisitor) subqueries(nodeName string, subplans []planNode) {
	if len(subplans) == 0 || v.err != nil {
		return
	}
	if v.observer.attr != nil {
		v.observer.attr(nodeName, "subqueries", strconv.Itoa(len(subplans)))
	}
	for _, p := range subplans {
		v.visit(p)
	}
}

// expr wraps observer.expr() and provides it with the current node's
// name. It also collects the plans for the sub-queries.
func (v *planVisitor) expr(
	nodeName string, fieldName string, n int, expr parser.Expr, subplans []planNode,
) []planNode {
	if v.err != nil {
		return subplans
	}

	if v.observer.expr != nil {
		v.observer.expr(nodeName, fieldName, n, expr)
	}

	if expr != nil {
		// Note: the recursion through WalkExprConst does nothing else
		// than calling observer.subqueryNode() and collect subplans in
		// v.subplans, in particular it does not recurse into the
		// collected subplans (this recursion is performed by visit() only
		// after all the subplans have been collected). Therefore, there
		// is no risk that v.subplans will be clobbered by a recursion
		// into visit().
		v.subplans = subplans
		parser.WalkExprConst(v, expr)
		subplans = v.subplans
		v.subplans = nil
	}
	return subplans
}

// planVisitor is also an Expr visitor whose task is to collect
// sub-query plans for the surrounding planNode.
var _ parser.Visitor = &planVisitor{}

func (v *planVisitor) VisitPre(expr parser.Expr) (bool, parser.Expr) {
	if v.err != nil {
		return false, expr
	}
	if sq, ok := expr.(*subquery); ok {
		if v.observer.subqueryNode != nil {
			if err := v.observer.subqueryNode(v.ctx, sq); err != nil {
				v.err = err
				return false, expr
			}
		}
		if sq.plan != nil {
			v.subplans = append(v.subplans, sq.plan)
		}
		return false, expr
	}
	return true, expr
}
func (v *planVisitor) VisitPost(expr parser.Expr) parser.Expr { return expr }

// nodeName returns the name of the given planNode as string.  The
// node's current state is taken into account, e.g. sortNode has
// either name "sort" or "nosort" depending on whether sorting is
// needed.
func nodeName(plan planNode) string {
	// Some nodes have custom names depending on attributes.
	switch n := plan.(type) {
	case *emptyNode:
		if n.results {
			return "nullrow"
		}
	case *sortNode:
		if !n.needSort {
			return "nosort"
		}
	case *scanNode:
		if n.reverse {
			return "revscan"
		}
	case *unionNode:
		if n.emitAll {
			return "append"
		}
	}

	name, ok := planNodeNames[reflect.TypeOf(plan)]
	if !ok {
		panic(fmt.Sprintf("name missing for type %T", plan))
	}

	return name
}

// planNodeNames is the mapping from node type to strings.  The
// strings are constant and not precomptued so that the type names can
// be changed without changing the output of "EXPLAIN".
var planNodeNames = map[reflect.Type]string{
	reflect.TypeOf(&alterTableNode{}):     "alter table",
	reflect.TypeOf(&copyNode{}):           "copy",
	reflect.TypeOf(&createDatabaseNode{}): "create database",
	reflect.TypeOf(&createIndexNode{}):    "create index",
	reflect.TypeOf(&createTableNode{}):    "create table",
	reflect.TypeOf(&createUserNode{}):     "create user",
	reflect.TypeOf(&createViewNode{}):     "create view",
	reflect.TypeOf(&delayedNode{}):        "virtual table",
	reflect.TypeOf(&deleteNode{}):         "delete",
	reflect.TypeOf(&distinctNode{}):       "distinct",
	reflect.TypeOf(&dropDatabaseNode{}):   "drop database",
	reflect.TypeOf(&dropIndexNode{}):      "drop index",
	reflect.TypeOf(&dropTableNode{}):      "drop table",
	reflect.TypeOf(&dropViewNode{}):       "drop view",
	reflect.TypeOf(&emptyNode{}):          "empty",
	reflect.TypeOf(&explainDebugNode{}):   "explain debug",
	reflect.TypeOf(&explainDistSQLNode{}): "explain dist_sql",
	reflect.TypeOf(&explainPlanNode{}):    "explain plan",
	reflect.TypeOf(&explainTraceNode{}):   "explain trace",
	reflect.TypeOf(&filterNode{}):         "filter",
	reflect.TypeOf(&groupNode{}):          "group",
	reflect.TypeOf(&hookFnNode{}):         "plugin",
	reflect.TypeOf(&indexJoinNode{}):      "index-join",
	reflect.TypeOf(&insertNode{}):         "insert",
	reflect.TypeOf(&joinNode{}):           "join",
	reflect.TypeOf(&limitNode{}):          "limit",
	reflect.TypeOf(&ordinalityNode{}):     "ordinality",
	reflect.TypeOf(&relocateNode{}):       "relocate",
	reflect.TypeOf(&renderNode{}):         "render",
	reflect.TypeOf(&scanNode{}):           "scan",
	reflect.TypeOf(&scatterNode{}):        "scatter",
	reflect.TypeOf(&showRangesNode{}):     "showRanges",
	reflect.TypeOf(&sortNode{}):           "sort",
	reflect.TypeOf(&splitNode{}):          "split",
	reflect.TypeOf(&unionNode{}):          "union",
	reflect.TypeOf(&updateNode{}):         "update",
	reflect.TypeOf(&valueGenerator{}):     "generator",
	reflect.TypeOf(&valuesNode{}):         "values",
	reflect.TypeOf(&windowNode{}):         "window",
}


text:
<?php namespace Arcanedev\Stripe\Resources;

use Arcanedev\Stripe\Contracts\Resources\Balance as BalanceContract;
use Arcanedev\Stripe\SingletonResource;

/**
 * Class     Balance
 *
 * @package  Arcanedev\Stripe\Resources
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 * @link     https://stripe.com/docs/api/php#balance_object
 *
 * @property  string  object     // "balance"
 * @property  array   available
 * @property  bool    livemode
 * @property  array   pending
 */
class Balance extends SingletonResource implements BalanceContract
{
    /* ------------------------------------------------------------------------------------------------
     |  Main Functions
     | ------------------------------------------------------------------------------------------------
     */
    /**
     * Retrieve a balance.
     *
     * @link   https://stripe.com/docs/api/php#retrieve_balance
     *
     * @param  array|string|null  $options
     *
     * @return self
     */
    public static function retrieve($options = null)
    {
        return self::scopedSingletonRetrieve(get_class(), $options);
    }
}


text:
import os

try:
    import cPickle as pickle
except:
    import pickle

SETTINGS_PATH = os.path.abspath(os.path.expanduser("~/.cshare"))

class GoogleAdapter(object):
    def __init__(self, accessor):
        self._api = accessor
        self._authenticator = None
        self._auth_url = None
        self._auth_token = None
        self._token_path = os.path.join(SETTINGS_PATH, "token.dat")
        self._create_user_settings()

    def _create_user_settings(self):
        #TODO this isn't portable, use ENVIRON!
        if not os.path.exists(SETTINGS_PATH):
            os.mkdir(SETTINGS_PATH)

    def get_access_url(self):
        self._authenticator = self._api.create_auth()
        self._auth_url = self._authenticator.next()
        return self._auth_url

    def get_access_credentials(self):
        self._auth_token = self._authenticator.next()
        self._store_credential()
        return self._auth_token

    def _store_credential(self):
        with open(self._token_path, "w") as token_file:
            pickle.dump(self._auth_token, token_file)

    def login(self):
        if self._auth_token is None:
            with open(self._token_path) as token_file:
                self._auth_token = pickle.load(token_file)
        self._api.login(self._auth_token)


text:
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <runtime name="com.genuitec.runtime.generic.jee60"/>
  <fixed facet="wst.jsdt.web"/>
  <fixed facet="jst.web"/>
  <fixed facet="java"/>
  <installed facet="java" version="1.7"/>
  <installed facet="jst.web" version="3.0"/>
  <installed facet="jst.web.jstl" version="1.2.1"/>
  <installed facet="wst.jsdt.web" version="1.0"/>
  <installed facet="me.spring" version="4.1"/>
</faceted-project>


text:
<!DOCTYPE html>
<body>
<script src="../resources/runner.js"></script>
<script>

var length = 1000000;
var source = new Uint8Array(length);
for (var i = 0; i < length; i++)
    source[i] = i;

PerfTestRunner.measureRunsPerSecond({
    description: "Measures performance of creating a Uint8Array from an existing Uint8Array.",
    run: function() {
        var target = new Uint8Array(source);
    }
});
</script>
</body>


text:
package jwt

import (
	"math/big"
	"testing"

	"github.com/google/go-cmp/cmp"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/testing/protocmp"
	"github.com/google/tink/go/core/registry"
	jrsppb "github.com/google/tink/go/proto/jwt_rsa_ssa_pkcs1_go_proto"
	tpb "github.com/google/tink/go/proto/tink_go_proto"
)

const testJWTRSSignerKeyType = "type.googleapis.com/google.crypto.tink.JwtRsaSsaPkcs1PrivateKey"

func makeValidJWTRSPrivateKey() (*jrsppb.JwtRsaSsaPkcs1PrivateKey, error) {
	// key taken from: https://datatracker.ietf.org/doc/html/rfc7515#appendix-A.2
	pubKey, err := makeValidRSPublicKey()
	if err != nil {
		return nil, err
	}
	d, err := base64Decode(
		"Eq5xpGnNCivDflJsRQBXHx1hdR1k6Ulwe2JZD50LpXyWPEAeP88vLNO97I" +
			"jlA7_GQ5sLKMgvfTeXZx9SE-7YwVol2NXOoAJe46sui395IW_GO-pWJ1O0" +
			"BkTGoVEn2bKVRUCgu-GjBVaYLU6f3l9kJfFNS3E0QbVdxzubSu3Mkqzjkn" +
			"439X0M_V51gfpRLI9JYanrC4D4qAdGcopV_0ZHHzQlBjudU2QvXt4ehNYT" +
			"CBr6XCLQUShb1juUO1ZdiYoFaFQT5Tw8bGUl_x_jTj3ccPDVZFD9pIuhLh" +
			"BOneufuBiB4cS98l2SR_RQyGWSeWjnczT0QU91p1DhOVRuOopznQ")
	if err != nil {
		return nil, err
	}
	p, err := base64Decode(
		"4BzEEOtIpmVdVEZNCqS7baC4crd0pqnRH_5IB3jw3bcxGn6QLvnEtfdUdi" +
			"YrqBdss1l58BQ3KhooKeQTa9AB0Hw_Py5PJdTJNPY8cQn7ouZ2KKDcmnPG" +
			"BY5t7yLc1QlQ5xHdwW1VhvKn-nXqhJTBgIPgtldC-KDV5z-y2XDwGUc")
	if err != nil {
		return nil, err
	}
	q, err := base64Decode(
		"uQPEfgmVtjL0Uyyx88GZFF1fOunH3-7cepKmtH4pxhtCoHqpWmT8YAmZxa" +
			"ewHgHAjLYsp1ZSe7zFYHj7C6ul7TjeLQeZD_YwD66t62wDmpe_HlB-TnBA" +
			"-njbglfIsRLtXlnDzQkv5dTltRJ11BKBBypeeF6689rjcJIDEz9RWdc")
	if err != nil {
		return nil, err
	}
	dp, err := base64Decode(
		"BwKfV3Akq5_MFZDFZCnW-wzl-CCo83WoZvnLQwCTeDv8uzluRSnm71I3Q" +
			"CLdhrqE2e9YkxvuxdBfpT_PI7Yz-FOKnu1R6HsJeDCjn12Sk3vmAktV2zb" +
			"34MCdy7cpdTh_YVr7tss2u6vneTwrA86rZtu5Mbr1C1XsmvkxHQAdYo0")
	if err != nil {
		return nil, err
	}
	dq, err := base64Decode(
		"h_96-mK1R_7glhsum81dZxjTnYynPbZpHziZjeeHcXYsXaaMwkOlODsWa" +
			"7I9xXDoRwbKgB719rrmI2oKr6N3Do9U0ajaHF-NKJnwgjMd2w9cjz3_-ky" +
			"NlxAr2v4IKhGNpmM5iIgOS1VZnOZ68m6_pbLBSp3nssTdlqvd0tIiTHU")
	if err != nil {
		return nil, err
	}
	qi, err := base64Decode(
		"IYd7DHOhrWvxkwPQsRM2tOgrjbcrfvtQJipd-DlcxyVuuM9sQLdgjVk2o" +
			"y26F0EmpScGLq2MowX7fhd_QJQ3ydy5cY7YIBi87w93IKLEdfnbJtoOPLU" +
			"W0ITrJReOgo1cq9SbsxYawBgfp_gh6A5603k2-ZQwVK0JKSHuLFkuQ3U")
	if err != nil {
		return nil, err
	}
	return &jrsppb.JwtRsaSsaPkcs1PrivateKey{
		PublicKey: pubKey,
		Version:   0,
		D:         d,
		P:         p,
		Q:         q,
		Dp:        dp,
		Dq:        dq,
		Crt:       qi,
	}, nil
}

func TestJWTRSSignerKeyManagerDoesSupport(t *testing.T) {
	km, err := registry.GetKeyManager(testJWTRSSignerKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSSignerKeyType, err)
	}
	if !km.DoesSupport(testJWTRSSignerKeyType) {
		t.Errorf("DoesSupport(%q) = false, want true", testJWTRSSignerKeyType)
	}
	if km.DoesSupport("invalid.key.type") {
		t.Errorf("DoesSupport(%q) = true, want false", "invalid.key.type")
	}
}

func TestJWTRSSignerKeyManagerTypeURL(t *testing.T) {
	km, err := registry.GetKeyManager(testJWTRSSignerKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSSignerKeyType, err)
	}
	if km.TypeURL() != testJWTRSSignerKeyType {
		t.Errorf("TypeURL() = %v, want = %v", km.TypeURL(), testJWTRSSignerKeyType)
	}
}

func TestJWTRSSignerKeyManagerPrimitiveSignAndVerify(t *testing.T) {
	skm, err := registry.GetKeyManager(testJWTRSSignerKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSSignerKeyType, err)
	}
	privKey, err := makeValidJWTRSPrivateKey()
	if err != nil {
		t.Fatalf("makeValidJWTRSPrivateKey() err = %v, want nil", err)
	}
	privKey.PublicKey.CustomKid = nil
	serializedPrivKey, err := proto.Marshal(privKey)
	if err != nil {
		t.Fatalf("proto.Marshal() err = %v, want nil", err)
	}
	sp, err := skm.Primitive(serializedPrivKey)
	if err != nil {
		t.Fatalf("Primitive() err = %v, want nil", err)
	}
	signer, ok := sp.(*signerWithKID)
	if !ok {
		t.Fatalf("primitive isn't a JWT signer")
	}
	unsigned, err := NewRawJWT(&RawJWTOptions{WithoutExpiration: true})
	if err != nil {
		t.Fatalf("NewRawJWT() err = %v, want nil", err)
	}
	signed, err := signer.SignAndEncodeWithKID(unsigned, nil)
	if err != nil {
		t.Fatalf("SignAndEncodeWithKID(kid = nil) err = %v, want nil", err)
	}
	vkm, err := registry.GetKeyManager(testJWTRSVerifierKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSVerifierKeyType, err)
	}
	serializedPubKey, err := proto.Marshal(privKey.PublicKey)
	if err != nil {
		t.Fatalf("proto.Marshal() err = %v, want nil", err)
	}
	vp, err := vkm.Primitive(serializedPubKey)
	if err != nil {
		t.Fatalf("Primitive() err = %v, want nil", err)
	}
	verifier, ok := vp.(*verifierWithKID)
	if !ok {
		t.Fatalf("primitive isn't a JWT Verifier")
	}
	validator, err := NewValidator(&ValidatorOpts{AllowMissingExpiration: true})
	if err != nil {
		t.Fatalf("NewValidator() err = %v, want nil", err)
	}
	if _, err := verifier.VerifyAndDecodeWithKID(signed, validator, nil); err != nil {
		t.Errorf("VerifyAndDecodeWithKID(kid = nil) err = %v, want nil", err)
	}
	// Shouldn't contain KID header at all.
	if _, err := verifier.VerifyAndDecodeWithKID(signed, validator, refString("")); err == nil {
		t.Errorf("VerifyAndDecodeWithKID(kid = '123') err = nil, want error")
	}
}

func TestJWTRSSignerKeyManagerPrimitiveWithInvalidSerializedKeyFails(t *testing.T) {
	km, err := registry.GetKeyManager(testJWTRSSignerKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSSignerKeyType, err)
	}
	if _, err := km.Primitive([]byte("invalid_serialization")); err == nil {
		t.Fatalf("Primitive() err = nil, want error")
	}
}

func TestJWTRSSignerKeyManagerPrimitiveSignAndVerifyWithTinkKID(t *testing.T) {
	skm, err := registry.GetKeyManager(testJWTRSSignerKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSSignerKeyType, err)
	}
	privKey, err := makeValidJWTRSPrivateKey()
	if err != nil {
		t.Fatalf("makeValidJWTRSPrivateKey() err = %v, want nil", err)
	}
	privKey.PublicKey.CustomKid = nil
	serializedPrivKey, err := proto.Marshal(privKey)
	if err != nil {
		t.Fatalf("proto.Marshal() err = %v, want nil", err)
	}
	sp, err := skm.Primitive(serializedPrivKey)
	if err != nil {
		t.Fatalf("Primitive() err = %v, want nil", err)
	}
	signer, ok := sp.(*signerWithKID)
	if !ok {
		t.Fatalf("primitive isn't a JWT signer")
	}
	unsigned, err := NewRawJWT(&RawJWTOptions{WithoutExpiration: true})
	if err != nil {
		t.Fatalf("NewRawJWT() err = %v, want nil", err)
	}
	signedWithKID, err := signer.SignAndEncodeWithKID(unsigned, refString("555"))
	if err != nil {
		t.Fatalf("SignAndEncodeWithKID(kid = '555') err = %v, want nil", err)
	}
	vkm, err := registry.GetKeyManager(testJWTRSVerifierKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSVerifierKeyType, err)
	}
	serializedPubKey, err := proto.Marshal(privKey.PublicKey)
	if err != nil {
		t.Fatalf("proto.Marshal() err = %v, want nil", err)
	}
	vp, err := vkm.Primitive(serializedPubKey)
	if err != nil {
		t.Fatalf("Primitive() err = %v, want nil", err)
	}
	verifier, ok := vp.(*verifierWithKID)
	if !ok {
		t.Fatalf("primitive isn't a JWT Verifier")
	}
	validator, err := NewValidator(&ValidatorOpts{AllowMissingExpiration: true})
	if err != nil {
		t.Fatalf("NewValidator() err = %v, want nil", err)
	}
	if _, err := verifier.VerifyAndDecodeWithKID(signedWithKID, validator, refString("555")); err != nil {
		t.Fatalf("VerifyAndDecodeWithKID(kid = '555') err = %v, want nil", err)
	}
	if _, err := verifier.VerifyAndDecodeWithKID(signedWithKID, validator, refString("0")); err == nil {
		t.Fatalf("VerifyAndDecodeWithKID(kid = '0') err = nil, want error")
	}
}

func TestJWTRSSignerKeyManagerPrimitiveSignAndVerifyWithCustomKID(t *testing.T) {
	skm, err := registry.GetKeyManager(testJWTRSSignerKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSSignerKeyType, err)
	}
	privKey, err := makeValidJWTRSPrivateKey()
	if err != nil {
		t.Fatalf("makeValidJWTRSPrivateKey() err = %v, want nil", err)
	}
	privKey.PublicKey.CustomKid = &jrsppb.JwtRsaSsaPkcs1PublicKey_CustomKid{
		Value: "7843",
	}
	serializedPrivKey, err := proto.Marshal(privKey)
	if err != nil {
		t.Fatalf("proto.Marshal() err = %v, want nil", err)
	}
	sp, err := skm.Primitive(serializedPrivKey)
	if err != nil {
		t.Fatalf("Primitive() err = %v, want nil", err)
	}
	signer, ok := sp.(*signerWithKID)
	if !ok {
		t.Fatalf("primitive isn't a JWT signer")
	}
	unsigned, err := NewRawJWT(&RawJWTOptions{WithoutExpiration: true})
	if err != nil {
		t.Fatalf("NewRawJWT() err = %v, want nil", err)
	}
	signed, err := signer.SignAndEncodeWithKID(unsigned, nil)
	if err != nil {
		t.Fatalf("SignAndEncodeWithKID(kid = nil) err = %v, want nil", err)
	}
	if _, err := signer.SignAndEncodeWithKID(unsigned, refString("555")); err == nil {
		t.Fatalf("SignAndEncodeWithKID(kid = '555') err = nil, want error")
	}
	vkm, err := registry.GetKeyManager(testJWTRSVerifierKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSVerifierKeyType, err)
	}
	serializedPubKey, err := proto.Marshal(privKey.PublicKey)
	if err != nil {
		t.Fatalf("proto.Marshal() err = %v, want nil", err)
	}
	vp, err := vkm.Primitive(serializedPubKey)
	if err != nil {
		t.Fatalf("Primitive() err = %v, want nil", err)
	}
	verifier, ok := vp.(*verifierWithKID)
	if !ok {
		t.Fatalf("primitive isn't a JWT Verifier")
	}
	validator, err := NewValidator(&ValidatorOpts{AllowMissingExpiration: true})
	if err != nil {
		t.Fatalf("NewValidator() err = %v, want nil", err)
	}
	if _, err := verifier.VerifyAndDecodeWithKID(signed, validator, nil); err != nil {
		t.Fatalf("VerifyAndDecodeWithKID(kid = nil) err = %v, want nil", err)
	}
	if _, err := verifier.VerifyAndDecodeWithKID(signed, validator, refString("7843")); err == nil {
		t.Fatalf("VerifyAndDecodeWithKID(kid = '7843') err = nil, want error")
	}
}

func TestJWTRSSignerKeyManagerPrimitiveFailsWithInvalidKey(t *testing.T) {
	type testCase struct {
		name    string
		privKey *jrsppb.JwtRsaSsaPkcs1PrivateKey
	}
	km, err := registry.GetKeyManager(testJWTRSSignerKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSSignerKeyType, err)
	}
	validPrivKey, err := makeValidJWTRSPrivateKey()
	if err != nil {
		t.Fatalf("makeValidJWTRSPrivateKey() err = %v, want nil", err)
	}
	for _, tc := range []testCase{
		{
			name:    "nil private key",
			privKey: nil,
		},
		{
			name:    "empty private key",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{},
		},
		{
			name: "invalid private key version",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{
				PublicKey: validPrivKey.GetPublicKey(),
				Version:   validPrivKey.GetVersion() + 1,
				D:         validPrivKey.GetD(),
				P:         validPrivKey.GetP(),
				Q:         validPrivKey.GetQ(),
				Dp:        validPrivKey.GetDp(),
				Dq:        validPrivKey.GetDq(),
				Crt:       validPrivKey.GetCrt(),
			},
		},
		{
			name: "invalid D private key value",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{
				PublicKey: validPrivKey.GetPublicKey(),
				Version:   validPrivKey.GetVersion(),
				D:         nil,
				P:         validPrivKey.GetP(),
				Q:         validPrivKey.GetQ(),
				Dp:        validPrivKey.GetDp(),
				Dq:        validPrivKey.GetDq(),
				Crt:       validPrivKey.GetCrt(),
			},
		},
		{
			name: "invalid P private key value",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{
				PublicKey: validPrivKey.GetPublicKey(),
				Version:   validPrivKey.GetVersion(),
				D:         validPrivKey.GetD(),
				P:         nil,
				Q:         validPrivKey.GetQ(),
				Dp:        validPrivKey.GetDp(),
				Dq:        validPrivKey.GetDq(),
				Crt:       validPrivKey.GetCrt(),
			},
		},
		{
			name: "invalid Q private key value",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{
				PublicKey: validPrivKey.GetPublicKey(),
				Version:   validPrivKey.GetVersion(),
				D:         validPrivKey.GetD(),
				P:         validPrivKey.GetP(),
				Q:         nil,
				Dp:        validPrivKey.GetDp(),
				Dq:        validPrivKey.GetDq(),
				Crt:       validPrivKey.GetCrt(),
			},
		},
		{
			name: "invalid pre computed Dp key value",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{
				PublicKey: validPrivKey.GetPublicKey(),
				Version:   validPrivKey.GetVersion(),
				D:         validPrivKey.GetD(),
				P:         validPrivKey.GetP(),
				Q:         validPrivKey.GetQ(),
				Dp:        nil,
				Dq:        validPrivKey.GetDq(),
				Crt:       validPrivKey.GetCrt(),
			},
		},
		{
			name: "invalid pre computed Dq key value",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{
				PublicKey: validPrivKey.GetPublicKey(),
				Version:   validPrivKey.GetVersion(),
				D:         validPrivKey.GetD(),
				P:         validPrivKey.GetP(),
				Q:         validPrivKey.GetQ(),
				Dp:        validPrivKey.GetDp(),
				Dq:        nil,
				Crt:       validPrivKey.GetCrt(),
			},
		},
		{
			name: "invalid pre computed Dq key value",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{
				PublicKey: validPrivKey.GetPublicKey(),
				Version:   validPrivKey.GetVersion(),
				D:         validPrivKey.GetD(),
				P:         validPrivKey.GetP(),
				Q:         validPrivKey.GetQ(),
				Dp:        validPrivKey.GetDp(),
				Dq:        validPrivKey.GetDq(),
				Crt:       nil,
			},
		},
		{
			name: "nil public key",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{
				PublicKey: nil,
				Version:   validPrivKey.GetVersion(),
				D:         validPrivKey.GetD(),
				P:         validPrivKey.GetP(),
				Q:         validPrivKey.GetQ(),
				Dp:        validPrivKey.GetDp(),
				Dq:        validPrivKey.GetDq(),
				Crt:       validPrivKey.GetCrt(),
			},
		},
		{
			name: "empty public key",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{
				PublicKey: &jrsppb.JwtRsaSsaPkcs1PublicKey{},
				Version:   validPrivKey.GetVersion(),
				D:         validPrivKey.GetD(),
				P:         validPrivKey.GetP(),
				Q:         validPrivKey.GetQ(),
				Dp:        validPrivKey.GetDp(),
				Dq:        validPrivKey.GetDq(),
				Crt:       validPrivKey.GetCrt(),
			},
		},
		{
			name: "invalid private key version",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{
				PublicKey: validPrivKey.GetPublicKey(),
				Version:   validPrivKey.Version + 1,
				D:         validPrivKey.GetD(),
				P:         validPrivKey.GetP(),
				Q:         validPrivKey.GetQ(),
				Dp:        validPrivKey.GetDp(),
				Dq:        validPrivKey.GetDq(),
				Crt:       validPrivKey.GetCrt(),
			},
		},
		{
			name: "invalid public key version",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{
				PublicKey: &jrsppb.JwtRsaSsaPkcs1PublicKey{
					Version:   validPrivKey.GetPublicKey().GetVersion() + 1,
					Algorithm: validPrivKey.GetPublicKey().GetAlgorithm(),
					N:         validPrivKey.GetPublicKey().GetN(),
					E:         validPrivKey.GetPublicKey().GetE(),
					CustomKid: validPrivKey.GetPublicKey().GetCustomKid(),
				},
				Version: validPrivKey.GetVersion(),
				D:       validPrivKey.GetD(),
				P:       validPrivKey.GetP(),
				Q:       validPrivKey.GetQ(),
				Dp:      validPrivKey.GetDp(),
				Dq:      validPrivKey.GetDq(),
				Crt:     validPrivKey.GetCrt(),
			},
		},
		{
			name: "invalid algorithm",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{
				PublicKey: &jrsppb.JwtRsaSsaPkcs1PublicKey{
					Version:   validPrivKey.GetPublicKey().GetVersion(),
					Algorithm: jrsppb.JwtRsaSsaPkcs1Algorithm_RS_UNKNOWN,
					N:         validPrivKey.GetPublicKey().GetN(),
					E:         validPrivKey.GetPublicKey().GetE(),
					CustomKid: validPrivKey.GetPublicKey().GetCustomKid(),
				},
				Version: validPrivKey.GetVersion(),
				D:       validPrivKey.GetD(),
				P:       validPrivKey.GetP(),
				Q:       validPrivKey.GetQ(),
				Dp:      validPrivKey.GetDp(),
				Dq:      validPrivKey.GetDq(),
				Crt:     validPrivKey.GetCrt(),
			},
		},
		{
			name: "invalid modulus",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{
				PublicKey: &jrsppb.JwtRsaSsaPkcs1PublicKey{
					Version:   validPrivKey.GetPublicKey().GetVersion(),
					Algorithm: validPrivKey.GetPublicKey().GetAlgorithm(),
					N:         []byte{0x00, 0x01},
					E:         validPrivKey.GetPublicKey().GetE(),
					CustomKid: validPrivKey.GetPublicKey().GetCustomKid(),
				},
				Version: validPrivKey.GetVersion(),
				D:       validPrivKey.GetD(),
				P:       validPrivKey.GetP(),
				Q:       validPrivKey.GetQ(),
				Dp:      validPrivKey.GetDp(),
				Dq:      validPrivKey.GetDq(),
				Crt:     validPrivKey.GetCrt(),
			},
		},
		{
			name: "invalid exponent",
			privKey: &jrsppb.JwtRsaSsaPkcs1PrivateKey{
				PublicKey: &jrsppb.JwtRsaSsaPkcs1PublicKey{
					Version:   validPrivKey.GetPublicKey().GetVersion(),
					Algorithm: validPrivKey.GetPublicKey().GetAlgorithm(),
					N:         validPrivKey.GetPublicKey().GetN(),
					E:         []byte{0x07},
					CustomKid: validPrivKey.GetPublicKey().GetCustomKid(),
				},
				Version: validPrivKey.GetVersion(),
				D:       validPrivKey.GetD(),
				P:       validPrivKey.GetP(),
				Q:       validPrivKey.GetQ(),
				Dp:      validPrivKey.GetDp(),
				Dq:      validPrivKey.GetDq(),
				Crt:     validPrivKey.GetCrt(),
			},
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			serializedPrivKey, err := proto.Marshal(tc.privKey)
			if err != nil {
				t.Fatalf("proto.Marshal() err = %v, want nil", err)
			}
			if _, err := km.Primitive(serializedPrivKey); err == nil {
				t.Fatalf("Primitive() err = nil, want error")
			}
			if _, err := km.(registry.PrivateKeyManager).PublicKeyData(serializedPrivKey); err == nil {
				t.Fatalf("PublicKeyData() err = nil, want error")
			}
		})
	}
}

func TestJWTRSSignerKeyManagerPrimitiveFailsWithCorruptedKey(t *testing.T) {
	km, err := registry.GetKeyManager(testJWTRSSignerKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSSignerKeyType, err)
	}
	validPrivKey, err := makeValidJWTRSPrivateKey()
	if err != nil {
		t.Fatalf("makeValidJWTRSPrivateKey() err = %v, want nil", err)
	}
	corruptedPrivKey := validPrivKey
	corruptedPrivKey.P[100] = byte(uint8(corruptedPrivKey.P[100] + 1))
	corruptedPrivKey.P[5] = byte(uint8(corruptedPrivKey.P[5] + 1))
	serializedPrivKey, err := proto.Marshal(corruptedPrivKey)
	if err != nil {
		t.Fatalf("proto.Marshal() err = %v, want nil", err)
	}
	if _, err := km.Primitive(serializedPrivKey); err == nil {
		t.Fatalf("Primitive() err = nil, want error")
	}
}

func TestJWTRSSignerKeyManagerPublicKeyData(t *testing.T) {
	km, err := registry.GetKeyManager(testJWTRSSignerKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSSignerKeyType, err)
	}
	privKey, err := makeValidJWTRSPrivateKey()
	if err != nil {
		t.Fatalf("makeValidJWTRSPrivateKey() err = %v, want nil", err)
	}
	serializedPrivKey, err := proto.Marshal(privKey)
	if err != nil {
		t.Fatalf("proto.Marshal() err = %v, want nil", err)
	}
	pubKeyData, err := km.(registry.PrivateKeyManager).PublicKeyData(serializedPrivKey)
	if err != nil {
		t.Fatalf("PublicKeyData() err = %v, want nil", err)
	}
	if pubKeyData.GetKeyMaterialType() != tpb.KeyData_ASYMMETRIC_PUBLIC {
		t.Errorf("GetKeyMaterialType() = %v, want %v", pubKeyData.GetKeyMaterialType(), tpb.KeyData_ASYMMETRIC_PUBLIC)
	}
	if pubKeyData.GetTypeUrl() != testJWTRSVerifierKeyType {
		t.Errorf("TypeURL() = %v, want %v", pubKeyData.GetTypeUrl(), testJWTRSVerifierKeyType)
	}
	gotPubKey := &jrsppb.JwtRsaSsaPkcs1PublicKey{}
	if err := proto.Unmarshal(pubKeyData.GetValue(), gotPubKey); err != nil {
		t.Fatalf("proto.Unmarshal() err = %v, want nil", err)
	}
	if !cmp.Equal(gotPubKey, privKey.GetPublicKey(), protocmp.Transform()) {
		t.Errorf("got = %v, want = %v", gotPubKey, privKey.GetPublicKey())
	}
}

func TestJWTRSSignerKeyManagerPublicKeyDataWithNilKeyFails(t *testing.T) {
	km, err := registry.GetKeyManager(testJWTRSSignerKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSSignerKeyType, err)
	}
	if _, err := km.(registry.PrivateKeyManager).PublicKeyData(nil); err == nil {
		t.Fatalf("PublicKeyData(nil) err = nil, want error")
	}
}

func TestJWTRSSignerKeyManagerNewKeyData(t *testing.T) {
	km, err := registry.GetKeyManager(testJWTRSSignerKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSSignerKeyType, err)
	}
	type testCase struct {
		name      string
		keyFormat *jrsppb.JwtRsaSsaPkcs1KeyFormat
	}
	for _, tc := range []testCase{
		{
			name: "RS256 with 3072 modulus",
			keyFormat: &jrsppb.JwtRsaSsaPkcs1KeyFormat{
				Version:           0,
				Algorithm:         jrsppb.JwtRsaSsaPkcs1Algorithm_RS256,
				ModulusSizeInBits: 3072,
				PublicExponent:    []byte{0x01, 0x00, 0x01},
			},
		},
		{
			name: "RS384 with 3072 modulus",
			keyFormat: &jrsppb.JwtRsaSsaPkcs1KeyFormat{
				Version:           0,
				Algorithm:         jrsppb.JwtRsaSsaPkcs1Algorithm_RS384,
				ModulusSizeInBits: 3072,
				PublicExponent:    []byte{0x01, 0x00, 0x01},
			},
		},
		{
			name: "RS512 with 4096 modulus",
			keyFormat: &jrsppb.JwtRsaSsaPkcs1KeyFormat{
				Version:           0,
				Algorithm:         jrsppb.JwtRsaSsaPkcs1Algorithm_RS512,
				ModulusSizeInBits: 4096,
				PublicExponent:    []byte{0x01, 0x00, 0x01},
			},
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			serializedKeyFormat, err := proto.Marshal(tc.keyFormat)
			if err != nil {
				t.Fatalf("proto.Marshal() err = %v, want nil", err)
			}
			keyData, err := km.NewKeyData(serializedKeyFormat)
			if err != nil {
				t.Fatalf("NewKeyData() err = %v, want nil", err)
			}
			if keyData.GetTypeUrl() != testJWTRSSignerKeyType {
				t.Errorf("GetTypeURL() = %v, want %v", keyData.GetTypeUrl(), testJWTRSSignerKeyType)
			}
			if keyData.GetKeyMaterialType() != tpb.KeyData_ASYMMETRIC_PRIVATE {
				t.Errorf("GetKeyMaterialType() = %v, want %v", keyData.GetKeyMaterialType(), tpb.KeyData_ASYMMETRIC_PRIVATE)
			}
			key := &jrsppb.JwtRsaSsaPkcs1PrivateKey{}
			if err := proto.Unmarshal(keyData.GetValue(), key); err != nil {
				t.Fatalf("proto.Unmarshal() err = %v, want nil", err)
			}
			pubKey := key.GetPublicKey()
			got, want := pubKey.GetAlgorithm(), tc.keyFormat.GetAlgorithm()
			if got != want {
				t.Errorf("GetAlgorithm() = %v, want %v", got, want)
			}
			gotE, wantE := pubKey.GetE(), tc.keyFormat.GetPublicExponent()
			if !cmp.Equal(gotE, wantE) {
				t.Errorf("Exponent = %v, want %v", gotE, wantE)
			}
			gotMod := new(big.Int).SetBytes(pubKey.GetN()).BitLen()
			wantMod := int(tc.keyFormat.GetModulusSizeInBits())
			if gotMod != wantMod {
				t.Errorf("Modulus Size in Bits = %d, want %d", gotMod, wantMod)
			}
		})
	}
}

func TestJWTRSSignerKeyManagerNewKeyDataFailsWithInvalidFormat(t *testing.T) {
	type testCase struct {
		name      string
		keyFormat *jrsppb.JwtRsaSsaPkcs1KeyFormat
	}
	km, err := registry.GetKeyManager(testJWTRSSignerKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSSignerKeyType, err)
	}
	for _, tc := range []testCase{
		{
			name:      "nil key format",
			keyFormat: nil,
		},
		{
			name:      "empty key format",
			keyFormat: &jrsppb.JwtRsaSsaPkcs1KeyFormat{},
		},
		{
			name: "invalid version",
			keyFormat: &jrsppb.JwtRsaSsaPkcs1KeyFormat{
				Algorithm:         jrsppb.JwtRsaSsaPkcs1Algorithm_RS256,
				Version:           1,
				PublicExponent:    []byte{0x01, 0x00, 0x01},
				ModulusSizeInBits: 3072,
			},
		},
		{
			name: "invalid algorithm",
			keyFormat: &jrsppb.JwtRsaSsaPkcs1KeyFormat{
				Algorithm:         jrsppb.JwtRsaSsaPkcs1Algorithm_RS_UNKNOWN,
				Version:           0,
				PublicExponent:    []byte{0x01, 0x00, 0x01},
				ModulusSizeInBits: 3072,
			},
		},
		{
			name: "invalid public exponent",
			keyFormat: &jrsppb.JwtRsaSsaPkcs1KeyFormat{
				Algorithm:         jrsppb.JwtRsaSsaPkcs1Algorithm_RS256,
				Version:           0,
				PublicExponent:    []byte{0x01},
				ModulusSizeInBits: 3072,
			},
		},
		{
			name: "invalid modulus size",
			keyFormat: &jrsppb.JwtRsaSsaPkcs1KeyFormat{
				Algorithm:         jrsppb.JwtRsaSsaPkcs1Algorithm_RS256,
				Version:           0,
				PublicExponent:    []byte{0x01, 0x00, 0x01},
				ModulusSizeInBits: 1024,
			},
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			serializedKeyFormat, err := proto.Marshal(tc.keyFormat)
			if err != nil {
				t.Fatalf("proto.Marshal() err = %v, want nil", err)
			}
			if _, err := km.NewKeyData(serializedKeyFormat); err == nil {
				t.Fatalf("NewKeyData() err = nil, want error")
			}
			if _, err := km.NewKey(serializedKeyFormat); err == nil {
				t.Fatalf("NewKey() err = nil, want error")
			}
		})
	}
}

func TestJWTRSSignerKeyManagerNewKeyDataFailsWithNilKeyFormat(t *testing.T) {
	km, err := registry.GetKeyManager(testJWTRSSignerKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSSignerKeyType, err)
	}
	if _, err := km.NewKeyData(nil); err == nil {
		t.Fatalf("NewKeyData() err = nil, want error")
	}
	if _, err := km.NewKey(nil); err == nil {
		t.Fatalf("NewKey() err = nil, want error")
	}
}

func TestJWTRSSignerKeyManagerNewKeyDataFailsWithInvalidSerializedKeyFormat(t *testing.T) {
	km, err := registry.GetKeyManager(testJWTRSSignerKeyType)
	if err != nil {
		t.Fatalf("registry.GetKeyManager(%q) err = %v, want nil", testJWTRSSignerKeyType, err)
	}
	if _, err := km.NewKeyData([]byte("invalid_data")); err == nil {
		t.Fatalf("NewKeyData() err = nil, want error")
	}
	if _, err := km.NewKey([]byte("invalid_data")); err == nil {
		t.Fatalf("NewKey() err = nil, want error")
	}
}


text:
import unittest

from pytest import raises

from apache.aurora.client.api import UpdaterConfig

from gen.apache.aurora.api.ttypes import Range

class TestRangeConversion(unittest.TestCase):
  """Job instance ID to range conversion."""

  def test_multiple_ranges(self):
    """Test multiple ranges."""
    ranges = [repr(e) for e in UpdaterConfig.instances_to_ranges([1, 2, 3, 5, 7, 8])]
    assert 3 == len(ranges), "Wrong number of ranges:%s" % len(ranges)
    assert repr(Range(first=1, last=3)) in ranges, "Missing range [1,3]"
    assert repr(Range(first=5, last=5)) in ranges, "Missing range [5,5]"
    assert repr(Range(first=7, last=8)) in ranges, "Missing range [7,8]"

  def test_one_element(self):
    """Test one ID in the list."""
    ranges = [repr(e) for e in UpdaterConfig.instances_to_ranges([1])]
    assert 1 == len(ranges), "Wrong number of ranges:%s" % len(ranges)
    assert repr(Range(first=1, last=1)) in ranges, "Missing range [1,1]"

  def test_none_list(self):
    """Test None list produces None result."""
    assert UpdaterConfig.instances_to_ranges(None) is None, "Result must be None."

  def test_empty_list(self):
    """Test empty list produces None result."""
    assert UpdaterConfig.instances_to_ranges([]) is None, "Result must be None."

  def test_pulse_interval_secs(self):
    config = UpdaterConfig(1, 1, 1, 1, pulse_interval_secs=60)
    assert 60000 == config.to_thrift_update_settings().blockIfNoPulsesAfterMs

  def test_pulse_interval_unset(self):
    config = UpdaterConfig(1, 1, 1, 1)
    assert config.to_thrift_update_settings().blockIfNoPulsesAfterMs is None

  def test_pulse_interval_too_low(self):
    threshold = UpdaterConfig.MIN_PULSE_INTERVAL_SECONDS
    with raises(ValueError) as e:
      UpdaterConfig(1, 1, 1, 1, pulse_interval_secs=threshold - 1)
    assert 'Pulse interval seconds must be at least %s seconds.' % threshold in e.value.message


text:
"use strict";

const Widget = require('./widget');

class TitleWidget extends Widget {}

TitleWidget.Instance = require('./TitleWidgetInstance');
TitleWidget.id = 'Layout.TitleWidget';
// TODO: Translate.
TitleWidget.title = 'Page Title';
TitleWidget.description = 'Shows the title of the page.';
TitleWidget.templateFile = __dirname + '/../html/titleWidget.html';

module.exports = TitleWidget;


text:
import { click, render } from '@ember/test-helpers';
import {
  DEFAULT_A11Y_TEST_HELPER_NAMES,
  setEnableA11yAudit,
  setupGlobalA11yHooks,
  teardownGlobalA11yHooks,
} from 'ember-a11y-testing/test-support';
import { module, test } from 'qunit';

import hbs from 'htmlbars-inline-precompile';
import { setupRenderingTest } from 'ember-qunit';

module(
  'Integration | Component | setup-global-a11y-hooks-test',
  function (hooks) {
    setupRenderingTest(hooks);

    let actualAuditInvocationsCount = 0;

    function invokeAll(): boolean {
      return true;
    }

    async function a11yAuditFake() {
      actualAuditInvocationsCount += 1;
    }

    hooks.before(function () {
      setupGlobalA11yHooks(invokeAll, a11yAuditFake, {
        helpers: [...DEFAULT_A11Y_TEST_HELPER_NAMES, 'render'],
      });
      setEnableA11yAudit(true);
    });

    hooks.after(function () {
      teardownGlobalA11yHooks();
      setEnableA11yAudit();
    });

    hooks.beforeEach(function () {
      actualAuditInvocationsCount = 0;
    });

    test('it audits on render', async function (assert) {
      await render(hbs`
        <button type="button">Hello!</button>
      `);
      await click('button');

      assert.strictEqual(
        actualAuditInvocationsCount,
        2,
        'a11yAudit was automatically called twice'
      );
    });
  }
);


text:
'use strict';

/**
 * @ngdoc function
 * @name tbsApp.controller:JobListCtrl
 * @description
 * # JobListCtrl
 * Controller of the tbsApp
 */
angular.module('tbsApp').controller('JobListCtrl', function($scope, RJob, InGame, UserData) {
    var have_char = UserData.get('have_character', {});
    var job_levels = UserData.get('job_level', {});
    var job_level = {
        "1" : UserData.get('job1_level', {}),
        "2" : UserData.get('job2_level', {}),
        "3" : UserData.get('job3_level', {})
    };
    $scope.jobs = [];
    $scope.max_level = 90;

    $scope.cap_level = undefined;

    var calc_value = function(level, min, max, coeff) {
        var f = parseFloat(parseInt(level) - 1) / parseFloat(InGame.ChrJobParams_MaxLevel - 1);
        return Math.floor(parseFloat(min) + parseFloat(parseInt(max) - parseInt(min)) * Math.pow(f, parseFloat(coeff)));
    };

    RJob.all(function(jobs) {
        for (var i = 0; i < jobs.length; ++i) {
            var job = jobs[i];
            job.char_level = function(lvl){ return (angular.isNumber(lvl) ? lvl: (job_level[this.level][this.character_ref] || 1)); };

            job._hp    = function(lvl){ return calc_value(this.char_level(lvl), this.hp_min,   this.hp_max,   this.hp_coeff);   };
            job.m_hp   = function(lvl){ return calc_value($scope.max_level,     this.hp_min,   this.hp_max,   this.hp_coeff);   };
            job._atk   = function(lvl){ return calc_value(this.char_level(lvl), this.atk_min,  this.atk_max,  this.atk_coeff);  };
            job.m_atk  = function(lvl){ return calc_value($scope.max_level,     this.atk_min,  this.atk_max,  this.atk_coeff);  };
            job._def   = function(lvl){ return calc_value(this.char_level(lvl), this.def_min,  this.def_max,  this.def_coeff);  };
            job.m_def  = function(lvl){ return calc_value($scope.max_level,     this.def_min,  this.def_max,  this.def_coeff);  };
            job._matk  = function(lvl){ return calc_value(this.char_level(lvl), this.matk_min, this.matk_max, this.matk_coeff); };
            job.m_matk = function(lvl){ return calc_value($scope.max_level,     this.matk_min, this.matk_max, this.matk_coeff); };
            job._mdef  = function(lvl){ return calc_value(this.char_level(lvl), this.mdef_min, this.mdef_max, this.mdef_coeff); };
            job.m_mdef = function(lvl){ return calc_value($scope.max_level,     this.mdef_min, this.mdef_max, this.mdef_coeff); };

            if (have_char[job.character_ref] && job.xp && ((job_levels[job.character_ref] && job_levels[job.character_ref] >= job.level) || job.level == 1 )) {
                job.have_char = true;
                job.have_job = true;
            } else {
                if (!have_char[job.character_ref]) {
                    job.have_char = false;
                    job.have_job = false;
                } else {
                    job.have_char = true;
                    job.have_job = false;
                }
            }
            $scope.jobs.push(job);
        }
        $scope.jobs_limit = $scope.jobs.length;
    });

    $scope.btn_class = function(p) {
        if ($scope.predicate == p) {
            return $scope.reverse ? 'btn-success' : 'btn-danger';
        }
    };

    $scope.toggle_have_char = function() {
        if ($scope.search.have_char == '') {
            $scope.search.have_job = '';
        }
    };

    $scope.filters = {
        generation: '0'
    };

    $scope.filter_generation = function(job){
        if($scope.filters.generation == 0){
            return true;
        }
        return job.generation == $scope.filters.generation;
    }

    $scope.order_opts = {
        pred : 'ref',
        desc : true
    };
    var old_predicate = null;

    $scope.sort_change = function(pred) {
        if (pred == old_predicate) {
            $scope.order_opts.desc = !$scope.order_opts.desc;
            return;
        } else {
            $scope.order_opts.pred = function(job) {
                return job[pred]();
            };
            $scope.order_opts.desc = false;
            old_predicate = pred;
        }
    };
});


text:
(function ($) {
  //window scroll menu
  $(".current-position").on('click', '.btn-filter-advance', function(){
    $(".filter-advance").toggle('fast');
  });
  $(window).bind("scroll", function() {
    $(window).scrollTop() > 500 ? $("#header").addClass("fixed") : $("#header").removeClass("fixed");
  });
  $("body").on('click', '.popup-page .buttom-comment', function(){
    alert('a');
  });
})(jQuery);


text:
class Admin::StatisticsController < Admin::AdminController

  layout false
  respond_to :json, :xml

  # GET /admin/statistics/visitors.json
  def visitors
    respond_with Visit.facet_date options_params
  end

  # GET /admin/statistics/professions.json
  def professions
    respond_with Person.facet_profession
  end

  private
    # Never trust parameters from the scary internet, only allow the white list through.
    def options_params
      if params[:options]
        params.require(:options).permit(:interval)
      else
        {}
      end
    end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Xunit;

namespace TwelveDays
{
    public class TwelveDaysTest
    {
        [Fact]
        public void Return_verse_1()
        {
            var expected = "On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree.\n";
            var actual = TwelveDaysSong.Verse(1);
            Console.WriteLine(actual);
            actual.Should().Be(expected);
        }

        [Fact]
        public void Return_verse_2()
        {
            var expected = "On the second day of Christmas my true love gave to me, two Turtle Doves, and a Partridge in a Pear Tree.\n";
            var actual = TwelveDaysSong.Verse(2);
            Console.WriteLine(actual);
            actual.Should().Be(expected);
        }

        [Fact]
        public void Return_verse_3()
        {
            TwelveDaysSong.Verse(3).Should()
                .Be("On the third day of Christmas my true love gave to me, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n");
        }

        [Fact]
        public void Return_verse_4()
        {
            TwelveDaysSong.Verse(4).Should()
                .Be("On the fourth day of Christmas my true love gave to me, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n");
        }

        [Fact]
        public void Return_verse_5()
        {
            TwelveDaysSong.Verse(5).Should()
                .Be("On the fifth day of Christmas my true love gave to me, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n");
        }

        [Fact]
        public void Return_verse_6()
        {
            TwelveDaysSong.Verse(6).Should()
                .Be("On the sixth day of Christmas my true love gave to me, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n");
        }

        [Fact]
        public void Return_verse_7()
        {
            TwelveDaysSong.Verse(7).Should()
                .Be("On the seventh day of Christmas my true love gave to me, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n");
        }

        [Fact]
        public void Return_verse_8()
        {
            TwelveDaysSong.Verse(8).Should()
                .Be("On the eighth day of Christmas my true love gave to me, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n");
        }

        [Fact]
        public void Return_verse_9()
        {
            TwelveDaysSong.Verse(9).Should()
                .Be("On the ninth day of Christmas my true love gave to me, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n");
        }

        [Fact]
        public void Return_verse_10()
        {
            TwelveDaysSong.Verse(10).Should()
                .Be("On the tenth day of Christmas my true love gave to me, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n");
        }

        [Fact]
        public void Return_verse_11()
        {
            TwelveDaysSong.Verse(11).Should()
                .Be("On the eleventh day of Christmas my true love gave to me, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n");
        }

        [Fact]
        public void Return_verse_12()
        {
            TwelveDaysSong.Verse(12).Should()
                .Be("On the twelfth day of Christmas my true love gave to me, twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n");
        }

        [Fact]
        public void Return_multiple_verses()
        {
            TwelveDaysSong.Verses(1, 3).Should()
                .Be("On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree.\n\n" +
              "On the second day of Christmas my true love gave to me, two Turtle Doves, and a Partridge in a Pear Tree.\n\n" +
              "On the third day of Christmas my true love gave to me, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n\n");
        }

        [Fact]
        public void Return_entire_song()
        {
            TwelveDaysSong.Sing().Should()
                .Be(TwelveDaysSong.Verses(1, 12));
        }

        [Fact]
        public void SomeTest()
        {
            var list = new List<string>{"A", "B"};
            var result = list.Aggregate((a, b) => a + ", " + b);
            result.Should().Be("A, B");
        }
    }
}


text:
module BWAPI
  class Client
    module CommandCenter
      module Projects
        # TagColours module for commandcenter/projects/{project_id}/tagColours endpoints
        module TagColours
          # Get colours defined for tags in given project
          #
          # TODO: Add parameters documentation
          def tag_colours(project_id)
            get "/commandcenter/projects/#{project_id}/tagColours"
          end

          # Get colour defined for given tag
          #
          # TODO: Add parameters documentation
          def tag_colour(project_id, tag_name)
            get "/commandcenter/projects/#{project_id}/tagColours/#{tag_name}"
          end

          # Define the colour for a tag
          #
          # TODO: Add parameters documentation
          def create_tag_colour(project_id, opts = {})
            post "/commandcenter/projects/#{project_id}/tagColours", opts
          end

          # Update the colour for a tag
          #
          # TODO: Add parameters documentation
          def update_tag_colour(project_id, tag_name, opts = {})
            put "/commandcenter/projects/#{project_id}/tagColours/#{tag_name}", opts
          end

          # Remove the colour for a tag
          #
          # TODO: Add parameters documentation
          def delete_tag_colour(project_id, tag_name)
            delete "/commandcenter/projects/#{project_id}/tagColours/#{tag_name}"
          end
        end
      end
    end
  end
end


text:
package org.swing.on.steroids.wizard.swing.components;

import java.awt.Color;
import java.awt.Component;
import javax.swing.BorderFactory;
import javax.swing.JPanel;

import net.miginfocom.layout.AC;
import net.miginfocom.layout.CC;
import net.miginfocom.layout.LC;
import net.miginfocom.swing.MigLayout;

/**
 * @author Paul Merlin
 */
public class SwingWizardPagesStackPanel
        extends JPanel
{

    private static final long serialVersionUID = 1L;
    private Component currentPageComponent;

    public SwingWizardPagesStackPanel()
    {
        super( new MigLayout( new LC().fill(),
                              new AC(),
                              new AC() ) );
        setBorder( BorderFactory.createLineBorder( Color.white ) );
    }

    public void setPageComponent( Component pageComponent )
    {
        if ( currentPageComponent != null ) {
            remove( currentPageComponent );
        }
        add( pageComponent, new CC().grow() );
        validate();
        repaint();
        currentPageComponent = pageComponent;
    }

}


text:
package org.leguan.versioncontrol;

public abstract class DefaultControlAdapter implements VersionControlAdapter {

  @Override
  public String toString () {
    return getClass().getName();
  }
}


text:
<?php

namespace AnyContent\CMCK\Modules\Backend\Core\Files;

use AnyContent\CMCK\Modules\Backend\Core\Application\Application;

class Module extends \AnyContent\CMCK\Modules\Backend\Core\Core\Module
{

    public function init(Application $app, $options = array())
    {

        parent::init($app, $options);

        $app->addTemplatesFolders(__DIR__ . '/views/');

        $app->get('/files/{repositoryAccessHash}/{path}', 'AnyContent\CMCK\Modules\Backend\Core\Files\Controller::listFiles')
            ->assert('path', '.*')->bind('listFiles');

        $app->get('/file/{repositoryAccessHash}/view/{id}', 'AnyContent\CMCK\Modules\Backend\Core\Files\Controller::viewFile')
            ->assert('id', '.*')->bind('viewFile');

        $app
            ->get('/file/{repositoryAccessHash}/download/{id}', 'AnyContent\CMCK\Modules\Backend\Core\Files\Controller::downloadFile')
            ->assert('id', '.*')->bind('downloadFile');

        $app
            ->get('/file/{repositoryAccessHash}/delete/{id}', 'AnyContent\CMCK\Modules\Backend\Core\Files\Controller::deleteFile')
            ->assert('id', '.*')->bind('deleteFile');

        $app->post('/files/{repositoryAccessHash}/{path}', 'AnyContent\CMCK\Modules\Backend\Core\Files\Controller::post')
            ->assert('path', '.*')->value('mode','page');

        // routes for file selection (as used in file form elements)

        $app->get('/file-select/{repositoryAccessHash}/{path}', 'AnyContent\CMCK\Modules\Backend\Core\Files\Controller::listFiles')
            ->assert('path', '.*')->value('mode','modal')->bind('listFilesSelect');

        $app->post('/file-select/{repositoryAccessHash}/{path}', 'AnyContent\CMCK\Modules\Backend\Core\Files\Controller::post')
            ->assert('path', '.*')->value('mode','modal')->value('mode','modal');

    }

}


text:
from dataflows import Flow, filter_rows
from datapackage_pipelines.wrapper import ingest
from datapackage_pipelines.utilities.flow_utils import spew_flow

def flow(parameters):
    return Flow(
        filter_rows(
            equals=parameters.get('in', []),
            not_equals=parameters.get('out', []),
            resources=parameters.get('resources'),
        )
    )

if __name__ == '__main__':
    with ingest() as ctx:
        spew_flow(flow(ctx.parameters), ctx)


text:
copyright:
  years: 2016,2017
lastupdated: "2017-04-27"
---

{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:codeblock: .codeblock}
{:pre: .pre}

# Guía de inicio con Compose for Elasticsearch
{: #getting-started-with-compose-for-elasticsearch}

{{site.data.keyword.composeForElasticsearch_full}} combina la potencia de un motor de búsqueda de texto completo con la fuerza de indexación de una base de datos de documentos JSON. Juntos, crean una herramienta potente para el análisis de datos enriquecidos en grandes volúmenes de datos. Con Elasticsearch, su búsqueda se puede puntuar para su exactitud, permitiéndole indagar en el conjunto de datos para las coincidencias casi exactas que no puede conseguir.
{:shortdesc}

**Nota:** Cualquier instancia de servicio de Compose proporcionada antes del 14 de septiembre de 2016 que siga activa se puede seguir utilizando y se puede acceder a ella directamente en [https://www.compose.com/](https://www.compose.com). Se puede acceder directamente a cualquier instancia de servicio de Compose que se proporcione desde este momento en adelante y se utilizará dentro de la cuenta de Bluemix.

Siga estos pasos para iniciarse a {{site.data.keyword.composeForElasticsearch}}:

1. [Cree una instancia de {{site.data.keyword.composeForElasticsearch}}](https://console.ng.bluemix.net/catalog/services/compose-for-elasticsearch/).

  Al crear una instancia del servicio, asegúrese de que elige un nombre para el servicio y un nombre de credencial. Deje el servicio desenlazado; puede conectar una aplicación al servicio más adelante utilizando las credenciales proporcionadas cuando se proporcione el servicio. Los distintos valores de credenciales se listan en la sección *Credenciales disponibles*.

2. Conéctese al servicio de {{site.data.keyword.composeForElasticsearch}}.

  Para conectar una app al servicio, utilice las [credenciales](./credentials.html) creadas junto con el servicio. La app de ejemplo muestra cómo utilizar Node.js para conectar a un servicio de {{site.data.keyword.composeForElasticsearch}}.

  Descargue la app de ejemplo [compose-elasticsearch-helloworld-nodejs](https://github.com/IBM-Bluemix/compose-elasticsearch-helloworld-nodejs) y siga las instrucciones del archivo readme. A continuación, en la página de detalles de la aplicación en Bluemix, pulse **Ver APP** para ver el contenido del índice de *ejemplos*.


text:
#pragma
#ifndef MYLIB
#define MYLIB

#include <GL/glut.h>
#include <cmath>
#include<iostream>
#include<vector>
#include"Vertex.h"

namespace gnr{
//START OF gnr NAMESPACE

class MyLib
{
public:
	MyLib();
	~MyLib();

	/* v1 and v2 are parameters and vr is a return value as a result*/
	static void crossProduct(GLfloat v1[3],GLfloat v2[3],GLfloat vr[3]);

	static void normalizeCalculation(GLfloat polygon[][3],GLfloat *normal,GLint *face);

	static void normalizeCalculation3d(GLfloat polygon[][3], GLfloat normal[][3], GLint face[][4],GLint faceSize);

};

//END_OF ml NAMESPACE
}
#endif


text:
from tests.infrastructure.test_utils import parse_local, normalize_id
from tests.parser.test_method_call_parsing import validate_method_call
from thinglang.lexer.values.identifier import Identifier
from thinglang.lexer.values.numeric import NumericValue
from thinglang.parser.values.indexed_access import IndexedAccess
from thinglang.parser.values.inline_list import InlineList
from thinglang.parser.values.method_call import MethodCall
from thinglang.parser.values.named_access import NamedAccess

def validate_indexed_access(node, target, index):
    assert isinstance(node, IndexedAccess)
    assert node.target == normalize_id(target)
    assert node.index == normalize_id(index)

def validate_access(node, target):
    assert isinstance(node, NamedAccess)
    assert node.target == normalize_id(target)

def test_simple_access():
    validate_access(parse_local('a.b'), ['a', 'b'])

def test_chained_access():
    validate_access(parse_local('a.b.c.d'), ['a', 'b', 'c', 'd'])

def test_local_index_access():
    validate_indexed_access(parse_local('a[0]'), 'a', NumericValue(0))

def test_member_index_access():
    validate_indexed_access(parse_local('person.hobbies[idx]'),
                            NamedAccess([Identifier('person'), Identifier('hobbies')]),
                            'idx')

def test_chained_index_access():
    validate_indexed_access(parse_local('person.hobbies[idx]'),
                            NamedAccess([Identifier('person'), Identifier('hobbies')]),
                            'idx')

    validate_indexed_access(parse_local('game.map[x][y]'),
                            IndexedAccess(NamedAccess([Identifier('game'), Identifier('map')]), Identifier('x')),
                            'y')

def test_complex_mixed_access():

    node = parse_local('person.hobbies.all[selection.index].effects[selection.effect()]')

    assert isinstance(node, IndexedAccess)
    assert isinstance(node.target, NamedAccess)

    validate_method_call(node.index, ['selection', 'effect'], [])
    assert node.target == NamedAccess([
        IndexedAccess(
            NamedAccess([Identifier('person'), Identifier('hobbies'), Identifier('all')]),
            NamedAccess([Identifier('selection'), Identifier('index')])),
        Identifier('effects')
        ])

    node = parse_local('person.hobbies.generate()[selection.index].effects[selection.effect()]')

    assert isinstance(node, IndexedAccess)
    assert isinstance(node.target, NamedAccess)

    validate_method_call(node.index, ['selection', 'effect'], [])
    assert node.target == NamedAccess([
        IndexedAccess(
            MethodCall(NamedAccess([Identifier('person'), Identifier('hobbies'), Identifier('generate')])),
            NamedAccess([Identifier('selection'), Identifier('index')])),
        Identifier('effects')
    ])

def test_complex_mixed_access_ambiguity():
    node = parse_local('person.hobbies.generate(123, [selection.index].effects[selection.effect()])')

    assert isinstance(node, MethodCall)
    assert node.target == NamedAccess([Identifier('person'), Identifier('hobbies'), Identifier('generate')])
    assert len(node.arguments) == 2
    assert node.arguments[0] == NumericValue(123)
    assert node.arguments[1] == IndexedAccess(
        NamedAccess([
            InlineList(NamedAccess([Identifier('selection'), Identifier('index')])),
            Identifier('effects')]),
        MethodCall(NamedAccess([Identifier('selection'), Identifier('effect')]))
    )


text:
![Icon](https://raw.github.com/TrekkingForCharity/divulge/master/Icons/package_icon.png)

A Fody library that makes private setters public

[Introduction to Fody](http://github.com/Fody/Fody/wiki/SampleUsage)

## The nuget package  [![NuGet](https://img.shields.io/nuget/v/Divulge.Fody.svg)](https://www.nuget.org/packages/Divulge.Fody/)

https://nuget.org/packages/Divulge.Fody/

    PM> Install-Package Divulge.Fody

Converts private setters public.

## The myget feed  [![t4c MyGet Build Status](https://www.myget.org/BuildSource/Badge/t4c?identifier=44df3025-5e13-41b1-aa76-df9acc6b530f)](https://www.myget.org/) [![MyGet](https://img.shields.io/myget/t4c/v/Divulge.Fody.svg)](https://www.myget.org/feed/t4c/package/nuget/Divulge.Fody)

https://www.myget.org/feed/t4c/package/nuget/Divulge.Fody


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Melaleuca minutifolia subsp. monantha

### Remarks
null


text:
"""This is the GCI Views module.
"""


text:
using Newtonsoft.Json;

namespace NPushover.ResponseObjects
{
    /// <summary>
    /// Represents information about a user which is part of the response from a <see cref="ListMessagesResponse"/> from
    /// a <see cref="M:NPushover.Pushover.ListMessagesAsync(System.String,System.String)"/> call.
    /// </summary>
    /// <remarks>
    /// This part of the response is undocumented by Pushover.
    /// </remarks>
    public class ListMessagesUser
    {
        /// <summary>
        /// Indicates if the user is, currently(?), in quiet hours.
        /// </summary>
        [JsonProperty("quiet_hours")]
        public bool QuietHours { get; set; }

        /// <summary>
        /// Indicates if the user has a license for Android devices.
        /// </summary>
        [JsonProperty("is_android_licensed")]
        public bool IsAndroidLicensed { get; set; }

        /// <summary>
        /// Indicates if the user has a license for iOS devices.
        /// </summary>
        [JsonProperty("is_ios_licensed")]
        public bool IsIosLicensed { get; set; }

        /// <summary>
        /// Indicates if the user has a license for desktop application.
        /// </summary>
        [JsonProperty("is_desktop_licensed")]
        public bool IsDesktopLicensed { get; set; }
    }
}


text:
package org.zstack.sdk;

public class IpStatisticData  {

    public java.lang.String ip;
    public void setIp(java.lang.String ip) {
        this.ip = ip;
    }
    public java.lang.String getIp() {
        return this.ip;
    }

    public java.lang.String vipUuid;
    public void setVipUuid(java.lang.String vipUuid) {
        this.vipUuid = vipUuid;
    }
    public java.lang.String getVipUuid() {
        return this.vipUuid;
    }

    public java.lang.String vipName;
    public void setVipName(java.lang.String vipName) {
        this.vipName = vipName;
    }
    public java.lang.String getVipName() {
        return this.vipName;
    }

    public java.lang.String vmInstanceUuid;
    public void setVmInstanceUuid(java.lang.String vmInstanceUuid) {
        this.vmInstanceUuid = vmInstanceUuid;
    }
    public java.lang.String getVmInstanceUuid() {
        return this.vmInstanceUuid;
    }

    public java.lang.String vmInstanceName;
    public void setVmInstanceName(java.lang.String vmInstanceName) {
        this.vmInstanceName = vmInstanceName;
    }
    public java.lang.String getVmInstanceName() {
        return this.vmInstanceName;
    }

    public java.lang.String vmInstanceType;
    public void setVmInstanceType(java.lang.String vmInstanceType) {
        this.vmInstanceType = vmInstanceType;
    }
    public java.lang.String getVmInstanceType() {
        return this.vmInstanceType;
    }

    public java.util.List vmDefaultIp;
    public void setVmDefaultIp(java.util.List vmDefaultIp) {
        this.vmDefaultIp = vmDefaultIp;
    }
    public java.util.List getVmDefaultIp() {
        return this.vmDefaultIp;
    }

    public java.util.List resourceTypes;
    public void setResourceTypes(java.util.List resourceTypes) {
        this.resourceTypes = resourceTypes;
    }
    public java.util.List getResourceTypes() {
        return this.resourceTypes;
    }

    public java.lang.String state;
    public void setState(java.lang.String state) {
        this.state = state;
    }
    public java.lang.String getState() {
        return this.state;
    }

    public java.lang.String useFor;
    public void setUseFor(java.lang.String useFor) {
        this.useFor = useFor;
    }
    public java.lang.String getUseFor() {
        return this.useFor;
    }

    public java.sql.Timestamp createDate;
    public void setCreateDate(java.sql.Timestamp createDate) {
        this.createDate = createDate;
    }
    public java.sql.Timestamp getCreateDate() {
        return this.createDate;
    }

    public java.lang.String ownerName;
    public void setOwnerName(java.lang.String ownerName) {
        this.ownerName = ownerName;
    }
    public java.lang.String getOwnerName() {
        return this.ownerName;
    }

}


text:
[![Build Status](https://travis-ci.org/stefankoegel/clickyEvaluation.svg?branch=master)](https://travis-ci.org/stefankoegel/clickyEvaluation)

## Description

*Clicky Evaluation* parses simple *Haskell-like* expressions and function
definitions and renders them as HTML.
The user can then choose which subexpressions to evaluate for one step by
clicking on them.
This is intended as a simple learning tool for beginners,
which shows them how their Haskell code **might** be evaluated.

You can try it [here](http://stefankoegel.github.io/clickyEvaluation/).

The projects name is a play on *lazy evaluation* and *clicking* to evaluate an expression.

## Supported Features

* Bool
* Char
* Int
* String
* List
* Tupel
* Arithmetic operators `[(+), (-), (*), ('div'), ('mod'), (^)]`
* Comparsion operators `[(==), (/=), (<=), (<), (>), (>=)]`
* Boolean operators `[(&&), (||), (not)]`
* Other operators `[($), (.), (:), (++)]`
* Infix to prefix conversion `a + b <=> (+) a b`
* Pattern matching on atoms (numbers, ...), lists and tuples
* Anonymous functions (lambdas)
* Sections `(^2) 4 => 4^2 => 16`
* Most of the simple Prelude functions on lists `head, map, foldr, scanr, filter, all, ...`
* Types for Bool, Char, Int, List, Tupel and Prelude functions
* Type inference for user defined functions and expressions
* ADTs
* Listcomprehensions

## Missing Features

* Guards
* `case`, `where`, `let`
* Multi-line expressions, significant whitespace
* Floating point numbers
* Comments
* Type classes

## Building

Install `npm` and `purescript` (at least 0.8.0).
You can get `purescript` via `cabal install purescript` or `npm install purescript`.
Then run:
```
npm install
npm run build
```
For the unit tests you can also run:
```
npm run test
```

After a successful build use:

```
<your_browser> html/index.html
```

## Hosting

You can build and host a specific version of ClickyEvaluation yourself by providing the following files on your webserver:
* index.html
* source.css
* Main.js (generated with `npm run test` or `pulp build --to Main.js`)

Or you can link to the most recent version [here](http://stefankoegel.github.io/clickyEvaluation/).


text:
"use strict";

var tabIcon = require("./tabIcon.js");
module.exports = function tabBar(tabs) {
	var currectCard;
	var tabsEl = $("

");
	function insertCard(c) {
		if (currectCard) {
			c.insertAfter(currectCard);
			currectCard.remove();
		}
		currectCard = c;
		return c;
	}
	function addTab (t, i) {
		var tab = tabIcon()
			.text(t.text)
			.css("background-image", "url(\"images/"+t.image+".png\")")
			.click(function () {
				insertCard(t.card);
				tabsEl.find(".tab-icon").removeClass("selected");
				tab.addClass("selected");
			});
		if (i === 0) {
			tab.addClass("selected");
		}
		tabsEl.prepend(tab);
	}
	for (var i = tabs.length - 1; i >= 0; i--) {
		addTab(tabs[i], i);
	}
	return [tabsEl, insertCard(tabs[0].card)];
};


text:
Placeholder component used to render content of any component, using the scope data.
If content value is string, it will be rendered as paragraph. If value is an array it will parhe it and for each string render a separate paragraph.

If value is an object (either as value or within array) it will look for key **component*** and call that partial wiyh its remaining data, for instance {"component": "heading", "text": "My string content"}.

If