<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import DocumentTitle from 'react-document-title';
import { seconds } from 'metrick/duration';

import AgentStateIcon from './state-icon';
import BuildState from '../icons/BuildState';
import BuildStates from '../../constants/BuildStates';
import Button from '../shared/Button';
import FlashesStore from '../../stores/FlashesStore';
import FriendlyTime from '../shared/FriendlyTime';
import JobLink from '../shared/JobLink';
import PageWithContainer from '../shared/PageWithContainer';
import Panel from '../shared/Panel';
import permissions from '../../lib/permissions';
import { getLabelForConnectionState } from './shared';

import AgentStopMutation from '../../mutations/AgentStop';

class AgentShow extends React.Component {
  static propTypes = {
    agent: PropTypes.shape({
      id: PropTypes.string,
      name: PropTypes.string,
      connectionState: PropTypes.string,
      job: PropTypes.object,
      permissions: PropTypes.shape({
        agentStop: PropTypes.shape({
          allowed: PropTypes.bool
        })
      }),
      organization: PropTypes.shape({
        name: PropTypes.string,
        slug: PropTypes.string
      })
    }),
    relay: PropTypes.object.isRequired
  };

  state = {
    stopping: false
  };

  componentDidMount() {
    // Only bother setting up the delayed load and refresher if we've got an
    // actual agent to play with.
    if (this.props.agent && this.props.agent.id) {
      // This will cause a full refresh of the data every 3 seconds. This seems
      // very low, but chances are people aren't really looking at this page
      // for long periods of time.
      this.startTimeout();
    }
  }

  componentWillUnmount() {
    clearTimeout(this._agentRefreshTimeout);
  }

  startTimeout = () => {
    this._agentRefreshTimeout = setTimeout(
      this.fetchUpdatedData,
      3::seconds
    );
  };

  fetchUpdatedData = () => {
    this.props.relay.forceFetch(
      true,
      (readyState) => {
        if (readyState.done) {
          this.startTimeout();
        }
      }
    );
  };

  getBuildStateForJob(job) {
    // Naïvely transliterate Job state to Build state
    switch (job.state) {
      case "FINISHED":
        return (
          job.passed
            ? BuildStates.PASSED
            : BuildStates.FAILED
        );
      case "PENDING":
      case "WAITING":
      case "UNBLOCKED":
      case "LIMITED":
      case "ASSIGNED":
      case "ACCEPTED":
        return BuildStates.SCHEDULED;
      case "TIMING_OUT":
      case "TIMED_OUT":
      case "WAITING_FAILED":
      case "BLOCKED_FAILED":
      case "UNBLOCKED_FAILED":
      case "BROKEN":
        return BuildStates.FAILED;
      default:
        return job.state;
    }
  }

  renderJob(job) {
    if (!job) {
      return 'A job owned by another team';
    }

    return (

        <BuildState.XSmall
          state={this.getBuildStateForJob(job)}
          style={{  marginLeft: '-1.4em', marginRight: '.4em' }}
        />
        <JobLink job={job} />

    );
  }

  renderExtraItem(title, content) {
    return (

        {title}
        {content}

    );
  }

  renderExtras(agent) {
    const extras = [];

    let extraStoppingInfo;
    if (agent.connectionState === "stopping") {
      extraStoppingInfo = (

          If the agent doesn’t respond to the stop signal within a few minutes, Buildkite will forcefully disconnect the agent and remove it from your pool of agents.

      );
    }

    extras.push(this.renderExtraItem('State', (

        <AgentStateIcon agent={agent} style={{ marginRight: '.4em' }} />
        {getLabelForConnectionState(agent.connectionState)}
        {extraStoppingInfo}

    )));

    if (agent.version) {
      extras.push(this.renderExtraItem('Version', agent.version));
    }

    if (agent.hostname) {
      extras.push(this.renderExtraItem('Hostname', agent.hostname));
    }

    if (agent.pid) {
      extras.push(this.renderExtraItem('PID', agent.pid));
    }

    if (agent.ipAddress) {
      extras.push(this.renderExtraItem('IP Address', agent.ipAddress));
    }

    if (agent.userAgent) {
      extras.push(this.renderExtraItem('User Agent', agent.userAgent));
    }

    if (agent.operatingSystem) {
      extras.push(this.renderExtraItem('OS', agent.operatingSystem.name));
    }

    if (agent.priority) {
      extras.push(this.renderExtraItem('Priority', agent.priority));
    }

    if (agent.isRunningJob) {
      extras.push(this.renderExtraItem(
        'Running',
        // if we have access to the job, show a link
        this.renderJob(agent.job)
      ));
    }

    if (agent.jobs.edges.length) {
      extras.push(this.renderExtraItem(
        'Recent Jobs',

          {
            agent.jobs.edges.map(({ node: job }) => (

                {this.renderJob(job)}

            ))
          }

      ));
    }

    if (agent.connectedAt) {
      extras.push(this.renderExtraItem(
        'Connected',

          <FriendlyTime value={agent.connectedAt} />
          {agent.pingedAt && agent.connectionState === 'connected' &&
             (last check-in was <FriendlyTime value={agent.pingedAt} capitalized={false} />)
          }

      ));
    }

    if (agent.connectionState === 'disconnected') {
      extras.push(this.renderExtraItem(
        'Disconnected',
        <FriendlyTime value={agent.disconnectedAt} />
      ));
    } else if (agent.connectionState === 'lost') {
      extras.push(this.renderExtraItem(
        'Lost',
        <FriendlyTime value={agent.lostAt} />
      ));
    } else if (agent.connectionState === 'stopped' || agent.connectionState === 'stopping') {
      extras.push(this.renderExtraItem(
        'Stopped',

          <FriendlyTime value={agent.stoppedAt} /> by {agent.stoppedBy.name}

      ));

      if (agent.disconnectedAt) {
        extras.push(this.renderExtraItem(
          'Disconnected',
          <FriendlyTime value={agent.disconnectedAt} />
        ));
      } else {
        extras.push(this.renderExtraItem(
          'Disconnected',
          '-'
        ));
      }
    }

    let metaDataContent = 'None';

    if (agent.metaData && agent.metaData.length) {
      metaDataContent = agent.metaData.sort().map((metaData) => {
        return (

{metaData}

        );
      });
    }
    extras.push(this.renderExtraItem(
      'Meta-data',

{metaDataContent}

    ));

    return extras;
  }

  handleStopButtonClick = (evt) => {
    evt.preventDefault();

    this.setState({ stopping: true });

    // We add a delay in case it executes so quickly that the user can't
    // understand what just flashed past their face.
    setTimeout(() => {
      const mutation = new AgentStopMutation({
        agent: this.props.agent,
        graceful: false
      });

      Relay.Store.commitUpdate(mutation, {
        onSuccess: this.handleMutationSuccess,
        onFailure: this.handleMutationError
      });
    }, 1250);
  };

  handleMutationSuccess = () => {
    this.setState({ stopping: false });
  };

  handleMutationError = (transaction) => {
    FlashesStore.flash(FlashesStore.ERROR, transaction.getError());

    this.setState({ stopping: false });
  };

  render() {
    // If we don't have an agent object, or we do but it doesn't have an id
    // (perhaps Relay gave us an object but it's empty) then we can safely
    // assume that it's a 404.
    if (!this.props.agent || !this.props.agent.id) {
      return (
        <DocumentTitle title={`Agents / No Agent Found`}>
          <PageWithContainer>

No agent could be found!

          </PageWithContainer>
        </DocumentTitle>
      );
    }

    const agent = this.props.agent;

    return (
      <DocumentTitle title={`Agents / ${this.props.agent.name} · ${this.props.agent.organization.name}`}>
        <PageWithContainer>
          <Panel className="sm-col-9 lg-col-6 mx-auto">
            <Panel.Header>{this.props.agent.name}</Panel.Header>

            <Panel.Row key="info">

                  {this.renderExtras(agent)}

                You can use the agent’s meta-data to target the agent in your pipeline’s step configuration, or to set the agent’s queue.
                See the Agent Meta-data Documentation and Agent Queues Documentation for more details.

            </Panel.Row>

            {this.renderStopRow()}
          </Panel>
        </PageWithContainer>
      </DocumentTitle>
    );
  }

  renderStopRow() {
    if (this.props.agent.connectionState !== 'connected') {
      return null;
    }

    return permissions(this.props.agent.permissions).collect(
      {
        allowed: "agentStop",
        render: (idx) => (
          <Panel.Row key={idx}>
            <Button
              theme="default"
              outline={true}
              loading={this.state.stopping ? "Stopping…" : false}
              onClick={this.handleStopButtonClick}
              className="mb1"
            >
              Stop Agent
            </Button>
            {this.renderStopWarningMessage()}
          </Panel.Row>
        )
      }
    );
  }

  renderStopWarningMessage() {
    if (this.props.agent.job) {
      return (

          The running job will be canceled.

      );
    }
  }
}

export default Relay.createContainer(AgentShow, {
  fragments: {
    agent: () => Relay.QL`
      fragment on Agent {
        ${AgentStateIcon.getFragment('agent')}
        ${AgentStopMutation.getFragment('agent')}
        id
        name
        organization {
          name
          slug
        }
        connectedAt
        connectionState
        disconnectedAt
        hostname
        id
        ipAddress
        job {
          ...on JobTypeCommand {
            state
            passed
          }
          ${JobLink.getFragment('job')}
        }
        jobs(first: 10) {
          edges {
            node {
              ...on JobTypeCommand {
                uuid
                state
                passed
              }
              ${JobLink.getFragment('job')}
            }
          }
        }
        isRunningJob
        lostAt
        metaData
        operatingSystem {
          name
        }
        priority
        permissions {
          agentStop {
            allowed
            code
            message
          }
        }
        pid
        pingedAt
        stoppedAt
        stoppedBy {
          name
        }
        userAgent
        uuid
        version
      }
    `
  }
});
<commit_msg>Responsive layout for agent show table<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import styled from 'styled-components';
import DocumentTitle from 'react-document-title';
import { seconds } from 'metrick/duration';

import AgentStateIcon from './state-icon';
import BuildState from '../icons/BuildState';
import BuildStates from '../../constants/BuildStates';
import Button from '../shared/Button';
import FlashesStore from '../../stores/FlashesStore';
import FriendlyTime from '../shared/FriendlyTime';
import JobLink from '../shared/JobLink';
import PageWithContainer from '../shared/PageWithContainer';
import Panel from '../shared/Panel';
import permissions from '../../lib/permissions';
import { getLabelForConnectionState } from './shared';

import AgentStopMutation from '../../mutations/AgentStop';

const ExtrasTable = styled.table`
  @media (max-width: 768px) {
    &, tbody {
      display: block;
    }

    tr {
      display: flex;
    }

    th {
      padding-bottom: 0;
    }
  }
`;

class AgentShow extends React.Component {
  static propTypes = {
    agent: PropTypes.shape({
      id: PropTypes.string,
      name: PropTypes.string,
      connectionState: PropTypes.string,
      job: PropTypes.object,
      permissions: PropTypes.shape({
        agentStop: PropTypes.shape({
          allowed: PropTypes.bool
        })
      }),
      organization: PropTypes.shape({
        name: PropTypes.string,
        slug: PropTypes.string
      })
    }),
    relay: PropTypes.object.isRequired
  };

  state = {
    stopping: false
  };

  componentDidMount() {
    // Only bother setting up the delayed load and refresher if we've got an
    // actual agent to play with.
    if (this.props.agent && this.props.agent.id) {
      // This will cause a full refresh of the data every 3 seconds. This seems
      // very low, but chances are people aren't really looking at this page
      // for long periods of time.
      this.startTimeout();
    }
  }

  componentWillUnmount() {
    clearTimeout(this._agentRefreshTimeout);
  }

  startTimeout = () => {
    this._agentRefreshTimeout = setTimeout(
      this.fetchUpdatedData,
      3::seconds
    );
  };

  fetchUpdatedData = () => {
    this.props.relay.forceFetch(
      true,
      (readyState) => {
        if (readyState.done) {
          this.startTimeout();
        }
      }
    );
  };

  getBuildStateForJob(job) {
    // Naïvely transliterate Job state to Build state
    switch (job.state) {
      case "FINISHED":
        return (
          job.passed
            ? BuildStates.PASSED
            : BuildStates.FAILED
        );
      case "PENDING":
      case "WAITING":
      case "UNBLOCKED":
      case "LIMITED":
      case "ASSIGNED":
      case "ACCEPTED":
        return BuildStates.SCHEDULED;
      case "TIMING_OUT":
      case "TIMED_OUT":
      case "WAITING_FAILED":
      case "BLOCKED_FAILED":
      case "UNBLOCKED_FAILED":
      case "BROKEN":
        return BuildStates.FAILED;
      default:
        return job.state;
    }
  }

  renderJob(job) {
    if (!job) {
      return 'A job owned by another team';
    }

    return (

        <BuildState.XSmall
          state={this.getBuildStateForJob(job)}
          style={{  marginLeft: '-1.4em', marginRight: '.4em' }}
        />
        <JobLink job={job} />

    );
  }

  renderExtraItem(title, content) {
    return (

        {title}
        {content}

    );
  }

  renderExtras(agent) {
    const extras = [];

    let extraStoppingInfo;
    if (agent.connectionState === "stopping") {
      extraStoppingInfo = (

          If the agent doesn’t respond to the stop signal within a few minutes, Buildkite will forcefully disconnect the agent and remove it from your pool of agents.

      );
    }

    extras.push(this.renderExtraItem('State', (

        <AgentStateIcon agent={agent} style={{ marginRight: '.4em' }} />
        {getLabelForConnectionState(agent.connectionState)}
        {extraStoppingInfo}

    )));

    if (agent.version) {
      extras.push(this.renderExtraItem('Version', agent.version));
    }

    if (agent.hostname) {
      extras.push(this.renderExtraItem('Hostname', agent.hostname));
    }

    if (agent.pid) {
      extras.push(this.renderExtraItem('PID', agent.pid));
    }

    if (agent.ipAddress) {
      extras.push(this.renderExtraItem('IP Address', agent.ipAddress));
    }

    if (agent.userAgent) {
      extras.push(this.renderExtraItem('User Agent', agent.userAgent));
    }

    if (agent.operatingSystem) {
      extras.push(this.renderExtraItem('OS', agent.operatingSystem.name));
    }

    if (agent.priority) {
      extras.push(this.renderExtraItem('Priority', agent.priority));
    }

    if (agent.isRunningJob) {
      extras.push(this.renderExtraItem(
        'Running',
        // if we have access to the job, show a link
        this.renderJob(agent.job)
      ));
    }

    if (agent.jobs.edges.length) {
      extras.push(this.renderExtraItem(
        'Recent Jobs',

          {
            agent.jobs.edges.map(({ node: job }) => (

                {this.renderJob(job)}

            ))
          }

      ));
    }

    if (agent.connectedAt) {
      extras.push(this.renderExtraItem(
        'Connected',

          <FriendlyTime value={agent.connectedAt} />
          {agent.pingedAt && agent.connectionState === 'connected' &&
             (last check-in was <FriendlyTime value={agent.pingedAt} capitalized={false} />)
          }

      ));
    }

    if (agent.connectionState === 'disconnected') {
      extras.push(this.renderExtraItem(
        'Disconnected',
        <FriendlyTime value={agent.disconnectedAt} />
      ));
    } else if (agent.connectionState === 'lost') {
      extras.push(this.renderExtraItem(
        'Lost',
        <FriendlyTime value={agent.lostAt} />
      ));
    } else if (agent.connectionState === 'stopped' || agent.connectionState === 'stopping') {
      extras.push(this.renderExtraItem(
        'Stopped',

          <FriendlyTime value={agent.stoppedAt} /> by {agent.stoppedBy.name}

      ));

      if (agent.disconnectedAt) {
        extras.push(this.renderExtraItem(
          'Disconnected',
          <FriendlyTime value={agent.disconnectedAt} />
        ));
      } else {
        extras.push(this.renderExtraItem(
          'Disconnected',
          '-'
        ));
      }
    }

    let metaDataContent = 'None';

    if (agent.metaData && agent.metaData.length) {
      metaDataContent = agent.metaData.sort().map((metaData) => {
        return (

{metaData}

        );
      });
    }
    extras.push(this.renderExtraItem(
      'Meta-data',

{metaDataContent}

    ));

    return (
      <ExtrasTable className="col-12">

          {extras}

      </ExtrasTable>
    );
  }

  handleStopButtonClick = (evt) => {
    evt.preventDefault();

    this.setState({ stopping: true });

    // We add a delay in case it executes so quickly that the user can't
    // understand what just flashed past their face.
    setTimeout(() => {
      const mutation = new AgentStopMutation({
        agent: this.props.agent,
        graceful: false
      });

      Relay.Store.commitUpdate(mutation, {
        onSuccess: this.handleMutationSuccess,
        onFailure: this.handleMutationError
      });
    }, 1250);
  };

  handleMutationSuccess = () => {
    this.setState({ stopping: false });
  };

  handleMutationError = (transaction) => {
    FlashesStore.flash(FlashesStore.ERROR, transaction.getError());

    this.setState({ stopping: false });
  };

  render() {
    // If we don't have an agent object, or we do but it doesn't have an id
    // (perhaps Relay gave us an object but it's empty) then we can safely
    // assume that it's a 404.
    if (!this.props.agent || !this.props.agent.id) {
      return (
        <DocumentTitle title={`Agents / No Agent Found`}>
          <PageWithContainer>

No agent could be found!

          </PageWithContainer>
        </DocumentTitle>
      );
    }

    const agent = this.props.agent;

    return (
      <DocumentTitle title={`Agents / ${this.props.agent.name} · ${this.props.agent.organization.name}`}>
        <PageWithContainer>
          <Panel className="sm-col-9 lg-col-6 mx-auto">
            <Panel.Header>{this.props.agent.name}</Panel.Header>

            <Panel.Row key="info">
              {this.renderExtras(agent)}

                You can use the agent’s meta-data to target the agent in your pipeline’s step configuration, or to set the agent’s queue.
                See the Agent Meta-data Documentation and Agent Queues Documentation for more details.

            </Panel.Row>

            {this.renderStopRow()}
          </Panel>
        </PageWithContainer>
      </DocumentTitle>
    );
  }

  renderStopRow() {
    if (this.props.agent.connectionState !== 'connected') {
      return null;
    }

    return permissions(this.props.agent.permissions).collect(
      {
        allowed: "agentStop",
        render: (idx) => (
          <Panel.Row key={idx}>
            <Button
              theme="default"
              outline={true}
              loading={this.state.stopping ? "Stopping…" : false}
              onClick={this.handleStopButtonClick}
              className="mb1"
            >
              Stop Agent
            </Button>
            {this.renderStopWarningMessage()}
          </Panel.Row>
        )
      }
    );
  }

  renderStopWarningMessage() {
    if (this.props.agent.job) {
      return (

          The running job will be canceled.

      );
    }
  }
}

export default Relay.createContainer(AgentShow, {
  fragments: {
    agent: () => Relay.QL`
      fragment on Agent {
        ${AgentStateIcon.getFragment('agent')}
        ${AgentStopMutation.getFragment('agent')}
        id
        name
        organization {
          name
          slug
        }
        connectedAt
        connectionState
        disconnectedAt
        hostname
        id
        ipAddress
        job {
          ...on JobTypeCommand {
            state
            passed
          }
          ${JobLink.getFragment('job')}
        }
        jobs(first: 10) {
          edges {
            node {
              ...on JobTypeCommand {
                uuid
                state
                passed
              }
              ${JobLink.getFragment('job')}
            }
          }
        }
        isRunningJob
        lostAt
        metaData
        operatingSystem {
          name
        }
        priority
        permissions {
          agentStop {
            allowed
            code
            message
          }
        }
        pid
        pingedAt
        stoppedAt
        stoppedBy {
          name
        }
        userAgent
        uuid
        version
      }
    `
  }
});
<|endoftext|>


<commit_before>'use strict';

var React = require('react-native');
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');

var {NativeModules} = React;

module.exports = {
  getOrientation: function(callback) {
    NativeModules.OrientationListener.getOrientation(callback);
  },
  addListener: function(callback) {
    return RCTDeviceEventEmitter.addListener(
      'orientationDidChange', callback
    );
  },
  removeListener: function(listener) {
    RCTDeviceEventEmitter.removeListener(
      'orientationDidChange', listener
    );
  }
}<commit_msg>Updated path to RCTDeviceEventEmitter<commit_after>'use strict';

var React = require('react-native');
var RCTDeviceEventEmitter = require('react-native/Libraries/Device/RCTDeviceEventEmitter');

var {NativeModules} = React;

module.exports = {
  getOrientation: function(callback) {
    NativeModules.OrientationListener.getOrientation(callback);
  },
  addListener: function(callback) {
    return RCTDeviceEventEmitter.addListener(
      'orientationDidChange', callback
    );
  },
  removeListener: function(listener) {
    RCTDeviceEventEmitter.removeListener(
      'orientationDidChange', listener
    );
  }
}
<|endoftext|>


<commit_before>
/*!
 * Module dependencies.
 */

var mongoose = require('mongoose')
var Articulo = mongoose.model('Articulo')

exports.dameArticulos= function(req, res){
	Articulo.find(function(error, data){
		if (error) return res.status(500).send(err.message);
		return res.status(200).jsonp(data);
	});
};

exports.dameArticulosFecha= function(req, res){
	var dia=req.params.dia;
	var mes=req.params.mes;
	var ano =req.params.ano;
	var fecha = new date(ano, mes, dia);
	Articulo.find({"createdAt" : { $gte : fecha }).exec(function(error, data){
		if (error) return res.status(500).send(err.message);
		return res.status(200).jsonp(data);
	});
};

exports.nuevo=function(req,res){
	var datos = req.body;
	console.log('Añadir a: -> ' + req.params.id);
	//console.log ('Datos pasados ->');
	//console.log(datos);

	articulo = new Articulo(datos);
	articulo.save(function(err, object){
		if (err){
			//console.log("ERROR -> Al crear el articulo")
			//console.log(err.message);
			return res.status(500).send(err.message);
		}else{
			console.log("Articulo creado");
			return res.status(200).send('Correcto');
		}

	});
};<commit_msg>fecha2<commit_after>
/*!
 * Module dependencies.
 */

var mongoose = require('mongoose')
var Articulo = mongoose.model('Articulo')

exports.dameArticulos= function(req, res){
	Articulo.find(function(error, data){
		if (error) return res.status(500).send(err.message);
		return res.status(200).jsonp(data);
	});
};

exports.dameArticulosFecha= function(req, res){
	var dia=req.params.dia;
	var mes=req.params.mes;
	var ano =req.params.ano;
	var fecha = new date(ano, mes, dia);
	Articulo.find({"createdAt" : { $gte : fecha }}).exec(function(error, data){
		if (error) return res.status(500).send(err.message);
		return res.status(200).jsonp(data);
	});
};

exports.nuevo=function(req,res){
	var datos = req.body;
	console.log('Añadir a: -> ' + req.params.id);
	//console.log ('Datos pasados ->');
	//console.log(datos);

	articulo = new Articulo(datos);
	articulo.save(function(err, object){
		if (err){
			//console.log("ERROR -> Al crear el articulo")
			//console.log(err.message);
			return res.status(500).send(err.message);
		}else{
			console.log("Articulo creado");
			return res.status(200).send('Correcto');
		}

	});
};<|endoftext|>


<commit_before>(function($) {
    // Setup label help text
    $('label[title]').each(function(){
        var $this = $(this);
        $this.append('');
        $this.tooltip({showURL: false});
    });
    // Setup title-pane widgets
    $('.title-pane .title').click(function(e) {
        e.preventDefault();
        $(this).closest('.title-pane')
            .find('> .content').toggle('fast', function() {
                $(this)
                    .closest('.title-pane').toggleClass('closed').end()
                    .toggleClass('hidden');
            });
    });
    if(window.location.hash) {
        $(window.location.hash + '.title-pane').removeClass('closed');
    }

    // Setup editable widgets
    $('div.editable, span.editable, h1.editable')
        .find('.viewer')
        .append('<button class="edit_btn ui-button ui-widget ui-state-default ui-button-icon-only" title="Edit">Edit</button>')
        .click(function(e){
            var editable = $(this).closest('.editable');
            var editor = editable.find('.editor');
            var viewer = editable.find('.viewer');
            if(editor.hasClass('overlap')){
                editor.width(viewer.width());
            }
            editable.addClass('editing')
                    .removeClass('viewing');
            // autoresize textareas will be the wrong size the first time due to being hidden, so nudge them
            editor.find('textarea').change();
            return false;
        })
        .find('a').click(function(event){
          event.stopPropagation();
        })
        .end()
        .end()
        .find('.editor')
        .find('input, select, textarea').each(function(i){
            // we only want one submit button for each editor even if there are multiple inputs
            // make sure the visually important one is first!
            var editor = $(this).closest('.editor');
            if(!$('a.cancel_btn', editor).length){
                var save_btns = $('
<input type="submit" value="Save"/>Cancel
');
                if(editor.hasClass('multiline')){
                    var save_holder = editor.find('.save_holder');
                    if(save_holder.length){
                        save_holder.append(save_btns);
                    }
                    else{
                        editor.append(save_btns);
                    }
                }
                else{
                    editor.append($('

')
                                .append($('').append($(this)))
                                .append($('').append($(save_btns)))
                    );
                }
            }
        })
        .end()
        .find('.cancel_btn').click(function(e){
            $(this).closest('.editable')
                      .addClass('viewing')
                      .removeClass('editing');
            return false;
        });
})(jQuery);

$(function(){
    $('.defaultText').
        focus(function(){
            var $this = $(this);
            if ( $this.val() == $this[0].title ){
                $this.removeClass('defaultTextActive').val('');
            }
        }).
        blur(function(){
            var $this = $(this);
            if ( !$this.val() ){
                $this.addClass('defaultTextActive').val($this[0].title);
            }
        }).
        blur();
});

function flash( html, kind ){
    kind || (kind = 'notice');
    return $('
').append(html).prependTo('#notifications');
}

function attach_form_retry( form ){
    $(form).submit(function(){
        $form = $(this);

        var $message = $('#save-message');
        $message.length || ($message = flash('
saving...
').attr('id', 'save-message'));
        setTimeout(function(){
            // After 7 seconds, express our concern.
            $message.
                addClass('error').
                removeClass('notice').
                html('
The server is taking too long to respond.
Retrying in 30 seconds.
').
                show();
            setTimeout(function(){
                // After 30 seconds total, give up and try again.
                $message.html('
retrying...
').show();
                $form.submit();
            }, 23000)
        }, 7000);
    });
}

$(function(){
    // Setup notifications.
    $('#flash > div').prependTo('#notifications');
    $('#notifications > div').live('click', function(){
        $(this).hide();
    });

    // Add notifications for form submission.
    attach_form_retry('form.can-retry');

    // Make life a little better for Chrome users by setting tab-order on inputs.
    // This won't stop Chrome from tabbing over links, but should stop links from
    // coming "in between" fields.
    var i = 0;
    $('input,textarea,select,button').each(function(){
        $(this).attr('tabindex', i++);
    });

    // Provide prompt text for otherwise empty viewers
    var ws = /^\s*$/;
    $('[data-prompt]').each(function(){
        var $this = $(this);
        if ( ws.test($this.text()) ) {
            $this.css('color', 'gray').text($this.attr('data-prompt'))
        }
    });
});
<commit_msg>[#680] Hover edit cancel button now restores the original value<commit_after>(function($) {
    // Setup label help text
    $('label[title]').each(function(){
        var $this = $(this);
        $this.append('');
        $this.tooltip({showURL: false});
    });
    // Setup title-pane widgets
    $('.title-pane .title').click(function(e) {
        e.preventDefault();
        $(this).closest('.title-pane')
            .find('> .content').toggle('fast', function() {
                $(this)
                    .closest('.title-pane').toggleClass('closed').end()
                    .toggleClass('hidden');
            });
    });
    if(window.location.hash) {
        $(window.location.hash + '.title-pane').removeClass('closed');
    }

    // Setup editable widgets
    $('div.editable, span.editable, h1.editable')
        .find('.viewer')
        .append('<button class="edit_btn ui-button ui-widget ui-state-default ui-button-icon-only" title="Edit">Edit</button>')
        .click(function(e){
            var editable = $(this).closest('.editable');
            var editor = editable.find('.editor');
            var viewer = editable.find('.viewer');
            if(editor.hasClass('overlap')){
                editor.width(viewer.width());
            }
            editable.addClass('editing')
                    .removeClass('viewing');
            // autoresize textareas will be the wrong size the first time due to being hidden, so nudge them
            editor.find('textarea').change();
            return false;
        })
        .find('a').click(function(event){
          event.stopPropagation();
        })
        .end()
        .end()
        .find('.editor')
        .find('input, select, textarea').each(function(i){
            var $this = $(this);
            var editor = $this.closest('.editor');
            $this.attr('original_val', this.value);
            if(!$('a.cancel_btn', editor).length){
                var save_btns = $('
<input type="submit" value="Save"/>Cancel
');
                if(editor.hasClass('multiline')){
                    var save_holder = editor.find('.save_holder');
                    if(save_holder.length){
                        save_holder.append(save_btns);
                    }
                    else{
                        editor.append(save_btns);
                    }
                }
                else{
                    editor.append($('

')
                                .append($('').append($this))
                                .append($('').append($(save_btns)))
                    );
                }
            }
        })
        .end()
        .find('.cancel_btn').click(function(e){
            $(this).closest('.editable')
                        .addClass('viewing')
                        .removeClass('editing')
                        .find('input, select, textarea').each(function(){
                            $(this).val($(this).attr('original_val'));
                        });
            return false;
        });
})(jQuery);

$(function(){
    $('.defaultText').
        focus(function(){
            var $this = $(this);
            if ( $this.val() == $this[0].title ){
                $this.removeClass('defaultTextActive').val('');
            }
        }).
        blur(function(){
            var $this = $(this);
            if ( !$this.val() ){
                $this.addClass('defaultTextActive').val($this[0].title);
            }
        }).
        blur();
});

function flash( html, kind ){
    kind || (kind = 'notice');
    return $('
').append(html).prependTo('#notifications');
}

function attach_form_retry( form ){
    $(form).submit(function(){
        $form = $(this);

        var $message = $('#save-message');
        $message.length || ($message = flash('
saving...
').attr('id', 'save-message'));
        setTimeout(function(){
            // After 7 seconds, express our concern.
            $message.
                addClass('error').
                removeClass('notice').
                html('
The server is taking too long to respond.
Retrying in 30 seconds.
').
                show();
            setTimeout(function(){
                // After 30 seconds total, give up and try again.
                $message.html('
retrying...
').show();
                $form.submit();
            }, 23000)
        }, 7000);
    });
}

$(function(){
    // Setup notifications.
    $('#flash > div').prependTo('#notifications');
    $('#notifications > div').live('click', function(){
        $(this).hide();
    });

    // Add notifications for form submission.
    attach_form_retry('form.can-retry');

    // Make life a little better for Chrome users by setting tab-order on inputs.
    // This won't stop Chrome from tabbing over links, but should stop links from
    // coming "in between" fields.
    var i = 0;
    $('input,textarea,select,button').each(function(){
        $(this).attr('tabindex', i++);
    });

    // Provide prompt text for otherwise empty viewers
    var ws = /^\s*$/;
    $('[data-prompt]').each(function(){
        var $this = $(this);
        if ( ws.test($this.text()) ) {
            $this.css('color', 'gray').text($this.attr('data-prompt'))
        }
    });
});
<|endoftext|>


<commit_before>import { A } from '@ember/array';
import Controller from '@ember/controller';
import { computed } from '@ember/object';

import { task } from 'ember-concurrency';
import { alias } from 'macro-decorators';

import ajax from '../utils/ajax';

const TO_SHOW = 5;

export default class DashboardController extends Controller {
  hasMore = false;
  myFeed = A();

  @alias('model.myCrates') myCrates;
  @alias('model.myFollowing') myFollowing;
  @alias('model.myStats') myStats;

  @computed('myCrates.[]')
  get visibleCrates() {
    return this.myCrates.slice(0, TO_SHOW);
  }

  @computed('myFollowing.[]')
  get visibleFollowing() {
    return this.myFollowing.slice(0, TO_SHOW);
  }

  @computed('myCrates.[]')
  get hasMoreCrates() {
    return this.myCrates.length > TO_SHOW;
  }

  @computed('myFollowing.[]')
  get hasMoreFollowing() {
    return this.myFollowing.length > TO_SHOW;
  }

  @task(function* () {
    let page = this.myFeed.length / 10 + 1;

    let data = yield ajax(`/api/v1/me/updates?page=${page}`);
    let versions = data.versions.map(version => this.store.push(this.store.normalize('version', version)));

    this.myFeed.pushObjects(versions);
    this.set('hasMore', data.meta.more);
  })
  loadMoreTask;
}
<commit_msg>dashboard: Remove unnecessary `@computed` decorator<commit_after>import { A } from '@ember/array';
import Controller from '@ember/controller';

import { task } from 'ember-concurrency';
import { alias } from 'macro-decorators';

import ajax from '../utils/ajax';

const TO_SHOW = 5;

export default class DashboardController extends Controller {
  hasMore = false;
  myFeed = A();

  @alias('model.myCrates') myCrates;
  @alias('model.myFollowing') myFollowing;
  @alias('model.myStats') myStats;

  get visibleCrates() {
    return this.myCrates.slice(0, TO_SHOW);
  }

  get visibleFollowing() {
    return this.myFollowing.slice(0, TO_SHOW);
  }

  get hasMoreCrates() {
    return this.myCrates.length > TO_SHOW;
  }

  get hasMoreFollowing() {
    return this.myFollowing.length > TO_SHOW;
  }

  @task(function* () {
    let page = this.myFeed.length / 10 + 1;

    let data = yield ajax(`/api/v1/me/updates?page=${page}`);
    let versions = data.versions.map(version => this.store.push(this.store.normalize('version', version)));

    this.myFeed.pushObjects(versions);
    this.set('hasMore', data.meta.more);
  })
  loadMoreTask;
}
<|endoftext|>


<commit_before>const fsp = require('fs-promise');

const newLineCharacters = ["\n", "\r"]

const readPreviousChar = function(stat, file, currentCharacterCount) {
	return fsp.read(file, new Buffer(1), 0, 1, stat.size - 1 - currentCharacterCount)
		.then((bytesReadAndBuffer) => {
			return String.fromCharCode(bytesReadAndBuffer[1][0]);
		})
}

module.exports = {

	/**
	 * Read in the last `n` lines of a file
	 * @param  {string}  file (direct or relative path to file.)
	 * @param  {int}     maxLineCount max number of lines to read in.
	 * @return {promise} new Promise, resolved with lines or rejected with error.
	 */

	read: function(input_file_path, maxLineCount) {
		return new Promise((resolve, reject) => {
			let self = {
				stat: null,
				file: null
			}

			fsp.exists(input_file_path)
			.then(function(exists) {
				if (!exists) {
					throw "file does not exist";
				}

			}).then(function() {
				var promises = [];

				// Load file Stats.
				promises.push(
					fsp.stat(input_file_path)
						.then(stat => self.stat = stat));

				// Open file for reading.
				promises.push(
					fsp.open(input_file_path, 'r')
						.then(file => self.file = file));

				return promises;
			}).then(function(promises) {
				Promise.all(promises)
					.then(() => {
						var chars = 0;
						var lineCount = 0;
						var lines = '';

						var do_while_loop = function() {
							if (lines.length > self.stat.size) {
								lines = lines.substring(lines.length - self.stat.size);
							}

							if (lines.length >= self.stat.size || lineCount >= maxLineCount) {
								if (newLineCharacters.includes(lines.substring(0, 1))) {
									lines = lines.substring(1);
								}
								return resolve(lines);
							}

							readPreviousChar(self.stat, self.file, chars)
								.then((nextCharacter) => {
									lines = nextCharacter + lines;
									if (newLineCharacters.includes(nextCharacter) && lines.length > 1) {
										lineCount++;
									}
									chars++;
								})
								.then(do_while_loop);
						}
						do_while_loop();

					});
			}).catch(reject);
		})
	}
}
<commit_msg>fix(strict): add use strict to index<commit_after>'use strict';
const fsp = require('fs-promise');

const newLineCharacters = ["\n", "\r"]

const readPreviousChar = function(stat, file, currentCharacterCount) {
	return fsp.read(file, new Buffer(1), 0, 1, stat.size - 1 - currentCharacterCount)
		.then((bytesReadAndBuffer) => {
			return String.fromCharCode(bytesReadAndBuffer[1][0]);
		})
}

module.exports = {

	/**
	 * Read in the last `n` lines of a file
	 * @param  {string}  file (direct or relative path to file.)
	 * @param  {int}     maxLineCount max number of lines to read in.
	 * @return {promise} new Promise, resolved with lines or rejected with error.
	 */

	read: function(input_file_path, maxLineCount) {
		return new Promise((resolve, reject) => {
			let self = {
				stat: null,
				file: null
			}

			fsp.exists(input_file_path)
			.then(function(exists) {
				if (!exists) {
					throw "file does not exist";
				}

			}).then(function() {
				var promises = [];

				// Load file Stats.
				promises.push(
					fsp.stat(input_file_path)
						.then(stat => self.stat = stat));

				// Open file for reading.
				promises.push(
					fsp.open(input_file_path, 'r')
						.then(file => self.file = file));

				return promises;
			}).then(function(promises) {
				Promise.all(promises)
					.then(() => {
						var chars = 0;
						var lineCount = 0;
						var lines = '';

						var do_while_loop = function() {
							if (lines.length > self.stat.size) {
								lines = lines.substring(lines.length - self.stat.size);
							}

							if (lines.length >= self.stat.size || lineCount >= maxLineCount) {
								if (newLineCharacters.includes(lines.substring(0, 1))) {
									lines = lines.substring(1);
								}
								return resolve(lines);
							}

							readPreviousChar(self.stat, self.file, chars)
								.then((nextCharacter) => {
									lines = nextCharacter + lines;
									if (newLineCharacters.includes(nextCharacter) && lines.length > 1) {
										lineCount++;
									}
									chars++;
								})
								.then(do_while_loop);
						}
						do_while_loop();

					});
			}).catch(reject);
		})
	}
}
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Controller.extend({
  selectedDisplay: null,
  selectedOrientation: null,
  watchDisplay: function() {
    console.log(this.get('selectedDisplay'));
    var selected = this.get('selectedDisplay');
    if(selected){
      this.send('updateModelProperty', 'display', this.get('selectedDisplay'));
    }
  }.observes('selectedDisplay'),
  watchOrientation: function() {
    var selected = this.get('selectedOrientation');
    if(selected !== ''){
      this.send('updateModelProperty', 'orientation', this.get('selectedOrientation'));
    }
  }.observes('selectedOrientation'),
  watchModel: function() {
    // I want to call this.model.save() here, but that'll be an endless loop
  }.observes('model.manifest.wat_sharing')
});
<commit_msg>Setting dropdowns values to empty string<commit_after>import Ember from 'ember';

export default Ember.Controller.extend({
  selectedDisplay: null,
  selectedOrientation: null,
  valueOrEmptyString: function (value) {
    if(value) {
      return value;
    } else {
      return '';
    }
  },
  watchDisplay: function() {
    var selected = this.get('selectedDisplay');
    this.send('updateModelProperty', 'display', this.valueOrEmptyString(selected));
  }.observes('selectedDisplay'),
  watchOrientation: function() {
    var selected = this.get('selectedOrientation');
    this.send('updateModelProperty', 'orientation', this.valueOrEmptyString(selected));
  }.observes('selectedOrientation')
});
<|endoftext|>


<commit_before>"use strict";

// Make sure lines are splited correctly
// http://stackoverflow.com/questions/1155678/javascript-string-newline-character
var NEW_LINE = /\r\n|\n|\r/;
var COLON = ":";
// var COMMA = ",";
// var DQUOTE = "\"";
// var SEMICOLON = ";";
var SPACE = " ";

/**
 * Take ical string data and convert to JSON
 *
 * @param {string} source
 * @returns {Object}
 */
function convert(source) {
  var currentKey = "",
    currentValue = "",
    parentObj = {},
    splitAt;

  var output = {};
  var lines = source.split(NEW_LINE);

  var currentObj = output;
  var parents = [];

  for (var i = 0; i < lines.length; i++) {
    var line = lines[i];
    if (line.charAt(0) === SPACE) {
      currentObj[currentKey] += line.substr(1);
    } else {
      splitAt = line.indexOf(COLON);

      if (splitAt < 0) {
        continue;
      }

      currentKey = line.substr(0, splitAt);
      currentValue = line.substr(splitAt + 1);

      switch (currentKey) {
        case "BEGIN":
          parents.push(parentObj);
          parentObj = currentObj;
          if (parentObj[currentValue] == null) {
            parentObj[currentValue] = [];
          }
          // Create a new object, store the reference for future uses
          currentObj = {};
          parentObj[currentValue].push(currentObj);
          break;
        case "END":
          currentObj = parentObj;
          parentObj = parents.pop();
          break;
        default:
          if (currentObj[currentKey]) {
            if (!Array.isArray(currentObj[currentKey])) {
              currentObj[currentKey] = [currentObj[currentKey]];
            }
            currentObj[currentKey].push(currentValue);
          } else {
            currentObj[currentKey] = currentValue;
          }
      }
    }
  }
  return output;
}

/**
 * Take JSON, revert back to ical
 * @param {Object} object
 * @return {String}
 */
function revert(object) {
  var lines = [];

  for (var key in object) {
    var value = object[key];
    if (Array.isArray(value)) {
      if (key === 'RDATE') {
        value.forEach(item => lines.push(`${key}:${item}`));
      } else {
        value.forEach(item => {
          lines.push(`BEGIN:${key}`);
          lines.push(revert(item));
          lines.push(`END:${key}`);
        });
      }
    } else {
      var fullLine = key + ":" + value;
      do {
        // According to ical spec, lines of text should be no longer
        // than 75 octets
        lines.push(fullLine.substr(0, 75));
        fullLine = SPACE + fullLine.substr(75);
      } while (fullLine.length > 1);
    }
  }

  return lines.join("\n");
}

module.exports = {
  revert: revert,
  convert: convert
};
<commit_msg>don't use new es features<commit_after>"use strict";

// Make sure lines are splited correctly
// http://stackoverflow.com/questions/1155678/javascript-string-newline-character
var NEW_LINE = /\r\n|\n|\r/;
var COLON = ":";
// var COMMA = ",";
// var DQUOTE = "\"";
// var SEMICOLON = ";";
var SPACE = " ";

/**
 * Take ical string data and convert to JSON
 *
 * @param {string} source
 * @returns {Object}
 */
function convert(source) {
  var currentKey = "",
    currentValue = "",
    parentObj = {},
    splitAt;

  var output = {};
  var lines = source.split(NEW_LINE);

  var currentObj = output;
  var parents = [];

  for (var i = 0; i < lines.length; i++) {
    var line = lines[i];
    if (line.charAt(0) === SPACE) {
      currentObj[currentKey] += line.substr(1);
    } else {
      splitAt = line.indexOf(COLON);

      if (splitAt < 0) {
        continue;
      }

      currentKey = line.substr(0, splitAt);
      currentValue = line.substr(splitAt + 1);

      switch (currentKey) {
        case "BEGIN":
          parents.push(parentObj);
          parentObj = currentObj;
          if (parentObj[currentValue] == null) {
            parentObj[currentValue] = [];
          }
          // Create a new object, store the reference for future uses
          currentObj = {};
          parentObj[currentValue].push(currentObj);
          break;
        case "END":
          currentObj = parentObj;
          parentObj = parents.pop();
          break;
        default:
          if (currentObj[currentKey]) {
            if (!Array.isArray(currentObj[currentKey])) {
              currentObj[currentKey] = [currentObj[currentKey]];
            }
            currentObj[currentKey].push(currentValue);
          } else {
            currentObj[currentKey] = currentValue;
          }
      }
    }
  }
  return output;
}

/**
 * Take JSON, revert back to ical
 * @param {Object} object
 * @return {String}
 */
function revert(object) {
  var lines = [];

  for (var key in object) {
    var value = object[key];
    if (Array.isArray(value)) {
      if (key === "RDATE") {
        value.forEach(function(item) {
          lines.push(key + ":" +item );
        });
      } else {
        value.forEach(function(item) {
          lines.push("BEGIN:" + key);
          lines.push(revert(item));
          lines.push("END:" + key);
        });
      }
    } else {
      var fullLine = key + ":" + value;
      do {
        // According to ical spec, lines of text should be no longer
        // than 75 octets
        lines.push(fullLine.substr(0, 75));
        fullLine = SPACE + fullLine.substr(75);
      } while (fullLine.length > 1);
    }
  }

  return lines.join("\n");
}

module.exports = {
  revert: revert,
  convert: convert
};
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2018 gRPC authors.
 *
 * 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.
 *
 */

/**
 * @fileoverview Description of this file.
 */

'use strict';

const assert = require('assert');
const grpc = require('grpc');
const {GoogleAuth} = require('google-auth-library');
const spanner_grpc = require('../google/spanner/v1/spanner_grpc_pb.js');
const spanner = require('../google/spanner/v1/spanner_pb.js');

const _TARGET = 'spanner.googleapis.com:443';
const _OAUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform';
const _DATABASE = 'projects/grpc-gcp/instances/sample/databases/benchmark';
const _TEST_SQL = 'select id from storage';

/**
 * Client to use to make requests to Spanner target.
 */
var client;

describe('Spanner integration tests', function() {
  before(function(done) {
    var authFactory = new GoogleAuth();
    authFactory.getApplicationDefault((err, auth) => {
      assert.ifError(err);

      if (auth.createScopedRequired && auth.createScopedRequired()) {
        var scopes = [_OAUTH_SCOPE];
        auth = auth.createScoped(scopes);
      }
      var sslCreds = grpc.credentials.createSsl();
      var callCreds = grpc.credentials.createFromGoogleCredential(auth);
      var channelCreds = grpc.credentials.combineChannelCredentials(
        sslCreds,
        callCreds
      );
      client = new spanner_grpc.SpannerClient(_TARGET, channelCreds);
      done();
    });
  });

  it('Test createSession, getSession, listSessions, deleteSession', function(done) {
    var createSessionRequest = new spanner.CreateSessionRequest();
    createSessionRequest.setDatabase(_DATABASE);
    client.createSession(createSessionRequest, (err, session) => {
      assert.ifError(err);
      var sessionName = session.getName();

      var getSessionRequest = new spanner.GetSessionRequest();
      getSessionRequest.setName(sessionName);

      client.getSession(getSessionRequest, (err, sessionResult) => {
        assert.ifError(err);
        assert.strictEqual(sessionResult.getName(), sessionName);

        var deleteSessionRequest = new spanner.DeleteSessionRequest();
        deleteSessionRequest.setName(sessionName);

        client.deleteSession(deleteSessionRequest, err => {
          assert.ifError(err);
          done();
        });
      });
    });
  });

  it ('Test executeSql', function(done) {
    var createSessionRequest = new spanner.CreateSessionRequest();
    createSessionRequest.setDatabase(_DATABASE);
    client.createSession(createSessionRequest, (err, session) => {
      assert.ifError(err);
      var sessionName = session.getName();

      var executeSqlRequest = new spanner.ExecuteSqlRequest();
      executeSqlRequest.setSession(sessionName);
      executeSqlRequest.setSql(_TEST_SQL);

      client.executeSql(executeSqlRequest, (err, resultSet) => {
        assert.ifError(err);
        assert.notEqual(resultSet, null);
        var rowsList = resultSet.getRowsList();
        var value = rowsList[0].getValuesList()[0].getStringValue();
        assert.equal(value, 'payload');

        var deleteSessionRequest = new spanner.DeleteSessionRequest();
        deleteSessionRequest.setName(sessionName);

        client.deleteSession(deleteSessionRequest, err => {
          assert.ifError(err);
          done();
        });
      });
    });
  });

});
<commit_msg>Add basic spanner integration tests.<commit_after>/**
 * @license
 * Copyright 2018 gRPC authors.
 *
 * 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.
 *
 */

/**
 * @fileoverview Description of this file.
 */

'use strict';

const assert = require('assert');
const grpc = require('grpc');
const {GoogleAuth} = require('google-auth-library');
const spannerGrpc = require('../google/spanner/v1/spanner_grpc_pb.js');
const spanner = require('../google/spanner/v1/spanner_pb.js');

const _TARGET = 'spanner.googleapis.com:443';
const _OAUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform';
const _DATABASE = 'projects/grpc-gcp/instances/sample/databases/benchmark';
const _TEST_SQL = 'select id from storage';

const grpcGcp = require('../..');

/**
 * Client to use to make requests to Spanner target.
 */
var client;

describe('Spanner integration tests', function() {
  before(function(done) {
    var authFactory = new GoogleAuth();
    authFactory.getApplicationDefault((err, auth) => {
      assert.ifError(err);

      var scopes = [_OAUTH_SCOPE];
      auth = auth.createScoped(scopes);

      var sslCreds = grpc.credentials.createSsl();
      var callCreds = grpc.credentials.createFromGoogleCredential(auth);
      var channelCreds = grpc.credentials.combineChannelCredentials(
        sslCreds,
        callCreds
      );

      function addMethod(apiConfig, methodName, command, affinityKey) {
        apiConfig.addMethod(
          new grpcGcp.MethodConfig({
            name: '/google.spanner.v1.Spanner/CreateSession',
            affinity: new grpcGcp.AffinityConfig({
              command: command,
              affinityKey: affinityKey,
            }),
          })
        );
      }

      var apiConfig = new grpcGcp.ApiConfig();
      apiConfig.setChannelPool(
        new grpcGcp.ChannelPoolConfig({
          maxSize: 10,
          maxConcurrentStreamsLowWatermark: 1,
        })
      );

      addMethod(
        apiConfig,
        '/google.spanner.v1.Spanner/CreateSession',
        grpcGcp.AffinityConfig.Command.BIND,
        'name'
      );
      addMethod(
        apiConfig,
        '/google.spanner.v1.Spanner/GetSession',
        grpcGcp.AffinityConfig.Command.BOUND,
        'name'
      );
      addMethod(
        apiConfig,
        '/google.spanner.v1.Spanner/DeleteSession',
        grpcGcp.AffinityConfig.Command.UNBIND,
        'name'
      );
      addMethod(
        apiConfig,
        '/google.spanner.v1.Spanner/ExecuteSql',
        grpcGcp.AffinityConfig.Command.BOUND,
        'session'
      );

      var channelOptions = {
        channelFactoryOverride: grpcGcp.gcpChannelFactoryOverride,
        callInvocationTransformer: grpcGcp.gcpCallInvocationTransformer,
        gcpApiConfig: apiConfig,
      };

      client = new spannerGrpc.SpannerClient(
        _TARGET,
        channelCreds,
        channelOptions
      );

      done();
    });
  });

  it('Test createSession, getSession, listSessions, deleteSession', function(done) {
    var createSessionRequest = new spanner.CreateSessionRequest();
    createSessionRequest.setDatabase(_DATABASE);
    client.createSession(createSessionRequest, (err, session) => {
      assert.ifError(err);
      var sessionName = session.getName();

      var getSessionRequest = new spanner.GetSessionRequest();
      getSessionRequest.setName(sessionName);

      client.getSession(getSessionRequest, (err, sessionResult) => {
        assert.ifError(err);
        assert.strictEqual(sessionResult.getName(), sessionName);

        var deleteSessionRequest = new spanner.DeleteSessionRequest();
        deleteSessionRequest.setName(sessionName);

        client.deleteSession(deleteSessionRequest, err => {
          assert.ifError(err);
          done();
        });
      });
    });
  });

  it('Test executeSql', function(done) {
    var createSessionRequest = new spanner.CreateSessionRequest();
    createSessionRequest.setDatabase(_DATABASE);
    client.createSession(createSessionRequest, (err, session) => {
      assert.ifError(err);
      var sessionName = session.getName();

      var executeSqlRequest = new spanner.ExecuteSqlRequest();
      executeSqlRequest.setSession(sessionName);
      executeSqlRequest.setSql(_TEST_SQL);

      client.executeSql(executeSqlRequest, (err, resultSet) => {
        assert.ifError(err);
        assert.notStrictEqual(resultSet, null);
        var rowsList = resultSet.getRowsList();
        var value = rowsList[0].getValuesList()[0].getStringValue();
        assert.strictEqual(value, 'payload');

        var deleteSessionRequest = new spanner.DeleteSessionRequest();
        deleteSessionRequest.setName(sessionName);

        client.deleteSession(deleteSessionRequest, err => {
          assert.ifError(err);
          done();
        });
      });
    });
  });

  it('Test executeStreamingSql', function(done) {
    var createSessionRequest = new spanner.CreateSessionRequest();
    createSessionRequest.setDatabase(_DATABASE);
    client.createSession(createSessionRequest, (err, session) => {
      assert.ifError(err);
      console.log('---Created session---');
      var sessionName = session.getName();

      var executeSqlRequest = new spanner.ExecuteSqlRequest();
      executeSqlRequest.setSession(sessionName);
      executeSqlRequest.setSql('select data from storage');

      var call = client.executeStreamingSql(executeSqlRequest);
      call.on('data', function(partialResultSet) {
        console.log('Found partial result!');
      });
      call.on('end', function() {
        var deleteSessionRequest = new spanner.DeleteSessionRequest();
        deleteSessionRequest.setName(sessionName);
        client.deleteSession(deleteSessionRequest, err => {
          assert.ifError(err);
          done();
          console.log('---Deleted session---');
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Google Docs quick download
// @description Skips the "this file could not be checked for viruses" prompt when downloading files from Google Docs
// @namespace   trashihansen@gmail.com
// @match       https://docs.google.com/uc?id=*&export=download
// @match       http://docs.google.com/uc?id=*&export=download
// @version     1.1
// @grant       none
// @license     MIT License (Expat); opensource.org/licenses/MIT
// ==/UserScript==
"use strict";

var u = document.location.href;
document.location.href = 'https://docs.google.com/uc?export=download&confirm=sULL&id=' + u.substring(u.indexOf('uc?id=') + 'uc?id='.length, u.indexOf('&export=download'));
<commit_msg>Update googledocs-fast-download.user.js<commit_after>// ==UserScript==
// @name        Google Docs quick download
// @description Skips the "this file could not be checked for viruses" prompt when downloading files from Google Docs
// @namespace   trashihansen@gmail.com
// @match       https://docs.google.com/uc?id=*&export=download
// @match       http://docs.google.com/uc?id=*&export=download
// @version     1.1
// @grant       none
// @license     MIT License (Expat); opensource.org/licenses/MIT
// ==/UserScript==
"use strict";

document.location.href = document.getElementById('uc-download-link').href;
<|endoftext|>


<commit_before>angular.module("storageExplorer").directive("entryValue", function ($compile) {
    function checkWidth(string) {
        if (string.length > 50) {
            return string.substr(0, 49) + "...";
        }
        return string;
    }

    var stringTemplate = '"{{displayedValue}}"';
    var booleanTemplate = '{{displayedValue}}';
    var numberTemplate = '{{displayedValue}}';
    var objectTemplate = '{{{displayedValue}}}';
    var arrayTemplate = '[{{displayedValue}}]';

    function escape(input) {
        var string = '' + input;
        var newString = [];
        var replace = {
            '$': '$',
            '<': '<',
            '>': '>'
        };
        for (var i = 0; i < string.length; i++) {
            if(angular.isDefined(replace[string.charAt(i)])) {
                newString.push(replace[string.charAt(i)]);
                continue;
            }
            newString.push(string.charAt(i));
        }

        return newString.join('');
    }

    function string(value) {

        return stringTemplate.replace('{{displayedValue}}', checkWidth(escape(value)));
    }

    function bool(value) {
        return booleanTemplate.replace('{{displayedValue}}', value);
    }

    function num(value) {
        return numberTemplate.replace('{{displayedValue}}', value)
    }

    function object(value) {
        if (angular.isArray(value)) {
            return array(value);
        }
        if (angular.isString(value)) {
            return string(value);
        }
        if (angular.isNumber(value)) {
            return num(value);
        }
        if (angular.isObject(value)) {
            var template = [];
            angular.forEach(value, function (propVal, propKey) {
                template.push(string(propKey));
                template.push(" : ");
                template.push(object(propVal));
                template.push(", ");
            });
            template.pop();
            return objectTemplate.replace("{{displayedValue}}", template.join(''));
        }
        if (value === null) {
            return bool(null);
        }
        return bool(value);

    }

    function array(value) {

        var template = [];
        angular.forEach(value, function (propVal) {
            template.push(object(propVal));
            template.push(", ");
        });
        template.pop();
        return arrayTemplate.replace("{{displayedValue}}", template.join(''));
    }

    function val(val) {
        if (angular.isString(val)) {
            return string(val);
        }
        if (angular.isNumber(val)) {
            return num(val);
        }
        if (angular.isObject(val)) {
            return object(val);
        }
        if (val === null) {
            return bool('null');
        }
        return bool(val);
    }

    return {
        restrict: 'E',
        scope: {
            value: "=",
            key: "="
        },
        link: function (scope, element, attr) {
            var value = scope.value;
            element.append(val(value));
            element.bind("dblclick", function () {
                var editor = angular.element("<input type='text' style='width:100%;height:100%'>");
                editor.val(JSON.stringify(value));
                element.html('');
                element.append(editor);
                editor.select();
                editor.bind("blur", function () {
                    element.html(val(value));
                });
                editor.bind("keydown", function (e) {
                    editor.css("backgroundColor", "");
                    if (e.keyCode == 13) {
                        var newValue = editor.val().trim();
                        if (newValue == "") {
                            newValue = null;
                        }
                        try {
                            scope.$emit("$valueChanged", scope.key, JSON.parse(newValue));
                        } catch (e) {
                            editor.css("backgroundColor", "red");
                            return;
                        }

                    }
                    if (e.keyCode == 13 || e.keyCode == 27) {
                        editor.blur();
                    }
                });
            });
        }
    }

});<commit_msg>bug - fixed inline editing<commit_after>angular.module("storageExplorer").directive("entryValue", function ($compile) {
    function checkWidth(string) {
        if (string.length > 50) {
            return string.substr(0, 49) + "...";
        }
        return string;
    }

    var stringTemplate = '"{{displayedValue}}"';
    var booleanTemplate = '{{displayedValue}}';
    var numberTemplate = '{{displayedValue}}';
    var objectTemplate = '{{{displayedValue}}}';
    var arrayTemplate = '[{{displayedValue}}]';

    function escape(input) {
        var string = '' + input;
        var newString = [];
        var replace = {
            '$': '$',
            '<': '<',
            '>': '>'
        };
        for (var i = 0; i < string.length; i++) {
            if (angular.isDefined(replace[string.charAt(i)])) {
                newString.push(replace[string.charAt(i)]);
                continue;
            }
            newString.push(string.charAt(i));
        }

        return newString.join('');
    }

    function string(value) {

        return stringTemplate.replace('{{displayedValue}}', checkWidth(escape(value)));
    }

    function bool(value) {
        return booleanTemplate.replace('{{displayedValue}}', value);
    }

    function num(value) {
        return numberTemplate.replace('{{displayedValue}}', value)
    }

    function object(value) {
        if (angular.isArray(value)) {
            return array(value);
        }
        if (angular.isString(value)) {
            return string(value);
        }
        if (angular.isNumber(value)) {
            return num(value);
        }
        if (angular.isObject(value)) {
            var template = [];
            angular.forEach(value, function (propVal, propKey) {
                template.push(string(propKey));
                template.push(" : ");
                template.push(object(propVal));
                template.push(", ");
            });
            template.pop();
            return objectTemplate.replace("{{displayedValue}}", template.join(''));
        }
        if (value === null) {
            return bool(null);
        }
        return bool(value);

    }

    function array(value) {

        var template = [];
        angular.forEach(value, function (propVal) {
            template.push(object(propVal));
            template.push(", ");
        });
        template.pop();
        return arrayTemplate.replace("{{displayedValue}}", template.join(''));
    }

    function val(val) {
        if (angular.isString(val)) {
            return string(val);
        }
        if (angular.isNumber(val)) {
            return num(val);
        }
        if (angular.isObject(val)) {
            return object(val);
        }
        if (val === null) {
            return bool('null');
        }
        return bool(val);
    }

    return {
        restrict: 'E',
        scope: {
            value: "=",
            key: "="
        },
        link: function (scope, element, attr) {
            element.append(val(scope.value));
            element.bind("dblclick", function () {
                var editor = angular.element("<input type='text' style='width:100%;height:100%'>");
                editor.val(JSON.stringify(scope.value));
                element.html('');
                element.append(editor);
                editor.select();
                editor.bind("blur", function () {
                    element.html(val(scope.value));
                });
                editor.bind("keydown", function (e) {
                    editor.css("backgroundColor", "");
                    if (e.keyCode == 13) {
                        var newValue = editor.val().trim();
                        if (newValue == "") {
                            newValue = null;
                        }
                        try {
                            scope.$emit("$valueChanged", scope.key, JSON.parse(newValue));
                        } catch (e) {
                            editor.css("backgroundColor", "red");
                            return;
                        }

                    }
                    if (e.keyCode == 27) {
                        editor.blur();
                    }
                });
            });

            scope.$watch('value', function () {
                element.html('');
                element.html(val(scope.value));
            });
        }
    }

});<|endoftext|>


<commit_before>var cadence = require('cadence')

function yes () { return true }

function Forward (cursor) {
    this._cursor = cursor
    this._index = cursor.index
}

Forward.prototype.next = cadence(function (step, condition) {
    condition = condition || yes
    step(function () {
        if (this._index < this._cursor.length) return true
        else step(function () {
            this._cursor.next(step())
            this._index = 0
        })
    }, function (more) {
        if (!more) {
            this.terminated = true
            step(null)
        } else {
            this._cursor.get(this._index++, step())
        }
    }, function (record) {
        if (condition(record)) {
            step(null, record)
        }
    })()
})

Forward.prototype.unlock = function () {
    this._cursor.unlock()
}

exports.forward = cadence(function (step, strata, key) {
    var condition = key == null ? strata.left : strata.key(key)
    step(function () {
        strata.iterator(condition, step())
    }, function (cursor) {
        return new Forward(cursor)
    })
})
<commit_msg>Perform tests on key, not on record.<commit_after>var cadence = require('cadence')

function yes () { return true }

function Forward (cursor) {
    this._cursor = cursor
    this._index = cursor.index
}

Forward.prototype.next = cadence(function (step, condition) {
    condition = condition || yes
    step(function () {
        if (this._index < this._cursor.length) return true
        else step(function () {
            this._cursor.next(step())
            this._index = 0
        })
    }, function (more) {
        if (!more) {
            this.terminated = true
            step(null)
        } else {
            this._cursor.get(this._index++, step())
        }
    }, function (record, key) {
        if (condition(key)) {
            step(null, record, key)
        }
    })()
})

Forward.prototype.unlock = function () {
    this._cursor.unlock()
}

exports.forward = cadence(function (step, strata, key) {
    var condition = key == null ? strata.left : strata.key(key)
    step(function () {
        strata.iterator(condition, step())
    }, function (cursor) {
        return new Forward(cursor)
    })
})
<|endoftext|>