<commit_before>// - get availavle locales on init stage
// - setup locale fromsession if exists
// - guess locale from browser if no session
//

'use strict';

var _ = require('lodash');

module.exports = function (N) {
  // Enabled locales map of `normalized -> original` pairs.
  //
  //   { 'ru-ru': 'ru-RU', 'en': 'en-US' }
  //
  var enabledLocalesMap = {};

  // returns 'normalized' locale string:
  // - [^a-z] are replaced with dash `-`,
  // - all chars are lower-cased
  //
  // 'ru' -> 'ru'
  // 'ru_RU' -> 'ru-ru'
  // 'ru-UA' -> 'ru-ua'
  //
  function normalizeLocale(locale) {
    return String(locale).replace(/[^a-zA-Z]+/g, '-').toLowerCase();
  }

  // RegExp used to extract language quality
  //
  var QUALITY_RE = /^q=(.+)/;

  // returns object with `locale` (normalized) and `quality` from `str`
  //
  //  'en; q=0.5' -> { locale: 'en', quality: 0.5 }
  //  'en_US'     -> { locale: 'en-us', quality: 1 }
  //
  function parseLanguagePart(str) {
    var arr, match;

    // remove any whitespace that might appear according to RFC:
    // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
    arr   = str.replace(/\s+/g, '').split(';');
    match = QUALITY_RE.exec(arr[1]);

    return {
      locale:   normalizeLocale(arr[0]),
      quality:  match ? +match[1] : 1
    };
  }

  // Parses Accept-Language header string into array of locale names sorted by
  // quality and with appended zone-less fallback for each language.
  //
  //   'en-US;q=0.8,en-GB,ru-RU' -> [ 'en-gb', 'en-us', 'en', 'ru-ru', 'ru' ]
  //
  // NOTE: We limit amount of variant to maximum 10 elements.
  //
  function getAcceptedLanguages(string) {
    var result = [], fallbacks = {}, tmp;

    tmp = String(string).split(',').slice(0, 10).map(parseLanguagePart);

    tmp = _.sortBy(tmp, 'quality')
              .map(function (val) { return val.locale; })
              .reverse();

    tmp.forEach(function (locale) {
      var fallback = locale.split('-')[0]; // Cut off zone part.

      result.push(locale);

      // Add zone-less locale for after each language group if it not exists
      // to improve locale detection quality.
      if (fallback !== locale && !fallbacks[fallback] && tmp.indexOf(fallback) < 0) {
        result.push(fallback);
        fallbacks[fallback] = true;
      }

    });

    return result;
  }

  // find first matching locale from the list of accepted languages
  //
  function findAcceptedLanguage(req) {
    var locales, l;

    if (req && req.headers && req.headers['accept-language']) {
      locales = getAcceptedLanguages(req.headers['accept-language']);
      while (locales.length) {
        l = locales.shift();
        if (enabledLocalesMap[l]) {
          return l;
        }
      }
    }
  }

  ////////////////////////////////////////////////////////////////////////////////

  // Fill enabled locales map on INIT stage. (all i18n is done in bundler)
  //
  N.wire.after('init:bundle', function locale_set_prepare(N) {

    // Add full locale names to the map.
    _.forEach(N.config.locales.enabled, function (locale) {
      enabledLocalesMap[normalizeLocale(locale)] = locale;
    });

    // Add zone-less locale aliases like 'en' for 'en-US'.
    _.forEach(N.config.locales.enabled, function (locale) {
      var languageId = normalizeLocale(locale).split('-')[0];

      if (!_.has(enabledLocalesMap, languageId)) {
        enabledLocalesMap[languageId] = locale;
      }
    });
  });

  // - load locale from session if possible
  // - fallback to browser/default
  // - update session if exists
  //
  N.wire.before('server_chain:*', { priority: -60 }, function locale_set(env, callback) {
    var locale;

    // First of all look for locale in the session.
    if (env.session && env.session.locale) {
      locale = env.session.locale;
    }

    // If not found, try to fetch it from plain cookies.
    if (!locale || !_.contains(N.config.locales.enabled, locale)) {
      locale = env.extras.getCookie('locale');
    }

    // At least try to detect locale from the browser preferences.
    if (!locale || !_.contains(N.config.locales.enabled, locale)) {
      locale = enabledLocalesMap[findAcceptedLanguage(env.origin.req)];
    }

    // If proper locale is still not found, fallback to the default one.
    if (!locale || !_.contains(N.config.locales.enabled, locale)) {
      locale = N.config.locales['default'];
    }

    env.runtime.locale = locale;

    // make sure next time we'll use locale from session directly.
    if (env.session) {
      env.session.locale = env.runtime.locale;
    }

    callback();
  });

};
<commit_msg>AcceptLanguage parser cleanup<commit_after>// - get availavle locales on init stage
// - setup locale fromsession if exists
// - guess locale from browser if no session
//

'use strict';

var _ = require('lodash');

module.exports = function (N) {
  // Enabled locales map of `normalized -> original` pairs.
  //
  //   { 'ru-ru': 'ru-RU', 'en': 'en-US' }
  //
  var enabledLocalesMap = {};

  // RegExp used to extract language quality
  //
  var QUALITY_RE = /^q=([0-9.]+)$/;

  // Parses Accept-Language header string into array of locale names sorted by
  // quality and with appended zone-less fallback for each language.
  //
  //   'en-US;q=0.8,en-GB,ru-RU' -> [ 'en-gb', 'en-us', 'en', 'ru-ru', 'ru' ]
  //
  // NOTE: We limit amount of variant to maximum 10 elements.
  //
  function getAcceptedLanguages(string) {
    var tmp = String(string)
            // remove any whitespace that might appear according to RFC:
            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
            .replace(/\s+/g, '')
            .split(',')
            // Limit list to 10 for safety
            .slice(0, 10);

    return _(tmp)
              // parse partials
              // [ 'en-US;q=0.8', 'en-GB', 'ru-RU' ]
              .map(function (str) {
                var q = 1,
                    parts = str.split(';', 2);

                if (QUALITY_RE.test(parts[1])) {
                  var qval = parseFloat(parts[1].match(QUALITY_RE)[1]);
                  if (!isNaN(qval)) { q = qval; }
                }

                return {
                  locale: parts[0].toLowerCase(),
                  quality: q
                };
              })
              .sortBy(tmp, 'quality')
              .pluck('locale')
              // cleanup garbage
              .compact()
              .uniq()
              .value();
  }

  // find first matching locale from the list of accepted languages
  //
  function findAcceptedLanguage(req) {
    var locales, i, l;

    if (req && req.headers && req.headers['accept-language']) {
      locales = getAcceptedLanguages(req.headers['accept-language']);

      for (i = 0; i < locales.length; i++) {
        l = locales[i];
        if (enabledLocalesMap[l]) {
          return l;
        }
      }

      // if not found - try second pass, with stripped language zones
      for (i = 0; i < locales.length; i++) {
        l = locales[i].split('-', 2)[0];
        if (enabledLocalesMap[l]) {
          return l;
        }
      }
    }
  }

  ////////////////////////////////////////////////////////////////////////////////

  // Fill enabled locales map on INIT stage. (all i18n is done in bundler)
  //
  N.wire.after('init:bundle', function locale_set_prepare(N) {

    // Add full locale names to the map.
    N.config.locales.enabled.forEach(function (locale) {
      enabledLocalesMap[locale.toLowerCase()] = locale;
    });

    // Add zone-less locale aliases like 'en' for 'en-US'.
    N.config.locales.enabled.forEach(function (locale) {
      var languageId = locale.toLowerCase().split('-')[0];

      if (!enabledLocalesMap[languageId]) {
        enabledLocalesMap[languageId] = locale;
      }
    });
  });

  // - load locale from session if possible
  // - fallback to browser/default
  // - update session if exists
  //
  N.wire.before('server_chain:*', { priority: -60 }, function locale_set(env, callback) {
    var locale,
        enabled = N.config.locales.enabled;

    // First of all look for locale in the session.
    if (env.session && env.session.locale) {
      locale = env.session.locale;
    }

    // If not found, try to fetch it from plain cookies.
    if (enabled.indexOf(locale) < 0) {
      locale = env.extras.getCookie('locale');

      // At least try to detect locale from the browser preferences.
      if (enabled.indexOf(locale) < 0) {
        locale = enabledLocalesMap[findAcceptedLanguage(env.origin.req)];

        // If proper locale is still not found, fallback to the default one.
        if (enabled.indexOf(locale) < 0) {
          locale = N.config.locales['default'];
        }
      }
    }

    env.runtime.locale = locale;

    // make sure next time we'll use locale from session directly.
    if (env.session) {
      env.session.locale = env.runtime.locale;
    }

    callback();
  });

};
<|endoftext|>


<commit_before>import React from 'react';
import {graphql, createFragmentContainer} from 'react-relay';
import PropTypes from 'prop-types';

import {
  BranchSetPropType, RemoteSetPropType, ItemTypePropType, EndpointPropType, RefHolderPropType,
} from '../prop-types';
import IssueDetailView from '../views/issue-detail-view';
import CommitDetailItem from '../items/commit-detail-item';
import ReviewsItem from '../items/reviews-item';
import {addEvent} from '../reporter-proxy';
import PullRequestCheckoutController from './pr-checkout-controller';
import PullRequestDetailView from '../views/pr-detail-view';

export class BareIssueishDetailController extends React.Component {
  static propTypes = {
    // Relay response
    relay: PropTypes.object.isRequired,
    repository: PropTypes.shape({
      name: PropTypes.string.isRequired,
      owner: PropTypes.shape({
        login: PropTypes.string.isRequired,
      }).isRequired,
      pullRequest: PropTypes.any,
      issue: PropTypes.any,
    }),

    // Local Repository model properties
    localRepository: PropTypes.object.isRequired,
    branches: BranchSetPropType.isRequired,
    remotes: RemoteSetPropType.isRequired,
    isMerging: PropTypes.bool.isRequired,
    isRebasing: PropTypes.bool.isRequired,
    isAbsent: PropTypes.bool.isRequired,
    isLoading: PropTypes.bool.isRequired,
    isPresent: PropTypes.bool.isRequired,
    workdirPath: PropTypes.string,
    issueishNumber: PropTypes.number.isRequired,

    // Review comment threads
    reviewCommentsLoading: PropTypes.bool.isRequired,
    reviewCommentsTotalCount: PropTypes.number.isRequired,
    reviewCommentsResolvedCount: PropTypes.number.isRequired,
    reviewCommentThreads: PropTypes.arrayOf(PropTypes.shape({
      thread: PropTypes.object.isRequired,
      comments: PropTypes.arrayOf(PropTypes.object).isRequired,
    })).isRequired,

    // Connection information
    endpoint: EndpointPropType.isRequired,
    token: PropTypes.string.isRequired,

    // Atom environment
    workspace: PropTypes.object.isRequired,
    commands: PropTypes.object.isRequired,
    keymaps: PropTypes.object.isRequired,
    tooltips: PropTypes.object.isRequired,
    config: PropTypes.object.isRequired,

    // Action methods
    onTitleChange: PropTypes.func.isRequired,
    switchToIssueish: PropTypes.func.isRequired,
    destroy: PropTypes.func.isRequired,
    reportMutationErrors: PropTypes.func.isRequired,

    // Item context
    itemType: ItemTypePropType.isRequired,
    refEditor: RefHolderPropType.isRequired,

    // For opening files changed tab
    initChangedFilePath: PropTypes.string,
    initChangedFilePosition: PropTypes.number,
    selectedTab: PropTypes.number.isRequired,
    onTabSelected: PropTypes.func.isRequired,
    onOpenFilesTab: PropTypes.func.isRequired,
  }

  componentDidMount() {
    this.updateTitle();
  }

  componentDidUpdate() {
    this.updateTitle();
  }

  updateTitle() {
    const {repository} = this.props;
    if (repository && (repository.issue || repository.pullRequest)) {
      let prefix, issueish;
      if (this.getTypename() === 'PullRequest') {
        prefix = 'PR:';
        issueish = repository.pullRequest;
      } else {
        prefix = 'Issue:';
        issueish = repository.issue;
      }
      const title = `${prefix} ${repository.owner.login}/${repository.name}#${issueish.number} — ${issueish.title}`;
      this.props.onTitleChange(title);
    }
  }

  render() {
    const {repository} = this.props;
    if (!repository || !repository.issue || !repository.pullRequest) {
      return
Issue/PR #{this.props.issueishNumber} not found
; // TODO: no PRs
    }

    if (this.getTypename() === 'PullRequest') {
      // todo: clean up the props that we are passing here omg
      return (
        <PullRequestCheckoutController
          repository={repository}
          pullRequest={repository.pullRequest}

          localRepository={this.props.localRepository}
          isAbsent={this.props.isAbsent}
          isLoading={this.props.isLoading}
          isPresent={this.props.isPresent}
          isMerging={this.props.isMerging}
          isRebasing={this.props.isRebasing}
          branches={this.props.branches}
          remotes={this.props.remotes}>

          {checkoutOp => (
            <PullRequestDetailView
              relay={this.props.relay}
              repository={this.props.repository}
              pullRequest={this.props.repository.pullRequest}

              checkoutOp={checkoutOp}
              localRepository={this.props.localRepository}

              reviewCommentsLoading={this.props.reviewCommentsLoading}
              reviewCommentsTotalCount={this.props.reviewCommentsTotalCount}
              reviewCommentsResolvedCount={this.props.reviewCommentsResolvedCount}
              reviewCommentThreads={this.props.reviewCommentThreads}

              endpoint={this.props.endpoint}
              token={this.props.token}

              workspace={this.props.workspace}
              commands={this.props.commands}
              keymaps={this.props.keymaps}
              tooltips={this.props.tooltips}
              config={this.props.config}

              openCommit={this.openCommit}
              openReviews={this.openReviews}
              switchToIssueish={this.props.switchToIssueish}
              destroy={this.props.destroy}
              reportMutationErrors={this.props.reportMutationErrors}

              itemType={this.props.itemType}
              refEditor={this.props.refEditor}

              initChangedFilePath={this.props.initChangedFilePath}
              initChangedFilePosition={this.props.initChangedFilePosition}
              selectedTab={this.props.selectedTab}
              onTabSelected={this.props.onTabSelected}
              onOpenFilesTab={this.props.onOpenFilesTab}
              workdirPath={this.props.workdirPath}
            />
          )}

        </PullRequestCheckoutController>
      );
    } else {
      return (
        <IssueDetailView
          repository={repository}
          issue={repository.issue}
          switchToIssueish={this.props.switchToIssueish}
          tooltips={this.props.tooltips}
          reportMutationErrors={this.props.reportMutationErrors}
        />
      );
    }
  }

  openCommit = async ({sha}) => {
    /* istanbul ignore if */
    if (!this.props.workdirPath) {
      return;
    }

    const uri = CommitDetailItem.buildURI(this.props.workdirPath, sha);
    await this.props.workspace.open(uri, {pending: true});
    addEvent('open-commit-in-pane', {package: 'github', from: this.constructor.name});
  }

  openReviews = async () => {
    /* istanbul ignore if */
    if (this.getTypename() !== 'PullRequest') {
      return;
    }

    const uri = ReviewsItem.buildURI(
      this.props.endpoint.getHost(),
      this.props.repository.owner.login,
      this.props.repository.name,
      this.props.issueishNumber,
      this.props.workdirPath,
    );
    await this.props.workspace.open(uri);
    addEvent('open-reviews-tab', {package: 'github', from: this.constructor.name});
  }

  getTypename() {
    const {repository} = this.props;
    /* istanbul ignore if */
    if (!repository) {
      return null;
    }
    /* istanbul ignore if */
    if (!repository.pullRequest) {
      return null;
    }
    return repository.pullRequest.__typename;
  }
}

export default createFragmentContainer(BareIssueishDetailController, {
  repository: graphql`
    fragment issueishDetailController_repository on Repository
    @argumentDefinitions(
      issueishNumber: {type: "Int!"}
      timelineCount: {type: "Int!"}
      timelineCursor: {type: "String"}
      commitCount: {type: "Int!"}
      commitCursor: {type: "String"}
    ) {
      ...issueDetailView_repository
      ...prCheckoutController_repository
      ...prDetailView_repository
      name
      owner {
        login
      }
      issue: issueOrPullRequest(number: $issueishNumber) {
        __typename
        ... on Issue {
          title
          number
          ...issueDetailView_issue @arguments(
            timelineCount: $timelineCount,
            timelineCursor: $timelineCursor,
          )
        }
      }
      pullRequest: issueOrPullRequest(number: $issueishNumber) {
        __typename
        ... on PullRequest {
          title
          number
          ...prCheckoutController_pullRequest
          ...prDetailView_pullRequest @arguments(
            timelineCount: $timelineCount
            timelineCursor: $timelineCursor
            commitCount: $commitCount
            commitCursor: $commitCursor
            reviewCount: $reviewCount
            reviewCursor: $reviewCursor
            threadCount: $threadCount
            threadCursor: $threadCursor
            commentCount: $commentCount
            commentCursor: $commentCursor
          )
        }
      }
    }
  `,
});
<commit_msg>Remove TODO<commit_after>import React from 'react';
import {graphql, createFragmentContainer} from 'react-relay';
import PropTypes from 'prop-types';

import {
  BranchSetPropType, RemoteSetPropType, ItemTypePropType, EndpointPropType, RefHolderPropType,
} from '../prop-types';
import IssueDetailView from '../views/issue-detail-view';
import CommitDetailItem from '../items/commit-detail-item';
import ReviewsItem from '../items/reviews-item';
import {addEvent} from '../reporter-proxy';
import PullRequestCheckoutController from './pr-checkout-controller';
import PullRequestDetailView from '../views/pr-detail-view';

export class BareIssueishDetailController extends React.Component {
  static propTypes = {
    // Relay response
    relay: PropTypes.object.isRequired,
    repository: PropTypes.shape({
      name: PropTypes.string.isRequired,
      owner: PropTypes.shape({
        login: PropTypes.string.isRequired,
      }).isRequired,
      pullRequest: PropTypes.any,
      issue: PropTypes.any,
    }),

    // Local Repository model properties
    localRepository: PropTypes.object.isRequired,
    branches: BranchSetPropType.isRequired,
    remotes: RemoteSetPropType.isRequired,
    isMerging: PropTypes.bool.isRequired,
    isRebasing: PropTypes.bool.isRequired,
    isAbsent: PropTypes.bool.isRequired,
    isLoading: PropTypes.bool.isRequired,
    isPresent: PropTypes.bool.isRequired,
    workdirPath: PropTypes.string,
    issueishNumber: PropTypes.number.isRequired,

    // Review comment threads
    reviewCommentsLoading: PropTypes.bool.isRequired,
    reviewCommentsTotalCount: PropTypes.number.isRequired,
    reviewCommentsResolvedCount: PropTypes.number.isRequired,
    reviewCommentThreads: PropTypes.arrayOf(PropTypes.shape({
      thread: PropTypes.object.isRequired,
      comments: PropTypes.arrayOf(PropTypes.object).isRequired,
    })).isRequired,

    // Connection information
    endpoint: EndpointPropType.isRequired,
    token: PropTypes.string.isRequired,

    // Atom environment
    workspace: PropTypes.object.isRequired,
    commands: PropTypes.object.isRequired,
    keymaps: PropTypes.object.isRequired,
    tooltips: PropTypes.object.isRequired,
    config: PropTypes.object.isRequired,

    // Action methods
    onTitleChange: PropTypes.func.isRequired,
    switchToIssueish: PropTypes.func.isRequired,
    destroy: PropTypes.func.isRequired,
    reportMutationErrors: PropTypes.func.isRequired,

    // Item context
    itemType: ItemTypePropType.isRequired,
    refEditor: RefHolderPropType.isRequired,

    // For opening files changed tab
    initChangedFilePath: PropTypes.string,
    initChangedFilePosition: PropTypes.number,
    selectedTab: PropTypes.number.isRequired,
    onTabSelected: PropTypes.func.isRequired,
    onOpenFilesTab: PropTypes.func.isRequired,
  }

  componentDidMount() {
    this.updateTitle();
  }

  componentDidUpdate() {
    this.updateTitle();
  }

  updateTitle() {
    const {repository} = this.props;
    if (repository && (repository.issue || repository.pullRequest)) {
      let prefix, issueish;
      if (this.getTypename() === 'PullRequest') {
        prefix = 'PR:';
        issueish = repository.pullRequest;
      } else {
        prefix = 'Issue:';
        issueish = repository.issue;
      }
      const title = `${prefix} ${repository.owner.login}/${repository.name}#${issueish.number} — ${issueish.title}`;
      this.props.onTitleChange(title);
    }
  }

  render() {
    const {repository} = this.props;
    if (!repository || !repository.issue || !repository.pullRequest) {
      return
Issue/PR #{this.props.issueishNumber} not found
; // TODO: no PRs
    }

    if (this.getTypename() === 'PullRequest') {
      return (
        <PullRequestCheckoutController
          repository={repository}
          pullRequest={repository.pullRequest}

          localRepository={this.props.localRepository}
          isAbsent={this.props.isAbsent}
          isLoading={this.props.isLoading}
          isPresent={this.props.isPresent}
          isMerging={this.props.isMerging}
          isRebasing={this.props.isRebasing}
          branches={this.props.branches}
          remotes={this.props.remotes}>

          {checkoutOp => (
            <PullRequestDetailView
              relay={this.props.relay}
              repository={this.props.repository}
              pullRequest={this.props.repository.pullRequest}

              checkoutOp={checkoutOp}
              localRepository={this.props.localRepository}

              reviewCommentsLoading={this.props.reviewCommentsLoading}
              reviewCommentsTotalCount={this.props.reviewCommentsTotalCount}
              reviewCommentsResolvedCount={this.props.reviewCommentsResolvedCount}
              reviewCommentThreads={this.props.reviewCommentThreads}

              endpoint={this.props.endpoint}
              token={this.props.token}

              workspace={this.props.workspace}
              commands={this.props.commands}
              keymaps={this.props.keymaps}
              tooltips={this.props.tooltips}
              config={this.props.config}

              openCommit={this.openCommit}
              openReviews={this.openReviews}
              switchToIssueish={this.props.switchToIssueish}
              destroy={this.props.destroy}
              reportMutationErrors={this.props.reportMutationErrors}

              itemType={this.props.itemType}
              refEditor={this.props.refEditor}

              initChangedFilePath={this.props.initChangedFilePath}
              initChangedFilePosition={this.props.initChangedFilePosition}
              selectedTab={this.props.selectedTab}
              onTabSelected={this.props.onTabSelected}
              onOpenFilesTab={this.props.onOpenFilesTab}
              workdirPath={this.props.workdirPath}
            />
          )}

        </PullRequestCheckoutController>
      );
    } else {
      return (
        <IssueDetailView
          repository={repository}
          issue={repository.issue}
          switchToIssueish={this.props.switchToIssueish}
          tooltips={this.props.tooltips}
          reportMutationErrors={this.props.reportMutationErrors}
        />
      );
    }
  }

  openCommit = async ({sha}) => {
    /* istanbul ignore if */
    if (!this.props.workdirPath) {
      return;
    }

    const uri = CommitDetailItem.buildURI(this.props.workdirPath, sha);
    await this.props.workspace.open(uri, {pending: true});
    addEvent('open-commit-in-pane', {package: 'github', from: this.constructor.name});
  }

  openReviews = async () => {
    /* istanbul ignore if */
    if (this.getTypename() !== 'PullRequest') {
      return;
    }

    const uri = ReviewsItem.buildURI(
      this.props.endpoint.getHost(),
      this.props.repository.owner.login,
      this.props.repository.name,
      this.props.issueishNumber,
      this.props.workdirPath,
    );
    await this.props.workspace.open(uri);
    addEvent('open-reviews-tab', {package: 'github', from: this.constructor.name});
  }

  getTypename() {
    const {repository} = this.props;
    /* istanbul ignore if */
    if (!repository) {
      return null;
    }
    /* istanbul ignore if */
    if (!repository.pullRequest) {
      return null;
    }
    return repository.pullRequest.__typename;
  }
}

export default createFragmentContainer(BareIssueishDetailController, {
  repository: graphql`
    fragment issueishDetailController_repository on Repository
    @argumentDefinitions(
      issueishNumber: {type: "Int!"}
      timelineCount: {type: "Int!"}
      timelineCursor: {type: "String"}
      commitCount: {type: "Int!"}
      commitCursor: {type: "String"}
    ) {
      ...issueDetailView_repository
      ...prCheckoutController_repository
      ...prDetailView_repository
      name
      owner {
        login
      }
      issue: issueOrPullRequest(number: $issueishNumber) {
        __typename
        ... on Issue {
          title
          number
          ...issueDetailView_issue @arguments(
            timelineCount: $timelineCount,
            timelineCursor: $timelineCursor,
          )
        }
      }
      pullRequest: issueOrPullRequest(number: $issueishNumber) {
        __typename
        ... on PullRequest {
          title
          number
          ...prCheckoutController_pullRequest
          ...prDetailView_pullRequest @arguments(
            timelineCount: $timelineCount
            timelineCursor: $timelineCursor
            commitCount: $commitCount
            commitCursor: $commitCursor
            reviewCount: $reviewCount
            reviewCursor: $reviewCursor
            threadCount: $threadCount
            threadCursor: $threadCursor
            commentCount: $commentCount
            commentCursor: $commentCursor
          )
        }
      }
    }
  `,
});
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import {GitError} from '../git-shell-out-strategy';
import ObserveModelDecorator from '../decorators/observe-model';
import {BranchPropType, RemotePropType} from '../prop-types';
import BranchView from '../views/branch-view';
import BranchMenuView from '../views/branch-menu-view';
import PushPullView from '../views/push-pull-view';
import PushPullMenuView from '../views/push-pull-menu-view';
import ChangedFilesCountView from '../views/changed-files-count-view';
import Tooltip from '../views/tooltip';
import Commands, {Command} from '../views/commands';
import {nullBranch} from '../models/branch';
import {nullRemote} from '../models/remote';
import yubikiri from 'yubikiri';
import {autobind} from 'core-decorators';

@ObserveModelDecorator({
  getModel: props => props.repository,
  fetchData: repository => {
    return yubikiri({
      currentBranch: repository.getCurrentBranch(),
      branches: repository.getBranches(),
      changedFilesCount: repository.getStatusesForChangedFiles().then(statuses => {
        const {stagedFiles, unstagedFiles, mergeConflictFiles} = statuses;
        const changedFiles = new Set();

        for (const filePath in unstagedFiles) {
          changedFiles.add(filePath);
        }
        for (const filePath in stagedFiles) {
          changedFiles.add(filePath);
        }
        for (const filePath in mergeConflictFiles) {
          changedFiles.add(filePath);
        }

        return changedFiles.size;
      }),
      currentRemote: async query => repository.getRemoteForBranch((await query.currentBranch).getName()),
      aheadCount: async query => repository.getAheadCount((await query.currentBranch).getName()),
      behindCount: async query => repository.getBehindCount((await query.currentBranch).getName()),
      originExists: async () => {
        const remotes = await repository.getRemotes();
        return remotes.filter(remote => remote.getName() === 'origin').length > 0;
      },
    });
  },
})
export default class StatusBarTileController extends React.Component {
  static propTypes = {
    workspace: PropTypes.object.isRequired,
    notificationManager: PropTypes.object.isRequired,
    commandRegistry: PropTypes.object.isRequired,
    tooltips: PropTypes.object.isRequired,
    confirm: PropTypes.func.isRequired,
    repository: PropTypes.object.isRequired,
    currentBranch: BranchPropType.isRequired,
    branches: PropTypes.arrayOf(BranchPropType).isRequired,
    currentRemote: RemotePropType.isRequired,
    aheadCount: PropTypes.number,
    behindCount: PropTypes.number,
    changedFilesCount: PropTypes.number,
    originExists: PropTypes.bool,
    toggleGitTab: PropTypes.func,
  }

  static defaultProps = {
    currentBranch: nullBranch,
    branches: [],
    currentRemote: nullRemote,
    toggleGitTab: () => {},
  }

  constructor(props, context) {
    super(props, context);

    this.state = {
      inProgress: false,
      pushInProgress: false,
      fetchInProgress: false,
    };
  }

  render() {
    const repoProps = {
      repository: this.props.repository,
      currentBranch: this.props.currentBranch,
      branches: this.props.branches,
      currentRemote: this.props.currentRemote,
      aheadCount: this.props.aheadCount,
      behindCount: this.props.behindCount,
      changedFilesCount: this.props.changedFilesCount,
    };

    return (

        {this.renderTiles(repoProps)}
        <ChangedFilesCountView
          didClick={this.props.toggleGitTab}
          {...repoProps}
        />

    );
  }

  renderTiles(repoProps) {
    if (!this.props.repository.showStatusBarTiles()) {
      return null;
    }

    return (

        <Commands registry={this.props.commandRegistry} target="atom-workspace">
          <Command command="github:fetch" callback={this.fetch} />
          <Command command="github:pull" callback={this.pull} />
          <Command
            command="github:push"
            callback={() => this.push({force: false, setUpstream: !this.props.currentRemote.isPresent()})}
          />
          <Command
            command="github:force-push"
            callback={() => this.push({force: true, setUpstream: !this.props.currentRemote.isPresent()})}
          />
        </Commands>
        <BranchView
          ref={e => { this.branchView = e; }}
          workspace={this.props.workspace}
          checkout={this.checkout}
          {...repoProps}
        />
        <Tooltip
          manager={this.props.tooltips}
          target={() => this.branchView}
          trigger="click"
          className="github-StatusBarTileController-tooltipMenu">
          <BranchMenuView
            workspace={this.props.workspace}
            notificationManager={this.props.notificationManager}
            commandRegistry={this.props.commandRegistry}
            checkout={this.checkout}
            {...repoProps}
          />
        </Tooltip>
        <PushPullView
          ref={e => { this.pushPullView = e; }}
          pushInProgress={this.state.pushInProgress}
          fetchInProgress={this.state.fetchInProgress}
          {...repoProps}
        />
        <Tooltip
          manager={this.props.tooltips}
          target={() => this.pushPullView}
          trigger="click"
          className="github-StatusBarTileController-tooltipMenu">
          <PushPullMenuView
            onMarkSpecialClick={this.handleOpenGitTimingsView}
            workspace={this.props.workspace}
            inProgress={this.state.inProgress}
            originExists={!!this.props.originExists}
            push={this.push}
            pull={this.pull}
            fetch={this.fetch}
            {...repoProps}
          />
        </Tooltip>

    );
  }

  @autobind
  handleOpenGitTimingsView(e) {
    e && e.preventDefault();
    this.props.workspace.open('atom-github://debug/timings');
  }

  setInProgressWhile(block, {push, pull, fetch} = {push: false, pull: false, fetch: false}) {
    return new Promise((resolve, reject) => {
      if (this.state.inProgress) {
        resolve();
        return;
      }

      this.setState({inProgress: true, pushInProgress: push, fetchInProgress: pull || fetch}, async () => {
        try {
          await block();
        } catch (e) {
          reject(e);
        } finally {
          this.setState({inProgress: false, pushInProgress: false, fetchInProgress: false}, resolve);
        }
      });
    });
  }

  async attemptGitOperation(operation, errorTransform = error => ({message: error.stdErr})) {
    const operationPromise = operation();
    try {
      return await operationPromise;
    } catch (error) {
      if (!(error instanceof GitError)) { throw error; }
      const {type, message, description} = errorTransform(error);
      if (type === 'Error') {
        this.props.notificationManager.addError(
          message || 'Cannot complete remote interaction',
          {description, dismissable: true},
        );
      } else if (type === 'Warning') {
        this.props.notificationManager.addWarning(
          message || 'Cannot complete remote interaction',
          {description, dismissable: true},
        );
      } else {
        throw new Error(`Notification type ${type} not currently supported.`);
      }
      return null;
    }
  }

  @autobind
  checkout(branchName, options) {
    return this.setInProgressWhile(() => this.props.repository.checkout(branchName, options));
  }

  @autobind
  async push({force, setUpstream}) {
    await this.attemptGitOperation(
      () => this.doPush({force, setUpstream}),
      error => {
        if (/rejected[\s\S]*failed to push/.test(error.stdErr)) {
          return {
            type: 'Error',
            message: 'Push rejected',
            description: 'The tip of your current branch is behind its remote counterpart.' +
              ' Try pulling before pushing again. Or, to force push, hold `cmd` or `ctrl` while clicking.',
          };
        }

        return {type: 'Error', message: 'Unable to push', description: `<pre>${error.stdErr}</pre>`};
      },
    );
  }

  async doPush(options) {
    if (options.force) {
      const choice = this.props.confirm({
        message: 'Are you sure you want to force push?',
        detailedMessage: 'This operation could result in losing data on the remote.',
        buttons: ['Force Push', 'Cancel Push'],
      });
      if (choice !== 0) { return; }
    }

    await this.setInProgressWhile(() => {
      return this.props.repository.push(this.props.currentBranch.getName(), options);
    }, {push: true});
  }

  @autobind
  async pull() {
    await this.attemptGitOperation(
      () => this.doPull(),
      error => {
        if (/error: Your local changes to the following files would be overwritten by merge/.test(error.stdErr)) {
          const lines = error.stdErr.split('\n');
          const files = lines.slice(3, lines.length - 3).map(l => `\`${l.trim()}\``).join('
');
          return {
            type: 'Error',
            message: 'Pull aborted',
            description: 'Local changes to the following would be overwritten by merge:
' + files +
              '
Please commit your changes or stash them before you merge.',
          };
        } else if (/Automatic merge failed; fix conflicts and then commit the result./.test(error.stdOut)) {
          return {
            type: 'Warning',
            message: 'Automatic merge after pull failed',
            description: 'Please fix conflicts and then commit the result.',
          };
        }

        return {type: 'Error', message: 'Unable to pull', description: `<pre>${error.stdErr}</pre>`};
      },
    );

  }

  async doPull() {
    await this.setInProgressWhile(() => this.props.repository.pull(this.props.currentBranch.getName()), {pull: true});
  }

  @autobind
  async fetch() {
    await this.attemptGitOperation(
      () => this.doFetch(),
      error => {
        return {
          type: 'Error',
          message: 'Unable to fetch',
          description: `<pre>${error.stdErr}</pre>`,
        };
      },
    );
  }

  async doFetch() {
    await this.setInProgressWhile(() => this.props.repository.fetch(this.props.currentBranch.getName()), {fetch: true});
  }
}
<commit_msg>Use friendlier language in warning notification<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import {GitError} from '../git-shell-out-strategy';
import ObserveModelDecorator from '../decorators/observe-model';
import {BranchPropType, RemotePropType} from '../prop-types';
import BranchView from '../views/branch-view';
import BranchMenuView from '../views/branch-menu-view';
import PushPullView from '../views/push-pull-view';
import PushPullMenuView from '../views/push-pull-menu-view';
import ChangedFilesCountView from '../views/changed-files-count-view';
import Tooltip from '../views/tooltip';
import Commands, {Command} from '../views/commands';
import {nullBranch} from '../models/branch';
import {nullRemote} from '../models/remote';
import yubikiri from 'yubikiri';
import {autobind} from 'core-decorators';

@ObserveModelDecorator({
  getModel: props => props.repository,
  fetchData: repository => {
    return yubikiri({
      currentBranch: repository.getCurrentBranch(),
      branches: repository.getBranches(),
      changedFilesCount: repository.getStatusesForChangedFiles().then(statuses => {
        const {stagedFiles, unstagedFiles, mergeConflictFiles} = statuses;
        const changedFiles = new Set();

        for (const filePath in unstagedFiles) {
          changedFiles.add(filePath);
        }
        for (const filePath in stagedFiles) {
          changedFiles.add(filePath);
        }
        for (const filePath in mergeConflictFiles) {
          changedFiles.add(filePath);
        }

        return changedFiles.size;
      }),
      currentRemote: async query => repository.getRemoteForBranch((await query.currentBranch).getName()),
      aheadCount: async query => repository.getAheadCount((await query.currentBranch).getName()),
      behindCount: async query => repository.getBehindCount((await query.currentBranch).getName()),
      originExists: async () => {
        const remotes = await repository.getRemotes();
        return remotes.filter(remote => remote.getName() === 'origin').length > 0;
      },
    });
  },
})
export default class StatusBarTileController extends React.Component {
  static propTypes = {
    workspace: PropTypes.object.isRequired,
    notificationManager: PropTypes.object.isRequired,
    commandRegistry: PropTypes.object.isRequired,
    tooltips: PropTypes.object.isRequired,
    confirm: PropTypes.func.isRequired,
    repository: PropTypes.object.isRequired,
    currentBranch: BranchPropType.isRequired,
    branches: PropTypes.arrayOf(BranchPropType).isRequired,
    currentRemote: RemotePropType.isRequired,
    aheadCount: PropTypes.number,
    behindCount: PropTypes.number,
    changedFilesCount: PropTypes.number,
    originExists: PropTypes.bool,
    toggleGitTab: PropTypes.func,
  }

  static defaultProps = {
    currentBranch: nullBranch,
    branches: [],
    currentRemote: nullRemote,
    toggleGitTab: () => {},
  }

  constructor(props, context) {
    super(props, context);

    this.state = {
      inProgress: false,
      pushInProgress: false,
      fetchInProgress: false,
    };
  }

  render() {
    const repoProps = {
      repository: this.props.repository,
      currentBranch: this.props.currentBranch,
      branches: this.props.branches,
      currentRemote: this.props.currentRemote,
      aheadCount: this.props.aheadCount,
      behindCount: this.props.behindCount,
      changedFilesCount: this.props.changedFilesCount,
    };

    return (

        {this.renderTiles(repoProps)}
        <ChangedFilesCountView
          didClick={this.props.toggleGitTab}
          {...repoProps}
        />

    );
  }

  renderTiles(repoProps) {
    if (!this.props.repository.showStatusBarTiles()) {
      return null;
    }

    return (

        <Commands registry={this.props.commandRegistry} target="atom-workspace">
          <Command command="github:fetch" callback={this.fetch} />
          <Command command="github:pull" callback={this.pull} />
          <Command
            command="github:push"
            callback={() => this.push({force: false, setUpstream: !this.props.currentRemote.isPresent()})}
          />
          <Command
            command="github:force-push"
            callback={() => this.push({force: true, setUpstream: !this.props.currentRemote.isPresent()})}
          />
        </Commands>
        <BranchView
          ref={e => { this.branchView = e; }}
          workspace={this.props.workspace}
          checkout={this.checkout}
          {...repoProps}
        />
        <Tooltip
          manager={this.props.tooltips}
          target={() => this.branchView}
          trigger="click"
          className="github-StatusBarTileController-tooltipMenu">
          <BranchMenuView
            workspace={this.props.workspace}
            notificationManager={this.props.notificationManager}
            commandRegistry={this.props.commandRegistry}
            checkout={this.checkout}
            {...repoProps}
          />
        </Tooltip>
        <PushPullView
          ref={e => { this.pushPullView = e; }}
          pushInProgress={this.state.pushInProgress}
          fetchInProgress={this.state.fetchInProgress}
          {...repoProps}
        />
        <Tooltip
          manager={this.props.tooltips}
          target={() => this.pushPullView}
          trigger="click"
          className="github-StatusBarTileController-tooltipMenu">
          <PushPullMenuView
            onMarkSpecialClick={this.handleOpenGitTimingsView}
            workspace={this.props.workspace}
            inProgress={this.state.inProgress}
            originExists={!!this.props.originExists}
            push={this.push}
            pull={this.pull}
            fetch={this.fetch}
            {...repoProps}
          />
        </Tooltip>

    );
  }

  @autobind
  handleOpenGitTimingsView(e) {
    e && e.preventDefault();
    this.props.workspace.open('atom-github://debug/timings');
  }

  setInProgressWhile(block, {push, pull, fetch} = {push: false, pull: false, fetch: false}) {
    return new Promise((resolve, reject) => {
      if (this.state.inProgress) {
        resolve();
        return;
      }

      this.setState({inProgress: true, pushInProgress: push, fetchInProgress: pull || fetch}, async () => {
        try {
          await block();
        } catch (e) {
          reject(e);
        } finally {
          this.setState({inProgress: false, pushInProgress: false, fetchInProgress: false}, resolve);
        }
      });
    });
  }

  async attemptGitOperation(operation, errorTransform = error => ({message: error.stdErr})) {
    const operationPromise = operation();
    try {
      return await operationPromise;
    } catch (error) {
      if (!(error instanceof GitError)) { throw error; }
      const {type, message, description} = errorTransform(error);
      if (type === 'Error') {
        this.props.notificationManager.addError(
          message || 'Cannot complete remote interaction',
          {description, dismissable: true},
        );
      } else if (type === 'Warning') {
        this.props.notificationManager.addWarning(
          message || 'Cannot complete remote interaction',
          {description, dismissable: true},
        );
      } else {
        throw new Error(`Notification type ${type} not currently supported.`);
      }
      return null;
    }
  }

  @autobind
  checkout(branchName, options) {
    return this.setInProgressWhile(() => this.props.repository.checkout(branchName, options));
  }

  @autobind
  async push({force, setUpstream}) {
    await this.attemptGitOperation(
      () => this.doPush({force, setUpstream}),
      error => {
        if (/rejected[\s\S]*failed to push/.test(error.stdErr)) {
          return {
            type: 'Error',
            message: 'Push rejected',
            description: 'The tip of your current branch is behind its remote counterpart.' +
              ' Try pulling before pushing again. Or, to force push, hold `cmd` or `ctrl` while clicking.',
          };
        }

        return {type: 'Error', message: 'Unable to push', description: `<pre>${error.stdErr}</pre>`};
      },
    );
  }

  async doPush(options) {
    if (options.force) {
      const choice = this.props.confirm({
        message: 'Are you sure you want to force push?',
        detailedMessage: 'This operation could result in losing data on the remote.',
        buttons: ['Force Push', 'Cancel Push'],
      });
      if (choice !== 0) { return; }
    }

    await this.setInProgressWhile(() => {
      return this.props.repository.push(this.props.currentBranch.getName(), options);
    }, {push: true});
  }

  @autobind
  async pull() {
    await this.attemptGitOperation(
      () => this.doPull(),
      error => {
        if (/error: Your local changes to the following files would be overwritten by merge/.test(error.stdErr)) {
          const lines = error.stdErr.split('\n');
          const files = lines.slice(3, lines.length - 3).map(l => `\`${l.trim()}\``).join('
');
          return {
            type: 'Error',
            message: 'Pull aborted',
            description: 'Local changes to the following would be overwritten by merge:
' + files +
              '
Please commit your changes or stash them before you merge.',
          };
        } else if (/Automatic merge failed; fix conflicts and then commit the result./.test(error.stdOut)) {
          return {
            type: 'Warning',
            message: 'Your pull resulted in merge conflicts',
            description: `Your last pull resulted in merge conflicts between your local changes
              and the changes on the remote. You can resolve the conflicts with the Git panel
              and commit them to continue.`,
          };
        }

        return {type: 'Error', message: 'Unable to pull', description: `<pre>${error.stdErr}</pre>`};
      },
    );

  }

  async doPull() {
    await this.setInProgressWhile(() => this.props.repository.pull(this.props.currentBranch.getName()), {pull: true});
  }

  @autobind
  async fetch() {
    await this.attemptGitOperation(
      () => this.doFetch(),
      error => {
        return {
          type: 'Error',
          message: 'Unable to fetch',
          description: `<pre>${error.stdErr}</pre>`,
        };
      },
    );
  }

  async doFetch() {
    await this.setInProgressWhile(() => this.props.repository.fetch(this.props.currentBranch.getName()), {fetch: true});
  }
}
<|endoftext|>


<commit_before>var config = require('config');
var log = require('./client/log')('geocode');
var get = require('./client/request').get;

var southWest = [-123.099060058594, 36.745486924699];
var northEast = [-121.192932128906, 38.182068998322];

/**********tismart **********************/
var dev_amigo_token = "R:3jqO9zmsFuFpdn0BosPJbXpjf82PISOJXqMbwN";
console.log("imprimir key token actual 2");
console.log(config.realtime_access_token());

/**
 * Geocode
 */

module.exports = geocode;
module.exports.reverse = reverse;
module.exports.suggest = suggest;

/**
 * Geocode
 */

function geocode(address, callback) {
  log('--> geocoding %s', address);
  get('/geocode/' + address, function(err, res) {
    if (err) {
      log('<-- geocoding error %s', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Reverse geocode
 */

function reverse(ll, callback) {
  log('--> reverse geocoding %s', ll);
  get('/geocode/reverse/' + ll[0] + ',' + ll[1], function(err, res) {
    if (err) {
      log('<-- geocoding error %e', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Suggestions!
 */

function suggest(text, callback) {
  var bingSuggestions, nominatimSuggestions, totalSuggestions;
  log('--> getting suggestion for %s', text);

  get('https://www.amigocloud.com/api/v1/me/geocoder/autocomplete?text=' + text +'&token=' + dev_amigo_token, function(err, res) {

    if(err) {
        console.log("Error amigo cloud");
        console.log(err);
    }else{
        console.log("json amigo cloud response");
        console.log(res);
    }
  });

  get('/geocode/suggest/'+ text, function(err, res){

    if (err) {
      log('<-- suggestion error %s', err);
      callback(err, res);
    } else {
      log('<-- got %s suggestions', res.body.length);

	bingSuggestions = res.body;

    console.log("------------API GEOCODE---------------");
    console.log("res ->", res.body);
    console.log("res.body ->", res);

//      callback(null, res.body);
	get('http://nominatim.openstreetmap.org/search' +
	    '?format=json&addressdetails=1&' +
	    'viewbox=' + southWest[0] + ',' +
	    northEast[1] + ',' + northEast[0] + ',' + southWest[1] +
	    '&bounded=1' +
	    'countrycodes=us&q=' + text, function (err, nRes) {
		var inside = false;
	    nominatimSuggestions = [];
            for (var i = 0; i < nRes.body.length; i++) {
//		inside = inside && (nRes.body[i].lng > southWest[0]);
//		inside = inside && (nRes.body[i].lng < northEast[0]);
//		inside = inside && (nRes.body[i].lat > southWest[1]);
//		inside = inside && (nRes.body[i].lat < northEast[1]);
//		if (inside) {
                    nominatimSuggestions.push(nRes.body[i]);
//		}
            }

            console.log('======data enviada===============');
            callback(
		null,
		nominatimSuggestions.slice(0,2).concat(bingSuggestions.slice(0,3))
	    );
	});
    }
  });

}

var request = require('request');
request('https://www.amigocloud.com/api/v1/me/geocoder/autocomplete?text=palo&token=R:3jqO9zmsFuFpdn0BosPJbXpjf82PISOJXqMbwN', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log("body", body);
    console.log("response",response);
    console.log("error", error)
  }
});
<commit_msg>quitando modulo request<commit_after>var config = require('config');
var log = require('./client/log')('geocode');
var get = require('./client/request').get;

var southWest = [-123.099060058594, 36.745486924699];
var northEast = [-121.192932128906, 38.182068998322];

/**********tismart **********************/
var dev_amigo_token = "R:3jqO9zmsFuFpdn0BosPJbXpjf82PISOJXqMbwN";
console.log("imprimir key token actual 2");
console.log(config.realtime_access_token());

/**
 * Geocode
 */

module.exports = geocode;
module.exports.reverse = reverse;
module.exports.suggest = suggest;

/**
 * Geocode
 */

function geocode(address, callback) {
  log('--> geocoding %s', address);
  get('/geocode/' + address, function(err, res) {
    if (err) {
      log('<-- geocoding error %s', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Reverse geocode
 */

function reverse(ll, callback) {
  log('--> reverse geocoding %s', ll);
  get('/geocode/reverse/' + ll[0] + ',' + ll[1], function(err, res) {
    if (err) {
      log('<-- geocoding error %e', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Suggestions!
 */

function suggest(text, callback) {
  var bingSuggestions, nominatimSuggestions, totalSuggestions;
  log('--> getting suggestion for %s', text);

  get('https://www.amigocloud.com/api/v1/me/geocoder/autocomplete?text=' + text +'&token=' + dev_amigo_token, function(err, res) {

    if(err) {
        console.log("Error amigo cloud");
        console.log(err);
    }else{
        console.log("json amigo cloud response");
        console.log(res);
    }
  });

  get('/geocode/suggest/'+ text, function(err, res){

    if (err) {
      log('<-- suggestion error %s', err);
      callback(err, res);
    } else {
      log('<-- got %s suggestions', res.body.length);

	bingSuggestions = res.body;

    console.log("------------API GEOCODE---------------");
    console.log("res ->", res.body);
    console.log("res.body ->", res);

//      callback(null, res.body);
	get('http://nominatim.openstreetmap.org/search' +
	    '?format=json&addressdetails=1&' +
	    'viewbox=' + southWest[0] + ',' +
	    northEast[1] + ',' + northEast[0] + ',' + southWest[1] +
	    '&bounded=1' +
	    'countrycodes=us&q=' + text, function (err, nRes) {
		var inside = false;
	    nominatimSuggestions = [];
            for (var i = 0; i < nRes.body.length; i++) {
//		inside = inside && (nRes.body[i].lng > southWest[0]);
//		inside = inside && (nRes.body[i].lng < northEast[0]);
//		inside = inside && (nRes.body[i].lat > southWest[1]);
//		inside = inside && (nRes.body[i].lat < northEast[1]);
//		if (inside) {
                    nominatimSuggestions.push(nRes.body[i]);
//		}
            }

            console.log('======data enviada===============');
            console.log(nominatimSuggestions.slice(0,2).concat(bingSuggestions.slice(0,3)));
            callback(
		null,
		nominatimSuggestions.slice(0,2).concat(bingSuggestions.slice(0,3))
	    );
	});
    }
  });

}
});
<|endoftext|>


<commit_before>/**
 * Adds a date and price as a tuple to a targetSeries
 * @param {HighChart.series} targetSeries reference
 * @param {int} date UTC formatted time
 * @param {int} price currency price
 */
var addDataPointToSeries = function (targetSeries, date, price) {
  targetSeries.addPoint([date, price], false);
  // tities
};

// Adds a live data point to a series, differs from "addDataPointToSeries"
//    because it defaults to true for redrawing the chart, hence a "live"
//    addPoint functionality
var addLiveDataPointToSeries = function (targetSeries, date, price) {
  targetSeries.addPoint([date, price], true);
};

/**
 * Adds data points to a certain series, given a data set (chartData)
 * @param {HighChart.series} targetSeries reference
 * @param {object} chartData
 */
var addCandlestickDatasetToSeries = function (targetSeries, candlestick) {
  for (var i = 0; i < candlestick.length; i++) {
    var date = candlestick[i].date * 1000;
    var price = candlestick[i].close;
    console.log('adding point...');
    addDataPointToSeries(targetSeries, date, price);
  }
};

/**
 * Adds data points to a certain series, given a data set (chartData)
 * @param {HighChart.series} targetSeries reference
 * @param {object} chartData
 */
var addBacktestDatasetToSeries = function (targetSeries, candlestick) {
  for (var i = 0; i < candlestick.length; i++) {
    var date = candlestick[i][0] * 1000;
    var price = candlestick[i][1];
    console.log('backtest: adding point...');
    addDataPointToSeries(targetSeries, date, price);
  }
};

/**
 * Adds data points to a certain series, given a data set (chartData)
 * @param {HighChart.series} targetSeries reference
 * @param {object} chartData
 */
var addBenchMarkDatasetToSeries = function (targetSeries, candlestick) {
  for (var i = 0; i < candlestick.length; i++) {
    var date = candlestick[i][0] * 1000;
    var price = candlestick[i][1];
    console.log('benchmark: adding point...');
    addDataPointToSeries(targetSeries, date, price);
  }
};

/**
 * Adds data points to a certain series, given a data set (chartData)
 * @param {HighChart.series} targetSeries reference
 * @param {array[][]} chartData
 */
var addIndicatorDatasetToSeries = function (targetSeries, chartData) {
  for (var i = 0; i < chartData.length; i++) {
    var date = chartData[i][0] * 1000;
    var price = chartData[i][1];
    //console.log('date:', date, 'price:', price);
    addDataPointToSeries(targetSeries, date, price);
  }
};

/**
 * Creates object literal, given paramaters, and adds it to highchart
 * @param {HighChart} highchart self reference
 * @param {object} params parameters to add to series
 */
var createCandlestickSeries = function (highchart, name) {
  var seriesObj = {};
  seriesObj.name = name;
  seriesObj.id = name;
  seriesObj.data = [];
  seriesObj.marker = {
    enabled: true,
    radius: 3
  };
  seriesObj.tooltip = {
    valueDecimals: 5
  };
  highchart.addSeries(seriesObj, true);
};

/**
 * Creates object literal, given paramaters, and adds it to highchart
 * @param {HighChart} highchart self reference
 * @param {object} params parameters to add to series
 */
var createIndicatorSeries = function (highchart, name) {
  var seriesObj = {};
  seriesObj.name = name;
  seriesObj.id = name;
  seriesObj.data = [];
  seriesObj.marker = {
    enabled: false,
    radius: 3
  };
  seriesObj.type = 'spline';
  seriesObj.tooltip = {
    valueDecimals: 5
  };
  highchart.addSeries(seriesObj, true);
};

var createFlagSeries = function (highchart) {
  var seriesObj = {};
  seriesObj.id = 'flags';
  seriesObj.type = 'flags';
  seriesObj.data = [];
  seriesObj.onSeries = '10-Day Moving Average';
  seriesObj.shape = 'circlepin';
  seriesObj.width = 20;

  highchart.addSeries(seriesObj);
};

/**
 * Every flag consists of x, title and text. The attribute "x" must be set to
 * the point where the flag should appear. The attribute "title" is the text
 * which is displayed inside the flag on the chart. The attribute "text" contains
 * the text which will appear when the mouse hover above the flag.
 */
var addFlagToSeries = function (highchart, timeStamp, order) {
  var flagObj = {};
  console.log('inside addFlagToSeries:', timeStamp, order);
  flagObj.x = timeStamp;
  flagObj.title = order;
  flagObj.text = 'Make a trade here.';

  highchart.get('flags').addPoint(flagObj);
};

/**
 * Connects and listens on two sockets to initialize and then update a chart.
 *     initializedChartData creates a series and adds historical data to it.
 *     updatedChartData listens for live data and adds it to a targetSeries
 * @param {HighChart} highchart self reference
 */
var loadStrategyTrades = function (highchart) {
  var socket = io.connect('http://localhost:3000');
  console.log('CONNECTION RECEIVED. SERVER RUNNING AT http://localhost:3000');

  highchart.showLoading('');

  // INITALIZE CHART WITH HISTORICAL DATA
  socket.on('initializedChartData', function (chartData) {

    // setTimeout(function () {
    //   highchart.hideLoading();
    // }, 2000);

    console.log('### initializedChartData received...');
    console.log('### creating series...');

    createCandlestickSeries(highchart, 'Closing Price');
    createIndicatorSeries(highchart, '10-Day Moving Average');
    createIndicatorSeries(highchart, '20-Day Moving Average');

    /* Creating candlestick chart lines */
    var candlestickData = chartData.candlestickData;
    var targetSeries = highchart.get("Closing Price");
    addCandlestickDatasetToSeries(targetSeries, candlestickData);

    /* Adding indicators */
    var SMA10 = chartData.indicators.SMA10;
    var targetSMA10 = highchart.get('10-Day Moving Average');
    console.log('### adding SMA10 to chart');
    addIndicatorDatasetToSeries(targetSMA10, SMA10);

    var SMA20 = chartData.indicators.SMA20;
    var targetSMA20 = highchart.get('20-Day Moving Average');
    console.log('### adding SMA20 to chart');
    addIndicatorDatasetToSeries(targetSMA20, SMA20);

    /* Adding order flags */
    createFlagSeries(highchart);
    for (var i = 0; i < chartData.flags.length; i++) {
      console.log('flag added');
      var timeStamp = chartData.flags[i].timestamp * 1000;
      var orderLongShort = chartData.flags[i].longShort;
      addFlagToSeries(highchart, timeStamp, orderLongShort);
    }

    highchart.hideLoading();

  });

  // UPDATE CHART WITH LIVE DATA
  socket.on('updatedChartData', function (chartData) {
    console.log("### CLIENT: Live Data Point Received");
    var date = chartData.time;
    var price = parseFloat(chartData.mostRecentTickerPrice);
    var targetSeries = highchart.get('Closing Price');
    addLiveDataPointToSeries(targetSeries, date, price);
  });
};

/**
 * Connects and listens on two sockets to initialize and then update a chart.
 *     initializedChartData creates a series and adds historical data to it.
 *     updatedChartData listens for live data and adds it to a targetSeries
 * @param {HighChart} highchart self reference
 */
var loadPortfolioPerformance = function (highchart) {
  var socket = io.connect('http://localhost:3000');
  console.log('CONNECTION RECEIVED. SERVER RUNNING AT http://localhost:3000');
  highchart.showLoading('');

  // INITALIZE CHART WITH HISTORICAL DATA
  socket.on('backtest', function (chartData) {

    console.log('### Portfolio: initializedChartData received...');
    console.log('### Portfolio: creating series...');

    /* Creating candlestick chart lines */
    createIndicatorSeries(highchart, 'Backtest');
    var bt = chartData.backtest;
    //console.log(chartData);
    console.log('bt', bt);
    var btarget = highchart.get('Backtest');
    addBacktestDatasetToSeries(btarget, bt);

    /* Creating candlestick benchmark chart lines */
    createIndicatorSeries(highchart, 'Benchmark');
    var bm = chartData.benchmark;
    var bmtarget = highchart.get('Benchmark');
    addBenchMarkDatasetToSeries(bmtarget, bm);

    /* This line needs to be here for some reason, or else chart won't render properly... */
    createFlagSeries(highchart);

    highchart.hideLoading();
  });
};

$(document).ready(function () {
  $('#hcharts-strategy').highcharts('StockChart', {
    plotOptions: {
      series: {
        dataGrouping: {
          enabled: true,
          groupPixelWidth: 8
        }
      }
    },
    // loading: {
    //     labelStyle: {
    //         fontStyle: 'italic'
    //     }
    // },
    rangeSelector: {
      buttons: [{
        type: 'month',
        count: 1,
        text: '1m'
      }, {
        type: 'month',
        count: 3,
        text: '3m'
      }, {
        type: 'month',
        count: 6,
        text: '6m'
      }, {
        type: 'ytd',
        text: 'YTD'
      }, {
        type: 'year',
        count: 1,
        text: '1y'
      }, {
        type: 'all',
        text: 'All'
      }],
      inputEnabled: false,
      selected: 1
    },

    title: {
      text: 'Moving Avg. Crossover Trades'
    },
    subtitle: {
      text: '+ Indicators (BTC/USD)'
    },
    xAxis: {
      type: 'datetime',
      ordinal: false
    },
    // yAxis:
    //   [{
    //     title: {
    //       text: 'Ticker',
    //     },
    //     opposite: false
    //   }
    // ],
    chart: {
      events: {
        load: function () {
          var self = this;
          loadStrategyTrades(self);
        }
      },
    },
    series: []
  });

  $('#hcharts-portfolio').highcharts('StockChart', {
    plotOptions: {
      series: {
        dataGrouping: {
          enabled: true,
          groupPixelWidth: 15
        }
      }
    },
    rangeSelector: {
      buttons: [{
        type: 'month',
        count: 1,
        text: '1m'
      }, {
        type: 'month',
        count: 3,
        text: '3m'
      }, {
        type: 'month',
        count: 6,
        text: '6m'
      }, {
        type: 'ytd',
        text: 'YTD'
      }, {
        type: 'year',
        count: 1,
        text: '1y'
      }, {
        type: 'all',
        text: 'All'
      }],
      inputEnabled: false,
      selected: 1
    },

    title: {
      text: 'Portfolio Performance'
    },
    subtitle: {
      text: 'Moving Average Crossover Strategy'
    },
    xAxis: {
      type: 'datetime',
      ordinal: false
    },
    // yAxis:
    //   [{
    //     title: {
    //       text: 'Value',
    //     },
    //     opposite: false
    //   }
    // ],
    chart: {
      events: {
        load: function () {
          var self = this;
          loadPortfolioPerformance(self);
        }
      },
    },
    series: []
  });
});
<commit_msg>changed chart type and disabled data grouping<commit_after>/**
 * Adds a date and price as a tuple to a targetSeries
 * @param {HighChart.series} targetSeries reference
 * @param {int} date UTC formatted time
 * @param {int} price currency price
 */
var addDataPointToSeries = function (targetSeries, date, price) {
  targetSeries.addPoint([date, price], false);
  // tities
};

// Adds a live data point to a series, differs from "addDataPointToSeries"
//    because it defaults to true for redrawing the chart, hence a "live"
//    addPoint functionality
var addLiveDataPointToSeries = function (targetSeries, date, price) {
  targetSeries.addPoint([date, price], true);
};

/**
 * Adds data points to a certain series, given a data set (chartData)
 * @param {HighChart.series} targetSeries reference
 * @param {object} chartData
 */
var addCandlestickDatasetToSeries = function (targetSeries, candlestick) {
  for (var i = 0; i < candlestick.length; i++) {
    var date = candlestick[i].date * 1000;
    var price = candlestick[i].close;
    console.log('adding point...');
    addDataPointToSeries(targetSeries, date, price);
  }
};

/**
 * Adds data points to a certain series, given a data set (chartData)
 * @param {HighChart.series} targetSeries reference
 * @param {object} chartData
 */
var addBacktestDatasetToSeries = function (targetSeries, candlestick) {
  for (var i = 0; i < candlestick.length; i++) {
    var date = candlestick[i][0] * 1000;
    var price = candlestick[i][1];
    console.log('backtest: adding point...');
    addDataPointToSeries(targetSeries, date, price);
  }
};

/**
 * Adds data points to a certain series, given a data set (chartData)
 * @param {HighChart.series} targetSeries reference
 * @param {object} chartData
 */
var addBenchMarkDatasetToSeries = function (targetSeries, candlestick) {
  for (var i = 0; i < candlestick.length; i++) {
    var date = candlestick[i][0] * 1000;
    var price = candlestick[i][1];
    console.log('benchmark: adding point...');
    addDataPointToSeries(targetSeries, date, price);
  }
};

/**
 * Adds data points to a certain series, given a data set (chartData)
 * @param {HighChart.series} targetSeries reference
 * @param {array[][]} chartData
 */
var addIndicatorDatasetToSeries = function (targetSeries, chartData) {
  for (var i = 0; i < chartData.length; i++) {
    var date = chartData[i][0] * 1000;
    var price = chartData[i][1];
    //console.log('date:', date, 'price:', price);
    addDataPointToSeries(targetSeries, date, price);
  }
};

/**
 * Creates object literal, given paramaters, and adds it to highchart
 * @param {HighChart} highchart self reference
 * @param {object} params parameters to add to series
 */
var createCandlestickSeries = function (highchart, name) {
  var seriesObj = {};
  seriesObj.name = name;
  seriesObj.id = name;
  seriesObj.data = [];
  seriesObj.marker = {
    enabled: false,
    radius: 3
  };
  seriesObj.tooltip = {
    valueDecimals: 5
  };
  highchart.addSeries(seriesObj, true);
};

/**
 * Creates object literal, given paramaters, and adds it to highchart
 * @param {HighChart} highchart self reference
 * @param {object} params parameters to add to series
 */
var createIndicatorSeries = function (highchart, name, spline) {
  var seriesObj = {};
  seriesObj.name = name;
  seriesObj.id = name;
  seriesObj.data = [];
  seriesObj.marker = {
    enabled: false,
    radius: 3
  };
  if (spline == true) {
    seriesObj.type = 'spline';
  }
  seriesObj.tooltip = {
    valueDecimals: 5
  };
  highchart.addSeries(seriesObj, true);
};

var createFlagSeries = function (highchart) {
  var seriesObj = {};
  seriesObj.id = 'flags';
  seriesObj.type = 'flags';
  seriesObj.data = [];
  seriesObj.onSeries = '10-Day Moving Average';
  seriesObj.shape = 'circlepin';
  seriesObj.width = 20;

  highchart.addSeries(seriesObj);
};

/**
 * Every flag consists of x, title and text. The attribute "x" must be set to
 * the point where the flag should appear. The attribute "title" is the text
 * which is displayed inside the flag on the chart. The attribute "text" contains
 * the text which will appear when the mouse hover above the flag.
 */
var addFlagToSeries = function (highchart, timeStamp, order) {
  var flagObj = {};
  console.log('inside addFlagToSeries:', timeStamp, order);
  flagObj.x = timeStamp;
  flagObj.title = order;
  flagObj.text = 'Make a trade here.';

  highchart.get('flags').addPoint(flagObj);
};

/**
 * Connects and listens on two sockets to initialize and then update a chart.
 *     initializedChartData creates a series and adds historical data to it.
 *     updatedChartData listens for live data and adds it to a targetSeries
 * @param {HighChart} highchart self reference
 */
var loadStrategyTrades = function (highchart) {
  var socket = io.connect('http://localhost:3000');
  console.log('CONNECTION RECEIVED. SERVER RUNNING AT http://localhost:3000');

  highchart.showLoading('');

  // INITALIZE CHART WITH HISTORICAL DATA
  socket.on('initializedChartData', function (chartData) {

    // setTimeout(function () {
    //   highchart.hideLoading();
    // }, 2000);

    console.log('### initializedChartData received...');
    console.log('### creating series...');

    createCandlestickSeries(highchart, 'Closing Price');
    createIndicatorSeries(highchart, '10-Day Moving Average');
    createIndicatorSeries(highchart, '20-Day Moving Average');

    /* Creating candlestick chart lines */
    var candlestickData = chartData.candlestickData;
    var targetSeries = highchart.get("Closing Price");
    addCandlestickDatasetToSeries(targetSeries, candlestickData);

    /* Adding indicators */
    var SMA10 = chartData.indicators.SMA10;
    var targetSMA10 = highchart.get('10-Day Moving Average');
    console.log('### adding SMA10 to chart');
    addIndicatorDatasetToSeries(targetSMA10, SMA10);

    var SMA20 = chartData.indicators.SMA20;
    var targetSMA20 = highchart.get('20-Day Moving Average');
    console.log('### adding SMA20 to chart');
    addIndicatorDatasetToSeries(targetSMA20, SMA20);

    /* Adding order flags */
    createFlagSeries(highchart);
    for (var i = 0; i < chartData.flags.length; i++) {
      console.log('flag added');
      var timeStamp = chartData.flags[i].timestamp * 1000;
      var orderLongShort = chartData.flags[i].longShort;
      addFlagToSeries(highchart, timeStamp, orderLongShort);
    }

    highchart.hideLoading();

  });

  // UPDATE CHART WITH LIVE DATA
  socket.on('updatedChartData', function (chartData) {
    console.log("### CLIENT: Live Data Point Received");
    var date = chartData.time;
    var price = parseFloat(chartData.mostRecentTickerPrice);
    var targetSeries = highchart.get('Closing Price');
    addLiveDataPointToSeries(targetSeries, date, price);
  });
};

/**
 * Connects and listens on two sockets to initialize and then update a chart.
 *     initializedChartData creates a series and adds historical data to it.
 *     updatedChartData listens for live data and adds it to a targetSeries
 * @param {HighChart} highchart self reference
 */
var loadPortfolioPerformance = function (highchart) {
  var socket = io.connect('http://localhost:3000');
  console.log('CONNECTION RECEIVED. SERVER RUNNING AT http://localhost:3000');
  highchart.showLoading('');

  // INITALIZE CHART WITH HISTORICAL DATA
  socket.on('backtest', function (chartData) {

    console.log('### Portfolio: initializedChartData received...');
    console.log('### Portfolio: creating series...');

    /* Creating candlestick chart lines */
    createIndicatorSeries(highchart, 'Backtest', false);
    var bt = chartData.backtest;
    //console.log(chartData);
    console.log('bt', bt);
    var btarget = highchart.get('Backtest');
    addBacktestDatasetToSeries(btarget, bt);

    /* Creating candlestick benchmark chart lines */
    createIndicatorSeries(highchart, 'Benchmark', false);
    var bm = chartData.benchmark;
    var bmtarget = highchart.get('Benchmark');
    addBenchMarkDatasetToSeries(bmtarget, bm);

    /* This line needs to be here for some reason, or else chart won't render properly... */
    createFlagSeries(highchart);

    highchart.hideLoading();
  });
};

$(document).ready(function () {
  $('#hcharts-strategy').highcharts('StockChart', {
    plotOptions: {
      series: {
        dataGrouping: {
          enabled: false,
          groupPixelWidth: 5
        }
      }
    },
    // loading: {
    //     labelStyle: {
    //         fontStyle: 'italic'
    //     }
    // },
    rangeSelector: {
      buttons: [{
        type: 'month',
        count: 1,
        text: '1m'
      }, {
        type: 'month',
        count: 3,
        text: '3m'
      }, {
        type: 'month',
        count: 6,
        text: '6m'
      }, {
        type: 'ytd',
        text: 'YTD'
      }, {
        type: 'year',
        count: 1,
        text: '1y'
      }, {
        type: 'all',
        text: 'All'
      }],
      inputEnabled: false,
      selected: 1
    },

    title: {
      text: 'Moving Avg. Crossover Trades'
    },
    subtitle: {
      text: '+ Indicators (BTC/USD)'
    },
    xAxis: {
      type: 'datetime',
      ordinal: false
    },
    // yAxis:
    //   [{
    //     title: {
    //       text: 'Ticker',
    //     },
    //     opposite: false
    //   }
    // ],
    chart: {
      events: {
        load: function () {
          var self = this;
          loadStrategyTrades(self);
        }
      },
    },
    series: []
  });

  $('#hcharts-portfolio').highcharts('StockChart', {
    plotOptions: {
      series: {
        dataGrouping: {
          enabled: false,
          groupPixelWidth: 15
        }
      }
    },
    rangeSelector: {
      buttons: [{
        type: 'month',
        count: 1,
        text: '1m'
      }, {
        type: 'month',
        count: 3,
        text: '3m'
      }, {
        type: 'month',
        count: 6,
        text: '6m'
      }, {
        type: 'ytd',
        text: 'YTD'
      }, {
        type: 'year',
        count: 1,
        text: '1y'
      }, {
        type: 'all',
        text: 'All'
      }],
      inputEnabled: false,
      selected: 1
    },

    title: {
      text: 'Portfolio Performance'
    },
    subtitle: {
      text: 'Moving Average Crossover Strategy'
    },
    xAxis: {
      type: 'datetime',
      ordinal: false
    },
    // yAxis:
    //   [{
    //     title: {
    //       text: 'Value',
    //     },
    //     opposite: false
    //   }
    // ],
    chart: {
      events: {
        load: function () {
          var self = this;
          loadPortfolioPerformance(self);
        }
      },
    },
    series: []
  });
});
<|endoftext|>


<commit_before>// Timestamp, das muss man eigentlich auf der Serverseite machen,
// damit mans nicht faken kann?? Noch anschauen.
get_timestamp = function (){
	var now = new Date();
	return now.getTime();
}

hasRole = function(members, role) {
	var has = false;
	members.forEach(function(member) {
		if (member.roles.indexOf(role) !== -1) {
			has = true;
			return true;
		}
	})
	return has;
}

havingRole = function(members, role) {
	return _.reduce(members, function(ids, member) {
		if (member.roles.indexOf(role) !== -1) ids.push(member.user)
			return ids;
	}, [])
}

getMemeber = function(members, user) {
	var member = false;
	members.forEach(function(member_candidate) {
		if (member.user == user) {
			member = member_candidate
			return true; // break
		}
	})
	return member;
}

hasRoleUser = function(members, role, user) {
	var has = false;
	members.forEach(function(member) {
		if (member.user == user) {
			has = member.roles.indexOf(role) !== -1
			return true; // break
		}
	})
	return has;
}

/*************** HandleBars Helpers ***********************/

Handlebars.registerHelper("log", function(context) {
	if (window.console) console.log(context)
});

Handlebars.registerHelper("title", function() {
	var les = Array.prototype.slice.call(arguments, 0, -1)
	document.title = les.join("");
});

Handlebars.registerHelper('username', function (userid){
	console.log(userid)
	var user= Meteor.users.findOne({_id:userid});
	if(user){
		if(user.username){
			return user.username;
		}else{
			return "userid: "+user._id; // solange .username noch nix ist, haben wir nur die _id...
		}
	}else{
		if (userid.substr(0, 5)  == 'Anon_'){
			return "Anonymous☔";
		}else{
			return "No_User";
		}

	}
})

Handlebars.registerHelper('dateformat', function(date) {
    // We'll need a date formatter at some point
    //if (date) return date.toDateString();

    if (date) return date.getDate()+"."+(date.getMonth()+1)+"."+date.getFullYear();
});

Handlebars.registerHelper('dateformat_withday', function(date) {
    // We'll need a date formatter at some point
    //if (date) return date.toDateString();
    horrible_date_array=["Mo","Tue","Wed","Thu","Fr","Sat","So"]; //FIXME

    if (date) return horrible_date_array[date.getDay()]+". "+date.getDate()+"."+(date.getMonth()+1)+"."+date.getFullYear();
});

Handlebars.registerHelper('dateformat_mini', function(date) {
    // We'll need a date formatter at some point
    //if (date) return date.toDateString();
    if (date) return date.getDate()+"."+(date.getMonth()+1)+".";
});

Handlebars.registerHelper('timeformat', function(date) {
    // We'll need a time formatter at some point
    //if (date) return date.toTimeString();

    if (date) return ("0"+date.getHours()).slice(-2)+":"+("0"+date.getMinutes()).slice(-2);
});

Handlebars.registerHelper('isNull', function(val) {
    return val === null
});

Handlebars.registerHelper('courseURL', function(_id) {
    var course=Courses.findOne(_id);
    var name = getSlug(course.name);
	//var name = course.name.replace(/[^\w\s]/gi, '-').replace(/[_\s]/g, '_')
	var _id = _id
	return '/course/' + _id + '/' + name;
});

//Html title attribute of participant-state-sybol in courselist
Handlebars.registerHelper('isYes', function(val) {
 	return val === 'yes'
});
Handlebars.registerHelper('isOntheway', function(val) {
 	return val === 'ontheway'
});

Handlebars.registerHelper('isAdmin', function() {
    var user = Meteor.user()
    error.log(user.isAdmin)
    return user && user.isAdmin
});

<commit_msg>minor change<commit_after>// Timestamp, das muss man eigentlich auf der Serverseite machen,
// damit mans nicht faken kann?? Noch anschauen.
get_timestamp = function (){
	var now = new Date();
	return now.getTime();
}

hasRole = function(members, role) {
	var has = false;
	members.forEach(function(member) {
		if (member.roles.indexOf(role) !== -1) {
			has = true;
			return true;
		}
	})
	return has;
}

havingRole = function(members, role) {
	return _.reduce(members, function(ids, member) {
		if (member.roles.indexOf(role) !== -1) ids.push(member.user)
			return ids;
	}, [])
}

getMemeber = function(members, user) {
	var member = false;
	members.forEach(function(member_candidate) {
		if (member.user == user) {
			member = member_candidate
			return true; // break
		}
	})
	return member;
}

hasRoleUser = function(members, role, user) {
	var has = false;
	members.forEach(function(member) {
		if (member.user == user) {
			has = member.roles.indexOf(role) !== -1
			return true; // break
		}
	})
	return has;
}

/*************** HandleBars Helpers ***********************/

Handlebars.registerHelper("log", function(context) {
	if (window.console) console.log(context)
});

Handlebars.registerHelper("title", function() {
	var les = Array.prototype.slice.call(arguments, 0, -1)
	document.title = les.join("");
});

Handlebars.registerHelper('username', function (userid){
	var user= Meteor.users.findOne({_id:userid});
	if(user){
		if(user.username){
			return user.username;
		}else{
			return "userid: "+user._id; // solange .username noch nix ist, haben wir nur die _id...
		}
	}else{
		if (userid.substr(0, 5)  == 'Anon_'){
			return "Anonymous☔";
		}else{
			return "No_User";
		}

	}
})

Handlebars.registerHelper('dateformat', function(date) {
    // We'll need a date formatter at some point
    //if (date) return date.toDateString();

    if (date) return date.getDate()+"."+(date.getMonth()+1)+"."+date.getFullYear();
});

Handlebars.registerHelper('dateformat_withday', function(date) {
    // We'll need a date formatter at some point
    //if (date) return date.toDateString();
    horrible_date_array=["Mo","Tue","Wed","Thu","Fr","Sat","So"]; //FIXME

    if (date) return horrible_date_array[date.getDay()]+". "+date.getDate()+"."+(date.getMonth()+1)+"."+date.getFullYear();
});

Handlebars.registerHelper('dateformat_mini', function(date) {
    // We'll need a date formatter at some point
    //if (date) return date.toDateString();
    if (date) return date.getDate()+"."+(date.getMonth()+1)+".";
});

Handlebars.registerHelper('timeformat', function(date) {
    // We'll need a time formatter at some point
    //if (date) return date.toTimeString();

    if (date) return ("0"+date.getHours()).slice(-2)+":"+("0"+date.getMinutes()).slice(-2);
});

Handlebars.registerHelper('isNull', function(val) {
    return val === null
});

Handlebars.registerHelper('courseURL', function(_id) {
    var course=Courses.findOne(_id);
    var name = getSlug(course.name);
	//var name = course.name.replace(/[^\w\s]/gi, '-').replace(/[_\s]/g, '_')
	var _id = _id
	return '/course/' + _id + '/' + name;
});

//Html title attribute of participant-state-sybol in courselist
Handlebars.registerHelper('isYes', function(val) {
 	return val === 'yes'
});
Handlebars.registerHelper('isOntheway', function(val) {
 	return val === 'ontheway'
});

Handlebars.registerHelper('isAdmin', function() {
    var user = Meteor.user()
    error.log(user.isAdmin)
    return user && user.isAdmin
});

<|endoftext|>


<commit_before>/**
 *  @file dialog
 *
 *  dialog adapter for jQuery UI
 *  As its own instance of the d4p.ajaxLoader
 *
 *  Copyright 2012 DITA For Publishers
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */ (function (d4p) {

    // Remove links on dialogs
    d4p.ajaxLoader.prototype.removeLinks = function () {
        var uri = d4p.hash.current;
        //console.log(this.content.html());
        this.content.find("a").each(function(index) {
      		$(this).replaceWith(this.childNodes);
    	});
    	//console.log(this.content.html());
    };

    d4p.ui.dialog = {

        ids: 0,

        done: {},

        init: function (obj) {

        	var uri = '', id = '';

            if (obj[0].tagName.toUpperCase() === "DFN") {
                obj = obj.parent();
            }

            uri = obj.attr('href');
            uri = uri.substring(0, 1) === '#' ? uri.substring(1) : uri;

            id = this.getId();

            // keep track of every external dialog loaded
            if (this.done[uri] == undefined) {
                this.done[uri] = {
                    'id': id,
                    'uri': uri,
                    'done': false
                };
            }

            if (this.checkDialog(obj, uri)) {
                this.dialog(obj, uri);
            }

        },

        getId: function () {
            this.ids++;
            return this.ids;
        },

        checkDialog: function (obj, uri) {

            // avoid processing url twice
            if (this.done[uri].done == true) {

                if (uri != "") {
                    obj.attr('href', "#");

                    // add click handler
                    obj.click(function (event) {
                     	event.preventDefault();
                        $("#dialog-" + d4p.ui.dialog.done[uri].id).dialog('open');
                    });
                }
                return false;
            } else {
                return true;
            }
        },

        dialog: function (obj, uri) {
            // add dialog
            var ajax = new d4p.ajaxLoader(),
            id = this.done[uri].id,
			dialog = $("<div />").attr("id", "dialog-" + id);

			ajax.name = 'dialog';
			ajax.collectionSet(uri, uri, id, id, "");

            ajax.bind('ready', 'rewriteAttrSrc');
            ajax.bind('postFilter', 'removeLinks');

            $(d4p.ajax.loaderParentElement).append(dialog);

            ajax.setOutputSelector("#dialog-" + id);
            ajax.load(uri);

            dialog.dialog({
                autoOpen: false,
                minWidth: d4p.ui.dialogMinWidth
            });

            dialog.dialog('close');

            // remove href
            obj.attr('href', "#");

            // add click handler
            obj.click(function (event) {
            	event.preventDefault();
                $("#dialog-" + id).dialog('open');
            });

            this.done[uri].done = true;
        }
    };

})(d4p);<commit_msg>fix dialofg href according to the new ajax loader function<commit_after>/**
 *  @file dialog
 *
 *  dialog adapter for jQuery UI
 *  As its own instance of the d4p.ajaxLoader
 *
 *  Copyright 2012 DITA For Publishers
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
(function (d4p) {

    // Remove links on dialogs
    d4p.ajaxLoader.prototype.removeLinks = function () {
        var uri = d4p.hash.current;
        this.content.find("a").each(function(index) {
      		$(this).replaceWith(this.childNodes);
    	});
    };

    d4p.ui.dialog = {

        ids: 0,

        done: {},

        init: function (obj) {

        	var uri = '', id = '', href='';

            if (obj[0].tagName.toUpperCase() === "DFN") {
                obj = obj.parent();
            }

			href = obj.attr('href');
			href = href.substring(0,1) == '#' ? href.substring(1) : href;
            uri = d4p.ajax.collection[href].uri;

            id = this.getId();

            // keep track of every external dialog loaded
            if (this.done[uri] == undefined) {
                this.done[uri] = {
                    'id': id,
                    'uri': uri,
                    'done': false
                };
            }

            if (this.checkDialog(obj, uri)) {
                this.dialog(obj, uri);
            }

        },

        getId: function () {
            this.ids++;
            return this.ids;
        },

        checkDialog: function (obj, uri) {

            // avoid processing url twice
            if (this.done[uri].done == true) {

                if (uri != "") {
                    obj.attr('href', "#");

                    // add click handler
                    obj.click(function (event) {
                     	event.preventDefault();
                        $("#dialog-" + d4p.ui.dialog.done[uri].id).dialog('open');
                    });
                }
                return false;
            } else {
                return true;
            }
        },

        dialog: function (obj, uri) {
            // add dialog
            var ajax = new d4p.ajaxLoader(),
            id = this.done[uri].id,
			dialog = $("<div />").attr("id", "dialog-" + id);

			ajax.name = 'dialog';
			ajax.collectionSet(uri, uri, id, id, "");

            ajax.bind('ready', 'rewriteAttrSrc');
            ajax.bind('postFilter', 'removeLinks');

            $(d4p.ajax.loaderParentElement).append(dialog);

            ajax.setOutputSelector("#dialog-" + id);
            ajax.load(uri);

            dialog.dialog({
                autoOpen: false,
                minWidth: d4p.ui.dialogMinWidth
            });

            dialog.dialog('close');

            // remove href
            obj.attr('href', "#");

            // add click handler
            obj.click(function (event) {
            	event.preventDefault();
                $("#dialog-" + id).dialog('open');
            });

            this.done[uri].done = true;
        }
    };

})(d4p);<|endoftext|>


<commit_before>// This is a content script, it runs on starbase_trade.php and planet_trade.php.

// From other files:
var Overlay;

setup();

// End of script execution.

function setup() {
	var ukey, form, container, img, button;

	// Insert a BK button.  That's all our UI.

	form = document.forms.planet_trade || document.forms.starbase_trade;

	container = document.createElement( 'div' );
	container.id = 'bookkeeper-ui';
	container.className = 'bookkeeper-starbasetrade';

	img = document.createElement( 'img' );
	img.title = 'Pardus Bookkeeper';
	img.src = chrome.extension.getURL( 'icons/16.png' );
	container.appendChild( img );

	button = document.createElement( 'button' );
	button.id = 'bookkeeper-overview-toggle';
	button.textContent = 'OPEN';
	container.appendChild( button );

	// Button injection take 3.  There's just no good spot to paste in, but
	// I really don't want it near the centre of the page where it can be
	// covered.  Add as previous sibling of the form.
	form.parentElement.style.position = 'relative';
	form.parentElement.insertBefore( container, form );

	ukey = document.location.hostname[0].toUpperCase();
	new Overlay(
		ukey, document, button,
		{ overlayClassName: 'bookkeeper-starbasetrade',
		  mode: 'compact',
		  storageKey: 'SB' } );
}
<commit_msg>New auto buttons.<commit_after>// This is a content script, it runs on starbase_trade.php and planet_trade.php.

// From other files:
var Overlay;

setup();

// End of script execution.

function setup() {
	var ukey, form, container, img, button;

	// Insert a BK button.  That's all our UI.

	form = document.forms.planet_trade || document.forms.starbase_trade;

	container = document.createElement( 'div' );
	container.id = 'bookkeeper-ui';
	container.className = 'bookkeeper-starbasetrade';

	img = document.createElement( 'img' );
	img.title = 'Pardus Bookkeeper';
	img.src = chrome.extension.getURL( 'icons/16.png' );
	container.appendChild( img );

	button = document.createElement( 'button' );
	button.id = 'bookkeeper-overview-toggle';
	button.textContent = 'OPEN';
	container.appendChild( button );

	// Button injection take 3.  There's just no good spot to paste in, but
	// I really don't want it near the centre of the page where it can be
	// covered.  Add as previous sibling of the form.
	form.parentElement.style.position = 'relative';
	form.parentElement.insertBefore( container, form );

	ukey = document.location.hostname[0].toUpperCase();
	new Overlay(
		ukey, document, button,
		{ overlayClassName: 'bookkeeper-starbasetrade',
		  mode: 'compact',
		  storageKey: 'SB' } );

	function makeButton( id ) {
		button = document.createElement( 'button' );
		button.type = 'button';
		button.id = id;
		button.style = "width: 175px; height: 35px; margin-left: 3px; margin-right: 3px;";
		return button
	}

	if (document.forms.planet_trade) {
		var middleNode = document.getElementById('quickButtonsTbl').parentNode;
		middleNode.appendChild( document.createElement( 'br' ));
		middleNode.appendChild( document.createElement( 'br' ));

		button = makeButton ( 'bookkeeper-transfer-food' )
		button.textContent = '<- Food | Energy ->';
		middleNode.appendChild ( button ) ;
		button.addEventListener('click', function() {
			if ( document.getElementById('shiprow2').getElementsByTagName('a')[1] ) {
				document.getElementById('shiprow2').getElementsByTagName('a')[1].click();
			}
			document.getElementById('baserow1').getElementsByTagName('a')[1].click();
			document.forms.planet_trade.submit();
		});

		middleNode.appendChild( document.createElement( 'br' ));
		middleNode.appendChild( document.createElement( 'br' ));
		button = makeButton ( 'bookkeeper-transfer-water' )
		button.textContent = '<- Water | Energy ->';
		middleNode.appendChild ( button ) ;
		button.addEventListener('click', function() {
			if ( document.getElementById('shiprow2').getElementsByTagName('a')[1] ) {
				document.getElementById('shiprow2').getElementsByTagName('a')[1].click();
			}
			document.getElementById('baserow3').getElementsByTagName('a')[1].click();
			document.forms.planet_trade.submit();
		});
		middleNode.appendChild( document.createElement( 'br' ));
		middleNode.appendChild( document.createElement( 'br' ));

		button = makeButton ( 'bookkeeper-transfer-FWE' )
		button.textContent = '<-SB FW | Energy ->';
		middleNode.appendChild ( button ) ;
		button.addEventListener('click', function() {
			var ship_cargo = parseInt(document.getElementById('shiprow32').nextElementSibling.nextElementSibling.lastElementChild.textContent.split(/t/g)[0]);

			if (document.getElementById('shiprow2').getElementsByTagName('a')[1] ) {
				document.getElementById('shiprow2').getElementsByTagName('a')[1].click();
				ship_cargo += parseInt( document.getElementById('sell_2').value );
			}
			var buyFood = Math.floor( ship_cargo / 5 * 3);
			var buyWater = ship_cargo - buyFood;

			document.getElementById('buy_1').value = buyFood;
			document.getElementById('buy_3').value = buyWater;
			document.forms.planet_trade.submit();
		});
	}
}
<|endoftext|>