diff --git a/pool/shard005/JavaScript/0032510_demo-wizard.js b/pool/shard005/JavaScript/0032510_demo-wizard.js new file mode 100644 index 0000000000000000000000000000000000000000..32509b2e37b380be249e5fab506406894f69178c --- /dev/null +++ b/pool/shard005/JavaScript/0032510_demo-wizard.js @@ -0,0 +1,98 @@ +// FORM DEMO - Account Form +// ------------------------------------------------------------------------------------------------ * --> +$(document).ready(function ($) { + + $(function (wizardForm) { + // navbar, numbering, progressbar, submit button well-nice + wizardForm('#demoWizard').bootstrapWizard({ + nextSelector: '.wizard-action .next', + previousSelector: '.wizard-action .previous', + firstSelector: '.wizard-action .first', + lastSelector: '.wizard-action .last', + onTabShow: function (tab, navigation, index) { + + var $total = navigation.find('li').length; + var $current = index + 1; + var $percent = ($current / $total) * 100; + var $wizard = $('#demoWizard'); + + $wizard.find('.bar').css({ + width: $percent + '%' + }); + + $wizard.find('.number-page').text($current + ' of ' + $total); + + // If it's the last tab then hide the last button and show the finish instead + if ($current >= $total) { + $wizard.find('.wizard-action .next').hide(); + $wizard.find('.wizard-action .finish').show(); + $wizard.find('.wizard-action .finish').removeClass('disabled'); + $wizard.find('.wizard-action .print').show(); + $wizard.find('.wizard-action .print').removeClass('disabled'); + $wizard.find('.wizard-action .cancel').show(); + $wizard.find('.wizard-action .cancel').removeClass('disabled'); + } else { + $wizard.find('.wizard-action .next').show(); + $wizard.find('.wizard-action .finish').hide(); + $wizard.find('.wizard-action .print').hide(); + $wizard.find('.wizard-action .cancel').hide(); + } + + } + + }); + wizardForm('#demoWizard .finish').click(function () { + alert('Finished!, Starting over!'); + $('#demoWizard').find("a[href*='tab1e']").trigger('click'); + }); + + wizardForm('#wzNewAddressState').select2(); + }); + + $(function (wizardForm) { + // navbar, numbering, progressbar, submit button well-nice + wizardForm('#demoWizard2').bootstrapWizard({ + nextSelector: '.wizard-action .next', + previousSelector: '.wizard-action .previous', + firstSelector: '.wizard-action .first', + lastSelector: '.wizard-action .last', + onTabShow: function (tab, navigation, index) { + + var $total = navigation.find('li').length; + var $current = index + 1; + var $percent = ($current / $total) * 100; + var $wizard = $('#demoWizard2'); + + $wizard.find('.bar').css({ + width: $percent + '%' + }); + + $wizard.find('.number-page').text($current + ' of ' + $total); + + // If it's the last tab then hide the last button and show the finish instead + if ($current >= $total) { + $wizard.find('.wizard-action .next').hide(); + $wizard.find('.wizard-action .finish').show(); + $wizard.find('.wizard-action .finish').removeClass('disabled'); + $wizard.find('.wizard-action .print').show(); + $wizard.find('.wizard-action .print').removeClass('disabled'); + $wizard.find('.wizard-action .cancel').show(); + $wizard.find('.wizard-action .cancel').removeClass('disabled'); + } else { + $wizard.find('.wizard-action .next').show(); + $wizard.find('.wizard-action .finish').hide(); + $wizard.find('.wizard-action .print').hide(); + $wizard.find('.wizard-action .cancel').hide(); + } + + } + + }); + wizardForm('#demoWizard2 .finish').click(function () { + alert('Finished!, Starting over!'); + $('#demoWizard2').find("a[href*='tab1e']").trigger('click'); + }); + + wizardForm('#wzNewAddressState2').select2(); + }); +}); diff --git a/pool/shard005/JavaScript/0032515_gulpfile.js b/pool/shard005/JavaScript/0032515_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..649dd1039711447f8df72c4b4bcf610d53104531 --- /dev/null +++ b/pool/shard005/JavaScript/0032515_gulpfile.js @@ -0,0 +1,119 @@ +/* + gulpfile.js + =========== + Rather than manage one giant configuration file responsible + for creating multiple tasks, each task has been broken out into + its own file in gulp/tasks. Any file in that folder gets automatically + required by the loop in ./gulp/index.js (required below). + + To add a new task, simply add a new task file to gulp/tasks. +*/ +// require('./gulp'); + + +var path = require('path'); +var gulp = require('gulp'); +var gutil = require('gulp-util'); +var express = require('express'); +var clean = require('gulp-clean'); +var tiny_lr = require('tiny-lr'); +var webpack = require("webpack"); +var webpackConfig = require("./webpack.config.js"); +var WebpackDevServer = require("webpack-dev-server"); + +// == COMPASS TASK ============= +require('./gulp/tasks/compass'); + +// == COPY TASK ============= +require('./gulp/tasks/copy'); + +// == IMAGES TASK ============= +require('./gulp/tasks/images'); + +// == BUILD TASK ============= +require('./gulp/tasks/build'); + +// == DEFAULT TASK ============= +require('./gulp/tasks/default'); + +gulp.task('clean', function() { + return gulp.src('build', { + read: false + }).pipe(clean()); +}); + +gulp.task('webpack', function(callback) { + execWebpack(webpackConfig); + return callback(); +}); + +gulp.task("dev", ['build'], function(callback) { + gulp.watch(['./src/**/*'], function(evt) { + gutil.log("Files changed, re-building.."); + return gulp.run('build'); + }); + + // modify some webpack config options + var myConfig = Object.create(webpackConfig); + myConfig.devtool = "sourcemap"; + myConfig.debug = true; + + myConfig = webpackConfig; + + // Start a webpack-dev-server + new WebpackDevServer(webpack(myConfig), { + publicPath: "/" + myConfig.output.publicPath, + stats: { + colors: true + } + }) + .listen(4000, "localhost", function(err) { + if(err) throw new gutil.PluginError("webpack-dev-server", err); + gutil.log("[webpack-dev-server]", "http://localhost:4000/webpack-dev-server/index.html"); + }); +}); + +// gulp.task('dev', ['build'], function() { +// var servers; +// servers = createServers(4000, 35729); +// gulp.watch(['./src/**/*'], function(evt) { +// return gulp.run('build'); +// }); +// return gulp.watch(['./build/**/*'], function(evt) { +// gutil.log(gutil.colors.cyan(evt.path), 'changed'); +// return servers.lr.changed({ +// body: { +// files: [evt.path] +// } +// }); +// }); +// }); + +// var createServers = function(port, lrport) { +// var app, lr; +// lr = tiny_lr(); +// lr.listen(lrport, function() { +// return gutil.log("LiveReload listening on", lrport); +// }); +// app = express(); +// app.use(express["static"](path.resolve("./build"))); +// app.listen(port, function() { +// return gutil.log("HTTP server listening on", port); +// }); +// return { +// lr: lr, +// app: app +// }; +// }; + +var execWebpack = function(config) { + return webpack(config, function(err, stats) { + if (err) { + throw new gutil.PluginError("execWebpack", err); + } + return gutil.log("[execWebpack]", stats.toString({ + colors: true + })); + }); +}; + diff --git a/pool/shard005/JavaScript/0032517_catalogActions.js b/pool/shard005/JavaScript/0032517_catalogActions.js new file mode 100644 index 0000000000000000000000000000000000000000..bbcd3b42b21e4760ece33471e5bd5a5800953090 --- /dev/null +++ b/pool/shard005/JavaScript/0032517_catalogActions.js @@ -0,0 +1,28 @@ + +import {collection, element} from './actions'; +import {createAction} from 'redux-actions'; +import {request} from '../services'; + +export const getCategories = createAction( + 'GET_CATEGORIES', + (...args) => request('GET', 'categories', null, collection(...args))); + +export const getCategory = createAction( + 'GET_CATEGORY', + (id, ...args) => request('GET', 'categories', id, element(...args))); + +export const getProducts = createAction( + 'GET_PRODUCTS', + (...args) => request('GET', 'products', null, collection(...args))); + +export const getProduct = createAction( + 'GET_PRODUCT', + (id, ...args) => request('GET', 'products', id, element(...args))); + +export const getOrders = createAction( + 'GET_ORDERS', + (...args) => request('GET', 'orders', null, collection(...args))); + +export const getOrder = createAction( + 'GET_ORDER', + (id, ...args) => request('GET', 'orders', id, element(...args))); diff --git a/pool/shard005/JavaScript/0032519_index.js b/pool/shard005/JavaScript/0032519_index.js new file mode 100644 index 0000000000000000000000000000000000000000..9ead8294cecd20ea55a1f866c0f09b71abbfafef --- /dev/null +++ b/pool/shard005/JavaScript/0032519_index.js @@ -0,0 +1,39 @@ +$.index.open(); + +$.index.addEventListener('focus', function(e){ + library.fetch(); +}); + +$.add.addEventListener('click', function(e){ + var newUser = Alloy.createModel('user', { + name: $.userName.value, + age: $.userAge.value, + email: $.userEmail.value, + }); + + /* validate */ + if(newUser.isValid()){ + newUser.save(); + alert('success'); + $.userName.setValue(''); + $.userAge.setValue(''); + $.userEmail.setValue(''); + } else{ + alert(newUser.errorMsg.join("\n")); + } +}); + +/* これ重要 */ +function transFormFunction(model){ + var transform = model.toJSON(); + return transform; +} + +function doClick(e){ + Ti.API.debug(e); + alert('name: ' + e.row.title); +} + +/* これ重要 */ +var library = Alloy.Collections.user; +library.fetch(); diff --git a/pool/shard005/JavaScript/0032528_rq-angular-napp-menu.js b/pool/shard005/JavaScript/0032528_rq-angular-napp-menu.js new file mode 100644 index 0000000000000000000000000000000000000000..75270fcab0f028b5c5c1a3185879d6d23f831e74 --- /dev/null +++ b/pool/shard005/JavaScript/0032528_rq-angular-napp-menu.js @@ -0,0 +1,83 @@ +/** + * Module + * + * Description + */ +define(["angular"], function(angular) { + 'use strict'; + + return angular.module('napp.menu', []) + .directive('menu', ["$location", + function(location) { + return { + restrict: "AE", + transclude: true, + replace: true, + scope: { + title: "@" + }, + controller: function($scope) { + $scope.items = []; + + this.addItem = function(match, element) { + $scope.items.push({"element": element, "match": match}); + + var reg = new RegExp(match); + + if (reg.test(location.path())) { + angular.element(element).addClass("active"); + } + }; + + $scope.$on("$routeChangeStart", function() { + var route = location.path(); + + for (var item in $scope.items) { + item = $scope.items[item]; + var reg = new RegExp(item.match); + if (reg.test(route)) { + angular.element(item.element).addClass("active"); + } else { + angular.element(item.element).removeClass("active"); + } + } + }); + }, + templateUrl: "/app/lib/napp-menu/partials/menu.html", + }; + } + ]) + .directive("menuItemParent", function() { + return { + require: "^menu", + restrict: "AE", + replace: true, + transclude: true, + scope: { + match: "@", + title: "@" + }, + link: function(scope, element, attrs, menuCtrl) { + menuCtrl.addItem(scope.match, element); + }, + templateUrl: "/app/lib/napp-menu/partials/menu-item-parent.html" + }; + }) + .directive('menuItem', function() { + return { + require: "^menu", + restrict: 'AE', + replace: true, + transclude: true, + scope: { + match: "@", + route: "@", + title: "@" + }, + link: function(scope, element, attrs, menuCtrl) { + menuCtrl.addItem(scope.match, element); + }, + templateUrl: "/app/lib/napp-menu/partials/menu-item.html", + } + }); +}); \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032529_poseestimation_normal.js b/pool/shard005/JavaScript/0032529_poseestimation_normal.js new file mode 100644 index 0000000000000000000000000000000000000000..6ca241d0e2b121f64be0887fe152f4ace418617d --- /dev/null +++ b/pool/shard005/JavaScript/0032529_poseestimation_normal.js @@ -0,0 +1,79 @@ +QUnit.module("PoseEstimation Profile Normal Test", { + before: function () { + init(); + } +}); + + +/** + * PoseEstimationプロファイルの正常系テストを行うクラス。 + * @class + */ +let PoseEstimationProfileNormalTest = {}; + +/** + * 姿勢推定を取得するテストを行う。 + *

【HTTP通信】

+ *

+ * Method: GET
+ * Path: /poseEstimation/onPoseEstimation?serviceId=xxxx&accessToken=xxx
+ *

+ *

【期待する動作】

+ *

+ * ・resultに0が返ってくること。
+ * ・poseの値が返ってくること。
+ *

+ */ +PoseEstimationProfileNormalTest.poseNormalTest = function (assert) { + let done = assert.async(); + sdk.get({ + profile: 'poseEstimation', + attribute: 'onPoseEstimation', + params: { + serviceId: getCurrentServiceId() + } + }).then(json => { + assert.ok(true, "result=" + json.result); + assert.ok(json.pose != undefined, "pose=" + json.pose); + done(); + }).catch(e => { + assert.ok(checkErrorCode(e.errorCode), + 'errorCode=' + e.errorCode + ' errorMessage=' + e.errorMessage); + done(); + }); +} +QUnit.test("pose", PoseEstimationProfileNormalTest.poseNormalTest); + +/** + * PoseEstimationプロファイルのheartrateの登録と解除を行うテストを行う。 + *

【HTTP通信】

+ *

+ * Method: PUT
+ * Path: /poseEstimation/onPoseEstimation?serviceId=xxxx&accessToken=xxx
+ *

+ *

【期待する動作】

+ *

+ * ・resultに0が返ってくること。
+ * ・イベント通知が送られてくること。
+ *

+ */ +PoseEstimationProfileNormalTest.poseEventNormalTest001 = function (assert) { + let params = { + profile: 'poseEstimation', + attribute: 'onPoseEstimation', + params: { + serviceId: getCurrentServiceId() + } + }; + openWebsocket(params, assert, 10000, message => { + let json = JSON.parse(message); + if (json.profile === "poseEstimation" + && json.attribute === "onPoseEstimation") { + assert.ok(true, message); + assert.ok(json.pose != undefined, "pose=" + json.pose); + return true; + } + return false; + }); +} +QUnit.test("poseEventNormalTest001", PoseEstimationProfileNormalTest.poseEventNormalTest001); diff --git a/pool/shard005/JavaScript/0032530_ruleFileList.js b/pool/shard005/JavaScript/0032530_ruleFileList.js new file mode 100644 index 0000000000000000000000000000000000000000..98a9d68cf9de8e4e4c4d4645fa163e727dcc40c1 --- /dev/null +++ b/pool/shard005/JavaScript/0032530_ruleFileList.js @@ -0,0 +1,289 @@ +/** + * HABmin - the openHAB admin interface + * + * openHAB, the open Home Automation Bus. + * Copyright (C) 2010-2013, openHAB.org + * + * See the contributors.txt file in the distribution for a + * full listing of individual contributors. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + * Additional permission under GNU GPL version 3 section 7 + * + * If you modify this Program, or any covered work, by linking or + * combining it with Eclipse (or a modified version of that library), + * containing parts covered by the terms of the Eclipse Public License + * (EPL), the licensors of this Program grant you additional permission + * to convey the resulting work. + */ + +/** + * OpenHAB Admin Console HABmin + * + * @author Chris Jackson + */ + + +Ext.define('openHAB.automation.ruleFileList', { + extend: 'Ext.panel.Panel', + layout: 'fit', + icon: 'images/document-copy.png', + + initComponent: function () { + this.title = language.rule_FileListTitle; + + // Define the Rule Template Store + Ext.define('RuleModelModel', { + extend: 'Ext.data.Model', + fields: [ + {name: 'model'}, + {name: 'rule'} + ] + }); + + var ruleModelStore = Ext.create('Ext.data.ArrayStore', { + model: 'RuleModelModel' + }); + + var toolbar = Ext.create('Ext.toolbar.Toolbar', { + items: [ + { + icon: 'images/plus-button.png', + itemId: 'add', + text: language.add, + cls: 'x-btn-icon', + disabled: false, + tooltip: language.rule_FileListAddTip, + handler: function () { + Ext.define('RuleModelsModel', { + extend: 'Ext.data.Model', + fields: [ + {name: 'name'}, + {name: 'icon'}, + {name: 'iconCls'} + ] + }); + + // Generate a list of all existing models + // User can type their own, but this gives them options. + var models = []; + var ocnt = 0; + for (var cnt = 0; cnt < ruleModelStore.getCount(); cnt++) { + var found = false; + var name = ruleModelStore.getAt(cnt).get("model"); + for (var mcnt = 0; mcnt < models.length; mcnt++) { + if (models[mcnt].name == name) { + found = true; + break; + } + } + if (found === false) { + models[ocnt] = {}; + models[ocnt].name = name; + ocnt++; + } + } + + var form = Ext.widget('form', { + layout: { + type: 'vbox', + align: 'stretch' + }, + border: false, + bodyPadding: 10, + fieldDefaults: { + labelAlign: 'top', + labelWidth: 100, + labelStyle: 'font-weight:bold' + }, + defaults: { + margins: '0 0 10 0' + }, + items: [ + { + margin: '0 0 0 0', + xtype: 'combobox', + fieldLabel: 'Model name:', + itemId: 'model', + name: 'model', + store: {model: 'RuleModelsModel', data: models}, + allowBlank: false, + valueField: 'name', + displayField: 'name', + queryMode: 'local', + forceSelection: false, + editable: true, + typeAhead: true + } + ], + buttons: [ + { + text: language.cancel, + handler: function () { + this.up('window').destroy(); + } + }, + { + text: language.rule_FileListCreateButton, + handler: function () { + if (this.up('form').getForm().isValid()) { + // Read the model name + var model = form.getForm().findField('model').getSubmitValue(); + + var newProperties = null; + + // Create a new ruleEditor + var newProperties = Ext.create('openHAB.automation.ruleEditor', { + modelName: model + }); + + if (newProperties != null) + Ext.getCmp('automationPropertyContainer').setNewProperty(newProperties); + + this.up('window').destroy(); + } + } + } + ] + }); + + var createWin = Ext.widget('window', { + title: language.rule_FileListCreateButton, + closeAction: 'destroy', + width: 225, + resizable: false, + draggable: false, + modal: true, + layout: { + type: 'vbox', + align: 'stretch' + }, + items: [form] + }); + + createWin.show(); + } + }, + { + xtype: 'tbfill' + }, + { + icon: 'images/arrow-circle-315.png', + itemId: 'refresh', + cls: 'x-btn-icon', + disabled: false, + tooltip: language.refresh, + handler: function () { + loadModelList(); + } + } + ] + }); + + var ruleList = Ext.create('Ext.grid.Panel', { + store: ruleModelStore, + header: false, + split: true, + tbar: toolbar, + collapsible: false, + multiSelect: false, + columns: [ + { + text: language.rule_FileListModel, + flex: 1, + dataIndex: 'model' + /*, + renderer:function (value, metadata, record) { + var icon = ""; + var ref = itemConfigStore.findExact("name", value); + if (ref != -1) { + if (itemConfigStore.getAt(ref).get('icon') != "") + icon = ''; + } + + return '
' + icon + '
' + value + '
'; + }*/ + }, + { + text: language.rule_FileListRule, + flex: 3, + dataIndex: 'rule' + } + ], + listeners: { + itemclick: function (grid, record) { + if (record == null) + return; + + // Create a new ruleEditor + var newProperties = Ext.create('openHAB.automation.ruleEditor', { + modelName: record.get('model'), + ruleName: record.get('rule') + }); + + if (newProperties != null) + Ext.getCmp('automationPropertyContainer').setNewProperty(newProperties); + + // Update the toolbar +// toolbar.getComponent('delete').enable(); + } + } + }); + + this.items = ruleList; + + this.callParent(); + + loadModelList(); + + function loadModelList() { + // Clear the existing data + ruleModelStore.loadData([], false); + + // Load the rule list from openHAB + Ext.Ajax.request({ + url: HABminBaseURL + "/config/rules/model/list", + headers: {'Accept': 'application/json'}, + method: 'GET', + success: function (response, opts) { + var json = Ext.decode(response.responseText); + // If there's no config for this sitemap, records will be null + if (json == null) + return; + + var models = [].concat(json.rule); + for (var cnt = 0; cnt < models.length; cnt++) { + if (models[cnt].rules == null) { + var element = {}; + element.model = models[cnt].model; + + ruleModelStore.add(element); + continue; + } + var rules = [].concat(models[cnt].rules); + for (var elcnt = 0; elcnt < rules.length; elcnt++) { + var element = {}; + element.model = models[cnt].model; + element.rule = rules[elcnt].name; + + ruleModelStore.add(element); + } + } + } + }); + } + } +}) +; \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032531_index.ui.js b/pool/shard005/JavaScript/0032531_index.ui.js new file mode 100644 index 0000000000000000000000000000000000000000..e64d6a7380e39942299ff0593edf968bd8ede5a7 --- /dev/null +++ b/pool/shard005/JavaScript/0032531_index.ui.js @@ -0,0 +1,36 @@ +//related to pullAnimation.ui +var image=ui("do_ImageView_3"); +var scroll=ui("do_ScrollView_1"); +var nf=sm("do_Notification"); +var list=ui("do_ListView_1"); +var page=sm("do_Page"); +var app=sm("do_App"); +var close = ui("close1"); +var do_Label_3=ui("do_Label_3"); + +close.on("touch", function() { + app.closePage(); +}) +page.on("back", function() { + app.closePage(); +}); + +do_Label_3.show("slide_l2r", 3000); + +var animator = mm("do_Animator"); +var animatorB = mm("do_Animator"); + + //顶部背景显示动画 + animator.append(5000, props, "EaseOut"); + var props = {bgColor:"0080FFFF"} + animatorB.append(5000, propsB, "EaseOut"); + var propsB = {bgColor:"#ffFFFF00"} + scroll.on("scroll", function(datas) { + //根据返回的值,改变图片的高 + deviceone.print(JSON.stringify(datas)); + image.height = 500 -+ datas; + image.redraw(); + + }); + + diff --git a/pool/shard005/JavaScript/0032532_main.js b/pool/shard005/JavaScript/0032532_main.js new file mode 100644 index 0000000000000000000000000000000000000000..35582debf4e68c328642e8f34bb627823b4193d1 --- /dev/null +++ b/pool/shard005/JavaScript/0032532_main.js @@ -0,0 +1,114 @@ +var obj_geditor=document.getElementById("geditor"); +var obj_tools=document.getElementById("tools"); +var obj_geditor_co=document.getElementById("geditor").contentWindow; +//³õʼ»¯£¬±à¼­Æ÷ +//¼ì²âÓû§°´¼ü£¬´Ó¶øÌí¼Ó±êÇ© + var p_ok=0; + window.onkeyup=function(event){ + var e = event || window.event || arguments.callee.caller.arguments[0]; + if(obj_geditor.textContent!=""){ + if(p_ok==0){ + for(var i=0;i<=100;i++){ + if(e && e.keyCode==i){ + //alert(s.textContent); + obj_geditor.innerHTML="

"+obj_geditor.textContent+"

"; + p_ok=1; + } + + } + } + }else{ + p_ok=0; + } +}; + + +/**¹«¹²µ÷Ó÷½·¨**/ +//½«Îı¾ÄÚÈÝÑ¡ÖУ¬²¢½øÐÐÏàÓ¦²Ù×÷ +var s; +function funcSelectText(mode,attr,value){ //modeÖ¸ÔªËØ±êÇ©;attrÖ¸Ëù´´½¨ÔªËصÄÊôÐÔ;valueÖ¸ÊôÐÔÖµ + var txt=""; + if(document.selection){ + sel=document.selection.createRange().text; + }else{ + sel=document.getSelection(); + } + txt=sel.getRangeAt(0).extractContents().textContent; + range=sel.getRangeAt(0); + if(txt.length>0){ + s=range; + range.deleteContents(); + var obj_txt=document.createElement(mode); + if(attr==""||value==""){ + obj_txt.innerHTML=txt; + range.insertNode(obj_txt); + }else{ + obj_txt.setAttribute(attr,value); + obj_txt.innerHTML=txt; + range.insertNode(obj_txt); + } + } + // alert(range); + /*if(txt!=null || txt!=""){ + obj_geditor.innerHTML=obj_geditor.textContent.replace(txt,"121312"); + } Ìæ»»Îı¾*/ + + } +/**var container = container || document; + container.onmouseup = function(){ + funcSelectText(); + } °´ÏÂÊó±êµ÷ÓÃÑ¡ÖÐÎı¾,²âÊÔʱºòÓõÄ**/ + +//option±êÇ©µÄÑ¡Ôñº¯Êý·½·¨£¨¹«¹²·½·¨,¿Éµ÷Óã© +/**function opsel(id,mode,attr,val){ + var oindex; + var id=id; + var mode=mode; + var attr=attr; + var obj=document.getElementById(id); + value=obj.options[obj_font_size.options.selectedIndex].text; + obj_geditor.onfocus=funcSelectText(mode,attr,val+value); + } +**/ +//(×¢ÒâÕâ¸ö·½·¨Ö»ÄÜÔÚselectÏÂʹÓã¡)µ÷ÓÃѡȡoptionµÄ·½·¨º¯Êý£¬¿ÉÖ±½Óµ÷ÓÃʹÓã¡idÖ¸£ºÒªµ÷Ó÷½·¨µÄÔªËØidÖµ£»modeÖ¸±êÇ©,±ÈÈç:span£»attrÖ¸ÊôÐÔÃû³Æ,È磺style£»valÖ¸ÊôÐÔÖµµÄÒ»²¿·Ö,È磺font-size:,×¢ÒâðºÅ±ØÐë¼ÓÉÏvalue¾ÍÊÇÑ¡ÖеÄÖµÁË +function fs(id,mode,attr,val,ty){ + var val=val; + var id=id; + var obj=document.getElementById(id); + value=obj.options[obj.options.selectedIndex].text; + if(ty=="" || ty==null){ //tyÖ¸µÄÊÇÇл»valueºÍmode,ÒÔÊÊÓ¦¿ª·¢½×¶Î + funcSelectText(mode,attr,val+value);}else{ + funcSelectText(value,attr,mode); //´ËʱvalueºÍmode½øÐÐÁËÇл» + } + } + +//ÏÔÊ¾ÔªËØ + function show(){ +alert(obj_geditor.innerHTML); +} + + +/**µ÷Óòå¼þ¹Ø¼ü¹¦ÄÜ**/ + +var js_src=new Array("tools/font/font_size.js","tools/font/font_type.js"); //×¢²á²å¼þµØÖ· + + function diaoyong(src1){ //µ÷Óòå¼þ + var src=src1; + new_js=document.createElement("script"); + new_js.setAttribute("type","text/javascript"); + new_js.setAttribute("src",src); + document.body.appendChild(new_js); +} + + + function js_ok(){ + for(var i=0;i<=js_src.length;i++){ + //alert(js_src[i]); + diaoyong(js_src[i]); + } + } + +js_ok(); +//alert("ssssss"); + + diff --git a/pool/shard005/JavaScript/0032534_index.js b/pool/shard005/JavaScript/0032534_index.js new file mode 100644 index 0000000000000000000000000000000000000000..3bd37e631b22beb42f0e96e99e203ae97ee50206 --- /dev/null +++ b/pool/shard005/JavaScript/0032534_index.js @@ -0,0 +1,84 @@ +/*jslint node: true, forin: true, jslint white: true, newcap: true*/ +/* + * wrappify + * author : Takeshi Iwana + * https://github.com/iwatakeshi + * license : MIT + * Code heavily borrowed from Adam Draper + * https://github.com/adamwdraper + */ + +(function() { + 'use strict'; + + var wrappify, + hasModule = (typeof module !== 'undefined' && module.exports); + + function Wrappify(core) { + 'use strict'; + this.core = core; + } + + Wrappify.prototype.express = function() { + return this.core.ship.bind(this.core); + }; + + Wrappify.prototype.hapi = function() { + var core = this.core; + var plugin = { + register: function hapi(plugin, options, next) { + plugin.ext('onPreHandler', function(request, reply) { + core.ship.bind(core)(request); + reply.continue(); + }); + plugin.ext('onPreResponse', function(request, reply) { + core.ship.bind(core)(request); + reply.continue(); + }); + return next(); + } + } + plugin.register.attributes = { + name: 'Wrappify', + version: '0.0.1' + } + return plugin; + }; + + Wrappify.prototype.koa = function() { + var core = this.core; + return function (self, next) { + core.ship.bind(core)(self); + return next(); + } + }; + + + wrappify = function(core) { + return new Wrappify(core); + }; + + /************************************ + Exposing wrappify + ************************************/ + + // CommonJS module is defined + if (hasModule) { + module.exports = wrappify; + } + + /*global ender:false */ + if (typeof ender === 'undefined') { + // here, `this` means `window` in the browser, or `global` on the server + // add `wrappify` as a global object via a string identifier, + // for Closure Compiler 'advanced' mode + this.wrappify = wrappify; + } + + /*global define:false */ + if (typeof define === 'function' && define.amd) { + define([], function() { + return wrappify; + }); + } +}).call(this); diff --git a/pool/shard005/JavaScript/0032535_index.js b/pool/shard005/JavaScript/0032535_index.js new file mode 100644 index 0000000000000000000000000000000000000000..42e4fe2a92984efca4ade79347fa39ebc69e45b0 --- /dev/null +++ b/pool/shard005/JavaScript/0032535_index.js @@ -0,0 +1,28 @@ +const lastSaid = {}; +const replaceRegex = /^s\/(.*?)\/(.*?)(?:(?:\/g)|(?:\/))?$/; + +function replaceAll(find, replace, str) { + return str.replace(new RegExp(find, 'g'), replace); +} + +module.exports.msg = function (text, from, reply, raw) { + match = replaceRegex.exec(text); + if (match) { + // Replace the last thing the person said, if anything + if (lastSaid[from] != undefined) { + let personLastSaid = lastSaid[from], + find = match[1], + replace = match[2]; + const fixed = replaceAll(find, replace, personLastSaid); + + if (fixed != personLastSaid) { + const response = `<${from}> ${fixed}`; + + reply(response); + } + } + } else { + // The proper way to do this would be with scrollback module but w/e + lastSaid[from] = text; + } +}; diff --git a/pool/shard005/JavaScript/0032537_child-router.test.js b/pool/shard005/JavaScript/0032537_child-router.test.js new file mode 100644 index 0000000000000000000000000000000000000000..91e4d8cd84548c7dc95956a183629dd49a895968 --- /dev/null +++ b/pool/shard005/JavaScript/0032537_child-router.test.js @@ -0,0 +1,37 @@ +import { ChildRouter } from '../../src/child-router'; +var RouterStub = (function () { + function RouterStub() { + } + RouterStub.prototype.configure = function (handler) { + handler(this); + }; + RouterStub.prototype.map = function (routes) { + this.routes = routes; + }; + return RouterStub; +}()); +describe('the Child Router module', function () { + var sut; + var mockedRouter; + beforeEach(function () { + mockedRouter = new RouterStub(); + sut = new ChildRouter(); + sut.configureRouter(mockedRouter, mockedRouter); + }); + it('contains a router property', function () { + expect(sut.router).toBeDefined(); + }); + it('configures the heading', function () { + expect(sut.heading).toEqual('Child Router'); + }); + it('should have a welcome route', function () { + expect(sut.router.routes).toContainEqual({ route: ['', 'welcome'], name: 'welcome', moduleId: './welcome', nav: true, title: 'Welcome' }); + }); + it('should have a users route', function () { + expect(sut.router.routes).toContainEqual({ route: 'users', name: 'users', moduleId: './users', nav: true, title: 'Github Users' }); + }); + it('should have a child router route', function () { + expect(sut.router.routes).toContainEqual({ route: 'child-router', name: 'child-router', moduleId: './child-router', nav: true, title: 'Child Router' }); + }); +}); +//# sourceMappingURL=child-router.test.js.map \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032538_collapser.user.js b/pool/shard005/JavaScript/0032538_collapser.user.js new file mode 100644 index 0000000000000000000000000000000000000000..7fd0d2b56277506d8b0cd37b467da0baf3e03972 --- /dev/null +++ b/pool/shard005/JavaScript/0032538_collapser.user.js @@ -0,0 +1,97 @@ +import UI from './ui'; +import Settings from './settings'; + +const idPrefix = 'collapser'; +const userSettings = new Settings('collapser.'); +const dataToggle = 'data-toggle'; + +var buffers; // All networks +var colEnabled, colTogActive, colTogInactive, colTogConvo, colTogArchive; +var toggleApply = false; + +function hide () { + var header = $(this); + var restore = header.data('restore'); + + if (restore == null || toggleApply == true) { + toggleApply = false; + restore = header.nextAll(); + + var classes = [colTogActive, colTogInactive, colTogConvo, colTogArchive] + .filter(i => i.prop('checked')) + .map(i => i.attr(dataToggle)) + .join(', '); + + restore = restore.filter(classes); + header.data('restore', restore); + } + + restore.filter('.archiveToggle').toggleClass('show'); + restore.not('.archiveToggle').toggleClass('hide'); +} + +function toggleActivation (toggle) { + buffers[toggle == true ? 'on' : 'off']('dblclick', hide); +} + +UI.pageReady(function () { + + var style = '$includeStyle$'; + style = UI.embedStyle(style); + + const hashName = 'collapser'; + var menu = UI.buildMenuTemplate('collapser-menu', hashName, 'Collapser'); + menu = $(menu); + menu = UI.addMenu(menu); + + var container = '$includeContainer$'; + container = $(container); + container = UI.addContainer(container); + + window.location.hash === '#?/settings=' + hashName && SESSIONVIEW.showSettings(hashName); + buffers = $('h2.buffer'); + + // Init container props + const snEnabled = 'enabled'; + colEnabled = container.find(`#${idPrefix}-enabled-check`); + colEnabled + .change(() => { userSettings.set(snEnabled, colEnabled[0].checked); toggleActivation(colEnabled[0].checked); }) + .prop('checked', JSON.parse(userSettings.get(snEnabled, true))); + + + function blink1 (next) { buffers.css({ outline: '4px solid blue' }); next(); } + function blink2 (next) { buffers.css({ outline: '' }); next(); } + var colShowNetworks = container.find(`#${idPrefix}-show-networks`) + .click(() => { buffers.clearQueue(); for (var i = 0; i < 2; i++) buffers.queue(blink1).delay(600).queue(blink2).delay(600); }); + + const snActive = 'toggle.active'; + colTogActive = container.find(`#${idPrefix}-collapse-active`); + colTogActive + .attr(dataToggle, '.channels') + .change(() => { userSettings.set(snActive, colTogActive[0].checked); toggleApply = true; }) + .prop('checked', JSON.parse(userSettings.get(snActive, true))); + + const snInactive = 'toggle.inactive'; + colTogInactive = container.find(`#${idPrefix}-collapse-inactive`); + colTogInactive + .attr(dataToggle, '.inactiveChannels') + .change(() => { userSettings.set(snInactive, colTogInactive[0].checked); toggleApply = true; }) + .prop('checked', JSON.parse(userSettings.get(snInactive, true))); + + const snConvo = 'toggle.convo'; + colTogConvo = container.find(`#${idPrefix}-collapse-convo`); + colTogConvo + .attr(dataToggle, '.conversations') + .change(() => { userSettings.set(snConvo, colTogConvo[0].checked); toggleApply = true; }) + .prop('checked', JSON.parse(userSettings.get(snConvo, true))); + + const snArchive = 'toggle.archive'; + colTogArchive = container.find(`#${idPrefix}-collapse-archive`); + colTogArchive + .attr(dataToggle, '.archiveToggle') + .change(() => { userSettings.set(snArchive, colTogArchive[0].checked); toggleApply = true; }) + .prop('checked', JSON.parse(userSettings.get(snArchive, true))); + + // Start + JSON.parse(userSettings.get('enabled', true)) && toggleActivation(true); +}); diff --git a/pool/shard005/JavaScript/0032543_map_flatten_and_wrap_filters.js b/pool/shard005/JavaScript/0032543_map_flatten_and_wrap_filters.js new file mode 100644 index 0000000000000000000000000000000000000000..7b449468f44ea4655acba35da844c8ac460cf541 --- /dev/null +++ b/pool/shard005/JavaScript/0032543_map_flatten_and_wrap_filters.js @@ -0,0 +1,14 @@ +import _ from 'lodash'; +import FilterBarLibMapAndFlattenFiltersProvider from 'ui/filter_bar/lib/map_and_flatten_filters'; +export default function mapFlattenAndWrapFilters(Private) { + const mapAndFlattenFilters = Private(FilterBarLibMapAndFlattenFiltersProvider); + return function (filters) { + return mapAndFlattenFilters(filters).then(function (filters) { + return _.map(filters, function (filter) { + filter.meta = filter.meta || {}; + filter.meta.apply = true; + return filter; + }); + }); + }; +} diff --git a/pool/shard005/JavaScript/0032547_train-tracking-service.js b/pool/shard005/JavaScript/0032547_train-tracking-service.js new file mode 100644 index 0000000000000000000000000000000000000000..e52ccfe94379f876e5a7766586db2e76e138d4b0 --- /dev/null +++ b/pool/shard005/JavaScript/0032547_train-tracking-service.js @@ -0,0 +1,43 @@ +'use strict'; + +/** + * @ngdoc service + * @name traffic.trainTrackingService + * @description + * # trainTrackingService + * Service in the traffic. + */ +angular.module('traffic') + .service('trainTrackingService', function() { + var stompClient = null; + var subscription; + +/* function getHistory(trainNumber) { + var url = 'http://rata.digitraffic.fi/api/v1/train-tracking/' + trainNumber + '?departure_date=2016-01-26'; + return $http.get(url); + } +*/ + //TODO: refactor as generic pub/sub stomp service & extend + var trainTrackingService = { + track: function(trainNumber, callback) { + var socket = new SockJS('http://rata.digitraffic.fi/api/v1/websockets/train-tracking'); + stompClient = Stomp.over(socket); + stompClient.connect({}, function(frame) { + console.log('frame', frame); + subscription = stompClient.subscribe('/' + trainNumber, function(message) { + callback(angular.fromJson(message.body)[0]); + }); + }); + }, + stop: function() { + if (subscription) { + subscription.unsubscribe(); + } + if (stompClient) { + stompClient.disconnect(); + } + } + }; + + return trainTrackingService; + }); diff --git a/pool/shard005/JavaScript/0032548_work.js b/pool/shard005/JavaScript/0032548_work.js new file mode 100644 index 0000000000000000000000000000000000000000..c748e82dd2a3fac292fd2a6c6f025f5708f1ef52 --- /dev/null +++ b/pool/shard005/JavaScript/0032548_work.js @@ -0,0 +1,16 @@ +//alert(localStorage["user"]); +var storage = {}; + +function loginform(){ + if(storage.user && storage.pass){ + if($("#loginForm").length>0&&$("p.error").length==0){ + $("#loginForm #nme").val(storage.user); + $("#loginForm #pwd").val(storage.pass); + $("#loginForm [type=submit]").click(); + } + } +} +chrome.runtime.sendMessage({greeting: "hello"}, function(response) { + storage = response.storage; + loginform(); +}); diff --git a/pool/shard005/JavaScript/0032551_ui_tab_panel_library.js b/pool/shard005/JavaScript/0032551_ui_tab_panel_library.js new file mode 100644 index 0000000000000000000000000000000000000000..ed0c25378eebecd4d915f968cd78102b9d213ebb --- /dev/null +++ b/pool/shard005/JavaScript/0032551_ui_tab_panel_library.js @@ -0,0 +1,255 @@ +/* + * @Author: Vaninadh + * @Date: 2016-03-30 19:51:31 + * @Last Modified by: Vaninadh + * @Last Modified time: 2016-04-27 11:31:12 + */ + +define(function(require) { + var defineComponent = require("flight/lib/component"); + var uiCellMixinDraggable = require("KCEPROD/ui/sider_panel/cell/ui_cell_mixin_draggable"); + var util = require("KCEPROD/util/util"); + + var Mustache = require("mustache"); + var ns = window.kc.ns; + + return defineComponent(uiCellMixinDraggable, uiTabPanelLibrary); + + function uiTabPanelLibrary() { + this.attributes({ + loadonce: false, + picAddBtnSelector: "#library-add-pic", + picUploadFileSelector: ".pic-upload-file", + picBtnDivSelector: ".pic-btn-div", + libraryTabSelector: "#tab-library", + libraryPicBoxSelector: "#library-pic-box", + pageid: 0, + cellLibrarySelector: ".library-cell", + cellImageSelector: ".cell-image", + itemOpDeleteSelector: ".icon-shanchu", + itemDraggable: ".item-draggable", + picDialog: "", + pic_dialog_url: "#pic_dialog_url", + picPreview: "#picPreview", + picAddClose: "#picAddClose", + picSaveBtn: "#picSaveBtn" + + }); + + this.renderTab = function(e, data) { + if (!this.attr.loadonce) { + console.log("render uiTabPanelLibrary is ok!"); + + var that = this; + $('body').append(this.getDialog()); + + this.attr.picDialog = $("#uiPicAdd").dialog({ + closeOnEscape:false, + create: function(event) { + $(event.target).dialog("widget").css({ "position": "fixed" }); + }, + resizable: false, + height: 400, + width: 680, + modal: true, + title: 'i am dialog', + position: { my: "top", at: "bottom", of: $('#artOpPanel') }, + dialogClass: '', + autoOpen: false, + buttons: { + + } + }); + + this.renderPicListScroll(); + this.addBoxListener(); + } + this.attr.loadonce = true; + } + + this.addBoxListener = function() { + var that = this; + + $(this.attr.loveBoxSelector).scroll(function() { + var $this = $(this); + var height = this.scrollHeight - $this.height() - 50; // Get the height of the div + var scroll = $this.scrollTop(); // Get the vertical scroll position + + var isScrolledToEnd = (scroll >= height); + + if (isScrolledToEnd) { + that.renderPicListScroll(); + } + }); + + this.on(this.attr.libraryTabSelector, 'click', { + itemOpDeleteSelector: this.itemOpDelete, + picAddBtnSelector: this.picAddDialog + }); + + this.on(this.attr.picBtnDivSelector, 'change', { + picUploadFileSelector: this.picUpload + }); + + this.on(this.attr.picAddClose, 'click', this.closePicAddDialog); + + this.on(this.attr.pic_dialog_url, 'change', this.onImgUrlChange); + this.on(this.attr.picSaveBtn, 'click', this.picSave); + } + + this.renderPicListScroll = function() { + this.trigger(ns.e.data.dataPicList, { + pageid: this.attr.pageid, + triggerEvent:ns.e.tab.uiPicList + }); + this.attr.pageid++; + } + this.clearPicListInBox = function() { + this.attr.pageid = 0; + $(this.attr.libraryPicBoxSelector).html(''); + } + + this.itemOpDelete = function(e, data) { + var lid = $(data.el).parent().data('id'); + this.trigger(ns.e.data.dataPicDelete, { + lid: lid, + el: data.el, + triggerEvent:ns.e.tab.uiPicDelete + }); + }; + this.picSave = function (){ + var url = $("#pic_dialog_url").val(); + this.picAdd(null, { + url: url + }); + + this.closePicAddDialog(); + } + + this.picAdd = function(e, data) { + this.trigger(ns.e.data.dataPicAdd, { + url: data.url, + triggerEvent:ns.e.tab.uiPicRefresh + }); + } + + this.picUpload = function(e, data) { + var file = $(data.el)[0].files[0]; + var that = this; + var ic = ns.c.img; + util.uploadfile(file, { + success: function(blkRet) { + that.picAdd(null, { + url: ic.url + blkRet.key + "?" + ic.api_type + ic.suf + ic.mode + ic.suf + "w" + ic.suf + ic.pic_list_img.w + }); + }, + error: function() { + + } + }); + } + + this.onImgUrlChange = function () { + var url = $("#pic_dialog_url").val(); + $(this.attr.picPreview).attr("src",url); + } + + this.picAddDialog = function() { + util.displayGrayBg(); + this.attr.picDialog.dialog("open"); + } + + this.closePicAddDialog = function() { + this.attr.picDialog.dialog("close"); + util.hideGrayBg(); + } + + //callback when server send json data to client + this.renderPicList = function(e, data) { + $(this.attr.libraryPicBoxSelector).append(Mustache.render(this.getTmpl(), data.json)); + this.activeDraggable($(this.attr.itemDraggable)); + } + + this.renderPicDelete = function(e, data) { + $(data.el).parent().parent().remove(); + } + + this.renderPicRefresh = function(e, data) { + if (this.attr.loadonce) { + /*var json = { + objs: { + id: data.json.lid, + url: data.url + } + }; + $(this.attr.libraryPicBoxSelector).append(Mustache.render(this.getTmpl(), json));*/ + this.clearPicListInBox(); + this.renderPicListScroll(); + } + } + + this.getDialog = function() { + return [ + // '
', + // '
', + // '', + // '', + // '
', + // '
', + '
\ + \ +
\ +
图片
\ +
\ + \ +
\ +
\ + 保存\ +
\ +
\ +
\ +
预览
\ + \ +
\ +
' + ].join('\n'); + } + + this.getTmpl = function() { + return [ + '{{#objs}}', + '
', + '
', + '', + '
', + '
', + '', + '
', + '
', + '{{/objs}}', + ].join('\n'); + } + + this.doDirectInsert = function (e, data){ + var lastIdx = util.getLastCanvasItemIndex(); + + var styleObj = {}; + styleObj['src']= e.currentTarget.attributes['src'].value; + this.trigger(ns.e.createNode, { + itemtype: 'image', + para : styleObj, + el:$(".canvas > [kctype='container']")[0], + preel: lastIdx, + }); + } + + this.after("initialize", function() { + console.log("uiTabPanelLibrary is ok!"); + this.on(document, ns.e.tab.uiTabLibrary, this.renderTab); + this.on(document, ns.e.tab.uiPicList, this.renderPicList); + this.on(document, ns.e.tab.uiPicDelete, this.renderPicDelete); + this.on(document, ns.e.tab.uiPicRefresh, this.renderPicRefresh); + this.on('click', {cellImageSelector: this.doDirectInsert}); + }); + } +}); diff --git a/pool/shard005/JavaScript/0032554_Data.js b/pool/shard005/JavaScript/0032554_Data.js new file mode 100644 index 0000000000000000000000000000000000000000..cbb9c91dc486a29d64a0ff442842aa5d5b7ad1c0 --- /dev/null +++ b/pool/shard005/JavaScript/0032554_Data.js @@ -0,0 +1,110 @@ +function Data(){ + + //this.config = JSON.parse(Titanium.App.Properties.getString("config")); +} + +Data.prototype.getGasolineras = function(coordenadas) { + var config = JSON.parse(Titanium.App.Properties.getString("config")); + var xhr = Titanium.Network.createHTTPClient({ + enableKeepAlive:false + }); + if(Ti.Network.online){ + xhr.timeout = 15000; + xhr.onload = function() + { + Ti.API.info('XHR "onload" ['+this.status+']: '+this.responseText+''); + Titanium.API.info('loaded'); + //Si nos responde correctamente con el JSON + if (this.status == 200) + { + var gasolineras = JSON.parse(this.responseText); + if (gasolineras.error == "Ninguna gasolinera cercana") + { + //hideIndicator(); + Titanium.API.info('Ninguna gasolinera cercana'); + var alertDialog = Titanium.UI.createAlertDialog({ + title: 'Aviso', + message: 'Ninguna gasolinera cercana a tu posición', + buttonNames: ['Reintentar','Ajustes'] + }); + //Mostramos alerta del error y volvemos a pedir las gasolineras si clicka el boton + alertDialog.show(); + alertDialog.addEventListener('click', function(e){ + //Si ha pulsado reintentar + if (e.index==0) + { + //showIndicator(); + Ti.App.fireEvent('location.refresh'); + } + else{ + Ti.App.fireEvent('gas.notfound'); + } + }); + } + else + { + var gasolinerasArray = new Array(); + + for (var c=0;c or + *
'); + subview.on("resize", finish); + subview.attr("id", (grid.target.attr("id") || "subview") + "-" + record.id); + + var subviewcontainer = $('
'); + subviewcontainer.css('top', $super.rowHeight(rowIdx)); + subviewcontainer.append(subview); + + target.append(subviewcontainer); + } else { + subview = [rowParts[0].querySelector(".pg-subview")]; + } + + if (subviewsExpanded[record.id]) { + target.addClass('pg-subview-expanded'); + + if (!target.is(".pg-row-subview-rendered")) { + var promise = pluginOptions.renderSubView(grid, record, subview[0]); + if (promise.then) { + promise.then(finish); + } else { + finish(); + } + } else { + grid.queueAdjustHeights(); + } + } + } + + $super.afterRenderRow(record, rowIdx, rowParts); + }, + + renderCellContent: function(record, column, value) { + var content = $super.renderCellContent.apply(this, arguments); + if(column.subViewToggle && record && grid.subviews.hasSubView(record)) { + var frag = document.createDocumentFragment(); + var subview = document.createElement("div"); + subview.classList.add("pg-subview-toggle"); + subview.classList.add(column.subViewToggleClass || "pg-subview-toggle-default"); + if(subviewsExpanded[record.id] == true) { + subview.classList.add("pg-subview-expanded"); + } + + frag.appendChild(subview); + if(content) { + frag.appendChild(content); + } + return frag; + } else { + return content; + } + }, + + rowHeight: function rowHeight(start, end) { + if(end === undefined) { + var record = grid.getRow(start); + if(!record || !subviewsExpanded[record.id]) { + return $super.rowHeight(start); + } else { + return $super.rowHeight(start) + subViewHeights[record.id]; + } + } else { + var baseHeight = $super.rowHeight(start, end); + + for(var id in subviewsExpanded) { + if(subviewsExpanded[id]) { + var record = grid.getRecordById(id); + var idx = grid.indexOfRow(record); + if(idx >= start && idx < end) { + baseHeight += subViewHeights[record.id]; + } + } + } + + return baseHeight; + } + } + } + }); + } + }; + +}); diff --git a/pool/shard005/JavaScript/0032864_Breadcrumb.js b/pool/shard005/JavaScript/0032864_Breadcrumb.js new file mode 100644 index 0000000000000000000000000000000000000000..0f93d0ba3c0409207eaccbc4f819bcee3a25c126 --- /dev/null +++ b/pool/shard005/JavaScript/0032864_Breadcrumb.js @@ -0,0 +1,52 @@ +(function() { + "use strict"; + + function Breadcrumb(options) { + this.$super(options); + } + + Breadcrumb.prototype = { + build: function() { + this.shadow($.create('div.wrap').attr('select', '*')); + + var items = this.items(); + + this.on('item.added', function(e) { + var item = e.detail.item; + var html = (item.contents || item.html || item.title || item); + var a = $.create('a').attr('href', (item.href || 'javascript:;')).html(html); + + this.append(a); + this.pack(); + items.related(item, a); + }); + + this.on('item.cleared', function(e) { + //console.log('cleared'); + this.empty(); + }); + + this.on('item.removed', function(e) { + var item = e.detail.item; + var a = items.related(item); + if( a ) a.detach(); + items.related(item, false); + }); + + this.$super(); + }, + pop: function() { + var items = this.items(); + items.remove(items.last()); + return this; + }, + push: function(item) { + var items = this.items(); + items.add(item); + return this; + } + }; + + Breadcrumb.fname = 'Breadcrumb'; + UI.component('breadcrumb', Breadcrumb); +})(); diff --git a/pool/shard005/JavaScript/0032865_IndexDatatypeSpec.js b/pool/shard005/JavaScript/0032865_IndexDatatypeSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..fdf5be5a399247b75548f346ee41a624536b0075 --- /dev/null +++ b/pool/shard005/JavaScript/0032865_IndexDatatypeSpec.js @@ -0,0 +1,95 @@ +define([ + 'Core/IndexDatatype', + 'Core/Math' + ], function( + IndexDatatype, + CesiumMath) { + 'use strict'; + +describe('Core/IndexDatatype', function() { + + it('IndexDatatype.validate validates input', function() { + expect(IndexDatatype.validate(IndexDatatype.UNSIGNED_SHORT)).toEqual(true); + expect(IndexDatatype.validate('invalid')).toEqual(false); + expect(IndexDatatype.validate(undefined)).toEqual(false); + }); + + it('IndexDatatype.createTypedArray creates array', function() { + expect(IndexDatatype.createTypedArray(3, 3).BYTES_PER_ELEMENT).toEqual(Uint16Array.BYTES_PER_ELEMENT); + expect(IndexDatatype.createTypedArray(CesiumMath.SIXTY_FOUR_KILOBYTES + 1, 3).BYTES_PER_ELEMENT).toEqual(Uint32Array.BYTES_PER_ELEMENT); + }); + + it('IndexDatatype.createTypedArray throws without numberOfVertices', function() { + expect(function() { + IndexDatatype.createTypedArray(undefined); + }).toThrowDeveloperError(); + }); + + it('IndexDatatype.createTypedArrayFromArrayBuffer creates Uint16Array', function() { + var sourceArray = new Uint16Array(10); + sourceArray.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + var indexBuffer = IndexDatatype.createTypedArrayFromArrayBuffer(3, sourceArray.buffer, 0, 5); + expect(indexBuffer.BYTES_PER_ELEMENT).toEqual(Uint16Array.BYTES_PER_ELEMENT); + expect(indexBuffer.length).toEqual(5); + expect(indexBuffer[0]).toEqual(0); + }); + + it('IndexDatatype.createTypedArrayFromArrayBuffer creates Uint16Array with offset', function() { + var sourceArray = new Uint16Array(10); + sourceArray.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + var indexBuffer = IndexDatatype.createTypedArrayFromArrayBuffer(3, sourceArray.buffer, Uint16Array.BYTES_PER_ELEMENT * 5, 5); + expect(indexBuffer.BYTES_PER_ELEMENT).toEqual(Uint16Array.BYTES_PER_ELEMENT); + expect(indexBuffer.length).toEqual(5); + expect(indexBuffer[0]).toEqual(5); + }); + + it('IndexDatatype.createTypedArrayFromArrayBuffer creates Uint32Array', function() { + var sourceArray = new Uint32Array(10); + sourceArray.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + var indexBuffer = IndexDatatype.createTypedArrayFromArrayBuffer(CesiumMath.SIXTY_FOUR_KILOBYTES + 1, sourceArray.buffer, 0, 5); + expect(indexBuffer.BYTES_PER_ELEMENT).toEqual(Uint32Array.BYTES_PER_ELEMENT); + expect(indexBuffer.length).toEqual(5); + expect(indexBuffer[0]).toEqual(0); + }); + + it('IndexDatatype.createTypedArrayFromArrayBuffer creates Uint32Array with offset', function() { + var sourceArray = new Uint32Array(10); + sourceArray.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + var indexBuffer = IndexDatatype.createTypedArrayFromArrayBuffer(CesiumMath.SIXTY_FOUR_KILOBYTES + 1, sourceArray.buffer, Uint32Array.BYTES_PER_ELEMENT * 5, 5); + expect(indexBuffer.BYTES_PER_ELEMENT).toEqual(Uint32Array.BYTES_PER_ELEMENT); + expect(indexBuffer.length).toEqual(5); + expect(indexBuffer[0]).toEqual(5); + }); + + it('IndexDatatype.createTypedArrayFromArrayBuffer throws without numberOfVertices', function() { + expect(function() { + IndexDatatype.createTypedArrayFromArrayBuffer(undefined); + }).toThrowDeveloperError(); + }); + + it('IndexDatatype.createTypedArrayFromArrayBuffer throws without sourceArray', function() { + expect(function() { + IndexDatatype.createTypedArrayFromArrayBuffer(3, undefined); + }).toThrowDeveloperError(); + }); + + it('IndexDatatype.createTypedArrayFromArrayBuffer throws without byteOffset', function() { + var sourceArray = new Uint16Array(5); + expect(function() { + IndexDatatype.createTypedArrayFromArrayBuffer(3, sourceArray.buffer, undefined); + }).toThrowDeveloperError(); + }); + + it('IndexDatatype.getSizeInBytes returns size', function() { + expect(IndexDatatype.getSizeInBytes(IndexDatatype.UNSIGNED_BYTE)).toEqual(Uint8Array.BYTES_PER_ELEMENT); + expect(IndexDatatype.getSizeInBytes(IndexDatatype.UNSIGNED_SHORT)).toEqual(Uint16Array.BYTES_PER_ELEMENT); + expect(IndexDatatype.getSizeInBytes(IndexDatatype.UNSIGNED_INT)).toEqual(Uint32Array.BYTES_PER_ELEMENT); + }); + + it('IndexDatatype.getSizeInBytes throws without indexDatatype', function() { + expect(function() { + IndexDatatype.getSizeInBytes(undefined); + }).toThrowDeveloperError(); + }); +}); +}); diff --git a/pool/shard005/JavaScript/0032866_dom.js b/pool/shard005/JavaScript/0032866_dom.js new file mode 100644 index 0000000000000000000000000000000000000000..587e33b87c32a4c01fe56dce2f1b358928fa4a6b --- /dev/null +++ b/pool/shard005/JavaScript/0032866_dom.js @@ -0,0 +1,57 @@ +import { Shatter, VoronoiPieces } from '../../src/index'; +import loadImage from '../../src/lib/loadImage'; + +async function run() { + const exImagePath = '/img/BlueMarbleNasa.png'; + const originalImageContainer = document.querySelector('.js-original'); + const original = await loadImage(exImagePath); + originalImageContainer.appendChild(original); + const pieceMargin = '1rem'; + let wrap = document.querySelector('.js-result'); + let assembled = document.querySelector('.js-result-assembled'); + const formEl = document.querySelector('form'); + + formEl.addEventListener('submit', (event) => { + event.preventDefault(); + const pieces = event.target.elements?.pieces?.value; + + if (pieces && Number(pieces) !== NaN) { + shatterExImage(Number(pieces)); + } + }); + + async function shatterExImage(num = 10) { + while (wrap.firstChild) { + wrap.firstChild.remove(); + } + + while (assembled.firstChild) { + assembled.firstChild.remove(); + } + + const voropieces = VoronoiPieces({ + height: original.width, + width: original.height, + numPieces: num, + }); + + const vshatter = new Shatter(exImagePath); + vshatter.setPieces(voropieces); + let results = await vshatter.shatter(); + + wrap.style.position = 'relative'; + + results.forEach((res, i) => { + res.image.style.marginRight = pieceMargin; + wrap.appendChild(res.image); + + const clone = res.image.cloneNode(); + clone.setAttribute('style', `position: absolute; top: ${res.y}px; left: ${res.x}px;`); + assembled.appendChild(clone); + }); + } + + shatterExImage(); +} + +run(); diff --git a/pool/shard005/JavaScript/0032868_mapper.js b/pool/shard005/JavaScript/0032868_mapper.js new file mode 100644 index 0000000000000000000000000000000000000000..0107704741dd5a84d99ba3801cd8b72add1fe314 --- /dev/null +++ b/pool/shard005/JavaScript/0032868_mapper.js @@ -0,0 +1,120 @@ +import _regeneratorRuntime from 'babel-runtime/regenerator'; + +/** + * Enhances a set of StackFrames with their original positions and code (when available). + * @param {StackFrame[]} frames A set of StackFrames which contain (generated) code positions. + * @param {number} [contextLines=3] The number of lines to provide before and after the line specified in the StackFrame. + */ +var map = function () { + var _ref = _asyncToGenerator(_regeneratorRuntime.mark(function _callee2(frames) { + var _this = this; + + var contextLines = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3; + var cache, files; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + cache = {}; + files = []; + + frames.forEach(function (frame) { + var fileName = frame.fileName; + + if (fileName == null) { + return; + } + if (files.indexOf(fileName) !== -1) { + return; + } + files.push(fileName); + }); + _context2.next = 5; + return settle(files.map(function () { + var _ref2 = _asyncToGenerator(_regeneratorRuntime.mark(function _callee(fileName) { + var fileSource, map; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return fetch(fileName).then(function (r) { + return r.text(); + }); + + case 2: + fileSource = _context.sent; + _context.next = 5; + return getSourceMap(fileName, fileSource); + + case 5: + map = _context.sent; + + cache[fileName] = { fileSource: fileSource, map: map }; + + case 7: + case 'end': + return _context.stop(); + } + } + }, _callee, _this); + })); + + return function (_x3) { + return _ref2.apply(this, arguments); + }; + }())); + + case 5: + return _context2.abrupt('return', frames.map(function (frame) { + var functionName = frame.functionName, + fileName = frame.fileName, + lineNumber = frame.lineNumber, + columnNumber = frame.columnNumber; + + var _ref3 = cache[fileName] || {}, + map = _ref3.map, + fileSource = _ref3.fileSource; + + if (map == null || lineNumber == null) { + return frame; + } + + var _map$getOriginalPosit = map.getOriginalPosition(lineNumber, columnNumber), + source = _map$getOriginalPosit.source, + line = _map$getOriginalPosit.line, + column = _map$getOriginalPosit.column; + + var originalSource = source == null ? [] : map.getSource(source); + return new StackFrame(functionName, fileName, lineNumber, columnNumber, getLinesAround(lineNumber, contextLines, fileSource), functionName, source, line, column, getLinesAround(line, contextLines, originalSource)); + })); + + case 6: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function map(_x2) { + return _ref.apply(this, arguments); + }; +}(); + +function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import StackFrame from './stack-frame'; +import { getSourceMap } from './getSourceMap'; +import { getLinesAround } from './getLinesAround'; +import { settle } from 'settle-promise'; + +export { map }; +export default map; \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032870_md-toast-config-service.js b/pool/shard005/JavaScript/0032870_md-toast-config-service.js new file mode 100644 index 0000000000000000000000000000000000000000..aeaa60a2b2b852342ed27b2f6aff5704f302c1b6 --- /dev/null +++ b/pool/shard005/JavaScript/0032870_md-toast-config-service.js @@ -0,0 +1,45 @@ +//noinspection BadExpressionStatementJS +'format es6'; + +let name = 'mdToastConfig'; + +import { registerProvider } from 'nn-ng-utils'; + +import MdToastConfig from './md-toast-config'; + +const DEFAULT_HIDE_DELAY = 3000; +const DEFAULT_POSITION = 'bottom right'; +const DEFAULT_PARENT_ELEMENT_NAME = 'footer'; + +class MdToastConfigProvider { + constructor () { + //noinspection BadExpressionStatementJS + 'ngInject'; + + this.config = new MdToastConfig( + DEFAULT_HIDE_DELAY, + DEFAULT_POSITION, + DEFAULT_PARENT_ELEMENT_NAME + ); + } + + $get () { + return this.config; + } + + setPosition ( value ) { + this.config.position = value; + } + + setHideDelay ( value ) { + this.config.hideDelay = value; + } + + setParentElementName ( firstElementFoundByTagName ) { + this.config.parentElementName = firstElementFoundByTagName; + } +} + +registerProvider( name, MdToastConfigProvider ); + +export default MdToastConfigProvider; diff --git a/pool/shard005/JavaScript/0032872_about.js b/pool/shard005/JavaScript/0032872_about.js new file mode 100644 index 0000000000000000000000000000000000000000..572f375eac74d1ef0cdcbba8b4d8f9d225aa0cd4 --- /dev/null +++ b/pool/shard005/JavaScript/0032872_about.js @@ -0,0 +1,22 @@ +'use strict'; + +describe('Controller: AboutCtrl', function () { + + // load the controller's module + beforeEach(module('ffmApp')); + + var AboutCtrl, + scope; + + // Initialize the controller and a mock scope + beforeEach(inject(function ($controller, $rootScope) { + scope = $rootScope.$new(); + AboutCtrl = $controller('AboutCtrl', { + $scope: scope + }); + })); + + it('should attach a list of awesomeThings to the scope', function () { + expect(scope.awesomeThings.length).toBe(3); + }); +}); diff --git a/pool/shard005/JavaScript/0032873_NotesList.js b/pool/shard005/JavaScript/0032873_NotesList.js new file mode 100644 index 0000000000000000000000000000000000000000..2af3c8e7903f435b1e938bc8f3a5f78cf924f9d3 --- /dev/null +++ b/pool/shard005/JavaScript/0032873_NotesList.js @@ -0,0 +1,110 @@ +import React from 'react'; +import xhr from 'xhr'; +import config from '../config'; +import {Link} from 'react-router'; +import NotesListItem from './NotesListItem'; +import Loading from './Loading'; +import APIError from './APIError'; +import NoResults from './NoResults'; +import utils from '../utils'; + +var NotesList = React.createClass({ + getInitialState: function() { + return { + 'notes': [], + 'loading': true, + 'apiError': false + }; + }, + componentDidMount: function() { + this.fetchNotes(); + }, + componentWillReceiveProps: function(newProps) { + this.fetchNotes(newProps); + }, + getQueryString: function(props) { + var query = props.location.query; + var params = { + 'users': config.USERS.join(','), + 'isOpen': 'true', + 'sort': '-commented_at', + 'limit': 100 + }; + if (query.show === 'all') { + delete params.isOpen; + } + if (query.q) { + var queryComponents = utils.getQueryComponents(query.q); + params.comment = queryComponents.text; + delete queryComponents.text; + params = Object.assign({}, params, queryComponents); + if (params.users === '*') { + delete params.users; + } + } + return utils.getQueryString(params); + }, + fetchNotes: function(props) { + props = props || this.props; + var queryURL = config.API_BASE + 'notes/?'; + queryURL += this.getQueryString(props); + this.setState({ + 'loading': true, + 'notes': [] + }); + xhr.get(queryURL, (err, response) => { + if (err) { + return this.setState({ + 'apiError': err + }); + } + const statusCode = response.statusCode; + if (statusCode > 400) { + return this.setState({ + 'apiError': JSON.parse(response.body).message + }); + } + const data = JSON.parse(response.body); + const notes = data.features; + const total = data.total; + this.setState({ + 'notes': notes, + 'total': total, + 'loading': false, + 'apiError': false + }); + }); + }, + render: function() { + if (this.state.apiError) { + return ( + + ) + } + if (this.state.loading) { + return ( + + ); + } + if (this.state.notes.length === 0) { + return ( + + ); + } + let notesHTML = []; + this.state.notes.forEach(function(note) { + let elem = ( + + ); + notesHTML.push(elem); + }); + return ( +
+

Total Results: {this.state.total}

+ {notesHTML} +
+ ); + } +}); + +export default NotesList; \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032877_TestClientFramework.js b/pool/shard005/JavaScript/0032877_TestClientFramework.js new file mode 100644 index 0000000000000000000000000000000000000000..4b425296d5c241593f281ee18662d4c2d95fbe37 --- /dev/null +++ b/pool/shard005/JavaScript/0032877_TestClientFramework.js @@ -0,0 +1,142 @@ +'use strict'; + +var net = require('net'); +var CONFIG = require('./cfg/testconfig.js'); + +var Promise = require('promise'); + +var NUL = '\u0000'; +var SOH = '\u0001'; +var EOT = '\u0004'; +var ENQ = '\u0005'; + +function Clients(numClients, port, host) { + if (numClients === undefined + || (isNaN(numClients) || parseInt(Number(numClients)) !== numClients || isNaN(parseInt(numClients, 10)))) { + + numClients = 1; + } + if (!(this instanceof Clients)) { + return new Clients(numClients, port, host); + } + + this.clients = []; + this.chunks = []; + for (var i = 0; i < numClients; i++) { + this.clients[i] = new net.Socket(); + this.chunks[i] = ''; + + this.clients[i].on('error', function(error) { + console.log(error); + this.clients[i].end(); + }); + } + + if (port !== undefined) { + this.serverPort = port; + } else { + this.serverPort = CONFIG.rpcServer.port; + } + if (host !== undefined) { + this.serverHost = host; + } else { + this.serverHost = CONFIG.rpcServer.host; + } + + //this.sendRpc = this.sendRpc.bind(this); +} + + +/** + * Passes the rpc to the socket for the specified client. sets up handlers for the promise. + * Returns the promise + * + * @param client net.Socket + * @param rpc rpcString + * @returns promise {*|exports|module.exports} + */ +Clients.prototype = { + constructor: Clients, + + sendRpc: function (clientNum, rpc) { + var self = this; + self.chunks[clientNum] = ''; + + return new Promise(function (fulfill, reject) { + + function errorFunction(error) { + reject(error); + } + + function dataFunction(data) { + // clean up the 'data' and 'error' listeners for the next step through + self.clients[clientNum].removeListener('data', dataFunction); + self.clients[clientNum].removeListener('error', errorFunction); + + fulfill(receiveData(self.chunks[clientNum], data)); + } + + self.clients[clientNum].on('data', dataFunction); + self.clients[clientNum].on('error', errorFunction); + + var rpcBuffer = new Buffer(rpc, 'binary'); + self.clients[clientNum].write(rpcBuffer); + }); + }, + + startAllClients: function() { + for (var i = 0; i < this.clients.length; i++) { + this.clients[i].connect(this.serverPort, this.serverHost); + } + }, + + startClient: function(clientNum) { + this.clients[clientNum].connect(this.serverPort, this.serverHost); + }, + + setClientTest: function(clientNum, testFunction) { + this.clients[clientNum].on('connect', testFunction); + }, + + closeClient: function(clientNum) { + this.clients[clientNum].end(); + }, + + closeAllClients: function() { + for (var i = 0; i < this.clients.length; i++) { + this.clients[i].end(); + } + }, + + throwError: function (rpcName, response) { + throw new Error(rpcName + " Error: " + response); + }, + + getClient: function(clientNum) { + return this.clients[clientNum]; + } + +} + +function receiveData(chunk, data) { + chunk += data; + // find the end of a RPC packet + var eotIndex = chunk.indexOf(EOT); + + // loop for each packet in the data chunk + while (eotIndex > -1) { + var response = ''; + + // get a packet from the chunk (without the EOT) + var recievedPacket = chunk.substr(0, eotIndex + 1); + // remove the RPC packet from the chunk + chunk = chunk.substring(eotIndex + 1); + // find the end of the next RPC packet + eotIndex = chunk.indexOf(EOT); + } + + return recievedPacket; + +} + +module.exports.Clients = Clients; diff --git a/pool/shard005/JavaScript/0032882_compile.js b/pool/shard005/JavaScript/0032882_compile.js new file mode 100644 index 0000000000000000000000000000000000000000..a72350b22a44868ef5f5a025b59e8fd601cc404e --- /dev/null +++ b/pool/shard005/JavaScript/0032882_compile.js @@ -0,0 +1,40 @@ +import path from 'path'; +import compile, {compiler} from '../compile.js'; + +/** + * Provides a middleware that can compile Cap'n Proto schema files into their binary representation and return them to + * the client. + * + * Will return a `501` error if the Cap'n Proto compiler cannot be found on the server. + * @param {String} root the root location of the schema files to return + * @returns {Function} a middleware function that can handle HTTP requests + */ +export default function(root) { + return function(request, response, next) { + const {accept} = request.headers; + if (['application/x-capnp-schema-binary', 'application/*', '*/*'].indexOf(accept) === -1) { + response.writeHead(406, {'Content-Type': 'application/json'}); + response.end(JSON.stringify({error: `Invalid accepts: ${accept}`})); + return; + } + + const url = new URL(`${location.origin}${request.url}`); + compiler() + .then(executable => { + return compile(path.join(root, url.pathname), executable) + .then(schema => { + response.writeHead(200, {'Content-Type': 'application/x-capnp-schema-binary'}); + response.end(Buffer.from(schema.buffer, schema.byteOffset, schema.byteLength)); + }) + .catch(err => { + response.writeHead(500, {'Content-Type': 'application/json'}); + response.end(JSON.stringify({error: `Failed to compile schema: ${err.message}`})); + }); + }, err => { + response.writeHead(501, {'Content-Type': 'application/json'}); + response.end(JSON.stringify({error: `Failed to find compiler: ${err}`})); + }) + .then(next, next); + }; +} + diff --git a/pool/shard005/JavaScript/0032883_yql-jsonp.js b/pool/shard005/JavaScript/0032883_yql-jsonp.js new file mode 100644 index 0000000000000000000000000000000000000000..7fa647b597544d7610fb991bc09e9bee1e65253e --- /dev/null +++ b/pool/shard005/JavaScript/0032883_yql-jsonp.js @@ -0,0 +1,36 @@ +/* +YUI 3.18.1 (build f7e7bcb) +Copyright 2014 Yahoo! Inc. All rights reserved. +Licensed under the BSD License. +http://yuilibrary.com/license/ +*/ + +YUI.add('yql-jsonp', function (Y, NAME) { + +/** +* Plugin for YQL to use JSONP to make YQL requests. This is the default method, +* when loaded in nodejs or winjs this will not load. The new module is needed +* to make sure that JSONP is not loaded in the environments that it is not needed. +* @module yql +* @submodule yql-jsonp +*/ + +//Over writes Y.YQLRequest._send to use IO instead of JSONP +Y.YQLRequest.prototype._send = function (url, o) { + if (o.allowCache !== false) { + o.allowCache = true; + } + if (!this._jsonp) { + this._jsonp = Y.jsonp(url, o); + } else { + this._jsonp.url = url; + if (o.on && o.on.success) { + this._jsonp._config.on.success = o.on.success; + } + this._jsonp.send(); + } +}; + + + +}, '3.18.1', {"requires": ["yql", "jsonp", "jsonp-url"]}); diff --git a/pool/shard005/JavaScript/0032884_Message.js b/pool/shard005/JavaScript/0032884_Message.js new file mode 100644 index 0000000000000000000000000000000000000000..1d6c272f3a39a50619d9625396ae3a226065a6e5 --- /dev/null +++ b/pool/shard005/JavaScript/0032884_Message.js @@ -0,0 +1,21 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (channel, type, data) { + return { + id: _nodeUuid2.default.v4(), + when: new Date().toISOString(), + channel: channel, + type: type, + meta: data + }; +}; + +var _nodeUuid = require('node-uuid'); + +var _nodeUuid2 = _interopRequireDefault(_nodeUuid); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032887_alertModalFactory.js b/pool/shard005/JavaScript/0032887_alertModalFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..63dfbe5ceed60951248e1e5f9d58ec4b3049341c --- /dev/null +++ b/pool/shard005/JavaScript/0032887_alertModalFactory.js @@ -0,0 +1,74 @@ +/* + * 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. + */ + +(function () { + 'use strict'; + + angular + .module('refstackApp') + .factory('raiseAlert', raiseAlert); + + raiseAlert.$inject = ['$uibModal']; + + /** + * This allows alert pop-ups to be raised. Just inject it as a dependency + * in the calling controller. + */ + function raiseAlert($uibModal) { + return function(mode, title, text) { + $uibModal.open({ + templateUrl: '/shared/alerts/alertModal.html', + controller: 'RaiseAlertModalController as alert', + backdrop: true, + keyboard: true, + backdropClick: true, + size: 'md', + resolve: { + data: function () { + return { + mode: mode, + title: title, + text: text + }; + } + } + }); + }; + } + + angular + .module('refstackApp') + .controller('RaiseAlertModalController', RaiseAlertModalController); + + RaiseAlertModalController.$inject = ['$uibModalInstance', 'data']; + + /** + * This is the controller for the alert pop-up. + */ + function RaiseAlertModalController($uibModalInstance, data) { + var ctrl = this; + + ctrl.close = close; + ctrl.data = data; + + /** + * This method will close the alert modal. The modal will close + * when the user clicks the close button or clicks outside of the + * modal. + */ + function close() { + $uibModalInstance.close(); + } + } +})(); diff --git a/pool/shard005/JavaScript/0032889_APIHandler.js b/pool/shard005/JavaScript/0032889_APIHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..cac8c15c51b578fd50078db3daf5607d97d61ec6 --- /dev/null +++ b/pool/shard005/JavaScript/0032889_APIHandler.js @@ -0,0 +1,195 @@ +/** + * The API Handler handles all API http requests + */ + +/* + * 2011 Peter 'Pita' Martischka (Primary Technology Ltd) + * + * 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. + */ + +var absolutePaths = require('../utils/AbsolutePaths'); +var fs = require("fs"); +var api = require("../db/API"); +var log4js = require('log4js'); +var padManager = require("../db/PadManager"); +var randomString = require("../utils/randomstring"); +var argv = require('../utils/Cli').argv; +var createHTTPError = require('http-errors'); + +var apiHandlerLogger = log4js.getLogger('APIHandler'); + +//ensure we have an apikey +var apikey = null; +var apikeyFilename = absolutePaths.makeAbsolute(argv.apikey || "./APIKEY.txt"); + +try { + apikey = fs.readFileSync(apikeyFilename,"utf8"); + apiHandlerLogger.info(`Api key file read from: "${apikeyFilename}"`); +} catch(e) { + apiHandlerLogger.info(`Api key file "${apikeyFilename}" not found. Creating with random contents.`); + apikey = randomString(32); + fs.writeFileSync(apikeyFilename,apikey,"utf8"); +} + +// a list of all functions +var version = {}; + +version["1"] = Object.assign({}, + { "createGroup" : [] + , "createGroupIfNotExistsFor" : ["groupMapper"] + , "deleteGroup" : ["groupID"] + , "listPads" : ["groupID"] + , "createPad" : ["padID", "text"] + , "createGroupPad" : ["groupID", "padName", "text"] + , "createAuthor" : ["name"] + , "createAuthorIfNotExistsFor": ["authorMapper" , "name"] + , "listPadsOfAuthor" : ["authorID"] + , "createSession" : ["groupID", "authorID", "validUntil"] + , "deleteSession" : ["sessionID"] + , "getSessionInfo" : ["sessionID"] + , "listSessionsOfGroup" : ["groupID"] + , "listSessionsOfAuthor" : ["authorID"] + , "getText" : ["padID", "rev"] + , "setText" : ["padID", "text"] + , "getHTML" : ["padID", "rev"] + , "setHTML" : ["padID", "html"] + , "getRevisionsCount" : ["padID"] + , "getLastEdited" : ["padID"] + , "deletePad" : ["padID"] + , "getReadOnlyID" : ["padID"] + , "setPublicStatus" : ["padID", "publicStatus"] + , "getPublicStatus" : ["padID"] + , "setPassword" : ["padID", "password"] + , "isPasswordProtected" : ["padID"] + , "listAuthorsOfPad" : ["padID"] + , "padUsersCount" : ["padID"] + } +); + +version["1.1"] = Object.assign({}, version["1"], + { "getAuthorName" : ["authorID"] + , "padUsers" : ["padID"] + , "sendClientsMessage" : ["padID", "msg"] + , "listAllGroups" : [] + } +); + +version["1.2"] = Object.assign({}, version["1.1"], + { "checkToken" : [] + } +); + +version["1.2.1"] = Object.assign({}, version["1.2"], + { "listAllPads" : [] + } +); + +version["1.2.7"] = Object.assign({}, version["1.2.1"], + { "createDiffHTML" : ["padID", "startRev", "endRev"] + , "getChatHistory" : ["padID", "start", "end"] + , "getChatHead" : ["padID"] + } +); + +version["1.2.8"] = Object.assign({}, version["1.2.7"], + { "getAttributePool" : ["padID"] + , "getRevisionChangeset" : ["padID", "rev"] + } +); + +version["1.2.9"] = Object.assign({}, version["1.2.8"], + { "copyPad" : ["sourceID", "destinationID", "force"] + , "movePad" : ["sourceID", "destinationID", "force"] + } +); + +version["1.2.10"] = Object.assign({}, version["1.2.9"], + { "getPadID" : ["roID"] + } +); + +version["1.2.11"] = Object.assign({}, version["1.2.10"], + { "getSavedRevisionsCount" : ["padID"] + , "listSavedRevisions" : ["padID"] + , "saveRevision" : ["padID", "rev"] + , "restoreRevision" : ["padID", "rev"] + } +); + +version["1.2.12"] = Object.assign({}, version["1.2.11"], + { "appendChatMessage" : ["padID", "text", "authorID", "time"] + } +); + +version["1.2.13"] = Object.assign({}, version["1.2.12"], + { "appendText" : ["padID", "text"] + } +); + +version["1.2.14"] = Object.assign({}, version["1.2.13"], + { "getStats" : [] + } +); + +// set the latest available API version here +exports.latestApiVersion = '1.2.14'; + +// exports the versions so it can be used by the new Swagger endpoint +exports.version = version; + +/** + * Handles a HTTP API call + * @param functionName the name of the called function + * @param fields the params of the called function + * @req express request object + * @res express response object + */ +exports.handle = async function(apiVersion, functionName, fields, req, res) +{ + // say goodbye if this is an unknown API version + if (!(apiVersion in version)) { + throw new createHTTPError.NotFound('no such api version'); + } + + // say goodbye if this is an unknown function + if (!(functionName in version[apiVersion])) { + throw new createHTTPError.NotFound('no such function'); + } + + // check the api key! + fields["apikey"] = fields["apikey"] || fields["api_key"]; + + if (fields["apikey"] !== apikey.trim()) { + throw new createHTTPError.Unauthorized('no or wrong API Key'); + } + + // sanitize any padIDs before continuing + if (fields["padID"]) { + fields["padID"] = await padManager.sanitizePadId(fields["padID"]); + } + // there was an 'else' here before - removed it to ensure + // that this sanitize step can't be circumvented by forcing + // the first branch to be taken + if (fields["padName"]) { + fields["padName"] = await padManager.sanitizePadId(fields["padName"]); + } + + // put the function parameters in an array + var functionParams = version[apiVersion][functionName].map(function (field) { + return fields[field] + }); + + // call the api function + return api[functionName].apply(this, functionParams); +} diff --git a/pool/shard005/JavaScript/0032892_categoriesIndex.component.spec.js b/pool/shard005/JavaScript/0032892_categoriesIndex.component.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..5ceba5c68946ec0c6d6b05a3a45f887fd6b3f18b --- /dev/null +++ b/pool/shard005/JavaScript/0032892_categoriesIndex.component.spec.js @@ -0,0 +1,21 @@ +'use strict'; + +describe('Controller: CategoriesIndexComponent', function() { + // load the controller's module + beforeEach(module('paizaqaApp')); + + var CategoriesIndexComponent, scope; + + // Initialize the controller and a mock scope + beforeEach(inject(function($componentController, $rootScope) { + scope = $rootScope.$new(); + CategoriesIndexComponent = $componentController('CategoriesIndexComponent', { + $scope: scope, + query: {}, + }); + })); + + it('should ...', function() { + expect(1).toEqual(1); + }); +}); diff --git a/pool/shard005/JavaScript/0032893_session.js b/pool/shard005/JavaScript/0032893_session.js new file mode 100644 index 0000000000000000000000000000000000000000..4585a070a5dda7f7fd7c55c704089a6361fa4e55 --- /dev/null +++ b/pool/shard005/JavaScript/0032893_session.js @@ -0,0 +1,133 @@ +dump('entering auth/session.js\n'); +// vim:sw=4:ts=4:noet: + +if (typeof auth == 'undefined') auth = {}; +auth.session = function (view,login_type) { + + JSAN.use('util.error'); this.error = new util.error(); + JSAN.use('util.network'); this.network = new util.network(); + this.view = view; + this.login_type = login_type || 'staff'; + + return this; +}; + +auth.session.prototype = { + + 'init' : function () { + + var obj = this; + + try { + var init = this.network.request( + api.AUTH_INIT.app, + api.AUTH_INIT.method, + [ this.view.name_prompt.value ] + ); + + if (init) { + if (xulG._data) { delete xulG._data; } // quick kludge; we were re-using a poisoned OpenILS.data (from ws_info.xul?) where js2JSON (and maybe other stuff) does not exist + JSAN.use('OpenILS.data'); var data = new OpenILS.data(); data.stash_retrieve(); + + var params = { + 'username' : this.view.name_prompt.value, + 'password' : hex_md5( + init + + hex_md5( + this.view.password_prompt.value + ) + ), + 'type' : 'temp', + }; + + if (data.ws_info[ this.view.server_prompt.value ]) { + params.type = this.login_type; + params.workstation = data.ws_info[ this.view.server_prompt.value ].name; + data.ws_name = params.workstation; data.stash('ws_name'); + } + + var robj = this.network.simple_request( 'AUTH_COMPLETE', [ params ]); + + switch (Number(robj.ilsevent)) { + case 0: + this.key = robj.payload.authtoken; + this.authtime = robj.payload.authtime; + break; + case 1520 /* WORKSTATION_NOT_FOUND */: + alert(document.getElementById('authStrings').getFormattedString('staff.auth.session.unregistered', [params.workstation])); + delete(params.workstation); + delete(data.ws_info[ this.view.server_prompt.value ]); + data.stash('ws_info'); + data.ws_name = null; data.stash('ws_name'); + params.type = 'temp'; + robj = this.network.simple_request('AUTH_COMPLETE',[ params ]); + if (robj.ilsevent == 0) { + this.key = robj.payload.authtoken; + this.authtime = robj.payload.authtime; + } else { + //this.error.standard_unexpected_error_alert('auth.session.init',robj); + throw(robj); + } + break; + default: + //obj.error.standard_unexpected_error_alert('auth.session.init',robj); + throw(robj); + break; + } + + this.error.sdump('D_AUTH','auth.session.key = ' + this.key + '\n'); + + if (typeof this.on_init == 'function') { + this.error.sdump('D_AUTH','auth.session.on_init()\n'); + this.on_init(); + } + + } else { + + var error = document.getElementById('authStrings').getString('staff.auth.session.init_false') + '\n'; + this.error.sdump('D_ERROR',error); + throw(error); + } + + } catch(E) { + alert(document.getElementById('authStrings').getString('staff.auth.session.login_failed')); + //obj.error.standard_unexpected_error_alert('Error on auth.session.init()',E); + + if (typeof this.on_init_error == 'function') { + this.error.sdump('D_AUTH','auth.session.on_init_error()\n'); + this.on_init_error(E); + } + if (typeof this.on_error == 'function') { + this.error.sdump('D_AUTH','auth.session.on_error()\n'); + this.on_error(); + } + + //throw(E); + /* This was for testing + if (typeof this.on_init == 'function') { + this.error.sdump('D_AUTH','auth.session.on_init() despite error\n'); + this.on_init(); + } + */ + } + }, + + 'close' : function () { + var obj = this; + obj.error.sdump('D_AUTH','auth.session.close()\n'); + if (obj.key) obj.network.request( + api.AUTH_DELETE.app, + api.AUTH_DELETE.method, + [ obj.key ], + function(req) {} + ); + obj.key = null; + if (typeof obj.on_close == 'function') { + obj.error.sdump('D_AUTH','auth.session.on_close()\n'); + obj.on_close(); + } + } + +} + +dump('exiting auth/session.js\n'); diff --git a/pool/shard005/JavaScript/0032894_data.js b/pool/shard005/JavaScript/0032894_data.js new file mode 100644 index 0000000000000000000000000000000000000000..f3720ea0280970c20cbedb07104d7aefdc5585e2 --- /dev/null +++ b/pool/shard005/JavaScript/0032894_data.js @@ -0,0 +1,127 @@ +/** + * [getTimeSeries description] + * @param {[type]} state [description] + * @param {[type]} start [description] + * @param {[type]} end [description] + * @return {[type]} [description] + */ +function getTimeSeries(state, start, end) { + let statistics = {}; + let stat_keys = stats; + for (el in stat_keys) { + statistics[stat_keys[el]] = []; + } + + for (var i = start; i <= end; i++) { + statistics["population"].push({"year":i, "population":state.population[i]}); + statistics["median_age"].push({"year":i, "median_age":state.median_age[i]}); + statistics["median_income"].push({"year":i, "median_income":state.median_income[i]}); + statistics["high_school_graduation"].push({"year":i, "high_school_graduation":state.high_school_graduation[i]}); + statistics["some_college"].push({"year":i, "some_college":state.some_college[i]}); + statistics["unemployment"].push({"year":i, "unemployment":state.unemployment[i]}); + + } + return statistics; +} +/** + * @mimlowe [createRingChart description] + * @param {[type]} data [description] + * @param {[type]} targetDiv [description] + * @return {[type]} [description] + */ + +function createRingChart(data,data2, key, targetDiv, size) { + var width = size, height = size-15, radius = Math.min(width, height) / 2; + + //var theCSV = "age,population\n<5,2704659\n5-13,4499890\n14-17,2159981\n18-24,3853788\n25-44,14106543\n45-64,8819342\n≥65,612463"; + var color = d3.scaleOrdinal().range(["#98abc5", "#a7a7a7", "#794e67", "#a7a7a7",]); + var arc = d3.arc().outerRadius(radius - 6).innerRadius(radius - 30); + var pie = d3.pie().sort(null).value(function(d) { return d["edu_level"]; }); + var svg = d3.select(targetDiv).append("svg") + .attr("width", width) + .attr("height", height) + .append("g") + .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); + + var div = d3.select("body").append("div") + .attr("class", "tooltip") + .style("opacity", 0); + + var g = svg.selectAll("arc").data(pie(data)).enter().append("g").attr("class", "arc").on("mouseover", function(d) { + div.transition() + .duration(200) + .style("opacity", .9); + div.html(d.data["edu_level"]) + .style("left", (d3.event.pageX) + "px") + .style("top", (d3.event.pageY) + "px"); + }) + .on("mouseout", function(d) { + div.transition() + .duration(500) + .style("opacity", 0); + });; + g.append("path").attr("d", arc).style("fill", function(d) { return color(d.data.edu_level); + }); + + var width2 = size-100, height2 = size-115, radius2 = Math.min(width2, height2) / 2; + + //var theCSV = "age,population\n<5,2704659\n5-13,4499890\n14-17,2159981\n18-24,3853788\n25-44,14106543\n45-64,8819342\n≥65,612463"; + var arc2 = d3.arc().outerRadius(radius2 - 6).innerRadius(radius2 - 30); + var pie2 = d3.pie().sort(null).value(function(d) { return d["edu_level"]; }); + + + var div2 = d3.select("body").append("div") + .attr("class", "tooltip") + .style("opacity", 0); + + var g2 = svg.selectAll("arc").data(pie(data2)).enter().append("g").attr("class", "arc").on("mouseover", function(d) { + div2.transition() + .duration(200) + .style("opacity", .9); + div2.html(d.data["edu_level"]) + .style("left", (d3.event.pageX) + "px") + .style("top", (d3.event.pageY) + "px"); + }) + .on("mouseout", function(d) { + div2.transition() + .duration(500) + .style("opacity", 0); + });; + g2.append("path").attr("d", arc2).style("fill", function(d) { return color(d.data.edu_level); + + }); + + /** + * [type description] + * @param {[type]} d [description] + * @return {[type]} [description] + */ + function type(d) { + // could this be rewritten as d.population += d.population? + d.population = +d.population; + return d; + } +} + +/** +* @mimlowe [createTimeSeries description] +* @param {[type]} data [state data set ex: data["median_age"]] +* @param {[type]} key [data set key as string ex: "median_age"] +* @param {[type]} targetDiv [div that the graph will be drawn in] +* @param {[type]} chartType [dimple.js chart type ex: dimple.plot.line, dimple.plot.bubble] +*/ +function createTimeSeries(data, key, targetDiv, chartType, w, h) { + var svg = dimple.newSvg(targetDiv, w, h); + var myChart = new dimple.chart(svg, data); + myChart.setBounds(70, 30, w-100, h-50); + var x = myChart.addCategoryAxis("x", "year") + x.showGridlines = true; + x.addOrderRule("year"); + var y = myChart.addCategoryAxis("y", key); + var s = myChart.addSeries(null,chartType); + s.lineWeight = 4; + s.lineMarkers = true; + myChart.draw(800); + y.titleShape.remove(); + x.titleShape.remove(); +} diff --git a/pool/shard005/JavaScript/0032897_ContextMenu.test.js b/pool/shard005/JavaScript/0032897_ContextMenu.test.js new file mode 100644 index 0000000000000000000000000000000000000000..3ffd7a15c6556b5487a5a62a53c18b6ba83a7cb9 --- /dev/null +++ b/pool/shard005/JavaScript/0032897_ContextMenu.test.js @@ -0,0 +1,197 @@ +import React from 'react'; +import { mount } from 'enzyme'; + +import ContextMenu from '../src/ContextMenu'; +import { showMenu, hideMenu } from '../src/actions'; + +describe('ContextMenu tests', () => { + test('shows when event with correct "id" is triggered', () => { + const ID = 'CORRECT_ID'; + const x = 50; + const y = 50; + const component = mount(); + + expect(component).toMatchSnapshot(); + expect(component.state()).toEqual({ + isVisible: false, + x: 0, + y: 0, + forceSubMenuOpen: false, + selectedItem: null + }); + showMenu({ position: { x, y }, id: ID }); + component.update(); + expect(component.state()).toEqual({ + isVisible: true, + x, + y, + forceSubMenuOpen: false, + selectedItem: null + }); + expect(component.find('.react-contextmenu--visible').length).toBe(1); + expect(component).toMatchSnapshot(); + component.unmount(); + }); + + test('does not shows when event with incorrect "id" is triggered', () => { + const ID = 'CORRECT_ID'; + const x = 50; + const y = 50; + const component = mount(); + + expect(component).toMatchSnapshot(); + expect(component.state()).toEqual({ + isVisible: false, + x: 0, + y: 0, + forceSubMenuOpen: false, + selectedItem: null + }); + showMenu({ position: { x, y }, id: 'ID' }); + component.update(); + expect(component.state()).toEqual({ + isVisible: false, + x: 0, + y: 0, + forceSubMenuOpen: false, + selectedItem: null + }); + expect(component.find('.react-contextmenu--visible').length).toBe(0); + expect(component).toMatchSnapshot(); + component.unmount(); + }); + + test('onShow and onHide are triggered correctly', () => { + const data = { position: { x: 50, y: 50 }, id: 'CORRECT_ID' }; + const onShow = jest.fn(); + const onHide = jest.fn(); + const component = mount(); + + hideMenu(); + showMenu(data); + expect(component.state()).toEqual( + Object.assign( + { isVisible: true, forceSubMenuOpen: false, selectedItem: null }, + data.position + ) + ); + expect(onShow).toHaveBeenCalled(); + showMenu(data); + expect(onShow).toHaveBeenCalledTimes(1); + expect(onHide).not.toHaveBeenCalled(); + hideMenu(); + expect(component.state()).toEqual( + Object.assign( + { isVisible: false, forceSubMenuOpen: false, selectedItem: null }, + data.position + ) + ); + expect(onShow).toHaveBeenCalledTimes(1); + expect(onHide).toHaveBeenCalledTimes(1); + component.unmount(); + }); + + test('menu should close on "Escape"', () => { + const data = { position: { x: 50, y: 50 }, id: 'CORRECT_ID' }; + const onHide = jest.fn(); + const component = mount(); + const escape = new window.KeyboardEvent('keydown', { keyCode: 27 }); + + showMenu(data); + expect(component.state()).toEqual( + Object.assign( + { isVisible: true, forceSubMenuOpen: false, selectedItem: null }, + data.position + ) + ); + document.dispatchEvent(escape); + expect(component.state()).toEqual( + Object.assign( + { isVisible: false, forceSubMenuOpen: false, selectedItem: null }, + data.position + ) + ); + expect(onHide).toHaveBeenCalled(); + component.unmount(); + }); + + test('menu should close on "Enter" when selectedItem is null', () => { + const data = { position: { x: 50, y: 50 }, id: 'CORRECT_ID' }; + const onHide = jest.fn(); + const component = mount(); + const enter = new window.KeyboardEvent('keydown', { keyCode: 13 }); + + showMenu(data); + expect(component.state()).toEqual( + Object.assign( + { isVisible: true, forceSubMenuOpen: false, selectedItem: null }, + data.position + ) + ); + document.dispatchEvent(enter); + expect(component.state()).toEqual( + Object.assign( + { isVisible: false, forceSubMenuOpen: false, selectedItem: null }, + data.position + ) + ); + expect(onHide).toHaveBeenCalled(); + component.unmount(); + }); + + test('menu should close on "outside" click', () => { + const data = { position: { x: 50, y: 50 }, id: 'CORRECT_ID' }; + const onHide = jest.fn(); + const component = mount(); + const outsideClick = new window.MouseEvent('mousedown', { target: document }); + + showMenu(data); + expect(component.state()).toEqual( + Object.assign( + { isVisible: true, forceSubMenuOpen: false, selectedItem: null }, + data.position + ) + ); + component.simulate('mousedown'); + expect(component.state()).toEqual( + Object.assign( + { isVisible: true, forceSubMenuOpen: false, selectedItem: null }, + data.position + ) + ); + document.dispatchEvent(outsideClick); + expect(component.state()).toEqual( + Object.assign( + { isVisible: false, forceSubMenuOpen: false, selectedItem: null }, + data.position + ) + ); + expect(onHide).toHaveBeenCalled(); + component.unmount(); + }); + + test('hideOnLeave and onMouseLeave options', () => { + const data = { position: { x: 50, y: 50 }, id: 'CORRECT_ID' }; + const onMouseLeave = jest.fn(); + const component = mount( + + ); + + showMenu(data); + expect(component.state()).toEqual( + Object.assign( + { isVisible: true, forceSubMenuOpen: false, selectedItem: null }, + data.position + ) + ); + component.simulate('mouseleave'); + expect(component.state()).toEqual( + Object.assign( + { isVisible: false, forceSubMenuOpen: false, selectedItem: null }, + data.position + ) + ); + expect(onMouseLeave).toHaveBeenCalled(); + component.unmount(); + }); +}); diff --git a/pool/shard005/JavaScript/0032902_ajax-scripts.js b/pool/shard005/JavaScript/0032902_ajax-scripts.js new file mode 100644 index 0000000000000000000000000000000000000000..631b6f881afc83c413231d7d2522ccacffea3c24 --- /dev/null +++ b/pool/shard005/JavaScript/0032902_ajax-scripts.js @@ -0,0 +1,145 @@ +/* + * Ajax scripts + */ + +function WsvRedirectPostType(pType) { + var listUrl = $("input[name=wsv_redirect_post_type_url]").val(); + window.location.href = listUrl+'&posttype='+pType; +} + + +function getPostId(pid) { + var pidArr = pid.split("_"); + var postId = pidArr[pidArr.length-1]; + + /* ================= Voing action ================= */ + if (postId) { + jQuery.ajax({ + type: 'post', + url: myAjax.ajaxurl, + dataType: 'json', + data: { + action: 'do_post_vote', + post_id: postId + }, + beforeSend: function() { + var loadHtml = ''; + loadHtml += ''; + loadHtml += ''; + + $("#voting_area_outer_"+postId).html(loadHtml); + }, + success: function(data, textStatus, XMLHttpRequest) { + var afterLoadText = ''; + + if (data.status == "s") { + afterLoadText = 'Voted'; + $("#vote-count-"+postId).html(data.total_votes); + } else { + afterLoadText = 'Error'; + } + + //var afterLoadHtml = ''+afterLoadText+''; + var afterLoadHtml = ''; + $("#voting_area_outer_"+postId).html(afterLoadHtml); + + /*if (data == "s") { + if ($("#vote-count-"+postId).length > 0) { + $("#vote-count-"+postId).html(voteCount); + } + }*/ + }, + error: function (MLHttpRequest, textStatus, errorThrown) { + alert('ERROR - '+errorThrown); + } + }) + } + +} + + +jQuery(function() { + jQuery(".wsv-reset-button-single").live("click", function() { + if (confirm("Are you sure want to reset votes for this post?")) { + var postIdArr = jQuery(this).attr("id"); + postIdArr = postIdArr.split("_"); + var postId = postIdArr[postIdArr.length-1]; + + if (postId) { + jQuery.ajax({ + type: 'post', + url: myAjax.ajaxurl, + dataType: 'json', + data: { + action: 'do_reset_vote_single', + post_id: postId + }, + beforeSend: function() { + var loadHtml = ''; + //loadHtml += ''; + loadHtml += ''; + loadHtml += ''; + + jQuery("#reset-area-outer-"+postId).html(loadHtml); + }, + success: function(data, textStatus, XMLHttpRequest) { + var afterLoadText = ''; + if (data == "s") { + afterLoadText = 'Voting has been reset'; + jQuery("#reset-area-outer-"+postId).html(afterLoadText); + setTimeout(function() { + window.location.href = window.location.href; + }, 2000); + } else { + jQuery("#reset-area-outer-"+postId).html(afterLoadText); + afterLoadText = 'Error'; + } + }, + error: function (MLHttpRequest, textStatus, errorThrown) { + alert('ERROR - '+errorThrown); + } + }) + } + } + }) + + jQuery(".wsv-reset-button-all").live("click", function() { + if (confirm("Are you sure want to reset votes for all post?")) { + jQuery.ajax({ + type: 'post', + url: myAjax.ajaxurl, + dataType: 'json', + data: { + action: 'do_reset_vote_all', + called_reset: '1' + }, + beforeSend: function() { + var loadHtml = ''; + //loadHtml += ''; + loadHtml += ''; + loadHtml += ''; + + jQuery("#reset-area-outer-all").html(loadHtml); + }, + success: function(data, textStatus, XMLHttpRequest) { + var afterLoadText = ''; + if (data == "s") { + afterLoadText = 'All votes has been reset'; + jQuery("#reset-area-outer-all").html(afterLoadText); + setTimeout(function() { + window.location.href = window.location.href; + }, 2000); + } else { + jQuery("#reset-area-outer-all").html(afterLoadText); + afterLoadText = 'Error'; + } + }, + error: function (MLHttpRequest, textStatus, errorThrown) { + alert('ERROR - '+errorThrown); + } + }) + } + }) + +}); + diff --git a/pool/shard005/JavaScript/0032903_index.js b/pool/shard005/JavaScript/0032903_index.js new file mode 100644 index 0000000000000000000000000000000000000000..568e4ca9e74374bb30a1fe888e7df610e9cf6776 --- /dev/null +++ b/pool/shard005/JavaScript/0032903_index.js @@ -0,0 +1,24 @@ +/* global fis */ + +/** + * fis.baidu.com + */ + +module.exports = function (content, file, options) { + var reg = /\b__id\s*\(\s*("(?:[^\\"\r\n\f]|\\[\s\S])*"|'(?:[^\\'\n\r\f]|\\[\s\S])*')\s*\)/g; + return content.replace(reg, function (all, $1) { + var info = fis.util.stringQuote($1); + var result = fis.uri(info.rest, file.dirname); + if (result.file) { + if (options.withQuote) { + return info.quote + result.file.getId() + info.quote; + } + return result.file.getId(); + } + return all; + }); +}; + +module.exports.defaultOptions = { + withQuote: true +}; diff --git a/pool/shard005/JavaScript/0032904_main-routes.js b/pool/shard005/JavaScript/0032904_main-routes.js new file mode 100644 index 0000000000000000000000000000000000000000..02dd17955141cc326be20e04357fdcbc62315ad0 --- /dev/null +++ b/pool/shard005/JavaScript/0032904_main-routes.js @@ -0,0 +1,23 @@ +// Dependencies +import express from 'express'; +import React from 'react'; +import ReactDOMServer from 'react-dom/server'; + +// Components +import Home from '../src/pages/home'; + +const router = express.Router(); + +// Home route +router.get('/', (req, res) => { + let html = ReactDOMServer.renderToString(); + res.end('' + html); +}); + +// Name route +router.get('/:name', (req, res) => { + let html = ReactDOMServer.renderToString(); + res.end('' + html); +}); + +export default router; diff --git a/pool/shard005/JavaScript/0032905_events.spec.js b/pool/shard005/JavaScript/0032905_events.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..d1068217ff006ed05f6def0e07a76a8128511f08 --- /dev/null +++ b/pool/shard005/JavaScript/0032905_events.spec.js @@ -0,0 +1,46 @@ +import { createStore } from '../src'; +import * as Reducers from './helpers/reducers/counter'; + +describe('store events', () => { + it('triggers state:changed after every dispatch', () => { + const store = createStore({ + count: 0 + }); + + let callback = jest.fn(); + + store.getStore().on('state:changed', callback); + + return store.dispatch(Reducers.incrementCounter) + .then(() => + expect(callback).toHaveBeenCalled() + ); + }); + + it('listens and responds to events in reducers', () => { + const store = createStore({ + count: 0 + }); + + const incrementCallback = jest.fn(); + const decrementCallback = jest.fn(); + const resetCallback = jest.fn(); + + store.getStore().on('count:incremented', incrementCallback); + store.getStore().on('count:reset', resetCallback); + store.getStore().on('count:decremented', decrementCallback); + + return store.dispatch(Reducers.incrementCounterWithEvent) + .then(() => { + expect(incrementCallback).toHaveBeenCalled() + }) + .then(store.dispatch(Reducers.resetCounterWithEvent)) + .then(() => { + expect(resetCallback).toHaveBeenCalled(); + }) + .then(store.dispatch(Reducers.decrementCounterWithEvent)) + .then(() => { + expect(decrementCallback).toHaveBeenCalled(); + }); + }); +}); diff --git a/pool/shard005/JavaScript/0032908_Meeting.js b/pool/shard005/JavaScript/0032908_Meeting.js new file mode 100644 index 0000000000000000000000000000000000000000..31bd0a17178e0bbf3ac875a4d3f180b51c553db7 --- /dev/null +++ b/pool/shard005/JavaScript/0032908_Meeting.js @@ -0,0 +1,229 @@ +var meetingCode = ""; + +function goBackToStartScreen() { + window.location = './index.html'; +} +function goToGradeScreen() { + //window.location = './GradeMeeting.html'; +} +/* +Funkcja umo¿liwia szybsze i bardziej intuicyjne wpisywanie kodu. Przyjmuj¹c w argumencie 2 elementy: Ÿród³owy i docelowy, +zaznacza docelowy jako aktywny po wpisaniu jednego znaku w elemencie Ÿród³owym. +*/ +function autotab(current, to) { + if (current.getAttribute && + current.value.length == "1") { + to.focus() + } +} + +/** + * Funkcja odpowiedzialna za zalogowanie na spotkanie. Do serwera wysyłane jest zapytanie, czy spotkanie o danym kodzie + * jest zarejestrowane w bazie danych. W zależności od tego, czy wpisano kod spotkania, czy kod admina, użytkownik przenoszony + * jest odpowiednio do panelu głosowania lub do panelu prowadzącego spotkanie. + */ +$("#codeReadyButton").bind("click", + +function LoginToMeeting() { + + meetingCode = $("#code_1").val(); + meetingCode = meetingCode + $("#code_2").val(); + meetingCode = meetingCode + $("#code_3").val(); + meetingCode = meetingCode + $("#code_4").val(); + meetingCode = meetingCode + $("#code_5").val(); + meetingCode = meetingCode.toUpperCase(); + + //inserting into session html memory + + + // Having adminCode in response is insecure (!) + $.ajax({ + type: "GET", + url: "http://antivps.pl:3033/meeting/" + meetingCode, + success: function (data){ + if("_id" in data) { + + + + if (typeof (Storage) != "undefined") { + + localStorage.setItem("meetingCode", data.meetingCode); + + localStorage.setItem("meetingCodeControl", data.adminCode); + localStorage.setItem("meetingTitle", data.title); + } + + if(meetingCode === data.meetingCode) { + if(!("start" in data)) { + alert("The meeting hasn't been started yet."); + } + else if("end" in data) { + alert("The meeting has been finished."); + } + else { + alert("Welcome on the meeting."); + window.location = './GradeMeeting.html'; + } + } + else if(meetingCode === data.adminCode) { + if (typeof (Storage) != "undefined") { + var dateTmp; + + if("end" in data) { + localStorage.setItem("started", "2"); + dateTmp = new Date(data.end); + localStorage.setItem("endTime", dateTmp.getTime().toString()); + + dateTmp = new Date(data.start); + localStorage.setItem("startTime", dateTmp.getTime().toString()); + } + else if("start" in data) { + localStorage.setItem("started", "1"); + dateTmp = new Date(data.start); + localStorage.setItem("startTime", dateTmp.getTime().toString()); + } + else { + localStorage.setItem("started", "0"); + //clearing localStorage options for watcher + localStorage.removeItem("startingTime"); + localStorage.removeItem("timeToAdd"); + } + + } + window.location = './Charts.html'; + } + + + + + } + else { + alert("There's no meeting with code: " + meetingCode); + } + }, + error: function (jqXHR, textStatus, errorThrown) { + if (jqXHR.status === 0) { + alert("Verify network."); + } else if (jqXHR.status == 404) { + alert("Requested page not found."); + } else if (jqXHR.status == 500) { + alert("Internal Server Error."); + } else if (textStatus === "timeout") { + alert("Time out error."); + } else { + alert("Uncaught Error.\n" + jqXHR.responseText); + } + + + } + }); + +}); + + + +////////////////////////////// +////Grade meeting area//////// +////////////////////////////// + +function ShowVoteModal() { + + $('#ThanksForVoteModal').modal('toggle'); + + +} + + + +/** + * Funkcja odpowiedzialna za wysłanie głosu na serwer. + */ +function SendVote(vote) { + + var gradeName = $(vote).attr("id"); + var grade = gradeName.substr(9, gradeName.length); + var timeOfVote; + + var minutes = 5; + var milliseconds = minutes * 60 * 1000; + + var diff; + + + + //retriving meetingCode from session memoty + if (typeof (Storage) != "undefined") { + meetingCode = localStorage.getItem("meetingCode"); + + if (localStorage.getItem("voteTime") != null) { + timeOfVote = new Date(localStorage.getItem("voteTime")); + diff = (new Date()).getTime() - timeOfVote.getTime(); + } + else { + timeOfVote = new Date(); + diff = 300001; + } + } + else { + meetingCode = "dupa"; + timeOfVote = new Date(); + } + + + + if (diff > milliseconds) { + if (typeof (Storage) != "undefined") { + localStorage.removeItem("voteTime"); + localStorage.setItem("voteTime", (new Date()).toString()); + } + + var mac = "23-23-23-23-23-23"; + + $.ajax({ + type: "POST", + url: "http://antivps.pl:3033/vote", + data: { + "voteTime" : (new Date()), + "meetingCode": meetingCode, + "value": grade + }, + processData: true, + success: function (message) { + if ("errors" in message) { + alert(message.errors); + } + else { + alert(message.message); + } + + + }, + error: function (jqXHR, textStatus, errorThrown) { + if (jqXHR.status === 0) { + alert("Verify network."); + } else if (jqXHR.status == 404) { + alert("Requested page not found."); + } else if (jqXHR.status == 500) { + alert("Internal Server Error."); + } else if (textStatus === "timeout") { + alert("Time out error."); + } else { + alert("Uncaught Error.\n" + jqXHR.responseText); + } + } + }); + } + else { + alert("You can't vote for this meeting yet.\nYou can add new vote after " + ((milliseconds-diff)/1000) + " s"); + + } + + + + //ShowVoteModal(); +}; + +function initControlPanel() { + + +} \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032911_admin_new.js b/pool/shard005/JavaScript/0032911_admin_new.js new file mode 100644 index 0000000000000000000000000000000000000000..34714c05da8cbc44a6351247727dfc7e43cd9ed7 --- /dev/null +++ b/pool/shard005/JavaScript/0032911_admin_new.js @@ -0,0 +1,69 @@ +// Javascript functions for event-list admin_new page + +// Date helpers +jQuery(document).ready(function($) { + // Read required config data from hidden field json_for_js + var json = $("#json_for_js").val(); + var conf = eval('(' + json + ')'); + + // Show or hide end_date + if ($("#start_date").val() == $("#end_date").val()) { + $("#end_date_area").hide(); + } + else { + $("#multiday").attr('checked', true); + } + + // Datepickers + $("#start_date").datepicker( { + dateFormat: conf.el_date_format, + firstDay: 1, + changeMonth: true, + changeYear: true, + numberOfMonths: 3, + showOn: "both", + buttonImage: conf.el_url + "admin/images/calendar-icon.png", + buttonImageOnly: true, + constrainInput: true, + altField: "#sql_start_date", + altFormat: "yy-mm-dd", + onClose: function(selectedDate) { + // set minDate for end_date picker + minDate = $.datepicker.parseDate( conf.el_date_format, selectedDate ); + minDate.setDate(minDate.getDate()+1); + $("#end_date").datepicker("option", "minDate", minDate); + } + }); + $("#end_date").datepicker( { + dateFormat: conf.el_date_format, + firstDay: 1, + changeMonth: true, + changeYear: true, + numberOfMonths: 3, + showOn: "both", + buttonImage: conf.el_url + "admin/images/calendar-icon.png", + buttonImageOnly: true, + constrainInput: true, + altField: "#sql_end_date", + altFormat: "yy-mm-dd" + }); + + // Toogle end_date visibility and insert the correct date + $("#multiday").click(function() { + var enddate = $("#start_date").datepicker("getDate"); + if (this.checked) { + timestamp = enddate.getTime() + 1*24*60*60*1000; + enddate.setTime(timestamp); + $("#end_date_area").fadeIn(); + $("#end_date").datepicker("option", "minDate", enddate); + } + else { + $("#end_date_area").fadeOut(); + } + $("#end_date").datepicker("setDate", enddate); + }); + + // Initialize Dates + $("#start_date").datepicker("setDate", $.datepicker.parseDate('yy-mm-dd', $("#start_date").val())); + $("#end_date").datepicker("setDate", $.datepicker.parseDate('yy-mm-dd', $("#end_date").val())); +}); diff --git a/pool/shard005/JavaScript/0032915_wrapper.js b/pool/shard005/JavaScript/0032915_wrapper.js new file mode 100644 index 0000000000000000000000000000000000000000..0ed807c8135ffff9a0e00cb2a835640145aafcd4 --- /dev/null +++ b/pool/shard005/JavaScript/0032915_wrapper.js @@ -0,0 +1,91 @@ +/** @module liaison/wrapper */ +define([ + "decor/Observable", + "decor/ObservableArray" +], function (Observable, ObservableArray) { + "use strict"; + + var getPrototypeOf = Object.getPrototypeOf; + + /** + * @function module:liaison/wrapper.wrap + * @param {Object} o A plain object. + * @returns {module:decor/Observable} The {@link module:decor/Observable Observable} version of the given object. + */ + function wrap(o) { + var root = o, + tree = []; + + function wrapImpl(o) { + var index = tree.indexOf(o); + if (index >= 0) { + return tree[index + 1]; + } + + var proto, + isArray = Array.isArray(o), + isObject = Observable.test(o) || o && typeof o === "object" && (o === root || (proto = getPrototypeOf(o)) && !getPrototypeOf(proto)), + wrapped = isArray ? new ObservableArray() : isObject ? new Observable() : o; + + tree.push(o, wrapped); + + if (isArray) { + for (var i = 0, l = o.length; i < l; ++i) { + wrapped[i] = wrapImpl(o[i]); + } + } else if (isObject) { + for (var s in o) { + wrapped[s] = wrapImpl(o[s]); + } + } + + tree.splice(-2, 2); + return wrapped; + } + + return wrapImpl(o); + } + + /** + * @function module:liaison/wrapper.unwrap + * @param {module:decor/Observable} o A {@link module:decor/Observable Observable}. + * @returns {Object} The plain object version of the given {@link module:decor/Observable Observable}. + */ + function unwrap(o) { + var tree = []; + + function unwrapImpl(o) { + var index = tree.indexOf(o); + if (index >= 0) { + return tree[index + 1]; + } + + var proto, + isArray = Array.isArray(o), + isObject = Observable.test(o) || o && typeof o === "object" && (proto = getPrototypeOf(o)) && !getPrototypeOf(proto), + unwrapped = isArray ? [] : isObject ? {} : o; + + tree.push(o, unwrapped); + + if (isArray) { + for (var i = 0, l = o.length; i < l; ++i) { + unwrapped[i] = unwrapImpl(o[i]); + } + } else if (isObject) { + for (var s in o) { + unwrapped[s] = unwrapImpl(o[s]); + } + } + + tree.splice(-2, 2); + return unwrapped; + } + + return unwrapImpl(o); + } + + return { + wrap: wrap, + unwrap: unwrap + }; +}); \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032917_ol3googlemaps.test.js b/pool/shard005/JavaScript/0032917_ol3googlemaps.test.js new file mode 100644 index 0000000000000000000000000000000000000000..bd92a5a0b3cbe8c70b1feb5be3d148ebf0094cd9 --- /dev/null +++ b/pool/shard005/JavaScript/0032917_ol3googlemaps.test.js @@ -0,0 +1,138 @@ +goog.provide('olgm.test.OLGoogleMaps'); + +describe('olgm.OLGoogleMaps', function() { + var target = document.createElement('div'); + var style = target.style; + style.width = '300px'; + style.height = '300px'; + + var view = new ol.View({ + center: [-7908084, 6177492], + zoom: 12 + }); + + describe('constructor', function() { + var map = new ol.Map({}); + var olGM; + + it('creates a new OLGoogleMaps object', function() { + olGM = new olgm.OLGoogleMaps({map: map}); + expect(olGM).to.be.an.instanceof(olgm.OLGoogleMaps); + }); + + it('creates the Google Maps map', function() { + var gmap = olGM.gmap; + expect(gmap).to.be.an.instanceof(google.maps.Map); + }); + }); + + describe('#activate()', function() { + document.body.appendChild(target); + var googleLayer = new olgm.layer.Google(); + var map = new ol.Map({ + layers: [ + googleLayer + ], + target: target, + view: view + }); + var olGM = new olgm.OLGoogleMaps({map: map}); + + it('activates the heralds', function() { + expect(olGM.getGoogleMapsActive()).to.be.false; + olGM.activate(); + expect(olGM.getGoogleMapsActive()).to.be.true; + }); + + document.body.removeChild(target); + }); + + describe('#deactivate()', function() { + document.body.appendChild(target); + var googleLayer = new olgm.layer.Google(); + var map = new ol.Map({ + layers: [ + googleLayer + ], + target: target, + view: view + }); + var olGM = new olgm.OLGoogleMaps({map: map}); + + olGM.activate(); + it('deactivates the heralds', function() { + expect(olGM.getGoogleMapsActive()).to.be.true; + olGM.deactivate(); + expect(olGM.getGoogleMapsActive()).to.be.false; + }); + + document.body.removeChild(target); + }); + + describe('#getGoogleMapsActive()', function() { + document.body.appendChild(target); + var googleLayer = new olgm.layer.Google(); + var map = new ol.Map({ + layers: [ + googleLayer + ], + target: target, + view: view + }); + var olGM = new olgm.OLGoogleMaps({map: map}); + + it('returns true when Google Maps is active', function() { + expect(olGM.getGoogleMapsActive()).to.be.false; + olGM.activate(); + expect(olGM.getGoogleMapsActive()).to.be.true; + }); + it('returns false when Google Maps is not active', function() { + olGM.deactivate(); + expect(olGM.getGoogleMapsActive()).to.be.false; + olGM.activate(); + }); + it('returns false when there is no Google Maps layer', function() { + olGM.ol3map.removeLayer(googleLayer); + expect(olGM.getGoogleMapsActive()).to.be.false; + }); + + document.body.removeChild(target); + }); + + describe('#getGoogleMapsMap()', function() { + var map = new ol.Map({}); + var olGM = new olgm.OLGoogleMaps({map: map}); + + it('returns the Google Maps map', function() { + var gmap = olGM.gmap; + expect(gmap).to.be.an.instanceof(google.maps.Map); + expect(gmap).to.equal(olGM.getGoogleMapsMap()); + }); + }); + + describe('#toggle()', function() { + document.body.appendChild(target); + var googleLayer = new olgm.layer.Google(); + var map = new ol.Map({ + layers: [ + googleLayer + ], + target: target, + view: view + }); + var olGM = new olgm.OLGoogleMaps({map: map}); + + it('sets the OLGoogleMaps object to active when inactive', function() { + expect(olGM.getGoogleMapsActive()).to.be.false; + olGM.toggle(); + expect(olGM.getGoogleMapsActive()).to.be.true; + }); + it('sets the OLGoogleMaps object to inactive when active', function() { + expect(olGM.getGoogleMapsActive()).to.be.true; + olGM.toggle(); + expect(olGM.getGoogleMapsActive()).to.be.false; + }); + + document.body.removeChild(target); + }); +}); diff --git a/pool/shard005/JavaScript/0032918_NotesPicker.js b/pool/shard005/JavaScript/0032918_NotesPicker.js new file mode 100644 index 0000000000000000000000000000000000000000..c560d8b2839b1a1a4dffbb7ce3976e8d5e744593 --- /dev/null +++ b/pool/shard005/JavaScript/0032918_NotesPicker.js @@ -0,0 +1,94 @@ +/** + * Note data type, composed of a unique identifier and a label + * + * @typedef {Object} chordsWiki.NotesPicker.Note + * @property {number} id - The id of the note + * @property {String} label - The label with the name of the note + */ + +(function() { + 'use strict'; + /** + * Constructor of the NotesPicker widget, a UI with a list of notes that can be selected to compose a chord + * @param {Object} params.dataSource - data with the list of chords types and categories + * @constructor + */ + chordsWiki.NotesPicker = function(params) { + + var CONST = { + DOM: { + INPUT_TYPE: 'checkbox', + INPUT_NAME: 'note' + } + }; + + var config = { + dataSource: chordsWiki.chordsData + }; + + $.extend(config, params); + + var self = this; + + var notesList = null; + + this.container = $('
'); + + var init = function() { + notesList = initializeNotesCheckboxList(); + render(); + populateNotesCheckboxList(config.dataSource.notes, notesList); + }; + + /** + * Render the UI + */ + var render = function() { + self.container.append(notesList); + }; + + /** + * Initialize the list of notes creating the html list container + */ + var initializeNotesCheckboxList = function() { + notesList = $('
    '); + return notesList; + }; + + /** + * Populate the list of notes appending the options to the list + * @param {chordsWiki.NotesPicker.Note[]} dataArray - the array of notes + * @param {jQuery} list - the jQuery wrapper of the html list container + */ + var populateNotesCheckboxList = function(dataArray, list) { + for (var i = 0; i < dataArray.length; i++) { + var record = dataArray[i]; + var listEntry = $('
  • '); + var checkboxElement = $('', { type: CONST.DOM.INPUT_TYPE, name: CONST.DOM.INPUT_NAME, value: record.id }); + listEntry.append(checkboxElement); + listEntry.append(record.label); + list.append(listEntry); + } + }; + + /** + * Get the notes currently selected + * @returns {String[]} notes - the list of ids of the selected notes + */ + this.getSelectedNotes = function() { + var options = notesList.find('input'); + var notes = []; + for (var i = 0; i < options.length; i++) { + if(options[i].checked === true){ + notes.push(options[i].value); + } + } + + return notes; + }; + + init(); + + }; + +}()); diff --git a/pool/shard005/JavaScript/0032919_index.js b/pool/shard005/JavaScript/0032919_index.js new file mode 100644 index 0000000000000000000000000000000000000000..f41e1be4138f582b329f4877f8f69a1aad916474 --- /dev/null +++ b/pool/shard005/JavaScript/0032919_index.js @@ -0,0 +1,137 @@ +var http = require('http') + , fs = require('fs') + , path = require('path') + , stylus = require('stylus') + , nib = require('nib') + , qs = require('querystring') + , browserify = require('browserify') + , uglify = require('uglify-js') + , inherits = require('util').inherits + , EventEmitter = require('events').EventEmitter + , makeAgent = require('zag-agent') + , MetricsRouter = require('./routes') + , clientDir = path.join(__dirname, "../client") + , stylusDir = path.join(clientDir, "stylus") + , jsDir = path.join(clientDir, "js") + +module.exports = MetricsWeb + +/// +/// options: (required) +/// host - "address:port" +/// db - String postgres connection +/// env - "dev", "prod", "test", ... +/// daemons - ["address:port"] +/// defaultPath - String "/graph/some_metrics_key" or "/dashboards/some_dashboard" +/// backend - PGBackend +/// public - String, a readable/writable directory path. +/// +/// Events: +/// error(err) +/// ready() - The server is online. +/// +function MetricsWeb(options) { + var _this = this + , publicDir = options.public = path.resolve(options.public) + + this.agent = makeAgent(options.daemons) + this.agent.on("error", this.onError.bind(this)) + this.metrics = this.agent.scope("zag-web") + + this.db = new options.backend( + { env: options.env + , db: options.db + , agent: this.metrics.scope("backend") + , onError: this.onError.bind(this) + }) + this.router = new MetricsRouter( + { db: this.db + , agent: this.metrics + , defaultPath: options.defaultPath || "/graph/zag-daemon>backend>timing" + , public: options.public + }) + this.server = http.createServer(function(req, res) { _this.onRequest(req, res) }) + + try { fs.mkdirSync(publicDir) } catch(e) {} + + // Generate assets. + buildCSS(path.join(stylusDir, "index.styl"), function(err, css) { + if (err) console.log(err) + fs.writeFile(path.join(publicDir, "index.css"), css) + buildJS(publicDir, options.env === "prod", function() { + var addrport = options.host.split(":") + _this.server.listen(+addrport[1], addrport[0], _this.onReady.bind(_this)) + }) + }) +} + +inherits(MetricsWeb, EventEmitter) + +MetricsWeb.prototype.onError = function(err) { this.emit("error", err) } +MetricsWeb.prototype.onReady = function(err) { this.emit("ready", err) } + +MetricsWeb.prototype.close = function() { + this.db.close() + this.router.close() + this.server.close() + this.agent.close() +} + +var reRoute = /[*?]/g + +MetricsWeb.prototype.onRequest = function(req, res) { + var split = req.url.split("?") + , match = this.router.match(split[0]) + req.qs = qs.parse(split[1]) + req.params = match.params + req.splats = match.splats + + res.on("finish", trackTiming(this.metrics, match.route.replace(reRoute, ""))) + match.fn(req, res) +} + +function trackTiming(agent, route) { + var start = Date.now() + return function() { + agent.histogram("timing|" + route + "|" + this.statusCode, Date.now() - start) + } +} + +// file - The `.styl` file to compile. +// callback - Receives `(err, css_string)`. +function buildCSS(file, callback) { + fs.readFile(file, function(err, data) { + if (err) return callback(err) + stylus(data.toString()) + .set("filename", file) + .set("paths", [stylusDir, nib.path]) + .render(function(err, css) { + if (err) return callback(err) + callback(null, css) + }) + }) +} + +function buildJS(publicDir, minify, callback) { + var bundle = path.join(publicDir, "bundle.js") + , bundleMin = path.join(publicDir, "bundle.min.js") + , sourceMap = path.join(publicDir, "bundle.js.map") + browserify(path.join(jsDir, "index.js")).bundle() + .pipe(fs.createWriteStream(bundle)) + .on("close", done) + + function done() { + if (!minify) { + return fs.createReadStream(bundle) + .pipe(fs.createWriteStream(bundleMin)) + .on("close", callback) + } + var res = uglify.minify(fs.readFileSync(bundle, "utf8"), {sourceMap: { url: "/public/bundle.js.map" }}) + map = JSON.parse(res.map) + map.sources = ["/public/bundle.js"] + res.code += "\n//# sourceMappingURL=/public/bundle.js.map" + fs.writeFileSync(bundleMin, res.code) + fs.writeFileSync(sourceMap, JSON.stringify(map)) + callback() + } +} diff --git a/pool/shard005/JavaScript/0032921_Hub.js b/pool/shard005/JavaScript/0032921_Hub.js new file mode 100644 index 0000000000000000000000000000000000000000..241b0decda348cd320e08fbb39f6702f9043f85d --- /dev/null +++ b/pool/shard005/JavaScript/0032921_Hub.js @@ -0,0 +1,107 @@ +function handleSearchComputerHub(e) { + if (e.Status == "denied") { + showDialog("Access Denied", "You don't have access to computers in that group."); + return; + } + if (e.Status == "ok") { + InstaTech.Hub_Computers = e.Computers; + if (InstaTech.Hub_Computers.length == 0) { + showDialog("No Results", "No computers matched the search criteria."); + } + else { + $("#tableComputerHub tbody").html(""); + for (var i = 0; i < InstaTech.Hub_Computers.length; i++) { + var tr = document.createElement("tr"); + tr.onclick = hubRowClicked; + var td = document.createElement("td"); + td.innerHTML = InstaTech.Hub_Computers[i].ComputerName; + td.setAttribute("prop", "ComputerName"); + tr.appendChild(td); + td = document.createElement("td"); + td.innerHTML = parseNETDate(InstaTech.Hub_Computers[i].LastReboot).toLocaleString(); + td.setAttribute("prop", "LastReboot"); + tr.appendChild(td); + td = document.createElement("td"); + td.innerHTML = InstaTech.Hub_Computers[i].CurrentUser; + td.setAttribute("prop", "CurrentUser"); + tr.appendChild(td); + td = document.createElement("td"); + td.innerHTML = InstaTech.Hub_Computers[i].LastLoggedOnUser; + td.setAttribute("prop", "LastLoggedOnUser"); + tr.appendChild(td); + td = document.createElement("td"); + var sel = document.createElement("select"); + sel.onchange = hubComputerGroupChanged; + var option = document.createElement("option"); + sel.options.add(option); + for (var i2 = 0; i2 < InstaTech.ComputerGroups.length; i2++) { + var option = document.createElement("option"); + option.value = InstaTech.ComputerGroups[i2]; + option.innerHTML = InstaTech.ComputerGroups[i2]; + if (InstaTech.Hub_Computers[i].ComputerGroup == InstaTech.ComputerGroups[i2]) { + option.selected = true; + } + sel.options.add(option); + } + td.appendChild(sel); + td.setAttribute("prop", "ComputerGroup"); + tr.appendChild(td); + $("#tableComputerHub tbody").append(tr); + } + } + window.scroll(0, $("#tableComputerHub").offset().top); + } +} +function handleSetComputerGroup(e) { + if (e.Status == "denied") { + showDialog("Access Denied", "You do not have access to modify that group."); + return; + } + if (e.Status == "unknown") { + showDialog("Computer Not Found", "Unable to find that computer. Please refresh your search results."); + return; + } + if (e.Status == "ok") { + showTooltip($("select:focus"), "left", "green", "Group changed."); + } +} +function handleFileDeploy(e) { + if (e.Status == "denied") { + $("#textDeployResults")[0].value += "[FAILED]\nAccess to " + e.TargetComputer + " denied."; + } + else if (e.Status == "notfound") { + $("#textDeployResults")[0].value += "[FAILED]\nComputer " + e.TargetComputer + " wasn't found."; + } + else if (e.Status == "ok") { + InstaTech.Temp.DeployResults = InstaTech.Temp.DeployResults || []; + InstaTech.Temp.DeployResults.push(e); + $("#textDeployResults")[0].value += "[SUCCESS]\nComputer: " + e.TargetComputer + "\nExit Code: " + e.ExitCode + + "\nOutput: " + e.Output + "\Errors: " + e.Error; + } + $("#textDeployResults")[0].value += "\n-------------------------\n\n"; + $("#textDeployResults")[0].scrollTop = $("#textDeployResults")[0].scrollHeight; +} +function handleConsoleCommand(e) { + if (e.Status == "denied") { + $("#textConsoleOutput")[0].value += "[" + e.TargetComputer + "]\nAccess to denied.\n"; + } + else if (e.Status == "notfound") { + $("#textConsoleOutput")[0].value += "[" + e.TargetComputer + "]\nComputer wasn't found.\n"; + } + else if (e.Status == "ok") { + $("#textConsoleOutput")[0].value += "[" + e.TargetComputer + "]: " + e.Output + "\n"; + } + $("#textConsoleOutput")[0].scrollTop = $("#textConsoleOutput")[0].scrollHeight; +} +function handleNewConsole(e) { + if (e.Status == "denied") { + $("#textConsoleOutput")[0].value += "[" + e.TargetComputer + "]\nAccess to denied.\n"; + } + else if (e.Status == "notfound") { + $("#textConsoleOutput")[0].value += "[" + e.TargetComputer + "]\nComputer wasn't found.\n"; + } + else if (e.Status == "ok") { + $("#textConsoleOutput")[0].value += "[" + e.TargetComputer + "]: New console session started.\n"; + } + $("#textConsoleOutput")[0].scrollTop = $("#textConsoleOutput")[0].scrollHeight; +} \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032925_BootstrapChannelServer.js b/pool/shard005/JavaScript/0032925_BootstrapChannelServer.js new file mode 100644 index 0000000000000000000000000000000000000000..67af74668d6a920d526580f53d139faafe7f79d4 --- /dev/null +++ b/pool/shard005/JavaScript/0032925_BootstrapChannelServer.js @@ -0,0 +1,183 @@ +"use strict"; + +const msg_types = require("webrtc-conductor").enums, + WebSocketServer = require("ws").Server, + pki = require("node-forge").pki, + random = require("node-forge").random, + cipher = require("node-forge").cipher, + forgeUtil = require("node-forge").util, + u = require("./UtilFunctions.js"); + +// This initial version uses the chord spec - i.e. we use a wrtc connection with the node +// of the server itself, rather than a level above being used to route information across. +// This way is simpler, but may be more taxing on the server. + +class BootstrapChannelServer{ + constructor(chord){ + this._manager = null; + this.wss = null; + this.chord = chord; + this.id = chord.id; + + this.connMap = {}; + } + + get internalID(){ + return "Boot-Server"; + } + + onbind(){ + let t = this; + this.wss = new WebSocketServer(t.chord.config.serverConfig); + u.log(t.chord, "Bound, opening WSS."); + + return new Promise((resolve, reject) => { + this.wss.on("open", () => { + u.log(t.chord, "Server finally ready!"); + resolve(false); + }); + + this.wss.on("error", e => {reject(e);}); + + this.wss.on("connection", conn => { + u.log(t.chord, "Connection from client, setting up."); + + conn.onmessage = function(evt) { + u.log(t.chord, "Initial message from client, checking..."); + let obj = JSON.parse(evt.data); + u.log(t.chord, obj) + switch(obj.type){ + case "bstrap-reg": + t.connMap[obj.id] = this; + this.id = obj.id; + this.registered = true; + this.pubKey = obj.data; + this.pubKeyObj = pki.publicKeyFromPem(this.pubKey); + + this.aesKey = random.getBytesSync(16); + + this.onmessage = evt => {t._manager.response(evt, t);}; + + u.log(t.chord, "Valid. Connection from "+this.id+". Message handler bound."); + + safeSend(this, { + type: "bstrap-wel", + id: t.id.idString, + data: t.chord.pubKeyPem, + encKey: this.pubKeyObj.encrypt(this.aesKey, "RSA-OAEP") + }); + break; + default: + throw new Error("Illegal class "+type+" of message sent to "+this.internalID+" channel!"); + } + }; + + conn.onclose = () => { + if(conn.registered) + delete this.connMap[conn.id] + }; + }); + }); + } + + send(id,type,data){ + u.log(this.chord, "Send instruction given to server bootstrap."); + + let iv = random.getBytesSync(12), + cipherObj = cipher.createCipher('AES-GCM', this.connMap[id].aesKey); + + cipherObj.start({ + iv, + additionalData: 'binary-encoded string', + tagLength: 128 + }); + + cipherObj.update(forgeUtil.createBuffer(JSON.stringify(data))); + cipherObj.finish(); + + let obj = { + id: this.id.idString, + //encIv: this.connMap[id].pubKeyObj.encrypt(iv), + iv: iv, + data: cipherObj.output.data, + tag: cipherObj.mode.tag.data + }; + + let target = this.connMap[id]; + + switch(type){ + case msg_types.MSG_SDP_OFFER: + u.log(this.chord, "Sending offer to client (?)") + obj.type = "bstrap-offer"; + break; + case msg_types.MSG_SDP_ANSWER: + u.log(this.chord, "Sending SDP reply to client.") + obj.type = "bstrap-reply"; + break; + case msg_types.MSG_ICE: + u.log(this.chord, "Sending ICE candidate to client.") + obj.type = "bstrap-ice"; + break; + default: + throw new Error("Illegal class "+type+" of message sent to "+this.internalID+" channel!"); + } + + safeSend(target, obj); + } + + onmessage(evt){ + let obj = JSON.parse(evt.data), + iv = obj.iv,//this.chord.key.privateKey.decrypt(obj.encIv, "RSA-OAEP"), + decipher = cipher.createDecipher('AES-GCM', this.connMap[obj.id].aesKey);; + + u.log(this.chord, "Server bootstrap received message:"); + u.log(this.chord, obj); + + decipher.start({ + iv, + additionalData: 'binary-encoded string', + tagLength: 128, + tag: obj.tag + }); + + decipher.update(forgeUtil.createBuffer(obj.data)); + let success = decipher.finish(); + + let out = { + type: null, + data: (success) ? JSON.parse(decipher.output.data) : "", + id: null + }; + + switch(obj.type){ + case "bstrap-offer": + out.type = msg_types.RESPONSE_SDP_OFFER; + break; + case "bstrap-ice": + out.type = msg_types.RESPONSE_ICE; + break; + default: + out.type = msg_types.RESPONSE_NONE; + break; + } + + out.id = obj.id; + + return out; + } + + close(){ + u.log(this.chord, "Closing server bootstrap - this shouldn't happen."); + this.wss.close(); + } +} + +function safeSend(ws, obj){ + try{ + ws.send(JSON.stringify(obj)); + } catch (e) { + console.log(e); + } +} + +module.exports = BootstrapChannelServer; \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032926_wget.js b/pool/shard005/JavaScript/0032926_wget.js new file mode 100644 index 0000000000000000000000000000000000000000..9d6b5b739dba4b7f246b0f2479eb27729125d2d7 --- /dev/null +++ b/pool/shard005/JavaScript/0032926_wget.js @@ -0,0 +1,105 @@ +'use strict'; + +/*! + * + * Copyright(c) 2011 Vladimir Dronnikov + * MIT Licensed + * + */ + +// +// TODO: consider using 'request' repo -- just reuse bodyParser +// + +var parseUrl = require('url').parse; +var bodyParser = require('./body')(); + +var proto = { + 'http:': { + port: 80, + module: require('http') + }, + 'https:': { + port: 443, + module: require('https') + } +}; + +function request(method, url, data, headers, next) { + // defaults + if (!next) { + next = headers; + headers = null; + } + if (!headers) { + headers = { + accept: '*/*', + 'user-agent': 'wget 1.14', + 'content-type': 'application/x-www-form-urlencoded' + } + } + // compose request params + var params = parseUrl(url); + var protocol = params.protocol; + params = { + //host: headers.host = params.hostname, + host: params.hostname, + port: params.port || proto[protocol].port || 3128, + path: params.pathname + (params.search ? params.search : ''), + headers: headers + }; + // proxy? + var proxy; + if (proxy = process.env['' + protocol.replace(/\:$/,'') + '_proxy'] || process.env.http_proxy) { + proxy = parseUrl(proxy); + protocol = proxy.protocol; + params.headers.host = params.host; + params.port = proxy.port || 80; + params.host = proxy.hostname; + params.path = url; + } + // set the verb + params.method = method; + // stringify data + if (data) { + if (Object(data) === data) { + data = JSON.stringify(data); + headers['content-type'] = 'application/json'; + } else { + data = String(data); + } + // set content-length + headers['content-length'] = data.length; + } + //console.log('REQ', params); + // issue the request + var req = proto[protocol].module.request(params, function(res) { + //console.log('WGETRESPONSEHEADERS', url, res.headers); + if (res.statusCode !== 200) { + next(res.statusCode); + } else { + // reuse body middleware to parse the response + bodyParser(res, null, function(err, result) { + //console.log('WGETBODY', res.body); + next(err, res.body); + }); + } + }); + // catch errors + req.on('error', next); + // send the data, if any + if (data) { + req.write(data, 'utf8'); + } + req.end(); +} + +module.exports = { + request: request, + get: function(url, headers, next) { + return request('GET', url, null, headers, next); + }, + post: function(url, data, headers, next) { + return request('POST', url, data, headers, next); + } +}; diff --git a/pool/shard005/JavaScript/0032928_table36.js b/pool/shard005/JavaScript/0032928_table36.js new file mode 100644 index 0000000000000000000000000000000000000000..2cfb59e431f2b802ebd1777e855486a0b38f8f24 --- /dev/null +++ b/pool/shard005/JavaScript/0032928_table36.js @@ -0,0 +1,112 @@ + +/* +Copyright © 2001-2004 World Wide Web Consortium, +(Massachusetts Institute of Technology, European Research Consortium +for Informatics and Mathematics, Keio University). All +Rights Reserved. This work is distributed under the W3C® Software License [1] 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. + +[1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 +*/ + + + + /** + * Gets URI that identifies the test. + * @return uri identifier of test + */ +function getTargetURI() { + return "http://www.w3.org/2001/DOM-Test-Suite/level2/html/table36"; + } + +var docsLoaded = -1000000; +var builder = null; + +// +// This function is called by the testing framework before +// running the test suite. +// +// If there are no configuration exceptions, asynchronous +// document loading is started. Otherwise, the status +// is set to complete and the exception is immediately +// raised when entering the body of the test. +// +function setUpPage() { + setUpPageStatus = 'running'; + try { + // + // creates test document builder, may throw exception + // + builder = createConfiguredBuilder(); + + docsLoaded = 0; + + var docRef = null; + if (typeof(this.doc) != 'undefined') { + docRef = this.doc; + } + docsLoaded += preload(docRef, "doc", "table"); + + if (docsLoaded == 1) { + setUpPageStatus = 'complete'; + } + } catch(ex) { + catchInitializationError(builder, ex); + setUpPageStatus = 'complete'; + } +} + + + +// +// This method is called on the completion of +// each asychronous load started in setUpTests. +// +// When every synchronous loaded document has completed, +// the page status is changed which allows the +// body of the test to be executed. +function loadComplete() { + if (++docsLoaded == 1) { + setUpPageStatus = 'complete'; + } +} + + +/** +* +Specifies which external table borders to render. +The value of attribute frame of the table element is read and checked against the expected value. + +* @author Netscape +* @author Sivakiran Tummala +* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html#ID-64808476 +*/ +function table36() { + var success; + if(checkInitialization(builder, "table36") != null) return; + var nodeList; + var testNode; + var vframe; + var doc; + + var docRef = null; + if (typeof(this.doc) != 'undefined') { + docRef = this.doc; + } + doc = load(docRef, "doc", "table"); + nodeList = doc.getElementsByTagName("table"); + assertSize("Asize",3,nodeList); +testNode = nodeList.item(1); + vframe = testNode.frame; + + assertEquals("frameLink","border",vframe); + +} + + + + +function runTest() { + table36(); +} diff --git a/pool/shard005/JavaScript/0032935_thingsAndPools.js b/pool/shard005/JavaScript/0032935_thingsAndPools.js new file mode 100644 index 0000000000000000000000000000000000000000..95eb4d55e294a9459923c9fe78975924cab3e923 --- /dev/null +++ b/pool/shard005/JavaScript/0032935_thingsAndPools.js @@ -0,0 +1,32 @@ +import exists from '../utils/existingProperty'; +import XMLRequest from '../utils/XMLRequest'; +import SemiPromise from '../utils/semiPromise'; + +// {thingId: [thing, pool, learnable]} +const cache = {}; +export default cache; + +// fill the cache asynchronously +// resolves to {thingId: SemiPromise<[thing, pool]>} +export const promisesPromise = exists(window, ['MEMRISE', 'garden', 'session_data', 'learnables']) + .then(([learnables]) => learnables.reduce((promises, learnable) => { + const thingId = learnable.thing_id; + + const thingUrl = `https://www.memrise.com/api/thing/get/?thing_id=${thingId}`; + const poolUrl = (poolId) => `https://www.memrise.com/api/pool/get/?pool_id=${poolId}`; + + const thingPromise = XMLRequest(['GET', thingUrl]) + .then((response) => JSON.parse(response).thing); + + const poolPromise = thingPromise + .then((thing) => XMLRequest(['GET', poolUrl(thing.pool_id)])) + .then((response) => JSON.parse(response).pool); + + promises[thingId] = SemiPromise.all([ + thingPromise, + poolPromise, + ]).then(([thing, pool]) => cache[thingId] = [thing, pool]); + + return promises; + }, {}) +); diff --git a/pool/shard005/JavaScript/0032936_mentions_with_indices.js b/pool/shard005/JavaScript/0032936_mentions_with_indices.js new file mode 100644 index 0000000000000000000000000000000000000000..0c06d7d2115fb2f3feba7c09631c056aa3725a1d --- /dev/null +++ b/pool/shard005/JavaScript/0032936_mentions_with_indices.js @@ -0,0 +1,25 @@ +import test from 'ava'; +import { parse } from '../../..'; + +const transform = output => output.entities.user_mentions; + +test("Extract a mention at the start", t => { + const actual = parse("@username yo!"); + const expected = [{"screen_name":"username","indices":[0,9]}]; + + t.deepEqual(transform(actual), expected); +}); + +test("Extract a mention that has the same thing mentioned at the start", t => { + const actual = parse("username @username"); + const expected = [{"screen_name":"username","indices":[9,18]}]; + + t.deepEqual(transform(actual), expected); +}); + +test("Extract a mention in the middle of a Japanese tweet", t => { + const actual = parse("の@usernameに到着を待っている"); + const expected = [{"screen_name":"username","indices":[1,10]}]; + + t.deepEqual(transform(actual), expected); +}); diff --git a/pool/shard005/JavaScript/0032941_app.controller.js b/pool/shard005/JavaScript/0032941_app.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..22dc22afd6e02d73b5563ce00a44222c795609b3 --- /dev/null +++ b/pool/shard005/JavaScript/0032941_app.controller.js @@ -0,0 +1,15 @@ +angular.module('orderCloud') + .controller('AppCtrl', AppController) +; + +function AppController($state, $ocMedia, OrderCloudSDK, ocAppName, ocStateLoading, ocIsTouchDevice, ocRoles) { + var vm = this; + vm.name = ocAppName.Watch; + vm.$state = $state; + vm.$ocMedia = $ocMedia; + vm.isTouchDevice = ocIsTouchDevice; + vm.stateLoading = ocStateLoading.Watch; + vm.logout = OrderCloudSDK.Auth.Logout; + vm.userIsAuthorized = ocRoles.UserIsAuthorized; + vm.logoUrl = "assets/images/jb-logo.png"; +} \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032948_test_job_queue.js b/pool/shard005/JavaScript/0032948_test_job_queue.js new file mode 100644 index 0000000000000000000000000000000000000000..1875c9290318dffefef017ffa7d505edccf0b822 --- /dev/null +++ b/pool/shard005/JavaScript/0032948_test_job_queue.js @@ -0,0 +1,198 @@ +/** + * Created by aismael on 1/3/14. + */ +'use strict'; + +var assert = require('assert'); + +var path = require('path'); + +var exec = require("child_process").exec; + + +var job_queue_1 = require("../lib/index"); + +var repoConfig = { + repository: { + git_cmd_path: "c:\\Program Files (x86)\\Git\\bin\\git.exe", + git_repository_uri: "git@github.com:gaaiatinc/async-job-queue.git", + clone_dir: "./TestRepo", + git_remote_name: "origin", + git_branch: "master" + }, + instanceId: "git_job_queue", + persistent: false, + maxSize: 1000, + heartbeatMillis: 4000, + consoleLog: true +}; + + +function dummyExecutor(aJob) { + //console.log(">>>> dummy executor", aJob.toString()); +} +/** + * + */ +describe('job-queue', function () { + + + before(function (done) { + // + + + var appRoot = path.resolve('.'); + var basedir = path.join(appRoot, 'config'); + + //confit(basedir).create(function (err, config) { + // + // var appConfig = require("../../lib/util/app_config"); + // appConfig.init(config); + // + // job_queue.init(); + // + // //console.log(config); + // + // done(); + // + //}); + + job_queue_1.init(repoConfig) + .then(done) + .finally(done); + }); + + + /** + * + */ + after(function () { + + }); + + /** + * + */ + beforeEach(function () { + + }); + + /** + * + */ + afterEach(function () { + + }); + + + /** + * + */ + describe('GitJobQueue Performance test', function () { + + //it("original code", function (done) { + // + // var remoteName = "origin"; + // var repoURI = "git@github.com:gaaiatinc/git-job-queue.git"; + // + // (function checkRemote() { + // exec("git remote -v", {cwd: "./TestRepo"}, function (gitErr, output) { + // console.log("output:", output); + // + // var elems, idx; + // if (gitErr) { + // logger.warn("Could not check for repo consistency:", gitErr); + // return done(); + // } else { + // if (output) { + // elems = output.trim().split(/[\s]+/); + // for (idx = 0; (idx + 2) < elems.length; idx += 3) { + // if (elems[idx + 2] === "(fetch)" && elems[idx] === remoteName && elems[idx + 1] === repoURI) { + // return done(); + // } + // } + // } + // console.log("Could not find a matching remote name:", remoteName); + // return done(); + // } + // }); + // }()); + //}); + + it('should clean git repository without error', function (done) { + + job_queue_1.cleanRepositoryFolder() + .then(function () { + console.log("repository is wipedout:"); + }) + .catch(function (err) { + console.log(err); + }) + .finally(function () { + done(); + }); + + }); + + + it('should clone git repository without error', function (done) { + + job_queue_1.cloneRepository() + .then(function () { + console.log("repository is cloned:"); + }) + .catch(function (err) { + console.log(err); + }) + .finally(function () { + done(); + }); + + }); + + it('should test git repository without error', function (done) { + + job_queue_1.testRepository() + .then(function () { + console.log("repository is ok:"); + }) + .catch(function (err) { + console.log(err); + }) + .finally(function () { + done(); + }); + + }); + + it('should schedule a git command without error', function (done) { + + job_queue_1.scheduleGitCommand(["log", "-5"]) + .then(function (results) { + console.log("repository is ok, last few logs:", results); + }) + .catch(function (err) { + console.log(err); + }) + .finally(function () { + done(); + }); + + }); + + it('should list modified upstream files without error', function (done) { + + job_queue_1.listModifiedUpstreamFiles() + .then(function (results) { + console.log("repository is ok, modified upstream files:", results); + }) + .catch(function (err) { + console.log(err); + }) + .finally(function () { + done(); + }); + + }); + }); +}); diff --git a/pool/shard005/JavaScript/0032951_mkdir.js b/pool/shard005/JavaScript/0032951_mkdir.js new file mode 100644 index 0000000000000000000000000000000000000000..c6a154c24fe600995de3ef3bdb17af41aaf75397 --- /dev/null +++ b/pool/shard005/JavaScript/0032951_mkdir.js @@ -0,0 +1,206 @@ +'use strict' +// wrapper around mkdirp for tar's needs. + +// TODO: This should probably be a class, not functionally +// passing around state in a gazillion args. + +const mkdirp = require('mkdirp') +const fs = require('fs') +const path = require('path') +const chownr = require('chownr') + +class SymlinkError extends Error { + constructor (symlink, path) { + super('Cannot extract through symbolic link') + this.path = path + this.symlink = symlink + } + + get name () { + return 'SylinkError' + } +} + +class CwdError extends Error { + constructor (path, code) { + super(code + ': Cannot cd into \'' + path + '\'') + this.path = path + this.code = code + } + + get name () { + return 'CwdError' + } +} + +const mkdir = module.exports = (dir, opt, cb) => { + // if there's any overlap between mask and mode, + // then we'll need an explicit chmod + const umask = opt.umask + const mode = opt.mode | 0o0700 + const needChmod = (mode & umask) !== 0 + + const uid = opt.uid + const gid = opt.gid + const doChown = typeof uid === 'number' && + typeof gid === 'number' && + ( uid !== opt.processUid || gid !== opt.processGid ) + + const preserve = opt.preserve + const unlink = opt.unlink + const cache = opt.cache + const cwd = opt.cwd + + const done = (er, created) => { + if (er) + cb(er) + else { + cache.set(dir, true) + if (created && doChown) + chownr(created, uid, gid, er => done(er)) + else if (needChmod) + fs.chmod(dir, mode, cb) + else + cb() + } + } + + if (cache && cache.get(dir) === true) + return done() + + if (dir === cwd) + return fs.stat(dir, (er, st) => { + if (er || !st.isDirectory()) + er = new CwdError(dir, er && er.code || 'ENOTDIR') + done(er) + }) + + if (preserve) + return mkdirp(dir, mode, done) + + const sub = path.relative(cwd, dir) + const parts = sub.split(/\/|\\/) + mkdir_(cwd, parts, mode, cache, unlink, cwd, null, done) +} + +const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => { + if (!parts.length) + return cb(null, created) + const p = parts.shift() + const part = base + '/' + p + if (cache.get(part)) + return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) + fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) +} + +const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => er => { + if (er) { + if (er.path && path.dirname(er.path) === cwd && + (er.code === 'ENOTDIR' || er.code === 'ENOENT')) + return cb(new CwdError(cwd, er.code)) + + fs.lstat(part, (statEr, st) => { + if (statEr) + cb(statEr) + else if (st.isDirectory()) + mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) + else if (unlink) + fs.unlink(part, er => { + if (er) + return cb(er) + fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) + }) + else if (st.isSymbolicLink()) + return cb(new SymlinkError(part, part + '/' + parts.join('/'))) + else + cb(er) + }) + } else { + created = created || part + mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) + } +} + +const mkdirSync = module.exports.sync = (dir, opt) => { + // if there's any overlap between mask and mode, + // then we'll need an explicit chmod + const umask = opt.umask + const mode = opt.mode | 0o0700 + const needChmod = (mode & umask) !== 0 + + const uid = opt.uid + const gid = opt.gid + const doChown = typeof uid === 'number' && + typeof gid === 'number' && + ( uid !== opt.processUid || gid !== opt.processGid ) + + const preserve = opt.preserve + const unlink = opt.unlink + const cache = opt.cache + const cwd = opt.cwd + + const done = (created) => { + cache.set(dir, true) + if (created && doChown) + chownr.sync(created, uid, gid) + if (needChmod) + fs.chmodSync(dir, mode) + } + + if (cache && cache.get(dir) === true) + return done() + + if (dir === cwd) { + let ok = false + let code = 'ENOTDIR' + try { + ok = fs.statSync(dir).isDirectory() + } catch (er) { + code = er.code + } finally { + if (!ok) + throw new CwdError(dir, code) + } + done() + return + } + + if (preserve) + return done(mkdirp.sync(dir, mode)) + + const sub = path.relative(cwd, dir) + const parts = sub.split(/\/|\\/) + let created = null + for (let p = parts.shift(), part = cwd; + p && (part += '/' + p); + p = parts.shift()) { + + if (cache.get(part)) + continue + + try { + fs.mkdirSync(part, mode) + created = created || part + cache.set(part, true) + } catch (er) { + if (er.path && path.dirname(er.path) === cwd && + (er.code === 'ENOTDIR' || er.code === 'ENOENT')) + return new CwdError(cwd, er.code) + + const st = fs.lstatSync(part) + if (st.isDirectory()) { + cache.set(part, true) + continue + } else if (unlink) { + fs.unlinkSync(part) + fs.mkdirSync(part, mode) + created = created || part + cache.set(part, true) + continue + } else if (st.isSymbolicLink()) + return new SymlinkError(part, part + '/' + parts.join('/')) + } + } + + return done(created) +} diff --git a/pool/shard005/JavaScript/0032952_app.js b/pool/shard005/JavaScript/0032952_app.js new file mode 100644 index 0000000000000000000000000000000000000000..68902b6818376ab88e28033fa2e7a9c254302b94 --- /dev/null +++ b/pool/shard005/JavaScript/0032952_app.js @@ -0,0 +1,166 @@ +$(document).ready(function() { + toggleHeaderFooter(); + enterTheSite(); + submitCurateFlight(); + seeTheFlightMap(); +}); + +var toggleHeaderFooter = function() { + if (window.location.pathname === '/') { + $('header').hide(); + $('footer').hide(); + } else { + $('main').show(); + $('header').show(); + $('footer').show(); + } +} + +var pushBrowserHistory = function(url, title, state) { + history.pushState( state, title, url); +} + +window.addEventListener("popstate", function(e) { + + if (window.location.pathname === '/') { + window.location.reload(); + } else { + + if (e.state.callback) { + window[e.state.callback](false, e.state.data ); + } else { + window.location.reload(); + } + } +}); + + +var loadSearchForm = function(pushState) { + + $.ajax({ + url: '/flights/search'+ '?partial=true', + success: successCallback + }); + + function successCallback(response) { + if(pushState){ + pushBrowserHistory( '/flights/search', 'Search SipTrip', { callback: 'loadSearchForm' } ) + } + $('main').html(response); + } +} + +var enterTheSite = function() { + $('#homepage-box').on('click', 'button', function(e){ + e.preventDefault(); + $('main').animate({ + opacity: "toggle" + }, 500, function(){ + loadSearchForm(true); + $('main').animate({ + opacity: 'toggle' + }, 500); + $('header').animate({ + opacity: 'toggle' + }, 500); + $('footer').animate({ + opacity: 'toggle' + }, 500); + }); + }); +} + +var runSearchForm = function(pushState, formData) { + $.ajax({ + url: '/flights/search_results'+ '?partial=true', + method: 'POST', + data: formData, + success: successCallback, + error: errorCallback + }); + + function successCallback(response) { + var theme; + var formValues; + + $('main').html(response); + if (pushState) { + pushBrowserHistory( '/flights/search_results', 'SipTrip', { + callback: 'runSearchForm', + data: formData + }); + } + + $(window).scrollTop($('#search-results-container').offset().top); + + formValues = deparam(formData); + theme = formValues["search_form[beverage]"].toLowerCase(); + setBackgroundTheme(theme); + + } + + function errorCallback(response) { + $('main').html(response.responseText); + } + + function deparam(query) { + var pairs, i, keyValuePair, key, value, map = {}; + + if (query.slice(0, 1) === '?') { + query = query.slice(1); + } + if (query !== '') { + pairs = query.split('&'); + for (i = 0; i < pairs.length; i += 1) { + keyValuePair = pairs[i].split('='); + key = decodeURIComponent(keyValuePair[0]); + value = (keyValuePair.length > 1) ? decodeURIComponent(keyValuePair[1]) : undefined; + map[key] = value; + } + } + return map; +} + +} + +var submitCurateFlight = function() { + $('main').on('click', '#new_search_form button', function(e){ + e.preventDefault(); + + var formData = $('#new_search_form').serialize(); + runSearchForm(true, formData); + }); +} + +var showFlightMap = function(pushState, flightUrl) { + $.ajax({ + url: flightUrl + '?partial=true', + success: successCallback + }); + + function successCallback(response) { + $('#business-results-container').html(response); + if (pushState) { + pushBrowserHistory( flightUrl, 'SipTrip', { + callback: 'showFlightMap', + data: flightUrl + }); + } + adjustMapHeight(); + $(window).scrollTop($('#business-results-container').offset().top); + } + +} +var seeTheFlightMap = function() { + $('main').on('click', '#search-results-box a', function(e){ + e.preventDefault(); + var flightUrl; + + flightUrl = $(this).attr('href'); + + showFlightMap(true, flightUrl); + + }); +} + + diff --git a/pool/shard005/JavaScript/0032954_Sidebar.Geometry.SphereGeometry.js b/pool/shard005/JavaScript/0032954_Sidebar.Geometry.SphereGeometry.js new file mode 100644 index 0000000000000000000000000000000000000000..7817468921cec9b2e9db349b9f1a314374fcd754 --- /dev/null +++ b/pool/shard005/JavaScript/0032954_Sidebar.Geometry.SphereGeometry.js @@ -0,0 +1,107 @@ +import * as THREE from '../../build/three.module.js'; + +import { UIRow, UIText, UIInteger, UINumber } from './libs/ui.js'; + +import { SetGeometryCommand } from './commands/SetGeometryCommand.js'; + +function SidebarGeometrySphereGeometry( editor, object ) { + + var strings = editor.strings; + + var container = new UIRow(); + + var geometry = object.geometry; + var parameters = geometry.parameters; + + // radius + + var radiusRow = new UIRow(); + var radius = new UINumber( parameters.radius ).onChange( update ); + + radiusRow.add( new UIText( strings.getKey( 'sidebar/geometry/sphere_geometry/radius' ) ).setWidth( '90px' ) ); + radiusRow.add( radius ); + + container.add( radiusRow ); + + // widthSegments + + var widthSegmentsRow = new UIRow(); + var widthSegments = new UIInteger( parameters.widthSegments ).setRange( 1, Infinity ).onChange( update ); + + widthSegmentsRow.add( new UIText( strings.getKey( 'sidebar/geometry/sphere_geometry/widthsegments' ) ).setWidth( '90px' ) ); + widthSegmentsRow.add( widthSegments ); + + container.add( widthSegmentsRow ); + + // heightSegments + + var heightSegmentsRow = new UIRow(); + var heightSegments = new UIInteger( parameters.heightSegments ).setRange( 1, Infinity ).onChange( update ); + + heightSegmentsRow.add( new UIText( strings.getKey( 'sidebar/geometry/sphere_geometry/heightsegments' ) ).setWidth( '90px' ) ); + heightSegmentsRow.add( heightSegments ); + + container.add( heightSegmentsRow ); + + // phiStart + + var phiStartRow = new UIRow(); + var phiStart = new UINumber( parameters.phiStart * THREE.MathUtils.RAD2DEG ).setStep( 10 ).onChange( update ); + + phiStartRow.add( new UIText( strings.getKey( 'sidebar/geometry/sphere_geometry/phistart' ) ).setWidth( '90px' ) ); + phiStartRow.add( phiStart ); + + container.add( phiStartRow ); + + // phiLength + + var phiLengthRow = new UIRow(); + var phiLength = new UINumber( parameters.phiLength * THREE.MathUtils.RAD2DEG ).setStep( 10 ).onChange( update ); + + phiLengthRow.add( new UIText( strings.getKey( 'sidebar/geometry/sphere_geometry/philength' ) ).setWidth( '90px' ) ); + phiLengthRow.add( phiLength ); + + container.add( phiLengthRow ); + + // thetaStart + + var thetaStartRow = new UIRow(); + var thetaStart = new UINumber( parameters.thetaStart * THREE.MathUtils.RAD2DEG ).setStep( 10 ).onChange( update ); + + thetaStartRow.add( new UIText( strings.getKey( 'sidebar/geometry/sphere_geometry/thetastart' ) ).setWidth( '90px' ) ); + thetaStartRow.add( thetaStart ); + + container.add( thetaStartRow ); + + // thetaLength + + var thetaLengthRow = new UIRow(); + var thetaLength = new UINumber( parameters.thetaLength * THREE.MathUtils.RAD2DEG ).setStep( 10 ).onChange( update ); + + thetaLengthRow.add( new UIText( strings.getKey( 'sidebar/geometry/sphere_geometry/thetalength' ) ).setWidth( '90px' ) ); + thetaLengthRow.add( thetaLength ); + + container.add( thetaLengthRow ); + + + // + + function update() { + + editor.execute( new SetGeometryCommand( editor, object, new THREE.SphereBufferGeometry( + radius.getValue(), + widthSegments.getValue(), + heightSegments.getValue(), + phiStart.getValue() * THREE.MathUtils.DEG2RAD, + phiLength.getValue() * THREE.MathUtils.DEG2RAD, + thetaStart.getValue() * THREE.MathUtils.DEG2RAD, + thetaLength.getValue() * THREE.MathUtils.DEG2RAD + ) ) ); + + } + + return container; + +} + +export { SidebarGeometrySphereGeometry }; diff --git a/pool/shard005/JavaScript/0032956_current-build-stats.js b/pool/shard005/JavaScript/0032956_current-build-stats.js new file mode 100644 index 0000000000000000000000000000000000000000..4d842bfbce4607689c011126b14d10e217fd470c --- /dev/null +++ b/pool/shard005/JavaScript/0032956_current-build-stats.js @@ -0,0 +1,28 @@ +const fs = require("fs-extra"); +const path = require("path"); +const glob = require("globby"); +const paths = require("../config/paths"); + +const { gzipSizeOf } = require("../util/gzipSizeOf"); +const { getRelativeChunkName } = require("../util/getRelativeChunkName"); + +const sourcePath = paths.appBuild; + +const gzipDisplayOpts = { level: 6 }; +const globbed = glob.sync(["**/*.{js,css,json,webmanifest}"], { + cwd: sourcePath, + absolute: true, +}); +const stats = globbed.reduce((result, fileName) => { + const contents = fs.readFileSync(fileName); + const key = getRelativeChunkName(sourcePath, fileName); + const originalSize = fs.statSync(fileName).size; + result[key] = { + original: originalSize, + gzip: gzipSizeOf(contents, gzipDisplayOpts), + }; + return result; +}, {}); + +fs.mkdirSync(paths.appTmpDir, { recursive: true }); +fs.writeJSONSync(paths.appTmpDir + path.sep + "build-stats.json", stats, {}); diff --git a/pool/shard005/JavaScript/0032957_right-sidebar-controller.js b/pool/shard005/JavaScript/0032957_right-sidebar-controller.js new file mode 100644 index 0000000000000000000000000000000000000000..37ca82474d78d99835b8e35b2f29ce6422c2bb4a --- /dev/null +++ b/pool/shard005/JavaScript/0032957_right-sidebar-controller.js @@ -0,0 +1,29 @@ +'use strict'; +angular.module('adsApp.controllers', []) + .controller('RightSidebarController', [ + '$scope', '$rootScope', 'categoriesService', 'townsService', function ($scope, $rootScope, categoriesService, townsService) { + categoriesService.getCategories().$promise.then(function(data) { + $scope.categories = data; + }, + function(error) { + debugger; + }); + + townsService.getTowns().$promise.then(function(data) { + $scope.towns = data; + }, + function(error) { + debugger; + }); + + $scope.categoryClicked = function (clickedCategoryId) { + $scope.selectedCategoryId = clickedCategoryId; + $rootScope.$broadcast('categorySelectionChanged', clickedCategoryId); + } + + $scope.townClicked = function (clickedTownId) { + $scope.selectedTownId = clickedTownId; + $rootScope.$broadcast('townSelectionChanged', clickedTownId); + } + } + ]); \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032963_Persona.EditarPersonaJuridica.DatosPrincipalesController.js b/pool/shard005/JavaScript/0032963_Persona.EditarPersonaJuridica.DatosPrincipalesController.js new file mode 100644 index 0000000000000000000000000000000000000000..2bd5da9744478b5326062d0524e79fcf0ee68329 --- /dev/null +++ b/pool/shard005/JavaScript/0032963_Persona.EditarPersonaJuridica.DatosPrincipalesController.js @@ -0,0 +1,61 @@ +'use strict'; + +/* jshint -W098 */ +angular.module('mean.persona').controller('Persona.EditarPersonaJuridica.DatosPrincipalesController', function( + $scope, $state, personaJuridica, SGCountryCode, SGTipoDocumento, SGTipoEmpresa, SGPersonaJuridica, toastr){ + + $scope.combo = { + pais: SGCountryCode.$search().$object, + tipoDocumento: SGTipoDocumento.$search({tipoPersona: 'juridica'}).$object, + tipoEmpresa: SGTipoEmpresa.$search().$object + }; + $scope.combo.selected = { + pais: undefined, + tipoDocumento: undefined, + tipoEmpresa: undefined + }; + + $scope.checkPersona = function($event){ + if(!angular.isUndefined($event)) + $event.preventDefault(); + if(!angular.isUndefined($scope.combo.selected.tipoDocumento) && !angular.isUndefined($scope.view.persona.numeroDocumento)){ + SGPersonaJuridica.$findByTipoNumeroDocumento($scope.combo.selected.tipoDocumento.abreviatura, $scope.view.persona.numeroDocumento).then(function(data){ + if(!data) + toastr.info('Documento de identidad disponible.'); + else + toastr.warning('Documento de identidad no disponible'); + }); + } + }; + + $scope.view = { + persona: personaJuridica + }; + + $scope.submit = function(){ + if ($scope.form.$valid) { + var save = function(){ + $scope.view.persona.$save().then( + function(data){ + $scope.view.personaDB = angular.copy($scope.view.persona); + toastr.success('Persona actualizada'); + }, + function error(err){ + toastr.error(err.data.message); + } + ); + }; + SGPersonaJuridica.$findByTipoNumeroDocumento($scope.view.persona.tipoDocumento, $scope.view.persona.numeroDocumento).then(function(data){ + if(data && data.id === $scope.view.persona.id){ + save(); + } + else { + toastr.warning('Documento de identidad no disponible'); + } + }); + } + }; + +}); + + \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032969_main.js b/pool/shard005/JavaScript/0032969_main.js new file mode 100644 index 0000000000000000000000000000000000000000..fa810e613893cae8727aedd8750b1295a0100a17 --- /dev/null +++ b/pool/shard005/JavaScript/0032969_main.js @@ -0,0 +1,66 @@ + + +function Minigame(started, playAreaQuery, targetQuery) { + this.playArea = $(playAreaQuery); + this.target = $(targetQuery); + this.score = 0; + this.timeToAutoChange = 3000; + this.timeoutID; + this.started = started; + this.score_callback = function(score) {}; + + // To be used when x points are scored + this.increaseScore = function(inc) { + if (!this.started) { + return; + } + this.setScore(this.score + inc); + this.score_callback(this.score); + } + + this.setScore = function(score) { + this.score = score; + this.changeToRandomPos(); + //this.playArea.css("background-image", 'url(' + this.calc_background(this.score) + ')'); + } + + + this.changeToRandomPos = function() { + posx = Math.floor(Math.random() * (this.playArea.width() - this.target.width())); + posy = Math.floor(Math.random() * (this.playArea.height() - this.target.height())); + return this.moveElement(posx, posy); + } + + this.moveElement = function(toX, toY) { + var elem = document.getElementById("archery"); + elem.style.position = "relative"; + + this.target.animate({ + left : toX + "px", + top : toY + "px", + }, 100); + + clearTimeout(this.timeoutID) + this.timeoutID = setTimeout(this.changeToRandomPos.bind(this), this.timeToAutoChange); + } + + this.finish = function() { + this.target.fadeOut(); + } + + this.start = function() { + this.started = true; + this.target.hide(); + document.getElementById('archery').style.visibility = "visible"; + this.target.fadeIn(); + this.changeToRandomPos(); + } + + this.hide = function() { + this.target.fadeOut(); + } + +if (this.started) { + this.start() + } +} diff --git a/pool/shard005/JavaScript/0032971_index.js b/pool/shard005/JavaScript/0032971_index.js new file mode 100644 index 0000000000000000000000000000000000000000..25fddca78d188f5f0a75074d0dd505a61dd910ab --- /dev/null +++ b/pool/shard005/JavaScript/0032971_index.js @@ -0,0 +1,18 @@ +var npm = require('npm'); + +test('setup4.x', function(done) { + npm.load(function(err, npm) { + npm.localPrefix = __dirname; + npm.commands.install(['express@4.12.0'], function(err) { + if (err) { + return done(err); + } + // run tests + require('./app'); + require('./async_helpers'); + require('./view_engine'); + require('./no_layout_app'); + done(); + }); + }); +}); diff --git a/pool/shard005/JavaScript/0032972_render-format-button.js b/pool/shard005/JavaScript/0032972_render-format-button.js new file mode 100644 index 0000000000000000000000000000000000000000..55f59608cb7bfbce8609f1aaba1e63acdf3dc8e9 --- /dev/null +++ b/pool/shard005/JavaScript/0032972_render-format-button.js @@ -0,0 +1,26 @@ +var svgFormat = require('./svg-format'); +var Mousetrap = require('mousetrap'); +require('mousetrap/plugins/global-bind/mousetrap-global-bind'); + +function renderFormatButton(onFormatClick) { + var extras = document.getElementsByClassName("extras")[0]; + + var formatLink = document.createElement("a"); + formatLink.className = "json_viewer icon format"; + formatLink.href = "#"; + formatLink.title = "Format (ctrl+shift+F / command+shift+F)"; + formatLink.innerHTML = svgFormat; + formatLink.onclick = function(e) { + e.preventDefault(); + onFormatClick(); + } + + Mousetrap.bindGlobal(['command+shift+f', 'ctrl+shift+f'], function() { + onFormatClick(); + return false; + }); + + extras.appendChild(formatLink); +} + +module.exports = renderFormatButton; diff --git a/pool/shard005/JavaScript/0032973_fsm.js b/pool/shard005/JavaScript/0032973_fsm.js new file mode 100644 index 0000000000000000000000000000000000000000..c5e6aa0a1fde13e55c02148c1ad5dd541a4bdd69 --- /dev/null +++ b/pool/shard005/JavaScript/0032973_fsm.js @@ -0,0 +1,123 @@ +'use strict' + +var FSM = function(defaultState) { + if(typeof defaultState !== "string") { + throw("FSM:constructor(defaultState: missing the argument defaultState!") + } + + this._action = {}; + this._actionRegExp = []; + this._currentState = defaultState; + this._lastState = defaultState; + this._runAction = false; + this._stalledEvents = []; +}; + +FSM.prototype.append = function(scope) { + // check so the scope is a function. + if(typeof scope !== "function") { + throw "FSM:append(scope): scope given as arument is not a function!"; + } + + // check so the table is an Array. + var tbl = scope(); + if(!(tbl instanceof Array)) { + throw("FSM:append(scope): state table returned by the scope function is not an array!") + } + + // create new states for the action + var len = tbl.length; + for(var i=0; i 1) { + var args = Array.prototype.slice.call(arguments); + args.splice(0, 1); + } + + this._runAction = true; + event.action.apply(event.action, args); + this._runAction = false; + } + + // move to the next state + if(event.next === '<') { + var t = this._currentState; + this._currentState = this._lastState; + this._lastState = t; + } else { + this._lastState = this._currentState; + this._currentState = event.next; + } + + // send any stalled events + while(this._stalledEvents.length > 0) { + var args = this._stalledEvents[0]; + this._stalledEvents.splice(0,1); + FSM.prototype.fireEvent.apply(this, args); + } + } else { + // an action is already run, push it to the stall list then + this._stalledEvents.push(arguments); + return; + } +}; diff --git a/pool/shard005/JavaScript/0032974_pubsub.js b/pool/shard005/JavaScript/0032974_pubsub.js new file mode 100644 index 0000000000000000000000000000000000000000..db5391149e980fd850ffbbbc610514e23e565e3f --- /dev/null +++ b/pool/shard005/JavaScript/0032974_pubsub.js @@ -0,0 +1,217 @@ +var PubSub = Class(function () { + /** + ** @param string {String} + ** @return {*} + **/ + var parseChannel = function ( string ) { + if ( string.length ) { + if( Utils.asteriskEnd( string ) ) { + return Utils.removeAsteriskEnd( string ); + } + } + }; + return { + main: function () { + this.modules = []; // Subscribers + this.channels = {}; // channels by name includes info; + this.channelsList = []; + this.subscriptions = {}; // every module has a list of the subscriptions/regexs + }, + $singleton: true, + $statics: { + /** + ** @param fn {Function} + **/ + async: function ( fn ) { + setTimeout(function() { fn(); }, 0 ); + }, + /** + ** @param channel {String} + ** @return {Boolean} + **/ + hasSubscribers: function (channel) { + return ( (this.channels[channel].subscribers).length > 0 ); + } + }, + /** + ** @param channel {String} + ** @goal creates a new channel as well as any subchannels + **/ + createChannel: function ( channel ) { + if ( this.channels[ channel ] ) { + return this; + } else { + this.channels[ channel ] = new Channel( channel, true ); + this.channelsList.push( channel ); + + var len = this.channels[ channel ].subChannels.length, + i = 0; + for ( i = 0; i < len; i++ ) { + if ( !this.channels[ this.channels[ channel ].subChannels[i] ] ) { + this.channels[ this.channels[ channel ].subChannels[i]] = new Channel( this.channels[ channel ].subChannels[i], false ); + this.channelsList.push( this.channels[ channel ].subChannels[i] ); + } + } + return this; + } + }, + /** + ** @param channel {String} + ** @param data {JSON/Object} + **/ + deliver: function( channel, data ) { + var len = this.channels[ channel ].subscribers.length, i = 0; + for ( i = 0; i < len; i++ ) { + if ( this.channels[ channel ].subscribers[i] ) { + this.channels[ channel ].subscribers[i].callback( data ); + } + } + }, + /** + * + * @param channel {String} + * @param data {JSON/Object} + */ + publish: function ( channel, data ) { + if( !this.channels[ channel ] || !this.channels[ channel ].subscribers ) { + return; + } + + if ( this.channels[ channel ].subscribers.length ) { + var len = this.channels[ channel ].subscribers.length, i; + + for ( i = 0; i < len; i++ ) { + if ( this.channels[ channel ].subscribers[i] ) { + this.channels[ channel ].subscribers[i].callback( data ); + } + } + if ( this.channels[ channel ].subChannels.length ) { + len = this.channels[ channel ].subChannels.length; + for ( i = 0; i < len; i++ ) { + this.deliver( this.channels[ channel ].subChannels[i], data ); + } + } + } + }, + /** + * + * @param channel {String} + * @param cb {Function} + * @return {Number} + */ + subscribe: function (channel, cb) { + if(Utils.asteriskEnd( channel )) { + channel = parseChannel( channel ); + } + + if(!this.channels[ channel ]) { + this.createChannel(channel); + } + + if (this.channels[channel].subscribers) { + this.channels[channel].subscribers.push({callback: cb }); + + return this.channels[channel].subscribers.length - 1; + } else { + return null; + } + }, + /** + * + * @param channel {String} + * @param id {Integer} + * @return {Number} + */ + unsubscribe: function ( channel, id ) { + if ( this.channels[ channel ].subscribers[id] ) { + this.channels[ channel ].subscribers[ id ] = 0; + + return this; + } else { + return this; + } + } + }; +}); +/** + * + * @type {Class} + */ +var Channel = Class({ + constructor: function ( channel, original ) { + "use strict"; + this.channel = channel; + this.original = original; + this.subscribers = []; + this.splitter = ':'; + if( this.original ) { + this.subChannels = []; + this.parseTopics(); + } + }, + /** + * + * @return {Boolean} + */ + deleteChannel: function () { + "use strict"; + this.channel = null; + this.original = null; + this.subscribers = null; + this.splitter = null; + this.subChannels = null; + this.parseTopics = null; + this.clearSubs = null; + this.changeChannel = null; + return true; + }, + /** + * @goal Clear current Subscriptions + */ + clearSubs: function () { + "use strict"; + this.subscribers = []; + }, + /** + * + * @param channel + */ + changeChannel: function ( channel ) { + "use strict"; + PubSub.publish( 'pubsub:channels:changeChannel', { prev: this.channel, next: channel }, true ); + + this.channel = channel; + }, + /** + * @goal parse the topics within the channels name such that even the partial subs will recieve the + * channel's messages as expected. + */ + parseTopics: function () { + "use strict"; + var colonIdx = this.channel.indexOf(':'), + dotIdx = this.channel.indexOf('.'); + + if( colonIdx > -1 ) { + this.splitter = ':'; + } else if( dotIdx > -1 ) { + this.splitter = '.'; + } + + var channelArr = this.channel.split(this.splitter); + var len = channelArr.length, + str = '', i = 0, x = 0; + + for ( i = 0; i < ( len - 1 ); i++ ) { + str = ''; + for ( x = 0; x <= i; x++ ) { + + if (x === 0) { + str = channelArr[x]; + } else { + str = str + this.splitter + channelArr[x]; + } + } + this.subChannels.push(str); + } + } +}); diff --git a/pool/shard005/JavaScript/0032975_websockets.test.js b/pool/shard005/JavaScript/0032975_websockets.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a1fdb558dd1efebbabd7c8fac87b383d58a07117 --- /dev/null +++ b/pool/shard005/JavaScript/0032975_websockets.test.js @@ -0,0 +1,149 @@ +import { initialise } from '../../src/services/websockets.js'; +import { expect } from 'chai'; +import thunk from 'redux-thunk'; +import simple from 'simple-mock'; +import { bindActionCreators } from 'redux'; +import { SAVE_SOCKET_CONNECTION_ID, RESET_TAGS } from '../../src/constants/actionTypes'; +import querystring from '../../src/utils/querystring'; +import * as tagActions from '../../src/actions/tags'; +import * as searchActions from '../../src/actions/tags'; +// mock redux store +import configureMockStore from '../actions/test-helpers'; +const mockStore = configureMockStore([thunk]); + +describe('Web Socket Service', function () { + afterEach(() => { + simple.restore(); + }); + it('calls the saveSocketConnectionId action when connection is opened', () => { + const store = mockStore({search: { tags: [], resultId: '1234' }}); + const actionCreatorBinder = actions => bindActionCreators(actions, store.dispatch); + const primus = initialise(actionCreatorBinder, 'search'); + primus.id = (cb) => { cb('abc123'); }; + primus.emit('open'); + let expectedActions = [ + { + type: SAVE_SOCKET_CONNECTION_ID, + id: 'abc123' + }, + { type: RESET_TAGS } + ]; + expect(store.getActions()).to.deep.equal(expectedActions); + }); + it('calls the saveSocketConnectionId action when connection is opened but only calls resetTags if on the home page', () => { + const store = mockStore({search: { tags: [], resultId: '1234' }}); + const actionCreatorBinder = actions => bindActionCreators(actions, store.dispatch); + const primus = initialise(actionCreatorBinder, 'hotel'); + primus.id = (cb) => { cb('abc123'); }; + primus.emit('open'); + let expectedActions = [ + { + type: SAVE_SOCKET_CONNECTION_ID, + id: 'abc123' + } + ]; + expect(store.getActions()).to.deep.equal(expectedActions); + }); + it('performs an autocomplete lookup for a default tag if a query string search parameter is provided', () => { + simple.mock(querystring, 'parse').returnWith({ search: 'family' }); + simple.mock(tagActions, 'searchForTag'); + const store = mockStore({search: { tags: [], resultId: '1234' }}); + const actionCreatorBinder = actions => bindActionCreators(actions, store.dispatch); + const primus = initialise(actionCreatorBinder, 'search'); + primus.id = (cb) => { cb('abc123'); }; + primus.emit('open'); + expect(store.getActions()).not.to.contain({ type: RESET_TAGS }); + expect(tagActions.searchForTag.called).to.be.true; + expect(tagActions.searchForTag.lastCall.args[0]).to.equal('family'); + }); + it('only calls the saveSocketConnectionId action on first connection', () => { + const store = mockStore({search: { tags: [], resultId: '1234' }}); + const actionCreatorBinder = actions => bindActionCreators(actions, store.dispatch); + const primus = initialise(actionCreatorBinder, 'search'); + primus.id = (cb) => { cb('abc123'); }; + primus.emit('open'); + primus.emit('open'); + primus.emit('open'); + let expectedActions = [ + { + type: SAVE_SOCKET_CONNECTION_ID, + id: 'abc123' + }, + { type: RESET_TAGS } + ]; + expect(store.getActions()).to.deep.equal(expectedActions); + }); + it('subscribes to a primus room on connection', () => { + const store = mockStore({search: { tags: [], resultId: '1234' }}); + const actionCreatorBinder = actions => bindActionCreators(actions, store.dispatch); + const primus = initialise(actionCreatorBinder, 'search'); + simple.mock(primus, 'write'); + primus.id = (cb) => { cb('abc123'); }; + primus.emit('open'); + expect(primus.write.callCount).to.equal(1); + expect(primus.write.lastCall.args[0]).to.deep.equal({ action: 'join', room: 'abc123' }); + }); + it('subscribes to the original primus room on reconnection', () => { + const store = mockStore({search: { tags: [], resultId: '1234' }}); + const actionCreatorBinder = actions => bindActionCreators(actions, store.dispatch); + const primus = initialise(actionCreatorBinder, 'search'); + simple.mock(primus, 'write'); + primus.id = (cb) => { cb('abc123'); }; + primus.emit('open'); + expect(primus.write.callCount).to.equal(1); + expect(primus.write.lastCall.args[0]).to.deep.equal({ action: 'join', room: 'abc123' }); + primus.id = (cb) => { cb('def456'); }; + primus.emit('reconnected'); + expect(primus.write.callCount).to.equal(2); + expect(primus.write.lastCall.args[0]).to.deep.equal({ action: 'join', room: 'abc123' }); + }); + it('if there are search results in the data, calls saveSearchResult action', done => { + simple.mock(searchActions, 'saveSearchResult'); + const store = mockStore({search: { tags: [], resultId: 'abc123', displayedItems: [], items: [] }}); + const actionCreatorBinder = actions => bindActionCreators(actions, store.dispatch); + const primus = initialise(actionCreatorBinder, 'search'); + const event = { + graphql: { + searchId: 'abc123', + items: [ + { + name: 'test', + packageOffer: {} + } + ] + } + }; + primus.once('data', data => { + process.nextTick(() => { + expect(searchActions.saveSearchResult.callCount).to.equal(1); + expect(searchActions.saveSearchResult.lastCall.args[0]).to.deep.equal(event); + done(); + }); + }); + primus.emit('data', event); + }); + it('if there are search rankings in the data, calls updateTileRanking action', done => { + simple.mock(searchActions, 'updateTileRanking'); + const store = mockStore({search: { tags: [], resultId: 'abc123', displayedItems: [], items: [] }}); + const actionCreatorBinder = actions => bindActionCreators(actions, store.dispatch); + const primus = initialise(actionCreatorBinder, 'search'); + const event = { + graphql: { + searchId: 'abc123', + ranking: { + a: 1, + b: 0, + c: -1 + } + } + }; + primus.once('data', data => { + process.nextTick(() => { + expect(searchActions.updateTileRanking.callCount).to.equal(1); + expect(searchActions.updateTileRanking.lastCall.args[0]).to.deep.equal(event); + done(); + }); + }); + primus.emit('data', event); + }); +}); diff --git a/pool/shard005/JavaScript/0032977_optimizeNames.js b/pool/shard005/JavaScript/0032977_optimizeNames.js new file mode 100644 index 0000000000000000000000000000000000000000..ab554c98f752c7cff9ab6699817dfc53f3d6526b --- /dev/null +++ b/pool/shard005/JavaScript/0032977_optimizeNames.js @@ -0,0 +1,222 @@ +var atTmpl = require('basisjs-tools-ast').tmpl; + +function toBase52(num){ + var res = ''; + + do { + var n = num % 52; + res = String.fromCharCode((n % 26) + (n < 26 ? 97 : 65)) + res; + num = parseInt(num / 52); + } + while (num); + + return res; +} + +(module.exports = function(flow){ + var fconsole = flow.console; + var themeIdMap = flow.css.idMap; + var themeClassMap = flow.css.classMap; + var totalSaving = 0; + + + // + // class rename + // + + fconsole.start('Process class names'); + + var tmplModule = flow.js.basis && flow.js.basis.template; + var classReplaceMap = {}; + var classReplaceMapIdx = 0; + var classRenameSaving = 0; + var typeSaving = { + html: 0, + style: 0, + tmpl: 0, + 'tmpl-overhead': 0 + }; + + function getClassNameReplace(name){ + if (!hasOwnProperty.call(classReplaceMap, name)) + classReplaceMap[name] = toBase52(classReplaceMapIdx++); + return classReplaceMap[name]; + } + + for (var theme in themeClassMap) + { + fconsole.start(theme); + + var classMap = themeClassMap[theme]; + Object.keys(classMap).filter(function(key){ + return !classMap[key].postfix; + }).sort(function(a, b){ + return (b.length - 1) * classMap[b].length - (a.length - 1) * classMap[a].length; + }).forEach(function processKey(name, idx){ + function replaceFn(cls){ + var result = cls == name ? replace : cls; + if (item.type != 'tmpl-class-binding') + { + var saving = cls.length - result.length; + tokenSaving += saving; + typeSaving['tmpl-overhead'] += saving; + } + return result; + } + function replaceStr(str){ + return str.trim().split(/\s+/).map(replaceFn).join(' '); + } + + var list = classMap[name]; + var replace = getClassNameReplace(name) + list.postfix; + var saving = 0; + + for (var i = 0, item, token; item = list[i]; i++) + { + token = item.token; + tokenSaving = 0; + + switch (item.type){ + case 'html-class': + token.class = replaceStr(token.class); + break; + case 'style-class': + token[2] = replace; + tokenSaving = name.length - replace.length; + break; + case 'tmpl-class': + token.context.tokenValue(token, replaceStr(token.context.tokenValue(token))); + break; + case 'tmpl-class-binding': + tokenSaving = JSON.stringify(token).length; + + atTmpl.setBindingClassNames(tmplModule, token, + atTmpl.getBindingClassNames(tmplModule, token).map(replaceFn) + ); + + tokenSaving -= JSON.stringify(token).length; + + if (tokenSaving < 0) + { + typeSaving['tmpl-overhead'] += -tokenSaving; + tokenSaving = 0; + } + break; + case 'tmpl-class-anim': + // nothing todo + break; + default: + flow.warn({ + fatal: true, + message: 'Unknown token type - ' + cfg.type + }); + } + + saving += tokenSaving; + typeSaving[item.type.split('-')[0]] += tokenSaving; + } + + classRenameSaving += saving; + totalSaving += saving; + fconsole.log(name, '->', replace, '(' + saving + ' / ' + list.length + ')'); + + list.nested.forEach(function(nestedName){ + processKey(nestedName, idx); + }); + }); + + fconsole.endl(); + } + fconsole.endl(); + + classRenameSaving += typeSaving['tmpl-overhead']; + fconsole.start('Total class rename saving:', classRenameSaving + ' bytes'); + fconsole.list(Object.keys(typeSaving).map(function(type){ + return type + ': ' + typeSaving[type] + ' bytes'; + })); + fconsole.endl(); + + + // + // id + // + + fconsole.start('Process `id` attributes (skip)'); + + // ID could affect many things, for example ID uses in url(), + // in SVG attributes like fill or stroke. For now extract doesn't found + // this ID usage. That's why don't change ID until all cases will be localed. + + // var idReplaceMap = {}; + // var idReplaceIdx = 0; + // var idRenameSaving = 0; + // var typeSaving = { + // html: 0, + // style: 0, + // tmpl: 0 + // }; + + // function getIdReplace(name){ + // if (!hasOwnProperty.call(idReplaceMap, name)) + // idReplaceMap[name] = toBase52(idReplaceIdx++); + // return idReplaceMap[name]; + // } + + // for (var theme in themeIdMap) + // { + // fconsole.start(theme); + + // var idMap = themeIdMap[theme]; + // Object.keys(idMap).sort(function(a, b){ + // return (b.length - 1) * idMap[b].length - (a.length - 1) * idMap[a].length; + // }).forEach(function(name, idx){ + // var list = idMap[name]; + // var replace = getIdReplace(name); + // var oneSaving = name.length - replace.length; + // var saving = oneSaving * list.length; + + // idRenameSaving += saving; + // totalSaving += saving; + // fconsole.log(name, '->', replace, '(' + saving + ')'); + + // for (var i = 0, item; item = list[i]; i++) + // { + // var token = item.token; + // typeSaving[item.type.split('-')[0]] += oneSaving; + // switch (item.type){ + // case 'html-id': + // token.id = replace; + // break; + // case 'style-id': + // token[2] = replace; + // break; + // case 'tmpl-id': + // token.context.tokenValue(token, replace); + // break; + // default: + // flow.warn({ + // fatal: true, + // message: 'Unknown token type - ' + cfg.type + // }); + // } + // } + // }); + + // fconsole.endl(); + // } + // fconsole.endl(); + + // fconsole.start('Total id rename saving:', idRenameSaving + ' bytes'); + // fconsole.list(Object.keys(typeSaving).map(function(type){ + // return type + ': ' + typeSaving[type] + ' bytes'; + // })); + // fconsole.endl(); + + // fconsole.start('Total rename saving:', idRenameSaving + ' bytes'); + +}).handlerName = '[css] Optimize names'; + +module.exports.skip = function(flow){ + if (!flow.options.cssOptimizeNames) + return 'Use option --css-optimize-names'; +}; diff --git a/pool/shard005/JavaScript/0032980_44f2db4c3deb241c42229d7dee29124ee3594354.js b/pool/shard005/JavaScript/0032980_44f2db4c3deb241c42229d7dee29124ee3594354.js new file mode 100644 index 0000000000000000000000000000000000000000..13fe264ce69f798e480433a8ef5da171e1c02157 --- /dev/null +++ b/pool/shard005/JavaScript/0032980_44f2db4c3deb241c42229d7dee29124ee3594354.js @@ -0,0 +1,51 @@ +define(['react','underscore','ImageLoader'], function(React,_,ImageLoader) { + console.log(ImageLoader); + var LazyLoadImg=React.createClass({displayName: "LazyLoadImg", + componentDidUpdate: function() { + console.log("algoCambio"); + }, + render:function(){ + return React.createElement(ImageLoader, {src: this.props.img}) + } + + }); + var FeedNoticia = React.createClass({displayName: "FeedNoticia", + getInitialState: function() { + return { + visible:false + }; + }, + componentWillMount:function(){ + console.log("imagen Cargada"); + }, + render: function() { + return React.createElement("article", {className: "Componente_Article"}, + React.createElement("div", {className: "Loader_Noticias"}, + React.createElement("figure", null, React.createElement(LazyLoadImg, {img: this.props.img, alt: this.props.titulo})), + React.createElement("div", {className: "Loader_Noticias-Cont"}, + React.createElement("h1", null, this.props.titulo) + ) + ) + ) + + } + }); + //**Componente Principal - Recibe datos del ajax + var AppNoticiasCA = React.createClass({displayName: 'AppNoticiasCA', + getInitialState: function() { + return { + Noticias:this.props.Noticias, + }; + }, + render: function() { + var Items = _.map(this.state.Noticias, function(item){ + return React.createElement(FeedNoticia, {key: item.clave, id_noticia: item.clave, img: item.grande, sumario: item.sumario, titulo: item.titulo, fecha: item.fecha}) + }); + return React.createElement("div", {className: "ThoyCA_ContMain-MoPrincipal--React"}, + Items + ) + } + }); + window.React = React; + return AppNoticiasCA; +}); \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032982_IconButton.js b/pool/shard005/JavaScript/0032982_IconButton.js new file mode 100644 index 0000000000000000000000000000000000000000..0a9e8d6a0941b85ae835aa87d987f6f6330bc86e --- /dev/null +++ b/pool/shard005/JavaScript/0032982_IconButton.js @@ -0,0 +1,200 @@ +import _extends from "@babel/runtime/helpers/esm/extends"; +import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; +import React from 'react'; +import PropTypes from 'prop-types'; +import clsx from 'clsx'; +import { chainPropTypes } from '@material-ui/utils'; +import withStyles from '../styles/withStyles'; +import { fade } from '../styles/colorManipulator'; +import ButtonBase from '../ButtonBase'; +import capitalize from '../utils/capitalize'; +export var styles = function styles(theme) { + return { + /* Styles applied to the root element. */ + root: { + textAlign: 'center', + flex: '0 0 auto', + fontSize: theme.typography.pxToRem(24), + padding: 12, + borderRadius: '50%', + overflow: 'visible', + // Explicitly set the default value to solve a bug on IE 11. + color: theme.palette.action.active, + transition: theme.transitions.create('background-color', { + duration: theme.transitions.duration.shortest + }), + '&:hover': { + backgroundColor: fade(theme.palette.action.active, theme.palette.action.hoverOpacity), + // Reset on touch devices, it doesn't add specificity + '@media (hover: none)': { + backgroundColor: 'transparent' + } + }, + '&$disabled': { + backgroundColor: 'transparent', + color: theme.palette.action.disabled + } + }, + + /* Styles applied to the root element if `edge="start"`. */ + edgeStart: { + marginLeft: -12, + '$sizeSmall&': { + marginLeft: -3 + } + }, + + /* Styles applied to the root element if `edge="end"`. */ + edgeEnd: { + marginRight: -12, + '$sizeSmall&': { + marginRight: -3 + } + }, + + /* Styles applied to the root element if `color="inherit"`. */ + colorInherit: { + color: 'inherit' + }, + + /* Styles applied to the root element if `color="primary"`. */ + colorPrimary: { + color: theme.palette.primary.main, + '&:hover': { + backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity), + // Reset on touch devices, it doesn't add specificity + '@media (hover: none)': { + backgroundColor: 'transparent' + } + } + }, + + /* Styles applied to the root element if `color="secondary"`. */ + colorSecondary: { + color: theme.palette.secondary.main, + '&:hover': { + backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity), + // Reset on touch devices, it doesn't add specificity + '@media (hover: none)': { + backgroundColor: 'transparent' + } + } + }, + + /* Pseudo-class applied to the root element if `disabled={true}`. */ + disabled: {}, + + /* Styles applied to the root element if `size="small"`. */ + sizeSmall: { + padding: 3, + fontSize: theme.typography.pxToRem(18) + }, + + /* Styles applied to the children container element. */ + label: { + width: '100%', + display: 'flex', + alignItems: 'inherit', + justifyContent: 'inherit' + } + }; +}; +/** + * Refer to the [Icons](/components/icons/) section of the documentation + * regarding the available icon options. + */ + +var IconButton = React.forwardRef(function IconButton(props, ref) { + var _props$edge = props.edge, + edge = _props$edge === void 0 ? false : _props$edge, + children = props.children, + classes = props.classes, + className = props.className, + _props$color = props.color, + color = _props$color === void 0 ? 'default' : _props$color, + _props$disabled = props.disabled, + disabled = _props$disabled === void 0 ? false : _props$disabled, + _props$disableFocusRi = props.disableFocusRipple, + disableFocusRipple = _props$disableFocusRi === void 0 ? false : _props$disableFocusRi, + _props$size = props.size, + size = _props$size === void 0 ? 'medium' : _props$size, + other = _objectWithoutProperties(props, ["edge", "children", "classes", "className", "color", "disabled", "disableFocusRipple", "size"]); + + return React.createElement(ButtonBase, _extends({ + className: clsx(classes.root, className, color !== 'default' && classes["color".concat(capitalize(color))], disabled && classes.disabled, size === "small" && classes["size".concat(capitalize(size))], { + 'start': classes.edgeStart, + 'end': classes.edgeEnd + }[edge]), + centerRipple: true, + focusRipple: !disableFocusRipple, + disabled: disabled, + ref: ref + }, other), React.createElement("span", { + className: classes.label + }, children)); +}); +process.env.NODE_ENV !== "production" ? IconButton.propTypes = { + /** + * The icon element. + */ + children: chainPropTypes(PropTypes.node, function (props) { + var found = React.Children.toArray(props.children).some(function (child) { + return React.isValidElement(child) && child.props.onClick; + }); + + if (found) { + return new Error(['Material-UI: you are providing an onClick event listener ' + 'to a child of a button element.', 'Firefox will never trigger the event.', 'You should move the onClick listener to the parent button element.', 'https://github.com/mui-org/material-ui/issues/13957'].join('\n')); + } + + return null; + }), + + /** + * Override or extend the styles applied to the component. + * See [CSS API](#css) below for more details. + */ + classes: PropTypes.object.isRequired, + + /** + * @ignore + */ + className: PropTypes.string, + + /** + * The color of the component. It supports those theme colors that make sense for this component. + */ + color: PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary']), + + /** + * If `true`, the button will be disabled. + */ + disabled: PropTypes.bool, + + /** + * If `true`, the keyboard focus ripple will be disabled. + * `disableRipple` must also be true. + */ + disableFocusRipple: PropTypes.bool, + + /** + * If `true`, the ripple effect will be disabled. + */ + disableRipple: PropTypes.bool, + + /** + * If given, uses a negative margin to counteract the padding on one + * side (this is often helpful for aligning the left or right + * side of the icon with content above or below, without ruining the border + * size and shape). + */ + edge: PropTypes.oneOf(['start', 'end', false]), + + /** + * The size of the button. + * `small` is equivalent to the dense button styling. + */ + size: PropTypes.oneOf(['small', 'medium']) +} : void 0; +export default withStyles(styles, { + name: 'MuiIconButton' +})(IconButton); \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032983_auth.service.js b/pool/shard005/JavaScript/0032983_auth.service.js new file mode 100644 index 0000000000000000000000000000000000000000..8486a040959c14b8f5cbbbb2aab62783103b6ec8 --- /dev/null +++ b/pool/shard005/JavaScript/0032983_auth.service.js @@ -0,0 +1,151 @@ +'use strict'; + +angular.module('telebumApp') + .factory('Auth', function Auth($location, $rootScope, $http, User, $cookieStore, $q) { + var currentUser = {}; + var currentShow = { + seriesid: '', + added: false + }; + if($cookieStore.get('token')) { + console.log("Making a call for the token"); + currentUser = User.get(); + } + + return { + + /** + * Authenticate user and save token + * + * @param {Object} user - login info + * @param {Function} callback - optional + * @return {Promise} + */ + login: function(user, callback) { + var cb = callback || angular.noop; + var deferred = $q.defer(); + + $http.post('/auth/local', { + username: user.username, + password: user.password + }). + success(function(data) { + $cookieStore.put('token', data.token); + currentUser = User.get(); + deferred.resolve(data); + return cb(); + }). + error(function(err) { + this.logout(); + deferred.reject(err); + return cb(err); + }.bind(this)); + + return deferred.promise; + }, + + /** + * Delete access token and user info + * + * @param {Function} + */ + logout: function() { + $cookieStore.remove('token'); + currentUser = {}; + }, + + /** + * Create a new user + * + * @param {Object} user - user info + * @param {Function} callback - optional + * @return {Promise} + */ + createUser: function(user, callback) { + var cb = callback || angular.noop; + + return User.save(user, + function(data) { + $cookieStore.put('token', data.token); + currentUser = User.get(); + return cb(user); + }, + function(err) { + this.logout(); + return cb(err); + }.bind(this)).$promise; + }, + + /** + * Change password + * + * @param {String} oldPassword + * @param {String} newPassword + * @param {Function} callback - optional + * @return {Promise} + */ + changePassword: function(oldPassword, newPassword, callback) { + var cb = callback || angular.noop; + + return User.changePassword({ id: currentUser._id }, { + oldPassword: oldPassword, + newPassword: newPassword + }, function(user) { + return cb(user); + }, function(err) { + return cb(err); + }).$promise; + }, + + /** + * Gets all available info on authenticated user + * + * @return {Object} user + */ + getCurrentUser: function() { + return currentUser; + }, + + /** + * Check if a user is logged in + * + * @return {Boolean} + */ + isLoggedIn: function() { + return currentUser.hasOwnProperty('role'); + }, + + /** + * Waits for currentUser to resolve before checking if user is logged in + */ + isLoggedInAsync: function(cb) { + if(currentUser.hasOwnProperty('$promise')) { + currentUser.$promise.then(function() { + cb(true); + }).catch(function() { + cb(false); + }); + } else if(currentUser.hasOwnProperty('role')) { + cb(true); + } else { + cb(false); + } + }, + + /** + * Check if a user is an admin + * + * @return {Boolean} + */ + isAdmin: function() { + return currentUser.role === 'admin'; + }, + + /** + * Get auth token + */ + getToken: function() { + return $cookieStore.get('token'); + } + }; + }); diff --git a/pool/shard005/JavaScript/0032984_test_createAndUpdateSessionRestorePoint.js b/pool/shard005/JavaScript/0032984_test_createAndUpdateSessionRestorePoint.js new file mode 100644 index 0000000000000000000000000000000000000000..ab1522c85958deb7492ac43109d92920d29cb2fb --- /dev/null +++ b/pool/shard005/JavaScript/0032984_test_createAndUpdateSessionRestorePoint.js @@ -0,0 +1,141 @@ +/*global chrome, gsIndexedDb, gsSession, getFixture, loadJsFile, assertTrue, FIXTURE_CURRENT_SESSIONS */ +var testSuites = typeof testSuites === 'undefined' ? [] : testSuites; +testSuites.push( + (function() { + 'use strict'; + + const oldVersion = '1.2.34'; + + const tests = [ + // Test create session restore point. Should create a session from the currently open windows + async () => { + // Simulate gsSession.prepareForUpdate + const session1 = await getFixture( + FIXTURE_CURRENT_SESSIONS, + 'currentSession1' + ); + const currentSession = await gsSession.buildCurrentSession(); + currentSession.windows = session1.windows; + const sessionRestorePointAfter = await gsIndexedDb.createOrUpdateSessionRestorePoint( + currentSession, + oldVersion + ); + const isSessionRestorePointValid = + sessionRestorePointAfter.windows[0].tabs.length === 5; + return assertTrue(isSessionRestorePointValid); + }, + + // Test create session restore point when session restore point already exists from same session + async () => { + // Create a session restore point + const session1 = await getFixture( + FIXTURE_CURRENT_SESSIONS, + 'currentSession1' + ); + const currentSession1 = await gsSession.buildCurrentSession(); + currentSession1.windows = session1.windows; + await gsIndexedDb.createOrUpdateSessionRestorePoint( + currentSession1, + oldVersion + ); + const newSessionRestorePointBefore = await gsIndexedDb.fetchSessionBySessionId( + currentSession1.sessionId + ); + const isSessionRestorePointBeforeValid = + newSessionRestorePointBefore.windows[0].tabs.length === 5; + + const session2 = await getFixture( + FIXTURE_CURRENT_SESSIONS, + 'currentSession1' + ); + const currentSession2 = await gsSession.buildCurrentSession(); + currentSession2.windows = session2.windows; + currentSession2.windows[0].tabs.push({ + id: 7777, + title: 'testTab', + url: 'https://test.com', + }); + const sessionRestorePointAfter = await gsIndexedDb.createOrUpdateSessionRestorePoint( + currentSession2, + oldVersion + ); + const sessionRestorePointAfterValid = + sessionRestorePointAfter.windows[0].tabs.length === 6; + + const gsTestDb = await gsIndexedDb.getDb(); + const sessionRestoreCount = await gsTestDb + .query(gsIndexedDb.DB_SAVED_SESSIONS) + .filter(gsIndexedDb.DB_SESSION_PRE_UPGRADE_KEY, oldVersion) + .execute() + .then(o => o.length); + + return assertTrue( + isSessionRestorePointBeforeValid && + sessionRestorePointAfterValid && + sessionRestoreCount === 1 + ); + }, + + // Test create session restore point when session restore point already exists from another session + async () => { + // Create a session restore point (uses current session based on gsSession.getSessionId) + const session1 = await getFixture( + FIXTURE_CURRENT_SESSIONS, + 'currentSession1' + ); + const currentSession1 = await gsSession.buildCurrentSession(); + currentSession1.windows = session1.windows; + const oldCurrentSessionId = currentSession1.sessionId; + const sessionRestorePointBefore = await gsIndexedDb.createOrUpdateSessionRestorePoint( + currentSession1, + oldVersion + ); + const isSessionRestorePointBeforeValid = + sessionRestorePointBefore.windows[0].tabs.length === 5; + + // Simulate an extension restart by resetting gsSession sessionId and saving a new 'current session' + await loadJsFile('gsSession'); + const session2 = await getFixture( + FIXTURE_CURRENT_SESSIONS, + 'currentSession1' + ); + const currentSession2 = await gsSession.buildCurrentSession(); + const newCurrentSessionId = currentSession2.sessionId; + const isCurrentSessionIdChanged = + oldCurrentSessionId !== newCurrentSessionId; + + currentSession2.windows = session2.windows; + currentSession2.windows[0].tabs.push({ + id: 7777, + title: 'testTab', + url: 'https://test.com', + }); + const sessionRestorePointAfter = await gsIndexedDb.createOrUpdateSessionRestorePoint( + currentSession2, + oldVersion + ); + const sessionRestorePointAfterValid = + sessionRestorePointAfter.windows[0].tabs.length === 6; + + const gsTestDb = await gsIndexedDb.getDb(); + const sessionRestoreCount = await gsTestDb + .query(gsIndexedDb.DB_SAVED_SESSIONS) + .filter(gsIndexedDb.DB_SESSION_PRE_UPGRADE_KEY, oldVersion) + .execute() + .then(o => o.length); + + return assertTrue( + isSessionRestorePointBeforeValid && + isCurrentSessionIdChanged && + sessionRestorePointAfterValid && + sessionRestoreCount === 1 + ); + }, + ]; + + return { + name: 'Session Restore Points', + tests, + }; + })() +); diff --git a/pool/shard005/JavaScript/0032986_color-scheme.js b/pool/shard005/JavaScript/0032986_color-scheme.js new file mode 100644 index 0000000000000000000000000000000000000000..e063a3563d7a688fde91356b0cf4fb803044719b --- /dev/null +++ b/pool/shard005/JavaScript/0032986_color-scheme.js @@ -0,0 +1,113 @@ +ludo.colorPicker.ColorScheme = new Class({ + Extends: ludo.View, + useController:true, + type:'colorPicker.ColorScheme', + + elCss:{ + 'border-top': '1px solid #383838' + }, + colorBoxes:[], + currentColorCount : undefined, + + colors:undefined, + stateful:true, + statefulProperties:['colors'], + + __construct:function(config){ + this.parent(config); + if(config.colors !== undefined)this.colors = config.colors; + }, + __rendered:function(){ + this.parent(); + this.colorObj = new ludo.color.Color(); + this.$b().html('
    Generate color scheme using the buttons below
    '); + if(this.colors !== undefined){ + this.renderColorBoxes(this.colors); + } + }, + + createDefaultColorBoxes:function(){ + this.$b().html(''); + var c = jQuery('
    '); + this.$b().append(c); + + c.css('height', '100%'); + c.css('width', '2000px'); + for(var i=0;i<9;i++){ + var box = this.colorBoxes[i] = jQuery(''); + + box.on('click', this.boxClick.bind(this)); + c.append(box); + } + }, + + boxClick:function(e){ + this.fireEvent('setColor', jQuery(e.target).attr("title")); + }, + + generateMonochromaticScheme:function(color){ + var colors = this.getColorsBySaturation(color, [-28,-21,-14,-7,0,7,14,21,28]); + this.renderColorBoxes(colors); + }, + + generateComplementaryScheme:function(color){ + var colors = this.getColors(color, [-15,0,15,165,180,195]); + this.renderColorBoxes(colors); + }, + + generateTriadScheme:function(color){ + var colors = this.getColors(color, [0,120,240]); + this.renderColorBoxes(colors); + }, + + generateSplitComplementary:function(color){ + var colors = this.getColors(color, [0,160,200]); + this.renderColorBoxes(colors); + }, + + showBoxes:function(howMany){ + for(var i=0;i=0;i--){ + this.colorBoxes[i].css('backgroundColor', colors[i]); + this.colorBoxes[i].attr("title", colors[i]); + + } + this.colors = colors; + this.fireEvent('state'); + }, + + getColors:function(startColor, offsets){ + var ret = []; + for(var i=0;i=360)h-=360; + if(h<0)h+=360; + ret.push(this.colorObj.rgbCode({ h: h, s : startColor.s, v: startColor.v })); + } + return ret; + }, + + getColorsBySaturation:function(startColor, offsets){ + var ret = []; + for(var i=0;i=100)s-=100; + if(s<0)s+=100; + ret.push(this.colorObj.rgbCode({ h: startColor.h, s : s, v: startColor.v })); + } + return ret; + } +}); \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032992_user.service.spec.js b/pool/shard005/JavaScript/0032992_user.service.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..2741aa649471a6e656136bd482a2a323e066a9b2 --- /dev/null +++ b/pool/shard005/JavaScript/0032992_user.service.spec.js @@ -0,0 +1,39 @@ +/** + * Created by niraj on 9/12/2016. + */ + +describe('UserService', function(){ + + var values, service; + beforeEach(function(){ + module('movieflix'); + + inject(function($injector){ + service = $injector.get('userService'); + + }) + }) + + var userservice + it('should post data (string)', inject(function($http,$httpBackend) { + var $scope = {}; + + /* Code Under Test */ + $http.post('http://localhost/3005/user/auth', { + username: 'ali', + password: 'password' + }) + .success(function(data, status, headers, config) { + $scope.user = data; + }); + /* End Code */ + + $httpBackend + .when('POST', 'http://localhost/3005/user/auth', '{"username":"ali","password":"password"}') + .respond({ + username: 'ali' + }); + $httpBackend.flush(); + expect($scope.user).toEqual({ username: 'ali' }); + })); +}) diff --git a/pool/shard005/JavaScript/0032994_sad-editor.js b/pool/shard005/JavaScript/0032994_sad-editor.js new file mode 100644 index 0000000000000000000000000000000000000000..14d62eebf38a3466f02879367824088251d9482d --- /dev/null +++ b/pool/shard005/JavaScript/0032994_sad-editor.js @@ -0,0 +1,182 @@ +'use babel'; +import { + TextEditor +} from 'atom'; +import AutoFormatter from './auto-formatter'; +import Renumberer from './renumberer'; + +// ---------------------------------------------------------------- +// SadEditor +// ---------------------------------------------------------------- +export default class SadEditor { + // アクティブエディタのgrammarがsadのときアクティブエディタを返す。 + // そうでない場合はnullを返す。 + static getActiveSadEditor() { + let editor = atom.workspace.getActiveTextEditor(); + if (!(editor instanceof TextEditor)) return null; + if ("source.sad" !== editor.getGrammar().scopeName) return null; + if (editor.sadEditor === undefined) + editor.sadEditor = new SadEditor(editor); + return editor.sadEditor + } + + static findSadEditor(filepath) { + let editors = atom.workspace.getTextEditors(); + for (let i = 0; i < editors.length; i++) { + let editor = editors[i]; + if (editor instanceof TextEditor) + if ("source.sad" === editor.getGrammar().scopeName) + if (filepath === editor.getPath()) + return new SadEditor(editor); + } + return null; + } + + constructor(editor) { + this.editor = editor; + this.buffer = editor.getBuffer(); + this.suppressAutoFormat = false; + this.cursorRow = editor.getCursorBufferPosition().row; + } + + statementInfoByRow(row) { + let info = { + byRow: row + }; + + // 命題行を探す + for (let r = row; r >= 0; r--) { + let line = this.buffer.lineForRow(r); + + // 命題行に出会ったらinfoに情報を保存する + let matches = line.match(reStatement); + if (matches) { + info.localId = matches[1]; + info.firstRow = r; + break; + } + } + if (info.firstRow === undefined) return null; + + // 属性行の範囲を調べる + info.lastRow = info.firstRow; + for (let r = info.firstRow + 1; r <= this.buffer.getLastRow(); r++) { + let line = this.buffer.lineForRow(r); + + // 空行または命題行に出会ったら属性行は終わり + if (line.match(reEmpty)) break; + if (line.match(reStatement)) break; + + // lineは属性行だったのでinfo.lastRowを更新 + info.lastRow = r; + } + + return info; + } + + selectStatementBlockByRow(row) { + // 指定行が命題に所属するかどうか調べる + let statementInfo = this.statementInfoByRow(row); + if (statementInfo === null) return; + + // 属性行を含めた命題の範囲を選択する + let firstRange = this.buffer.rangeForRow(statementInfo.firstRow); + let lastRange = this.buffer.rangeForRow(statementInfo.lastRow); + let range = firstRange.union(lastRange); + this.editor.setSelectedBufferRange(range); + } + + cursorStatementId() { + let statementInfo = this.statementInfoByRow( + this.editor.getCursorBufferPosition().row); + if (statementInfo === null) return null; + return statementInfo.localId; + } + + indent() { + // 選択範囲が長さゼロときカーソルのある命題行とすべての属性行を選択する + if (this.editor.getSelectedText().length === 0) { + let cursorRow = this.editor.getCursorBufferPosition().row; + this.selectStatementBlockByRow(cursorRow); + } + + // 標準エディタのインデント処理を呼び出す + this.editor.indentSelectedRows(); + } + + outdent() { + // 選択範囲が長さゼロときカーソルのある命題行とすべての属性行を選択する + if (this.editor.getSelectedText().length === 0) { + let cursorRow = this.editor.getCursorBufferPosition().row; + this.selectStatementBlockByRow(cursorRow); + } + + // 標準エディタのインデント処理を呼び出す + this.editor.outdentSelectedRows(); + } + + undo() { + // 標準のUndo処理を呼び出す + this.buffer.undo(); + + // Undo後またはRedo後は自動整形しない + this.suppressAutoFormat = true; + } + + redo() { + // 標準のRedo処理を呼び出す + this.buffer.redo(); + + // Undo後またはRedo後は自動整形しない + this.suppressAutoFormat = true; + } + + onDidStopChanging() { + // Undo直後またはRedo直後にもonDidStopChanging()が1回呼ばれるので、 + // 自動整形せずにsuppressAutoFormatをクリアしておく + if (this.suppressAutoFormat) { + this.suppressAutoFormat = false; + return; + } + + // 自動整形する + this.autoFormat(); + } + + onDidChangeGrammar() { + // 自動整形する + this.autoFormat(); + } + + onDidChangeCursorPosition() { + // 自動整形する + this.autoFormat(); + } + + autoFormat() { + // カーソルが同じ行にいる間の編集は無視する + let row = this.editor.getCursorBufferPosition().row; + if (row == this.cursorRow) return; + this.cursorRow = row; + + // doAll()を1回のUndoで戻せるように1つのtransactionにまとめる + let formatter = new AutoFormatter(this.editor); + this.buffer.transact(function() { + formatter.doAll(); + }); + + // autoFormat()自身によるonDidChanging()を抑制する + this.suppressAutoFormat = true; + } + + renumber() { + // do()を1回のUndoで戻せるように1つのtransactionにまとめる + let renumberer = new Renumberer(this.editor); + this.buffer.transact(function() { + renumberer.do(); + }); + } +} + +const reEmpty = /^\s*$/; +const reStatement = /^\s*\[(\d*)\]\s*.*$/; diff --git a/pool/shard005/JavaScript/0032995_codemirrorSpec.js b/pool/shard005/JavaScript/0032995_codemirrorSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..373a31dff2587c5f3288da1531fef0edcf1f6f6b --- /dev/null +++ b/pool/shard005/JavaScript/0032995_codemirrorSpec.js @@ -0,0 +1,136 @@ +/*global beforeEach, afterEach, describe, it, inject, expect, module, spyOn, CodeMirror, angular, $*/ +/** + * TODO Test all the CodeMirror events : cursorActivity viewportChange gutterClick focus blur scroll update. + * with ')($rootScope); + } + + expect(compile).not.toThrow(); + }); + + it('should throw an error when no ngModel attribute defined', function () { + function compile() { + $compile('')($rootScope); + } + + expect(compile).toThrow(); + }); + + it('should watch the uiCodemirror attribute', function () { + spyOn($rootScope, '$watch'); + $compile('')($rootScope); + $timeout.flush(); + expect($rootScope.$watch).toHaveBeenCalled(); + }); + + // Sorry I'm not enough familiar Jasmine to fix this... + /* + it('should include the passed options', function () { + spyOn(CodeMirror, 'fromTextArea'); + $compile('')($rootScope); + expect(CodeMirror.fromTextArea.mostRecentCall.args[1].foo).toEqual('bar'); + }); + + it('should include the default options', function () { + spyOn(CodeMirror, 'fromTextArea'); + $compile('')($rootScope); + expect(CodeMirror.fromTextArea.mostRecentCall.args[1].bar).toEqual('baz'); + }); + */ + }); + + describe('when the model changes', function () { + it('should update the IDE', function () { + var element = $compile('')($rootScope); + $rootScope.foo = 'bar'; + $rootScope.$apply(); + $timeout.flush(); + expect($.trim(element.siblings().text())).toBe($rootScope.foo); + }); + }); + + describe('when the IDE changes', function () { + it('should update the model', function () { + var codemirror, + fromTextArea = CodeMirror.fromTextArea; + spyOn(CodeMirror, 'fromTextArea').andCallFake(function () { + codemirror = fromTextArea.apply(this, arguments); + return codemirror; + }); + $compile('')($rootScope); + $rootScope.foo = 'bar'; + $rootScope.$apply(); + $timeout.flush(); + var value = 'baz'; + codemirror.setValue(value); + expect($rootScope.foo).toBe(value); + }); + }); + + describe('when the model is undefined/null', function () { + it('should update the IDE with an empty string', function () { + var element = $compile('')($rootScope); + $rootScope.$apply(); + expect($rootScope.foo).toBe(undefined); + expect($.trim(element.siblings().text())).toBe(''); + $rootScope.foo = null; + $rootScope.$apply(); + expect($rootScope.foo).toBe(null); + expect($.trim(element.siblings().text())).toBe(''); + }); + }); + + describe('when the model is an object or an array', function () { + it('should throw an error', function () { + function compileWithObject() { + $compile('')($rootScope); + $timeout.flush(); + $rootScope.foo = {}; + $rootScope.$apply(); + } + + function compileWithArray() { + $compile('')($rootScope); + $timeout.flush(); + $rootScope.foo = []; + $rootScope.$apply(); + } + + expect(compileWithObject).toThrow(); + expect(compileWithArray).toThrow(); + }); + }); +}); \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032997_exposure-minus-1.js b/pool/shard005/JavaScript/0032997_exposure-minus-1.js new file mode 100644 index 0000000000000000000000000000000000000000..4a16d526e460603bb6f2d0bd7489e05316026eca --- /dev/null +++ b/pool/shard005/JavaScript/0032997_exposure-minus-1.js @@ -0,0 +1,32 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _reactIconBase = require('react-icon-base'); + +var _reactIconBase2 = _interopRequireDefault(_reactIconBase); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var MdExposureMinus1 = function MdExposureMinus1(props) { + return _react2.default.createElement( + _reactIconBase2.default, + _extends({ viewBox: '0 0 40 40' }, props), + _react2.default.createElement( + 'g', + null, + _react2.default.createElement('path', { d: 'm31.6 30h-3.2v-17.7l-5 1.7v-2.8l7.8-2.8h0.4v21.6z m-25-11.6h13.4v3.2h-13.4v-3.2z' }) + ) + ); +}; + +exports.default = MdExposureMinus1; +module.exports = exports['default']; \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032998_index.txt.js b/pool/shard005/JavaScript/0032998_index.txt.js new file mode 100644 index 0000000000000000000000000000000000000000..64642e7a13921af4c442e15172a401a7127e6d5c --- /dev/null +++ b/pool/shard005/JavaScript/0032998_index.txt.js @@ -0,0 +1,34 @@ +(function() { + $(function() { + var collapseMyMenu, expandMyMenu, hideMenuTexts, showMenuTexts; + expandMyMenu = function() { + return $("nav.sidebar").removeClass("sidebar-menu-collapsed").addClass("sidebar-menu-expanded"); + }; + collapseMyMenu = function() { + return $("nav.sidebar").removeClass("sidebar-menu-expanded").addClass("sidebar-menu-collapsed"); + }; + showMenuTexts = function() { + return $("nav.sidebar ul a span.expanded-element").show(); + }; + hideMenuTexts = function() { + return $("nav.sidebar ul a span.expanded-element").hide(); + }; + return $("#justify-icon").click(function(e) { + if ($(this).parent("nav.sidebar").hasClass("sidebar-menu-collapsed")) { + expandMyMenu(); + showMenuTexts(); + $(this).css({ + color: "#000" + }); + } else if ($(this).parent("nav.sidebar").hasClass("sidebar-menu-expanded")) { + collapseMyMenu(); + hideMenuTexts(); + $(this).css({ + color: "#FFF" + }); + } + return false; + }); + }); + +}).call(this); \ No newline at end of file diff --git a/pool/shard005/JavaScript/0032999_TestUtils.js b/pool/shard005/JavaScript/0032999_TestUtils.js new file mode 100644 index 0000000000000000000000000000000000000000..193f2da63794cfb1945928c7d81de1896723dac3 --- /dev/null +++ b/pool/shard005/JavaScript/0032999_TestUtils.js @@ -0,0 +1,77 @@ +var + CeresTree= require("ceres").CeresTree, + TargetParseContext= require("../../lib/TargetParseContext"), + MetricsStore= require("../../lib/MetricsStore"); + +function buildTargetParseContext( targetString, metrics, metricValues, tInfo, from, to) { + var realMetrics= {}; + var firstK= null; + for( var k in metrics ) { + if( firstK == null ) firstK= metrics[k].name; + realMetrics[metrics[k].name]= metrics[k]; + realMetrics[metrics[k].name].info= {aggregationMethod: "avg"}; + realMetrics[metrics[k].name].filename= metrics[k].name; + + realMetrics[metrics[k].name].node = (function(name){ + return { + read: function( from, to, cb ) { + cb( null, {startTime:tInfo[0], endTime:tInfo[1], timeStep:tInfo[2], values:(metricValues === undefined || metricValues[name] === undefined ) ? []:metricValues[name]}); + }}; + })(metrics[k].name); + } + + + if( tInfo === undefined ) { + var t= Math.floor( new Date().getTime() / 1000 ); + var interval= 10; + var f= t - ( metricValues[firstK].length * interval); + tInfo= [f, t, interval]; + } + if( from === undefined ) from= 0; + if( to === undefined ) to= 0; + + var ms= new MetricsStore( "/tmp" ); + ms.availableMetrics= realMetrics; + return new TargetParseContext( ms, targetString, from, to ) ; +} + +function populateRealMetricsStore( storedData, cb ) { + var tmp_dir= "tree_" + new Date().getTime(); + CeresTree.create(tmp_dir, function(err, tree) { + if( err ) { cb(err); } + else { + var keys=[]; + for(var k in storedData) { keys.push(k); } + function popNext() { + if( keys.length == 0 ) { + var metricsStore= new MetricsStore(tree.root, function(err) { + if( err ) { cb(err); } + else { + metricsStore.getAvailableMetrics( function(err) { + cb( err, metricsStore ); + }); + } + }); + } + else { + var key= keys.shift(); + tree.createNode(key, {}, function(err, node) { + if( err ) { cb(err); } + else { + node.write(storedData[key].data, function(err) { + if( err ) { cb(err); } + else { + setImmediate( popNext ); + } + }); + } + }); + } + } + popNext(); + } + }); +}; + +module.exports.buildTargetParseContext= buildTargetParseContext; +module.exports.populateRealMetricsStore= populateRealMetricsStore; \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033001_arrow.js b/pool/shard005/JavaScript/0033001_arrow.js new file mode 100644 index 0000000000000000000000000000000000000000..1d62505bad4e29818d6dce9bb40eea1dba98484c --- /dev/null +++ b/pool/shard005/JavaScript/0033001_arrow.js @@ -0,0 +1,34 @@ +// Why Arrow Functions? +// Arrow function is a way to write anonymous functions which gives you to write a clear syntex with less keywords. + +// Anonymous function in ES5 +var f = function(data) { return data } + +//Anonymous function in ES6 +let f2 = (data) => { return data } + + +//Drwabacks in ES5 +// keyword "this" can change value when create a new function and it give a scope which use to confuse everyone but now in ES6 +// you cannot use keyword "that = this OR self = this or _this = this OR .bind(this)" because ES6 Arrow function have its own lexical this and also because of lexical this we cannot use Arrow function as a constructor and we cannot use like bind() or call() it itself increase verbosity + + +//Example + + function circleArea(r) { + var PI = 3.14; + return PI * r * r; + } + + console.log("Normal function execution r is : " + circleArea(7)); + + let circleArea2 = (r) => { + const PI = 3.14; + return PI * r * r; + } + + console.log("\nFat Arrow function execution r is : " + circleArea2(7)); + + + let circleArea3 = r => 3.14 * r * r; // if we have single parameter we can write this also. + console.log("\nFat Arrow function one line execution r is : " + circleArea3(7)); diff --git a/pool/shard005/JavaScript/0033002_wordnet_spec.js b/pool/shard005/JavaScript/0033002_wordnet_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..38dd83b1a7f3bc3899200ca60d98e13108ce0641 --- /dev/null +++ b/pool/shard005/JavaScript/0033002_wordnet_spec.js @@ -0,0 +1,74 @@ +/* +Copyright (c) 2011, Chris Umbel + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +'use strict' + +const WordNet = require('lib/natural/wordnet/wordnet') + +describe('wordnet', function () { + it('should lookup synonyms', function (done) { + const wordnet = new WordNet() + + wordnet.lookupSynonyms('entity', function (records) { + expect(records.length).toBe(3) + done() + }) + }) + + function expectResults (records) { + expect(records.length).toBe(3) + expect(records[0].synsetOffset).toBe(4431553) + expect(records[1].synsetOffset).toBe(2137) + expect(records[2].synsetOffset).toBe(1930) + } + + it('should lookup synonyms give a synset offset and a pos', function (done) { + const wordnet = new WordNet() + + wordnet.getSynonyms(1740, 'n', function (records) { + expectResults(records) + done() + }) + }) + + it('should lookup synonyms via a provided synset object', function (done) { + const wordnet = new WordNet() + + wordnet.lookup('entity', function (results) { + wordnet.getSynonyms(results[0], function (records) { + expectResults(records) + done() + }) + }) + }) + + it('should add records but once', function (done) { + const wordnet = new WordNet() + + wordnet.lookup('node', function (records) { + expect(records.length).toBe(8) + expect(records[0].lemma).toBe('node') + + done() + }) + }) +}) diff --git a/pool/shard005/JavaScript/0033003_link.js b/pool/shard005/JavaScript/0033003_link.js new file mode 100644 index 0000000000000000000000000000000000000000..c5eb450a8c116c8068f1e4f8354fa2dca22cc109 --- /dev/null +++ b/pool/shard005/JavaScript/0033003_link.js @@ -0,0 +1,207 @@ +const Boom = require('boom') +const server = require('../').hapi +const log = require('../helpers/logger') +const fieldsParser = require('../helpers/fieldsParser') +const Link = require('../db/link') +const _ = require('underscore') +const Achievement = require('../db/achievement') + +server.method('link.create', create, {}) +server.method('link.update', update, {}) +server.method('link.get', get, {}) +server.method('link.list', list, {}) +server.method('link.remove', remove, {}) +server.method('link.checkCompany', checkCompany, {}) + +function create (companyId, link, cb) { + let _link = { + company: companyId, + edition: link.editionId, + user: link.userId, + attendee: link.attendeeId, + updated: Date.now(), + created: Date.now(), + notes: link.notes === undefined ? { + contacts: { + email: '', + phone: '' + }, + interestedIn: undefined, + degree: undefined, + availability: undefined, + otherObservations: undefined + } + : { + contacts: { + email: link.notes.contacts !== undefined && + link.notes.contacts.email !== undefined + ? link.notes.contacts.email + : '', + phone: link.notes.contacts !== undefined && + link.notes.contacts.email !== undefined + ? link.notes.contacts.phone + : '' + }, + interestedIn: link.notes.interestedIn, + degree: link.notes.degree, + availability: link.notes.availability, + otherObservations: link.notes.otherObservations + } + } + + Link.create(_link, (err, newlink) => { + if (err) { + if (err.code === 11000) { + log.error({ link: _link }, `Link is a duplicate`) + return cb(Boom.conflict(`Link is a duplicate`)) + } + + log.error({ err: err, link: newlink }, 'error creating link') + return cb(Boom.internal()) + } + + cb(null, newlink.toObject({ getters: true })) + }) +} + +function update (filter, editionId, link, cb) { + log.debug({ filter: filter, edition: editionId, link: link }, 'updating link') + + filter = { + company: filter.companyId, + edition: editionId, + attendee: filter.attendeeId + } + + link.updated = Date.now() + + Link.findOneAndUpdate(filter, link, (err, _link) => { + if (err) { + log.error({ err: err, link: filter }, 'error updating link') + return cb(Boom.internal()) + } + if (!_link) { + log.error({ err: err, link: filter }, 'error updating link') + return cb(Boom.notFound()) + } + + cb(null, _link.toObject({ getters: true })) + }) +} + +function get (filter, editionId, cb) { + log.debug({ filter: filter, edition: editionId }, 'getting link') + + filter = { + company: filter.companyId, + edition: editionId, + attendee: filter.attendeeId + } + + Link.findOne(filter, (err, link) => { + if (err) { + log.error({ err: err, link: filter }, 'error getting link') + return cb(Boom.internal('error getting link')) + } + if (!link) { + log.error({ err: 'not found', link: filter }, 'link not found') + return cb(Boom.notFound('link not found')) + } + + cb(null, link.toObject({ getters: true })) + }) +} + +function list (filter, query, cb) { + log.debug({ filter: filter }, 'list link') + + cb = cb || query // fields is optional + + if (typeof filter === 'string') { + filter = { company: filter } + } + + if (query && query.editionId) { + filter.edition = query.editionId + } + + const fields = fieldsParser(query.fields) + const options = { + skip: query.skip, + limit: query.limit, + sort: fieldsParser(query.sort) + } + + Link.find(filter, fields, options, (err, links) => { + if (err) { + log.error({ err: err }, 'error getting all links') + return cb(Boom.internal()) + } + + let achFilter = { + 'validity.to': + { '$gt': new Date('January 1, 2021 00:00:00').toISOString() }, + 'kind': 'cv' + } + + log.debug({ filter: filter }, 'finding achievements') + + Achievement.findOne(achFilter, (err, achievement) => { + if (err) { + log.error({ err: err }, 'error getting achievements') + return cb(Boom.internal()) + } + + let objLinks = Array.from(links, (l) => { return l.toObject() }) + + objLinks.forEach( + (l) => { l.cv = achievement ? achievement.toObject().users.includes(l.attendee) : false }) + + cb(null, objLinks) + }) + }) +} + +function remove (filter, editionId, cb) { + log.debug({ filter: filter, edition: editionId }, 'removing link') + + filter = { + company: filter.companyId, + edition: editionId, + attendee: filter.attendeeId + } + + Link.findOneAndRemove(filter, (err, link) => { + if (err) { + log.error({ err: err, link: editionId }, 'error deleting link') + return cb(Boom.internal()) + } + if (!link) { + log.error({ err: 'not found', link: editionId }, 'error deleting link') + return cb(Boom.notFound('link not found')) + } + + return cb(null, link) + }) +} + +// Checks if the user is/was part of the company whose link he trying accessing +function checkCompany (userId, companyId, editionId, cb) { + server.methods.user.get({ id: userId }, (err, user) => { + if (err) { + log.error({ err: err, user: userId }, 'error getting user') + return cb(Boom.internal()) + } + + if (!user) { + log.error({ err: 'not found', user: userId }, 'error getting user') + return cb(Boom.notFound('user not found')) + } + + if (_.findWhere(user.company, { company: companyId, edition: editionId })) { + return cb(null, true) + } + log.error({company: companyId, user: userId, edition: editionId, userCompany: user.company}, 'company not found') + return cb(Boom.notFound('company not found')) + }) +} diff --git a/pool/shard005/JavaScript/0033004_MapFileParser.js b/pool/shard005/JavaScript/0033004_MapFileParser.js new file mode 100644 index 0000000000000000000000000000000000000000..a9626d6621268d4f2c0628a2959b34cb9de9f7ac --- /dev/null +++ b/pool/shard005/JavaScript/0033004_MapFileParser.js @@ -0,0 +1,70 @@ +/*jslint bitwise: true*/ +goog.require('Odyssey.Model.Matrix3D'); +goog.provide('Odyssey.Model.MapFileParser'); +Odyssey.Model.MapFileParser = (function () { + "use strict"; + /** + * Creates a new MapFileParser. A parser to parse Odyssey MapFiles. + * @constructor + */ + function MapFileParser() { + this.tilePosition = new Odyssey.Model.Matrix3D(0, 0, 0); + } + + /** + * Gets a tile's index within the object. This refers + * to the tile's array index inside the Explored property + * of the JSON object. + * @param {Number} posx The x-position of the tile, relative to the base X position. + * @param {Number} posy The y-position of the tile, relative to the base Y position. + * @returns {Number} The index corresponding to the number which contains the Explored flag of the tile. + */ + MapFileParser.getTileIndex = function (posx, posy) { + return Math.floor((posy / 32) + (posx << 3)); + }; + + /** + * Gets a tile's binary offset within the object. This refers + * to the tile's offset inside the Explored integer corresponding + * to the tile. + * @param {Number} posx The x-position of the tile. + * @param {Number} posy The y-position of the tile. + * @returns {Number} The tile's index within an Explored bit flag set. + */ + MapFileParser.getTileOffset = function (posx, posy) { + return (posy % 32); + }; + + /** + * Parses a JSON-deserialized object from a file and fixes the data + * according to Odyssey's map structure. + * @param {Object} map the JSON-deserialized object parsed from a file. + * @returns {Object|Null} the parsed map. + */ + MapFileParser.prototype.parse = function (map) { + var x, y, explored, tileMap, mapReplacement = [], i = 0, baseX, baseY; + + if (!map) { + return null; + } + + explored = map.Explored; + tileMap = map.Map; + baseX = map.BaseX; + baseY = map.BaseY; + + // Recreate the map structure. + for (x = 255; x >= 0; x -= 1) { + for (y = 255; y >= 0; y -= 1) { + if ((explored[MapFileParser.getTileIndex(x, y)] >> MapFileParser.getTileOffset(x, y)) & 0x1) { + i += 1; + mapReplacement[(x << 8) + y] = tileMap[tileMap.length - i]; + } + } + } + map.Map = mapReplacement; + return map; + }; + + return MapFileParser; +}()); diff --git a/pool/shard005/JavaScript/0033007_main.js b/pool/shard005/JavaScript/0033007_main.js new file mode 100644 index 0000000000000000000000000000000000000000..100f25a1fa6c443eb94e3960f5a378407506c8ce --- /dev/null +++ b/pool/shard005/JavaScript/0033007_main.js @@ -0,0 +1,74 @@ +// The Jikken Shading Language Transpiler +// +// Copyright (c) 2017 Jeffrey Hutchinson +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +var shader = require('./lib/processShader'); +var gatherPass = require('./lib/gatherPass'); + +function main(argv) { + if (argv.length < 4) { + console.log("Usage: node main.js --vertex --fragment ") + return; + } + + var shaders = []; + + for (var i = 0; i < argv.length; i++) { + switch (argv[i]) { + case '--vertex': + if (i+1 == argv.length) { + console.log("Next argument must be a vertex shader file."); + return; + } + + shaders.push({ + type: 'VERTEX', + file: argv[i + 1] + }); + i++; + break; + case '--fragment': + if (i+1 == argv.length) { + console.log("Next argument must be a fragment shader file.") + return; + } + + shaders.push({ + type: 'FRAGMENT', + file: argv[i + 1] + }); + break; + } + } + + shaders.forEach((sh) => { + shader.processShader(sh); + var gatherPassTokens = gatherPass.gatherPass(shader.lex); + shader.rewindLex(); + + console.log("Shader: " + sh.file); + console.log(JSON.stringify(gatherPassTokens)); + + shader.resetLex(); + }); +} + +main(process.argv); diff --git a/pool/shard005/JavaScript/0033010_config.js b/pool/shard005/JavaScript/0033010_config.js new file mode 100644 index 0000000000000000000000000000000000000000..27b9bd73736cbed3ceb13e6ea5a90ca8ad7b63dd --- /dev/null +++ b/pool/shard005/JavaScript/0033010_config.js @@ -0,0 +1,91 @@ +'use strict'; +/* jshint node:true */ +/* global module, process, console, require */ + +var osenv = require('osenv'), + Configstore = require('configstore'), + forown = require('lodash.forown'); + +var conf = new Configstore('logsene' + (process.env.SSH_TTY || '/' + osenv.user())); + + +module.exports = { + + /** + * Defaults: + * Logsene ES API endpoint + * Logsene API endpoint + * Duration of user's CLI session (m) + * Max number of hits to return + */ + logseneEsHost: 'https://logsene-receiver.sematext.com', + logseneEsHostEU: 'https://logsene-receiver.eu.sematext.com', + logseneUri: 'https://apps.sematext.com/users-web/api/v3', + logseneUriEU: 'https://apps.eu.sematext.com/users-web/api/v3', + sessionDuration: 60, + maxHits: 200, + + + /** + * Used to tidy up set and get commands a bit + * @returns {string[]} all params + * @public + */ + getAvailableParams: function _getAvailableParams() { + return['api-key', 'token', 'app-name', 'default-size', 'range-separator', 'trace']; + }, + + + /** + * Gets configuration parameter synchronously + * @param {String} key + * @public + */ + getSync: function _getSync(key) { + return conf.get(key); + }, + + + /** + * Sets the configuration parameter + * @param {String} key + * @param {String} value + * @public + */ + setSync: function _setSync(key, value) { + conf.set(key, value); + }, + + + /** + * Deletes the configuration parameter from the store + * @param {String} key + * @public + */ + deleteSync: function _deleteSync(key) { + conf.del(key); + }, + + + /** + * Gets all configuration parameters + * for the current user + * @returns {*|{get, set}} + * @public + */ + getAllSync: function _getAllSync() { + return conf.all; + }, + + + /** + * Nukes all configuration keys + * @public + */ + deleteAllSync: function _deleteAllSync() { + forown(module.exports.getAllSync(), function(v, k) { + module.exports.deleteSync(k); + }); + } + +}; diff --git a/pool/shard005/JavaScript/0033011_comments-page.js b/pool/shard005/JavaScript/0033011_comments-page.js new file mode 100644 index 0000000000000000000000000000000000000000..c2627cfe6ef7a71b3a9073ac3baefe0bdfc503b2 --- /dev/null +++ b/pool/shard005/JavaScript/0033011_comments-page.js @@ -0,0 +1,15 @@ +import { By } from 'selenium-webdriver'; +import AsyncBaseContainer from '../async-base-container'; +import * as driverHelper from '../driver-helper'; + +export default class CommentsPage extends AsyncBaseContainer { + constructor( driver ) { + super( driver, By.css( '.comments' ) ); + } + + async waitForComments() { + const driver = this.driver; + const resultsLoadingLocator = By.css( '.comment .is-placeholder' ); + return await driverHelper.waitUntilElementNotLocated( driver, resultsLoadingLocator ); + } +} diff --git a/pool/shard005/JavaScript/0033013_Controls.js b/pool/shard005/JavaScript/0033013_Controls.js new file mode 100644 index 0000000000000000000000000000000000000000..693e152f2b2e75285fb9aac6a1d8c019890a63fb --- /dev/null +++ b/pool/shard005/JavaScript/0033013_Controls.js @@ -0,0 +1,126 @@ +//jscs: disable +/*jslint browser: true, devel:true */ +/*globals jQuery, extend, OdysseyMapSearch*/ +// TODO move from Controls.js to more specialized classes. +(function ($) { + "use strict"; + var $body = $(document.body), + $inputs = $("input"), + requestAnimationFrame = window.requestAnimationFrame; + /** + * @constructor + */ + function OdysseyController() { + this.context = null; + } + extend(OdysseyController.prototype, new Odyssey.Event.EventDispatchInterface()); + + // Keys that affect map position. + /** @const */ + OdysseyController.KEYCODE_ARROW_DOWN = 40; + /** @const */ + OdysseyController.KEYCODE_ARROW_LEFT = 37; + /** @const */ + OdysseyController.KEYCODE_ARROW_UP = 38; + /** @const */ + OdysseyController.KEYCODE_ARROW_RIGHT = 39; + /** @const */ + OdysseyController.KEYCODE_PAGE_UP = 33; + /** @const */ + OdysseyController.KEYCODE_PAGE_DOWN = 34; + + // Keys that affect movement speed. + /** @const */ + OdysseyController.CTRL_MULTIPLIER = 10; + /** @const */ + OdysseyController.NOCTRL_MULTIPLIER = 1; + + /** + * Handles the keyboard controls of map position shifting. + * @param {Object} e the keyboard event. + */ + function handleMapShiftControls(e) { + var position = map.getPosition(), + ctrlModifier = e.ctrlKey ? OdysseyController.CTRL_MULTIPLIER : OdysseyController.NOCTRL_MULTIPLIER, + hasChanged = false; + // Down. + if (e.keyCode === OdysseyController.KEYCODE_ARROW_DOWN) { + e.preventDefault(); + hasChanged = true; + map.setPosition(position.x, position.y + ctrlModifier, position.z); + } + + // Left. + if (e.keyCode === OdysseyController.KEYCODE_ARROW_LEFT) { + e.preventDefault(); + hasChanged = true; + map.setPosition(position.x + (-1) * ctrlModifier, position.y, position.z); + } + + // Up. + if (e.keyCode === OdysseyController.KEYCODE_ARROW_UP) { + e.preventDefault(); + hasChanged = true; + map.setPosition(position.x, position.y + (-1) * ctrlModifier, position.z); + } + + // Right. + if (e.keyCode === OdysseyController.KEYCODE_ARROW_RIGHT) { + e.preventDefault(); + hasChanged = true; + map.setPosition(position.x + ctrlModifier, position.y, position.z); + } + + // Down a floor. + if (e.keyCode === OdysseyController.KEYCODE_PAGE_DOWN) { + // Top floor is 0, so controls are reversed (PgDn = +z) + e.preventDefault(); + // Test if the current position is legal. + if (0 <= position.z && position.z <= 15) { + // Don't advance if Z = max Z. + if (position.z < 15) { + hasChanged = true; + map.setPosition(position.x, position.y, position.z + 1); + } + } else { + // Set the floor to the default of 7. + hasChanged = true; + map.setPosition(position.x, position.y, 7); + } + } + + // Up a floor. + if (e.keyCode === OdysseyController.KEYCODE_PAGE_UP) { + e.preventDefault(); + if (0 <= position.z && position.z <= 15) { + if (position.z > 0) { + hasChanged = true; + map.setPosition(position.x, position.y, position.z + (-1)); + } + } else { + // Set the floor to the default of 7. + hasChanged = true; + map.setPosition(position.x, position.y, 7); + } + } + if (hasChanged) { + worldmap.setMapPosition(position); + } + // Do not return false. It will prevent event bubbling + // i.e. it will disable other controls and browser behaviors. + //return false; + } + + /** + * Handles keydown events for input fields. Prevents event propagation + * to ensure other controls do not respond to this event. + * @param {Object} e the event that fired on the input. + */ + function inputPreventPropagation(e) { + e.stopPropagation(); + } + + // DOM event listeners. + $body.keydown(handleMapShiftControls); + $inputs.keydown(inputPreventPropagation); +}(jQuery)); diff --git a/pool/shard005/JavaScript/0033016_app-layout-behavior.js b/pool/shard005/JavaScript/0033016_app-layout-behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..b7a8ef75f75f0c142e9ac0153c82fe62c267fa19 --- /dev/null +++ b/pool/shard005/JavaScript/0033016_app-layout-behavior.js @@ -0,0 +1,82 @@ +define(["exports", "../../polymer/polymer-legacy.js", "../../iron-resizable-behavior/iron-resizable-behavior.js", "../../polymer/lib/legacy/polymer.dom.js", "../../polymer/lib/utils/async.js", "../../polymer/lib/utils/debounce.js", "../../polymer/lib/utils/flush.js"], function (_exports, _polymerLegacy, _ironResizableBehavior, _polymerDom, _async, _debounce, _flush) { + "use strict"; + + Object.defineProperty(_exports, "__esModule", { + value: true + }); + _exports.AppLayoutBehavior = void 0; + + /** + @license + Copyright (c) 2016 The Polymer Project Authors. All rights reserved. + This code may only be used under the BSD style license found at + http://polymer.github.io/LICENSE.txt The complete set of authors may be found at + http://polymer.github.io/AUTHORS.txt The complete set of contributors may be + found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as + part of the polymer project is also subject to an additional IP rights grant + found at http://polymer.github.io/PATENTS.txt + */ + + /** + * @polymerBehavior + */ + var AppLayoutBehavior = [_ironResizableBehavior.IronResizableBehavior, { + listeners: { + 'app-reset-layout': '_appResetLayoutHandler', + 'iron-resize': 'resetLayout' + }, + attached: function attached() { + this.fire('app-reset-layout'); + }, + _appResetLayoutHandler: function _appResetLayoutHandler(e) { + if ((0, _polymerDom.dom)(e).path[0] === this) { + return; + } + + this.resetLayout(); + e.stopPropagation(); + }, + _updateLayoutStates: function _updateLayoutStates() { + console.error('unimplemented'); + }, + + /** + * Resets the layout. If you changed the size of this element via CSS + * you can notify the changes by either firing the `iron-resize` event + * or calling `resetLayout` directly. + * + * @method resetLayout + */ + resetLayout: function resetLayout() { + var self = this; + + var cb = this._updateLayoutStates.bind(this); + + this._layoutDebouncer = _debounce.Debouncer.debounce(this._layoutDebouncer, _async.animationFrame, cb); + (0, _flush.enqueueDebouncer)(this._layoutDebouncer); + + this._notifyDescendantResize(); + }, + _notifyLayoutChanged: function _notifyLayoutChanged() { + var self = this; // TODO: the event `app-reset-layout` can be fired synchronously + // as long as `_updateLayoutStates` waits for all the microtasks after + // rAF. E.g. requestAnimationFrame(setTimeOut()) + + requestAnimationFrame(function () { + self.fire('app-reset-layout'); + }); + }, + _notifyDescendantResize: function _notifyDescendantResize() { + if (!this.isAttached) { + return; + } + + this._interestedResizables.forEach(function (resizable) { + if (this.resizerShouldNotify(resizable)) { + this._notifyDescendant(resizable); + } + }, this); + } + }]; + _exports.AppLayoutBehavior = AppLayoutBehavior; +}); \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033017_store.js b/pool/shard005/JavaScript/0033017_store.js new file mode 100644 index 0000000000000000000000000000000000000000..87d6b08c0805252e432fd9c391491f9d1c182e8c --- /dev/null +++ b/pool/shard005/JavaScript/0033017_store.js @@ -0,0 +1,64 @@ +/** + * @module app/js/core + */ + +var Base = require('./base'); + +/** + * @class Store + * @export + */ +var Store = module.exports = Base.extend({ + + /** + * @constructor + * @param {string} namespace + */ + constructor: function(namespace) { + this.namespace = namespace; + + try { + this.data = JSON.parse(localStorage.getItem(namespace)) || {}; + } catch (e) { + this.data = {}; + } + }, + + /** + * Get data from storage + * @param {string} key + * @returns {*} + */ + get: function(key) { + return this.data[key]; + }, + + /** + * Set data to storage and persist it + * @param {string} key + * @param {*} data + */ + set: function(key, data) { + this.data[key] = data; + this.persist(); + }, + + /** + * Saves data to localStorage + */ + persist: function() { + var data = JSON.stringify(this.data); + localStorage.setItem(this.namespace, data); + } + +}, { + + /** + * Returns new exemplar of Store class + * @param namespace + */ + register: function(namespace) { + return new Store(namespace); + } + +}); diff --git a/pool/shard005/JavaScript/0033019_index.js b/pool/shard005/JavaScript/0033019_index.js new file mode 100644 index 0000000000000000000000000000000000000000..0b1d19b0a8eeabddfb40e5589622a0f313598b9c --- /dev/null +++ b/pool/shard005/JavaScript/0033019_index.js @@ -0,0 +1,26 @@ +import './index.css'; +import { getUsers, deleteUser } from './api/userApi'; + +getUsers().then(result => { + let usersBody = ''; + result.forEach(user => { + usersBody += ` + Delete + ${user.id} + ${user.firstName} + ${user.lastName} + ${user.email} + `; + }); + global.document.getElementById('users').innerHTML = usersBody; + var deleteLinks = global.document.getElementsByClassName('deleteUser'); + Array.from(deleteLinks, link => { + link.onclick = function(event) { + const element = event.target; + event.preventDefault(); + deleteUser(element.attributes['data-id'].value); + const row = element.parentNode.parentNode; + row.parentNode.removeChild(row); + }; + }); +}); diff --git a/pool/shard005/JavaScript/0033020_routes.js b/pool/shard005/JavaScript/0033020_routes.js new file mode 100644 index 0000000000000000000000000000000000000000..fedfe675df855998deba6c1490e3b058f6633e6a --- /dev/null +++ b/pool/shard005/JavaScript/0033020_routes.js @@ -0,0 +1,70 @@ +/* global __PRODUCTION__ */ + +import React from "react"; +import { Route } from "react-router"; +import { PageContainer as PhenomicPageContainer } from "phenomic"; +import { Link } from "phenomic"; +import ReactGA from "react-ga"; + +import AppContainer from "./AppContainer"; +import Page from "./layouts/Page"; +import PageError from "./layouts/PageError"; +import PageLoading from "./layouts/PageLoading"; +import Homepage from "./layouts/Homepage"; +import Post from "./layouts/Post"; +import Blog from "./layouts/Blog"; + +let trackPage = page => { +}; + +if (typeof window !== "undefined" && __PRODUCTION__) { + ReactGA.initialize("UA-86953911-1"); + + trackPage = page => { + ReactGA.set({ + page + }); + + ReactGA.pageview(page); + }; +} + +const trackRouteVisit = ({ pathname, hash }) => { + trackPage(pathname + (hash || "")); +}; + +const routeChangeHandler = (prevState, nextState) => { + trackRouteVisit(nextState.location); + return true; +}; + +const routeEnterHandler = nextState => { + trackRouteVisit(nextState.location); + return true; +}; + +const PageContainer = props => { + return ( + + ); +}; + +export default ( + + + +); diff --git a/pool/shard005/JavaScript/0033022_router.js b/pool/shard005/JavaScript/0033022_router.js new file mode 100644 index 0000000000000000000000000000000000000000..2e67f380e226d7c4b29836a40f1f52455d6027ff --- /dev/null +++ b/pool/shard005/JavaScript/0033022_router.js @@ -0,0 +1,99 @@ +/** +Sample SMS +{ ToCountry: 'US', + ToState: 'UT', + SmsMessageSid: 'SM9e7f9a00e70d9220ccc77b9843c6b8ba', + NumMedia: '0', + ToCity: 'PROVO', + FromZip: '84606', + SmsSid: 'SM9e7f9a00e70d9220ccc77b9843c6b8ba', + FromState: 'UT', + SmsStatus: 'received', + FromCity: 'PROVO', + Body: 'Brent Anderson', + FromCountry: 'US', + To: '+18016917644', + ToZip: '84606', + MessageSid: 'SM9e7f9a00e70d9220ccc77b9843c6b8ba', + AccountSid: 'ACbc2b15d148b848529f98c5f408254042', + From: '+18016912841', + ApiVersion: '2010-04-01' } +*/ +Router.map(function() { + this.route('voice-hook', {where: 'server', path: '/api/voice-hook', action:function() { + this.response.end("Voice Handled"); + }}); + this.route('sms-hook', {where: 'server', path: '/api/sms-hook', action: function() { + var params = this.request.body, + fromNumber = params.From, + toNumber = params.To, + message = params.Body; + + // Find the last message sent to this number + var lastMessage = Messages.findOne({to: fromNumber}) || {}; + var lastConvo = Conversations.findOne(lastMessage.conversationId); + var member = Members.findOne({ + number: fromNumber + }); + + if (!lastConvo || (member && !member.subscribed)) { + // We don't know who this person is or what's going on + // Register them in the system! + + Members.upsert({ + number: fromNumber + }, { + name: message, + number: fromNumber, + groups: ["Ward"], + subscribed: true + }); + + member = Members.findOne({ number: fromNumber }); + + var message = Messages.insert({ + fromNumber: fromNumber, + toNumber: toNumber, + memberId: member._id, + message: message, + messageCode: "START", + direction: "inbound", + sentReceived: true + }); + + Messages.insert({ + fromNumber: Meteor.settings.twilioNumber, + toNumber: fromNumber, // Flipped here since we're replying + memberId: member._id, + message: "Thank you for signing up! Reply with STOP at any time to cancel.", + messageCode: "START_REPLY", + direction: "outbound", + sentReceived: false + }); + this.response.end("Subscribed"); + } else { // We know this number + + if (!member) { + Meteor.Error(500, "Unknown member with number " + fromNumber); + this.response.end("Unknown member error"); + } + if (message.toLowerCase() === "stop") { + // Unsubscribe this member + Members.update({_id: member._id}, {$set: {subscribed: false}}); + this.response.end("Unsubscribed"); + } else { // Handle the message properly + var inMessage = Messages.insert({ + conversationId: lastConvo._id, + fromNumber: fromNumber, + toNumber: Meteor.settings.twilioNumber, + memberId: member._id, + message: message, + direction: "inbound", + sentReceived: true + }); + + this.response.end("New message received"); + } + } + }}); +}); \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033025_catmullRomOpen.js b/pool/shard005/JavaScript/0033025_catmullRomOpen.js new file mode 100644 index 0000000000000000000000000000000000000000..217ddb82afdb02f44e619dc76a5597a530d6b6f4 --- /dev/null +++ b/pool/shard005/JavaScript/0033025_catmullRomOpen.js @@ -0,0 +1,62 @@ +import {CardinalOpen} from "./cardinalOpen"; +import {point} from "./catmullRom"; + +function CatmullRomOpen(context, alpha) { + this._context = context; + this._alpha = alpha; +} + +CatmullRomOpen.prototype = { + areaStart: function() { + this._line = 0; + }, + areaEnd: function() { + this._line = NaN; + }, + lineStart: function() { + this._x0 = this._x1 = this._x2 = + this._y0 = this._y1 = this._y2 = NaN; + this._l01_a = this._l12_a = this._l23_a = + this._l01_2a = this._l12_2a = this._l23_2a = + this._point = 0; + }, + lineEnd: function() { + if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath(); + this._line = 1 - this._line; + }, + point: function(x, y) { + x = +x, y = +y; + + if (this._point) { + var x23 = this._x2 - x, + y23 = this._y2 - y; + this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha)); + } + + switch (this._point) { + case 0: this._point = 1; break; + case 1: this._point = 2; break; + case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break; + case 3: this._point = 4; // proceed + default: point(this, x, y); break; + } + + this._l01_a = this._l12_a, this._l12_a = this._l23_a; + this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a; + this._x0 = this._x1, this._x1 = this._x2, this._x2 = x; + this._y0 = this._y1, this._y1 = this._y2, this._y2 = y; + } +}; + +export default (function custom(alpha) { + + function catmullRom(context) { + return alpha ? new CatmullRomOpen(context, alpha) : new CardinalOpen(context, 0); + } + + catmullRom.alpha = function(alpha) { + return custom(+alpha); + }; + + return catmullRom; +})(0.5); diff --git a/pool/shard005/JavaScript/0033028_main.js b/pool/shard005/JavaScript/0033028_main.js new file mode 100644 index 0000000000000000000000000000000000000000..c0c6c90a540e0b2d3f51a80e298f6ac6a4696da3 --- /dev/null +++ b/pool/shard005/JavaScript/0033028_main.js @@ -0,0 +1,241 @@ +/* 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/. */ + +load('lib/WindowManager'); +load('lib/prefs'); + +var myPrefs = prefs.createStore('extensions.tabsonbottom@piro.sakura.ne.jp.'); +myPrefs.define('newTabByDblclick', true); + +Cu.import('resource://gre/modules/Services.jsm'); + +const TYPE_BROWSER = 'navigator:browser'; + +var baseStyleURL = 'chrome://tabsonbottom/skin/base.css'; +var platformStyleURL = 'chrome://tabsonbottom/skin/' + Services.appinfo.OS + '.css'; + +function addStyleSheet(aURL, aWindow) { + var d = aWindow.document; + var pi = d.createProcessingInstruction( + 'xml-stylesheet', + 'type="text/css" href="'+aURL+'"' + ); + d.insertBefore(pi, d.documentElement); + return pi; +} + +function FullscreenObserver(aWindow) { + this.window = aWindow; + this.init(); +} +FullscreenObserver.prototype = { + get MutationObserver() { + var w = this.window; + return w.MutationObserver || w.MozMutationObserver; + }, + + init : function FullscreenObserver_onInit() { + if (!this.MutationObserver) + return; + this.observer = new this.MutationObserver((function(aMutations, aObserver) { + this.onMutation(aMutations, aObserver); + }).bind(this)); + this.observer.observe(this.window.document.documentElement, { attributes : true }); + + this.onSizeModeChange(); + }, + + destroy : function FullscreenObserver_destroy() { + if (this.observer) { + this.observer.disconnect(); + delete this.observer; + } + delete this.window; + }, + + onMutation : function FullscreenObserver_onMutation(aMutations, aObserver) { + aMutations.forEach(function(aMutation) { + if (aMutation.type != 'attributes') + return; + if (aMutation.attributeName == 'sizemode') + this.window.setTimeout((function() { + this.onSizeModeChange(); + }).bind(this), 10); + }, this); + }, + + onSizeModeChange : function FullscreenObserver_onSizeModeChange() { + var w = this.window; + var d = w.document; + if (d.documentElement.getAttribute('sizemode') != 'fullscreen' || + !w.FullScreen._safeToCollapse()) + return; + + var toolbox = w.gNavToolbox; + toolbox.style.marginTop = -toolbox.getBoundingClientRect().height + 'px'; + + var windowControls = d.getElementById('window-controls'); + var navigationToolbar = d.getElementById('nav-bar'); + if (!windowControls || + !navigationToolbar || + windowControls.parentNode == navigationToolbar) + return; + + // the location bar is flex=1, so we should not apply it. + // windowControls.setAttribute('flex', '1'); + navigationToolbar.appendChild(windowControls); + } +}; + +function getTabStrip(aTabBrowser, aWindow) { + if (!(aTabBrowser instanceof aWindow.Element)) + return null; + + var strip = aTabBrowser.mStrip; + return (strip && strip instanceof Ci.nsIDOMElement) ? + strip : + evaluateXPath( + 'ancestor::xul:toolbar[1]', + aTabBrowser.tabContainer, + Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE + ).singleNodeValue || aTabBrowser.tabContainer.parentNode; +} +function getTab(aEvent) { + return evaluateXPath( + 'ancestor-or-self::xul:tab', + aEvent.originalTarget || aEvent.target, + Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE + ).singleNodeValue; +} +function getClickable(aEvent) { + return evaluateXPath( + 'ancestor-or-self::*[contains(" button toolbarbutton scrollbar nativescrollbar popup menupopup panel tooltip splitter textbox ", concat(" ", local-name(), " "))]', + aEvent.originalTarget, + Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE + ).singleNodeValue; +} +var NSResolver = { + lookupNamespaceURI : function(aPrefix) { + switch (aPrefix) { + case 'xul': + return 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; + case 'html': + case 'xhtml': + return 'http://www.w3.org/1999/xhtml'; + case 'xlink': + return 'http://www.w3.org/1999/xlink'; + default: + return ''; + } + } +}; +function evaluateXPath(aExpression, aContext, aType) { + if (!aType) + aType = Ci.nsIDOMXPathResult.ORDERED_NODE_SNAPSHOT_TYPE; + try { + var XPathResult = (aContext.ownerDocument || aContext).evaluate( + aExpression, + (aContext || document), + NSResolver, + aType, + null + ); + } + catch(e) { + return { + singleNodeValue : null, + snapshotLength : 0, + snapshotItem : function() { + return null + } + }; + } + return XPathResult; +} + +function onMozMouseHittest(aEvent) { + if (!myPrefs.newTabByDblclick) + return; + // block default behaviors of the tab bar (dragging => window move, etc.) + aEvent.stopPropagation(); +} + +function onDoubleClick(aEvent) { + if (!myPrefs.newTabByDblclick) + return; + if (!getTab(aEvent) && !getClickable(aEvent)) { + aEvent.view.BrowserOpenTab(); + aEvent.stopPropagation(); + } +} + +var baseStyles = new WeakMap(); +var platformStyles = new WeakMap(); +var fullscreenObservers = new WeakMap(); + +function onUnload(aEvent) { + (aEvent.view || aEvent.target.defaultView).addEventListener('unload', onUnload, false); + uninitWindow(aWindow); +} + +function uninitWindow(aWindow) { + aWindow.removeEventListener('unload', onUnload, false); + + delete aWindow.TabsOnBottom; + + var strip = getTabStrip(aWindow.gBrowser, aWindow); + strip.removeEventListener('MozMouseHittest', onMozMouseHittest, true); + strip.removeEventListener('dblclick', onDoubleClick, true); + + baseStyles.delete(aWindow); + platformStyles.delete(aWindow); + + fullscreenObservers.get(aWindow).destroy(); + fullscreenObservers.delete(aWindow); +} + +function handleWindow(aWindow) { + var doc = aWindow.document; + if (doc.documentElement.getAttribute('windowtype') != TYPE_BROWSER) + return; + + aWindow.TabsOnBottom = true; + + var allowedByOtherAddons = Boolean( + aWindow.TreeStyleTabService + ); + aWindow.TabsInTitlebar.allowedBy('tabsOnBottom', allowedByOtherAddons); + + baseStyles.set(aWindow, addStyleSheet(baseStyleURL, aWindow)); + platformStyles.set(aWindow, addStyleSheet(platformStyleURL, aWindow)); + fullscreenObservers.set(aWindow, new FullscreenObserver(aWindow)); + + var strip = getTabStrip(aWindow.gBrowser, aWindow); + strip.addEventListener('MozMouseHittest', onMozMouseHittest, true); // to block default behaviors of the tab bar + strip.addEventListener('dblclick', onDoubleClick, true); + + aWindow.addEventListener('unload', onUnload, false); +} + +WindowManager.getWindows(TYPE_BROWSER).forEach(handleWindow); +WindowManager.addHandler(handleWindow); + +function shutdown() { + WindowManager.getWindows(TYPE_BROWSER).forEach(function(aWindow) { + aWindow.TabsInTitlebar.allowedBy('tabsOnBottom', true); + + aWindow.document.removeChild(baseStyles.get(aWindow)); + aWindow.document.removeChild(platformStyles.get(aWindow)); + + aWindow.removeEventListener('unload', onUnload, false); + uninitWindow(aWindow); + }); + + WindowManager = undefined; + myPrefs.destroy(); + myPrefs = undefined; + prefs = undefined; + baseStyles = undefined; + platformStyles = undefined; +} diff --git a/pool/shard005/JavaScript/0033030_b2ContactConstraintPoint.js b/pool/shard005/JavaScript/0033030_b2ContactConstraintPoint.js new file mode 100644 index 0000000000000000000000000000000000000000..e76ce3cd42111e62b7a9b497a2c4157fdcfd408d --- /dev/null +++ b/pool/shard005/JavaScript/0033030_b2ContactConstraintPoint.js @@ -0,0 +1,48 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http: +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked, and must not be +* misrepresented the original software. +* 3. This notice may not be removed or altered from any source distribution. +* +* Converted for The Render Engine v2.0 +* Aug. 4, 2010 Brett Fattori +*/ + +Engine.include("/physics/common/math/b2Vec2.js"); + + +Engine.initObject("b2ContactConstraintPoint", null, function() { + + var b2ContactConstraintPoint = Base.extend({ + + localAnchor1: null, + localAnchor2: null, + normalImpulse: null, + tangentImpulse: null, + positionImpulse: null, + normalMass: null, + tangentMass: null, + separation: null, + velocityBias: null, + + constructor: function() { + this.localAnchor1 = new b2Vec2(); + this.localAnchor2 = new b2Vec2(); + } + + }); + + return b2ContactConstraintPoint; + +}); diff --git a/pool/shard005/JavaScript/0033031_routerHelperProvider.js b/pool/shard005/JavaScript/0033031_routerHelperProvider.js new file mode 100644 index 0000000000000000000000000000000000000000..5d050c934da9d3c78bb925743decdbaabe5f80e2 --- /dev/null +++ b/pool/shard005/JavaScript/0033031_routerHelperProvider.js @@ -0,0 +1,37 @@ +(function() { + // Modified version of John Papa's Router Helper + // https://github.com/johnpapa/angular-styleguide + + angular + .module('mobile-bazaar') + .provider('routerHelper', routerHelperProvider); + + routerHelperProvider.$inject = ['$locationProvider', '$stateProvider', '$urlRouterProvider']; + + function routerHelperProvider($locationProvider, $stateProvider, $urlRouterProvider) { + + this.$get = RouterHelper; + + $locationProvider.html5Mode(false); + + RouterHelper.$inject = ['$state']; + + function RouterHelper($state) { + var service = { + configureStates: configureStates, + getStates: getStates + }; + + return service; + + function configureStates(states, otherwisePath) { + states.forEach(function(state) { + $stateProvider.state(state.state, state.config); + }); + $urlRouterProvider.otherwise("login"); + } + + function getStates() { return $state.get(); } + } + } +}()); \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033033_phoenix.js b/pool/shard005/JavaScript/0033033_phoenix.js new file mode 100644 index 0000000000000000000000000000000000000000..e9a38d1cf7eb23ca35f6beecde902ed12885e71d --- /dev/null +++ b/pool/shard005/JavaScript/0033033_phoenix.js @@ -0,0 +1,123 @@ +var fs = require('fs'), + path = require('path'), + mm = require('musicmetadata'), + gui = require('nw.gui'), + win = gui.Window.get(), + tray; + +var Phoenix = (function () { + var index = 1, + loaded = 0, + count = 0, + files = {}, + $tracks = $('#tracks'), + $timeline = $('#timeline span'), + $play = $('#ic-play'), + $pause = $('#ic-pause'), + $audio = document.getElementById('audio-cache'); + + function getFileList(dir) { + fs.readdir(dir, function (err, items) { + if (err) { throw err; } + else { + items.forEach(function (item) { + var p = dir+'\\'+item; + fs.stat(p, function (err, stats) { + if (path.extname(item) === '.mp3') { + var id = index, + elem = $('
    Loading: ' + item + '
    '), + content = null, + track = null;; + + index += 1; + + files[id] = {}; + track = files[id]; + track.id = id; + track.fileName = item; + track.path = p; + Phoenix.count += 1; + + $tracks.append(elem); + + content = fs.createReadStream(p); + mm(content, { duration: true }, function (err, metadata) { + content.close(); + if (err) { throw err } + else { + track.metadata = metadata; + updateTrack(track); + } + loaded += 1; + }); + } + }); + }); + } + }); + } + + function updateTrack(track) { + var s = '', + $t = $('#track-'+track.id); + + if (track.metadata && track.metadata.title) { + s = track.metadata.artist.join(' & ') + ' - ' + track.metadata.title; + } else { + s = track.fileName.replace('.mp3', ''); + } + $t.find('span.file-name').html(s); + $t.find('span.length').html(formatSecond(track.metadata.duration)); + } + + function formatSecond(seconds) { + var s = '', + min = Math.floor(seconds/60), + sec = seconds % 60; + + s += min + ':'; + s += (sec < 10) ? '0'+sec : sec; + + return s; + } + + function play(id) { + var track = files[id], + $c = $('#current'); + + if (track.metadata && track.metadata.title) { + $c.find('h2[data-attribute="title"]').html(track.metadata.title); + $c.find('h4[data-attribute="artist"]').html(track.metadata.artist.join(' & ')); + } else { + $c.find('h2[data-attribute="title"]').html(track.fileName); + $c.find('h4[data-attribute="artist"]').html(''); + } + $audio.src = 'file:///' + track.path; + $audio.play(); + + $timeline.css('width', '0%'); + $play.hide(); + $pause.show(); + } + + function pause () { + $pause.hide(); + $play.show(); + } + + function attachEventHandlers () { + $tracks.on('click', '.track', function () { play( $(this).data('id') ); }); + $pause.on('click', function () { pause(); }); + } + + function init() { + getFileList('d:\\Z\\all'); + attachEventHandlers(); + } + + return { + init: init, + play: play, + getFileList: getFileList + } +})(); diff --git a/pool/shard005/JavaScript/0033041_spec-helpers.js b/pool/shard005/JavaScript/0033041_spec-helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..9e8b831db011af8d8252e077b8b974cee720a1d7 --- /dev/null +++ b/pool/shard005/JavaScript/0033041_spec-helpers.js @@ -0,0 +1,39 @@ +/* eslint-env browser */ +import { memStorage } from '../storage' + +let _window + +// polyfill missing/incomplete APIs in jsdom +export const polyfillWindow = () => { + _window = global.window + global.window = Object.create(window) + + Object.defineProperty(window, 'location', { + value: { + href: 'https://app.biz/', + pathname: '/', + origin: 'https://app.biz', + get hash() { + return this.href.replace(/^[^#]+/, '') + }, + set hash(value) { + this.href = this.href.replace(/#.*|$/, value) + }, + }, + }) + + window.localStorage = memStorage() + + // this is fixed in the latest jsdom, but jest has not yet updated the jsdom dependency + window.origin = window.location.origin + Object.defineProperty(MessageEvent.prototype, 'origin', { + writable: true, + value: window.origin, + }) + MessageEvent.prototype.origin = window.location.origin +} + +export const polyunfillWindow = () => { + delete window.localStorage + global.window = _window +} diff --git a/pool/shard005/JavaScript/0033043_TestimonialController.js b/pool/shard005/JavaScript/0033043_TestimonialController.js new file mode 100644 index 0000000000000000000000000000000000000000..72a882011af7df0912556550995b04fca2bd333c --- /dev/null +++ b/pool/shard005/JavaScript/0033043_TestimonialController.js @@ -0,0 +1,19 @@ +(function() { + + + var TestimonialsController = function ($scope, $rootScop) { + + console.log('hello world from TestimonialsController') + + $('#testimonialFlexNavButton').parent().siblings().children('a').removeClass('activeNav') + $('#testimonialFlexNavButton').parent().siblings().children('a').addClass('cmn-t-underline') + $('#testimonialFlexNavButton').removeClass('cmn-t-underline') + $('#testimonialFlexNavButton').addClass('activeNav') + + } + + TestimonialsController.$inject = ['$scope', '$rootScope'] + + angular.module('OakHarborSoccerApp') + .controller('TestimonialsController', TestimonialsController); +}()); \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033048_api.js b/pool/shard005/JavaScript/0033048_api.js new file mode 100644 index 0000000000000000000000000000000000000000..eef3b5af5b9de7182f03eb9d4dc1997f45060de2 --- /dev/null +++ b/pool/shard005/JavaScript/0033048_api.js @@ -0,0 +1,72 @@ + +KeyValStore = (function() { + var stores = {}; + + function build(name, options) { + options = _.extend({ + collection: null + }, options); + + var collection = options.collection || new Mongo.Collection('keyvalstore_' + name); + collection._ensureIndex({key: 1}); + + return { + get: function(key, defaultVal) { + var result = collection.findOne({key: key}); + + if (result === undefined || (result.expiresAt && result.expiresAt <= new Date())) { + return defaultVal; + } + return result.isJson ? JSON.parse(result.value) : result.value; + }, + + set: function(key, value, expiresAt) { + var isJson = typeof(key) !== 'string'; + + collection.upsert({key: key}, { + $set: { + key: key, + value: isJson ? JSON.stringify(value) : value, + isJson: isJson, + expiresAt: expiresAt + } + }); + }, + + remove: function(key) { + collection.remove({key: key}); + }, + + removeAll: function() { + return collection.remove({}); + }, + + getCollection: function() { + return collection; + } + }; + }; + + + return { + store: function(name, options) { + if (!(name in stores)) { + stores[name] = build(name, options); + } + + return stores[name]; + }, + + get: function(key, defaultVal) { + return this.store('default').get(key, defaultVal); + }, + + set: function(key, value, expiresAt) { + this.store('default').set(key, value, expiresAt); + }, + + remove: function(key) { + this.store('default').remove(key); + } + }; +})(); diff --git a/pool/shard005/JavaScript/0033049_index.js b/pool/shard005/JavaScript/0033049_index.js new file mode 100644 index 0000000000000000000000000000000000000000..985318ec3c30319a3b0051c7048c24aed3d73774 --- /dev/null +++ b/pool/shard005/JavaScript/0033049_index.js @@ -0,0 +1,140 @@ +'use strict'; +var chalk = require('chalk'); +var pad = require('pad-component'); +var wrap = require('word-wrap'); +var stringWidth = require('string-width'); +var stripAnsi = require('strip-ansi'); +var ansiStyles = require('ansi-styles'); +var ansiRegex = require('ansi-regex')(); +var repeating = require('repeating'); + +var topOffset = 3; +var leftOffset = 17; +var defaultGreeting = + '\n _-----_' + + '\n | | ' + + '\n |' + chalk.red('--(o)--') + '| ' + + '\n `---------´ ' + + '\n ' + chalk.yellow('(') + ' _' + chalk.yellow('´U`') + '_ ' + chalk.yellow(')') + ' ' + + '\n /___A___\\ ' + + '\n ' + chalk.yellow('| ~ |') + ' ' + + '\n __' + chalk.yellow('\'.___.\'') + '__ ' + + '\n ´ ' + chalk.red('` |') + '° ' + chalk.red('´ Y') + ' ` '; + +module.exports = function (message, options) { + message = (message || 'Welcome to Yeoman, ladies and gentlemen!').trim(); + options = options || {}; + + /* + * What you're about to see may confuse you. And rightfully so. Here's an + * explanation. + * + * When yosay is given a string, we create a duplicate with the ansi styling + * sucked out. This way, the true length of the string is read by `pad` and + * `wrap`, so they can correctly do their job without getting tripped up by + * the "invisible" ansi. Along with the duplicated, non-ansi string, we store + * the character position of where the ansi was, so that when we go back over + * each line that will be printed out in the message box, we check the + * character position to see if it needs any styling, then re-insert it if + * necessary. + * + * Better implementations welcome :) + */ + + var maxLength = 24; + var frame; + var styledIndexes = {}; + var completedString = ''; + var regExNewLine; + + if (options.maxLength) { + maxLength = stripAnsi(message).toLowerCase().split(' ').sort()[0].length; + + if (maxLength < options.maxLength) { + maxLength = options.maxLength; + } + } + + regExNewLine = new RegExp('\\s{' + maxLength + '}'); + + frame = { + top: '.' + repeating('-', maxLength + 2) + '.', + side: ansiStyles.reset.open + '|' + ansiStyles.reset.open, + bottom: ansiStyles.reset.open + '\'' + repeating('-', maxLength + 2) + '\'' + }; + + message.replace(ansiRegex, function (match, offset) { + Object.keys(styledIndexes).forEach(function (key) { + offset -= styledIndexes[key].length; + }); + + styledIndexes[offset] = styledIndexes[offset] ? styledIndexes[offset] + match : match; + }); + + return wrap(stripAnsi(message), { width: maxLength }) + .split(/\n/) + .reduce(function (greeting, str, index, array) { + var paddedString; + + if (!regExNewLine.test(str)) { + str = str.trim(); + } + + completedString += str; + + str = completedString + .substr(completedString.length - str.length) + .replace(/./g, function (char, charIndex) { + if (index > 0) { + charIndex += completedString.length - str.length + index; + } + + var hasContinuedStyle = 0; + var continuedStyle; + + Object.keys(styledIndexes).forEach(function (offset) { + if (charIndex > offset) { + hasContinuedStyle++; + continuedStyle = styledIndexes[offset]; + } + + if (hasContinuedStyle === 1 && charIndex < offset) { + hasContinuedStyle++; + } + }); + + if (styledIndexes[charIndex]) { + return styledIndexes[charIndex] + char; + } else if (hasContinuedStyle >= 2) { + return continuedStyle + char; + } else { + return char; + } + }) + .trim(); + + paddedString = pad({ + length: stringWidth(str), + valueOf: function () { + return ansiStyles.reset.open + str + ansiStyles.reset.open; + } + }, maxLength); + + if (index === 0) { + greeting[topOffset - 1] += frame.top; + } + + greeting[index + topOffset] = + (greeting[index + topOffset] || pad.left('', leftOffset)) + + frame.side + ' ' + paddedString + ' ' + frame.side; + + if (array.length === index + 1) { + greeting[index + topOffset + 1] = + (greeting[index + topOffset + 1] || pad.left('', leftOffset)) + + frame.bottom; + } + + return greeting; + }, defaultGreeting.split(/\n/)) + .join('\n') + '\n'; +}; diff --git a/pool/shard005/JavaScript/0033051_oppsfilebrowser.js b/pool/shard005/JavaScript/0033051_oppsfilebrowser.js new file mode 100644 index 0000000000000000000000000000000000000000..9a55d38c510abe446314bac7a72e189b78b7b2e1 --- /dev/null +++ b/pool/shard005/JavaScript/0033051_oppsfilebrowser.js @@ -0,0 +1,60 @@ +// this functions are just a proxy +function opps_editor_popup_selector(path){ + top.tinymce.activeEditor.windowManager. + getParams().selectfunction(path); +} + +function opps_editor_popup_selecto_embed(path){ + top.tinymce.activeEditor.windowManager. + getParams().selectembedfunction(path); +} + +function CustomFileBrowser(field_name, url, type, win) { + + // default functions, meant to be overrided + var selectfunction = function (){console.log('selecting')} + var selectembedfunction = function (){ + console.log('selecting embed') + } + + if (type == 'image'){ + var cmsURL = '/admin/images/get_images/' + selectfunction = function (path){ + console.log(path); + window.document.getElementById(field_name).value = path; + + // Try to set the image dimension to 300 + try { + dt = field_name.split('_'); + new_number = parseInt(dt[1])+3 + dm_selector = dt[0] + "_" + new_number.toString(); + window.document.getElementById(dm_selector).value = '600'; + } catch(err) { + console.log(err); + } + + tinymce.activeEditor.windowManager.close(); + }; + } + tinyMCE.activeEditor.windowManager.open({ + url: cmsURL, + width: 980, + height: 500, + resizable: 'yes', + scrollbars: 'yes', + inline: 'no', + close_previous: 'no', + buttons: [{ + text: 'Close', + onclick: 'close' + }] + }, { + field_name: field_name, + win: win, + type: type, + selectfunction: selectfunction, + selectembedfunction: selectembedfunction + }); + return false; + +} diff --git a/pool/shard005/JavaScript/0033052_grepit.spec.js b/pool/shard005/JavaScript/0033052_grepit.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..f00ece1df2776d6ebec42f0e13940a21754bfe7d --- /dev/null +++ b/pool/shard005/JavaScript/0033052_grepit.spec.js @@ -0,0 +1,84 @@ +'use strict'; + +var expect = require('expect.js') + , catchE = require('catch-error') + , grepit = require('../index'); + +describe('grepit module', function(){ + + describe('when passing pattern and file arguments', function(){ + it('should return an array', function(){ + // arrange + var pattern = 'abc'; + var file = 'test/test_file.txt'; + // act + var result = grepit(pattern, file); + // assert + expect(result).to.be.an('array'); + }); + it('should return an error if file is not found', function(){ + var pattern = 'abc'; + var file = 'test/not_test_file.txt'; + var result = catchE({func: grepit, args: [pattern, file]}); + expect(result).to.be.an(Error); + }); + it('should return an error if pattern is not a string or regex', function(){ + var pattern = {}; + var file = 'test/test_file.txt'; + var result = catchE({func: grepit, args: [pattern, file]}); + expect(result).to.be.an(Error); + }); + it('should return an array if pattern is a regular expression', function(){ + var pattern = /abc/; + var file = 'test/test_file.txt'; + var result = grepit(pattern, file); + expect(result).to.be.an('array'); + }); + }); + + describe('when passing a string pattern', function(){ + it('should return an array of lines from the text that contain pattern', function(){ + var pattern = 'first'; + var file = 'test/test_file.txt'; + var result = grepit(pattern, file); + var expected = ['The first sentence of the text.']; + expect(result).to.eql(expected); + }); + it('should return an empty array if the pattern is not in the text.', function(){ + var pattern = 'xyz'; + var file = 'test/test_file.txt'; + var result = grepit(pattern, file); + var expected = []; + expect(result).to.eql(expected); + }); + }); + + describe('when passing a regex pattern', function(){ + it('should return an array of lines from the text that contain pattern', function(){ + var pattern = /first/; + var file = 'test/test_file.txt'; + var result = grepit(pattern, file); + var expected = ['The first sentence of the text.']; + expect(result).to.eql(expected); + }); + it('should return an empty array if the pattern is not in the text.', function(){ + var pattern = /xyz/; + var file = 'test/test_file.txt'; + var result = grepit(pattern, file); + var expected = []; + expect(result).to.eql(expected); + }); + it('should return an array of lines from the text that contain pattern', function(){ + var pattern = /sentence/; + var file = 'test/test_file.txt'; + var result = grepit(pattern, file); + var expected = [ + 'The first sentence of the text.', + 'Now the second sentence.', + 'And then comes the fourth sentence.' + ]; + expect(result).to.eql(expected); + }); + }); + +}); diff --git a/pool/shard005/JavaScript/0033053_index.js b/pool/shard005/JavaScript/0033053_index.js new file mode 100644 index 0000000000000000000000000000000000000000..c54304d7a20b2dab4fcfdd27365f2806550e8293 --- /dev/null +++ b/pool/shard005/JavaScript/0033053_index.js @@ -0,0 +1,61 @@ +'use strict'; + +var assert = require('assert'); +var GetBible = require('../lib'); + +describe('getbible', function () { + + var api; + describe('Invoking API', function () { + it('should return an instance of GetBible, and the translation should be "aov"', function () { + api = new GetBible({translation: 'aov'}); + assert.equal(api.getTranslation(), 'aov'); + }); + + it('should return an instance of GetBible, and the translation should be "kjv"', function () { + api = new GetBible(); + assert.equal(api.getTranslation(), 'kjv'); + }); + }); + + describe('GET test', function () { + describe('Empty parameters test', function () { + it('should return an empty object when passed an epmty parameters object.', function () { + api.get({}, function (err, body) { + assert.equal(err, null); + assert.equal(Object.keys(body).length, 0); + }); + }); + }); // Empty parameters test + + }); // GET test + + describe('getBooks()', function () { + it('should return an array of available books', function () { + api.getBooks(function (err, body) { + assert.equal(err, null); + assert.equal(Object.prototype.toString.call(body), '[object Array]'); + }); + }); + }); + + describe('getPassage()', function () { + it('should return the book of John', function () { + api.getPassage('John', function (err, body) { + assert.equal(err, null); + assert.equal(body.book_name, 'John'); + assert.equal(body.chapter_nr, null); + }); + }); + + it('should return John, Chapter 3', function () { + api.getPassage('John 3', function (err, body) { + assert.equal(err, null); + assert.equal(body.book_name, 'John'); + assert.equal(body.chapter_nr, 3); + }); + }); + + }); + +}); diff --git a/pool/shard005/JavaScript/0033056_grid-cells.js b/pool/shard005/JavaScript/0033056_grid-cells.js new file mode 100644 index 0000000000000000000000000000000000000000..8b83501961bd1dfa8c1efcfeb69aa6bd0e093fa5 --- /dev/null +++ b/pool/shard005/JavaScript/0033056_grid-cells.js @@ -0,0 +1,149 @@ +$(function () { + let HexagonGridCellModule = window.HTM.gridCells.HexagonGridCellModule + let GridCellModuleRenderer = window.HTM.gridCells.GridCellModuleRenderer + + const minScale = 20, + maxScale = 100, + minOrientation = 0, + maxOrientation = 45 + + let GlobalConfig = function() { + this.lite = false + this.sdr = false + this.showFields = false + this.screenLock = false + this.showNumbers = true + this.stroke = 3 + this.textSize = 24 + }; + let config = new GlobalConfig(); + + ////////// + // UTILS + + function getRandomInt(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive + } + + function toggleScreenLock() { + config.screenLock = ! config.screenLock + } + + function prepareDom() { + $('body').html(''); + } + + function setupDatGui(modules, renderer) { + let gui = new dat.GUI(); + let moduleFolders = []; + + gui.add(config, 'lite').onChange(function(value) { + config.lite = value; + renderer.render(config); + }); + + gui.add(config, 'sdr').onChange(function(value) { + config.sdr = value; + d3.select('#encoding svg').remove() + renderer.render(config); + }); + + gui.add(config, 'showFields').onChange(function(value) { + config.showFields = value; + d3.select('#encoding svg').remove() + renderer.render(config); + }); + + gui.add(config, 'showNumbers').onChange(function(value) { + config.showNumbers = value; + d3.select('#encoding svg').remove() + renderer.render(config); + }); + + function updateAllControllerDisplays() { + moduleFolders.forEach(function(folder) { + for (let i in folder.__controllers) { + folder.__controllers[i].updateDisplay(); + } + }); + } + + modules.forEach(function(module, i) { + let folder = gui.addFolder('Module ' + module.id) + // This is because of laziness. + module.visible = true; + folder.add(module, 'visible').onChange(function(value) { + module.visible = value; + renderer.render(config); + }); + folder.add(module, 'weight', 1, 5).onChange(function(value) { + module.weight = value; + renderer.render(config); + }).step(1); + folder.add(module, 'scale', minScale, maxScale).onChange(function(value) { + module.scale = value; + renderer.render(config); + }); + folder.add(module, 'activeCells', 1, 10).onChange(function(value) { + module.activeCells = value; + renderer.render(config); + }).step(1); + folder.add(module, 'orientation', minOrientation, maxOrientation).onChange(function(value) { + module.orientation = value; + renderer.render(config); + }); + // folder.open(); + moduleFolders.push(folder); + }); + } + + // END UTILS + ///////////// + + let gridCellModules = []; + + + function run() { + prepareDom(); + + let module = new HexagonGridCellModule(0, 4, 4, 0, 100) + module.setColor(100, 100, 255) + module.activeCells = 1 + module.weight = 3 + gridCellModules.push(module) + + let renderer = new GridCellModuleRenderer(gridCellModules) + + renderer.prepareRender(); + setupDatGui(gridCellModules, renderer) + + renderer.render(config) + + if (renderer.worldPoints) { + + renderer.onWorld('mousemove', function() { + renderer.renderFromWorld(config, d3.event.pageX, d3.event.pageY) + }); + + renderer.onOverlay('mousemove', function(_, i) { + renderer.renderFromOverlay(i, config, d3.event.offsetX, d3.event.offsetY) + }) + } + } + + $(document).keyup(function(e) { + if (e.keyCode === 32) { + toggleScreenLock(); + } + }); + + window.onload = run; + + // add listener to disable scroll + window.addEventListener('scroll', () => { + window.scrollTo( 0, 0 ); + }); + +}); diff --git a/pool/shard005/JavaScript/0033057_locations.js b/pool/shard005/JavaScript/0033057_locations.js new file mode 100644 index 0000000000000000000000000000000000000000..38c82a7767d46b54941d026ca1e55e28201bd1d8 --- /dev/null +++ b/pool/shard005/JavaScript/0033057_locations.js @@ -0,0 +1,46 @@ +(function (ng) { + + function router($stateProvider) { + $stateProvider + .state("locations", { + url: 'locations', + templateUrl: "/locations/index.html" + }) + .state("locations.list", { + url: "/list", + templateUrl: "/locations/list.html", + controller: "LocationListController" + }) + .state("locations.create", { + url: '/create', + templateUrl: "/locations/create.html", + controller: 'LocationCreateController' + }) + .state("locations.edit", { + url: '/edit/:locationId', + templateUrl: '/locations/edit.html', + controller: "LocationEditController", + controllerAs: "ctrl", + resolve: { + outlet: ["$stateParams", "LocationUpdateService", function locationResolver($stateParams, LocationUpdateService){ + return LocationUpdateService.fetch($stateParams.locationId) + .then(function fetchLocation(obj) { + var outlet = obj.data.location; + outlet.loc.lat = outlet.loc.coordinates[1]; + outlet.loc.lon = outlet.loc.coordinates[0]; + return outlet; + }); + }] + } + }) + .state("locations.summary", { + url: "/:locationId/summary", + templateUrl: "/locations/surveys_summary.html", + controller: "LocationDetailsController" + }); + } + + ng.module("PasmoLocation", ["location.create", "locations.list", "locations.details", "location.edit"]) + .config(["$stateProvider", router]); + +}(angular)); diff --git a/pool/shard005/JavaScript/0033058_WelcomeHomeController.js b/pool/shard005/JavaScript/0033058_WelcomeHomeController.js new file mode 100644 index 0000000000000000000000000000000000000000..d927513e49379362d0d94b6d116eb6992ba80c88 --- /dev/null +++ b/pool/shard005/JavaScript/0033058_WelcomeHomeController.js @@ -0,0 +1,52 @@ +/** + * Created by AOWPINS01_01 on 6/23/2015. + */ + + +angular + .module('foodieJournal.home', []) + .controller('WelcomeHomeController',['$scope','activityService',function ($scope,activityService){ + + $scope.title = 'Welcome! Choose a track to get started.'; + + activityService.getActivities().then(function(data) { + $scope.activities = data + }); + }]) + .factory('activityService',activityFactory) + .directive('activityDetails', function() { + return { + scope: { + activity: '=' + }, + restrict: 'CAE', // default behaviour + templateUrl: 'home/view/activityTemplate.html' + }; + }); + +function activityFactory($http){ + this.$inject = ['$http']; + + return { + getActivities: getActivities + }; + + function getActivities () { + debugger; + return $http + .get('data/activity.json') + .then(complete) + .catch(failed); + } + + function complete(response) { + debugger; + return response.data; + } + + function failed(error) { + return error.statusText; + } +} + + diff --git a/pool/shard005/JavaScript/0033061_apds9002.js b/pool/shard005/JavaScript/0033061_apds9002.js new file mode 100644 index 0000000000000000000000000000000000000000..4cc4e11d1c33c939980e5aac03e4e980d59f4fc9 --- /dev/null +++ b/pool/shard005/JavaScript/0033061_apds9002.js @@ -0,0 +1,45 @@ +/* +* Author: Zion Orent +* Copyright (c) 2015 Intel Corporation. +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +// Load Grove Luminance sensor module +var luminanceSensor_lib = require('jsupm_apds9002'); + +// Instantiate a Grove Luminance sensor on analog pin A0 +var myLuminanceSensor_obj = new luminanceSensor_lib.APDS9002(0); + +var myInterval = setInterval(function() +{ + console.log("Luminance value is " + myLuminanceSensor_obj.value()); +}, 1000); + +// On exit: clear interval and memory, print message +process.on('SIGINT', function() +{ + clearInterval(myInterval); + myLuminanceSensor_obj = null; + luminanceSensor_lib.cleanUp(); + luminanceSensor_lib = null; + console.log("Exiting"); + process.exit(0); +}); diff --git a/pool/shard005/JavaScript/0033063_RepositoryManager.js b/pool/shard005/JavaScript/0033063_RepositoryManager.js new file mode 100644 index 0000000000000000000000000000000000000000..211ab6aec6a74f382ab6fb6d155170bec9a350f0 --- /dev/null +++ b/pool/shard005/JavaScript/0033063_RepositoryManager.js @@ -0,0 +1,88 @@ +/** + * Created by mark on 2016/07/30. + */ + + +import HostComponent from '../../base/HostComponent'; +import base from '../../base/Base'; +import {logger} from '../../../Logger'; +import Package from './Package'; + +class RepositoryManager extends HostComponent{ + + constructor(provider,data){ + super(provider,data); + this.data.packages = []; + if(data){ + this.data.updateCache=data.updateCache? data.updateCache: true; + if(data.packages) { + data.packages.forEach((pack)=> { + this.data.packages.push(new Package(pack.name, pack.state)); + }); + + } + }else { + this.data.updateCache = true; + this.data.packages = []; + } + } + + get updateCache(){ + return this.data.updateCache; + } + + set updateCache(cache){ + this.data.updateCache=base.getBooleanValue(cache); + } + + addRepository(){ + throw new Error("Not yet implemented"); + } + + install(repopackage){ + this.data.packages.push(new Package(repopackage,"present")); + } + + remove(repopackage){ + let idx = this.data.packages.indexOf(repopackage); + if(idx!=-1){ + this.data.packages[idx].state="absent"; + }else{ + this.data.packages.push(new Package(repopackage,"absent")); + } + } + + purge(repopackage){ + let idx = this.data.packages.indexOf(repopackage); + if(idx!=-1){ + this.data.packages[idx].state="purge"; + }else{ + this.data.packages.push(new Package(repopackage,"purge")); + } + } + + doNotUpdate(repopackage){ + let idx = this.data.packages.indexOf(repopackage); + if(idx!=-1){ + this.data.packages[idx].state="hold"; + }else{ + this.data.packages.push(new Package(repopackage,"hold")); + } + } + + get packages(){ + return this.data.packages; + } + + export(){ + let obj={}; + obj.updateCache=this.data.updateCache; + obj.packages=[]; + this.packages.forEach((repopackage)=>{ + obj.packages.push(repopackage.export()); + }); + return obj; + } +} + +export default RepositoryManager; \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033065_yobi.milestone.Write.js b/pool/shard005/JavaScript/0033065_yobi.milestone.Write.js new file mode 100644 index 0000000000000000000000000000000000000000..99ac1eae59e0ed970b6c76aabe73b846f582ad8c --- /dev/null +++ b/pool/shard005/JavaScript/0033065_yobi.milestone.Write.js @@ -0,0 +1,150 @@ +/** + * Yobi, Project Hosting SW + * + * Copyright 2013 NAVER Corp. + * http://yobi.io + * + * @Author Jihan Kim + * + * 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. + */ +(function(ns){ + + var oNS = $yobi.createNamespace(ns); + oNS.container[oNS.name] = function(htOptions){ + + var htVar = {}; + var htElement = {}; + + /** + * initialize + */ + function _init(htOptions){ + _initVar(htOptions); + _initElement(htOptions); + _initDatePicker(); + _attachEvent(); + _initFileUploader(); + } + + /** + * initialize variables + */ + function _initVar(htOptions){ + htVar.sDateFormat = htOptions.sDateFormat || "YYYY-MM-DD"; + htVar.rxDateFormat = htOptions.rxDateFormat || /\d{4}-\d{2}-\d{2}/; + htVar.sTplFileItem = $('#tplAttachedFile').text(); + } + + /** + * initialize element variables + */ + function _initElement(htOptions){ + htElement.welForm = $("form.nm"); + htElement.welDatePicker = $(htOptions.elDatePicker); + htElement.welInputDueDate = $(htOptions.elDueDate); + htElement.welInputTitle = $('#title'); + htElement.welInputContent = $('textarea[data-editor-mode="content-body"]'); + htElement.welUploader = $(htOptions.elUploader || "#upload"); + } + + /** + * attach event handlers + */ + function _attachEvent(){ + htElement.welForm.submit(_onSubmitForm); + } + + /** + * on submit form + */ + function _onSubmitForm(weEvt){ + return _validateForm(); + } + + function _validateForm(){ + var sTitle = $.trim(htElement.welInputTitle.val()); + var sContent = $.trim(htElement.welInputContent.val()); + var sDueDate = $.trim(htElement.welInputDueDate.val()); + + if(sTitle.length === 0){ + $yobi.showAlert(Messages("milestone.error.title")); + return false; + } + + if(sContent.length === 0){ + $yobi.showAlert(Messages("milestone.error.content")); + return false; + } + + if(sDueDate.length > 0 && htVar.rxDateFormat.test(sDueDate) === false){ + $yobi.showAlert(Messages("milestone.error.duedateFormat")); + return false; + } + + return true; + } + + /** + * initialize DatePicker + * @requires Pikaday + */ + function _initDatePicker(){ + if(typeof Pikaday != "function"){ + console.log("[Yobi] Pikaday required (https://github.com/dbushell/Pikaday)"); + return false; + } + + // append Pikaday element to DatePicker + htVar.oPicker = new Pikaday({ + "format" : htVar.sDateFormat, + "onSelect" : function(oDate) { + htElement.welInputDueDate.val(this.toString()); + } + }); + htElement.welDatePicker.append(htVar.oPicker.el); + + // fill DatePicker date to InputDueDate if empty + // or set DatePicker date with InputDueDate + var sDueDate = htElement.welInputDueDate.val(); + if(sDueDate.length > 0){ + htVar.oPicker.setDate(sDueDate); + } + + // set relative event between dueDate input and datePicker + htElement.welInputDueDate.blur(function() { + htVar.oPicker.setDate(this.value); + }); + } + + /** + * 파일 업로더 초기화 + * initialize fileUploader + */ + function _initFileUploader(){ + var oUploader = yobi.Files.getUploader(htElement.welUploader, htElement.welInputContent); + + if(oUploader){ + (new yobi.Attachments({ + "elContainer" : htElement.welUploader, + "elTextarea" : htElement.welInputContent, + "sTplFileItem" : htVar.sTplFileItem, + "sUploaderId" : oUploader.attr("data-namespace") + })); + } + } + + _init(htOptions || {}); + }; + +})("yobi.milestone.Write"); diff --git a/pool/shard005/JavaScript/0033070_livechat.js b/pool/shard005/JavaScript/0033070_livechat.js new file mode 100644 index 0000000000000000000000000000000000000000..bb4a7b4bb75f417f21e90a1fc0cd5f39be23f053 --- /dev/null +++ b/pool/shard005/JavaScript/0033070_livechat.js @@ -0,0 +1,155 @@ +import { Meteor } from 'meteor/meteor'; +import { Random } from 'meteor/random'; +import _ from 'underscore'; + +import { LivechatRooms, LivechatVisitors, LivechatDepartment, LivechatTrigger } from '../../../../models'; +import { Livechat } from '../../lib/Livechat'; +import { callbacks } from '../../../../callbacks/server'; +import { normalizeAgent } from '../../lib/Helper'; + +export function online(department) { + return Livechat.online(department); +} + +export function findTriggers() { + return LivechatTrigger.findEnabled().fetch().map((trigger) => _.pick(trigger, '_id', 'actions', 'conditions', 'runOnce')); +} + +export function findDepartments() { + return LivechatDepartment.findEnabledWithAgents().fetch().map((department) => _.pick(department, '_id', 'name', 'showOnRegistration', 'showOnOfflineForm')); +} + +export function findGuest(token) { + return LivechatVisitors.getVisitorByToken(token, { + fields: { + name: 1, + username: 1, + token: 1, + visitorEmails: 1, + department: 1, + }, + }); +} + +export function findRoom(token, rid) { + const fields = { + t: 1, + departmentId: 1, + servedBy: 1, + open: 1, + v: 1, + ts: 1, + }; + + if (!rid) { + return LivechatRooms.findOneByVisitorToken(token, fields); + } + + return LivechatRooms.findOneByIdAndVisitorToken(rid, token, fields); +} + +export function findOpenRoom(token, departmentId) { + const options = { + fields: { + departmentId: 1, + servedBy: 1, + open: 1, + }, + }; + + let room; + const rooms = departmentId ? LivechatRooms.findOpenByVisitorTokenAndDepartmentId(token, departmentId, options).fetch() : LivechatRooms.findOpenByVisitorToken(token, options).fetch(); + if (rooms && rooms.length > 0) { + room = rooms[0]; + } + + return room; +} + +export function getRoom({ guest, rid, roomInfo, agent, extraParams }) { + const token = guest && guest.token; + + const message = { + _id: Random.id(), + rid, + msg: '', + token, + ts: new Date(), + }; + + return Livechat.getRoom(guest, message, roomInfo, agent, extraParams); +} + +export function findAgent(agentId) { + return normalizeAgent(agentId); +} + +export function normalizeHttpHeaderData(headers = {}) { + const httpHeaders = Object.assign({}, headers); + return { httpHeaders }; +} +export function settings() { + const initSettings = Livechat.getInitSettings(); + const triggers = findTriggers(); + const departments = findDepartments(); + const sound = `${ Meteor.absoluteUrl() }sounds/chime.mp3`; + const emojis = Meteor.call('listEmojiCustom'); + return { + enabled: initSettings.Livechat_enabled, + settings: { + registrationForm: initSettings.Livechat_registration_form, + allowSwitchingDepartments: initSettings.Livechat_allow_switching_departments, + nameFieldRegistrationForm: initSettings.Livechat_name_field_registration_form, + emailFieldRegistrationForm: initSettings.Livechat_email_field_registration_form, + displayOfflineForm: initSettings.Livechat_display_offline_form, + videoCall: initSettings.Livechat_videocall_enabled === true && initSettings.Jitsi_Enabled === true, + fileUpload: initSettings.Livechat_fileupload_enabled && initSettings.FileUpload_Enabled, + language: initSettings.Language, + transcript: initSettings.Livechat_enable_transcript, + historyMonitorType: initSettings.Livechat_history_monitor_type, + forceAcceptDataProcessingConsent: initSettings.Livechat_force_accept_data_processing_consent, + showConnecting: initSettings.Livechat_Show_Connecting, + agentHiddenInfo: initSettings.Livechat_show_agent_info === false, + limitTextLength: initSettings.Livechat_enable_message_character_limit + && (initSettings.Livechat_message_character_limit || initSettings.Message_MaxAllowedSize), + }, + theme: { + title: initSettings.Livechat_title, + color: initSettings.Livechat_title_color, + offlineTitle: initSettings.Livechat_offline_title, + offlineColor: initSettings.Livechat_offline_title_color, + actionLinks: [ + { icon: 'icon-videocam', i18nLabel: 'Accept', method_id: 'createLivechatCall', params: '' }, + { icon: 'icon-cancel', i18nLabel: 'Decline', method_id: 'denyLivechatCall', params: '' }, + ], + }, + messages: { + offlineMessage: initSettings.Livechat_offline_message, + offlineSuccessMessage: initSettings.Livechat_offline_success_message, + offlineUnavailableMessage: initSettings.Livechat_offline_form_unavailable, + conversationFinishedMessage: initSettings.Livechat_conversation_finished_message, + conversationFinishedText: initSettings.Livechat_conversation_finished_text, + transcriptMessage: initSettings.Livechat_transcript_message, + registrationFormMessage: initSettings.Livechat_registration_form_message, + dataProcessingConsentText: initSettings.Livechat_data_processing_consent_text, + }, + survey: { + items: ['satisfaction', 'agentKnowledge', 'agentResposiveness', 'agentFriendliness'], + values: ['1', '2', '3', '4', '5'], + }, + triggers, + departments, + resources: { + sound, + emojis, + }, + }; +} + +export async function getExtraConfigInfo(room) { + return callbacks.run('livechat.onLoadConfigApi', { room }); +} + +export function onCheckRoomParams(params) { + return callbacks.run('livechat.onCheckRoomApiParams', params); +} diff --git a/pool/shard005/JavaScript/0033071_gulpfile.js b/pool/shard005/JavaScript/0033071_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..b7e75fac339f5e0a91c932b6fdf0bd0b65d723b6 --- /dev/null +++ b/pool/shard005/JavaScript/0033071_gulpfile.js @@ -0,0 +1,37 @@ +var gulp = require('gulp'); +var prettify = require('../'); + +// normal usage +gulp.task('verify-js', function() { + gulp.src(['./src/foo.js', './src/bar.json']) + .pipe(prettify({config: '.jsbeautifyrc', mode: 'VERIFY_ONLY'})); +}); + +gulp.task('verify-js-diff', function() { + gulp.src(['./src/foo.js', './src/bar.json']) + .pipe(prettify({config: '.jsbeautifyrc', mode: 'VERIFY_ONLY', showDiff: false})); +}); + +gulp.task('format-js', function() { + gulp.src(['./src/foo.js', './src/bar.json']) + .pipe(prettify({config: '.jsbeautifyrc', mode: 'VERIFY_AND_WRITE'})) + .pipe(gulp.dest('./build')); +}); + +gulp.task('prettify-html', function() { + gulp.src('./src/foo.html') + .pipe(prettify({indent_size: 2})) + .pipe(gulp.dest('./build')); +}); + +gulp.task('prettify-css', function() { + gulp.src('./src/foo.css') + .pipe(prettify({indent_size: 2})) + .pipe(gulp.dest('./build')); +}); + +gulp.task('prettify-css-with-just-css-options', function() { + gulp.src('./src/foo.css') + .pipe(prettify({css: {indent_size: 2, indent_char: '\t'}})) + .pipe(gulp.dest('./build')); +}); diff --git a/pool/shard005/JavaScript/0033073_10607.js b/pool/shard005/JavaScript/0033073_10607.js new file mode 100644 index 0000000000000000000000000000000000000000..da90949a16afc9aba981a914b3592b693052e6d0 --- /dev/null +++ b/pool/shard005/JavaScript/0033073_10607.js @@ -0,0 +1,19 @@ +{ + var i; + if ( + (n.push(function() { + if (t) + try { + t.call(o); + } catch (t) { + k(t, o, "nextTick"); + } + else i && i(o); + }), + r || ((r = !0), e()), + !t && "undefined" != typeof Promise) + ) + return new Promise(function(t, e) { + i = t; + }); +} diff --git a/pool/shard005/JavaScript/0033076_gulpfile.js b/pool/shard005/JavaScript/0033076_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..f6a3fa8d954b648bf93ee58e109b39eb4f902369 --- /dev/null +++ b/pool/shard005/JavaScript/0033076_gulpfile.js @@ -0,0 +1,39 @@ +var gulp = require('gulp'); +var $ = require('gulp-load-plugins')(); +var sherpa = require('style-sherpa'); +var uglifycss = require('gulp-uglifycss'); + +var sassPaths = [ + 'node_modules/foundation-sites/scss', + 'node_modules/motion-ui/src', + 'node_modules/hamburgers/_sass/hamburgers' +]; + +gulp.task('sass', function() { + return gulp.src('_scss/styles.scss') + .pipe($.sass({ + includePaths: sassPaths + }) + .on('error', $.sass.logError)) + .pipe($.autoprefixer({ + browsers: ['last 2 versions', 'ie >= 10'] + })) + .pipe(uglifycss({ + "maxLineLen": 80, + "uglyComments": true + })) + .pipe(gulp.dest('static/css')); +}); + +gulp.task('styleguide', function() { + sherpa('_styleguide/styleguide.md', { + output: 'styleguide/index.html', + template: '_styleguide/template.hbs' + }); + +}); + +gulp.task('default', ['sass'], function() { + gulp.watch(['_scss/**/*.scss'], ['sass']); + gulp.watch(['_styleguide/**/*.*'], ['styleguide']); +}); diff --git a/pool/shard005/JavaScript/0033077_stubs.js b/pool/shard005/JavaScript/0033077_stubs.js new file mode 100644 index 0000000000000000000000000000000000000000..20ea3a92cca73868486154135dc76bcf4bc99fa9 --- /dev/null +++ b/pool/shard005/JavaScript/0033077_stubs.js @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2018. Wise Wild Web + * + * This File is part of Caipi and under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License + * Full license at https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode + * + * @author : Nathanael Braun + * @contact : caipilabs@gmail.com + */ + +let _stubs = require("$map(db/stubs, **.js)"), + stubs = {}; + + +Object.keys(_stubs).forEach( + etty => { + let map = stubs[etty] = {all : [], byId : {}}; + _stubs[etty].forEach(( v ) => { + map.all.push(v); + map.byId[v._id] = v; + }) + } +); + +export default stubs; diff --git a/pool/shard005/JavaScript/0033079_sort.directive.js b/pool/shard005/JavaScript/0033079_sort.directive.js new file mode 100644 index 0000000000000000000000000000000000000000..4f74d6ac4aae8b1dcbcb9d267a82ba4253211c31 --- /dev/null +++ b/pool/shard005/JavaScript/0033079_sort.directive.js @@ -0,0 +1,54 @@ +'use strict'; + +angular.module('mongohipsterApp') + .directive('jhSort', function () { + return { + restrict: 'A', + scope: { + predicate: '=jhSort', + ascending: '=', + callback: '&' + }, + controller: ['$scope', function ($scope) { + this.sort = function (field) { + if (field !== $scope.predicate) { + $scope.ascending = true; + } else { + $scope.ascending = !$scope.ascending; + } + $scope.predicate = field; + $scope.$apply(); + $scope.callback(); + } + this.applyClass = function (element) { + var allThIcons = element.parent().find('span.glyphicon'), + sortIcon = 'glyphicon-sort', + sortAsc = 'glyphicon-sort-by-attributes', + sortDesc = 'glyphicon-sort-by-attributes-alt', + remove = sortIcon + ' ' + sortDesc, + add = sortAsc, + thisIcon = element.find('span.glyphicon'); + if (!$scope.ascending) { + remove = sortIcon + ' ' + sortAsc; + add = sortDesc; + } + allThIcons.removeClass(sortAsc + ' ' + sortDesc); + allThIcons.addClass(sortIcon); + thisIcon.removeClass(remove); + thisIcon.addClass(add); + } + }] + } + }).directive('jhSortBy', function () { + return { + restrict: 'A', + scope: false, + require: '^jhSort', + link: function (scope, element, attrs, parentCtrl) { + element.bind('click', function () { + parentCtrl.sort(attrs.jhSortBy); + parentCtrl.applyClass(element); + }); + } + }; + }); diff --git a/pool/shard005/JavaScript/0033082_ReactHighcharts.src.js b/pool/shard005/JavaScript/0033082_ReactHighcharts.src.js new file mode 100644 index 0000000000000000000000000000000000000000..a61e18ed4cc05092946009cec6eced30e05fb0f3 --- /dev/null +++ b/pool/shard005/JavaScript/0033082_ReactHighcharts.src.js @@ -0,0 +1,166 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(require("react"), require("highcharts")); + else if(typeof define === 'function' && define.amd) + define(["react", "highcharts"], factory); + else if(typeof exports === 'object') + exports["ReactHighcharts"] = factory(require("react"), require("highcharts")); + else + root["ReactHighcharts"] = factory(root["React"], root["Highcharts"]); +})(this, function(__WEBPACK_EXTERNAL_MODULE_3__, __WEBPACK_EXTERNAL_MODULE_4__) { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + module.exports = __webpack_require__(1); + + +/***/ }, +/* 1 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + module.exports = __webpack_require__(2)('Chart', __webpack_require__(4)); + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {'use strict'; + + 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; }; + + var React = __webpack_require__(3); + + module.exports = function (chartType, Highcharts) { + var displayName = 'Highcharts' + chartType; + var result = React.createClass({ + displayName: displayName, + + propTypes: { + config: React.PropTypes.object.isRequired, + isPureConfig: React.PropTypes.bool, + neverReflow: React.PropTypes.bool, + callback: React.PropTypes.func + }, + + defaultProps: { + callback: function callback() {} + }, + + renderChart: function renderChart(config) { + var _this = this; + + if (!config) { + throw new Error('Config must be specified for the ' + displayName + ' component'); + } + var chartConfig = config.chart; + this.chart = new Highcharts[chartType](_extends({}, config, { + chart: _extends({}, chartConfig, { + renderTo: this.refs.chart + }) + }), this.props.callback); + + global.requestAnimationFrame && requestAnimationFrame(function () { + _this.chart && _this.chart.options && _this.chart.reflow(); + }); + }, + + shouldComponentUpdate: function shouldComponentUpdate(nextProps) { + if (this.props.neverReflow || this.props.isPureConfig && this.props.config === nextProps.config) { + return true; + } + this.renderChart(nextProps.config); + return false; + }, + + + getChart: function getChart() { + if (!this.chart) { + throw new Error('getChart() should not be called before the component is mounted'); + } + return this.chart; + }, + + componentDidMount: function componentDidMount() { + this.renderChart(this.props.config); + }, + + componentWillUnmount: function componentWillUnmount() { + this.chart.destroy(); + }, + + + render: function render() { + var props = this.props; + props = _extends({}, props, { + ref: 'chart' + }); + return React.createElement('div', props); + } + }); + + result.Highcharts = Highcharts; + return result; + }; + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }, +/* 3 */ +/***/ function(module, exports) { + + module.exports = __WEBPACK_EXTERNAL_MODULE_3__; + +/***/ }, +/* 4 */ +/***/ function(module, exports) { + + module.exports = __WEBPACK_EXTERNAL_MODULE_4__; + +/***/ } +/******/ ]) +}); +; \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033084_divide.js b/pool/shard005/JavaScript/0033084_divide.js new file mode 100644 index 0000000000000000000000000000000000000000..6c483299bd024b7ae393e4cae40186c91ee0056b --- /dev/null +++ b/pool/shard005/JavaScript/0033084_divide.js @@ -0,0 +1,90 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createDivide = void 0; + +var _factory = require("../../utils/factory"); + +var _object = require("../../utils/object"); + +var _algorithm = require("../../type/matrix/utils/algorithm11"); + +var _algorithm2 = require("../../type/matrix/utils/algorithm14"); + +var name = 'divide'; +var dependencies = ['typed', 'matrix', 'multiply', 'equalScalar', 'divideScalar', 'inv']; +var createDivide = +/* #__PURE__ */ +(0, _factory.factory)(name, dependencies, function (_ref) { + var typed = _ref.typed, + matrix = _ref.matrix, + multiply = _ref.multiply, + equalScalar = _ref.equalScalar, + divideScalar = _ref.divideScalar, + inv = _ref.inv; + var algorithm11 = (0, _algorithm.createAlgorithm11)({ + typed: typed, + equalScalar: equalScalar + }); + var algorithm14 = (0, _algorithm2.createAlgorithm14)({ + typed: typed + }); + /** + * Divide two values, `x / y`. + * To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`. + * + * Syntax: + * + * math.divide(x, y) + * + * Examples: + * + * math.divide(2, 3) // returns number 0.6666666666666666 + * + * const a = math.complex(5, 14) + * const b = math.complex(4, 1) + * math.divide(a, b) // returns Complex 2 + 3i + * + * const c = [[7, -6], [13, -4]] + * const d = [[1, 2], [4, 3]] + * math.divide(c, d) // returns Array [[-9, 4], [-11, 6]] + * + * const e = math.unit('18 km') + * math.divide(e, 4.5) // returns Unit 4 km + * + * See also: + * + * multiply + * + * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Numerator + * @param {number | BigNumber | Fraction | Complex | Array | Matrix} y Denominator + * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Quotient, `x / y` + */ + + return typed('divide', (0, _object.extend)({ + // we extend the signatures of divideScalar with signatures dealing with matrices + 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(x, y) { + // TODO: implement matrix right division using pseudo inverse + // https://www.mathworks.nl/help/matlab/ref/mrdivide.html + // https://www.gnu.org/software/octave/doc/interpreter/Arithmetic-Ops.html + // https://stackoverflow.com/questions/12263932/how-does-gnu-octave-matrix-division-work-getting-unexpected-behaviour + return multiply(x, inv(y)); + }, + 'DenseMatrix, any': function DenseMatrixAny(x, y) { + return algorithm14(x, y, divideScalar, false); + }, + 'SparseMatrix, any': function SparseMatrixAny(x, y) { + return algorithm11(x, y, divideScalar, false); + }, + 'Array, any': function ArrayAny(x, y) { + // use matrix implementation + return algorithm14(matrix(x), y, divideScalar, false).valueOf(); + }, + 'any, Array | Matrix': function anyArrayMatrix(x, y) { + return multiply(x, inv(y)); + } + }, divideScalar.signatures)); +}); +exports.createDivide = createDivide; \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033088_pointing.js b/pool/shard005/JavaScript/0033088_pointing.js new file mode 100644 index 0000000000000000000000000000000000000000..312d5188de2e9d8dd1292820727123f5d84de57d --- /dev/null +++ b/pool/shard005/JavaScript/0033088_pointing.js @@ -0,0 +1,43 @@ +// Translate touch and mouse events to canvas-relative coords +// etc. + +;(function(exports) { + +'use strict'; + +// XXX review the touch API and see if this is right +function touchCoords(canvas, touch) { + return canvasCoords(canvas, touch.clientX, touch.clientY); +} + +function mouseCoords(canvas, event) { + return canvasCoords(canvas, event.clientX, event.clientY); +} + +function canvasCoords(canvas, pageX, pageY) { + const canvasBounds = canvas.getBoundingClientRect(); + return {x: pageX - canvasBounds.left, + y: pageY - canvasBounds.top}; +} + +function mouseHandler(canvas, handler) { + return event => handler(mouseCoords(canvas, event)); +} + +function leftButtonOnly(handler) { + return event => { + if (event.button === 0) { // left mouse button + handler(event); + } + }; +} + +if (exports.mathtoys === void 0) exports.mathtoys = {}; +exports.mathtoys.pointing = { + touchCoords, + mouseCoords, + //canvasCoords, + mouseHandler, + leftButtonOnly, +}; +})(this); diff --git a/pool/shard005/JavaScript/0033089_maps_http_geolocation_error_404.js b/pool/shard005/JavaScript/0033089_maps_http_geolocation_error_404.js new file mode 100644 index 0000000000000000000000000000000000000000..7a9c413e979ac8ad48a1a8f379aee4d391d313a9 --- /dev/null +++ b/pool/shard005/JavaScript/0033089_maps_http_geolocation_error_404.js @@ -0,0 +1,24 @@ +// [START maps_http_geolocation_error_404] +var axios = require('axios'); +var data = JSON.stringify({ + "considerIP": false +}); + +var config = { + method: 'post', + url: 'https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_API_KEY', + headers: { + 'content-type': 'application/json' + }, + data : data +}; + +axios(config) +.then(function (response) { + console.log(JSON.stringify(response.data)); +}) +.catch(function (error) { + console.log(error); +}); + +// [END maps_http_geolocation_error_404] \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033094_body.js b/pool/shard005/JavaScript/0033094_body.js new file mode 100644 index 0000000000000000000000000000000000000000..afc5c314755aacdba5501528ba3054e31315d7d9 --- /dev/null +++ b/pool/shard005/JavaScript/0033094_body.js @@ -0,0 +1,109 @@ +import React from 'react'; +import {createStore, combineReducers} from 'redux'; +import {reducer as formReducer, initialize} from 'redux-form'; +import {Provider} from 'react-redux'; +import Liform from 'liform-react'; +import {renderField, DefaultTheme} from 'liform-react'; +import {setSchema, setOnChange, setBodyKey} from './actions'; +import {schemaReducer, onChangeReducer, bodyKeyReducer} from './reducers'; +import PropTypes from 'prop-types'; +/** + * Represents the container for the liform-react form + * @class {object} MyBaseForm + * @param {object} props - properties to initialise the editor UI + * @return {object} MyBaseForm + */ +const MyBaseForm = (props) => { + const {schema, theme, error} = props; + return ( +
    +
    + {error && {error}} + {error &&
    } +
    + {renderField(schema, schema.title, theme || DefaultTheme)} +
    ); +}; + +/** + * Class to control the BasicEditor body UI + * @class BasicBody + * @extends React.Component + */ +class BasicBody extends React.Component { + /** + * Constructor to initialise the UI Body + * @param {object} props - properties to initialise the editor UI Body + */ + constructor(props) { + super(props); + + const reducer = combineReducers({ + form: formReducer, + schema: schemaReducer, + onChange: onChangeReducer, + bodyKey: bodyKeyReducer, + }); + + const store = (window.devToolsExtension ? + window.devToolsExtension()(createStore) : createStore)(reducer); + store.dispatch(setSchema(props.schema)); + store.dispatch(setOnChange(props.onChange)); + store.dispatch(setBodyKey(Date.now())); + + this.state = store.getState(); + this.schema = this.state.schema; + this.store = store; + } + /** + * Method to be called after this component mounts successfully + */ + componentDidMount() { + this.store.subscribe(() => { + this.schema = this.state.schema; + let key = this.state.schema.title || 'form'; + let values = this.store.getState().form[key]; + if (values) { + values = values.values; + this.state.onChange(values); + } + }); + } + /** + * Method to be used to render the component + * @return {object} provider - container for managing liform-react UI state + */ + render() { + return ( + + ); + } + /** + * Methods to be used to set data within liform react-editor + * @param {object} data - data to be set within the editor + */ + setData(data) { + const name = this.props.schema.title || 'form'; + this.store.dispatch(initialize(name, data)); + } +} + +MyBaseForm.propTypes = { + schema: PropTypes.object, + error: PropTypes.object, + theme: PropTypes.array, +}; + +BasicBody.propTypes = { + schema: PropTypes.object, + onChange: PropTypes.func, + data: PropTypes.object, + ajv: PropTypes.object, +}; + +export default BasicBody; +export {MyBaseForm}; diff --git a/pool/shard005/JavaScript/0033096_report.controller.js b/pool/shard005/JavaScript/0033096_report.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..5564cd11bf1a93a8771ce59d0f25b6d6be30b0a8 --- /dev/null +++ b/pool/shard005/JavaScript/0033096_report.controller.js @@ -0,0 +1,225 @@ +/** + * Copyright (C) 2015 Mabel Ticketing + * GNU General Public License v2.0 + * https://github.com/mabelticketing/mabel/blob/master/LICENSE.txt + */ + +/* global _ */ +angular.module('mabel.admin') + .controller("ReportController", ReportController); + +function ReportController($scope, APICaller, $modal) { + var vm = this; + var t = { + tables: [], + joins: [], + cols: [], + filters: [], + pageSize: 10 + } + vm.pageNum = 1; + vm.tableNames = []; + vm.schemata = {}; + vm.t = t; + r = vm; + + APICaller.get("schema", {}, + function(err, data) { + if (err) return alert("ERROR " + err); + vm.tableNames = data; + }); + + function fieldify(col) { + return col.table + "." + col.Field; + } + vm.fieldify = fieldify; + vm.updateData = function updateData() { + console.log(r.pageNum); + // TODO: just send over t, and let the server unpick it + APICaller.get("schema/data", { + from: (vm.pageNum - 1) * t.pageSize, + size: t.pageSize, + columns: JSON.stringify(t.cols.map(fieldify)), + tables: JSON.stringify(t.tables), + joins: JSON.stringify(t.joins), + filters: JSON.stringify(t.filters) + }, + function(err, data) { + if (err) return alert("ERROR " + err); + console.log(data); + vm.data = data.data; + vm.dataSize = data.size; + }); + + } + vm.rmCol = function(col) { + t.cols.splice(t.cols.indexOf(col), 1); + } + + vm.filter = function(col) { + // TODO: Other filters as well as equals (e.g. <, <>) + // TODO (maybe): "OR" filters (currently it's a big conjunction) + var q = prompt("What would you like to search for the value of '" + col.Field + "'?") + t.filters.push({ + field: fieldify(col), + precise: true, // TODO: make this imprecise for text fields + value: q // TODO: parseNumber for numeric fields + }) + vm.updateData(); + } + vm.lookUpSchema = function(table, callback) { + if (callback === undefined) callback = function(){}; + if (vm.schemata[table] === undefined) { + APICaller.get("schema/" + table, {}, + function(err, data) { + if (err) return alert("ERROR " + err); + data.forEach(function(d) { + d.table = table; + }) + vm.schemata[table] = data; + callback(data); + }); + } else { + callback(vm.schemata[table]) + } + } + vm.init = function(table) { + t.tables.push(table); + vm.pageNum = 1 + // TODO (maybe): preload all schemata instead of on-demand? + vm.lookUpSchema(table, function(d) { + t.cols = d; + vm.updateData(); + }) + + } + vm.getCSV = function() { + + // enclose a string in quotes so the comma is escaped. + // also replace any quote-marks with escaped versions. + function esc(s) { + return "\"" + ("" + s).replace(/"/g, "\\\"") + "\"" + } + + // first get all data, regardless of page limits + APICaller.get("schema/data", { + columns: JSON.stringify(t.cols.map(fieldify)), + tables: JSON.stringify(t.tables), + joins: JSON.stringify(t.joins) + }, + function(err, data) { + if (err) return alert("ERROR " + err); + data = data.data; + var csv = ""; + for (var i = -1; i < data.length; i++) { + var sep = ""; + for (var j = 0; j < t.cols.length; j++) { + // prepare the first row according to schema + if (i < 0) { + csv += sep + esc(t.cols[j].Field); + } else { + csv += sep + esc(data[i][t.cols[j].table + "_" + t.cols[j].Field]); + } + sep = ","; + } + csv += "\n"; + } + + var d = new Date(); + var a = document.createElement('a'); + a.href = "data:text/csv;charset=utf-8," + encodeURIComponent(csv); + a.target = '_blank'; + a.download = t.tables.join("-") + "_" + d.getDate() + "-" + d.getMonth() + '.csv'; + + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + }); + } + vm.saveTable = function() { + alert("This doesn't work yet, but I've console.log'd the table description.") + // TODO: reduce t down further + // e.g. remove unneccessary bits of 'col' + // e.g. perhaps shrink property names (too far?) + console.log(JSON.stringify(t)); + } + vm.updatePage = function(a) { + vm.pageNum = Math.ceil(a); + vm.updateData(); + } + vm.alert = function(a) { + alert(a); + } + vm.showJoin = function(col) { + + var modalInstance = $modal.open({ + templateUrl: 'join.html', + controller: 'JoinModalController', + size: "sm", + resolve: { + tables: function () { + return vm.tableNames; + }, + schemata: function () { + return vm.schemata; + }, + lookUpSchema: function () { + return vm.lookUpSchema; + }, + data: function() { + return col; + } + } + }); + + modalInstance.result.then(function (r) { + var field = r.field; + + t.tables.push(field.table); + t.joins.push({ + left: fieldify(col), + right: fieldify(field) + }); + + vm.lookUpSchema(field.table, function(fields) { + for (var i = 0; i < fields.length; i++) { + if (fields[i] !== field) { + t.cols.push(fields[i]); + } + } + vm.updateData(); + }); + }, function (err) { + // do something with dismissal? + }); + } +} + +angular.module('mabel.admin').filter('floor', function() { + return Math.floor +}); +angular.module('mabel.admin').filter('ceil', function() { + return Math.ceil +}); +angular.module('mabel.admin').filter('min', function() { + return function(a) { + return Math.min.apply(null, a); + } +}); + + +angular.module('mabel.admin').controller('JoinModalController', function($scope, $modalInstance, tables, schemata, lookUpSchema, data) { + $scope.result = {}; + $scope.tables = tables; + $scope.schemata = schemata; + $scope.lookUpSchema = lookUpSchema; + $scope.data = data; + + $scope.ok = function() { + $modalInstance.close($scope.result); + }; + + $scope.cancel = function() { + $modalInstance.dismiss('cancel'); + }; +}); \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033100_get.js b/pool/shard005/JavaScript/0033100_get.js new file mode 100644 index 0000000000000000000000000000000000000000..7b5fdbd3e02f2b57dff2fe83113680abe76710f9 --- /dev/null +++ b/pool/shard005/JavaScript/0033100_get.js @@ -0,0 +1,40 @@ +const { strict: assert } = require('assert'); +const faker = require('faker'); +const { createOrganization } = require('../../../helpers/organization'); + +describe('#get organization', function registerSuite() { + this.timeout(50000); + + beforeEach(global.startService); + beforeEach(function pretest() { + return createOrganization.call(this, {}, 2); + }); + afterEach(global.clearRedis); + + it('must reject invalid organization params and return detailed error', async function test() { + await assert.rejects(this.users.dispatch('organization.get', { params: {} }), { + name: 'HttpStatusError', + statusCode: 400, + message: "organization.get validation failed: data must have required property 'organizationId'", + }); + }); + + it('must be able to get organization', async function test() { + const { invites, ...organization } = this.organization; + return this.users.dispatch('organization.get', { params: { organizationId: this.organization.id } }) + .then((response) => { + assert.deepEqual(response.data.attributes, organization); + }); + }); + + it('must return organization not found error', async function test() { + const opts = { + organizationId: faker.company.companyName(), + }; + + await assert.rejects(this.users.dispatch('organization.get', { params: opts }), { + name: 'HttpStatusError', + statusCode: 404, + }); + }); +}); diff --git a/pool/shard005/JavaScript/0033101_repeatingimage.js b/pool/shard005/JavaScript/0033101_repeatingimage.js new file mode 100644 index 0000000000000000000000000000000000000000..9a009d6637026005e9a9f9b29e88b982fb916a4b --- /dev/null +++ b/pool/shard005/JavaScript/0033101_repeatingimage.js @@ -0,0 +1,59 @@ +define(['utils', 'engine/point', 'engine/entity'], function (utils, Point, Entity) { + + var RepeatingImage = Entity.create({ + init: function (imageName) { + this.velocity = new Point(0, 0); + this.offset = new Point(0, 0); + + this.imageName = imageName; + this._image = null; + this.pattern = null; + }, + tick: function () { + this.offset.add(this.velocity); + var size = this.image.size; + + if (this.offset.x > size.width) { + this.offset.x = this.offset.x - size.width; + } + if (this.offset.x < (size.width * -1)) { + this.offset.x = size.width - Math.abs(this.offset.x); + } + if (this.offset.y > size.height) { + this.offset.y = this.offset.y - size.height; + } + if (this.offset.y < (size.height * -1)) { + this.offset.y = size.height - Math.abs(this.offset.y); + } + + Entity.prototype.tick.call(this); + }, + render: function (context) { + if (!this.pattern) { + this.pattern = context.createPattern(this.image.image, 'repeat'); + } + + var translatedFrame = this.frame.clone(); + translatedFrame.origin.sub(this.offset); + + context + .save() + .fillStyle(this.pattern) + .translateUsingPoint(this.offset) + .fillRectUsingFrame(translatedFrame) + .restore(); + + Entity.prototype.render.call(this, context); + }, + }); + + Object.defineProperty(RepeatingImage.prototype, 'image', { + get: function () { + if (!this._image) { this._image = this.engine.assetManager.get(this.imageName); } + return this._image; + } + }); + + return RepeatingImage; + +}); diff --git a/pool/shard005/JavaScript/0033104_jquery.fancytree.debug.js b/pool/shard005/JavaScript/0033104_jquery.fancytree.debug.js new file mode 100644 index 0000000000000000000000000000000000000000..d3df3d4575927ce09810a14948784c9eba38fa83 --- /dev/null +++ b/pool/shard005/JavaScript/0033104_jquery.fancytree.debug.js @@ -0,0 +1,142 @@ +/*! + * jquery.fancytree.debug.js + * + * Miscellaneous debug extensions. + * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) + * + * Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de) + * + * Released under the MIT license + * https://github.com/mar10/fancytree/wiki/LicenseInfo + * + * @version @VERSION + * @date @DATE + */ + +;(function($, window, document, undefined) { + +"use strict"; + +// prevent duplicate loading +// if ( $.ui.fancytree && $.ui.fancytree.version ) { +// $.ui.fancytree.warn("Fancytree: duplicate include"); +// return; +// } + + +/* ***************************************************************************** + * Private functions and variables + */ +var i, + HOOK_NAMES = "nodeClick nodeCollapseSiblings".split(" "), + EVENT_NAMES = "activate beforeActivate".split(" "), + HOOK_NAME_MAP = {}, + EVENT_NAME_MAP = {}; + +for(i=0; i tag + traceEvents: false, // `true`or list of hook names + traceHooks: false // `true`or list of event names + }, + // Overide virtual methods for this extension. + // `this` : is this Fancytree object + // `this._super`: the virtual function that was overridden (member of prev. extension or Fancytree) + treeInit: function(ctx){ + var tree = ctx.tree; + + // Bind init-handler to apply cookie state + tree.$div.bind("fancytreeinit", function(event){ + tree.debug("COOKIE " + document.cookie); + }); + // Init the tree + this._superApply(arguments); + }, + nodeClick: function(ctx) { + if(this.options.tracecalls.traceHooks){ + this.debug(); + } + }, + nodeCollapseSiblings: function(ctx) { + }, + nodeDblclick: function(ctx) { + }, + nodeKeydown: function(ctx) { + }, + nodeLoadChildren: function(ctx, source) { + }, + nodeOnFocusInOut: function(ctx) { + }, + nodeRemoveChildMarkup: function(ctx) { + }, + nodeRemoveMarkup: function(ctx) { + }, + nodeRender: function(ctx, force, deep, collapsed, _recursive) { + }, + nodeRenderStatus: function(ctx) { + }, + nodeRenderTitle: function(ctx, title) { + }, + nodeSetActive: function(ctx, flag, opts) { + }, + nodeSetExpanded: function(ctx, flag, opts) { + }, + nodeSetFocus: function(ctx) { + }, + nodeSetSelected: function(ctx, flag) { + }, + nodeSetStatus: function(ctx, status, message, details) { + }, + nodeToggleExpanded: function(ctx) { + }, + nodeToggleSelected: function(ctx) { + }, + treeClear: function(ctx) { + }, + treeCreate: function(ctx) { + }, + treeDestroy: function(ctx) { + }, +// treeInit: function(ctx) { +// }, + treeLoad: function(ctx, source) { + }, + treeSetFocus: function(ctx, flag) { + } +}); + +}(jQuery, window, document)); + + + +/* ***************************************************************************** + * Fancytree extension: profiler + */ +;(function($, window, document, undefined) { + $.ui.fancytree.registerExtension({ + name: "profiler", + version: "@VERSION", + // Default options for this extension + options: { + prefix: "" + }, + // Overide virtual methods for this extension + nodeRender: function(ctx, force, deep, collapsed){ + // ctx.tree.debug("**** PROFILER nodeRender"); + var s = this.options.prefix + "render '" + ctx.node + "'"; + /*jshint expr:true */ + window.console && window.console.time && window.console.time(s); + this._superApply(arguments); + window.console && window.console.timeEnd && window.console.timeEnd(s); + } + }); +}(jQuery, window, document)); diff --git a/pool/shard005/JavaScript/0033108_DropZone.js b/pool/shard005/JavaScript/0033108_DropZone.js new file mode 100644 index 0000000000000000000000000000000000000000..765de7585a12db93aef13f06b954ab5de9ad0626 --- /dev/null +++ b/pool/shard005/JavaScript/0033108_DropZone.js @@ -0,0 +1,244 @@ +/* + +This file is part of Ext JS 4 + +Copyright (c) 2011 Sencha Inc + +Contact: http://www.sencha.com/contact + +GNU General Public License Usage +This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. + +If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. + +*/ +/** + * @class Ext.view.DropZone + * @extends Ext.dd.DropZone + * @private + */ +Ext.define('Ext.view.DropZone', { + extend: 'Ext.dd.DropZone', + + indicatorHtml: '
    ', + indicatorCls: 'x-grid-drop-indicator', + + constructor: function(config) { + var me = this; + Ext.apply(me, config); + + // Create a ddGroup unless one has been configured. + // User configuration of ddGroups allows users to specify which + // DD instances can interact with each other. Using one + // based on the id of the View would isolate it and mean it can only + // interact with a DragZone on the same View also using a generated ID. + if (!me.ddGroup) { + me.ddGroup = 'view-dd-zone-' + me.view.id; + } + + // The DropZone's encapsulating element is the View's main element. It must be this because drop gestures + // may require scrolling on hover near a scrolling boundary. In Ext 4.x two DD instances may not use the + // same element, so a DragZone on this same View must use the View's parent element as its element. + me.callParent([me.view.el]); + }, + +// Fire an event through the client DataView. Lock this DropZone during the event processing so that +// its data does not become corrupted by processing mouse events. + fireViewEvent: function() { + var me = this, + result; + + me.lock(); + result = me.view.fireEvent.apply(me.view, arguments); + me.unlock(); + return result; + }, + + getTargetFromEvent : function(e) { + var node = e.getTarget(this.view.getItemSelector()), + mouseY, nodeList, testNode, i, len, box; + +// Not over a row node: The content may be narrower than the View's encapsulating element, so return the closest. +// If we fall through because the mouse is below the nodes (or there are no nodes), we'll get an onContainerOver call. + if (!node) { + mouseY = e.getPageY(); + for (i = 0, nodeList = this.view.getNodes(), len = nodeList.length; i < len; i++) { + testNode = nodeList[i]; + box = Ext.fly(testNode).getBox(); + if (mouseY <= box.bottom) { + return testNode; + } + } + } + return node; + }, + + getIndicator: function() { + var me = this; + + if (!me.indicator) { + me.indicator = Ext.createWidget('component', { + html: me.indicatorHtml, + cls: me.indicatorCls, + ownerCt: me.view, + floating: true, + shadow: false + }); + } + return me.indicator; + }, + + getPosition: function(e, node) { + var y = e.getXY()[1], + region = Ext.fly(node).getRegion(), + pos; + + if ((region.bottom - y) >= (region.bottom - region.top) / 2) { + pos = "before"; + } else { + pos = "after"; + } + return pos; + }, + + /** + * @private Determines whether the record at the specified offset from the passed record + * is in the drag payload. + * @param records + * @param record + * @param offset + * @returns {Boolean} True if the targeted record is in the drag payload + */ + containsRecordAtOffset: function(records, record, offset) { + if (!record) { + return false; + } + var view = this.view, + recordIndex = view.indexOf(record), + nodeBefore = view.getNode(recordIndex + offset), + recordBefore = nodeBefore ? view.getRecord(nodeBefore) : null; + + return recordBefore && Ext.Array.contains(records, recordBefore); + }, + + positionIndicator: function(node, data, e) { + var me = this, + view = me.view, + pos = me.getPosition(e, node), + overRecord = view.getRecord(node), + draggingRecords = data.records, + indicator, indicatorY; + + if (!Ext.Array.contains(draggingRecords, overRecord) && ( + pos == 'before' && !me.containsRecordAtOffset(draggingRecords, overRecord, -1) || + pos == 'after' && !me.containsRecordAtOffset(draggingRecords, overRecord, 1) + )) { + me.valid = true; + + if (me.overRecord != overRecord || me.currentPosition != pos) { + + indicatorY = Ext.fly(node).getY() - view.el.getY() - 1; + if (pos == 'after') { + indicatorY += Ext.fly(node).getHeight(); + } + me.getIndicator().setWidth(Ext.fly(view.el).getWidth()).showAt(0, indicatorY); + + // Cache the overRecord and the 'before' or 'after' indicator. + me.overRecord = overRecord; + me.currentPosition = pos; + } + } else { + me.invalidateDrop(); + } + }, + + invalidateDrop: function() { + if (this.valid) { + this.valid = false; + this.getIndicator().hide(); + } + }, + + // The mouse is over a View node + onNodeOver: function(node, dragZone, e, data) { + var me = this; + + if (!Ext.Array.contains(data.records, me.view.getRecord(node))) { + me.positionIndicator(node, data, e); + } + return me.valid ? me.dropAllowed : me.dropNotAllowed; + }, + + // Moved out of the DropZone without dropping. + // Remove drop position indicator + notifyOut: function(node, dragZone, e, data) { + var me = this; + + me.callParent(arguments); + delete me.overRecord; + delete me.currentPosition; + if (me.indicator) { + me.indicator.hide(); + } + }, + + // The mouse is past the end of all nodes (or there are no nodes) + onContainerOver : function(dd, e, data) { + var me = this, + view = me.view, + count = view.store.getCount(); + + // There are records, so position after the last one + if (count) { + me.positionIndicator(view.getNode(count - 1), data, e); + } + + // No records, position the indicator at the top + else { + delete me.overRecord; + delete me.currentPosition; + me.getIndicator().setWidth(Ext.fly(view.el).getWidth()).showAt(0, 0); + me.valid = true; + } + return me.dropAllowed; + }, + + onContainerDrop : function(dd, e, data) { + return this.onNodeDrop(dd, null, e, data); + }, + + onNodeDrop: function(node, dragZone, e, data) { + var me = this, + dropped = false, + + // Create a closure to perform the operation which the event handler may use. + // Users may now return false from the beforedrop handler, and perform any kind + // of asynchronous processing such as an Ext.Msg.confirm, or an Ajax request, + // and complete the drop gesture at some point in the future by calling this function. + processDrop = function () { + me.invalidateDrop(); + me.handleNodeDrop(data, me.overRecord, me.currentPosition); + dropped = true; + me.fireViewEvent('drop', node, data, me.overRecord, me.currentPosition); + }, + performOperation = false; + + if (me.valid) { + performOperation = me.fireViewEvent('beforedrop', node, data, me.overRecord, me.currentPosition, processDrop); + if (performOperation !== false) { + // If the processDrop function was called in the event handler, do not do it again. + if (!dropped) { + processDrop(); + } + } + } + return performOperation; + }, + + destroy: function(){ + Ext.destroy(this.indicator); + delete this.indicator; + this.callParent(); + } +}); + diff --git a/pool/shard005/JavaScript/0033111_DotPlot.js b/pool/shard005/JavaScript/0033111_DotPlot.js new file mode 100644 index 0000000000000000000000000000000000000000..26deb5d2cae35aad6217156c9dfbb3b07b274c70 --- /dev/null +++ b/pool/shard005/JavaScript/0033111_DotPlot.js @@ -0,0 +1,246 @@ +function DotPlot() { + "use strict"; + +//Internals + var self = this; + var container = null, + svg = null, + data = null, + valueAxisLayer = null, + categoryAxisLayer = null, + itemLayer = null, + xScale = d3.time.scale(), + yScale = d3.scale.ordinal(), + rScale = d3.scale.linear(), + circles = null, + nodes = null, + selectedItem = null; + +//Properties + var width = 100, + height = 100, + margin = 10, + rMultiplier = 1, + parseTime = d3.time.format.utc("%Y-%m-%d %H:%M:%S").parse, + getX = function(d) { return d; }, + getY = function(d) { return d; }, + getR = function(d) { return d; }, + getID = function(d) { return d; }, + getTooltip = function(d) { return d; }, + selectionCallback = null; + +//Priviliged methods + this.initialize = function(containerSelection) { + container = containerSelection; + svg = container.append("svg") + .attr("class", "dot-plot"); + + valueAxisLayer = svg.append("g"); + categoryAxisLayer = svg.append("g"); + itemLayer = svg.append("g"); + + layout(); + + return self; + } + + this.selectedItem = function(item) { + if (!arguments.length) return selectedItem; + + selectedItem = item; + + if (nodes == null) + return self; + + var findVal = getID(item); + var oldItem = nodes.filter(".selected") + .classed("selected", false); + var newItem = nodes.filter(function(d,i) { return getID(d)==findVal; }) + .classed("selected", true); + + return self; + } + + this.data = function(value) { + if (!arguments.length) return data; + data = value.splice(0).sort(function(a,b) { return getR(b)-getR(a); }); + updateElements(); + layout(); + return self; + } + + this.onSizeChanged = function() { + layout(); + return self; + } + + this.rMultiplier = function(func) { + if (!arguments.length) return rMultiplier; + rMultiplier = func; + return self; + } + + this.getX = function(func) { + if (!arguments.length) return getX; + getX = func; + return self; + } + + this.getY = function(func) { + if (!arguments.length) return getY; + getY = func; + return self; + } + + this.getR = function(func) { + if (!arguments.length) return getR; + getR = func; + return self; + } + + this.getID = function(func) { + if (!arguments.length) return getID; + getID = func; + return self; + } + + this.getTooltip = function(func) { + if (!arguments.length) return getTooltip; + getTooltip = func; + return self; + } + + this.onItemSelected = function(func) { + if (!arguments.length) return selectionCallback; + selectionCallback = func; + return self; + } + + this.doLayout = function() { + layout(); + return self; + } + +//Private methods + function updateElements() { + if (svg == null || data == null) + return; + + data.forEach(function(d) { + d.dotplot_filter_time = parseTime(getX(d)); + }); + + var uniqueYValues = data.map(getY).unique(); + yScale.domain(uniqueYValues); + xScale.domain(d3.extent(data.map(function(d) { return d.dotplot_filter_time; }))); + rScale.domain([0, d3.max(data, function(d) { return Math.sqrt(getR(d)); })]); + + //Update circles + itemLayer.selectAll("g.data-item").remove(); + + nodes = itemLayer.selectAll("g.data-item") + .data(data); + + nodes.enter().append("g") + .attr("class", "data-item") + .on("mousedown", onItemSelected) + .on("mouseover", function(d, i) { + d3.select(this) + .classed("mouseover", true); + }) + .on("mouseout", function(d, i) { + d3.select(this) + .classed("mouseover", false); + }) + .append("circle"); + + circles = nodes.selectAll("circle"); + + nodes.append("title").text(getTooltip); + + } + + function layout() { + if (container == null || data == null) { + return; + } + + if (nodes == null) { + updateElements(); + } + + width = $(container.node()).width(); + height = $(container.node()).height(); + + yScale.rangePoints([0, height], 1); + xScale.range([margin, width-margin]); + rScale.range([2, 40]); + + layoutCategoryAxis(); + layoutValueAxis(); + layoutItems(); + } + + function layoutItems() { + nodes.attr("transform", function(d) { + return "translate(" + xScale(d.dotplot_filter_time) + "," + yScale(getY(d)) + ")"; }) + + circles + .attr("r", function(d) { return rMultiplier*rScale(Math.sqrt(getR(d))); }); + } + + function layoutCategoryAxis() { + var categoryAxes = categoryAxisLayer.selectAll('line') + .data(yScale.range()); + + categoryAxes.enter() + .append("line") + .attr("class", "category-axis"); + + categoryAxes.exit() + .remove(); + + categoryAxes + .attr("x1", 0) + .attr("x2", width) + .attr("y1", function(d) { return d; }) + .attr("y2", function(d) { return d; }) + .attr("class", "y axis"); + + var axisLabels = categoryAxisLayer.selectAll("text.category-label") + .data(yScale.domain(), String); + axisLabels.enter().append("text") + .attr("class", "category-label") + .text(String); + axisLabels.exit() + .remove(); + axisLabels.attr("x", 3) + .attr("y", function(d) { return yScale(d) - 2; }); + } + + function layoutValueAxis() { + var ypos = 16; + + var valueAxis = d3.svg.axis() + .scale(xScale) + .orient('bottom') + .ticks(Math.round(width/50)) + .tickSize(-(height-ypos)) + .tickSubdivide(true); + + valueAxisLayer + .attr("class", "x axis") + .attr("transform", "translate(0, " + (height-ypos) + ")") + .call(valueAxis); + } + + function onItemSelected(d, i) { + if (selectedItem == d) + return; + + if (selectionCallback != null) { + self.selectedItem(d); + selectionCallback(d, i); + } + } +} \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033114_AbstractNotification.js b/pool/shard005/JavaScript/0033114_AbstractNotification.js new file mode 100644 index 0000000000000000000000000000000000000000..61c10ef283c0f80ae9784a100e09ce339c6070f1 --- /dev/null +++ b/pool/shard005/JavaScript/0033114_AbstractNotification.js @@ -0,0 +1,75 @@ +/** + * @author Geert Fokke [geert@sector22.com] + * @www sector22.com + * @module sector22/control/notification + */ + +// @formatter:off + +var inherits = require('../../core/utils/inherits'); + +// @formatter:on + +/** + * Creates a new Notification to be used with the notification center. + * @param type {string} + * @param opt_target {object=} + * @param opt_message {string=} + * @param opt_data {object=} + * @constructor + */ +function AbstractNotification ( type, opt_target, opt_message, opt_data ) { + + var _type = type; + var _target = opt_target; + var _message = opt_message; + var _data = opt_data; + + Object.defineProperty(this, 'type', { + enumerable: true, + get: function() { + return _type; + } + }); + + Object.defineProperty(this, 'target', { + enumerable: true, + get: function() { + return _target; + } + }); + + Object.defineProperty(this, 'message', { + enumerable: true, + get: function() { + return _message; + } + }); + + Object.defineProperty(this, 'data', { + enumerable: true, + get: function() { + return _data; + } + }); + +} + + +/** + * Function to easily inherit the CoreEvent class. + * @memberOf sector22/core/events.CoreEvent + * @protected + * @function extend + * @param constructor {function} the class that should inherit the CoreEvent + */ +AbstractNotification.prototype.extend = function ( constructor ) { + + inherits( constructor, this ); + constructor.extend = AbstractNotification.extend; + +} + +AbstractNotification.extend = AbstractNotification.prototype.extend; + +module.exports = AbstractNotification; \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033118_WebSound.js b/pool/shard005/JavaScript/0033118_WebSound.js new file mode 100644 index 0000000000000000000000000000000000000000..9d6850672af455e5453cdddceacc3880ba9ab79b --- /dev/null +++ b/pool/shard005/JavaScript/0033118_WebSound.js @@ -0,0 +1,103 @@ +/** + * hilojs 2.0.2 for commonjs + * Copyright 2016 alibaba.com + * Licensed under the MIT License + */ +var HTMLAudio = require('./HTMLAudio'); +var WebAudio = require('./WebAudio'); +var util = require('../util/util'); + + + +/** + * @language=en + * + *
    + * demo: + *
    + * var audio = WebSound.getAudio({
    + *     src: 'test.mp3',
    + *     loop: false,
    + *     volume: 1
    + * }).on('load', function(e){
    + *     console.log('load');
    + * }).on('end', function(e){
    + *     console.log('end');
    + * }).play();
    + * 
    + * @class Audio playing manager. + * @static + * @module hilo/media/WebSound + * @requires hilo/media/HTMLAudio + * @requires hilo/media/WebAudio + * @requires hilo/util/util + */ +var WebSound = { + _audios: {}, + + /** + * @language=en + * Activate audio function. Note: Require user action events to activate. Currently support WebAudio. + */ + enableAudio: function(){ + if(WebAudio.isSupported){ + WebAudio.enable(); + } + }, + + /** + * @language=en + * Get audio element. Default use WebAudio if supported. + * @param {String|Object} source If String, it's the source of the audio; If Object, it should contains a src property. + * @param {Boolean} [preferWebAudio=true] Whether or not to use WebAudio first, default is true. + * @returns {WebAudio|HTMLAudio} Audio playing instance. + */ + getAudio: function(source, preferWebAudio){ + if(preferWebAudio === undefined){ + preferWebAudio = true; + } + + source = this._normalizeSource(source); + var audio = this._audios[source.src]; + if(!audio){ + if(preferWebAudio && WebAudio.isSupported){ + audio = new WebAudio(source); + }else if(HTMLAudio.isSupported){ + audio = new HTMLAudio(source); + } + this._audios[source.src] = audio; + } + + return audio; + }, + + /** + * @language=en + * Remove audio element. + * @param {String|Object} source If String, it's the source of the audio; If Object, it should contains a src property. + */ + removeAudio: function(source){ + var src = typeof source === 'string' ? source : source.src; + var audio = this._audios[src]; + if(audio){ + audio.stop(); + audio.off(); + this._audios[src] = null; + delete this._audios[src]; + } + }, + + /** + * @language=en + * @private + */ + _normalizeSource: function(source){ + var result = {}; + if(typeof source === 'string') result = {src:source}; + else util.copy(result, source); + return result; + } + +}; + +module.exports = WebSound; \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033120_loginREST.js b/pool/shard005/JavaScript/0033120_loginREST.js new file mode 100644 index 0000000000000000000000000000000000000000..248229c95fdc43a5563e4035fbc251d8a8571006 --- /dev/null +++ b/pool/shard005/JavaScript/0033120_loginREST.js @@ -0,0 +1,228 @@ +/* +Copyright IBM Corporation 2016, 2017 + +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 BaseREST = require("./BaseREST.js"); + +// Require the modules used by this component. +const Q = require("q"); +const options = require("./utils/options.js"); +const utils = require("./utils/utils.js"); + +// Get the utility modules used by this component. +const request = utils.getRequestWrapper(); +const i18n = utils.getI18N(__dirname + "/nls", ".json", "en"); + +// Define the symbols used by the singleton logic. +const singleton = Symbol(); +const singletonEnforcer = Symbol(); + +// FUTURE Need to work on this abstraction. LoginREST extends BaseREST so that it can leverage the addRetryOptions() +// FUTURE method. It does not need the rest of the inherited methods. A lower-level common base class may be preferable. +class LoginREST extends BaseREST { + /** + * Constructor. Create a LoginREST object. + * + * @param {Symbol} enforcer - A symbol that must match the pre-defined symbol. + */ + constructor (enforcer) { + if (enforcer !== singletonEnforcer) { + throw i18n.__("singleton_construct_error", {classname: "LoginREST"}); + } + + super("login", "/login/v1/basicauth", undefined, undefined); + } + + /** + * Get the singleton instance for this class. + * + * @returns {LoginREST} The singleton instance for this class. + */ + static get instance () { + if (!this[singleton]) { + this[singleton] = new LoginREST(singletonEnforcer); + } + return this[singleton]; + } + + /** + * Get the request headers to be used for logging in. + * + * @param {Object} context The current API context. + * @param {Object} opts - Optional API settings. + * + * @returns {Object} The request headers to be used for logging in. + */ + static getHeaders (context, opts) { + const hdrs = { + "Connection": "keep-alive", + "User-Agent": utils.getUserAgent() + }; + + // Allow for explicit tenant id defined by an environment variable. + if (process.env.TENANT_ID) { + hdrs["x-ibm-dx-tenant-id"] = process.env.TENANT_ID; + } else { + const id = options.getRelevantOption(context, opts, "x-ibm-dx-tenant-id"); + if (id) { + hdrs["x-ibm-dx-tenant-id"] = id; + } + } + return hdrs; + } + + /** + * Get the request options to be used for logging in. + * + * @param {Object} context The current API context. + * @param {Object} opts - Optional API settings. + * + * @returns {Object} The request options to be used for logging in. + */ + getRequestOptions (context, opts) { + const baseUrl = options.getRelevantOption(context, opts, "x-ibm-dx-tenant-base-url"); + + // FUTURE We expect x-ibm-dx-tenant-base-url should exist before getting here. If not, the error from + // FUTURE the login request is "Invalid URI null/login/v1/basicauth". This isn't very useful. It would be more + // FUTURE useful to throw an Error from here and catch it before login. Or at least add an error to the log. + + // Resolve the promise with the standard request options and the retry options. + const requestOptions = { + uri: this._appendURI(baseUrl, this.getUriPath(context, opts)), + headers: LoginREST.getHeaders(context, opts), + auth: { + "user": opts.username, + "pass": opts.password, + "sendImmediately": true + }, + followRedirect: false, + timeout: options.getRelevantOption(context, opts, "request-timeout") || BaseREST.DEFAULT_TIMEOUT + }; + + return this.addRetryOptions(context, requestOptions, opts); + } + + /** + * Login using the specified options. + * + * @param {Object} context The current API context. + * @param {Object} opts - Optional API settings. + * + * @returns {Q.Promise} A promise to be fulfilled with the name of the logged in user. + */ + login (context, opts) { + const deferred = Q.defer(); + const requestOptions = this.getRequestOptions(context, opts); + const result = {"username": opts.username}; + request.get(requestOptions, function (err, res, body) { + const response = res || {}; + if (err || (response.statusCode !== 200 && response.statusCode !== 302)) { + // An error was returned, or at least an unexpected response code. + if (!err && body && body.includes("FBTBLU101E")) { + err = new Error(body); + } else { + err = utils.getError(err, body, response, requestOptions); + } + + BaseREST.logRetryInfo(context, requestOptions, response.attempts, err); + utils.logErrors(context, "LoginREST.login", err); + deferred.reject(err); + } else if (response.headers && response.headers["set-cookie"] && response.headers["x-ibm-dx-tenant-id"]) { + // The login succeeded. + BaseREST.logRetryInfo(context, requestOptions, response.attempts); + + const tenant = response.headers["x-ibm-dx-tenant-id"]; + const baseUrl = response.headers["x-ibm-dx-tenant-base-url"]; + const existingBaseUrl = options.getRelevantOption(context, opts,"x-ibm-dx-tenant-base-url"); + + // Resolve the promise with the tenant and baseUrl values from the login response. + result["x-ibm-dx-tenant-id"] = tenant; + result["x-ibm-dx-tenant-base-url"] = existingBaseUrl || baseUrl; + result["base-url-from-login-response"] = baseUrl; + context.logger.debug("LoginREST.login: successful authentication to " + result["x-ibm-dx-tenant-base-url"] + " as " + opts.username); + + // Add the tenant tier if it's available. + if (body) { + try { + // A login response originally contained items for each tenant the specified user had access to. + // The response array currently contains only the item for the specific tenant and user. + const bodyObject = JSON.parse(body); + if (Array.isArray(bodyObject) && bodyObject[0]) { + result["tier"] = bodyObject[0].tier; + } + } catch (err) { + // Ignore + } + } + + // Keep track of the returned values, but do not overwrite an existing base URL. + const loginResults = {"x-ibm-dx-tenant-id": tenant}; + if (!existingBaseUrl) { + loginResults["x-ibm-dx-tenant-base-url"] = baseUrl; + } + if (result["tier"]) { + loginResults["tier"] = result["tier"]; + } + context.logger.debug("LoginREST.login: Setting tenant options based on login response: " + JSON.stringify(loginResults)); + context.logger.debug("LoginREST.login: cookie " + response.headers["set-cookie"]); + options.setOptions(context, loginResults); + deferred.resolve(result); + + // Determine the interval to be used for the relogin timer. + let interval = options.getRelevantOption(context, opts, "reloginInterval"); + if (typeof interval !== "number") { + interval = (11 * 60 + 45) * 60 * 1000; + } + context.logger.debug("LoginREST.login: Setting relogin timer to " + interval + "ms."); + + // Create a timer to relogin before the login token expires. + context.reloginTimer = setInterval(function () { + context.logger.debug("LoginREST.login: attempting to relogin"); + request.get(requestOptions, function (err, res, body) { + const response = res || {}; + if (err || (response.statusCode !== 200 && response.statusCode !== 302)) { + // The attempt to relogin failed. + context.logger.debug("LoginREST.login: attempt to relogin failed: " + err + " - " + body); + } else { + // Assume success. + context.logger.debug("LoginREST.login: relogin succeeded: " + JSON.stringify(response.headers["set-cookie"]) + " - " + body); + } + }); + }, interval); + + // Do not keep the event loop running if the timer is the only thing waiting. + context.reloginTimer.unref(); + } else { + BaseREST.logRetryInfo(context, requestOptions, res.attempts); + + // The login did not return the expected authentication token or tenant id. + err = utils.getError(err, body, res, requestOptions); + + // Log the actual error that was returned from the service. + const message = i18n.__("login_missing_authn"); + utils.logErrors(context, message, err); + + // Reject the promise. + deferred.reject(new Error(message)); + } + }); + + return deferred.promise; + } +} + +// Export the class definition. +module.exports = LoginREST; diff --git a/pool/shard005/JavaScript/0033121_jquery-ui.catcomplete.js b/pool/shard005/JavaScript/0033121_jquery-ui.catcomplete.js new file mode 100644 index 0000000000000000000000000000000000000000..48717c9cc961e92c31c982e36f21e4578925500b --- /dev/null +++ b/pool/shard005/JavaScript/0033121_jquery-ui.catcomplete.js @@ -0,0 +1,19 @@ +$.widget( "custom.catcomplete", $.ui.autocomplete, { + _create: function() { + this._super(); + this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" ); + }, + _renderMenu: function( ul, items ) { + var that = this; + + $.each( items, function( index, item ) { + var li; + + li = that._renderItemData( ul, item ); + if ( item.category ) { + li.addClass("cat_"+item.category); + li.attr( "aria-label", item.category + " : " + item.label ); + } + }); + } +}); \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033122_shallowEqual.js b/pool/shard005/JavaScript/0033122_shallowEqual.js new file mode 100644 index 0000000000000000000000000000000000000000..a2cbe04a39b144ca0db9f1918f944a1bb6f51319 --- /dev/null +++ b/pool/shard005/JavaScript/0033122_shallowEqual.js @@ -0,0 +1,36 @@ +function is(x, y) { + if (x === y) { + return x !== 0 || y !== 0 || 1 / x === 1 / y + } else { + return x !== x && y !== y + } +} + +export default function shallowEqual(objA, objB) { + if (is(objA, objB)) return true + + if ( + typeof objA !== 'object' || + objA === null || + typeof objB !== 'object' || + objB === null + ) { + return false + } + + const keysA = Object.keys(objA) + const keysB = Object.keys(objB) + + if (keysA.length !== keysB.length) return false + + for (let i = 0; i < keysA.length; i++) { + if ( + !Object.prototype.hasOwnProperty.call(objB, keysA[i]) || + !is(objA[keysA[i]], objB[keysA[i]]) + ) { + return false + } + } + + return true +} diff --git a/pool/shard005/JavaScript/0033127_example.js b/pool/shard005/JavaScript/0033127_example.js new file mode 100644 index 0000000000000000000000000000000000000000..1ae23d9171eb134ca4669564cd24aa2a519c3ef2 --- /dev/null +++ b/pool/shard005/JavaScript/0033127_example.js @@ -0,0 +1,36 @@ + +let argv = process.argv; + +let email = argv[ 2 ]; +let domains = argv[ 3 ].split( "," ); + +// create a simple express app that returns index.html for all requests +express = require( "express" ); +app = express(); +app.use(function( req, res, next ) { + let html = require("fs").readFileSync( "./index.html", "utf8" ); + res.setHeader( "Content-Type", "text/html; charset=utf-8" ); + res.end( html ); +}); + + +// This function handles incoming websocket connections +let ws = function( socket, req ) { + socket.send( "A socket connection has come in. Welcome, client! I'll be your server today." ); + socket.on( "message", function( data ) { + socket.send( "Hey client, thanks for the message: " + data ); + }); +} + + +// create our cool webserver +let webserver = require( "./webserver.js" ); +webserver({ + http_handler: app, // Required + websocket_handler: ws, // Required + email, // required + domains, // Required + staging: false, // Optional. Defaults to "true". Change to "false" for production. +}); + + diff --git a/pool/shard005/JavaScript/0033128_panel.js b/pool/shard005/JavaScript/0033128_panel.js new file mode 100644 index 0000000000000000000000000000000000000000..ab0338bce034a9204d44d93ba0a5396e82f7ca49 --- /dev/null +++ b/pool/shard005/JavaScript/0033128_panel.js @@ -0,0 +1,49 @@ +define(function() { + var insertPanel = function(model) { + var $panel = $('').css({ + visibility: 'visible', + position: 'absolute', + bottom: 0, + right: 0, + }).attr({ + name: "donation_panel", + src: "coui://ui/mods/donation_panel/donation_panel.html", + 'no-keyboard': true, + 'yield-focus': true, + fit: "dock-bottom-right", + 'data-bind': 'visible: visible', + }) + $panel.appendTo('body') + ko.applyBindings(model, $panel[0]) + api.Panel.bindElement($panel[0]) + } + + var viewModel = { + visible: ko.observable(false), + } + + var inserted = false + var insert = function() { + console.log('insert') + insertPanel(viewModel) + api.panels.options_bar && api.panels.options_bar.message('donation_panel_loading', true) + inserted = true + } + viewModel.visible.subscribe(function(visible) { + if (visible && !inserted) { + insert() + } + }) + + model.toggleDonationPanel = function() { + viewModel.visible(!viewModel.visible()) + } + + return { + insert: insert, + viewModel: viewModel, + show: function() { + viewModel.visible(true) + }, + } +}) diff --git a/pool/shard005/JavaScript/0033131_secrets.js b/pool/shard005/JavaScript/0033131_secrets.js new file mode 100644 index 0000000000000000000000000000000000000000..3adca16c71ff657b48f774f5415c930fb13cf3bb --- /dev/null +++ b/pool/shard005/JavaScript/0033131_secrets.js @@ -0,0 +1,29 @@ +'use strict'; + +var EventEmitter = require('events').EventEmitter; +var emitter = new EventEmitter(); +var util = require('util'); +var File = require('./file'); + +var Secrets = function() { + var that = { + secrets: { + accessToken: undefined, + accessTokenSecret: undefined + } + }; + + that.loadSecrets = function() { + File.readContents('.twitter-api-secrets.json').on('done', function(info) { + emitter.emit('done', info); + }); + return that; + }, + + // Plumbing + that.on = function(event, action) { emitter.on(event, action); } + + return that; +}; + +module.exports = Secrets; diff --git a/pool/shard005/JavaScript/0033132_user.js b/pool/shard005/JavaScript/0033132_user.js new file mode 100644 index 0000000000000000000000000000000000000000..7c829b14c858272338046fd7136cbaaa985b6484 --- /dev/null +++ b/pool/shard005/JavaScript/0033132_user.js @@ -0,0 +1,217 @@ +/** + * @file + * User behaviors. + */ + +(function ($, Drupal, drupalSettings) { + + "use strict"; + + /** + * Attach handlers to evaluate the strength of any password fields and to + * check that its confirmation is correct. + * + * @type {Drupal~behavior} + * + * @prop {Drupal~behaviorAttach} attach + * Attaches password strength indicator and other relevant validation to + * password fields. + */ + Drupal.behaviors.password = { + attach: function (context, settings) { + var $passwordInput = $(context).find('input.js-password-field').once('password'); + + if ($passwordInput.length) { + var translate = settings.password; + + var $passwordInputParent = $passwordInput.parent(); + var $passwordInputParentWrapper = $passwordInputParent.parent(); + var $passwordSuggestions; + + // Add identifying class to password element parent. + $passwordInputParent.addClass('password-parent'); + + // Add the password confirmation layer. + $passwordInputParentWrapper + .find('input.js-password-confirm') + .parent() + .append('
    ' + translate.confirmTitle + '
    ') + .addClass('confirm-parent'); + + var $confirmInput = $passwordInputParentWrapper.find('input.js-password-confirm'); + var $confirmResult = $passwordInputParentWrapper.find('div.js-password-confirm'); + var $confirmChild = $confirmResult.find('span'); + + // If the password strength indicator is enabled, add its markup. + if (settings.password.showStrengthIndicator) { + var passwordMeter = '
    ' + translate.strengthTitle + '
    '; + $confirmInput.parent().after('
    '); + $passwordInputParent.append(passwordMeter); + $passwordSuggestions = $passwordInputParentWrapper.find('div.password-suggestions').hide(); + } + + // Check that password and confirmation inputs match. + var passwordCheckMatch = function (confirmInputVal) { + var success = $passwordInput.val() === confirmInputVal; + var confirmClass = success ? 'ok' : 'error'; + + // Fill in the success message and set the class accordingly. + $confirmChild.html(translate['confirm' + (success ? 'Success' : 'Failure')]) + .removeClass('ok error').addClass(confirmClass); + }; + + // Check the password strength. + var passwordCheck = function () { + if (settings.password.showStrengthIndicator) { + // Evaluate the password strength. + var result = Drupal.evaluatePasswordStrength($passwordInput.val(), settings.password); + + // Update the suggestions for how to improve the password. + if ($passwordSuggestions.html() !== result.message) { + $passwordSuggestions.html(result.message); + } + + // Only show the description box if a weakness exists in the + // password. + $passwordSuggestions.toggle(result.strength !== 100); + + // Adjust the length of the strength indicator. + $passwordInputParent.find('.js-password-strength__indicator') + .css('width', result.strength + '%') + .removeClass('is-weak is-fair is-good is-strong') + .addClass(result.indicatorClass); + + // Update the strength indication text. + $passwordInputParent.find('.js-password-strength__text').html(result.indicatorText); + } + + // Check the value in the confirm input and show results. + if ($confirmInput.val()) { + passwordCheckMatch($confirmInput.val()); + $confirmResult.css({visibility: 'visible'}); + } + else { + $confirmResult.css({visibility: 'hidden'}); + } + }; + + // Monitor input events. + $passwordInput.on('input', passwordCheck); + $confirmInput.on('input', passwordCheck); + } + } + }; + + /** + * Evaluate the strength of a user's password. + * + * Returns the estimated strength and the relevant output message. + * + * @param {string} password + * The password to evaluate. + * @param {object} translate + * An object containing the text to display for each strength level. + * + * @return {object} + * An object containing strength, message, indicatorText and indicatorClass. + */ + Drupal.evaluatePasswordStrength = function (password, translate) { + password = password.trim(); + var indicatorText; + var indicatorClass; + var weaknesses = 0; + var strength = 100; + var msg = []; + + var hasLowercase = /[a-z]/.test(password); + var hasUppercase = /[A-Z]/.test(password); + var hasNumbers = /[0-9]/.test(password); + var hasPunctuation = /[^a-zA-Z0-9]/.test(password); + + // If there is a username edit box on the page, compare password to that, + // otherwise use value from the database. + var $usernameBox = $('input.username'); + var username = ($usernameBox.length > 0) ? $usernameBox.val() : translate.username; + + // Lose 5 points for every character less than 12, plus a 30 point penalty. + if (password.length < 12) { + msg.push(translate.tooShort); + strength -= ((12 - password.length) * 5) + 30; + } + + // Count weaknesses. + if (!hasLowercase) { + msg.push(translate.addLowerCase); + weaknesses++; + } + if (!hasUppercase) { + msg.push(translate.addUpperCase); + weaknesses++; + } + if (!hasNumbers) { + msg.push(translate.addNumbers); + weaknesses++; + } + if (!hasPunctuation) { + msg.push(translate.addPunctuation); + weaknesses++; + } + + // Apply penalty for each weakness (balanced against length penalty). + switch (weaknesses) { + case 1: + strength -= 12.5; + break; + + case 2: + strength -= 25; + break; + + case 3: + strength -= 40; + break; + + case 4: + strength -= 40; + break; + } + + // Check if password is the same as the username. + if (password !== '' && password.toLowerCase() === username.toLowerCase()) { + msg.push(translate.sameAsUsername); + // Passwords the same as username are always very weak. + strength = 5; + } + + // Based on the strength, work out what text should be shown by the + // password strength meter. + if (strength < 60) { + indicatorText = translate.weak; + indicatorClass = 'is-weak'; + } + else if (strength < 70) { + indicatorText = translate.fair; + indicatorClass = 'is-fair'; + } + else if (strength < 80) { + indicatorText = translate.good; + indicatorClass = 'is-good'; + } + else if (strength <= 100) { + indicatorText = translate.strong; + indicatorClass = 'is-strong'; + } + + // Assemble the final message. + msg = translate.hasWeaknesses + '
    • ' + msg.join('
    • ') + '
    '; + + return { + strength: strength, + message: msg, + indicatorText: indicatorText, + indicatorClass: indicatorClass + }; + + }; + +})(jQuery, Drupal, drupalSettings); diff --git a/pool/shard005/JavaScript/0033133_DetailsTableView.js b/pool/shard005/JavaScript/0033133_DetailsTableView.js new file mode 100644 index 0000000000000000000000000000000000000000..949f8bf98365bd9386ae69519fab3d711bdb8e13 --- /dev/null +++ b/pool/shard005/JavaScript/0033133_DetailsTableView.js @@ -0,0 +1,27 @@ +define(['views/result_item/DetailsView', + 'vendor/requirejs/text!templates/result_item/details_table.html'], + function (DetailsView, + detailsTableTemplate) { + var DetailsTableView, templates; + + templates = { + details: _.template(detailsTableTemplate) + }; + + DetailsTableView = DetailsView.extend({ + + render: function () { + this.$el.append( + templates.details( + { summary: this.model.get('summary'), + keywords: this.model.get('keywords'), + updated: this.model.get('updated'), + dataFormats: this.model.get('dataFormats')})); + + return this; + } + + }); + + return DetailsTableView; +}); diff --git a/pool/shard005/JavaScript/0033139_revisions.js b/pool/shard005/JavaScript/0033139_revisions.js new file mode 100644 index 0000000000000000000000000000000000000000..fb8859c49a46eb923925af3f6c196a859ff28583 --- /dev/null +++ b/pool/shard005/JavaScript/0033139_revisions.js @@ -0,0 +1,235 @@ +var m = require('mithril'); +var $ = require('jquery'); +var bootbox = require('bootbox'); // TODO: Why is this required? Is it? See [#OSF-6100] +var $osf = require('js/osfHelpers'); +var waterbutler = require('js/waterbutler'); + +var util = require('./util.js'); +var makeClient = require('js/clipboard'); + +// Helper for filtering +function TRUTHY(item) { + return !!item; //Force cast to a bool +} + + +var model = { + revisions: [], + loaded: m.prop(false), + errorMessage: undefined, + hasUser: false, + hasDate: false, + hasHashes: false, + hasURL: false, + selectedRevision: 0 +}; + + +var FileRevisionsTable = { + controller: function(file, node, enableEditing, canEdit) { + var self = {}; + self.node = node; + self.file = file; + self.canEdit = canEdit; + self.enableEditing = enableEditing; + self.baseUrl = (window.location.href).split('?')[0]; + + model.hasDate = self.file.provider !== 'dataverse'; + + self.reload = function() { + model.loaded(false); + m.redraw(); + $.ajax({ + dataType: 'json', + async: true, + url: self.file.urls.revisions, + beforeSend: $osf.setXHRAuthorization + }).done(function(response) { + m.startComputation(); + var urlParmas = $osf.urlParams(); + model.revisions = response.data.map(function(rev, index) { + rev = FileRevisionsTable.postProcessRevision(self.file, self.node, rev, index); + if (urlParmas[rev.versionIdentifier] === rev.version) { + model.selectedRevision = index; + } + return rev; + }); + model.loaded(true); + // Can only edit the latest version of a file + if (model.selectedRevision === 0) { + self.enableEditing(); + } + model.hasUser = model.revisions[0] && model.revisions[0].extra && model.revisions[0].extra.user; + model.hasHashes = model.revisions && model.revisions[0] && model.revisions[0].extra.hashes; + m.endComputation(); + }).fail(function(response) { + m.startComputation(); + model.loaded(true); + model.errorMessage = response.responseJSON ? + response.responseJSON.message || 'Unable to fetch versions' : + 'Unable to fetch versions'; + m.endComputation(); + + // model.errorMessage(err); + + if (self.file.provider === 'figshare') { + // Hack for Figshare + // only figshare will error on a revisions request + // so dont allow downloads and set a fake current version + $.ajax({ + method: 'GET', + url: self.file.urls.metadata, + beforeSend: $osf.setXHRAuthorization + }).done(function(resp) { + self.canEdit(self.canEdit() && resp.data.extra.canDelete); + m.redraw(); + }).fail(function(xhr) { + self.canEdit(false); + m.redraw(); + }); + } + }); + }; + + + var popOver = function(element, isInit) { + if (!isInit) { + $(element).popover(); + } + }; + + self.getTableHead = function() { + return m('thead', [ + m('tr', [ + m('th', 'Version ID'), + model.hasDate ? m('th', 'Date') : false, + model.hasUser ? m('th', 'User') : false, + m('th[colspan=2]', 'Download'), + model.hasHashes ? m('th', [ + 'MD5 ', m('.fa.fa-question-circle[data-content="MD5 is an algorithm used to verify data integrity."][rel="popover"]' + + '[data-placement="top"][data-trigger="hover"]', {config: popOver}) ]) : false, + model.hasHashes ? m('th', [ + 'SHA2 ', m('.fa.fa-question-circle[data-content="SHA-2 is a cryptographic hash function designed by the NSA used to verify data integrity."][rel="popover"]' + + '[data-placement="top"][data-trigger="hover"]', {config: popOver}) ]) : false, + ].filter(TRUTHY)) + ]); + + }; + + self.makeTableRow = function(revision, index) { + var isSelected = index === model.selectedRevision; + var clipBoard = function(element) { + makeClient(element); + }; + return m('tr' + (isSelected ? '.active' : ''), [ + m('td', isSelected ? revision.displayVersion : + m('a', {href: parseInt(revision.displayVersion) === model.revisions.length ? self.baseUrl : revision.osfViewUrl}, revision.displayVersion) + ), + model.hasDate ? m('td', revision.displayDate) : false, + model.hasUser ? + m('td', revision.extra.user.url ? + m('a', {href: revision.extra.user.url}, revision.extra.user.name) : + revision.extra.user.name + ) : false, + m('td', revision.extra.downloads > -1 ? m('.badge', revision.extra.downloads) : ''), + m('td', + m('a.btn.btn-primary.btn-sm.file-download', { + href: revision.osfDownloadUrl, + onclick: function() { + window.location = revision.waterbutlerDownloadUrl; + return false; + } + }, m('i.fa.fa-download')) + ), + model.hasHashes ? m('td', + m('div.input-group[style="width: 180px"]', + [ + m('span.input-group-btn', m('button.btn.btn-default.btn-sm[type="button"][data-clipboard-text="'+revision.extra.hashes.md5 + '"]', {config: clipBoard}, m('.fa.fa-copy'))), + m('input[value="'+revision.extra.hashes.md5+'"][type="text"][readonly="readonly"][style="float:left; height: 30px;"]') + ] + )) : false, + model.hasHashes ? m('td', + m('div.input-group[style="width: 180px"]', + [ + m('span.input-group-btn', m('button.btn.btn-default.btn-sm[type="button"][data-clipboard-text="'+revision.extra.hashes.sha256 + '"]',{config: clipBoard}, m('.fa.fa-copy'))), + m('input[value="'+revision.extra.hashes.sha256+'"][type="text"][readonly="readonly"][style="float:left; height: 30px;"]') + ] + )) : false + ].filter(TRUTHY)); + }; + + if (!model.loaded()) { + self.reload(); + } + $(document).on('fileviewpage:reload', self.reload); + return self; + }, + view: function(ctrl) { + return m('#revisionsPanel.panel.panel-default', [ + m('.panel-heading.clearfix', m('h3.panel-title', 'Revisions')), + m('.panel-body', {style:{'padding-right': '0','padding-left':'0', 'padding-bottom' : '0', + 'overflow': 'auto'}}, (function() { + if (!model.loaded()) { + return util.Spinner; + } + if (model.errorMessage) { + return m('.alert.alert-warning', {style:{margin: '10px'}}, model.errorMessage); + } + return m('table.table.table-responsive', {style:{marginBottom: '0'}}, [ + ctrl.getTableHead(), + m('tbody', model.revisions.map(ctrl.makeTableRow)) + ]); + })()) + ]); + }, + postProcessRevision: function(file, node, revision, index) { + var options = {}; + var urlParams = $osf.urlParams(); + + if (urlParams.branch !== undefined) { + options.branch = urlParams.branch; + } + options[revision.versionIdentifier] = revision.version; + + revision.date = new $osf.FormattableDate(revision.modified); + revision.displayDate = revision.date.local !== 'Invalid date' ? + revision.date.local : + revision.date; + + switch (file.provider) { + // Note: Google Drive version identifiers often begin with the same sequence + case 'googledrive': + revision.displayVersion = revision.version.substring(revision.version.length - 8); + break; + // Note: Dataverse internal version names are ugly; Substitute our own + case 'dataverse': + var displayMap = { + 'latest': 'Draft', + 'latest-published': 'Published' + }; + + revision.displayVersion = revision.version in displayMap ? + displayMap[revision.version] : revision.version.substring(0, 8); + break; + default: + revision.displayVersion = revision.version.substring(0, 8); + } + + if (file.provider === 'osfstorage' && file.name && index !== 0) { + var parts = file.name.split('.'); + if (parts.length === 1) { + options.displayName = parts[0] + '-' + revision.modified; + } else { + options.displayName = parts.slice(0, parts.length - 1).join('') + '-' + revision.modified + '.' + parts[parts.length - 1]; + } + } + + revision.osfViewUrl = '?' + $.param(options); + revision.osfDownloadUrl = '?' + $.param($.extend({action: 'download'}, options)); + revision.waterbutlerDownloadUrl = waterbutler.buildDownloadUrl(file.path, file.provider, node.id, options); + + return revision; + } +}; + +module.exports = FileRevisionsTable; diff --git a/pool/shard005/JavaScript/0033140_TerrainData.js b/pool/shard005/JavaScript/0033140_TerrainData.js new file mode 100644 index 0000000000000000000000000000000000000000..570418275b0b84450e323f06e90bbf1b820533eb --- /dev/null +++ b/pool/shard005/JavaScript/0033140_TerrainData.js @@ -0,0 +1,112 @@ +import DeveloperError from "./DeveloperError.js"; + +/** + * Terrain data for a single tile. This type describes an + * interface and is not intended to be instantiated directly. + * + * @alias TerrainData + * @constructor + * + * @see HeightmapTerrainData + * @see QuantizedMeshTerrainData + * @see GoogleEarthEnterpriseTerrainData + */ +function TerrainData() { + DeveloperError.throwInstantiationError(); +} + +Object.defineProperties(TerrainData.prototype, { + /** + * An array of credits for this tile. + * @memberof TerrainData.prototype + * @type {Credit[]} + */ + credits: { + get: DeveloperError.throwInstantiationError, + }, + /** + * The water mask included in this terrain data, if any. A water mask is a rectangular + * Uint8Array or image where a value of 255 indicates water and a value of 0 indicates land. + * Values in between 0 and 255 are allowed as well to smoothly blend between land and water. + * @memberof TerrainData.prototype + * @type {Uint8Array|Image|Canvas} + */ + waterMask: { + get: DeveloperError.throwInstantiationError, + }, +}); + +/** + * Computes the terrain height at a specified longitude and latitude. + * @function + * + * @param {Rectangle} rectangle The rectangle covered by this terrain data. + * @param {Number} longitude The longitude in radians. + * @param {Number} latitude The latitude in radians. + * @returns {Number} The terrain height at the specified position. If the position + * is outside the rectangle, this method will extrapolate the height, which is likely to be wildly + * incorrect for positions far outside the rectangle. + */ +TerrainData.prototype.interpolateHeight = + DeveloperError.throwInstantiationError; + +/** + * Determines if a given child tile is available, based on the + * {@link TerrainData#childTileMask}. The given child tile coordinates are assumed + * to be one of the four children of this tile. If non-child tile coordinates are + * given, the availability of the southeast child tile is returned. + * @function + * + * @param {Number} thisX The tile X coordinate of this (the parent) tile. + * @param {Number} thisY The tile Y coordinate of this (the parent) tile. + * @param {Number} childX The tile X coordinate of the child tile to check for availability. + * @param {Number} childY The tile Y coordinate of the child tile to check for availability. + * @returns {Boolean} True if the child tile is available; otherwise, false. + */ +TerrainData.prototype.isChildAvailable = DeveloperError.throwInstantiationError; + +/** + * Creates a {@link TerrainMesh} from this terrain data. + * @function + * + * @private + * + * @param {TilingScheme} tilingScheme The tiling scheme to which this tile belongs. + * @param {Number} x The X coordinate of the tile for which to create the terrain data. + * @param {Number} y The Y coordinate of the tile for which to create the terrain data. + * @param {Number} level The level of the tile for which to create the terrain data. + * @returns {Promise.|undefined} A promise for the terrain mesh, or undefined if too many + * asynchronous mesh creations are already in progress and the operation should + * be retried later. + */ +TerrainData.prototype.createMesh = DeveloperError.throwInstantiationError; + +/** + * Upsamples this terrain data for use by a descendant tile. + * @function + * + * @param {TilingScheme} tilingScheme The tiling scheme of this terrain data. + * @param {Number} thisX The X coordinate of this tile in the tiling scheme. + * @param {Number} thisY The Y coordinate of this tile in the tiling scheme. + * @param {Number} thisLevel The level of this tile in the tiling scheme. + * @param {Number} descendantX The X coordinate within the tiling scheme of the descendant tile for which we are upsampling. + * @param {Number} descendantY The Y coordinate within the tiling scheme of the descendant tile for which we are upsampling. + * @param {Number} descendantLevel The level within the tiling scheme of the descendant tile for which we are upsampling. + * @returns {Promise.|undefined} A promise for upsampled terrain data for the descendant tile, + * or undefined if too many asynchronous upsample operations are in progress and the request has been + * deferred. + */ +TerrainData.prototype.upsample = DeveloperError.throwInstantiationError; + +/** + * Gets a value indicating whether or not this terrain data was created by upsampling lower resolution + * terrain data. If this value is false, the data was obtained from some other source, such + * as by downloading it from a remote server. This method should return true for instances + * returned from a call to {@link TerrainData#upsample}. + * @function + * + * @returns {Boolean} True if this instance was created by upsampling; otherwise, false. + */ +TerrainData.prototype.wasCreatedByUpsampling = + DeveloperError.throwInstantiationError; +export default TerrainData; diff --git a/pool/shard005/JavaScript/0033144_flattenColorPalette.js b/pool/shard005/JavaScript/0033144_flattenColorPalette.js new file mode 100644 index 0000000000000000000000000000000000000000..644ee3fe34a89e75e5a2f6d52ada44e52773af1e --- /dev/null +++ b/pool/shard005/JavaScript/0033144_flattenColorPalette.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +const flattenColorPalette = colors => Object.assign({}, ...Object.entries(colors).flatMap(([color, values]) => typeof values == 'object' ? Object.entries(flattenColorPalette(values)).map(([number, hex]) => ({ + [color + (number === 'DEFAULT' ? '' : `-${number}`)]: hex +})) : [{ + [`${color}`]: values +}])); + +var _default = flattenColorPalette; +exports.default = _default; \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033145_server.js b/pool/shard005/JavaScript/0033145_server.js new file mode 100644 index 0000000000000000000000000000000000000000..f70de468d14b6544b394e75cdaa4ad796c543db7 --- /dev/null +++ b/pool/shard005/JavaScript/0033145_server.js @@ -0,0 +1,159 @@ +#!/bin/env node +// OpenShift sample Node application +var express = require('express'); +var fs = require('fs'); + +/** + * Define the sample application. + */ +var SampleApp = function() { + + // Scope. + var self = this; + + + /* ================================================================ */ + /* Helper functions. */ + /* ================================================================ */ + + /** + * Set up server IP address and port # using env variables/defaults. + */ + self.setupVariables = function() { + // Set the environment variables we need. + self.ipaddress = process.env.OPENSHIFT_NODEJS_IP; + self.port = process.env.OPENSHIFT_NODEJS_PORT || 8080; + + if (typeof self.ipaddress === "undefined") { + // Log errors on OpenShift but continue w/ 127.0.0.1 - this + // allows us to run/test the app locally. + console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1'); + self.ipaddress = "127.0.0.1"; + }; + }; + + + /** + * Populate the cache. + */ + self.populateCache = function() { + if (typeof self.zcache === "undefined") { + self.zcache = { 'index.html': '' }; + } + + // Local cache for static content. + self.zcache['index.html'] = fs.readFileSync('./index.html'); + }; + + + /** + * Retrieve entry (content) from cache. + * @param {string} key Key identifying content to retrieve from cache. + */ + self.cache_get = function(key) { return self.zcache[key]; }; + + + /** + * terminator === the termination handler + * Terminate server on receipt of the specified signal. + * @param {string} sig Signal to terminate on. + */ + self.terminator = function(sig){ + if (typeof sig === "string") { + console.log('%s: Received %s - terminating sample app ...', + Date(Date.now()), sig); + process.exit(1); + } + console.log('%s: Node server stopped.', Date(Date.now()) ); + }; + + + /** + * Setup termination handlers (for exit and a list of signals). + */ + self.setupTerminationHandlers = function(){ + // Process on exit and signals. + process.on('exit', function() { self.terminator(); }); + + // Removed 'SIGPIPE' from the list - bugz 852598. + ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', + 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM' + ].forEach(function(element, index, array) { + process.on(element, function() { self.terminator(element); }); + }); + }; + + + /* ================================================================ */ + /* App server functions (main app logic here). */ + /* ================================================================ */ + + /** + * Create the routing table entries + handlers for the application. + */ + self.createRoutes = function() { + self.routes = { }; + + self.routes['/asciimo'] = function(req, res) { + var link = "http://i.imgur.com/kmbjB.png"; + res.send(""); + }; + + self.routes['/'] = function(req, res) { + res.setHeader('Content-Type', 'text/html'); + res.send(self.cache_get('index.html') ); + }; + }; + + + /** + * Initialize the server (express) and create the routes and register + * the handlers. + */ + self.initializeServer = function() { + self.createRoutes(); + self.app = express.createServer(); + self.app.use(express.static('public')); + + // Add handlers for the app (from the routes). + for (var r in self.routes) { + self.app.get(r, self.routes[r]); + } + }; + + + /** + * Initializes the sample application. + */ + self.initialize = function() { + self.setupVariables(); + self.populateCache(); + self.setupTerminationHandlers(); + + // Create the express server and routes. + self.initializeServer(); + }; + + + /** + * Start the server (starts up the sample application). + */ + self.start = function() { + // Start the app on the specific interface (and port). + self.app.listen(self.port, self.ipaddress, function() { + console.log('%s: Node server started on %s:%d ...', + Date(Date.now() ), self.ipaddress, self.port); + }); + }; + +}; /* Sample Application. */ + + + +/** + * main(): Main code. + */ +var zapp = new SampleApp(); +zapp.initialize(); +zapp.start(); + diff --git a/pool/shard005/JavaScript/0033147_orwdxvb3-swpanel-spec.js b/pool/shard005/JavaScript/0033147_orwdxvb3-swpanel-spec.js new file mode 100644 index 0000000000000000000000000000000000000000..4c58f6a5a72d3a70e6e4bbb5c9bc6811acfec934 --- /dev/null +++ b/pool/shard005/JavaScript/0033147_orwdxvb3-swpanel-spec.js @@ -0,0 +1,25 @@ +'use strict'; + +const rpcEmulatorModel = require('../orwdxvb3-swpanel').rpcEmulatorModel; +const unitTestUtils = require('./unitTestUtils'); + +describe('ORWDXVB3 SWPANEL asynchronous specs', () => { + let rpc; + let context; + + beforeAll(() => { + const res = unitTestUtils.beforeAllScript(rpcEmulatorModel); + context = res.context; + rpc = res; + }); + + it('Expect res to be defined and number', (done) => { + rpc.run([], context, (err, res) => { + if (err) return unitTestUtils.handleError(err, done); + expect(res).toBeDefined(); + expect(res).toEqual(jasmine.any(Number)); + expect(res === 0 || res === 1).toEqual(true); + done(); + }); + }); +}); diff --git a/pool/shard005/JavaScript/0033148_index.js b/pool/shard005/JavaScript/0033148_index.js new file mode 100644 index 0000000000000000000000000000000000000000..4ecccec1fb851c2d9c16b6ba9c2fbcbcd6611de3 --- /dev/null +++ b/pool/shard005/JavaScript/0033148_index.js @@ -0,0 +1,87 @@ +var util = require("util"); +var path = require("path"); +var Q = require("q"); +var _ = require("lodash"); +var exec = require('child_process').exec; + +var fs = require('graceful-fs'); +var parse = require("../../parse"); +var BaseGenerator = require("../page"); +var stringUtils = require("../../utils/string"); + +var Generator = function() { + BaseGenerator.apply(this, arguments); +}; +util.inherits(Generator, BaseGenerator); + +Generator.prototype.finish = function() { + var that = this; + + return BaseGenerator.prototype.finish.apply(this) + .then(function() { + var d = Q.defer(); + var format = that.options.extension || path.extname(that.options.output).replace("\.", "") || "pdf"; + + if (!that.options.cover && fs.existsSync(path.join(that.options.output, "cover.jpg"))) { + that.options.cover = path.join(that.options.output, "cover.jpg"); + } + + var _options = { + "--cover": that.options.cover, + "--title": that.options.title, + "--comments": that.options.description, + "--isbn": that.options.isbn, + "--authors": that.options.author, + "--publisher": "GitBook", + "--chapter": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter ')]", + "--chapter-mark": "pagebreak", + "--page-breaks-before": "/", + "--level1-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-1 ')]", + "--level2-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-2 ')]", + "--level3-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-3 ')]", + "--no-chapters-in-toc": true, + "--max-levels": "1", + "--breadth-first": true + }; + + if (format == "pdf") { + var pdfOptions = that.options.pdf; + + _.extend(_options, { + "--margin-left": String(pdfOptions.margin.left), + "--margin-right": String(pdfOptions.margin.right), + "--margin-top": String(pdfOptions.margin.top), + "--margin-bottom": String(pdfOptions.margin.bottom), + "--pdf-default-font-size": String(pdfOptions.fontSize), + "--pdf-mono-font-size": String(pdfOptions.fontSize), + "--paper-size": String(pdfOptions.paperSize), + "--pdf-page-numbers": Boolean(pdfOptions.pageNumbers), + "--pdf-header-template": String(pdfOptions.headerTemplate), + "--pdf-footer-template": String(pdfOptions.footerTemplate) + }); + } + + var command = [ + "ebook-convert", + path.join(that.options.output, "SUMMARY.html"), + path.join(that.options.output, "index."+format), + stringUtils.optionsToShellArgs(_options) + ].join(" "); + + exec(command, function (error, stdout, stderr) { + if (error) { + if (error.code == 127) { + error.message = "Need to install ebook-convert from Calibre"; + } else { + error.message = error.message + " "+stdout; + } + return d.reject(error); + } + d.resolve(); + }); + + return d.promise; + }); +}; + +module.exports = Generator; diff --git a/pool/shard005/JavaScript/0033152_ref-view.js b/pool/shard005/JavaScript/0033152_ref-view.js new file mode 100644 index 0000000000000000000000000000000000000000..e946abf47796798fbb3061877d8437cacea5b22a --- /dev/null +++ b/pool/shard005/JavaScript/0033152_ref-view.js @@ -0,0 +1,105 @@ +'use babel' + +const SelectList = require('atom-select-list') + +export default class RefView { + constructor(provider) { + this.provider = provider + + this.resultTemplate = atom.config.get("autocomplete-bibtex.resultTemplate") + atom.config.observe("autocomplete-bibtex.resultTemplate", resultTemplate => { + this.resultTemplate = resultTemplate + }) + } + + async show() { + let references = await this.provider.references + references = [].concat.apply([], references) + + let selectListView = new SelectList({ + items: references, + maxResults: 10, + elementForItem: item => { + if (item) { + if (!item.title) item.title = '--' + if (!item.author) item.author = '--' + + let typeClass = "icon-mortar-board" + if (item.type === 'article' || item.journal) { + typeClass = "icon-file-text" + } else if (item.type === 'book' || item.booktitle) { + typeClass = "icon-repo" + } + let el = document.createElement('li') + el.innerHTML = `
    +
    + +
    +
    +
    +
    ${item.prettyAuthors}
    +
    [${item.id}]
    +
    +
    + ${item.title} +
    +
    +
    ` + return el + } + return document.createElement('li') + }, + filterKeyForItem: item => { + // const filterKeys = ['title', 'author', 'journal', 'year'] + // let filterKey = '' + // for (let key of filterKeys) { + // if (item[key]) { + // filterKey = filterKey + ' ' + item[key] + // } + // } + return item.fuzzyLabel + }, + didConfirmSelection: item => { + this.hide() + + // insert ref at cursor + const editor = atom.workspace.getActiveTextEditor() + const citekey = this.resultTemplate.replace('[key]', item.id) + editor.insertText(citekey) + }, + didCancelSelection: () => { + if (this.panel.isVisible()) { + this.panel.hide() + } + this.hide() + } + }) // end of select list + + if (!this.panel) { + this.panel = atom.workspace.addModalPanel({item: selectListView}) + } + + selectListView.element.classList.add('autocomplete-bibtex') + + selectListView.reset() + this.previouslyFocusedElement = document.activeElement + this.panel.show() + selectListView.focus() + } + + toggle() { + if (this.panel && this.panel.isVisible()) { + this.hide() + return Promise.resolve() + } + return this.show() + } + + hide() { + this.panel.hide() + if (this.previouslyFocusedElement) { + this.previouslyFocusedElement.focus() + this.previouslyFocusedElement = null + } + } +} diff --git a/pool/shard005/JavaScript/0033155_home.js b/pool/shard005/JavaScript/0033155_home.js new file mode 100644 index 0000000000000000000000000000000000000000..dfa46fe15d618bdde4595fe974210db801ec509a --- /dev/null +++ b/pool/shard005/JavaScript/0033155_home.js @@ -0,0 +1,211 @@ +import regexp from 'utils/regexp' +import fetch from 'isomorphic-fetch' +// import jsonp from 'fetch-jsonp' + +// ------------------------------------ +// Constants +// ------------------------------------ +export const SUCCESS_HOME_SLIDER = 'SUCCESS_HOME_SLIDER'; +export const SUCCESS_PRODUCT_CATS = 'SUCCESS_PRODUCT_CATS'; +export const SUCCESS_PRODUCT_HOTS = 'SUCCESS_PRODUCT_HOTS'; +export const SUCCESS_PRODUCT_NEW = 'SUCCESS_PRODUCT_NEW'; +export const SUCCESS_ARTICLE_HOT = 'SUCCESS_ARTICLE_HOT'; + +export const SUCCESS_PRODUCT_BY_CATES = 'SUCCESS_PRODUCT_BY_CATES'; + +// ------------------------------------ +// States +// ------------------------------------ +const state = { + slider: [], // 首页幻灯片信息 + cates: [], // 商品分类 + productsByCates: { + cate110: [], + cate109: [], + cate120: [], + },// 分类商品 + hotProducts: [], // 热门商品 + newProducts: [], // 新到尖货 + hotArticles: [] // 热门文章 +} + +// ------------------------------------ +// Getters +// ------------------------------------ +export const getters = { + homeSlider: state => state.slider, + cates: state => state.cates, + productsByCates: state => state.productsByCates, + hotProducts: state => state.hotProducts, + newProducts: state => state.newProducts, + hotArticles: state => state.hotArticles +} + +// ------------------------------------ +// Action Handlers +// ------------------------------------ +export const actions = { + + //获取所有商品分类 + async getProductCates ({ commit }) { + const res = await fetch(`http://ransj.com/topic/subcates?category=108`, { + method: "GET", + mode: 'cors', + credentials: 'include', // ['cors', include', 'same-origin'] + headers: { + 'Accept': 'application/json', + 'x-requested-with': 'XMLHttpRequest', + 'Content-Type': 'application/json' + } + }) + const json = await res.json(); + if(json && json.data && json.errno == 0) { + commit(SUCCESS_PRODUCT_CATS, json) + return json + } + }, + + + //获取首页Slider + async getHomeSliders ({ commit }, data) { + const res = await fetch(`http://ransj.com/cart/addcart`, { + method: "POST", + mode: 'cors', + credentials: 'include', // ['cors', include', 'same-origin'] + headers: { + 'Accept': 'application/json', + 'x-requested-with': 'XMLHttpRequest', + 'Content-Type': 'application/json' + }, + body: JSON.stringify(data) + }) + const json = await res.json(); + // console.log(json); + if(json && json.data) { + commit(SUCCESS_HOME_SLIDER, json) + } + }, + + //获取热门文章 + async getHotArticles ({ commit }, data) { + const res = await fetch(`http://ransj.com/topic/list?category=1-1`, { + method: "POST", + mode: 'cors', + credentials: 'include', // ['cors', include', 'same-origin'] + headers: { + 'Accept': 'application/json', + 'x-requested-with': 'XMLHttpRequest', + 'Content-Type': 'application/json' + }, + body: JSON.stringify(data) + }) + const json = await res.json(); + // console.log(json); + if(json && json.data) { + commit(SUCCESS_ARTICLE_HOT, json) + } + }, + + //获取热门商品 + async getHotProducts ({ commit }, data) { + const res = await fetch(`http://ransj.com/topic/list?category=108-1`, { + method: "POST", + mode: 'cors', + credentials: 'include', // ['cors', include', 'same-origin'] + headers: { + 'Accept': 'application/json', + 'x-requested-with': 'XMLHttpRequest', + 'Content-Type': 'application/json' + }, + body: JSON.stringify(data) + }) + const json = await res.json(); + // console.log(json); + if(json && json.data) { + commit(SUCCESS_PRODUCT_HOTS, json) + } + }, + + + //获取分类商品 + async getProductsByCate ({ commit }, cate) { + const res = await fetch(`http://ransj.com/topic/list?category=${cate}-1`, { + method: "POST", + mode: 'cors', + credentials: 'include', // ['cors', include', 'same-origin'] + headers: { + 'Accept': 'application/json', + 'x-requested-with': 'XMLHttpRequest', + 'Content-Type': 'application/json' + }, + body: '' + }) + const json = await res.json(); + // console.log(json); + if(json && json.data) { + commit(SUCCESS_PRODUCT_BY_CATES, {cate: cate, data: json.data}) + } + }, + + + //获取最新商品 + async getNewProducts ({ commit }, data) { + const res = await fetch(`http://ransj.com/cart/addcart`, { + method: "POST", + mode: 'cors', + credentials: 'include', // ['cors', include', 'same-origin'] + headers: { + 'Accept': 'application/json', + 'x-requested-with': 'XMLHttpRequest', + 'Content-Type': 'application/json' + }, + body: JSON.stringify(data) + }) + const json = await res.json(); + // console.log(json); + if(json && json.data) { + commit(SUCCESS_PRODUCT_NEW, json) + } + }, + + + +} + +// ------------------------------------ +// Mutations +// ------------------------------------ +export const mutations = { + [SUCCESS_HOME_SLIDER] (state, data){ + state.slider = data; + }, + + [SUCCESS_PRODUCT_CATS] (state, data){ + state.cates = data; + }, + + [SUCCESS_PRODUCT_HOTS] (state, data){ + state.hotProducts = data; + }, + + [SUCCESS_PRODUCT_NEW] (state, data){ + state.newProducts = data; + }, + + [SUCCESS_ARTICLE_HOT] (state, data){ + state.hotArticles = data; + }, + + + [SUCCESS_PRODUCT_BY_CATES] (state, payload) { + // console.log(payload.cate, payload.data) + state.productsByCates['cate'+ payload.cate] = payload.data; + }, +} + +export default { + state, + getters, + actions, + mutations +} \ No newline at end of file diff --git a/pool/shard005/JavaScript/0033156_ListItem.js b/pool/shard005/JavaScript/0033156_ListItem.js new file mode 100644 index 0000000000000000000000000000000000000000..d9105d78c2dfadabc37bea8fe341a4730195f28d --- /dev/null +++ b/pool/shard005/JavaScript/0033156_ListItem.js @@ -0,0 +1,53 @@ +import styles from './ListItem.scss'; +import fa from 'font-awesome/css/font-awesome.css'; + +import React, { PropTypes } from 'react'; +import Button from '../Button'; +import { ItemTypes } from './Constants'; +import cx from 'classnames'; + +const style = { + +}; + +const Types = { + LIST_ITEM: 'list_item' +}; + +class ListItem extends React.Component { + constructor (props) { + super(props); + } + + handleRemove() { + this.props.onClickRemove(this.props.id); + } + + render() { + const { value, canRemove } = this.props; + + return ( +
  • + {value} + {this.props.children} + {canRemove ?
  • + ); + } +}; + +ListItem.propTypes = { + value: PropTypes.string, + canRemove: PropTypes.bool, + id: PropTypes.number, + onClickRemove: PropTypes.func +}; + +ListItem.defaultProps = { + value: '', + canRemove: false, + id: null, + onClickRemove: function () {} +}; + +export default ListItem; diff --git a/pool/shard005/JavaScript/0033157_posts.js b/pool/shard005/JavaScript/0033157_posts.js new file mode 100644 index 0000000000000000000000000000000000000000..7de116772681e828adf3b692ecddc429d3d657ef --- /dev/null +++ b/pool/shard005/JavaScript/0033157_posts.js @@ -0,0 +1,167 @@ + +'use strict'; + +var async = require('async'), + winston = require('winston'), + + posts = require('../posts'), + topics = require('../topics'), + user = require('../user'), + helpers = require('./helpers'), + groups = require('../groups'), + categories = require('../categories'), + plugins = require('../plugins'); + +module.exports = function(privileges) { + + privileges.posts = {}; + + privileges.posts.get = function(pids, uid, callback) { + if (!Array.isArray(pids) || !pids.length) { + return callback(null, []); + } + async.parallel({ + manage: function(next) { + helpers.hasEnoughReputationFor(['privileges:manage_content', 'privileges:manage_topic'], uid, next); + }, + isAdministrator: function(next) { + user.isAdministrator(uid, next); + }, + }, function(err, userResults) { + if(err) { + return callback(err); + } + + var userPriv = userResults.isAdministrator || userResults.manage; + + async.parallel({ + isOwner: function(next) { + posts.isOwner(pids, uid, next); + }, + isModerator: function(next) { + posts.isModerator(pids, uid, next); + } + }, function(err, postResults) { + if (err) { + return callback(err); + } + + var privileges = []; + + for (var i=0; i { + function normalizeCodeLocInfo(str) { + return str && str.replace(/\(at .+?:\d+\)/g, '(at **)'); + } + + var React; + var ReactDOM; + var ReactDOMFeatureFlags; + var ReactTestUtils; + + beforeEach(() => { + React = require('React'); + ReactDOM = require('ReactDOM'); + ReactDOMFeatureFlags = require('ReactDOMFeatureFlags'); + ReactTestUtils = require('ReactTestUtils'); + }); + + it('should flatten children to a string', () => { + var stub = ; + stub = ReactTestUtils.renderIntoDocument(stub); + var node = ReactDOM.findDOMNode(stub); + + expect(node.innerHTML).toBe('1 foo'); + }); + + it('should ignore and warn invalid children types', () => { + spyOn(console, 'error'); + var el =