text:
//===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements pieces of the Preprocessor interface that manage the
// current lexer stack.
//
//===----------------------------------------------------------------------===//

#include "clang/Lex/Preprocessor.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/LexDiagnostic.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/PTHManager.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
using namespace clang;

PPCallbacks::~PPCallbacks() {}

//===----------------------------------------------------------------------===//
// Miscellaneous Methods.
//===----------------------------------------------------------------------===//

/// isInPrimaryFile - Return true if we're in the top-level file, not in a
/// \#include.  This looks through macro expansions and active _Pragma lexers.
bool Preprocessor::isInPrimaryFile() const {
  if (IsFileLexer())
    return IncludeMacroStack.empty();

  // If there are any stacked lexers, we're in a #include.
  assert(IsFileLexer(IncludeMacroStack[0]) &&
         "Top level include stack isn't our primary lexer?");
  return std::none_of(IncludeMacroStack.begin() + 1, IncludeMacroStack.end(),
                      [this](const IncludeStackInfo &ISI) -> bool {
    return IsFileLexer(ISI);
  });
}

/// getCurrentLexer - Return the current file lexer being lexed from.  Note
/// that this ignores any potentially active macro expansions and _Pragma
/// expansions going on at the time.
PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
  if (IsFileLexer())
    return CurPPLexer;

  // Look for a stacked lexer.
  for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
    if (IsFileLexer(ISI))
      return ISI.ThePPLexer;
  }
  return nullptr;
}

//===----------------------------------------------------------------------===//
// Methods for Entering and Callbacks for leaving various contexts
//===----------------------------------------------------------------------===//

/// EnterSourceFile - Add a source file to the top of the include stack and
/// start lexing tokens from it instead of the current buffer.
bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
                                   SourceLocation Loc) {
  assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
  ++NumEnteredSourceFiles;

  if (MaxIncludeStackDepth < IncludeMacroStack.size())
    MaxIncludeStackDepth = IncludeMacroStack.size();

  if (PTH) {
    if (PTHLexer *PL = PTH->CreateLexer(FID)) {
      EnterSourceFileWithPTH(PL, CurDir);
      return false;
    }
  }

  // Get the MemoryBuffer for this FID, if it fails, we fail.
  bool Invalid = false;
  const llvm::MemoryBuffer *InputFile =
    getSourceManager().getBuffer(FID, Loc, &Invalid);
  if (Invalid) {
    SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
    Diag(Loc, diag::err_pp_error_opening_file)
      << std::string(SourceMgr.getBufferName(FileStart)) << "";
    return true;
  }

  if (isCodeCompletionEnabled() &&
      SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
    CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
    CodeCompletionLoc =
        CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
  }

  EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
  return false;
}

/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
///  and start lexing tokens from it instead of the current buffer.
void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
                                            const DirectoryLookup *CurDir) {

  // Add the current lexer to the include stack.
  if (CurPPLexer || CurTokenLexer)
    PushIncludeMacroStack();

  CurLexer.reset(TheLexer);
  CurPPLexer = TheLexer;
  CurDirLookup = CurDir;
  CurSubmodule = nullptr;
  if (CurLexerKind != CLK_LexAfterModuleImport)
    CurLexerKind = CLK_Lexer;

  // Notify the client, if desired, that we are in a new source file.
  if (Callbacks && !CurLexer->Is_PragmaLexer) {
    SrcMgr::CharacteristicKind FileType =
       SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());

    Callbacks->FileChanged(CurLexer->getFileLoc(),
                           PPCallbacks::EnterFile, FileType);
  }
}

/// EnterSourceFileWithPTH - Add a source file to the top of the include stack
/// and start getting tokens from it using the PTH cache.
void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
                                          const DirectoryLookup *CurDir) {

  if (CurPPLexer || CurTokenLexer)
    PushIncludeMacroStack();

  CurDirLookup = CurDir;
  CurPTHLexer.reset(PL);
  CurPPLexer = CurPTHLexer.get();
  CurSubmodule = nullptr;
  if (CurLexerKind != CLK_LexAfterModuleImport)
    CurLexerKind = CLK_PTHLexer;

  // Notify the client, if desired, that we are in a new source file.
  if (Callbacks) {
    FileID FID = CurPPLexer->getFileID();
    SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
    SrcMgr::CharacteristicKind FileType =
      SourceMgr.getFileCharacteristic(EnterLoc);
    Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
  }
}

/// EnterMacro - Add a Macro to the top of the include stack and start lexing
/// tokens from it instead of the current buffer.
void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
                              MacroInfo *Macro, MacroArgs *Args) {
  std::unique_ptr<TokenLexer> TokLexer;
  if (NumCachedTokenLexers == 0) {
    TokLexer = llvm::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);
  } else {
    TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
    TokLexer->Init(Tok, ILEnd, Macro, Args);
  }

  PushIncludeMacroStack();
  CurDirLookup = nullptr;
  CurTokenLexer = std::move(TokLexer);
  if (CurLexerKind != CLK_LexAfterModuleImport)
    CurLexerKind = CLK_TokenLexer;
}

/// EnterTokenStream - Add a "macro" context to the top of the include stack,
/// which will cause the lexer to start returning the specified tokens.
///
/// If DisableMacroExpansion is true, tokens lexed from the token stream will
/// not be subject to further macro expansion.  Otherwise, these tokens will
/// be re-macro-expanded when/if expansion is enabled.
///
/// If OwnsTokens is false, this method assumes that the specified stream of
/// tokens has a permanent owner somewhere, so they do not need to be copied.
/// If it is true, it assumes the array of tokens is allocated with new[] and
/// must be freed.
///
void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
                                    bool DisableMacroExpansion,
                                    bool OwnsTokens) {
  if (CurLexerKind == CLK_CachingLexer) {
    if (CachedLexPos < CachedTokens.size()) {
      // We're entering tokens into the middle of our cached token stream. We
      // can't represent that, so just insert the tokens into the buffer.
      CachedTokens.insert(CachedTokens.begin() + CachedLexPos,
                          Toks, Toks + NumToks);
      if (OwnsTokens)
        delete [] Toks;
      return;
    }

    // New tokens are at the end of the cached token sequnece; insert the
    // token stream underneath the caching lexer.
    ExitCachingLexMode();
    EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
    EnterCachingLexMode();
    return;
  }

  // Create a macro expander to expand from the specified token stream.
  std::unique_ptr<TokenLexer> TokLexer;
  if (NumCachedTokenLexers == 0) {
    TokLexer = llvm::make_unique<TokenLexer>(
        Toks, NumToks, DisableMacroExpansion, OwnsTokens, *this);
  } else {
    TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
    TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
  }

  // Save our current state.
  PushIncludeMacroStack();
  CurDirLookup = nullptr;
  CurTokenLexer = std::move(TokLexer);
  if (CurLexerKind != CLK_LexAfterModuleImport)
    CurLexerKind = CLK_TokenLexer;
}

/// \brief Compute the relative path that names the given file relative to
/// the given directory.
static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
                                const FileEntry *File,
                                SmallString<128> &Result) {
  Result.clear();

  StringRef FilePath = File->getDir()->getName();
  StringRef Path = FilePath;
  while (!Path.empty()) {
    if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
      if (CurDir == Dir) {
        Result = FilePath.substr(Path.size());
        llvm::sys::path::append(Result,
                                llvm::sys::path::filename(File->getName()));
        return;
      }
    }

    Path = llvm::sys::path::parent_path(Path);
  }

  Result = File->getName();
}

void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
  if (CurTokenLexer) {
    CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
    return;
  }
  if (CurLexer) {
    CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
    return;
  }
  // FIXME: Handle other kinds of lexers?  It generally shouldn't matter,
  // but it might if they're empty?
}

/// \brief Determine the location to use as the end of the buffer for a lexer.
///
/// If the file ends with a newline, form the EOF token on the newline itself,
/// rather than "on the line following it", which doesn't exist.  This makes
/// diagnostics relating to the end of file include the last file that the user
/// actually typed, which is goodness.
const char *Preprocessor::getCurLexerEndPos() {
  const char *EndPos = CurLexer->BufferEnd;
  if (EndPos != CurLexer->BufferStart &&
      (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
    --EndPos;

    // Handle \n\r and \r\n:
    if (EndPos != CurLexer->BufferStart &&
        (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
        EndPos[-1] != EndPos[0])
      --EndPos;
  }

  return EndPos;
}

/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
/// the current file.  This either returns the EOF token or pops a level off
/// the include stack and keeps going.
bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
  assert(!CurTokenLexer &&
         "Ending a file when currently in a macro!");

  // See if this file had a controlling macro.
  if (CurPPLexer) {  // Not ending a macro, ignore it.
    if (const IdentifierInfo *ControllingMacro =
          CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
      // Okay, this has a controlling macro, remember in HeaderFileInfo.
      if (const FileEntry *FE = CurPPLexer->getFileEntry()) {
        HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
        if (MacroInfo *MI =
              getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro))) {
          MI->UsedForHeaderGuard = true;
        }
        if (const IdentifierInfo *DefinedMacro =
              CurPPLexer->MIOpt.GetDefinedMacro()) {
          if (!isMacroDefined(ControllingMacro) &&
              DefinedMacro != ControllingMacro &&
              HeaderInfo.FirstTimeLexingFile(FE)) {

            // If the edit distance between the two macros is more than 50%,
            // DefinedMacro may not be header guard, or can be header guard of
            // another header file. Therefore, it maybe defining something
            // completely different. This can be observed in the wild when
            // handling feature macros or header guards in different files.

            const StringRef ControllingMacroName = ControllingMacro->getName();
            const StringRef DefinedMacroName = DefinedMacro->getName();
            const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
                                                  DefinedMacroName.size()) / 2;
            const unsigned ED = ControllingMacroName.edit_distance(
                DefinedMacroName, true, MaxHalfLength);
            if (ED <= MaxHalfLength) {
              // Emit a warning for a bad header guard.
              Diag(CurPPLexer->MIOpt.GetMacroLocation(),
                   diag::warn_header_guard)
                  << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
              Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
                   diag::note_header_guard)
                  << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
                  << ControllingMacro
                  << FixItHint::CreateReplacement(
                         CurPPLexer->MIOpt.GetDefinedLocation(),
                         ControllingMacro->getName());
            }
          }
        }
      }
    }
  }

  // Complain about reaching a true EOF within arc_cf_code_audited.
  // We don't want to complain about reaching the end of a macro
  // instantiation or a _Pragma.
  if (PragmaARCCFCodeAuditedLoc.isValid() &&
      !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
    Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);

    // Recover by leaving immediately.
    PragmaARCCFCodeAuditedLoc = SourceLocation();
  }

  // Complain about reaching a true EOF within assume_nonnull.
  // We don't want to complain about reaching the end of a macro
  // instantiation or a _Pragma.
  if (PragmaAssumeNonNullLoc.isValid() &&
      !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
    Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);

    // Recover by leaving immediately.
    PragmaAssumeNonNullLoc = SourceLocation();
  }

  // If this is a #include'd file, pop it off the include stack and continue
  // lexing the #includer file.
  if (!IncludeMacroStack.empty()) {

    // If we lexed the code-completion file, act as if we reached EOF.
    if (isCodeCompletionEnabled() && CurPPLexer &&
        SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
            CodeCompletionFileLoc) {
      if (CurLexer) {
        Result.startToken();
        CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
        CurLexer.reset();
      } else {
        assert(CurPTHLexer && "Got EOF but no current lexer set!");
        CurPTHLexer->getEOF(Result);
        CurPTHLexer.reset();
      }

      CurPPLexer = nullptr;
      return true;
    }

    if (!isEndOfMacro && CurPPLexer &&
        SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
      // Notify SourceManager to record the number of FileIDs that were created
      // during lexing of the #include'd file.
      unsigned NumFIDs =
          SourceMgr.local_sloc_entry_size() -
          CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
      SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
    }

    FileID ExitedFID;
    if (Callbacks && !isEndOfMacro && CurPPLexer)
      ExitedFID = CurPPLexer->getFileID();

    bool LeavingSubmodule = CurSubmodule && CurLexer;
    if (LeavingSubmodule) {
      // Notify the parser that we've left the module.
      const char *EndPos = getCurLexerEndPos();
      Result.startToken();
      CurLexer->BufferPtr = EndPos;
      CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
      Result.setAnnotationEndLoc(Result.getLocation());
      Result.setAnnotationValue(CurSubmodule);

      // We're done with this submodule.
      LeaveSubmodule();
    }

    // We're done with the #included file.
    RemoveTopOfLexerStack();

    // Propagate info about start-of-line/leading white-space/etc.
    PropagateLineStartLeadingSpaceInfo(Result);

    // Notify the client, if desired, that we are in a new source file.
    if (Callbacks && !isEndOfMacro && CurPPLexer) {
      SrcMgr::CharacteristicKind FileType =
        SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
      Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
                             PPCallbacks::ExitFile, FileType, ExitedFID);
    }

    // Client should lex another token unless we generated an EOM.
    return LeavingSubmodule;
  }

  // If this is the end of the main file, form an EOF token.
  if (CurLexer) {
    const char *EndPos = getCurLexerEndPos();
    Result.startToken();
    CurLexer->BufferPtr = EndPos;
    CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);

    if (isCodeCompletionEnabled()) {
      // Inserting the code-completion point increases the source buffer by 1,
      // but the main FileID was created before inserting the point.
      // Compensate by reducing the EOF location by 1, otherwise the location
      // will point to the next FileID.
      // FIXME: This is hacky, the code-completion point should probably be
      // inserted before the main FileID is created.
      if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
        Result.setLocation(Result.getLocation().getLocWithOffset(-1));
    }

    if (!isIncrementalProcessingEnabled())
      // We're done with lexing.
      CurLexer.reset();
  } else {
    assert(CurPTHLexer && "Got EOF but no current lexer set!");
    CurPTHLexer->getEOF(Result);
    CurPTHLexer.reset();
  }

  if (!isIncrementalProcessingEnabled())
    CurPPLexer = nullptr;

  if (TUKind == TU_Complete) {
    // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
    // collected all macro locations that we need to warn because they are not
    // used.
    for (WarnUnusedMacroLocsTy::iterator
           I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
           I!=E; ++I)
      Diag(*I, diag::pp_macro_not_used);
  }

  // If we are building a module that has an umbrella header, make sure that
  // each of the headers within the directory covered by the umbrella header
  // was actually included by the umbrella header.
  if (Module *Mod = getCurrentModule()) {
    if (Mod->getUmbrellaHeader()) {
      SourceLocation StartLoc
        = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());

      if (!getDiagnostics().isIgnored(diag::warn_uncovered_module_header,
                                      StartLoc)) {
        ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
        const DirectoryEntry *Dir = Mod->getUmbrellaDir().Entry;
        vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
        std::error_code EC;
        for (vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC), End;
             Entry != End && !EC; Entry.increment(EC)) {
          using llvm::StringSwitch;

          // Check whether this entry has an extension typically associated with
          // headers.
          if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->getName()))
                 .Cases(".h", ".H", ".hh", ".hpp", true)
                 .Default(false))
            continue;

          if (const FileEntry *Header =
                  getFileManager().getFile(Entry->getName()))
            if (!getSourceManager().hasFileInfo(Header)) {
              if (!ModMap.isHeaderInUnavailableModule(Header)) {
                // Find the relative path that would access this header.
                SmallString<128> RelativePath;
                computeRelativePath(FileMgr, Dir, Header, RelativePath);
                Diag(StartLoc, diag::warn_uncovered_module_header)
                  << Mod->getFullModuleName() << RelativePath;
              }
            }
        }
      }
    }
  }

  return true;
}

/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
/// hits the end of its token stream.
bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
  assert(CurTokenLexer && !CurPPLexer &&
         "Ending a macro when currently in a #include file!");

  if (!MacroExpandingLexersStack.empty() &&
      MacroExpandingLexersStack.back().first == CurTokenLexer.get())
    removeCachedMacroExpandedTokensOfLastLexer();

  // Delete or cache the now-dead macro expander.
  if (NumCachedTokenLexers == TokenLexerCacheSize)
    CurTokenLexer.reset();
  else
    TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);

  // Handle this like a #include file being popped off the stack.
  return HandleEndOfFile(Result, true);
}

/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
/// lexer stack.  This should only be used in situations where the current
/// state of the top-of-stack lexer is unknown.
void Preprocessor::RemoveTopOfLexerStack() {
  assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");

  if (CurTokenLexer) {
    // Delete or cache the now-dead macro expander.
    if (NumCachedTokenLexers == TokenLexerCacheSize)
      CurTokenLexer.reset();
    else
      TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
  }

  PopIncludeMacroStack();
}

/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
/// comment (/##/) in microsoft mode, this method handles updating the current
/// state, returning the token on the next source line.
void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
  assert(CurTokenLexer && !CurPPLexer &&
         "Pasted comment can only be formed from macro");
  // We handle this by scanning for the closest real lexer, switching it to
  // raw mode and preprocessor mode.  This will cause it to return \n as an
  // explicit EOD token.
  PreprocessorLexer *FoundLexer = nullptr;
  bool LexerWasInPPMode = false;
  for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
    if (ISI.ThePPLexer == nullptr) continue;  // Scan for a real lexer.

    // Once we find a real lexer, mark it as raw mode (disabling macro
    // expansions) and preprocessor mode (return EOD).  We know that the lexer
    // was *not* in raw mode before, because the macro that the comment came
    // from was expanded.  However, it could have already been in preprocessor
    // mode (#if COMMENT) in which case we have to return it to that mode and
    // return EOD.
    FoundLexer = ISI.ThePPLexer;
    FoundLexer->LexingRawMode = true;
    LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
    FoundLexer->ParsingPreprocessorDirective = true;
    break;
  }

  // Okay, we either found and switched over the lexer, or we didn't find a
  // lexer.  In either case, finish off the macro the comment came from, getting
  // the next token.
  if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);

  // Discarding comments as long as we don't have EOF or EOD.  This 'comments
  // out' the rest of the line, including any tokens that came from other macros
  // that were active, as in:
  //  #define submacro a COMMENT b
  //    submacro c
  // which should lex to 'a' only: 'b' and 'c' should be removed.
  while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
    Lex(Tok);

  // If we got an eod token, then we successfully found the end of the line.
  if (Tok.is(tok::eod)) {
    assert(FoundLexer && "Can't get end of line without an active lexer");
    // Restore the lexer back to normal mode instead of raw mode.
    FoundLexer->LexingRawMode = false;

    // If the lexer was already in preprocessor mode, just return the EOD token
    // to finish the preprocessor line.
    if (LexerWasInPPMode) return;

    // Otherwise, switch out of PP mode and return the next lexed token.
    FoundLexer->ParsingPreprocessorDirective = false;
    return Lex(Tok);
  }

  // If we got an EOF token, then we reached the end of the token stream but
  // didn't find an explicit \n.  This can only happen if there was no lexer
  // active (an active lexer would return EOD at EOF if there was no \n in
  // preprocessor directive mode), so just return EOF as our token.
  assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
}

void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc) {
  if (!getLangOpts().ModulesLocalVisibility) {
    // Just track that we entered this submodule.
    BuildingSubmoduleStack.push_back(BuildingSubmoduleInfo(
        M, ImportLoc, CurSubmoduleState, PendingModuleMacroNames.size()));
    return;
  }

  // Resolve as much of the module definition as we can now, before we enter
  // one of its headers.
  // FIXME: Can we enable Complain here?
  // FIXME: Can we do this when local visibility is disabled?
  ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
  ModMap.resolveExports(M, /*Complain=*/false);
  ModMap.resolveUses(M, /*Complain=*/false);
  ModMap.resolveConflicts(M, /*Complain=*/false);

  // If this is the first time we've entered this module, set up its state.
  auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));
  auto &State = R.first->second;
  bool FirstTime = R.second;
  if (FirstTime) {
    // Determine the set of starting macros for this submodule; take these
    // from the "null" module (the predefines buffer).
    //
    // FIXME: If we have local visibility but not modules enabled, the
    // NullSubmoduleState is polluted by #defines in the top-level source
    // file.
    auto &StartingMacros = NullSubmoduleState.Macros;

    // Restore to the starting state.
    // FIXME: Do this lazily, when each macro name is first referenced.
    for (auto &Macro : StartingMacros) {
      // Skip uninteresting macros.
      if (!Macro.second.getLatest() &&
          Macro.second.getOverriddenMacros().empty())
        continue;

      MacroState MS(Macro.second.getLatest());
      MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
      State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
    }
  }

  // Track that we entered this module.
  BuildingSubmoduleStack.push_back(BuildingSubmoduleInfo(
      M, ImportLoc, CurSubmoduleState, PendingModuleMacroNames.size()));

  // Switch to this submodule as the current submodule.
  CurSubmoduleState = &State;

  // This module is visible to itself.
  if (FirstTime)
    makeModuleVisible(M, ImportLoc);
}

bool Preprocessor::needModuleMacros() const {
  // If we're not within a submodule, we never need to create ModuleMacros.
  if (BuildingSubmoduleStack.empty())
    return false;
  // If we are tracking module macro visibility even for textually-included
  // headers, we need ModuleMacros.
  if (getLangOpts().ModulesLocalVisibility)
    return true;
  // Otherwise, we only need module macros if we're actually compiling a module
  // interface.
  return getLangOpts().isCompilingModule();
}

void Preprocessor::LeaveSubmodule() {
  auto &Info = BuildingSubmoduleStack.back();

  Module *LeavingMod = Info.M;
  SourceLocation ImportLoc = Info.ImportLoc;

  if (!needModuleMacros() ||
      (!getLangOpts().ModulesLocalVisibility &&
       LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {
    // If we don't need module macros, or this is not a module for which we
    // are tracking macro visibility, don't build any, and preserve the list
    // of pending names for the surrounding submodule.
    BuildingSubmoduleStack.pop_back();
    makeModuleVisible(LeavingMod, ImportLoc);
    return;
  }

  // Create ModuleMacros for any macros defined in this submodule.
  llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
  for (unsigned I = Info.OuterPendingModuleMacroNames;
       I != PendingModuleMacroNames.size(); ++I) {
    auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]);
    if (!VisitedMacros.insert(II).second)
      continue;

    auto MacroIt = CurSubmoduleState->Macros.find(II);
    if (MacroIt == CurSubmoduleState->Macros.end())
      continue;
    auto &Macro = MacroIt->second;

    // Find the starting point for the MacroDirective chain in this submodule.
    MacroDirective *OldMD = nullptr;
    auto *OldState = Info.OuterSubmoduleState;
    if (getLangOpts().ModulesLocalVisibility)
      OldState = &NullSubmoduleState;
    if (OldState && OldState != CurSubmoduleState) {
      // FIXME: It'd be better to start at the state from when we most recently
      // entered this submodule, but it doesn't really matter.
      auto &OldMacros = OldState->Macros;
      auto OldMacroIt = OldMacros.find(II);
      if (OldMacroIt == OldMacros.end())
        OldMD = nullptr;
      else
        OldMD = OldMacroIt->second.getLatest();
    }

    // This module may have exported a new macro. If so, create a ModuleMacro
    // representing that fact.
    bool ExplicitlyPublic = false;
    for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) {
      assert(MD && "broken macro directive chain");

      // Stop on macros defined in other submodules of this module that we
      // #included along the way. There's no point doing this if we're
      // tracking local submodule visibility, since there can be no such
      // directives in our list.
      if (!getLangOpts().ModulesLocalVisibility) {
        Module *Mod = getModuleContainingLocation(MD->getLocation());
        if (Mod != LeavingMod &&
            Mod->getTopLevelModule() == LeavingMod->getTopLevelModule())
          break;
      }

      if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
        // The latest visibility directive for a name in a submodule affects
        // all the directives that come before it.
        if (VisMD->isPublic())
          ExplicitlyPublic = true;
        else if (!ExplicitlyPublic)
          // Private with no following public directive: not exported.
          break;
      } else {
        MacroInfo *Def = nullptr;
        if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
          Def = DefMD->getInfo();

        // FIXME: Issue a warning if multiple headers for the same submodule
        // define a macro, rather than silently ignoring all but the first.
        bool IsNew;
        // Don't bother creating a module macro if it would represent a #undef
        // that doesn't override anything.
        if (Def || !Macro.getOverriddenMacros().empty())
          addModuleMacro(LeavingMod, II, Def,
                         Macro.getOverriddenMacros(), IsNew);
        break;
      }
    }
  }
  PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);

  // FIXME: Before we leave this submodule, we should parse all the other
  // headers within it. Otherwise, we're left with an inconsistent state
  // where we've made the module visible but don't yet have its complete
  // contents.

  // Put back the outer module's state, if we're tracking it.
  if (getLangOpts().ModulesLocalVisibility)
    CurSubmoduleState = Info.OuterSubmoduleState;

  BuildingSubmoduleStack.pop_back();

  // A nested #include makes the included submodule visible.
  makeModuleVisible(LeavingMod, ImportLoc);
}


text:
{% extends "oscar/checkout/shipping_address.html" %}
{% load currency_filters %}
{% load i18n %}

{% block content %}

{% trans "Who are you?" %}

<form action="." method="post" class="form-stacked">

                {% csrf_token %}
                {{ form.non_field_errors }}
                {% include 'partials/form_field.html' with field=form.username %}

                    {{ form.options.errors }}

                             <input type="radio" id="id_options_1" name="options" value="existing" {% if form.password.errors %}checked="checked"{% endif %} />
                             {% trans "I have an account and my password is" %}:

                        {{ form.password }}
                        {% trans "Get a password reminder" %}
                        {% for error in form.password.errors %}

                                {{ error }}

                        {% endfor %}

                             <input type="radio" id="id_options_0" name="options" value="anonymous" {% if not form.password.errors %}checked="checked"{% endif %} />
                             {% trans "I don't want to create an account" %}:

    <button type="submit" class="btn btn-large btn-primary pull-right" data-loading-text="{% trans 'Submitting...' %}">{% trans "Continue" %}</button>
</form>

{% endblock content %}

redpajama_set_name: RedPajamaGithub


text:
package com.twitter.chill.java;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unchecked")
public class TestLists {

    private static final Kryo kryo = new Kryo();

    private static final Map<Class<?>, List<?>> map = new HashMap<Class<?>, List<?>>(9);

    static {
        ArraysAsListSerializer.registrar().apply(kryo);
        map.put(byte.class, Arrays.asList((byte) 1, (byte) 2, (byte) 3, (byte) 4));
        map.put(short.class, Arrays.asList((short) 1, (short) 2, (short) 3, (short) 4));
        map.put(int.class, Arrays.asList(1, 2, 3, 4));
        map.put(long.class, Arrays.asList(1L, 2L, 3L, 4L));
        map.put(char.class, Arrays.asList('1', '2', '3', '4'));
        map.put(float.class, Arrays.asList(1.0F, 2.0F, 3.0F, 4.0F));
        map.put(double.class, Arrays.asList(1.0, 2.0, 3.0, 4.0));
        map.put(boolean.class, Arrays.asList(true, false, true));
        map.put(String.class, Arrays.asList("one", "two", "three"));
        map.put(List.class, Arrays.asList(
                Arrays.asList(1, 2, 3, 4),
                Arrays.asList(1.0, 2.0, 3.0, 4.0),
                Arrays.asList("one", "two", "three")
        ));
    }

    public static <T> T serializeAndDeserialize(T t) {
        Output output = new Output(1000, -1);
        kryo.writeClassAndObject(output, t);
        Input input = new Input(output.toBytes());
        return (T) kryo.readClassAndObject(input);
    }

    public static List<?> getList(Class<?> c) {
        return map.get(c);
    }
}


text:
package com.mecury.download;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import com.mecury.Utils.FileUtils;

import android.R.integer;
import android.R.string;

public class HttpDownload {

	/*
	 * ÏÂÔز¿·Ö´úÂë
	 */
	public String download(String urlstr){
			StringBuffer sb = new StringBuffer();
			String line = null;
			BufferedReader buffer = null;
		try {
			//´´½¨Ò»¸öURL¶ÔÏó
			URL url = new URL(urlstr);
			//´´½¨Ò»¸öhttpÁ¬½Ó
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			buffer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			while ((line = buffer.readLine())!=null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				buffer.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return sb.toString();
	}

	/*
	 * serviceÖÐÓõ½µÄÏÂÔØ·½·¨,¸Ã·½·¨·µ»ØµÄÖµ-1£º´ú±í³ö´í£¬0£º´ú±íÏÂÔسɹ¦£¬1£º´ú±íÎļþÒѾ´æÔÚ
	 */
	public int downloadFile(String urlstr, String path, String fileName){
		InputStream inputStream = null;
		try {
			FileUtils fileUtils = new FileUtils();
			if (fileUtils.isFileExist(fileName, path)) {
				return 1;
			}else {
				inputStream = getInputStreamFromUrl(urlstr);
				File result = fileUtils.writeSDFromInput(path, fileName, inputStream);
				if (result == null) {
					return -1;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}finally{
			try {
				inputStream.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return 0;
	}

	/*
	 * ¸ù¾ÝUrlµÃµ½ÊäÈëÁ÷
	 */
	public InputStream getInputStreamFromUrl(String urlstr) throws MalformedURLException,IOException{
		URL url = new URL(urlstr);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		InputStream inputStream = connection.getInputStream();
		return inputStream;
	}
}


text:
namespace ash {

// Ash-specific information about a Message Center notifier.
struct ASH_PUBLIC_EXPORT NotifierMetadata {
  NotifierMetadata();
  NotifierMetadata(const NotifierMetadata& other);
  NotifierMetadata(NotifierMetadata&& other);
  NotifierMetadata(const message_center::NotifierId& notifier_id,
                   const std::u16string& name,
                   bool enabled,
                   bool enforced,
                   const gfx::ImageSkia& icon);

  ~NotifierMetadata();

  NotifierMetadata& operator=(const NotifierMetadata& other);
  NotifierMetadata& operator=(NotifierMetadata&& other);

  // The notifier (e.g. an extension).
  message_center::NotifierId notifier_id;

  // The user-visible name of the notifier (e.g. an extension's name).
  std::u16string name;

  // True if notifications from the notifier are presently enabled.
  bool enabled = false;

  // True if the setting is enforced by administrator and the user can't change.
  bool enforced = false;

  // An icon displayed next to the name.
  gfx::ImageSkia icon;
};

}  // namespace ash

#endif  // ASH_PUBLIC_CPP_NOTIFIER_METADATA_H_


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>org.apache.solr.morphlines.cell (Solr 5.5.0 API)</title>
<meta name="date" content="2016-02-16">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.apache.solr.morphlines.cell

Classes

SolrCellBuilder

StripNonCharSolrContentHandlerFactory

TrimSolrContentHandlerFactory


text:
//------------------------------------------------------------------------------
// Project:  arrayfunc
// Module:   arrayparams_onesimd.c
// Purpose:  Common functions for arrayfunc.
// Language: C
// Date:     28-Nov-2017
//
//------------------------------------------------------------------------------
//
//   Copyright 2014 - 2017    Michael Griffin    <m12.griffin@gmail.com>
//
//   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.
//
//------------------------------------------------------------------------------

#include <stdbool.h>

#include "Python.h"

/*--------------------------------------------------------------------------- */

#define ARGSINIT_ONE {0, 0, 0, 0, 0, 0, 0, 0, {NULL}, {NULL}, {NULL}, {NULL}}

// Provide a struct for returning data from parsing Python arguments.
struct args_params_1 {
	char error;
	char arraytype;
	bool hasoutputarray;
	char hasbuffer1;
	char hasbuffer2;
	unsigned int ignoreerrors;
	int nosimd;
	Py_ssize_t arraylength;
	union dataarrays array1;
	union dataarrays array2;
	Py_buffer pybuffer1;
	Py_buffer pybuffer2;
};

/*--------------------------------------------------------------------------- */

struct args_params_1 getparams_one(PyObject *self, PyObject *args, PyObject *keywds, char matherrors, char *funcname);

void releasebuffers_one(struct args_params_1 arraydata);

/*--------------------------------------------------------------------------- */


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MaterialModule } from '../../material.module';
import { TaskListCloudComponent } from './components/task-list-cloud.component';
import { ServiceTaskListCloudComponent } from './components/service-task-list-cloud.component';
import { CoreModule } from '@alfresco/adf-core';
import { TASK_LIST_CLOUD_TOKEN, TASK_LIST_PREFERENCES_SERVICE_TOKEN } from '../../services/cloud-token.service';
import { TaskListCloudService } from './services/task-list-cloud.service';
import { LocalPreferenceCloudService } from '../../services/local-preference-cloud.service';

@NgModule({
    imports: [
        CommonModule,
        MaterialModule,
        CoreModule
    ],
    declarations: [
        TaskListCloudComponent,
        ServiceTaskListCloudComponent
    ],
    exports: [
        TaskListCloudComponent,
        ServiceTaskListCloudComponent
    ],
    providers: [
        {
            provide: TASK_LIST_CLOUD_TOKEN,
            useClass: TaskListCloudService
        },
        {
            provide: TASK_LIST_PREFERENCES_SERVICE_TOKEN,
            useClass: LocalPreferenceCloudService
        }
    ]
})
export class TaskListCloudModule { }


text:
var attire = require('attire');

attire.buildDemo({
    file: 'README.md',
    dest: 'index.html',
    title: 'Type factory',
    description: 'Simple and convenient generator of prototype based constructor functions',
    canonicalUrl: 'http://dbrekalo.github.io/type-factory/',
    githubUrl: 'https://github.com/dbrekalo/type-factory',
    userRepositories: {
        user: 'dbrekalo',
        onlyWithPages: true
    },
    author: {
        caption: 'Damir Brekalo',
        url: 'https://github.com/dbrekalo',
        image: 'https://s.gravatar.com/avatar/32754a476fb3db1c5a1f9ad80c65d89d?s=80',
        email: 'dbrekalo@gmail.com',
        github: 'https://github.com/dbrekalo',
        twitter: 'https://twitter.com/dbrekalo'
    },
    afterParse: function($) {
        $('p').first().remove();
        $('a').first().parent().remove();
    },
    inlineCss: true,
});


text:
<?php

namespace App\Http\Controllers\Admin;

use App\Models\ViewCustomerHire;
use App\Services\ExcelService;
use Illuminate\Http\Request;
use App\Http\Controllers\Admin\BaseController;
use App\Models\CustomerHire;

class CustomerHireController extends BaseController
{
    public function newEntity(array $attributes = [])
    {
        // TODO: Implement newEntity() method.
        return new CustomerHire($attributes);
    }

    /**
     * Display a listing of the resource.
     *
     * @return  \Illuminate\Http\Response
     */
    public function index()
    {
        //
        return view('admin.customer-hire.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return  \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.customer-hire.create');
    }

    /**
     * Display the specified resource.
     *
     * @param    int $id
     * @return  \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $entity = CustomerHire::find($id);
        return view('admin.customer-hire.edit', ['entity' => $entity]);
    }

    /**
     * Display the specified resource.
     *
     * @param    int $id
     * @return  \Illuminate\Http\Response
     */
    public function show($id)
    {
        $entity = CustomerHire::find($id);
        return view('admin.customer-hire.show', ['entity' => $entity]);
    }

    /**
     * @param  Request $request
     * @param  array $searchCols
     * @param  array $with
     * @param  null $conditionCall
     * @param  bool $all_columns
     * @return  \Illuminate\Http\JsonResponse
     */
    public function pagination(Request $request, $searchCols = [], $with = [], $conditionCall = null, $dataHandleCall = null, $all_columns = false)
    {
        $searchCols = [];
        return parent::pagination($request, $searchCols, $with, $conditionCall, function ($entities) {
            foreach ($entities as $entity) {
                $entity->status_name = $entity->status();

                $entity->real_time = $entity->hire_hours;

                //租借单状态不为初始或者租借中时 计算租借时间
                if ($entity->status == CustomerHire::STATUS_INIT || $entity->status == CustomerHire::STATUS_HIRING){
                    $entity->real_time = '未还伞';
                    continue ;
                }

                if ($entity->hire_hours == 0) {
                    $time = strtotime($entity->return_at) - strtotime($entity->hire_at);
                    $entity->real_time = time_diff($time);
                    continue ;
                }

            }
        }, true);
    }

    public function entityQuery()
    {
        return ViewCustomerHire::query();
    }

    public function export($entities)
    {
        $result[0] = [
//            '共享伞编号',
            '用户',
            '借伞网点',
            '借伞时间',
            '还伞网点',
            '还伞时间',
            '到期时间',
            '租用时长(小时)',
            '租借费用',
        ];
        foreach ($entities as $entity) {
            $result[] = [
                $entity->customer_name,
                $entity->hire_site_name,
                $entity->hire_at,
                $entity->return_site_name,
                $entity->return_at,
                $entity->expired_at,
                $entity->hire_hours,
                $entity->hire_amt,
            ];
        }

        $excel = new ExcelService();
        $excel->export($result, date('Ymd') . '_客户租借单');
    }

    public function filterQuery($filters, $queryBuilder)
    {
        foreach ($filters as $filter) {
            foreach ($filter as $k => $v) {
                if (empty($v)) {
                    continue;
                }
                switch ($k) {
                    case 'start_created_at': {
                        $queryBuilder->where('created_at', '>=', $v);
                        break;
                    }
                    case 'end_created_at': {
                        $queryBuilder->where('created_at', '<=', $v);
                        break;
                    }
                    case 'start_expired_at': {
                        $queryBuilder->where('expired_at', '>=', $v);
                        break;
                    }
                    case 'end_expired_at': {
                        $queryBuilder->where('expired_at', '<=', $v);
                        break;
                    }
                    case 'start_hire_amt': {
                        $queryBuilder->where('hire_amt', '>=', $v);
                        break;
                    }
                    case 'end_hire_amt': {
                        $queryBuilder->where('hire_amt', '<=', $v);
                        break;
                    }
                    case 'start_hire_at': {
                        $queryBuilder->where('hire_at', '>=', $v);
                        break;
                    }
                    case 'end_hire_at': {
                        $queryBuilder->where('hire_at', '<=', $v);
                        break;
                    }
                    case 'start_return_at': {
                        $queryBuilder->where('return_at', '>=', $v);
                        break;
                    }
                    case 'end_return_at': {
                        $queryBuilder->where('return_at', '<=', $v);
                        break;
                    }
                    default : {
                        $queryBuilder->where($k, 'like binary', '%' . $v . '%');
                    }
                }
            }

        }
    }

}


text:
include("interp.jl")

@flavor julia [blocktex, blockinterp, hashheader, list, indentcode, fencedcode,
               blockquote, github_table, horizontalrule, setextheader, paragraph,

               linebreak, escapes, tex, interp, en_dash, inline_code,
               asterisk_bold, asterisk_italic, image, link]


text:
    <input type="checkbox" id="topic_wait_time" ng-change="filterChanged()" ng-model="topicQuery[6]">
    Wait Time

    <input type="checkbox" id="topic_polling_location" ng-change="filterChanged()" ng-model="topicQuery[7]">
    Polling Location

    <input type="checkbox" id="topic_adm_issues" ng-change="filterChanged()" ng-model="topicQuery[8]">
    Adm. Issues

    <input type="checkbox" id="topic_pr_issues" ng-change="filterChanged()" ng-model="topicQuery[9]">
    PR Issues

    <input type="checkbox" id="topic_voter_id" ng-change="filterChanged()" ng-model="topicQuery[10]">
    Voter id

    <input type="checkbox" id="topic_absentee_voting" ng-change="filterChanged()" ng-model="topicQuery[11]">
    Absentee Voting

Toggle Feeds:

      <input type="checkbox" id="feed_twitter" ng-change="filterChanged()" ng-model="sourceQuery.twitter">

      <input type="checkbox" id="feed_facebook" ng-change="filterChanged()" ng-model="sourceQuery.facebook">

      <input type="checkbox" id="feed_googleplus" ng-change="filterChanged()" ng-model="sourceQuery.googleplus">

      <input type="checkbox" id="feed_wordpress" ng-change="filterChanged()" ng-model="sourceQuery.wordpress">

      <input type="checkbox" id="feed_disqus" ng-change="filterChanged()" ng-model="sourceQuery.disqus">

    <input type="checkbox" id="feed_paused" ng-model="streamIsActive" ng-change="togglePause()">

Bookmarks

<?php echo $stream; ?>

Limit Stream by Location or Distance

    <input type="radio" name="limit" value="all" ng-change="filterChanged()" ng-model="limitQuery" id="limit_all_posts">
     All posts

    <input type="radio" name="limit" value="state" ng-change="filterChanged()" ng-model="limitQuery" id="limit_state" data-state="<?php echo $profile->user_state; ?>">
     Within <?php echo (isset($states[$profile->user_state]) ? $states[$profile->user_state] : $profile->user_state); ?>

    <input type="radio" name="limit" value="radius" ng-change="filterChanged()" ng-model="limitQuery" id="limit_radius" data-lat="<?php echo $profile->user_lat; ?>" data-lon="<?php echo $profile->user_lon; ?>">
     Within radius

    <input type="radio" name="limit" value="custom" ng-change="filterChanged()" ng-model="limitQuery" id="limit_custom">

       Within custom area

You can define a custom area on the area settings page.

Radius:

  <slider ng-model="radiusQuery.val" slider-id="radiusSlider" min="1" max="1000" step="1" value="50" tooltip="always" formatter="radiusQuery.formatter" ng-change="radiusQuery.changed()" />

Filter

    <input type="text" id="filter-query" name="" class="form-control" ng-model="contentQuery" placeholder="Filter the current stream">


text:
package com.opengamma.analytics.financial.timeseries.analysis;

import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;

import org.testng.annotations.Test;

import com.opengamma.timeseries.precise.instant.InstantDoubleTimeSeries;
import com.opengamma.util.test.TestGroup;

/**
 * Test.
 */
@Test(groups = TestGroup.UNIT)
public class SampleAutocorrelationIIDHypothesisTest extends IIDHypothesisTestCase {
  private static final IIDHypothesis SAMPLE_ACF = new SampleAutocorrelationIIDHypothesis(0.05, 100);

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testNegativeLevel() {
    new SampleAutocorrelationIIDHypothesis(-0.1, 20);
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testHighLevel() {
    new SampleAutocorrelationIIDHypothesis(1.5, 20);
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testZeroLag() {
    new SampleAutocorrelationIIDHypothesis(0.05, 0);
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testInsufficientData() {
    final InstantDoubleTimeSeries subSeries = RANDOM.subSeries(RANDOM.getTimeAtIndex(0), RANDOM.getTimeAtIndex(3));
    SAMPLE_ACF.evaluate(subSeries);
  }

  @Test
  public void test() {
    super.assertNullTS(SAMPLE_ACF);
    super.assertEmptyTS(SAMPLE_ACF);
    assertTrue(SAMPLE_ACF.evaluate(RANDOM));
    assertFalse(SAMPLE_ACF.evaluate(SIGNAL));
    assertFalse(SAMPLE_ACF.evaluate(INCREASING));
  }
}


text:
- Setup MongoDB
- Show/Hide Forms
- Add River Data
- Full Log
- User Authentication
- Integrate maps


text: package testexecutionservice


text:
<?php

namespace Symfony\Component\Console\Completion;

use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;

/**
 * An input specialized for shell completion.
 *
 * This input allows unfinished option names or values and exposes what kind of
 * completion is expected.
 *
 * @author Wouter de Jong <wouter@wouterj.nl>
 */
final class CompletionInput extends ArgvInput
{
    public const TYPE_ARGUMENT_VALUE = 'argument_value';
    public const TYPE_OPTION_VALUE = 'option_value';
    public const TYPE_OPTION_NAME = 'option_name';
    public const TYPE_NONE = 'none';

    private $tokens;
    private $currentIndex;
    private $completionType;
    private $completionName = null;
    private $completionValue = '';

    /**
     * Converts a terminal string into tokens.
     *
     * This is required for shell completions without COMP_WORDS support.
     */
    public static function fromString(string $inputStr, int $currentIndex): self
    {
        preg_match_all('/(?<=^|\s)([\'"]?)(.+?)(?<!\\\\)\1(?=$|\s)/', $inputStr, $tokens);

        return self::fromTokens($tokens[0], $currentIndex);
    }

    /**
     * Create an input based on an COMP_WORDS token list.
     *
     * @param string[] $tokens       the set of split tokens (e.g. COMP_WORDS or argv)
     * @param          $currentIndex the index of the cursor (e.g. COMP_CWORD)
     */
    public static function fromTokens(array $tokens, int $currentIndex): self
    {
        $input = new self($tokens);
        $input->tokens = $tokens;
        $input->currentIndex = $currentIndex;

        return $input;
    }

    /**
     * {@inheritdoc}
     */
    public function bind(InputDefinition $definition): void
    {
        parent::bind($definition);

        $relevantToken = $this->getRelevantToken();
        if ('-' === $relevantToken[0]) {
            // the current token is an input option: complete either option name or option value
            [$optionToken, $optionValue] = explode('=', $relevantToken, 2) + ['', ''];

            $option = $this->getOptionFromToken($optionToken);
            if (null === $option && !$this->isCursorFree()) {
                $this->completionType = self::TYPE_OPTION_NAME;
                $this->completionValue = $relevantToken;

                return;
            }

            if (null !== $option && $option->acceptValue()) {
                $this->completionType = self::TYPE_OPTION_VALUE;
                $this->completionName = $option->getName();
                $this->completionValue = $optionValue ?: (!str_starts_with($optionToken, '--') ? substr($optionToken, 2) : '');

                return;
            }
        }

        $previousToken = $this->tokens[$this->currentIndex - 1];
        if ('-' === $previousToken[0] && '' !== trim($previousToken, '-')) {
            // check if previous option accepted a value
            $previousOption = $this->getOptionFromToken($previousToken);
            if (null !== $previousOption && $previousOption->acceptValue()) {
                $this->completionType = self::TYPE_OPTION_VALUE;
                $this->completionName = $previousOption->getName();
                $this->completionValue = $relevantToken;

                return;
            }
        }

        // complete argument value
        $this->completionType = self::TYPE_ARGUMENT_VALUE;

        foreach ($this->definition->getArguments() as $argumentName => $argument) {
            if (!isset($this->arguments[$argumentName])) {
                break;
            }

            $argumentValue = $this->arguments[$argumentName];
            $this->completionName = $argumentName;
            if (\is_array($argumentValue)) {
                $this->completionValue = $argumentValue ? $argumentValue[array_key_last($argumentValue)] : null;
            } else {
                $this->completionValue = $argumentValue;
            }
        }

        if ($this->currentIndex >= \count($this->tokens)) {
            if (!isset($this->arguments[$argumentName]) || $this->definition->getArgument($argumentName)->isArray()) {
                $this->completionName = $argumentName;
                $this->completionValue = '';
            } else {
                // we've reached the end
                $this->completionType = self::TYPE_NONE;
                $this->completionName = null;
                $this->completionValue = '';
            }
        }
    }

    /**
     * Returns the type of completion required.
     *
     * TYPE_ARGUMENT_VALUE when completing the value of an input argument
     * TYPE_OPTION_VALUE   when completing the value of an input option
     * TYPE_OPTION_NAME    when completing the name of an input option
     * TYPE_NONE           when nothing should be completed
     *
     * @return string One of self::TYPE_* constants. TYPE_OPTION_NAME and TYPE_NONE are already implemented by the Console component
     */
    public function getCompletionType(): string
    {
        return $this->completionType;
    }

    /**
     * The name of the input option or argument when completing a value.
     *
     * @return string|null returns null when completing an option name
     */
    public function getCompletionName(): ?string
    {
        return $this->completionName;
    }

    /**
     * The value already typed by the user (or empty string).
     */
    public function getCompletionValue(): string
    {
        return $this->completionValue;
    }

    public function mustSuggestOptionValuesFor(string $optionName): bool
    {
        return self::TYPE_OPTION_VALUE === $this->getCompletionType() && $optionName === $this->getCompletionName();
    }

    public function mustSuggestArgumentValuesFor(string $argumentName): bool
    {
        return self::TYPE_ARGUMENT_VALUE === $this->getCompletionType() && $argumentName === $this->getCompletionName();
    }

    protected function parseToken(string $token, bool $parseOptions): bool
    {
        try {
            return parent::parseToken($token, $parseOptions);
        } catch (RuntimeException $e) {
            // suppress errors, completed input is almost never valid
        }

        return $parseOptions;
    }

    private function getOptionFromToken(string $optionToken): ?InputOption
    {
        $optionName = ltrim($optionToken, '-');
        if (!$optionName) {
            return null;
        }

        if ('-' === ($optionToken[1] ?? ' ')) {
            // long option name
            return $this->definition->hasOption($optionName) ? $this->definition->getOption($optionName) : null;
        }

        // short option name
        return $this->definition->hasShortcut($optionName[0]) ? $this->definition->getOptionForShortcut($optionName[0]) : null;
    }

    /**
     * The token of the cursor, or the last token if the cursor is at the end of the input.
     */
    private function getRelevantToken(): string
    {
        return $this->tokens[$this->isCursorFree() ? $this->currentIndex - 1 : $this->currentIndex];
    }

    /**
     * Whether the cursor is "free" (i.e. at the end of the input preceded by a space).
     */
    private function isCursorFree(): bool
    {
        $nrOfTokens = \count($this->tokens);
        if ($this->currentIndex > $nrOfTokens) {
            throw new \LogicException('Current index is invalid, it must be the number of input tokens or one more.');
        }

        return $this->currentIndex >= $nrOfTokens;
    }

    public function __toString()
    {
        $str = '';
        foreach ($this->tokens as $i => $token) {
            $str .= $token;

            if ($this->currentIndex === $i) {
                $str .= '|';
            }

            $str .= ' ';
        }

        if ($this->currentIndex > $i) {
            $str .= '|';
        }

        return rtrim($str);
    }
}


text:
classdef CaffeNet < handle
    properties (SetAccess = private)
        %model_def_file = '../../examples/imagenet/imagenet_deploy.prototxt';
        %root_dir ='/home/tzeng/ABA/autoGenelable_multi_lables_proj/code/caffe/models/';
		%model_def_file = [root_dir ''];
		%model_def_file='/home/tzeng/ABA/autoGenelable_multi_lables_proj/code/caffe/models/vgg_16/deploy.prototxt';
		%model_def_file='/home/tzeng/ABA/autoGenelable_multi_lables_proj/code/caffe/models/vgg_16_fine_tune_gen/deploy.prototxt';
        %model_file = '../../examples/imagenet/caffe_reference_imagenet_model';
		%model_file = '/home/tzeng/ABA/autoGenelable_multi_lables_proj/code/caffe/models/vgg_16/VGG_16.caffemodel';
		%model_file =  '/home/tzeng/ABA/autoGenelable_multi_lables_proj/code/caffe/models/vgg_16_fine_tune_gen/finetune_vgg_16_brain_onotology_3color_mean_iter_5000';
		%model_file ='/home/tzeng/ABA/autoGenelable_multi_lables_proj/code/caffe/models/finetune_vgg_16_brain_onotology_3color_mean_noCrop_last_L_3-6_L0.001_step2500_iter_12000';

		model_def_file ='/home/tzeng/ABA/RL_gene_ontology_proj/caffe/models/vgg_16_fine_tune/deploy.prototxt';
		model_file    ='/home/tzeng/ABA/RL_gene_ontology_proj/caffe/models/finetune_vgg_16_100_labels_GO_lR_E-05_Step-2000_msk_iter_10000';

        layers_info
        blobs_info
    end
    properties
        mode
        phase
        device_id
        input_blobs
        output_blobs
    end
    properties (Dependent)
        weights
    end
    properties (Access = private)
        init_key
        weights_changed = true;
        weights_store
    end
    methods (Access=private)
        function self = CaffeNet(model_def_file, model_file)
            if nargin == 0
                init(self, self.model_def_file, self.model_file);
            end
            if nargin > 0
                init_net(self, model_def_file);
            end
            if nargin > 1
                load_net(self, model_file);
            end
            assert(is_initialized(self))
            self.mode = caffe_safe('get_mode');
            self.phase = caffe_safe('get_phase');
            self.device_id = caffe_safe('get_device');
        end
    end
    methods (Static)
        function obj = instance(model_def_file, model_file)
            persistent self
            if isempty(self)
                switch nargin
                    case 2
                        self = CaffeNet(model_def_file, model_file);
                    case 1
                        self = CaffeNet(model_def_file);
                    case 0
                        self = CaffeNet();
                end
            else
                if nargin > 0 && ~isempty(model_def_file)
                    init_net(self,model_def_file);
                    disp(' init_net(self,model_def_file)');
                end
                if nargin > 1 && ~isempty(model_file)
                    load_net(self,model_file);
                    disp('load_net(self,model_file)');
                end
            end
            obj = self;
        end
    end
    methods
        function weights = get.weights(self)
            assert(is_initialized(self))
            if (self.weights_changed)
                self.weights_store = caffe_safe('get_weights');
                self.weights_changed = false;
            end
            weights = self.weights_store;
        end
        function set.weights(self,weights)
            assert(is_initialized(self))
            caffe_safe('set_weights', weights);
            self.weights_store = weights;
            self.weights_changed = false;
        end
        function set.mode(self,mode)
            % mode = {'CPU' 'GPU'}
            switch mode
                case 'CPU'
                    caffe_safe('set_mode_cpu');
                    self.mode = mode;
                case 'GPU'
                    caffe_safe('set_mode_gpu');
                    self.mode = mode;
                otherwise
                    fprintf('Mode unknown choose between CPU and GPU\n');
                    error('Mode unknown');
            end
        end
        function set.phase(self, phase)
            % phase = {'TRAIN' 'TEST'}
            switch phase
                case 'TRAIN'
                    caffe_safe('set_phase_train');
                    self.phase = phase;
                case {'test','TEST'}
                    caffe_safe('set_phase_test');
                    self.phase = phase;
                otherwise
                    fprintf('Phase unknown choose between TRAIN and TEST')
                    error('Phase unknown');
            end
        end
        function set.device_id(self, device_id)
            caffe_safe('set_device', device_id);
            self.device_id = device_id;
        end
        function set.input_blobs(self, input_blobs)
            assert(is_initialized(self))
            caffe_safe('set_input_blobs', input_blobs);
            self.input_blobs = input_blobs;
        end
        function set.output_blobs(self, output_blobs)
            assert(is_initialized(self))
            caffe_safe('set_output_blobs', output_blobs);
            self.output_blobs = output_blobs;
        end
    end
    methods
        function res = forward(self,input)
            assert(is_initialized(self))
            if nargin < 2
                res = caffe_safe('forward');
            else
                res = caffe_safe('forward',input);
            end
        end
        function res = backward(self,diff)
            assert(is_initialized(self))
            if nargin < 2
                res = caffe_safe('backward');
            else
                res = caffe_safe('backward',diff);
            end
        end
        function res = forward_prefilled(self)
            assert(is_initialized(self))
            res = caffe_safe('forward_prefilled');
        end
        function res = backward_prefilled(self)
            assert(is_initialized(self))
            res = caffe_safe('backward_prefilled');
        end
        function res = init(self, model_def_file, model_file)
            self.init_key = caffe_safe('init',model_def_file, model_file);
            assert(is_initialized(self))
            self.model_def_file = model_def_file;
            self.model_file = model_file;
            self.layers_info = caffe_safe('get_layers_info');
            self.blobs_info = caffe_safe('get_blobs_info');
            self.weights_changed = true;
            res = self.init_key;
        end
        function res = init_net(self, model_def_file)
            self.init_key = caffe_safe('init_net',model_def_file);
            assert(is_initialized(self))
            self.model_def_file = model_def_file;
            self.model_file = [];
            self.layers_info = caffe_safe('get_layers_info');
            self.blobs_info = caffe_safe('get_blobs_info');
            self.weights_changed = true;
            res = self.init_key;
        end
        function res = load_net(self, model_file)
            assert(is_initialized(self))
            self.init_key = caffe_safe('load_net',model_file);
            self.model_file = model_file;
            self.weights_changed = true;
            res = self.init_key;
        end
        function res = save_net(self, model_file)
            assert(is_initialized(self))
            res = caffe_safe('save_net', model_file);
        end
        function res = is_initialized(~)
            res = caffe_safe('is_initialized')>0;
        end
        function set_mode_cpu(self)
            self.mode = 'CPU';
        end
        function set_mode_gpu(self)
            self.mode = 'GPU';
        end
        function set_phase_train(self)
            self.phase = 'TRAIN';
        end
        function set_phase_test(self)
            self.phase = 'TEST';
        end
        function set_device(self, device_id)
            self.device_id = device_id;
        end
        function res = get_weights(self)
            assert(is_initialized(self))
            res = self.weights;
        end
        function set_weights(self, weights)
            self.weights = weights;
        end
        function res = get_layer_weights(self, layer_name)
            assert(is_initialized(self))
            res = caffe_safe('get_layer_weights', layer_name);
        end
        function res = set_layer_weights(self, layer_name, weights)
            assert(is_initialized(self))
            res = caffe_safe('set_layer_weights', layer_name, weights);
            self.weights = caffe_safe('get_weights');
        end
        function res = get_layers_info(self)
            assert(is_initialized(self))
            res = self.layers_info;
        end
        function res = get_blobs_info(self)
            assert(is_initialized(self))
            res = self.blobs_info;
        end
        function res = get_blob_data(self, blob_name)
            assert(is_initialized(self))
            res = caffe_safe('get_blob_data', blob_name);
        end
        function res = get_blob_diff(self, blob_name)
            assert(is_initialized(self))
            res = caffe_safe('get_blob_diff', blob_name);
        end
        function res = get_all_data(self)
            assert(is_initialized(self))
            res = caffe_safe('get_all_data');
        end
        function res = get_all_diff(self)
            assert(is_initialized(self))
            res = caffe_safe('get_all_diff');
        end
        function res = get_init_key(self)
            self.init_key = caffe_safe('get_init_key');
            res = self.init_key;
        end
        function reset(self)
            caffe_safe('reset');
            self.init_key = caffe_safe('get_init_key');
            self.layers_info = [];
            self.blobs_info = [];
            self.weights_store = [];
        end
        function delete(self)
            self.weights_store = [];
            caffe_safe('reset');
            clear caffe;
        end
    end
end


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

    <title>HTML Elements</title>

Html Elements Page

    (All delays are of 2 seconds)

1. Test for presence

    <input type="button" id="test1_addElementsButton" value="Add Elements With Delay" />

        <input type="button" class="child-button" value="Child button that does nothing" />

2. Test for visibility

    <input type="text" id="test2_input" value="test2_input" />
    <input type="button" id="test2_toggleInputVisibility" value="Toggle Visibility"/>
    <input type="button" id="test2_toggleInputVisibilityWithDelay" value="Toggle Visibility With Delay"/>

    <input type="button" id="test2_addElementsButton" value="Add Elements With Delay" />

3. Test for text

    Span Value

    <input type="button" id="test3_setTextButton" value="Set Text With Delay" />

    <input type="button" id="test3_addElementsButton" value="Add Elements With Delay" />

4. Test for find

            Parent List

                    Child List

Item 1

Item 2

Item 3

    <input type="button" id="test4_addElementsButton" value="Add Elements With Delay" />

5. Test for attribute

    <input type="text" id="test5_input" class="test5-input-class" empty="" />
    <input type="button" id="test5_addAttribute" value="Add attribute with delay" />

    <input type="button" id="test5_addElementsButton" value="Add Elements With Delay" />

6. Test for timed() within context

    SelectElement singleSelect = Test6_Span

        Test6_Inner_Span
        <input type="button" id="test6_hideSpanButton" value="Hide Inner Span With Delay" />

7. Test for Element with ByJQuery

        Awesome!

    <select id="awesome-select">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>

8. Test for Checkbox

    <input type="checkbox" id="test8_checkbox1" value="Test8_Checkbox1" />
    Test8_Checkbox1

    <input type="checkbox" id="test8_checkbox2" value="Test8_Checkbox2" checked=checked />
    Test8_Checkbox2

9. Test for PageElement.find() with custom types

        <select id="nested-select" class="nested-select-marker">
          <option value="volvo">Volvo</option>
          <option value="saab">Saab</option>
          <option value="mercedes">Mercedes</option>
          <option value="audi">Audi</option>
        </select>

        <select id="nested-select2" >
          <option value="volvo">JIRA</option>
          <option value="saab">Confluence</option>
          <option value="mercedes">Bamboo</option>
          <option value="audi">Fisheye</option>
          <option value="audi">Crucible</option>
        </select>

10. Test for value

    <input type="text" id="test9_input" value="test9_value" />
    <input type="button" id="test9_toggleValue" value="Toggle Value"/>

11. Test for find with reload

            Parent List

                    Child List

Item 1

Item 2

Item 3

    <input type="button" id="test10_reloadChildListButton" value="Reload whole child list" />

    <input type="button" id="test10_reloadChildElementsButton" value="Reload child elements" />

12. Test for execute script on an element

    <input type="button" id="test11_button" value="Test11 Button" />


text:
package org.neo4j.kernel.impl.core;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.Collection;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.io.fs.DefaultFileSystemAbstraction;
import org.neo4j.io.pagecache.PageCache;
import org.neo4j.kernel.GraphDatabaseAPI;
import org.neo4j.kernel.impl.store.NeoStores;
import org.neo4j.kernel.impl.store.PropertyKeyTokenStore;
import org.neo4j.kernel.impl.store.PropertyStore;
import org.neo4j.kernel.impl.store.StoreFactory;
import org.neo4j.kernel.impl.store.record.DynamicRecord;
import org.neo4j.kernel.impl.store.record.PropertyKeyTokenRecord;
import org.neo4j.kernel.impl.transaction.state.NeoStoresSupplier;
import org.neo4j.logging.NullLogProvider;
import org.neo4j.test.OtherThreadExecutor;
import org.neo4j.test.OtherThreadExecutor.WorkerCommand;
import org.neo4j.test.PageCacheRule;
import org.neo4j.test.TargetDirectory;
import org.neo4j.test.TestGraphDatabaseFactory;

import static org.junit.Assert.assertEquals;
import static org.neo4j.helpers.collection.IteratorUtil.first;

/**
 * Tests for handling many property keys (even after restart of database)
 * as well as concurrent creation of property keys.
 */
public class ManyPropertyKeysIT
{
    @Test
    public void creating_many_property_keys_should_have_all_loaded_the_next_restart() throws Exception
    {
        // GIVEN
        // The previous limit to load was 2500, so go some above that
        GraphDatabaseAPI db = databaseWithManyPropertyKeys( 3000 );
        int countBefore = propertyKeyCount( db );

        // WHEN
        db.shutdown();
        db = database();
        createNodeWithProperty( db, key( 2800 ), true );

        // THEN
        assertEquals( countBefore, propertyKeyCount( db ) );
        db.shutdown();
    }

    @Test
    public void concurrently_creating_same_property_key_in_different_transactions_should_end_up_with_same_key_id()
            throws Exception
    {
        // GIVEN
        GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabase();
        OtherThreadExecutor<WorkerState> worker1 = new OtherThreadExecutor<>( "w1", new WorkerState( db ) );
        OtherThreadExecutor<WorkerState> worker2 = new OtherThreadExecutor<>( "w2", new WorkerState( db ) );
        worker1.execute( new BeginTx() );
        worker2.execute( new BeginTx() );

        // WHEN
        String key = "mykey";
        worker1.execute( new CreateNodeAndSetProperty( key ) );
        worker2.execute( new CreateNodeAndSetProperty( key ) );
        worker1.execute( new FinishTx() );
        worker2.execute( new FinishTx() );
        worker1.close();
        worker2.close();

        // THEN
        assertEquals( 1, propertyKeyCount( db ) );
        db.shutdown();
    }

    @Rule
    public final PageCacheRule pageCacheRule = new PageCacheRule();
    @Rule
    public final TargetDirectory.TestDirectory testDirectory = TargetDirectory.testDirForTest( getClass() );
    private File storeDir;

    @Before
    public void setup()
    {
        storeDir  = testDirectory.graphDbDir();
    }

    private GraphDatabaseAPI database()
    {
        return (GraphDatabaseAPI) new TestGraphDatabaseFactory().newEmbeddedDatabase( storeDir.getAbsolutePath() );
    }

    private GraphDatabaseAPI databaseWithManyPropertyKeys( int propertyKeyCount ) throws IOException
    {
        DefaultFileSystemAbstraction fs = new DefaultFileSystemAbstraction();
        PageCache pageCache = pageCacheRule.getPageCache( fs );
        StoreFactory storeFactory = new StoreFactory( fs, storeDir, pageCache, NullLogProvider.getInstance() );
        NeoStores neoStores = storeFactory.openAllNeoStores( true );
        PropertyKeyTokenStore store = neoStores.getPropertyKeyTokenStore();
        for ( int i = 0; i < propertyKeyCount; i++ )
        {
            PropertyKeyTokenRecord record = new PropertyKeyTokenRecord( (int) store.nextId() );
            record.setInUse( true );
            Collection<DynamicRecord> nameRecords = store.allocateNameRecords( PropertyStore.encodeString( key( i ) ) );
            record.addNameRecords( nameRecords );
            record.setNameId( (int) first( nameRecords ).getId() );
            store.updateRecord( record );
        }
        neoStores.close();

        return database();
    }

    private String key( int i )
    {
        return "key" + i;
    }

    private Node createNodeWithProperty( GraphDatabaseService db, String key, Object value )
    {
        try ( Transaction tx = db.beginTx() )
        {
            Node node = db.createNode();
            node.setProperty( key, value );
            tx.success();
            return node;
        }
    }

    private int propertyKeyCount( GraphDatabaseAPI db )
    {
        return (int) db.getDependencyResolver().resolveDependency( NeoStoresSupplier.class ).get()
                .getPropertyKeyTokenStore().getHighId();
    }

    private static class WorkerState
    {
        protected final GraphDatabaseService db;
        protected Transaction tx;

        WorkerState( GraphDatabaseService db )
        {
            this.db = db;
        }
    }

    private static class BeginTx implements WorkerCommand<WorkerState, Void>
    {
        @Override
        public Void doWork( WorkerState state )
        {
            state.tx = state.db.beginTx();
            return null;
        }
    }

    private static class CreateNodeAndSetProperty implements WorkerCommand<WorkerState, Void>
    {
        private final String key;

        public CreateNodeAndSetProperty( String key )
        {
            this.key = key;
        }

        @Override
        public Void doWork( WorkerState state )
        {
            Node node = state.db.createNode();
            node.setProperty( key, true );
            return null;
        }
    }

    private static class FinishTx implements WorkerCommand<WorkerState, Void>
    {
        @Override
        public Void doWork( WorkerState state )
        {
            state.tx.success();
            state.tx.close();
            return null;
        }
    }
}


text:
package org.apache.nifi.controller;

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

import org.apache.nifi.annotation.configuration.DefaultSchedule;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.reporting.AbstractReportingTask;
import org.apache.nifi.reporting.ReportingContext;
import org.apache.nifi.scheduling.SchedulingStrategy;

/**
 * Dummy reporting task to test @DefaultSchedule annotation
 */
@DefaultSchedule(strategy = SchedulingStrategy.CRON_DRIVEN, period = "0 0 0 1/1 * ?")
public class DummyScheduledReportingTask extends AbstractReportingTask {

    public static final PropertyDescriptor TEST_WITH_DEFAULT_VALUE = new PropertyDescriptor.Builder()
        .name("Test with default value")
        .description("Test with default value")
        .required(true)
        .expressionLanguageSupported(true)
        .defaultValue("nifi")
        .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
        .build();

    public static final PropertyDescriptor TEST_WITHOUT_DEFAULT_VALUE = new PropertyDescriptor.Builder()
        .name("Test without default value")
        .description("Test without default value")
        .required(false)
        .expressionLanguageSupported(true)
        .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
        .build();

    @Override
    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
        final List<PropertyDescriptor> properties = new ArrayList<>(super.getSupportedPropertyDescriptors());
        properties.add(TEST_WITH_DEFAULT_VALUE);
        properties.add(TEST_WITHOUT_DEFAULT_VALUE);
        return properties;
    }

    @Override
    public void onTrigger(ReportingContext context) {

    }
}


text:
require "waigo/version"

module Waigo
  module_function

  NG_WORDS = File.readlines('lib/waigo/data/ngword.txt')

  def check(word)
    if NG_WORDS.grep(/#{word}/).length > 0
      check = true
    else
      check = false
    end

    return check
  end
end


text:
{% extends 'base.html' %}

{% block content %}

Beerography What are you drinking?

Beerography What are you drinking?

			<form role="form" method="post">

				<input type="text" class="form-control" name="beer-search" id="beer-search" placeholder="Beer">

			<button type="submit" class="btn btn-info center-block col-xs-3 col-md-3">Beer Me!</button>

	{% if beers is defined %}

		{% if beers|length != 0 %}

Search Results:   {{ beers|length }} results found

							Name
							Brewery
							Style

						{% for item in beers %}

							{{ item.beer.beer_name }}
							{{ item.brewery.brewery_name }}
							{{ item.beer.beer_style }}

						{% endfor %}

		{% else %}

Try searching for something!

		{% endif %}

	{% endif %}

			  Breweries Close to You

Brewery 1

Name

Brewery 2

Name

Brewery 3

Name

			  Similar Local Beers

Brewery 1

Name

Brewery 2

Name

Brewery 3

Name

			  Local Events

Brewery 1

Name

Brewery 2

Name

Brewery 3

Name

{% endblock %}


text:
<?php

namespace spec\IPFS\Annotation;

use IPFS\Annotation\Param;
use PhpSpec\ObjectBehavior;

class ParamSpec extends ObjectBehavior
{
    public function let()
    {
        $this->beConstructedWith('foo', 'bar', 'lol');
    }

    public function it_is_initializable()
    {
        $this->shouldHaveType(Param::class);
    }

    public function it_has_simple_getters()
    {
        $this->getName()->shouldBe('foo');
        $this->getDescription()->shouldBe('bar');
        $this->getDefault()->shouldBe('lol');
    }

    public function it_can_check_if_there_is_a_default_value()
    {
        $this->beConstructedWith('foo', 'bar');
        $this->hasDefault()->shouldBe(false);
        $this->getDefault()->shouldBe(null);
    }

    public function it_can_check_if_there_is_no_default_value()
    {
        $this->beConstructedWith('foo', 'bar', 'lol');
        $this->hasDefault()->shouldBe(true);
        $this->getDefault()->shouldBe('lol');
    }
}


text:
The blog used many tool/service,many thanks to:

* [Github](https://github.com/), all the data based on;
* [Git](https://git-scm.com/), blogs and code files version control system;
* [Jekyll](http://jekyllrb.com/), a static site generator;
* [Clean Blog Theme](https://github.com/IronSummitMedia/startbootstrap-clean-blog-jekyll), a theme by Start Bootstrap;
* [Markdown](https://daringfireball.net/projects/markdown/), a beautiful lightweight markup language.
* [DNSPod](https://www.dnspod.cn/), the DNS service provider who surport the domain name resolution;
* [Duoshuo](http://duoshuo.com/), a socialization comments plugin.
* [Google](http://google.com), the one who tell me how to make it.
* …

## Just write

Start writing now!


text:
local function find( _type )
    for _, name in ipairs( peripheral.getNames() ) do
        if peripheral.getType( name ) == _type then
            return name
        end
    end
end

local function round(num, places)
		if not num then
			return
		end

        num = tostring(num)
        local inc = false
        local decimal = string.find(num, "%.")
		if not decimal then
			return
		end
        if num:len() - decimal <= places then return tonumber(num) end --already rounded, nothing to do.
        local digit = tonumber(num:sub(decimal + places + 1))
        num = num:sub(1, decimal + places)
        if digit <= 4 then return tonumber(num) end --no incrementation needed, return truncated number
        local newNum = ""
        for i=num:len(), 1, -1 do
                digit = tonumber(num:sub(i))
                if digit == 9 then
                        if i > 1 then
                                newNum = "0"..newNum
                        else
                                newNum = "10"..newNum
                        end
                elseif digit == nil then
                        newNum = "."..newNum
                else
                        if i > 1 then
                                newNum = num:sub(1,i-1)..(digit + 1)..newNum
                        else
                                newNum = (digit + 1)..newNum
                        end
                        return tonumber(newNum) --No more 9s found, so we are done incrementing. Copy remaining digits, then return number.
                end
        end
        return tonumber(newNum)
end

function setMode(mode)
	if mode == "efficent" then
		contStrTarget = 30000000
		tmpTarget=5000
	elseif mode == "extreme" then
		contStrTarget = 5000000
	else
		mode = "balance"
		contStrTarget = 50000000
		tmpTarget=6250
	end
end

function initializeController()
	--set up reactor devices
	reactor = peripheral.wrap(find("draconic_reactor"))
	inputFluxGate = peripheral.wrap("flux_gate_0")
	outputFluxGate = peripheral.wrap("flux_gate_1")
	mon = peripheral.wrap(find("monitor"))
--	store = peripheral.wrap(find("draconic_rf_storage"))

	--set initial mode to balanced

	--placeholders need to be tweaked by experimenting with the reactor
	timestep = 100
	integral = 0

	--input controller parameters
	maxInputValue = 700000
	contStrTarget = 20000000

	inputKP = 0.0264
	inputKI = 0.3
	inputKD = 0.02
	intputScaleFactor = 1

	inputFluxGate.setSignalLowFlow(10000)

	--output controller parameters
	maxOutputValue = 1000000
	tmpTarget=6000
	outputKP = 25
	outputKI = 0.35
	outputKD = 1000
	outputScaleFactor = 1

	rInfo = reactor.getReactorInfo()
	genRate = rInfo["generationRate"]
	--initilize variables
	inputIntegral = 50000/inputKI
	inputDerivate = 0
	outputIntegral = genRate/outputKI
	outputDerivate = 0
	preInputError = 0
	preOutputError = 0
	outputValue = 0
end

function updateLine(y,text)
	-- start at specified line
	mon.setCursorPos(1,y)
	maxw, maxh = mon.getSize()

	for i = #text, maxw do
		text = text .. " "
	end
	mon.write(text)
end

function getInfo()
	--update reactor internal values
	rInfo = reactor.getReactorInfo()

	tmp = rInfo["temperature"]
	eSat = rInfo["energySaturation"]
	contStr = rInfo["fieldStrength"]
	contDrain = rInfo["fieldDrainRate"]
	genRate = rInfo["generationRate"]
	fConv = rInfo["fuelConversion"]
	fConvR = rInfo["fuelConversionRate"]
end

function formatDisplay()
	-- update display values
	rfCharge = eSat * 0.0000001
	fieldStr = contStr * 0.000001
	rfDisplay = genRate / 1000
	fuel = (fConv / 10368) *100

	-- update screen text without clearing
	updateLine(1,"Reactor temperature = " .. tmp)
	--updateLine(2,"Energy saturation = " .. round(rfCharge,2) .. "%")  		--TODO: when the reactor starts charging (and on other random times), this line throws an error: concatinating string with nil
	--updateLine(3,"Containtment strength = " .. round(fieldStr,2) .. "%") 		--TODO: when the reactor starts charging (and on other random times), this line throws an error: concatinating string with nil

	updateLine(4,"Fuel Used = " .. round(fuel,2) .. "%")
	updateLine(6,"RF production = " .. rfDisplay .. " RF/t")
	updateLine(7,"Containtment Strain = " .. contDrain .. " RF/t")
	updateLine(8,"Net = " ..(genRate - contDrain) .. " RF/t")
end

function regulateInput()
	-- Reactor startup
	if rInfo["status"] == "charging" then
		inputFluxGate.setSignalLowFlow(400000)
		return
	elseif rInfo["status"] == "charged" then
		reactor.activateReactor()
	end

	--sets the value of the input gate of the reactor.
	--call this function each time step to regulate the input level of the reactor
	inputError = contStrTarget - contStr
	inputIntegral = inputIntegral + (inputError * timestep/1000)
	if inputIntegral < 0 then
		inputIntegral = 0
	end
	inputDerivate = (inputError - preInputError) / (timestep/1000)

	--set the actual value on the flow gate
	inputValue = intputScaleFactor * ((inputKP * inputError) + (inputKI * inputIntegral) + (inputKD * inputDerivate))
	print("P-input: " .. (inputKP * inputError))
	print("I-Input: " .. (inputKI * inputIntegral))
	print("D-Input: " .. (inputKD * inputDerivate))
	print("Input: " .. inputValue)

	if inputValue < 0 then
		inputValue = 0
	elseif inputValue > maxInputValue then
		inputValue = maxInputValue
	end

	inputFluxGate.setSignalLowFlow(inputValue)
end

function regulateOutput()
	-- Reactor Heat up
	if tmp < 7500 and mode == "extreme" then
		outputFluxGate.setSignalLowFlow(maxOutputValue)
		return
	else
		--sets the value of the output gate of the reactor.
		--call this function each time step to regulate the output level of the reactor
		outputError = tmpTarget - tmp
		outputIntegral = outputIntegral + (outputError * timestep/1000)
		outputDerivate = (outputError - preOutputError) / (timestep/1000)

		--set the actual value on the flow gate
		outputValue = outputScaleFactor * ((outputKP * outputError) + (outputKI * outputIntegral) + (outputKD * outputDerivate))

		print("P-output: " .. (outputKP * outputError))
		print("I-output: " .. (outputKI * outputIntegral))
		print("D-output: " .. (outputKD * outputDerivate))
		print(tmp)
		print(tmpTarget)
		print("output: " .. outputValue)

		if outputValue < 0 then
			outputValue = 0
		elseif outputValue > maxOutputValue then
			outputValue = maxOutputValue
		end

		outputFluxGate.setSignalLowFlow(outputValue)

		--save the error for next cycle
		preOutputError = outputError
	end
end

function safety()
	eText = "Reactor Running"
	--checks all safety constraints of the controller
	if tmp > 7900 then
		eText = "Reactor too hot"
		reactor.stopReactor()
		stopped = true
	end

	if fuel >= 90 then
		eText = "Reactor needs to refuel"
		reactor.stopReactor()
		stopped = true
	end

	if tmp < 2000 and fuel <= 90 and rInfo["status"] == "offline" then
		reactor.chargeReactor()
		eText = "Charging reactor"
	end

	updateLine(10, eText)
end

function run()
	-- Set initil values
	initializeController()
	-- Set Balanced mode
	--setMode("balanced")
	while true do
		-- debug
		term.clear()
		term.setCursorPos(1,1)

		getInfo()
		regulateInput()
		regulateOutput()
		formatDisplay()
		safety()
		sleep(timestep / 1000)
	end
end

-- Run program loop
run()


text:
<?php

namespace PHPixie\Validate\Errors\Error;

/**
 * Class Filter
 * @package PHPixie\Validate\Errors\Error
 */
class Filter extends \PHPixie\Validate\Errors\Error
{
    /**
     * @var string
     */
    protected $filter;
    /**
     * @var array
     */
    protected $parameters;

    /**
     * Filter constructor.
     * @param $filter string
     * @param array $parameters
     */
    public function __construct($filter, $parameters = array())
    {
        $this->filter     = $filter;
        $this->parameters = $parameters;
    }

    /**
     * @return string
     */
    public function type()
    {
        return 'filter';
    }

    /**
     * @return string
     */
    public function filter()
    {
        return $this->filter;
    }

    /**
     * @return array
     */
    public function parameters()
    {
        return $this->parameters;
    }

    /**
     * @return string
     */
    public function asString()
    {
        return "Value did not pass filter '{$this->filter}'";
    }
}


text:
#!/bin/bash
# Copyright 2012 AMG.lab, a Bull Group Company
#
# 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.

# ---------------------------------------------------------------------------
# HPC script that can be called to list content of specifed path
#
# History:
# - December 14, 2012 - Piotr Kulasek-Szwed (AMG.net, a Bull group company) - creation
# ---------------------------------------------------------------------------

#
#       global configuration
#
CONFIGURATION_PROPERTIES=/etc/hpc/hpc-scripts.properties

if [ -r $CONFIGURATION_PROPERTIES ]; then
  . $CONFIGURATION_PROPERTIES
else
  echo "ERROR: Could not find $CONFIGURATION_PROPERTIES or user does not have permission to read. Exiting." >&2
  exit 1
fi

#
#       external functions
#
if [ -r $FUNCTIONS_LOCATION ]; then
  . $FUNCTIONS_LOCATION
else
  echo "ERROR: Could not find $FUNCTIONS_LOCATION or user does not have permission to read. Exiting." >&2
  exit 1
fi

# --------------
# Usage function
# --------------

DIR_PATH=`pwd`

scriptName=`basename $0`

usage()
{
    echo ""
    echo "Usage: $scriptName [ -a ] [ -d | -f | -c | -df | -fd ] [ -ss ] [ -sr ] [-l <INTEGER> ] [-s <INTEGER> ] [ -p <PATH> ]"
    echo ""
    echo "Without arguments script return detailed information for current directoty. Possible options:"
    echo ""
    echo "  -h, --help              This help"
    echo "  -p, --path <PATH>       Path to get directory detailed information"
    echo "  -a, --all               Return all files and directories (hidden included)"
    echo "  -d, --directories       Return only directories"
    echo "  -f, --files             Return only files"
    echo "  -c, --currentFile       Return current file or directory"
    echo "  -l, --limit             Limits totalAmount of results. 0 describes infinity. Must be positive integer."
    echo "  -s, --skip              Skips first N results. Must be positive integer or 0."
    echo "  -sr, --sortReverse      Reverse default sorting."
    echo "  -ss, --sortSize         Instead of by name sorts by size of file."
    echo ""
    exit 1
}

# -----------------------------------------------
# Parsing script arguments
# -----------------------------------------------

localDir=`pwd`

while [ -n "$1" ]; do
  case "$1" in
    -h|--help)        usage;;
    -p|--path)        shift; DIR_PATH="$1";shift; ;;
    -a|--all)         shift; ALL=" -a " ;;
    -d|--directories) shift; LS_PARAMETER=" | grep ^d" ;;
    -f|--files)       shift; LS_PARAMETER=" | grep ^-" ;;
    -c|--currentFile)  shift; LS_PARAMETER=" -d" ;;
    -l|--limit)           shift; LS_LIMIT=$1; shift; ;;
    -s|--skip)            shift; LS_SKIP=$1; shift; ;;
    -sr|--sortReverse)shift; LS_SORT_PARAMETER="r$LS_SORT_PARAMETER" ;;
    -ss|--sortSize)   shift; LS_SORT_PARAMETER="S$LS_SORT_PARAMETER" ;;
    *) echo ""; echo "Command line option [$1] is invalid.";
       echo "Valid options are:"; usage; break;;
  esac
done

if [ ! -e "$DIR_PATH" ]; then
        exit_with_error "No such file or directory." 1
fi

DIR_PATH_TO_DISPLAY=`echo  "$DIR_PATH" | sed 's/[/]*$//'` #Remove '/' at the end of string if exists
DIR_PATH=`echo  "$DIR_PATH" | sed 's/[/]*$//'` #Remove '/' at the end of string if exists

if [[ $foo == *[!0-9]* ]]; then
    exit_with_error "Limit must be an integer > 0." 1
fi

if [ "x$LS_SKIP" != "x" ] && [ $LS_SKIP -ge 0 ]; then
        LS_SKIP=$((LS_SKIP + 1))
        LS_PAGER_PARAM="$LS_PAGER_PARAM | tail -n +$LS_SKIP"
fi

if [ "x$LS_LIMIT" != "x" ] && [ $LS_LIMIT -gt 0 ]; then
        LS_PAGER_PARAM="$LS_PAGER_PARAM | head -$LS_LIMIT"
fi

if [ "x$LS_SORT_PARAMETER" != "x" ]; then
        LS_SORT_PARAMETER="-$LS_SORT_PARAMETER"
fi

# ------------------------------------------------------
# Declaration of functions
# ------------------------------------------------------

lx() {
	\ls -QlL1 --full-time "$@" | grep ^d | cat;
	AMOUNT=2
	if [ "$LS_PARAMETER" = " -d" ]; then
		AMOUNT=1
	fi
        \ls -QlL1 --full-time "$@" | grep -v '^d' | cat | tail -n +$AMOUNT;

}

#-----------------------------
# Script body
#-----------------------------

set +e
totalAmount=`eval "lx \"$DIR_PATH\" $LS_SORT_PARAMETER $ALL $LS_PARAMETER" | wc -l`
buffer=`eval "lx \"$DIR_PATH\" $LS_SORT_PARAMETER $ALL $LS_PARAMETER" $LS_PAGER_PARAM`
amount=`echo "$buffer" | wc -l`
set -e

echo -e "{\"dirInfo\":"
echo -e "\t{"
echo -ne "\t\t\"path\":\""; echo -n "`toJsonValue \"$DIR_PATH_TO_DISPLAY\"`"; echo -e "\","
echo -e "\t\t\"children\":\"$totalAmount\","
echo -e "\t\t\"files\":["

counter=0
echo "$buffer" | while read -r line; do
AMOUNT_OF_FILEDS=`echo $line | awk '{print NF}'`
if [ $AMOUNT_OF_FILEDS -ge 9 ]; then
	counter=$(($counter + 1))
	name=`echo "$line" | sed 's/\\\"/quot;/g' | sed 's/quot;$/\"/g' | awk 'BEGIN { FS = "\""; OFS = "";} {$1="" ;print $0}' | sed 's/quot;/\"/g'`
	if [ "$LS_PARAMETER" = " -d" ]; then
		filePath="${DIR_PATH_TO_DISPLAY%/*}"
		name=${name#$filePath/}
	else
		filePath="$DIR_PATH_TO_DISPLAY"
	fi
	date=`echo $line | awk '{print $6}' | sed  "s/-/\./g"`
	ttime=`echo $line | awk '{print $7}' | sed "s/\..*//g"`
	permisions=`echo $line | awk '{print $1}'`

	if [ ${permisions:0:1} = "-" ]; then
		fileType="FILE_TYPE"
	elif [ ${permisions:0:1} = "d" ]; then
		fileType="DIRECTORY_TYPE"
	elif [ ${permisions:0:1} = "l" ]; then
		fileType="SOFTLINK_TYPE"
	elif [ ${permisions:0:1} = "c" ] || [ ${permisions:0:1} = "b" ]; then
		fileType="DEVICE_TYPE"
	else
		fileType="UNKNOWN_TYPE"
	fi

	size=`echo $line | awk '{print $5}'`
	echo -ne "\t\t\t{\"name\":\""; echo -n "`toJsonValue \"$name\"`"; echo -e "\","
	echo -ne "\t\t\t \"path\":\""; echo -n "`toJsonValue \"$filePath\"`"; echo -e "\","
	echo -e "\t\t\t \"date\":\"$date-$ttime\","
	echo -e "\t\t\t \"type\":\"$fileType\","
	echo -e "\t\t\t \"size\":\"$size\""
	if [ "$counter" != "$amount" ]; then
		echo -e "\t\t\t},"
	else
		echo -e "\t\t\t}"
	fi
else
	amount=$((amount - 1))
fi
done

echo -e "\t\t]"
echo -e "\t}"
echo "}"


text:
'use strict';

var index = require('./controllers'),
    users = require('./controllers/users'),
    session = require('./controllers/session');

var middleware = require('./middleware');

/**
 * Application routes
 */
module.exports = function (app) {

    // Server API Routes
    app.post('/api/users', users.create);
    app.put('/api/users', users.changePassword);
    app.get('/api/users/me', users.me);
    app.get('/api/users/:id', users.show);

    app.post('/api/session', session.login);
    app.del('/api/session', session.logout);

    // All other routes to use Angular routing in app/scripts/app.js
    app.get('/partials/*', index.partials);
    app.get('/*', middleware.setUserCookie, index.index);
};