<commit_before>import React, { Component } from 'react';
import { TouchableOpacity } from 'react-native';
import {
  Divider,
  Screen,
  SectionList,
  Subtitle,
  Text,
  Title,
  View,
} from '@blankapp/ui';

class Home extends Component {
  static navigationOptions = {
    title: 'UIExplorer',
    headerLeft: null,
  };

  constructor(props) {
    super(props);
    this.navigation = this.props.navigation;

    this.renderSectionHeader = this.renderSectionHeader.bind(this);
    this.renderItem = this.renderItem.bind(this);

    const sectionsSource = [
      {
        title: 'Basic components',
        data: [
          {
            title: 'ActivityIndicator',
            description: 'Indicate that something is ongoing',
            routeName: 'DemoActivityIndicator',
          },
          {
            title: 'Badge',
            description: 'Small count controls',
            routeName: 'DemoBadge',
          },
          {
            title: 'Button',
            description: 'Flat and outline buttons',
            routeName: 'DemoButton',
          },
          {
            title: 'Card',
            description: 'Various card layout styles',
            routeName: 'DemoCard',
          },
          {
            title: 'CheckBox',
            description: 'Multi-selection controls',
            routeName: 'DemoCheckBox',
          },
          {
            title: 'Divider',
            description: 'Used to separate distinct content sections',
            routeName: 'DemoDivider',
          },
          {
            title: 'HyperlinkButton',
            description: 'Like hyperlink buttons',
            routeName: 'DemoHyperlinkButton',
          },
          {
            title: 'Modal',
            description: 'Coming soon',
            routeName: 'DemoModal',
          },
          {
            title: 'RadioButton',
            description: 'Single selection controls',
            routeName: 'DemoRadioButton',
          },
          {
            title: 'Subtitle',
            description: 'Subtitle text display controls',
            routeName: 'DemoSubtitle',
          },
          {
            title: 'Switch',
            description: 'On off switches',
            routeName: 'DemoSwitch',
          },
          {
            title: 'Text',
            description: 'Single and multi-line text display controls',
            routeName: 'DemoText',
          },
          {
            title: 'TextInput',
            description: 'Single and multi-line text edit controls',
            routeName: 'DemoTextInput',
          },
          {
            title: 'Title',
            description: 'Title text display controls',
            routeName: 'DemoTitle',
          },
          {
            title: 'View',
            description: 'A special view that can contain other views',
            routeName: 'DemoView',
          },
        ],
      },
      {
        title: 'Advanced components',
        data: [
          {
            title: 'AppBar',
            description: 'Coming soon',
            routeName: 'DemoAppBar',
          },
          {
            title: 'Icon',
            description: 'Coming soon',
            routeName: 'DemoIcon',
          },
          {
            title: 'IconButton',
            description: 'Coming soon',
            routeName: 'DemoIconButton',
          },
          {
            title: 'TabBar',
            description: 'Coming soon',
            routeName: 'DemoTabBar',
          },
          {
            title: 'ViewPager',
            description: 'Coming soon',
            routeName: 'DemoViewPager',
          },
        ],
      },
      {
        title: 'Experimental components',
        data: [
          {
            title: 'ListItem',
            description: 'Coming soon',
            routeName: 'DemoListItem',
          },
        ],
      },
    ];

    this.state = {
      sectionsSource,
    };
  }

  pressItem(item) {
    this.navigation.navigate(item.routeName);
  }

  renderSectionHeader({ section }) {
    return (
      <View
        style={{
          paddingTop: 5,
          paddingRight: 15,
          paddingBottom: 0,
          paddingLeft: 15,
        }}
      >
        <Text
          style={{
            fontWeight: 'bold',
          }}
        >{section.title}
        </Text>
      </View>
    );
  }

  renderItem({ item }) {
    return (
      <TouchableOpacity
        activeOpacity={0.8}
        onPress={() => this.pressItem(item)}
      >
        <View
          style={{
            paddingTop: 10,
            paddingBottom: 10,
            paddingLeft: 15,
            paddingRight: 15,
            minHeight: 64,
          }}
        >
          <Title>{item.title}</Title>
          <Subtitle>{item.description}</Subtitle>
        </View>
      </TouchableOpacity>
    );
  }

  render() {
    return (
      <Screen>
        <SectionList
          renderItem={this.renderItem}
          sections={this.state.sectionsSource}
          ItemSeparatorComponent={() => <Divider />}
          renderSectionHeader={this.renderSectionHeader}
          keyExtractor={item => `${item.routeName}`}
        />
      </Screen>
    );
  }
}

export default Home;
<commit_msg>Move UIExplorer to https://github.com/blankapp/uiexplorer<commit_after><|endoftext|>


<commit_before>"use strict";

angular.module("hikeio").
	directive("contenteditable", ["$filter", function($filter) {

		var runFilter = function(filterString, value) {
			var filterParams = filterString.split(":");
			var filterName = filterParams.splice(0, 1);
			filterParams.splice(0, 0, value);
			return $filter(filterName).apply(this, filterParams);
		};

		return {
			require: "ngModel",
			link: function(scope, element, attributes, controller) {

				// view -> model
				element.on("input", function() {
					scope.$apply(function() {
						var viewValue = "";
						if (attributes.type === "text") {
							viewValue = element.text();
						} else {
							viewValue = element.html();
						}

						if (attributes.filterModel) {
							viewValue = runFilter(attributes.filterModel, viewValue);
						}

						controller.$setViewValue(viewValue);
					});

					if (attributes.change) {
						scope.$apply(attributes.change);
					}
				});

				element.on("paste", function(event) {
					if (event.originalEvent.clipboardData) {
						var pastedData = event.originalEvent.clipboardData.getData("text/plain");
						if (attributes.type === "numeric") {
							if (($.isNumeric(pastedData) && (!attributes.positive || parseFloat(pastedData) > 0)) || pastedData === ".") {
								// programmatically paste to ensure that result will be numeric
								var before = element.html();
								document.execCommand("insertText", false, pastedData);
								var after = element.html();
								if ($.isNumeric(after) && (!attributes.positive || parseFloat(after) > 0)) {
									element.trigger("change");
								} else {
									element.html(before);
									element.blur();
								}
							}
						} else {
							document.execCommand("insertText", false, pastedData);
							element.trigger("change");
						}
					}

					return false;
				});

			element.keypress(function(event) {
				if (event.keyCode === 13 && attributes.singleLine) { // return
					event.preventDefault();
					element.blur();
				} else if (attributes.type === "numeric" &&
					(event.keyCode !== 46 && (event.keyCode < 48 || event.keyCode > 57) || // is anything other than 0-9 or period
					(event.keyCode === 46 && element.text().indexOf(".") > -1))) { // make sure if we're adding a period, we don't already have one

					if (attributes.positive && event.keyCode === 45) {
						var before = element.text();
						setTimeout(function(){
							if (!$.isNumeric(element.text())) {
								element.html(before);
							}
						});
						return true;
					}
					return false;
				}
				return true;
			});

			// model -> view
			controller.$render = function() {
				var viewValue = controller.$viewValue
				if (attributes.filterView) {
					viewValue = runFilter(attributes.filterView, viewValue);
				}
				element.html(viewValue);
			};

			// Load init value from DOM
			controller.$setViewValue(element.html());
			}
		};
	}]);<commit_msg>Delay reading of attributes from contenteditable directive, otherwise it may not be evaluated yet.<commit_after>"use strict";

angular.module("hikeio").
	directive("contenteditable", ["$filter", "$timeout", function($filter, $timeout) {

		var runFilter = function(filterString, value) {
			console.log("running filter", filterString, value)
			var filterParams = filterString.split(":");
			var filterName = filterParams.splice(0, 1);
			filterParams.splice(0, 0, value);
			return $filter(filterName).apply(this, filterParams);
		};

		return {
			require: "ngModel",
			link: function(scope, element, attributes, controller) {

				// view -> model
				element.on("input", function() {
					scope.$apply(function() {
						var viewValue = "";
						if (attributes.type === "text") {
							viewValue = element.text();
						} else {
							viewValue = element.html();
						}

						if (attributes.filterModel) {
							viewValue = runFilter(attributes.filterModel, viewValue);
						}

						controller.$setViewValue(viewValue);
					});

					if (attributes.change) {
						scope.$apply(attributes.change);
					}
				});

				element.on("paste", function(event) {
					if (event.originalEvent.clipboardData) {
						var pastedData = event.originalEvent.clipboardData.getData("text/plain");
						if (attributes.type === "numeric") {
							if (($.isNumeric(pastedData) && (!attributes.positive || parseFloat(pastedData) > 0)) || pastedData === ".") {
								// programmatically paste to ensure that result will be numeric
								var before = element.html();
								document.execCommand("insertText", false, pastedData);
								var after = element.html();
								if ($.isNumeric(after) && (!attributes.positive || parseFloat(after) > 0)) {
									element.trigger("change");
								} else {
									element.html(before);
									element.blur();
								}
							}
						} else {
							document.execCommand("insertText", false, pastedData);
							element.trigger("change");
						}
					}

					return false;
				});

			element.keypress(function(event) {
				if (event.keyCode === 13 && attributes.singleLine) { // return
					event.preventDefault();
					element.blur();
				} else if (attributes.type === "numeric" &&
					(event.keyCode !== 46 && (event.keyCode < 48 || event.keyCode > 57) || // is anything other than 0-9 or period
					(event.keyCode === 46 && element.text().indexOf(".") > -1))) { // make sure if we're adding a period, we don't already have one

					if (attributes.positive && event.keyCode === 45) {
						var before = element.text();
						setTimeout(function(){
							if (!$.isNumeric(element.text())) {
								element.html(before);
							}
						});
						return true;
					}
					return false;
				}
				return true;
			});

			// model -> view
			controller.$render = function() {

				// Delay reading of attributes.filterView, otherwise it will appear to be undefined
				// http://stackoverflow.com/questions/14547425/angularjs-cant-read-dynamically-set-attributes
				$timeout(function() {
					var viewValue = controller.$viewValue;
					if (attributes.filterView) {
						viewValue = runFilter(attributes.filterView, viewValue);
					}
					element.html(viewValue);
				});
			};

			// Load init value from DOM
			controller.$setViewValue(element.html());
			}
		};
	}]);<|endoftext|>


<commit_before>import axios from 'axios'

const _saveContact = (contactId, values) => {
  const request = contactId ? axios.patch : axios.post
  const endpoint = '/api-proxy/v4/contact'

  return request(contactId ? `${endpoint}/${contactId}` : endpoint, values)
    .catch((e) => {
      return Promise.reject(e.message)
    })
    .then((response) => {
      return response.data
    })
}

export const saveContact = ({ contactId, duplicateEmail, values }) => {
  // Check if contact with same email exists on company
  if (!contactId && (!duplicateEmail || duplicateEmail !== values.email)) {
    return axios
      .get(`/api-proxy/v4/contact`, { params: { email: values.email } })
      .then(({ data }) => {
        if (data.count) {
          return values.email
        } else {
          return _saveContact(contactId, values)
        }
      })
  } else {
    return _saveContact(contactId, values)
  }
}
<commit_msg>FIXUP use apiproxyaxios<commit_after>import { apiProxyAxios } from '../Task/utils'

const _saveContact = (contactId, values) => {
  const request = contactId ? apiProxyAxios.patch : apiProxyAxios.post
  const endpoint = '/api-proxy/v4/contact'

  return request(contactId ? `${endpoint}/${contactId}` : endpoint, values)
    .catch((e) => {
      return Promise.reject(e.message)
    })
    .then((response) => {
      return response.data
    })
}

export const saveContact = ({ contactId, duplicateEmail, values }) => {
  // Check if contact with same email exists on company
  if (!contactId && (!duplicateEmail || duplicateEmail !== values.email)) {
    return apiProxyAxios
      .get(`/api-proxy/v4/contact`, { params: { email: values.email } })
      .then(({ data }) => {
        if (data.count) {
          return values.email
        } else {
          return _saveContact(contactId, values)
        }
      })
  } else {
    return _saveContact(contactId, values)
  }
}
<|endoftext|>


<commit_before>var Survey = new Ti.App.joli.model({
	table : 'survey',
	columns : {
		id : 'INTEGER PRIMARY KEY',
		name : 'TEXT',
		description : 'TEXT',
		expiry_date : 'TEXT'
	},

	methods : {
		fetch : function() {
			var url = Ti.App.Properties.getString('server_url') + '/api/mobile/surveys';
			var that = this;
			var client = Ti.Network.createHTTPClient({
				// function called when the response data is available
				onload : function(e) {
					Ti.API.info("Received text: " + this.responseText);
					data = JSON.parse(this.responseText);
					// Emptying the table for now (until we get all the survey info from the server)
					that.truncate();
					that.createRecords(data);
					Ti.App.fireEvent('surveys.fetch.success');
				},
				// function called when an error occurs, including a timeout
				onerror : function(e) {
					Ti.API.debug(e.error);
					Ti.App.fireEvent('surveys.fetch.error', {
						status : this.status
					});
				},
				timeout : 5000 // in milliseconds
			});
			// Prepare the connection.
			client.open("GET", url);
			// Send the request.
			client.send();
		},

		createRecords : function(data) {
			var _ = require('lib/underscore')._;
			var that = this;
			_(data).each(function(survey) {
				var record = that.newRecord({
					id : survey.id,
					name : survey.name,
					description : survey.description,
					expiry_date : survey.expiry_date
				});
				record.save();
			});
		},

		isEmpty : function() {
			return this.count() == 0;
		}
	}
});

Ti.App.joli.models.initialize();
module.exports = Survey;

<commit_msg>Added a function to fetch all questions for a survey<commit_after>var Survey = new Ti.App.joli.model({
	table : 'survey',
	columns : {
		id : 'INTEGER PRIMARY KEY',
		name : 'TEXT',
		description : 'TEXT',
		expiry_date : 'TEXT'
	},

	methods : {
		fetch : function() {
			var url = Ti.App.Properties.getString('server_url') + '/api/mobile/surveys';
			var that = this;
			var client = Ti.Network.createHTTPClient({
				// function called when the response data is available
				onload : function(e) {
					Ti.API.info("Received text: " + this.responseText);
					data = JSON.parse(this.responseText);
					// Emptying the table for now (until we get all the survey info from the server)
					that.truncate();
					that.createRecords(data);
					Ti.App.fireEvent('surveys.fetch.success');
				},
				// function called when an error occurs, including a timeout
				onerror : function(e) {
					Ti.API.debug(e.error);
					Ti.App.fireEvent('surveys.fetch.error', {
						status : this.status
					});
				},
				timeout : 5000 // in milliseconds
			});
			// Prepare the connection.
			client.open("GET", url);
			// Send the request.
			client.send();
		},

		createRecords : function(data) {
			var _ = require('lib/underscore')._;
			var that = this;
			_(data).each(function(survey) {
				var record = that.newRecord({
					id : survey.id,
					name : survey.name,
					description : survey.description,
					expiry_date : survey.expiry_date
				});
				record.save();
			});
		},

		isEmpty : function() {
			return this.count() == 0;
		},

		fetchQuestions : function(surveyID) {
			var url = Ti.App.Properties.getString('server_url') + '/api/mobile/surveys/' + surveyID ;
			Ti.API.info("foooooo" + url)
			var client = Ti.Network.createHTTPClient({
				// function called when the response data is available
				onload : function(e) {
					Ti.API.info("Received text: " + this.responseText);
					data = JSON.parse(this.responseText);
				},
				// function called when an error occurs, including a timeout
				onerror : function(e) {
					Ti.API.info("Foooooo Error");
				},
				timeout : 5000 // in milliseconds
			});
			// Prepare the connection.
			client.open("GET", url);
			// Send the request.
			client.send();
		}
	}
});

Ti.App.joli.models.initialize();
module.exports = Survey;

<|endoftext|>


<commit_before>/* global afterEach, beforeEach, describe, expect, it, mongo, sinon */
/* global xdescribe */
$.ready = function () {}; // Prevent mongo.init() from running.

var CONST = {
  cssFile: 'mongo-web-shell.css'
};

xdescribe('The init function', function () {
  // TODO: The calls made in mongo.init() need to be stubbed; there should be
  // no side effects to the page (alternatively, have side effects but restore
  // the page to the initial state on afterEach()). Then re-enable this.
  var xhr, requests;

  beforeEach(function () {
    xhr = sinon.useFakeXMLHttpRequest();
    requests = [];
    xhr.onCreate = function (req) { requests.push(req); };
  });

  afterEach(function () {
    xhr.restore();
  });

  it('makes a post request for todo items', function () {
    mongo.init(sinon.spy());
    expect(requests.length).toBe(1);
    expect(requests[0].url).toBe('/mws/');
  });
});

describe('The const module', function () {
  it('stores keycode constants', function () {
    var key = mongo.const.keycodes;
    expect(key.enter).toBe(13);
    expect(key.left).toBe(37);
    expect(key.up).toBe(38);
    expect(key.right).toBe(39);
    expect(key.down).toBe(40);
  });
});

describe('A Cursor', function () {
  // TODO: Test.
});

describe('The dom module', function () {
  it('retrives the shell configuration from the DOM', function () {
    // TODO: Test more than the default values.
    var config = mongo.dom.retrieveConfig();
    // Default values.
    expect(config.cssPath).toBe(CONST.cssFile);
    expect(config.mwsHost).toBe('');
    expect(config.baseUrl).toBe('/mws/');
  });

  it('injects a stylesheet into the DOM', function () {
    function expectAbsentCSS(cssFile) {
      $('link').each(function (index, linkElement) {
        expect(linkElement.href).not.toBe(cssFile);
      });
    }

    // TODO: Should the dom methods be stubbed instead?
    expectAbsentCSS(CONST.cssFile);
    mongo.dom.injectStylesheet(CONST.cssFile);
    var injected = $('head').children().get(0); // Expect to be prepended.
    expect(injected.tagName).toBe('LINK');
    expect(injected.href).toMatch(CONST.cssFile + '$');
    expect(injected.rel).toBe('stylesheet');
    expect(injected.type).toBe('text/css');

    // Clean up.
    injected.parentNode.removeChild(injected);
    expectAbsentCSS(CONST.cssFile);
  });
});

describe('The keyword module', function () {
  // TODO: Test.
});

describe('The mutateSource module', function () {
  // TODO: Test.
});

describe('A Query', function () {
  // TODO: Test.
});

describe('A Readline instance', function () {
  // TODO: Test.
});

describe('The request module', function () {
  // TODO: Test untested methods.
  describe('relying on mongo.config', function () {
    var configStore;

    beforeEach(function () {
      configStore = mongo.config;
      mongo.config = {};
    });

    afterEach(function () {
      mongo.config = configStore;
    });

    it('creates a resource URL from the given parameters', function () {
      var gru = mongo.request._getResURL;
      mongo.config = {baseUrl: '/kpop/'};
      expect(gru('iu', 'jjang')).toBe('/kpop/iu/db/jjang/');
      mongo.config = {baseUrl: 'mws/'};
      expect(gru(30, 2)).toBe('mws/30/db/2/');
      expect(gru(null)).toBe('mws/null/db/undefined/');
      mongo.config = {baseUrl: 123};
      expect(gru('a', 'b')).toBe('123a/db/b/');
    });
  });

  it('prunes the given keys from the given object if undefined or null',
      function () {
    // TODO: Clean this up.
    function Param (db, query, projection) {
      this.db = db;
      this.query = query;
      this.projection = projection;
    }
    var param = [new Param(0, null, 0), new Param(0, 0, undefined),
                 new Param(0, undefined, null), new Param(0, 0, 0)];
    var keys = ['query', 'projection'];
    for (var i in param) {
      mongo.request._pruneKeys(param[i], keys);
    }
    expect(Object.keys(param[0]).length).toBe(2);
    expect(Object.keys(param[1]).length).toBe(2);
    expect(Object.keys(param[2]).length).toBe(1);
    expect(Object.keys(param[3]).length).toBe(3);
  });

  it('stringifies the keys of the given object', function () {
    // TODO: Use stringify rather than creating the output by hand.
    // TODO: Pass in an object with a prototype.
    // TODO: In general, more tests.
    var a = {'a':{1:2}};
    var res = {'a':'{"1":2}'};
    mongo.request._stringifyKeys(a);
    expect(a).toEqual(res);
  });
});

describe('A Shell', function () {
  // TODO: Test untested methods.
  it('injects its HTML into the DOM', function () {
    // TODO: Clean this up.
    var mwsBorder = $('.mws-border');
    expect(mwsBorder.length).toEqual(0);
    var shell = new mongo.Shell($('.mongo-web-shell'));
    shell.injectHTML();
    mwsBorder = $('.mws-border');
    expect(mwsBorder.length).toEqual(1);
    expect(mwsBorder.find('.mshell').length).toEqual(1);
    expect(mwsBorder.find('.mshell').find('.mws-input').length).toEqual(1);
  });
});

describe('The util module', function () {
  it('divides source code into statements', function () {
    // TODO: Clean this up.
    var ast = {};
    var str0 = 'db.inventory.find( { qty: 50 } )';
    var str1 = 'db.collection.totalSize()';
    var str2 = 'db.products.update( { item: "book", qty: { $gt: 5 } } )';
    var src  = str0 + str1 + str2;
    var params  = {};
    var params1 = {};
    var params2 = {};
    ast.body = [];
    params.range  = {0:0, 1:str0.length};
    params1.range = {0:str0.length, 1:str0.length+str1.length};
    params2.range = {0:str0.length+str1.length, 1:(src.length)};
    ast.body.push(params);
    ast.body.push(params1);
    ast.body.push(params2);
    var statements = mongo.util.sourceToStatements(src, ast);
    expect(statements[0]).toEqual(str0);
    expect(statements[1]).toEqual(str1);
    expect(statements[2]).toEqual(str2);
  });
});
<commit_msg>Clean up request._pruneKeys.<commit_after>/* global afterEach, beforeEach, describe, expect, it, mongo, sinon */
/* global xdescribe */
$.ready = function () {}; // Prevent mongo.init() from running.

var CONST = {
  cssFile: 'mongo-web-shell.css'
};

xdescribe('The init function', function () {
  // TODO: The calls made in mongo.init() need to be stubbed; there should be
  // no side effects to the page (alternatively, have side effects but restore
  // the page to the initial state on afterEach()). Then re-enable this.
  var xhr, requests;

  beforeEach(function () {
    xhr = sinon.useFakeXMLHttpRequest();
    requests = [];
    xhr.onCreate = function (req) { requests.push(req); };
  });

  afterEach(function () {
    xhr.restore();
  });

  it('makes a post request for todo items', function () {
    mongo.init(sinon.spy());
    expect(requests.length).toBe(1);
    expect(requests[0].url).toBe('/mws/');
  });
});

describe('The const module', function () {
  it('stores keycode constants', function () {
    var key = mongo.const.keycodes;
    expect(key.enter).toBe(13);
    expect(key.left).toBe(37);
    expect(key.up).toBe(38);
    expect(key.right).toBe(39);
    expect(key.down).toBe(40);
  });
});

describe('A Cursor', function () {
  // TODO: Test.
});

describe('The dom module', function () {
  it('retrives the shell configuration from the DOM', function () {
    // TODO: Test more than the default values.
    var config = mongo.dom.retrieveConfig();
    // Default values.
    expect(config.cssPath).toBe(CONST.cssFile);
    expect(config.mwsHost).toBe('');
    expect(config.baseUrl).toBe('/mws/');
  });

  it('injects a stylesheet into the DOM', function () {
    function expectAbsentCSS(cssFile) {
      $('link').each(function (index, linkElement) {
        expect(linkElement.href).not.toBe(cssFile);
      });
    }

    // TODO: Should the dom methods be stubbed instead?
    expectAbsentCSS(CONST.cssFile);
    mongo.dom.injectStylesheet(CONST.cssFile);
    var injected = $('head').children().get(0); // Expect to be prepended.
    expect(injected.tagName).toBe('LINK');
    expect(injected.href).toMatch(CONST.cssFile + '$');
    expect(injected.rel).toBe('stylesheet');
    expect(injected.type).toBe('text/css');

    // Clean up.
    injected.parentNode.removeChild(injected);
    expectAbsentCSS(CONST.cssFile);
  });
});

describe('The keyword module', function () {
  // TODO: Test.
});

describe('The mutateSource module', function () {
  // TODO: Test.
});

describe('A Query', function () {
  // TODO: Test.
});

describe('A Readline instance', function () {
  // TODO: Test.
});

describe('The request module', function () {
  // TODO: Test untested methods.
  describe('relying on mongo.config', function () {
    var configStore;

    beforeEach(function () {
      configStore = mongo.config;
      mongo.config = {};
    });

    afterEach(function () {
      mongo.config = configStore;
    });

    it('creates a resource URL from the given parameters', function () {
      var gru = mongo.request._getResURL;
      mongo.config = {baseUrl: '/kpop/'};
      expect(gru('iu', 'jjang')).toBe('/kpop/iu/db/jjang/');
      mongo.config = {baseUrl: 'mws/'};
      expect(gru(30, 2)).toBe('mws/30/db/2/');
      expect(gru(null)).toBe('mws/null/db/undefined/');
      mongo.config = {baseUrl: 123};
      expect(gru('a', 'b')).toBe('123a/db/b/');
    });
  });

  it('prunes the given keys from the given object if undefined or null',
      function () {
    function Parent() {
      this.a = 'a';
      this.b = null;
    }
    function Child(y, z) {
      this.y = y;
      this.z = z;
    }
    Child.prototype = Parent;

    var keysToDelete = ['b', 'z'];
    var actual = [
      {b: 'b', z: 'z'}, // 0
      {a: 'a', b: undefined, y: undefined, z: null}, // 1
      {a: 'a'}, // 2
      {}, // 3
      new Parent(), // 4
      new Child('y', 'z'), // 5
      new Child('y') // 6
    ];
    var expected = [
      {b: 'b', z: 'z'}, // 0
      {a: 'a', y: undefined}, // 1
      {a: 'a'}, // 2
      {} // 3
    ];
    var tmp = new Parent();
    delete tmp.b;
    expected.push(tmp);  // 4
    expected.push(new Child('y', 'z')); // 5
    tmp = new Child('y');
    delete tmp.z;
    expected.push(tmp); // 6

    actual.forEach(function (obj, i) {
      mongo.request._pruneKeys(obj, keysToDelete);
      expect(obj).toEqual(expected[i]);
    });
    actual = {a: 'a', b: 'b'};
    mongo.request._pruneKeys(actual, []);
    expect(actual).toEqual({a: 'a', b: 'b'});

    var throwerFunc = [
      function () { mongo.request._pruneKeys(null, ['key']); },
      function () { mongo.request._pruneKeys({}, null); }
    ];
    throwerFunc.forEach(function (func) {
      expect(func).toThrow();
    });
  });

  it('stringifies the keys of the given object', function () {
    // TODO: Use stringify rather than creating the output by hand.
    // TODO: Pass in an object with a prototype.
    // TODO: In general, more tests.
    var a = {'a':{1:2}};
    var res = {'a':'{"1":2}'};
    mongo.request._stringifyKeys(a);
    expect(a).toEqual(res);
  });
});

describe('A Shell', function () {
  // TODO: Test untested methods.
  it('injects its HTML into the DOM', function () {
    // TODO: Clean this up.
    var mwsBorder = $('.mws-border');
    expect(mwsBorder.length).toEqual(0);
    var shell = new mongo.Shell($('.mongo-web-shell'));
    shell.injectHTML();
    mwsBorder = $('.mws-border');
    expect(mwsBorder.length).toEqual(1);
    expect(mwsBorder.find('.mshell').length).toEqual(1);
    expect(mwsBorder.find('.mshell').find('.mws-input').length).toEqual(1);
  });
});

describe('The util module', function () {
  it('divides source code into statements', function () {
    // TODO: Clean this up.
    var ast = {};
    var str0 = 'db.inventory.find( { qty: 50 } )';
    var str1 = 'db.collection.totalSize()';
    var str2 = 'db.products.update( { item: "book", qty: { $gt: 5 } } )';
    var src  = str0 + str1 + str2;
    var params  = {};
    var params1 = {};
    var params2 = {};
    ast.body = [];
    params.range  = {0:0, 1:str0.length};
    params1.range = {0:str0.length, 1:str0.length+str1.length};
    params2.range = {0:str0.length+str1.length, 1:(src.length)};
    ast.body.push(params);
    ast.body.push(params1);
    ast.body.push(params2);
    var statements = mongo.util.sourceToStatements(src, ast);
    expect(statements[0]).toEqual(str0);
    expect(statements[1]).toEqual(str1);
    expect(statements[2]).toEqual(str2);
  });
});
<|endoftext|>


<commit_before>CKEDITOR.on('instanceReady', function (ev) {

    var writer = ev.editor.dataProcessor.writer;

    // Tighten up the indentation a bit from the default of wide tabs.
    writer.indentationChars = '  ';

    // Configure this set of tags to open and close all on the same line, if
    // possible.
    var oneliner_tags = [
        'hgroup', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
        'p', 'th', 'td', 'li'
    ]
    for (var i=0,tag; tag=oneliner_tags[i]; i++) {
        writer.setRules(tag, {
            indent: true,
            breakBeforeOpen: true,
            breakAfterOpen: false,
            breakBeforeClose: false,
            breakAfterClose: true
        });
    }

    //  Retrieve nodes important to moving the path bar to the top
    var tbody = ev.editor._.cke_contents.$.parentNode.parentNode,
        pathP = tbody.lastChild.childNodes[0].childNodes[1],
        toolbox = tbody.childNodes[0].childNodes[0].childNodes[0];
    toolbox.appendChild(pathP);
});

// Any utilities we need to be globably available will go here
CKEDITOR.mdn = {};

(function() {
    // Brick dialog "changed" prompts
    var originalOn = CKEDITOR.dialog.prototype.on;
    CKEDITOR.dialog.prototype.on = function(event, callback) {
        // If it's the cancel event that pops up the confirmation, just get out
        if(event == 'cancel' && callback.toString().indexOf('confirmCancel') != -1) {
            return true;
        }
        originalOn.apply(this, arguments);
    };

    // Manage key presses
    var keys = CKEDITOR.mdn.keys = {
            control2: CKEDITOR.CTRL + 50,
            control3: CKEDITOR.CTRL + 51,
            control4: CKEDITOR.CTRL + 52,
            control5: CKEDITOR.CTRL + 53,
            control6: CKEDITOR.CTRL + 54,

            controlK: CKEDITOR.CTRL + 75,
            controlL: CKEDITOR.CTRL + 76,
            controlShiftL: CKEDITOR.CTRL + CKEDITOR.SHIFT + 76,
            controlS: CKEDITOR.CTRL + 83,
            controlO: CKEDITOR.CTRL + 79,
            controlShiftO: CKEDITOR.CTRL + CKEDITOR.SHIFT + 79,
            controlShiftS: CKEDITOR.CTRL + CKEDITOR.SHIFT + 83,
            shiftSpace: CKEDITOR.SHIFT + 32,
            tab: 9,
            shiftTab: CKEDITOR.SHIFT + 9,
            enter: 13,
            back: 1114149,
            forward: 1114151
        },
        block = function(k) {
            return CKEDITOR.config.blockedKeystrokes.push(keys[k]);
        };

    // Prevent key handling
    block('tab');
    block('shiftTab');
    block('control2');
    block('control3');
    block('control4');
    block('control5');
    block('control6');
    block('controlO');
    block('controlS');
    block('controlShiftL');
    block('controlShiftO');
    block('back');
    block('forward');
})();

CKEDITOR.editorConfig = function(config) {

    config.extraPlugins = 'autogrow,definitionlist,mdn-buttons,mdn-link,mdn-syntaxhighlighter,mdn-keystrokes,mdn-attachments,mdn-image,mdn-enterkey,mdn-wrapstyle,mdn-table';
    config.removePlugins = 'link,image,tab,enterkey,table';
    config.entities = false;

    config.toolbar_MDN = [
        ['Source', 'mdnSaveExit', 'mdnSave', '-', 'PasteText', 'PasteFromWord', '-', 'SpellChecker', 'Scayt', '-', 'Find', 'Replace', '-', 'ShowBlocks'],
        ['BulletedList', 'NumberedList', 'DefinitionList', 'DefinitionTerm', 'DefinitionDescription', '-', 'Outdent', 'Indent', 'Blockquote', '-', 'Image', 'MDNTable', '-', 'TextColor', 'BGColor', '-', 'BidiLtr', 'BidiRtl'],
        ['Maximize'],
        '/',
        ['h1Button', 'h2Button', 'h3Button', 'h4Button', 'h5Button', 'h6Button', '-', 'preButton', 'mdn-syntaxhighlighter', 'Styles'],
        ['Link', 'Unlink', 'Anchor', '-', 'Bold', 'Italic', 'Underline', 'codeButton', 'Strike', 'Superscript', 'RemoveFormat', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight']
    ];

    config.skin = 'kuma';
    config.startupFocus = true;
    config.toolbar = 'MDN';

    config.autoGrow_minHeight = 600;
    config.contentsCss = ['/media/css/wiki-edcontent.css', '/en-US/docs/Template:CustomCSS?raw=1'];
    config.toolbarCanCollapse = false;
    config.resize_enabled = false;
    config.dialog_backgroundCoverColor = 'black';
    config.dialog_backgroundCoverOpacity = 0.3;
    config.docType = '<!DOCTYPE html>';

    CKEDITOR.stylesSet.add('default',[
        { name: "None", element: 'p' },
        { name: "Note box", element: 'div', attributes: { 'class': 'note' }, wrap: true },
        { name: "Warning box", element: 'div', attributes: { 'class': 'warning' }, wrap: true },
        { name: "Callout box", element: 'div', attributes: { 'class': 'geckoVersionNote' }, wrap: true },
        { name: "Plaintext (nowiki)", element: 'span', attributes: { 'class': 'plain' }},
        { name: "Two columns", element: 'div', attributes: { 'class': 'twocolumns' }, wrap: true },
        { name: "Three columns", element: 'div', attributes: { 'class': 'threecolumns' }, wrap: true }
    ]);

    {{ editor_config|safe }}
};
<commit_msg>fix bug 780196 - remove nowiki style from dropdown<commit_after>CKEDITOR.on('instanceReady', function (ev) {

    var writer = ev.editor.dataProcessor.writer;

    // Tighten up the indentation a bit from the default of wide tabs.
    writer.indentationChars = '  ';

    // Configure this set of tags to open and close all on the same line, if
    // possible.
    var oneliner_tags = [
        'hgroup', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
        'p', 'th', 'td', 'li'
    ]
    for (var i=0,tag; tag=oneliner_tags[i]; i++) {
        writer.setRules(tag, {
            indent: true,
            breakBeforeOpen: true,
            breakAfterOpen: false,
            breakBeforeClose: false,
            breakAfterClose: true
        });
    }

    //  Retrieve nodes important to moving the path bar to the top
    var tbody = ev.editor._.cke_contents.$.parentNode.parentNode,
        pathP = tbody.lastChild.childNodes[0].childNodes[1],
        toolbox = tbody.childNodes[0].childNodes[0].childNodes[0];
    toolbox.appendChild(pathP);
});

// Any utilities we need to be globably available will go here
CKEDITOR.mdn = {};

(function() {
    // Brick dialog "changed" prompts
    var originalOn = CKEDITOR.dialog.prototype.on;
    CKEDITOR.dialog.prototype.on = function(event, callback) {
        // If it's the cancel event that pops up the confirmation, just get out
        if(event == 'cancel' && callback.toString().indexOf('confirmCancel') != -1) {
            return true;
        }
        originalOn.apply(this, arguments);
    };

    // Manage key presses
    var keys = CKEDITOR.mdn.keys = {
            control2: CKEDITOR.CTRL + 50,
            control3: CKEDITOR.CTRL + 51,
            control4: CKEDITOR.CTRL + 52,
            control5: CKEDITOR.CTRL + 53,
            control6: CKEDITOR.CTRL + 54,

            controlK: CKEDITOR.CTRL + 75,
            controlL: CKEDITOR.CTRL + 76,
            controlShiftL: CKEDITOR.CTRL + CKEDITOR.SHIFT + 76,
            controlS: CKEDITOR.CTRL + 83,
            controlO: CKEDITOR.CTRL + 79,
            controlShiftO: CKEDITOR.CTRL + CKEDITOR.SHIFT + 79,
            controlShiftS: CKEDITOR.CTRL + CKEDITOR.SHIFT + 83,
            shiftSpace: CKEDITOR.SHIFT + 32,
            tab: 9,
            shiftTab: CKEDITOR.SHIFT + 9,
            enter: 13,
            back: 1114149,
            forward: 1114151
        },
        block = function(k) {
            return CKEDITOR.config.blockedKeystrokes.push(keys[k]);
        };

    // Prevent key handling
    block('tab');
    block('shiftTab');
    block('control2');
    block('control3');
    block('control4');
    block('control5');
    block('control6');
    block('controlO');
    block('controlS');
    block('controlShiftL');
    block('controlShiftO');
    block('back');
    block('forward');
})();

CKEDITOR.editorConfig = function(config) {

    config.extraPlugins = 'autogrow,definitionlist,mdn-buttons,mdn-link,mdn-syntaxhighlighter,mdn-keystrokes,mdn-attachments,mdn-image,mdn-enterkey,mdn-wrapstyle,mdn-table';
    config.removePlugins = 'link,image,tab,enterkey,table';
    config.entities = false;

    config.toolbar_MDN = [
        ['Source', 'mdnSaveExit', 'mdnSave', '-', 'PasteText', 'PasteFromWord', '-', 'SpellChecker', 'Scayt', '-', 'Find', 'Replace', '-', 'ShowBlocks'],
        ['BulletedList', 'NumberedList', 'DefinitionList', 'DefinitionTerm', 'DefinitionDescription', '-', 'Outdent', 'Indent', 'Blockquote', '-', 'Image', 'MDNTable', '-', 'TextColor', 'BGColor', '-', 'BidiLtr', 'BidiRtl'],
        ['Maximize'],
        '/',
        ['h1Button', 'h2Button', 'h3Button', 'h4Button', 'h5Button', 'h6Button', '-', 'preButton', 'mdn-syntaxhighlighter', 'Styles'],
        ['Link', 'Unlink', 'Anchor', '-', 'Bold', 'Italic', 'Underline', 'codeButton', 'Strike', 'Superscript', 'RemoveFormat', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight']
    ];

    config.skin = 'kuma';
    config.startupFocus = true;
    config.toolbar = 'MDN';

    config.autoGrow_minHeight = 600;
    config.contentsCss = ['/media/css/wiki-edcontent.css', '/en-US/docs/Template:CustomCSS?raw=1'];
    config.toolbarCanCollapse = false;
    config.resize_enabled = false;
    config.dialog_backgroundCoverColor = 'black';
    config.dialog_backgroundCoverOpacity = 0.3;
    config.docType = '<!DOCTYPE html>';

    CKEDITOR.stylesSet.add('default',[
        { name: "None", element: 'p' },
        { name: "Note box", element: 'div', attributes: { 'class': 'note' }, wrap: true },
        { name: "Warning box", element: 'div', attributes: { 'class': 'warning' }, wrap: true },
        { name: "Callout box", element: 'div', attributes: { 'class': 'geckoVersionNote' }, wrap: true },
        { name: "Two columns", element: 'div', attributes: { 'class': 'twocolumns' }, wrap: true },
        { name: "Three columns", element: 'div', attributes: { 'class': 'threecolumns' }, wrap: true }
    ]);

    {{ editor_config|safe }}
};
<|endoftext|>


<commit_before>'use strict';

const remote = require('electron').remote;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;

var createDefault = function() {
  var menu = new Menu();
  menu.append(new MenuItem({
    role: 'cut'
  }));
  menu.append(new MenuItem({
    role: 'copy'
  }));
  menu.append(new MenuItem({
    role: 'paste'
  }));
  menu.append(new MenuItem({
    role: 'selectall'
  }));
  return menu;
};

module.exports = {
  createDefault: createDefault
};
<commit_msg>Cleanup, remvoe old menu code<commit_after><|endoftext|>


<commit_before>import constants, { errorCodes }  from '../constants';
import transition from '../transition';
import { noop } from '../utils';

export default function withNavigation(router) {
    let cancelCurrentTransition;

    router.navigate = navigate;
    router.navigateToDefault = navigateToDefault;
    router.transitionToState = transitionToState;
    router.cancel = cancel;

    function cancel() {
        if (cancelCurrentTransition) {
            cancelCurrentTransition('navigate');
            cancelCurrentTransition = null;
        }

        return router;
    }

    function navigate(name, params = {}, opts = {}, done = noop) {
        if (!router.isStarted()) {
            done({ code: errorCodes.ROUTER_NOT_STARTED });
            return;
        }

        const toState = router.buildState(name, params);

        if (!toState) {
            const err = { code: errorCodes.ROUTE_NOT_FOUND };
            done(err);
            router.invokeListeners(constants.TRANSITION_ERROR, null, router.getState(), err);
            return;
        }

        toState.path = router.buildPath(name, params);
        const sameStates = router.getState() ? router.areStatesEqual(router.getState(), toState, false) : false;

        // Do not proceed further if states are the same and no reload
        // (no desactivation and no callbacks)
        if (sameStates && !opts.reload) {
            const err = { code: errorCodes.SAME_STATES };
            done(err);
            router.invokeListeners(constants.TRANSITION_ERROR, toState, router.getState(), err);
            return;
        }

        const fromState = sameStates ? null : router.getState();

        // Transition and amend history
        return transitionToState(toState, fromState, opts, (err, state) => {
            if (err) {
                if (err.redirect) navigate(err.redirect.name, err.redirect.params, { reload: true }, done);
                else done(err);
                return;
            }

            router.invokeListeners(constants.TRANSITION_SUCCESS, state, fromState, opts);
            done(null, state);
        });
    }

    function navigateToDefault(opts = {}, done = noop) {
        const options = router.getOptions();

        return navigate(options.defaultRoute, options.defaultParams, opts, done);
    }

    function transitionToState(toState, fromState, options = {}, done = noop) {
        cancel();
        router.invokeListeners(constants.TRANSITION_START, toState, fromState);

        cancelCurrentTransition = transition(router, toState, fromState, options, (err, state) => {
            cancelCurrentTransition = null;
            state = state || toState;

            if (err) {
                if (err.code === errorCodes.TRANSITION_CANCELLED) {
                    router.invokeListeners(constants.TRANSITION_CANCELLED, toState, fromState);
                } else {
                    router.invokeListeners(constants.TRANSITION_ERROR, toState, fromState, err);
                }
                done(err);
            } else {
                router.setState(state);
                done(null, state);
            }
        });

        return cancelCurrentTransition;
    }
}
<commit_msg>fix: inherit navigate options when redirecting<commit_after>import constants, { errorCodes }  from '../constants';
import transition from '../transition';
import { noop } from '../utils';

export default function withNavigation(router) {
    let cancelCurrentTransition;

    router.navigate = navigate;
    router.navigateToDefault = navigateToDefault;
    router.transitionToState = transitionToState;
    router.cancel = cancel;

    function cancel() {
        if (cancelCurrentTransition) {
            cancelCurrentTransition('navigate');
            cancelCurrentTransition = null;
        }

        return router;
    }

    function navigate(name, params = {}, opts = {}, done = noop) {
        if (!router.isStarted()) {
            done({ code: errorCodes.ROUTER_NOT_STARTED });
            return;
        }

        const toState = router.buildState(name, params);

        if (!toState) {
            const err = { code: errorCodes.ROUTE_NOT_FOUND };
            done(err);
            router.invokeListeners(constants.TRANSITION_ERROR, null, router.getState(), err);
            return;
        }

        toState.path = router.buildPath(name, params);
        const sameStates = router.getState() ? router.areStatesEqual(router.getState(), toState, false) : false;

        // Do not proceed further if states are the same and no reload
        // (no desactivation and no callbacks)
        if (sameStates && !opts.reload) {
            const err = { code: errorCodes.SAME_STATES };
            done(err);
            router.invokeListeners(constants.TRANSITION_ERROR, toState, router.getState(), err);
            return;
        }

        const fromState = sameStates ? null : router.getState();

        // Transition and amend history
        return transitionToState(toState, fromState, opts, (err, state) => {
            if (err) {
                if (err.redirect) {
                    const { name, params } = err.redirect;

                    navigate(name, params, { ...opts, reload: true }, done);
                } else {
                    done(err);
                }
            } else {
                router.invokeListeners(constants.TRANSITION_SUCCESS, state, fromState, opts);
                done(null, state);
            }
        });
    }

    function navigateToDefault(opts = {}, done = noop) {
        const options = router.getOptions();

        return navigate(options.defaultRoute, options.defaultParams, opts, done);
    }

    function transitionToState(toState, fromState, options = {}, done = noop) {
        cancel();
        router.invokeListeners(constants.TRANSITION_START, toState, fromState);

        cancelCurrentTransition = transition(router, toState, fromState, options, (err, state) => {
            cancelCurrentTransition = null;
            state = state || toState;

            if (err) {
                if (err.code === errorCodes.TRANSITION_CANCELLED) {
                    router.invokeListeners(constants.TRANSITION_CANCELLED, toState, fromState);
                } else {
                    router.invokeListeners(constants.TRANSITION_ERROR, toState, fromState, err);
                }
                done(err);
            } else {
                router.setState(state);
                done(null, state);
            }
        });

        return cancelCurrentTransition;
    }
}
<|endoftext|>


<commit_before>/*
 * jQuery image clipper
 * Copyright (c) 2015 Lancee (xrhy.me)
 * Dual licensed under the MIT and GPL licenses
 */

!(function() {
  (function($, Export) {
    "use strict";

    $.clipper = function(fileInput, options) {
      if (!fileInput || fileInput.nodeName !== "INPUT") {
        throw new Error('this is not a input');
      }

      var Clipper = function() {
        this.init();
      }

      Clipper.prototype = {
        constructor: Clipper,

        init: function() {
          var me = this,
              $image = build.call(me),
              blobURL = '';

          $(fileInput).on('change', function(e) {
            if (!$(this).hasClass('clipper')) {
              $image = build.call(me);
            }

            var files = this.files, file = files[0];

            if (file && isImg(file.type)) {
              if (blobURL) {
                blobURL = URL.revokeObjectURL(blobURL);
              }

              blobURL = URL.createObjectURL(file);

              if ($image.hasClass('cropper-clipper')) {
                // $image.cropper("reset", true).cropper("replace", blobURL);
              }

              $image.attr('src', blobURL).data('origin', blobURL);

            }
          });

          me.options = options;
        },

        options: $.clipper.defaults
      } //Clipper.prototype

      function build() {
        options = $.extend({}, $.clipper.defaults, options);

        var $input = $(fileInput).data('clipper', this),
            $image = $(options.imageSelector),
            filePath = $input.val(),
            me = this;

        if (!window.URL) {
          return;
        }

        if ($image.length === 0) {
          $image = createImg();
        }

        me.$el = $input.addClass('clipper');

        var $cropperDataHolder = $(options.cropperDataHolderSelector);

        if (!$cropperDataHolder.length) {
          $cropperDataHolder = $(options.cropperDataHolderTemplate);
          $input.before($cropperDataHolder);
        }

        $image.data('origin', $image[0].src).wrap('

');

        var $cropBtn = $('Crop'),
            $cropConfirm = $(options.cropperConfirmTemplate);

        $image.before($cropBtn).before($cropConfirm);

        $cropBtn.on('click', function() {
          $(this).hide();
          $cropConfirm.show();

          $image.attr('src', $image.data('origin').replace(/(jpg|jpeg|png|gif|bmp)$/, 'original.$1'));

          var cropData = JSON.parse($cropperDataHolder.val() || '{}').CropOption;

          $image.cropper({
            built: function() {
              $(this).addClass('cropper-clipper').cropper('setCropBoxData', cropData);
            },
            crop: function(data) {},
            multiple: true,
            zoomable: false
          });

        });

        $cropConfirm.on('click', '.act', function(e) {
          var act = $(e.target).data('act'),
              data = $image.cropper('getData', true),
              cropData = $image.cropper('getCropBoxData'),
              imageData = $image.cropper('getImageData');

          data.width = Math.round(data.width);
          data.height = Math.round(data.height);

          data = JSON.stringify({CropOption: data, Crop: !!(act*1)});

          $cropperDataHolder.val(data);

          var dataURL = act*1 ? $image.cropper('getDataURL') : $image.data('origin');

          $image.cropper('destroy');
          $image.attr('src', dataURL);

          $cropConfirm.hide();

          $cropBtn.show();
        });

        return $image;
      }

      function isImg(suffix) {
        return suffix.search(/jpg|jpeg|png|gif|bmp/i) !== -1;
      }

      function createImg(src) {
        var img = new Image();
        img.src = src;

        $(fileInput).after(img);

        return $(img);
      }

      return new Clipper();

    }

    $.clipper.defaults = {
      imageSelector: '.image-cropper',
      imageClass: 'clipper-uploaded-image',
      cropperDataHolderSelector: '.image-cropper-crop-option',
      cropperDataHolderTemplate: '<textarea name="QorResource.File" style="display:none">',
      cropperConfirmTemplate: '
\
                                 Cancel\
                                 Save\

'
    };

    $.fn.clipper = function(options, callback) {
      var clipper = $(this).data('clipper');

      if ($.isFunction(options)) {
        callback = options;
        options = null;
      } else {
        options = options || {};
      }

      if(typeof(options) === 'object') {
        return this.each(function(i) {
          if(!clipper) {
            clipper = $.clipper(this, options);
            if(callback)
              callback.call(clipper);
          } else {
            if(callback)
              callback.call(clipper);
          }
        });
      } else {
        throw new Error('arguments[0] is not a instance of Object');
      }
    }

  })(jQuery, window);

}).call(this);<commit_msg>fix cropper remember positions issues<commit_after>/*
 * jQuery image clipper
 * Copyright (c) 2015 Lancee (xrhy.me)
 * Dual licensed under the MIT and GPL licenses
 */

!(function() {
  (function($, Export) {
    "use strict";

    $.clipper = function(fileInput, options) {
      if (!fileInput || fileInput.nodeName !== "INPUT") {
        throw new Error('this is not a input');
      }

      var Clipper = function() {
        this.init();
      }

      Clipper.prototype = {
        constructor: Clipper,

        init: function() {
          var me = this,
              $image = build.call(me),
              blobURL = '';

          $(fileInput).on('change', function(e) {
            if (!$(this).hasClass('clipper')) {
              $image = build.call(me);
            }

            var files = this.files, file = files[0];

            if (file && isImg(file.type)) {
              if (blobURL) {
                blobURL = URL.revokeObjectURL(blobURL);
              }

              blobURL = URL.createObjectURL(file);

              if ($image.hasClass('cropper-clipper')) {
                // $image.cropper("reset", true).cropper("replace", blobURL);
              }

              $image.attr('src', blobURL).data('origin', blobURL);

            }
          });

          me.options = options;
        },

        options: $.clipper.defaults
      } //Clipper.prototype

      function build() {
        options = $.extend({}, $.clipper.defaults, options);

        var $input = $(fileInput).data('clipper', this),
            $image = $(options.imageSelector),
            filePath = $input.val(),
            me = this;

        if (!window.URL) {
          return;
        }

        if ($image.length === 0) {
          $image = createImg();
        }

        me.$el = $input.addClass('clipper');

        var $cropperDataHolder = $(options.cropperDataHolderSelector);

        if (!$cropperDataHolder.length) {
          $cropperDataHolder = $(options.cropperDataHolderTemplate);
          $input.before($cropperDataHolder);
        }

        $image.data('origin', $image[0].src).wrap('

');

        var $cropBtn = $('Crop'),
            $cropConfirm = $(options.cropperConfirmTemplate);

        $image.before($cropBtn).before($cropConfirm);

        $cropBtn.on('click', function() {
          $(this).hide();
          $cropConfirm.show();

          $image.attr('src', $image.data('origin').replace(/(jpg|jpeg|png|gif|bmp)$/, 'original.$1'));

          var data = JSON.parse($cropperDataHolder.val() || '{}').CropOption;

          for (var k in data) {
            data[k.toLowerCase()] = data[k];
          }

          $image.cropper({
            built: function() {
              var imageData = $(this).cropper('getImageData', true),
                  cropData = {};

              var zoomLevel = imageData.width / imageData.naturalWidth;

              cropData.left = imageData.left + zoomLevel * data.x;
              cropData.top = imageData.top + zoomLevel * data.y;
              cropData.width = data.width * zoomLevel;
              cropData.height = data.height * zoomLevel;

              $(this).addClass('cropper-clipper').cropper('setCropBoxData', cropData);
            },
            crop: function(data) {},
            multiple: true,
            zoomable: false
          });

        });

        $cropConfirm.on('click', '.act', function(e) {
          var act = $(e.target).data('act'),
              data = $image.cropper('getData', true);

          data = JSON.stringify({CropOption: data, Crop: !!(act*1)});

          $cropperDataHolder.val(data);

          var dataURL = act*1 ? $image.cropper('getDataURL') : $image.data('origin');

          $image.cropper('destroy');
          $image.attr('src', dataURL);

          $cropConfirm.hide();

          $cropBtn.show();
        });

        return $image;
      }

      function isImg(suffix) {
        return suffix.search(/jpg|jpeg|png|gif|bmp/i) !== -1;
      }

      function createImg(src) {
        var img = new Image();
        img.src = src;

        $(fileInput).after(img);

        return $(img);
      }

      return new Clipper();

    }

    $.clipper.defaults = {
      imageSelector: '.image-cropper',
      imageClass: 'clipper-uploaded-image',
      cropperDataHolderSelector: '.image-cropper-crop-option',
      cropperDataHolderTemplate: '<textarea name="QorResource.File" style="display:none">',
      cropperConfirmTemplate: '
\
                                 Cancel\
                                 Save\

'
    };

    $.fn.clipper = function(options, callback) {
      var clipper = $(this).data('clipper');

      if ($.isFunction(options)) {
        callback = options;
        options = null;
      } else {
        options = options || {};
      }

      if(typeof(options) === 'object') {
        return this.each(function(i) {
          if(!clipper) {
            clipper = $.clipper(this, options);
            if(callback)
              callback.call(clipper);
          } else {
            if(callback)
              callback.call(clipper);
          }
        });
      } else {
        throw new Error('arguments[0] is not a instance of Object');
      }
    }

  })(jQuery, window);

}).call(this);<|endoftext|>


<commit_before>Router.route('/', {
    name: 'home'
});

Router.route('/dashboard', {

});

Router.route('/register');

Router.route('/wizard/:step?', {
  name: 'registerWizard'
});

Router.route('/edit/:_id', {
    name: 'editRegistration'
});

// Route for individuals to review their registration(s)
Router.route('/view', {
  name: "registrantsView"
});

var requiresUserLogin = function () {
    if (!Meteor.user()) {
        this.render('login');
    } else {
        this.next();
    }
};

// Make sure user is logged in with registrar role
var requiresRegistrarAccess = function () {
  const userId = Meteor.userId();

  if (Roles.userIsInRole(userId, 'registrar')) {
    this.next();
  } else {
    this.render('notFound');
  }
};

// User login required for event registration
Router.onBeforeAction(requiresUserLogin, {only: ['register', 'view']});

// Admin-only access to certain routes
Router.onBeforeAction(requiresRegistrarAccess, {only: ['dashboard', 'editRegistration']});
<commit_msg>Add requiresUserLogin to registerWizard route<commit_after>Router.route('/', {
    name: 'home'
});

Router.route('/dashboard', {

});

Router.route('/register');

Router.route('/wizard/:step?', {
  name: 'registerWizard'
});

Router.route('/edit/:_id', {
    name: 'editRegistration'
});

// Route for individuals to review their registration(s)
Router.route('/view', {
  name: "registrantsView"
});

var requiresUserLogin = function () {
    if (!Meteor.user()) {
        this.render('login');
    } else {
        this.next();
    }
};

// Make sure user is logged in with registrar role
var requiresRegistrarAccess = function () {
  const userId = Meteor.userId();

  if (Roles.userIsInRole(userId, 'registrar')) {
    this.next();
  } else {
    this.render('notFound');
  }
};

// User login required for event registration
Router.onBeforeAction(requiresUserLogin, {only: ['register', 'registerWizard', 'view']});

// Admin-only access to certain routes
Router.onBeforeAction(requiresRegistrarAccess, {only: ['dashboard', 'editRegistration']});
<|endoftext|>


<commit_before>/* @flow */

import React from "react";
import { Disposable } from "atom";

import { StatusBar } from "./status-bar-component";
import { SignalListView } from "./signal-list-view";

import { reactFactory } from "../../../utils";

import type { Store } from "../../../store";
import type Kernel from "../../../kernel";
import type MarkerStore from "../../../store/markers";

export function addStatusBar(
  store: Store,
  statusBar: atom$StatusBar,
  handleKernelCommand: Function
) {
  const statusBarElement = document.createElement("div");
  statusBarElement.classList.add("inline-block", "hydrogen");

  const statusBarTile = statusBar.addLeftTile({
    item: statusBarElement,
    priority: 100
  });

  const onClick = showKernelCommands.bind(this, handleKernelCommand);

  reactFactory(<StatusBar store={store} onClick={onClick} />, statusBarElement);

  return new Disposable(() => statusBarTile.destroy());
}

function showKernelCommands(handleKernelCommand, { kernel, markers }) {
  if (this.signalListView) {
    this.signalListView.destroy();
  }
  this.signalListView = new SignalListView(kernel);
  this.signalListView.onConfirmed = (kernelCommand: { command: string }) =>
    handleKernelCommand(kernelCommand, { kernel, markers });
  this.signalListView.toggle();
}
<commit_msg>replace kernel rather than destroy component<commit_after>/* @flow */

import React from "react";
import { Disposable } from "atom";

import { StatusBar } from "./status-bar-component";
import { SignalListView } from "./signal-list-view";

import { reactFactory } from "../../../utils";

import type { Store } from "../../../store";
import type Kernel from "../../../kernel";
import type MarkerStore from "../../../store/markers";

export function addStatusBar(
  store: Store,
  statusBar: atom$StatusBar,
  handleKernelCommand: Function
) {
  const statusBarElement = document.createElement("div");
  statusBarElement.classList.add("inline-block", "hydrogen");

  const statusBarTile = statusBar.addLeftTile({
    item: statusBarElement,
    priority: 100
  });

  const onClick = showKernelCommands.bind(this, handleKernelCommand);

  reactFactory(<StatusBar store={store} onClick={onClick} />, statusBarElement);

  return new Disposable(() => statusBarTile.destroy());
}

function showKernelCommands(handleKernelCommand, { kernel, markers }) {
  if (!this.signalListView) {
    this.signalListView = new SignalListView(kernel);
    this.signalListView.onConfirmed = (kernelCommand: { command: string }) =>
      handleKernelCommand(kernelCommand, { kernel, markers });
  } else {
    this.signalListView.kernel = kernel;
  }
  this.signalListView.toggle();
}
<|endoftext|>


<commit_before>var config = require('./config.js');
var knex = require('knex')({
  dialect: 'mysql',
  connection: config.mysql,
  debug: false
});

Data = {}

FIELDS_KEEP = {
  user: ['id', 'name', 'screen_name', 'location', 'url', 'description', 'protected', 'verified', 'followers_count',
  'listed_count', 'favourites_count', 'statuses_count', 'utc_offset', 'time_zone', 'geo_enabled', 'lang',
  'contributors_enabled', 'is_translator', 'default_profile', 'friends_count'],
  tweet: ['id', 'text', 'source', 'truncated', 'geo', 'coordinates', 'place', 'contributors', 'retweet_count',
  'favorite_count', 'entities', 'created_at', 'favorited', 'retweeted', 'filter_level', 'possibly_sensitive', 'lang',
  'userId', 'flag']
}

var flags = ['angular','bootstrap','famous','famous_angular','ionic','meteor','backbone','bmarrionette',
'd3','ember','enyo','react','hammer','jquerymobile','jquery','kendo','knockout','polymer','sencha','threejs','titanium'];

Data.saveUser = function (tweet){
  return knex('users').insert(_pickFields(tweet.user, FIELDS_KEEP.user))
  .then(function(id){
    //object safely stored
  }, function(error) {
    //error occured, duplicate entry?
  });
}

Data.saveTweet = function (tweet){
  tweet.userId = tweet.user.id;
  //convert string to timestamps
  tweet.created_at = Date.parse(tweet.created_at) * 0.001;
  tweet.entities = tweet.entities.toString();

  var new_tweet = _pickFields(tweet, FIELDS_KEEP.tweet);
  return knex('tweets').insert(new_tweet).then(function(data){
  });
}

Data.getAllTweets = function () {
  //retrieve tweets for showing.
  return knex('tweets').select().then(function(data){
    return _formatStream(data, flags);
  });
}

_pickFields = function (object, whitelist) {
  var newObj = {};
  for(var key in whitelist) {
    var fieldName = whitelist[key];
    newObj[fieldName] = object[fieldName];
  }
  return newObj;
}

_formatStream = function (data, stream_names) {

  var data_streams = {};
  for(var i=0; i<data.length; i++){
    var record = data[i];
    if(data_streams[record.flag] == undefined){
      data_streams[record.flag] = [];
    }
    data_streams[record.flag].push(record.created_at);
  }

  return data_streams
}

module.exports = Data;
<commit_msg>ignore geo and place which are crashing the bot<commit_after>var config = require('./config.js');
var knex = require('knex')({
  dialect: 'mysql',
  connection: config.mysql,
  debug: false
});

Data = {}

FIELDS_KEEP = {
  user: ['id', 'name', 'screen_name', 'location', 'url', 'description', 'protected', 'verified', 'followers_count',
  'listed_count', 'favourites_count', 'statuses_count', 'utc_offset', 'time_zone', 'geo_enabled', 'lang',
  'contributors_enabled', 'is_translator', 'default_profile', 'friends_count'],
  tweet: ['id', 'text', 'source', 'truncated', 'coordinates', 'contributors', 'retweet_count',
  'favorite_count', 'entities', 'created_at', 'favorited', 'retweeted', 'filter_level', 'possibly_sensitive', 'lang',
  'userId', 'flag']
}

var flags = ['angular','bootstrap','famous','famous_angular','ionic','meteor','backbone','bmarrionette',
'd3','ember','enyo','react','hammer','jquerymobile','jquery','kendo','knockout','polymer','sencha','threejs','titanium'];

Data.saveUser = function (tweet){
  return knex('users').insert(_pickFields(tweet.user, FIELDS_KEEP.user))
  .then(function(id){
    //object safely stored
  }, function(error) {
    //error occured, duplicate entry?
    console.log('SAVE USER ERROR', tweet);
  });
}

Data.saveTweet = function (tweet){
  tweet.userId = tweet.user.id;
  //convert string to timestamps
  tweet.created_at = Date.parse(tweet.created_at) * 0.001;
  tweet.entities = tweet.entities.toString();

  var new_tweet = _pickFields(tweet, FIELDS_KEEP.tweet);
  return knex('tweets').insert(new_tweet).then(function(data){
  }, function(error){
    console.log('SAVE TWEET ERROR', tweet);
  });
}

Data.getAllTweets = function () {
  //retrieve tweets for showing.
  return knex('tweets').select().then(function(data){
    return _formatStream(data, flags);
  });
}

_pickFields = function (object, whitelist) {
  var newObj = {};
  for(var key in whitelist) {
    var fieldName = whitelist[key];
    newObj[fieldName] = object[fieldName];
  }
  return newObj;
}

_formatStream = function (data, stream_names) {

  var data_streams = {};
  for(var i=0; i<data.length; i++){
    var record = data[i];
    if(data_streams[record.flag] == undefined){
      data_streams[record.flag] = [];
    }
    data_streams[record.flag].push(record.created_at);
  }

  return data_streams
}

module.exports = Data;
<|endoftext|>


<commit_before>import { transform } from 'babel-standalone';

export default
target => {
  target.prototype._renderChildren = function() {
    let transpiledCode;
    try {
      transpiledCode = transform(
        `{<div>${this.props._childrenCode}</div>}`,
        { presets: ['es2015', 'react', 'stage-0'] }
      ).code;
    } catch (err) {
      console.log('Showroom scope decorator - transpiling code error:', err);
    }
    transpiledCode = transpiledCode.replace(/_scope/g, 'this');
    let compiledCode = eval(transpiledCode);
    return compiledCode;
  }
};
<commit_msg>Fixed lint errors.<commit_after>import { transform } from 'babel-standalone';

export default
target => {
  target.prototype._renderChildren = function() { // eslint-disable-line no-param-reassign
    let transpiledCode;
    try {
      transpiledCode = transform(
        `{<div>${this.props._childrenCode}</div>}`,
        { presets: ['es2015', 'react', 'stage-0'] }
      ).code;
    } catch (err) {
      console.log('Showroom scope decorator - transpiling code error:', err);
    }
    transpiledCode = transpiledCode.replace(/_scope/g, 'this');
    let compiledCode = eval(transpiledCode); // eslint-disable-line no-eval
    return compiledCode;
  }
};
<|endoftext|>


<commit_before>define([
  'summernote/base/core/dom'
], function (dom) {
  var Handle = function (context) {
    var self = this;

    var $document = $(document);
    var $editingArea = context.layoutInfo.editingArea;
    var options = context.options;

    this.events = {
      'summernote.mousedown': function (we, e) {
        if (self.update(e.target)) {
          e.preventDefault();
        }
      },
      'summernote.keyup summernote.scroll summernote.change summernote.dialog.shown': function () {
        self.update();
      },
      'summernote.disable': function () {
        self.hide();
      }
    };

    this.initialize = function () {
      this.$handle = $([
        '
',
        '
',
        '

',
        '

',
        '

',
        '

',
        '

',
        (options.disableResizeImage ? '' : '

'),
        '
',
        '
'
      ].join('')).prependTo($editingArea);

      this.$handle.on('mousedown', function (event) {
        if (dom.isControlSizing(event.target)) {
          event.preventDefault();
          event.stopPropagation();

          var $target = self.$handle.find('.note-control-selection').data('target'),
              posStart = $target.offset(),
              scrollTop = $document.scrollTop();

          var onMouseMove = function (event) {
            context.invoke('editor.resizeTo', {
              x: event.clientX - posStart.left,
              y: event.clientY - (posStart.top - scrollTop)
            }, $target, !event.shiftKey);

            self.update($target[0]);
          };

          $document
            .on('mousemove', onMouseMove)
            .one('mouseup', function (e) {
              e.preventDefault();
              $document.off('mousemove', onMouseMove);
              context.invoke('editor.afterCommand');
            });

          if (!$target.data('ratio')) { // original ratio.
            $target.data('ratio', $target.height() / $target.width());
          }
        }
      });
    };

    this.destroy = function () {
      this.$handle.remove();
    };

    this.update = function (target) {
      if (context.isDisabled()) {
        return false;
      }

      var isImage = dom.isImg(target);
      var $selection = this.$handle.find('.note-control-selection');

      context.invoke('imagePopover.update', target);

      if (isImage) {
        var $image = $(target);
        var pos = $image.position();

        // include margin
        var imageSize = {
          w: $image.outerWidth(true),
          h: $image.outerHeight(true)
        };

        $selection.css({
          display: 'block',
          left: pos.left,
          top: pos.top,
          width: imageSize.w,
          height: imageSize.h
        }).data('target', $image); // save current image element.

        var sizingText = imageSize.w + 'x' + imageSize.h;
        $selection.find('.note-control-selection-info').text(sizingText);
        context.invoke('editor.saveTarget', target);
      } else {
        this.hide();
      }

      return isImage;
    };

    /**
     * hide
     *
     * @param {jQuery} $handle
     */
    this.hide = function () {
      context.invoke('editor.clearTarget');
      this.$handle.children().hide();
    };
  };

  return Handle;
});
<commit_msg>Deselect image when scrolling on the handle overlay<commit_after>define([
  'summernote/base/core/dom'
], function (dom) {
  var Handle = function (context) {
    var self = this;

    var $document = $(document);
    var $editingArea = context.layoutInfo.editingArea;
    var options = context.options;

    this.events = {
      'summernote.mousedown': function (we, e) {
        if (self.update(e.target)) {
          e.preventDefault();
        }
      },
      'summernote.keyup summernote.scroll summernote.change summernote.dialog.shown': function () {
        self.update();
      },
      'summernote.disable': function () {
        self.hide();
      }
    };

    this.initialize = function () {
      this.$handle = $([
        '
',
        '
',
        '

',
        '

',
        '

',
        '

',
        '

',
        (options.disableResizeImage ? '' : '

'),
        '
',
        '
'
      ].join('')).prependTo($editingArea);

      this.$handle.on('mousedown', function (event) {
        if (dom.isControlSizing(event.target)) {
          event.preventDefault();
          event.stopPropagation();

          var $target = self.$handle.find('.note-control-selection').data('target'),
              posStart = $target.offset(),
              scrollTop = $document.scrollTop();

          var onMouseMove = function (event) {
            context.invoke('editor.resizeTo', {
              x: event.clientX - posStart.left,
              y: event.clientY - (posStart.top - scrollTop)
            }, $target, !event.shiftKey);

            self.update($target[0]);
          };

          $document
            .on('mousemove', onMouseMove)
            .one('mouseup', function (e) {
              e.preventDefault();
              $document.off('mousemove', onMouseMove);
              context.invoke('editor.afterCommand');
            });

          if (!$target.data('ratio')) { // original ratio.
            $target.data('ratio', $target.height() / $target.width());
          }
        }
      });

      // Listen for scrolling on the handle overlay.
      this.$handle.on('wheel', function (e) {
        e.preventDefault();
        self.update();
      });
    };

    this.destroy = function () {
      this.$handle.remove();
    };

    this.update = function (target) {
      if (context.isDisabled()) {
        return false;
      }

      var isImage = dom.isImg(target);
      var $selection = this.$handle.find('.note-control-selection');

      context.invoke('imagePopover.update', target);

      if (isImage) {
        var $image = $(target);
        var pos = $image.position();

        // include margin
        var imageSize = {
          w: $image.outerWidth(true),
          h: $image.outerHeight(true)
        };

        $selection.css({
          display: 'block',
          left: pos.left,
          top: pos.top,
          width: imageSize.w,
          height: imageSize.h
        }).data('target', $image); // save current image element.

        var sizingText = imageSize.w + 'x' + imageSize.h;
        $selection.find('.note-control-selection-info').text(sizingText);
        context.invoke('editor.saveTarget', target);
      } else {
        this.hide();
      }

      return isImage;
    };

    /**
     * hide
     *
     * @param {jQuery} $handle
     */
    this.hide = function () {
      context.invoke('editor.clearTarget');
      this.$handle.children().hide();
    };
  };

  return Handle;
});
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing fro<commit_msg>Cleaned out the intertubes<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up <|endoftext|>


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

    const latest_file = 'https://raw.githubusercontent.com/taengstagram/IG-Comments-Bookmarklet/master/latest.txt';
    let xhr = new XMLHttpRequest();
    xhr.open("GET", latest_file, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState != 4) {
            return;
        }
        let bookmarklet_src = xhr.responseText;
        let head = document.getElementsByTagName('head')[0];
        let scriptBookmarklet = document.createElement('script');
        scriptBookmarklet.src = bookmarklet_src;
        scriptBookmarklet.async = false;
        head.appendChild(scriptBookmarklet);
    };
    xhr.send();
})();
<commit_msg>Fix code format<commit_after>(function () {
    "use strict";

    const latestFile = 'https://raw.githubusercontent.com/taengstagram/IG-Comments-Bookmarklet/master/latest.txt';
    let xhr = new XMLHttpRequest();
    xhr.open("GET", latestFile, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState != 4) {
            return;
        }
        let bookmarkletSrc = xhr.responseText;
        let head = document.getElementsByTagName('head')[0];
        let scriptBookmarklet = document.createElement('script');
        scriptBookmarklet.src = bookmarkletSrc;
        scriptBookmarklet.async = false;
        head.appendChild(scriptBookmarklet);
    };
    xhr.send();
})();
<|endoftext|>


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

(function ($, oh) {
    'use strict';

    var hackathon_name = oh.comm.getCurrentHackathon();
    var def_expid = 0;

    function pageload() {
        var temp_name = $.getUrlParam('t');
        def_expid = $('[data-experiment]').data('experiment') || 0;
        if (def_expid) {
            getExperiment()
        } else {
            getTemplate(temp_name);
        }
        teamMember();
        hacakthonStat();
    }

    function teamMember() {
//        oh.api.team.member.list.get({header: {hackathon_name: hackathon_name}}, function (data) {
//            // todo 'Response team member'
//            if (data.error) {
//
//            } else {
//
//            }
//            console.log(data);
//        });
    }

    function hacakthonStat() {
        oh.api.hackathon.stat.get({
            header: {hackathon_name: hackathon_name}
        }, function (data) {
            $('#online').text(data.online);
            $('#total').text(data.total);
            //setTimeout(hacakthonStat(), 600000)
        });
    }

    function getTemplate(name) {
        oh.api.hackathon.template.get({header: {hackathon_name: hackathon_name}}, function (data) {
            if (data.error) {
                showErrorMsg(data);
            } else {

                if (data.length > 0) {
                    def_expid = data[0].id;
                    var tname = data[0].name;
                    $.each(data,function(i,item){
                        if(item.name == name){
                            def_expid = item.id;
                            tname = item.name;
                        }
                    });
                    postTemplate(item.name);
                } else {
                    showErrorMsg({
                        error: {
                            code: 404,
                            friendly_message: '没有模板'
                        }
                    });
                }
            }
        });
    }

    function postTemplate(name) {
        oh.api.user.experiment.post({
            body: {template_name: name, hackathon_name: hackathon_name}
        }, function (data) {
            loadExperiment(data);
        });
    }

    function showErrorMsg(data) {
        $('#load').hide();
        var errorbox = $('#error').hide();
        if (data.error.code) {
            errorbox.find('.code').text(data.error.code);
        }
        if (data.error.friendly_message) {
            errorbox.find('.message').text(data.error.friendly_message);
        }
        errorbox.show();
    }

    function getExperiment() {
        oh.api.user.experiment.get({query: {id: def_expid}}, function (data) {
            loadExperiment(data);
        });
    }

    function loadExperiment(data) {
        var tmpe = '
\

\
                            \
                                \
                            \

{name}
\

\

';

        if (data.status == 2) {
            var dockers = []
            for (var i in data.remote_servers) {
                dockers.push({
                    purl: "",
                    imgUrl: data.remote_servers[i].name == 'cloud_eclipse' ? '/static/pic/idehub.png' : '/static/pic/dseries.png',
                    name: data.remote_servers[i].name,
                    surl: data.remote_servers[i].name == 'cloud_eclipse' ? data.remote_servers[i].url + window.location.origin : data.remote_servers[i].url + "&oh=" + $.cookie('token')
                })
                $('.hackathon-nav').append(tmpe.format(dockers[i]));
            }
            heartbeat(def_expid);
        } else if (data.status == 1) {
            setTimeout(getExperiment, 60000);
        } else {
            showErrorMsg(data);
        }
    }

    function bindEvent() {
        var work_center = $('.center').on('mouseover', 'iframe', function (e) {
            $(this).focus();
        });
        var hnav = $('.hackathon-nav').on('click', 'a.vm-box', function (e) {
            hnav.find('.vm-box').removeClass('active')
            var a = $(this).addClass('active');
            var url = a.data('url');
            var token = a.data('token');
            var name = a.attr('id')
            var ifrem = work_center.find('#' + name);
            work_center.find('iframe').addClass('invisible');
            if (ifrem.length > 0) {
                ifrem.removeClass('invisible');
            } else {
                ifrem = $('').attr({
                    src: url,
                    id: name,
                    width: '100%',
                    height: '100%',
                    frameborder: 'no',
                    marginwidth: '0',
                    scrolling: 'no'
                }).appendTo(work_center)
            }
        });

        var smallbtn = $('

')
            .click(function (e) {
                e.preventDefault();
                $('iframe[class!="invisible"]').removeClass('work-full');
                smallbtn.hide();
            }).appendTo('body');

        var fullbtn = $('#workfull').click(function (e) {
            e.preventDefault();
            $('iframe[class!="invisible"]').addClass('work-full');
            $('.smallscreen').show();
        });
    }

    function heartbeat(id) {
        oh.api.user.experiment.put({
            body: {id: id}
        }, function (data) {
            if (data.error) {
                // todo 'heartbeat error'
            } else {
                window.setTimeout(function(){
                        heartbeat(id)
                    }, 300000)
            }
        });
    }

    function init() {
        pageload();
        bindEvent();
    }

    function endCountdown() {
        var timerTmpe = '{day}天{hour}小时{minute}分钟{second}秒';

        function show_time() {
            var timing = {day: 0, hour: 0, minute: 0, second: 0, distance: 0};
            this.time_server += 1000
            timing.distance = this.time_end - this.time_server;
            if (timing.distance > 0) {
                timing.day = Math.floor(timing.distance / 86400000)
                timing.distance -= timing.day * 86400000;
                timing.hour = Math.floor(timing.distance / 3600000)
                timing.distance -= timing.hour * 3600000;
                timing.minute = Math.floor(timing.distance / 60000)
                timing.distance -= timing.minute * 60000;
                timing.second = Math.floor(timing.distance / 1000)
                if (timing.day == 0) {
                    timing.day = null
                }
                if (timing.hour == 0 && timing.day == null) {
                    timing.hour = null
                }
                if (timing.minute == 0 && timing.hour == null) {
                    timing.minute = null
                }
                if (timing.second == 0 && timing.minute == null) {
                    timing.second = null
                }
                return timing;
            } else {
                return null;
            }
        }

        function showCountDown(countDown) {
            var timing = show_time.apply(countDown);
            if (!timing) {
                $('#timer').text('本次活动已结束，非常感谢您的参与。')
                clearInterval(stop);
            } else {
                $('#end_timer').text(timerTmpe.format(timing))
            }
        }

        var countDown = {
            time_server: new Date().getTime(),
            time_end: $('#end_timer').data('endtiem')
        }
        showCountDown(countDown);
        var stop = setInterval(function () {
            showCountDown(countDown);
        }, 1000);
    }

    $(function () {
        init();
        endCountdown();
    })
})(window.jQuery, window.oh);
<commit_msg>Update oh.site.workspace.js<commit_after>/*
 * Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd.  All rights reserved.
 *
 * The MIT License (MIT)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

(function ($, oh) {
    'use strict';

    var hackathon_name = oh.comm.getCurrentHackathon();
    var def_expid = 0;

    function pageload() {
        var temp_name = $.getUrlParam('t');
        def_expid = $('[data-experiment]').data('experiment') || 0;
        if (def_expid) {
            getExperiment()
        } else {
            getTemplate(temp_name);
        }
        teamMember();
        hacakthonStat();
    }

    function teamMember() {
//        oh.api.team.member.list.get({header: {hackathon_name: hackathon_name}}, function (data) {
//            // todo 'Response team member'
//            if (data.error) {
//
//            } else {
//
//            }
//            console.log(data);
//        });
    }

    function hacakthonStat() {
        oh.api.hackathon.stat.get({
            header: {hackathon_name: hackathon_name}
        }, function (data) {
            $('#online').text(data.online);
            $('#total').text(data.total);
            //setTimeout(hacakthonStat(), 600000)
        });
    }

    function getTemplate(name) {
        oh.api.hackathon.template.get({header: {hackathon_name: hackathon_name}}, function (data) {
            if (data.error) {
                showErrorMsg(data);
            } else {

                if (data.length > 0) {
                    def_expid = data[0].id;
                    var tname = data[0].name;
                    $.each(data,function(i,item){
                        if(item.name == name){
                            def_expid = item.id;
                            tname = item.name;
                        }
                    });
                    postTemplate(tname);
                } else {
                    showErrorMsg({
                        error: {
                            code: 404,
                            friendly_message: '没有模板'
                        }
                    });
                }
            }
        });
    }

    function postTemplate(name) {
        oh.api.user.experiment.post({
            body: {template_name: name, hackathon_name: hackathon_name}
        }, function (data) {
            loadExperiment(data);
        });
    }

    function showErrorMsg(data) {
        $('#load').hide();
        var errorbox = $('#error').hide();
        if (data.error.code) {
            errorbox.find('.code').text(data.error.code);
        }
        if (data.error.friendly_message) {
            errorbox.find('.message').text(data.error.friendly_message);
        }
        errorbox.show();
    }

    function getExperiment() {
        oh.api.user.experiment.get({query: {id: def_expid}}, function (data) {
            loadExperiment(data);
        });
    }

    function loadExperiment(data) {
        var tmpe = '
\

\
                            \
                                \
                            \

{name}
\

\

';

        if (data.status == 2) {
            var dockers = []
            for (var i in data.remote_servers) {
                dockers.push({
                    purl: "",
                    imgUrl: data.remote_servers[i].name == 'cloud_eclipse' ? '/static/pic/idehub.png' : '/static/pic/dseries.png',
                    name: data.remote_servers[i].name,
                    surl: data.remote_servers[i].name == 'cloud_eclipse' ? data.remote_servers[i].url + window.location.origin : data.remote_servers[i].url + "&oh=" + $.cookie('token')
                })
                $('.hackathon-nav').append(tmpe.format(dockers[i]));
            }
            heartbeat(def_expid);
        } else if (data.status == 1) {
            setTimeout(getExperiment, 60000);
        } else {
            showErrorMsg(data);
        }
    }

    function bindEvent() {
        var work_center = $('.center').on('mouseover', 'iframe', function (e) {
            $(this).focus();
        });
        var hnav = $('.hackathon-nav').on('click', 'a.vm-box', function (e) {
            hnav.find('.vm-box').removeClass('active')
            var a = $(this).addClass('active');
            var url = a.data('url');
            var token = a.data('token');
            var name = a.attr('id')
            var ifrem = work_center.find('#' + name);
            work_center.find('iframe').addClass('invisible');
            if (ifrem.length > 0) {
                ifrem.removeClass('invisible');
            } else {
                ifrem = $('').attr({
                    src: url,
                    id: name,
                    width: '100%',
                    height: '100%',
                    frameborder: 'no',
                    marginwidth: '0',
                    scrolling: 'no'
                }).appendTo(work_center)
            }
        });

        var smallbtn = $('

')
            .click(function (e) {
                e.preventDefault();
                $('iframe[class!="invisible"]').removeClass('work-full');
                smallbtn.hide();
            }).appendTo('body');

        var fullbtn = $('#workfull').click(function (e) {
            e.preventDefault();
            $('iframe[class!="invisible"]').addClass('work-full');
            $('.smallscreen').show();
        });
    }

    function heartbeat(id) {
        oh.api.user.experiment.put({
            body: {id: id}
        }, function (data) {
            if (data.error) {
                // todo 'heartbeat error'
            } else {
                window.setTimeout(function(){
                        heartbeat(id)
                    }, 300000)
            }
        });
    }

    function init() {
        pageload();
        bindEvent();
    }

    function endCountdown() {
        var timerTmpe = '{day}天{hour}小时{minute}分钟{second}秒';

        function show_time() {
            var timing = {day: 0, hour: 0, minute: 0, second: 0, distance: 0};
            this.time_server += 1000
            timing.distance = this.time_end - this.time_server;
            if (timing.distance > 0) {
                timing.day = Math.floor(timing.distance / 86400000)
                timing.distance -= timing.day * 86400000;
                timing.hour = Math.floor(timing.distance / 3600000)
                timing.distance -= timing.hour * 3600000;
                timing.minute = Math.floor(timing.distance / 60000)
                timing.distance -= timing.minute * 60000;
                timing.second = Math.floor(timing.distance / 1000)
                if (timing.day == 0) {
                    timing.day = null
                }
                if (timing.hour == 0 && timing.day == null) {
                    timing.hour = null
                }
                if (timing.minute == 0 && timing.hour == null) {
                    timing.minute = null
                }
                if (timing.second == 0 && timing.minute == null) {
                    timing.second = null
                }
                return timing;
            } else {
                return null;
            }
        }

        function showCountDown(countDown) {
            var timing = show_time.apply(countDown);
            if (!timing) {
                $('#timer').text('本次活动已结束，非常感谢您的参与。')
                clearInterval(stop);
            } else {
                $('#end_timer').text(timerTmpe.format(timing))
            }
        }

        var countDown = {
            time_server: new Date().getTime(),
            time_end: $('#end_timer').data('endtiem')
        }
        showCountDown(countDown);
        var stop = setInterval(function () {
            showCountDown(countDown);
        }, 1000);
    }

    $(function () {
        init();
        endCountdown();
    })
})(window.jQuery, window.oh);
<|endoftext|>