diff --git a/pool/shard007/JavaScript/0047834_Adjustor.js b/pool/shard007/JavaScript/0047834_Adjustor.js new file mode 100644 index 0000000000000000000000000000000000000000..516b5060e7c8258bccee18e4d055bf957f4c4958 --- /dev/null +++ b/pool/shard007/JavaScript/0047834_Adjustor.js @@ -0,0 +1,115 @@ +var Adjustor = {}; + +Adjustor.UP = 38; +Adjustor.DOWN = 40; + +Adjustor.nudge = function (input, event, format){ + + // when replacing the nudged value, tells us where to start and + // how far to go (like substr(repl.start, repl.length)) + var repl = { start: 0, length: 0 }; + + // record the original position of the cursor + var cursor = input.selectionStart; + + // determine which direction we're nudging + var direction = event.keyCode; + if (direction != Adjustor.UP && direction != Adjustor.DOWN){ + return; + } + + // since we'll sometimes prevent the cursor from moving, we + // should always prevent the cursor from moving + event.preventDefault(); + + function parse(){ + var value = input.value, + p = cursor, + start; + + function isNumeric(value){ + return !isNaN(parseInt(value)); + } + + while (start == undefined){ + + var left = isNumeric(value[p - 1]), + right = isNumeric(value[p]); + + // if there's no digit left or right, bail + if (!left && !right){ + return; + } + + // if there's no digit left but a digit right, we've found our start + else if (!left && right){ + start = p; + } + + // if there's a digit left, regardless of a digit right, move left + else if (left){ + p--; + } + } + + var parsed = parseInt(value.substr(start)); + + // record the start and the length to replace this value later + repl.start = start; + repl.length = parsed.toString().length; + + return parsed; + } + + /** + * Replaces the currently matched substring with another value, based on + * the start and length found by parse() (i.e., call that first). Returns + * the new string. + * + * @param string + * @return string + */ + function replace(value){ + var min = 0, max; + + // determine the maximum value for this...value + if (format == Color.RGB){ + max = 255; + } else { + + // if we're looking at hue, then there will be no digits to the + // left of the start position + max = /\d/.test(input.value.substr(0, repl.start)) ? 100 : 359; + } + + value = Math.max(min, Math.min(max, value)); + + var chunks = input.value.split(""); + chunks.splice(repl.start, repl.length, value); + return chunks.join(""); + } + + /** + * Provides the offset to add to the current value, based on whether + * we're nudging up or down (which arrow key) and big or small (whether + * the Option key was being held). + * + * @return int + */ + function adjustment(){ + return (direction == Adjustor.UP ? 1 : -1) * (event.altKey ? 10 : 1); + } + + var parsed = parse(); + + if (parsed == undefined){ + return; + } + + input.value = replace(parsed + adjustment()); + + // put the cursor in the right spot + input.selectionStart = input.selectionEnd = cursor; + + return input.value; +}; diff --git a/pool/shard007/JavaScript/0047836_checkbox.js b/pool/shard007/JavaScript/0047836_checkbox.js new file mode 100644 index 0000000000000000000000000000000000000000..2b764f9bce7cebace9ef52c283a6d801f6bdcdd6 --- /dev/null +++ b/pool/shard007/JavaScript/0047836_checkbox.js @@ -0,0 +1,36 @@ +'use strict'; + +angular.module('angularify.semantic.checkbox', []) +.directive('checkbox', function() { + return { + restrict: 'E', + replace: true, + transclude: true, + scope: { + checked: '&?', + disabled: '&?', + ngModel: '=ngModel' + }, + controller: function() { + var vm = this; + + // TODO: assert this is usefull ? + // if(angular.isUndefined(vm.ngModel)) { vm.ngModel = !!vm.ngModel; } + + if(angular.isFunction(vm.checked)) { vm.ngModel = !!vm.checked(); } + + vm.toggle = function() { + if(angular.isFunction(vm.disabled) && vm.disabled()) return; + vm.ngModel = !vm.ngModel; + } + }, + controllerAs: 'vm', + bindToController: true, + require: 'ngModel', + template: '
' + + '' + + '' + + '
', + link: function() { } + }; +}); diff --git a/pool/shard007/JavaScript/0047837_passify.js b/pool/shard007/JavaScript/0047837_passify.js new file mode 100644 index 0000000000000000000000000000000000000000..b5a53e96c20be143d682c9c16cdec1d515b5d3d3 --- /dev/null +++ b/pool/shard007/JavaScript/0047837_passify.js @@ -0,0 +1,39 @@ +var passify = require('../index'); + +describe('Passify', function() { + describe('Create', function() { + var passwordDefault = passify.create(); + var passwordCustom = passify.create(11); + + it('should result in an 8 character [0-9][A-Z][a-z] string', function() { + passwordDefault.length.should.equal(8); + }); + it('should result in an 11 character [0-9][A-Z][a-z] string', function() { + passwordCustom.length.should.equal(11); + }); + }); + + describe('Hash', function() { + it('should create a hash for the password "secret".', function(cb) { + passify.hash('secret', function(err, hash) { + hash.should.be.ok; + cb(); + }); + }); + }); + + describe('Compare', function() { + it('should return false when comparing a password to a wrong hash.', function(cb) { + passify.compare('secret', '123', function(err, bool) { + bool.should.be.false; + cb(); + }); + }); + it('should return true when comparing a password to a correct hash.', function(cb) { + passify.compare('secret', '$2a$05$uwnq6r5LxGIMjFGjHwKBWuMgcH/XcazHPG6b/xj3Yze5DRd6NmNGO', function(err, bool) { + bool.should.be.true; + cb(); + }); + }); + }); +}); diff --git a/pool/shard007/JavaScript/0047840_SAXTreeBuilder.js b/pool/shard007/JavaScript/0047840_SAXTreeBuilder.js new file mode 100644 index 0000000000000000000000000000000000000000..1a4842151202abcba5d8b81541de01e949c3d0df --- /dev/null +++ b/pool/shard007/JavaScript/0047840_SAXTreeBuilder.js @@ -0,0 +1,126 @@ +System.register(["./TreeBuilder", "./Characters", "./Comment", "./Document", "./DocumentFragment", "./DTD", "./Element", "./getAttribute"], function (exports_1, context_1) { + "use strict"; + var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __moduleName = context_1 && context_1.id; + var TreeBuilder_1, Characters_1, Comment_1, Document_1, DocumentFragment_1, DTD_1, Element_1, getAttribute_1, SAXTreeBuilder; + return { + setters: [ + function (TreeBuilder_1_1) { + TreeBuilder_1 = TreeBuilder_1_1; + }, + function (Characters_1_1) { + Characters_1 = Characters_1_1; + }, + function (Comment_1_1) { + Comment_1 = Comment_1_1; + }, + function (Document_1_1) { + Document_1 = Document_1_1; + }, + function (DocumentFragment_1_1) { + DocumentFragment_1 = DocumentFragment_1_1; + }, + function (DTD_1_1) { + DTD_1 = DTD_1_1; + }, + function (Element_1_1) { + Element_1 = Element_1_1; + }, + function (getAttribute_1_1) { + getAttribute_1 = getAttribute_1_1; + } + ], + execute: function () { + SAXTreeBuilder = (function (_super) { + __extends(SAXTreeBuilder, _super); + function SAXTreeBuilder() { + return _super.call(this) || this; + } + SAXTreeBuilder.prototype.start = function (tokenizer) { + this.document = new Document_1.Document(this.tokenizer); + }; + SAXTreeBuilder.prototype.end = function () { + this.document.endLocator = this.tokenizer; + }; + SAXTreeBuilder.prototype.insertDoctype = function (name, publicId, systemId) { + var doctype = new DTD_1.DTD(this.tokenizer, name, publicId, systemId); + doctype.endLocator = this.tokenizer; + this.document.appendChild(doctype); + }; + SAXTreeBuilder.prototype.createElement = function (namespaceURI, localName, attributes) { + var element = new Element_1.Element(this.tokenizer, namespaceURI, localName, localName, attributes || []); + return element; + }; + SAXTreeBuilder.prototype.insertComment = function (data, parent) { + if (!parent) + parent = this.currentStackItem(); + var comment = new Comment_1.Comment(this.tokenizer, data); + parent.appendChild(comment); + }; + SAXTreeBuilder.prototype.appendCharacters = function (parent, data) { + var text = new Characters_1.Characters(this.tokenizer, data); + parent.appendChild(text); + }; + SAXTreeBuilder.prototype.insertText = function (data) { + if (this.redirectAttachToFosterParent && this.openElements.top.isFosterParenting()) { + var tableIndex = this.openElements.findIndex('table'); + var tableItem = this.openElements.item(tableIndex); + var table = tableItem.node; + if (tableIndex === 0) { + return this.appendCharacters(table, data); + } + var text = new Characters_1.Characters(this.tokenizer, data); + var parent = table.parentNode; + if (parent) { + parent.insertBetween(text, table.previousSibling, table); + return; + } + var stackParent = this.openElements.item(tableIndex - 1).node; + stackParent.appendChild(text); + return; + } + this.appendCharacters(this.currentStackItem().node, data); + }; + SAXTreeBuilder.prototype.attachNode = function (node, parent) { + parent.appendChild(node); + }; + SAXTreeBuilder.prototype.attachNodeToFosterParent = function (child, table, stackParent) { + var parent = table.parentNode; + if (parent) + parent.insertBetween(child, table.previousSibling, table); + else + stackParent.appendChild(child); + }; + SAXTreeBuilder.prototype.detachFromParent = function (element) { + element.detach(); + }; + SAXTreeBuilder.prototype.reparentChildren = function (oldParent, newParent) { + newParent.appendChildren(oldParent.firstChild); + }; + SAXTreeBuilder.prototype.getFragment = function () { + var fragment = new DocumentFragment_1.DocumentFragment(); + this.reparentChildren(this.openElements.rootNode, fragment); + return fragment; + }; + SAXTreeBuilder.prototype.addAttributesToElement = function (element, attributes) { + for (var i = 0; i < attributes.length; i++) { + var attribute = attributes[i]; + if (!getAttribute_1.getAttribute(element, attribute.nodeName)) + element.attributes.push(attribute); + } + }; + return SAXTreeBuilder; + }(TreeBuilder_1.TreeBuilder)); + exports_1("SAXTreeBuilder", SAXTreeBuilder); + } + }; +}); diff --git a/pool/shard007/JavaScript/0047847_Cube.js b/pool/shard007/JavaScript/0047847_Cube.js new file mode 100644 index 0000000000000000000000000000000000000000..9adb9e99d3df04854866c10b2df8853d7411d72b --- /dev/null +++ b/pool/shard007/JavaScript/0047847_Cube.js @@ -0,0 +1,54 @@ +import THREE from 'three'; + +export default class Cube { + + constructor(config) { + if(config === undefined) { + config = {}; + } + + let radius = config.radius || 70; + + this.rotationX = config.rotationX || 0; + this.rotationY = config.rotationY || 0; + + // Create a group + this.group = new THREE.Group + this.widthSegments = config.widthSegments || 16; + this.heightSegments = config.heightSegments || 16 + + // this.geometry = new THREE.SphereGeometry(radius, this.widthSegments, this.heightSegments); + this.geometry = new THREE.BoxGeometry(radius, radius, radius); + this.material = new THREE.MeshBasicMaterial({ + color: config.color || 0xffaa00, + opacity: config.opacity || 0.3, + transparent: true, + wireframe: config.wireframe || false, + wireframeLinewidth: config.wireframeLinewidth || 1 + }); + + // Create a cube + this.cube = new THREE.Mesh(this.geometry, this.material); + + // Cube positions + this.cube.position.x = config.positionX || 0; + this.cube.position.y = config.positionY || 0; + this.cube.position.z = 100; + + // Group position + this.group.position.x = -window.innerWidth / 2 - 60; + // this.group.position.y = -window.innerHeight / 2 + 200; + + this.group.add(this.cube); + } + + render() { + this.cube.rotation.x += this.rotationX; + this.cube.rotation.y += this.rotationY; + } + + getObject() { + return this.group; + } + +} diff --git a/pool/shard007/JavaScript/0047850_reserveLoad.js b/pool/shard007/JavaScript/0047850_reserveLoad.js new file mode 100644 index 0000000000000000000000000000000000000000..53ace1644d04b8d463b09822cef99e18680402ef --- /dev/null +++ b/pool/shard007/JavaScript/0047850_reserveLoad.js @@ -0,0 +1,171 @@ +'use strict'; + +/*! + * reserveLoad.js, version 0.4.1, 2013/10/27 + * Dynamic JavaScript/CSS loader, and load JavaScript with reserve URL. + * https://github.com/zensh/reserveLoad.js + * (c) admin@zensh.com 2013 + * License: MIT + */ + +(function (global) { + var doc = global.document, + _define = global.define, + location = doc.location, + head = doc.getElementsByTagName('head')[0] || doc.documentElement, + baseElement = head.getElementsByTagName('base')[0], + slice = [].slice, + validCSS = /\.css(?:\?|$)/i, + validState = /^(?:loaded|complete|undefined)$/, + currentlyAddingScript = null, + scripts = {}; // 缓存已加载脚本 + + // 入口函数 + var reserveLoad = global.reserveLoad = function () { + startLoad(slice.call(arguments)); + }; + reserveLoad.version = 'v0.4.0'; + + // 获取原始define函数,从而支持reserveLoad覆盖 + _define = isFunction(_define) ? (_define._originalDefine ? _define._originalDefine : _define) : null; + // 封装define,从而兼容requirejs的define等 + var define = global.define = function (name, deps, callback) { + callback = isFunction(callback) ? callback : isFunction(deps) ? deps : isFunction(name) ? name : noop; + if (currentlyAddingScript) { + scripts[currentlyAddingScript] = callback(); + currentlyAddingScript = null; + } else if (_define) { + _define(name, deps, callback); + } + }; + // 保存原始define + define._originalDefine = _define; + + function noop() {} + + function isArray(obj) { + return Array.isArray ? Array.isArray(obj) : Object.prototype.toString.call(obj) === '[object Array]'; + } + function isFunction(fn) { + return typeof fn === 'function'; + } + function each(array, iterator, context) { + for (var i = 0, l = array.length; i < l; i++) { + iterator.call(context, array[i], i, array); + } + } + // 逐步执行函数 + function eachThen(array, iterator, context) { + var i = -1, + end = array.length - 1; + function next() { + i += 1; + iterator.call(context, i < end ? next : null, array[i], i, array); + } + return next(); + } + // 获取当前url地址对应的JS + function getScript(context, exports, url) { + var value = null; + if (url) { + if (scripts[url]) { + value = scripts[url]; + } else if (isFunction(exports)) { + value = exports(); + scripts[url] = value; + } else if (exports && typeof exports === 'string') { + value = context || global; + each(exports.split('.'), function (part) { + if (value) { + value = value[part]; + } + }); + scripts[url] = value; + } + } + return value; + } + // 加载JS或CSS + function request(url, exports, callback) { + var isCSS = validCSS.test(url), + node = doc.createElement(isCSS ? 'link' : 'script'), + success = isCSS || !exports; + + if (!url || (!isCSS && getScript(global, exports, url))) { + return; + } + node.onload = node.onerror = node.onreadystatechange = function () { + if (validState.test(node.readyState + '')) { + if (!isCSS) { + head.removeChild(node); + } + node = node.onload = node.onerror = node.onreadystatechange = null; + callback(success || !! getScript(global, exports, url)); + } + }; + if (isCSS) { + node.rel = 'stylesheet'; + node.href = url; + } else { + node.async = 1; + node.src = url; + } + currentlyAddingScript = url; + head[baseElement ? 'insertBefore' : 'appendChild'](node, baseElement); + } + // 主函数 + function startLoad(list) { + var count = 0, + total = list.length, + scriptList = [], // 当前加载器脚本清单 + callback = list[total - 1]; + // 检测是否完成加载 + function checkLoaded(next, url) { + if (url || count === total) { + each(scriptList, function (key, index) { + scriptList[index] = scripts[key] || key; + }); + scriptList.unshift(url); + return callback.apply(null, scriptList); + } else if (isFunction(next)) { + return next(); + } + } + function load(array, nextLoad) { + function get(url, fnName, next) { + request(url, fnName, function (success) { + count += +success; + if (!success && next) { + next(); + } else { + scriptList.push(url); + checkLoaded(nextLoad, success ? null : url); + } + }); + } + if (isArray(array)) { + var checkFn; + if (array.length > 1) { + checkFn = array.pop(); + } + eachThen(array, function (next, x) { + get(x, checkFn, next); + }); + } else if (array && typeof array === 'string') { + get(array, null); + } else { + count += 1; + checkLoaded(nextLoad, null); + } + } + if (isFunction(callback)) { + total -= 1; + list.pop(); + } else { + callback = noop; + } + eachThen(list, function (next, x) { + load(x, next); + }); + } +})(window); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0047853_response.js b/pool/shard007/JavaScript/0047853_response.js new file mode 100644 index 0000000000000000000000000000000000000000..47caa4ab47abb8f79adb1e9ac2984d378fd623ea --- /dev/null +++ b/pool/shard007/JavaScript/0047853_response.js @@ -0,0 +1,196 @@ + +/** + * response.js + * + * Response class provides content decoding + */ + +var http = require('http'); +var convert = require('encoding').convert; +var Headers = require('./headers'); + +module.exports = Response; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Response(body, opts) { + + opts = opts || {}; + + this.url = opts.url; + this.status = opts.status; + this.statusText = http.STATUS_CODES[this.status]; + this.headers = new Headers(opts.headers); + this.body = body; + this.bodyUsed = false; + this.size = opts.size; + this.ok = this.status >= 200 && this.status < 300; + this.timeout = opts.timeout; + this.res = opts.res; +} + +/** + * Decode response as json + * + * @return Promise + */ +Response.prototype.json = function() { + + return this._decode().then(function(text) { + return JSON.parse(text); + }); + +} + +/** + * Decode response as text + * + * @return Promise + */ +Response.prototype.text = function() { + + return this._decode(); + +} + +/** + * Decode buffers into utf-8 string + * + * @return Promise + */ +Response.prototype._decode = function() { + + var self = this; + + if (this.bodyUsed) { + return Response.Promise.reject(new Error('body used already for: ' + this.url)); + } + + this.bodyUsed = true; + this._bytes = 0; + this._abort = false; + this._raw = []; + + return new Response.Promise(function(resolve, reject) { + var resTimeout; + + // allow timeout on slow response body + if (self.timeout) { + resTimeout = setTimeout(function() { + self._abort = true; + reject(new Error('response timeout at ' + self.url + ' over limit: ' + self.timeout)); + }, self.timeout); + } + + // handle stream error, such as incorrect content-encoding + self.body.on('error', function(err) { + reject(new Error('invalid response body at: ' + self.url + ' reason: ' + err.message)); + }); + + self.body.on('data', function(chunk) { + if (self._abort || chunk === null) { + return; + } + + if (self.size && self._bytes + chunk.length > self.size) { + self._abort = true; + reject(new Error('content size at ' + self.url + ' over limit: ' + self.size)); + return; + } + + self._bytes += chunk.length; + self._raw.push(chunk); + }); + + self.body.on('end', function() { + if (self._abort) { + return; + } + + clearTimeout(resTimeout); + resolve(self._convert()); + }); + }); + +}; + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param String encoding Target encoding + * @return String + */ +Response.prototype._convert = function(encoding) { + + encoding = encoding || 'utf-8'; + + var charset = 'utf-8'; + var res, str; + + // header + if (this.headers.has('content-type')) { + res = /charset=([^;]*)/i.exec(this.headers.get('content-type')); + } + + // no charset in content type, peek at response body + if (!res && this._raw.length > 0) { + if (this.headers.get('transfer-encoding') === 'chunked') { + var buf, index = 0, length = 0; + while(length < 1024 && (buf = this._raw[index])) { + length += buf.length; + index++; + } + str = this._raw.slice(0,index).join(''); + } else { + str = this._raw[0].toString(); + } + str = str.substr(0, 1024); + } + + // html5 + if (!res && str) { + res = / { + arango.reconnect(arango.getEndpoint(), dbname, user, ''); +}; + +const wait = (keySpaceId, key) => { + for (let i = 0; i < 200; i++) { + if (getKey(keySpaceId, key)) break; + require('internal').wait(0.1); + } +}; + +const createKeySpace = (keySpaceId) => { + return executeJS(`return global.KEYSPACE_CREATE('${keySpaceId}', 128, true);`).body === 'true'; +}; + +const dropKeySpace = (keySpaceId) => { + executeJS(`global.KEYSPACE_DROP('${keySpaceId}');`); +}; + +const getKey = (keySpaceId, key) => { + return executeJS(`return global.KEY_GET('${keySpaceId}', '${key}');`).body === 'true'; +}; + +const setKey = (keySpaceId, name) => { + return executeJS(`global.KEY_SET('${keySpaceId}', '${name}', false);`); +}; + +const executeJS = (code) => { + let httpOptions = pu.makeAuthorizationHeaders({ + username: 'root', + password: '' + }); + httpOptions.method = 'POST'; + httpOptions.timeout = 1800; + httpOptions.returnBodyOnError = true; + return download(arango.getEndpoint().replace('tcp', 'http') + `/_db/${dbName}/_admin/execute?returnAsJSON=true`, + code, + httpOptions); +}; + +switchUser('root', '_system'); +helper.removeAllUsers(); + +describe('User Rights Management', () => { + before(helper.generateAllUsers); + after(helper.removeAllUsers); + + it('should check if all users are created', () => { + switchUser('root', '_system'); + expect(userSet.size).to.equal(helper.userCount); + for (let name of userSet) { + expect(users.document(name), `Could not find user: ${name}`).to.not.be.undefined; + } + }); + + it('should test rights for', () => { + for (let name of userSet) { + let canUse = false; + try { + switchUser(name, dbName); + canUse = true; + } catch (e) { + canUse = false; + } + + if (canUse) { + describe(`user ${name}`, () => { + before(() => { + switchUser(name, dbName); + expect(createKeySpace(keySpaceId)).to.equal(true, 'keySpace creation failed!'); + }); + + after(() => { + dropKeySpace(keySpaceId); + }); + + describe('update on collection level', () => { + const rootTestCollection = (switchBack = true) => { + switchUser('root', dbName); + let col = db._collection(colName); + if (switchBack) { + switchUser(name, dbName); + } + return col !== null; + }; + + const rootPrepareCollection = () => { + if (rootTestCollection(false)) { + db._collection(colName).truncate(); + db._collection(colName).save({_key: '123'}); + db._collection(colName).save({_key: '456'}); + } + switchUser(name, dbName); + }; + + describe('remove a document', () => { + before(() => { + db._useDatabase(dbName); + rootPrepareCollection(); + }); + + it('by key', () => { + expect(rootTestCollection()).to.equal(true, 'Precondition failed, the collection does not exist.'); + setKey(keySpaceId, name); + const taskId = 'task_collection_level_drop_by_key' + name; + const task = { + id: taskId, + name: taskId, + command: `(function (params) { + try { + const db = require('@arangodb').db; + db._collection('${colName}').remove('123'); + global.KEY_SET('${keySpaceId}', '${name}_status', true); + } catch (e) { + global.KEY_SET('${keySpaceId}', '${name}_status', false); + } finally { + global.KEY_SET('${keySpaceId}', '${name}', true); + } + })(params);` + }; + if (dbLevel['rw'].has(name)) { + if ((dbLevel['rw'].has(name) || dbLevel['ro'].has(name)) && + colLevel['rw'].has(name)) { + let col = db._collection(colName); + expect(col.document('123')._key).to.equal('123', 'Precondition failed, document does not exist.'); + tasks.register(task); + wait(keySpaceId, name); + expect(getKey(keySpaceId, `${name}_status`)).to.equal(true, `${name} could not drop the document with sufficient rights`); + try { + col.document('123'); + expect(true).to.be(false, `${name} could not drop the document with sufficient rights`); + } catch (e) {} + } else { + let hasReadAccess = ((dbLevel['rw'].has(name) || dbLevel['ro'].has(name)) && + (colLevel['rw'].has(name) || colLevel['ro'].has(name))); + if (hasReadAccess) { + let col = db._collection(colName); + expect(col.document('123')._key).to.equal('123', 'Precondition failed, document does not exist.'); + } + tasks.register(task); + wait(keySpaceId, name); + expect(getKey(keySpaceId, `${name}_status`)).to.not.equal(true, `${name} managed to remove the document with insufficient rights`); + if (hasReadAccess) { + let col = db._collection(colName); + try { + expect(col.document('123')._key).to.equal('123', `${name} managed to remove the document with insufficient rights`); + } catch (e) {} + } + } + } else { + try { + tasks.register(task); + expect(false).to.equal(true, `${name} managed to register a task with insufficient rights`); + } catch (e) { + expect(e.errorNum).to.equal(errors.ERROR_FORBIDDEN.code); + } + } + }); + + it('by aql', () => { + expect(rootTestCollection()).to.equal(true, 'Precondition failed, the collection does not exist'); + let q = `REMOVE '456' IN ${colName} RETURN OLD`; + setKey(keySpaceId, name); + const taskId = 'task_collection_level_drop_by_key' + name; + const task = { + id: taskId, + name: taskId, + command: `(function (params) { + try { + const db = require('@arangodb').db; + db._query("${q}"); + global.KEY_SET('${keySpaceId}', '${name}_status', true); + } catch (e) { + global.KEY_SET('${keySpaceId}', '${name}_status', false); + }finally { + global.KEY_SET('${keySpaceId}', '${name}', true); + } + })(params);` + }; + if (dbLevel['rw'].has(name)) { + if ((dbLevel['rw'].has(name) || dbLevel['ro'].has(name)) && + colLevel['rw'].has(name)) { + let col = db._collection(colName); + tasks.register(task); + wait(keySpaceId, name); + expect(getKey(keySpaceId, `${name}_status`)).to.equal(true, `${name} could not drop the document with sufficient rights`); + try { + col.document('456'); + expect(true).to.be(false, 'Document still in collection after remove'); + } catch (e) {} + } else { + let hasReadAccess = ((dbLevel['rw'].has(name) || dbLevel['ro'].has(name)) && + (colLevel['rw'].has(name) || colLevel['ro'].has(name))); + tasks.register(task); + wait(keySpaceId, name); + expect(getKey(keySpaceId, `${name}_status`)).to.not.equal(true, `${name} managed to remove the document with insufficient rights`); + if (hasReadAccess) { + let col = db._collection(colName); + try { + expect(col.document('456')._key).to.equal('456', `${name} managed to remove the document with insufficient rights`); + } catch (e) {} + } + } + } else { + try { + tasks.register(task); + expect(false).to.equal(true, `${name} managed to register a task with insufficient rights`); + } catch (e) { + expect(e.errorNum).to.equal(errors.ERROR_FORBIDDEN.code); + } + } + }); + }); + }); + }); + } + } + }); +}); diff --git a/pool/shard007/JavaScript/0047862_html_actuator.js b/pool/shard007/JavaScript/0047862_html_actuator.js new file mode 100644 index 0000000000000000000000000000000000000000..c2f32989f0a983da141528a6996e1c84b1078ffa --- /dev/null +++ b/pool/shard007/JavaScript/0047862_html_actuator.js @@ -0,0 +1,140 @@ +function HTMLActuator() { + this.tileContainer = document.querySelector(".tile-container"); + this.scoreContainer = document.querySelector(".score-container"); + this.bestContainer = document.querySelector(".best-container"); + this.messageContainer = document.querySelector(".game-message"); + + this.score = 0; +} + +HTMLActuator.prototype.actuate = function (grid, metadata, callback) { + var self = this; + + window.requestAnimationFrame(function () { + self.clearContainer(self.tileContainer); + + grid.cells.forEach(function (column) { + column.forEach(function (cell) { + if (cell) { + self.addTile(cell); + } + }); + }); + + self.updateScore(metadata.score); + self.updateBestScore(metadata.bestScore); + + if (metadata.terminated) { + if (metadata.over) { + self.message(false); // You lose + } else if (metadata.won) { + self.message(true); // You win! + } + } + if(callback) callback(); + }); + +}; + +// Continues the game (both restart and keep playing) +HTMLActuator.prototype.continueGame = function () { + this.clearMessage(); +}; + +HTMLActuator.prototype.clearContainer = function (container) { + while (container.firstChild) { + container.removeChild(container.firstChild); + } +}; + +HTMLActuator.prototype.addTile = function (tile) { + var self = this; + + var wrapper = document.createElement("div"); + var inner = document.createElement("div"); + var position = tile.previousPosition || { x: tile.x, y: tile.y }; + var positionClass = this.positionClass(position); + + // We can't use classlist because it somehow glitches when replacing classes + var classes = ["tile", "tile-" + tile.value, positionClass]; + + if (tile.value > 2048) classes.push("tile-super"); + + this.applyClasses(wrapper, classes); + + inner.classList.add("tile-inner"); + inner.textContent = tile.value; + + if (tile.previousPosition) { + // Make sure that the tile gets rendered in the previous position first + window.requestAnimationFrame(function () { + classes[2] = self.positionClass({ x: tile.x, y: tile.y }); + self.applyClasses(wrapper, classes); // Update the position + }); + } else if (tile.mergedFrom) { + classes.push("tile-merged"); + this.applyClasses(wrapper, classes); + + // Render the tiles that merged + tile.mergedFrom.forEach(function (merged) { + self.addTile(merged); + }); + } else { + classes.push("tile-new"); + this.applyClasses(wrapper, classes); + } + + // Add the inner part of the tile to the wrapper + wrapper.appendChild(inner); + + // Put the tile on the board + this.tileContainer.appendChild(wrapper); +}; + +HTMLActuator.prototype.applyClasses = function (element, classes) { + element.setAttribute("class", classes.join(" ")); +}; + +HTMLActuator.prototype.normalizePosition = function (position) { + return { x: position.x + 1, y: position.y + 1 }; +}; + +HTMLActuator.prototype.positionClass = function (position) { + position = this.normalizePosition(position); + return "tile-position-" + position.x + "-" + position.y; +}; + +HTMLActuator.prototype.updateScore = function (score) { + this.clearContainer(this.scoreContainer); + + var difference = score - this.score; + this.score = score; + + this.scoreContainer.textContent = this.score; + + if (difference > 0) { + var addition = document.createElement("div"); + addition.classList.add("score-addition"); + addition.textContent = "+" + difference; + + this.scoreContainer.appendChild(addition); + } +}; + +HTMLActuator.prototype.updateBestScore = function (bestScore) { + this.bestContainer.textContent = bestScore; +}; + +HTMLActuator.prototype.message = function (won) { + var type = won ? "game-won" : "game-over"; + var message = won ? "You win!" : "Game over!"; + + this.messageContainer.classList.add(type); + this.messageContainer.getElementsByTagName("p")[0].textContent = message; +}; + +HTMLActuator.prototype.clearMessage = function () { + // IE only takes one value to remove at a time. + this.messageContainer.classList.remove("game-won"); + this.messageContainer.classList.remove("game-over"); +}; diff --git a/pool/shard007/JavaScript/0047863_howter.js b/pool/shard007/JavaScript/0047863_howter.js new file mode 100644 index 0000000000000000000000000000000000000000..45f0589321dd72f6f89dd981cc037f3e876f9831 --- /dev/null +++ b/pool/shard007/JavaScript/0047863_howter.js @@ -0,0 +1,89 @@ +/*jslint ass: true, forin: true, plusplus: true, regexp: true */ +(function (global) { + + 'use strict'; + + var h = global.Howter || {}, + routes = {}, + routesCount = 0, + shared = {}; + + // Ember.js inspired root + // (http://emberjs.com/guides/routing/#toc_specifying-a-root-url). + h.root = h.root || ''; + + // Dispatch a path. + h.dispatch = function (path) { + var name; + + // Trailing slashes are not meaningful. + path = path.replace(/\/$/, ''); + + for (name in routes) { + routes[name].test(path); + } + + return this; + }; + + // Laravel inspired route prefixing + // (http://laravel.com/docs/routing#route-prefixing). + h.prefix = function (prefix, callback) { + var oldRoot = this.root; + + this.root += prefix; + + callback.call(this); + + this.root = oldRoot; + + return this; + }; + + // Get a route or set a new one. + h.route = function (paths, callback, name) { + var i; + + // Getter... + if (callback === undefined) { + name = paths; + + return routes[name]; + } + + // ... or setter. + if (paths.constructor !== Array) { + paths = [paths]; + } + + for (i = 0; i < paths.length; i++) { + if (paths[i].constructor === String) { + paths[i] = this.root + paths[i]; + } + } + + name = name || routesCount; + routes[name] = new h.Route(paths, callback); + + routesCount++; + + return this; + }; + + // Universal data sharing. + h.share = function (key, data) { + // Getter... + if (data === undefined) { + return shared[key]; + } + + // ... or setter. + shared[key] = data; + + return this; + } + + // Export. + global.Howter = h; + +}(this)); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0047865_blogPost.js b/pool/shard007/JavaScript/0047865_blogPost.js new file mode 100644 index 0000000000000000000000000000000000000000..683b62059490f3514e49d31e5f0ac82c3650ac33 --- /dev/null +++ b/pool/shard007/JavaScript/0047865_blogPost.js @@ -0,0 +1,119 @@ +import React from "react"; +import Link from "gatsby-link"; +import Helmet from "react-helmet"; +import { DiscussionEmbed } from "disqus-react"; + +import styles from "../styles/Post.module.css"; + +export default function Template({ data }) { + // this prop will be injected by the GraphQL query below. + const { markdownRemark, allMarkdownRemark } = data; // data.markdownRemark holds our post data + const { frontmatter, html } = markdownRemark; + const post = markdownRemark.frontmatter; + + const disqusShortname = "mateoolarte"; + + const disqusConfig = { + url: post.url, + identifier: post.id.toString(), + title: post.title + }; + + const currentPostTitle = frontmatter.title; + const postsShuffled = allMarkdownRemark.edges + .map(a => [Math.random(), a]) + .sort((a, b) => a[0] - b[0]) + .map(a => a[1]); + let otherPosts = []; + + postsShuffled.forEach((edge, index) => { + if (edge.node.frontmatter.title !== currentPostTitle) { + if (otherPosts.length !== 3) { + otherPosts.push(edge); + } + } + + return otherPosts; + }); + + return ( +
+ +
+

{frontmatter.title}

+

{frontmatter.date}

+
+ {frontmatter.title} + {frontmatter.copyright.length > 0 && ( +
Tomado de: {frontmatter.copyright}
+ )} +
+
+
+ {allMarkdownRemark.edges.length > 2 && ( +
+

+ También te puede interesar +

+
+ {otherPosts.map((post, i) => { + return ( + + {post.node.frontmatter.title} +
+ {post.node.frontmatter.title} +
+ + ); + })} +
+
+ )} + +
+ ); +} + +export const pageQuery = graphql` + query IndexQueryAndBlogPostByPath($path: String!) { + markdownRemark(frontmatter: { path: { eq: $path } }) { + html + frontmatter { + id + url + date(formatString: "MMMM DD, YYYY") + path + title + thumbnail + cover + copyright + } + } + + allMarkdownRemark(limit: 10) { + edges { + node { + frontmatter { + path + title + thumbnail + } + } + } + } + } +`; diff --git a/pool/shard007/JavaScript/0047872_login.js b/pool/shard007/JavaScript/0047872_login.js new file mode 100644 index 0000000000000000000000000000000000000000..167e6457cb19e7463725d8d207b11415730e56f7 --- /dev/null +++ b/pool/shard007/JavaScript/0047872_login.js @@ -0,0 +1,24 @@ +'use strict'; +app + .component('login', + { + templateUrl: 'spa/src/components/login/login.html', + controller: function ($scope, $state, LoginService, SweetAlert) { + const $ctrl = this; + $ctrl.title = 'Login'; + $ctrl.logIn = (username, password) => LoginService.login(username, password) + .then(response => { + if (response.status === 200) { + angular.copy(response, $scope.token); + $state.go('dashboard'); + } + if (response.status === 404) { + SweetAlert.swal("Email or passwrod incorect"); + $ctrl.password = ''; + $ctrl.username = ''; + } + }); + $ctrl.signUp = () => $state.go('sign-up'); + $ctrl.goToHome = () => $state.go('dashboard'); + } + }); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0047873_tickets.js b/pool/shard007/JavaScript/0047873_tickets.js new file mode 100644 index 0000000000000000000000000000000000000000..20f2b78b04c3548388490593a1834f5221eabd71 --- /dev/null +++ b/pool/shard007/JavaScript/0047873_tickets.js @@ -0,0 +1,74 @@ +$(document).on('turbolinks:load', function() { + + // Next Ticket button functionality + $(function () { + $("#js-next").on("click", function() { + var nextId = parseInt($("#js-next").attr("data-id")) + 1; + $.getJSON(`/tickets/${nextId}`, function(data){ + + // Updates Ticket information after "Next Ticket" is clicked + $(".ticketTitle").text(data["title"]); + $(".ticketId").text(data["id"]); + var date = new Date(data["due_date"]) + $(".ticketDueDate").text(`${date.getMonth()+1}/${date.getDate()}/${date.getFullYear()}`); + $(".ticketLocation").text(data["user_tickets"][0]["location"]); + $(".ticketStatus").text(data["status"]); + $("#js-next").attr("data-id", data["id"]); + window.history.replaceState( {}, null, `${data["id"]}`); // Updates browser URL to visible Ticket + + // Edit and Delete Tickets button attributes are updated when Next Ticket is pressed. + $("#edit-ticket-button").attr("href", `/tickets/${data["id"]}/edit`); + $("#delete-ticket-button").attr({ + "data-confirm": "Are you sure?", + "class": "btn btn-danger btn-xs", + "rel": "nofollow", + "data-method": "delete", + "href": `/tickets/${data["id"]}` + }); + + // Updates Issues information after "Next Ticket" is clicked. + $(".list-group").text("") // Clears out visible issues. + data["issues"].forEach(function(el) { + var li = document.createElement('li'); + li.setAttribute('class', 'list-group-item') + li.innerHTML = `${el["status"]}${el["title"]}`; + $(".list-group").append(li); + }); + + // Add Issue button href is updated when Next Ticket is pressed" + $("#add-issue-button").attr("href", `/tickets/${data["id"]}/issues/new`); + }); + }); + }); + + // New Issue Form is Serialized and Posted. New Issue Section is cleared out. + $(function () { + $("#add-issue-button").on("click", function(e) { + $addIssueButton = $("a#add-issue-button") + $("a#add-issue-button").remove(); // Removes the Add Issue button + + $.get(this.href).success(function(response) { // Goes out and grabs HTML from this.href + $("#new-issue-form").html(response); // Add the New Issue Form to #new-issue-form element in HTML + + // New Issue Form is loaded and adds new Issue to
  • after Submitted. + $('form').submit(function(e){ + var values = $(this).serialize(); + var action = $('form').attr("action"); + var posting = $.post(action, values); + + posting.done(function(data) { + var li = document.createElement('li'); + li.setAttribute('class', 'list-group-item') + li.innerHTML = `${data["status"]}${data["title"]}`; + $(".list-group").append(li); // Append new issue to
  • + $("div.jumbotron").append($addIssueButton); // Append the Add Issue back + }); + $("#new-issue-section").text("") //clears out New Issue form html + e.preventDefault(); + }); + }); + e.preventDefault(); + }); + }); + +}); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0047875_app.js b/pool/shard007/JavaScript/0047875_app.js new file mode 100644 index 0000000000000000000000000000000000000000..c7f1a1fa9c8f397184c21bf9ee93563c58c7e57a --- /dev/null +++ b/pool/shard007/JavaScript/0047875_app.js @@ -0,0 +1,70 @@ +var express = require('express'); +var path = require('path'); +var favicon = require('static-favicon'); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); + +var routes = require('./routes/index'); +var users = require('./routes/users'); +var json = require('./routes/json'); +var getallbids = require('./routes/getallbids'); +var getbids = require('./routes/getbids'); +var makebid = require('./routes/makebid'); +var createuser = require('./routes/createuser'); + +var app = express(); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'jade'); + +app.use(favicon()); +app.use(logger('dev')); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded()); +app.use(cookieParser()); +app.use(require('stylus').middleware(path.join(__dirname, 'public'))); +app.use(express.static(path.join(__dirname, 'public'))); + +app.use('/', routes); +app.use('/users', users); +app.use('/json', json); +app.use('/getallbids', getallbids); +app.use('/getbids', getbids); +app.use('/makebid', makebid); +app.use('/createuser', createuser); + +/// catch 404 and forwarding to error handler +app.use(function (req, res, next) { + var err = new Error('Not Found 404'); + err.status = 404; + next(err); +}); + +/// error handlers + +// development error handler +// will print stacktrace +if (app.get('env') === 'development') { + app.use(function (err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: err + }); + }); +} + +// production error handler +// no stacktraces leaked to user +app.use(function (err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: {} + }); +}); + + +module.exports = app; diff --git a/pool/shard007/JavaScript/0047877_qa_annotation_listing.js b/pool/shard007/JavaScript/0047877_qa_annotation_listing.js new file mode 100644 index 0000000000000000000000000000000000000000..7848140c76eb052837501f6f7c69e4814e43f1b7 --- /dev/null +++ b/pool/shard007/JavaScript/0047877_qa_annotation_listing.js @@ -0,0 +1,69 @@ +dc.ui.QAAnnotationListing = dc.ui.BaseAnnotationListing.extend({ + + showApprove: true, + showReject: true, + + initialize: function() { + dc.ui.BaseAnnotationListing.prototype.initialize.apply(this, arguments); + + this.events['click .approve_item'] = 'handleApprove'; + this.events['click .reject_item'] = 'handleReject'; + this.events['click .point_note'] = 'handleEditNote'; + }, + + render : function() { + dc.ui.BaseAnnotationListing.prototype.render.apply(this, arguments); + + this.$('.clone_item').hide(); + this.$('.delete_item').hide(); + + if( this.model.get('approved') ) { this.setApprove(); } + if( this.model.get('qa_reject_note') != null ){ this.setReject(); } + + return this; + }, + + + //setApprove: Sets UI to approved + setApprove: function(){ + this.$('.approve_item').hide(); + this.$('.point_note').hide(); + this.$('.row_status').removeClass('incomplete'); + this.$('.row_status').removeClass('rejected'); + this.$('.row_status').addClass('complete'); + this.$('.reject_item').show().css('display', 'inline-block'); + }, + + + //setReject: Sets UI to rejected + setReject: function(){ + this.$('.reject_item').hide(); + this.$('.row_status').removeClass('incomplete'); + this.$('.row_status').removeClass('complete'); + this.$('.row_status').addClass('rejected'); + this.$('.approve_item').show().css('display', 'inline-block'); + this.$('.point_note').show().css('display', 'inline-block'); + }, + + + handleApprove: function(){ + this.model.set({approved: true, qa_reject_note: null}); + this.setApprove(false); + this.trigger('qaAddress', this); + }, + + + handleReject: function(){ + var _thisView = this; + dc.ui.QARejectDialog.open(_thisView.model, false, function(){ + _thisView.setReject(); + _thisView.trigger('qaAddress', _thisView); + }); + }, + + + handleEditNote: function(){ + var _thisView = this; + dc.ui.QARejectDialog.open(_thisView.model, function(){}); + } +}); diff --git a/pool/shard007/JavaScript/0047880_app.js b/pool/shard007/JavaScript/0047880_app.js new file mode 100644 index 0000000000000000000000000000000000000000..33e435f90b9f1e8e892e3ed56f3f7340266d54e3 --- /dev/null +++ b/pool/shard007/JavaScript/0047880_app.js @@ -0,0 +1,59 @@ +import Express from 'express'; +import compression from 'compression'; +import http from 'http'; +import favicon from 'serve-favicon'; +import Path from 'path'; +import chalk from 'chalk'; +import httpProxy from 'http-proxy'; +import { default as routes } from '../routes'; +import { checkAuth, RenderPage } from '../../../common/server/middleware'; +import {getConfig} from '../../../common/utils/helpers'; + +const {apiPort} = getConfig().default; + +const proxy = httpProxy.createServer({ + target: `http://127.0.0.1:${apiPort}/api` +}); + +proxy.on('error', (error, req, res) => { + let json; + if (error.code !== 'ECONNRESET') { + console.error('proxy error', error); + } + if (!res.headersSent) { + res.writeHead(500, {'content-type': 'application/json'}); + } + + json = {error: 'proxy_error', reason: error.message}; + res.end(JSON.stringify(json)); +}); + + +const renderPage = RenderPage({ routes }); +const app = new Express(); +const server = new http.Server(app); +const serverPort = process.env.PORT; +const staticRoot = Path.join(__dirname, '../../../../', `statics/${__APPNAME__}`); + +app.use(compression()); +app.use(favicon(Path.join(staticRoot, 'favicon_.ico'))); +app.use(Express.static(staticRoot)); + +app.use('/api', (req, res) => { + proxy.web(req, res) +}); + + +app.use(checkAuth, renderPage); + + +app.use((req, res, next)=>{ + console.log('sss'); + res.status(404).send('not_found'); +}); + +server.listen(serverPort, (err) => { + if (err) + return console.render(chalk.red(err)); + console.log(chalk.green('Server is running on port:'), serverPort); +}); diff --git a/pool/shard007/JavaScript/0047883_2010002.js b/pool/shard007/JavaScript/0047883_2010002.js new file mode 100644 index 0000000000000000000000000000000000000000..1f29480f00f54bd0c334385e7b44bd243a375395 --- /dev/null +++ b/pool/shard007/JavaScript/0047883_2010002.js @@ -0,0 +1,91 @@ +/* + This file is part of the OdinMS Maple Story Server + Copyright (C) 2008 Patrick Huy + Matthias Butz + Jan Christian Meyer + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License version 3 + as published by the Free Software Foundation. You may not use, modify + or distribute this program under any other version of the + GNU Affero General Public License. + + 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 . +*/ + +/* Franz the Owner + Orbis VIP Eye Change. +*/ +var status = 0; +var beauty = 0; +var price = 1000000; +var mface = Array(20000, 20001, 20002, 20003, 20004, 20005, 20006, 20007, 20008, 20012, 20014); +var fface = Array(21000, 21001, 21002, 21003, 21004, 21005, 21006, 21007, 21008, 21012, 21014); +var facenew = Array(); + +function start() { + status = -1; + action(1, 0, 0); +} + +function action(mode, type, selection) { + if (mode == -1) { + cm.dispose(); + } else { + if (mode == 0 && status == 0) { + cm.dispose(); + return; + } + if (mode == 1) + status++; + else + status--; + if (status == 0) { + cm.sendSimple("Well well well, welcome to the Orbis Plastic Surgery! Would you like to transform your face into something new? With a #b#t5152005##k, you can let us take care of the rest and have the face you've always wanted~!\r\n#L1#I would like to buy a #b#t5152005##k for " + price + " mesos, please!#l\r\n\#L2#I already have a Coupon!#l"); + } else if (status == 1) { + if (selection == 1) { + if(cm.getMeso() >= price) { + cm.gainMeso(-price); + cm.gainItem(5152005, 1); + cm.sendOk("Enjoy!"); + } else { + cm.sendOk("You don't have enough mesos to buy a coupon!"); + } + cm.dispose(); + } else if (selection == 2) { + facenew = Array(); + if (cm.getPlayer().getGender() == 0) { + for(var i = 0; i < mface.length; i++) { + facenew.push(mface[i] + cm.getPlayer().getFace() + % 1000 - (cm.getPlayer().getFace() + % 100)); + } + } + if (cm.getPlayer().getGender() == 1) { + for(var i = 0; i < fface.length; i++) { + facenew.push(fface[i] + cm.getPlayer().getFace() + % 1000 - (cm.getPlayer().getFace() + % 100)); + } + } + cm.sendStyle("I can totally transform your face into something new... how about giving us a try? For #b#t5152005##k, you can get the face of your liking...take your time in choosing the face of your preference.", facenew); + } + } + else if (status == 2){ + cm.dispose(); + if (cm.haveItem(5152005) == true){ + cm.gainItem(5152005, -1); + cm.setFace(facenew[selection]); + cm.sendOk("Enjoy your new and improved face!"); + } else { + cm.sendOk("Hmm ... it looks like you don't have the coupon specifically for this place. Sorry to say this, but without the coupon, there's no plastic surgery for you..."); + } + } + } +} diff --git a/pool/shard007/JavaScript/0047885_test.controller.js b/pool/shard007/JavaScript/0047885_test.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..697a7d646e68b671dd3a8c1202d32cd9bec1c0d9 --- /dev/null +++ b/pool/shard007/JavaScript/0047885_test.controller.js @@ -0,0 +1,20 @@ +(function () { + 'use strict'; + + angular + .module('jfy') + .controller('TestController', TestController); + + /** @ngInject */ + function TestController($scope, ImportExportToExcel) { + var vm = this; + + vm.tableData = [{a: 1, b: 10}, {a: 2, b: 20}]; + vm.export = function () { + ImportExportToExcel.exportToExcel('test', vm.tableData); + }; + $scope.$on('import-excel-data', function (e, v) { + console.log('excel-data:', v) + }); + } +})(); diff --git a/pool/shard007/JavaScript/0047889_CompositeSprite.js b/pool/shard007/JavaScript/0047889_CompositeSprite.js new file mode 100644 index 0000000000000000000000000000000000000000..be08a6f2bf6a16766d9ecbc7ecfef03ccb50bf4d --- /dev/null +++ b/pool/shard007/JavaScript/0047889_CompositeSprite.js @@ -0,0 +1,51 @@ +/* +This file is part of Ext JS 4.2 + +Copyright (c) 2011-2013 Sencha Inc + +Contact: http://www.sencha.com/contact + +Commercial Usage +Licensees holding valid commercial licenses may use this file in accordance with the Commercial +Software License Agreement provided with the Software or, alternatively, in accordance with the +terms contained in a written agreement between you and Sencha. + +If you are unsure which license is appropriate for your use, please contact the sales department +at http://www.sencha.com/contact. + +Build date: 2013-09-18 17:18:59 (940c324ac822b840618a3a8b2b4b873f83a1a9b1) +*/ +/** + * @class Ext.fx.target.CompositeSprite + +This class represents a animation target for a {@link Ext.draw.CompositeSprite}. It allows +each {@link Ext.draw.Sprite} in the group to be animated as a whole. In general this class will not be +created directly, the {@link Ext.draw.CompositeSprite} will be passed to the animation and +and the appropriate target will be created. + + * @markdown + */ + +Ext.define('Ext.fx.target.CompositeSprite', { + + /* Begin Definitions */ + + extend: 'Ext.fx.target.Sprite', + + /* End Definitions */ + + getAttr: function(attr, val) { + var out = [], + sprites = [].concat(this.target.items), + length = sprites.length, + i, + sprite; + + for (i = 0; i < length; i++) { + sprite = sprites[i]; + out.push([sprite, val != undefined ? val : this.getFromPrim(sprite, attr)]); + } + + return out; + } +}); diff --git a/pool/shard007/JavaScript/0047898_queensland.js b/pool/shard007/JavaScript/0047898_queensland.js new file mode 100644 index 0000000000000000000000000000000000000000..dd33a1748f9e6d2022b901bbfa443ec25763c1e1 --- /dev/null +++ b/pool/shard007/JavaScript/0047898_queensland.js @@ -0,0 +1,121 @@ +'use strict'; + +import { REQUEST_TIMEOUT } from '../lib/constants'; +import { default as baseRequest } from 'request'; +import _ from 'lodash'; +import { default as moment } from 'moment-timezone'; +import cheerio from 'cheerio'; +import { removeUnwantedParameters } from '../lib/utils'; +const request = baseRequest.defaults({timeout: REQUEST_TIMEOUT}); + +exports.name = 'queensland'; + +exports.fetchData = function (source, cb) { + request(source.url, function (err, res, body) { + if (err || res.statusCode !== 200) { + return cb(err || res); + } + + try { + var data = formatData(body, source); + var result = { + name: 'unused', + measurements: _.flatten(data) + }; + + result.measurements = removeUnwantedParameters(result.measurements); + return cb(null, result); + } catch (e) { + return cb({message: 'Unknown adapter error.'}); + } + }); +}; + +const renameParameter = function (parameter) { + switch (parameter) { + case 'Nitrogen Dioxide': + return 'no2'; + case 'Sulfur Dioxide': + return 'so2'; + case 'Carbon Monoxide': + return 'co'; + case 'Particle PM2.5': + return 'pm25'; + case 'Ozone': + return 'o3'; + case 'Particle PM10': + return 'pm10'; + default: + return parameter; + } +}; + +const getParameterUnit = function (parameter) { + switch (parameter) { + case 'pm25': + case 'pm10': + case 'bc': + return 'µg/m³'; + case 'no2': + case 'so2': + case 'o3': + case 'co': + return 'ppm'; + default: + return '?'; + } +}; + +// hardcoded coordinates for locations with no coordinates from source +var locationCoordinates = { + 'Miles Airport': { latitude: -26.8088, longitude: 150.1799 }, + 'Hopeland': { latitude: -26.8637, longitude: 150.5028 } +}; + +var formatData = function (data, source) { + var $ = cheerio.load(data, {xmlMode: true}); + + var dateStr = $('category').attr('measurementdate') + $('category').attr('measurementhour'); + var date = moment.tz(dateStr, 'YYYY-MM-DDHH', 'Australia/Queensland'); + var dates = {utc: date.toDate(), local: date.format()}; + + var measurements = []; + + $('measurement').each(function (i, elem) { + var location = $(this).parent().attr('name'); + var param = renameParameter($(this).attr('name')); + + var m = { + date: dates, + parameter: param, + location: location, + value: Number($(this).text()), + unit: getParameterUnit(param), + city: $(this).parent().parent().attr('name'), + attribution: [{ + name: 'The State of Queensland (Department of Environment and Science)', + url: source.sourceURL + }, { + name: 'The State of Queensland (Department of Environment and Science)', + url: $(this).parent().attr('information') + }], + averagingPeriod: {'value': 1, 'unit': 'hours'} + }; + + // Add coordinates if they're available + if ($(this).parent().attr('latitude') && $(this).parent().attr('longitude') && Number($(this).parent().attr('latitude')) !== 0 && Number($(this).parent().attr('longitude')) !== 0) { + m.coordinates = { + latitude: Number($(this).parent().attr('latitude')), + longitude: Number($(this).parent().attr('longitude')) + }; + } + + if (!m.coordinates && locationCoordinates[m.location]) { + m.coordinates = locationCoordinates[m.location]; + } + + measurements.push(m); + }); + + return measurements; +}; diff --git a/pool/shard007/JavaScript/0047899_product.js b/pool/shard007/JavaScript/0047899_product.js new file mode 100644 index 0000000000000000000000000000000000000000..415e35750fed207be02d92bd5704aecba0bcd544 --- /dev/null +++ b/pool/shard007/JavaScript/0047899_product.js @@ -0,0 +1,19 @@ +"use strict"; + +const ProductCtrl = require('../ctrl/product'); + +module.exports = class ProductRoutes { + static init(router) { + + router + .route('/api/v1/products') + .get(ProductCtrl.list) + .post(ProductCtrl.save); + + router + .route('/api/v1/products/:id') + .get(ProductCtrl.getWithCartNumb) + .delete(ProductCtrl.delete); + + } +} diff --git a/pool/shard007/JavaScript/0047900_users.js b/pool/shard007/JavaScript/0047900_users.js new file mode 100644 index 0000000000000000000000000000000000000000..7063e1ab01a85c44598ba62d70f40a572d3a5b9f --- /dev/null +++ b/pool/shard007/JavaScript/0047900_users.js @@ -0,0 +1,71 @@ +var express = require('express'); +var router = express.Router(); +var User = require('../models/User'); + +/* GET users listing. */ +router.get('/', function(req, res, next) { + res.send('respond with a resource'); +}); + +router.get('/check',function (req, res, next) { + console.log('get usercheck---'); + res.end() +}); + +router.post('/reg', function(req,res,next) { + var data = req.body; + + // 这个回调黑洞真是要命!!! 想用Promise!!!!想用await!!! + User.findOne({user_name: data.user_name},function(err,user){ + if (err) { + res.send(new Error(err)); + } else { + if (user) { + console.log('user---',user); + res.send({msg:"exist"}) + } else { + + User.findOne({email: data.email}, function(err,user){ + if (err) { + res.send(new Error(err)); + } else { + if (user) {res.send({msg: 'email_exist'})} else { + var newUser = new User({ + user_name: data.user_name, + email: data.email, + password: data.password, + }); + newUser.save(); + res.send({msg: 'success'}) + } + } + }) + } + } + }) + +}); + +router.post('/login', function(req, res, next) { + var data = req.body; + console.log('data---',data); + User.findOne({email: data.email},function(err,user){ + console.log('err',err,'user',user); + if (err) { + res.send(new Error(err)) + } else { + if (user) { + if (user.password == data.password) { + // 登录成功的后端操作 todo + res.send({msg:'success',token:user._id}); + } else { + res.send({msg: 'pass_err'}) + } + } else { + res.send({msg:'not_exist'}) + } + } + }) +}); + +module.exports = router; diff --git a/pool/shard007/JavaScript/0047904_InvoiceSettingsApi.spec.js b/pool/shard007/JavaScript/0047904_InvoiceSettingsApi.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..f947349cf6ef801f70fa32c7719b72ef319fd751 --- /dev/null +++ b/pool/shard007/JavaScript/0047904_InvoiceSettingsApi.spec.js @@ -0,0 +1,63 @@ +/** + * AvaTax Brazil + * The Avatax-Brazil API exposes the most commonly services available for interacting with the AvaTax-Brazil services, allowing calculation of taxes, issuing electronic invoice documents and modifying existing transactions when allowed by tax authorities. This API is exclusively for use by business with a physical presence in Brazil. + * + * OpenAPI spec version: 1.0 + * + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.AvaTaxBrazil); + } +}(this, function(expect, AvaTaxBrazil) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new AvaTaxBrazil.InvoiceSettingsApi(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('InvoiceSettingsApi', function() { + describe('invoiceSettings', function() { + it('should call invoiceSettings successfully', function(done) { + //uncomment below and update the code to test invoiceSettings + //instance.invoiceSettings(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + }); + +})); diff --git a/pool/shard007/JavaScript/0047908_race-participant-detail.controller.js b/pool/shard007/JavaScript/0047908_race-participant-detail.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..95253ae4a533eb348845412dda59be1a6d7f2ad9 --- /dev/null +++ b/pool/shard007/JavaScript/0047908_race-participant-detail.controller.js @@ -0,0 +1,20 @@ +(function() { + 'use strict'; + + angular + .module('gpmrApp') + .controller('RaceParticipantDetailController', RaceParticipantDetailController); + + RaceParticipantDetailController.$inject = ['$scope', '$rootScope', '$stateParams', 'entity', 'RaceParticipant']; + + function RaceParticipantDetailController($scope, $rootScope, $stateParams, entity, RaceParticipant) { + var vm = this; + vm.raceParticipant = entity; + + var unsubscribe = $rootScope.$on('gpmrApp:raceParticipantUpdate', function(event, result) { + vm.raceParticipant = result; + }); + $scope.$on('$destroy', unsubscribe); + + } +})(); diff --git a/pool/shard007/JavaScript/0047909_app.js b/pool/shard007/JavaScript/0047909_app.js new file mode 100644 index 0000000000000000000000000000000000000000..ffacb4c49e982dadbb2f82a0cec9ba5d8b61cde2 --- /dev/null +++ b/pool/shard007/JavaScript/0047909_app.js @@ -0,0 +1,67 @@ +var express = require('express'); +var path = require('path'); +var pogg = require('pogg').globalize(); + +var routes = require('./routes/index'); + +var app = express(); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'ejs'); +app.set('title', '<%= name %>'); +logg.big.green(app.get('title')); + +app.use(express.static(path.join(__dirname, 'public'))); + +app.use('/', routes); + +// catch 404 and forward to error handler +app.use(function (req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + +// error handlers + +// development error handler +// will print stacktrace +if (app.get('env') === 'development') { + app.use(function (err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: err + }); + }); +} + +// production error handler +// no stacktraces leaked to user +app.use(function (err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: {} + }); +}); + +//Set port to env.Port or default to 1337 +app.set('port', process.env.PORT || 1337); +//Listen to port for connections +app.listen(app.get('port'), function () { + // delay so these info show after the big title log + setTimeout(function () { + logg.green('> port: ' + app.get('port')); + logg.green('> pid: ' + process.pid); + logg.green('> env: ' + process.env.NODE_ENV); + }, 10); +}); + +process.on('SIGTERM', function () { + console.log('Connection terminated'); +}); + +module.exports = app; + diff --git a/pool/shard007/JavaScript/0047911_ProfileAddressForm.js b/pool/shard007/JavaScript/0047911_ProfileAddressForm.js new file mode 100644 index 0000000000000000000000000000000000000000..672382efd32da3803617a523ed1bf62ecbb64e95 --- /dev/null +++ b/pool/shard007/JavaScript/0047911_ProfileAddressForm.js @@ -0,0 +1,202 @@ +import React from 'react'; +import PropTypes from 'prop-types'; +import { compose, branch, renderComponent, setPropTypes, pure } from 'recompose'; +import Yup from 'yup'; +import { withFormik } from 'formik'; +import get from 'lodash/get'; +import ActivityIndicator from '@ui/ActivityIndicator'; +import * as Inputs from '@ui/inputs'; +import TableView from '@ui/TableView'; +import PaddedView from '@ui/PaddedView'; +import withUser from '@data/withUser'; +import Button from '@ui/Button'; +import { H6 } from '@ui/typography'; +import styled from '@ui/styled'; +import { withFieldValueHandler, withFieldTouchedHandler } from './formikSetters'; + +const Status = styled({ textAlign: 'center' })(H6); + +const enhance = compose( + setPropTypes({ + createFieldTouchedHandler: PropTypes.func, + handleSubmit: PropTypes.func, + countries: PropTypes.arrayOf( + PropTypes.shape({ + id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), + label: PropTypes.string, + }), + ), + states: PropTypes.arrayOf( + PropTypes.shape({ + id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), + label: PropTypes.string, + }), + ), + values: PropTypes.shape({ + street1: PropTypes.string, + street2: PropTypes.string, + countryId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), + city: PropTypes.string, + stateId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), + zip: PropTypes.string, + }), + createFieldValueHandler: PropTypes.func, + errors: PropTypes.shape({ + street1: PropTypes.string, + street2: PropTypes.string, + countryId: PropTypes.string, + city: PropTypes.string, + stateId: PropTypes.string, + zip: PropTypes.string, + }), + touched: PropTypes.shape({ + street1: PropTypes.bool, + street2: PropTypes.bool, + countryId: PropTypes.bool, + city: PropTypes.bool, + stateId: PropTypes.bool, + zip: PropTypes.bool, + }), + isSubmitting: PropTypes.bool, + isValid: PropTypes.bool, + status: PropTypes.string, + }), +); + +export const ProfileAddressFormWithoutData = enhance( + ({ + createFieldTouchedHandler, + handleSubmit, + values, + countries, + states, + createFieldValueHandler, + errors, + touched, + isSubmitting, + isValid, + status, + }) => { + const isUSOrCanada = values.countryId === 'US' || values.countryId === 'CA'; + return ( + + + + + + country.id === values.countryId), + 'label', + )} + onValueChange={createFieldValueHandler('countryId')} + error={touched.countryId && errors.countryId} + > + {countries.map(({ label, id }) => ( + + ))} + + + {isUSOrCanada && ( + state.id === values.stateId), 'label')} + onValueChange={createFieldValueHandler('stateId')} + error={touched.stateId && errors.stateId} + > + {states.map(({ label, id }) => ( + + ))} + + )} + + + + {status ? {status} : null} + + + + + ) + } + + render() { + const { + visible, onCancel, title, + } = this.props + const { getFieldDecorator } = this.props.form + const formItemLayout = { + labelCol: { span: 5 }, + wrapperCol: { span: 17 }, + } + return ( + +
    +
    + + {getFieldDecorator('roleName', { + rules: [ + { required: true, message: '请输入角色名称' }, + // { pattern: regExpConfig.isNormalEncode, message: '请输入非特殊字符' }, + ], + })()} + + + {getFieldDecorator('sort', { + rules: [ + { required: true, message: '请输入排序数字' }, + { pattern: regExpConfig.num, message: '请输入数字' }, + ], + })()} + + + {getFieldDecorator('tjFlag', { + initialValue: '1', + rules: [ + { required: true, message: '请选择是否统计' }, + ], + })()} + + +
    +
    +
    + ) + } +} + diff --git a/pool/shard007/JavaScript/0048044_HeroInfoLayer.js b/pool/shard007/JavaScript/0048044_HeroInfoLayer.js new file mode 100644 index 0000000000000000000000000000000000000000..b5fe9bf24e7ea774e6a233a19091f442022c2653 --- /dev/null +++ b/pool/shard007/JavaScript/0048044_HeroInfoLayer.js @@ -0,0 +1,190 @@ +var HeroInfoLayer_root; +var HeroInfoLayer = cc.Layer.extend({ + rootnode:null, + + ImageHero:null, + FontDps:null, + FontLevel:null, + TextDetails:null, + TextHeroName:null, + ImageBlack:null, + ButtonClose:null, + + heroIndex:null, + ListView_SkillList:null, + ButtonReincarnation:null, + ctor:function(){ + this._super(); + HeroInfoLayer_root = this; + HeroInfoLayer_root.rootnode = ccs.load(res.HeroInfoLayer_json).node; + + HeroInfoLayer_root.addChild(HeroInfoLayer_root.rootnode); + + HeroInfoLayer_root.ImageHero = ccui.helper.seekWidgetByName(HeroInfoLayer_root.rootnode, "ImageHero"); + HeroInfoLayer_root.TextHeroName = ccui.helper.seekWidgetByName(HeroInfoLayer_root.rootnode, "TextHeroName"); + HeroInfoLayer_root.FontLevel = ccui.helper.seekWidgetByName(HeroInfoLayer_root.rootnode, "FontLevel"); + HeroInfoLayer_root.FontDps = ccui.helper.seekWidgetByName(HeroInfoLayer_root.rootnode, "FontDps"); + HeroInfoLayer_root.TextDetails = ccui.helper.seekWidgetByName(HeroInfoLayer_root.rootnode, "TextDetails"); + HeroInfoLayer_root.ListView_SkillList = ccui.helper.seekWidgetByName(HeroInfoLayer_root.rootnode, "ListView_SkillList"); + + HeroInfoLayer_root.ButtonReincarnation = ccui.helper.seekWidgetByName(HeroInfoLayer_root.rootnode, "ButtonReincarnation"); + + ccui.helper.seekWidgetByName(HeroInfoLayer_root.rootnode, "ButtonClose").addTouchEventListener(HeroInfoLayer_root.onCloseClick); + + HeroInfoLayer_root.heroIndex = 0; + return true; + }, + setReincarnationButton:function() + { + HeroInfoLayer_root.ButtonReincarnation = ccui.helper.seekWidgetByName(HeroInfoLayer_root.rootnode, "ButtonReincarnation"); + HeroInfoLayer_root.ButtonReincarnation.setVisible(true); + }, + setHeroDate : function(heroData, level, index) { + HeroInfoLayer_root.heroIndex = index; + HeroInfoLayer_root.ImageHero.loadTexture(heroData.Icon); + HeroInfoLayer_root.TextHeroName.setString(heroData.Name); + HeroInfoLayer_root.FontLevel.setString("Lv. "+level); + + UserData.UpdateHeroDPS(); + HeroInfoLayer_root.TextDetails.setString(heroData.Desc); + HeroInfoLayer_root.FontDps.setString("DPS: "+GetShowNumFromArray(heroData.HeroDPS)); + + for (var i = 0; i < heroData.Skill.length; i++) { + var array_element = heroData.Skill[i]; + HeroInfoLayer_root.createCell(array_element, heroData.SkillUnlock[i], i); + } + }, + setUserDate : function(Data, level, index) { + HeroInfoLayer_root.heroIndex = index; + HeroInfoLayer_root.ImageHero.loadTexture(Data.Icon); + HeroInfoLayer_root.TextHeroName.setString(UserData.NickName); + HeroInfoLayer_root.FontLevel.setString("Lv. "+level); + HeroInfoLayer_root.TextDetails.setString(Data.Desc); + + UserData.UpdateTapAttack(); + HeroInfoLayer_root.FontDps.setString("DMG: "+GetShowNumFromArray(UserData.TapAttack)); + + for (var i = 0; i < Data.Skill.length; i++) { + var array_element = Data.Skill[i]; + HeroInfoLayer_root.createUserCell(array_element, Data.SkillUnlock[i], i); + } + }, + createUserCell:function(skillData, unLockLevel, index) { + var custom_item = new ccui.Layout(); + custom_item.setTag(index); + if (unLockLevel >0) + { + var cellBg = new cc.Sprite(res.info_bg_xinxitiao_png); + cellBg.x = cellBg.getContentSize().width * 0.5; + cellBg.y = cellBg.getContentSize().height * 0.5; + + var skillIconBg = new cc.Sprite(res.icon_skill_bg_png); + skillIconBg.x = 60; + skillIconBg.y = 50; + + var skillIcon = new cc.Sprite(skillData.Icon); + skillIcon.x = 60; + skillIcon.y = 50; + + var SkillName = new cc.LabelTTF(skillData.Name, res.TTF_正粗黑, 24); + SkillName.setColor(cc.color.BLACK); + SkillName.setAnchorPoint(0, 0); + SkillName.x = 110; + SkillName.y = 50; + + var SkillDesc = new cc.LabelTTF(skillData.BaseData.Desc, res.TTF_黑体加粗, 24); + SkillDesc.setColor(cc.color.BLACK); + SkillDesc.setAnchorPoint(0, 0); + SkillDesc.x = 110; + SkillDesc.y = 24; + + custom_item.setContentSize(cellBg.getContentSize()); + custom_item.addChild(cellBg); + custom_item.addChild(skillIconBg); + custom_item.addChild(skillIcon); + custom_item.addChild(SkillName); + custom_item.addChild(SkillDesc); + + if (UserData.UserSkillUnLockCount[HeroInfoLayer_root.heroIndex] > index) { + var icon = new cc.Sprite(res.info_icon_kaiqi_png); + icon.x = 500; + icon.y = 50; + custom_item.addChild(icon); + } else { + var skillUnlock = new cc.LabelTTF("需要Lv."+unLockLevel, res.TTF_正粗黑, 24); + skillUnlock.setColor(cc.color.ORANGE); + skillUnlock.setAnchorPoint(0, 0); + skillUnlock.x = 450; + skillUnlock.y = 50; + custom_item.addChild(skillUnlock); + } + + } + HeroInfoLayer_root.ListView_SkillList.insertCustomItem(custom_item, index); + }, + createCell:function(skillData, unLockLevel, index) { + var custom_item = new ccui.Layout(); + custom_item.setTag(index); + if (unLockLevel > 0) + { + var cellBg = new cc.Sprite(res.info_bg_xinxitiao_png); + cellBg.x = cellBg.getContentSize().width * 0.5; + cellBg.y = cellBg.getContentSize().height * 0.5; + + var skillIconBg = new cc.Sprite(res.icon_skill_bg_png); + skillIconBg.x = 60; + skillIconBg.y = 50; + + var skillIcon = new cc.Sprite(skillData.Icon); + skillIcon.x = 60; + skillIcon.y = 50; + + var SkillName = new cc.LabelTTF(skillData.Name, res.TTF_正粗黑, 24); + SkillName.setColor(cc.color.BLACK); + SkillName.setAnchorPoint(0, 0); + SkillName.x = 110; + SkillName.y = 50; + + var SkillDesc = new cc.LabelTTF(skillData.BaseData.Desc, res.TTF_黑体加粗, 24); + SkillDesc.setColor(cc.color.BLACK); + SkillDesc.setAnchorPoint(0, 0); + SkillDesc.x = 110; + SkillDesc.y = 24; + + custom_item.setContentSize(cellBg.getContentSize()); + custom_item.addChild(cellBg); + custom_item.addChild(skillIconBg); + custom_item.addChild(skillIcon); + custom_item.addChild(SkillName); + custom_item.addChild(SkillDesc); + + var HeroLevel = UserData.HeroLevel[index]; + var heroData = HeroData[index]; + + if (UserData.HeroSkillUnLockCount[HeroInfoLayer_root.heroIndex] > index) { + var icon = new cc.Sprite(res.info_icon_kaiqi_png); + icon.x = 500; + icon.y = 50; + custom_item.addChild(icon); + } else { + var skillUnlock = new cc.LabelTTF("需要Lv."+unLockLevel, res.TTF_正粗黑, 24); + skillUnlock.setColor(cc.color.ORANGE); + skillUnlock.setAnchorPoint(0, 0); + skillUnlock.x = 450; + skillUnlock.y = 50; + custom_item.addChild(skillUnlock); + } + + } + HeroInfoLayer_root.ListView_SkillList.insertCustomItem(custom_item, index); + }, + onCloseClick:function(sender,type){ + switch(type){ + case ccui.Widget.TOUCH_ENDED: + MainScene_root.popLayer(); + break; + default: + break; + } + }, +}); diff --git a/pool/shard007/JavaScript/0048045_signup.js b/pool/shard007/JavaScript/0048045_signup.js new file mode 100644 index 0000000000000000000000000000000000000000..ec302ea3820f366fc6f762a4571f870bec5ff6bc --- /dev/null +++ b/pool/shard007/JavaScript/0048045_signup.js @@ -0,0 +1,53 @@ +var bCrypt = require('bcrypt-nodejs'); + +var LocalStrategy = require('passport-local').Strategy; +var User = require('../models/user'); + +module.exports = function(passport) { + + //Define passport signup strategy + passport.use('signup', new LocalStrategy({ + passReqToCallback: true + }, function(req, username, password, done) { + findOrCreateUser = function() { + + User.findOne({ 'username': username }, function(err, user) { + if (err) { + console.log('Error during signup: ' + err); + return done(err); + } + + if (user) { + console.log('User ' + username + ' already exists.'); + return done(null, false); + } + else { + + var newUser = new User(); + + newUser.username = username; + newUser.password = createHash(password); + newUser.email = req.body.email; + + newUser.save(function(err) { + if (err) { + console.log('Could not save user!'); + console.log(err); + return done(err); + } + + console.log("Successfully added new user: " + username); + return done(null, newUser); + }); + } + }); + }; + + console.log("Adding user..."); + process.nextTick(findOrCreateUser); + })); + + var createHash = function(password) { + return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null); + }; +}; diff --git a/pool/shard007/JavaScript/0048047_docs.server.policy.js b/pool/shard007/JavaScript/0048047_docs.server.policy.js new file mode 100644 index 0000000000000000000000000000000000000000..ca93f6d658799d83ebcb626e5a71fe49b1d2950c --- /dev/null +++ b/pool/shard007/JavaScript/0048047_docs.server.policy.js @@ -0,0 +1,72 @@ +'use strict'; + +/** + * Module dependencies. + */ +var acl = require('acl'); + +// Using the memory backend +acl = new acl(new acl.memoryBackend()); + +/** + * Invoke Docs Permissions + */ +exports.invokeRolesPolicies = function() { + acl.allow([{ + roles: ['admin'], + allows: [{ + resources: '/api/docs', + permissions: '*' + }, { + resources: '/api/docs/:docId', + permissions: '*' + }] + }, { + roles: ['user'], + allows: [{ + resources: '/api/docs', + permissions: ['get', 'post','put'] + }, { + resources: '/api/docs/:docId', + permissions: ['get','put'] + }] + }, { + roles: ['guest'], + allows: [{ + resources: '/api/docs', + permissions: ['get','put'] + }, { + resources: '/api/docs/:docId', + permissions: ['get','put'] + }] + }]); +}; + +/** + * Check If Docs Policy Allows + */ +exports.isAllowed = function(req, res, next) { + var roles = (req.user) ? req.user.roles : ['guest']; + + // If an doc is being processed and the current user created it then allow any manipulation + if (req.doc && req.user && req.doc.user.id === req.user.id) { + return next(); + } + + // Check for user roles + acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function(err, isAllowed) { + if (err) { + // An authorization error occurred. + return res.status(500).send('Unexpected authorization error'); + } else { + if (isAllowed) { + // Access granted! Invoke next middleware + return next(); + } else { + return res.status(403).json({ + message: 'User is not authorized' + }); + } + } + }); +}; diff --git a/pool/shard007/JavaScript/0048048_external-helpers-prod.js b/pool/shard007/JavaScript/0048048_external-helpers-prod.js new file mode 100644 index 0000000000000000000000000000000000000000..6624e463d7892246f0c22f4e29f0187e6de181fb --- /dev/null +++ b/pool/shard007/JavaScript/0048048_external-helpers-prod.js @@ -0,0 +1,54 @@ +export function inherits(subClass, superClass) { + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true, + }, + }); + + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : defaults(subClass, superClass); +} + +export function taggedTemplateLiteralLoose(strings, raw) { + strings.raw = raw; + return strings; +} + +function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} + +export function createClass(Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; +} + +export function defaults(obj, defaults) { + var keys = Object.getOwnPropertyNames(defaults); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = Object.getOwnPropertyDescriptor(defaults, key); + if (value && value.configurable && obj[key] === undefined) { + Object.defineProperty(obj, key, value); + } + } + return obj; +} + +export const possibleConstructorReturn = function(self, call) { + return call && (typeof call === 'object' || typeof call === 'function') ? call : self; +}; + +export const slice = Array.prototype.slice; diff --git a/pool/shard007/JavaScript/0048049_dumpdb.js b/pool/shard007/JavaScript/0048049_dumpdb.js new file mode 100644 index 0000000000000000000000000000000000000000..a686702c103b6c9a5e8326a96661e7c77413282d --- /dev/null +++ b/pool/shard007/JavaScript/0048049_dumpdb.js @@ -0,0 +1,30 @@ +var model=require("./db"); +var protocolInfo=require("./protocolDeclare"); +var db=model.db; +var cl=model.cList; + +function gen(callback) { + var result={}; + var finished=0; + for (var i=0;i { + + debug(`getToken() > ${tokenURL}`); + + superagent + .get(tokenURL) + .query({ + grant_type: 'client_credentials', + client_id: clientID, + client_secret: clientSecret + }) + .type('application/json') + .end(function (err, _res) { + if (err) { + debug('getToken() Error'); + debug(err); + } + + debug(`getToken() AccessToken > ${_res.body.access_token}`); + req.auth = _res.body; + next(); + }); +}; + +export default { + getToken +}; diff --git a/pool/shard007/JavaScript/0048051_oojs-ui-mediawiki.js b/pool/shard007/JavaScript/0048051_oojs-ui-mediawiki.js new file mode 100644 index 0000000000000000000000000000000000000000..4c6c77cd920b7e3413676b429ec5f1a1cb05466c --- /dev/null +++ b/pool/shard007/JavaScript/0048051_oojs-ui-mediawiki.js @@ -0,0 +1,69 @@ +/*! + * OOjs UI v0.12.10 + * https://www.mediawiki.org/wiki/OOjs_UI + * + * Copyright 2011–2015 OOjs UI Team and other contributors. + * Released under the MIT license + * http://oojs.mit-license.org + * + * Date: 2015-09-29T21:20:38Z + */ +/** + * @class + * @extends OO.ui.Theme + * + * @constructor + */ +OO.ui.MediaWikiTheme = function OoUiMediaWikiTheme() { + // Parent constructor + OO.ui.MediaWikiTheme.parent.call( this ); +}; + +/* Setup */ + +OO.inheritClass( OO.ui.MediaWikiTheme, OO.ui.Theme ); + +/* Methods */ + +/** + * @inheritdoc + */ +OO.ui.MediaWikiTheme.prototype.getElementClasses = function ( element ) { + // Parent method + var variant, + variants = { + warning: false, + invert: false, + progressive: false, + constructive: false, + destructive: false + }, + // Parent method + classes = OO.ui.MediaWikiTheme.parent.prototype.getElementClasses.call( this, element ), + isFramed; + + if ( element.supports( [ 'hasFlag' ] ) ) { + isFramed = element.supports( [ 'isFramed' ] ) && element.isFramed(); + if ( + ( isFramed && ( element.isDisabled() || element.hasFlag( 'primary' ) ) ) || + ( !isFramed && element.hasFlag( 'primary' ) ) + ) { + variants.invert = true; + } else { + variants.progressive = element.hasFlag( 'progressive' ); + variants.constructive = element.hasFlag( 'constructive' ); + variants.destructive = element.hasFlag( 'destructive' ); + variants.warning = element.hasFlag( 'warning' ); + } + } + + for ( variant in variants ) { + classes[ variants[ variant ] ? 'on' : 'off' ].push( 'oo-ui-image-' + variant ); + } + + return classes; +}; + +/* Instantiation */ + +OO.ui.theme = new OO.ui.MediaWikiTheme(); diff --git a/pool/shard007/JavaScript/0048052_menu.js b/pool/shard007/JavaScript/0048052_menu.js new file mode 100644 index 0000000000000000000000000000000000000000..6c9ac985be87c381944e9735eda8e44df0c5a757 --- /dev/null +++ b/pool/shard007/JavaScript/0048052_menu.js @@ -0,0 +1,63 @@ +// $Id: menu.js,v 1.4 2009/11/06 03:17:59 webchick Exp $ + +(function ($) { + +Drupal.behaviors.menuFieldsetSummaries = { + attach: function (context) { + $('fieldset.menu-link-form', context).setSummary(function (context) { + if ($('#edit-menu-enabled', context).attr('checked')) { + return Drupal.checkPlain($('#edit-menu-link-title', context).val()); + } + else { + return Drupal.t('Not in menu'); + } + }); + } +}; + +/** + * Automatically fill in a menu link title, if possible. + */ +Drupal.behaviors.menuLinkAutomaticTitle = { + attach: function (context) { + // Try to find menu settings widget elements as well as a 'title' field in + // the form, but play nicely with user permissions and form alterations. + var $checkbox = $('fieldset.menu-link-form #edit-menu-enabled', context); + var $link_title = $('#menu-wrapper #edit-menu-link-title', context); + var $title = $('#menu-wrapper', context).closest('form').find('#title-wrapper input.form-text'); + // Bail out if we do not have all required fields. + if (!($checkbox.length && $link_title.length && $title.length)) { + return; + } + // If there is a link title already, mark it as overridden. The user expects + // that toggling the checkbox twice will take over the node's title. + if ($checkbox.attr('checked') && $link_title.val().length) { + $link_title.data('menuLinkAutomaticTitleOveridden', true); + } + // Whenever the value is changed manually, disable this behavior. + $link_title.keyup(function () { + $link_title.data('menuLinkAutomaticTitleOveridden', true); + }); + // Global trigger on checkbox (do not fill-in a value when disabled). + $checkbox.change(function () { + if ($checkbox.attr('checked')) { + if (!$link_title.data('menuLinkAutomaticTitleOveridden')) { + $link_title.val($title.val()); + } + } + else { + $link_title.val(''); + $link_title.removeData('menuLinkAutomaticTitleOveridden'); + } + $checkbox.closest('fieldset.vertical-tabs-pane').trigger('summaryUpdated'); + }); + // Take over any title change. + $title.keyup(function () { + if (!$link_title.data('menuLinkAutomaticTitleOveridden') && $checkbox.attr('checked')) { + $link_title.val($title.val()); + } + }); + } +}; + +})(jQuery); diff --git a/pool/shard007/JavaScript/0048055_ota.js b/pool/shard007/JavaScript/0048055_ota.js new file mode 100644 index 0000000000000000000000000000000000000000..25e0a8aa966ec027dc29fd916acd255770b8ce05 --- /dev/null +++ b/pool/shard007/JavaScript/0048055_ota.js @@ -0,0 +1,45 @@ +module.exports = ota; + +var fhc = require("../../fhc"); +var fhreq = require("../../utils/request"); + +ota.desc = "Build OTA version of an app"; +ota.usage = "\nfhc ota app= destination= version= config= keypass= certpass=" + + "\nwhere is one of: android, iphone, ipad, blackberry, windowsphone7" + + "\nwhere is specific to the destination" + + "\nwhere is always distribution or release for OTA" + + "\n'keypass' and 'certpass' only needed for 'release' builds"; + +var build = require('./build.js'); +var request = require('request').defaults({'proxy': fhc.config.get("proxy")}); + +// main ota entry point +function ota (argv, cb) { + var args = argv._; + try{ + build(argv, function(err, res){ + if (err){ + return cb(err); + } + if (res && res.length && res[0] && res[0].length && res[0][0].action){ // the response is strangely nested arrays - + var url = res[0][0].action.url; + url = url.replace(/\/[a-zA-Z]+~.+~/g,'/'); // Strip the platform~osVersion~versionNum string + url = url.replace('.zip','.plist'); // Make the zip a plist instead! + url = "http://ota.feedhenry.com/ota/ios.html?url=" + url; // Now, throw the plist over to the ota server + + var shortenerRequestBody = { + "longUrl": url + }; + + request({uri: 'https://www.googleapis.com/urlshortener/v1/url', method: 'POST', json: shortenerRequestBody}, function (err, response, body) { + var shortUrl = body.id.replace("\\",""); + ota.message = 'OTA URL: ' + url + '\nShort URL: ' + shortUrl; + cb(undefined, {ota_url: url, short_url: shortUrl}); + }); + + } + }); + }catch (x) { + return cb("Error processing args: " + x + "\nUsage: " + ota.usage); + } +} diff --git a/pool/shard007/JavaScript/0048056_PathTest.js b/pool/shard007/JavaScript/0048056_PathTest.js new file mode 100644 index 0000000000000000000000000000000000000000..91793d0e9c615233e5f42b9efb680c80437a8709 --- /dev/null +++ b/pool/shard007/JavaScript/0048056_PathTest.js @@ -0,0 +1,68 @@ +define([ "../../main/javascript/Private", "../../main/javascript/Path" ], function(Private, Path) { + var properties = new Private(PathTest); + + function PathTest() { + properties.setPrivate(this, {}); + } + PathTest.isTestCase = true; + + PathTest.prototype.setup = function PathTest$setup() { + var x = properties.getPrivate(this); + }; + + PathTest.prototype.testToString = function PathTest$testToString() { + path = Path.normalize("$.store.book[*].author"); + path = Path.normalize("$..author"); + path = Path.normalize("$.store.*"); + path = Path.normalize("$.store..price"); + path = Path.normalize("$..book[2]"); + path = Path.normalize("$..book[(@.length-1)]"); + path = Path.normalize("$..book[-1:]"); + path = Path.normalize("$..book[0,1]"); + path = Path.normalize("$..book[:2]"); + path = Path.normalize("$..book[?(@.isbn)]"); + path = Path.normalize("$..book[?(@.price<10)]"); + path = Path.normalize("$..*"); + path = Path.normalize("#/store/book/author"); + path = Path.normalize("#//author"); + path = Path.normalize("#/store/*"); + path = Path.normalize("#/store//price"); + path = Path.normalize("#//book[3]"); + path = Path.normalize("#//book[last()]"); + path = Path.normalize("#//book[position()<3]"); + path = Path.normalize("#//book[isbn]"); + path = Path.normalize("#//book[price<10]"); + path = Path.normalize("#//*"); + + }; + + PathTest.prototype.testNormalize = function PathTest$testNormalize() { + + }; + + PathTest.prototype.testJoin = function PathTest$testJoin() { + + }; + + PathTest.prototype.testResolve = function PathTest$testResolve() { + + }; + + PathTest.prototype.testRelative = function PathTest$testRelative() { + + }; + + PathTest.prototype.testDirname = function PathTest$testDirname() { + + }; + + PathTest.prototype.testBasename = function PathTest$testBasename() { + + }; + + PathTest.prototype.testExtname = function PathTest$testExtname() { + + }; + + return PathTest; +}); diff --git a/pool/shard007/JavaScript/0048060_store.js b/pool/shard007/JavaScript/0048060_store.js new file mode 100644 index 0000000000000000000000000000000000000000..dfdebb1b9592aa0419b0f2f4be81e39377760d09 --- /dev/null +++ b/pool/shard007/JavaScript/0048060_store.js @@ -0,0 +1,107 @@ +import { observable, extendObservable } from 'mobx'; +import { getSessions, getProposals, getTeam, getProposal, getMe, getMessages, addMessage, removeMessage } from './data-service'; +import uniqBy from 'lodash/uniqBy'; +import flatMap from 'lodash/flatMap'; +import { isServer } from './utils'; + +const store = observable({ + speakers: [], + sessions: [], + proposals: [], + team: [], + messages: [], + showTeamMember: null, + onTeamMemberClick: id => { + store.showTeamMember = store.showTeamMember === id ? null : id; + }, + selectedDate: 0, + setSelectedDate: i => store.selectedDate = i, + isSmallScreen: window.innerWidth < 576, + user: { isFetching: true }, + onLogout: () => store.user = { authenticated: false }, + getProposal: (id) => getProposal(id).then(proposal => { + console.log("!!!", proposal ? proposal.id : '@@@'); + store.sessions = store.sessions.concat(processSession(proposal)); + }), + isUploadingPhoto: false, + onUploadingPhoto: () => { + store.isUploadingPhoto = true; + }, + onPhotoUploaded: (url) => { + store.isUploadingPhoto = false; + console.log("user", store.user); + store.user = { ...store.user, picture: url }; + const speaker = store.speakers.find(x => x.id === store.user.id); + if (speaker) speaker.picutre = url; + }, + onAddMessage: (text) => { + addMessage(text).then(msg => store.messages.push(msg)); + }, + onRemoveMessage: (id) => { + const index = store.messages.findIndex(x => x._id === id); + removeMessage(id).then(() => store.messages.splice(index, 1)); + } +}); + +const processSession = session => ({ + ...session, + speaker_ids: session.speaker_ids.map(speaker => ({ + ...speaker, + picture: speaker.picture.replace("/dtltonc5g/image/upload/", "/dtltonc5g/image/upload/w_300/"), + get href() { + return isServer ? `${speaker._id}.html` : speaker._id; + } + })), + get href() { + return isServer ? `${session.id}.html` : session.id; + } +}); + +const filterSessions = sessionIds => sessionIds.map(p => store.sessions.find(session => session._id === p)).filter(x => !!x); + +export async function initStore(initialState) { + if (initialState) { + extendObservable(store, initialState); + return; + } + + store.team = await getTeam(); + + const sessions = await getSessions(); + const processedSessions = sessions.map(processSession); + store.sessions = processedSessions; + + const proposals = await getProposals(); + store.proposals = proposals.map(processSession); + + store.speakers = uniqBy(flatMap(processedSessions, session => session.speaker_ids), x => x._id) + .map(speaker => ({ + ...speaker, + sessions: filterSessions(speaker.proposals), + get href() { + return isServer ? `${speaker._id}.html` : speaker._id; + } + })) + .sort((a, b) => { + if (a.name === "Sheizaf Rafaeli") return -1; + if (b.name === "Sheizaf Rafaeli") return 1; + if (a.name === "Randy Shoup") return -1; + if (b.name === "Randy Shoup") return 1; + return a.name.toLowerCase().localeCompare(b.name.toLowerCase()) + }); + + const user = await getMe(); + if (user.proposals) { + user.sessions = filterSessions(user.proposals); + } + store.user = user; + + store.messages = await getMessages(); +} + +export default store; + +if (!isServer) { + initStore(window.__INITIAL_STATE__); + window.__store = store; +} \ No newline at end of file diff --git a/pool/shard007/JavaScript/0048061_presentation.js b/pool/shard007/JavaScript/0048061_presentation.js new file mode 100644 index 0000000000000000000000000000000000000000..89b34049d45bcbd9e03bb513f785dc6a500d68e3 --- /dev/null +++ b/pool/shard007/JavaScript/0048061_presentation.js @@ -0,0 +1,89 @@ +import * as fs from 'fs'; + +//Presentation object +export var presentation = { + type:'md|json', + path:null, + file:null, + slides:null +}; + +//Validate folder and open it +export function open (path) { + //Validate if selected folder contains all required elements for a frontal slide folder + /* + We accept: + xyz.md + xyz.json + folder/xyz.md + folder/xyz.json + we do not accept: + folder/package.json + */ + + //Test if path is a folder + var extension; + if(fs.lstatSync(path).isDirectory()){ + //Loop through the folder + var presentation_file = null; + fs.readdirSync(path).forEach(function(file){ + //Ignore sub-folders + if(!fs.lstatSync(path+'/'+file).isDirectory()){ + //Ignore package and readme files (npm/git support) + if((file.toLowerCase() !== 'package.json')&&(file.toLowerCase() !== 'readme.md')){ + extension = file.substring(file.lastIndexOf(".")+1).toLowerCase(); + if((extension === 'md')||(extension === 'json')){ + presentation_file = file; + } + } + } + }); + + if(presentation_file !== null){ + path = path+'/'+presentation_file; + }else{ + global.error("No presentation file found in: ",path); + } + + } + + if(fs.existsSync(path)&&(!fs.lstatSync(path).isDirectory())){ + + presentation.type = path.substring(path.lastIndexOf(".")+1).toLowerCase(); + presentation.file = path.substring(path.lastIndexOf('/')+1); + presentation.path = path.substring(0, (path.length-presentation.file.length)); + var presentation_data = fs.readFileSync(path); + + if(presentation.type === 'md'){ + presentation.slides = parser.md(presentation_data); + + }else if(presentation.type === 'json'){ + presentation.slides = parser.json(presentation_data); + + }else{ + global.error("Unsupported file type: ",path); + } + } + + console.log(presentation); + + //Set current slideshow path to this path + //Switch to presentation mode if not already in presentation mode +}; + +//The note window is only required in presentation mode, so either manage it in presentation module or create a seperate note module +//Note Window +/*var noteWindow = null; + +if (externalDisplay) { + noteWindow = new BrowserWindow({ + x: externalDisplay.bounds.x + 50, + y: externalDisplay.bounds.y + 50, + width: 200, + height: 200, + title: 'Frontal:Notes' + }); + + noteWindow.loadUrl('file://' + __dirname + '/views/layouts/notes.html'); + } +*/ \ No newline at end of file diff --git a/pool/shard007/JavaScript/0048064_notification.server.controller.js b/pool/shard007/JavaScript/0048064_notification.server.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..d60a63019095dc4559f1023e9b85987e6b2c0fe3 --- /dev/null +++ b/pool/shard007/JavaScript/0048064_notification.server.controller.js @@ -0,0 +1,113 @@ +'use strict'; + +/** + * Module dependencies. + */ +var mongoose = require('mongoose'), + errorHandler = require('./errors.server.controller'), + User = mongoose.model('User'), + Project = mongoose.model('Project'), + async = require('async'), + config = require('../../config/config'), + nodemailer = require('nodemailer'), + _ = require('lodash'); + +exports.sendInvites = function(req, res, next) { + Project.findOne({_id: req.body.projectId}, function(err, project) { + if (err) { + return res.status(400).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + var userName; + + var funcDone = function(user, done) { + res.render('templates/invite-email', { + name: user.displayName, + //name: 'No_Name', + appName: config.app.title, + projectName: project.name, + url: 'http://' + req.headers.host + '/#!/projects/' + project._id + '/edit' + }, function(err, emailHTML) { + done(err, emailHTML, user); + }); + }; + + var funcEmail = function(emailHTML, user, done) { + var smtpTransport = nodemailer.createTransport(config.mailer.options); + var mailOptions = { + to: user.email, + from: config.mailer.from, + subject: 'Estimation Invite', + html: emailHTML + }; + smtpTransport.sendMail(mailOptions, function(err) { + if (!err) { + console.log('No Error.'); + } + + done(err, user); + }); + }; + + var funcError = function(err) { + if (err) { + return next(err); + } + }; + + var funcPromise = function(err, user) { + if (!err) { + async.waterfall([ + async.apply(funcDone,user), + // If valid email, send reset email using service + funcEmail + ],funcError ); + } + }; + + for (var i = project.users.length - 1; i >= 0; i--) { + userName = project.users[i]; + + User.findOne({username: userName}, funcPromise); + } + } + }); +}; +exports.sendReport = function(string, project, res) { + var owner = project.owner; + User.findOne({username : owner}, function(err, user) { + if (!err) { + async.waterfall([ + function(done) { + res.render('templates/report-email', { + name: user.displayName, + appName: config.app.title, + projectName: project.name, + report: string + }, function(err, emailHTML) { + done(err, emailHTML, user); + }); + }, + function(emailHTML, user, done) { + var smtpTransport = nodemailer.createTransport(config.mailer.options); + var mailOptions = { + to: user.email, + from: config.mailer.from, + subject: 'Estimation report for ' + project.name, + html: emailHTML + }; + smtpTransport.sendMail(mailOptions, function(err) { + if (!err) { + console.log('No error'); + } + done(err); + }); + } + ], function(err) { + if (err) return err; + }); + } + }); +}; + diff --git a/pool/shard007/JavaScript/0048069_index.js b/pool/shard007/JavaScript/0048069_index.js new file mode 100644 index 0000000000000000000000000000000000000000..2f2087f9c78041a87d972cb3434eae3f399a0268 --- /dev/null +++ b/pool/shard007/JavaScript/0048069_index.js @@ -0,0 +1,20 @@ +class AsyncPlugin { + constructor(akyuu) { + this.akyuu = akyuu; + this.position = akyuu.PLUGIN_POS.BEFORE_CONTROLLER; + } + + plug(callback) { + const self = this; + setTimeout(function() { + self.akyuu.get("/async_plugin", function(req, resp) { + resp.succ("success-load-sync-plugin"); + }); + callback(); + }, 500); + } +} + +exports.create = function(akyuu, options) { + return new AsyncPlugin(akyuu, options); +}; diff --git a/pool/shard007/JavaScript/0048070_push.js b/pool/shard007/JavaScript/0048070_push.js new file mode 100644 index 0000000000000000000000000000000000000000..9d899813a88322e6662a10251aa87c8764b6b335 --- /dev/null +++ b/pool/shard007/JavaScript/0048070_push.js @@ -0,0 +1,44 @@ +import $ from 'jquery'; +import dialog from '../../../node_modules/phraseanet-common/src/components/dialog'; +import pushRecordWindow from './recordPush/index'; + +const pushRecord = (services, datas) => { + const {configService, localeService, appEvents} = services; + const url = configService.get('baseUrl'); + + + const openModal = (datas) => { + + let $dialog = dialog.create(services, { + size: 'Full', + title: localeService.t('push') + }); + + $dialog.getDomElement().closest('.ui-dialog').addClass('push_dialog_container'); + + $.post(`${url}prod/push/sendform/`, datas, function (data) { + $dialog.setContent(data); + _onDialogReady(); + return; + }); + + return true; + }; + + const _onDialogReady = () => { + pushRecordWindow(services).initialize({ + feedback: { + containerId: '#PushBox', + context: 'Push' + }, + listManager: { + containerId: '#ListManager' + } + }); + }; + + + return {openModal}; +}; + +export default pushRecord; diff --git a/pool/shard007/JavaScript/0048071_app.js b/pool/shard007/JavaScript/0048071_app.js new file mode 100644 index 0000000000000000000000000000000000000000..61f698d6e27035e2e01a6498ec26948d7061d48c --- /dev/null +++ b/pool/shard007/JavaScript/0048071_app.js @@ -0,0 +1,96 @@ +/** + * Created by hochelm on 15.8.2014. + */ +(function (global) { + 'use strict'; + + var demoApp = angular.module('demoApp', ['ngMaterial']); + + demoApp + .controller('DemoController', DemoController) + .controller('TabDemo3Controller', TabDemo3Controller) + .controller('CheckboxController', CheckboxController) + .controller('RadioController', RadioController) + .controller('BtnController', BtnController) + ; + + function DemoController() { + + } + + function BtnController() { + var ctrl = this, + disabled = false; + + + ctrl.toggleDisabled = function () { + disabled = !disabled; + }; + ctrl.isDisabled = function () { + return disabled; + }; + + ctrl.sayHi = function (event) { + console.log('Hi from %o', event); + } + } + + + function TabDemo3Controller() { + var ctrl = this; + var tabs = [ + {title: 'Polymer', active: true, disabled: false, content: "Polymer practices are great!"}, + {title: 'Material', active: false, disabled: true, content: "Material Design practices are better!"}, + {title: 'Angular', active: false, disabled: true, content: "AngularJS practices are the best!"}, + {title: 'NodeJS', active: false, disabled: false, content: "NodeJS practices are amazing!"} + ]; + + ctrl.activeIndex = 1; + ctrl.tabs = [].concat(tabs); + } + + + function CheckboxController() { + var ctrl = this, + disabled = false; + + ctrl.data = {}; + ctrl.data.cb1 = true; + ctrl.data.cb2 = false; + + + ctrl.toggleDisabled = function () { + disabled = !disabled; + }; + ctrl.isDisabled = function () { + return disabled; + }; + } + + function RadioController() { + var ctrl = this; + + ctrl.data = { + group2: '6', + group1: '2' + }; + + ctrl.radioData = [ + {label: 'Label 4', value: '4'}, + {label: 'Label 5', value: '5'}, + {label: 'Label 6', value: '6'} + ]; + + ctrl.addItem = function () { + var r = Math.ceil(Math.random() * 1000); + ctrl.radioData.push({label: 'Label ' + r, value: r}); + }; + + ctrl.removeItem = function () { + ctrl.radioData.pop(); + }; + } + + +})(this); + diff --git a/pool/shard007/JavaScript/0048072_crests.js b/pool/shard007/JavaScript/0048072_crests.js new file mode 100644 index 0000000000000000000000000000000000000000..ccd0a2b9418fa1c04fb59693dd75124724979846 --- /dev/null +++ b/pool/shard007/JavaScript/0048072_crests.js @@ -0,0 +1,46 @@ +import { mapGetters, mapActions } from 'vuex'; +import parameterize from '../lib/parameterize'; + +export default { + computed: { + ...mapGetters([ + 'crests', + 'crest', + 'crestCount', + ]), + }, + + methods: { + ...mapActions([ + 'setSkillCrest', + 'removeSkillCrest', + ]), + + setCrest(index) { + if (index === -1) { + this.removeSkillCrest(this.active); + } else { + this.setSkillCrest({ skillId: this.active, index }); + } + }, + + crestDescription(index) { + const messages = this.messages; + const crests = this.crests; + const crest = crests[this.active][index]; + + return parameterize(messages[crest.description], crest.params, messages); + }, + + isCrested(crestIndex) { + const crests = this.build.crests; + const active = this.active; + + if (arguments.length) { + return crests[active] === crestIndex; + } + + return crests[active] === 0 || crests[active] > 0; + }, + }, +}; diff --git a/pool/shard007/JavaScript/0048074_Weixin.js b/pool/shard007/JavaScript/0048074_Weixin.js new file mode 100644 index 0000000000000000000000000000000000000000..369bb51fad840e4dffa967afdbcdad063151d214 --- /dev/null +++ b/pool/shard007/JavaScript/0048074_Weixin.js @@ -0,0 +1,148 @@ +/** + * Created with IntelliJ IDEA. + * Author: 禹 + * Date: 13-9-7 + * Time: 下午3:07 + * File: + * Description: + */ + +var crypto = require("crypto"); +var xml = require("node-xml") + +// var https = require('https'); + +Winxin = {}; + +Winxin.global = {}; +Winxin.global.accessToken = { + token: null, + time: new Date() +} + +// setInterval(function(){ +// https.get("https://api.weixin.qq.com/cgi-bin/tok5en?grant_type=client_credential&appid=" + Weixin.config.APPID + "&secret=" + Weixin.config.APPSECRET + "", function(res) { +// res.setEncoding('utf8'); +// res.on('data', function(chunk) { +// console.log('BODY: ' + chunk); +// }); +// }); +// }, 7000 * 1000); + +Winxin.config = function(conf) { + // body... + this.config = conf; +} + + +Winxin.MessageHandlers = function(stream) { + + this.outStream = stream; + + this.msgHandlers = { + "text": [], + "image": [], + "location": [], + "link": [], + "event": [], + "voice": [] + }; + +} + +Winxin.MessageHandlers.prototype = { + addHandler: function(type, handler) { + if (typeof(handler) == "object") { + this.msgHandlers[type].push(function(msg) { + return handler.handle(msg); + }); + } + if (typeof(handler) == "function") { + this.msgHandlers[type].push(handler); + } + }, + + handle: function(msg) { + if (typeof(msg) == "string") { + msg = this.getMsgFromXml(msg); + } + + var type = msg.type; + + try { + var handlers = this.msgHandlers[type]; + if (handlers) { + for (var i = 0; i < handlers.length; i++) { + var h = handlers[i]; + var r = h(msg); + if (r.handled) { + this.outStream.write(this.getMsgFromXml(r.msg)); + } + } + } + } catch (e) { + return false; + } + return false; + }, + + getMsgFromXml: function(xml) { + var msg = {}; + // msg + return msg; + }, + getXmlFromMsg: function(msg) { + var o2x = require('object-to-xml'); + return o2x(msg) + } + +} + +Winxin.Utities = { + getTimeTicks: function(dt) { + return dt.getTime(); + }, + getTime: function(ticks) { + return new Date(ticks); + }, + log: function() { + + }, + getAccessToken: function(appid, appsecret) { + var http = require("http"); + + }, + addMenuFromFile: function(accessToken, path) { + + }, + addMenu: function(accessToken, menu) { + + }, + getMenu: function(accessToken) { + + }, + deleteMenu: function(accessToken) { + + }, + isLegel: function(signature, timestamp, nonce, token) { + var array = new Array(); + array[0] = timestamp; + array[1] = nonce; + array[2] = token; + array.sort(); + var hasher = crypto.createHash("sha1"); + var msg = array[0] + array[1] + array[2]; + hasher.update(msg); + var msg = hasher.digest('hex'); + if (msg == signature) { + return true; + } else { + return false; + } + } + + +}; + + +exports.Weixin = Winxin; \ No newline at end of file diff --git a/pool/shard007/JavaScript/0048075_todolist.js b/pool/shard007/JavaScript/0048075_todolist.js new file mode 100644 index 0000000000000000000000000000000000000000..064e93483b9c0c44ef9cf74b7fec7b0e318f3d54 --- /dev/null +++ b/pool/shard007/JavaScript/0048075_todolist.js @@ -0,0 +1,103 @@ +const axios = require('axios'); +const initialState = []; +const RECEIVE_TODO = 'RECEIVE_TODO'; +const ADD_TODO = 'ADD_TODO'; +const TOGGLE_TODO = 'TOGGLE_TODO'; +const DEL_TODO = 'DEL_TODO'; +const URL = 'https://anna-todolist-api.herokuapp.com/'; + +export function receiveTodoList (data) { + return { + type: RECEIVE_TODO, + data: data + }; +} + +export function getTodoList() { + return function(dispatch) { + return axios.get(`${URL}todo`) + .then(res => { + dispatch(receiveTodoList(res.data)); + }); + } +} + +export function receiveAddTodoList (payload) { + return { + type: ADD_TODO, + payload: payload + }; +} + +export function addTodoList (value) { + return function(dispatch) { + return axios({ + method: 'post', + url: `${URL}todo`, + headers: { + 'Content-Type': 'application/json' + }, + data: { + isComplete: false, + desc: value + } + }) + .then(res => { + dispatch(receiveAddTodoList(res.data)); + }) + .catch(error => { console.log(error) }) + } +} + +// { id: 1, name: 'anna', isComplete: true } +export function toggleTodoList (payload) { + return function(dispatch) { + return axios({ + method: 'put', + url: `${URL}todo`, + headers: { + 'Content-Type': 'application/json' + }, + data: payload + }) + .then(res => { + dispatch({type: TOGGLE_TODO, payload: payload}); + }) + } +} + +export function delTodoList (id) { + return function(dispatch) { + return axios({ + method: 'delete', + url: `${URL}todo/${id}`, + headers: { + 'Content-Type': 'application/json' + } + }) + .then(res => { + dispatch({type: DEL_TODO, id: id}); + }) + } +} + +export default function todolist (state = initialState, action) { + switch (action.type) { + case RECEIVE_TODO: + return action.data; + case ADD_TODO: + state.push(action.payload); + return [...state]; + case TOGGLE_TODO: + state.forEach((item, index) => { + if (item.id === action.payload.id) { + state[index] = action.payload; + } + }) + return [...state]; + case DEL_TODO: + return state.filter(item => item.id !== action.id) + default: + return state; + } +} diff --git a/pool/shard007/JavaScript/0048076_PeopleController.js b/pool/shard007/JavaScript/0048076_PeopleController.js new file mode 100644 index 0000000000000000000000000000000000000000..4d781f1d9dfc25b5f0c1bf81cc39fef502425246 --- /dev/null +++ b/pool/shard007/JavaScript/0048076_PeopleController.js @@ -0,0 +1,53 @@ +angular.module('ceaseless.controllers') + + .controller('PeopleCtrl', function($scope, background, $stateParams, $ionicPlatform, $cordovaContacts, PeopleService) { + $scope.userMsg = 'waiting for platform readiness'; + $scope.contacts = []; + $scope.backgroundStyles = background.styles; + $scope.active = true; + $scope.shouldShowDelete = false; + $scope.listCanSwipe = true; + + $ionicPlatform.ready(function() { + $scope.userMsg = 'platform ready'; + if (!navigator.contacts) { + console.log('Cordova contacts not available.') + } else { + + $scope.getContactList = function() { + $scope.userMsg = 'fetching'; + var fields = ['displayName', 'name', 'photos']; + $cordovaContacts.find({filter: '', fields: fields}).then(function(result) { + $scope.userMsg = 'in process'; + var contacts = _.sortBy(_.filter(result, function (c) { + return c.name.formatted !== '' && !_.startsWith(c.name.formatted, '#'); + }), 'displayName'); + + for(var i in contacts) { + var c = contacts[i]; + if(c.photos) { + c.profilePicture = c.photos[0].value; + } else { + c.initials = PeopleService.getInitialsForContact(c); + } + } + + $scope.userMsg = ''; + $scope.contacts = contacts; + }, function(error) { + console.log('ERROR', error); + $scope.userMsg = error; + }); + }; + $scope.initContacts = function () { + PeopleService.init(); + }; + $scope.getContactsFromDB = function () { + PeopleService.list().then(function (contacts) { + $scope.contacts = contacts; + }); + } + } + }); + + }); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0048078_index.js b/pool/shard007/JavaScript/0048078_index.js new file mode 100644 index 0000000000000000000000000000000000000000..577ce2138610f3859efd5edd0888c14ab58357f1 --- /dev/null +++ b/pool/shard007/JavaScript/0048078_index.js @@ -0,0 +1,122 @@ +/* global PlasticalSettings, PlasticalData, PlasticalMenu, jQuery */ +// Load in the babel (es6) polyfill, and fetch polyfill +import 'babel-polyfill'; + +const isEdge = /Edge\//.test(navigator.userAgent); +if (isEdge) window.fetch = undefined; // ensure the polyfill runs +require('isomorphic-fetch'); // exports to global if necessary + +// React +import React from 'react'; +import { render } from 'react-dom'; +import { Provider } from 'react-redux'; +import { bindActionCreators } from 'redux'; + +// Load the CSS +require('../less/base.less'); +require('../less/style.less'); + +// Internal dependecies +import Structure from './structure'; +import store from './store'; +import { IntlReduxProvider, selectedLocale } from './i18n'; +import { setMenu } from 'wordpress-query-menu/lib/state'; + +// Accessibility +import { skipLink } from 'utils/a11y'; + +function renderApp() { + render( + + + + + , + document.getElementById('root') + ); +} + +// Set up link capture on all links in the app context. +function handleURLs() { + if (/files/.test(location.href) || (/\.(xml)$/i).test(location.href)) { + return; + } + + if (location.pathname.substr(-1) !== '/') { + window.h.push(`${location.pathname}/`); + } + + jQuery('#slider, #container').on('click', 'a[rel!=external][target!=_blank]', (e) => { + // Don't capture clicks in post content. + if (jQuery(e.currentTarget).closest('.entry_content').length) { + return; + } + // Don't capture clicks to wp-admin, or the RSS feed + if (/wp-(admin|login)/.test(e.currentTarget.href) || /\/feed\/$/.test(e.currentTarget.href) || /files/.test(e.currentTarget.href) || (/\.(xml)$/i).test(location.href)) { + return; + } + e.preventDefault(); + let url = e.currentTarget.href; + + url = url.replace(PlasticalSettings.URL.base, PlasticalSettings.URL.path); + + // get global history from ./store + window.h.push(url); + }); + + // anchor scroll + jQuery('#slider, #container').on('click', 'a[href^="#"]', (e) => { + skipLink(e.currentTarget); + }); +} + +// If we have pre-loaded data, we know we're viewing the list of posts, events and locale, and should pre-load it. +function renderPreloadData() { + const actions = bindActionCreators({ setMenu, selectedLocale }, store.dispatch); + actions.selectedLocale(PlasticalSettings.lang); + actions.setMenu(`primary-${PlasticalSettings.lang}`, PlasticalMenu.data); +} + +/* eslint no-use-before-define: 1 */ +function detectScroll() { + jQuery(window).scroll(() => { + clearTimeout(scrollTimer); + let moveHeight = 1; + if (jQuery('.home').length > 0 && jQuery('#slider').length > 0) { + moveHeight = (jQuery('#slider').height() - 70); + } + const scrollTimer = setTimeout(() => { + const winPosition = jQuery(window).scrollTop(); + if (winPosition > moveHeight) { + jQuery('#header, #container').addClass('moved'); + } else { + jQuery('#header, #container').removeClass('moved'); + } + }, 100); + }); +} + +/* eslint prefer-arrow-callback: 1 no-unused-expressions: 1 */ +document.addEventListener('DOMContentLoaded', function () { + if (!global.Intl) { + require.ensure(['intl'], require => { + require('intl').default; + renderApp(); + renderPreloadData(); + handleURLs(); + detectScroll(); + }, 'IntlBundle'); + } else { + renderApp(); + renderPreloadData(); + handleURLs(); + detectScroll(); + } +}); + +// Install ServiceWorker and AppCache in the end since +// it's not the most important operation and if main code fails, +// we do not want it installed +if (process.env.NODE_ENV === 'production') { + require('offline-plugin/runtime').install(); // eslint-disable-line global-require +} diff --git a/pool/shard007/JavaScript/0048079_Axis.test.js b/pool/shard007/JavaScript/0048079_Axis.test.js new file mode 100644 index 0000000000000000000000000000000000000000..097f3b8dad87d04a4ec8b8a32a786b10c05319dd --- /dev/null +++ b/pool/shard007/JavaScript/0048079_Axis.test.js @@ -0,0 +1,87 @@ +import React from 'react'; +import { Axis } from '../src'; +import { shallow } from 'enzyme'; +import { scaleLinear } from '../../vx-scale'; + +const fakeScale = scaleLinear({ + rangeRound: [10, 0], + domain: [0, 10], +}); + +describe('', () => { + test('it should be defined', () => { + expect(Axis).toBeDefined(); + }); + + test('it should render with class .vx-axis', () => { + const wrapper = shallow(); + expect(wrapper.prop('className')).toEqual('vx-axis'); + }); + + test('it should pass users class down to element', () => { + const fakeClass = "test-class"; + const wrapper = shallow(); + expect(wrapper.prop('className')).toEqual(`vx-axis ${fakeClass}`); + }); + + test('it should render the 0th element if hideZero is false', () => { + // Note that we're explicitly passing in false so that we're testing + // the rendering, NOT wether or not this is a default value. + const wrapper = shallow(); + expect(wrapper.find('.vx-axis-ticks').at(0).key()).toBe('vx-tick-0-0'); + }); + + test('it should not show 0th tick if hideZero is true', () => { + const wrapper = shallow(); + expect(wrapper.find('.vx-axis-ticks').at(0).key()).toBe('vx-tick-1-1'); + }); + + test('it should SHOW an axis line if hideAxisLine is false', () => { + // Again, we're explicitly passing in false so we're testing + // the rendering, NOT the default value. + const wrapper = shallow(); + expect(wrapper.children().not(".vx-axis-ticks").find("Line").length).toBe(1); + }); + + test('it should HIDE an axis line if hideAxisLine is true', () => { + const wrapper = shallow(); + expect(wrapper.children().not(".vx-axis-ticks").find("Line").length).toBe(0); + }); + + test('it should SHOW ticks if hideTicks is false', () => { + // Again, we're explicitly passing in false so we're testing + // the rendering, NOT the default value. + const wrapper = shallow(); + expect(wrapper.children().find(".vx-axis-ticks").find("Line").length).toBeGreaterThan(0); + }); + + test('it should HIDE ticks if hideTicks is true', () => { + const wrapper = shallow(); + expect(wrapper.children().find(".vx-axis-ticks").find("Line").length).toBe(0); + }); + + test('it should render one tick for each value specified in tickValues', () => { + let wrapper = shallow(); + expect(wrapper.children().find(".vx-axis-ticks").find("Line").length).toBe(0); + + wrapper = shallow(); + expect(wrapper.children().find(".vx-axis-ticks").find("Line").length).toBe(1); + + wrapper = shallow(); + expect(wrapper.children().find(".vx-axis-ticks").find("Line").length).toBe(7); + }); + + test('it should use tickFormat to format ticks if passed', () => { + const wrapper = shallow( + 'test!!!'} /> + ); + expect(wrapper.children().find(".vx-axis-ticks").find("text").text()).toBe('test!!!'); + }); + + test('tickFormat should have access to tick index', () => { + const wrapper = shallow( + i} /> + ); + expect(wrapper.children().find(".vx-axis-ticks").find("text").text()).toBe('0'); + }); +}) diff --git a/pool/shard007/JavaScript/0048088_Order.js b/pool/shard007/JavaScript/0048088_Order.js new file mode 100644 index 0000000000000000000000000000000000000000..ff6c6e78a5a7d57c8591568d3fdc781f986b52de --- /dev/null +++ b/pool/shard007/JavaScript/0048088_Order.js @@ -0,0 +1,235 @@ +import React from 'react'; +import areaData from './areaData'; +import '../../node_modules/whatwg-fetch'; + +let AreaSelector = React.createClass({ +getInitialState: function() { +return { +prov: this.props.options.prov, +city: this.props.options.city, +county: this.props.options.county, + province: '' + +}; +}, +selectProv: function (evt) { + console.log("select prov"); +this.setState({ +prov: evt.target.value, +city: '', +county: '' +}); +}, +selectCity: function(evt){ + console.log("select city"); +this.setState({ +city: evt.target.value, +county: '' +}); +}, +selectCounty: function(evt){ + console.log("select county"); + let province = this.props.data.provinces[this.state.prov].name; + let city = this.props.data.provinces[this.state.prov].citys[this.state.city].name; + let area=this.props.data.provinces[this.state.prov].citys[this.state.city].countys[evt.target.value].name; +this.setState({ + county: evt.target.value +}); + this.props.onProvinceChange(province,city,area); +}, + + +render: function() { +var data = this.props.data, + options = Object.assign({ + defaultName:['provinceId','cityId','countyId'], + defaultText:['请选择','请选择','请选择'] + },this.props.options); +var provs = [], citys = [], countys = []; +for(var i in data.provinces){ + provs.push([i,data.provinces[i].name]); +} +provs = provs.map(function(item){ + return (); +}); + +if(this.state.prov){ +for(var i in data.provinces[this.state.prov].citys){ + citys.push([i,data.provinces[this.state.prov].citys[i].name]); +} +citys = citys.map(function(item){ + return (); +}); +} +if(this.state.prov && this.state.city){ +for(var i in data.provinces[this.state.prov].citys[this.state.city].countys){ + countys.push([i,data.provinces[this.state.prov].citys[this.state.city].countys[i].name]); +} +countys = countys.map(function(item){ + return (); +}); +} + +return (
    + + + +
    ) +; +} +}); + +let data = areaData; +let AreaOptions= { + defaultText:['省份','城市','区县'] +}; + + +class Order extends React.Component { + + constructor(props){ + super(props); + this.state = { + price:'888', + customer:'', + phone:'', + province: '', + address: '', + payment:'货到付款', + notes:'' + }; + } + + + handleCustomer(e){ + this.setState({customer:e.target.value}); + } + + handlePhone(e){ + this.setState({phone:e.target.value}); + } + + handleProvince(province,city,area){ + this.setState({ + province:province, + city:city, + area:area + }); + } + + handleAddress(e){ + this.setState({address:e.target.value}); + } + + handlePayment(e){ + if(e.currentTarget.value=='支付宝'){ + this.setState({ + payment:e.currentTarget.value, + form_status: '_blank' + }); + }else if(e.currentTarget.value == '货到付款'){ + this.setState({ + payment:e.currentTarget.value + }); + } + } + + handleNotes(e){ + this.setState({notes:e.target.value}); + } + + handleSubmit(e){ + e.preventDefault(); + if(this.state.payment=='支付宝'){ + let aplipay_form= document.querySelector(".orderForm"); + aplipay_form.submit(); + }else if(this.state.payment=="货到付款"){ + fetch('/api/orders', { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json' + }, + body: JSON.stringify(this.state) + }).then(function(response){ + return response.json(); + }).then(function(j){ + if(j.error){ + alert(j.message); + }else{ + console.dir(j); + alert("订购成功!"); + } + }); + } + } + + handlePrice(e){ + switch(e.currentTarget.value){ + case '700': + this.setState({price:'888'}); + break; + case '550': + this.setState({price:'688'}); + break; + case '366': + this.setState({price:'458'}); + break; + case '220': + this.setState({price:'288'}); + break; + } + } + + render(){ + return ( +
    +
    + +

    + 支付说明:由于货到付款,顺丰快递要加收5%的服务费用,所以,如果选择货到付款购买我们产品,没有相关优惠。本公司已与支付宝签订战略协议,选择支付宝付款,可享受8折优惠。如需其他支付方式(网银支付/转账汇款/微信支付等)可以我们在线客服,索取转款账号。谢谢! +

    +
    +
    this.handleSubmit(e)} target={this.state.form_status}> +
    + 产品选择 + ¥888 4个疗程8瓶装 支付宝付款:¥700
    + ¥688 3个疗程6瓶装 支付宝付款:¥550
    + ¥458 2个疗程4瓶装 支付宝付款:¥366
    + ¥288 1个疗程2瓶装 支付宝付款:¥220 +
    +
    + 联系方式 +
    +
    +
    + +
    +
    + 付款方式 + 货到付款 + 支付宝付款 +
    +
    + 备注信息 + + + + */ + this.foreignObject_ = Blockly.createSvgElement('foreignObject', + {'x': Blockly.Bubble.BORDER_WIDTH, 'y': Blockly.Bubble.BORDER_WIDTH}, + null); + this.foreignBody_ = document.createElementNS(Blockly.HTML_NS, 'body'); + this.foreignBody_.setAttribute('xmlns', Blockly.HTML_NS); + this.foreignBody_.className = 'blocklyMinimalBody'; + this.textarea_ = document.createElementNS(Blockly.HTML_NS, 'textarea'); + this.textarea_.className = 'blocklyCommentTextarea'; + this.textarea_.setAttribute('dir', Blockly.RTL ? 'RTL' : 'LTR'); + this.foreignBody_.appendChild(this.textarea_); + this.foreignObject_.appendChild(this.foreignBody_); + Blockly.bindEvent_(this.textarea_, 'mouseup', this, this.textareaFocus_); + return this.foreignObject_; +}; + +/** + * Add or remove editability of the comment. + * @override + */ +Blockly.Comment.prototype.updateEditable = function() { + if (this.isVisible()) { + // Toggling visibility will force a rerendering. + this.setVisible(false); + this.setVisible(true); + } + // Allow the icon to update. + Blockly.Icon.prototype.updateEditable.call(this); +}; + +/** + * Callback function triggered when the bubble has resized. + * Resize the text area accordingly. + * @private + */ +Blockly.Comment.prototype.resizeBubble_ = function() { + var size = this.bubble_.getBubbleSize(); + var doubleBorderWidth = 2 * Blockly.Bubble.BORDER_WIDTH; + this.foreignObject_.setAttribute('width', size.width - doubleBorderWidth); + this.foreignObject_.setAttribute('height', size.height - doubleBorderWidth); + this.foreignBody_.style.height = (size.height - doubleBorderWidth) + 'px'; + this.textarea_.style.width = (size.width - doubleBorderWidth) + 'px'; + this.textarea_.style.height = (size.height - doubleBorderWidth) + 'px'; +}; + +/** + * Show or hide the comment bubble. + * @param {boolean} visible True if the bubble should be visible. + */ +Blockly.Comment.prototype.setVisible = function(visible) { + if (visible == this.isVisible()) { + // No change. + return; + } + if ((!this.block_.isEditable() && !this.textarea_) || goog.userAgent.IE) { + // Steal the code from warnings to make an uneditable text bubble. + // MSIE does not support foreignobject; textareas are impossible. + // http://msdn.microsoft.com/en-us/library/hh834675%28v=vs.85%29.aspx + // Always treat comments in IE as uneditable. + Blockly.Warning.prototype.setVisible.call(this, visible); + return; + } + // Save the bubble stats before the visibility switch. + var text = this.getText(); + var size = this.getBubbleSize(); + if (visible) { + // Create the bubble. + this.bubble_ = new Blockly.Bubble( + /** @type {!Blockly.Workspace} */ (this.block_.workspace), + this.createEditor_(), this.block_.svg_.svgPath_, + this.iconX_, this.iconY_, + this.width_, this.height_); + this.bubble_.registerResizeEvent(this, this.resizeBubble_); + this.updateColour(); + this.text_ = null; + } else { + // Dispose of the bubble. + this.bubble_.dispose(); + this.bubble_ = null; + this.textarea_ = null; + this.foreignObject_ = null; + } + // Restore the bubble stats after the visibility switch. + this.setText(text); + this.setBubbleSize(size.width, size.height); +}; + +/** + * Bring the comment to the top of the stack when clicked on. + * @param {!Event} e Mouse up event. + * @private + */ +Blockly.Comment.prototype.textareaFocus_ = function(e) { + // Ideally this would be hooked to the focus event for the comment. + // However doing so in Firefox swallows the cursor for unknown reasons. + // So this is hooked to mouseup instead. No big deal. + this.bubble_.promote_(); + // Since the act of moving this node within the DOM causes a loss of focus, + // we need to reapply the focus. + this.textarea_.focus(); +}; + +/** + * Get the dimensions of this comment's bubble. + * @return {!Object} Object with width and height properties. + */ +Blockly.Comment.prototype.getBubbleSize = function() { + if (this.isVisible()) { + return this.bubble_.getBubbleSize(); + } else { + return {width: this.width_, height: this.height_}; + } +}; + +/** + * Size this comment's bubble. + * @param {number} width Width of the bubble. + * @param {number} height Height of the bubble. + */ +Blockly.Comment.prototype.setBubbleSize = function(width, height) { + if (this.textarea_) { + this.bubble_.setBubbleSize(width, height); + } else { + this.width_ = width; + this.height_ = height; + } +}; + +/** + * Returns this comment's text. + * @return {string} Comment text. + */ +Blockly.Comment.prototype.getText = function() { + return this.textarea_ ? this.textarea_.value : this.text_; +}; + +/** + * Set this comment's text. + * @param {string} text Comment text. + */ +Blockly.Comment.prototype.setText = function(text) { + if (this.textarea_) { + this.textarea_.value = text; + } else { + this.text_ = text; + } +}; + +/** + * Dispose of this comment. + */ +Blockly.Comment.prototype.dispose = function() { + this.block_.comment = null; + Blockly.Icon.prototype.dispose.call(this); +}; diff --git a/pool/shard007/JavaScript/0048391_index.js b/pool/shard007/JavaScript/0048391_index.js new file mode 100644 index 0000000000000000000000000000000000000000..cd4d816bb359bfb95d47d119050b89357edbbf3a --- /dev/null +++ b/pool/shard007/JavaScript/0048391_index.js @@ -0,0 +1,75 @@ +import React from 'react'; +import { + BrowserRouter as Router, + Route, + Link, + Prompt +} from 'react-router-dom'; + +const PreventingTransitionsExample = () => ( + +
    +
      +
    • Form
    • +
    • One
    • +
    • Two
    • +
    + +

    One

    } /> +

    Two

    } /> +
    +
    +); + +class Form extends React.Component { + constructor(props) { + super(props); + this.state = { + isBlocking: false + }; + } + render() { + const { isBlocking } = this.state; + + return ( + { + event.preventDefault(); + event.target.reset(); + this.setState({ + isBlocking: false + }); + }} + > + ( + `Are you sure you want to go to ${location.pathname}` + )} + /> + +

    + Blocking? {isBlocking ? 'Yes, click a link or the back button' : 'Nope'} +

    + +

    + { + this.setState({ + isBlocking: event.target.value.length > 0 + }); + }} + /> +

    + +

    + +

    + + ); + } +} + +export default PreventingTransitionsExample; diff --git a/pool/shard007/JavaScript/0048392_Viewport.Camera.js b/pool/shard007/JavaScript/0048392_Viewport.Camera.js new file mode 100644 index 0000000000000000000000000000000000000000..f7b77663d4c0b6f79bae9cef9b98e5a797dcb334 --- /dev/null +++ b/pool/shard007/JavaScript/0048392_Viewport.Camera.js @@ -0,0 +1,52 @@ +/** + * @author mrdoob / http://mrdoob.com/ + */ + +import { UISelect } from './libs/ui.js'; + +var ViewportCamera = function ( editor ) { + + var signals = editor.signals; + + // + + var cameraSelect = new UISelect(); + cameraSelect.setPosition( 'absolute' ); + cameraSelect.setRight( '10px' ); + cameraSelect.setTop( '10px' ); + cameraSelect.onChange( function () { + + editor.setViewportCamera( this.getValue() ); + + } ); + + signals.cameraAdded.add( update ); + signals.cameraRemoved.add( update ); + + update(); + + // + + function update() { + + var options = {}; + + var cameras = editor.cameras; + + for ( var key in cameras ) { + + var camera = cameras[ key ]; + options[ camera.uuid ] = camera.name; + + } + + cameraSelect.setOptions( options ); + cameraSelect.setValue( editor.viewportCamera.uuid ); + + } + + return cameraSelect; + +}; + +export { ViewportCamera }; diff --git a/pool/shard007/JavaScript/0048395_ledger.js b/pool/shard007/JavaScript/0048395_ledger.js new file mode 100644 index 0000000000000000000000000000000000000000..9a97660c2c45c46447eaf032125b3992587c8102 --- /dev/null +++ b/pool/shard007/JavaScript/0048395_ledger.js @@ -0,0 +1,44 @@ +'use strict' + +const Wantlist = require('../types/wantlist') + +class Ledger { + constructor (peerId) { + this.partner = peerId + this.wantlist = new Wantlist() + + this.exchangeCount = 0 + this.sentToPeer = new Map() + + this.accounting = { + bytesSent: 0, + bytesRecv: 0 + } + } + + sentBytes (n) { + this.exchangeCount++ + this.lastExchange = (new Date()).getTime() + this.accounting.bytesSent += n + } + + receivedBytes (n) { + this.exchangeCount++ + this.lastExchange = (new Date()).getTime() + this.accounting.bytesRecv += n + } + + wants (cid, priority) { + this.wantlist.add(cid, priority) + } + + cancelWant (cid) { + this.wantlist.remove(cid) + } + + wantlistContains (cid) { + return this.wantlist.contains(cid) + } +} + +module.exports = Ledger diff --git a/pool/shard007/JavaScript/0048396_uspt.js b/pool/shard007/JavaScript/0048396_uspt.js new file mode 100644 index 0000000000000000000000000000000000000000..5aa4d75d8d02c7486405be62e8a10a1b332c8445 --- /dev/null +++ b/pool/shard007/JavaScript/0048396_uspt.js @@ -0,0 +1,225 @@ +/* main server of uspt: + * starting the listening server, + * binding socket.io to listen to websocket connections from the single-page client */ + +var express = require('express'); +var crypto = require('crypto'); +var mysql = require('mysql'); +var https = require('https'); +var http = require('http'); +var fs = require('fs'); + +var app = express(); +var server = http.createServer(app); +var io = require('socket.io')(server); + +var db = require('./db/db.js'); +var SurveyData = require('./dataObjects/surveyData'); + +/* configure logging */ +var log4js = require('log4js'); +log4js.configure({ + appenders: [ + { type: 'console' }, + { type: 'file', filename: 'uspt.log'} + ] +}); +var logger = log4js.getLogger(); +db.setLogger(logger); + +/* building db connection */ +//creating connection pool +var pool = mysql.createPool({ + host : 'localhost', + user : 'root', + password : 'root', + database : 'uspt' +}); + +pool.getConnection(function(err, connection){ + //try to establish one connection to see whether db can be reached + if (err){ + logger.error('error connecting to db: ' + err.toString()); + throw err; + } + + logger.info('connected to db'); + connection.release(); +}); + +var port = 80; +if(process.argv.length > 2){ + //assuming that argument on index 2 is a specified port + port = process.argv[2]; +} + +server.listen(port, function(err){ + logger.info('http server listening on port ' + port + '!'); +}); + +//TODO: also support https -> options! +//https.createServer(options, app).listen(443); + +//TODO: handle case where study is cancelled midway by leaving socket (exit window, reload...) +// -> to do so, its probably needed to save undone entries to db (completed 0 --> 1) +// --> or yet better, save to db only after completion? + +//TODO: make data objects, e.g. for user, surveyData etc. +//TODO: split socket code in multiple files, one for each 'channel' +//TODO: after split of code in multiple files, also make http endpoints? +//(to detach from sockets, e.g. when used in plugins or moodle) + +//TODO: validate input - also client side? html/js "validator"? +//TODO: error codes for client + +//TODO: if using auth-tokens for survey start, how to configure auth-tokens? +//maybe through an admin interface? + +//TODO: date for survey data + participation data? might be used to link survey to participant... + +app.get('/', function(req, res){ + logger.info('request served on /'); + fs.createReadStream('uspt.html').pipe(res); +}); + +app.get('/info', function(req, res){ + logger.info('request served on /info'); + res.send('universal students personality testing - research project - aau klagenfurt'); +}); + +io.on('connection', function(socket){ + logger.info('user connected'); + + var user = {}; + + socket.on('auth', function(data){ + //support auth-token to begin survey + logger.info('auth data received: ' + JSON.stringify(data)); + + //TODO: check in db for open surveys / corresponding auth_keys + //TODO: survey_key could be set (queried from db) with auth_key + + if(data.auth_key.length > 0){ + socket.emit('auth-success'); + } else{ + socket.emit('auth-fail'); + } + }); + + socket.on('login', function(data){ + //get login data from json + logger.info('login data received: ' + JSON.stringify(data)); + + user.sex = data.sex; + user.age = data.birthday; + user.institution = data.institution; + user.survey_key = data.survey_key; + user.date = Date.now(); + + var hash = crypto.createHash('sha512'); + hash.update(data.fname + data.lname + data.sex + data.birthday + data.p_info_select + data.p_info); + var hash_hex = hash.digest('hex'); + + user.hash = hash_hex; + logger.info('new user: ' + JSON.stringify(user)); + + //create user in db, if not exists + pool.getConnection(function(err, connection){ + if(err){ + logger.error('error getting connection from pool: ' + err.toString()); + socket.emit('err', {'error' : 403}); + return; + } + + var n_user = {} + n_user.first_name = data.fname; + n_user.last_name = data.lname; + n_user.sex = data.sex; + n_user.birthday = data.birthday; + + db.createUser(connection, n_user, function(err, result){ + if(err){ + //check if err contains known db error code + if(err.error){ + logger.error('error posting to db: ' + JSON.stringify(err)); + socket.emit('err', err); + } else{ + //else send unspecified db error + logger.error('error posting to db: ' + err.toString()); + socket.emit('err', {'error' : 400}); + } + } else{ + user.id = result.student_id; + socket.emit('login-success', {hash: hash_hex}); + } + }); + connection.release(); + }); + }); + + //TODO: make it possible to unlock specific survey keys (-> admin portal?) + //e.g. table open_surveys + socket.on('survey', function(data){ + //get survey data from json + logger.info('survey data received: ' + JSON.stringify(data)); + + user.answer = data.f1 + ',' + data.f2; + logger.info('updated user: ' + JSON.stringify(user)); + + pool.getConnection(function(err, connection){ + if(err){ + logger.error('error getting connection from pool: ' + err.toString()); + socket.emit('err', {'error' : 403}); + return; + } + + var success = false; + var s_user = {}; + s_user.student_id = user.id; + s_user.survey_key = user.survey_key; + //s_user.date = user.date; //TODO: if same date is saved, survey-data could be linked to survey-participant?! + + db.writeSurveyParticipation(connection, s_user, function(err, result){ + if(err){ + //check if err contains known db error code + if(err.error){ + logger.error('error posting to db: ' + JSON.stringify(err)); + socket.emit('err', err); + } else{ + //else send unspecified db error + logger.error('error posting to db: ' + err.toString()); + socket.emit('err', {'error' : 400}); + } + } else{ + //write survey data + + //answer is now csv, to support different test structures + //TODO: change age to birthday? (invariant to time) + var surveyData = new SurveyData(user.hash, user.survey_key, user.answer, user.sex, user.age, user.institution); + logger.info("survey data: " + JSON.stringify(surveyData)); + + db.writeSurvey(connection, surveyData, function(err, result){ + if(err){ + //check if err contains known db error code + if(err.error){ + logger.error('error posting to db: ' + JSON.stringify(err)); + socket.emit('err', err); + } else{ + //else send unspecified db error + logger.error('error posting to db: ' + err.toString()); + socket.emit('err', {'error' : 400}); + } + } else{ + socket.emit('survey-success'); + } + }); + } + }); + connection.release(); + }); + }); + + socket.on('disconnect', function(){ + logger.info('user disconnected'); + }); +}); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0048405_sketch.js b/pool/shard007/JavaScript/0048405_sketch.js new file mode 100644 index 0000000000000000000000000000000000000000..7372f9d26e789ab95fa4d3d0bd8ad4eaad88ade0 --- /dev/null +++ b/pool/shard007/JavaScript/0048405_sketch.js @@ -0,0 +1,77 @@ +// The Nature of Code +// Daniel Shiffman +// http://natureofcode.com + +// Forces (Gravity and Fluid Resistence) with Vectors + +// Demonstration of multiple force acting on bodies (Mover class) +// Bodies experience gravity continuously +// Bodies experience fluid resistance when in "water" + +// Five moving bodies +var movers = []; + +// Liquid +var liquid; + +function setup() { + // Must be before createGraphics + var text = createP("click mouse to reset"); + + createCanvas(640, 360); + reset(); + // Create liquid object + liquid = new Liquid(0, height/2, width, height/2, 0.1); + + // Here we call methods of each element to set the position and id, try changing these values. + text.position(10, 365); + +} + +function draw() { + background(127); + + // Draw water + liquid.display(); + + for (var i = 0; i < movers.length; i++) { + + // Is the Mover in the liquid? + if (liquid.contains(movers[i])) { + // Calculate drag force + var dragForce = liquid.calculateDrag(movers[i]); + // Apply drag force to Mover + movers[i].applyForce(dragForce); + } + + // Gravity is scaled by mass here! + var gravity = createVector(0, 0.1*movers[i].mass); + // Apply gravity + movers[i].applyForce(gravity); + + // Update and display + movers[i].update(); + movers[i].display(); + movers[i].checkEdges(); + } + +} + + +// Not working??? +function mousePressed() { + reset(); +} + +// Restart all the Mover objects randomly +function reset() { + for (var i = 0; i < 9; i++) { + movers[i] = new Mover(random(0.5, 3), 40+i*70, 0); + } +} + + + + + + diff --git a/pool/shard007/JavaScript/0048406_locus.js b/pool/shard007/JavaScript/0048406_locus.js new file mode 100644 index 0000000000000000000000000000000000000000..f0579ab3c4542e1dde44c4920d5118f575d2af5e --- /dev/null +++ b/pool/shard007/JavaScript/0048406_locus.js @@ -0,0 +1,44 @@ +(function() { + var Locus, _base; + + if (global.locus_variables == null) { + global.locus_variables = {}; + } + + if ((_base = global.locus_variables).modules == null) { + _base.modules = {}; + } + + global.locus_variables.modules.sync_prompt = require.resolve('sync-prompt'); + + Locus = (function() { + function Locus() {} + + Locus.listen = function() { + var e, input, prompt, quit, _results; + quit = false; + _results = []; + while (!quit) { + prompt = require(locus_variables.modules.sync_prompt).prompt; + input = prompt('> ').trim(); + try { + if (input === 'quit' || input === 'exit') { + _results.push(quit = true); + } else { + _results.push(console.log(eval(input))); + } + } catch (_error) { + e = _error; + _results.push(console.log(e)); + } + } + return _results; + }; + + return Locus; + + })(); + + global.locus = "(" + (Locus.listen.toString()) + ").call(this)"; + +}).call(this); diff --git a/pool/shard007/JavaScript/0048407_Button.js b/pool/shard007/JavaScript/0048407_Button.js new file mode 100644 index 0000000000000000000000000000000000000000..72cdc1e621b8be23e75cf3c0565da1a8b3396fc5 --- /dev/null +++ b/pool/shard007/JavaScript/0048407_Button.js @@ -0,0 +1,32 @@ +import React from 'react'; + +import style from 'modules/ui/button'; + +class Button extends React.Component { + render() { + let defaultProps = { + }; + let styleTypeProps = { + 'positive': { + className: style.button + " " + style['button--positive'] + }, + 'neutral': { + className: style.button + " " + style['button--neutral'] + }, + 'action': { + className: style.button + " " + style['button--action'] + } + }; + const props = Object.assign({}, defaultProps, styleTypeProps['neutral'], styleTypeProps[this.props.styleType], this.props); + + return ( + + ); + } +} + +export default Button; diff --git a/pool/shard007/JavaScript/0048409_analytics.js b/pool/shard007/JavaScript/0048409_analytics.js new file mode 100644 index 0000000000000000000000000000000000000000..e40a078889c2b691132f50f14c2d8f044bdab6e3 --- /dev/null +++ b/pool/shard007/JavaScript/0048409_analytics.js @@ -0,0 +1,107 @@ +/** + * GA Anomalies Monitor (https://github.com/fraszczakszymon/ga-anomalies-monitor) + * + * Copyright © 2016 Frąszczak Szymon. All rights reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + */ + +/*global module, require*/ +var api = require('api/api'), + analytics = require('googleapis').analytics('v3'), + config, + logger = require('utils/logger'), + q = require('q'); + +function prepareQueryParam(params) { + if (!params) { + return; + } + return params.map(function (param) { + return 'ga:' + param; + }) + .join(','); +} + +function getProfiles() { + var deferred = q.defer(); + api.authenticate() + .then(function (authClient) { + analytics.management.profiles.list({ + 'auth': authClient, + 'accountId': '~all', + 'webPropertyId': '~all' + }, function (err, result) { + if (err) { + logger.error('getProfiles', { + error: err + }); + deferred.reject(err); + } else { + logger.info('getProfiles', { + results: result.items.length + }); + deferred.resolve(result); + } + }); + }); + + return deferred.promise; +} + +function runQuery(viewIds, metrics, dimensions, filters, extra) { + var deferred = q.defer(); + dimensions = dimensions || []; + dimensions = JSON.parse(JSON.stringify(dimensions)); // make a copy + dimensions.push('date'); + dimensions.push('hour'); + extra = extra || {}; + + config = require('../../config/config.json'); + setTimeout(function () { + api.authenticate() + .then(function (authClient) { + var params = { + 'auth': authClient, + 'ids': 'ga:' + viewIds, + 'metrics': prepareQueryParam(metrics), + 'dimensions': prepareQueryParam(dimensions), + 'samplingLevel': 'HIGHER_PRECISION', + 'startIndex': extra.startIndex || 1, + 'max-results': extra.maxResults || 10000, + 'start-date': extra.start || config.settings.timeSpan + 'daysAgo', + 'end-date': extra.end || 'today' + }; + if (filters) { + params.filters = filters; + } + analytics.data.ga.get(params, function (err, result) { + if (err) { + logger.error('runQuery', { + metrics: metrics, + dimensions: dimensions, + filters: filters, + error: err + }); + deferred.reject(err); + } else { + logger.info('runQuery', { + metrics: metrics, + dimensions: dimensions, + filters: filters, + results: result.rows ? result.rows.length : 0 + }); + deferred.resolve(result); + } + }); + }); + }, extra.timeout || 0); + + return deferred.promise; +} + +module.exports = { + getProfiles: getProfiles, + runQuery: runQuery +}; diff --git a/pool/shard007/JavaScript/0048412_ref-collector.js b/pool/shard007/JavaScript/0048412_ref-collector.js new file mode 100644 index 0000000000000000000000000000000000000000..8141dddd9c3be316e4fa05ce454e03fe583e0165 --- /dev/null +++ b/pool/shard007/JavaScript/0048412_ref-collector.js @@ -0,0 +1,38 @@ +'use strict'; +var RSVP = require('rsvp'); + +module.exports = RefCollector; +function RefCollector(excludes) { + if (!(this instanceof RefCollector)) { + return new RefCollector(excludes); + } + + this.excludes = excludes || []; + this.selector = null; + this.refAttr = null; +} + +RefCollector.prototype.exclude = function(ref) { + return this.excludes.some(function(exclude) { + return ref.search(exclude); + }); +}; + +RefCollector.prototype.process = function(ref, refs) { + if (!this.exclude(ref)) { + refs[ref] = true; + } +}; + +RefCollector.prototype.collect = function($) { + var refs = {}; + + return new RSVP.Promise(function(resolve) { + $(this.selector).each(function(index, el) { + var ref = $(el).attr(this.refAttr); + this.process(ref, refs); + }.bind(this)); + + resolve(Object.keys(refs)); + }.bind(this)); +}; diff --git a/pool/shard007/JavaScript/0048413_bulk.js b/pool/shard007/JavaScript/0048413_bulk.js new file mode 100644 index 0000000000000000000000000000000000000000..060fea7f19790b171a9c93157af902d844396a4b --- /dev/null +++ b/pool/shard007/JavaScript/0048413_bulk.js @@ -0,0 +1,131 @@ +var _ = require('lodash'); + +var OperationResult = function () { + this.ok = true; + this.nInserted = 0; + this.nUpdated = 0; + this.nUpserted = 0; + this.nModified = 0; + this.nRemoved = 0; + this._insertedIds = []; + this._upsertedIds = []; +}; + +OperationResult.prototype.getInsertedIds = function () { + return this._insertedIds; +}; + +OperationResult.prototype.getLastOp = function () { + return null; +}; + +OperationResult.prototype.getUpsertedIdAt = function (index) { + return _.get(this._upsertedIds, index); +}; + +OperationResult.prototype.getUpsertedIds = function () { + return this._upsertedIds; +}; + +OperationResult.prototype.getWriteConcernError = function () { + return null; +}; + +OperationResult.prototype.getWriteErrorAt = function () { + return null; +}; + +OperationResult.prototype.getWriteErrorCount = function () { + return 0; +}; + +OperationResult.prototype.getWriteErrors = function () { + return []; +}; + +OperationResult.prototype.hasWriteErrors = function () { + return false; +}; + +var BulkOperation = function (collection) { + this.__collection__ = collection; + this._operations = []; + this._bulkResult = new OperationResult(); +}; + +BulkOperation.prototype.execute = function (callback) { + var self = this; + var promises = []; + var len = this._operations.length; + for (var i = 0; i < len; i++) { + var op = this._operations[i]; + promises.push(this.__collection__[op.method].apply(this.__collection__, op.args)); + } + Promise.all(promises).then(function (results) { + for (var i = 0; i < len; i++) { + var _op = self._operations[i]; + switch (_op.method) { + case 'insert': + self._bulkResult.nInserted += 1; + self._bulkResult._insertedIds.push(results[i]._id); + break; + case 'update': + if (results[i].updatedExisting) { + self._bulkResult.nUpdated += results[i].nUpdated; + } else { + self._bulkResult.nInserted += results[i].nInserted; + self._bulkResult._upsertedIds.push(results[i]._id); + } + break; + case 'remove': + self._bulkResult.nRemoved += results[i].nRemoved; + break; + default: + break; + } + } + callback(null, self._bulkResult); + }).catch(function (err) { + callback(err); + }); + if(typeof callback !== 'function') { + return new Promise(function (resolve,reject) { + callback = function (e, r) { e? reject(e) : resolve(r) }; + }) + } +}; + +BulkOperation.prototype.find = function (query) { + var self = this; + return { + removeOne: function () { + self._operations.push({ method: 'removeOne', args: [query].concat(Array.from(arguments)) }); + }, + remove: function () { + self._operations.push({ method: 'remove', args: [query].concat(Array.from(arguments)) }); + }, + replaceOne: function () { + self._operations.push({ method: 'replaceOne', args: [query].concat(Array.from(arguments)) }); + }, + updateOne: function () { + self._operations.push({ method: 'updateOne', args: [query].concat(Array.from(arguments)) }); + }, + update: function () { + self._operations.push({ method: 'update', args: [query].concat(Array.from(arguments)) }); + }, + }; +}; + +BulkOperation.prototype.insert = function () { + this._operations.push({ method: 'insert', args: Array.from(arguments) }); +}; + +BulkOperation.prototype.update = function () { + this._operations.push({ method: 'update', args: Array.from(arguments) }); +}; + +BulkOperation.prototype.remove = function () { + this._operations.push({ method: 'remove', args: Array.from(arguments) }); +}; + +module.exports = BulkOperation; \ No newline at end of file diff --git a/pool/shard007/JavaScript/0048415_login.js b/pool/shard007/JavaScript/0048415_login.js new file mode 100644 index 0000000000000000000000000000000000000000..bb41621b7a3af5b7e6d73ac007030a3b42c93d0f --- /dev/null +++ b/pool/shard007/JavaScript/0048415_login.js @@ -0,0 +1,111 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +/* + * Copyright (c) 2014, Joyent, Inc. + */ + +var assert = require('assert'); +var sprintf = require('util').format; + +var restify = require('restify'); + + +var util = require('./util'); + + + +// --- Globals + +var BadRequestError = restify.BadRequestError; + +// --- API + +module.exports = { + + getSalt: function getSalt(req, res, next) { + assert.ok(req.ufds); + + var log = req.log; + + log.debug({login: req.params.uuid}, 'GetSalt: entered'); + + assert.ok(req.customer); + + res.send(200, { salt: req.customer._salt }); + + return next(); + }, + + + login: function login(req, res, next) { + assert.ok(req.ufds); + + var log = req.log; + + log.debug({params: req.params}, 'Login: entered'); + + if (!req.params.login) { + return next(new BadRequestError('login is required')); + } + if (!req.params.digest) { + return next(new BadRequestError('digest is required')); + } + + assert.ok(req.customer); + + var result = null; + if (req.customer.userpassword === req.params.digest) { + result = util.translateCustomer(req.customer); + if (req.accepts('application/xml')) { + result = { customer: result }; + } + } + + log.debug({ + login: req.params.login, + result: result || {} + }, 'Login: done'); + + res.send(200, result); + return next(); + + + + }, + + forgotPassword: function forgotPassword(req, res, next) { + assert.ok(req.ufds); + + var log = req.log; + + log.debug({params: req.params}, 'ForgotPassword: entered'); + + if (!req.params.email) { + return next(new BadRequestError('email is required')); + } + + req.ufds.getUserByEmail(req.params.email, function (err, user) { + console.dir(err); + console.dir(user); + if (err) { + return next(err); + } + var customers = [util.translateCustomer(user)]; + if (req.accepts('application/xml')) { + customers = { customers: customers }; + } + + log.debug({ + email: req.params.email, + customers: customers || {} + }, 'ForgotPassword: done'); + res.send(200, customers); + return next(); + }); + } + +}; diff --git a/pool/shard007/JavaScript/0048423_buildModuleUrl.js b/pool/shard007/JavaScript/0048423_buildModuleUrl.js new file mode 100644 index 0000000000000000000000000000000000000000..130e6778a6525a0940bd3e9a14ed14a4267a945c --- /dev/null +++ b/pool/shard007/JavaScript/0048423_buildModuleUrl.js @@ -0,0 +1,103 @@ +/*global define*/ +define([ + '../ThirdParty/Uri', + './defined', + './DeveloperError', + 'require' + ], function( + Uri, + defined, + DeveloperError, + require) { + "use strict"; + /*global CESIUM_BASE_URL*/ + + var cesiumScriptRegex = /((?:.*\/)|^)cesium[\w-]*\.js(?:\W|$)/i; + function getBaseUrlFromCesiumScript() { + var scripts = document.getElementsByTagName('script'); + for ( var i = 0, len = scripts.length; i < len; ++i) { + var src = scripts[i].getAttribute('src'); + var result = cesiumScriptRegex.exec(src); + if (result !== null) { + return result[1]; + } + } + return undefined; + } + + var baseUrl; + function getCesiumBaseUrl() { + if (defined(baseUrl)) { + return baseUrl; + } + + var baseUrlString; + if (typeof CESIUM_BASE_URL !== 'undefined') { + baseUrlString = CESIUM_BASE_URL; + } else { + baseUrlString = getBaseUrlFromCesiumScript(); + } + + if (!defined(baseUrlString)) { + throw new DeveloperError('Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL.'); + } + + baseUrl = new Uri(baseUrlString).resolve(new Uri(document.location.href)); + + return baseUrl; + } + + function buildModuleUrlFromRequireToUrl(moduleID) { + //moduleID will be non-relative, so require it relative to this module, in Core. + return require.toUrl('../' + moduleID); + } + + function buildModuleUrlFromBaseUrl(moduleID) { + return new Uri(moduleID).resolve(getCesiumBaseUrl()).toString(); + } + + var implementation; + var a; + + /** + * Given a non-relative moduleID, returns an absolute URL to the file represented by that module ID, + * using, in order of preference, require.toUrl, the value of a global CESIUM_BASE_URL, or + * the base URL of the Cesium.js script. + * + * @private + */ + var buildModuleUrl = function(moduleID) { + if (!defined(implementation)) { + //select implementation + if (defined(require.toUrl)) { + implementation = buildModuleUrlFromRequireToUrl; + } else { + implementation = buildModuleUrlFromBaseUrl; + } + } + + if (!defined(a)) { + a = document.createElement('a'); + } + + var url = implementation(moduleID); + + a.href = url; + a.href = a.href; // IE only absolutizes href on get, not set + + return a.href; + }; + + // exposed for testing + buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex; + + /** + * Sets the base URL for resolving modules. + * @param {String} value The new base URL. + */ + buildModuleUrl.setBaseUrl = function(value) { + baseUrl = new Uri(value).resolve(new Uri(document.location.href)); + }; + + return buildModuleUrl; +}); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0048425_objectDirCtrl.js b/pool/shard007/JavaScript/0048425_objectDirCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..54b3cb0ed512872e221f20e30db7541ee9611947 --- /dev/null +++ b/pool/shard007/JavaScript/0048425_objectDirCtrl.js @@ -0,0 +1,44 @@ +(function () { + "use strict"; + + // ReSharper disable once UndeclaredGlobalVariableUsing + angular + .module("umbraco") + .controller("ujetObjectDirCtrl", ujetObjectDirCtrl); + + ujetObjectDirCtrl.$inject = ["$scope"]; + + function ujetObjectDirCtrl($scope) { + var vm = { + canSelect: $scope.canSelect, + canEdit: $scope.canEdit, + canDelete: $scope.canDelete, + selectObject: selectObject, + editObject: editObject, + deleteObject: deleteObject + }; + + $scope.vm = vm; + + function selectObject() { + $scope.$emit("selectObject", vm.object); + }; + + function editObject() { + $scope.$emit("editObject", vm.object); + }; + + function deleteObject() { + $scope.$emit("deleteObject", vm.object); + }; + + $scope.$watch("model", function (newValue) { + if (_.isNull(newValue) || + _.isUndefined(newValue)) { + return; + } + + vm.object = newValue; + }); + }; +})(); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0048426_Intro.js b/pool/shard007/JavaScript/0048426_Intro.js new file mode 100644 index 0000000000000000000000000000000000000000..3003e92bd150f296412c550b1c16d830ce777f96 --- /dev/null +++ b/pool/shard007/JavaScript/0048426_Intro.js @@ -0,0 +1,60 @@ +define(function(require, exports, module) { + + var Womb = require( 'app/Womb' ); + + var Ring = require( 'app/scenes/html5_webGL/Ring' ); + var Text = require( 'app/scenes/html5_webGL/Text' ); + var Image = require( 'app/scenes/html5_webGL/Image' ); + var Fan = require( 'app/scenes/html5_webGL/Fan' ); + var Random = require( 'app/scenes/html5_webGL/Random' ); + + function Intro( womb, params ){ + + this.womb = womb; + + this.womb.loader.addToLoadBar(); + + this.scenes = []; + + this.voicePulser = new Ring( womb , { + numOf: 10, + //img: null, + geo: new THREE.CubeGeometry( 450 , 5 , 450 , 10 , 10 , 10 ) + }); + this.voicePulser.scene.rotation.x = Math.PI / 2; + this.voicePulser.scene.position.z = -100; + + this.womb.loader.loadBarAdd(); + + //this.world.update = this.update.bind( this ); + + } + + + Intro.prototype.triggerEvent = function( e ){ + + this.events[e].bind( this )(); + + } + + + Intro.prototype.nextEvent = function(){ + + this.triggerEvent( this.currentEvent ); + this.currentEvent ++; + + } + + + Intro.prototype.enter = function(){ + + + } + + Intro.prototype.exit = function(){ + + } + + module.exports = Intro; + +}); diff --git a/pool/shard007/JavaScript/0048428_server.js b/pool/shard007/JavaScript/0048428_server.js new file mode 100644 index 0000000000000000000000000000000000000000..88c5f71924ef9bca47ad91824690f0c9407ffdc8 --- /dev/null +++ b/pool/shard007/JavaScript/0048428_server.js @@ -0,0 +1,98 @@ +"use strict"; + +const http = require('http'); +const app = require('express')(); +const bodyParser = require('body-parser'); +const util = require('util'); +const NginxController = require('./NginxController'); +const ifconfigSecureListenHosts = require('./ifconfigSecureListenHosts'); + +const CONTROL_PORT = 1081; + +const nginx = new NginxController(__dirname); + +function validateEndpoint(endpoint, res) { + if (!endpoint.match(/[0-9a-z\.\-_]{4,}/)) { + res.status(400).end('endpoint is suspicious: ' + endpoint + "\n"); + return false; + } + return true; +} + +function proxyCreateHandler(endpoint, url, res) { + res.set('Content-type', 'text/plain'); + + if (!validateEndpoint(endpoint, res)) + return; + + nginx.generateProxyConfig(endpoint, url); + nginx.reloadNginx(); + + const msg = util.format('proxy %s -> %s\n', endpoint, url); + res.status(201).end(msg); +} + + +app.use(bodyParser.json()); + + +app.delete('/proxy/:endpoint', (req, res) => { + + const endpoint = req.params.endpoint; + if (!validateEndpoint(endpoint, res)) + return; + + nginx.deleteProxyConfig(endpoint); + nginx.reloadNginx(); + + res.end('delete'); +}); + +app.put('/proxy/:endpoint/to-port/:port', (req, res) => { + const port = Number.parseInt(req.params.port, 10); + + if (!(port > 1 && port < 65535 )) { + res.status(400).end('bad port specified\n'); + return; + } + + const url = 'http://' + (req.ip.indexOf(':') > -1 ? '[' + req.ip + ']' : req.ip) + ':' + port; + + proxyCreateHandler(req.params.endpoint, url, res); + +}); + +app.put('/proxy/:endpoint/to-http-url/:url', (req, res) => { + const rawUrl = req.params.url; + + // 1.1.1.1:1 + + if (!rawUrl.match(/^[\d\.:]{9,}/)) { + res.status(400).end("url should contain numeric ip4 address, possible semicolon (encoded as %3a) and port\n"); + return; + } + + const url = 'http://' + rawUrl; + + proxyCreateHandler(req.params.endpoint, url, res); +}); + + +ifconfigSecureListenHosts((hosts) => { + + hosts.map((host) => { + + http.createServer(app).listen(CONTROL_PORT, host); + console.log("%s: control REST API listening on %s:%d", new Date(), host, CONTROL_PORT); + + }); + + nginx.run(); + +}); + + +process.on('SIGTERM', function () { + nginx.stop(); + process.exit(0); +}); diff --git a/pool/shard007/JavaScript/0048434_syncPaging.spec.js b/pool/shard007/JavaScript/0048434_syncPaging.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..757b241548540b8ff774e32fcaaa7fa6881c43d2 --- /dev/null +++ b/pool/shard007/JavaScript/0048434_syncPaging.spec.js @@ -0,0 +1,53 @@ +const PagedArray= require("../bin/PagedArray"); + +const testArr=[1,2,3]; +const dummyRun =function(data,val){ + return data; +} +var obj; +const dummyPageArray=function(){ + if(!obj) + obj=new PagedArray.default(testArr,{size:2,run:dummyRun}); + return obj; +} + + +describe("paging-create", function () { + it("should create a empty array ready to be loaded", function () { + //var product = calculator.multiply(2, 3); + + var arr=dummyPageArray(); + expect(arr.length).toBe(0); + }); +}); + +describe("paging-load", function () { + it("should show an array of two positions", function () { + //var product = calculator.multiply(2, 3); + + var arr=dummyPageArray(); + arr.load(); + expect(arr.length).toBe(2); + }); +}); + +describe("paging-next", function () { + it("should show an array of one position", function () { + //var product = calculator.multiply(2, 3); + + var arr=dummyPageArray(); + arr.next(); + expect(arr.length).toBe(1); + }); +}); + +describe("paging-previous", function () { + it("should show an array of two positions", function () { + //var product = calculator.multiply(2, 3); + + var arr=dummyPageArray(); + + arr.previous(); + expect(arr.length).toBe(2); + }); +}); diff --git a/pool/shard007/JavaScript/0048439_index.js b/pool/shard007/JavaScript/0048439_index.js new file mode 100644 index 0000000000000000000000000000000000000000..150d7f7ec14ec33fa124837d485cc541a6969276 --- /dev/null +++ b/pool/shard007/JavaScript/0048439_index.js @@ -0,0 +1,79 @@ +import gutil from 'gulp-util'; +import {Plugin} from 'gulp-tools'; +import {PatternStream} from './pattern_stream'; +import File from 'vinyl'; +import path from 'path'; + +class GulpPlugin extends Plugin { + + constructor() { + super('gulp-magic-template'); + this.patterns = null; + } + + configure(options) { + this.options = options ? options : {}; + + // The set of patterns we expect to find + this.option('patterns'); + + // The set of globals we expect to find + this.option('globals', null, (v) => { return true; }); + + // The handler to invoke with the set of loaded pattern files + // The input is { key: token, key: token, ... } + // where token: { path: 'foo/source2.html', value: '...', uid: 'foo/source2', id: 'html' } + this.option('action'); + + // The handler to invoke to generate the output path for complete files + // The input is { key: token, key: token, ... } + // where token: { path: 'foo/source2.html', value: '...', uid: 'foo/source2', id: 'html' } + this.option('path'); + + // This handler is invoked with debug information at the end of the process + // Use this if things seem to be going strange. + this.option('debug', null, (v) => { return true; }); + } + + handle_string(file, value, callback, fstream) { + + /// Create a new pattern config, if none exists + if (this.patterns == null) { + this.patterns = new PatternStream(); + this.patterns.instance(this.options.patterns); + if (this.options.globals) { + this.patterns.global(this.options.globals); + } + } + + // Process a value + var results = this.patterns.handle(file.path, value); + var failed = null; + if (results) { + for (var i = 0; i < results.length; ++i) { + try { + var output = this.options.action(results[i].tokens); + var path = this.options.path(results[i].tokens); + var fp = new File({ path: path, cwd: file.cwd, base: file.base, contents: new Buffer(output) }); + fstream.push(fp); + } + catch(err) { + failed = new gutil.PluginError(this.name, err, {fileName: file.path}); + } + } + } + callback(failed); + } + + /** Emit debug information on close */ + handle_close(fstream, callback) { + if (this.options.debug) { + this.options.debug(this.patterns.debug()); + } + callback(); + } +} + +export default function handler(opts) { + return new GulpPlugin().handler()(opts); +} diff --git a/pool/shard007/JavaScript/0048442_gulpfile.js b/pool/shard007/JavaScript/0048442_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..a85368952ad7a7d4b2a587b3a508c6c7ba0cea95 --- /dev/null +++ b/pool/shard007/JavaScript/0048442_gulpfile.js @@ -0,0 +1,50 @@ +'use strict'; + +var gulp = require('gulp'); +var browserify = require('browserify'); +var source = require('vinyl-source-stream'); +var streamify = require('gulp-streamify'); +var size = require('gulp-size'); +var uglify = require('gulp-uglify'); +var rename = require('gulp-rename'); +var watch = require('gulp-watch'); +var eslint = require('gulp-eslint'); +var del = require('del'); + +var config = { + namespace: 'braintree', + src: { + js: { + all: './src/**/*.js', + main: './index.js', + output: 'card-validator.js', + min: 'card-validator.min.js' + } + }, + dist: 'dist' +}; + +gulp.task('lint', function () { + gulp.src([config.src.js.all]) + .pipe(eslint()) + .pipe(eslint.format()); +}); + +gulp.task('js', ['lint'], function () { + return browserify({standalone: 'cardValidator'}) + .add(config.src.js.main) + .bundle() + .pipe(source(config.src.js.output)) + .pipe(streamify(size())) + .pipe(gulp.dest(config.dist)) + .pipe(streamify(uglify())) + .pipe(streamify(size())) + .pipe(rename(config.src.js.min)) + .pipe(gulp.dest(config.dist)); +}); + +gulp.task('clean', function (done) { + del([ config.dist ], done); +}); + +gulp.task('build', ['clean', 'js']); diff --git a/pool/shard007/JavaScript/0048444_batchconsumerbatchmodifier.js b/pool/shard007/JavaScript/0048444_batchconsumerbatchmodifier.js new file mode 100644 index 0000000000000000000000000000000000000000..a72524cacef18709f41dac77b2b35a696737a292 --- /dev/null +++ b/pool/shard007/JavaScript/0048444_batchconsumerbatchmodifier.js @@ -0,0 +1,93 @@ +/** + * @file batchconsumerbatchmodifier.js + * @brief Batch consumer - batch modifier step + * @author Frédéric SCHERMA (INRA UMR1095) + * @date 2017-12-19 + * @copyright Copyright (c) 2017 INRA/CIRAD + * @license MIT (see LICENSE file) + * @details + */ + +let ActionStepFormat = require('./actionstepformat'); +let Marionette = require('backbone.marionette'); + +let Format = function() { + ActionStepFormat.call(this); + + this.name = "batchconsumer_batchmodifier"; + this.group = "standard"; + this.description = _t("Take a list of batch in input and some descriptors to be defined on those batches, the output list is the list of the batches."); + + this.acceptFormat = ['batch_id']; + this.dataFormat = ['batch_id']; +}; + +_.extend(Format.prototype, ActionStepFormat.prototype, { + defaultFormat: function() { + return {}; + } +}); + + +Format.ActionStepProcessView = ActionStepFormat.ActionStepProcessView.extend({ + className: 'action-step-process', + template: require('../templates/actionstep/process/batchconsumerbatchmodifier.html'), + + initialize: function(options) { + options || (options = {readonly: true}); + + this.listenTo(this.model, 'change', this.render, this); + }, + + onRender: function() { + if (this.getOption('readonly')) { + + } else { + + } + }, + + onBeforeDestroy: function() { + if (!this.getOption('readonly')) { + } + }, + + exportInput: function() { + + }, + + importData: function() { + + }, + + inputsType: function() { + return 'none'; + }, + + inputsData: function() { + return null; + } +}); + +Format.ActionStepReadView = ActionStepFormat.ActionStepReadView.extend({ +}); + +Format.ActionStepFormatDetailsView = ActionStepFormat.ActionStepFormatDetailsView.extend({ + className: 'action-step-format-details', + template: require('../templates/actionstep/type/batchconsumerbatchmodifier.html'), + + initialize: function() { + this.listenTo(this.model, 'change', this.render, this); + }, + + onRender: function() { + let format = this.model.get('format'); + }, + + storeData: function() { + return { + } + } +}); + +module.exports = Format; diff --git a/pool/shard007/JavaScript/0048445_Skills.js b/pool/shard007/JavaScript/0048445_Skills.js new file mode 100644 index 0000000000000000000000000000000000000000..135d42c06367435d096af95d4b9686b77a4067d0 --- /dev/null +++ b/pool/shard007/JavaScript/0048445_Skills.js @@ -0,0 +1,134 @@ +/** + * Skills Controller By Nicholas Dickey, Copyright (c) 2013, Hudson Wilde Labs + */ +Ext.define('QwiketMVC.controller.Skills', { + extend: 'Ext.app.Controller', + stores: ['Skill'], + models: ['Skill'], + views: ['positions.SkillsPanel'], + refs: [{ + ref: 'SkillsPanel', + selector: 'skills' + }, + { + ref:'SkillForm', + selector: '#edit_skill' + } + ], + + init: function() { + //alert(positionid); + //store=this.getSkillStore(); + //store.proxy.extraParams.positionid=positionid; + this.control({ + 'skills button[action=new_skill]': { + click: this.newSkill + }, + 'skills button[action=save_skill]': { + click: this.saveSkill + } + , + 'skills button[action=cancel_skill]': { + click: this.cancelSkill + } + , + 'skills dataview': { + itemdblclick: this.editSkill + }, + 'skills dataview': { + itemclick: this.editSkill + } + }); + }, + newSkill: function(grid, record) { + var panel = Ext.create('QwiketMVC.view.positions.SkillForm').show(); + /* if(record){ + panel.down('form').loadRecord(record); + }*/ + + }, + loadPositionsList: function(){ + + store=this.getPositionStore(); + var status_selector=this.getStatusSelectorCombo().getValue(); + if(status_selector==null) + status_selector=0; + store.proxy.extraParams.status_selector=status_selector; + store.load(); + }, + editPosition: function(grid, record) { + var dom = Ext.query('div#account_summary'); + var div=dom[0]; + div.innerHTML=''; + + var panel=this.getPositionsPanel(); + panel.layout.setActiveItem(1); + var form=this.getPositionForm(); + if(record){ + panel.down('form').loadRecord(record); + var status=record.get('status'); + var position_status=this.getPositionStatus(); + var status_text='Pending'; + if(status==1) + status_text='Active'; + else if (status==2) + status_text='Closed'; + form.setTitle("Edit Position: "+record.get('code')); + position_status.setValue(status_text); + } + }, + newPosition: function(button) { + var dom = Ext.query('div#account_summary'); + var div=dom[0]; + div.innerHTML=''; + + var panel=this.getPositionsPanel(); + panel.layout.setActiveItem(1); + var form=this.getPositionForm(); + form.setTitle("New Position"); + form.getForm().reset(); + var elem=Ext.get("content").el.child("ul") + var v=elem.child("li:last"); + v.update("
  • "); + elem.insertHtml("beforeEnd","
  •  Edit
  • ",false); + }, + cancelPosition: function(button) { + var dom = Ext.query('div#account_summary'); + var div=dom[0]; + div.innerHTML=''; + + var panel=this.getPositionsPanel(); + panel.layout.setActiveItem(0); + var elem=Ext.get("content").el.child("ul") + var v=elem.child("li:last"); + v.update("
  • "); + elem.insertHtml("beforeEnd","
  •  Overview
  • ",false); + }, + savePosition: function(button) { + var dom = Ext.query('div#account_summary'); + var div=dom[0]; + div.innerHTML=''; + + var form = button.up('form'), + record = form.getRecord(), + values = form.getValues(), + store=this.getPositionStore(); + + var novo = false; + if (values.account_id > 0){ + record.set(values); + } else{ + record = Ext.create('QwiketMVC.model.Position'); + record.set(values); + store.add(record); + novo = true; + } + store.sync(); + var panel=this.getPositionsPanel(); + panel.layout.setActiveItem(0); + + if (novo){ + store.load(); + } + } +}); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0048447_remove-ownership-of-blog.js b/pool/shard007/JavaScript/0048447_remove-ownership-of-blog.js new file mode 100644 index 0000000000000000000000000000000000000000..44eb2a720366470246ce194a072f84439dd9ec8c --- /dev/null +++ b/pool/shard007/JavaScript/0048447_remove-ownership-of-blog.js @@ -0,0 +1,31 @@ +var userID = process.argv[2]; +var blogID = process.argv[3]; + +if (!userID) throw new Error("Please pass userID as first argument"); +if (!blogID) throw new Error("Please pass blogID as second argument"); + +var User = require("user"); + +User.getById(userID, function(err, user) { + + if (err || !user) throw err || new Error("No user with userID " + userID); + + if (user.blogs.indexOf(blogID) === -1) + throw new Error("User " + userID + " does not have blog " + blogID); + + var before = user.blogs.slice(); + + user.blogs = user.blogs.filter(function(otherBlogID) { + return otherBlogID !== blogID; + }); + + console.log('BEFORE', before, 'AFTER', user.blogs); + + User.set(userID, { blogs: user.blogs }, function(err) { + if (err) throw err; + + console.log('Warning! This will not affect the user\'s subscription settings to make sure to adjust their bill'); + console.log("Done!"); + process.exit(); + }); +}); diff --git a/pool/shard007/JavaScript/0048448_jquery.flyingobjects.js b/pool/shard007/JavaScript/0048448_jquery.flyingobjects.js new file mode 100644 index 0000000000000000000000000000000000000000..ff0254470f62d069a251794393dcc4aa009db65d --- /dev/null +++ b/pool/shard007/JavaScript/0048448_jquery.flyingobjects.js @@ -0,0 +1,132 @@ +/* flyingObjects jQuery Plugin +written by: Nolan R Campbell +NuvuScripts@gmail.com +http://flyingobjects.nrcstudios.info +http://be.net/nrcstudios +http://codecanyon.net/user/NuvuScripts +*/ + +(function($){ + + //set options prior to each functions + $.fn.flyingobjects = function( options ) { + // defaults + options = $.extend({ + + images: ["",""], //array of images + totalobjects: 30, //total number of images added to the target container + easing: "swing", //image animation easing + speed: 1100, //speed of animation the lower the number the faster the animation + zindex: 2, //set the z-index of the images + addclass: "", //add a class to the images for DOM manipulation or styling + initialize: "mouseover" // trigger to start the animation set to "load" or "mouseover" + + }, options); + + + + + + +// Generate Random Speed +fObjects.prototype.speed = function(evt) { + this.duration = (randomInt(10) + 5) * options.speed; + + return this; +}; + + + + +function randomInt(max) { +// Generate a random integer + return Math.floor(Math.random() * max); +} + + + function fObjects() { + + this.images = options.images; + +// Randomly Pick a fObjects Model + this.image = this.images[randomInt(this.images.length)]; + this.file = this.image; + +// Create a fObjects DOM + this.element = document.createElement('img'); + + this.speed().newPoint().display().newPoint().fly(); +}; + + + return this.each(function() { + + var $this = $(this); + + //extend settings as options + var o = $.metadata ? $.extend({}, options, $this.metadata()) : options; + + + fObjects.prototype.display = function() { + $(this.element) + .addClass(options.addclass) + .attr('src', this.file) + .css('position', 'absolute') + .css('z-index', options.zindex) + .css('top', this.pointY) + .css('left', this.pointX); + $this.append(this.element); + + + return this; +}; + + + + +// Animate fObjects Movements +fObjects.prototype.fly = function() { + var self = this; + $(this.element).animate({ + "top": this.pointY, + "left": this.pointX + },this.duration, options.easing, function(){ + //if options initialize "mouseover" else "load" bind events + if(options.initialize == "mouseover"){$(this).mousemove(function(){ self.speed().newPoint().fly();});}else if(options.initialize == "load"){ + self.speed().newPoint().fly(); + } + + }); +}; +// Generate a Random Position +fObjects.prototype.newPoint = function() { + this.pointX = randomInt($this.width()); + this.pointY = randomInt($this.height()); + + return this; +}; + + + +// Display the fObjects + + //loop total number of objects and create new objects +$(function(){ + var total = o.totalobjects; + var fobjects = []; + + for (var i = 0; i < total; i++){ + fobjects[i] = new fObjects(); + } +}); + + + + + + + }); //end each function + + }; + +})( jQuery ); diff --git a/pool/shard007/JavaScript/0048452_compressor.js b/pool/shard007/JavaScript/0048452_compressor.js new file mode 100644 index 0000000000000000000000000000000000000000..e24764cc4ab88839573a038dc7c683ef7981182c --- /dev/null +++ b/pool/shard007/JavaScript/0048452_compressor.js @@ -0,0 +1,75 @@ +/* +* Compressor for Metro UI CSS +* Require: +* node.js +* node-minify (https://github.com/srod/node-minify) +* */ + +var compressor = require('node-minify'); +var project_root = '/Projects/Metro-UI-CSS/', + module_path = project_root+'docs/js/metro/', + css_path = project_root+'docs/css/', + js_compile_path = project_root+'min/', + css_compile_path = project_root+'min/'; + +var modules = [ + module_path+'metro-core.js', + module_path+'metro-locale.js', + module_path+'metro-touch-handler.js', + module_path+'metro-accordion.js', + module_path+'metro-button-set.js', + module_path+'metro-date-format.js', + module_path+'metro-calendar.js', + module_path+'metro-datepicker.js', + module_path+'metro-carousel.js', + module_path+'metro-countdown.js', + module_path+'metro-dropdown.js', + module_path+'metro-input-control.js', + module_path+'metro-live-tile.js', + module_path+'metro-drag-tile.js', + module_path+'metro-progressbar.js', + module_path+'metro-rating.js', + module_path+'metro-slider.js', + module_path+'metro-tab-control.js', + module_path+'metro-table.js', + module_path+'metro-times.js', + module_path+'metro-dialog.js', + module_path+'metro-notify.js', + module_path+'metro-listview.js', + module_path+'metro-treeview.js', + module_path+'metro-fluentmenu.js', + module_path+'metro-hint.js', + module_path+'metro-streamer.js', + module_path+'metro-scroll.js', + module_path+'metro-stepper.js', + module_path+'metro-initiator.js' + +]; + +new compressor.minify({ + type: 'gcc', + language: 'ECMASCRIPT5', + fileIn: modules, + fileOut: js_compile_path+'metro.min.js', + callback: function(err, min){ + if (err) console.log(err); else console.log("js compiled"); + } +}); + +new compressor.minify({ + type: 'yui-css', + fileIn: css_path+'metro-bootstrap.css', + fileOut: css_compile_path+'metro-bootstrap.min.css', + callback: function(err, min){ + if (err) console.log(err); else console.log("main css compiled"); + } +}); + +new compressor.minify({ + type: 'yui-css', + fileIn: css_path+'metro-bootstrap-responsive.css', + fileOut: css_compile_path+'metro-responsive.min.css', + callback: function(err, min){ + if (err) console.log(err); else console.log("responsive css compiled"); + } +}); diff --git a/pool/shard007/JavaScript/0048454_node_event_emitter_runner.js b/pool/shard007/JavaScript/0048454_node_event_emitter_runner.js new file mode 100644 index 0000000000000000000000000000000000000000..6a81326579f297067389da6aea380668fde01ab9 --- /dev/null +++ b/pool/shard007/JavaScript/0048454_node_event_emitter_runner.js @@ -0,0 +1,30 @@ +// A custom execjs runner that expects the source to return an instance of EventEmitter +// http://nodejs.org/api/events.html#events_class_events_eventemitter +// Works in node only +(function(program, execJS) { execJS(program) })(function(callback) { #{source} +}, function(program) { + var output, print = function(string) { + process.stdout.write('' + string); + }; + var callback = function(result){ + if (typeof result == 'undefined' && result !== null) { + print('["ok"]'); + } else { + try { + print('["ok", ' + JSON.stringify(result) + ']'); + } catch (err) { + print('["err"]'); + } + } + }; + var returnError = function(err) { + print(JSON.stringify(['err', '' + err])); + }; + + // data and end -> success, error -> error + try { + program().on('data', callback).on('end', callback).on('error', returnError); + } catch (err) { + returnError(err); + } +}); diff --git a/pool/shard007/JavaScript/0048456_individual.js b/pool/shard007/JavaScript/0048456_individual.js new file mode 100644 index 0000000000000000000000000000000000000000..616a1bf1375736176efff96e9d5aaa6a2208e651 --- /dev/null +++ b/pool/shard007/JavaScript/0048456_individual.js @@ -0,0 +1,35 @@ +import 'babel/polyfill'; +import Individual from '../../core/individual'; +import { sum } from '../../utils'; + + +export default class MagicSquareIndividual extends Individual { + deconstruct(alleles) { + return alleles.reduce((merged, allele) => merged.concat(allele), []); + } + + reconstruct(alleles) { + var output = []; + for (let i = 0, l = Math.sqrt(alleles.length); i < l; i++) { + output.push(alleles.slice(i * l, i * l + l)); + } + return output; + } + + fitness() { + var sums = [0, 0]; + for (let i = 0, l = this._alleles.length; i < l; i++) { + sums.push(sum(...this._alleles[i])); + sums.push(sum(...this._alleles.map(row => row[i]))); + sums[0] += this._alleles[i][i]; + sums[1] += this._alleles[i][l - i - 1]; + } + var counts = sums.reduce((counts, sum) => { + counts[sum] = counts.hasOwnProperty(sum) ? counts[sum] + 1 : 1; + return counts; + }, {}); + var highest = Object.keys(counts).map(count => counts[count]) + .reduce((highest, count) => count > highest ? count : highest, 0); + return sums.length - highest; + } +} diff --git a/pool/shard007/JavaScript/0048457_base-dse-authenticator.js b/pool/shard007/JavaScript/0048457_base-dse-authenticator.js new file mode 100644 index 0000000000000000000000000000000000000000..bddc6493eb6bdb2d35546aa79933c60841be28b5 --- /dev/null +++ b/pool/shard007/JavaScript/0048457_base-dse-authenticator.js @@ -0,0 +1,76 @@ +/* + * Copyright DataStax, 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. + */ +'use strict'; +const util = require('util'); +const { Authenticator } = require('./provider'); + +const dseAuthenticatorName = 'com.datastax.bdp.cassandra.auth.DseAuthenticator'; + +/** + * Base class for Authenticator implementations that want to make use of + * the authentication scheme negotiation in the DseAuthenticator + * @param {String} authenticatorName + * @extends Authenticator + * @constructor + * @ignore + */ +function BaseDseAuthenticator(authenticatorName) { + this.authenticatorName = authenticatorName; +} + +util.inherits(BaseDseAuthenticator, Authenticator); + +/** + * Return a Buffer containing the required SASL mechanism. + * @abstract + * @returns {Buffer} + */ +BaseDseAuthenticator.prototype.getMechanism = function () { + throw new Error('Not implemented'); +}; + +/** + * Return a byte array containing the expected successful server challenge. + * @abstract + * @returns {Buffer} + */ +BaseDseAuthenticator.prototype.getInitialServerChallenge = function () { + throw new Error('Not implemented'); +}; + +/** + * @param {Function} callback + * @override + */ +BaseDseAuthenticator.prototype.initialResponse = function (callback) { + if (!this._isDseAuthenticator()) { + //fallback + return this.evaluateChallenge(this.getInitialServerChallenge(), callback); + } + //send the mechanism as a first auth message + callback(null, this.getMechanism()); +}; + +/** + * Determines if the name of the authenticator matches DSE 5+ + * @protected + * @ignore + */ +BaseDseAuthenticator.prototype._isDseAuthenticator = function () { + return this.authenticatorName === dseAuthenticatorName; +}; + +module.exports = BaseDseAuthenticator; \ No newline at end of file diff --git a/pool/shard007/JavaScript/0048458_waiters-test.js b/pool/shard007/JavaScript/0048458_waiters-test.js new file mode 100644 index 0000000000000000000000000000000000000000..34fbb0ddceb90c4193c19d6bd26d98bc0e204928 --- /dev/null +++ b/pool/shard007/JavaScript/0048458_waiters-test.js @@ -0,0 +1,145 @@ +import { registerWaiter, unregisterWaiter, checkWaiters } from '../../lib/test/waiters'; +import { moduleFor, AbstractTestCase } from 'internal-test-helpers'; + +class Waiters { + constructor() { + this._waiters = []; + } + + add() { + this._waiters.push([...arguments]); + } + + register() { + this.forEach((...args) => { + registerWaiter(...args); + }); + } + + unregister() { + this.forEach((...args) => { + unregisterWaiter(...args); + }); + } + + forEach(callback) { + for (let i = 0; i < this._waiters.length; i++) { + let args = this._waiters[i]; + + callback(...args); + } + } + + check() { + this.register(); + let result = checkWaiters(); + this.unregister(); + + return result; + } +} + +moduleFor( + 'ember-testing: waiters', + class extends AbstractTestCase { + constructor() { + super(); + this.waiters = new Waiters(); + } + + teardown() { + this.waiters.unregister(); + } + + ['@test registering a waiter'](assert) { + assert.expect(2); + + let obj = { foo: true }; + + this.waiters.add(obj, function () { + assert.ok(this.foo, 'has proper `this` context'); + return true; + }); + + this.waiters.add(function () { + assert.ok(true, 'is called'); + return true; + }); + + this.waiters.check(); + } + + ['@test unregistering a waiter'](assert) { + assert.expect(2); + + let obj = { foo: true }; + + this.waiters.add(obj, function () { + assert.ok(true, 'precond - waiter with context is registered'); + return true; + }); + + this.waiters.add(function () { + assert.ok(true, 'precond - waiter without context is registered'); + return true; + }); + + this.waiters.check(); + this.waiters.unregister(); + + checkWaiters(); + } + + ['@test checkWaiters returns false if all waiters return true'](assert) { + assert.expect(3); + + this.waiters.add(function () { + assert.ok(true, 'precond - waiter is registered'); + + return true; + }); + + this.waiters.add(function () { + assert.ok(true, 'precond - waiter is registered'); + + return true; + }); + + assert.notOk(this.waiters.check(), 'checkWaiters returns true if all waiters return true'); + } + + ['@test checkWaiters returns true if any waiters return false'](assert) { + assert.expect(3); + + this.waiters.add(function () { + assert.ok(true, 'precond - waiter is registered'); + + return true; + }); + + this.waiters.add(function () { + assert.ok(true, 'precond - waiter is registered'); + + return false; + }); + + assert.ok(this.waiters.check(), 'checkWaiters returns false if any waiters return false'); + } + + ['@test checkWaiters short circuits after first falsey waiter'](assert) { + assert.expect(2); + + this.waiters.add(function () { + assert.ok(true, 'precond - waiter is registered'); + + return false; + }); + + this.waiters.add(function () { + assert.notOk(true, 'waiter should not be called'); + }); + + assert.ok(this.waiters.check(), 'checkWaiters returns false if any waiters return false'); + } + } +); diff --git a/pool/shard007/JavaScript/0048461_createBrowserHistory.js b/pool/shard007/JavaScript/0048461_createBrowserHistory.js new file mode 100644 index 0000000000000000000000000000000000000000..2a95e8198b431ea474dd8dde6ad792e38c5cdb60 --- /dev/null +++ b/pool/shard007/JavaScript/0048461_createBrowserHistory.js @@ -0,0 +1,139 @@ +'use strict'; + +exports.__esModule = 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; }; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _invariant = require('invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _Actions = require('./Actions'); + +var _ExecutionEnvironment = require('./ExecutionEnvironment'); + +var _DOMUtils = require('./DOMUtils'); + +var _DOMStateStorage = require('./DOMStateStorage'); + +var _createDOMHistory = require('./createDOMHistory'); + +var _createDOMHistory2 = _interopRequireDefault(_createDOMHistory); + +var _createLocation = require('./createLocation'); + +var _createLocation2 = _interopRequireDefault(_createLocation); + +/** + * Creates and returns a history object that uses HTML5's history API + * (pushState, replaceState, and the popstate event) to manage history. + * This is the recommended method of managing history in browsers because + * it provides the cleanest URLs. + * + * Note: In browsers that do not support the HTML5 history API full + * page reloads will be used to preserve URLs. + */ +function createBrowserHistory(options) { + _invariant2['default'](_ExecutionEnvironment.canUseDOM, 'Browser history needs a DOM'); + + var isSupported = _DOMUtils.supportsHistory(); + + function getCurrentLocation(historyState) { + historyState = historyState || window.history.state || {}; + + var path = _DOMUtils.getWindowPath(); + var _historyState = historyState; + var key = _historyState.key; + + var state = undefined; + if (key) { + state = _DOMStateStorage.readState(key); + } else { + state = null; + key = history.createKey(); + + if (isSupported) window.history.replaceState(_extends({}, historyState, { key: key }), null, path); + } + + return _createLocation2['default'](path, state, undefined, key); + } + + function startPopStateListener(_ref) { + var transitionTo = _ref.transitionTo; + + function popStateListener(event) { + if (event.state === undefined) return; // Ignore extraneous popstate events in WebKit. + + transitionTo(getCurrentLocation(event.state)); + } + + _DOMUtils.addEventListener(window, 'popstate', popStateListener); + + return function () { + _DOMUtils.removeEventListener(window, 'popstate', popStateListener); + }; + } + + function finishTransition(location) { + var basename = location.basename; + var pathname = location.pathname; + var search = location.search; + var state = location.state; + var action = location.action; + var key = location.key; + + if (action === _Actions.POP) return; // Nothing to do. + + _DOMStateStorage.saveState(key, state); + + var path = (basename || '') + pathname + search; + var historyState = { + key: key + }; + + if (action === _Actions.PUSH) { + if (isSupported) { + window.history.pushState(historyState, null, path); + } else { + window.location.href = path; // Use page reload to preserve the URL. + } + } else { + // REPLACE + if (isSupported) { + window.history.replaceState(historyState, null, path); + } else { + window.location.replace(path); // Use page reload to preserve the URL. + } + } + } + + var history = _createDOMHistory2['default'](_extends({}, options, { + getCurrentLocation: getCurrentLocation, + finishTransition: finishTransition, + saveState: _DOMStateStorage.saveState + })); + + var listenerCount = 0, + stopPopStateListener = undefined; + + function listen(listener) { + if (++listenerCount === 1) stopPopStateListener = startPopStateListener(history); + + var unlisten = history.listen(listener); + + return function () { + unlisten(); + + if (--listenerCount === 0) stopPopStateListener(); + }; + } + + return _extends({}, history, { + listen: listen + }); +} + +exports['default'] = createBrowserHistory; +module.exports = exports['default']; \ No newline at end of file diff --git a/pool/shard007/JavaScript/0048463_app.js b/pool/shard007/JavaScript/0048463_app.js new file mode 100644 index 0000000000000000000000000000000000000000..af3872416133131f4484329369f46162317d6ecc --- /dev/null +++ b/pool/shard007/JavaScript/0048463_app.js @@ -0,0 +1,166 @@ +var express = require('express') + , app = express() + , fs = require('fs') + ,http = require('http') + , path = require('path') + , server = require("http").createServer(app) + , io = require('socket.io').listen(server) + , arDrone = require('ar-drone') + , arDroneConstants = require('ar-drone/lib/constants') + ; + +// Fetch configuration +try { + var config = require('./config'); +} catch (err) { + console.log("Missing or corrupted config file. Have a look at config.js.example if you need an example."); + process.exit(-1); +} + + +// Override the drone ip using an environment variable, +// using the same convention as node-ar-drone +var drone_ip = process.env.DEFAULT_DRONE_IP || '192.168.1.1'; + +// Keep track of plugins js and css to load them in the view +var scripts = [] + , styles = [] + ; + +app.configure(function () { + app.set('port', process.env.PORT || 3000); + app.set('views', process.cwd() + '/views'); + app.set('view engine', 'ejs', { pretty: true }); + app.use(express.favicon()); + app.use(express.logger('dev')); + app.use(app.router); + app.use(express.static(path.join(process.cwd(), 'public'))); + app.use("/components", express.static(path.join(process.cwd(), 'bower_components'))); +}); + +app.configure('development', function () { + app.use(express.errorHandler()); + app.locals.pretty = true; +}); + +app.get('/', function (req, res) { + res.render('index', { + title: 'Nodecopter' + ,scripts: scripts + ,styles: styles + ,options: { + keyboard: config.keyboard + } + }); +}); + +function navdata_option_mask(c) { + return 1 << c; +} + +// From the SDK. +var navdata_options = ( + navdata_option_mask(arDroneConstants.options.DEMO) + | navdata_option_mask(arDroneConstants.options.VISION_DETECT) + | navdata_option_mask(arDroneConstants.options.MAGNETO) + | navdata_option_mask(arDroneConstants.options.WIFI) +); + +// Connect and configure the drone +var client = new arDrone.createClient({timeout:4000}); +client.config('general:navdata_demo', 'TRUE'); +client.config('video:video_channel', '0'); +client.config('general:navdata_options', navdata_options); + +// Add a handler on navdata updates +var latestNavData; +client.on('navdata', function (d) { + latestNavData = d; +}); + +// Signal landed and flying events. +client.on('landing', function () { + console.log('LANDING'); + io.sockets.emit('landing'); +}); +client.on('landed', function () { + console.log('LANDED'); + io.sockets.emit('landed'); +}); +client.on('takeoff', function() { + console.log('TAKEOFF'); + io.sockets.emit('takeoff'); +}); +client.on('hovering', function() { + console.log('HOVERING'); + io.sockets.emit('hovering'); +}); +client.on('flying', function() { + console.log('FLYING'); + io.sockets.emit('flying'); +}); + +// Process new websocket connection +io.set('log level', 1); +io.sockets.on('connection', function (socket) { + socket.emit('event', { message: 'Welcome to cockpit :-)' }); +}); + +// Schedule a time to push navdata updates +var pushNavData = function() { + io.sockets.emit('navdata', latestNavData); +}; +var navTimer = setInterval(pushNavData, 100); + +// Prepare dependency map for plugins +var deps = { + server: server + , app: app + , io: io + , client: client + , config: config +}; + + +// Load the plugins +var dir = path.join(process.cwd(), 'plugins'); +function getFilter(ext) { + return function(filename) { + return filename.match(new RegExp('\\.' + ext + '$', 'i')); + }; +} + +config.plugins.forEach(function (plugin) { + console.log("Loading " + plugin + " plugin."); + + // Load the backend code + require(path.join(dir, plugin))(plugin, deps); + + // Add the public assets to a static route + if (fs.existsSync(assets = path.join(dir, plugin, 'public'))) { + app.use("/plugin/" + plugin, express.static(assets)); + } + + // Add the js to the view + if (fs.existsSync(js = path.join(assets, 'js'))) { + fs.readdirSync(js).filter(getFilter('js')).forEach(function(script) { + scripts.push("/plugin/" + plugin + "/js/" + script); + }); + } + + // Add the css to the view + if (fs.existsSync(css = path.join(assets, 'css'))) { + fs.readdirSync(css).filter(getFilter('css')).forEach(function(style) { + styles.push("/plugin/" + plugin + "/css/" + style); + }); + } +}); + +// Start the web server +server.listen(app.get('port'), function() { + console.log('AR. Drone WebFlight is listening on port ' + app.get('port')); +}); + +if (window.location.href.indexOf('localhost') < 0) { + window.location = 'http://localhost:' + app.get('port'); +} diff --git a/pool/shard007/JavaScript/0048465_app.js b/pool/shard007/JavaScript/0048465_app.js new file mode 100644 index 0000000000000000000000000000000000000000..2f62689af484ece05368b6e78faeee9912716163 --- /dev/null +++ b/pool/shard007/JavaScript/0048465_app.js @@ -0,0 +1,36 @@ + +/** + * Module dependencies. + */ + +var express = require('express'); +var routes = require('./routes'); +var user = require('./routes/user'); +var http = require('http'); +var path = require('path'); + +var app = express(); + +// all environments +app.set('port', process.env.PORT || 3000); +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'jade'); +app.use(express.favicon()); +app.use(express.logger('dev')); +app.use(express.json()); +app.use(express.urlencoded()); +app.use(express.methodOverride()); +app.use(app.router); +app.use(express.static(path.join(__dirname, 'public'))); + +// development only +if ('development' == app.get('env')) { + app.use(express.errorHandler()); +} + +app.get('/', routes.index); +app.get('/oauth2callback', routes.oauthcallback); + +http.createServer(app).listen(app.get('port'), function(){ + console.log('Express server listening on port ' + app.get('port')); +}); diff --git a/pool/shard007/JavaScript/0048469_extendDisplayName.js b/pool/shard007/JavaScript/0048469_extendDisplayName.js new file mode 100644 index 0000000000000000000000000000000000000000..bf510443db99e8751b58d2cebb230347ec66541d --- /dev/null +++ b/pool/shard007/JavaScript/0048469_extendDisplayName.js @@ -0,0 +1,22 @@ +import { setDisplayName, getDisplayName, wrapDisplayName } from 'recompose'; + +export default nameOrOptions => (Component) => { + const options = typeof nameOrOptions !== 'object' ? { name: nameOrOptions } : nameOrOptions; + const { name, operation = 'wrap' } = options; + + let newDisplayName; + switch (operation) { + case 'wrap': { + newDisplayName = wrapDisplayName(Component, name); + break; + } + case 'replace': { + newDisplayName = name; + break; + } + default: { + newDisplayName = getDisplayName(Component); + } + } + return setDisplayName(newDisplayName)(Component); +}; diff --git a/pool/shard007/JavaScript/0048470_15.4.4.20-9-c-ii-23.js b/pool/shard007/JavaScript/0048470_15.4.4.20-9-c-ii-23.js new file mode 100644 index 0000000000000000000000000000000000000000..5f670b467e0102c4130667c9be3abf52ed1d6f55 --- /dev/null +++ b/pool/shard007/JavaScript/0048470_15.4.4.20-9-c-ii-23.js @@ -0,0 +1,24 @@ +/// 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.20/15.4.4.20-9-c-ii-23.js + * @description Array.prototype.filter - callbackfn called with correct parameters (this object O is correct) + */ + + +function testcase() { + + var obj = { 0: 11, length: 2 }; + + function callbackfn(val, idx, o) { + return obj === o; + } + + var newArr = Array.prototype.filter.call(obj, callbackfn); + + return newArr.length === 1 && newArr[0] === 11; + } +runTestCase(testcase); diff --git a/pool/shard007/JavaScript/0048472_controller.js b/pool/shard007/JavaScript/0048472_controller.js new file mode 100644 index 0000000000000000000000000000000000000000..27d624af64937d08d24361671f80308e51adde9d --- /dev/null +++ b/pool/shard007/JavaScript/0048472_controller.js @@ -0,0 +1,259 @@ +/** + * Created by Steven on 2/20/2016. + */ +angular.module('TimeCapsule') + .controller('landingController', function ($scope, $location) { + $scope.scrollDown = function () { + $('html, body').animate({ + scrollTop: $("#about").offset().top + }, 1000); + }; + + $scope.launchLogin = function () { + $('#login-modal') + .modal('show').modal('refresh')//re-centers + //.modal('attach events', '#login-modal .remove', 'hide') + .modal({ + closable: false, + onDeny: function () { + return true; + }, + onApprove: function () { + //$scope.loginConfirm; + return true; + } + + }); + $('#login-modal .form .message').hide(); + + $('#login-modal .ui.form') + .form({ + fields: { + email: { + identifier: 'email', + rules: [ + { + type: 'empty', + prompt: 'Please enter your e-mail' + }, + { + type: 'email', + prompt: 'Please enter a valid e-mail' + } + ] + }, + password: { + identifier: 'password', + rules: [ + { + type: 'empty', + prompt: 'Please enter your password' + }, + { + type: 'length[6]', + prompt: 'Your password must be at least 6 characters' + } + ] + } + } + }); + }; + + $scope.loginConfirm = function () { + if (!$('#login-modal .ui.form').form('validate form')) { + $('#login-modal .form .message').show(); + return false; + } + $location.path('/dashboard/'); + //$scope.redirectFunction(); + //$location.redirect('/dashboard/'); + //Redirect + return true; + }; + + + + }) + .controller('loginController', function ($scope, $location) { + $scope.redirectFunction = function () { + if (!$('#login-modal .ui.form').form('validate form')) { + $('#login-modal .form .message').show(); + return false; + } else { + $('#login-modal') + .modal('hide'); + //console.log("I was hit"); + $location.path('/dashboard/'); + return true; + } + } + }) + .controller('dashboardController', function ($scope, $location, CityService) { + $scope.emptyfunc = function () { + }; + $scope.redirectFunction = function (location) { + console.log(location); + $location.url(location + "/Chicago"); + }; + $scope.launchUpload = function(){ + $location.path('/upload'); + }; + + + $scope.launchLogin = function () { + $('#city-modal') + .modal('show').modal('refresh')//re-centers + //.modal('attach events', '#login-modal .remove', 'hide') + .modal({ + closable: false, + onDeny: function () { + return true; + }, + onApprove: function () { + //$scope.loginConfirm; + return true; + } + + }); + $('#city-modal .form .message').hide(); + + $('#city-modal .ui.form') + .form({ + fields: { + magicsuggest: { + identifier: 'input', + rules: [ + { + type: 'empty', + prompt: 'Please select a city' + } + ] + } + } + }); + }; + + $scope.exploreRandom = function(){ + CityService.getCitesWithData(function(data){ + $location.path('/capsule/' + data[(Math.floor((Math.random() * data.length)))]); + }); + }; + + }) + .controller('capsuleController', function ($scope, PhotoService, $routeParams, $location) { + //$scope.cityName = "Chicago"; + //$scope.contact = Contact.get({id: parseInt($routeParams.id, 10)}); + $scope.cityName = $routeParams.location ? $routeParams.location : "Chicago"; + + $scope.cityImages = [{ + "Id": -1, + "Title": "Chicago Auto Show", + "Description": "The Chicago Auto Show is not only the nation's largest car show, it is also the longest running. The first show was held in the Chicago Coliseum in 1901. It received relatively little attention in the local press. Within a few short years, the show grew into a major tourist attraction. These photos are from the 1909 show.", + "Path": "../images/Chicago/12716328_10152896329597465_1232418463979988700_o.jpg", + "Location": "", + "OwnerId": "", + "DateUploaded": "", + "Year": 1909, + "Month": -1 + }]; + + $('.special.cards .image').dimmer({ + on: 'hover' + }); + + $scope.jumpToDash = function(){ + $location.path('/dashboard'); + }; + + PhotoService.queryImagesForCity($scope.cityName, function (data) { + $scope.cityImages = data; + }); + //$scope.masonryStart = function(){ + // console.log("hit mem"); + $scope.$grid = $('.grid').masonry({ + itemSelector: '.grid-item', + percentPosition: true, + //columnWidth: '.grid-sizer' + }); + + }) + .controller('inputController', function ($scope, $location, CityService) { + $scope.array = []; + CityService.getCitesWithData(function (data) { + $scope.array = data; + msInit(); + }); + var msInit = function () { + $scope.mgsug = $('#magicsuggest').magicSuggest({ + data: $scope.array, + maxSelection: 1, + allowFreeEntries: false//disallow free entries + + // + }); + }; + + $scope.travel = function () { + //console.log($scope.mgsug.getValue()); + var location = $scope.mgsug.getValue()[0]; + $('#city-modal') + .modal('hide'); + + //$location.path('/capsule') + $location.url('/capsule/' + location); + };//add string to path var + }) + .controller('imageUploadController', ['$scope', 'Upload', '$timeout','CityService', '$location', function ($scope, Upload, $timeout, CityService, $location) { + $scope.phase={ + upload:true, + crop:false, + submit:false + }; + + $scope.array =[]; + + CityService.getCitesWithData(function (data) { + $scope.array = data; + msInit(); + }); + var msInit = function () { + $scope.mgsug = $('#magicSuggestOpen').magicSuggest({ + data: $scope.array, + maxSelection: 1, + allowFreeEntries: true//allow free entries and new cities + }); + }; + + $scope.imgData = { + title: "", + // City: "", + month:"", + year:"", + description:"", + ownerId:1, + path:" ", + + }; + + $scope.upload = function (dataUrl) { + $scope.imgData.city = $scope.mgsug.getValue()[0]; + $scope.imgData.file = Upload.dataUrltoBlob(dataUrl); + console.log($scope.imgData); + $location.path('/dashboard'); + //Upload.upload({ + // url: '', + // data: $scope.imgData, + //}).then(function (response) { + // $timeout(function () { + // $scope.result = response.data; + // }); + //}, function (response) { + // // if (response.status > 0) $scope.errorMsg = response.status + // // + ': ' + response.data; + // $location.path('/dashboard'); + //}, function (evt) { + // //$scope.progress = parseInt(100.0 * evt.loaded / evt.total); + // $location.path('/dashboard'); + //}); + } + }]); diff --git a/pool/shard007/JavaScript/0048473_phone_part.js b/pool/shard007/JavaScript/0048473_phone_part.js new file mode 100644 index 0000000000000000000000000000000000000000..25570c013ae226f38c1a43d040f2ec801cd655c3 --- /dev/null +++ b/pool/shard007/JavaScript/0048473_phone_part.js @@ -0,0 +1,105 @@ +var Location = "Omsk"; +var Vibe_Hourly = 1; +var Vibe_BT = 1; + +var Location_key = 1; +var Vibe_Hourly_key = 2; +var Vibe_BT_key = 3; + +function HTTPGET(url) { + var req = new XMLHttpRequest(); + req.open("GET", url, false); + req.send(null); + return req.responseText; +} + +function ReadSettings(){ + Location = localStorage.getItem(Location_key); + if (!Location) + Location = "London"; + + Vibe_Hourly = localStorage.getItem(Vibe_Hourly_key); + if (!Vibe_Hourly) + Vibe_Hourly = 1; + + Vibe_BT = localStorage.getItem(Vibe_BT_key); + if (!Vibe_BT) + Vibe_BT = 1; +} + +function GetWeather(){ + var response = HTTPGET("http://api.openweathermap.org/data/2.5/weather?q=" + Location); + var json = JSON.parse(response); + var temperature = (json.main.temp - 273.15) ; + var conditions = json.weather[0].main; + + /*Just adding "+" sign for good temperature*/ + var sign = ""; + if (temperature > 0) + sign = "+"; + + temperature = temperature.toFixed(0); + + /*Sending All data to Pebble*/ + var CurrentWeather = sign + temperature ; + console.log("Weahter updated!" + CurrentWeather); + + var Num_Condition = 0; + + console.log(conditions); + + if (conditions == "Rain") + Num_Condition = 1; + if (conditions == "Snow") + Num_Condition = 2; + if (conditions == "Thunderstorm") + Num_Condition = 3; + if (conditions == "Clear") + Num_Condition = 4; + + Pebble.sendAppMessage( {"WEATHER_TEMPERATURE" : CurrentWeather, "WEATHER_CONDITIONS" : Num_Condition} ); +} + +function SendSettings(){ + Pebble.sendAppMessage({ + 'SETTINGS_HOURLY_VIBE': parseInt(Vibe_Hourly), + 'SETTINGS_BT_VIBE': parseInt(Vibe_BT) + }); +} + +Pebble.addEventListener("showConfiguration", + function(e) { + Pebble.openURL("http://grakovne.org/pebble/vic4884/AppConfig.php?Location=" + Location + "&Hourly_Vibe=" + Vibe_Hourly + "&BT_Vibe=" + Vibe_BT); + } +); + +Pebble.addEventListener("ready", + function(e) { + console.log("Connection established!"); + ReadSettings(); + SendSettings(); + GetWeather(); + } +); + +Pebble.addEventListener("webviewclosed", + function(e) { + var configuration = JSON.parse(decodeURIComponent(e.response)); + + localStorage.setItem(Location_key, configuration.Location); + localStorage.setItem(Vibe_Hourly_key, configuration.Hourly_Vibe); + localStorage.setItem(Vibe_BT_key, configuration.BT_Vibe); + + ReadSettings(); + SendSettings(); + GetWeather(); + + } +); + +Pebble.addEventListener("appmessage", + function(e) { + GetWeather(); + } +); + diff --git a/pool/shard007/JavaScript/0048475_classes-trans.js b/pool/shard007/JavaScript/0048475_classes-trans.js new file mode 100644 index 0000000000000000000000000000000000000000..bf3efe51ae5d4407e9897609afe6c45323c63408 --- /dev/null +++ b/pool/shard007/JavaScript/0048475_classes-trans.js @@ -0,0 +1,72 @@ +'use strict'; + +angular.module('trng.transformers').factory('ClassesTransformer', [ + function() { + function studentDtoToEntity(dto) { + var entity = _.cloneDeep(dto); + + entity.id = dto._id; + entity = _.omit(entity, '_id'); + + entity.user.id = dto.user._id; + entity.user = _.omit(entity.user, '_id'); + + return entity; + } + + function studentEntityToDto(entity) { + var dto = _.cloneDeep(entity); + + dto._id = entity.id; + dto = _.omit(dto, 'id'); + + dto.user._id = entity.user.id; + dto.user = _.omit(dto.user, 'id'); + + return dto; + } + + var service = { + dtoToEntity: function(dto) { + var entity = _.cloneDeep(dto); + + entity.id = dto._id; + entity = _.omit(entity, '_id'); + + entity.students = _.map(dto.students, function(studentDto) { + return studentDtoToEntity(studentDto); + }); + + _.forEach(entity.bpPublishDetailsList, function(publishDetails) { + if (publishDetails.autoStop !== -1) { + publishDetails.autoStop = publishDetails.autoStop; + } + }); + + return entity; + }, + + entityToDto: function(entity) { + var dto = _.cloneDeep(entity); + + dto._id = entity.id; + dto = _.omit(dto, 'id'); + + dto.students = _.map(entity.students, function(studentEntity) { + return studentEntityToDto(studentEntity); + }); + + _.forEach(dto.bpPublishDetailsList, function(publishDetails) { + delete publishDetails.bpName; + if (publishDetails.autoStop !== -1) { + publishDetails.autoStop = publishDetails.autoStop; + } + }); + + return dto; + } + }; + + return service; + } +]); diff --git a/pool/shard007/JavaScript/0048480_editor.js b/pool/shard007/JavaScript/0048480_editor.js new file mode 100644 index 0000000000000000000000000000000000000000..622f2859c1a7e57c538f0447346c2a77d77e1a96 --- /dev/null +++ b/pool/shard007/JavaScript/0048480_editor.js @@ -0,0 +1,27 @@ +var app=angular.module('Ruenoor'); + +function robotControl($scope, $routeParams, Restangular) { + + $scope.aceLoaded = function (_editor) { + $scope.editor = _editor; + _editor.setReadOnly(false); + Restangular.one("program", $routeParams.id).get().then(function (program) { + $scope.program = program; + $scope.editor.getSession().setValue($scope.program.code); + }); + }; + + $scope.aceChanged = function (e) { + // + }; + + $scope.saveFile = function () { + console.log($scope.editor.getSession().getValue()); + $scope.program.code = $scope.editor.getSession().getValue(); + $scope.program.save(); + alert("Program file saved"); + } + +} + +app.controller("RobotControl", ['$scope', '$routeParams', 'Restangular', robotControl]); diff --git a/pool/shard007/JavaScript/0048481_translate.js b/pool/shard007/JavaScript/0048481_translate.js new file mode 100644 index 0000000000000000000000000000000000000000..103e739187f7c017c1f59e77a383cbe73d91b590 --- /dev/null +++ b/pool/shard007/JavaScript/0048481_translate.js @@ -0,0 +1,233 @@ +var at = require('basisjs-tools-ast').css; +var at_js = require('basisjs-tools-ast').js; +var html_at = require('basisjs-tools-ast').html; + +module.exports = function(flow){ + var fconsole = flow.console; + var themeUrlsMap = false; + var customFilenames = true; //flow.options.sameFilenames || (flow.tmpl.hasIsolated && !flow.tmpl.isolationReproducible); + + fconsole.start('Process packages'); + flow.css.packages = flow.css.packages.filter(function(file){ + var outputContent = at.translate(file.ast); + var isEmpty = !outputContent.length; + + if (isEmpty && !file.themeUrlsMap) + { + fconsole.log('[!] ' + file.relOutputFilename + ' is empty - reject'); + + // 'cut' token from html + if (file.htmlNode) + { + file.htmlFile.unlink(file, file.htmlNode); + html_at.removeToken(file.htmlNode, true); + } + } + else + { + fconsole.log('[OK] ' + file.relOutputFilename); + + file.outputContent = outputContent; + + if (!flow.options.singleFile) + { + if (customFilenames) + { + file.htmlRef = file.proposedOutputFilename + '?' + file.digest; + file.outputFilename = file.proposedOutputFilename; + } + else + { + file.htmlRef = flow.outputResourceDir + file.digest + '.css'; + file.outputFilename = file.htmlRef; + } + } + else + { + if (flow.js.rootNSFile.basis) + { + // temp solution + // TODO: make it better + var ast = flow.js.rootNSFile.basis.ast[1][1][1][1][3]; + ast.splice(ast.length - 1, 0, at_js.parse( + 'basis.require("./' + file.jsRef + '").startUse();' + )[1][0]); + } + else + { + flow.exit('Can\'t inject css into result bundle. --single-file w/o basis.js is not supported for now.'); + } + } + + if (file.themeUrlsMap) + { + themeUrlsMap = file.themeUrlsMap; + file.themeUrlsMap[file.themeName] = file.htmlRef || file.outputFilename; + fconsole.log(' [+] add to theme map: ' + file.themeName + ' -> ' + file.themeUrlsMap[file.themeName]); + } + + if (file.htmlNode) + { + if (file.inline && file.htmlId) + { + // replace content for