text:
@implementation MBSpinningCircle
{
    float progress;
}

+(MBSpinningCircle*)circleWithSize:(NSSpinningCircleSize)size color:(UIColor*)color
{
    float width;
    switch (size)
    {
        case NSSpinningCircleSizeDefault:
            width = 40;
            break;
        case NSSpinningCircleSizeLarge:
            width = 50;
            break;
        case  NSSpinningCircleSizeSmall:
            width = 10;
            break;
    }

    MBSpinningCircle *circle = [[MBSpinningCircle alloc] initWithFrame:CGRectMake(0, 0, width, width)];
    circle.color = color;
    return circle;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.opaque = NO;
        self.autoresizingMask =  UIViewAutoresizingFlexibleLeftMargin;
    }
    return self;
}

-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    for (UIView *view in self.subviews)
    {
        if ([view pointInside:[self convertPoint:point toView:view] withEvent:event])
            return YES;
    }
    return NO;
}

-(void)setIsAnimating:(BOOL)animating
{
    _isAnimating = animating;
    if(animating)
    {
        [UIView animateWithDuration:0.9 animations:^{ self.alpha = 1.0; }];
        [self addRotationAnimation];
    }
    else
    {
        [self hide];
    }
}

-(void)hide
{
    [UIView animateWithDuration:0.45 animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL fin) {
        [self.layer removeAllAnimations];
    }];
}

-(CGGradientRef)gradient
{

    UIColor *sideColor = [UIColor redColor];
    UIColor *midColor = [UIColor lightGrayColor];
    NSArray* gradientColors = @[(id)sideColor.CGColor,
                               (id)midColor.CGColor,
                               (id)sideColor.CGColor];
    CGFloat gradientLocations[] = {0, 0.5, 1};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    return CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)gradientColors, gradientLocations);
}

-(void)drawAnnular
{
    progress += 0.05;
    if(progress > M_PI) progress = 0;
    CGFloat lineWidth = 3.25f;
    if(_circleSize == NSSpinningCircleSizeDefault)
        lineWidth = 2.0f;
    UIBezierPath *processBackgroundPath = [UIBezierPath bezierPath];
    processBackgroundPath.lineWidth = lineWidth;
    processBackgroundPath.lineCapStyle = kCGLineCapRound;

    CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
    CGFloat radius = (self.bounds.size.width - 16 - lineWidth)/2;
    CGFloat startAngle = - ((float)M_PI / 2 - progress*2);

    [[UIColor colorWithRed:1 green:1 blue:1 alpha:0.1] set];

    UIBezierPath *processPath = [UIBezierPath bezierPath];
    processPath.lineCapStyle = kCGLineCapSquare;
    processPath.lineWidth = lineWidth;
    CGFloat endAngle = ((float)M_PI + startAngle);
    [processPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    if(_hasGlow)
        CGContextSetShadowWithColor(UIGraphicsGetCurrentContext(), CGSizeMake(0, 0), 6, _color.CGColor);
    [_color set];
    [processPath stroke];
    CGContextRestoreGState(context);

    if(_isAnimating)
        [self addRotationAnimation];
}

-(void)addRotationAnimation
{
    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI];
    rotationAnimation.duration = _speed;
    rotationAnimation.repeatCount = MAXFLOAT;
    rotationAnimation.cumulative = YES;
    [self.layer addAnimation:rotationAnimation forKey:@"rotationAnimation1"];
}

-(void)drawRect:(CGRect)rect
{
    [self drawAnnular];
}

@end


text:
using System;
using UnityEngine;
using Utils;

namespace SimpleContainer.Container
{
    public class UnityContainerAOT : IContainerAOT
    {
        #region IContainerExtension implementation

        public void OnRegister(IInjectionContainer container)
        {
            container.beforeAddBinding += OnBeforeAddBinding;
            container.beforeDefaultInstantiate += this.OnBindingEvaluation;
        }

        public void OnUnregister(IInjectionContainer container)
        {
            container.beforeAddBinding -= this.OnBeforeAddBinding;
            container.beforeDefaultInstantiate -= this.OnBindingEvaluation;
        }

        #endregion

        public void Init(IInjectionContainer container) { }

        /// <summary>
        /// 如果当前 binding 的值是类型且是 MonoBehaviour 派生类就抛出异常
        /// </summary>
        protected void OnBeforeAddBinding(IBinder source, ref IBinding binding)
        {
            if (binding.value is Type &&
                TypeUtils.IsAssignable(typeof(MonoBehaviour), binding.value as Type))
            {
                throw new Exceptions(Exceptions.CANNOT_RESOLVE_MONOBEHAVIOUR);
            }
        }

        /// <summary>
        /// 为 ADDRESS 类型 binding 返回实例化并加载好组件的 gameObject(在 Injector 类的
        /// ResolveBinding 方法中触发)
        /// </summary>
        protected object OnBindingEvaluation(
            IInjector source,
            ref IBinding binding)
        {
            if (binding.value is PrefabInfo)
            {
                if (binding.bindingType == BindingType.ADDRESS)
                {
                    var prefabInfo = (PrefabInfo)binding.value;
                    var gameObject = (GameObject)MonoBehaviour.Instantiate(prefabInfo.prefab);

                    if (prefabInfo.type.Equals(typeof(GameObject))) { return gameObject; }
                    else
                    {
                        var component = gameObject.GetComponent(prefabInfo.type);

                        if (component == null)
                        {
                            component = gameObject.AddComponent(prefabInfo.type);
                        }

                        return component;
                    }
                }
                else
                {
                    throw new Exceptions(
                        string.Format(Exceptions.CANNOT_RESOLVE_NOT_ADDRESS_PREFAB, "UnityEngine.Object"));
                }
            }
            else { return null; }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using namespace nanogui;
using namespace std;

TEV_NAMESPACE_BEGIN

pair<string, string> Channel::split(const string& channel) {
    size_t dotPosition = channel.rfind(".");
    if (dotPosition != string::npos) {
        return {channel.substr(0, dotPosition + 1), channel.substr(dotPosition + 1)};
    }

    return {"", channel};
}

string Channel::tail(const string& channel) {
    return split(channel).second;
}

string Channel::head(const string& channel) {
    return split(channel).first;
}

bool Channel::isTopmost(const string& channel) {
    return tail(channel) == channel;
}

bool Channel::isAlpha(const string& channel) {
    return toLower(tail(channel)) == "a";
}

Color Channel::color(string channel) {
    channel = toLower(tail(channel));

    if (channel == "r") {
        return Color(0.8f, 0.2f, 0.2f, 1.0f);
    } else if (channel == "g") {
        return Color(0.2f, 0.8f, 0.2f, 1.0f);
    } else if (channel == "b") {
        return Color(0.2f, 0.3f, 1.0f, 1.0f);
    }

    return Color(1.0f, 1.0f);
}

Channel::Channel(const std::string& name, const nanogui::Vector2i& size)
: mName{name}, mSize{size} {
    mData.resize((size_t)mSize.x() * mSize.y());
}

Task<void> Channel::divideByAsync(const Channel& other, int priority) {
    co_await ThreadPool::global().parallelForAsync<size_t>(0, other.numPixels(), [&](size_t i) {
        if (other.at(i) != 0) {
            at(i) /= other.at(i);
        } else {
            at(i) = 0;
        }
    }, priority);
}

Task<void> Channel::multiplyWithAsync(const Channel& other, int priority) {
    co_await ThreadPool::global().parallelForAsync<size_t>(0, other.numPixels(), [&](size_t i) {
        at(i) *= other.at(i);
    }, priority);
}

void Channel::updateTile(int x, int y, int width, int height, const vector<float>& newData) {
    if (x < 0 || y < 0 || x + width > size().x() || y + height > size().y()) {
        tlog::warning() << "Tile [" << x << "," << y << "," << width << "," << height << "] could not be updated because it does not fit into the channel's size " << size();
        return;
    }

    for (int posY = 0; posY < height; ++posY) {
        for (int posX = 0; posX < width; ++posX) {
            at({x + posX, y + posY}) = newData[posX + posY * width];
        }
    }
}

TEV_NAMESPACE_END


text:
"""Ce fichier contient la classe VenteUnique, détaillée plus bas."""

from abstraits.obase import BaseObj

class VenteUnique(BaseObj):

    """Cette classe définit un service pour la vente unique d'objet.

    Par défaut, les magasins ne retiennent pas les objets, juste
    les prototypes d'objets. Pour certains objets uniques, c'est
    un problème. Ce service existe donc pour s'assurer que, dans
    certains cas (si le nom de l'objet diffère du nom du prototype),
    l'objet soit conservé intégralement.

    """

    type_achat = "unique"

    def __init__(self, objet):
        """Constructeur de la classe"""
        BaseObj.__init__(self)
        self.objet = objet
        self._construire()

    def __getnewargs__(self):
        return (None, )

    def __repr__(self):
        return "<{}>".format(repr(self.objet))

    def __str__(self):
        return str(self.objet)

    @property
    def m_valeur(self):
        return self.objet.prix

    @property
    def nom_achat(self):
        """Retourne le nom à afficher dans le magasin."""
        if self.objet:
            return self.objet.get_nom(1)

        return "inconnu"

    @property
    def cle(self):
        return self.objet.identifiant

    def get_nom(self, nombre=1):
        """Retourne le nom complet en fonction du nombre.

        Par exemple :
        Si nombre == 1 : retourne le nom singulier
        Sinon : retourne le nombre et le nom pluriel

        """
        if self.objet:
            return self.objet.get_nom(nombre)

        return "inconnu"

    def acheter(self, quantite, magasin, transaction):
        """Achète les objets dans la quantité spécifiée."""
        salle = magasin.parent
        if self.objet:
            salle.objets_sol.ajouter(self.objet)

    def regarder(self, personnage):
        """Le personnage regarde le service (avant achat)."""
        return self.objet.regarder(personnage)


text: {{ product.title }}


text:
(function() {
    "use strict";

    let products = getProductList();

    let orderGroups = products.reduce((array, p) => {
        let key = p.Category;

        let hasKey = array.some(item =>
            item.key === key ? ((item.values.push(p)), true) : false
        );

        if(!hasKey){
            array.push({key: key, values: [p]});
        }

        return array;
    }, []).map((g, index) =>
        ({ category: g.key, products: g.values })
    );

    orderGroups.forEach(g => {
        console.log(`Category=${g.category} Products=...`);

        g.products.forEach(p => console.log(`Products: ProductID=${p.ProductID} ProductName=${p.ProductName}` +
            ` Category=${p.Category} UnitPrice=${p.UnitPrice} UnitsInStock=${p.UnitsInStock}`));
    });
})();


text:
using namespace llvm;

//===----------------------------------------------------------------------===//
// Lexer
//===----------------------------------------------------------------------===//

// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
// of these for known things.
enum Token {
  tok_eof = -1,

  // commands
  tok_def = -2,
  tok_extern = -3,

  // primary
  tok_identifier = -4,
  tok_number = -5
};

static std::string IdentifierStr; // Filled in if tok_identifier
static double NumVal;             // Filled in if tok_number

/// gettok - Return the next token from standard input.
static int gettok() {
  static int LastChar = ' ';

  // Skip any whitespace.
  while (isspace(LastChar))
    LastChar = getchar();

  if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
    IdentifierStr = LastChar;
    while (isalnum((LastChar = getchar())))
      IdentifierStr += LastChar;

    if (IdentifierStr == "def")
      return tok_def;
    if (IdentifierStr == "extern")
      return tok_extern;
    return tok_identifier;
  }

  if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
    std::string NumStr;
    do {
      NumStr += LastChar;
      LastChar = getchar();
    } while (isdigit(LastChar) || LastChar == '.');

    NumVal = strtod(NumStr.c_str(), nullptr);
    return tok_number;
  }

  if (LastChar == '#') {
    // Comment until end of line.
    do
      LastChar = getchar();
    while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');

    if (LastChar != EOF)
      return gettok();
  }

  // Check for end of file.  Don't eat the EOF.
  if (LastChar == EOF)
    return tok_eof;

  // Otherwise, just return the character as its ascii value.
  int ThisChar = LastChar;
  LastChar = getchar();
  return ThisChar;
}

//===----------------------------------------------------------------------===//
// Abstract Syntax Tree (aka Parse Tree)
//===----------------------------------------------------------------------===//

namespace {

/// ExprAST - Base class for all expression nodes.
class ExprAST {
public:
  virtual ~ExprAST() = default;

  virtual Value *codegen() = 0;
};

/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : public ExprAST {
  double Val;

public:
  NumberExprAST(double Val) : Val(Val) {}

  Value *codegen() override;
};

/// VariableExprAST - Expression class for referencing a variable, like "a".
class VariableExprAST : public ExprAST {
  std::string Name;

public:
  VariableExprAST(const std::string &Name) : Name(Name) {}

  Value *codegen() override;
};

/// BinaryExprAST - Expression class for a binary operator.
class BinaryExprAST : public ExprAST {
  char Op;
  std::unique_ptr<ExprAST> LHS, RHS;

public:
  BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
                std::unique_ptr<ExprAST> RHS)
      : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}

  Value *codegen() override;
};

/// CallExprAST - Expression class for function calls.
class CallExprAST : public ExprAST {
  std::string Callee;
  std::vector<std::unique_ptr<ExprAST>> Args;

public:
  CallExprAST(const std::string &Callee,
              std::vector<std::unique_ptr<ExprAST>> Args)
      : Callee(Callee), Args(std::move(Args)) {}

  Value *codegen() override;
};

/// PrototypeAST - This class represents the "prototype" for a function,
/// which captures its name, and its argument names (thus implicitly the number
/// of arguments the function takes).
class PrototypeAST {
  std::string Name;
  std::vector<std::string> Args;

public:
  PrototypeAST(const std::string &Name, std::vector<std::string> Args)
      : Name(Name), Args(std::move(Args)) {}

  Function *codegen();
  const std::string &getName() const { return Name; }
};

/// FunctionAST - This class represents a function definition itself.
class FunctionAST {
  std::unique_ptr<PrototypeAST> Proto;
  std::unique_ptr<ExprAST> Body;

public:
  FunctionAST(std::unique_ptr<PrototypeAST> Proto,
              std::unique_ptr<ExprAST> Body)
      : Proto(std::move(Proto)), Body(std::move(Body)) {}

  Function *codegen();
};

} // end anonymous namespace

//===----------------------------------------------------------------------===//
// Parser
//===----------------------------------------------------------------------===//

/// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
/// token the parser is looking at.  getNextToken reads another token from the
/// lexer and updates CurTok with its results.
static int CurTok;
static int getNextToken() { return CurTok = gettok(); }

/// BinopPrecedence - This holds the precedence for each binary operator that is
/// defined.
static std::map<char, int> BinopPrecedence;

/// GetTokPrecedence - Get the precedence of the pending binary operator token.
static int GetTokPrecedence() {
  if (!isascii(CurTok))
    return -1;

  // Make sure it's a declared binop.
  int TokPrec = BinopPrecedence[CurTok];
  if (TokPrec <= 0)
    return -1;
  return TokPrec;
}

/// LogError* - These are little helper functions for error handling.
std::unique_ptr<ExprAST> LogError(const char *Str) {
  fprintf(stderr, "Error: %s\n", Str);
  return nullptr;
}

std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
  LogError(Str);
  return nullptr;
}

static std::unique_ptr<ExprAST> ParseExpression();

/// numberexpr ::= number
static std::unique_ptr<ExprAST> ParseNumberExpr() {
  auto Result = llvm::make_unique<NumberExprAST>(NumVal);
  getNextToken(); // consume the number
  return std::move(Result);
}

/// parenexpr ::= '(' expression ')'
static std::unique_ptr<ExprAST> ParseParenExpr() {
  getNextToken(); // eat (.
  auto V = ParseExpression();
  if (!V)
    return nullptr;

  if (CurTok != ')')
    return LogError("expected ')'");
  getNextToken(); // eat ).
  return V;
}

/// identifierexpr
///   ::= identifier
///   ::= identifier '(' expression* ')'
static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
  std::string IdName = IdentifierStr;

  getNextToken(); // eat identifier.

  if (CurTok != '(') // Simple variable ref.
    return llvm::make_unique<VariableExprAST>(IdName);

  // Call.
  getNextToken(); // eat (
  std::vector<std::unique_ptr<ExprAST>> Args;
  if (CurTok != ')') {
    while (true) {
      if (auto Arg = ParseExpression())
        Args.push_back(std::move(Arg));
      else
        return nullptr;

      if (CurTok == ')')
        break;

      if (CurTok != ',')
        return LogError("Expected ')' or ',' in argument list");
      getNextToken();
    }
  }

  // Eat the ')'.
  getNextToken();

  return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
}

/// primary
///   ::= identifierexpr
///   ::= numberexpr
///   ::= parenexpr
static std::unique_ptr<ExprAST> ParsePrimary() {
  switch (CurTok) {
  default:
    return LogError("unknown token when expecting an expression");
  case tok_identifier:
    return ParseIdentifierExpr();
  case tok_number:
    return ParseNumberExpr();
  case '(':
    return ParseParenExpr();
  }
}

/// binoprhs
///   ::= ('+' primary)*
static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
                                              std::unique_ptr<ExprAST> LHS) {
  // If this is a binop, find its precedence.
  while (true) {
    int TokPrec = GetTokPrecedence();

    // If this is a binop that binds at least as tightly as the current binop,
    // consume it, otherwise we are done.
    if (TokPrec < ExprPrec)
      return LHS;

    // Okay, we know this is a binop.
    int BinOp = CurTok;
    getNextToken(); // eat binop

    // Parse the primary expression after the binary operator.
    auto RHS = ParsePrimary();
    if (!RHS)
      return nullptr;

    // If BinOp binds less tightly with RHS than the operator after RHS, let
    // the pending operator take RHS as its LHS.
    int NextPrec = GetTokPrecedence();
    if (TokPrec < NextPrec) {
      RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
      if (!RHS)
        return nullptr;
    }

    // Merge LHS/RHS.
    LHS =
        llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
  }
}

/// expression
///   ::= primary binoprhs
///
static std::unique_ptr<ExprAST> ParseExpression() {
  auto LHS = ParsePrimary();
  if (!LHS)
    return nullptr;

  return ParseBinOpRHS(0, std::move(LHS));
}

/// prototype
///   ::= id '(' id* ')'
static std::unique_ptr<PrototypeAST> ParsePrototype() {
  if (CurTok != tok_identifier)
    return LogErrorP("Expected function name in prototype");

  std::string FnName = IdentifierStr;
  getNextToken();

  if (CurTok != '(')
    return LogErrorP("Expected '(' in prototype");

  std::vector<std::string> ArgNames;
  while (getNextToken() == tok_identifier)
    ArgNames.push_back(IdentifierStr);
  if (CurTok != ')')
    return LogErrorP("Expected ')' in prototype");

  // success.
  getNextToken(); // eat ')'.

  return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
}

/// definition ::= 'def' prototype expression
static std::unique_ptr<FunctionAST> ParseDefinition() {
  getNextToken(); // eat def.
  auto Proto = ParsePrototype();
  if (!Proto)
    return nullptr;

  if (auto E = ParseExpression())
    return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
  return nullptr;
}

/// toplevelexpr ::= expression
static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
  if (auto E = ParseExpression()) {
    // Make an anonymous proto.
    auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
                                                 std::vector<std::string>());
    return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
  }
  return nullptr;
}

/// external ::= 'extern' prototype
static std::unique_ptr<PrototypeAST> ParseExtern() {
  getNextToken(); // eat extern.
  return ParsePrototype();
}

//===----------------------------------------------------------------------===//
// Code Generation
//===----------------------------------------------------------------------===//

static LLVMContext TheContext;
static IRBuilder<> Builder(TheContext);
static std::unique_ptr<Module> TheModule;
static std::map<std::string, Value *> NamedValues;

Value *LogErrorV(const char *Str) {
  LogError(Str);
  return nullptr;
}

Value *NumberExprAST::codegen() {
  return ConstantFP::get(TheContext, APFloat(Val));
}

Value *VariableExprAST::codegen() {
  // Look this variable up in the function.
  Value *V = NamedValues[Name];
  if (!V)
    return LogErrorV("Unknown variable name");
  return V;
}

Value *BinaryExprAST::codegen() {
  Value *L = LHS->codegen();
  Value *R = RHS->codegen();
  if (!L || !R)
    return nullptr;

  switch (Op) {
  case '+':
    return Builder.CreateFAdd(L, R, "addtmp");
  case '-':
    return Builder.CreateFSub(L, R, "subtmp");
  case '*':
    return Builder.CreateFMul(L, R, "multmp");
  case '<':
    L = Builder.CreateFCmpULT(L, R, "cmptmp");
    // Convert bool 0/1 to double 0.0 or 1.0
    return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext), "booltmp");
  default:
    return LogErrorV("invalid binary operator");
  }
}

Value *CallExprAST::codegen() {
  // Look up the name in the global module table.
  Function *CalleeF = TheModule->getFunction(Callee);
  if (!CalleeF)
    return LogErrorV("Unknown function referenced");

  // If argument mismatch error.
  if (CalleeF->arg_size() != Args.size())
    return LogErrorV("Incorrect # arguments passed");

  std::vector<Value *> ArgsV;
  for (unsigned i = 0, e = Args.size(); i != e; ++i) {
    ArgsV.push_back(Args[i]->codegen());
    if (!ArgsV.back())
      return nullptr;
  }

  return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
}

Function *PrototypeAST::codegen() {
  // Make the function type:  double(double,double) etc.
  std::vector<Type *> Doubles(Args.size(), Type::getDoubleTy(TheContext));
  FunctionType *FT =
      FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);

  Function *F =
      Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());

  // Set names for all arguments.
  unsigned Idx = 0;
  for (auto &Arg : F->args())
    Arg.setName(Args[Idx++]);

  return F;
}

Function *FunctionAST::codegen() {
  // First, check for an existing function from a previous 'extern' declaration.
  Function *TheFunction = TheModule->getFunction(Proto->getName());

  if (!TheFunction)
    TheFunction = Proto->codegen();

  if (!TheFunction)
    return nullptr;

  // Create a new basic block to start insertion into.
  BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
  Builder.SetInsertPoint(BB);

  // Record the function arguments in the NamedValues map.
  NamedValues.clear();
  for (auto &Arg : TheFunction->args())
    NamedValues[Arg.getName()] = &Arg;

  if (Value *RetVal = Body->codegen()) {
    // Finish off the function.
    Builder.CreateRet(RetVal);

    // Validate the generated code, checking for consistency.
    verifyFunction(*TheFunction);

    return TheFunction;
  }

  // Error reading body, remove function.
  TheFunction->eraseFromParent();
  return nullptr;
}

//===----------------------------------------------------------------------===//
// Top-Level parsing and JIT Driver
//===----------------------------------------------------------------------===//

static void HandleDefinition() {
  if (auto FnAST = ParseDefinition()) {
    if (auto *FnIR = FnAST->codegen()) {
      fprintf(stderr, "Read function definition:");
      FnIR->print(errs());
      fprintf(stderr, "\n");
    }
  } else {
    // Skip token for error recovery.
    getNextToken();
  }
}

static void HandleExtern() {
  if (auto ProtoAST = ParseExtern()) {
    if (auto *FnIR = ProtoAST->codegen()) {
      fprintf(stderr, "Read extern: ");
      FnIR->print(errs());
      fprintf(stderr, "\n");
    }
  } else {
    // Skip token for error recovery.
    getNextToken();
  }
}

static void HandleTopLevelExpression() {
  // Evaluate a top-level expression into an anonymous function.
  if (auto FnAST = ParseTopLevelExpr()) {
    if (auto *FnIR = FnAST->codegen()) {
      fprintf(stderr, "Read top-level expression:");
      FnIR->print(errs());
      fprintf(stderr, "\n");
    }
  } else {
    // Skip token for error recovery.
    getNextToken();
  }
}

/// top ::= definition | external | expression | ';'
static void MainLoop() {
  while (true) {
    fprintf(stderr, "ready> ");
    switch (CurTok) {
    case tok_eof:
      return;
    case ';': // ignore top-level semicolons.
      getNextToken();
      break;
    case tok_def:
      HandleDefinition();
      break;
    case tok_extern:
      HandleExtern();
      break;
    default:
      HandleTopLevelExpression();
      break;
    }
  }
}

//===----------------------------------------------------------------------===//
// Main driver code.
//===----------------------------------------------------------------------===//

int main() {
  // Install standard binary operators.
  // 1 is lowest precedence.
  BinopPrecedence['<'] = 10;
  BinopPrecedence['+'] = 20;
  BinopPrecedence['-'] = 20;
  BinopPrecedence['*'] = 40; // highest.

  // Prime the first token.
  fprintf(stderr, "ready> ");
  getNextToken();

  // Make the module, which holds all the code.
  TheModule = llvm::make_unique<Module>("my cool jit", TheContext);

  // Run the main "interpreter loop" now.
  MainLoop();

  // Print out all of the generated code.
  TheModule->print(errs(), nullptr);

  return 0;
}


text:
package cmd

import (
	"fmt"
	"io"
	"strings"

	kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	kerrors "github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
	cmdutil "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd/util"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	imageapi "github.com/openshift/origin/pkg/image/api"
	"github.com/openshift/origin/pkg/image/registry/imagestreamimage"
	"github.com/spf13/cobra"

	"github.com/openshift/origin/pkg/cmd/util/clientcmd"
)

const (
	tagLong = `Tag existing images into image streams

The tag command allows you to take an existing tag or image from an image
stream, or a Docker image pull spec, and set it as the most recent image for a
tag in 1 or more other image streams. It is similar to the 'docker tag'
command, but it operates on image streams instead.`

	tagExample = `  // Tag the current image for the image stream 'openshift/ruby' and tag '2.0' into the image stream 'yourproject/ruby with tag 'tip':
  $ %[1]s tag openshift/ruby:2.0 yourproject/ruby:tip

  // Tag a specific image:
  $ %[1]s tag openshift/ruby@sha256:6b646fa6bf5e5e4c7fa41056c27910e679c03ebe7f93e361e6515a9da7e258cc yourproject/ruby:tip

  // Tag an external Docker image:
  $ %[1]s tag --source=docker openshift/origin:latest yourproject/ruby:tip`
)

// NewCmdTag implements the OpenShift cli tag command.
func NewCmdTag(fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	var sourceKind string

	cmd := &cobra.Command{
		Use:     "tag [--source=SOURCETYPE] SOURCE DEST [DEST ...]",
		Short:   "Tag existing images into image streams",
		Long:    tagLong,
		Example: fmt.Sprintf(tagExample, fullName),
		Run: func(cmd *cobra.Command, args []string) {
			err := RunTag(f, out, cmd, args, sourceKind)
			cmdutil.CheckErr(err)
		},
	}

	cmd.Flags().StringVar(&sourceKind, "source", sourceKind, "Optional hint for the source type; valid values are 'imagestreamtag', 'istag', 'imagestreamimage', 'isimage', and 'docker'")

	return cmd
}

func parseStreamName(name, defaultNamespace string) (string, string, error) {
	if !strings.Contains(name, "/") {
		return defaultNamespace, name, nil
	}

	parts := strings.Split(name, "/")
	if len(parts) != 2 {
		return "", "", fmt.Errorf("invalid image stream %q", name)
	}

	namespace := parts[0]
	if len(namespace) == 0 {
		return "", "", fmt.Errorf("invalid namespace %q for image stream %q", namespace, name)
	}

	streamName := parts[1]
	if len(streamName) == 0 {
		return "", "", fmt.Errorf("invalid name %q for image stream %q", streamName, name)
	}

	return namespace, streamName, nil
}

func determineSourceKind(f *clientcmd.Factory, input string) string {
	mapper, _ := f.Object()
	_, kind, err := mapper.VersionAndKindForResource(input)
	if err == nil {
		return kind
	}

	// DockerImage isn't in RESTMapper
	switch strings.ToLower(input) {
	case "docker", "dockerimage":
		return "DockerImage"
	}

	return input
}

// RunTag contains all the necessary functionality for the OpenShift cli tag command.
func RunTag(f *clientcmd.Factory, out io.Writer, cmd *cobra.Command, args []string, sourceKind string) error {
	if len(args) < 2 {
		return cmdutil.UsageError(cmd, "you must specify a source and at least one destination")
	}

	original := sourceKind
	if len(sourceKind) > 0 {
		sourceKind = determineSourceKind(f, sourceKind)
	}
	if len(sourceKind) > 0 {
		validSources := util.NewStringSet("imagestreamtag", "istag", "imagestreamimage", "isimage", "docker", "dockerimage")
		if !validSources.Has(strings.ToLower(sourceKind)) {
			cmdutil.CheckErr(cmdutil.UsageError(cmd, "invalid source %q; valid values are %v", original, strings.Join(validSources.List(), ", ")))
		}
	}

	namespace, err := f.DefaultNamespace()
	if err != nil {
		return err
	}

	sourceNamespace, sourceNameAndRef, err := parseStreamName(args[0], namespace)
	if err != nil {
		return err
	}

	osClient, _, err := f.Clients()
	if err != nil {
		return err
	}

	if len(sourceKind) == 0 {
		if sourceName, sourceTag, ok := imageapi.SplitImageStreamTag(sourceNameAndRef); ok {
			if _, err := osClient.ImageStreamTags(sourceNamespace).Get(sourceName, sourceTag); err == nil {
				sourceKind = "ImageStreamTag"
			}
		}
	}

	if len(sourceKind) == 0 {
		if sourceName, sourceID, err := imagestreamimage.ParseNameAndID(sourceNameAndRef); err == nil {
			if _, err := osClient.ImageStreamImages(sourceNamespace).Get(sourceName, sourceID); err == nil {
				sourceKind = "ImageStreamImage"
			}
		}
	}

	if len(sourceKind) == 0 {
		sourceKind = "DockerImage"
	}

	for _, arg := range args[1:] {
		destNamespace, destNameAndTag, err := parseStreamName(arg, namespace)
		if err != nil {
			return err
		}

		destName, destTag, ok := imageapi.SplitImageStreamTag(destNameAndTag)
		if !ok {
			return fmt.Errorf("%q must be of the form <namespace>/<stream name>:<tag>", arg)
		}

		isc := osClient.ImageStreams(destNamespace)

		target, err := isc.Get(destName)
		if err != nil {
			if !kerrors.IsNotFound(err) {
				return err
			}

			// try to create the target if it doesn't exist
			target = &imageapi.ImageStream{
				ObjectMeta: kapi.ObjectMeta{
					Name: destName,
				},
			}
			target, err = isc.Create(target)
			if err != nil {
				return nil
			}
		}

		if target.Spec.Tags == nil {
			target.Spec.Tags = make(map[string]imageapi.TagReference)
		}

		targetRef, ok := target.Spec.Tags[destTag]
		if !ok {
			targetRef = imageapi.TagReference{}
		}

		targetRef.From = &kapi.ObjectReference{
			Kind: sourceKind,
		}
		switch sourceKind {
		case "DockerImage":
			targetRef.From.Name = args[0]
		default:
			targetRef.From.Namespace = sourceNamespace
			targetRef.From.Name = sourceNameAndRef
		}

		target.Spec.Tags[destTag] = targetRef

		if _, err = isc.Update(target); err != nil {
			return err
		}
	}

	return nil
}


text:
package kieker.tools.slastic.plugins.slasticImpl.control.performanceEvaluation.performanceLogger;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPStatement;

import kieker.tools.slastic.common.IComponentContext;

/**
 *
 * @author Andre van Hoorn
 *
 */
public class AbstractPerformanceLogger implements IPerformanceLogger {
	private static final Log LOG = LogFactory.getLog(AbstractPerformanceLogger.class);

	private volatile EPServiceProvider epServiceProvider;
	private final IComponentContext context;

	/**
	 * @return the context
	 */
	protected final IComponentContext getContext() {
		return this.context;
	}

	private final Collection<AbstractPerformanceMeasureLogger<?>> performanceMeasureLoggers = new ArrayList<AbstractPerformanceMeasureLogger<?>>();

	public AbstractPerformanceLogger(final EPServiceProvider epServiceProvider, final IComponentContext context) {
		this.epServiceProvider = epServiceProvider;
		this.context = context;
	}

	/**
	 *
	 * @param loggerClasses
	 */
	protected final void startLoggersByClassname(final Collection<Class<? extends AbstractPerformanceMeasureLogger<?>>> loggerClasses) {
		for (final Class<? extends AbstractPerformanceMeasureLogger<?>> lc : loggerClasses) {
			final AbstractPerformanceMeasureLogger<?> logger = this.createLoggerFromClass(lc);
			this.addAndRegisterLoggerAsSubscriber(logger);
		}
	}

	/**
	 *
	 * @param loggerClass
	 * @return
	 */
	private AbstractPerformanceMeasureLogger<?> createLoggerFromClass(final Class<? extends AbstractPerformanceMeasureLogger<?>> loggerClass) {
		AbstractPerformanceMeasureLogger<?> loggerInst = null;
		try {
			final Constructor<? extends AbstractPerformanceMeasureLogger<?>> con = loggerClass.getConstructor(IComponentContext.class);
			loggerInst = con.newInstance(this.context.createSubcontext(loggerClass.getSimpleName()));
		} catch (final Exception e) {
			LOG.error("Error instantiating logger:" + e.getMessage(), e);
		}
		return loggerInst;
	}

	@Override
	public final void addAndRegisterLoggerAsSubscriber(final AbstractPerformanceMeasureLogger<?> logger) {
		final String epStatementStr = logger.createEPStatement();
		final EPStatement epStatement = this.epServiceProvider.getEPAdministrator().createEPL(epStatementStr);
		epStatement.setSubscriber(logger);
		this.performanceMeasureLoggers.add(logger);
	}

	@Override
	public final void closeLogs() {
		for (final AbstractPerformanceMeasureLogger<?> l : this.performanceMeasureLoggers) {
			l.closePrintWriters();
		}
	}
}


text:
package com.facebook.buck.haskell;

import com.facebook.buck.cxx.Archive;
import com.facebook.buck.cxx.CxxBuckConfig;
import com.facebook.buck.cxx.CxxDeps;
import com.facebook.buck.cxx.CxxDescriptionEnhancer;
import com.facebook.buck.cxx.CxxPreprocessorDep;
import com.facebook.buck.cxx.CxxSourceRuleFactory;
import com.facebook.buck.cxx.platform.CxxPlatform;
import com.facebook.buck.cxx.platform.Linker;
import com.facebook.buck.cxx.platform.NativeLinkable;
import com.facebook.buck.cxx.platform.NativeLinkableInput;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.FlavorConvertible;
import com.facebook.buck.model.FlavorDomain;
import com.facebook.buck.model.Flavored;
import com.facebook.buck.model.InternalFlavor;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.CommonDescriptionArg;
import com.facebook.buck.rules.DefaultSourcePathResolver;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.HasDeclaredDeps;
import com.facebook.buck.rules.ImplicitDepsInferringDescription;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.args.SourcePathArg;
import com.facebook.buck.rules.coercer.PatternMatchedCollection;
import com.facebook.buck.rules.coercer.SourceList;
import com.facebook.buck.rules.macros.StringWithMacros;
import com.facebook.buck.util.MoreCollectors;
import com.facebook.buck.util.RichStream;
import com.facebook.buck.util.immutables.BuckStyleImmutable;
import com.facebook.buck.versions.VersionPropagator;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import java.io.File;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
import org.immutables.value.Value;

public class HaskellLibraryDescription
    implements Description<HaskellLibraryDescriptionArg>,
        ImplicitDepsInferringDescription<
            HaskellLibraryDescription.AbstractHaskellLibraryDescriptionArg>,
        Flavored,
        VersionPropagator<HaskellLibraryDescriptionArg> {

  private static final FlavorDomain<Type> LIBRARY_TYPE =
      FlavorDomain.from("Haskell Library Type", Type.class);

  private final HaskellConfig haskellConfig;
  private final CxxBuckConfig cxxBuckConfig;
  private final FlavorDomain<CxxPlatform> cxxPlatforms;

  public HaskellLibraryDescription(
      HaskellConfig haskellConfig,
      CxxBuckConfig cxxBuckConfig,
      FlavorDomain<CxxPlatform> cxxPlatforms) {
    this.haskellConfig = haskellConfig;
    this.cxxBuckConfig = cxxBuckConfig;
    this.cxxPlatforms = cxxPlatforms;
  }

  @Override
  public Class<HaskellLibraryDescriptionArg> getConstructorArgType() {
    return HaskellLibraryDescriptionArg.class;
  }

  private BuildTarget getBaseBuildTarget(BuildTarget target) {
    return target.withoutFlavors(Sets.union(Type.FLAVOR_VALUES, cxxPlatforms.getFlavors()));
  }

  /** @return the package identifier to use for the library with the given target. */
  private HaskellPackageInfo getPackageInfo(BuildTarget target) {
    String name = String.format("%s-%s", target.getBaseName(), target.getShortName());
    name = name.replace(File.separatorChar, '-');
    name = name.replace('_', '-');
    name = name.replaceFirst("^-*", "");

    Optional<String> packageNamePrefix = haskellConfig.getPackageNamePrefix();
    if (packageNamePrefix.isPresent()) {
      name = packageNamePrefix.get() + "-" + name;
    }

    return HaskellPackageInfo.of(name, "1.0.0", name);
  }

  private HaskellCompileRule requireCompileRule(
      BuildTarget buildTarget,
      ProjectFilesystem projectFilesystem,
      BuildRuleParams params,
      BuildRuleResolver resolver,
      SourcePathResolver pathResolver,
      SourcePathRuleFinder ruleFinder,
      CxxPlatform cxxPlatform,
      HaskellLibraryDescriptionArg args,
      ImmutableSet<BuildRule> deps,
      Linker.LinkableDepType depType,
      boolean hsProfile)
      throws NoSuchBuildTargetException {
    return HaskellDescriptionUtils.requireCompileRule(
        buildTarget,
        projectFilesystem,
        params,
        resolver,
        ruleFinder,
        deps,
        cxxPlatform,
        haskellConfig,
        depType,
        hsProfile,
        Optional.empty(),
        Optional.of(getPackageInfo(buildTarget)),
        args.getCompilerFlags(),
        HaskellSources.from(
            buildTarget, resolver, pathResolver, ruleFinder, cxxPlatform, "srcs", args.getSrcs()));
  }

  private Archive createStaticLibrary(
      BuildTarget target,
      ProjectFilesystem projectFilesystem,
      BuildRuleParams baseParams,
      BuildRuleResolver resolver,
      SourcePathResolver pathResolver,
      SourcePathRuleFinder ruleFinder,
      CxxPlatform cxxPlatform,
      HaskellLibraryDescriptionArg args,
      ImmutableSet<BuildRule> deps,
      Linker.LinkableDepType depType,
      boolean hsProfile)
      throws NoSuchBuildTargetException {
    HaskellCompileRule compileRule =
        requireCompileRule(
            target,
            projectFilesystem,
            baseParams,
            resolver,
            pathResolver,
            ruleFinder,
            cxxPlatform,
            args,
            deps,
            depType,
            hsProfile);
    return Archive.from(
        target,
        projectFilesystem,
        ruleFinder,
        cxxPlatform,
        cxxBuckConfig.getArchiveContents(),
        CxxDescriptionEnhancer.getStaticLibraryPath(
            projectFilesystem,
            target.withoutFlavors(HaskellDescriptionUtils.PROF),
            cxxPlatform.getFlavor(),
            depType == Linker.LinkableDepType.STATIC
                ? CxxSourceRuleFactory.PicType.PDC
                : CxxSourceRuleFactory.PicType.PIC,
            cxxPlatform.getStaticLibraryExtension(),
            hsProfile ? "_p" : ""),
        compileRule.getObjects(),
        // TODO(#20466393): Currently, GHC produces nono-deterministically sized object files.
        // This means that it's possible to get a thin archive fetched from cache originating from
        // one build and the associated object files fetched from cache originating from another, in
        // which the sizes listed in the archive differ from the objects on disk, causing the GHC
        // linker to fail. Technically, since `HaskellCompileRule` is producing non-deterministic
        // outputs, we should mark that as uncacheable.  However, as that would have a significant
        // affect on build efficiency, and since this issue appears to only manifest by a size
        // mismatch with what is embedded in thin archives, just disable caching when using thin
        // archives.
        /* cacheable */ cxxBuckConfig.getArchiveContents() != Archive.Contents.THIN);
  }

  private Archive requireStaticLibrary(
      BuildTarget baseTarget,
      ProjectFilesystem projectFilesystem,
      BuildRuleParams baseParams,
      BuildRuleResolver resolver,
      SourcePathResolver pathResolver,
      SourcePathRuleFinder ruleFinder,
      CxxPlatform cxxPlatform,
      HaskellLibraryDescriptionArg args,
      ImmutableSet<BuildRule> deps,
      Linker.LinkableDepType depType,
      boolean hsProfile)
      throws NoSuchBuildTargetException {
    Preconditions.checkArgument(
        Sets.intersection(
                baseTarget.getFlavors(), Sets.union(Type.FLAVOR_VALUES, cxxPlatforms.getFlavors()))
            .isEmpty());
    BuildTarget target =
        baseTarget.withAppendedFlavors(
            depType == Linker.LinkableDepType.STATIC
                ? Type.STATIC.getFlavor()
                : Type.STATIC_PIC.getFlavor(),
            cxxPlatform.getFlavor());

    if (hsProfile) {
      target = target.withAppendedFlavors(HaskellDescriptionUtils.PROF);
    } else {
      target = target.withoutFlavors(HaskellDescriptionUtils.PROF);
    }

    Optional<Archive> archive = resolver.getRuleOptionalWithType(target, Archive.class);
    if (archive.isPresent()) {
      return archive.get();
    }

    return resolver.addToIndex(
        createStaticLibrary(
            target,
            projectFilesystem,
            baseParams,
            resolver,
            pathResolver,
            ruleFinder,
            cxxPlatform,
            args,
            deps,
            depType,
            hsProfile));
  }

  private HaskellPackageRule createPackage(
      BuildTarget target,
      ProjectFilesystem projectFilesystem,
      BuildRuleParams baseParams,
      BuildRuleResolver resolver,
      SourcePathResolver pathResolver,
      SourcePathRuleFinder ruleFinder,
      CxxPlatform cxxPlatform,
      HaskellLibraryDescriptionArg args,
      ImmutableSet<BuildRule> deps,
      Linker.LinkableDepType depType,
      boolean hsProfile)
      throws NoSuchBuildTargetException {

    ImmutableSortedSet<SourcePath> libraries;
    BuildRule library;
    switch (depType) {
      case SHARED:
        library =
            requireSharedLibrary(
                getBaseBuildTarget(target),
                projectFilesystem,
                baseParams,
                resolver,
                pathResolver,
                ruleFinder,
                cxxPlatform,
                args,
                deps);
        libraries = ImmutableSortedSet.of(library.getSourcePathToOutput());
        break;
      case STATIC:
      case STATIC_PIC:
        library =
            requireStaticLibrary(
                getBaseBuildTarget(target),
                projectFilesystem,
                baseParams,
                resolver,
                pathResolver,
                ruleFinder,
                cxxPlatform,
                args,
                deps,
                depType,
                false);

        if (hsProfile) {
          if (!(Linker.LinkableDepType.STATIC == depType
              || Linker.LinkableDepType.STATIC_PIC == depType)) {
            throw new IllegalStateException();
          }

          BuildRule profiledLibrary =
              requireStaticLibrary(
                  getBaseBuildTarget(target),
                  projectFilesystem,
                  baseParams,
                  resolver,
                  pathResolver,
                  ruleFinder,
                  cxxPlatform,
                  args,
                  deps,
                  depType,
                  true);

          libraries =
              ImmutableSortedSet.of(
                  library.getSourcePathToOutput(), profiledLibrary.getSourcePathToOutput());

        } else {
          libraries = ImmutableSortedSet.of(library.getSourcePathToOutput());
        }
        break;
      default:
        throw new IllegalStateException();
    }

    ImmutableSortedMap.Builder<String, HaskellPackage> depPackagesBuilder =
        ImmutableSortedMap.naturalOrder();
    for (BuildRule rule : deps) {
      if (rule instanceof HaskellCompileDep) {
        ImmutableList<HaskellPackage> packages =
            ((HaskellCompileDep) rule)
                .getCompileInput(cxxPlatform, depType, hsProfile)
                .getPackages();
        for (HaskellPackage pkg : packages) {
          depPackagesBuilder.put(pkg.getInfo().getIdentifier(), pkg);
        }
      }
    }

    ImmutableSortedMap<String, HaskellPackage> depPackages = depPackagesBuilder.build();

    ImmutableSortedSet<SourcePath> interfaces;
    ImmutableSortedSet<SourcePath> objects;
    HaskellCompileRule compileRule =
        requireCompileRule(
            target,
            projectFilesystem,
            baseParams,
            resolver,
            pathResolver,
            ruleFinder,
            cxxPlatform,
            args,
            deps,
            depType,
            false);

    if (hsProfile) {
      HaskellCompileRule profiledCompileRule =
          requireCompileRule(
              target,
              projectFilesystem,
              baseParams,
              resolver,
              pathResolver,
              ruleFinder,
              cxxPlatform,
              args,
              deps,
              depType,
              true);

      interfaces =
          ImmutableSortedSet.of(compileRule.getInterfaces(), profiledCompileRule.getInterfaces());
      objects =
          ImmutableSortedSet.of(compileRule.getObjectsDir(), profiledCompileRule.getObjectsDir());
    } else {
      interfaces = ImmutableSortedSet.of(compileRule.getInterfaces());
      objects = ImmutableSortedSet.of(compileRule.getObjectsDir());
    }

    return HaskellPackageRule.from(
        target,
        projectFilesystem,
        baseParams,
        ruleFinder,
        haskellConfig.getPackager().resolve(resolver),
        haskellConfig.getHaskellVersion(),
        depType,
        getPackageInfo(target),
        depPackages,
        compileRule.getModules(),
        libraries,
        interfaces,
        objects);
  }

  private HaskellPackageRule requirePackage(
      BuildTarget baseTarget,
      ProjectFilesystem projectFilesystem,
      BuildRuleParams baseParams,
      BuildRuleResolver resolver,
      SourcePathResolver pathResolver,
      SourcePathRuleFinder ruleFinder,
      CxxPlatform cxxPlatform,
      HaskellLibraryDescriptionArg args,
      ImmutableSet<BuildRule> deps,
      Linker.LinkableDepType depType,
      boolean hsProfile)
      throws NoSuchBuildTargetException {
    Preconditions.checkArgument(
        Sets.intersection(
                baseTarget.getFlavors(), Sets.union(Type.FLAVOR_VALUES, cxxPlatforms.getFlavors()))
            .isEmpty());
    BuildTarget target = baseTarget.withAppendedFlavors(cxxPlatform.getFlavor());
    switch (depType) {
      case SHARED:
        target = target.withAppendedFlavors(Type.PACKAGE_SHARED.getFlavor());
        break;
      case STATIC:
        target = target.withAppendedFlavors(Type.PACKAGE_STATIC.getFlavor());
        break;
      case STATIC_PIC:
        target = target.withAppendedFlavors(Type.PACKAGE_STATIC_PIC.getFlavor());
        break;
      default:
        throw new IllegalStateException();
    }

    if (hsProfile) {
      target = target.withAppendedFlavors(HaskellDescriptionUtils.PROF);
    }

    Optional<HaskellPackageRule> packageRule =
        resolver.getRuleOptionalWithType(target, HaskellPackageRule.class);
    if (packageRule.isPresent()) {
      return packageRule.get();
    }
    return resolver.addToIndex(
        createPackage(
            target,
            projectFilesystem,
            baseParams,
            resolver,
            pathResolver,
            ruleFinder,
            cxxPlatform,
            args,
            deps,
            depType,
            hsProfile));
  }

  private HaskellLinkRule createSharedLibrary(
      BuildTarget target,
      ProjectFilesystem projectFilesystem,
      BuildRuleParams baseParams,
      BuildRuleResolver resolver,
      SourcePathResolver pathResolver,
      SourcePathRuleFinder ruleFinder,
      CxxPlatform cxxPlatform,
      HaskellLibraryDescriptionArg args,
      ImmutableSet<BuildRule> deps)
      throws NoSuchBuildTargetException {
    HaskellCompileRule compileRule =
        requireCompileRule(
            target,
            projectFilesystem,
            baseParams,
            resolver,
            pathResolver,
            ruleFinder,
            cxxPlatform,
            args,
            deps,
            Linker.LinkableDepType.SHARED,
            false);

    String name =
        CxxDescriptionEnhancer.getSharedLibrarySoname(
            Optional.empty(), target.withFlavors(), cxxPlatform);
    Path outputPath = BuildTargets.getGenPath(projectFilesystem, target, "%s").resolve(name);

    return HaskellDescriptionUtils.createLinkRule(
        target,
        projectFilesystem,
        baseParams,
        resolver,
        ruleFinder,
        cxxPlatform,
        haskellConfig,
        Linker.LinkType.SHARED,
        ImmutableList.of(),
        ImmutableList.copyOf(SourcePathArg.from(compileRule.getObjects())),
        RichStream.from(deps).filter(NativeLinkable.class).toImmutableList(),
        ImmutableSet.of(),
        Linker.LinkableDepType.SHARED,
        outputPath,
        Optional.of(name),
        false);
  }

  private HaskellLinkRule requireSharedLibrary(
      BuildTarget baseTarget,
      ProjectFilesystem projectFilesystem,
      BuildRuleParams baseParams,
      BuildRuleResolver resolver,
      SourcePathResolver pathResolver,
      SourcePathRuleFinder ruleFinder,
      CxxPlatform cxxPlatform,
      HaskellLibraryDescriptionArg args,
      ImmutableSet<BuildRule> deps)
      throws NoSuchBuildTargetException {
    Preconditions.checkArgument(
        Sets.intersection(
                baseTarget.getFlavors(), Sets.union(Type.FLAVOR_VALUES, cxxPlatforms.getFlavors()))
            .isEmpty());
    BuildTarget target =
        baseTarget.withAppendedFlavors(Type.SHARED.getFlavor(), cxxPlatform.getFlavor());

    Optional<HaskellLinkRule> linkRule =
        resolver.getRuleOptionalWithType(target, HaskellLinkRule.class);
    if (linkRule.isPresent()) {
      return linkRule.get();
    }
    return resolver.addToIndex(
        createSharedLibrary(
            target,
            projectFilesystem,
            baseParams,
            resolver,
            pathResolver,
            ruleFinder,
            cxxPlatform,
            args,
            deps));
  }

  @Override
  public BuildRule createBuildRule(
      TargetGraph targetGraph,
      BuildTarget buildTarget,
      final ProjectFilesystem projectFilesystem,
      BuildRuleParams params,
      final BuildRuleResolver resolver,
      CellPathResolver cellRoots,
      final HaskellLibraryDescriptionArg args)
      throws NoSuchBuildTargetException {

    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    final SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
    CxxDeps allDeps =
        CxxDeps.builder().addDeps(args.getDeps()).addPlatformDeps(args.getPlatformDeps()).build();

    // See if we're building a particular "type" and "platform" of this library, and if so, extract
    // them from the flavors attached to the build target.
    Optional<Map.Entry<Flavor, Type>> type = LIBRARY_TYPE.getFlavorAndValue(buildTarget);
    Optional<CxxPlatform> cxxPlatform = cxxPlatforms.getValue(buildTarget);
    if (type.isPresent()) {
      Preconditions.checkState(cxxPlatform.isPresent());

      // Get the base build, without any flavors referring to the library type or platform.
      BuildTarget baseTarget =
          buildTarget.withoutFlavors(Sets.union(Type.FLAVOR_VALUES, cxxPlatforms.getFlavors()));

      ImmutableSet<BuildRule> deps = allDeps.get(resolver, cxxPlatform.get());

      switch (type.get().getValue()) {
        case PACKAGE_SHARED:
        case PACKAGE_STATIC:
        case PACKAGE_STATIC_PIC:
          Linker.LinkableDepType depType;
          if (type.get().getValue().equals(Type.PACKAGE_SHARED)) {
            depType = Linker.LinkableDepType.SHARED;
          } else if (type.get().getValue().equals(Type.PACKAGE_STATIC)) {
            depType = Linker.LinkableDepType.STATIC;
          } else {
            depType = Linker.LinkableDepType.STATIC_PIC;
          }
          return requirePackage(
              baseTarget,
              projectFilesystem,
              params,
              resolver,
              pathResolver,
              ruleFinder,
              cxxPlatform.get(),
              args,
              deps,
              depType,
              false);
        case SHARED:
          return requireSharedLibrary(
              baseTarget,
              projectFilesystem,
              params,
              resolver,
              pathResolver,
              ruleFinder,
              cxxPlatform.get(),
              args,
              deps);
        case STATIC_PIC:
        case STATIC:
          return requireStaticLibrary(
              baseTarget,
              projectFilesystem,
              params,
              resolver,
              pathResolver,
              ruleFinder,
              cxxPlatform.get(),
              args,
              deps,
              type.get().getValue() == Type.STATIC
                  ? Linker.LinkableDepType.STATIC
                  : Linker.LinkableDepType.STATIC_PIC,
              false);
      }

      throw new IllegalStateException(
          String.format("%s: unexpected type `%s`", buildTarget, type.get().getValue()));
    }

    return new HaskellLibrary(buildTarget, projectFilesystem, params) {

      @Override
      public Iterable<BuildRule> getCompileDeps(CxxPlatform cxxPlatform) {
        return RichStream.from(allDeps.get(resolver, cxxPlatform))
            .filter(dep -> dep instanceof HaskellCompileDep || dep instanceof CxxPreprocessorDep)
            .toImmutableList();
      }

      @Override
      public HaskellCompileInput getCompileInput(
          CxxPlatform cxxPlatform, Linker.LinkableDepType depType, boolean hsProfile)
          throws NoSuchBuildTargetException {
        HaskellPackageRule rule =
            requirePackage(
                getBaseBuildTarget(getBuildTarget()),
                projectFilesystem,
                params,
                resolver,
                pathResolver,
                ruleFinder,
                cxxPlatform,
                args,
                allDeps.get(resolver, cxxPlatform),
                depType,
                hsProfile);
        return HaskellCompileInput.builder().addPackages(rule.getPackage()).build();
      }

      @Override
      public Iterable<? extends NativeLinkable> getNativeLinkableDeps() {
        return ImmutableList.of();
      }

      @Override
      public Iterable<? extends NativeLinkable> getNativeLinkableExportedDepsForPlatform(
          CxxPlatform cxxPlatform) {
        return RichStream.from(allDeps.get(resolver, cxxPlatform))
            .filter(NativeLinkable.class)
            .toImmutableList();
      }

      @Override
      public Iterable<? extends NativeLinkable> getNativeLinkableExportedDeps() {
        return RichStream.from(allDeps.getForAllPlatforms(resolver))
            .filter(NativeLinkable.class)
            .toImmutableList();
      }

      @Override
      public NativeLinkableInput getNativeLinkableInput(
          CxxPlatform cxxPlatform,
          Linker.LinkableDepType type,
          boolean forceLinkWhole,
          ImmutableSet<NativeLinkable.LanguageExtensions> languageExtensions)
          throws NoSuchBuildTargetException {
        Iterable<com.facebook.buck.rules.args.Arg> linkArgs;
        switch (type) {
          case STATIC:
          case STATIC_PIC:
            Archive archive =
                requireStaticLibrary(
                    getBaseBuildTarget(getBuildTarget()),
                    projectFilesystem,
                    params,
                    resolver,
                    pathResolver,
                    ruleFinder,
                    cxxPlatform,
                    args,
                    allDeps.get(resolver, cxxPlatform),
                    type,
                    false);
            linkArgs =
                args.getLinkWhole() || forceLinkWhole
                    ? cxxPlatform.getLd().resolve(resolver).linkWhole(archive.toArg())
                    : ImmutableList.of(archive.toArg());
            break;
          case SHARED:
            BuildRule rule =
                requireSharedLibrary(
                    getBaseBuildTarget(getBuildTarget()),
                    projectFilesystem,
                    params,
                    resolver,
                    pathResolver,
                    ruleFinder,
                    cxxPlatform,
                    args,
                    allDeps.get(resolver, cxxPlatform));
            linkArgs = ImmutableList.of(SourcePathArg.of(rule.getSourcePathToOutput()));
            break;
          default:
            throw new IllegalStateException();
        }
        return NativeLinkableInput.builder().addAllArgs(linkArgs).build();
      }

      @Override
      public Linkage getPreferredLinkage(CxxPlatform cxxPlatform) {
        return args.getPreferredLinkage();
      }

      @Override
      public ImmutableMap<String, SourcePath> getSharedLibraries(CxxPlatform cxxPlatform)
          throws NoSuchBuildTargetException {
        ImmutableMap.Builder<String, SourcePath> libs = ImmutableMap.builder();
        String sharedLibrarySoname =
            CxxDescriptionEnhancer.getSharedLibrarySoname(
                Optional.empty(), getBuildTarget(), cxxPlatform);
        BuildRule sharedLibraryBuildRule =
            requireSharedLibrary(
                getBaseBuildTarget(getBuildTarget()),
                projectFilesystem,
                params,
                resolver,
                pathResolver,
                ruleFinder,
                cxxPlatform,
                args,
                allDeps.get(resolver, cxxPlatform));
        libs.put(sharedLibrarySoname, sharedLibraryBuildRule.getSourcePathToOutput());
        return libs.build();
      }
    };
  }

  @Override
  public boolean hasFlavors(ImmutableSet<Flavor> flavors) {
    if (cxxPlatforms.containsAnyOf(flavors)) {
      return true;
    }

    for (Type type : Type.values()) {
      if (flavors.contains(type.getFlavor())) {
        return true;
      }
    }

    return false;
  }

  @Override
  public void findDepsForTargetFromConstructorArgs(
      BuildTarget buildTarget,
      CellPathResolver cellRoots,
      AbstractHaskellLibraryDescriptionArg constructorArg,
      ImmutableCollection.Builder<BuildTarget> extraDepsBuilder,
      ImmutableCollection.Builder<BuildTarget> targetGraphOnlyDepsBuilder) {
    HaskellDescriptionUtils.getParseTimeDeps(
        haskellConfig, cxxPlatforms.getValues(), extraDepsBuilder);
  }

  protected enum Type implements FlavorConvertible {
    PACKAGE_SHARED(InternalFlavor.of("package-shared")),
    PACKAGE_STATIC(InternalFlavor.of("package-static")),
    PACKAGE_STATIC_PIC(InternalFlavor.of("package-static-pic")),

    SHARED(CxxDescriptionEnhancer.SHARED_FLAVOR),
    STATIC(CxxDescriptionEnhancer.STATIC_FLAVOR),
    STATIC_PIC(CxxDescriptionEnhancer.STATIC_PIC_FLAVOR),
    ;

    public static final ImmutableSet<Flavor> FLAVOR_VALUES =
        ImmutableList.copyOf(Type.values())
            .stream()
            .map(Type::getFlavor)
            .collect(MoreCollectors.toImmutableSet());

    private final Flavor flavor;

    Type(Flavor flavor) {
      this.flavor = flavor;
    }

    @Override
    public Flavor getFlavor() {
      return flavor;
    }
  }

  @BuckStyleImmutable
  @Value.Immutable
  interface AbstractHaskellLibraryDescriptionArg extends CommonDescriptionArg, HasDeclaredDeps {
    @Value.Default
    default SourceList getSrcs() {
      return SourceList.EMPTY;
    }

    ImmutableList<StringWithMacros> getLinkerFlags();

    ImmutableList<String> getCompilerFlags();

    @Value.Default
    default PatternMatchedCollection<ImmutableSortedSet<BuildTarget>> getPlatformDeps() {
      return PatternMatchedCollection.of();
    }

    @Value.Default
    default boolean getLinkWhole() {
      return false;
    }

    @Value.Default
    default NativeLinkable.Linkage getPreferredLinkage() {
      return NativeLinkable.Linkage.ANY;
    }
  }
}


text:
#ifndef ALINOUS_COMPILE_ANALYSE_TOOLS_FUNCTIONCALLCOLLECTOR_H_
#define ALINOUS_COMPILE_ANALYSE_TOOLS_FUNCTIONCALLCOLLECTOR_H_
namespace alinous{namespace annotation{
class OneSource;
}}
namespace alinous {namespace compile {
class AbstractSrcElement;}}

namespace alinous {namespace compile {namespace expression {namespace expstream {
class FunctionCallExpression;}}}}

namespace alinous {namespace compile {
class IAlinousElementVisitor;}}

namespace java {namespace lang {
class IObject;
}}

namespace alinous {
class ThreadContext;
}

namespace alinous {namespace compile {namespace analyse {namespace tools {

using namespace ::alinous;
using namespace ::java::lang;
using ::java::util::Iterator;
using ::java::util::ArrayList;
using ::alinous::compile::AbstractSrcElement;
using ::alinous::compile::IAlinousElementVisitor;
using ::alinous::compile::expression::expstream::FunctionCallExpression;

class FunctionCallCollector final : public IAlinousElementVisitor, public virtual IObject {
public:
	FunctionCallCollector(const FunctionCallCollector& base) = default;
public:
	FunctionCallCollector(ThreadContext* ctx) throw() ;
	void __construct_impl(ThreadContext* ctx) throw() ;
	virtual ~FunctionCallCollector() throw();
	virtual void __releaseRegerences(bool prepare, ThreadContext* ctx) throw();
private:
	ArrayList<FunctionCallExpression>* list;
public:
	bool visit(AbstractSrcElement* element, AbstractSrcElement* parent, ThreadContext* ctx) throw()  final;
	ArrayList<FunctionCallExpression>* getList(ThreadContext* ctx) throw() ;
public:
	static bool __init_done;
	static bool __init_static_variables();
public:
	static void __cleanUp(ThreadContext* ctx);
};

}}}}

#endif /* end of ALINOUS_COMPILE_ANALYSE_TOOLS_FUNCTIONCALLCOLLECTOR_H_ */


text:
import logging
import sys

from dino import environ
from dino import utils
from dino.config import SessionKeys
from dino.config import UserKeys
from dino.exceptions import NoSuchUserException

class OnStatusHooks(object):
    logger = logging.getLogger(__name__)

    @staticmethod
    def set_status(arg: tuple) -> None:
        data, activity = arg

        user_id = activity.actor.id
        user_name = environ.env.session.get(SessionKeys.user_name.value, None)
        image = environ.env.session.get(SessionKeys.image.value, '')
        status = activity.verb

        if user_name is None:
            try:
                user_name = utils.get_user_name_for(user_id)
            except NoSuchUserException:
                user_name = str(user_id)

        if not utils.is_valid_id(user_id):
            OnStatusHooks.logger.warning('got invalid user id for activity: {}'.format(str(data)))
            return

        if utils.is_super_user(user_id) or utils.is_global_moderator(user_id):
            OnStatusHooks.log_admin_activity(user_id, user_name, status)

        if status == 'online':
            OnStatusHooks.set_online(user_id, user_name, image)
        elif status == 'invisible':
            stage = 'status'
            if hasattr(activity.actor, 'summary'):
                stage = activity.actor.summary

            OnStatusHooks.set_invisible(user_id, user_name, stage=stage)
        elif status == 'visible':
            OnStatusHooks.set_visible(user_id, user_name)
        elif status == 'offline':
            OnStatusHooks.set_offline(user_id, user_name)

        if status in {"offline", "invisible"}:
            utils.add_last_online_at_to_event(data)

        environ.env.publish(data, external=True)

    @staticmethod
    def log_admin_activity(user_id, user_name, status):
        try:
            info_message = \
                'op {} ({}) requested to change status to {}; user status is currently set to {}'.format(
                    user_id,
                    user_name,
                    status,
                    utils.get_user_status(user_id)
                )
            OnStatusHooks.logger.info(info_message)
        except NoSuchUserException:
            OnStatusHooks.logger.error('no username found for op user {}'.format(user_id))
        except Exception as e:
            OnStatusHooks.logger.error('exception while getting username for op {}: {}'.format(user_id, str(e)))
            OnStatusHooks.logger.exception(e)
            environ.env.capture_exception(sys.exc_info())

    @staticmethod
    def set_offline(user_id: str, user_name: str) -> None:
        OnStatusHooks.logger.info('setting user {} ({}) to offline'.format(
            user_id, user_name,
        ))
        environ.env.db.set_user_offline(user_id)
        activity_json = utils.activity_for_disconnect(user_id, user_name)
        rooms = utils.rooms_for_user(user_id)
        for room_id in rooms:
            environ.env.emit(
                'gn_user_disconnected', activity_json, room=room_id, broadcast=True,
                include_self=False, namespace='/ws')

    @staticmethod
    def set_visible(user_id: str, user_name: str) -> None:
        user_status = utils.get_user_status(user_id, skip_cache=True)
        if user_status in {UserKeys.STATUS_AVAILABLE, UserKeys.STATUS_CHAT}:
            return

        # status is UserKeys.STATUS_VISIBLE, but is in multicast so the user is online
        if environ.env.cache.user_is_in_multicast(user_id):
            OnStatusHooks.logger.info(
                'setting user {} ({}) to visible (online), was invisible (online)'.format(user_id, user_name))
            OnStatusHooks.set_online(user_id, user_name)

        # otherwise status is UserKeys.STATUS_INVISIBLE, but if not in multicast the user is offline
        # TODO: when choosing to login invisibly, this is called before the user connects to dino, so should NOT do set_offline()
        # TODO: should visible login call set_status with 'online' or 'visible'?
        else:
            OnStatusHooks.logger.info(
                'setting user {} ({}) to visible (offline), was invisible (offline)'.format(user_id, user_name))
            OnStatusHooks.set_offline(user_id, user_name)

    @staticmethod
    def set_invisible(user_id: str, user_name: str, stage: str) -> None:
        user_status = utils.get_user_status(user_id)

        # no need to set it again if already invisible
        if user_status == UserKeys.STATUS_INVISIBLE:
            return

        OnStatusHooks.logger.info('setting user {} ({}) to invisible'.format(
            user_id, user_name,
        ))

        # when logging in as 'invisible', the rest call can happen after ws
        # logs in, in which case we don't want to update last_online
        if stage == 'login':
            is_offline = True
        else:
            is_offline = not utils.user_is_online(user_id)

        environ.env.db.set_user_invisible(user_id, is_offline=is_offline)

        if is_offline:
            # nothing more to do if offline already
            return

        disconnect_activity = utils.activity_for_disconnect(user_id, user_name)

        rooms = utils.rooms_for_user(user_id)
        for room_id in rooms:
            admins_in_room = environ.env.db.get_admins_in_room(room_id, user_id)
            if admins_in_room is None or len(admins_in_room) == 0:
                environ.env.emit('gn_user_disconnected', disconnect_activity, room=room_id, broadcast=True,
                                 include_self=False, namespace='/ws')
                continue

            users_in_room = utils.get_users_in_room(room_id)
            for other_user_id, _ in users_in_room.items():
                if other_user_id in admins_in_room:
                    continue
                environ.env.emit(
                    'gn_user_disconnected', disconnect_activity, room=other_user_id, broadcast=True,
                    include_self=False, namespace='/ws')

            invisible_activity = utils.activity_for_going_invisible(user_id)
            for admin_id in admins_in_room:
                environ.env.emit(
                    'gn_user_invisible', invisible_activity, room=admin_id, broadcast=False, namespace='/ws')

    @staticmethod
    def set_online(user_id: str, user_name: str, image: str = '') -> None:
        was_invisible = utils.user_is_invisible(user_id)
        OnStatusHooks.logger.info('setting user {} ({}) online (was invisible before? {})'.format(
            user_id, user_name, was_invisible
        ))
        environ.env.db.set_user_online(user_id)
        rooms = utils.rooms_for_user(user_id)

        if not was_invisible:
            for room_id in rooms:
                room_name = utils.get_room_name(room_id)
                join_activity = utils.activity_for_user_joined(user_id, user_name, room_id, room_name, image)
                environ.env.emit(
                    'gn_user_joined', join_activity, room=room_id, broadcast=True,
                    include_self=False, namespace='/ws')
            return

        visible_activity = utils.activity_for_going_visible(user_id)
        for room_id in rooms:
            room_name = utils.get_room_name(room_id)
            join_activity = utils.activity_for_user_joined(user_id, user_name, room_id, room_name, image)
            admins_in_room = environ.env.db.get_admins_in_room(room_id, user_id)

            if admins_in_room is None or len(admins_in_room) == 0:
                environ.env.emit(
                    'gn_user_joined', join_activity, room=room_id, broadcast=True,
                    include_self=False, namespace='/ws')
                continue

            users_in_room = utils.get_users_in_room(room_id).copy()
            for user_id_in_room, _ in users_in_room.items():
                if user_id_in_room in admins_in_room:
                    continue
                environ.env.emit(
                    'gn_user_joined', join_activity, room=user_id_in_room, broadcast=True,
                    include_self=False, namespace='/ws')

            for admin_id in admins_in_room:
                environ.env.emit(
                    'gn_user_visible', visible_activity, room=admin_id, broadcast=False, namespace='/ws')

@environ.env.observer.on('on_status')
def _on_status_set_status(arg: tuple) -> None:
    OnStatusHooks.set_status(arg)


text:
/**
 * Created by yqdong on 2017/9/6.
 * qq: 1013501639
 * @author yqdong
 *
 */
import './main.sass'
import Button from './components/button/button'
import ButtonGroup from './components/button/buttonGroup'

import ZoomPanel from './components/zoomPanel/zoomPanel'
import Dialog from './components/dialog/dialog'

import ZoomAbleSunburst from './components/charts/sunburst/zoomAbleSunburst'
import PathTree from './components/charts/pathTree/pathTree'

import Loading from './components/loading/loading'
import Copy from './components/copy/copy'
import Badge from './components/badge/badge'
import Tooltip from './components/tooltip/tooltip'

export {
  // form
  Button,
  ButtonGroup,
  // layout
  ZoomPanel,
  Dialog,
  // charts
  ZoomAbleSunburst,
  PathTree,
  // other
  Loading,
  Copy,
  Badge,
  Tooltip
}


text:
class CreateHitChallenges < ActiveRecord::Migration
  def change
    create_table :hit_challenges do |t|
      t.integer :game_id, null: false
      t.integer :suite_id, null: false
      t.string :title
      t.boolean :over, default: false

      t.timestamps null: false
    end
  end
end


text:
package com.intellij.openapi.vfs;

import com.intellij.concurrency.JobLauncher;
import com.intellij.concurrency.JobSchedulerImpl;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.IoTestUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.newvfs.ManagingFS;
import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
import com.intellij.testFramework.EdtTestUtil;
import com.intellij.testFramework.JITSensitive;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.SkipSlowTestLocally;
import com.intellij.testFramework.fixtures.BareTestFixtureTestCase;
import com.intellij.testFramework.fixtures.impl.LightTempDirTestFixtureImpl;
import com.intellij.testFramework.rules.TempDirectory;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.ThrowableRunnable;
import com.intellij.util.TimeoutUtil;
import com.intellij.util.ui.UIUtil;
import org.junit.Rule;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.*;

@JITSensitive
@SkipSlowTestLocally
public class VfsUtilPerformanceTest extends BareTestFixtureTestCase {
  @Rule public TempDirectory myTempDir = new TempDirectory();

  @Test
  public void testFindChildByNamePerformance() throws IOException {
    File tempDir = myTempDir.newFolder();
    VirtualFile vDir = LocalFileSystem.getInstance().findFileByIoFile(tempDir);
    assertNotNull(vDir);
    assertTrue(vDir.isDirectory());

    new WriteCommandAction.Simple(null) {
      @Override
      protected void run() throws Throwable {
        for (int i = 0; i < 10000; i++) {
          String name = i + ".txt";
          vDir.createChildData(vDir, name);
        }
      }
    }.execute();

    VirtualFile theChild = vDir.findChild("5111.txt");
    assertNotNull(theChild);
    UIUtil.pump(); // wait for all event handlers to calm down

    System.out.println("Start searching...");
    PlatformTestUtil.startPerformanceTest("find child is slow", 1000, () -> {
      for (int i = 0; i < 1000000; i++) {
        VirtualFile child = vDir.findChild("5111.txt");
        assertEquals(theChild, child);
      }
    }).useLegacyScaling().assertTiming();

    new WriteCommandAction.Simple(null) {
      @Override
      protected void run() throws Throwable {
        for (VirtualFile file : vDir.getChildren()) {
          file.delete(this);
        }
      }
    }.execute().throwException();
  }

  @Test
  public void testFindRootPerformance() throws IOException {
    File tempJar = IoTestUtil.createTestJar(myTempDir.newFile("test.jar"));
    VirtualFile jar = LocalFileSystem.getInstance().findFileByIoFile(tempJar);
    assertNotNull(jar);

    JarFileSystem fs = JarFileSystem.getInstance();
    String path = jar.getPath() + "!/";
    NewVirtualFile root = ManagingFS.getInstance().findRoot(path, fs);
    PlatformTestUtil.startPerformanceTest(
      "find root is slow", 5000,
      () -> JobLauncher.getInstance().invokeConcurrentlyUnderProgress(
        Collections.nCopies(500, null), null, false, false,
        o -> {
          for (int i = 0; i < 20000; i++) {
            NewVirtualFile rootJar = ManagingFS.getInstance().findRoot(path, fs);
            assertNotNull(rootJar);
            assertSame(root, rootJar);
          }
          return true;
        })).useLegacyScaling().assertTiming();
  }

  @Test
  public void testGetParentPerformance() throws IOException {
    File tempDir = myTempDir.newFolder();
    VirtualFile vDir = LocalFileSystem.getInstance().findFileByIoFile(tempDir);
    assertNotNull(vDir);
    assertTrue(vDir.isDirectory());
    int depth = 10;
    new WriteCommandAction.Simple(null) {
      @Override
      protected void run() throws Throwable {
        VirtualFile dir = vDir;
        for (int i = 0; i < depth; i++) {
          dir = dir.createChildDirectory(this, "foo");
        }
        VirtualFile leafDir = dir;
        ThrowableRunnable checkPerformance = new ThrowableRunnable() {
          private VirtualFile findRoot(VirtualFile file) {
            while (true) {
              VirtualFile parent = file.getParent();
              if (parent == null) {
                return file;
              }
              file = parent;
            }
          }

          @Override
          public void run() throws Throwable {
            for (int i = 0; i < 5000000; i++) {
              checkRootsEqual();
            }
          }

          private void checkRootsEqual() {
            assertEquals(findRoot(vDir), findRoot(leafDir));
          }
        };
        int time = 1200;
        PlatformTestUtil.startPerformanceTest("getParent is slow before movement", time, checkPerformance).useLegacyScaling().assertTiming();
        VirtualFile dir1 = vDir.createChildDirectory(this, "dir1");
        VirtualFile dir2 = vDir.createChildDirectory(this, "dir2");
        for (int i = 0; i < 13; i++) {  /*13 is max length with THashMap capacity of 17, we get plenty collisions then*/
          dir1.createChildData(this, "a" + i + ".txt").move(this, dir2);
        }
        PlatformTestUtil.startPerformanceTest("getParent is slow after movement", time, checkPerformance).useLegacyScaling().assertTiming();
      }
    }.execute();
  }

  @Test
  public void testGetPathPerformance() throws Exception {
    LightTempDirTestFixtureImpl fixture = new LightTempDirTestFixtureImpl();
    fixture.setUp();
    Disposer.register(getTestRootDisposable(), () -> {
      try {
        fixture.tearDown();
      }
      catch (Exception e) {
        ExceptionUtil.rethrowAllAsUnchecked(e);
      }
    });

    EdtTestUtil.runInEdtAndWait(() -> {
      String path = "unitTest_testGetPathPerformance_6542623412414351229/" +
                    "junit6921058097194294088/" +
                    StringUtil.repeat("xxx/", 50) +
                    "fff.txt";
      VirtualFile file = fixture.findOrCreateDir(path);

      PlatformTestUtil.startPerformanceTest("VF.getPath() performance failed", 4000, () -> {
        for (int i = 0; i < 1000000; ++i) {
          file.getPath();
        }
      }).cpuBound().useLegacyScaling().assertTiming();
    });
  }

  @Test
  public void testAsyncRefresh() throws Throwable {
    Ref<Throwable> ex = Ref.create();
    boolean success = JobLauncher.getInstance().invokeConcurrentlyUnderProgress(
      Arrays.asList(new Object[JobSchedulerImpl.CORES_COUNT]), ProgressManager.getInstance().getProgressIndicator(), false,
      o -> {
        try {
          doAsyncRefreshTest();
        }
        catch (Throwable t) {
          ex.set(t);
        }
        return true;
      });

    if (!ex.isNull()) throw ex.get();
    if (!success) fail("!success");
  }

  private void doAsyncRefreshTest() throws Exception {
    int N = 1000;
    byte[] data = "xxx".getBytes(CharsetToolkit.UTF8_CHARSET);

    File temp = myTempDir.newFolder();
    LocalFileSystem fs = LocalFileSystem.getInstance();
    VirtualFile vTemp = fs.findFileByIoFile(temp);
    assertNotNull(vTemp);

    VirtualFile[] children = new VirtualFile[N];
    long[] timestamp = new long[N];

    for (int i = 0; i < N; i++) {
      File file = new File(temp, i + ".txt");
      FileUtil.writeToFile(file, data);
      VirtualFile child = fs.refreshAndFindFileByIoFile(file);
      assertNotNull(child);
      children[i] = child;
      timestamp[i] = file.lastModified();
    }

    vTemp.refresh(false, true);

    for (int i = 0; i < N; i++) {
      File file = new File(temp, i + ".txt");
      assertEquals(timestamp[i], file.lastModified());
      VirtualFile child = fs.findFileByIoFile(file);
      assertNotNull(child);
      IoTestUtil.assertTimestampsEqual(timestamp[i], child.getTimeStamp());
    }

    for (int i = 0; i < N; i++) {
      File file = new File(temp, i + ".txt");
      FileUtil.writeToFile(file, data);
      assertTrue(file.setLastModified(timestamp[i] - 2000));
      long modified = file.lastModified();
      assertTrue("File:" + file.getPath() + "; time:" + modified, timestamp[i] != modified);
      timestamp[i] = modified;
      IoTestUtil.assertTimestampsNotEqual(children[i].getTimeStamp(), modified);
    }

    CountDownLatch latch = new CountDownLatch(N);
    for (VirtualFile child : children) {
      child.refresh(true, true, latch::countDown);
      TimeoutUtil.sleep(10);
    }
    while (latch.getCount() > 0) {
      latch.await(100, TimeUnit.MILLISECONDS);
      UIUtil.pump();
    }

    for (int i = 0; i < N; i++) {
      VirtualFile child = children[i];
      IoTestUtil.assertTimestampsEqual(timestamp[i], child.getTimeStamp());
    }
  }
}