//===- ThreadSafetyCommon.h -------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Parts of thread safety analysis that are not specific to thread safety
// itself have been factored into classes here, where they can be potentially
// used by other analyses.  Currently these include:
//
// * Generalize clang CFG visitors.
// * Conversion of the clang CFG to SSA form.
// * Translation of clang Exprs to TIL SExprs
//
// UNDER CONSTRUCTION.  USE AT YOUR OWN RISK.
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYCOMMON_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYCOMMON_H

#include "clang/AST/Decl.h"
#include "clang/Analysis/Analyses/PostOrderCFGView.h"
#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
#include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
#include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
#include "clang/Analysis/AnalysisDeclContext.h"
#include "clang/Analysis/CFG.h"
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Casting.h"
#include <sstream>
#include <string>
#include <utility>
#include <vector>

namespace clang {

class AbstractConditionalOperator;
class ArraySubscriptExpr;
class BinaryOperator;
class CallExpr;
class CastExpr;
class CXXDestructorDecl;
class CXXMemberCallExpr;
class CXXOperatorCallExpr;
class CXXThisExpr;
class DeclRefExpr;
class DeclStmt;
class Expr;
class MemberExpr;
class Stmt;
class UnaryOperator;

namespace threadSafety {

// Various helper functions on til::SExpr
namespace sx {

inline bool equals(const til::SExpr *E1, const til::SExpr *E2) {
  return til::EqualsComparator::compareExprs(E1, E2);
}

inline bool matches(const til::SExpr *E1, const til::SExpr *E2) {
  // We treat a top-level wildcard as the "univsersal" lock.
  // It matches everything for the purpose of checking locks, but not
  // for unlocking them.
  if (isa<til::Wildcard>(E1))
    return isa<til::Wildcard>(E2);
  if (isa<til::Wildcard>(E2))
    return isa<til::Wildcard>(E1);

  return til::MatchComparator::compareExprs(E1, E2);
}

inline bool partiallyMatches(const til::SExpr *E1, const til::SExpr *E2) {
  const auto *PE1 = dyn_cast_or_null<til::Project>(E1);
  if (!PE1)
    return false;
  const auto *PE2 = dyn_cast_or_null<til::Project>(E2);
  if (!PE2)
    return false;
  return PE1->clangDecl() == PE2->clangDecl();
}

inline std::string toString(const til::SExpr *E) {
  std::stringstream ss;
  til::StdPrinter::print(E, ss);
  return ss.str();
}

}  // namespace sx

// This class defines the interface of a clang CFG Visitor.
// CFGWalker will invoke the following methods.
// Note that methods are not virtual; the visitor is templatized.
class CFGVisitor {
  // Enter the CFG for Decl D, and perform any initial setup operations.
  void enterCFG(CFG *Cfg, const NamedDecl *D, const CFGBlock *First) {}

  // Enter a CFGBlock.
  void enterCFGBlock(const CFGBlock *B) {}

  // Returns true if this visitor implements handlePredecessor
  bool visitPredecessors() { return true; }

  // Process a predecessor edge.
  void handlePredecessor(const CFGBlock *Pred) {}

  // Process a successor back edge to a previously visited block.
  void handlePredecessorBackEdge(const CFGBlock *Pred) {}

  // Called just before processing statements.
  void enterCFGBlockBody(const CFGBlock *B) {}

  // Process an ordinary statement.
  void handleStatement(const Stmt *S) {}

  // Process a destructor call
  void handleDestructorCall(const VarDecl *VD, const CXXDestructorDecl *DD) {}

  // Called after all statements have been handled.
  void exitCFGBlockBody(const CFGBlock *B) {}

  // Return true
  bool visitSuccessors() { return true; }

  // Process a successor edge.
  void handleSuccessor(const CFGBlock *Succ) {}

  // Process a successor back edge to a previously visited block.
  void handleSuccessorBackEdge(const CFGBlock *Succ) {}

  // Leave a CFGBlock.
  void exitCFGBlock(const CFGBlock *B) {}

  // Leave the CFG, and perform any final cleanup operations.
  void exitCFG(const CFGBlock *Last) {}
};

// Walks the clang CFG, and invokes methods on a given CFGVisitor.
class CFGWalker {
public:
  CFGWalker() = default;

  // Initialize the CFGWalker.  This setup only needs to be done once, even
  // if there are multiple passes over the CFG.
  bool init(AnalysisDeclContext &AC) {
    ACtx = &AC;
    CFGraph = AC.getCFG();
    if (!CFGraph)
      return false;

    // Ignore anonymous functions.
    if (!dyn_cast_or_null<NamedDecl>(AC.getDecl()))
      return false;

    SortedGraph = AC.getAnalysis<PostOrderCFGView>();
    if (!SortedGraph)
      return false;

    return true;
  }

  // Traverse the CFG, calling methods on V as appropriate.
  template <class Visitor>
  void walk(Visitor &V) {
    PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);

    V.enterCFG(CFGraph, getDecl(), &CFGraph->getEntry());

    for (const auto *CurrBlock : *SortedGraph) {
      VisitedBlocks.insert(CurrBlock);

      V.enterCFGBlock(CurrBlock);

      // Process predecessors, handling back edges last
      if (V.visitPredecessors()) {
        SmallVector<CFGBlock*, 4> BackEdges;
        // Process successors
        for (CFGBlock::const_pred_iterator SI = CurrBlock->pred_begin(),
                                           SE = CurrBlock->pred_end();
             SI != SE; ++SI) {
          if (*SI == nullptr)
            continue;

          if (!VisitedBlocks.alreadySet(*SI)) {
            BackEdges.push_back(*SI);
            continue;
          }
          V.handlePredecessor(*SI);
        }

        for (auto *Blk : BackEdges)
          V.handlePredecessorBackEdge(Blk);
      }

      V.enterCFGBlockBody(CurrBlock);

      // Process statements
      for (const auto &BI : *CurrBlock) {
        switch (BI.getKind()) {
        case CFGElement::Statement:
          V.handleStatement(BI.castAs<CFGStmt>().getStmt());
          break;

        case CFGElement::AutomaticObjectDtor: {
          CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
          auto *DD = const_cast<CXXDestructorDecl *>(
              AD.getDestructorDecl(ACtx->getASTContext()));
          auto *VD = const_cast<VarDecl *>(AD.getVarDecl());
          V.handleDestructorCall(VD, DD);
          break;
        }
        default:
          break;
        }
      }

      V.exitCFGBlockBody(CurrBlock);

      // Process successors, handling back edges first.
      if (V.visitSuccessors()) {
        SmallVector<CFGBlock*, 8> ForwardEdges;

        // Process successors
        for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
                                           SE = CurrBlock->succ_end();
             SI != SE; ++SI) {
          if (*SI == nullptr)
            continue;

          if (!VisitedBlocks.alreadySet(*SI)) {
            ForwardEdges.push_back(*SI);
            continue;
          }
          V.handleSuccessorBackEdge(*SI);
        }

        for (auto *Blk : ForwardEdges)
          V.handleSuccessor(Blk);
      }

      V.exitCFGBlock(CurrBlock);
    }
    V.exitCFG(&CFGraph->getExit());
  }

  const CFG *getGraph() const { return CFGraph; }
  CFG *getGraph() { return CFGraph; }

  const NamedDecl *getDecl() const {
    return dyn_cast<NamedDecl>(ACtx->getDecl());
  }

  const PostOrderCFGView *getSortedGraph() const { return SortedGraph; }

private:
  CFG *CFGraph = nullptr;
  AnalysisDeclContext *ACtx = nullptr;
  PostOrderCFGView *SortedGraph = nullptr;
};

// TODO: move this back into ThreadSafety.cpp
// This is specific to thread safety.  It is here because
// translateAttrExpr needs it, but that should be moved too.
class CapabilityExpr {
private:
  /// The capability expression.
  const til::SExpr* CapExpr;

  /// True if this is a negative capability.
  bool Negated;

public:
  CapabilityExpr(const til::SExpr *E, bool Neg) : CapExpr(E), Negated(Neg) {}

  const til::SExpr* sexpr() const { return CapExpr; }
  bool negative() const { return Negated; }

  CapabilityExpr operator!() const {
    return CapabilityExpr(CapExpr, !Negated);
  }

  bool equals(const CapabilityExpr &other) const {
    return (Negated == other.Negated) && sx::equals(CapExpr, other.CapExpr);
  }

  bool matches(const CapabilityExpr &other) const {
    return (Negated == other.Negated) && sx::matches(CapExpr, other.CapExpr);
  }

  bool matchesUniv(const CapabilityExpr &CapE) const {
    return isUniversal() || matches(CapE);
  }

  bool partiallyMatches(const CapabilityExpr &other) const {
    return (Negated == other.Negated) &&
            sx::partiallyMatches(CapExpr, other.CapExpr);
  }

  const ValueDecl* valueDecl() const {
    if (Negated || CapExpr == nullptr)
      return nullptr;
    if (const auto *P = dyn_cast<til::Project>(CapExpr))
      return P->clangDecl();
    if (const auto *P = dyn_cast<til::LiteralPtr>(CapExpr))
      return P->clangDecl();
    return nullptr;
  }

  std::string toString() const {
    if (Negated)
      return "!" + sx::toString(CapExpr);
    return sx::toString(CapExpr);
  }

  bool shouldIgnore() const { return CapExpr == nullptr; }

  bool isInvalid() const { return sexpr() && isa<til::Undefined>(sexpr()); }

  bool isUniversal() const { return sexpr() && isa<til::Wildcard>(sexpr()); }
};

// Translate clang::Expr to til::SExpr.
class SExprBuilder {
public:
  /// Encapsulates the lexical context of a function call.  The lexical
  /// context includes the arguments to the call, including the implicit object
  /// argument.  When an attribute containing a mutex expression is attached to
  /// a method, the expression may refer to formal parameters of the method.
  /// Actual arguments must be substituted for formal parameters to derive
  /// the appropriate mutex expression in the lexical context where the function
  /// is called.  PrevCtx holds the context in which the arguments themselves
  /// should be evaluated; multiple calling contexts can be chained together
  /// by the lock_returned attribute.
  struct CallingContext {
    // The previous context; or 0 if none.
    CallingContext  *Prev;

    // The decl to which the attr is attached.
    const NamedDecl *AttrDecl;

    // Implicit object argument -- e.g. 'this'
    const Expr *SelfArg = nullptr;

    // Number of funArgs
    unsigned NumArgs = 0;

    // Function arguments
    const Expr *const *FunArgs = nullptr;

    // is Self referred to with -> or .?
    bool SelfArrow = false;

    CallingContext(CallingContext *P, const NamedDecl *D = nullptr)
        : Prev(P), AttrDecl(D) {}
  };

  SExprBuilder(til::MemRegionRef A) : Arena(A) {
    // FIXME: we don't always have a self-variable.
    SelfVar = new (Arena) til::Variable(nullptr);
    SelfVar->setKind(til::Variable::VK_SFun);
  }

  // Translate a clang expression in an attribute to a til::SExpr.
  // Constructs the context from D, DeclExp, and SelfDecl.
  CapabilityExpr translateAttrExpr(const Expr *AttrExp, const NamedDecl *D,
                                   const Expr *DeclExp, VarDecl *SelfD=nullptr);

  CapabilityExpr translateAttrExpr(const Expr *AttrExp, CallingContext *Ctx);

  // Translate a clang statement or expression to a TIL expression.
  // Also performs substitution of variables; Ctx provides the context.
  // Dispatches on the type of S.
  til::SExpr *translate(const Stmt *S, CallingContext *Ctx);
  til::SCFG  *buildCFG(CFGWalker &Walker);

  til::SExpr *lookupStmt(const Stmt *S);

  til::BasicBlock *lookupBlock(const CFGBlock *B) {
    return BlockMap[B->getBlockID()];
  }

  const til::SCFG *getCFG() const { return Scfg; }
  til::SCFG *getCFG() { return Scfg; }

private:
  // We implement the CFGVisitor API
  friend class CFGWalker;

  til::SExpr *translateDeclRefExpr(const DeclRefExpr *DRE,
                                   CallingContext *Ctx) ;
  til::SExpr *translateCXXThisExpr(const CXXThisExpr *TE, CallingContext *Ctx);
  til::SExpr *translateMemberExpr(const MemberExpr *ME, CallingContext *Ctx);
  til::SExpr *translateObjCIVarRefExpr(const ObjCIvarRefExpr *IVRE,
                                       CallingContext *Ctx);
  til::SExpr *translateCallExpr(const CallExpr *CE, CallingContext *Ctx,
                                const Expr *SelfE = nullptr);
  til::SExpr *translateCXXMemberCallExpr(const CXXMemberCallExpr *ME,
                                         CallingContext *Ctx);
  til::SExpr *translateCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE,
                                           CallingContext *Ctx);
  til::SExpr *translateUnaryOperator(const UnaryOperator *UO,
                                     CallingContext *Ctx);
  til::SExpr *translateBinOp(til::TIL_BinaryOpcode Op,
                             const BinaryOperator *BO,
                             CallingContext *Ctx, bool Reverse = false);
  til::SExpr *translateBinAssign(til::TIL_BinaryOpcode Op,
                                 const BinaryOperator *BO,
                                 CallingContext *Ctx, bool Assign = false);
  til::SExpr *translateBinaryOperator(const BinaryOperator *BO,
                                      CallingContext *Ctx);
  til::SExpr *translateCastExpr(const CastExpr *CE, CallingContext *Ctx);
  til::SExpr *translateArraySubscriptExpr(const ArraySubscriptExpr *E,
                                          CallingContext *Ctx);
  til::SExpr *translateAbstractConditionalOperator(
      const AbstractConditionalOperator *C, CallingContext *Ctx);

  til::SExpr *translateDeclStmt(const DeclStmt *S, CallingContext *Ctx);

  // Map from statements in the clang CFG to SExprs in the til::SCFG.
  using StatementMap = llvm::DenseMap<const Stmt *, til::SExpr *>;

  // Map from clang local variables to indices in a LVarDefinitionMap.
  using LVarIndexMap = llvm::DenseMap<const ValueDecl *, unsigned>;

  // Map from local variable indices to SSA variables (or constants).
  using NameVarPair = std::pair<const ValueDecl *, til::SExpr *>;
  using LVarDefinitionMap = CopyOnWriteVector<NameVarPair>;

  struct BlockInfo {
    LVarDefinitionMap ExitMap;
    bool HasBackEdges = false;

    // Successors yet to be processed
    unsigned UnprocessedSuccessors = 0;

    // Predecessors already processed
    unsigned ProcessedPredecessors = 0;

    BlockInfo() = default;
    BlockInfo(BlockInfo &&) = default;
    BlockInfo &operator=(BlockInfo &&) = default;
  };

  void enterCFG(CFG *Cfg, const NamedDecl *D, const CFGBlock *First);
  void enterCFGBlock(const CFGBlock *B);
  bool visitPredecessors() { return true; }
  void handlePredecessor(const CFGBlock *Pred);
  void handlePredecessorBackEdge(const CFGBlock *Pred);
  void enterCFGBlockBody(const CFGBlock *B);
  void handleStatement(const Stmt *S);
  void handleDestructorCall(const VarDecl *VD, const CXXDestructorDecl *DD);
  void exitCFGBlockBody(const CFGBlock *B);
  bool visitSuccessors() { return true; }
  void handleSuccessor(const CFGBlock *Succ);
  void handleSuccessorBackEdge(const CFGBlock *Succ);
  void exitCFGBlock(const CFGBlock *B);
  void exitCFG(const CFGBlock *Last);

  void insertStmt(const Stmt *S, til::SExpr *E) {
    SMap.insert(std::make_pair(S, E));
  }

  til::SExpr *getCurrentLVarDefinition(const ValueDecl *VD);

  til::SExpr *addStatement(til::SExpr *E, const Stmt *S,
                           const ValueDecl *VD = nullptr);
  til::SExpr *lookupVarDecl(const ValueDecl *VD);
  til::SExpr *addVarDecl(const ValueDecl *VD, til::SExpr *E);
  til::SExpr *updateVarDecl(const ValueDecl *VD, til::SExpr *E);

  void makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E);
  void mergeEntryMap(LVarDefinitionMap Map);
  void mergeEntryMapBackEdge();
  void mergePhiNodesBackEdge(const CFGBlock *Blk);

private:
  // Set to true when parsing capability expressions, which get translated
  // inaccurately in order to hack around smart pointers etc.
  static const bool CapabilityExprMode = true;

  til::MemRegionRef Arena;

  // Variable to use for 'this'.  May be null.
  til::Variable *SelfVar = nullptr;

  til::SCFG *Scfg = nullptr;

  // Map from Stmt to TIL Variables
  StatementMap SMap;

  // Indices of clang local vars.
  LVarIndexMap LVarIdxMap;

  // Map from clang to til BBs.
  std::vector<til::BasicBlock *> BlockMap;

  // Extra information per BB. Indexed by clang BlockID.
  std::vector<BlockInfo> BBInfo;

  LVarDefinitionMap CurrentLVarMap;
  std::vector<til::Phi *> CurrentArguments;
  std::vector<til::SExpr *> CurrentInstructions;
  std::vector<til::Phi *> IncompleteArgs;
  til::BasicBlock *CurrentBB = nullptr;
  BlockInfo *CurrentBlockInfo = nullptr;
};

// Dump an SCFG to llvm::errs().
void printSCFG(CFGWalker &Walker);

} // namespace threadSafety
} // namespace clang

#endif // LLVM_CLANG_THREAD_SAFETY_COMMON_H

{'repo_name': 'apple/swift-clang', 'stars': '668', 'repo_language': 'C++', 'file_name': '__init__.py', 'mime_type': 'text/plain', 'hash': -2807252079772653443, 'source_dataset': 'data'}


import React from 'react';

import { StyledIcon } from '../StyledIcon';

export const Inspect = props => (
  <StyledIcon viewBox='0 0 24 24' a11yTitle='Inspect' {...props}>
    <path fill='none' stroke='#000' strokeWidth='2' d='M5.5,21 C7.98528137,21 10,18.9852814 10,16.5 C10,14.0147186 7.98528137,12 5.5,12 C3.01471863,12 1,14.0147186 1,16.5 C1,18.9852814 3.01471863,21 5.5,21 Z M1,16 L1,7 L1,6.5 C1,4.01471863 3.01471863,2 5.5,2 L6,2 M23,16 L23,7 L23,6.5 C23,4.01471863 20.9852814,2 18.5,2 L18,2 M18.5,21 C20.9852814,21 23,18.9852814 23,16.5 C23,14.0147186 20.9852814,12 18.5,12 C16.0147186,12 14,14.0147186 14,16.5 C14,18.9852814 16.0147186,21 18.5,21 Z M10,17 C10,17 10,15 12,15 C14,15 14,17 14,17' />
  </StyledIcon>
);

{'repo_name': 'grommet/grommet-icons', 'stars': '180', 'repo_language': 'JavaScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 6005147089431510929, 'source_dataset': 'data'}


/*
 * Copyright 2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gradle.api.internal.artifacts.repositories.metadata;

import org.gradle.api.artifacts.ModuleIdentifier;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.MetaDataParser;
import org.gradle.internal.hash.ChecksumService;
import org.gradle.api.internal.artifacts.repositories.maven.MavenMetadataLoader;
import org.gradle.api.internal.artifacts.repositories.resolver.ResourcePattern;
import org.gradle.api.internal.artifacts.repositories.resolver.VersionLister;
import org.gradle.internal.component.external.model.ModuleDependencyMetadata;
import org.gradle.internal.component.external.model.maven.MutableMavenModuleResolveMetadata;
import org.gradle.internal.component.model.IvyArtifactName;
import org.gradle.internal.resolve.result.BuildableModuleVersionListingResolveResult;
import org.gradle.internal.resource.local.FileResourceRepository;

import javax.inject.Inject;
import java.util.List;

import static org.gradle.api.internal.artifacts.repositories.metadata.DefaultArtifactMetadataSource.getPrimaryDependencyArtifact;

public class MavenLocalPomMetadataSource extends DefaultMavenPomMetadataSource {

    @Inject
    public MavenLocalPomMetadataSource(MetadataArtifactProvider metadataArtifactProvider, MetaDataParser<MutableMavenModuleResolveMetadata> pomParser, FileResourceRepository fileResourceRepository, MavenMetadataValidator validator, MavenMetadataLoader mavenMetadataLoader, ChecksumService checksumService) {
        super(metadataArtifactProvider, pomParser, fileResourceRepository, validator, mavenMetadataLoader, checksumService);
    }

    @Override
    public void listModuleVersions(ModuleDependencyMetadata dependency, ModuleIdentifier module, List<ResourcePattern> ivyPatterns, List<ResourcePattern> artifactPatterns, VersionLister versionLister, BuildableModuleVersionListingResolveResult result) {
        IvyArtifactName dependencyArtifact = getPrimaryDependencyArtifact(dependency);
        versionLister.listVersions(module, dependencyArtifact, artifactPatterns, result);
    }
}

{'repo_name': 'gradle/gradle', 'stars': '10712', 'repo_language': 'Groovy', 'file_name': 'DefaultRuleActionAdapterTest.groovy', 'mime_type': 'text/plain', 'hash': 2961538894354833027, 'source_dataset': 'data'}


/**
 * The backgound color for tooltips.
 *
 * @type color
 * @group tooltip
 */
$v-tooltip-background-color: rgba(if(is-dark-color($v-background-color), scale-color($v-background-color, $lightness: 80%), scale-color($v-background-color, $lightness: -80%)), .9) !default;

/**
 * The font color for tooltips.
 *
 * @type color
 * @group tooltip
 */
$v-tooltip-font-color: valo-font-color(opacify($v-tooltip-background-color, 1), 1) !default;

/**
 * The font size for tooltips.
 *
 * @type size
 * @group tooltip
 */
$v-tooltip-font-size: max(12px, round($v-font-size * 0.86)) !default;

/**
 * The CSS box shadow for tooltips.
 *
 * @type list
 * @group tooltip
 */
$v-tooltip-box-shadow: 0 2px 12px rgba(#000, .2) !default;

/**
 * The vertical padding for tooltips.
 *
 * @type size
 * @group tooltip
 */
$v-tooltip-padding-vertical: round($v-unit-size/8) !default;

/**
 * The horizontal padding for tooltips.
 *
 * @type size
 * @group tooltip
 */
$v-tooltip-padding-horizontal: round($v-unit-size/4) !default;

/**
 * The backgound color for error tooltips.
 *
 * @type color
 * @group tooltip
 */
$v-tooltip-error-message-background-color: #fff !default;

/**
 * The font color for error tooltips.
 *
 * @type color
 * @group tooltip
 */
$v-tooltip-error-message-font-color: $v-error-indicator-color !default;

/**
 * The font color for error tooltips for level 'info'.
 *
 * @type color
 * @group tooltip
 */
$v-tooltip-error-message-level-info-font-color: $v-error-indicator-level-info-color !default;

/**
 * The font color for error tooltips for level 'warning'.
 *
 * @type color
 * @group tooltip
 */
$v-tooltip-error-message-level-warning-font-color: $v-error-indicator-level-warning-color !default;

/**
 * The font color for error tooltips for level 'error'.
 *
 * @type color
 * @group tooltip
 */
$v-tooltip-error-message-level-error-font-color: $v-error-indicator-level-error-color !default;

/**
 * The font color for error tooltips for level 'critical'.
 *
 * @type color
 * @group tooltip
 */
$v-tooltip-error-message-level-critical-font-color: $v-error-indicator-level-critical-color !default;

/**
 * The font color for error tooltips for level 'system'.
 *
 * @type color
 * @group tooltip
 */
$v-tooltip-error-message-level-system-font-color: $v-error-indicator-level-system-color !default;

/**
 * The corner radius for tooltips.
 *
 * @type size
 * @group tooltip
 */
$v-tooltip-border-radius: $v-border-radius - 1px !default;

/**
 * Outputs the selectors and styles for tooltip elements.
 *
 * @group tooltip
 */
@mixin valo-tooltip {
  .v-tooltip {
    @include valo-tooltip-style;

    div[style*="width"] {
      width: auto !important;
    }

    .v-errormessage {
      background-color: opacify($v-tooltip-error-message-background-color, 1);
      background-color: $v-tooltip-error-message-background-color;
      color: $v-tooltip-error-message-font-color;
      margin: -$v-tooltip-padding-vertical #{-$v-tooltip-padding-horizontal};
      padding: $v-tooltip-padding-vertical $v-tooltip-padding-horizontal;
      max-height: 10em;
      overflow: auto;
      font-weight: $v-font-weight + 100;

      h2:only-child {
        font: inherit;
        line-height: inherit;
      }
    }

    .v-errormessage-info {
      color: $v-tooltip-error-message-level-info-font-color;
    }

    .v-errormessage-warning {
      color: $v-tooltip-error-message-level-warning-font-color;
    }

    .v-errormessage-error {
      color: $v-tooltip-error-message-level-error-font-color;
    }

    .v-errormessage-critical {
      color: $v-tooltip-error-message-level-critical-font-color;
    }

    .v-errormessage-system {
      color: $v-tooltip-error-message-level-system-font-color;
    }

    .v-tooltip-text {
      max-height: 10em;
      overflow: auto;
      margin-top: $v-tooltip-padding-vertical * 2;
      pre {
        margin: 0px;
      }
    }

    .v-errormessage[aria-hidden="true"] + .v-tooltip-text {
      margin-top: 0;
    }

    h1,
    h2,
    h3,
    h4 {
      color: inherit;
    }

    pre.v-tooltip-pre {
      font: inherit;
      white-space: pre-wrap;
    }
  }
}

/**
 * Outputs the main styles for tooltip elements.
 *
 * @group tooltip
 */
@mixin valo-tooltip-style {
  background-color: $v-tooltip-background-color;
  @include box-shadow($v-tooltip-box-shadow);
  color: $v-tooltip-font-color;
  padding: $v-tooltip-padding-vertical $v-tooltip-padding-horizontal;
  border-radius: $v-tooltip-border-radius;
  max-width: 35em;
  overflow: hidden !important;
  font-size: $v-tooltip-font-size;
}

{'repo_name': 'vaadin/framework', 'stars': '1611', 'repo_language': 'Java', 'file_name': 'ServerRpcHandlerTest.java', 'mime_type': 'text/x-java', 'hash': 6615311731435665719, 'source_dataset': 'data'}


using System;
using System.Collections.Generic;

namespace Performance.EFCore
{
    public partial class Location
    {
        public Location()
        {
            ProductInventory = new HashSet<ProductInventory>();
            WorkOrderRouting = new HashSet<WorkOrderRouting>();
        }

        public short LocationID { get; set; }
        public string Name { get; set; }
        public decimal CostRate { get; set; }
        public decimal Availability { get; set; }
        public DateTime ModifiedDate { get; set; }

        public virtual ICollection<ProductInventory> ProductInventory { get; set; }
        public virtual ICollection<WorkOrderRouting> WorkOrderRouting { get; set; }
    }
}

{'repo_name': 'rowanmiller/Demo-EFCore', 'stars': '111', 'repo_language': 'C#', 'file_name': 'AssemblyInfo.cs', 'mime_type': 'text/plain', 'hash': -4431332878075673592, 'source_dataset': 'data'}


--TEST--
Oniguruma retry limit
--SKIPIF--
<?php
extension_loaded('mbstring') or die('skip mbstring not available');
if (!function_exists('mb_ereg')) die('skip mb_ereg not available');
if (version_compare(MB_ONIGURUMA_VERSION, '6.9.3') < 0) {
    die('skip requires Oniguruma >= 6.9.3');
}
?>
--FILE--
<?php

$regex = 'A(B|C+)+D|AC+X';
$str = 'ACCCCCCCCCCCCCCCCCCCX';
var_dump(mb_ereg($regex, $str));
ini_set('mbstring.regex_retry_limit', '100000');
var_dump(mb_ereg($regex, $str));

?>
--EXPECT--
int(1)
bool(false)

{'repo_name': 'php/php-src', 'stars': '27767', 'repo_language': 'C', 'file_name': 'echo.inc', 'mime_type': 'text/x-php', 'hash': 3489978492704163188, 'source_dataset': 'data'}


#!/bin/sh
set -e

echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"

SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"

install_framework()
{
  if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
    local source="${BUILT_PRODUCTS_DIR}/$1"
  elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
    local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
  elif [ -r "$1" ]; then
    local source="$1"
  fi

  local destination="${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"

  if [ -L "${source}" ]; then
      echo "Symlinked..."
      source="$(readlink "${source}")"
  fi

  # use filter instead of exclude so missing patterns dont' throw errors
  echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
  rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"

  local basename
  basename="$(basename -s .framework "$1")"
  binary="${destination}/${basename}.framework/${basename}"
  if ! [ -r "$binary" ]; then
    binary="${destination}/${basename}"
  fi

  # Strip invalid architectures so "fat" simulator / device frameworks work on device
  if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
    strip_invalid_archs "$binary"
  fi

  # Resign the code if required by the build settings to avoid unstable apps
  code_sign_if_enabled "${destination}/$(basename "$1")"

  # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
  if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
    local swift_runtime_libs
    swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u  && exit ${PIPESTATUS[0]})
    for lib in $swift_runtime_libs; do
      echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
      rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
      code_sign_if_enabled "${destination}/${lib}"
    done
  fi
}

# Signs a framework with the provided identity
code_sign_if_enabled() {
  if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
    # Use the current code_sign_identitiy
    echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
    echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements \"$1\""
    /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements "$1"
  fi
}

# Strip invalid architectures
strip_invalid_archs() {
  binary="$1"
  # Get architectures for current file
  archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
  stripped=""
  for arch in $archs; do
    if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then
      # Strip non-valid architectures in-place
      lipo -remove "$arch" -output "$binary" "$binary" || exit 1
      stripped="$stripped $arch"
    fi
  done
  if [[ "$stripped" ]]; then
    echo "Stripped $binary of architectures:$stripped"
  fi
}

{'repo_name': 'liu044100/SmileWeather', 'stars': '482', 'repo_language': 'Objective-C', 'file_name': 'Info.plist', 'mime_type': 'text/xml', 'hash': 7149171167571693668, 'source_dataset': 'data'}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Loyc.Ecs.Parser;
using Loyc.MiniTest;
using Loyc.Syntax;
using Loyc.Syntax.Lexing;
using S = Loyc.Syntax.CodeSymbols;

namespace Loyc.Ecs.Tests
{
	partial class EcsPrinterAndParserTests
	{
		[Test]
		public void PrintingRegressions()
		{
			Stmt("\"Hello\";", F.Literal("Hello")); // bug: was handled as an empty statement because Name.Name=="" for a literal
			Stmt("new Foo().x;", F.Dot(F.Call(S.New, F.Call(Foo)), x));            // this worked
			Stmt("new Foo().x();", F.Call(F.Dot(F.Call(S.New, F.Call(Foo)), x)));  // but this used to Assert
			// bug: 'public' attribute was suppressed by DropNonDeclarationAttributes
			Stmt("class Foo {\n  public Foo() { }\n}",
				F.Call(S.Class, Foo, F.List(), F.Braces(
					Attr(@public, F.Call(S.Constructor, F.Missing, Foo, F.List(), F.Braces())))),
				p => p.DropNonDeclarationAttributes = true);
			// bug: 'ref' and 'out' attributes were suppressed by DropNonDeclarationAttributes
			Option(Mode.PrintBothParseFirst,
				"Foo(out a, ref b, public static c, [#partial] x);", "Foo(out a, ref b, c, x);",
				F.Call(Foo, Attr(@out, a), Attr(@ref, b), Attr(@public, @static, c), Attr(@partial, x)),
				p => p.DropNonDeclarationAttributes = true);
			Stmt("private set;", F.Attr(F.Private, _("set")), p => p.DropNonDeclarationAttributes = true);
		}

		[Test]
		public void BugFixes()
		{
			LNode stmt;
			Expr("(a + b).b<c>()", F.Call(F.Dot(F.InParens(F.Call(S.Add, a, b)), F.Of(b, c))));
			Stmt("@`'+`(a, b)(c, 1);", F.Call(F.Call(S.Add, a, b), c, one)); // was: "c+1"
			// once printed as "partial #var(Foo, a);" which would be parsed as a method declaration
			Stmt("partial Foo a;", Attr(@partialWA, F.Vars(Foo, a)));
			Stmt("public partial alt class BinaryTree<T> { }", F.Attr(F.Public, partialWA, WordAttr("#alt"),
				F.Call(S.Class, F.Of(F.Id("BinaryTree"), T), F.List(), F.Braces())));
			Stmt("partial Foo.T x { get; }",  Attr(partialWA, F.Property(F.Dot(Foo, T), x, F.Braces(get))));
			Stmt("IFRange<char> ICloneable<IFRange<char>>.Clone() {\n  return Clone();\n}",
				F.Fn(F.Of(_("IFRange"), F.Char), F.Dot(F.Of(_("ICloneable"), F.Of(_("IFRange"), F.Char)), _("Clone")), F.List(), F.Braces(F.Call(S.Return, F.Call("Clone")))));
			Stmt("Foo<a> IDictionary<a, b>.Keys { }",
				F.Property(F.Of(Foo, a), F.Dot(F.Of(_("IDictionary"), a, b), _("Keys")), F.Braces()));
			Stmt("T IDictionary<Symbol, T>.this[Symbol x] { get; set; }",
				F.Property(T, F.Dot(F.Of(_("IDictionary"), _("Symbol"), T), F.@this), F.List(F.Var(_("Symbol"), x)), F.Braces(get, set)));
			Stmt("Func<T, T> x = delegate(T a) {\n  return a;\n};", F.Var(F.Of(_("Func"), T, T), x,
				F.Call(S.Lambda, F.List(F.Var(T, a)), F.Braces(F.Call(S.Return, a))).SetBaseStyle(NodeStyle.OldStyle)));
			Stmt("public static rule EmailAddress Parse(T x) { }",
				F.Attr(F.Public, _(S.Static), WordAttr("rule"), F.Fn(_("EmailAddress"), _("Parse"), F.List(F.Var(T, x)), F.Braces())));
			// Currently we're not trying to treat this as a keyword
			Stmt("dynamic Foo();", F.Fn(_("dynamic"), Foo, F.List()));
			Stmt("dynamic x;", F.Var(_("dynamic"), x));

			Token[] token = new[] { new Token((int)TokenType.Literal, 0, 0, 0, 'a') };
			var tree = new TokenTree(F.File, (ICollection<Token>)token);
			var lexer = F.Call(_("LLLPG"), _("lexer"), F.Braces(
					Attr(F.Public, F.Property(_("rule"), a, F.Literal(tree))))).SetBaseStyle(NodeStyle.Special);
			Stmt("LLLPG (lexer) {\n  public rule a @{ 'a' };\n}", lexer, Mode.ParserTest);
			Stmt("LLLPG (lexer) {\n  public rule a => @{ 'a' };\n}", lexer);
			// 2016-04 bug: ForEachStmt failed to call Up() before returning
			Stmt("{\n  foreach (var x in Foo) { }\n  Foo();\n}",
				F.Braces(F.Call(S.ForEach, F.Vars(F.Missing, x), Foo, F.Braces()), F.Call(Foo)));
			// 2016-10 bug: `property:` was applied to both attributes
			stmt = F.Attr(a, F.Call(S.NamedArg, F.Id("property"), b), F.Private, F.Property(F.String, Foo, F.Braces(get, set)));
			Stmt("[a, property: b] private string Foo { get; set; }", stmt);
			Stmt("[a] [property: b] public string Foo { get; set; }", stmt.WithAttrChanged(2, @public), Mode.ParserTest);
			Stmt("a = (var b = x);", F.Call(S.Assign, a, F.InParens(F.Var(F.Missing, b, x))));

			// 2017-01 bug: operator>> and operator<< wouldn't parse
			// (because there is no dedicated token for >> or <<)
			stmt = Attr(F.Id(S.Static), F.Fn(F.Int32, Attr(trivia_operator, _(S.Shl)), F.List(F.Var(Foo, x), F.Var(F.Int32, a)),
			                            F.Braces(F.Call(S.Return, F.Call(S.Shl, x, a)))));
			Stmt("static int operator<<(Foo x, int a) {\n  return x << a;\n}", stmt);
			stmt = Attr(F.Id(S.Static), F.Fn(F.Int32, Attr(trivia_operator, _(S.Shr)), F.List(F.Var(Foo, x), F.Var(F.Int32, a)),
			                            F.Braces(F.Call(S.Return, F.Call(S.Shr, x, a)))));
			Stmt("static int operator>>(Foo x, int a) {\n  return x >> a;\n}", stmt);

			// https://github.com/qwertie/ecsharp/issues/90
			Expr("({\n  Foo;\n})", F.InParens(F.Braces(Foo)));
			Stmt("({\n  stuff;\n});", F.InParens(F.Braces(_("stuff"))));
		}

		[Test]
		public void PrecedenceChallenges()
		{
			Expr(@"a.([] -b)",       F.Dot(a, F.Call(S._Negate, b)));
			Expr(@"a.([] -b).c",     F.Dot(a, F.Call(S._Negate, b), c));
			Expr(@"a.([] -b.c)",     F.Dot(a, F.Call(S._Negate, F.Dot(b, c))));
			Expr(@"a::([] -b)",      F.Call(S.ColonColon, a, F.Call(S._Negate, b)));
			Expr(@"a.b->c",          F.Call(S.RightArrow, F.Dot(a, b), c));
			Expr(@"a->([] b.c)",     F.Call(S.RightArrow, a, F.Dot(b, c)));
			Expr(@"a.(-b)(c)",       F.Call(F.Dot(a, F.InParens(F.Call(S._Negate, b))), c));
			// The printer should revert to prefix notation in certain cases in
			// order to faithfully represent the original tree.
			Expr(@"a * b + c",       F.Call(S.Add, F.Call(S.Mul, a, b), c));
			Expr(@"(a + b) * c",     F.Call(S.Mul, F.InParens(F.Call(S.Add, a, b)), c));
			Expr(@"@`'+`(a, b) * c", F.Call(S.Mul, F.Call(S.Add, a, b), c));
			Expr(@"--a++",           F.Call(S.PreDec, F.Call(S.PostInc, a)));
			Expr(@"(--a)++",         F.Call(S.PostInc, F.InParens(F.Call(S.PreDec, a))));
			Expr(@"@`'--`(a)++",     F.Call(S.PostInc, F.Call(S.PreDec, a)));
			LNode a_b = F.Dot(a, b), a_b__c = F.Call(S.NullDot, F.Dot(a, b), c);
			Expr(@"a.b?.c.x",        F.Call(S.NullDot, a_b, F.Dot(c, x)));
			Expr(@"(a.b?.c).x",      F.Dot(F.InParens(a_b__c), x));
			Expr(@"@`'?.`(a.b, c).x", F.Dot(a_b__c, x));
			Expr(@"++$x",            F.Call(S.PreInc, F.Call(S.Substitute, x)));
			Expr(@"++$([Foo] x)",    F.Call(S.PreInc, F.Call(S.Substitute, Attr(Foo, x))));
			Expr(@"a ? b : c",       F.Call(S.QuestionMark, a, b, c));
			Expr(@"a ? b + x : c + x",  F.Call(S.QuestionMark, a, F.Call(S.Add, b, x), F.Call(S.Add, c, x)));
			Expr(@"a ? b = x : (c = x)",F.Call(S.QuestionMark, a, F.Assign(b, x), F.InParens(F.Assign(c, x))));
			Expr(@"++$x",            F.Call(S.PreInc, F.Call(S.Substitute, x))); // easy
			Expr(@"++--x",           F.Call(S.PreInc, F.Call(S.PreDec, x)));     // easy
			// Note: It was decided not to bother supporting `$++x`, or even
			// `$...x` which would be more convenient than writing `$(...x)`
			Expr(@"$(++x)", F.Call(S.Substitute, F.Call(S.PreInc, x)));
			Expr(@".(~x)",          F.Call(S.Dot, F.Call(S.NotBits, x)));
			Expr(@"x++.Foo",        F.Dot(F.Call(S.PostInc, x), Foo));
			Expr(@"x++.Foo()",      F.Call(F.Dot(F.Call(S.PostInc, x), Foo)));
			Expr(@"x++--.Foo",      F.Dot(F.Call(S.PostDec, F.Call(S.PostInc, x)), Foo));
			// Due to the high precedence of `$`, its argument must be in parens
			// unless it is trivial.
			Expr(@"$x",             F.Call(S.Substitute, x));
			Expr(@"$(x++)",         F.Call(S.Substitute, F.Call(S.PostInc, x)));
			Expr(@"$(Foo(x))",      F.Call(S.Substitute, F.Call(Foo, x)));
			Expr(@"$(a<b>)",        F.Call(S.Substitute, F.Of(a, b)));
			Expr(@"$(a.b)",         F.Call(S.Substitute, F.Dot(a, b)));
			Expr(@"$(a.b<c>)",      F.Call(S.Substitute, F.Dot(a, F.Of(b, c))));
			Expr(@"$((Foo) x)",     F.Call(S.Substitute, F.Call(S.Cast, x, Foo)));
			Expr(@"$(x(->Foo))",    F.Call(S.Substitute, Alternate(F.Call(S.Cast, x, Foo))));
		}

		[Test]
		public void IsAsChallenges()
		{
			Expr("x / a as Foo / b", F.Call(S.Div, F.Call(S.As, F.Call(S.Div, x, a), Foo), b));
			Expr("x / a as Foo? / b", F.Call(S.Div, F.Call(S.As, F.Call(S.Div, x, a), F.Of(_(S.QuestionMark), Foo)), b));
			Expr("x / a is Foo? / b", F.Call(S.Div, F.Call(S.Is, F.Call(S.Div, x, a), F.Of(_(S.QuestionMark), Foo)), b));
			Expr("x / a as Foo? < b", F.Call(S.LT,  F.Call(S.As, F.Call(S.Div, x, a), F.Of(_(S.QuestionMark), Foo)), b));
			Expr("x / a is Foo? < b", F.Call(S.LT,  F.Call(S.Is, F.Call(S.Div, x, a), F.Of(_(S.QuestionMark), Foo)), b));
		}

		[Test(Fails = "Failure caused by a bug in LLLPG")]
		public void IsAsChallenges2()
		{
			Expr("x / a as Foo < b", F.Call(S.LT, F.Call(S.As, F.Call(S.Div, x, a), Foo), b));
		}

		[Test]
		public void SpecialEcsChallenges()
		{
			Expr("Foo x = a",            F.Var(Foo, x.Name, a));
			Expr("(Foo x = a) + 1",      F.Call(S.Add, F.InParens(F.Var(Foo, x.Name, a)), one));
			// Sadly, the way the printer uses parens in this situation does not
			// round-trip so we need separate printer and parser tests. Perhaps
			// ideally the parser would ignore parens when there's an attr list,
			// but then the printer might have to print extra parens in some cases.
			Expr("([] Foo x = a) + 1",   F.Call(S.Add, F.Var(Foo, x.Name, a), one));
			Expr("([] Foo a) = x",       F.Assign(F.Vars(Foo, a), x));
			Expr("([] Foo a) + x",       F.Call(S.Add, F.Vars(Foo, a), x));
			Expr("x + ([] Foo a)",       F.Call(S.Add, x, F.Vars(Foo, a)));
			Expr("#label(Foo)",          F.Call(S.Label, Foo));
			Stmt("Foo:",                 F.Call(S.Label, Foo));
			LNode Foo_a = F.Call(S.NamedArg, Foo, a);
			Expr("Foo: a",               Foo_a);
			Stmt("@`'::=`(Foo, a);",     Foo_a);
			Expr("@`'::=`(Foo(x), a)",   F.Call(S.NamedArg, F.Call(Foo, x), a));
			Expr("b + (Foo: a)",         F.Call(S.Add, b, F.InParens(Foo_a)));
			Expr("b + @`'::=`(Foo, a)", F.Call(S.Add, b, Foo_a));
			// Ambiguity between multiplication and pointer declarations:
			// - multiplication at stmt level => prefix notation, except in #result or when lhs is not a complex identifier
			// - pointer declaration inside expr => generic, not pointer, notation
			Expr("a * b",                F.Call(S.Mul, a, b));
			Stmt("a `'*` b;",             F.Call(S.Mul, a, b));
			Stmt("a() * b;",             F.Call(S.Mul, F.Call(a), b));
			Expr("#result(a * b)",       F.Result(F.Call(S.Mul, a, b)));
			Stmt("{\n  a * b\n}",        F.Braces(F.Result(F.Call(S.Mul, a, b))));
			Stmt("Foo* a = x;",          F.Var(F.Of(_(S._Pointer), Foo), a.Name, x));
			// Ambiguity between bitwise not and destructor declarations
			Expr("~Foo()",               F.Call(S.NotBits, F.Call(Foo)));
			Stmt("@`'~`(Foo());",        F.Call(S.NotBits, F.Call(Foo)));
			Stmt("~Foo;",                F.Call(S.NotBits, Foo));
			Stmt("$Foo $x;",             F.Var(F.Call(S.Substitute, Foo), F.Call(S.Substitute, x)));
			Stmt("$Foo $x = 1;",         F.Var(F.Call(S.Substitute, Foo), F.Call(S.Substitute, x), one));
			Stmt("$Foo<$2> $x = 1;",     F.Var(F.Of(F.Call(S.Substitute, Foo), F.Call(S.Substitute, two)),
			                                                              F.Call(S.Substitute, x), one));
			Expr("$Foo $x = 1",          F.Var(F.Call(S.Substitute, Foo), F.Call(S.Substitute, x), one));
		}

		[Test]
		public void TypeContext()
		{
			// Certain syntax trees can print differently in a "type context" than elsewhere.
			var FooBracks = F.Call(S.IndexBracks, Foo);
			var FooArray = F.Of(_(S.Array), Foo);
			var Foo2DArray = F.Of(_(S.TwoDimensionalArray), Foo);
			var FooNArray = F.Of(_(S.Array), F.Of(S.QuestionMark, Foo));
			var FooNullable = F.Of(_(S.QuestionMark), Foo);
			var FooPointer = F.Of(_(S._Pointer), Foo);
			Expr("Foo[]",             FooBracks);
			Expr("@`'[]`<Foo>",        FooArray);
			Expr("@`'?`<Foo>",         FooNullable);
			Expr("@`'*`<Foo>",         FooPointer);
			Stmt("#var(Foo[], a);",   F.Vars(FooBracks, a));
			Stmt("Foo[] a;",          F.Vars(FooArray, a));
			Stmt("Foo?[] a;",         F.Vars(FooNArray, a));
			Stmt("typeof(Foo?);",     F.Call(S.Typeof, FooNullable));
			Stmt("default(Foo*);",    F.Call(S.Default, FooPointer));
			Stmt("(Foo[]) a;",        F.Call(S.Cast, a, FooArray));
			Stmt("(Foo?[]) a;",       F.Call(S.Cast, a, FooNArray));
			Stmt("(Foo[,]) a;",       F.Call(S.Cast, a, Foo2DArray));
			Stmt("a(->Foo?);",        Alternate(F.Call(S.Cast, a, FooNullable)));
			Stmt("a(as Foo*);",       Alternate(F.Call(S.As, a, FooPointer)));
			Stmt("Foo!(#(Foo[]));",   F.Of(Foo, F.List(FooBracks)));
			Stmt("Foo!(#(@`'*`<Foo>));", F.Of(Foo, F.List(FooPointer)));
			Expr("checked(Foo[])",    F.Call(S.Checked, FooBracks));
			Stmt("Foo<a*> x;",        F.Vars(F.Of(Foo, F.Of(_(S._Pointer), a)), x));
			Stmt("(Foo, Foo x) a, b;", F.Vars(F.Of(_(S.Tuple), Foo, F.Var(Foo, x)), a, b));
		}

		[Test]
		public void TypeContextTuples()
		{
			// Type Tuples are printed in a "type context" (Ambiguity.TypeContext)
			// which changes printing behavior, e.g. Foo[10] normally means
			// @`'suf[]`(Foo), but in a type context it means @`'of`(@`'[]`, Foo)
			// (which can also be written as @`'[]`<Foo>)
			var FooBracks = F.Call(S.IndexBracks, Foo);
			var FooArray = F.Of(_(S.Array), Foo);
			var FooNullable = F.Of(_(S.QuestionMark), Foo);
			LNode stmt;
			stmt = F.Vars(F.Of(_(S.Tuple), F.Var(FooNullable, x), FooArray), a, b);
			Stmt("(Foo? x, Foo[]) a, b;", stmt);
			Stmt("tuple!(2 + 2);",    F.Of(_("tuple"), F.Call(S.Add, two, two)));
			Stmt("@tuple!(2 + 2);",   F.Of(_("tuple"), F.Call(S.Add, two, two)), Mode.ParserTest);
			Stmt("@'tuple !(2 + 2);", F.Of(_("'tuple"), F.Call(S.Add, two, two)));
			// In a type context, FooBracks shows as @`'suf[]`(Foo) instead of the usual Foo[]
			stmt = F.Vars(F.Of(_(S.Tuple), F.Var(FooNullable, x), FooBracks), a, b);
			Stmt("#var(@'tuple !(Foo? x, @`'suf[]`(Foo)), a, b);", stmt);
			stmt = F.Vars(F.Of(_(S.Tuple), F.Var(FooNullable, x), F.Var(FooBracks, T)), a, b);
			Stmt("#var(@'tuple !(Foo? x, #var(Foo[], T)), a, b);", stmt);
		}
	}
}

{'repo_name': 'qwertie/ecsharp', 'stars': '128', 'repo_language': 'C#', 'file_name': 'TestMatchMacro.cs', 'mime_type': 'text/plain', 'hash': -9192845436832569408, 'source_dataset': 'data'}


https = require 'https'
http = require 'http'
{parse} = require 'url'
ProgressBar = require 'progress'
urlmod = require 'url'
request = require 'request'

#========================================================================

class Request

  constructor : ({url, uri, @headers, progress}) ->
    url = url or uri
    @_res = null
    @_data = []
    @_err = null
    @uri = @url = if typeof(url) is 'string' then parse(url) else url
    @_bar = null
    @_opts = { progress }

  #--------------------

  run : (cb) ->
    @_done_cb = cb
    @_launch()

  #--------------------

  _make_opts : () ->
    opts =
      host : @url.hostname
      port : @url.port or (if @url.protocol is 'https:' then 443 else 80)
      path : @url.path
      method : 'GET'
      headers : @headers

    if (@url.protocol is 'https:')
      opts.mod = https
      opts.agent = new https.Agent opts
    else
      opts.mod = http

    opts

  #--------------------

  _launch : () ->
    opts = @_make_opts()
    req = opts.mod.request opts, (res) =>
      if @_opts.progress? and (l = res.headers?["content-length"])? and
         not(isNaN(l = parseInt(l,10))) and l > @_opts.progress
        @_bar = new ProgressBar "Download #{@url.path} [:bar] :percent :etas (#{l} bytes total)", {
          complete : "=",
          incomplete : ' ',
          width : 50,
          total : l
        }
      @_res = res
      res.request = @
      res.on 'data', (d) =>
        @_data.push d
        @_bar?.tick(d.length)
      res.on 'end',  () => @_finish()
    req.end()
    req.on 'error', (e) =>
      @_err = e
      @_finish()

  #--------------------

  _finish : () ->
    cb = @_done_cb
    @_done_cb = null
    cb @_err, @_res, (Buffer.concat @_data)

#=============================================================================

single = (opts, cb) -> (new Request opts).run cb

#=============================================================================

format_url = (u) -> if (typeof u is 'string') then u else urlmod.format(u)

#-----------

request_progress = (opts, cb) ->
  lim = opts.maxRedirects or 10
  res = body = null
  found = false
  opts.url = parse(opts.url) if typeof(opts.url) is 'string'
  for i in [0...lim]
    prev_url = opts.url
    await single opts, defer err, res, body
    if err? then break
    else if not (res.statusCode in [301, 302])
      found = true
      break
    else if not (url = res.headers?.location)?
      err = new Error "Can't find a location in header for redirect"
      break
    else
      url = parse(url)
      unless url.host
        url.host = prev_url.host
        url.hostname = prev_url.hostname
        url.port = prev_url.port
        url.protocol = prev_url.protocol
      opts.url = url

  err = if err? then err
  else if not found then new Error "Too many redirects"
  else if (res.statusCode >= 200 and res.statusCode < 300) then null
  else new Error "In #{format_url opts.url}: HTTP failure, code #{res.statusCode}"

  cb err, res, body

#============================================================================

request_mikeal = (opts, cb) ->
  opts.encoding = null
  rv = new iced.Rendezvous()
  url = opts.url or opts.uri
  url_s = if typeof(url) is 'object' then url.format() else url
  request opts, rv.id(true).defer(err, res, body)

  process.stderr.write("Downloading...")
  loop
    setTimeout rv.id(false).defer(), 100
    await rv.wait defer which
    if which then break
    process.stderr.write(".")
  process.stderr.write("..done\n")
  cb err, res, body

#============================================================================

exports.request = (opts, cb) ->
  if opts.proxy? then request_mikeal opts, cb
  else request_progress opts, cb

#============================================================================

{'repo_name': 'keybase/node-client', 'stars': '298', 'repo_language': 'CoffeeScript', 'file_name': 'versions.iced', 'mime_type': 'text/plain', 'hash': -3187765781829770480, 'source_dataset': 'data'}


//このコードはT4 Templateによって自動生成されています。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Windows;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Controls.Primitives;
using System.ComponentModel;
using System.Windows.Interop;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Documents.Serialization;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
using System.Windows.Annotations;
using System.Windows.Ink;
using System.Windows.Automation.Peers;
using System.Windows.Markup.Localizer;
using System.Windows.Media.Imaging;
using System.IO.Packaging;
using System.Security.RightsManagement;
using System.Windows.Threading;
using System.Windows.Media.Effects;
using System.Windows.Shell;
using System.Security.Permissions;
using System.Windows.Annotations.Storage;
using System.Diagnostics;

namespace Livet.Converters
{
	///
    /// DataGridHeadersVisibility列挙体とbool値の相互変換を行うIValueConverterです。
    ///
    public class DataGridHeadersVisibilityAndBooleanConverter : IValueConverter
    {
        //VM→View
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (!(value is bool)) throw new ArgumentException();

            if ((bool)value)
            {
                if (_isConvertWhenTrueSet)
                {
                    return ConvertWhenTrue;
                }
            }
            else
            {
                if (_isConvertWhenFalseSet)
                {
                    return ConvertWhenFalse;
                }
            }

            return DependencyProperty.UnsetValue;
        }

        private bool _isConvertWhenTrueSet;
        private DataGridHeadersVisibility _convertWhenTrue;
		///
        /// ソース値がTrueの際にどのDataGridHeadersVisibility列挙体メンバーに変換するかを指定、または取得します。
        ///
        public DataGridHeadersVisibility ConvertWhenTrue
        {
            get
            {
                return _convertWhenTrue;
            }
            set
            {
                _convertWhenTrue = value;
                _isConvertWhenTrueSet = true;
            }
        }

        private bool _isConvertWhenFalseSet;
        private DataGridHeadersVisibility _convertWhenFalse;
		///
        /// ソース値がFalseの際にどのDataGridHeadersVisibility列挙体メンバーに変換するかを指定、または取得します。
        ///
        public DataGridHeadersVisibility ConvertWhenFalse
        {
            get
            {
                return _convertWhenFalse;
            }
            set
            {
                _convertWhenFalse = value;
                _isConvertWhenFalseSet = true;
            }
        }

        //View→VM
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (!(value is DataGridHeadersVisibility)) throw new ArgumentException();

            var enumValue = (DataGridHeadersVisibility)value;

			switch(enumValue.ToString())
			{
				case "None":
					if (_isConvertBackWhenNoneSet)
					{
						return ConvertBackWhenNone;
					}
					break;
				case "Column":
					if (_isConvertBackWhenColumnSet)
					{
						return ConvertBackWhenColumn;
					}
					break;
				case "Row":
					if (_isConvertBackWhenRowSet)
					{
						return ConvertBackWhenRow;
					}
					break;
				case "All":
					if (_isConvertBackWhenAllSet)
					{
						return ConvertBackWhenAll;
					}
					break;
				default:
					throw new ArgumentException();
			}

            if (_isConvertBackDefaultBooleanValueSet)
            {
                return ConvertBackDefaultBooleanValue;
            }

            return DependencyProperty.UnsetValue;
        }

        private bool _isConvertBackDefaultBooleanValueSet;
        private bool _convertBackDefaultBooleanValue;
		///
        /// DataGridHeadersVisibilityの値をbool値に変換する際のデフォルト値を指定、または取得します。
        ///
        public bool ConvertBackDefaultBooleanValue
        {
            get
            {
                return _convertBackDefaultBooleanValue;
            }
            set
            {
                _convertBackDefaultBooleanValue = value;
				_isConvertBackDefaultBooleanValueSet = true;
            }
        }

        private bool _isConvertBackWhenNoneSet;
        private bool _convertBackWhenNone;
		///
        /// DataGridHeadersVisibilityの値がNoneの際True/Falseいずれに変換するのかを指定、または取得します。

        /// この値が設定されておらず、ConvertBackDefaultBooleanValueが設定されている場合はConvertBackDefaultBooleanValueに従います。
        ///
        public bool ConvertBackWhenNone
        {
            get
            {
                return _convertBackWhenNone;
            }
            set
            {
                _convertBackWhenNone = value;
                _isConvertBackWhenNoneSet = true;
            }
        }
        private bool _isConvertBackWhenColumnSet;
        private bool _convertBackWhenColumn;
		///
        /// DataGridHeadersVisibilityの値がColumnの際True/Falseいずれに変換するのかを指定、または取得します。

        /// この値が設定されておらず、ConvertBackDefaultBooleanValueが設定されている場合はConvertBackDefaultBooleanValueに従います。
        ///
        public bool ConvertBackWhenColumn
        {
            get
            {
                return _convertBackWhenColumn;
            }
            set
            {
                _convertBackWhenColumn = value;
                _isConvertBackWhenColumnSet = true;
            }
        }
        private bool _isConvertBackWhenRowSet;
        private bool _convertBackWhenRow;
		///
        /// DataGridHeadersVisibilityの値がRowの際True/Falseいずれに変換するのかを指定、または取得します。

        /// この値が設定されておらず、ConvertBackDefaultBooleanValueが設定されている場合はConvertBackDefaultBooleanValueに従います。
        ///
        public bool ConvertBackWhenRow
        {
            get
            {
                return _convertBackWhenRow;
            }
            set
            {
                _convertBackWhenRow = value;
                _isConvertBackWhenRowSet = true;
            }
        }
        private bool _isConvertBackWhenAllSet;
        private bool _convertBackWhenAll;
		///
        /// DataGridHeadersVisibilityの値がAllの際True/Falseいずれに変換するのかを指定、または取得します。

        /// この値が設定されておらず、ConvertBackDefaultBooleanValueが設定されている場合はConvertBackDefaultBooleanValueに従います。
        ///
        public bool ConvertBackWhenAll
        {
            get
            {
                return _convertBackWhenAll;
            }
            set
            {
                _convertBackWhenAll = value;
                _isConvertBackWhenAllSet = true;
            }
        }
    }
}

{'repo_name': 'runceel/Livet', 'stars': '176', 'repo_language': 'C#', 'file_name': 'Command.cs', 'mime_type': 'text/plain', 'hash': 2166698625143376199, 'source_dataset': 'data'}


gauge
=====

A nearly stateless terminal based horizontal gauge / progress bar.

```javascript
var Gauge = require("gauge")

var gauge = new Gauge()

gauge.show("test", 0.20)

gauge.pulse("this")

gauge.hide()
```

![](gauge-demo.gif)

### CHANGES FROM 1.x

Gauge 2.x is breaking release, please see the [changelog] for details on
what's changed if you were previously a user of this module.

[changelog]: CHANGELOG.md

### THE GAUGE CLASS

This is the typical interface to the module– it provides a pretty
fire-and-forget interface to displaying your status information.

```
var Gauge = require("gauge")

var gauge = new Gauge([stream], [options])
```

* **stream** – *(optional, default STDERR)* A stream that progress bar
  updates are to be written to.  Gauge honors backpressure and will pause
  most writing if it is indicated.
* **options** – *(optional)* An option object.

Constructs a new gauge. Gauges are drawn on a single line, and are not drawn
if **stream** isn't a tty and a tty isn't explicitly provided.

If **stream** is a terminal or if you pass in **tty** to **options** then we
will detect terminal resizes and redraw to fit.  We do this by watching for
`resize` events on the tty.  (To work around a bug in verisons of Node prior
to 2.5.0, we watch for them on stdout if the tty is stderr.) Resizes to
larger window sizes will be clean, but shrinking the window will always
result in some cruft.

**IMPORTANT:** If you prevously were passing in a non-tty stream but you still
want output (for example, a stream wrapped by the `ansi` module) then you
need to pass in the **tty** option below, as `gauge` needs access to
the underlying tty in order to do things like terminal resizes and terminal
width detection.

The **options** object can have the following properties, all of which are
optional:

* **updateInterval**: How often gauge updates should be drawn, in miliseconds.
* **fixedFramerate**: Defaults to false on node 0.8, true on everything
  else.  When this is true a timer is created to trigger once every
  `updateInterval` ms, when false, updates are printed as soon as they come
  in but updates more often than `updateInterval` are ignored.  The reason
  0.8 doesn't have this set to true is that it can't `unref` its timer and
  so it would stop your program from exiting– if you want to use this
  feature with 0.8 just make sure you call `gauge.disable()` before you
  expect your program to exit.
* **themes**: A themeset to use when selecting the theme to use. Defaults
  to `gauge/themes`, see the [themes] documentation for details.
* **theme**: Select a theme for use, it can be a:
  * Theme object, in which case the **themes** is not used.
  * The name of a theme, which will be looked up in the current *themes*
    object.
  * A configuration object with any of `hasUnicode`, `hasColor` or
    `platform` keys, which if wlll be used to override our guesses when making
    a default theme selection.

  If no theme is selected then a default is picked using a combination of our
  best guesses at your OS, color support and unicode support.
* **template**: Describes what you want your gauge to look like.  The
  default is what npm uses.  Detailed [documentation] is later in this
  document.
* **hideCursor**: Defaults to true.  If true, then the cursor will be hidden
  while the gauge is displayed.
* **tty**: The tty that you're ultimately writing to.  Defaults to the same
  as **stream**.  This is used for detecting the width of the terminal and
  resizes. The width used is `tty.columns - 1`. If no tty is available then
  a width of `79` is assumed.
* **enabled**: Defaults to true if `tty` is a TTY, false otherwise.  If true
  the gauge starts enabled.  If disabled then all update commands are
  ignored and no gauge will be printed until you call `.enable()`.
* **Plumbing**: The class to use to actually generate the gauge for
  printing.  This defaults to `require('gauge/plumbing')` and ordinarly you
  shouldn't need to override this.
* **cleanupOnExit**: Defaults to true. Ordinarily we register an exit
  handler to make sure your cursor is turned back on and the progress bar
  erased when your process exits, even if you Ctrl-C out or otherwise exit
  unexpectedly. You can disable this and it won't register the exit handler.

[has-unicode]: https://www.npmjs.com/package/has-unicode
[themes]: #themes
[documentation]: #templates

#### `gauge.show(section | status, [completed])`

The first argument is either the section, the name of the current thing
contributing to progress, or an object with keys like **section**,
**subsection** & **completed** (or any others you have types for in a custom
template).  If you don't want to update or set any of these you can pass
`null` and it will be ignored.

The second argument is the percent completed as a value between 0 and 1.
Without it, completion is just not updated. You'll also note that completion
can be passed in as part of a status object as the first argument. If both
it and the completed argument are passed in, the completed argument wins.

#### `gauge.hide([cb])`

Removes the gauge from the terminal.  Optionally, callback `cb` after IO has
had an opportunity to happen (currently this just means after `setImmediate`
has called back.)

It turns out this is important when you're pausing the progress bar on one
filehandle and printing to another– otherwise (with a big enough print) node
can end up printing the "end progress bar" bits to the progress bar filehandle
while other stuff is printing to another filehandle. These getting interleaved
can cause corruption in some terminals.

#### `gauge.pulse([subsection])`

* **subsection** – *(optional)* The specific thing that triggered this pulse

Spins the spinner in the gauge to show output.  If **subsection** is
included then it will be combined with the last name passed to `gauge.show`.

#### `gauge.disable()`

Hides the gauge and ignores further calls to `show` or `pulse`.

#### `gauge.enable()`

Shows the gauge and resumes updating when `show` or `pulse` is called.

#### `gauge.isEnabled()`

Returns true if the gauge is enabled.

#### `gauge.setThemeset(themes)`

Change the themeset to select a theme from. The same as the `themes` option
used in the constructor. The theme will be reselected from this themeset.

#### `gauge.setTheme(theme)`

Change the active theme, will be displayed with the next show or pulse. This can be:

* Theme object, in which case the **themes** is not used.
* The name of a theme, which will be looked up in the current *themes*
  object.
* A configuration object with any of `hasUnicode`, `hasColor` or
  `platform` keys, which if wlll be used to override our guesses when making
  a default theme selection.

If no theme is selected then a default is picked using a combination of our
best guesses at your OS, color support and unicode support.

#### `gauge.setTemplate(template)`

Change the active template, will be displayed with the next show or pulse

### Tracking Completion

If you have more than one thing going on that you want to track completion
of, you may find the related [are-we-there-yet] helpful.  It's `change`
event can be wired up to the `show` method to get a more traditional
progress bar interface.

[are-we-there-yet]: https://www.npmjs.com/package/are-we-there-yet

### THEMES

```
var themes = require('gauge/themes')

// fetch the default color unicode theme for this platform
var ourTheme = themes({hasUnicode: true, hasColor: true})

// fetch the default non-color unicode theme for osx
var ourTheme = themes({hasUnicode: true, hasColor: false, platform: 'darwin'})

// create a new theme based on the color ascii theme for this platform
// that brackets the progress bar with arrows
var ourTheme = themes.newTheme(theme(hasUnicode: false, hasColor: true}), {
  preProgressbar: '→',
  postProgressbar: '←'
})
```

The object returned by `gauge/themes` is an instance of the `ThemeSet` class.

```
var ThemeSet = require('gauge/theme-set')
var themes = new ThemeSet()
// or
var themes = require('gauge/themes')
var mythemes = themes.newThemeset() // creates a new themeset based on the default themes
```

#### themes(opts)
#### themes.getDefault(opts)

Theme objects are a function that fetches the default theme based on
platform, unicode and color support.

Options is an object with the following properties:

* **hasUnicode** - If true, fetch a unicode theme, if no unicode theme is
  available then a non-unicode theme will be used.
* **hasColor** - If true, fetch a color theme, if no color theme is
  available a non-color theme will be used.
* **platform** (optional) - Defaults to `process.platform`.  If no
  platform match is available then `fallback` is used instead.

If no compatible theme can be found then an error will be thrown with a
`code` of `EMISSINGTHEME`.

#### themes.addTheme(themeName, themeObj)
#### themes.addTheme(themeName, [parentTheme], newTheme)

Adds a named theme to the themeset.  You can pass in either a theme object,
as returned by `themes.newTheme` or the arguments you'd pass to
`themes.newTheme`.

#### themes.getThemeNames()

Return a list of all of the names of the themes in this themeset. Suitable
for use in `themes.getTheme(…)`.

#### themes.getTheme(name)

Returns the theme object from this theme set named `name`.

If `name` does not exist in this themeset an error will be thrown with
a `code` of `EMISSINGTHEME`.

#### themes.setDefault([opts], themeName)

`opts` is an object with the following properties.

* **platform** - Defaults to `'fallback'`.  If your theme is platform
  specific, specify that here with the platform from `process.platform`, eg,
  `win32`, `darwin`, etc.
* **hasUnicode** - Defaults to `false`. If your theme uses unicode you
  should set this to true.
* **hasColor** - Defaults to `false`.  If your theme uses color you should
  set this to true.

`themeName` is the name of the theme (as given to `addTheme`) to use for
this set of `opts`.

#### themes.newTheme([parentTheme,] newTheme)

Create a new theme object based on `parentTheme`.  If no `parentTheme` is
provided then a minimal parentTheme that defines functions for rendering the
activity indicator (spinner) and progress bar will be defined. (This
fallback parent is defined in `gauge/base-theme`.)

newTheme should be a bare object– we'll start by discussing the properties
defined by the default themes:

* **preProgressbar** - displayed prior to the progress bar, if the progress
  bar is displayed.
* **postProgressbar** - displayed after the progress bar, if the progress bar
  is displayed.
* **progressBarTheme** - The subtheme passed through to the progress bar
  renderer, it's an object with `complete` and `remaining` properties
  that are the strings you want repeated for those sections of the progress
  bar.
* **activityIndicatorTheme** - The theme for the activity indicator (spinner),
  this can either be a string, in which each character is a different step, or
  an array of strings.
* **preSubsection** - Displayed as a separator between the `section` and
  `subsection` when the latter is printed.

More generally, themes can have any value that would be a valid value when rendering
templates. The properties in the theme are used when their name matches a type in
the template. Their values can be:

* **strings & numbers** - They'll be included as is
* **function (values, theme, width)** - Should return what you want in your output.
  *values* is an object with values provided via `gauge.show`,
  *theme* is the theme specific to this item (see below) or this theme object,
  and *width* is the number of characters wide your result should be.

There are a couple of special prefixes:

* **pre** - Is shown prior to the property, if its displayed.
* **post** - Is shown after the property, if its displayed.

And one special suffix:

* **Theme** - Its value is passed to a function-type item as the theme.

#### themes.addToAllThemes(theme)

This *mixes-in* `theme` into all themes currently defined. It also adds it
to the default parent theme for this themeset, so future themes added to
this themeset will get the values from `theme` by default.

#### themes.newThemeset()

Copy the current themeset into a new one.  This allows you to easily inherit
one themeset from another.

### TEMPLATES

A template is an array of objects and strings that, after being evaluated,
will be turned into the gauge line.  The default template is:

```javascript
[
    {type: 'progressbar', length: 20},
    {type: 'activityIndicator', kerning: 1, length: 1},
    {type: 'section', kerning: 1, default: ''},
    {type: 'subsection', kerning: 1, default: ''}
]
```

The various template elements can either be **plain strings**, in which case they will
be be included verbatum in the output, or objects with the following properties:

* *type* can be any of the following plus any keys you pass into `gauge.show` plus
  any keys you have on a custom theme.
  * `section` – What big thing you're working on now.
  * `subsection` – What component of that thing is currently working.
  * `activityIndicator` – Shows a spinner using the `activityIndicatorTheme`
    from your active theme.
  * `progressbar` – A progress bar representing your current `completed`
    using the `progressbarTheme` from your active theme.
* *kerning* – Number of spaces that must be between this item and other
  items, if this item is displayed at all.
* *maxLength* – The maximum length for this element. If its value is longer it
  will be truncated.
* *minLength* – The minimum length for this element. If its value is shorter it
  will be padded according to the *align* value.
* *align* – (Default: left) Possible values "left", "right" and "center". Works
  as you'd expect from word processors.
* *length* – Provides a single value for both *minLength* and *maxLength*. If both
  *length* and *minLength or *maxLength* are specifed then the latter take precedence.
* *value* – A literal value to use for this template item.
* *default* – A default value to use for this template item if a value
  wasn't otherwise passed in.

### PLUMBING

This is the super simple, assume nothing, do no magic internals used by gauge to
implement its ordinary interface.

```
var Plumbing = require('gauge/plumbing')
var gauge = new Plumbing(theme, template, width)
```

* **theme**: The theme to use.
* **template**: The template to use.
* **width**: How wide your gauge should be

#### `gauge.setTheme(theme)`

Change the active theme.

#### `gauge.setTemplate(template)`

Change the active template.

#### `gauge.setWidth(width)`

Change the width to render at.

#### `gauge.hide()`

Return the string necessary to hide the progress bar

#### `gauge.hideCursor()`

Return a string to hide the cursor.

#### `gauge.showCursor()`

Return a string to show the cursor.

#### `gauge.show(status)`

Using `status` for values, render the provided template with the theme and return
a string that is suitable for printing to update the gauge.

{'repo_name': 'sx1989827/DOClever', 'stars': '2669', 'repo_language': 'JavaScript', 'file_name': 'parse.js', 'mime_type': 'text/plain', 'hash': 6265654543467672899, 'source_dataset': 'data'}