text:
package main

import (
	"io/ioutil"
	"regexp"
	"strconv"
	"strings"
)

type Reindeer struct {
	speed, duration, rest, distance int
	points, restingTime, flyingTime int
}

func (r *Reindeer) tick() {
	if r.restingTime > 0 {
		r.restingTime--
	} else {
		r.flyingTime++
		r.distance += r.speed
	}

	if r.flyingTime == r.duration {
		r.flyingTime = 0
		r.restingTime = r.rest
	}
}

func (r *Reindeer) race(seconds int) {
	for seconds > 0 {
		if seconds < r.duration {
			r.distance += r.speed * seconds
		} else {
			r.distance += r.speed * r.duration
		}
		seconds -= r.duration
		seconds -= r.rest
	}
}

func main() {
	input, err := ioutil.ReadFile("./day-14-input.txt")
	if err != nil {
		panic(err)
	}

	descriptions := strings.Split(string(input), "\n")
	reindeers := []*Reindeer{}

	regex := regexp.MustCompile("(\\d+) km/s.* (\\d+) seconds.* (\\d+)")

	seconds := 2503

	for _, description := range descriptions {
		matches := regex.FindStringSubmatch(description)[1:]

		speed, _ := strconv.Atoi(matches[0])
		duration, _ := strconv.Atoi(matches[1])
		rest, _ := strconv.Atoi(matches[2])

		reindeer := Reindeer{speed: speed, duration: duration, rest: rest}
		reindeers = append(reindeers, &reindeer)
	}

	for s := 0; s < seconds; s++ {
		maximumDistance := 0
		for _, reindeer := range reindeers {
			reindeer.tick()
			if reindeer.distance > maximumDistance {
				maximumDistance = reindeer.distance
			}
		}

		for _, reindeer := range reindeers {
			if reindeer.distance == maximumDistance {
				reindeer.points++
			}
		}
	}

	maximumPoints := -1
	for _, reindeer := range reindeers {
		if reindeer.points > maximumPoints {
			maximumPoints = reindeer.points
		}
	}

	println(maximumPoints)
}

redpajama_set_name: RedPajamaGithub


text:
namespace keys = extension_management_api_constants;
namespace util = extension_function_test_utils;

namespace extensions {

class ExtensionManagementApiBrowserTest : public ExtensionBrowserTest {
 protected:
  bool CrashEnabledExtension(const std::string& extension_id) {
    ExtensionHost* background_host =
        ProcessManager::Get(browser()->profile())
            ->GetBackgroundHostForExtension(extension_id);
    if (!background_host)
      return false;
    content::CrashTab(background_host->host_contents());
    return true;
  }
};

// We test this here instead of in an ExtensionApiTest because normal extensions
// are not allowed to call the install function.
IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, InstallEvent) {
  ExtensionTestMessageListener listener1("ready", false);
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("management/install_event")));
  ASSERT_TRUE(listener1.WaitUntilSatisfied());

  ExtensionTestMessageListener listener2("got_event", false);
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("api_test/management/enabled_extension")));
  ASSERT_TRUE(listener2.WaitUntilSatisfied());
}

IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, LaunchApp) {
  ExtensionTestMessageListener listener1("app_launched", false);
  ExtensionTestMessageListener listener2("got_expected_error", false);
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("management/simple_extension")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("management/packaged_app")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("management/launch_app")));
  ASSERT_TRUE(listener1.WaitUntilSatisfied());
  ASSERT_TRUE(listener2.WaitUntilSatisfied());
}

IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest,
                       LaunchAppFromBackground) {
  ExtensionTestMessageListener listener1("success", false);
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("management/packaged_app")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("management/launch_app_from_background")));
  ASSERT_TRUE(listener1.WaitUntilSatisfied());
}

IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest,
                       SelfUninstall) {
  ExtensionTestMessageListener listener1("success", false);
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("management/self_uninstall_helper")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("management/self_uninstall")));
  ASSERT_TRUE(listener1.WaitUntilSatisfied());
}

IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest,
                       SelfUninstallNoPermissions) {
  ExtensionTestMessageListener listener1("success", false);
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("management/self_uninstall_helper")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("management/self_uninstall_noperm")));
  ASSERT_TRUE(listener1.WaitUntilSatisfied());
}

IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest,
                       GetSelfNoPermissions) {
  ExtensionTestMessageListener listener1("success", false);
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("management/get_self")));
  ASSERT_TRUE(listener1.WaitUntilSatisfied());
}

IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest,
                       UninstallWithConfirmDialog) {
  ExtensionService* service = ExtensionSystem::Get(browser()->profile())->
      extension_service();

  // Install an extension.
  const Extension* extension = InstallExtension(
      test_data_dir_.AppendASCII("api_test/management/enabled_extension"), 1);
  ASSERT_TRUE(extension);

  const std::string id = extension->id();

  scoped_refptr<Extension> empty_extension(test_util::CreateEmptyExtension());
  // Uninstall, then cancel via the confirm dialog.
  scoped_refptr<ManagementUninstallFunction> uninstall_function(
      new ManagementUninstallFunction());
  uninstall_function->set_extension(empty_extension.get());
  uninstall_function->set_user_gesture(true);
  ManagementUninstallFunction::SetAutoConfirmForTest(false);

  EXPECT_TRUE(MatchPattern(
      util::RunFunctionAndReturnError(
          uninstall_function.get(),
          base::StringPrintf("[\"%s\", {\"showConfirmDialog\": true}]",
                             id.c_str()),
          browser()),
      keys::kUninstallCanceledError));

  // Make sure the extension wasn't uninstalled.
  EXPECT_TRUE(service->GetExtensionById(id, false) != NULL);

  // Uninstall, then accept via the confirm dialog.
  uninstall_function = new ManagementUninstallFunction();
  uninstall_function->set_extension(empty_extension.get());
  ManagementUninstallFunction::SetAutoConfirmForTest(true);
  uninstall_function->set_user_gesture(true);
  util::RunFunctionAndReturnSingleResult(
      uninstall_function.get(),
      base::StringPrintf("[\"%s\", {\"showConfirmDialog\": true}]", id.c_str()),
      browser());

  // Make sure the extension was uninstalled.
  EXPECT_TRUE(service->GetExtensionById(id, false) == NULL);
}

IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest,
                       CreateAppShortcutConfirmDialog) {
  const Extension* app = InstallExtension(
      test_data_dir_.AppendASCII("api_test/management/packaged_app"), 1);
  ASSERT_TRUE(app);

  const std::string app_id = app->id();

  scoped_refptr<ManagementCreateAppShortcutFunction> create_shortcut_function(
      new ManagementCreateAppShortcutFunction());
  create_shortcut_function->set_user_gesture(true);
  ManagementCreateAppShortcutFunction::SetAutoConfirmForTest(true);
  util::RunFunctionAndReturnSingleResult(
      create_shortcut_function.get(),
      base::StringPrintf("[\"%s\"]", app_id.c_str()),
      browser());

  create_shortcut_function = new ManagementCreateAppShortcutFunction();
  create_shortcut_function->set_user_gesture(true);
  ManagementCreateAppShortcutFunction::SetAutoConfirmForTest(false);
  EXPECT_TRUE(MatchPattern(
      util::RunFunctionAndReturnError(
          create_shortcut_function.get(),
          base::StringPrintf("[\"%s\"]", app_id.c_str()),
          browser()),
      keys::kCreateShortcutCanceledError));
}

IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest,
                       GetAllIncludesTerminated) {
  // Load an extension with a background page, so that we know it has a process
  // running.
  ExtensionTestMessageListener listener("ready", false);
  const Extension* extension = LoadExtension(
      test_data_dir_.AppendASCII("management/install_event"));
  ASSERT_TRUE(extension);
  ASSERT_TRUE(listener.WaitUntilSatisfied());

  // The management API should list this extension.
  scoped_refptr<ManagementGetAllFunction> function =
      new ManagementGetAllFunction();
  scoped_ptr<base::Value> result(util::RunFunctionAndReturnSingleResult(
      function.get(), "[]", browser()));
  base::ListValue* list;
  ASSERT_TRUE(result->GetAsList(&list));
  EXPECT_EQ(1U, list->GetSize());

  // And it should continue to do so even after it crashes.
  ASSERT_TRUE(CrashEnabledExtension(extension->id()));

  function = new ManagementGetAllFunction();
  result.reset(util::RunFunctionAndReturnSingleResult(
      function.get(), "[]", browser()));
  ASSERT_TRUE(result->GetAsList(&list));
  EXPECT_EQ(1U, list->GetSize());
}

class ExtensionManagementApiEscalationTest :
    public ExtensionManagementApiBrowserTest {
 protected:
  // The id of the permissions escalation test extension we use.
  static const char kId[];

  void SetUpOnMainThread() override {
    EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());
    base::FilePath pem_path = test_data_dir_.
        AppendASCII("permissions_increase").AppendASCII("permissions.pem");
    base::FilePath path_v1 = PackExtensionWithOptions(
        test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v1"),
        scoped_temp_dir_.path().AppendASCII("permissions1.crx"),
        pem_path,
        base::FilePath());
    base::FilePath path_v2 = PackExtensionWithOptions(
        test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v2"),
        scoped_temp_dir_.path().AppendASCII("permissions2.crx"),
        pem_path,
        base::FilePath());

    ExtensionService* service = ExtensionSystem::Get(browser()->profile())->
        extension_service();

    // Install low-permission version of the extension.
    ASSERT_TRUE(InstallExtension(path_v1, 1));
    EXPECT_TRUE(service->GetExtensionById(kId, false) != NULL);

    // Update to a high-permission version - it should get disabled.
    EXPECT_FALSE(UpdateExtension(kId, path_v2, -1));
    EXPECT_TRUE(service->GetExtensionById(kId, false) == NULL);
    EXPECT_TRUE(service->GetExtensionById(kId, true) != NULL);
    EXPECT_TRUE(ExtensionPrefs::Get(browser()->profile())
                    ->DidExtensionEscalatePermissions(kId));
  }

  void SetEnabled(bool enabled, bool user_gesture,
                  const std::string& expected_error) {
    scoped_refptr<ManagementSetEnabledFunction> function(
        new ManagementSetEnabledFunction);
    const char* const enabled_string = enabled ? "true" : "false";
    if (user_gesture)
      function->set_user_gesture(true);
    function->SetRenderViewHost(browser()->tab_strip_model()->
        GetActiveWebContents()->GetRenderViewHost());
    bool response = util::RunFunction(
        function.get(),
        base::StringPrintf("[\"%s\", %s]", kId, enabled_string),
        browser(),
        util::NONE);
    if (expected_error.empty()) {
      EXPECT_EQ(true, response);
    } else {
      EXPECT_TRUE(response == false);
      EXPECT_EQ(expected_error, function->GetError());
    }
  }

 private:
  base::ScopedTempDir scoped_temp_dir_;
};

const char ExtensionManagementApiEscalationTest::kId[] =
    "pgdpcfcocojkjfbgpiianjngphoopgmo";

IN_PROC_BROWSER_TEST_F(ExtensionManagementApiEscalationTest,
                       DisabledReason) {
  scoped_refptr<ManagementGetFunction> function =
      new ManagementGetFunction();
  scoped_ptr<base::Value> result(util::RunFunctionAndReturnSingleResult(
      function.get(),
      base::StringPrintf("[\"%s\"]", kId),
      browser()));
  ASSERT_TRUE(result.get() != NULL);
  ASSERT_TRUE(result->IsType(base::Value::TYPE_DICTIONARY));
  base::DictionaryValue* dict =
      static_cast<base::DictionaryValue*>(result.get());
  std::string reason;
  EXPECT_TRUE(dict->GetStringASCII(keys::kDisabledReasonKey, &reason));
  EXPECT_EQ(reason, std::string(keys::kDisabledReasonPermissionsIncrease));
}

IN_PROC_BROWSER_TEST_F(ExtensionManagementApiEscalationTest,
                       SetEnabled) {
  // Expect an error about no gesture.
  SetEnabled(true, false, keys::kGestureNeededForEscalationError);

  // Expect an error that user cancelled the dialog.
  ExtensionInstallPrompt::g_auto_confirm_for_tests =
      ExtensionInstallPrompt::CANCEL;
  SetEnabled(true, true, keys::kUserDidNotReEnableError);

  // This should succeed when user accepts dialog.  We must wait for the process
  // to connect *and* for the channel to finish initializing before trying to
  // crash it.  (NOTIFICATION_RENDERER_PROCESS_CREATED does not wait for the
  // latter and can cause KillProcess to fail on Windows.)
  content::WindowedNotificationObserver observer(
      extensions::NOTIFICATION_EXTENSION_HOST_CREATED,
      content::NotificationService::AllSources());
  ExtensionInstallPrompt::g_auto_confirm_for_tests =
      ExtensionInstallPrompt::ACCEPT;
  SetEnabled(true, true, std::string());
  observer.Wait();

  // Crash the extension. Mock a reload by disabling and then enabling. The
  // extension should be reloaded and enabled.
  ASSERT_TRUE(CrashEnabledExtension(kId));
  SetEnabled(false, true, std::string());
  SetEnabled(true, true, std::string());
  const Extension* extension = ExtensionSystem::Get(browser()->profile())
      ->extension_service()->GetExtensionById(kId, false);
  EXPECT_TRUE(extension);
}

}  // namespace extensions


text:
/**
 * BlogController for Server-side logic to managing Blog posts
 *
 * @module BlogController
 * @see http://sailsjs.org/#!/documentation/concepts/Controllers
 */

/**
 * Setup Blog Posts
 *
 * @param {!object} req - Request
 * @param {!object} res - responses
 * @param {function} next
 */
var setup = function (req, res, next) {
  MultisiteService.getCurrentSiteConfig(req.session.uri.host, function (err, config) {
    SetupService.generateBlog(config.name, function(err, result) {
      if(err) { return res.serverError(err); }
      res.json(result);
    });
  });
};

/**
 * Create a Blog Post
 *
 * @param {!object} req - Request
 * @param {!object} res - responses
 * @param {function} next
 */
var create = function (req, res, next) {
  MultisiteService.getCurrentSiteConfig(req.session.uri.host, function (err, config) {
    if(err) { return res.serverError(err); }
    var data = req.params.all();
    data.site = config.name;
    Blog.create(data).exec(function create(err, created){
      // Blog.publisCreate(created[0].id, created[0]);
      sails.log.info("created", created);
      res.json(created);
    });
  });
};

/**
 * Update a Blog Post
 *
 * @param {!object} req - Request
 * @param {!object} res - responses
 * @param {function} next
 */
var update = function (req, res, next) {
  MultisiteService.getCurrentSiteConfig(req.session.uri.host, function (err, config) {
    if(err) { return res.serverError(err); }
    var id = req.param('id');
    var data = req.params.all();
    data.site = config.name;
    Blog.update({id:id, site:config.name},data).exec(function update(err, updated){
      // Blog.publishUpdate(updated[0].id, updated[0]);
      sails.log.info("updated", updated);
      res.json(updated);
    });
  });
};

/**
 * Upload a file for a Blog Post
 *
 * @param {!object} req - Request
 * @param {!object} res - responses
 * @param {function} next
 */
var upload = function (req, res) {
  FileService.upload(req, sails.config.paths.blog, function (err, result) {
    sails.log.debug("[BlogController.upload] finish", err, result);
    if(err) return res.serverError(err);
    res.json(result);
  });
};

/**
 * Find Blog posts for the current site and if set of the page
 *
 * @param {!object} req - Request
 * @param {!object} res - responses
 * @param {function} next
 */
var find = function (req, res) {
  var page = req.param('page');
  var limit = req.param('limit');
  var skip = req.param('skip');
  BlogService.find(req.session.uri.host, page, limit, skip, function (err, results, status, config) {
    if(err) return res.serverError(err);
    sails.log.debug("[BlogController.find]", status, result);
    switch(status.code) {
      case 200: return res.json(results);
      case 400: return res.badRequest();
      case 403: return res.forbidden();
      case 404: return res.notFound();
      case 500: return res.serverError(status.error);
      default: return res.serverError("Unknown Error");
    }
  });
}

/**
 * Get the number of blog posts for site and page
 *
 * @param {!object} req - Request
 * @param {!object} res - responses
 * @param {function} next
 */
var count = function (req, res) {
  var page = req.param('page');
  BlogService.count(req.session.uri.host, page, function (err, count, status, config) {
    if(err) return res.serverError(err);
    sails.log.debug("[BlogController.count]", count);
    switch(status.code) {
      case 200: return res.json({count:count});
      case 400: return res.badRequest();
      case 403: return res.forbidden();
      case 404: return res.notFound();
      case 500: return res.serverError(status.error);
      default: return res.serverError("Unknown Error");
    }
  });
}

/**
 * Destroy / delete a Blog Post by id
 *
 * @param {!object} req - Request
 * @param {!object} res - responses
 * @param {function} next
 */
var destroy = function (req, res, next) {
  MultisiteService.getCurrentSiteConfig(req.session.uri.host, function (err, config) {
    if(err) return res.serverError(err);
    var id = req.param('id');
    var site = config.name;
    // TODO delete all attachments!!
    Blog.destroy({id:id, site:site}).exec(function create(err, destroyed){
      // Blog.publisCreate(destroyed[0].id, destroyed[0]);
      sails.log.info("destroyed", destroyed);
      res.json(destroyed);
    });
  });
};

/**
 * delete attachment found by blog post id and attachmentUploadedAs string
 *
 * @param {!object} req - Request
 * @param {!object} res - responses
 * @param {function} next
 */
var destroyAttachment = function (req, res, next) {
  var id = req.param('blogPostID') || req.param('id');
  var attachmentUploadedAs = req.param('attachmentUploadedAs');
  sails.log.debug("[BlogController.destroyAttachment]", id, attachmentUploadedAs);
  BlogService.findAttachmentInPost(req.session.uri.host, id, attachmentUploadedAs, function (err, index, attachment, status, config) {
    if(err || status.code !== 200) {
      sails.log.error(status);
      return res.serverError(err);
    }
    if(index <= -1) {
      sails.log.warn("[BlogController.destroyAttachment] Attachment not found");
      return res.ok();
    }
    sails.log.debug("[BlogController.destroyAttachment] Found attachment", attachment)
    FileService.removeFromFilesystem(config.name, attachment, sails.config.paths.blog, function (err) {
      if(err) { return res.serverError(err); }
      return res.ok();
    });
  });

}

/**
 * public api functions
 */
module.exports = {
  setup: setup,
  create: create,
  update: update,
  upload: upload,
  find: find,
  findAll: find, // alias
  count: count,
  destroy: destroy,
  destroyAttachment: destroyAttachment
}


text:
using namespace clang;
using namespace llvm;

namespace seec {

namespace seec_clang {

//===----------------------------------------------------------------------===//
// class Mapper
//===----------------------------------------------------------------------===//

/// \brief Visit an AST and construct mapping information.
///
class MappingASTVisitor : public RecursiveASTVisitor<MappingASTVisitor> {
  typedef MappedAST::ASTNodeTy ASTNodeTy;

  /// The AST that we are visiting.
  clang::ASTUnit &AST;

  /// The SourceManager for this AST.
  clang::SourceManager &SourceManager;

  /// All Decls in visitation order.
  std::vector<Decl const *> Decls;

  /// All Stmts in visitation order.
  std::vector<Stmt const *> Stmts;

  /// All Decls seen.
  llvm::DenseSet<Decl const *> DeclsSeen;

  /// All Stmts seen.
  llvm::DenseSet<Stmt const *> StmtsSeen;

  /// All Decls that are referred to by non-system code.
  llvm::DenseSet<clang::Decl const *> DeclsReferenced;

  /// All VariableArrayType types in visitation order.
  std::vector<::clang::VariableArrayType *> VATypes;

public:
  /// \brief Constructor.
  ///
  MappingASTVisitor(clang::ASTUnit &ForAST)
  : AST(ForAST),
    SourceManager(ForAST.getSourceManager()),
    Decls(),
    Stmts(),
    DeclsSeen(),
    StmtsSeen(),
    DeclsReferenced(),
    VATypes()
  {}

  /// \name Accessors.
  /// @{

  /// Get all Decls in visitation order.
  decltype(Decls) &getDecls() { return Decls; }

  /// Get all Stmts in visitation order.
  decltype(Stmts) &getStmts() { return Stmts; }

  /// Get all Decls that are referenced by non-system code.
  decltype(DeclsReferenced) &getDeclsReferenced() { return DeclsReferenced; }

  /// @}

  /// \name Mutators.
  /// @{

  /// \brief Revisits VariableArrayType's size expressions.
  ///
  void revisitVariableArrayTypeSizeExprs() {
    for (auto const VAType : VATypes)
      TraverseStmt(VAType->getSizeExpr());
  }

  /// @}

  /// \name RecursiveASTVisitor Methods
  /// @{

  /// \brief Return whether \param S should be traversed using data recursion
  /// to avoid a stack overflow with extreme cases.
  ///
  bool shouldUseDataRecursionFor(Stmt *S) const {
    return false;
  }

  /// \brief Visit a Decl.
  ///
  bool VisitDecl(::clang::Decl *D) {
    if (DeclsSeen.insert(D).second)
      Decls.push_back(D);
    return true;
  }

  /// \brief Visit a Stmt.
  ///
  bool VisitStmt(::clang::Stmt *S) {
    if (StmtsSeen.insert(S).second)
      Stmts.push_back(S);
    return true;
  }

  /// \brief Visit a DeclRefExpr.
  ///
  bool VisitDeclRefExpr(::clang::DeclRefExpr *DR) {
    if (DR && !SourceManager.isInSystemHeader(DR->getLocation())) {
      if (auto const TheDecl = DR->getDecl()) {
        auto const Canon = TheDecl->getCanonicalDecl();
        DeclsReferenced.insert(Canon);
      }
    }

    return true;
  }

  /// \brief Visit a VariableArrayType.
  ///
  bool VisitVariableArrayType(::clang::VariableArrayType *T) {
    VATypes.push_back(T);
    return true;
  }

  /// \brief Print Decl kinds and Stmt classes in visitation order.
  ///
  void printInVisitationOrder(clang::SourceManager &SM) const
  {
    llvm::errs() << "decls:\n";
    unsigned Index = 0;
    for (auto const D : Decls) {
      auto const Loc = D->getLocation();
      llvm::errs() << "  " << '[' << Index++ << "] "
                  << D->getDeclKindName()
                  << " (" << SM.getFilename(Loc)
                  << ":" << SM.getSpellingLineNumber(Loc) << ")\n";
    }

    llvm::errs() << "stmts:\n";
    Index = 0;
    for (auto const S : Stmts) {
      auto const Loc = S->getLocStart();
      llvm::errs() << "  " << '[' << Index++ << "] "
                  << S->getStmtClassName()
                  << " (" << SM.getFilename(Loc)
                  << ":" << SM.getSpellingLineNumber(Loc) << ")\n";
    }
  }

  /// @}
};

//===----------------------------------------------------------------------===//
// class MappedAST
//===----------------------------------------------------------------------===//

MappedAST::MappedAST(MappedCompileInfo const &FromCompileInfo,
                     clang::ASTUnit *ForAST,
                     MappingASTVisitor WithMapping)
: CompileInfo(FromCompileInfo),
  AST(ForAST),
  Decls(std::move(WithMapping.getDecls())),
  Stmts(std::move(WithMapping.getStmts())),
  DeclsReferenced(std::move(WithMapping.getDeclsReferenced()))
{}

MappedAST::~MappedAST() {
  delete AST;
}

std::unique_ptr<MappedAST>
MappedAST::FromASTUnit(MappedCompileInfo const &FromCompileInfo,
                       clang::ASTUnit *AST)
{
  if (!AST)
    return nullptr;

  MappingASTVisitor Mapper {*AST};

  Mapper.TraverseDecl(AST->getASTContext().getTranslationUnitDecl());
  Mapper.revisitVariableArrayTypeSizeExprs();

#if defined(SEEC_DEBUG_NODE_MAPPING)
  Mapper.printInVisitationOrder(AST->getSourceManager());
#endif

  auto Mapped = std::unique_ptr<MappedAST>(new MappedAST(FromCompileInfo,
                                                         AST,
                                                         std::move(Mapper)));
  if (!Mapped)
    delete AST;

  return Mapped;
}

seec::Maybe<uint64_t> MappedAST::getIdxForDecl(clang::Decl const *Decl) const
{
  auto const It = std::find(Decls.begin(), Decls.end(), Decl);
  uint64_t const Idx = It != Decls.end() ? std::distance(Decls.begin(), It) : 0;
  return Idx;
}

seec::Maybe<uint64_t> MappedAST::getIdxForStmt(clang::Stmt const *Stmt) const
{
  auto const It = std::find(Stmts.begin(), Stmts.end(), Stmt);
  uint64_t const Idx = It != Stmts.end() ? std::distance(Stmts.begin(), It) : 0;
  return Idx;
}

bool MappedAST::contains(::clang::Decl const *Decl) const
{
  return &(Decl->getASTContext()) == &(AST->getASTContext());
}

bool MappedAST::contains(::clang::Stmt const *Stmt) const {
  for (auto const S : Stmts)
    if (S == Stmt)
      return true;
  return false;
}

static MappedAST::ASTNodeTy
getFirstParent(clang::ASTContext::DynTypedNodeList const &Parents)
{
  if (!Parents.empty()) {
    auto const &Parent = Parents[0];

    if (auto const ParentDecl = Parent.get<clang::Decl>())
      return ParentDecl;
    else if (auto const ParentStmt = Parent.get<clang::Stmt>())
      return ParentStmt;
  }

  return MappedAST::ASTNodeTy();
}

MappedAST::ASTNodeTy MappedAST::getParent(clang::Decl const *D) const
{
  return getFirstParent(AST->getASTContext().getParents(*D));
}

MappedAST::ASTNodeTy MappedAST::getParent(clang::Stmt const *S) const
{
  return getFirstParent(AST->getASTContext().getParents(*S));
}

bool MappedAST::isParent(::clang::Decl const *Parent,
                         ::clang::Decl const *Child) const
{
  auto const DP = getParent(Child);

  if (DP.assigned<clang::Decl const *>()) {
    auto const DPDecl = DP.get<clang::Decl const *>();
    return DPDecl == Parent ? true : isParent(Parent, DPDecl);
  }
  else if (DP.assigned<clang::Stmt const *>()) {
    auto const DPStmt = DP.get<clang::Stmt const *>();
    return isParent(Parent, DPStmt);
  }

  return false;
}

bool MappedAST::isParent(::clang::Decl const *Parent,
                         ::clang::Stmt const *Child) const
{
  auto const DP = getParent(Child);

  if (DP.assigned<clang::Decl const *>()) {
    auto const DPDecl = DP.get<clang::Decl const *>();
    return DPDecl == Parent ? true : isParent(Parent, DPDecl);
  }
  else if (DP.assigned<clang::Stmt const *>()) {
    auto const DPStmt = DP.get<clang::Stmt const *>();
    return isParent(Parent, DPStmt);
  }

  return false;
}

} // namespace seec_clang (in seec)

} // namespace seec


text:
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core.Entities;
using OfficeDevPnP.Core.Framework.Provisioning.Model;
using File = Microsoft.SharePoint.Client.File;
using OfficeDevPnP.Core.Diagnostics;
using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.Extensions;
using System;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using OfficeDevPnP.Core.Utilities;
using Microsoft.SharePoint.Client.Taxonomy;
using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions;
using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.Utilities;

namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers
{
    internal class ObjectFiles : ObjectHandlerBase
    {
        private readonly string[] WriteableReadOnlyFields = new string[] { "publishingpagelayout", "contenttypeid" };

        // See https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f?ui=en-US&rs=en-US&ad=US
        public static readonly string[] BlockedExtensionsInNoScript = new string[] { ".asmx", ".ascx", ".aspx", ".htc", ".jar", ".master", ".swf", ".xap", ".xsf" };
        public static readonly string[] BlockedLibrariesInNoScript = new string[] { "_catalogs/theme", "style library", "_catalogs/lt", "_catalogs/wp" };

        public override string Name
        {
            get { return "Files"; }
        }

        public override string InternalName => "Files";

        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Check if this is not a noscript site as we're not allowed to write to the web property bag is that one
                bool isNoScriptSite = web.IsNoScriptSite();
                web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Url);

                // Build on the fly the list of additional files coming from the Directories
                var directoryFiles = new List<Model.File>();
                foreach (var directory in template.Directories)
                {
                    var metadataProperties = directory.GetMetadataProperties();
                    directoryFiles.AddRange(directory.GetDirectoryFiles(metadataProperties));
                }

                var filesToProcess = template.Files.Union(directoryFiles).ToArray();

                var siteAssetsFiles = filesToProcess.Where(f => f.Folder.ToLower().Contains("siteassets")).FirstOrDefault();
                if (siteAssetsFiles != null)
                {
                    // Need this so that we dont have access denied error during the first time upload, especially for modern sites
                    web.Lists.EnsureSiteAssetsLibrary();
                    web.Context.ExecuteQueryRetry();
                }

                var currentFileIndex = 0;
                var originalWeb = web; // Used to store and re-store context in case files are deployed to masterpage gallery
                foreach (var file in filesToProcess)
                {
                    file.Src = parser.ParseString(file.Src);
                    var targetFileName = parser.ParseString(
                        !String.IsNullOrEmpty(file.TargetFileName) ? file.TargetFileName : template.Connector.GetFilenamePart(file.Src)
                        );

                    currentFileIndex++;
                    WriteSubProgress("File", targetFileName, currentFileIndex, filesToProcess.Length);
                    var folderName = parser.ParseString(file.Folder);

                    if (folderName.ToLower().Contains("/_catalogs/"))
                    {
                        // Edge case where you have files in the template which should be provisioned to the site collection
                        // master page gallery and not to a connected subsite
                        web = web.Context.GetSiteCollectionContext().Web;
                        web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Url);
                    }

                    if (folderName.ToLower().StartsWith((web.ServerRelativeUrl.ToLower())))
                    {
                        folderName = folderName.Substring(web.ServerRelativeUrl.Length);
                    }

                    if (SkipFile(isNoScriptSite, targetFileName, folderName))
                    {
                        // add log message
                        scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_Files_SkipFileUpload, targetFileName, folderName);
                        continue;
                    }

                    var folder = web.EnsureFolderPath(folderName);
#if !SP2013
                    //register folder UniqueId as Token
                    folder.EnsureProperties(p => p.UniqueId, p => p.ServerRelativeUrl);
                    parser.AddToken(new FileUniqueIdToken(web, folder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), folder.UniqueId));
                    parser.AddToken(new FileUniqueIdEncodedToken(web, folder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), folder.UniqueId));
#endif
                    var checkedOut = false;

                    var targetFile = folder.GetFile(template.Connector.GetFilenamePart(targetFileName));

                    if (targetFile != null)
                    {
                        if (file.Overwrite)
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_and_overwriting_existing_file__0_, targetFileName);
                            checkedOut = CheckOutIfNeeded(web, targetFile);

                            using (var stream = FileUtilities.GetFileStream(template, file))
                            {
                                targetFile = UploadFile(folder, stream, targetFileName, file.Overwrite);
                            }
                        }
                        else
                        {
                            checkedOut = CheckOutIfNeeded(web, targetFile);
                        }
                    }
                    else
                    {
                        using (var stream = FileUtilities.GetFileStream(template, file))
                        {
                            if (stream == null)
                            {
                                throw new FileNotFoundException($"File {file.Src} does not exist");
                            }
                            else
                            {
                                scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_file__0_, targetFileName);
                                targetFile = UploadFile(folder, stream, targetFileName, file.Overwrite);
                            }
                        }

                        checkedOut = CheckOutIfNeeded(web, targetFile);
                    }

                    if (targetFile != null)
                    {
                        // Add the fileuniqueid tokens
#if !SP2013
                        targetFile.EnsureProperties(p => p.UniqueId, p => p.ServerRelativeUrl);
                        parser.AddToken(new FileUniqueIdToken(web, targetFile.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), targetFile.UniqueId));
                        parser.AddToken(new FileUniqueIdEncodedToken(web, targetFile.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), targetFile.UniqueId));
#endif

#if !SP2013
                        bool webPartsNeedLocalization = false;
#endif
                        if (file.WebParts != null && file.WebParts.Any())
                        {
                            targetFile.EnsureProperties(f => f.ServerRelativeUrl);

                            var existingWebParts = web.GetWebParts(targetFile.ServerRelativeUrl).ToList();
                            foreach (var webPart in file.WebParts)
                            {
                                // check if the webpart is already set on the page
                                if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == parser.ParseString(webPart.Title)) == null)
                                {
                                    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Adding_webpart___0___to_page, webPart.Title);
                                    var wpEntity = new WebPartEntity();
                                    wpEntity.WebPartTitle = parser.ParseString(webPart.Title);
                                    wpEntity.WebPartXml = parser.ParseXmlString(webPart.Contents).Trim(new[] { '\n', ' ' });
                                    wpEntity.WebPartZone = webPart.Zone;
                                    wpEntity.WebPartIndex = (int)webPart.Order;
                                    var wpd = web.AddWebPartToWebPartPage(targetFile.ServerRelativeUrl, wpEntity);
#if !SP2013
                                    if (webPart.Title.ContainsResourceToken())
                                    {
                                        // update data based on where it was added - needed in order to localize wp title
                                        wpd.EnsureProperties(w => w.ZoneId, w => w.WebPart, w => w.WebPart.Properties);
                                        webPart.Zone = wpd.ZoneId;
                                        webPart.Order = (uint)wpd.WebPart.ZoneIndex;
                                        webPartsNeedLocalization = true;
                                    }
#endif
                                }
                            }
                        }

#if !SP2013
                        if (webPartsNeedLocalization)
                        {
                            file.LocalizeWebParts(web, parser, targetFile, scope);
                        }
#endif

                        //Set Properties before Checkin
                        if (file.Properties != null && file.Properties.Any())
                        {
                            Dictionary<string, string> transformedProperties = file.Properties.ToDictionary(property => property.Key, property => parser.ParseString(property.Value));
                            SetFileProperties(targetFile, transformedProperties, parser, false);
                        }

                        switch (file.Level)
                        {
                            case Model.FileLevel.Published:
                                {
                                    targetFile.PublishFileToLevel(Microsoft.SharePoint.Client.FileLevel.Published);
                                    break;
                                }
                            case Model.FileLevel.Draft:
                                {
                                    targetFile.PublishFileToLevel(Microsoft.SharePoint.Client.FileLevel.Draft);
                                    break;
                                }
                            default:
                                {
                                    if (checkedOut)
                                    {
                                        targetFile.CheckIn("", CheckinType.MajorCheckIn);
                                        web.Context.ExecuteQueryRetry();
                                    }
                                    break;
                                }
                        }

                        // Don't set security when nothing is defined. This otherwise breaks on files set outside of a list
                        if (file.Security != null &&
                            (file.Security.ClearSubscopes == true || file.Security.CopyRoleAssignments == true || file.Security.RoleAssignments.Count > 0))
                        {
                            targetFile.ListItemAllFields.SetSecurity(parser, file.Security, WriteMessage);
                        }
                    }

                    web = originalWeb; // restore context in case files are provisioned to the master page gallery #1059
                }
            }
            WriteMessage("Done processing files", ProvisioningMessageType.Completed);
            return parser;
        }

        private static bool CheckOutIfNeeded(Web web, File targetFile)
        {
            var checkedOut = false;
            try
            {
                web.Context.Load(targetFile, f => f.CheckOutType, f => f.CheckedOutByUser, f => f.ListItemAllFields.ParentList.ForceCheckout);
                web.Context.ExecuteQueryRetry();

                if (targetFile.ListItemAllFields.ServerObjectIsNull.HasValue
                    && !targetFile.ListItemAllFields.ServerObjectIsNull.Value
                    && targetFile.ListItemAllFields.ParentList.ForceCheckout)
                {
                    if (targetFile.CheckOutType == CheckOutType.None)
                    {
                        targetFile.CheckOut();
                    }
                    checkedOut = true;
                }
            }
            catch (ServerException ex)
            {
                // Handling the exception stating the "The object specified does not belong to a list."
#if !ONPREMISES
                if (ex.ServerErrorCode != -2113929210)
#else
                if (ex.ServerErrorCode != -2146232832)
#endif
                {
                    throw;
                }
            }
            return checkedOut;
        }

        public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {

            return template;
        }

        public void SetFileProperties(File file, IDictionary<string, string> properties, bool checkoutIfRequired = true)
        {
            SetFileProperties(file, properties, null, checkoutIfRequired);
        }

        public void SetFileProperties(File file, IDictionary<string, string> properties, TokenParser parser, bool checkoutIfRequired = true)
        {
            var context = file.Context;
            if (properties != null && properties.Count > 0)
            {
                // Get a reference to the target list, if any
                // and load file item properties
                var parentList = file.ListItemAllFields.ParentList;
                context.Load(parentList);
                context.Load(file.ListItemAllFields);
                try
                {
                    context.ExecuteQueryRetry();
                }
                catch (ServerException ex)
                {
                    // If this throws ServerException (does not belong to list), then shouldn't be trying to set properties)
#if !ONPREMISES
                    if (ex.ServerErrorCode != -2113929210)
#else
                    if (ex.ServerErrorCode != -2146232832)
#endif
                    {
                        throw;
                    }
                }

                ListItemUtilities.UpdateListItem(file.ListItemAllFields, parser, properties, ListItemUtilities.ListItemUpdateType.UpdateOverwriteVersion);
            }
        }

        /// <summary>
        /// Checks if a given file can be uploaded. Sites using NoScript can't handle all uploads
        /// </summary>
        /// <param name="isNoScriptSite">Is this a noscript site?</param>
        /// <param name="fileName">Filename to verify</param>
        /// <param name="folderName">Folder (library) to verify</param>
        /// <returns>True is the file will not be uploaded, false otherwise</returns>
        public static bool SkipFile(bool isNoScriptSite, string fileName, string folderName)
        {
            string fileExtionsion = Path.GetExtension(fileName).ToLower();
            if (isNoScriptSite)
            {
                if (!String.IsNullOrEmpty(fileExtionsion) && BlockedExtensionsInNoScript.Contains(fileExtionsion))
                {
                    // We need to skip this file
                    return true;
                }

                if (!String.IsNullOrEmpty(folderName))
                {
                    foreach (string blockedlibrary in BlockedLibrariesInNoScript)
                    {
                        if (folderName.ToLower().StartsWith(blockedlibrary))
                        {
                            // Can't write to this library, let's skip
                            return true;
                        }
                    }
                }
            }

            return false;
        }

        public override bool WillProvision(Web web, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            if (!_willProvision.HasValue)
            {
                _willProvision = template.Files.Any() | template.Directories.Any();
            }
            return _willProvision.Value;
        }

        public override bool WillExtract(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            if (!_willExtract.HasValue)
            {
                _willExtract = false;
            }
            return _willExtract.Value;
        }

        private static File UploadFile(Microsoft.SharePoint.Client.Folder folder, Stream stream, string fileName, bool overwrite)
        {
            if (folder == null) throw new ArgumentNullException(nameof(folder));
            if (stream == null) throw new ArgumentNullException(nameof(stream));

            File targetFile = null;
            try
            {
                targetFile = folder.UploadFile(fileName, stream, overwrite);
            }
            catch (ServerException ex)
            {
                if (ex.ServerErrorCode != -2130575306) //Error code: -2130575306 = The file is already checked out.
                {
                    //The file name might contain encoded characters that prevent upload. Decode it and try again.
                    fileName = WebUtility.UrlDecode(fileName);
                    try
                    {
                        targetFile = folder.UploadFile(fileName, stream, overwrite);
                    }
                    catch (Exception)
                    {
                        //unable to Upload file, just ignore
                    }
                }
            }
            return targetFile;
        }
    }
}


text:
module Fog
  module DNS
    class Bluebox
      class Real

        require 'fog/bluebox/parsers/dns/get_record'

        # Get an individual DNS record from the specified zone
        #
        # ==== Returns
        # * response<~Excon::Response>:
        #   * hash<~Hash>:
        #     * 'id'<~String> - The id of this record
        #     * 'type'<~String> - type of DNS record to create (A, CNAME, etc)
        #     * 'domain-id'<~Integer> - ID of the zone
        #     * 'name'<~String> - empty?
        #     * 'domain'<~String> - The domain name
        #     * 'type'<~String> - The type of DNS record (e.g. A, MX, NS, etc.)
        #     * 'content'<~String> - data for the DNS record (ie for an A record, the IP address)
        def get_record(zone_id, record_id)
          request(
            :expects  => 200,
            :method   => 'GET',
            :parser   => Fog::Parsers::DNS::Bluebox::GetRecord.new,
            :path     => "/api/domains/#{zone_id}/records/#{record_id}.xml"
          )
        end

      end

      class Mock

        def get_record(record_id)
          Fog::Mock.not_implemented
        end

      end
    end
  end
end


text:
package de.vandermeer.asciiparagraph.examples;

import org.apache.commons.lang3.text.StrBuilder;

import de.svenjacobs.loremipsum.LoremIpsum;
import de.vandermeer.asciiparagraph.AP_Context;
import de.vandermeer.asciiparagraph.AsciiParagraph;
import de.vandermeer.skb.interfaces.StandardExampleAsCmd;
import de.vandermeer.skb.interfaces.transformers.textformat.TextAlignment;

/**
 * AsciiParagraph example demonstrating alignment behavior.
 *
 * @author     Sven van der Meer <vdmeer.sven@mykolab.com>
 * @version    v0.1.1 build 170502 (02-May-17) for Java 1.8
 * @since      v0.0.3
 */
public class AP_02_Alignment_Behavior implements StandardExampleAsCmd {

	@Override
	public void showOutput(){
		// tag::example[]
		AP_Context ctx = new AP_Context().setWidth(39);

		AsciiParagraph ap = new AsciiParagraph(ctx);
		ap.addText(new LoremIpsum().getWords(29));

		ctx.setAlignment(TextAlignment.JUSTIFIED);
		System.out.println(ap.render());

		ctx.setAlignment(TextAlignment.JUSTIFIED_LEFT);
		System.out.println(ap.render());

		ctx.setAlignment(TextAlignment.JUSTIFIED_RIGHT);
		System.out.println(ap.render());

		ctx.setAlignment(TextAlignment.CENTER);
		System.out.println(ap.render());

		ctx.setAlignment(TextAlignment.LEFT);
		System.out.println(ap.render());

		ctx.setAlignment(TextAlignment.RIGHT);
		System.out.println(ap.render());
		// end::example[]
	}

	@Override
	public StrBuilder getSource(){
		String[] source = new String[]{
				"AP_Context ctx = new AP_Context().setWidth(39);",
				"",
				"AsciiParagraph ap = new AsciiParagraph(ctx);",
				"ap.addText(new LoremIpsum().getWords(29));",
				"",
				"ctx.setAlignment(AP_Alignment.JUSTIFIED);",
				"System.out.println(ap.render());",
				"",
				"ctx.setAlignment(AP_Alignment.JUSTIFIED_LEFT);",
				"System.out.println(ap.render());",
				"",
				"ctx.setAlignment(AP_Alignment.JUSTIFIED_RIGHT);",
				"System.out.println(ap.render());",
				"",
				"ctx.setAlignment(AP_Alignment.CENTER);",
				"System.out.println(ap.render());",
				"",
				"ctx.setAlignment(AP_Alignment.LEFT);",
				"System.out.println(ap.render());",
				"",
				"ctx.setAlignment(AP_Alignment.RIGHT);",
				"System.out.println(ap.render());",
		};
		return new StrBuilder().appendWithSeparators(source, "\n");
	}

	@Override
	public String getDescription() {
		return "text alignment behavior";
	}

	@Override
	public String getID() {
		return "alignment";
	}
}


text:
package org.sterl.training.aws.springbootaws;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootAwsApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootAwsApplication.class, args);
    }

}


text:
import re
import os
import pprint
currentFolder = r"C:\\"
txtCount = 0
newDirectory = True
while True:
    if newDirectory:
        txts = []
        txtCount = 0
        direct = os.listdir(currentFolder)
        for file in direct:
            newDirectory = False
            txt = re.search("\.txt$", file)
            if txt is not None:
                txts.append(file)
                txtCount += 1
    print("There are "+str(txtCount)+" text files in this directory.")
    m = "You are in " + currentFolder + ". Type directory or search txt files. "
    task = input(m)
    if task == "search":
        searchterm = re.compile(input("Type in a search. "))
        for file in txts:
            print(file)
            currentFile = open(os.path.join(currentFolder, file))
            print(searchterm.findall(currentFile.read()))
    elif task == "look":
        pprint.pprint(direct)
    elif task in direct:
        newDirectory = True
        currentFolder = os.path.join(currentFolder, task)
        print(currentFolder)
    elif os.path.isdir(task):
        currentFolder = task
        newDirectory = True
    else:
        print("That is not a directory.")


text:
<!-- - Describe your changes. -->

### Motivation and Context
<!-- - Why is this change required? What problem does it solve? -->
<!-- - If it fixes an open issue, please link to the issue here. -->


text:
require 'rails_helper'
require_relative '../shared_examples'

RSpec.describe Archived::DeliverPetitionEmailJob, type: :job do
  let(:requested_at) { Time.current.change(usec: 0) }
  let(:requested_at_as_string) { requested_at.getutc.iso8601(6) }

  let(:petition) { FactoryBot.create(:archived_petition) }
  let(:signature) { FactoryBot.create(:archived_signature, petition: petition) }
  let(:email) { FactoryBot.create(:archived_petition_email, petition: petition) }
  let(:timestamp_name) { 'petition_email' }

  let :arguments do
    {
      signature: signature,
      timestamp_name: timestamp_name,
      petition: petition,
      requested_at: requested_at_as_string,
      email: email
    }
  end

  before do
    petition.set_email_requested_at_for(timestamp_name, to: requested_at)
  end

  it_behaves_like "a job to send an signatory email"

  context "when the signature is the creator" do
    before do
      allow(signature).to receive(:creator?).and_return(true)
    end

    it "uses the correct mailer method to generate the email" do
      expect(subject).to receive_message_chain(:mailer, :email_creator).with(petition, signature, email).and_return double.as_null_object
      subject.perform(**arguments)
    end
  end

  context "when the signature is not the creator" do
    before do
      allow(signature).to receive(:creator?).and_return(false)
    end

    it "uses the correct mailer method to generate the email" do
      expect(subject).to receive_message_chain(:mailer, :email_signer).with(petition, signature, email).and_return double.as_null_object
      subject.perform(**arguments)
    end
  end
end


text:
#include "ElementGame.h"
#include <Rocket/Core/ElementDocument.h>
#include <Rocket/Core/Input.h>
#include <Rocket/Core/Factory.h>
#include <Rocket/Core/Python/ElementInstancer.h>
#include <Rocket/Core/Python/ElementWrapper.h>
#include <Rocket/Core/Python/Python.h>
#include "Defender.h"
#include "Game.h"

ElementGame::ElementGame(const Rocket::Core::String& tag) : Rocket::Core::Element(tag)
{
	game = new Game();
}

ElementGame::~ElementGame()
{
	delete game;
}

void ElementGame::InitialisePythonInterface()
{
	PyObject* object = python::class_<ElementGame, Rocket::Core::Python::ElementWrapper<ElementGame>, python::bases<Rocket::Core::Element>, boost::noncopyable >("ElementGame", python::init<const char*>())
		.ptr();

	Rocket::Core::Factory::RegisterElementInstancer("game", new Rocket::Core::Python::ElementInstancer(object))->RemoveReference();
}

// Intercepts and handles key events.
void ElementGame::ProcessEvent(Rocket::Core::Event& event)
{
	Rocket::Core::Element::ProcessEvent(event);

	if (event == "keydown" ||
		event == "keyup")
	{
		bool key_down = event == "keydown";
		Rocket::Core::Input::KeyIdentifier key_identifier = (Rocket::Core::Input::KeyIdentifier) event.GetParameter< int >("key_identifier", 0);

		// Process left and right keys
		if (key_down)
		{
			if (key_identifier == Rocket::Core::Input::KI_LEFT)
				game->GetDefender()->StartMove(-1.0f);
			if (key_identifier == Rocket::Core::Input::KI_RIGHT)
				game->GetDefender()->StartMove(1.0f);
			if (key_identifier == Rocket::Core::Input::KI_SPACE)
				game->GetDefender()->Fire();
		}
		else if (!key_down)
		{
			if (key_identifier == Rocket::Core::Input::KI_LEFT)
				game->GetDefender()->StopMove(-1.0f);
			if (key_identifier == Rocket::Core::Input::KI_RIGHT)
				game->GetDefender()->StopMove(1.0f);
		}
	}

	if (event == "load")
	{
		game->Initialise();
	}
}

// Updates the game.
void ElementGame::OnUpdate()
{
	game->Update();

	if (game->IsGameOver())
		DispatchEvent("gameover", Rocket::Core::Dictionary(), false);
}

// Renders the game.
void ElementGame::OnRender()
{
	game->Render();
}

void ElementGame::OnChildAdd(Rocket::Core::Element* element)
{
	Rocket::Core::Element::OnChildAdd(element);

	if (element == this)
		GetOwnerDocument()->AddEventListener("load", this);
}


text:
// TTTTimeIntervalFormatter.h
//
// Copyright (c) 2011 Mattt Thompson (http://mattt.me)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import <Foundation/Foundation.h>

/**
 Instances of `TTTTimeIntervalFormatter` create localized string representations of `NSTimeInterval` values.

 For example, a time interval of -75 would be formatted as @"1 minute ago" in English.
 */
@interface TTTTimeIntervalFormatter : NSFormatter

/**
 Specifies the locale used to format strings. Defaults to the current system locale.
 */
@property (nonatomic, strong) NSLocale *locale;

/**
 Specifies the calendar used in date calculation. Defaults to the current system calendar.
 */
@property (nonatomic, strong) NSCalendar *calendar;

///--------------------------------------
/// @name Configuring Deictic Expressions
///--------------------------------------

/**
 Specifies the localized string used to express the past deictic expression. "ago" by default.
 */
@property (nonatomic, copy) NSString *pastDeicticExpression;

/**
 Specifies the localized string used to express the present deictic expression. "just now" by default.
 */
@property (nonatomic, copy) NSString *presentDeicticExpression;

/**
 Specifies the localized string used to express the future deictic expression. "from now" by default.
 */
@property (nonatomic, copy) NSString *futureDeicticExpression;

/**
 Specifies the localized string used to format the time interval string and deictic expression. Defaults to a format with the deictic expression following the time interval
 */
@property (nonatomic, copy) NSString *deicticExpressionFormat;

/**
 Specifies the localized string used to format the time with its suffix. "#{Time} #{Unit}" by default.
 */
@property (nonatomic, strong) NSString *suffixExpressionFormat;

/**
 Specifies the time interval before and after the present moment that is described as still being in the present, rather than the past or future. Defaults to 1 second.
 */
@property (nonatomic, assign) NSTimeInterval presentTimeIntervalMargin;

/**
 Specifies whether to use idiomatic deictic expressions when available, such as "last week" instead of "1 week ago". Defaults to `NO`.

 @discussion This implementation is entirely separate from the equivalent behavior used by `NSDateFormatter`.
 */
@property (nonatomic, assign) BOOL usesIdiomaticDeicticExpressions;

///-----------------------------------------
/// @name Configuring Approximate Qualifiers
///-----------------------------------------

/**
 Specifies the localized string used to qualify a time interval as being an approximate time. "about" by default.
 */
@property (nonatomic, copy) NSString *approximateQualifierFormat;

/**
 Specifies whether to use an approximate qualifier when the described interval is not exact. `NO` by default.
 */
@property (nonatomic, assign) BOOL usesApproximateQualifier;

///------------------------------------
/// @name Configuring Significant Units
///------------------------------------

/**
 A bitmask specifying the significant units. Defaults to a bitmask of year, month, week, day, hour, minute, and second.
 */
@property (nonatomic, assign) NSCalendarUnit significantUnits;

/**
 Specifies the number of units that should be displayed before approximating. `0` to show all units. `1` by default.
 */
@property (nonatomic, assign) NSUInteger numberOfSignificantUnits;

/**
 Specifies the least significant unit that should be displayed when not approximating. Defaults to `NSCalendarUnitSeconds`.
 */
@property (nonatomic, assign) NSCalendarUnit leastSignificantUnit;

///----------------------------------------------
/// @name Configuring Calendar Unit Abbreviations
///----------------------------------------------

/**
 Specifies whether to use abbreviated calendar units to describe time intervals, for instance "wks" instead of "weeks" in English. Defaults to `NO`.
 */
@property (nonatomic, assign) BOOL usesAbbreviatedCalendarUnits;

///-------------------------
/// @name Converting Objects
///-------------------------

/**
 Returns a string representation of a time interval formatted using the receiver's current settings.

 @param seconds The number of seconds to add to the receiver. Use a negative value for seconds to have the returned object specify a date before the receiver.
 */
- (NSString *)stringForTimeInterval:(NSTimeInterval)seconds;

/**
 Returns a string representation of the time interval between two specified dates formatted using the receiver's current settings.

 @param startingDate The starting date
 @param endingDate The ending date
 */
- (NSString *)stringForTimeIntervalFromDate:(NSDate *)startingDate
                                     toDate:(NSDate *)endingDate;

@end


text:
<?php
namespace phprules;

use InvalidArgumentException;

/**
 * Represents an operator with a boolean result.
 *
 *
New operators may be added by using the addOperatorClass() method.

 *
 * @author Greg Swindle <greg@swindle.net>
 * @author Martin Rademacher <mano@radebatz.net>
 */
class Operator extends RuleElement
{
    private static $DEFAULT_OPERATORS = array(
        'phprules\operators\Logical',
        'phprules\operators\Comparison',
        'phprules\operators\In',
    );
    private static $symbols = array();

    /**
     * Create new instance.
     *
     * @param string operator The operator.
     */
    public function __construct($operator)
    {
        parent::__construct($operator);
        if (!static::$symbols) {
            foreach (static::$DEFAULT_OPERATORS as $class) {
                static::addOperatorClass($class);
            }
        }
        if (!in_array($operator, array_keys(static::$symbols))) {
            throw new InvalidArgumentException($operator . " is not a valid operator.");
        }
    }

    /**
     * Add operator class.
     *
     * @param string class The implementation class.
     */
    public static function addOperatorClass($class)
    {
        foreach ($class::getSymbols() as $symbol) {
            static::$symbols[$symbol] = $class;
        }
    }

    /**
     * {@inheritDoc}
     */
    public function evaluate($stack)
    {
        $class = static::$symbols[$this->getName()];

        return $class::perform($this->getName(), $stack);
    }

}


text:
//------------------------------------------------------------------------------
// <license file="NativeCliMethodInfo.cs">
//
//      The use and distribution terms for this software are contained in the file
//      named 'LICENSE', which can be found in the resources directory of this
//		distribution.
//
//      By using this software in any fashion, you are agreeing to be bound by the
//      terms of this license.
//
// </license>
//------------------------------------------------------------------------------

using System;
using System.Text;
using System.Reflection;

namespace EcmaScript.NET.Types.Cli
{

    public class CliMethodInfo : BaseFunction
    {

        private string m_Name = string.Empty;

        public override string ClassName
        {
            get
            {
                return m_Name;
            }
        }

        public override string FunctionName
        {
            get
            {
                return m_Name;
            }
        }

        private MethodInfo [] m_MethodInfos = null;

        private object m_Target = null;

        private bool [] paramsParameters = null;

        public CliMethodInfo (object target, string methodName)
        {
            Init (methodName, new MemberInfo [] {
                target.GetType().GetMethod(methodName) }, target);
        }

        public CliMethodInfo (string name, MemberInfo methodInfo, object target)
        {
            Init (name, new MemberInfo [] { methodInfo }, target);
        }

        public CliMethodInfo (string name, MemberInfo [] methodInfos, object target)
        {
            Init (name, methodInfos, target);
        }

        void Init (string name, MemberInfo [] methodInfos, object target)
        {
            m_Name = name;
            m_MethodInfos = new MethodInfo [methodInfos.Length];
            Array.Copy (
                methodInfos, 0, m_MethodInfos, 0, m_MethodInfos.Length);
            m_Target = target;

            // Cache paramsParameters attribute
            paramsParameters = new bool [methodInfos.Length];
            for (int i = 0; i < methodInfos.Length; i++) {
                paramsParameters [i] = CliHelper.HasParamsParameter (
                    m_MethodInfos [i]);
            }
        }

        public override object Call (Context cx, IScriptable scope, IScriptable thisObj, object [] args)
        {
            if (m_MethodInfos.Length == 0) {
                throw new ApplicationException ("No methods defined for call");
            }

            int index = FindFunction (cx, m_MethodInfos, args, paramsParameters);
            if (index < 0) {
                Type c = m_MethodInfos [0].DeclaringType;
                string sig = c.FullName + '.' + FunctionName + '(' + ScriptSignature (args) + ')';
                throw Context.ReportRuntimeErrorById ("msg.java.no_such_method", sig);
            }

            MethodBase meth = (MethodBase)m_MethodInfos [index];
            ParameterInfo [] pis = meth.GetParameters ();

            // First, we marshall the args.
            object [] origArgs = args;
            for (int i = 0; i < args.Length; i++) {
                object arg = args [i];

                if (paramsParameters [index] && i >= pis.Length - 1) {
                    // params[] arg is always an array type
                    Type arrayType = pis [pis.Length - 1].ParameterType;
                    Type arrayElementType = arrayType.GetElementType ();

                    object [] dummyArg = new object [args.Length - i];
                    for (int e = i; e < args.Length; e++) {
                        dummyArg [e - i] = Context.JsToCli (arg, arrayElementType);
                    }
                    args = new object [i + 1];
                    args.CopyTo (args, 0);
                    args [i] = dummyArg;
                }
                else {
                    Type argType = pis [i].ParameterType;
                    object coerced = Context.JsToCli (arg, argType);
                    if (coerced != arg) {
                        if (origArgs == args) {
                            args = new object [args.Length];
                            args.CopyTo (args, 0);
                        }
                        args [i] = coerced;
                    }
                }
            }
            object cliObject;
            if (meth.IsStatic) {
                cliObject = null; // don't need an object
            }
            else {
                IScriptable o = thisObj;
                Type c = meth.DeclaringType;
                for (; ; ) {
                    if (o == null) {
                        throw Context.ReportRuntimeErrorById ("msg.nonjava.method", FunctionName, ScriptConvert.ToString (thisObj), c.FullName);
                    }
                    if (o is Wrapper) {
                        cliObject = ((Wrapper)o).Unwrap ();
                        if (c.IsInstanceOfType (cliObject)) {
                            break;
                        }
                    }
                    o = o.GetPrototype ();
                }
            }

            object retval = null;
            try {
                retval = (meth as MethodBase).Invoke (cliObject, args);
            }
            catch (Exception ex) {
                Context.ThrowAsScriptRuntimeEx (ex);
            }

            Type staticType = meth.DeclaringType;
            if (meth is MethodInfo)
                staticType = ((MethodInfo)meth).ReturnType;

            object wrapped = cx.Wrap (scope, retval, staticType);
            if (wrapped == null && staticType == Type.GetType ("System.Void")) {
                wrapped = Undefined.Value;
            }
            return wrapped;
        }

        /// <summary> Find the index of the correct function to call given the set of methods
        /// or constructors and the arguments.
        /// If no function can be found to call, return -1.
        /// </summary>
        internal static int FindFunction (Context cx, MethodBase [] methodsOrCtors, object [] args, bool [] paramsParameter)
        {
            if (methodsOrCtors.Length == 0) {
                return -1;
            }
            else if (methodsOrCtors.Length == 1) {
                MethodBase member = methodsOrCtors [0];
                ParameterInfo [] pis = member.GetParameters ();
                int alength = pis.Length;

                if (alength != args.Length) {
                    if (!paramsParameter [0]) {
                        return -1;
                    }
                }

                for (int j = 0; j != alength; ++j) {
                    object arg = args [j];
                    Type argType = null;

                    if (paramsParameter [0] && j >= pis.Length - 1) {
                        // params[] arg is always an array type
                        argType = pis [pis.Length - 1].ParameterType.GetElementType ();
                    }
                    else {
                        argType = pis [j].ParameterType;
                    }

                    if (!CliObject.CanConvert (arg, argType)) {
                        //if (debug)
                        //	printDebug("Rejecting (args can't convert) ", member, args);
                        return -1;
                    }
                }
                //if (debug)
                //	printDebug("Found ", member, args);
                return 0;
            }

            int firstBestFit = -1;
            int [] extraBestFits = null;
            int extraBestFitsCount = 0;

            for (int i = 0; i < methodsOrCtors.Length; i++) {
                MethodBase member = methodsOrCtors [i];
                ParameterInfo [] pis = member.GetParameters ();
                if (pis.Length != args.Length) {
                    goto search;
                }
                for (int j = 0; j < pis.Length; j++) {
                    if (!CliObject.CanConvert (args [j], pis [j].ParameterType)) {
                        //if (debug)
                        //	printDebug("Rejecting (args can't convert) ", member, args);
                        goto search;
                    }
                }
                if (firstBestFit < 0) {
                    //if (debug)
                    //	printDebug("Found first applicable ", member, args);
                    firstBestFit = i;
                }
                else {
                    // Compare with all currently fit methods.
                    // The loop starts from -1 denoting firstBestFit and proceed
                    // until extraBestFitsCount to avoid extraBestFits allocation
                    // in the most common case of no ambiguity
                    int betterCount = 0; // number of times member was prefered over
                    // best fits
                    int worseCount = 0; // number of times best fits were prefered
                    // over member
                    for (int j = -1; j != extraBestFitsCount; ++j) {
                        int bestFitIndex;
                        if (j == -1) {
                            bestFitIndex = firstBestFit;
                        }
                        else {
                            bestFitIndex = extraBestFits [j];
                        }
                        MethodBase bestFit = methodsOrCtors [bestFitIndex];
                        int preference = PreferSignature (args, pis, bestFit.GetParameters ());
                        if (preference == PREFERENCE_AMBIGUOUS) {
                            break;
                        }
                        else if (preference == PREFERENCE_FIRST_ARG) {
                            ++betterCount;
                        }
                        else if (preference == PREFERENCE_SECOND_ARG) {
                            ++worseCount;
                        }
                        else {
                            if (preference != PREFERENCE_EQUAL)
                                Context.CodeBug ();
                            // This should not happen in theory
                            // but on some JVMs, Class.getMethods will return all
                            // static methods of the class heirarchy, even if
                            // a derived class's parameters match exactly.
                            // We want to call the dervied class's method.
                            if (bestFit.IsStatic && bestFit.DeclaringType.IsAssignableFrom (member.DeclaringType)) {
                                // On some JVMs, Class.getMethods will return all
                                // static methods of the class heirarchy, even if
                                // a derived class's parameters match exactly.
                                // We want to call the dervied class's method.
                                //if (debug)
                                //	printDebug("Substituting (overridden static)", member, args);
                                if (j == -1) {
                                    firstBestFit = i;
                                }
                                else {
                                    extraBestFits [j] = i;
                                }
                            }
                            else {
                                //if (debug)
                                //	printDebug("Ignoring same signature member ", member, args);
                            }
                            goto search;
                        }
                    }
                    if (betterCount == 1 + extraBestFitsCount) {
                        // member was prefered over all best fits
                        //if (debug)
                        //	printDebug("New first applicable ", member, args);
                        firstBestFit = i;
                        extraBestFitsCount = 0;
                    }
                    else if (worseCount == 1 + extraBestFitsCount) {
                        // all best fits were prefered over member, ignore it
                        //if (debug)
                        //	printDebug("Rejecting (all current bests better) ", member, args);
                    }
                    else {
                        // some ambiguity was present, add member to best fit set
                        //if (debug)
                        //	printDebug("Added to best fit set ", member, args);
                        if (extraBestFits == null) {
                            // Allocate maximum possible array
                            extraBestFits = new int [methodsOrCtors.Length - 1];
                        }
                        extraBestFits [extraBestFitsCount] = i;
                        ++extraBestFitsCount;
                    }
                }
            //UPGRADE_NOTE: Label 'search' was moved. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1014_3"'

            search:
                ;
            }

            if (firstBestFit < 0) {
                // Nothing was found
                return -1;
            }
            else if (extraBestFitsCount == 0) {
                // single best fit
                return firstBestFit;
            }

            // report remaining ambiguity
            System.Text.StringBuilder buf = new System.Text.StringBuilder ();
            for (int j = -1; j != extraBestFitsCount; ++j) {
                int bestFitIndex;
                if (j == -1) {
                    bestFitIndex = firstBestFit;
                }
                else {
                    bestFitIndex = extraBestFits [j];
                }
                buf.Append ("\n    ");
                buf.Append (CliHelper.ToSignature (methodsOrCtors [bestFitIndex]));
            }

            MethodBase firstFitMember = methodsOrCtors [firstBestFit];
            string memberName = firstFitMember.Name;
            //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Class.getName' may return a different value. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1043_3"'
            string memberClass = firstFitMember.DeclaringType.FullName;

            if (methodsOrCtors [0] is MethodInfo) {
                throw Context.ReportRuntimeErrorById ("msg.constructor.ambiguous", memberName, ScriptSignature (args), buf.ToString ());
            }
            else {
                throw Context.ReportRuntimeErrorById ("msg.method.ambiguous", memberClass, memberName, ScriptSignature (args), buf.ToString ());
            }
        }

        internal static string ScriptSignature (object [] values)
        {
            System.Text.StringBuilder sig = new System.Text.StringBuilder ();
            for (int i = 0; i != values.Length; ++i) {
                object value = values [i];

                string s;
                if (value == null) {
                    s = "null";
                }
                else if (value is System.Boolean) {
                    s = "boolean";
                }
                else if (value is string) {
                    s = "string";
                }
                else if (CliHelper.IsNumber (value)) {
                    s = "number";
                }
                else if (value is IScriptable) {
                    if (value is Undefined) {
                        s = "undefined";
                    }
                    else if (value is Wrapper) {
                        object wrapped = ((Wrapper)value).Unwrap ();
                        //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Class.getName' may return a different value. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1043_3"'
                        s = wrapped.GetType ().FullName;
                    }
                    else if (value is IFunction) {
                        s = "function";
                    }
                    else {
                        s = "object";
                    }
                }
                else {
                    s = CliHelper.ToSignature (value.GetType ());
                }

                if (i != 0) {
                    sig.Append (',');
                }
                sig.Append (s);
            }
            return sig.ToString ();
        }

        /// <summary>Types are equal </summary>
        private const int PREFERENCE_EQUAL = 0;
        private const int PREFERENCE_FIRST_ARG = 1;
        private const int PREFERENCE_SECOND_ARG = 2;
        /// <summary>No clear "easy" conversion </summary>
        private const int PREFERENCE_AMBIGUOUS = 3;

        /// <summary> Determine which of two signatures is the closer fit.
        /// Returns one of PREFERENCE_EQUAL, PREFERENCE_FIRST_ARG,
        /// PREFERENCE_SECOND_ARG, or PREFERENCE_AMBIGUOUS.
        /// </summary>
        private static int PreferSignature (object [] args, ParameterInfo [] sig1, ParameterInfo [] sig2)
        {
            int totalPreference = 0;
            for (int j = 0; j < args.Length; j++) {
                Type type1 = sig1 [j].ParameterType;
                Type type2 = sig2 [j].ParameterType;
                if (type1 == type2) {
                    continue;
                }
                object arg = args [j];

                // Determine which of type1, type2 is easier to convert from arg.

                int rank1 = CliObject.GetConversionWeight (arg, type1);
                int rank2 = CliObject.GetConversionWeight (arg, type2);

                int preference;
                if (rank1 < rank2) {
                    preference = PREFERENCE_FIRST_ARG;
                }
                else if (rank1 > rank2) {
                    preference = PREFERENCE_SECOND_ARG;
                }
                else {
                    // Equal ranks
                    if (rank1 == CliObject.CONVERSION_NONTRIVIAL) {
                        if (type1.IsAssignableFrom (type2)) {
                            preference = PREFERENCE_SECOND_ARG;
                        }
                        else if (type2.IsAssignableFrom (type1)) {
                            preference = PREFERENCE_FIRST_ARG;
                        }
                        else {
                            preference = PREFERENCE_AMBIGUOUS;
                        }
                    }
                    else {
                        preference = PREFERENCE_AMBIGUOUS;
                    }
                }

                totalPreference |= preference;

                if (totalPreference == PREFERENCE_AMBIGUOUS) {
                    break;
                }
            }
            return totalPreference;
        }

        public override object GetDefaultValue (Type typeHint)
        {
            if (typeHint == typeof (String))
                return ToString ();
            return base.GetDefaultValue (typeHint);
        }

        public override string ToString ()
        {
            string ret = "function " + m_Name + "() \n";
            ret += "{/*\n";
            foreach (MethodInfo mi in m_MethodInfos) {
                ret += CliHelper.ToSignature (mi) + "\n";
            }
            ret += "*/}";
            return ret;
        }

    }
}


text:
from django.conf import settings
from django.db import models
from django.db.models.query import QuerySet
from django.utils.translation import gettext as _

class OrderableModel(models.Model):
    """
    Add extra field and default ordering column for and inline orderable model
    """
    position = models.IntegerField(blank=True, null=True, db_index=True)

    class Meta:
        abstract = True
        ordering = ('position',)

    def save(self, force_insert=False, force_update=False, using=None):
        """
        Calculate position (max+1) for new records
        """
        if not self.position:
            max = self.__class__.objects.filter().aggregate(models.Max('position'))
            try:
                self.position = max['position__max'] + 1
            except TypeError:
                self.position = 1
        return super(OrderableModel, self).save(force_insert=force_insert, force_update=force_update, using=using)

class TimeStampedModel(models.Model):
  date_created = models.DateTimeField(_("date/time created"), auto_now_add=True)
  date_modified = models.DateTimeField(_("date/time modified"), auto_now=True)

  class Meta:
      abstract = True

class LanguageMixin(models.Model):
  language = models.CharField(max_length=7, choices=settings.LANGUAGES, db_index=True)

  class Meta:
      abstract = True

class SubclassQuerySet(QuerySet):

    def iterator(self):
        for obj in super(SubclassQuerySet, self).iterator():
            yield obj.get_subclass_object()

class SubclassManager(models.Manager):

    def get_query_set(self):
        return SubclassQuerySet(self.model)

class ParentModel(models.Model):
    _subclass_name = models.CharField(max_length=100, editable=False)

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        self._subclass_name = self.get_subclass_name()
        super(ParentModel, self).save(*args, **kwargs)

    def get_subclass_name(self):
        if type(self) is self.get_parent_model():
            return self._subclass_name
        if self._meta.proxy:
            return self.__class__.__name__.lower()
        return self.get_parent_link().related_query_name()

    def get_subclass_object(self):
        if self._meta.proxy:
            pass
        else:
            return getattr(self, self.get_subclass_name())

    def get_parent_link(self):
        return self._meta.parents[self.get_parent_model()]

    def get_parent_model(self):
        raise NotImplementedError

    def get_parent_object(self):
        return getattr(self, self.get_parent_link().name)


text:
@implementation QuitResponse
+ (void)load
{
	[iCukeHTTPResponseHandler registerHandler:self];
}

+ (BOOL)canHandleRequest:(CFHTTPMessageRef)aRequest
	method:(NSString *)requestMethod
	url:(NSURL *)requestURL
	headerFields:(NSDictionary *)requestHeaderFields
{
	return [requestURL.path isEqualToString:@"/quit"];
}

- (void)startResponse
{
	exit(0);
}
@end


text:
document.addEventListener('DOMContentLoaded', function() {
    var gData
    var URL = "13Xd93PIiGvGh2JQ6uygnsUTTLAlJu7F7TE-doTy-5OY"
    Tabletop.init({
        key: URL,
        callback: showInfo,
        simpleSheet: true
    })
})

function showInfo(gData) {
    var map = Sheetsee.loadMap("map");
    var stamenToner = L.tileLayer('http://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}.png', {
        attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap'
    }).addTo(map);

    var optionsJSON = ["rowNumber", "name", "icon", "city", "type"]
    var geoJSON = Sheetsee.createGeoJSON(gData, optionsJSON)
    console.log(geoJSON);

    markerLayer = L.geoJson(geoJSON,{
        pointToLayer: function(feature,latlng) {
            var featureIcon = L.icon({
                // Beer by Fabián Sanabria from the Noun Project
                iconUrl:'img/beer.png',
                iconSize: [18,18],
                popupAnchor: [0, -9]
            })
            var marker = L.marker(latlng,{
                icon: featureIcon
            });
            var popupContent = "

" + feature.opts.name + "

" + feature.opts.city + " | " + feature.opts.type + "

"
            marker.bindPopup(popupContent);
            return marker
        }
    }).addTo(map);

    map.fitBounds(markerLayer.getBounds())

    tableOptions = {
        "data": gData,
        "tableDiv": "#beerTable",
        "filterDiv": "#tableFilter"
    }

    Sheetsee.makeTable(tableOptions)
    Sheetsee.initiateTableFilter(tableOptions)

    // TABLE CLICK
    $('.beerRow').live("click", function(event) {
        //TABLE
        $('.beerRow').removeClass("selectedRow")
        var rowNumber = $(this).closest("tr").attr("id")
        $('#' + rowNumber).addClass("selectedRow")

        var dataElement = Sheetsee.getMatches(gData, rowNumber, "rowNumber")

        //MAP
        var selectedCoords = [dataElement[0].lat, dataElement[0].long]
        map.setView(selectedCoords, 17)

        // INFOPANE
        var selectedBeer = Sheetsee.ich.selectedBeer({
            rows: dataElement
        })
        $('#selectedBeer').html(selectedBeer).css("display", "inline")
    })

    // MAP MARKER CLICK
    markerLayer.on('click', function(e) {
        // TABLE
        $('.beerRow').removeClass("selectedRow")
        var rowNumber = e.layer.feature.opts.rowNumber
        $('#' + rowNumber).addClass("selectedRow")

        var dataElement = Sheetsee.getMatches(gData, rowNumber.toString(), "rowNumber")
        var selectedBeer = Sheetsee.ich.selectedBeer({
            rows: dataElement
        })

        // MAP
        selectedMarkerLocation = [dataElement[0].lat, dataElement[0].long]
        map.setView(selectedMarkerLocation, 17)

        // INFOPANE
        $('#selectedBeer').html(selectedBeer).css("display", "inline")
    })

    // resets the map to the extent of the feature layer when you click the reset map button
    $('.resetMap').click(function() {
        // TABLE
        // Clear whatever row is selected of the .selectedRow style
        $('.beerRow').removeClass("selectedRow")

        // INFOPANE
        // Clear the infopane of the info about the most recently selected beer place
        $('#selectedBeer').css("display", "none")

        // MAP
        // Center map and set zoom to include all the markers
        map.fitBounds(markerLayer.getBounds())
    })
}


text:
#pragma once

#include "Extent2.h"
#include "DeviceBuffer.h"
#include "CudaExecConfig.h"
#include <thrust/device_vector.h>
#include "Stencil.h"
#include <memory>

#ifdef __CUDACC__

template <typename T>
__global__
void stencil_heat_2d_kernel(const T* src, T* dest, Extent2 with, Extent2 without, const Pos2 offset, const T value)
{
	int x = blockIdx.x * blockDim.x + threadIdx.x;
	int y = blockIdx.y * blockDim.y + threadIdx.y;

	if (without.in_bounds(x, y))
	{
		auto get = [&with, &src](const int x, const int y, const T default_value)
		{
			return with.in_bounds_strict(x, y) ? src[with.index(x, y)] : default_value;
		};
		x += offset.x; y += offset.y;
		const int idx = with.index(x, y);
		const T c = src[idx];
		const T l = get(x - 1, y, c);
		const T r = get(x + 1, y, c);
		const T t = get(x, y - 1, c);
		const T b = get(x, y + 1, c);
		dest[idx] = c + value * (t + b + l + r - 4 * c);
	}
}

#endif

template <typename T>
void stencil_heat_2d(
	const CudaExecConfig& cnf,
	DeviceBuffer<T>& srcBuf,
	DeviceBuffer<T>& destBuf,
	const Extent2& without, const Pos2& offset,
	const T value
	);

template <typename T>
void stencil_heat_2d(
	const CudaExecConfig& cnf,
	std::shared_ptr<DeviceBuffer<T>> src,
	std::shared_ptr<DeviceBuffer<T>> dst,
	const Extent2& without, const Pos2& offset,
	const T value);


text:
Write AMF3 String
--DESCRIPTION--
Writes a String in AMF3 format.

--SKIPIF--
<?php if (!extension_loaded('amf')) print 'skip'; ?>
--FILE--
<?php
include 'amf_encoder.inc';
$encoder = new AmfEncoder();
$encoder->setAvmPlus(true);
$data = unserialize(file_get_contents(__DIR__ . '/asset/value/string.amf3'));
$obj = new stdClass();
$obj->value = 'abc';
$res = $encoder->run($obj);
echo ($res === $data) ? 'same' : 'diff';
?>
--EXPECT--
same


text:
namespace IntUITive.Selenium.Tests.SimpleCases
{
    using FluentAssertions;
    using NUnit.Framework;

    public class IndexingTests
    {
        [Test]
        public void Find_WithTwoElementWithSameText_ReturnsFirst()
        {
            var element = Context.Intuitively.Find("Same text header");

            element.GetAttribute("id").Should().Be("headerId1");
        }

        [Test]
        public void Find_WithIndexOfOne_ReturnsFirst()
        {
            var element = Context.Intuitively.Find("Same text header[1]");

            element.GetAttribute("id").Should().Be("headerId1");
        }

        [Test]
        public void Find_WithIndexOfTwo_ReturnsSecond()
        {
            var element = Context.Intuitively.Find("Same text header[2]");

            element.GetAttribute("id").Should().Be("headerId2");
        }

        [Test]
        public void Find_WithIndexOfNegOne_ReturnsLast()
        {
            var element = Context.Intuitively.Find("Same text header[-1]");

            element.GetAttribute("id").Should().Be("headerId3");
        }

        [Test]
        public void Find_WithIndexOfNegTwo_ReturnsSecondToLast()
        {
            var element = Context.Intuitively.Find("Same text header[-2]");

            element.GetAttribute("id").Should().Be("headerId2");
        }
    }
}


text:
class CGnuPlotPlot;
class CGnuPlotRenderer;
class CGnuPlotTipData;

class CGnuPlotStyleBase {
 public:
  CGnuPlotStyleBase(CGnuPlotTypes::PlotStyle style) :
   style_(style) {
  }

  virtual ~CGnuPlotStyleBase() { }

  CGnuPlotTypes::PlotStyle style() const { return style_; }

  // if single type is true, must define drawKey, drawAxis and fit
  virtual bool isSingleType() const { return false; }

  virtual bool has3D() const { return false; }

  virtual int numUsing() const = 0;

  virtual void draw2D(CGnuPlotPlot *plot, CGnuPlotRenderer *renderer) = 0;

  virtual void draw3D(CGnuPlotPlot *, CGnuPlotRenderer *) {
    std::cerr << "draw3D not implemented" << std::endl;
  }

  virtual void drawKey(CGnuPlotPlot *, CGnuPlotRenderer *) {
    std::cerr << "drawKey not implemented" << std::endl;
  }

  virtual bool hasKeyLine() const { return false; }

  virtual void drawKeyLine(CGnuPlotPlot *, CGnuPlotRenderer *,
                           const CPoint2D &, const CPoint2D &) {
    std::cerr << "drawKeyLine not implemented" << std::endl;
  }

  virtual void drawAxes(CGnuPlotPlot *, CGnuPlotRenderer *) {
    std::cerr << "drawAxes not implemented" << std::endl;
  }

  virtual CBBox2D fit(CGnuPlotPlot *) { return CBBox2D(); }

  virtual bool mouseTip(CGnuPlotPlot *, const CGnuPlotMouseEvent &,
                        CGnuPlotTipData &) { return false; }

  virtual void mousePress  (CGnuPlotPlot *, const CGnuPlotMouseEvent &) { }
  virtual void mouseMove   (CGnuPlotPlot *, const CGnuPlotMouseEvent &, bool) { }
  virtual void mouseRelease(CGnuPlotPlot *, const CGnuPlotMouseEvent &) { }

  virtual bool mouseProbe(CGnuPlotPlot *, CGnuPlotProbeEvent &) { return false; }

  virtual bool isAnimated() const { return false; }

  virtual int animateTimeout() const { return 30; }

  virtual void animate(CGnuPlotPlot *) const { }

 protected:
  CGnuPlotTypes::PlotStyle style_;
};

//------

class CGnuPlotStylePointsBase : public CGnuPlotStyleBase {
 public:
  CGnuPlotStylePointsBase(CGnuPlotTypes::PlotStyle style);

  virtual bool mouseProbe(CGnuPlotPlot *plot, CGnuPlotProbeEvent &probeEvent) override;
};

#endif


text:
<?php

namespace Drupal\hal\Normalizer;

use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\rest\LinkManager\LinkManagerInterface;
use Drupal\serialization\EntityResolver\EntityResolverInterface;
use Drupal\serialization\EntityResolver\UuidReferenceInterface;

/**
 * Converts the Drupal entity reference item object to HAL array structure.
 */
class EntityReferenceItemNormalizer extends FieldItemNormalizer implements UuidReferenceInterface {

  /**
   * The interface or class that this Normalizer supports.
   *
   * @var string
   */
  protected $supportedInterfaceOrClass = 'Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem';

  /**
   * The hypermedia link manager.
   *
   * @var \Drupal\rest\LinkManager\LinkManagerInterface
   */
  protected $linkManager;

  /**
   * The entity resolver.
   *
   * @var \Drupal\serialization\EntityResolver\EntityResolverInterface
   */
  protected $entityResolver;

  /**
   * Constructs an EntityReferenceItemNormalizer object.
   *
   * @param \Drupal\rest\LinkManager\LinkManagerInterface $link_manager
   *   The hypermedia link manager.
   * @param \Drupal\serialization\EntityResolver\EntityResolverInterface $entity_Resolver
   *   The entity resolver.
   */
  public function __construct(LinkManagerInterface $link_manager, EntityResolverInterface $entity_Resolver) {
    $this->linkManager = $link_manager;
    $this->entityResolver = $entity_Resolver;
  }

  /**
   * {@inheritdoc}
   */
  public function normalize($field_item, $format = NULL, array $context = array()) {
    /** @var $field_item \Drupal\Core\Field\FieldItemInterface */
    $target_entity = $field_item->get('entity')->getValue();

    // If this is not a content entity, let the parent implementation handle it,
    // only content entities are supported as embedded resources.
    if (!($target_entity instanceof FieldableEntityInterface)) {
      return parent::normalize($field_item, $format, $context);
    }

    // If the parent entity passed in a langcode, unset it before normalizing
    // the target entity. Otherwise, untranslatable fields of the target entity
    // will include the langcode.
    $langcode = isset($context['langcode']) ? $context['langcode'] : NULL;
    unset($context['langcode']);
    $context['included_fields'] = array('uuid');

    // Normalize the target entity.
    $embedded = $this->serializer->normalize($target_entity, $format, $context);
    $link = $embedded['_links']['self'];
    // If the field is translatable, add the langcode to the link relation
    // object. This does not indicate the language of the target entity.
    if ($langcode) {
      $embedded['lang'] = $link['lang'] = $langcode;
    }

    // The returned structure will be recursively merged into the normalized
    // entity so that the items are properly added to the _links and _embedded
    // objects.
    $field_name = $field_item->getParent()->getName();
    $entity = $field_item->getEntity();
    $field_uri = $this->linkManager->getRelationUri($entity->getEntityTypeId(), $entity->bundle(), $field_name, $context);
    return array(
      '_links' => array(
        $field_uri => array($link),
      ),
      '_embedded' => array(
        $field_uri => array($embedded),
      ),
    );
  }

  /**
   * {@inheritdoc}
   */
  protected function constructValue($data, $context) {
    $field_item = $context['target_instance'];
    $field_definition = $field_item->getFieldDefinition();
    $target_type = $field_definition->getSetting('target_type');
    $id = $this->entityResolver->resolve($this, $data, $target_type);
    if (isset($id)) {
      return array('target_id' => $id);
    }
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function getUuid($data) {
    if (isset($data['uuid'])) {
      $uuid = $data['uuid'];
      // The value may be a nested array like $uuid[0]['value'].
      if (is_array($uuid) && isset($uuid[0]['value'])) {
        $uuid = $uuid[0]['value'];
      }
      return $uuid;
    }
  }

}


text:
package reborncore.client.gui.builder.widget.tooltip;

import net.minecraft.client.font.TextRenderer;
import reborncore.client.gui.GuiUtil;

import java.util.ArrayList;
import java.util.Collections;

public class ToolTip {

	protected ArrayList<ToolTipLine> lines = new ArrayList<>();

	public ToolTip(String... textLines) {
		for (String text : textLines) {
			lines.add(new ToolTipLine(text));
		}
	}

	public ToolTip(ToolTipLine... toolTipLines) {
		Collections.addAll(lines, toolTipLines);
	}

	public ToolTip(int linesSize) {
		for (int i = 0; i < linesSize; i++) {
			lines.add(new ToolTipLine());
		}
	}

	public void addLine(ToolTipLine toolTipLine) {
		lines.add(toolTipLine);
	}

	public void removeLine(int index) {
		lines.remove(index);
	}

	public ToolTipLine getLine(int index) {
		return lines.get(index);
	}

	public ArrayList<ToolTipLine> getLines() {
		return lines;
	}

	protected void refresh() {}

	public void draw(TextRenderer font, int mouseX, int mouseY) {
		refresh();
		int maxLineLength = 0;
		int textX = mouseX + 3;
		int textY = mouseY + 3;
		for (ToolTipLine toolTipLine : lines) {
			toolTipLine.draw(font, textX, textY);
			textY += (font.fontHeight + 3);
			int lineWidth = toolTipLine.getWidth(font);
			if (lineWidth > maxLineLength) {
				maxLineLength = lineWidth;
			}
		}
		GuiUtil.drawTooltipBox(mouseX, mouseY, maxLineLength, textY + 3);
	}

}


text:
namespace doris {

class StatusTest : public testing::Test {
};

TEST_F(StatusTest, OK) {
    // default
    Status st;
    ASSERT_TRUE(st.ok());
    ASSERT_EQ("", st.get_error_msg());
    ASSERT_EQ("OK", st.to_string());
    // copy
    {
        Status other = st;
        ASSERT_TRUE(other.ok());
    }
    // move assign
    st = Status();
    ASSERT_TRUE(st.ok());
    // move construct
    {
        Status other = std::move(st);
        ASSERT_TRUE(other.ok());
    }
}

TEST_F(StatusTest, Error) {
    // default
    Status st = Status::InternalError("123");
    ASSERT_FALSE(st.ok());
    ASSERT_EQ("123", st.get_error_msg());
    ASSERT_EQ("Internal error: 123", st.to_string());
    // copy
    {
        Status other = st;
        ASSERT_FALSE(other.ok());
        ASSERT_EQ("123", st.get_error_msg());
    }
    // move assign
    st = Status::InternalError("456");
    ASSERT_FALSE(st.ok());
    ASSERT_EQ("456", st.get_error_msg());
    // move construct
    {
        Status other = std::move(st);
        ASSERT_FALSE(other.ok());
        ASSERT_EQ("456", other.get_error_msg());
        ASSERT_EQ("Internal error: 456", other.to_string());
        ASSERT_TRUE(st.ok());
        ASSERT_EQ("OK", st.to_string());
    }
}

}

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}