')
+ if (test.match('')) {
+ test = test.split('')
+ if (typeof test[0] !== 'undefined') {
+ return test[0]
+ }
+ }
+ return test
+ }
+
+ categories(data) {
+ if (!data) {
+ return
+ }
+ const categories = []
+ data.forEach((category, i) => {
+ categories.push(
+
+ {category}
+
+ )
+ })
+ return categories
+ }
+
+
+
+ tags(data) {
+ if (!data) {
+ return
+ }
+ const tags = []
+ data.forEach((tag, i) => {
+ tags.push(
+
+ #{tag}
+
+ )
+ })
+ return tags
+ }
+
+ render() {
+ const { site, data, isIndex } = this.props
+ const postNode = get(data, 'frontmatter')
+ const title = get(data, 'frontmatter.title')
+ const path = get(data, 'frontmatter.path')
+ const date = get(data, 'frontmatter.date')
+ const desc = get(data, 'frontmatter.description') || get(data, 'html')
+ const cate =
+ get(data, 'frontmatter.category') || get(data, 'frontmatter.categories')
+ const tag =
+ get(data, 'frontmatter.tag') || get(data, 'frontmatter.tags')
+ const categories = cate ? this.categories(cate) : ''
+ const tags = tag ? this.tags(tag) : ''
+ const description = isIndex ? this.description(desc) : desc
+ const more = isIndex ? this.more(desc, path) : ''
+ const footer = isIndex ? '' :
+ return (
+
+
+
+
+
+
{title}
+
{date}
+
+
+
+
+
+
+
+
+
+ )
+ }
+}
+
+export default SitePost
diff --git a/pool/shard010/JavaScript/0068436_LearnGallery.js b/pool/shard010/JavaScript/0068436_LearnGallery.js
new file mode 100644
index 0000000000000000000000000000000000000000..bbcee917d1ba4f1f6cf5b64ceb9cdfeb5184e951
--- /dev/null
+++ b/pool/shard010/JavaScript/0068436_LearnGallery.js
@@ -0,0 +1,92 @@
+// Copyright 2014 The Oppia Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS-IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+/**
+ * @fileoverview Data and controllers for the Oppia learners' gallery page.
+ *
+ * @author sll@google.com (Sean Lip)
+ */
+
+function LearnGallery($scope, $http, $rootScope, warningsData, oppiaRequestCreator) {
+ $scope.learnGalleryDataUrl = '/learnhandler/data';
+ $scope.categoryList = [];
+ $scope.categories = {};
+ // The default is to show only explorations that have moved out of beta or
+ // that this user has been invited to playtest.
+ $scope.areAllBetaExplorationsShown = false;
+
+ $scope.displayedCategoryList = [];
+ $scope.displayedCategories = {};
+
+ $rootScope.loadingMessage = 'Loading';
+
+ // Retrieves gallery data from the server.
+ $http.get($scope.learnGalleryDataUrl).success(function(data) {
+ $scope.categories = data.categories;
+
+ // Put the category names in a list.
+ for (var category in $scope.categories) {
+ $scope.categoryList.push(category);
+ }
+
+ $scope.initializeDisplay();
+
+ $rootScope.loadingMessage = '';
+ }).error(function(data) {
+ warningsData.addWarning(data.error || 'Error communicating with server.');
+ });
+
+ // TODO(sll): If there is no difference between the two types of displays,
+ // hide the 'Show All' button.
+ $scope.initializeDisplay = function() {
+ if ($scope.areAllBetaExplorationsShown) {
+ $scope.displayedCategoryList = angular.copy($scope.categoryList);
+ $scope.displayedCategories = angular.copy($scope.categories);
+ } else {
+ $scope.displayedCategoryList = [];
+ $scope.displayedCategories = {};
+
+ for (var category in $scope.categories) {
+ var validExplorationCount = 0;
+ var filteredExplorations = {};
+ for (var exploration in $scope.categories[category]) {
+ if ($scope.categories[category][exploration].to_playtest ||
+ $scope.categories[category][exploration].is_publicized) {
+ filteredExplorations[exploration] = $scope.categories[category][exploration];
+ validExplorationCount++;
+ }
+ }
+ if (validExplorationCount > 0) {
+ $scope.displayedCategories[category] = filteredExplorations;
+ $scope.displayedCategoryList.push(category);
+ }
+ }
+ }
+ };
+
+ $scope.showBetaExplorations = function() {
+ $scope.areAllBetaExplorationsShown = true;
+ $scope.initializeDisplay();
+ };
+
+ $scope.hideBetaExplorations = function() {
+ $scope.areAllBetaExplorationsShown = false;
+ $scope.initializeDisplay();
+ };
+}
+
+/**
+ * Injects dependencies in a way that is preserved by minification.
+ */
+LearnGallery.$inject = ['$scope', '$http', '$rootScope', 'warningsData', 'oppiaRequestCreator'];
diff --git a/pool/shard010/JavaScript/0068437_detach.js b/pool/shard010/JavaScript/0068437_detach.js
new file mode 100644
index 0000000000000000000000000000000000000000..5e612b186d0a4c91ab9cd001ef4a979fef26d98d
--- /dev/null
+++ b/pool/shard010/JavaScript/0068437_detach.js
@@ -0,0 +1,15 @@
+"use strict";
+
+const setImmediate = require('../async/setImmediate');
+
+module.exports = function(fn, bind) {
+ var args = [].slice.call(arguments, 2);
+
+ return function() {
+ args.push.apply(args, arguments);
+ setImmediate(function() {
+ if(fn)
+ return fn.apply(bind, args);
+ });
+ };
+};
diff --git a/pool/shard010/JavaScript/0068438_webpack-protocol.js b/pool/shard010/JavaScript/0068438_webpack-protocol.js
new file mode 100644
index 0000000000000000000000000000000000000000..941ca4f7bb94b5701782e5a5f6159e13518188a7
--- /dev/null
+++ b/pool/shard010/JavaScript/0068438_webpack-protocol.js
@@ -0,0 +1,45 @@
+'use strict';
+
+var projectRelative = require('./project-relative');
+
+/**
+ * Codec for relative paths with respect to the context directory, preceded by a webpack:// protocol.
+ * @type {{name:string, decode: function, encode: function, root: function}}
+ */
+module.exports = {
+ name : 'webpackProtocol',
+ decode: decode,
+ encode: encode,
+ root : root
+};
+
+/**
+ * Decode the given uri.
+ * @this {{options: object}} A loader or compilation
+ * @param {string} uri A source uri to decode
+ * @returns {boolean|string} False where unmatched else the decoded path
+ */
+function decode(uri) {
+ /* jshint validthis:true */
+ var analysis = /^webpack:\/{2}(.*)$/.exec(uri);
+ return !!analysis && projectRelative.decode.call(this, analysis[1]);
+}
+
+/**
+ * Encode the given file path.
+ * @this {{options: object}} A loader or compilation
+ * @param {string} absolute An absolute file path to encode
+ * @returns {string} A uri
+ */
+function encode(absolute) {
+ /* jshint validthis:true */
+ return 'webpack://' + projectRelative.encode.call(this, absolute);
+}
+
+/**
+ * The source-map root where relevant.
+ * @this {{options: object}} A loader or compilation
+ * @returns {string|undefined} The source-map root applicable to any encoded uri
+ */
+function root() {
+}
diff --git a/pool/shard010/JavaScript/0068439_DeleteFigure-test.js b/pool/shard010/JavaScript/0068439_DeleteFigure-test.js
new file mode 100644
index 0000000000000000000000000000000000000000..2d52dc4fbc548f9b3178cc8a98fae9c4cb230655
--- /dev/null
+++ b/pool/shard010/JavaScript/0068439_DeleteFigure-test.js
@@ -0,0 +1,39 @@
+import { fromJS } from 'immutable';
+import DeleteFigure from '../DeleteFigure';
+
+describe('DeleteFigure', () => {
+ let content;
+
+ beforeEach(() => {
+ content = {
+ "sections": [
+ {
+ "id": "de5f",
+ "blocks": [
+ {
+ "id": "c6a8",
+ "type": "figure",
+ "src": "http://example.com.png",
+ "text": "Caption text"
+ }
+ ]
+ }
+ ]
+ };
+ });
+
+ describe('#execute', () => {
+ it('should convert a figure to a paragraph', () => {
+ const manager = new DeleteFigure(fromJS(content));
+
+ const guids = { anchor: 'c6a8', focus: 'c6a8' };
+ const offsets = { anchor: 0, focus: 0 };
+ const result = manager.execute(guids, offsets);
+
+ const blocks = result.content.toJS().sections[0].blocks;
+ expect(blocks.length).to.equal(1);
+ expect(blocks[0].text).to.equal('');
+ expect(blocks[0].type).to.equal('p');
+ });
+ });
+});
diff --git a/pool/shard010/JavaScript/0068440_index.js b/pool/shard010/JavaScript/0068440_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..d5600b0fb733dce7e2f9daf012ffe57693b2f691
--- /dev/null
+++ b/pool/shard010/JavaScript/0068440_index.js
@@ -0,0 +1,30 @@
+import { DLS_ROOT } from "../locators";
+import {
+ SUBMENU,
+ SCROLL_BLOCK,
+ MENU_DIVIDER,
+ SEGMENT_TITLE,
+ MENU,
+ FULLSCREEN_MENU,
+ MENU_ITEM,
+} from "./locators";
+
+// component preview locators
+export const submenu = () => cy.get(SUBMENU);
+export const submenuBlock = () => cy.get(SUBMENU).find("ul");
+export const innerMenu = (index, htmlProp) =>
+ submenuBlock().find(`li:nth-child(${index})`).find(htmlProp);
+export const scrollBlock = () => cy.get(SUBMENU).find(SCROLL_BLOCK);
+export const lastSubmenuElement = (htmlProp) =>
+ submenuBlock().find(htmlProp).last();
+export const menuDivider = () => cy.get(MENU_DIVIDER);
+export const segmentTitle = () => cy.get(SEGMENT_TITLE);
+export const menuComponent = (index) =>
+ cy.get(MENU).first().find(`li:nth-child(${index})`);
+export const submenuItem = (index) =>
+ menuComponent(index).find(SUBMENU).find("ul > li");
+export const menuCanvas = () => cy.get(DLS_ROOT);
+export const fullscreenMenu = (index) =>
+ cy.get(FULLSCREEN_MENU).find("div").eq(index);
+export const menu = () => cy.get(MENU);
+export const menuItem = () => cy.get(MENU_ITEM);
diff --git a/pool/shard010/JavaScript/0068443_ButtonRepeat.react.js b/pool/shard010/JavaScript/0068443_ButtonRepeat.react.js
new file mode 100644
index 0000000000000000000000000000000000000000..4a10d941f1cb7cefaff70733cf056cfe042ff89f
--- /dev/null
+++ b/pool/shard010/JavaScript/0068443_ButtonRepeat.react.js
@@ -0,0 +1,69 @@
+import React, { Component } from 'react';
+import InlineSVG from 'svg-inline-react';
+import classnames from 'classnames';
+import { connect } from 'react-redux';
+
+import lib from '../../lib';
+
+const svgMap = {
+ one: require('../../../images/icons/player-repeat-one.svg'),
+ all: require('../../../images/icons/player-repeat.svg'),
+ default: require('../../../images/icons/player-repeat.svg')
+};
+
+class ButtonRepeat extends Component {
+
+ static propTypes = {
+ repeat: React.PropTypes.string,
+ repeatTrack: React.PropTypes.func,
+ }
+
+ constructor(props) {
+ super(props);
+ }
+
+ render() {
+ const svg = svgMap[this.props.repeat] || svgMap.default;
+ const buttonClasses = classnames('button repeat',{
+ active: this.props.repeat === 'one' || this.props.repeat === 'all'
+ });
+
+ const svgClasses = classnames('icon', {
+ 'repeat-one': this.props.repeat === 'one',
+ 'repeat': this.props.repeat !== 'one'
+ });
+
+ return (
+
+
+
+ );
+ }
+
+ toggleRepeat = () => {
+ let repeat = 'none';
+
+ switch (this.props.repeat) {
+
+ case 'none':
+ repeat = 'all';
+ break;
+ case 'all':
+ repeat = 'one';
+ break;
+ case 'one':
+ repeat = 'none';
+ break;
+ }
+
+ this.props.repeatTrack(repeat);
+ }
+}
+
+const stateToProps = () => ({});
+
+const dispatchToProps = {
+ repeatTrack: lib.actions.player.repeat
+};
+
+export default connect(stateToProps, dispatchToProps)(ButtonRepeat);
diff --git a/pool/shard010/JavaScript/0068449_difficultySetting.js b/pool/shard010/JavaScript/0068449_difficultySetting.js
new file mode 100644
index 0000000000000000000000000000000000000000..22ebd66617d1e082faf3324c384abdad822eef2c
--- /dev/null
+++ b/pool/shard010/JavaScript/0068449_difficultySetting.js
@@ -0,0 +1,15 @@
+var difficulty = localStorage.getItem('difficulty') || 'easy' //Check for a cached difficulty or default to 'easy'
+
+function selectDifficulty(level) {
+ if (newGame == false) {
+ difficulty = level; //Set the difficulty to the selected level
+ $("li > button").attr("class", "pure-button inactive"); //"Gray out" the difficulty buttons
+ $("#" + level).attr("class", "pure-button" + " " + level); //Colorize the selected level
+ localStorage.setItem('difficulty', level); //Cache the difficulty level
+ };
+ reloadIfWinner(); //Reload the game if this function is called after a winner is determined
+};
+
+function previousDifficulty() {
+ selectDifficulty(difficulty);
+};
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068451_index.js b/pool/shard010/JavaScript/0068451_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..79d501756b0ff7ce92dc9a6a1295e47cd62838dc
--- /dev/null
+++ b/pool/shard010/JavaScript/0068451_index.js
@@ -0,0 +1,89 @@
+import React from 'react/addons'
+const { CSSTransitionGroup, PureRenderMixin } = React.addons
+import { Link, RouteHandler, Navigation } from 'react-router'
+
+import Sidebar from 'components/Sidebar'
+import Albums from 'components/Albums'
+
+import './layout.scss'
+
+const Layout = React.createClass({
+
+ mixins: [ Navigation, PureRenderMixin ],
+
+ getInitialState() {
+ let widths = this.getWidth(200)
+ let styles = {
+ cursor: 'default'
+ }
+ let resizing = false
+ return {widths, styles, resizing}
+ },
+
+ getWidth(sidebarWidth = this.state.widths.sidebar) {
+ let w = document.body.clientWidth
+ return {
+ sidebar: sidebarWidth,
+ main: w - sidebarWidth
+ }
+ },
+
+ componentDidMount() {
+ this.setState({widths: this.getWidth()})
+ window.addEventListener('resize', () => {
+ this.setState({widths: this.getWidth()})
+ })
+ },
+
+ sidebarRight() {
+ let sidebar = this.refs.sidebar.getDOMNode()
+ return sidebar.offsetLeft + sidebar.offsetWidth
+ },
+
+ mouseMove(event) {
+ if (this.state.resizing) {
+ let width = this.refs.sidebar.getDOMNode().offsetWidth
+ let newWidth = event.clientX
+ let widths = this.getWidth(newWidth)
+ this.setState({widths})
+ } else {
+ if (this.sidebarRight() === event.clientX) {
+ this.setState({styles: {
+ cursor: 'col-resize'
+ }})
+ } else {
+ this.setState({styles: {
+ cursor: 'default'
+ }})
+ }
+ }
+ },
+
+ mouseDown() {
+ if (this.sidebarRight() !== event.clientX) return
+ this.setState({resizing: true})
+
+ },
+
+ mouseUp() {
+ if (!this.state.resizing) return
+ this.setState({resizing: false, widths: this.getWidth()})
+ },
+
+ render() {
+ return (
+
+
+
+
+ );
+ }
+
+});
+
+
+export default Layout
diff --git a/pool/shard010/JavaScript/0068452_sanitytest.js b/pool/shard010/JavaScript/0068452_sanitytest.js
new file mode 100644
index 0000000000000000000000000000000000000000..d41a32d7c65b6b81770512b34f13339e9a0bbc1b
--- /dev/null
+++ b/pool/shard010/JavaScript/0068452_sanitytest.js
@@ -0,0 +1,146 @@
+//
+// simple testing interface
+// written by Einar Lielmanis, einar@beautifier.io
+//
+// usage:
+//
+// var t = new SanityTest(function (x) { return x; }, 'my function');
+// t.expect('input', 'output');
+// t.expect('a', 'a');
+// output_somewhere(t.results()); // good for , html safe-ish
+// alert(t.results_raw()); // html unescaped
+
+function SanityTest(func, name_of_test) {
+ 'use strict';
+
+ var test_func = func || function(x) {
+ return x;
+ };
+
+ var test_name = name_of_test || '';
+
+ var n_failed = 0;
+ var n_succeeded = 0;
+
+ var failures = [];
+
+ this.test_function = function(func, name) {
+ test_func = func;
+ test_name = name || '';
+ };
+
+ this.get_exitcode = function() {
+ return n_succeeded === 0 || n_failed !== 0 ? 1 : 0;
+ };
+
+ this.expect = function(parameters, expected_value) {
+ // multi-parameter calls not supported (I don't need them now).
+ var result = test_func(parameters);
+ // proper array checking is a pain. i'll maybe do it later, compare strings representations instead
+ if ((result === expected_value) || (expected_value instanceof Array && result.join(', ') === expected_value.join(', '))) {
+ n_succeeded += 1;
+ return true;
+ } else {
+ n_failed += 1;
+ failures.push([test_name, parameters, expected_value, result]);
+ return false;
+ }
+ };
+
+
+ this.results_raw = function() {
+ var results = '';
+ if (n_failed === 0) {
+ if (n_succeeded === 0) {
+ results = 'No tests run.';
+ } else {
+ results = 'All ' + n_succeeded + ' tests passed.';
+ }
+ } else {
+ for (var i = 0; i < failures.length; i++) {
+ var f = failures[i];
+ if (f[0]) {
+ f[0] = f[0] + ' ';
+ }
+ results += '==== ' + f[0] + '============================================================\n';
+ results += '---- input -------\n' + this.prettyprint(f[1]) + '\n';
+ results += '---- expected ----\n' + this.prettyprint(f[2]) + '\n';
+ results += '---- output ------\n' + this.prettyprint(f[3]) + '\n';
+ results += '---- expected-ws ------\n' + this.prettyprint_whitespace(f[2]) + '\n';
+ results += '---- output-ws ------\n' + this.prettyprint_whitespace(f[3]) + '\n';
+ results += '================================================================\n\n';
+ }
+ results += n_failed + ' tests failed.\n';
+ }
+ return results;
+ };
+
+
+ this.results = function() {
+ return this.lazy_escape(this.results_raw());
+ };
+
+ this.prettyprint_whitespace = function(something, quote_strings) {
+ return (this.prettyprint(something, quote_strings)
+ .replace(/\r\n/g, '\\r\n')
+ .replace(/\n/g, '\\n\n')
+ .replace(/\r/g, '\\r\n')
+ .replace(/ /g, '_')
+ .replace(/\t/g, '===|'));
+ };
+
+ this.prettyprint = function(something, quote_strings) {
+ var type = typeof something;
+ switch (type.toLowerCase()) {
+ case 'string':
+ if (quote_strings) {
+ return "'" + something.replace("'", "\\'") + "'";
+ }
+ return something;
+ case 'number':
+ return '' + something;
+ case 'boolean':
+ return something ? 'true' : 'false';
+ case 'undefined':
+ return 'undefined';
+ case 'object':
+ if (something instanceof Array) {
+ var x = [];
+ var expected_index = 0;
+ for (var k in something) {
+ if (k === expected_index) {
+ x.push(this.prettyprint(something[k], true));
+ expected_index += 1;
+ } else {
+ x.push('\n' + k + ': ' + this.prettyprint(something[k], true));
+ }
+ }
+ return '[' + x.join(', ') + ']';
+ }
+ return 'object: ' + something;
+ default:
+ return type + ': ' + something;
+ }
+ };
+
+
+ this.lazy_escape = function(str) {
+ return str.replace(//g, '>').replace(/\n/g, ' ');
+ };
+
+
+ this.log = function() {
+ if (window.console) {
+ if (console.firebug) {
+ console.log.apply(console, Array.prototype.slice.call(arguments));
+ } else {
+ console.log.call(console, Array.prototype.slice.call(arguments));
+ }
+ }
+ };
+
+}
+
+if (typeof module !== 'undefined' && module.exports) {
+ module.exports = SanityTest;
+}
diff --git a/pool/shard010/JavaScript/0068453_streamdir.test.js b/pool/shard010/JavaScript/0068453_streamdir.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..8f1c3d6cd0960f3b4f1588cecd8f9a0aee96bc54
--- /dev/null
+++ b/pool/shard010/JavaScript/0068453_streamdir.test.js
@@ -0,0 +1,19 @@
+require("chai").should();
+
+var streamdir = require("../");
+
+describe("streamdir", function(){
+
+ it("should stream the contents of a directory", function(done){
+ var s = streamdir(__dirname);
+ s.on("data", function(fname){
+ fname.should.equal("streamdir.test.js");
+ done();
+ });
+ });
+
+ it("should fail without a path", function(){
+ streamdir().should.equal(false);
+ });
+
+});
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068460_isArguments.js b/pool/shard010/JavaScript/0068460_isArguments.js
new file mode 100644
index 0000000000000000000000000000000000000000..09c9c62bc436c80a58cb54e5013cb9077647b745
--- /dev/null
+++ b/pool/shard010/JavaScript/0068460_isArguments.js
@@ -0,0 +1,40 @@
+/*jslint browser: true, devel: true, node: true, ass: true, nomen: true, unparam: true, indent: 4 */
+
+/**
+ * @license
+ * Copyright (c) 2015 The ExpandJS authors. All rights reserved.
+ * This code may only be used under the BSD style license found at https://expandjs.github.io/LICENSE.txt
+ * The complete set of authors may be found at https://expandjs.github.io/AUTHORS.txt
+ * The complete set of contributors may be found at https://expandjs.github.io/CONTRIBUTORS.txt
+ */
+(function () {
+ "use strict";
+
+ var lodash = require('lodash'),
+ isVoid = require('../tester/isVoid'),
+ xnor = require('../operator/xnor');
+
+ /**
+ * Checks if `value` is instance of `Arguments`.
+ *
+ * ```js
+ * XP.isArguments(function() { return arguments; }());
+ * // => true
+ *
+ * XP.isArguments(function() { return arguments; }(), true);
+ * // => false
+ *
+ * XP.isArguments([1, 2, 3]);
+ * // => false
+ * ```
+ *
+ * @function isArguments
+ * @param {*} value The value to check.
+ * @param {boolean} [notEmpty] Specifies if `value` must be not empty.
+ * @returns {boolean} Returns `true` or `false` accordingly to the check.
+ */
+ module.exports = function isArguments(value, notEmpty) {
+ return lodash.isArguments(value) && (isVoid(notEmpty) || xnor(value.length, notEmpty));
+ };
+
+}());
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068461_index.js b/pool/shard010/JavaScript/0068461_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..90d2ad9baa0c65b7740f74184ce34c820646c016
--- /dev/null
+++ b/pool/shard010/JavaScript/0068461_index.js
@@ -0,0 +1,64 @@
+"use strict";
+
+var grep = require("../grep")
+var into = require("reducers/into")
+
+var cities = {
+ "kiev": 1985,
+ "tbilisi": 1985,
+ "amsterdam": 2008,
+ "paris": 2010,
+ "san francisco": 2012
+}
+
+exports["test grep"] = function(assert) {
+ assert.deepEqual(into(grep("", Object.keys(cities))), [
+ [ 'kiev', 0.75 ],
+ [ 'tbilisi', 0.75 ],
+ [ 'amsterdam', 0.75 ],
+ [ 'paris', 0.75 ],
+ [ 'san francisco', 0.75 ]
+ ], "no input gives 0.75 match on all")
+
+ assert.deepEqual(into(grep("t", Object.keys(cities))), [
+ [ 'tbilisi', 0.8444911182523067 ],
+ [ 'amsterdam', 0.6833333333333333 ]
+ ], "more matches scores better")
+
+ assert.deepEqual(into(grep("nope", Object.keys(cities))), [],
+ "no matches")
+}
+
+exports["test grep with serializer"] = function(assert) {
+ var data = Object.keys(cities).reduce(function(data, name) {
+ data.push({ key: name, value: cities[name] })
+ return data
+ }, [])
+
+ function serialize(value) {
+ return value.key + "\n" + value.value
+ }
+
+ assert.deepEqual(into(grep("", data, serialize)), [
+ [ { key: 'kiev', value: 1985 }, 0.75 ],
+ [ { key: 'tbilisi', value: 1985 }, 0.75 ],
+ [ { key: 'amsterdam', value: 2008 }, 0.75 ],
+ [ { key: 'paris', value: 2010 }, 0.75 ],
+ [ { key: 'san francisco', value: 2012 }, 0.75 ]
+ ], "no input gives 0.75 match on all")
+
+ assert.deepEqual(into(grep("t", data, serialize)), [
+ [ { key: 'tbilisi', value: 1985 }, 0.8221687836487032 ],
+ [ { key: 'amsterdam', value: 2008 }, 0.7203867390495347 ]
+ ], "more matches scores better")
+
+ assert.deepEqual(into(grep("nope", data, serialize)), [],
+ "no matches")
+
+ assert.deepEqual(into(grep("19", data, serialize)), [
+ [ { key: 'kiev', value: 1985 }, 0.6178511301977578 ],
+ [ { key: 'tbilisi', value: 1985 }, 0.5520620726159657 ]
+ ], "values are also searched if they are serialized")
+}
+
+require("test").run(exports)
diff --git a/pool/shard010/JavaScript/0068463_activityPreview_875b3c8e.js b/pool/shard010/JavaScript/0068463_activityPreview_875b3c8e.js
new file mode 100644
index 0000000000000000000000000000000000000000..52ee5d184f722f89bab61b025e109acac291c655
--- /dev/null
+++ b/pool/shard010/JavaScript/0068463_activityPreview_875b3c8e.js
@@ -0,0 +1,141 @@
+ var session=getSession();
+ var isDataReady = false;
+ var isRolling = false;
+ var result;
+ var data;
+
+ function rotateIt(i){
+ $("#wheelcanvas").rotate({
+ angle:0,
+ animateTo:3600 - i * (360 / 6),
+ duration:8000,
+ callback:function (){
+ console.log("rotateIt finished");
+ isRolling = false;
+ }
+ });
+ }
+
+ function RandomOneCoupon(){
+ var num=Math.floor(Math.random()*6 + 1);
+ rotateIt(num);
+ }
+
+ function drawRoulettePrizes(prizes){
+ // make it not smaller than 6
+ var len = prizes.length;
+ if (len <= 0) return;
+ while(prizes.length < 6){
+ for (var i = 0; i < len; i++){
+ prizes.push(prizes[i]);
+ }
+ }
+
+ var canvas = document.getElementById("wheelcanvas");
+ var ctx = canvas.getContext("2d");
+ var img = document.getElementById("imgFreeCoupon");
+ // var arc = Math.PI / (prizes.length/2);
+ var arc = Math.PI / (6/2);
+ var startAngle = 0;
+ for(var i = 0; i < 6; i++){
+ ctx.font = 'bold 20px Microsoft YaHei';
+ ctx.fillStyle = i % 2 ? "#f46747" : "#ffffff";
+ ctx.strokeStyle = "#FFBE04";
+
+ ctx.save();
+ var angle = startAngle + i * arc;
+ ctx.translate(canvas.width/2, canvas.height/2);
+ ctx.rotate(angle);
+
+ // ctx.fillText(prizes[i].coupon_name, -ctx.measureText(prizes[i].coupon_name).width/2, -200);
+ ctx.fillText(prizes[i].coupon_name, -ctx.measureText(prizes[i].coupon_name).width/2, -130);
+ var width = canvas.width * 0.18;
+ var height = width * 0.36
+ var x = - width / 2;
+ // var y = - height / 2 - 160;
+ var y = - height / 2 - 100;
+ img.onload = function(){
+ ctx.drawImage(img, x, y, width, height);
+ };
+ ctx.drawImage(img, x, y, width, height);
+ ctx.restore();
+ }
+ }
+
+ function drawRoulette(){
+ var canvas = document.getElementById("wheelcanvas");
+ if (! canvas.getContext) {
+ console.log("Error in canvas.getContext");
+ return;
+ }
+
+ var ctx = canvas.getContext("2d");
+ ctx.imageSmoothingEnabled = false;
+ ctx.imageSmoothingEnabled = false;
+
+ var imgWheel = document.getElementById("imgWheel");
+ ctx.drawImage(imgWheel, 0, 0, canvas.width, canvas.height);
+}
+
+ $(window).on("load",function(){
+ drawRoulette();
+ requestLuckyDrawData();
+ });
+
+ function autoScrollHorizontal(obj){
+ var objLi = $(obj).find("li");
+ var width = objLi.width()
+ var marginRight = parseInt(objLi.css("marginRight"));
+ console.log("width=" + width + ", marginRight=" + marginRight);
+ $(obj).animate({marginLeft:- width - marginRight}, 500, function(){
+ $(this).css({marginLeft:"0px"}).find("li:first").appendTo(this);
+ });
+}
+
+
+ function drawRoulette(){
+ var canvas = document.getElementById("wheelcanvas");
+ if (! canvas.getContext) {
+ console.log("Error in canvas.getContext");
+ return;
+ }
+ var ctx = canvas.getContext("2d");
+ ctx.imageSmoothingEnabled = false;
+ ctx.imageSmoothingEnabled = false;
+ var imgWheel = document.getElementById("imgWheel");
+ ctx.drawImage(imgWheel, 0, 0, canvas.width, canvas.height);
+}
+
+ function requestLuckyDrawData(){
+ var key=getUrlPara(location.href,"key");
+ $.ajax({
+ url: globalData.apiBusiness + 'LotteryView.aspx',
+ dataType: 'json',
+ data: {
+ "session": session,
+ "LotteryKey":key
+ },
+ success: function(res) {
+ if (res.status == 0) {
+ document.title=res.LotteryName;
+ result=res;
+ var html = template('couponItem', res.data);
+ $('.couponList').html(html);
+ autoResizeCouponList();
+ drawRoulettePrizes(res.data.CouponList);
+ setInterval('autoScrollHorizontal(".couponList")',3000);
+ } else {
+ showTip("暂无优惠券数据");
+ return;
+ }
+ }
+ });
+ }
+
+ function autoResizeCouponList(){
+ var swidth=$("ul.couponList li:first").width();
+ var num=$("ul.couponList li").length;
+ var totalWidth=swidth*num;
+ totalWidth=totalWidth+swidth;
+ $("ul.couponList").css("width",totalWidth+"px");
+ }
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068464_deviceMeasurementApiSpecs.js b/pool/shard010/JavaScript/0068464_deviceMeasurementApiSpecs.js
new file mode 100644
index 0000000000000000000000000000000000000000..ef567347d95abf28c5eb3fa726a635fc33ce674a
--- /dev/null
+++ b/pool/shard010/JavaScript/0068464_deviceMeasurementApiSpecs.js
@@ -0,0 +1,210 @@
+"use strict";
+var proxyquire = require('proxyquire');
+var expressTesting = require('./expressTesting');
+
+var chai = require("chai");
+var sinon = require('sinon');
+var sinonChai = require('sinon-chai');
+/*jshint -W079 */
+var expect = chai.expect;
+chai.use(sinonChai);
+
+describe('Device Measurements Api', function () {
+ var sut, cloudDeviceFactory, loadDeviceCallbackArgs, loadProductDescriptorCallbackArgs, saveProductDescriptorCallbackArgs, deviceRepositoryStub;
+ beforeEach(function () {
+ loadDeviceCallbackArgs = [];
+ deviceRepositoryStub = {
+ findBy: function loadCloudDeviceFromStub(productDescriptorId, serialNumber, callback) { callback.apply(null, loadDeviceCallbackArgs); }
+ };
+
+ loadProductDescriptorCallbackArgs = [];
+ var productDescriptorRepositoryStub = {
+ filterBy: function loadCloudProductDescriptorFromStub(vendor, productType, callback) { callback.apply(null, loadProductDescriptorCallbackArgs); }
+ };
+
+ proxyquire.noCallThru();
+
+ cloudDeviceFactory = proxyquire('../../cloudDeviceFactory', {
+ './repositories/cloudDeviceRepository': deviceRepositoryStub,
+ './repositories/cloudProductDescriptorRepository': productDescriptorRepositoryStub
+ });
+
+ sut = proxyquire('../../routes/deviceMeasurementsApi', {
+ '../cloudDeviceFactory': cloudDeviceFactory
+ });
+ });
+ describe('When requesting device measurements with serial padded with leading zeroes', function () {
+ var next, res, req;
+ beforeEach(function (done) {
+ req = expressTesting.generateRequestStub(
+ 'application/vnd.linn.device-measurements+xml; version=4',
+ {
+ vendor: 'linn',
+ productType: 'speaker',
+ serialNumber: '001234'
+ }
+ );
+ res = expressTesting.generateResponseStub(done);
+
+ next = function(error) {
+ res.statusCode = error.status;
+ done();
+ };
+
+ sinon.spy(cloudDeviceFactory, 'create');
+
+ loadProductDescriptorCallbackArgs[1] = [ { id: '1cfdb6aa-dc7f-4e1e-a983-7ed19659866c'} ];
+ loadDeviceCallbackArgs[1] = { serialNumber: '1234', lastUpdate: '2015-02-18T04:57:56Z' };
+
+ sut.get(req, res, next);
+ });
+ it('Should return ok', function () {
+ expect(res.statusCode).to.eql(200);
+ });
+ it('Should call device factory with unpadded serial number', function () {
+ expect(cloudDeviceFactory.create).to.have.been.calledWith('linn', 'speaker', '1234');
+ });
+ it('Should return xml', function () {
+ expect(res.send).to.have.been.called;
+ expect(res.send.args[0][0]).to.be.eql("\n\n 1234 \n \n 2015-02-18T04:57:56Z \n ");
+ });
+ });
+ describe('When requesting device measurements with alphanumeric serial as XML', function () {
+ var next, res, req;
+ beforeEach(function (done) {
+ req = expressTesting.generateRequestStub(
+ 'application/vnd.linn.device-measurements+xml; version=4',
+ {
+ vendor: 'linn',
+ productType: 'speaker',
+ serialNumber: 'ABCDEFG'
+ }
+ );
+ res = expressTesting.generateResponseStub(done);
+
+ next = function(error) {
+ res.statusCode = error.status;
+ done();
+ };
+
+ sinon.spy(cloudDeviceFactory, 'create');
+
+ loadProductDescriptorCallbackArgs[1] = [ { id: '1cfdb6aa-dc7f-4e1e-a983-7ed19659866c'} ];
+ loadDeviceCallbackArgs[1] = { serialNumber: 'ABCDEFG', lastUpdate: '2015-02-18T04:57:56Z' };
+
+ sut.get(req, res, next);
+ });
+ it('Should return ok', function () {
+ expect(res.statusCode).to.eql(200);
+ });
+ it('Should call device factory with unpadded serial number', function () {
+ expect(cloudDeviceFactory.create).to.have.been.calledWith('linn', 'speaker', 'ABCDEFG');
+ });
+ it('Should return xml', function () {
+ expect(res.send).to.have.been.called;
+ expect(res.send.args[0][0]).to.be.eql("\n\n ABCDEFG \n \n 2015-02-18T04:57:56Z \n ");
+ });
+ });
+ describe('When requesting device measurements as XML', function () {
+ var next, res, req;
+ beforeEach(function (done) {
+ req = expressTesting.generateRequestStub(
+ 'application/vnd.linn.device-measurements+xml; version=4',
+ {
+ vendor: 'linn',
+ productType: 'speaker',
+ serialNumber: '123456'
+ }
+ );
+ res = expressTesting.generateResponseStub(done);
+
+ next = function(error) {
+ res.statusCode = error.status;
+ done();
+ };
+
+ loadProductDescriptorCallbackArgs[1] = [ { id: '1cfdb6aa-dc7f-4e1e-a983-7ed19659866c'} ];
+ loadDeviceCallbackArgs[1] = { serialNumber: '123456', lastUpdate: '2015-02-18T04:57:56Z' };
+
+ sut.get(req, res, next);
+ });
+ it('Should return ok', function () {
+ expect(res.statusCode).to.eql(200);
+ });
+ it('Should return xml', function () {
+ expect(res.send).to.have.been.called;
+ expect(res.send.args[0][0]).to.be.eql("\n\n 123456 \n \n 2015-02-18T04:57:56Z \n ");
+ });
+ it('Should set Content-Type', function () {
+ expect(res.set).to.have.been.calledWith('Content-Type', 'application/vnd.linn.device-measurements+xml; version=4');
+ });
+ });
+ describe('When requesting device measurements with unsupported media type', function () {
+ var next, res, req;
+ beforeEach(function (done) {
+ req = expressTesting.generateRequestStub(
+ 'application/vnd.linn.device-measurements+json; version=1',
+ {
+ vendor: 'linn',
+ productType: 'speaker',
+ serialNumber: '123456'
+ }
+ );
+ res = expressTesting.generateResponseStub(done);
+
+ next = function(error) {
+ res.statusCode = error.status;
+ done();
+ };
+
+ loadProductDescriptorCallbackArgs[1] = [ { id: '1cfdb6aa-dc7f-4e1e-a983-7ed19659866c'} ];
+ loadDeviceCallbackArgs[1] = { serialNumber: '123456', lastUpdate: '2015-02-18T04:57:56Z' };
+
+ sut.get(req, res, next);
+ });
+ it('Should return ok', function () {
+ expect(res.statusCode).to.eql(406);
+ });
+ it('Should not return json', function () {
+ expect(res.json).not.to.have.been.called;
+ });
+ });
+ describe('When requesting device measurements as JSON', function () {
+ var next, res, req;
+ beforeEach(function (done) {
+ req = expressTesting.generateRequestStub(
+ 'application/vnd.linn.device-measurements+json; version=4',
+ {
+ vendor: 'linn',
+ productType: 'speaker',
+ serialNumber: '123456'
+ }
+ );
+ res = expressTesting.generateResponseStub(done);
+
+ next = function(error) {
+ res.statusCode = error.status;
+ done();
+ };
+
+ loadProductDescriptorCallbackArgs[1] = [ { id: '1cfdb6aa-dc7f-4e1e-a983-7ed19659866c'} ];
+ loadDeviceCallbackArgs[1] = { serialNumber: '123456', lastUpdate: '2015-02-18T04:57:56Z' };
+
+ sut.get(req, res, next);
+ });
+ it('Should return ok', function () {
+ expect(res.statusCode).to.eql(200);
+ });
+ it('Should return json', function () {
+ expect(res.json).to.have.been.called;
+ expect(res.json.args[0][0]).to.be.eql({
+ "components": [],
+ "lastUpdate": "2015-02-18T04:57:56Z",
+ "serialNumber": "123456"
+ });
+ });
+ it('Should set Content-Type', function () {
+ expect(res.set).to.have.been.calledWith('Content-Type', 'application/vnd.linn.device-measurements+json; version=4');
+ });
+ });
+});
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068468_test_async_comment_loading.js b/pool/shard010/JavaScript/0068468_test_async_comment_loading.js
new file mode 100644
index 0000000000000000000000000000000000000000..66c00229788b089fe064f9f5530edd205d8ca3cc
--- /dev/null
+++ b/pool/shard010/JavaScript/0068468_test_async_comment_loading.js
@@ -0,0 +1,188 @@
+/* Copyright 2011-2012 Canonical Ltd. This software is licensed under the
+ * GNU Affero General Public License version 3 (see the file LICENSE). */
+
+YUI.add('lp.bugs.async_comments.test', function (Y) {
+
+ // Local aliases.
+ var Assert = Y.Assert,
+ ArrayAssert = Y.ArrayAssert;
+ var module = Y.lp.bugs.bugtask_index;
+ var suite = new Y.Test.Suite("Async comment loading tests");
+
+ var comments_markup =
+ "This is a comment
" +
+ "So is this
" +
+ "So is this
" +
+ "And this, too.
";
+
+
+ var tests = Y.namespace('lp.bugs.async_comments.test');
+ tests.suite = new Y.Test.Suite('Async Comment Tests');
+
+ tests.suite.add(new Y.Test.Case({
+ name: 'Basic async comment loading tests',
+
+ setUp: function() {
+ // Monkeypatch LP to avoid network traffic and to make
+ // some things work as expected.
+ Y.lp.client.Launchpad.prototype.named_post =
+ function(url, func, config) {
+ config.on.success();
+ };
+ LP = {
+ 'cache': {
+ 'bug': {
+ self_link: "http://bugs.example.com/bugs/1234"
+ },
+ 'context': {
+ self_link: "http://bugs.example.com/bugs/1234"
+ }
+ }
+ };
+ // Some tests monkey-patch load_more_comments, so we save it
+ // here to restore it after each test.
+ this.old_load_more_comments = module.load_more_comments;
+
+ // Add some HTML to the page for us to use.
+ this.comments_container = Y.Node.create(
+ '');
+ this.add_comment_form_container = Y.Node.create(
+ '');
+ Y.one('body').appendChild(this.comments_container);
+ Y.one('body').appendChild(this.add_comment_form_container);
+ },
+
+ tearDown: function() {
+ this.comments_container.remove();
+ this.add_comment_form_container.remove();
+ // Restore load_more_comments in case it's been monkey-patched.
+ module.load_more_comments = this.old_load_more_comments;
+ },
+
+ /**
+ * load_more_comments() calls the passed batch_commments_url of the
+ * current bug task and loads more comments from it.
+ */
+ test_load_more_comments_loads_more_comments: function() {
+ var mockio = new Y.lp.testing.mockio.MockIo();
+ module.load_more_comments(
+ '', this.comments_container, mockio);
+ mockio.success({
+ responseText: comments_markup,
+ responseHeaders: {'Content-Type': 'application/xhtml'}
+ });
+ Assert.areEqual(
+ '' + comments_markup + '
',
+ this.comments_container.get('innerHTML'));
+ },
+
+ /**
+ * load_more_comments() sets the display style on the comment
+ * container to "block" so that its contents don't end up
+ * overflowing other parts of the page.
+ */
+ test_load_more_comments_sets_container_display_style: function() {
+ var mockio = new Y.lp.testing.mockio.MockIo();
+ module.load_more_comments(
+ '', this.comments_container, mockio);
+ mockio.success({
+ responseText: comments_markup,
+ responseHeaders: {'Content-Type': 'application/xhtml'}
+ });
+ Assert.areEqual(
+ 'block', this.comments_container.getStyle('display'));
+ },
+
+ /**
+ * load_more_comments() will show the "add comment" form once all
+ * the comments have loaded.
+ */
+ test_load_more_comments_shows_add_comment_form: function() {
+ var add_comment_form_container = Y.one(
+ '#add-comment-form-container');
+ Assert.isTrue(add_comment_form_container.hasClass('hidden'));
+ var mockio = new Y.lp.testing.mockio.MockIo();
+ module.load_more_comments(
+ '', this.comments_container, mockio);
+ mockio.success({
+ responseText: comments_markup,
+ responseHeaders: {'Content-Type': 'application/xhtml'}
+ });
+ Assert.isFalse(add_comment_form_container.hasClass('hidden'));
+ },
+
+ /**
+ * load_more_comments() will call itself recursively until there are
+ * no more comments to load.
+ */
+ test_load_more_comments_is_recursive: function() {
+ var next_batch_url_div =
+ 'https://launchpad.dev/
';
+ var more_comments_to_load_markup =
+ 'Here, have a comment. There are more where this came' +
+ 'from
';
+ var mockio = new Y.lp.testing.mockio.MockIo();
+ module.load_more_comments(
+ '', this.comments_container, mockio);
+ mockio.success({
+ responseText: next_batch_url_div + more_comments_to_load_markup,
+ responseHeaders: {'Content-Type': 'application/xhtml'}
+ });
+ mockio.success({
+ responseText: comments_markup,
+ responseHeaders: {'Content-Type': 'application/xhtml'}
+ });
+ var expected_markup =
+ '' + more_comments_to_load_markup + '
' +
+ '' + comments_markup + '
';
+ Assert.areEqual(
+ expected_markup, this.comments_container.get('innerHTML'));
+ },
+
+ /**
+ * setup_show_more_comments_link() will set the onClick handler for
+ * the link passed to it, and will also add a js-action class to the
+ * link.
+ */
+ test_setup_show_more_comments_link_jsifies_link: function() {
+ // We monkey-patch load_mode_comments so that we can use it to
+ // test whether the link has been JS-ified properly.
+ var load_more_comments_called = false;
+ module.load_more_comments = function() {
+ load_more_comments_called = true;
+ };
+ var link = Y.Node.create('A link ');
+ module.setup_show_more_comments_link(link, '#', Y.Node.create());
+ Assert.isTrue(link.hasClass('js-action'));
+ link.simulate('click');
+ Assert.isTrue(load_more_comments_called);
+ },
+
+ /**
+ * setup_load_comments() will call load_more_comments if it's told
+ * to.
+ */
+ test_setup_load_comments_calls_load_more_comments: function() {
+ // Monkey-patch load_more_comments for the purposes of this
+ // test.
+ var load_more_comments_called = false;
+ module.load_more_comments = function() {
+ load_more_comments_called = true;
+ };
+ // A parameterless call to setup_load_comments won't call
+ // load_more_comments.
+ module.setup_load_comments();
+ Assert.isFalse(load_more_comments_called);
+ // Passing true for the load_more_comments parameter will cause
+ // load_more_comments to be called.
+ module.setup_load_comments(true);
+ Assert.isTrue(load_more_comments_called);
+ }
+
+ }));
+}, '0.1', {
+ requires: ['test', 'lp.testing.helpers', 'test-console',
+ 'lp.bugs.bugtask_index', 'lp.client', 'event', 'node',
+ 'lp.testing.mockio', 'test', 'widget-stack', 'node-event-simulate']
+
+});
diff --git a/pool/shard010/JavaScript/0068473_add_graph.js b/pool/shard010/JavaScript/0068473_add_graph.js
new file mode 100644
index 0000000000000000000000000000000000000000..c7929500db7f05ee17308585123b937980370a8a
--- /dev/null
+++ b/pool/shard010/JavaScript/0068473_add_graph.js
@@ -0,0 +1,44 @@
+function display_graph(Y, quizid, questionid, whichtries){
+
+ $('document').ready(function(){
+ //The ajax call - gets the required data to display in graph
+ $.ajax({
+ url: M.cfg.wwwroot+"/local/weizman_graph/get_question_analytics.php",
+ type: 'POST',
+ data: {'questionid': questionid, 'quizid': quizid, 'whichtries': whichtries},
+ dataType: 'json',
+ success: function(result){
+ //Loop on the data returned from ajax call- contains the statistics data
+ //And insert into the 2 arrays
+ var labels = new Array();
+ var series = new Array();
+ var max_amount = 10; //This variable helps to specify weather the max number for the y axis
+ $.each(result, function(index, element) {
+ if(element === null) {
+ element = 0;
+ } else {
+ if(element > max_amount) {
+ max_amount = element;
+ }
+ }
+ labels.push(index);
+ series.push(element);
+ });
+ //Display the graph using the data that returned from ajax.
+ $("
").insertBefore('div.backtomainstats');
+ new Chartist.Bar('.ct-chart', {
+ labels: labels,
+ series: series
+ }, {
+ width: 500,
+ height: 200,
+ distributeSeries: true,
+ high: max_amount,
+ axisY: {
+ onlyInteger: true
+ }
+ })
+ }
+ });
+ });
+}
diff --git a/pool/shard010/JavaScript/0068474_file.js b/pool/shard010/JavaScript/0068474_file.js
new file mode 100644
index 0000000000000000000000000000000000000000..e311d00bd1f6b1b49b8d29937521fecec1291ada
--- /dev/null
+++ b/pool/shard010/JavaScript/0068474_file.js
@@ -0,0 +1,37 @@
+import 'codemirror/mode/gfm/gfm.js';
+import 'codemirror/mode/javascript/javascript.js';
+import 'codemirror/mode/css/css.js';
+import 'codemirror/mode/htmlmixed/htmlmixed.js';
+import 'codemirror/mode/xml/xml.js';
+
+const fileTypes = {
+ markdown: ['md', 'markdown'],
+ javascript: ['js', 'json'],
+ text: ['text'],
+ css: ['css', 'scss', 'less'],
+ html: ['html'],
+ xml: ['xml'],
+ image: [
+ 'png',
+ 'svg',
+ 'jpg',
+ ],
+};
+
+export default () => {
+ return function processFile(file) {
+ return determinType(file.data.name)
+ .then(type => [type, file]);
+ };
+
+ function determinType(filename) {
+ const ext = filename.split('.').pop();
+
+ const filetype = Object.keys(fileTypes).reduce((acc, item) => {
+ if (fileTypes[item].some(value => value === ext)) return item;
+ return acc;
+ });
+
+ return Promise.resolve().then(() => filetype || 'text');
+ }
+};
diff --git a/pool/shard010/JavaScript/0068475_index.ios-ajax.js b/pool/shard010/JavaScript/0068475_index.ios-ajax.js
new file mode 100644
index 0000000000000000000000000000000000000000..baf01b8109d352906d0e07a577f7c96d79670e7b
--- /dev/null
+++ b/pool/shard010/JavaScript/0068475_index.ios-ajax.js
@@ -0,0 +1,133 @@
+/**
+ * Sample React Native App
+ * https://github.com/facebook/react-native
+ * @flow
+ */
+
+import React, { Component } from 'react';
+import { AppRegistry, StyleSheet, Text, View, Image } from 'react-native';
+import RNPhotosFramework from './react-native-photos-framework';
+import {postAsset, postAssets} from './react-native-photos-framework/src/ajax-helper';
+
+export default class Example extends Component {
+
+ constructor() {
+ super();
+ this.state = {
+ images: []
+ };
+ }
+
+ componentDidMount() {
+ RNPhotosFramework.requestAuthorization().then((statusObj) => {
+ if (statusObj.isAuthorized) {
+ RNPhotosFramework.getAlbums({
+ type: 'smartAlbum',
+ subType: 'smartAlbumUserLibrary',
+ assetCount: 'exact',
+ fetchOptions: {
+ sortDescriptors: [
+ {
+ key: 'title',
+ ascending: true
+ }
+ ],
+ includeHiddenAssets: false,
+ includeAllBurstAssets: false
+ },
+ //When you say 'trackInsertsAndDeletes or trackChanges' for an albums query result,
+ //They will be cached and tracking will start.
+ //Call queryResult.stopTracking() to stop this. ex. on componentDidUnmount
+ trackInsertsAndDeletes: true,
+ trackChanges: false
+
+ }).then((queryResult) => {
+ const album = queryResult.albums[0];
+ return album.getAssets({
+ fetchOptions: {
+ // mediaTypes: ['video']
+ },
+ includeResourcesMetadata : true,
+
+ //The fetch-options from the outer query will apply here, if we get
+ startIndex: 0,
+ endIndex: 10,
+ //When you say 'trackInsertsAndDeletes or trackAssetsChange' for an albums assets,
+ //They will be cached and tracking will start.
+ //Call album.stopTracking() to stop this. ex. on componentDidUnmount
+ trackInsertsAndDeletes: true,
+ trackChanges: false
+ }).then((response) => {
+ /* response.assets[1].getImageMetadata().then((asset) => {
+ debugger;
+ });*/
+ setTimeout(() => {
+ const assets = [response.assets[0], response.assets[1]];
+ postAssets(assets, {
+ url: 'http://localhost:3000/upload',
+ headers : {},
+ onProgress: (progressPercentage, details) => {
+ console.log('On Progress called', progressPercentage);
+ },
+ onComplete : (asset, status, responseText, xhr) => {
+ console.log('Asset upload completed successfully');
+ },
+ onError : (asset, status, responseText, xhr) => {
+ console.log('Asset upload failed');
+ },
+ onFinnished : (completedItems) => {
+ console.log('Operation complete');
+ },
+ modifyAssetData : (postableAsset, asset) => {
+ postableAsset.name = `${postableAsset.name}-special-name-maybe-guid.jpg`;
+ return postableAsset;
+ }
+ }).then((result) => {
+ console.log('Operation complete, promise resolved', result);
+ });
+ }, 2000);
+
+ this.setState({
+ images: [response.assets[0]]
+ });
+ });
+ });
+ }
+ });
+ }
+
+ renderImage(asset, index) {
+ return (
+
+ );
+ }
+
+ render() {
+ return (
+
+ {this.state.images.map(this.renderImage.bind(this))}
+
+ );
+ }
+}
+
+const styles = StyleSheet.create({
+ container: {
+ flex: 1,
+ justifyContent: 'center',
+ alignItems: 'center',
+ backgroundColor: '#F5FCFF'
+ },
+ welcome: {
+ fontSize: 20,
+ textAlign: 'center',
+ margin: 10
+ },
+ instructions: {
+ textAlign: 'center',
+ color: '#333333',
+ marginBottom: 5
+ }
+});
+
+AppRegistry.registerComponent('Example', () => Example);
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068477_Logging.js b/pool/shard010/JavaScript/0068477_Logging.js
new file mode 100644
index 0000000000000000000000000000000000000000..b86eb9fa737bd9e7457c1172231fa80b38b6d836
--- /dev/null
+++ b/pool/shard010/JavaScript/0068477_Logging.js
@@ -0,0 +1,28 @@
+"use strict";
+var Logging = (function () {
+ function Logging() {
+ }
+ Logging.info = function (message) {
+ var optionalParams = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ optionalParams[_i - 1] = arguments[_i];
+ }
+ if (Logging.enableDebug) {
+ console.info(Logging.TAG + message, optionalParams);
+ }
+ };
+ Logging.warn = function (message) {
+ var optionalParams = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ optionalParams[_i - 1] = arguments[_i];
+ }
+ if (!Logging.disableWarnings) {
+ console.warn(Logging.TAG + message, optionalParams);
+ }
+ };
+ Logging.enableDebug = false;
+ Logging.disableWarnings = false;
+ Logging.TAG = "ApplicationInsights:";
+ return Logging;
+}());
+module.exports = Logging;
diff --git a/pool/shard010/JavaScript/0068479_webpack.config.dev.js b/pool/shard010/JavaScript/0068479_webpack.config.dev.js
new file mode 100644
index 0000000000000000000000000000000000000000..62ce7aa1ddf65becc710ddd9e0dda8464ef0fe3a
--- /dev/null
+++ b/pool/shard010/JavaScript/0068479_webpack.config.dev.js
@@ -0,0 +1,363 @@
+// @remove-on-eject-begin
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+// @remove-on-eject-end
+'use strict';
+
+const autoprefixer = require('autoprefixer');
+const path = require('path');
+const webpack = require('webpack');
+const HtmlWebpackPlugin = require('html-webpack-plugin');
+const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
+const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
+const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
+const eslintFormatter = require('react-dev-utils/eslintFormatter');
+const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
+const getClientEnvironment = require('./env');
+const paths = require('./paths');
+
+// Webpack uses `publicPath` to determine where the app is being served from.
+// In development, we always serve from the root. This makes config easier.
+const publicPath = '/';
+// `publicUrl` is just like `publicPath`, but we will provide it to our app
+// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
+// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
+const publicUrl = '';
+// Get environment variables to inject into our app.
+const env = getClientEnvironment(publicUrl);
+
+// Options for PostCSS as we reference these options twice
+// Adds vendor prefixing based on your specified browser support in
+// package.json
+const postCSSLoaderOptions = {
+ // Necessary for external CSS imports to work
+ // https://github.com/facebookincubator/create-react-app/issues/2677
+ ident: 'postcss',
+ plugins: () => [
+ require('postcss-flexbugs-fixes'),
+ autoprefixer({
+ flexbox: 'no-2009',
+ }),
+ ],
+};
+
+// This is the development configuration.
+// It is focused on developer experience and fast rebuilds.
+// The production configuration is different and lives in a separate file.
+module.exports = {
+ // You may want 'eval' instead if you prefer to see the compiled output in DevTools.
+ // See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
+ devtool: 'cheap-module-source-map',
+ // These are the "entry points" to our application.
+ // This means they will be the "root" imports that are included in JS bundle.
+ // The first two entry points enable "hot" CSS and auto-refreshes for JS.
+ entry: [
+ // We ship a few polyfills by default:
+ require.resolve('./polyfills'),
+ // Include an alternative client for WebpackDevServer. A client's job is to
+ // connect to WebpackDevServer by a socket and get notified about changes.
+ // When you save a file, the client will either apply hot updates (in case
+ // of CSS changes), or refresh the page (in case of JS changes). When you
+ // make a syntax error, this client will display a syntax error overlay.
+ // Note: instead of the default WebpackDevServer client, we use a custom one
+ // to bring better experience for Create React App users. You can replace
+ // the line below with these two lines if you prefer the stock client:
+ // require.resolve('webpack-dev-server/client') + '?/',
+ // require.resolve('webpack/hot/dev-server'),
+ require.resolve('react-dev-utils/webpackHotDevClient'),
+ // Finally, this is your app's code:
+ paths.appIndexJs,
+ // We include the app code last so that if there is a runtime error during
+ // initialization, it doesn't blow up the WebpackDevServer client, and
+ // changing JS code would still trigger a refresh.
+ ],
+ output: {
+ // Add /* filename */ comments to generated require()s in the output.
+ pathinfo: true,
+ // This does not produce a real file. It's just the virtual path that is
+ // served by WebpackDevServer in development. This is the JS bundle
+ // containing code from all our entry points, and the Webpack runtime.
+ filename: 'static/js/bundle.js',
+ // There are also additional JS chunk files if you use code splitting.
+ chunkFilename: 'static/js/[name].chunk.js',
+ // This is the URL that app is served from. We use "/" in development.
+ publicPath: publicPath,
+ // Point sourcemap entries to original disk location (format as URL on Windows)
+ devtoolModuleFilenameTemplate: info =>
+ path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
+ },
+ resolve: {
+ // This allows you to set a fallback for where Webpack should look for modules.
+ // We placed these paths second because we want `node_modules` to "win"
+ // if there are any conflicts. This matches Node resolution mechanism.
+ // https://github.com/facebookincubator/create-react-app/issues/253
+ modules: ['node_modules', paths.appNodeModules].concat(
+ // It is guaranteed to exist because we tweak it in `env.js`
+ process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
+ ),
+ // These are the reasonable defaults supported by the Node ecosystem.
+ // We also include JSX as a common component filename extension to support
+ // some tools, although we do not recommend using it, see:
+ // https://github.com/facebookincubator/create-react-app/issues/290
+ // `web` extension prefixes have been added for better support
+ // for React Native Web.
+ extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
+ alias: {
+ // @remove-on-eject-begin
+ // Resolve Babel runtime relative to react-scripts.
+ // It usually still works on npm 3 without this but it would be
+ // unfortunate to rely on, as react-scripts could be symlinked,
+ // and thus @babel/runtime might not be resolvable from the source.
+ '@babel/runtime': path.dirname(
+ require.resolve('@babel/runtime/package.json')
+ ),
+ // @remove-on-eject-end
+ // Support React Native Web
+ // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
+ 'react-native': 'react-native-web',
+ },
+ plugins: [
+ // Prevents users from importing files from outside of src/ (or node_modules/).
+ // This often causes confusion because we only process files within src/ with babel.
+ // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
+ // please link the files into your node_modules/ and let module-resolution kick in.
+ // Make sure your source files are compiled, as they will not be processed in any way.
+ new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
+ ],
+ },
+ module: {
+ strictExportPresence: true,
+ rules: [
+ // Disable require.ensure as it's not a standard language feature.
+ { parser: { requireEnsure: false } },
+
+ // First, run the linter.
+ // It's important to do this before Babel processes the JS.
+ {
+ test: /\.(js|jsx|mjs)$/,
+ enforce: 'pre',
+ use: [
+ {
+ options: {
+ formatter: eslintFormatter,
+ eslintPath: require.resolve('eslint'),
+ // @remove-on-eject-begin
+ baseConfig: {
+ extends: [require.resolve('eslint-config-react-app')],
+ },
+ ignore: false,
+ useEslintrc: false,
+ // @remove-on-eject-end
+ },
+ loader: require.resolve('eslint-loader'),
+ },
+ ],
+ include: paths.appSrc,
+ },
+ {
+ // "oneOf" will traverse all following loaders until one will
+ // match the requirements. When no loader matches it will fall
+ // back to the "file" loader at the end of the loader list.
+ oneOf: [
+ // "url" loader works like "file" loader except that it embeds assets
+ // smaller than specified limit in bytes as data URLs to avoid requests.
+ // A missing `test` is equivalent to a match.
+ {
+ test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
+ loader: require.resolve('url-loader'),
+ options: {
+ limit: 10000,
+ name: 'static/media/[name].[hash:8].[ext]',
+ },
+ },
+ // Process application JS with Babel.
+ // The preset includes JSX, Flow, and some ESnext features.
+ {
+ test: /\.(js|jsx|mjs)$/,
+ include: paths.appSrc,
+ use: [
+ // This loader parallelizes code compilation, it is optional but
+ // improves compile time on larger projects
+ require.resolve('thread-loader'),
+ {
+ loader: require.resolve('babel-loader'),
+ options: {
+ // @remove-on-eject-begin
+ babelrc: false,
+ presets: [require.resolve('babel-preset-react-app')],
+ // @remove-on-eject-end
+ // This is a feature of `babel-loader` for webpack (not Babel itself).
+ // It enables caching results in ./node_modules/.cache/babel-loader/
+ // directory for faster rebuilds.
+ cacheDirectory: true,
+ highlightCode: true,
+ },
+ },
+ ],
+ },
+ // Process any JS outside of the app with Babel.
+ // Unlike the application JS, we only compile the standard ES features.
+ {
+ test: /\.js$/,
+ use: [
+ // This loader parallelizes code compilation, it is optional but
+ // improves compile time on larger projects
+ require.resolve('thread-loader'),
+ {
+ loader: require.resolve('babel-loader'),
+ options: {
+ babelrc: false,
+ compact: false,
+ presets: [
+ require.resolve('babel-preset-react-app/dependencies'),
+ ],
+ cacheDirectory: true,
+ highlightCode: true,
+ },
+ },
+ ],
+ },
+ // "postcss" loader applies autoprefixer to our CSS.
+ // "css" loader resolves paths in CSS and adds assets as dependencies.
+ // "style" loader turns CSS into JS modules that inject bolded text italic text ';
+ var rules = [
+ {
+ styleContains: 'bold',
+ wrapWith: 'strong'
+ },
+ {
+ styleContains: 'Italic',
+ wrapWith: 'i'
+ }
+ ];
+ sematicafy.parse(html, rules, function (err, semHtml) {
+ semHtml.should.containEql('bolded text italic text ');
+ done();
+ });
+ });
+
+ it('should remove bolded text italic text ';
+ var rules = [
+ {
+ styleContains: 'bold',
+ wrapWith: 'strong'
+ },
+ {
+ styleContains: 'Italic',
+ wrapWith: 'i'
+ }
+ ];
+ sematicafy.parse(html, rules, function (err, semHtml) {
+ semHtml.should.not.containEql('style');
+ semHtml.should.not.containEql('class');
+ done();
+ });
+ });
+});
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068584_core.server.controller.js b/pool/shard010/JavaScript/0068584_core.server.controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..6cd1b36f9dfeb1b790ec4780b1e9b69fcee3376d
--- /dev/null
+++ b/pool/shard010/JavaScript/0068584_core.server.controller.js
@@ -0,0 +1,62 @@
+'use strict';
+
+
+var nodemailer = require('nodemailer');
+var transporter = nodemailer.createTransport();
+
+/**
+ * Render the main application page
+ */
+exports.renderIndex = function (req, res) {
+ res.render('modules/core/server/views/index', {
+ user: req.user || null
+ });
+};
+
+/**
+ * Render the server error page
+ */
+exports.renderServerError = function (req, res) {
+ res.status(500).render('modules/core/server/views/500', {
+ error: 'Oops! Something went wrong...'
+ });
+};
+
+/**
+ * Render the server not found responses
+ * Performs content-negotiation on the Accept HTTP header
+ */
+exports.renderNotFound = function (req, res) {
+
+ res.status(404).format({
+ 'text/html': function () {
+ res.render('modules/core/server/views/404', {
+ url: req.originalUrl
+ });
+ },
+ 'application/json': function () {
+ res.json({
+ error: 'Path not found'
+ });
+ },
+ 'default': function () {
+ res.send('Path not found');
+ }
+ });
+};
+
+/**
+ *
+ */
+exports.sendMail = function(req, res){
+
+ var data = req.body;
+
+ transporter.sendMail({
+ from: 'christian.soto9@upr.edu',
+ to: 'christian.soto9@upr.edu',
+ subject: 'test',
+ text: 'text'
+ });
+ res.json(data);
+};
diff --git a/pool/shard010/JavaScript/0068590_GetFileInfoByXmlID.js b/pool/shard010/JavaScript/0068590_GetFileInfoByXmlID.js
new file mode 100644
index 0000000000000000000000000000000000000000..9fb0cc983bf48bc84e926c6eb82cb58ea2c5af69
--- /dev/null
+++ b/pool/shard010/JavaScript/0068590_GetFileInfoByXmlID.js
@@ -0,0 +1,26 @@
+Ext.namespace('ui','ui.task');
+
+// config - { xmlID }
+ui.task.GetFileInfoByXmlID = function(config)
+{
+ Ext.apply(this, config);
+
+ // We load the File
+ XHR({
+ scope : this,
+ params : {
+ task : 'getFileInfoByXmlID',
+ xmlID : this.xmlID
+ },
+ success : function(r)
+ {
+ var o = Ext.util.JSON.decode(r.responseText);
+
+ ui.cmp.RepositoryTree.getInstance().openFile(
+ 'byPath',
+ o.lang + o.path,
+ o.name
+ );
+ }
+ });
+};
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068591_measurement.js b/pool/shard010/JavaScript/0068591_measurement.js
new file mode 100644
index 0000000000000000000000000000000000000000..2665a3d5ad83295b749b356908a93994aff3e7df
--- /dev/null
+++ b/pool/shard010/JavaScript/0068591_measurement.js
@@ -0,0 +1,22 @@
+'use strict';
+
+module.exports = function (Measurements, app, auth) {
+
+ var measurements = require('../controllers/measurement');
+
+ app.route('/api/measurement')
+ .get(auth.requiresLogin, measurements.all);
+
+ app.route('/api/measurement/:date')
+ .get(auth.requiresLogin, measurements.get)
+ .delete(auth.requiresLogin, measurements.ignore)
+ .put(auth.requiresLogin, measurements.unignore);
+
+ app.route('/api/measurement')
+ .post(auth.requiresLogin, measurements.update);
+
+ app.route('/api/measurement/:date/consumptions')
+ .post(auth.requiresLogin, measurements.addConsumption)
+ .delete(auth.requiresLogin, measurements.removeConsumption);
+
+};
diff --git a/pool/shard010/JavaScript/0068593_inferers.js b/pool/shard010/JavaScript/0068593_inferers.js
new file mode 100644
index 0000000000000000000000000000000000000000..a08dd32ff39a50336f4ae82a9a29484051933bf5
--- /dev/null
+++ b/pool/shard010/JavaScript/0068593_inferers.js
@@ -0,0 +1,193 @@
+"use strict";
+
+var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
+
+var _interopRequire = require("babel-runtime/helpers/interop-require")["default"];
+
+exports.__esModule = true;
+exports.VariableDeclarator = VariableDeclarator;
+exports.TypeCastExpression = TypeCastExpression;
+exports.NewExpression = NewExpression;
+exports.TemplateLiteral = TemplateLiteral;
+exports.UnaryExpression = UnaryExpression;
+exports.BinaryExpression = BinaryExpression;
+exports.LogicalExpression = LogicalExpression;
+exports.ConditionalExpression = ConditionalExpression;
+exports.SequenceExpression = SequenceExpression;
+exports.AssignmentExpression = AssignmentExpression;
+exports.UpdateExpression = UpdateExpression;
+exports.StringLiteral = StringLiteral;
+exports.NumericLiteral = NumericLiteral;
+exports.BooleanLiteral = BooleanLiteral;
+exports.NullLiteral = NullLiteral;
+exports.RegExpLiteral = RegExpLiteral;
+exports.ObjectExpression = ObjectExpression;
+exports.ArrayExpression = ArrayExpression;
+exports.RestElement = RestElement;
+exports.CallExpression = CallExpression;
+exports.TaggedTemplateExpression = TaggedTemplateExpression;
+
+var _babelTypes = require("babel-types");
+
+var t = _interopRequireWildcard(_babelTypes);
+
+var _infererReference = require("./inferer-reference");
+
+exports.Identifier = _interopRequire(_infererReference);
+
+function VariableDeclarator() {
+ var id = this.get("id");
+
+ if (id.isIdentifier()) {
+ return this.get("init").getTypeAnnotation();
+ } else {
+ return;
+ }
+}
+
+function TypeCastExpression(node) {
+ return node.typeAnnotation;
+}
+
+TypeCastExpression.validParent = true;
+
+function NewExpression(node) {
+ if (this.get("callee").isIdentifier()) {
+ // only resolve identifier callee
+ return t.genericTypeAnnotation(node.callee);
+ }
+}
+
+function TemplateLiteral() {
+ return t.stringTypeAnnotation();
+}
+
+function UnaryExpression(node) {
+ var operator = node.operator;
+
+ if (operator === "void") {
+ return t.voidTypeAnnotation();
+ } else if (t.NUMBER_UNARY_OPERATORS.indexOf(operator) >= 0) {
+ return t.numberTypeAnnotation();
+ } else if (t.STRING_UNARY_OPERATORS.indexOf(operator) >= 0) {
+ return t.stringTypeAnnotation();
+ } else if (t.BOOLEAN_UNARY_OPERATORS.indexOf(operator) >= 0) {
+ return t.booleanTypeAnnotation();
+ }
+}
+
+function BinaryExpression(node) {
+ var operator = node.operator;
+
+ if (t.NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) {
+ return t.numberTypeAnnotation();
+ } else if (t.BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) {
+ return t.booleanTypeAnnotation();
+ } else if (operator === "+") {
+ var right = this.get("right");
+ var left = this.get("left");
+
+ if (left.isBaseType("number") && right.isBaseType("number")) {
+ // both numbers so this will be a number
+ return t.numberTypeAnnotation();
+ } else if (left.isBaseType("string") || right.isBaseType("string")) {
+ // one is a string so the result will be a string
+ return t.stringTypeAnnotation();
+ }
+
+ // unsure if left and right are strings or numbers so stay on the safe side
+ return t.unionTypeAnnotation([t.stringTypeAnnotation(), t.numberTypeAnnotation()]);
+ }
+}
+
+function LogicalExpression() {
+ return t.createUnionTypeAnnotation([this.get("left").getTypeAnnotation(), this.get("right").getTypeAnnotation()]);
+}
+
+function ConditionalExpression() {
+ return t.createUnionTypeAnnotation([this.get("consequent").getTypeAnnotation(), this.get("alternate").getTypeAnnotation()]);
+}
+
+function SequenceExpression() {
+ return this.get("expressions").pop().getTypeAnnotation();
+}
+
+function AssignmentExpression() {
+ return this.get("right").getTypeAnnotation();
+}
+
+function UpdateExpression(node) {
+ var operator = node.operator;
+ if (operator === "++" || operator === "--") {
+ return t.numberTypeAnnotation();
+ }
+}
+
+function StringLiteral() {
+ return t.stringTypeAnnotation();
+}
+
+function NumericLiteral() {
+ return t.numberTypeAnnotation();
+}
+
+function BooleanLiteral() {
+ return t.booleanTypeAnnotation();
+}
+
+function NullLiteral() {
+ return t.voidTypeAnnotation();
+}
+
+function RegExpLiteral() {
+ return t.genericTypeAnnotation(t.identifier("RegExp"));
+}
+
+function ObjectExpression() {
+ return t.genericTypeAnnotation(t.identifier("Object"));
+}
+
+function ArrayExpression() {
+ return t.genericTypeAnnotation(t.identifier("Array"));
+}
+
+function RestElement() {
+ return ArrayExpression();
+}
+
+RestElement.validParent = true;
+
+function Func() {
+ return t.genericTypeAnnotation(t.identifier("Function"));
+}
+
+exports.Function = Func;
+exports.Class = Func;
+
+function CallExpression() {
+ return resolveCall(this.get("callee"));
+}
+
+function TaggedTemplateExpression() {
+ return resolveCall(this.get("tag"));
+}
+
+function resolveCall(callee) {
+ callee = callee.resolve();
+
+ if (callee.isFunction()) {
+ if (callee.is("async")) {
+ if (callee.is("generator")) {
+ return t.genericTypeAnnotation(t.identifier("AsyncIterator"));
+ } else {
+ return t.genericTypeAnnotation(t.identifier("Promise"));
+ }
+ } else {
+ if (callee.node.returnType) {
+ return callee.node.returnType;
+ } else {
+ // todo: get union type of all return arguments
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068596_plasma.js b/pool/shard010/JavaScript/0068596_plasma.js
new file mode 100644
index 0000000000000000000000000000000000000000..4f254acb284d76307bf4e9dd1d1c4a6f6ae7a1e8
--- /dev/null
+++ b/pool/shard010/JavaScript/0068596_plasma.js
@@ -0,0 +1,31 @@
+import SimplexNoise from 'simplex-noise';
+
+const canvas = document.createElement('canvas');
+canvas.width = 512;
+canvas.height = 512;
+document.body.appendChild(canvas);
+
+const simplex = new SimplexNoise(),
+ ctx = canvas.getContext('2d'),
+ imgdata = ctx.getImageData(0, 0, canvas.width, canvas.height),
+ width = imgdata.width,
+ height = imgdata.height,
+ data = imgdata.data;
+
+function render() {
+ const t = performance.now()/1000;
+ for (var x = 0; x < width; x++) {
+ for (var y = 0; y < height; y++) {
+ var r = simplex.noise3D(x / 16, y / 16, t) * 0.5 + 0.5;
+ var g = simplex.noise3D(x / 8, y / 8, t) * 0.5 + 0.5;
+ data[(x + y * width) * 4 + 0] = r * 255;
+ data[(x + y * width) * 4 + 1] = (r + g) * 200;
+ data[(x + y * width) * 4 + 2] = 0;
+ data[(x + y * width) * 4 + 3] = 255;
+ }
+ }
+ ctx.putImageData(imgdata, 0, 0);
+ requestAnimationFrame(render);
+}
+
+requestAnimationFrame(render);
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068602_15.4.4.21-3-21.js b/pool/shard010/JavaScript/0068602_15.4.4.21-3-21.js
new file mode 100644
index 0000000000000000000000000000000000000000..0f1fde7b7c6da362941d5e99e8a11368a2183253
--- /dev/null
+++ b/pool/shard010/JavaScript/0068602_15.4.4.21-3-21.js
@@ -0,0 +1,38 @@
+/// Copyright (c) 2012 Ecma International. All rights reserved.
+/// Ecma International makes this code available under the terms and conditions set
+/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
+/// "Use Terms"). Any redistribution of this code must retain the above
+/// copyright and this notice and otherwise comply with the Use Terms.
+/**
+ * @path ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-21.js
+ * @description Array.prototype.reduce - 'length' is an object that has an own valueOf method that returns an object and toString method that returns a string
+ */
+
+
+function testcase() {
+
+ var valueOfOccured = false;
+ var toStringOccured = false;
+
+ function callbackfn(prevVal, curVal, idx, obj) {
+ return (curVal === 11 && idx === 1);
+ }
+
+ var obj = {
+ 1: 11,
+ 2: 9,
+ length: {
+ valueOf: function () {
+ valueOfOccured = true;
+ return {};
+ },
+ toString: function () {
+ toStringOccured = true;
+ return '2';
+ }
+ }
+ };
+
+ return Array.prototype.reduce.call(obj, callbackfn, 1) === true && valueOfOccured && toStringOccured;
+ }
+runTestCase(testcase);
diff --git a/pool/shard010/JavaScript/0068605_Token.js b/pool/shard010/JavaScript/0068605_Token.js
new file mode 100644
index 0000000000000000000000000000000000000000..bf66afe8becdbe7fc8e6b2973bd0772d39411189
--- /dev/null
+++ b/pool/shard010/JavaScript/0068605_Token.js
@@ -0,0 +1,136 @@
+/**
+ * A Token represents a single token represented in a Conllu file
+ * For example, a Token may represent the following line:
+ *
+ * 1 I I PRON PRP Case=Nom|Number=Sing|Person=1 2 nsubj _ _
+ *
+ * @constructor
+ */
+var Token = function() {};
+
+Token.prototype = {
+ // note: id is generally managed by Sentence
+ id: undefined,
+ form: '',
+ lemma: undefined,
+ upostag: undefined,
+ xpostag: undefined,
+ feats: undefined,
+ head: undefined,
+ deprel: undefined,
+ deps: undefined,
+ misc: undefined
+};
+
+Object.defineProperty(Token.prototype,'serial',
+ {
+ get: function() {
+ // takes this token object and returns a string
+ // no iteration through the properties of the object, because of non-conllu properties (ex: "serialize" property)
+ var id_output = "_";
+ if (!(this.id === undefined) && !(this.id === "")){
+ id_output = String(this.id);
+ }
+
+ var form_output = "_";
+ if (!(this.id === undefined) && !(this.id === "")){
+ form_output = String(this.form);
+ }
+
+ var lemma_output = "_";
+ if (!(this.lemma === undefined) && !(this.lemma === "")){
+ lemma_output = String(this.lemma);
+ }
+
+ var upostag_output = "_";
+ if (!(this.upostag === undefined) && !(this.upostag === "")){
+ upostag_output = String(this.upostag);
+ }
+
+ var xpostag_output = "_";
+ if (!(this.xpostag === undefined) && !(this.xpostag === "")){
+ xpostag_output = String(this.xpostag);
+ }
+
+ var feats_output = "_";
+ if (!(this.feats === undefined) && !(this.feats === "")){
+ feats_output = String(this.feats);
+ }
+
+ var head_output = "_";
+ if (!(this.head === undefined) && !(this.head === "")){
+ head_output = String(this.head);
+ }
+
+ var deprel_output = "_";
+ if (!(this.deprel === undefined) && !(this.deprel === "")){
+ deprel_output = String(this.deprel);
+ }
+
+ var deps_output = "_";
+ if (!(this.deps === undefined) && !(this.deps === "")){
+ deps_output = String(this.deps);
+ }
+
+ var misc_output = "_";
+ if (!(this.misc === undefined) && !(this.misc === "")){
+ misc_output = String(this.misc);
+ }
+
+ return (id_output + "\t" + form_output + "\t" + lemma_output + "\t" + upostag_output + "\t" + xpostag_output + "\t" + feats_output + "\t" + head_output + "\t" + deprel_output + "\t" + deps_output + "\t" + misc_output);
+ },
+
+ set: function(arg) {
+ //takes a string and sets this object's value to match the string.
+
+ var fields = arg.split("\t");
+
+ this.id = Number(fields[0]);
+ if (this.id === "_")
+ this.id = undefined;
+
+ this.form = fields[1];
+ if (this.form === "_")
+ this.form = undefined;
+
+ this.lemma = fields[2];
+ if (this.lemma === "_")
+ this.lemma = undefined;
+
+ this.upostag = fields[3];
+ if (this.upostag === "_")
+ this.upostag = undefined;
+
+ this.xpostag = fields[4];
+ if (this.xpostag === "_")
+ this.xpostag = undefined;
+
+ this.feats = fields[5];
+ if (this.feats === "_")
+ this.feats = undefined;
+
+ this.head = fields[6];
+ if (this.head === "_")
+ this.head = undefined;
+
+ this.deprel = fields[7];
+ if (this.deprel === "_")
+ this.deprel = undefined;
+
+ this.deps = fields[8];
+ if (this.deps === "_")
+ this.deps = undefined;
+
+ this.misc = fields[9];
+ if (this.misc === "_")
+ this.misc = undefined;
+ }
+ }
+);
+
+
+// if using Node.js export module
+if (typeof exports !== 'undefined' && this.exports !== exports) {
+ exports.Token = Token;
+}
+
diff --git a/pool/shard010/JavaScript/0068606_init.js b/pool/shard010/JavaScript/0068606_init.js
new file mode 100644
index 0000000000000000000000000000000000000000..cb870ab329c20968d803702e51ed07144af47894
--- /dev/null
+++ b/pool/shard010/JavaScript/0068606_init.js
@@ -0,0 +1,110 @@
+var path = require('path');
+
+var TaskRunner = {
+ _grunt: null,
+ seedTypes: {
+ 'component': 'https://github.com/thomsonreuters/jet-seed',
+ 'plugin': 'https://github.com/thomsonreuters/jet-plugin-seed'
+ },
+ init: function (grunt) {
+ this._grunt = grunt;
+ this.loadNPM(grunt);
+ this.register(grunt);
+ return this.getGruntConfig(grunt);
+ },
+ loadNPM: function (grunt) {
+ grunt.loadNpmTasks('grunt-shell-spawn');
+ grunt.loadNpmTasks('grunt-replace');
+ grunt.loadNpmTasks('grunt-contrib-copy');
+ grunt.loadNpmTasks('grunt-contrib-clean');
+ },
+ getGruntConfig: function (grunt) {
+ var project = grunt.option('project') || './';
+ var folderName = project.substr(project.lastIndexOf('\\') + 1);
+ console.log(project+"/tmp");
+ return {
+ replace: {
+ init: {
+ options: {
+ patterns: [{
+ match: /jet-seed|jet-plugin-seed/g,
+ replacement: folderName
+ }, {
+ match: /Seed/g,
+ replacement: function () {
+ var index = folderName.lastIndexOf('-');
+ if (index > -1) {
+ var replaceText = folderName.substring(index + 1);
+ return replaceText[0].toUpperCase() + replaceText.substring(1);
+ } else
+ return folderName;
+ }
+ }]
+ },
+ files: [{
+ cwd: project,
+ expand: true,
+ src: ['**/*','!**/Gruntfile.js','!**/node_modules/**','!**/grunt/**'],
+ dest: project
+ }]
+ }
+ },
+ copy: {
+ init: {
+ expand: true,
+ cwd: path.join(project, 'tmp'),
+ dot: true,
+ src: ['**', '!.git/**'],
+ dest: project,
+ rename: function (dest, src) {
+ return path.join(dest, src.replace(/jet-seed|jet-plugin-seed/g, folderName));
+ }
+ }
+ },
+ clean: {
+ temp: {
+ options:{
+ force:true
+ },
+ src: [project+"\\tmp"]
+ }
+ },
+ shell: {
+ cloneSeed: {
+ command: 'git clone ' + TaskRunner.seedTypes[TaskRunner.getSeedType()] + ' tmp',
+ options: {
+ execOptions: {
+ cwd: project
+ }
+ }
+ },
+ bowerInstall: {
+ command: 'bower install',
+ options: {
+ execOptions: {
+ cwd: project
+ }
+ }
+ }
+ }
+ };
+ },
+ getSeedType: function () {
+
+ // If no type or wrong type, default to component
+ if (TaskRunner._grunt.option('type') === undefined || seedTypes[TaskRunner._grunt.option('type')] === undefined) {
+ return 'component';
+ }
+
+ return TaskRunner._grunt.option('type');
+
+ },
+ registerCustomTasks: {
+
+ },
+ register: function (grunt) {
+ grunt.registerTask('init', ['shell:cloneSeed', 'copy:init', 'replace:init', 'shell:bowerInstall','clean:temp']);
+ }
+
+}
+module.exports = TaskRunner.init.bind(TaskRunner);
diff --git a/pool/shard010/JavaScript/0068607_hotkeyNavigation.js b/pool/shard010/JavaScript/0068607_hotkeyNavigation.js
new file mode 100644
index 0000000000000000000000000000000000000000..162f857d08060a3b5d27ec8064484eceab417e90
--- /dev/null
+++ b/pool/shard010/JavaScript/0068607_hotkeyNavigation.js
@@ -0,0 +1,90 @@
+import { remote } from 'electron';
+import { style, cssRule } from '../customUI';
+
+window.wait(() => {
+ const listenNowURL = 'https://play.google.com/music/listen#/now';
+ const searchBox = (document.querySelector('#material-one-middle > sj-search-box')
+ || document.querySelector('#material-one-middle'));
+ const searchInput = (document.querySelector('sj-search-box input')
+ || document.querySelector('#material-one-middle > input'));
+
+ const backBtn = document.createElement('paper-icon-button');
+ backBtn.setAttribute('icon', 'arrow-back');
+ backBtn.setAttribute('id', 'backButton');
+ backBtn.setAttribute('class', 'x-scope paper-icon-button-0');
+ searchBox.insertBefore(backBtn, null);
+
+ const canBack = () => !(location.href.indexOf(listenNowURL) === 0);
+
+ const attemptBack = () => {
+ const testJs = 'document.querySelector("webview").canGoBack()';
+ remote.getCurrentWindow().webContents.executeJavaScript(testJs, false, (canGoBack) => {
+ if (!canBack()) return null;
+ if (canGoBack) return history.back();
+ location.href = listenNowURL;
+ });
+ };
+ const attemptForward = () => {
+ const testJs = 'document.querySelector("webview").canGoForward()';
+ remote.getCurrentWindow().webContents.executeJavaScript(testJs, false, (canGoForward) => {
+ if (canGoForward) return history.forward();
+ });
+ };
+ Emitter.on('GPMNav:Forward', attemptForward);
+ Emitter.on('GPMNav:Back', attemptBack);
+
+ backBtn.addEventListener('click', attemptBack);
+
+ /*
+ OSX has a standard of cmd+left and cmd+right for browser navigation.
+ However cmd does not show up as a modifier key, but rather as a
+ separate keypress, which also eats the keyup event of the key it
+ is modifying.
+ */
+ const holdingKeyMap = {};
+
+ window.addEventListener('keydown', (e) => {
+ holdingKeyMap[e.which] = true;
+
+ if ((holdingKeyMap[91] || holdingKeyMap[93])
+ && document.activeElement.value === undefined) {
+ if (e.which === 37) {
+ attemptBack();
+ } else if (e.which === 39) {
+ attemptForward();
+ }
+ }
+ });
+
+ window.addEventListener('keyup', (e) => {
+ if ((e.which === 8 && document.activeElement.value === undefined)
+ || (e.which === 37 && e.altKey && document.activeElement.value === undefined)) {
+ attemptBack();
+ } else if (e.which === 39 && e.altKey && document.activeElement.value === undefined) {
+ attemptForward();
+ }
+ holdingKeyMap[e.which] = false;
+ });
+
+ style('#backButton', {
+ position: 'absolute',
+ right: '3px',
+ top: '1px',
+ width: '46px',
+ height: '46px',
+ opacity: '0',
+ transition: 'opacity 0.2s ease-in-out',
+ });
+
+ // Make sure the clearSearch button is above the arrow
+ style('sj-search-box #clearButton', { 'z-index': 10 });
+
+ // Hide Back button if search box has query
+ cssRule('sj-search-box #backButton { color: #fff !important }');
+ cssRule('sj-search-box[has-query] #backButton {opacity: 0 !important}');
+
+ const correctButtonVis = () => { backBtn.style.opacity = (!canBack()) ? 0 : 1; };
+ window.addEventListener('popstate', correctButtonVis);
+ searchInput.addEventListener('input', correctButtonVis);
+ correctButtonVis();
+});
diff --git a/pool/shard010/JavaScript/0068608_logger.js b/pool/shard010/JavaScript/0068608_logger.js
new file mode 100644
index 0000000000000000000000000000000000000000..5093738430540c659c7933f3938bb9399146d0d6
--- /dev/null
+++ b/pool/shard010/JavaScript/0068608_logger.js
@@ -0,0 +1,132 @@
+'use strict'
+
+var stringify = require('json-stringify-safe')
+var util = require('util')
+var os = require('os')
+
+module.exports = Logger
+
+var LEVELS = {
+ 'trace': 10,
+ 'debug': 20,
+ 'info': 30,
+ 'warn': 40,
+ 'error': 50,
+ 'fatal': 60
+}
+
+var json_replace = /([^%]|^)((?:%%)*)%j/g
+
+function Logger(options, extra) {
+ if(!(this instanceof Logger)) {
+ return new Logger(options, extra)
+ }
+ this.name = options.name
+ this._level = this.coerce(options.level)
+ this.hostname = options.hostname || os.hostname()
+ this.extra = extra || {}
+ this.stream = options.stream
+ this.state = {
+ queue: '',
+ queued: false
+ }
+}
+
+Object.keys(LEVELS).forEach(function(_level) {
+ Logger.prototype[_level] = function checkLevel(extra) {
+ var level = this.coerce(LEVELS[_level])
+
+ if(level < this._level) {
+ return
+ }
+
+ var has_extra = typeof extra === 'object'
+ var args = Array.prototype.slice.call(arguments, has_extra ? 1 : 0)
+ this.write(level, args, has_extra ? extra : null)
+ }
+})
+
+Logger.prototype.coerce = function coerce(value) {
+ if (!isNaN(parseInt(value, 10)) && isFinite(value)) {
+ // value is numeric
+ if (value < 10) value = 10
+ if (value > 60) value = 60
+
+ return value
+ }
+
+ return LEVELS[value] || 10
+}
+
+Logger.prototype.child = function child(extra) {
+ var child = Object.create(this)
+ child.extra = util._extend({}, this.extra)
+ child.extra = util._extend(child.extra, extra)
+
+ return child
+}
+
+Logger.prototype.level = function(level) {
+ return this._level = this.coerce(level)
+}
+
+Logger.prototype.write = function write(level, args, extra) {
+ for(var i = 0, l = args.length; i < l; ++i) {
+ if(typeof args[i] === 'function') {
+ args[i] = args[i].valueOf()
+ } else if(typeof args[i] === 'object') {
+ args[i] = stringify(args[i])
+ }
+ }
+
+ // for performance reasons we do not support %j since we are already
+ // stringifing objects
+ /*if(typeof args[0] === 'string') {
+ args[0] = args[0].replace(json_replace, '$1$2%s')
+ }*/
+
+ var entry = new Entry(this, level, util.format.apply(util, args))
+
+ util._extend(entry, this.extra)
+ util._extend(entry, extra)
+
+ this.queueLine(stringify(entry))
+}
+
+Logger.prototype.queueLine = function queueLine(line) {
+ this.state.queue += line + '\n'
+
+ if(!this.state.queued) {
+ this.writeQueuedData()
+ }
+}
+
+Logger.prototype.writeQueuedData = function writeQueuedData() {
+ var logger = this
+ var chunk = logger.state.queue
+
+ logger.state.queue = ''
+ logger.state.queued = !logger.stream.write(chunk)
+
+ if(!logger.state.queued) {
+ return
+ }
+
+ logger.stream.once('drain', function() {
+ if(logger.state.queue) {
+ logger.writeQueuedData()
+ } else {
+ logger.state.queued = false
+ }
+ })
+}
+
+function Entry(logger, level, msg) {
+ this.v = 0
+ this.level = level
+ this.name = logger.name
+ this.hostname = logger.hostname
+ this.pid = process.pid
+ this.time = new Date().toISOString()
+ this.msg = msg
+}
diff --git a/pool/shard010/JavaScript/0068611_index.js b/pool/shard010/JavaScript/0068611_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..3a5aa0a04112ffcaa9acf8c74d1f626b9407bc84
--- /dev/null
+++ b/pool/shard010/JavaScript/0068611_index.js
@@ -0,0 +1,29 @@
+import CreateShader from 'gl-shader'
+
+const VERTEX = require('fs').readFileSync(__dirname + '/../utils/pass-through.glsl', 'utf8')
+const FRAGMENT = require('fs').readFileSync(__dirname + '/index.frag', 'utf8')
+
+function initGL (pass, multipass) {
+ pass.shader = CreateShader(multipass.gl, VERTEX, FRAGMENT)
+
+ var pixelRatio = [0,0]
+
+ pass.render = function render (input, renderScreen) {
+ pass.shader.bind()
+ pass.shader.uniforms.uDepth = input.depth.bind(0)
+ renderScreen()
+ }
+}
+
+function DepthPass (config) {
+ this.shader = null
+ this.render = null
+ this.initGL = initGL.bind(null, this)
+}
+
+export default function createDepthPass (props) {
+ var config = Object.assign({
+ })
+
+ return new DepthPass(config)
+}
diff --git a/pool/shard010/JavaScript/0068613_redisSearch.js b/pool/shard010/JavaScript/0068613_redisSearch.js
new file mode 100644
index 0000000000000000000000000000000000000000..650e66b8030c0d4159be700bde98a00727c70227
--- /dev/null
+++ b/pool/shard010/JavaScript/0068613_redisSearch.js
@@ -0,0 +1,17 @@
+var redis = require("redis");
+var rd = redis.createClient();
+
+var term = process.argv[2];
+console.log("Searching for term: " + term);
+
+console.time("Redis search");
+rd.zrangebylex("search", "["+term+"", "["+term+"\xff", function(err, resp) {
+ console.timeEnd("Redis search");
+ console.log(resp);
+ console.log("");
+ console.log("Results found: " + resp.length);
+ rd.zcard("search", function(err2, count) {
+ console.log("Terms searched: " + count);
+ process.exit();
+ });
+});
diff --git a/pool/shard010/JavaScript/0068615_decorators.js b/pool/shard010/JavaScript/0068615_decorators.js
new file mode 100644
index 0000000000000000000000000000000000000000..8f9f3de1894161463d39a888f790da509e6d95f1
--- /dev/null
+++ b/pool/shard010/JavaScript/0068615_decorators.js
@@ -0,0 +1,60 @@
+'use strict';
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+
+var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
+
+exports.myDecoratorsConfig = {
+ // default config if any...
+};
+
+function setConfig (configObj) {
+ exports.myDecoratorsConfig = _extends({}, exports.myDecoratorsConfig, configObj);
+};
+exports.setConfig = setConfig;
+
+
+// ---------------------------- STATETRACKER -----------------------------------
+// -----------------------------------------------------------------------------
+
+setConfig({
+ showStateTracker: true
+})
+
+exports.STContainer = require('./stateTracker/STContainer').STContainer;
+exports.stateTrackerII = require('./stateTracker/stateTrackerHOC');
+
+// -----------------------------------------------------------------------------
+// -----------------------------------------------------------------------------
+
+
+
+// ---------------------------- STATETRACKER NATIVE -----------------------------------
+// -----------------------------------------------------------------------------
+
+setConfig({
+ showStateTrackerNative: true
+})
+
+exports.STContainerNative = require('./stateTrackerNative/STContainer').STContainer;
+exports.stateTrackerNativeII = require('./stateTrackerNative/stateTrackerHOC');
+
+// -----------------------------------------------------------------------------
+// -----------------------------------------------------------------------------
+
+
+
+// ---------------------------- UPDATEREPORTER ---------------------------------
+// ------------------------------------------------------------------------------
+
+setConfig({
+ updateReports: { mount: false, update: false, pass: false, render: false }
+})
+
+exports.updateReporterPP = require('./updateReporterHOC').updateReporterPP;
+exports.updateReporterII = require('./updateReporterHOC').updateReporterII;
+
+// ------------------------------------------------------------------------------
+// ------------------------------------------------------------------------------
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068616_mailer.js b/pool/shard010/JavaScript/0068616_mailer.js
new file mode 100644
index 0000000000000000000000000000000000000000..0dc36fddac304cc961e24044929a28977fedc4fd
--- /dev/null
+++ b/pool/shard010/JavaScript/0068616_mailer.js
@@ -0,0 +1,26 @@
+var nodemailer = require('nodemailer');
+
+var smtpTransport = require('nodemailer-smtp-transport');
+
+var transport = nodemailer.createTransport(smtpTransport({
+ service: 'gmail',
+ auth: {
+ user: 'm3anh1r@gmail.com',
+ pass: '1234567890Go'
+ }
+}));
+
+var mailOptions = {
+ from: 'm3anh1r@gmail.com',
+ to: 'm3anh1r@yahoo.com',
+ subject: 'Sending Email using Node.js',
+ text: 'That was easy!'
+};
+
+transporter.sendMail(mailOptions, function(error, info){
+ if (error) {
+ console.log(error);
+ } else {
+ console.log('Email sent: ' + info.response);
+ }
+});
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068617_Carousel.spec.js b/pool/shard010/JavaScript/0068617_Carousel.spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..2b6435440781911bc538f9a0ba0887dfd82e10ae
--- /dev/null
+++ b/pool/shard010/JavaScript/0068617_Carousel.spec.js
@@ -0,0 +1,74 @@
+import Vue from 'vue'
+import Carousel from '@src/components/carousel/Carousel.vue'
+import Slide from '@src/components/carousel/Slide.vue'
+
+describe('Carousel', () => {
+ it('should not be able to work if not using ... ', () => {
+ let _error = window.console.error
+ window.console.error = () => {
+ // Silent to remove out logs in terminal
+ }
+ try {
+ let spy = sinon.spy(window.console, 'error')
+ let res = Vue.compile('{{ msg }} ')
+ let vm = new Vue({
+ data () {
+ return {
+ msg: 'hello'
+ }
+ },
+ components: {Carousel, Slide},
+ render: res.render,
+ staticRenderFns: res.staticRenderFns
+ })
+ vm.$mount()
+ sinon.assert.called(spy)
+ vm.$destroy()
+ } finally {
+ window.console.error = _error
+ }
+ })
+
+ it('should not be able to work with v-model', (done) => {
+ let res = Vue.compile('1 2 ')
+ let vm = new Vue({
+ data () {
+ return {
+ index: 1
+ }
+ },
+ components: {Carousel, Slide},
+ render: res.render,
+ staticRenderFns: res.staticRenderFns
+ })
+ vm.$mount()
+ vm.$nextTick(() => {
+ expect(vm.$el.querySelectorAll('.carousel-inner .item.active').length).to.equal(1)
+ expect(vm.$el.querySelectorAll('.carousel-inner .item')[1].className).to.contain('active')
+ vm.$el.querySelector('.carousel-control.right').click()
+ setTimeout(() => {
+ expect(vm.$el.querySelectorAll('.carousel-inner .item.active').length).to.equal(1)
+ expect(vm.$el.querySelectorAll('.carousel-inner .item')[0].className).to.contain('active')
+ expect(vm.index).to.equal(0)
+ vm.$destroy()
+ done()
+ }, 700)
+ })
+ })
+
+ it('should be ok if no present in ', () => {
+ let res = Vue.compile('{{msg}} ')
+ let vm = new Vue({
+ data () {
+ return {
+ msg: 'hello'
+ }
+ },
+ components: {Carousel, Slide},
+ render: res.render,
+ staticRenderFns: res.staticRenderFns
+ })
+ vm.$mount()
+ vm.$destroy()
+ })
+})
diff --git a/pool/shard010/JavaScript/0068618_sanitized_test.js b/pool/shard010/JavaScript/0068618_sanitized_test.js
new file mode 100644
index 0000000000000000000000000000000000000000..60b0d963d06e284ebd9e4beb49a564e4a90fde3d
--- /dev/null
+++ b/pool/shard010/JavaScript/0068618_sanitized_test.js
@@ -0,0 +1,128 @@
+/* jshint scripturl:true */
+
+import EmberView from "ember-views/views/view";
+import compile from "ember-template-compiler/system/compile";
+import { SafeString } from "ember-htmlbars/utils/string";
+import { runAppend, runDestroy } from "ember-runtime/tests/utils";
+import environment from "ember-metal/environment";
+
+var view;
+
+QUnit.module("ember-htmlbars: sanitized attribute", {
+ teardown() {
+ runDestroy(view);
+ }
+});
+
+// jscs:disable validateIndentation
+// jscs:disable disallowTrailingWhitespace
+if (Ember.FEATURES.isEnabled('ember-htmlbars-attribute-syntax')) {
+
+var badTags = [
+ { tag: 'a', attr: 'href',
+ unquotedTemplate: compile(" "),
+ quotedTemplate: compile(" "),
+ multipartTemplate: compile(" ") },
+
+ { tag: 'base', attr: 'href',
+ unquotedTemplate: compile(" "),
+ quotedTemplate: compile(" "),
+ multipartTemplate: compile(" ") },
+
+ { tag: 'embed', attr: 'src',
+ unquotedTemplate: compile(" "),
+ quotedTemplate: compile(" "),
+ multipartTemplate: compile(" ") },
+
+ { tag: 'body', attr: 'background',
+ unquotedTemplate: compile(""),
+ quotedTemplate: compile(""),
+ multipartTemplate: compile("") },
+
+ { tag: 'link', attr: 'href',
+ unquotedTemplate: compile(" "),
+ quotedTemplate: compile(" "),
+ multipartTemplate: compile(" ") },
+
+ { tag: 'img', attr: 'src',
+ unquotedTemplate: compile(" "),
+ quotedTemplate: compile(" "),
+ multipartTemplate: compile(" ") },
+
+ { tag: 'iframe', attr: 'src',
+ // Setting an iframe with a bad protocol results in the browser
+ // being redirected. in IE8. Skip the iframe tests on that platform.
+ skip: (environment.hasDOM && document.documentMode && document.documentMode <= 8),
+ unquotedTemplate: compile(""),
+ quotedTemplate: compile(""),
+ multipartTemplate: compile("") }
+];
+
+for (var i=0, l=badTags.length; i= this.slidesCount ) {
+
+ this.current = 0;
+
+ }
+
+ this.$slides.eq( this.current ).addClass( 'da-slide-current' );
+
+ var $navigation = $( ' ' );
+ for( var i = 0; i < this.slidesCount; ++i ) {
+
+ $navigation.append( ' ' );
+
+ }
+ $navigation.appendTo( this.$el );
+
+ this.$pages = this.$el.find('nav.da-dots > span');
+ this.$navNext = this.$el.find('span.da-arrows-next');
+ this.$navPrev = this.$el.find('span.da-arrows-prev');
+
+ this.isAnimating = false;
+
+ this.bgpositer = 0;
+
+ this.cssAnimations = Modernizr.cssanimations;
+ this.cssTransitions = Modernizr.csstransitions;
+
+ if( !this.cssAnimations || !this.cssAnimations ) {
+
+ this.$el.addClass( 'da-slider-fb' );
+
+ }
+
+ this._updatePage();
+
+ // load the events
+ this._loadEvents();
+
+ // slideshow
+ if( this.options.autoplay ) {
+
+ this._startSlideshow();
+
+ }
+
+ },
+ _navigate : function( page, dir ) {
+
+ var $current = this.$slides.eq( this.current ), $next, _self = this;
+
+ if( this.current === page || this.isAnimating ) return false;
+
+ this.isAnimating = true;
+
+ // check dir
+ var classTo, classFrom, d;
+
+ if( !dir ) {
+
+ ( page > this.current ) ? d = 'next' : d = 'prev';
+
+ }
+ else {
+
+ d = dir;
+
+ }
+
+ if( this.cssAnimations && this.cssAnimations ) {
+
+ if( d === 'next' ) {
+
+ classTo = 'da-slide-toleft';
+ classFrom = 'da-slide-fromright';
+ ++this.bgpositer;
+
+ }
+ else {
+
+ classTo = 'da-slide-toright';
+ classFrom = 'da-slide-fromleft';
+ --this.bgpositer;
+
+ }
+
+ this.$el.css( 'background-position' , this.bgpositer * this.options.bgincrement + '% 0%' );
+
+ }
+
+ this.current = page;
+
+ $next = this.$slides.eq( this.current );
+
+ if( this.cssAnimations && this.cssAnimations ) {
+
+ var rmClasses = 'da-slide-toleft da-slide-toright da-slide-fromleft da-slide-fromright';
+ $current.removeClass( rmClasses );
+ $next.removeClass( rmClasses );
+
+ $current.addClass( classTo );
+ $next.addClass( classFrom );
+
+ $current.removeClass( 'da-slide-current' );
+ $next.addClass( 'da-slide-current' );
+
+ }
+
+ // fallback
+ if( !this.cssAnimations || !this.cssAnimations ) {
+
+ $next.css( 'left', ( d === 'next' ) ? '100%' : '-100%' ).stop().animate( {
+ left : '0%'
+ }, 1000, function() {
+ _self.isAnimating = false;
+ });
+
+ $current.stop().animate( {
+ left : ( d === 'next' ) ? '-100%' : '100%'
+ }, 1000, function() {
+ $current.removeClass( 'da-slide-current' );
+ });
+
+ }
+
+ this._updatePage();
+
+ },
+ _updatePage : function() {
+
+ this.$pages.removeClass( 'da-dots-current' );
+ this.$pages.eq( this.current ).addClass( 'da-dots-current' );
+
+ },
+ _startSlideshow : function() {
+
+ var _self = this;
+
+ this.slideshow = setTimeout( function() {
+
+ var page = ( _self.current < _self.slidesCount - 1 ) ? page = _self.current + 1 : page = 0;
+ _self._navigate( page, 'next' );
+
+ if( _self.options.autoplay ) {
+
+ _self._startSlideshow();
+
+ }
+
+ }, this.options.interval );
+
+ },
+ page : function( idx ) {
+
+ if( idx >= this.slidesCount || idx < 0 ) {
+
+ return false;
+
+ }
+
+ if( this.options.autoplay ) {
+
+ clearTimeout( this.slideshow );
+
+ this.options.autoplay = true;
+
+ }
+
+ this._navigate( idx );
+
+ },
+ _loadEvents : function() {
+
+ var _self = this;
+
+ this.$pages.on( 'click.cslider', function( event ) {
+
+ if( _self.options.autoplay ) {
+
+ _self._startSlideshow();
+
+ }
+
+ _self.page( $(this).index() );
+ return false;
+
+ });
+
+ this.$navNext.on( 'click.cslider', function( event ) {
+
+ if( _self.options.autoplay ) {
+
+ clearTimeout( _self.slideshow );
+
+ _self._startSlideshow();
+
+ }
+
+ var page = ( _self.current < _self.slidesCount - 1 ) ? page = _self.current + 1 : page = 0;
+ _self._navigate( page, 'next' );
+ return false;
+
+ });
+
+ this.$navPrev.on( 'click.cslider', function( event ) {
+
+ if( _self.options.autoplay ) {
+
+ clearTimeout( _self.slideshow );
+
+ _self._startSlideshow();
+
+ }
+
+ var page = ( _self.current > 0 ) ? page = _self.current - 1 : page = _self.slidesCount - 1;
+ _self._navigate( page, 'prev' );
+ return false;
+
+ });
+
+ if( this.cssTransitions ) {
+
+ if( !this.options.bgincrement ) {
+
+ this.$el.on( 'webkitAnimationEnd.cslider animationend.cslider OAnimationEnd.cslider', function( event ) {
+
+ if( event.originalEvent.animationName === 'toRightAnim4' || event.originalEvent.animationName === 'toLeftAnim4' ) {
+
+ _self.isAnimating = false;
+
+ }
+
+ });
+
+ }
+ else {
+
+ this.$el.on( 'webkitTransitionEnd.cslider transitionend.cslider OTransitionEnd.cslider', function( event ) {
+
+ if( event.target.id === _self.$el.attr( 'id' ) )
+ _self.isAnimating = false;
+
+ });
+
+ }
+
+ }
+
+ }
+ };
+
+ var logError = function( message ) {
+ if ( this.console ) {
+ console.error( message );
+ }
+ };
+
+ $.fn.cslider = function( options ) {
+
+ if ( typeof options === 'string' ) {
+
+ var args = Array.prototype.slice.call( arguments, 1 );
+
+ this.each(function() {
+
+ var instance = $.data( this, 'cslider' );
+
+ if ( !instance ) {
+ logError( "cannot call methods on cslider prior to initialization; " +
+ "attempted to call method '" + options + "'" );
+ return;
+ }
+
+ if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
+ logError( "no such method '" + options + "' for cslider instance" );
+ return;
+ }
+
+ instance[ options ].apply( instance, args );
+
+ });
+
+ }
+ else {
+
+ this.each(function() {
+
+ var instance = $.data( this, 'cslider' );
+ if ( !instance ) {
+ $.data( this, 'cslider', new $.Slider( options, this ) );
+ }
+ });
+
+ }
+
+ return this;
+
+ };
+
+})( jQuery );
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068623_FileStorage.js b/pool/shard010/JavaScript/0068623_FileStorage.js
new file mode 100644
index 0000000000000000000000000000000000000000..68f292d23ed7f42242b8df19ca73a776524a1528
--- /dev/null
+++ b/pool/shard010/JavaScript/0068623_FileStorage.js
@@ -0,0 +1,170 @@
+"use strict";
+var fs = require('fs');
+var path = require('path');
+var env = require('./env');
+var Spec = require('./Spec');
+var Storage = require('./Storage');
+
+/**
+ * An improvised filesystem-based storage implementation.
+ * Objects are saved into separate files in a hashed directory
+ * tree. Ongoing operations are streamed into a log file.
+ * One can go surprisingly far with this kind of an approach.
+ * https://news.ycombinator.com/item?id=7872239 */
+function FileStorage (dir) {
+ Storage.call(this);
+ this._host = null; //will be set during Host creation
+ this.dir = path.resolve(dir);
+ if (!fs.existsSync(this.dir)) {
+ fs.mkdirSync(this.dir);
+ }
+ this._id = 'file';
+ this.tail = {};
+
+ this.loadLog();
+ this.rotateLog();
+}
+FileStorage.prototype = new Storage();
+module.exports = FileStorage;
+
+FileStorage.prototype.stateFileName = function (spec) {
+ var base = path.resolve(this.dir, spec.type());
+ var file = path.resolve(base, spec.id());
+ return file; // TODO hashing?
+};
+
+FileStorage.prototype.logFileName = function () {
+ return path.resolve(this.dir, "_log");
+};
+
+FileStorage.prototype.writeState = function (spec, state, cb) {
+ var self = this;
+ var ti = spec.filter('/#');
+ var fileName = this.stateFileName(ti);
+ var dir = path.dirname(fileName);
+ if (!fs.existsSync(dir)) {
+ fs.mkdirSync(dir);
+ }
+ var save = JSON.stringify(state, undefined, 2);
+ // dump JSON to the tmp file
+ delete self.tails[ti]; // TODO save 'em in case write fails
+ fs.writeFile(fileName, save, function onSave(err) {
+ if (err) {
+ console.error("failed to flush state; can't trim the log", err);
+ }
+ cb(err);
+ });
+};
+
+FileStorage.prototype.writeOp = function (spec, value, cb) {
+ var self = this;
+ var ti = spec.filter('/#');
+ var vm = spec.filter('!.');
+ var tail = this.tails[ti] || (this.tails[ti] = {});
+ if (vm in tail) {
+ console.error('op replay @storage',vm,new Error().stack);
+ return;
+ }
+ var clone = JSON.parse(JSON.stringify(value)); // FIXME performance please
+ tail[vm] = clone;
+ var record = ',\n"'+spec+'":\t'+JSON.stringify(clone);
+ this.logFile.write (record, function onFail(err) {
+ if (err) { self.close(null,err); }
+ cb(err);
+ });
+};
+
+
+FileStorage.prototype.readState = function (ti, callback) {
+ var statefn = this.stateFileName(ti);
+ // read in the state
+ fs.readFile(statefn, function onRead(err, data) { // FIXME fascism
+ var state = err ? {_version: '!0'} : JSON.parse(data.toString());
+ callback(null,state||null); // important: no state is "null"
+ });
+};
+
+
+FileStorage.prototype.readOps = function (ti, callback) {
+ var tail = this.tails[ti];
+ if (tail) {
+ var unjsoned = {};
+ for(var key in tail) {
+ unjsoned[key] = tail[key];
+ }
+ tail = unjsoned;
+ }
+ callback(null, tail||null);
+};
+
+
+FileStorage.prototype.close = function (callback,error) {
+ if (error) {
+ console.log("fatal IO error", error);
+ }
+ if (this.logFile) {
+ this.rotateLog(true, callback);
+ } else {
+ callback();
+ }
+};
+
+
+FileStorage.prototype.rotateLog = function (noOpen, callback) {
+ var self = this;
+ if (this.logFile) {
+ this.logFile.end('}', callback);
+ this.logFile = null;
+ callback = undefined;
+ }
+
+ if (!noOpen) {
+
+ if (fs.existsSync(this.logFileName())) {
+ fs.rename(this.logFileName(),this.logFileName()+'.bak');
+ }
+ this.logFile = fs.createWriteStream(this.logFileName()); // TODO file swap
+ this.logFile.on('error', function (err) {
+ self.close(null,err);
+ });
+
+ var json = JSON.stringify(this.tails, undefined, 2);
+ json = '{"":\n' + json; // open-ended JSON
+
+ this.logFile.write (json, function onFail(err) {
+ if (err) { self.close(null,err); }
+ });
+
+ }
+
+ if (callback) {
+ callback();
+ }
+
+};
+
+FileStorage.prototype.loadLog = function () {
+ if ( !fs.existsSync(this.logFileName()) ) {
+ return;
+ }
+ var json = fs.readFileSync(this.logFileName(), {encoding:"utf8"});
+ if (!json) { return; }
+ var log;
+ try {
+ log = JSON.parse(json);
+ } catch (ex) {
+ // open-ended JSON
+ log = JSON.parse(json + '}');
+ }
+ this.tails = log[''];
+ delete log[''];
+ for(var s in log) {
+ var spec = new Spec(s);
+ if (spec.pattern()==='/#!.') {
+ var ti = spec.filter('/#');
+ var vm = spec.filter('!.');
+ var tail = this.tails[ti] || (this.tails[ti] = {});
+ tail[vm] = log[spec];
+ }
+ }
+};
diff --git a/pool/shard010/JavaScript/0068626_render_params.js b/pool/shard010/JavaScript/0068626_render_params.js
new file mode 100644
index 0000000000000000000000000000000000000000..99e07be4c49fe701d08603f57021a22cd3dd9112
--- /dev/null
+++ b/pool/shard010/JavaScript/0068626_render_params.js
@@ -0,0 +1,42 @@
+goog.provide('jchemhub.config.RenderParams');
+
+goog.require("goog.graphics");
+goog.require('goog.graphics.SolidFill');
+goog.require('goog.graphics.Stroke');
+goog.require('goog.graphics.Font');
+
+jchemhub.config.RenderParams=function(){
+
+};
+
+jchemhub.config.RenderParams.get=function(){
+ return jchemhub.config.RenderParams.defaultValue;
+ //TODO implement config persistence with cookies
+}
+jchemhub.config.RenderParams.defaultValue = {
+ zoomFactor: 0.8,
+ margin: 0.05,
+ bondDistance:3,
+ showExplicitHydrogens:true,
+ showImplicitHydrogens:true,
+ drawEndCarbon:true,
+ backgroundFill:new goog.graphics.SolidFill('#F0FFF0'),
+ bondStroke:new goog.graphics.Stroke(2, 'black'),
+ upBondStroke:new goog.graphics.Stroke(1, 'black'),
+ upBondFill:new goog.graphics.SolidFill('black'),
+ downBondStroke:new goog.graphics.Stroke(1, 'black'),
+ downBondFill:null,
+ upOrDownBondStroke:new goog.graphics.Stroke(1, 'black'),
+ upOrDownBondFill:null,
+ bondHighlightStroke:new goog.graphics.Stroke(2, 'blue'),
+ atomFont:new goog.graphics.Font(0, 'Times'), //Font size is dynamic
+ atomSubFont:new goog.graphics.Font(0, 'Times'), //Font size is dynamic
+ atomLabelStroke:null,
+ atomLabelFill:{"C":new goog.graphics.SolidFill('black'),
+ "N":new goog.graphics.SolidFill('blue'),
+ "O":new goog.graphics.SolidFill('red')
+ },
+ atomTransparentCircleSize:9,
+ atomHighlightStroke:new goog.graphics.Stroke(2, 'blue'),
+ transparentFill:new goog.graphics.SolidFill('blue', 0.00001) //This is a closure library bug. Transparent can not set to zero. I've submitted a patch, waiting for their fix.
+};
diff --git a/pool/shard010/JavaScript/0068627_test.taskqueue.js b/pool/shard010/JavaScript/0068627_test.taskqueue.js
new file mode 100644
index 0000000000000000000000000000000000000000..d875872cf70291212e87eb5fb148c0ddb77ad9d8
--- /dev/null
+++ b/pool/shard010/JavaScript/0068627_test.taskqueue.js
@@ -0,0 +1,71 @@
+'use strict';
+
+var adapters = ['http', 'local'];
+
+adapters.forEach(function (adapter) {
+ describe('test.taskqueue.js-' + adapter, function () {
+
+ var dbs = {};
+
+ beforeEach(function (done) {
+ dbs.name = testUtils.adapterUrl(adapter, 'test_taskqueue');
+ testUtils.cleanup([dbs.name], done);
+ });
+
+ after(function (done) {
+ testUtils.cleanup([dbs.name], done);
+ });
+
+
+ it('Add a doc', function (done) {
+ var db = new PouchDB(dbs.name);
+ db.post({ test: 'somestuff' }, function (err, info) {
+ done(err);
+ });
+ });
+
+ it('Query', function (done) {
+ var db = new PouchDB(dbs.name);
+ var queryFun = {
+ map: function (doc) {
+ }
+ };
+ db.query(queryFun, { reduce: false }, function (_, res) {
+ res.rows.should.have.length(0);
+ done();
+ });
+ });
+
+ it('Bulk docs', function (done) {
+ var db = new PouchDB(dbs.name);
+ db.bulkDocs({
+ docs: [
+ { test: 'somestuff' },
+ { test: 'another' }
+ ]
+ }, function (err, infos) {
+ should.not.exist(infos[0].error);
+ should.not.exist(infos[1].error);
+ done();
+ });
+ });
+
+ it('Get', function (done) {
+ var db = new PouchDB(dbs.name);
+ db.get('0', function (err, res) {
+ should.exist(err);
+ done();
+ });
+ });
+
+ it('Info', function (done) {
+ var db = new PouchDB(dbs.name);
+ db.info(function (err, info) {
+ info.doc_count.should.equal(0);
+ info.update_seq.should.equal(0);
+ done();
+ });
+ });
+
+ });
+});
diff --git a/pool/shard010/JavaScript/0068628_SettingsSceneContent.js b/pool/shard010/JavaScript/0068628_SettingsSceneContent.js
new file mode 100644
index 0000000000000000000000000000000000000000..ffa74e4a86e2e24e71163ccf92abfa20edb55db3
--- /dev/null
+++ b/pool/shard010/JavaScript/0068628_SettingsSceneContent.js
@@ -0,0 +1,214 @@
+import PropTypes from 'prop-types'
+import React from 'react'
+import { DialogContent, DialogActions, Button, Tabs, Tab, AppBar } from '@material-ui/core'
+import GeneralSettings from './GeneralSettings'
+import ExtensionSettings from './ExtensionSettings'
+import AccountSettings from './Accounts/AccountSettings'
+import ProSettings from './ProSettings'
+import SupportSettings from './SupportSettings'
+import shallowCompare from 'react-addons-shallow-compare'
+import { WB_RELAUNCH_APP } from 'shared/ipcEvents'
+import { ipcRenderer } from 'electron'
+import { withStyles } from '@material-ui/core/styles'
+import lightBlue from '@material-ui/core/colors/lightBlue'
+
+const styles = {
+ // Dialog
+ dialogContent: {
+ position: 'relative',
+ backgroundColor: 'rgb(242, 242, 242)'
+ },
+ dialogActions: {
+ backgroundColor: 'white',
+ borderTop: '1px solid rgb(232, 232, 232)',
+ margin: 0,
+ padding: '8px 4px'
+ },
+
+ // Tabs
+ appBar: {
+ backgroundColor: lightBlue[600]
+ },
+ tabButton: {
+ color: 'white',
+ maxWidth: 'none'
+ },
+ tabInkBar: {
+ backgroundColor: lightBlue[100]
+ },
+
+ // Footer
+ button: {
+ marginLeft: 8,
+ marginRight: 8
+ }
+}
+
+@withStyles(styles)
+class SettingsSceneContent extends React.Component {
+ /* **************************************************************************/
+ // Class
+ /* **************************************************************************/
+
+ static propTypes = {
+ match: PropTypes.shape({
+ params: PropTypes.shape({
+ tab: PropTypes.string,
+ tabArg: PropTypes.string
+ }).isRequired
+ }).isRequired
+ }
+
+ /* **************************************************************************/
+ // Data lifecycle
+ /* **************************************************************************/
+
+ state = {
+ showRestart: false
+ }
+
+ /* **************************************************************************/
+ // User Interaction
+ /* **************************************************************************/
+
+ /**
+ * Changes the tab
+ */
+ handleTabChange = (evt, value) => {
+ if (typeof (value) === 'string') {
+ window.location.hash = `/settings/${value}`
+ }
+ }
+
+ /**
+ * Shows the option to restart
+ */
+ handleShowRestart = () => {
+ this.setState({ showRestart: true })
+ }
+
+ /**
+ * Closes the modal
+ */
+ handleClose = () => {
+ window.location.hash = '/'
+ }
+
+ /**
+ * Restarts the app
+ */
+ handleRestart = () => {
+ // The temptation for the user is sometimes to edit a field and hit restart,
+ // but this can leave some waiting ipc events and data that isn't written to
+ // disk. Seeing that we don't have a "wait for everything to finish" call at
+ // the moment we need to wait a little time. By the way this is really bad,
+ // but it's an infrequent event and just fixes it. (@Thomas101) we should
+ // look into a better solution to this problem
+
+ // Close the popup so it looks like something is happening
+ setTimeout(() => {
+ this.handleClose()
+ }, 250)
+
+ // Wait and then restart
+ setTimeout(() => {
+ ipcRenderer.send(WB_RELAUNCH_APP, { })
+ }, 1000)
+ }
+
+ /* **************************************************************************/
+ // Rendering
+ /* **************************************************************************/
+
+ shouldComponentUpdate (nextProps, nextState) {
+ return shallowCompare(this, nextProps, nextState)
+ }
+
+ /**
+ * @param classes:
+ * @param currentTab: the current tab
+ * @param tabArg: any arguments for the tab
+ */
+ renderTab (classes, currentTab, tabArg) {
+ if (currentTab === 'general') {
+ return ( )
+ } else if (currentTab === 'extensions') {
+ return ( )
+ } else if (currentTab === 'accounts') {
+ return (
+
+ )
+ } else if (currentTab === 'support') {
+ return ( )
+ } else if (currentTab === 'pro') {
+ return ( )
+ }
+ }
+
+ render () {
+ const { showRestart } = this.state
+ const { classes, match } = this.props
+
+ const tab = match.params.tab || 'general'
+ const tabArg = match.params.tabArg
+
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ {this.renderTab(classes, tab, tabArg)}
+
+
+
+ Close
+
+ {showRestart ? (
+
+ Restart
+
+ ) : undefined}
+
+
+ )
+ }
+}
+
+export default SettingsSceneContent
diff --git a/pool/shard010/JavaScript/0068629_transition.js b/pool/shard010/JavaScript/0068629_transition.js
new file mode 100644
index 0000000000000000000000000000000000000000..a1cd2e741d7f09d2a00d2ab9f47dfdc2dc23a2ab
--- /dev/null
+++ b/pool/shard010/JavaScript/0068629_transition.js
@@ -0,0 +1,28 @@
+var Tween = require('./loop/tween').Tween;
+var util = require('./util');
+
+/**
+ * ## *constructor*
+ *
+ * @param options
+ * @constructor
+ */
+var Transition = function(state, options) {
+ options = options || {};
+ Tween.prototype.constructor.call(this, state, _transition, options.from, options.to, options.duration, options.easing);
+};
+util.inherits(Transition, Tween);
+
+function _transition() {
+ var args = Array.prototype.slice.call(arguments);
+ args.unshift('transition');
+ this.transition.apply(this, args);
+}
+
+/**
+ * **internal sugar**
+ * - - - - - - - - -
+ */
+
+/** **exports** */
+module.exports.Transition = Transition;
diff --git a/pool/shard010/JavaScript/0068630_author-model.js b/pool/shard010/JavaScript/0068630_author-model.js
new file mode 100644
index 0000000000000000000000000000000000000000..d19212742ed3d34b92caeb264d1413fcf01b3257
--- /dev/null
+++ b/pool/shard010/JavaScript/0068630_author-model.js
@@ -0,0 +1,19 @@
+const findName = name => author => author.uid === name;
+const authorEdgesToList = authorEdges => authorEdges.map(edge => edge.node);
+
+class AuthorModel {
+ static hasAuthor(authorEdges, authorUid) {
+ const authorList = authorEdgesToList(authorEdges);
+ return Boolean(authorList.find(findName(authorUid)));
+ }
+
+ static getAuthor(authorEdges, authorUid, fallbackId) {
+ const authorList = authorEdgesToList(authorEdges);
+ if (this.hasAuthor(authorEdges, authorUid)) {
+ return authorList.find(findName(authorUid));
+ }
+ return authorList.find(findName(fallbackId));
+ }
+}
+
+export default AuthorModel;
diff --git a/pool/shard010/JavaScript/0068631_statistics.js b/pool/shard010/JavaScript/0068631_statistics.js
new file mode 100644
index 0000000000000000000000000000000000000000..ad9212daef9139474291d7258ebf546c17187991
--- /dev/null
+++ b/pool/shard010/JavaScript/0068631_statistics.js
@@ -0,0 +1,168 @@
+const _ = require('lodash');
+const moment = require('moment');
+const Promise = require('bluebird');
+const debug = require('debug')('routes:statistics');
+const nconf = require('nconf');
+
+const mongo = require('../lib/mongo');
+
+const cache = {};
+const cacheTime = 120;
+
+function formatCached(what, updated) {
+
+ let ref = _.get(cache, what, {
+ content: null,
+ computedAt: null,
+ next: null,
+ });
+ if(updated) {
+ ref.content = updated.content;
+ ref.computedAt = updated.computedAt;
+ ref.next = updated.next;
+ _.set(cache, what, ref);
+ }
+ if(!ref.content) throw new Error("Invalid cache usage");
+ return {
+ json: {
+ content: ref.content,
+ computedt: ref.computedAt.toISOString(),
+ next: ref.next.toISOString(),
+ cacheTimeSeconds: cacheTime,
+ }
+ };
+};
+
+function cacheAvailable(what) {
+ let ref = _.get(cache, what);
+ if(!ref)
+ return null;
+ if(ref.next && moment().isAfter(ref.next))
+ return null;
+ if(!ref.content)
+ return null;
+
+ return true;
+}
+
+function countStoredDocuments() {
+ const p = {};
+ const aweekago = moment().subtract(1, 'week').toISOString();
+ const timeVars = {
+ impressions: 'impressionTime',
+ supporters: 'keyTime',
+ timelines: 'startTime',
+ accesses: 'when',
+ htmls: 'savingTime',
+ metadata: 'impressionTime',
+ errors: 'when',
+ summary: 'impressionTime',
+ anomalies: 'when',
+ semantics: 'when',
+ labels: 'when',
+ // feeds: "feeds",
+ aggregated: 'hourOnly',
+ };
+
+ return Promise
+ .map(_.keys(timeVars), function(c) {
+ let lastwtv = _.set({}, timeVars[c], { "$gte": new Date(aweekago) });
+ return Promise.all([
+ mongo.count(nconf.get('schema')[c]),
+ mongo.count(nconf.get('schema')[c], lastwtv)
+ ])
+ .tap(function(numbers) {
+ _.set(p, c, numbers[0]);
+ _.set(p, `${c}_lw`, numbers[1]);
+ });
+ }, { concurrency: 1 })
+ .return(p);
+};
+
+function counter(req) {
+
+ return Promise.resolve().then(function() {
+ if(cacheAvailable('counter'))
+ return formatCached('counter');
+ })
+ .then(function(tbd) {
+ if(tbd) return tbd;
+ return countStoredDocuments()
+ .then(function(fresh) {
+ const updated = {
+ content: fresh,
+ computedAt: moment(),
+ next: moment().add(cacheTime, 'seconds')
+ };
+ return formatCached('counter', updated);
+ })
+ .catch(function(error) {
+ debug("Error in counter: %s", error.message);
+ return { json: { error: true, message: error.message }};
+ });
+ });
+}
+
+function parsers(req) {
+ // the content in 'aggregated' is saved by parserv in regards of parsed content
+ const days = 14;
+ debug("Requested aggregated parsers results (last %d days hardcoded)", days);
+ const twoWeeks = moment().subtract(days, 'days');
+ const expected = 24 * days;
+ return mongo
+ .read(nconf.get('schema').aggregated, { hourOnly: { $gt: new Date(twoWeeks) }})
+ .then(function(all) {
+ if(_.size(all) != expected)
+ debug("(?) Returning %d elements on %d expected", _.size(all), expected);
+ return { json: all };
+ });
+};
+
+function statistics(req) {
+ // the content in 'stats' is saved by count-o-clock and the selector here required is
+ // specifiy in config/stats.json
+ const expectedFormat = "/api/v2/statistics/:name/:unit/:amount";
+
+
+ const allowedNames = ['supporters', 'active', 'timelines', 'metadata',
+ 'processing', 'impressions'];
+ const name = req.params.name;
+ if(allowedNames.indexOf(name) == -1)
+ return { json: { error: true, expectedFormat, allowedNames, note: `the statistic name you look for was ${name}` }}
+
+ const unit = req.params.unit;
+ const allowedRanges = ['hours', 'hour', 'day', 'days'];
+ if(allowedRanges.indexOf(unit) == -1 )
+ return { json: { error: true, expectedFormat, allowedRanges, note: `the statistic unit you look for was ${unit}` }}
+
+ const amount = _.parseInt(req.params.amount);
+ if(_.isNaN(amount))
+ return { json: { error: true, expectedFormat, invalidNumber: req.params.amount }};
+
+ debug("Requested statistics %s (since %d %s)", name, amount, unit);
+
+ const filter = { name };
+ const refDate = new Date( moment().subtract(amount, _.nth(unit, 0)));
+
+ if(_.startsWith(unit, 'day'))
+ _.set(filter, 'day', { '$gt': refDate });
+ else
+ _.set(filter, 'hour', { '$gt': refDate });
+
+ return mongo
+ .read(nconf.get('schema').stats, filter)
+ .map(function(e) {
+ return _.omit(e, ['_id'])
+ })
+ .then(function(content) {
+ return { json: content,
+ headers: { amount, unit, name }
+ };
+ });
+}
+
+module.exports = {
+ counter,
+ statistics,
+ parsers
+};
diff --git a/pool/shard010/JavaScript/0068632_main.js b/pool/shard010/JavaScript/0068632_main.js
new file mode 100644
index 0000000000000000000000000000000000000000..1a1537e1958d0b8c72a49c0becb85a27043de546
--- /dev/null
+++ b/pool/shard010/JavaScript/0068632_main.js
@@ -0,0 +1,71 @@
+import * as Simple from './lib/simple.es.js';
+import * as three from 'three';
+
+import Camera from './camera';
+import Viewport from './viewport';
+import Game from './game';
+
+
+// Set up Simple.World
+const worldSetup = () => {
+ const world = new Simple.World();
+ world.ComponentManager = new Simple.ComponentManager();
+ world.EntityManager = new Simple.EntityManager();
+ world.SystemManager = new Simple.SystemManager();
+
+ return world;
+};
+
+
+// onload bootstrap
+const init = () => {
+ const viewport = new Viewport(),
+ scene = new three.Scene(),
+ camera = new Camera(),
+ world = worldSetup();
+
+ viewport.setup();
+ camera.setup();
+
+ const game = new Game(world);
+ game.setup();
+
+ let playerSprite = new three.Sprite(),
+ mobSprite = new three.Sprite();
+
+ world.entities.attachComponents(
+ game.instances.player, {
+ sprite: playerSprite
+ }
+ );
+
+ world.entities.attachComponents(
+ game.instances.mob, {
+ sprite: mobSprite
+ }
+ );
+
+ scene.add(playerSprite);
+ scene.add(mobSprite);
+
+ // Get a Loop and run `world.go()`.
+ const loopFactory = new Simple.LoopFactory(
+ Simple.extrapolated_loop,
+ world.update.bind(world),
+ (lagOffset) => {
+ camera.camera.lookAt(scene.position);
+
+ viewport.renderer.render(scene, camera.camera);
+ },
+ world
+ );
+ let frame = loopFactory.build();
+
+ let reqId = world.go(frame);
+
+ setTimeout(() => {
+ world.stop(frame, reqId);
+ }, 10000);
+};
+
+window.onload = init;
diff --git a/pool/shard010/JavaScript/0068633_15.4.4.19-8-b-6.js b/pool/shard010/JavaScript/0068633_15.4.4.19-8-b-6.js
new file mode 100644
index 0000000000000000000000000000000000000000..6f983455ee1c28c48309ec26b62adc17d9b7842f
--- /dev/null
+++ b/pool/shard010/JavaScript/0068633_15.4.4.19-8-b-6.js
@@ -0,0 +1,39 @@
+// Copyright (c) 2012 Ecma International. All rights reserved.
+// This code is governed by the BSD license found in the LICENSE file.
+
+/*---
+esid: sec-array.prototype.map
+es5id: 15.4.4.19-8-b-6
+description: >
+ Array.prototype.map - properties can be added to prototype after
+ current position are visited on an Array-like object
+---*/
+
+function callbackfn(val, idx, obj) {
+ if (idx === 1 && val === 6.99) {
+ return false;
+ } else {
+ return true;
+ }
+}
+var obj = {
+ length: 2
+};
+
+Object.defineProperty(obj, "0", {
+ get: function() {
+ Object.defineProperty(Object.prototype, "1", {
+ get: function() {
+ return 6.99;
+ },
+ configurable: true
+ });
+ return 0;
+ },
+ configurable: true
+});
+
+var testResult = Array.prototype.map.call(obj, callbackfn);
+
+assert.sameValue(testResult[0], true, 'testResult[0]');
+assert.sameValue(testResult[1], false, 'testResult[1]');
diff --git a/pool/shard010/JavaScript/0068634_cache.js b/pool/shard010/JavaScript/0068634_cache.js
new file mode 100644
index 0000000000000000000000000000000000000000..451514682ed2084f12e6ff1ce2d3cf4357319445
--- /dev/null
+++ b/pool/shard010/JavaScript/0068634_cache.js
@@ -0,0 +1,109 @@
+/*global exports: true, process: true, require: true */
+/*jslint onevar: true, undef: true, nomen: true, eqeqeq: true, bitwise: true, newcap: true, immed: true */
+var crypto = require('crypto'),
+ fs = require('fs'),
+ glob = require('glob'),
+ path = require('path'),
+
+ mkdirp = require('mkdir-p'),
+ solder = require('solder');
+
+function Cache() {
+ var self = this;
+
+ this.CACHE_DIR = solder.HOME_DIR + '/.solder';
+
+ mkdirp(this.CACHE_DIR, 0755, function (err) {
+ if (err) { throw err; }
+
+ self.purgeExpired();
+ });
+}
+
+Cache.prototype.fetch = function (key, callback) {
+ var now = Math.floor((new Date()).getTime() / 1000),
+ pattern = this.CACHE_DIR + '/solder.*.' + this.keyHash(key),
+ self = this;
+
+ glob.glob(pattern, 0, function (err, files) {
+ if (err) {
+ return callback(err);
+ }
+
+ if (!files.length) {
+ return callback(null, null);
+ }
+
+ files.forEach(function (filename) {
+ var meta = self.parseFilename(filename);
+
+ if (meta && meta.expires <= now) {
+ fs.unlink(filename);
+ callback(null, null);
+ }
+ else {
+ fs.readFile(filename, function (err, data) {
+ if (err) {
+ return callback(err);
+ }
+
+ callback(null, data);
+ });
+ }
+ });
+ });
+};
+
+Cache.prototype.store = function (key, value, expires, callback) {
+ expires = expires || Math.floor((new Date()).getTime() / 1000) + 1800;
+
+ var filename = path.join(this.CACHE_DIR, 'solder.' + expires + '.' +
+ this.keyHash(key));
+
+ fs.writeFile(filename, value, function (err) {
+ if (err) {
+ return callback(err);
+ }
+
+ callback(null, value);
+ });
+};
+
+// -- Protected --------------------------------------------------------------
+
+Cache.prototype.keyHash = function (key) {
+ return crypto.createHash('sha1').update(key).digest('hex');
+};
+
+Cache.prototype.parseFilename = function (filename) {
+ var match = path.basename(filename).match(/^solder\.([0-9]+)\.([0-9a-f]{40})$/),
+ expires, hash;
+
+ if (match) {
+ expires = parseInt(match[1], 10);
+ hash = match[2];
+
+ return {expires: expires, hash: hash};
+ }
+};
+
+Cache.prototype.purgeExpired = function () {
+ var now = (new Date()).getTime(),
+ self = this;
+
+ glob.glob(this.CACHE_DIR + '/solder.*', 0, function (err, files) {
+ if (!err) {
+ files.forEach(function (filename) {
+ var meta = self.parseFilename(filename);
+
+ if (meta && meta.expires <= now) {
+ fs.unlink(path.join(self.CACHE_DIR, filename));
+ }
+ });
+ }
+ });
+};
+
+// -- Exports ----------------------------------------------------------------
+
+exports.create = function () { return new Cache(); };
diff --git a/pool/shard010/JavaScript/0068638_improvedigital.js b/pool/shard010/JavaScript/0068638_improvedigital.js
new file mode 100644
index 0000000000000000000000000000000000000000..16419918b010c4ff671cf02245410646e67b31b0
--- /dev/null
+++ b/pool/shard010/JavaScript/0068638_improvedigital.js
@@ -0,0 +1,64 @@
+/**
+ * Copyright 2016 The AMP HTML Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS-IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {validateData, writeScript} from '../3p/3p';
+
+/**
+ * @param {!Window} global
+ * @param {!Object} data
+ */
+export function improvedigital(global, data) {
+ validateData(data, ['placement'], ['width', 'height', 'optin', 'keyvalue']);
+
+ let url =
+ 'https://ad.360yield.com' +
+ '/adj?' +
+ 'p=' +
+ encodeURIComponent(data.placement) +
+ '&w=' +
+ encodeURIComponent(data.width) +
+ '&h=' +
+ encodeURIComponent(data.height) +
+ '&optin=' +
+ encodeURIComponent(data.optin) +
+ '&tz=' +
+ new Date().getTimezoneOffset();
+
+ const value = data.keyvalue;
+ let newData = '';
+ const amps = '&';
+ let validKey = 0;
+
+ if (value && value.length > 0) {
+ const keys = value.split('&');
+ for (let i = 0; i < keys.length; i++) {
+ if (!keys[i]) {
+ continue;
+ }
+ const segment = keys[i].split('=');
+ const segment1 = segment[1] ? encodeURIComponent(segment[1]) : '';
+ if (validKey > 0) {
+ newData += amps;
+ }
+ validKey++;
+ newData += segment[0] + '=' + segment1;
+ }
+ }
+ if (newData) {
+ url += '&' + newData;
+ }
+ writeScript(global, url);
+}
diff --git a/pool/shard010/JavaScript/0068643_domobject.js b/pool/shard010/JavaScript/0068643_domobject.js
new file mode 100644
index 0000000000000000000000000000000000000000..e51039738add5242fe288717d9ae8d7e113cd5b0
--- /dev/null
+++ b/pool/shard010/JavaScript/0068643_domobject.js
@@ -0,0 +1,246 @@
+/*
+Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
+For licensing, see LICENSE.html or http://ckeditor.com/license
+*/
+
+/**
+ * @fileOverview Defines the {@link CKEDITOR.editor} class, which is the base
+ * for other classes representing DOM objects.
+ */
+
+/**
+ * Represents a DOM object. This class is not intended to be used directly. It
+ * serves as the base class for other classes representing specific DOM
+ * objects.
+ * @constructor
+ * @param {Object} nativeDomObject A native DOM object.
+ * @augments CKEDITOR.event
+ * @example
+ */
+CKEDITOR.dom.domObject = function( nativeDomObject )
+{
+ if ( nativeDomObject )
+ {
+ /**
+ * The native DOM object represented by this class instance.
+ * @type Object
+ * @example
+ * var element = new CKEDITOR.dom.element( 'span' );
+ * alert( element.$.nodeType ); // "1"
+ */
+ this.$ = nativeDomObject;
+ }
+};
+
+CKEDITOR.dom.domObject.prototype = (function()
+{
+ // Do not define other local variables here. We want to keep the native
+ // listener closures as clean as possible.
+
+ var getNativeListener = function( domObject, eventName )
+ {
+ return function( domEvent )
+ {
+ // In FF, when reloading the page with the editor focused, it may
+ // throw an error because the CKEDITOR global is not anymore
+ // available. So, we check it here first. (#2923)
+ if ( typeof CKEDITOR != 'undefined' )
+ domObject.fire( eventName, new CKEDITOR.dom.event( domEvent ) );
+ };
+ };
+
+ return /** @lends CKEDITOR.dom.domObject.prototype */ {
+
+ getPrivate : function()
+ {
+ var priv;
+
+ // Get the main private function from the custom data. Create it if not
+ // defined.
+ if ( !( priv = this.getCustomData( '_' ) ) )
+ this.setCustomData( '_', ( priv = {} ) );
+
+ return priv;
+ },
+
+ /** @ignore */
+ on : function( eventName )
+ {
+ // We customize the "on" function here. The basic idea is that we'll have
+ // only one listener for a native event, which will then call all listeners
+ // set to the event.
+
+ // Get the listeners holder object.
+ var nativeListeners = this.getCustomData( '_cke_nativeListeners' );
+
+ if ( !nativeListeners )
+ {
+ nativeListeners = {};
+ this.setCustomData( '_cke_nativeListeners', nativeListeners );
+ }
+
+ // Check if we have a listener for that event.
+ if ( !nativeListeners[ eventName ] )
+ {
+ var listener = nativeListeners[ eventName ] = getNativeListener( this, eventName );
+
+ if ( this.$.addEventListener )
+ this.$.addEventListener( eventName, listener, !!CKEDITOR.event.useCapture );
+ else if ( this.$.attachEvent )
+ this.$.attachEvent( 'on' + eventName, listener );
+ }
+
+ // Call the original implementation.
+ return CKEDITOR.event.prototype.on.apply( this, arguments );
+ },
+
+ /** @ignore */
+ removeListener : function( eventName )
+ {
+ // Call the original implementation.
+ CKEDITOR.event.prototype.removeListener.apply( this, arguments );
+
+ // If we don't have listeners for this event, clean the DOM up.
+ if ( !this.hasListeners( eventName ) )
+ {
+ var nativeListeners = this.getCustomData( '_cke_nativeListeners' );
+ var listener = nativeListeners && nativeListeners[ eventName ];
+ if ( listener )
+ {
+ if ( this.$.removeEventListener )
+ this.$.removeEventListener( eventName, listener, false );
+ else if ( this.$.detachEvent )
+ this.$.detachEvent( 'on' + eventName, listener );
+
+ delete nativeListeners[ eventName ];
+ }
+ }
+ },
+
+ /**
+ * Removes any listener set on this object.
+ * To avoid memory leaks we must assure that there are no
+ * references left after the object is no longer needed.
+ */
+ removeAllListeners : function()
+ {
+ var nativeListeners = this.getCustomData( '_cke_nativeListeners' );
+ for ( var eventName in nativeListeners )
+ {
+ var listener = nativeListeners[ eventName ];
+ if ( this.$.removeEventListener )
+ this.$.removeEventListener( eventName, listener, false );
+ else if ( this.$.detachEvent )
+ this.$.detachEvent( 'on' + eventName, listener );
+
+ delete nativeListeners[ eventName ];
+ }
+ }
+ };
+})();
+
+(function( domObjectProto )
+{
+ var customData = {};
+
+ /**
+ * Determines whether the specified object is equal to the current object.
+ * @name CKEDITOR.dom.domObject.prototype.equals
+ * @function
+ * @param {Object} object The object to compare with the current object.
+ * @returns {Boolean} "true" if the object is equal.
+ * @example
+ * var doc = new CKEDITOR.dom.document( document );
+ * alert( doc.equals( CKEDITOR.document ) ); // "true"
+ * alert( doc == CKEDITOR.document ); // "false"
+ */
+ domObjectProto.equals = function( object )
+ {
+ return ( object && object.$ === this.$ );
+ };
+
+ /**
+ * Sets a data slot value for this object. These values are shared by all
+ * instances pointing to that same DOM object.
+ * @name CKEDITOR.dom.domObject.prototype.setCustomData
+ * @function
+ * @param {String} key A key used to identify the data slot.
+ * @param {Object} value The value to set to the data slot.
+ * @returns {CKEDITOR.dom.domObject} This DOM object instance.
+ * @see CKEDITOR.dom.domObject.prototype.getCustomData
+ * @example
+ * var element = new CKEDITOR.dom.element( 'span' );
+ * element.setCustomData( 'hasCustomData', true );
+ */
+ domObjectProto.setCustomData = function( key, value )
+ {
+ var expandoNumber = this.getUniqueId(),
+ dataSlot = customData[ expandoNumber ] || ( customData[ expandoNumber ] = {} );
+
+ dataSlot[ key ] = value;
+
+ return this;
+ };
+
+ /**
+ * Gets the value set to a data slot in this object.
+ * @name CKEDITOR.dom.domObject.prototype.getCustomData
+ * @function
+ * @param {String} key The key used to identify the data slot.
+ * @returns {Object} This value set to the data slot.
+ * @see CKEDITOR.dom.domObject.prototype.setCustomData
+ * @example
+ * var element = new CKEDITOR.dom.element( 'span' );
+ * alert( element.getCustomData( 'hasCustomData' ) ); // e.g. 'true'
+ */
+ domObjectProto.getCustomData = function( key )
+ {
+ var expandoNumber = this.$._cke_expando,
+ dataSlot = expandoNumber && customData[ expandoNumber ];
+
+ return dataSlot && dataSlot[ key ];
+ };
+
+ /**
+ * @name CKEDITOR.dom.domObject.prototype.removeCustomData
+ */
+ domObjectProto.removeCustomData = function( key )
+ {
+ var expandoNumber = this.$._cke_expando,
+ dataSlot = expandoNumber && customData[ expandoNumber ],
+ retval = dataSlot && dataSlot[ key ];
+
+ if ( typeof retval != 'undefined' )
+ delete dataSlot[ key ];
+
+ return retval || null;
+ };
+
+ /**
+ * Removes any data stored on this object.
+ * To avoid memory leaks we must assure that there are no
+ * references left after the object is no longer needed.
+ * @name CKEDITOR.dom.domObject.prototype.clearCustomData
+ * @function
+ */
+ domObjectProto.clearCustomData = function()
+ {
+ // Clear all event listeners
+ this.removeAllListeners();
+
+ var expandoNumber = this.$._cke_expando;
+ expandoNumber && delete customData[ expandoNumber ];
+ };
+
+ /**
+ * @name CKEDITOR.dom.domObject.prototype.getCustomData
+ */
+ domObjectProto.getUniqueId = function()
+ {
+ return this.$._cke_expando || ( this.$._cke_expando = CKEDITOR.tools.getNextNumber() );
+ };
+
+ // Implement CKEDITOR.event.
+ CKEDITOR.event.implementOn( domObjectProto );
+
+})( CKEDITOR.dom.domObject.prototype );
diff --git a/pool/shard010/JavaScript/0068648_extending_a_group.js b/pool/shard010/JavaScript/0068648_extending_a_group.js
new file mode 100644
index 0000000000000000000000000000000000000000..cd5fb8964be5e4971002c010ced34bbf2b9bd8ea
--- /dev/null
+++ b/pool/shard010/JavaScript/0068648_extending_a_group.js
@@ -0,0 +1,49 @@
+window.onload = function() {
+
+ // Here is a custom group
+ // It will automatically create 30 sprites of the given image when created.
+
+ MonsterGroup = function (game, image, action) {
+
+ Phaser.Group.call(this, game);
+
+ for (var i = 0; i < 30; i++)
+ {
+ var sprite = this.create(game.world.randomX, game.world.randomY, image);
+
+ if (action == 'bounce')
+ {
+ game.add.tween(sprite).to({ y: sprite.y - 100 }, 2000, Phaser.Easing.Elastic.Out, true, 0, 1000, true);
+ }
+ else if (action == 'slide')
+ {
+ game.add.tween(sprite).to({ x: sprite.x + 200 }, 4000, Phaser.Easing.Elastic.Out, true, 0, 1000, true);
+ }
+
+ }
+
+ };
+
+ MonsterGroup.prototype = Object.create(Phaser.Group.prototype);
+ MonsterGroup.prototype.constructor = MonsterGroup;
+
+ var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create });
+
+ var customGroup1;
+ var customGroup2;
+
+ function preload() {
+
+ game.load.image('ufo', 'assets/sprites/ufo.png');
+ game.load.image('baddie', 'assets/sprites/space-baddie.png');
+
+ }
+
+ function create() {
+
+ customGroup1 = new MonsterGroup(game, 'ufo', 'bounce');
+ customGroup2 = new MonsterGroup(game, 'baddie', 'slide');
+
+ }
+
+}();
diff --git a/pool/shard010/JavaScript/0068649_dom_parser.js b/pool/shard010/JavaScript/0068649_dom_parser.js
new file mode 100644
index 0000000000000000000000000000000000000000..108de35a3144ee94bac09ae34f879498ac138855
--- /dev/null
+++ b/pool/shard010/JavaScript/0068649_dom_parser.js
@@ -0,0 +1,47 @@
+/*
+ * DOMParser HTML extension
+ * 2012-02-02
+ *
+ * By Eli Grey, http://eligrey.com
+ * Public domain.
+ * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+ * https://developer.mozilla.org/en-US/docs/DOM/DOMParser?redirectlocale=en-US&redirectslug=DOMParser#DOMParser_HTML_extension_for_other_browsers
+ */
+
+/*! @source https://gist.github.com/1129031 */
+/*global document, DOMParser*/
+
+(function(DOMParser) {
+ "use strict";
+ var DOMParser_proto = DOMParser.prototype
+ , real_parseFromString = DOMParser_proto.parseFromString;
+
+ // Firefox/Opera/IE throw errors on unsupported types
+ try {
+ // WebKit returns null on unsupported types
+ if ((new DOMParser).parseFromString("", "text/html")) {
+ // text/html parsing is natively supported
+ return;
+ }
+ } catch (ex) {}
+
+ DOMParser_proto.parseFromString = function(markup, type) {
+ if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
+ var doc = document.implementation.createHTMLDocument("")
+ , doc_elt = doc.documentElement
+ , first_elt;
+
+ doc_elt.innerHTML = markup;
+ first_elt = doc_elt.firstElementChild;
+
+ if (doc_elt.childElementCount === 1
+ && first_elt.localName.toLowerCase() === "html") {
+ doc.replaceChild(first_elt, doc_elt);
+ }
+
+ return doc;
+ } else {
+ return real_parseFromString.apply(this, arguments);
+ }
+ };
+}(DOMParser));
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068651_header.js b/pool/shard010/JavaScript/0068651_header.js
new file mode 100644
index 0000000000000000000000000000000000000000..c72ffa3982fa7b53ce212c4dd9ad3160c4ebe397
--- /dev/null
+++ b/pool/shard010/JavaScript/0068651_header.js
@@ -0,0 +1,87 @@
+import React from 'react';
+import { func, string } from 'prop-types';
+import {
+ Platform,
+ StyleSheet,
+ Text,
+ TouchableOpacity,
+ View,
+} from 'react-native';
+
+import { iOSColors } from 'react-native-typography';
+import Ionicons from 'react-native-vector-icons/Ionicons';
+
+import noop from '../utils/helpers';
+
+const styles = StyleSheet.create({
+ container: {
+ flex: 1,
+ flexDirection: 'row',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ paddingTop: Platform.OS === 'ios' ? 50 : 20,
+ paddingHorizontal: 10,
+ backgroundColor: 'white',
+ },
+ titleText: {
+ fontSize: 24,
+ color: 'black',
+ },
+ descriptionText: {
+ marginTop: 6,
+ fontSize: 16,
+ color: 'black',
+ lineHeight: 16,
+ },
+ rightIcon: {
+ flex: 1,
+ alignItems: 'flex-end',
+ paddingRight: 5,
+ },
+});
+
+const Header = ({ title, description, iconName, onPress, backOnPress }) => (
+
+
+ {backOnPress && backOnPress !== noop && (
+
+ )}
+
+
+ {title && {title} }
+ {description && (
+ {description}
+ )}
+
+
+ {iconName && (
+
+
+
+ )}
+
+
+);
+
+Header.defaultProps = {
+ title: null,
+ description: null,
+ onPress: noop,
+ backOnPress: noop,
+ iconName: null,
+};
+
+Header.propTypes = {
+ title: string,
+ description: string,
+ onPress: func,
+ backOnPress: func,
+ iconName: string,
+};
+
+export default Header;
diff --git a/pool/shard010/JavaScript/0068657_game_inventory.js b/pool/shard010/JavaScript/0068657_game_inventory.js
new file mode 100644
index 0000000000000000000000000000000000000000..3848a953a5f32aac8f996bc0fb7d4a1d1c3acf77
--- /dev/null
+++ b/pool/shard010/JavaScript/0068657_game_inventory.js
@@ -0,0 +1,114 @@
+var GameInventory =function(model){
+ this.model = model
+ this.items = []
+ this.space = 0
+
+ this.UI_SCALE = 2
+ this.UI_ICON_SIZE = this.UI_SCALE * ICON_SIZE
+ this.UI_PADDING = 1
+
+ // this.dirt = null
+ // this.stone = null
+ // this.iron = null
+
+ this,full = null
+
+ this.init = function()
+ {
+ this.space = 25
+ this.full = false
+ }
+
+ this.add = function(gameItem)
+ {
+ var added = false
+ for(var i=0;i item)
+ {
+ if(this.items[item])
+ {
+ view.renderIcon(this.items[item].icon, this.UI_SCALE)
+ } else
+ {
+ view.renderIcon(0, this.UI_SCALE);
+ }
+ }
+ }
+
+ this.render_push = function(view)
+ {
+
+ }
+ this.render_pop = function(view)
+ {
+ }
+
+ this.init();
+}
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068659_filters.js b/pool/shard010/JavaScript/0068659_filters.js
new file mode 100644
index 0000000000000000000000000000000000000000..397b4ee92f7c6f55451be3628f5e65c4eaf5dc1b
--- /dev/null
+++ b/pool/shard010/JavaScript/0068659_filters.js
@@ -0,0 +1,176 @@
+'use strict';
+
+/* Filters */
+
+var loFilters = angular.module('loApp.filters', []);
+
+loFilters.filter('interpolate', ['version', function(version) {
+ return function(text) {
+ return String(text).replace(/\%VERSION\%/mg, version);
+ };
+}]);
+
+// based on https://github.com/sparkalow/angular-truncate/blob/master/src/truncate.js
+
+loFilters.filter('characters', function () {
+ return function (input, chars, breakOnWord) {
+ if (isNaN(chars)) { return input; }
+ if (chars <= 0) { return ''; }
+ if (input && input.length > chars) {
+ input = input.substring(0, chars);
+
+ if (!breakOnWord) {
+ var lastspace = input.lastIndexOf(' ');
+ //get last space
+ if (lastspace !== -1) {
+ input = input.substr(0, lastspace);
+ }
+ }
+ else {
+ while(input.charAt(input.length-1) === ' '){
+ input = input.substr(0, input.length -1);
+ }
+ }
+ return input + '...';
+ }
+ return input;
+ };
+});
+
+loFilters.filter('words', function () {
+ return function (input, words) {
+ if (isNaN(words)) { return input; }
+ if (words <= 0) { return ''; }
+ if (input) {
+ var inputWords = input.split(/\s+/);
+ if (inputWords.length > words) {
+ input = inputWords.slice(0, words).join(' ') + '...';
+ }
+ }
+ return input;
+ };
+});
+
+loFilters.filter('dataContains', function () {
+ return function (input, query) {
+ var output = [];
+
+ angular.forEach(input, function (line) {
+ angular.forEach(line, function (cell) {
+ if (cell.indexOf && cell.indexOf(query) > -1) {
+ if (output.indexOf(line) === -1) {
+ output.push(line);
+ }
+ }
+ });
+ });
+
+ return output;
+ };
+});
+
+loFilters.filter('condition', function () {
+ return function (input, conditions) {
+ var output = [];
+
+ angular.forEach(input, function(item) {
+ var pass = true;
+
+ angular.forEach(conditions, function(condition){
+ var cell = item[condition.column];
+
+ if (condition.type === 'E' && cell !== condition.text){
+ pass = false;
+ }
+
+ if (condition.type !== 'E' && cell === condition.text){
+ pass = false;
+ }
+ });
+
+ if (pass){
+ output.push(item);
+ }
+ });
+
+ return output;
+ };
+});
+
+loFilters.filter('clientname', function() {
+ return function (clientName, appName) {
+ return clientName ? clientName.replace(new RegExp('^liveoak.client.' + appName + '.'), '') : clientName;
+ };
+});
+
+loFilters.filter('ures', function () {
+ return function(item) {
+ if (item) {
+ var uris = [];
+ for (var i = 0; i < item.length; i++) {
+ for (var j = 0; j < item[i].rules.length; j++) {
+ if(item[i].rules[j].uriPattern !== '*') {
+ uris.push(item[i].rules[j].uriPattern.replace(/\/\*$/,''));
+ }
+ }
+ }
+ return uris;
+ }
+ };
+});
+
+
+/* taken from http://angular-ui.github.io/ui-utils/dist/ui-utils.js */
+loFilters.filter('unique', ['$parse', function ($parse) {
+
+ return function (items, filterOn) {
+
+ if (filterOn === false) {
+ return items;
+ }
+
+ if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
+ var newItems = [],
+ get = angular.isString(filterOn) ? $parse(filterOn) : function (item) { return item; };
+
+ var extractValueToCompare = function (item) {
+ return angular.isObject(item) ? get(item) : item;
+ };
+
+ angular.forEach(items, function (item) {
+ var isDuplicate = false;
+
+ for (var i = 0; i < newItems.length; i++) {
+ if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
+ isDuplicate = true;
+ break;
+ }
+ }
+ if (!isDuplicate) {
+ newItems.push(item);
+ }
+
+ });
+ items = newItems;
+ }
+ return items;
+ };
+}]);
+
+loFilters.filter('orderObjectBy', function() {
+ return function(items, field, reverse) {
+ var filtered = [];
+ angular.forEach(items, function(item) {
+ if (item.hasOwnProperty(field) || (item[0] && item[0].hasOwnProperty(field))) {
+ filtered.push(item);
+ }
+ });
+ filtered.sort(function (a, b) {
+ return (a[field] > b[field] ? 1 : -1);
+ });
+ if(reverse) {
+ filtered.reverse();
+ }
+ return filtered;
+ };
+});
diff --git a/pool/shard010/JavaScript/0068660_GeneratePropsJavaInterface-test.js b/pool/shard010/JavaScript/0068660_GeneratePropsJavaInterface-test.js
new file mode 100644
index 0000000000000000000000000000000000000000..cc1eadab41ab78d319f60f79d78cd9461e368d3c
--- /dev/null
+++ b/pool/shard010/JavaScript/0068660_GeneratePropsJavaInterface-test.js
@@ -0,0 +1,27 @@
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @emails oncall+react_native
+ * @flow strict-local
+ * @format
+ */
+
+'use strict';
+
+const fixtures = require('../__test_fixtures__/fixtures.js');
+const generator = require('../GeneratePropsJavaInterface.js');
+
+describe('GeneratePropsJavaInterface', () => {
+ Object.keys(fixtures)
+ .sort()
+ .forEach(fixtureName => {
+ const fixture = fixtures[fixtureName];
+
+ it(`can generate fixture ${fixtureName}`, () => {
+ expect(generator.generate(fixtureName, fixture)).toMatchSnapshot();
+ });
+ });
+});
diff --git a/pool/shard010/JavaScript/0068661_mesh.js b/pool/shard010/JavaScript/0068661_mesh.js
new file mode 100644
index 0000000000000000000000000000000000000000..601b3f3e8a076b3393ba11545ac489da773ac521
--- /dev/null
+++ b/pool/shard010/JavaScript/0068661_mesh.js
@@ -0,0 +1,201 @@
+/*global window*/
+(function (module) {
+ /**
+ * Used to make an object observable
+ * @param object subject Contains the object that is to be observed
+ * @return object Containing the injected observable functionality.
+ */
+ module.exports = function ($, module) {
+ var base = {};
+
+ /**
+ * Used to parse the data into a specific format.
+ * @param string name Contains the levels name
+ * @param object level Contains the object collection
+ * @param array data Contains the level data
+ * @return object Containing a node-collection
+ */
+ base.parse = function (name, level, data) {
+ var
+ // Acts as a temporary cache for found vertices, this allows corner
+ // vertices that are common to multiple faces to share a common
+ // object which reduces memory usage, and makes comparison easier.
+ vertices = {},
+ uniqueVertices = 0,
+ i, // Used for loop control
+ ii, // Used for loop delimiting
+ vs, // Will contains all vertices within this poly.
+ j, // Used for loop control
+ jj, // Used for loop delimiting
+ vert,
+ key;
+
+ for (i = 0, ii = data.length; i < ii; i += 1) {
+ // The goal with vs is to store vectors, and was we want three
+ // vectors we must loop over the sub-record and store found
+ // vectors in this list.
+ vs = [];
+
+ for (j = 0, jj = data[i].length; j < jj; j += 1) {
+ vert = data[i][j];
+
+ // The goal here is to create the minimum number of vector2
+ // objects as possible, so if multiple polys all share a
+ // commonly position vertice then in memory there should
+ // only be one instance of that point.
+ // So this code creats a crude key, and maintains a list
+ // of currently discoverted nodes, if a node is refound
+ // then a new vector2 isn't created.
+ key = vert.x + '-' + vert.y;
+ if (vertices[key] === undefined) {
+ vertices[key] = $('thorny level node').factory(
+ $('thorny math vector2').factory(
+ vert.x + level.getX(),
+ vert.y + level.getY()
+ ),
+ name,
+ 'vector2',
+ uniqueVertices
+ );
+ uniqueVertices += 1;
+ }
+
+ // Store the vertex in the list.
+ vs.push(vertices[key]);
+ }
+
+ // Makesure we have the correct number of vertices.
+ if (vs.length !== 3) {
+ throw new Error("Thorny.level: Invalid level data, all poly2's must contain 3 vertices.");
+ }
+
+ // Store the poly in the collection.
+ level.push(
+ $('thorny math poly2').factory(vs[0], vs[1], vs[2])
+ );
+ }
+
+ return level;
+ };
+
+ /**
+ * Used to network nodes together
+ * @param object level Contains the object collection
+ * @return object Containing a node-collection
+ */
+ base.network = function (level) {
+ var
+ parent, // Will contain a parent node
+ parents = level.iterator(), // Contains all parent nodes
+ child, // Will contain a child node
+ children = level.iterator(),// Contains all chilren nodes
+ edge; // Will contain the
+ // neighbouring edge.
+
+ // We're going to iterate over this collection twice so we
+ // can pair each of the polys together.
+ while ((parent = parents.step())) {
+ while ((child = children.step())) {
+ // See if the parent shares an edge with the child
+ if ((edge = parent.node.sharesEdge(child.node))) {
+ // If it does then they are neighbours
+ parent.node.addNeighbour(child.node, {
+ distanceTo: parent.node.getMidpoint()
+ .distance(child.node.getMidpoint()),
+ edgeWidth: edge[0].distance(edge[1])
+ });
+ }
+ }
+ children.rewind();
+ }
+ return level;
+ };
+
+ /**
+ * Used to search for a specific node within this level
+ * @param object entity Contains the entity that owns the map
+ * @param int x Contains the x coordinate
+ * @param int y Contains the y coordinate
+ * @param boolean findClosest Used to find the cloest node
+ * @return object Containing a node within this level
+ */
+ base.xySearch = function (entity, x, y, findClosest) {
+ var
+ point,
+ nodes,
+ node,
+ goalGoal = false,
+ bestNode = false,
+ distance = false,
+ distanceToBestNode = false;
+
+ if (findClosest === undefined) {
+ findClosest = false;
+ }
+
+ // Convert the xy coords into a vector
+ point = $('thorny math vector2').factory(x, y);
+
+ entity
+ .getComponent('load-level')
+ .each(function (level) {
+ if (goalGoal !== false) {
+ return;
+ }
+
+ // Check to see if the clicked xy is within
+ // the bounds of this level, but only on direct
+ // search mode, if we want to find the closest
+ // node then we need to ask every poly within
+ // every level in the collcetion.
+ if (! findClosest &&
+ (
+ x < level.data.getX() || x > (level.data.getX() + level.data.getWidth()) ||
+ y < level.data.getY() || y > (level.data.getY() + level.data.getHeight())
+ )
+ ) {
+ return;
+ }
+
+ // Loop over each node within this level
+ nodes = level.data.iterator();
+ while ((node = nodes.step().node)) {
+ if (node.isVector2Internal(point)) {
+ goalGoal = node;
+ return;
+ }
+
+ // If we want to find the closest match
+ if (findClosest) {
+ distance = point.distance(node);
+
+ // See if the distance is better than
+ // the current best.
+ if (
+ distanceToBestNode === false ||
+ distance < distanceToBestNode
+ ) {
+ bestNode = node;
+ distanceToBestNode = distance;
+ }
+ }
+ }
+ });
+
+ // If the goal node was found, return it
+ if (goalGoal) {
+ return goalGoal;
+ }
+
+ // If we're meant to find the closest node return it
+ if (findClosest) {
+ return bestNode;
+ }
+
+ // Otherwise return false.
+ return false;
+ };
+
+ return base;
+ };
+}((typeof window === 'undefined') ? module : window.thorny_path('./thorny/common/level/2d/mesh')));
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068668_checkRelayQueryData.js b/pool/shard010/JavaScript/0068668_checkRelayQueryData.js
new file mode 100644
index 0000000000000000000000000000000000000000..a564ee4f32c2e4a3871d29caf65cdedb1fc5648c
--- /dev/null
+++ b/pool/shard010/JavaScript/0068668_checkRelayQueryData.js
@@ -0,0 +1,224 @@
+/**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule checkRelayQueryData
+ *
+ * @typechecks
+ */
+
+'use strict';
+
+var _inherits = require('babel-runtime/helpers/inherits')['default'];
+
+var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
+
+var RelayConnectionInterface = require('./RelayConnectionInterface');
+
+var RelayProfiler = require('./RelayProfiler');
+
+var RelayQueryVisitor = require('./RelayQueryVisitor');
+var RelayRecordState = require('./RelayRecordState');
+
+var forEachRootCallArg = require('./forEachRootCallArg');
+
+var EDGES = RelayConnectionInterface.EDGES;
+var PAGE_INFO = RelayConnectionInterface.PAGE_INFO;
+
+/**
+ * @internal
+ *
+ * Traverses a query and data in the record store to determine whether we have
+ * enough data to satisfy the query.
+ */
+function checkRelayQueryData(store, query) {
+
+ var checker = new RelayQueryChecker(store);
+
+ var state = {
+ dataID: undefined,
+ rangeInfo: undefined,
+ result: true
+ };
+
+ checker.visit(query, state);
+ return state.result;
+}
+
+var RelayQueryChecker = (function (_RelayQueryVisitor) {
+ _inherits(RelayQueryChecker, _RelayQueryVisitor);
+
+ function RelayQueryChecker(store) {
+ _classCallCheck(this, RelayQueryChecker);
+
+ _RelayQueryVisitor.call(this);
+ this._store = store;
+ }
+
+ /**
+ * Skip visiting children if result is already false.
+ */
+
+ RelayQueryChecker.prototype.traverse = function traverse(node, state) {
+ var children = node.getChildren();
+ for (var ii = 0; ii < children.length; ii++) {
+ if (!state.result) {
+ return;
+ }
+ this.visit(children[ii], state);
+ }
+ };
+
+ RelayQueryChecker.prototype.visitRoot = function visitRoot(root, state) {
+ var _this = this;
+
+ var nextState;
+
+ forEachRootCallArg(root, function (rootCallArg, rootCallName) {
+ var dataID = _this._store.getRootCallID(rootCallName, rootCallArg);
+ if (dataID == null) {
+ state.result = false;
+ } else {
+ nextState = {
+ dataID: dataID,
+ rangeInfo: undefined,
+ result: true
+ };
+ _this.traverse(root, nextState);
+ state.result = state.result && nextState.result;
+ }
+ });
+ };
+
+ RelayQueryChecker.prototype.visitField = function visitField(field, state) {
+ var dataID = state.dataID;
+ var recordState = dataID && this._store.getRecordState(dataID);
+ if (recordState === RelayRecordState.UNKNOWN) {
+ state.result = false;
+ return;
+ } else if (recordState === RelayRecordState.NONEXISTENT) {
+ return;
+ }
+ var rangeInfo = state.rangeInfo;
+ if (rangeInfo && field.getSchemaName() === EDGES) {
+ this._checkEdges(field, state);
+ } else if (rangeInfo && field.getSchemaName() === PAGE_INFO) {
+ this._checkPageInfo(field, state);
+ } else if (field.isScalar()) {
+ this._checkScalar(field, state);
+ } else if (field.isPlural()) {
+ this._checkPlural(field, state);
+ } else if (field.isConnection()) {
+ this._checkConnection(field, state);
+ } else {
+ this._checkLinkedField(field, state);
+ }
+ };
+
+ RelayQueryChecker.prototype._checkScalar = function _checkScalar(field, state) {
+ var fieldData = state.dataID && this._store.getField(state.dataID, field.getStorageKey());
+ if (fieldData === undefined) {
+ state.result = false;
+ }
+ };
+
+ RelayQueryChecker.prototype._checkPlural = function _checkPlural(field, state) {
+ var dataIDs = state.dataID && this._store.getLinkedRecordIDs(state.dataID, field.getStorageKey());
+ if (dataIDs === undefined) {
+ state.result = false;
+ return;
+ }
+ if (dataIDs) {
+ for (var ii = 0; ii < dataIDs.length; ii++) {
+ if (!state.result) {
+ break;
+ }
+ var nextState = {
+ dataID: dataIDs[ii],
+ rangeInfo: undefined,
+ result: true
+ };
+ this.traverse(field, nextState);
+ state.result = nextState.result;
+ }
+ }
+ };
+
+ RelayQueryChecker.prototype._checkConnection = function _checkConnection(field, state) {
+ var calls = field.getCallsWithValues();
+ var dataID = state.dataID && this._store.getLinkedRecordID(state.dataID, field.getStorageKey());
+ if (dataID === undefined) {
+ state.result = false;
+ return;
+ }
+ var nextState = {
+ dataID: dataID,
+ rangeInfo: null, // Flow rejects `undefined` here
+ result: true
+ };
+ var metadata = this._store.getRangeMetadata(dataID, calls);
+ if (metadata) {
+ nextState.rangeInfo = metadata;
+ }
+ this.traverse(field, nextState);
+ state.result = state.result && nextState.result;
+ };
+
+ RelayQueryChecker.prototype._checkEdges = function _checkEdges(field, state) {
+ var rangeInfo = state.rangeInfo;
+ if (!rangeInfo) {
+ state.result = false;
+ return;
+ }
+ if (rangeInfo.diffCalls.length) {
+ state.result = false;
+ return;
+ }
+ var edges = rangeInfo.requestedEdges;
+ for (var ii = 0; ii < edges.length; ii++) {
+ if (!state.result) {
+ break;
+ }
+ var nextState = {
+ dataID: edges[ii].edgeID,
+ rangeInfo: undefined,
+ result: true
+ };
+ this.traverse(field, nextState);
+ state.result = nextState.result;
+ }
+ };
+
+ RelayQueryChecker.prototype._checkPageInfo = function _checkPageInfo(field, state) {
+ var rangeInfo = state.rangeInfo;
+ if (!rangeInfo || !rangeInfo.pageInfo) {
+ state.result = false;
+ return;
+ }
+ };
+
+ RelayQueryChecker.prototype._checkLinkedField = function _checkLinkedField(field, state) {
+ var dataID = state.dataID && this._store.getLinkedRecordID(state.dataID, field.getStorageKey());
+ if (dataID === undefined) {
+ state.result = false;
+ return;
+ }
+ if (dataID) {
+ var nextState = {
+ dataID: dataID,
+ rangeInfo: undefined,
+ result: true
+ };
+ this.traverse(field, nextState);
+ state.result = state.result && nextState.result;
+ }
+ };
+
+ return RelayQueryChecker;
+})(RelayQueryVisitor);
+
+module.exports = RelayProfiler.instrument('checkRelayQueryData', checkRelayQueryData);
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068670_requireInterface.js b/pool/shard010/JavaScript/0068670_requireInterface.js
new file mode 100644
index 0000000000000000000000000000000000000000..85b87efed9b64a631a5e8f392ef85e0514988f4d
--- /dev/null
+++ b/pool/shard010/JavaScript/0068670_requireInterface.js
@@ -0,0 +1,59 @@
+getJasmineRequireObj().interface = function(jasmine, env) {
+ var jasmineInterface = {
+ describe: function(description, specDefinitions) {
+ return env.describe(description, specDefinitions);
+ },
+
+ xdescribe: function(description, specDefinitions) {
+ return env.xdescribe(description, specDefinitions);
+ },
+
+ it: function(desc, func) {
+ return env.it(desc, func);
+ },
+
+ xit: function(desc, func) {
+ return env.xit(desc, func);
+ },
+
+ beforeEach: function(beforeEachFunction) {
+ return env.beforeEach(beforeEachFunction);
+ },
+
+ afterEach: function(afterEachFunction) {
+ return env.afterEach(afterEachFunction);
+ },
+
+ expect: function(actual) {
+ return env.expect(actual);
+ },
+
+ pending: function() {
+ return env.pending();
+ },
+
+ spyOn: function(obj, methodName) {
+ return env.spyOn(obj, methodName);
+ },
+
+ jsApiReporter: new jasmine.JsApiReporter({
+ timer: new jasmine.Timer()
+ }),
+
+ jasmine: jasmine
+ };
+
+ jasmine.addCustomEqualityTester = function(tester) {
+ env.addCustomEqualityTester(tester);
+ };
+
+ jasmine.addMatchers = function(matchers) {
+ return env.addMatchers(matchers);
+ };
+
+ jasmine.clock = function() {
+ return env.clock;
+ };
+
+ return jasmineInterface;
+};
diff --git a/pool/shard010/JavaScript/0068672_VectorizerStrategy.js b/pool/shard010/JavaScript/0068672_VectorizerStrategy.js
new file mode 100644
index 0000000000000000000000000000000000000000..79469cc9c3e3d1d2c845325d23326d6f3d707a7f
--- /dev/null
+++ b/pool/shard010/JavaScript/0068672_VectorizerStrategy.js
@@ -0,0 +1,124 @@
+/*
+Class for outline and threshold class
+
+Florian Wokurka (2013)
+https://github.com/notiontaxi
+*/
+
+"use strict"
+
+define(['text!templates/task-vectorizer.html', 'js/strategies/ImageProcessingMenubarStrategy'], function(contentTemplate, ImageProcessingMenubarStrategy) {
+
+var VectorizerStrategy, _ref, module,
+
+
+ module = function() {}
+ VectorizerStrategy = (function(_super){
+ __extends(VectorizerStrategy, ImageProcessingMenubarStrategy);
+// --------------------------------------
+
+ VectorizerStrategy.NAME = 'vectorizer'
+ VectorizerStrategy.LABEL = 'Vectorizer'
+
+ function VectorizerStrategy(canvases, imageProcessor){
+ this.name = VectorizerStrategy.NAME
+ VectorizerStrategy.__super__.constructor(canvases, imageProcessor)
+ // render templates
+
+ $(".controls-wrapper").append($(contentTemplate))
+ this.init()
+ this.filled = true
+ }
+
+ VectorizerStrategy.prototype.appendToMenuBar = function(){
+ this.appendToLGMenuBar('Vectorizer', 'action-menu-vectorizer', 'image-actions-list')
+ this.appendToSDMenuBar('Vectorizer', 'action-menu-vectorizer', 'image-actions-list-sd')
+ }
+
+
+ VectorizerStrategy.prototype.initializeTools = function(){
+
+ // Automatic threshold button
+ $("#action-compute-paths").click(
+ function(event, ui){
+ var result = this.imageProcessor.processPathFinding(this.canvasOrigin.getImageData(), this.canvasOrigin.getImageWidth())
+ this.canvasStage.paths = result.paths
+ this.canvasStage.pathType = 'none'
+ $("#path-count").html(result.message)
+ }.bind(this)
+ )
+ $("#action-show-full-paths").click(
+ function(event, ui){
+ this.canvasStage.pathType = 'full'
+ this.canvasStage.draw()
+ }.bind(this)
+ )
+ $("#action-show-straight-paths").click(
+ function(event, ui){
+ this.canvasStage.pathType = 'straight'
+ this.canvasStage.draw()
+ }.bind(this)
+ )
+ $("#action-show-allowed-paths").click(
+ function(event, ui){
+ this.canvasStage.pathType = 'allowed'
+ this.canvasStage.draw()
+ }.bind(this)
+ )
+ $("#action-hide-paths").click(
+ function(event, ui){
+ this.canvasStage.pathType = 'none'
+ this.canvasStage.draw()
+ }.bind(this)
+ )
+ $("#action-toggle-filled").click(
+ function(event, ui){
+ this.filled = !this.filled
+ this.canvasStage.filling = this.filled
+ this.canvasStage.draw()
+ }.bind(this)
+ )
+
+ $( "#alpha-limit-slider" ).slider(
+ {
+ range: "min",
+ value: 0.55,
+ min: 0.1,
+ max: 2.0,
+ step: 0.01,
+ slide: function( event, ui ) {
+ $( "#alpha-limit-slider-output" ).html(ui.value)
+ this.canvasStage.alpha = ui.value
+ this.canvasStage.draw()
+
+ }.bind(this)
+ }
+ )
+
+ $( "#curve-limit-slider" ).slider(
+ {
+ range: "min",
+ value: 1.0,
+ min: 0.1,
+ max: 1.4,
+ step: 0.01,
+ slide: function( event, ui ) {
+ $( "#curve-limit-slider-output" ).html(ui.value)
+ this.canvasStage.curveLimit = ui.value
+ this.canvasStage.draw()
+ }.bind(this)
+ }
+ )
+
+ }
+
+ VectorizerStrategy.prototype.cancel = function(event, ui){
+
+ }
+
+
+// --------------------------------------
+ return VectorizerStrategy
+ })()
+ return module.exports = VectorizerStrategy
+})
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068673_redoc.e2e.js b/pool/shard010/JavaScript/0068673_redoc.e2e.js
new file mode 100644
index 0000000000000000000000000000000000000000..b9ef55de0eb68b1b8e8367fd83d87208b3bb8517
--- /dev/null
+++ b/pool/shard010/JavaScript/0068673_redoc.e2e.js
@@ -0,0 +1,138 @@
+'use strict';
+const verifyNoBrowserErrors = require('./helpers').verifyNoBrowserErrors;
+const scrollToEl = require('./helpers').scrollToEl;
+const fixFFTest = require('./helpers').fixFFTest;
+const eachNth = require('./helpers').eachNth;
+const getInnerHtml = require('./helpers').getInnerHtml;
+
+const URL = 'index.html';
+
+function waitForInit() {
+ const EC = protractor.ExpectedConditions;
+ const $apiInfo = $('api-info');
+ const $errorMessage = $('.redoc-error');
+ browser.wait(EC.or(EC.visibilityOf($apiInfo), EC.visibilityOf($errorMessage)), 60000);
+}
+
+function basicTests(swaggerUrl, title) {
+ describe(`Basic suite for ${title}`, () => {
+ let specUrl = URL;
+ if (swaggerUrl) {
+ specUrl += `?url=${encodeURIComponent(swaggerUrl)}`;
+ }
+
+ beforeEach(done => {
+ browser.get(specUrl);
+ waitForInit();
+ fixFFTest(done);
+ });
+
+ afterEach(() => {
+ verifyNoBrowserErrors();
+ });
+
+ it('should init redoc without errors', done => {
+ const $redoc = $('redoc');
+ expect($redoc.isPresent()).toBe(true);
+ setTimeout(() => {
+ const $operations = $$('operation');
+ expect($operations.count()).toBeGreaterThan(0);
+ done();
+ });
+ });
+ });
+}
+
+basicTests(null, 'Extended Petstore');
+
+describe('Scroll sync', () => {
+ const specUrl = URL;
+
+ beforeEach(done => {
+ browser.get(specUrl);
+ waitForInit();
+ fixFFTest(done);
+ });
+
+ it('should update active menu entries on page scroll forwards', () => {
+ scrollToEl('[section="tag/store"]').then(() => {
+ expect(getInnerHtml('.menu-item.menu-item-depth-1.active > .menu-item-header')).toContain(
+ 'store',
+ );
+ expect(getInnerHtml('.selected-tag')).toContain('store');
+ });
+ });
+
+ it('should update active menu entries on page scroll backwards', () => {
+ scrollToEl('[operation-id="getPetById"]').then(() => {
+ expect(getInnerHtml('.menu-item.menu-item-depth-1.active .menu-item-header')).toContain(
+ 'pet',
+ );
+ expect(getInnerHtml('.selected-tag')).toContain('pet');
+ expect(getInnerHtml('.menu-item.menu-item-depth-2.active .menu-item-header')).toContain(
+ 'Find pet by ID',
+ );
+ expect(getInnerHtml('.selected-endpoint')).toContain('Find pet by ID');
+ });
+ });
+});
+
+describe('Language tabs sync', () => {
+ const specUrl = URL;
+
+ beforeEach(done => {
+ browser.get(specUrl);
+ waitForInit();
+ fixFFTest(done);
+ });
+
+ // skip as it fails for no reason on IE on sauce-labs
+ // TODO: fixme
+ xit('should sync language tabs', () => {
+ const $item = $$('[operation-id="addPet"] tabs > ul > li').last();
+ // check if correct item
+ expect($item.getText()).toContain('PHP');
+ const EC = protractor.ExpectedConditions;
+ browser.wait(EC.elementToBeClickable($item), 5000);
+ $item.click().then(() => {
+ expect($('[operation-id="updatePet"] li.active').getText()).toContain('PHP');
+ });
+ });
+});
+
+if (process.env.JOB === 'e2e-guru') {
+ describe('APIs.guru specs test', () => {
+ // global.apisGuruList was loaded in onPrepare method of protractor config
+ let apisGuruList = global.apisGuruList;
+
+ // Remove certain APIs that are known to cause problems
+ delete apisGuruList['motaword.com']; // invalid (see https://github.com/BigstickCarpet/swagger-parser/issues/26)
+ delete apisGuruList['learnifier.com']; // allof object and no type
+ delete apisGuruList['googleapis.com:mirror']; // bad urls in images
+ delete apisGuruList['googleapis.com:discovery']; // non-string references
+ delete apisGuruList['clarify.io']; // non-string references
+ //delete apisGuruList['pushpay.com']; // https://github.com/Redocly/redoc/issues/30
+ delete apisGuruList['bbci.co.uk']; // too big
+ delete apisGuruList['bbc.com']; // too big
+ delete apisGuruList['osisoft.com']; // too big
+ delete apisGuruList['magento.com']; // too big
+
+ // run quick version of e2e test on all builds except releases
+ if (process.env.TRAVIS && !process.env.TRAVIS_TAG) {
+ console.log('Running on a short APIs guru list');
+ apisGuruList = eachNth(apisGuruList, 20);
+ } else {
+ console.log('Running on full APIs guru list');
+ }
+
+ for (const apiName of Object.keys(apisGuruList)) {
+ const apiInfo = apisGuruList[apiName].versions[apisGuruList[apiName].preferred];
+ let url = apiInfo.swaggerUrl;
+
+ // temporary hack due to this issue: https://github.com/substack/https-browserify/issues/6
+ url = url.replace('https://', 'http://');
+ url = url.replace('apis-guru.github.io/', 'apis-guru.github.io:80/');
+ basicTests(url, `${apiName}:${apiInfo.info.version}\n${url}`);
+ }
+ });
+}
diff --git a/pool/shard010/JavaScript/0068677_comm.js b/pool/shard010/JavaScript/0068677_comm.js
new file mode 100644
index 0000000000000000000000000000000000000000..9c4e207bf1f9dae8210e7439d849c9564929c8bc
--- /dev/null
+++ b/pool/shard010/JavaScript/0068677_comm.js
@@ -0,0 +1,91 @@
+var AD = require('AppDev');
+var $ = require('jquery');
+
+module.exports = $.extend(AD.Comm, {
+ pingServer: function(server) {
+ return AD.Comm.HTTP.get({
+ url: server+'/nsserver/ping'
+ }).then(function(response) {
+ // Tweak the API configuration response to make it more useful
+ var apiConfig = response;
+ apiConfig.server = server;
+ // Prepend the server url to each of the uri paths so that they will be fully qualified URLs
+ $.each(apiConfig.uris, function(key, uri) {
+ apiConfig.uris[key] = server + uri;
+ });
+ });
+ },
+
+ // Make an authentication request to the specified server using the provided username and password credentials
+ // Return a deferred object that will be resolved if the credentials are valid and rejected if they are invalid
+ authenticate: function(apiConfig, username, password) {
+ var authenticateDfd = $.Deferred();
+
+ // Get the CAS service ticket
+ var casConfig = apiConfig.CAS;
+ var cas = new AD.Comm.CAS({ casBaseUrl: casConfig.uri });
+ cas.getServiceTicket(username, password, apiConfig.server + '/' + casConfig.authURI).done(function(serviceTicket) {
+ console.log('CAS service ticket: ' + serviceTicket);
+ AD.Comm.appdevRequest({
+ method: 'POST',
+ url: apiConfig.uris.auth,
+ query: {
+ ticket: serviceTicket
+ },
+ params: {
+ username: username,
+ password: password
+ }
+ }).done(authenticateDfd.resolve).fail(authenticateDfd.reject).fail(function(response) {
+ console.log('Authentication failed:');
+ console.log(response);
+ });
+ }).fail(authenticateDfd.reject).fail(function(response) {
+ console.log('getServiceTicket failed:');
+ console.log(response);
+ });
+
+ return authenticateDfd.promise();
+ },
+
+ // Send the provided transactions to the server and return a deferred
+ // that will resolve to the transaction log received from the server
+ syncWithServer: function(apiConfig, transactions, username, password) {
+ var syncDfd = $.Deferred();
+ AD.Comm.appdevRequest({
+ method: 'POST',
+ url: apiConfig.uris.sync,
+ params: {
+ username: username,
+ password: password,
+ lastSyncTimestamp: (apiConfig.server === AD.PropertyStore.get('lastSyncServer')) ? AD.PropertyStore.get('lastSyncTimestamp') : 0,
+ appVersion: AD.Defaults.version,
+ transactionLog: transactions
+ },
+ timeout: 300000 // five minutes
+ }).done(function(response) {
+ console.log("syncWithServer() >> response (done) = ");
+ console.log(response);
+ AD.PropertyStore.set('lastSyncServer', apiConfig.server);
+ AD.PropertyStore.set('lastSyncTimestamp', response.data.lastSyncTimestamp);
+ syncDfd.resolve(response.data.transactionLog);
+ }).fail(syncDfd.reject);
+ return syncDfd.promise();
+ },
+
+ // Make a request to an AppDev resource
+ appdevRequest: function(options) {
+ var requestDfd = $.Deferred();
+ AD.Comm.HTTP.request(options).done(function(response) {
+ if (response.status === 'success') {
+ // The request succeeded
+ requestDfd.resolve(response);
+ }
+ else {
+ // The request failed
+ requestDfd.reject(response);
+ }
+ }).fail(requestDfd.reject);
+ return requestDfd.promise();
+ }
+});
diff --git a/pool/shard010/JavaScript/0068678_app.run.js b/pool/shard010/JavaScript/0068678_app.run.js
new file mode 100644
index 0000000000000000000000000000000000000000..0a60a86041c27524ebb825082feff872c2949e1f
--- /dev/null
+++ b/pool/shard010/JavaScript/0068678_app.run.js
@@ -0,0 +1,26 @@
+/*************************
+ Application Run
+ **************************/
+(function () {
+ 'use strict';
+ angular
+ .module('JetThunder2')
+ .run(JetThunder2Run);
+
+ JetThunder2Run.$inject = ["$rootScope", "$window"];
+ function JetThunder2Run($rootScope, $window) {
+ $rootScope.connection = navigator.onLine;
+ $window.addEventListener("offline", function() {
+ $rootScope.$apply(function() {
+ $rootScope.connection = false;
+ });
+ }, false);
+
+ $window.addEventListener("online", function() {
+ $rootScope.$apply(function() {
+ $rootScope.connection = true;
+ });
+ }, false);
+ }
+})();
+
diff --git a/pool/shard010/JavaScript/0068682_scripts.js b/pool/shard010/JavaScript/0068682_scripts.js
new file mode 100644
index 0000000000000000000000000000000000000000..e33fb1b9a82846fd60057d71e9d9191ca9798261
--- /dev/null
+++ b/pool/shard010/JavaScript/0068682_scripts.js
@@ -0,0 +1,186 @@
+/* ******* Map Area Draw ******* */
+/* ******* @ Serhio Magpie ******* */
+
+/* serdidg@gmail.com */
+/* http://screensider.com */
+
+var Painter = new function(){
+ var that = this,
+ isCanvas = false,
+ nodes,
+ context,
+ points = [],
+ areas = [];
+
+ var checkCanvas = function(){
+ if(nodes['canvas'].getContext){
+ isCanvas = true;
+ nodes['canvas'].width = nodes['draw'].offsetWidth;
+ nodes['canvas'].height = nodes['draw'].offsetHeight;
+ context = nodes['canvas'].getContext('2d');
+ }else{
+ _.remove(nodes['canvas']);
+ }
+ };
+
+ var clearAllBtn = function(){
+ nodes['clear_all'] = nodes['buttons'].appendChild(_.node('input', {'type':'button', 'value':'Clear All'}));
+ nodes['clear_all'].onclick = clearAll;
+ };
+
+ var addBtn = function(){
+ nodes['add'] = nodes['buttons'].appendChild(_.node('input', {'type':'button', 'value':'Add Area'}));
+ nodes['add'].onclick = add;
+ };
+
+ var saveBtn = function(){
+ nodes['save'] = nodes['buttons'].appendChild(_.node('input', {'type':'button', 'value':'Save Area'}));
+ nodes['save'].onclick = save;
+ };
+
+ var clearAll = function(){
+ clear();
+ _.clearNode(nodes['info']);
+ points = [];
+ areas = [];
+ // Clear preview from points or canvas
+ if(isCanvas){
+ clearCanvas();
+ }else{
+ clearPoints();
+ }
+ };
+
+ var add = function(){
+ _.remove(nodes['add']);
+ _.addClass(nodes['preview'], 'draw');
+ _.addEvent(nodes['draw'], 'mousedown', addPoint);
+ // Render buttons
+ saveBtn();
+ };
+
+ var save = function(){
+ clear();
+ areas.push(_.clone(points));
+ points = [];
+ renderInfo();
+ };
+
+ var clear = function(){
+ _.remove(nodes['add']);
+ _.remove(nodes['save']);
+ _.removeClass(nodes['preview'], 'draw');
+ _.removeEvent(nodes['draw'], 'mousedown', addPoint);
+ addBtn();
+ }
+
+ var clearCanvas = function(){
+ context.clearRect(0, 0, nodes['canvas'].width, nodes['canvas'].height);
+ };
+
+ var clearPoints = function(){
+ _.clearNode(nodes['points']);
+ };
+
+ var addPoint = function(e){
+ var e = _.getEvent(e),
+ offset = _.getOffset(nodes['draw']),
+ x = e.clientX + _.getDocScrollLeft() - offset[0],
+ y = e.clientY + _.getDocScrollTop() - offset[1];
+ // Push point to area array
+ points.push({'x' : x, 'y' : y});
+ // Draw point
+ if(isCanvas){
+ drawCanvasAll();
+ }else{
+ drawHtmlPoint(x,y);
+ }
+ // Prevent drag event
+ e.preventDefault && e.preventDefault();
+ return false;
+ };
+
+ var drawHtmlPoint = function(x, y){
+ var node = nodes['points'].appendChild(_.node('div', {'class':'point'}));
+ node.style.top = y-1+'px';
+ node.style.left = x-1+'px';
+ };
+
+ var drawCanvasPoints = function(o){
+ // Draw lines
+ context.fillStyle = 'rgba(0,172,239,0.2)';
+ context.lineWidth = 1;
+ context.strokeStyle = 'rgba(0,172,239,0.8)';
+ context.beginPath();
+ for(var i = 0, l = o.length; i < l; i++){
+ if(i == 0){
+ context.moveTo(o[i]['x'], o[i]['y']);
+ }else{
+ context.lineTo(o[i]['x'], o[i]['y']);
+ }
+ }
+ context.closePath();
+ context.fill();
+ context.stroke();
+ // Draw points
+ context.fillStyle = 'rgba(0,139,191,0.8)';
+ for(var i = 0, l = o.length; i < l; i++){
+ context.fillRect(o[i]['x']- 2, o[i]['y']- 2, 4, 4);
+ }
+ };
+
+ var drawCanvasAll = function(){
+ clearCanvas();
+ // Draw saved areas
+ for(var i = 0, l = areas.length; i < l; i++){
+ drawCanvasPoints(areas[i]);
+ }
+ // Draw current area
+ drawCanvasPoints(points);
+ };
+
+ var renderInfo = function(){
+ var text;
+
+ _.clearNode(nodes['info']);
+
+ nodes['info'].appendChild(_.node('span', ''));
+ nodes['info'].appendChild(_.node('br'));
+
+ for(var i = 0, l = areas.length; i < l; i++){
+ if(areas[i].length > 0){
+ text = ' ';
+ nodes['info'].appendChild(_.node('span', text));
+ nodes['info'].appendChild(_.node('br'));
+ }
+ }
+
+ nodes['info'].appendChild(_.node('span', ' '));
+ };
+
+ that.init = function(){
+ nodes = {
+ 'preview' : _.getEl('preview'),
+ 'draw' : _.getEl('draw'),
+ 'canvas' : _.getEl('canvas'),
+ 'points' : _.getEl('points'),
+ 'buttons' : _.getEl('bar'),
+ 'info' : _.getEl('info')
+ }
+ // Init Canvas
+ checkCanvas();
+ // Render buttons
+ clearAllBtn();
+ addBtn();
+ };
+};
+
+
+window.onload = Painter.init;
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068684_PasswordChangePage_test.js b/pool/shard010/JavaScript/0068684_PasswordChangePage_test.js
new file mode 100644
index 0000000000000000000000000000000000000000..1fc3921e98909b8cd8ab3d2af76abd7c61d116b8
--- /dev/null
+++ b/pool/shard010/JavaScript/0068684_PasswordChangePage_test.js
@@ -0,0 +1,104 @@
+// @flow
+import { assert } from "chai"
+import sinon from "sinon"
+import { FETCH_SUCCESS } from "redux-hammock/constants"
+
+import { actions } from "../actions"
+import IntegrationTestHelper from "../util/integration_test_helper"
+import ConnectedPasswordChangePage, {
+ PasswordChangePage,
+ FORM_KEY
+} from "./PasswordChangePage"
+
+const DEFAULT_STATE = {
+ passwordChange: {
+ data: {},
+ processing: false
+ },
+ forms: {
+ [FORM_KEY]: {
+ value: {
+ current_password: "asdfasdf",
+ new_password: "asdfasdf"
+ },
+ errors: {}
+ }
+ }
+}
+
+describe("PasswordChangePage", () => {
+ let helper, renderPage
+
+ beforeEach(() => {
+ helper = new IntegrationTestHelper()
+ helper.postSetPasswordStub.returns(Promise.resolve())
+ renderPage = helper.configureHOCRenderer(
+ ConnectedPasswordChangePage,
+ PasswordChangePage,
+ DEFAULT_STATE
+ )
+ })
+
+ afterEach(() => {
+ helper.cleanup()
+ })
+
+ it("should render the password change form by default", async () => {
+ const { inner } = await renderPage()
+
+ const form = inner.find("PasswordChangeForm")
+ assert.ok(form.exists())
+ assert.isNotOk(form.prop("invalidPwError"))
+ })
+
+ it("should render a success message after the form submits successfully", async () => {
+ const { inner } = await renderPage({
+ passwordChange: {
+ loaded: true,
+ processing: false,
+ postStatus: FETCH_SUCCESS
+ }
+ })
+
+ assert.isFalse(inner.find("PasswordChangeForm").exists())
+ assert.include(
+ inner
+ .find("h3")
+ .at(0)
+ .text(),
+ "Your password has been changed successfully!"
+ )
+ })
+
+ it("form onSubmit prop calls api correctly", async () => {
+ const { inner, store } = await renderPage()
+
+ const { onSubmit } = inner.find("PasswordChangeForm").props()
+
+ await onSubmit()
+
+ const dispatchedActions = store.getActions()
+
+ assert.isAtLeast(dispatchedActions.length, 3)
+ assert.equal(
+ dispatchedActions[2].type,
+ actions.passwordChange.post.requestType
+ )
+ sinon.assert.calledOnce(helper.postSetPasswordStub)
+ sinon.assert.calledWith(helper.postSetPasswordStub, "asdfasdf", "asdfasdf")
+ })
+
+ it("should pass an error object into the form when the API call fails", async () => {
+ const { inner } = await renderPage({
+ passwordChange: {
+ error: {
+ current_password: "Invalid password"
+ }
+ }
+ })
+
+ const form = inner.find("PasswordChangeForm")
+ assert.ok(form.exists())
+ assert.equal(form.prop("invalidPwError"), "Invalid password")
+ })
+})
diff --git a/pool/shard010/JavaScript/0068685_blockMenu.js b/pool/shard010/JavaScript/0068685_blockMenu.js
new file mode 100644
index 0000000000000000000000000000000000000000..bdd1d38dde7c9177e112eb92674a5802ae9d5dcc
--- /dev/null
+++ b/pool/shard010/JavaScript/0068685_blockMenu.js
@@ -0,0 +1,227 @@
+
+/**
+ * Graphic Global variables
+ * in this variables will be saved the initial ui position values for the considering elements
+ */
+var menu_top;
+var menu_offset;
+var sidebar_left_offset_top;
+var sidebar_left_offset;
+var scrollTop;
+var sidebar_right_offset_top;
+var sidebar_right_offset;
+
+
+
+/**
+ *
+ * @param menu
+ */
+function menu_fixed(menu){
+ menu.attr("class","fixed-position ");
+ menu.css("top", "0");
+ menu.css("width","90%");
+}
+
+
+/**
+ *
+ * @param menu
+ */
+function menu_absolute(menu){
+ menu.attr("class","absolute-position");
+ menu.css("top",$("#bar-menu-hidden").position().top);
+ menu.css("width","100%");
+}
+
+/**
+ *
+ * @param sidebar_left
+ */
+function sidebar_left_fixed(sidebar_left){
+ var menu = $("#bar-menu");
+ sidebar_left.css("position","fixed");
+ sidebar_left.css("top",menu.outerHeight(true)-15);
+ sidebar_left.css("left", (
+ $("#sidebar-left-hidden").offset().left )
+ );
+}
+
+/**
+ *
+ * @param sidebar_left
+ */
+function sidebar_left_absolute(sidebar_left){
+ var menu = $("#bar-menu");
+ sidebar_left.css("position","absolute");
+ sidebar_left.css("top",(menu.outerHeight(true)+menu.position().top));
+ sidebar_left.css("left", 0);
+}
+/**
+ *
+ * @returns
+ */
+function sidebar_right_absolute(sidebar_right){
+ var menu = $("#bar-menu");
+ hidden_right_sidebar=$("#sidebar-right-hidden");
+ sidebar_right.css("position","absolute");
+ sidebar_right.css("top",(menu.outerHeight(true)+menu.position().top));
+ sidebar_right.css("left", hidden_right_sidebar.position().left);
+ sidebar_right.css("margin-right", 0);
+ return news.position().left;
+}
+
+
+/**
+ *
+ * @param news it must be a jquery object, not a dom element
+ * @param position it must be a jquery object, not a dom element
+ */
+function sidebar_right_fixed(sidebar_right){
+
+ var menu = $("#bar-menu");
+ sidebar_right.css("position","fixed");
+ sidebar_right.css("top",menu.outerHeight(true)-15);
+ sidebar_right.css("left", $("#sidebar-right-hidden").offset().left);
+ sidebar_right.css("width", $("#sidebar-right-hidden").width());
+
+}
+
+/**
+ * this function is responsible for the left sidebar behavior
+ */
+function rightSideBarBehavior()
+{
+ vertical_viewport = $(window).height();
+ header_height = $("#header_content").height();
+ sidebar_right = $("#sidebar-right");
+ sidebar_right_offset = sidebar_right.offset();
+ sidebar_right_offset_top = sidebar_right.offset().top+sidebar_right.height();
+ scrollTop = $(window).scrollTop();
+
+ /**
+ * If the top bar is too close to the footer hide the menu
+ */
+ if (sidebar_right_offset_top >= ($("#footer").position().top-20))
+ {
+ sidebar_right.hide();
+ }
+ else{
+ /**
+ * Otherwise show the menu
+ */
+ sidebar_right.show();
+ }
+
+ /**
+ * If the scroll is lower (major in monitor coordinates system) convert the menu in fixed
+ * in order to follow the screen
+ */
+ if ( (scrollTop) > menu_top)
+ {
+ sidebar_right_fixed(sidebar_right);
+ }
+ else
+ {
+ /**
+ * Otherwise place the menu where it was
+ */
+ sidebar_right_absolute(sidebar_right);
+ }
+}
+
+
+/**
+ * this function is responsible for the left sidebar behavior
+ */
+function leftSideBarBehavior()
+{
+
+ vertical_viewport = $(window).height();
+ header_height = $("#header_content").height();
+ menu = $("#bar-menu");
+ sidebar_left = $("#sidebar-left");
+ sidebar_left_offset = sidebar_left.offset();
+ sidebar_left_offset_top = sidebar_left.offset().top+sidebar_left.height();
+ scrollTop = $(window).scrollTop();
+
+ /**
+ * If the top bar is too close to the footer hide the menu
+ */
+ if (sidebar_left_offset_top >= ($("#footer").position().top-20))
+ {
+ sidebar_left.hide();
+ }
+ else{
+ /**
+ * Otherwise show the menu
+ */
+ sidebar_left.show();
+ }
+
+ /**
+ * If the scroll is lower (major in monitor coordinates system) convert the menu in fixed
+ * in order to follow the screen
+ */
+ if ( (scrollTop) > menu_top)
+ {
+ menu_fixed(menu);
+ sidebar_left_fixed(sidebar_left);
+ }
+ else
+ {
+ /**
+ * Otherwise place the menu where it was
+ */
+ menu_absolute(menu);
+ sidebar_left_absolute(sidebar_left);
+ }
+}
+
+
+/**
+ * Loading function and associating it to events in document
+ */
+$(document).ready(function(){
+
+ /**
+ * Creating the behavior for desktop browser interface (more than 767 px width)
+ */
+ if($(window).width() > "767"){
+
+ vertical_viewport = $(window).height();
+ header_height = $("#header_content").height();
+
+ /**
+ * Imposing the footer "over the fold"
+ */
+ $("#content").css("min-height", (vertical_viewport - header_height) );
+
+ news = $("#news");
+ menu = $("#bar-menu");
+ sidebar_left = $("#sidebar-left");
+ sidebar_right= $("#sidebar-right");
+
+ menu_top = menu.position().top;
+ sidebar_left_offset_top = sidebar_left.position().top+sidebar_left.height();
+ sidebar_right_offset_top = sidebar_right.position().top+sidebar_right.height();
+
+ menu_offset = menu.offset();
+
+ /**
+ * appliying the behavior on the scroll event of the entire window
+ */
+ $(window).scroll(function(){
+ /**
+ * moves left sidebar plus sitemap bar
+ */
+ leftSideBarBehavior();
+ /**
+ * moves only right sidebar
+ */
+ //rightSideBarBehavior();
+ });
+ }
+});
+
+
diff --git a/pool/shard010/JavaScript/0068686_mwlCalendarMonth.spec.js b/pool/shard010/JavaScript/0068686_mwlCalendarMonth.spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..f62fa82223a819296f9fd6f2310f886538a8487d
--- /dev/null
+++ b/pool/shard010/JavaScript/0068686_mwlCalendarMonth.spec.js
@@ -0,0 +1,199 @@
+'use strict';
+
+var angular = require('angular'),
+ moment = require('moment');
+
+describe('mwlCalendarMonth directive', function() {
+ var MwlCalendarCtrl,
+ element,
+ scope,
+ $rootScope,
+ directiveScope,
+ showModal,
+ calendarHelper,
+ $templateCache,
+ template =
+ ' ';
+ var calendarDay = new Date(2015, 4, 1);
+
+ function prepareScope(vm) {
+ //These variables MUST be set as a minimum for the calendar to work
+ vm.currentDay = calendarDay;
+ vm.cellIsOpen = true;
+ vm.dayViewStart = '06:00';
+ vm.dayViewEnd = '22:00';
+ vm.dayViewsplit = 30;
+ vm.events = [
+ {
+ $id: 0,
+ title: 'An event',
+ type: 'warning',
+ startsAt: moment(calendarDay).startOf('week').subtract(2, 'days').add(8, 'hours').toDate(),
+ endsAt: moment(calendarDay).startOf('week').add(1, 'week').add(9, 'hours').toDate(),
+ draggable: true,
+ resizable: true
+ }, {
+ $id: 1,
+ title: ' Another event , with a html title',
+ type: 'info',
+ startsAt: moment(calendarDay).subtract(1, 'day').toDate(),
+ endsAt: moment(calendarDay).add(5, 'days').toDate(),
+ draggable: true,
+ resizable: true
+ }, {
+ $id: 2,
+ title: 'This is a really long event title that occurs on every year',
+ type: 'important',
+ startsAt: moment(calendarDay).startOf('day').add(7, 'hours').toDate(),
+ endsAt: moment(calendarDay).startOf('day').add(19, 'hours').toDate(),
+ recursOn: 'year',
+ draggable: true,
+ resizable: true
+ }
+ ];
+
+ showModal = sinon.spy();
+
+ vm.onEventClick = function(event) {
+ showModal('Clicked', event);
+ };
+
+ vm.onTimeSpanClick = function(event) {
+ showModal('Day clicked', event);
+ };
+
+ vm.onEventTimesChanged = function(event) {
+ showModal('Dropped or resized', event);
+ };
+ }
+
+ beforeEach(angular.mock.module('mwl.calendar'));
+
+ beforeEach(angular.mock.inject(function($compile, _$rootScope_, _calendarHelper_, _$templateCache_) {
+ $rootScope = _$rootScope_;
+ $templateCache = _$templateCache_;
+ calendarHelper = _calendarHelper_;
+ scope = $rootScope.$new();
+ prepareScope(scope);
+ element = angular.element(template);
+ element.data('$mwlCalendarController', {});
+ element = $compile(element)(scope);
+ scope.$apply();
+ directiveScope = element.isolateScope();
+ MwlCalendarCtrl = directiveScope.vm;
+ }));
+
+ it('should get the new month view when calendar refreshes and show the list of events for the current day if required', function() {
+ var monthView = [{date: moment(calendarDay), inMonth: true}];
+ sinon.stub(calendarHelper, 'getWeekDayNames').returns(['Mon', 'Tu']);
+ sinon.stub(calendarHelper, 'getMonthView').returns(monthView);
+ sinon.stub(calendarHelper, 'getWeekViewWithTimes').returns({event: 'event2'});
+ scope.$broadcast('calendar.refreshView');
+ expect(calendarHelper.getWeekDayNames).to.have.been.called;
+ expect(calendarHelper.getMonthView).to.have.been.calledWith(scope.events, scope.currentDay);
+ expect(MwlCalendarCtrl.weekDays).to.eql(['Mon', 'Tu']);
+ expect(MwlCalendarCtrl.view).to.equal(monthView);
+ expect(MwlCalendarCtrl.openRowIndex).to.equal(0);
+ expect(MwlCalendarCtrl.openDayIndex).to.equal(0);
+ });
+
+ it('should toggle the event list for the selected day ', function() {
+ MwlCalendarCtrl.view = [{date: moment(calendarDay), inMonth: true}];
+ MwlCalendarCtrl.dayClicked(MwlCalendarCtrl.view[0]);
+ //Open event list
+ expect(MwlCalendarCtrl.openRowIndex).to.equal(0);
+ expect(MwlCalendarCtrl.openDayIndex).to.equal(0);
+ expect(showModal).to.have.been.calledWith('Day clicked', {
+ calendarDate: MwlCalendarCtrl.view[0].date.toDate(),
+ $event: undefined
+ });
+
+ //Close event list
+ MwlCalendarCtrl.dayClicked(MwlCalendarCtrl.view[0]);
+ expect(MwlCalendarCtrl.openRowIndex).to.equal(null);
+ expect(MwlCalendarCtrl.openDayIndex).to.equal(null);
+ });
+
+ it('should disable the slidebox if the click event is prevented', function() {
+ expect(MwlCalendarCtrl.openRowIndex).to.be.null;
+ expect(MwlCalendarCtrl.openDayIndex).to.be.undefined;
+ MwlCalendarCtrl.view = [{date: moment(calendarDay), inMonth: true}];
+ MwlCalendarCtrl.dayClicked(MwlCalendarCtrl.view[0], false, {defaultPrevented: true});
+ expect(MwlCalendarCtrl.openRowIndex).to.be.null;
+ expect(MwlCalendarCtrl.openDayIndex).to.be.undefined;
+ });
+
+ it('should highlight an event across multiple days', function() {
+ var monthView = [{
+ date: moment(calendarDay),
+ inMonth: true,
+ events: [scope.events[0]]
+ }, {
+ date: moment(calendarDay),
+ inMonth: true,
+ events: [scope.events[0]]
+ }, {
+ date: moment(calendarDay),
+ inMonth: true,
+ events: [scope.events[1]]
+ }];
+
+ MwlCalendarCtrl.view = monthView;
+ MwlCalendarCtrl.highlightEvent(scope.events[0], true);
+ expect(monthView[0].highlightClass).to.equal('day-highlight dh-event-warning');
+ });
+
+ it('should call the callback function when you finish dropping an event', function() {
+ MwlCalendarCtrl.handleEventDrop(scope.events[0], calendarDay);
+ expect(showModal).to.have.been.calledWith('Dropped or resized', {
+ calendarEvent: scope.events[0],
+ calendarDate: new Date(2015, 4, 1),
+ calendarNewEventStart: new Date(2015, 4, 1, 8, 0),
+ calendarNewEventEnd: new Date(2015, 4, 10, 9, 0)
+ });
+ });
+
+ it('should call the callback function when you finish dropping an event with no end date', function() {
+ delete scope.events[0].endsAt;
+ MwlCalendarCtrl.handleEventDrop(scope.events[0], calendarDay);
+ expect(showModal).to.have.been.calledWith('Dropped or resized', {
+ calendarEvent: scope.events[0],
+ calendarDate: new Date(2015, 4, 1),
+ calendarNewEventStart: new Date(2015, 4, 1, 8, 0),
+ calendarNewEventEnd: null
+ });
+ });
+
+ it('should use a custom cell url', function() {
+ var templatePath = 'customMonthCell.html';
+ $templateCache.put(templatePath, 'Hello world! ');
+ scope.monthCellTemplateUrl = templatePath;
+ MwlCalendarCtrl.cellModifier = angular.noop;
+ scope.$broadcast('calendar.refreshView');
+ scope.$apply();
+ expect(element.find('my-custom-cell').length).to.be.at.least(1);
+ });
+
+ it('should use a custom cell events url', function() {
+ var templatePath = 'customMonthCellEvents.html';
+ $templateCache.put(templatePath, 'Hello world! ');
+ scope.monthCellEventsTemplateUrl = templatePath;
+ MwlCalendarCtrl.cellModifier = angular.noop;
+ scope.$broadcast('calendar.refreshView');
+ scope.$apply();
+ expect(element.find('my-custom-events').length).to.be.at.least(1);
+ });
+
+});
diff --git a/pool/shard010/JavaScript/0068687_todos.js b/pool/shard010/JavaScript/0068687_todos.js
new file mode 100644
index 0000000000000000000000000000000000000000..b9338f88ef6bda38ba60a93a935a15c2bed5bc5d
--- /dev/null
+++ b/pool/shard010/JavaScript/0068687_todos.js
@@ -0,0 +1,105 @@
+import {Rx} from '@cycle/core';
+
+function getFilterFn(route) {
+ switch (route) {
+ case '/active': return (task => task.completed === false);
+ case '/completed': return (task => task.completed === true);
+ default: return () => true; // allow anything
+ }
+}
+
+function determineFilter(todosData, route) {
+ todosData.filter = route.replace('/', '').trim();
+ todosData.filterFn = getFilterFn(route);
+ return todosData;
+}
+
+function searchTodoIndex(todosList, todoid) {
+ let top = todosList.length;
+ let bottom = 0;
+ let pointerId;
+ let index;
+ while (true) { // binary search
+ index = bottom + ((top - bottom) >> 1);
+ pointerId = todosList[index].id;
+ if (pointerId === todoid) {
+ return index;
+ } else if (pointerId < todoid) {
+ bottom = index;
+ } else if (pointerId > todoid) {
+ top = index;
+ }
+ }
+}
+
+function makeModification$(intent) {
+ let clearInputMod$ = intent.clearInput$.map(() => (todosData) => {
+ todosData.input = '';
+ return todosData;
+ });
+
+ let insertTodoMod$ = intent.insertTodo$.map((todoTitle) => (todosData) => {
+ let lastId = todosData.list.length > 0 ?
+ todosData.list[todosData.list.length - 1].id :
+ 0;
+ todosData.list.push({
+ id: lastId + 1,
+ title: todoTitle,
+ completed: false
+ });
+ todosData.input = '';
+ return todosData;
+ });
+
+ let editTodoMod$ = intent.editTodo$.map((evdata) => (todosData) => {
+ let todoIndex = searchTodoIndex(todosData.list, evdata.id);
+ todosData.list[todoIndex].title = evdata.content;
+ return todosData;
+ });
+
+ let toggleTodoMod$ = intent.toggleTodo$.map((todoid) => (todosData) => {
+ let todoIndex = searchTodoIndex(todosData.list, todoid);
+ let previousCompleted = todosData.list[todoIndex].completed;
+ todosData.list[todoIndex].completed = !previousCompleted;
+ return todosData;
+ });
+
+ let toggleAllMod$ = intent.toggleAll$.map(() => (todosData) => {
+ let allAreCompleted = todosData.list
+ .reduce((x, y) => x && y.completed, true);
+ todosData.list.forEach((todoData) => {
+ todoData.completed = allAreCompleted ? false : true;
+ });
+ return todosData;
+ });
+
+ let deleteTodoMod$ = intent.deleteTodo$.map((todoid) => (todosData) => {
+ let todoIndex = searchTodoIndex(todosData.list, todoid);
+ todosData.list.splice(todoIndex, 1);
+ return todosData;
+ });
+
+ let deleteCompletedsMod$ = intent.deleteCompleteds$.map(() => (todosData) => {
+ todosData.list = todosData.list
+ .filter(todoData => todoData.completed === false);
+ return todosData
+ });
+
+ return Rx.Observable.merge(
+ insertTodoMod$, deleteTodoMod$, toggleTodoMod$, toggleAllMod$,
+ clearInputMod$, deleteCompletedsMod$, editTodoMod$
+ );
+}
+
+function model(intent, source) {
+ let modification$ = makeModification$(intent);
+ let route$ = Rx.Observable.just('/').merge(intent.changeRoute$);
+
+ return modification$
+ .merge(source.todosData$)
+ .scan((todosData, modFn) => modFn(todosData))
+ .combineLatest(route$, determineFilter)
+ .shareReplay(1);
+}
+
+export default model;
diff --git a/pool/shard010/JavaScript/0068688_sidecar.js b/pool/shard010/JavaScript/0068688_sidecar.js
new file mode 100644
index 0000000000000000000000000000000000000000..c1215c8688308084b6733fef19d880b0a7b9fe0a
--- /dev/null
+++ b/pool/shard010/JavaScript/0068688_sidecar.js
@@ -0,0 +1,57 @@
+var joust = jupyterJsOutputArea;
+var OutputModel = joust.OutputModel, OutputView = joust.OutputView;
+
+var SideCar = function Sidecar(container, document) {
+ this.document = document;
+ this.container = container;
+
+ // parentID -> OutputArea
+ this.areas = new Map();
+};
+
+SideCar.prototype.consume = function consume (message) {
+ if (! message.parent_header && ! message.parent_header.msg_id) {
+ return;
+ }
+ if (message.header &&
+ (message.header.msg_type === "status" || message.header.msg_type === "execute_input")
+ ) {
+ return;
+ }
+
+ var parentID = message.parent_header.msg_id;
+ var area = this.areas[parentID];
+
+ if(!area) {
+ // Create it
+ area = new OutputArea(this.document);
+ area.el.id = parentID; // For later bookkeeping
+ this.container.appendChild(area.el);
+
+ // Keep a running tally of output areas
+ this.areas[parentID] = area;
+ }
+
+ var consumed = area.consume(message);
+ if (consumed) {
+ area.el.scrollIntoView();
+ }
+
+ return consumed;
+
+};
+
+var OutputArea = function OutputArea(document) {
+ this.model = new OutputModel();
+ this.view = new OutputView(this.model, document);
+
+ this.el = this.view.el;
+
+ this.el.className = 'output-area';
+};
+
+OutputArea.prototype.consume = function consume(message) {
+ return this.model.consumeMessage(message);
+};
+
+window.SideCar = SideCar;
diff --git a/pool/shard010/JavaScript/0068691_theme961.core.js b/pool/shard010/JavaScript/0068691_theme961.core.js
new file mode 100644
index 0000000000000000000000000000000000000000..01e691523a6e722d1990ebe78e3cd997de898c20
--- /dev/null
+++ b/pool/shard010/JavaScript/0068691_theme961.core.js
@@ -0,0 +1,61 @@
+/**
+ * theme961 javascript core
+ *
+ * - Provides frequently used extensions to base javascript objects
+ * - jQuery browser detection tweak
+ * - Define functions used in events
+ */
+
+// Add String.trim() method
+String.prototype.trim = function() {
+ return this.replace(/\s+$/, '').replace(/^\s+/, '');
+}
+
+// Add Array.indexOf() method
+if (!Array.prototype.indexOf) {
+ Array.prototype.indexOf = function (obj, fromIndex) {
+ if (fromIndex == null) {
+ fromIndex = 0;
+ } else if (fromIndex < 0) {
+ fromIndex = Math.max(0, this.length + fromIndex);
+ }
+
+ for (var i = fromIndex, j = this.length; i < j; i++) {
+ if (this[i] === obj) {
+ return i;
+ }
+ }
+ return -1;
+ };
+}
+
+// jQuery Browser Detect Tweak For IE7
+jQuery.browser.version = jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 && window["XMLHttpRequest"] ? "7.0" : jQuery.browser.version;
+
+// Console.log wrapper to avoid errors when firebug is not present
+// usage: log('inside coolFunc', this, arguments);
+// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
+window.log = function() {
+ log.history = log.history || []; // store logs to an array for reference
+ log.history.push(arguments);
+ if (this.console) {
+ console.log(Array.prototype.slice.call(arguments));
+ }
+};
+
+// init object
+var theme961 = theme961 || {};
+
+/**
+ * Image handling functions
+ */
+theme961.image = { _cache : [] };
+
+// preload images
+theme961.image.preload = function() {
+ for (var i = arguments.length; i--;) {
+ var cacheImage = document.createElement('img');
+ cacheImage.src = arguments[i];
+ theme961.image._cache.push(cacheImage);
+ }
+}
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068697_index.js b/pool/shard010/JavaScript/0068697_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..14afcc09fe92efa676da82c5dd9f2899c6694201
--- /dev/null
+++ b/pool/shard010/JavaScript/0068697_index.js
@@ -0,0 +1,13 @@
+import loaderUtils from 'loader-utils';
+
+module.exports = function classesLoader() {};
+module.exports.pitch = function pitch(remainingRequest) {
+ if (this.cacheable) this.cacheable();
+ return [
+ '// classes-loader: add classes names to tags from css-modules',
+ '',
+ `var content = require(${loaderUtils.stringifyRequest(this, `!!${remainingRequest}`)});`,
+ 'if(typeof content === \'string\') content = [[module.id, content, \'\']];',
+ 'if(content.locals) module.exports = content.locals;',
+ ].join(`\n`);
+};
diff --git a/pool/shard010/JavaScript/0068698_test.js b/pool/shard010/JavaScript/0068698_test.js
new file mode 100644
index 0000000000000000000000000000000000000000..35a83d7b37f9dac2f6fcbcae7cb84cb69f95854c
--- /dev/null
+++ b/pool/shard010/JavaScript/0068698_test.js
@@ -0,0 +1,62 @@
+var log4js = require('log4js');
+
+var appender = require('./index');
+
+// log4js.configure({
+// replaceConsole: true
+// });
+
+log4js.loadAppender('json', appender((event) => {
+ console.log(event);
+}));
+
+log4js.addAppender(log4js.appenders.json());
+
+var logger = log4js.getLogger();
+
+logger.trace('trace');
+logger.debug('debug');
+logger.info('info');
+logger.warn('warn');
+var error = new Error('test');
+error.code = 'fatal';
+logger.error(error);
+logger.fatal('fatal');
+logger.mark('mark');
+
+
+// logger.trace('trace test');
+// logger.debug('debug test');
+// logger.info('info test');
+// logger.warn('warn test');
+
+// var logger2 = log4js.getLogger();
+// logger2.error(new Error('2test error'));
+// logger2.error('2test error');
+// logger2.fatal('2fatal test');
+// logger2.mark('2mark test');
+
+
+
+
+// var http = require('http');
+//
+//
+// var server = http.createServer();
+//
+//
+// server.on('request', (req, res) => {
+//
+// res.start_time = new Date().getTime();
+// res.on('finish', () => {
+// var endTime = new Date().getTime();
+// console.log(req.path + 'end in ' + (endTime - res.start_time) + ' ms');
+// });
+//
+// res.write('\nok\n');
+// res.end();
+//
+// });
+//
+//
+// server.listen(6001);
diff --git a/pool/shard010/JavaScript/0068700_swarm.js b/pool/shard010/JavaScript/0068700_swarm.js
new file mode 100644
index 0000000000000000000000000000000000000000..80fa67c564e8c7ed9c9794f9cb1e94bba28f534b
--- /dev/null
+++ b/pool/shard010/JavaScript/0068700_swarm.js
@@ -0,0 +1,57 @@
+let colors = require('colors');
+let async = require('async');
+let shelljs = require('shelljs');
+
+class Swarm {
+ constructor(options) {
+ this.options = options;
+ this.buildDir = options.buildDir || 'dist/';
+ }
+
+ deploy() {
+ let self = this;
+ async.waterfall([
+ function findBinary(callback) {
+ let swarm_bin = shelljs.exec('which swarm').output.split("\n")[0];
+
+ if (swarm_bin === 'swarm not found' || swarm_bin === '') {
+ console.log('=== WARNING: Swarm not in an executable path. Guessing ~/go/bin/swarm for path'.yellow);
+ swarm_bin = "~/go/bin/swarm";
+ }
+
+ return callback(null, swarm_bin);
+ },
+ function runCommand(swarm_bin, callback) {
+ let cmd = swarm_bin + " --defaultpath " + self.buildDir + "index.html --recursive up " + self.buildDir;
+ console.log(("=== adding " + self.buildDir + " to swarm").green);
+ console.log(cmd.green);
+ let result = shelljs.exec(cmd);
+
+ return callback(null, result);
+ },
+ function getHashFromOutput(result, callback) {
+ if (result.code !== 0) {
+ return callback("couldn't upload, is the swarm daemon running?");
+ }
+
+ let rows = result.output.split("\n");
+ let dir_hash = rows.reverse()[1];
+
+ return callback(null, dir_hash);
+ },
+ function printUrls(dir_hash, callback) {
+ console.log(("=== DApp available at http://localhost:8500/bzz:/" + dir_hash + "/").green);
+
+ return callback();
+ }
+ ], function (err, result) {
+ if (err) {
+ console.log("error uploading to swarm".red);
+ console.log(err);
+ }
+ });
+ }
+}
+
+module.exports = Swarm;
+
diff --git a/pool/shard010/JavaScript/0068702_jquery.combobox.js b/pool/shard010/JavaScript/0068702_jquery.combobox.js
new file mode 100644
index 0000000000000000000000000000000000000000..8fe0f2314bbad3dee6682c426a5af9efee8a22f0
--- /dev/null
+++ b/pool/shard010/JavaScript/0068702_jquery.combobox.js
@@ -0,0 +1,192 @@
+/* Combobox widget for the autocomplete plugin. */
+(function ($) {
+ $.widget("ui.combobox", {
+ _create: function () {
+ var self = this,
+ select = this.element.hide(),
+ selected = select.children(":selected"),
+ value = selected.val() ? selected.text() : "",
+ regSearch = /^[^a-zA-Z0-9]*([a-zA-Z0-9])/i,
+ comboData = select.children("option").map(function () {
+ if (this.value ) {
+ var text = $(this).text(),
+ labelHtml = self.options.label ? self.options.label(this) : text; //allows list customization
+
+ return {
+ label: labelHtml,
+ value: $.trim(text),
+ option: this
+ };
+ }
+ });
+
+ var input = this.input = $(" ")
+ .insertAfter(select)
+ //Yunjia: this has been changed from value to value.trim()
+ .val($.trim(value))
+ .keydown( function( event ) {
+ var keyCode = $.ui.keyCode;
+ switch( event.keyCode ) {
+ case keyCode.PAGE_UP:
+ case keyCode.PAGE_DOWN:
+ case keyCode.UP:
+ case keyCode.DOWN:
+ case keyCode.ENTER:
+ case keyCode.NUMPAD_ENTER:
+ case keyCode.TAB:
+ case keyCode.ESCAPE:
+ //let autocomplete handle these
+ break;
+ default:
+ //prevent autocomplete doing anything
+ event.stopImmediatePropagation();
+ //only react to [a-zA-Z0-9]
+ if ((event.keyCode < 91 && event.keyCode > 59)
+ || (event.keyCode < 58 && event.keyCode > 47)) {
+
+ var str = String.fromCharCode(event.keyCode).toLowerCase(), currVal = input.val(), opt;
+
+ //find all options whose first alpha character matches that pressed
+ var matchOpt = select.children().filter(function() {
+ var test = regSearch.exec(this.text);
+ return (test && test.length == 2 && test[1].toLowerCase() == str);
+ });
+
+ if (!matchOpt.length ) return false;
+
+ //if there is something selected we need to find the next in the list
+ if (currVal.length) {
+ var test = regSearch.exec(currVal);
+ if (test && test.length == 2 && test[1].toLowerCase() == str) {
+ //the next one that begins with that letter
+ matchOpt.each(function(ix, el) {
+ if (el.selected) {
+ if ((ix + 1) <= matchOpt.length-1) {
+ opt = matchOpt[ix + 1];
+ }
+ return false;
+ }
+ });
+ }
+ }
+
+ //fallback to the first one that begins with that character
+ if (!opt)
+ opt = matchOpt[0];
+
+ //select that item
+ opt.selected = true;
+ input.val(opt.text);
+
+ //if the dropdown is open, find it in the list
+ if (input.autocomplete("widget").is(":visible")) {
+ input.data("autocomplete").widget().children('li').each(function() {
+ var $li = $(this);
+ if ($li.data("item.autocomplete").option == opt) {
+ input.data("autocomplete").menu.activate(event,$li);
+ return false;
+ }
+ });
+ }
+ }
+ //ignore all other keystrokes
+ return false;
+ break;
+ }
+ })
+ .autocomplete({
+ delay: 0,
+ minLength: 0,
+ source: function (request, response) { response(comboData); },
+ select: function (event, ui) {
+ ui.item.option.selected = true;
+ self._trigger("selected", event, {
+ item: ui.item.option
+ });
+ },
+ change: function (event, ui) {
+ if (!ui.item) {
+ var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
+ valid = false;
+ select.children("option").each(function () {
+ if ($(this).text().match(matcher)) {
+ this.selected = valid = true;
+ return false;
+ }
+ });
+ if (!valid) {
+ // remove invalid value, as it didn't match anything
+ $(this).val("");
+ select.val("");
+ input.data("autocomplete").term = "";
+ return false;
+ }
+ }
+ }
+ })
+ .addClass("ui-widget ui-widget-content ui-corner-left")
+ .click(function() { self.button.click(); })
+ .bind("autocompleteopen", function(event, ui){
+ //find the currently selected item and highlight it in the list
+ var opt = select.children(":selected")[0];
+ input.data("autocomplete").widget().children('li').each(function() {
+ var $li = $(this);
+ if ($li.data("item.autocomplete").option == opt) {
+ input.data("autocomplete").menu.activate(event,$li);
+ return false;
+ }
+ });
+ });
+
+ input.data("autocomplete")._renderItem = function (ul, item) {
+ return $(" ")
+ .data("item.autocomplete", item)
+ .append("" + item.label + " ")
+ .appendTo(ul);
+ };
+
+ this.button = $(" ")
+ .attr("tabIndex", -1)
+ .attr("title", "Show All Items")
+ .insertAfter(input)
+ .button({
+ icons: {
+ primary: "ui-icon-triangle-1-s"
+ },
+ text: false
+ })
+ .removeClass("ui-corner-all")
+ .addClass("ui-corner-right ui-button-icon")
+ .click(function () {
+ // close if already visible
+ if (input.autocomplete("widget").is(":visible")) {
+ input.autocomplete("close");
+ return;
+ }
+
+ // pass empty string as value to search for, displaying all results
+ input.autocomplete("search", "");
+ input.focus();
+ });
+ },
+
+ //allows programmatic selection of combo using the option value
+ setValue: function (value) {
+ var $input = this.input;
+ $("option", this.element).each(function () {
+ if ($(this).val() == value) {
+ this.selected = true;
+ $input.val(this.text);
+ return false;
+ }
+ });
+ },
+
+ destroy: function () {
+ this.input.remove();
+ this.button.remove();
+ this.element.show();
+ $.Widget.prototype.destroy.call(this);
+ }
+ });
+})(jQuery);
diff --git a/pool/shard010/JavaScript/0068703_document.js b/pool/shard010/JavaScript/0068703_document.js
new file mode 100644
index 0000000000000000000000000000000000000000..33f865d0276500edcd63439b54017ab900e88303
--- /dev/null
+++ b/pool/shard010/JavaScript/0068703_document.js
@@ -0,0 +1,53 @@
+(function() {
+ 'use strict';
+ var mongoose = require('mongoose');
+ var Schema = mongoose.Schema;
+ require('./user');
+
+ var DocumentSchema = new Schema({
+ ownerId: {
+ type: Schema.Types.ObjectId,
+ ref: 'User',
+ required: true
+ },
+
+ accessLevel: {
+ type: Number,
+ enum: [1, 2, 3],
+ default: 1
+ },
+
+ contributors: [{
+ type: Schema.Types.ObjectId,
+ ref: 'User',
+ required: false
+ }],
+
+ title: {
+ type: String,
+ required: true
+ },
+
+ category: {
+ type: Schema.Types.ObjectId,
+ ref: 'Category',
+ required: true
+ },
+
+ content: {
+ type: String,
+ required: true
+ },
+
+ createdAt: {
+ type: Date
+ },
+
+ modifiedAt: {
+ type: Date,
+ Default: Date.now
+ }
+ });
+
+ module.exports = mongoose.model('Document', DocumentSchema);
+})();
diff --git a/pool/shard010/JavaScript/0068705_logger.js b/pool/shard010/JavaScript/0068705_logger.js
new file mode 100644
index 0000000000000000000000000000000000000000..63be21324bcebdcf749748520ca280b902aef74a
--- /dev/null
+++ b/pool/shard010/JavaScript/0068705_logger.js
@@ -0,0 +1,30 @@
+var chalk = require('chalk');
+var mout = require('mout');
+
+var lfit = function(str, len) {
+ str = mout.string.truncate(str, len);
+ str = mout.string.lpad(str, len);
+ return str;
+};
+
+var rfit = function(str, len) {
+ str = mout.string.truncate(str, len);
+ str = mout.string.rpad(str, len);
+ return str;
+};
+
+var prefix = chalk.gray('chute');
+
+module.exports = {
+ info: function(locals) {
+ var line = [
+ prefix,
+ chalk.cyan(rfit(locals.actor, 24)),
+ chalk.green(lfit(locals.action, 9)),
+ chalk.white(rfit(locals.detail, 39))
+ ];
+ line = line.join(' ');
+ console.log(line);
+ return line;
+ }
+};
diff --git a/pool/shard010/JavaScript/0068709_decoder.js b/pool/shard010/JavaScript/0068709_decoder.js
new file mode 100644
index 0000000000000000000000000000000000000000..b60e1e820d00da891378b17d551d8e6cf28ba0a1
--- /dev/null
+++ b/pool/shard010/JavaScript/0068709_decoder.js
@@ -0,0 +1,204 @@
+// Copyright 2015 Yahoo! Inc.
+// Copyrights licensed under the Mit License. See the accompanying LICENSE file for terms.
+
+var Chunk = require('./chunk');
+
+var CRC = require('./processor/crc');
+
+var BufferedStream = require('./utils/bufferedStream');
+var utils = require('./utils/utils');
+var constants = require('./utils/constants');
+
+var path = require('path');
+
+
+/**
+ * @class Decoder
+ * @module PNG
+ * @submodule PNGCore
+ * @extends chunkUtils
+ * @constructor
+ */
+var Decoder = function () {
+ this._chunks = {};
+ this._chunkData = {};
+
+ utils.loadModule(path.join(__dirname, 'utils', 'chunkUtils.js'), this);
+};
+
+
+/**
+ * Gets the data supplied by each chunk
+ *
+ * @method getChunkData
+ * @return {object}
+ */
+Decoder.prototype.getChunkData = function () {
+ return this._chunkData;
+};
+
+
+/**
+ * Decodes the supplied data
+ *
+ * @method decode
+ * @param {Buffer} buffer Image data
+ * @param {object} [options] Decoding options
+ * @param {boolean} [options.strict=false] Strict decoding
+ */
+Decoder.prototype.decode = function (buffer, options) {
+
+ options = options || {};
+
+ var i, len,
+ chunk, image = null,
+ signature = constants.signature,
+ streamSignature,
+ strict = !!options.strict,
+ stream = new BufferedStream(buffer, false);
+
+ this._chunks = {};
+ this._chunkData = {};
+
+ // Check signature
+ streamSignature = stream.readBuffer(signature.length);
+ for (i = 0, len = signature.length; i < len; i++) {
+ if (streamSignature[i] !== signature[i]) {
+ // Always throw error (even with strict=false) - need to be sure it is a PNG
+ throw new Error('Invalid signature for a PNG image.');
+ }
+ }
+
+ // Load all chunks until end is reached
+ // Phase 1 - Forward
+ do {
+ chunk = this._parseChunk(stream, strict, options);
+ } while (chunk.getType() !== 'IEND');
+
+ // Run through all chunks before scaling
+ // Phase 2 - Forward
+ this.applyWithSortedChunks(function (chunk) {
+
+ try {
+ image = chunk.decode(image, strict, options);
+
+ } catch (err) {
+
+ // Ignore non-critical errors - not required for image reading
+ // If strict is requested, then re-throw
+ if (strict || chunk.isCritical()) {
+ throw err;
+ }
+ }
+ }, true);
+
+ // Run through all chunks after scaling
+ // Phase 3 - Forward
+ this.applyWithSortedChunks(function (chunk) {
+
+ try {
+ image = chunk.postDecode(image, strict, options);
+
+ } catch (err) {
+
+ // Ignore non-critical errors - not required for image reading
+ // If strict is requested, then re-throw
+ if (strict || chunk.isCritical()) {
+ throw err;
+ }
+ }
+ }, true);
+
+ // Run through all chunks after image is complete
+ // Phase 4 - Forward
+ this.applyWithSortedChunks(function (chunk) {
+
+ try {
+ image = chunk.finalizeDecode(image, strict, options);
+
+ } catch (err) {
+
+ // Ignore non-critical errors - not required for image reading
+ // If strict is requested, then re-throw
+ if (strict || chunk.isCritical()) {
+ throw err;
+ }
+ }
+ }, true);
+
+ // Run through all chunks-types (not chunks) to gather chunk-data
+ // Phase 5 - Forward
+ this.applyWithSortedChunks(function (chunk) {
+ Chunk.decodeTypeData(chunk.getType(), this._chunkData, this._chunks, strict, options);
+ }.bind(this), false);
+
+ return image;
+};
+
+/**
+ * Reads the next chunk in the stream
+ *
+ * @method _parseChunk
+ * @param {BufferedStream} stream Data stream
+ * @param {boolean} strict Should decoding be strict?
+ * @param {object} options Decoding options
+ * @return {Chunk} Chunk read
+ * @private
+ */
+Decoder.prototype._parseChunk = function (stream, strict, options) {
+
+ var chunkLength,
+ chunkType,
+ chunkCrc,
+ calculatedCrc,
+ crc,
+ chunk,
+ chunkOffset;
+
+ // Read chunk-length
+ chunkLength = stream.readUInt32BE();
+ if (chunkLength + 8 > stream.length) {
+ throw new Error('Chunk length is greater than the input data.');
+ }
+ chunkOffset = stream.readOffset + chunkLength + 8; // 8 for type and CRC value
+
+ // Load chunk for crc calculation
+ crc = new CRC();
+ crc.write(stream.toBuffer(true), stream.readOffset, chunkLength + 4); // Including chunk-type
+
+ // Create chunk that is suggested by the data
+ chunkType = stream.readString(4, 'ascii');
+ chunk = new Chunk(chunkType, this._chunks);
+
+ try {
+
+ // Parsing of chunk data
+ chunk.parse(stream, chunkLength, strict, options);
+
+ // Load crc and compare with calculated one
+ chunkCrc = stream.readInt32BE();
+ calculatedCrc = crc.getValue();
+ if (strict && (chunkCrc !== calculatedCrc)) {
+ //throw new Error('CRC error.');
+ //TODO: Something is not working; overflow?
+ }
+
+ // Add to parsed chunks
+ this.addChunk(chunk);
+
+ } catch (err) {
+
+ // Ignore non-critical errors - not required for image reading
+ // If strict is requested, then re-throw
+ if (strict || chunk.isCritical()) {
+ throw err;
+ }
+ } finally {
+ // Make sure the chunk did not read over bounds - resetting of reader offset
+ stream.readOffset = chunkOffset;
+ }
+
+ return chunk;
+};
+
+module.exports = Decoder;
diff --git a/pool/shard010/JavaScript/0068711_generateHashes.js b/pool/shard010/JavaScript/0068711_generateHashes.js
new file mode 100644
index 0000000000000000000000000000000000000000..ee5fde837b2006c395388fff3be8fee33762f86e
--- /dev/null
+++ b/pool/shard010/JavaScript/0068711_generateHashes.js
@@ -0,0 +1,33 @@
+var fs = require('fs');
+var crypto = require('crypto');
+
+var sha1Stream = crypto.createHash('sha1');
+sha1Stream.setEncoding('base64');
+
+var md5Stream = crypto.createHash('md5');
+md5Stream.setEncoding('base64');
+
+
+var inputFile = process.argv[2];
+var inputStream = fs.createReadStream(inputFile);
+
+console.log('[sha1]');
+inputStream
+ .pipe(sha1Stream)
+ .pipe(process.stdout);
+
+inputStream.on('end', function() {
+ console.log("\n\n[md5]");
+});
+
+
+inputStream
+ .pipe(md5Stream)
+ .pipe(process.stdout);
+
+inputStream.on('end', function() {
+ console.log("\n");
+});
+
+//spliting stream
+//node generateHashes pathToFile
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068712_generate_blocks.js b/pool/shard010/JavaScript/0068712_generate_blocks.js
new file mode 100644
index 0000000000000000000000000000000000000000..4d9b48b476920d796e44a22a7d421e944f8b11cf
--- /dev/null
+++ b/pool/shard010/JavaScript/0068712_generate_blocks.js
@@ -0,0 +1,141 @@
+const asyncAuto = require('async/auto');
+const asyncMap = require('async/map');
+const asyncTimesSeries = require('async/timesSeries');
+const asyncRetry = require('async/retry');
+const {networks} = require('bitcoinjs-lib');
+const {payments} = require('bitcoinjs-lib');
+const {returnResult} = require('asyncjs-util');
+const tinysecp = require('tiny-secp256k1');
+
+const rpc = require('./rpc');
+
+const interval = retryCount => 2000 * Math.random();
+const {p2pkh} = payments;
+const retryTimes = 50;
+
+/** Generate blocks on the chain daemon
+
+ {
+ [cert]:
+ [chain]:
+ [count]:
+ host:
+ [key]:
+ pass:
+ port:
+ user:
+ }
+
+ @return via cbk or Promise
+ {
+ blocks: []
+ }
+*/
+module.exports = ({cert, chain, count, host, key, pass, port, user}, cbk) => {
+ return new Promise((resolve, reject) => {
+ return asyncAuto({
+ // Import ECPair library
+ ecp: async () => (await import('ecpair')).ECPairFactory(tinysecp),
+
+ // Check arguments
+ validate: cbk => {
+ if (!host) {
+ return cbk([400, 'ExpectedChainRpcHostForGenerateBlocks']);
+ }
+
+ if (!pass) {
+ return cbk([400, 'ExpectedChainRpcPassForGenerateBlocks']);
+ }
+
+ if (!port) {
+ return cbk([400, 'ExpectedChainRpcPortForGenerateBlocks']);
+ }
+
+ if (!user) {
+ return cbk([400, 'ExpectedChainRpcUserForGenerateBlocks']);
+ }
+
+ return cbk();
+ },
+
+ // Generate blocks
+ generate: ['ecp', 'validate', ({ecp}, cbk) => {
+ let cmd;
+ let params;
+
+ switch (chain) {
+ case 'bitcoind':
+ const miningKey = Buffer.from(key, 'hex');
+ const network = networks.testnet;
+
+ const pubkey = ecp.fromPublicKey(miningKey, network).publicKey;
+
+ cmd = 'generatetoaddress';
+ params = [[count].length, p2pkh({network, pubkey}).address];
+ break;
+
+ default:
+ cmd = 'generate';
+ params = [count];
+ break;
+ }
+
+ return rpc({
+ cert,
+ cmd,
+ host,
+ params,
+ pass,
+ port,
+ user,
+ },
+ (err, res) => {
+ if (!!err) {
+ return cbk([503, 'UnexpectedErrorGeneratingBlocks']);
+ }
+
+ if (!res) {
+ return cbk();
+ }
+
+ if (!Array.isArray(res)) {
+ return cbk([503, 'ExpectedBlockHashesForBlockGeneration', res]);
+ }
+
+ return cbk(null, res);
+ });
+ }],
+
+ // Get blocks with transaction ids
+ blocks: ['generate', ({generate}, cbk) => {
+ const cmd = 'getblock';
+
+ return asyncMap(generate.filter(n => !!n), (blockId, cbk) => {
+ const opts = {cert, cmd, host, pass, port, user, params: [blockId]};
+
+ return asyncRetry({interval, times: retryTimes}, cbk => {
+ return rpc(opts, (err, res) => {
+ if (!!err) {
+ return cbk([503, 'UnexpectedErrorGettingBlock', {err}]);
+ }
+
+ if (!res || !Array.isArray(res.tx)) {
+ return cbk([503, 'ExpectedBlockTransactionsForBlock', res]);
+ }
+
+ return cbk(null, {id: blockId, transaction_ids: res.tx});
+ });
+ },
+ cbk);
+ },
+ cbk);
+ }],
+
+ // Final result
+ generation: ['blocks', ({blocks}, cbk) => {
+ return cbk(null, {blocks})
+ }],
+ },
+ returnResult({reject, resolve, of: 'generation'}, cbk));
+ });
+};
diff --git a/pool/shard010/JavaScript/0068714_plugin-sharing.js b/pool/shard010/JavaScript/0068714_plugin-sharing.js
new file mode 100644
index 0000000000000000000000000000000000000000..d20b14fbe0541a3e05eb7991733295a39cf4d9af
--- /dev/null
+++ b/pool/shard010/JavaScript/0068714_plugin-sharing.js
@@ -0,0 +1,94 @@
+require(["gitbook", "lodash"], function(gitbook, _) {
+ var SITES = {
+ 'facebook': {
+ 'label': 'Facebook',
+ 'icon': 'fa fa-facebook',
+ 'onClick': function(e) {
+ e.preventDefault();
+ window.open("http://www.facebook.com/sharer/sharer.php?s=100&p[url]="+encodeURIComponent(location.href));
+ }
+ },
+ 'twitter': {
+ 'label': 'Twitter',
+ 'icon': 'fa fa-twitter',
+ 'onClick': function(e) {
+ e.preventDefault();
+ window.open("http://twitter.com/home?status="+encodeURIComponent(document.title+" "+location.href));
+ }
+ },
+ 'google': {
+ 'label': 'Google+',
+ 'icon': 'fa fa-google-plus',
+ 'onClick': function(e) {
+ e.preventDefault();
+ window.open("https://plus.google.com/share?url="+encodeURIComponent(location.href));
+ }
+ },
+ 'weibo': {
+ 'label': 'Weibo',
+ 'icon': 'fa fa-weibo',
+ 'onClick': function(e) {
+ e.preventDefault();
+ window.open("http://service.weibo.com/share/share.php?content=utf-8&url="+encodeURIComponent(location.href)+"&title="+encodeURIComponent(document.title));
+ }
+ },
+ 'instapaper': {
+ 'label': 'Instapaper',
+ 'icon': 'fa fa-instapaper',
+ 'onClick': function(e) {
+ e.preventDefault();
+ window.open("http://www.instapaper.com/text?u="+encodeURIComponent(location.href));
+ }
+ },
+ 'vk': {
+ 'label': 'VK',
+ 'icon': 'fa fa-vk',
+ 'onClick': function(e) {
+ e.preventDefault();
+ window.open("http://vkontakte.ru/share.php?url="+encodeURIComponent(location.href));
+ }
+ }
+ };
+
+
+
+ gitbook.events.bind("start", function(e, config) {
+ var opts = config.sharing;
+ if (!opts) return;
+
+ // Create dropdown menu
+ var menu = _.chain(opts.all)
+ .map(function(id) {
+ var site = SITES[id];
+
+ return {
+ text: site.label,
+ onClick: site.onClick
+ };
+ })
+ .compact()
+ .value();
+
+ // Create main button with dropdown
+ if (menu.length > 0) {
+ gitbook.toolbar.createButton({
+ icon: 'fa fa-share-alt',
+ label: 'Share',
+ position: 'right',
+ dropdown: [menu]
+ });
+ }
+
+ // Direct actions to share
+ _.each(SITES, function(site, sideId) {
+ if (!opts[sideId]) return;
+
+ gitbook.toolbar.createButton({
+ icon: site.icon,
+ label: site.text,
+ position: 'right',
+ onClick: site.onClick
+ });
+ });
+ });
+});
diff --git a/pool/shard010/JavaScript/0068716_previous-search-result.directive.js b/pool/shard010/JavaScript/0068716_previous-search-result.directive.js
new file mode 100644
index 0000000000000000000000000000000000000000..4d73175661034c635ee90a3bff29a94e4e73a81c
--- /dev/null
+++ b/pool/shard010/JavaScript/0068716_previous-search-result.directive.js
@@ -0,0 +1,42 @@
+/* global _ */
+'use strict';
+
+angular.module('metadatamanagementApp').directive('previousSearchResult',
+ function(SearchResultNavigatorService, SearchTypeToDetailsStateMapper,
+ $state, Principal) {
+ return {
+ restrict: 'E',
+ templateUrl: 'scripts/searchmanagement/directives/' +
+ 'previous-search-result.html.tmpl',
+ link: function(scope) {
+ SearchResultNavigatorService.getPreviousSearchResult().promise
+ .then(function(data) {
+ if (data.hits.hits.length === 1) {
+ scope.previousSearchResult = data.hits.hits[0]._source;
+ scope.previousSearchResultIndex = SearchResultNavigatorService
+ .getPreviousSearchResultIndex();
+
+ var state = SearchTypeToDetailsStateMapper
+ .getDetailStateUrl(data.hits.hits[0]._index);
+ var id = scope.previousSearchResult.masterId ?
+ scope.previousSearchResult.masterId : scope
+ .previousSearchResult.id;
+
+ scope.goToPreviousSearchResult = function() {
+ $state.go(state, {
+ id: id,
+ 'search-result-index': scope.previousSearchResultIndex,
+ version: Principal.loginName() ? undefined :
+ _.get(scope.previousSearchResult, 'release.version'),
+ lang: scope.currentLanguage
+ }, {inherit: false});
+ };
+ }
+ });
+ },
+ scope: {
+ currentLanguage: '=',
+ bowser: '='
+ }
+ };
+ });
diff --git a/pool/shard010/JavaScript/0068717_index.js b/pool/shard010/JavaScript/0068717_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..9a02d48c906a8683480c87f82155a39c2d4f5aaf
--- /dev/null
+++ b/pool/shard010/JavaScript/0068717_index.js
@@ -0,0 +1,92 @@
+'use strict';
+
+/**
+ * This microservice retrieves all the selfies from the database.
+ *
+ * @author Sam Verschueren
+ * @since 4 Aug. 2015
+ */
+
+// module dependencies
+var db = require('dynongo'),
+ moment = require('moment'),
+ Q = require('q'),
+ _ = require('lodash');
+
+// connect with the database
+db.connect();
+
+var Selfie = db.table('Selfie');
+
+var MIN_DATE = moment('2015-08-14').startOf('day'),
+ ITEMS_PER_PAGE = 50;
+
+/**
+ * Main entrypoint of the service.
+ *
+ * @param {object} event The data regarding the event.
+ * @param {object} context The AWS Lambda execution context.
+ */
+exports.handler = function(event, context) {
+ // Log the event for debugging purposes
+ console.log(event);
+
+ var since;
+
+ Q.fcall(function() {
+ if(event.since && event.since.length > 0) {
+ // If the since query parameter is provided, set it
+ since = moment(event.since);
+ }
+
+ // Retrieve all the selfies from the database
+ return fetch(since);
+ }).then(function(result) {
+ // Send the result back to the client
+ context.succeed(_.flatten(result));
+ }).catch(function(err) {
+ // Print the error if something went wrong
+ console.error(err, err.stack);
+
+ // Something went wrong
+ context.fail(err);
+ });
+
+ function fetch(date) {
+ return fetchHelper(date);
+ };
+
+ function fetchHelper(date, numberOfItems) {
+ var start = (moment(date) || moment()).startOf('day');
+
+ return Q.fcall(function() {
+ var query;
+
+ if(since) {
+ query = Selfie.find({id: start.format('YYYY-MM-DD'), date: {$lt: since.format()}}, 'DateIndex');
+ }
+ else {
+ query = Selfie.find({id: start.format('YYYY-MM-DD')});
+ }
+
+ return query.select('name email date description image').sort(-1).limit(numberOfItems || ITEMS_PER_PAGE).exec()
+ })
+ .then(function(result) {
+ if(result.length === 0) {
+ start.subtract(1, 'day');
+ }
+ else {
+ since = moment(result[result.length-1].date);
+ }
+
+ if(result.length < ITEMS_PER_PAGE && start.diff(MIN_DATE, 'days') >= 0) {
+ return fetchHelper(start, ITEMS_PER_PAGE-result.length)
+ .then(function(data) {
+ return result.concat(data);
+ });
+ }
+
+ return result;
+ });
+ }
+};
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068719_main.js b/pool/shard010/JavaScript/0068719_main.js
new file mode 100644
index 0000000000000000000000000000000000000000..5ea153685458e15f9357b3ef64406b8f355df8c6
--- /dev/null
+++ b/pool/shard010/JavaScript/0068719_main.js
@@ -0,0 +1,97 @@
+require.config({
+ baseUrl: "engine",
+ packages: [
+ {
+ name: 'audio',
+ location: './audio',
+ main: "audio-module"
+ },
+ {
+ name: 'error',
+ location: './error',
+ main: "error-module"
+ },
+ {
+ name: 'input',
+ location: './input',
+ main: "input-module"
+ },
+ {
+ name: 'parser',
+ location: './parser',
+ main: "parser-module"
+ },
+ {
+ name: 'physics',
+ location: './physics',
+ main: "physics-module"
+ },
+ {
+ name: 'render',
+ location: './render',
+ main: "render-module"
+ },
+ {
+ name: 'resource',
+ location: './resource',
+ main: "resource-module"
+ },
+ {
+ name: 'scene',
+ location: './scene',
+ main: "scene-module"
+ },
+ {
+ name: 'shims',
+ location: './shims',
+ main: "shims-module"
+ }
+ ]
+});
+
+define(["audio","error","input","parser","physics","render","resource","scene","shims"], function(){
+ var engine = {};
+
+ engine.audio = require("audio");
+ engine.error = require("error");
+ engine.input = require("input");
+ engine.parser = require("parser");
+ engine.physics = require("physics");
+ engine.render = require("render");
+ engine.resource = require("resource");
+ engine.scene = require("scene");
+ engine.shims = require("shims");
+
+ engine.tick = 1;
+ engine.loopId = null;
+ engine.animId = null;
+ engine.halted = false;
+
+ engine.loop = function(callback, fps) {
+ if(!engine.halted)
+ this.loopId = setTimeout(function(){
+ engine.animId = requestAnimationFrame(engine.loop.bind(this, callback, fps));
+ if(++engine.tick>fps)
+ engine.tick = 1;
+ $.publish("engineTick", [engine.tick]);
+ callback();
+ }, 1000/fps);
+ };
+
+ engine.init = function(callback, fps) {
+ engine.fps = fps;
+ engine.loop(callback, fps);
+ };
+
+ engine.halt = function() {
+ clearTimeout(this.loopId);
+ cancelAnimationFrame(this.animId);
+ this.loopId = null;
+ this.animId = null;
+ engine.halted = true;
+ };
+
+ $.subscribe("haltEngine", engine.halt);
+
+ return engine;
+});
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068720_js.js b/pool/shard010/JavaScript/0068720_js.js
new file mode 100644
index 0000000000000000000000000000000000000000..5cca057eb67299f1c1785f18ffacec8a321b20e2
--- /dev/null
+++ b/pool/shard010/JavaScript/0068720_js.js
@@ -0,0 +1,46 @@
+define(function()
+{
+ var Analyze = function()
+ {
+ var node,
+ data,
+ max,
+
+ init = function(_node, _data)
+ {
+ this.node = _node;
+ this.data = _data.data;
+
+ this.draw(this.data.disk,this.data.network,this.data.name,_data.max*1.02);
+ return this;
+ },
+
+ draw = function(_disk,_network,_name,_max)
+ {
+ var totalWidth = $("div.content",this.node).width();
+ var diskWidth = (_disk/_max)*totalWidth;
+ var networkWidth = (_network/_max)*totalWidth;
+
+ $("div.user",this.node).text(_name);
+ $("div.content > div.disk",this.node).text(_disk).animate({width:diskWidth});
+ $("div.content > div.network",this.node).text(_network).animate({width:networkWidth});
+ $("div.money",this.node).html(configuration.fee.networkGB.unit+" "+(_disk+_network));
+ },
+
+ destroy = function()
+ {
+ this.node.remove();
+ },
+
+ that =
+ {
+ init: init,
+ draw:draw,
+ destroy: destroy
+ };
+
+ return that;
+ }
+
+ return Analyze;
+});
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068725_domain.js b/pool/shard010/JavaScript/0068725_domain.js
new file mode 100644
index 0000000000000000000000000000000000000000..8b1394ad7fd475fca1adb6ccd5529e0e06a42344
--- /dev/null
+++ b/pool/shard010/JavaScript/0068725_domain.js
@@ -0,0 +1,18 @@
+var d = require('domain').create();
+
+d.on('error', function(err) {
+ console.error('LivelyFS encountered error: ', err.stack || err);
+ process.exit();
+});
+
+d.bindMethods = function(obj) {
+ var result = [];
+ Object.keys(obj).forEach(function(name) {
+ var val = obj[name];
+ if (typeof val === 'function') val = d.bind(val);
+ result[name] = val;
+ });
+ return result;
+}
+
+module.exports = d;
diff --git a/pool/shard010/JavaScript/0068726_index.js b/pool/shard010/JavaScript/0068726_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..a586b33f43bcc87172cd73263d0ff2907f773983
--- /dev/null
+++ b/pool/shard010/JavaScript/0068726_index.js
@@ -0,0 +1,407 @@
+import { dataset } from './models/dataset_new'
+import { mesh_view } from './views/mesh_view'
+import { display_view } from './views/display_view'
+import { timeseries_view } from './views/timeseries_view'
+
+// Build the UI
+var canvas = d3.select( '#canvas' );
+
+// Initialize the renderer
+var renderer = adcirc
+ .gl_renderer( canvas )
+ .clear_color( d3.color( '#666666' ) );
+
+// Initialize the UI
+var ui = adcirc
+ .ui( d3.select( 'body' ) );
+
+// The container for available mesh fields
+var fields;
+
+
+//// Sidebar sections
+
+// The sidebar itself
+var sidebar = d3.select( '#sidebar' );
+
+// Mesh Properties
+var mesh_properties_section = sidebar.append( 'div' ).attr( 'class', 'item' );
+
+// Mesh data
+var mesh_data_section= sidebar.append( 'div' ).attr( 'class', 'item' );
+
+// Timeseries things
+var timeseries_section = sidebar.append( 'div' ).attr( 'class', 'item' );
+var ts_selection;
+var ts_view = timeseries_view();
+
+// Display options
+var display_options_section = sidebar.append( 'div' ).attr( 'class', 'item' );
+var display_options = display_view()
+ .on( 'render', renderer.render );
+
+// Step 1 is to select a fort.14 file
+ui.fort14.file_picker( function ( file ) {
+
+ // Remove the opening message
+ d3.select( '#opening-message' ).remove();
+
+ // Remove the fort.14 button
+ d3.select( '#fort14-item' ).remove();
+
+ // Add load bar
+ var progress = adcirc.progress()
+ .height( 25 );
+
+ var selection = sidebar.append( 'div' )
+ .attr( 'class', 'item' );
+
+ progress( selection.append( 'div' ) );
+
+ // Create the dataset
+ var data = dataset( renderer.gl_context() );
+ var mesh = data.mesh();
+
+ // Connect events
+ data.on( 'progress', update_progress );
+ data.on( 'render', renderer.render );
+
+ data.once( 'ready', function () {
+
+ selection.remove();
+
+ data.off( 'progress', update_progress );
+
+ display_mesh( data );
+
+ });
+
+ data.on( 'has_view', function ( event ) {
+
+ renderer.add_view( event.view );
+
+ } );
+
+ ts_view.on( 'request', function ( event ) {
+
+ data.request_timestep( event.value );
+
+ });
+
+ // Zoom to the mesh once it's loaded
+ mesh.on( 'bounding_box', function () {
+
+ renderer.zoom_to( mesh, 200 );
+
+ });
+
+ // Load the file
+ data.load_fort_14( file );
+
+ // The progress bar update function
+ function update_progress ( event ) {
+
+ progress.progress( event.progress );
+
+ }
+
+});
+
+// Step 2 is to display fort.14 information and provide options for loading more data
+function display_mesh ( data ) {
+
+ // Get the mesh
+ var mesh = data.mesh();
+
+ // Add mesh info header
+ mesh_properties_section.append( 'div' )
+ .attr( 'class', 'header' )
+ .text( 'Mesh Properties' );
+
+ var mesh_info = mesh_properties_section
+ .attr( 'class', 'item' );
+
+ // Add number of nodes
+ var node_info = mesh_info
+ .append( 'div' )
+ .attr( 'class', 'two-col' );
+
+ node_info.append( 'div' ).attr( 'class', 'left' ).text( 'Nodes:' );
+ node_info.append( 'div' ).attr( 'class', 'right' ).text( mesh.num_nodes().toLocaleString() );
+
+ var element_info = mesh_info
+ .append( 'div' )
+ .attr( 'class', 'two-col' );
+
+ element_info.append( 'div' ).attr( 'class', 'left' ).text( 'Elements:' );
+ element_info.append( 'div' ).attr( 'class', 'right' ).text( mesh.num_elements().toLocaleString() );
+
+ // Add the mesh datasets header
+ mesh_data_section
+ .append( 'div' )
+ .attr( 'class', 'header' )
+ .text( 'Mesh Data' );
+
+ // Initialize display of mesh datasets
+ initialize_mesh_datasets( mesh_data_section.append( 'div' ).attr( 'class', 'item' ), data );
+
+ // Add the fort.63 button
+ var fort63_item = mesh_data_section.append( 'div' )
+ .attr( 'class', 'item' );
+
+ var fort63 = fort63_item.append( 'div' )
+ .attr( 'class', 'button bordered' )
+ .text( 'Open fort.63' );
+
+ adcirc.button().file_picker( function ( file ) {
+
+ // Remove the fort.63 button
+ fort63.remove();
+
+ // Create load bar
+ var progress = adcirc.progress();
+
+ // Add load bar
+ progress( fort63_item.append( 'div' ) );
+
+ // Respond to events
+ data.on( 'progress', update_progress );
+
+ data.once( 'finish', function ( event ) {
+
+ data.off( 'progress', update_progress );
+
+ fort63_item.remove();
+
+ });
+
+ data.once( 'ready', function () {
+
+ show_timeseries_controls( timeseries_section );
+
+ });
+
+ data.on( 'timestep', function ( event ) {
+
+ ts_view.timestep( event );
+ display_options.bounds( event.bounds );
+
+ });
+
+ // Repond to keyboard events
+ d3.select( 'body' ).on( 'keydown', function () {
+
+ switch ( d3.event.key ) {
+
+ case 'ArrowRight':
+ data.next_timestep();
+ break;
+
+ case 'ArrowLeft':
+ data.previous_timestep();
+ break;
+
+ }
+
+ });
+
+ data.load_fort_63( file );
+
+ // Progress bar update function
+ function update_progress ( event ) {
+
+ progress.progress( event.progress );
+
+ }
+
+ })( fort63 );
+
+ // Add the display options
+ display_options( display_options_section );
+
+}
+
+function initialize_mesh_datasets ( selection, data ) {
+
+ fields = selection;
+
+ data.on( 'view', function ( event ) {
+
+ // Tell the renderer to render the view
+ renderer.set_view( event.view );
+ renderer.render();
+
+ // Tell the display options to show the gradient
+ display_options.view( event.view );
+
+ });
+
+ data.on( 'new_view', function ( event ) {
+
+ // Add the field to the list of mesh data
+ var field = new_field( event.name );
+
+ // When depth is loaded for the first time, display it
+ if ( event.name == 'depth' ) {
+
+ pick_field( 'depth' );
+ data.view( 'depth' );
+
+ }
+
+ // Respond to field clicks
+ field.on( 'click', function ( d ) {
+
+ pick_field( d );
+ data.view( d );
+
+ } );
+
+ });
+
+}
+
+function show_timeseries_controls ( sidebar ) {
+
+ // if ( !ts_selection ) ts_selection = sidebar.append( 'div' ).attr( 'class', 'item' );
+ ts_view( sidebar );
+
+}
+
+function new_field ( name ) {
+
+ // Full size clickable item
+ var field = fields.append( 'div' )
+ .attr( 'class', 'two-col clickable' )
+ .data( [ name ] );
+
+ // Left column has field name
+ field.append( 'div' ).attr( 'class', 'left' ).text( upper( name ) );
+
+ // Right column has eyeball
+ field.append( 'div' ).attr( 'class', 'right' )
+ .append( 'i' ).attr( 'class', 'fa fa-fw fa-eye' );
+
+ return field;
+
+}
+
+function pick_field ( name ) {
+
+ fields.selectAll( '.clickable' ).each( function ( d ) {
+
+ var field = d3.select( this );
+
+ if ( d === name ) {
+
+ field.selectAll( '.right' ).style( 'color', 'limegreen' );
+
+
+ } else {
+
+ field.selectAll( '.right' ).style( 'color', null );
+
+ }
+
+ });
+
+}
+
+function upper ( string ) {
+
+ return string.replace( /\b\w/g, function ( l ) { return l.toUpperCase() } );
+
+}
+
+// var elemental_values = d3.select( '#elemental_values' );
+// var nodal_values = d3.select( '#nodal_values' );
+// var num_nodes = d3.select( '#num-nodes' );
+// var num_elements = d3.select( '#num-elements' );
+// var bounding_box = d3.select( '#bounding-box' );
+//
+// // Set up data views
+// var initialized = false;
+// var view_mesh = mesh_view()
+// .elemental_values( elemental_values )
+// .nodal_values( nodal_values )
+// .num_nodes( num_nodes )
+// .num_elements( num_elements )
+// .bounding_box( bounding_box );
+//
+// // There'll only be a single dataset to begin with
+// var data = dataset( renderer.gl_context() );
+// var mesh = data.mesh();
+//
+// // Set up file pickers
+// ui.fort14.file_picker( data.load_fort_14 );
+// ui.fort63.file_picker( data.load_fort_63 );
+// ui.residuals.file_picker( data.load_residuals );
+//
+// // Set up gradient slider
+// ui.colorbar.on( 'gradient', data.gradient );
+//
+// // Connect the views to the data
+// view_mesh( data.mesh() );
+//
+// // Respond to events from the mesh
+// mesh.on( 'bounding_box', function () {
+//
+// if ( !initialized ) {
+//
+// renderer.zoom_to( mesh, 200 );
+// initialized = true;
+//
+// }
+//
+// });
+//
+// // Respond to events from the dataset
+// data.on( 'has_view', function ( event ) {
+//
+// renderer.add_view( event.view );
+//
+// });
+//
+// data.on( 'progress', function ( event ) {
+//
+// ui.progress.progress( event.progress );
+//
+// });
+//
+// data.on( 'gradient', function ( event ) {
+//
+// ui.colorbar.stops( event.values, event.colors );
+//
+// });
+//
+// data.on( 'render', renderer.render );
+//
+// // Respond to events from views
+// view_mesh.on( 'nodal_value', function ( event ) {
+//
+// data.view( event.nodal_value );
+//
+// });
+//
+// view_mesh.on( 'elemental_value', function ( event ) {
+//
+// data.view( event.elemental_value );
+//
+// });
+//
+// // Repond to keyboard events
+// d3.select( 'body' ).on( 'keydown', function () {
+//
+// switch ( d3.event.key ) {
+//
+// case 'ArrowRight':
+// data.next_timestep();
+// break;
+//
+// case 'ArrowLeft':
+// data.previous_timestep();
+// break;
+//
+// }
+//
+// });
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068731_form.js b/pool/shard010/JavaScript/0068731_form.js
new file mode 100644
index 0000000000000000000000000000000000000000..11381f4966140560b8d1fc22c1a3de20723044e4
--- /dev/null
+++ b/pool/shard010/JavaScript/0068731_form.js
@@ -0,0 +1,88 @@
+import React, { Component, Children, cloneElement } from 'react';
+import { type } from './';
+
+class Form extends Component {
+ constructor() {
+ super();
+ this.state = {
+ inputs: {}
+ };
+ }
+ renderChildren() {
+ const { children, onSubmit } = this.props;
+ return Children
+ .map(children, (child) => {
+ const childComponent = type({ function: child.type })
+ ? child.type(child.props)
+ : child;
+ // console.log('childComponent: ', childComponent);
+
+
+ if (childComponent.type === 'input') {
+ // console.log('input type: ', childComponent.props);
+ const name = childComponent.props.name;
+ // console.log('component name: ', name);
+ return cloneElement(
+ childComponent,
+ {
+ ...childComponent.props,
+ onChange: (ev) => {
+ childComponent.props.onChange && childComponent.props.onChange(ev);
+ this.handleChange(ev);
+ },
+ // value: this.state.inputs[name],
+ 'data-name': name
+ }
+ );
+ }
+ if (childComponent.props.type === 'submit') {
+ const stdOnClick = childComponent.props.onClick;
+ const onClick = (ev) => {
+ ev.preventDefault();
+ stdOnClick && stdOnClick(ev);
+ onSubmit(this.state.inputs);
+ this.setState({ inputs: {} });
+ };
+ // console.log('submit button: ', child);
+ return cloneElement(
+ childComponent,
+ {
+ ...childComponent.props,
+ onClick
+ }
+ );
+ }
+ return childComponent;
+ });
+ }
+ handleSubmit = (ev) => {
+ // send all input
+ console.log('Form handleSubmit: ', ev.target);
+ this.props.onSubmit(this.state.inputs);
+ }
+ handleChange = (ev) => {
+ const { checked, value, dataset } = ev.target;
+ console.log('checked: %o, value: %o, dataset: %o', checked, value, dataset);
+ const inputVal = checked || value;
+ const inputName = dataset.name;
+ const inputs = this.state.inputs;
+ inputs[inputName] = inputVal;
+ this.setState({ inputs });
+ }
+ render() {
+ const { className } = this.props;
+ return (
+
+ );
+ }
+}
+
+Form.propTypes = {
+ className: React.PropTypes.string,
+ children: React.PropTypes.element,
+ onSubmit: React.PropTypes.func.isRequired
+};
+
+export default Form;
diff --git a/pool/shard010/JavaScript/0068736_DisputeForm.js b/pool/shard010/JavaScript/0068736_DisputeForm.js
new file mode 100644
index 0000000000000000000000000000000000000000..c395324ef491616ebf7ea060feb77636afd1103f
--- /dev/null
+++ b/pool/shard010/JavaScript/0068736_DisputeForm.js
@@ -0,0 +1,49 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+import {connect} from 'react-redux';
+import {Panel} from 'react-bootstrap';
+import {RichText, Msg} from '../containers';
+import {EmailField, TextField, CaptchaForm, TextAreaField, SelectOption, SelectField} from '../containers/form';
+import formstatus from '../formstatus';
+import {FORM} from './constants';
+import {dispute} from './actions';
+import {getDetail} from './selectors';
+
+const DisputeForm = ({advocateFinal, resultFinal}) => (
+ }>
+
+
+
+
+
+ {resultFinal || }
+ {advocateFinal || }
+ {resultFinal || advocateFinal || }
+ {advocateFinal && }
+ {resultFinal && }
+
+
+
+
+
+
+);
+
+DisputeForm.propTypes = {
+ advocateFinal: PropTypes.bool.isRequired,
+ resultFinal: PropTypes.bool.isRequired,
+};
+
+const mapStateToProps = (state) => {
+ const detail = getDetail(state);
+ return {
+ advocateFinal: detail.advocateFinal,
+ resultFinal: detail.resultFinal,
+ };
+};
+
+export default connect(mapStateToProps)(DisputeForm);
diff --git a/pool/shard010/JavaScript/0068738_regress-452498-178.js b/pool/shard010/JavaScript/0068738_regress-452498-178.js
new file mode 100644
index 0000000000000000000000000000000000000000..3a8ac8df3c58729e41a71e46037ca1503570297e
--- /dev/null
+++ b/pool/shard010/JavaScript/0068738_regress-452498-178.js
@@ -0,0 +1,63 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is JavaScript Engine testing utilities.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2008
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s): Gary Kwong
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+//-----------------------------------------------------------------------------
+var BUGNUMBER = 452498;
+var summary = 'TM: upvar2 regression tests';
+var actual = '';
+var expect = '';
+
+//------- Comment #178 From Gary Kwong
+
+//-----------------------------------------------------------------------------
+test();
+//-----------------------------------------------------------------------------
+
+function test()
+{
+ enterFunc ('test');
+ printBugNumber(BUGNUMBER);
+ printStatus (summary);
+
+// Assertion failure: slot < fp2->script->nfixed, at ../jsinterp.cpp:5610
+
+ eval("with({}) let(x=[])(function(){#2=x})()");
+
+ reportCompare(expect, actual, summary);
+
+ exitFunc ('test');
+}
diff --git a/pool/shard010/JavaScript/0068739_measurements_table.js b/pool/shard010/JavaScript/0068739_measurements_table.js
new file mode 100644
index 0000000000000000000000000000000000000000..dd0dcaaf17f9fbcf3c8728ff29b02227bad7dacc
--- /dev/null
+++ b/pool/shard010/JavaScript/0068739_measurements_table.js
@@ -0,0 +1,234 @@
+/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */
+/* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */
+/* global
+ fetchSkeletons,
+ InstanceRegistry,
+ project,
+*/
+
+(function(CATMAID) {
+
+ "use strict";
+
+ var SkeletonMeasurementsTable = function() {
+ this.widgetID = this.registerInstance();
+ this.registerSource();
+ this.table = null;
+ this.models = {};
+ this.sigma = 200;
+ };
+
+ SkeletonMeasurementsTable.prototype = {};
+ $.extend(SkeletonMeasurementsTable.prototype, new InstanceRegistry());
+ $.extend(SkeletonMeasurementsTable.prototype, new CATMAID.SkeletonSource());
+
+ SkeletonMeasurementsTable.prototype.labels = ['Neuron', 'Skeleton', 'Raw cable (nm)', 'Smooth cable (nm)', 'Lower-bound cable (nm)', 'N inputs', 'N outputs', 'N presynaptic sites', 'N nodes', 'N branch nodes', 'N end nodes'];
+
+ SkeletonMeasurementsTable.prototype.getName = function() {
+ return "Measurements " + this.widgetID;
+ };
+
+ SkeletonMeasurementsTable.prototype.destroy = function() {
+ this.clear();
+ this.table = null;
+ this.unregisterInstance();
+ this.unregisterSource();
+ CATMAID.NeuronNameService.getInstance().unregister(this);
+ };
+
+ SkeletonMeasurementsTable.prototype.append = function(models) {
+ // Update models and find out which ones are missing
+ var new_models = {};
+ Object.keys(models).forEach(function(skid) {
+ var model = models[skid];
+ if (this.models.hasOwnProperty(skid)) this.models[skid] = model;
+ else {
+ new_models[skid] = model;
+ this.models[skid] = model;
+ }
+ }, this);
+
+ if (0 === Object.keys(new_models).length) return;
+
+ CATMAID.NeuronNameService.getInstance().registerAll(this, new_models,
+ (function() {
+ this.load(new_models, this.sigma, this.table.fnAddData.bind(this.table));
+ }).bind(this));
+ };
+
+ SkeletonMeasurementsTable.prototype.load = function(models, sigma, fnDone) {
+ var rows = [],
+ failed = [];
+
+ fetchSkeletons(
+ Object.keys(models).map(Number),
+ function(skid) {
+ return django_url + project.id + '/' + skid + '/1/1/0/compact-arbor';
+ },
+ function(skid) { return {}; },
+ function(skid, json) {
+ var ap = new CATMAID.ArborParser().init('compact-arbor', json),
+ arbor = ap.arbor,
+ positions = ap.positions,
+ raw_cable = Math.round(arbor.cableLength(positions)) | 0,
+ smooth_cable = Math.round(arbor.smoothCableLength(positions, sigma)) | 0,
+ lower_bound_cable = Math.round(arbor.topologicalCopy().cableLength(positions)) | 0,
+ n_presynaptic_sites = ap.n_output_connectors,
+ n_outputs = ap.n_outputs,
+ n_inputs = ap.n_inputs,
+ n_nodes = arbor.countNodes(),
+ be = arbor.findBranchAndEndNodes(),
+ n_branching = be.n_branches,
+ n_ends = be.ends.length;
+ var name = CATMAID.NeuronNameService.getInstance().getName(skid);
+ rows.push([SkeletonMeasurementsTable.prototype._makeStringLink(name, skid), skid,
+ raw_cable, smooth_cable, lower_bound_cable,
+ n_inputs, n_outputs, n_presynaptic_sites,
+ n_nodes, n_branching, n_ends]);
+ },
+ function(skid) {
+ failed.push(skid);
+ },
+ function() {
+ fnDone(rows);
+ if (failed.length > 0) {
+ alert("Skeletons that failed to load: " + failed);
+ }
+ });
+ };
+
+ SkeletonMeasurementsTable.prototype._makeStringLink = function(name, skid) {
+ return '' + name + ' ';
+ };
+
+ SkeletonMeasurementsTable.prototype.clear = function() {
+ if (!this.table) return;
+ this.models = {};
+ this.table.fnClearTable();
+ };
+
+ SkeletonMeasurementsTable.prototype.removeSkeletons = function(skids) {
+ var to_remove = skids.reduce((function(o, skid) {
+ if (this.models.hasOwnProperty(skid)) {
+ o[skid] = true;
+ delete this.models[skid];
+ }
+ return o;
+ }).bind(this), {});
+
+ if (0 === Object.keys(to_remove).length) return;
+
+ var rows = this.table.fnGetData().filter(function(row) {
+ return !to_remove.hasOwnProperty(row[1]);
+ });
+
+ this.table.fnClearTable();
+ if (rows.length > 0) {
+ this.table.fnAddData(rows);
+ }
+ };
+
+ SkeletonMeasurementsTable.prototype.update = function() {
+ var models = this.models;
+ this.clear();
+ this.append(models);
+ };
+
+ SkeletonMeasurementsTable.prototype.updateModels = function(models) {
+ Object.keys(models).forEach(function(skid) {
+ if (this.models.hasOwnProperty(skid)) this.models[skid] = models[skid];
+ }, this);
+ };
+
+ SkeletonMeasurementsTable.prototype.getSkeletonColor = function(skid) {
+ var model = this.models[skid];
+ if (model) return model.color;
+ return new THREE.Color().setRGB(1, 0, 1);
+ };
+
+ SkeletonMeasurementsTable.prototype.hasSkeleton = function(skid) {
+ return this.models.hasOwnProperty(skid);
+ };
+
+ SkeletonMeasurementsTable.prototype.getSelectedSkeletonModels = function() {
+ return Object.keys(this.models).reduce((function(o, skid) {
+ o[skid] = this.models[skid].clone();
+ return o;
+ }).bind(this), {});
+ };
+
+ SkeletonMeasurementsTable.prototype.getSkeletonModels = SkeletonMeasurementsTable.prototype.getSelectedSkeletonModels;
+
+ SkeletonMeasurementsTable.prototype.getSkeletonModel = function( id ) {
+ if (id in this.models) {
+ return this.models[id].clone();
+ }
+ };
+
+ SkeletonMeasurementsTable.prototype.highlight = function(skid) {
+ // TODO
+ };
+
+ SkeletonMeasurementsTable.prototype.init = function() {
+ if (this.table) this.table.remove();
+
+ var n_labels = this.labels.length;
+
+ this.table = $('#skeleton_measurements_table' + this.widgetID).dataTable({
+ // http://www.datatables.net/usage/options
+ "bDestroy": true,
+ "sDom": '<"H"lr>t<"F"ip>',
+ // default: <"H"lfr>t<"F"ip>
+ "bProcessing": true,
+ "bServerSide": false, // Enable sorting locally, and prevent sorting from calling the fnServerData to reload the table -- an expensive and undesirable operation.
+ "bAutoWidth": false,
+ "iDisplayLength": -1,
+ "aLengthMenu": [
+ [-1, 10, 100, 200],
+ ["All", 10, 100, 200]
+ ],
+ //"aLengthChange": false,
+ "bJQueryUI": true,
+ "aoColumns": this.labels.map((function() { return this; }).bind({bSearchable: true, bSortable: true}))
+ });
+
+ // Remove default dummy row
+ this.table.fnClearTable();
+ };
+
+ SkeletonMeasurementsTable.prototype.updateNeuronNames = function() {
+ this.table.fnGetData().forEach(function(row, i) {
+ this.table.fnUpdate(this._makeStringLink(CATMAID.NeuronNameService.getInstance().getName(row[1]), row[1]), i, 0);
+ }, this);
+ };
+
+ SkeletonMeasurementsTable.prototype.adjustOptions = function() {
+ var od = new CATMAID.OptionsDialog("Parameters");
+ od.appendField("Smooth skeletons by Gaussian convolution with sigma (nm): ", "SMT-sigma-" + this.widgetID, this.sigma);
+ od.onOK = (function() {
+ var field = $('#SMT-sigma-' + this.widgetID);
+ try {
+ var sigma = parseInt(field.val()) | 0;
+ if (sigma < 0) return alert("Sigma must be larger than zero.");
+ this.sigma = sigma;
+ this.update();
+ } catch (e) {
+ alert("Invalid value for sigma: " + field.val());
+ }
+ }).bind(this);
+ od.show();
+ };
+
+ SkeletonMeasurementsTable.prototype.exportCSV = function() {
+ if (!this.table) return;
+ var csv = this.labels.join(',') + '\n' + this.table.fnGetData().map(function(row) {
+ return $(row[0]).text() + ',' + row.slice(1).join(',');
+ }).join('\n'),
+ blob = new Blob([csv], {type: 'text/plain'});
+ saveAs(blob, "skeleton_measurements.csv");
+ };
+
+ // Make measurement table available in CATMAID namespace
+ CATMAID.SkeletonMeasurementsTable = SkeletonMeasurementsTable;
+
+})(CATMAID);
diff --git a/pool/shard010/JavaScript/0068743_selection.js b/pool/shard010/JavaScript/0068743_selection.js
new file mode 100644
index 0000000000000000000000000000000000000000..ca0e612df5476c1387a056e7e21710600866125a
--- /dev/null
+++ b/pool/shard010/JavaScript/0068743_selection.js
@@ -0,0 +1,99 @@
+c3_chart_internal_fn.selectPoint = function C3_INTERNAL_selectPoint(target, d, i) {
+ var $$ = this,
+ config = $$.config,
+ cx = (config.axis_rotated ? $$.circleY : $$.circleX).bind($$),
+ cy = (config.axis_rotated ? $$.circleX : $$.circleY).bind($$),
+ r = $$.pointSelectR.bind($$);
+ config.data_onselected.call($$.api, d, target.node());
+ // add selected-circle on low layer g
+ $$.main.select('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i)
+ .data([d])
+ .enter().append('circle')
+ .attr("class", function () {
+ return $$.generateClass(CLASS.selectedCircle, i);
+ })
+ .attr("cx", cx)
+ .attr("cy", cy)
+ .attr("stroke", function () {
+ return $$.color(d);
+ })
+ .attr("r", function (d) {
+ return $$.pointSelectR(d) * 1.4;
+ })
+ .transition().duration(100)
+ .attr("r", r);
+};
+c3_chart_internal_fn.unselectPoint = function C3_INTERNAL_unselectPoint(target, d, i) {
+ var $$ = this;
+ $$.config.data_onunselected.call($$.api, d, target.node());
+ // remove selected-circle from low layer g
+ $$.main.select('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i)
+ .transition().duration(100).attr('r', 0)
+ .remove();
+};
+c3_chart_internal_fn.togglePoint = function C3_INTERNAL_togglePoint(selected, target, d, i) {
+ if (selected) {
+ this.selectPoint(target, d, i);
+ } else {
+ this.unselectPoint(target, d, i);
+ }
+};
+c3_chart_internal_fn.selectPath = function C3_INTERNAL_selectPath(target, d) {
+ var $$ = this;
+ $$.config.data_onselected.call($$, d, target.node());
+ if ($$.config.interaction_brighten) {
+ target.transition().duration(100)
+ .style("fill", function () {
+ return $$.d3.rgb($$.color(d)).brighter(0.75);
+ });
+ }
+};
+c3_chart_internal_fn.unselectPath = function C3_INTERNAL_unselectPath(target, d) {
+ var $$ = this;
+ $$.config.data_onunselected.call($$, d, target.node());
+ if ($$.config.interaction_brighten) {
+ target.transition().duration(100)
+ .style("fill", function () {
+ return $$.color(d);
+ });
+ }
+};
+c3_chart_internal_fn.togglePath = function C3_INTERNAL_togglePath(selected, target, d, i) {
+ selected ? this.selectPath(target, d, i) : this.unselectPath(target, d, i);
+};
+c3_chart_internal_fn.getToggle = function C3_INTERNAL_getToggle(that, d) {
+ var $$ = this, toggle;
+ if (that.nodeName === 'circle') {
+ if ($$.isStepType(d)) {
+ // circle is hidden in step chart, so treat as within the click area
+ toggle = function () {}; // TODO: how to select step chart?
+ } else {
+ toggle = $$.togglePoint;
+ }
+ }
+ else if (that.nodeName === 'path') {
+ toggle = $$.togglePath;
+ }
+ return toggle;
+};
+c3_chart_internal_fn.toggleShape = function C3_INTERNAL_toggleShape(that, d, i) {
+ var $$ = this,
+ d3 = $$.d3,
+ config = $$.config,
+ shape = d3.select(that),
+ isSelected = shape.classed(CLASS.SELECTED),
+ toggle = $$.getToggle(that, d).bind($$);
+
+ if (config.data_selection_enabled && config.data_selection_isselectable(d)) {
+ if (!config.data_selection_multiple) {
+ $$.main.selectAll('.' + CLASS.shapes + (config.data_selection_grouped ? $$.getTargetSelectorSuffix(d.id) : "")).selectAll('.' + CLASS.shape).each(function (d, i) {
+ var shape = d3.select(this);
+ if (shape.classed(CLASS.SELECTED)) {
+ toggle(false, shape.classed(CLASS.SELECTED, false), d, i);
+ }
+ });
+ }
+ shape.classed(CLASS.SELECTED, !isSelected);
+ toggle(!isSelected, shape, d, i);
+ }
+};
diff --git a/pool/shard010/JavaScript/0068752_aui-property-builder-settings.js b/pool/shard010/JavaScript/0068752_aui-property-builder-settings.js
new file mode 100644
index 0000000000000000000000000000000000000000..2e5dd185ad6e5a67d033a3fbccdbe0157b4cc045
--- /dev/null
+++ b/pool/shard010/JavaScript/0068752_aui-property-builder-settings.js
@@ -0,0 +1,348 @@
+YUI.add('aui-property-builder-settings', function (A, NAME) {
+
+var PropertyBuilderSettings;
+
+/**
+ * A base class for `A.PropertyBuilderSettings`.
+ *
+ * @class A.PropertyBuilderSettings
+ * @constructor
+ */
+var PropertyBuilderSettings = function() {},
+ CSS_PROPERTY_BUILDER_TABS = A.getClassName('property', 'builder', 'tabs'),
+ CSS_PROPERTY_BUILDER_TOOLBAR_CONTAINER = A.getClassName('property', 'builder', 'toolbar', 'container'),
+ CSS_TABBABLE = A.getClassName('tabbable'),
+ CSS_TABBABLE_CONTENT = A.getClassName('tabbable', 'content'),
+ CSS_TABLE_STRIPED = A.getClassName('table', 'striped');
+
+/**
+ * Static property used to define the default attribute
+ * configuration for the `A.PropertyBuilderSettings`.
+ *
+ * @property ATTRS
+ * @type Object
+ * @static
+ */
+PropertyBuilderSettings.ATTRS = {
+ /**
+ * Stores an instance of `A.PropertyList`.
+ *
+ * @attribute propertyList
+ * @default null
+ * @type Object
+ */
+ propertyList: {
+ setter: '_setPropertyList',
+ validator: A.Lang.isObject,
+ value: null
+ },
+
+ /**
+ * Stores an instance of `A.TabView`.
+ *
+ * @attribute tabView
+ * @default null
+ * @type Object
+ * @writeOnce
+ */
+ tabView: {
+ setter: '_setTabView',
+ validator: A.Lang.isObject,
+ value: null,
+ writeOnce: true
+ },
+
+ /**
+ * Stores an instance of `A.Toolbar`.
+ *
+ * @attribute toolbar
+ * @default null
+ * @type Object
+ */
+ toolbar: {
+ setter: '_setToolbar',
+ validator: A.Lang.isObject,
+ value: null
+ },
+
+ /**
+ * Host node for toolbar created using the `TOOLBAR_CONTAINER_TEMPLATE`
+ * template.
+ *
+ * @attribute toolbarContainer
+ */
+ toolbarContainer: {
+ valueFn: function() {
+ return A.Node.create(this.TOOLBAR_CONTAINER_TEMPLATE);
+ }
+ }
+};
+
+/**
+ * Object hash, defining how attribute values have to be parsed from markup.
+ *
+ * @property HTML_PARSER
+ * @type Object
+ * @extends A.PropertyBuilder.HTML_PARSER
+ * @static
+ */
+PropertyBuilderSettings.HTML_PARSER = {
+ toolbarContainer: '.' + CSS_PROPERTY_BUILDER_TOOLBAR_CONTAINER
+};
+
+A.mix(PropertyBuilderSettings.prototype, {
+ TOOLBAR_CONTAINER_TEMPLATE: '
',
+
+ propertyList: null,
+
+ settingsNode: null,
+
+ tabView: null,
+
+ toolbar: null,
+
+ initializer: function() {
+ this.publish({
+ cancel: {
+ defaultFn: this._defCancelFn
+ }
+ });
+
+ this.on('render', function() {
+ this._renderTabs();
+ });
+ },
+
+ /**
+ * Fires after one or more attributes on the model are changed.
+ *
+ * @method _afterModelChange
+ * @param event
+ * @protected
+ */
+ _afterModelChange: function() {
+ var instance = this;
+
+ instance._handleSaveEvent();
+ },
+
+ /**
+ * Fires after `tabView` selection change.
+ *
+ * @method _afterSelectionChange
+ * @param event
+ * @protected
+ */
+ _afterSelectionChange: function(event) {
+ var instance = this,
+ tabview = event.newVal,
+ tabNode;
+
+ if (tabview) {
+ tabNode = tabview.get('panelNode');
+
+ if (instance.get('rendered') && (tabNode === instance.settingsNode)) {
+ instance._renderSettings();
+ }
+ }
+ },
+
+ /**
+ * Selects the `tabView` child at index zero.
+ *
+ * @method _defCancelFn
+ * @param event
+ * @protected
+ */
+ _defCancelFn: function() {
+ var instance = this;
+
+ instance.tabView.selectChild(0);
+ },
+
+ /**
+ * Fires a cancel event.
+ *
+ * @method _handleCancelEvent
+ * @protected
+ */
+ _handleCancelEvent: function() {
+ var instance = this;
+
+ instance.fire('cancel');
+ },
+
+ /**
+ * Fires a save event.
+ *
+ * @method _handleSaveEvent
+ * @protected
+ */
+ _handleSaveEvent: function() {
+ var instance = this;
+
+ instance.fire('save');
+ },
+
+ /**
+ * Creates an instance of `A.PropertyList` in `propertyList` attribute
+ * and renders it.
+ *
+ * @method _renderPropertyList
+ * @protected
+ */
+ _renderPropertyList: function() {
+ var instance = this;
+
+ if (!instance.propertyList) {
+ var propertyList = instance.propertyList = new A.PropertyList(instance.get('propertyList'));
+
+ propertyList.render(instance.settingsNode);
+
+ propertyList.get('boundingBox').unselectable().addClass(CSS_TABLE_STRIPED);
+ }
+ },
+
+ /**
+ * Calls the `_renderPropertyList` and `_renderToolbar` functions.
+ *
+ * @method _renderSettings
+ * @protected
+ */
+ _renderSettings: function() {
+ var instance = this;
+
+ instance._renderPropertyList();
+
+ instance._renderToolbar();
+ },
+
+ /**
+ * Creates an instance of `A.TabView` in `tabView` attribute.
+ *
+ * @method _renderTabs
+ * @protected
+ */
+ _renderTabs: function() {
+ var instance = this;
+
+ if (!instance.tabView) {
+ var tabView = new A.TabView(instance.get('tabView'));
+
+ instance.tabView = tabView;
+ instance.fieldsNode = tabView.item(0).get('panelNode');
+ instance.settingsNode = tabView.item(1).get('panelNode');
+ }
+ },
+
+ /**
+ * Creates an instance of `A.Toolbar` in `toolbar` attribute and renders
+ * it.
+ *
+ * @method _renderToolbar
+ * @protected
+ */
+ _renderToolbar: function() {
+ var instance = this;
+
+ if (!instance.toolbar) {
+ instance.toolbar = new A.Toolbar(
+ instance.get('toolbar')
+ ).render(instance.settingsNode);
+ }
+ },
+
+ /**
+ * Sets the `propertyList` attribute.
+ *
+ * @method _setPropertyList
+ * @param val
+ * @protected
+ */
+ _setPropertyList: function(val) {
+ var instance = this;
+
+ return A.merge({
+ bubbleTargets: instance,
+ scroll: {
+ height: 400,
+ width: 'auto'
+ },
+ width: '99%'
+ },
+ val
+ );
+ },
+
+ /**
+ * Sets the `tabView` attribute.
+ *
+ * @method _setTabView
+ * @param val
+ * @protected
+ */
+ _setTabView: function(val) {
+ var instance = this,
+ boundingBox = instance.get('boundingBox'),
+ tabViewContentNode = boundingBox.one('.' + CSS_TABBABLE_CONTENT),
+ defaultValue;
+
+ defaultValue = {
+ after: {
+ selectionChange: A.bind(instance._afterSelectionChange, instance)
+ },
+ boundingBox: boundingBox.one('.' + CSS_TABBABLE),
+ bubbleTargets: instance,
+ cssClass: CSS_PROPERTY_BUILDER_TABS,
+ render: instance.get('contentBox'),
+ srcNode: tabViewContentNode
+ };
+
+ if (!tabViewContentNode) {
+ var strings = instance.getStrings();
+
+ defaultValue.children = [
+ {
+ label: strings.addNode
+ },
+ {
+ label: strings.settings,
+ disabled: true
+ }
+ ];
+ }
+
+ return A.merge(defaultValue, val);
+ },
+
+ /**
+ * Sets the `toolbar` attribute.
+ *
+ * @method _setToolbar
+ * @param val
+ * @protected
+ */
+ _setToolbar: function(val) {
+ var instance = this;
+ var strings = instance.getStrings();
+
+ return A.merge({
+ bubbleTargets: instance,
+ children: [
+ {
+ on: {
+ click: A.bind(instance._handleCancelEvent, instance)
+ },
+ label: strings.close
+ }
+ ]
+ },
+ val
+ );
+ }
+});
+
+A.PropertyBuilderSettings = PropertyBuilderSettings;
+
+
+}, '3.0.0pr1', {"requires": ["aui-tabview", "aui-datatable-property-list"]});
diff --git a/pool/shard010/JavaScript/0068754_tcp_disable.js b/pool/shard010/JavaScript/0068754_tcp_disable.js
new file mode 100644
index 0000000000000000000000000000000000000000..2aa7c237f1c200579bb906d393147cc18a2295ca
--- /dev/null
+++ b/pool/shard010/JavaScript/0068754_tcp_disable.js
@@ -0,0 +1,31 @@
+var sip = require('sip');
+var util = require('sys');
+
+sip.start({
+ logger: {
+ send: function(m) { util.debug("send " + util.inspect(arguments, null, null)); },
+ recv: function(m) { util.debug("recv " + util.inspect(m, null, null)); },
+ error: function() { util.debug('error ' + util.inspect(arguments, null, null)); }
+ },
+ tcp: false
+},
+function(rq) {
+ util.debug("rq\n" + util.inspect(rq, null, null));
+});
+
+sip.send({
+ method: 'INVITE',
+ uri: 'sip:123@cnn.com',
+ headers: {
+ cseq: { method: 'INVITE', seq: 1},
+ to: { uri: 'sip:test'},
+ from: { uri: 'sip:test', params: { branch: 123 } },
+ 'call-id': 'xxxxx',
+ 'content-length': 0
+ }
+ },
+ function(rs) {
+ util.debug('response ' + util.inspect(rs, null, null));
+ }
+);
+
diff --git a/pool/shard010/JavaScript/0068756_cli.js b/pool/shard010/JavaScript/0068756_cli.js
new file mode 100644
index 0000000000000000000000000000000000000000..f481b095eca67670271bbf5064f132603e1d5c62
--- /dev/null
+++ b/pool/shard010/JavaScript/0068756_cli.js
@@ -0,0 +1,56 @@
+#!/usr/bin/env node
+
+'use strict'
+
+var semver = require('semver')
+if (semver.lt(process.versions.node, '4.0.0')) {
+ console.error('CANNOT RUN WITH NODE ' + process.versions.node)
+ console.error('Electron Packager requires Node 4.0 or above.')
+ process.exit(1)
+}
+
+// Not consts so that this file can load in Node < 4.0
+var common = require('./common')
+var fs = require('fs')
+var packager = require('./')
+var path = require('path')
+var usage = fs.readFileSync(path.join(__dirname, 'usage.txt')).toString()
+
+var args = common.parseCLIArgs(process.argv.slice(2))
+
+// temporary fix for https://github.com/nodejs/node/issues/6456
+var stdioWriters = [process.stdout, process.stderr]
+stdioWriters.forEach(function (stdioWriter) {
+ if (stdioWriter._handle && stdioWriter._handle.setBlocking) {
+ stdioWriter._handle.setBlocking(true)
+ }
+})
+
+function printUsageAndExit (isError) {
+ var print = isError ? console.error : console.log
+ print(usage)
+ process.exit(isError ? 1 : 0)
+}
+
+if (args.help) {
+ printUsageAndExit(false)
+} else if (args.version) {
+ if (typeof args.version !== 'boolean') {
+ console.error('--version does not take an argument. Perhaps you meant --app-version or --electron-version?\n')
+ }
+ console.log(common.hostInfo())
+ process.exit(0)
+} else if (!args.dir) {
+ printUsageAndExit(true)
+}
+
+packager(args)
+ .then(function done (appPaths) {
+ if (appPaths.length > 1) console.error('Wrote new apps to:\n' + appPaths.join('\n'))
+ else if (appPaths.length === 1) console.error('Wrote new app to', appPaths[0])
+ return true
+ }).catch(function error (err) {
+ if (err.message) console.error(err.message)
+ else console.error(err, err.stack)
+ process.exit(1)
+ })
diff --git a/pool/shard010/JavaScript/0068759_test_popups.js b/pool/shard010/JavaScript/0068759_test_popups.js
new file mode 100644
index 0000000000000000000000000000000000000000..9d299563fcb2eccf7f4a41680354b8c1c2a863e6
--- /dev/null
+++ b/pool/shard010/JavaScript/0068759_test_popups.js
@@ -0,0 +1,179 @@
+odoo.define('point_of_sale.test_popups', function(require) {
+ 'use strict';
+
+ const Registries = require('point_of_sale.Registries');
+ const testUtils = require('web.test_utils');
+ const PosComponent = require('point_of_sale.PosComponent');
+ const PopupControllerMixin = require('point_of_sale.PopupControllerMixin');
+ const makePosTestEnv = require('point_of_sale.test_env');
+ const { xml } = owl.tags;
+
+ QUnit.module('unit tests for Popups', {
+ before() {
+ class Root extends PopupControllerMixin(PosComponent) { }
+ Root.template = xml`
+
+
+
+ `;
+ Root.env = makePosTestEnv();
+ this.Root = Root;
+ Registries.Component.freeze();
+ },
+ });
+
+ QUnit.test('ConfirmPopup', async function(assert) {
+ assert.expect(6);
+
+ const root = new this.Root();
+ await root.mount(testUtils.prepareTarget());
+
+ let promResponse, userResponse;
+
+ // Step: show popup and confirm
+ promResponse = root.showPopup('ConfirmPopup', {});
+ await testUtils.nextTick();
+ testUtils.dom.click(root.el.querySelector('.confirm'));
+ await testUtils.nextTick();
+ userResponse = await promResponse;
+ assert.strictEqual(userResponse.confirmed, true);
+
+ // Step: show popup then cancel
+ promResponse = root.showPopup('ConfirmPopup', {});
+ await testUtils.nextTick();
+ testUtils.dom.click(root.el.querySelector('.cancel'));
+ await testUtils.nextTick();
+ userResponse = await promResponse;
+ assert.strictEqual(userResponse.confirmed, false);
+
+ // Step: check texts
+ promResponse = root.showPopup('ConfirmPopup', {
+ title: 'Are you sure?',
+ body: 'Are you having fun?',
+ confirmText: 'Hell Yeah!',
+ cancelText: 'Are you kidding me?',
+ });
+ await testUtils.nextTick();
+ assert.strictEqual(root.el.querySelector('.title').innerText.trim(), 'Are you sure?');
+ assert.strictEqual(root.el.querySelector('.body').innerText.trim(), 'Are you having fun?');
+ assert.strictEqual(root.el.querySelector('.confirm').innerText.trim(), 'Hell Yeah!');
+ assert.strictEqual(
+ root.el.querySelector('.cancel').innerText.trim(),
+ 'Are you kidding me?'
+ );
+
+ root.unmount();
+ root.destroy();
+ });
+
+ QUnit.test('NumberPopup', async function(assert) {
+ assert.expect(8);
+
+ const root = new this.Root();
+ await root.mount(testUtils.prepareTarget());
+
+ let promResponse, userResponse;
+
+ // Step: show NumberPopup and confirm with empty buffer
+ promResponse = root.showPopup('NumberPopup', { startingValue: 1 });
+ await testUtils.nextTick();
+ testUtils.dom.triggerEvent(root.el.querySelector('.confirm'), 'mousedown');
+ await testUtils.nextTick();
+ userResponse = await promResponse;
+ assert.strictEqual(userResponse.confirmed, true);
+ assert.strictEqual(userResponse.payload, "1");
+
+ // Step: show NumberPopup and cancel
+ promResponse = root.showPopup('NumberPopup', {});
+ await testUtils.nextTick();
+ testUtils.dom.triggerEvent(root.el.querySelector('.cancel'), 'mousedown');
+ await testUtils.nextTick();
+ userResponse = await promResponse;
+ assert.strictEqual(userResponse.confirmed, false);
+
+ // Step: show NumberPopup and confirm with filled buffer, new title, new text
+ promResponse = root.showPopup('NumberPopup', {
+ title: 'Are you sure?',
+ confirmText: 'Hell Yeah!',
+ cancelText: 'Are you kidding me?',
+ });
+ await testUtils.nextTick();
+ let nodes = Array.from(root.el.querySelectorAll('button'));
+ testUtils.dom.triggerEvent(nodes.find(elem => elem.innerHTML === "7"), 'mousedown');
+ await testUtils.nextTick();
+ testUtils.dom.triggerEvent(nodes.find(elem => elem.innerHTML === "+10"), 'mousedown');
+ await testUtils.nextTick();
+ assert.strictEqual(root.el.querySelector('.title').innerText.trim(), 'Are you sure?');
+ assert.strictEqual(root.el.querySelector('.confirm').innerText.trim(), 'Hell Yeah!');
+ assert.strictEqual(root.el.querySelector('.cancel').innerText.trim(), 'Are you kidding me?');
+ testUtils.dom.triggerEvent(root.el.querySelector('.confirm'), 'mousedown');
+ await testUtils.nextTick();
+ userResponse = await promResponse;
+ assert.strictEqual(userResponse.confirmed, true);
+ assert.strictEqual(userResponse.payload, "17");
+
+ root.unmount();
+ root.destroy();
+ });
+
+ QUnit.test('EditListPopup', async function(assert) {
+ assert.expect(7);
+
+ const root = new this.Root();
+ await root.mount(testUtils.prepareTarget());
+
+ let promResponse, userResponse;
+
+ // Step: show popup and confirm
+ promResponse = root.showPopup('EditListPopup', {});
+ await testUtils.nextTick();
+ testUtils.dom.click(root.el.querySelector('.confirm'));
+ await testUtils.nextTick();
+ userResponse = await promResponse;
+ assert.strictEqual(userResponse.confirmed, true);
+ assert.strictEqual(JSON.stringify(userResponse.payload.newArray), JSON.stringify([]));
+
+ // Step: show popup and cancel
+ promResponse = root.showPopup('EditListPopup', {});
+ await testUtils.nextTick();
+ testUtils.dom.click(root.el.querySelector('.cancel'));
+ await testUtils.nextTick();
+ userResponse = await promResponse;
+ assert.strictEqual(userResponse.confirmed, false);
+
+ // Step: show popup and confirm with a default array
+ let defaultArray = ["Banana", "Cherry"];
+ promResponse = root.showPopup('EditListPopup', {
+ title: "Fruits",
+ isSingleItem: false,
+ array: defaultArray,
+ });
+ await testUtils.nextTick();
+ testUtils.dom.click(root.el.querySelector('.confirm'));
+ await testUtils.nextTick();
+ userResponse = await promResponse;
+
+ assert.strictEqual(userResponse.confirmed, true);
+ let i = 0;
+ defaultArray = defaultArray.map((item) => Object.assign({}, { _id: i++ }, { 'text': item}));
+ assert.strictEqual(JSON.stringify(userResponse.payload.newArray), JSON.stringify(defaultArray));
+
+ // Step: show popup and confirm with a new array
+ promResponse = root.showPopup('EditListPopup', {
+ title: "Fruits",
+ isSingleItem: false,
+ array: ["Banana", "Cherry"],
+ });
+ await testUtils.nextTick();
+ testUtils.dom.click(root.el.querySelector('.fa-trash-o'));
+ await testUtils.nextTick();
+ testUtils.dom.click(root.el.querySelector('.confirm'));
+ await testUtils.nextTick();
+ userResponse = await promResponse;
+ assert.strictEqual(userResponse.confirmed, true);
+ assert.strictEqual(JSON.stringify(userResponse.payload.newArray), JSON.stringify([{ _id: 1, text: "Cherry"}]));
+
+ root.unmount();
+ root.destroy();
+ });
+});
diff --git a/pool/shard010/JavaScript/0068762_ErrorInfoSpec.js b/pool/shard010/JavaScript/0068762_ErrorInfoSpec.js
new file mode 100644
index 0000000000000000000000000000000000000000..deac215f64c84502b3f4d8c1712d81afc61303df
--- /dev/null
+++ b/pool/shard010/JavaScript/0068762_ErrorInfoSpec.js
@@ -0,0 +1,92 @@
+'use strict';
+var expect = require('chai').expect;
+var Engine = require('../src/index.js').Engine;
+
+var FutureValue = require('../src/values/FutureValue');
+var Value = require('../src/Value');
+
+
+describe('Extra Error Info', () => {
+ it('UndefinedVariable', () => {
+ try {
+ new Engine({strict: true, extraErrorInfo: true}).evalSync('var otherthing; console.log(something);');
+ expect(false).to.be.true;
+ } catch ( e ) {
+ expect(e.line).to.equal(1);
+ expect(e.code).to.equal('UndefinedVariable');
+ expect(e.when).to.equal('read');
+ expect(e.strict).to.be.true;
+ expect(e.candidates).to.contain('otherthing');
+ expect(e.ast.type).to.equal('Identifier');
+ }
+ });
+
+ it('CallNonFunction on Object', () => {
+ try {
+ new Engine({extraErrorInfo: true}).evalSync('var v = {a: function() {}, b:1};\nconsole.log(v.c());');
+ expect(false).to.be.true;
+ } catch ( e ) {
+ expect(e.line).to.equal(2);
+ expect(e.code).to.equal('CallNonFunction');
+ expect(e.candidates).to.contain('a');
+ expect(e.candidates).to.not.contain('b');
+ expect(e.ast.type).to.equal('CallExpression');
+ }
+ });
+
+ it('CallNonFunction on Link', () => {
+ try {
+ var e = new Engine({extraErrorInfo: true});
+ e.addGlobal('rob', {a: 10, b: function() {}});
+ e.evalSync('console.log(rob.c());');
+ expect(false).to.be.true;
+ } catch ( e ) {
+ expect(e.line).to.equal(1);
+ expect(e.code).to.equal('CallNonFunction');
+ expect(e.candidates).to.contain('b');
+ expect(e.candidates).to.not.contain('a');
+ expect(e.ast.type).to.equal('CallExpression');
+ }
+ });
+
+ it('CallNonFunction on SmartLink', () => {
+ try {
+ var e = new Engine({extraErrorInfo: true, foreignObjectMode: 'smart'});
+ e.addGlobal('rob', {a: 10, b: function() {}, c: function() {}, apiMethods: ['c']});
+ e.evalSync('console.log(rob.d());');
+ expect(false).to.be.true;
+ } catch ( e ) {
+ expect(e.line).to.equal(1);
+ expect(e.code).to.equal('CallNonFunction');
+ expect(e.candidates).to.contain('c');
+ expect(e.candidates).to.not.contain('b');
+ expect(e.candidates).to.not.contain('a');
+ expect(e.ast.type).to.equal('CallExpression');
+ }
+ });
+
+ it('CallNonFunction on global', () => {
+ try {
+ new Engine({extraErrorInfo: true}).evalSync('function y() {};\nvar z = 10;\nvar a = 7;\na();');
+ expect(false).to.be.true;
+ } catch ( e ) {
+ expect(e.line).to.equal(4);
+ expect(e.code).to.equal('CallNonFunction');
+ expect(e.candidates).to.contain('y');
+ expect(e.candidates).to.not.contain('z');
+ expect(e.ast.type).to.equal('CallExpression');
+ }
+ });
+
+ it('Change an added global const', () => {
+ var engine = new Engine({extraErrorInfo: true, strict: true});
+ engine.addGlobalValue('pi', 3.14, {const: true});
+ try {
+ engine.evalSync('pi = 3;');
+ expct(false).to.equal(true);
+ } catch ( e ) {
+ expect(e.name).to.equal('TypeError');
+ }
+ expect(engine.globalScope.get('pi').toNative()).to.equal(3.14);
+ });
+});
diff --git a/pool/shard010/JavaScript/0068764_config.js b/pool/shard010/JavaScript/0068764_config.js
new file mode 100644
index 0000000000000000000000000000000000000000..615439d76b9b9b91c547725aa6c0fad87174afd1
--- /dev/null
+++ b/pool/shard010/JavaScript/0068764_config.js
@@ -0,0 +1,282 @@
+/******************************************************************************
+Copyright (c) 2016, Intel Corporation
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * Neither the name of Intel Corporation nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*****************************************************************************/
+/**
+ * Parse and handle the config files to raw files
+ */
+
+var B = require("hope-base");
+var _ = require("lodash");
+
+var reldir = B.fs.dir_exists(__dirname + "/../../ui-widgets") ? "/../.." : "/../../..";
+var absdir = B.path.resolve(__dirname + reldir);
+
+exports.process = function(file_path) {
+ return new Config(file_path);
+};
+
+function Config(file_path) {
+ this.path = B.path.resolve(file_path);
+ this.json = B.fs.read_json_with_comments(this.path);
+ this.to_assemble = {};
+ this.generated_config = {
+ assemble: this.to_assemble
+ };
+
+ this.enable_log();
+
+ this.parse_basic();
+
+ this.gen_shared();
+
+ if (this.type === "center") {
+ this.gen_center_specific();
+ } else if (this.type === "hub") {
+ this.gen_hub_specific();
+ }
+
+}
+
+
+Config.prototype.parse_basic = function() {
+ this.type = this.json.type;
+ B.check(_.includes(["center", "hub"], this.type), "The type of configuration is",
+ this.type, "while it can only be one of", ["center", "hub"]);
+
+ this.name = this.json.name;
+ if (!this.name) {
+ this.name = (this.type === "center" ? "Center" : "anonymous");
+ }
+
+ this.id = this.json.id;
+
+ if (this.id) {
+ this.generated_config.id = this.id;
+ }
+
+ this.generated_config.config_path = this.path;
+};
+
+
+Config.prototype.enable_log = function() {
+ var log = this.json.log || {
+ enabled: false
+ };
+ log.levels = log.levels || {
+ debug: false,
+ info: true,
+ warn: true,
+ error: true
+ };
+ var categories = log.categories || {
+ "*": false
+ };
+ delete log.categories;
+
+ B.log.configure_options(log);
+ B.log.configure_categories(categories);
+
+};
+
+Config.prototype.gen_shared = function() {
+ B.check(_.isObject(this.json.broker), "Missing broker configuration");
+ _.assign(this.to_assemble, {
+ mnode: {
+ $type: "MNode",
+ $params: {
+ name: this.name,
+ brokers: this.json.broker
+ }
+ },
+
+ hub_store: {
+ $type: "HubStore",
+ $params: "memory"
+ },
+ thing_store: {
+ $type: "ThingStore",
+ $params: "memory"
+ },
+ service_store: {
+ $type: "ServiceStore",
+ $params: "memory"
+ },
+ spec_store: {
+ $type: "SpecStore",
+ $params: "memory"
+ },
+ specbundle_store: {
+ $type: "SpecBundleStore",
+ $params: "memory"
+ },
+ session_store: {
+ $type: "SessionStore",
+ $params: "memory"
+ },
+ graph_store: {
+ $type: "GraphStore",
+ $params: "memory"
+ },
+ app_store: {
+ $type: "AppStore",
+ $params: "memory"
+ },
+ ui_store: {
+ $type: "UiStore",
+ $params: "memory"
+ },
+
+ entity_manager: {
+ $type: "EntityManager",
+ $params: [{
+ hub_store: "$hub_store",
+ thing_store: "$thing_store",
+ service_store: "$service_store",
+ spec_store: "$spec_store",
+ specbundle_store: "$specbundle_store",
+ session_store: "$session_store",
+ graph_store: "$graph_store",
+ app_store: "$app_store",
+ ui_store: "$ui_store"
+ }]
+ }
+ });
+};
+
+Config.prototype.gen_center_specific = function() {
+
+ this.to_assemble.entity_manager.$params[0].user_store = "$user_store";
+
+ _.assign(this.to_assemble, {
+ appbundle_path: this.json.appbundle_path || "./appbundle",
+ user_json_path: this.json.user_json_path || "./user.json",
+
+ user_store: {
+ $type: "UserStore",
+ $params: ["file", {
+ path: "$user_json_path"
+ }]
+ },
+
+
+ dev_web_app: {
+ $type: "WebApp",
+ $params: {
+ port: _.get(this.json, "web_for_developer.port", 8080),
+ static: [absdir + "/ui-dev/public", absdir + "/doc/html", absdir + "/ui-widgets"],
+ web_socket: true
+ }
+ },
+
+ user_web_app: {
+ $type: "WebApp",
+ $params: {
+ port: _.get(this.json, "web_for_end_users.port", 3000),
+ static: [absdir + "/ui-user/public", absdir + "/ui-widgets"],
+ web_socket: true
+ }
+ },
+
+ center: {
+ $type: "Center",
+ $params: {
+ id: "$id",
+ name: this.name,
+ mnode: "$mnode",
+ config_path: "$config_path",
+ entity_manager: "$entity_manager",
+ appbundle_path: "$appbundle_path",
+ dev_web_app: "$dev_web_app",
+ user_web_app: "$user_web_app",
+ auth: this.json.authenticate ? true : false,
+
+ workflow_engine: {
+ $type: "WorkflowEngine",
+ $params: {
+ "mnode": "$mnode",
+ "em": "$entity_manager"
+ }
+ },
+ heartbeat_server: {
+ store: {
+ $type: "Store",
+ $params: "memory"
+ },
+ check_interval: _.get(this.json, "heartbeat_server.check_interval", 30000),
+ drop_threshold: _.get(this.json, "heartbeat_server.drop_threshold", 120000)
+ }
+ }
+ }
+ });
+};
+
+
+Config.prototype.gen_hub_specific = function() {
+ _.assign(this.to_assemble, {
+ thingbundle_path: this.json.thingbundle_path || "./thing_bundle",
+
+ session_manager: {
+ $type: "SessionManager",
+ $params: {
+ mnode : "$mnode",
+ em : "$entity_manager"
+ }
+ },
+
+ hub: {
+ $type: "Hub",
+ $params: {
+ id: "$id",
+ name : this.name,
+ config_path : "$config_path",
+ mnode: "$mnode",
+ entity_manager: "$entity_manager",
+ thingbundle_path: "$thingbundle_path",
+ session_manager: "$session_manager",
+ heartbeat: {
+ interval: _.get(this.json, "heartbeat.interval", 20000)
+ }
+ }
+ }
+ });
+
+ if (this.json.init_script) {
+ this.to_assemble.hub.$params.init_script_path = this.json.init_script;
+ }
+
+ if (this.json.destroy_script) {
+ this.to_assemble.hub.$params.destroy_script_path = this.json.destroy_script;
+ }
+
+ if (this.json.specbundle_path) {
+ this.to_assemble.hub.$params.specbundle_path = this.json.specbundle_path;
+ }
+
+ // special handling for grove
+ if (_.isObject(this.json.grove_config)) {
+ this.to_assemble.hub.$params.grove_config = this.json.grove_config;
+ }
+};
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068768_FulltextIndexColumn.js b/pool/shard010/JavaScript/0068768_FulltextIndexColumn.js
new file mode 100644
index 0000000000000000000000000000000000000000..ba1e257eadba92e89c5f709cfe6bc5ffb1b7cd3c
--- /dev/null
+++ b/pool/shard010/JavaScript/0068768_FulltextIndexColumn.js
@@ -0,0 +1,36 @@
+
+
+const _ = require('lodash');
+var forklift = require('../');
+var BaseColumn = require('./BaseColumn.js');
+
+class FulltextIndexColumn extends BaseColumn {
+ constructor (name) {
+ super(name);
+ this._column = null;
+ this._analyzer = null;
+ }
+
+ column (column) {
+ this._column = column;
+ return this;
+ }
+
+ analyzer (analyzer='default') {
+ this._analyzer = analyzer;
+ return this;
+ }
+
+ toString () {
+ // var stmt = `index ${this._name} using fulltext(${this._column})`;
+ var stmt = 'index ' + this._name + ' using fulltext(' + this._column + ')';
+ if (this._analyzer) {
+ // return `${stmt} with (analyzer=\'${this._analyzer}\')`;
+ return stmt + ' with (analyzer=\'' + this._analyzer + '\')';
+ } else {
+ return stmt;
+ }
+ }
+};
+
+module.exports = FulltextIndexColumn;
diff --git a/pool/shard010/JavaScript/0068769_index.js b/pool/shard010/JavaScript/0068769_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..01a8db52153f6e54d79bc68ef136094078722c57
--- /dev/null
+++ b/pool/shard010/JavaScript/0068769_index.js
@@ -0,0 +1,75 @@
+var crypto = require('crypto');
+var hashes = require('../');
+var test = require('tape');
+
+
+function testHash(t, ianaName, cryptoName) {
+ var avail = hashes.getHashes();
+ if (avail.indexOf(ianaName) >= 0) {
+ t.equal(crypto.createHash(cryptoName).update('test').digest('hex'),
+ hashes.createHash(ianaName).update('test').digest('hex'));
+ } else {
+ t.skip('The ' + ianaName + ' algorithm is not supported in this environment');
+ }
+ t.end();
+}
+
+function testHMAC(t, ianaName, cryptoName) {
+ var avail = hashes.getHashes();
+ if (avail.indexOf(ianaName) >= 0) {
+ t.equal(crypto.createHmac(cryptoName, 'key').update('test').digest('hex'),
+ hashes.createHmac(ianaName, 'key').update('test').digest('hex'));
+ } else {
+ t.skip('The ' + ianaName + ' algorithm is not supported in this environment');
+ }
+ t.end();
+}
+
+
+test('Hash MD5', function (t) {
+ testHash(t, 'md5', 'md5');
+});
+
+test('Hash SHA-1', function (t) {
+ testHash(t, 'sha-1', 'sha1');
+});
+
+test('Hash SHA-224', function (t) {
+ testHash(t, 'sha-224', 'sha224');
+});
+
+test('Hash SHA-256', function (t) {
+ testHash(t, 'sha-256', 'sha256');
+});
+
+test('Hash SHA-384', function (t) {
+ testHash(t, 'sha-384', 'sha384');
+});
+
+test('Hash SHA-512', function (t) {
+ testHash(t, 'sha-512', 'sha512');
+});
+
+test('HMAC MD5', function (t) {
+ testHMAC(t, 'md5', 'md5');
+});
+
+test('HMAC SHA-1', function (t) {
+ testHMAC(t, 'sha-1', 'sha1');
+});
+
+test('HMAC SHA-224', function (t) {
+ testHMAC(t, 'sha-224', 'sha224');
+});
+
+test('HMAC SHA-256', function (t) {
+ testHMAC(t, 'sha-256', 'sha256');
+});
+
+test('HMAC SHA-384', function (t) {
+ testHMAC(t, 'sha-384', 'sha384');
+});
+
+test('HMAC SHA-512', function (t) {
+ testHMAC(t, 'sha-512', 'sha512');
+});
diff --git a/pool/shard010/JavaScript/0068771_CatmullRomSplineSpec.js b/pool/shard010/JavaScript/0068771_CatmullRomSplineSpec.js
new file mode 100644
index 0000000000000000000000000000000000000000..fd5d49562692ce0eabbdde1a582c7e0fe93b6e4b
--- /dev/null
+++ b/pool/shard010/JavaScript/0068771_CatmullRomSplineSpec.js
@@ -0,0 +1,174 @@
+/*global defineSuite*/
+defineSuite([
+ 'Core/CatmullRomSpline',
+ 'Core/Cartesian3',
+ 'Core/HermiteSpline',
+ 'Core/Math'
+ ], function(
+ CatmullRomSpline,
+ Cartesian3,
+ HermiteSpline,
+ CesiumMath) {
+ "use strict";
+
+ var points;
+ var times;
+
+ beforeEach(function() {
+ points = [
+ new Cartesian3(-1.0, -1.0, 0.0),
+ new Cartesian3(-0.5, -0.125, 0.0),
+ new Cartesian3(0.5, 0.125, 0.0),
+ new Cartesian3(1.0, 1.0, 0.0)
+ ];
+ times = [0.0, 1.0, 2.0, 3.0];
+ });
+
+ it('constructor throws without points or times', function() {
+ expect(function() {
+ return new CatmullRomSpline();
+ }).toThrowDeveloperError();
+ });
+
+ it('constructor throws when control points length is less than 2', function() {
+ expect(function() {
+ return new CatmullRomSpline({
+ points : [Cartesian3.ZERO]
+ });
+ }).toThrowDeveloperError();
+ });
+
+ it('constructor throws when times.length is not equal to points.length', function() {
+ expect(function() {
+ return new CatmullRomSpline({
+ points : points,
+ times : [0.0, 1.0]
+ });
+ }).toThrowDeveloperError();
+ });
+
+ it('sets start and end tangents', function() {
+ var start = Cartesian3.subtract(points[1], points[0], new Cartesian3());
+ var end = Cartesian3.subtract(points[points.length - 1], points[points.length - 2], new Cartesian3());
+ var crs = new CatmullRomSpline({
+ points : points,
+ times : times,
+ firstTangent : start,
+ lastTangent : end
+ });
+
+ expect(start).toEqual(crs.firstTangent);
+ expect(end).toEqual(crs.lastTangent);
+ });
+
+ it('computes start and end tangents', function() {
+ var controlPoint0 = Cartesian3.clone(points[0]);
+ var controlPoint1 = Cartesian3.clone(points[1]);
+ var controlPoint2 = Cartesian3.clone(points[2]);
+
+ var start = new Cartesian3();
+ start = Cartesian3.multiplyByScalar(Cartesian3.subtract(Cartesian3.subtract(Cartesian3.multiplyByScalar(controlPoint1, 2.0, start), controlPoint2, start), controlPoint0, start), 0.5, start);
+
+ var controlPointn0 = Cartesian3.clone(points[points.length - 1]);
+ var controlPointn1 = Cartesian3.clone(points[points.length - 2]);
+ var controlPointn2 = Cartesian3.clone(points[points.length - 3]);
+
+ var end = new Cartesian3();
+ end = Cartesian3.multiplyByScalar(Cartesian3.add(Cartesian3.subtract(controlPointn0, Cartesian3.multiplyByScalar(controlPointn1, 2.0, end), end), controlPointn2, end), 0.5, end);
+
+ var crs = new CatmullRomSpline({
+ points : points,
+ times : times
+ });
+
+ expect(start).toEqual(crs.firstTangent);
+ expect(end).toEqual(crs.lastTangent);
+ });
+
+ it('evaluate throws without time', function() {
+ var crs = new CatmullRomSpline({
+ points : points,
+ times : times
+ });
+
+ expect(function() {
+ crs.evaluate();
+ }).toThrowDeveloperError();
+ });
+
+ it('evaluate throws when time is out of range', function() {
+ var crs = new CatmullRomSpline({
+ points : points,
+ times : times
+ });
+
+ expect(function() {
+ crs.evaluate(times[0] - 1.0);
+ }).toThrowDeveloperError();
+ });
+
+ it('check Catmull-Rom spline against a Hermite spline', function() {
+ var crs = new CatmullRomSpline({
+ points : points,
+ times : times
+ });
+
+ var tangents = [crs.firstTangent];
+ for ( var i = 1; i < points.length - 1; ++i) {
+ tangents.push(Cartesian3.multiplyByScalar(Cartesian3.subtract(points[i + 1], points[i - 1], new Cartesian3()), 0.5, new Cartesian3()));
+ }
+ tangents.push(crs.lastTangent);
+
+ var hs = HermiteSpline.createC1({
+ points : points,
+ tangents : tangents,
+ times : times
+ });
+
+ var granularity = 0.5;
+ for ( var j = times[0]; j <= times[points.length - 1]; j = j + granularity) {
+ expect(hs.evaluate(j)).toEqualEpsilon(crs.evaluate(j), CesiumMath.EPSILON4);
+ }
+ });
+
+ it('evaluate with result parameter', function() {
+ var crs = new CatmullRomSpline({
+ points : points,
+ times : times
+ });
+ var result = new Cartesian3();
+
+ var point = crs.evaluate(times[0], result);
+ expect(point).toBe(result);
+ expect(result).toEqual(points[0]);
+ });
+
+ it('spline with 2 control points defaults to lerp', function() {
+ points = points.slice(0, 2);
+ times = times.slice(0, 2);
+
+ var crs = new CatmullRomSpline({
+ points : points,
+ times : times
+ });
+
+ var t = (times[0] + times[1]) * 0.5;
+ expect(crs.evaluate(t)).toEqual(Cartesian3.lerp(points[0], points[1], t, new Cartesian3()));
+ });
+
+ it('spline with 2 control points defaults to lerp and result parameter', function() {
+ points = points.slice(0, 2);
+ times = times.slice(0, 2);
+
+ var crs = new CatmullRomSpline({
+ points : points,
+ times : times
+ });
+
+ var t = (times[0] + times[1]) * 0.5;
+ var result = new Cartesian3();
+ var actual = crs.evaluate(t, result);
+ expect(actual).toBe(result);
+ expect(actual).toEqual(Cartesian3.lerp(points[0], points[1], t, new Cartesian3()));
+ });
+});
diff --git a/pool/shard010/JavaScript/0068773_ACHTCENT.Inventory.js b/pool/shard010/JavaScript/0068773_ACHTCENT.Inventory.js
new file mode 100644
index 0000000000000000000000000000000000000000..2b7d1e873064535ec1367bf54f657ebb39c9d771
--- /dev/null
+++ b/pool/shard010/JavaScript/0068773_ACHTCENT.Inventory.js
@@ -0,0 +1,262 @@
+/**
+ * @author Ikaros Kappler
+ * @date 2013-10-02
+ * @version 1.0.0
+ **/
+
+ACHTCENT.Inventory = function( id ) {
+
+ ACHTCENT.Object.call();
+
+ this.setID( id );
+
+ // An array for storing the depositables (bottles, cans, ...)
+ this.depositables = [];
+ this.totalDepositValue = 0;
+
+ // TODO (no such class exists yet)
+ this.carriages = [];
+ this.totalCarryCapacity = 0;
+
+ // Decoration stuff
+ this.blingBlings = [];
+}
+
+ACHTCENT.Inventory.prototype = new ACHTCENT.Object( null );
+ACHTCENT.Inventory.prototype.constructor = ACHTCENT.Inventory;
+
+/**
+ * Get the total depositable value this inventory currently contains.
+ **/
+ACHTCENT.Inventory.prototype.getTotalDepositValue = function() {
+ return this.totalDepositValue;
+}
+
+/**
+ * Get the total depositable value this inventory currently contains.
+ **/
+ACHTCENT.Inventory.prototype.getTotalCarryCapacity = function() {
+ return this.totalCarryCapacity;
+}
+
+
+
+/**
+ * Adds any item to this inventory.
+ * There are three item types:
+ * - depositables
+ * - carriage containers
+ * - bling blings
+ **/
+ACHTCENT.Inventory.prototype.addItem = function( item ) {
+
+ if( typeof item.getDepositValue == "function" ) {
+
+ return this.addDepositable( item );
+
+ } else if( typeof item.getCarryCapacity == "function" ) {
+
+ return this.addCarriage( item );
+
+ } else {
+
+ return this.addBlingBling( item );
+
+ }
+
+}
+
+/**
+ * Removes the passed item.
+ * There are three item types:
+ * - depositables
+ * - carriage containers
+ * - bling blings
+ **/
+ACHTCENT.Inventory.prototype.removeItem = function( item ) {
+
+ if( typeof item.getDepositValue == "function" ) {
+
+ return this.removeDepositable( item );
+
+ } else if( typeof item.getCarryCapacity == "function" ) {
+
+ return this.removeCarriage( item );
+
+ } else {
+
+ return this.removeBlingBling( item );
+
+ }
+
+}
+
+/**
+ * Adds a new depositable to this inventory.
+ * The passed item MUST have a getDepositValue() function.
+ **/
+ACHTCENT.Inventory.prototype.addDepositable = function( depositable ) {
+
+ // Inventory capacity check
+ if( this.getTotalCarryCapacity() <= this.depositables.length ) {
+
+ // No more space to carry depositables
+ return false;
+ }
+ // else:
+
+ this.totalDepositValue += depositable.getDepositValue();
+ this.depositables.push( depositable );
+
+ return true;
+}
+
+/**
+ * Removes the passed depositable and decreases the total deposit value.
+ **/
+ACHTCENT.Inventory.prototype.removeDepositable = function( depositable ) {
+
+ // Locate carriage by id
+ for( var i = 0; i < this.depositables.length; i++ ) {
+
+ if( this.depositables[i].getID() == depositable.getID() )
+ return this.removeDepositableAt(i);
+
+ }
+
+ // Loop terminated -> element not found
+ return false;
+}
+
+/**
+ * Removes the depositable at the given array index and decreases the total deposit value.
+ **/
+ACHTCENT.Inventory.prototype.removeDepositableAt = function( index ) {
+
+ if( index < 0 || index >= this.depositables.length )
+ return false;
+
+ //window.alert( "Before: " + JSON.stringify(this.depositables) );
+ var depositable = this.depositables[ index ];
+ this.depositables.splice( index, 1 );
+ //window.alert( "After: " + JSON.stringify(this.depositables) );
+
+ this.totalDepositValue = Math.max( 0,
+ this.totalDepositValue - depositable.getDepositValue()
+ );
+
+ return true;
+}
+
+/**
+ * Adds a new carryable to this inventory.
+ * The passed item MUST have a getDepositValue() function.
+ **/
+ACHTCENT.Inventory.prototype.addCarriage = function( carriage ) {
+
+ // Inventory capacity check?
+ // ...
+
+ this.totalCarryCapacity += carriage.getCarryCapacity();
+ this.carriages.push( carriage );
+
+ return true;
+
+}
+
+/**
+ * Removes the passed carriage and decreases the total carry capacity.
+ **/
+ACHTCENT.Inventory.prototype.removeCarriage = function( carriage ) {
+
+ // Locate carriage by id
+ for( var i = 0; i < this.carriages.length; i++ ) {
+
+ if( this.carriages[i].getID() == carriage.getID() )
+ return this.removeCarriageAt(i);
+
+ }
+
+ // Loop terminated -> element not found
+ return false;
+}
+
+/**
+ * Removes the carriage at the given array index and decreases the total carry capacity.
+ **/
+ACHTCENT.Inventory.prototype.removeCarriageAt = function( index ) {
+
+ if( index < 0 || index >= this.carriages.length )
+ return false;
+
+ var carriage = this.carriages[ index ];
+ this.carriages.splice( index, 1 );
+
+ this.totalCarryCapacity = Math.max( 0,
+ this.totalCarryCapacity - carriage.getCarryCapacity()
+ );
+
+ // Drop depositables that do not fit!
+ while( this.depositables.length > this.totalCarryCapacity ) {
+ this.removeDepositableAt( this.depositables.length-1 );
+ }
+
+ return true;
+}
+
+ACHTCENT.Inventory.prototype.addBlingBling = function( blingBling ) {
+
+ // Inventory capacity check?
+ // ...
+
+ this.blingBlings.push( blingBling );
+
+ return true;
+
+}
+
+/**
+ * Removes the passed bling bling.
+ **/
+ACHTCENT.Inventory.prototype.removeBlingBling = function( blingBling ) {
+
+ // Locate carriage by id
+ for( var i = 0; i < this.blingBlings.length; i++ ) {
+
+ if( this.blingBlings[i].getID() == blingbling.getID() )
+ return this.removeBlingBlingAt(i);
+
+ }
+
+ // Loop terminated -> element not found
+ return false;
+}
+
+/**
+ * Removes the bling bling at the given array index.
+ **/
+ACHTCENT.Inventory.prototype.removeBlingBlingAt = function( index ) {
+
+ if( index < 0 || index >= this.blingBlings.length )
+ return false;
+
+ this.blingBlingss.splice( index, 1 );
+ return true;
+}
+
+
+
+ACHTCENT.Inventory.prototype.__getClassName = function() {
+ return "ACHTCENT.Inventory";
+}
+
+ACHTCENT.Inventory.prototype.__toString = function() {
+ return "[" + this.__getClassName() + "]={ " +
+ "id=" + this.getID() +
+ ", depositables.length=" + this.depositables.length +
+ ", totalDepositValue=" + this.totalDepositValue +
+ ", carriages.length=" + this.carriages.length +
+ ", totalCarryCapacity=" + this.totalCarryCapacity +
+ ", blingBlings.length=" + this.blingBlings.length +
+ " }";
+}
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068776_imageslider.js b/pool/shard010/JavaScript/0068776_imageslider.js
new file mode 100644
index 0000000000000000000000000000000000000000..b51980749e63df69349fbcbc43feef753e121952
--- /dev/null
+++ b/pool/shard010/JavaScript/0068776_imageslider.js
@@ -0,0 +1,76 @@
+import Swipe from 'static/js/utils/swipe.js'
+import Util from 'static/js/utils/util'
+
+
+let style = __inline('./imageslider.inline.less');
+let tpl = __inline('./imageslider.tpl');
+
+require.loadCss({
+ name: 'market-widget-imageslider-style',
+ content: style
+});
+export default Vue.component('imageslider', {
+ template: tpl,
+ data: () => ({
+ curIndex: 0
+ }),
+ ready: function () {
+ if (this.isReady) {
+ this.render();
+ }
+ },
+ props:{
+ images: {
+ type: Array,
+ default: []
+ },
+ isReady: {
+ type: Boolean,
+ default: false
+ },
+ useThumbnail: {type: Boolean, default: false}
+ },
+ computed: {
+ thumbnails: function () {
+ if (this.useThumbnail) {
+ return this.images.map(image => Util.thumbnail({
+ width: 640,
+ src: image
+ })).slice(0, 10);
+ } else {
+ return this.images.slice(0, 10);
+ }
+ }
+ },
+ methods:{
+ render: function () {
+ let container = $(this.$el).find('.slider');
+ let me = this;
+ Vue.nextTick(function () {
+ new Swipe(container.get(0), {
+ auto: 3000,
+ transitionEnd: (index) => {
+ me.curIndex = index % me.thumbnails.length;
+ },
+ callback: function(index, element) {
+ /*that.slideTab(index);*/
+ },
+ continuous: true,
+ });
+ });
+
+ setTimeout(() => {
+ container.css({opacity: 1});
+ }, 1000);
+ }
+ },
+ watch: {
+ isReady: function (val) {
+ let container = $(this.$el).find('.slider');
+ let me = this;
+ if (val === true) {
+ this.render();
+ }
+ }
+ }
+})
diff --git a/pool/shard010/JavaScript/0068777_shoppingCart.dir.js b/pool/shard010/JavaScript/0068777_shoppingCart.dir.js
new file mode 100644
index 0000000000000000000000000000000000000000..9c2c30fc24a90de9d67f3caf59ec928c86f45cbb
--- /dev/null
+++ b/pool/shard010/JavaScript/0068777_shoppingCart.dir.js
@@ -0,0 +1,51 @@
+(function (ng) {
+ var mod = ng.module('shoppingCartModule');
+
+ mod.directive('addShoppingCart', function() {
+ return {
+ restrict: 'E',
+ templateUrl: 'src/modules/shoppingcart/shoppingCart.tpl.html',
+ scope: {
+ artwork: "="
+ },
+ controller: controller
+ };
+ });
+
+ controller.$inject = ['$scope', '$rootScope', '$state', '$modal', 'Restangular'];
+ function controller($scope, $rootScope, $state, $modal, Restangular){
+ var addToCart = function(artwork){
+ return Restangular.all('shoppingCart').post({
+ quantity: 1,
+ artwork: artwork
+ }).then(function() {
+ $modal.open({
+ templateUrl: 'src/modules/shoppingcart/shoppingCartModal.tpl.html',
+ controller: modalController,
+ scope: $scope,
+ resolve: {
+ artwork: artwork
+ }
+ });
+ });
+ };
+
+ $scope.addToCart = function(artwork){
+ if ($rootScope.CheckAuthenticated()) {
+ addToCart(artwork);
+ }
+ };
+ };
+
+ modalController.$inject = ['$scope', '$modalInstance', '$state'];
+ function modalController($scope, $modalInstance, $state){
+ $scope.goToCart = function(){
+ $modalInstance.close($state.go('shoppingCart'));
+ };
+
+ $scope.cancel = function () {
+ $modalInstance.dismiss('cancel');
+ };
+ };
+
+})(window.angular);
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068778_ZClippedMesh.js b/pool/shard010/JavaScript/0068778_ZClippedMesh.js
new file mode 100644
index 0000000000000000000000000000000000000000..ec6d7c04d93f0ee04c5cf164530c1bbf119de31a
--- /dev/null
+++ b/pool/shard010/JavaScript/0068778_ZClippedMesh.js
@@ -0,0 +1,44 @@
+import UberObject from './UberObject'
+import { Matrix4, Mesh, Vector3 } from 'three'
+
+const OurMesh = UberObject(Mesh)
+
+class ZClippedMesh extends OurMesh {
+ constructor(geometry, material) {
+ super(geometry, material)
+ this.castShadow = true
+ this.receiveShadow = true
+ }
+
+ static _mvLength = new Vector3()
+
+ static _center = new Vector3()
+
+ static _modelView = new Matrix4()
+
+ _onBeforeRender(renderer, scene, camera) {
+ OurMesh.prototype._onBeforeRender.call(this, renderer, scene, camera)
+
+ const geo = this.geometry
+ const { material } = this
+ if (!geo.zClip || !material.uberOptions) {
+ return
+ }
+
+ const zClipCoef = 0.5
+
+ const modelView = ZClippedMesh._modelView
+ const mvLength = ZClippedMesh._mvLength
+ const center = ZClippedMesh._center
+
+ modelView.multiplyMatrices(this.matrixWorld, camera.matrixWorldInverse)
+ const s = mvLength.setFromMatrixColumn(modelView, 0).length()
+ center.copy(geo.boundingSphere.center)
+
+ this.localToWorld(center)
+ material.uberOptions.zClipValue =
+ camera.position.z - center.z - s * (zClipCoef * geo.boundingSphere.radius)
+ }
+}
+
+export default ZClippedMesh
diff --git a/pool/shard010/JavaScript/0068779_app.js b/pool/shard010/JavaScript/0068779_app.js
new file mode 100644
index 0000000000000000000000000000000000000000..dc0bf0d99172d72941cf014e814da9dbd876711b
--- /dev/null
+++ b/pool/shard010/JavaScript/0068779_app.js
@@ -0,0 +1,119 @@
+/**
+ * Created by fanjunwei on 15/12/19.
+ */
+var app = angular.module('desktop', ["ngAnimate", "ngTouch", 'perfect_scrollbar', 'ngFileUpload', 'ui.router', "ui.bootstrap", 'desktop.services', 'directive', 'ui.codemirror', "infinite-scroll"]);
+app.run(function ($rootScope) {
+ $rootScope.base_config = base_config;
+});
+app.config(['$stateProvider', '$urlRouterProvider', 'modalBoxProvider', 'mqttProvider', function ($stateProvider, $urlRouterProvider, modalBoxProvider, mqttProvider) {
+ $stateProvider
+ .state('login', {
+ url: '/login',
+ templateUrl: "app/login/login.html",
+ controller: "loginCtrl"
+ })
+ .state('join_org', {
+ url: '/join_org',
+ templateUrl: "app/organization/join_org.html",
+ controller: "firstJoinOrgCtrl"
+ })
+ .state('main', {
+ url: '/main',
+ templateUrl: "app/main/main.html",
+ controller: "mainCtrl"
+ })
+ .state('main.message', {
+ url: '/message',
+ templateUrl: "app/message/message.html",
+ controller: "messageCtrl"
+ })
+ .state('main.contacts', {
+ url: '/contacts',
+ templateUrl: "app/contacts/contacts.html",
+ controller: "contactsCtrl"
+ })
+ .state('main.contacts.org_group', {
+ url: '/org_group',
+ templateUrl: "app/contacts/org_group/org_group.html",
+ controller: "orgGroupCtrl"
+ })
+ .state('main.contacts.relationship', {
+ url: '/relationship',
+ templateUrl: "app/contacts/relationship/relationship.html",
+ controller: "relationshipCtrl"
+ })
+ .state('main.application', {
+ url: '/application',
+ templateUrl: "app/application/application.html",
+ controller: "applicationCtrl"
+ })
+ .state('main.push', {
+ url: '/push',
+ templateUrl: "app/push/push.html",
+ controller: "pushCtrl"
+ })
+ .state('main.test', {
+ url: '/test',
+ templateUrl: "app/test/test.html",
+ controller: "testCtrl"
+ })
+ .state('main.develop', {
+ url: '/develop',
+ templateUrl: "app/develop/develop.html",
+ controller: "developCtrl"
+ })
+
+ $urlRouterProvider.otherwise(function ($injector, $location) {
+ var auth = $injector.get("auth");
+ auth.hasLogin().then(function (has_login) {
+ if (has_login) {
+ $location.replace().path("/main/message");
+ }
+ else {
+ $location.replace().path("/login");
+ }
+
+ })
+
+ });
+
+ modalBoxProvider
+ .set('test', {
+ templateUrl: "app/test/test_right_box.html",
+ controller: "testRigthBoxCtrl",
+ type: "rightBox"
+ })
+ .set("develop", {
+ templateUrl: "app/develop/develop_right_box.html",
+ controller: "developRigthBoxCtrl",
+ type: "rightBox"
+ })
+ .set("user_info", {
+ templateUrl: "app/user_info/user_info.html",
+ controller: "userInfoCtrl"
+ })
+ .set("create_organization", {
+ templateUrl: "app/organization/create_organization.html",
+ controller: "organizationCreateCtrl"
+ })
+ .set("create_group", {
+ templateUrl: "app/organization/create_group.html",
+ controller: "groupCreateCtrl"
+ })
+ .set("modefy_group", {
+ templateUrl: "app/organization/modefy_group.html",
+ controller: "groupModefyCtrl"
+ })
+ .set("join_organization", {
+ templateUrl: "app/organization/join_organization.html",
+ controller: "joinOrgCtrl"
+ })
+ .set("modefy_org_apply", {
+ templateUrl: "app/organization/modefy_org_apply.html",
+ controller: "modefyOrgApplyCtrl"
+ });
+
+ base_config.mqtt.device_id = (new Date()).valueOf();
+ mqttProvider.set(base_config.mqtt);
+
+}]);
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068780_dialog.js b/pool/shard010/JavaScript/0068780_dialog.js
new file mode 100644
index 0000000000000000000000000000000000000000..5a2e75d86b49ff378e7fda3985847020e491d750
--- /dev/null
+++ b/pool/shard010/JavaScript/0068780_dialog.js
@@ -0,0 +1,33 @@
+var dlgSuccess = {
+ open : function() { $("#dlgSuccess").dialog('open'); },
+ close : function() { $("#dlgSuccess").dialog('close'); }
+ };
+
+ var dlgError = {
+ open : function() { $("#dlgError").dialog('open'); },
+ close : function() { $("#dlgError").dialog('close'); }
+ };
+
+ $(document).ready(function(){
+
+ $("#dlgSuccess").dialog({
+ width : 480,
+ heigth : 300,
+ modal : true,
+ autoOpen : false,
+ resizable : false,
+ open : function() {$(".ui-dialog-titlebar").css('display', 'none'); },
+ close : function() {$(".ui-dialog-titlebar").css('display', '');}
+ });
+
+ $("#dlgError").dialog({
+ width : 480,
+ heigth : 300,
+ modal : true,
+ autoOpen : false,
+ resizable : false,
+ open : function() {$(".ui-dialog-titlebar").css('display', 'none'); },
+ close : function() {$(".ui-dialog-titlebar").css('display', '');}
+ });
+
+ });
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068781_graph-edge.js b/pool/shard010/JavaScript/0068781_graph-edge.js
new file mode 100644
index 0000000000000000000000000000000000000000..fdd9c667f4f48405e4ff788fe0c79d1c032414ca
--- /dev/null
+++ b/pool/shard010/JavaScript/0068781_graph-edge.js
@@ -0,0 +1,41 @@
+import Ember from 'ember';
+import SigmaChildBase from './sigma-child-base';
+
+export default SigmaChildBase.extend({
+
+ sigmaProperties: ['source', 'target', 'label', 'size', 'color', 'type'],
+
+ dynamicSigmaProperties: ['label', 'size', 'color', 'type'],
+
+ didInsertParent: function() {
+ this._super(...arguments);
+ if (this.get('parentComponent')) {
+ let attrs = this.getSigmaProperties();
+ if (this.graphModel().nodes(attrs.source) && this.graphModel().nodes(attrs.target)) {
+ try {
+ this.graphModel().addEdge(attrs);
+ this.sigma().refresh();
+ }
+ catch(e) {
+ Ember.Logger.error(e);
+ }
+ }
+ }
+ },
+
+ willDestroyParent: function() {
+ this._super(...arguments);
+ if (this.sigma()) {
+ if (this.graphModel().edges(this.get('id'))) {
+ this.graphModel().dropEdge(this.get('id'));
+ this.sigma().refresh();
+ }
+ }
+ },
+
+ _changeProperty: function(property) {
+ let child = this.graphModel().edges(this.id);
+ child[property] = this.get(property);
+ this._super(...arguments);
+ }
+});
diff --git a/pool/shard010/JavaScript/0068784_tuple.js b/pool/shard010/JavaScript/0068784_tuple.js
new file mode 100644
index 0000000000000000000000000000000000000000..f88ad8804c4909b5e99d3878db523a4ac400328d
--- /dev/null
+++ b/pool/shard010/JavaScript/0068784_tuple.js
@@ -0,0 +1,113 @@
+/* globals describe, it */
+var assert = require('assert');
+var t = require('../index');
+var util = require('./util');
+
+var Point = t.struct({
+ x: t.Number,
+ y: t.Number
+});
+
+describe('t.tuple(types, [name])', function () {
+
+ var Area = t.tuple([t.Number, t.Number], 'Area');
+
+ describe('combinator', function () {
+
+ it('should throw if used with wrong arguments', function () {
+
+ util.throwsWithMessage(function () {
+ t.tuple();
+ }, '[tcomb] Invalid argument types undefined supplied to tuple(types, [name]) combinator (expected an array of types)');
+
+ util.throwsWithMessage(function () {
+ t.tuple([1]);
+ }, '[tcomb] Invalid argument types [\n 1\n] supplied to tuple(types, [name]) combinator (expected an array of types)');
+
+ util.throwsWithMessage(function () {
+ t.tuple([Point, Point], 1);
+ }, '[tcomb] Invalid argument name 1 supplied to tuple(types, [name]) combinator (expected a string)');
+
+ });
+
+ });
+
+ describe('constructor', function () {
+
+ var S = t.struct({}, 'S');
+ var T = t.tuple([S, S], 'T');
+
+ it('should throw with a contextual error message if used with wrong arguments', function () {
+
+ var T = t.tuple([t.Number, t.Number], 'T');
+
+ util.throwsWithMessage(function () {
+ T();
+ }, '[tcomb] Invalid value undefined supplied to T (expected an array of length 2)');
+
+ util.throwsWithMessage(function () {
+ T(['a']);
+ }, '[tcomb] Invalid value [\n "a"\n] supplied to T (expected an array of length 2)');
+
+ });
+
+ it('should hydrate the elements of the list', function () {
+ var instance = T([{}, {}]);
+ assert.equal(S.is(instance[0]), true);
+ });
+
+ it('should hydrate the elements of the list in production', util.production(function () {
+ var instance = T([{}, {}]);
+ assert.equal(S.is(instance[0]), true);
+ }));
+
+ it('should be idempotent', function () {
+ var t0 = [{}, {}];
+ var t1 = T(t0);
+ var t2 = T(t1);
+ assert.equal(t0 === t1, false);
+ assert.equal(t1 === t2, true);
+ });
+
+ it('should be idempotent in production', util.production(function () {
+ var t0 = [{}, {}];
+ var t1 = T(t0);
+ var t2 = T(t1);
+ assert.equal(t0 === t1, false);
+ assert.equal(t1 === t2, true);
+ }));
+
+ });
+
+ describe('is(x)', function () {
+
+ it('should return true when x is an instance of the tuple', function () {
+ assert.ok(Area.is([1, 2]));
+ });
+
+ it('should return false when x is not an instance of the tuple', function () {
+ assert.strictEqual(Area.is([1]), false);
+ assert.strictEqual(Area.is([1, 2, 3]), false);
+ assert.strictEqual(Area.is([1, 'a']), false);
+ });
+
+ it('should not depend on `this`', function () {
+ assert.ok([[1, 2]].every(Area.is));
+ });
+
+ });
+
+ describe('update(instance, patch)', function () {
+
+ it('should return a new instance', function () {
+ var Tuple = t.tuple([t.String, t.Number]);
+ var instance = Tuple(['a', 1]);
+ var newInstance = Tuple.update(instance, {0: { $set: 'b' }});
+ assert.equal(Tuple.is(newInstance), true);
+ assert.equal(newInstance !== instance, true);
+ assert.equal(newInstance[0], 'b');
+ });
+
+ });
+
+});
diff --git a/pool/shard010/JavaScript/0068790_stories.js b/pool/shard010/JavaScript/0068790_stories.js
new file mode 100644
index 0000000000000000000000000000000000000000..27d83d1325fcc242486f6bbe641e4b0cbc605301
--- /dev/null
+++ b/pool/shard010/JavaScript/0068790_stories.js
@@ -0,0 +1,19 @@
+/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
+import React from 'react';
+import any from '@travi/any';
+import MeetingDetails from './index';
+
+export default {
+ title: 'Molecules/Meeting Details'
+};
+
+export const Default = () => (
+
+);
+
+Default.story = {
+ name: 'default'
+};
diff --git a/pool/shard010/JavaScript/0068791_tsl2561.js b/pool/shard010/JavaScript/0068791_tsl2561.js
new file mode 100644
index 0000000000000000000000000000000000000000..1b967a3634655feb44850038709923f7f5254543
--- /dev/null
+++ b/pool/shard010/JavaScript/0068791_tsl2561.js
@@ -0,0 +1,350 @@
+/*
+ * Espruino TSL2561 luminosity sensor
+ * by Tom Gidden , January 2014
+ *
+ * Derived largely from C++ Arduino TSL2561 code, from:
+ * https://github.com/adafruit/TSL2561-Arduino-Library
+ * by K. Townsend (microBuilder.eu)
+ *
+ * Currently unimplemented:
+ * - calculateLux function
+ * - Interrupt-driven operation
+ *
+ * Not currently working right:
+ * - INFRARED doesn't seem to work
+ *
+ * It's possibly the features listed above _do_ work, but my particular
+ * TSL2561 breakout sensor _doesn't_ work for some reason. Or there are
+ * bugs in the original C++ code.
+ */
+
+function TSL(i2c) {
+ this.i2c = i2c;
+ this.debug = false;
+}
+
+// All the constants we should need to drive this thing
+TSL.prototype.config = {
+ spectrum: {
+ FULLSPECTRUM: 0,
+ INFRARED: 1,
+ VISIBLE: 2
+ },
+
+ address: {
+ LOW: 0x29,
+ FLOAT: 0x39,
+ HIGH: 0x49
+ },
+
+ timing: {
+ _13MS: 0x00, // 13.7ms
+ _101MS: 0x01, // 101ms
+ _402MS: 0x02 // 402ms
+ },
+
+ gain: {
+ _1X: 0x00, // No gain
+ _16X: 0x10 // 16x gain
+ }
+};
+
+/*
+ var READBIT = (0x01);
+ var COMMAND_BIT = (0x80); // Must be 1
+ var CLEAR_BIT = (0x40); // Clears any pending interrupt (write 1 to clear)
+ var WORD_BIT = (0x20); // 1 = read/write word (rather than byte)
+ var BLOCK_BIT = (0x10); // 1 = using block read/write
+
+ var CONTROL_POWERON = (0x03);
+ var CONTROL_POWEROFF = (0x00);
+
+ var LUX_LUXSCALE = (14); // Scale by 2^14
+ var LUX_RATIOSCALE = (9); // Scale ratio by 2^9
+ var LUX_CHSCALE = (10); // Scale channel values by 2^10
+ var LUX_CHSCALE_TINT0 = (0x7517); // 322/11 * 2^TSL2561_LUX_CHSCALE
+ var LUX_CHSCALE_TINT1 = (0x0FE7); // 322/81 * 2^TSL2561_LUX_CHSCALE
+
+ var REG_CONTROL = 0x00;
+ var REG_TIMING = 0x01;
+ var REG_THRESHHOLDL_LOW = 0x02;
+ var REG_THRESHHOLDL_HIGH = 0x03;
+ var REG_THRESHHOLDH_LOW = 0x04;
+ var REG_THRESHHOLDH_HIGH = 0x05;
+ var REG_INTERRUPT = 0x06;
+ var REG_CRC = 0x08;
+ var REG_ID = 0x0A;
+ var REG_CHAN0_LOW = 0x0C;
+ var REG_CHAN0_HIGH = 0x0D;
+ var REG_CHAN1_LOW = 0x0E;
+ var REG_CHAN1_HIGH = 0x0F;
+*/
+
+// Power up and enable the sensor's data gathering process
+TSL.prototype.enable = function () {
+ this.i2c.writeTo(this.address, [0x80/*COMMAND_BIT*/ | 0/*REG_CONTROL*/,
+ 0x03/*CONTROL_POWERON*/]);
+ return this;
+};
+
+// Disable the sensor's data gathering process and power down.
+TSL.prototype.disable = function () {
+ this.i2c.writeTo(this.address, [0x80/*COMMAND_BIT*/ | 0/*REG_CONTROL*/,
+ 0/*CONTROL_POWEROFF*/]);
+ return this;
+};
+
+// Set the integration timing for the sensor, using values from
+// TSL.config.timing. Setting this to TSL.config.timing._402MS will
+// gather the most data (using the automatic integration, that is)
+TSL.prototype.setTiming = function (timing) {
+ this.timing = timing;
+ this.i2c.writeTo(this.address, [0x80/*COMMAND_BIT*/ | 0x01/*REG_TIMING*/,
+ this.timing | this.gain ]);
+ return this;
+};
+
+// Set the gain of the sensor, to either TSL.config.gain._1X (no gain) or
+// TSL.config.gain._16X (16x gain)
+TSL.prototype.setGain = function (gain) {
+ this.gain = gain;
+ this.i2c.writeTo(this.address, [0x80/*COMMAND_BIT*/ | 0x01/*REG_TIMING*/,
+ this.timing | this.gain ]);
+ return this;
+};
+
+// Initialise the TSL object and send the passed initial configuration to
+// the sensor. The address should be taken from TSL.config.address.LOW,
+// .FLOAT, or .HIGH. If the ADDR pin on the sensor is left unconnected,
+// address should be TSL.config.address.FLOAT. Alternatively it can be
+// pulled high or low to use an alternative address.
+TSL.prototype.init = function (address, timing, gain) {
+ this.address = address;
+ this.timing = timing;
+ this.gain = gain;
+
+ this.i2c.writeTo(this.address, [
+ 0x80/*COMMAND_BIT*/ | 0/*REG_CONTROL*/,
+ 0x03/*CONTROL_POWERON*/
+ ]);
+
+ this.i2c.writeTo(this.address, [
+ 0x80/*COMMAND_BIT*/ | 0x01/*REG_TIMING*/,
+ this.timing | this.gain
+ ]);
+
+ this.i2c.writeTo(this.address, [
+ 0x80/*COMMAND_BIT*/ | 0/*REG_CONTROL*/,
+ 0/*CONTROL_POWEROFF*/
+ ]);
+
+ return this;
+};
+
+TSL.prototype.calculateLux = function (ch0, ch1) {
+ // Not currently implemented.
+ //
+ // This function should use the calibration tables to convert the
+ // device-specific light-level values into Lux units. The code is
+ // available in the Arduino library, but just hasn't been ported yet.
+ /*
+ // T, FN and CL Lux conversion tables
+ var LUX_T = {
+ LUX_K1: (0x0040), // 0.125 * 2^RATIO_SCALE
+ LUX_B1: (0x01f2), // 0.0304 * 2^LUX_SCALE
+ LUX_M1: (0x01be), // 0.0272 * 2^LUX_SCALE
+ LUX_K2: (0x0080), // 0.250 * 2^RATIO_SCALE
+ LUX_B2: (0x0214), // 0.0325 * 2^LUX_SCALE
+ LUX_M2: (0x02d1), // 0.0440 * 2^LUX_SCALE
+ LUX_K3: (0x00c0), // 0.375 * 2^RATIO_SCALE
+ LUX_B3: (0x023f), // 0.0351 * 2^LUX_SCALE
+ LUX_M3: (0x037b), // 0.0544 * 2^LUX_SCALE
+ LUX_K4: (0x0100), // 0.50 * 2^RATIO_SCALE
+ LUX_B4: (0x0270), // 0.0381 * 2^LUX_SCALE
+ LUX_M4: (0x03fe), // 0.0624 * 2^LUX_SCALE
+ LUX_K5: (0x0138), // 0.61 * 2^RATIO_SCALE
+ LUX_B5: (0x016f), // 0.0224 * 2^LUX_SCALE
+ LUX_M5: (0x01fc), // 0.0310 * 2^LUX_SCALE
+ LUX_K6: (0x019a), // 0.80 * 2^RATIO_SCALE
+ LUX_B6: (0x00d2), // 0.0128 * 2^LUX_SCALE
+ LUX_M6: (0x00fb), // 0.0153 * 2^LUX_SCALE
+ LUX_K7: (0x029a), // 1.3 * 2^RATIO_SCALE
+ LUX_B7: (0x0018), // 0.00146 * 2^LUX_SCALE
+ LUX_M7: (0x0012), // 0.00112 * 2^LUX_SCALE
+ LUX_K8: (0x029a), // 1.3 * 2^RATIO_SCALE
+ LUX_B8: (0x0000), // 0.000 * 2^LUX_SCALE
+ LUX_M8: (0x0000) // 0.000 * 2^LUX_SCALE
+ };
+
+ // CS Lux conversion tables
+ var LUX_CS = {
+ LUX_K1: (0x0043), // 0.130 * 2^RATIO_SCALE
+ LUX_B1: (0x0204), // 0.0315 * 2^LUX_SCALE
+ LUX_M1: (0x01ad), // 0.0262 * 2^LUX_SCALE
+ LUX_K2: (0x0085), // 0.260 * 2^RATIO_SCALE
+ LUX_B2: (0x0228), // 0.0337 * 2^LUX_SCALE
+ LUX_M2: (0x02c1), // 0.0430 * 2^LUX_SCALE
+ LUX_K3: (0x00c8), // 0.390 * 2^RATIO_SCALE
+ LUX_B3: (0x0253), // 0.0363 * 2^LUX_SCALE
+ LUX_M3: (0x0363), // 0.0529 * 2^LUX_SCALE
+ LUX_K4: (0x010a), // 0.520 * 2^RATIO_SCALE
+ LUX_B4: (0x0282), // 0.0392 * 2^LUX_SCALE
+ LUX_M4: (0x03df), // 0.0605 * 2^LUX_SCALE
+ LUX_K5: (0x014d), // 0.65 * 2^RATIO_SCALE
+ LUX_B5: (0x0177), // 0.0229 * 2^LUX_SCALE
+ LUX_M5: (0x01dd), // 0.0291 * 2^LUX_SCALE
+ LUX_K6: (0x019a), // 0.80 * 2^RATIO_SCALE
+ LUX_B6: (0x0101), // 0.0157 * 2^LUX_SCALE
+ LUX_M6: (0x0127), // 0.0180 * 2^LUX_SCALE
+ LUX_K7: (0x029a), // 1.3 * 2^RATIO_SCALE
+ LUX_B7: (0x0037), // 0.00338 * 2^LUX_SCALE
+ LUX_M7: (0x002b), // 0.00260 * 2^LUX_SCALE
+ LUX_K8: (0x029a), // 1.3 * 2^RATIO_SCALE
+ LUX_B8: (0x0000), // 0.000 * 2^LUX_SCALE
+ LUX_M8: (0x0000) // 0.000 * 2^LUX_SCALE
+ };
+ */
+ return undefined;
+};
+
+
+TSL.prototype.getLuminosity = function(channel, callback) {
+ var self = this;
+
+ // getLuminosity is asynchronous, as after triggering, the sensor
+ // needs a short time to integrate the data together before it can be
+ // read. As a result, the sensor is initialised and a setTimeout is
+ // set to the readCallback function. The readCallback function should
+ // then collect the data and pass it to 'callback'.
+
+ // Get the luminosity data from the requested channel.
+ var getDataFromChannel = function (ch) {
+
+ // Send a command to the sensor requesting the 16-bit data from
+ // the requested channel.
+ self.i2c.writeTo(
+ self.address,
+ 0x80/*COMMAND_BIT*/ |
+ 0x20/*WORD_BIT*/ |
+ (ch === 1 ? 0x0e/*REG_CHAN1_LOW*/ : 0x0c/*REG_CHAN0_LOW*/));
+
+ // Immediately read the next two bytes from the sensor
+ buf = self.i2c.readFrom(self.address, 2);
+
+ if (self.debug) print (buf);
+
+ // And turn it into a 16-bit value.
+ return (buf[1]<<8) | buf[0];
+ };
+
+ // The timeout should trigger readCallback to collect the data from
+ // the sensor and execute the return callback passed to getLuminosity.
+ var readCallback = function () {
+ var x1, x0, buf;
+
+ // If we're reading visible or infrared, we need the infrared
+ // channel. Visible is calculated using the full spectrum minus
+ // the infrared channel.
+ if(channel != self.config.spectrum.FULLSPECTRUM) {
+ x1 = getDataFromChannel(1);
+ }
+
+ // If we're reading full-spectrum or visible, we need the
+ // full-spectrum channel, for the same reason as above.
+ if(channel != self.config.spectrum.INFRARED) {
+ x0 = getDataFromChannel(0);
+ }
+
+ // Switch off the sensor
+ self.disable();
+
+ // Clear the timeout, unlocking the sensor for future use.
+ self._read_timeout = false;
+
+ // Call the callback with the requested value.
+ switch (channel) {
+ case self.config.spectrum.INFRARED:
+ callback(x1/readCallback.scale);
+ return;
+
+ case self.config.spectrum.VISIBLE:
+ callback((x0 - x1)/readCallback.scale);
+ return;
+
+ default:// case self.config.spectrum.FULLSPECTRUM:
+ callback(x0/readCallback.scale);
+ return;
+ }
+ };
+
+ // If there's already a read timeout set, then another call is still
+ // in progress, so just execute the callback with a null parameter
+ // (error state)
+ if(this._read_timeout) {
+ setTimeout(function () { callback(null); }, 0);
+ this._read_timeout = false;
+ return this;
+ }
+
+ // Otherwise, we're good to go. First thing to do is set the timeout
+ // to something dummy to try to avoid a race condition. We'll replace
+ // it with the real timeout shortly.
+ this._read_timeout = true;
+
+ // Switch on the sensor
+ this.enable();
+
+ // Now that the sensor is set up -- and should be integrating data --
+ // we need to schedule the data collection using a timeout.
+ //
+ // We can also set the scaling factor: the sum of light-things
+ // accumulated over the integration period will be relative to the
+ // time spent integrating, so divide to scale it. These scaling
+ // values and the process to calculate them come from the TSL2561 data
+ // sheet.
+
+ var int_time;
+
+ switch (this.timing) {
+ case this.config.timing._13MS:
+ readCallback.scale = 0.034;
+ int_time = 14;
+ break;
+
+ case this.config.timing._101MS:
+ readCallback.scale = 0.252;
+ int_time = 102;
+ break;
+
+ default:// case this.config.timing._402MS:
+ readCallback.scale = 1;
+ int_time = 403;
+ }
+
+ // Set up a timeout to read the data and execute the callback once
+ // enough time has passed for the integration to occur.
+ this._read_timeout = setTimeout(readCallback, int_time);
+
+ return this;
+};
+
+////////////////////////////////////////////////////////////////////////////
+
+function test() {
+ I2C1.setup({sda:B7, scl:B6});
+ var tsl = new TSL(I2C1);
+ //tsl.debug = true;
+
+ tsl.init(tsl.config.address.FLOAT,
+ tsl.config.timing._402MS,
+ tsl.config.gain._1X);
+
+ setInterval(function () {
+ tsl.getLuminosity(
+ tsl.config.spectrum.VISIBLE,
+ function (x) { print ("L="+x); }
+ );
+ }, 1000);
+}
+
+test();
diff --git a/pool/shard010/JavaScript/0068795_customize1.js b/pool/shard010/JavaScript/0068795_customize1.js
new file mode 100644
index 0000000000000000000000000000000000000000..6e4788d2f486e8ffbaf4d92196c6fa20d5dda515
--- /dev/null
+++ b/pool/shard010/JavaScript/0068795_customize1.js
@@ -0,0 +1,94 @@
+(function($) {
+ $(document).ready(function() {
+ // $('.region-highlighted').width($('body').width());
+ // $( window ).resize(function() {
+ // // $('.region-highlighted').width($('body').width());
+ // var heightP = $(window).height()*1.5 + 'px';
+ // $('.backgroundPoster').height($(window).height()*1.5);
+ // $('.backgroundPoster').css('min-height',heightP);
+ // });
+ console.log($('body').width());
+ $('li.expanded.dropdown ').hover(function() {
+ $(this).find('ul.menu.dropdown-menu').stop(true, true).delay(200).fadeIn(500);
+ }, function() {
+ $(this).find('ul.menu.dropdown-menu').stop(true, true).delay(200).fadeOut(500);
+ });
+
+
+
+ $('#block-ourqualifications .progress-bar').each(function() {
+ $(this).addClass('setWidth');
+ });
+
+ $('#block-ourqualifications .progress-bar').each(function() {
+ var This = this;
+ $(This).waypoint(function() {
+ $(This).removeClass('setWidth');
+ }, {
+ offset: '85%'
+ });
+ });
+ var sparcnetsinformationtechnology = $('#block-sparcnetsinformationtechnology');
+ sparcnetsinformationtechnology.waypoint(function() {
+ sparcnetsinformationtechnology.addClass('zoomInTrans');
+ }, {
+ offset: '75%'
+ });
+ // var creativesolutions = $('#block-creativesolutionstoimproveyourbusinesspresence .block-title');
+ // creativesolutions.addClass('animated zoomIn delay-1000 display');
+ var helpReg = $('.region-help');
+ helpReg.waypoint(function() {
+ helpReg.addClass('animated slideInUp delay-2000 display');
+ }, {
+ offset: '75%'
+ });
+
+ var ourvalues = $('#block-ourvalues');
+ var clientservice = $('#block-clientservices');
+ var pleasepost = $('#block-pleasepostyourresumehere');
+ clientservice.waypoint(function() {
+ ourvalues.addClass('animated slideInUp delay-750 display');
+ clientservice.addClass('animated slideInUp delay-750 display');
+ pleasepost.addClass('animated slideInUp delay-1000 display');
+ }, {
+ offset: '75%'
+ });
+
+
+ var footerL = $('#block-views-block-news-events-block-1-3');
+ var footerM = $('#block-views-block-service-for-client-block-block-1');
+ var footerR = $('#block-contact-3');
+ footerL.waypoint(function() {
+ footerL.addClass('animated fadeInLeft delay-500 display');
+ footerM.addClass('animated fadeInUp delay-500 display');
+ footerR.addClass('animated fadeInRight delay-500 display');
+ }, {
+ offset: '75%'
+ });
+
+ var blockimg1 = $('section#block-images1');
+ var blockimg2 = $('section#block-images2');
+ blockimg1.waypoint(function() {
+ blockimg1.addClass('animated fadeInLeft delay-500 display');
+ blockimg2.addClass('animated fadeInRight delay-500 display');
+ }, {
+ offset: '75%'
+ });
+ });
+
+})(jQuery);
+// var pathImg = 'url('+$('#block-views-block-slideshow-block-1 .img-responsive').attr('src')+') no-repeat';
+// // console.log(pathImg);
+// // $('#block-views-block-slideshow-block-1 .field-content').data('parallax','scroll');
+// $('#block-views-block-slideshow-block-1 .field-content').css("background", pathImg );
+//
+// //
+// $('#block-views-block-slideshow-block-1 .field-content').parallax('50%',0.9);
+
+
+
+// $('#views_slideshow_controls_text_services-block_1 span a').each(function(){
+// var This = $(this);
+// var content = $(This).innerHTML;
+//
+// });
diff --git a/pool/shard010/JavaScript/0068797_bootstrap.js b/pool/shard010/JavaScript/0068797_bootstrap.js
new file mode 100644
index 0000000000000000000000000000000000000000..6a690f95bb7524275d1b80034bced2eb50ac8b3c
--- /dev/null
+++ b/pool/shard010/JavaScript/0068797_bootstrap.js
@@ -0,0 +1,44 @@
+/*
+ * file bootstrap.js
+ * path /common/
+ * purpose container of bootstrap init
+ */
+
+exports = module.exports.main = function () {
+ var express = require('express');
+
+// console.log(basepath);
+
+ var app = express();
+
+ return app;
+}
+
+exports = module.exports.config = function () {
+ var path = require('path');
+ var basepath = path.dirname(process.mainModule.filename);
+
+ app.set('basepath', basepath);
+ app.set('configloc', path.join(basepath, './config/config.conf'));
+
+ //console.log(path.join(basepath,'./config/express.js'));
+ require(path.join(basepath, './config/express.js'));
+ require(path.join(basepath, './config/routes.js'));
+
+ return app;
+}
+
+exports = module.exports.db = function () {
+ // var db = require('mongoose');//,
+ // autoIncrement = require('mongoose-auto-increment');
+ // db.connect('mongodb://localhost/controller');
+ // autoIncrement.initialize(db);
+
+ // setter
+ // app.set('db', db);
+ // app.set('autoIncrement', autoIncrement);
+
+ // app.models = require('../app/model');
+
+ return app;
+}
diff --git a/pool/shard010/JavaScript/0068800_Environment.js b/pool/shard010/JavaScript/0068800_Environment.js
new file mode 100644
index 0000000000000000000000000000000000000000..8ab20488eb8df43fdc45aaf7fa7e9732f53865a0
--- /dev/null
+++ b/pool/shard010/JavaScript/0068800_Environment.js
@@ -0,0 +1,58 @@
+
+var Environment = function ( $core, $control ) {
+
+var self = require( "./rock/RockContent" )( $core, $control );
+
+self.execute = function(){ }
+
+self.remove = function(){
+ //self.core.glob.landscapeLayer.removeChild( rock.display );
+}
+
+self.awake = function( rock ){
+
+ var soul = self.core.soul;
+ var max = soul.toonList.length;
+
+ for ( var i = 0; i < max; i++ )
+ {
+ var toon = soul.toonList[ i ];
+ self.buildToon( toon );
+ }
+
+ self.core.glob.landscapeLayer.addChild( rock.display );
+}
+
+self.buildToon = function( toon ){
+
+ var max;
+ if ( toon.src != null ) max = toon.src.length;
+ if ( toon.frames != null ) max = toon.frames.length;
+ var textureList = [];
+
+ for ( var i = 0; i < max; i++ ){
+ var index = i;
+ if ( toon.frames != null ) index = toon.frames[ i ];
+ if ( toon.frames == null ) index = toon.src[ i ];
+ var texture = PIXI.Texture.fromImage( index );
+ if ( texture != null ) textureList.push( texture );
+ }
+
+ self.buildLandscape( toon, textureList );
+}
+
+self.buildLandscape = function( toon, textureList){
+ var display = new PIXI.MovieClip( textureList );
+ var f = new PIXI.MovieClip( textureList );
+ f.visible = true;
+ if ( toon.y != null ) f.position.y = toon.y;
+ if ( toon.y == null ) f.position.y = 0;
+
+ f.position.x = 0;
+ self.display.addChild(f);
+ }
+
+return self;
+};
+
+exports = module.exports = Environment;
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068802_ImportFileDropzone.js b/pool/shard010/JavaScript/0068802_ImportFileDropzone.js
new file mode 100644
index 0000000000000000000000000000000000000000..285727e169f574c33be8edbfc979f909a9001c46
--- /dev/null
+++ b/pool/shard010/JavaScript/0068802_ImportFileDropzone.js
@@ -0,0 +1,146 @@
+import cuid from 'cuid'
+import Papa from 'papaparse'
+import PropTypes from 'prop-types'
+import {head} from 'ramda'
+import React from 'react'
+import Dropzone from 'react-dropzone'
+import FontAwesome from 'react-fontawesome'
+import styled from 'styled-components'
+import {Box} from '../../presentational/atoms/Box'
+import {CenteredSpinner} from '../../presentational/atoms/CenteredSpinner'
+
+const DropzoneContainer = styled.div`
+ display: flex;
+ justify-content: center;
+`
+
+const DropzoneInside = styled(Dropzone)`
+ width: 150px;
+ height: 150px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ border: 1px dashed rgba(0, 0, 0, 0.4);
+ font-size: 4rem;
+ border-radius: 0.5rem;
+`
+
+export class ImportFileDropzone extends React.Component {
+ static propTypes = {
+ account: PropTypes.shape({
+ name: PropTypes.string.isRequired,
+ }).isRequired,
+ clearImportAccountUuid: PropTypes.func.isRequired,
+ setImportTransactions: PropTypes.func.isRequired,
+ }
+
+ state = {
+ loading: false,
+ errors: null,
+ }
+
+ transformValue = (value, column) => {
+ const result = value.trim()
+
+ if (column === 'amount') {
+ return parseInt(result, 10)
+ }
+
+ return result
+ }
+
+ transformResults(transactions) {
+ return transactions.map(transaction => ({...transaction, importId: cuid()}))
+ }
+
+ onDrop = files => {
+ if (files.length !== 1) {
+ this.setState({errors: ['Please provide exactly one CSV file']})
+ }
+
+ this.setState({loading: true}, () => {
+ Papa.parse(head(files), {
+ header: true,
+ skipEmptyLines: true,
+ transform: this.transformValue,
+ complete: results => {
+ if (results.errors.length > 0) {
+ this.setState({loading: false, errors: results.errors})
+ return
+ }
+
+ this.setState({loading: false})
+ this.props.setImportTransactions(this.transformResults(results.data))
+ },
+ })
+ })
+ }
+
+ render() {
+ const {account, clearImportAccountUuid} = this.props
+ const {loading, errors} = this.state
+
+ if (loading) {
+ return
+ }
+
+ return (
+
+
+
+
+ {errors && (
+
+
+ {errors.map((error, i) => (
+ {error.message}
+ ))}
+
+
+ )}
+
+
+ Importing transactions for account: {account.name}
+
+ Clear account
+
+
+
+
+ One CSV file
+ Must be UTF-8
+ First line must be a header row
+
+ One line needs to be amount
+
+
+ One line needs to be date
+
+
+ You can have a payee_uuid line
+
+
+ You can have a payee line that will be used to match
+ payees by name
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ )
+ }
+}
diff --git a/pool/shard010/JavaScript/0068806_sass.worker.js b/pool/shard010/JavaScript/0068806_sass.worker.js
new file mode 100644
index 0000000000000000000000000000000000000000..3a1cb372b2de539760ce2f317021884b4ba0f9a0
--- /dev/null
+++ b/pool/shard010/JavaScript/0068806_sass.worker.js
@@ -0,0 +1,96 @@
+/*! sass.js - v0.6.3 - web worker - 2015-03-03 */(function (root, factory) {
+ 'use strict';
+ if (typeof define === 'function' && define.amd) {
+ // AMD. Register as an anonymous module.
+ define([], factory);
+ } else if (typeof exports === 'object') {
+ // Node. Does not work with strict CommonJS, but
+ // only CommonJS-like enviroments that support module.exports,
+ // like Node.
+ module.exports = factory();
+ } else {
+ // Browser globals (root is window)
+ root.Sass = factory();
+ }
+}(this, function () {
+ 'use strict';
+ /*global Worker*/
+
+ var Sass = {
+ _worker: null,
+ _callbacks: {},
+
+ style: {
+ nested: 0,
+ expanded: 1,
+ compact: 2,
+ compressed: 3
+ },
+ comments: {
+ 'none': 0,
+ 'default': 1
+ },
+
+ _dispatch: function(options, callback) {
+ options.id = 'cb' + Date.now() + Math.random();
+ Sass._callbacks[options.id] = callback;
+ Sass._worker.postMessage(options);
+ },
+
+ writeFile: function(filename, text, callback) {
+ Sass._dispatch({
+ command: 'writeFile',
+ filename: filename,
+ text: text
+ }, callback);
+ },
+
+ readFile: function(filename, callback) {
+ Sass._dispatch({
+ command: 'readFile',
+ filename: filename
+ }, callback);
+ },
+
+ listFiles: function(callback) {
+ Sass._dispatch({
+ command: 'listFiles'
+ }, callback);
+ },
+
+ removeFile: function(filename, callback) {
+ Sass._dispatch({
+ command: 'removeFile',
+ filename: filename
+ }, callback);
+ },
+
+ options: function(options, callback) {
+ Sass._dispatch({
+ command: 'options',
+ options: options
+ }, callback);
+ },
+
+ compile: function(text, callback) {
+ Sass._dispatch({
+ command: 'compile',
+ text: text
+ }, callback);
+ },
+
+ initialize: function(workerUrl) {
+ if (Sass._worker) {
+ throw new Error('Sass Worker is already initalized');
+ }
+
+ Sass._worker = new Worker(workerUrl);
+ Sass._worker.addEventListener('message', function(event) {
+ Sass._callbacks[event.data.id] && Sass._callbacks[event.data.id](event.data.result);
+ delete Sass._callbacks[event.data.id];
+ }, false);
+ }
+ };
+
+ return Sass;
+}));
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068808_url-helper.js b/pool/shard010/JavaScript/0068808_url-helper.js
new file mode 100644
index 0000000000000000000000000000000000000000..09547640fdef842a02c563315e42d117b7bcbf3d
--- /dev/null
+++ b/pool/shard010/JavaScript/0068808_url-helper.js
@@ -0,0 +1,45 @@
+// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
+'use strict';
+var expect = require('chai').expect;
+var UrlHelper = require('../services/url-helper');
+
+describe('URL Helper', function() {
+ var middleware1 = {
+ priority: 1,
+ getUrl: function(id) {
+ if (id === 'both') return '/both1';
+ if (id === 'foo') return '/foo';
+ return null;
+ }
+ };
+ var middleware2 = {
+ priority: 2,
+ getUrl: function(id) {
+ if (id === 'both') return '/both2';
+ if (id === 'bar') return '/bar';
+ return null;
+ },
+ getId: function(url) {
+ return 'id:' + url;
+ }
+ };
+ var scope = {
+ getServices: function() {return [middleware1, middleware2];}
+ };
+
+ it('can give the URL of content items', function() {
+ var urlHelper = new UrlHelper(scope);
+
+ expect(urlHelper.getUrl('null')).to.equal('/');
+ expect(urlHelper.getUrl('foo')).to.equal('/foo');
+ expect(urlHelper.getUrl('bar')).to.equal('/bar');
+ expect(urlHelper.getUrl('both')).to.equal('/both1');
+ });
+
+ it('can give the ID for the main content item behind a URL', function() {
+ var urlHelper = new UrlHelper(scope);
+
+ expect(urlHelper.getId('/')).to.equal('id:/');
+ expect(urlHelper.getId('/foo')).to.equal('id:/foo');
+ });
+});
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068810_sexp-parser.js b/pool/shard010/JavaScript/0068810_sexp-parser.js
new file mode 100644
index 0000000000000000000000000000000000000000..fd5aa923f5f235cf3f4738af769f46b23b587991
--- /dev/null
+++ b/pool/shard010/JavaScript/0068810_sexp-parser.js
@@ -0,0 +1,53 @@
+/*
+ * This file is part of yoob.js version 0.9
+ * Available from https://github.com/catseye/yoob.js/
+ * This file is in the public domain. See http://unlicense.org/ for details.
+ */
+if (window.yoob === undefined) yoob = {};
+
+/*
+ * A simple S-expression parser. Note that it produces yoob.Trees rather
+ * than cons cells (pairs), so parsing "(a b c)" will yield a single yoob.Tree
+ * node with three children.
+ *
+ * Note also that atomic symbols are restricted to alphanumeric characters.
+ *
+ * This module requires that you load yoob.Tree and yoob.Scanner first.
+ *
+ * This module is really intended more for you to copy and modify (and maybe
+ * extend into a parser for a more complex language) than to use directly.
+ */
+yoob.SexpParser = function() {
+ this.scanner = undefined;
+
+ this.init = function(text) {
+ this.scanner = (new yoob.Scanner()).init({
+ table: [
+ ['paren', "^(\\(|\\))"],
+ ['atom', "^([a-zA-Z]\\w*)"]
+ ]
+ });
+ this.scanner.reset(text);
+ };
+
+ /*
+ * SExp ::= Atom | "(" {SExpr} ")".
+ */
+ this.parse = function(text) {
+ if (this.scanner.onType('atom')) {
+ var x = this.scanner.token;
+ this.scanner.scan();
+ return (new yoob.Tree('atom')).setValue(x);
+ } else if (this.scanner.consume('(')) {
+ var children = []
+ while (!this.scanner.on(')') && !this.scanner.onType('EOF')) {
+ children.push(this.parse());
+ }
+ this.scanner.expect(')');
+ return new yoob.Tree('list', children);
+ } else {
+ /* TODO: register some kind of error */
+ this.scanner.scan();
+ }
+ };
+};
diff --git a/pool/shard010/JavaScript/0068811_VideoClicks.js b/pool/shard010/JavaScript/0068811_VideoClicks.js
new file mode 100644
index 0000000000000000000000000000000000000000..8e1524e18f2f717cdcf1a276cc35f90fc019efac
--- /dev/null
+++ b/pool/shard010/JavaScript/0068811_VideoClicks.js
@@ -0,0 +1,28 @@
+'use strict';
+
+var utilities = require('../../utils/utilityFunctions');
+var xml = require('../../utils/xml');
+
+function VideoClicks(videoClickJTree) {
+ if (!(this instanceof VideoClicks)) {
+ return new VideoClicks(videoClickJTree);
+ }
+
+ this.clickThrough = xml.keyValue(videoClickJTree.clickThrough);
+ this.clickTrackings = parseClickTrackings(videoClickJTree.clickTracking);
+ this.customClicks = parseClickTrackings(videoClickJTree.customClick);
+
+ /*** Local functions ***/
+ function parseClickTrackings(trackingData) {
+ var clickTrackings = [];
+ if (trackingData) {
+ trackingData = utilities.isArray(trackingData) ? trackingData : [trackingData];
+ trackingData.forEach(function (clickTrackingData) {
+ clickTrackings.push(xml.keyValue(clickTrackingData));
+ });
+ }
+ return clickTrackings;
+ }
+}
+
+module.exports = VideoClicks;
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068814_about.js b/pool/shard010/JavaScript/0068814_about.js
new file mode 100644
index 0000000000000000000000000000000000000000..e35b4797d5f172f15e864533ab55c53490eee0b2
--- /dev/null
+++ b/pool/shard010/JavaScript/0068814_about.js
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2019 ThoughtWorks, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import Stream from "mithril/stream";
+
+export const About = function (data) {
+ this.name = Stream(data.name);
+ this.version = Stream(data.version);
+ this.targetGoVersion = Stream(data.targetGoVersion);
+ this.description = Stream(data.description);
+ this.targetOperatingSystems = Stream(data.targetOperatingSystems);
+ this.vendor = Stream(data.vendor);
+};
+
+About.fromJSON = (data = {}) => new About({
+ name: data.name,
+ version: data.version,
+ targetGoVersion: data.target_go_version,
+ description: data.description,
+ targetOperatingSystems: data.target_operating_systems,
+ vendor: About.Vendor.fromJSON(data.vendor)
+});
+
+About.Vendor = function ({name, url}) {
+ this.name = Stream(name);
+ this.url = Stream(url);
+};
+
+About.Vendor.fromJSON = (data = {}) => new About.Vendor({
+ name: data.name,
+ url: data.url
+});
+
diff --git a/pool/shard010/JavaScript/0068816_ping.js b/pool/shard010/JavaScript/0068816_ping.js
new file mode 100644
index 0000000000000000000000000000000000000000..4727358924cbf976699120eb10671329946ce891
--- /dev/null
+++ b/pool/shard010/JavaScript/0068816_ping.js
@@ -0,0 +1,16 @@
+'use strict';
+
+function setup(bot){
+ var config = bot.config.modules.ping;
+ bot.commands.register('ping', function(message){
+ if(config.enabled){
+ message.reply('pong!');
+ }
+ });
+ for(let role of config.allowedRoles){
+ bot.commands.allowRole('ping', role);
+ }
+}
+
+exports.setup = setup;
+exports.name = "ping";
diff --git a/pool/shard010/JavaScript/0068820_user-service.js b/pool/shard010/JavaScript/0068820_user-service.js
new file mode 100644
index 0000000000000000000000000000000000000000..b98a926c051e1d478e04e88bb3f267fd0a01c240
--- /dev/null
+++ b/pool/shard010/JavaScript/0068820_user-service.js
@@ -0,0 +1,87 @@
+var userModuleService = angular.module('firekitApp.user.services',[]);
+
+userModuleService.service('UserService',['$log', '$q', '$firebaseAuth', 'FBURL', 'User', 'AUTO_ANON', function($log, $q, $firebaseAuth, FBURL, User, AUTO_ANON) {
+
+ var self, auth, _authObj, currentUser, previousUser, firebaseRef;
+ firebaseRef = new Firebase(FBURL);
+ _authObj = $firebaseAuth(firebaseRef);
+ self = {
+ init: function(successCb, errorCb) {
+ if (_authObj.$getAuth()) {
+ User(_authObj.$getAuth()).then(function(userData){
+ currentUser = userData;
+ $log.debug("User loaded", currentUser);
+ });
+ } else {
+ if(AUTO_ANON === true) {
+ self.loginAnonymously().then(function(authData){
+ User(authData).then(function(userData){
+ currentUser = userData;
+ $log.debug("User loaded", currentUser);
+ });
+ });
+ }
+ }
+ },
+ requireAuth: function () {
+ return _authObj.$requireAuth();
+ },
+ getRef: function() {
+ return currentUser.$ref();
+ },
+ createAndLoginUserWithPassword: function(user, successCb, errorCb){
+ self.logout();
+ _authObj.$createUser({
+ email: user.email,
+ password: user.password
+ }).then(function(userData) {
+ $log.debug("Created user:" + userData.uid);
+ return _authObj.$authWithPassword({
+ email: user.email,
+ password: user.password
+ });
+ }).then(function(authData) {
+ self.init();
+ if(successCb) successCb();
+ }).catch(function(error) {
+ $log.error("Error: ", error);
+ });
+ },
+ loginWithPassword: function(user, successCb, errorCb) {
+ self.logout();
+ _authObj.$authWithPassword({
+ email: user.email,
+ password: user.password
+ }).then(function(authData) {
+ $log.debug("User", authData.uid, "logged in.");
+ self.init();
+ if(successCb) successCb();
+ }).catch(function(error) {
+ $log.error("User login failed:", error);
+ if(errorCb) errorCb(error);
+ });
+ },
+ loginAnonymously: function() {
+ var deferred = $q.defer();
+ _authObj.$authAnonymously().then(function(authData) {
+ console.debug("User ", authData.uid, " logged in.");
+ deferred.resolve(authData);
+ }).catch(function(error) {
+ console.error("Authenticating anonymous user failed:", error);
+ deferred.reject(error);
+ });
+ return deferred.promise;
+ },
+ logout: function(successCb, errorCb) {
+ if (_authObj.$getAuth()) {
+ currentUser.$logout();
+ $log.debug("User successfully logged out.");
+ if(successCb) successCb();
+ } else {
+ $log.debug("User tried to logout but is not logged in.");
+ if(errorCb) errorCb();
+ }
+ }
+ };
+ return self;
+}]);
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068825_browser_newtab_drop_preview.js b/pool/shard010/JavaScript/0068825_browser_newtab_drop_preview.js
new file mode 100644
index 0000000000000000000000000000000000000000..61c163d9debada0e8e8af2cad3437c1a195c6077
--- /dev/null
+++ b/pool/shard010/JavaScript/0068825_browser_newtab_drop_preview.js
@@ -0,0 +1,22 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*
+ * These tests ensure that the drop preview correctly arranges sites when
+ * dragging them around.
+ */
+function runTests() {
+ // the first three sites are pinned - make sure they're re-arranged correctly
+ yield setLinks("0,1,2,3,4,5,6,7,8");
+ setPinnedLinks("0,1,2,,,5");
+
+ yield addNewTabPageTab();
+ checkGrid("0p,1p,2p,3,4,5p,6,7,8");
+
+ let cw = getContentWindow();
+ cw.gDrag._draggedSite = getCell(0).site;
+ let sites = cw.gDropPreview.rearrange(getCell(4));
+ cw.gDrag._draggedSite = null;
+
+ checkGrid("3,1p,2p,4,0p,5p,6,7,8", sites);
+}
diff --git a/pool/shard010/JavaScript/0068829_photo_upload.js b/pool/shard010/JavaScript/0068829_photo_upload.js
new file mode 100644
index 0000000000000000000000000000000000000000..3733c1c4a1ac864b2e4f1753f9db2e0b625ced64
--- /dev/null
+++ b/pool/shard010/JavaScript/0068829_photo_upload.js
@@ -0,0 +1,92 @@
+var batch_upload = function(gallery) {
+ var filelist;
+ var files = [];
+ var file;
+ var uploading = 0;
+ var url = '/admin/xhr/photo-upload/';
+ var $photos_group = $('div#photos-group');
+ var $batch_upload = $('
Batch Upload ');
+ var $batch_inner = $('
');
+ var $upload_area = $(' ');
+ var $upload_button = $('Upload ');
+ var $progress_bar = $('
');
+ var $num_left = $('
');
+
+
+ var update_num_left = function() {
+ $num_left.text('Uploading: '+ file.name + ', Photos left: ' + files.length);
+ }
+
+ var show_progress = function(percent, callback) {
+ var duration = 50;
+ if (percent == 0) {
+ duration = 0;
+ }
+ $progress_bar.stop(true, true).animate({
+ width: percent + '%'
+ }, duration, 'swing', callback);
+ }
+ var upload_files = function() {
+ show_progress(0);
+ if (files.length == 0) {
+ location.reload();
+ return true
+ }
+ file = files.pop();
+ update_num_left();
+ var form_data = new FormData();
+ form_data.append('image', file);
+ form_data.append('gallery', gallery);
+ var xhr = new XMLHttpRequest();
+ xhr.open('POST', url, true);
+ xhr.upload.onprogress = function(event) {
+ if (event.lengthComputable) {
+ var percent = (event.loaded / event.total) * 100;
+ show_progress(percent);
+ }
+ };
+ xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
+ xhr.onreadystatechange = function() {
+ if (xhr.readyState === 4 && xhr.status === 200) {
+ var response = $.parseJSON(xhr.response);
+ if (response == 'OK') {
+ show_progress(100, upload_files);
+ } else {
+ alert("Error!");
+ }
+ }
+ };
+ xhr.send(form_data);
+ form_data = new FormData();
+ return true;
+ };
+
+ $photos_group.prepend($batch_upload);
+ $batch_upload.append($batch_inner);
+ $batch_inner.append($upload_area);
+ $batch_inner.append($upload_button);
+ $batch_inner.append($num_left);
+ $batch_inner.append($progress_bar);
+
+ $upload_area.on('change', function(event) {
+ filelist = event.target.files;
+ });
+ $upload_button.on('click', function(event) {
+ event.preventDefault();
+ $.each(filelist, function() {
+ files.push(this);
+ });
+ upload_files();
+ });
+};
+$(function() {
+ var path = window.location.pathname;
+
+ if(path.substr(-1) == '/') {
+ path = path.substr(0, path.length - 1);
+ }
+ gallery = path.split('/').pop();
+ if (gallery != 'add') {
+ batch_upload(gallery);
+ }
+});
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068830_browserchannel.js b/pool/shard010/JavaScript/0068830_browserchannel.js
new file mode 100644
index 0000000000000000000000000000000000000000..6004b62b7ee96dde2aaf8355fddd42e735795008
--- /dev/null
+++ b/pool/shard010/JavaScript/0068830_browserchannel.js
@@ -0,0 +1,52 @@
+var p;
+goog.provide('bc');
+goog.require('goog.net.BrowserChannel');
+goog.require('goog.net.BrowserChannel.Handler');
+goog.require('goog.net.BrowserChannel.Error');
+goog.require('goog.net.BrowserChannel.State');
+p = goog.net.BrowserChannel.prototype;
+p['getChannelDebug'] = p.getChannelDebug;
+p['setChannelDebug'] = p.setChannelDebug;
+p['connect'] = p.connect;
+p['disconnect'] = p.disconnect;
+p['getSessionId'] = p.getSessionId;
+p['getExtraHeaders'] = p.getExtraHeaders;
+p['setExtraHeaders'] = p.setExtraHeaders;
+p['getHandler'] = p.getHandler;
+p['setHandler'] = p.setHandler;
+p['getAllowHostPrefix'] = p.getAllowHostPrefix;
+p['setAllowHostPrefix'] = p.setAllowHostPrefix;
+p['getAllowChunkedMode'] = p.getAllowChunkedMode;
+p['setAllowChunkedMode'] = p.setAllowChunkedMode;
+p['isBuffered'] = p.isBuffered;
+p['sendMap'] = p.sendMap;
+p['setFailFast'] = p.setFailFast;
+p['isClosed'] = p.isClosed;
+p['getState'] = p.getState;
+p['getLastStatusCode'] = p.getLastStatusCode;
+goog.require('goog.json');
+p['send'] = function(message) {
+ return this.sendMap({
+ 'JSON': goog.json.serialize(message)
+ });
+};
+goog.net.BrowserChannel['Handler'] = goog.net.BrowserChannel.Handler;
+goog.net.BrowserChannel['Error'] = {
+ 'OK': goog.net.BrowserChannel.Error.OK,
+ 'REQUEST_FAILED': goog.net.BrowserChannel.Error.REQUEST_FAILED,
+ 'LOGGED_OUT': goog.net.BrowserChannel.Error.LOGGED_OUT,
+ 'NO_DATA': goog.net.BrowserChannel.Error.NO_DATA,
+ 'UNKNOWN_SESSION_ID': goog.net.BrowserChannel.Error.UNKNOWN_SESSION_ID,
+ 'STOP': goog.net.BrowserChannel.Error.STOP,
+ 'NETWORK': goog.net.BrowserChannel.Error.NETWORK,
+ 'BLOCKED': goog.net.BrowserChannel.Error.BLOCKED,
+ 'BAD_DATA': goog.net.BrowserChannel.Error.BAD_DATA,
+ 'BAD_RESPONSE': goog.net.BrowserChannel.Error.BAD_RESPONSE
+};
+goog.net.BrowserChannel['State'] = {
+ 'CLOSED': goog.net.BrowserChannel.State.CLOSED,
+ 'INIT': goog.net.BrowserChannel.State.INIT,
+ 'OPENING': goog.net.BrowserChannel.State.OPENING,
+ 'OPENED': goog.net.BrowserChannel.State.OPENED
+};
+goog.exportSymbol('goog.net.BrowserChannel', goog.net.BrowserChannel, typeof exports !== "undefined" && exports !== null ? exports : window);
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068832_dummyapi.js b/pool/shard010/JavaScript/0068832_dummyapi.js
new file mode 100644
index 0000000000000000000000000000000000000000..2a956948eb0fff9ce604cc930ddda87b550aa336
--- /dev/null
+++ b/pool/shard010/JavaScript/0068832_dummyapi.js
@@ -0,0 +1,48 @@
+/*
+* Dummy SCORM API
+*/
+
+function GenericAPIAdaptor(){
+ this.LMSInitialize = LMSInitializeMethod;
+ this.LMSGetValue = LMSGetValueMethod;
+ this.LMSSetValue = LMSSetValueMethod;
+ this.LMSCommit = LMSCommitMethod;
+ this.LMSFinish = LMSFinishMethod;
+ this.LMSGetLastError = LMSGetLastErrorMethod;
+ this.LMSGetErrorString = LMSGetErrorStringMethod;
+ this.LMSGetDiagnostic = LMSGetDiagnosticMethod;
+}
+/*
+* LMSInitialize.
+*/
+function LMSInitializeMethod(parameter){return "true";}
+/*
+* LMSFinish.
+*/
+function LMSFinishMethod(parameter){return "true";}
+/*
+* LMSCommit.
+*/
+function LMSCommitMethod(parameter){return "true";}
+/*
+* LMSGetValue.
+*/
+function LMSGetValueMethod(element){return "";}
+/*
+* LMSSetValue.
+*/
+function LMSSetValueMethod(element, value){return "true";}
+/*
+* LMSGetLastErrorString
+*/
+function LMSGetErrorStringMethod(errorCode){return "No error";}
+/*
+* LMSGetLastError
+*/
+function LMSGetLastErrorMethod(){return "0";}
+/*
+* LMSGetDiagnostic
+*/
+function LMSGetDiagnosticMethod(errorCode){return "No error. No errors were encountered. Successful API call.";}
+
+var API = new GenericAPIAdaptor;
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068834_bulmawp.js b/pool/shard010/JavaScript/0068834_bulmawp.js
new file mode 100644
index 0000000000000000000000000000000000000000..cfebab364a9b79cc2f6aeb3ad30b20cae8104fb8
--- /dev/null
+++ b/pool/shard010/JavaScript/0068834_bulmawp.js
@@ -0,0 +1,25 @@
+document.addEventListener('DOMContentLoaded', function () {
+
+ // Get all "navbar-burger" elements
+ var $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0);
+
+ // Check if there are any nav burgers
+ if ($navbarBurgers.length > 0) {
+
+ // Add a click event on each of them
+ $navbarBurgers.forEach(function ($el) {
+ $el.addEventListener('click', function () {
+
+ // Get the target from the "data-target" attribute
+ var target = $el.dataset.target;
+ var $target = document.getElementById(target);
+
+ // Toggle the class on both the "navbar-burger" and the "navbar-menu"
+ $el.classList.toggle('is-active');
+ $target.classList.toggle('is-active');
+
+ });
+ });
+ }
+
+});
diff --git a/pool/shard010/JavaScript/0068836_script.js b/pool/shard010/JavaScript/0068836_script.js
new file mode 100644
index 0000000000000000000000000000000000000000..8c1b34f57bb5f5c5dc0e99090d313a9886280104
--- /dev/null
+++ b/pool/shard010/JavaScript/0068836_script.js
@@ -0,0 +1,39 @@
+let observer = new IntersectionObserver(function (observables) {
+ observables.forEach(function (observable) {
+ if (observable.intersectionRatio > 0.5) {
+ observable.target.classList.remove('hidden')
+ console.log('remove hidden');
+ observer.unobserve(observable.target)
+ }
+ })
+}, {
+ threshold: [0.5]
+});
+
+
+let cards = document.querySelectorAll('.card')
+for (var i = 0, len = cards.length; i < len; i++) {
+ cards[i].classList.add('hidden')
+ cards[i].classList.add('up')
+ observer.observe(cards[i])
+}
+
+let rigthItems = document.querySelectorAll('.right')
+for (var i = 0, len = rigthItems.length; i < len; i++) {
+ rigthItems[i].classList.add('hidden')
+ rigthItems[i].classList.add('up')
+ observer.observe(rigthItems[i])
+}
+
+let leftItems = document.querySelectorAll('.left')
+for (var i = 0, len = leftItems.length; i < len; i++) {
+ leftItems[i].classList.add('hidden')
+ leftItems[i].classList.add('up')
+ observer.observe(leftItems[i])
+}
+
+let foot = document.querySelector('#foot')
+foot.classList.add('hidden')
+foot.classList.add('up')
+observer.observe(foot)
+
diff --git a/pool/shard010/JavaScript/0068837_basic-usage-2.js b/pool/shard010/JavaScript/0068837_basic-usage-2.js
new file mode 100644
index 0000000000000000000000000000000000000000..6fb5ece009d02cb12f5b9800c21e48f4e7929068
--- /dev/null
+++ b/pool/shard010/JavaScript/0068837_basic-usage-2.js
@@ -0,0 +1,50 @@
+angular.module( 'app' ).config( function( $rootScope, $q ) {
+
+ fakeHttp( { url: 'stuff' } ).then(
+ // success/resolve callback
+ function( response ) {
+ $rootScope.response = response;
+ $rootScope.rejectedResponse = undefined;
+ },
+ // error/reject callback
+ function( rejection ) {
+ $rootScope.response = undefined;
+ $rootScope.rejectedResponse = response;
+ }
+ );
+
+ // initialize some odds where mostly, requests will not fail
+ $rootScope.communicationOdds = 0.75;
+ $rootScope.authenticationOdds = 0.75;
+
+ function fakeHttp( request ) {
+ var deferredResponse = $q.defer();
+
+ setTimeout( function() {
+
+ var response = { request: request };
+
+ var communicationSucceeded = Math.random() < $rootScope.communicationOdds;
+ var authenticationSucceeded = Math.random() < $rootScope.authenticationOdds;
+
+ // Sometimes, both communication and authentication succeed
+ if ( communicationSucceeded && authenticationSucceeded ) {
+ response.status = 200;
+
+ // So we resolve to the response
+ deferredResponse.resolve( response );
+ }
+ // Sometimes, one or the other fail:
+ else {
+ response.status = communicationSucceeded ? 401 : 0;
+
+ // So we result in a rejected response
+ deferredResponse.reject( response );
+ }
+
+ }, ( 2 - Math.random() ) * 1000 ); // wait between 1 and 2 seconds
+
+ return deferredResponse.promise;
+ }
+
+} );
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068840_event.js b/pool/shard010/JavaScript/0068840_event.js
new file mode 100644
index 0000000000000000000000000000000000000000..984dca58e981065cc7f840c1866c6393fd61073b
--- /dev/null
+++ b/pool/shard010/JavaScript/0068840_event.js
@@ -0,0 +1,71 @@
+define(['jquery'], function($){
+
+ return {
+
+ add: function(title, date, desc, photo, category, location){
+ var deferred = $.Deferred();
+ var Event = Parse.Object.extend("Event");
+ var event = new Event();
+ event.set("title", title);
+ event.set("date", date);
+ event.set("description", desc);
+ event.set("photo", photo);
+
+ if(location) {
+ var point = new Parse.GeoPoint({latitude: location.lat, longitude: location.lng});
+ event.set("location", point);
+ }
+ console.log(location);
+ if(category){
+ event.set("category", category);
+ }
+ event.setACL(new Parse.ACL(Parse.User.current()));
+ event.save(null,{
+ success: deferred.resolve,
+ error: deferred.reject
+ });
+ return deferred.promise();
+ },
+
+ edit: function(event){
+ var deferred = $.Deferred();
+ event.save(null, {
+ success: deferred.resolve,
+ error: deferred.reject
+ });
+ return deferred.promise();
+ },
+
+ getAll: function(){
+ var deferred = $.Deferred();
+ var Event = Parse.Object.extend("Event");
+ var query = new Parse.Query(Event);
+ query.find({
+ success: deferred.resolve,
+ error: deferred.reject
+ });
+ return deferred.promise();
+ },
+
+ remove: function(event){
+ var deferred = $.Deferred();
+ event.destroy({
+ success: deferred.resolve,
+ error: deferred.reject
+ });
+ return deferred.promise();
+ },
+
+ get: function(id){
+ var deferred = $.Deferred();
+ var Event = Parse.Object.extend("Event");
+ var query = new Parse.Query(Event);
+ query.get(id, {
+ success: deferred.resolve,
+ error: deferred.reject
+ });
+ return deferred.promise();
+ }
+ };
+
+});
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068845_fb-incubator.js b/pool/shard010/JavaScript/0068845_fb-incubator.js
new file mode 100644
index 0000000000000000000000000000000000000000..0b889b8af13f8c9782582e5f9e0485ed84056563
--- /dev/null
+++ b/pool/shard010/JavaScript/0068845_fb-incubator.js
@@ -0,0 +1,39 @@
+//Progress bar
+$('.next').click(function(){
+
+ var nextId = $(this).parents('.tab-pane').next().attr("id");
+ $('[href=#'+nextId+']').tab('show');
+ return false;
+
+})
+
+$('.prev').click(function(){
+
+ var prevId = $(this).parents('.tab-pane').prev().attr("id");
+ $('[href=#'+prevId+']').tab('show');
+ return false;
+
+})
+
+$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
+
+ var step = $(e.target).data('step');
+ var percent = (parseInt(step) / 3) * 100;
+
+ $('.progress-bar').css({width: percent + '%'});
+ $('.progress-bar').text("Step " + step + " of 3");
+
+})
+
+$('.first').click(function(){
+
+ $('#stepper a:first').tab('show')
+
+})
+
+//Google font
+WebFont.load({
+ google: {
+ families: ['Work Sans', 'Roboto', 'Bangers', 'Orbitron', 'Pacifico', 'Passion One', 'Yanone Kaffeesatz', 'Montserrat', 'Fjalla One', 'Oswald', 'Open Sans']
+ }
+ });
diff --git a/pool/shard010/JavaScript/0068846_struct-skip.js b/pool/shard010/JavaScript/0068846_struct-skip.js
new file mode 100644
index 0000000000000000000000000000000000000000..9f7156ce3d54c644bbfbe5722e90a504c76efe44
--- /dev/null
+++ b/pool/shard010/JavaScript/0068846_struct-skip.js
@@ -0,0 +1,166 @@
+// Copyright (c) 2020 Uber Technologies, Inc.
+//
+// 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.
+
+'use strict';
+
+var test = require('tape');
+
+var Buffer = require('buffer').Buffer;
+var Thrift = require('../thrift').Thrift;
+var fs = require('fs');
+var path = require('path');
+var source = fs.readFileSync(path.join(__dirname, 'struct.thrift'), 'utf-8');
+var thrift = new Thrift({source: source});
+
+var Health = thrift.$Health;
+
+test('skip void', function t(assert) {
+ var result = Health.rw.readFrom((Buffer.from || Buffer)([
+ 0x02, // type:1 -- 2 -- BOOL
+ 0x00, 0x02, // id:2 -- 2 -- WHAT EVEN IS!?
+ 0x00, // bool:1
+
+ 0x00 // typeid:1 -- 0 -- STOP
+ ]), 0);
+ if (result.err) {
+ return assert.end(result.err);
+ }
+ assert.deepEqual(result.value, new Health());
+ assert.end();
+});
+
+test('string', function t(assert) {
+ var result = Health.rw.readFrom((Buffer.from || Buffer)([
+ 11, // typeid:1 -- 11 -- STRING
+ 0x00, 0x02, // id:2 -- 2 -- WHAT EVEN IS!?
+ 0x00, 0x00, 0x00, 0x02, // len~4
+ 0x20, 0x20, // ' '
+ 0x00 // typeid:1 -- 0 -- STOP
+ ]), 0);
+ if (result.err) {
+ return assert.end(result.err);
+ }
+ assert.deepEqual(result.value, new Health());
+ assert.end();
+});
+
+test('struct', function t(assert) {
+ var result = Health.rw.readFrom((Buffer.from || Buffer)([
+ 12, // typeid:1 -- 12 -- STRUCT
+ 0x00, 0x02, // id:2 -- 2 -- ?
+ 11, // typeid:1 -- 11 -- STRING
+ 0x00, 0x01, // fieldid:2 -- 1 -- ?
+ 0x00, 0x00, 0x00, 0x02, // len~4
+ 0x20, 0x20, // ' '
+ 0x00, // typeid:1 -- 0 -- STOP
+ 0x00 // typeid:1 -- 0 -- STOP
+ ]), 0);
+ if (result.err) {
+ return assert.end(result.err);
+ }
+ assert.deepEqual(result.value, new Health());
+ assert.end();
+});
+
+test('map', function t(assert) {
+ var result = Health.rw.readFrom((Buffer.from || Buffer)([
+ 0x0d, // typeid:1 -- 13, map
+ 0x00, 0x02, // id:2 -- 2 UNKNOWN
+
+ // Thus begins a large map
+ 0x0b, // key_type:1 -- string @ 4
+ 0x0c, // val_type:1 -- struct
+ 0x00, 0x00, 0x00, 0x02, // length:4 -- 2
+ // --
+ 0x00, 0x00, 0x00, 0x04, // key[0] str_len:4 -- 4 @ 10
+ 0x6b, 0x65, 0x79, 0x30, // key[0] chars -- "key0" @ 14
+ 0x0c, // val[0] type:1 -- struct @ 18
+ 0x00, 0x01, // val[0] id:2 -- 1 @ 19
+ 0x08, // val[0] > type:1 -- i32 @ 21
+ 0x00, 0x01, // val[0] > id:2 -- 1 @ 22
+ 0x00, 0x00, 0x00, 0x14, // val[0] > Int32BE -- 20 @ 24
+ 0x00, // val[0] > type:1 -- stop @ 25
+ 0x0c, // val[0] type:1 -- struct @ 26
+ 0x00, 0x02, // val[0] id:2 -- 2 @ 27
+ 0x0b, // val[0] > type:1 -- string @ 29
+ 0x00, 0x01, // val[0] > id:2 -- 1 @ 30
+ 0x00, 0x00, 0x00, 0x04, // val[0] > str_len:4 -- 4 @ 32
+ 0x73, 0x74, 0x72, 0x32, // val[0] > chars -- "str2" @ 36
+ 0x00, // val[0] > type:1 -- stop @ 40
+ 0x00, // val[0] > type:1 -- stop
+ // --
+ 0x00, 0x00, 0x00, 0x04, // key[1] str_len:4 -- 4
+ 0x6b, 0x65, 0x79, 0x31, // key[1] chars -- "key1"
+ 0x0c, // val[1] type:1 -- struct
+ 0x00, 0x01, // val[1] id:2 -- 1
+ 0x08, // val[1] > type:1 -- i32
+ 0x00, 0x01, // val[1] > id:2 -- 1
+ 0x00, 0x00, 0x00, 0x0a, // val[1] > Int32BE -- 10
+ 0x00, // val[1] > type:1 -- stop
+ 0x0c, // val[1] type:1 -- struct
+ 0x00, 0x02, // val[1] id:2 -- 2
+ 0x0b, // val[1] > type:1 -- string
+ 0x00, 0x01, // val[1] > id:2 -- 1
+ 0x00, 0x00, 0x00, 0x04, // val[1] > str_len:4 -- 4
+ 0x73, 0x74, 0x72, 0x31, // val[1] > chars -- "str1"
+ 0x00, // val[1] > type:1 -- stop
+ 0x00, // val[1] > type:1 -- stop
+ // Thus ends the map
+
+ 0x00 // typeid:1 -- 0 STOP
+ ]), 0);
+ if (result.err) {
+ return assert.end(result.err);
+ }
+ assert.deepEqual(result.value, new Health());
+ assert.end();
+});
+
+test('list', function t(assert) {
+ var result = Health.rw.readFrom((Buffer.from || Buffer)([
+ 0x02, // type:1 -- 2 BOOL
+ 0x00, 0x02, // id:2 -- 2 UNKNOWN
+ 0x0f, // typeid:1 -- 15, list
+
+ // Thus begins a list
+ 0x0c, // el_type:1 -- struct
+ 0x00, 0x00, 0x00, 0x03, // length:4 -- 3
+ 0x08, // el[0] type:1 -- i32
+ 0x00, 0x01, // el[0] id:2 -- 2
+ 0x00, 0x00, 0x00, 0x1e, // el[0] Int32BE -- 30
+ 0x00, // el[0] type:1 -- stop
+ 0x08, // el[1] type:1 -- i32
+ 0x00, 0x01, // el[1] id:2 -- 2
+ 0x00, 0x00, 0x00, 0x64, // el[1] Int32BE -- 100
+ 0x00, // el[1] type:1 -- stop
+ 0x08, // el[2] type:1 -- i32
+ 0x00, 0x01, // el[2] id:2 -- 2
+ 0x00, 0x00, 0x00, 0xc8, // el[2] Int32BE -- 200
+ 0x00, // el[2] type:1 -- stop
+ // Thus ends the map
+
+ 0x00 // typeid:1 -- 0 STOP
+ ]), 0);
+ if (result.err) {
+ return assert.end(result.err);
+ }
+ assert.deepEqual(result.value, new Health());
+ assert.end();
+});
diff --git a/pool/shard010/JavaScript/0068849_test.js b/pool/shard010/JavaScript/0068849_test.js
new file mode 100644
index 0000000000000000000000000000000000000000..f9495b3bd010833ec0e33971d2be9586898c29e4
--- /dev/null
+++ b/pool/shard010/JavaScript/0068849_test.js
@@ -0,0 +1,36 @@
+const expect = require('expect');
+const Boilerplate = require('./boilerplate');
+
+describe('bot behavior', function () {
+ const boilerplate = new Boilerplate();
+
+ it('recognizes issues with placeholder body', function () {
+ const text = "Context: http://example.com\r\n\r\nChange the title above to describe your issue and add your feedback here, including code if necessary"
+ expect(boilerplate.hasOnlyDefaultBody(text)).toBe(true);
+ })
+
+ it('does not match on custom body text', function() {
+ const text = "Something else"
+ expect(boilerplate.hasOnlyDefaultBody(text)).toBe(false);
+ })
+
+ it('recognizes issues with placeholder title', function () {
+ const text = "tour: [REPLACE WITH SHORT DESCRIPTION]"
+ expect(boilerplate.hasDefaultTitle(text)).toBe(true);
+ })
+
+ it('does not match on custom body text', function() {
+ const text = "Something else"
+ expect(boilerplate.hasDefaultTitle(text)).toBe(false);
+ })
+
+ it('does not match on custom body text containing placeholder body', function() {
+ const text = "Context: http://example.com\r\n\r\nChange the title above to describe your issue and add your feedback here, including code if necessary\r\n\r\nSomething else"
+ expect(boilerplate.hasOnlyDefaultBody(text)).toBe(false);
+ })
+
+ it('recognizes issues with placeholder body including added whitespace', function () {
+ const text = "Context: http://example.com\r\n\r\nChange the title above to describe your issue and add your feedback here, including code if necessary\r\n\r\n"
+ expect(boilerplate.hasDefaultBody(text)).toBe(true);
+ })
+})
diff --git a/pool/shard010/JavaScript/0068850_Twitter.js b/pool/shard010/JavaScript/0068850_Twitter.js
new file mode 100644
index 0000000000000000000000000000000000000000..1eed52c5f10c15b4ee24b08b6b04dc76df96c5d2
--- /dev/null
+++ b/pool/shard010/JavaScript/0068850_Twitter.js
@@ -0,0 +1,61 @@
+var TwitterUser = function () {}
+TwitterUser.prototype.userName = '';
+TwitterUser.prototype.screenName = '';
+TwitterUser.prototype.tweetTimeCount = [];
+
+var Twitter = function () {}
+Twitter.prototype = {
+ consumerKey: "EeqWTnX0daCeEFu3eGtg",
+ consumerSecret: "UT1E0kzuWNlntDeWGsXWk5nMfQP93MJBKphVfjmi4",
+ accessToken: "413861403-DjNoMVbhyCoCwCHEMGVrtIKRAAASdYNLEXkhTW6A",
+ tokenSecret: "tYZxpJyZMDYuNpi6j0WJc1BZUgO0NghVEbKXDElDg"
+};
+
+Twitter.prototype.get = function (api, content) {
+ var accessor = {
+ consumerSecret: this.consumerSecret,
+ tokenSecret: this.tokenSecret
+ };
+
+ var message = {
+ method: "GET",
+ action: api,
+ parameters: {
+ oauth_version: "1.0",
+ oauth_signature_method: "HMAC-SHA1",
+ oauth_consumer_key: this.consumerKey,
+ oauth_token: this.accessToken
+ }
+ };
+ for (var key in content) {
+ message.parameters[key] = content[key];
+ }
+ OAuth.setTimestampAndNonce(message);
+ OAuth.SignatureMethod.sign(message, accessor);
+ var target = OAuth.addToURL(message.action, message.parameters);
+
+ var options = {
+ type: message.method,
+ url: target,
+ dataType: "jsonp", //ここでjsonpを指定する
+ jsonp: false, //jQueryによるcallback関数名の埋め込みはしない
+ cache: true //リクエストパラメータに時刻を埋め込まない
+ };
+ $.ajax(options);
+}
+
+Twitter.prototype.callback = function (data) {
+ console.log(data);
+}
+
+Twitter.prototype.parse = function (username) {
+ //オプションとコールバック関数の指定
+ var content = {
+ count: "200",
+ screen_name: username,
+ callback: 'Twitter.prototype.callback'
+ };
+
+ //Twitter APIの呼び出し
+ this.get("https://api.twitter.com/1.1/statuses/user_timeline.json", content)
+}
diff --git a/pool/shard010/JavaScript/0068854_application.js b/pool/shard010/JavaScript/0068854_application.js
new file mode 100644
index 0000000000000000000000000000000000000000..0d23efa13e7b1c40079fbd132761ac588a34a021
--- /dev/null
+++ b/pool/shard010/JavaScript/0068854_application.js
@@ -0,0 +1,44 @@
+import Ember from 'ember';
+
+const postAttrs = [
+ { id: "1", title: "The best post ever" },
+ { id: "2", title: "The next best post" },
+ { id: "3", title: "The worst post ever written" }
+];
+
+export default Ember.Route.extend({
+ beforeModel() {
+ this._buildPosts();
+ this._buildComments();
+ },
+
+ model() {
+ return Ember.RSVP.hash({
+ posts: this.store.all('post'),
+ comments: this.store.all('comment'),
+ newPost: this.store.createRecord('post'),
+ newComment: this.store.createRecord('comment')
+ });
+ },
+
+ _buildPosts() {
+ return postAttrs.map((attrs) => {
+ return this.store.createRecord('post', attrs);
+ });
+ },
+
+ _buildComments() {
+ const comments = [];
+
+ for (let i = 0; i < 300; i ++) {
+ const comment = this.store.createRecord('comment', {
+ id: i.toString(),
+ body: `Awesome comment #${i}`
+ });
+
+ comments.push(comment);
+ }
+
+ return comments;
+ }
+});
diff --git a/pool/shard010/JavaScript/0068857_topnav.client.directive.js b/pool/shard010/JavaScript/0068857_topnav.client.directive.js
new file mode 100644
index 0000000000000000000000000000000000000000..dec013e044c3b18222c1d20d9a7ff0fb360de934
--- /dev/null
+++ b/pool/shard010/JavaScript/0068857_topnav.client.directive.js
@@ -0,0 +1,23 @@
+'use strict';
+
+angular.module('core').directive('topnav', ['$window',
+ function($window) {
+ var $win = angular.element($window); // wrap window object as jQuery object
+
+ return {
+ restrict: 'AE',
+ link: function (scope, element, attrs) {
+ var topClass = attrs.topnav, // get CSS class from directive's attribute value
+ offsetTop = element.offset().top; // get element's top relative to the document
+
+ $win.on('scroll', function (e) {
+ if ($win.scrollTop() >= offsetTop) {
+ element.addClass(topClass);
+ } else {
+ element.removeClass(topClass);
+ }
+ });
+ }
+ };
+ }
+]);
diff --git a/pool/shard010/JavaScript/0068858_app.js b/pool/shard010/JavaScript/0068858_app.js
new file mode 100644
index 0000000000000000000000000000000000000000..f9cf35a920497cd41eacf4fa8c5dc61db26fbfe8
--- /dev/null
+++ b/pool/shard010/JavaScript/0068858_app.js
@@ -0,0 +1,50 @@
+const config = require('config.js');
+const api = require('lib/api.js');
+const request = require('lib/request.js');
+const storage = require('lib/storage.js');
+App({
+ onLaunch: function() {
+ wx.login({
+ success: function(res) {
+ wx.getUserInfo({
+ success: function (res) {
+ storage.setStorage({
+ key: 'avatarUrl',
+ data: res.userInfo.avatarUrl,
+ })
+ }
+ })
+ if (res.code) {
+ //code换取id
+ request({
+ method: 'POST',
+ header: {
+ "content-type": "application/x-www-form-urlencoded"
+ },
+ url: api.getUrl('/security/register/init'),
+ data: {
+ code: res.code
+ }
+ }).then((resp) => {
+ console.log(resp)
+ storage.setStorage({
+ key: 'openId',
+ data: resp.openId,
+ }).then((ress) => {
+ if(resp.resCode=='0000'){
+ wx.redirectTo(
+ { url: 'pages/portal/myAccount' });
+ }
+ if(resp.resCode=='0001'){
+ wx.redirectTo({
+ url: 'pages/register/registerOne' });
+ }
+ })
+ })
+ } else {
+ console.log('获取用户登录态失败!' + res.errMsg)
+ }
+ }
+ });
+ }
+})
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068863_build.js b/pool/shard010/JavaScript/0068863_build.js
new file mode 100644
index 0000000000000000000000000000000000000000..c6bf3994359f249ac3b01b9b6e205d5efb1382b8
--- /dev/null
+++ b/pool/shard010/JavaScript/0068863_build.js
@@ -0,0 +1,89 @@
+var fs = require('fs');
+var stat = fs.stat;
+var UglifyJS = require("uglify-js");
+var log4js = require('log4js');
+var config = require("./config");
+//日志
+log4js.configure({
+ appenders: [
+ {
+ type: 'console',
+ category: 'js'
+ }/*, //控制台输出
+ {
+ type: 'file', //文件输出
+ filename: 'logs/web.log',
+ maxLogSize: 102400,
+ category: 'normal'
+ }*/
+ ],
+ replaceConsole: true
+});
+var logger = log4js.getLogger('js');
+logger.setLevel('DEBUG');
+
+function walk(path,buildPath,handleFile) {
+ //handleFile(path,buildPath);
+ if(!fs.existsSync(buildPath)){
+ fs.mkdirSync(buildPath);
+ }
+ fs.readdir(path, function(err, files) {
+ if (err) {
+ console.log('read dir error');
+ } else {
+ files.forEach(function(item) {
+ var tmpPath = path + '/' + item;
+ var tmpBuildPath = buildPath + '/' + item;
+ //console.log(tmpBuildPath+"------"+fs.existsSync(tmpBuildPath));
+ if(!fs.existsSync(buildPath)){
+ fs.mkdirSync(buildPath);
+ }
+ fs.stat(tmpPath, function(err1, stats) {
+ if (err1) {
+ console.log('stat error');
+ } else {
+ if (stats.isDirectory()) {
+ walk(tmpPath,tmpBuildPath,handleFile);
+ } else {
+ handleFile(tmpPath,tmpBuildPath);
+ }
+ }
+ })
+ });
+
+ }
+ });
+}
+logger.debug("源文件地址:"+config.devPath.sourcesPath);
+logger.debug("目标文件地址:"+config.devPath.buildPath);
+walk(config.devPath.sourcesPath,config.devPath.buildPath,
+ function(sourcePath,destinationPath){
+ stat( sourcePath, function( err, st ){
+ if( err ){
+ throw err;
+ }
+ if(sourcePath.indexOf(".js")>0){
+ var result = UglifyJS.minify(sourcePath);
+ fs.writeFile(destinationPath,result.code,"utf-8",function(err){
+ //console.log(err);
+ });
+ }else{
+ stat( sourcePath, function( err, st ){
+ if( err ){
+ throw err;
+ }
+ // 判断是否为文件
+ if( st.isFile() ){
+ // 创建读取流
+ readable = fs.createReadStream(sourcePath);
+ // 创建写入流
+ writable = fs.createWriteStream(destinationPath);
+ // 通过管道来传输流
+ readable.pipe( writable );
+ }
+ });
+ }
+ });
+});
+logger.debug("building successful!");
+
diff --git a/pool/shard010/JavaScript/0068864_GestureController.js b/pool/shard010/JavaScript/0068864_GestureController.js
new file mode 100644
index 0000000000000000000000000000000000000000..66e8571f919c455886b579d86bd9c2210f60a4dd
--- /dev/null
+++ b/pool/shard010/JavaScript/0068864_GestureController.js
@@ -0,0 +1,26 @@
+define(['dom/primitives/Elem', 'TweenMax'], function(Elem) {
+ var GestureController = function() {
+
+ var label = new Elem({
+ css: {
+ width: '100%',
+ color: "#ffffff",
+ textAlign: 'center',
+ textTransform: 'uppercase',
+ fontSize: '100px',
+ position: 'absolute',
+ top: window.innerHeight / 2 + 'px'
+ },
+ insert: {
+ type: 'parent',
+ target: document.body
+ }
+ });
+
+ this.show = function(gesture) {
+ label.el.innerHTML = gesture;
+ };
+ };
+
+ return GestureController;
+});
diff --git a/pool/shard010/JavaScript/0068867_primitives.js b/pool/shard010/JavaScript/0068867_primitives.js
new file mode 100644
index 0000000000000000000000000000000000000000..b77a7fe276ec2bc86964485f7d9072de91f1699d
--- /dev/null
+++ b/pool/shard010/JavaScript/0068867_primitives.js
@@ -0,0 +1,77 @@
+let Primitives = {};
+Primitives.GridAxis = class {
+ static createMesh(gl) {
+ let verts = [];
+ let size = 1.8; // W/H of the outer box of the grid, from origin we can only go 1 unit in each direction so from left to right is 2 units max
+ let div = 10.0; // How to divide up the grid
+ let step = size / div; // Steps between each line, just a number we increment by for each line in the grid
+ let half = size / 2; // From origin the starting position is half the size.
+
+ let p; // Temp variable for position value
+ for (let i = 0; i <= div; i++) {
+ // Vertical line
+ p = -half + (i * step);
+ verts.push(p); //x1
+ verts.push(half); //y1
+ verts.push(0) //z1
+ verts.push(0); //c1
+
+ verts.push(p); //x2
+ verts.push(-half); //y2;
+ verts.push(0) //z2
+ verts.push(1); //c2
+
+ //Horizontal line
+ p = half - (i * step);
+ verts.push(-half); //x1
+ verts.push(p); //y1
+ verts.push(0) //z1
+ verts.push(0); //c1
+
+ verts.push(half); //x2
+ verts.push(p); //y2;
+ verts.push(0) //z2
+ verts.push(1); //c2
+ }
+
+ let attrColorLocation = 4;
+ let strideLength;
+ let mesh = { drawMode: gl.LINES, vao: gl.createVertexArray() };
+
+ // Do some math
+ mesh.vertexComponentLength = 4;
+ mesh.vertexCount = verts.length / mesh.vertexComponentLength;
+ strideLength = Float32Array.BYTES_PER_ELEMENT * mesh.vertexComponentLength; // Stride Length is the Vertex Size for the buffer in Bytes
+
+ // Setup our Buffer
+ mesh.bufVertices = gl.createBuffer();
+ gl.bindVertexArray(mesh.vao);
+ gl.bindBuffer(gl.ARRAY_BUFFER, mesh.bufVertices);
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(verts), gl.STATIC_DRAW);
+ gl.enableVertexAttribArray(ATTR_POSITION_LOCATION);
+ gl.enableVertexAttribArray(attrColorLocation);
+
+ gl.vertexAttribPointer(
+ ATTR_POSITION_LOCATION, // Attribute Location
+ 3, // How big is the vector by number count
+ gl.FLOAT, // What type of number we passing in
+ false, // Does it need to be normalized
+ strideLength, // How big is a vertex chunk of data
+ 0); // OffSet by how much
+
+
+ gl.vertexAttribPointer(
+ attrColorLocation, // new shader has 'in float a_color' as second attrib
+ 1, // This attrib is a single float
+ gl.FLOAT,
+ false,
+ strideLength, // Each vertex chunk is 4 floats long
+ Float32Array.BYTES_PER_ELEMENT * 3); // Skip first 3 floats
+
+ // Cleanup and Finalize
+ gl.bindVertexArray(null);
+ gl.bindBuffer(gl.ARRAY_BUFFER, null);
+ gl.mMeshCache['grid'] = mesh;
+ return mesh;
+ }
+}
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068870_BlocksView.js b/pool/shard010/JavaScript/0068870_BlocksView.js
new file mode 100644
index 0000000000000000000000000000000000000000..853f5dea8c755588c760455089b910d27eb3cfe7
--- /dev/null
+++ b/pool/shard010/JavaScript/0068870_BlocksView.js
@@ -0,0 +1,203 @@
+import Backbone from 'backbone';
+import { isString, isObject, bindAll } from 'underscore';
+import BlockView from './BlockView';
+import CategoryView from './CategoryView';
+
+export default Backbone.View.extend({
+ initialize(opts, config) {
+ bindAll(this, 'getSorter', 'onDrag', 'onDrop');
+ this.config = config || {};
+ this.categories = opts.categories || '';
+ this.renderedCategories = [];
+ var ppfx = this.config.pStylePrefix || '';
+ this.ppfx = ppfx;
+ this.noCatClass = `${ppfx}blocks-no-cat`;
+ this.blockContClass = `${ppfx}blocks-c`;
+ this.catsClass = `${ppfx}block-categories`;
+ const coll = this.collection;
+ this.listenTo(coll, 'add', this.addTo);
+ this.listenTo(coll, 'reset', this.render);
+ this.em = this.config.em;
+ this.tac = 'test-tac';
+ this.grabbingCls = this.ppfx + 'grabbing';
+
+ if (this.em) {
+ this.config.getSorter = this.getSorter;
+ this.canvas = this.em.get('Canvas');
+ }
+ },
+
+ updateConfig(opts = {}) {
+ this.config = {
+ ...this.config,
+ ...opts
+ };
+ },
+
+ /**
+ * Get sorter
+ * @private
+ */
+ getSorter() {
+ if (!this.em) return;
+ if (!this.sorter) {
+ var utils = this.em.get('Utils');
+ var canvas = this.canvas;
+ this.sorter = new utils.Sorter({
+ container: canvas.getBody(),
+ placer: canvas.getPlacerEl(),
+ containerSel: '*',
+ itemSel: '*',
+ pfx: this.ppfx,
+ onStart: this.onDrag,
+ onEndMove: this.onDrop,
+ onMove: this.onMove,
+ document: canvas.getFrameEl().contentDocument,
+ direction: 'a',
+ wmargin: 1,
+ nested: 1,
+ em: this.em,
+ canvasRelative: 1
+ });
+ }
+ return this.sorter;
+ },
+
+ /**
+ * Callback when block is on drag
+ * @private
+ */
+ onDrag(e) {
+ this.em.stopDefault();
+ this.em.trigger('block:drag:start', e);
+ },
+
+ onMove(e) {
+ this.em.trigger('block:drag:move', e);
+ },
+
+ /**
+ * Callback when block is dropped
+ * @private
+ */
+ onDrop(model) {
+ const em = this.em;
+ em.runDefault();
+
+ if (model && model.get) {
+ if (model.get('activeOnRender')) {
+ model.trigger('active');
+ model.set('activeOnRender', 0);
+ }
+
+ em.trigger('block:drag:stop', model);
+ }
+ },
+
+ /**
+ * Add new model to the collection
+ * @param {Model} model
+ * @private
+ * */
+ addTo(model) {
+ this.add(model);
+ },
+
+ /**
+ * Render new model inside the view
+ * @param {Model} model
+ * @param {Object} fragment Fragment collection
+ * @private
+ * */
+ add(model, fragment) {
+ const { config } = this;
+ var frag = fragment || null;
+ var view = new BlockView(
+ {
+ model,
+ attributes: model.get('attributes')
+ },
+ config
+ );
+ var rendered = view.render().el;
+ var category = model.get('category');
+
+ // Check for categories
+ if (category && this.categories && !config.ignoreCategories) {
+ if (isString(category)) {
+ category = {
+ id: category,
+ label: category
+ };
+ } else if (isObject(category) && !category.id) {
+ category.id = category.label;
+ }
+
+ var catModel = this.categories.add(category);
+ var catId = catModel.get('id');
+ var catView = this.renderedCategories[catId];
+ var categories = this.getCategoriesEl();
+ model.set('category', catModel);
+
+ if (!catView && categories) {
+ catView = new CategoryView(
+ {
+ model: catModel
+ },
+ this.config
+ ).render();
+ this.renderedCategories[catId] = catView;
+ categories.appendChild(catView.el);
+ }
+
+ catView && catView.append(rendered);
+ return;
+ }
+
+ if (frag) frag.appendChild(rendered);
+ else this.append(rendered);
+ },
+
+ getCategoriesEl() {
+ if (!this.catsEl) {
+ this.catsEl = this.el.querySelector(`.${this.catsClass}`);
+ }
+
+ return this.catsEl;
+ },
+
+ getBlocksEl() {
+ if (!this.blocksEl) {
+ this.blocksEl = this.el.querySelector(
+ `.${this.noCatClass} .${this.blockContClass}`
+ );
+ }
+
+ return this.blocksEl;
+ },
+
+ append(el) {
+ let blocks = this.getBlocksEl();
+ blocks && blocks.appendChild(el);
+ },
+
+ render() {
+ const ppfx = this.ppfx;
+ const frag = document.createDocumentFragment();
+ this.catsEl = null;
+ this.blocksEl = null;
+ this.renderedCategories = [];
+ this.el.innerHTML = `
+
+
+ `;
+
+ this.collection.each(model => this.add(model, frag));
+ this.append(frag);
+ const cls = `${this.blockContClass}s ${ppfx}one-bg ${ppfx}two-color`;
+ this.$el.addClass(cls);
+ return this;
+ }
+});
diff --git a/pool/shard010/JavaScript/0068873_keyboard_help_widget.js b/pool/shard010/JavaScript/0068873_keyboard_help_widget.js
new file mode 100644
index 0000000000000000000000000000000000000000..7fcee8d0f4725e8082d1e84099de886d1243964a
--- /dev/null
+++ b/pool/shard010/JavaScript/0068873_keyboard_help_widget.js
@@ -0,0 +1,85 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview Widget presenting all keyboard commands.
+ */
+
+goog.provide('cvox.KeyboardHelpWidget');
+
+goog.require('cvox.ChromeVox');
+goog.require('cvox.CommandStore');
+goog.require('cvox.KeyUtil');
+goog.require('cvox.OverlayWidget');
+
+/**
+ * @constructor
+ * @extends {cvox.OverlayWidget}
+ */
+cvox.KeyboardHelpWidget = function() {
+ goog.base(this, '');
+ this.container_ = document.createElement('div');
+ var list = [];
+ var callbacks = [];
+ var keymap = cvox.ChromeVoxKbHandler.handlerKeyMap;
+
+ keymap.bindings().forEach(goog.bind(function(pair) {
+ var command = pair.command;
+ var keySeq = pair.sequence;
+ var message = command;
+ try {
+ var id = cvox.CommandStore.messageForCommand(command);
+ if (!id) {
+ return;
+ }
+ message = cvox.ChromeVox.msgs.getMsg(id);
+ } catch (e) {
+ // TODO(dtseng): We have some commands that don't have valid message id's.
+ }
+
+ var commandElement = document.createElement('p');
+ commandElement.id = command;
+ commandElement.setAttribute('role', 'menuitem');
+ commandElement.textContent =
+ message + ' - ' + cvox.KeyUtil.keySequenceToString(keySeq, true);
+ this.container_.appendChild(commandElement);
+ }, this));
+};
+goog.inherits(cvox.KeyboardHelpWidget, cvox.OverlayWidget);
+goog.addSingletonGetter(cvox.KeyboardHelpWidget);
+
+
+/**
+ * @override
+ */
+cvox.KeyboardHelpWidget.prototype.show = function() {
+ goog.base(this, 'show');
+ this.host_.appendChild(this.container_);
+};
+
+
+/**
+ * @override
+ */
+cvox.KeyboardHelpWidget.prototype.getNameMsg = function() {
+ return ['keyboard_help_intro'];
+};
+
+/**
+ * @override
+ */
+cvox.KeyboardHelpWidget.prototype.onKeyDown = function(evt) {
+ if (evt.keyCode == 13) { // Enter
+ var currentCommand =
+ cvox.ChromeVox.navigationManager.getCurrentNode().parentNode.id;
+ this.hide();
+ cvox.ChromeVoxEventSuspender.withSuspendedEvents(
+ cvox.ChromeVoxUserCommands.commands[currentCommand])();
+ evt.preventDefault();
+ evt.stopPropagation();
+ return true;
+ } else {
+ return goog.base(this, 'onKeyDown', evt);
+ }
+};
diff --git a/pool/shard010/JavaScript/0068874_unsubscribeCtrl.js b/pool/shard010/JavaScript/0068874_unsubscribeCtrl.js
new file mode 100644
index 0000000000000000000000000000000000000000..73ff8e71ef01cead116b99ab0dd933e9d8ccd0d6
--- /dev/null
+++ b/pool/shard010/JavaScript/0068874_unsubscribeCtrl.js
@@ -0,0 +1,82 @@
+/**
+ * Created by hunte on 30/05/2016.
+ */
+var mainAppCtrls = angular.module("mainAppCtrls");
+/**
+ * @ngdoc controller
+ * @name mainAppCtrls.controller:UnsubscribeCtrl
+ * @description Providing resources used to complete unsubscription from a workshop
+ */
+mainAppCtrls.controller('UnsubscribeCtrl', ['$scope', 'Workshops', '$stateParams', '$translate', '$alert',
+ function ($scope, Workshops, $stateParams, $translate, $alert) {
+
+ //Define used variables
+ var _userId = $stateParams.id;
+ var _workshopId = $stateParams.workshopid;
+ var _token = $stateParams.token;
+
+ $scope.workshop = {};
+ $scope.alertUnsub = $alert({});
+
+ //get and store translations for errors
+ var _translations = {};
+ $translate(['TITLE_ERROR', 'TITLE_SUCCESS', 'ALERT_WORKSHOP_NOT_FOUND', 'UNSUBSCRIBE_CONFIRM_ERROR', 'UNSUBSCRIBE_CONFIRM_SUCCESS']).then(function (translations) {
+ _translations = translations;
+ });
+ $scope.confirm = function () {
+ var _params = {
+ id: _workshopId,
+ token: _token,
+ participantId: _userId
+ };
+ $scope.working = true;
+ Workshops.unsubscribeConfirm(_params).$promise.then(function (response) {
+ $scope.alertUnsub.hide();
+ $scope.alertUnsub = $alert({
+ title: _translations.TITLE_SUCCESS,
+ type: 'success',
+ content: _translations.UNSUBSCRIBE_CONFIRM_SUCCESS,
+ show: true,
+ container: '#alert',
+ dismissable: false
+ });
+ $scope.working = false;
+ }, function (response) {
+ $scope.alertUnsub.hide();
+ $scope.alertUnsub = $alert({
+ title: _translations.TITLE_ERROR,
+ type: 'danger',
+ content: _translations.UNSUBSCRIBE_CONFIRM_ERROR,
+ show: true,
+ container: '#alert',
+ dismissable: false
+ });
+ $scope.working = false;
+ });
+ }
+
+ //Load workshop to display additional data
+ $scope.loading = true;
+ $scope.error = false;
+ Workshops.getWorkshop({id: _workshopId}).$promise.then(function (response) {
+ $scope.workshop = response;
+ var _ea = Date.parse($scope.workshop.end_at);
+ var _sa = Date.parse($scope.workshop.start_at);
+
+ $scope.workshop.duration = new Date(_ea - _sa);
+ $scope.loading = false;
+ }, function (response) {
+ $scope.alertUnsub.hide();
+ $scope.alertUnsub = $alert({
+ title: _translations.TITLE_ERROR,
+ type: 'danger',
+ content: _translations.ALERT_WORKSHOP_NOT_FOUND,
+ show: true,
+ container: '#alert',
+ dismissable: false
+ });
+ $scope.loading = false;
+ $scope.error = true;
+ });
+ }
+]);
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068875_status_group.js b/pool/shard010/JavaScript/0068875_status_group.js
new file mode 100644
index 0000000000000000000000000000000000000000..7f1287a314fa932f55bd69b53b3db5943b406ab5
--- /dev/null
+++ b/pool/shard010/JavaScript/0068875_status_group.js
@@ -0,0 +1,29 @@
+/*jslint browser: true, white: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, newcap: true, immed: true, indent: 4, onevar: false */
+/*global window, $, jQuery, _ */
+
+STUDIP.StatusGroup = {
+ init: function () {
+ // make the tables in the div sortable
+ jQuery('div.sortable').sortable({
+ axis: 'y',
+ items: "table.sortable",
+ handle: 'tr.handle',
+
+ stop: function () {
+ // iterate over the statusgroups and collect the ids
+ var statusgroup_ids = {};
+ statusgroup_ids.statusgroup_ids = {};
+ //areas.areas = {};
+ jQuery('div.sortable').find('table.sortable').each(function () {
+ statusgroup_ids.statusgroup_ids[jQuery(this).attr('id')] = jQuery(this).attr('id');
+ });
+
+ jQuery.ajax({
+ type: 'POST',
+ url: STUDIP.URLHelper.getURL('contact_statusgruppen.php?cmd=storeSortOrder'),
+ data: statusgroup_ids
+ });
+ }
+ });
+ }
+};
diff --git a/pool/shard010/JavaScript/0068876_ConfigView.js b/pool/shard010/JavaScript/0068876_ConfigView.js
new file mode 100644
index 0000000000000000000000000000000000000000..5843d27a11e7bc5f39d102f924bd7d5d88058630
--- /dev/null
+++ b/pool/shard010/JavaScript/0068876_ConfigView.js
@@ -0,0 +1,89 @@
+import _ from 'underscore';
+
+import PluginConfigBreadcrumbWidget from 'girder/views/widgets/PluginConfigBreadcrumbWidget';
+import View from 'girder/views/View';
+import events from 'girder/events';
+import { restRequest } from 'girder/rest';
+
+import ConfigViewTemplate from '../templates/configView.pug';
+import '../stylesheets/configView.styl';
+
+var ConfigView = View.extend({
+ events: {
+ 'submit #g-item-licenses-settings-form': function (event) {
+ event.preventDefault();
+
+ this.$('#g-item-licenses-error-message').empty();
+
+ this._saveSettings([{
+ key: 'item_licenses.licenses',
+ value: this.$('#g-item-licenses').val().trim()
+ }]);
+ },
+ 'click #g-item-licenses-defaults': function (event) {
+ event.preventDefault();
+
+ restRequest({
+ method: 'GET',
+ url: 'item/licenses',
+ data: {
+ 'default': true
+ }
+ }).done(_.bind(function (resp) {
+ this.licenses = resp;
+ this.render();
+ }, this));
+ }
+ },
+
+ initialize: function () {
+ restRequest({
+ method: 'GET',
+ url: 'system/setting',
+ data: {
+ list: JSON.stringify(['item_licenses.licenses'])
+ }
+ }).done(_.bind(function (resp) {
+ this.licenses = resp['item_licenses.licenses'];
+ this.render();
+ }, this));
+ },
+
+ render: function () {
+ this.$el.html(ConfigViewTemplate({
+ licenses: JSON.stringify(this.licenses, null, 4)
+ }));
+
+ this.breadcrumb = new PluginConfigBreadcrumbWidget({
+ pluginName: 'Item licenses',
+ el: this.$('.g-config-breadcrumb-container'),
+ parentView: this
+ }).render();
+
+ return this;
+ },
+
+ _saveSettings: function (settings) {
+ restRequest({
+ method: 'PUT',
+ url: 'system/setting',
+ data: {
+ list: JSON.stringify(settings)
+ },
+ error: null
+ }).done(_.bind(function () {
+ events.trigger('g:alert', {
+ icon: 'ok',
+ text: 'Settings saved.',
+ type: 'success',
+ timeout: 3000
+ });
+ }, this)).fail(_.bind(function (resp) {
+ this.$('#g-item-licenses-error-message').text(
+ resp.responseJSON.message
+ );
+ }, this));
+ }
+});
+
+export default ConfigView;
diff --git a/pool/shard010/JavaScript/0068879_user.js b/pool/shard010/JavaScript/0068879_user.js
new file mode 100644
index 0000000000000000000000000000000000000000..ab980d8a28f58f01b68d79000a45c228c0ac2c5b
--- /dev/null
+++ b/pool/shard010/JavaScript/0068879_user.js
@@ -0,0 +1,184 @@
+'use strict';
+
+var BasicStrategy = require('passport-http').BasicStrategy,
+ BearerStrategy = require('passport-http-bearer').Strategy,
+ bcrypt = require('bcrypt'),
+ passport = require('passport'),
+ validator = require('validator');
+
+module.exports = function (logger, cache, User, OAuthClient, OAuthCode, OAuthToken) {
+ var cachePrefixClient = 'cache:oauthclient:',
+ cachePrefixUser = 'cache:user:',
+ cacheTtl = 300,
+ saltRounds = 12;
+
+ var userController = {};
+
+ // Authentication
+
+ passport.use(new BasicStrategy(
+ function (username, password, callback) {
+ cache.wrap(cachePrefixUser + username, function (cacheCallback) {
+ User.findOne({
+ where: {
+ username: username
+ }
+ }).then(function (user) {
+ if (!user) {
+ return cacheCallback(null, false);
+ }
+
+ // Load hash from DB.
+ bcrypt.compare(password, user.password_hash, function (err, isMatch) {
+ if (err) {
+ return cacheCallback(err);
+ }
+
+ // Password did not match
+ if (!isMatch) {
+ return cacheCallback(null, false);
+ }
+
+ // Success
+ return cacheCallback(null, user.get({plain: true}));
+ })
+ })
+ }, {ttl: cacheTtl}, callback);
+ }
+ ));
+ userController.isAuthenticated = passport.authenticate('basic', {session: false});
+
+ passport.use('client-basic', new BasicStrategy(
+ function (username, password, callback) {
+ cache.wrap(cachePrefixClient + username, function (cacheCallback) {
+ OAuthClient.findOne({
+ where: {
+ name: username
+ }
+ }).then(function (client) {
+ // No client found with that id
+ if (!client) {
+ return callback(null, false);
+ }
+
+ // Load hash from DB.
+ bcrypt.compare(password, client.secret, function (err, isMatch) {
+ if (err) {
+ return cacheCallback(err);
+ }
+
+ // Password did not match
+ if (!isMatch) {
+ return cacheCallback(null, false);
+ }
+
+ // Success
+ return cacheCallback(null, client);
+ })
+ })
+ }, {ttl: cacheTtl}, callback)
+ }
+ ));
+ userController.isClientAuthenticated = passport.authenticate('client-basic', {session: false});
+
+ passport.use(new BearerStrategy(
+ function (accessToken, callback) {
+ OAuthToken.findOne({
+ where: {
+ value: accessToken
+ }
+ }).then(function (token) {
+ // No client found with that id
+ if (!token) {
+ return callback(null, false);
+ }
+
+ User.findOne({
+ where: {
+ id: token.userId
+ }
+ }).then(function (user) {
+ // Simple example with no scope
+ callback(null, user, {scope: '*'});
+ })
+ })
+ }
+ ));
+ userController.isBearerAuthenticated = passport.authenticate('bearer', { session: false });
+
+ // User Resource
+
+ userController.postUsers = function (req, res) {
+ var passValidation = req.body.password || '';
+ if (passValidation.length > 7) {
+ var user = {
+ username: req.body.username,
+ password: req.body.password,
+ email : req.body.email
+ };
+
+ User.create(user).then(function (user) {
+ return res.json(user);
+ }).catch(function (error) {
+ res.status(400);
+ return res.json(error);
+ });
+ }
+ else {
+ res.status(400);
+ return res.json({
+ "name" : "SequelizeUniqueConstraintError",
+ "message": "Validation error",
+ "errors" : [
+ {
+ "message": "password must be longer than 7 characters",
+ "path" : "password"
+ }
+ ]
+ })
+ }
+ };
+
+ userController.getUser = function (req, res) {
+ User.findOne({
+ username: req.params.username
+ }).then(function (user) {
+ res.json(user);
+ })
+ };
+
+ userController.getUsers = function (req, res) {
+ User.findAll().then(function (users) {
+ res.json(users);
+ })
+ };
+
+ // OAuth Client Resource
+
+ userController.postClients = function (req, res) {
+ bcrypt.hash(req.body.secret, saltRounds, function (err, hash) {
+ var client = {
+ name : req.body.name || '',
+ secret: hash,
+ userId: req.user.id
+ };
+
+ OAuthClient.create(client).then(function (client) {
+ return res.json(client);
+ }).catch(function (error) {
+ res.status(400);
+ return res.json(error);
+ });
+
+ });
+ };
+
+ // Create endpoint /api/clients for GET
+ userController.getClients = function (req, res) {
+ OAuthClient.findAll().then(function (clients) {
+ res.json(clients);
+ });
+ };
+
+ return userController;
+};
diff --git a/pool/shard010/JavaScript/0068880_connection.js b/pool/shard010/JavaScript/0068880_connection.js
new file mode 100644
index 0000000000000000000000000000000000000000..64362a12e4a07b1a9ec7b7a591b82fca77558028
--- /dev/null
+++ b/pool/shard010/JavaScript/0068880_connection.js
@@ -0,0 +1,13 @@
+var mongoose = require( 'mongoose' ),
+ channel = require( './channel.js' );
+
+var Connection = function( url , options ){
+ channel.options = options;
+ mongoose.connection.once( 'open' , function(){
+ console.log( 'Mnxg start now & Mongodb also connected...' );
+ if( options.connected ) options.connected();
+ });
+ mongoose.connect( url );
+}
+Connection.prototype.channel = channel;
+module.exports = Connection;
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068882_controllers.js b/pool/shard010/JavaScript/0068882_controllers.js
new file mode 100644
index 0000000000000000000000000000000000000000..016a0561d61ad52ff5c823f678b294547b91a2a3
--- /dev/null
+++ b/pool/shard010/JavaScript/0068882_controllers.js
@@ -0,0 +1,173 @@
+'use strict';
+
+/* Controllers */
+
+angular.module('Qemy.controllers', [
+ 'Qemy.i18n'
+])
+ .controller('PageCtrl', ['$scope', '_', function($scope, _) {
+ var defaultTitle = _('app_name');
+ $scope.$on('change_title', function(e, args) {
+ $scope.title = args.title !== undefined && args.title.length ? args.title : defaultTitle;
+ });
+ $scope.isPageReady = true;
+ }])
+
+ .controller('AppCtrl', ['$scope', '$rootScope', 'UserManager', '$state', function($scope, $rootScope, UserManager, $state) {
+ function updateUserData() {
+ console.log('User data updating...');
+ $rootScope.$broadcast('data loading');
+ var userPromise = UserManager.getCurrentUser({ cache: false });
+ userPromise.then(function (user) {
+ $rootScope.$broadcast('data loaded');
+ if (!user || !user.id) {
+ $rootScope.$broadcast('user updated', { user: {} });
+ return $state.go('auth.form');
+ }
+ $rootScope.$broadcast('user updated', { user: user });
+ console.log('User data updated.');
+ }).catch(function (err) {
+ $state.go('auth.form');
+ });
+ }
+ updateUserData();
+
+ $scope.$on('user update needed', function (ev, args) {
+ console.log('User data update needed.');
+ updateUserData();
+ });
+ }])
+
+ .controller('IndexCtrl', ['$scope', '_', '$state', '$rootScope', 'UserManager',
+ function($scope, _, $state, $rootScope, UserManager) {
+ $scope.$emit('change_title', {
+ title: _('app_name')
+ });
+
+ $scope.$emit('user update needed');
+ $scope.$on('user updated', function (ev, args) {
+ if (!args.user) {
+ return;
+ }
+ $state.go('contests.list');
+ });
+ }
+ ])
+
+ .controller('HeaderCtrl', ['$scope', '$rootScope', '$state', 'UserManager', '$mdDialog', '$interval',
+ function ($scope, $rootScope, $state, UserManager, $mdDialog, $interval) {
+ $scope.$state = $state;
+ $scope.user = {};
+ $scope.isAuth = false;
+ $scope.$on('user updated', function (ev, args) {
+ if (!args.user) {
+ return;
+ }
+ $scope.user = args.user;
+ $scope.isAuth = !!args.user.id;
+ });
+
+ $scope.menuList = [{
+ type: 'item',
+ id: 'settings',
+ name: 'Настройки',
+ iconSrc: '/img/icons/ic_settings_48px.svg'
+ }, {
+ type: 'item',
+ onlyFor: 5,
+ id: 'admin-panel',
+ name: 'Панель администратора',
+ iconSrc: '/img/icons/ic_security_48px.svg'
+ }, {
+ type: 'divider'
+ }, {
+ type: 'item',
+ id: 'exit-app',
+ name: 'Выход',
+ iconSrc: '/img/icons/ic_exit_to_app_48px.svg'
+ }];
+
+ $scope.profileItemClick = function (event, item, index) {
+ switch (item.id) {
+ case 'settings':
+ break;
+ case 'admin-panel':
+ $state.go('admin.index');
+ break;
+ case 'exit-app':
+ exitFromApp(event);
+ break;
+ }
+ };
+
+ function exitFromApp(ev) {
+ var confirm = $mdDialog.confirm()
+ .title('Предупреждение')
+ .content('Вы действительно хотите выйти?')
+ .clickOutsideToClose(true)
+ .ariaLabel('Lucky day')
+ .ok('Да')
+ .cancel('Отмена')
+ .targetEvent(ev);
+ $mdDialog.show(confirm).then(function() {
+ UserManager.logout().then(function (result) {
+ $scope.$emit('user update needed');
+ });
+ });
+ }
+
+ $scope.headerMenu = {};
+ $scope.$on('header expand open', function (ev, args) {
+ var contest = args.contest;
+ $scope.headerMenu = {
+ contest: contest
+ };
+ });
+
+ $scope.$on('header expand close', function (ev, args) {
+ $scope.headerMenu.contest = null;
+ $scope.headerMenu = {};
+ });
+
+ $scope.logoClick = function (ev) {
+ if ($state.current
+ && $state.current.name
+ && $state.is('contests.list')) {
+ $rootScope.$broadcast('contests list update needed')
+ }
+ };
+
+ $scope.unreadMessagesNumber = 0;
+ $scope.allMessagesNumber = 0;
+
+ $scope.openInbox = function (ev) {
+ $rootScope.$broadcast('toggleRightSidenav');
+ };
+
+ $scope.$on('inbox.messages.update-numbers', function (ev, args) {
+ $scope.unreadMessagesNumber = typeof args.unreadMessagesNumber !== 'undefined' ?
+ args.unreadMessagesNumber : $scope.unreadMessagesNumber;
+ $scope.allMessagesNumber = typeof args.allMessagesNumber !== 'undefined' ?
+ args.allMessagesNumber : $scope.allMessagesNumber;
+ });
+ }
+ ])
+
+ .controller('WrapperCtrl', ['$scope', '$rootScope', '$timeout', '$interval', function ($scope, $rootScope, $timeout, $interval) {
+
+ $scope.pageLoading = false;
+ $scope.progress = 0;
+ $scope.$on('data loading', function (ev, args) {
+ $scope.pageLoading = true;
+ $scope.progress = 0;
+ $timeout(function () {
+ $scope.progress = 90;
+ }, 100);
+ });
+
+ $scope.$on('data loaded', function (ev, args) {
+ $scope.pageLoading = false;
+ $scope.progress = 100;
+ });
+ }])
+;
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068885_settings.js b/pool/shard010/JavaScript/0068885_settings.js
new file mode 100644
index 0000000000000000000000000000000000000000..e67e92bb6704efeb0905c3b488f9185a15c05aa8
--- /dev/null
+++ b/pool/shard010/JavaScript/0068885_settings.js
@@ -0,0 +1,42 @@
+import axios from 'axios';
+import config from '../config';
+import store from '../store';
+import { LOAD_SETTINGS, LOAD_SETTINGS_SUCCESS, LOAD_SETTINGS_FAILURE, loadSettingsSuccess, loadSettingsFailure } from '../actions/settings';
+
+export const defaultState = null;
+
+export default (state, action) => {
+ // Make sure to apply a default state if necessary
+ if (typeof state === 'undefined') {
+ state = defaultState;
+ }
+ // Switch case for all possible actions
+ switch(action.type) {
+ case LOAD_SETTINGS:
+ axios.get(`${config.apiUrl}/wp-json/react-api/v1/settings/`)
+ .then(response => {
+ setTimeout(() => {
+ store.dispatch(loadSettingsSuccess(response));
+ }, 2000);
+ })
+ .catch(error => {
+ store.dispatch(loadSettingsSuccess(error))
+ });
+ return state;
+ break;
+
+ case LOAD_SETTINGS_SUCCESS:
+ console.log('success')
+ return action.response.data;
+ break;
+
+ case LOAD_SETTINGS_FAILURE:
+ console.error('ERROR CAUGHT', action.error);
+ return state;
+ break;
+
+ default:
+ return state;
+ break;
+ }
+};
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068887_adminTour.data.js b/pool/shard010/JavaScript/0068887_adminTour.data.js
new file mode 100644
index 0000000000000000000000000000000000000000..4cfba95810b15a749a2167cc447175ee404f9e6c
--- /dev/null
+++ b/pool/shard010/JavaScript/0068887_adminTour.data.js
@@ -0,0 +1,133 @@
+/* Admin tour script */
+(function($){
+
+ $.data_AdminTour = function(){
+
+ hopscotch.endTour(true);
+
+ var lnTour = {};
+
+ if(cc.adminLang == "de"){
+ lnTour = { nextBtn: "weiter",
+ prevBtn: "zurück",
+ doneBtn: "fertig",
+ skipBtn: "überspringen",
+ closeTooltip: "schließen",
+ start: "Tour starten",
+ taskBtn: "weitere Hilfe?",
+ titleFst: $('.headerBox .adminHeader').text(),
+ titleLst: "Tour Ende",
+ textLst: 'Hinweis: Zum Anzeigen von Moduldaten auf der Website muss eine entsprechende Liste als Inhaltselement in eine der Webseiten eingefügt werden.'
+ };
+ }else{
+ lnTour = { start: "Start tour",
+ taskBtn: "need further help?",
+ titleFst: $('.headerBox .adminHeader').text(),
+ titleLst: "End of tour",
+ textLst: 'Hint: To show module data to your visitors you must include a data list type content element in one of your pages.'
+ };
+
+ }
+
+ var steps = new Array();
+ var stepSrc = $('.headerBox .description li');
+
+ // Read steps from description
+ stepSrc.each(function(i,e){
+ var sTitle = "";
+ var sText = $(e).html();
+ var sTarget = $(".headerBox")[0];
+ //sTarget = document.querySelector(".adminTask-main .cc-section-heading");
+ var sPlacecm = "bottom";
+ var xOffset = 0;
+ var aOffset = 0;
+ var onNext = null;
+ var onPrev = null;
+ var sDelay = 0;
+ var bubbleWidth = 280;
+
+ // targets
+ switch(i){
+ case 0:
+ sTitle = lnTour.titleFst;
+ sTarget = "logoDiv";
+ break;
+ case 1:
+ sTarget = "#right .controlBar";
+ sPlacecm = "left";
+ bubbleWidth = 450;
+ onNext = function(){
+ $(".adminTask-modules .editDataCategories").slideDown(500);
+ $(".adminTask-modules .editDataEntrySection").slideUp(500);
+ };
+ break;
+ case 2:
+ sTarget = ".adminTask-modules .editDataCategories";
+ xOffset = "center";
+ aOffset = "center";
+ bubbleWidth = 450;
+ onNext = function(){
+ $(".adminTask-modules .editDataEntrySection").slideDown(500);
+ $(".adminTask-modules .editDataCategories").slideUp(500);
+ };
+ break;
+ case 3:
+ sTarget = ".adminTask-modules .editDataEntrySection";
+ sPlacecm = "top";
+ xOffset = "center";
+ aOffset = "center";
+ bubbleWidth = 450;
+ onPrev = function(){
+ $(".adminTask-modules .editDataCategories").slideDown(500);
+ $(".adminTask-modules .editDataEntrySection").slideUp(500);
+ };
+ break;
+ }
+
+ // Steps
+ steps.push({
+ title: sTitle,
+ content: sText,
+ target: sTarget,
+ placement: sPlacecm,
+ xOffset: xOffset,
+ arrowOffset: aOffset,
+ delay: sDelay,
+ width: bubbleWidth,
+ onNext: onNext,
+ onPrev: onPrev
+ });
+ });
+
+ // Last step
+ steps.push({
+ title: lnTour.titleLst,
+ content: lnTour.textLst,
+ target: document.querySelector(".headerBox"),
+ placement: "bottom",
+ xOffset: "center",
+ arrowOffset: "-9999px"
+ });
+
+ // Define the tour!
+ var optsTour = {
+ id: "cwms-admin-data-tour",
+ i18n: lnTour,
+ showPrevButton: true,
+ steps: steps
+ };
+
+ var startTourBtn = $('
');
+
+ startTourBtn.css('transition','all 0.5s ease');
+
+ startTourBtn.prependTo('#iconPanelTop');
+
+ startTourBtn.bind("click", function(){
+
+ // Start the tour!
+ hopscotch.startTour(optsTour);
+
+ });
+ };
+})(jQuery);
diff --git a/pool/shard010/JavaScript/0068892_15.2.3.6-3-139-1.js b/pool/shard010/JavaScript/0068892_15.2.3.6-3-139-1.js
new file mode 100644
index 0000000000000000000000000000000000000000..07216abce0ea519c9555c42968bd83b4ebb67f69
--- /dev/null
+++ b/pool/shard010/JavaScript/0068892_15.2.3.6-3-139-1.js
@@ -0,0 +1,31 @@
+// Copyright (c) 2012 Ecma International. All rights reserved.
+// Ecma International makes this code available under the terms and conditions set
+// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
+// "Use Terms"). Any redistribution of this code must retain the above
+// copyright and this notice and otherwise comply with the Use Terms.
+
+/*---
+es5id: 15.2.3.6-3-139-1
+description: >
+ Object.defineProperty - 'Attributes' is a Function object which
+ implements its own [[Get]] method to access the 'value' property
+ of prototype object (8.10.5 step 5.a)
+includes: [runTestCase.js]
+---*/
+
+function testcase() {
+ var obj = {};
+ try {
+ Function.prototype.value = "Function";
+ var funObj = function (a, b) {
+ return a + b;
+ };
+
+ Object.defineProperty(obj, "property", funObj);
+
+ return obj.property === "Function";
+ } finally {
+ delete Function.prototype.value;
+ }
+ }
+runTestCase(testcase);
diff --git a/pool/shard010/JavaScript/0068894_gpgmail.js b/pool/shard010/JavaScript/0068894_gpgmail.js
new file mode 100644
index 0000000000000000000000000000000000000000..c80f8afbdb44de101bbdcb525d26b531453fc938
--- /dev/null
+++ b/pool/shard010/JavaScript/0068894_gpgmail.js
@@ -0,0 +1,74 @@
+/**
+ * OpenPGP integration for GPGMail_Mobile.
+ *
+ * @author Alexander Willner
+ * @version 2011-02-22
+ * @see http://gpgtools.org
+ * @license BSD
+ * @todo Remove hard coded keys and use key management instead.
+ * @todo I18N.
+ */
+
+/* hard coded keys for now ------------------------------------------------- */
+var keytype = 0;
+var exp_u = "12075,254029157,49411353,118585420,30333430,182355735,113267204,59879655,246186742,89307457,122612671,87009111,182656057,146899134,253466372,74988166,102757214,66706255,113".split(',');
+var exp_d = "16128693,257125582,198009612,139557212,137415092,28244646,262178813,164292477,91525038,156964779,247191904,267451101,228712303,53989207,261371544,246153944,150829682,249770095,25129227,261561015,81191918,43848397,16495765,53235668,162006057,193519501,106995674,95902518,126698399,218294843,33861852,240767243,89592116,130861474,79306072,77555856,3499".split(',');
+var exp_p = "226197815,195655162,238712700,84661672,79309410,250904587,203484457,240974443,224227230,126874073,179538153,39985901,31019509,61544693,181895321,140514284,265995133,48022167,232".split(',');
+var exp_q = "59391045,127440241,248887009,192654032,240088215,223902554,87919612,632607,82318265,127773417,126207976,43284671,118612664,11872646,165429592,27674223,243581030,191560393,249".split(',');
+var pubkey = "BADiejt3X/biElrPwczuou+GxI1eVbbb0mAS5Eek0h8SKGBO9cHC/tj3uWG/bF6A2+q0WLj+46mI9j60drz5osu3aerjZkiZiGFj9GhdnvYZ7ErT+wV8koxj/2Lrbq8iQyfNpj76VqTl7Rl09BaR/eSm6o6mQ1clqqiEV0FOcTi30wARAQAB";
+var keyid = "a99b311c7f20062a";
+/* ------------------------------------------------------------------------- */
+
+
+/* ------------------------------------------------------------------------- */
+function encrypt() {
+ var text = document.encrypt.rawtext.value;
+
+ var startTime = new Date();
+ var text_enc = OpenPGP_Encrypt(keyid, keytype, pubkey, text);
+ var endTime = new Date();
+
+ document.encrypt.rawtext.value = text_enc;
+ document.getElementById("sendMailButton").href=
+ "mailto:alex@willner.ws?subject=Encrypted:%20Test&body=" +
+ encodeURIComponent(document.getElementById("text").value);
+ document.getElementById("sendMailButton").removeAttribute('disabled');
+ document.getElementById("sendMailButton").style.color = "#fff";
+
+ document.encrypt.howLong.value =
+ (endTime.getTime()-startTime.getTime())/1000.0 + " ms";
+}
+/* ------------------------------------------------------------------------- */
+
+
+/* ------------------------------------------------------------------------- */
+function decryptWithKey(key) {
+ var text = document.decrypt.encryptedtext.value;
+ document.getElementById("decryptButton").setAttribute('disabled');
+ document.getElementById("decryptButton").style.color = "#333";
+ document.decrypt.encryptedtext.value = "Please wait...";
+ alert("This might take some time...");
+
+ var startTime = new Date();
+ if (undefined != key && key.length) {
+ key = OpenPGP_GetSecretInformation(key);
+ exp_u = key['u'];
+ exp_d = key['d'];
+ exp_p = key['p'];
+ exp_q = key['q'];
+ }
+ var text_plain = OpenPGP_Decrypt(exp_p, exp_q, exp_d, exp_u, text);
+ var endTime = new Date();
+
+ document.decrypt.encryptedtext.value = text_plain;
+ document.getElementById("decryptButton").removeAttribute('disabled');
+ document.getElementById("decryptButton").style.color = "#fff";
+
+ document.decrypt.howLongDecrypt.value =
+ (endTime.getTime()-startTime.getTime())/1000.0 + " ms";
+}
+
+function decrypt() {
+ dbGetFirstPrivateKey(decryptWithKey);
+}
+/* ------------------------------------------------------------------------- */
diff --git a/pool/shard010/JavaScript/0068896_users.controller.js b/pool/shard010/JavaScript/0068896_users.controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..d1626e68c4ad548f41d0b8776d13d24e5fb1743e
--- /dev/null
+++ b/pool/shard010/JavaScript/0068896_users.controller.js
@@ -0,0 +1,100 @@
+var config = require('config.json');
+var express = require('express');
+var router = express.Router();
+var userService = require('services/user.service');
+
+// routes
+router.post('/authenticate', authenticateUser);
+router.post('/register', registerUser);
+router.get('/current', getCurrentUser);
+router.get('/', getAllUsers);
+router.put('/:_id', updateUser);
+router.delete('/:_id', deleteUser);
+
+module.exports = router;
+
+function authenticateUser(req, res) {
+ userService.authenticate(req.body.username, req.body.password)
+ .then(function (token) {
+ if (token) {
+ // authentication successful
+ res.send({ token: token });
+ } else {
+ // authentication failed
+ res.status(401).send('Username or password is incorrect');
+ }
+ })
+ .catch(function (err) {
+ res.status(400).send(err);
+ });
+}
+
+function registerUser(req, res) {
+ userService.create(req.body)
+ .then(function () {
+ res.sendStatus(200);
+ })
+ .catch(function (err) {
+ res.status(400).send(err);
+ });
+}
+
+function getAllUsers(req, res) {
+ userService.getAll()
+ .then(function (users) {
+ if (users) {
+ res.send(users);
+ } else {
+ res.sendStatus(404);
+ }
+ })
+ .catch(function (err) {
+ res.status(400).send(err);
+ });
+ }
+
+function getCurrentUser(req, res) {
+ userService.getById(req.user.sub)
+ .then(function (user) {
+ if (user) {
+ res.send(user);
+ } else {
+ res.sendStatus(404);
+ }
+ })
+ .catch(function (err) {
+ res.status(400).send(err);
+ });
+}
+
+function updateUser(req, res) {
+ var userId = req.user.sub;
+ if (req.params._id !== userId) {
+ // can only update own account
+ return res.status(401).send('You can only update your own account');
+ }
+
+ userService.update(userId, req.body)
+ .then(function () {
+ res.sendStatus(200);
+ })
+ .catch(function (err) {
+ res.status(400).send(err);
+ });
+}
+
+function deleteUser(req, res) {
+ var userId = req.user.sub;
+ if (req.params._id !== userId) {
+ // can only delete own account
+ return res.status(401).send('You can only delete your own account');
+ }
+
+ userService.delete(userId)
+ .then(function () {
+ res.sendStatus(200);
+ })
+ .catch(function (err) {
+ res.status(400).send(err);
+ });
+}
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068897_EntityOverlayLaser.js b/pool/shard010/JavaScript/0068897_EntityOverlayLaser.js
new file mode 100644
index 0000000000000000000000000000000000000000..59dcaaf50305676aaaab8eb8f4b17621a79e65d5
--- /dev/null
+++ b/pool/shard010/JavaScript/0068897_EntityOverlayLaser.js
@@ -0,0 +1,65 @@
+/**
+ * @author Jordi Ros: shine.3p@gmail.com
+ *
+ */
+
+var EntityOverlayLaser = EntityOverlayLaser || {};
+
+//--------------------------------------------------------------------------------------------------------
+// Entity
+//--------------------------------------------------------------------------------------------------------
+EntityOverlayLaser.create = function(world, name, params) {
+ var entity = Entity.create(world, name, 'OVERLAYLASER', params);
+ entity.sprite1 = Sprite.create(world, params.sprite);
+ entity.sprite2 = Sprite.create(world, params.sprite);
+ entity.sprite1.overlay = true;
+ entity.sprite2.overlay = true;
+ entity.position.x = params.position.x;
+ entity.position.y = params.position.y;
+
+ // Init
+ entity.init = function() {
+ this.realw = this.sprite2.sprite.getSeq('Barra').size.x;
+ this.reset();
+ }
+
+ // Reset
+ entity.reset = function() {
+ this.show(0, true);
+ this.timeflash = 0;
+ this.size = 1;
+ this.sprite1.playSeq(0, 'Fondo');
+ this.sprite2.playSeq(0, 'Barra');
+ this.visible = this.params.hidden ? false : true;
+ }
+
+ // Update
+ entity.update = function(time, delta) {
+ this.sprite1.update(time, delta);
+ this.sprite2.update(time, delta);
+ this.flash = MTime010(time, this.timeflash, 0.25);
+ this.fade = this.visible ? MTime01(time, this.timeVisible, 0.5) : MTime10(time, this.timeVisible, 0.5);
+ }
+
+ // Render
+ entity.render = function(fade) {
+ var f = fade * this.fade;
+ // Fondo
+ this.sprite2.sprite.getFrame(0).w = 1;
+ this.sprite2.sprite.getSeq('Fondo').size.x = this.realw * 1;
+ this.sprite1.render(this.position, this.scale, 0, f, 0);
+ // Barra
+ this.sprite2.sprite.getFrame(1).w = this.size;
+ this.sprite2.sprite.getSeq('Barra').size.x = this.realw * this.size;
+ this.sprite2.render(this.position, this.scale, 0, f, f * this.flash);
+ }
+
+ // Use
+ entity.setSize = function(time, size) {
+ if (size != this.size && size == 1)
+ this.timeflash = time;
+ this.size = size;
+ }
+
+ return entity;
+}
diff --git a/pool/shard010/JavaScript/0068899_bench.js b/pool/shard010/JavaScript/0068899_bench.js
new file mode 100644
index 0000000000000000000000000000000000000000..4852da0f396fe50e2901f173404ec97e1d6b96c8
--- /dev/null
+++ b/pool/shard010/JavaScript/0068899_bench.js
@@ -0,0 +1,38 @@
+const fs = require('fs');
+const path = require('path');
+const load = require('load-json-file');
+const Benchmark = require('benchmark');
+const nearestPointOnLine = require('./').default;
+
+const directory = path.join(__dirname, 'test', 'in') + path.sep;
+const fixtures = fs.readdirSync(directory).map(filename => {
+ return {
+ filename,
+ name: path.parse(filename).name,
+ geojson: load.sync(directory + filename)
+ };
+});
+
+/**
+ * Benchmark Results
+ *
+ * ==after (@turf/line-intersect)==
+ * line1 x 234,231 ops/sec ±1.78% (88 runs sampled)
+ * route1 x 161 ops/sec ±1.53% (80 runs sampled)
+ * route2 x 184 ops/sec ±1.96% (80 runs sampled)
+ *
+ * ==before (original)==
+ * line1 x 272,785 ops/sec ±1.29% (87 runs sampled)
+ * route1 x 195 ops/sec ±2.23% (80 runs sampled)
+ * route2 x 218 ops/sec ±2.42% (78 runs sampled)
+ */
+const suite = new Benchmark.Suite('turf-nearest-point-on-line');
+for (const {name, geojson} of fixtures) {
+ const [line, point] = geojson.features;
+ suite.add(name, () => nearestPointOnLine(line, point));
+}
+
+suite
+ .on('cycle', e => console.log(String(e.target)))
+ .on('complete', () => {})
+ .run();
diff --git a/pool/shard010/JavaScript/0068900_BodyPanelView.js b/pool/shard010/JavaScript/0068900_BodyPanelView.js
new file mode 100644
index 0000000000000000000000000000000000000000..7adc0cb351dc53f40ae30dc5c2d4d58331f3784f
--- /dev/null
+++ b/pool/shard010/JavaScript/0068900_BodyPanelView.js
@@ -0,0 +1,101 @@
+/**
+ * Created by kevin.mayo on 31/08/16.
+ */
+var BodyPanelView = (function () {
+ var BodyPanelView = function (el) {
+ this.name = name || "Body Panel";
+ this.el = el;
+ this.model = null;
+ this.pos = {
+ x: 0,
+ y: 0
+ };
+ this.invalidated = false;
+
+ this.transition = {
+ type: "",
+ startTime: -1,
+ duration: -1,
+ onComplete: function () {
+ },
+ onUpdate: function () {
+
+ },
+ startPos: 0,
+ destPos: null,
+
+ startOpacityTransition : function () {
+ console.log("BODY PANEL LELE");
+ }
+ }
+ };
+
+ BodyPanelView.prototype = new View;
+
+
+ BodyPanelView.prototype.draw = function () {
+ if (this.transition.startTime != -1)
+ this.transition.onUpdate();
+
+ if (this.invalidated) {
+ this.el.style.transform = "translate3d(" + this.pos.x + "px, " + this.pos.y + "px,0px)";
+ this.invalidated = false;
+ }
+
+ };
+
+ BodyPanelView.prototype.update = function (changed) {
+ if (changed == "state") {
+ this.setState(this.model.getState());
+ }
+ };
+
+ BodyPanelView.prototype.setState = function (state) {
+ switch (state) {
+ case State.INTRO:
+ this.startIntroAnimation();
+ break;
+ case State.LEFT:
+ this.transition.destPos = window.innerWidth / 2 - 100;
+ this.startAnimation(1500);
+ break;
+ case State.RIGHT:
+ this.transition.destPos = -window.innerWidth / 2 + 100;
+ this.startAnimation(1500);
+ break;
+ case State.NONE:
+ this.transition.destPos = 0;
+ this.startAnimation(2000);
+ break;
+ }
+ };
+
+ BodyPanelView.prototype.startIntroAnimation = function () {
+ //should just be the intro text fading in.
+ };
+
+ BodyPanelView.prototype.startAnimation = function (duration) {
+ var _this = this;
+ this.transition.startTime = Date.now();
+ this.transition.duration = duration;
+
+ this.transition.onUpdate = function () {
+
+ var value = (Date.now() - this.startTime) / this.duration;
+ value = Math.pow(value, 2);
+
+ _this.pos.x = _this.pos.x + (this.destPos - _this.pos.x) * value;
+
+ _this.invalidated = true;
+
+ if (value > 1) {
+ this.onComplete();
+ }
+ };
+ this.transition.onComplete = function () {
+
+ this.startTime = -1;
+ }
+ };
+ return BodyPanelView;
+})();
diff --git a/pool/shard010/JavaScript/0068902_test.js b/pool/shard010/JavaScript/0068902_test.js
new file mode 100644
index 0000000000000000000000000000000000000000..48e991085fbfd7d5d417791ac507bb053fb591a5
--- /dev/null
+++ b/pool/shard010/JavaScript/0068902_test.js
@@ -0,0 +1,14 @@
+'use strict'
+
+var tape = require('tape')
+var orientation = require('../orientation')
+
+tape('cell-orientation', function(t) {
+
+ t.equals(orientation([0, 1, 2]), 1)
+ t.equals(orientation([1, 0, 2]), -1)
+ t.equals(orientation([0, 2, 1]), -1)
+ t.equals(orientation([1, 1, 2]), 0)
+
+ t.end()
+})
diff --git a/pool/shard010/JavaScript/0068903_shape.js b/pool/shard010/JavaScript/0068903_shape.js
new file mode 100644
index 0000000000000000000000000000000000000000..be98630f00453080ddda8a84de36bc1c2217414e
--- /dev/null
+++ b/pool/shard010/JavaScript/0068903_shape.js
@@ -0,0 +1,21 @@
+LMAG.components.shape = (function() {
+ var shapeComponent = new LMAG.engine.component('shape', {});
+
+ return function(config) {
+ var data = {
+ type: config.type || 1
+ };
+
+ switch(data.type) {
+ case 1: //circle
+ data.radius = config.radius || 100;
+ break;
+ case 2: //rectangle
+ data.width = config.width || 100;
+ data.height = config.height || 100;
+ }
+
+ shapeComponent.shape = data;
+ return shapeComponent;
+ };
+})();
diff --git a/pool/shard010/JavaScript/0068906_canvas.js b/pool/shard010/JavaScript/0068906_canvas.js
new file mode 100644
index 0000000000000000000000000000000000000000..44985d880c350aa2c6fe1726130e4a44624439dc
--- /dev/null
+++ b/pool/shard010/JavaScript/0068906_canvas.js
@@ -0,0 +1,90 @@
+
+var Canvas = function(width, height){
+ this.canvas = document.createElement("canvas");
+ this.canvas.width = width;
+ this.canvas.height = height;
+ this.context = this.canvas.getContext("2d");
+}
+
+Canvas.prototype.createFromFile = function(path, parentNode){
+ var ctx = this.context;
+ var img = new Image();
+ img.src = path;
+ img.onload = function(){
+ ctx.drawImage(img, 0, 0, 400, 300);
+ testRun();
+ }
+ parentNode.appendChild(this.canvas);
+}
+
+var Filter = function(ctx, data){
+ this.context = ctx;
+ this.imageData = data;
+ this.pixelData = this.imageData.data;
+ this.numPixels = this.imageData.width * this.imageData.height;
+ this.r, this.g, this.b;
+}
+
+Filter.prototype.invert = function(){
+ for(var i=0; i {
+ if (!Array.isArray(arr)) {
+ return undefined
+ }
+
+ let chunks = [],
+ i = 0,
+ j = arr.length;
+
+ while (i < j) {
+ chunks.push(arr.slice(i, i += split));
+ }
+
+ return chunks;
+}
+
+module.exports = {
+ chunk
+}
diff --git a/pool/shard010/JavaScript/0068908_webpack.dev.conf.js b/pool/shard010/JavaScript/0068908_webpack.dev.conf.js
new file mode 100644
index 0000000000000000000000000000000000000000..25523b3418db85efee872de31542be4f2fb52055
--- /dev/null
+++ b/pool/shard010/JavaScript/0068908_webpack.dev.conf.js
@@ -0,0 +1,41 @@
+var webpack = require('webpack')
+var merge = require('webpack-merge')
+var utils = require('./utils')
+var baseWebpackConfig = require('./webpack.base.conf')
+var HtmlWebpackPlugin = require('html-webpack-plugin')
+
+// add hot-reload related code to entry chunks
+Object.keys(baseWebpackConfig.entry).forEach(function (name) {
+ baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
+})
+
+var configDev = merge(baseWebpackConfig, {
+ module: {
+ loaders: utils.styleLoaders()
+ },
+ // eval-source-map is faster for development
+ devtool: '#eval-source-map',
+ plugins: [
+ // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
+ new webpack.optimize.OccurenceOrderPlugin(),
+ new webpack.HotModuleReplacementPlugin(),
+ new webpack.NoErrorsPlugin(),
+ // https://github.com/ampedandwired/html-webpack-plugin
+ ]
+})
+
+for (var key in baseWebpackConfig.entry) {
+ configDev.plugins.push(
+ // generate dist index.html with correct asset hash for caching.
+ // you can customize output by editing /index.html
+ // see https://github.com/ampedandwired/html-webpack-plugin
+ new HtmlWebpackPlugin({
+ filename: key + '.html',
+ template: 'src/' + key + '.html',
+ inject: true,
+ chunks: [key]
+ })
+ )
+}
+
+module.exports = configDev
diff --git a/pool/shard010/JavaScript/0068910_build_db.js b/pool/shard010/JavaScript/0068910_build_db.js
new file mode 100644
index 0000000000000000000000000000000000000000..675a322c64d504328ae1902032e2559af7da6bde
--- /dev/null
+++ b/pool/shard010/JavaScript/0068910_build_db.js
@@ -0,0 +1,66 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview Collect JS nodes.
+ */
+
+const program = require('commander');
+
+const corpus = require('./corpus.js');
+const db = require('./db.js');
+const path = require('path');
+
+const sourceHelpers = require('./source_helpers.js');
+
+function main() {
+ Error.stackTraceLimit = Infinity;
+
+ program
+ .version('0.0.1')
+ .option('-i, --input_dir ', 'Input directory.')
+ .option('-o, --output_dir ', 'Output directory.')
+ .parse(process.argv);
+
+ if (!program.args.length) {
+ console.log('Need to specify corpora.');
+ return;
+ }
+
+ if (!program.output_dir) {
+ console.log('Need to specify output dir.');
+ return;
+ }
+
+ const mutateDb = new db.MutateDbWriter(program.output_dir);
+ const expressions = new Set();
+
+ const inputDir = path.resolve(program.input_dir);
+ for (const corpusName of program.args) {
+ const curCorpus = new corpus.Corpus(inputDir, corpusName);
+ for (const relPath of curCorpus.relFiles()) {
+ let source;
+ try {
+ source = sourceHelpers.loadSource(inputDir, relPath);
+ } catch (e) {
+ console.log(e);
+ continue;
+ }
+
+ if (!source) {
+ continue;
+ }
+
+ try{
+ mutateDb.process(source, expressions);
+ } catch (e) {
+ console.log(e);
+ }
+ }
+ }
+
+ mutateDb.writeIndex();
+}
+
+main();
diff --git a/pool/shard010/JavaScript/0068911_preload.js b/pool/shard010/JavaScript/0068911_preload.js
new file mode 100644
index 0000000000000000000000000000000000000000..cf7a18c05d182a61c1ed37277969faedf2eb3b53
--- /dev/null
+++ b/pool/shard010/JavaScript/0068911_preload.js
@@ -0,0 +1,43 @@
+'use strict'
+
+const electron = require('electron')
+const remote = electron.remote
+const Menu = remote.Menu
+
+const InputMenu = Menu.buildFromTemplate([
+ {
+ type: 'separator'
+ },
+ {
+ label: 'Cut',
+ role: 'cut'
+ },
+ {
+ label: 'Copy',
+ role: 'copy'
+ },
+ {
+ label: 'Paste',
+ role: 'paste'
+ }
+])
+
+// https://github.com/electron/electron/issues/4068#issuecomment-170911307
+window.addEventListener('DOMContentLoaded', () => {
+ document.body.addEventListener('contextmenu', e => {
+ e.preventDefault()
+ e.stopPropagation()
+
+ let node = e.target
+
+ while (node) {
+ if (node.nodeName.match(/DIV/) && node.className && node.className.match(/^CodeMirror.*$/i)) {
+ InputMenu.popup(remote.getCurrentWindow())
+
+ break
+ }
+
+ node = node.parentNode
+ }
+ })
+})
diff --git a/pool/shard010/JavaScript/0068912_ReactDOMEventListener-test.js b/pool/shard010/JavaScript/0068912_ReactDOMEventListener-test.js
new file mode 100644
index 0000000000000000000000000000000000000000..e80d40d6dd7adda54baf2f44e9497ca40cc581f8
--- /dev/null
+++ b/pool/shard010/JavaScript/0068912_ReactDOMEventListener-test.js
@@ -0,0 +1,215 @@
+/**
+ * Copyright 2013-present, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @emails react-core
+ */
+
+'use strict';
+
+var EVENT_TARGET_PARAM = 1;
+
+describe('ReactDOMEventListener', () => {
+ var React;
+ var ReactDOM;
+ var ReactDOMComponentTree;
+ var ReactDOMEventListener;
+ var ReactTestUtils;
+ var handleTopLevel;
+
+ beforeEach(() => {
+ jest.resetModules();
+ React = require('react');
+ ReactDOM = require('react-dom');
+ ReactDOMComponentTree = require('ReactDOMComponentTree');
+ ReactDOMEventListener = require('ReactDOMEventListener');
+ ReactTestUtils = require('ReactTestUtils');
+
+ handleTopLevel = jest.fn();
+ ReactDOMEventListener._handleTopLevel = handleTopLevel;
+ });
+
+ it('should dispatch events from outside React tree', () => {
+ var otherNode = document.createElement('h1');
+ var component = ReactDOM.render(
, document.createElement('div'));
+ expect(handleTopLevel.mock.calls.length).toBe(0);
+ ReactDOMEventListener.dispatchEvent('topMouseOut', {
+ type: 'mouseout',
+ fromElement: otherNode,
+ target: otherNode,
+ srcElement: otherNode,
+ toElement: ReactDOM.findDOMNode(component),
+ relatedTarget: ReactDOM.findDOMNode(component),
+ view: window,
+ path: [otherNode, otherNode],
+ });
+ expect(handleTopLevel.mock.calls.length).toBe(1);
+ });
+
+ describe('Propagation', () => {
+ it('should propagate events one level down', () => {
+ var childContainer = document.createElement('div');
+ var childControl = Child
;
+ var parentContainer = document.createElement('div');
+ var parentControl = Parent
;
+ childControl = ReactDOM.render(childControl, childContainer);
+ parentControl = ReactDOM.render(parentControl, parentContainer);
+ ReactDOM.findDOMNode(parentControl).appendChild(childContainer);
+
+ var callback = ReactDOMEventListener.dispatchEvent.bind(null, 'test');
+ callback({
+ target: ReactDOM.findDOMNode(childControl),
+ });
+
+ var calls = handleTopLevel.mock.calls;
+ expect(calls.length).toBe(2);
+ expect(calls[0][EVENT_TARGET_PARAM]).toBe(
+ ReactDOMComponentTree.getInstanceFromNode(childControl),
+ );
+ expect(calls[1][EVENT_TARGET_PARAM]).toBe(
+ ReactDOMComponentTree.getInstanceFromNode(parentControl),
+ );
+ });
+
+ it('should propagate events two levels down', () => {
+ var childContainer = document.createElement('div');
+ var childControl = Child
;
+ var parentContainer = document.createElement('div');
+ var parentControl = Parent
;
+ var grandParentContainer = document.createElement('div');
+ var grandParentControl = Parent
;
+ childControl = ReactDOM.render(childControl, childContainer);
+ parentControl = ReactDOM.render(parentControl, parentContainer);
+ grandParentControl = ReactDOM.render(
+ grandParentControl,
+ grandParentContainer,
+ );
+ ReactDOM.findDOMNode(parentControl).appendChild(childContainer);
+ ReactDOM.findDOMNode(grandParentControl).appendChild(parentContainer);
+
+ var callback = ReactDOMEventListener.dispatchEvent.bind(null, 'test');
+ callback({
+ target: ReactDOM.findDOMNode(childControl),
+ });
+
+ var calls = handleTopLevel.mock.calls;
+ expect(calls.length).toBe(3);
+ expect(calls[0][EVENT_TARGET_PARAM]).toBe(
+ ReactDOMComponentTree.getInstanceFromNode(childControl),
+ );
+ expect(calls[1][EVENT_TARGET_PARAM]).toBe(
+ ReactDOMComponentTree.getInstanceFromNode(parentControl),
+ );
+ expect(calls[2][EVENT_TARGET_PARAM]).toBe(
+ ReactDOMComponentTree.getInstanceFromNode(grandParentControl),
+ );
+ });
+
+ it('should not get confused by disappearing elements', () => {
+ var childContainer = document.createElement('div');
+ var childControl = Child
;
+ var parentContainer = document.createElement('div');
+ var parentControl = Parent
;
+ childControl = ReactDOM.render(childControl, childContainer);
+ parentControl = ReactDOM.render(parentControl, parentContainer);
+ ReactDOM.findDOMNode(parentControl).appendChild(childContainer);
+
+ // ReactBrowserEventEmitter.handleTopLevel might remove the
+ // target from the DOM. Here, we have handleTopLevel remove the
+ // node when the first event handlers are called; we'll still
+ // expect to receive a second call for the parent control.
+ var childNode = ReactDOM.findDOMNode(childControl);
+ handleTopLevel.mockImplementation(function(
+ topLevelType,
+ topLevelTarget,
+ topLevelTargetID,
+ nativeEvent,
+ ) {
+ if (topLevelTarget === childNode) {
+ ReactDOM.unmountComponentAtNode(childContainer);
+ }
+ });
+
+ var callback = ReactDOMEventListener.dispatchEvent.bind(null, 'test');
+ callback({
+ target: childNode,
+ });
+
+ var calls = handleTopLevel.mock.calls;
+ expect(calls.length).toBe(2);
+ expect(calls[0][EVENT_TARGET_PARAM]).toBe(
+ ReactDOMComponentTree.getInstanceFromNode(childNode),
+ );
+ expect(calls[1][EVENT_TARGET_PARAM]).toBe(
+ ReactDOMComponentTree.getInstanceFromNode(parentControl),
+ );
+ });
+
+ it('should batch between handlers from different roots', () => {
+ var childContainer = document.createElement('div');
+ var parentContainer = document.createElement('div');
+ var childControl = ReactDOM.render(Child
, childContainer);
+ var parentControl = ReactDOM.render(Parent
, parentContainer);
+ ReactDOM.findDOMNode(parentControl).appendChild(childContainer);
+
+ // Suppose an event handler in each root enqueues an update to the
+ // childControl element -- the two updates should get batched together.
+ var childNode = ReactDOM.findDOMNode(childControl);
+ handleTopLevel.mockImplementation(function(
+ topLevelType,
+ topLevelTarget,
+ topLevelTargetID,
+ nativeEvent,
+ ) {
+ ReactDOM.render(
+ {topLevelTarget === childNode ? '1' : '2'}
,
+ childContainer,
+ );
+ // Since we're batching, neither update should yet have gone through.
+ expect(childNode.textContent).toBe('Child');
+ });
+
+ var callback = ReactDOMEventListener.dispatchEvent.bind(
+ ReactDOMEventListener,
+ 'test',
+ );
+ callback({
+ target: childNode,
+ });
+
+ var calls = handleTopLevel.mock.calls;
+ expect(calls.length).toBe(2);
+ expect(childNode.textContent).toBe('2');
+ });
+ });
+
+ it('should not fire duplicate events for a React DOM tree', () => {
+ class Wrapper extends React.Component {
+ getInner = () => {
+ return this.refs.inner;
+ };
+
+ render() {
+ var inner = Inner
;
+ return ;
+ }
+ }
+
+ var instance = ReactTestUtils.renderIntoDocument( );
+
+ var callback = ReactDOMEventListener.dispatchEvent.bind(null, 'test');
+ callback({
+ target: ReactDOM.findDOMNode(instance.getInner()),
+ });
+
+ var calls = handleTopLevel.mock.calls;
+ expect(calls.length).toBe(1);
+ expect(calls[0][EVENT_TARGET_PARAM]).toBe(
+ ReactDOMComponentTree.getInstanceFromNode(instance.getInner()),
+ );
+ });
+});
diff --git a/pool/shard010/JavaScript/0068913_cli.js b/pool/shard010/JavaScript/0068913_cli.js
new file mode 100644
index 0000000000000000000000000000000000000000..26443a0587c64dfccff8d9c6abdc37a7e98b61d8
--- /dev/null
+++ b/pool/shard010/JavaScript/0068913_cli.js
@@ -0,0 +1,60 @@
+const root = __dirname + '/..';
+
+require('@babel/register')({
+ root,
+ cwd: root,
+ configFile: root + '/tools/babel.config.js',
+ extensions: ['.js', '.jsx', '.ts', '.tsx']
+});
+
+const prog = require('caporal');
+const addModuleCommand = require('./cli/commands/addModule');
+const deleteModuleCommand = require('./cli/commands/deleteModule');
+const chooseTemplateCommand = require('./cli/commands/chooseTemplate');
+const deleteStackCommand = require('./cli/commands/deleteStack');
+
+const CommandInvoker = require('./cli/CommandInvoker');
+
+const commandInvoker = new CommandInvoker(
+ addModuleCommand,
+ deleteModuleCommand,
+ chooseTemplateCommand,
+ deleteStackCommand
+);
+
+prog
+ .version('1.0.0')
+ .description('Full info: https://github.com/sysgears/apollo-universal-starter-kit/blob/master/docs/tools/cli.md')
+ // Add module
+ .command('addmodule', 'Create a new Module.')
+ .argument('', 'Module name')
+ .argument(
+ '[location]',
+ 'Where should new module be created. [both, server, client]',
+ ['both', 'server', 'client'],
+ 'both'
+ )
+ .option('-o, --old', 'Old Structure')
+ .action((args, options, logger) => commandInvoker.runAddModule(args, options, logger))
+ // Delete module
+ .command('deletemodule', 'Delete a Module')
+ .argument('', 'Module name')
+ .argument('[location]', 'Where should we delete module. [both, server, client]', ['both', 'server', 'client'], 'both')
+ .option('-o, --old', 'Old Structure')
+ .action((args, options, logger) => commandInvoker.runDeleteModule(args, options, logger))
+ // Choose stack
+ .command('choosestack', 'Choose the stack of technologies for the app')
+ .action(() => commandInvoker.runChooseStack())
+ .command(
+ 'deletestack',
+ `Delete the stack of technologies for the app.
+List of technologies [react, angular, vue, scala, node]`
+ )
+ .argument('[stackList...]', 'List of technologies [react, angular, vue, scala, node]')
+ .option('-l --list', 'Show stack of technologies list')
+
+ .action(({ stackList }, { list }, logger) => {
+ commandInvoker.runDeleteStack(stackList, logger, list);
+ });
+
+prog.parse(process.argv);
diff --git a/pool/shard010/JavaScript/0068916_welcome_page.js b/pool/shard010/JavaScript/0068916_welcome_page.js
new file mode 100644
index 0000000000000000000000000000000000000000..de42f55b49554c5726fdf5835b925cea35f5730b
--- /dev/null
+++ b/pool/shard010/JavaScript/0068916_welcome_page.js
@@ -0,0 +1,36 @@
+$(document).ready(function(){
+ console.log("what?")
+
+ $("#signup_button").on("click", function(e){
+ e.preventDefault();
+ console.log("ding")
+
+ $.ajax({
+ url: $("#signup_link").attr("href"),
+ method: $("#signup_link").attr("method"),
+ success: function(response){
+ var signup_form = $(response).find("#sign_up_form");
+ $("#opening_forms").html(signup_form[0])
+ }
+ })
+ });
+
+
+
+
+ $("#login_button").on("click", function(e){
+ e.preventDefault();
+
+ $.ajax({
+ url: $("#login_link").attr("href"),
+ method: $("#login_link").attr("method"),
+ success: function(response){
+ var login_form = $(response).find("#login_form");
+ $("#opening_forms").html(login_form[0])
+ }
+
+ })
+ });
+
+
+});
diff --git a/pool/shard010/JavaScript/0068918_videodragproperties.js b/pool/shard010/JavaScript/0068918_videodragproperties.js
new file mode 100644
index 0000000000000000000000000000000000000000..5e09035d29826baf8e01ff183f20e8c694d1f06e
--- /dev/null
+++ b/pool/shard010/JavaScript/0068918_videodragproperties.js
@@ -0,0 +1,129 @@
+//this function is for check and add properties in Video Drag&Drop
+var Excel = require ( 'exceljs' );
+var workbook1 = new Excel.Workbook ( );
+if ( typeof require !== 'undefined' ) XLSX = require ( 'xlsx' );
+var result = [ ];
+exports.command = function ( videoTitle, shortTitle, shortDesc, author, attribution, categoryName, shortNote, dragImg, currentCount ) {
+ this.pause ( 3000 ).
+ //Wait for Edit the title is visible
+ waitForElementVisible ( '.container-head > text-field > input', 3000, false ).
+ //Verify the Video Title field is visible
+ verify.visible ( ".container-head > text-field > input" ).
+ //Clear the Video Title data in the field
+ clearValue ( '.container-head > text-field > input' ).
+ //Enter the Video Title data in the field
+ setValue ( '.container-head > text-field > input', videoTitle ).
+ //Check the description display
+ verify.visible ( "#wmd-input-0" ).
+ //Verify the properties tab is visible
+ verify.visible ( ".video-tabs > a[ href='#properties']" ).
+ //Click the properties tab
+ click ( ".video-tabs > a[ href='#properties']" ).
+ pause ( 3000 ).
+ //Check and enter short name
+ verify.visible ( "textarea[ ng-model='artifact.shortName']" ).
+ //Clear the Shortname data in the field
+ clearValue ( "textarea[ ng-model='artifact.shortName']" ).
+ //Enter the Shortname data in the field
+ setValue ( "textarea[ ng-model='artifact.shortName']", shortTitle ).
+ //Check and enter short description
+ verify.visible ( "textarea[ ng-model='artifact.shortDescription']" ).
+ //Clear the Short description data in the field
+ clearValue ( "textarea[ ng-model='artifact.shortDescription']" ).
+ //Enter the Short description data in the field
+ setValue ( "textarea[ ng-model='artifact.shortDescription']", shortDesc ).
+ pause ( 3000 ).
+ //Select Author name
+ verify.visible ( ".attribution-container>a[ng-click='showAddAuthor()']" ).
+ //Click on the Authors dropdown option
+ click ( ".attribution-container>a[ng-click='showAddAuthor()']" ).
+ pause ( 3000 ).useXpath ( ).
+ //Enter the search data in the field
+ setValue ( '//input[@placeholder ="Search authors"]',author.trim() )
+ this.pause ( 3000 ).
+ //click on the searched Author
+ click ( "//ul/li/a/span[ text( ) = '"+ author.trim() +"']" ).
+ pause ( 3000 ).useCss ( ).
+ //Get the Attribution values
+ getValue ( ".add-icon", function ( attributeExist ) {
+ var attributeExistValuse = attributeExist.value;
+ if ( attributeExistValuse === true ) {
+ //Verify the Attribution field is visible
+ this.verify.visible ( ".attribution-container>a[ng-click='showAddAttribution()']" ).
+ //Click on the Attribution dropdown option
+ click ( ".attribution-container>a[ng-click='showAddAttribution()']" ).
+ pause ( 3000 ).useXpath ( ).
+ //Enter the Attribution name in the field
+ setValue ( '//input[@placeholder ="Search attributions"]',attribution.trim( ) ).
+ pause ( 3000 ).
+ //click on the searched Attribution
+ click ( "//ul/li/a/span[contains(.,'"+ attribution.trim( ) +"')]" ).
+ pause ( 3000 ).useCss ( )
+ }
+ else {
+ }
+ });
+ //Wait for categories name field is visible
+ this.waitForElementVisible ( '.collections-widget', 3000,false ).
+ //Verify categories name field is visible
+ verify.visible ( ".collections-widget" ).
+ pause ( 3000 ).
+ //clear the text in the category field
+ clearValue ( ".collections-widget > input" ).
+ //Enter the categories name
+ setValue ( ".collections-widget > input", categoryName ).
+ pause ( 3000 ).
+ verify.visible ( ".suggestion-list-wrap > div:nth-child( 1 ) > div:nth-child( 1 ) > span:nth-child( 1 )" ).
+ //click on the category name from the list
+ click ( ".suggestion-list-wrap > div:nth-child( 1 ) > div:nth-child( 1 ) > span:nth-child( 1 )" ).
+ pause ( 3000 ).
+ //Clear the Short Note data in the field
+ clearValue ( "textarea[ ng-model='artifact.note' ]" ).
+ //Click on the Short Note data in the field
+ setValue ( "textarea[ ng-model='artifact.note' ]", shortNote ).
+ pause ( 3000 ).
+ verify.visible ( "a.btn-active" ).
+ pause ( 3000 ).
+ //Click on the Save button
+ click ( "a.btn-active" ).
+ pause ( 3000 ).
+ //Check Thumbnail ADD and Delete
+ waitForElementVisible ( ".uploaded-image-container", 9000, false ).
+ pause ( 3000 ).
+ getAttribute ( ".uploaded-image", "src", function ( imageCheck ) {
+ var imageValue = imageCheck.value;
+ var imageStatus = imageCheck.status;
+ if ( imageStatus === 0 ) {
+ this.pause ( 3000 ).
+ verify.visible ( " .content-menu > li:nth-child( 3 ) > a:nth-child( 1 )" ).
+ pause ( 3000 ).
+ click ( ".content-menu > li:nth-child( 3 ) > a:nth-child( 1 )" ).
+ pause ( 3000 ).
+ waitForElementNotPresent ( ".uploaded-image-container", 9000, false ).
+ pause ( 3000 ).
+ setValue ( 'span.hidden-input:nth-child( 1 ) > input:nth-child( 1 )', require ( 'path' ).resolve ( dragImg ) ).
+ pause ( 3000 )
+ }
+ else {
+ }
+ } );
+ //Check and click save button
+ this.verify.visible ( "a.btn-active" ).
+ pause ( 3000 ).
+ //Click on the Save button
+ click ( "a.btn-active" ).
+ pause ( 3000 ).
+ //Check and click Distribution Tab
+ verify.visible ( ".video-tabs a[ href='#distribution']" ).
+ pause ( 3000 ).
+ //click on the distribution tab
+ click ( ".video-tabs a[ href='#distribution']" ).
+ pause ( 3000 ).useXpath ( ).
+ //verify and click on the videoe menu in CONTENT
+ verify.containsText ( "//ul/li/a[ text( ) = 'Videos']" , "Videos" ).
+ pause ( 3000 ).
+ //Click on the videos menu in CONTENT
+ click ( "//ul/li/a[ text( ) = 'Videos']" ).
+ useCss ( ).pause ( 3000 )
+ return this;
+};
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068925_queue.js b/pool/shard010/JavaScript/0068925_queue.js
new file mode 100644
index 0000000000000000000000000000000000000000..f11bd4a2fb848a90bb4650d396d9c3ff20481c50
--- /dev/null
+++ b/pool/shard010/JavaScript/0068925_queue.js
@@ -0,0 +1,46 @@
+"use strict";
+/**
+ * @module common
+ */ /** for typedoc */
+Object.defineProperty(exports, "__esModule", { value: true });
+var Queue = /** @class */ (function () {
+ function Queue(_items, _limit) {
+ if (_items === void 0) { _items = []; }
+ if (_limit === void 0) { _limit = null; }
+ this._items = _items;
+ this._limit = _limit;
+ }
+ Queue.prototype.enqueue = function (item) {
+ var items = this._items;
+ items.push(item);
+ if (this._limit && items.length > this._limit)
+ items.shift();
+ return item;
+ };
+ Queue.prototype.dequeue = function () {
+ if (this.size())
+ return this._items.splice(0, 1)[0];
+ };
+ Queue.prototype.clear = function () {
+ var current = this._items;
+ this._items = [];
+ return current;
+ };
+ Queue.prototype.size = function () {
+ return this._items.length;
+ };
+ Queue.prototype.remove = function (item) {
+ var idx = this._items.indexOf(item);
+ return idx > -1 && this._items.splice(idx, 1)[0];
+ };
+ Queue.prototype.peekTail = function () {
+ return this._items[this._items.length - 1];
+ };
+ Queue.prototype.peekHead = function () {
+ if (this.size())
+ return this._items[0];
+ };
+ return Queue;
+}());
+exports.Queue = Queue;
+//# sourceMappingURL=queue.js.map
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068926_product.js b/pool/shard010/JavaScript/0068926_product.js
new file mode 100644
index 0000000000000000000000000000000000000000..75d8eb92ea22b7476124653836780c95817212be
--- /dev/null
+++ b/pool/shard010/JavaScript/0068926_product.js
@@ -0,0 +1,15 @@
+
+'use strict';
+
+const bookshelf = require('../../config/bookshelf').getInstance();
+
+const Product = bookshelf.Model.extend({
+ tableName: 'products',
+ idAttribute: 'product_id',
+ hasTimestamps: ['created_at', 'updated_at'],
+ photos: function() {
+ return this.morphMany('Photo', 'imageable');
+ }
+});
+
+module.exports = bookshelf.model('Product', Product);
diff --git a/pool/shard010/JavaScript/0068927_trade.js b/pool/shard010/JavaScript/0068927_trade.js
new file mode 100644
index 0000000000000000000000000000000000000000..2901b163910e11d1bbd61216da7fc32f7e4c80e7
--- /dev/null
+++ b/pool/shard010/JavaScript/0068927_trade.js
@@ -0,0 +1,35 @@
+'use strict';
+// Stock is defined as the model, require that bad boy.
+const Stock = require('../models/stockquote');
+// When the router (routes/trade.js) does a GET on the method .index, it renders views/index.jade
+module.exports.index = (req, res) => {
+ res.render('index');
+};
+
+//When the router (routes/trade.js) does a POST on the method .buy, it does everything below.
+module.exports.buy = (req, res) => {
+// Show me what the req.body looks like when I put a symbol in the input box and press buy. This req.body is the name, sym, price, qty, and dowhat from routes/quotedetails.jade, passed through the route, output at the console (here).
+ console.log("buyPost", req.body);
+// Create a new Stock obj (see line 3 of this code). Put all that output, you can see in line 12's console.log in an object called myStock.
+ const myStock = new Stock({
+ name: req.body.name,
+ symbol: req.body.sym,
+ price: req.body.price,
+ qty: req.body.qty
+ });
+// Log the myStock that has been processed by the .buy method. Notice that the save below is WITHIN the buy.method.
+ console.log("buymyStock", myStock);
+// Save it to the database! Then render to the indexbuy.jade.
+ myStock.save((err, savedStock) => {
+ if (err) throw err;
+// Show me that the stock saved on the console.
+ console.log("savedStock", savedStock);
+// Show me the saved stock on the DOM.
+ res.render('indexbuy', {
+ savedStockName: savedStock.name,
+ savedStockSym: savedStock.symbol,
+ savedStockPrice: savedStock.price,
+ savedStockQty: savedStock.qty
+ });
+ });
+};
diff --git a/pool/shard010/JavaScript/0068928_RegularPolygon.js b/pool/shard010/JavaScript/0068928_RegularPolygon.js
new file mode 100644
index 0000000000000000000000000000000000000000..45332be9b071aa0d6e4e838d05c48566e01235c5
--- /dev/null
+++ b/pool/shard010/JavaScript/0068928_RegularPolygon.js
@@ -0,0 +1,429 @@
+/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for
+ * full list of contributors). Published under the Clear BSD license.
+ * See http://svn.openlayers.org/trunk/openlayers/license.txt for the
+ * full text of the license. */
+
+
+/**
+ * @requires OpenLayers/Handler/Drag.js
+ */
+
+/**
+ * Class: OpenLayers.Handler.RegularPolygon
+ * Handler to draw a regular polygon on the map. Polygon is displayed on mouse
+ * down, moves or is modified on mouse move, and is finished on mouse up.
+ * The handler triggers callbacks for 'done' and 'cancel'. Create a new
+ * instance with the constructor.
+ *
+ * Inherits from:
+ * -
+ */
+OpenLayers.Handler.RegularPolygon = OpenLayers.Class(OpenLayers.Handler.Drag, {
+
+ /**
+ * APIProperty: sides
+ * {Integer} Number of sides for the regular polygon. Needs to be greater
+ * than 2. Defaults to 4.
+ */
+ sides: 4,
+
+ /**
+ * APIProperty: radius
+ * {Float} Optional radius in map units of the regular polygon. If this is
+ * set to some non-zero value, a polygon with a fixed radius will be
+ * drawn and dragged with mose movements. If this property is not
+ * set, dragging changes the radius of the polygon. Set to null by
+ * default.
+ */
+ radius: null,
+
+ /**
+ * APIProperty: snapAngle
+ * {Float} If set to a non-zero value, the handler will snap the polygon
+ * rotation to multiples of the snapAngle. Value is an angle measured
+ * in degrees counterclockwise from the positive x-axis.
+ */
+ snapAngle: null,
+
+ /**
+ * APIProperty: snapToggle
+ * {String} If set, snapToggle is checked on mouse events and will set
+ * the snap mode to the opposite of what it currently is. To disallow
+ * toggling between snap and non-snap mode, set freehandToggle to
+ * null. Acceptable toggle values are 'shiftKey', 'ctrlKey', and
+ * 'altKey'. Snap mode is only possible if this.snapAngle is set to a
+ * non-zero value.
+ */
+ snapToggle: 'shiftKey',
+
+ /**
+ * Property: layerOptions
+ * {Object} Any optional properties to be set on the sketch layer.
+ */
+ layerOptions: null,
+
+ /**
+ * APIProperty: persist
+ * {Boolean} Leave the feature rendered until clear is called. Default
+ * is false. If set to true, the feature remains rendered until
+ * clear is called, typically by deactivating the handler or starting
+ * another drawing.
+ */
+ persist: false,
+
+ /**
+ * APIProperty: irregular
+ * {Boolean} Draw an irregular polygon instead of a regular polygon.
+ * Default is false. If true, the initial mouse down will represent
+ * one corner of the polygon bounds and with each mouse movement, the
+ * polygon will be stretched so the opposite corner of its bounds
+ * follows the mouse position. This property takes precedence over
+ * the radius property. If set to true, the radius property will
+ * be ignored.
+ */
+ irregular: false,
+
+ /**
+ * APIProperty: citeCompliant
+ * {Boolean} If set to true, coordinates of features drawn in a map extent
+ * crossing the date line won't exceed the world bounds. Default is false.
+ */
+ citeCompliant: false,
+
+ /**
+ * Property: angle
+ * {Float} The angle from the origin (mouse down) to the current mouse
+ * position, in radians. This is measured counterclockwise from the
+ * positive x-axis.
+ */
+ angle: null,
+
+ /**
+ * Property: fixedRadius
+ * {Boolean} The polygon has a fixed radius. True if a radius is set before
+ * drawing begins. False otherwise.
+ */
+ fixedRadius: false,
+
+ /**
+ * Property: feature
+ * {} The currently drawn polygon feature
+ */
+ feature: null,
+
+ /**
+ * Property: layer
+ * {} The temporary drawing layer
+ */
+ layer: null,
+
+ /**
+ * Property: origin
+ * {} Location of the first mouse down
+ */
+ origin: null,
+
+ /**
+ * Constructor: OpenLayers.Handler.RegularPolygon
+ * Create a new regular polygon handler.
+ *
+ * Parameters:
+ * control - {} The control that owns this handler
+ * callbacks - {Object} An object with a properties whose values are
+ * functions. Various callbacks described below.
+ * options - {Object} An object with properties to be set on the handler.
+ * If the options.sides property is not specified, the number of sides
+ * will default to 4.
+ *
+ * Named callbacks:
+ * create - Called when a sketch is first created. Callback called with
+ * the creation point geometry and sketch feature.
+ * done - Called when the sketch drawing is finished. The callback will
+ * recieve a single argument, the sketch geometry.
+ * cancel - Called when the handler is deactivated while drawing. The
+ * cancel callback will receive a geometry.
+ */
+ initialize: function(control, callbacks, options) {
+ if(!(options && options.layerOptions && options.layerOptions.styleMap)) {
+ this.style = OpenLayers.Util.extend(OpenLayers.Feature.Vector.style['default'], {});
+ }
+
+ OpenLayers.Handler.Drag.prototype.initialize.apply(this,
+ [control, callbacks, options]);
+ this.options = (options) ? options : {};
+ },
+
+ /**
+ * APIMethod: setOptions
+ *
+ * Parameters:
+ * newOptions - {Object}
+ */
+ setOptions: function (newOptions) {
+ OpenLayers.Util.extend(this.options, newOptions);
+ OpenLayers.Util.extend(this, newOptions);
+ },
+
+ /**
+ * APIMethod: activate
+ * Turn on the handler.
+ *
+ * Returns:
+ * {Boolean} The handler was successfully activated
+ */
+ activate: function() {
+ var activated = false;
+ if(OpenLayers.Handler.Drag.prototype.activate.apply(this, arguments)) {
+ // create temporary vector layer for rendering geometry sketch
+ var options = OpenLayers.Util.extend({
+ displayInLayerSwitcher: false,
+ // indicate that the temp vector layer will never be out of range
+ // without this, resolution properties must be specified at the
+ // map-level for this temporary layer to init its resolutions
+ // correctly
+ calculateInRange: OpenLayers.Function.True,
+ wrapDateLine: this.citeCompliant
+ }, this.layerOptions);
+ this.layer = new OpenLayers.Layer.Vector(this.CLASS_NAME, options);
+ this.map.addLayer(this.layer);
+ activated = true;
+ }
+ return activated;
+ },
+
+ /**
+ * APIMethod: deactivate
+ * Turn off the handler.
+ *
+ * Returns:
+ * {Boolean} The handler was successfully deactivated
+ */
+ deactivate: function() {
+ var deactivated = false;
+ if(OpenLayers.Handler.Drag.prototype.deactivate.apply(this, arguments)) {
+ // call the cancel callback if mid-drawing
+ if(this.dragging) {
+ this.cancel();
+ }
+ // If a layer's map property is set to null, it means that that
+ // layer isn't added to the map. Since we ourself added the layer
+ // to the map in activate(), we can assume that if this.layer.map
+ // is null it means that the layer has been destroyed (as a result
+ // of map.destroy() for example.
+ if (this.layer.map != null) {
+ this.layer.destroy(false);
+ if (this.feature) {
+ this.feature.destroy();
+ }
+ }
+ this.layer = null;
+ this.feature = null;
+ deactivated = true;
+ }
+ return deactivated;
+ },
+
+ /**
+ * Method: down
+ * Start drawing a new feature
+ *
+ * Parameters:
+ * evt - {Event} The drag start event
+ */
+ down: function(evt) {
+ this.fixedRadius = !!(this.radius);
+ var maploc = this.layer.getLonLatFromViewPortPx(evt.xy);
+ this.origin = new OpenLayers.Geometry.Point(maploc.lon, maploc.lat);
+ // create the new polygon
+ if(!this.fixedRadius || this.irregular) {
+ // smallest radius should not be less one pixel in map units
+ // VML doesn't behave well with smaller
+ this.radius = this.map.getResolution();
+ }
+ if(this.persist) {
+ this.clear();
+ }
+ this.feature = new OpenLayers.Feature.Vector();
+ this.createGeometry();
+ this.callback("create", [this.origin, this.feature]);
+ this.layer.addFeatures([this.feature], {silent: true});
+ this.layer.drawFeature(this.feature, this.style);
+ },
+
+ /**
+ * Method: move
+ * Respond to drag move events
+ *
+ * Parameters:
+ * evt - {Evt} The move event
+ */
+ move: function(evt) {
+ var maploc = this.layer.getLonLatFromViewPortPx(evt.xy);
+ var point = new OpenLayers.Geometry.Point(maploc.lon, maploc.lat);
+ if(this.irregular) {
+ var ry = Math.sqrt(2) * Math.abs(point.y - this.origin.y) / 2;
+ this.radius = Math.max(this.map.getResolution() / 2, ry);
+ } else if(this.fixedRadius) {
+ this.origin = point;
+ } else {
+ this.calculateAngle(point, evt);
+ this.radius = Math.max(this.map.getResolution() / 2,
+ point.distanceTo(this.origin));
+ }
+ this.modifyGeometry();
+ if(this.irregular) {
+ var dx = point.x - this.origin.x;
+ var dy = point.y - this.origin.y;
+ var ratio;
+ if(dy == 0) {
+ ratio = dx / (this.radius * Math.sqrt(2));
+ } else {
+ ratio = dx / dy;
+ }
+ this.feature.geometry.resize(1, this.origin, ratio);
+ this.feature.geometry.move(dx / 2, dy / 2);
+ }
+ this.layer.drawFeature(this.feature, this.style);
+ },
+
+ /**
+ * Method: up
+ * Finish drawing the feature
+ *
+ * Parameters:
+ * evt - {Event} The mouse up event
+ */
+ up: function(evt) {
+ this.finalize();
+ // the mouseup method of superclass doesn't call the
+ // "done" callback if there's been no move between
+ // down and up
+ if (this.start == this.last) {
+ this.callback("done", [evt.xy]);
+ }
+ },
+
+ /**
+ * Method: out
+ * Finish drawing the feature.
+ *
+ * Parameters:
+ * evt - {Event} The mouse out event
+ */
+ out: function(evt) {
+ this.finalize();
+ },
+
+ /**
+ * Method: createGeometry
+ * Create the new polygon geometry. This is called at the start of the
+ * drag and at any point during the drag if the number of sides
+ * changes.
+ */
+ createGeometry: function() {
+ this.angle = Math.PI * ((1/this.sides) - (1/2));
+ if(this.snapAngle) {
+ this.angle += this.snapAngle * (Math.PI / 180);
+ }
+ this.feature.geometry = OpenLayers.Geometry.Polygon.createRegularPolygon(
+ this.origin, this.radius, this.sides, this.snapAngle
+ );
+ },
+
+ /**
+ * Method: modifyGeometry
+ * Modify the polygon geometry in place.
+ */
+ modifyGeometry: function() {
+ var angle, point;
+ var ring = this.feature.geometry.components[0];
+ // if the number of sides ever changes, create a new geometry
+ if(ring.components.length != (this.sides + 1)) {
+ this.createGeometry();
+ ring = this.feature.geometry.components[0];
+ }
+ for(var i=0; i}
+ * evt - {Event}
+ */
+ calculateAngle: function(point, evt) {
+ var alpha = Math.atan2(point.y - this.origin.y,
+ point.x - this.origin.x);
+ if(this.snapAngle && (this.snapToggle && !evt[this.snapToggle])) {
+ var snapAngleRad = (Math.PI / 180) * this.snapAngle;
+ this.angle = Math.round(alpha / snapAngleRad) * snapAngleRad;
+ } else {
+ this.angle = alpha;
+ }
+ },
+
+ /**
+ * APIMethod: cancel
+ * Finish the geometry and call the "cancel" callback.
+ */
+ cancel: function() {
+ // the polygon geometry gets cloned in the callback method
+ this.callback("cancel", null);
+ this.finalize();
+ },
+
+ /**
+ * Method: finalize
+ * Finish the geometry and call the "done" callback.
+ */
+ finalize: function() {
+ this.origin = null;
+ this.radius = this.options.radius;
+ },
+
+ /**
+ * APIMethod: clear
+ * Clear any rendered features on the temporary layer. This is called
+ * when the handler is deactivated, canceled, or done (unless persist
+ * is true).
+ */
+ clear: function() {
+ if (this.layer) {
+ this.layer.renderer.clear();
+ this.layer.destroyFeatures();
+ }
+ },
+
+ /**
+ * Method: callback
+ * Trigger the control's named callback with the given arguments
+ *
+ * Parameters:
+ * name - {String} The key for the callback that is one of the properties
+ * of the handler's callbacks object.
+ * args - {Array} An array of arguments with which to call the callback
+ * (defined by the control).
+ */
+ callback: function (name, args) {
+ // override the callback method to always send the polygon geometry
+ if (this.callbacks[name]) {
+ this.callbacks[name].apply(this.control,
+ [this.feature.geometry.clone()]);
+ }
+ // since sketch features are added to the temporary layer
+ // they must be cleared here if done or cancel
+ if(!this.persist && (name == "done" || name == "cancel")) {
+ this.clear();
+ }
+ },
+
+ CLASS_NAME: "OpenLayers.Handler.RegularPolygon"
+});
diff --git a/pool/shard010/JavaScript/0068930_generate.js b/pool/shard010/JavaScript/0068930_generate.js
new file mode 100644
index 0000000000000000000000000000000000000000..73b88ba380946d084fe7a164fb9e1bb5ef789aed
--- /dev/null
+++ b/pool/shard010/JavaScript/0068930_generate.js
@@ -0,0 +1,50 @@
+"use strict";
+
+var crypto = require('crypto');
+var uuid = require('node-uuid');
+
+var randomString = function(payload) {
+ var randomSalt = new Date().getTime() + Math.random() * Math.random();
+ var md5engine = crypto.createHash('md5');
+
+ return md5engine.update(payload.toString() + randomSalt.toString()).digest('hex');
+};
+
+// TODO: Probably need a list of stop words, to avoid possibility
+// of offending the user
+var upperCase = "ABCDEFGHJKLMNPQRSTUVWXYZ"; // removed: 'I', 'O'
+var lowerCase = "abcdefghijkmnpqrstuvwxyz"; // removed: 'l', 'o'
+var characterSet = upperCase + lowerCase;
+
+var characterSetLength = characterSet.length;
+var userCodeLength = 8;
+var numberOfCombinations = Math.pow(characterSetLength, userCodeLength);
+
+module.exports = {
+ clientSecret: function(payload) {
+ return randomString(payload);
+ },
+
+ userCode: function() {
+ var number = Math.random() * numberOfCombinations;
+
+ var userCode = '';
+
+ for (var i = 0; i < userCodeLength; i++) {
+ var digit = number % characterSetLength;
+ userCode += characterSet[digit];
+
+ number = Math.floor(number / characterSetLength);
+ }
+
+ return userCode;
+ },
+
+ deviceCode: function() {
+ return uuid.v4();
+ },
+
+ accessToken: function() {
+ return randomString('');
+ }
+};
diff --git a/pool/shard010/JavaScript/0068932_TestFormOverlay.js b/pool/shard010/JavaScript/0068932_TestFormOverlay.js
new file mode 100644
index 0000000000000000000000000000000000000000..b4140cf296126cc5422fe90ef8671c00ba24a019
--- /dev/null
+++ b/pool/shard010/JavaScript/0068932_TestFormOverlay.js
@@ -0,0 +1,194 @@
+import * as React from 'react';
+
+import {
+ beginFormOverlaySubmit,
+ closeFormOverlay,
+ finishFormOverlaySubmit,
+ openFormOverlay,
+} from 'amo/reducers/formOverlay';
+import {
+ createFakeEvent,
+ dispatchClientMetadata,
+ fakeI18n,
+ shallowUntilTarget,
+} from 'tests/unit/helpers';
+import FormOverlay, { FormOverlayBase } from 'amo/components/FormOverlay';
+
+describe(__filename, () => {
+ let store;
+
+ beforeEach(() => {
+ store = dispatchClientMetadata().store;
+ });
+
+ const render = (customProps = {}) => {
+ const props = {
+ i18n: fakeI18n(),
+ title: 'Form Title',
+ id: 'example-form-id',
+ store,
+ ...customProps,
+ };
+ return shallowUntilTarget( , FormOverlayBase);
+ };
+
+ const renderOpen = (customProps = {}) => {
+ const id = customProps.id || 'example-form-id';
+ store.dispatch(openFormOverlay(id));
+ return render({ id, ...customProps });
+ };
+
+ it('renders a custom class name', () => {
+ const root = renderOpen({ className: 'some-class' });
+
+ expect(root).toHaveClassName('some-class');
+ expect(root).toHaveClassName('FormOverlay');
+ });
+
+ it('renders a title', () => {
+ const root = renderOpen({ title: 'Some Form' });
+
+ expect(root.find('.FormOverlay-h3')).toHaveText('Some Form');
+ });
+
+ it('is closed by default', () => {
+ const root = render();
+
+ expect(root.find('.FormOverlay')).toHaveLength(0);
+ });
+
+ it('can be closed', () => {
+ const id = 'some-id';
+ store.dispatch(openFormOverlay(id));
+ store.dispatch(closeFormOverlay(id));
+ const root = render({ id });
+
+ expect(root.find('.FormOverlay')).toHaveLength(0);
+ });
+
+ it('can be opened', () => {
+ const id = 'some-id';
+ store.dispatch(closeFormOverlay(id));
+ store.dispatch(openFormOverlay(id));
+ const root = render({ id });
+
+ expect(root.find('.FormOverlay')).toHaveLength(1);
+ });
+
+ it('renders children', () => {
+ const id = 'some-id';
+ store.dispatch(openFormOverlay(id));
+ const root = render({ id, children: [ ] });
+
+ expect(root.find('input')).toHaveLength(1);
+ });
+
+ it('closes when clicking the X', () => {
+ const id = 'some-id';
+ sinon.spy(store, 'dispatch');
+ const root = renderOpen({ id });
+ root.find('.FormOverlay-close-button').simulate('click', createFakeEvent());
+
+ sinon.assert.calledWith(store.dispatch, closeFormOverlay(id));
+ });
+
+ it('closes when clicking on the background', () => {
+ const id = 'some-id';
+ sinon.spy(store, 'dispatch');
+ const root = renderOpen({ id });
+ root.find('.FormOverlay').simulate('click', createFakeEvent());
+
+ sinon.assert.calledWith(store.dispatch, closeFormOverlay(id));
+ });
+
+ it('stops click events from propagating past the overlay', () => {
+ const root = renderOpen();
+ const event = createFakeEvent();
+ root.find('.FormOverlay-overlay').simulate('click', event);
+
+ sinon.assert.called(event.stopPropagation);
+ });
+
+ it('closes on cancel', () => {
+ const id = 'some-id';
+ sinon.spy(store, 'dispatch');
+ const root = renderOpen({ id });
+ root.find('.FormOverlay-cancel').simulate('click', createFakeEvent());
+
+ sinon.assert.calledWith(store.dispatch, closeFormOverlay(id));
+ });
+
+ it('invokes cancel callback', () => {
+ const onCancel = sinon.stub();
+ const root = renderOpen({ onCancel });
+ root.find('.FormOverlay-cancel').simulate('click', createFakeEvent());
+
+ sinon.assert.called(onCancel);
+ });
+
+ // eslint-disable-next-line jest/expect-expect
+ it('handles an empty cancel callback', () => {
+ const root = renderOpen({ onCancel: undefined });
+ // This should not throw an error.
+ root.find('.FormOverlay-cancel').simulate('click', createFakeEvent());
+ });
+
+ it('invokes submit callback', () => {
+ const onSubmit = sinon.stub();
+ const root = renderOpen({ onSubmit });
+ root.find('.FormOverlay-submit').simulate('click', createFakeEvent());
+
+ sinon.assert.called(onSubmit);
+ });
+
+ // eslint-disable-next-line jest/expect-expect
+ it('handles an empty submit callback', () => {
+ const root = renderOpen({ onSubmit: undefined });
+ // This should not throw an error.
+ root.find('.FormOverlay-submit').simulate('click', createFakeEvent());
+ });
+
+ it('renders a default submit button', () => {
+ const root = renderOpen();
+
+ expect(root.find('.FormOverlay-submit').html()).toContain('Submit');
+ });
+
+ it('renders a custom submit button', () => {
+ const submitText = 'Do The Thing Now';
+ const root = renderOpen({ submitText });
+
+ expect(root.find('.FormOverlay-submit').html()).toContain(submitText);
+ });
+
+ it('enters into a submitting state', () => {
+ const id = 'some-form';
+ store.dispatch(beginFormOverlaySubmit(id));
+ const root = renderOpen({ id });
+
+ const button = root.find('.FormOverlay-submit');
+ expect(button.html()).toContain('Submitting');
+ expect(button).toHaveProp('disabled', true);
+ expect(root.find('.FormOverlay-cancel')).toHaveProp('disabled', true);
+ });
+
+ it('exits out of a submitting state', () => {
+ const id = 'some-form';
+ store.dispatch(beginFormOverlaySubmit(id));
+ store.dispatch(finishFormOverlaySubmit(id));
+ const root = renderOpen({ id });
+
+ const button = root.find('.FormOverlay-submit');
+ expect(button).toHaveProp('disabled', false);
+ });
+
+ it('renders custom submitting text', () => {
+ const id = 'some-form';
+ const submittingText = 'Now submitting the form';
+ store.dispatch(beginFormOverlaySubmit(id));
+ const root = renderOpen({ id, submittingText });
+
+ const button = root.find('.FormOverlay-submit');
+ expect(button.html()).toContain(submittingText);
+ });
+});
diff --git a/pool/shard010/JavaScript/0068936_SpecIconBox.js b/pool/shard010/JavaScript/0068936_SpecIconBox.js
new file mode 100644
index 0000000000000000000000000000000000000000..4fd3e8aafc00ccd9b211abdb49adfc6992140778
--- /dev/null
+++ b/pool/shard010/JavaScript/0068936_SpecIconBox.js
@@ -0,0 +1,53 @@
+import React from 'react-native';
+const {
+ StyleSheet,
+ Image,
+ Text,
+ View,
+} = React;
+
+import globalVariables from '../globalVariables.js';
+
+const SpecIconBox = React.createClass({
+
+ render() {
+ return (
+
+
+ {this.props.value}
+ {this.props.label}
+
+ );
+ },
+});
+
+const styles = StyleSheet.create({
+ container: {
+ justifyContent: 'center',
+ padding: 20
+ },
+
+ icon: {
+ flex: 1,
+ alignSelf: 'center',
+ height: 34,
+ width: 34,
+ },
+
+ value: {
+ flex: 1,
+ fontSize: 19,
+ fontWeight: '200',
+ color: globalVariables.textColor,
+ textAlign: 'center'
+ },
+
+ label: {
+ flex: 1,
+ fontSize: 12,
+ color: globalVariables.textColor,
+ textAlign: 'center'
+ },
+});
+
+export default SpecIconBox;
diff --git a/pool/shard010/JavaScript/0068937_ExternalPrefixedCssVariableProperty.js b/pool/shard010/JavaScript/0068937_ExternalPrefixedCssVariableProperty.js
new file mode 100644
index 0000000000000000000000000000000000000000..eac5b70545af9efe4853c4bb90067c5c865ca12a
--- /dev/null
+++ b/pool/shard010/JavaScript/0068937_ExternalPrefixedCssVariableProperty.js
@@ -0,0 +1,88 @@
+/* Copyright (C) 2011-2014 Mattias Ekendahl. Used under MIT license, see full details at https://github.com/developedbyme/dbm/blob/master/LICENSE.txt */
+/**
+ * Property that updates a style property of an element, and it's set with all browser prefixes.
+ */
+dbm.registerClass("dbm.core.objectparts.ExternalPrefixedCssVariableProperty", "dbm.core.objectparts.ExternalCssVariableProperty", function(objectFunctions, staticFunctions, ClassReference) {
+ //console.log("dbm.core.objectparts.ExternalPrefixedCssVariableProperty");
+ //"use strict";
+
+ //Self reference
+ var ExternalPrefixedCssVariableProperty = dbm.importClass("dbm.core.objectparts.ExternalPrefixedCssVariableProperty");
+
+ //Error report
+ var ErrorManager = dbm.importClass("dbm.core.globalobjects.errormanager.ErrorManager");
+ var ReportTypes = dbm.importClass("dbm.constants.error.ReportTypes");
+ var ReportLevelTypes = dbm.importClass("dbm.constants.error.ReportLevelTypes");
+
+ //Dependencies
+
+ //Utils
+ var CssFunctions = dbm.importClass("dbm.utils.css.CssFunctions");
+
+ //Constants
+ var FlowStatusTypes = dbm.importClass("dbm.constants.status.FlowStatusTypes");
+
+ /**
+ * Constructor
+ */
+ objectFunctions._init = function() {
+ //console.log("dbm.core.objectparts.ExternalPrefixedCssVariableProperty::_init");
+
+ this.superCall();
+
+ return this;
+ };
+
+ /**
+ * Sets the value of this property (which updates the style of the external object). Value is stored internally if the external object is not set yet.
+ *
+ * @param aValue * The value of this property.
+ */
+ objectFunctions._performSetValue = function(aValue) {
+ //console.log("dbm.core.objectparts.ExternalPrefixedCssVariableProperty::_performSetValue");
+ //console.log(aValue);
+
+ if(this._externalObject === null) {
+ this._value = aValue;
+ return;
+ }
+
+ CssFunctions.setBrowserSpecificCssToElement(this._externalObject, this._externalVariableName, aValue, this._unit, this._priority);
+ };
+
+ /**
+ * Set all properties of the object to null. Part of the destroy function.
+ */
+ objectFunctions.setAllReferencesToNull = function() {
+
+ this.superCall();
+ };
+
+ /**
+ * Creates a new object of this class.
+ *
+ * @param aExternalObject * The object where the variable is stored.
+ * @param aVariableName String The name of the variable to store the value in.
+ * @param aUnit String The css unit for the value
+ *
+ * @return ExternalPrefixedCssVariableProperty The newly created object.
+ */
+ staticFunctions.create = function(aExternalObject, aVariableName, aUnit) {
+ var newExternalPrefixedCssVariableProperty = (new ExternalPrefixedCssVariableProperty()).init();
+ newExternalPrefixedCssVariableProperty.setupExternalObject(aExternalObject, aVariableName, aUnit);
+ return newExternalPrefixedCssVariableProperty;
+ };
+
+ /**
+ * Creates a new object of this class, without setting the external object.
+ *
+ * @param aValue * The value for the new property. (Optional)
+ *
+ * @return ExternalPrefixedCssVariableProperty The newly created object.
+ */
+ staticFunctions.createWithoutExternalObject = function(aValue) {
+ var newExternalPrefixedCssVariableProperty = ClassReference._createWithInputValue(ClassReference, aValue);
+ return newExternalPrefixedCssVariableProperty;
+ };
+
+});
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068938_layout-manager.js b/pool/shard010/JavaScript/0068938_layout-manager.js
new file mode 100644
index 0000000000000000000000000000000000000000..8a81b387b4f5c86169c5faf3a9b974fe9e766931
--- /dev/null
+++ b/pool/shard010/JavaScript/0068938_layout-manager.js
@@ -0,0 +1,155 @@
+/**
+ * Class LayoutManager
+ * Singleton that permit to manage the application layout
+ */
+class LayoutManager {
+
+ /**
+ * The current window reference
+ * @type {Element}
+ */
+ currentWindow = null;
+
+ /**
+ * List of loaded CSS files for an associate window
+ * @type {Object}
+ */
+ loadedCSSFiles = {};
+
+ /**
+ * The singleton instance
+ * @type {Layout}
+ */
+ static instance = null;
+
+ /**
+ * Singleton forger
+ * @method forge
+ * @param {Element} DOMNode The DOM node associate to the layout
+ * @return {LayoutManager} The current instance
+ */
+ static forge(DOMNode) {
+ LayoutManager.instance === null && (LayoutManager.instance = new LayoutManager(DOMNode));
+ return LayoutManager.instance;
+ }
+
+ /**
+ * Return the instance of the manager
+ * @method getInstance
+ * @return {LayoutManager} The current instance
+ */
+ static getInstance() {
+ return LayoutManager.instance;
+ }
+
+ /**
+ * Class constructor
+ * Can't be called directly, use the forge method
+ * @method constructor
+ * @param {Element} DOMNode The DOM node associate to the layout
+ * @return {void}
+ */
+ constructor(DOMNode) {
+ this.setCurrentWindow(DOMNode);
+ }
+
+ /**
+ * Set the currentWindow property
+ * Permit to work with the good window reference,
+ * in the case the component is injected in a window from another window.
+ * @method setCurrentWindow
+ * @param {Element} DOMNode The DOM node used as starting point to search it associated window
+ * @return {LayoutManager} The current instance, permit to maintain chainability
+ */
+ setCurrentWindow(DOMNode) {
+ this.currentWindow = this.getDOMNodeWindow(DOMNode);
+
+ return this;
+ }
+
+ /**
+ * Find the window of the root DOM node.
+ * Permit to work with the good window reference,
+ * in the case the component is injected in a window from another window.
+ * @method getDOMNodeWindow
+ * @param {Element} DOMNode The DOM node used as starting point to search it associated window
+ * @return {Element} The associate window
+ */
+ getDOMNodeWindow(DOMNode) {
+ return ((DOMNode.ownerDocument.defaultView) ?
+ DOMNode.ownerDocument.defaultView :
+ DOMNode.ownerDocument.parentWindow) || window;
+ }
+
+ /**
+ * Inject meta properties in the page.
+ * @method setMetaInDom
+ * @param {object} meta The meta properties that will be set to the page
+ * @return {LayoutManager} The current instance, permit to maintain chainability
+ */
+ setMetaInDom(meta) {
+ if (this.currentWindow !== null) {
+ const metaDescriptionDomNode = this.currentWindow.document.querySelector('meta[name=description]');
+
+ this.currentWindow.document.title = meta.title;
+ if (metaDescriptionDomNode) {
+ metaDescriptionDomNode.content = meta.description;
+ }
+ }
+
+ return this;
+ }
+
+ /**
+ * Inject CSS files in the page.
+ * @method injectCssFiles
+ * @param {Array} files The CSS files to inject in the page
+ * @return {LayoutManager} The current instance, permit to maintain chainability
+ */
+ injectCssFiles(files = []) {
+ if (this.currentWindow !== null && files.length) {
+ const doc = this.currentWindow.document;
+ const head = doc.head;
+ const loadedFiles = this.loadedCSSFiles[this.currentWindow] || [];
+
+ files.forEach((file) => {
+ if (loadedFiles.indexOf(file.href) === -1) {
+ const link = doc.createElement('link');
+
+ link.type = 'text/css';
+ link.rel = 'stylesheet';
+ link.href = file.href;
+ head.appendChild(link);
+ loadedFiles.push(file.href);
+ }
+ });
+
+ this.loadedCSSFiles[this.currentWindow] = loadedFiles;
+ }
+
+ return this;
+ }
+
+ /**
+ * Inject a style tag in the head of the document
+ * @method injectStyleTag
+ * @param {String} content The style content
+ * @return {LayoutManager} The current instance, permit to maintain chainability
+ */
+ injectStyleTag(content) {
+ const style = document.createElement('style');
+
+ style.type = 'text/css';
+ style.innerHTML = content;
+
+ const doc = this.currentWindow.document;
+ const head = doc.head;
+
+ head.appendChild(style);
+
+ return this;
+ }
+
+}
+
+export default LayoutManager;
diff --git a/pool/shard010/JavaScript/0068939_main.js b/pool/shard010/JavaScript/0068939_main.js
new file mode 100644
index 0000000000000000000000000000000000000000..b3084f7f2d0a4bf4387e0ec0ed5269a1840544c5
--- /dev/null
+++ b/pool/shard010/JavaScript/0068939_main.js
@@ -0,0 +1,39 @@
+'use strict';
+
+var WeatherController = require('./controllers/weather_controller');
+var WeatherQueryController = require('./controllers/weather_query_controller');
+var HomeController = require('./controllers/home_controller');
+var PollutionController = require('./controllers/pollution_controller');
+
+var Application = (function(){
+
+ var initRouter = function(){
+ var router = new Router({
+ '/weather':{
+ on:WeatherController.start
+ },
+ '/weatherQuery':{
+ on:WeatherQueryController.start
+ },
+ '/pollution':{
+ on:PollutionController.start
+ }
+ }).configure({recurse:'backward'});
+
+ router.init('/');
+ };
+
+ var start = function(){
+ HomeController.start();
+ initRouter();
+ };
+
+ return{
+ start:start
+ };
+
+}());
+
+jQuery(function(){
+ Application.start();
+});
diff --git a/pool/shard010/JavaScript/0068940_api.js b/pool/shard010/JavaScript/0068940_api.js
new file mode 100644
index 0000000000000000000000000000000000000000..c2744ee654ba6dedd277cade6983a10c5b90b6a0
--- /dev/null
+++ b/pool/shard010/JavaScript/0068940_api.js
@@ -0,0 +1,144 @@
+(function (Misago) {
+ 'use strict';
+
+ var filtersUrl = function(filters) {
+ if (typeof filters === 'object') {
+ var values = [];
+ for (var key in filters) {
+ if (filters.hasOwnProperty(key)) {
+ var encodedKey = encodeURIComponent(key);
+ var encodedValue = encodeURIComponent(filters[key]);
+ values.push(encodedKey + '=' + encodedValue);
+ }
+ }
+ return '?' + values.join('&');
+ } else {
+ return filters + '/';
+ }
+ };
+
+ var Query = function(_, call) {
+ this.url = call.url || _.setup.api;
+
+ if (call.path) {
+ this.url += call.path + '/';
+ } else if (call.related) {
+ this.url += call.related + '/';
+ } else {
+ this.url += call.model + 's' + '/';
+ }
+
+ if (call.filters) {
+ this.url += filtersUrl(call.filters);
+ }
+
+ if (!call.url && call.filters) {
+ if (call.model) {
+ this.related = function(model, filters) {
+ return new Query(_, {
+ url: this.url,
+ relation: call.model,
+ related: model,
+ filters: filters,
+ });
+ };
+ }
+
+ this.endpoint = function(path, filters) {
+ return new Query(_, {
+ url: this.url,
+ path: path,
+ filters: filters
+ });
+ };
+ }
+
+ this.get = function() {
+ var model = null;
+ if (call.related) {
+ model = call.relation + ':' + call.related;
+ } else if (call.model) {
+ model = call.model;
+ }
+
+ return _.ajax.get(this.url).then(function(data) {
+ if (model) {
+ if (data.results) {
+ data.results.map(function(item) {
+ return _.models.new(model, item);
+ });
+ return data;
+ } else {
+ return _.models.new(model, data);
+ }
+ } else {
+ return data;
+ }
+ });
+ };
+
+ this.post = function(data) {
+ return _.ajax.post(this.url, data);
+ };
+
+ this.patch = function(data) {
+ return _.ajax.patch(this.url, data);
+ };
+
+ this.put = function(data) {
+ return _.ajax.put(this.url, data);
+ };
+
+ this.delete = function() {
+ return _.ajax.delete(this.url);
+ };
+
+ // shortcut for get()
+ this.then = function(resolve, reject) {
+ return this.get().then(resolve, reject);
+ };
+ };
+
+ var Api = function(_) {
+ this.model = function(model, filters) {
+ return new Query(_, {
+ model: model,
+ filters: filters,
+ });
+ };
+
+ this.endpoint = function(path, filters) {
+ return new Query(_, {
+ path: path,
+ filters: filters
+ });
+ };
+
+ this.alert = function(rejection) {
+ // Shorthand for API errors
+ var message = gettext("Unknown error has occured.");
+
+ if (rejection.status === 0) {
+ message = gettext("Lost connection with application.");
+ }
+
+ if (rejection.status === 403) {
+ message = rejection.detail;
+ if (message === "Permission denied") {
+ message = gettext(
+ "You don't have permission to perform this action.");
+ }
+ }
+
+ if (rejection.status === 404) {
+ message = gettext("Action link is invalid.");
+ }
+
+ _.alert.error(message);
+ };
+ };
+
+ Misago.addService('api', function(_) {
+ return new Api(_);
+ });
+}(Misago.prototype));
diff --git a/pool/shard010/JavaScript/0068942_list-post-example-1.3.x.js b/pool/shard010/JavaScript/0068942_list-post-example-1.3.x.js
new file mode 100644
index 0000000000000000000000000000000000000000..cd9885544db7fbfbad60c6132989def111e33a28
--- /dev/null
+++ b/pool/shard010/JavaScript/0068942_list-post-example-1.3.x.js
@@ -0,0 +1,15 @@
+// Download the Node helper library from twilio.com/docs/node/install
+// These consts are your accountSid and authToken from https://www.twilio.com/console
+// To set up environmental variables, see http://twil.io/secure
+const accountSid = process.env.TWILIO_ACCOUNT_SID;
+const authToken = process.env.TWILIO_AUTH_TOKEN;
+const client = require('twilio')(accountSid, authToken);
+
+client.incomingPhoneNumbers
+ .create({
+ friendlyName: 'My Company Line',
+ voiceUrl: 'http://demo.twilio.com/docs/voice.xml',
+ phoneNumber: '+15105647903',
+ voiceMethod: 'GET',
+ })
+ .then(number => console.log(number.sid));
diff --git a/pool/shard010/JavaScript/0068944_console-output.js b/pool/shard010/JavaScript/0068944_console-output.js
new file mode 100644
index 0000000000000000000000000000000000000000..185e7cf62d353fbdb546f0074254dc3ee58b1769
--- /dev/null
+++ b/pool/shard010/JavaScript/0068944_console-output.js
@@ -0,0 +1,18 @@
+'use strict'
+
+const LoggerOutputInterface = require('./logger-output-interface')
+
+class ConsoleOutput extends LoggerOutputInterface {
+ constructor (enabled) {
+ super()
+ this.level = 'debug'
+ this.stream = process.stdout
+ this.enabled = enabled
+ }
+
+ isAvailable () {
+ return this.enabled
+ }
+}
+
+module.exports = ConsoleOutput
diff --git a/pool/shard010/JavaScript/0068947_autocomplete-highlighters.js b/pool/shard010/JavaScript/0068947_autocomplete-highlighters.js
new file mode 100644
index 0000000000000000000000000000000000000000..92fd03a89d23a6d607466b6972ee3c8b756010d2
--- /dev/null
+++ b/pool/shard010/JavaScript/0068947_autocomplete-highlighters.js
@@ -0,0 +1,206 @@
+/*
+YUI 3.18.1 (build f7e7bcb)
+Copyright 2014 Yahoo! Inc. All rights reserved.
+Licensed under the BSD License.
+http://yuilibrary.com/license/
+*/
+
+YUI.add('autocomplete-highlighters', function (Y, NAME) {
+
+/**
+Provides pre-built result highlighters for AutoComplete.
+
+@module autocomplete
+@submodule autocomplete-highlighters
+@class AutoCompleteHighlighters
+@static
+**/
+
+var YArray = Y.Array,
+ Highlight = Y.Highlight,
+
+Highlighters = Y.mix(Y.namespace('AutoCompleteHighlighters'), {
+ // -- Public Methods -------------------------------------------------------
+
+ /**
+ Highlights any individual query character that occurs anywhere in a result.
+ Case-insensitive.
+
+ @method charMatch
+ @param {String} query Query to match
+ @param {Array} results Results to highlight
+ @return {Array} Highlighted results
+ @static
+ **/
+ charMatch: function (query, results, caseSensitive) {
+ // The caseSensitive parameter is only intended for use by
+ // charMatchCase(). It's intentionally undocumented.
+
+ var queryChars = YArray.unique((caseSensitive ? query :
+ query.toLowerCase()).split(''));
+
+ return YArray.map(results, function (result) {
+ return Highlight.all(result.text, queryChars, {
+ caseSensitive: caseSensitive
+ });
+ });
+ },
+
+ /**
+ Case-sensitive version of `charMatch()`.
+
+ @method charMatchCase
+ @param {String} query Query to match
+ @param {Array} results Results to highlight
+ @return {Array} Highlighted results
+ @static
+ **/
+ charMatchCase: function (query, results) {
+ return Highlighters.charMatch(query, results, true);
+ },
+
+ /**
+ Highlights the complete query as a phrase anywhere within a result. Case-
+ insensitive.
+
+ @method phraseMatch
+ @param {String} query Query to match
+ @param {Array} results Results to highlight
+ @return {Array} Highlighted results
+ @static
+ **/
+ phraseMatch: function (query, results, caseSensitive) {
+ // The caseSensitive parameter is only intended for use by
+ // phraseMatchCase(). It's intentionally undocumented.
+
+ return YArray.map(results, function (result) {
+ return Highlight.all(result.text, [query], {
+ caseSensitive: caseSensitive
+ });
+ });
+ },
+
+ /**
+ Case-sensitive version of `phraseMatch()`.
+
+ @method phraseMatchCase
+ @param {String} query Query to match
+ @param {Array} results Results to highlight
+ @return {Array} Highlighted results
+ @static
+ **/
+ phraseMatchCase: function (query, results) {
+ return Highlighters.phraseMatch(query, results, true);
+ },
+
+ /**
+ Highlights the complete query as a phrase at the beginning of a result.
+ Case-insensitive.
+
+ @method startsWith
+ @param {String} query Query to match
+ @param {Array} results Results to highlight
+ @return {Array} Highlighted results
+ @static
+ **/
+ startsWith: function (query, results, caseSensitive) {
+ // The caseSensitive parameter is only intended for use by
+ // startsWithCase(). It's intentionally undocumented.
+
+ return YArray.map(results, function (result) {
+ return Highlight.all(result.text, [query], {
+ caseSensitive: caseSensitive,
+ startsWith : true
+ });
+ });
+ },
+
+ /**
+ Case-sensitive version of `startsWith()`.
+
+ @method startsWithCase
+ @param {String} query Query to match
+ @param {Array} results Results to highlight
+ @return {Array} Highlighted results
+ @static
+ **/
+ startsWithCase: function (query, results) {
+ return Highlighters.startsWith(query, results, true);
+ },
+
+ /**
+ Highlights portions of results in which words from the query match either
+ whole words or parts of words in the result. Non-word characters like
+ whitespace and certain punctuation are ignored. Case-insensitive.
+
+ @method subWordMatch
+ @param {String} query Query to match
+ @param {Array} results Results to highlight
+ @return {Array} Highlighted results
+ @static
+ **/
+ subWordMatch: function (query, results, caseSensitive) {
+ // The caseSensitive parameter is only intended for use by
+ // subWordMatchCase(). It's intentionally undocumented.
+
+ var queryWords = Y.Text.WordBreak.getUniqueWords(query, {
+ ignoreCase: !caseSensitive
+ });
+
+ return YArray.map(results, function (result) {
+ return Highlight.all(result.text, queryWords, {
+ caseSensitive: caseSensitive
+ });
+ });
+ },
+
+ /**
+ Case-sensitive version of `subWordMatch()`.
+
+ @method subWordMatchCase
+ @param {String} query Query to match
+ @param {Array} results Results to highlight
+ @return {Array} Highlighted results
+ @static
+ **/
+ subWordMatchCase: function (query, results) {
+ return Highlighters.subWordMatch(query, results, true);
+ },
+
+ /**
+ Highlights individual words in results that are also in the query. Non-word
+ characters like punctuation are ignored. Case-insensitive.
+
+ @method wordMatch
+ @param {String} query Query to match
+ @param {Array} results Results to highlight
+ @return {Array} Highlighted results
+ @static
+ **/
+ wordMatch: function (query, results, caseSensitive) {
+ // The caseSensitive parameter is only intended for use by
+ // wordMatchCase(). It's intentionally undocumented.
+
+ return YArray.map(results, function (result) {
+ return Highlight.words(result.text, query, {
+ caseSensitive: caseSensitive
+ });
+ });
+ },
+
+ /**
+ Case-sensitive version of `wordMatch()`.
+
+ @method wordMatchCase
+ @param {String} query Query to match
+ @param {Array} results Results to highlight
+ @return {Array} Highlighted results
+ @static
+ **/
+ wordMatchCase: function (query, results) {
+ return Highlighters.wordMatch(query, results, true);
+ }
+});
+
+
+}, '3.18.1', {"requires": ["array-extras", "highlight-base"]});
diff --git a/pool/shard010/JavaScript/0068950_firewalls.get.js b/pool/shard010/JavaScript/0068950_firewalls.get.js
new file mode 100644
index 0000000000000000000000000000000000000000..9682833e3739662549ee26a29261519638d68466
--- /dev/null
+++ b/pool/shard010/JavaScript/0068950_firewalls.get.js
@@ -0,0 +1,63 @@
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// ** This file is automatically generated by gapic-generator-typescript. **
+// ** https://github.com/googleapis/gapic-generator-typescript **
+// ** All changes to this file may be overwritten. **
+
+
+
+'use strict';
+
+function main(firewall, project) {
+ // [START compute_v1_generated_Firewalls_Get_async]
+ /**
+ * TODO(developer): Uncomment these variables before running the sample.
+ */
+ /**
+ * Name of the firewall rule to return.
+ */
+ // const firewall = 'abc123'
+ /**
+ * Project ID for this request.
+ */
+ // const project = 'my-project'
+
+ // Imports the Compute library
+ const {FirewallsClient} = require('@google-cloud/compute').v1;
+
+ // Instantiates a client
+ const computeClient = new FirewallsClient();
+
+ async function callGet() {
+ // Construct request
+ const request = {
+ firewall,
+ project,
+ };
+
+ // Run request
+ const response = await computeClient.get(request);
+ console.log(response);
+ }
+
+ callGet();
+ // [END compute_v1_generated_Firewalls_Get_async]
+}
+
+process.on('unhandledRejection', err => {
+ console.error(err.message);
+ process.exitCode = 1;
+});
+main(...process.argv.slice(2));
diff --git a/pool/shard010/JavaScript/0068955_tool.js b/pool/shard010/JavaScript/0068955_tool.js
new file mode 100644
index 0000000000000000000000000000000000000000..0f7de07619804da9d0bf4c82236c4e44d321c8c6
--- /dev/null
+++ b/pool/shard010/JavaScript/0068955_tool.js
@@ -0,0 +1,46 @@
+function getImg(idx) {
+ var canvas = document.getElementById('canvas');
+ var c = canvas.getContext('2d');
+ //新建Image对象
+ var img = new Image();
+ img.src = '../images/icon_bg.png';//svg内容中可以有中文字符
+ var y = parseInt(idx / 12);
+ var x = idx % 12;
+ var imgs = new Image();
+ $(imgs).css({
+ 'vertical-align': '-9px'
+ })
+ //图片初始化完成后调用
+ var canvas2 = document.createElement("canvas")
+ var cxt2 = canvas2.getContext("2d")
+ img.onload = function () {
+ //将canvas的宽高设置为图像的宽高
+ canvas.width = img.width;
+ canvas.height = img.height;
+ //canvas画图片
+ c.drawImage(img, 0, 0);
+ var dataImg = c.getImageData(x * 30 +5+ 6, y * 30 + 5+6, 20, 20);
+
+ //
+ // var pixel = dataImg.data;
+ //
+ // var r=0, g=1, b=2,a=3;
+ // for (var p = 0; p {
+ // Handle hot updates, copied with slight adjustments from webpack/hot/signal.js
+ if (module.hot) {
+ const log = (type, msg) => console[type](`sswp> ${msg}`);
+ // TODO don't show this when sending signal instead of message
+ log('log', 'Handling Hot Module Reloading');
+ var checkForUpdate = function checkForUpdate(fromUpdate) {
+ module.hot
+ .check()
+ .then(function (updatedModules) {
+ if (!updatedModules) {
+ if (fromUpdate) log('log', 'Update applied.');
+ else log('warn', 'Cannot find update.');
+ return;
+ }
+
+ return module.hot
+ .apply({
+ ignoreUnaccepted: true,
+ // TODO probably restart
+ onUnaccepted: function (data) {
+ log(
+ 'warn',
+ '\u0007Ignored an update to unaccepted module ' +
+ data.chain.join(' -> ')
+ );
+ },
+ })
+ .then(function (renewedModules) {
+ require('webpack/hot/log-apply-result')(
+ updatedModules,
+ renewedModules
+ );
+
+ checkForUpdate(true);
+ });
+ })
+ .catch(function (err) {
+ var status = module.hot.status();
+ if (['abort', 'fail'].indexOf(status) >= 0) {
+ if (process.send) {
+ process.send('SSWP_HMR_FAIL');
+ }
+ log('warn', 'Cannot apply update.');
+ log('warn', '' + err.stack || err.message);
+ log(
+ 'error',
+ 'Quitting process - will reload on next file change\u0007\n\u0007\n\u0007'
+ );
+ process.exit(222);
+ } else {
+ log('warn', 'Update failed: ' + err.stack || err.message);
+ }
+ });
+ };
+
+ process.on('message', function (message) {
+ if (message !== 'SSWP_HMR') return;
+
+ if (module.hot.status() !== 'idle') {
+ log(
+ 'warn',
+ 'Got signal but currently in ' + module.hot.status() + ' state.'
+ );
+ log('warn', 'Need to be in idle state to start hot update.');
+ return;
+ }
+
+ checkForUpdate();
+ });
+ }
+
+ // Tell our plugin we loaded all the code without initially crashing
+ if (process.send) {
+ process.send('SSWP_LOADED');
+ }
+};
+
+export default monitorFn;
diff --git a/pool/shard010/JavaScript/0068964_localize.js b/pool/shard010/JavaScript/0068964_localize.js
new file mode 100644
index 0000000000000000000000000000000000000000..fbd492f2f7ec7948ff62fdd1ffd576a35431bec2
--- /dev/null
+++ b/pool/shard010/JavaScript/0068964_localize.js
@@ -0,0 +1,188 @@
+'use strict';
+
+/*
+ * An AngularJS Localization Service
+ *
+ * Written by Jim Lavin
+ * http://codingsmackdown.tv
+ *
+ */
+
+angular.module('localization', [])
+ // localization service responsible for retrieving resource files from the server and
+ // managing the translation dictionary
+ .factory('localize', ['$http', '$rootScope', '$window', '$filter', function ($http, $rootScope, $window, $filter) {
+ var localize = {
+ // use the $window service to get the language of the user's browser
+ language:'',
+ // array to hold the localized resource string entries
+ dictionary:[],
+ // location of the resource file
+ url: undefined,
+ // flag to indicate if the service hs loaded the resource file
+ resourceFileLoaded:false,
+
+ // success handler for all server communication
+ successCallback:function (data) {
+ // store the returned array in the dictionary
+ localize.dictionary = data;
+ // set the flag that the resource are loaded
+ localize.resourceFileLoaded = true;
+ // broadcast that the file has been loaded
+ $rootScope.$broadcast('localizeResourcesUpdated');
+ },
+
+ // allows setting of language on the fly
+ setLanguage: function(value) {
+ localize.language = value;
+ localize.initLocalizedResources();
+ },
+
+ // allows setting of resource url on the fly
+ setUrl: function(value) {
+ localize.url = value;
+ localize.initLocalizedResources();
+ },
+
+ // builds the url for locating the resource file
+ buildUrl: function() {
+ if(!localize.language){
+ var lang, androidLang;
+ // works for earlier version of Android (2.3.x)
+ if ($window.navigator && $window.navigator.userAgent && (androidLang = $window.navigator.userAgent.match(/android.*\W(\w\w)-(\w\w)\W/i))) {
+ lang = androidLang[1];
+ } else {
+ // works for iOS, Android 4.x and other devices
+ lang = $window.navigator.userLanguage || $window.navigator.language;
+ }
+ // set language
+ localize.language = lang;
+ }
+ return 'i18n/resources-locale_' + localize.language + '.js';
+ },
+
+ // loads the language resource file from the server
+ initLocalizedResources:function () {
+ // build the url to retrieve the localized resource file
+ var url = localize.url || localize.buildUrl();
+ // request the resource file
+ $http({ method:"GET", url:url, cache:false }).success(localize.successCallback).error(function () {
+ // the request failed set the url to the default resource file
+ var url = '/i18n/resources-locale_default.js';
+ // request the default resource file
+ $http({ method:"GET", url:url, cache:false }).success(localize.successCallback);
+ });
+ },
+
+ // checks the dictionary for a localized resource string
+ getLocalizedString: function(value) {
+ // default the result to an empty string
+ var result = '';
+
+ // make sure the dictionary has valid data
+ if ((localize.dictionary !== []) && (localize.dictionary.length > 0)) {
+ // use the filter service to only return those entries which match the value
+ // and only take the first result
+ var entry = $filter('filter')(localize.dictionary, function(element) {
+ return element.key === value;
+ }
+ )[0];
+
+ // set the result
+ result = entry.value;
+ }
+ // return the value to the call
+ return result;
+ }
+ };
+
+ // force the load of the resource file
+ localize.initLocalizedResources();
+
+ // return the local instance when called
+ return localize;
+ } ])
+ // simple translation filter
+ // usage {{ TOKEN | i18n }}
+ .filter('i18n', ['localize', function (localize) {
+ return function (input) {
+ return localize.getLocalizedString(input);
+ };
+ }])
+ // translation directive that can handle dynamic strings
+ // updates the text value of the attached element
+ // usage
+ // or
+ //
+ .directive('i18n', ['localize', function(localize){
+ var i18nDirective = {
+ restrict:"EAC",
+ updateText:function(elm, token){
+ var values = token.split('|');
+ if (values.length >= 1) {
+ // construct the tag to insert into the element
+ var tag = localize.getLocalizedString(values[0]);
+ // update the element only if data was returned
+ if ((tag !== null) && (tag !== undefined) && (tag !== '')) {
+ if (values.length > 1) {
+ for (var index = 1; index < values.length; index++) {
+ var target = '{' + (index - 1) + '}';
+ tag = tag.replace(target, values[index]);
+ }
+ }
+ // insert the text into the element
+ elm.text(tag);
+ };
+ }
+ },
+
+ link:function (scope, elm, attrs) {
+ scope.$on('localizeResourcesUpdated', function() {
+ i18nDirective.updateText(elm, attrs.i18n);
+ });
+
+ attrs.$observe('i18n', function (value) {
+ i18nDirective.updateText(elm, attrs.i18n);
+ });
+ }
+ };
+
+ return i18nDirective;
+ }])
+ // translation directive that can handle dynamic strings
+ // updates the attribute value of the attached element
+ // usage
+ // or
+ //
+ .directive('i18nAttr', ['localize', function (localize) {
+ var i18NAttrDirective = {
+ restrict: "EAC",
+ updateText:function(elm, token){
+ var values = token.split('|');
+ // construct the tag to insert into the element
+ var tag = localize.getLocalizedString(values[0]);
+ // update the element only if data was returned
+ if ((tag !== null) && (tag !== undefined) && (tag !== '')) {
+ if (values.length > 2) {
+ for (var index = 2; index < values.length; index++) {
+ var target = '{' + (index - 2) + '}';
+ tag = tag.replace(target, values[index]);
+ }
+ }
+ // insert the text into the element
+ elm.attr(values[1], tag);
+ }
+ },
+ link: function (scope, elm, attrs) {
+ scope.$on('localizeResourcesUpdated', function() {
+ i18NAttrDirective.updateText(elm, attrs.i18nAttr);
+ });
+
+ attrs.$observe('i18nAttr', function (value) {
+ i18NAttrDirective.updateText(elm, value);
+ });
+ }
+ };
+
+ return i18NAttrDirective;
+ }]);
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068967_script.js b/pool/shard010/JavaScript/0068967_script.js
new file mode 100644
index 0000000000000000000000000000000000000000..939b755d3ae878b1289e8e29837bbde8a2a30a20
--- /dev/null
+++ b/pool/shard010/JavaScript/0068967_script.js
@@ -0,0 +1,17 @@
+;
+( function( $ ) {
+ $( '.cg-gallery' ).each( function() {
+ var instance = this;
+
+ $( 'input[type=button]', instance ).click( function() {
+ var gallerysc = '[gallery ids="' + $( 'input[type=hidden]', instance ).val() + '"]';
+ wp.media.gallery.edit( gallerysc ).on( 'update', function( g ) {
+ var id_array = [];
+ $.each( g.models, function( id, img ) {
+ id_array.push( img.id );
+ } );
+ $( 'input[type=hidden]', instance ).val( id_array.join( "," ) );
+ } );
+ } );
+ } );
+}( jQuery ) );
\ No newline at end of file
diff --git a/pool/shard010/JavaScript/0068968_filter-player-view-7cb2b79d.js b/pool/shard010/JavaScript/0068968_filter-player-view-7cb2b79d.js
new file mode 100644
index 0000000000000000000000000000000000000000..ebbc8d236bf0596fa6e6338cafe323f8e61dd8dc
--- /dev/null
+++ b/pool/shard010/JavaScript/0068968_filter-player-view-7cb2b79d.js
@@ -0,0 +1,87 @@
+import { x as PlayerView } from './turn-order-406c4349.js';
+import { createPatch } from 'rfc6902';
+
+const applyPlayerView = (game, playerID, state) => ({
+ ...state,
+ G: game.playerView(state.G, state.ctx, playerID),
+ plugins: PlayerView(state, { playerID, game }),
+ deltalog: undefined,
+ _undo: [],
+ _redo: [],
+});
+/** Gets a function that filters the TransportData for a given player and game. */
+const getFilterPlayerView = (game) => (playerID, payload) => {
+ switch (payload.type) {
+ case 'patch': {
+ const [matchID, stateID, prevState, state] = payload.args;
+ const log = redactLog(state.deltalog, playerID);
+ const filteredState = applyPlayerView(game, playerID, state);
+ const newStateID = state._stateID;
+ const prevFilteredState = applyPlayerView(game, playerID, prevState);
+ const patch = createPatch(prevFilteredState, filteredState);
+ return {
+ type: 'patch',
+ args: [matchID, stateID, newStateID, patch, log],
+ };
+ }
+ case 'update': {
+ const [matchID, state] = payload.args;
+ const log = redactLog(state.deltalog, playerID);
+ const filteredState = applyPlayerView(game, playerID, state);
+ return {
+ type: 'update',
+ args: [matchID, filteredState, log],
+ };
+ }
+ case 'sync': {
+ const [matchID, syncInfo] = payload.args;
+ const filteredState = applyPlayerView(game, playerID, syncInfo.state);
+ const log = redactLog(syncInfo.log, playerID);
+ const newSyncInfo = {
+ ...syncInfo,
+ state: filteredState,
+ log,
+ };
+ return {
+ type: 'sync',
+ args: [matchID, newSyncInfo],
+ };
+ }
+ default: {
+ return payload;
+ }
+ }
+};
+/**
+ * Redact the log.
+ *
+ * @param {Array} log - The game log (or deltalog).
+ * @param {String} playerID - The playerID that this log is
+ * to be sent to.
+ */
+function redactLog(log, playerID) {
+ if (log === undefined) {
+ return log;
+ }
+ return log.map((logEvent) => {
+ // filter for all other players and spectators.
+ if (playerID !== null && +playerID === +logEvent.action.payload.playerID) {
+ return logEvent;
+ }
+ if (logEvent.redact !== true) {
+ return logEvent;
+ }
+ const payload = {
+ ...logEvent.action.payload,
+ args: null,
+ };
+ const filteredEvent = {
+ ...logEvent,
+ action: { ...logEvent.action, payload },
+ };
+ const { redact, ...remaining } = filteredEvent;
+ return remaining;
+ });
+}
+
+export { getFilterPlayerView as g };
diff --git a/pool/shard010/Python/0089171_component.py b/pool/shard010/Python/0089171_component.py
new file mode 100644
index 0000000000000000000000000000000000000000..729e2b49e93d48a7c82ef41b7920d987cd6fa901
--- /dev/null
+++ b/pool/shard010/Python/0089171_component.py
@@ -0,0 +1,181 @@
+"""
+Defines a base class for drawn jobs.
+"""
+
+# Copyright 2013 Paul Griffiths
+# Email: mail@paulgriffiths.net
+#
+# All rights reserved.
+
+
+import cairo
+from jobcalc.helper import draw_text_box, Point, TextInfo
+
+
+class DrawnComponent:
+
+ """
+ DrawnComponent class to be used to automatically create a drawing.
+
+ This is a base class from which classes for specific components
+ should inherit. Instances of this class are not intended to be
+ directly drawn.
+
+ Public methods:
+ __init__()
+ draw()
+ """
+
+ def __init__(self):
+
+ """
+ Initializes a DrawnComponent instance.
+
+ Subclasses should call this at the beginning of their
+ own constructor function.
+ """
+
+ # Drawing attributes
+
+ self.scale = 1
+ self.drawing_line_width = 0.5
+ self.drawing_line_color = (0, 0, 0)
+ self.hatching = False
+
+ # Text objects and styles common to all components
+
+ self.dash_style = [7.0, 2.0, 2.0, 2.0]
+
+ self.text = {"dims": TextInfo(face="Arial", size=8,
+ padding=3, color=(0.0, 0.0, 0.0)),
+ "info": TextInfo(face="Arial", size=8,
+ padding=3, color=(0.0, 0.0, 0.0)),
+ "notice": TextInfo(face="Arial", size=10,
+ padding=3, color=(0.0, 0.0, 0.0))}
+
+ # Create Pycairo hatching patterns
+
+ if self.hatching:
+ chatch = cairo.ImageSurface(cairo.FORMAT_RGB24, 10, 10)
+ ctx = cairo.Context(chatch)
+ ctx.set_source_rgb(1, 1, 1)
+ ctx.paint()
+ ctx.set_source_rgb(0, 0, 0)
+ ctx.set_line_width(1)
+ ctx.move_to(0, 10)
+ ctx.line_to(10, 0)
+ ctx.stroke()
+ self.chatch = cairo.SurfacePattern(chatch)
+
+ lhatch = cairo.ImageSurface(cairo.FORMAT_RGB24, 10, 10)
+ ctx = cairo.Context(lhatch)
+ ctx.set_source_rgb(0, 0, 0)
+ ctx.paint()
+ ctx.set_source_rgb(1, 1, 1)
+ ctx.set_line_width(1)
+ ctx.move_to(0, 10)
+ ctx.line_to(10, 0)
+ ctx.move_to(0, 9)
+ ctx.line_to(9, 0)
+ ctx.move_to(1, 10)
+ ctx.line_to(10, 1)
+ ctx.move_to(0, 1)
+ ctx.line_to(1, 0)
+ ctx.move_to(9, 10)
+ ctx.line_to(10, 9)
+ ctx.stroke()
+ self.lhatch = cairo.SurfacePattern(lhatch)
+
+ def draw(self, ctx, page_w, page_h):
+
+ """
+ Draws a component. Mainly calls supporting functions.
+
+ The drawing page class will call this function, which
+ in turn calls draw_component(), which should be overridden
+ by subclasses to provide drawing functionality for that
+ specific component.
+
+ Subclasses should not normally override draw() itself.
+
+ Arguments:
+ ctx -- a Pycairo context
+ page_w, page_h -- width and height of drawing area
+
+ Returns the scale factor of the drawn component, which is
+ then used to show the scale on the page.
+ """
+
+ ctx.save()
+
+ self.draw_pre_scale(ctx, page_w, page_h)
+
+ self.set_scale(ctx, page_w, page_h)
+
+ ctx.set_source_rgb(*self.drawing_line_color)
+ ctx.set_line_width(self.drawing_line_width)
+
+ self.draw_component(ctx, page_w, page_h)
+
+ ctx.restore()
+
+ return self.scale
+
+ def draw_pre_scale(self, ctx, page_w, page_h):
+
+ """
+ Drawing actions to perform prior to scaling.
+
+ Subclasses should override this if desired.
+ """
+
+ pass
+
+ def set_scale(self, ctx, page_w, page_h):
+
+ """
+ Automatically sets a scale factor for the drawing.
+
+ Subclasses should override this and call their
+ parent class set_scale() function at the end of
+ their own. 'page_h' and 'page_w' should already have been
+ up-scaled by the time this happens and we get here.
+
+ Arguments:
+ ctx -- a Pycairo context
+ page_w, page_h -- height and width of the drawing area
+ """
+
+ # Upscale dash style
+
+ for dims in range(len(self.dash_style)):
+ self.dash_style[dims] /= self.scale
+
+ # Upscale fonts
+
+ for key in self.text.iterkeys():
+ self.text[key].size /= self.scale
+ self.text[key].padding /= self.scale
+
+ # Upscale lines
+
+ self.drawing_line_width /= self.scale
+
+ def draw_component(self, ctx, page_w, page_h):
+
+ """
+ Draws the drawn component.
+
+ Subclasses should override this method and not call this.
+
+ Arguments:
+ ctx -- a Pycairo context
+ page_w, page_h -- width and height of drawing area
+ """
+
+ ctx.save()
+
+ notice = "Override this base class"
+ draw_text_box(ctx=ctx, labels=[notice], textinfo=self.text["notice"],
+ centerpoint=Point(page_w / 2, page_h / 2), noborder=True)
+ ctx.restore()
diff --git a/pool/shard010/Python/0089175_send.py b/pool/shard010/Python/0089175_send.py
new file mode 100644
index 0000000000000000000000000000000000000000..91d0205196587b5e896b357f3d3f20a0d6100cc2
--- /dev/null
+++ b/pool/shard010/Python/0089175_send.py
@@ -0,0 +1,72 @@
+import sys
+import socket
+import time
+import os
+import getpass
+
+
+def handshake(address):
+ print ("Attempting handshake...")
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #create socket
+ port = 5010 #specify port
+ s.connect((address,port)) #connect
+ s.sendall('110') #send data
+ reply = s.recv(512) #save reply.
+ if reply == '111':
+ print("Connection made")
+ return s
+ elif reply != '111':
+ print("Invalid handshake reply.")
+ s.close() #close socket
+ sys.exit()
+
+def send_files(files, socket, repname):
+ socket.sendall(str(len(files))) #send number of files
+ print ("files to send: "),str(files)
+
+ for x in range(0, len(files)):
+
+ if os.path.exists(files[x]): #make sure the file actually exists
+
+ if repname == 1:
+ dat = os.path.abspath(files[x]) #send the paths for each file
+ print ("Sending '"),dat,("'...")
+ dat = dat.replace(getpass.getuser(), "%%%%") #if replace name set then replace username with %
+ else:
+ dat = os.path.abspath(files[x]) #send the paths for each file
+ print ("Sending "),dat
+
+ socket.send(dat)
+ time.sleep(0.5)
+ f = open(files[x], 'rb') #open file for read
+ data = f.read() #read data in
+ size = len(data) #get size of data
+ print("Sending "),size,(" bytes...")
+ socket.send(str(size)) #send size of file
+ time.sleep(0.5)
+ socket.send(data) #send data
+ time.sleep(0.5)
+ msg = socket.recv(512)
+ if msg == '1':
+ print ("Sending of file "),x+1 ,("Was succsessful")
+ time.sleep(0.5)
+ dat = ""
+ else:
+ socket.send("null") #If file doesnt exist, tell the server.
+ time.sleep(0.5)
+ print("File '"), files[x], ("' does not exist. Ignoring it.")
+
+ return
+
+def send(files, address):
+
+ repname = 1
+
+ socket = handshake(address) #call handshake process.
+ send_files(files, socket, repname)
+
+
+
+ sys.exit()
+
+
diff --git a/pool/shard010/Python/0089180_websettings.py b/pool/shard010/Python/0089180_websettings.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e57af45fb3a09c360a0b3600811f2266c9983e7
--- /dev/null
+++ b/pool/shard010/Python/0089180_websettings.py
@@ -0,0 +1,228 @@
+# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
+
+# Copyright 2014-2017 Florian Bruhin (The Compiler)
+#
+# This file is part of qutebrowser.
+#
+# qutebrowser is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# qutebrowser is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with qutebrowser. If not, see .
+
+# We get various "abstract but not overridden" warnings
+# pylint: disable=abstract-method
+
+"""Bridge from QWeb(Engine)Settings to our own settings."""
+
+from PyQt5.QtGui import QFont
+
+from qutebrowser.config import config
+from qutebrowser.utils import log, utils, debug, usertypes
+from qutebrowser.misc import objects
+
+UNSET = object()
+
+
+class Base:
+
+ """Base class for QWeb(Engine)Settings wrappers."""
+
+ def __init__(self, default=UNSET):
+ self._default = default
+
+ def _get_global_settings(self):
+ """Get a list of global QWeb(Engine)Settings to use."""
+ raise NotImplementedError
+
+ def _get_settings(self, settings):
+ """Get a list of QWeb(Engine)Settings objects to use.
+
+ Args:
+ settings: The QWeb(Engine)Settings instance to use, or None to use
+ the global instance.
+
+ Return:
+ A list of QWeb(Engine)Settings objects. The first one should be
+ used for reading.
+ """
+ if settings is None:
+ return self._get_global_settings()
+ else:
+ return [settings]
+
+ def set(self, value, settings=None):
+ """Set the value of this setting.
+
+ Args:
+ value: The value to set, or None to restore the default.
+ settings: The QWeb(Engine)Settings instance to use, or None to use
+ the global instance.
+ """
+ if value is None:
+ self.set_default(settings=settings)
+ else:
+ self._set(value, settings=settings)
+
+ def set_default(self, settings=None):
+ """Set the default value for this setting.
+
+ Not implemented for most settings.
+ """
+ if self._default is UNSET:
+ raise ValueError("No default set for {!r}".format(self))
+ else:
+ self._set(self._default, settings=settings)
+
+ def _set(self, value, settings):
+ """Inner function to set the value of this setting.
+
+ Must be overridden by subclasses.
+
+ Args:
+ value: The value to set.
+ settings: The QWeb(Engine)Settings instance to use, or None to use
+ the global instance.
+ """
+ raise NotImplementedError
+
+
+class Attribute(Base):
+
+ """A setting set via QWeb(Engine)Settings::setAttribute.
+
+ Attributes:
+ self._attributes: A list of QWeb(Engine)Settings::WebAttribute members.
+ """
+
+ ENUM_BASE = None
+
+ def __init__(self, *attributes, default=UNSET):
+ super().__init__(default=default)
+ self._attributes = list(attributes)
+
+ def __repr__(self):
+ attributes = [debug.qenum_key(self.ENUM_BASE, attr)
+ for attr in self._attributes]
+ return utils.get_repr(self, attributes=attributes, constructor=True)
+
+ def _set(self, value, settings=None):
+ for obj in self._get_settings(settings):
+ for attribute in self._attributes:
+ obj.setAttribute(attribute, value)
+
+
+class Setter(Base):
+
+ """A setting set via a QWeb(Engine)Settings setter method.
+
+ This will pass the QWeb(Engine)Settings instance ("self") as first argument
+ to the methods, so self._setter is the *unbound* method.
+
+ Attributes:
+ _setter: The unbound QWeb(Engine)Settings method to set this value.
+ _args: An iterable of the arguments to pass to the setter (before the
+ value).
+ _unpack: Whether to unpack args (True) or pass them directly (False).
+ """
+
+ def __init__(self, setter, args=(), unpack=False, default=UNSET):
+ super().__init__(default=default)
+ self._setter = setter
+ self._args = args
+ self._unpack = unpack
+
+ def __repr__(self):
+ return utils.get_repr(self, setter=self._setter, args=self._args,
+ unpack=self._unpack, constructor=True)
+
+ def _set(self, value, settings=None):
+ for obj in self._get_settings(settings):
+ args = [obj]
+ args.extend(self._args)
+ if self._unpack:
+ args.extend(value)
+ else:
+ args.append(value)
+ self._setter(*args)
+
+
+class StaticSetter(Setter):
+
+ """A setting set via a static QWeb(Engine)Settings method.
+
+ self._setter is the *bound* method.
+ """
+
+ def _set(self, value, settings=None):
+ if settings is not None:
+ raise ValueError("'settings' may not be set with StaticSetters!")
+ args = list(self._args)
+ if self._unpack:
+ args.extend(value)
+ else:
+ args.append(value)
+ self._setter(*args)
+
+
+class FontFamilySetter(Setter):
+
+ """A setter for a font family.
+
+ Gets the default value from QFont.
+ """
+
+ def __init__(self, setter, font, qfont):
+ super().__init__(setter=setter, args=[font])
+ self._qfont = qfont
+
+ def set_default(self, settings=None):
+ font = QFont()
+ font.setStyleHint(self._qfont)
+ value = font.defaultFamily()
+ self._set(value, settings=settings)
+
+
+def init_mappings(mappings):
+ """Initialize all settings based on a settings mapping."""
+ for option, mapping in mappings.items():
+ value = config.instance.get(option)
+ log.config.vdebug("Setting {} to {!r}".format(option, value))
+ mapping.set(value)
+
+
+def update_mappings(mappings, option):
+ """Update global settings when QWeb(Engine)Settings changed."""
+ try:
+ mapping = mappings[option]
+ except KeyError:
+ return
+ value = config.instance.get(option)
+ mapping.set(value)
+
+
+def init(args):
+ """Initialize all QWeb(Engine)Settings."""
+ if objects.backend == usertypes.Backend.QtWebEngine:
+ from qutebrowser.browser.webengine import webenginesettings
+ webenginesettings.init(args)
+ else:
+ from qutebrowser.browser.webkit import webkitsettings
+ webkitsettings.init(args)
+
+
+def shutdown():
+ """Shut down QWeb(Engine)Settings."""
+ if objects.backend == usertypes.Backend.QtWebEngine:
+ from qutebrowser.browser.webengine import webenginesettings
+ webenginesettings.shutdown()
+ else:
+ from qutebrowser.browser.webkit import webkitsettings
+ webkitsettings.shutdown()
diff --git a/pool/shard010/Python/0089183_mapParser.py b/pool/shard010/Python/0089183_mapParser.py
new file mode 100644
index 0000000000000000000000000000000000000000..92617c470c854a71c1b556fa973f0ab2f2f73346
--- /dev/null
+++ b/pool/shard010/Python/0089183_mapParser.py
@@ -0,0 +1,144 @@
+#!/usr/bin/python3.3 -O
+
+from pyrser import grammar,meta
+from pyrser.directives import ignore
+from network import Host, Router
+import sys
+
+def insensitiveCase(s):
+ return "[" + " ".join("['" + "'|'".join(x) + "']" for x in map((lambda each: [each.lower(), each.upper()]), s)) + "]"
+
+class MapParser(grammar.Grammar):
+ entry = "Map"
+ grammar = """
+
+ Map = [#init_map(_) @ignore("null") [[[Hosts:h #add_host(_, h)] | [Routers:r #add_router(_, r)]] eol*]+
+ #link_hosts(_) eof]
+
+ Hosts = [#init_host(_) '[' ws {host} ws ']' eol+ [[Name | Ip | TTL | Route]:r #add_fhost(_, r)]+]
+
+ Routers = [#init_router(_) '[' ws {router} ws ']' eol+ [[Name | Ip | TTL | Route]:r #add_frouter(_, r)]+]
+
+ Name = [ws {name} ws '=' ws id:i #ret_f(_, "id", i) ws eol+]
+
+ Ip = [ws {ip} ws '=' ws cidraddr:c #ret_f(_, "ip", c) ws eol+]
+
+ TTL = [ws {ttl} ws '=' ws num:n #ret_f(_, "ttl", n) ws eol+]
+
+ Route = [ws {route} ws '=' ws [[{default}:c ws id:i #ret_f(_, "route", c, i)]
+ | [cidraddr:c ws id:i #ret_f(_, "route", c, i)]] ws eol+]
+
+ cidraddr = [num '.' num '.' num '.' num '/' num]
+
+ ws = [[' ' | '\r' | '\t']*]
+ """.format(host = insensitiveCase("Host"),
+ router = insensitiveCase("Router"),
+ route = insensitiveCase("Route"),
+ ip = insensitiveCase("IP"),
+ ttl = insensitiveCase("TTL"),
+ name = insensitiveCase("Name"),
+ default = insensitiveCase("Default"),
+ internet = insensitiveCase("Internet"))
+
+
+@meta.hook(MapParser)
+def init_map(self, ast):
+ ast.network = {}
+ ast.routes = {}
+ return True
+
+@meta.hook(MapParser)
+def init_host(self, ast):
+ self.init_map(ast)
+ ast.network["route"] = []
+ return True
+
+@meta.hook(MapParser)
+def init_router(self, ast):
+ self.init_host(ast)
+ ast.network["ips"] = []
+ return True
+
+@meta.hook(MapParser)
+def link_hosts(self, ast):
+ for k,v in ast.routes.items():
+ for x in v:
+ if x[1] not in ast.network:
+ raise Exception("Unknown host ({0}) for {1} route.".format(x[1], k))
+ ast.network[k].addRoute(ast.network[x[1]], x[0])
+ return True
+
+def base_add(ast, h):
+ if "name" not in h.network:
+ raise Exception("Missing name field for given host:\n{0}".format(self.value(h)))
+ if h.network["name"] in ast.network:
+ raise Exception("Redefinion of {0}.".format(h.network["name"]))
+ ast.routes[h.network["name"]] = h.network["route"][::]
+
+@meta.hook(MapParser)
+def add_host(self, ast, h):
+ base_add(ast, h)
+ if "ip" not in h.network:
+ raise Exception("Missing ip field for given host:\n{0}".format(self.value(h)))
+ if "ttl" in h.network:
+ ast.network[h.network["name"]] = Host(h.network["name"],
+ h.network["ip"], h.network["ttl"])
+ else:
+ ast.network[h.network["name"]] = Host(h.network["name"],
+ h.network["ip"])
+ return True
+
+@meta.hook(MapParser)
+def add_router(self, ast, h):
+ base_add(ast, h)
+ if not h.network["ips"]:
+ raise Exception("Missing ip field for given host")
+ if "ttl" in h.network:
+ ast.network[h.network["name"]] = Router(h.network["name"],
+ *h.network["ips"], ttl = h.network["ttl"])
+ else:
+ ast.network[h.network["name"]] = Router(h.network["name"],
+ *h.network["ips"])
+ return True
+
+@meta.hook(MapParser)
+def ret_f(self, ast, *args):
+ ast.retvals = [args[0]]
+ ast.retvals.extend([self.value(x) for x in args[1:]])
+ return True
+
+@meta.hook(MapParser)
+def add_fhost(self, ast, r):
+ def reg_name(ast, name):
+ ast.network["name"] = name[0]
+ def reg_ip(ast, ip):
+ ast.network["ip"] = ip[0]
+ def reg_ttl(ast, ttl):
+ ast.network["ttl"] = ttl[0]
+ def reg_route(ast, route):
+ ast.network["route"].append(route)
+ fmap = {'id' : reg_name,
+ 'ip' : reg_ip,
+ 'ttl' : reg_ttl,
+ 'route' : reg_route}
+ if r.retvals[0] in fmap:
+ fmap[r.retvals[0]](ast, r.retvals[1:])
+ return True
+
+@meta.hook(MapParser)
+def add_frouter(self, ast, r):
+ def reg_name(ast, name):
+ ast.network["name"] = name[0]
+ def reg_ip(ast, ip):
+ ast.network["ips"].append(ip[0])
+ def reg_ttl(ast, ttl):
+ ast.network["ttl"] = ttl[0]
+ def reg_route(ast, route):
+ ast.network["route"].append(route)
+ fmap = {'id' : reg_name,
+ 'ip' : reg_ip,
+ 'ttl' : reg_ttl,
+ 'route' : reg_route}
+ if r.retvals[0] in fmap:
+ fmap[r.retvals[0]](ast, r.retvals[1:])
+ return True
diff --git a/pool/shard010/Python/0089190_pureftp.py b/pool/shard010/Python/0089190_pureftp.py
new file mode 100644
index 0000000000000000000000000000000000000000..48018c0c0f335492dea327690474bbe68d467d38
--- /dev/null
+++ b/pool/shard010/Python/0089190_pureftp.py
@@ -0,0 +1,159 @@
+"""
+PureFTP Blueprint
+===============
+
+**Fabric environment:**
+
+.. code-block:: yaml
+
+ blueprints:
+ - blues.pureftp
+ settings:
+ pureftp:
+ users:
+ - username: joe
+ password: rosebud
+
+"""
+import os
+from fabric.context_managers import settings
+from fabric.contrib import files
+from fabric.decorators import task
+
+from refabric.context_managers import sudo, silent
+from refabric.contrib import blueprints
+
+from . import debian
+from . import user
+from refabric.operations import run
+
+__all__ = ['start', 'stop', 'restart', 'setup', 'configure']
+
+
+blueprint = blueprints.get(__name__)
+
+start = debian.service_task('pure-ftpd', 'start')
+stop = debian.service_task('pure-ftpd', 'stop')
+restart = debian.service_task('pure-ftpd', 'restart')
+
+ftp_root = '/srv/ftp'
+ftp_user = 'ftp'
+ftp_group = 'www-data'
+
+
+@task
+def setup():
+ """
+ Install and configure PureFTP
+ """
+ install()
+ configure()
+
+
+def install():
+ with sudo():
+ debian.apt_get('install', 'pure-ftpd', 'openssl')
+
+ # Create ftp user
+ debian.useradd(ftp_user, '/dev/null', shell='/bin/false',
+ user_group=True, groups=[ftp_group], uid_min=1000)
+
+ # Create ftp root dir
+ debian.mkdir(ftp_root, mode=1770, owner=ftp_user, group=ftp_group)
+
+ # Set up symlinks
+ debian.ln('/etc/pure-ftpd/conf/PureDB', '/etc/pure-ftpd/auth/PureDB')
+
+ # Enable TLS
+ run('echo 1 > /etc/pure-ftpd/conf/TLS')
+ key_path = '/etc/ssl/private/pure-ftpd.pem'
+ if not files.exists(key_path):
+ prompts = {
+ 'Country Name (2 letter code) [AU]:': '',
+ 'State or Province Name (full name) [Some-State]:': '',
+ 'Locality Name (eg, city) []:': '',
+ 'Organization Name (eg, company) [Internet Widgits Pty Ltd]:': '',
+ 'Organizational Unit Name (eg, section) []:': '',
+ 'Common Name (e.g. server FQDN or YOUR name) []:': '',
+ 'Email Address []:': ''
+ }
+ with settings(prompts=prompts):
+ run('openssl req -x509 -nodes -newkey rsa:2048 -keyout {0} -out {0}'.format(
+ key_path))
+ debian.chmod(key_path, 600)
+
+
+@task
+def configure():
+ """
+ Configure PureFTP
+ """
+ with sudo():
+ # Echo configurations
+ setup_config()
+
+ for user in blueprint.get('users'):
+ username, password = user['username'], user['password']
+ if 'homedir' in user:
+ user_home = user['homedir']
+ else:
+ user_home = os.path.join(ftp_root, username)
+
+ passwd_path = '/etc/pure-ftpd/pureftpd.passwd'
+ with settings(warn_only=True):
+ if files.exists(passwd_path) and run('pure-pw show {}'.format(
+ username)).return_code == 0:
+ continue
+ debian.mkdir(user_home, owner=ftp_user, group=ftp_group)
+ prompts = {
+ 'Password: ': password,
+ 'Enter it again: ': password
+ }
+ with settings(prompts=prompts):
+ run('pure-pw useradd {} -u {} -g {} -d {}'.format(username, ftp_user, ftp_group,
+ user_home))
+ run('pure-pw mkdb')
+ restart()
+
+
+config_defaults = {
+ 'ChrootEveryone': 'yes', # Cage in every user in his home directory
+ 'BrokenClientsCompatibility': 'yes', # Turn on compatibility hacks for broken clients
+ 'MaxClientsNumber': '50', # Maximum number of simultaneous users
+ 'MaxClientsPerIP': '5', # Maximum number of sim clients with the same IP address
+ 'Daemonize': 'yes', # Fork in background
+ 'VerboseLog': 'yes', # Turn off verbose logging
+ 'DisplayDotFiles': 'yes', # List dot-files even when the client doesn't send "-a".
+ 'ProhibitDotFilesWrite': 'yes', # Users can't delete/write files beginning with a dot ('.')
+ 'NoChmod': 'yes', # Disallow the CHMOD command. Users can't change perms of their files.
+ 'AnonymousOnly': 'no', # Don't allow authenticated users - have a public anonymous FTP only.
+ 'NoAnonymous': 'yes', # Don't allow authenticated users - have a public anonymous FTP only.
+ 'PAMAuthentication': 'no', # Disable PAM authentication
+ 'UnixAuthentication': 'no', # Disable /etc/passwd (UNIX) authentication
+ 'DontResolve': 'yes', # Don't resolve host names in log files.
+ 'MaxIdleTime': '15', # Maximum idle time in minutes (default = 15 minutes)
+ 'LimitRecursion': '2000 8', # 'ls' recursion limits.
+ 'AntiWarez': 'yes', # Disallow downloading of files owned by "ftp"
+ 'AnonymousCanCreateDirs': 'no', # Are anonymous users allowed to create new directories ?
+ 'MaxLoad': '6', # If the system is more loaded than the following value, disallow download.
+ 'AllowUserFXP': 'no', # Disallow FXP transfers for authenticated users.
+ 'AllowAnonymousFXP': 'no', # Disallow anonymous FXP for anonymous and non-anonymous users.
+ 'AutoRename': 'no', # Turn off autorenaming of conflicting filenames
+ 'AnonymousCantUpload': 'yes', # Disallow anonymous users to upload new files (no = upload is allowed)
+ 'NoChmod': 'yes', # Disallow the CHMOD command. Users can't change perms of their files.
+ 'MaxDiskUsage': '80', # When the partition is more that X percent full, new uploads are disallowed.
+ 'CustomerProof': 'yes', # Workaround against common customer mistakes like chmod 0 public_html
+ 'PureDB': '/etc/pure-ftpd/pureftpd.pdb' # User database
+}
+
+
+def set_pureftp_config_value(**kwargs):
+ for key, value in kwargs.iteritems():
+ run("echo '{}' > /etc/pure-ftpd/conf/{}".format(value, key))
+
+
+def setup_config():
+ with silent():
+ config = config_defaults.copy()
+ config.update(blueprint.get(''))
+ set_pureftp_config_value(**config_defaults)
diff --git a/pool/shard010/Python/0089210_run.py b/pool/shard010/Python/0089210_run.py
new file mode 100644
index 0000000000000000000000000000000000000000..88823cf8c68f8b84a1188e7268bfe57555117c0a
--- /dev/null
+++ b/pool/shard010/Python/0089210_run.py
@@ -0,0 +1,181 @@
+#!/usr/bin/env python
+# ----------------------------------------------------------------------
+# Copyright (C) 2014-2015, Numenta, Inc. Unless you have an agreement
+# with Numenta, Inc., for a separate license for this software code, the
+# following terms and conditions apply:
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero Public License version 3 as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the GNU Affero Public License for more details.
+#
+# You should have received a copy of the GNU Affero Public License
+# along with this program. If not, see http://www.gnu.org/licenses.
+#
+# http://numenta.org/licenses/
+# ----------------------------------------------------------------------
+
+import argparse
+import os
+try:
+ import simplejson as json
+except ImportError:
+ import json
+
+from nab.runner import Runner
+from nab.util import (detectorNameToClass, checkInputs)
+
+
+
+def getDetectorClassConstructors(detectors):
+ """
+ Takes in names of detectors. Collects class names that correspond to those
+ detectors and returns them in a dict. The dict maps detector name to class
+ names. Assumes the detectors have been imported.
+ """
+ detectorConstructors = {
+ d : globals()[detectorNameToClass(d)] for d in detectors}
+
+ return detectorConstructors
+
+
+def main(args):
+
+ root = os.path.dirname(os.path.realpath(__file__))
+
+ numCPUs = int(args.numCPUs) if args.numCPUs is not None else None
+
+ dataDir = os.path.join(root, args.dataDir)
+ windowsFile = os.path.join(root, args.windowsFile)
+ resultsDir = os.path.join(root, args.resultsDir)
+ profilesFile = os.path.join(root, args.profilesFile)
+ thresholdsFile = os.path.join(root, args.thresholdsFile)
+
+ runner = Runner(dataDir=dataDir,
+ labelPath=windowsFile,
+ resultsDir=resultsDir,
+ profilesPath=profilesFile,
+ thresholdPath=thresholdsFile,
+ numCPUs=numCPUs)
+
+ runner.initialize()
+
+ if args.detect:
+ detectorConstructors = getDetectorClassConstructors(args.detectors)
+ runner.detect(detectorConstructors)
+
+ if args.optimize:
+ runner.optimize(args.detectors)
+
+ if args.score:
+ with open(args.thresholdsFile) as thresholdConfigFile:
+ detectorThresholds = json.load(thresholdConfigFile)
+ runner.score(args.detectors, detectorThresholds)
+
+ if args.normalize:
+ try:
+ runner.normalize()
+ except AttributeError("Error: you must run the scoring step with the "
+ "normalization step."):
+ return
+
+
+if __name__ == "__main__":
+
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument("--detect",
+ help="Generate detector results but do not analyze results "
+ "files.",
+ default=False,
+ action="store_true")
+
+ parser.add_argument("--optimize",
+ help="Optimize the thresholds for each detector and user "
+ "profile combination",
+ default=False,
+ action="store_true")
+
+ parser.add_argument("--score",
+ help="Analyze results in the results directory",
+ default=False,
+ action="store_true")
+
+ parser.add_argument("--normalize",
+ help="Normalize the final scores",
+ default=False,
+ action="store_true")
+
+ parser.add_argument("--skipConfirmation",
+ help="If specified will skip the user confirmation step",
+ default=False,
+ action="store_true")
+
+ parser.add_argument("--dataDir",
+ default="data",
+ help="This holds all the label windows for the corpus.")
+
+ parser.add_argument("--resultsDir",
+ default="results",
+ help="This will hold the results after running detectors "
+ "on the data")
+
+ parser.add_argument("--windowsFile",
+ default=os.path.join("labels", "combined_windows.json"),
+ help="JSON file containing ground truth labels for the "
+ "corpus.")
+
+ parser.add_argument("-d", "--detectors",
+ nargs="*",
+ type=str,
+ default=["null", "numenta", "random", "skyline"],
+ help="Comma separated list of detector(s) to use, e.g. "
+ "null,numenta")
+
+ parser.add_argument("-p", "--profilesFile",
+ default=os.path.join("config", "profiles.json"),
+ help="The configuration file to use while running the "
+ "benchmark.")
+
+ parser.add_argument("-t", "--thresholdsFile",
+ default=os.path.join("config", "thresholds.json"),
+ help="The configuration file that stores thresholds for "
+ "each combination of detector and username")
+
+ parser.add_argument("-n", "--numCPUs",
+ default=None,
+ help="The number of CPUs to use to run the "
+ "benchmark. If not specified all CPUs will be used.")
+
+ args = parser.parse_args()
+
+ if (not args.detect
+ and not args.optimize
+ and not args.score
+ and not args.normalize):
+ args.detect = True
+ args.optimize = True
+ args.score = True
+ args.normalize = True
+
+ if len(args.detectors) == 1:
+ # Handle comma-seperated list argument.
+ args.detectors = args.detectors[0].split(',')
+
+ # The following imports are necessary for getDetectorClassConstructors to
+ # automatically figure out the detector classes.
+ # Only import numenta detector if used so as to avoid unnecessary dependency
+ if "numenta" in args.detectors:
+ from nab.detectors.numenta.numenta_detector import NumentaDetector
+ from nab.detectors.skyline.skyline_detector import SkylineDetector
+ from nab.detectors.random.random_detector import RandomDetector
+ from nab.detectors.null.null_detector import NullDetector
+ from nab.detectors.democratic.democratic_detector import DemocraticDetector
+
+ if args.skipConfirmation or checkInputs(args):
+ main(args)
+
diff --git a/pool/shard010/Python/0089213_api_views.py b/pool/shard010/Python/0089213_api_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..13bbbff573d37c69a92593f1f9563aa24ed7ccc1
--- /dev/null
+++ b/pool/shard010/Python/0089213_api_views.py
@@ -0,0 +1,108 @@
+from rest_framework.renderers import JSONRenderer, JSONPRenderer
+from rest_framework import permissions, viewsets
+from rest_framework import generics
+
+from django.contrib.auth.models import User
+from django.shortcuts import get_object_or_404
+
+from fastapp.models import Base, Apy, Setting
+from fastapp.serializers import ApySerializer, BaseSerializer, SettingSerializer
+from fastapp.utils import info, error, warn
+from rest_framework.decorators import link
+from rest_framework.response import Response
+
+import logging
+logger = logging.getLogger(__name__)
+
+class SettingViewSet(viewsets.ModelViewSet):
+ model = Setting
+ serializer_class = SettingSerializer
+ renderer_classes = [JSONRenderer, JSONPRenderer]
+
+ def get_queryset(self):
+ base_pk = self.kwargs['base_pk']
+ return Setting.objects.filter(base__user=self.request.user, base__pk=base_pk)
+
+ def pre_save(self, obj):
+ obj.base = Base.objects.get(id=self.kwargs['base_pk'])
+
+class ApyViewSet(viewsets.ModelViewSet):
+ model = Apy
+ serializer_class = ApySerializer
+ renderer_classes = [JSONRenderer, JSONPRenderer]
+ permission_classes = (permissions.IsAuthenticated,)
+
+ def get_queryset(self):
+ base_pk = self.kwargs['base_pk']
+ return Apy.objects.filter(base__user=self.request.user, base__pk=base_pk)
+
+ def pre_save(self, obj):
+ obj.base = Base.objects.get(id=self.kwargs['base_pk'], user=self.request.user)
+
+ def post_save(self, obj, created=False):
+ info(self.request.user.username, "Apy saved")
+
+ def clone(self, request, base_pk, pk):
+ base = get_object_or_404(Base, id=base_pk, user=User.objects.get(username=request.user.username))
+ clone_count = base.apys.filter(name__startswith="%s_clone" % pk).count()
+ created = False
+ while not created:
+ cloned_exec, created = Apy.objects.get_or_create(base=base, name="%s_clone_%s" % (pk, str(clone_count+1)))
+ clone_count+=1
+
+ cloned_exec.module = base.apys.get(id=pk).module
+ cloned_exec.save()
+
+ self.object = cloned_exec
+ self.kwargs['pk'] = self.object.id
+ return self.retrieve(request, new_pk=cloned_exec.id)
+
+class BaseViewSet(viewsets.ModelViewSet):
+ model = Base
+ serializer_class = BaseSerializer
+ renderer_classes = [JSONRenderer, JSONPRenderer]
+ permission_classes = (permissions.IsAuthenticated,)
+
+ def get_queryset(self):
+ return Base.objects.filter(user=self.request.user)
+
+ def start(self, request, pk):
+ logger.info("starting %s" % pk)
+ base = self.get_queryset().get(id=pk)
+ base.start()
+ return self.retrieve(request, pk=pk)
+
+ def stop(self, request, pk):
+ logger.info("stopping %s" % pk)
+ base = self.get_queryset().get(id=pk)
+ base.stop()
+ return self.retrieve(request, pk=pk)
+
+ @link()
+ def apy(self, request, pk=None):
+ queryset = Apy.objects.filter(base__pk=pk)
+ serializer = ApySerializer(queryset,
+ context={'request': request}, many=True)
+ return Response(serializer.data)
+
+
+#class BaseListView(generics.GenericAPIView):
+# serializer_class = BaseSerializer
+# permission_classes = (permissions.IsAuthenticated,)
+#
+# def get_queryset(self):
+# return Base.objects.filter(user=self.request.user)
+
+#class BaseListView(generics.GenericAPIView):
+# serializer_class = BaseSerializer
+# permission_classes = (permissions.IsAuthenticated,)
+#
+# def get_queryset(self):
+# return Base.objects.filter(user=self.request.user)
+
+ #@link()
+ #def apy(self, request, pk=None):
+ # queryset = Apy.objects.filter(base__pk=pk)
+ # serializer = ApySerializer(queryset,
+ # context={'request': request}, many=True)
+ # return Response(serializer.data)
diff --git a/pool/shard010/Python/0089214_test3.py b/pool/shard010/Python/0089214_test3.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2794c5fcf20727a6972b2af665fda824cf986e6
--- /dev/null
+++ b/pool/shard010/Python/0089214_test3.py
@@ -0,0 +1,19 @@
+"""
+Programmatically checking radio-buttons.
+"""
+
+import os, sys
+
+os.chdir(os.path.dirname(os.path.realpath(__file__)))
+sys.path.append("../../atlastk")
+
+import atlastk
+
+CALLBACKS = {
+ "": lambda dom: dom.inner("", open("Test3.html").read()),
+ "rdSelect": lambda dom, id: dom.set_value("rdCheck", dom.get_value(id)),
+ "rdSubmit": lambda dom, id: dom.alert(f'Selected method: "{dom.get_value("rdContact")}"' ),
+ "rdCheck": lambda dom, id: dom.set_value("rdContact", dom.get_value(id))
+}
+
+atlastk.launch(CALLBACKS)
\ No newline at end of file
diff --git a/pool/shard010/Python/0089216_export.py b/pool/shard010/Python/0089216_export.py
new file mode 100644
index 0000000000000000000000000000000000000000..3383dcf2eab0ba5620151b6c989de5a3557ae685
--- /dev/null
+++ b/pool/shard010/Python/0089216_export.py
@@ -0,0 +1,24 @@
+import os
+
+from keras import backend as K
+import tensorflow as tf
+from tensorflow.python.tools.freeze_graph import freeze_graph
+
+
+def exportModelToTF(tfModelOutputDir):
+
+ if not os.path.exists(tfModelOutputDir):
+ os.makedirs(tfModelOutputDir)
+
+ # Save checkpoint
+ saver = tf.train.Saver()
+ save_path = saver.save(K.get_session(), tfModelOutputDir + "/model")
+
+ # Save metagraph
+ tf.train.write_graph(K.get_session().graph.as_graph_def(), "", tfModelOutputDir + "/metagraph.pb", False)
+
+ # Freeze graph
+ freeze_graph(input_graph=tfModelOutputDir + "/metagraph.pb", input_saver="", input_binary=True,
+ input_checkpoint=tfModelOutputDir + "/model", output_node_names='softmax/Softmax',
+ restore_op_name="save/restore_all", filename_tensor_name="save/Const:0",
+ output_graph=tfModelOutputDir + "/graph.pb", clear_devices=True, initializer_nodes="")
diff --git a/pool/shard010/Python/0089221_flash_info.py b/pool/shard010/Python/0089221_flash_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bfa68a9eb80594978fd2006645f837ef51b3e8a
--- /dev/null
+++ b/pool/shard010/Python/0089221_flash_info.py
@@ -0,0 +1,98 @@
+###########################################################
+#
+# Copyright (c) 2005, Southpaw Technology
+# All Rights Reserved
+#
+# PROPRIETARY INFORMATION. This software is proprietary to
+# Southpaw Technology, and is not to be reproduced, transmitted,
+# or disclosed in any way without written permission.
+#
+#
+#
+__all__ = ['FlashInfo']
+
+import cStringIO, os, sys, urllib, xmlrpclib
+from xml.dom.minidom import parseString
+
+
+from pyasm.application.common import BaseAppInfo
+
+
+class FlashInfo(BaseAppInfo):
+ '''Gets data fed by the TACTIC server in a well know location'''
+
+ def __init__(my, app_name):
+
+ super(FlashInfo,my).__init__(app_name)
+
+ # read from a file a parse
+ my.ticket = "2b6754788b90877f0240e4b1d8e620b3"
+ my.xmlrpc_url = "http://fugu/tactic/flash/XMLRPC"
+ my.upload_server = "http://fugu/tactic/default/UploadServer/"
+ my.tactic_user = "boris"
+ my.tmpdir = "D:/tactic_temp"
+ my.trash_dir = '%s/temp' %my.tmpdir
+ my.sandbox_dir = "D:/tactic_temp/sandbox"
+ my.publish_dir = "D:/tactic_temp/publish/%s" %my.tactic_user
+ my.check_dirs()
+
+ def check_dirs(my):
+
+ if not os.path.exists(my.trash_dir):
+ os.makedirs(dir)
+ if not os.path.exists(my.publish_dir):
+ os.makedirs(my.publish_dir)
+
+ def get_ticket(my):
+ assert my.ticket
+ return my.ticket
+
+ def get_xmlrpc_server(my):
+ assert my.xmlrpc_url
+ if not my.xmlrpc_server:
+ my.xmlrpc_server = xmlrpclib.Server(my.xmlrpc_url)
+ return my.xmlrpc_server
+
+ def get_upload_server(my):
+ assert my.upload_server
+ return my.upload_server
+
+ def get_user(my):
+ assert my.user
+ return my.user
+
+ def get_tmp_dir(my):
+ assert my.tmpdir
+ return my.tmpdir
+
+ def get_sandbox_dir(my):
+ assert my.sandbox_dir
+ return my.sandbox_dir
+
+ def get_log_path(my):
+
+ to_path = '%s/actionLog.txt' %my.trash_dir
+ if not os.path.exists(to_path):
+ file = open(to_path, "wb")
+ return to_path
+
+ def get_publish_dir(my):
+ return my.publish_dir
+
+ def report_error(my, exception):
+ print "Error: ", exception
+
+ def report_warning(my, exception):
+ print "Warning: ", exception
+
+"""
+def upload_warning():
+ info = TacticInfo.get()
+ info.report_warning('','', upload=True)
+
+ #remove the file afterwards
+ path = "%s/warning.txt" % info.get_tmpdir()
+ if os.path.exists(path):
+ os.unlink(path)
+
+"""
diff --git a/pool/shard010/Python/0089222_test_cmdline.py b/pool/shard010/Python/0089222_test_cmdline.py
new file mode 100644
index 0000000000000000000000000000000000000000..e75b7baf0e1b3443167e78d65fd2604e6f37871d
--- /dev/null
+++ b/pool/shard010/Python/0089222_test_cmdline.py
@@ -0,0 +1,142 @@
+import argparse
+import base64
+from mitmproxy import cmdline
+from . import tutils
+
+
+def test_parse_replace_hook():
+ x = cmdline.parse_replace_hook("/foo/bar/voing")
+ assert x == ("foo", "bar", "voing")
+
+ x = cmdline.parse_replace_hook("/foo/bar/vo/ing/")
+ assert x == ("foo", "bar", "vo/ing/")
+
+ x = cmdline.parse_replace_hook("/bar/voing")
+ assert x == (".*", "bar", "voing")
+
+ tutils.raises(
+ cmdline.ParseException,
+ cmdline.parse_replace_hook,
+ "/foo"
+ )
+ tutils.raises(
+ "replacement regex",
+ cmdline.parse_replace_hook,
+ "patt/[/rep"
+ )
+ tutils.raises(
+ "filter pattern",
+ cmdline.parse_replace_hook,
+ "/~/foo/rep"
+ )
+ tutils.raises(
+ "empty clause",
+ cmdline.parse_replace_hook,
+ "//"
+ )
+
+
+def test_parse_server_spec():
+ tutils.raises("Invalid server specification", cmdline.parse_server_spec, "")
+ assert cmdline.parse_server_spec(
+ "http://foo.com:88") == ("http", ("foo.com", 88))
+ assert cmdline.parse_server_spec(
+ "http://foo.com") == ("http", ("foo.com", 80))
+ assert cmdline.parse_server_spec(
+ "https://foo.com") == ("https", ("foo.com", 443))
+ tutils.raises(
+ "Invalid server specification",
+ cmdline.parse_server_spec,
+ "foo.com")
+ tutils.raises(
+ "Invalid server specification",
+ cmdline.parse_server_spec,
+ "http://")
+
+
+def test_parse_upstream_auth():
+ tutils.raises("Invalid upstream auth specification", cmdline.parse_upstream_auth, "")
+ tutils.raises("Invalid upstream auth specification", cmdline.parse_upstream_auth, ":")
+ tutils.raises("Invalid upstream auth specification", cmdline.parse_upstream_auth, ":test")
+ assert cmdline.parse_upstream_auth(
+ "test:test") == "Basic" + " " + base64.b64encode("test:test")
+ assert cmdline.parse_upstream_auth(
+ "test:") == "Basic" + " " + base64.b64encode("test:")
+
+
+def test_parse_setheaders():
+ x = cmdline.parse_setheader("/foo/bar/voing")
+ assert x == ("foo", "bar", "voing")
+
+
+def test_common():
+ parser = argparse.ArgumentParser()
+ cmdline.common_options(parser)
+ opts = parser.parse_args(args=[])
+
+ assert cmdline.get_common_options(opts)
+
+ opts.stickycookie_filt = "foo"
+ opts.stickyauth_filt = "foo"
+ v = cmdline.get_common_options(opts)
+ assert v["stickycookie"] == "foo"
+ assert v["stickyauth"] == "foo"
+
+ opts.setheader = ["/foo/bar/voing"]
+ v = cmdline.get_common_options(opts)
+ assert v["setheaders"] == [("foo", "bar", "voing")]
+
+ opts.setheader = ["//"]
+ tutils.raises(
+ "empty clause",
+ cmdline.get_common_options,
+ opts
+ )
+ opts.setheader = []
+
+ opts.replace = ["/foo/bar/voing"]
+ v = cmdline.get_common_options(opts)
+ assert v["replacements"] == [("foo", "bar", "voing")]
+
+ opts.replace = ["//"]
+ tutils.raises(
+ "empty clause",
+ cmdline.get_common_options,
+ opts
+ )
+
+ opts.replace = []
+ opts.replace_file = [("/foo/bar/nonexistent")]
+ tutils.raises(
+ "could not read replace file",
+ cmdline.get_common_options,
+ opts
+ )
+
+ opts.replace_file = [("/~/bar/nonexistent")]
+ tutils.raises(
+ "filter pattern",
+ cmdline.get_common_options,
+ opts
+ )
+
+ p = tutils.test_data.path("data/replace")
+ opts.replace_file = [("/foo/bar/%s" % p)]
+ v = cmdline.get_common_options(opts)["replacements"]
+ assert len(v) == 1
+ assert v[0][2].strip() == "replacecontents"
+
+
+def test_mitmproxy():
+ ap = cmdline.mitmproxy()
+ assert ap
+
+
+def test_mitmdump():
+ ap = cmdline.mitmdump()
+ assert ap
+
+
+def test_mitmweb():
+ ap = cmdline.mitmweb()
+ assert ap
diff --git a/pool/shard010/Python/0089233_0035_auto_20170330_0850.py b/pool/shard010/Python/0089233_0035_auto_20170330_0850.py
new file mode 100644
index 0000000000000000000000000000000000000000..aacdec01d8a3cea4c6d41c8314e560b6914b2d89
--- /dev/null
+++ b/pool/shard010/Python/0089233_0035_auto_20170330_0850.py
@@ -0,0 +1,25 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9.9 on 2017-03-30 08:50
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('website', '0034_auto_20170330_0836'),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name='lecture',
+ name='lector',
+ ),
+ migrations.AddField(
+ model_name='lecture',
+ name='speaker',
+ field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='website.Speaker'),
+ ),
+ ]
diff --git a/pool/shard010/Python/0089234_test_toolchain.py b/pool/shard010/Python/0089234_test_toolchain.py
new file mode 100644
index 0000000000000000000000000000000000000000..024fa24084f8e73b946b0981d1fd410b09d23688
--- /dev/null
+++ b/pool/shard010/Python/0089234_test_toolchain.py
@@ -0,0 +1,143 @@
+import io
+import sys
+import pytest
+from unittest import mock
+from pythonforandroid.recipe import Recipe
+from pythonforandroid.toolchain import ToolchainCL
+from pythonforandroid.util import BuildInterruptingException
+
+
+def patch_sys_argv(argv):
+ return mock.patch('sys.argv', argv)
+
+
+def patch_argparse_print_help():
+ return mock.patch('argparse.ArgumentParser.print_help')
+
+
+def patch_sys_stdout():
+ return mock.patch('sys.stdout', new_callable=io.StringIO)
+
+
+def raises_system_exit():
+ return pytest.raises(SystemExit)
+
+
+class TestToolchainCL:
+
+ def test_help(self):
+ """
+ Calling with `--help` should print help and exit 0.
+ """
+ argv = ['toolchain.py', '--help', '--storage-dir=/tmp']
+ with patch_sys_argv(argv), raises_system_exit(
+ ) as ex_info, patch_argparse_print_help() as m_print_help:
+ ToolchainCL()
+ assert ex_info.value.code == 0
+ assert m_print_help.call_args_list == [mock.call()]
+
+ @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires python3")
+ def test_unknown(self):
+ """
+ Calling with unknown args should print help and exit 1.
+ """
+ argv = ['toolchain.py', '--unknown']
+ with patch_sys_argv(argv), raises_system_exit(
+ ) as ex_info, patch_argparse_print_help() as m_print_help:
+ ToolchainCL()
+ assert ex_info.value.code == 1
+ assert m_print_help.call_args_list == [mock.call()]
+
+ def test_create(self):
+ """
+ Basic `create` distribution test.
+ """
+ argv = [
+ 'toolchain.py',
+ 'create',
+ '--sdk-dir=/tmp/android-sdk',
+ '--ndk-dir=/tmp/android-ndk',
+ '--bootstrap=service_only',
+ '--requirements=python3',
+ '--dist-name=test_toolchain',
+ ]
+ with patch_sys_argv(argv), mock.patch(
+ 'pythonforandroid.build.get_available_apis'
+ ) as m_get_available_apis, mock.patch(
+ 'pythonforandroid.build.get_toolchain_versions'
+ ) as m_get_toolchain_versions, mock.patch(
+ 'pythonforandroid.build.get_ndk_platform_dir'
+ ) as m_get_ndk_platform_dir, mock.patch(
+ 'pythonforandroid.toolchain.build_recipes'
+ ) as m_build_recipes, mock.patch(
+ 'pythonforandroid.bootstraps.service_only.'
+ 'ServiceOnlyBootstrap.assemble_distribution'
+ ) as m_run_distribute:
+ m_get_available_apis.return_value = [27]
+ m_get_toolchain_versions.return_value = (['4.9'], True)
+ m_get_ndk_platform_dir.return_value = (
+ '/tmp/android-ndk/platforms/android-21/arch-arm', True)
+ ToolchainCL()
+ assert m_get_available_apis.call_args_list in [
+ [mock.call('/tmp/android-sdk')], # linux case
+ [mock.call('/private/tmp/android-sdk')] # macos case
+ ]
+ assert m_get_toolchain_versions.call_args_list in [
+ [mock.call('/tmp/android-ndk', mock.ANY)], # linux case
+ [mock.call('/private/tmp/android-ndk', mock.ANY)], # macos case
+ ]
+ build_order = [
+ 'hostpython3', 'libffi', 'openssl', 'sqlite3', 'python3',
+ 'genericndkbuild', 'setuptools', 'six', 'pyjnius', 'android',
+ ]
+ python_modules = []
+ context = mock.ANY
+ project_dir = None
+ assert m_build_recipes.call_args_list == [
+ mock.call(
+ build_order,
+ python_modules,
+ context,
+ project_dir,
+ ignore_project_setup_py=False
+ )
+ ]
+ assert m_run_distribute.call_args_list == [mock.call()]
+
+ @mock.patch(
+ 'pythonforandroid.build.environ',
+ # Make sure that no environ variable modifies `sdk_dir`
+ {'ANDROIDSDK': None, 'ANDROID_HOME': None})
+ def test_create_no_sdk_dir(self):
+ """
+ The `--sdk-dir` is mandatory to `create` a distribution.
+ """
+ argv = ['toolchain.py', 'create']
+ with patch_sys_argv(argv), pytest.raises(
+ BuildInterruptingException
+ ) as ex_info:
+ ToolchainCL()
+ assert ex_info.value.message == (
+ 'Android SDK dir was not specified, exiting.')
+
+ @pytest.mark.skipif(sys.version_info < (3, 0), reason="requires python3")
+ def test_recipes(self):
+ """
+ Checks the `recipes` command prints out recipes information without crashing.
+ """
+ argv = ['toolchain.py', 'recipes']
+ with patch_sys_argv(argv), patch_sys_stdout() as m_stdout:
+ ToolchainCL()
+ # check if we have common patterns in the output
+ expected_strings = (
+ 'conflicts:',
+ 'depends:',
+ 'kivy',
+ 'optional depends:',
+ 'python3',
+ 'sdl2',
+ )
+ for expected_string in expected_strings:
+ assert expected_string in m_stdout.getvalue()
+ # deletes static attribute to not mess with other tests
+ del Recipe.recipes
diff --git a/pool/shard010/Python/0089236_gtk_web_browser.py b/pool/shard010/Python/0089236_gtk_web_browser.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9c74c2e79aedd5c5110d321ba4c8528ce86334c
--- /dev/null
+++ b/pool/shard010/Python/0089236_gtk_web_browser.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python
+
+import os
+os.environ["LD_LIBRARY_PATH"]="/usr/lib/firefox/"
+import gtk
+import gtkmozembed
+
+class TinyGecko:
+ def __init__(self):
+ self.moz = gtkmozembed.MozEmbed()
+ win = gtk.Window()
+ win.set_default_size(800,800)
+ win.add(self.moz)
+ gtkmozembed.set_profile_path("/tmp", "foobar")
+ win.show_all()
+ self.moz.load_url('http://hatfull12.bio.pitt.edu:8080')
+ data = 'Hello pygtk dev'
+ self.moz.render_data(data, long(len(data)), 'file:///', 'text/html')
+
+if __name__ == '__main__':
+ TinyGecko()
+ gtk.main()
diff --git a/pool/shard010/Python/0089241_master.py b/pool/shard010/Python/0089241_master.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a9a9d605cf264cbcfb7f5e1c4fbca74b1da2472
--- /dev/null
+++ b/pool/shard010/Python/0089241_master.py
@@ -0,0 +1,162 @@
+from pynamodb.models import Model
+from pynamodb.attributes import (UnicodeAttribute, UTCDateTimeAttribute,
+ NumberAttribute, UnicodeSetAttribute, JSONAttribute)
+from datetime import datetime
+import logging
+import boto.ec2
+import boto.exception
+import masterdirac.models.systemdefaults as sys_def
+#STATES
+NA = -10
+TERMINATED_WITH_ERROR = -5
+INIT = 0
+RUN = 10
+TERMINATED = 30
+logger = logging.getLogger(__name__)
+
+class ANMaster(Model):
+ class Meta:
+ region = 'us-east-1'
+ table_name = 'aurea-nebula-master'
+ master_name = UnicodeAttribute( hash_key=True )
+ date_created = UTCDateTimeAttribute(
+ default=datetime.utcnow() )
+ aws_region = UnicodeAttribute(default='')
+ branch = UnicodeAttribute(default='master')
+ key_pairs = JSONAttribute(default={})
+ instance_id = UnicodeAttribute(default='')
+ comm_queue = UnicodeAttribute(default='')
+ status = NumberAttribute(default=0)
+
+def to_dict( master_item ):
+ result = {}
+ result['master_name'] = master_item.master_name
+ result['date_created'] = master_item.date_created
+ result['aws_region'] = master_item.aws_region
+ result['key_pairs'] = master_item.key_pairs
+ result['instance_id'] = master_item.instance_id
+ result['comm_queue'] = master_item.comm_queue
+ result['branch'] = master_item.branch
+ result['status'] = master_item.status
+ return result
+
+def get_active_master( branch=None ):
+ masters = get_master()
+ for master in masters:
+ if branch is None or branch == master['branch']:
+ if master['status'] in [INIT, RUN]:
+ if confirm_master_active( master ):
+ return master
+ else:
+ update_master( master['master_name'],
+ status= TERMINATED_WITH_ERROR)
+ return None
+
+def handle_inconsistent_masters():
+ masters = get_master()
+ for master in masters:
+ _handle_inconsistent_master( master)
+
+def _handle_inconsistent_master( master):
+ if master['status'] in [INIT, RUN] and not confirm_master_active(master):
+ logger.error(("Master server with inconsistent status [%r]"
+ ) % ( master ))
+ try:
+ update_master( master['master_name'], status= TERMINATED_WITH_ERROR)
+ logger.error( ("Master server [%s] status changed"
+ " to TERMINATED_WITH_ERROR") % ( master['master_name'] ) )
+ except:
+ logger.exception("Something horrible going on in the db")
+
+
+
+def confirm_master_active(master):
+ try:
+ conn = boto.ec2.connect_to_region( master['aws_region'] )
+ for reservation in conn.get_all_reservations(
+ instance_ids=[master['instance_id']] ):
+ for inst in reservation.instances:
+ if (inst.id, inst.state) == (master['instance_id'], 'running'):
+ return True
+ except AttributeError as ae:
+ logger.exception("Unable to connect to [%s] region." % (
+ master['aws_region'] ))
+ logger.error("Error attempting to confirm [%r]" % ( master ))
+ except boto.exception.EC2ResponseError as ec2e:
+ logger.exception("%s is an invalid instance id in %s region." % (
+ master['instance_id'], master['aws_region'] ))
+ logger.error("Error attempting to confirm [%r]" % ( master ))
+ return False
+
+def get_master( master_name=None):
+ if master_name is None:
+ results = []
+ for item in ANMaster.scan():
+ results.append( to_dict( item ) )
+ return results
+ else:
+ try:
+ print "in get_master"
+ print master_name
+ item = ANMaster.get( master_name )
+ return to_dict( item )
+ except ANMaster.DoesNotExist as dne:
+ return {}
+
+def update_master( master_name,
+ aws_region=None,
+ key_pairs=None,
+ instance_id = None,
+ comm_queue = None,
+ status = None,
+ branch = None,
+ **kwargs):
+
+ item = ANMaster.get( master_name )
+ if aws_region is not None:
+ item.aws_region = aws_region
+ if key_pairs is not None:
+ item.key_pairs = key_pairs
+ if instance_id is not None:
+ item.instance_id = instance_id
+ if comm_queue is not None:
+ item.comm_queue = comm_queue
+ if status is not None:
+ item.status = status
+ if branch is not None:
+ item.branch = branch
+ item.save()
+ return to_dict( item )
+
+def insert_master( master_name,
+ aws_region=None,
+ key_pairs=None,
+ instance_id = None,
+ comm_queue = None,
+ status = None,
+ branch = None,
+ **kwargs):
+
+ item = ANMaster( master_name )
+ if aws_region is not None:
+ item.aws_region = aws_region
+ if key_pairs is not None:
+ item.key_pairs = key_pairs
+ if instance_id is not None:
+ item.instance_id = instance_id
+ if comm_queue is not None:
+ item.comm_queue = comm_queue
+ if status is not None:
+ item.status = status
+ if branch is not None:
+ item.branch = branch
+ item.save()
+ return to_dict( item )
+
+
+if __name__ == "__main__":
+ if not ANMaster.exists():
+ print "creaing aurea-nebula-master"
+ ANMaster.create_table( read_capacity_units=2,
+ write_capacity_units=1, wait=True )
+
diff --git a/pool/shard010/Python/0089242_SPIeeprom.py b/pool/shard010/Python/0089242_SPIeeprom.py
new file mode 100644
index 0000000000000000000000000000000000000000..20ecca6f270ebf65edb7efc5a972dfe96fffa12f
--- /dev/null
+++ b/pool/shard010/Python/0089242_SPIeeprom.py
@@ -0,0 +1,223 @@
+#!/usr/bin/python
+
+# Bus Pirate script for SPI EEPROM read/write
+# Tested on Bus Pirate v3.6
+#
+# Alain Iamburg
+#
+#
+# References:
+# http://dangerousprototypes.com/docs/Bitbang
+# http://dangerousprototypes.com/docs/SPI_(binary)
+
+import argparse, serial, struct, time, sys, os
+
+
+
+def Bin_Enter(usb):
+ entry_bytes = 20
+ success = 0
+
+ while (entry_bytes and not success):
+ usb.write("\x00")
+ entry_bytes = entry_bytes - 1
+ if "BBIO" in usb.read(10): #10
+ success = 1
+
+ return success
+
+
+def Bin_Exit(usb):
+ usb.write("\x00") # Exit Binary Mode
+ usb.write("\x0F") # Reset
+
+
+def SPI_Enter(usb):
+ success = 0
+
+ usb.write("\x01")
+ if "SPI" in usb.read(10):
+ success = 1
+
+ return success
+
+
+def SPI_Setup(usb):
+ success = 1
+
+ usb.write("\x49") # 0100 1001 = Power ON, CS High
+ if "\x00" in usb.read():
+ success = 0
+ usb.write("\x67") # 0110 0011 = 1 MHz 0110 0111 = 8 MHz
+ if "\x00" in usb.read():
+ success = 0
+ usb.write("\x8A") # 1000 1010 = 3.3v, clock idle low,
+ if "\x00" in usb.read(): # clock edge active-to-idle, sample middle
+ success = 0
+
+ return success
+
+
+def EEPROM_Read(usb, addr, readbytes, outfile):
+ success = 0
+
+ # [COMMAND][NUM BYTES TO WRITE][NUM BYTES TO READ][BYTES TO WRITE]
+ # (1byte) (2 bytes) (2 bytes) (0-4096 bytes)
+
+ ## Command ##
+ packet = "\x04" # Write-Then-Read Bus Pirate cmd
+ ## Number of Bytes to Write ##
+ packet += "\x00\x03" # 1-byte EEPROM READ command + 2-byte addr
+ ## Number of Bytes to Read ##
+ packet += struct.pack('>H', readbytes&0xFFFF)
+ ## Bytes to Write ##
+ packet += "\x03" # EEPROM Read command (see datasheet)
+ packet += struct.pack('>H', addr) # 16-bit address
+ usb.write(packet)
+
+ ## Receive Incoming Bytes ##
+ while (usb.inWaiting() == 0):
+ wait = 1
+
+ if "\x01" in usb.read():
+ success = 1
+ data = usb.read(readbytes)
+ if args.x:
+ dump(data, 16, addr)
+
+ outfile.write(data)
+ return success
+
+
+def EEPROM_Write(usb, addr, writebytes, infile):
+ success = 1
+
+ # Bulk SPI Transfer command used to send Write Enable command
+ usb.write("\x02") # 0000 0010 - Bring CS Low
+ if "\x01" != usb.read():
+ success = 0
+ usb.write("\x10") # 0001 0000 = Bulk SPI Transfer 1 byte
+ if "\x01" != usb.read():
+ success = 0
+ usb.write("\x06") # EEPROM Write Enable command
+ usb.read()
+ usb.write("\x03") # 0000 0011 - Bring CS High
+ if "\x01" != usb.read():
+ success = 0
+
+
+ # Write-Then-Read command (takes care of CS transitions) used to write data
+ # [COMMAND][# OF BYTES TO WRITE][# OF BYTES TO READ][BYTES TO WRITE]
+ # (1byte) (2 bytes) (2 bytes) (0-4096 bytes)
+
+ ## Command ##
+ usb.write("\x04") # Write-Then-Read cmd
+ ## Number of Bytes to Write ##
+ usb.write(struct.pack('>H', writebytes+3)) # bytes to write to eeprom + command + address
+ ## Number of Bytes to Read ##
+ usb.write("\x00\x00") # read nothing, we are doing a write operation
+ ## Bytes to Write ##
+ usb.write("\x02") # EEPROM Write command
+ usb.write(struct.pack('>H', addr)) # Address (16 bits))
+ ## Write Bytes to SPI ##
+ for b in range(writebytes):
+ char = infile.read(1)
+ usb.write(char)
+ if "\x01" != usb.read():
+ success = 0
+
+ return success
+
+
+def bail(usb):
+ try:
+ f.close()
+ Bin_Exit(usb)
+ usb.close()
+ sys.exit(1)
+ except:
+ sys.exit(1)
+
+
+# Thanks Stephen Chappell
+# http://code.activestate.com/recipes/576945/
+# modified by Alain Iamburg
+def dump(data, length, addr):
+ hex = lambda line: ' '.join('{:02x}'.format(b) for b in map(ord, line))
+ str = lambda line: ''.join(31 < c < 127 and chr(c) or '.' for c in map(ord, line))
+
+ for i in range(0, len(data), length):
+ line = data[i:i+length]
+ print('{:08x} {:47} {}'.format(addr+i, hex(line), str(line)))
+
+
+
+# Program Start
+
+parser = argparse.ArgumentParser(description="Bus Pirate script for SPI EEPROM read/write.")
+parser.add_argument("bp_interface", help="Bus Pirate serial interface (e.g. /dev/ttyUSB0)")
+#parser.add_argument("addr_len", choices=['16', '24'], help="length of address in bits (check EEPROM datasheet)")
+parser.add_argument("addr", type=int, help="EEPROM address from which to read/write")
+parser.add_argument("mode", choices=['r', 'w'], help="read or write")
+parser.add_argument("numbytes", type=int, help="number of bytes to read or write")
+parser.add_argument("file", help="file from which to read or write")
+parser.add_argument("-x", help="also dump data to screen", action="store_true")
+parser.add_argument("-p", help="enable power from Bus Pirate", action="store_true")
+args = parser.parse_args()
+
+if args.mode == "write" and args.numbytes > 64:
+ print "TODO: Add support to write more than 64 (or 256) bytes at a time.\r\n"
+ sys.exit(1)
+
+
+if not os.access(args.bp_interface, os.W_OK):
+ print "[-] Cannot access interface. Check your permissions.\r\n"
+ sys.exit(1)
+
+try:
+ if args.mode == "r":
+ f = open(args.file, 'ab')
+ elif args.mode == "w":
+ f = open(args.file, 'rb')
+except:
+ print "[-] Could not open {0}\r\n".format(args.file)
+ sys.exit(1)
+
+print "[*] Opening serial port..."
+usb = serial.Serial(args.bp_interface, 115200, timeout=0.1) # default is 8-N-1 #timeout=0.1
+usb.write("#\r\n")
+usb.read(8)
+print usb.read(1024) + "\r\n"
+
+print "[*] Entering Binary Mode...\r"
+if not Bin_Enter(usb):
+ print "[-] Could not enter Binary Mode\r\n"
+ bail(usb)
+
+print "[*] Entering SPI Mode...\r"
+if not SPI_Enter(usb):
+ print "[-] Could not enter SPI Mode\r\n"
+ bail(usb)
+
+print "[*] Setting up SPI...\r"
+if not SPI_Setup(usb):
+ print "[-] Could not set up SPI\r\n"
+ bail(usb)
+
+if args.mode == "r":
+ print "[*] Reading {0} bytes from {1}...\r\n".format(args.numbytes, hex(args.addr))
+ if not EEPROM_Read(usb, args.addr, args.numbytes, f):
+ print "[-] Could not read from EEPROM\r\n"
+ bail(usb)
+ print "\r\n\n[+] Saved to {0}\r\n".format(f.name)
+elif args.mode == "w":
+ print "[*] Writing {0} bytes to {1}...\r\n".format(args.numbytes, hex(args.addr))
+ if not EEPROM_Write(usb, args.addr, args.numbytes, f):
+ print "[-] Could not write to EEPROM\r\n"
+ bail(usb)
+ print "\r\n\n[+] EEPROM written\r\n"
+
+
+f.close()
+Bin_Exit(usb)
+usb.close()
diff --git a/pool/shard010/Python/0089248_cms_menus.py b/pool/shard010/Python/0089248_cms_menus.py
new file mode 100644
index 0000000000000000000000000000000000000000..db8dd8ad29b9c18bd0d7419e84eb553564aeaf2e
--- /dev/null
+++ b/pool/shard010/Python/0089248_cms_menus.py
@@ -0,0 +1,52 @@
+from django.utils.translation import ugettext_lazy as _
+from django.core.urlresolvers import reverse
+
+from menus.base import Modifier, Menu, NavigationNode
+from menus.menu_pool import menu_pool
+from cms.menu_bases import CMSAttachMenu
+
+
+class ProfileMenu(CMSAttachMenu):
+
+ name = _("Profile Menu")
+
+ def get_nodes(self, request):
+ nodes = []
+
+ node = NavigationNode(_("All Users"), reverse("profiles-profile-list"), 110)
+ nodes.append(node)
+
+ if request.user.is_active:
+ node = NavigationNode(
+ _("My Profile"),
+ reverse(
+ "profiles-profile-detail",
+ kwargs={"uuid": str(request.user.profile.uuid)},
+ ),
+ 111,
+ )
+ nodes.append(node)
+
+ node = NavigationNode(
+ _("Edit my Profile"),
+ # reverse("profiles-profile-edit"),
+ reverse(
+ "profiles-profile-edit",
+ kwargs={"uuid": str(request.user.profile.uuid)},
+ ),
+ 121,
+ )
+
+ nodes.append(node)
+
+ if request.user.has_perm("invitation.change_invitation"):
+
+ node = NavigationNode(
+ _("My Invitations"), reverse("profiles-invitations"), 123
+ )
+ nodes.append(node)
+
+ return nodes
+
+
+menu_pool.register_menu(ProfileMenu)
diff --git a/pool/shard010/Python/0089250_plottools.py b/pool/shard010/Python/0089250_plottools.py
new file mode 100644
index 0000000000000000000000000000000000000000..04eb4d9c1e781c7b901386ce5a8b086963ad9df5
--- /dev/null
+++ b/pool/shard010/Python/0089250_plottools.py
@@ -0,0 +1,249 @@
+# plottools.py
+"""
+Collection of classes to help create plots.
+"""
+import matplotlib.pyplot as plt
+
+
+class Plot(object):
+ """
+ Base class for a plot.
+
+ :param title: Plot title. Optional.
+ :type title: str
+ """
+ def __init__(self, title=None):
+ self.fig = plt.figure()
+ self.axplot = self.fig.add_subplot(1, 1, 1)
+ for item in [self.fig, self.axplot]:
+ item.patch.set_visible(False)
+ if title is not None:
+ self.set_title(title)
+
+ def set_title(self, title):
+ """
+ Add a title to the plot.
+
+ :param title: Title to assign to the plot.
+ :type title: str
+ """
+ self.axplot.set_title(title)
+
+ def set_axis_label(self, label, axis):
+ """
+ Add an axis label to the plot.
+
+ :param label: Label to assign to axis.
+ :type label: str
+ :param axis: Name of the axis, x or y
+ :type axis: str
+ """
+ if axis == 'x':
+ self.axplot.set_xlabel(label)
+ elif axis == 'y':
+ self.axplot.set_ylabel(label)
+ else:
+ errmsg = 'Valid axis names are x and y.'
+ raise ValueError(errmsg)
+
+
+class SpPlot(Plot):
+ """
+ Class to create and customize a spectrum plot. Subclasses Plot.
+
+ :param title: Title to assign to the plot.
+ :type title: str
+ """
+ def __init__(self, title=None):
+ Plot.__init__(self, title)
+
+ def plot_spectrum(self, sp1d, title=None, color='k'):
+ """
+ Plot the spectrum (counts vs wavelength) with title and axis labels.
+
+ :param sp1d: A Spectrum instance.
+ :type sp1d: Spectrum object.
+ :param title: Title for the plot. Optional.
+ :type title: str
+ :param color: Colour of the line
+ :type color: str
+ """
+ if title is not None:
+ self.set_title(title)
+ self.set_axis_label(''.join(['Wavelength [', sp1d.wunit.name, ']']),
+ 'x')
+ self.set_axis_label('Counts', 'y')
+ self.axplot.plot(sp1d.wlen, sp1d.counts, color)
+ self.axplot.axis('tight')
+ self.fig.canvas.draw()
+ return
+
+ def adjust_ylimits(self, ylim1, ylim2):
+ """
+ Adjust the lower and upper bounds to the y-axis.
+
+ :param ylim1: Lower limit for the y-axis.
+ :type ylim1: float
+ :param ylim2: Upper limit for the y-axis.
+ :type ylim2: float
+ """
+ self.axplot.set_ylim(ylim1, ylim2)
+ self.fig.canvas.draw()
+ return
+
+ def erase_plot(self, line_position=0):
+ """
+ Erase the spectrum but not the box and axes.
+
+ :param line_position: Position on the stack of the spectrum to
+ erase.
+ :type line_position: int
+ """
+ self.axplot.lines.pop(line_position).remove
+ self.fig.canvas.draw()
+ return
+
+ def annotate_lines(self, lines):
+ """
+ Annotate the plot with spectra line identifications.
+
+ :param lines: The line list to add to the plot. The lines are stored
+ in a list of tuples with (obswlen, name), where obswlen is a float
+ and name is a string.
+ :type lines: list of tuples
+ """
+ # lines is list of tuple (obswlen, name)
+ (xlow, xhigh) = self.axplot.get_xlim()
+ (_, yhigh) = self.axplot.get_ylim()
+ ypos = yhigh * 0.8
+ ydelta = yhigh * 0.05
+ i = 0
+ for line in lines:
+ if xlow < line[0] < xhigh:
+ self.axplot.text(line[0], ypos-(i*ydelta)-ydelta*1.25, '|',
+ horizontalalignment='center',
+ verticalalignment='center', fontsize=10)
+ self.axplot.text(line[0], ypos-(i*ydelta), line[1],
+ horizontalalignment='center',
+ verticalalignment='center', fontsize=10)
+ i += 1
+ self.fig.canvas.draw()
+
+ return
+
+ # def draw_band_limits(self):
+ # return
+
+ def write_png(self, output_name):
+ """
+ Write the figure to a PNG file.
+
+ :param output_name: Name of the output file.
+ ??Is the extension .png required or is it added automatically??
+ :type output_name: str
+ """
+ self.fig.savefig(output_name)
+ return
+
+
+class MultiPlot(object):
+ def __init__(self, nrows=1, ncols=1, title=None):
+ self.nrows = nrows
+ self.ncols = ncols
+ if title is not None:
+ self.title = title
+ self.plots_titles = None
+ self.plots_labels = None
+ self.plots_data = None
+ self.pdf = None
+
+ def add_data(self, plots_data, plots_labels=None):
+ """
+
+ Parameters
+ ----------
+ plot_data : list of tuple
+ tuples of x and y data, one tuple per plot
+
+ """
+ self.plots_data = plots_data
+ if plots_labels is not None:
+ self.add_labels(plots_labels)
+
+ def add_labels(self, plots_labels):
+ self.plots_labels = plots_labels
+
+ def add_titles(self, plots_titles):
+ self.plots_titles = plots_titles
+
+ def set_size(self, width, height):
+ self.width = width
+ self.height = height
+
+ def plot(self, png=False, filename='multiplot.png', pdf=None):
+ self.fig, self.axs = plt.subplots(self.nrows, self.ncols)
+ self.fig.suptitle(self.title)
+ self.fig.set_size_inches(self.width, self.height)
+
+ nplots = len(self.plots_data)
+ plotid = 0
+ for axrow in self.axs:
+ for ax in axrow:
+ xlabel = None
+ ylabel = None
+ title = None
+
+ if plotid == nplots:
+ break # fewer plots then slots
+
+ x = self.plots_data[plotid][0]
+ y = self.plots_data[plotid][1]
+ if len(self.plots_labels) == 1:
+ xlabel = self.plots_labels[0][0]
+ ylabel = self.plots_labels[0][1]
+ elif self.plots_labels is not None:
+ xlabel = self.plots_labels[plotid][0]
+ ylabel = self.plots_labels[plotid][1]
+ if self.plots_titles is not None:
+ title = self.plots_titles[plotid]
+
+ ax.plot(x, y)
+ ax.set_title(title)
+ ax.set(xlabel=xlabel, ylabel=ylabel)
+ plotid += 1
+
+ self.fig.tight_layout(rect=[0, 0.03, 1, 0.95])
+
+ if pdf:
+ pdf.savefig()
+
+ if png:
+ plt.savefig(filename)
+ else:
+ plt.show()
+
+ def save_plot(self, filename='multiplot.png'):
+ self.plot(save=True, filename=filename)
+
+ def close(self):
+ plt.close()
+
+
+
+
+"""
+import plottools
+from importlib import reload
+import numpy as np
+
+x = np.linspace(0, 2 * np.pi, 400)
+y = np.sin(x ** 2)
+
+m = plottools.MultiPlot(2,2,'test')
+plot_data = [(x,y), (x,-y), (-x, y), (-x, -y)]
+plot_labels = [('x axis', 'y axis'),('x axis', '-y axis'),('-x axis', 'y axis'),('-x axis', '-y axis')]
+
+m.add_data(plot_data, plot_labels)
+m.plot()
+
+"""
\ No newline at end of file
diff --git a/pool/shard010/Python/0089251_test_app.py b/pool/shard010/Python/0089251_test_app.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdd0bd227dfe2820f19a8403953fa0860992dcf9
--- /dev/null
+++ b/pool/shard010/Python/0089251_test_app.py
@@ -0,0 +1,218 @@
+from pyswagger import App, errs, utils
+from ..utils import get_test_data_folder
+from pyswagger.spec.v2_0.objects import (
+ Schema,
+ Operation,
+)
+import unittest
+import httpretty
+import os
+import six
+
+
+class HTTPGetterTestCase(unittest.TestCase):
+ """ test HTTPGetter """
+
+ @httpretty.activate
+ def test_http_getter(self):
+ """ make sure HTTPGetter works """
+
+ folder = get_test_data_folder(version='1.2', which='wordnik')
+ resource_list = user = pet = store = None
+
+ with open(os.path.join(folder, 'resource_list.json')) as f:
+ resource_list = f.read()
+
+ with open(os.path.join(folder, 'user.json')) as f:
+ user = f.read()
+
+ with open(os.path.join(folder, 'pet.json')) as f:
+ pet = f.read()
+
+ with open(os.path.join(folder, 'store.json')) as f:
+ store = f.read()
+
+ httpretty.register_uri(
+ httpretty.GET, 'http://petstore.swagger.wordnik.com/api/api-docs',
+ status=200,
+ body=resource_list
+ )
+
+ httpretty.register_uri(
+ httpretty.GET, 'http://petstore.swagger.wordnik.com/api/api-docs/user',
+ status=200,
+ body=user
+ )
+
+ httpretty.register_uri(
+ httpretty.GET, 'http://petstore.swagger.wordnik.com/api/api-docs/pet',
+ status=200,
+ body=pet
+ )
+
+ httpretty.register_uri(
+ httpretty.GET, 'http://petstore.swagger.wordnik.com/api/api-docs/store',
+ status=200,
+ body=store
+ )
+
+ local_app = App._create_('http://petstore.swagger.wordnik.com/api/api-docs')
+
+ self.assertEqual(sorted(local_app.raw._field_names_), sorted(['info', 'authorizations', 'apiVersion', 'swaggerVersion', 'apis']))
+
+ op = local_app.raw.apis['pet'].apis['updatePet']
+ self.assertEqual(sorted(op._field_names_), sorted([
+ 'authorizations',
+ 'consumes',
+ 'defaultValue',
+ 'deprecated',
+ 'enum',
+ 'format',
+ 'items',
+ 'maximum',
+ 'method',
+ 'minimum',
+ 'nickname',
+ 'parameters',
+ 'produces',
+ '$ref',
+ 'responseMessages',
+ 'type',
+ 'uniqueItems',
+ 'summary',
+ 'notes'
+ ]))
+
+
+class ValidationTestCase(unittest.TestCase):
+ """ test case for validation """
+
+ def setUp(self):
+ self.app = App.load(get_test_data_folder(version='1.2', which='err'))
+
+ def test_errs(self):
+ """
+ """
+ errs = self.app.validate(strict=False)
+ self.maxDiff = None
+ self.assertEqual(sorted(errs), sorted([
+ (('#/info', 'Info'), 'requirement description not meet.'),
+ (('#/info', 'Info'), 'requirement title not meet.'),
+ (('#/authorizations/oauth2', 'Authorization'), 'requirement type not meet.'),
+ (('#/authorizations/oauth2/grantTypes/implicit/loginEndpoint', 'LoginEndpoint'), 'requirement url not meet.'),
+ (('#/authorizations/oauth2/scopes/0', 'Scope'), 'requirement scope not meet.'),
+ (('#/authorizations/oauth2/grantTypes/authorization_code/tokenRequestEndpoint', 'TokenRequestEndpoint'), 'requirement url not meet.'),
+ (('#/apis/pet/apis/getPetById', 'Operation'), 'requirement method not meet.'),
+ (('#/apis/pet/apis/getPetById/parameters/0', 'Parameter'), 'requirement name not meet.'),
+ (('#/apis/pet/apis/getPetById/responseMessages/0', 'ResponseMessage'), 'requirement code not meet.'),
+ (('#/apis/pet/apis', 'Operation'), 'requirement nickname not meet.'),
+ (('#/apis/pet/models/Pet/properties/tags', 'Property'), 'array should be existed along with items'),
+ (('#/apis/pet/apis/getPetById/parameters/0', 'Parameter'), 'allowMultiple should be applied on path, header, or query parameters'),
+ (('#/apis/pet/apis/partialUpdate/parameters/1', 'Parameter'), 'body parameter with invalid name: qqq'),
+ (('#/apis/pet/apis/partialUpdate/parameters/0', 'Parameter'), 'void is only allowed in Operation object.')
+ ]))
+
+ def test_raise_exception(self):
+ """ raise exceptions in strict mode """
+ self.assertRaises(errs.ValidationError, self.app.validate)
+
+
+class AppTestCase(unittest.TestCase):
+ """ test case for App """
+
+ def setUp(self):
+ folder = get_test_data_folder(
+ version='1.2',
+ )
+
+ def _hook(url):
+ # a demo of hooking a remote url to local path
+ p = six.moves.urllib.parse.urlparse(url)
+ return utils.normalize_url(os.path.join(folder, p.path[1:]))
+
+ self.app = App.load('http://petstore.io/wordnik', url_load_hook=_hook)
+ self.app.prepare()
+
+ def test_url(self):
+ """ make sure url is not touched by hook """
+ req, _ = self.app.op['getUserByName'](username='Tom')
+ req.prepare()
+ self.assertEqual(req.url, 'http://petstore.swagger.wordnik.com/api/user/Tom')
+
+ def test_ref(self):
+ """ test ref function """
+ self.assertRaises(ValueError, self.app.resolve, None)
+ self.assertRaises(ValueError, self.app.resolve, '')
+
+ self.assertTrue(isinstance(self.app.resolve('#/definitions/user!##!User'), Schema))
+ self.assertTrue(isinstance(self.app.resolve('#/paths/~1api~1user~1{username}/put'), Operation))
+ self.assertEqual(self.app.resolve('#/paths/~1api~1store~1order/post/produces'), ['application/json'])
+ self.assertEqual(self.app.resolve('#/host'), 'petstore.swagger.wordnik.com')
+
+ # resolve with URL part
+ # refer to
+ # http://stackoverflow.com/questions/10246116/python-dereferencing-weakproxy
+ # for how to dereferencing weakref
+ self.assertEqual(
+ self.app.resolve('#/definitions/user!##!User').__repr__(),
+ self.app.resolve('http://petstore.io/wordnik#/definitions/user!##!User').__repr__()
+ )
+ self.assertEqual(
+ self.app.resolve('#/paths/~1api~1user~1{username}/put').__repr__(),
+ self.app.resolve('http://petstore.io/wordnik#/paths/~1api~1user~1{username}/put').__repr__()
+ )
+
+ def test_scope_dict(self):
+ """ ScopeDict is a syntactic suger
+ to access scoped named object, ex. Operation, Model
+ """
+ # Operation
+ self.assertTrue(self.app.op['user', 'getUserByName'], Operation)
+ self.assertTrue(self.app.op['user', 'getUserByName'] is self.app.op['user!##!getUserByName'])
+ self.assertTrue(self.app.op['getUserByName'] is self.app.op['user!##!getUserByName'])
+
+ def test_shortcut(self):
+ """ a short cut to Resource, Operation, Model from App """
+ # Resource
+ # TODO: resource is now replaced by tags
+ #self.assertTrue(isinstance(app.rs['pet'], Resource))
+ #self.assertTrue(isinstance(app.rs['user'], Resource))
+ #self.assertTrue(isinstance(app.rs['store'], Resource))
+
+ # Operation
+ self.assertEqual(len(self.app.op.values()), 20)
+ self.assertEqual(sorted(self.app.op.keys()), sorted([
+ 'pet!##!addPet',
+ 'pet!##!deletePet',
+ 'pet!##!findPetsByStatus',
+ 'pet!##!findPetsByTags',
+ 'pet!##!getPetById',
+ 'pet!##!partialUpdate',
+ 'pet!##!updatePet',
+ 'pet!##!updatePetWithForm',
+ 'pet!##!uploadFile',
+ 'store!##!deleteOrder',
+ 'store!##!getOrderById',
+ 'store!##!placeOrder',
+ 'user!##!createUser',
+ 'user!##!createUsersWithArrayInput',
+ 'user!##!createUsersWithListInput',
+ 'user!##!deleteUser',
+ 'user!##!getUserByName',
+ 'user!##!loginUser',
+ 'user!##!logoutUser',
+ 'user!##!updateUser'
+ ]))
+ self.assertTrue(self.app.op['user!##!getUserByName'], Operation)
+
+ # Model
+ d = self.app.resolve('#/definitions')
+ self.assertEqual(len(d.values()), 5)
+ self.assertEqual(sorted(d.keys()), sorted([
+ 'pet!##!Category',
+ 'pet!##!Pet',
+ 'pet!##!Tag',
+ 'store!##!Order',
+ 'user!##!User'
+ ]))
+
diff --git a/pool/shard010/Python/0089252_exif.py b/pool/shard010/Python/0089252_exif.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff1fac7c3ef27670eda7a6a9ef8db9ceb1a65414
--- /dev/null
+++ b/pool/shard010/Python/0089252_exif.py
@@ -0,0 +1,160 @@
+"""
+Contains functionality for analyzing the exif data of an image.
+"""
+
+from __future__ import division
+
+import math
+import exifread
+
+
+def analyze_background_blur(tags):
+ """Calculates and returns an estimated hyperfocal distance that tells
+ how far an object must be to be in focus. Values near zero mean
+ hyperfocal distance is so low, that most likely everything in the
+ picture is sharp. Values near 1 mean that all the objects has to be
+ hundreds of meters away to be in focus.
+
+ :param tags: the exif tags
+ :type tags: dict
+ :returns: float -- the estimated hyperfocal distance, None if not able
+ to calculate the value due to missing EXIF value
+ """
+ if tags and "EXIF FocalLength" in tags:
+ if "EXIF FNumber" in tags:
+ aperture = eval(str(tags["EXIF FNumber"]))
+ elif "EXIF ApertureValue" in tags:
+ aperture = eval(str(tags["EXIF ApertureValue"]))
+ else:
+ return None
+
+ focal = eval(str(tags["EXIF FocalLength"]))
+ return get_background_blur_ratio(focal, aperture)
+
+ return None
+
+
+def analyze_picture_exposure(tags):
+ """Parses exif from given image and returns a float between 0 and 1,
+ where values closer to 0 indicate low motion blur probability and
+ values closer to 1 indicate high motion-blur probability.
+
+ :param tags: the exif tags
+ :type tags: dict
+ :returns: float -- the estimated motion blur probability, None if not
+ able to calculate the value due to missing EXIF value
+ """
+ if tags and "EXIF ExposureTime" in tags:
+ exposure = tags["EXIF ExposureTime"]
+ exposure = eval(str(exposure))
+ return get_exposure_ratio(exposure)
+ return None
+
+
+def get_exposure_value(tags):
+ """Extracts exposure value from given tags
+ """
+ if tags and "EXIF ExposureTime" in tags:
+ exposure = tags["EXIF ExposureTime"]
+ exposure = eval(str(exposure))
+ return exposure
+ return None
+
+
+def get_focal_value(tags):
+ """Extracts focal length value from given tags
+ """
+ if tags and "EXIF FocalLength" in tags:
+ return eval(str(tags["EXIF FocalLength"]))
+ return None
+
+
+def get_iso_value(tags):
+ """Extracts ISO value from given tags
+ """
+ if tags and "EXIF ISOSpeedRatings" in tags:
+ iso = tags["EXIF ISOSpeedRatings"]
+ iso = eval(str(iso))
+ return iso
+ return None
+
+
+def get_aperture_value(tags):
+ """Extracts aperture values from given tags if focal
+ length also exists
+ """
+ if tags and "EXIF FocalLength" in tags:
+ if "EXIF FNumber" in tags:
+ return eval(str(tags["EXIF FNumber"]))
+ elif "EXIF ApertureValue" in tags:
+ return eval(str(tags["EXIF ApertureValue"]))
+ else:
+ return None
+ return None
+
+
+def get_background_blur_ratio(focal, aperture):
+ """Calculates hyperfocal length from given focal and aperture values
+ and returns an estimation on how likely the background is blurred
+ """
+ if aperture < 0.001:
+ return None
+
+ # circle of confusion size
+ coc = 0.015
+
+ # hyperfocal calculation
+ hyperfocal = focal ** 2 / (aperture * coc) + focal
+
+ # hyperfocal thresholds in millimeters
+ min_threshold = 200
+ max_threshold = 100000
+
+ # normalize:
+ hyperfocal = math.log(hyperfocal, 2)
+ min_threshold = math.log(min_threshold, 2)
+ max_threshold = math.log(max_threshold, 2)
+
+ hyperfocal = (hyperfocal - min_threshold) / (max_threshold - min_threshold)
+
+ if hyperfocal < 0:
+ return 0.0
+ if hyperfocal > 1:
+ return 1.0
+
+ return hyperfocal
+
+
+def get_exposure_ratio(exposure):
+ """Calculates the probability of motion blur in an image using
+ the given exposure time. Exposure of over 1/4 seconds is most likely
+ to be motion blurred.
+ """
+ # min and max exposure threshold values
+ min_exposure = 1 / 2000
+ max_exposure = 1 / 4
+
+ # normalize
+ exposure = math.log(exposure, 2)
+ min_exposure = math.log(min_exposure, 2)
+ max_exposure = math.log(max_exposure, 2)
+
+ exposure = (exposure - min_exposure) / (max_exposure - min_exposure)
+
+ if exposure < 0:
+ return 0.0
+ if exposure > 1:
+ return 1.0
+
+ return exposure
+
+
+def parse_exif(image_path):
+ """Parses the exif tags from an image
+
+ :param image_path: path to the image file
+ :type image_path: str
+ :returns: dict -- the exif tags
+ """
+ with open(image_path, 'rb') as image:
+ return exifread.process_file(image, details=False)
diff --git a/pool/shard010/Python/0089254_welcome.py b/pool/shard010/Python/0089254_welcome.py
new file mode 100644
index 0000000000000000000000000000000000000000..f60945a275fbed80cdf8e0df79a1fd1223d6da6f
--- /dev/null
+++ b/pool/shard010/Python/0089254_welcome.py
@@ -0,0 +1,120 @@
+# -*- coding: utf-8 -*-
+
+"""
+The MIT License (MIT)
+
+Copyright (c) 2017 Dino#0631 (discord)
+
+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.
+"""
+import itertools
+import discord
+from discord.ext import commands
+from discord.ext.commands import Context
+import cogs
+from cogs.utils.chat_formatting import pagify
+from cogs.utils import checks
+from random import choice
+import aiohttp
+from __main__ import send_cmd_help
+import os
+from cogs.utils.dataIO import dataIO
+
+PATH = os.path.join('data', 'welcome')
+WELCOMEJSON = os.path.join(PATH, 'settings.json')
+class Welcome:
+ """Display RACF specifc info.
+
+ Note: RACF specific plugin for Red
+ """
+
+ def __init__(self, bot):
+ """Constructor."""
+ self.bot = bot
+ self.settings = dataIO.load_json(WELCOMEJSON)
+
+ @checks.mod_or_permissions()
+ @commands.group(aliases=['wel'],pass_context=True)
+ async def welcome(self, ctx):
+
+ if ctx.invoked_subcommand is None:
+ await send_cmd_help(ctx)
+
+ @welcome.command(aliases=['chan'], pass_context=True)
+ async def setchan(self, ctx, channel:discord.Channel=None, *, welmsg:str=r'"Welcome to "+server.name+", "+member.name+"!"'):
+ server = ctx.message.server
+ if channel == None:
+ channel = ctx.message.channel
+ try:
+ test = self.settings[server.id]
+ except KeyError:
+ self.settings[server.id] = {}
+ self.settings[server.id]['channel'] = channel.id
+ self.settings[server.id]['message'] = welmsg
+ dataIO.save_json(WELCOMEJSON, self.settings)
+ await self.bot.say('Set welcome channel to: {}'.format(channel.mention))
+
+ @welcome.command(aliases=['msg'], pass_context=True)
+ async def setmessage(self, ctx, *, message):
+ '''write `server` to imply the server name and
+ `member` to imply the member being welcomed'''
+ server = ctx.message.server
+ channel = ctx.message.channel
+ print(self.settings)
+ message = '\"' + message + '\"'
+ message = message.replace('`server`', r'"+server.name+"').replace('`member`', r'"+member.name+"')
+ self.settings[server.id]['message'] = message
+ dataIO.save_json(WELCOMEJSON, self.settings)
+ await self.bot.say('Set welcome msg to: ```{}```'.format(message))
+
+
+ @welcome.command(aliases=['del'], pass_context=True)
+ async def delserv(self, ctx):
+ server = ctx.message.server
+ self.settings.pop(server.id, None)
+ dataIO.save_json(WELCOMEJSON, self.settings)
+ await self.bot.say('Deleted welcome channel settings for this server')
+
+ @checks.is_owner()
+ @welcome.command(pass_context=True)
+ async def sendjson(self, ctx):
+ heroku = False
+ if 'DYNO_RAM' in os.environ:
+ heroku = True
+ if heroku:
+ await self.bot.send_file(destination=ctx.message.channel, fp=r"/app/data/welcome/settings.json", filename="welcome.json")
+ else:
+ await self.bot.send_file(destination=ctx.message.channel, fp=r"data\welcome\settings.json", filename="welcome.json")
+
+
+
+def check_folder():
+ if not os.path.exists(PATH):
+ os.makedirs(PATH)
+
+def check_file():
+ defaults = {}
+ if not dataIO.is_valid_json(WELCOMEJSON):
+ dataIO.save_json(WELCOMEJSON, defaults)
+
+def setup(bot):
+ check_folder()
+ check_file()
+ r = Welcome(bot)
+ bot.add_cog(r)
\ No newline at end of file
diff --git a/pool/shard010/Python/0089256_unites.py b/pool/shard010/Python/0089256_unites.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ac1878dc8d015ef86149e50c5cb5413184c662e
--- /dev/null
+++ b/pool/shard010/Python/0089256_unites.py
@@ -0,0 +1,133 @@
+#!/usr/bin/env python
+# encoding: utf-8
+# Carlos Rafael Giani, 2006
+# Thomas Nagy, 2010
+# Bernhard Schuster, 2014-2016
+
+"""
+Unit testing system for C/C++/D providing test execution:
+
+* in parallel, by using ``waf -j``
+* partial (only the tests that have changed) or full (by using ``waf``)
+
+The tests are declared by adding the **test** feature to programs::
+
+ def options(opt):
+ opt.load('compiler_c unites')
+ def configure(conf):
+ conf.load('compiler_c unites')
+ def build(bld):
+ bld(features='c cprogram unites', source='main.cpp', target='app')
+ # or
+ bld.program(features='unites', source='main2.cpp', target='app2')
+
+When the build is executed, the program 'test' will be built and executed without arguments.
+The success/failure is detected by looking at the return code. The status and the standard output/error
+are stored on the build context.
+"""
+
+import os, sys
+from waflib.TaskGen import feature, after_method
+from waflib import Utils, Task, Logs, Options, Errors, Context
+
+@feature('unites')
+@after_method('apply_link')
+def make_test(self):
+ """Create the unit test task. There can be only one unit test task per task generator."""
+ if getattr(self, 'link_task', None):
+ self.create_task('unites', self.link_task.outputs)
+
+
+class unites(Task.Task):
+ """
+ Execute a unit test
+ """
+ color = 'PINK'
+ after = ['vnum','inst']
+ vars = []
+ def runnable_status(self):
+ """
+ Always execute the task if ``waf --no-tests`` was not used
+ """
+ if getattr(Options.options, 'no_tests', False):
+ return Task.SKIP_ME
+
+ ret = super(unites, self).runnable_status()
+ if ret == Task.SKIP_ME:
+ return Task.RUN_ME
+ return ret
+
+ def run(self):
+ """
+ Execute the test. This can fail.
+ """
+
+ testname = str(self.inputs[0])
+ filename = self.inputs[0].abspath()
+
+
+
+ self.ut_exec = getattr(self.generator, 'ut_exec', [filename])
+
+ try:
+ fu = getattr(self.generator.bld, 'all_test_paths')
+ except AttributeError:
+ # this operation may be performed by at most #maxjobs
+ fu = os.environ.copy()
+
+ lst = []
+ for g in self.generator.bld.groups:
+ for tg in g:
+ if getattr(tg, 'link_task', None):
+ s = tg.link_task.outputs[0].parent.abspath()
+ if s not in lst:
+ lst.append(s)
+
+ def add_path(dct, path, var):
+ dct[var] = os.pathsep.join(Utils.to_list(path) + [os.environ.get(var, '')])
+
+ if Utils.is_win32:
+ add_path(fu, lst, 'PATH')
+ elif Utils.unversioned_sys_platform() == 'darwin':
+ add_path(fu, lst, 'DYLD_LIBRARY_PATH')
+ add_path(fu, lst, 'LD_LIBRARY_PATH')
+ else:
+ add_path(fu, lst, 'LD_LIBRARY_PATH')
+ self.generator.bld.all_test_paths = fu
+
+ cwd = getattr(self.generator, 'ut_cwd', '') or self.inputs[0].parent.abspath()
+ testcmd = getattr(Options.options, 'testcmd', False)
+
+ if testcmd:
+ self.ut_exec = (testcmd % self.ut_exec[0]).split(' ')
+
+ #overwrite the default logger to prevent duplicate logging
+ proc = Utils.subprocess.Popen(self.ut_exec,\
+ cwd=cwd,\
+ env=fu,\
+ stderr=Utils.subprocess.PIPE,\
+ stdout=Utils.subprocess.PIPE)
+
+ (out, err) = proc.communicate()
+
+ msg = []
+ if out:
+ msg.append('stdout:%s%s' % (os.linesep, out.decode('utf-8')))
+ if err:
+ msg.append('stderr:%s%s' % (os.linesep, err.decode('utf-8')))
+ msg = os.linesep.join(msg)
+ Logs.debug(msg)
+
+ return proc.returncode
+
+
+def options(opt):
+ """
+ Provide the ``permissive``, ``--notests`` and ``--testcmd`` command-line options.
+ """
+ opt.add_option('--permissive-tests', action='store_true', default=False, help='Do not force exit if tests fail', dest='permissive_tests')
+ opt.add_option('--no-tests', action='store_true', default=False, help='Exec no unit tests', dest='no_tests')
+ opt.add_option('--testcmd', action='store', default=False,
+ help = 'Run the unit tests using the test-cmd string'
+ ' example "--test-cmd="valgrind --error-exitcode=1'
+ ' %s" to run under valgrind', dest='testcmd')
diff --git a/pool/shard010/Python/0089265_s4.py b/pool/shard010/Python/0089265_s4.py
new file mode 100644
index 0000000000000000000000000000000000000000..6df9e741cace535351b59e7df8879c766bf451b5
--- /dev/null
+++ b/pool/shard010/Python/0089265_s4.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# Author: Janice Cheng
+
+import socket
+
+ip_port = ('127.0.0.1',8080,)
+
+s=socket.socket()
+s.bind(ip_port)
+s.listen(5)
+while True:
+ conn, addr = s.accept()
+ conn.sendall(bytes('hello',encoding='utf-8'))
+
+ while True:
+ recv_bytes = conn.recv(1024)
+ if str(recv_bytes,encoding='utf-8') == 'q':
+ break
+
+ conn.sendall(recv_bytes)
+
+
+s.close()
\ No newline at end of file
diff --git a/pool/shard010/Python/0089267_init__.py b/pool/shard010/Python/0089267_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d50240a12d4ddfe2af4a352dcc3b069a87821262
--- /dev/null
+++ b/pool/shard010/Python/0089267_init__.py
@@ -0,0 +1,35 @@
+from flask import Flask
+from flask_sqlalchemy import SQLAlchemy
+from config import config
+from flask_apscheduler import APScheduler
+import os
+
+basedir = os.path.abspath(os.path.dirname(__file__))
+
+db = SQLAlchemy()
+
+def create_app(config_name):
+ app = Flask(__name__)
+ app.config.from_object(config[config_name])
+ config[config_name].init_app(app)
+ db.init_app(app)
+ db.app = app
+
+ # APScheduler
+ scheduler = APScheduler()
+ scheduler.init_app(app)
+ scheduler.start()
+
+ # Register Blueprint
+ # main blueprint : api and db operation
+ from .main import main as main_blueprint
+ app.register_blueprint(main_blueprint)
+
+ # spider blueprint : spider script for wanted blog
+ from .spider import spider as spider_blueprint
+ app.register_blueprint(spider_blueprint)
+
+ with app.app_context():
+ db.create_all()
+
+ return app
\ No newline at end of file
diff --git a/pool/shard010/Python/0089275_92.py b/pool/shard010/Python/0089275_92.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f4d10515afebfdb809867a6c624d8678ff8f131
--- /dev/null
+++ b/pool/shard010/Python/0089275_92.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python
+
+"""This script solves the Project Euler problem "Square digit chains". The
+problem is: How many starting numbers below ten million will arrive at 89?
+"""
+
+
+def main():
+ """Square digit chains"""
+
+ # Constants
+ MAX = 10000000
+
+ count = 0
+
+ cache = {
+ '1': 1,
+ '89': 89,
+ }
+
+ for num in range(2, MAX):
+ chain = []
+ final = None
+ n = ''.join(sorted(digit for digit in str(num)))
+ while (True):
+ if n in cache:
+ final = cache[n]
+ break
+ chain.append(n)
+ n = str(sum(int(digit) * int(digit) for digit in str(n)))
+ if final == 89:
+ count += 1
+ for n in chain:
+ cache[n] = final
+
+ print(count)
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard010/Python/0089277_urls.py b/pool/shard010/Python/0089277_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..919c226260527768d788092e47e4109fd1da1235
--- /dev/null
+++ b/pool/shard010/Python/0089277_urls.py
@@ -0,0 +1,23 @@
+from django.conf.urls import patterns, include, url
+
+# Uncomment the next two lines to enable the admin:
+# from django.contrib import admin
+# admin.autodiscover()
+
+urlpatterns = patterns('dropbox_api.views',
+ # Examples:
+ # url(r'^$', 'dropbox_api.views.home', name='home'),
+ # url(r'^dropbox_api/', include('dropbox_api.foo.urls')),
+
+ # Uncomment the admin/doc line below to enable admin documentation:
+ # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
+
+ url(r'^$', 'start', name="start"),
+ url(r'^dropin-chooser/$', 'dropin_chooser', name="dropin_chooser"),
+ url(r'^dropin-saver/$', 'dropin_saver', name="dropin_saver"),
+ url(r'^datastore-js/$', 'datastore_js', name="datastore_js"),
+ url(r'^datastore-python/$', 'datastore_python', name="datastore_python"),
+
+ # Uncomment the next line to enable the admin:
+ # url(r'^admin/', include(admin.site.urls)),
+)
diff --git a/pool/shard010/Python/0089280_order.py b/pool/shard010/Python/0089280_order.py
new file mode 100644
index 0000000000000000000000000000000000000000..500a0021f6c9a35b90a47f94d541121d19f24f2e
--- /dev/null
+++ b/pool/shard010/Python/0089280_order.py
@@ -0,0 +1,61 @@
+"""Flow - Algorithmic HF trader
+
+ Copyright 2016, Yazan Obeidi
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+"""
+
+__author__ = 'matthew/yazan'
+
+BUY = 'buy'
+SELL = 'sell'
+OPEN = 'open'
+ACTIONS = [1, -1, 0] # BUY, SELL, DO_NOTHING
+
+#action: buy/sell
+class Order(object):
+ """
+ This class defines a single order and records details to bankroll and log.
+ """
+ def __init__(self, scope, bankroll, log=None):
+ self.bankroll = bankroll
+ self.log = log
+ self.scope = scope
+ self.open_cost = float()
+ self.close_profit = float()
+ self.profit = float()
+
+ def open_order(self, action, quote, volume):
+ self.action = action
+ self.volume = volume
+ self.open_cost = quote*volume
+ self.bankroll.transaction(-self.open_cost)
+ self.logger.info('{volume} {action} opened by {agent} in {scope}.'\
+ .format(action=action, volume=volume,
+ agent=self, scope=self.scope))
+
+ def close_order(self, action, quote):
+ self.close_profit = quote*self.volume
+ self.bankroll.transaction(self.close_profit)
+ self.profit = self.close_profit - self.open_cost
+ self.logger.info('{volume} {action} closed by {agent} in {scope}. '\
+ 'Profit = ${profit}.'.format(action=action, agent=self,
+ volume=self.volume, scope=self.scope, profit=self.profit))
+ def get_profit(self):
+ return self.profit
+
+
+
+
+
+
diff --git a/pool/shard010/Python/0089281_migration_simplified_db.py b/pool/shard010/Python/0089281_migration_simplified_db.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb971f1823443c731715fdd50917378acebe9f54
--- /dev/null
+++ b/pool/shard010/Python/0089281_migration_simplified_db.py
@@ -0,0 +1,62 @@
+import psycopg2
+
+with open("project/production/configs/db_auth.txt") as fh:
+ vals = [x.strip() for x in fh.readlines()]
+auth_data = dict(zip(("user", "pass"), vals))
+
+con = psycopg2.connect("dbname=kilink user={user} password={pass} host=localhost".format(**auth_data))
+cur = con.cursor()
+cur.execute("drop table if exists kilink_new;")
+con.commit()
+
+create_table = """
+CREATE TABLE kilink_new (
+ linkode_id character varying NOT NULL primary key,
+ root character varying NOT NULL,
+ parent character varying,
+ compressed bytea,
+ "timestamp" timestamp without time zone,
+ text_type character varying DEFAULT ''::character varying
+);"""
+
+cur.execute(create_table)
+con.commit()
+
+q_root_nodes = """
+SELECT kid, revno, parent, compressed, timestamp, text_type from kilink where parent is NULL;
+"""
+
+q_first_child_node = """
+SELECT kid, revno, parent, compressed, timestamp, text_type
+from kilink
+where parent = %s"""
+
+q_rest_child_node = """
+SELECT kid, revno, parent, compressed, timestamp, text_type
+from kilink
+where kid=%s and parent != %s and parent is not null"""
+
+q_insert = """
+INSERT into kilink_new (linkode_id, root, parent, compressed, timestamp, text_type)
+values (%s,%s,%s,%s,%s,%s)"""
+
+cur.execute(q_root_nodes)
+root_nodes = cur.fetchall()
+
+for r_kid, r_revno, r_parent, r_compressed, r_timestamp, r_text_type in root_nodes:
+ print "=============================Root ", r_kid, r_revno, r_parent, "=============="
+ cur.execute(q_insert, (r_kid, r_kid, r_parent, r_compressed, r_timestamp, r_text_type))
+
+ cur.execute(q_first_child_node, (r_revno,))
+ first_children = cur.fetchall()
+ for kid, revno, parent, compressed, timestamp, text_type in first_children:
+ print "=============================First One ", kid, revno, parent, "=============="
+ cur.execute(q_insert, (revno, kid, kid, compressed, timestamp, text_type))
+
+ cur.execute(q_rest_child_node, (r_kid, r_revno))
+ rest_children = cur.fetchall()
+ for kid, revno, parent, compressed, timestamp, text_type in rest_children:
+ print "=============================Rest ", kid, revno, parent, "=============="
+ cur.execute(q_insert, (revno, kid, parent, compressed, timestamp, text_type))
+
+ con.commit()
diff --git a/pool/shard010/Python/0089285_node_memory.py b/pool/shard010/Python/0089285_node_memory.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2fde12850d800c7781c9c8a77481476753091f8
--- /dev/null
+++ b/pool/shard010/Python/0089285_node_memory.py
@@ -0,0 +1,50 @@
+from xii import error
+from xii.validator import ByteSize
+from xii.components.node import NodeAttribute
+import re
+
+
+class MemoryAttribute(NodeAttribute):
+ atype = "memory"
+ requires = []
+ defaults = "512M"
+ keys = ByteSize("512M")
+
+ factors = {
+ "k": 1,
+ "M": 2,
+ "G": 3,
+ "T": 4
+ }
+ warn_on = 512 * 1024 * 1024
+
+ def validate(self):
+ NodeAttribute.validate(self)
+ value, unit = self.extract(self.settings())
+ in_bytes = int(value) * pow(1024, self.factors[unit])
+
+ if unit not in self.factors.keys():
+ raise error.DefError("Invalid memory size (kMGT can be used)")
+
+ # FIXME: Move this to only start/spawn command
+ if in_bytes < self.warn_on:
+ self.warn("It looks like you are trying to start a node with less "
+ "than 512M. Starting the virtual maschine's OS might not "
+ "work as expected. Raise memory in case.")
+
+ def spawn(self):
+ memory_settings = self.settings()
+ value, unit = self.extract(memory_settings)
+ self.verbose("setting Memory to {} {}...".format(value, unit))
+
+ # FIXME: Move to a template
+ memory = "{} ".format(unit, value)
+ current_memory = ("{} "
+ .format(unit, value))
+ memory_section = "{}\n{}".format(memory, current_memory)
+ self.add_xml("core", memory_section)
+
+ def extract(self, memory):
+ validator = re.compile("(?P\d+)(\ *)(?P[GkMT])")
+ result = validator.search(memory)
+ return (result.group("value"), result.group("unit"))
diff --git a/pool/shard010/Python/0089286_k_feature_routing_function_op_test.py b/pool/shard010/Python/0089286_k_feature_routing_function_op_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc053f3b94dcdcae7af20848515768ef67aa410b
--- /dev/null
+++ b/pool/shard010/Python/0089286_k_feature_routing_function_op_test.py
@@ -0,0 +1,89 @@
+# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ==============================================================================
+"""Tests for the routing function op."""
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from tensorflow.contrib.tensor_forest.hybrid.ops import gen_training_ops
+from tensorflow.contrib.tensor_forest.hybrid.python.ops import training_ops
+from tensorflow.contrib.tensor_forest.python import tensor_forest
+
+from tensorflow.python.framework import test_util
+from tensorflow.python.platform import googletest
+
+
+class KFeatureRoutingFunctionTest(test_util.TensorFlowTestCase):
+
+ def setUp(self):
+ self.input_data = [[-1., 0.], [-1., 2.],
+ [1., 0.], [1., -2.]]
+ self.input_labels = [0., 1., 2., 3.]
+ self.tree = [[1, 0], [-1, 0], [-1, 0]]
+ self.tree_weights = [[1.0, 0.0], [1.0, 0.0], [1.0, 0.0]]
+ self.tree_thresholds = [0., 0., 0.]
+
+ self.ops = training_ops.Load()
+
+ self.params = tensor_forest.ForestHParams(
+ num_features=2,
+ hybrid_tree_depth=2,
+ base_random_seed=10,
+ feature_bagging_fraction=1.0,
+ regularization_strength=0.01,
+ regularization="",
+ weight_init_mean=0.0,
+ weight_init_std=0.1)
+ self.params.num_nodes = 2**self.params.hybrid_tree_depth - 1
+ self.params.num_leaves = 2**(self.params.hybrid_tree_depth - 1)
+ self.params.num_features_per_node = (
+ self.params.feature_bagging_fraction * self.params.num_features)
+ self.params.regression = False
+
+ def testParams(self):
+ self.assertEquals(self.params.num_nodes, 3)
+ self.assertEquals(self.params.num_features, 2)
+ self.assertEquals(self.params.num_features_per_node, 2)
+
+ def testRoutingFunction(self):
+ with self.cached_session():
+ route_tensor = gen_training_ops.k_feature_routing_function(
+ self.input_data,
+ self.tree_weights,
+ self.tree_thresholds,
+ max_nodes=self.params.num_nodes,
+ num_features_per_node=self.params.num_features_per_node,
+ layer_num=0,
+ random_seed=self.params.base_random_seed)
+
+ route_tensor_shape = route_tensor.get_shape()
+ self.assertEquals(len(route_tensor_shape), 2)
+ self.assertEquals(route_tensor_shape[0], 4)
+ self.assertEquals(route_tensor_shape[1], 3)
+
+ routes = route_tensor.eval()
+ print(routes)
+
+ # Point 1
+ # Node 1 is a decision node => probability = 1.0
+ self.assertAlmostEquals(1.0, routes[0, 0])
+ # Probability left output = 1.0 / (1.0 + exp(1.0)) = 0.26894142
+ self.assertAlmostEquals(0.26894142, routes[0, 1])
+ # Probability right = 1 - 0.2689414 = 0.73105858
+ self.assertAlmostEquals(0.73105858, routes[0, 2])
+
+
+if __name__ == "__main__":
+ googletest.main()
diff --git a/pool/shard010/Python/0089305_multiple_inheritance.py b/pool/shard010/Python/0089305_multiple_inheritance.py
new file mode 100644
index 0000000000000000000000000000000000000000..281a34fb60d609e94a6123b511a4e5b6fecb1282
--- /dev/null
+++ b/pool/shard010/Python/0089305_multiple_inheritance.py
@@ -0,0 +1,39 @@
+class A(object):
+ def __init__(self):
+ self.a = 1
+ def x(self):
+ print "A.x"
+ def y(self):
+ print "A.y"
+ def z(self):
+ print "A.z"
+
+class B(A):
+ def __init__(self):
+ A.__init__(self)
+ self.a = 2
+ self.b = 3
+ def y(self):
+ print "B.y"
+ def z(self):
+ print "B.z"
+
+class C(object):
+ def __init__(self):
+ self.a = 4
+ self.c = 5
+ def y(self):
+ print "C.y"
+ def z(self):
+ print "C.z"
+
+class D(C, B):
+ def __init__(self):
+ C.__init__(self)
+ B.__init__(self)
+ self.d = 6
+ def z(self):
+ print "D.z"
+
+obj = D()
+print obj.a
\ No newline at end of file
diff --git a/pool/shard010/Python/0089307_argtools.py b/pool/shard010/Python/0089307_argtools.py
new file mode 100644
index 0000000000000000000000000000000000000000..b75ad7326b41e08a679dcd107beb02f3e0e2dd9a
--- /dev/null
+++ b/pool/shard010/Python/0089307_argtools.py
@@ -0,0 +1,229 @@
+# -*- coding: utf-8 -*-
+# File: argtools.py
+
+
+import inspect
+import functools
+
+from . import logger
+
+__all__ = ['map_arg', 'memoized', 'memoized_method', 'graph_memoized', 'shape2d', 'shape4d',
+ 'memoized_ignoreargs', 'log_once']
+
+
+def map_arg(**maps):
+ """
+ Apply a mapping on certain argument before calling the original function.
+
+ Args:
+ maps (dict): {argument_name: map_func}
+ """
+ def deco(func):
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ # getcallargs was deprecated since 3.5
+ sig = inspect.signature(func)
+ argmap = sig.bind_partial(*args, **kwargs).arguments
+ for k, map_func in maps.items():
+ if k in argmap:
+ argmap[k] = map_func(argmap[k])
+ return func(**argmap)
+ return wrapper
+ return deco
+
+
+memoized = functools.lru_cache(maxsize=None)
+""" Alias to :func:`functools.lru_cache`
+WARNING: memoization will keep keys and values alive!
+"""
+
+
+def graph_memoized(func):
+ """
+ Like memoized, but keep one cache per default graph.
+ """
+
+ # TODO it keeps the graph alive
+ from ..compat import tfv1
+ GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__'
+
+ @memoized
+ def func_with_graph_arg(*args, **kwargs):
+ kwargs.pop(GRAPH_ARG_NAME)
+ return func(*args, **kwargs)
+
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ assert GRAPH_ARG_NAME not in kwargs, "No Way!!"
+ graph = tfv1.get_default_graph()
+ kwargs[GRAPH_ARG_NAME] = graph
+ return func_with_graph_arg(*args, **kwargs)
+ return wrapper
+
+
+_MEMOIZED_NOARGS = {}
+
+
+def memoized_ignoreargs(func):
+ """
+ A decorator. It performs memoization ignoring the arguments used to call
+ the function.
+ """
+ def wrapper(*args, **kwargs):
+ if func not in _MEMOIZED_NOARGS:
+ res = func(*args, **kwargs)
+ _MEMOIZED_NOARGS[func] = res
+ return res
+ return _MEMOIZED_NOARGS[func]
+ return wrapper
+
+
+def shape2d(a):
+ """
+ Ensure a 2D shape.
+
+ Args:
+ a: a int or tuple/list of length 2
+
+ Returns:
+ list: of length 2. if ``a`` is a int, return ``[a, a]``.
+ """
+ if type(a) == int:
+ return [a, a]
+ if isinstance(a, (list, tuple)):
+ assert len(a) == 2
+ return list(a)
+ raise RuntimeError("Illegal shape: {}".format(a))
+
+
+def get_data_format(data_format, keras_mode=True):
+ if keras_mode:
+ dic = {'NCHW': 'channels_first', 'NHWC': 'channels_last'}
+ else:
+ dic = {'channels_first': 'NCHW', 'channels_last': 'NHWC'}
+ ret = dic.get(data_format, data_format)
+ if ret not in dic.values():
+ raise ValueError("Unknown data_format: {}".format(data_format))
+ return ret
+
+
+def shape4d(a, data_format='NHWC'):
+ """
+ Ensuer a 4D shape, to use with 4D symbolic functions.
+
+ Args:
+ a: a int or tuple/list of length 2
+
+ Returns:
+ list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]``
+ or ``[1, 1, a, a]`` depending on data_format.
+ """
+ s2d = shape2d(a)
+ if get_data_format(data_format, False) == 'NHWC':
+ return [1] + s2d + [1]
+ else:
+ return [1, 1] + s2d
+
+
+@memoized
+def log_once(message, func='info'):
+ """
+ Log certain message only once. Call this function more than one times with
+ the same message will result in no-op.
+
+ Args:
+ message(str): message to log
+ func(str): the name of the logger method. e.g. "info", "warn", "error".
+ """
+ getattr(logger, func)(message)
+
+
+def call_only_once(func):
+ """
+ Decorate a method or property of a class, so that this method can only
+ be called once for every instance.
+ Calling it more than once will result in exception.
+ """
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ self = args[0]
+ # cannot use hasattr here, because hasattr tries to getattr, which
+ # fails if func is a property
+ assert func.__name__ in dir(self), "call_only_once can only be used on method or property!"
+
+ if not hasattr(self, '_CALL_ONLY_ONCE_CACHE'):
+ cache = self._CALL_ONLY_ONCE_CACHE = set()
+ else:
+ cache = self._CALL_ONLY_ONCE_CACHE
+
+ cls = type(self)
+ # cannot use ismethod(), because decorated method becomes a function
+ is_method = inspect.isfunction(getattr(cls, func.__name__))
+ assert func not in cache, \
+ "{} {}.{} can only be called once per object!".format(
+ 'Method' if is_method else 'Property',
+ cls.__name__, func.__name__)
+ cache.add(func)
+
+ return func(*args, **kwargs)
+
+ return wrapper
+
+
+def memoized_method(func):
+ """
+ A decorator that performs memoization on methods. It stores the cache on the object instance itself.
+ """
+
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ self = args[0]
+ assert func.__name__ in dir(self), "memoized_method can only be used on method!"
+
+ if not hasattr(self, '_MEMOIZED_CACHE'):
+ cache = self._MEMOIZED_CACHE = {}
+ else:
+ cache = self._MEMOIZED_CACHE
+
+ key = (func, ) + args[1:] + tuple(kwargs)
+ ret = cache.get(key, None)
+ if ret is not None:
+ return ret
+ value = func(*args, **kwargs)
+ cache[key] = value
+ return value
+
+ return wrapper
+
+
+if __name__ == '__main__':
+ class A():
+ def __init__(self):
+ self._p = 0
+
+ @call_only_once
+ def f(self, x):
+ print(x)
+
+ @property
+ def p(self):
+ return self._p
+
+ @p.setter
+ @call_only_once
+ def p(self, val):
+ self._p = val
+
+ a = A()
+ a.f(1)
+
+ b = A()
+ b.f(2)
+ b.f(1)
+
+ print(b.p)
+ print(b.p)
+ b.p = 2
+ print(b.p)
+ b.p = 3
+ print(b.p)
diff --git a/pool/shard010/Python/0089311_deploy.py b/pool/shard010/Python/0089311_deploy.py
new file mode 100644
index 0000000000000000000000000000000000000000..da947f9a8b7e1e043af603f569c0283a5e5bb18d
--- /dev/null
+++ b/pool/shard010/Python/0089311_deploy.py
@@ -0,0 +1,235 @@
+# -*- coding: utf-8 -*-
+import os.path
+
+from fabric.api import settings, run, cd, lcd, put, get, local, env, with_settings
+from fabric.colors import green
+
+from .. import versions
+from .. import distro
+from .. import tools
+
+class Deployment(object):
+ """The core :class:`Deployment ` object. All Fabric tasks built with
+ Parcel will probably use this an instance of this class.
+ """
+
+ virtual = "vp"
+ build_dir = '.parcel'
+
+ # these are the full text versions of the scripts
+ prerm = None
+ postrm = None
+ preinst = None
+ postinst = None
+
+ # these are a list representation of commands to go into the scripts
+ # if the control script templating is used
+ prerm_lines = []
+ postrm_lines = []
+ preinst_lines = []
+ postinst_lines = []
+
+ def __init__(self, app_name, build_deps=[], run_deps=[], path=".", base=None, arch=distro.Debian(), version=None):
+
+ #: The architecture of the build host. This should be a :class:`Distro ` object.
+ self.arch = arch
+ remotehome = run('echo $HOME').strip()
+
+ # if path isn't set, make it the home directory of the build user
+ if base is None:
+ base = remotehome
+ elif not base.startswith('/'):
+ base = os.path.join(remotehome, base)
+
+ # update and install missing build dependency packages
+ arch.update_packages()
+ if build_deps:
+ arch.build_deps(build_deps)
+
+ # the version in the archives of this package if we have been built and uploaded before.
+ self.version = arch.version(app_name).next() if version is None else versions.Version(version)
+
+ #: The name of the resulting package.
+ self.app_name = app_name
+
+ #: A list of packages that must be installed to run the resulting package.
+ self.run_deps = run_deps
+
+ #: A list of packages that need to be installed to build the software.
+ self.build_deps = build_deps
+ self.pkg_name = app_name.lower()
+
+ #: The directory that will be used as the base level directory.
+ self.path = os.path.realpath(path)
+
+ #: Location of files during build on build host. Default is user's home directory.
+ #: If path is relative, it's relative to the remote user's home directory. If the path is absolute,
+ #: it's used as is.
+ self.base_path = os.path.join(remotehome,self.build_dir)
+
+ self.pkg_name = app_name.lower()
+ self.root_path = os.path.join(self.base_path,"root") # where the final root fs is located
+
+ # the path the app will be installed into
+ self.app_path = os.path.join(base,'%s-%s'%(self.pkg_name,self.version))
+
+ # the build path
+ self.build_path = os.path.join(self.root_path, self.app_path[1:]) # cut the first / off app_path
+
+ print "ROOT_PATH", self.root_path
+ print "BASE_PATH",self.base_path
+ print "APP PATH",self.app_path
+ print "BUILD PATH",self.build_path
+
+ self._clean()
+
+ def prepare_app(self, branch=None, requirements="requirements.txt"):
+ """Creates the necessary directories on the build server, checks out the desired branch (None means current),
+ creates a virtualenv and populates it with dependencies from requirements.txt.
+ As a bonus it also fixes the shebangs (#!) of all scripts in the virtualenv to point the correct Python path
+ on the target system."""
+ self._sync_app()
+ self._add_venv(requirements)
+
+ def add_to_root_fs(self,localfile,remotepath):
+ """Add a local file to the root package path.
+ If remote path ends in /, the filename is copied into
+ that directory. If the remote path doesn't end in /, it represents
+ the final filename.
+ """
+ while remotepath[0]=='/':
+ remotepath=remotepath[1:]
+ put(localfile,os.path.join(self.root_path,remotepath))
+
+ def add_data_to_root_fs(self, data, remotepath):
+ """Copies data in file on remotepath (relative to final root)"""
+ while remotepath[0]=='/':
+ remotepath=remotepath[1:]
+ tools.write_contents_to_remote(data,os.path.join(self.root_path, remotepath))
+
+ def compile_python(self):
+ # compile all python (with virtual python)
+ vpython_path = os.path.join(self.venv_path,'bin/python')
+ command = '%s -c "import compileall;compileall.compile_dir(\'%s\', force=1)"'%(vpython_path, self.build_path)
+ run(command)
+
+ def clear_py_files(self):
+ # clear all .py files
+ run('find "%s" -name "*.py" -exec rm {} \;'%(self.build_path))
+
+ def add_prerm(self, lines):
+ """Add lines to the prerm file"""
+ self.prerm_lines.extend(lines)
+
+ def add_postrm(self, lines):
+ """Add lines to the postrm file"""
+ self.postrm_lines.extend(lines)
+
+ def add_preinst(self, lines):
+ """Add lines to the preinst file"""
+ self.preinst_lines.extend(lines)
+
+ def add_postinst(self, lines):
+ """Add lines to the postinst file"""
+ self.postinst_lines.extend(lines)
+
+ def build_package(self, templates=True):
+ """Takes the whole app including the virtualenv, packages it using fpm and downloads it to the local host.
+ The version of the package is the build number - which is just the latest package version in our Ubuntu repositories plus one.
+ """
+
+ # add install and remove templates, use defaults if not supplied
+ if templates:
+ if not self.prerm:
+ self.arch.defaults.prerm_template
+ self.write_prerm_template(self.arch.defaults.prerm_template)
+ if not self.postrm:
+ self.write_postrm_template(self.arch.defaults.postrm_template)
+ if not self.preinst:
+ self.write_preinst_template(self.arch.defaults.preinst_template)
+ if not self.postinst:
+ self.write_postinst_template(self.arch.defaults.postinst_template)
+
+ with cd(self.base_path):
+ self.deps_str = '-d ' + ' -d '.join(self.run_deps)
+ self.dirs_str = '.'
+
+ if self.prerm or self.postrm or self.preinst or self.postinst:
+ run("rm -rf installscripts && mkdir -p installscripts")
+
+ # render pre/posts
+ hooks = []
+ if self.prerm:
+ prerm = self.prerm.format(self)
+ tools.write_contents_to_remote(prerm,'installscripts/prerm')
+ hooks.extend(['--before-remove', '../installscripts/prerm'])
+
+ if self.postrm:
+ postrm = self.postrm.format(self)
+ tools.write_contents_to_remote(postrm,'installscripts/postrm')
+ hooks.extend(['--after-remove', '../installscripts/postrm'])
+
+ if self.preinst:
+ tools.write_contents_to_remote(self.preinst,'installscripts/preinst')
+ hooks.extend(['--before-install', '../installscripts/preinst'])
+
+ if self.postinst:
+ tools.write_contents_to_remote(self.postinst,'installscripts/postinst')
+ hooks.extend(['--after-install', '../installscripts/postinst'])
+
+ self.hooks_str = ' '.join(hooks)
+
+ self.arch.build_package(deployment=self)
+
+
+ def write_prerm_template(self, template):
+ """Take a template prerm script and format it with appname and prerm_lines
+ If you call this function you must supply a template string that includes {app_name} and {lines}."""
+ self.prerm = template.format(app_name=self.app_name, lines="\n ".join(self.prerm_lines))
+
+ def write_postrm_template(self, template):
+ """Take a template postrm script and format it with appname and postrm_lines
+ If you call this function you must supply a template string that includes {app_name} and {lines}."""
+ self.postrm = template.format(app_name=self.app_name, lines="\n ".join(self.postrm_lines))
+
+ def write_preinst_template(self, template):
+ """Take a template preinst script and format it with appname and preinst_lines
+ If you call this function you must supply a template string that includes {app_name} and {lines}."""
+ self.preinst = template.format(app_name=self.app_name, lines="\n ".join(self.preinst_lines))
+
+ def write_postinst_template(self, template):
+ """Take a template postinst script and format it with appname and postinst_lines
+ If you call this function you must supply a template string that includes {app_name} and {lines}."""
+ self.postinst = template.format(app_name=self.app_name, lines="\n ".join(self.postinst_lines))
+
+ def _clean(self):
+ """Make sure the root filesystem directory is empty."""
+ run('rm -rf "%s"'%self.root_path)
+
+ def _sync_app(self):
+ """There is no revision control at the moment so... just copy directory over."""
+ print self.build_path
+ tools.rsync([self.path+'/'],self.build_path,rsync_ignore='.rsync-ignore')
+
+ def _add_venv(self,requirements="requirements.txt"):
+ """Builds virtualenv on remote host and installs from requirements.txt.
+
+ :param requirements: The name of the requirements.txt file.
+ """
+ self.venv_path = os.path.join(self.build_path, self.virtual)
+ run('virtualenv %s'%(self.venv_path))
+ if requirements and os.path.exists(requirements):
+ run('PIP_DOWNLOAD_CACHE="%s" %s install -r %s'%(
+ self.arch.pip_download_cache,
+ os.path.join(self.venv_path, 'bin/pip'),
+ os.path.join(self.build_path, requirements))
+ )
+
+ # venv_root is final path
+ self.venv_root = os.path.join(self.app_path, self.virtual)
+
+ # lets make sure this venv is relinked on installation
+ self.add_postinst(['virtualenv "%s"'%self.venv_root])
+
+ # and we have the virtualenv executable
+ self.run_deps.append('python-virtualenv')
diff --git a/pool/shard010/Python/0089315_stock_account.py b/pool/shard010/Python/0089315_stock_account.py
new file mode 100644
index 0000000000000000000000000000000000000000..df04f22df3854bba0e3f39b6345be2e33a3d33dc
--- /dev/null
+++ b/pool/shard010/Python/0089315_stock_account.py
@@ -0,0 +1,222 @@
+# -*- coding: utf-8 -*-
+# Copyright (C) 2014 Renato Lima - Akretion
+# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
+
+from openerp import models, fields, api
+
+
+class StockPicking(models.Model):
+ _inherit = 'stock.picking'
+
+ @api.model
+ def _default_fiscal_category(self):
+ return self.env.user.company_id.stock_fiscal_category_id
+
+ fiscal_category_id = fields.Many2one(
+ 'l10n_br_account.fiscal.category', 'Categoria Fiscal',
+ readonly=True, domain="[('state', '=', 'approved')]",
+ states={'draft': [('readonly', False)]},
+ default=_default_fiscal_category)
+ fiscal_position = fields.Many2one(
+ 'account.fiscal.position', u'Posição Fiscal',
+ domain="[('fiscal_category_id','=',fiscal_category_id)]",
+ readonly=True, states={'draft': [('readonly', False)]})
+
+ def _fiscal_position_map(self, result, **kwargs):
+ ctx = dict(self.env.context)
+ if ctx.get('fiscal_category_id'):
+ kwargs['fiscal_category_id'] = ctx.get('fiscal_category_id')
+ ctx.update({'use_domain': ('use_picking', '=', True)})
+ return self.env['account.fiscal.position.rule'].with_context(
+ ctx).apply_fiscal_mapping(result, **kwargs)
+
+ @api.onchange('fiscal_category_id', 'company_id')
+ def onchange_fiscal(self):
+ if self.partner_id and self.company_id and self.fiscal_category_id:
+ result = {'value': {'fiscal_position': None}}
+ kwargs = {
+ 'partner_id': self.partner_id.id,
+ 'partner_invoice_id': self.partner_id.id,
+ 'partner_shipping_id': self.partner_id.id,
+ 'company_id': self.company_id.id,
+ 'context': dict(self.env.context),
+ 'fiscal_category_id': self.fiscal_category_id.id,
+ }
+ result = self._fiscal_position_map(result, **kwargs)
+ self.fiscal_position = result['value'].get('fiscal_position')
+
+ @api.model
+ def _create_invoice_from_picking(self, picking, vals):
+ result = {}
+
+ comment = ''
+ if picking.fiscal_position.inv_copy_note:
+ comment += picking.fiscal_position.note or ''
+
+ if picking.note:
+ comment += ' - ' + picking.note
+
+ result['partner_shipping_id'] = picking.partner_id.id
+
+ result['comment'] = comment
+ result['fiscal_category_id'] = picking.fiscal_category_id.id
+ result['fiscal_position'] = picking.fiscal_position.id
+
+ if picking.fiscal_category_id.journal_type in ('sale_refund',
+ 'purchase_refund'):
+ result['nfe_purpose'] = '4'
+
+ vals.update(result)
+ return super(StockPicking, self)._create_invoice_from_picking(
+ picking, vals)
+
+
+class StockMove(models.Model):
+ _inherit = "stock.move"
+
+ fiscal_category_id = fields.Many2one(
+ 'l10n_br_account.fiscal.category', 'Categoria Fiscal', readonly=True,
+ domain="[('type', '=', 'output'), ('journal_type', '=', 'sale')]",
+ states={'draft': [('readonly', False)],
+ 'sent': [('readonly', False)]})
+ fiscal_position = fields.Many2one(
+ 'account.fiscal.position', 'Fiscal Position', readonly=True,
+ domain="[('fiscal_category_id','=',fiscal_category_id)]",
+ states={'draft': [('readonly', False)],
+ 'sent': [('readonly', False)]})
+
+ @api.model
+ def _fiscal_position_map(self, result, **kwargs):
+ ctx = dict(self.env.context)
+ ctx.update({'use_domain': ('use_picking', '=', True)})
+
+ partner = self.env['res.partner'].browse(kwargs.get('partner_id'))
+ obj_fp_rule = self.env['account.fiscal.position.rule']
+ product_fc_id = obj_fp_rule.with_context(
+ ctx).product_fiscal_category_map(
+ kwargs.get('product_id'),
+ kwargs.get('fiscal_category_id'),
+ partner.state_id.id)
+
+ if product_fc_id:
+ kwargs['fiscal_category_id'] = product_fc_id
+ result['value']['fiscal_category_id'] = product_fc_id
+ else:
+ result['value']['fiscal_category_id'] = kwargs.get(
+ 'fiscal_category_id')
+
+ return obj_fp_rule.with_context(ctx).apply_fiscal_mapping(
+ result, **kwargs)
+
+ @api.multi
+ def onchange_product_id(self, product_id, location_id,
+ location_dest_id, partner_id):
+ context = dict(self.env.context)
+ parent_fiscal_category_id = context.get('parent_fiscal_category_id')
+ if context.get('company_id'):
+ company_id = context['company_id']
+ else:
+ company_id = self.env.user.company_id.id
+
+ result = {'value': {}}
+ result['value']['invoice_state'] = context.get('parent_invoice_state')
+
+ if parent_fiscal_category_id and product_id and partner_id:
+
+ kwargs = {
+ 'partner_id': partner_id,
+ 'product_id': product_id,
+ 'partner_invoice_id': partner_id,
+ 'partner_shipping_id': partner_id,
+ 'fiscal_category_id': parent_fiscal_category_id,
+ 'company_id': company_id,
+ 'context': context
+ }
+
+ result.update(self._fiscal_position_map(result, **kwargs))
+
+ result_super = super(StockMove, self).onchange_product_id(
+ product_id, location_id, location_dest_id, partner_id)
+
+ if result_super.get('value'):
+ result_super.get('value').update(result['value'])
+ else:
+ result_super.update(result)
+ return result_super
+
+ @api.onchange('fiscal_category_id', 'fiscal_position')
+ def onchange_fiscal(self):
+ if self.picking_id.partner_id and self.picking_id.company_id \
+ and self.fiscal_category_id:
+ result = {'value': {'fiscal_position': None}}
+ kwargs = {
+ 'partner_id': self.picking_id.partner_id.id,
+ 'product_id': self.product_id.id,
+ 'partner_invoice_id': self.picking_id.partner_id.id,
+ 'partner_shipping_id': self.picking_id.partner_id.id,
+ 'company_id': self.picking_id.company_id.id,
+ 'context': dict(self.env.context),
+ 'fiscal_category_id': self.fiscal_category_id.id,
+ }
+ result = self._fiscal_position_map(result, **kwargs)
+ self.fiscal_position = result['value'].get('fiscal_position')
+ self.fiscal_category_id = result['value'].get('fiscal_category_id')
+
+ @api.model
+ def _get_invoice_line_vals(self, move, partner, inv_type):
+ result = super(StockMove, self)._get_invoice_line_vals(
+ move, partner, inv_type)
+ fiscal_position = move.fiscal_position or \
+ move.picking_id.fiscal_position
+ fiscal_category_id = move.fiscal_category_id or \
+ move.picking_id.fiscal_category_id
+
+ result['cfop_id'] = fiscal_position.cfop_id.id
+ result['fiscal_category_id'] = fiscal_category_id.id
+ result['fiscal_position'] = fiscal_position.id
+
+ # TODO este código é um fix pq no core nao se copia os impostos
+ ctx = dict(self.env.context)
+ ctx['fiscal_type'] = move.product_id.fiscal_type
+ ctx['partner_id'] = partner.id
+
+ # Required to compute_all in account.invoice.line
+ result['partner_id'] = partner.id
+
+ ctx['product_id'] = move.product_id.id
+
+ if inv_type in ('out_invoice', 'in_refund'):
+ ctx['type_tax_use'] = 'sale'
+ taxes = move.product_id.taxes_id
+ else:
+ ctx['type_tax_use'] = 'purchase'
+ taxes = move.product_id.supplier_taxes_id
+
+ if fiscal_position:
+ taxes = fiscal_position.with_context(ctx).map_tax(taxes)
+ result['invoice_line_tax_id'] = [[6, 0, taxes.ids]]
+
+ if fiscal_position:
+ account_id = result.get('account_id')
+ account_id = fiscal_position.map_account(account_id)
+
+ return result
+
+ @api.cr_uid_ids_context
+ def _picking_assign(self, cr, uid, move_ids, procurement_group,
+ location_from, location_to, context=None):
+
+ result = super(StockMove, self)._picking_assign(
+ cr, uid, move_ids, procurement_group,
+ location_from, location_to, context)
+ if move_ids:
+ move = self.browse(cr, uid, move_ids, context=context)[0]
+ if move.picking_id:
+ picking_values = {
+ 'fiscal_category_id': move.fiscal_category_id.id,
+ 'fiscal_position': move.fiscal_position.id,
+ }
+ self.pool.get("stock.picking").write(
+ cr, uid, move.picking_id.id,
+ picking_values, context=context)
+ return result
diff --git a/pool/shard010/Python/0089317_iir.py b/pool/shard010/Python/0089317_iir.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c7d0ff4502fbc332e9c568133bd5dc50de4f7d8
--- /dev/null
+++ b/pool/shard010/Python/0089317_iir.py
@@ -0,0 +1,133 @@
+"""Filter signals with IIR filters."""
+
+from warnings import warn
+
+from scipy.signal import butter, filtfilt
+
+from neurodsp.utils import remove_nans, restore_nans
+from neurodsp.utils.decorators import multidim
+from neurodsp.filt.utils import compute_nyquist, compute_frequency_response
+from neurodsp.filt.checks import check_filter_definition, check_filter_properties
+from neurodsp.plts.filt import plot_frequency_response
+
+###################################################################################################
+###################################################################################################
+
+@multidim
+def filter_signal_iir(sig, fs, pass_type, f_range, butterworth_order,
+ print_transitions=False, plot_properties=False, return_filter=False):
+ """Apply an IIR filter to a signal.
+
+ Parameters
+ ----------
+ sig : 1d array
+ Time series to be filtered.
+ fs : float
+ Sampling rate, in Hz.
+ pass_type : {'bandpass', 'bandstop', 'lowpass', 'highpass'}
+ Which kind of filter to apply:
+
+ * 'bandpass': apply a bandpass filter
+ * 'bandstop': apply a bandstop (notch) filter
+ * 'lowpass': apply a lowpass filter
+ * 'highpass' : apply a highpass filter
+ f_range : tuple of (float, float) or float
+ Cutoff frequency(ies) used for filter, specified as f_lo & f_hi.
+ For 'bandpass' & 'bandstop', must be a tuple.
+ For 'lowpass' or 'highpass', can be a float that specifies pass frequency, or can be
+ a tuple and is assumed to be (None, f_hi) for 'lowpass', and (f_lo, None) for 'highpass'.
+ butterworth_order : int
+ Order of the butterworth filter, if using an IIR filter.
+ See input 'N' in scipy.signal.butter.
+ print_transitions : bool, optional, default: False
+ If True, print out the transition and pass bandwidths.
+ plot_properties : bool, optional, default: False
+ If True, plot the properties of the filter, including frequency response and/or kernel.
+ return_filter : bool, optional, default: False
+ If True, return the filter coefficients of the IIR filter.
+
+ Returns
+ -------
+ sig_filt : 1d array
+ Filtered time series.
+ filter_coefs : tuple of (1d array, 1d array)
+ Filter coefficients of the IIR filter, as (b_vals, a_vals).
+ Only returned if `return_filter` is True.
+ """
+
+ # Design filter
+ b_vals, a_vals = design_iir_filter(fs, pass_type, f_range, butterworth_order)
+
+ # Check filter properties: compute transition bandwidth & run checks
+ check_filter_properties(b_vals, a_vals, fs, pass_type, f_range, verbose=print_transitions)
+
+ # Remove any NaN on the edges of 'sig'
+ sig, sig_nans = remove_nans(sig)
+
+ # Apply filter
+ sig_filt = filtfilt(b_vals, a_vals, sig)
+
+ # Add NaN back on the edges of 'sig', if there were any at the beginning
+ sig_filt = restore_nans(sig_filt, sig_nans)
+
+ # Plot frequency response, if desired
+ if plot_properties:
+ f_db, db = compute_frequency_response(b_vals, a_vals, fs)
+ plot_frequency_response(f_db, db)
+
+ if return_filter:
+ return sig_filt, (b_vals, a_vals)
+ else:
+ return sig_filt
+
+
+def design_iir_filter(fs, pass_type, f_range, butterworth_order):
+ """Design an IIR filter.
+
+ Parameters
+ ----------
+ fs : float
+ Sampling rate, in Hz.
+ pass_type : {'bandpass', 'bandstop', 'lowpass', 'highpass'}
+ Which kind of filter to apply:
+
+ * 'bandpass': apply a bandpass filter
+ * 'bandstop': apply a bandstop (notch) filter
+ * 'lowpass': apply a lowpass filter
+ * 'highpass' : apply a highpass filter
+ f_range : tuple of (float, float) or float
+ Cutoff frequency(ies) used for filter, specified as f_lo & f_hi.
+ For 'bandpass' & 'bandstop', must be a tuple.
+ For 'lowpass' or 'highpass', can be a float that specifies pass frequency, or can be
+ a tuple and is assumed to be (None, f_hi) for 'lowpass', and (f_lo, None) for 'highpass'.
+ butterworth_order : int
+ Order of the butterworth filter, if using an IIR filter.
+ See input 'N' in scipy.signal.butter.
+
+ Returns
+ -------
+ b_vals : 1d array
+ B value filter coefficients for an IIR filter.
+ a_vals : 1d array
+ A value filter coefficients for an IIR filter.
+ """
+
+ # Warn about only recommending IIR for bandstop
+ if pass_type != 'bandstop':
+ warn('IIR filters are not recommended other than for notch filters.')
+
+ # Check filter definition
+ f_lo, f_hi = check_filter_definition(pass_type, f_range)
+
+ f_nyq = compute_nyquist(fs)
+ if pass_type in ('bandpass', 'bandstop'):
+ win = (f_lo / f_nyq, f_hi / f_nyq)
+ elif pass_type == 'highpass':
+ win = f_lo / f_nyq
+ elif pass_type == 'lowpass':
+ win = f_hi / f_nyq
+
+ # Design filter
+ b_vals, a_vals = butter(butterworth_order, win, pass_type)
+
+ return b_vals, a_vals
diff --git a/pool/shard010/Python/0089322_test_ipmi.py b/pool/shard010/Python/0089322_test_ipmi.py
new file mode 100644
index 0000000000000000000000000000000000000000..8700419ec69cf343b2ed53c292bc99add394e03e
--- /dev/null
+++ b/pool/shard010/Python/0089322_test_ipmi.py
@@ -0,0 +1,155 @@
+#!/usr/bin/env python
+#-*- coding: utf-8 -*-
+
+from nose.tools import eq_, ok_, raises
+from mock import MagicMock
+
+from pyipmi import interfaces, create_connection, Target, Routing
+from pyipmi.errors import CompletionCodeError, RetryError
+from pyipmi.msgs.bmc import GetDeviceIdReq, GetDeviceIdRsp
+from pyipmi.msgs.sensor import GetSensorReadingReq, GetSensorReadingRsp
+from pyipmi.msgs.constants import CC_NODE_BUSY
+
+
+def test_target():
+ target = Target()
+ eq_(target.ipmb_address, None)
+ eq_(target.routing, None)
+
+ target = Target(0xa0)
+ eq_(target.ipmb_address, 0xa0)
+ eq_(target.routing, None)
+
+ target = Target(ipmb_address=0xb0)
+ eq_(target.ipmb_address, 0xb0)
+ eq_(target.routing, None)
+
+
+def test_target_routing():
+ target = Target(routing=[(0x82, 0x20, 0)])
+ eq_(len(target.routing), 1)
+ eq_(target.routing[0].rq_sa, 0x82)
+ eq_(target.routing[0].rs_sa, 0x20)
+ eq_(target.routing[0].channel, 0)
+
+ target = Target(routing=[(0x82, 0x20, 0), (0x20, 0x82, 7)])
+ eq_(len(target.routing), 2)
+ eq_(target.routing[0].rq_sa, 0x82)
+ eq_(target.routing[0].rs_sa, 0x20)
+ eq_(target.routing[0].channel, 0)
+ eq_(target.routing[1].rq_sa, 0x20)
+ eq_(target.routing[1].rs_sa, 0x82)
+ eq_(target.routing[1].channel, 7)
+
+
+def test_routing():
+ routing = Routing(0x82, 0x20, 7)
+ eq_(routing.rq_sa, 0x82)
+ eq_(routing.rs_sa, 0x20)
+ eq_(routing.channel, 7)
+
+
+def test_target_set_routing():
+ target = Target()
+
+ target.set_routing([(0x11, 0x12, 0x13)])
+ eq_(len(target.routing), 1)
+ eq_(target.routing[0].rq_sa, 0x11)
+ eq_(target.routing[0].rs_sa, 0x12)
+ eq_(target.routing[0].channel, 0x13)
+
+ target.set_routing([(0x11, 0x12, 0x13), (0x21, 0x22, 0x23)])
+ eq_(len(target.routing), 2)
+ eq_(target.routing[0].rq_sa, 0x11)
+ eq_(target.routing[0].rs_sa, 0x12)
+ eq_(target.routing[0].channel, 0x13)
+ eq_(target.routing[1].rq_sa, 0x21)
+ eq_(target.routing[1].rs_sa, 0x22)
+ eq_(target.routing[1].channel, 0x23)
+
+
+def test_target_set_routing_from_string():
+ target = Target()
+
+ target.set_routing('[(0x11, 0x12, 0x13)]')
+ eq_(len(target.routing), 1)
+ eq_(target.routing[0].rq_sa, 0x11)
+ eq_(target.routing[0].rs_sa, 0x12)
+ eq_(target.routing[0].channel, 0x13)
+
+ target.set_routing('[(0x11, 0x12, 0x13), (0x21, 0x22, 0x23)]')
+ eq_(len(target.routing), 2)
+ eq_(target.routing[0].rq_sa, 0x11)
+ eq_(target.routing[0].rs_sa, 0x12)
+ eq_(target.routing[0].channel, 0x13)
+ eq_(target.routing[1].rq_sa, 0x21)
+ eq_(target.routing[1].rs_sa, 0x22)
+ eq_(target.routing[1].channel, 0x23)
+
+
+def test_ipmi_send_message_retry():
+ req = GetDeviceIdReq()
+ rsp = GetDeviceIdRsp()
+
+ interface = interfaces.create_interface('mock')
+ cc = CompletionCodeError(CC_NODE_BUSY)
+ mock = MagicMock(side_effect=(cc, 0))
+ mock.return_value = rsp
+ interface.send_and_receive = mock
+ ipmi = create_connection(interface)
+ ipmi.target = None
+ ipmi.send_message(req)
+ eq_(mock.call_count, 2)
+
+
+@raises(RetryError)
+def test_ipmi_send_message_retry_error():
+ req = GetDeviceIdReq()
+ rsp = GetDeviceIdRsp()
+
+ interface = interfaces.create_interface('mock')
+ cc = CompletionCodeError(CC_NODE_BUSY)
+ mock = MagicMock(side_effect=(cc, cc, cc))
+ mock.return_value = rsp
+ interface.send_and_receive = mock
+ ipmi = create_connection(interface)
+ ipmi.target = None
+ ipmi.send_message(req)
+
+
+def test_ipmi_send_message_with_name():
+
+ rsp = GetDeviceIdRsp()
+ rsp.completion_code = 0
+
+ mock_send_message = MagicMock()
+ mock_send_message.return_value = rsp
+
+ interface = interfaces.create_interface('mock')
+ ipmi = create_connection(interface)
+ ipmi.send_message = mock_send_message
+
+ ipmi.send_message_with_name('GetDeviceId')
+ args, kwargs = mock_send_message.call_args
+ req = args[0]
+ ok_(isinstance(req, GetDeviceIdReq))
+
+
+def test_ipmi_send_message_with_name_and_kwargs():
+
+ rsp = GetSensorReadingRsp()
+ rsp.completion_code = 0
+
+ mock_send_message = MagicMock()
+ mock_send_message.return_value = rsp
+
+ interface = interfaces.create_interface('mock')
+ ipmi = create_connection(interface)
+ ipmi.send_message = mock_send_message
+
+ ipmi.send_message_with_name('GetSensorReading', sensor_number=5, lun=2)
+ args, kwargs = mock_send_message.call_args
+ req = args[0]
+ ok_(isinstance(req, GetSensorReadingReq))
+ eq_(req.sensor_number, 5)
+ eq_(req.lun, 2)
diff --git a/pool/shard010/Python/0089326_views.py b/pool/shard010/Python/0089326_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..31b9fe8244a09ede7a7d5a619f0cd897eee02cdc
--- /dev/null
+++ b/pool/shard010/Python/0089326_views.py
@@ -0,0 +1,32 @@
+from django.views.generic import ListView, DetailView
+
+from .models import Book, Category
+
+
+class BooksListView(ListView):
+ model = Book
+
+ paginate_by = 10
+
+ def categories(self):
+ return Category.objects.all()
+
+ def get_queryset(self):
+ query_set = super(BooksListView, self).get_queryset()
+
+ category = self.kwargs.get('category')
+
+ if category:
+ query_set = query_set.filter(category__name=category)
+
+ return query_set
+
+
+book_list_view = BooksListView.as_view()
+
+
+class BookDetail(DetailView):
+ model = Book
+
+
+book_detail_view = BookDetail.as_view()
diff --git a/pool/shard010/Python/0089329_subset.py b/pool/shard010/Python/0089329_subset.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb8c8daba4fb2fb48e20cc25a95d16796b5383e0
--- /dev/null
+++ b/pool/shard010/Python/0089329_subset.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python
+# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai
+from __future__ import (unicode_literals, division, absolute_import,
+ print_function)
+
+__license__ = 'GPL v3'
+__copyright__ = '2013, Kovid Goyal '
+__docformat__ = 'restructuredtext en'
+
+import os, sys
+
+from calibre import prints, as_unicode
+from calibre.ebooks.oeb.base import OEB_STYLES, OEB_DOCS, XPath
+from calibre.ebooks.oeb.polish.container import OEB_FONTS
+from calibre.ebooks.oeb.polish.utils import guess_type
+from calibre.utils.fonts.sfnt.subset import subset
+from calibre.utils.fonts.sfnt.errors import UnsupportedFont
+from calibre.utils.fonts.utils import get_font_names
+
+def remove_font_face_rules(container, sheet, remove_names, base):
+ changed = False
+ for rule in tuple(sheet.cssRules):
+ if rule.type != rule.FONT_FACE_RULE:
+ continue
+ try:
+ uri = rule.style.getProperty('src').propertyValue[0].uri
+ except (IndexError, KeyError, AttributeError, TypeError, ValueError):
+ continue
+ name = container.href_to_name(uri, base)
+ if name in remove_names:
+ sheet.deleteRule(rule)
+ changed = True
+ return changed
+
+def subset_all_fonts(container, font_stats, report):
+ remove = set()
+ total_old = total_new = 0
+ changed = False
+ for name, mt in container.mime_map.iteritems():
+ if (mt in OEB_FONTS or name.rpartition('.')[-1].lower() in {'otf', 'ttf'}) and mt != guess_type('a.woff'):
+ chars = font_stats.get(name, set())
+ with container.open(name, 'rb') as f:
+ f.seek(0, os.SEEK_END)
+ total_old += f.tell()
+ if not chars:
+ remove.add(name)
+ report('Removed unused font: %s'%name)
+ continue
+ with container.open(name, 'r+b') as f:
+ raw = f.read()
+ font_name = get_font_names(raw)[-1]
+ warnings = []
+ container.log('Subsetting font: %s'%(font_name or name))
+ try:
+ nraw, old_sizes, new_sizes = subset(raw, chars,
+ warnings=warnings)
+ except UnsupportedFont as e:
+ container.log.warning(
+ 'Unsupported font: %s, ignoring. Error: %s'%(
+ name, as_unicode(e)))
+ continue
+
+ for w in warnings:
+ container.log.warn(w)
+ olen = sum(old_sizes.itervalues())
+ nlen = sum(new_sizes.itervalues())
+ total_new += len(nraw)
+ if nlen == olen:
+ report('The font %s was already subset'%font_name)
+ else:
+ report('Decreased the font %s to %.1f%% of its original size'%
+ (font_name, nlen/olen * 100))
+ changed = True
+ f.seek(0), f.truncate(), f.write(nraw)
+
+ for name in remove:
+ container.remove_item(name)
+ changed = True
+
+ if remove:
+ for name, mt in container.mime_map.iteritems():
+ if mt in OEB_STYLES:
+ sheet = container.parsed(name)
+ if remove_font_face_rules(container, sheet, remove, name):
+ container.dirty(name)
+ elif mt in OEB_DOCS:
+ for style in XPath('//h:style')(container.parsed(name)):
+ if style.get('type', 'text/css') == 'text/css' and style.text:
+ sheet = container.parse_css(style.text, name)
+ if remove_font_face_rules(container, sheet, remove, name):
+ style.text = sheet.cssText
+ container.dirty(name)
+ if total_old > 0:
+ report('Reduced total font size to %.1f%% of original'%(
+ total_new/total_old*100))
+ else:
+ report('No embedded fonts found')
+ return changed
+
+if __name__ == '__main__':
+ from calibre.ebooks.oeb.polish.container import get_container
+ from calibre.ebooks.oeb.polish.stats import StatsCollector
+ from calibre.utils.logging import default_log
+ default_log.filter_level = default_log.DEBUG
+ inbook = sys.argv[-1]
+ ebook = get_container(inbook, default_log)
+ report = []
+ stats = StatsCollector(ebook).font_stats
+ subset_all_fonts(ebook, stats, report.append)
+ outbook, ext = inbook.rpartition('.')[0::2]
+ outbook += '_subset.'+ext
+ ebook.commit(outbook)
+ prints('\nReport:')
+ for msg in report:
+ prints(msg)
+ print()
+ prints('Output written to:', outbook)
+
diff --git a/pool/shard010/Python/0089330_ncbi_header_split.py b/pool/shard010/Python/0089330_ncbi_header_split.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f7f94cd25d07db9adeac3dd3df3252968f95e70
--- /dev/null
+++ b/pool/shard010/Python/0089330_ncbi_header_split.py
@@ -0,0 +1,27 @@
+#!/usr/bin/env python
+import sys
+import copy
+import argparse
+import logging
+from Bio import SeqIO
+
+logging.basicConfig(level=logging.INFO)
+log = logging.getLogger()
+
+
+def split(fasta_file=None, id="merged"):
+ for rec in SeqIO.parse(fasta_file, "fasta"):
+ for header in rec.description.split(">"):
+ nrec = copy.deepcopy(rec)
+ nrec.id = header
+ nrec.description = ""
+ yield nrec
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("fasta_file", type=argparse.FileType("r"))
+
+ args = parser.parse_args()
+ for seq in split(**vars(args)):
+ SeqIO.write([seq], sys.stdout, "fasta")
diff --git a/pool/shard010/Python/0089333_parts.py b/pool/shard010/Python/0089333_parts.py
new file mode 100644
index 0000000000000000000000000000000000000000..5616a4a0db6239460f5afa9b4bfcd33697c208ed
--- /dev/null
+++ b/pool/shard010/Python/0089333_parts.py
@@ -0,0 +1,123 @@
+# ##### BEGIN GPL LICENSE BLOCK #####
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# ##### END GPL LICENSE BLOCK #####
+
+# Copyright (C) 2015: SCS Software
+
+
+from collections import OrderedDict
+from io_scs_tools.utils.printout import lprint
+
+
+class PartsTrans:
+ """Transitional parts class for storing used parts during export.
+
+ This storage shall be used to store parts from SCS Root part inventory. Morover users
+ should be added to each part during collecting of all object to export.
+ Once exporters asks for list of parts, only the parts with at least one user will be returned.
+ """
+
+ def __init__(self, part_inventory):
+ """Creates class instance of parts transitional structure.
+ :param part_inventory: part inventory for SCS Root object
+ :type part_inventory: list[io_scs_tools.properties.object.ObjectPartInventoryItem]
+ """
+ self.__storage = OrderedDict()
+ """:type: collections.OrderedDict[str, int]"""
+ self.__default_part = ""
+
+ for i, part in enumerate(part_inventory):
+ self.__storage[part.name] = 0
+ if i == 0:
+ self.__default_part = part.name
+
+ # if given part inventory won't have any parts inside, then we have to fallback to default part
+ # and properly report the issue
+ if self.__default_part == "":
+ self.__default_part = "defaultpart"
+ lprint("E Parts can't be properly constructed, 'defaultpart' will be used for export!\n\t "
+ "However issue should be addressed to developer...")
+
+ def count(self):
+ """Number of currently stored parts in transitional structure.
+
+ :return: number of currently stored parts
+ :rtype: int
+ """
+ return len(self.get_as_list())
+
+ def is_present(self, part_name):
+ """Tells if given part is present in storage.
+
+ :param part_name: name of the part to search for
+ :type part_name: str
+ :return: True if present; False otherwise
+ :rtype: bool
+ """
+ return part_name in self.__storage
+
+ def add_user(self, obj):
+ """Adds user to validated object part.
+ In case that object part doesn't exists in storage, default part get's a user
+
+ :param obj: mesh or locator blender object from which part should be taken
+ :type obj: bpy.types.Object
+ """
+
+ part_name = self.ensure_part(obj, suppress_warning=True)
+
+ self.__storage[part_name] += 1
+
+ def ensure_part(self, obj, suppress_warning=False):
+ """Ensures and returns part for the given mesh or locator object.
+ If part of the object is not preset in internal parts dictionary,
+ then default part is returned and invalid part name is properly reported to log.
+
+ :param obj: mesh or locator blender object from which part should be taken
+ :type obj: bpy.types.Object
+ :param suppress_warning: flag for suppressing the warning from being raised
+ :type suppress_warning: bool
+ :return: part name of the object or default part if object part name is invalid
+ :rtype: str
+ """
+ part_name = obj.scs_props.scs_part
+
+ if not self.is_present(part_name):
+ if not suppress_warning:
+ lprint("W Invalid part name %r detected on object %r, using first available for export: %r!"
+ "Select object and try to assign part again.",
+ (part_name, obj.name, self.__default_part))
+ part_name = self.__default_part
+
+ return part_name
+
+ def get_as_list(self):
+ """Get stored part names list with at least one user.
+
+ Parts without user shouldn't be exported thus are not returned by this method.
+
+ :return: stored part names list
+ :rtype: list[str]
+ """
+
+ part_list = []
+
+ for part_name in self.__storage:
+ if self.__storage[part_name] > 0:
+ part_list.append(part_name)
+
+ return part_list
diff --git a/pool/shard010/Python/0089336_crawler.py b/pool/shard010/Python/0089336_crawler.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6c1c111ffadc305061642d0a6f07c5dfae58582
--- /dev/null
+++ b/pool/shard010/Python/0089336_crawler.py
@@ -0,0 +1,191 @@
+#!/usr/bin/env python
+'''
+ crawler.py
+ Adam Canady
+ Jeff Ondich, CS257
+ October 4, 2013
+
+ This project is a single-threaded web crawler that returns a number of basic useful functionalities
+ directed towards webmasters or website content managers.
+
+ Usage: python crawler.py [--linklimit int] [--searchprefix string] [--action brokenlinks | outgoing links | summary] url
+
+ Note: an option given as a searchprefix will be tested as being inside a URL string, not just a prefix. This
+ functionality allows the crawler to work on multiple subdomains if just a root domain is given (e.g. carleton.edu).
+ Additionally, all URLs will be processed without a trailing "/" to allow for greater flexibility in intra-site
+ navigation conventions.
+
+ This crawler pauses for 1/10th of a second between requests to avoid imposing denial of service attacks on webservers.
+
+ Some code in this project was derived from Jeff Ondich's web-precrawler.py. Additionally, the
+ breadth-first-search algorithm was derived from the following Stack Overflow article:
+ http://stackoverflow.com/questions/16755546/python-breadth-first-search-capable-of-returning-largest-distance
+'''
+
+import argparse
+import re
+import urllib2
+import urlparse
+import Queue
+import sets
+import time
+
+class Crawl():
+
+ def __init__(self, arguments):
+ self.arguments = arguments
+ self.process_arguments(self.arguments.linklimit, self.arguments.startingURL, self.arguments.searchprefix)
+
+ self.main()
+
+ def process_arguments(self, link_limit, startingURL, search_prefix):
+ ## Take care of arguments ##
+ if not link_limit: self.link_limit = 1000
+ elif "infinity" in link_limit: self.link_limit = float('inf')
+ else: self.link_limit = int(link_limit[0])
+
+ self.startingURL = urllib2.urlopen(startingURL).geturl() # Reconcile initial redirects
+ self.search_prefix = self.startingURL if not search_prefix else search_prefix
+
+ self.urls_to_crawl = Queue.Queue()
+ self.urls_to_crawl.put(self.startingURL)
+ self.queued_for_crawling = set()
+ self.queued_for_crawling.add(self.startingURL)
+ self.links_reverse = {} # links_reverse[link_to] = [link_from]
+ self.crawled_nodes = set()
+ self.crawled_path = {} # crawled_nodes[url] = (path_to_url)
+ self.broken_links = set() # "url_from, url_to"
+
+ def print_broken_links(self):
+ print "Broken Links:"
+ for link in self.broken_links:
+ for backlink in self.links_reverse[link]:
+ print backlink + ", " + link
+
+ def print_outgoing_links(self):
+ print "Outgoing Links:"
+ for link in self.links_reverse:
+ if self.search_prefix not in link:
+ print link
+
+ def print_summary(self):
+ # Process Graph (derived from Stack Overflow post linked above)
+ q = Queue.Queue()
+ q.put((self.startingURL,))
+ visited = set()
+ visited.add(self.startingURL)
+
+ while not q.empty():
+ path = q.get()
+ last_node = path[-1]
+ for node in self.links_reverse.get(last_node,[]):
+ if node not in visited:
+ new_path = path + (node,)
+ q.put(new_path)
+ visited.add(node)
+
+ # Find longest path
+ longest_path_len = 0
+ longest_path = ()
+ for key in self.crawled_path:
+ path = self.crawled_path[key]
+ if len(path) > longest_path_len:
+ longest_path = path
+ longest_path_len = len(path)
+
+ # FilesFound
+ print "FilesFound:", len(self.crawled_nodes)
+
+ # LongestPathDepth
+ print "LongestPathDepth:", longest_path_len
+
+ # LongestPath
+ print "LongestPath:"
+ for node in longest_path:
+ print node
+
+ # CantGetHome
+ print "CantGetHome:"
+
+ for link in self.crawled_nodes - visited - self.broken_links:
+ print link
+
+ def do_crawl(self):
+ while not self.urls_to_crawl.empty() and len(self.crawled_nodes) < self.link_limit:
+ cur_url = self.urls_to_crawl.get()
+ cur_page = Page(cur_url)
+
+ self.crawled_nodes.add(cur_url)
+
+ if cur_page.response_code == 404:
+ self.broken_links.add(cur_url)
+
+ for link in cur_page.links:
+ full_url = urlparse.urljoin(cur_url, link) # Deal with relational links
+
+ if self.search_prefix in full_url and full_url not in self.queued_for_crawling:
+ self.urls_to_crawl.put(full_url)
+ self.queued_for_crawling.add(full_url)
+
+ # Generate Path
+ if self.crawled_path.get(cur_url):
+ self.crawled_path[full_url] = self.crawled_path.get(cur_url) + (full_url,)
+ else:
+ self.crawled_path[full_url] = (self.startingURL, full_url)
+
+ # Links Reverse
+ if full_url in self.links_reverse: self.links_reverse[full_url].append(cur_url)
+ else: self.links_reverse[full_url] = [cur_url]
+
+ time.sleep(0.1)
+
+ def process_crawl(self):
+ # Process the crawl
+ if self.arguments.action and "brokenlinks" in self.arguments.action:
+ self.print_broken_links()
+
+ if self.arguments.action and "outgoinglinks" in self.arguments.action:
+ self.print_outgoing_links()
+
+ if self.arguments.action and "summary" in self.arguments.action:
+ self.print_summary()
+
+ def main(self):
+ self.do_crawl()
+ self.process_crawl()
+
+class Page():
+ def __init__(self, url):
+ self.url = url
+ self.get_page()
+ self.get_links()
+
+ # Derived from Jeff's Code
+ def get_links(self):
+ href_pattern = re.compile(r'
+#
+# This file is part of the BioNEB package released
+# under the MIT license.
+#
+import data
+
+__all__ = ["revcomp", "translate"]
+
+def revcomp(seq):
+ return seq.translate(data.TRANSTABLE)[::-1]
+
+CODON_TABLES = {}
+def translate(seq, table=1, start=0, modifications=None, partial=False):
+ if start > 0:
+ seq = seq[start:]
+ if modifications is None:
+ modifications = []
+ if isinstance(partial, bool):
+ partial = (partial, partial)
+ if table not in CODON_TABLES:
+ raise ValueError("Unknown translation table: %s" % table)
+ if len(seq) < 3:
+ raise ValueError("Sequnce length is too short.")
+ t = CODON_TABLES[table]
+ (acid, is_start) = t.translate(seq[:3], len(seq) == 3)
+ if not partial[0] and is_start:
+ ret = ["M"]
+ elif not partial[0] and start < 1:
+ ret = ["X"]
+ else:
+ ret = [acid]
+ seqlen = len(seq)
+ for i in xrange(3, seqlen-(seqlen%3), 3):
+ ret.append(t.translate(seq[i:i+3], i == len(seq) - 3)[0])
+ ret = ''.join(ret)
+ for m in modifications:
+ if m[0] % 3 != 0:
+ raise ValueError("Invalid modification coordinate: %s" % m[0])
+ idx = m[0]/3
+ ret = "%s%s%s" % (ret[:idx], m[1], ret[idx+1:])
+ if not partial[1] and ret[-1:] == "*":
+ ret = ret[:-1]
+ return ret
+
+class TranslationTable(object):
+ def __init__(self, codons, starts):
+ self.codons = codons
+ self.starts = starts
+ def translate(self, codon, is_stop):
+ assert len(codon) == 3, "Invalid codon: %s" % codon
+ degen = map(lambda b: data.DEGENERATES.get(b, b), codon)
+ degencodons = [
+ "%s%s%s" % (b1, b2, b3)
+ for b1 in degen[0]
+ for b2 in degen[1]
+ for b3 in degen[2]
+ ]
+ acids = set(map(lambda x: self.codons.get(x, 'X'), degencodons))
+ starts = set(map(lambda x: self.starts.get(x, False), degencodons))
+ if len(acids) == 1 and acids == set("*") and not is_stop:
+ acid = "X"
+ elif len(acids) == 1:
+ acid = acids.pop()
+ elif acids == set("DN"):
+ acid = "B"
+ elif acids == set("EQ"):
+ acid = "Z"
+ elif acids == set("IL"):
+ acid = "J"
+ else:
+ acid = "X"
+ if len(starts) > 1:
+ start = False
+ else:
+ start = starts.pop()
+ return (acid, start)
+
+for tbl in [t.split() for t in data.CODON_TABLE_DATA]:
+ tid = int(tbl[0])
+ trans = dict(zip(data.CODONS, tbl[1]))
+ starts = dict(zip(data.CODONS, map(lambda x: x == "M", tbl[2])))
+ CODON_TABLES[tid] = TranslationTable(trans, starts)
diff --git a/pool/shard010/Python/0089344_PointsAlongLines.py b/pool/shard010/Python/0089344_PointsAlongLines.py
new file mode 100644
index 0000000000000000000000000000000000000000..09c11c92d1957c69ef4b3eb46889c6548043e026
--- /dev/null
+++ b/pool/shard010/Python/0089344_PointsAlongLines.py
@@ -0,0 +1,125 @@
+# -*- coding: utf-8 -*-
+
+"""
+***************************************************************************
+ PointsAlongLines.py
+ ---------------------
+ Date : Janaury 2015
+ Copyright : (C) 2015 by Giovanni Manghi
+ Email : giovanni dot manghi at naturalgis dot pt
+***************************************************************************
+* *
+* This program is free software; you can redistribute it and/or modify *
+* it under the terms of the GNU General Public License as published by *
+* the Free Software Foundation; either version 2 of the License, or *
+* (at your option) any later version. *
+* *
+***************************************************************************
+"""
+
+__author__ = 'Giovanni Manghi'
+__date__ = 'January 2015'
+__copyright__ = '(C) 2015, Giovanni Manghi'
+
+from qgis.core import (QgsProcessingException,
+ QgsProcessingParameterFeatureSource,
+ QgsProcessingParameterString,
+ QgsProcessingParameterNumber,
+ QgsProcessingParameterVectorDestination,
+ QgsProcessingParameterDefinition,
+ QgsProcessing)
+
+from processing.algs.gdal.GdalAlgorithm import GdalAlgorithm
+from processing.algs.gdal.GdalUtils import GdalUtils
+
+from processing.tools.system import isWindows
+
+
+class PointsAlongLines(GdalAlgorithm):
+ INPUT = 'INPUT'
+ GEOMETRY = 'GEOMETRY'
+ DISTANCE = 'DISTANCE'
+ OPTIONS = 'OPTIONS'
+ OUTPUT = 'OUTPUT'
+
+ def __init__(self):
+ super().__init__()
+
+ def initAlgorithm(self, config=None):
+ self.addParameter(QgsProcessingParameterFeatureSource(self.INPUT,
+ self.tr('Input layer'),
+ [QgsProcessing.TypeVectorLine]))
+ self.addParameter(QgsProcessingParameterString(self.GEOMETRY,
+ self.tr('Geometry column name'),
+ defaultValue='geometry'))
+ self.addParameter(QgsProcessingParameterNumber(self.DISTANCE,
+ self.tr('Distance from line start represented as fraction of line length'),
+ type=QgsProcessingParameterNumber.Double,
+ minValue=0,
+ maxValue=1,
+ defaultValue=0.5))
+
+ options_param = QgsProcessingParameterString(self.OPTIONS,
+ self.tr('Additional creation options'),
+ defaultValue='',
+ optional=True)
+ options_param.setFlags(options_param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
+ self.addParameter(options_param)
+
+ self.addParameter(QgsProcessingParameterVectorDestination(self.OUTPUT,
+ self.tr('Points along lines'),
+ QgsProcessing.TypeVectorPoint))
+
+ def name(self):
+ return 'pointsalonglines'
+
+ def displayName(self):
+ return self.tr('Points along lines')
+
+ def group(self):
+ return self.tr('Vector geoprocessing')
+
+ def groupId(self):
+ return 'vectorgeoprocessing'
+
+ def commandName(self):
+ return 'ogr2ogr'
+
+ def getConsoleCommands(self, parameters, context, feedback, executing=True):
+ source = self.parameterAsSource(parameters, self.INPUT, context)
+ if source is None:
+ raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))
+
+ fields = source.fields()
+ ogrLayer, layerName = self.getOgrCompatibleSource(self.INPUT, parameters, context, feedback, executing)
+ distance = self.parameterAsDouble(parameters, self.DISTANCE, context)
+ geometry = self.parameterAsString(parameters, self.GEOMETRY, context)
+ outFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
+ self.setOutputValue(self.OUTPUT, outFile)
+ options = self.parameterAsString(parameters, self.OPTIONS, context)
+
+ output, outputFormat = GdalUtils.ogrConnectionStringAndFormat(outFile, context)
+
+ other_fields_exist = any(
+ f for f in fields
+ if f.name() != geometry
+ )
+
+ other_fields = ',*' if other_fields_exist else ''
+
+ arguments = [
+ output,
+ ogrLayer,
+ '-dialect',
+ 'sqlite',
+ '-sql',
+ f'SELECT ST_Line_Interpolate_Point({geometry}, {distance}) AS {geometry}{other_fields} FROM "{layerName}"'
+ ]
+
+ if options:
+ arguments.append(options)
+
+ if outputFormat:
+ arguments.append(f'-f {outputFormat}')
+
+ return ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]
diff --git a/pool/shard010/Python/0089346_fio-postprocess-viz.py b/pool/shard010/Python/0089346_fio-postprocess-viz.py
new file mode 100644
index 0000000000000000000000000000000000000000..974cb748c4407049f3abe3ac5aa5d94b79146921
--- /dev/null
+++ b/pool/shard010/Python/0089346_fio-postprocess-viz.py
@@ -0,0 +1,114 @@
+#!/usr/bin/env python3
+
+import sys
+from os.path import join, basename
+from configparser import ConfigParser
+
+_prog = basename(sys.argv[0])
+
+html = """
+
+ Latency
+
+
+
+
+
+
+
+
+
+
+
+
+
+"""
+
+
+def main(ctx):
+ columns = ["samples"]
+ plot_files = ["samples.log"]
+ for pct in ctx.percentiles:
+ if pct == 0:
+ col = "min"
+ elif pct == 50.0:
+ col = "median"
+ elif pct == 100.0:
+ col = "max"
+ else:
+ col = "p{:1.0f}".format(pct)
+ columns.append(col)
+ plot_files.append("{}.log".format(col))
+ columns_l = len(columns)
+ with open(join(ctx.DIR, "hist.csv"), "r") as csv:
+ line = csv.readline()
+ # FIXME: this check for the string "min, median" is a little fragile
+ while line and not line.__contains__("min, median"):
+ line = csv.readline()
+ if not line:
+ print(
+ "[{}] ERROR: hit end of file without seeing header".format(_prog),
+ file=sys.stderr,
+ )
+ return 1
+ out_files = [open(join(ctx.DIR, pf), "w") for pf in plot_files]
+ for i in range(columns_l):
+ out_files[i].write("#LABEL:{}\n".format(columns[i]))
+ for line in csv:
+ vs = line.split(", ")
+ for i in range(columns_l):
+ out_files[i].write("{:d} {}\n".format(int(vs[0]), vs[i + 1].rstrip()))
+ for i in range(columns_l):
+ out_files[i].close()
+ chart_type = "xy"
+ cp = ConfigParser(allow_no_value=True)
+ cp.read(ctx.job_file)
+ for s in cp.sections():
+ try:
+ cp.get(s, "log_unix_epoch")
+ except Exception:
+ pass
+ else:
+ chart_type = "timeseries"
+ result_file_name = join(ctx.DIR, "results.html")
+ print("[{}] Chart Type: {} ({})".format(_prog, chart_type, result_file_name))
+ with open(result_file_name, "w") as fp:
+ list_of_plot_file_quoted_strings = ['"{}"'.format(pf) for pf in plot_files]
+ # Note we don't plot samples.log
+ concatenated_plot_file_quoted_strings = ", ".join(
+ list_of_plot_file_quoted_strings[1:]
+ )
+ fp.write(html.format(chart_type, concatenated_plot_file_quoted_strings))
+ return 0
+
+
+if __name__ == "__main__":
+ import argparse
+
+ p = argparse.ArgumentParser(_prog)
+ arg = p.add_argument
+ arg("-j", "--job-file", help="fio job file")
+ arg(
+ "-t",
+ "--time-quantum",
+ nargs=1,
+ type=int,
+ default="1",
+ help="time quantum given to fio-histo-log-pctiles.py",
+ )
+ arg(
+ "-p",
+ "--percentiles",
+ nargs="+",
+ type=float,
+ default=[0.0, 50.0, 95.0, 99.0, 100.0],
+ help="percentiles given to fio-histo-log-pctiles.py",
+ )
+ arg("DIR", help="results directory")
+ ret_status = main(p.parse_args())
+ sys.exit(ret_status)
diff --git a/pool/shard010/Python/0089353_work_type.py b/pool/shard010/Python/0089353_work_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..61eec9a03e243e48bd6a8caf14347b5828f1d93a
--- /dev/null
+++ b/pool/shard010/Python/0089353_work_type.py
@@ -0,0 +1,43 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+# OpenERP, Open Source Management Solution Addon
+# Copyright (C) 2009-2013 IRSID (),
+# Paul Korotkov (korotkov.paul@gmail.com).
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
+#
+##############################################################################
+
+from openerp import models, fields
+
+class edu_work_type(models.Model):
+ _name = 'edu.work.type'
+ _description = 'Work Type'
+ # Fields
+ name = fields.Char(
+ string = 'Name',
+ required = True,
+ )
+ code = fields.Char(
+ string = 'Code',
+ required = True,
+ )
+ ind_work = fields.Boolean(
+ string = 'Individual Work',
+ )
+ scale = fields.Many2one(
+ 'edu.scale',
+ string = 'Rating Scale',
+ )
diff --git a/pool/shard010/Python/0089356_mesh_vertex.py b/pool/shard010/Python/0089356_mesh_vertex.py
new file mode 100644
index 0000000000000000000000000000000000000000..09284edad129f5dcddc5f97eb8aa865766dfcc7d
--- /dev/null
+++ b/pool/shard010/Python/0089356_mesh_vertex.py
@@ -0,0 +1,124 @@
+#################################################################################
+# Copyright 2014 See AUTHORS file.
+#
+# Licensed under the GNU General Public License Version 3.0 (the "LICENSE");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.gnu.org/licenses/gpl-3.0.txt
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#################################################################################
+
+from mathutils import Vector, Color
+
+class MeshVertex:
+ """Represents a vertex we can export, with facilities to compare two of them"""
+
+ _position = None
+ @property
+ def position(self):
+ return self._position
+ @position.setter
+ def position(self,position):
+ if not isinstance(position, Vector):
+ raise TypeError("position needs to be a mathutils.Vector")
+ self._position = position
+
+ _normal = None
+ @property
+ def normal(self):
+ return self._normal
+ @normal.setter
+ def normal(self,normal):
+ if not isinstance(normal, Vector):
+ raise TypeError("normal needs to be a mathutils.Vector")
+ self._normal = normal
+
+ _tangent = None
+ @property
+ def tangent(self):
+ return self._tangent
+ @tangent.setter
+ def tangent(self,tangent):
+ if tangent != None and not isinstance(tangent, Vector):
+ raise TypeError("tangent needs to be a mathutils.Vector")
+ self._tangent = tangent
+
+ _binormal = None
+ @property
+ def binormal(self):
+ return self._binormal
+ @binormal.setter
+ def binormal(self,binormal):
+ if binormal != None and not isinstance(binormal, Vector):
+ raise TypeError("binormal needs to be a mathutils.Vector")
+ self._binormal = binormal
+
+ _texcoord = None
+ @property
+ def texcoord(self):
+ return self._texcoord
+ @texcoord.setter
+ def texcoord(self,texcoord):
+ if texcoord != None and not isinstance(texcoord, list):
+ raise TypeError("texcoord needs to be a list of vectors (mathutils.Vector) or None")
+ self._texcoord = texcoord
+
+ _blendweight = None
+ @property
+ def blendweight(self):
+ return self._blendweight
+ @blendweight.setter
+ def blendweight(self,blendweight):
+ if blendweight != None and not isinstance(blendweight, list):
+ raise TypeError("blendweight needs to be a list of vectors (mathutils.Vector) or None")
+ self._blendweight = blendweight
+
+ def __init__(self, position, normal, tangent = None, binormal = None, texcoord = None, blendweight = None):
+ self.position = position
+ self.normal = normal
+ self.tangent = tangent
+ self.binormal = binormal
+ self.texcoord = texcoord
+ self.blendweight = blendweight
+
+ _color = None
+ @property
+ def color(self):
+ return self._color
+ @color.setter
+ def color(self,color):
+ if not isinstance(color, Color):
+ raise TypeError("color needs to be a mathutils.Color")
+ self._color = color
+
+ def compare(self, another):
+ """Compare two vertices, return True if they have the same value for all fields"""
+ if another == None or not isinstance(another, MeshVertex):
+ return False
+
+ comparison = self.position == another.position \
+ and self.normal == another.normal \
+ and self.color == another.color \
+ and self.tangent == another.tangent \
+ and self.binormal == another.binormal \
+ and self.texcoord == another.texcoord \
+ and self.blendweight == another.blendweight
+
+ return comparison
+
+ def normalize_weights(self):
+ """Normalize all bone weights in this vertex so that they all sum to 1 (one)."""
+ if self.blendweight != None:
+ total_weight = 0.0
+ for weight in self.blendweight:
+ total_weight = total_weight + weight[1]
+
+ if total_weight != 0.0:
+ for weight in self.blendweight:
+ weight[1] = weight[1] / total_weight
\ No newline at end of file
diff --git a/pool/shard010/Python/0089358_dependencies.py b/pool/shard010/Python/0089358_dependencies.py
new file mode 100644
index 0000000000000000000000000000000000000000..6dd372a76fa1e57c5e59da49794f2325248130a0
--- /dev/null
+++ b/pool/shard010/Python/0089358_dependencies.py
@@ -0,0 +1,68 @@
+from galaxy.tools.deps.requirements import ToolRequirement
+from galaxy.util import bunch
+
+
+class DependenciesDescription(object):
+ """ Capture (in a readily serializable way) context related a tool
+ dependencies - both the tool's listed requirements and the tool shed
+ related context required to resolve dependencies via the
+ ToolShedPackageDependencyResolver.
+
+ This is meant to enable remote resolution of dependencies, by the Pulsar or
+ other potential remote execution mechanisms.
+ """
+
+ def __init__(self, requirements=[], installed_tool_dependencies=[]):
+ self.requirements = requirements
+ # tool shed installed tool dependencies...
+ self.installed_tool_dependencies = installed_tool_dependencies
+
+ def to_dict(self):
+ return dict(
+ requirements=[r.to_dict() for r in self.requirements],
+ installed_tool_dependencies=[DependenciesDescription._toolshed_install_dependency_to_dict(d) for d in self.installed_tool_dependencies]
+ )
+
+ @staticmethod
+ def from_dict(as_dict):
+ if as_dict is None:
+ return None
+
+ requirements_dicts = as_dict.get('requirements', [])
+ requirements = [ToolRequirement.from_dict(r) for r in requirements_dicts]
+ installed_tool_dependencies_dicts = as_dict.get('installed_tool_dependencies', [])
+ installed_tool_dependencies = map(DependenciesDescription._toolshed_install_dependency_from_dict, installed_tool_dependencies_dicts)
+ return DependenciesDescription(
+ requirements=requirements,
+ installed_tool_dependencies=installed_tool_dependencies
+ )
+
+ @staticmethod
+ def _toolshed_install_dependency_from_dict(as_dict):
+ # Rather than requiring full models in Pulsar, just use simple objects
+ # containing only properties and associations used to resolve
+ # dependencies for tool execution.
+ repository_object = bunch.Bunch(
+ name=as_dict['repository_name'],
+ owner=as_dict['repository_owner'],
+ installed_changeset_revision=as_dict['repository_installed_changeset'],
+ )
+ dependency_object = bunch.Bunch(
+ name=as_dict['dependency_name'],
+ version=as_dict['dependency_version'],
+ type=as_dict['dependency_type'],
+ tool_shed_repository=repository_object,
+ )
+ return dependency_object
+
+ @staticmethod
+ def _toolshed_install_dependency_to_dict(tool_dependency):
+ tool_shed_repository = tool_dependency.tool_shed_repository
+ return dict(
+ dependency_name=tool_dependency.name,
+ dependency_version=tool_dependency.version,
+ dependency_type=tool_dependency.type,
+ repository_name=tool_shed_repository.name,
+ repository_owner=tool_shed_repository.owner,
+ repository_installed_changeset=tool_shed_repository.installed_changeset_revision,
+ )
diff --git a/pool/shard010/Python/0089360_file_properties.py b/pool/shard010/Python/0089360_file_properties.py
new file mode 100644
index 0000000000000000000000000000000000000000..a690a1f18ce066ebf3eaa6f0075f79f890ccd776
--- /dev/null
+++ b/pool/shard010/Python/0089360_file_properties.py
@@ -0,0 +1,65 @@
+"""
+# Majic
+# Copyright (C) 2015 CEH
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+"""
+
+
+class FileProperties(object):
+ """
+ Important properties of a file needing to be synchronised
+ """
+
+ def __init__(self, file_path, owner, is_published, is_public):
+ """
+ constructor
+ :param file_path: path to the file relative to the root
+ :param owner: userid of the user who owns the file
+ :param is_published: True if the file is published, false otherwise (i.e. readable by majic users)
+ :param is_public: True if the file is public, false otherwise (i.e. readable by everyone)
+ """
+ self.file_path = file_path
+ self.owner = owner
+ self.is_published = is_published
+ self.is_public = is_public
+
+ def __repr__(self):
+ return "{} (model_owner:{}, published?:{}, public?:{})"\
+ .format(self.file_path, self.owner, self.is_published, self.is_public)
+
+ def __cmp__(self, other):
+ """
+ Compare two File properties
+ Order is filepath, model_owner, is_publoshed, is_publis
+ :param other: other File Property to compare
+ :return: negative integer if self < other, zero if self == other, a positive integer if self > other
+ """
+ if self.file_path != other.file_path:
+ if self.file_path < other.file_path:
+ return -1
+ else:
+ return 1
+
+ if self.owner != other.owner:
+ if self.owner < other.owner:
+ return -1
+ else:
+ return 1
+
+ result = self.is_published.__cmp__(other.is_published)
+ if result == 0:
+ result = self.is_public.__cmp__(other.is_public)
+ return result
\ No newline at end of file
diff --git a/pool/shard010/Python/0089367_trajectory_gps.py b/pool/shard010/Python/0089367_trajectory_gps.py
new file mode 100644
index 0000000000000000000000000000000000000000..924c4be86a73e23ffe7f5da606010e8d34bf7040
--- /dev/null
+++ b/pool/shard010/Python/0089367_trajectory_gps.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python
+
+# ---------------------------------------------------------------------------
+# Licensing Information: You are free to use or extend these projects for
+# education or reserach purposes provided that (1) you retain this notice
+# and (2) you provide clear attribution to UC Berkeley, including a link
+# to http://barc-project.com
+#
+# Author: J. Gonzales
+# Email: jon.gonzales@berkeley.edu
+#
+# Note: Code adapted from ideas in code from J. Noonan (jpnoonan@berkeley.edu)
+#
+# This code provides a way to see the car's trajectory, orientation, and velocity profile in
+# real time with referenced to the track defined a priori.
+#
+# ---------------------------------------------------------------------------
+
+import rospy
+import matplotlib.pyplot as plt
+from sensor_msgs.msg import NavSatFix
+from lla2flat import lla2flat
+
+class gps_viewer():
+ def __init__(self):
+ # define variables
+ self.lat0 = None
+ self.lng0 = None
+ self.xt = None
+ self.yt = None
+
+ # launch figure
+ self.ax1 = plt.subplot()
+ self.ax1.grid('on')
+ self.ax1.axis('equal')
+ self.ax1.set_title("Data from GPS")
+ self.xlim = 50.0
+ self.ylim = 50.0
+ plt.ion()
+
+ rospy.Subscriber("/fix", NavSatFix, self.gps_callback)
+ rospy.on_shutdown(self.show)
+ loop_rate = 50
+ rate = rospy.Rate(loop_rate)
+
+ while not rospy.is_shutdown():
+ self.update_figure()
+
+ def show(self):
+ plt.show()
+
+ def gps_callback(self, data):
+ lat = data.latitude
+ lng = data.longitude
+ alt = data.altitude
+
+ if self.lat0 == None:
+ self.lat0 = lat
+ self.lng0 = lng
+
+ (self.xt, self.yt,_) = lla2flat((lat,lng,alt), (self.lat0, self.lng0), 0, 100)
+ print "coordinates : (%f,%f) " % (self.xt, self.yt)
+
+
+ def update_figure(self):
+ # draw position
+ if self.xt != None:
+ self.ax1.plot( 0, 0, 'ko')
+ self.ax1.plot( self.xt, self.yt, 'bo')
+
+ # set axis
+ self.ax1.set_xlim([-self.xlim, self.xlim])
+ self.ax1.set_ylim([-self.ylim, self.ylim])
+
+ # clear drawing and pause briefly
+ plt.pause(0.01)
+
+if __name__ == '__main__':
+ # initialize the node
+ rospy.init_node('gps_viewer', anonymous=True)
+
+ try:
+ node = gps_viewer()
+ except rospy.ROSInterruptException:
+ pass
diff --git a/pool/shard010/Python/0089369_14-Longest_Collatz_sequence.py b/pool/shard010/Python/0089369_14-Longest_Collatz_sequence.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b29a25a65d95b49954b1baae6e20527ab5d81a6
--- /dev/null
+++ b/pool/shard010/Python/0089369_14-Longest_Collatz_sequence.py
@@ -0,0 +1,52 @@
+"""
+The following iterative sequence is defined for the set of positive integers:
+
+n -> n/2 (n is even)
+n -> 3n + 1 (n is odd)
+
+Using the rule above and starting with 13, we generate the following sequence:
+
+13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
+It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms.
+Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
+
+Which starting number, under one million, produces the longest chain?
+
+NOTE: Once the chain starts the terms are allowed to go above one million.
+"""
+
+chainLengths = {}
+longestChain = 0
+longestChainStartingNumber = 0
+
+def get_next_collatz_number(number):
+ if number % 2 == 0:
+ return number / 2
+ else:
+ return number * 3 + 1
+
+
+def get_collatz_chain_length(number):
+ chain_length = 0
+ original_number = number
+
+ while number > 1:
+ if number in chainLengths:
+ chain_length += chainLengths[number]
+ break
+ else:
+ number = get_next_collatz_number(number)
+ chain_length += 1
+
+ chainLengths[original_number] = chain_length
+ return chain_length
+
+
+for i in xrange(2, 1000 * 1000):
+ currentLength = get_collatz_chain_length(i)
+
+ if currentLength > longestChain:
+ longestChain = currentLength
+ longestChainStartingNumber = i
+
+print str(longestChainStartingNumber)
\ No newline at end of file
diff --git a/pool/shard010/Python/0089380_merge_solution.py b/pool/shard010/Python/0089380_merge_solution.py
new file mode 100644
index 0000000000000000000000000000000000000000..af1ea71d4b08452d7ce313ef833c378fb537870e
--- /dev/null
+++ b/pool/shard010/Python/0089380_merge_solution.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+
+## \file merge_solution.py
+# \brief Python script for merging of the solution files.
+# \author F. Palacios
+# \version 7.0.3 "Blackbird"
+#
+# SU2 Project Website: https://su2code.github.io
+#
+# The SU2 Project is maintained by the SU2 Foundation
+# (http://su2foundation.org)
+#
+# Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md)
+#
+# SU2 is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# SU2 is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with SU2. If not, see .
+
+from optparse import OptionParser
+import SU2
+
+# -------------------------------------------------------------------
+# Main
+# -------------------------------------------------------------------
+
+def main():
+
+ parser = OptionParser()
+ parser.add_option("-f", "--file", dest="filename",
+ help="read config from FILE", metavar="FILE")
+ parser.add_option("-n", "--partitions", dest="partitions", default=-1,
+ help="number of PARTITIONS", metavar="PARTITIONS")
+
+ (options, args)=parser.parse_args()
+ options.partitions = int(options.partitions)
+
+ merge_solution( options.filename ,
+ options.partitions )
+
+
+# -------------------------------------------------------------------
+# MERGE SOLUTION
+# -------------------------------------------------------------------
+
+def merge_solution( filename ,
+ partitions = -1 ):
+
+ config = SU2.io.Config(filename)
+
+ if partitions > -1 :
+ config.NUMBER_PART = partitions
+
+ SU2.run.merge(config)
+
+#: def merge_solution()
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard010/Python/0089388_api_admin_controller.py b/pool/shard010/Python/0089388_api_admin_controller.py
new file mode 100644
index 0000000000000000000000000000000000000000..10ef4cd365a637f69730e1396cd5db6448edafcc
--- /dev/null
+++ b/pool/shard010/Python/0089388_api_admin_controller.py
@@ -0,0 +1,49 @@
+import json
+import logging
+
+from api.apiv3.api_base_controller import ApiBaseController
+from models.sitevar import Sitevar
+
+
+class ApiAdminController(ApiBaseController):
+ """
+ Allow special admin-only endpoints for APIv3
+ """
+ REQUIRE_ADMIN_AUTH = True
+
+ def get(self, *args, **kw):
+ # We want these to be POST-only
+ self.abort(405)
+
+
+class ApiAdminSetBuildInfo(ApiAdminController):
+ """
+ A controller that allows us to set data about the currently deployed version
+ """
+
+ def _track_call(self):
+ self._track_call_defer('set-build-status', '')
+
+ def _render(self):
+ data = json.loads(self.request.body)
+ current_commit_sha = data.get('current_commit', '')
+ commit_time = data.get('commit_time', '')
+ deploy_time = data.get('deploy_time', '')
+ travis_job = data.get('travis_job', '')
+ endpoints_sha = data.get('endpoints_sha', '')
+ tbaClient_endpoints_sha = data.get('tbaClient_endpoints_sha', '')
+
+ web_info = {
+ 'current_commit': current_commit_sha,
+ 'commit_time': commit_time,
+ 'deploy_time': deploy_time,
+ 'travis_job': travis_job,
+ 'endpoints_sha': endpoints_sha,
+ 'tbaClient_endpoints_sha': tbaClient_endpoints_sha,
+ }
+
+ status_sitevar = Sitevar.get_or_insert('apistatus', values_json='{}')
+ contents = status_sitevar.contents
+ contents['web'] = web_info
+ status_sitevar.contents = contents
+ status_sitevar.put()
diff --git a/pool/shard010/Python/0089393_test_packet.py b/pool/shard010/Python/0089393_test_packet.py
new file mode 100644
index 0000000000000000000000000000000000000000..18799a538492fdb9efe8f4b02ef8655728dddca0
--- /dev/null
+++ b/pool/shard010/Python/0089393_test_packet.py
@@ -0,0 +1,184 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Maintainer: Aaron Welch
+# Based on code written by Jed Smith who based it on
+# code written by Alex Polvi
+#
+
+import sys
+import unittest
+from libcloud.utils.py3 import httplib
+
+from libcloud.compute.drivers.packet import PacketNodeDriver
+from libcloud.compute.base import Node, KeyPair
+from libcloud.compute.types import NodeState
+
+from libcloud.test import MockHttp
+from libcloud.test.compute import TestCaseMixin
+from libcloud.test.file_fixtures import ComputeFileFixtures
+
+
+class PacketTest(unittest.TestCase, TestCaseMixin):
+ def setUp(self):
+ PacketNodeDriver.connectionCls.conn_class = PacketMockHttp
+ self.driver = PacketNodeDriver('foo')
+
+ def test_list_nodes(self):
+ nodes = self.driver.list_nodes('project-id')
+ self.assertEqual(len(nodes), 1)
+ node = nodes[0]
+ self.assertEqual(node.id, '1e52437e-bbbb-cccc-dddd-74a9dfd3d3bb')
+ self.assertEqual(node.name, 'test-node')
+ self.assertEqual(node.state, NodeState.RUNNING)
+ self.assertTrue('147.75.255.255' in node.public_ips)
+ self.assertTrue('2604:EEEE::EE' in node.public_ips)
+ self.assertTrue('10.0.0.255' in node.private_ips)
+ self.assertEqual(node.extra['created_at'], '2015-05-03T15:50:49Z')
+ self.assertEqual(node.extra['updated_at'], '2015-05-03T16:00:08Z')
+ self.assertEqual(node.extra['billing_cycle'], 'hourly')
+ self.assertEqual(node.extra['locked'], False)
+ self.assertEqual(node.size.id, 'baremetal_1')
+ self.assertEqual(node.size.name, 'Type 1')
+ self.assertEqual(node.size.ram, 16384)
+ self.assertEqual(node.size.disk, 240)
+ self.assertEqual(node.size.price, 0.4)
+ self.assertEqual(node.size.extra['line'], 'baremetal')
+ self.assertEqual(node.image.id, 'ubuntu_14_04')
+ self.assertEqual(node.image.name, 'Ubuntu 14.04 LTS')
+ self.assertEqual(node.image.extra['distro'], 'ubuntu')
+ self.assertEqual(node.image.extra['version'], '14.04')
+
+ def test_list_nodes_response(self):
+ nodes = self.driver.list_nodes('project-id')
+ self.assertTrue(isinstance(nodes, list))
+ for node in nodes:
+ self.assertTrue(isinstance(node, Node))
+
+ def test_list_locations(self):
+ locations = self.driver.list_locations()
+ self.assertEqual(len(locations), 1)
+
+ def test_list_images(self):
+ images = self.driver.list_images()
+ self.assertEqual(len(images), 4)
+
+ def test_list_sizes(self):
+ sizes = self.driver.list_sizes()
+ self.assertEqual(len(sizes), 1)
+
+ def test_create_node(self):
+ node = self.driver.create_node(ex_project_id="project-id",
+ name="node-name",
+ size=self.driver.list_sizes()[0],
+ image=self.driver.list_images()[0],
+ location=self.driver.list_locations()[
+ 0])
+ self.assertTrue(isinstance(node, Node))
+
+ def test_create_node_response(self):
+ size = self.driver.list_sizes()[0]
+ image = self.driver.list_images()[0]
+ location = self.driver.list_locations()[0]
+ node = self.driver.create_node(ex_project_id="project-id",
+ name='node-name',
+ image=image,
+ size=size,
+ location=location)
+ self.assertTrue(isinstance(node, Node))
+
+ def test_reboot_node(self):
+ node = self.driver.list_nodes('project-id')[0]
+ self.driver.reboot_node(node)
+
+ def test_reboot_node_response(self):
+ node = self.driver.list_nodes('project-id')[0]
+ self.driver.reboot_node(node)
+
+ def test_destroy_node(self):
+ node = self.driver.list_nodes('project-id')[0]
+ self.driver.destroy_node(node)
+
+ def test_destroy_node_response(self):
+ node = self.driver.list_nodes('project-id')[0]
+ self.driver.destroy_node(node)
+
+ def test_list_key_pairs(self):
+ keys = self.driver.list_key_pairs()
+ self.assertEqual(len(keys), 3)
+
+ def test_create_key_pair(self):
+ key = self.driver.create_key_pair(name="sshkey-name",
+ public_key="ssh-rsa AAAAB3NzaC1yc2EA\
+AAADAQABAAABAQDI4pIqzpb5g3992h+yr527VRcaB68KE4vPjWPPoiQws49KIs2NMcOzS9QE4641uW\
+1u5ML2HgQdfYKMF/YFGnI1Y6xV637DjhDyZYV9LasUH49npSSJjsBcsk9JGfUpNAOdcgpFzK8V90ei\
+OrOC5YncxdwwG8pwjFI9nNVPCl4hYEu1iXdyysHvkFfS2fklsNjLWrzfafPlaen+qcBxygCA0sFdW/\
+7er50aJeghdBHnE2WhIKLUkJxnKadznfAge7oEe+3LLAPfP+3yHyvp2+H0IzmVfYvAjnzliYetqQ8p\
+g5ZW2BiJzvqz5PebGS70y/ySCNW1qQmJURK/Wc1bt9en root@libcloud")
+ self.assertTrue(isinstance(key, KeyPair))
+
+ def test_delete_key_pair(self):
+ key = self.driver.list_key_pairs()[0]
+ self.driver.delete_key_pair(key)
+
+
+class PacketMockHttp(MockHttp):
+ fixtures = ComputeFileFixtures('packet')
+
+ def _facilities(self, method, url, body, headers):
+ body = self.fixtures.load('facilities.json')
+ return (httplib.OK, body, {}, httplib.responses[httplib.OK])
+
+ def _plans(self, method, url, body, headers):
+ body = self.fixtures.load('plans.json')
+ return (httplib.OK, body, {}, httplib.responses[httplib.OK])
+
+ def _operating_systems(self, method, url, body, headers):
+ body = self.fixtures.load('operatingsystems.json')
+ return (httplib.OK, body, {}, httplib.responses[httplib.OK])
+
+ def _ssh_keys(self, method, url, body, headers):
+ if method == 'GET':
+ body = self.fixtures.load('sshkeys.json')
+ return (httplib.OK, body, {}, httplib.responses[httplib.OK])
+ if method == 'POST':
+ body = self.fixtures.load('sshkey_create.json')
+ return (httplib.OK, body, {}, httplib.responses[httplib.OK])
+
+ def _ssh_keys_2c1a7f23_1dc6_4a37_948e_d9857d9f607c(self, method, url,
+ body, headers):
+ if method == 'DELETE':
+ return (httplib.OK, '', {}, httplib.responses[httplib.OK])
+
+ def _projects_project_id_devices(self, method, url, body, headers):
+ if method == 'POST':
+ body = self.fixtures.load('device_create.json')
+ return (httplib.OK, body, {}, httplib.responses[httplib.OK])
+ elif method == 'GET':
+ body = self.fixtures.load('devices.json')
+ return (httplib.OK, body, {}, httplib.responses[httplib.OK])
+
+ def _devices_1e52437e_bbbb_cccc_dddd_74a9dfd3d3bb(self, method, url,
+ body, headers):
+ if method == 'DELETE':
+ return (httplib.OK, '', {}, httplib.responses[httplib.OK])
+
+ def _devices_1e52437e_bbbb_cccc_dddd_74a9dfd3d3bb_actions(
+ self, method, url, body, headers):
+ return (httplib.OK, '', {}, httplib.responses[httplib.OK])
+
+
+if __name__ == '__main__':
+ sys.exit(unittest.main())
diff --git a/pool/shard010/Python/0089394_DerivedPulses.py b/pool/shard010/Python/0089394_DerivedPulses.py
new file mode 100644
index 0000000000000000000000000000000000000000..222ed6d3d5843511eb496f6177327570d46e4024
--- /dev/null
+++ b/pool/shard010/Python/0089394_DerivedPulses.py
@@ -0,0 +1,277 @@
+# -*- coding: utf-8 -*-
+"""
+Created on Thu Jun 04 13:48:11 2015
+This file is part of pyNLO.
+
+ pyNLO is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ pyNLO is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with pyNLO. If not, see .
+@author: ycasg
+"""
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import numpy as np
+from scipy.interpolate import interp1d
+from pynlo.util import IFFT_t
+from pynlo.light.PulseBase import Pulse
+
+class SechPulse(Pulse):
+ def __init__(self, power, T0_ps, center_wavelength_nm,
+ time_window_ps = 10., frep_MHz = 100., NPTS = 2**10,
+ GDD = 0, TOD = 0, chirp2 = 0, chirp3 = 0,
+ power_is_avg = False):
+ """Generate a squared-hyperbolic secant "sech" pulse
+ A(t) = sqrt(P0 [W]) * sech(t/T0 [ps])
+ centered at wavelength center_wavelength_nm (nm).
+ time_window (ps) sets temporal grid size.
+
+ Optional GDD and TOD are in ps^2 and ps^3.
+
+ Note: The full-width-at-half-maximum (FWHM) is given by
+ T0_ps * 1.76
+ """
+ Pulse.__init__(self, frep_MHz = frep_MHz, n = NPTS)
+ # make sure we weren't passed mks units
+ assert (center_wavelength_nm > 1.0)
+ assert (time_window_ps > 1.0 )
+ self.set_center_wavelength_nm(center_wavelength_nm)
+ self.set_time_window_ps(time_window_ps)
+
+ ### Generate pulse
+ if not power_is_avg:
+ # from https://www.rp-photonics.com/sech2_shaped_pulses.html
+ self.set_AT( np.sqrt(power)/np.cosh(self.T_ps/T0_ps) )
+ else:
+ self.set_AT( 1 / np.cosh(self.T_ps/T0_ps) )
+ self.set_AT(self.AT * np.sqrt( power / ( frep_MHz*1.0e6 * self.calc_epp()) ))
+
+ self.chirp_pulse_W(GDD, TOD)
+ self.chirp_pulse_T(chirp2, chirp3, T0_ps)
+
+class GaussianPulse(Pulse):
+ def __init__(self, power, T0_ps, center_wavelength_nm,
+ time_window_ps = 10., frep_MHz = 100., NPTS = 2**10,
+ GDD = 0, TOD = 0, chirp2 = 0, chirp3 = 0,
+ power_is_avg = False):
+ """Generate Gaussian pulse A(t) = sqrt(peak_power[W]) *
+ exp( -(t/T0 [ps])^2 / 2 ) centered at wavelength
+ center_wavelength_nm (nm). time_window (ps) sets temporal grid
+ size. Optional GDD and TOD are in ps^2 and ps^3.
+
+ Note: For this definition of a Gaussian pulse, T0_ps is the
+ full-width-at-half-maximum (FWHM) of the pulse.
+ """
+
+ Pulse.__init__(self, frep_MHz = frep_MHz, n = NPTS)
+ # make sure we weren't passed mks units
+ assert (center_wavelength_nm > 1.0)
+ assert (time_window_ps > 1.0 )
+ self.set_center_wavelength_nm(center_wavelength_nm)
+ self.set_time_window_ps(time_window_ps)
+
+ GDD = GDD
+ TOD = TOD
+
+ # from https://www.rp-photonics.com/gaussian_pulses.html
+ self.set_AT( np.sqrt(power) * np.exp(-2.77*0.5*self.T_ps**2/(T0_ps**2)) ) # input field (W^0.5)
+ if power_is_avg:
+ self.set_AT(self.AT * np.sqrt( power / ( frep_MHz*1.0e6 * self.calc_epp()) ))
+ self.chirp_pulse_W(GDD, TOD)
+ self.chirp_pulse_T(chirp2, chirp3, T0_ps)
+
+class SincPulse(Pulse):
+ def __init__(self, power, FWHM_ps, center_wavelength_nm,
+ time_window_ps = 10., frep_MHz = 100., NPTS = 2**10,
+ GDD = 0, TOD = 0, chirp2 = 0, chirp3 = 0,
+ power_is_avg = False):
+ """Generate sinc pulse A(t) = sqrt(peak_power[W]) * sin(t/T0)/(t/T0)
+ centered at wavelength center_wavelength_nm (nm).
+ The width is given by FWHM_ps, which is the full-width-at-half-maximum
+ in picoseconds. T0 is equal th FWHM/3.7909885.
+ time_window_ps sets temporal grid size. Optional GDD and TOD are
+ in ps^2 and ps^3."""
+ Pulse.__init__(self, frep_MHz = frep_MHz, n = NPTS)
+ # make sure we weren't passed mks units
+ assert (center_wavelength_nm > 1.0)
+ assert (time_window_ps > 1.0 )
+ self.set_center_wavelength_nm(center_wavelength_nm)
+ self.set_time_window_ps(time_window_ps)
+
+ T0_ps = FWHM_ps/3.7909885
+ ### Generate pulse
+ if not power_is_avg:
+ # numpy.sinc is sin(pi*x)/(pi*x), so we divide by pi
+ self.set_AT( np.sqrt(power) * np.sinc(self.T_ps/(T0_ps*np.pi)) )
+ else:
+ self.set_AT( 1 / np.sinc(np.pi * self.T_ps/(T0_ps*np.pi)) )
+ self.set_AT(self.AT * np.sqrt( power / ( frep_MHz*1.0e6 * self.calc_epp()) ))
+
+ self.chirp_pulse_W(GDD, TOD)
+ self.chirp_pulse_T(chirp2, chirp3, T0_ps)
+
+class FROGPulse(Pulse):
+ def __init__(self, time_window_ps, center_wavelength_nm, power,frep_MHz = 100., NPTS = 2**10,
+ power_is_avg = False,
+ fileloc = '',
+ flip_phase = True):
+ """Generate pulse from FROG data. Grid is centered at wavelength
+ center_wavelength_nm (nm), but pulse properties are loaded from data
+ file. If flip_phase is true, all phase is multiplied by -1 [useful
+ for correcting direction of time ambiguity]. time_window (ps) sets
+ temporal grid size.
+
+ power sets the pulse energy:
+ if power_is_epp is True then the number is pulse energy [J]
+ if power_is_epp is False then the power is average power [W], and
+ is multiplied by frep to calculate pulse energy"""
+ Pulse.__init__(self, frep_MHz = frep_MHz, n = NPTS)
+ try:
+ self.fileloc = fileloc
+ # make sure we weren't passed mks units
+ assert (center_wavelength_nm > 1.0)
+ assert (time_window_ps > 1.0 )
+ self.set_time_window_ps(time_window_ps)
+ self.set_center_wavelength_nm(center_wavelength_nm) # reference wavelength (nm)
+
+ # power -> EPP
+ if power_is_avg:
+ power = power / self.frep_mks
+
+ # Read in retrieved FROG trace
+ frog_data = np.genfromtxt(self.fileloc)
+ wavelengths = frog_data[:,0]# (nm)
+ intensity = frog_data[:,1]# (arb. units)
+ phase = frog_data[:,2]# (radians)
+
+ if flip_phase:
+ phase = -1 * phase
+
+ pulse_envelope = interp1d(wavelengths, intensity, kind='linear',
+ bounds_error=False,fill_value=0)
+ phase_envelope = interp1d(wavelengths, phase, kind='linear',
+ bounds_error=False,fill_value=0)
+
+ gridded_intensity = pulse_envelope(self.wl_nm)
+ gridded_phase = phase_envelope(self.wl_nm)
+
+ # Calculate time domain complex electric field A
+ self.set_AW(gridded_intensity*np.exp(1j*gridded_phase))
+ # Calculate normalization factor to achieve requested
+ # pulse energy
+ e_scale = np.sqrt(power / self.calc_epp() )
+ self.set_AT(self.AT * e_scale )
+
+ except IOError:
+ print ('File not found.' )
+
+class NoisePulse(Pulse):
+ def __init__(self, center_wavelength_nm, time_window_ps = 10., NPTS = 2**8,
+ frep_MHz = None):
+ Pulse.__init__(self, n = NPTS, frep_MHz = frep_MHz)
+ self.set_center_wavelength_nm(center_wavelength_nm)
+ self.set_time_window_ps(time_window_ps)
+
+ self.set_AW( 1e-30 * np.ones(self.NPTS) * np.exp(1j * 2 * np.pi *
+ 1j * np.random.rand(self.NPTS)))
+
+class CWPulse(Pulse):
+ def __init__(self, avg_power, center_wavelength_nm, time_window_ps = 10.0,
+ NPTS = 2**8,offset_from_center_THz = None):
+ Pulse.__init__(self, n = NPTS)
+ # make sure we weren't passed mks units
+ assert (center_wavelength_nm > 1.0)
+ assert (time_window_ps > 1.0 )
+
+ if offset_from_center_THz is None:
+ self.set_center_wavelength_nm(center_wavelength_nm)
+ self.set_time_window_ps(time_window_ps)
+
+ # Set the time domain to be CW, which should give us a delta function in
+ # frequency. Then normalize that delta function (in frequency space) to
+ # the average power. Note that frep does not factor in here.
+ self.set_AT(np.ones(self.NPTS,))
+ self.set_AW(self.AW * np.sqrt(avg_power) / sum(abs(self.AW)) )
+ else:
+ dF = 1.0/time_window_ps
+ n_offset = np.round( offset_from_center_THz/dF)
+
+ center_THz = self._c_nmps/center_wavelength_nm -\
+ n_offset * dF
+ center_nm = self._c_nmps / center_THz
+ self.set_time_window_ps(time_window_ps)
+
+ self.set_center_wavelength_nm(center_nm)
+ aws = np.zeros((self.NPTS, ))
+ aws[int(self.NPTS/2.0) + int(n_offset) ] = 1.0 *np.sqrt(avg_power)
+ self.set_AW(aws)
+
+ def gen_OSA(self, time_window_ps, center_wavelength_nm, power,
+ power_is_epp = False,
+ fileloc = 'O:\\OFM\\Maser\\Dual-Comb 100 MHz System\\Pump spectrum-Yb-101614.csv',
+ log = True, rows = 30): # Yb spectrum
+
+ """Generate pulse from OSA data. Grid is centered at wavelength
+ center_wavelength_nm (nm), but pulse properties are loaded from data
+ file. time_window (ps) sets temporal grid size. Switch in place for
+ importing log vs. linear data.
+
+ power sets the pulse energy:
+ if power_is_epp is True then the number is pulse energy [J]
+ if power_is_epp is False then the power is average power [W], and
+ is multiplied by frep to calculate pulse energy"""
+
+ try:
+ self.fileloc = fileloc
+
+ self.set_time_window_ps(time_window_ps)
+
+ self.center_wl = center_wavelength_nm # reference wavelength (nm)
+
+ self.w0 = (2. * np.pi * self.c) / self.center_wl # reference angular frequency
+
+ self.setup_grids()
+
+ if not power_is_epp:
+ power = power / self.frep
+
+ # Read in OSA data
+ osa_data = np.genfromtxt(self.fileloc, delimiter = ',', skiprows = rows)
+
+ wavelengths = osa_data[:,0]# (nm)
+ wavelengths = self.internal_wl_from_nm(wavelengths)
+
+ intensity = osa_data[:,1]# (arb. units)
+
+ if log:
+ intensity = 10.**(intensity / 10.)
+
+ freq_abs = self.c/wavelengths
+ freq_abs = np.sort(freq_abs)
+
+ self.freq_rel = freq_abs - self.c / self.center_wl
+
+ pulse_envelope = interp1d(self.freq_rel, intensity, kind='linear',
+ bounds_error = False, fill_value=0)
+
+ self.gridded_intensity = pulse_envelope(self.V / (2*np.pi))
+
+ # Calculate time domain complex electric field A
+ self.A = IFFT_t(self.gridded_intensity)
+ # Calculate normalization factor to achieve requested
+ # pulse energy
+ e_scale = np.sqrt(power / self.calc_epp() )
+ self.A = self.A * e_scale
+
+ except IOError:
+ print ('File not found.')
diff --git a/pool/shard010/Python/0089399_init__.py b/pool/shard010/Python/0089399_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..01c91810f4c70d592f7ca17f9c7b17f85c861d4d
--- /dev/null
+++ b/pool/shard010/Python/0089399_init__.py
@@ -0,0 +1,93 @@
+#
+# Copyright (C) 2008-2012 UNINETT AS
+#
+# This file is part of Network Administration Visualized (NAV).
+#
+# NAV is free software: you can redistribute it and/or modify it under
+# the terms of the GNU General Public License version 2 as published by
+# the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+# more details. You should have received a copy of the GNU General Public
+# License along with NAV. If not, see .
+#
+"""ipdevpoll plugin handling.
+
+This package contains plugins submodules as distributed with NAV.
+
+"""
+import inspect
+import logging
+
+from nav.errors import GeneralException
+
+from nav.ipdevpoll import Plugin
+
+_logger = logging.getLogger(__name__)
+plugin_registry = {}
+
+class PluginImportError(GeneralException):
+ """Failed to import plugin"""
+
+def import_plugins():
+ """Import all configured plugins into the plugin registry."""
+ from nav.ipdevpoll.config import ipdevpoll_conf
+
+ plugin_counter = 0
+ for alias in ipdevpoll_conf.options('plugins'):
+ import_plugin(ipdevpoll_conf, alias)
+ plugin_counter += 1
+
+ _logger.info('Imported %d plugin classes, '
+ '%d classes in plugin registry',
+ plugin_counter, len(plugin_registry))
+
+
+def import_plugin(config, alias):
+ """Attempts to import the plugin aliased to alias in config.
+
+ If alias is set, but the config doesn't contain the full name of the
+ plugin class, the module and class will be searched for in the
+ nav.ipdevpoll.plugins package.
+
+ """
+ full_class_name = config.get('plugins', alias)
+ if full_class_name:
+ module_name = '.'.join(full_class_name.split('.')[:-1])
+ class_name = full_class_name.split('.')[-1]
+ else:
+ module_name = 'nav.ipdevpoll.plugins.%s' % alias
+ class_name = None
+
+ _logger.debug('Importing plugin %s=%s', alias, full_class_name)
+ try:
+ module_ = __import__(module_name, globals(), locals(),
+ [module_name])
+ if class_name:
+ class_ = getattr(module_, class_name)
+ else:
+ class_ = get_plugin_from_module(module_)
+ except (ImportError, AttributeError), error:
+ _logger.exception("Failed to import plugin %s", full_class_name)
+ raise PluginImportError(error)
+
+ class_.alias = alias
+ plugin_registry[alias] = class_
+ class_.on_plugin_load()
+
+
+def get_plugin_from_module(module_):
+ """Tries to find a Plugin subclass in module_ and returns it"""
+ def _predicate(thing):
+ return (inspect.isclass(thing) and issubclass(thing, Plugin)
+ and inspect.getmodule(thing) == module_)
+
+ members = inspect.getmembers(module_, _predicate)
+ if members:
+ name, value = members[0]
+ _logger.debug('found plugin class %s in %s', name, module_)
+ return value
+ else:
+ raise AttributeError("no plugin class defined in module %r", module_)
diff --git a/pool/shard010/Python/0089401_test_user_defined_fragments.py b/pool/shard010/Python/0089401_test_user_defined_fragments.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f8a79176ba8347d28538f662794df0173f73ff2
--- /dev/null
+++ b/pool/shard010/Python/0089401_test_user_defined_fragments.py
@@ -0,0 +1,22 @@
+from django.test import TestCase
+from edge.models import Fragment, Genome
+
+
+class UserDefinedFragmentsTests(TestCase):
+ def test_user_defined_fragments_does_not_include_genomic_fragment(self):
+ genome = Genome.create("Foo")
+ s = "atggcatattcgcagct"
+ genome.add_fragment("chrI", s)
+
+ f = Fragment.create_with_sequence("Bar", "aacctaaaattataa")
+ self.assertEquals(len(Fragment.user_defined_fragments()), 1)
+ self.assertEquals(Fragment.user_defined_fragments()[0].name, "Bar")
+ self.assertEquals(Fragment.user_defined_fragments()[0].id, f.id)
+
+ def test_user_defined_fragments_does_not_include_inactive_fragments(self):
+ f1 = Fragment.create_with_sequence("Bar", "aacctaaaattataa")
+ self.assertEquals(len(Fragment.user_defined_fragments()), 1)
+ self.assertEquals(Fragment.user_defined_fragments()[0].id, f1.id)
+ f1.active = False
+ f1.save()
+ self.assertEquals(len(Fragment.user_defined_fragments()), 0)
diff --git a/pool/shard010/Python/0089405_test_gro.py b/pool/shard010/Python/0089405_test_gro.py
new file mode 100644
index 0000000000000000000000000000000000000000..5de27a653b532924ce28d5d899dae7db28ea1c61
--- /dev/null
+++ b/pool/shard010/Python/0089405_test_gro.py
@@ -0,0 +1,129 @@
+##############################################################################
+# MDTraj: A Python Library for Loading, Saving, and Manipulating
+# Molecular Dynamics Trajectories.
+# Copyright 2012-2017 Stanford University and the Authors
+#
+# Authors: Robert T. McGibbon
+# Contributors: Matthew Harrigan
+#
+# MDTraj is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation, either version 2.1
+# of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with MDTraj. If not, see .
+##############################################################################
+
+
+import tempfile, os
+import mdtraj as md
+from mdtraj.formats import GroTrajectoryFile
+from mdtraj.testing import eq
+
+fd, temp = tempfile.mkstemp(suffix='.gro')
+os.close(fd)
+
+
+def teardown_module(module):
+ """remove the temporary file created by tests in this file
+ this gets automatically called by pytest"""
+ os.unlink(temp)
+
+
+def test_read_write(get_fn):
+ for t in [md.load(get_fn('4waters.pdb')), # no unit cell
+ md.load(get_fn('native2.pdb')), # unitcell
+ md.load(get_fn('frame0.pdb'))]: # multiframe
+ with GroTrajectoryFile(temp, 'w') as f:
+ f.write(t.xyz, t.topology, unitcell_vectors=t.unitcell_vectors)
+
+ with GroTrajectoryFile(temp) as f:
+ xyz, time, unitcell = f.read()
+ top = f.topology
+
+ eq(xyz, t.xyz, decimal=3)
+ eq(list(top.atoms), list(t.top.atoms))
+ if t.unitcell_vectors is not None:
+ eq(unitcell, t.unitcell_vectors)
+
+
+def test_read_write_precision(get_fn):
+ import random
+ for t in [md.load(get_fn('4waters.pdb')), # no unit cell
+ md.load(get_fn('native2.pdb')), # unitcell
+ md.load(get_fn('frame0.pdb'))]: # multiframe
+ with GroTrajectoryFile(temp, 'w') as f:
+ f.write(t.xyz, t.topology, unitcell_vectors=t.unitcell_vectors,
+ precision=random.randint(4, 10))
+
+ with GroTrajectoryFile(temp) as f:
+ xyz, time, unitcell = f.read()
+ top = f.topology
+
+ eq(xyz, t.xyz, decimal=3)
+ eq(list(top.atoms), list(t.top.atoms))
+ if t.unitcell_vectors is not None:
+ eq(unitcell, t.unitcell_vectors)
+
+ # Test out the automatic saver and loader with different precisions
+ t = md.load(get_fn('native2.pdb'))
+ t.save(temp, precision=5)
+ eq(t.xyz, md.load(temp).xyz, decimal=3)
+
+
+def test_no_whitespace_gro(get_fn):
+ t = md.load(get_fn('v_error.gro'))
+ eq(t.xyz.shape, (1, 1, 3))
+ eq(t.n_atoms, 1)
+
+
+def test_load(get_fn):
+ for tref in [md.load(get_fn('4waters.pdb')), # no unit cell
+ md.load(get_fn('native2.pdb'))]: # unit cell
+ with GroTrajectoryFile(temp, 'w') as f:
+ f.write(tref.xyz, tref.topology, unitcell_vectors=tref.unitcell_vectors)
+
+ t = md.load(temp)
+ eq(t.xyz, tref.xyz, decimal=3)
+ eq(list(t.top.atoms), list(tref.top.atoms))
+ eq(t.unitcell_vectors, tref.unitcell_vectors)
+
+ #if there are 2 residues with same renum but different resname
+ t = md.load(get_fn('two_residues_same_resnum.gro'))
+ eq(t.n_residues, 2)
+
+def test_load_with_given_top(get_fn):
+ gro = get_fn('frame0.gro')
+ t = md.load(gro, top=gro)
+ tref = md.load(gro)
+
+ eq(t.xyz, tref.xyz)
+ eq(t.top, tref.top)
+ eq(list(t.top.atoms), list(tref.top.atoms))
+ eq(t.unitcell_vectors, tref.unitcell_vectors)
+
+
+
+
+def test_against_gmx(get_fn, tmpdir):
+ t1 = md.load(get_fn('frame0.pdb'))
+
+ # generated by converting frame0.pdb to gro with g_trajconv
+ t2 = md.load(get_fn('frame0.gro'))
+
+ fn = "{}/temp.gro".format(tmpdir)
+ t1.save(fn)
+ t3 = md.load(fn)
+
+ eq(t1.xyz, t2.xyz)
+ eq(t1.xyz, t3.xyz)
+ eq(t1.time, t2.time)
+ eq(t1.time, t3.time)
+ eq(t1.unitcell_vectors, t2.unitcell_vectors)
+ eq(t1.unitcell_vectors, t3.unitcell_vectors)
diff --git a/pool/shard010/Python/0089413_test_python_sim.py b/pool/shard010/Python/0089413_test_python_sim.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe7b5425bfb9b2b1a26a91e4a3518c0e306a4350
--- /dev/null
+++ b/pool/shard010/Python/0089413_test_python_sim.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2018 Piero Dalle Pezze
+#
+# 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.
+
+
+import os
+import sys
+import unittest
+from tests.context import sbpipe
+from sbpipe.utils.dependencies import is_py_package_installed
+
+
+class TestPythonSim(unittest.TestCase):
+
+ _orig_wd = os.getcwd()
+ _python_folder = 'python_models'
+ _output = 'OK'
+
+ @classmethod
+ def setUpClass(cls):
+ os.chdir(cls._python_folder)
+ if not is_py_package_installed("numpy"):
+ cls._output = "Python numpy not found: SKIP ... "
+ elif not is_py_package_installed("scipy"):
+ cls._output = "Python scipy not found: SKIP ... "
+ elif not is_py_package_installed("pandas"):
+ cls._output = "Python pandas not found: SKIP ... "
+
+ @classmethod
+ def tearDownClass(cls):
+ os.chdir(cls._orig_wd)
+
+ def setUp(self):
+ pass
+
+ def tearDown(self):
+ pass
+
+ def test_sim_python_ir(self):
+ if self._output == 'OK':
+ self.assertEqual(sbpipe(simulate="insulin_receptor.yaml", quiet=True), 0)
+ else:
+ sys.stdout.write(self._output)
+ sys.stdout.flush()
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/pool/shard010/Python/0089415_discuz.py b/pool/shard010/Python/0089415_discuz.py
new file mode 100644
index 0000000000000000000000000000000000000000..30a08d3ebcedf271cbf75298ab19265b93e9e673
--- /dev/null
+++ b/pool/shard010/Python/0089415_discuz.py
@@ -0,0 +1,186 @@
+# -*- coding: utf-8 -*-
+
+import requests
+import re
+import time
+
+from requests.exceptions import ReadTimeout
+# 论坛网址,这里只需要论坛地址和header
+import config
+import sched
+import logging
+from bs4 import BeautifulSoup
+
+'''
+ config.home_url 为php结尾的论坛首页,最后不带/
+ config.headers http 请求header
+ config.reply_form+url = home_url + mod=post&action=reply&fid={:d}&tid={:d}&extra=page%3D1&" \
+ "replysubmit=yes&infloat=yes&handlekey=fastpost&inajax=1
+ 自带了格式化,方便一些.
+'''
+
+
+def today():
+ time_str = time.strftime("%m.%d", time.localtime())
+ return time_str
+
+
+def gmt_time():
+ """
+
+ :rtype: object
+ """
+ gmt_time = 'GMT:' + time.strftime('%m-%d %H:%M:%S', time.gmtime(time.time()))
+ return gmt_time
+
+
+class Discuz(object):
+ def __init__(self):
+ self.user_pattern = re.compile(r'uid:(\w+)')
+ self.password_pattern = re.compile(r'password:(.+)')
+ self.comment_id_pattern = re.compile(r'pid=(\d+)')
+ self.page_number_pattern = re.compile(r'共 (\d+) 页')
+ self.html_content = ''
+ self.form_hash = ''
+ self.req = requests.session()
+ self.operate = ""
+ self.temp_soup = ''
+ self.uid = 0 # 用户uid
+ self.tid_pattern = re.compile(r'thread-(\d+)-1-1.html')
+ # re 匹配模式
+ self.hash_pattern = re.compile(r' ')
+
+ def login(self):
+ with open('user.txt', encoding='utf8') as f:
+ user = f.read()
+ username = re.search(self.user_pattern, user).group(1)
+ password = re.search(self.password_pattern, user).group(1)
+ self.login_name(username=username, password=password)
+
+ def login_name(self, username=0, password=0):
+ self.uid = username
+ print(username, password)
+ username = str(username).encode('gbk')
+ postdate = dict(username=username, password=password)
+ self.operate = self._get_response(config.form_url + '/member.php?mod=logging&action=login&loginsubmit'
+ '=yes&infloat=yes&inajax=1', postdate)
+ if re.search('现在将转入登录前页面', self.operate.text):
+ print('登录成功')
+ self.get_form_hash(config.home_url)
+ else:
+ print('出错啦')
+ print(self.operate.text)
+ exit()
+
+ def _get_response(self, url, data=None):
+ # 此处还有bug,只能进行一次处理,第二次出错,还是会退出脚本
+ try:
+ if data is not None:
+ req = self.req.post(url, data=data, headers=config.headers)
+ else:
+ req = self.req.get(url, headers=config.headers)
+ return req
+ except requests.exceptions.RequestException as error:
+ logging.exception(error)
+ print('error时间:' + gmt_time())
+ schedule = sched.scheduler(time.time, time.sleep)
+ schedule.enter(delay=300, priority=0, action=self._get_response, argument=(self, url, data))
+ return self._get_response(self, url, data)
+ except requests.exceptions.ConnectionError as connect_error:
+ logging.exception(connect_error)
+ print('conect_error时间:' + gmt_time())
+ schedule = sched.scheduler(time.time, time.sleep)
+ schedule.enter(delay=300, priority=0, action=self._get_response, argument=(self, url, data))
+ return self._get_response(self, url, data)
+ finally:
+ pass
+
+ def get_form_hash(self, url):
+ # 找到隐藏hash的位置,使用re的research功能查找,比用BS4方便一些
+ soup = self.req.get(url)
+ self.form_hash = self.hash_pattern.search(soup.text).group(1)
+ # self.form_hash = re.search(r' ', soup.text).group(1)
+ print(self.form_hash)
+
+ # fid版块号码+tid帖子,拼凑url.后续可以尝试从帖子页面抓取生成回复地址
+ def reply_fid_tid(self, fid, tid, message):
+ reply_url = config.form_url + '/forum.php?mod=post&action=reply&fid={:d}&tid={:d}&extra=page%3D1&replysubmit' \
+ '=yes&infloat=yes&handlekey=fastpost&inajax=1'.format(fid, tid)
+ assert isinstance(reply_url, object)
+ # 先打印一遍回帖内容,好知道如果失败是哪一贴
+ print(message)
+ post_time = time.time()
+ # 长度必须大于10,且要加进行encode成gbk编码
+ if len(message) < 20:
+ message += '\n'
+ message += str(today())
+ message += " "
+ reply = dict(message=message.encode("gbk"), posttime=int(post_time), formhash=self.form_hash, usesig=1,
+ subject='', connect_publish_t=0)
+ html = self._get_response(reply_url, data=reply)
+ soup = BeautifulSoup(html.content, "html.parser")
+ result = re.search('succee', soup.text)
+ if result:
+ print('回帖成功')
+ else:
+ print(soup.contents)
+ print('------------------')
+
+ # 点评,已验证
+ def comment_tid_pid(self, tid, pid, page, message):
+ comment_url = config.form_url + '/forum.php?mod=post&action=reply&comment=yes&tid={:d}&pid={:d}&extra=page%3D' \
+ '{:d}&replysubmit=yes&infloat=yes&inajax=1'.format(tid, pid, page)
+ if len(message) < 10:
+ message += " "
+ reply = dict(formhash=self.form_hash, handlekey='comment', message=message.encode("gbk"), commentsubmit='true')
+ html = self._get_response(comment_url, data=reply)
+ soup = BeautifulSoup(html.content, "html.parser")
+ result = re.search('succee', soup.text)
+ if result:
+ print('点评成功')
+ else:
+ print(soup.contents)
+ print('------------------')
+
+ # 发帖,已验证,关键字参数,带默认一些值,方便自定义。
+ def publish_fid_subject(self, fid, subject, msg, allownoticeauthor=1, readperm=0, credits=0, reply_times=1,
+ membertimes=1, random=10):
+ publish_url = config.form_url + '/forum.php?mod=post&action=newthread&fid=' + str(
+ fid) + '&extra=&topicsubmit=yes'
+ post_data = {'formhash': self.form_hash,
+ 'message': msg.encode('gbk'),
+ 'subject': subject.encode('gbk'),
+ 'posttime': int(time.time()),
+ 'addfeed': '1',
+ 'allownoticeauthor': str(allownoticeauthor), # 通知作者
+ 'checkbox': '0',
+ 'newalbum': '',
+ 'readperm': str(readperm), # 阅读权限
+ 'rewardfloor': '',
+ 'rushreplyfrom': '',
+ 'rushreplyto': '',
+ 'save': '',
+ 'stopfloor': '',
+ 'uploadalbum': '',
+ 'usesig': '1',
+ 'replycredit_extcredits': str(credits), # 单次中奖金额(一次中奖的金额),此处填0,则无中奖金额
+ 'replycredit_times': str(reply_times), # 奖励次数
+ 'replycredit_membertimes': str(membertimes), # 每人最多中奖次数
+ 'replycredit_random': str(random), # 中奖几率
+ 'wysiwyg': '0'}
+ html = self._get_response(publish_url, data=post_data)
+ soup = BeautifulSoup(html.content, "html.parser")
+ print(soup)
+ tie = soup.find(href=re.compile(config.form_url + '/thread-\d+-1-1.html'))
+ tid = re.search('thread-(\d+)-1-1.html', tie['href']).group(1)
+ print(tid)
+ return int(tid) # 返回数字,保证可以发帖
+
+ # 找出共多少页
+ def find_page_number(self, url):
+ html = self.req.get(url)
+ soup = BeautifulSoup(html.content, "html.parser")
+ page_soup = soup.find('span', title=self.page_number_pattern)
+ page_number = re.search('\d+', page_soup.get_text()).group()
+ print('共' + page_number + '页')
+ return page_number
diff --git a/pool/shard010/Python/0089422_usrp_wfm_rcv2_nogui.py b/pool/shard010/Python/0089422_usrp_wfm_rcv2_nogui.py
new file mode 100644
index 0000000000000000000000000000000000000000..4173468efc4be6569d5d726ad9e1601498d3f7ce
--- /dev/null
+++ b/pool/shard010/Python/0089422_usrp_wfm_rcv2_nogui.py
@@ -0,0 +1,155 @@
+#!/usr/bin/env python
+#
+# Copyright 2005-2007,2011 Free Software Foundation, Inc.
+#
+# This file is part of GNU Radio
+#
+# GNU Radio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# GNU Radio is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GNU Radio; see the file COPYING. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street,
+# Boston, MA 02110-1301, USA.
+#
+
+from gnuradio import gr, optfir, audio, blks2, uhd
+from gnuradio.eng_option import eng_option
+from optparse import OptionParser
+from usrpm import usrp_dbid
+import sys
+import math
+
+class wfm_rx_block (gr.top_block):
+
+ def __init__(self):
+ gr.top_block.__init__(self)
+
+ parser=OptionParser(option_class=eng_option)
+ parser.add_option("-a", "--args", type="string", default="",
+ help="UHD device address args [default=%default]")
+ parser.add_option("", "--spec", type="string", default="A:0 A:0",
+ help="Subdevice of UHD device where appropriate")
+ parser.add_option("-A", "--antenna", type="string", default=None,
+ help="select Rx Antenna where appropriate")
+ parser.add_option("", "--f1", type="eng_float", default=100.7e6,
+ help="set 1st station frequency to FREQ", metavar="FREQ")
+ parser.add_option("", "--f2", type="eng_float", default=102.5e6,
+ help="set 2nd station freq to FREQ", metavar="FREQ")
+ parser.add_option("-g", "--gain", type="eng_float", default=40,
+ help="set gain in dB (default is midpoint)")
+ parser.add_option("-O", "--audio-output", type="string", default="",
+ help="pcm device name. E.g., hw:0,0 or surround51 or /dev/dsp")
+ parser.add_option("", "--freq-min", type="eng_float", default=87.9e6,
+ help="Set a minimum frequency [default=%default]")
+ parser.add_option("", "--freq-max", type="eng_float", default=108.1e6,
+ help="Set a maximum frequency [default=%default]")
+
+ (options, args) = parser.parse_args()
+ if len(args) != 0:
+ parser.print_help()
+ sys.exit(1)
+
+ if abs(options.f1 - options.f2) > 5.5e6:
+ print "Sorry, two stations must be within 5.5MHz of each other"
+ raise SystemExit
+
+ f = (options.f1, options.f2)
+
+ self.vol = .1
+ self.state = "FREQ"
+
+ self.fm_freq_min = options.freq_min
+ self.fm_freq_max = options.freq_max
+
+ # build graph
+ stream_args = uhd.stream_args('fc32', channels=range(2))
+ self.u = uhd.usrp_source(device_addr=options.args, stream_args=stream_args)
+
+ # Set front end channel mapping
+ self.u.set_subdev_spec(options.spec)
+
+ usrp_rate = 320e3
+ demod_rate = 320e3
+ audio_rate = 32e3
+ audio_decim = int(demod_rate / audio_rate)
+
+ self.u.set_samp_rate(usrp_rate)
+ dev_rate = self.u.get_samp_rate()
+
+ # Make sure dboard can suppor the required frequencies
+ frange = self.u.get_freq_range()
+ if(frange.start() > self.fm_freq_max or frange.stop() < self.fm_freq_min):
+ sys.stderr.write("Radio does not support required frequency range.\n")
+ sys.exit(1)
+
+ # sound card as final sink
+ self.audio_sink = audio.sink(int(audio_rate), options.audio_output)
+
+ # taps for channel filter
+ nfilts = 32
+ chan_coeffs = optfir.low_pass (nfilts, # gain
+ nfilts*usrp_rate, # sampling rate
+ 80e3, # passband cutoff
+ 115e3, # stopband cutoff
+ 0.1, # passband ripple
+ 60) # stopband attenuation
+ rrate = usrp_rate / dev_rate
+
+ # set front end PLL to middle frequency
+ mid_freq = (f[0] + f[1]) / 2.0
+
+ if options.gain is None:
+ # if no gain was specified, use the mid-point in dB
+ g = self.u.get_gain_range()
+ options.gain = float(g.start()+g.stop())/2.0
+
+ for n in range(2):
+ chan_filt = blks2.pfb_arb_resampler_ccf(rrate, chan_coeffs, nfilts)
+ guts = blks2.wfm_rcv (demod_rate, audio_decim)
+ volume_control = gr.multiply_const_ff(self.vol)
+
+ #self.connect((self.di, n), chan_filt)
+ self.connect((self.u, n), chan_filt)
+ self.connect(chan_filt, guts, volume_control)
+ self.connect(volume_control, (self.audio_sink, n))
+
+ # Test the the requested frequencies are in range
+ if(f[n] < self.fm_freq_min or f[n] > self.fm_freq_max):
+ sys.stderr.write("Requested frequency is outside of required frequency range.\n")
+ sys.exit(1)
+
+ # Tune each channel by setting the RF freq to mid_freq and the
+ # DDC freq to f[n].
+ tr = uhd.tune_request(f[n], rf_freq=mid_freq,
+ rf_freq_policy=uhd.tune_request.POLICY_MANUAL)
+ self.u.set_center_freq(tr, n)
+
+ # Set gain for each channel
+ self.set_gain(options.gain, n)
+
+ # Set the antenna
+ if(options.antenna):
+ self.u.set_antenna(options.antenna, n)
+
+ def set_vol (self, vol):
+ self.vol = vol
+ self.volume_control.set_k(self.vol)
+
+
+ def set_gain(self, gain, n):
+ self.u.set_gain(gain, n)
+
+if __name__ == '__main__':
+ tb = wfm_rx_block()
+ try:
+ tb.run()
+ except KeyboardInterrupt:
+ pass
diff --git a/pool/shard010/Python/0089425_generate-seeds.py b/pool/shard010/Python/0089425_generate-seeds.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae7a446b17115d91299313f1c2176c2973715b67
--- /dev/null
+++ b/pool/shard010/Python/0089425_generate-seeds.py
@@ -0,0 +1,137 @@
+#!/usr/bin/env python3
+# Copyright (c) 2014-2017 Wladimir J. van der Laan
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+'''
+Script to generate list of seed nodes for chainparams.cpp.
+
+This script expects two text files in the directory that is passed as an
+argument:
+
+ nodes_main.txt
+ nodes_test.txt
+
+These files must consist of lines in the format
+
+
+ :
+ []
+ []:
+ .onion
+ 0xDDBBCCAA (IPv4 little-endian old pnSeeds format)
+
+The output will be two data structures with the peers in binary format:
+
+ static SeedSpec6 pnSeed6_main[]={
+ ...
+ }
+ static SeedSpec6 pnSeed6_test[]={
+ ...
+ }
+
+These should be pasted into `src/chainparamsseeds.h`.
+'''
+
+from base64 import b32decode
+from binascii import a2b_hex
+import sys, os
+import re
+
+# ipv4 in ipv6 prefix
+pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff])
+# tor-specific ipv6 prefix
+pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43])
+
+def name_to_ipv6(addr):
+ if len(addr)>6 and addr.endswith('.onion'):
+ vchAddr = b32decode(addr[0:-6], True)
+ if len(vchAddr) != 16-len(pchOnionCat):
+ raise ValueError('Invalid onion %s' % s)
+ return pchOnionCat + vchAddr
+ elif '.' in addr: # IPv4
+ return pchIPv4 + bytearray((int(x) for x in addr.split('.')))
+ elif ':' in addr: # IPv6
+ sub = [[], []] # prefix, suffix
+ x = 0
+ addr = addr.split(':')
+ for i,comp in enumerate(addr):
+ if comp == '':
+ if i == 0 or i == (len(addr)-1): # skip empty component at beginning or end
+ continue
+ x += 1 # :: skips to suffix
+ assert(x < 2)
+ else: # two bytes per component
+ val = int(comp, 16)
+ sub[x].append(val >> 8)
+ sub[x].append(val & 0xff)
+ nullbytes = 16 - len(sub[0]) - len(sub[1])
+ assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0))
+ return bytearray(sub[0] + ([0] * nullbytes) + sub[1])
+ elif addr.startswith('0x'): # IPv4-in-little-endian
+ return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:])))
+ else:
+ raise ValueError('Could not parse address %s' % addr)
+
+def parse_spec(s, defaultport):
+ match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s)
+ if match: # ipv6
+ host = match.group(1)
+ port = match.group(2)
+ elif s.count(':') > 1: # ipv6, no port
+ host = s
+ port = ''
+ else:
+ (host,_,port) = s.partition(':')
+
+ if not port:
+ port = defaultport
+ else:
+ port = int(port)
+
+ host = name_to_ipv6(host)
+
+ return (host,port)
+
+def process_nodes(g, f, structname, defaultport):
+ g.write('static SeedSpec6 %s[] = {\n' % structname)
+ first = True
+ for line in f:
+ comment = line.find('#')
+ if comment != -1:
+ line = line[0:comment]
+ line = line.strip()
+ if not line:
+ continue
+ if not first:
+ g.write(',\n')
+ first = False
+
+ (host,port) = parse_spec(line, defaultport)
+ hoststr = ','.join(('0x%02x' % b) for b in host)
+ g.write(' {{%s}, %i}' % (hoststr, port))
+ g.write('\n};\n')
+
+def main():
+ if len(sys.argv)<2:
+ print(('Usage: %s ' % sys.argv[0]), file=sys.stderr)
+ exit(1)
+ g = sys.stdout
+ indir = sys.argv[1]
+ g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n')
+ g.write('#define BITCOIN_CHAINPARAMSSEEDS_H\n')
+ g.write('/**\n')
+ g.write(' * List of fixed seed nodes for the bitcoin network\n')
+ g.write(' * AUTOGENERATED by contrib/seeds/generate-seeds.py\n')
+ g.write(' *\n')
+ g.write(' * Each line contains a 16-byte IPv6 address and a port.\n')
+ g.write(' * IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.\n')
+ g.write(' */\n')
+ with open(os.path.join(indir,'nodes_main.txt'),'r') as f:
+ process_nodes(g, f, 'pnSeed6_main', 1237)
+ g.write('\n')
+ with open(os.path.join(indir,'nodes_test.txt'),'r') as f:
+ process_nodes(g, f, 'pnSeed6_test', 1239)
+ g.write('#endif // BITCOIN_CHAINPARAMSSEEDS_H\n')
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard010/Python/0089436_post_sso.py b/pool/shard010/Python/0089436_post_sso.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2215e610f4c83a6389b55e3fc8d0165f2560e03
--- /dev/null
+++ b/pool/shard010/Python/0089436_post_sso.py
@@ -0,0 +1,40 @@
+from http_response_builder import HTTP_Response_Builder
+from param_definition.parameter import Parameter, Base_64_Encoded_XML_Parameter_Type
+from model.user_model import User
+
+class Post_SSO_HTTP_Response_Builder(HTTP_Response_Builder):
+ relay_state = Parameter('RelayState', required = False, default = 'dashboard')
+ saml_response = Parameter('SAMLResponse', required = True, parameter_type = Base_64_Encoded_XML_Parameter_Type)
+ type = Parameter("type", required = False, default = "")
+ requires_authentication = False
+
+ def print_forbidden_headers(self):
+ print "Status: 403"
+
+ def print_headers(self, authenticated_user):
+ status_code = None
+ for status_code_element in self.saml_response.iter("{urn:oasis:names:tc:SAML:2.0:protocol}StatusCode"):
+ status_code = status_code_element.get('Value')
+ if status_code != 'urn:oasis:names:tc:SAML:2.0:status:Success':
+ self.print_forbidden_headers()
+ return
+ if status_code is None:
+ self.print_forbidden_headers()
+ return
+
+ email = None
+ # There really should only be one... but we'll loop through it anyway.
+ for email_element in self.saml_response.iter('{urn:oasis:names:tc:SAML:2.0:assertion}NameID'):
+ email = email_element.text
+ if email is None:
+ self.print_forbidden_headers()
+ return
+
+ user = User.refresh_user_session(email)
+ print "Status: 303"
+ print "Set-Cookie: session_id=" + user.session_id + "; Domain=onsite-inflight.com; Path=/"
+ if self.type == "expense":
+ self.relay_state = "expenses"
+ if self.relay_state[0] is not '/':
+ self.relay_state = '/' + self.relay_state
+ print "Location: https://onsite-inflight.com" + self.relay_state