text:
<?php

/**
 * Implements a runnable command, like "arc diff" or "arc help".
 *
 * = Managing Conduit =
 *
 * Workflows have the builtin ability to open a Conduit connection to a
 * Phabricator installation, so methods can be invoked over the API. Workflows
 * may either not need this (e.g., "help"), or may need a Conduit but not
 * authentication (e.g., calling only public APIs), or may need a Conduit and
 * authentication (e.g., "arc diff").
 *
 * To specify that you need an //unauthenticated// conduit, override
 * @{method:requiresConduit} to return ##true##. To specify that you need an
 * //authenticated// conduit, override @{method:requiresAuthentication} to
 * return ##true##. You can also manually invoke @{method:establishConduit}
 * and/or @{method:authenticateConduit} later in a workflow to upgrade it.
 * Once a conduit is open, you can access the client by calling
 * @{method:getConduit}, which allows you to invoke methods. You can get
 * verified information about the user identity by calling @{method:getUserPHID}
 * or @{method:getUserName} after authentication occurs.
 *
 * = Scratch Files =
 *
 * Arcanist workflows can read and write 'scratch files', which are temporary
 * files stored in the project that persist across commands. They can be useful
 * if you want to save some state, or keep a copy of a long message the user
 * entered if something goes wrong.
 *
 *
 * @task  conduit   Conduit
 * @task  scratch   Scratch Files
 * @task  phabrep   Phabricator Repositories
 *
 * @stable
 */
abstract class ArcanistWorkflow extends Phobject {

  const COMMIT_DISABLE = 0;
  const COMMIT_ALLOW = 1;
  const COMMIT_ENABLE = 2;

  const AUTO_COMMIT_TITLE = 'Automatic commit by arc';

  private $commitMode = self::COMMIT_DISABLE;

  private $conduit;
  private $conduitURI;
  private $conduitCredentials;
  private $conduitAuthenticated;
  private $forcedConduitVersion;
  private $conduitTimeout;

  private $userPHID;
  private $userName;
  private $repositoryAPI;
  private $configurationManager;
  private $workingCopy;
  private $arguments;
  private $passedArguments;
  private $command;

  private $stashed;
  private $shouldAmend;

  private $projectInfo;
  private $repositoryInfo;
  private $repositoryReasons;

  private $arcanistConfiguration;
  private $parentWorkflow;
  private $workingDirectory;
  private $repositoryVersion;

  private $changeCache = array();

  public function __construct() {}

  abstract public function run();

  /**
   * Finalizes any cleanup operations that need to occur regardless of
   * whether the command succeeded or failed.
   */
  public function finalize() {
    // TODO: Remove this once ArcanistBaseWorkflow is gone.
    if ($this instanceof ArcanistBaseWorkflow) {
      phutil_deprecated(
        'ArcanistBaseWorkflow',
        'You should extend from `ArcanistWorkflow` instead.');
    }

    $this->finalizeWorkingCopy();
  }

  /**
   * Return the command used to invoke this workflow from the command like,
   * e.g. "help" for @{class:ArcanistHelpWorkflow}.
   *
   * @return string   The command a user types to invoke this workflow.
   */
  abstract public function getWorkflowName();

  /**
   * Return console formatted string with all command synopses.
   *
   * @return string  6-space indented list of available command synopses.
   */
  abstract public function getCommandSynopses();

  /**
   * Return console formatted string with command help printed in `arc help`.
   *
   * @return string  10-space indented help to use the command.
   */
  abstract public function getCommandHelp();

/* -(  Conduit  )------------------------------------------------------------ */

  /**
   * Set the URI which the workflow will open a conduit connection to when
   * @{method:establishConduit} is called. Arcanist makes an effort to set
   * this by default for all workflows (by reading ##.arcconfig## and/or the
   * value of ##--conduit-uri##) even if they don't need Conduit, so a workflow
   * can generally upgrade into a conduit workflow later by just calling
   * @{method:establishConduit}.
   *
   * You generally should not need to call this method unless you are
   * specifically overriding the default URI. It is normally sufficient to
   * just invoke @{method:establishConduit}.
   *
   * NOTE: You can not call this after a conduit has been established.
   *
   * @param string  The URI to open a conduit to when @{method:establishConduit}
   *                is called.
   * @return this
   * @task conduit
   */
  final public function setConduitURI($conduit_uri) {
    if ($this->conduit) {
      throw new Exception(
        'You can not change the Conduit URI after a conduit is already open.');
    }
    $this->conduitURI = $conduit_uri;
    return $this;
  }

  /**
   * Returns the URI the conduit connection within the workflow uses.
   *
   * @return string
   * @task conduit
   */
  final public function getConduitURI() {
    return $this->conduitURI;
  }

  /**
   * Open a conduit channel to the server which was previously configured by
   * calling @{method:setConduitURI}. Arcanist will do this automatically if
   * the workflow returns ##true## from @{method:requiresConduit}, or you can
   * later upgrade a workflow and build a conduit by invoking it manually.
   *
   * You must establish a conduit before you can make conduit calls.
   *
   * NOTE: You must call @{method:setConduitURI} before you can call this
   * method.
   *
   * @return this
   * @task conduit
   */
  final public function establishConduit() {
    if ($this->conduit) {
      return $this;
    }

    if (!$this->conduitURI) {
      throw new Exception(
        'You must specify a Conduit URI with setConduitURI() before you can '.
        'establish a conduit.');
    }

    $this->conduit = new ConduitClient($this->conduitURI);

    if ($this->conduitTimeout) {
      $this->conduit->setTimeout($this->conduitTimeout);
    }

    $user = $this->getConfigFromAnySource('http.basicauth.user');
    $pass = $this->getConfigFromAnySource('http.basicauth.pass');
    if ($user !== null && $pass !== null) {
      $this->conduit->setBasicAuthCredentials($user, $pass);
    }

    return $this;
  }

  final public function getConfigFromAnySource($key) {
    return $this->configurationManager->getConfigFromAnySource($key);
  }

  /**
   * Set credentials which will be used to authenticate against Conduit. These
   * credentials can then be used to establish an authenticated connection to
   * conduit by calling @{method:authenticateConduit}. Arcanist sets some
   * defaults for all workflows regardless of whether or not they return true
   * from @{method:requireAuthentication}, based on the ##~/.arcrc## and
   * ##.arcconf## files if they are present. Thus, you can generally upgrade a
   * workflow which does not require authentication into an authenticated
   * workflow by later invoking @{method:requireAuthentication}. You should not
   * normally need to call this method unless you are specifically overriding
   * the defaults.
   *
   * NOTE: You can not call this method after calling
   * @{method:authenticateConduit}.
   *
   * @param dict  A credential dictionary, see @{method:authenticateConduit}.
   * @return this
   * @task conduit
   */
  final public function setConduitCredentials(array $credentials) {
    if ($this->isConduitAuthenticated()) {
      throw new Exception(
        'You may not set new credentials after authenticating conduit.');
    }

    $this->conduitCredentials = $credentials;
    return $this;
  }

  /**
   * Force arc to identify with a specific Conduit version during the
   * protocol handshake. This is primarily useful for development (especially
   * for sending diffs which bump the client Conduit version), since the client
   * still actually speaks the builtin version of the protocol.
   *
   * Controlled by the --conduit-version flag.
   *
   * @param int Version the client should pretend to be.
   * @return this
   * @task conduit
   */
  final public function forceConduitVersion($version) {
    $this->forcedConduitVersion = $version;
    return $this;
  }

  /**
   * Get the protocol version the client should identify with.
   *
   * @return int Version the client should claim to be.
   * @task conduit
   */
  final public function getConduitVersion() {
    return nonempty($this->forcedConduitVersion, 6);
  }

  /**
   * Override the default timeout for Conduit.
   *
   * Controlled by the --conduit-timeout flag.
   *
   * @param float Timeout, in seconds.
   * @return this
   * @task conduit
   */
  final public function setConduitTimeout($timeout) {
    $this->conduitTimeout = $timeout;
    if ($this->conduit) {
      $this->conduit->setConduitTimeout($timeout);
    }
    return $this;
  }

  /**
   * Open and authenticate a conduit connection to a Phabricator server using
   * provided credentials. Normally, Arcanist does this for you automatically
   * when you return true from @{method:requiresAuthentication}, but you can
   * also upgrade an existing workflow to one with an authenticated conduit
   * by invoking this method manually.
   *
   * You must authenticate the conduit before you can make authenticated conduit
   * calls (almost all calls require authentication).
   *
   * This method uses credentials provided via @{method:setConduitCredentials}
   * to authenticate to the server:
   *
   *    - ##user## (required) The username to authenticate with.
   *    - ##certificate## (required) The Conduit certificate to use.
   *    - ##description## (optional) Description of the invoking command.
   *
   * Successful authentication allows you to call @{method:getUserPHID} and
   * @{method:getUserName}, as well as use the client you access with
   * @{method:getConduit} to make authenticated calls.
   *
   * NOTE: You must call @{method:setConduitURI} and
   * @{method:setConduitCredentials} before you invoke this method.
   *
   * @return this
   * @task conduit
   */
  final public function authenticateConduit() {
    if ($this->isConduitAuthenticated()) {
      return $this;
    }

    $this->establishConduit();
    $credentials = $this->conduitCredentials;

    try {
      if (!$credentials) {
        throw new Exception(
          'Set conduit credentials with setConduitCredentials() before '.
          'authenticating conduit!');
      }

      if (empty($credentials['user'])) {
        throw new ConduitClientException(
          'ERR-INVALID-USER',
          'Empty user in credentials.');
      }
      if (empty($credentials['certificate'])) {
        throw new ConduitClientException(
          'ERR-NO-CERTIFICATE',
          'Empty certificate in credentials.');
      }

      $description = idx($credentials, 'description', '');
      $user        = $credentials['user'];
      $certificate = $credentials['certificate'];

      $connection = $this->getConduit()->callMethodSynchronous(
        'conduit.connect',
        array(
          'client'              => 'arc',
          'clientVersion'       => $this->getConduitVersion(),
          'clientDescription'   => php_uname('n').':'.$description,
          'user'                => $user,
          'certificate'         => $certificate,
          'host'                => $this->conduitURI,
        ));
    } catch (ConduitClientException $ex) {
      if ($ex->getErrorCode() == 'ERR-NO-CERTIFICATE' ||
          $ex->getErrorCode() == 'ERR-INVALID-USER') {
        $conduit_uri = $this->conduitURI;
        $message =
          "\n".
          phutil_console_format(
            'YOU NEED TO __INSTALL A CERTIFICATE__ TO LOGIN TO PHABRICATOR').
          "\n\n".
          phutil_console_format(
            '    To do this, run: **arc install-certificate**').
          "\n\n".
          "The server '{$conduit_uri}' rejected your request:".
          "\n".
          $ex->getMessage();
        throw new ArcanistUsageException($message);
      } else if ($ex->getErrorCode() == 'NEW-ARC-VERSION') {

        // Cleverly disguise this as being AWESOME!!!

        echo phutil_console_format("**New Version Available!**\n\n");
        echo phutil_console_wrap($ex->getMessage());
        echo "\n\n";
        echo "In most cases, arc can be upgraded automatically.\n";

        $ok = phutil_console_confirm(
          'Upgrade arc now?',
          $default_no = false);
        if (!$ok) {
          throw $ex;
        }

        $root = dirname(phutil_get_library_root('arcanist'));

        chdir($root);
        $err = phutil_passthru('%s upgrade', $root.'/bin/arc');
        if (!$err) {
          echo "\nTry running your arc command again.\n";
        }
        exit(1);
      } else {
        throw $ex;
      }
    }

    $this->userName = $user;
    $this->userPHID = $connection['userPHID'];

    $this->conduitAuthenticated = true;

    return $this;
  }

  /**
   * @return bool True if conduit is authenticated, false otherwise.
   * @task conduit
   */
  final protected function isConduitAuthenticated() {
    return (bool)$this->conduitAuthenticated;
  }

  /**
   * Override this to return true if your workflow requires a conduit channel.
   * Arc will build the channel for you before your workflow executes. This
   * implies that you only need an unauthenticated channel; if you need
   * authentication, override @{method:requiresAuthentication}.
   *
   * @return bool True if arc should build a conduit channel before running
   *              the workflow.
   * @task conduit
   */
  public function requiresConduit() {
    return false;
  }

  /**
   * Override this to return true if your workflow requires an authenticated
   * conduit channel. This implies that it requires a conduit. Arc will build
   * and authenticate the channel for you before the workflow executes.
   *
   * @return bool True if arc should build an authenticated conduit channel
   *              before running the workflow.
   * @task conduit
   */
  public function requiresAuthentication() {
    return false;
  }

  /**
   * Returns the PHID for the user once they've authenticated via Conduit.
   *
   * @return phid Authenticated user PHID.
   * @task conduit
   */
  final public function getUserPHID() {
    if (!$this->userPHID) {
      $workflow = get_class($this);
      throw new Exception(
        "This workflow ('{$workflow}') requires authentication, override ".
        "requiresAuthentication() to return true.");
    }
    return $this->userPHID;
  }

  /**
   * Return the username for the user once they've authenticated via Conduit.
   *
   * @return string Authenticated username.
   * @task conduit
   */
  final public function getUserName() {
    return $this->userName;
  }

  /**
   * Get the established @{class@libphutil:ConduitClient} in order to make
   * Conduit method calls. Before the client is available it must be connected,
   * either implicitly by making @{method:requireConduit} or
   * @{method:requireAuthentication} return true, or explicitly by calling
   * @{method:establishConduit} or @{method:authenticateConduit}.
   *
   * @return @{class@libphutil:ConduitClient} Live conduit client.
   * @task conduit
   */
  final public function getConduit() {
    if (!$this->conduit) {
      $workflow = get_class($this);
      throw new Exception(
        "This workflow ('{$workflow}') requires a Conduit, override ".
        "requiresConduit() to return true.");
    }
    return $this->conduit;
  }

  final public function setArcanistConfiguration(
    ArcanistConfiguration $arcanist_configuration) {

    $this->arcanistConfiguration = $arcanist_configuration;
    return $this;
  }

  final public function getArcanistConfiguration() {
    return $this->arcanistConfiguration;
  }

  final public function setConfigurationManager(
    ArcanistConfigurationManager $arcanist_configuration_manager) {

    $this->configurationManager = $arcanist_configuration_manager;
    return $this;
  }

  final public function getConfigurationManager() {
    return $this->configurationManager;
  }

  public function requiresWorkingCopy() {
    return false;
  }

  public function desiresWorkingCopy() {
    return false;
  }

  public function requiresRepositoryAPI() {
    return false;
  }

  public function desiresRepositoryAPI() {
    return false;
  }

  final public function setCommand($command) {
    $this->command = $command;
    return $this;
  }

  final public function getCommand() {
    return $this->command;
  }

  public function getArguments() {
    return array();
  }

  final public function setWorkingDirectory($working_directory) {
    $this->workingDirectory = $working_directory;
    return $this;
  }

  final public function getWorkingDirectory() {
    return $this->workingDirectory;
  }

  final private function setParentWorkflow($parent_workflow) {
    $this->parentWorkflow = $parent_workflow;
    return $this;
  }

  final protected function getParentWorkflow() {
    return $this->parentWorkflow;
  }

  final public function buildChildWorkflow($command, array $argv) {
    $arc_config = $this->getArcanistConfiguration();
    $workflow = $arc_config->buildWorkflow($command);
    $workflow->setParentWorkflow($this);
    $workflow->setCommand($command);
    $workflow->setConfigurationManager($this->getConfigurationManager());

    if ($this->repositoryAPI) {
      $workflow->setRepositoryAPI($this->repositoryAPI);
    }

    if ($this->userPHID) {
      $workflow->userPHID = $this->getUserPHID();
      $workflow->userName = $this->getUserName();
    }

    if ($this->conduit) {
      $workflow->conduit = $this->conduit;
      $workflow->setConduitCredentials($this->conduitCredentials);
      $workflow->conduitAuthenticated = $this->conduitAuthenticated;
    }

    if ($this->workingCopy) {
      $workflow->setWorkingCopy($this->workingCopy);
    }

    $workflow->setArcanistConfiguration($arc_config);

    $workflow->parseArguments(array_values($argv));

    return $workflow;
  }

  final public function getArgument($key, $default = null) {
    return idx($this->arguments, $key, $default);
  }

  final public function getPassedArguments() {
    return $this->passedArguments;
  }

  final public function getCompleteArgumentSpecification() {
    $spec = $this->getArguments();
    $arc_config = $this->getArcanistConfiguration();
    $command = $this->getCommand();
    $spec += $arc_config->getCustomArgumentsForCommand($command);

    return $spec;
  }

  final public function parseArguments(array $args) {
    $this->passedArguments = $args;

    $spec = $this->getCompleteArgumentSpecification();

    $dict = array();

    $more_key = null;
    if (!empty($spec['*'])) {
      $more_key = $spec['*'];
      unset($spec['*']);
      $dict[$more_key] = array();
    }

    $short_to_long_map = array();
    foreach ($spec as $long => $options) {
      if (!empty($options['short'])) {
        $short_to_long_map[$options['short']] = $long;
      }
    }

    foreach ($spec as $long => $options) {
      if (!empty($options['repeat'])) {
        $dict[$long] = array();
      }
    }

    $more = array();
    for ($ii = 0; $ii < count($args); $ii++) {
      $arg = $args[$ii];
      $arg_name = null;
      $arg_key = null;
      if ($arg == '--') {
        $more = array_merge(
          $more,
          array_slice($args, $ii + 1));
        break;
      } else if (!strncmp($arg, '--', 2)) {
        $arg_key = substr($arg, 2);
        if (!array_key_exists($arg_key, $spec)) {
          $corrected = ArcanistConfiguration::correctArgumentSpelling(
            $arg_key,
            array_keys($spec));
          if (count($corrected) == 1) {
            PhutilConsole::getConsole()->writeErr(
              pht(
                "(Assuming '%s' is the British spelling of '%s'.)",
                '--'.$arg_key,
                '--'.head($corrected))."\n");
            $arg_key = head($corrected);
          } else {
            throw new ArcanistUsageException(pht(
              "Unknown argument '%s'. Try 'arc help'.",
              $arg_key));
          }
        }
      } else if (!strncmp($arg, '-', 1)) {
        $arg_key = substr($arg, 1);
        if (empty($short_to_long_map[$arg_key])) {
          throw new ArcanistUsageException(pht(
            "Unknown argument '%s'. Try 'arc help'.",
            $arg_key));
        }
        $arg_key = $short_to_long_map[$arg_key];
      } else {
        $more[] = $arg;
        continue;
      }

      $options = $spec[$arg_key];
      if (empty($options['param'])) {
        $dict[$arg_key] = true;
      } else {
        if ($ii == count($args) - 1) {
          throw new ArcanistUsageException(pht(
            "Option '%s' requires a parameter.",
            $arg));
        }
        if (!empty($options['repeat'])) {
          $dict[$arg_key][] = $args[$ii + 1];
        } else {
          $dict[$arg_key] = $args[$ii + 1];
        }
        $ii++;
      }
    }

    if ($more) {
      if ($more_key) {
        $dict[$more_key] = $more;
      } else {
        $example = reset($more);
        throw new ArcanistUsageException(pht(
          "Unrecognized argument '%s'. Try 'arc help'.",
          $example));
      }
    }

    foreach ($dict as $key => $value) {
      if (empty($spec[$key]['conflicts'])) {
        continue;
      }
      foreach ($spec[$key]['conflicts'] as $conflict => $more) {
        if (isset($dict[$conflict])) {
          if ($more) {
            $more = ': '.$more;
          } else {
            $more = '.';
          }
          // TODO: We'll always display these as long-form, when the user might
          // have typed them as short form.
          throw new ArcanistUsageException(
            "Arguments '--{$key}' and '--{$conflict}' are mutually exclusive".
            $more);
        }
      }
    }

    $this->arguments = $dict;

    $this->didParseArguments();

    return $this;
  }

  protected function didParseArguments() {
    // Override this to customize workflow argument behavior.
  }

  final public function getWorkingCopy() {
    $working_copy = $this->getConfigurationManager()->getWorkingCopyIdentity();
    if (!$working_copy) {
      $workflow = get_class($this);
      throw new Exception(
        "This workflow ('{$workflow}') requires a working copy, override ".
        "requiresWorkingCopy() to return true.");
    }
    return $working_copy;
  }

  final public function setWorkingCopy(
    ArcanistWorkingCopyIdentity $working_copy) {
    $this->workingCopy = $working_copy;
    return $this;
  }

  final public function setRepositoryAPI($api) {
    $this->repositoryAPI = $api;
    return $this;
  }

  final public function hasRepositoryAPI() {
    try {
      return (bool)$this->getRepositoryAPI();
    } catch (Exception $ex) {
      return false;
    }
  }

  final public function getRepositoryAPI() {
    if (!$this->repositoryAPI) {
      $workflow = get_class($this);
      throw new Exception(
        "This workflow ('{$workflow}') requires a Repository API, override ".
        "requiresRepositoryAPI() to return true.");
    }
    return $this->repositoryAPI;
  }

  final protected function shouldRequireCleanUntrackedFiles() {
    return empty($this->arguments['allow-untracked']);
  }

  final public function setCommitMode($mode) {
    $this->commitMode = $mode;
    return $this;
  }

  final public function finalizeWorkingCopy() {
    if ($this->stashed) {
      $api = $this->getRepositoryAPI();
      $api->unstashChanges();
      echo pht('Restored stashed changes to the working directory.')."\n";
    }
  }

  final public function requireCleanWorkingCopy() {
    $api = $this->getRepositoryAPI();

    $must_commit = array();

    $working_copy_desc = phutil_console_format(
      "  Working copy: __%s__\n\n",
      $api->getPath());

    $untracked = $api->getUntrackedChanges();
    if ($this->shouldRequireCleanUntrackedFiles()) {

      if (!empty($untracked)) {
        echo "You have untracked files in this working copy.\n\n".
             $working_copy_desc.
             "  Untracked files in working copy:\n".
             "    ".implode("\n    ", $untracked)."\n\n";

        if ($api instanceof ArcanistGitAPI) {
          echo phutil_console_wrap(
            "Since you don't have '.gitignore' rules for these files and have ".
            "not listed them in '.git/info/exclude', you may have forgotten ".
            "to 'git add' them to your commit.\n");
        } else if ($api instanceof ArcanistSubversionAPI) {
          echo phutil_console_wrap(
            "Since you don't have 'svn:ignore' rules for these files, you may ".
            "have forgotten to 'svn add' them.\n");
        } else if ($api instanceof ArcanistMercurialAPI) {
          echo phutil_console_wrap(
            "Since you don't have '.hgignore' rules for these files, you ".
            "may have forgotten to 'hg add' them to your commit.\n");
        }

        if ($this->askForAdd($untracked)) {
          $api->addToCommit($untracked);
          $must_commit += array_flip($untracked);
        } else if ($this->commitMode == self::COMMIT_DISABLE) {
          $prompt = $this->getAskForAddPrompt($untracked);
          if (phutil_console_confirm($prompt)) {
            throw new ArcanistUsageException(pht(
              "Add these files and then run 'arc %s' again.",
              $this->getWorkflowName()));
          }
        }

      }
    }

    // NOTE: this is a subversion-only concept.
    $incomplete = $api->getIncompleteChanges();
    if ($incomplete) {
      throw new ArcanistUsageException(
        "You have incompletely checked out directories in this working copy. ".
        "Fix them before proceeding.\n\n".
        $working_copy_desc.
        "  Incomplete directories in working copy:\n".
        "    ".implode("\n    ", $incomplete)."\n\n".
        "You can fix these paths by running 'svn update' on them.");
    }

    $conflicts = $api->getMergeConflicts();
    if ($conflicts) {
      throw new ArcanistUsageException(
        "You have merge conflicts in this working copy. Resolve merge ".
        "conflicts before proceeding.\n\n".
        $working_copy_desc.
        "  Conflicts in working copy:\n".
        "    ".implode("\n    ", $conflicts)."\n");
    }

    $missing = $api->getMissingChanges();
    if ($missing) {
      throw new ArcanistUsageException(
        pht(
          "You have missing files in this working copy. Revert or formally ".
          "remove them (with `svn rm`) before proceeding.\n\n".
          "%s".
          "  Missing files in working copy:\n%s\n",
          $working_copy_desc,
          "    ".implode("\n    ", $missing)));
    }

    $unstaged = $api->getUnstagedChanges();
    if ($unstaged) {
      echo "You have unstaged changes in this working copy.\n\n".
        $working_copy_desc.
        "  Unstaged changes in working copy:\n".
        "    ".implode("\n    ", $unstaged)."\n";
      if ($this->askForAdd($unstaged)) {
        $api->addToCommit($unstaged);
        $must_commit += array_flip($unstaged);
      } else {
        $permit_autostash = $this->getConfigFromAnySource(
          'arc.autostash',
          false);
        if ($permit_autostash && $api->canStashChanges()) {
          echo "Stashing uncommitted changes. (You can restore them with ".
               "`git stash pop`.)\n";
          $api->stashChanges();
          $this->stashed = true;
        } else {
          throw new ArcanistUsageException(
            'Stage and commit (or revert) them before proceeding.');
        }
      }
    }

    $uncommitted = $api->getUncommittedChanges();
    foreach ($uncommitted as $key => $path) {
      if (array_key_exists($path, $must_commit)) {
        unset($uncommitted[$key]);
      }
    }
    if ($uncommitted) {
      echo "You have uncommitted changes in this working copy.\n\n".
        $working_copy_desc.
        "  Uncommitted changes in working copy:\n".
        "    ".implode("\n    ", $uncommitted)."\n";
      if ($this->askForAdd($uncommitted)) {
        $must_commit += array_flip($uncommitted);
      } else {
        throw new ArcanistUncommittedChangesException(
          'Commit (or revert) them before proceeding.');
      }
    }

    if ($must_commit) {
      if ($this->getShouldAmend()) {
        $commit = head($api->getLocalCommitInformation());
        $api->amendCommit($commit['message']);
      } else if ($api->supportsLocalCommits()) {
        $commit_message = phutil_console_prompt('Enter commit message:');
        if ($commit_message == '') {
          $commit_message = self::AUTO_COMMIT_TITLE;
        }
        $api->doCommit($commit_message);
      }
    }
  }

  private function getShouldAmend() {
    if ($this->shouldAmend === null) {
      $this->shouldAmend = $this->calculateShouldAmend();
    }
    return $this->shouldAmend;
  }

  private function calculateShouldAmend() {
    $api = $this->getRepositoryAPI();

    if ($this->isHistoryImmutable() || !$api->supportsAmend()) {
      return false;
    }

    $commits = $api->getLocalCommitInformation();
    if (!$commits) {
      return false;
    }

    $commit = reset($commits);
    $message = ArcanistDifferentialCommitMessage::newFromRawCorpus(
      $commit['message']);

    if ($message->getGitSVNBaseRevision()) {
      return false;
    }

    if ($api->getAuthor() != $commit['author']) {
      return false;
    }

    if ($message->getRevisionID() && $this->getArgument('create')) {
      return false;
    }

    // TODO: Check commits since tracking branch. If empty then return false.

    $repository = $this->loadProjectRepository();
    if ($repository) {
      $callsign = $repository['callsign'];
      $known_commits = $this->getConduit()->callMethodSynchronous(
        'diffusion.getcommits',
        array('commits' => array('r'.$callsign.$commit['commit'])));
      if (ifilter($known_commits, 'error', $negate = true)) {
        return false;
      }
    }

    if (!$message->getRevisionID()) {
      return true;
    }

    $in_working_copy = $api->loadWorkingCopyDifferentialRevisions(
      $this->getConduit(),
      array(
        'authors' => array($this->getUserPHID()),
        'status' => 'status-open',
      ));
    if ($in_working_copy) {
      return true;
    }

    return false;
  }

  private function askForAdd(array $files) {
    if ($this->commitMode == self::COMMIT_DISABLE) {
      return false;
    }
    if ($this->commitMode == self::COMMIT_ENABLE) {
      return true;
    }
    $prompt = $this->getAskForAddPrompt($files);
    return phutil_console_confirm($prompt);
  }

  private function getAskForAddPrompt(array $files) {
    if ($this->getShouldAmend()) {
      $prompt = pht(
        'Do you want to amend these files to the commit?',
        count($files));
    } else {
      $prompt = pht(
        'Do you want to add these files to the commit?',
        count($files));
    }
    return $prompt;
  }

  final protected function loadDiffBundleFromConduit(
    ConduitClient $conduit,
    $diff_id) {

    return $this->loadBundleFromConduit(
      $conduit,
      array(
      'diff_id' => $diff_id,
    ));
  }

  final protected function loadRevisionBundleFromConduit(
    ConduitClient $conduit,
    $revision_id) {

    return $this->loadBundleFromConduit(
      $conduit,
      array(
      'revision_id' => $revision_id,
    ));
  }

  final private function loadBundleFromConduit(
    ConduitClient $conduit,
    $params) {

    $future = $conduit->callMethod('differential.getdiff', $params);
    $diff = $future->resolve();

    $changes = array();
    foreach ($diff['changes'] as $changedict) {
      $changes[] = ArcanistDiffChange::newFromDictionary($changedict);
    }
    $bundle = ArcanistBundle::newFromChanges($changes);
    $bundle->setConduit($conduit);
    // since the conduit method has changes, assume that these fields
    // could be unset
    $bundle->setProjectID(idx($diff, 'projectName'));
    $bundle->setBaseRevision(idx($diff, 'sourceControlBaseRevision'));
    $bundle->setRevisionID(idx($diff, 'revisionID'));
    $bundle->setAuthorName(idx($diff, 'authorName'));
    $bundle->setAuthorEmail(idx($diff, 'authorEmail'));
    return $bundle;
  }

  /**
   * Return a list of lines changed by the current diff, or ##null## if the
   * change list is meaningless (for example, because the path is a directory
   * or binary file).
   *
   * @param string      Path within the repository.
   * @param string      Change selection mode (see ArcanistDiffHunk).
   * @return list|null  List of changed line numbers, or null to indicate that
   *                    the path is not a line-oriented text file.
   */
  final protected function getChangedLines($path, $mode) {
    $repository_api = $this->getRepositoryAPI();
    $full_path = $repository_api->getPath($path);
    if (is_dir($full_path)) {
      return null;
    }

    if (!file_exists($full_path)) {
      return null;
    }

    $change = $this->getChange($path);

    if ($change->getFileType() !== ArcanistDiffChangeType::FILE_TEXT) {
      return null;
    }

    $lines = $change->getChangedLines($mode);
    return array_keys($lines);
  }

  final protected function getChange($path) {
    $repository_api = $this->getRepositoryAPI();

    // TODO: Very gross
    $is_git = ($repository_api instanceof ArcanistGitAPI);
    $is_hg = ($repository_api instanceof ArcanistMercurialAPI);
    $is_svn = ($repository_api instanceof ArcanistSubversionAPI);

    if ($is_svn) {
      // NOTE: In SVN, we don't currently support a "get all local changes"
      // operation, so special case it.
      if (empty($this->changeCache[$path])) {
        $diff = $repository_api->getRawDiffText($path);
        $parser = $this->newDiffParser();
        $changes = $parser->parseDiff($diff);
        if (count($changes) != 1) {
          throw new Exception('Expected exactly one change.');
        }
        $this->changeCache[$path] = reset($changes);
      }
    } else if ($is_git || $is_hg) {
      if (empty($this->changeCache)) {
        $changes = $repository_api->getAllLocalChanges();
        foreach ($changes as $change) {
          $this->changeCache[$change->getCurrentPath()] = $change;
        }
      }
    } else {
      throw new Exception('Missing VCS support.');
    }

    if (empty($this->changeCache[$path])) {
      if ($is_git || $is_hg) {
        // This can legitimately occur under git/hg if you make a change,
        // "git/hg commit" it, and then revert the change in the working copy
        // and run "arc lint".
        $change = new ArcanistDiffChange();
        $change->setCurrentPath($path);
        return $change;
      } else {
        throw new Exception(
          "Trying to get change for unchanged path '{$path}'!");
      }
    }

    return $this->changeCache[$path];
  }

  final public function willRunWorkflow() {
    $spec = $this->getCompleteArgumentSpecification();
    foreach ($this->arguments as $arg => $value) {
      if (empty($spec[$arg])) {
        continue;
      }
      $options = $spec[$arg];
      if (!empty($options['supports'])) {
        $system_name = $this->getRepositoryAPI()->getSourceControlSystemName();
        if (!in_array($system_name, $options['supports'])) {
          $extended_info = null;
          if (!empty($options['nosupport'][$system_name])) {
            $extended_info = ' '.$options['nosupport'][$system_name];
          }
          throw new ArcanistUsageException(
            "Option '--{$arg}' is not supported under {$system_name}.".
            $extended_info);
        }
      }
    }
  }

  final protected function normalizeRevisionID($revision_id) {
    return preg_replace('/^D/i', '', $revision_id);
  }

  protected function shouldShellComplete() {
    return true;
  }

  protected function getShellCompletions(array $argv) {
    return array();
  }

  protected function getSupportedRevisionControlSystems() {
    return array('any');
  }

  final protected function getPassthruArgumentsAsMap($command) {
    $map = array();
    foreach ($this->getCompleteArgumentSpecification() as $key => $spec) {
      if (!empty($spec['passthru'][$command])) {
        if (isset($this->arguments[$key])) {
          $map[$key] = $this->arguments[$key];
        }
      }
    }
    return $map;
  }

  final protected function getPassthruArgumentsAsArgv($command) {
    $spec = $this->getCompleteArgumentSpecification();
    $map = $this->getPassthruArgumentsAsMap($command);
    $argv = array();
    foreach ($map as $key => $value) {
      $argv[] = '--'.$key;
      if (!empty($spec[$key]['param'])) {
        $argv[] = $value;
      }
    }
    return $argv;
  }

  /**
   * Write a message to stderr so that '--json' flags or stdout which is meant
   * to be piped somewhere aren't disrupted.
   *
   * @param string  Message to write to stderr.
   * @return void
   */
  final protected function writeStatusMessage($msg) {
    fwrite(STDERR, $msg);
  }

  final protected function isHistoryImmutable() {
    $repository_api = $this->getRepositoryAPI();

    $config = $this->getConfigFromAnySource('history.immutable');
    if ($config !== null) {
      return $config;
    }

    return $repository_api->isHistoryDefaultImmutable();
  }

  /**
   * Workflows like 'lint' and 'unit' operate on a list of working copy paths.
   * The user can either specify the paths explicitly ("a.js b.php"), or by
   * specifying a revision ("--rev a3f10f1f") to select all paths modified
   * since that revision, or by omitting both and letting arc choose the
   * default relative revision.
   *
   * This method takes the user's selections and returns the paths that the
   * workflow should act upon.
   *
   * @param   list          List of explicitly provided paths.
   * @param   string|null   Revision name, if provided.
   * @param   mask          Mask of ArcanistRepositoryAPI flags to exclude.
   *                        Defaults to ArcanistRepositoryAPI::FLAG_UNTRACKED.
   * @return  list          List of paths the workflow should act on.
   */
  final protected function selectPathsForWorkflow(
    array $paths,
    $rev,
    $omit_mask = null) {

    if ($omit_mask === null) {
      $omit_mask = ArcanistRepositoryAPI::FLAG_UNTRACKED;
    }

    if ($paths) {
      $working_copy = $this->getWorkingCopy();
      foreach ($paths as $key => $path) {
        $full_path = Filesystem::resolvePath($path);
        if (!Filesystem::pathExists($full_path)) {
          throw new ArcanistUsageException("Path '{$path}' does not exist!");
        }
        $relative_path = Filesystem::readablePath(
          $full_path,
          $working_copy->getProjectRoot());
        $paths[$key] = $relative_path;
      }
    } else {
      $repository_api = $this->getRepositoryAPI();

      if ($rev) {
        $this->parseBaseCommitArgument(array($rev));
      }

      $paths = $repository_api->getWorkingCopyStatus();
      foreach ($paths as $path => $flags) {
        if ($flags & $omit_mask) {
          unset($paths[$path]);
        }
      }
      $paths = array_keys($paths);
    }

    return array_values($paths);
  }

  final protected function renderRevisionList(array $revisions) {
    $list = array();
    foreach ($revisions as $revision) {
      $list[] = '     - D'.$revision['id'].': '.$revision['title']."\n";
    }
    return implode('', $list);
  }

/* -(  Scratch Files  )------------------------------------------------------ */

  /**
   * Try to read a scratch file, if it exists and is readable.
   *
   * @param string Scratch file name.
   * @return mixed String for file contents, or false for failure.
   * @task scratch
   */
  final protected function readScratchFile($path) {
    if (!$this->repositoryAPI) {
      return false;
    }
    return $this->getRepositoryAPI()->readScratchFile($path);
  }

  /**
   * Try to read a scratch JSON file, if it exists and is readable.
   *
   * @param string Scratch file name.
   * @return array Empty array for failure.
   * @task scratch
   */
  final protected function readScratchJSONFile($path) {
    $file = $this->readScratchFile($path);
    if (!$file) {
      return array();
    }
    return json_decode($file, true);
  }

  /**
   * Try to write a scratch file, if there's somewhere to put it and we can
   * write there.
   *
   * @param  string Scratch file name to write.
   * @param  string Data to write.
   * @return bool   True on success, false on failure.
   * @task scratch
   */
  final protected function writeScratchFile($path, $data) {
    if (!$this->repositoryAPI) {
      return false;
    }
    return $this->getRepositoryAPI()->writeScratchFile($path, $data);
  }

  /**
   * Try to write a scratch JSON file, if there's somewhere to put it and we can
   * write there.
   *
   * @param  string Scratch file name to write.
   * @param  array Data to write.
   * @return bool   True on success, false on failure.
   * @task scratch
   */
  final protected function writeScratchJSONFile($path, array $data) {
    return $this->writeScratchFile($path, json_encode($data));
  }

  /**
   * Try to remove a scratch file.
   *
   * @param   string  Scratch file name to remove.
   * @return  bool    True if the file was removed successfully.
   * @task scratch
   */
  final protected function removeScratchFile($path) {
    if (!$this->repositoryAPI) {
      return false;
    }
    return $this->getRepositoryAPI()->removeScratchFile($path);
  }

  /**
   * Get a human-readable description of the scratch file location.
   *
   * @param string  Scratch file name.
   * @return mixed  String, or false on failure.
   * @task scratch
   */
  final protected function getReadableScratchFilePath($path) {
    if (!$this->repositoryAPI) {
      return false;
    }
    return $this->getRepositoryAPI()->getReadableScratchFilePath($path);
  }

  /**
   * Get the path to a scratch file, if possible.
   *
   * @param string  Scratch file name.
   * @return mixed  File path, or false on failure.
   * @task scratch
   */
  final protected function getScratchFilePath($path) {
    if (!$this->repositoryAPI) {
      return false;
    }
    return $this->getRepositoryAPI()->getScratchFilePath($path);
  }

  final protected function getRepositoryEncoding() {
    $default = 'UTF-8';
    return nonempty(idx($this->getProjectInfo(), 'encoding'), $default);
  }

  final protected function getProjectInfo() {
    if ($this->projectInfo === null) {
      $project_id = $this->getWorkingCopy()->getProjectID();
      if (!$project_id) {
        $this->projectInfo = array();
      } else {
        try {
          $this->projectInfo = $this->getConduit()->callMethodSynchronous(
            'arcanist.projectinfo',
            array(
              'name' => $project_id,
            ));
        } catch (ConduitClientException $ex) {
          if ($ex->getErrorCode() != 'ERR-BAD-ARCANIST-PROJECT') {
            throw $ex;
          }

          // TODO: Implement a proper query method that doesn't throw on
          // project not found. We just swallow this because some pathways,
          // like Git with uncommitted changes in a repository with a new
          // project ID, may attempt to access project information before
          // the project is created. See T2153.
          return array();
        }
      }
    }

    return $this->projectInfo;
  }

  final protected function loadProjectRepository() {
    $project = $this->getProjectInfo();
    if (isset($project['repository'])) {
      return $project['repository'];
    }
    // NOTE: The rest of the code is here for backwards compatibility.

    $repository_phid = idx($project, 'repositoryPHID');
    if (!$repository_phid) {
      return array();
    }

    $repositories = $this->getConduit()->callMethodSynchronous(
      'repository.query',
      array());
    $repositories = ipull($repositories, null, 'phid');

    return idx($repositories, $repository_phid, array());
  }

  final protected function newInteractiveEditor($text) {
    $editor = new PhutilInteractiveEditor($text);

    $preferred = $this->getConfigFromAnySource('editor');
    if ($preferred) {
      $editor->setPreferredEditor($preferred);
    }

    return $editor;
  }

  final protected function newDiffParser() {
    $parser = new ArcanistDiffParser();
    if ($this->repositoryAPI) {
      $parser->setRepositoryAPI($this->getRepositoryAPI());
    }
    $parser->setWriteDiffOnFailure(true);
    return $parser;
  }

  final protected function resolveCall(ConduitFuture $method, $timeout = null) {
    try {
      return $method->resolve($timeout);
    } catch (ConduitClientException $ex) {
      if ($ex->getErrorCode() == 'ERR-CONDUIT-CALL') {
        echo phutil_console_wrap(
          "This feature requires a newer version of Phabricator. Please ".
          "update it using these instructions: ".
          "http://www.phabricator.com/docs/phabricator/article/".
          "Installation_Guide.html#updating-phabricator\n\n");
      }
      throw $ex;
    }
  }

  final protected function dispatchEvent($type, array $data) {
    $data += array(
      'workflow' => $this,
    );

    $event = new PhutilEvent($type, $data);
    PhutilEventEngine::dispatchEvent($event);

    return $event;
  }

  final public function parseBaseCommitArgument(array $argv) {
    if (!count($argv)) {
      return;
    }

    $api = $this->getRepositoryAPI();
    if (!$api->supportsCommitRanges()) {
      throw new ArcanistUsageException(
        'This version control system does not support commit ranges.');
    }

    if (count($argv) > 1) {
      throw new ArcanistUsageException(
        'Specify exactly one base commit. The end of the commit range is '.
        'always the working copy state.');
    }

    $api->setBaseCommit(head($argv));

    return $this;
  }

  final protected function getRepositoryVersion() {
    if (!$this->repositoryVersion) {
      $api = $this->getRepositoryAPI();
      $commit = $api->getSourceControlBaseRevision();
      $versions = array('' => $commit);
      foreach ($api->getChangedFiles($commit) as $path => $mask) {
        $versions[$path] = (Filesystem::pathExists($path)
          ? md5_file($path)
          : '');
      }
      $this->repositoryVersion = md5(json_encode($versions));
    }
    return $this->repositoryVersion;
  }

/* -(  Phabricator Repositories  )------------------------------------------- */

  /**
   * Get the PHID of the Phabricator repository this working copy corresponds
   * to. Returns `null` if no repository can be identified.
   *
   * @return phid|null  Repository PHID, or null if no repository can be
   *                    identified.
   *
   * @task phabrep
   */
  final protected function getRepositoryPHID() {
    return idx($this->getRepositoryInformation(), 'phid');
  }

  /**
   * Get the callsign of the Phabricator repository this working copy
   * corresponds to. Returns `null` if no repository can be identified.
   *
   * @return string|null  Repository callsign, or null if no repository can be
   *                      identified.
   *
   * @task phabrep
   */
  final protected function getRepositoryCallsign() {
    return idx($this->getRepositoryInformation(), 'callsign');
  }

  /**
   * Get the URI of the Phabricator repository this working copy
   * corresponds to. Returns `null` if no repository can be identified.
   *
   * @return string|null  Repository URI, or null if no repository can be
   *                      identified.
   *
   * @task phabrep
   */
  final protected function getRepositoryURI() {
    return idx($this->getRepositoryInformation(), 'uri');
  }

  /**
   * Get human-readable reasoning explaining how `arc` evaluated which
   * Phabricator repository corresponds to this working copy. Used by
   * `arc which` to explain the process to users.
   *
   * @return list<string> Human-readable explanation of the repository
   *                      association process.
   *
   * @task phabrep
   */
  final protected function getRepositoryReasons() {
    $this->getRepositoryInformation();
    return $this->repositoryReasons;
  }

  /**
   * @task phabrep
   */
  private function getRepositoryInformation() {
    if ($this->repositoryInfo === null) {
      list($info, $reasons) = $this->loadRepositoryInformation();
      $this->repositoryInfo = nonempty($info, array());
      $this->repositoryReasons = $reasons;
    }

    return $this->repositoryInfo;
  }

  /**
   * @task phabrep
   */
  private function loadRepositoryInformation() {
    list($query, $reasons) = $this->getRepositoryQuery();
    if (!$query) {
      return array(null, $reasons);
    }

    try {
      $results = $this->getConduit()->callMethodSynchronous(
        'repository.query',
        $query);
    } catch (ConduitClientException $ex) {
      if ($ex->getErrorCode() == 'ERR-CONDUIT-CALL') {
        $reasons[] = pht(
          'This version of Arcanist is more recent than the version of '.
          'Phabricator you are connecting to: the Phabricator install is '.
          'out of date and does not have support for identifying '.
          'repositories by callsign or URI. Update Phabricator to enable '.
          'these features.');
        return array(null, $reasons);
      }
      throw $ex;
    }

    $result = null;
    if (!$results) {
      $reasons[] = pht(
        'No repositories matched the query. Check that your configuration '.
        'is correct, or use "repository.callsign" to select a repository '.
        'explicitly.');
    } else if (count($results) > 1) {
      $reasons[] = pht(
        'Multiple repostories (%s) matched the query. You can use the '.
        '"repository.callsign" configuration to select the one you want.',
        implode(', ', ipull($results, 'callsign')));
    } else {
      $result = head($results);
      $reasons[] = pht('Found a unique matching repository.');
    }

    return array($result, $reasons);
  }

  /**
   * @task phabrep
   */
  private function getRepositoryQuery() {
    $reasons = array();

    $callsign = $this->getConfigFromAnySource('repository.callsign');
    if ($callsign) {
      $query = array(
        'callsigns' => array($callsign),
      );
      $reasons[] = pht(
        'Configuration value "repository.callsign" is set to "%s".',
        $callsign);
      return array($query, $reasons);
    } else {
      $reasons[] = pht(
        'Configuration value "repository.callsign" is empty.');
    }

    $project_info = $this->getProjectInfo();
    $project_name = $this->getWorkingCopy()->getProjectID();
    if ($this->getProjectInfo()) {
      if (!empty($project_info['repository']['callsign'])) {
        $callsign = $project_info['repository']['callsign'];
        $query = array(
          'callsigns' => array($callsign),
        );
        $reasons[] = pht(
          'Configuration value "project.name" is set to "%s"; this project '.
          'is associated with the "%s" repository.',
          $project_name,
          $callsign);
        return array($query, $reasons);
      } else {
        $reasons[] = pht(
          'Configuration value "project.name" is set to "%s", but this '.
          'project is not associated with a repository.',
          $project_name);
      }
    } else if (strlen($project_name)) {
      $reasons[] = pht(
        'Configuration value "project.name" is set to "%s", but that '.
        'project does not exist.',
        $project_name);
    } else {
      $reasons[] = pht(
        'Configuration value "project.name" is empty.');
    }

    $uuid = $this->getRepositoryAPI()->getRepositoryUUID();
    if ($uuid !== null) {
      $query = array(
        'uuids' => array($uuid),
      );
      $reasons[] = pht(
        'The UUID for this working copy is "%s".',
        $uuid);
      return array($query, $reasons);
    } else {
      $reasons[] = pht(
        'This repository has no VCS UUID (this is normal for git/hg).');
    }

    $remote_uri = $this->getRepositoryAPI()->getRemoteURI();
    if ($remote_uri !== null) {
      $query = array(
        'remoteURIs' => array($remote_uri),
      );
      $reasons[] = pht(
        'The remote URI for this working copy is "%s".',
        $remote_uri);
      return array($query, $reasons);
    } else {
      $reasons[] = pht(
        'Unable to determine the remote URI for this repository.');
    }

    return array(null, $reasons);
  }

  /**
   * Build a new lint engine for the current working copy.
   *
   * Optionally, you can pass an explicit engine class name to build an engine
   * of a particular class. Normally this is used to implement an `--engine`
   * flag from the CLI.
   *
   * @param string Optional explicit engine class name.
   * @return ArcanistLintEngine Constructed engine.
   */
  protected function newLintEngine($engine_class = null) {
    $working_copy = $this->getWorkingCopy();
    $config = $this->getConfigurationManager();

    if (!$engine_class) {
      $engine_class = $config->getConfigFromAnySource('lint.engine');
    }

    if (!$engine_class) {
      if (Filesystem::pathExists($working_copy->getProjectPath('.arclint'))) {
        $engine_class = 'ArcanistConfigurationDrivenLintEngine';
      }
    }

    if (!$engine_class) {
      throw new ArcanistNoEngineException(
        pht(
          "No lint engine is configured for this project. ".
          "Create an '.arclint' file, or configure an advanced engine ".
          "with 'lint.engine' in '.arcconfig'."));
    }

    $base_class = 'ArcanistLintEngine';
    if (!class_exists($engine_class) ||
        !is_subclass_of($engine_class, $base_class)) {
      throw new ArcanistUsageException(
        pht(
          'Configured lint engine "%s" is not a subclass of "%s", but must '.
          'be.',
          $engine_class,
          $base_class));
    }

    $engine = newv($engine_class, array())
      ->setWorkingCopy($working_copy)
      ->setConfigurationManager($config);

    return $engine;
  }

  protected function openURIsInBrowser(array $uris) {
    $browser = $this->getBrowserCommand();
    foreach ($uris as $uri) {
      $err = phutil_passthru('%s %s', $browser, $uri);
      if ($err) {
        throw new ArcanistUsageException(
          pht(
            "Failed to open '%s' in browser ('%s'). ".
            "Check your 'browser' config option.",
            $uri,
            $browser));
      }
    }
  }

  private function getBrowserCommand() {
    $config = $this->getConfigFromAnySource('browser');
    if ($config) {
      return $config;
    }

    if (phutil_is_windows()) {
      return 'start';
    }

    $candidates = array('sensible-browser', 'xdg-open', 'open');

    // NOTE: The "open" command works well on OS X, but on many Linuxes "open"
    // exists and is not a browser. For now, we're just looking for other
    // commands first, but we might want to be smarter about selecting "open"
    // only on OS X.

    foreach ($candidates as $cmd) {
      if (Filesystem::binaryExists($cmd)) {
        return $cmd;
      }
    }

    throw new ArcanistUsageException(
      pht(
        "Unable to find a browser command to run. Set 'browser' in your ".
        "Arcanist config to specify a command to use."));
  }

  /**
   * Ask Phabricator to update the current repository as soon as possible.
   *
   * Calling this method after pushing commits allows Phabricator to discover
   * the commits more quickly, so the system overall is more responsive.
   *
   * @return void
   */
  protected function askForRepositoryUpdate() {
    // If we know which repository we're in, try to tell Phabricator that we
    // pushed commits to it so it can update. This hint can help pull updates
    // more quickly, especially in rarely-used repositories.
    if ($this->getRepositoryCallsign()) {
      try {
        $this->getConduit()->callMethodSynchronous(
          'diffusion.looksoon',
          array(
            'callsigns' => array($this->getRepositoryCallsign()),
          ));
      } catch (ConduitClientException $ex) {
        // If we hit an exception, just ignore it. Likely, we are running
        // against a Phabricator which is too old to support this method.
        // Since this hint is purely advisory, it doesn't matter if it has
        // no effect.
      }
    }
  }

}


Introduction to Parallel Programming is given in this course either for Shared Memory and Message Passing paradigms.
The basic functionalities of two of the widest used parallel programming tools are presented: the MPI (Message Passing Interface) library for distributed architectures and OpenMP system for shared memory and multicore architectures. MPI is a message-passing library specification which provides a powerful and portable way for expressing parallel programs. OpenMP is a portable and scalable model that gives shared-memory parallel programmers a simple and flexible interface for developing parallel applications for platforms ranging from desktop to supercomputers.


Please call the number the listed.
NEXT Village SF is a 501c3 nonprofit organization founded in 2009. The name stands for Northeast Exchange Team, and our Village has always been committed to the principles of teamwork and exchange in all. Their mission is to provide residents of San Francisco's northeast corner with the confidence and practical means to live safely and comfortably in their homes and in their community as they age. They are part of the international Village to Village Network, dedicated to improving the management of all villages.They are also a member of CASE, Coalition of Agencies Serving the Elderly.


text:
package com.android.vcard;

import com.android.vcard.exception.VCardException;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 *

 * vCard parser for vCard 2.1. See the specification for more detail about the spec itself.
 *

 *

 * The spec is written in 1996, and currently various types of "vCard 2.1" exist.
 * To handle real the world vCard formats appropriately and effectively, this class does not
 * obey with strict vCard 2.1.
 * In stead, not only vCard spec but also real world vCard is considered.
 *

 * e.g. A lot of devices and softwares let vCard importer/exporter to use
 * the PNG format to determine the type of image, while it is not allowed in
 * the original specification. As of 2010, we can see even the FLV format
 * (possible in Japanese mobile phones).
 *

 */
public final class VCardParser_V21 extends VCardParser {
    /**
     * A unmodifiable Set storing the property names available in the vCard 2.1 specification.
     */
    /* package */ static final Set<String> sKnownPropertyNameSet =
            Collections.unmodifiableSet(new HashSet<String>(
                    Arrays.asList("BEGIN", "END", "LOGO", "PHOTO", "LABEL", "FN", "TITLE", "SOUND",
                            "VERSION", "TEL", "EMAIL", "TZ", "GEO", "NOTE", "URL",
                            "BDAY", "ROLE", "REV", "UID", "KEY", "MAILER")));

    /**
     * A unmodifiable Set storing the types known in vCard 2.1.
     */
    /* package */ static final Set<String> sKnownTypeSet =
            Collections.unmodifiableSet(new HashSet<String>(
                    Arrays.asList("DOM", "INTL", "POSTAL", "PARCEL", "HOME", "WORK",
                            "PREF", "VOICE", "FAX", "MSG", "CELL", "PAGER", "BBS",
                            "MODEM", "CAR", "ISDN", "VIDEO", "AOL", "APPLELINK",
                            "ATTMAIL", "CIS", "EWORLD", "INTERNET", "IBMMAIL",
                            "MCIMAIL", "POWERSHARE", "PRODIGY", "TLX", "X400", "GIF",
                            "CGM", "WMF", "BMP", "MET", "PMB", "DIB", "PICT", "TIFF",
                            "PDF", "PS", "JPEG", "QTIME", "MPEG", "MPEG2", "AVI",
                            "WAVE", "AIFF", "PCM", "X509", "PGP")));

    /**
     * A unmodifiable Set storing the values for the type "VALUE", available in the vCard 2.1.
     */
    /* package */ static final Set<String> sKnownValueSet =
            Collections.unmodifiableSet(new HashSet<String>(
                    Arrays.asList("INLINE", "URL", "CONTENT-ID", "CID")));

    /**
     *

     * A unmodifiable Set storing the values for the type "ENCODING", available in the vCard 2.1.
     *

     *

     * Though vCard 2.1 specification does not allow "B" encoding, some data may have it.
     * We allow it for safety.
     *

     */
    /* package */ static final Set<String> sAvailableEncoding =
        Collections.unmodifiableSet(new HashSet<String>(
                Arrays.asList(VCardConstants.PARAM_ENCODING_7BIT,
                        VCardConstants.PARAM_ENCODING_8BIT,
                        VCardConstants.PARAM_ENCODING_QP,
                        VCardConstants.PARAM_ENCODING_BASE64,
                        VCardConstants.PARAM_ENCODING_B)));

    private final VCardParserImpl_V21 mVCardParserImpl;

    public VCardParser_V21() {
        mVCardParserImpl = new VCardParserImpl_V21();
    }

    public VCardParser_V21(int vcardType) {
        mVCardParserImpl = new VCardParserImpl_V21(vcardType);
    }

    @Override
    public void addInterpreter(VCardInterpreter interpreter) {
        mVCardParserImpl.addInterpreter(interpreter);
    }

    @Override
    public void parse(InputStream is) throws IOException, VCardException {
        mVCardParserImpl.parse(is);
    }

    @Override
    public void parseOne(InputStream is) throws IOException, VCardException {
        mVCardParserImpl.parseOne(is);
    }

    @Override
    public void cancel() {
        mVCardParserImpl.cancel();
    }
}

redpajama_set_name: RedPajamaGithub


text:
Władcy Jawy

władcy Jawadwipy
 Tiaopien (władca Jawadwipy na terenie Jawy Zachodniej ok. 132)
 Nieznani władcy (do po 435)

Królowie Tarumy
 Purnawarman (król Tarumy na terenie Jawy Zachodniej ok. 400–424)
 Potuodżia (ok. 424–535)
 Dwarawarman (ok. 535–przed 500)
 Nieznani władcy (przed 500–686)
 Panowanie Śriwidźai ok. 686–838/1025
 Dżajabhupati (ok. 1030–1050)
 Zależność od Mataramu 1037–1049
 Nieznani władcy (1050–1250)
 Niskalawastu Kancana (po 1250–1300)
 Dewa Niskala (ok. 1300–1333) [syn]
 Ratu Dewata (1333–1357) [syn]
 Nieznani władcy(?) (1357–1520)
 Sanghjang (ok. 1522)

Władcy Sanjai
 Sanna (władca Sanjai na terenie Jawy Środkowej przed 730-ok. 732)
 Sandżaja (władca (rakai, rake) ok. 732–746) [bratanek?]
 Panangkaran (746–784) [syn?]
 Panunggalan (784–803) [syn?]
 Warak Djah Manara (803–827) [syn?]
 Djah Gula (827–828)
 Patapan (828–847) [syn Waraka?]
 Pikatan (847–855) [syn?]
 Kajuwangi Djah Lokapala (855–885) [syn?]
 Tagwas (885)
 Panumwangan Djah Dewendra (885–887)
 Gurunwangi Djah Bhadra (887)
 N.N. (887–894)
 Humalang Djah Dżbang (894–898) [syn Kajuwangi?]
 Watukara Balitung (898-ok. 910) [syn?]
 Hino Daksa (przed 913–915) [szwagier?]
 Lajang Tulodong (przed 919–921) [syn Watukary Balitunga]
 Pangkaja Wawa (przed 927–928)

Władcy Śailendry
 Bhanu (władca Śailendry na terenie Jawy Środkowej ok. 732–775)
 Wisznu (ok. 775–782) [syn]
 Indra (ok. 782–812) [syn]
 Taga (ok. 812–832) [syn]
 Pramodawardhani (832) [siostra]
 Sanjaja podbija Śailendrę 838

Władcy Surabai
Władcy (Starej) Surabai
 Dewasimha (władca Surabai na terenie Jawy Wschodniej ok. 740–760)
 Gadżajana (ok. 760–przed 800)
 A[...]nana (ok. 800)
 Panowanie Sanjai po 800–900
Władcy Hino
 Daksa (władca (rake) Hino przed 913–915; król Sanjai)
 Sindok (przed 929–947) [wnuk]
 Isanatunga Widżaja (947–?) [córka]
 Makutawamśa (?–991) [syn]
 Dharmawamśa (ok. 991–1007) [syn?]
 Okupacja Śriwidźai 1006–1010
Władcy (Nowej) Surabai
 Ngampeldenta (władca (pangeran) przed 1500–1513)
 Pekat Tanda Terung (ok. 1513–1530)
 Tundungmusuh (ok. 1530–1546) [syn]
 Lena (ok. 1546–1560) [syn]
 Dżebuk (ok. 1560–przed 1580) [syn]
 Wanakrama (p. 1580–1590) [syn]
 Rama (ok. 1590–1600) [syn]
 Surabaja (ok. 1600-p. 1610) [syn]
 Sundżaja (ok. 1610) [brat]
 Dżajalenkara (po 1610–1625; usunięty, zmarł 1630)
 Pekik (1625–1659) [syn]
 Gede Kapulungan (regent)
 Wiranegara I (1686–1706)
 Wiranegara II (1706–1707) [syn]
 Nieznani władcy(?) (1707–1743)
 Holenderskie Indie Wschodnie podbijają Surabaję 1743

Władcy Janggali
 Airlangga (władca Janggali na terenie Jawy Wschodniej 1019–1042/9) [bratanek Surabai, władcy Surabai]
 Wisznuwardhana (1042–?)
 Garasakan (?–1050/1) [syn Airlanggi]
 Alandżung Ahjes (1051–1058) [brat]
 Samarotsaha (ok. 1058–?) [brat]
 Halu (ok. 1060)
 Panjalu podbija Janggalę po 1175

Władcy Panjalu
 Samarawidżaja (władca Panjalu na terenie Jawy Wschodniej ok. 1049–1050)
 Anakwungsu (ok. 1050–1078) [z Bali]
 Dżajabhaja I (ok. 1104–1110) [syn Samarawidżai?]
 Dżajasaba (ok. 1110–1115) [syn Samarawidżai?]
 Kediri (ok. 1115) [syn]
 Kameśwara I (Bameśwara) (ok. 1115–1130)
 Dżajabhaja II (ok. 1135–1159)
 Sarweśwara I (ok. 1159–1161)
 Arjeśwara (p. 1171–1174)
 Kronczarjadipa Gandra (ok. 1181)
 Kameśwara II (ok. 1182–1185)
 Sarweśwara II (ok. 1190–1194)
 Kertadżaja (1194–1222) [syn?]
 Panowanie Singasari 1222–1293
 Panowanie Majapahitu 1293–1527
 Panowanie Mataramu 1558–16??
 Trunadżaja (1676–1678; usunięty, zmarł 1680) [książę balijski]
 Mataram podbija Panjalu 1678

Władcy Singasari
 Ken Angrok (władca Singasari na terenie Jawy Wschodniej 1222–1227)
 Anuśapati (uzurpator 1227–1248) [pasierb]
 Tohdżaja (1248) [syn Ken Angroka]
 Dżajawisznuwardhana (1248–1268) [syn]
 Narasimhamurti (koregent 1248–?)
 Kertanagara (1254–1292) [syn Dżajawisznuwardhany]
 Dżajakatwang (uzurpator 1292–1293; usunięty)
 Powstanie Majapahitu 1293

Władcy Tubanu
 Papringan (władca Tubanu pod zwierzchnością Majapahitu na terenie Jawy Wschodniej po 1270–1300)
 Rangga Lawe (ok. 1300–1350) [wnuk]
 Sira Lawe (ok. 1350–1380) [syn]
 Sira Weneng (ok. 1380–1410) [syn]
 Sira Lena (ok. 1410–1450) [syn]
 Dikara (ok. 1450–1490) [syn]
 Tedża (ok. 1490–1513) [syn?]
 Wilatikta (ok. 1513–1520) [syn]
 Ngrasena (ok. 1520–1530) [wnuk po kądzieli]
 Gegelang (ok. 1530–1550) [syn]
 Batubang (ok. 1550–1570) [syn]
 Balewot (ok. 1570–1580) [syn]
 Sekar Tandżung (ok. 1580–1585) [syn]
 Ngangsar (ok. 1585–1587) [brat]
 Pamalad (ok. 1587–1590) [syn Sekar Tandżunga]
 Salempe (ok. 1590–1600) [brat]
 Dalem (ok. 1600–1619) [syn Pamalada]
 Mataram podbija Tuban 1619

Władcy imperium Majapahitu
 Kertaradżasadżajawardhana (Raden Widżaja) (władca Majapahitu na terenie Jawy Wschodniej 1293–1309) [zięć Kertanagary, władcy Singasari]
 Dżajanagara (1309–1328) [syn]
 Tribhuwanawidżajatunggadewi (1328–1350; regencja 1328–1350) [córka]
 Radżasanagara (1350–1389) [syn]
 Wikramawardhana (1390–1428) [bratanek]
 Bhre Wirabumi (koregent 1390–1401; usunięty, zmarł 1406) [syn Gajatitribu, wdowy po Dżajanagarze]
 Suhita (1429–1447) [córka Wikramawardhany]
 Djah Kertawidżaja (1447–1451) [syn Bhre Wirabumi]
 Radżasawardhana (1451–1453)
 Interregnum 1453–1456
 Giriśawardhana (1456–1466)
 Singhawikramawardhana (1466–1474)
 Bhre Kertabumi (1374–1478; koregent od 1466)
 Dezintegracja państwa 1477–1527
 Girindrawardhana (1478–1519)
 Pateudra (?–1527?)
 Mataram podbija Majapahit 1527

Władcy Gresiku
 Nieznani władcy (p. 1411–1680)
 Zależność od Majapahitu przed 1411–1500
 Zależność od Pajangu 1568–1586
 Nolodiko (władca Gresiku na terenie Jawy Wschodniej 1680–1686)
 Panowanie Giri 1686–1695
 Puspanegara I (1695–1730)
 Astranegara (1730–?)
 Puspanegara II (?–1743)
 Holenderskie Indie Wschodnie podbijają Gresik 1743

Władcy Balambanganu
 Massembar (władca Balambanganu na terenie Jawy Wschodniej ok. 1450–1500)
 Bimakonkar (ok. 1500–1513) [syn]
 Menakpentor (ok. 1513–1530) [syn]
 Menakpangseng (ok. 1530–1550) [syn]
 Menakpati (ok. 1550–1570) [syn]
 N.N. (ok. 1570–1585/8)
 N.N. (ok. 1588–1590)
 N.N. (ok. 1590–1597) [syn]
 Maskarian (ok. 1597–1632; usunięty, zmarł 1633)
 Sunantawangalun I (1632–1639) [potomek Bimakonkara]
 Zależność od Mataramu 1639–1650
 Sunantawangalun II (1646–1691) [syn]
 Zależność od Bali (Bulelengu od 1697) 1686–1768
 Senapati (1691) [syn]
 Mankanagara (1691–1692) [brat]
 Mankanapura (1692–1697) [brat]
 Putra (1697–1736) [syn Senapatiego]
 Zależność od Mengwi 1711–17??
 Danuningrat (1736–1767) [syn]
 Wilis (1767–1768) [brat]
 N.N. (1768–1777)
 Holenderskie Indie Wschodnie podbijają Balambangan 1777

Władcy Demaku
 Patah (władca (panembahan senapati dżimbun) Demaku (Bintoro) pod zwierzchnością Majapahitu na terenie Jawy Środkowej 1478/1500–1490/1511)
 Sabrang Lor (1490/1511–1495/1518)
 Junus (1518–1521; zrzucił zwierzność Majapahitu 1520) [syn Pataha]
 Trengganu (sułtan 1521–1539) [brat]
 Prawata (1539/46) [syn]
 Pangiri (władca (arja) 1547) [syn]
 Penengsan (uzurpator 1547–?)
 Karebet (władca (pangeran) ?–1582) [zięć]
 Mataram podbija Demak 1582

Władcy Giri
Dynastia Wali
 Satmata (duchowy władca Giri na terenie Jawy Wschodniej 1485–1506)
 Dalem (1506–1545/6) [syn]
 Sedamargi (1545/6–1548) [syn]
 Prapen (władca (maharadża pratikal) 1548–1605) [brat]
 Kawisgua (1605–1621) [syn]
 Agung (1621–1626) [syn]
 Waswitana (1626–1660) [syn]
 Puspaita (1660–1680)
 Wirajadi (1680–1703)
 Singanegara (1703–1725)
 Singasarie (1725–1743)
 Holenderskie Indie Wschodnie podbijają Giri 1743

Władcy Cirebonu
Dynastia muzułmańska
 Nieznani władcy (1478–1527)
 Sunan Gunung Dżati (władca Cirebonu w zachodniej części Jawy Zachodniejok. 1527–1570; władca Bantamu ok. 1527–1552)
 Ratu (ok. 1570–1649; król (panembahan) od 1639) [prawnuk]
 Zależność od Mataramu 1582–1679
 Giri Laja (1649–1662) [wnuk]
 Rozpad państwa na cztery pałace (kraton) 1662–1819
Kraton Kasepuhan
 Sepuh I Szams ad-Din (sułtan 1662–1697) [syn]
 Sepuh II Dżamal ad-Din (1697–1723) [syn]
 Protektorat holenderski 1705/1758–1819
 Sepuh III Salam ad-Din (1723–1734) [syn]
 Sepuh IV Tadż al-Arifin Muhammad Zajn ad-Din (1734–1753) [syn]
 Sepuh V Muhammad Szams ad-Din (1753–1773)
 Sepuh VI (1773–1787) [syn]
 Sepuh VII (regent 1781–1787; władca 1787–1791) [brat]
 Sepuh VIII (1791–1819; regencja 17791–1792; usunięty, zmarł 1845) [syn]
 Holenderskie Indie Wschodnie podbijają Kraton Kasepuhan 1819
Kraton Kanoman
 Anom I Abu-Manasiri Badr ad-Din (sułtan 1662–1703) [syn Giri Lai]
 Hallar ad-Din (1703–1706) [syn]
 Protektorat holenderski 1705/1758–1819
 Radża Kusama (1706–1719)
 Anom II Abu-Manasiri Muhammad Alim ad-Din (1719–1732) [syn]
 Temenggong (Minister) (1732–1744)
 Anom III Abu'l-Chajr Muhammmad Chajr ad-Din (1744–1797) [syn Anoma II]
 Anom IV Iman ad-Din (1797–1819; usunięty, zmarł 1853) [syn nieślubny]
 Holenderskie Indie Wschodnie podbijają Kraton Kanoman 1819
 Anom Muhammad Nurus (?–198?)
 Hadżi Muhammad Dżalaluddin (?–2002)
 Muhammad Saladin (2003)
 Radża Muhammad Emiruddin (2003-dziś)
Kraton Kaprabonan
 Cirebon I Abd al-Kamil Muhammad Nasr ad-Din (władca (panembahan) 1694–1714) [syn Radży Kusamy]
 Protektorat holenderski 1705/1758–1819
 Temenggong (Minister) (1714–1725)
 Cirebon II Abd al-Pahur Muhji ad-Din (1725–1731) [syn Cirebona I]
 Temenggong (Minister) Secadipura (1731–1752)
 Cirebon III Muhammad Tajr Jaridin Sabririn (1752–1773) [syn Cirebona II]
Kraton Kacirebonan
 Kamar ad-Din (władca (pangeran) 1697–1723)
 Protektorat holenderski 1705/1758–1819
 Cirebon I Muhammad Akbar ad-Din (sułtan 1723–1734) [syn]
 Cirebon II Abu Muharram Muhammad Salih ad-Din (1734–1758) [brat]
 Cirebon III Muhammad Harr ad-Din (1758–1768) [syn]
 Interregnum 1768–1808
 Cirebon IV (1808–1810) [brat]
 Interregnum 1810–1819
 Holenderskie Indie Wschodnie podbijają Kraton Kacirebonan 1819

Władcy Pasuruhanu
 Menaksepetak (władca Pasuruhanu na terenie Jawy Wschodniej ok. 1513/26)
 N.N. (ok. 1546) [syn]
 Pekik (ok. 1600–1614)
 Kapulungan (regent ok. 1614–1616/7)
 Nieznani władcy? (1617–1686; zależność od Mataramu 1617–1643)
 Wiranegara I (1686–1706)
 Wiranegara II (1706–1707)
 Holenderskie Indie Wschodnie podbijają Pasuruhan 1707

Sułtani Bantamu
Dynastia Sunda
 Sunan Gutung Dżati (władca Bantamu (Bantenu) w zachodnim krańcu wyspy Jawy ok. 1527–1552)
 Zależność od Demaku 1527–przed 1582
 Hasan ad-Din (ok. 1552–1570; sułtan od 1568) [syn]
 Jusuf (ok. 1570–1580) [syn]
 Muhammad (ok. 1580–1596) [syn]
 Abd al-Kadir (1596–1631; regencja 1596–1624) [syn]
 Ahmad Rahmat Allah (1631–1634) [syn]
 Abu'l Fattah (1634–1680; usunięty, zmarł 1692) [syn]
 Abd al-Kahhar (1672–1687) [syn]
 Protektorat holenderski 1684/1753–1832
 Jahja (1687–1689; regencja 1687) [syn]
 Zajn al-Abidin (1689–1733) [brat]
 Szafi (1733–1748; usunięty, zmarł 1758) [syn]
 Fatima (regentka 1748–1750; usunięta, zmarła 1751) [żona]
 Muhammad Wasi al-Halimin (1750–1753; usunięty, zmarł 1760) [syn wezyra Dipati-Ningrata, regenta z 1687]
 Arif Zajn al-Aszikin (1753–1777) [syn Zajn al-Abidina]
 Ali ad-Din I (1777–1802/4) [syn]
 Muhji ad-Din I Zajn at-Talah (1804–1805) [brat]
 Iszak Zajn al-Muttakin (1805–1808; usunięty, zmarł 1842) [syn nieślubny]
 Ali ad-Din II (1808–1810; usunięty, zmarł 1849) [syn Ali ad-Dina I]
 Safi ad-Din (1810–1811/6) [syn Muhji ad-Dina I]
 Ahmad (regent 1811–1813) [syn Iszaka]
 Muhji ad-Din II (1813–1816) [brat]
 Rafi ad-Din (sułtan nominalny 1816–1832; usunięty, zmarł 1900) [syn Safi ad-Dina]
 Holenderskie Indie Wschodnie podbijają Bantam 1832

Sułtani Mataramu
 Bagus Kachung (władca (panembahan) Mataramu na terenie Jawy Środkowej 1558–1575)
 Zależność od Pajangu 1568–1584/1681
 Sutawidżaja (1575–1601) [syn]
 Seda Karapjak (1601–1613) [syn]
 Mas Wurja (1613; usunięty, zmarł 1678) [syn]
 Abd ar-Rahman (1613–1645; sułtan (też tytułowany susuhanan) od 1625) [syn]
 Amangkurat I (1645–1677; usunięty, zmarł 1677) [syn]
 Trunadżaja (uzurpator 1677; usunięty, zmarł 1680)
 Amangkurat II (1677–1703) [syn Amangkurata I]
 Amangkurat III (1703–1708; tylko we wschodniej części kraju od 1704; usunięty, zmarł przed 1734) [syn]
 Pakubuwono I (1704–1719) [syn Amangkurata I]
 Amangkurat IV (1719–1726) [syn]
 Pakubuwono II (1726–1742; usunięty) [syn]
 Amangkurat V (1742; uusnięty, zmarł 1743) [wnuk Amangkurata III]
 Pakubuwono II (2. panowanie 1742–1749)
 Protektorat holenderski 1743/49–1755
 Pakubuwono III (1749–1755; po podziale w Surakarcie od 1755) [syn]
 Rozpad sułtanatu na Surakartę i Jogyakartę 1755

Sułtani Pajangu
 Karebet (sułtan Pajangu na terenie Jawy Środkowej 1568–1582; władca Demaku ?–1582) [zięć Penengsana, uzurpatora Demaku]
 Benawa (1582–1586) [syn Penengsana, uzurpatora Demaku]
 Nieznani sułtani (1586-po 1681)
 Mataram podbija Pajang po 1681

Władcy Sumedangu
 Kusumadinata I (władca (pangeran) Sumedangu na terenie Jawy Zachodniej pod zwierznością Mataramu przed 1624–1650)
 Geusan Ulun (ok. 1650–1680)
 Rangga Gede (ok. 1680–1700)
 Gempol (ok. 1700–?)
 Tanumadża (?–1737)
 Kusumadinata II (1737–1748)
 Kusumadinata III (1748–1761)
 Surjanegara I (1761–1765)
 Kusumadinata IV (1765–1773)
 Tanubaja I (1773–1775)
 Tanubaja II (1775–1789)
 Surjanegara II (1789–1828)
 Kusumajuda (1828–1836)
 Kusumadinata V (1836–1882)
 Surja Atmadża (1882–1919; usunięty, zmarł 1921)
 Kusumadilaga (1919–1925)
 Holenderskie Indie Wschodnie podbijają Sumedang 1925

Władcy Semarangu
 Dżurukiting (władca (pangeran) Semarangu pod protektoratem holenderskim na terenie Jawy Środkowej ok. 1638–1682)
 Sura Adimenggala I (1682–1721)
 Setra Widżaja (1723–1741)
 Sura Adimenggala II (1741–1751)
 Sura Adimenggala III (1751–1777)
 Sura Adimenggala IV (1777–1791)
 Sura Adimenggala V (1791–1809)

Władcy Cianjuru
 Arja Wiratanu I (władca (pangeran) Cianjuru na terenie Jawy Wschodniej ok. 1640–1686)
 Arja Wiratanu II (1686–1707)
 Arja Wiratanu III (1707–1727)
 Adipati Wiratanudatar IV (1727–1761)
 Adipati Wiratanudatar V (1761–1776)
 Adipati Wiratanudatar VI (1776–1813)
 Adipati Prawiradiredża I (1813–1833)
 Tumenggung Wiranegara (1833–1834)
 Arja Adipati Kusumaningrat (1834–1862)
 Arja Adipati Prawiradiredża II (1862–1910)
 Demang Natakusuma (regent 1910–1912)
 Arja Adipati Wiranatakusuma (1912–1920)
 A. Surjadiningrat (1920–1932)
 Holenderskie Indie Wschodnie podbijają Cianjur 1925
 Sunarja (regent 1932–1934)
 Surjanataatmadża (1934–1943)
 Adiwikarta (1943–1945)

Władcy Sukapury
 Wiradedaha I (władca (pangeran) Sukapury na terenie Jawy Wschodniej ok. 1641–?)
 Wiradedaha II (?–1674)
 Anggadipa Wiradedaha III (1674–1726)
 Wiradedaha IV (1726–1745)
 Satjapati (1745–1747)
 Wiradedaha V (1747–1765)
 Dżajamenggala (1765–1807)
 Demang Anggadipa (1807–1813)
 Surjalaga (1813–1814)
 Wiradedaha VI (1814–1828)
 Wiratanubaja I (1828–1835)
 Wiratanubaja II (1835–1854)
 Adipati Wiradedaha VII (1854–1874; usunięty, zmarł 1912)
 Wirahadiningrat (1874–1906)
 Aria Prawiradiningrat (1906–1908)
 Wiratanudiningrat (1908–1925)
 Holenderskie Indie Wschodnie podbijają Sukapurę 1925

Władcy Limbanganu
 Najawangsa (władca (pangeran) Limbanganu na terenie Jawy Wschodniej ok. 1660–1678)
 Kjai Mas Martasinga (1678–1726)
 Wangsadita (1726–1740)
 Rangga Limbangan (1740–1744)
 Surapradża (1744–1752)
 Suraprija (Wangsadiredża I) (1752–1763)
 Wangsadiredża II (1763–1799; usunięty)
 Wangsakusuma (1799)
 Wangsadiredża II (2. panowanie 1799–1805)
 Wangsaredża III (1805–1813)
 Adiwidżaja (1813–?)
 Kusumadinata (?–1836)
 Dżajaningrat (1836–1871)
 Arja Wiratanudatar (1871–1915)
 Rangga Surja Kartalegawa (1915–1925)
 Holenderskie Indie Wschodnie podbijają Limbangan 1925

Władcy Bandungu
 Wira Anggonanggon (władca (pangeran) Bandungu na terenie Jawy Środkowej 1678–1681)
 Protektorat holenderski 1684–1925
 Anggadiredża I (1681–1704)
 Demang Timbanganten (1704–1747)
 Anggadiredża II (1747–1763)
 Anggadiredża III (1763–1794)
 Adipati Wiranatakusuma II (1794–1829)
 Adipati Wiranatakusuma III (1829–1846)
 Adipati Wiranatakusuma IV (1846–1874)
 Adipati Kusumadilaga (1874–1893)
 Adipati Arja Martanagara (1893–1920)
 Adipati Arja Wiranatakusuma V (1820–1931; usunięty)
 Holenderskie Indie Wschodnie podbijają Bandung 1925
 T. Hasan Sumadipradża (1831–1835)
 Adipati Arja Wiranatakusuma V (2. panowanie 1835–1945)
 T.E. Surjaputra (1945–1947)
 T.M. Wiranatakusuma VI (1948–1956)
 Apandi Wiradiputra (1956–1957)

Sułtani Surakarty
 Pakubuwono III (sułtan (też tytułowany susuhanan) Surakarty (Solo) na terenie Jawy Środkowej pod zwierzchnością holenderską 1755–1788; wcześniej sułtan Mataramu od 1749)
 Pakubuwono IV (1788–1820) [syn]
 Pakubuwono V (1820–1823) [syn]
 Pakubuwono VI (1823–1830; usunięty, zmarł 1849) [syn]
 Pakubuwono VII (1830–1858) [stryj]
 Pakubuwono VIII (1858–1861) [brat]
 Pakubuwono IX (1861–1893) [syn Pakubuwono VI]
 Pakubuwono X (1893–1939) [syn]
 Pakubuwono XI (1939–1945) [syn]
 Pakubuwono XII (1945–2004; usunięty 1946–1948) [syn]
 Surakarta włączona do Indonezji 1946
 Pakubuwono XIII (Hangabehi) (2004-dziś) [brat przyrodni]

Sułtani Jogyakarty
 Hamengkubuwono I (sułtan Jogyakarty w centrum Jawy pod zwierzchnością holenderską 1755–1792) [syn Amangkurata IV, sułtana Mataramu]
 Hamengkubuwono II (1792–1812; usunięty) [syn]
 Hamengkubuwono III (1812–1814) [syn]
 Hamengkubuwono IV (1814–1823; regencja 1814–1816) [syn]
 Hamengkubuwono V (1823–1826; regencja 1823–1826; usunięty) [syn]
 Hamengkubuwono II (2. panowanie 1826–1828)
 Hamengkubuwono V (2. panowanie 1828–1855; regencja 1828–1836)
 Hamengkubuwono VI (1855 –1877) [brat]
 Hamengkubuwono VII (1877–1921) [syn]
 Hamengkubuwono VIII (1921–1939) [syn]
 Hamengkubuwono IX (1940–1988) [syn]
 Jogyakarta włączona do Indonezji 1949
 Hamengkubuwono X (1989-dziś) [syn]

Władcy Mangkunegaranu
Dynastia Mangkunegaran
 Mangkunegara I (władca (pangeran) Mangkunegaranu na terenie Jawy Środkowej w granicach Surakarty pod zwierzchnością holenderską 1757–1795)
 Mangkunegara II (1795–1835) [wnuk]
 Mangkunegara III (1835–1853) [wnuk]
 Mangkunegara IV (1853–1881) [kuzyn]
 Mangkunegara V (1881–1896) [syn]
 Mangkunegara VI (1896–1916; abdykował, zmarł 1928) [brat]
 Mangkunegara VII (1916–1944) [syn Mangkunegary V]
 Mangkunegara VIII (1944–1987; usunięty 1946–1948) [syn]
 Mangkunegaran włączony do Indonezji 1946
 Mangkunegara IX (1987-dziś) [syn]

Władcy Pakualamanu
Dynastia Pakualaman
 Pakualam I (władca Pakualamanu w centrum Jawy w granicach Jogyakarty pod zwierzchnością holenderską 1812–1829)
 Pakualam II (1829–1858) [syn]
 Pakualam III (1858–1864) [syn]
 Pakualam IV (1864–1878) [bratanek]
 Pakualam V (1878–1900) [syn nieślubny Pakualama II]
 Pakualam VI (1900–1902) [syn]
 Pakualam VII (1902–1937; regencja 1902–1906) [syn]
 Pakualam VIII (1937–1998; regencja 1937–1938) [syn]
 Pakualaman włączony do Indonezji 1946
 Pakualam IX (1998-dziś) [syn]

Władcy Kalibawangu
 Mangkudiningrat (władca (pangeran) Kalibawangu na terenie Jawy Środkowej pod zwierzchnością holenderską 1831; usunięty) [wnuk Hamengkubuwono II, sułtana Jogyakarty]
 Natapraja (1831–1853) [brat]
 Kalibawang włączony do Jogyakarty 1853

Władcy Nangulanu
 Prabu Adiningrat (władca (pangeran adipati) Nangulanu na terenie Jawy Środkowej pod zwierzchnością holenderską 1831–1833)
 Panowanie Holenderskich Indii Wschodnich 1833–1853
 Nangulan włączony do Jogyakarty 1853

Władcy Madury (Jawa Wschodnia)

Władcy Bangkalanu
 Raden Lembu Peteng (władca Bangkalanu w zachodniej części wyspy ok. 1350–1380)
 Arja Menger (ok. 1380–1400) [syn]
 Arja Pratikel (ok. 1400–1430) [syn]
 Arja Pojok (ok. 1430–1460) [zięć]
 Ki Demung (w Arosbai, Bangkalanie, Kota Anjar i Palakaranie ok. 1460–1500) [syn]
 Ki Pragalba (w Bangkalanie i Palakaranie ok. 1500–1531) [syn]
 Raden Pratanu (w Arosbai i Bangkalanie 1531–1592/6) [syn]
 Raden Kara (1592/6–1621; władca (adipati) Madury od przed 1600) [syn]
 Pangeran Mas (1621–1624) [brat]
 Cakraningrat I (1624–1648) [syn]
 Zależność od Mataramu od 1624
 Raden Demang Malaja Kusuma (regent(?) 1648–1646) [brat]
 Cakraningrat II (1648–1707; władca (panembahan) Madury od ok. 1650) [syn Cakraningrata I]
 Cakraningrat III (1707–1718; usunięty) [syn]
 Cakraningrat IV (1718–1745; usunięty) [brat]
 Cakraningrat V (1745–1770) [syn]
 Cakraningrat VI (1770–1779) [wnuk]
 Cakraningrat VII (1779–1815; sułtan od 1808) [syn Cakraningrata V]
 Cakraningrat VIII (1815–1847) [syn]
 Cakraningrat IX (władca (panembahan) 1847–1862) [syn]
 Cakraningrat X (1862–1882) [syn]
 Holenderskie Indie Wschodnie podbijają Bangkalan 1882
 Cakraningrat XI (tylko regent Madury 1882–1905; tylko w Bangkalanie od 1885) [stryj]
 Surjanegara (1905–1918) [syn]
 Cakraningrat XII (1918–1945) [brat]
 Muhammad Aziz Cakraningrat XIII (1948–1956) [syn]
 R. A. Muhammad Rusłan (1956–1976) [brat]

Władcy Sumanepu
 Waragong (władca (pangeran) Sumanepu we wschodniej części wyspy ok. 1400–1430)
 (?)N.N. (ok. 1430–1466)
 Demang (1466–?)
 Nieznani władcy(?) (przed 1500–1550)
 Raden Temenggong Raduruwan (ok. 1550–1579)
 Ellor I (ok. 1579–?) [syn]
 Wetan (?-ok. 1600) [brat]
 Ellor II (ok. 1600–1624) [syn]
 Mas Anggadipa (1624–?)
 Jang Pati (?–1671)
 Judanegara (1671–1684) [wnuk Ellora II]
 Pulang Dżiwa (1684–1702) [zięć]
 Cakranegara I (1702–1705) [zięć]
 Suderma (1705–1707) [wnuk Judanegary]
 Cakranegara II (1707–1737) [syn Cakranegary I]
 Protektorat holenderski przed 1708–1879
 Cakranegara III (1737–1746/50) [bratanek]
 Aju Tirtanegara (regentka 1746–1750) [córka Cakranegary I]
 Bendara Saud (1750–1767) [mąż]
 Tirtanegara (1767–1812) [syn]
 Natadiningrat (koregent 1804–1810; usunięty) [syn]
 Paku Nataningrat (1812–1854; koregent od 1810; tylko sułtan od 1825) [brat]
 Natakusuma (władca (panembahan) 1854–1879) [syn]
 Rada regencyjna 1867/79–1883
 Holenderskie Indie Wschodnie podbijają Sumanep 1883

Sułtani Pamekasanu
 Adikara I (władca Pamekasanu 1685–1708)
 Protektorat holenderski od 1705
 Adikara II (1708–1737) [syn]
 Adikara III (1737–1743) [brat]
 (?)
 Mangku Adiningrat (sułtan ?–1842)
 Adiningrat (1842–1853)
 Holenderskie Indie Wschodnie podbijają Pamekasan 1853

Bibliografia
 Truhart P., Regents of Nations. Systematic Chronology of States and Their Political Representatives in Past and Present. A Biographical Reference Book, Part 3: Asia & Pacific Oceania, München 2003, s. 1227–1238, 1318–1319,  .

Linki zewnętrzne
 Indonesian tradition polities w Rulers

Jawa

redpajama_set_name: RedPajamaWikipedia


The Kinross Corporate Head Office is located in downtown Toronto and supports Kinross operations and projects worldwide. Corporate functions include Finance, Procurement, Health & Safety, Human Resources, IT and Investor Relations.
To provide geological interpretation and resource estimation supporting the company's operations, exploration and merger and acquisitions activities. The role spans the entire mining life cycle from discovery, exploration, development, construction, operations, closure and reclamation. Key areas of responsibility include: geology modelling (including orebody characterization), resource modelling, resource and reserve reporting, mine geology, regulatory compliance, support of brownfield exploration, management of consultants, and management of direct reports.
Performs technical audits to support business decisions and ensure compliance with statutory regulation as per legislation requirements.
Kinross is a Canadian-based gold mining company with mines and projects in Canada, the United States, Brazil, Chile, Russia, Ghana and Mauritania, employing approximately 9,300 people worldwide. Our core purpose is to lead the world in generating value through responsible mining.


Festival Jazz Roja III will take place at La Plaza de La Pescadora, Los Cristianos (Arona, South Tenerife) from the 19th until the 21st of April 2018. (Click on the map at the bottom of this page).
Here are the forthcoming dates and times for the Concerts, Workshops and Masterclasses.
21 April 13:30H - Masterclass (Fermín Rivero) - Sax; "Improvision and Application to Musical Genres"
21 April 15:30H - Masterclass (Charly Daicz) - String Instruments; "Open Tuning and World Rhythms"


Only 11 days left to pledge your saupport! The album features Steve Hunt-Keys, Joe Santerre-Bass, and Chad Wackerman-Drums.
Additional content © Don Lappin from the Don Lappin Is Recording His New Record!!! (Canceled) project.


It is our vision to Inspire people to live better lives through Natural Healthcare.
Built on a 60 year history of science and research into herbal remedies, Integria Healthcare continues the work of its founding fathers to develop scientifically tested natural therapies that help support health and wellbeing.
Integria Healthcare provides health professionals and retailers with integrated access to more than 75 of the most trusted names in natural health therapies and personal care products. Through our online customer portal, MyIntegria, you can order practitioner and retail healthcare brands, anytime, from any location.
Integria Healthcare provides advanced educational programs for natural healthcare professionals, delivered by leading practising clinicians, technical experts and natural medicine researchers and scientists. As well as manufacturing the highest quality practitioner healthcare brands, we share knowledge and expertise to keep you at the forefront of integrative medicine.
We make it our business to help your business run smoothly. Integria Healthcare provides round-the-clock technical and customer support to health practitioners and retailers across Australia and New Zealand. Through our online customer portal, MyIntegria, you can place orders, track delivery and ask product-specific questions anytime, from any location.
For the latest offers, news and product information, enter your details.
Available to Integria Healthcare account holders only. Click here to apply for an account.


text:
Q: Why might Apache Flink write files on a Windows box, but not write files on a Linux container using simple FileSink and SimpleStringEncoder? I'm working with the examples provided in 'flink-training' in the GitHub repository here.  Specifically, I'm working on the 'ride-cleansing' example.
I've replaced the PrintSinkFunction with a simple FileSink configured as follows:
        FileSink fileSink =
            FileSink.forRowFormat(new Path(args[0]),
                                           new SimpleStringEncoder<String>("UTF-8"))
                             .withRollingPolicy(DefaultRollingPolicy.builder()
                             .withRolloverInterval(Duration.ofMinutes(1))
                             .withInactivityInterval(Duration.ofSeconds(30))
                             .withMaxPartSize(512 * 512 * 512)
                             .build())
                    .build();

When I run this example on my local machine in Intellij, the expected directory are created and files are created to reflect the data streamed to the sink.
However, when I run this same example on a Linux box (on Google Colab), the directory is created, but no files are created, regardless of how long I leave it running (I've tried 10+ minutes).
On the Linux Container, I'm running the example using the gradle setup and the following command:
./gradlew :ride-cleansing:runJavaSolution --args="/content/datastream"
On the Windows box, I'm just executing the RideCleansingSolution 'main' with a simple 'Application' run configuration.
What might be different about my setup on the two systems that would decide whether data is written?

A: it might not work, but if you set up mono develop on whatever nx your using and write it all in c# via Xamarin in VS.NET23 it MIGHT work seamlessly across all platforms and arches... but I'm just spitballing here so `_o_/'

A: Turns out that the files were in fact being written, I just hadn't realized they were written prefixed with '.' and hidden by default...

redpajama_set_name: RedPajamaStackExchange


One thing that often gets overlooked during the process of purchasing pieces, parts, and components for your surround sound system is the importance of cables to the overall sound of your system. It makes absolutely no idea to buy top of the line speakers and excellent quality components only to use substandard el cheapo cables with which to connect them to one another. Unfortunately we see this every day and it causes problem with the quality of the sound that leads over time to a total and complete dissatisfaction with the quality of sound your system provides.
There are other considerations when it comes to cables such as aesthetics, which will also affect the price when it comes to your system. I strongly encourage you to seriously consider what level of cabling and wires you can and cannot live with before you purchase your surround sound or home theater system, as both tend to be very wire and cable intensive. There are however things you can do to tame the tangle before it overtakes your home and one of my first recommendations is to seriously consider the value that going wireless would add to your system.
Wireless speakers eliminate the need for a good portion of the wires and cabling that are typically part and parcel of the lot when it comes to good sound systems. Going wireless for me is far preferable to drilling holes into the walls and running the wires through and having a rat's next of speaker wires overhead in my home is simply not an option. Of course everyone has different priorities when it comes to their surround sound or home theater systems and some people aren't all the considered about wires and cables. If you are not one that bothers then that is no problem either.
Unfortunately the wires and cables in a home theater or surround sound system are not limited to the speakers alone and while going wireless for the speakers is often financially feasible it's an entirely different ball park to go wireless for the whole kit and caboodle. For this reason there are all kinds of nifty tips and tricks for taming a mess of wires and keeping things organized and tidy behind the scenes. Among my favorites are these new power strips that allow you to color code and label which cord goes where. These strips are also great because they offer surge protection for your costly electronic equipment.
In addition to having the power strips labeled and organized you can purchase PVC piping and run all the cords down one tube in order to reach the power strip. You can also paint the tube in order to blend in with your wall if you are concerned about the aesthetics of the tube. I personally like this option for keeping all the chords in one spot rather than having them run haphazardly along the back of your other electronic components. It simply looks neater and more organized and your friends and family will be impressed at your cleverness for thinking of it.
If you have a certain disdain for over organization or having things too terribly tidy you can always opt for these Velcro ties that you simple use like the old sandwich bag ties. They can keep several chords together so that you aren't constantly having to work around them and yet allows you easy access to the chords should you find a sudden need for access or get the urge to rearrange or change settings and situations.
While it doesn't take rocket science to tame the wild tangle of chords that sometimes invade of entertainment space, it often helps to have a few tricks up your sleeve when confronting the seemingly endless stream of wires that are part of the average home theater or surround sound system. Hopefully you will find that some of these suggestions and tips will be helpful in your home.


Ignore this wee advertising banner. We hates it. And no matter how hard I hack, I can't get rid of it. Grrr.
This website celebrates the wonderful Engrish subtitles featured in an Asian bootleg DVD of Lord of The Rings - The Two Towers. What you see is exactly what appears on the TV screen. The first half of the movie has the most screen grabs, as there is more action than talking later on, and the subtitle writers eventually started getting the name of the characters right. Have fun!
"Engrish is a slang term which refers to an English language phrase that arose through poor translation of another language (usually Japanese) into English, or sometimes, poor translation of English into another language followed by good translation back into English. This used to be a frequent occurrence with product manuals, which might say something like "to make speed up find up out document", but it's less frequent today. Another source of poor translation is an unchecked machine-produced translation, such as that from the Babelfish service."