text
stringlengths 2
6.14k
|
|---|
/*
* Copyright (C) 2021 Inera AB (http://www.inera.se)
*
* This file is part of sklintyg (https://github.com/sklintyg).
*
* sklintyg 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.
*
* sklintyg 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 <http://www.gnu.org/licenses/>.
*/
angular.module('StatisticsApp').directive('dataerrorview', function() {
'use strict';
return {
restrict: 'A',
transclude: true,
replace: true,
scope: {
errorPageUrl: '=',
showError: '='
},
templateUrl: '/components/directives/dataerrorview/dataerrorview.html'
};
});
|
Famono.scope('famous/surfaces/Gruntfile', ["load-grunt-tasks","time-grunt"], function(require, define) {
define(function() {
/*global module:false*/
/*Generated initially from grunt-init, heavily inspired by yo webapp*/
module.exports = function(grunt) {
'use strict';
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Project configuration.
grunt.initConfig({
eslint: {
options: {
config: '.eslintrc'
},
target: ['*.js']
},
jscs: {
src: ['*.js'],
options: {
config: '.jscsrc'
}
}
});
grunt.registerTask('test', [
'jscs',
'eslint'
]);
grunt.registerTask('default', [
'test'
]);
};
});
});
|
import getURL from '../utils/getURL.js'
import getUserInfo from './getUserInfo.js'
import people from './people.js'
/**
@name $SP().getManager
@function
@category people
@description Return the manager for the provided user, as a People string
@param {String} [username] With or without the domain, and you can also use an email address, and if you leave it empty it's the current user by default
@param {Object} [setup] Options (see below)
@param {String} [setup.url='current website'] The website url
@return {Function} resolve(manager), reject(error)
@example
$SP().getManager("john_doe",{url:"http://my.si.te/subdir/"})
.then(function(manager) {
console.log(manager); // 42;#Smith,, Jane,#i:0#.w|domain\Jane_Smith,#Jane_Smith@Domain.com,#Jane_Smith@Domain.com,#Smith,, Jane
manager = $SP().getPeopleLookup(manager);
console.log(manager.name); // "Smith, Jane"
})
.catch(function(err) {
console.log("Err => ",err)
});
*/
export default async function getManager(username, setup) {
try {
if (arguments.length===1 && typeof username === "object") { setup=username; username="" }
// default values
username = (username || "");
setup = setup || {};
if (!setup.url) {
setup.url = await getURL.call(this);
}
let pres = await people.call(this, username, setup);
let managerUserName = pres.Manager;
if (!managerUserName.startsWith('i:0')) managerUserName = "i:0#.w|" + managerUserName;
let res = await getUserInfo.call(this, managerUserName, setup);
// "42;#Doe,, John,#i:0#.w|domain\John_Doe,#John_Doe@Domain.com,#John_Doe@Domain.com,#Doe,, John
let displayName = res.Name.replace(/,/,",,");
return Promise.resolve(res.ID+";#"+displayName+",#"+managerUserName+",#"+res.Email+",#"+res.Email+",#"+displayName);
} catch(err) {
return Promise.reject(err);
}
}
|
/**
* Copyright (C) 2005-2015 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @module aikauTesting/mockservices/ListMockService
* @extends module:alfresco/core/Core
* @author Dave Draper
* @author Martin Doyle
*/
define([
"alfresco/core/Core",
"alfresco/core/CoreXhr",
"dojo/_base/array",
"dojo/_base/declare",
"dojo/_base/lang",
"dojo/io-query",
"service/constants/Default"
],
function(AlfCore, CoreXhr, array, declare, lang, ioQuery, AlfConstants) {
return declare([AlfCore, CoreXhr], {
/**
* Constructor
*
* @instance
*/
constructor: function alfresco_testing_mockservices_ListMockService__constructor() {
this.alfSubscribe("ALF_RETRIEVE_DOCUMENTS_REQUEST", lang.hitch(this, this.onRetrieveDocumentsRequest));
},
/**
* Handle document retrieval requests
*
* @instance
*/
onRetrieveDocumentsRequest: function alfresco_testing_mockservices_ListMockService__onRetrieveDocumentsRequest(payload) {
// Setup the request parameters object
var filterKeys = (payload.dataFilters && Object.keys(payload.dataFilters)) || [],
filters = filterKeys.map(function(filterKey) {
var filter = payload.dataFilters[filterKey];
return filter.name + "|" + filter.value;
}).join(),
pageNum = payload.page || 1,
pageSize = payload.pageSize || 0,
startIndex = (pageNum - 1) * pageSize;
// Setup request params
var requestParams = {};
if (startIndex) {
requestParams.startIndex = startIndex;
}
if (pageSize) {
requestParams.pageSize = pageSize;
}
if (filters) {
requestParams.filters = filters;
}
// Make an XHR
var serviceUrl = AlfConstants.URL_SERVICECONTEXT + "mockdata/list";
if (Object.keys(requestParams).length) {
serviceUrl += "?" + ioQuery.objectToQuery(requestParams);
}
this.serviceXhr({
alfTopic: payload.alfResponseTopic,
url: serviceUrl,
method: "GET",
callbackScope: this
});
}
});
});
|
var cats;
(function (cats) {
'use strict';
var initModule = function () {
};
var getCat = function () {
return "tabby";
};
cats.model = {
initModule: initModule,
getCat: getCat
};
})(cats || (cats = {}));
|
(function($, window, document, undefined) {
'use strict';
var gridContainer = $('#grid-container'),
filtersContainer = $('#filters-container'),
wrap, filtersCallback;
/*********************************
init cubeportfolio
*********************************/
gridContainer.cubeportfolio({
layoutMode: 'grid',
rewindNav: true,
scrollByPage: false,
defaultFilter: '*',
animationType: 'slideLeft',
gapHorizontal: 0,
gapVertical: 0,
gridAdjustment: 'responsive',
mediaQueries: [{
width: 800,
cols: 2
}, {
width: 500,
cols: 2
}, {
width: 320,
cols: 1
}],
caption: 'zoom',
displayType: 'lazyLoading',
displayTypeSpeed: 100
});
/*********************************
add listener for filters
*********************************/
if (filtersContainer.hasClass('cbp-l-filters-dropdown')) {
wrap = filtersContainer.find('.cbp-l-filters-dropdownWrap');
wrap.on({
'http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/mouseover.cbp': function() {
wrap.addClass('cbp-l-filters-dropdownWrap-open');
},
'http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/mouseleave.cbp': function() {
wrap.removeClass('cbp-l-filters-dropdownWrap-open');
}
});
filtersCallback = function(me) {
wrap.find('.cbp-filter-item').removeClass('cbp-filter-item-active');
wrap.find('.cbp-l-filters-dropdownHeader').text(me.text());
me.addClass('cbp-filter-item-active');
wrap.trigger('http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/mouseleave.cbp');
};
} else {
filtersCallback = function(me) {
me.addClass('cbp-filter-item-active').siblings().removeClass('cbp-filter-item-active');
};
}
filtersContainer.on('http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/click.cbp', '.cbp-filter-item', function() {
var me = $(this);
if (me.hasClass('cbp-filter-item-active')) {
return;
}
// get cubeportfolio data and check if is still animating (reposition) the items.
if (!$.data(gridContainer[0], 'cubeportfolio').isAnimating) {
filtersCallback.call(null, me);
}
// filter the items
gridContainer.cubeportfolio('filter', me.data('filter'), function() {});
});
/*********************************
activate counter for filters
*********************************/
gridContainer.cubeportfolio('showCounter', filtersContainer.find('.cbp-filter-item'), function() {
// read from url and change filter active
var match = /#cbpf=(.*?)([#|?&]|$)/gi.exec(location.href),
item;
if (match !== null) {
item = filtersContainer.find('.cbp-filter-item').filter('[data-filter="' + match[1] + '"]');
if (item.length) {
filtersCallback.call(null, item);
}
}
});
})(jQuery, window, document);
|
// LauncherOSX
//
// Created by Boris Schneiderman.
// Copyright (c) 2012-2013 The Readium Foundation.
//
// The Readium SDK 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 <http://www.gnu.org/licenses/>.
/**
* Top level ReadiumSDK namespace
* @class ReadiumSDK
* @static
*/
ReadiumSDK = {
/**
Current version of the JS SDK
@method version
@static
@return {string} version
*/
version: function() {
return "0.8.0";
},
Models : {
Smil: {}
},
Views : {},
Collections: {},
Routers: {},
Helpers: {}
};
_.extend(ReadiumSDK, Backbone.Events);
|
import {
categorySave,
categorySortSave,
categoryDel,
categoryGetById,
categoryGetList
} from '../platformApi';
const categoryModule = {
namespaced: true,
state: {
loading: false,
},
mutations: {
setLoading(state, val) {
state.loading = val;
},
},
actions: {
async getList(ctx, params) {
ctx.commit("setLoading", true);
let nParams = Object.assign({}, params);
let result = await categoryGetList(nParams);
ctx.commit("setLoading", false);
return result;
},
async save(ctx, params) {
ctx.commit("setLoading", true);
let result = await categorySave(params);
ctx.commit("setLoading", false);
return result;
},
async sortSave(ctx, params) {
ctx.commit("setLoading", true);
let result = await categorySortSave(params);
ctx.commit("setLoading", false);
return result;
},
async del(ctx, params) {
ctx.commit("setLoading", true);
let result = await categoryDel(params);
ctx.commit("setLoading", false);
return result;
},
async getById(ctx, params) {
ctx.commit("setLoading", true);
let result = await categoryGetById(params);
ctx.commit("setLoading", false);
return result;
},
}
}
export default categoryModule;
|
import { isObject, isFunction, keys } from 'lodash';
// Removes all functions in an object so you can test
// against objects without errors
export const withoutFunctions = (obj) => {
if (!isObject(obj)) {
return obj;
}
let temp = {}
const _keys = keys(obj)
_keys.forEach((k) => {
if (isObject(obj[k])) {
temp[k] = withoutFunctions(obj[k]);
} else if (isFunction(obj[k])) {
temp[k] = null;
} else {
temp[k] = obj[k];
}
});
return temp;
}
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* Load top 5 recommendations */
function loadTopRecommendations() {
// Get category, costRating and crowdRating from user input radio buttons
const chosenCategory = document.querySelector('input[name="recommendation-category"]:checked').value;
const preferredCost = document.querySelector('input[name="price"]:checked').value;
const preferredCrowd = document.querySelector('input[name="crowd"]:checked').value;
const url = "recommender?category=" + chosenCategory +"&cost-rating="
+ preferredCost +"&crowd-rating=" + preferredCrowd;
fetch(url).then(response => response.json()).then((recommendations) => {
displayRecommendation(recommendations);
});
}
/* Update HTML to display recommendation */
function displayRecommendation(recommendations) {
const topRecommendationsList = document.getElementById("top-recommendations-list");
topRecommendationsList.innerHTML = "";
for (var i = 0; i < recommendations.length; i++) {
const recommendationBox = document.createElement("div");
recommendationBox.className = "recommendation-box";
// if highest recommendation, label with 'Most Recommended' in the HTML
if (i == 0) {
recommendationBox.innerHTML = "<p class=\"top-recommendation\">Most Recommended</p>";
}
const recommendation = recommendations[i];
const nameHTML = "<h3><b>#" + (i + 1) + " " + recommendation.name + "</b></h3>";
const locationHTML = "<p>latitiude: " + recommendation.lat + ", longitude: " + recommendation.lng + "</p>";
const ratingHTML = "<p>crowd: " + recommendation.crowdRating + "/5, price: " + recommendation.costRating + "/5</p>";
const descriptionHTML = "<p>" + recommendation.description + "</p>";
recommendationBox.innerHTML += nameHTML + locationHTML + ratingHTML + descriptionHTML;
topRecommendationsList.append(recommendationBox);
}
}
|
var detect = require('rtc-core/detect');
var extend = require('cog/extend');
var test = require('tape');
var expect = require('./helpers/expect-constraints');
var format = require('./helpers/format');
function mozMediaSource(type) {
return {
mozMediaSource: type,
mediaSource: type
};
}
test('share', expect({
audio: false,
video: extend(detect.moz ? mozMediaSource('window') : {}, {
mandatory: detect.moz ? {} : {
chromeMediaSource: 'screen'
},
optional: [
{ maxWidth: 1920 },
{ maxHeight: 1080 }
]
})
}, format.LEGACY));
test('share', expect({
audio: false,
video: extend(detect.moz ? mozMediaSource('window') : {},
detect.moz ? {
width: { max: 1920 },
height: { max: 1080 }
} : {
chromeMediaSource: 'screen',
width: { max: 1920 },
height: { max: 1080 }
}
)
}, format.STANDARD));
test('share:window', expect({
audio: false,
video: extend(detect.moz ? mozMediaSource('window') : {}, {
mandatory: detect.moz ? {} : {
chromeMediaSource: 'screen'
},
optional: [
{ maxWidth: 1920 },
{ maxHeight: 1080 }
]
})
}, format.LEGACY));
test('share:window', expect({
audio: false,
video: extend(detect.moz ? mozMediaSource('window') : {},
detect.moz ? {
width: { max: 1920 },
height: { max: 1080 }
} : {
chromeMediaSource: 'screen',
width: { max: 1920 },
height: { max: 1080 }
}
)
}, format.STANDARD));
|
var dir_4d08ff304006deda5c4a9fa99aae6a31 =
[
[ "java", "dir_8e445b0d87012ac190b46837b3341970.html", "dir_8e445b0d87012ac190b46837b3341970" ]
];
|
import {
PROBES_SCIENCE_QUERY,
PROBES_SCIENCE_SUB,
PROBES_SCIENCE_CONTACT_SUB,
} from "components/views/ProbeScience";
import systems from "../data/systems";
import sensors from "../data/sensors";
import sensorContacts from "../data/sensorContacts";
import {
PROBE_SCIENCE_CORE_QUERY,
PROBES_SCIENCE_CORE_SUB,
PROBE_SCIENCE_CONTACTS_CORE_SUB,
} from "components/views/ProbeScience/core";
import {PROBE_SCIENCE_EMITTER_SUB} from "components/views/ProbeScience/probeScience";
export default [
{
request: {
query: PROBES_SCIENCE_QUERY,
variables: {simulatorId: "test"},
},
result: {
data: {
sensorContacts,
sensors,
probes: systems.probes,
},
},
},
{
request: {
query: PROBES_SCIENCE_SUB,
variables: {simulatorId: "test"},
},
result: {
data: {
probesUpdate: systems.probes,
},
},
},
{
request: {
query: PROBES_SCIENCE_CONTACT_SUB,
variables: {simulatorId: "test"},
},
result: {
data: {
sensorContactUpdate: sensorContacts,
},
},
},
{
request: {
query: PROBE_SCIENCE_EMITTER_SUB,
variables: {simulatorId: "test"},
},
result: {
data: {
scienceProbeEmitter: {
name: null,
type: null,
charge: null,
},
},
},
},
{
request: {
query: PROBE_SCIENCE_EMITTER_SUB,
variables: {simulatorId: "test"},
},
result: {
data: {
scienceProbeEmitter: {
name: null,
type: null,
charge: null,
},
},
},
},
{
request: {
query: PROBE_SCIENCE_CORE_QUERY,
variables: {simulatorId: "test"},
},
result: {
data: {
sensorContacts,
sensors,
probes: systems.probes,
},
},
},
{
request: {
query: PROBES_SCIENCE_CORE_SUB,
variables: {simulatorId: "test"},
},
result: {
data: {
probesUpdate: systems.probes,
},
},
},
{
request: {
query: PROBE_SCIENCE_CONTACTS_CORE_SUB,
variables: {simulatorId: "test"},
},
result: {
data: {
sensorContactUpdate: sensorContacts,
},
},
},
];
|
var multiplayer = new function(){
this.players = [];
this.add_player = function(player){
console.log("new player");
var scale = [1,1,1];
var data = {};
data['x1'] = 0;
data['y1'] = 0;
elements.add_OBJ(link_mushroom_obj,link_tree_texture,data, scale,"opponent",false, player.id);
};
this.remove_player = function(id){
scene.remove(multiplayer.players[""+id]);
delete multiplayer.players[""+id];
}
};
Arena.when({
playerMove: function (player) {
var local_player = multiplayer.players[""+player.id];
if(local_player == undefined){
return;
}
local_player.position.x = player.x;
local_player.position.y = player.y - 15;
local_player.position.z = player.z;
},
newRegularMushroom: function (position) {
elements.addMushroomWithPosition(position);
},
pickupMushroom: function (id, team, position) {
elements.removeElementPositionMush(position);
},
newPlayer: function (player) {
multiplayer.add_player(player);
},
playerLeft: function (id) {
multiplayer.remove_player(id);
},
newMegaMushroom: function (position) {
position.isMegamush = true;
elements.addMushroomWithPosition(position);
},
updateScore: function (score) {
game.player.points = score[0];
game.opponent.points = score[1];
message.showScore();
},
displayMegaMushroom: function () {
message.showStrobMessage("MEGA MUSH !!",20);
},
displayMushroomWave: function () {
message.showStrobMessage("Vague de champignons !",20);
}
});
|
define(function(require, exports, module) {
exports.init = function(){
Manager()
}
function Manager(){
$("#manager").click(function(){
location.href = $(this).attr("data-href");
});
}
});
|
MapSearchApp.init = function () {
var realEstates = MapSearchApp.Repositories.realEstateRepository.getAll();
var pageView = new MapSearchApp.Views.PageView({
collection: realEstates
});
pageView.render();
$(".js-app").html(pageView.$el);
MapSearchApp.trigger("afterRender");
};
$(function () {
MapSearchApp.init();
});
|
(function(){
function CollectionCtrl(Fixtures){
this.albums = Fixtures.getCollection(12);
}
angular
.module('blocJams')
.controller('CollectionCtrl',['Fixtures', CollectionCtrl]);
})();
|
/**
* TODO: Rename. Refactor with VerticalLabelNames.
*/
Ext.define('HorizontalLabelNames', {
alias: "widget.HorizontalLabelNames",
extend: 'Ext.panel.Panel',
layout: 'absolute',
items: [
{
xtype: 'component',
autoEl: 'canvas',
itemId: 'canvas',
x: 0,
y: 0,
style: {
'z-index': '0'
}
},
{
xtype: 'component',
autoEl: 'canvas',
itemId: 'canvasOverlay',
x: 0,
y: 0,
style: {
'z-index': '1'
}
}
],
config: {
labelVisibleLength: null,
propertiesToRender: []
},
initComponent: function () {
this.callParent(arguments);
},
afterRender: function () {
this.callParent(arguments);
this.canvas = this.getComponent("canvas").getEl();
this.ctx = this.canvas.dom.getContext("2d");
this.canvasOverlay = this.getComponent("canvasOverlay").getEl();
this.ctxOverlay = this.canvasOverlay.dom.getContext("2d");
},
refreshCanvasSize: function () {
this.canvas.dom.width = this.getWidth();
this.canvas.dom.height = this.getLabelVisibleLength();
this.canvasOverlay.dom.width = this.getWidth();
this.canvasOverlay.dom.height = this.getLabelVisibleLength();
},
/**
*
*/
draw: function () {
this.refreshCanvasSize();
this.ctx.save();
this.ctx.translate(0, this.getLabelVisibleLength());
this.ctx.fillStyle = "black";
for (var i = 0; i < this.propertiesToRender.length; i++) {
var property = this.propertiesToRender[i];
this.ctx.translate(0, -(property.size / 2 + 4)); //fontSize
this.ctx.fillText(property.name, 0, 0);
this.ctx.translate(0, -(property.size / 2 - 4)); //fontSize
}
this.ctx.restore();
}
});
|
import React, { PropTypes } from 'react';
import c from '../../pages/common.css';
import cx from 'classnames';
class ApplicationPanel extends React.Component {
static propTypes = {
handleChange: React.PropTypes.func,
value: React.PropTypes.string
};
render() {
const {handleChange, value} = this.props;
return (
<form role="form">
<div className="form-group">
<label htmlFor="input1" className="required-pf">Application</label>
<textarea type="text" className="form-control" id="input1" required="" rows="10"
placeholder="paste application json..."
value={value}
onChange={handleChange}/>
</div>
</form>
)
}
}
export default ApplicationPanel;
|
/*
* Copyright 2013 Amadeus s.a.s.
* 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.
*/
/**
* Test different API for the section statement
*/
Aria.classDefinition({
$classpath : "test.aria.templates.section.sectionAttributes.SectionAttributesTestCase",
$extends : "aria.jsunit.TemplateTestCase",
$dependencies : ["aria.utils.Dom"],
$prototype : {
runTemplateTest : function () {
this.dom = this.templateCtxt.$getElementById('section_1');
this.checkGetAttribute();
},
checkGetAttribute : function (args) {
var dom = this.dom;
var title = dom.getAttribute('title');
this.assertEquals(title, "This is my section", "getAttributes doesn't work properly");
this.checkClasses();
},
checkClasses : function (args) {
var dom = this.dom;
this.assertTrue(dom.classList.contains("class1"), "The dom should contains the class1");
this.assertTrue(dom.classList.contains("class2"), "The dom should contains the class2");
this.assertEquals(dom.classList.getClassName(), "class1 class2", "classList.getClassName should return 'class1 class2'");
dom.classList.add("class3");
this.assertTrue(dom.classList.contains("class3"), "The dom should contains the class3");
dom.classList.remove("class2");
this.assertFalse(dom.classList.contains("class2"), "The dom shouldn't contains the class2");
dom.classList.toggle("class3");
this.assertFalse(dom.classList.contains("class3"), "The dom shouldn't contains the class3");
dom.classList.toggle("class2");
this.assertTrue(dom.classList.contains("class2"), "The dom should contains the class2");
dom.classList.setClassName("foo1 foo2");
this.assertFalse(dom.classList.contains("class1"), "The dom shouldn't contains class1");
this.assertTrue(dom.classList.contains("foo1"), "The dom should contains foo1");
this.assertTrue(dom.classList.contains("foo2"), "The dom should contains foo2");
this.checkExpando();
},
checkExpando : function (args) {
var dom = this.dom;
this.assertEquals(dom.getData("foo1"), "Foo 1", "The expando attribute 'foo1' should be set to 'Foo 1'");
this.assertEquals(dom.getData("foo2"), "Foo 2", "The expando attribute 'foo2' should be set to 'Foo 2'");
this.testEnd();
},
testEnd : function () {
this.notifyTemplateTestEnd();
}
}
});
|
(function () {
'use strict';
angular.module('xos.dashboardManager')
.directive('dashboardForm', function(){
return {
restrict: 'E',
scope: {},
bindToController: true,
controllerAs: 'vm',
templateUrl: 'templates/dashboard-form.tpl.html',
controller: function($stateParams, $log, Dashboards){
this.dashboard = {
enabled: true
};
if($stateParams.id){
Dashboards.get({id: $stateParams.id}).$promise
.then(dash => {
this.dashboard = dash;
})
.catch(e => {
console.log(e);
})
}
this.formConfig = {
exclude: [
'backend_register',
'controllers',
'deployments',
'enacted',
'humanReadableName',
'lazy_blocked',
'no_policy',
'no_sync',
'policed',
'write_protect',
'icon',
'icon_active'
],
actions: [
{
label: 'Save',
icon: 'ok',
cb: (item,form) => {
if (!form.$valid){
return;
}
if(item.name && item.url && item.custom_icon){
var indexOfXos = item.url.indexOf('xos');
if (indexOfXos>=0){
var dashboard_name = item.url.slice(indexOfXos+3,item.url.length).toLowerCase();
item.icon =dashboard_name.concat('-icon.png');
item.icon_active =dashboard_name.concat('-icon-active.png');
}
else{
item.icon ='default-icon.png';
item.icon_active ='default-icon-active.png';
}
}
else{
item.icon ='default-icon.png';
item.icon_active ='default-icon-active.png';
}
this.createOrUpdateDashboard(item);
},
class: 'success'
},
{
label: 'Esport to TOSCA',
icon: 'export',
cb: (item) => {
this.toTosca(item);
},
class: 'primary'
}
],
formName: 'dashboardForm',
feedback: {
show: false,
message: 'Form submitted successfully !!!',
type: 'success'
},
fields: {
name: {
type: 'string',
validators: {
required: true
}
},
url: {
type: 'string',
validators: {
required: true
}
},
enabled: {
type: 'boolean'
},
custom_icon: {
type: 'boolean'
}
}
};
this.createOrUpdateDashboard = dashboard => {
let p;
if(dashboard.id){
delete dashboard.controllers;
delete dashboard.deployments;
p = dashboard.$save();
}
else{
p = Dashboards.save(dashboard).$promise;
}
p.then(res => {
this.formConfig.feedback.show = true;
})
.catch(e => {
$log.info(e);
this.formConfig.feedback.show = true;
this.formConfig.feedback.message = e;
this.formConfig.feedback.type='danger';
})
};
this.toTosca = dashboard => {
const yaml = {}
yaml[dashboard.name] = {
type: 'tosca.nodes.DashboardView',
properties: {
url: dashboard.url
}
};
this.tosca = jsyaml.dump(yaml).replace(/'/g, '');
const yamlRequirements = {
requirements: []
};
const dashboardRequirements = {};
dashboardRequirements[`${dashboard.name.toLowerCase()}_dashboard`] = {
node: dashboard.name,
relationship: 'tosca.relationships.UsesDashboard'
}
yamlRequirements.requirements.push(dashboardRequirements);
this.toscaRequirements = jsyaml.dump(yamlRequirements).replace(/'/g, '');
};
}
}
});
})();
|
// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
// Get our API routes
const api = require('./server/routes/api');
const app = express();
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Set our api routes
app.use('/api', api);
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3000';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on localhost:${port}`));
|
const assert = require('assert');
const adminHelper = require('../common/admin-helper')();
const Config = require('../../lib/config/config');
const os = require('os');
const fs = require('fs');
const path = require('path');
const idGen = require('uuid62');
const yaml = require('js-yaml');
describe('REST: policies', () => {
let config;
beforeEach(() => {
config = new Config();
config.gatewayConfigPath = path.join(os.tmpdir(), idGen.v4() + 'yml');
});
afterEach(() => {
return adminHelper.stop();
});
describe('when no policies defined', () => {
beforeEach(() => {
const initialConfig = {
admin: { port: 0 }
};
fs.writeFileSync(config.gatewayConfigPath, yaml.dump(initialConfig));
config.loadGatewayConfig();
return adminHelper.start({ config });
});
it('should activate new policy', () => {
return adminHelper.admin.config.policies
.activate('test')
.then(() => {
const data = fs.readFileSync(config.gatewayConfigPath, 'utf8');
const cfg = yaml.load(data);
assert.deepStrictEqual(cfg.policies, ['test']);
});
});
});
describe('when policies defined', () => {
beforeEach(() => {
const initialConfig = {
admin: { port: 0 },
policies: ['example', 'hello']
};
fs.writeFileSync(config.gatewayConfigPath, yaml.dump(initialConfig));
config.loadGatewayConfig();
return adminHelper.start({ config });
});
it('should create a new api endpoint', () => {
return adminHelper.admin.config.policies
.activate('test')
.then(() => {
const data = fs.readFileSync(config.gatewayConfigPath, 'utf8');
const cfg = yaml.load(data);
assert.deepStrictEqual(cfg.policies, ['example', 'hello', 'test']);
});
});
it('should deactivate existing policy', () => {
return adminHelper.admin.config.policies
.deactivate('example')
.then(() => {
const data = fs.readFileSync(config.gatewayConfigPath, 'utf8');
const cfg = yaml.load(data);
assert.deepStrictEqual(cfg.policies, ['hello']);
});
});
it('should list all enabled policies', () => {
return adminHelper.admin.config.policies
.list()
.then((policies) => {
assert.deepStrictEqual(policies, ['example', 'hello']);
});
});
});
});
|
describe("", function() {
var rootEl;
beforeEach(function() {
rootEl = browser.rootEl;
browser.get("build/docs/examples/example-example100/index.html");
});
it('should format numbers', function() {
expect(element(by.id('number-default')).getText()).toBe('1,234.568');
expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
});
it('should update', function() {
element(by.model('val')).clear();
element(by.model('val')).sendKeys('3374.333');
expect(element(by.id('number-default')).getText()).toBe('3,374.333');
expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
});
});
|
import React from 'react'
import { Component } from 'react'
import Select from 'react-select'
import './CategorySelect.scss'
export default class CategorySelect extends Component {
render() {
const {categories, value, onChange, handleBeingTouched, touched, error} = this.props
var options = categories.map(function(category) {
return {label: category.display_name, value: category.id}
})
return (
<div className='category-select-container'>
<label className='category-select-label ncss-label'>Category</label>
<Select
className={((touched && error) ? 'category-select select-container-error' : 'category-select select-container')}
onChange = {(v) => { handleBeingTouched(); onChange(v)} }
onBlur={() => { handleBeingTouched() }}
placeholder="Choose a Category"
value={value}
options={options} />
{touched && error && <div className='select-error-msg'>{error}</div>}
</div>
)
}
}
|
import React from 'react';
import { BannerRow, H2, Button } from '@appbaseio/designkit';
import PropTypes from 'prop-types';
import { css } from 'react-emotion';
import { SecondaryLink } from '../styles';
const style = css`
p {
color: #ffffff;
font-weight: 300;
}
`;
const button = {
fontSize: '14px',
lineHeight: '19px',
fontWeight: 'bold',
};
const Banner = ({ config, theme, configName }) => (
<BannerRow>
{config.map((b, i) => (
<BannerRow.Column
key={
// eslint-disable-next-line
i
}
className={style}
style={{
backgroundColor: b.backgroundColor,
}}
>
<div>
<H2 light>{b.title}</H2>
<p>{b.description}</p>
<div className="button-row center">
<Button
href={b.button.href}
uppercase
big
primary={configName !== 'vue'}
bold
style={{
backgroundColor: theme.secondary,
...button,
}}
>
{b.button.title}
</Button>
<SecondaryLink href={b.link.href}>{b.link.title}</SecondaryLink>
</div>
</div>
</BannerRow.Column>
))}
</BannerRow>
);
Banner.defaultProps = {
configName: 'web',
};
Banner.propTypes = {
// eslint-disable-next-line
theme: PropTypes.object,
configName: PropTypes.string,
config: PropTypes.arrayOf(PropTypes.shape({
backgroundColor: PropTypes.string,
title: PropTypes.string,
description: PropTypes.string,
button: PropTypes.shape({
title: PropTypes.string,
href: PropTypes.string,
}),
link: PropTypes.shape({
title: PropTypes.string,
href: PropTypes.string,
}),
})).isRequired,
};
export default Banner;
|
/*
* Copyright 2015 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var container = require('rhea');
var amqp_message = container.message;
var args = require('./options.js').options({
'm': { alias: 'messages', default: 100, describe: 'number of messages to send'},
'n': { alias: 'node', default: 'examples', describe: 'name of node (e.g. queue) to which messages are sent'},
'h': { alias: 'host', default: 'localhost', describe: 'dns or ip name of server where you want to connect'},
'p': { alias: 'port', default: 5672, describe: 'port to connect to'}
}).help('help').argv;
var confirmed = 0, sent = 0;
var total = args.messages;
container.on('sendable', function (context) {
while (context.sender.sendable() && sent < total) {
sent++;
console.log('sent ' + sent);
var stringifiedPayload = JSON.stringify({'sequence':sent});
// In this example, we are sending a byte array containing ascii
// characters though this can be any opaque binary payload
var body = amqp_message.data_section(new Buffer(stringifiedPayload, 'utf8'));
context.sender.send({message_id:sent, body});
}
});
container.on('accepted', function (context) {
if (++confirmed === total) {
console.log('all messages confirmed');
context.connection.close();
}
});
container.on('disconnected', function (context) {
if (context.error) console.error('%s %j', context.error, context.error);
sent = confirmed;
});
container.connect({port: args.port, host: args.host}).open_sender(args.node);
|
let obj = {
@readonly firstName: "first",
@readonly lastName: "last",
@nonconfigurable fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
/*
// Desugaring
//
// The following is an approximate down-level desugaring to match the expected semantics.
// The actual host implementation would generally be more efficient.
let obj = declareObject(
// Object literal declaration
{
firstName: "first",
lastName: "last",
fullName() {
return `${this.firstName} ${this.lastName}`;
}
},
// Object description
{
members: [
{ kind: "property", name: "firstName", decorations: [readonly] },
{ kind: "property", name: "lastName", decorations: [readonly] },
{ kind: "method", name: "fullName", decorations: [nonconfigurable] }
]
}
).finishDeclarationInitialization();
*/
|
'use strict';
angular.module('moviefanApp')
.controller('LoginController', function ($rootScope, $scope, $state, $timeout, Auth) {
$scope.user = {};
$scope.errors = {};
$scope.rememberMe = true;
$timeout(function (){angular.element('[ng-model="username"]').focus();});
$scope.login = function (event) {
event.preventDefault();
Auth.login({
username: $scope.username,
password: $scope.password,
rememberMe: $scope.rememberMe
}).then(function () {
$scope.authenticationError = false;
if ($rootScope.previousStateName === 'register') {
$state.go('home');
} else {
$rootScope.back();
}
}).catch(function () {
$scope.authenticationError = true;
});
};
});
|
/*
* ../../../..//jax/input/MathML/entities/k.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* 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.
*/
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/entities/k.js
*
* Copyright (c) 2010-2018 The MathJax Consortium
*
* 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(MATHML) {
MathJax.Hub.Insert(MATHML.Parse.Entity, {
KHcy: "\u0425",
KJcy: "\u040C",
Kappa: "\u039A",
Kcedil: "\u0136",
Kcy: "\u041A",
kcedil: "\u0137",
kcy: "\u043A",
kgreen: "\u0138",
khcy: "\u0445",
kjcy: "\u045C"
});
MathJax.Ajax.loadComplete(MATHML.entityDir + "/k.js");
})(MathJax.InputJax.MathML);
|
var clusterpost = require("clusterpost-lib");
var path = require('path');
var Promise = require('bluebird');
var argv = require('minimist')(process.argv.slice(2));
const os = require('os');
const fs = require('fs');
var agentoptions = {
rejectUnauthorized: false
}
clusterpost.setAgentOptions(agentoptions);
const help = function(){
console.error("Help: Download tasks from the server.");
console.error("\nOptional parameters:");
console.error("--dir Output directory, default: ./out");
console.error("--status one of [DONE, RUN, FAIL, EXIT, UPLOADING, CREATE], default: DONE");
console.error("--print , if provided the information is printed only");
console.error("--delete, default false, when downloading jobs with status 'DONE', the jobs will be deleted upon completion");
console.error("--j job id, default: ");
console.error("--executable executable, default: all executables");
console.error("--email email, default: (authenticated user)");
console.error("--config_codename codename, default: clusterpost");
}
if(argv["h"] || argv["help"]){
help();
process.exit(1);
}
var deletejobs = false;
if(argv["delete"] !== undefined){
console.log("After successful download, jobs with status DONE will be deleted!");
deletejobs = true;
}
var userEmail = undefined;
if(argv["email"]){
userEmail = argv["email"];
}
var outputdir = "./out";
if(argv["dir"]){
outputdir = argv["dir"];
}
var status = 'DONE';
if(argv["status"]){
status = argv["status"];
}
var jobid = argv["j"];
var executable = argv["executable"];
var print = argv["print"];
console.log("Output dir", outputdir);
console.log("Status", status);
if(jobid){
console.log("jobid", jobid);
}
if(executable){
console.log("executable", executable);
}
if(print){
console.log("print", print);
}
var config_codename = 'clusterpost';
if(argv["config_codename"]){
config_codename = argv["config_codename"];
}
clusterpost.start(path.join(os.homedir(), '.' + config_codename + '.json'))
.then(function(){
if(!print){
if(!jobid){
return clusterpost.getJobs(executable, status, userEmail)
.then(function(jobs){
return Promise.map(jobs, function(job){
console.log(JSON.stringify(job, null, 2));
if(job.outputdir){
return clusterpost.getJobOutputs(job, job.outputdir)
.then(function(){
if(job.name){
console.log(job.name, "downloaded...");
}else{
console.log(job._id, "downloaded...");
}
if(deletejobs){
console.log("Deleting job");
return clusterpost.deleteJob(job._id);
}
});
}else{
var joboutputdir = undefined;
if(job.name){
joboutputdir = path.join(outputdir, job.name);
}else{
joboutputdir = path.join(outputdir, job._id);
}
return clusterpost.getJobOutputs(job, joboutputdir)
.then(function(){
if(job.name){
console.log(job.name, "downloaded...");
}else{
console.log(job._id, "downloaded...");
}
if(deletejobs){
console.log("Deleting job");
return clusterpost.deleteJob(job._id);
}
});
}
},
{
concurrency: 1
});
});
}else{
return clusterpost.getDocument(jobid)
.then(function(job){
if(job.outputdir){
return clusterpost.getJobOutputs(job, job.outputdir);
}else{
var joboutputdir = undefined;
if(job.name){
joboutputdir = path.join(outputdir, job.name);
}else{
joboutputdir = path.join(outputdir, job._id);
}
return clusterpost.getJobOutputs(job, joboutputdir);
}
})
.then(function(){
console.log("job downloaded...");
if(deletejobs){
console.log("Deleting job");
return clusterpost.deleteJob(jobid);
}
});
}
}else{
if(!jobid){
return clusterpost.getJobs(executable, status, userEmail)
.then(function(jobs){
console.log(JSON.stringify(jobs, null, 2))
});
}else{
return clusterpost.getDocument(jobid)
.then(function(job){
console.log(JSON.stringify(job, null, 2))
});
}
}
})
.catch(console.error)
|
'use strict';
angular.module('aquilaApp')
.config(function ($stateProvider) {
$stateProvider
.state('register', {
parent: 'account',
url: '/register',
data: {
roles: [],
pageTitle: 'register.title'
},
views: {
'content@': {
templateUrl: 'scripts/app/account/register/register.html',
controller: 'RegisterController'
}
},
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('register');
return $translate.refresh();
}]
}
});
});
|
var pulse = pulse || {};
pulse.NoteGroup = Backbone.Collection.extend({
model: pulse.Note,
});
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { SnackbarContext } from '@googleforcreators/design-system';
import { ConfigContext } from '@googleforcreators/story-editor';
/**
* Internal dependencies
*/
import useMediaPicker from '../useMediaPicker';
jest.mock('@googleforcreators/design-system', () => ({
...jest.requireActual('@googleforcreators/design-system'),
useSnackbar: () => {
return {
showSnackbar: jest.fn(),
};
},
}));
function setup({ args, cropParams }) {
const configValue = {
capabilities: {
hasUploadMediaAction: true,
},
...args,
};
const wrapper = ({ children }) => (
<ConfigContext.Provider value={configValue}>
<SnackbarContext.Provider>{children}</SnackbarContext.Provider>
</ConfigContext.Provider>
);
const onSelect = jest.fn();
const onClose = jest.fn();
const onPermissionError = jest.fn();
const { result } = renderHook(
() => useMediaPicker({ onSelect, onClose, onPermissionError, cropParams }),
{
wrapper,
}
);
return {
openMediaPicker: result.current,
onPermissionError,
};
}
describe('useMediaPicker', () => {
it('user unable to upload', () => {
const { openMediaPicker, onPermissionError } = setup({
args: {
capabilities: {
hasUploadMediaAction: false,
},
},
});
act(() => {
openMediaPicker(new Event('click'));
});
expect(onPermissionError).toHaveBeenCalledTimes(1);
});
it('user unable to upload with cropped', () => {
const { openMediaPicker, onPermissionError } = setup({
args: {
capabilities: {
hasUploadMediaAction: false,
},
},
cropParams: {
height: 500,
width: 500,
flex_width: false,
flex_height: false,
},
});
act(() => {
openMediaPicker(new Event('click'));
});
expect(onPermissionError).toHaveBeenCalledTimes(1);
});
});
|
/**
* @license
* Copyright 2016 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const Audit = require('../../../audits/accessibility/aria-allowed-attr.js');
const assert = require('assert');
/* eslint-env mocha */
describe('Accessibility: aria-allowed-attr audit', () => {
it('generates an audit output', () => {
const artifacts = {
Accessibility: {
violations: [{
id: 'aria-allowed-attr',
nodes: [],
help: 'http://example.com/'
}]
}
};
const output = Audit.audit(artifacts);
assert.equal(output.rawValue, false);
assert.equal(output.displayValue, '');
});
it('generates an audit output (single node)', () => {
const artifacts = {
Accessibility: {
violations: [{
id: 'aria-allowed-attr',
nodes: [{}],
help: 'http://example.com/'
}]
}
};
const output = Audit.audit(artifacts);
assert.equal(output.rawValue, false);
assert.equal(output.displayValue, '');
});
});
|
import Vue from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import vuetify from './plugins/vuetify';
import 'roboto-fontface/css/roboto/roboto-fontface.css'
import '@mdi/font/css/materialdesignicons.css'
import VueCompositionApi from "@vue/composition-api";
Vue.use(VueCompositionApi);
Vue.config.productionTip = false
new Vue({
router,
store,
vuetify,
render: h => h(App)
}).$mount('#app')
|
/**
* @namespace export
*/
module.exports =
{
CmConfiguration: require('./CmConfiguration.js').CmConfiguration,
CmExporter: require('./CmExporter.js').CmExporter,
CmRenderer: require('./CmRenderer.js').CmRenderer,
CmTransformer: require('./CmTransformer.js').CmTransformer,
renderer: require('./renderer/index.js'),
transformer: require('./transformer/index.js')
};
|
import { setPropertiesFromJSON } from '../../json-helper';
import Entity from './Entity';
/**
* Generated class for shr.entity.Group.
* @extends Entity
*/
class Group extends Entity {
/**
* Get the entry information.
* @returns {Entry} The shr.base.Entry
*/
get entryInfo() {
return this._entryInfo;
}
/**
* Set the entry information.
* @param {Entry} entryInfo - The shr.base.Entry
*/
set entryInfo(entryInfo) {
this._entryInfo = entryInfo;
}
/**
* Get the Type.
* @returns {Type} The shr.entity.Type
*/
get type() {
return this._type;
}
/**
* Set the Type.
* @param {Type} type - The shr.entity.Type
*/
set type(type) {
this._type = type;
}
/**
* Get the ActiveFlag.
* @returns {ActiveFlag} The shr.entity.ActiveFlag
*/
get activeFlag() {
return this._activeFlag;
}
/**
* Set the ActiveFlag.
* @param {ActiveFlag} activeFlag - The shr.entity.ActiveFlag
*/
set activeFlag(activeFlag) {
this._activeFlag = activeFlag;
}
/**
* Get the Title.
* @returns {Title} The shr.core.Title
*/
get title() {
return this._title;
}
/**
* Set the Title.
* @param {Title} title - The shr.core.Title
*/
set title(title) {
this._title = title;
}
/**
* Get the Definitional.
* @returns {Definitional} The shr.core.Definitional
*/
get definitional() {
return this._definitional;
}
/**
* Set the Definitional.
* @param {Definitional} definitional - The shr.core.Definitional
*/
set definitional(definitional) {
this._definitional = definitional;
}
/**
* Get the MembershipCriterion array.
* @returns {Array<MembershipCriterion>} The shr.entity.MembershipCriterion array
*/
get membershipCriterion() {
return this._membershipCriterion;
}
/**
* Set the MembershipCriterion array.
* @param {Array<MembershipCriterion>} membershipCriterion - The shr.entity.MembershipCriterion array
*/
set membershipCriterion(membershipCriterion) {
this._membershipCriterion = membershipCriterion;
}
/**
* Get the Member array.
* @returns {Array<Member>} The shr.entity.Member array
*/
get member() {
return this._member;
}
/**
* Set the Member array.
* @param {Array<Member>} member - The shr.entity.Member array
*/
set member(member) {
this._member = member;
}
/**
* Get the Count.
* @returns {Count} The shr.core.Count
*/
get count() {
return this._count;
}
/**
* Set the Count.
* @param {Count} count - The shr.core.Count
*/
set count(count) {
this._count = count;
}
/**
* Deserializes JSON data to an instance of the Group class.
* The JSON must be valid against the Group JSON schema, although this is not validated by the function.
* @param {object} json - the JSON data to deserialize
* @returns {Group} An instance of Group populated with the JSON data
*/
static fromJSON(json={}) {
const inst = new Group();
setPropertiesFromJSON(inst, json);
return inst;
}
}
export default Group;
|
import React from 'react';
export default () => {return <h1>Page Under Construction</h1>}
|
document.write('2018年1月');
|
/**
* @fileoverview Utility to detect and address folder and file sharing which is broader than intended
* Removes overly broad permissions at folder level
* Notifies specified email of breaches
*/
function main() {
var user = Session.getActiveUser().getEmail();
var hostDomain = user.split('@')[1];
var permittedDomainArr = [];
var folder = DriveApp.getFolderById(ROOT_FOLDER_ID);
var notificationObj = {};
folderPermissions_(hostDomain, folder, permittedDomainArr, notificationObj);
var rootFolderName = folder.getName();
notify(notificationObj, rootFolderName);
}
// recursive rename
function folderPermissions_(hostDomain, folder, permittedDomainArr, notificationObj) {
//Logger.log('permittedDomainArr '+JSON.stringify(permittedDomainArr));
//Logger.log('notificationObj '+JSON.stringify(notificationObj));
var file;
var isFolder;
try {
// check whether down at shared folder level
var folderId = folder.getId();
if (SHARED_FOLDER_OBJ[folderId]) {
// add to list of permitted domains at this level
permittedDomainArr.push(SHARED_FOLDER_OBJ[folderId]);
}
//validate folder permissions
isFolder = true;
var userArr = folder.getViewers(); // includes commenters
validatePermissions_(hostDomain, isFolder, folder, 'VIEWER', userArr, permittedDomainArr, notificationObj);
var userArr = folder.getEditors();
validatePermissions_(hostDomain, isFolder, folder, 'EDITOR', userArr, permittedDomainArr, notificationObj);
//validate file permissions
isFolder = false;
var files = folder.getFiles();
while (files.hasNext()) {
file = files.next();
if (!file.isTrashed()) {
var userArr = file.getViewers(); // includes commenters
validatePermissions_(hostDomain, isFolder, file, 'VIEWER', userArr, permittedDomainArr, notificationObj);
var userArr = file.getEditors();
validatePermissions_(hostDomain, isFolder, file, 'EDITOR', userArr, permittedDomainArr, notificationObj);
}
}
//do the same for nested folders
var folders = folder.getFolders();
while (folders.hasNext()) {
folder = folders.next();
var branchPermittedDomainArr = (permittedDomainArr.length > 0) ? permittedDomainArr: []; // need one per branch or permissions are accumulated across folders as well as down
folderPermissions_(hostDomain, folder, permittedDomainArr, notificationObj);
}
}
catch (error) {
Logger.log(error);
}
}
function validatePermissions_(hostDomain, isFolder, fileOrFolder, permissionType, userArr, permittedDomainArr, notificationObj) {
var permissionsArr = [];
var userArrLen = userArr.length;
var userDomain;
for (var i=userArrLen; i--;) {
userDomain = userArr[i].getDomain();
if (userDomain != hostDomain && permittedDomainArr.indexOf(userDomain) == -1) {
fixPermissions_(isFolder, fileOrFolder, permissionType, userArr[i], permittedDomainArr, notificationObj);
}
}
}
function fixPermissions_(isFolder, fileOrFolder, permissionType, user, permittedDomainArr, notificationObj) {
var result = '';
if ((isFolder && REMOVE_FOLDER_PERMISSIONS) || (!isFolder && REMOVE_FILE_PERMISSIONS)) {
// may not want to remove individual file shares
if (permissionType == 'VIEWER') {
try {
fileOrFolder.removeViewer(user); // includes commenter
result = 'SUCCESS';
}
catch (error){
result = 'FAILURE';
}
}
else {
try {
fileOrFolder.removeEditor(user); // includes commenter
result = 'SUCCESS';
}
catch (error){
result = 'FAILURE';
}
}
}
if (isFolder || NOTIFY_FILE_ISSUES) {
addNotification_(isFolder, fileOrFolder, user, permissionType, permittedDomainArr, notificationObj, result);
}
}
function addNotification_(isFolder, fileOrFolder, user, permissionType, permittedDomainArr, notificationObj, result) {
var id;
var name;
var url;
var email;
try {
id = fileOrFolder.getId();
name = fileOrFolder.getName();
url = fileOrFolder.getUrl();
email = user.getEmail();
}
catch (error){
}
var assetType = isFolder ? 'Folder' : 'File';
var permittedDomains = '';
var permittedDomainArrLen = permittedDomainArr.length;
for (var i=0;i<permittedDomainArrLen;i++) {
if (permittedDomains) {
permittedDomains = permittedDomains + ', ';
}
permittedDomains = permittedDomains + permittedDomainArr[i];
}
if (!notificationObj[id]) {
notificationObj[id] = {assetType: assetType, fileOrFolder: fileOrFolder, name: name, url: url, permittedDomains: permittedDomains, emailArr: [email], permissionTypeArr: [permissionType], resultArr: [result]};
}
else {
notificationObj[id].emailArr.push(email);
notificationObj[id].permissionTypeArr.push(permissionType);
notificationObj[id].resultArr.push(result);
}
}
|
import Ember from 'ember';
export default Ember.Route.extend({
k8s: Ember.inject.service(),
model(params) {
return this.get('k8s').getService(params.name);
}
});
|
angular.module('elementBoxApp.products.productInfo')
.controller('ProductInfoCtrl', [
'$scope', '$rootScope', '$state', '$stateParams', '$timeout', 'ModalAlert', 'ProductsService', 'UserService', 'CommentsService', 'EVENT_NAMES',
function($scope, $rootScope, $state, $stateParams, $timeout, ModalAlert, ProductsService, UserService, CommentsService, EVENT_NAMES) {
$scope.slides = [];
$scope.slidesIndex = 0;
$scope.userHasRated = false;
$scope.rateVal = null;
$scope.newComment = '';
$scope.commentSent = false;
var ratingInProcess = false;
$rootScope.$emit('title', 'TITLE_MY_PRODUCT_INFO');
// Comments pagination:
$scope.comments = [];
$scope.commentsData = {
page: 1,
pageSize: 3,
totalPages: 0,
totalComments: 0
};
var onNeedToLogin = function() {
ModalAlert.alert({
title: 'PRODUCTS.PLEASE_SIGNIN',
msg: 'PRODUCTS.PLEASE_SIGNIN_TO_ACCESS'
});
};
// $scope.myInterval = 5000;
// $scope.slides2 = [];
// Fetching product:
$scope.product = ProductsService.get({
id: $stateParams.productId
}, function(p) { // success cbk.
p.images = p.images ? p.images : [];
p.images.forEach(function(image, index) {
$scope.slides.push({ url: image.url, index: index+1 });
});
// p.rating.value = parseInt(p.rating.value);
}, function(err) { // error cbk.
$state.go('main.products.info-404');
});
$scope.fetchPage = function() {
CommentsService.query({
prodId: $stateParams.productId,
page: $scope.commentsData.page,
pageSize: $scope.commentsData.pageSize
})
.$promise.then(function(res) {
$scope.comments = res.results;
$scope.commentsData.page = res.page;
$scope.commentsData.totalPages = res.totalPages;
$scope.commentsData.totalComments = res.total;
$scope.commentsData.pageSize = res.pageSize;
});
};
$scope.addComment = function(commentTxt) {
if (!commentTxt || !commentTxt.trim()) { return; }
if (!$scope.currentUser || !$scope.currentUser.id) {
onNeedToLogin();
return;
}
var newComment = {
prodId: $stateParams.productId,
text: commentTxt
};
CommentsService.save(newComment, function(data) {
$scope.fetchPage();
$rootScope.$emit(EVENT_NAMES.addComment, newComment);
$scope.newComment = '';
$scope.commentSent = true;
});
};
$scope.$watch('commentsData.page', function(newVal, oldVal) {
$scope.fetchPage();
});
$scope.rate = function(val) {
if ($scope.rateVal || ratingInProcess) { return; }
if (!$scope.currentUser || !$scope.currentUser.id) {
onNeedToLogin();
return;
}
ratingInProcess = true;
ProductsService.rate({_id: $scope.product._id, rating: val}, function() { // success cbk.
$scope.userHasRated = true;
$scope.rateVal = val;
ratingInProcess = false;
}, function() { // err cbk.
ratingInProcess = false;
});
};
$scope.addToWishList = function() {
if (!$scope.currentUser || !$scope.currentUser.id) {
return onNeedToLogin();
}
UserService.addToWishList({ prodId: $scope.product._id }, function() {
$rootScope.$emit(EVENT_NAMES.addWishList, $scope.product);
});
};
$scope.removeFromWishList = function() {
UserService.removeFromWishList({ itemId: $scope.product._id }, function() {
$rootScope.$emit(EVENT_NAMES.removeWishList, $scope.product);
});
};
$scope.hasWishListedProduct = function() {
if (!$scope.currentUser || !$scope.product) {
return false;
}
if (!$scope.currentUser.wishList) {
$scope.currentUser.wishList = [];
}
return $scope.currentUser.wishList.indexOf($scope.product._id) >= 0;
};
// $scope.fetchPage(); // fetching first page.
}
]);
|
var dir_40645110f4b881381ac11b52da3dfc1e =
[
[ "provider", "dir_9a95dbcede8719bb251f64fc00e6b0a1.html", "dir_9a95dbcede8719bb251f64fc00e6b0a1" ]
];
|
'use strict';
const _ = require('lodash');
const serviceUtils = require('../serviceUtils');
/**
* @summary Retrieve a Coding System object.
* @param {String} source Abbreviation of the source coding system under test.
* @param {Function} callback Function called on process completion, with standard (err, result) signature.
* @return {Object} Coding System object
* 'sourceAbbreviation' {String} Abbreviated name of the coding system
* 'nomenclature' {String} Longer description
* 'implementationDate' {String} Implementation date in ISO format
*
* @memberof LexiconService
* @instance
*/
function lookupCodingSystem(source, cb) {
if (!source) {
return cb(this.error('INVALID_CODING_SYSTEM_SOURCE_VALUE'));
}
const findObject = {
query: { sourceAbbreviation: source },
projection: serviceUtils.createProjection(['sourceAbbreviation', 'implementationDate']),
};
this.find('CodingSystems', findObject, (err, res) => {
if (err) {
return cb(err);
}
const codingSystem = _.first(res);
const impDate = _.get(codingSystem, 'implementationDate');
if (_.isDate(impDate)) {
_.set(codingSystem, 'implementationDate', impDate.toISOString());
}
cb(null, codingSystem);
});
}
module.exports = {
lookupCodingSystem,
};
|
import * as utils from '../src/utils.js';
import {config} from '../src/config.js';
import {registerBidder} from '../src/adapters/bidderFactory.js';
import {BANNER, VIDEO} from '../src/mediaTypes.js';
const BIDDER_CODE = 'vdoai';
const ENDPOINT_URL = 'https://prebid.vdo.ai/auction';
export const spec = {
code: BIDDER_CODE,
supportedMediaTypes: [BANNER, VIDEO],
/**
* Determines whether or not the given bid request is valid.
*
* @param {BidRequest} bid The bid params to validate.
* @return boolean True if this is a valid bid, and false otherwise.
*/
isBidRequestValid: function (bid) {
return !!(bid.params.placementId);
},
/**
* Make a server request from the list of BidRequests.
*
* @return Array Info describing the request to the server.
* @param validBidRequests
* @param bidderRequest
*/
buildRequests: function (validBidRequests, bidderRequest) {
if (validBidRequests.length === 0) {
return [];
}
return validBidRequests.map(bidRequest => {
const sizes = utils.getAdUnitSizes(bidRequest);
const payload = {
placementId: bidRequest.params.placementId,
sizes: sizes,
bidId: bidRequest.bidId,
referer: bidderRequest.refererInfo.referer,
id: bidRequest.auctionId,
mediaType: bidRequest.mediaTypes.video ? 'video' : 'banner'
};
bidRequest.params.bidFloor && (payload['bidFloor'] = bidRequest.params.bidFloor);
return {
method: 'POST',
url: ENDPOINT_URL,
data: payload
};
});
},
/**
* Unpack the response from the server into a list of bids.
*
* @param {ServerResponse} serverResponse A successful response from the server.
* @param bidRequest
* @return {Bid[]} An array of bids which were nested inside the server.
*/
interpretResponse: function (serverResponse, bidRequest) {
const bidResponses = [];
const response = serverResponse.body;
const creativeId = response.adid || 0;
// const width = response.w || 0;
const width = response.width;
// const height = response.h || 0;
const height = response.height;
const cpm = response.price || 0;
response.rWidth = width;
response.rHeight = height;
const adCreative = response.vdoCreative;
if (width !== 0 && height !== 0 && cpm !== 0 && creativeId !== 0) {
// const dealId = response.dealid || '';
const currency = response.cur || 'USD';
const netRevenue = true;
// const referrer = bidRequest.data.referer;
const bidResponse = {
requestId: response.bidId,
cpm: cpm,
width: width,
height: height,
creativeId: creativeId,
// dealId: dealId,
currency: currency,
netRevenue: netRevenue,
ttl: config.getConfig('_bidderTimeout'),
// referrer: referrer,
// ad: response.adm
// ad: adCreative,
mediaType: response.mediaType
};
if (response.mediaType == 'video') {
bidResponse.vastXml = adCreative;
} else {
bidResponse.ad = adCreative;
}
if (response.adDomain) {
bidResponse.meta = {
advertiserDomains: response.adDomain
}
}
bidResponses.push(bidResponse);
}
return bidResponses;
},
getUserSyncs: function(syncOptions, serverResponse) {
let syncUrls = serverResponse[0] && serverResponse[0].body && serverResponse[0].body.cookiesync && serverResponse[0].body.cookiesync.bidder_status;
if (syncOptions.iframeEnabled && syncUrls && syncUrls.length > 0) {
let prebidSyncUrls = syncUrls.map(syncObj => {
return {
url: syncObj.usersync.url,
type: 'iframe'
}
})
return prebidSyncUrls;
}
return [];
},
onTImeout: function(data) {},
onBidWon: function(bid) {},
onSetTargeting: function(bid) {}
};
registerBidder(spec);
|
var auth = require( './auth' ),
surveyTemplate = require( '../lib/survey_template' ),
SurveyResponse = require( '../models/survey_response' );
var ExportController = function() {
this.csv = function( req, res ) {
var now = new Date(),
cleanTitle = req.survey.title.replace( /[^a-z0-9]/ig, '' ),
key = req.param( 'key' ),
today = now.getFullYear() + '_' + ( now.getMonth() + 1 ) + '_' + now.getDate(),
flatSurvey = [],
csvData = [],
survey = surveyTemplate.getSurvey( req.survey.version );
survey.pages.forEach( function( page ) {
page.fields.forEach( function( q ) {
if( q.type === 'gridselect' ) {
for( var key in q.options ) {
flatSurvey.push( { name: key, label: q.options[ key ] } );
}
} else {
flatSurvey.push( { name: q.name, label: q.label } );
}
} );
} );
csvData.push( flatSurvey.map( function( q ) { return q.label; } ) );
SurveyResponse.find( { surveyId: req.survey.id }, function( err, responses ) {
if( responses && responses.length ) {
responses.forEach( function( response ) {
csvData.push( flatSurvey.map( function( q ) {
try {
return response.response[ q.name ];
} catch( e ) {
return '';
}
} ) );
} );
}
res.header('Content-Disposition', 'attachment; filename=' + today + '_' + cleanTitle + '.csv');
res.csv( csvData );
} );
};
};
exports.setup = function( app ) {
var exporter = new ExportController();
app.get( '/export/:key', auth.canAccessSurvey, exporter.csv );
};
|
/******************************************************************************
* $URL: https://source.sakaiproject.org/svn/user/tags/sakai-10.1/user-tool/tool/src/webapp/js/userCreateValidation.js $
* $Id: userCreateValidation.js 308075 2014-04-11 12:34:16Z azeckoski@unicon.net $
******************************************************************************
*
* Copyright (c) 2003-2014 The Apereo Foundation
*
* Licensed under the Educational Community 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://opensource.org/licenses/ecl2
*
* 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.
*
*****************************************************************************/
// USER declared in userValidationCommon.js
// Validate the password from the form
USER.validatePassword = function () {
var username = USER.trim(USER.get("eid").value);
var pw = USER.get("pw").value;
var strongMsg = USER.get("strongMsg");
var moderateMsg = USER.get("moderateMsg");
var weakMsg = USER.get("weakMsg");
var failMsg = USER.get("failMsg");
var strengthInfo = USER.get("strengthInfo");
var strengthBar = USER.get("strengthBar");
var strengthBarMeter = USER.get("strengthBarMeter");
// If the password field has a value:
// 1) make the AJAX call to the validate password REST endpoint
// 2) conditionally display the appropriate messages
// 3) conditionally hide/show the strength info message
if (USER.isPasswordPolicyEnabled && pw.length > 0) {
USER.validatePasswordREST(pw, username);
USER.displayMessages(strongMsg, moderateMsg, weakMsg, failMsg, strengthBar, strengthBarMeter);
USER.displayStrengthInfo();
}
// Otherwise, password policy is disabled OR the password field has no value
else {
USER.passwordValid = pw.length > 0;
USER.hideAllElements(strongMsg, moderateMsg, weakMsg, failMsg, strengthInfo, strengthBar, strengthBarMeter);
}
// Verify the passwords match (which in turn validates the form)
USER.verifyPasswordsMatch();
};
// Verify the passwords match
USER.verifyPasswordsMatch = function () {
var pw = USER.get("pw").value;
var pw2 = USER.get("pw0").value;
var matchMsg = USER.get("matchMsg");
var noMatchMsg = USER.get("noMatchMsg");
USER.passwordsMatch = pw === pw2;
if (pw.length > 0 || pw2.length > 0) {
USER.display(matchMsg, USER.passwordsMatch);
USER.display(noMatchMsg, !USER.passwordsMatch);
}
else {
USER.display(matchMsg, false);
USER.display(noMatchMsg, false);
}
USER.validateForm();
}
// Validate the user ID from the form
USER.validateUserId = function () {
var userId = USER.trim(USER.get("eid").value);
USER.userValid = userId.length > 0;
USER.validatePassword();
};
// Validate the email address from the form
USER.validateEmail = function () {
var email = USER.trim(USER.get("email").value);
var emailWarningMsg = USER.get("emailWarningMsg");
if (email.length < 1) {
USER.emailValid = true;
}
else {
USER.emailValid = USER.checkEmail(email);
}
USER.display(emailWarningMsg, !USER.emailValid);
USER.validateForm();
};
// Validate the form (enable/disable the submit button)
USER.validateForm = function () {
var submitButton = USER.get("eventSubmit_doSave");
if (USER.userValid && USER.emailValid && USER.passwordValid && USER.passwordsMatch) {
submitButton.disabled = false;
}
else {
submitButton.disabled = true;
}
setMainFrameHeightNow(window.name);
};
// Initialization function
jQuery(document).ready(function () {
USER.validateEmail();
USER.validateUserId();
});
|
/**
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* 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.
*/
const path = require('path');
const Benchmark = require('benchmark');
const parsePackageString = require('npm-package-arg');
const InstallationUtils = require('../src/utils/installation-utils');
const BenchmarkUtils = require('./utils/benchmark-utils');
const { getLocalPackageEcmaVersion } = require('../src/index.js');
async function coldStartBenchmark(packageString) {
const installPath = await InstallationUtils.getInstallPath();
await InstallationUtils.installPackage(packageString, installPath);
const packageName = parsePackageString(packageString).name;
const packagePath = path.join(installPath, 'node_modules', packageName);
console.log(
'| %s | %dms |',
packageString,
await BenchmarkUtils.getAsyncRuntime(() =>
getLocalPackageEcmaVersion(packagePath)
)
);
await InstallationUtils.cleanupPath(installPath);
}
// Multiple asynchronous suites will interfere in BenchmarkJS so we must use
// suite.on('complete') to sequentially run suites
async function warmRunBenchmark(packageStrings, index) {
if (index >= packageStrings.length) {
return;
}
const packageString = packageStrings[index];
const installPath = await InstallationUtils.getInstallPath();
await InstallationUtils.installPackage(packageString, installPath);
const packageName = parsePackageString(packageString).name;
const packagePath = path.join(installPath, 'node_modules', packageName);
const suite = new Benchmark.Suite('getLocalPackageEcmaVersion');
suite
.add(`Benchmarking getLocalPackageEcmaVersion for ${packageString}`, {
defer: true,
fn: async function (deferred) {
await getLocalPackageEcmaVersion(packagePath);
deferred.resolve();
},
})
.on('cycle', function (event) {
console.log('%s ', String(event.target));
console.log(
' Mean runtime: %dms ',
String((event.target.stats.mean * 1000).toFixed(2))
);
})
.on('complete', async function (event) {
await InstallationUtils.cleanupPath(installPath);
warmRunBenchmark(packageStrings, index + 1);
});
suite.run();
}
async function main() {
const packageNames = [
'bowser@2.10.0',
'chalk@4.1.0',
'@lattice/configurer@0.0.1',
'@babel/core@7.11.4',
'request@2.88.2',
'react@16.13.1',
'react-dom@16.13.1',
'lit-html@1.2.1',
'lodash@4.17.19',
'lodash-es@4.17.15',
'conf@7.1.1',
'swr@0.3.0',
'vue@2.6.11',
'@nelsongomes/ts-timeframe@0.2.2',
];
console.log('Cold-start Benchmarks');
console.log('');
console.log('| File | Time |');
console.log('|------|------|');
for (const packageName of packageNames) {
await coldStartBenchmark(packageName);
}
console.log('\nWarm-run Benchmarks ');
await warmRunBenchmark(packageNames, 0);
}
main();
|
var gulp = require('gulp');
var karma = require('karma');
var fs = require('fs');
gulp.task('test', function() {
new karma.Server({configFile: __dirname + '/karma.conf.js', reporters: 'dots'}).start();
var content = fs.readFileSync('copyAndRenameTest.js');
console.log(content);
});
|
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* 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';
/**
* Compute the hyperbolic cosecant of a number.
*
* @module @stdlib/math/base/special/csch
*
* @example
* var csch = require( '@stdlib/math/base/special/csch' );
*
* var v = csch( 0.0 );
* // returns Infinity
*
* v = csch( 2.0 );
* // returns ~0.2757
*
* v = csch( -2.0 );
* // returns ~-0.2757
*
* v = csch( NaN );
* // returns NaN
*/
// MODULES //
var main = require( './main.js' );
// EXPORTS //
module.exports = main;
|
var Q = require("q")
Q.longStackSupport = true
function a() { Q.delay(100).done(b) }
function b() { throw new Error("foo") }
a()
// Error: foo
// at b (/path/to/snippets/q-longStack-after.js:5:22)
// From previous event:
// at a (/path/to/snippets/q-longStack-after.js:4:29)
// at Object.<anonymous> (/path/to/snippets/q-longStack-after.js:7:1)
|
goog.provide('recoil.ui.widgets.table.LabelColumn');
goog.require('recoil.frp.Behaviour');
goog.require('recoil.frp.struct');
goog.require('recoil.ui.BoolWithExplanation');
goog.require('recoil.ui.widgets.LabelWidget');
goog.require('recoil.ui.widgets.table.Column');
/**
* @implements {recoil.ui.widgets.table.Column}
* @template T
* @constructor
* @param {recoil.structs.table.ColumnKey} key
* @param {string|Node} name
* @param {(recoil.frp.Behaviour<Object>|Object)=} opt_meta
*/
recoil.ui.widgets.table.LabelColumn = function(key, name, opt_meta) {
this.key_ = key;
this.name_ = name;
this.options_ = opt_meta || {};
};
/**
* adds all the meta information that a column should need
* this should at least include cellWidgetFactory
* other meta data can include:
* headerDecorator
* cellDecorator
* and anything else specific to this column such as options for a combo box
*
* @param {Object} curMeta
* @return {Object}
*/
recoil.ui.widgets.table.LabelColumn.prototype.getMeta = function(curMeta) {
var meta = {name: this.name_,
cellWidgetFactory: recoil.ui.widgets.table.LabelColumn.defaultWidgetFactory_};
goog.object.extend(meta, this.options_, curMeta);
return meta;
};
/**
* @private
* @param {!recoil.ui.WidgetScope} scope
* @param {!recoil.frp.Behaviour<recoil.structs.table.TableCell>} cellB
* @return {!recoil.ui.Widget}
*/
recoil.ui.widgets.table.LabelColumn.defaultWidgetFactory_ =
function(scope, cellB)
{
var frp = scope.getFrp();
var widget = new recoil.ui.widgets.LabelWidget(scope);
var value = recoil.frp.table.TableCell.getValue(frp, cellB);
var metaData = recoil.frp.table.TableCell.getMeta(frp, cellB);
widget.attachStruct(recoil.frp.struct.extend(frp, metaData, {name: value}));
return widget;
};
/**
* @const
* @type {!Object}
*/
recoil.ui.widgets.table.LabelColumn.meta = {cellWidgetFactory: recoil.ui.widgets.table.LabelColumn.defaultWidgetFactory_};
/**
* @param {!recoil.ui.WidgetScope} scope
* @param {!recoil.frp.Behaviour<recoil.structs.table.TableCell>} cellB
* @return {!recoil.ui.Widget}
*/
recoil.ui.widgets.table.LabelColumn.defaultWidgetFactory = recoil.ui.widgets.table.LabelColumn.defaultWidgetFactory_;
/**
* @return {recoil.structs.table.ColumnKey}
*/
recoil.ui.widgets.table.LabelColumn.prototype.getKey = function() {
return this.key_;
};
|
var assert = require('assert');
describe('Array', function(){
describe('#indexOf()', function(){
it('should return -1 when the value is not present', function(){
assert.equal(-1, [1,2,3,4].indexOf(5));
});
});
});
|
var Location = function (jsonInFeed) {
var jsonContent = JSON.parse(jsonInFeed);
this.globalid = jsonContent.identifier[0].value;
this.name = jsonContent.name;
this.parentId = jsonContent.managingOrganization.reference;
this.fullName = function () {
var fullName = this.parent.fullName() + ', ' + this.name;
// FIXME: we shouldn't need this once Evan fixed RapidPro db restriction
if (fullName.length > 64) {
fullName = fullName.substring(0, 62) + '..';
}
return fullName;
};
this.groups = function () {
return [this.fullName()].concat(this.parent.groups());
};
};
Location.loadAll = function (url) {
var FeedReader = require(__dirname + '/feed-reader');
var feedReader = new FeedReader(Location, url);
return feedReader.loadAll();
};
module.exports = Location;
|
/**
* Created by jan on 20/10/14.
*/
function AccountManager() {
}
AccountManager.prototype.generateAmount = function () {
var s1 = Math.floor(Math.random() * 7) % 10;
var s2 = Math.floor(Math.random() * 7) % 10;
var s3 = Math.floor(Math.random() * 7) % 10;
var sum = s1 * 1000 + s2 * 100 + s3 * 10;
return sum;
}
AccountManager.prototype.generateAccount = function (accounts) {
var owners = (function (a) {
var o = [];
for (var i = 0; i < a.length; i++) {
o[i] = a[i].getOwner();
}
return o;
});
var _owners = function () {
return owners(accounts())
};
var owner = (new OwnerGenerator(_owners)).generateOwner();
var account = new Account(owner, this.generateAmount());
(accounts())[accounts().length] = account;
return account;
}
AccountManager.prototype.donateRandomToAllAccounts = function (accounts) {
var allAccounts = accounts();
for (var i = 0; i < allAccounts.length; i++) {
//We will donate only to active accounts
if (allAccounts[i].isActive())
allAccounts[i].add(this.generateAmount());
}
}
|
// increment the number below each time you push a new model version
// (forces rebuild on phone)
var current_migration_version = 1;
// create the tables if required
joli.models.migrate(current_migration_version);
joli.models.initialize();
|
import { newRxTypeError, newRxError } from '../../rx-error';
import { getPreviousVersions } from '../../rx-schema';
/**
* checks if the migrationStrategies are ok, throws if not
* @throws {Error|TypeError} if not ok
*/
export function checkMigrationStrategies(schema, migrationStrategies) {
// migrationStrategies must be object not array
if (typeof migrationStrategies !== 'object' || Array.isArray(migrationStrategies)) {
throw newRxTypeError('COL11', {
schema: schema
});
}
var previousVersions = getPreviousVersions(schema); // for every previousVersion there must be strategy
if (previousVersions.length !== Object.keys(migrationStrategies).length) {
throw newRxError('COL12', {
have: Object.keys(migrationStrategies),
should: previousVersions
});
} // every strategy must have number as property and be a function
previousVersions.map(function (vNr) {
return {
v: vNr,
s: migrationStrategies[vNr + 1]
};
}).filter(function (strat) {
return typeof strat.s !== 'function';
}).forEach(function (strat) {
throw newRxTypeError('COL13', {
version: strat.v,
type: typeof strat,
schema: schema
});
});
return true;
}
//# sourceMappingURL=check-migration-strategies.js.map
|
Template.favoritesPages.onCreated(function () {
var template = this;
template.subscribe('FavoritesPages');
});
Template.favoritesPages.helpers({
favoritesPages: function () {
if (Meteor.userId()) {
return Pages.find(
{ $or: [{ isPublic: true }, { owners: Meteor.userId() }, { users: Meteor.userId() }], favorites: Meteor.userId() },
{ sort: { updatedAt: -1 } }
);
}
}
});
Template.favoritesPages.events({
});
Template.favoritesPages.onRendered(function () {
});
|
'use strict';
/**
* @ngdoc object
* @name activityApp
* @requires $routeProvider
* @requires activityControllers
* @requires ui.bootstrap
*
* @description
* Root app, which routes and specifies the partial html and controller depending on the url requested.
*
*/
var app = angular.module('activityApp',
['activityControllers', 'ngRoute', 'ui.bootstrap', 'ui.bootstrap.datetimepicker']).
config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/activity', {
templateUrl: '/partials/show_activities.html',
controller: 'ShowActivityCtrl'
}).
when('/activity/create', {
templateUrl: '/partials/create_activities.html',
controller: 'CreateActivityCtrl'
}).
when('/activity/detail/:websafeActivityKey', {
templateUrl: '/partials/activity_detail.html',
controller: 'ActivityDetailCtrl'
}).
when('/profile', {
templateUrl: '/partials/profile.html',
controller: 'MyProfileCtrl'
}).
when('/', {
templateUrl: '/partials/home.html'
}).
otherwise({
redirectTo: '/'
});
}]);
/**
* @ngdoc filter
* @name startFrom
*
* @description
* A filter that extracts an array from the specific index.
*
*/
app.filter('startFrom', function () {
/**
* Extracts an array from the specific index.
*
* @param {Array} data
* @param {Integer} start
* @returns {Array|*}
*/
var filter = function (data, start) {
return data.slice(start);
}
return filter;
});
/**
* @ngdoc constant
* @name HTTP_ERRORS
*
* @description
* Holds the constants that represent HTTP error codes.
*
*/
app.constant('HTTP_ERRORS', {
'UNAUTHORIZED': 401
});
/**
* @ngdoc service
* @name oauth2Provider
*
* @description
* Service that holds the OAuth2 information shared across all the pages.
*
*/
app.factory('oauth2Provider', function ($modal) {
var oauth2Provider = {
CLIENT_ID: '411586073540-cq6ialm9aojdtjts6f12bb68up7k04t1.apps.googleusercontent.com',
SCOPES: 'https://www.googleapis.com/auth/userinfo.email profile',
signedIn: false
};
/**
* Calls the OAuth2 authentication method.
*/
oauth2Provider.signIn = function (callback) {
gapi.auth.signIn({
'clientid': oauth2Provider.CLIENT_ID,
'cookiepolicy': 'single_host_origin',
'accesstype': 'online',
'approveprompt': 'auto',
'scope': oauth2Provider.SCOPES,
'callback': callback
});
};
/**
* Logs out the user.
*/
oauth2Provider.signOut = function () {
gapi.auth.signOut();
// Explicitly set the invalid access token in order to make the API calls fail.
gapi.auth.setToken({access_token: ''});
oauth2Provider.signedIn = false;
};
/**
* Shows the modal with Google+ sign in button.
*
* @returns {*|Window}
*/
oauth2Provider.showLoginModal = function() {
var modalInstance = $modal.open({
templateUrl: '/partials/login.modal.html',
controller: 'OAuth2LoginModalCtrl'
});
return modalInstance;
};
return oauth2Provider;
});
|
/**
* Copyright (C) 2014 TopCoder Inc., All Rights Reserved.
* @version 1.1
* @author Sky_, TCSASSEMBLER
* changes in 1.1:
* 1. change handleError. Return sql error with unique constrains as Bad Request.
* 2. close db when request ends.
* 3. don't create transactions for GET requests
*/
"use strict";
var _ = require('underscore');
var async = require('async');
var winston = require('winston');
var BadRequestError = require("../errors/BadRequestError");
var IllegalArgumentError = require("../errors/IllegalArgumentError");
var NotFoundError = require("../errors/NotFoundError");
var initDb = require("../db");
/**
* Api codes
*/
var apiCodes = {
OK: { name: 'OK', value: 200, description: 'Success' },
notModified: { name: 'Not Modified', value: 304, description: 'There was no new data to return.' },
badRequest: { name: 'Bad Request', value: 400, description: 'The request was invalid. An accompanying message will explain why.' },
unauthorized: { name: 'Unauthorized', value: 401, description: 'Authentication credentials were missing or incorrect.' },
forbidden: { name: 'Forbidden', value: 403, description: 'The request is understood, but it has been refused or access is not allowed.' },
notFound: { name: 'Not Found', value: 404, description: 'The URI requested is invalid or the requested resource does not exist.' },
serverError: { name: 'Internal Server Error', value: 500, description: 'Something is broken. Please contact support.' }
};
/**
* Handle error and return as JSON to the response.
* @param {Error} error the error to handle
* @param {Object} res the express response object
*/
function handleError(error, res) {
var errdetail, baseError = apiCodes.serverError;
if (error.isValidationError ||
error instanceof IllegalArgumentError ||
error instanceof BadRequestError) {
baseError = apiCodes.badRequest;
} else if (error instanceof NotFoundError) {
baseError = apiCodes.notFound;
} else if (error.code === 'ER_DUP_ENTRY') {
baseError = apiCodes.badRequest;
if (error.message.indexOf("UC_c_sort") !== -1) {
error.message += ". Pair of the columns 'sort' and 'tab' must be unique.";
}
}
errdetail = _.clone(baseError);
errdetail.details = error.message;
res.statusCode = baseError.value;
res.json(errdetail);
}
/**
* This function create a delegate for the express action.
* Input and output logging is performed.
* Errors are handled also and proper http status code is set.
* Wrapped method must always call the callback function, first param is error, second param is object to return.
* @param {String} signature the signature of the method caller
* @param {Function} fn the express method to call. It must have signature (req, res, callback) or (req, callback). Res
* parameter is optional, because he is usually not used.
* @param {Boolean} customHandled true if the express action is handling the response.
* This is useful for downloading files. Wrapper will render only the error response.
* @returns {Function} the wrapped function
*/
function wrapExpress(signature, fn, customHandled) {
if (!_.isString(signature)) {
throw new Error("signature should be a string");
}
if (!_.isFunction(fn)) {
throw new Error("fn should be a function");
}
return function (req, res, next) {
var paramsToLog, db, transaction, apiResult, canRollback = false, useGlobalDB = req.method === 'GET';
paramsToLog = {
body: req.body,
params: req.params,
query : req.query,
url: req.url
};
winston.info("ENTER %s %j", signature, paramsToLog, {});
var disposeDB = function () {
if (useGlobalDB) {
return;
}
//close db connection
//we need this timeout because there is a bug for parallel requests
setTimeout(function () {
db.driver.close();
}, 1000);
};
async.waterfall([
function (cb) {
if (useGlobalDB) {
db = global.db;
cb();
} else {
async.waterfall([
function (cb) {
initDb(cb, false);
}, function (result, cb) {
db = result;
db.transaction(cb);
}, function (t, cb) {
transaction = t;
canRollback = true;
cb();
}
], cb);
}
}, function (cb) {
if (fn.length === 3) {
fn(req, db, cb);
} else {
fn(req, res, db, cb);
}
}, function (result, cb) {
apiResult = result;
if (useGlobalDB) {
cb();
} else {
transaction.commit(cb);
}
}, function (cb) {
if (process.env.NO_LOG_RESPONSE) {
paramsToLog.response = "<disabled>";
} else {
paramsToLog.response = apiResult;
}
winston.info("EXIT %s %j", signature, paramsToLog, {});
if (!customHandled) {
res.json(apiResult);
}
disposeDB();
}
], function (error) {
if (canRollback && transaction) {
transaction.rollback(function () {
});
}
disposeDB();
winston.error("EXIT %s %j\n", signature, paramsToLog, error.stack);
handleError(error, res);
});
};
}
module.exports = {
wrapExpress: wrapExpress,
apiCodes: apiCodes,
handleError: handleError
};
|
'use strict';
var mongoose = require('mongoose');
var mongoose_uuid = require('mongoose-uuid');
var mongoose_relationship = require('mongoose-relationship');
function tierModel () {
var tierSchema = mongoose.Schema({
environment: { type: String, ref: 'Environment', childPath: 'tiers', index: true },
platform: { type: String, ref: 'Platform', childPath: 'tiers', index: true },
machines: [{ type: String, ref: 'Machine' }],
cfpersonas: { type: String, ref: 'CfPersonas', index: true },
name: { type: String },
system_name: { type: String },
user_script: { type: String },
base_image: { type: String },
base_package: { type: String },
home_network: { type: String },
networks: [{ type: String }]
}, { _id: false, versionKey: false });
tierSchema.plugin(mongoose_uuid.plugin, 'Tier');
tierSchema.plugin(mongoose_relationship, {
relationshipPathName: [ 'environment', 'platform' ]
});
tierSchema.pre('save', function (next) {
var tier = this;
if (tier.system_name && tier.system_name.length > 0) {
next();
return;
}
tier.system_name = tier.name.toLowerCase().replace(/\s+/g, '_');
next();
});
return mongoose.model('Tier', tierSchema);
}
module.exports = new tierModel();
|
var gId = '#dataGrid';
var lastIndex;
$(document).ready(function(){
//列表
$(gId).datagrid({
url:getUrlOpt(),
idField:'id',
fitColumns:true,
frozenColumns:[[
{field:'ck',checkbox:true}
]],
columns:[
getTableHeadOpt(),
getColumnsOpt(),
getTotal()
],
rownumbers:true,
pagination:false,
loadMsg:'数据装载中......',
onClickRow:function(rowIndex){
if (lastIndex != rowIndex){
$(gId).datagrid('endEdit', lastIndex);
$(gId).datagrid('beginEdit', rowIndex);
}
lastIndex = rowIndex;
}
});
});
//计算总计
function getTotal()
{
var opt=[
{field:'totalSalesmoney',title:'出货金额总计',hidden:true,align:'left',formatter:totalFormat},
{field:'totalCostmoney',title:'成本金额总计',hidden:true,align:'left'},
{field:'totalOrderNum',title:'出货数量总计',hidden:true,align:'left'}
];
return opt;
}
//格式化总计
function totalFormat(value,rowData,rowIndex){
var totalSalesmoney = rowData.totalSalesmoney;
var totalCostmoney=rowData.totalCostmoney;
var totalOrderNum=rowData.totalOrderNum;
$("#num").html(totalOrderNum);
$("#sale").html(totalSalesmoney);
$("#cost").html(totalCostmoney);
return totalSalesmoney;
}
//获取表头参数
function getTableHeadOpt(){
var opt = [];
opt.push({title:'销售汇总报表',colspan:11});
return opt;
}
//获取列头参数
function getColumnsOpt(){
var opt = [
{field:'goodCode',title:'资料编号',width:15,align:'left'},
{field:'goodTypeName',title:'资料类别',width:10,align:'left'},
{field:'goodName',title:'资料名',width:30,align:'left'},
{field:'unit',title:'单位',width:10,align:'left'},
{field:'purchasePrice',title:'进货价',width:15,align:'left'},
{field:'goodPrice',title:'销售单价',width:15,align:'left'},
{field:'taxRate',title:'资料税率',width:15,align:'left'},
{field:'orderNumber',title:'销售数量',width:20,align:'left'},
{field:'taxDueSum',title:'销售税金',width:15,align:'left',formatter:taxDueSumFormat},
{field:'salesmoney',title:'不含税销售金额',width:20,align:'left'},
{field:'costmoney',title:'成本金额',width:20,align:'left'}
];
return opt;
}
//Json加载数据路径
function getUrlOpt(){
var url = ctx+'/Salesummary_json!listJson.do?1=1';
return url;
}
//搜索框检查用户是否按下‘回车键’,按下则调用搜索方法
function checkKey(){
if(event.keyCode=='13'){
searchData();
}
}
//格式化销售税金显示方式
function taxDueSumFormat(value,rowData,rowIndex){
var taxDueSum = rowData.taxDueSum;
if(taxDueSum){
taxDueSum = taxDueSum.toFixed(2);
}
return taxDueSum;
}
//搜索功能
function searchData(){
var goodTypeName = $('#goodTypeName').val();
var goodName = $('#goodName').val();
var begin = $('#begin').val();
var end = $('#end').val();
var brandName=$('#brandName').val();
var positionName=$('#warehousePositionName').val();
realoadGrid(goodTypeName,goodName,begin,end,brandName,positionName);
}
function cancelSearch(){
$('#goodTypeName').val('');
$('#goodName').val('');
$('#begin').val('');
$('#end').val('');
$('#brandName').val('');
$('#warehouseName').val('');
$('#warehousePositionName').val('');
searchData();
}
//确定搜索时重新加载datagrid
function realoadGrid(goodTypeName,goodName,begin,end,brandName,positionName){
var queryParams = $(gId).datagrid('options').queryParams;
queryParams={"saleWare.goodTypeName":goodTypeName,"saleWare.goodName":goodName,"saleWare.begin":begin,"saleWare.end":end,"saleWare.brandName":brandName,"saleWare.warehousePositionName":positionName};
$(gId).datagrid('options').queryParams = queryParams;
$(gId).datagrid('reload');
}
//仓库
function selectWarehouse(){
var warehouse = common.getWarehouse();
if(warehouse){
$('#warehouseId').val(warehouse.id);
$('#warehouseName').val(warehouse.name);
}
}
//选择仓库
function selectWarehousePosition(){
var warehouseName=$('#warehouseName').val();
if(warehouseName==null||warehouseName=='')
{
alert('请选择仓库');
}
else
{
WarehousePosition();
}
}
//仓位
function WarehousePosition(){
var warehousePosition = common.getWarehousePosition();
if(warehousePosition){
$('#warehousePositionName').val(warehousePosition.name);
}
}
//选择资料品牌
function selectBrand(obj){
var obj = $(obj);
var dataArr = window.showModalDialog(ctx+"/goodBrand!list.do?todo=show", '',"status:no;left:yes;scroll:yes;resizable:no;help:no;dialogWidth:800px;dialogHeight:600px");
if(dataArr!=null){
$(obj).val(dataArr.brandName);
$("#brandId").val(dataArr.brandId);
$(obj).focus();
}
}
//选择资料类别弹出窗
function selectType(obj){
var obj = $(obj);
var dataArr = window.showModalDialog(ctx+"/goodType!list.do?todo=show", '',"status:no;left:yes;scroll:yes;resizable:no;help:no;dialogWidth:800px;dialogHeight:600px");
if(dataArr!=null){
$(obj).val(dataArr.typeName);
$(obj).focus();
}
}
//重新加载
function reloadDataGrid(){
$(gId).datagrid('reload');
}
|
module.exports = require('./lib/SimpleNodeDb');
|
//// [tests/cases/compiler/importHelpersWithLocalCollisions.ts] ////
//// [a.ts]
declare var dec: any, __decorate: any;
@dec export class A {
}
const o = { a: 1 };
const y = { ...o };
//// [tslib.d.ts]
export declare function __extends(d: Function, b: Function): void;
export declare function __decorate(decorators: Function[], target: any, key?: string | symbol, desc?: any): any;
export declare function __param(paramIndex: number, decorator: Function): Function;
export declare function __metadata(metadataKey: any, metadataValue: any): Function;
export declare function __awaiter(thisArg: any, _arguments: any, P: Function, generator: Function): any;
//// [a.js]
define(["require", "exports", "tslib"], function (require, exports, tslib_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.A = void 0;
let A = class A {
};
A = (0, tslib_1.__decorate)([
dec
], A);
exports.A = A;
const o = { a: 1 };
const y = Object.assign({}, o);
});
|
new require('styles/dark')
module.exports = class extends require('base/app'){
prototype(){
this.tools = {
Rect:require('shaders/quad'),
Code: require('views/code').extend({
w:'100#',
h:'100%'
})
}
}
constructor(){
super()
//this.code = new this.Code(this, {text:require('/examples/tiny.js').__module__.source})
let code =
'var x=(1,2,)\n'
this.code = new this.Code(this, {text:code})
//this.code = new this.Code(this, {text:module.source})
//this.code = new this.Code(this, {text:'if(x){\n\t1+2\nif(t){\n}\n}'})
}
onDraw(){
/*this.drawRect({
w:100,
h:100,
color:'red'
})*/
this.code.draw(this)
}
}
|
/* global document */
import test from 'ava'
import { $ } from '../lib/traversal.js'
import { addClass, removeClass, css, chain } from '../lib/manipulation.js'
test.beforeEach(() => { document.body.innerHTML = '' })
/**
* addClass
*/
test('addClass', t => {
t.is(typeof addClass, 'function')
})
test('addClass adds a class to the list of an elements classes', t => {
document.body.innerHTML = `
<div id="element"></div>
`
const element = $('#element')
addClass(element, 'some-class')
t.is(element.className, 'some-class')
})
test('addClass adds a class to a given list of an elements classes', t => {
document.body.innerHTML = `
<div id="element" class="fubar"></div>
`
const element = $('#element')
addClass(element, 'some-class')
addClass(element, 'fubar')
t.is(element.className, 'fubar some-class')
})
/**
* removeClass
*/
test('removeClass', t => {
t.is(typeof removeClass, 'function')
})
test('removeClass removes a given class from the list of an elements classes', t => {
document.body.innerHTML = `
<div id="element" class="some-other fubar second"></div>
`
const element = $('#element')
removeClass(element, 'fubar')
t.is(element.className, 'some-other second')
removeClass(element, 'second')
removeClass(element, 'some-class')
t.is(element.className, 'some-other')
})
/**
* css
*/
test('css function is specified', t => {
t.is(typeof css, 'function')
})
test('css retrieves property values, if no value is set', t => {
document.body.innerHTML = `
<div id="element" style="display:inline"></div>
`
const element = $('#element')
t.is(css(element, 'display'), 'inline')
})
test('css resets property values, if empty string is given', t => {
document.body.innerHTML = `
<div id="element" style="display:inline"></div>
`
const element = $('#element')
css(element, 'display', '')
t.is(css(element, 'display'), 'block')
})
test('css sets property values, if an actual value is given', t => {
document.body.innerHTML = `
<div id="element" style="height:50px">Some Content</div>
`
const element = $('#element')
css(element, 'border', '1px solid red')
t.is(css(element, 'border'), '1px solid red')
css(element, 'height', 0)
t.is(css(element, 'height'), '0px')
})
/**
* chain
*/
test('chain function is specified', t => {
t.is(typeof chain, 'function')
})
test('chain returns an object, containing a set of curried functions for the given element', t => {
document.body.innerHTML = `
<div id="element" class="initial"></div>
`
const element = $('#element')
chain(element)
.addClass('changed')
.removeClass('initial')
t.is(element.className, 'changed')
})
|
var util = require('../../../utils/util.js');
var check = require('../../../utils/check.js');
var api = require('../../../config/api.js');
var app = getApp();
Page({
data: {
array: ['请选择反馈类型', '商品相关', '功能异常', '优化建议', '其他'],
index: 0,
content: '',
contentLength: 0,
mobile: '',
hasPicture: false,
picUrls: [],
files: []
},
chooseImage: function(e) {
if (this.data.files.length >= 5) {
util.showErrorToast('只能上传五张图片')
return false;
}
var that = this;
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function(res) {
that.setData({
files: that.data.files.concat(res.tempFilePaths)
});
that.upload(res);
}
})
},
upload: function(res) {
var that = this;
const uploadTask = wx.uploadFile({
url: api.StorageUpload,
filePath: res.tempFilePaths[0],
name: 'file',
success: function(res) {
var _res = JSON.parse(res.data);
if (_res.errno === 0) {
var url = _res.data.url
that.data.picUrls.push(url)
that.setData({
hasPicture: true,
picUrls: that.data.picUrls
})
}
},
fail: function(e) {
wx.showModal({
title: '错误',
content: '上传失败',
showCancel: false
})
},
})
uploadTask.onProgressUpdate((res) => {
console.log('上传进度', res.progress)
console.log('已经上传的数据长度', res.totalBytesSent)
console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
})
},
previewImage: function(e) {
wx.previewImage({
current: e.currentTarget.id, // 当前显示图片的http链接
urls: this.data.files // 需要预览的图片http链接列表
})
},
bindPickerChange: function(e) {
this.setData({
index: e.detail.value
});
},
mobileInput: function(e) {
this.setData({
mobile: e.detail.value
});
},
contentInput: function(e) {
this.setData({
contentLength: e.detail.cursor,
content: e.detail.value,
});
},
clearMobile: function(e) {
this.setData({
mobile: ''
});
},
submitFeedback: function(e) {
if (!app.globalData.hasLogin) {
wx.navigateTo({
url: "/pages/auth/login/login"
});
}
let that = this;
if (that.data.index == 0) {
util.showErrorToast('请选择反馈类型');
return false;
}
if (that.data.content == '') {
util.showErrorToast('请输入反馈内容');
return false;
}
if (that.data.mobile == '') {
util.showErrorToast('请输入手机号码');
return false;
}
if (!check.isValidPhone(this.data.mobile)) {
this.setData({
mobile: ''
});
util.showErrorToast('请输入手机号码');
return false;
}
wx.showLoading({
title: '提交中...',
mask: true,
success: function() {
}
});
util.request(api.FeedbackAdd, {
mobile: that.data.mobile,
feedType: that.data.array[that.data.index],
content: that.data.content,
hasPicture: that.data.hasPicture,
picUrls: that.data.picUrls
}, 'POST').then(function(res) {
wx.hideLoading();
if (res.errno === 0) {
wx.showToast({
title: '感谢您的反馈!',
icon: 'success',
duration: 2000,
complete: function() {
that.setData({
index: 0,
content: '',
contentLength: 0,
mobile: '',
hasPicture: false,
picUrls: [],
files: []
});
}
});
} else {
util.showErrorToast(res.errmsg);
}
});
},
onLoad: function(options) {
},
onReady: function() {
},
onShow: function() {
},
onHide: function() {
// 页面隐藏
},
onUnload: function() {
// 页面关闭
}
})
|
define(
"dojo/cldr/nls/en-ie/gregorian", //begin v1.x content
{
"dateFormatItem-Md": "d/M",
"dateFormatItem-yMEd": "EEE, d/M/yyyy",
"timeFormat-full": "HH:mm:ss zzzz",
"timeFormat-medium": "HH:mm:ss",
"dateFormatItem-yyyyMMMM": "MMMM y",
"dateFormatItem-MEd": "E, d/M",
"dateFormat-medium": "d MMM y",
"dateFormatItem-MMdd": "dd/MM",
"dateFormatItem-yyyyMM": "MM/yyyy",
"dateFormat-full": "EEEE d MMMM y",
"timeFormat-long": "HH:mm:ss z",
"dayPeriods-format-wide-am": "a.m.",
"timeFormat-short": "HH:mm",
"dateFormat-short": "dd/MM/yyyy",
"dateFormatItem-MMMMd": "d MMMM",
"dayPeriods-format-wide-pm": "p.m.",
"dateFormat-long": "d MMMM y"
}
//end v1.x content
);
|
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company, L.P.
import path from 'path';
import fecha from 'fecha';
import lunr from 'lunr';
import GithubPostDAO from '../persistance/GithubPostDAO';
import PostDAO from '../persistance/PostDAO';
export function loadPosts () {
return new PostDAO().getAll();
}
export function getPostById (id) {
return new PostDAO().getById(id);
}
export function postsMonthMap (posts) {
return posts.reduce((postMap, post) => {
let monthLabel = fecha.format(
new Date(post.createdAt), 'MMMM, YYYY'
);
if (postMap.hasOwnProperty(monthLabel)) {
postMap[monthLabel].push(post);
} else {
postMap[monthLabel] = [post];
}
return postMap;
}, {});
}
export function filterPostsMapByMonth (postsByMonth, year, month) {
let monthLabel = fecha.format(
new Date(year, month - 1), 'MMMM, YYYY'
);
let archive = {};
if (monthLabel in postsByMonth) {
archive[monthLabel] = postsByMonth[monthLabel];
}
return archive;
}
export function buildSearchIndex (posts) {
const index = lunr(function () {
this.field('title', {boost: 10});
this.field('author', {boost: 2});
this.field('content', {boost: 5});
this.field('tags');
this.ref('id');
});
posts.forEach((post) => index.add(post));
return index;
}
export function addPost (content, metadata, images) {
const titleId = metadata.title
.replace(/ /g, '-').replace(/[^a-zA-Z0-9\-]/g, '').toLowerCase();
const today = new Date();
const idDateFormat = fecha.format(today, 'YYYY/MM/DD');
const folderDateFormat = fecha.format(today, 'YYYY-MM-DD');
metadata.id = `${idDateFormat}/${titleId}`;
metadata.createdAt = today;
const postFolderName = `${folderDateFormat}__${titleId}`;
if (process.env.BLOG_PERSISTANCE === 'github') {
return new GithubPostDAO(postFolderName, content, metadata, images).add();
} else {
return new PostDAO(postFolderName, content, metadata, images).add(
path.resolve(path.join(__dirname, '../../'))
);
}
}
export function editPost (content, metadata, images) {
const titleId = metadata.title
.replace(/ /g, '-').replace(/[^a-zA-Z0-9\-]/g, '').toLowerCase();
const folderDateFormat = fecha.format(
new Date(metadata.createdAt), 'YYYY-MM-DD'
);
const postFolderName = `${folderDateFormat}__${titleId}`;
if (process.env.BLOG_PERSISTANCE === 'github') {
return new GithubPostDAO(postFolderName, content, metadata, images).edit();
} else {
return new PostDAO(postFolderName, content, metadata, images).edit(
path.resolve(path.join(__dirname, '../../'))
);
}
}
function getPostFolderName (id) {
const idGroup = id.split('/');
const postTitle = idGroup[idGroup.length - 1];
idGroup.pop();
const postDate = idGroup.join('-');
return `${postDate}__${postTitle}`;
}
export function deletePost (id) {
const postFolderName = getPostFolderName(id);
if (process.env.BLOG_PERSISTANCE === 'github') {
return new GithubPostDAO(postFolderName).delete();
} else {
return new PostDAO(postFolderName).delete(
path.resolve(path.join(__dirname, '../../'))
);
}
}
export function getAllPosts () {
return new GithubPostDAO().getAll();
}
export function cancelChange (post) {
const titleId = post.title
.replace(/ /g, '-').replace(/[^a-zA-Z0-9\-]/g, '').toLowerCase();
const folderDateFormat = fecha.format(
new Date(post.createdAt), 'YYYY-MM-DD'
);
const postFolderName = `${folderDateFormat}__${titleId}`;
return new GithubPostDAO(postFolderName).cancelChange(post.action);
}
export function getPendingPost (id) {
const postFolderName = getPostFolderName(id);
return new GithubPostDAO(postFolderName).getPending();
}
export function getImageAsBase64 (imagePath) {
const postPath = imagePath.split('server/posts/')[1];
const postFolderGroup = postPath.split('/images/');
const postFolderName = postFolderGroup[0];
const imageName = decodeURI(postFolderGroup[1]);
return new GithubPostDAO(postFolderName).getImageAsBase64(imageName);
}
|
/* Copyright 2014 Open Ag Data Alliance
*
* 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';
var debug = require('debug-logger')('oada-error');
var codes = {
OK: 200,
CREATED: 201,
NO_CONTENT: 204,
PARTIAL_CONTENT: 206,
MOVED_PERMANENTLY: 301,
NOT_MODIFIED: 304,
TEMPORARY_REDIRECT: 307,
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404,
NOT_ACCEPTABLE: 406,
CONFLICT: 409,
LENGTH_REQUIRED: 411,
PRECONDITION_FAILED: 412,
UNSUPPORTED_MEDIA_TYPE: 415,
REQUESTED_RANGE_NOT_SATISFIABLE: 416,
TOO_MANY_REQUESTS: 429,
INTERNAL_ERROR: 500,
};
module.exports.codes = codes;
var names = {
200: 'OK',
201: 'Created',
204: 'No Content',
206: 'Partial Content',
301: 'Moved Permanently',
304: 'Not Modified',
307: 'Temporary Redirect',
400: 'Bad Request',
401: 'Unauthorized',
403: 'Forbidden',
404: 'Not Found',
406: 'Not Acceptable',
409: 'Conflict',
411: 'Length Required',
412: 'Precondition Failed',
415: 'Unsupported Media Type',
416: 'Requested Range Not Satisfiable',
429: 'Too Many Requests',
500: 'Internal Error',
};
function OADAError(message, code, userMessage, href, detail) {
var error = Error.apply(null, arguments);
// Copy Error's properties
var self = this;
Object.getOwnPropertyNames(error).forEach(function(propertyName) {
Object.defineProperty(self, propertyName,
Object.getOwnPropertyDescriptor(error, propertyName));
});
// Convert named code to numeric code
if (isNaN(parseFloat(code))) {
this.code = codes[code];
} else {
this.code = code;
}
// Make sure code is OADA compliant
if (!names[code]) {
this.code = codes['INTERNAL_ERROR'];
}
this.status = names[this.code];
Object.defineProperty(this, 'message', {
configurable: true,
enumerable: false,
value: this.message || message || '',
writable: true
});
Object.defineProperty(this, 'type', {
configurable: true,
enumerable: false,
value: 'OADAError',
writable: true
});
this.title = this.message;
this.href = href || 'https://github.com/OADA/oada-docs';
if (detail) {
this.detail = detail;
}
this.userMessage = userMessage ||
'Unexpected error. Please try again or contact support.';
}
OADAError.prototype = Object.create(Error.prototype);
OADAError.prototype.name = 'OADAError';
OADAError.codes = codes;
module.exports.OADAError = OADAError;
function middleware(cb) {
return function(err, req, res, next) {
debug.trace('**** OADAError: ',err);
if (err.name === 'Error') {
debug.error(err);
// Don't expose interal error to client
err = new OADAError('Unexpected Error', codes.INTERNAL_ERROR);
}
if (err.type !== 'OADAError') {
return next(err);
}
if (typeof cb === 'function') {
cb(err);
}
debug.error('OADAError: ' + err);
res.status(err.code).json(err);
};
}
module.exports.middleware = middleware;
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app';
ReactDOM.render(<App />, document.getElementById('main'));
|
ConstructIndex(); //non ui
for(let B of Bakteriler) {
AddBacteriaToDisplay(B);//sadece isimler ve aileler //only ui with variables
BakteriRouterSearch(B); //non ui +
}
ConstructBottomPanel(); //only ui with variables
IndexFamilies(); //non ui
PremakeLeftPanel(); //only ui
if(HaveNotification) {
document.querySelector("#notificationCircle").style.display = "block";
}
FilterRuleQueExec(); //sayi vs icin //non ui
//asd
//SozlukBuilderStart();
|
'use strict';
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
debug: true,
context: path.join(__dirname, '/client'),
entry: {
app: './index.js',
},
output: {
path: path.join(__dirname, 'public'),
hash: true,
filename: '[name]-[hash].js',
sourceMapFilename: '[file].map',
},
devtool: '#source-map',
module: {
loaders: [
{
test: /\.css$/i,
loader: 'style!css!autoprefixer',
},
{
test: /\.js(x)?$/i,
exclude: /node_modules/,
loader: 'babel',
},
{
test: /\.(png|jpg|jpeg|gif)$/i,
loader: 'file?name=[path][name]-[sha512:hash:hex:7].[ext]',
},
],
},
resolve: {
extensions: ['', '.js', '.jsx'],
},
plugins: [
new HtmlWebpackPlugin({
title: 'Mochi',
favicon: './assets/favicon.ico',
chunks: ['app'],
inject: false,
template: './index-template.html',
}),
new CleanWebpackPlugin(['public'], {
root: __dirname,
verbose: true,
}),
],
};
|
/*global QUnit*/
sap.ui.define([
"sap/ui/test/opaQunit",
"./pages/Home",
"./pages/Overview"
], function (opaTest) {
"use strict";
QUnit.module("Home");
opaTest("Should see the homepage displayed", function (Given, When, Then) {
// Arrangements
Given.iStartMyApp({
hash: ""
});
// Assertions
Then.onTheHomePage.iShouldSeeSomeFontTiles();
});
opaTest("Should navigate to SAP icon TNT", function (Given, When, Then) {
// Actions
When.onTheHomePage.iClickOnTheTNTTitleLink();
// Assertions
Then.onTheOverviewPage.iShouldSeeTheTNTFontPage();
});
opaTest("Should be on the Home page when back button is pressed", function (Given, When, Then) {
//Actions
When.onTheOverviewPage.iPressTheNavigationBackButton();
// Assertions
Then.onTheHomePage.iShouldSeeSomeFontTiles();
// Cleanup
Then.iTeardownMyApp();
});
});
|
define(['backbone', 'collections/players', 'views/player'], function(Backbone, PlayersCollection, PlayerView) {
return Backbone.View.extend({
tagName: 'table',
className: 'table table-striped',
template: _.template($('#players-view').html()),
initialize: function() {
this.collection = new PlayersCollection();
this.listenTo(this.collection, 'reset', this.render);
this.collection.fetch({reset: true});
},
render: function () {
this.$el.html(this.template());
this.$tbody = this.$el.find('tbody');
this.$tbody.empty();
this.collection.each(this.renderOne, this);
return this;
},
renderOne: function (player) {
var view = new PlayerView({model: player});
this.$tbody.append(view.render().el);
}
});
});
|
/*
* Copyright 2015 Concept
*
* 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.
*/
/**
* SEO configuration for EvaluationCriteria route
*/
Meteor.startup(function() {
SeoCollection.update({
route_name: 'EvaluationCriteria'
},
{
$set: {
route_name: 'EvaluationCriteria',
title: 'Evalueringskriterier',
meta: {
'description': 'Etterevaluering av en rekke statlige prosjekter gjort av Concept-programmet. På oppdrag fra Finansdepartementet'
},
og: {
'title': 'Evalueringskriterier',
'image': '/images/logo.jpg'
}
}
},
{
upsert: true
});
});
|
/**
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const ISO6391 = require('iso-639-1');
module.exports = eleventy => {
// Transforms given date string into local date string
// Requires full-icu and NODE_ICU_DATA=node_modules/full-icu to function
eleventy.addFilter('date', (date, locale = 'en-US', format = {}) => new Date(date).toLocaleDateString(locale, format));
// Transforms given URL into a URL for the given locale
eleventy.addFilter('localeURL', (url, locale) => {
const changed = url.split('/');
if (changed[changed.length - 1] === '') {
changed.splice(-1, 1);
}
changed.splice(1, 1, locale);
return changed.join('/');
});
// Returns the native name for the language code
eleventy.addFilter('langName', code => ISO6391.getNativeName(code));
};
|
/* eslint prefer-arrow-callback: 0, func-names: 0, 'react/jsx-filename-extension': [1, { "extensions": [".js", ".jsx"] }] */
import React from 'react';
import assert from 'assert';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import DisplayNameSlugEditor from '../partials/display-name-slug-editor';
import CollectionSettings from './settings';
import Thumbnail from '../components/thumbnail';
const collectionWithDefaultSubject = {
id: '1',
default_subject_src: 'subject.png',
display_name: 'A collection',
private: false,
slug: 'username/a-collection'
};
const collectionWithoutDefaultSubject = {
id: '1',
display_name: 'A collection',
private: false,
slug: 'username/a-collection'
};
describe('<CollectionSettings />', function () {
let wrapper;
let confirmationSpy;
let deleteButton;
let handleDescriptionInputChangeStub;
before(function () {
confirmationSpy = sinon.spy(CollectionSettings.prototype, 'confirmDelete');
handleDescriptionInputChangeStub = sinon.stub(CollectionSettings.prototype, 'handleDescriptionInputChange');
wrapper = shallow(<CollectionSettings
canCollaborate={true}
collection={collectionWithoutDefaultSubject}
/>,
{ context: { router: {}}}
);
deleteButton = wrapper.find('button.error');
});
it('should render without crashing', function () {
assert.equal(wrapper, wrapper);
});
it('should render a <DisplayNameSlugEditor /> component', function () {
assert.equal(wrapper.find(DisplayNameSlugEditor).length, 1);
});
it('should render the correct default checked attribute for visibility', function () {
const privateChecked = wrapper.find('input[type="radio"]').first().props().defaultChecked;
const publicChecked = wrapper.find('input[type="radio"]').last().props().defaultChecked;
assert.equal(privateChecked, collectionWithoutDefaultSubject.private);
assert.notEqual(publicChecked, collectionWithoutDefaultSubject.private);
});
it('should render the thumbnail correctly depending on presence of default_subject_src', function () {
const thumbnailFirstInstance = wrapper.find(Thumbnail);
assert.equal(thumbnailFirstInstance.length, 0);
wrapper.setProps({ collection: collectionWithDefaultSubject });
const thumbnailSecondInstance = wrapper.find(Thumbnail);
assert.equal(thumbnailSecondInstance.length, 1);
});
it('should call this.handleDescriptionInputChange() when a user changes description text', function () {
wrapper.find('textarea').simulate('change');
sinon.assert.calledOnce(handleDescriptionInputChangeStub);
});
it('should render permission messaging if there is no user', function () {
wrapper.setProps({ canCollaborate: false, user: null });
const permissionMessage = wrapper.contains(<p>Not allowed to edit this collection</p>);
assert(permissionMessage, true);
});
it('should call this.confirmDelete() when the delete button is clicked', function () {
deleteButton.simulate('click');
sinon.assert.calledOnce(confirmationSpy);
});
});
|
var path = require('path');
var fs = require('fs')
var http = require('http')
var url = require('url')
var mime = require('./mime').types
var config = require("./config");
var zlib = require("zlib")
var utils = require("./utils")
var port = 8089;
var server = http.createServer(function(request, response){
var pathname = url.parse(request.url).pathname;
var realpath = path.join("assets", path.normalize(pathname.replace(/\.\./g, "")))
var ext = path.extname(realpath)
ext = ext ? ext.slice(1):"unknown"
var contentType = mime[ext] || "text/plain"
fs.exists(realpath, function(exists) {
if (!exists) {
response.writeHead(404, {
'Content-Type': 'text/plain'
})
response.write("This request URL " + pathname + "was not found on this server");
response.end();
} else {
response.setHeader("Content-Type",contentType);
var stats = fs.statSync(realpath);
if (request.headers["range"]) {
var range = utils.parseRange(request.headers["range"], stats.size);
if (range) {
response.setHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + stats.size);
response.setHeader("Content-Length", (range.end - range.start + 1));
var stream = fs.createReadStream(realpath, {
"start": range.start,
"end": range.end
});
response.writeHead('206', "Partial Content");
stream.pipe(response);
} else {
response.removeHeader("Content-Length");
response.writeHead(416, "Request Range Not Satisfiable");
response.end();
}
} else {
var stream = fs.createReadStream(realpath);
response.writeHead('200', "Partial Content");
stream.pipe(response);
}
}
})
})
server.listen(port)
|
import React, {
Component
} from 'react';
class ProjectItem extends Component {
render() {
return ( <
li className = "Project" >
<
strong > {
this.props.project.title
} < /strong> - {this.props.project.category} < /
li >
);
}
}
export default ProjectItem;
|
import Collection from './collection';
import extend from '../utils/extend';
export default function Grouping(key, elements) {
this.key = key;
this.elements = elements;
Collection.call(this, elements);
}
extend(Grouping, Collection, {
/**
* Gets the number of elements in the Grouping.
* @returns {Number}
*/
count: function () {
return this.elements.length;
},
/**
* Creates an array from the Grouping.
* @returns {Array}
*/
toArray: function () {
return this.elements;
},
toString: function () {
return '[Grouping]';
}
});
|
define(function(require) {
/*
DEPENDENCIES
*/
var BaseDialog = require('utils/dialogs/dialog');
var TemplateHTML = require('hbs!./clone/html');
var Sunstone = require('sunstone');
var Notifier = require('utils/notifier');
var Locale = require('utils/locale');
var OpenNebulaSecurityGroup = require('opennebula/securitygroup');
/*
CONSTANTS
*/
var DIALOG_ID = require('./clone/dialogId');
var TAB_ID = require('../tabId');
/*
CONSTRUCTOR
*/
function Dialog() {
this.dialogId = DIALOG_ID;
BaseDialog.call(this);
}
Dialog.DIALOG_ID = DIALOG_ID;
Dialog.prototype = Object.create(BaseDialog.prototype);
Dialog.prototype.constructor = Dialog;
Dialog.prototype.html = _html;
Dialog.prototype.onShow = _onShow;
Dialog.prototype.setup = _setup;
return Dialog;
/*
FUNCTION DEFINITIONS
*/
function _html() {
return TemplateHTML({
'dialogId': this.dialogId
});
}
function _setup(context) {
var that = this;
context.off('invalid.fndtn.abide', '#' + DIALOG_ID + 'Form');
context.off('valid.fndtn.abide', '#' + DIALOG_ID + 'Form');
context.on('invalid.fndtn.abide', '#' + DIALOG_ID + 'Form', function(e) {
// Fix for valid event firing twice
if (e.namespace != 'abide.fndtn') { return; }
Notifier.notifyError(Locale.tr("One or more required fields are missing or malformed."));
}).on('valid.fndtn.abide', '#' + DIALOG_ID + 'Form', function(e) {
// Fix for valid event firing twice
if (e.namespace != 'abide.fndtn') { return; }
var name = $('input', this).val();
var sel_elems = Sunstone.getDataTable(TAB_ID).elements();
if (sel_elems.length > 1){
for (var i=0; i< sel_elems.length; i++)
//use name as prefix if several items selected
Sunstone.runAction('SecurityGroup.clone',
sel_elems[i],
name + OpenNebulaSecurityGroup.getName(sel_elems[i]));
} else {
Sunstone.runAction('SecurityGroup.clone',sel_elems[0],name);
}
return false;
});
context.foundation('reflow', 'abide');
return false;
}
function _onShow(context) {
var sel_elems = Sunstone.getDataTable(TAB_ID).elements();
//show different text depending on how many elements are selected
if (sel_elems.length > 1) {
$('.clone_one', context).hide();
$('.clone_several', context).show();
$('input',context).val('Copy of ');
} else {
$('.clone_one', context).show();
$('.clone_several', context).hide();
$('input',context).val('Copy of ' + OpenNebulaSecurityGroup.getName(sel_elems[0]));
}
$("input[name='name']",context).focus();
return false;
}
});
|
/*
Siesta 3.0.1
Copyright(c) 2009-2015 Bryntum AB
http://bryntum.com/contact
http://bryntum.com/products/siesta/license
*/
/**
@class Siesta.Harness.NodeJS
@extends Siesta.Harness
Class, representing the NodeJS harness. This class reports the output from all test files to console.
This file is a reference only however, for a getting start guide and manual, please refer to <a href="#!/guide/siesta_getting_started">Getting Started Guide</a>.
Synopsys
========
var Harness,
isNode = typeof process != 'undefined' && process.pid
if (isNode) {
Harness = require('siesta');
} else {
Harness = Siesta.Harness.Browser;
}
Harness.configure({
title : 'Awesome Test Suite',
transparentEx : true,
autoCheckGlobals : true,
expectedGlobals : [
'Ext',
'Sch'
],
preload : [
"http://cdn.sencha.io/ext-4.0.2a/ext-all-debug.js",
"../awesome-project-all.js",
{
text : "console.log('preload completed')"
}
]
})
Harness.start(
// simple string - url relative to harness file
'sanity.t.js',
// test file descriptor with own configuration options
{
url : 'basic.t.js',
// replace `preload` option of harness
preload : [
"http://cdn.sencha.io/ext-4.0.6/ext-all-debug.js",
"../awesome-project-all.js"
]
},
// groups ("folders") of test files (possibly with own options)
{
group : 'Sanity',
autoCheckGlobals : false,
items : [
'data/crud.t.js',
...
]
},
...
)
Running the test suite in NodeJS
================================
To run the suite in NodeJS, launch the harness javascript file:
> node t/index.js
*/
Class('Siesta.Harness.NodeJS', {
// static
my : {
isa : Siesta.Harness,
does : Siesta.Role.ConsoleReporter,
has : {
contentManagerClass : Siesta.Content.Manager.NodeJS,
scopeProvider : 'Scope.Provider.NodeJS',
chdirToIndex : true
},
before : {
start : function () {
this.runCore = 'sequential'
if (this.chdirToIndex) {
var indexFile = process.argv[1]
var path = require('path')
process.chdir(path.dirname(indexFile))
}
}
},
methods : {
log : console.log,
exit : process.exit,
getScopeProviderConfigFor : function (desc, launchId) {
var config = this.SUPER(desc, launchId)
config.sourceURL = desc.url
return config
},
normalizeURL : function (url) {
// ref to lib in current dist (no trailing `.js`)
if (!/\.js$/.test(url)) {
url = '../lib/' + url.replace(/\./g, '/') + '.js'
}
return url
}
}
}
//eof my
})
//eof Siesta.Harness.NodeJS
|
<script>
$(document).ready(function() {
$("#jobs_table").DataTable({
"ajax": {
'type': 'POST',
'url': "{{ url_for('api.jobs', query_str=query_str) }}",
},
"columns": [
{"data": "name"},
{"data": "last_build.status",
"defaultContent": "None"
},
{"data": "release",
"defaultContent": "None"
},
{"data": "last_build.timestamp",
"defaultContent": "None"
},
{"data": "name"},
{"data": "name"},
],
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
status = aData.last_build.status;
{% include "tables/color_result.js" -%}
columnDefs: [
{
targets:0,
render: function ( data, type, row, meta ) {
if(type === 'display'){
return $('<a>')
.attr('href', data)
.text(data)
.wrap('<div></div>')
.parent()
.html();
}
else { return data; }
}
},
{
targets:[1],
render: function ( data, type, row, meta ) {
data = '<a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '">' + row['last_build']['status'] + '</a>';
return data;
}
},
{
targets:4,
render: function ( data, type, row, meta ) {
if(type === 'display' && row[1] != 0 && (row['last_build']['status'] == 'SUCCESS' || row['last_build']['status'] == 'UNSTABLE')){
data = '<a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/testReport' + '">Tests</a>';
}
else {
data = 'No Tests';
}
return data;
}
},
{
targets:5,
render: function ( data, type, row, meta ) {
{% if current_user.is_anonymous %}
data = '<a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/consoleFull"><img src="{{ url_for('static', filename='images/terminal.png') }}">';
{% else %}
data = '<a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/consoleFull"><img src="{{ url_for('static', filename='images/terminal.png') }}"> <a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/build"><img src="{{ url_for('static' , filename='images/clock.png') }}"> <a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/configure"><img src="{{ url_for('static', filename='images/gear.png') }}"> ';
{% endif %}
return data;
}
}
],
processing: true,
search: { "regex": true },
"lengthChange": false,
deferRender: true,
});
});
</script>
|
define([
'backbone',
'models/comment'
], function(Backbone, model){
var Collection = Backbone.Collection.extend({
model: model,
url: '/api/1/comments'
});
return new Collection(init.comments);
});
|
var express = require('express');
var http = require('http');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var router = require('./server/router');
var morgan = require('morgan');
app.use(bodyParser.urlencoded({extended: true}));
// parse application/json
app.use(bodyParser.json());
app.use(methodOverride());
app.use(morgan('dev', { format: 'dev', immediate: true }));
app.use(router());
http.createServer(app).listen(9999, function() {
console.log('Server up: http://localhost:' + 9999);
});
|
'use strict';
/* eslint-disable max-len */
const { extend } = require('underscore');
const lifecycleManager = require('abacus-lifecycle-manager')();
const moment = require('abacus-moment');
const { createStatsReader } = require('abacus-test-helper');
const env = {
tokenSecret: 'secret',
tokenAlgorithm: 'HS256',
abacusClientId: 'abacus-collector-client-id',
abacusClientSecret: 'abacus-collector-client-secret',
retryCount: 3
};
const port = 9501;
const hourInMillis = 3600000;
// There may be a case where the test is run at the very last moment of the month
// and until the renewer starts up, we enter into the next month, which causes our tests
// to fail. In order to avoid such a scenario, we check if we are in the last hour of the month
// and we roll back the clock of the renewer through the `ABACUS_TIME_OFFSET` env variable
// to assure that tests work as expected.
const now = moment.now();
const isLastHourOfCurrentMonth = () =>
now >
moment
.utc(now)
.endOf('month')
.subtract(1, 'hour')
.valueOf() &&
now <=
moment
.utc(now)
.endOf('month')
.valueOf();
// Use value larger then the months' length in order to force renewer to start
// independently of current date (renewer starts working only if current date
// is before "start of month + slack")
const slack = '32D';
const getEnviornmentVars = (externalSystems) => ({
ABACUS_CLIENT_ID: env.abacusClientId,
ABACUS_CLIENT_SECRET: env.abacusClientSecret,
SECURED: 'true',
AUTH_SERVER: externalSystems.cloudController.url(),
API: externalSystems.cloudController.url(),
COLLECTOR: externalSystems.abacusCollector.url(),
JWTKEY: env.tokenSecret,
JWTALGO: env.tokenAlgorithm,
RETRIES: env.retryCount,
ABACUS_TIME_OFFSET: isLastHourOfCurrentMonth() ? -hourInMillis : 0,
SLACK: slack
});
module.exports = (customEnv) => ({
env,
readStats: createStatsReader({
port,
tokenSecret: env.tokenSecret
}),
start: (externalSystemsMocks) => {
externalSystemsMocks
.cloudController
.infoService
.returnUaaAddress(externalSystemsMocks.uaaServer.url());
const renewerEnv = extend({}, process.env, getEnviornmentVars(externalSystemsMocks), customEnv);
lifecycleManager.useEnv(renewerEnv).startModules([lifecycleManager.modules.renewer]);
},
stop: lifecycleManager.stopAllStarted
});
|
'use strict';
import React, {Component, PropTypes} from 'react';
import ReactNative, {View, Text} from 'react-native';
var Popover = require('../Popover');
var AutoHide = require('./AutoHide');
var ToptipAnimation = require('../Popover/PopoverAnimationVertical').create(
{onStartShouldSetResponder: () => false}
);
class Toptip extends AutoHide {
static propTypes = {
...AutoHide.propTypes,
text: PropTypes.string,
children: PropTypes.node,
type: PropTypes.oneOf(['success', 'warning', 'error', 'info']),
};
static contextTypes = {
uiTheme: PropTypes.object.isRequired,
};
render() {
const {
text,
duration,
type,
style,
children,
...other,
} = this.props;
const {toptip, spacing} = this.context.uiTheme;
const paddingTop = spacing.statusbarHeight;
const backgroundColor = toptip.backgroundColors[type];
const color = toptip.colors[type];
let content = children;
if(typeof text === 'string') {
content = (
<Text style={[styles.text, {color}]}>
{text}
</Text>
);
}
return (
<Popover
layerStyle={styles.layer}
{...other}
useLayerForClickAway={true}
animation={ToptipAnimation}
style={[styles.toptip, {backgroundColor, paddingTop}, style]}>
{content}
</Popover>
);
}
}
const styles = {
layer: {
right: 0,
},
toptip: {
alignSelf: 'stretch',
},
text: {
fontSize: 15,
padding: 10,
fontWeight: 'bold',
textAlign: 'center',
},
};
module.exports = Toptip;
|
import React from 'react';
import PropTypes from 'prop-types';
import FormField from '../../components/FormField';
import TextHelp from '../../components/TextHelp';
import DomainIdField from '../../components/DomainIdField';
import PodcastEdit from './PodcastEdit';
const LibraryFormContents = (props) => {
const { className, errors, formState, session } = props;
const library = formState.object;
let podcast;
if (library.podcast) {
const url = `${window.location.origin}/${library.path || library.id}.rss`;
podcast = [
<p key="loc" className="form__text secondary">
Published at: {url}<br />
<a href={`https://validator.w3.org/feed/check.cgi?url=${encodeURIComponent(url)}`}>
Test
</a> <a href="https://help.apple.com/itc/podcasts_connect/#/itcd88ea40b9">
Submit
</a>
</p>,
<PodcastEdit key="podcast"
podcast={library.podcast}
onChange={formState.change('podcast')} />,
];
}
return (
<div className={className}>
<fieldset className="form__fields">
<FormField label="Name" error={errors.name}>
<input name="name"
value={library.name || ''}
onChange={formState.change('name')} />
</FormField>
<FormField name="text" label="Description" help={<TextHelp />}>
<textarea name="text"
value={library.text || ''}
rows={4}
onChange={formState.change('text')} />
</FormField>
<FormField name="path"
label="Url ID"
help="unique url name"
error={errors.path}>
<input name="path"
value={library.path || ''}
onChange={formState.change('path')} />
</FormField>
<DomainIdField formState={formState} session={session} />
<FormField>
<input name="podcast"
type="checkbox"
checked={library.podcast}
onChange={() =>
formState.set('podcast', library.podcast ? undefined : {})} />
<label htmlFor="podcast">podcast</label>
</FormField>
</fieldset>
{podcast}
</div>
);
};
LibraryFormContents.propTypes = {
className: PropTypes.string,
errors: PropTypes.object,
formState: PropTypes.object.isRequired,
session: PropTypes.object.isRequired,
};
LibraryFormContents.defaultProps = {
className: undefined,
errors: {},
};
export default LibraryFormContents;
|
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel",
"sap/m/MessageToast"
], function (Controller, JSONModel, MessageToast) {
"use strict";
var TABLESETTINGS = window.TABLESETTINGS;
return Controller.extend("sap.ui.table.testApps.DragAndDrop", {
onInit: function () {
var oTable = this.byId("table");
var oTreeTable = this.byId("treetable");
var oModel = new JSONModel();
oModel.setData({
listData: TABLESETTINGS.listTestData,
treeData: TABLESETTINGS.treeTestData
});
oTable.setModel(oModel);
oTreeTable.setModel(oModel);
oTable.addExtension(new sap.m.Toolbar());
TABLESETTINGS.init(oTable, function(oButton) {
oTable.getExtension()[0].addContent(oButton);
});
oTreeTable.addExtension(new sap.m.Toolbar());
// TODO: Make table settings interoperable with multi table pages
//TABLESETTINGS.init(oTreeTable, function(oButton) {
// oTreeTable.getExtension()[0].addContent(oButton);
//});
window.oTable = oTable;
window.oTreeTable = oTreeTable;
},
tableDragStart: function(oEvent) {
var oRow = oEvent.getParameter("target");
var oRowContext = oRow.getBindingContext();
var oModelProperty = oRowContext.getModel().getProperty(oRowContext.getPath());
var sStatus = oModelProperty && oModelProperty.objStatusState != null ? oModelProperty.objStatusState : "";
if (sStatus !== "Success") {
oEvent.preventDefault();
}
this.showDragStartEventInfo(oEvent, "Table");
},
tableReorderDragEnter: function(oEvent) {
var oRow = oEvent.getParameter("target");
var oRowContext = oRow.getBindingContext();
var oModelProperty = oRowContext.getModel().getProperty(oRowContext.getPath());
var sStatus = oModelProperty && oModelProperty.objStatusState != null ? oModelProperty.objStatusState : "";
if (sStatus !== "Success") {
oEvent.preventDefault();
}
this.showDragEnterEventInfo(oEvent, "Table Reorder");
},
tableReorderDrop: function(oEvent) {
this.showDropEventInfo(oEvent, "Table Reorder");
},
tableToTreeTableDragEnter: function(oEvent) {
this.showDragEnterEventInfo(oEvent, "Table to TreeTable");
},
tableToTreeTableDrop: function(oEvent) {
this.showDropEventInfo(oEvent, "Table to TreeTable");
},
treeTableDragStart: function(oEvent) {
this.showDragStartEventInfo(oEvent, "TreeTable");
},
treeTableReorderDragEnter: function(oEvent) {
this.showDragEnterEventInfo(oEvent, "TreeTable Reorder");
},
treeTableReorderDrop: function(oEvent) {
this.showDropEventInfo(oEvent, "TreeTable Reorder");
},
treeTableToTableDragEnter: function(oEvent) {
this.showDragEnterEventInfo(oEvent, "TreeTable to Table");
},
treeTableToTableDrop: function(oEvent) {
this.showDropEventInfo(oEvent, "TreeTable to Table");
},
showDragStartEventInfo: function(oEvent, sTitle) {
sap.m.MessageToast.show(
sTitle + " (" + "DragStart parameters" + ")"
+ "\nDrag target: " + oEvent.getParameter("target").getId()
+ "\nDrag session: " + (oEvent.getParameter("dragSession") ? "available" : "not available")
+ "\nBrowser event: " + oEvent.getParameter("browserEvent").type,
{
width: "25rem"
}
);
},
showDragEnterEventInfo: function(oEvent, sTitle) {
sap.m.MessageToast.show(
sTitle + " (" + "DragEnter parameters" + ")"
+ "\nDrop target: " + oEvent.getParameter("target").getId()
+ "\nDrag session: " + (oEvent.getParameter("dragSession") ? "available" : "not available")
+ "\nBrowser event: " + oEvent.getParameter("browserEvent").type,
{
width: "25rem"
}
);
},
showDropEventInfo: function(oEvent, sTitle) {
sap.m.MessageToast.show(
sTitle + " (" + "Drop parameters" + ")"
+ "\nDragged control: " + oEvent.getParameter("draggedControl").getId()
+ "\nDropped control: " + oEvent.getParameter("droppedControl").getId()
+ "\nDrop position: " + oEvent.getParameter("dropPosition")
+ "\nDrag session: " + (oEvent.getParameter("dragSession") ? "available" : "not available")
+ "\nBrowser event: " + oEvent.getParameter("browserEvent").type,
{
duration: 8000,
width: "25rem"
}
);
},
getProgress: function(sValue) {
sValue = sValue || "";
return (sValue.length * 10) % 100;
},
getRating: function(sValue) {
sValue = sValue || "";
return sValue.length % 5;
}
});
});
|
/* global suite test internalScope */
(function () {
suite('offsetPath', function () {
test('basicShapeCircle', function () {
var assertTransformInterpolation = internalScope.assertTransformInterpolation;
assertTransformInterpolation([
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '0%'},
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '100%'}],
[
{at: 0, is: 'translate3d(0px, -10px, 0px)'},
{at: 0.25, is: 'translate3d(10px, 0px, 0px) rotate(90deg)'},
{at: 0.5, is: 'translate3d(0px, 10px, 0px) rotate(180deg)'},
{at: 0.75, is: 'translate3d(-10px, 0px, 0px) rotate(-90deg)'},
{at: 1, is: 'translate3d(0px, -10px, 0px)'}
]
);
assertTransformInterpolation([
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '0px'},
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '62.83px'}],
[
{at: 0, is: 'translate3d(0px, -10px, 0px)'},
{at: 0.25, is: 'translate3d(10px, 0px, 0px) rotate(89.45deg)'},
{at: 0.5, is: 'translate3d(0.01px, 10px, 0px) rotate(180deg)'},
{at: 0.75, is: 'translate3d(-10px, 0.01px, 0px) rotate(-90deg)'},
{at: 1, is: 'translate3d(-0.01px, -10px, 0px) rotate(-0.55deg)'}
]
);
assertTransformInterpolation([
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '0%'},
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '50%'}],
[
{at: 0, is: 'translate3d(0px, -10px, 0px)'},
{at: 0.5, is: 'translate3d(10px, 0px, 0px) rotate(90deg)'},
{at: 1, is: 'translate3d(0px, 10px, 0px) rotate(180deg)'}
]
);
assertTransformInterpolation([
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '0px'},
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '31.42px'}],
[
{at: 0, is: 'translate3d(0px, -10px, 0px)'},
{at: 0.5, is: 'translate3d(10px, 0px, 0px) rotate(90deg)'},
{at: 1, is: 'translate3d(0px, 10px, 0px) rotate(179.45deg)'}
]
);
assertTransformInterpolation([
{'offsetPath': 'circle(10px at 100px 100px)', 'offsetDistance': '0%'},
{'offsetPath': 'circle(10px at 100px 100px)', 'offsetDistance': '100%'}],
[
{at: 0, is: 'translate3d(100px, 90px, 0px)'},
{at: 0.25, is: 'translate3d(110px, 100px, 0px) rotate(90deg)'},
{at: 0.5, is: 'translate3d(100px, 110px, 0px) rotate(180deg)'},
{at: 0.75, is: 'translate3d(90px, 100px, 0px) rotate(-90deg)'},
{at: 1, is: 'translate3d(100px, 90px, 0px)'}
]
);
// TODO: Support path interpolation for basic shapes.
assertTransformInterpolation([
{'offsetPath': 'circle(0px at 100px 200px)', 'offsetDistance': '1000px', 'offsetRotate': '0deg', 'offsetAnchor': '50% 50%'},
{'offsetPath': 'circle(0px at 300px 400px)', 'offsetDistance': '1000px', 'offsetRotate': '0deg', 'offsetAnchor': '50% 50%'}],
[
{at: 0, is: 'translate3d(100px, 200px, 0px)'},
{at: 1, is: 'translate3d(300px, 400px, 0px)'}
]
);
});
});
})();
|
/*
* Copyright (C) 2014 Xillio (support@xillio.com)
*
* 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.
*/
|
//// [promiseIdentityWithAny2.ts]
interface IPromise<T, V> {
then<U, W>(callback: (x: T) => IPromise<U, W>): IPromise<U, W>;
}
interface Promise<T, V> {
then(callback: (x: T) => Promise<any, any>): Promise<any, any>;
}
// Error because type parameter arity doesn't match
var x: IPromise<string, number>;
var x: Promise<string, boolean>;
interface IPromise2<T, V> {
then<U, W>(callback: (x: T) => IPromise2<U, W>): IPromise2<U, W>;
}
interface Promise2<T, V> {
then<U, W>(callback: (x: T) => Promise2<string, any>): Promise2<any, any>; // Uses string instead of any!
}
// Error because string and any don't match
var y: IPromise2<string, number>;
var y: Promise2<string, boolean>;
//// [promiseIdentityWithAny2.js]
// Error because type parameter arity doesn't match
var x;
var x;
// Error because string and any don't match
var y;
var y;
|
'use strict';
/**
* Created by zhaoxueyong on 2017/1/14.
*/
angular.module('browserApp').
controller('ColuslifeCtrl', function ($scope, $http) {
$scope.countryName = "China";
var mapObj = null;
$scope.init_map = function(){
console.log("init map now");
mapObj = new AMap.Map("mapbody", {
level: 7,
building: false,
point: false
});
var marker = new AMap.Marker({
position: new AMap.LngLat(120.58, 31.335),
title: 'SuZhouLeYuan'
});
marker.setMap(mapObj);
};
$('#btnLocation').on("click", function(){
var locations = null;
if (null === locations){
$http({
method: 'GET',
url: 'http://127.0.0.1:8000/coluslife/locations',
timeout: 5
}).then(
function successCallback(response){
console.log(response.data);
locations = response.data;
for (var i = 0; i < locations.length; i++){
var loc = locations[i];
placeMarker(loc);
}
},
function errorCallback(error){
console.error(error);
});
}
});
var placeMarker = function(location){
var marker = new AMap.Marker({
position: new AMap.LngLat(location.fields.gislng, location.fields.gislat),
title: location.fields.name
});
marker.setMap(mapObj);
}
});
|
angular.module('n52.core.base')
.factory('styleService', ['$rootScope', 'settingsService', 'colorService', '$injector', "styleServiceStandalone",
function($rootScope, settingsService, colorService, $injector, styleServiceStandalone) {
var intervalList = settingsService.intervalList;
function createStylesInTs(ts) {
var styles, color, visible, selected, zeroScaled, groupedAxis;
if (!ts.styles) {
ts.styles = {};
}
color = ts.styles.color || ts.renderingHints && ts.renderingHints.properties.color || colorService.getColor(ts.id);
visible = true;
selected = false;
if (angular.isUndefined(ts.styles.zeroScaled)) {
zeroScaled = settingsService.defaultZeroScale;
}
if (angular.isUndefined(ts.styles.groupedAxis)) {
groupedAxis = settingsService.defaultGroupedAxis;
}
styles = styleServiceStandalone.createStyle(ts, color, zeroScaled, groupedAxis, selected, visible);
angular.merge(ts.styles, styles);
angular.forEach(ts.referenceValues, function(refValue) {
refValue.color = colorService.getRefColor(refValue.referenceValueId);
});
}
function deleteStyle(ts) {
colorService.removeColor(ts.styles.color);
angular.forEach(ts.referenceValues, function(refValue) {
colorService.removeRefColor(refValue.color);
});
}
function toggleSelection(ts) {
ts.styles.selected = !ts.styles.selected;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function setSelection(ts, selected, quiet) {
ts.styles.selected = selected;
if (!quiet) {
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
}
function toggleTimeseriesVisibility(ts) {
ts.styles.visible = !ts.styles.visible;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function updateColor(ts, color) {
ts.styles.color = color;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function updateZeroScaled(ts) {
ts.styles.zeroScaled = !ts.styles.zeroScaled;
if (ts.styles.groupedAxis) {
var tsSrv = $injector.get('timeseriesService');
angular.forEach(tsSrv.getAllTimeseries(), function(timeseries) {
if (timeseries.uom === ts.uom && timeseries.styles.groupedAxis) {
timeseries.styles.zeroScaled = ts.styles.zeroScaled;
}
});
}
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function updateGroupAxis(ts) {
ts.styles.groupedAxis = !ts.styles.groupedAxis;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function updateInterval(ts, interval) {
ts.renderingHints.properties.interval = interval.caption;
ts.renderingHints.properties.value = interval.value;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function notifyAllTimeseriesChanged() {
$rootScope.$emit('allTimeseriesChanged');
}
function triggerStyleUpdate(ts) {
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
return {
createStylesInTs: createStylesInTs,
deleteStyle: deleteStyle,
notifyAllTimeseriesChanged: notifyAllTimeseriesChanged,
toggleSelection: toggleSelection,
setSelection: setSelection,
toggleTimeseriesVisibility: toggleTimeseriesVisibility,
updateColor: updateColor,
updateZeroScaled: updateZeroScaled,
updateGroupAxis: updateGroupAxis,
updateInterval: updateInterval,
intervalList: intervalList,
triggerStyleUpdate: triggerStyleUpdate
};
}
]);
|
/**
* Slices arrays.
* @param array
* @param pos
* @returns {string}
*/
var arraySlicer = function (array, pos) {
return array.slice(0, pos).concat(array.slice(pos + 1, array.length));
};
/**
* https://en.wikipedia.org/wiki/Cosine_similarity
* https://en.wikipedia.org/wiki/Canberra_distance
* https://en.wikipedia.org/wiki/Sørensen–Dice_coefficient
* @param arr1
* @param arr2
* @returns {number}
*/
function distanceFunction(arr1, arr2) {
var INTERVAL = 70;
/*var sum1 = 0;
var sum2 = 0;
var sum3 = 0;
var canberra = 0;
var Czekanowski1 = 0;
var Czekanowski2 = 0;
*/
var intervalCount = 0;
for (var i = 0; i < arr1.length && i < arr2.length; i++) {
/*sum1 += arr1[i] * arr2[i];
sum2 += arr1[i] * arr1[i];
sum3 += arr2[i] * arr2[i];
canberra += Math.abs(arr1[i] - arr2[i]) / (arr1[i] + arr2[i]);
Czekanowski1 += (arr1[i] * arr2[i]);
Czekanowski2 += (arr1[i] * arr1[i] + arr2[i] * arr2[i]);
*/
if (Math.abs(arr1[i] - arr2[i]) > INTERVAL) {
intervalCount++;
}
}
/*var similarity = (sum1 / (Math.sqrt(sum2) * Math.sqrt(sum3)));
var distance = Math.acos(similarity) * 2 / Math.PI;
var Sørensen = (2 * Czekanowski1) / Czekanowski2;
return [similarity, distance, 1 - distance, 2 * sum1 / (sum2 + sum3), canberra, Sørensen, intervaledCount];
*/
return intervalCount;
}
function randInt(N) {
if (!N) N = Number.MAX_SAFE_INTEGER;
return Math.floor((Math.random() * Number.MAX_VALUE) % (Math.pow(10, N)));
}
if (typeof exports != "undefined") {
exports.distanceFunction = distanceFunction;
exports.randInt = randInt;
}
|
(function () {
'use strict';
var dccModul = angular.module('workinghours', ['dcc.controller', 'dcc.factories', 'dcc.filter', 'ngCookies', 'ngRoute']);
dccModul.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {
$routeProvider.when('/duration/new', {
templateUrl: '/partials/durationNew.html',
controller: 'DurationController'
});
$routeProvider.when('/duration/:id', {
templateUrl: '/partials/durationNew.html',
controller: 'DurationController'
});
$routeProvider.when('/login', {templateUrl: '/partials/login.html', controller: 'LoginController'});
$routeProvider.when('/adminoverview', {
templateUrl: '/partials/adminoverview.html',
controller: 'AdminOverviewController'
});
$routeProvider.when('/users/new', {templateUrl: '/partials/userNew.html', controller: 'NewUserController'});
$routeProvider.when('/checkin', {templateUrl: '/partials/checkIn.html', controller: 'CheckInController'});
$routeProvider.when('/changepassword', {
templateUrl: '/partials/changepassword.html',
controller: 'ChangePasswordController'
});
$routeProvider.otherwise({templateUrl: '/partials/overview.html', controller: 'OverviewController'});
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);
}());
|
/// <reference types="cypress" />
context('Waiting', () => {
beforeEach(() => {
cy.visit('https://example.cypress.io/commands/waiting')
})
// BE CAREFUL of adding unnecessary wait times.
// https://on.cypress.io/best-practices#Unnecessary-Waiting
// https://on.cypress.io/wait
it('cy.wait() - wait for a specific amount of time', () => {
cy.get('.wait-input1').type('Wait 1000ms after typing')
cy.wait(1000)
cy.get('.wait-input2').type('Wait 1000ms after typing')
cy.wait(1000)
cy.get('.wait-input3').type('Wait 1000ms after typing')
cy.wait(1000)
})
it('cy.wait() - wait for a specific route', () => {
cy.server()
// Listen to GET to comments/1
cy.route('GET', 'comments/*').as('getComment')
// we have code that gets a comment when
// the button is clicked in scripts.js
cy.get('.network-btn').click()
// wait for GET comments/1
cy.wait('@getComment').its('status').should('eq', 200)
})
})
|
webserver.prototype.__proto__ = require('events').EventEmitter.prototype;
webserver.prototype.server = null;
webserver.prototype.config = null;
webserver.prototype.endpoints = [];
const bodyParser = require('body-parser');
const express = require('express');
const multer = require('multer');
const formData = multer({ storage: multer.memoryStorage() });
const https = require('https');
const http = require('http');
const fs = require('fs');
/**
* Initalize a webserver with options such as SSL
* @param port
* @param options
*/
function webserver(logger, port, options) {
var self = this;
self.logger = logger;
self.port = port;
self.options = options;
self.app = express();
self.app.use(bodyParser.urlencoded({extended: true}));
self.app.set('json spaces', 2);
}
webserver.prototype.start = function (callback) {
var self = this;
if (self.HTTPserver != null && self.HTTPSserver != null)
return callback({Error: "Server is already active... Try restarting instead."});
if (self.HTTPSserver == null) {
try {
self.ssl = {};
if (self.options && self.options.hasOwnProperty("ssl")) {
// Create a service (the app object is just a callback).
// This line is from the Node.js HTTPS documentation.
if (self.options.ssl.hasOwnProperty("key") && self.options.ssl.hasOwnProperty("cert")) {
var options = {
key: self.options.ssl.key,
cert: self.options.ssl.cert
};
self.HTTPSserver = https.createServer(options, self.app).listen(443);// Create an HTTPS service identical to the HTTP service.
self.logger.log("debug", "Started SSL server on port 443.");
}
}
if (self.HTTPserver == null) {
try {
self.HTTPserver = http.createServer(self.app).listen(self.port);// Create an HTTP service.
self.logger.log("debug", "Started HTTP server on port " + self.port);
if (callback)
return callback();
} catch (e){
console.log(e);
if (callback)
return callback({Error: "Failed to start HTTP server due to " + e});
}
}
} catch (e){
console.log(e);
if (callback)
return callback({Error: "Failed to start HTTP server due to " + e});
}
} else if (self.HTTPserver == null) {
try {
self.ssl = {};
if (self.HTTPserver == null) {
try {
self.HTTPserver = http.createServer(self.app).listen(self.port);// Create an HTTP service.
self.logger.log("debug", "Started HTTP server on port " + self.port);
if (self.options && self.options.hasOwnProperty("ssl")) {
if (self.options.ssl.hasOwnProperty("key") && self.options.ssl.hasOwnProperty("cert")) {
var options = {
key: self.options.ssl.key,
cert: self.options.ssl.cert
};
self.HTTPSserver = https.createServer(options, self.app).listen(443);// Create an HTTPS service identical to the HTTP service.
self.logger.log("debug", "Started SSL server on port 443.");
}
}
} catch (e){
console.log(e);
if (callback)
return callback({Error: "Failed to start HTTP server due to " + e});
}
}
} catch (e){
console.log(e);
if (callback)
return callback({Error: "Failed to start HTTP server due to " + e});
}
}
};
webserver.prototype.addEndpoint = function (method, url, callback) {
var self = this;
self.endpoints.push({method: method, url: url, callback: callback});
switch (method.toLowerCase()) {
case 'post':
// console.log("Reg post...");
//
// var func = new Function(
// "return function " + method + "_" + url + "(req, res, next){ " +
// "console.log('Test' + self.app._router.stack);}"
// )();
self.app.post(url, formData.array(), callback);
break;
case 'get':
self.app.get(url, callback);
break;
default:
self.app.post(url, formData.array(), callback);
break;
}
};
webserver.prototype.removeEndpoint = function (method, url) {
var self = this;
console.log("Added route " + self.app._router.stack);
var routes = self.app._router.stack;
routes.forEach(removeMiddlewares);
function removeMiddlewares(route, i, routes) {
switch (route.handle.name) {
case method + "_" + url:
routes.splice(i, 1);
}
if (route.route)
route.route.stack.forEach(removeMiddlewares);
}
};
webserver.prototype.restart = function () {
var self = this;
if (self.HTTPSserver != null && self.HTTPserver != null) {
self.HTTPSserver.close();
self.HTTPserver.close();
for (var endpoint in self.endpoints)
if (self.endpoints.hasOwnProperty(endpoint))
self.addEndpoint(self.endpoints[endpoint].method, self.endpoints[endpoint].url, self.endpoints[endpoint].callback);
self.start();
}
};
module.exports = webserver;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.