text:
//===--- USRLocFinder.cpp - Clang refactoring library ---------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Methods for finding all instances of a USR. Our strategy is very
/// simple; we just compare the USR at every relevant AST node with the one
/// provided.
///
//===----------------------------------------------------------------------===//

#include "clang/Tooling/Refactoring/Rename/USRLocFinder.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/Lexer.h"
#include "clang/Tooling/Core/Lookup.h"
#include "clang/Tooling/Refactoring/RecursiveSymbolVisitor.h"
#include "clang/Tooling/Refactoring/Rename/SymbolName.h"
#include "clang/Tooling/Refactoring/Rename/USRFinder.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include <cstddef>
#include <set>
#include <string>
#include <vector>

using namespace llvm;

namespace clang {
namespace tooling {

namespace {

// Returns true if the given Loc is valid for edit. We don't edit the
// SourceLocations that are valid or in temporary buffer.
bool IsValidEditLoc(const clang::SourceManager& SM, clang::SourceLocation Loc) {
  if (Loc.isInvalid())
    return false;
  const clang::FullSourceLoc FullLoc(Loc, SM);
  std::pair<clang::FileID, unsigned> FileIdAndOffset =
      FullLoc.getSpellingLoc().getDecomposedLoc();
  return SM.getFileEntryForID(FileIdAndOffset.first) != nullptr;
}

// This visitor recursively searches for all instances of a USR in a
// translation unit and stores them for later usage.
class USRLocFindingASTVisitor
    : public RecursiveSymbolVisitor<USRLocFindingASTVisitor> {
public:
  explicit USRLocFindingASTVisitor(const std::vector<std::string> &USRs,
                                   StringRef PrevName,
                                   const ASTContext &Context)
      : RecursiveSymbolVisitor(Context.getSourceManager(),
                               Context.getLangOpts()),
        USRSet(USRs.begin(), USRs.end()), PrevName(PrevName), Context(Context) {
  }

  bool visitSymbolOccurrence(const NamedDecl *ND,
                             ArrayRef<SourceRange> NameRanges) {
    if (USRSet.find(getUSRForDecl(ND)) != USRSet.end()) {
      assert(NameRanges.size() == 1 &&
             "Multiple name pieces are not supported yet!");
      SourceLocation Loc = NameRanges[0].getBegin();
      const SourceManager &SM = Context.getSourceManager();
      // TODO: Deal with macro occurrences correctly.
      if (Loc.isMacroID())
        Loc = SM.getSpellingLoc(Loc);
      checkAndAddLocation(Loc);
    }
    return true;
  }

  // Non-visitors:

  /// Returns a set of unique symbol occurrences. Duplicate or
  /// overlapping occurrences are erroneous and should be reported!
  SymbolOccurrences takeOccurrences() { return std::move(Occurrences); }

private:
  void checkAndAddLocation(SourceLocation Loc) {
    const SourceLocation BeginLoc = Loc;
    const SourceLocation EndLoc = Lexer::getLocForEndOfToken(
        BeginLoc, 0, Context.getSourceManager(), Context.getLangOpts());
    StringRef TokenName =
        Lexer::getSourceText(CharSourceRange::getTokenRange(BeginLoc, EndLoc),
                             Context.getSourceManager(), Context.getLangOpts());
    size_t Offset = TokenName.find(PrevName.getNamePieces()[0]);

    // The token of the source location we find actually has the old
    // name.
    if (Offset != StringRef::npos)
      Occurrences.emplace_back(PrevName, SymbolOccurrence::MatchingSymbol,
                               BeginLoc.getLocWithOffset(Offset));
  }

  const std::set<std::string> USRSet;
  const SymbolName PrevName;
  SymbolOccurrences Occurrences;
  const ASTContext &Context;
};

SourceLocation StartLocationForType(TypeLoc TL) {
  // For elaborated types (e.g. `struct a::A`) we want the portion after the
  // `struct` but including the namespace qualifier, `a::`.
  if (auto ElaboratedTypeLoc = TL.getAs<clang::ElaboratedTypeLoc>()) {
    NestedNameSpecifierLoc NestedNameSpecifier =
        ElaboratedTypeLoc.getQualifierLoc();
    if (NestedNameSpecifier.getNestedNameSpecifier())
      return NestedNameSpecifier.getBeginLoc();
    TL = TL.getNextTypeLoc();
  }
  return TL.getBeginLoc();
}

SourceLocation EndLocationForType(TypeLoc TL) {
  // Dig past any namespace or keyword qualifications.
  while (TL.getTypeLocClass() == TypeLoc::Elaborated ||
         TL.getTypeLocClass() == TypeLoc::Qualified)
    TL = TL.getNextTypeLoc();

  // The location for template specializations (e.g. Foo<int>) includes the
  // templated types in its location range.  We want to restrict this to just
  // before the `<` character.
  if (TL.getTypeLocClass() == TypeLoc::TemplateSpecialization) {
    return TL.castAs<TemplateSpecializationTypeLoc>()
        .getLAngleLoc()
        .getLocWithOffset(-1);
  }
  return TL.getEndLoc();
}

NestedNameSpecifier *GetNestedNameForType(TypeLoc TL) {
  // Dig past any keyword qualifications.
  while (TL.getTypeLocClass() == TypeLoc::Qualified)
    TL = TL.getNextTypeLoc();

  // For elaborated types (e.g. `struct a::A`) we want the portion after the
  // `struct` but including the namespace qualifier, `a::`.
  if (auto ElaboratedTypeLoc = TL.getAs<clang::ElaboratedTypeLoc>())
    return ElaboratedTypeLoc.getQualifierLoc().getNestedNameSpecifier();
  return nullptr;
}

// Find all locations identified by the given USRs for rename.
//
// This class will traverse the AST and find every AST node whose USR is in the
// given USRs' set.
class RenameLocFinder : public RecursiveASTVisitor<RenameLocFinder> {
public:
  RenameLocFinder(llvm::ArrayRef<std::string> USRs, ASTContext &Context)
      : USRSet(USRs.begin(), USRs.end()), Context(Context) {}

  // A structure records all information of a symbol reference being renamed.
  // We try to add as few prefix qualifiers as possible.
  struct RenameInfo {
    // The begin location of a symbol being renamed.
    SourceLocation Begin;
    // The end location of a symbol being renamed.
    SourceLocation End;
    // The declaration of a symbol being renamed (can be nullptr).
    const NamedDecl *FromDecl;
    // The declaration in which the nested name is contained (can be nullptr).
    const Decl *Context;
    // The nested name being replaced (can be nullptr).
    const NestedNameSpecifier *Specifier;
    // Determine whether the prefix qualifiers of the NewName should be ignored.
    // Normally, we set it to true for the symbol declaration and definition to
    // avoid adding prefix qualifiers.
    // For example, if it is true and NewName is "a::b::foo", then the symbol
    // occurrence which the RenameInfo points to will be renamed to "foo".
    bool IgnorePrefixQualifers;
  };

  bool VisitNamedDecl(const NamedDecl *Decl) {
    // UsingDecl has been handled in other place.
    if (llvm::isa<UsingDecl>(Decl))
      return true;

    // DestructorDecl has been handled in Typeloc.
    if (llvm::isa<CXXDestructorDecl>(Decl))
      return true;

    if (Decl->isImplicit())
      return true;

    if (isInUSRSet(Decl)) {
      // For the case of renaming an alias template, we actually rename the
      // underlying alias declaration of the template.
      if (const auto* TAT = dyn_cast<TypeAliasTemplateDecl>(Decl))
        Decl = TAT->getTemplatedDecl();

      auto StartLoc = Decl->getLocation();
      auto EndLoc = StartLoc;
      if (IsValidEditLoc(Context.getSourceManager(), StartLoc)) {
        RenameInfo Info = {StartLoc,
                           EndLoc,
                           /*FromDecl=*/nullptr,
                           /*Context=*/nullptr,
                           /*Specifier=*/nullptr,
                           /*IgnorePrefixQualifers=*/true};
        RenameInfos.push_back(Info);
      }
    }
    return true;
  }

  bool VisitMemberExpr(const MemberExpr *Expr) {
    const NamedDecl *Decl = Expr->getFoundDecl();
    auto StartLoc = Expr->getMemberLoc();
    auto EndLoc = Expr->getMemberLoc();
    if (isInUSRSet(Decl)) {
      RenameInfos.push_back({StartLoc, EndLoc,
                            /*FromDecl=*/nullptr,
                            /*Context=*/nullptr,
                            /*Specifier=*/nullptr,
                            /*IgnorePrefixQualifiers=*/true});
    }
    return true;
  }

  bool VisitCXXConstructorDecl(const CXXConstructorDecl *CD) {
    // Fix the constructor initializer when renaming class members.
    for (const auto *Initializer : CD->inits()) {
      // Ignore implicit initializers.
      if (!Initializer->isWritten())
        continue;

      if (const FieldDecl *FD = Initializer->getMember()) {
        if (isInUSRSet(FD)) {
          auto Loc = Initializer->getSourceLocation();
          RenameInfos.push_back({Loc, Loc,
                                 /*FromDecl=*/nullptr,
                                 /*Context=*/nullptr,
                                 /*Specifier=*/nullptr,
                                 /*IgnorePrefixQualifiers=*/true});
        }
      }
    }
    return true;
  }

  bool VisitDeclRefExpr(const DeclRefExpr *Expr) {
    const NamedDecl *Decl = Expr->getFoundDecl();
    // Get the underlying declaration of the shadow declaration introduced by a
    // using declaration.
    if (auto *UsingShadow = llvm::dyn_cast<UsingShadowDecl>(Decl)) {
      Decl = UsingShadow->getTargetDecl();
    }

    auto StartLoc = Expr->getBeginLoc();
    // For template function call expressions like `foo<int>()`, we want to
    // restrict the end of location to just before the `<` character.
    SourceLocation EndLoc = Expr->hasExplicitTemplateArgs()
                                ? Expr->getLAngleLoc().getLocWithOffset(-1)
                                : Expr->getEndLoc();

    if (const auto *MD = llvm::dyn_cast<CXXMethodDecl>(Decl)) {
      if (isInUSRSet(MD)) {
        // Handle renaming static template class methods, we only rename the
        // name without prefix qualifiers and restrict the source range to the
        // name.
        RenameInfos.push_back({EndLoc, EndLoc,
                               /*FromDecl=*/nullptr,
                               /*Context=*/nullptr,
                               /*Specifier=*/nullptr,
                               /*IgnorePrefixQualifiers=*/true});
        return true;
      }
    }

    // In case of renaming an enum declaration, we have to explicitly handle
    // unscoped enum constants referenced in expressions (e.g.
    // "auto r = ns1::ns2::Green" where Green is an enum constant of an unscoped
    // enum decl "ns1::ns2::Color") as these enum constants cannot be caught by
    // TypeLoc.
    if (const auto *T = llvm::dyn_cast<EnumConstantDecl>(Decl)) {
      // FIXME: Handle the enum constant without prefix qualifiers (`a = Green`)
      // when renaming an unscoped enum declaration with a new namespace.
      if (!Expr->hasQualifier())
        return true;

      if (const auto *ED =
              llvm::dyn_cast_or_null<EnumDecl>(getClosestAncestorDecl(*T))) {
        if (ED->isScoped())
          return true;
        Decl = ED;
      }
      // The current fix would qualify "ns1::ns2::Green" as
      // "ns1::ns2::Color::Green".
      //
      // Get the EndLoc of the replacement by moving 1 character backward (
      // to exclude the last '::').
      //
      //    ns1::ns2::Green;
      //    ^      ^^
      // BeginLoc  |EndLoc of the qualifier
      //           new EndLoc
      EndLoc = Expr->getQualifierLoc().getEndLoc().getLocWithOffset(-1);
      assert(EndLoc.isValid() &&
             "The enum constant should have prefix qualifers.");
    }
    if (isInUSRSet(Decl) &&
        IsValidEditLoc(Context.getSourceManager(), StartLoc)) {
      RenameInfo Info = {StartLoc,
                         EndLoc,
                         Decl,
                         getClosestAncestorDecl(*Expr),
                         Expr->getQualifier(),
                         /*IgnorePrefixQualifers=*/false};
      RenameInfos.push_back(Info);
    }

    return true;
  }

  bool VisitUsingDecl(const UsingDecl *Using) {
    for (const auto *UsingShadow : Using->shadows()) {
      if (isInUSRSet(UsingShadow->getTargetDecl())) {
        UsingDecls.push_back(Using);
        break;
      }
    }
    return true;
  }

  bool VisitNestedNameSpecifierLocations(NestedNameSpecifierLoc NestedLoc) {
    if (!NestedLoc.getNestedNameSpecifier()->getAsType())
      return true;

    if (const auto *TargetDecl =
            getSupportedDeclFromTypeLoc(NestedLoc.getTypeLoc())) {
      if (isInUSRSet(TargetDecl)) {
        RenameInfo Info = {NestedLoc.getBeginLoc(),
                           EndLocationForType(NestedLoc.getTypeLoc()),
                           TargetDecl,
                           getClosestAncestorDecl(NestedLoc),
                           NestedLoc.getNestedNameSpecifier()->getPrefix(),
                           /*IgnorePrefixQualifers=*/false};
        RenameInfos.push_back(Info);
      }
    }
    return true;
  }

  bool VisitTypeLoc(TypeLoc Loc) {
    auto Parents = Context.getParents(Loc);
    TypeLoc ParentTypeLoc;
    if (!Parents.empty()) {
      // Handle cases of nested name specificier locations.
      //
      // The VisitNestedNameSpecifierLoc interface is not impelmented in
      // RecursiveASTVisitor, we have to handle it explicitly.
      if (const auto *NSL = Parents[0].get<NestedNameSpecifierLoc>()) {
        VisitNestedNameSpecifierLocations(*NSL);
        return true;
      }

      if (const auto *TL = Parents[0].get<TypeLoc>())
        ParentTypeLoc = *TL;
    }

    // Handle the outermost TypeLoc which is directly linked to the interesting
    // declaration and don't handle nested name specifier locations.
    if (const auto *TargetDecl = getSupportedDeclFromTypeLoc(Loc)) {
      if (isInUSRSet(TargetDecl)) {
        // Only handle the outermost typeLoc.
        //
        // For a type like "a::Foo", there will be two typeLocs for it.
        // One ElaboratedType, the other is RecordType:
        //
        //   ElaboratedType 0x33b9390 'a::Foo' sugar
        //   `-RecordType 0x338fef0 'class a::Foo'
        //     `-CXXRecord 0x338fe58 'Foo'
        //
        // Skip if this is an inner typeLoc.
        if (!ParentTypeLoc.isNull() &&
            isInUSRSet(getSupportedDeclFromTypeLoc(ParentTypeLoc)))
          return true;

        auto StartLoc = StartLocationForType(Loc);
        auto EndLoc = EndLocationForType(Loc);
        if (IsValidEditLoc(Context.getSourceManager(), StartLoc)) {
          RenameInfo Info = {StartLoc,
                             EndLoc,
                             TargetDecl,
                             getClosestAncestorDecl(Loc),
                             GetNestedNameForType(Loc),
                             /*IgnorePrefixQualifers=*/false};
          RenameInfos.push_back(Info);
        }
        return true;
      }
    }

    // Handle specific template class specialiation cases.
    if (const auto *TemplateSpecType =
            dyn_cast<TemplateSpecializationType>(Loc.getType())) {
      TypeLoc TargetLoc = Loc;
      if (!ParentTypeLoc.isNull()) {
        if (llvm::isa<ElaboratedType>(ParentTypeLoc.getType()))
          TargetLoc = ParentTypeLoc;
      }

      if (isInUSRSet(TemplateSpecType->getTemplateName().getAsTemplateDecl())) {
        TypeLoc TargetLoc = Loc;
        // FIXME: Find a better way to handle this case.
        // For the qualified template class specification type like
        // "ns::Foo<int>" in "ns::Foo<int>& f();", we want the parent typeLoc
        // (ElaboratedType) of the TemplateSpecializationType in order to
        // catch the prefix qualifiers "ns::".
        if (!ParentTypeLoc.isNull() &&
            llvm::isa<ElaboratedType>(ParentTypeLoc.getType()))
          TargetLoc = ParentTypeLoc;

        auto StartLoc = StartLocationForType(TargetLoc);
        auto EndLoc = EndLocationForType(TargetLoc);
        if (IsValidEditLoc(Context.getSourceManager(), StartLoc)) {
          RenameInfo Info = {
              StartLoc,
              EndLoc,
              TemplateSpecType->getTemplateName().getAsTemplateDecl(),
              getClosestAncestorDecl(
                  ast_type_traits::DynTypedNode::create(TargetLoc)),
              GetNestedNameForType(TargetLoc),
              /*IgnorePrefixQualifers=*/false};
          RenameInfos.push_back(Info);
        }
      }
    }
    return true;
  }

  // Returns a list of RenameInfo.
  const std::vector<RenameInfo> &getRenameInfos() const { return RenameInfos; }

  // Returns a list of using declarations which are needed to update.
  const std::vector<const UsingDecl *> &getUsingDecls() const {
    return UsingDecls;
  }

private:
  // Get the supported declaration from a given typeLoc. If the declaration type
  // is not supported, returns nullptr.
  const NamedDecl *getSupportedDeclFromTypeLoc(TypeLoc Loc) {
    if (const auto* TT = Loc.getType()->getAs<clang::TypedefType>())
      return TT->getDecl();
    if (const auto *RD = Loc.getType()->getAsCXXRecordDecl())
      return RD;
    if (const auto *ED =
            llvm::dyn_cast_or_null<EnumDecl>(Loc.getType()->getAsTagDecl()))
      return ED;
    return nullptr;
  }

  // Get the closest ancester which is a declaration of a given AST node.
  template <typename ASTNodeType>
  const Decl *getClosestAncestorDecl(const ASTNodeType &Node) {
    auto Parents = Context.getParents(Node);
    // FIXME: figure out how to handle it when there are multiple parents.
    if (Parents.size() != 1)
      return nullptr;
    if (ast_type_traits::ASTNodeKind::getFromNodeKind<Decl>().isBaseOf(
            Parents[0].getNodeKind()))
      return Parents[0].template get<Decl>();
    return getClosestAncestorDecl(Parents[0]);
  }

  // Get the parent typeLoc of a given typeLoc. If there is no such parent,
  // return nullptr.
  const TypeLoc *getParentTypeLoc(TypeLoc Loc) const {
    auto Parents = Context.getParents(Loc);
    // FIXME: figure out how to handle it when there are multiple parents.
    if (Parents.size() != 1)
      return nullptr;
    return Parents[0].get<TypeLoc>();
  }

  // Check whether the USR of a given Decl is in the USRSet.
  bool isInUSRSet(const Decl *Decl) const {
    auto USR = getUSRForDecl(Decl);
    if (USR.empty())
      return false;
    return llvm::is_contained(USRSet, USR);
  }

  const std::set<std::string> USRSet;
  ASTContext &Context;
  std::vector<RenameInfo> RenameInfos;
  // Record all interested using declarations which contains the using-shadow
  // declarations of the symbol declarations being renamed.
  std::vector<const UsingDecl *> UsingDecls;
};

} // namespace

SymbolOccurrences getOccurrencesOfUSRs(ArrayRef<std::string> USRs,
                                       StringRef PrevName, Decl *Decl) {
  USRLocFindingASTVisitor Visitor(USRs, PrevName, Decl->getASTContext());
  Visitor.TraverseDecl(Decl);
  return Visitor.takeOccurrences();
}

std::vector<tooling::AtomicChange>
createRenameAtomicChanges(llvm::ArrayRef<std::string> USRs,
                          llvm::StringRef NewName, Decl *TranslationUnitDecl) {
  RenameLocFinder Finder(USRs, TranslationUnitDecl->getASTContext());
  Finder.TraverseDecl(TranslationUnitDecl);

  const SourceManager &SM =
      TranslationUnitDecl->getASTContext().getSourceManager();

  std::vector<tooling::AtomicChange> AtomicChanges;
  auto Replace = [&](SourceLocation Start, SourceLocation End,
                     llvm::StringRef Text) {
    tooling::AtomicChange ReplaceChange = tooling::AtomicChange(SM, Start);
    llvm::Error Err = ReplaceChange.replace(
        SM, CharSourceRange::getTokenRange(Start, End), Text);
    if (Err) {
      llvm::errs() << "Failed to add replacement to AtomicChange: "
                   << llvm::toString(std::move(Err)) << "\n";
      return;
    }
    AtomicChanges.push_back(std::move(ReplaceChange));
  };

  for (const auto &RenameInfo : Finder.getRenameInfos()) {
    std::string ReplacedName = NewName.str();
    if (RenameInfo.IgnorePrefixQualifers) {
      // Get the name without prefix qualifiers from NewName.
      size_t LastColonPos = NewName.find_last_of(':');
      if (LastColonPos != std::string::npos)
        ReplacedName = NewName.substr(LastColonPos + 1);
    } else {
      if (RenameInfo.FromDecl && RenameInfo.Context) {
        if (!llvm::isa<clang::TranslationUnitDecl>(
                RenameInfo.Context->getDeclContext())) {
          ReplacedName = tooling::replaceNestedName(
              RenameInfo.Specifier, RenameInfo.Begin,
              RenameInfo.Context->getDeclContext(), RenameInfo.FromDecl,
              NewName.startswith("::") ? NewName.str()
                                       : ("::" + NewName).str());
        } else {
          // This fixes the case where type `T` is a parameter inside a function
          // type (e.g. `std::function<void(T)>`) and the DeclContext of `T`
          // becomes the translation unit. As a workaround, we simply use
          // fully-qualified name here for all references whose `DeclContext` is
          // the translation unit and ignore the possible existence of
          // using-decls (in the global scope) that can shorten the replaced
          // name.
          llvm::StringRef ActualName = Lexer::getSourceText(
              CharSourceRange::getTokenRange(
                  SourceRange(RenameInfo.Begin, RenameInfo.End)),
              SM, TranslationUnitDecl->getASTContext().getLangOpts());
          // Add the leading "::" back if the name written in the code contains
          // it.
          if (ActualName.startswith("::") && !NewName.startswith("::")) {
            ReplacedName = "::" + NewName.str();
          }
        }
      }
      // If the NewName contains leading "::", add it back.
      if (NewName.startswith("::") && NewName.substr(2) == ReplacedName)
        ReplacedName = NewName.str();
    }
    Replace(RenameInfo.Begin, RenameInfo.End, ReplacedName);
  }

  // Hanlde using declarations explicitly as "using a::Foo" don't trigger
  // typeLoc for "a::Foo".
  for (const auto *Using : Finder.getUsingDecls())
    Replace(Using->getBeginLoc(), Using->getEndLoc(), "using " + NewName.str());

  return AtomicChanges;
}

} // end namespace tooling
} // end namespace clang


text:
<ion-header>

  <ion-navbar color="primary">
    <ion-title>{{nombreLista | placeholder: "Nueva lista"}}</ion-title>
  </ion-navbar>

</ion-header>

<ion-content padding>
  <ion-card>
    <ion-card-header>
      <ion-item>
        <ion-label floating>Nombre de la lista</ion-label>
        <ion-input type="text" [(ngModel)]="nombreLista" name="nombreLista"></ion-input>
      </ion-item>
    </ion-card-header>
    <ion-card-content>
      <ion-item>
        <ion-label floating>Item</ion-label>
        <ion-input (keyup.enter)="agregar()" type="text" [(ngModel)]="nombreItem" name="nombreItem"></ion-input>
      </ion-item>
      <button (click)="agregar()" ion-button class="button-block">Agregar</button>
    </ion-card-content>
  </ion-card>
  <ion-card *ngIf="items.length > 0">
    <ion-card-header>

Items agregados

    </ion-card-header>
    <ion-card-content>
      <ion-list>
        <ion-item *ngFor="let item of items; let i = index">
          <button ion-button color="dark" clear>
            {{item.nombre}}
          </button>
          <button (click)="borrarItem(i)" ion-button outline item-right color="danger">
            <ion-icon ios="ios-trash" md="md-trash"></ion-icon>
            Borrar
          </button>
        </ion-item>
      </ion-list>
    </ion-card-content>
  </ion-card>
  <button (click)="guardarLista()" ion-button icon-left class="button-block">
    <ion-icon ios="ios-add-circle" md="md-add-circle"></ion-icon>
    Agregar
  </button>
</ion-content>

redpajama_set_name: RedPajamaGithub


text:
package com.udacity.gamedev.inputtestbed;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.viewport.Viewport;

import java.util.Random;

public class BouncingBall extends InputAdapter {

    private static final Color COLOR = Color.RED;
    private static final float DRAG = 1.0f;
    private static final float RADIUS_FACTOR = 1.0f / 20;
    private static final float RADIUS_GROWTH_RATE = 1.5f;
    private static final float MIN_RADIUS_MULTIPLIER = 0.1f;
    private static final float ACCELERATION = 500.0f;
    private static final float MAX_SPEED = 400.0f;
    private static final float FOLLOW_MULTIPLIER = 2.0f;

    private static final float KICK_VELOCITY = 500.0f;

    Vector2 flickStart;
    boolean flicking = false;

    // Declare a Vector2 to hold the ball's target position
    Vector2 target;

    // Declare a boolean to hold whether the ball is following something (and set it to false)
    boolean isFollowing = false;

    float baseRadius;
    float radiusMultiplier;

    Vector2 position;
    Vector2 velocity;

    Viewport viewport;

    public BouncingBall(Viewport viewport) {
        this.viewport = viewport;
        init();
    }

    public void init() {

        position = new Vector2(viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2);
        velocity = new Vector2();
        baseRadius = RADIUS_FACTOR * Math.min(viewport.getWorldWidth(), viewport.getWorldHeight());
        radiusMultiplier = 1;
    }

    private void randomKick() {
        Random random = new Random();
        float angle = MathUtils.PI2 * random.nextFloat();
        velocity.x += KICK_VELOCITY * MathUtils.cos(angle);
        velocity.y += KICK_VELOCITY * MathUtils.sin(angle);
    }

    public void update(float delta) {

        // Growing and shrinking
        if (Gdx.input.isKeyPressed(Keys.Z)) {
            radiusMultiplier += delta * RADIUS_GROWTH_RATE;
        }
        if (Gdx.input.isKeyPressed(Keys.X)) {
            radiusMultiplier -= delta * RADIUS_GROWTH_RATE;
            radiusMultiplier = Math.max(radiusMultiplier, MIN_RADIUS_MULTIPLIER);
        }

        // If we're following something, calculate the difference vector between the targetPosition and the ball's position
        // Set the velocity to that vector times the FOLLOW_MULTIPLIER
        if (isFollowing) {
            Vector2 dragDirection = new Vector2 (target.x - position.x, target.y - position.y);
            velocity = dragDirection.scl(FOLLOW_MULTIPLIER);
        }

        // Movement
        if (Gdx.input.isKeyPressed(Keys.LEFT)) {
            velocity.x -= delta * ACCELERATION;

        }
        if (Gdx.input.isKeyPressed(Keys.RIGHT)) {
            velocity.x += delta * ACCELERATION;

        }
        if (Gdx.input.isKeyPressed(Keys.UP)) {
            velocity.y += delta * ACCELERATION;

        }
        if (Gdx.input.isKeyPressed(Keys.DOWN)) {
            velocity.y -= delta * ACCELERATION;
        }

        velocity.clamp(0, MAX_SPEED);

        velocity.x -= delta * DRAG * velocity.x;
        velocity.y -= delta * DRAG * velocity.y;

        position.x += delta * velocity.x;
        position.y += delta * velocity.y;

        collideWithWalls(baseRadius * radiusMultiplier, viewport.getWorldWidth(), viewport.getWorldHeight());
    }

    private void collideWithWalls(float radius, float viewportWidth, float viewportHeight) {
        if (position.x - radius < 0) {
            position.x = radius;
            velocity.x = -velocity.x;
        }
        if (position.x + radius > viewportWidth) {
            position.x = viewportWidth - radius;
            velocity.x = -velocity.x;
        }
        if (position.y - radius < 0) {
            position.y = radius;
            velocity.y = -velocity.y;
        }
        if (position.y + radius > viewportHeight) {
            position.y = viewportHeight - radius;
            velocity.y = -velocity.y;
        }
    }

    public void render(ShapeRenderer renderer) {
        renderer.set(ShapeType.Filled);
        renderer.setColor(COLOR);
        renderer.circle(position.x, position.y, baseRadius * radiusMultiplier);
    }

    @Override
    public boolean keyDown(int keycode) {

        if (keycode == Keys.SPACE) {
            randomKick();
        }
        if (keycode == Keys.R) {
            init();
        }

        return true;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {

        Vector2 worldClick = viewport.unproject(new Vector2(screenX, screenY));

        if (worldClick.dst(position) < baseRadius * radiusMultiplier) {
            Gdx.app.log("Ball", "Click in the ball, starting flick.");
            flicking = true;
            flickStart = worldClick;
        } else {
            // Set the target position
            target = new Vector2(worldClick);

            // Set the following flag
            isFollowing = true;

        }

        return true;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        // If we're following, then update the target position (remember to unproject the touch location)
        if (isFollowing) {
            target = new Vector2(viewport.unproject(new Vector2(screenX, screenY)));
        }

        return true;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        if (flicking) {
            flicking = false;
            Vector2 flickEnd = viewport.unproject(new Vector2(screenX, screenY));

            velocity.x += 3 * (flickEnd.x - flickStart.x);
            velocity.y += 3 * (flickEnd.y - flickStart.y);
            Gdx.app.log("Ball", "End flick");
        }

        // Reset the following flag
        if (isFollowing) isFollowing = false;

        return true;
    }
}


text:
layout: page
title: Kim - Ibarra Wedding
date: 2016-05-24
author: Richard Glover
tags: weekly links, java
status: published
summary: Integer rutrum arcu eu justo pretium.
banner: images/banner/people.jpg
booking:
  startDate: 07/01/2018
  endDate: 07/03/2018
  ctyhocn: GRBHXHX
  groupCode: KIW
published: true
---
Integer cursus rhoncus finibus. Praesent bibendum eget mi id rutrum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque posuere at eros et efficitur. Etiam nec dictum lacus. Sed id placerat sapien, quis tempor dui. Vestibulum porttitor et dui non luctus. Sed ornare nulla et tincidunt elementum. Nullam vel mauris luctus, finibus mauris vel, interdum felis. Suspendisse tempor dapibus lacus, in ornare mi iaculis ut.

* Nulla finibus lacus eget placerat bibendum
* Mauris vitae est ut orci vestibulum rhoncus sit amet sit amet dolor
* Duis ac neque a ante mattis eleifend
* Nullam sit amet augue a lacus tempor sagittis at suscipit nunc
* Mauris ac sem quis nulla hendrerit volutpat sit amet ultricies mi.

In hac habitasse platea dictumst. Nulla fringilla tortor sed pellentesque auctor. Vestibulum ullamcorper porttitor sapien, sit amet tincidunt risus sagittis varius. Vestibulum dapibus fringilla neque. Nam scelerisque pharetra massa, sit amet iaculis justo malesuada sed. Aenean iaculis urna id nulla placerat, at sagittis tortor sagittis. Aenean at odio malesuada lorem luctus iaculis at id libero. Quisque at mi lacus. Ut euismod urna eget justo bibendum imperdiet. Praesent ultricies auctor placerat. Vestibulum ullamcorper, tortor et aliquam cursus, est urna mattis sem, sed dictum felis orci in lacus. Morbi ac augue in velit vehicula suscipit. Phasellus ultrices lacus ut eleifend cursus.


text:
package com.renren.mobile.chat.base.views;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.Button;

/**
 * @author dingwei.chen
 * @说明 可移动button
 * */
public class MoveButton extends Button{

	static AnimationSet sLeftDissmissAnim = null;
	static AnimationSet sRightDissmissAnim = null;
	static AnimationSet sLeftShowAnim = null;
	static AnimationSet sRightShowAnim = null;
	static{
		sLeftDissmissAnim = new AnimationSet(false);
		Animation left_tran = new TranslateAnimation(0f, -50f, 0, 0);
		sLeftDissmissAnim.addAnimation(left_tran);
		Animation alpha_to_dissmiss = new AlphaAnimation(1f,0);
		Animation alpha_to_show = new AlphaAnimation(0f,1);
		sLeftDissmissAnim.addAnimation(alpha_to_dissmiss);
		sLeftDissmissAnim.setDuration(200);

		sLeftShowAnim = new AnimationSet(false);
		left_tran = new TranslateAnimation(50f, 0f, 0, 0);
		sLeftShowAnim.addAnimation(left_tran);
		sLeftShowAnim.addAnimation(alpha_to_show);
		sLeftShowAnim.setDuration(200);

		sRightShowAnim = new AnimationSet(false);
		Animation right_tran = new TranslateAnimation(-50f, 0f, 0, 0);
		sRightShowAnim.addAnimation(right_tran);
		sRightShowAnim.addAnimation(alpha_to_show);
		sRightShowAnim.setDuration(200);

		sRightDissmissAnim = new AnimationSet(false);
		right_tran = new TranslateAnimation(0f, 50f, 0, 0);
		sRightDissmissAnim.addAnimation(right_tran);
		sRightDissmissAnim.addAnimation(alpha_to_dissmiss);
	}

	public MoveButton(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public enum DIRECTION{
		LEFT,
		RIGHT
	}

	/**
	 * @param dir 代表的是控件移动朝向
	 * */
	public void moveToDissmiss(DIRECTION dir){
		switch(dir){
		case LEFT:
			this.startAnimation(sLeftDissmissAnim);
			;break;
		case RIGHT:
			this.startAnimation(sRightDissmissAnim);
			;break;
		}
		this.setVisibility(View.GONE);
	}
	/**
	 * @param dir 代表的是控件移动朝向
	 * */
	public void moveToShow(DIRECTION dir){
		switch(dir){
		case LEFT:
			this.startAnimation(sLeftShowAnim);
			;break;
		case RIGHT:
			this.startAnimation(sRightShowAnim);
			;break;
		}
		this.setVisibility(View.VISIBLE);
	}

}


text:
<?php

namespace projectAdmin\UploadBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('projectAdminUploadBundle:Default:index.html.twig', array('name' => $name));
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>
Primitives
</title>

Primitives

This example shows how to use the primitives utility library to make various
shapes.


text:
import sys
from typing import TYPE_CHECKING

if sys.version_info < (3, 7) or TYPE_CHECKING:
    from ._width import WidthValidator
    from ._visible import VisibleValidator
    from ._line import LineValidator
    from ._fillcolor import FillcolorValidator
else:
    from _plotly_utils.importers import relative_import

    __all__, __getattr__, __dir__ = relative_import(
        __name__,
        [],
        [
            "._width.WidthValidator",
            "._visible.VisibleValidator",
            "._line.LineValidator",
            "._fillcolor.FillcolorValidator",
        ],
    )


text:
var mediaPlugins = "";

if (mediaPickerEnabled) {
    mediaPlugins += " mediapicker";
}

if (mediaLibraryEnabled) {
    mediaPlugins += " medialibrary";
}

tinyMCE.init({
    selector: "textarea.tinymce",
    theme: "modern",
    schema: "html5",
    plugins: [
        "advlist, anchor, autolink, autoresize, charmap, code, colorpicker, contextmenu, directionality, emoticons, fullscreen, hr, image, insertdatetime, link, lists, media, nonbreaking, pagebreak, paste, preview, print, searchreplace, table, template, textcolor, textpattern, visualblocks, visualchars, wordcount" + mediaPlugins
    ],
    toolbar: "undo redo cut copy paste | bold italic | bullist numlist outdent indent formatselect | alignleft aligncenter alignright alignjustify ltr rtl | " + mediaPlugins + " link unlink charmap | code fullscreen",
    convert_urls: false,
    valid_elements: "*[*]",
    // Shouldn't be needed due to the valid_elements setting, but TinyMCE would strip script.src without it.
    extended_valid_elements: "script[type|defer|src|language]",
    //menubar: false,
    //statusbar: false,
    skin: "orchardlightgray",
    language: language,
    auto_focus: autofocus,
    directionality: directionality,
    setup: function (editor) {
        $(document).bind("localization.ui.directionalitychanged", function(event, directionality) {
            editor.getBody().dir = directionality;
        });

        // If the focused editable area is taller than the window, make the menu and the toolbox sticky-positioned within the editor
        // to help the user avoid excessive vertical scrolling.
        // There is a built-in fixed_toolbar_container option in the TinyMCE, but we can't use it, because it is only
        // available if the selector is a DIV with inline mode.

        editor.on("focus", function () {
            var $contentArea = $(this.contentAreaContainer.parentElement);
            stickyToolbar($contentArea);
        });

        editor.on("blur", function () {
            var $contentArea = $(this.contentAreaContainer.parentElement);
            $contentArea.prepend($contentArea.find("div.mce-toolbar-grp"));
            $contentArea.prepend($contentArea.find("div.mce-menubar"));
            $("#stickyContainer").remove();
            $("#stickyPlaceholder").remove();
        });

        function stickyToolbar($contentArea) {
            var $container = $("<div/>", { id: "stickyContainer", class: "container-layout" });

            $contentArea.prepend($container);
            $container.append($contentArea.find("div.mce-menubar"));
            $container.append($contentArea.find("div.mce-toolbar-grp"));

            var $containerPosition = $container.offset();
            var $placeholder = $("<div/>", { id: "stickyPlaceholder" });
            var isAdded = false;

            if ($(window).scrollTop() >= $containerPosition.top && !isAdded) {
                $container.addClass("sticky-top");
                $placeholder.insertBefore($container);
                $container.width($placeholder.width());
                $placeholder.height($container.height());
            }

            $(window).scroll(function (event) {
                var $statusbarPosition = $contentArea.find("div.mce-statusbar").offset();
                if ($(window).scrollTop() >= $containerPosition.top && !isAdded) {
                    $container.addClass("sticky-top");
                    $placeholder.insertBefore($container);
                    $container.width($placeholder.width());
                    $placeholder.height($container.height());
                    $(window).on("resize", function () {
                        $container.width($placeholder.width());
                        $placeholder.height($container.height());
                    });
                    isAdded = true;
                } else if ($(window).scrollTop() < $containerPosition.top && isAdded) {
                    $container.removeClass("sticky-top");
                    $placeholder.remove();
                    $(window).on("resize", function () {
                        $container.width("100%");
                    });
                    isAdded = false;
                }
                if ($(window).scrollTop() >= ($statusbarPosition.top - $container.height())) {
                    $container.hide();
                } else if ($(window).scrollTop() < ($statusbarPosition.top - $container.height()) && isAdded) {
                    $container.show();
                }
            });
        }
    }
});


text:
extern panic_dump_hex
global stack_dump

stack_dump:
	push ebp
	mov ebp, esp
	call panic_dump_hex
	pop ebp
	ret


text:
using System.IO;
using SanAndreasUnity.Importing.Collision;

namespace SanAndreasUnity.Importing.RenderWareStream
{
    [SectionType(0x0253F2FA)]
    public class CollisionModel : SectionData
    {
        public readonly CollisionFile Collision;

        public CollisionModel(SectionHeader header, Stream stream)
            : base(header, stream)
        {
            Collision = CollisionFile.Load(stream);
        }
    }
}


text:
export NODE_ENV=production
export PATH="$PWD"/env/sonar-runner-2.2.2/bin:$PATH
#start sonar server, will be listen on port 9000
if [ "$(uname -s)" == "Darwin" ];then #this is mac
sh env/sonar-3.6.1/bin/macosx-universal-64/sonar.sh start
else
sh env/sonar-3.6.1/bin/linux-x86-64/sonar.sh start
fi

forever ./app.js


text:
package com._4dconcept.springframework.data.marklogic.core.mapping;

import com._4dconcept.springframework.data.marklogic.core.query.Criteria;
import com._4dconcept.springframework.data.marklogic.repository.Address;
import com._4dconcept.springframework.data.marklogic.repository.Person;
import org.hamcrest.collection.IsCollectionWithSize;
import org.junit.Test;
import org.springframework.data.mapping.PersistentPropertyAccessor;
import org.springframework.data.mapping.PropertyHandler;
import org.springframework.data.util.TypeInformation;

import java.util.ArrayList;
import java.util.List;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * --Description--
 *
 * @author stoussaint
 * @since 2017-07-31
 */
public class MarklogicMappingContextTest {

    @Test
    @SuppressWarnings("unchecked")
    public void name() {
        Person person = new Person();
        person.setId("1");
        person.setLastname("Toussaint");
        person.setAge(38);

        Address address = new Address();
        address.setTown("Plaisir");
        address.setStreet("68 rue René Cassin");
        person.setAddress(address);

        MarklogicMappingContext mappingContext = new MarklogicMappingContext();
        BasicMarklogicPersistentEntity<?> entity = mappingContext.getPersistentEntity(Person.class);

        List<Criteria> criteria = doWith(entity, person);
        assertThat(criteria, IsCollectionWithSize.hasSize(4));
        assertThat(criteria.get(0).getCriteriaObject(), is("1"));
        assertThat(criteria.get(1).getCriteriaObject(), is("Toussaint"));
        assertThat(criteria.get(3).getCriteriaObject(), instanceOf(List.class));
        assertThat(((List<Criteria>)criteria.get(3).getCriteriaObject()).get(0).getCriteriaObject(), is("Plaisir"));
    }

    private List<Criteria> doWith(BasicMarklogicPersistentEntity<?> entity, Object bean) {
        ArrayList<Criteria> criteriaList = new ArrayList<>();
        PersistentPropertyAccessor<Object> propertyAccessor = entity.getPropertyAccessor(bean);

        entity.doWithProperties((PropertyHandler<MarklogicPersistentProperty>) property -> {
            Object value = propertyAccessor.getProperty(property);
            if (value != null) {
                Criteria criteria = new Criteria();
                criteria.setQname(property.getQName());

                if (property.getPersistentEntityTypes() != null) {
                    for (TypeInformation<?> typeInformation : property.getPersistentEntityTypes()) {
                        MarklogicMappingContext mappingContext = new MarklogicMappingContext();
                        BasicMarklogicPersistentEntity<?> subEntity = mappingContext.getPersistentEntity(typeInformation);
                        value = doWith(subEntity, value);
                    }

                    criteria.setCriteriaObject(value);
                }

                criteriaList.add(criteria);
            }
        });

        return criteriaList;
    }

}


text:
/* eslint max-nested-callbacks: [0] */
/* eslint no-console: [0] */

'use strict';

var wd = require('wd');

wd.addPromiseChainMethod('printLogs', function printLogs() {
  return this
    .log('browser')
    .then(function doPrintLogs(logs) {
      logs.forEach(function formatLog(log) {
        try {
          log.message = JSON.parse(log.message);
          var method = console[log.message.message.level] || console.log;
          method.call(console, 'browser log:', log.message.message.text);
        }
        catch (err) {
          console.log('browser log:', log.message);
        }
      });
    })
    .catch(function handleError(reason) {
      console.warn('failed to fetch browser logs', reason);
    });
});


text:
/*
This is a companion Java project for an SPL project (033_java_primitive_operator_at_work)
present in the same Eclipse workspace. This Java class extends from a Streams AbstractOperator
class. It receives an input tuple with rss provider information. Then, it queries that server
for the currently available RSS feeds. It parses the RSS XML data and converts that into
an output tuple and sends it on its output port.

Since the Java class from this Java project forms the basis for the Java primitive operator
of the above-mentioned SPL project, the compiled Java class file from this Java project
should be manually copied to the impl/java/bin directory in the SPL project.
Under that bin directory, you are required create the necessary sub-directories
that accurately reflect the package name of this java class.
Please read more detailed comments documented in the Main.spl file in the SPL project.

IMPORTANT:
This Java class is extended from a Streams AbstractOperator and in addition it uses
a lot of other Streams Java operators such as the Tuple class. In order to resolve those
Streams Java classes and compile it correctly, you have to do the following.

a) Ensure you are in the Eclipse Java perspective.
b) Right click on the RSS_Reader_Primitive Java project and select Properties.
c) In the left pane of the resulting dialog, click on "Java Build Path".
d) In the righ pane, click on the tab titled "Libraries".
e) Click the "Add External Jars" button, add the following Streams jar files from you
   Streams installation directory.

   i)   <Your Streams Install Directory>/lib/com.ibm.streams.operator.jar
   ii)  <Your Streams Install Directory>/lib/com.ibm.streams.operator.samples.jar
   iii) <Your Streams Install Directory>/ext/lib/commons-math-2.1.jar

f) After adding these three dependent jar files, you can delete/remove the three
erroneous jar entries in your "Libraries" tab that point to invalid directories.
*/
package com.ibm.streams.rss.reader;

import com.ibm.streams.operator.AbstractOperator;
import com.ibm.streams.operator.OperatorContext;
import com.ibm.streams.operator.OutputTuple;
import com.ibm.streams.operator.StreamingData;
import com.ibm.streams.operator.StreamingInput;
import com.ibm.streams.operator.StreamingOutput;
import com.ibm.streams.operator.Tuple;

import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class RSSReader extends AbstractOperator{
	public HashMap rssResults;

	@Override
	public synchronized void initialize(OperatorContext context) throws Exception {
		super.initialize(context);
		// Let us use a set to return the rss entries in the output tuple.
		rssResults = new HashMap();
	} // End of the method initialize.

	public void process(StreamingInput<Tuple> inputStream, Tuple tuple) {
		// Input tuple will have the following attributes.
		// 1) String rssProviderName
		// 2) String rssProviderURL
		// 3) int maxRssItemsToBeReturned

		// At first, let us clear all the entries in our HashMap.
		rssResults.clear();
		// Get the RSS entries now using the RSS provider URL.
		// Get only the requested number of RSS items.
		getRSSEntries(tuple.getString("rssProviderURL"), tuple.getInt("maxRssItemsToBeReturned"));

		boolean rssEntriesReturned = true;

		// If we didn't get any RSS results, set the error indicator.
		if (rssResults.size() <= 0) {
			rssEntriesReturned = false;
			// Send this one tuple away since we have no RSS results from this provider.
			StreamingOutput<OutputTuple> output = getOutput(0);
			OutputTuple outputTuple = output.newTuple();
			outputTuple.setString("rssProviderName", tuple.getString("rssProviderName"));
			outputTuple.setString("rssProviderURL", tuple.getString("rssProviderURL"));
			outputTuple.setInt("maxRssItemsToBeReturned", tuple.getInt("maxRssItemsToBeReturned"));
			outputTuple.setBoolean("rssEntriesReturned", rssEntriesReturned);
			outputTuple.setSet("rssResults", new TreeSet());

			try {
				output.submit(outputTuple);
			} catch (Exception ex) {
				ex.printStackTrace();
			} // End of try-catch block.
		} // End of if (rssEntries.size() <= 0)

		// Loop through the hash and send out the RSS results as
		// individual tuples.
		Set set = rssResults.entrySet();
		Iterator iterator = set.iterator();

		while (iterator.hasNext()) {
			Map.Entry entry = (Map.Entry) iterator.next();
			TreeSet resultSet = (TreeSet)entry.getValue();

			// We can now prepare an output tuple and send it out.
			StreamingOutput<OutputTuple> output = getOutput(0);
			OutputTuple outputTuple = output.newTuple();
			outputTuple.setString("rssProviderName", tuple.getString("rssProviderName"));
			outputTuple.setString("rssProviderURL", tuple.getString("rssProviderURL"));
			outputTuple.setInt("maxRssItemsToBeReturned", tuple.getInt("maxRssItemsToBeReturned"));
			outputTuple.setBoolean("rssEntriesReturned", rssEntriesReturned);
			outputTuple.setSet("rssResults", resultSet);

			try {
				output.submit(outputTuple);
			} catch (Exception ex) {
				ex.printStackTrace();
			} // End of try-catch block.
		} // End of while (iterator.hasNext())
	} // End of the method process.

	public void processPunctuation(StreamingInput<Tuple> inputStream, StreamingData.Punctuation marker) {

	} // End of the method processPuntuation

	public void getRSSEntries(String url, int maxRssItemsNeeded) {
		try {

			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			URL u = new URL(url); // your feed url

			Document doc = builder.parse(u.openStream());
			NodeList nodes = doc.getElementsByTagName("item");

			for(int i=0;i<nodes.getLength();i++) {
				TreeSet rssResult = new TreeSet();

				Element element = (Element)nodes.item(i);
				// Collect the RSS result entry to a List.
				rssResult.add("Title: " + getElementValue(element,"title"));
				rssResult.add("Link: " + getElementValue(element,"link"));
				rssResult.add("Publish Date: " + getElementValue(element,"pubDate"));
				rssResult.add("Author: " + getElementValue(element,"dc:creator"));
				rssResult.add("Description: " + getElementValue(element, "description"));
				// Add that set to the results hashmap.
				rssResults.put(i+1, rssResult);

				// If we already collected the maximum RSS entries needed, exit this loop now.
				if (i+1 >= maxRssItemsNeeded) {
					break;
				} // End of if (i+1 >= maxRssItemsNeeded)

			} // End of for(int i=0;i<nodes.getLength();i++)
		} // End of try
		catch(Exception ex) {
			System.out.println ("RSSReader: Error in accessing the URL: " + url);
		} // End of catch.
	} // End of method getRSSEntries (String url, int maxRssItemsNeeded)

	private String getCharacterDataFromElement(Element e) {
		try {
			Node child = e.getFirstChild();
			if(child instanceof CharacterData) {
				CharacterData cd = (CharacterData) child;
				return cd.getData();
			}
		}
		catch(Exception ex) {

		}
		return "";
	} //private String getCharacterDataFromElement

	protected float getFloat(String value) {
		if(value != null && !value.equals("")) {
			return Float.parseFloat(value);
		}
		return 0;
	} // End of getFloat.

	protected String getElementValue(Element parent,String label) {
		return getCharacterDataFromElement((Element)parent.getElementsByTagName(label).item(0));
	} // End of getElementValue.

} // End of class RSSReader.


text:
<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <FrameLayout
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.schinizer.hackernews.features.newsfeed.NewsFeedActivity">

        <com.malinskiy.superrecyclerview.SuperRecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:mainLayoutId="@layout/layout_recyclerview_verticalscroll"
            app:scrollbarStyle="insideInset"/>

    </FrameLayout>

</layout>


text:
#include "tensorflow/compiler/mlir/tfrt/transforms/fallback_converter.h"

#include "tensorflow/compiler/mlir/tensorflow/ir/tf_types.h"
#include "tensorflow/core/runtime_fallback/opdefs/tfrt_fallback.h"
#include "tensorflow/core/runtime_fallback/opdefs/tfrt_fallback_async.h"
#include "tfrt/basic_kernels/opdefs/types.h"  // from @tf_runtime
#include "tfrt/core_runtime/opdefs/types.h"  // from @tf_runtime

namespace tensorflow {
namespace tfrt_compiler {
namespace {
constexpr char kCpuDeviceName[] =
    "/job:localhost/replica:0/task:0/device:CPU:0";
}

FallbackConverter::FallbackConverter(mlir::MLIRContext *context)
    : builder_(context) {
  addConversion([](tfrt::compiler::ChainType type) { return type; });
  addConversion([](tfrt::fallback::TFTensorType type) { return type; });
  addConversion([=](mlir::TensorType type) -> llvm::Optional<mlir::Type> {
    // Ref types are not supported in both compiler and runtime.
    if (type.getElementType().isa<mlir::TF::TensorFlowRefType>()) {
      return llvm::None;
    }

    return builder_.getType<tfrt::fallback::TFTensorType>();
  });
  addConversion([=](mlir::Type type) -> llvm::Optional<mlir::Type> {
    if (type == builder_.getI1Type()) return type;
    return llvm::None;
  });
}

mlir::Value ConvertCoreRTTensorHandleToFallbackTensor(
    mlir::Location loc, llvm::StringRef device, mlir::Value value,
    mlir::ConversionPatternRewriter &rewriter) {
  if (value.getType().isa<tfrt::fallback::TFTensorType>()) return value;

  if (!value.getType().isa<tfrt::corert::TensorHandleType>()) return {};

  mlir::OpBuilder::InsertionGuard guard(rewriter);

  auto *def = value.getDefiningOp();
  if (def) {
    rewriter.setInsertionPointAfter(def);
  } else {
    rewriter.setInsertionPointToStart(value.getParentBlock());
  }

  return rewriter
      .create<tfrt::fallback_async::CoreRTTensorHandleToFallbackTensorOp>(
          loc, rewriter.getType<tfrt::fallback::TFTensorType>(), value, device)
      .getResult(0);
}

mlir::Value ConvertFallbackTensorToCoreRTTensorHandle(
    mlir::Location loc, mlir::Value value,
    mlir::ConversionPatternRewriter &rewriter) {
  if (value.getType().isa<tfrt::corert::TensorHandleType>()) return value;

  if (!value.getType().isa<tfrt::fallback::TFTensorType>()) return {};

  // Use CPU device by default if no device is specified.
  std::string device = kCpuDeviceName;
  if (auto *def = value.getDefiningOp()) {
    if (auto device_attr = def->getAttrOfType<mlir::StringAttr>("device")) {
      device = device_attr.getValue().str();
    }
  }

  return rewriter
      .create<tfrt::fallback_async::FallbackTensorToCoreRTTensorHandleOp>(
          loc, rewriter.getType<tfrt::corert::TensorHandleType>(), value,
          device)
      .getResult(0);
}

mlir::LogicalResult ConvertCoreRTOperands(
    mlir::Operation *op, llvm::ArrayRef<mlir::Value> operands,
    llvm::SmallVectorImpl<mlir::Value> *new_operands,
    mlir::ConversionPatternRewriter &rewriter) {
  mlir::OpBuilder::InsertionGuard guard(rewriter);
  // Insert before the current op.
  rewriter.setInsertionPoint(op);

  for (auto operand : operands) {
    auto value = ConvertFallbackTensorToCoreRTTensorHandle(op->getLoc(),
                                                           operand, rewriter);
    if (!value) {
      return op->emitWarning("failed to convert to !corert.tensorhandle")
             << operand.getType();
    }

    new_operands->push_back(value);
  }
  return success();
}

mlir::LogicalResult ConvertFallbackOperands(
    mlir::Operation *op, llvm::StringRef device,
    llvm::ArrayRef<mlir::Value> operands,
    llvm::SmallVectorImpl<mlir::Value> *new_operands,
    mlir::ConversionPatternRewriter &rewriter) {
  for (auto operand : operands) {
    if (!operand.getType().isa<tfrt::fallback::TFTensorType>()) {
      auto new_operand = ConvertCoreRTTensorHandleToFallbackTensor(
          op->getLoc(), device, operand, rewriter);
      if (!new_operand)
        return op->emitWarning(
            "failed to convert the operand to fallback tensor.");
      new_operands->push_back(new_operand);
    } else {
      new_operands->push_back(operand);
    }
  }
  return success();
}

}  // namespace tfrt_compiler
}  // namespace tensorflow


text:
package org.apache.oozie.executor.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.oozie.BundleJobBean;
import org.apache.oozie.ErrorCode;
import org.apache.oozie.util.ParamChecker;

/**
 * Load the BundleJob into a Bean and return it.
 */
public class BundleJobGetJPAExecutor implements JPAExecutor<BundleJobBean> {

    private String bundleJobId = null;

    public BundleJobGetJPAExecutor(String bundleJobId) {
        ParamChecker.notNull(bundleJobId, "bundleJobId");
        this.bundleJobId = bundleJobId;
    }

    /* (non-Javadoc)
     * @see org.apache.oozie.executor.jpa.JPAExecutor#getName()
     */
    @Override
    public String getName() {
        return "BundleJobGetJPAExecutor";
    }

    /* (non-Javadoc)
     * @see org.apache.oozie.executor.jpa.JPAExecutor#execute(javax.persistence.EntityManager)
     */
    @Override
    @SuppressWarnings("unchecked")
    public BundleJobBean execute(EntityManager em) throws JPAExecutorException {
        List<BundleJobBean> bdBeans;
        try {
            Query q = em.createNamedQuery("GET_BUNDLE_JOB");
            q.setParameter("id", bundleJobId);
            bdBeans = q.getResultList();
        }
        catch (Exception e) {
            throw new JPAExecutorException(ErrorCode.E0603, e);
        }
        BundleJobBean bean = null;
        if (bdBeans != null && bdBeans.size() > 0) {
            bean = bdBeans.get(0);
            bean.setStatus(bean.getStatus());
            return bean;
        }
        else {
            throw new JPAExecutorException(ErrorCode.E0604, bundleJobId);
        }
    }
}


text:
package com.scalyr.api.internal;

import com.scalyr.api.internal.ScalyrService.RpcOptions;
import com.scalyr.api.knobs.Knob;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.GzipCompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.zip.GZIPInputStream;

/**
 * AbstractHttpClient implementation based on the Apache HTTP client library.
 * Has Gzip compression capability.
 */
public class ApacheHttpClient extends AbstractHttpClient {
  private static final Knob.Integer scalyrClientMaxConnections = new Knob.Integer("scalyrClientMaxConnections", 20);
  private static final Knob.Integer scalyrClientMaxConnectionsPreRoute = new Knob.Integer("scalyrClientMaxConnectionsPreRoute", 15);

  /**
   * Connection manager used to issue requests to the Scalyr server.
   */
  private static volatile PoolingHttpClientConnectionManager connectionManager;

  private final CloseableHttpResponse response;
  private final InputStream responseStream;
  private final String responseContentType;
  private final String responseEncoding;

  /**
   * Version of constructor with desired Content-Encoding passed in.
   */
  public ApacheHttpClient(URL url, RpcOptions options,
                          byte[] requestBody, int requestBodyLength,
                          String contentType, String contentEncoding) throws IOException {
    if (connectionManager == null) {
      synchronized (ApacheHttpClient.class) {
        if (connectionManager == null) {
          createConnectionManager();
        }
      }
    }

    HttpClientBuilder clientBuilder = HttpClients.custom()
        .setConnectionManager(connectionManager)
        ;

    CloseableHttpClient httpClient = clientBuilder.build();
    RequestConfig.Builder configBuilder = RequestConfig.custom();
    configBuilder.setRedirectsEnabled(false);
    configBuilder.setConnectionRequestTimeout(options.connectionTimeoutMs);
    configBuilder.setConnectTimeout(options.connectionTimeoutMs);
    configBuilder.setSocketTimeout(options.readTimeoutMs);

    HttpPost request = new HttpPost(url.toString());
    request.setHeader("errorStatus", "always200");
    request.setHeader("X-XSS-Protection", "1; mode=block");

    if (contentEncoding != null && contentEncoding.length() > 0) {
      request.setHeader("Content-Encoding", contentEncoding);
      request.setHeader("Accept-Encoding", contentEncoding + ", identity");
    }

    request.setEntity(getEntity(requestBody, requestBodyLength, contentType, contentEncoding));

    request.setConfig(configBuilder.build());

    response = httpClient.execute(request);

    HttpEntity responseEntity = response.getEntity();
    responseContentType = (responseEntity != null && responseEntity.getContentType() != null) ? responseEntity.getContentType().getValue() : null;
    responseEncoding = (responseEntity != null && responseEntity.getContentEncoding() != null) ? responseEntity.getContentEncoding().getValue() : null;
    responseStream = getResponseStream(responseEntity, responseEncoding);
  }

  /** Returns the entity with the given body, content type, and supporting the given content encoding, mainly in the form of compression */
  private HttpEntity getEntity(byte[] requestBody, int requestBodyLength, String contentType, String contentEncoding) {
    ByteArrayEntity inputEntity = new ByteArrayEntity(requestBody, 0, requestBodyLength);
    inputEntity.setContentType(contentType);
    if (contentEncoding == null)
      return inputEntity;
    switch (contentEncoding) {
      case "gzip":
        return new GzipCompressingEntity(inputEntity);
      case "zstandard":
      case "zstd":
        return new ZstdCompressingEntity(inputEntity);
      default:
        return inputEntity;
    }
  }

  private InputStream getResponseStream(HttpEntity responseEntity, String responseEncoding) throws IOException {
    if (responseEntity != null) {
      if (responseEncoding != null && responseEncoding.contains("gzip")) {
        return new GZIPInputStream(responseEntity.getContent());
      } else {
        return responseEntity.getContent();
      }
    } else {
      return null;
    }
  }

  private static void createConnectionManager() {
    connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(scalyrClientMaxConnections.get());
    connectionManager.setDefaultMaxPerRoute(scalyrClientMaxConnectionsPreRoute.get());
  }

  @Override public OutputStream getOutputStream() {
    throw new RuntimeException("Not implemented for ApacheHttpClient (pass request body to our constructor)");
  }

  @Override public int getResponseCode() {
    return response.getStatusLine().getStatusCode();
  }

  @Override public String getResponseContentType() {
    return responseContentType;
  }

  @Override public String getResponseEncoding() {
    return responseEncoding;
  }

  @Override public InputStream getInputStream() {
    return responseStream;
  }

  @Override public void finishedReadingResponse() throws IOException {
    // We must close the response stream. This tells the HTTP library that this connection can
    // be released back into the pool. We do *not* close the proxyResponse object, as that would
    // close the underlying connection to the backend server, defeating keepalive.
    if (responseStream != null) {
      responseStream.close();
    }
  }

  @Override public void disconnect() {
  }
}


text:
<?php

class Mor_Software_Model extends DataMapper {

    var $table = 'mor_software';

    function __construct($id = NULL){
        parent::__construct($id);
        $ci = &get_instance();
        $ci->load->library('session');
        $this->session = $ci->session;
    }

    function getAll(){
        $bas = new Mor_Software_Model();
        $bas->get();
        $result = array();
        foreach ($bas as $ba)
        {
            $data = $this->getDetails($ba);
            // $data = ('1' => 'farhan');
            array_push($result, $data);
        }
        // print_r($result);
        return $result;
    }

    function getDetails($ba){
        $data = new stdClass();
        $data->id = $ba->id;
        $data->name = $ba->name;
        $data->is_hardware = $ba->is_hardware;
        return $data;
    }
}


text: Filemaker database to compare two EDLs


text:
(function(locals){
    return {
        someAsyncFunc: function(cb){
            async.start();
            process.nextTick(function(){
                cb();
                async.end();
            });
        }
    };
})


text:
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2;

/**
 * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2
 * @xmlType OriginalJobIDType
 * @xmlName OriginalJobID
 * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\OriginalJobID
 */
class OriginalJobID extends OriginalJobIDType
{
} // end class OriginalJobID


text:
@class NSString;

@interface ActionGridItem : NSObject <NSCoding>
{
    NSString *_name;
    NSString *_iconUrl;
    NSString *_productID;
}

@property(retain, nonatomic) NSString *productID; // @synthesize productID=_productID;
@property(retain, nonatomic) NSString *iconUrl; // @synthesize iconUrl=_iconUrl;
@property(retain, nonatomic) NSString *name; // @synthesize name=_name;
- (void).cxx_destruct;
- (id)toXml;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (id)init;

@end


text:
'use strict';

define([

], function () {

  var CrudService = function (BORAYU, CrudDictionary, $q, $http, ngProgress, AuthService, Error) {

    var baseUrl = BORAYU.API_URL + ':' + BORAYU.API_PORT;
    var resource = '/crud/';

    this.initialize = function () {

    };

    this.get = function () {
      var deferred = $q.defer();
      ngProgress.start();
      $http.get(baseUrl + resource, AuthService.getHttpOptions())
        .success(function (data) {
          console.log(CrudDictionary.TITLE + ' loaded', data);
          deferred.resolve(data);
          ngProgress.complete();
        })
        .error(function (error, status) {
          Error.msg(error, status, CrudDictionary.ERROR_GET);
        });
      return deferred.promise;
    };

    this.put = function (obj) {
      var deferred = $q.defer();
      ngProgress.start();
      $http.put(baseUrl + resource + obj.id + "/", obj, AuthService.getHttpOptions())
        .success(function (data) {
          console.log(CrudDictionary.TITLE + ' updated', data);
          deferred.resolve(data);
          ngProgress.complete();
        })
        .error(function (error, status) {
          Error.msg(error, status, CrudDictionary.ERROR_SAVE);
        });

      return deferred.promise;
    };

    this.post = function (obj) {
      var deferred = $q.defer();

      ngProgress.start();
      $http.post(baseUrl + resource, obj, AuthService.getHttpOptions())
        .success(function (data) {
          console.log(CrudDictionary.TITLE + ' saved', data);
          deferred.resolve(data);
          ngProgress.complete();
        })
        .error(function (error) {
          Error.msg(error, status, CrudDictionary.ERROR_SAVE);
        });
      return deferred.promise;
    };

    this.delete = function (obj) {
      var deferred = $q.defer();
      ngProgress.start();
      $http.delete(baseUrl + resource + obj.id + "/", AuthService.getHttpOptions())
        .success(function (data) {
          console.log(CrudDictionary.TITLE + ' deleted', data);
          deferred.resolve(data);
          ngProgress.complete();
        })
        .error(function (error, status) {
          Error.msg(error, status, CrudDictionary.ERROR_DELETE);
        });

      return deferred.promise;
    };

    this.initialize();
  };

  return ['BORAYU', 'CrudDictionary', '$q', '$http', 'ngProgress', 'AuthService', 'Error', CrudService];
});


text:
import { text } from '@storybook/addon-knobs';
import { forModule } from 'storybook-addon-angularjs';

import Tabs from '@ovh-ux/ui-kit.tabs';

import readme from '@ovh-ux/ui-kit.tabs/README.md';
import { compileTemplate } from '../../../src/utils';

const moduleName = 'tabs-webcomponent.stories';
angular.module(moduleName, [Tabs]);

export default {
  title: 'Design System/Components/Tabs/WebComponent',

  parameters: {
    notes: readme,
    options: {
      showPanel: true,
    },
  },
};

export const Simple = forModule(moduleName).createElement(
  () => compileTemplate(
    `
    <oui-tabs>
      <oui-tabs-item heading="Lorem ipsum">

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet congue urna. Praesent ultricies id ex convallis dictum. Pellentesque malesuada faucibus consectetur. Quisque vehicula tincidunt leo, quis auctor nisi luctus quis. Etiam purus lectus, placerat vitae vehicula at, molestie nec erat. Duis enim odio, maximus at laoreet in, finibus nec mi. Nam ultrices, lacus vitae egestas volutpat, libero odio gravida turpis, vitae dapibus ex mi nec quam. Pellentesque a tempor nibh.

      </oui-tabs-item>
      <oui-tabs-item heading="Dolor sit amet">

Proin egestas fermentum lectus nec euismod. Vivamus eu congue dui. Pellentesque sit amet pellentesque quam. Morbi posuere sem nec rutrum placerat. Vestibulum porttitor arcu eu risus tempor consectetur. Fusce aliquam bibendum aliquet. Morbi semper egestas iaculis. Ut sit amet sem et neque porta cursus pellentesque nec augue. Nullam semper in metus et luctus. Nunc molestie non ipsum a consequat. Etiam pellentesque laoreet lectus ut luctus. Nulla maximus, leo a mattis gravida, ligula felis vulputate libero, vitae fringilla nibh mauris nec dui. Fusce sed massa at arcu euismod dictum id sit amet lorem. Aliquam sed viverra sem, quis vehicula ligula. Vivamus blandit varius condimentum.

      </oui-tabs-item>
      <oui-tabs-item heading="Consectetur adipiscing elit">

Duis egestas nulla at euismod semper. Nullam bibendum auctor viverra. Sed posuere neque nulla, id cursus nisi molestie vel. Nulla ornare elit sit amet congue faucibus. Aliquam eget lorem id justo ornare pretium in sit amet lectus. Sed maximus odio id porttitor rhoncus. Quisque pulvinar mauris ut sapien dictum, ultrices fermentum orci efficitur. Cras nec auctor ante. Aliquam ornare eleifend neque, at condimentum lacus aliquet elementum. Mauris mattis porttitor tortor vel vehicula. Phasellus venenatis nibh nec viverra sollicitudin. Ut lobortis mattis mauris, vel euismod nibh faucibus a.

      </oui-tabs-item>
    </oui-tabs>`,
    {
      $ctrl: {
        activeTab: text('Active tab', 'basic1'),
      },
    },
  ),
);

export const WithSubheadings = forModule(moduleName).createElement(
  () => compileTemplate(
    `
    <oui-tabs>
      <oui-tabs-item heading="Lorem ipsum">

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet congue urna. Praesent ultricies id ex convallis dictum. Pellentesque malesuada faucibus consectetur. Quisque vehicula tincidunt leo, quis auctor nisi luctus quis. Etiam purus lectus, placerat vitae vehicula at, molestie nec erat. Duis enim odio, maximus at laoreet in, finibus nec mi. Nam ultrices, lacus vitae egestas volutpat, libero odio gravida turpis, vitae dapibus ex mi nec quam. Pellentesque a tempor nibh.

      </oui-tabs-item>
      <oui-tabs-item heading="Dolor sit amet" subheading="Proin egestas">

Proin egestas fermentum lectus nec euismod. Vivamus eu congue dui. Pellentesque sit amet pellentesque quam. Morbi posuere sem nec rutrum placerat. Vestibulum porttitor arcu eu risus tempor consectetur. Fusce aliquam bibendum aliquet. Morbi semper egestas iaculis. Ut sit amet sem et neque porta cursus pellentesque nec augue. Nullam semper in metus et luctus. Nunc molestie non ipsum a consequat. Etiam pellentesque laoreet lectus ut luctus. Nulla maximus, leo a mattis gravida, ligula felis vulputate libero, vitae fringilla nibh mauris nec dui. Fusce sed massa at arcu euismod dictum id sit amet lorem. Aliquam sed viverra sem, quis vehicula ligula. Vivamus blandit varius condimentum.

      </oui-tabs-item>
      <oui-tabs-item heading="Consectetur adipiscing elit" subheading="Promotion" variant="promotion">

Duis egestas nulla at euismod semper. Nullam bibendum auctor viverra. Sed posuere neque nulla, id cursus nisi molestie vel. Nulla ornare elit sit amet congue faucibus. Aliquam eget lorem id justo ornare pretium in sit amet lectus. Sed maximus odio id porttitor rhoncus. Quisque pulvinar mauris ut sapien dictum, ultrices fermentum orci efficitur. Cras nec auctor ante. Aliquam ornare eleifend neque, at condimentum lacus aliquet elementum. Mauris mattis porttitor tortor vel vehicula. Phasellus venenatis nibh nec viverra sollicitudin. Ut lobortis mattis mauris, vel euismod nibh faucibus a.

      </oui-tabs-item>
    </oui-tabs>`,
    {
      $ctrl: {
        activeTab: text('Active tab', 'basic1'),
      },
    },
  ),
);

WithSubheadings.story = {
  name: 'With subheadings',
};


text:
<?php
namespace PHProfiler\Exporter\FileExporter;

use PHProfiler\Point\AbstractPoint;

class LogExporter extends StringFileExporter {
    protected function getDefaultExtension(): string {
        return 'log';
    }

    protected function exportPoint(AbstractPoint $point) {
        fprintf($this->filePointer, $this->preparePoint($point));
    }

    protected function preparePoint(AbstractPoint $point): string {
        return sprintf("%s\n", $point);
    }
}


text:
<?php
/**
 * @filenames: GatotKaca/Erp/UtilitiesBundle/Model/UserModel.php
 * Author     : Muhammad Surya Ikhsanudin
 * License    : Protected
 * Email      : mutofiyah@gmail.com
 *
 * Dilarang merubah, mengganti dan mendistribusikan
 * ulang tanpa sepengetahuan Author
 **/

namespace GatotKaca\Erp\UtilitiesBundle\Model;

use Doctrine\DBAL\LockMode;
use GatotKaca\Erp\MainBundle\Model\BaseModel;

class UserModel extends BaseModel
{
    /**
     * Constructor
     *
     * @param EntityManager $entityManager
     * @param Helper        $helper
     **/
    public function __construct(\Doctrine\ORM\EntityManager $entityManager, \GatotKaca\Core\Helper\Helper $helper)
    {
        parent::__construct($entityManager, $helper);
    }

    /**
     * Untuk mendapatkan list user berdasarkan limit
     *
     * @param  integer $start
     * @param  integer $limit
     * @return array   result
     **/
    public function getList($keyword, $start, $limit)
    {
        $extra  = '';
        if ($this->getStatus() === 'true') {
            $extra  = "AND u.status = true";
        } elseif ($this->getStatus() === 'false') {
            $extra  = "AND u.status = false";
        }
        $start  = ($keyword == '') ? $start : 0;
        $query  = $this->getEntityManager()
            ->createQueryBuilder()
            ->select(
                'u.id AS user_id,
                u.name AS user_name,
                g.id AS group_id,
                g.name AS group_name,
                g.relation AS table,
                u.status AS user_status,
                u.online AS user_online'
            )
            ->from('GatotKacaErpUtilitiesBundle:User', 'u')
            ->leftJoin('GatotKacaErpUtilitiesBundle:UserGroup', 'g', 'WITH', 'g.id = u.group')
            ->where("u.name LIKE :name {$extra}")
            ->orderBy('g.name', 'ASC')
            ->setParameter('name', "%{$keyword}%")
            ->setFirstResult($start)
            ->setMaxResults($limit)
            ->getQuery();
        $this->setModelLog("get user from {$start} to {$limit}");

        return $query->getResult();
    }

    /**
     * Untuk mendapatkan total user
     *
     * @return integer total
     **/
    public function countTotal($keyword, $limit)
    {
        $extra  = '';
        if ($this->getStatus() === 'true') {
            $extra  = "AND u.status = true";
        } elseif ($this->getStatus() === 'false') {
            $extra  = "AND u.status = false";
        }
        $qb = $this->getEntityManager()->createQueryBuilder();
        $qb->select('u.id AS user_id');
        $qb->from('GatotKacaErpUtilitiesBundle:User', 'u');
        $qb->where("u.name LIKE :name {$extra}");
        $qb->setParameter('name', "%{$keyword}%");
        if ($keyword != '') {
            $qb->setFirstResult(0);
            $qb->setMaxResults($limit);
        };
        $query  = $qb->getQuery();

        return count($query->getResult());
    }

    /**
     * Untuk mendapatkan user berdasarkan id
     *
     * @param  string $id
     * @param  string $table
     * @return array  $result
     **/
    public function getById($id, $table)
    {
        $query  = $this->getEntityManager()
            ->createQueryBuilder()
            ->select(
                'u.id AS user_id,
                u.name AS user_name,
                g.id AS group_id,
                g.name AS group_name,
                t.first_name AS fname,
                t.last_name AS lname,
                u.status AS user_status,
                u.online AS user_online'
            )
            ->from('GatotKacaErpUtilitiesBundle:User', 'u')
            ->join('GatotKacaErpUtilitiesBundle:UserGroup', 'g', 'WITH', 'g.id = u.group')
            ->join($table, 't', 'WITH', 't.username = u.id')
            ->where('u.id = :id')
            ->setParameter('id', $id)
            ->getQuery();
        $this->setModelLog("get user by id {$id}");

        return $query->getResult();
    }

    /**
     * Update User
     *
     * @param  mixed $input
     * @return mixed $result
     **/
    public function save($input)
    {
        $this->setAction("modify");
        $user   = $this->getEntityManager()->getRepository('GatotKacaErpUtilitiesBundle:User')->find($input->user_id);
        if ($input->npassword != '') {
            $salt   = $this->getHelper()->getSalt($user->getName());
            $user->setSalt($salt);
            $user->setPass($this->getHelper()->hashPassword($input->npassword, $salt));
        }
        $user->setStatus(isset($input->user_status));
        $user->setOnline(isset($input->user_online));
        $user->setGroup($this->getEntityManager()->getReference('GatotKacaErpUtilitiesBundle:UserGroup', $input->group_name));
        //Simpan User
        $this->getEntityManager()->getConnection()->beginTransaction();
        $this->setEntityLog($user);
        try {
            $this->getEntityManager()->persist($user);
            $this->getEntityManager()->flush();
            $this->getEntityManager()->lock($user, LockMode::PESSIMISTIC_READ);
            $this->getEntityManager()->getConnection()->commit();
            $this->setModelLog("saving user with id {$user->getId()}");

            return $user->getId();
        } catch (\Exception $e) {
            $this->getEntityManager()->getConnection()->rollback();
            $this->getEntityManager()->close();
            $this->setMessage("Error while saving user");
            $this->setModelLog($this->getMessage());

            return false;
        }
    }

    /**
     * Update User
     *
     * @param  mixed $input
     * @return mixed $result
     **/
    public function updatePassword($input, $security)
    {
        $this->setAction("modify");
        $user   = $this->getEntityManager()->getRepository('GatotKacaErpUtilitiesBundle:User')->find($this->getHelper()->getSession()->get('user_id'));
        $salt   = $security->checkSalt($user->getName());
        if ($user->getPass() === $this->getHelper()->hashPassword($input->old_password, $salt)) {
            $salt   = $this->getHelper()->getSalt($user->getName());
            $user->setSalt($salt);
            $user->setPass($this->getHelper()->hashPassword($input->new_password, $salt));
            $this->setEntityLog($user);
            //Simpan User
            $this->getEntityManager()->getConnection()->beginTransaction();
            $this->setEntityLog($user);
            try {
                $this->getEntityManager()->persist($user);
                $this->getEntityManager()->flush();
                $this->getEntityManager()->lock($user, LockMode::PESSIMISTIC_READ);
                $this->getEntityManager()->getConnection()->commit();
                $this->setModelLog("change password for {$user->getName()}");

                return $user->getId();
            } catch (\Exception $e) {
                $this->getEntityManager()->getConnection()->rollback();
                $this->getEntityManager()->close();
                $this->setMessage("Error while saving user");
                $this->setModelLog($this->getMessage());

                return false;
            }
        }

        return false;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
  ~
  ~ 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.
  -->

<hazelcast xmlns="http://www.hazelcast.com/schema/config"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.hazelcast.com/schema/config
           http://www.hazelcast.com/schema/config/hazelcast-config-3.11.xsd">

    <group>
        <name>F4D03AC8-B5F7-4542-9BAD-0A94BA48E95D</name>
        <password>6E282022-3BAD-4F5F-8122-CCBE85BD057E</password>
    </group>
    <network>
        <join>
            <multicast enabled="false"/>
            <tcp-ip enabled="true">
                <member>127.0.0.1</member>
            </tcp-ip>
        </join>
    </network>

    <cache name="invalid-cache">
        <in-memory-format>NATIVE</in-memory-format>
        <eviction size="99" max-size-policy="ENTRY_COUNT" eviction-policy="LFU"/>
    </cache>

</hazelcast>


text:
import pytest
from .deque import Deque
from .binary_heap import BinaryHeap
from .priority_queue import PriorityQueue
from .graph import Graph

@pytest.fixture
def emptydeque():
    return Deque()

@pytest.fixture
def emptyheap():
    return BinaryHeap()

@pytest.fixture
def emptypqueue():
    return PriorityQueue()

@pytest.fixture
def empty_graph():
    return Graph()

@pytest.fixture
def sample_graph():
    g = Graph()
    # c < - a - > b
    #       ^     |
    #       |     |
    #       d < - /
    g.add_edge('a', 'b', 0)
    g.add_edge('a', 'c', 0)
    g.add_edge('b', 'd', 0)
    g.add_edge('d', 'a', 0)
    return g


text:
package cloudwatch

import (
	"context"
	awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
	"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
	"github.com/aws/smithy-go/middleware"
	smithyhttp "github.com/aws/smithy-go/transport/http"
)

// Stops the streaming of metrics for one or more of your metric streams.
func (c *Client) StopMetricStreams(ctx context.Context, params *StopMetricStreamsInput, optFns ...func(*Options)) (*StopMetricStreamsOutput, error) {
	if params == nil {
		params = &StopMetricStreamsInput{}
	}

	result, metadata, err := c.invokeOperation(ctx, "StopMetricStreams", params, optFns, c.addOperationStopMetricStreamsMiddlewares)
	if err != nil {
		return nil, err
	}

	out := result.(*StopMetricStreamsOutput)
	out.ResultMetadata = metadata
	return out, nil
}

type StopMetricStreamsInput struct {

	// The array of the names of metric streams to stop streaming. This is an "all or
	// nothing" operation. If you do not have permission to access all of the metric
	// streams that you list here, then none of the streams that you list in the
	// operation will stop streaming.
	//
	// This member is required.
	Names []string

	noSmithyDocumentSerde
}

type StopMetricStreamsOutput struct {
	// Metadata pertaining to the operation's result.
	ResultMetadata middleware.Metadata

	noSmithyDocumentSerde
}

func (c *Client) addOperationStopMetricStreamsMiddlewares(stack *middleware.Stack, options Options) (err error) {
	err = stack.Serialize.Add(&awsAwsquery_serializeOpStopMetricStreams{}, middleware.After)
	if err != nil {
		return err
	}
	err = stack.Deserialize.Add(&awsAwsquery_deserializeOpStopMetricStreams{}, middleware.After)
	if err != nil {
		return err
	}
	if err = addSetLoggerMiddleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
		return err
	}
	if err = addResolveEndpointMiddleware(stack, options); err != nil {
		return err
	}
	if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
		return err
	}
	if err = addRetryMiddlewares(stack, options); err != nil {
		return err
	}
	if err = addHTTPSignerV4Middleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
		return err
	}
	if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
		return err
	}
	if err = addClientUserAgent(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = addOpStopMetricStreamsValidationMiddleware(stack); err != nil {
		return err
	}
	if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStopMetricStreams(options.Region), middleware.Before); err != nil {
		return err
	}
	if err = addRequestIDRetrieverMiddleware(stack); err != nil {
		return err
	}
	if err = addResponseErrorMiddleware(stack); err != nil {
		return err
	}
	if err = addRequestResponseLogging(stack, options); err != nil {
		return err
	}
	return nil
}

func newServiceMetadataMiddleware_opStopMetricStreams(region string) *awsmiddleware.RegisterServiceMetadata {
	return &awsmiddleware.RegisterServiceMetadata{
		Region:        region,
		ServiceID:     ServiceID,
		SigningName:   "monitoring",
		OperationName: "StopMetricStreams",
	}
}


text:
<?php

namespace RM\ProductoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * InstanciaCriterioDesempate
 *
 * @ORM\Table(name="instancia_criterios_desempate")
 * @ORM\Entity
 */
class InstanciaCriterioDesempate
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id_instanc_crit", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var integer
     * @ORM\ManyToOne(targetEntity="RM\ProductoBundle\Entity\CriterioDesempate")
     * @ORM\JoinColumn(name="id_crit_desempate", referencedColumnName="id_crit_desempate", nullable=false)
     */
    private $criterioDesempate;

    /**
     * @var string
     *
     * @ORM\ManyToOne(targetEntity="RM\PlantillaBundle\Entity\GrupoSlots")
     * @ORM\JoinColumn(name="id_grupo", referencedColumnName="id_grupo", nullable=false)
     */
    private $grupo;

    /**
     * @var integer
     *
     * @ORM\ManyToOne(targetEntity="RM\ComunicacionBundle\Entity\InstanciaComunicacion")
     * @ORM\JoinColumn(name="id_instancia", referencedColumnName="id_instancia", nullable=false)
     */
    private $idInstancia;

    /**
     * @var integer
     *
     * @ORM\Column(name="num_slot", type="integer")
     */
    private $numSlot;

    /**
     * @var integer
     *
     * @ORM\Column(name="peso", type="integer")
     */
    private $peso;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set numSlot
     *
     * @param integer $numSlot
     * @return InstanciaCriterioDesempate
     */
    public function setNumSlot($numSlot)
    {
        $this->numSlot = $numSlot;

        return $this;
    }

    /**
     * Get numSlot
     *
     * @return integer
     */
    public function getNumSlot()
    {
        return $this->numSlot;
    }

    /**
     * Set peso
     *
     * @param integer $peso
     * @return InstanciaCriterioDesempate
     */
    public function setPeso($peso)
    {
        $this->peso = $peso;

        return $this;
    }

    /**
     * Get peso
     *
     * @return integer
     */
    public function getPeso()
    {
        return $this->peso;
    }

    /**
     * Set grupo
     *
     * @param \RM\PlantillaBundle\Entity\GrupoSlots $grupo
     * @return InstanciaCriterioDesempate
     */
    public function setGrupo(\RM\PlantillaBundle\Entity\GrupoSlots $grupo = null)
    {
        $this->grupo = $grupo;

        return $this;
    }

    /**
     * Get grupo
     *
     * @return \RM\PlantillaBundle\Entity\GrupoSlots
     */
    public function getGrupo()
    {
        return $this->grupo;
    }

    /**
     * Set idInstancia
     *
     * @param \RM\ComunicacionBundle\Entity\InstanciaComunicacion $idInstancia
     * @return InstanciaCriterioDesempate
     */
    public function setIdInstancia(\RM\ComunicacionBundle\Entity\InstanciaComunicacion $idInstancia = null)
    {
        $this->idInstancia = $idInstancia;

        return $this;
    }

    /**
     * Get idInstancia
     *
     * @return \RM\ComunicacionBundle\Entity\InstanciaComunicacion
     */
    public function getIdInstancia()
    {
        return $this->idInstancia;
    }

    /**
     * Set criterioDesempate
     *
     * @param \RM\ProductoBundle\Entity\CriterioDesempate $criterioDesempate
     * @return InstanciaCriterioDesempate
     */
    public function setCriterioDesempate(\RM\ProductoBundle\Entity\CriterioDesempate $criterioDesempate = null)
    {
        $this->criterioDesempate = $criterioDesempate;

        return $this;
    }

    /**
     * Get criterioDesempate
     *
     * @return \RM\ProductoBundle\Entity\CriterioDesempate
     */
    public function getCriterioDesempate()
    {
        return $this->criterioDesempate;
    }
}


text:
#import "NSObject.h"

@interface SUImageModifier : NSObject
{
}

@property(readonly, nonatomic) _Bool scalesImage;
- (id)newImageForImage:(id)arg1;
- (struct CGRect)imageFrameForImage:(id)arg1 currentFrame:(struct CGRect)arg2 finalSize:(struct CGSize)arg3;
- (struct CGSize)finalSizeForSize:(struct CGSize)arg1 originalSize:(struct CGSize)arg2;
- (void)drawBeforeImageForContext:(struct CGContext *)arg1 imageFrame:(struct CGRect)arg2 finalSize:(struct CGSize)arg3;
- (void)drawAfterImageForContext:(struct CGContext *)arg1 imageFrame:(struct CGRect)arg2 finalSize:(struct CGSize)arg3;

@end


text:
package com.intellij.execution.junit;

import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.testframework.AbstractInClassConfigurationProducer;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.PsiElement;

//to be deleted in 2018
@Deprecated
public class TestClassConfigurationProducer extends AbstractInClassConfigurationProducer<JUnitConfiguration> {
  public TestClassConfigurationProducer() {
    super(JUnitConfigurationType.getInstance());
  }

  @Override
  public boolean isConfigurationFromContext(JUnitConfiguration configuration, ConfigurationContext context) {
    return super.isConfigurationFromContext(configuration, context);
  }

  @Override
  protected boolean setupConfigurationFromContext(JUnitConfiguration configuration,
                                                  ConfigurationContext context,
                                                  Ref<PsiElement> sourceElement) {
    return super.setupConfigurationFromContext(configuration, context, sourceElement);
  }
}


text:
"use strict";

var lint = require("../api/lint");
var path = require("path");
var sh = require("shelljs");

module.exports = function testSrc (isLint, detectedBuild) {
  var shim = detectedBuild === "legacy" ? "-r babel-polyfill" : "";

  var result = sh.exec("BABEL_ENV=" + detectedBuild
             + " mocha -c "
             + shim
             + " -r " + path.join("test/fixture/src")
             + " 'test/**/*.test.js'");

  if (isLint) lint();

  return result;
};


text:
/**
 * Created by asafdavid on 01/03/2017.
 */
import Promise from 'bluebird';
import _ from 'lodash';

import BaseService from '../baseService';

export const NOOP = res => Promise.resolve(res);

/**
 * Creates a Middleware decorator
 * @param pre
 * @param post
 * @constructor
 */
export default function Middleware(name, pre = NOOP, post = NOOP, options = {}) {
  if (!name) throw new TypeError('name is required');
  if (!_.isFunction(pre)) throw new TypeError('pre is required and must be a function');
  if (!_.isFunction(post)) throw new TypeError('post is required and must be a function');

  return function middlewareDecorator(target, key, descriptor) {
    // Check if a task is defined within a service
    if (!(target instanceof BaseService)) {
      throw SyntaxError('@task must be defined within a service');
    }
    if (!_.isFunction(descriptor.value)) {
      throw SyntaxError(`@Middleware(${name}) must be defined on a function`);
    }
    // Check if it was defined on a task
    if (!target._tasks || !target._tasks[key]) {
      throw SyntaxError(
        `@Middleware(${name}) must be defined on a task, use @Task before @Middleware`
      );
    }

    // Add the middleware by order
    target._tasks[key].middleware.pre.push(pre);
    target._tasks[key].middleware.post.push(post);
    target._tasks[key].options[name] = options;
  };
}


text:
package org.web3j.abi.datatypes.generated;

import java.math.BigInteger;

import org.web3j.abi.datatypes.Fixed;

/**
 *
Auto generated code.

 * Do not modifiy!

 * Please use {@link org.web3j.codegen.AbiTypesGenerator} to update.

 */
public class Fixed72x144 extends Fixed {
    public static final Fixed72x144 DEFAULT = new Fixed72x144(BigInteger.ZERO);

    public Fixed72x144(BigInteger value) {
        super(72, 144, value);
    }

    public Fixed72x144(int mBitSize, int nBitSize, BigInteger m, BigInteger n) {
        super(72, 144, m, n);
    }
}


text:
import React from 'react';

import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';

export default function TableSection() {
  return (

        <Anchor id="tables">Tables</Anchor> Table

Use the striped, bordered, condensed and hover props to customise the table.

      <ReactPlayground codeText={Samples.TableBasic} />

<Anchor id="table-responsive">Responsive</Anchor>

Add responsive prop to make them scroll horizontally up to small devices (under 768px). When viewing on anything larger than 768px wide, you will not see any difference in these tables.

      <ReactPlayground codeText={Samples.TableResponsive} />

<Anchor id="table-props">Props</Anchor>

      <PropTable component="Table"/>

  );
}