text:
<?php

namespace Genj\SocialFeedBundle\Api;

use Genj\SocialFeedBundle\Entity\Post;
use Facebook\FacebookSession;
use Facebook\Entities\AccessToken;
use Facebook\FacebookRequest;

/**
 * Class FacebookApi
 *
 * @package Genj\SocialFeedBundle\Api
 */
class FacebookApi extends SocialApi
{
    protected $providerName = 'facebook';

    /**
     * @param array $oAuthConfig
     */
    public function __construct($oAuthConfig)
    {
        FacebookSession::setDefaultApplication($oAuthConfig['facebook']['app_id'], $oAuthConfig['facebook']['app_secret']);

        $accessToken = AccessToken::requestAccessToken(array('grant_type' => 'client_credentials'));
        $this->api = new FacebookSession($accessToken);
    }

    /**
     * @param string $username
     *
     * @return array
     */
    public function getUserPosts($username)
    {
        try {
            $parameters = array('fields' => 'message,link,from,full_picture,created_time,object_id');
            $data = $this->requestGet('/'. $username .'/posts', $parameters);

        } catch (\Exception $ex) {
            echo $ex->getMessage();

            return array();
        }

        return $data->asArray()['data'];
    }

    /**
     * @param \stdClass|array $socialPost
     *
     * @return Post
     */
    protected function getMappedPostObject($socialPost)
    {
        $post = new Post();

        if (!isset($socialPost->message)) {
            return false;
        }

        $post->setProvider($this->providerName);
        $post->setPostId($socialPost->id);

        $parameters = array('fields' => 'username');
        $rawUserDetails = $this->requestGet("/". $socialPost->from->id, $parameters);

        $userDetails = $rawUserDetails->asArray();

        if (empty($userDetails)) {
            return false;
        }

        $post->setAuthorUsername($userDetails['username']);
        $post->setAuthorName($socialPost->from->name);
        $post->setAuthorFile('https://graph.facebook.com/'. $socialPost->from->id .'/picture');
        $post->setHeadline(strip_tags($socialPost->message));

        $message = $this->getFormattedTextFromPost($socialPost);
        $post->setBody($message);

        if (isset($socialPost->full_picture) && !empty($socialPost->full_picture)) {
            // A picture is set, use the original url as a backup
            $post->setFile($socialPost->full_picture);

            // If there is an object_id, then the original file may be available, so check for that one
            if (isset($socialPost->object_id)) {
                $rawImageDetails = $this->requestGet("/". $socialPost->object_id, array('fields' => 'images'));
                $imageDetails = $rawImageDetails->asArray();

                if (isset($imageDetails['images'][0]->source)) {
                    $post->setFile($imageDetails['images'][0]->source);
                }
            } else {
                // Check if it is an external image, if so, use the original one.
                $pictureUrlData = parse_url($socialPost->full_picture);
                if (preg_match('#^fbexternal#', $pictureUrlData['host']) === 1) {
                    parse_str($pictureUrlData['query'], $pictureUrlQueryData);
                    if (isset($pictureUrlQueryData['url'])) {
                        $post->setFile($pictureUrlQueryData['url']);
                    }
                }
            }
        }

        $post->setLink('https://www.facebook.com/'. $socialPost->id);

        $post->setPublishAt(new \DateTime($socialPost->created_time));
        $post->setIsActive(true);

        return $post;
    }

    protected function getFormattedTextFromPost($socialPost)
    {
        $text = $socialPost->message;

        // Add href for links prefixed with ***:// (*** is most likely to be http(s) or ftp
        $text = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1\\2", $text);
        // Add href for links starting with www or ftp
        $text = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1\\2", $text);
        // Add link to hashtags
        $text = preg_replace("/#(\w+)/", "#\\1", $text);

        return $text;
    }

    protected function requestGet($method, $parameters = array())
    {
        try {
            $response = (new FacebookRequest($this->api, 'GET', $method, $parameters, 'v2.4'))->execute();

            return $response->getGraphObject();
        } catch (\Exception $ex) {
            throw $ex;
        }
    }

}


text:
import java.util.Random;

import main.java.Dice;

public final class Main {

	public static void main(String[] args) {
		Dice dice = new Dice(1, new Random());
		System.out.println("Number of eyes rolled: " + dice.roll());
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Zend\Ldap\Filter;

/**
 * Zend\Ldap\Filter\MaskFilter provides a simple string filter to be used with a mask.
 */
class MaskFilter extends StringFilter {
	/**
	 * Creates a Zend\Ldap\Filter\MaskFilter.
	 *
	 * @param string $mask
	 * @param string $value,...
	 */
	public function __construct($mask, $value) {
		$args = func_get_args ();
		array_shift ( $args );
		for($i = 0; $i < count ( $args ); $i ++) {
			$args [$i] = static::escapeValue ( $args [$i] );
		}
		$filter = vsprintf ( $mask, $args );
		parent::__construct ( $filter );
	}

	/**
	 * Returns a string representation of the filter.
	 *
	 * @return string
	 */
	public function toString() {
		return $this->filter;
	}
}


text:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="css/main.css"/>
    <meta charset="utf-8">
    <meta name="description" content="sqlite file viewer">
    <meta name="keywords" content="sqlite,viewer,db,database,online">
    <meta name="author" content="Juraj Novák">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SQLite Viewer</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/select2.css" rel="stylesheet">
    <link href="css/select2-bootstrap.css" rel="stylesheet">
    <link href="css/main.css" rel="stylesheet">
    <link href="css/ribbons.min.css" rel="stylesheet">
    <link rel="image_src" href="img/icon.png"/>

SQLite Viewer

view sqlite file online

Sorry but your browser does not support some of new HTML5 features! Try using latest version of Google Chrome or
                Firefox.

            Drop file here to load content or click on this box to open file dialog.

No file will be uploaded - uses only JavaScript HTML5 FileReader.

             Processing file ...

                <select id="tables" class="form-control select2" title="Table"></select>

                <button class="btn btn-sm btn-primary" id="sql-run" type="submit" onclick="executeSql(this)">Execute</button>

        <button class="btn btn-default btn-sm " id="page-prev" type="submit" onclick="setPage(this, false)"></button>

        <button class="btn btn-default btn-sm " id="page-next" type="submit" onclick="setPage(this, true)"></button>

        © 2015, Juraj Novák, inloop.eu

        | other projects |

<input type="file" id="dropzone-dialog" style="opacity: 0;display:none">

    Fork me on GitHub


text:
A quick start seed for a web application using io.js

## Server stack
* io.js
* hapi
* handlebars
* mongoose

## Client stack
* HTML5
* jQuery
* bootstrap

## Workshop

### Introduction to technology stack
* Have a complete application using the full stack
* Comment out several parts to make it just a seed
* Comment back in and explain what it does to application

### Installation
* Install io.js
* Fork this project on github and clone it
* Install Mongo
  * Start Mongo: mongod --config /usr/local/etc/mongod.conf
  * Optionally use a hosted mongo version (e.g. mongolab who have a free plan)
* npm install
* npm start
* use IDE/editor of your choice (use WebStorm or Atom, if you just do not know what to use)

### Assignment
* Install the sample application and make it run
* Choose one technology that was introduced today and play with it
* OR
* Create a vision of your own project based on what you have learned


text:
package com.google.javascript.jscomp.newtypes;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.jscomp.CodingConvention;
import com.google.javascript.jscomp.DiagnosticType;
import com.google.javascript.jscomp.JSError;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *
 * @author blickly@google.com (Ben Lickly)
 * @author dimvar@google.com (Dimitris Vardoulakis)
 */
public final class JSTypeCreatorFromJSDoc {
  public static final DiagnosticType INVALID_GENERICS_INSTANTIATION =
      DiagnosticType.warning(
        "JSC_INVALID_GENERICS_INSTANTIATION",
        "Invalid generics instantiation for {0}.\n"
        + "Expected {1} type argument(s), but found {2}.");

  public static final DiagnosticType BAD_JSDOC_ANNOTATION =
      DiagnosticType.warning(
        "JSC_BAD_JSDOC_ANNOTATION",
        "Bad JSDoc annotation. {0}");

  public static final DiagnosticType EXTENDS_NON_OBJECT =
      DiagnosticType.warning(
          "JSC_EXTENDS_NON_OBJECT",
          "{0} extends non-object type {1}.\n");

  public static final DiagnosticType EXTENDS_NOT_ON_CTOR_OR_INTERF =
      DiagnosticType.warning(
          "JSC_EXTENDS_NOT_ON_CTOR_OR_INTERF",
          "@extends used without @constructor or @interface for {0}.\n");

  public static final DiagnosticType INHERITANCE_CYCLE =
      DiagnosticType.warning(
          "JSC_INHERITANCE_CYCLE",
          "Cycle detected in inheritance chain of type {0}");

  public static final DiagnosticType DICT_IMPLEMENTS_INTERF =
      DiagnosticType.warning(
          "JSC_DICT_IMPLEMENTS_INTERF",
          "Class {0} is a dict. Dicts can't implement interfaces.");

  public static final DiagnosticType IMPLEMENTS_WITHOUT_CONSTRUCTOR =
      DiagnosticType.warning(
          "JSC_IMPLEMENTS_WITHOUT_CONSTRUCTOR",
          "@implements used without @constructor or @interface for {0}");

  public static final DiagnosticType CONFLICTING_SHAPE_TYPE =
      DiagnosticType.disabled(
          "JSC_CONFLICTING_SHAPE_TYPE",
          "{1} cannot extend this type; {0}s can only extend {0}s");

  public static final DiagnosticType CONFLICTING_EXTENDED_TYPE =
      DiagnosticType.warning(
          "JSC_CONFLICTING_EXTENDED_TYPE",
          "{1} cannot extend this type; {0}s can only extend {0}s");

  public static final DiagnosticType CONFLICTING_IMPLEMENTED_TYPE =
    DiagnosticType.warning(
        "JSC_CONFLICTING_IMPLEMENTED_TYPE",
        "{0} cannot implement this type; "
        + "an interface can only extend, but not implement interfaces");

  public static final DiagnosticType UNION_IS_UNINHABITABLE =
    DiagnosticType.warning(
        "JSC_UNION_IS_UNINHABITABLE",
        "Union of {0} with {1} would create an impossible type.");

  private final CodingConvention convention;

  // Used to communicate state between methods when resolving enum types
  private int howmanyTypeVars = 0;

  /** Exception for when unrecognized type names are encountered */
  public static class UnknownTypeException extends Exception {
    UnknownTypeException(String cause) {
      super(cause);
    }
  }

  private Set<JSError> warnings = new LinkedHashSet<>();
  // Unknown type names indexed by JSDoc AST node at which they were found.
  private Map<Node, String> unknownTypeNames = new LinkedHashMap<>();

  public JSTypeCreatorFromJSDoc(CodingConvention convention) {
    this.qmarkFunctionDeclared = new FunctionAndSlotType(
        null, FunctionTypeBuilder.qmarkFunctionBuilder().buildDeclaration());
    this.convention = convention;
  }

  private FunctionAndSlotType qmarkFunctionDeclared;
  private static final boolean NULLABLE_TYPES_BY_DEFAULT = true;

  public JSType maybeMakeNullable(JSType t) {
    if (NULLABLE_TYPES_BY_DEFAULT) {
      return JSType.join(JSType.NULL, t);
    }
    return t;
  }

  public JSType getDeclaredTypeOfNode(JSDocInfo jsdoc, RawNominalType ownerType,
      DeclaredTypeRegistry registry) {
    return getDeclaredTypeOfNode(jsdoc, registry, ownerType == null
        ? ImmutableList.<String>of() : ownerType.getTypeParameters());
  }

  private JSType getDeclaredTypeOfNode(JSDocInfo jsdoc,
      DeclaredTypeRegistry registry, ImmutableList<String> typeParameters) {
    if (jsdoc == null) {
      return null;
    }
    return getTypeFromJSTypeExpression(
        jsdoc.getType(), registry, typeParameters);
  }

  public Set<JSError> getWarnings() {
    return warnings;
  }

  public Map<Node, String> getUnknownTypesMap() {
    return unknownTypeNames;
  }

  private JSType getTypeFromJSTypeExpression(JSTypeExpression expr,
      DeclaredTypeRegistry registry, ImmutableList<String> typeParameters) {
    if (expr == null) {
      return null;
    }
    return getTypeFromComment(expr.getRoot(), registry, typeParameters);
  }

  // Very similar to JSTypeRegistry#createFromTypeNodesInternal
  // n is a jsdoc node, not an AST node; the same class (Node) is used for both
  private JSType getTypeFromComment(Node n, DeclaredTypeRegistry registry,
      ImmutableList<String> typeParameters) {
    try {
      return getTypeFromCommentHelper(n, registry, typeParameters);
    } catch (UnknownTypeException e) {
      return JSType.UNKNOWN;
    }
  }

  private JSType getMaybeTypeFromComment(Node n, DeclaredTypeRegistry registry,
      ImmutableList<String> typeParameters) {
    try {
      return getTypeFromCommentHelper(n, registry, typeParameters);
    } catch (UnknownTypeException e) {
      return null;
    }
  }

  private JSType getTypeFromCommentHelper(Node n, DeclaredTypeRegistry registry,
      ImmutableList<String> typeParameters) throws UnknownTypeException {
    Preconditions.checkNotNull(n);
    if (typeParameters == null) {
      typeParameters = ImmutableList.of();
    }
    switch (n.getType()) {
      case Token.LC:
        return getRecordTypeHelper(n, registry, typeParameters);
      case Token.EMPTY: // for function types that don't declare a return type
        return JSType.UNKNOWN;
      case Token.VOID:
        return JSType.UNDEFINED;
      case Token.LB:
        warn("The [] type syntax is no longer supported." +
             " Please use Array.<T> instead.", n);
        return JSType.UNKNOWN;
      case Token.STRING:
        return getNamedTypeHelper(n, registry, typeParameters);
      case Token.PIPE: {
        // The way JSType.join works, Subtype|Supertype is equal to Supertype,
        // so when programmers write un-normalized unions, we normalize them
        // silently. We may also want to warn.
        JSType union = JSType.BOTTOM;
        for (Node child = n.getFirstChild(); child != null;
             child = child.getNext()) {
          // TODO(dimvar): When the union has many things, we join and throw
          // away types, except the result of the last join. Very inefficient.
          // Consider optimizing.
          JSType nextType =
              getTypeFromCommentHelper(child, registry, typeParameters);
          if (nextType.isUnknown()) {
            warn("This union type is equivalent to '?'.", n);
            return JSType.UNKNOWN;
          }
          JSType nextUnion = JSType.join(union, nextType);
          if (nextUnion.isBottom()) {
            warnings.add(JSError.make(n, UNION_IS_UNINHABITABLE,
                    nextType.toString(), union.toString()));
            return JSType.UNKNOWN;
          }
          union = nextUnion;
        }
        return union;
      }
      case Token.BANG: {
        JSType nullableType = getTypeFromCommentHelper(
            n.getFirstChild(), registry, typeParameters);
        if (nullableType.isTypeVariable()) {
          warn("Cannot use ! to restrict type variable type.\n"
              + "Prefer to make type argument non-nullable and add "
              + "null explicitly where needed (e.g. through ?T or T|null)", n);
        }
        return nullableType.removeType(JSType.NULL);
      }
      case Token.QMARK: {
        Node child = n.getFirstChild();
        if (child == null) {
          return JSType.UNKNOWN;
        } else {
          return JSType.join(JSType.NULL,
              getTypeFromCommentHelper(child, registry, typeParameters));
        }
      }
      case Token.STAR:
        return JSType.TOP;
      case Token.FUNCTION:
        return getFunTypeHelper(n, registry, typeParameters);
      default:
        throw new IllegalArgumentException("Unsupported type exp: " +
            Token.name(n.getType()) + " " + n.toStringTree());
    }
  }

  private JSType getRecordTypeHelper(Node n, DeclaredTypeRegistry registry,
      ImmutableList<String> typeParameters)
      throws UnknownTypeException {
    Map<String, Property> props = new LinkedHashMap<>();
    for (Node propNode = n.getFirstChild().getFirstChild();
         propNode != null;
         propNode = propNode.getNext()) {
      boolean isPropDeclared = propNode.getType() == Token.COLON;
      Node propNameNode = isPropDeclared ? propNode.getFirstChild() : propNode;
      String propName = propNameNode.getString();
      if (propName.startsWith("'") || propName.startsWith("\"")) {
        propName = propName.substring(1, propName.length() - 1);
      }
      JSType propType = !isPropDeclared
          ? JSType.UNKNOWN
          : getTypeFromCommentHelper(propNode.getLastChild(), registry, typeParameters);
      Property prop;
      if (!propType.isUnknown() && !propType.isTop()
          && JSType.UNDEFINED.isSubtypeOf(propType)) {
        prop = Property.makeOptional(null, propType, propType);
      } else {
        prop = Property.make(propType, propType);
      }
      props.put(propName, prop);
    }
    return JSType.fromObjectType(ObjectType.fromProperties(props));
  }

  private JSType getNamedTypeHelper(Node n, DeclaredTypeRegistry registry,
      ImmutableList<String> outerTypeParameters)
      throws UnknownTypeException {
    String typeName = n.getString();
    switch (typeName) {
      case "boolean":
        return JSType.BOOLEAN;
      case "null":
        return JSType.NULL;
      case "number":
        return JSType.NUMBER;
      case "string":
        return JSType.STRING;
      case "undefined":
      case "void":
        return JSType.UNDEFINED;
      case "Function":
        return maybeMakeNullable(registry.getCommonTypes().qmarkFunction());
      case "Object":
        // We don't generally handle parameterized Object<...>, but we want to
        // at least not warn about inexistent properties on it, so we type it
        // as @dict.
        return maybeMakeNullable(n.hasChildren() ? JSType.TOP_DICT : JSType.TOP_OBJECT);
      default:
        return lookupTypeByName(typeName, n, registry, outerTypeParameters);
    }
  }

  private JSType lookupTypeByName(String name,
      Node n, DeclaredTypeRegistry registry, ImmutableList<String> outerTypeParameters)
      throws UnknownTypeException {
    if (outerTypeParameters.contains(name)) {
      return JSType.fromTypeVar(name);
    }
    Declaration decl = registry.getDeclaration(QualifiedName.fromQualifiedString(name), true);
    if (decl == null) {
      unknownTypeNames.put(n, name);
      throw new UnknownTypeException("Unhandled type: " + name);
    }
    // It's either a typedef, an enum, a type variable or a nominal type
    if (decl.getTypedef() != null) {
      return getTypedefType(decl.getTypedef(), registry);
    }
    if (decl.getEnum() != null) {
      return getEnumPropType(decl.getEnum(), registry);
    }
    if (decl.isTypeVar()) {
      howmanyTypeVars++;
      return decl.getTypeOfSimpleDecl();
    }
    if (decl.getNominal() != null) {
      return getNominalTypeHelper(decl.getNominal(), n, registry, outerTypeParameters);
    }
    return JSType.UNKNOWN;
  }

  private JSType getTypedefType(Typedef td, DeclaredTypeRegistry registry) {
    resolveTypedef(td, registry);
    return td.getType();
  }

  public void resolveTypedef(Typedef td, DeclaredTypeRegistry registry) {
    Preconditions.checkState(td != null, "getTypedef should only be " +
        "called when we know that the typedef is defined");
    if (td.isResolved()) {
      return;
    }
    JSTypeExpression texp = td.getTypeExpr();
    JSType tdType;
    if (texp == null) {
      warn("Circular type definitions are not allowed.",
          td.getTypeExprForErrorReporting().getRoot());
      tdType = JSType.UNKNOWN;
    } else {
      tdType = getTypeFromJSTypeExpression(texp, registry, null);
    }
    td.resolveTypedef(tdType);
  }

  private JSType getEnumPropType(EnumType e, DeclaredTypeRegistry registry) {
    resolveEnum(e, registry);
    return e.getPropType();
  }

  public void resolveEnum(EnumType e, DeclaredTypeRegistry registry) {
    Preconditions.checkState(e != null, "getEnum should only be " +
        "called when we know that the enum is defined");
    if (e.isResolved()) {
      return;
    }
    JSTypeExpression texp = e.getTypeExpr();
    JSType enumeratedType;
    if (texp == null) {
      warn("Circular type definitions are not allowed.",
          e.getTypeExprForErrorReporting().getRoot());
      enumeratedType = JSType.UNKNOWN;
    } else {
      int numTypeVars = howmanyTypeVars;
      enumeratedType = getTypeFromJSTypeExpression(texp, registry, null);
      if (howmanyTypeVars > numTypeVars) {
        warn("An enum type cannot include type variables.", texp.getRoot());
        enumeratedType = JSType.UNKNOWN;
        howmanyTypeVars = numTypeVars;
      } else if (enumeratedType.isTop()) {
        warn("An enum type cannot be *. " +
            "Use ? if you do not want the elements checked.",
            texp.getRoot());
        enumeratedType = JSType.UNKNOWN;
      } else if (enumeratedType.isUnion()) {
        warn("An enum type cannot be a union type.", texp.getRoot());
        enumeratedType = JSType.UNKNOWN;
      }
    }
    e.resolveEnum(enumeratedType);
  }

  private JSType getNominalTypeHelper(RawNominalType rawType, Node n,
      DeclaredTypeRegistry registry, ImmutableList<String> outerTypeParameters)
      throws UnknownTypeException {
    NominalType uninstantiated = rawType.getAsNominalType();
    if (!rawType.isGeneric() && !n.hasChildren()) {
      return rawType.getInstanceWithNullability(NULLABLE_TYPES_BY_DEFAULT);
    }
    ImmutableList.Builder<JSType> typeList = ImmutableList.builder();
    if (n.hasChildren()) {
      // Compute instantiation of polymorphic class/interface.
      Preconditions.checkState(n.getFirstChild().isBlock());
      for (Node child : n.getFirstChild().children()) {
        typeList.add(
            getTypeFromCommentHelper(child, registry, outerTypeParameters));
      }
    }
    ImmutableList<JSType> typeArguments = typeList.build();
    ImmutableList<String> typeParameters = rawType.getTypeParameters();
    int typeArgsSize = typeArguments.size();
    int typeParamsSize = typeParameters.size();
    if (typeArgsSize != typeParamsSize) {
      // We used to also warn when (typeArgsSize < typeParamsSize), but it
      // happens so often that we stopped. Array, Object and goog.Promise are
      // common culprits, but many other types as well.
      if (typeArgsSize > typeParamsSize) {
        warnings.add(JSError.make(
            n, INVALID_GENERICS_INSTANTIATION,
            uninstantiated.getName(), String.valueOf(typeParamsSize),
            String.valueOf(typeArgsSize)));
      }
      return maybeMakeNullable(JSType.fromObjectType(ObjectType.fromNominalType(
              uninstantiated.instantiateGenerics(
                  fixLengthOfTypeList(typeParameters.size(), typeArguments)))));
    }
    return maybeMakeNullable(JSType.fromObjectType(ObjectType.fromNominalType(
            uninstantiated.instantiateGenerics(typeArguments))));
  }

  private static List<JSType> fixLengthOfTypeList(
      int desiredLength, List<JSType> typeList) {
    int length = typeList.size();
    if (length == desiredLength) {
      return typeList;
    }
    ImmutableList.Builder<JSType> builder = ImmutableList.builder();
    for (int i = 0; i < desiredLength; i++) {
      builder.add(i < length ? typeList.get(i) : JSType.UNKNOWN);
    }
    return builder.build();
  }

  // Don't confuse with getFunTypeFromAtTypeJsdoc; the function below computes a
  // type that doesn't have an associated AST node.
  private JSType getFunTypeHelper(Node jsdocNode, DeclaredTypeRegistry registry,
      ImmutableList<String> typeParameters) throws UnknownTypeException {
    FunctionTypeBuilder builder = new FunctionTypeBuilder();
    fillInFunTypeBuilder(jsdocNode, null, registry, typeParameters, builder);
    return registry.getCommonTypes().fromFunctionType(builder.buildFunction());
  }

  private void fillInFunTypeBuilder(
      Node jsdocNode, RawNominalType ownerType, DeclaredTypeRegistry registry,
      ImmutableList<String> typeParameters, FunctionTypeBuilder builder)
      throws UnknownTypeException {
    Node child = jsdocNode.getFirstChild();
    NominalType builtinObject = registry.getCommonTypes().getObjectType();
    if (child.getType() == Token.THIS) {
      if (ownerType == null) {
        NominalType nt = getNominalType(child.getFirstChild(), registry, typeParameters);
        builder.addReceiverType(nt == null ? builtinObject : nt);
      }
      child = child.getNext();
    } else if (child.getType() == Token.NEW) {
      NominalType nt = getNominalType(child.getFirstChild(), registry, typeParameters);
      builder.addNominalType(nt == null ? builtinObject : nt);
      child = child.getNext();
    }
    if (child.getType() == Token.PARAM_LIST) {
      for (Node arg = child.getFirstChild(); arg != null; arg = arg.getNext()) {
        try {
          switch (arg.getType()) {
            case Token.EQUALS:
              builder.addOptFormal(getTypeFromCommentHelper(
                  arg.getFirstChild(), registry, typeParameters));
              break;
            case Token.ELLIPSIS:
              Node restNode = arg.getFirstChild();
              builder.addRestFormals(restNode == null ? JSType.UNKNOWN :
                  getTypeFromCommentHelper(restNode, registry, typeParameters));
              break;
            default:
              builder.addReqFormal(
                  getTypeFromCommentHelper(arg, registry, typeParameters));
              break;
          }
        } catch (FunctionTypeBuilder.WrongParameterOrderException e) {
          warn("Wrong parameter order: required parameters are first, " +
              "then optional, then varargs", jsdocNode);
          builder.addPlaceholderFormal();
        }
      }
      child = child.getNext();
    }
    builder.addRetType(
        getTypeFromCommentHelper(child, registry, typeParameters));
  }

  // May return null;
  private NominalType getNominalType(Node n,
      DeclaredTypeRegistry registry, ImmutableList<String> typeParameters) {
    return getTypeFromComment(n, registry, typeParameters)
        .removeType(JSType.NULL).getNominalTypeIfSingletonObj();
  }

  private ImmutableSet<NominalType> getImplementedInterfaces(
      JSDocInfo jsdoc, DeclaredTypeRegistry registry,
      ImmutableList<String> typeParameters) {
    return getInterfacesHelper(jsdoc, registry, typeParameters, true);
  }

  private ImmutableSet<NominalType> getExtendedInterfaces(
      JSDocInfo jsdoc, DeclaredTypeRegistry registry,
      ImmutableList<String> typeParameters) {
    return getInterfacesHelper(jsdoc, registry, typeParameters, false);
  }

  private ImmutableSet<NominalType> getInterfacesHelper(
      JSDocInfo jsdoc, DeclaredTypeRegistry registry,
      ImmutableList<String> typeParameters, boolean implementedIntfs) {
    ImmutableSet.Builder<NominalType> builder = ImmutableSet.builder();
    for (JSTypeExpression texp : (implementedIntfs ?
          jsdoc.getImplementedInterfaces() :
          jsdoc.getExtendedInterfaces())) {
      Node expRoot = texp.getRoot();
      JSType interfaceType =
          getMaybeTypeFromComment(expRoot, registry, typeParameters);
      if (interfaceType != null) {
        NominalType nt = interfaceType.getNominalTypeIfSingletonObj();
        if (nt != null && nt.isInterface()) {
          builder.add(nt);
        } else {
          String errorMsg = implementedIntfs ?
              "Cannot implement non-interface" :
              "Cannot extend non-interface";
          warn(errorMsg, expRoot);
        }
      }
    }
    return builder.build();
  }

  public static class FunctionAndSlotType {
    public JSType slotType;
    public DeclaredFunctionType functionType;

    public FunctionAndSlotType(JSType slotType, DeclaredFunctionType functionType) {
      this.slotType = slotType;
      this.functionType = functionType;
    }
  }

  /**
   * Consumes either a "classic" function jsdoc with @param, @return, etc,
   * or a jsdoc with @type {function ...} and finds the types of the formal
   * parameters and the return value. It returns a builder because the callers
   * of this function must separately handle @constructor, @interface, etc.
   *
   * constructorType is non-null iff this function is a constructor or
   * interface declaration.
   */
  public FunctionAndSlotType getFunctionType(
      JSDocInfo jsdoc, String functionName, Node declNode,
      RawNominalType constructorType, RawNominalType ownerType,
      DeclaredTypeRegistry registry) {
    FunctionTypeBuilder builder = new FunctionTypeBuilder();
    if (ownerType != null) {
      builder.addReceiverType(ownerType.getAsNominalType());
    }
    try {
      if (jsdoc != null && jsdoc.getType() != null) {
        JSType simpleType = getDeclaredTypeOfNode(jsdoc, ownerType, registry);
        if (simpleType.isUnknown() || simpleType.isTop()) {
          return qmarkFunctionDeclared;
        }
        FunctionType funType = simpleType.getFunType();
        if (funType != null) {
          JSType slotType = simpleType.isFunctionType() ? null : simpleType;
          DeclaredFunctionType declType = funType.toDeclaredFunctionType();
          if (ownerType != null) {
            declType = declType.withReceiverType(ownerType.getAsNominalType());
          }
          return new FunctionAndSlotType(slotType, declType);
        } else {
          warn("The function is annotated with a non-function jsdoc. " +
              "Ignoring jsdoc.", declNode);
          jsdoc = null;
        }
      }
      DeclaredFunctionType declType = getFunTypeFromTypicalFunctionJsdoc(
          jsdoc, functionName, declNode,
          constructorType, ownerType, registry, builder, false);
      return new FunctionAndSlotType(null, declType);
    } catch (FunctionTypeBuilder.WrongParameterOrderException e) {
      warn("Wrong parameter order: required parameters are first, " +
          "then optional, then varargs. Ignoring jsdoc.", declNode);
      return qmarkFunctionDeclared;
    }
  }

  private static class ParamIterator {
    /** The parameter names from the JSDocInfo. Only set if 'params' is null. */
    Iterator<String> paramNames;

    /**
     * The PARAM_LIST node containing the function parameters. Only set if
     * 'paramNames' is null.
     */
    Node params;

    int index = -1;

    ParamIterator(Node params, JSDocInfo jsdoc) {
      Preconditions.checkArgument(params != null || jsdoc != null);
      if (params != null) {
        this.params = params;
        this.paramNames = null;
      } else {
        this.params = null;
        this.paramNames = jsdoc.getParameterNames().iterator();
      }
    }

    boolean hasNext() {
      if (paramNames != null) {
        return paramNames.hasNext();
      }
      return index + 1 < params.getChildCount();
    }

    String nextString() {
      if (paramNames != null) {
        return paramNames.next();
      }
      index++;
      return params.getChildAtIndex(index).getString();
    }

    Node getNode() {
      if (paramNames != null) {
        return null;
      }
      return params.getChildAtIndex(index);
    }
  }

  private DeclaredFunctionType getFunTypeFromTypicalFunctionJsdoc(
      JSDocInfo jsdoc, String functionName, Node funNode,
      RawNominalType constructorType, RawNominalType ownerType,
      DeclaredTypeRegistry registry, FunctionTypeBuilder builder,
      boolean ignoreJsdoc /* for when the jsdoc is malformed */) {
    Preconditions.checkArgument(!ignoreJsdoc || jsdoc == null);
    Preconditions.checkArgument(!ignoreJsdoc || funNode.isFunction());
    ImmutableList.Builder<String> typeParamsBuilder = new ImmutableList.Builder<>();;
    ImmutableList<String> typeParameters = ImmutableList.of();
    Node parent = funNode.getParent();

    // TODO(dimvar): need more @template warnings
    // - warn for multiple @template annotations
    // - warn for @template annotation w/out usage

    if (jsdoc != null) {
      typeParamsBuilder.addAll(jsdoc.getTemplateTypeNames());
      // We don't properly support the type transformation language; we treat
      // its type variables as ordinary type variables.
      typeParamsBuilder.addAll(jsdoc.getTypeTransformations().keySet());
      typeParameters = typeParamsBuilder.build();
      if (!typeParameters.isEmpty()) {
        if (parent.isSetterDef() || parent.isGetterDef()) {
          ignoreJsdoc = true;
          jsdoc = null;
          warn("@template can't be used with getters/setters", funNode);
        } else {
          builder.addTypeParameters(typeParameters);
        }
      }
    }
    if (ownerType != null) {
      typeParamsBuilder.addAll(ownerType.getTypeParameters());
      typeParameters = typeParamsBuilder.build();
    }

    fillInFormalParameterTypes(
        jsdoc, funNode, typeParameters, registry, builder, ignoreJsdoc);
    fillInReturnType(
        jsdoc, funNode, parent, typeParameters, registry, builder, ignoreJsdoc);
    if (jsdoc == null) {
      return builder.buildDeclaration();
    }

    // Look at other annotations, eg, @constructor
    NominalType parentClass = getMaybeParentClass(
        jsdoc, functionName, funNode, typeParameters, registry);
    ImmutableSet<NominalType> implementedIntfs = getImplementedInterfaces(
        jsdoc, registry, typeParameters);
    if (constructorType == null && jsdoc.isConstructorOrInterface()) {
      // Anonymous type, don't register it.
      return builder.buildDeclaration();
    } else if (jsdoc.isConstructor()) {
      handleConstructorAnnotation(functionName, funNode, constructorType,
          parentClass, implementedIntfs, registry, builder);
    } else if (jsdoc.isInterface()) {
      handleInterfaceAnnotation(jsdoc, functionName, funNode, constructorType,
          implementedIntfs, typeParameters, registry, builder);
    } else if (!implementedIntfs.isEmpty()) {
      warnings.add(JSError.make(
          funNode, IMPLEMENTS_WITHOUT_CONSTRUCTOR, functionName));
    }

    if (jsdoc.hasThisType() && ownerType == null) {
      Node thisRoot = jsdoc.getThisType().getRoot();
      Preconditions.checkState(thisRoot.getType() == Token.BANG);
      Node thisNode = thisRoot.getFirstChild();
      // JsDocInfoParser wraps @this types with !. But we warn when we see !T,
      // and we don't want to warn for a ! that was automatically inserted.
      // So, we bypass the ! here.
      JSType thisType = getMaybeTypeFromComment(thisNode, registry, typeParameters);
      if (thisType != null) {
        thisType = thisType.removeType(JSType.NULL);
      }
      // TODO(dimvar): thisType may be non-null but have a null
      // thisTypeAsNominal.
      // We currently only support nominal types for the receiver type, but
      // people use other types as well: unions, records, etc.
      // For now, we just use the generic Object for these.
      NominalType nt = thisType == null ? null : thisType.getNominalTypeIfSingletonObj();
      NominalType builtinObject = registry.getCommonTypes().getObjectType();
      builder.addReceiverType(nt == null ? builtinObject : nt);
    }

    return builder.buildDeclaration();
  }

  private void fillInFormalParameterTypes(
      JSDocInfo jsdoc, Node funNode,
      ImmutableList<String> typeParameters,
      DeclaredTypeRegistry registry, FunctionTypeBuilder builder,
      boolean ignoreJsdoc /* for when the jsdoc is malformed */) {
    boolean ignoreFunNode  = !funNode.isFunction();
    Node params = ignoreFunNode ? null : funNode.getFirstChild().getNext();
    ParamIterator iterator = new ParamIterator(params, jsdoc);
    while (iterator.hasNext()) {
      String pname = iterator.nextString();
      Node param = iterator.getNode();
      ParameterKind p = ParameterKind.REQUIRED;
      if (param != null && convention.isOptionalParameter(param)) {
        p = ParameterKind.OPTIONAL;
      } else if (param != null && convention.isVarArgsParameter(param)) {
        p = ParameterKind.REST;
      }
      ParameterType inlineParamType = (ignoreJsdoc || ignoreFunNode || param.getJSDocInfo() == null)
          ? null : parseParameter(param.getJSDocInfo().getType(), p, registry, typeParameters);
      ParameterType fnParamType = inlineParamType;
      JSTypeExpression jsdocExp = jsdoc == null ? null : jsdoc.getParameterType(pname);
      if (jsdocExp != null) {
        if (inlineParamType == null) {
          fnParamType = parseParameter(jsdocExp, p, registry, typeParameters);
        } else {
          warn("Found two JsDoc comments for formal parameter " + pname, param);
        }
      }
      JSType t  = null;
      if (fnParamType != null) {
        p = fnParamType.kind;
        t = fnParamType.type;
      }
      switch (p) {
          case REQUIRED:
            builder.addReqFormal(t);
            break;
          case OPTIONAL:
            builder.addOptFormal(t);
            break;
          case REST:
            builder.addRestFormals(t != null ? t : JSType.UNKNOWN);
            break;
      }
    }
  }

  private void fillInReturnType(
      JSDocInfo jsdoc, Node funNode, Node parent,
      ImmutableList<String> typeParameters,
      DeclaredTypeRegistry registry, FunctionTypeBuilder builder,
      boolean ignoreJsdoc /* for when the jsdoc is malformed */) {
    JSDocInfo inlineRetJsdoc =
        ignoreJsdoc ? null : funNode.getFirstChild().getJSDocInfo();
    JSTypeExpression retTypeExp = jsdoc == null ? null : jsdoc.getReturnType();
    if (parent.isSetterDef() && retTypeExp == null) {
      // inline returns for getters/setters are not parsed
      builder.addRetType(JSType.UNDEFINED);
    } else if (inlineRetJsdoc != null) {
      builder.addRetType(
          getDeclaredTypeOfNode(inlineRetJsdoc, registry, typeParameters));
      if (retTypeExp != null) {
        warn("Found two JsDoc comments for the return type", funNode);
      }
    } else {
      builder.addRetType(
          getTypeFromJSTypeExpression(retTypeExp, registry, typeParameters));
    }
  }

  private NominalType getMaybeParentClass(
      JSDocInfo jsdoc, String functionName, Node funNode,
      ImmutableList<String> typeParameters, DeclaredTypeRegistry registry) {
    if (!jsdoc.hasBaseType()) {
      return null;
    }
    if (!jsdoc.isConstructor()) {
      warnings.add(JSError.make(
          funNode, EXTENDS_NOT_ON_CTOR_OR_INTERF, functionName));
      return null;
    }
    Node docNode = jsdoc.getBaseType().getRoot();
    JSType extendedType =
        getMaybeTypeFromComment(docNode, registry, typeParameters);
    if (extendedType == null) {
      return null;
    }
    NominalType parentClass = extendedType.getNominalTypeIfSingletonObj();
    if (parentClass != null && parentClass.isClass()) {
      return parentClass;
    }
    if (parentClass == null) {
      warnings.add(JSError.make(funNode, EXTENDS_NON_OBJECT,
              functionName, extendedType.toString()));
    } else {
      Preconditions.checkState(parentClass.isInterface());
      warnings.add(JSError.make(funNode, CONFLICTING_EXTENDED_TYPE,
              "constructor", functionName));
    }
    return null;
  }

  private void handleConstructorAnnotation(
      String functionName, Node funNode, RawNominalType constructorType,
      NominalType parentClass, ImmutableSet<NominalType> implementedIntfs,
      DeclaredTypeRegistry registry, FunctionTypeBuilder builder) {
    String className = constructorType.toString();
    NominalType builtinObject = registry.getCommonTypes().getObjectType();
    if (parentClass == null && !functionName.equals("Object")) {
      parentClass = builtinObject;
    }
    if (parentClass != null) {
      if (!constructorType.addSuperClass(parentClass)) {
        warnings.add(JSError.make(funNode, INHERITANCE_CYCLE, className));
      } else if (parentClass != builtinObject) {
        if (constructorType.isStruct() && !parentClass.isStruct()) {
          warnings.add(JSError.make(
              funNode, CONFLICTING_SHAPE_TYPE, "struct", className));
        } else if (constructorType.isDict() && !parentClass.isDict()) {
          warnings.add(JSError.make(
              funNode, CONFLICTING_SHAPE_TYPE, "dict", className));
        }
      }
    }
    if (constructorType.isDict() && !implementedIntfs.isEmpty()) {
      warnings.add(JSError.make(funNode, DICT_IMPLEMENTS_INTERF, className));
    }
    boolean noCycles = constructorType.addInterfaces(implementedIntfs);
    Preconditions.checkState(noCycles);
    builder.addNominalType(constructorType.getAsNominalType());
  }

  private void handleInterfaceAnnotation(
      JSDocInfo jsdoc, String functionName, Node funNode,
      RawNominalType constructorType,
      ImmutableSet<NominalType> implementedIntfs,
      ImmutableList<String> typeParameters,
      DeclaredTypeRegistry registry, FunctionTypeBuilder builder) {
    if (!implementedIntfs.isEmpty()) {
      warnings.add(JSError.make(
          funNode, CONFLICTING_IMPLEMENTED_TYPE, functionName));
    }
    boolean noCycles = constructorType.addInterfaces(
        getExtendedInterfaces(jsdoc, registry, typeParameters));
    if (!noCycles) {
      warnings.add(JSError.make(
          funNode, INHERITANCE_CYCLE, constructorType.toString()));
    }
    builder.addNominalType(constructorType.getAsNominalType());
  }

  // /** @param {...?} var_args */ function f(var_args) { ... }
  // var_args shouldn't be used in the body of f
  public static boolean isRestArg(JSDocInfo funJsdoc, String formalParamName) {
    if (funJsdoc == null) {
      return false;
    }
    JSTypeExpression texp = funJsdoc.getParameterType(formalParamName);
    Node jsdocNode = texp == null ? null : texp.getRoot();
    return jsdocNode != null && jsdocNode.getType() == Token.ELLIPSIS;
  }

  // TODO(blickly): Add more DiagnosticTypes and remove this method
  void warn(String msg, Node faultyNode) {
    warnings.add(JSError.make(faultyNode, BAD_JSDOC_ANNOTATION, msg));
  }

  private ParameterType parseParameter(
      JSTypeExpression jsdoc, ParameterKind p,
      DeclaredTypeRegistry registry, ImmutableList<String> typeParameters) {
    if (jsdoc == null) {
      return null;
    }
    return parseParameter(jsdoc.getRoot(), p, registry, typeParameters);
  }

  private ParameterType parseParameter(
      Node jsdoc, ParameterKind p,
      DeclaredTypeRegistry registry, ImmutableList<String> typeParameters) {
    if (jsdoc == null) {
      return null;
    }
    switch (jsdoc.getType()) {
      case Token.EQUALS:
        p = ParameterKind.OPTIONAL;
        jsdoc = jsdoc.getFirstChild();
        break;
      case Token.ELLIPSIS:
        p = ParameterKind.REST;
        jsdoc = jsdoc.getFirstChild();
        break;
    }
    JSType t = getMaybeTypeFromComment(jsdoc, registry, typeParameters);
    return new ParameterType(t, p);
  }

  private static class ParameterType {
    private JSType type;
    private ParameterKind kind;

    ParameterType(JSType type, ParameterKind kind) {
      this.type = type;
      this.kind = kind;
    }
  }

  private static enum ParameterKind {
    REQUIRED,
    OPTIONAL,
    REST,
  }
}


text:
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using pwiz.Common.DataAnalysis.Matrices;

namespace pwiz.Common.DataAnalysis.FoldChange
{
    /// <summary>
    /// Contains the linear regression model for a FoldChangeDataSet.
    /// The columns in the design matrix correspond to coefficients that will be fitted
    /// in the linear model.
    /// The rows in the matrix correspond to observed values.
    /// A value in the matrix is 1 if the coefficient applies to that observation.
    /// The contrast vector contains factors by which the fitted coefficients get multiplied
    /// to produce the final fold change result.
    /// </summary>
    public class DesignMatrix
    {
        // ReSharper disable NonLocalizedString
        private readonly double[][] _matrixColumns;
        private readonly double[][] _contrastValues;
        private readonly string[] _columnNames;

        private DesignMatrix(FoldChangeDataSet dataSet, double[][] matrixColumns, double[][] contrastValues, string[] columnNames)
        {
            DataSet = dataSet;
            _matrixColumns = matrixColumns;
            _contrastValues = contrastValues;
            _columnNames = columnNames;
        }

        /// <summary>
        /// Gets the design matrix used for obtaining a single abundance value per run.
        /// The contrast matrix ends up having the same number of rows as the number of runs.
        /// </summary>
        public static DesignMatrix GetRunQuantificationDesignMatrix(FoldChangeDataSet dataSet)
        {
            var columnNames = new List<string>();
            var matrixColumns = new List<double[]>();
            var contrastValues = new List<double[]>();
            var featuresByRun = Enumerable.Range(0, dataSet.RunCount)
                .Select(dataSet.GetFeaturesForRun).ToArray();
            columnNames.Add("Intercept");
            matrixColumns.Add(Enumerable.Repeat(1.0, dataSet.RowCount).ToArray());
            contrastValues.Add(Enumerable.Repeat(1.0, dataSet.RunCount).ToArray());

            for (int iFeature = 1; iFeature < dataSet.FeatureCount; iFeature++)
            {
                columnNames.Add("Feature" + iFeature);
                matrixColumns.Add(Enumerable.Range(0, dataSet.RowCount).Select(iRow => iFeature == dataSet.Features[iRow] ? 1.0 : 0.0).ToArray());
                contrastValues.Add(Enumerable.Range(0, dataSet.RunCount).Select(run =>
                {
                    var features = featuresByRun[run];
                    if (features.Contains(iFeature))
                    {
                        return 1.0/features.Count;
                    }
                    return 0;
                }).ToArray());
            }

            for (int iRun = 1; iRun < dataSet.RunCount; iRun++)
            {
                columnNames.Add("Run" + iRun);
                matrixColumns.Add(Enumerable.Range(0, dataSet.RowCount).Select(iRow=>iRun == dataSet.Runs[iRow] ? 1.0 : 0.0).ToArray());
                contrastValues.Add(Enumerable.Range(0, dataSet.RunCount).Select(run=>run == iRun ? 1.0 : 0).ToArray());
            }
            return new DesignMatrix(dataSet, matrixColumns.ToArray(), contrastValues.ToArray(), columnNames.ToArray());
        }

        /// <summary>
        /// Constructs a design matrix for a FoldChangeDataSet.
        /// If <paramref name="includeFeatureInteraction"/> is true, then the model is:
        /// ABUNDANCE ~ FEATURE +  SUBJECT + GROUP + FEATURE:GROUP
        /// if false, then the model is:
        /// ABUNDANCE ~ FEATURE +  SUBJECT + GROUP
        /// </summary>
        /// <param name="dataSet"></param>
        /// <param name="includeFeatureInteraction"></param>
        /// <returns></returns>
        public static DesignMatrix GetDesignMatrix(FoldChangeDataSet dataSet, bool includeFeatureInteraction)
        {
            var columnNames = new List<string>();
            var matrixColumns = new List<double[]>();
            var contrastValues = new List<double>();
            columnNames.Add("Intercept");
            matrixColumns.Add(Enumerable.Repeat(1.0, dataSet.RowCount).ToArray());
            contrastValues.Add(0);

            for (int iFeature = 1; iFeature < dataSet.FeatureCount; iFeature++)
            {
                columnNames.Add("Feature" + iFeature);
                matrixColumns.Add(Enumerable.Range(0, dataSet.RowCount).Select(iRow=>iFeature == dataSet.Features[iRow] ? 1.0 : 0.0).ToArray());
                contrastValues.Add(0.0);
            }

            if (dataSet.RowCount != dataSet.SubjectCount)
            {
                int controlGroupCount = dataSet.SubjectControls.Count(f => f);
                var subjectIndexes = Enumerable.Range(1, dataSet.SubjectCount - 1);
                foreach (int iSubject in subjectIndexes)
                {
                    columnNames.Add("Subject" + iSubject);
                    matrixColumns.Add(Enumerable.Range(0, dataSet.RowCount).Select(iRow=>iSubject == dataSet.Subjects[iRow] ? 1.0 : 0.0).ToArray());
                    if (dataSet.IsSubjectInControlGroup(iSubject))
                    {
                        contrastValues.Add(-1.0/controlGroupCount);
                    }
                    else
                    {
                        contrastValues.Add(1.0 / (dataSet.SubjectCount - controlGroupCount));
                    }
                }
            }

            columnNames.Add("Control");
            matrixColumns.Add(Enumerable.Range(0, dataSet.RowCount).Select(iRow => dataSet.IsRowInControlGroup(iRow) ? 1.0 : 0.0).ToArray());
            contrastValues.Add(-1.0);

            if (includeFeatureInteraction)
            {
                for (int iFeature = 1; iFeature < dataSet.FeatureCount; iFeature++)
                {
                    columnNames.Add("Feature" + iFeature + "Interaction");
                    matrixColumns.Add(Enumerable.Range(0, dataSet.RowCount).Select(iRow =>
                        iFeature == dataSet.Features[iRow] && dataSet.IsRowInControlGroup(iRow) ? 1.0 : 0.0).ToArray());
                    contrastValues.Add(-1.0 / dataSet.FeatureCount);
                }
            }
            return new DesignMatrix(dataSet, matrixColumns.ToArray(), contrastValues.Select(value => new[]{value}).ToArray(), columnNames.ToArray());
        }

        public FoldChangeDataSet DataSet { get; private set; }
        public Matrix<double> Matrix { get { return DenseMatrix.OfColumnArrays(_matrixColumns); } }

        /// <summary>
        /// Returns the vector for the given row of the contrast matrix.
        /// The dot product of the coefficents of the linear regression is equal to the estimated value.
        /// </summary>
        public IList<double> GetContrastValues(int iRow) { return _contrastValues.Select(value=>value[iRow]).ToArray(); }
        public IList<LinearFitResult> PerformLinearFit(QrFactorizationCache cache)
        {
            var linearModel = LinearModel.CreateModel(cache, DenseMatrix.OfColumnArrays(_matrixColumns), DenseMatrix.OfColumnArrays(_contrastValues), 1E-7);
            return linearModel.Fit(DataSet.Abundances.ToArray());
        }

        public override string ToString()
        {
            StringBuilder result = new StringBuilder();
            result.AppendLine(string.Join(",", _columnNames));
            for (int iRow = 0; iRow < _matrixColumns[0].Length; iRow++)
            {
                result.AppendLine(string.Join(",",
                    _matrixColumns.Select(col => col[iRow].ToString(CultureInfo.InvariantCulture)).ToArray()));
            }
            result.AppendLine("Contrast values:");
            for (int iRow = 0; iRow < _contrastValues[0].Length; iRow++)
            {
                result.AppendLine(string.Join(",", GetContrastValues(iRow)));
            }
            return result.ToString();
        }
    }
}


text:
package org.apache.james.mailbox.hbase;

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.james.mailbox.MailboxSession;
import static org.apache.james.mailbox.hbase.HBaseNames.*;
import org.apache.james.mailbox.hbase.mail.HBaseModSeqProvider;
import org.apache.james.mailbox.hbase.mail.HBaseUidProvider;
import org.apache.james.mailbox.store.mail.MailboxMapper;
import org.apache.james.mailbox.store.mail.MessageMapper;
import org.apache.james.mailbox.store.mail.ModSeqProvider;
import org.apache.james.mailbox.store.mail.UidProvider;
import org.apache.james.mailbox.store.user.SubscriptionMapper;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The MailboxSessionMapperFactory test.
 *
 */
public class HBaseMailboxSessionMapperFactoryTest {

    private final static Logger LOG = LoggerFactory.getLogger(HBaseMailboxSessionMapperFactoryTest.class);
    private static final HBaseClusterSingleton CLUSTER = HBaseClusterSingleton.build();
    private static Configuration conf;

    @Before
    public void beforeMethod() throws IOException {
        ensureTables();
        clearTables();
        conf = CLUSTER.getConf();
    }

    private void ensureTables() throws IOException {
        CLUSTER.ensureTable(MAILBOXES_TABLE, new byte[][]{MAILBOX_CF});
        CLUSTER.ensureTable(MESSAGES_TABLE,
                new byte[][]{MESSAGES_META_CF, MESSAGE_DATA_HEADERS_CF, MESSAGE_DATA_BODY_CF});
        CLUSTER.ensureTable(SUBSCRIPTIONS_TABLE, new byte[][]{SUBSCRIPTION_CF});
    }

    private void clearTables() {
        CLUSTER.clearTable(MAILBOXES);
        CLUSTER.clearTable(MESSAGES);
        CLUSTER.clearTable(SUBSCRIPTIONS);
    }

    /**
     * Test of createMessageMapper method, of class
     * HBaseMailboxSessionMapperFactory.
     */
    @Test
    public void testCreateMessageMapper() throws Exception {
        LOG.info("createMessageMapper");
        MailboxSession session = null;
        HBaseMailboxSessionMapperFactory instance = new HBaseMailboxSessionMapperFactory(conf, null, null);
        MessageMapper<HBaseId> messageMapper = instance.createMessageMapper(session);
        assertNotNull(messageMapper);
        assertTrue(messageMapper instanceof MessageMapper);
    }

    /**
     * Test of createMailboxMapper method, of class
     * HBaseMailboxSessionMapperFactory.
     */
    @Test
    public void testCreateMailboxMapper() throws Exception {
        LOG.info("createMailboxMapper");
        MailboxSession session = null;
        HBaseMailboxSessionMapperFactory instance = new HBaseMailboxSessionMapperFactory(conf, null, null);
        MailboxMapper<HBaseId> mailboxMapper = instance.createMailboxMapper(session);
        assertNotNull(mailboxMapper);
        assertTrue(mailboxMapper instanceof MailboxMapper);
    }

    /**
     * Test of createSubscriptionMapper method, of class
     * HBaseMailboxSessionMapperFactory.
     */
    @Test
    public void testCreateSubscriptionMapper() throws Exception {
        LOG.info("createSubscriptionMapper");
        MailboxSession session = null;
        HBaseMailboxSessionMapperFactory instance = new HBaseMailboxSessionMapperFactory(conf, null, null);
        SubscriptionMapper subscriptionMapper = instance.createSubscriptionMapper(session);
        assertNotNull(subscriptionMapper);
        assertTrue(subscriptionMapper instanceof SubscriptionMapper);
    }

    /**
     * Test of getModSeqProvider method, of class
     * HBaseMailboxSessionMapperFactory.
     */
    @Test
    public void testGetModSeqProvider() {
        LOG.info("getModSeqProvider");
        ModSeqProvider<HBaseId> expResult = new HBaseModSeqProvider(conf);
        HBaseMailboxSessionMapperFactory instance = new HBaseMailboxSessionMapperFactory(conf, null, expResult);
        ModSeqProvider<HBaseId> result = instance.getModSeqProvider();
        assertEquals(expResult, result);
    }

    /**
     * Test of getUidProvider method, of class HBaseMailboxSessionMapperFactory.
     */
    @Test
    public void testGetUidProvider() {
        LOG.info("getUidProvider");
        UidProvider<HBaseId> expResult = new HBaseUidProvider(conf);
        HBaseMailboxSessionMapperFactory instance = new HBaseMailboxSessionMapperFactory(conf, expResult, null);
        UidProvider<HBaseId> result = instance.getUidProvider();
        assertEquals(expResult, result);
    }
}


text:
class IntervalsController < ApplicationController
  skip_before_filter :verify_authenticity_token
  before_action :set_interval, only: [:update, :destroy]

  # POST /intervals
  # POST /intervals.json
  def create
  	@existing_interval = Interval.find_by(end: nil)

  	if(@existing_interval != nil)
  		@existing_interval.end = Time.now
  		@existing_interval.is_current = false
  		@existing_interval.save
	end

  	@new_interval = Interval.new
	@new_interval.start = Time.now
	@new_interval.is_current = true
	@new_interval.save

   respond_to do |format|
      format.html { redirect_to url_for(:controller => :application, :action => :index), notice: 'Interval was successfully created.' }
  		format.json { render :nothing => true, :status => 200 }
	end
  end

  # PUT /intervals/1
  def update
  	 @existing_interval = Interval.find_by(is_current: true)

  	 if(@existing_interval != nil)
	  	 @existing_interval.is_current = false
	  	 @existing_interval.save
	 end

  	 if(@interval.is_current)
  	 	@interval.is_current = false
  	 else
	  	@interval.is_current = true
	 end

	 @interval.save

	 respond_to do |format|
      format.html { redirect_to url_for(:controller => :application, :action => :index), notice: 'Interval was successfully updated.' }
      format.json { head :no_content }
    end
  end

  # DELETE /intervals/1
  # DELETE /intervals/1.json
  def destroy
    @interval.destroy
    respond_to do |format|
      format.html { redirect_to url_for(:controller => :application, :action => :index), notice: 'Interval was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_interval
      @interval = Interval.find(params[:id])
    end

    def interval_params
      params.require(:interval).permit(:start, :end)
    end
end


text:
package org.apache.cassandra.transport;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Supplier;

import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Ints;
import org.junit.*;

import com.codahale.metrics.Gauge;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.cql3.CQLTester;
import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.cql3.QueryProcessor;
import org.apache.cassandra.db.marshal.Int32Type;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.db.virtual.*;
import org.apache.cassandra.exceptions.OverloadedException;
import org.apache.cassandra.metrics.CassandraMetricsRegistry;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.transport.messages.QueryMessage;
import org.apache.cassandra.utils.FBUtilities;

import static org.apache.cassandra.Util.spinAssertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class ClientResourceLimitsTest extends CQLTester
{

    private static final long LOW_LIMIT = 600L;
    private static final long HIGH_LIMIT = 5000000000L;

    private static final QueryOptions V5_DEFAULT_OPTIONS = QueryOptions.create(
        QueryOptions.DEFAULT.getConsistency(),
        QueryOptions.DEFAULT.getValues(),
        QueryOptions.DEFAULT.skipMetadata(),
        QueryOptions.DEFAULT.getPageSize(),
        QueryOptions.DEFAULT.getPagingState(),
        QueryOptions.DEFAULT.getSerialConsistency(),
        ProtocolVersion.V5,
        KEYSPACE);

    @BeforeClass
    public static void setUp()
    {
        DatabaseDescriptor.setNativeTransportReceiveQueueCapacityInBytes(1);
        DatabaseDescriptor.setNativeTransportMaxConcurrentRequestsInBytesPerIp(LOW_LIMIT);
        DatabaseDescriptor.setNativeTransportMaxConcurrentRequestsInBytes(LOW_LIMIT);
        requireNetwork();
    }

    @AfterClass
    public static void tearDown()
    {
        DatabaseDescriptor.setNativeTransportMaxConcurrentRequestsInBytesPerIp(3000000000L);
        DatabaseDescriptor.setNativeTransportMaxConcurrentRequestsInBytes(HIGH_LIMIT);
    }

    @Before
    public void setLimits()
    {
        ClientResourceLimits.setGlobalLimit(LOW_LIMIT);
        ClientResourceLimits.setEndpointLimit(LOW_LIMIT);
    }

    @After
    public void dropCreatedTable()
    {
        try
        {
            QueryProcessor.executeOnceInternal("DROP TABLE " + KEYSPACE + ".atable");
        }
        catch (Throwable t)
        {
            // ignore
        }
    }

    @SuppressWarnings("resource")
    private SimpleClient client(boolean throwOnOverload)
    {
        try
        {
            return SimpleClient.builder(nativeAddr.getHostAddress(), nativePort)
                               .protocolVersion(ProtocolVersion.V5)
                               .useBeta()
                               .build()
                               .connect(false, throwOnOverload);
        }
        catch (IOException e)
        {
            throw new RuntimeException("Error initializing client", e);
        }
    }

    @SuppressWarnings("resource")
    private SimpleClient client(boolean throwOnOverload, int largeMessageThreshold)
    {
        try
        {
            return SimpleClient.builder(nativeAddr.getHostAddress(), nativePort)
                               .protocolVersion(ProtocolVersion.V5)
                               .useBeta()
                               .largeMessageThreshold(largeMessageThreshold)
                               .build()
                               .connect(false, throwOnOverload);
        }
        catch (IOException e)
        {
           throw new RuntimeException("Error initializing client", e);
        }
    }

    @Test
    public void testQueryExecutionWithThrowOnOverload() throws Throwable
    {
        testQueryExecution(true);
    }

    @Test
    public void testQueryExecutionWithoutThrowOnOverload() throws Throwable
    {
        testQueryExecution(false);
    }

    private void testQueryExecution(boolean throwOnOverload) throws Throwable
    {
        try (SimpleClient client = client(throwOnOverload))
        {
            QueryMessage queryMessage = new QueryMessage("CREATE TABLE atable (pk int PRIMARY KEY, v text)",
                                                         V5_DEFAULT_OPTIONS);
            client.execute(queryMessage);
            queryMessage = new QueryMessage("SELECT * FROM atable", V5_DEFAULT_OPTIONS);
            client.execute(queryMessage);
        }
    }

    @Test
    public void testBackpressureOnGlobalLimitExceeded() throws Throwable
    {
        // Bump the per-endpoint limit to make sure we exhaust the global
        ClientResourceLimits.setEndpointLimit(HIGH_LIMIT);
        backPressureTest(() -> ClientResourceLimits.setGlobalLimit(HIGH_LIMIT),
                         (provider) -> provider.globalWaitQueue().signal());
    }

    @Test
    public void testBackPressureWhenEndpointLimitExceeded() throws Throwable
    {
        // Make sure we can only exceed the per-endpoint limit
        ClientResourceLimits.setGlobalLimit(HIGH_LIMIT);
        backPressureTest(() -> ClientResourceLimits.setEndpointLimit(HIGH_LIMIT),
                         (provider) -> provider.endpointWaitQueue().signal());
    }

    private void backPressureTest(Runnable limitLifter, Consumer<ClientResourceLimits.ResourceProvider> signaller)
    throws Throwable
    {
        final AtomicReference<Exception> error = new AtomicReference<>();
        final CountDownLatch started = new CountDownLatch(1);
        final CountDownLatch complete = new CountDownLatch(1);
        try(SimpleClient client = client(false))
        {
            QueryMessage queryMessage = new QueryMessage("CREATE TABLE atable (pk int PRIMARY KEY, v text)",
                                                         V5_DEFAULT_OPTIONS);
            client.execute(queryMessage);

            // There should be no paused client connections yet
            Gauge<Integer> pausedConnections = getPausedConnectionsGauge();
            int before = pausedConnections.getValue();

            Thread t = new Thread(() -> {
                try
                {
                    started.countDown();
                    client.execute(queryMessage());
                    complete.countDown();
                }
                catch (Exception e)
                {
                    // if backpressure blocks the request execution for too long
                    // (10 seconds per SimpleClient), we'll catch a timeout exception
                    error.set(e);
                }
            });
            t.start();

            // When the client attempts to execute the second query, the backpressure
            // mechanism should report the client connection is paused
            assertTrue(started.await(5, TimeUnit.SECONDS));
            spinAssertEquals("Timed out after waiting 5 seconds for paused " +
                             "connections metric to increment due to backpressure",
                             before + 1, pausedConnections::getValue, 5, TimeUnit.SECONDS);

            // verify the request hasn't completed
            assertFalse(complete.await(1, TimeUnit.SECONDS));

            // backpressure has been applied, if we increase the limits of the exhausted reserve and signal
            // the appropriate WaitQueue, it should be released and the client request will complete
            limitLifter.run();
            // We need a ResourceProvider to get access to the WaitQueue
            ClientResourceLimits.Allocator allocator = ClientResourceLimits.getAllocatorForEndpoint(FBUtilities.getJustLocalAddress());
            ClientResourceLimits.ResourceProvider queueHandle = new ClientResourceLimits.ResourceProvider.Default(allocator);
            signaller.accept(queueHandle);

            // SimpleClient has a 10 second timeout, so if we have to wait
            // longer than that assume that we're not going to receive a
            // reply. If all's well, the completion should happen immediately
            assertTrue(complete.await(11, TimeUnit.SECONDS));
            assertNull(error.get());
        }
    }

    @Test
    public void testOverloadedExceptionWhenGlobalLimitExceeded() throws Throwable
    {
        // Bump the per-endpoint limit to make sure we exhaust the global
        ClientResourceLimits.setEndpointLimit(HIGH_LIMIT);
        testOverloadedException(() -> client(true));
    }

    @Test
    public void testOverloadedExceptionWhenEndpointLimitExceeded() throws Throwable
    {
        // Make sure we can only exceed the per-endpoint limit
        ClientResourceLimits.setGlobalLimit(HIGH_LIMIT);
        testOverloadedException(() -> client(true));
    }

    @Test
    public void testOverloadedExceptionWhenGlobalLimitByMultiFrameMessage() throws Throwable
    {
        // Bump the per-endpoint limit to make sure we exhaust the global
        ClientResourceLimits.setEndpointLimit(HIGH_LIMIT);
        testOverloadedException(() -> client(true, Ints.checkedCast(LOW_LIMIT / 2)));
    }

    @Test
    public void testOverloadedExceptionWhenEndpointLimitByMultiFrameMessage() throws Throwable
    {
        // Make sure we can only exceed the per-endpoint limit
        ClientResourceLimits.setGlobalLimit(HIGH_LIMIT);
        testOverloadedException(() -> client(true, Ints.checkedCast(LOW_LIMIT / 2)));
    }

    private void testOverloadedException(Supplier<SimpleClient> clientSupplier)
    {
        try (SimpleClient client = clientSupplier.get())
        {
            QueryMessage queryMessage = new QueryMessage("CREATE TABLE atable (pk int PRIMARY KEY, v text)",
                                                         V5_DEFAULT_OPTIONS);
            client.execute(queryMessage);

            queryMessage = queryMessage();
            try
            {
                client.execute(queryMessage);
                fail();
            }
            catch (RuntimeException e)
            {
                assertTrue(e.getCause() instanceof OverloadedException);
            }
        }
    }

    private QueryMessage queryMessage()
    {
        StringBuilder query = new StringBuilder("INSERT INTO atable (pk, v) VALUES (1, '");
        for (int i=0; i < LOW_LIMIT * 2; i++)
            query.append('a');
        query.append("')");
        return new QueryMessage(query.toString(), V5_DEFAULT_OPTIONS);
    }

    @SuppressWarnings("unchecked")
    private Gauge<Integer> getPausedConnectionsGauge()
    {
        String metricName = "org.apache.cassandra.metrics.Client.PausedConnections";
        Map<String, Gauge> metrics = CassandraMetricsRegistry.Metrics.getGauges((name, metric) -> name.equals(metricName));
        if (metrics.size() != 1)
            fail(String.format("Expected a single registered metric for paused client connections, found %s",
                               metrics.size()));
        return metrics.get(metricName);
    }

    @Test
    public void testQueryUpdatesConcurrentMetricsUpdate() throws Throwable
    {
        try (SimpleClient client = client(true))
        {
            CyclicBarrier barrier = new CyclicBarrier(2);
            String table = createTableName();

            // reusing table name for keyspace name since cannot reuse KEYSPACE and want it to be unique
            TableMetadata tableMetadata =
            TableMetadata.builder(table, table)
                         .kind(TableMetadata.Kind.VIRTUAL)
                         .addPartitionKeyColumn("pk", UTF8Type.instance)
                         .addRegularColumn("v", Int32Type.instance)
                         .build();

            VirtualTable vt1 = new AbstractVirtualTable.SimpleTable(tableMetadata, () -> {
                try
                {
                    // sync up with main thread thats waiting for query to be in progress
                    barrier.await(30, TimeUnit.SECONDS);
                    // wait until metric has been checked
                    barrier.await(30, TimeUnit.SECONDS);
                }
                catch (Exception e)
                {
                    // ignore interuption and barrier exceptions
                }
                return new SimpleDataSet(tableMetadata);
            });
            VirtualKeyspaceRegistry.instance.register(new VirtualKeyspace(table, ImmutableList.of(vt1)));

            final QueryMessage queryMessage = new QueryMessage(String.format("SELECT * FROM %s.%s", table, table),
                                                               V5_DEFAULT_OPTIONS);

            Assert.assertEquals(0L, ClientResourceLimits.getCurrentGlobalUsage());
            try
            {
                Thread tester = new Thread(() -> client.execute(queryMessage));
                tester.setDaemon(true); // so wont block exit if something fails
                tester.start();
                // block until query in progress
                barrier.await(30, TimeUnit.SECONDS);
                assertTrue(ClientResourceLimits.getCurrentGlobalUsage() > 0);
            } finally
            {
                // notify query thread that metric has been checked. This will also throw TimeoutException if both
                // the query threads barriers are not reached
                barrier.await(30, TimeUnit.SECONDS);
            }
        }
    }

    @Test
    public void testChangingLimitsAtRuntime() throws Throwable
    {
        SimpleClient client = client(true);
        try
        {
            QueryMessage smallMessage = new QueryMessage(String.format("CREATE TABLE %s.atable (pk int PRIMARY KEY, v text)", KEYSPACE),
                                                         V5_DEFAULT_OPTIONS);
            client.execute(smallMessage);
            try
            {
                client.execute(queryMessage());
                fail();
            }
            catch (RuntimeException e)
            {
                assertTrue(e.getCause() instanceof OverloadedException);
            }

            // change global limit, query will still fail because endpoint limit
            ClientResourceLimits.setGlobalLimit(HIGH_LIMIT);
            Assert.assertEquals("new global limit not returned by EndpointPayloadTrackers", HIGH_LIMIT, ClientResourceLimits.getGlobalLimit());
            Assert.assertEquals("new global limit not returned by DatabaseDescriptor", HIGH_LIMIT, DatabaseDescriptor.getNativeTransportMaxConcurrentRequestsInBytes());

            try
            {
                client.execute(queryMessage());
                fail();
            }
            catch (RuntimeException e)
            {
                assertTrue(e.getCause() instanceof OverloadedException);
            }

            // change endpoint limit, query will now succeed
            ClientResourceLimits.setEndpointLimit(HIGH_LIMIT);
            Assert.assertEquals("new endpoint limit not returned by EndpointPayloadTrackers", HIGH_LIMIT, ClientResourceLimits.getEndpointLimit());
            Assert.assertEquals("new endpoint limit not returned by DatabaseDescriptor", HIGH_LIMIT, DatabaseDescriptor.getNativeTransportMaxConcurrentRequestsInBytesPerIp());
            client.execute(queryMessage());

            // ensure new clients also see the new raised limits
            client.close();
            client = client(true);
            client.execute(queryMessage());

            // lower the global limit and ensure the query fails again
            ClientResourceLimits.setGlobalLimit(LOW_LIMIT);
            Assert.assertEquals("new global limit not returned by EndpointPayloadTrackers", LOW_LIMIT, ClientResourceLimits.getGlobalLimit());
            Assert.assertEquals("new global limit not returned by DatabaseDescriptor", LOW_LIMIT, DatabaseDescriptor.getNativeTransportMaxConcurrentRequestsInBytes());
            try
            {
                client.execute(queryMessage());
                fail();
            }
            catch (RuntimeException e)
            {
                assertTrue(e.getCause() instanceof OverloadedException);
            }

            // lower the endpoint limit and ensure existing clients also have requests that fail
            ClientResourceLimits.setEndpointLimit(60);
            Assert.assertEquals("new endpoint limit not returned by EndpointPayloadTrackers", 60, ClientResourceLimits.getEndpointLimit());
            Assert.assertEquals("new endpoint limit not returned by DatabaseDescriptor", 60, DatabaseDescriptor.getNativeTransportMaxConcurrentRequestsInBytesPerIp());
            try
            {
                client.execute(smallMessage);
                fail();
            }
            catch (RuntimeException e)
            {
                assertTrue(e.getCause() instanceof OverloadedException);
            }

            // ensure new clients also see the new lowered limit
            client.close();
            client = client(true);
            try
            {
                client.execute(smallMessage);
                fail();
            }
            catch (RuntimeException e)
            {
                assertTrue(e.getCause() instanceof OverloadedException);
            }

            // put the test state back
            ClientResourceLimits.setEndpointLimit(LOW_LIMIT);
            Assert.assertEquals("new endpoint limit not returned by EndpointPayloadTrackers", LOW_LIMIT, ClientResourceLimits.getEndpointLimit());
            Assert.assertEquals("new endpoint limit not returned by DatabaseDescriptor", LOW_LIMIT, DatabaseDescriptor.getNativeTransportMaxConcurrentRequestsInBytesPerIp());
        }
        finally
        {
            client.close();
        }
    }
}


text:
require 'spec_helper'

module Pageflow
  describe HomeButton do
    describe '#url' do
      it 'returns home_url of revision' do
        revision = build(:revision, configuration: {home_url: 'http://example.com'})
        theming = create(:theming)
        home_button = HomeButton.new(revision, theming)

        expect(home_button.url).to eq('http://example.com')
      end

      it 'falls back to cname of theming if theming has home_url' do
        revision = build(:revision, configuration: {home_url: ''})
        theming = create(:theming,
                         cname: 'pageflow.example.com',
                         home_url: 'http://example.com')
        home_button = HomeButton.new(revision, theming)

        expect(home_button.url).to eq('http://pageflow.example.com/')
      end
    end

    describe '#enabled?' do
      it 'is true if home_button is enabled, configured in revision and supported by theme' do
        pageflow_configure do |config|
          config.themes.register(:with_home_button)
        end
        revision = build(:revision,
                         configuration: {
                           home_url: 'http://example.com',
                           home_button_enabled: true
                         },
                         theme_name: 'with_home_button')
        theming = create(:theming)
        home_button = HomeButton.new(revision, theming)

        expect(home_button).to be_enabled
      end

      it 'is true if home_button is enabled, configured in theming and supported by theme' do
        pageflow_configure do |config|
          config.themes.register(:with_home_button)
        end
        revision = build(:revision,
                         configuration: {
                           home_url: '',
                           home_button_enabled: true
                         },
                         theme_name: 'with_home_button')
        theming = create(:theming,
                         home_url: 'http://example.com',
                         cname: 'pageflow.exmaple.com')
        home_button = HomeButton.new(revision, theming)

        expect(home_button).to be_enabled
      end

      it 'is false if home_button is disabled' do
        pageflow_configure do |config|
          config.themes.register(:with_home_button)
        end
        revision = build(:revision,
                         theme_name: 'with_home_button',
                         configuration: {
                           home_url: 'http://example.com',
                           home_button_enabled: false
                         })
        theming = create(:theming)
        home_button = HomeButton.new(revision, theming)

        expect(home_button).not_to be_enabled
      end

      it 'is false if no home_url is configured' do
        revision = build(:revision, configuration: {home_button_enabled: true})
        theming = create(:theming, home_url: '')
        home_button = HomeButton.new(revision, theming)

        expect(home_button).not_to be_enabled
      end

      it 'is false if theme does not support home button' do
        pageflow_configure do |config|
          config.themes.register(:no_home_button, no_home_button: true)
        end
        revision = build(:revision,
                         theme_name: 'no_home_button',
                         configuration: {
                           home_url: 'http://example.com',
                           home_button_enabled: true
                         })
        theming = create(:theming)
        home_button = HomeButton.new(revision, theming)

        expect(home_button).not_to be_enabled
      end
    end
  end
end


text:
package org.ehcache.clustered.common.internal.messages;

import org.hamcrest.Matchers;
import org.junit.Test;

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

import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertThat;

public class ReconnectDataCodecTest {

  @Test
  public void testCodec() {
    Set<String> cacheIds = new HashSet<String>();
    cacheIds.add("test");
    cacheIds.add("test1");
    cacheIds.add("test2");

    ReconnectDataCodec dataCodec = new ReconnectDataCodec();

    Set<String> decoded = dataCodec.decode(dataCodec.encode(cacheIds, 14));

    assertThat(decoded, Matchers.hasSize(3));
    assertThat(decoded, containsInAnyOrder("test", "test1", "test2"));

  }
}


text:
using UnityEngine;
using UnitySampleAssets.Utility;

namespace UnitySampleAssets.Characters.FirstPerson
{
	public class HeadBob : MonoBehaviour
	{
		public Camera _camera;
		public CurveControlledBob motionBob = new CurveControlledBob();
		public LerpControlledBob jumpAndLandingBob = new LerpControlledBob();
		public RigidbodyFirstPersonController rigidbodyFirstPersonController;
		public float StrideInterval;
		[Range(0f, 1f)] public float RunningStrideLengthen;

		private CameraRefocus cameraRefocus;

		private bool previouslyGrounded;
		private Vector3 originalCameraPosition;

		private void Start()
		{
			motionBob.Setup(_camera, StrideInterval);
			originalCameraPosition = _camera.transform.localPosition;
			cameraRefocus = new CameraRefocus(_camera, transform.root.transform, _camera.transform.localPosition);
		}

		private void Update()
		{
			cameraRefocus.GetFocusPoint();
			Vector3 newCameraPosition;
			if (rigidbodyFirstPersonController.Velocity.magnitude > 0 && rigidbodyFirstPersonController.Grounded)
			{
				_camera.transform.localPosition = motionBob.DoHeadBob(rigidbodyFirstPersonController.Velocity.magnitude*(rigidbodyFirstPersonController.Running ? RunningStrideLengthen : 1f));
				newCameraPosition = _camera.transform.localPosition;
				newCameraPosition.y = _camera.transform.localPosition.y - jumpAndLandingBob.Offset();
			}
			else
			{
				newCameraPosition = _camera.transform.localPosition;
				newCameraPosition.y = originalCameraPosition.y - jumpAndLandingBob.Offset();
			}
			_camera.transform.localPosition = newCameraPosition;

			if (!previouslyGrounded && rigidbodyFirstPersonController.Grounded)
			{
				StartCoroutine(jumpAndLandingBob.DoBobCycle());
			}

			previouslyGrounded = rigidbodyFirstPersonController.Grounded;
			cameraRefocus.SetFocusPoint();
		}
	}
}


text:
Your personal YouTube music player.

## Organise your YouTube audio experience.

Using the latest in cross-platform desktop development, we are creating a modern YouTube player complete with an organised library in which your audio can be easily accessed. Thanks to the amazing work found in frameworks listed below, the application is cross-platform, sleek, and easy to use.

**#AtrociousSpaghettiCodeForTheWin!** We'll sort out hardcoded stuff soon. We're still getting basic functionality under way.

### Building

Firstly, you must ensure [Node.js](https://nodejs.org/en/) and [npm](https://www.npmjs.com/) is installed on your operating system.

Clone the repo into a desired folder and change into the MuTube directory:

```
git clone https://github.com/lenku/mu-tube.git && cd mu-tube
```

Resolve `npm` dependencies from `package.json`:

```
npm install
```

Finally, run MuTube with the `start` script from `package.json`:

```
npm start
```

In the future, we will look at methods to bundle the application into a package or, preferrably, a binary executable for each supported operating system.

### Frameworks

- [YouTube API](https://developers.google.com/youtube/)
- [ytdl-core](https://github.com/fent/node-ytdl-core)
- [Node.js](https://nodejs.org/en/) and [npm](https://www.npmjs.com/)
- [Electron](http://electron.atom.io/)
- [jQuery](https://jquery.com/)
- [MaterializeCSS](http://materializecss.com/)
- [Hammer.js](http://hammerjs.github.io/)

### Collaborators

1. [dcarpinelli](https://github.com/dcarpinelli)
2. [enzokarate](https://github.com/enzokarate)


text:
import Component from 'flarum/Component';
import SessionDropdown from 'flarum/components/SessionDropdown';
import ItemList from 'flarum/utils/ItemList';
import listItems from 'flarum/helpers/listItems';

/**
 * The `HeaderSecondary` component displays secondary header controls.
 */
export default class HeaderSecondary extends Component {
  view() {
    return (
      <ul className="Header-controls">
        {listItems(this.items().toArray())}
      </ul>
    );
  }

  config(isInitialized, context) {
    // Since this component is 'above' the content of the page (that is, it is a
    // part of the global UI that persists between routes), we will flag the DOM
    // to be retained across route changes.
    context.retain = true;
  }

  /**
   * Build an item list for the controls.
   *
   * @return {ItemList}
   */
  items() {
    const items = new ItemList();

    items.add('session', SessionDropdown.component());

    return items;
  }
}


text:
package net.violet.platform.datamodel.factories.implementations;

import net.violet.db.records.factories.RecordFactoryImpl;
import net.violet.platform.datamodel.Hint;
import net.violet.platform.datamodel.HintImpl;
import net.violet.platform.datamodel.factories.HintFactory;

public class HintFactoryImpl extends RecordFactoryImpl<Hint, HintImpl> implements HintFactory {

	public HintFactoryImpl() {
		super(HintImpl.SPECIFICATION);
	}

}


text:
import cloneDeep from 'lodash/cloneDeep';
import get from 'lodash/get';

export default class CacheEditFormController {
    /** @type {ig.menu<string>} */
    modelsMenu;
    /** @type {ig.menu<string>} */
    igfssMenu;
    /**
     * IGFS IDs to validate against.
     * @type {Array<string>}
     */
    igfsIDs;

    static $inject = ['IgniteConfirm', 'IgniteVersion', '$scope', 'Caches', 'IgniteFormUtils'];
    constructor(IgniteConfirm, IgniteVersion, $scope, Caches, IgniteFormUtils) {
        Object.assign(this, {IgniteConfirm, IgniteVersion, $scope, Caches, IgniteFormUtils});
    }
    $onInit() {
        this.available = this.IgniteVersion.available.bind(this.IgniteVersion);

        const rebuildDropdowns = () => {
            this.$scope.affinityFunction = [
                {value: 'Rendezvous', label: 'Rendezvous'},
                {value: 'Custom', label: 'Custom'},
                {value: null, label: 'Default'}
            ];

            if (this.available(['1.0.0', '2.0.0']))
                this.$scope.affinityFunction.splice(1, 0, {value: 'Fair', label: 'Fair'});
        };

        rebuildDropdowns();

        const filterModel = () => {
            if (
                this.clonedCache &&
                this.available('2.0.0') &&
                get(this.clonedCache, 'affinity.kind') === 'Fair'
            )
                this.clonedCache.affinity.kind = null;

        };

        this.subscription = this.IgniteVersion.currentSbj
            .do(rebuildDropdowns)
            .do(filterModel)
            .subscribe();

        // TODO: Do we really need this?
        this.$scope.ui = this.IgniteFormUtils.formUI();
    }
    $onDestroy() {
        this.subscription.unsubscribe();
    }
    $onChanges(changes) {
        if (
            'cache' in changes && get(this.clonedCache, '_id') !== get(this.cache, '_id')
        ) {
            this.clonedCache = cloneDeep(changes.cache.currentValue);
            if (this.$scope.ui && this.$scope.ui.inputForm) {
                this.$scope.ui.inputForm.$setPristine();
                this.$scope.ui.inputForm.$setUntouched();
            }
        }
        if ('models' in changes)
            this.modelsMenu = (changes.models.currentValue || []).map((m) => ({value: m._id, label: m.valueType}));
        if ('igfss' in changes) {
            this.igfssMenu = (changes.igfss.currentValue || []).map((i) => ({value: i._id, label: i.name}));
            this.igfsIDs = (changes.igfss.currentValue || []).map((i) => i._id);
        }
    }
    getValuesToCompare() {
        return [this.cache, this.clonedCache].map(this.Caches.normalize);
    }
    save() {
        if (this.$scope.ui.inputForm.$invalid)
            return this.IgniteFormUtils.triggerValidation(this.$scope.ui.inputForm, this.$scope);
        this.onSave({$event: cloneDeep(this.clonedCache)});
    }
    reset = (forReal) => forReal ? this.clonedCache = cloneDeep(this.cache) : void 0;
    confirmAndReset() {
        return this.IgniteConfirm.confirm('Are you sure you want to undo all changes for current cache?')
        .then(this.reset);
    }
}


text:
namespace llvm {
class DWARFGdbIndex {
  uint32_t Version;

  uint32_t CuListOffset;
  uint32_t AddressAreaOffset;
  uint32_t SymbolTableOffset;
  uint32_t ConstantPoolOffset;

  struct CompUnitEntry {
    uint64_t Offset; // Offset of a CU in the .debug_info section.
    uint64_t Length; // Length of that CU.
  };
  SmallVector<CompUnitEntry, 0> CuList;

  struct AddressEntry {
    uint64_t LowAddress;  // The low address.
    uint64_t HighAddress; // The high address.
    uint32_t CuIndex;     // The CU index.
  };
  SmallVector<AddressEntry, 0> AddressArea;

  struct SymTableEntry {
    uint32_t NameOffset; // Offset of the symbol's name in the constant pool.
    uint32_t VecOffset;  // Offset of the CU vector in the constant pool.
  };
  SmallVector<SymTableEntry, 0> SymbolTable;

  // Each value is CU index + attributes.
  SmallVector<std::pair<uint32_t, SmallVector<uint32_t, 0>>, 0>
      ConstantPoolVectors;

  StringRef ConstantPoolStrings;
  uint32_t StringPoolOffset;

  void dumpCUList(raw_ostream &OS) const;
  void dumpAddressArea(raw_ostream &OS) const;
  void dumpSymbolTable(raw_ostream &OS) const;
  void dumpConstantPool(raw_ostream &OS) const;

  bool parseImpl(DataExtractor Data);

public:
  void dump(raw_ostream &OS);
  void parse(DataExtractor Data);

  bool HasContent = false;
  bool HasError = false;
};
}

#endif // LLVM_LIB_DEBUGINFO_DWARFGDBINDEX_H


text:
package com.ddmeng.hellowebview.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.webkit.URLUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;

public class FileUtils {

    private static final String LOG_TAG = "FileUtils";

    /**
     * 创建目录
     *
     * @param dirPath
     * @return
     */
    public static boolean createDir(String dirPath) {
        LogUtil.i(LOG_TAG, "create dir: " + dirPath);
        File f = new File(dirPath);
        if (f.exists()) {
            if (f.isDirectory()) {
                return true;
            }
            f.delete();
            return f.mkdir();
        }
        return f.mkdirs();
    }

    /**
     * 创建文件
     *
     * @param filename
     */
    public static void createFile(String filename) {

        File file = new File(filename);

        if (!file.exists()) {
            try {

                file.getParentFile().mkdirs();
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 根据下载路径得到文件名
     *
     * @param downloadUrl
     * @return
     */
    public static String getFileName(String downloadUrl) {
        String filenameUndecoded = URLUtil.guessFileName(downloadUrl, null, null);
        try {
            filenameUndecoded = URLDecoder.decode(filenameUndecoded, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        LogUtil.i(LOG_TAG, "getFileName: " + filenameUndecoded);
        return filenameUndecoded;
    }

    /**
     * 删除目录中的文件
     *
     * @param dirPath
     */
    public static void cleanFilesInDir(String dirPath) {
        LogUtil.i(LOG_TAG, "cleanFilesInDir");
        File dir = new File(dirPath);
        if (dir.exists() && dir.isDirectory()) {
            LogUtil.i(LOG_TAG, "directory exists");
            File[] files = dir.listFiles();
            if (null != files) {
                LogUtil.i(LOG_TAG, "files length: " + files.length);
                for (File f : files) {
                    boolean ret = f.delete();// 删除目录中的文件和空目录,非空目录无法删除
                    LogUtil.i(LOG_TAG, "ret: " + ret);
                }
            }
        }
    }

    /**
     * 存储Bitmap到指定路径
     *
     * @param bitmap
     * @param dirName
     * @param fileName
     * @return
     */
    public static boolean saveBitmap(Bitmap bitmap, String dirName, String fileName) {

        File file = new File(dirName, fileName);
        FileUtils.createFile(file.toString());
        LogUtil.i(LOG_TAG, "saveBitmap: " + file.toString());
        try {
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(
                    file.toString()));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            stream.flush();
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        LogUtil.i(LOG_TAG, "save finished! " + file.toString() + ", length: " + file.length());
        return true;
    }

    public static Bitmap loadBitmap(String dir, String fileName) {
        Bitmap bitmap = null;
        File path = new File(dir, fileName);
        if (path.exists() && path.isFile()) {
            bitmap = BitmapFactory.decodeFile(path.toString());
        }
        return bitmap;
    }

    private static final String TEMP_FILE_PREFIX = "tmp";

    /**
     * 创建临时文件
     *
     * @param dirFile
     * @return
     */
    public static File createTempFile(File dirFile) {
        File tmpFile = null;
        try {
            tmpFile = File.createTempFile(TEMP_FILE_PREFIX, null, dirFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return tmpFile;
    }

    public static boolean createSingleDir(String path) {
        LogUtil.i(LOG_TAG, "create sub dir: " + path);
        if (null == path) {
            return false;
        }
        File f = new File(path);
        if (f.exists()) {
            if (f.isDirectory()) {
                return true;
            } else {
                // exist but is a file
                f.delete();
            }

        }

        // if file not exists
        return f.mkdir();
    }

    public static boolean createDirForcely(String dirPath) {
        LogUtil.i(LOG_TAG, "create dir forcely: " + dirPath);
        if (null == dirPath) {
            return false;
        }
        File file = new File(dirPath);

        File parent = null;
        parent = file.getParentFile();

        if (null != parent) {
            // Recursion
            createDirForcely(parent.toString());
        }
        return createSingleDir(file.toString());

    }
}


text:
using EnterpriseApp.Domain.Blog.Entity;
using EnterpriseApp.Domain.Shared.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EnterpriseApp.Domain.Blog.Service.Read
{
    public interface IServiceReadTermTaxonomy : IServiceRead<long, TermTaxonomy>
    {

        TermTaxonomy GetByName(string name);

    }
}