<commit_before>/**
 * Created by daarond on 8/20/2015.
 */
'use strict';

goog.provide('Blockly.Blocks.Queue');

goog.require('Blockly.Blocks');

/**
 * adds data to the queue
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#tusqdy
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_add'] = {
    init: function() {
        this.appendValueInput("queue")
            .setCheck("String")
            .appendField("to queue");
        this.appendValueInput("data")
            .setCheck("Array")
            .appendField("add data");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(45);
        this.setTooltip('adds data to the queue');
    }
};

/**
 * gets the data for the next item in the queue without dequeueing it
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#e4zn54
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_peek'] = {
    init: function() {
        this.appendValueInput("queue")
            .setCheck("String")
            .appendField("peek next item in queue");
        this.setOutput(true, "queue_item");
        this.setColour(45);
        this.setTooltip('gets the data for the next item in the queue without dequeueing it');
    }
};

/**
 * adds data to the queue
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#rt4gje
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_item_data'] = {
    init: function() {
        this.appendValueInput("url")
            .setCheck("queue_item")
            .appendField("get queue item data");
        this.setOutput(true, "string");
        this.setColour(45);
        this.setTooltip('gets the data from a queue item');
    }
};

/**
 * gets the data for the next item in the queue
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#e4zn54
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_retrieve'] = {
    init: function() {
        this.appendValueInput("queue")
            .setCheck("String")
            .appendField("retrieve next item in queue");
        this.setOutput(true, "queue_item");
        this.setColour(45);
        this.setTooltip('gets the data for the next item in the queue');
    }
};

/**
 * gets the data for the next item from the first available queue
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#eepfj2
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_retrieve_list'] = {
    init: function() {
        this.appendValueInput("queue")
            .setCheck("Array")
            .appendField("retrieve next item from list of queues");
        this.setOutput(true, "queue_item");
        this.setColour(45);
        this.setTooltip('gets the data for the next item from the first available queue');
    }
};

/**
 * extends the timeout of a queue item
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#8rztpq
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_item_touch'] = {
    init: function() {
        this.appendValueInput("item")
            .setCheck("queue_item")
            .appendField("extend queue item");
        this.appendValueInput("timeout")
            .setCheck("Number")
            .appendField("timeout by");
        this.appendDummyInput()
            .appendField("seconds");
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(45);
        this.setTooltip('extends the timeout of a queue item');
    }
};

/**
 * releases an item back to the queue
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#gjr8i5
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_item_release'] = {
    init: function() {
        this.appendValueInput("item")
            .setCheck("queue_item")
            .appendField("release queue item");
        this.appendDummyInput()
            .appendField("back to queue");
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(45);
        this.setTooltip('releases an item back to the queue');
    }
};

/**
 * deletes an item from the queue
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#tomn6n
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_item_delete'] = {
    init: function() {
        this.appendValueInput("item")
            .setCheck("queue_item")
            .appendField("delete queue item");
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(45);
        this.setTooltip('deletes an item from the queue');
    }
};

/**
 * delete a queue and all contents
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#iyn83k
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_delete'] = {
    init: function() {
        this.appendValueInput("item")
            .setCheck("string")
            .appendField("delete queue");
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(45);
        this.setTooltip('delete a queue and all contents');
    }
};

/**
 * create a queue
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#iyn83k
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_create'] = {
    init: function() {
        this.appendValueInput("item")
            .setCheck("string")
            .appendField("create queue");
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(45);
        this.setTooltip('create a queue');
    }
};

<commit_msg>updating blocks<commit_after>/**
 * Created by daarond on 8/20/2015.
 */
'use strict';

goog.provide('Blockly.Blocks.Queue');

goog.require('Blockly.Blocks');

/**
 * adds data to the queue
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#tusqdy
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_add'] = {
    init: function() {
        this.appendValueInput("queue")
            .setCheck("String")
            .appendField("to queue");
        this.appendValueInput("data")
            .setCheck("String")
            .appendField("add data");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(45);
        this.setTooltip('adds data to the queue');
    }
};

/**
 * gets the data for the next item in the queue without dequeueing it
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#e4zn54
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_peek'] = {
    init: function() {
        this.appendValueInput("queue")
            .setCheck("String")
            .appendField("peek next item in queue");
        this.setOutput(true, "queue_item");
        this.setColour(45);
        this.setTooltip('gets the data for the next item in the queue without dequeueing it');
    }
};

/**
 * adds data to the queue
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#rt4gje
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_item_data'] = {
    init: function() {
        this.appendValueInput("item")
            .setCheck("queue_item")
            .appendField("get queue item data");
        this.setOutput(true, "string");
        this.setColour(45);
        this.setTooltip('gets the data from a queue item');
    }
};

/**
 * gets the data for the next item in the queue
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#e4zn54
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_retrieve'] = {
    init: function() {
        this.appendValueInput("queue")
            .setCheck("String")
            .appendField("retrieve next item in queue");
        this.setOutput(true, "queue_item");
        this.setColour(45);
        this.setTooltip('gets the data for the next item in the queue');
    }
};

/**
 * gets the data for the next item from the first available queue
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#eepfj2
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_retrieve_list'] = {
    init: function() {
        this.appendValueInput("queue")
            .setCheck("Array")
            .appendField("retrieve next item from list of queues");
        this.setOutput(true, "queue_item");
        this.setColour(45);
        this.setTooltip('gets the data for the next item from the first available queue');
    }
};

/**
 * extends the timeout of a queue item
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#8rztpq
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_item_touch'] = {
    init: function() {
        this.appendValueInput("item")
            .setCheck("queue_item")
            .appendField("extend queue item");
        this.appendValueInput("timeout")
            .setCheck("Number")
            .appendField("timeout by");
        this.appendDummyInput()
            .appendField("seconds");
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(45);
        this.setTooltip('extends the timeout of a queue item');
    }
};

/**
 * releases an item back to the queue
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#gjr8i5
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_item_release'] = {
    init: function() {
        this.appendValueInput("item")
            .setCheck("queue_item")
            .appendField("release queue item");
        this.appendDummyInput()
            .appendField("back to queue");
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(45);
        this.setTooltip('releases an item back to the queue');
    }
};

/**
 * deletes an item from the queue
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#tomn6n
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_item_delete'] = {
    init: function() {
        this.appendValueInput("item")
            .setCheck("queue_item")
            .appendField("delete queue item");
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(45);
        this.setTooltip('deletes an item from the queue');
    }
};

/**
 * delete a queue and all contents
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#iyn83k
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_delete'] = {
    init: function() {
        this.appendValueInput("queue")
            .setCheck("String")
            .appendField("delete queue");
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(45);
        this.setTooltip('delete a queue and all contents');
    }
};

/**
 * create a queue
 * @link https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#iyn83k
 * @type {{init: Function}}
 */
Blockly.Blocks['queue_create'] = {
    init: function() {
        this.appendValueInput("queue")
            .setCheck("String")
            .appendField("create queue");
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(45);
        this.setTooltip('create a queue');
    }
};

<|endoftext|>


<commit_before>/**
 * Copyright (c) 2017-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

const React = require('react')

const CompLibrary = require('../../core/CompLibrary.js')

const MarkdownBlock = CompLibrary.MarkdownBlock /* Used to read markdown */
const Container = CompLibrary.Container
const GridBlock = CompLibrary.GridBlock

const siteConfig = require(`${process.cwd()}/siteConfig.js`)

function imgUrl(img) {
  return `${siteConfig.baseUrl}img/${img}`
}

function docUrl(doc, language) {
  return `${siteConfig.baseUrl}docs/${language ? `${language}/` : ''}${doc}`
}

function pageUrl(page, language) {
  return siteConfig.baseUrl + (language ? `${language}/` : '') + page
}

class Button extends React.Component {
  render() {
    return (

          {this.props.children}

    )
  }
}

Button.defaultProps = {
  target: '_self'
}

const SplashContainer = props => (

{props.children}

)

const Logo = props => (

)

const ProjectTitle = () => (

    {siteConfig.title}
    {siteConfig.tagline}

)

const PromoSection = props => (

{props.children}

)

class HomeSplash extends React.Component {
  render() {
    const language = this.props.language || ''
    return (
      <SplashContainer>
        <Logo img_src={imgUrl('resolve.png')} />

          <ProjectTitle />
          <PromoSection>
            <Button href={docUrl('introduction.html', language)}>
              GET STARTED
            </Button>
            <Button href="https://github.com/reimagined/resolve/tree/master/examples">
              SEE EXAMPLES
            </Button>
          </PromoSection>

      </SplashContainer>
    )
  }
}

const Block = props => (
  <Container
    padding={['bottom', 'top']}
    id={props.id}
    background={props.background}
  >
    <GridBlock align="center" contents={props.children} layout={props.layout} />
  </Container>
)

const Features = props => (
  <Block layout="threeColumn" {...props}>
    {[
      {
        content: `You don't need to configure build and dev tools, libraries and frameworks.
  Your application is ready in seconds.`,
        //image: imgUrl('cqrs.png'),
        imageAlign: 'top',
        title: '## Everything you need in one place.'
      },
      {
        content: `With CQRS and Event Sourciing, your application is easier to develop, adapt, maintain and scale.
  Functional Java Script code is easier to test and reason about.`,
        //image: imgUrl('ddd.png'),
        imageAlign: 'top',
        title: 'Full stack scalable modern app'
      },
      {
        content: `With Event Sourcing your application stores everything and removes nothing.
You don't have to anticipate what data you will need later.`,
        //image: imgUrl('event-sourcing.png'),
        imageAlign: 'top',
        title: "Don't lose your data"
      }
    ]}
  </Block>
)

const GetStarted = props => (
  <Block layout="twoColumn" background="light" {...props}>
    {[
      {
        title: 'Get started in seconds',
        content: `reSolve lets you **focus on code, not build tools**.
To create a project called \`my-app\`, run this command:
\`\`\`sh
npx create-resolve-app my-app
\`\`\`
`
      },
      {
        image:
          'https://camo.githubusercontent.com/29765c4a32f03bd01d44edef1cd674225e3c906b/68747470733a2f2f63646e2e7261776769742e636f6d2f66616365626f6f6b2f6372656174652d72656163742d6170702f323762343261632f73637265656e636173742e737667',
        imageAlign: 'right'
      }
    ]}
  </Block>
)

const FeatureCallout = () => (

Feature Callout

    <MarkdownBlock>
      ### These are features of this project: ------- * Feature 1 * Feature 2
      ```js const a = 3 ```
    </MarkdownBlock>

)

const LearnHow = () => (
  <Block background="light">
    {[
      {
        content: 'Talk about learning how to use this',
        image: imgUrl('docusaurus.svg'),
        imageAlign: 'right',
        title: 'Learn How'
      }
    ]}
  </Block>
)

const TryOut = () => (
  <Block id="try">
    {[
      {
        content: 'Talk about trying this out',
        image: imgUrl('docusaurus.svg'),
        imageAlign: 'left',
        title: 'Try it Out'
      }
    ]}
  </Block>
)

const Description = () => (
  <Block background="dark">
    {[
      {
        content: 'This is another description of how this project is useful',
        image: imgUrl('docusaurus.svg'),
        imageAlign: 'right',
        title: 'Description'
      }
    ]}
  </Block>
)

const Showcase = props => {
  if ((siteConfig.users || []).length === 0) {
    return null
  }

  const showcase = siteConfig.users
    .filter(user => user.pinned)
    .map(user => (

    ))

  return (

Who is Using This?

This project is used by all these people

{showcase}

          More {siteConfig.title} Users

  )
}

const Index = ({ language = '' }) => (

    <HomeSplash language={language} />

      <Features />
      <GetStarted />
      {/*       <FeatureCallout />
      <LearnHow />
      <TryOut />
      <Description />
      <Showcase language={language} /> */}

)

module.exports = Index
<commit_msg>Landing - fix a typo<commit_after>/**
 * Copyright (c) 2017-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

const React = require('react')

const CompLibrary = require('../../core/CompLibrary.js')

const MarkdownBlock = CompLibrary.MarkdownBlock /* Used to read markdown */
const Container = CompLibrary.Container
const GridBlock = CompLibrary.GridBlock

const siteConfig = require(`${process.cwd()}/siteConfig.js`)

function imgUrl(img) {
  return `${siteConfig.baseUrl}img/${img}`
}

function docUrl(doc, language) {
  return `${siteConfig.baseUrl}docs/${language ? `${language}/` : ''}${doc}`
}

function pageUrl(page, language) {
  return siteConfig.baseUrl + (language ? `${language}/` : '') + page
}

class Button extends React.Component {
  render() {
    return (

          {this.props.children}

    )
  }
}

Button.defaultProps = {
  target: '_self'
}

const SplashContainer = props => (

{props.children}

)

const Logo = props => (

)

const ProjectTitle = () => (

    {siteConfig.title}
    {siteConfig.tagline}

)

const PromoSection = props => (

{props.children}

)

class HomeSplash extends React.Component {
  render() {
    const language = this.props.language || ''
    return (
      <SplashContainer>
        <Logo img_src={imgUrl('resolve.png')} />

          <ProjectTitle />
          <PromoSection>
            <Button href={docUrl('introduction.html', language)}>
              GET STARTED
            </Button>
            <Button href="https://github.com/reimagined/resolve/tree/master/examples">
              SEE EXAMPLES
            </Button>
          </PromoSection>

      </SplashContainer>
    )
  }
}

const Block = props => (
  <Container
    padding={['bottom', 'top']}
    id={props.id}
    background={props.background}
  >
    <GridBlock align="center" contents={props.children} layout={props.layout} />
  </Container>
)

const Features = props => (
  <Block layout="threeColumn" {...props}>
    {[
      {
        content: `You don't need to configure build and dev tools, libraries and frameworks.
  Your application is ready in seconds.`,
        //image: imgUrl('cqrs.png'),
        imageAlign: 'top',
        title: '## Everything you need in one place.'
      },
      {
        content: `With CQRS and Event Sourcing, your application is easier to develop, adapt, maintain and scale.
  Functional Java Script code is easier to test and reason about.`,
        //image: imgUrl('ddd.png'),
        imageAlign: 'top',
        title: 'Full stack scalable modern app'
      },
      {
        content: `With Event Sourcing your application stores everything and removes nothing.
You don't have to anticipate what data you will need later.`,
        //image: imgUrl('event-sourcing.png'),
        imageAlign: 'top',
        title: "Don't lose your data"
      }
    ]}
  </Block>
)

const GetStarted = props => (
  <Block layout="twoColumn" background="light" {...props}>
    {[
      {
        title: 'Get started in seconds',
        content: `reSolve lets you **focus on code, not build tools**.
To create a project called \`my-app\`, run this command:
\`\`\`sh
npx create-resolve-app my-app
\`\`\`
`
      },
      {
        image:
          'https://camo.githubusercontent.com/29765c4a32f03bd01d44edef1cd674225e3c906b/68747470733a2f2f63646e2e7261776769742e636f6d2f66616365626f6f6b2f6372656174652d72656163742d6170702f323762343261632f73637265656e636173742e737667',
        imageAlign: 'right'
      }
    ]}
  </Block>
)

const FeatureCallout = () => (

Feature Callout

    <MarkdownBlock>
      ### These are features of this project: ------- * Feature 1 * Feature 2
      ```js const a = 3 ```
    </MarkdownBlock>

)

const LearnHow = () => (
  <Block background="light">
    {[
      {
        content: 'Talk about learning how to use this',
        image: imgUrl('docusaurus.svg'),
        imageAlign: 'right',
        title: 'Learn How'
      }
    ]}
  </Block>
)

const TryOut = () => (
  <Block id="try">
    {[
      {
        content: 'Talk about trying this out',
        image: imgUrl('docusaurus.svg'),
        imageAlign: 'left',
        title: 'Try it Out'
      }
    ]}
  </Block>
)

const Description = () => (
  <Block background="dark">
    {[
      {
        content: 'This is another description of how this project is useful',
        image: imgUrl('docusaurus.svg'),
        imageAlign: 'right',
        title: 'Description'
      }
    ]}
  </Block>
)

const Showcase = props => {
  if ((siteConfig.users || []).length === 0) {
    return null
  }

  const showcase = siteConfig.users
    .filter(user => user.pinned)
    .map(user => (

    ))

  return (

Who is Using This?

This project is used by all these people

{showcase}

          More {siteConfig.title} Users

  )
}

const Index = ({ language = '' }) => (

    <HomeSplash language={language} />

      <Features />
      <GetStarted />
      {/*       <FeatureCallout />
      <LearnHow />
      <TryOut />
      <Description />
      <Showcase language={language} /> */}

)

module.exports = Index
<|endoftext|>


<commit_before>var app = require('../app'),
	expect = require('expect.js');

//test url - this has alot of OG info
var options1 = {
	'url': 'http://ogp.me/'
};

//test url formats
var	options2 = {
		'url': 'http://www.google.com/'
	},
	options3 = {
		'url': 'https://www.google.com/'
	},
	options4 = {
		'url': 'www.google.com/'
	},
	options5 = {
		'url': 'google.com/'
	},
	options6 = {
		'url': 'http://google.com/'
	};

//invaild url
var options7 = {
	'url': 'http://testtesttest4564568.com'
};

//empty value
var optionsEmpty = {
	'url': ''
};

// test timeout
var options8 = {
		'url': 'http://www.google.com/',
		'timeout': 2000
	},
	options9 = {
		'url': 'http://www.google.com/',
		'timeout': ''
	},
	options10 = {
		'url': 'http://www.google.com/',
		'timeout': '2000'
	},
	options11 = {
		'url': 'http://www.google.com/',
		'timeout': 'sdsdds'
	};

// some bad urls
var options12 = {
		'url': 23233
	},
	options13 = {
		'url': '2323233'
	},
	options14 = {
		'url': 'this is a testt'
	};

//no url
var optionsNoUrl = { };

describe('GET OG', function () {
	this.timeout(3000); //shoudl wait atleast 3secs before failing
	it('Valid call og - url1', function (done) {
		app(options1, function (err, result) {
			expect(err).to.be(null);
			expect(result.success).to.be(true);
			done();
		});
	});
	it('Valid call og - url2', function (done) {
		app(options2, function (err, result) {
			expect(err).to.be(null);
			expect(result.success).to.be(true);
			done();
		});
	});
	it('Valid call og - url3', function (done) {
		app(options3, function (err, result) {
			expect(err).to.be(null);
			expect(result.success).to.be(true);
			done();
		});
	});
	it('Valid call og - url4', function (done) {
		app(options4, function (err, result) {
			expect(err).to.be(null);
			expect(result.success).to.be(true);
			done();
		});
	});
	it('Valid call og - url5', function (done) {
		app(options5, function (err, result) {
			expect(err).to.be(null);
			expect(result.success).to.be(true);
			done();
		});
	});
	it('Valid call og - url6', function (done) {
		app(options6, function (err, result) {
			expect(err).to.be(null);
			expect(result.success).to.be(true);
			done();
		});
	});
	it('Invalid call og - url7', function (done) {
		app(options7, function (err, result) {
			expect(result.success).to.be(false);
			done();
		});
	});
	it('Invalid get og - empty url', function (done) {
		app(optionsEmpty, function (err, result) {
			expect(result.err).to.be('Invalid URL');
			expect(result.success).to.be(false);
			done();
		});
	});
	it('Valid call og - url8', function (done) {
		app(options8, function (err, result) {
			expect(result.success).to.be(true);
			done();
		});
	});
	it('Valid call og - url9', function (done) {
		app(options9, function (err, result) {
			expect(result.success).to.be(true);
			done();
		});
	});
	it('Valid call og - url10', function (done) {
		app(options10, function (err, result) {
			expect(result.success).to.be(true);
			done();
		});
	});
	it('Valid call og - url11', function (done) {
		app(options11, function (err, result) {
			expect(result.success).to.be(true);
			done();
		});
	});
	it('Valid call og - url12', function (done) {
		app(options12, function (err, result) {
			expect(result.success).to.be(false);
			expect(result.err).to.be('Page Not Found');
			done();
		});
	});
	it('Valid call og - url13', function (done) {
		app(options13, function (err, result) {
			expect(result.success).to.be(false);
			expect(result.err).to.be('Page Not Found');
			done();
		});
	});
	it('Valid call og - url14', function (done) {
		app(options14, function (err, result) {
			expect(result.success).to.be(false);
			expect(result.err).to.be('Page Not Found');
			done();
		});
	});
	it('Invalid get og - no url', function (done) {
		app(optionsNoUrl, function (err, result) {
			expect(result.err).to.be('Invalid URL');
			expect(result.success).to.be(false);
			done();
		});
	});
});
<commit_msg>make the tests alittle more useful<commit_after>var app = require('../app'),
	expect = require('expect.js');

// test url - this has alot of OG info
var options1 = {
	'url': 'http://ogp.me/'
};

// test url formats
var	options2 = {
		'url': 'http://www.google.com/'
	},
	options3 = {
		'url': 'https://www.google.com/'
	},
	options4 = {
		'url': 'www.google.com/'
	},
	options5 = {
		'url': 'google.com/'
	},
	options6 = {
		'url': 'http://google.com/'
	};

// invaild url
var options7 = {
	'url': 'http://testtesttest4564568.com'
};

// empty value
var optionsNoUrl = {
	'url': ''
};

// no url
var optionsEmpty = { };

// test timeout
var options8 = {
		'url': 'http://www.google.com/',
		'timeout': 2000
	},
	options9 = {
		'url': 'http://www.google.com/',
		'timeout': ''
	},
	options10 = {
		'url': 'http://www.google.com/',
		'timeout': '2000'
	},
	options11 = {
		'url': 'http://www.google.com/',
		'timeout': 'sdsdds'
	};

// some bad urls
var options12 = {
		'url': 23233
	},
	options13 = {
		'url': '2323233'
	},
	options14 = {
		'url': 'this is a testt'
	};

describe('GET OG', function () {
	this.timeout(3000); // should wait at least three seconds before failing
	it('Valid Call - ogp.me should return open graph data', function (done) {
		app(options1, function (err, result) {
			expect(err).to.be(false);
			expect(result.success).to.be(true);
			expect(result.data.ogTitle).to.be('Open Graph protocol');
			expect(result.data.ogType).to.be('website');
			expect(result.data.ogUrl).to.be('http://ogp.me/');
			expect(result.data.ogDescription).to.be('The Open Graph protocol enables any web page to become a rich object in a social graph.');
			expect(result.data.ogImage.url).to.be('http://ogp.me/logo.png');
			expect(result.data.ogImage.width).to.be('300');
			expect(result.data.ogImage.height).to.be('300');
			expect(result.data.ogImage.type).to.be('image/png');
			done();
		});
	});
	it('Valid Call - http', function (done) {
		app(options2, function (err, result) {
			expect(err).to.be(false);
			expect(result.success).to.be(true);
			expect(result.data).to.be.empty();
			done();
		});
	});
	it('Valid Call - https', function (done) {
		app(options3, function (err, result) {
			expect(err).to.be(false);
			expect(result.success).to.be(true);
			expect(result.data).to.be.empty();
			done();
		});
	});
	it('Valid Call - no protocol', function (done) {
		app(options4, function (err, result) {
			expect(err).to.be(false);
			expect(result.success).to.be(true);
			expect(result.data).to.be.empty();
			done();
		});
	});
	it('Valid Call - no protocol and no wwww', function (done) {
		app(options5, function (err, result) {
			expect(err).to.be(false);
			expect(result.success).to.be(true);
			expect(result.data).to.be.empty();
			done();
		});
	});
	it('Valid Call - protocol with no wwww', function (done) {
		app(options6, function (err, result) {
			expect(err).to.be(false);
			expect(result.success).to.be(true);
			expect(result.data).to.be.empty();
			done();
		});
	});
	it('Invalid Call - fake page', function (done) {
		app(options7, function (err, result) {
			expect(err).to.be(true);
			expect(result.success).to.be(false);
			expect(result.err).to.be('Page Not Found');
			done();
		});
	});
	it('Invalid Call - empty url', function (done) {
		app(optionsNoUrl, function (err, result) {
			expect(err).to.be(true);
			expect(result.success).to.be(false);
			expect(result.err).to.be('Invalid URL');
			done();
		});
	});
	it('Invalid Call - empty options', function (done) {
		app(optionsEmpty, function (err, result) {
			expect(err).to.be(true);
			expect(result.err).to.be('Invalid URL');
			expect(result.success).to.be(false);
			done();
		});
	});
	it('Valid Call - timeout set to 2000', function (done) {
		app(options8, function (err, result) {
			expect(err).to.be(false);
			expect(result.success).to.be(true);
			expect(result.data).to.be.empty();
			done();
		});
	});
	it('Valid Call - timeout set to empty string', function (done) {
		app(options9, function (err, result) {
			expect(err).to.be(false);
			expect(result.success).to.be(true);
			expect(result.data).to.be.empty();
			done();
		});
	});
	it('Valid Call - timeout number is a string', function (done) {
		app(options10, function (err, result) {
			expect(err).to.be(false);
			expect(result.success).to.be(true);
			expect(result.data).to.be.empty();
			done();
		});
	});
	it('Valid Call - time is just a string of chars', function (done) {
		app(options11, function (err, result) {
			expect(err).to.be(false);
			expect(result.success).to.be(true);
			expect(result.data).to.be.empty();
			done();
		});
	});
	it('Invalid Call - url is just a number', function (done) {
		app(options12, function (err, result) {
			expect(err).to.be(true);
			expect(result.success).to.be(false);
			expect(result.err).to.be('Page Not Found');
			done();
		});
	});
	it('Invalid Call - url is a string of numbers', function (done) {
		app(options13, function (err, result) {
			expect(err).to.be(true);
			expect(result.success).to.be(false);
			expect(result.err).to.be('Page Not Found');
			done();
		});
	});
	it('Invalid Call - url is a string of words', function (done) {
		app(options14, function (err, result) {
			expect(err).to.be(true);
			expect(result.success).to.be(false);
			expect(result.err).to.be('Page Not Found');
			done();
		});
	});
});
<|endoftext|>


<commit_before>(function () {
  'use strict';

  var sUrl = '(\\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])';

  function isLink (text) {
    var rUrl = new RegExp(_.T('^{0}$')(sUrl), 'i');
    return rUrl.test(text);
  }

  function linkify (text) {
    var rUrl = new RegExp(sUrl, 'ig');
    return text.replace(rUrl, function(match) {
      return _.T("{0}")(match);
    });
  }

  // Binbox pastes
  $.register({
    rule: {
      host: /^(www\.)?([a-zA-Z0-9]+\.)?binbox\.io$/,
      path: /\/([a-zA-Z0-9]+)/,
      hash: /#([a-zA-Z0-9]+)/,
    },
    ready: function (m) {
      // If the hash is not here, it should ask the user for the password.
      // In fact, there is a security issue: if the user is not connected,
      // then it'll ask to fill a captcha, and the user will be able to access
      // the paste by only typing the captcha.

      var sjcl = $.window.sjcl;

      var paste_id = m.path[1];
      var paste_salt = m.hash[1];

      $.get(API_URL).then(function (pasteInfo) {
        pasteInfo = JSON.parse(pasteInfo);
        if (!pasteInfo.ok) {
          throw new _.AdsBypasserError("error when getting paste information");
        }

        // Decrypt paste
        var raw_paste = sjcl.decrypt(paste_salt, pasteInfo.paste.text);
        if (isLink(raw_paste)) {
          $.openLink(raw_paste);
          return;
        }

        // Create paste
        var elm = document.createElement('pre');
        elm.id = 'paste-text';
        elm.innerHTML = linkify(raw_paste);

        // Replace captcha with paste
        var frame = $('#paste-frame, #captcha-page');
        frame.parentNode.replaceChild(elm, frame);
      });
    },
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>Fix Binbox.io<commit_after>(function () {
  'use strict';

  var sUrl = '(\\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])';

  function isLink (text) {
    var rUrl = new RegExp(_.T('^{0}$')(sUrl), 'i');
    return rUrl.test(text);
  }

  function linkify (text) {
    var rUrl = new RegExp(sUrl, 'ig');
    return text.replace(rUrl, function(match) {
      return _.T("{0}")(match);
    });
  }

  // Binbox pastes
  $.register({
    rule: {
      host: /^(www\.)?([a-zA-Z0-9]+\.)?binbox\.io$/,
      path: /\/([a-zA-Z0-9]+)/,
      hash: /#([a-zA-Z0-9]+)/,
    },
    ready: function (m) {
      // If the hash is not here, it should ask the user for the password.
      // In fact, there is a security issue: if the user is not connected,
      // then it'll ask to fill a captcha, and the user will be able to access
      // the paste by only typing the captcha.

      var sjcl = $.window.sjcl;

      var paste_id = m.path[1];
      var paste_salt = m.hash[1];

      var API_URL = _.T('https://binbox.io/{0}.json')(paste_id);

      $.get(API_URL).then(function (pasteInfo) {
        pasteInfo = JSON.parse(pasteInfo);
        if (!pasteInfo.ok) {
          throw new _.AdsBypasserError("error when getting paste information");
        }

        // Decrypt paste
        var raw_paste = sjcl.decrypt(paste_salt, pasteInfo.paste.text);
        if (isLink(raw_paste)) {
          $.openLink(raw_paste);
          return;
        }

        // Create paste
        var elm = document.createElement('pre');
        elm.id = 'paste-text';
        elm.innerHTML = linkify(raw_paste);

        // Replace captcha with paste
        var frame = $('#paste-frame, #captcha-page');
        frame.parentNode.replaceChild(elm, frame);
      });
    },
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>// Class to present and edit keywords
var totalIndex = 0;

function Keyword(id, name) {
    var self = this;
    self.name = name;
    self.id = id;
    self.index = totalIndex++;
}

function indexOfSelectedKeyword() {
	var input = document.getElementById("keywordSelect");
	var keywordIndex = input.options[input.selectedIndex].value;
	return keywordIndex;
}

// Overall viewmodel for this screen, along with initial state
function KeywordViewModel() {
    var self = this;

    // Non-editable catalog data - would come from the server
    self.selectedKeywords = ko.observableArray([]);
    self.availableKeywords = ko.observableArray([]);

    // Operations
    self.addKeyword = function() {

    	var index = indexOfSelectedKeyword();
    	var keyword = self.existingKeywords[index];

        self.selectedKeywords.push(keyword);
        self.availableKeywords.remove(keyword);
    };
    self.removeKeyword = function(keyword) {
        self.availableKeywords.push(keyword);
        self.selectedKeywords.remove(keyword);
    };

    self.fetchKeywords = function() {
		$.ajax({
			url: '/PIMS/keywords/?type=student&id=1488913&content=json'
		}).done(function() {
			console.log( "success" );
		}).fail(function() {
		    alert( "error" );
		});
    };

    self.loadKeywords = function() {

        if (typeof moduleKeywords != 'undefined') {
        	self.existingKeywords = moduleKeywords;
        } else {
        	self.existingKeywords = [];
        }
        self.existingKeywords.push(new Keyword(456, "Mobile"));
        self.existingKeywords.push(new Keyword(456, "Desktop"));
        self.existingKeywords.push(new Keyword(456, "Web"));
        ko.utils.arrayPushAll(self.availableKeywords, self.existingKeywords);
    };

    self.fetchKeywords();
    self.loadKeywords();
}

ko.applyBindings(new KeywordViewModel());<commit_msg>add ajax handler<commit_after>// Class to present and edit keywords
var totalIndex = 0;

function Keyword(id, name) {
    var self = this;
    self.name = name;
    self.id = id;
    self.index = totalIndex++;
}

function indexOfSelectedKeyword() {
	var input = document.getElementById("keywordSelect");
	var keywordIndex = input.options[input.selectedIndex].value;
	return keywordIndex;
}

// Overall viewmodel for this screen, along with initial state
function KeywordViewModel() {
    var self = this;

    // Non-editable catalog data - would come from the server
    self.selectedKeywords = ko.observableArray([]);
    self.availableKeywords = ko.observableArray([]);

    // Operations
    self.addKeyword = function() {

    	var index = indexOfSelectedKeyword();
    	var keyword = self.existingKeywords[index];

        self.selectedKeywords.push(keyword);
        self.availableKeywords.remove(keyword);
    };

    self.removeKeyword = function(keyword) {
        self.availableKeywords.push(keyword);
        self.selectedKeywords.remove(keyword);
    };

    self.keywoardWithID = function(keywordID) {
    	var keyword = null;
    	this.existingKeywords.forEach(function(keywordIte) {
    	    if (keywordIte.id == keywordID) {
    	    	keyword = keywordIte;
    	    }
    	});
    	return keyword;
    };

    self.fetchKeywords = function() {
		$.ajax({
			url: '/PIMS/keywords/?type=student&id=1488913&content=json',
			success: this.loadKeywords,
			error: null
		});
    };

    self.handleFetchKeywords = function(json) {

    	console.log(json);

    	json.existingKeywords.forEach(function(keywordInfo) {
    	    console.log(keywordInfo);
    	    this.existingKeywords.push(new Keyword(keywordInfo[0], keywordInfo[1]));
    	});

    	json.selectedKeywords.forEach(function(keywordInfo) {
    	    console.log(keywordInfo);
    	    var keyword = this.keywoardWithID(keywordInfo[0]);
    	    if (keyword) {
        	    this.addKeyword(keyword);
    	    }
    	});
    };

    self.loadKeywords = function() {
        if (typeof moduleKeywords != 'undefined') {
        	self.existingKeywords = moduleKeywords;
        } else {
        	self.existingKeywords = [];
        }
        self.existingKeywords.push(new Keyword(456, "Mobile"));
        self.existingKeywords.push(new Keyword(456, "Desktop"));
        self.existingKeywords.push(new Keyword(456, "Web"));
        ko.utils.arrayPushAll(self.availableKeywords, self.existingKeywords);
    };

    self.fetchKeywords();
    self.loadKeywords();
}

ko.applyBindings(new KeywordViewModel());<|endoftext|>


<commit_before>define(function defineMapSelector(require) {
  'use strict';

  var map = {
    // http://www.w3.org/TR/html5/editing.html#sequential-focus-navigation-and-the-tabindex-attribute
    focusable: 'body,'
      // navigational elements
      // Namespace problems of [xlink:href] explained in http://stackoverflow.com/a/23047888/515124
      + 'a[href], svg a[*|href],'
      // TODO: investigate SVG's focusable attribute
      //   https://bugzilla.mozilla.org/show_bug.cgi?id=409404
      //   SVG-Tiny 1.2 defines the focusable attribute: http://www.w3.org/TR/SVGTiny12/interact.html#focusable-attr
      //   SVG 2 does not mention the focusable attribute: https://svgwg.org/svg2-draft/interact.html#Focus
      //   waiting for feedback from Doug - https://twitter.com/shepazu/status/526800017516814337
      // validity determined by dom/is-focusable.js
      // TODO: figure out why no browser makes area[href] focusable
      + 'area[href],'
      // validity determined by dom/is-focusable.js
      + 'input, select, textarea, button,'
      // browsing context containers
      + 'iframe, object, embed,'
      // interactive content
      // FIXME: Chrome does not understand the controls attribute, it will remove it from the DOM while parsing the document
      + 'audio[controls], video[controls], keygen,'
      // validity determined by dom/is-focusable.js
      + '[tabindex],'
      // editing hosts
      + '[contenteditable]',
  };

  return map;
});<commit_msg>adding feature detection for audio/video focus<commit_after>define(function defineMapSelector(require) {
  'use strict';

  function canFocusWithoutControls(nodeName, contentType) {
    // create dummy element to test focusability disabled fieldset
    var element = document.createElement(nodeName);
    // invalid video can trigger warning in console, data-uri to prevent HTTP request
    element.setAttribute('src', 'data:' + contentType + ';base64,' + nodeName + '-focus-test');
    // element needs to be part of the DOM to be focusable
    document.body.appendChild(element);
    // remember what had focus to restore after test
    var previousActiveElement = document.activeElement;
    // test if the element with invalid tabindex can be focused
    element.focus();
    var allowsFocus = document.activeElement === element;
    // restore focus to what it was before test and cleanup
    previousActiveElement.focus();
    document.body.removeChild(element);
    return allowsFocus;
  }

  var canFocusVideoWithoutControls = canFocusWithoutControls('video', 'video/mp4');
  var canFocusAudioWithoutControls = canFocusWithoutControls('video', 'audio/mp3');

  var map = {
    // http://www.w3.org/TR/html5/editing.html#sequential-focus-navigation-and-the-tabindex-attribute
    focusable: 'body,'
      // navigational elements
      // Namespace problems of [xlink:href] explained in http://stackoverflow.com/a/23047888/515124
      + 'a[href], svg a[*|href],'
      // TODO: investigate SVG's focusable attribute
      //   https://bugzilla.mozilla.org/show_bug.cgi?id=409404
      //   SVG-Tiny 1.2 defines the focusable attribute: http://www.w3.org/TR/SVGTiny12/interact.html#focusable-attr
      //   SVG 2 does not mention the focusable attribute: https://svgwg.org/svg2-draft/interact.html#Focus
      //   waiting for feedback from Doug - https://twitter.com/shepazu/status/526800017516814337
      // validity determined by dom/is-focusable.js
      // TODO: figure out why no browser makes area[href] focusable
      + 'area[href],'
      // validity determined by dom/is-focusable.js
      + 'input, select, textarea, button,'
      // browsing context containers
      + 'iframe, object, embed,'
      // interactive content
      + 'keygen,'
      + (canFocusAudioWithoutControls ? 'audio,' : 'audio[controls],')
      + (canFocusVideoWithoutControls ? 'video,' : 'video[controls],')
      // validity determined by dom/is-focusable.js
      + '[tabindex],'
      // editing hosts
      + '[contenteditable]',
  };

  return map;
});<|endoftext|>


<commit_before>/*********************************************************
                    jQuery 交互式报表(IRR)格式初始化/保存/加载功能
                    Create Date:2016.7.13
                    Create By:bird
                    Last Update Date:2016.7.13
                    Last Update By:bird
                          修改日志
           2016.7.13   创建文件,并新增插件配置说明
		   2016.8.11   整合Spring框架进行的修改:和数据库栏位相关的变量统一大写。另外，插件js名称添加irr关键字。 by sam.t
*********************************************************/
(function($) {
	/****属性设置****/
	options={

	}

	/**************************
        	默认属性
	**************************/
	var defaults = {
		userid:'#USER_ID',     			/****用户id值存放标签id****/
		interactcode:'#INTERACT_CODE',  /****报表格式code值存放标签id****/
		orderpara:'#ORDER_BY',        /****排序参数值存放标签id****/
		headerid:'#HEADER_ID',      	/****报表格式头id值存放标签id****/
		pageframe:'table',
		pagesize:'#page_size',          /****每页显示行数值存放标签id****/
		setframe:'#setting',			/****设置框id****/
		tableid:'#tb',					/****表格id****/
		refresh:'#refresh',				/****刷新按钮id****/
		url:'irr/getDefaultIrr.do'	   /****ajax get地址****/
	};

	/****继承默认属性****/
    var options = $.extend({}, defaults, options);
    var tablename=$('#'+options.pageframe).attr('data-table');
    var autoquery=$('#'+options.pageframe+' input[data-type="autoquery"]').val();

    console.log('Start init');
    user_id=$(options.userid).val();
    interact_code=$(options.interactcode).val();
    param='USER_ID='+user_id+'&INTERACT_CODE='+interact_code;
    $.ajax({
    	type:'post',
		data:param,
		url:options.url,
		dataType:'json',
		success: function (data) {
			if(data.EXISTS=='Y'){
				$('#'+options.pageframe+' input[data-type="orderby"]').val(data.rows.HEADER[0].ORDER_BY);
				$(options.headerid).val(data.rows.HEADER[0].HEADER_ID);
				$('#'+options.pageframe+' input[data-type="pagesize"]').val(data.rows.HEADER[0].PAGE_SIZE);
				$(options.setframe+' i[data-value]').css('visibility','hidden');
		        $(options.setframe+' i[data-value="'+data.rows.HEADER[0].PAGE_SIZE+'"]').css('visibility','visible');
		        $('table[data-table="'+tablename+'"] th').css('display','none');
		        $('table[data-table="'+tablename+'"] td').css('display','none');
		        linenum=$('table[data-table="'+tablename+'"] tr').length-1;
            	setnum=data.rows.SEQ.length;
            	data.rows.SEQ.reverse();
            	for(i=0;i<setnum;i++){
					if(data.rows.SEQ[i].COLUMN_NAME!=null){
						row=$('.'+data.rows.SEQ[i].COLUMN_NAME);
						rowindex=row.index();
						$('.'+data.rows.SEQ[i].COLUMN_NAME).css('display','');
						if(rowindex!=0){
							$('table[data-table="'+tablename+'"] th:eq('+rowindex+')').insertBefore($('table[data-table="'+tablename+'"] th:eq(0)'));
							for(j=0;j<=linenum;j++){
								$('td:eq('+rowindex+')',$('table[data-table="'+tablename+'"] tr:eq('+j+')')).insertBefore($('td:eq(0)',$('table[data-table="'+tablename+'"] tr:eq('+j+')')));
     	            		}
						}
						else{
							$('table[data-table="'+tablename+'"] th:eq('+rowindex+')').insertBefore($('table[data-table="'+tablename+'"] th:eq(1)'));
							for(j=0;j<=linenum;j++){
								$('td:eq('+rowindex+')',$('table[data-table="'+tablename+'"] tr:eq('+j+')')).insertBefore($('td:eq(1)',$('table[data-table="'+tablename+'"] tr:eq('+j+')')));
     	            		}
						}
					}
				}
            	if(autoquery=='Y'){
            		$(options.refresh).click();
            	}else{
            		/**modify by bird 2016-12-6**/
            		$('td[data-column="db"]',$('table[data-table="'+tablename+'"] tr:eq(1)')).html('');
    				blank_tr=$('tr:eq(1)',$('table[data-table="'+tablename+'"]'));
    				$('td',$('table[data-table="'+tablename+'"]')).parent().remove();
    				for(j=1;j<=5;j++){
    					$('tr:eq(0)',$('table[data-table="'+tablename+'"]')).parent().append(blank_tr.clone());
    				}
    				/**modify by bird 2016-12-6**/
            		$('#'+options.pageframe+' i[data-pagetype="prevpage"]').css('display','none');
					$('#'+options.pageframe+' i[data-pagetype="firstpage"]').css('display','none');
					$('#'+options.pageframe+' i[data-pagetype="lastpage"]').css('display','none');
					$('#'+options.pageframe+' i[data-pagetype="nextpage"]').css('display','none');
            	}
			}
			else{
				if(autoquery=='Y'){
            		$(options.refresh).click();
            	}else{
            		/**modify by bird 2016-12-6**/
            		$('td[data-column="db"]',$('table[data-table="'+tablename+'"] tr:eq(1)')).html('');
    				blank_tr=$('tr:eq(1)',$('table[data-table="'+tablename+'"]'));
    				$('td',$('table[data-table="'+tablename+'"]')).parent().remove();
    				for(j=1;j<=5;j++){
    					$('tr:eq(0)',$('table[data-table="'+tablename+'"]')).parent().append(blank_tr.clone());
    				}
    				/**modify by bird 2016-12-6**/
            		$('#'+options.pageframe+' i[data-pagetype="prevpage"]').css('display','none');
					$('#'+options.pageframe+' i[data-pagetype="firstpage"]').css('display','none');
					$('#'+options.pageframe+' i[data-pagetype="lastpage"]').css('display','none');
					$('#'+options.pageframe+' i[data-pagetype="nextpage"]').css('display','none');
            	}
			}
		},
		error: function () {
			alert("获取Json数据失败");
		}
	});

    /******************listener start***********************
					监听data-config属性
				暂时只设置对<button>  两种标签的绑定
			如需对更多标签进行绑定，请在listener区域绑定新的监听标签
    *********************************************************/
    $.fn.configListener = function(){
    	/****绑定标签****/
		$('a[data-config]').on('click', function(e) {
			/****阻止标签默认的点击事件（超链接跳转)****/
			e.preventDefault();
			$(this).config($(this).data());
		});
		/****绑定<button>标签****/
		$('button[data-config]').on('click', function() {
			$(this).config($(this).data());
		});
    }
    /******************listener end***********************/

    /****执行监听函数****/
    $().configListener();

    $.fn.config = function(options) {
		/*********************************************
                           设置默认属性
        *********************************************/
		var defaults={
			userid:'#USER_ID',     			/****用户id值存放标签id****/
			interactcode:'#INTERACT_CODE',  /****报表格式code值存放标签id****/
			interactname:'#USER_INTERACT_NAME',	/****报表格式name值存放标签id****/
			interactdesc:'#DESCRIPTION',	/****报表格式desc值存放标签id****/
			orderpara:'#ORDER_BY',        /****排序参数值存放标签id****/
			headerid:'#HEADER_ID',      	/****报表格式头id值存放标签id****/
			pagesize:'#page_size',          /****每页显示行数值存放标签id****/
			tableid:'#tb',					/****表格id****/
			configid:'#config',				/****个人配置框id****/
			refresh:'#refresh',				/****刷新按钮id****/
			setframe:'#setting',			/****设置框id****/
			initurl:'irr/getIrrHead.do',	    /****获取用户报表格式信息url****/
			saveurl:'irr/saveIrr.do',		/****保存用户报表格式信息url****/
			loadurl:'irr/getIrr.do',			/****加载用户报表格式信息url****/
			publicflag:'#PUBLIC_FLAG',		/****共享标志框id****/
			defaultflag:'#DEFAULT_FLAG',	/****默认标志框id****/
			autoflag:'#AUTOQUERY_FLAG'		/****自动查询标志框id****/
		}
		/****继承默认属性****/
        var options = $.extend({}, defaults, options);

        return this.each(function() {
        	configType=options.config;
        	interact_code=$(options.interactcode).val();
    		user_id=$(options.userid).val();
    		header_id=$(options.headerid).val();
        	if(configType=='init'){
        		$(options.setframe).css('visibility','hidden');
        		$(options.interactname).val('');
        		$(options.interactdesc).val('');
        		param='INTERACT_CODE='+interact_code+'&USER_ID='+user_id;
        		$.ajax({
    				type:'post',
    				data:param,
    				url:options.initurl,
    				dataType:'json',
    				success: function (data) {
    					if(data.EXISTS=='Y'){
    						$(options.configid+' select').html('');
        					loadingindex=data.rows.length;
        					for(i=0;i<loadingindex;i++){
        						name=data.rows[i].USER_INTERACT_NAME;
        						value=data.rows[i].HEADER_ID;
        						$(options.configid+' select').append('<option value="'+value+'" >'+name+'</option>');
        					}
        					$(options.configid+' option[value="'+header_id+'"]').prop('selected',true);
    					}else{
    					    console.log("查无数据");
    					}
    				},error: function(){
    				    alert("获取json数据失败");
    				}
    			});
        	}
        	else if(configType=='save'){
        		user_interact_name=$(options.interactname).val();
        		order_by=$(options.orderpara).val();
        		page_size=$(options.pagesize).val();
        		if(user_interact_name==''){
        			alert('自定义名称不能为空');
        			return;
        		}
        		description=$(options.interactdesc).val();
        		seq = new Array();
        		count=$(options.tableid+' th').length-1;/****获取总列数（排除最后一列的空列）****/
         	    for(i=0;i<count;i++){/****遍历标题列（除最后一列空列外）****/
         	        if($(options.tableid+' th:eq('+i+')').css('display')!='none'){
    				    seq[i]=$(options.tableid+' th:eq('+i+')').attr('class');
         	        }
         	    }
         	    //seq.reverse();
        		if($(options.publicflag).prop("checked")==true){
        			public_flag='Y';
        		}
        		else{
        			public_flag='N';
        		}
        		if($(options.defaultflag).prop("checked")==true){
        			default_flag='Y';
        		}
        		else{
        			default_flag='N';
        		}
        		if($(options.autoflag).prop("checked")==true){
        			autoquery_flag='Y';
        		}
        		else{
        			autoquery_flag='N';
        		}
        		param='INTERACT_CODE='+interact_code+'&USER_ID='+user_id+'&USER_INTERACT_NAME='+user_interact_name+'&ORDER_BY='+order_by+'&PAGE_SIZE='+page_size+'&DESCRIPTION='+description+'&SEQ='+seq+'&PUBLIC_FLAG='+public_flag+'&DEFAULT_FLAG='+default_flag+'&AUTOQUERY_FLAG='+autoquery_flag;
        		$.ajax({
    				type:'post',
    				data:param,
    				url:options.saveurl,
    				dataType:'json',
    				success: function (data) {
    					if(data.retcode!=0){
    						alert("保存处理失败！错误信息:"+data.errbuf);
    					}else{
    						alert("保存成功");
        					$(options.configid+' .close-reveal-modal').click();
    					}
    				},error: function(){
    				    alert("save出现未知错误");
    				}
    			});
        	}
        	else if(configType=='load'){
        		header_id=$(options.configid+' option:selected').val()
        		if(header_id=='blank'){
        			alert('载入模板不能为空，请重新选择！');
        			return;
        		}
                param='HEADER_ID='+header_id;
                $.ajax({
    				type:'post',
    				data:param,
    				url:options.loadurl,
    				dataType:'json',
    				success: function (data) {
    				    if(data.EXISTS=='Y'){
    				        $(options.orderpara).val(data.rows.HEADER[0].ORDER_BY);
    				        $(options.headerid).val(data.rows.HEADER[0].HEADER_ID);
    				        $(options.pagesize).val(data.rows.HEADER[0].PAGE_SIZE);
    				        $(options.setframe+' i[data-value]').css('visibility','hidden');
    				        $(options.setframe+' i[data-value="'+data.rows.HEADER[0].PAGE_SIZE+'"]').css('visibility','visible');
    				        $(options.tableid+' th').css('display','none');
                			$(options.tableid+' td').css('display','none');
                			linenum=$(options.tableid+' tr').length-1;
                			setnum=data.rows.SEQ.length;
                			data.rows.SEQ.reverse();
                			for(i=0;i<setnum;i++){
    							if(data.rows.SEQ[i].COLUMN_NAME!=null){
    								row=$('.'+data.rows.SEQ[i].COLUMN_NAME);
    								rowindex=row.index();
    								$('.'+data.rows.SEQ[i].COLUMN_NAME).css('display','');
    								if(rowindex!=0){
    									$(options.tableid+' th:eq('+rowindex+')').insertBefore($(options.tableid+' th:eq(0)'));
    									for(j=0;j<=linenum;j++){
         	                				$('td:eq('+rowindex+')',$(options.tableid+' tr:eq('+j+')')).insertBefore($('td:eq(0)',$(options.tableid+' tr:eq('+j+')')));
         	            				}
    								}
    								else{
    									$(options.tableid+' th:eq('+rowindex+')').insertBefore($(options.tableid+' th:eq(1)'));
    									for(j=0;j<=linenum;j++){
         	                				$('td:eq('+rowindex+')',$(options.tableid+' tr:eq('+j+')')).insertBefore($('td:eq(1)',$(options.tableid+' tr:eq('+j+')')));
         	            				}
    								}
    							}
    				    	}
    				    	$(options.refresh).click();
    				    	alert("加载成功");
        					$(options.configid+' .close-reveal-modal').click();
    				    }
    				    else{

    				    }
    				},
    				error: function () {
    					alert("获取Json数据失败");
    				}
    			});
        	}
        	else{
        		alert('获取json数据失败，请联系IT部门');
        	}
		});
	}
})(jQuery);<commit_msg>修改当Autoquery为N时，自动弹出条件查询框<commit_after>/*********************************************************
                    jQuery 交互式报表(IRR)格式初始化/保存/加载功能
                    Create Date:2016.7.13
                    Create By:bird
                    Last Update Date:2016.7.13
                    Last Update By:bird
                          修改日志
           2016.7.13   创建文件,并新增插件配置说明
		   2016.8.11   整合Spring框架进行的修改:和数据库栏位相关的变量统一大写。另外，插件js名称添加irr关键字。 by sam.t
*********************************************************/
(function($) {
	/****属性设置****/
	options={

	}

	/**************************
        	默认属性
	**************************/
	var defaults = {
		userid:'#USER_ID',     			/****用户id值存放标签id****/
		interactcode:'#INTERACT_CODE',  /****报表格式code值存放标签id****/
		orderpara:'#ORDER_BY',        /****排序参数值存放标签id****/
		headerid:'#HEADER_ID',      	/****报表格式头id值存放标签id****/
		pageframe:'table',
		pagesize:'#page_size',          /****每页显示行数值存放标签id****/
		setframe:'#setting',			/****设置框id****/
		tableid:'#tb',					/****表格id****/
		refresh:'#refresh',				/****刷新按钮id****/
		url:'irr/getDefaultIrr.do'	   /****ajax get地址****/
	};

	/****继承默认属性****/
    var options = $.extend({}, defaults, options);
    var tablename=$('#'+options.pageframe).attr('data-table');
    var autoquery=$('#'+options.pageframe+' input[data-type="autoquery"]').val();

    console.log('Start init');
    user_id=$(options.userid).val();
    interact_code=$(options.interactcode).val();
    param='USER_ID='+user_id+'&INTERACT_CODE='+interact_code;
    $.ajax({
    	type:'post',
		data:param,
		url:options.url,
		dataType:'json',
		success: function (data) {
			if(data.EXISTS=='Y'){
				$('#'+options.pageframe+' input[data-type="orderby"]').val(data.rows.HEADER[0].ORDER_BY);
				$(options.headerid).val(data.rows.HEADER[0].HEADER_ID);
				$('#'+options.pageframe+' input[data-type="pagesize"]').val(data.rows.HEADER[0].PAGE_SIZE);
				$(options.setframe+' i[data-value]').css('visibility','hidden');
		        $(options.setframe+' i[data-value="'+data.rows.HEADER[0].PAGE_SIZE+'"]').css('visibility','visible');
		        $('table[data-table="'+tablename+'"] th').css('display','none');
		        $('table[data-table="'+tablename+'"] td').css('display','none');
		        linenum=$('table[data-table="'+tablename+'"] tr').length-1;
            	setnum=data.rows.SEQ.length;
            	data.rows.SEQ.reverse();
            	for(i=0;i<setnum;i++){
					if(data.rows.SEQ[i].COLUMN_NAME!=null){
						row=$('.'+data.rows.SEQ[i].COLUMN_NAME);
						rowindex=row.index();
						$('.'+data.rows.SEQ[i].COLUMN_NAME).css('display','');
						if(rowindex!=0){
							$('table[data-table="'+tablename+'"] th:eq('+rowindex+')').insertBefore($('table[data-table="'+tablename+'"] th:eq(0)'));
							for(j=0;j<=linenum;j++){
								$('td:eq('+rowindex+')',$('table[data-table="'+tablename+'"] tr:eq('+j+')')).insertBefore($('td:eq(0)',$('table[data-table="'+tablename+'"] tr:eq('+j+')')));
     	            		}
						}
						else{
							$('table[data-table="'+tablename+'"] th:eq('+rowindex+')').insertBefore($('table[data-table="'+tablename+'"] th:eq(1)'));
							for(j=0;j<=linenum;j++){
								$('td:eq('+rowindex+')',$('table[data-table="'+tablename+'"] tr:eq('+j+')')).insertBefore($('td:eq(1)',$('table[data-table="'+tablename+'"] tr:eq('+j+')')));
     	            		}
						}
					}
				}
            	if(autoquery=='Y'){
            		$(options.refresh).click();
            	}else{
            		/**modify by bird 2016-12-6**/
            		$('td[data-column="db"]',$('table[data-table="'+tablename+'"] tr:eq(1)')).html('');
    				blank_tr=$('tr:eq(1)',$('table[data-table="'+tablename+'"]'));
    				$('td',$('table[data-table="'+tablename+'"]')).parent().remove();
    				for(j=1;j<=5;j++){
    					$('tr:eq(0)',$('table[data-table="'+tablename+'"]')).parent().append(blank_tr.clone());
    				}
    				/**modify by bird 2016-12-6**/
            		$('#'+options.pageframe+' i[data-pagetype="prevpage"]').css('display','none');
					$('#'+options.pageframe+' i[data-pagetype="firstpage"]').css('display','none');
					$('#'+options.pageframe+' i[data-pagetype="lastpage"]').css('display','none');
					$('#'+options.pageframe+' i[data-pagetype="nextpage"]').css('display','none');
					$('#'+options.pageframe+' i[data-reveal-id="query"]').click();
            	}
			}
			else{
				if(autoquery=='Y'){
            		$(options.refresh).click();
            	}else{
            		/**modify by bird 2016-12-6**/
            		$('td[data-column="db"]',$('table[data-table="'+tablename+'"] tr:eq(1)')).html('');
    				blank_tr=$('tr:eq(1)',$('table[data-table="'+tablename+'"]'));
    				$('td',$('table[data-table="'+tablename+'"]')).parent().remove();
    				for(j=1;j<=5;j++){
    					$('tr:eq(0)',$('table[data-table="'+tablename+'"]')).parent().append(blank_tr.clone());
    				}
    				/**modify by bird 2016-12-6**/
            		$('#'+options.pageframe+' i[data-pagetype="prevpage"]').css('display','none');
					$('#'+options.pageframe+' i[data-pagetype="firstpage"]').css('display','none');
					$('#'+options.pageframe+' i[data-pagetype="lastpage"]').css('display','none');
					$('#'+options.pageframe+' i[data-pagetype="nextpage"]').css('display','none');
					$('#'+options.pageframe+' i[data-reveal-id="query"]').click();
            	}
			}
		},
		error: function () {
			alert("获取Json数据失败");
		}
	});

    /******************listener start***********************
					监听data-config属性
				暂时只设置对<button>  两种标签的绑定
			如需对更多标签进行绑定，请在listener区域绑定新的监听标签
    *********************************************************/
    $.fn.configListener = function(){
    	/****绑定标签****/
		$('a[data-config]').on('click', function(e) {
			/****阻止标签默认的点击事件（超链接跳转)****/
			e.preventDefault();
			$(this).config($(this).data());
		});
		/****绑定<button>标签****/
		$('button[data-config]').on('click', function() {
			$(this).config($(this).data());
		});
    }
    /******************listener end***********************/

    /****执行监听函数****/
    $().configListener();

    $.fn.config = function(options) {
		/*********************************************
                           设置默认属性
        *********************************************/
		var defaults={
			userid:'#USER_ID',     			/****用户id值存放标签id****/
			interactcode:'#INTERACT_CODE',  /****报表格式code值存放标签id****/
			interactname:'#USER_INTERACT_NAME',	/****报表格式name值存放标签id****/
			interactdesc:'#DESCRIPTION',	/****报表格式desc值存放标签id****/
			orderpara:'#ORDER_BY',        /****排序参数值存放标签id****/
			headerid:'#HEADER_ID',      	/****报表格式头id值存放标签id****/
			pagesize:'#page_size',          /****每页显示行数值存放标签id****/
			tableid:'#tb',					/****表格id****/
			configid:'#config',				/****个人配置框id****/
			refresh:'#refresh',				/****刷新按钮id****/
			setframe:'#setting',			/****设置框id****/
			initurl:'irr/getIrrHead.do',	    /****获取用户报表格式信息url****/
			saveurl:'irr/saveIrr.do',		/****保存用户报表格式信息url****/
			loadurl:'irr/getIrr.do',			/****加载用户报表格式信息url****/
			publicflag:'#PUBLIC_FLAG',		/****共享标志框id****/
			defaultflag:'#DEFAULT_FLAG',	/****默认标志框id****/
			autoflag:'#AUTOQUERY_FLAG'		/****自动查询标志框id****/
		}
		/****继承默认属性****/
        var options = $.extend({}, defaults, options);

        return this.each(function() {
        	configType=options.config;
        	interact_code=$(options.interactcode).val();
    		user_id=$(options.userid).val();
    		header_id=$(options.headerid).val();
        	if(configType=='init'){
        		$(options.setframe).css('visibility','hidden');
        		$(options.interactname).val('');
        		$(options.interactdesc).val('');
        		param='INTERACT_CODE='+interact_code+'&USER_ID='+user_id;
        		$.ajax({
    				type:'post',
    				data:param,
    				url:options.initurl,
    				dataType:'json',
    				success: function (data) {
    					if(data.EXISTS=='Y'){
    						$(options.configid+' select').html('');
        					loadingindex=data.rows.length;
        					for(i=0;i<loadingindex;i++){
        						name=data.rows[i].USER_INTERACT_NAME;
        						value=data.rows[i].HEADER_ID;
        						$(options.configid+' select').append('<option value="'+value+'" >'+name+'</option>');
        					}
        					$(options.configid+' option[value="'+header_id+'"]').prop('selected',true);
    					}else{
    					    console.log("查无数据");
    					}
    				},error: function(){
    				    alert("获取json数据失败");
    				}
    			});
        	}
        	else if(configType=='save'){
        		user_interact_name=$(options.interactname).val();
        		order_by=$(options.orderpara).val();
        		page_size=$(options.pagesize).val();
        		if(user_interact_name==''){
        			alert('自定义名称不能为空');
        			return;
        		}
        		description=$(options.interactdesc).val();
        		seq = new Array();
        		count=$(options.tableid+' th').length-1;/****获取总列数（排除最后一列的空列）****/
         	    for(i=0;i<count;i++){/****遍历标题列（除最后一列空列外）****/
         	        if($(options.tableid+' th:eq('+i+')').css('display')!='none'){
    				    seq[i]=$(options.tableid+' th:eq('+i+')').attr('class');
         	        }
         	    }
         	    //seq.reverse();
        		if($(options.publicflag).prop("checked")==true){
        			public_flag='Y';
        		}
        		else{
        			public_flag='N';
        		}
        		if($(options.defaultflag).prop("checked")==true){
        			default_flag='Y';
        		}
        		else{
        			default_flag='N';
        		}
        		if($(options.autoflag).prop("checked")==true){
        			autoquery_flag='Y';
        		}
        		else{
        			autoquery_flag='N';
        		}
        		param='INTERACT_CODE='+interact_code+'&USER_ID='+user_id+'&USER_INTERACT_NAME='+user_interact_name+'&ORDER_BY='+order_by+'&PAGE_SIZE='+page_size+'&DESCRIPTION='+description+'&SEQ='+seq+'&PUBLIC_FLAG='+public_flag+'&DEFAULT_FLAG='+default_flag+'&AUTOQUERY_FLAG='+autoquery_flag;
        		$.ajax({
    				type:'post',
    				data:param,
    				url:options.saveurl,
    				dataType:'json',
    				success: function (data) {
    					if(data.retcode!=0){
    						alert("保存处理失败！错误信息:"+data.errbuf);
    					}else{
    						alert("保存成功");
        					$(options.configid+' .close-reveal-modal').click();
    					}
    				},error: function(){
    				    alert("save出现未知错误");
    				}
    			});
        	}
        	else if(configType=='load'){
        		header_id=$(options.configid+' option:selected').val()
        		if(header_id=='blank'){
        			alert('载入模板不能为空，请重新选择！');
        			return;
        		}
                param='HEADER_ID='+header_id;
                $.ajax({
    				type:'post',
    				data:param,
    				url:options.loadurl,
    				dataType:'json',
    				success: function (data) {
    				    if(data.EXISTS=='Y'){
    				        $(options.orderpara).val(data.rows.HEADER[0].ORDER_BY);
    				        $(options.headerid).val(data.rows.HEADER[0].HEADER_ID);
    				        $(options.pagesize).val(data.rows.HEADER[0].PAGE_SIZE);
    				        $(options.setframe+' i[data-value]').css('visibility','hidden');
    				        $(options.setframe+' i[data-value="'+data.rows.HEADER[0].PAGE_SIZE+'"]').css('visibility','visible');
    				        $(options.tableid+' th').css('display','none');
                			$(options.tableid+' td').css('display','none');
                			linenum=$(options.tableid+' tr').length-1;
                			setnum=data.rows.SEQ.length;
                			data.rows.SEQ.reverse();
                			for(i=0;i<setnum;i++){
    							if(data.rows.SEQ[i].COLUMN_NAME!=null){
    								row=$('.'+data.rows.SEQ[i].COLUMN_NAME);
    								rowindex=row.index();
    								$('.'+data.rows.SEQ[i].COLUMN_NAME).css('display','');
    								if(rowindex!=0){
    									$(options.tableid+' th:eq('+rowindex+')').insertBefore($(options.tableid+' th:eq(0)'));
    									for(j=0;j<=linenum;j++){
         	                				$('td:eq('+rowindex+')',$(options.tableid+' tr:eq('+j+')')).insertBefore($('td:eq(0)',$(options.tableid+' tr:eq('+j+')')));
         	            				}
    								}
    								else{
    									$(options.tableid+' th:eq('+rowindex+')').insertBefore($(options.tableid+' th:eq(1)'));
    									for(j=0;j<=linenum;j++){
         	                				$('td:eq('+rowindex+')',$(options.tableid+' tr:eq('+j+')')).insertBefore($('td:eq(1)',$(options.tableid+' tr:eq('+j+')')));
         	            				}
    								}
    							}
    				    	}
    				    	$(options.refresh).click();
    				    	alert("加载成功");
        					$(options.configid+' .close-reveal-modal').click();
    				    }
    				    else{

    				    }
    				},
    				error: function () {
    					alert("获取Json数据失败");
    				}
    			});
        	}
        	else{
        		alert('获取json数据失败，请联系IT部门');
        	}
		});
	}
})(jQuery);<|endoftext|>


<commit_before>/*************************************************
 * Copyright (c) 2017  Ansible, Inc.
 *
 * All Rights Reserved
 *************************************************/

 export default ['i18n', function(i18n) {
     return {
        name: 'nested_groups',
        iterator: 'nested_group',
        editTitle: '{{ inventory.name }}',
        well: true,
        wellOverride: true,
        index: false,
        hover: true,
        multiSelect: true,
        trackBy: 'nested_group.id',
        basePath:  'api/v2/inventories/{{$stateParams.inventory_id}}/root_groups/',

        fields: {
            failed_hosts: {
                label: '',
                nosort: true,
                mode: 'all',
                iconOnly: true,
                awToolTip: "{{ nested_group.hosts_status_tip }}",
                dataPlacement: "top",
                icon: "{{ 'fa icon-job-' + nested_group.hosts_status_class }}",
                columnClass: 'status-column List-staticColumn--smallStatus'
            },
            name: {
                label: i18n._('Groups'),
                key: true,
                ngClick: "goToGroupGroups(nested_group.id)",
                columnClass: 'col-lg-6 col-md-6 col-sm-6 col-xs-6',
                class: 'InventoryManage-breakWord',
            }
        },

        actions: {
            refresh: {
                mode: 'all',
                awToolTip: i18n._("Refresh the page"),
                ngClick: "refreshGroups()",
                ngShow: "socketStatus == 'error'",
                actionClass: 'btn List-buttonDefault',
                buttonContent: i18n._('REFRESH')
            },
            launch: {
                mode: 'all',
                ngDisabled: '!groupsSelected',
                ngClick: 'setAdhocPattern()',
                awToolTip: i18n._("Select an inventory source by clicking the check box beside it. The inventory source can be a single group or host, a selection of multiple hosts, or a selection of multiple groups."),
                dataPlacement: 'top',
                actionClass: 'btn List-buttonDefault',
                buttonContent: i18n._('RUN COMMANDS'),
                showTipWhenDisabled: true,
                tooltipInnerClass: "Tooltip-wide",
                ngShow: 'canAdhoc'
                // TODO: set up a tip watcher and change text based on when
                // things are selected/not selected.  This is started and
                // commented out in the inventory controller within the watchers.
                // awToolTip: "{{ adhocButtonTipContents }}",
                // dataTipWatch: "adhocButtonTipContents"
            },
            add: {
                mode: 'all',
                type: 'buttonDropdown',
                awToolTip: i18n._("Add a group"),
                actionClass: 'btn List-buttonSubmit',
                buttonContent: '+ ' + i18n._('ADD'),
                ngShow: 'canAdd',
                dataPlacement: "top",
                options: [
                    {
                        optionContent: i18n._('Existing Group'),
                        optionSref: '.associate',
                        ngShow: 'canAdd'
                    },
                    {
                        optionContent: i18n._('New Group'),
                        optionSref: '.add',
                        ngShow: 'canAdd'
                    }
                ],
            }
        },

        fieldActions: {

            columnClass: 'col-lg-6 col-md-6 col-sm-6 col-xs-6 text-right',

            edit: {
                mode: 'all',
                ngClick: "editGroup(nested_group.id)",
                awToolTip: i18n._('Edit group'),
                dataPlacement: "top",
                ngShow: "nested_group.summary_fields.user_capabilities.edit"
            },
            view: {
                mode: 'all',
                ngClick: "editGroup(nested_group.id)",
                awToolTip: i18n._('View group'),
                dataPlacement: "top",
                ngShow: "!nested_group.summary_fields.user_capabilities.edit"
            },
            "delete": {
                mode: 'all',
                ngClick: "disassociateGroup(nested_group)",
                awToolTip: i18n._('Disassociate group'),
                iconClass: 'fa fa-times',
                dataPlacement: "top",
                ngShow: "nested_group.summary_fields.user_capabilities.delete"
            }
        }
    };
}];
<commit_msg>Fixed nested groups pagination<commit_after>/*************************************************
 * Copyright (c) 2017  Ansible, Inc.
 *
 * All Rights Reserved
 *************************************************/

 export default ['i18n', function(i18n) {
     return {
        name: 'nested_groups',
        iterator: 'nested_group',
        editTitle: '{{ inventory.name }}',
        well: true,
        wellOverride: true,
        index: false,
        hover: true,
        multiSelect: true,
        trackBy: 'nested_group.id',
        basePath:  '/api/v2/groups/{{$stateParams.group_id}}/children',

        fields: {
            failed_hosts: {
                label: '',
                nosort: true,
                mode: 'all',
                iconOnly: true,
                awToolTip: "{{ nested_group.hosts_status_tip }}",
                dataPlacement: "top",
                icon: "{{ 'fa icon-job-' + nested_group.hosts_status_class }}",
                columnClass: 'status-column List-staticColumn--smallStatus'
            },
            name: {
                label: i18n._('Groups'),
                key: true,
                ngClick: "goToGroupGroups(nested_group.id)",
                columnClass: 'col-lg-6 col-md-6 col-sm-6 col-xs-6',
                class: 'InventoryManage-breakWord',
            }
        },

        actions: {
            refresh: {
                mode: 'all',
                awToolTip: i18n._("Refresh the page"),
                ngClick: "refreshGroups()",
                ngShow: "socketStatus == 'error'",
                actionClass: 'btn List-buttonDefault',
                buttonContent: i18n._('REFRESH')
            },
            launch: {
                mode: 'all',
                ngDisabled: '!groupsSelected',
                ngClick: 'setAdhocPattern()',
                awToolTip: i18n._("Select an inventory source by clicking the check box beside it. The inventory source can be a single group or host, a selection of multiple hosts, or a selection of multiple groups."),
                dataPlacement: 'top',
                actionClass: 'btn List-buttonDefault',
                buttonContent: i18n._('RUN COMMANDS'),
                showTipWhenDisabled: true,
                tooltipInnerClass: "Tooltip-wide",
                ngShow: 'canAdhoc'
                // TODO: set up a tip watcher and change text based on when
                // things are selected/not selected.  This is started and
                // commented out in the inventory controller within the watchers.
                // awToolTip: "{{ adhocButtonTipContents }}",
                // dataTipWatch: "adhocButtonTipContents"
            },
            add: {
                mode: 'all',
                type: 'buttonDropdown',
                awToolTip: i18n._("Add a group"),
                actionClass: 'btn List-buttonSubmit',
                buttonContent: '+ ' + i18n._('ADD'),
                ngShow: 'canAdd',
                dataPlacement: "top",
                options: [
                    {
                        optionContent: i18n._('Existing Group'),
                        optionSref: '.associate',
                        ngShow: 'canAdd'
                    },
                    {
                        optionContent: i18n._('New Group'),
                        optionSref: '.add',
                        ngShow: 'canAdd'
                    }
                ],
            }
        },

        fieldActions: {

            columnClass: 'col-lg-6 col-md-6 col-sm-6 col-xs-6 text-right',

            edit: {
                mode: 'all',
                ngClick: "editGroup(nested_group.id)",
                awToolTip: i18n._('Edit group'),
                dataPlacement: "top",
                ngShow: "nested_group.summary_fields.user_capabilities.edit"
            },
            view: {
                mode: 'all',
                ngClick: "editGroup(nested_group.id)",
                awToolTip: i18n._('View group'),
                dataPlacement: "top",
                ngShow: "!nested_group.summary_fields.user_capabilities.edit"
            },
            "delete": {
                mode: 'all',
                ngClick: "disassociateGroup(nested_group)",
                awToolTip: i18n._('Disassociate group'),
                iconClass: 'fa fa-times',
                dataPlacement: "top",
                ngShow: "nested_group.summary_fields.user_capabilities.delete"
            }
        }
    };
}];
<|endoftext|>


<commit_before>/**
 * @author alteredq / http://alteredqualia.com/
 * @author WestLangley / http://github.com/WestLangley
 * @author bhouston / http://clara.io
 * @author tschw
 */

function Matrix3() {

	this.elements = [

		1, 0, 0,
		0, 1, 0,
		0, 0, 1

	];

	if ( arguments.length > 0 ) {

		console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );

	}

}

Object.assign( Matrix3.prototype, {

	isMatrix3: true,

	set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {

		var te = this.elements;

		te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
		te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
		te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;

		return this;

	},

	identity: function () {

		this.set(

			1, 0, 0,
			0, 1, 0,
			0, 0, 1

		);

		return this;

	},

	clone: function () {

		return new this.constructor().fromArray( this.elements );

	},

	copy: function ( m ) {

		var te = this.elements;
		var me = m.elements;

		te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
		te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
		te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];

		return this;

	},

	extractBasis: function ( xAxis, yAxis, zAxis ) {

		var te = this.elements;

		xAxis.fromArray( te, 0 );
		yAxis.fromArray( te, 3 );
		zAxis.fromArray( te, 6 );

		return this;

	},

	setFromMatrix4: function ( m ) {

		var me = m.elements;

		this.set(

			me[ 0 ], me[ 4 ], me[ 8 ],
			me[ 1 ], me[ 5 ], me[ 9 ],
			me[ 2 ], me[ 6 ], me[ 10 ]

		);

		return this;

	},

	multiply: function ( m ) {

		return this.multiplyMatrices( this, m );

	},

	premultiply: function ( m ) {

		return this.multiplyMatrices( m, this );

	},

	multiplyMatrices: function ( a, b ) {

		var ae = a.elements;
		var be = b.elements;
		var te = this.elements;

		var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
		var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
		var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];

		var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
		var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
		var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];

		te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
		te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
		te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;

		te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
		te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
		te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;

		te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
		te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
		te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;

		return this;

	},

	multiplyScalar: function ( s ) {

		var te = this.elements;

		te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
		te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
		te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;

		return this;

	},

	determinant: function () {

		var te = this.elements;

		var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
			d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
			g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];

		return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;

	},

	getInverse: function ( matrix, throwOnDegenerate ) {

		if ( matrix && matrix.isMatrix4 ) {

			console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );

		}

		var me = matrix.elements,
			te = this.elements,

			n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
			n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
			n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],

			t11 = n33 * n22 - n32 * n23,
			t12 = n32 * n13 - n33 * n12,
			t13 = n23 * n12 - n22 * n13,

			det = n11 * t11 + n21 * t12 + n31 * t13;

		if ( det === 0 ) {

			var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";

			if ( throwOnDegenerate === true ) {

				throw new Error( msg );

			} else {

				console.warn( msg );

			}

			return this.identity();

		}

		var detInv = 1 / det;

		te[ 0 ] = t11 * detInv;
		te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
		te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;

		te[ 3 ] = t12 * detInv;
		te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
		te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;

		te[ 6 ] = t13 * detInv;
		te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
		te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;

		return this;

	},

	transpose: function () {

		var tmp, m = this.elements;

		tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
		tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
		tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;

		return this;

	},

	getNormalMatrix: function ( matrix4 ) {

		return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();

	},

	transposeIntoArray: function ( r ) {

		var m = this.elements;

		r[ 0 ] = m[ 0 ];
		r[ 1 ] = m[ 3 ];
		r[ 2 ] = m[ 6 ];
		r[ 3 ] = m[ 1 ];
		r[ 4 ] = m[ 4 ];
		r[ 5 ] = m[ 7 ];
		r[ 6 ] = m[ 2 ];
		r[ 7 ] = m[ 5 ];
		r[ 8 ] = m[ 8 ];

		return this;

	},

	setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {

		var c = Math.cos( rotation );
		var s = Math.sin( rotation );

		this.set(
			sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
			- sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
			0, 0, 1
		);

	},

	scale: function ( sx, sy ) {

		var te = this.elements;

		te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
		te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;

		return this;

	},

	rotate: function ( theta ) {

		var c = Math.cos( theta );
		var s = Math.sin( theta );

		var te = this.elements;

		var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
		var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];

		te[ 0 ] = c * a11 + s * a21;
		te[ 3 ] = c * a12 + s * a22;
		te[ 6 ] = c * a13 + s * a23;

		te[ 1 ] = - s * a11 + c * a21;
		te[ 4 ] = - s * a12 + c * a22;
		te[ 7 ] = - s * a13 + c * a23;

		return this;

	},

	translate: function ( tx, ty ) {

		var te = this.elements;

		te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
		te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];

		return this;

	},

	equals: function ( matrix ) {

		var te = this.elements;
		var me = matrix.elements;

		for ( var i = 0; i < 9; i ++ ) {

			if ( te[ i ] !== me[ i ] ) return false;

		}

		return true;

	},

	fromArray: function ( array, offset ) {

		if ( offset === undefined ) offset = 0;

		for ( var i = 0; i < 9; i ++ ) {

			this.elements[ i ] = array[ i + offset ];

		}

		return this;

	},

	toArray: function ( array, offset ) {

		if ( array === undefined ) array = [];
		if ( offset === undefined ) offset = 0;

		var te = this.elements;

		array[ offset ] = te[ 0 ];
		array[ offset + 1 ] = te[ 1 ];
		array[ offset + 2 ] = te[ 2 ];

		array[ offset + 3 ] = te[ 3 ];
		array[ offset + 4 ] = te[ 4 ];
		array[ offset + 5 ] = te[ 5 ];

		array[ offset + 6 ] = te[ 6 ];
		array[ offset + 7 ] = te[ 7 ];
		array[ offset + 8 ] = te[ 8 ];

		return array;

	}

} );

export { Matrix3 };
<commit_msg>Matrix3: Rewrite .extractBasis().<commit_after>/**
 * @author alteredq / http://alteredqualia.com/
 * @author WestLangley / http://github.com/WestLangley
 * @author bhouston / http://clara.io
 * @author tschw
 */

function Matrix3() {

	this.elements = [

		1, 0, 0,
		0, 1, 0,
		0, 0, 1

	];

	if ( arguments.length > 0 ) {

		console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );

	}

}

Object.assign( Matrix3.prototype, {

	isMatrix3: true,

	set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {

		var te = this.elements;

		te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
		te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
		te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;

		return this;

	},

	identity: function () {

		this.set(

			1, 0, 0,
			0, 1, 0,
			0, 0, 1

		);

		return this;

	},

	clone: function () {

		return new this.constructor().fromArray( this.elements );

	},

	copy: function ( m ) {

		var te = this.elements;
		var me = m.elements;

		te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
		te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
		te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];

		return this;

	},

	extractBasis: function ( xAxis, yAxis, zAxis ) {

		xAxis.setFromMatrix3Column( this, 0 );
		yAxis.setFromMatrix3Column( this, 1 );
		zAxis.setFromMatrix3Column( this, 2 );

		return this;

	},

	setFromMatrix4: function ( m ) {

		var me = m.elements;

		this.set(

			me[ 0 ], me[ 4 ], me[ 8 ],
			me[ 1 ], me[ 5 ], me[ 9 ],
			me[ 2 ], me[ 6 ], me[ 10 ]

		);

		return this;

	},

	multiply: function ( m ) {

		return this.multiplyMatrices( this, m );

	},

	premultiply: function ( m ) {

		return this.multiplyMatrices( m, this );

	},

	multiplyMatrices: function ( a, b ) {

		var ae = a.elements;
		var be = b.elements;
		var te = this.elements;

		var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
		var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
		var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];

		var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
		var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
		var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];

		te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
		te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
		te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;

		te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
		te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
		te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;

		te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
		te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
		te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;

		return this;

	},

	multiplyScalar: function ( s ) {

		var te = this.elements;

		te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
		te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
		te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;

		return this;

	},

	determinant: function () {

		var te = this.elements;

		var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
			d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
			g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];

		return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;

	},

	getInverse: function ( matrix, throwOnDegenerate ) {

		if ( matrix && matrix.isMatrix4 ) {

			console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );

		}

		var me = matrix.elements,
			te = this.elements,

			n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
			n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
			n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],

			t11 = n33 * n22 - n32 * n23,
			t12 = n32 * n13 - n33 * n12,
			t13 = n23 * n12 - n22 * n13,

			det = n11 * t11 + n21 * t12 + n31 * t13;

		if ( det === 0 ) {

			var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";

			if ( throwOnDegenerate === true ) {

				throw new Error( msg );

			} else {

				console.warn( msg );

			}

			return this.identity();

		}

		var detInv = 1 / det;

		te[ 0 ] = t11 * detInv;
		te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
		te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;

		te[ 3 ] = t12 * detInv;
		te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
		te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;

		te[ 6 ] = t13 * detInv;
		te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
		te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;

		return this;

	},

	transpose: function () {

		var tmp, m = this.elements;

		tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
		tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
		tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;

		return this;

	},

	getNormalMatrix: function ( matrix4 ) {

		return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();

	},

	transposeIntoArray: function ( r ) {

		var m = this.elements;

		r[ 0 ] = m[ 0 ];
		r[ 1 ] = m[ 3 ];
		r[ 2 ] = m[ 6 ];
		r[ 3 ] = m[ 1 ];
		r[ 4 ] = m[ 4 ];
		r[ 5 ] = m[ 7 ];
		r[ 6 ] = m[ 2 ];
		r[ 7 ] = m[ 5 ];
		r[ 8 ] = m[ 8 ];

		return this;

	},

	setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {

		var c = Math.cos( rotation );
		var s = Math.sin( rotation );

		this.set(
			sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
			- sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
			0, 0, 1
		);

	},

	scale: function ( sx, sy ) {

		var te = this.elements;

		te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
		te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;

		return this;

	},

	rotate: function ( theta ) {

		var c = Math.cos( theta );
		var s = Math.sin( theta );

		var te = this.elements;

		var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
		var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];

		te[ 0 ] = c * a11 + s * a21;
		te[ 3 ] = c * a12 + s * a22;
		te[ 6 ] = c * a13 + s * a23;

		te[ 1 ] = - s * a11 + c * a21;
		te[ 4 ] = - s * a12 + c * a22;
		te[ 7 ] = - s * a13 + c * a23;

		return this;

	},

	translate: function ( tx, ty ) {

		var te = this.elements;

		te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
		te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];

		return this;

	},

	equals: function ( matrix ) {

		var te = this.elements;
		var me = matrix.elements;

		for ( var i = 0; i < 9; i ++ ) {

			if ( te[ i ] !== me[ i ] ) return false;

		}

		return true;

	},

	fromArray: function ( array, offset ) {

		if ( offset === undefined ) offset = 0;

		for ( var i = 0; i < 9; i ++ ) {

			this.elements[ i ] = array[ i + offset ];

		}

		return this;

	},

	toArray: function ( array, offset ) {

		if ( array === undefined ) array = [];
		if ( offset === undefined ) offset = 0;

		var te = this.elements;

		array[ offset ] = te[ 0 ];
		array[ offset + 1 ] = te[ 1 ];
		array[ offset + 2 ] = te[ 2 ];

		array[ offset + 3 ] = te[ 3 ];
		array[ offset + 4 ] = te[ 4 ];
		array[ offset + 5 ] = te[ 5 ];

		array[ offset + 6 ] = te[ 6 ];
		array[ offset + 7 ] = te[ 7 ];
		array[ offset + 8 ] = te[ 8 ];

		return array;

	}

} );

export { Matrix3 };
<|endoftext|>


<commit_before>/**
 * jspsych-survey-text
 * a jspsych plugin for free response survey questions
 *
 * Josh de Leeuw (March 2013)
 * Updated October 2013
 *
 * parameters:
 *      questions: array of arrays. inner arrays are arrays of strings, where each string represents a prompt
 *                  for the user to respond to.
 *      data: optional data object
 *
 */

(function($) {
    jsPsych['survey-text'] = (function() {

        var plugin = {};

        plugin.create = function(params) {
            var trials = [];
            for (var i = 0; i < params.questions.length; i++) {
                trials.push({
                    type: "survey-text",
                    questions: params.questions[i],
                    data: (typeof params.data === 'undefined') ? {} : params.data[i]
                });
            }
            return trials;
        };

        plugin.trial = function(display_element, block, trial, part) {

            // add likert scale questions
            for (var i = 0; i < trial.questions.length; i++) {
                // create div
                display_element.append($('
', {
                    "id": 'surveytext' + i,
                    "class": 'surveyquestion'
                }));

                // add question text
                $("#surveytext" + i).append('
' + trial.questions[i] + '
');

                // add text box
                $("#surveytext" + i).append('<input type="text" name="surveyresponse' + i + '"></input>');
            }

            // add submit button
            display_element.append($('<button>', {
                'id': 'next',
                'class': 'surveytext'
            }));
            $("#next").html('Submit Answers');
            $("#next").click(function() {
                // measure response time
                var endTime = (new Date()).getTime();
                var response_time = endTime - startTime;

                // create object to hold responses
                var question_data = {};
                $("div.surveyquestion").each(function(index) {
                    var id = "Q" + index;
                    var val = $(this).children('input').val();
                    var obje = {};
                    obje[id] = val;
                    $.extend(question_data, obje);
                });

                // save data
                block.writeData($.extend({}, {
                    "trial_type": "survey-text",
                    "trial_index": block.trial_idx,
                    "rt": response_time
                }, question_data, trial.data));

                display_element.html('');

                // next trial
                block.next();
            });

            var startTime = (new Date()).getTime();
        };

        return plugin;
    })();
})(jQuery);<commit_msg>css cleanup (#13)<commit_after>/**
 * jspsych-survey-text
 * a jspsych plugin for free response survey questions
 *
 * Josh de Leeuw (March 2013)
 * Updated October 2013
 *
 * parameters:
 *      questions: array of arrays. inner arrays are arrays of strings, where each string represents a prompt
 *                  for the user to respond to.
 *      data: optional data object
 *
 */

(function($) {
    jsPsych['survey-text'] = (function() {

        var plugin = {};

        plugin.create = function(params) {
            var trials = [];
            for (var i = 0; i < params.questions.length; i++) {
                trials.push({
                    type: "survey-text",
                    questions: params.questions[i],
                    data: (typeof params.data === 'undefined') ? {} : params.data[i]
                });
            }
            return trials;
        };

        plugin.trial = function(display_element, block, trial, part) {

            // add likert scale questions
            for (var i = 0; i < trial.questions.length; i++) {
                // create div
                display_element.append($('
', {
                    "id": 'jspsych-survey-text-' + i,
                    "class": '#jspsych-survey-text-question'
                }));

                // add question text
                $("#jspsych-survey-text-" + i).append('
' + trial.questions[i] + '
');

                // add text box
                $("#jspsych-survey-text-" + i).append('<input type="text" name="#jspsych-survey-text-response-' + i + '"></input>');
            }

            // add submit button
            display_element.append($('<button>', {
                'id': 'jspsych-survey-text-next',
                'class': 'jspsych-survey-text'
            }));
            $("#jspsych-survey-text-next").html('Submit Answers');
            $("#jspsych-survey-text-next").click(function() {
                // measure response time
                var endTime = (new Date()).getTime();
                var response_time = endTime - startTime;

                // create object to hold responses
                var question_data = {};
                $("div.jspsych-survey-text-question").each(function(index) {
                    var id = "Q" + index;
                    var val = $(this).children('input').val();
                    var obje = {};
                    obje[id] = val;
                    $.extend(question_data, obje);
                });

                // save data
                block.writeData($.extend({}, {
                    "trial_type": "survey-text",
                    "trial_index": block.trial_idx,
                    "rt": response_time
                }, question_data, trial.data));

                display_element.html('');

                // next trial
                block.next();
            });

            var startTime = (new Date()).getTime();
        };

        return plugin;
    })();
})(jQuery);
<|endoftext|>