text
stringlengths 2
6.14k
|
|---|
import { clone } from '../../utils/object.js'
import { format } from '../../utils/string.js'
import { factory } from '../../utils/factory.js'
const name = 'transpose'
const dependencies = ['typed', 'matrix']
export const createTranspose = /* #__PURE__ */ factory(name, dependencies, ({ typed, matrix }) => {
/**
* Transpose a matrix. All values of the matrix are reflected over its
* main diagonal. Only applicable to two dimensional matrices containing
* a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional
* vectors and scalars return the input unchanged.
*
* Syntax:
*
* math.transpose(x)
*
* Examples:
*
* const A = [[1, 2, 3], [4, 5, 6]]
* math.transpose(A) // returns [[1, 4], [2, 5], [3, 6]]
*
* See also:
*
* diag, inv, subset, squeeze
*
* @param {Array | Matrix} x Matrix to be transposed
* @return {Array | Matrix} The transposed matrix
*/
return typed('transpose', {
Array: function (x) {
// use dense matrix implementation
return this(matrix(x)).valueOf()
},
Matrix: function (x) {
// matrix size
const size = x.size()
// result
let c
// process dimensions
switch (size.length) {
case 1:
// vector
c = x.clone()
break
case 2:
{
// rows and columns
const rows = size[0]
const columns = size[1]
// check columns
if (columns === 0) {
// throw exception
throw new RangeError('Cannot transpose a 2D matrix with no columns (size: ' + format(size) + ')')
}
// process storage format
switch (x.storage()) {
case 'dense':
c = _denseTranspose(x, rows, columns)
break
case 'sparse':
c = _sparseTranspose(x, rows, columns)
break
}
}
break
default:
// multi dimensional
throw new RangeError('Matrix must be a vector or two dimensional (size: ' + format(this._size) + ')')
}
return c
},
// scalars
any: function (x) {
return clone(x)
}
})
function _denseTranspose (m, rows, columns) {
// matrix array
const data = m._data
// transposed matrix data
const transposed = []
let transposedRow
// loop columns
for (let j = 0; j < columns; j++) {
// initialize row
transposedRow = transposed[j] = []
// loop rows
for (let i = 0; i < rows; i++) {
// set data
transposedRow[i] = clone(data[i][j])
}
}
// return matrix
return m.createDenseMatrix({
data: transposed,
size: [columns, rows],
datatype: m._datatype
})
}
function _sparseTranspose (m, rows, columns) {
// matrix arrays
const values = m._values
const index = m._index
const ptr = m._ptr
// result matrices
const cvalues = values ? [] : undefined
const cindex = []
const cptr = []
// row counts
const w = []
for (let x = 0; x < rows; x++) { w[x] = 0 }
// vars
let p, l, j
// loop values in matrix
for (p = 0, l = index.length; p < l; p++) {
// number of values in row
w[index[p]]++
}
// cumulative sum
let sum = 0
// initialize cptr with the cummulative sum of row counts
for (let i = 0; i < rows; i++) {
// update cptr
cptr.push(sum)
// update sum
sum += w[i]
// update w
w[i] = cptr[i]
}
// update cptr
cptr.push(sum)
// loop columns
for (j = 0; j < columns; j++) {
// values & index in column
for (let k0 = ptr[j], k1 = ptr[j + 1], k = k0; k < k1; k++) {
// C values & index
const q = w[index[k]]++
// C[j, i] = A[i, j]
cindex[q] = j
// check we need to process values (pattern matrix)
if (values) { cvalues[q] = clone(values[k]) }
}
}
// return matrix
return m.createSparseMatrix({
values: cvalues,
index: cindex,
ptr: cptr,
size: [columns, rows],
datatype: m._datatype
})
}
})
|
export default
function GetSourceTypeOptions(Rest, ProcessErrors, GetBasePath) {
return function(params) {
var scope = params.scope,
variable = params.variable;
if (scope[variable] === undefined) {
scope[variable] = [];
Rest.setUrl(GetBasePath('inventory_sources'));
Rest.options()
.then(({data}) => {
var i, choices = data.actions.GET.source.choices;
for (i = 0; i < choices.length; i++) {
if (choices[i][0] !== 'file' && choices[i][0] !== "") {
scope[variable].push({
label: choices[i][1],
value: choices[i][0]
});
}
}
scope.cloudCredentialRequired = false;
scope.$emit('sourceTypeOptionsReady');
})
.catch(({data, status}) => {
ProcessErrors(scope, data, status, null, { hdr: 'Error!',
msg: 'Failed to retrieve options for inventory_sources.source. OPTIONS status: ' + status
});
});
}
};
}
GetSourceTypeOptions.$inject =
[ 'Rest',
'ProcessErrors',
'GetBasePath'
];
|
var app = angular.module('commentsApp', []);
var pageNumber = window.location.pathname
app.controller('CommentController', function($scope, $http) {
var updateCommentSection = function() {
$scope.comments = [];
$http({
method: 'GET',
url: '/svc/comments/get?page_number=' + pageNumber
}).then(function successCallback(response) {
$scope.comments = response.data;
}, function errorCallback(response) {
console.log("Service not found.")
});
};
updateCommentSection();
$scope.addComment = function() {
if ($scope.comment)
{
$http({
method: 'POST',
url: '/svc/comments/add',
data: {
username: $scope.username,
page_number: pageNumber,
comment_text: $scope.comment
}
}).then(function successCallback(response) {
$scope.comment = "";
updateCommentSection();
}, function errorCallback(response) {
console.log("Service not found.")
});
}
};
});
var s = new WebSocket("ws://dev.ivoirians.me/ws/echo");
s.onmessage = function(evt) {console.log(evt) };
s.onerror = function(evt) {console.log(evt) };
s.onclose = function(evt) {console.log(evt) };
s.send("hi");
s.send("hello");
s.send("what's up");
|
define(
({
_widgetLabel: "Vejledninger",
searchPlaceholder: "Find adresse eller sted"
})
);
|
Bridge.merge(new System.Globalization.CultureInfo("smn-FI", true), {
englishName: "Sami, Inari (Finland)",
nativeName: "anarâškielâ (Suomâ)",
numberFormat: Bridge.merge(new System.Globalization.NumberFormatInfo(), {
nanSymbol: "epiloho",
negativeSign: "-",
positiveSign: "+",
negativeInfinitySymbol: "-∞",
positiveInfinitySymbol: "∞",
percentSymbol: "%",
percentGroupSizes: [3],
percentDecimalDigits: 2,
percentDecimalSeparator: ",",
percentGroupSeparator: " ",
percentPositivePattern: 0,
percentNegativePattern: 0,
currencySymbol: "€",
currencyGroupSizes: [3],
currencyDecimalDigits: 2,
currencyDecimalSeparator: ",",
currencyGroupSeparator: " ",
currencyNegativePattern: 8,
currencyPositivePattern: 3,
numberGroupSizes: [3],
numberDecimalDigits: 2,
numberDecimalSeparator: ",",
numberGroupSeparator: " ",
numberNegativePattern: 1
}),
dateTimeFormat: Bridge.merge(new System.Globalization.DateTimeFormatInfo(), {
abbreviatedDayNames: ["pas","vuo","maj","kos","tuo","vás","láv"],
abbreviatedMonthGenitiveNames: ["uđiv","kuov","njuh","cuáŋ","vyes","kesi","syei","porg","čohč","roov","skam","juov",""],
abbreviatedMonthNames: ["uđiv","kuov","njuh","cuáŋ","vyes","kesi","syei","porg","čohč","roov","skam","juov",""],
amDesignator: "",
dateSeparator: ".",
dayNames: ["pasepeivi","vuossargâ","majebargâ","koskokko","tuorâstâh","vástuppeivi","lávurdâh"],
firstDayOfWeek: 1,
fullDateTimePattern: "MMMM d'. p. 'yyyy H:mm:ss",
longDatePattern: "MMMM d'. p. 'yyyy",
longTimePattern: "H:mm:ss",
monthDayPattern: "MMMM d'. p. '",
monthGenitiveNames: ["uđđâivemáánu","kuovâmáánu","njuhčâmáánu","cuáŋuimáánu","vyesimáánu","kesimáánu","syeinimáánu","porgemáánu","čohčâmáánu","roovvâdmáánu","skammâmáánu","juovlâmáánu",""],
monthNames: ["uđđâivemáánu","kuovâmáánu","njuhčâmáánu","cuáŋuimáánu","vyesimáánu","kesimáánu","syeinimáánu","porgemáánu","čohčâmáánu","roovvâdmáánu","skammâmáánu","juovlâmáánu",""],
pmDesignator: "",
rfc1123: "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
shortDatePattern: "d.M.yyyy",
shortestDayNames: ["p","v","m","k","t","v","l"],
shortTimePattern: "H:mm",
sortableDateTimePattern: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
sortableDateTimePattern1: "yyyy'-'MM'-'dd",
timeSeparator: ":",
universalSortableDateTimePattern: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
yearMonthPattern: "MMMM yyyy",
roundtripFormat: "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffzzz"
}),
TextInfo: Bridge.merge(new System.Globalization.TextInfo(), {
ANSICodePage: 1252,
CultureName: "smn-FI",
EBCDICCodePage: 20278,
IsRightToLeft: false,
LCID: 9275,
listSeparator: ";",
MacCodePage: 10000,
OEMCodePage: 850,
IsReadOnly: true
})
});
|
cordova.define("cordova-plugin-file.DirectoryEntry", function(require, exports, module) { /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var argscheck = require('cordova/argscheck'),
utils = require('cordova/utils'),
exec = require('cordova/exec'),
Entry = require('./Entry'),
FileError = require('./FileError'),
DirectoryReader = require('./DirectoryReader');
/**
* An interface representing a directory on the file system.
*
* {boolean} isFile always false (readonly)
* {boolean} isDirectory always true (readonly)
* {DOMString} name of the directory, excluding the path leading to it (readonly)
* {DOMString} fullPath the absolute full path to the directory (readonly)
* {FileSystem} filesystem on which the directory resides (readonly)
*/
var DirectoryEntry = function(name, fullPath, fileSystem, nativeURL) {
// add trailing slash if it is missing
if ((fullPath) && !/\/$/.test(fullPath)) {
fullPath += "/";
}
// add trailing slash if it is missing
if (nativeURL && !/\/$/.test(nativeURL)) {
nativeURL += "/";
}
DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath, fileSystem, nativeURL);
};
utils.extend(DirectoryEntry, Entry);
/**
* Creates a new DirectoryReader to read entries from this directory
*/
DirectoryEntry.prototype.createReader = function() {
return new DirectoryReader(this.toInternalURL());
};
/**
* Creates or looks up a directory
*
* @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory
* @param {Flags} options to create or exclusively create the directory
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.getDirectory = function(path, options, successCallback, errorCallback) {
argscheck.checkArgs('sOFF', 'DirectoryEntry.getDirectory', arguments);
var fs = this.filesystem;
var win = successCallback && function(result) {
var entry = new DirectoryEntry(result.name, result.fullPath, fs, result.nativeURL);
successCallback(entry);
};
var fail = errorCallback && function(code) {
errorCallback(new FileError(code));
};
exec(win, fail, "File", "getDirectory", [this.toInternalURL(), path, options]);
};
/**
* Deletes a directory and all of it's contents
*
* @param {Function} successCallback is called with no parameters
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.removeRecursively = function(successCallback, errorCallback) {
argscheck.checkArgs('FF', 'DirectoryEntry.removeRecursively', arguments);
var fail = errorCallback && function(code) {
errorCallback(new FileError(code));
};
exec(successCallback, fail, "File", "removeRecursively", [this.toInternalURL()]);
};
/**
* Creates or looks up a file
*
* @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file
* @param {Flags} options to create or exclusively create the file
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.getFile = function(path, options, successCallback, errorCallback) {
argscheck.checkArgs('sOFF', 'DirectoryEntry.getFile', arguments);
var fs = this.filesystem;
var win = successCallback && function(result) {
var FileEntry = require('./FileEntry');
var entry = new FileEntry(result.name, result.fullPath, fs, result.nativeURL);
successCallback(entry);
};
var fail = errorCallback && function(code) {
errorCallback(new FileError(code));
};
exec(win, fail, "File", "getFile", [this.toInternalURL(), path, options]);
};
module.exports = DirectoryEntry;
});
|
const URL = "ftp://localhost/bug543805/";
var year = new Date().getFullYear().toString();
const tests = [
// AIX ls format
["-rw-r--r-- 1 0 11 Jan 1 20:19 nodup.file\r\n" +
"-rw-r--r-- 1 0 22 Jan 1 20:19 test.blankfile\r\n" +
"-rw-r--r-- 1 0 33 Apr 1 2008 test2.blankfile\r\n" +
"-rw-r--r-- 1 0 44 Jan 1 20:19 nodup.file\r\n" +
"-rw-r--r-- 1 0 55 Jan 1 20:19 test.file\r\n" +
"-rw-r--r-- 1 0 66 Apr 1 2008 test2.file\r\n",
"300: " + URL + "\n" +
"200: filename content-length last-modified file-type\n" +
"201: \"%20nodup.file\" 11 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" +
"201: \"%20test.blankfile\" 22 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" +
"201: \"%20test2.blankfile\" 33 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n" +
"201: \"nodup.file\" 44 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" +
"201: \"test.file\" 55 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" +
"201: \"test2.file\" 66 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n"],
// standard ls format
[
"-rw-r--r-- 1 500 500 11 Jan 1 20:19 nodup.file\r\n" +
"-rw-r--r-- 1 500 500 22 Jan 1 20:19 test.blankfile\r\n" +
"-rw-r--r-- 1 500 500 33 Apr 1 2008 test2.blankfile\r\n" +
"-rw-r--r-- 1 500 500 44 Jan 1 20:19 nodup.file\r\n" +
"-rw-r--r-- 1 500 500 55 Jan 1 20:19 test.file\r\n" +
"-rw-r--r-- 1 500 500 66 Apr 1 2008 test2.file\r\n",
"300: " + URL + "\n" +
"200: filename content-length last-modified file-type\n" +
"201: \"%20nodup.file\" 11 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" +
"201: \"%20test.blankfile\" 22 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" +
"201: \"%20test2.blankfile\" 33 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n" +
"201: \"nodup.file\" 44 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" +
"201: \"test.file\" 55 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" +
"201: \"test2.file\" 66 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n"]
]
function checkData(request, data, ctx) {
do_check_eq(tests[0][1], data);
tests.shift();
next_test();
}
function storeData(status, entry) {
do_check_eq(status, Components.results.NS_OK);
entry.setMetaDataElement("servertype", "0");
var os = entry.openOutputStream(0);
var written = os.write(tests[0][0], tests[0][0].length);
if (written != tests[0][0].length) {
do_throw("os.write has not written all data!\n" +
" Expected: " + written + "\n" +
" Actual: " + tests[0][0].length + "\n");
}
os.close();
entry.close();
var ios = Components.classes["@mozilla.org/network/io-service;1"].
getService(Components.interfaces.nsIIOService);
var channel = ios.newChannel(URL, "", null);
channel.asyncOpen(new ChannelListener(checkData, null, CL_ALLOW_UNKNOWN_CL), null);
}
function next_test() {
if (tests.length == 0)
do_test_finished();
else {
asyncOpenCacheEntry(URL,
"FTP",
Components.interfaces.nsICache.STORE_ANYWHERE,
Components.interfaces.nsICache.ACCESS_READ_WRITE,
storeData);
}
}
function run_test() {
do_execute_soon(next_test);
do_test_pending();
}
|
function includeJsFile(filename) {
document.write(
'<script src="'
+ CUI_INCLUDE_PATH + filename +
'" type="text/javascript"><\/script>'
);
}
function includeAbsJsFile(filename) {
document.write(
'<script src="'
+ filename +
'" type="text/javascript"><\/script>'
);
}
function includeAbsCssFile(filename) {
document.write(
'<link href="'
+ filename +
'" rel="stylesheet" type="text/css">'
);
}
function includeCssFile(filename) {
document.write(
'<link href="'
+ CUI_INCLUDE_PATH + filename +
'" rel="stylesheet" type="text/css">'
);
}
includeAbsJsFile("//www.google.com/jsapi");
includeAbsJsFile("//maps.googleapis.com/maps/api/js?key=AIzaSyCRMz0xxBvCrYp4K_iYu1ncN8lHM6ITnYY");
includeAbsCssFile("//fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,700|ABeeZee|Titillium+Web:200,300,400,700");
includeJsFile("/cui_nav_state.js");
includeJsFile("/cui_node.js");
includeJsFile("/cui_events.js");
includeJsFile("/cui_util.js");
includeJsFile("/nodes/controls/cui_page_control.js");
includeCssFile("/nodes/controls/cui_page_control.css");
includeJsFile("/nodes/generic/cui_button.js");
includeJsFile("/nodes/generic/cui_dropdown.js");
includeJsFile("/nodes/generic/cui_editable_text.js");
includeJsFile("/nodes/generic/cui_option.js");
includeJsFile("/nodes/generic/cui_popup.js");
includeJsFile("/nodes/generic/cui_switcher.js");
includeJsFile("/nodes/generic/cui_toggle.js");
includeJsFile("/nodes/generic/cui_wrapper.js");
includeJsFile("/nodes/layout/cui_canvas.js");
includeJsFile("/nodes/layout/cui_quad_layout.js");
includeJsFile("/nodes/layout/cui_u_layout.js");
includeJsFile("/nodes/layout/cui_hsplit_layout.js");
includeJsFile("/nodes/layout/cui_hsplit3_layout.js");
includeJsFile ("/nodes/cloudvar_widget/cui_cloudvar_plot.js");
includeJsFile ("/nodes/cloudvar_widget/cui_cloudvar_widget.js");
includeCssFile ("/nodes/cloudvar_widget/cui_cloudvar_widget.css");
includeJsFile ("/nodes/topbar/cui_topbar.js");
includeJsFile ("/nodes/topbar/cui_app_dropdown.js");
includeJsFile ("/nodes/topbar/cui_user_dropdown.js");
includeCssFile("/nodes/topbar/cui_topbar.css");
includeCssFile("/nodes/topbar/cui_topbar_submenu.css");
includeCssFile("/nodes/topbar/cui_app_dropdown.css");
includeCssFile("/nodes/topbar/cui_user_dropdown.css");
includeCssFile("/nodes/generic/cui_generic.css");
includeJsFile ("/nodes/viz/cui_plot.js");
includeCssFile("/nodes/viz/cui_plot.css");
includeJsFile ("/nodes/viz/cui_map.js");
includeCssFile("/nodes/viz/cui_map.css");
includeCssFile("/nodes/layout/cui_layout.css");
includeCssFile("/nodes/layout/cui_responsive_layout.css");
includeCssFile("/cui_base.css");
|
/**
* views -- render HTML/CSS with JS templating
*/
App.Views.EducationList = Backbone.View.extend({
classname : 'educationList_view',
tagName: 'div',
tmpl_url : '',
initialize: function(options){
this.options = options;
this.bind('change', this.render);
this.model = this.options.model;
this.collection = this.options.collection;
var self = this;
$.ajax({
url: this.options.tmpl_url,
method: 'GET',
async: false,
dataType: 'html',
success: function(data) {
self.template = data;
}
});
},
render: function(){
var educationJson= {'educations':eval(JSON.stringify(this.collection))};
$(this.el).html(Mustache.to_html(this.template,educationJson));
$("#el").html(this.$el);
return this;
}
});
|
/*
** Copyright 2013 Google 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.
*/
define(
['config', 'bigl', 'stapes','googlemaps','mergemaps', 'sv_svc', 'jquery'],
function(config, L, Stapes, GMaps, XMaps, sv_svc, $) {
var MIN_SEARCH_RADIUS = 200;
var MAX_SEARCH_RADIUS = 3200;
var EarthPosModule = Stapes.subclass({
constructor: function(map) {
var self = this;
this.map = map;
if(XMaps.apiProvider != 1) return;
XMaps.addListenerOnce(this.map, 'idle', function(event) {
if (config.earth_pos_url) {
var ajax_opts = {
async: true,
cache: false,
dataType: 'json',
success: function(data) {
var ll = new GMaps.LatLng(data['cameraLat'], data['cameraLon']);
sv_svc.getPanoramaByLocation(
ll,
MIN_SEARCH_RADIUS,
self.searchCB.bind(self),
MAX_SEARCH_RADIUS
);
},
error: function(jqXHR, textStatus, errorThrown) {
console.warn('Error fetching Earth posiition:', errorThrown);
}
};
$.ajax(
config.earth_pos_url,
ajax_opts
);
}
});
},
searchCB: function(panodata, stat) {
if (stat == GMaps.StreetViewStatus.OK) {
this.emit('found_location', panodata);
}
}
});
return EarthPosModule;
});
|
"use strict";
const sinon = require('sinon')
, expect = require("chai").expect
, SecretStoreService = require("../../security/secret-store-service");
describe("Secret Store Tests", function () {
afterEach(function () {
sinon.restore();
});
it('Test read', function (done) {
const dataId = '12345';
const secretStore = new SecretStoreService();
const testData = 'some test data';
sinon.mock(secretStore).expects('read').withArgs('12345').resolves(testData);
secretStore.read(dataId).then(response => {
expect(response).to.not.be.undefined;
expect(response).to.equal(testData);
}).finally(() => {
done();
});
});
});
|
/**
* @license
* Copyright 2016 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var ts = require("typescript");
var Lint = require("../index");
var utils_1 = require("../language/utils");
var Rule = (function (_super) {
__extends(Rule, _super);
function Rule() {
return _super.apply(this, arguments) || this;
}
Rule.prototype.applyWithProgram = function (sourceFile, langSvc) {
return this.applyWithWalker(new RestrictPlusOperandsWalker(sourceFile, this.getOptions(), langSvc.getProgram()));
};
return Rule;
}(Lint.Rules.TypedRule));
/* tslint:disable:object-literal-sort-keys */
Rule.metadata = {
ruleName: "restrict-plus-operands",
description: "When adding two variables, operands must both be of type number or of type string.",
optionsDescription: "Not configurable.",
options: null,
optionExamples: ["true"],
type: "functionality",
typescriptOnly: false,
requiresTypeInfo: true,
};
/* tslint:enable:object-literal-sort-keys */
Rule.INVALID_TYPES_ERROR = "Operands of '+' operation must either be both strings or both numbers";
exports.Rule = Rule;
var RestrictPlusOperandsWalker = (function (_super) {
__extends(RestrictPlusOperandsWalker, _super);
function RestrictPlusOperandsWalker() {
return _super.apply(this, arguments) || this;
}
RestrictPlusOperandsWalker.prototype.visitBinaryExpression = function (node) {
if (node.operatorToken.kind === ts.SyntaxKind.PlusToken) {
var tc = this.getTypeChecker();
var leftType = getBaseTypeOfLiteralType(tc.getTypeAtLocation(node.left));
var rightType = getBaseTypeOfLiteralType(tc.getTypeAtLocation(node.right));
var width = node.getWidth();
var position = node.getStart();
if (leftType === "invalid" || rightType === "invalid" || leftType !== rightType) {
this.addFailureAt(position, width, Rule.INVALID_TYPES_ERROR);
}
}
_super.prototype.visitBinaryExpression.call(this, node);
};
return RestrictPlusOperandsWalker;
}(Lint.ProgramAwareRuleWalker));
function getBaseTypeOfLiteralType(type) {
if (utils_1.isTypeFlagSet(type, ts.TypeFlags.StringLiteral) || utils_1.isTypeFlagSet(type, ts.TypeFlags.String)) {
return "string";
}
else if (utils_1.isTypeFlagSet(type, ts.TypeFlags.NumberLiteral) || utils_1.isTypeFlagSet(type, ts.TypeFlags.Number)) {
return "number";
}
else if (utils_1.isTypeFlagSet(type, ts.TypeFlags.Union) && !utils_1.isTypeFlagSet(type, ts.TypeFlags.Enum)) {
var types = type.types.map(getBaseTypeOfLiteralType);
return allSame(types) ? types[0] : "invalid";
}
else if (utils_1.isTypeFlagSet(type, ts.TypeFlags.EnumLiteral)) {
return getBaseTypeOfLiteralType(type.baseType);
}
return "invalid";
}
function allSame(array) {
return array.every(function (value) { return value === array[0]; });
}
|
$(document).ready(function () {
LlenarTabla();
//$(".Agregar").click(function () {
// $('#ModalAgregarTipoPregunta').modal('show');
//});
});
function LlenarTabla() {
$('#TablaTipoPreguntas').dataTable({
"processing": true,
"serverSide": true,
"bFilter": false,
"dom": '<"toolbar">frtip',
"bDestroy": true,
"info": true,
"stateSave": true,
"lengthMenu": [[10, 20, 50, 100], [10, 20, 50, 100]],
"ajax": {
"url": "/TipoPreguntas/GetList/",
"type": "POST",
"data": { 'data': 1 },
//},
//"fnInitComplete": function (oSettings, json) {
//},
//"fnDrawCallback": function (oSettings) {
},
"columns": [
{ "data": "IdTipoPregunta", "orderable": false },
{ "data": "Descripcion", "orderable": false },
////{
//// sortable: false,
//// "render": function (data, type, full, meta) {
//// console.log(full);
//// }
////},
//{
// sortable: false,
// "render": function (data, type, full, meta) {
// return Opciones(); //Es el campo de opciones de la tabla.
// }
//}
],
language: {
processing: "Procesando información...",
search: "Buscar :",
lengthMenu: "Mostrar _MENU_ Elementos",
info: "Mostrando _START_ de _END_ Total _TOTAL_ elementos",
infoEmpty: "No hay elemetos para mostrar",
infoFiltered: "(filtrados _MAX_ )",
infoPostFix: "",
loadingRecords: "Búsqueda en curso...",
zeroRecords: "No hay registros para mostrar",
emptyTable: "No hay registros disponibles",
paginate: {
first: "Primera",
previous: "Anterior",
next: "Siguiente",
last: "Ultima"
},
//aria: {
// sortAscending: ": activer pour trier la colonne par ordre croissant",
// sortDescending: ": activer pour trier la colonne par ordre décroissant"
//}
},
"order": [[0, "asc"]]
})
//$("div.toolbar").html('<button class="btn btn-success btn-sm Agregar" style="float:right;" ><i class="fa fa-plus" aria-hidden="true"></i> Nuevo Tipo de Pregunta </button> <div class="input-group input-group-sm"><input class="form-control" type="text"><span class="input-group-btn"><button class="btn btn-info btn-flat" type="button">Buscar</button></span></div>');
}
function Opciones() {
var botones = "<button class='btn btn-info btn-xs detalleTipoPregunta' id='detalleTipoPregunta'>Detalles</button> <button class='btn btn-warning btn-xs editarTipoPregunta' id='editarTipoPregunta'>Editar</button> <button class='btn btn-danger btn-xs eliminarPregunta' id='eliminarTipoPregunta'> Eliminar</button> ";
return botones;
}
//funcion:retorna las opciones que tendra cada row en la tabla principal
function Opciones() {
var opc = "<button class='btn btn-info btn-xs Detalle' type='button'>Detalles</button> <button class='btn btn-warning btn-xs Editar' type='button'><i class='fa fa-pencil' aria-hidden='true'></i> Editar</button> <button class='btn btn-danger btn-xs eliminar' type='button'> <i class='fa fa-trash-o' aria-hidden='true'></i> Eliminar</button>"
return opc;
}
$('#TablaTipoPreguntas').on('click', '.Detalle', function () {
$('#ModalDetalleTipoPregunta').modal('show');
});
$('#TablaTipoPreguntas').on('click', '.Editar', function () {
$('#ModalDetalleTipoPregunta').modal('show');
});
$('#TablaTipoPreguntas').on('click', '.Eliminar', function () {
alert("click");
});
//function ActualizaListaPreguntas() {
// $('#TbodyPreguntas').empty();
// for (var b = 0; b < Lista_preguntas.length; b++) {
// $('#tablaPreguntas').append("<tr><td>" + Lista_preguntas[b].Nombre + "</td><td>" + Lista_preguntas[b].TipoControl + "</td><td><button class='btn btn-info btn-xs detallepregunta' rel='" + Lista_preguntas[b].id + "'>Detalles</button> <button class='btn btn-warning btn-xs EditarPregunta ' rel='" + Lista_preguntas[b].id + "'>Editar</button> <button class='btn btn-danger btn-xs EliminaPregunta' rel='" + Lista_preguntas[b].id + "'>Eliminar</button></td></tr>");
// }
//}
//$('#TablaClientes').on('click', '.EliminaCliente', function () {
// var id = $(this).attr('rel');
// $('#ModalEliminaCliente').modal('show');
// //$('#contrato').val(id);
//});
|
'use strict';
const chalk = require('chalk');
const fs = require('hexo-fs');
const pathFn = require('path');
const Promise = require('bluebird');
const COMPLETION_DIR = pathFn.join(__dirname, '../../completion');
function helpConsole(args) {
if (args.v || args.version) {
return this.call('version');
} else if (args.consoleList) {
return printConsoleList(this.extend.console.list());
} else if (typeof args.completion === 'string') {
return printCompletion(args.completion);
}
const command = args._[0];
if (typeof command === 'string' && command !== 'help') {
const c = this.extend.console.get(command);
if (c) return printHelpForCommand(this.extend.console.alias[command], c);
}
return printAllHelp(this.extend.console.list());
}
function printHelpForCommand(command, data) {
const { options } = data;
const desc = options.description || options.desc || data.description || data.desc;
console.log('Usage: hexo', command, options.usage || '');
console.log('\nDescription:');
console.log(`${desc}\n`);
if (options.arguments) printList('Arguments', options.arguments);
if (options.commands) printList('Commands', options.commands);
if (options.options) printList('Options', options.options);
return Promise.resolve();
}
function printAllHelp(list) {
const keys = Object.keys(list);
const commands = [];
const { length } = keys;
for (let i = 0; i < length; i++) {
const key = keys[i];
commands.push({
name: key,
desc: list[key].desc
});
}
console.log('Usage: hexo <command>\n');
printList('Commands', commands);
printList('Global Options', [
{name: '--config', desc: 'Specify config file instead of using _config.yml'},
{name: '--cwd', desc: 'Specify the CWD'},
{name: '--debug', desc: 'Display all verbose messages in the terminal'},
{name: '--draft', desc: 'Display draft posts'},
{name: '--safe', desc: 'Disable all plugins and scripts'},
{name: '--silent', desc: 'Hide output on console'}
]);
console.log('For more help, you can use \'hexo help [command]\' for the detailed information');
console.log('or you can check the docs:', chalk.underline('http://hexo.io/docs/'));
return Promise.resolve();
}
function printList(title, list) {
list.sort((a, b) => {
const nameA = a.name;
const nameB = b.name;
if (nameA < nameB) return -1;
if (nameA > nameB) return 1;
return 0;
});
const lengths = list.map(item => item.name.length);
const maxLen = lengths.reduce((prev, current) => Math.max(prev, current));
let str = `${title}:\n`;
const { length } = list;
for (let i = 0; i < length; i++) {
const { description = list[i].desc } = list[i];
const pad = ' '.repeat(maxLen - lengths[i] + 2);
str += ` ${chalk.bold(list[i].name)}${pad}${description}`;
}
console.log(str);
return Promise.resolve();
}
function printConsoleList(list) {
console.log(Object.keys(list).join('\n'));
return Promise.resolve();
}
function printCompletion(type) {
return fs.readFile(pathFn.join(COMPLETION_DIR, type)).then(content => {
console.log(content);
});
}
module.exports = helpConsole;
|
/*
* Copyright 2016 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.
*/
var Aria = require('ariatemplates/Aria');
module.exports = Aria.classDefinition({
$classpath : 'test.aria.widgets.wai.processingIndicator.ProcessingIndicatorOnSectionWithTabJawsTestCase',
$extends : require('./JawsBase'),
$statics : {
useCase : {
navigationKey : '[tab]',
reverse : false,
section : true
}
}
});
|
(function() {
var AppWindow;
AppWindow = function(title, navHiddenFlag) {
var self = Ti.UI.createWindow({
title:title,
barColor:'#000000',
backgroundColor:'#ffffff'
});
self.hideNavBar();
self.addEventListener('focus', function(e){
ActiveWinTab.activeWindow = self;
});
return self;
};
return module.exports = AppWindow;
})();
|
import Ember from 'ember';
const STATUS_HELP = {
pending: function(registration) {
return 'The application for ' + registration.sourceName + ' is being reviewed. Check back soon!';
},
accepted: function(registration) {
if (registration.directSource) {
return registration.sourceName + ' has been approved as a source. Start pushing data!';
}
return registration.sourceName + ' has been approved as a source but we have not started scraping it yet.';
},
implemented: function(registration) {
return registration.sourceName + ' is now a source. Check it out!';
},
rejected: function(registration) {
return registration.sourceName + ' has been rejected as a source. Contact share-support@osf.io for additional information.';
},
};
export default Ember.Component.extend({
init() {
this._super(...arguments);
Ember.run.schedule('afterRender', this, function() {
this.send('enablePopover');
});
},
colorClass: Ember.computed('registration.data.status', 'registration.data.sourceName', function() {
return this.getStatusColor(this.get('registration.data'));
}),
helpText: Ember.computed('registration.data.status', function() {
let registration = this.get('registration.data');
return STATUS_HELP[registration.status](registration);
}),
getStatusColor(registration) {
if (registration.status === 'pending') {
return 'bg-warning';
} else if (registration.directSource && registration.status === 'accepted') {
return 'bg-success';
} else if (registration.status === 'accepted') {
return 'bg-info';
} else if (registration.status === 'implemented') {
return 'bg-success';
}
return 'bg-danger';
},
actions: {
enablePopover() {
Ember.$('[data-toggle="popover"]').popover();
}
}
});
|
// http://www.cnblogs.com/lyqf365/p/3287293.html
//
define(["dojo/_base/declare","esri/layers/tiled"], function(declare){
return declare(esri.layers.TiledMapServiceLayer, {
constructor: function() {
g_wkid = 4326;
g_width = 180;
g_height = 90;
this.spatialReference = new esri.SpatialReference({ wkid:g_wkid });
this.initialExtent = (this.fullExtent = new esri.geometry.Extent(-g_width, -g_height, g_width, g_height, this.spatialReference));
this.tileInfo = new esri.layers.TileInfo({
"rows" : 256,
"cols" : 256,
"compressionQuality" : 0,
"origin" : {
"x" : -g_width,
"y" : g_height
},
"spatialReference" : {
"wkid" : g_wkid
},
"lods" : [
{"level" : 0, "resolution" : 1.40625, "scale" : 590995186.1175001},
{"level" : 1, "resolution" : 0.703125, "scale" : 295497593.05875003},
{"level" : 2, "resolution" : 0.3515625, "scale" : 147748796.52937502},
{"level" : 3, "resolution" : 0.17578125, "scale" : 73874398.264687508},
{"level" : 4, "resolution" : 0.087890625, "scale" : 36937199.132343754},
{"level" : 5, "resolution" : 0.0439453125, "scale" : 18468599.566171877},
{"level" : 6, "resolution" : 0.02197265625, "scale" : 9234299.7830859385},
{"level" : 7, "resolution" : 0.010986328125, "scale" : 4617149.8915429693},
{"level" : 8, "resolution" : 0.0054931640625, "scale" : 2308574.9457714846},
{"level" : 9, "resolution" : 0.00274658203125, "scale" : 1154287.4728857423},
{"level" : 10, "resolution" : 0.001373291015625, "scale" : 577143.73644287116},
{"level" : 11, "resolution" : 0.0006866455078125, "scale" : 288571.86822143558},
{"level" : 12, "resolution" : 0.00034332275390625, "scale" : 144285.93411071779},
{"level" : 13, "resolution" : 0.000171661376953125, "scale" : 72142.967055358895},
{"level" : 14, "resolution" : 8.58306884765625e-005, "scale" : 36071.483527679447},
{"level" : 15, "resolution" : 4.291534423828125e-005, "scale" : 18035.741763839724},
{"level" : 16, "resolution" : 2.1457672119140625e-005, "scale" : 9017.8708819198619},
{"level" : 17, "resolution" : 1.0728836059570313e-005, "scale" : 4508.9354409599309},
{"level" : 18, "resolution" : 5.3644180297851563e-006, "scale" : 2254.4677204799655},
{"level" : 19, "resolution" : 2.682209014892578e-006, "scale" : 1127.2338602399827},
{"level" : 20, "resolution" : 1.341104507446289e-006, "scale" : 563.6169301199914}
]
});
this.loaded = true;
this.onLoad(this);
},
getTileUrl: function(level, row, col) {
return "http://t" + row%8 + ".tianditu.cn/cva_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=c&TILEMATRIX="+level+"&TILEROW="+row+"&TILECOL="+col+"&FORMAT=tiles";
}
/*
getTileUrl_vector: function(level, row, col) {
return "http://t" + col%8 + ".tianditu.cn/vec_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=c&TILEMATRIX="+level+"&TILEROW="+row+"&TILECOL="+col+"&FORMAT=tiles";
}
getTileUrl_vector_anno: function(level, row, col) {
return "http://t" + row%8 + ".tianditu.cn/cva_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=c&TILEMATRIX="+level+"&TILEROW="+row+"&TILECOL="+col+"&FORMAT=tiles";
}
getTileUrl_image: function(level, row, col) {
return "http://t" + col%8 + ".tianditu.cn/img_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=c&TILEMATRIX="+level+"&TILEROW="+row+"&TILECOL="+col+"&FORMAT=tiles";
}
getTileUrl_image_anno: function(level, row, col) {
return "http://t" + row%8 + ".tianditu.cn/cia_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=c&TILEMATRIX="+level+"&TILEROW="+row+"&TILECOL="+col+"&FORMAT=tiles";
}
*/
});
});
|
var clickJquerySelector = function(sel){
clickJqueryResult(jQuery(sel))
};
var clickJqueryResult = function($el){
var el = $el[0];
var etype = 'click';
clickDomElement(el, etype);
};
var followLink = function(operationFn, $sel){
alert("about to click a link: " + jQuery_text(operationFn, $sel, true));
clickJqueryResult(operationFn($sel));
};
var submitEnclosingForm = function(operationFn, sel){
operationFn(sel).closest('form').submit();
};
var pressKey = function(sel, code){
var p = {which: code, keyCode: code};
jQuery(sel).trigger(jQuery.Event("keydown", p));
jQuery(sel).trigger(jQuery.Event("keyup", p));
jQuery(sel).trigger(jQuery.Event("keypress", p));
// alert("triggered " + JSON.stringify(p));
};
var clickDomElement = function(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
};
var printJQuery = function($sel){
var r = $($sel);
alert("found " + r.length + " results for " + $sel + ": " + r.html());
r.each(function(index, el){
alert(el.outerHTML);
});
};
var printJQuery2 = function(r){
alert("found " + r.length + " results : " + r.html());
r.each(function(index, el){
alert(el.outerHTML);
});
};
var newArrayFn = function(i){
return function($sel){
return $($($sel)[i]);
};
};
var arrayFn = function($sel){
return $($(sel)[i]);
};
var directFn = function($sel){
if(!window.__javaToJS) {
alert("warning: directFn is undefined!");
}
return window.__javaToJS;
};
var newFindFn = function($rootSel, $findSel){
return function($sel){
return $($rootSel).find($findSel).find($sel);
};
};
var jQueryAggregate = function(operationFn, $sel, initialValue, aggregator){
var r = operationFn($sel);
var result = initialValue;
r.each(function(index, el){
result = aggregator(result, index, el);
});
return result;
};
var jQueryFind = function(operationFn, $sel, $findSel){
return operationFn($sel).find($findSel);
};
var jQuerySetValue = function(operationFn, $sel, value){
return operationFn($sel).val(value);
};
var jQueryGetAttr = function(operationFn, $sel, name){
return operationFn($sel).attr(name);
};
var jQuerySetAttr = function(operationFn, $sel, name, value){
return operationFn($sel).attr(name, value);
};
var jQuery_asResultArray = function(operationFn, $sel){
var res = [];
jQueryAggregate(operationFn, $sel, res, function(r, i, el){
r.push(jQuery(el));
return r;
});
return res;
};
var jQueryAttrs = function(operationFn, $sel){
var r = operationFn($sel);
if(r.length == 0) return [];
var nodes=[], values=[];
var el = r[0];
for (var attr, i = 0, attrs = el.attributes, l=attrs.length; i<l; i++){
attr = attrs.item(i);
nodes.push(attr.nodeName);
values.push(attr.nodeValue);
}
return nodes;
};
//var jQuery_asResultArray = function($sel){
//
//};
var jQuery_text = function(operationFn, $sel, isHtml){
// alert('jQuery_text, operationFn: ' + operationFn + ", sel: " + $sel + ", isHtml: " + isHtml);
return jQueryAggregate(operationFn, $sel, '', function(r, i, el){
if(isHtml) {
return r + el.outerHTML + "\n";
} else {
return r + el.innerText + "\n";
}
});
};
|
//// [optionalParamAssignmentCompat.ts]
interface I1 {
(p1: number, p2: string): void;
}
interface I2 {
p1: I1;
m1(p1?: string): I1;
}
var i2: I2;
var c: I1 = i2.p1; // should be ok
var d: I1 = i2.m1; // should error
//// [optionalParamAssignmentCompat.js]
var i2;
var c = i2.p1;
var d = i2.m1;
|
/**
* @license
* Copyright 2015 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
*/
CLASS({
name: 'HTMLGraph',
package: 'foam.graphics',
extends: 'foam.ui.SimpleView',
properties: [
{
model_: 'ColorProperty',
name: 'graphColor',
defaultValue: 'green'
},
{
model_: 'ColorProperty',
name: 'backgroundColor',
defaultValue: 'transparent'
},
{
model_: 'ArrayProperty',
name: 'data',
preSet: function(old, nu) {
if ( old === nu ) return nu;
if ( nu.length > this.width ) return nu.slice(-this.width);
return nu;
},
lazyFactory: function() { return []; }
},
{
model_: 'IntProperty',
name: 'width',
defaultValue: 40
},
{
model_: 'IntProperty',
name: 'height',
defaultValue: 15
},
{
model_: 'FloatProperty',
name: 'min',
defaultValueFn: function() {
if ( this.data.length === 0 ) return 0;
var min = Number.INFINITY;
for ( var i = 0; i < this.data.length; ++i ) {
min = Math.min(min, this.data[i]);
}
return Number.isNaN(min) ? 0 : min;
}
},
{
model_: 'FloatProperty',
name: 'max',
defaultValueFn: function() {
if ( this.data.length === 0 ) return 100;
var max = Number.NEGATIVE_INFINITY;
for ( var i = 0; i < this.data.length; ++i ) {
max = Math.max(max, this.data[i]);
}
return Number.isNaN(max) ? 100 : max;
}
}
],
methods: [
function addData(value, opt_maxNumValues) {
var maxNumValues = opt_maxNumValues || this.width;
if ( this.data.length === maxNumValues ) this.data.shift();
this.data.push(value);
}
],
templates: [
function toHTML() {/*
<graph id="%%id">
<% for ( var i = 0; i < this.data.length; ++i ) {
var rowWidth = Math.round(10000 / this.data.length) / 100;
var dataHeight = Math.min(100,
Math.round(10000 * (this.data[i] - this.min) / this.max) / 100);
var bgHeight = 100 - dataHeight; %>
<graph-row style="width: {{rowWidth}}%">
<graph-row-bg style="background: {{this.backgroundColor}}; flex-grow: {{bgHeight}}; -webkit-flex-grow: {{bgHeight}}"></graph-row-bg>
<graph-row-data style="background: {{this.graphColor}}; flex-grow: {{dataHeight}}; -webkit-flex-grow: {{dataHeight}}"></graph-row-data>
</graph-row>
<% } %>
</graph>
*/},
function CSS() {/*
graph {
flex-grow: 1;
display: flex;
align-items: stretch;
align-content: stretch;
}
graph-row {
display: flex;
flex-direction: column;
align-items: stretch;
align-content: stretch;
}
graph-row-bg {
display: block;
flex-grow: 1;
}
graph-row-data {
display: block;
min-height: 1px;
}
*/}
]
});
|
// Copyright 2015 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.
import {GlobalStateParams as ResourceGlobalStateParams} from './globalresourcedetail';
/**
* Parameters for this state.
*
* All properties are @exported and in sync with URL param names.
*/
export class StateParams extends ResourceGlobalStateParams {
/**
* @param {string} objectNamespace
* @param {string} objectName
*/
constructor(objectNamespace, objectName) {
super(objectName);
/** @export {string} Namespace of this object. */
this.objectNamespace = objectNamespace;
}
}
export function appendDetailParamsToUrl(baseUrl) {
return `${baseUrl}/:objectNamespace/:objectName`;
}
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
export default [
[
['gauerdia', 'goizald.', 'goizeko', 'eguerd.', 'arrats.', 'iluntz.', 'gaueko'], ,
['gauerdia', 'goizaldeko', 'goizeko', 'eguerdiko', 'arratsaldeko', 'iluntzeko', 'gaueko']
],
[
['gauerdia', 'goizald.', 'goiza', 'eguerd.', 'arrats.', 'iluntz.', 'gaua'],
['gauerdia', 'goiz.', 'goiza', 'eguerd.', 'arrats.', 'iluntz.', 'gaua'],
['gauerdia', 'goizaldea', 'goiza', 'eguerdia', 'arratsaldea', 'iluntzea', 'gaua']
],
[
'00:00', ['00:00', '06:00'], ['06:00', '12:00'], ['12:00', '14:00'], ['14:00', '19:00'],
['19:00', '21:00'], ['21:00', '24:00']
]
];
//# sourceMappingURL=eu.js.map
|
function Monome( forest , whichHit , whichNote , mesh ){
this.forest = forest;
this.page = this.forest.page;
this.active = false;
this.selected = false;
this.hovered = false;
this.mesh = mesh;
this.mesh.visible = false;
this.mesh.monome = this; // For use in intersections
this.hit = whichHit;
this.noteIndex = whichNote;
this.note = this.page.audio.array[ this.noteIndex ];
/*this.createMaterial();
this.mesh.material = this.material;
this.mesh.material.needsUpdate = true;*/
this.mesh.hoverOver = this.hoverOver.bind( this );
this.mesh.hoverOut = this.hoverOut.bind( this );
this.mesh.select = this.select.bind( this );
// this.mesh.deselect = this.deselect.bind( this );
G.objectControls.add( this.mesh );
this.id = this.page.monomeMeshes.length;
this.page.monomeMeshes.push( this.mesh );
}
Monome.prototype.createMaterial = function(){
var t_iri = THREE.ImageUtils.loadTexture( 'img/iri/comboWet.png' )
this.uniforms = {
hovered:{type:"f" , value:0},
active:{type:"f" , value:0},
selected:{type:"f" , value:0},
t_audio:{ type:"t" , value:this.note.texture},
t_iri:{type:"t",value:t_iri},
lightPos:{type:"v3",value:G.iPoint.relative}
}
this.material = new THREE.ShaderMaterial({
uniforms:this.uniforms,
vertexShader: G.shaders.vertexShaders.monome,
fragmentShader: G.shaders.fragmentShaders.monome,
});
/*
this.material = new THREE.MeshBasicMaterial({
color: new THREE.Color( .5 , .1 ,1 )
});
*/
}
Monome.prototype.update = function( whichHit ){
if( whichHit !== this.hit ){
if( this.active == true ){
this.deactivate();
}
}
if( whichHit === this.hit ){
if( this.active == false ){
this.activate();
}
}
}
Monome.prototype.hoverOver = function(){
if( !this.selected ){
if( this.active == true ){
this.forest.updateActiveTexture( this.hit , this.noteIndex , 1 , 0 , 1 , 0 );
}else{
this.forest.updateActiveTexture( this.hit , this.noteIndex , 1 , 0 , 0 , 0 );
}
}else{
if( this.active == true ){
this.forest.updateActiveTexture( this.hit , this.noteIndex , 1 , 1 , 1 , 0 );
}else{
this.forest.updateActiveTexture( this.hit , this.noteIndex , 1 , 1 , 0 , 0 );
}
}
this.hovered = true;
// this.uniforms.hovered.value = 1;
}
Monome.prototype.hoverOut = function(){
if( !this.selected ){
if( this.active == true ){
this.forest.updateActiveTexture( this.hit , this.noteIndex , 0 , 0 , 1 , 0 );
}else{
this.forest.updateActiveTexture( this.hit , this.noteIndex , 0 , 0 , 0 , 0 );
}
}else{
if( this.active == true ){
this.forest.updateActiveTexture( this.hit , this.noteIndex , 0 , 1 , 1 , 0 );
}else{
this.forest.updateActiveTexture( this.hit , this.noteIndex , 0 , 1 , 0 , 0 );
}
}
this.hovered = false;
//this.uniforms.hovered.value = 0;
}
//
Monome.prototype.select = function(){
// this.note.play();
//console.log( this.id );
if( this.selected === false ){
if( this.active == true ){
this.forest.updateActiveTexture( this.hit , this.noteIndex , 1 , 1 , 1 , 0 );
}else{
this.forest.updateActiveTexture( this.hit , this.noteIndex , 1 , 1 , 0 , 0 );
}
this.selected = true;
//this.uniforms.selected.value = 1;
}else{
if( this.active == true ){
this.forest.updateActiveTexture( this.hit , this.noteIndex , 1 , 0 , 1 , 0 );
}else{
this.forest.updateActiveTexture( this.hit , this.noteIndex , 1 , 0 , 0 , 0 );
}
this.selected = false;
//this.uniforms.selected.value = 0;
}
}
Monome.prototype.deselect = function(){
if( this.active == true ){
this.forest.updateActiveTexture( this.hit , this.noteIndex , 1 , 0 , 1 , 0 );
}else{
this.forest.updateActiveTexture( this.hit , this.noteIndex , 1 , 0 , 0 , 0 );
}
this.selected = false;
//this.uniforms.selected.value = 0;
}
Monome.prototype.activate = function(){
this.active = true;
//this.mesh.material =this.activeMaterial;
//his.mesh.materialNeedsUpdate = true;
//this.uniforms.active.value = 1;
if( this.selected ){
if( this.hovered == true ){
this.forest.updateActiveTexture( this.hit , this.noteIndex , 1 , 1 , 1 , 0 );
}else{
this.forest.updateActiveTexture( this.hit , this.noteIndex , 0 , 1 , 1 , 0 );
}
this.note.play();
}else{
if( this.hovered == true ){
this.forest.updateActiveTexture( this.hit , this.noteIndex , 1 , 0 , 1 , 0 );
}else{
this.forest.updateActiveTexture( this.hit , this.noteIndex , 0 , 0 , 1 , 0 );
}
}
}
Monome.prototype.deactivate = function(){
this.active = false;
//this.uniforms.active.value = 0;
if( this.selected ){
if( this.hovered == true ){
this.forest.updateActiveTexture( this.hit , this.noteIndex , 1 , 1 , 0 , 0 );
}else{
this.forest.updateActiveTexture( this.hit , this.noteIndex , 0 , 1 , 0 , 0 );
}
}else{
if( this.hovered == true ){
this.forest.updateActiveTexture( this.hit , this.noteIndex , 1 , 0 , 0 , 0 );
}else{
this.forest.updateActiveTexture( this.hit , this.noteIndex , 0 , 0 , 0 , 0 );
}
}
}
|
'use strict';
describe('E2E: tests for the page routing', function () {
it('should have a working / route', function () {
});
// describe('Employee Page', function() {
//
// beforeEach(function () {
// browser().navigateTo('/taxcalculator/#/employees');
// });
//
// it('should generate 4 employees', function() {
// input('GenerateEmployeesModel.employeesCount').enter('4');
// element('#generateEmployeesSubmit').click();
// expect(element('[ng-view] table tr.employeeRow').count()).toBe(4);
// });
// });
});
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: |
When the Object constructor is called with one argument value and
the type of value is Number, return ToObject(number)
es5id: 15.2.2.1_A5_T3
description: Argument value is Infinity
---*/
var num = Infinity;
//CHECK#1
if (typeof num !== 'number') {
$ERROR('#1: Infinity is NOT a number');
}
var n_obj = new Object(num);
//CHECK#2
if (n_obj.constructor !== Number) {
$ERROR('#2: When the Object constructor is called with Number argument return ToObject(number)');
}
//CHECK#3
if (typeof n_obj !== 'object') {
$ERROR('#3: When the Object constructor is called with Number argument return ToObject(number)');
}
//CHECK#4
if (n_obj != num) {
$ERROR('#4: When the Object constructor is called with Number argument return ToObject(number)');
}
//CHECK#5
if (n_obj === num) {
$ERROR('#5: When the Object constructor is called with Number argument return ToObject(number)');
}
|
"use strict";
const batch_size = 1100;
class DataGenerator {
constructor() {
this._enabled = false;
this._data = [];
}
enable() {
this._enabled = true;
}
disable() {
this._enabled = false;
}
next() {
if (!this._enabled) {
return false;
}
if (this._data.length === 0) {
this._data = [];
for (let i = 0; i < batch_size; i++) {
this._data.push({ a: i });
}
return null;
} else {
return this._data.pop();
}
}
}
class MySpout {
constructor() {
this._name = null;
this._prefix = "";
this._generator = new DataGenerator();
//this._waiting_for_ack = false;
}
init(name, config, context, callback) {
this._context = context;
this._name = name;
this._prefix = `[InprocSpout ${this._name}]`;
console.log(this._prefix, "Inside init:", config);
callback();
}
heartbeat() { }
shutdown(callback) {
callback();
}
run() {
this._generator.enable();
}
pause() {
this._generator.disable();
}
next(callback) {
let data = this._generator.next();
callback(null, data, null/*, (err, xcallback) => {
this._waiting_for_ack = false;
if (xcallback) {
xcallback();
}
}*/);
}
}
////////////////////////////////////////////////////////////////////////////////
exports.MySpout = MySpout;
|
Ext.define('icc.view.idatabase.Statistic.Grid', {
extend: 'Ext.grid.Panel',
alias: 'widget.idatabaseStatisticGrid',
requires: ['icc.common.Paging', 'icc.view.common.Combobox.Boolean'],
collapsible: false,
closable: false,
multiSelect: false,
disableSelection: false,
sortableColumns: false,
initComponent: function() {
var me = this;
var store = Ext.create('icc.store.idatabase.Statistic');
store.proxy.extraParams = {
'__PROJECT_ID__': me.__PROJECT_ID__,
'__COLLECTION_ID__': me.__COLLECTION_ID__,
'__PLUGIN_ID__': me.__PLUGIN_ID__,
'__PLUGIN_COLLECTION_ID__': me.__PLUGIN_COLLECTION_ID__
};
store.load();
Ext.apply(me, {
store: store,
bbar: {
xtype: 'paging',
store: store
},
selType: 'rowmodel',
plugins: [Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 2
})],
dockedItems: [{
xtype: 'toolbar',
dock: 'top',
items: [{
text: '操作',
iconCls: 'menu',
width: 100,
menu: {
xtype: 'menu',
plain: true,
items: [{
xtype: 'button',
text: '新增',
iconCls: 'add',
action: 'add'
}, {
xtype: 'button',
text: '编辑',
iconCls: 'edit',
action: 'edit'
}, {
xtype: 'button',
text: '保存',
iconCls: 'save',
action: 'save'
}, {
xtype: 'button',
text: '删除',
iconCls: 'remove',
action: 'remove'
}]
}
}]
}],
columns: [{
text: '_id',
dataIndex: '_id',
hidden: true
}, {
text: '名称',
dataIndex: 'name',
flex: 1,
field: {
xtype: 'textfield',
allowBlank: false
}
}, {
text: '类型',
dataIndex: 'seriesType',
flex: 1,
field: {
xtype: 'combobox',
store: 'idatabase.Statistic.Series',
displayField: 'name',
valueField: 'value',
queryMode: 'local',
pageSize: 0,
editable: false,
typeAhead: false
},
renderer: function(value) {
var store = Ext.data.StoreManager.lookup('idatabase.Statistic.Series');
var record = store.findRecord('value', value, 0, false, true, true);
if (record != null) {
return record.get('name');
}
return value;
}
}, {
text: '执行间隔',
dataIndex: 'interval',
flex: 1,
field: {
xtype: 'numberfield'
}
}, {
xtype: 'datecolumn',
text: '更新时间',
dataIndex: 'lastExecuteTime',
flex: 1,
format : 'Y-m-d H:i:s'
}, {
xtype: 'booleancolumn',
trueText: '√',
falseText: '×',
text: '统计中……',
dataIndex: 'isRunning',
flex: 1,
field: {
xtype: 'commonComboboxBoolean'
}
}, {
xtype: 'datecolumn',
text: '创建时间',
dataIndex: '__CREATE_TIME__',
flex: 1,
format: 'Y-m-d',
hidden: true
}]
});
me.callParent();
}
});
|
require('chai').should();
var fakeweb = require('node-fakeweb');
var path = require('path');
var helper = require(path.join(__dirname, '..', '..', 'support',
'locker-helper.js'));
var follows = require(path.join('services', 'instagram', 'follows.js'));
var feed = require(path.join('services', 'instagram', 'feed.js'));
describe("Instagram connector", function () {
var pinfo;
var apiBase = "https://api.instagram.com:443/v1/";
beforeEach(function () {
fakeweb.allowNetConnect = false;
pinfo = helper.loadFixture(path.join(__dirname, '..', '..', 'fixtures',
'connectors', 'instagram.json'));
});
afterEach(function () {
fakeweb.tearDown();
});
describe("follows synclet", function () {
beforeEach(function () {
fakeweb.registerUri({
uri: apiBase + '/users/self/follows?access_token=token&count=100',
file: __dirname + '/../../fixtures/synclets/instagram/follows.json'
});
});
it('can fetch friend information', function (done) {
follows.sync(pinfo, function (err, response) {
if (err) return done(err);
response.data['contact:42@instagram/follows'][0].id.should
.equal('8327977');
done();
});
});
});
describe("feed synclet", function () {
beforeEach(function () {
fakeweb.registerUri({
uri: apiBase + '/users/self/feed?access_token=token&count=100',
file: __dirname + '/../../fixtures/synclets/instagram/feed.json'
});
});
it('can fetch feed', function (done) {
pinfo.config = {};
feed.sync(pinfo, function (err, response) {
if (err) return done(err);
response.data['photo:42@instagram/feed'][0].id.should
.equal('166833681386450342_1802');
done();
});
});
});
});
|
"use strict";
var assert = require("@sinonjs/referee").assert;
var proxyquire = require("proxyquire");
var colors = [
{ name: "bold", code: 1 },
{ name: "cyan", code: 96 },
{ name: "green", code: 32 },
{ name: "red", code: 31 },
{ name: "white", code: 39 },
];
describe("color", function () {
describe("when environment supports color", function () {
var color;
beforeEach(function () {
color = proxyquire("../../../lib/sinon/color", {
"supports-color": {
stdout: true,
},
});
});
// eslint-disable-next-line mocha/no-setup-in-describe
colors.forEach(function (method) {
// eslint-disable-next-line mocha/no-setup-in-describe
describe(method.name, function () {
it("should return a colored string", function () {
var string = "lorem ipsum";
var actual = color[method.name](string);
assert.contains(actual, `${method.code}m${string}`);
});
});
});
});
describe("when environment does not support color", function () {
var color;
beforeEach(function () {
color = proxyquire("../../../lib/sinon/color", {
"supports-color": {
stdout: false,
},
});
});
// eslint-disable-next-line mocha/no-setup-in-describe
colors.forEach(function (method) {
// eslint-disable-next-line mocha/no-setup-in-describe
describe(method.name, function () {
it("should return a regular string", function () {
var string = "lorem ipsum";
var actual = color[method.name](string);
assert.equals(actual, string);
});
});
});
});
});
|
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
import Ember from 'ember';
import {
moduleFor, test
}
from 'ember-qunit';
var options, validator, message;
var set = Ember.set;
moduleFor('validator:length', 'Unit | Validator | length', {
needs: ['validator:messages'],
setup: function() {
validator = this.subject();
}
});
test('no options', function(assert) {
assert.expect(1);
message = validator.validate();
assert.equal(message, true);
});
test('allow blank', function(assert) {
assert.expect(2);
options = {
allowBlank: true,
min: 5
};
set(validator, 'options', options);
message = validator.validate();
assert.equal(message, true);
message = validator.validate('test');
assert.equal(message, 'This field is too short (minimum is 5 characters)');
});
test('is', function(assert) {
assert.expect(2);
options = {
is: 4
};
set(validator, 'options', options);
message = validator.validate('testing');
assert.equal(message, 'This field is the wrong length (should be 4 characters)');
message = validator.validate('test');
assert.equal(message, true);
});
test('min', function(assert) {
assert.expect(2);
options = {
min: 5
};
set(validator, 'options', options);
message = validator.validate('test');
assert.equal(message, 'This field is too short (minimum is 5 characters)');
message = validator.validate('testing');
assert.equal(message, true);
});
test('max', function(assert) {
assert.expect(2);
options = {
max: 5
};
set(validator, 'options', options);
message = validator.validate('testing');
assert.equal(message, 'This field is too long (maximum is 5 characters)');
message = validator.validate('test');
assert.equal(message, true);
});
test('message function', function(assert) {
assert.expect(1);
options = {
max: 5,
message: function(type, options, value) {
return "is too long brosef. It like cant be more than like %@ characters";
}
};
set(validator, 'options', options);
message = validator.validate('testing');
assert.equal(message, 'This field is too long brosef. It like cant be more than like 5 characters');
});
|
function calculateLateDays(inputDate){
let select_menu = document.getElementById("g_id");
if(select_menu.selectedIndex === 0){
alert("Please select a gradeable first!");
return;
}
var due_date_value = select_menu.options[select_menu.selectedIndex].getAttribute("data-due-date");
var new_due_date = new Date(inputDate);
var old_due_date = new Date(due_date_value);
var delta = (new_due_date.getTime() - old_due_date.getTime()) / (1000*60*60*24);
if (delta < 0) {
delta = 0;
}
var diff = Math.floor(delta);
document.getElementById("late_days").value = diff;
}
$(document).ready(function() {
flatpickr("#late-calendar", {
plugins: [ShortcutButtonsPlugin(
{
button: [
{
label: "Now"
},
{
label: "End of time"
}
],
label: "or",
onClick: (index, fp) => {
let date;
switch (index) {
case 0:
date = new Date();
break;
case 1:
date = new Date("9998-01-01");
break;
}
fp.setDate(date, true);
}
}
)],
allowInput: true,
enableTime: false,
enableSeconds: false,
time_24hr: true,
dateFormat: "Y-m-d",
onChange: function(selectedDates, dateStr, instance) {
calculateLateDays(selectedDates[0]);
},
});
});
function updateLateDays(data) {
var fd = new FormData($('#late-day-form').get(0));
var selected_csv_option = $("input:radio[name=csv_option]:checked").val();
var url = buildCourseUrl(['late_days', 'update']) + '?csv_option=' + selected_csv_option;
$.ajax({
url: url,
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function() {
window.location.reload();
},
error: function() {
window.alert("Something went wrong. Please try again.");
}
})
return false;
}
function deleteLateDays(user_id, datestamp) {
// Convert 'MM/DD/YYYY HH:MM:SS A' to 'MM/DD/YYYY'
//datestamp_mmddyy = datestamp.split(" ")[0];
var url = buildCourseUrl(['late_days', 'delete']);
var confirm = window.confirm("Are you sure you would like to delete this entry?");
if (confirm) {
$.ajax({
url: url,
type: "POST",
data: {
csrf_token: csrfToken,
user_id: user_id,
datestamp: datestamp
},
success: function() {
window.location.reload();
},
error: function() {
window.alert("Something went wrong. Please try again.");
}
})
}
}
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("uicolor","tr",{title:"UI Renk Seçicisi",preview:"Canlı önizleme",config:"Bu dizeyi config.js dosyasının içine yapıştırın",predefined:"Önceden tanımlanmış renk kümeleri"});
|
'use strict';
var t = require('babel-types');
/**
* Try to find the part of JavaScript a comment is referring to, by
* looking at the syntax tree closest to that comment.
*
* @param {Object} path abstract syntax tree path
* @returns {?Object} ast path, if one is found.
* @private
*/
function findTarget(path) {
if (!path) {
return path;
}
if (t.isExportDefaultDeclaration(path) || t.isExportNamedDeclaration(path) && path.has('declaration')) {
path = path.get('declaration');
}
if (t.isVariableDeclaration(path)) {
// var x = init;
path = path.get('declarations')[0];
} else if (t.isExpressionStatement(path)) {
// foo.x = TARGET
path = path.get('expression').get('right');
} else if (t.isObjectProperty(path)) {
// var foo = { x: TARGET };
path = path.get('value');
}
return path.node && path;
}
module.exports.findTarget = findTarget;
|
/************
TODO :
TEL ALEXANDRE 21.01.2016
- tooltip entreprise: quel département paie ? quelle catégorie de services ?
- catégories: nettoyer données pour n'avoir que les 22 catégories principales
- prévoir chargement des données avec un fichier par année / langue
A DISCUTER
~ - quoi afficher dans détails
√ - comment faire figurer montant connus / inconnus (ma suggestion: pas dans sunburst)
HIGH
√ - calculer pourcentages dans données (0.5h : 16:00)
~ - multilingue : à discuter -> fichier lang.fr.js importé dans .html et qui crée une variable globale ?
Probablement le plus simple...
CONVENU CAFE DE GRANCY
√ - fixed-tooltip à cacher sur mobile
√ - tooltip: afficher aussi on mouse-over du breadcrumb (1h - 15:30)
~ - catégories : sparkline similaire NY times pour vue détaillée, fonction qui le fait (+ icônes?) -> refactor disposition
√ - détails, comme dans carnet
√ - résumé dans structures bootstrap plutôt que table
√ - switch années au-dessous sunburst "Année: 2011 2012 2013 etc."
√ - intégrer données Alex
√ - refactor données pour calculer la valeur des 'Unknown'
- basic tracking analytics
- show more ? cf. http://jsfiddle.net/KyleMit/MD2FP/
0- tooltip sur entreprise: table avec catégories de dépenses (reprendre icônes ?)
0- dernier niveau (seulement) -> ajouter le type de prestation, par ex. avec icône ?
X - label sunburst : mettre % en + sur les plus gros (si place)
MIDDLE
√ garder "état de la visualisation" quand on change d'année ? (= actuel filter, je pense, garder le datum actuel...)
√- Meilleur passage des années (pas reconstruire le SVG...)
- pym.js
X - "polissage" par Inventaire ?
LOW
√ - Breadcrumb sur mobile (pas d'overlap)
~ - object persistence (bars + pies)
~ - vraies données
√ - use breadcrumb from bootstrap
X- transition pour bar chart
0- interaction continue sur mobile pour sunburst (y.c. fixed tooltip -> différencier avec media queries ?)
=> voir aussi http://bl.ocks.org/mbostock/770ae19ca830a4ce87f5 -> listener ailleurs ? laisser tomber ?
√ - générer un breadcrumb plus évolué ? cf. http://bl.ocks.org/kerryrodden/7090426
√ - refactoring : modules ! -> sortir le traitement des data et préparation pour les deux viz
√ - tooltip: dans sunburst une zone fixe plutôt ?? Sous le breadcrumb par ex. ?
√ - highlight sunburst en masquant les autres (baisser opacité)
√ - rendre interaction indépendante du clic -> avoir une fonction "showDetail(dept)"
√ - update showDetail to provide data in argument, not dept name
---------
On updateable sunburst when year changes:
- ideally, should create sunburst with 'complete' structure (i.e. all depts, all years, with key function
associating data with paths), then update it based on only the current year.
---------
*******************/
|
/* jslint indent: 2 */
/* global $: false, document: false, togglbutton: false */
'use strict';
togglbutton.render('.review-request:not(.toggl)', { observe: true }, function () {
const description = $('#field_summary').textContent;
const projectName = $('#field_repository').textContent;
const li = document.createElement('li');
const link = togglbutton.createTimerLink({
className: 'reviewboard',
description: description,
projectName: projectName
});
li.appendChild(link);
$('.review-request-actions-left').appendChild(li);
});
|
'use strict';
angular.module("ngLocale", [], ["$provide", function ($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u0e01\u0e48\u0e2d\u0e19\u0e40\u0e17\u0e35\u0e48\u0e22\u0e07",
"\u0e2b\u0e25\u0e31\u0e07\u0e40\u0e17\u0e35\u0e48\u0e22\u0e07"
],
"DAY": [
"\u0e27\u0e31\u0e19\u0e2d\u0e32\u0e17\u0e34\u0e15\u0e22\u0e4c",
"\u0e27\u0e31\u0e19\u0e08\u0e31\u0e19\u0e17\u0e23\u0e4c",
"\u0e27\u0e31\u0e19\u0e2d\u0e31\u0e07\u0e04\u0e32\u0e23",
"\u0e27\u0e31\u0e19\u0e1e\u0e38\u0e18",
"\u0e27\u0e31\u0e19\u0e1e\u0e24\u0e2b\u0e31\u0e2a\u0e1a\u0e14\u0e35",
"\u0e27\u0e31\u0e19\u0e28\u0e38\u0e01\u0e23\u0e4c",
"\u0e27\u0e31\u0e19\u0e40\u0e2a\u0e32\u0e23\u0e4c"
],
"ERANAMES": [
"\u0e1b\u0e35\u0e01\u0e48\u0e2d\u0e19\u0e04\u0e23\u0e34\u0e2a\u0e15\u0e4c\u0e28\u0e31\u0e01\u0e23\u0e32\u0e0a",
"\u0e04\u0e23\u0e34\u0e2a\u0e15\u0e4c\u0e28\u0e31\u0e01\u0e23\u0e32\u0e0a"
],
"ERAS": [
"\u0e1b\u0e35\u0e01\u0e48\u0e2d\u0e19 \u0e04.\u0e28.",
"\u0e04.\u0e28."
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"\u0e21\u0e01\u0e23\u0e32\u0e04\u0e21",
"\u0e01\u0e38\u0e21\u0e20\u0e32\u0e1e\u0e31\u0e19\u0e18\u0e4c",
"\u0e21\u0e35\u0e19\u0e32\u0e04\u0e21",
"\u0e40\u0e21\u0e29\u0e32\u0e22\u0e19",
"\u0e1e\u0e24\u0e29\u0e20\u0e32\u0e04\u0e21",
"\u0e21\u0e34\u0e16\u0e38\u0e19\u0e32\u0e22\u0e19",
"\u0e01\u0e23\u0e01\u0e0e\u0e32\u0e04\u0e21",
"\u0e2a\u0e34\u0e07\u0e2b\u0e32\u0e04\u0e21",
"\u0e01\u0e31\u0e19\u0e22\u0e32\u0e22\u0e19",
"\u0e15\u0e38\u0e25\u0e32\u0e04\u0e21",
"\u0e1e\u0e24\u0e28\u0e08\u0e34\u0e01\u0e32\u0e22\u0e19",
"\u0e18\u0e31\u0e19\u0e27\u0e32\u0e04\u0e21"
],
"SHORTDAY": [
"\u0e2d\u0e32.",
"\u0e08.",
"\u0e2d.",
"\u0e1e.",
"\u0e1e\u0e24.",
"\u0e28.",
"\u0e2a."
],
"SHORTMONTH": [
"\u0e21.\u0e04.",
"\u0e01.\u0e1e.",
"\u0e21\u0e35.\u0e04.",
"\u0e40\u0e21.\u0e22.",
"\u0e1e.\u0e04.",
"\u0e21\u0e34.\u0e22.",
"\u0e01.\u0e04.",
"\u0e2a.\u0e04.",
"\u0e01.\u0e22.",
"\u0e15.\u0e04.",
"\u0e1e.\u0e22.",
"\u0e18.\u0e04."
],
"STANDALONEMONTH": [
"\u0e21\u0e01\u0e23\u0e32\u0e04\u0e21",
"\u0e01\u0e38\u0e21\u0e20\u0e32\u0e1e\u0e31\u0e19\u0e18\u0e4c",
"\u0e21\u0e35\u0e19\u0e32\u0e04\u0e21",
"\u0e40\u0e21\u0e29\u0e32\u0e22\u0e19",
"\u0e1e\u0e24\u0e29\u0e20\u0e32\u0e04\u0e21",
"\u0e21\u0e34\u0e16\u0e38\u0e19\u0e32\u0e22\u0e19",
"\u0e01\u0e23\u0e01\u0e0e\u0e32\u0e04\u0e21",
"\u0e2a\u0e34\u0e07\u0e2b\u0e32\u0e04\u0e21",
"\u0e01\u0e31\u0e19\u0e22\u0e32\u0e22\u0e19",
"\u0e15\u0e38\u0e25\u0e32\u0e04\u0e21",
"\u0e1e\u0e24\u0e28\u0e08\u0e34\u0e01\u0e32\u0e22\u0e19",
"\u0e18\u0e31\u0e19\u0e27\u0e32\u0e04\u0e21"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE\u0e17\u0e35\u0e48 d MMMM G y",
"longDate": "d MMMM G y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "d/M/yy HH:mm",
"shortDate": "d/M/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u0e3f",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "th",
"localeID": "th",
"pluralCat": function (n, opt_precision) {
return PLURAL_CATEGORY.OTHER;
}
});
}]);
|
// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var Event = require('org.chromium.common.events');
var exec = cordova.require('cordova/exec');
var callbackWithError = require('org.chromium.common.errors').callbackWithError;
exports.create = function(properties /** optional */, callback) {
if (typeof properties == 'function') {
callback = properties;
properties = {};
}
var win = callback && function(socketId) {
var createInfo = {
socketId: socketId
};
callback(createInfo);
};
exec(win, null, 'ChromeSocketsTcpServer', 'create', [properties]);
};
exports.update = function(socketId, properties, callback) {
exec(callback, null, 'ChromeSocketsTcpServer', 'update', [socketId, properties]);
};
exports.setPaused = function(socketId, paused, callback) {
exec(callback, null, 'ChromeSocketsTcpServer', 'setPaused', [socketId, paused]);
};
exports.listen = function(socketId, address, port, backlog /** optional */, callback) {
if (typeof backlog == 'function') {
callback = backlog;
backlog = null; /** Use SOMAXCONN */
}
var win = callback && function() {
callback(0);
};
var fail = callback && function(error) {
callbackWithError(error.message, callback, error.resultCode);
};
exec(win, fail, 'ChromeSocketsTcpServer', 'listen', [socketId, address, port, backlog]);
};
exports.disconnect = function(socketId, callback) {
exec(callback, null, 'ChromeSocketsTcpServer', 'disconnect', [socketId]);
};
exports.close = function(socketId, callback) {
exec(callback, null, 'ChromeSocketsTcpServer', 'close', [socketId]);
};
exports.getInfo = function(socketId, callback) {
var win = callback && function(result) {
result.persistent = !!result.persistent;
result.paused = !!result.paused;
callback(result);
};
exec(win, null, 'ChromeSocketsTcpServer', 'getInfo', [socketId]);
};
exports.getSockets = function(callback) {
var win = callback && function(results) {
for (var result in results) {
result.persistent = !!result.persistent;
result.paused = !!result.paused;
}
callback(results);
};
exec(win, null, 'ChromeSocketsTcpServer', 'getSockets', []);
};
exports.onAccept = new Event('onAccept');
exports.onAcceptError = new Event('onAcceptError');
function registerAcceptEvents() {
var win = function(info) {
exports.onAccept.fire(info);
};
var fail = function(info) {
var error = function() {
exports.onAcceptError.fire(info);
};
callbackWithError(info.message, error);
};
exec(win, fail, 'ChromeSocketsTcpServer', 'registerAcceptEvents', []);
}
require('org.chromium.common.helpers').runAtStartUp(registerAcceptEvents);
|
var client;
self.addEventListener('crossoriginconnect', function(event) {
client = event.client;
event.acceptConnection(true);
});
self.addEventListener('crossoriginmessage', function(event) {
client.postMessage(event.data, event.ports);
});
navigator.services.addEventListener('connect', function(event) {
event.respondWith({accept: true}).then(function(port) { client = port; });
});
|
import React from 'react';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import Header from './Header';
const mockProps = ( overrides) => ({ // eslint-disable-line no-unused-vars
user: {},
ws_notification: [],
consumeNotification: () => {},
...overrides
});
const wrapper = shallow(<Header {...mockProps()} />);
describe('(Component) Header', () => {
it('renders without exploding', () => {
expect(wrapper).to.have.lengthOf(1);
});
});
|
/*eslint-env mocha*/
/*global BOOMR_test,assert*/
describe("e2e/14-errors/12-events-xhr", function() {
var tf = BOOMR.plugins.TestFramework;
var t = BOOMR_test;
var C = BOOMR.utils.Compression;
if (!BOOMR.plugins.AutoXHR) {
it("Skipping on non-AutoXHR supporting browser", function() {
return this.skip();
});
return;
}
it("Should have only sent one page load beacon", function(done) {
this.timeout(10000);
t.ensureBeaconCount(done, 1);
});
it("Should have put the err on the page load beacon", function() {
var b = tf.lastBeacon();
assert.isDefined(b.err);
});
it("Should have had a single error", function() {
var b = tf.lastBeacon();
assert.equal(BOOMR.plugins.Errors.decompressErrors(C.jsUrlDecompress(b.err)).length, 1);
});
it("Should have count = 1", function() {
var b = tf.lastBeacon();
var err = BOOMR.plugins.Errors.decompressErrors(C.jsUrlDecompress(b.err))[0];
assert.equal(err.count, 1);
});
it("Should have fileName of the page (if set)", function() {
var b = tf.lastBeacon();
var err = BOOMR.plugins.Errors.decompressErrors(C.jsUrlDecompress(b.err))[0];
if (err.fileName) {
assert.include(err.fileName, window.location.pathname.substring(window.location.pathname.lastIndexOf("/") + 1));
}
else {
return this.skip();
}
});
it("Should have functionName of 'errorFunction'", function() {
var b = tf.lastBeacon();
var err = BOOMR.plugins.Errors.decompressErrors(C.jsUrlDecompress(b.err))[0];
if (err.functionName) {
assert.include(err.functionName, "errorFunction");
}
else {
return this.skip();
}
});
it("Should have message = 'a is not defined' or 'Can't find variable: a' or ''a' is undefined'", function() {
var b = tf.lastBeacon();
var err = BOOMR.plugins.Errors.decompressErrors(C.jsUrlDecompress(b.err))[0];
// Chrome, Firefox == a is not defined, Safari = Can't find variable, Edge = 'a' is not defined
assert.isTrue(
err.message.indexOf("a is not defined") !== -1 ||
err.message.indexOf("Can't find variable: a") !== -1 ||
err.message.indexOf("'a' is undefined") !== -1 ||
err.message.indexOf("'a' is not defined") !== -1);
});
it("Should have source = APP", function() {
var b = tf.lastBeacon();
var err = BOOMR.plugins.Errors.decompressErrors(C.jsUrlDecompress(b.err))[0];
assert.equal(err.source, BOOMR.plugins.Errors.SOURCE_APP);
});
it("Should have stack with the stack", function() {
var b = tf.lastBeacon();
var err = BOOMR.plugins.Errors.decompressErrors(C.jsUrlDecompress(b.err))[0];
assert.isDefined(err.stack);
});
it("Should have not have BOOMR_plugins_errors_wrap on the stack", function() {
var b = tf.lastBeacon();
var err = BOOMR.plugins.Errors.decompressErrors(C.jsUrlDecompress(b.err))[0];
assert.notInclude(err.stack, "BOOMR_plugins_errors_wrap");
});
it("Should have type = 'ReferenceError' or 'Error'", function() {
var b = tf.lastBeacon();
var err = BOOMR.plugins.Errors.decompressErrors(C.jsUrlDecompress(b.err))[0];
assert.isTrue(err.type === "ReferenceError" || err.type === "Error");
});
it("Should have via = EVENTHANDLER", function() {
var b = tf.lastBeacon();
var err = BOOMR.plugins.Errors.decompressErrors(C.jsUrlDecompress(b.err))[0];
assert.equal(err.via, BOOMR.plugins.Errors.VIA_EVENTHANDLER);
});
it("Should have columNumber to be a number if specified", function() {
var b = tf.lastBeacon();
var err = BOOMR.plugins.Errors.decompressErrors(C.jsUrlDecompress(b.err))[0];
if (typeof err.columnNumber !== "undefined") {
assert.isTrue(err.columnNumber >= 0);
}
else {
return this.skip();
}
});
it("Should have lineNumber ~ " + (HEADER_LINES + 20), function() {
var b = tf.lastBeacon();
var err = BOOMR.plugins.Errors.decompressErrors(C.jsUrlDecompress(b.err))[0];
if (err.lineNumber) {
assert.closeTo(err.lineNumber, HEADER_LINES + 20, 5);
}
else {
return this.skip();
}
});
});
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2012, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define(function (require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var TerraformHighlightRules = require("./terraform_highlight_rules").TerraformHighlightRules;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Mode = function () {
TextMode.call(this);
this.HighlightRules = TerraformHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function () {
this.$id = "ace/mode/terraform";
}).call(Mode.prototype);
exports.Mode = Mode;
});
|
var searchData=
[
['check_5fpersistent_5fptr_5farray_2ehpp_237',['check_persistent_ptr_array.hpp',['../check__persistent__ptr__array_8hpp.html',1,'']]],
['common_2ehpp_238',['common.hpp',['../common_8hpp.html',1,'']]],
['condition_5fvariable_2ehpp_239',['condition_variable.hpp',['../condition__variable_8hpp.html',1,'']]],
['contiguous_5fiterator_2ehpp_240',['contiguous_iterator.hpp',['../contiguous__iterator_8hpp.html',1,'']]],
['conversions_2ehpp_241',['conversions.hpp',['../conversions_8hpp.html',1,'']]]
];
|
import { Observable } from 'rxjs/Observable';
import 'firebase/database';
import * as utils from './utils';
export class FirebaseListObservable extends Observable {
constructor($ref, subscribe) {
super(subscribe);
this.$ref = $ref;
}
lift(operator) {
const observable = new FirebaseListObservable(this.$ref);
observable.source = this;
observable.operator = operator;
observable.$ref = this.$ref;
return observable;
}
push(val) {
if (!this.$ref) {
throw new Error('No ref specified for this Observable!');
}
return this.$ref.ref.push(val);
}
set(item, value) {
return this._checkOperationCases(item, {
stringCase: () => this.$ref.ref.child(item).set(value),
firebaseCase: () => item.set(value),
snapshotCase: () => item.ref.set(value),
unwrappedSnapshotCase: () => this.$ref.ref.child(item.$key).set(value)
});
}
update(item, value) {
return this._checkOperationCases(item, {
stringCase: () => this.$ref.ref.child(item).update(value),
firebaseCase: () => item.update(value),
snapshotCase: () => item.ref.update(value),
unwrappedSnapshotCase: () => this.$ref.ref.child(item.$key).update(value)
});
}
remove(item) {
if (!item) {
return this.$ref.ref.remove();
}
return this._checkOperationCases(item, {
stringCase: () => this.$ref.ref.child(item).remove(),
firebaseCase: () => item.remove(),
snapshotCase: () => item.ref.remove(),
unwrappedSnapshotCase: () => this.$ref.ref.child(item.$key).remove()
});
}
_checkOperationCases(item, cases) {
if (utils.isString(item)) {
return cases.stringCase();
}
else if (utils.isFirebaseRef(item)) {
return cases.firebaseCase();
}
else if (utils.isFirebaseDataSnapshot(item)) {
return cases.snapshotCase();
}
else if (utils.isAFUnwrappedSnapshot(item)) {
return cases.unwrappedSnapshotCase();
}
throw new Error(`Method requires a key, snapshot, reference, or unwrapped snapshot. Got: ${typeof item}`);
}
}
//# sourceMappingURL=firebase_list_observable.js.map
|
KISSY.add(function(S,Cookie) {
describe('cookie', function() {
if (location.protocol === 'file:') {
return;
}
describe('get', function() {
document.cookie = '_ks_test_1=1';
document.cookie = '_ks_test_2=';
document.cookie = '_ks_test_3=';
it('should return the cookie value for the given name', function() {
expect(Cookie.get('_ks_test_1')).toBe('1');
expect(Cookie.get('_ks_test_2')).toBe('');
expect(Cookie.get('_ks_test_3')).toBe('');
});
it('should return undefined for non-existing name', function() {
expect(Cookie.get('_ks_test_none')).toBeUndefined();
expect(Cookie.get(true)).toBeUndefined();
expect(Cookie.get({})).toBeUndefined();
expect(Cookie.get(null)).toBeUndefined();
});
});
describe('set', function() {
it('should set a cookie with a given name and value', function() {
Cookie.set('_ks_test_11', 'xx');
expect(Cookie.get('_ks_test_11')).toBe('xx');
Cookie.set('_ks_test_12', 'xx', 0);
expect(Cookie.get('_ks_test_12')).toBeUndefined();
Cookie.set('_ks_test_13', '1', new Date(2099, 1, 1), '', '/');
Cookie.set('_ks_test_13', '2', new Date(2099, 1, 1), '', '/');
expect(Cookie.get('_ks_test_13')).toBe('2');
Cookie.remove('_ks_test_14');
Cookie.set('_ks_test_14', '4', 1, document.domain, '/', true);
expect(Cookie.get('_ks_test_14')).toBeUndefined();
});
});
describe('remove', function() {
it('should remove a cookie from the machine', function() {
Cookie.set('_ks_test_21', 'xx');
Cookie.remove('_ks_test_21');
expect(Cookie.get('_ks_test_21')).toBeUndefined();
Cookie.set('_ks_test_22', 'xx', new Date(2099, 1, 1), '', '/');
Cookie.remove('_ks_test_22', '', '/');
expect(Cookie.get('_ks_test_22')).toBeUndefined();
});
});
});
},{
requires:['cookie']
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _bluebird = require('bluebird');
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
var _fs = require('mz/fs');
var _fs2 = _interopRequireDefault(_fs);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _stringArgv = require('string-argv');
var _stringArgv2 = _interopRequireDefault(_stringArgv);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ProfileLoader = function () {
function ProfileLoader(directory) {
(0, _classCallCheck3.default)(this, ProfileLoader);
this.directory = directory;
}
(0, _createClass3.default)(ProfileLoader, [{
key: 'getDefinitions',
value: function () {
var _ref = (0, _bluebird.coroutine)(function* () {
var definitionsFilePath = _path2.default.join(this.directory, 'cucumber.js');
var exists = yield _fs2.default.exists(definitionsFilePath);
if (!exists) {
return {};
}
var definitions = require(definitionsFilePath);
if ((typeof definitions === 'undefined' ? 'undefined' : (0, _typeof3.default)(definitions)) !== 'object') {
throw new Error(definitionsFilePath + ' does not export an object');
}
return definitions;
});
function getDefinitions() {
return _ref.apply(this, arguments);
}
return getDefinitions;
}()
}, {
key: 'getArgv',
value: function () {
var _ref2 = (0, _bluebird.coroutine)(function* (profiles) {
var definitions = yield this.getDefinitions();
if (profiles.length === 0 && definitions['default']) {
profiles = ['default'];
}
var argvs = profiles.map(function (profile) {
if (!definitions[profile]) {
throw new Error('Undefined profile: ' + profile);
}
return (0, _stringArgv2.default)(definitions[profile]);
});
return _lodash2.default.flatten(argvs);
});
function getArgv(_x) {
return _ref2.apply(this, arguments);
}
return getArgv;
}()
}]);
return ProfileLoader;
}();
exports.default = ProfileLoader;
|
'use strict';
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var config = require('../config');
module.exports = function (gulp) {
gulp.task('test', ['lint'], function (cb) {
gulp.src(['!' + config.paths.cliFile].concat(config.paths.lib))
.pipe(istanbul({
includeUntested: true
}))
.pipe(istanbul.hookRequire())
.on('finish', function () {
gulp.src(config.paths.test)
.pipe(mocha({reporter: 'spec'}))
.pipe(istanbul.writeReports())
.pipe(istanbul.enforceThresholds({thresholds: {global: 100}}))
.on('end', cb);
});
});
};
|
import React, {Component, PropTypes} from 'react';
import RadioButton from '../RadioButton';
import warning from 'warning';
class RadioButtonGroup extends Component {
static propTypes = {
/**
* Should be used to pass `RadioButton` components.
*/
children: PropTypes.node,
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* The `value` property of the radio button that will be
* selected by default. This takes precedence over the `checked` property
* of the `RadioButton` elements.
*/
defaultSelected: PropTypes.any,
/**
* Where the label will be placed for all child radio buttons.
* This takes precedence over the `labelPosition` property of the
* `RadioButton` elements.
*/
labelPosition: PropTypes.oneOf(['left', 'right']),
/**
* The name that will be applied to all child radio buttons.
*/
name: PropTypes.string.isRequired,
/**
* Callback function that is fired when a radio button has
* been checked.
*
* @param {object} event `change` event targeting the selected
* radio button.
* @param {*} value The `value` of the selected radio button.
*/
onChange: PropTypes.func,
/**
* Override the inline-styles of the root element.
*/
style: PropTypes.object,
/**
* The `value` of the currently selected radio button.
*/
valueSelected: PropTypes.any,
};
static defaultProps = {
style: {},
};
static contextTypes = {
muiTheme: PropTypes.object.isRequired,
};
state = {
numberCheckedRadioButtons: 0,
selected: '',
};
componentWillMount() {
let cnt = 0;
let selected = '';
const {valueSelected, defaultSelected} = this.props;
if (valueSelected !== undefined) {
selected = valueSelected;
} else if (defaultSelected !== undefined) {
selected = defaultSelected;
}
React.Children.forEach(this.props.children, (option) => {
if (this.hasCheckAttribute(option)) cnt++;
}, this);
this.setState({
numberCheckedRadioButtons: cnt,
selected,
});
}
componentWillReceiveProps(nextProps) {
if (nextProps.hasOwnProperty('valueSelected')) {
this.setState({
selected: nextProps.valueSelected,
});
}
}
hasCheckAttribute(radioButton) {
return radioButton.props.hasOwnProperty('checked') &&
radioButton.props.checked;
}
updateRadioButtons(newSelection) {
if (this.state.numberCheckedRadioButtons === 0) {
this.setState({selected: newSelection});
} else {
warning(false, `Material-UI: Cannot select a different radio button while another radio button
has the 'checked' property set to true.`);
}
}
handleChange = (event, newSelection) => {
this.updateRadioButtons(newSelection);
// Successful update
if (this.state.numberCheckedRadioButtons === 0) {
if (this.props.onChange) this.props.onChange(event, newSelection);
}
};
getSelectedValue() {
return this.state.selected;
}
setSelectedValue(newSelectionValue) {
this.updateRadioButtons(newSelectionValue);
}
clearValue() {
this.setSelectedValue('');
}
render() {
const {prepareStyles} = this.context.muiTheme;
const options = React.Children.map(this.props.children, (option) => {
const {
name, // eslint-disable-line no-unused-vars
value, // eslint-disable-line no-unused-vars
label, // eslint-disable-line no-unused-vars
onCheck, // eslint-disable-line no-unused-vars
...other
} = option.props;
return (
<RadioButton
{...other}
ref={option.props.value}
name={this.props.name}
key={option.props.value}
value={option.props.value}
label={option.props.label}
labelPosition={this.props.labelPosition}
onCheck={this.handleChange}
checked={option.props.value === this.state.selected}
/>
);
}, this);
return (
<div
style={prepareStyles(Object.assign({}, this.props.style))}
className={this.props.className}
>
{options}
</div>
);
}
}
export default RadioButtonGroup;
|
if(!dojo._hasResource["dojox.highlight.languages._all"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.highlight.languages._all"] = true;
dojo.provide("dojox.highlight.languages._all");
/* groups of similar languages */
dojo.require("dojox.highlight.languages._static");
dojo.require("dojox.highlight.languages._dynamic");
dojo.require("dojox.highlight.languages._www");
}
|
var bunyan = require('bunyan');
var PrettyStream = require('bunyan-prettystream');
var prettyStdOut = new PrettyStream();
prettyStdOut.pipe(process.stdout);
var config = {
name: 'coregi',
streams: [
{
level: process.env.LOG_LEVEL || 'info',
type: 'raw',
stream: prettyStdOut
},
{
type: 'file',
level:'info',
path: 'coregi.log'
}
],
serializers: bunyan.stdSerializers
};
module.exports = function() {
return bunyan.createLogger(config);
};
|
const { join } = require('path')
const { existsSync } = require('fs-extra')
module.exports = ({ base, template }) => {
const localPath = join(base, 'templates', template)
const npmPath = join(base, 'node_modules', template)
if (existsSync(localPath)) {
return localPath
}
let name = template
try {
// eslint-disable-next-line global-require, import/no-dynamic-require
name = require(npmPath).template || template
} catch (e) {
// ignore
}
const templatePath = join(npmPath, 'templates', name)
if (existsSync(templatePath)) {
return templatePath
}
throw new Error(`Template no exist: ${template}`)
}
|
(function() {
'use strict';
app.controller('profileCtrl', ['api', 'constants','commonFactory','url', 'localStorageService',
function(api, constants,commonFactory, url, localStorageService) {
var profile = this;
var profileCallConfig = {
url: url.user.me
};
api.executeCall(profileCallConfig,function(response) {
profile.user = response.data;
});
profile.validateAndSave = function() {
profileCallConfig.method = constants.method.post;
profileCallConfig.data = profile.user;
api.executeCall(profileCallConfig,function(response) {
if(response.data.user_id){
localStorageService.set('user', response.data);
profile.profileError = {type:'success',message:'Profile updated successfully.'};
}
},function(err){
profile.error = err.data;
});
};
}]);
})();
|
import BaseSyntax from './base.js';
/**
* The class to define the TemplateElement syntax
*
* @class TemplateElement
*/
export default
class TemplateElement extends BaseSyntax {
/**
* Create a template literal
*
* @constructor
*/
constructor() {
super('TemplateElement');
this.value = {raw: '', cooked: ''};
this.tail = false;
}
setValue(value) {
this.setRaw(value);
this.setCooked(value);
}
setRaw(raw) {
this.value.raw = raw;
}
setCooked(cooked) {
this.value.cooked = cooked;
}
}
|
//
// Sets up intial project settings, middleware, mounted apps, and
// global configuration such as overriding Backbone.sync and
// populating sharify data
//
var express = require('express'),
Backbone = require('backbone'),
sharify = require('sharify'),
path = require('path'),
fs = require('fs');
module.exports = function(app) {
// Inject some configuration & constant data into sharify
var sd = sharify.data = {
API_URL: process.env.API_URL,
NODE_ENV: process.env.NODE_ENV,
JS_EXT: 'production' == process.env.NODE_ENV ? '.min.js' : '.js',
CSS_EXT: 'production' == process.env.NODE_ENV ? '.min.css' : '.css'
};
// Override Backbone to use server-side sync
Backbone.sync = require('backbone-super-sync');
// Mount sharify
app.use(sharify);
// Development only
if ('development' == sd.NODE_ENV) {
// Compile assets on request in development
app.use(require('stylus').middleware({
src: path.resolve(__dirname, '../'),
dest: path.resolve(__dirname, '../public')
}));
app.use(require('browserify-dev-middleware')({
src: path.resolve(__dirname, '../'),
transforms: [require('jadeify')]
}));
}
// Test only
if('test' == sd.NODE_ENV) {
// Mount fake API server
app.use('/__api', require('../test/helpers/integration.js').api);
}
// Mount apps
app.use('/', function(req, res) {
res.send('Start by writing an app in /apps and mounting it in /lib/setup!');
});
// Mount static middleware for sub apps, components, and project-wide
fs.readdirSync(path.resolve(__dirname, '../apps')).forEach(function(fld) {
app.use(express.static(path.resolve(__dirname, '../apps/' + fld + '/public')));
});
fs.readdirSync(path.resolve(__dirname, '../components')).forEach(function(fld) {
app.use(express.static(path.resolve(__dirname, '../components/' + fld + '/public')));
});
app.use(express.static(path.resolve(__dirname, '../public')));
}
|
'use strict';
const rp = require('minimal-request-promise');
const prompt = require('souffleur');
const tlReply = require('./reply');
const tlParse = require('./parse');
const color = require('../console-colors');
module.exports = function tlSetup(api, bot, logError, optionalParser, optionalResponder) {
let parser = optionalParser || tlParse;
let responder = optionalResponder || tlReply;
api.post('/telegram', request => {
let tlMessage = request.body;
let parsedMessage = parser(tlMessage);
if (!parsedMessage){
return Promise.resolve('ok');
}
return Promise.resolve(parsedMessage).then(parsedMessage => bot(parsedMessage, request))
.then(botResponse => responder(parsedMessage, botResponse, request.env.telegramAccessToken))
.catch(logError);
});
api.addPostDeployStep('telegram', (options, lambdaDetails, utils) => {
return Promise.resolve()
.then(() => {
if (options['configure-telegram-bot']) {
console.log(`\n\n${color.green}Telegram setup${color.reset}\n`);
console.log(`\nFollowing info is required for the setup, for more info check the documentation.\n`);
console.log(`\nYour Telegram bot Request URL (POST only) is ${color.cyan}${lambdaDetails.apiUrl}/telegram${color.reset}\n`);
console.log(`\nIf you want your bot to receive inline queries\n just send /setinline to the @BotFather on your Telegram client and choose your bot\n`);
return prompt(['Telegram Access Token'])
.then(results => {
const deployment = {
restApiId: lambdaDetails.apiId,
stageName: lambdaDetails.alias,
variables: {
telegramAccessToken: results['Telegram Access Token']
}
};
return utils.apiGatewayPromise.createDeploymentPromise(deployment)
.then(() => {
let options = {
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: `${lambdaDetails.apiUrl}/telegram`
})
};
return rp.post(`https://api.telegram.org/bot${deployment.variables.telegramAccessToken}/setWebhook`, options);
});
});
}
})
.then(() => `${lambdaDetails.apiUrl}/telegram`);
});
};
|
import inatjs from "inaturalistjs";
import { showAlert } from "./alert_actions";
const POST_COMMENT = "post_comment";
function postComment( params ) {
return function ( dispatch ) {
const body = Object.assign( {}, params );
// TODO handle error state
return inatjs.comments.create( body ).catch( e => {
dispatch( showAlert(
I18n.t( "failed_to_save_record" ),
{ title: I18n.t( "request_failed" ) }
) );
throw e;
} );
};
}
function deleteComment( comment ) {
return function ( ) {
return inatjs.comments.delete( comment );
};
}
export {
postComment,
POST_COMMENT,
deleteComment
};
|
"use strict";
var dgram = require("dgram");
var mersenne = require("./mersenne");
var mt = new mersenne.MersenneTwister19937();
var EPHEMERAL_LIFETIME_MS = 1000;
var Client = function(host, port, socket, options) {
this.host = host || "localhost";
this.port = port || 8125;
// optional shared socket
this.socket = socket;
// when a *shared* socked isn't provided, an ephemeral
// socket is demand allocated. This ephemeral socket is closed
// after being idle for EPHEMERAL_LIFETIME_MS.
this.ephemeral_socket = this.last_used_timer = null;
options = options || {};
this.global_tags = options.global_tags;
};
Client.prototype.timing = function(stat, time, sample_rate, tags) {
var self = this;
var stats = {};
stats[stat] = time + "|ms";
self.send(stats, sample_rate, tags);
};
Client.prototype.increment = function(stats, sample_rate, tags) {
var self = this;
self.update_stats(stats, 1, sample_rate, tags);
};
Client.prototype.incrementBy = function(stats, value, tags) {
var self = this;
if (value === 0) return;
self.update_stats(stats, value, undefined, tags);
};
Client.prototype.decrement = function(stats, sample_rate, tags) {
var self = this;
self.update_stats(stats, - 1, sample_rate, tags);
};
Client.prototype.decrementBy = function(stats, value, tags) {
var self = this;
if (value === 0) return;
self.update_stats(stats, -value, undefined, tags);
};
Client.prototype.gauge = function(stat, value, sample_rate, tags) {
var self = this;
var stats = {};
stats[stat] = value + "|g";
self.send(stats, sample_rate, tags);
};
Client.prototype.histogram = function(stat, value, sample_rate, tags) {
var self = this;
var stats = {};
stats[stat] = value + "|h";
self.send(stats, sample_rate, tags);
};
Client.prototype.set = function(stat, value, sample_rate, tags) {
var self = this;
var stats = {};
stats[stat] = value + "|s";
self.send(stats, sample_rate, tags);
};
Client.prototype.update_stats = function(stats, delta, sampleRate, tags) {
var self = this;
if (typeof(stats) === "string")
stats = [stats];
if (!delta)
delta = 1;
var data = {};
for (var i = 0; i < stats.length; i++)
data[stats[i]] = delta + "|c";
self.send(data, sampleRate, tags);
};
// An internal function update the last time the socket was
// used. This function is called when the socket is used
// and causes demand allocated ephemeral sockets to be closed
// after a period of inactivity.
Client.prototype._update_last_used = function () {
if (!this.ephemeral_socket)
return;
if (this.last_used_timer)
clearTimeout(this.last_used_timer);
var self = this;
this.last_used_timer = setTimeout(function() {
if (self.ephemeral_socket)
self.ephemeral_socket.close();
delete self.ephemeral_socket;
}, EPHEMERAL_LIFETIME_MS);
};
Client.prototype.send_data = function (buf) {
var socket;
if (!this.socket) {
if (!this.ephemeral_socket) {
this.ephemeral_socket = dgram.createSocket("udp4");
this.ephemeral_socket.on("error", function() {});
}
socket = this.ephemeral_socket;
}
else {
socket = this.socket;
}
this._update_last_used();
socket.send(buf, 0, buf.length, this.port, this.host);
};
Client.prototype.send = function(data, sample_rate, tags) {
if (!tags && Array.isArray(sample_rate)) {
tags = sample_rate;
sample_rate = undefined;
}
if (!sample_rate)
sample_rate = 1;
var value;
var sampled_data = {};
if (sample_rate < 1) {
if (mt.genrand_real2(0, 1) <= sample_rate) {
for (stat in data) {
value = data[stat];
sampled_data[stat] = value + "|@" + sample_rate;
}
}
}
else
sampled_data = data;
if (this.global_tags || tags) {
var merged_tags = [];
if (Array.isArray(this.global_tags))
merged_tags = merged_tags.concat(this.global_tags);
if (Array.isArray(tags))
merged_tags = merged_tags.concat(tags);
if (merged_tags.length > 0) {
var merged_tags_str = merged_tags.join(',');
for (stat in sampled_data)
sampled_data[stat] = sampled_data[stat] + "|#" + merged_tags_str;
}
}
for (var stat in sampled_data) {
var send_data = stat + ":" + sampled_data[stat];
this.send_data(new Buffer(send_data));
}
};
Client.prototype.close = function() {
if (this.socket)
this.socket.close();
if (this.ephemeral_socket)
this.ephemeral_socket.close();
if (this.last_used_timer)
clearTimeout(this.last_used_timer);
this.ephemeral_socket =
this.last_used_timer =
this.socket = null;
};
exports.StatsD = Client;
|
import _extends from 'babel-runtime/helpers/extends';
import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import PropTypes from 'prop-types';
import TimePickerPanel from 'rc-time-picker/es/Panel';
import classNames from 'classnames';
import { generateShowHourMinuteSecond } from '../time-picker';
import warning from '../_util/warning';
import { getComponentLocale } from '../_util/getLocale';
function getColumns(_ref) {
var showHour = _ref.showHour,
showMinute = _ref.showMinute,
showSecond = _ref.showSecond,
use12Hours = _ref.use12Hours;
var column = 0;
if (showHour) {
column += 1;
}
if (showMinute) {
column += 1;
}
if (showSecond) {
column += 1;
}
if (use12Hours) {
column += 1;
}
return column;
}
export default function wrapPicker(Picker, defaultFormat) {
return _a = function (_React$Component) {
_inherits(PickerWrapper, _React$Component);
function PickerWrapper() {
_classCallCheck(this, PickerWrapper);
var _this = _possibleConstructorReturn(this, (PickerWrapper.__proto__ || Object.getPrototypeOf(PickerWrapper)).apply(this, arguments));
_this.handleOpenChange = function (open) {
var _this$props = _this.props,
onOpenChange = _this$props.onOpenChange,
toggleOpen = _this$props.toggleOpen;
onOpenChange(open);
if (toggleOpen) {
warning(false, '`toggleOpen` is deprecated and will be removed in the future, ' + 'please use `onOpenChange` instead, see: https://u.ant.design/date-picker-on-open-change');
toggleOpen({ open: open });
}
};
return _this;
}
_createClass(PickerWrapper, [{
key: 'render',
value: function render() {
var _classNames2;
var props = this.props;
var prefixCls = props.prefixCls,
inputPrefixCls = props.inputPrefixCls;
var pickerClass = classNames(_defineProperty({}, prefixCls + '-picker', true));
var pickerInputClass = classNames(prefixCls + '-picker-input', inputPrefixCls, (_classNames2 = {}, _defineProperty(_classNames2, inputPrefixCls + '-lg', props.size === 'large'), _defineProperty(_classNames2, inputPrefixCls + '-sm', props.size === 'small'), _defineProperty(_classNames2, inputPrefixCls + '-disabled', props.disabled), _classNames2));
var locale = getComponentLocale(props, this.context, 'DatePicker', function () {
return require('./locale/zh_CN');
});
var timeFormat = props.showTime && props.showTime.format || 'HH:mm:ss';
var rcTimePickerProps = _extends({}, generateShowHourMinuteSecond(timeFormat), { format: timeFormat, use12Hours: props.showTime && props.showTime.use12Hours });
var columns = getColumns(rcTimePickerProps);
var timePickerCls = prefixCls + '-time-picker-column-' + columns;
var timePicker = props.showTime ? React.createElement(TimePickerPanel, _extends({}, rcTimePickerProps, props.showTime, { prefixCls: prefixCls + '-time-picker', className: timePickerCls, placeholder: locale.timePickerLocale.placeholder, transitionName: 'slide-up' })) : null;
return React.createElement(Picker, _extends({}, props, { pickerClass: pickerClass, pickerInputClass: pickerInputClass, locale: locale, timePicker: timePicker, onOpenChange: this.handleOpenChange }));
}
}]);
return PickerWrapper;
}(React.Component), _a.contextTypes = {
antLocale: PropTypes.object
}, _a.defaultProps = {
format: defaultFormat || 'YYYY-MM-DD',
transitionName: 'slide-up',
popupStyle: {},
onChange: function onChange() {},
onOk: function onOk() {},
onOpenChange: function onOpenChange() {},
locale: {},
prefixCls: 'ant-calendar',
inputPrefixCls: 'ant-input'
}, _a;
var _a;
}
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */
'use strict';
var msRestAzure = require('ms-rest-azure');
exports.BaseResource = msRestAzure.BaseResource;
exports.CloudError = msRestAzure.CloudError;
exports.PolicySku = require('./policySku');
exports.PolicyAssignment = require('./policyAssignment');
exports.ErrorResponse = require('./errorResponse');
exports.PolicyDefinitionReference = require('./policyDefinitionReference');
exports.PolicySetDefinition = require('./policySetDefinition');
exports.PolicyDefinition = require('./policyDefinition');
exports.PolicyAssignmentListResult = require('./policyAssignmentListResult');
exports.PolicySetDefinitionListResult = require('./policySetDefinitionListResult');
exports.PolicyDefinitionListResult = require('./policyDefinitionListResult');
|
/*!
* Ext JS Connect
* Copyright(c) 2010 Sencha Inc.
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Buffer = require('buffer').Buffer;
/**
* Cache in memory for the given `cacheDuration`.
*
* @param {Number} cacheDuration
* @return {Function}
* @api public
*/
module.exports = function cache(cacheDuration){
var cache = {},
queue = {};
return function cache(req, res, next) {
// Skip all requests that are not GET method
if (req.method !== "GET") {
next();
return;
}
var key = req.headers["accept-encoding"] + req.url,
writeHead = res.writeHead,
write = res.write,
end = res.end,
code,
headers,
chunks = [],
totalSize = 0;
function serve() {
var resp = cache[key];
var headers = resp.headers;
headers["Content-Length"] = resp.body.length;
if (localQueue) {
// Send everyone in the wait queue the response.
for (var i = 0, l = localQueue.length; i < l; i++) {
var localRes = localQueue[i];
localRes.writeHead(resp.code, headers);
localRes.end(resp.body);
}
// Kill the wait queue
delete queue[key];
} else {
res.writeHead(resp.code, headers);
res.end(resp.body);
}
}
// If there is a cache-hit, serve it right away!
if (cache[key]) {
serve();
return;
}
var localQueue = queue[key];
if (localQueue) {
localQueue[localQueue.length] = res;
return;
}
localQueue = queue[key] = [res];
// Defer the call to writeHead
res.writeHead = function (setCode, setHeaders) {
code = setCode;
headers = setHeaders;
};
// Buffer the response body as an array of Buffer objects
res.write = function (chunk, encoding) {
if (typeof chunk === 'string') {
var length;
if (!encoding || encoding === 'utf8') {
length = Buffer.byteLength(chunk);
}
var buffer = new Buffer(length);
buffer.write(chunk, encoding);
chunks.push(buffer);
} else {
chunks.push(chunk);
}
totalSize += chunk.length;
};
res.end = function (chunk, encoding) {
if (chunk) {
res.write(chunk, encoding);
}
// Combine the buffer array into a single buffer
var body = new Buffer(totalSize);
var offset = 0;
chunks.forEach(function (chunk) {
chunk.copy(body, offset);
offset += chunk.length;
});
// Store the result in the cache
cache[key] = {
body: body,
code: code,
headers: headers
};
// Put the original methods back in place
res.writeHead = writeHead;
res.write = write;
res.end = end;
// Serve the response from the cache
serve();
if (cacheDuration) {
// Expire the ram cache after 100ms or the specified length
setTimeout(function(){
delete cache[key];
}, cacheDuration);
} else {
// When the timeout is zero, just kill it right away
delete cache[key];
}
};
next();
};
};
|
/**
* @file
* User related utility functions.
*/
var userHelper = module.exports = {
createUser: function(application, roles, callback) {
var User = application.type('user');
var account = userHelper.sample();
account.roles = roles;
User.validateAndSave(account, function(error, user) {
callback(error, user, account);
});
},
// Generate sample user data used in tests.
sample: function (confirmation) {
var user = {
username: 'user',
password: 'password',
roles: [],
email: 'email@email.com'
};
if (confirmation) {
user['password-confirm'] = 'password';
}
return user;
},
// Generate credentials used in tests.
credentials: function () {
return {
username: 'user',
password: 'password'
};
}
};
|
'use strict';
var SfTextSettingsPage = function() {
// currently this page is called questions-settings.html but will be refactored. IJH 2014-06
this.tabs = {
editText: element(by.linkText('Edit Text')),
archiveQuestions: element(by.linkText('Archived Questions')),
audioFile: element(by.linkText('Audio File')),
paratextExport: element(by.linkText('ParaTExt Export'))
};
this.editTextTab = {
title: element(by.model('editedText.title')),
usxText: element(by.model('editedText.content')),
letMeEditLink: element(by.partialLinkText('Edit previous text')),
contentEditor: element(by.model('editedText.content')),
saveButton: element(by.partialButtonText('Save')),
};
this.archivedQuestionsTab = {
questionNames: element.all(by.repeater('question in visibleArchivedQuestions').column('calculatedTitle')),
questionList: element.all(by.repeater('question in visibleArchivedQuestions')),
publishButton: element(by.partialButtonText('Re-publish Questions')),
questionLink: function(title) {
return element(by.linkText(title));
}
};
// getFirstCheckbox has to be a function because the .first() method will actually resolve the finder
this.archivedQuestionsTabGetFirstCheckbox = function() {
return this.archivedQuestionsTab.questionList.first().element(by.css('input[type="checkbox"]'));
};
this.audioFileTab = {
};
this.paratextExportTab = {
exportAnswers: element(by.id('exportAnswers')),
exportComments: element(by.model('exportConfig.exportComments')),
exportFlagged: element(by.model('exportConfig.exportFlagged')),
prepareButton: element(by.partialButtonText('Prepare')),
noExportMsg: element(by.id('noExportMsg')),
answerCount: element(by.binding('download.answerCount')),
commentCount: element(by.binding('download.commentCount')),
downloadButton: element(by.partialButtonText('Download')),
};
};
module.exports = new SfTextSettingsPage();
|
const personalData = require('./personalData');
const webModel = require('./webModel');
const robotModel = require('./robotModel');
const webModelFunctions = require('./webModelFunctions');
const EddystoneBeaconScanner = require('eddystone-beacon-scanner');
const inRoomDistance = 15;
const lostSignalTimeout = 120; // Seconds;
const leftRoomTimeout = 5; // Seconds
var possibleSignalLoss;
var possiblyLeftTheRoom;
const delayLostSignalResponse = function () {
if (possiblyLeftTheRoom) {
clearTimeout(possiblyLeftTheRoom);
possiblyLeftTheRoom = undefined;
}
webModelFunctions.updateRobotMasterStatus('isInRoom', false);
webModelFunctions.updateRobotMasterStatus('isClose', false);
possibleSignalLoss = undefined;
};
const delayLeftRoomResponse = function () {
webModelFunctions.updateRobotMasterStatus('isInRoom', false);
possiblyLeftTheRoom = undefined;
};
var workingAverage;
var previousValue;
var threwOneOut = false;
EddystoneBeaconScanner.on('found', function (beacon) {
if (possibleSignalLoss) {
clearTimeout(possibleSignalLoss);
possibleSignalLoss = undefined;
}
workingAverage = beacon.distance;
previousValue = beacon.distance;
// console.log('found Eddystone Beacon:\n', JSON.stringify(beacon, null, 2));
console.log(`Beacon distance: ${Math.round(beacon.distance)} NEW`);
webModelFunctions.updateRobotMasterStatus('isClose', true);
});
EddystoneBeaconScanner.on('updated', function (beacon) {
// console.log('updated Eddystone Beacon:\n', JSON.stringify(beacon, null, 2));
// TODO: Move the constants up in the program
// Throw out single instance spikes.
const spikeThreshold = 20;
if (!threwOneOut && Math.abs(beacon.distance - previousValue) > spikeThreshold) {
threwOneOut = true;
} else {
previousValue = beacon.distance;
threwOneOut = false;
}
var newValue = previousValue;
// Smooth out the changes
// This must be below 1. The closer to 1 it is, the more it smooths out the number.
const smoothingFactor = 0.20;
workingAverage = (newValue * smoothingFactor) + ( workingAverage * ( 1.0 - smoothingFactor) );
console.log(`Beacon distance: ${Math.round(workingAverage)} ${Math.round(beacon.distance)}`);
if (workingAverage < inRoomDistance) {
if (possiblyLeftTheRoom) {
clearTimeout(possiblyLeftTheRoom);
possiblyLeftTheRoom = undefined;
}
if (!robotModel.master.isInRoom) {
webModelFunctions.updateRobotMasterStatus('isInRoom', true);
}
} else {
if (!possiblyLeftTheRoom) {
possiblyLeftTheRoom = setTimeout(delayLeftRoomResponse, leftRoomTimeout * 1000);
}
}
});
EddystoneBeaconScanner.on('lost', function (beacon) {
// console.log('lost Eddystone beacon:\n', JSON.stringify(beacon, null, 2));
console.log(`Beacon lost.`);
if (!possibleSignalLoss) {
possibleSignalLoss = setTimeout(delayLostSignalResponse, lostSignalTimeout * 1000);
}
});
EddystoneBeaconScanner.startScanning(true);
/* Sample output:
found Eddystone Beacon:
{
"txPower": -59,
"url": "https://goo.gl/wl2NJt",
"id": "ecb428720d14",
"type": "url",
"rssi": -86,
"distance": 0.19952623149688797,
"lastSeen": 1465710585429
}
updated Eddystone Beacon:
{
"txPower": -59,
"url": "https://goo.gl/wl2NJt",
"id": "ecb428720d14",
"type": "url",
"rssi": -86,
"distance": 0.19952623149688797,
"lastSeen": 1465710585429
}
updated Eddystone Beacon:
{
"txPower": -59,
"url": "https://goo.gl/wl2NJt",
"id": "ecb428720d14",
"type": "url",
"rssi": -91,
"distance": 0.35481338923357547,
"lastSeen": 1465710587440
}
found Eddystone Beacon:
{
"txPower": -59,
"url": "https://goo.gl/wl2NJt",
"id": "ecb428720d14",
"type": "url",
"rssi": -86,
"distance": 0.19952623149688797,
"lastSeen": 1465710585429
}
updated Eddystone Beacon:
{
"txPower": -59,
"url": "https://goo.gl/wl2NJt",
"id": "ecb428720d14",
"type": "url",
"rssi": -86,
"distance": 0.19952623149688797,
"lastSeen": 1465710585429
}
updated Eddystone Beacon:
{
"txPower": -59,
"url": "https://goo.gl/wl2NJt",
"id": "ecb428720d14",
"type": "url",
"rssi": -91,
"distance": 0.35481338923357547,
"lastSeen": 1465710587440
}
found Eddystone Beacon:
{
"txPower": -59,
"url": "https://goo.gl/wl2NJt",
"id": "ecb428720d14",
"type": "url",
"rssi": -86,
"distance": 0.19952623149688797,
"lastSeen": 1465710585429
}
updated Eddystone Beacon:
{
"txPower": -59,
"url": "https://goo.gl/wl2NJt",
"id": "ecb428720d14",
"type": "url",
"rssi": -86,
"distance": 0.19952623149688797,
"lastSeen": 1465710585429
}
updated Eddystone Beacon:
{
"txPower": -59,
"url": "https://goo.gl/wl2NJt",
"id": "ecb428720d14",
"type": "url",
"rssi": -91,
"distance": 0.35481338923357547,
"lastSeen": 1465710587440
}
*/
|
define({
"_widgetLabel": "適合性モデラー",
"general": {
"clear": "消去",
"cancel": "キャンセル",
"save": "実行",
"saveAs": "エクスポート"
},
"saveModel": {
"save": "エクスポート",
"title": "タイトル: ",
"summary": "サマリー: ",
"description": "説明: ",
"tags": "タグ: ",
"folder": "フォルダー: ",
"homeFolderPattern": "{username} (ホーム)",
"failed": "エクスポートできません。"
},
"util": {
"colorRamp": {
"1": "極めて低い",
"2": "非常に低い",
"3": "低",
"4": "やや低い",
"5": "中",
"6": "やや高い",
"7": "高",
"8": "非常に高い",
"9": "極めて高い",
"low": "低",
"high": "高",
"tipPattern": "{label} ({value})",
"flipCaption": "反転"
}
},
"wro": {
"caption": "適合性モデラー",
"browsePrompt": "加重オーバーレイ サービス",
"selectLayersCaption": "レイヤーの選択",
"selectLayers": "レイヤー",
"designModelCaption": "モデルの設計",
"designModel": "モデルの設計",
"transparency": "透過表示",
"visible": "表示",
"total": "合計",
"unableToLoad": "モデルを読み込めません。",
"projectNotOpen": "プロジェクトが開いていません。",
"readMore": "詳細",
"validation": {
"validating": "整合チェックしています...",
"invalidItemCaption": "加重オーバーレイ サービスの警告",
"notAnImageService": "このアイテムはイメージ サービスではありません。",
"notAWroService": "このアイテムは加重オーバーレイ サービスではありません。",
"undefinedUrl": "このアイテムの URL が定義されていません。",
"inaccessible": "サービスにアクセスできません。",
"generalError": "アイテムを開けません。",
"missingFieldPattern": "{field} は必須フィールドです。",
"notAllowRasterFunction": "[allowRasterFunction] を [true] に設定する必要があります。",
"notNearestResampling": "[defaultResamplingMethod] を [最近隣内挿法] に設定する必要があります。",
"notIsWeightedOverlayProp": "主要プロパティの [IsWeightedOverlay] を [true] に設定する必要があります。",
"invalidLink": "URL が無効です。 選択したレイヤーのサイトを開けませんでした。",
"unexpectedError": "予期しない状態が発生しました。",
"rangeMessage": "値は ${0} ~ ${1} の間でなければなりません",
"rangeMessage100": "値は 0 ~ 100 の間でなければなりません",
"maxLayers": "サービスで許可されているレイヤーの最大数は ${0} です。新しいレイヤーを追加するには、レイヤーを削除する必要があります。",
"notFound": "加重オーバーレイ サービスでレイヤー ${0} が見つかりません",
"wroServiceNotDefined": "モデルに加重オーバーレイ サービスが定義されていません。",
"overlayLayerOutputInvalid": "オーバーレイ レイヤー [${0}] の再分類範囲 [${1}] の出力値がない、または無効です",
"overlayLayerInputInvalid": "オーバーレイ レイヤー [${0}] の再分類範囲 [${1}] の入力最小値/最大値がない、または無効です",
"overlayLayerRangesMissing": "オーバーレイ レイヤー [${0}] に再分類範囲がありません",
"overlayLayerWeight": "オーバーレイ レイヤーの加重を合計 100 にする必要があります",
"overlayLayerRequired": "少なくとも 1 つのオーバーレイ レイヤーが必要です",
"overlayLayerNotDefined": "オーバーレイ レイヤーが定義されていません",
"requiresColormap": "このラスター関数にはカラーマップが必要ですが、モデルに有効なカラーマップ定義がありません",
"createModelError": "モデルの作成中にエラーが発生しました",
"invalidModel": "モデルが有効ではありません",
"imageServiceNotDefined": "イメージ サービス レイヤーが定義されていません",
"imageLayerNotDefined": "イメージ サービス レイヤーが定義されていません",
"histogramNotDefined": "加重オーバーレイ ヒストグラム関数が定義されていません。"
},
"colorRampLabel": {
"Green Yellow Red": "緑 黄 赤",
"Red Yellow Green": "赤 黄 緑",
"Yellow to Dark Red": "黄から濃い赤",
"Dark Red to Yellow": "濃い赤から黄",
"Light Gray to Dark Gray": "ライト グレーからダーク グレー",
"Dark Gray to Light Gray": "ダーク グレーからライト グレー",
"Light Brown to Dark Brown": "ライト ブラウンからダーク ブラウン",
"Dark Brown to Light Brown": "ダーク ブラウンからライト ブラウン",
"Full Spectrum - Bright Red to Blue": "フル スペクトル - 明るい赤から青",
"Full Spectrum - Bright Blue to Red": "フル スペクトル - 明るい青から赤",
"Partial Spectrum - Yellow to Blue": "部分スペクトル - 黄から青",
"Partial Spectrum - Blue to Yellow": "部分スペクトル - 青から黄",
"Yellow-Green to Dark Blue": "黄緑から濃い青",
"Dark Blue to Yellow-Green": "濃い青から黄緑",
"Cold to Hot Diverging": "寒色から暖色に分散",
"Hot to Cold Diverging": "暖色から寒色に分散",
"Surface - Low to High": "サーフェス - 低から高",
"Surface - High to Low": "サーフェス - 高から低"
}
},
"tabs": {
"layers": "レイヤー",
"model": "モデル",
"chart": "チャート"
},
"chart": {
"prompt": "機能",
"working": "更新しています...",
"polygonTool": "ポリゴンを描画",
"freehandPolygonTool": "フリーハンド ポリゴンの描画",
"selectTool": "レイヤーから選択",
"panTool": "Pan",
"clearButton": "解除",
"noModelLayer": "モデルなし",
"noSubjectLayers": "マップにポリゴン レイヤーがありません。",
"tipPattern": "${category} - ${label}: ${percent}%",
"tipPattern2": "${category}: ${percent}%",
"labelPattern": "${category} - ${label}"
}
});
|
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var CircleSprite = cc.Sprite.extend({
_degree:0,
ctor:function () {
this._super();
},
draw:function () {
cc.drawingUtil.setDrawColor4B(255,255,255,255);
if (this._degree < 0)
this._degree = 360;
cc.drawingUtil.drawCircle(cc.PointZero(), 30, cc.DEGREES_TO_RADIANS(this._degree), 60, true);
},
myUpdate:function (dt) {
this._degree -= 6;
}
});
var Helloworld = cc.Layer.extend({
isMouseDown:false,
helloImg:null,
helloLabel:null,
circle:null,
sprite:null,
init:function () {
var selfPointer = this;
//////////////////////////////
// 1. super init first
this._super();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// ask director the window size
var size = cc.Director.getInstance().getWinSize();
// add a "close" icon to exit the progress. it's an autorelease object
var closeItem = cc.MenuItemImage.create(
"res/CloseNormal.png",
"res/CloseSelected.png",
function () {
history.go(-1);
},this);
closeItem.setAnchorPoint(cc.p(0.5, 0.5));
var menu = cc.Menu.create(closeItem);
menu.setPosition(cc.PointZero());
this.addChild(menu, 1);
closeItem.setPosition(cc.p(size.width - 20, 20));
/////////////////////////////
// 3. add your codes below...
// add a label shows "Hello World"
// create and initialize a label
this.helloLabel = cc.LabelTTF.create("Hello World", "Arial", 38);
// position the label on the center of the screen
this.helloLabel.setPosition(cc.p(size.width / 2, 0));
// add the label as a child to this layer
this.addChild(this.helloLabel, 5);
var lazyLayer = cc.Layer.create();
this.addChild(lazyLayer);
// add "HelloWorld" splash screen"
this.sprite = cc.Sprite.create("res/HelloWorld.png");
this.sprite.setPosition(cc.p(size.width / 2, size.height / 2));
this.sprite.setScale(0.5);
this.sprite.setRotation(180);
lazyLayer.addChild(this.sprite, 0);
var rotateToA = cc.RotateTo.create(2, 0);
var scaleToA = cc.ScaleTo.create(2, 1, 1);
this.sprite.runAction(cc.Sequence.create(rotateToA, scaleToA));
this.circle = new CircleSprite();
this.circle.setPosition(cc.p(40, size.height - 60));
this.addChild(this.circle, 2);
this.circle.schedule(this.circle.myUpdate, 1 / 60);
this.helloLabel.runAction(cc.Spawn.create(cc.MoveBy.create(2.5, cc.p(0, size.height - 40)),cc.TintTo.create(2.5,255,125,0)));
this.setTouchEnabled(true);
return true;
},
// a selector callback
menuCloseCallback:function (sender) {
cc.Director.getInstance().end();
},
onTouchesBegan:function (touches, event) {
this.isMouseDown = true;
},
onTouchesMoved:function (touches, event) {
if (this.isMouseDown) {
if (touches) {
//this.circle.setPosition(cc.p(touches[0].getLocation().x, touches[0].getLocation().y));
}
}
},
onTouchesEnded:function (touches, event) {
this.isMouseDown = false;
},
onTouchesCancelled:function (touches, event) {
console.log("onTouchesCancelled");
}
});
var HelloWorldScene = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new Helloworld();
layer.init();
this.addChild(layer);
}
});
|
define(['iframeResizer'], function(iFrameResize) {
describe('Parent Page', function() {
describe('reset Page', function() {
var iframe;
var log=LOG;
var testId = 'parentPage1';
beforeEach(function(done){
loadIFrame('iframe600.html');
iframe = iFrameResize({
log:log,
id:testId
})[0];
spyOn(iframe.contentWindow,'postMessage').and.callFake(done);
mockMsgFromIFrame(iframe,'reset');
});
afterEach(function(){
tearDown(iframe);
})
it('receive message', function() {
expect(iframe.contentWindow.postMessage).toHaveBeenCalledWith('[iFrameSizer]reset', 'http://localhost:9876');
});
});
describe('late load msg received', function() {
var iframe;
var log=LOG;
var testId = 'parentPage2';
beforeEach(function(done){
loadIFrame('iframe600.html');
iframe = iFrameResize({
log:log,
id:testId
})[0];
spyOn(iframe.contentWindow,'postMessage').and.callFake(done);
window.postMessage('[iFrameResizerChild]Ready','*');
});
afterEach(function(){
tearDown(iframe);
})
it('receive message', function() {
expect(iframe.contentWindow.postMessage).toHaveBeenCalledWith('[iFrameSizer]parentPage2:8:false:true:32:true:true:null:bodyOffset:null:null:0:false:parent:scroll', 'http://localhost:9876');
});
});
xdescribe('default resize', function() {
var iframe;
var log=LOG;
var testId = 'defaultResize3';
it('receive message', function(done) {
loadIFrame('iframe600.html');
iframe = iFrameResize({
log:log,
id:testId,
resizeCallback:function(){
setTimeout(tearDown.bind(null,iframe),1);
done();
}
})[0];
mockMsgFromIFrame(iframe,'foo');
});
});
});
});
|
var isDate = require('../lang/isDate');
/**
* return the day of the year (1..366)
*/
function dayOfTheYear(date){
return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) -
Date.UTC(date.getFullYear(), 0, 1)) / 86400000 + 1;
}
module.exports = dayOfTheYear;
|
module.exports = rotate
/**
* Rotates a mat2 by the given angle
*
* @alias mat2.rotate
* @param {mat2} out the receiving matrix
* @param {mat2} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat2} out
*/
function rotate(out, a, rad) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3]
var s = Math.sin(rad)
var c = Math.cos(rad)
out[0] = a0 * c + a2 * s
out[1] = a1 * c + a3 * s
out[2] = a0 * -s + a2 * c
out[3] = a1 * -s + a3 * c
return out
}
|
// Flags: --expose-internals
'use strict';
const common = require('../common');
const assert = require('assert');
const { fork } = require('child_process');
const http = require('http');
if (process.argv[2] === 'child') {
process.once('message', (req, socket) => {
const res = new http.ServerResponse(req);
res.assignSocket(socket);
res.end();
});
process.send('ready');
return;
}
const { kTimeout } = require('internal/timers');
let child;
let socket;
const server = http.createServer(common.mustCall((req, res) => {
const r = {
method: req.method,
headers: req.headers,
path: req.path,
httpVersionMajor: req.httpVersionMajor,
query: req.query,
};
socket = res.socket;
child.send(r, socket);
server.close();
}));
server.listen(0, common.mustCall(() => {
child = fork(__filename, [ 'child' ]);
child.once('message', (msg) => {
assert.strictEqual(msg, 'ready');
const req = http.request({
port: server.address().port,
}, common.mustCall((res) => {
res.on('data', () => {});
res.on('end', common.mustCall(() => {
assert.strictEqual(socket[kTimeout], null);
assert.strictEqual(socket.parser, null);
assert.strictEqual(socket._httpMessage, null);
}));
}));
req.end();
});
}));
|
/*jshint -W104 */
'use strict';
const
Transmitter = require('./transmitter'),
RfxCom = require('./rfxcom');
/*
* This is a class for controlling Lighting6 lights.
*/
class Lighting6 extends Transmitter {
constructor(rfxcom, subtype, options) {
super(rfxcom, subtype, options);
this.packetType = "lighting6";
this.packetNumber = 0x15;
this.cmdseqnbr = -1; // Will be incremented by the first call to nextCmdseqbr()
}
nextCmdseqnbr() {
this.cmdseqnbr = this.cmdseqnbr + 1;
if ((this.isSubtype('BLYSS') && this.cmdseqnbr >= 5) ||
(this.isSubtype('CUVEO') && this.cmdseqnbr >= 255)) {
this.cmdseqnbr = 0;
}
return this.cmdseqnbr;
}
/*
* Splits the device id into idBytes, group, unitCode.
*
*/
_splitDeviceId(deviceId) {
const parts = Transmitter.splitAtSlashes(deviceId);
if (this.isSubtype(['BLYSS', 'CUVEO']) && parts.length !== 3) {
throw new Error("Invalid deviceId format");
}
const
id = RfxCom.stringToBytes(parts[0], 2),
unit = parseInt(parts[2]);
let group = parts[1];
if (this.isSubtype('BLYSS')) {
group = group.toUpperCase().charCodeAt(0);
if (group < 0x41 || group > 0x50) {
throw new Error("Invalid group code '" + parts[1] + "'")
}
if (unit < 0 || unit > 5) {
throw new Error("Invalid unit number " + unit)
}
} else if (this.isSubtype('CUVEO')) {
group = parseInt(group);
if (group < 0x0 || group > 0x03) {
throw new Error("Invalid group code '" + parts[1] + "'")
}
if ((group === 0 && (unit < 1 || unit > 2)) ||
(group > 0 && (unit < 1 || unit > 8))) {
throw new Error("Invalid unit number " + unit)
}
}
return {
idBytes: id.bytes,
groupCode: group,
unitCode: unit
};
};
_sendCommand(deviceId, command, callback) {
const device = this._splitDeviceId(deviceId);
if (device.unitCode === 0) {
command = command + 2;
}
let buffer = [device.idBytes[0], device.idBytes[1], device.groupCode, device.unitCode,
command, this.nextCmdseqnbr(), 0, 0];
return this.sendRaw(this.packetNumber, this.subtype, buffer, callback);
};
/*
* Switch on deviceId/unitCode
*/
switchOn(deviceId, callback) {
return this._sendCommand(deviceId, 0x00, callback);
};
/*
* Switch off deviceId/unitCode
*/
switchOff(deviceId, callback) {
return this._sendCommand(deviceId, 0x01, callback);
};
}
module.exports = Lighting6;
|
var Router = require('koa-router');
var Role = require('../../lib/role');
var Middleware = require('../../lib/middleware');
var router = module.exports = new Router();
router.use(Middleware.allow('admin.roles'));
router.get('/admin/api/roles', function *() {
var page = parseInt(this.request.query.page) || 1;
var perPage = parseInt(this.request.query.perpage) || 100;
var perms = this.request.query.permissions || false;
var q = {};
try {
q = JSON.parse(this.request.query.q);
} catch(e) {}
var conditions = {};
if (q.name) {
conditions.name = new RegExp(q.name, 'i');
}
// Setup options
var _opts = {
skip: (page - 1) * perPage,
limit: perPage
};
// Setup fields
var _fields = [
'name',
'desc',
'created'
];
if (perms) {
_opts.populatedPermission = perms;
_fields.push('permissions');
}
// Fetching a list with specific condition
var data = yield Role.list(conditions, _fields, _opts);
this.body = {
page: page,
perPage: perPage,
pageCount: Math.ceil(data.count / perPage),
roles: data.roles
};
});
router.post('/admin/api/roles', function *() {
if (!this.request.body.name || !this.request.body.desc || !this.request.body.perms) {
this.status = 401;
return;
}
try {
// Create a new role
var role = yield Role.create({
name: this.request.body.name,
desc: this.request.body.desc,
perms: this.request.body.perms
});
} catch(e) {
console.log(e);
}
this.body = {
role: {
_id: role._id,
name: role.name,
desc: role.desc,
perms: role.perms
}
};
});
|
angular
.module('angularCancelOnNavigateModule', [])
.config(function($httpProvider) {
$httpProvider.interceptors.push('HttpRequestTimeoutInterceptor');
})
.run(function ($rootScope, HttpPendingRequestsService) {
$rootScope.$on('$locationChangeSuccess', function (event, newUrl, oldUrl) {
if (newUrl != oldUrl) {
HttpPendingRequestsService.cancelAll();
}
})
});
|
define([
'matreshka_dir/core/var/core',
'matreshka_dir/core/var/sym',
'matreshka_dir/core/initmk'
], function(core, sym, initMK) {
"use strict";
var unbindNode = core.unbindNode = function(object, key, node, evt) {
if (!object || typeof object != 'object') return object;
initMK(object);
var type = typeof key,
$nodes,
keys,
special = object[sym].special[key],
i,
indexOfDot,
path,
listenKey,
_evt;
if (key instanceof Array) {
for (i = 0; i < key.length; i++) {
evt = node;
unbindNode(object, key[i][0], key[i][1] || evt, evt);
}
return object;
}
if (type == 'string') {
keys = key.split(/\s/);
if (keys.length > 1) {
for (i = 0; i < keys.length; i++) {
unbindNode(object, keys[i], node, evt);
}
return object;
}
}
indexOfDot = key.indexOf('.');
if (~indexOfDot) {
path = key.split('.');
var target = object;
for (i = 0; i < path.length - 1; i++) {
target = target[path[i]];
}
core._undelegateListener(object, path.slice(0, path.length - 2), 'change:' + path[path.length - 2]);
unbindNode(target, path[path.length - 1], node, evt);
return object;
}
if (key === null) {
for (key in object[sym].special)
if (object[sym].special.hasOwnProperty(key)) {
unbindNode(object, key, node, evt);
}
return object;
} else if (type == 'object') {
for (i in key)
if (key.hasOwnProperty(i)) {
unbindNode(object, i, key[i], node);
}
return object;
} else if (!node) {
if (special && special.$nodes) {
return unbindNode(object, key, special.$nodes, evt);
} else {
return object;
}
} else if (node.length == 2 && !node[1].nodeName && (node[1].setValue || node[1].getValue || node[1].on)) {
// It actually ignores binder. With such a syntax you can assign definite binders to some variable and then easily delete all at once using
return unbindNode(object, key, node[0], evt);
} else if (!special) {
return object;
}
$nodes = core._getNodes(object, node);
for (i = 0; i < $nodes.length; i++) {
core.domEvents.remove({
key: key,
node: $nodes[i],
instance: object
});
special.$nodes = special.$nodes.not($nodes[i]);
(function(node) {
core._removeListener(object, '_runbindings:' + key, null, null, {
node: node,
howToRemove: function(onData, offData) {
return onData.node == offData.node;
}
});
})($nodes[i]);
}
if (object.isMK) {
object.$nodes[key] = special.$nodes;
object.nodes[key] = special.$nodes[0] || null;
if (key == 'sandbox') {
object.sandbox = special.$nodes[0] || null;
object.$sandbox = special.$nodes;
}
}
if (!evt || !evt.silent) {
_evt = {
key: key,
$nodes: $nodes,
node: $nodes[0] || null
};
for (i in evt) {
_evt[i] = evt[i];
}
core._fastTrigger(object, 'unbind:' + key, _evt);
core._fastTrigger(object, 'unbind', _evt);
}
return object;
};
});
|
var exampleOutput = function(id, content) {
var outputDiv = document.getElementById(id);
if (outputDiv && outputDiv.childNodes && outputDiv.childNodes[0]) {
outputDiv.replaceChild(document.createTextNode(content), outputDiv.childNodes[0]);
} else {
outputDiv.appendChild(document.createTextNode(content));
}
};
module.exports = exampleOutput;
|
'use strict';
angular.module( 'QualityABTracker.services', [] )
.factory( 'trackerDataService', function( $http ) {
var api = {};
return api;
})
|
const { WebContentsView, app } = require('electron');
app.whenReady().then(function () {
new WebContentsView({}) // eslint-disable-line
app.quit();
});
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const resolve = require('rollup-plugin-node-resolve');
const sourcemaps = require('rollup-plugin-sourcemaps');
const globals = {
'@angular/core': 'ng.core',
'rxjs/BehaviorSubject': 'Rx',
'rxjs/ConnectableObservable': 'Rx',
'rxjs/Observable': 'Rx',
'rxjs/Subject': 'Rx',
'rxjs/observable/concat': 'Rx.Observable',
'rxjs/observable/defer': 'Rx.Observable',
'rxjs/observable/fromEvent': 'Rx.Observable',
'rxjs/observable/merge': 'Rx.Observable',
'rxjs/observable/of': 'Rx.Observable',
'rxjs/observable/throw': 'Rx.Observable',
'rxjs/operator/do': 'Rx.Observable.prototype',
'rxjs/operator/filter': 'Rx.Observable.prototype',
'rxjs/operator/map': 'Rx.Observable.prototype',
'rxjs/operator/publish': 'Rx.Observable.prototype',
'rxjs/operator/startWith': 'Rx.Observable.prototype',
'rxjs/operator/switchMap': 'Rx.Observable.prototype',
'rxjs/operator/take': 'Rx.Observable.prototype',
'rxjs/operator/toPromise': 'Rx.Observable.prototype',
};
module.exports = {
entry: '../../dist/packages-dist/service-worker/esm5/service-worker.js',
dest: '../../dist/packages-dist/service-worker/bundles/service-worker.umd.js',
format: 'umd',
exports: 'named',
moduleName: 'ng.serviceWorker',
plugins: [resolve(), sourcemaps()],
external: Object.keys(globals),
globals: globals
};
|
'use strict';
const sysPath = require('./path');
const fs = require('fs');
const anymatch = require('anymatch');
const promisify = require('micro-promisify');
const modules = require('./modules');
const xBrowserResolve = require('./resolve');
const loadGlobalsAndStyles = require('./load-globs-styles');
const explore = require('./explore');
const processFiles = require('./process');
const packages = require('./packages');
const DepGraph = require('./dep-graph');
const UsedShims = require('./used-shims');
const ProjectModuleMap = require('./project-module-map');
const readFile = promisify((path, callback) => fs.readFile(path, {encoding: 'utf8'}, callback));
const dir = sysPath.dirname(sysPath.dirname(require.resolve('..')));
const brunchRe = /\-brunch|brunch\-/;
const packageRe = /node_modules/;
const isNodeModule = path => packageRe.test(path);
const isNotBrunchPlugin = path => !brunchRe.test(path);
const isShim = path => path.indexOf(dir) === 0;
const jsonRe = /\.json$/;
const isJson = path => jsonRe.test(path);
const jsJsonRe = /\.(json|js)$/;
const isJsOrJson = path => jsJsonRe.test(path);
const cssRe = /\.css$/;
const isNotCss = path => !cssRe.test(path);
const fileReflection = (statics, conventions) => {
const isPackage = path => isNodeModule(path) && (statics || []).indexOf(path) === -1;
const isVendor = path => isPackage(path) ? false : anymatch(conventions.vendor, path);
const isApp = path => !anymatch(conventions.vendor, path);
return {isPackage, isVendor, isApp};
};
class Deppack {
constructor(config, json) {
if (!json.overrides) json.overrides = {};
if (!json.dependencies) json.dependencies = {};
this.rootPackage = json;
this.conventions = config.conventions;
this.paths = config.paths;
this.npm = config.npm || {};
this.isProduction = config._normalized.isProduction;
this.globalPseudofile = '___globals___';
this.plugins = [];
this.npmPlugins = [];
this.allMatchers = [];
this.rootMainCache = {};
this.usedShims = new UsedShims();
this.depGraph = new DepGraph();
this.modMap = new ProjectModuleMap(config.modules.nameCleaner);
this.fileReflection = fileReflection(this.npm.static, this.conventions);
this.resolve = xBrowserResolve.resolve(this.rootPackage, this.modMap, this.npm.aliases, this.globalPseudofile);
this.getPackageJson = filePath => {
return packages.packageJson(filePath, this.rootPackage);
};
this.canCallDep = path => packages.canCallDep(this.getPackageJson, path);
}
init() {
return xBrowserResolve.buildModMap(this.modMap, this.paths.watched, this.rootPackage)
.then(() => loadGlobalsAndStyles(this.paths.root, this.depGraph, this.globalPseudofile, this.npm, this.resolve));
}
setPlugins(plugins, npmPlugins) {
this.plugins = plugins;
this.npmPlugins = npmPlugins;
const plugs = plugins.compilers.filter(x => x.type === 'javascript' && npmPlugins.indexOf(x.brunchPluginName) !== -1);
const extensions = plugs.map(x => x.extension).filter(x => x);
const patterns = plugs.map(x => x.pattern).filter(x => x);
const extMatchers = extensions.map(x => new RegExp(`\\.${x}$`));
const allMatchers = patterns.concat(extMatchers);
this.allMatchers = allMatchers;
}
exploreDeps(sourceFile) {
return explore(this.depGraph, this.modMap, this.usedShims, this.canCallDep, this.isProduction, this.fileReflection, this.resolve, this.npm)(sourceFile);
}
processFiles(root, files, processor) {
const filePaths = files.map(f => f.path);
const requiredAliases = modules.requiredAliases(this.rootMainCache, this.getPackageJson, this.usedShims, filePaths);
processFiles(this.npm.aliases || {}, this.npm.globals || {}, this.usedShims, requiredAliases)(root, files, processor);
}
wrapInModule(filePath) {
filePath = sysPath.resolve('.', filePath);
return readFile(filePath).then(src => this.wrapSourceInModule(src, filePath));
}
wrapSourceInModule(src, filePath) {
return modules.wrap(this.getPackageJson, this.rootMainCache, filePath, src);
}
needsProcessing(file) {
return isNodeModule(file.path) &&
(isJsOrJson(file.path) || this.allMatchers.some(reg => reg.test(file.path))) &&
isNotBrunchPlugin(file.path) &&
this.fileReflection.isPackage(file.path) ||
this.isNpm(file.path);
}
isNpm(path) {
return isNodeModule(path) &&
isNotBrunchPlugin(path) &&
isNotCss(path) &&
this.fileReflection.isPackage(path) ||
isShim(path);
}
isNpmJSON(path) {
return this.isNpm(path) && isJson(path);
}
isShim(path) {
return isShim(path);
}
getAllDependents(path) {
const fileDeps = [path].concat(this.depGraph.recursiveDependents(path));
const globDeps = this.depGraph.recursiveDependents(this.globalPseudofile);
return fileDeps.concat(globDeps);
}
graph() {
return this.depGraph.serialize(this.modMap, this.fileReflection);
}
}
module.exports = Deppack;
|
var gremlin = require('../src');
var client = gremlin.createClient();
var script = 'g.V().range(1, 2)';
// Callback style
client.execute(script, function(err, res) {
console.log(err, res);
});
// Stream style
var s = client.stream(script);
s.on('data', function(result) {
console.log(result);
});
s.on('end', function() {
console.log("All results fetched");
});
s.on('error', function(e) {
console.log(e);
});
|
module.exports = function(grunt) {
return grunt.file.readJSON('package.json');
};
|
// example - valid: true
app.controller('MyController', MyController);
function MyController($http,
$q) {
}
// example - valid: true
app.controller('MyController', function($http,
$q) {
});
// example - valid: true
app.controller('MyController', [
'$http',
'$q',
function($http,
$q) {
}]);
// example - valid: true
app.controller('MyController', [
'$http',
'$q',
MyController]);
function MyController($http,
$q) {
}
// example - valid: false, errorMessage: "Do not use multiple dependencies in one line"
app.controller('MyController', MyController);
function MyController($http, $q) {}
// example - valid: false, errorMessage: "Do not use multiple dependencies in one line"
app.controller('MyController', function($http, $q) {});
// example - valid: false, errorMessage: "Do not use multiple dependencies in one line"
app.controller('MyController', ['$http','$q',
function($http,
$q) {
}]);
// example - valid: false, errorMessage: "Do not use multiple dependencies in one line"
app.controller('MyController', [
'$http',
'$q',
function($http, $q) {}]);
// example - valid: false, errorMessage: "Do not use multiple dependencies in one line"
app.controller('MyController', ['$http', '$q', MyController]);
function MyController($http,
$q) {}
// example - valid: false, errorMessage: "Do not use multiple dependencies in one line"
app.controller('MyController', [
'$http',
'$q',
MyController]);
function MyController($http, $q) {}
// example - valid: false, errorMessages: ["Do not use multiple dependencies in one line", "Do not use multiple dependencies in one line"]
app.controller('MyController', ['$http', '$q', function($http, $q) {}]);
|
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { chainPropTypes, integerPropType, deepmerge } from '@material-ui/utils';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import experimentalStyled from '../styles/experimentalStyled';
import useThemeProps from '../styles/useThemeProps';
import { alpha } from '../styles/colorManipulator';
import useTheme from '../styles/useTheme';
import { getPaperUtilityClass } from './paperClasses'; // Inspired by https://github.com/material-components/material-components-ios/blob/bca36107405594d5b7b16265a5b0ed698f85a5ee/components/Elevation/src/UIColor%2BMaterialElevation.m#L61
import { jsx as _jsx } from "react/jsx-runtime";
var getOverlayAlpha = function getOverlayAlpha(elevation) {
var alphaValue;
if (elevation < 1) {
alphaValue = 5.11916 * Math.pow(elevation, 2);
} else {
alphaValue = 4.5 * Math.log(elevation + 1) + 2;
}
return (alphaValue / 100).toFixed(2);
};
var overridesResolver = function overridesResolver(props, styles) {
var styleProps = props.styleProps;
return deepmerge(_extends({}, styles[styleProps.variant], !styleProps.square && styles.rounded, styleProps.variant === 'elevation' && styles["elevation".concat(styleProps.elevation)]), styles.root || {});
};
var useUtilityClasses = function useUtilityClasses(styleProps) {
var square = styleProps.square,
elevation = styleProps.elevation,
variant = styleProps.variant,
classes = styleProps.classes;
var slots = {
root: ['root', variant, !square && 'rounded', variant === 'elevation' && "elevation".concat(elevation)]
};
return composeClasses(slots, getPaperUtilityClass, classes);
};
var PaperRoot = experimentalStyled('div', {}, {
name: 'MuiPaper',
slot: 'Root',
overridesResolver: overridesResolver
})(function (_ref) {
var theme = _ref.theme,
styleProps = _ref.styleProps;
return _extends({
/* Styles applied to the root element. */
backgroundColor: theme.palette.background.paper,
color: theme.palette.text.primary,
transition: theme.transitions.create('box-shadow')
}, !styleProps.square && {
borderRadius: theme.shape.borderRadius
}, styleProps.variant === 'outlined' && {
border: "1px solid ".concat(theme.palette.divider)
}, styleProps.variant === 'elevation' && _extends({
boxShadow: theme.shadows[styleProps.elevation]
}, theme.palette.mode === 'dark' && {
backgroundImage: "linear-gradient(".concat(alpha('#fff', getOverlayAlpha(styleProps.elevation)), ", ").concat(alpha('#fff', getOverlayAlpha(styleProps.elevation)), ")")
}));
});
var Paper = /*#__PURE__*/React.forwardRef(function Paper(inProps, ref) {
var props = useThemeProps({
props: inProps,
name: 'MuiPaper'
});
var className = props.className,
_props$component = props.component,
component = _props$component === void 0 ? 'div' : _props$component,
_props$elevation = props.elevation,
elevation = _props$elevation === void 0 ? 1 : _props$elevation,
_props$square = props.square,
square = _props$square === void 0 ? false : _props$square,
_props$variant = props.variant,
variant = _props$variant === void 0 ? 'elevation' : _props$variant,
other = _objectWithoutProperties(props, ["className", "component", "elevation", "square", "variant"]);
var styleProps = _extends({}, props, {
component: component,
elevation: elevation,
square: square,
variant: variant
});
var classes = useUtilityClasses(styleProps);
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
var theme = useTheme();
if (theme.shadows[elevation] === undefined) {
console.error(["Material-UI: The elevation provided <Paper elevation={".concat(elevation, "}> is not available in the theme."), "Please make sure that `theme.shadows[".concat(elevation, "]` is defined.")].join('\n'));
}
}
return /*#__PURE__*/_jsx(PaperRoot, _extends({
as: component,
styleProps: styleProps,
className: clsx(classes.root, className),
ref: ref
}, other));
});
process.env.NODE_ENV !== "production" ? Paper.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: PropTypes.elementType,
/**
* Shadow depth, corresponds to `dp` in the spec.
* It accepts values between 0 and 24 inclusive.
* @default 1
*/
elevation: chainPropTypes(integerPropType, function (props) {
var elevation = props.elevation,
variant = props.variant;
if (elevation > 0 && variant === 'outlined') {
return new Error("Material-UI: Combining `elevation={".concat(elevation, "}` with `variant=\"").concat(variant, "\"` has no effect. Either use `elevation={0}` or use a different `variant`."));
}
return null;
}),
/**
* If `true`, rounded corners are disabled.
* @default false
*/
square: PropTypes.bool,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object,
/**
* The variant to use.
* @default 'elevation'
*/
variant: PropTypes
/* @typescript-to-proptypes-ignore */
.oneOfType([PropTypes.oneOf(['elevation', 'outlined']), PropTypes.string])
} : void 0;
export default Paper;
|
// FI lang variables by Tuomo Aura, Ateco.fi
tinyMCE.addToLang('',{
print_desc : 'Tulosta'
});
|
( function ( $ ) {
$.kieli = {
loaded: false,
setup: function() {
$.kieli.addMenuLabel();
},
set: function( val ) {
var recent = $.cookie( 'kieli-recent' ) || [];
if ( typeof recent === "string" ) {
recent = recent.split( "," );
}
recent.unshift( val );
recent = recent.slice( 0, 5 );
recent = recent.join( "," );
$.cookie( 'kieli-recent', recent, { 'path': '/', 'expires': 30 } );
var uri = new mw.Uri( window.location.href );
uri.extend( { setlang: val } );
window.location.href = uri.toString();
},
setCustom: function( event, data ) {
$.kieli.set( data.item.value );
},
loadMenu: function() {
if ( $.kieli.loaded ) {
return;
}
$.kieli.loaded = true;
var params = {
action: "query",
meta: "userinfo",
uiprop: "acceptlang",
format: "json"
};
$.get( mw.util.wikiScript( "api" ), params, $.kieli.buildMenu );
params = {
action: "query",
meta: "siteinfo",
siprop: "languages",
format: "json"
};
$.get( mw.util.wikiScript( "api" ), params, $.kieli.buildLanguageInput );
},
buildLanguageInput: function( result ) {
var langlist = [];
var languages = result.query.languages;
var localnames = mw.config.get( "wgKieliLanguages" );
for ( var i = 0; i < languages.length; i++ ) {
var name = languages[i]["*"];
var code = languages[i].code;
if ( localnames[code] && localnames[code] !== name ) {
var localnamecode = localnames[code] + " (" + code + ")";
langlist.push( { label: localnamecode, value: code } );
}
var namecode = name + " (" + code + ")";
langlist.push( { label: namecode, value: code } );
}
var $list = $( "#pt-kieli .lt-list ul" );
var $input = $( "<input />" )
.attr( "placeholder", "Search all languages..." );
$input.autocomplete({
source: langlist,
select: $.kieli.setCustom
});
$list.prepend( $input );
},
buildMenu: function( result ) {
var $menu = $( "#pt-kieli .lt-list" );
var $list = $( "<ul />" );
$menu.append( $list );
var count = 1;
var seen = [];
var current = mw.config.get( "wgUserLanguage" );
$list.append( $.kieli.createMenuItem( current ) );
seen.push( current );
var recent = $.cookie( "kieli-recent" ) || [];
if ( typeof recent === "string" ) {
recent = recent.split( "," );
}
for ( var i = 0; i < recent.length; i++ ) {
var id = recent[i];
if ( $.inArray( id, seen ) > -1 ) { continue; }
seen.push( id );
if ( count++ >= 5 ) { continue; }
$list.append( $.kieli.createMenuItem( id ) );
}
var languages = result.query.userinfo.acceptlang;
for ( var i = 0; i < languages.length; i++ ) {
var id = languages[i]["*"];
if ( $.inArray( id, seen ) > -1 ) { continue; }
seen.push( id );
if ( count++ >= 5 ) { continue; }
$list.append( $.kieli.createMenuItem( id ) );
}
$list.delegate('input:radio', 'change', function( event ) {
$.kieli.set( $(this).val() );
});
},
createMenuItem: function( id ) {
var current = mw.config.get( "wgUserLanguage" );
var names = mw.config.get( "wgKieliLanguages" );
var name = names && names[id] || id;
var $link = $( '<input type="radio" name="language" />' )
.val( id );
if ( id === current ) {
$link = $link.attr( "checked", true );
}
var $label = $( "<label />" )
.append( $link )
.append( name );
var $menuItem = $( "<li />" ).append( $label );
return $menuItem;
},
addMenuLabel: function(config) {
var $menuDiv = $( '<div />' )
.addClass( 'menu' )
.addClass( 'lt-list' )
.append();
var $div = $( '<div />' )
.addClass( 'lt-menu-kieli' )
.addClass( 'lt-menu' )
.append( $('<a href="#" />').append(mw.msg("kieli-load")) )
.append( $menuDiv )
.hover( $.kieli.loadMenu );
//this is the fonts link
var $li = $( '<li />' ).attr('id','pt-kieli')
.append( $div );
//if rtl, add to the right of top personal links. Else, to the left
var fn = $('body').hasClass( 'rtl' ) ? "append" : "prepend";
$('#p-personal ul:first')[fn]( $li );
//workaround for IE bug - activex components like input fields coming on top of everything.
//TODO: is there a better solution other than hiding it on hover?
if ( $.browser.msie ) {
$("#pt-kieli .lt-menu").hover(function(){
$("#searchform").css({ visibility: "hidden" });
},function(){
$("#searchform").css({ visibility: "visible" });
});
}
}
};
$( document ).ready( function() {
$.kieli.setup();
} );
} )( jQuery );
|
http://jsfiddle.net/fusioncharts/PagLf/
|
import api, { orgId as getOrgId } from '../../services/api';
import {
ORGANIZATION_PRODUCTS_REQUEST,
ORGANIZATION_PRODUCTS_SUCCESS,
ORGANIZATION_PRODUCTS_FAILURE,
} from './OrganizationProductsConstants';
import { apiError } from '../../move_to_foreman/common/helpers';
export const loadOrganizationProducts = (params = {}, orgId = getOrgId()) => (dispatch) => {
dispatch({ type: ORGANIZATION_PRODUCTS_REQUEST });
return api
.get(`/organizations/${orgId}/products/`, {}, params)
.then(({ data }) => {
dispatch({
type: ORGANIZATION_PRODUCTS_SUCCESS,
payload: { orgId, ...data },
});
})
.catch(result => dispatch(apiError(ORGANIZATION_PRODUCTS_FAILURE, result)));
};
export default loadOrganizationProducts;
|
import { Map } from "immutable";
import {
DASHBOARD_QUERY,
DASHBOARD_QUERY_ERROR,
DASHBOARD_QUERY_REQUEST
} from "../actions/dashboard";
const initialState = Map({
loading: false,
error: null,
results: {
drafts: { data: [], more: null },
published: { data: [], more: null },
user_published: { data: [], more: null },
user_drafts: { data: [], more: null },
user_workflows: { data: [], more: null },
user_drafts_count: 0,
user_published_count: 0,
user_count: 0
}
});
export default function dashboardReducer(state = initialState, action) {
switch (action.type) {
case DASHBOARD_QUERY_REQUEST:
return state.set("loading", true);
case DASHBOARD_QUERY:
return state.set("loading", false).set("results", action.results);
case DASHBOARD_QUERY_ERROR:
return state.set("loading", false);
default:
return state;
}
}
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'templates', 'el', {
button: 'Πρότυπα',
emptyListMsg: '(Δεν έχουν καθοριστεί πρότυπα)',
insertOption: 'Αντικατάσταση υπάρχοντων περιεχομένων',
options: 'Επιλογές Προτύπου',
selectPromptMsg: 'Παρακαλώ επιλέξτε πρότυπο για εισαγωγή στο πρόγραμμα',
title: 'Πρότυπα Περιεχομένου'
} );
|
define([], function () {
'use strict';
function listenerSession(resolve, timeoutMs) {
var listenerSocket = null;
var serviceName = "7359";
var servers = [];
var timeout;
var stringToSend = "who is EmbyServer?|emby";
function closeListenerSocket() {
if (timeout) {
clearTimeout(timeout);
}
if (listenerSocket !== null) {
// The call below explicitly closes the socket, freeing the UDP port that it is currently bound to.
listenerSocket.close();
listenerSocket = null;
}
resolve(servers);
}
function startListener(eventObject) {
listenerSocket = new Windows.Networking.Sockets.DatagramSocket();
listenerSocket.addEventListener("messagereceived", onMessageReceived);
// Start listen operation.
listenerSocket.bindServiceNameAsync("").done(function () {
//try {
// var multicastGroup = '255.255.255.255';
// listenerSocket.joinMulticastGroup(new Windows.Networking.HostName(multicastGroup));
//}
//catch (exception) {
// onError("Error while joining multicast group: " + exception.message);
// return;
//}
sendMessage(stringToSend);
}, onError);
}
function sendMessage(txt) {
try {
var remoteHostname = new Windows.Networking.HostName("255.255.255.255");
// GetOutputStreamAsync can be called multiple times on a single DatagramSocket instance to obtain
// IOutputStreams pointing to various different remote endpoints. The remote hostname given to
// GetOutputStreamAsync can be a unicast, multicast or broadcast address.
listenerSocket.getOutputStreamAsync(remoteHostname, serviceName).done(function (outputStream) {
try {
// Send out some multicast or broadcast data. Datagrams generated by the IOutputStream will use
// <source host, source port> information obtained from the parent socket (i.e., 'listenSocket' in
// this case).
var writer = new Windows.Storage.Streams.DataWriter(outputStream);
writer.writeString(txt);
writer.storeAsync().done(function () {
timeout = setTimeout(closeListenerSocket, timeoutMs);
}, onError);
}
catch (exception) {
onError("Error sending message: " + exception.message);
}
}, onError);
}
catch (exception) {
onError("Error sending message outer: " + exception.message);
}
}
function onMessageReceived(eventArguments) {
try {
// Interpret the incoming datagram's entire contents as a string.
var stringLength = eventArguments.getDataReader().unconsumedBufferLength;
var receivedMessage = eventArguments.getDataReader().readString(stringLength);
if (receivedMessage === stringToSend) {
return;
}
var server = JSON.parse(receivedMessage);
var remoteAddress;
//if (eventArguments && eventArguments.remoteAddress) {
// remoteAddress = eventArguments.remoteAddress + ":" + eventArguments.remotePort;
//}
//if (remoteAddress) {
// server.RemoteAddress = remoteAddress;
//}
servers.push(server);
} catch (exception) {
onError("Error receiving message: " + exception);
}
}
function onError(reason) {
//require(['alert'], function (alert) {
// alert(reason);
//});
closeListenerSocket();
}
startListener();
}
return {
findServers: function (timeoutMs) {
return new Promise(function (resolve, reject) {
new listenerSession(resolve, timeoutMs);
});
}
};
});
|
var status = 0;
var entry;
function start() {
if(cm.getPlayer().getMapId() == 922000000) {
entry = 0;
cm.sendYesNo("Do you wish to quit this stage?");
status++;
}
else if(cm.isQuestStarted(3239)) {
entry = 1;
cm.sendYesNo("Do you want to enter #bToy Factory<Sector 4>#k?");
status++;
}
else {
cm.sendOk("Access to #bToy Factory<Sector 4>#k is restricted to the public.");
}
}
function action(mode, type, selection) {
if(status == 1) {
if(entry == 0) {
if(mode <= 0) {
cm.sendOk("Ok. Call me if you urge to exit, then.");
cm.dispose();
return;
}
cm.warp(922000009, 0);
if(!(cm.isQuestStarted(3239) && cm.haveItem(4031092, 10))) cm.removeAll(4031092);
cm.dispose();
}
else {
if(mode <= 0) {
cm.dispose();
return;
}
if(cm.getWarpMap(922000000).countPlayers() == 0) {
cm.warp(922000000, 0);
if(!(cm.isQuestStarted(3239) && cm.haveItem(4031092, 10))) cm.removeAll(4031092);
} else {
cm.sendOk("Someone else is already attempting the parts. Wait for them to finish before you enter.");
}
cm.dispose();
}
}
}
|
var searchData=
[
['singlecell_2ecpp',['singlecell.cpp',['../singlecell_8cpp.html',1,'']]]
];
|
/**
* Ironbane Editor
* Developed by Ironbane Team, 2014
* Written By: Jesse Stojan
* Copyright (C) 2014 Ironbane Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, GNU General Public License version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
|
var clac_snd = "/android_asset/www/sound/clac.wav";
var m_clac;
var melange_snd = "/android_asset/www/sound/melange.wav";
var m_melange;
var yeah_snd = "/android_asset/www/sound/oh_yeah.wav";
var m_yeah;
function soundLoaded() {
console.log('play sound.');
}
function isSoundReady() {
return (sound_loaded == 3);
}
function soundErr(err) {
alert(err);
}
function loadSounds() {
if (device.platform == "firefoxos") {
m_clac = document.getElementById("clac_snd");
m_melange = document.getElementById("melange_snd");
m_yeah = document.getElementById("yeah_snd");
sound_loaded = 3;
}
else {
m_clac = new Media(clac_snd, soundLoaded, soundErr);
m_melange = new Media(melange_snd, soundLoaded, soundErr);
m_yeah = new Media(yeah_snd, soundLoaded, soundErr);
}
}
|
var Modeler = require("../Modeler.js");
var className = 'ElementCreateSubnet';
var ElementCreateSubnet = function(json, parentObj) {
parentObj = parentObj || this;
// Class property definitions here:
Modeler.extend(className, {
CreateSubnet: {
type: "TypeCreateSubnetType",
wsdlDefinition: {
name: "CreateSubnet",
type: "tns:CreateSubnetType"
},
mask: Modeler.GET | Modeler.SET,
required: false
}
}, parentObj, json);
};
module.exports = ElementCreateSubnet;
Modeler.register(ElementCreateSubnet, "ElementCreateSubnet");
|
/*
Copyright (C) 2014 PencilBlue, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
function WPImportForm() {}
//dependencies
var PluginService = pb.PluginService;
//inheritance
util.inherits(WPImportForm, pb.BaseController);
WPImportForm.prototype.render = function(cb) {
var self = this;
var tabs = [
{
active: 'active',
href: '#import',
icon: 'upload',
title: self.ls.get('UPLOAD_XML')
}
];
var pills = [
{
name: 'content_settings',
title: self.ls.get('IMPORT_WORDPRESS'),
icon: 'chevron-left',
href: '/admin/plugins/wp_import/settings'
}];
var objects = {
navigation: pb.AdminNavigation.get(self.session, ['plugins', 'manage'], self.ls),
pills: pills,
tabs: tabs
};
this.setPageName(this.ls.get('IMPORT_WORDPRESS'));
var angularObjects = pb.js.getAngularObjects(objects);
self.ts.registerLocal('angular_objects', new pb.TemplateValue(angularObjects, false));
self.ts.load('/admin/plugins/settings/wp_import/import', function(err, result) {
var content = {
content: result,
content_type: "text/html",
code: 200
};
cb(content);
});
};
WPImportForm.getRoutes = function(cb) {
var routes = [
{
method: 'get',
path: '/admin/plugins/wp_import/settings/import',
auth_required: true,
access_level: ACCESS_MANAGING_EDITOR,
content_type: 'text/html'
}
];
cb(null, routes);
};
//exports
module.exports = WPImportForm;
|
// @flow
/**
* Helper to find if a string contains a pattern (case insensitive).
* Handle the null string case.
*/
export default function strContain(str : ?string, pattern : string) : boolean {
return (!!str) && (str.search(new RegExp(pattern, 'i')) !== -1)
}
|
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Report builder editor
*
* @module core_reportbuilder/editor
* @copyright 2021 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
"use strict";
import 'core/inplace_editable';
import Notification from 'core/notification';
import Pending from 'core/pending';
import Templates from 'core/templates';
import * as reportSelectors from 'core_reportbuilder/local/selectors';
import {init as columnsEditorInit} from 'core_reportbuilder/local/editor/columns';
import {init as conditionsEditorInit} from 'core_reportbuilder/local/editor/conditions';
import {init as filtersEditorInit} from 'core_reportbuilder/local/editor/filters';
import {init as sortingEditorInit} from 'core_reportbuilder/local/editor/sorting';
import {getReport} from 'core_reportbuilder/local/repository/reports';
let initialized = false;
/**
* Initialise editor and all it's modules
*/
export const init = () => {
const reportElement = document.querySelector(reportSelectors.regions.report);
columnsEditorInit(reportElement, initialized);
conditionsEditorInit(reportElement, initialized);
filtersEditorInit(reportElement, initialized);
sortingEditorInit(reportElement, initialized);
// Ensure we only add our listeners once (can be called multiple times by mustache template).
if (initialized) {
return;
}
// Add event handlers to generic report editor elements.
document.addEventListener('click', event => {
// Toggle between edit and preview mode.
const toggleEditViewMode = event.target.closest(reportSelectors.actions.toggleEditPreview);
if (toggleEditViewMode) {
event.preventDefault();
const pendingPromise = new Pending('core_reportbuilder/reports:get');
const toggledEditMode = toggleEditViewMode.dataset.editMode !== "1";
let customjs = '';
getReport(reportElement.dataset.reportId, toggledEditMode)
.then(response => {
customjs = response.javascript;
return Templates.render('core_reportbuilder/custom_report', response);
})
.then((html, js) => {
return Templates.replaceNodeContents(reportElement, html, js + customjs);
})
.then(() => pendingPromise.resolve())
.catch(Notification.exception);
}
});
initialized = true;
};
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'notification', 'zh-cn', {
closed: '通知已关闭。'
} );
|
// Variablendeklaration
var aktuellerhinweistext = 1;
// Funktion, um die Uhr zum Laufen zu bekommen - Zeigt lokale Systemzeit des Client an!
function time() {
var now = new Date();
hours = now.getHours();
minutes = now.getMinutes();
seconds = now.getSeconds();
dayinweek = now.getDay();
day = now.getDate();
month = now.getMonth();
year = now.getFullYear();
// Zeitstring erstellen
thetime = (hours < 10) ? "0" + hours + ":" : hours + ":";
thetime += (minutes < 10) ? "0" + minutes : minutes;
// thetime += ":";
// thetime += (seconds < 10) ? "0" + seconds : seconds;
// Tag-Datum-String erstellen
var weekday = new Array("Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag");
thedate = weekday[dayinweek] + " - ";
thedate += (day < 10) ? "0" + day + "." : day + ".";
month++;
thedate += (month < 10) ? "0" + month + "." : month + ".";
thedate += year;
// Schreiben
if (uhr = document.getElementById("uhr")) {uhr.innerHTML = thetime;}
if (datum = document.getElementById("datum")) {datum.innerHTML = thedate;}
}
// AJAX-Funktion zur Prüfung im Hintergrund, ob das Bild wechseln soll
function checkupdate(bildist)
{
// In bildist wird uns das angezeigte Bild übergeben
//Updatepruefung mit AJAX
var request = false;
request = new XMLHttpRequest();
if (!request)
{
alert("Keine Aktualisierung möglich. AJAX fehlgeschlagen");
} else {
// Wir fragen den Server, ob unser aktuell angezeigtes Bild noch passt
// sendet er "true" zurück, passt es
// sendet er aber false, müssen wir die ganze Seite aktualisieren
var url = location.href + "?bildist=" + bildist;
request.open('GET', url, 'true');
request.send();
request.onreadystatechange=function()
{
if (request.readyState==4 && request.status==200)
{
// Jetzt wirds ernst. True oder False?
if (request.responseText=="true")
{
// Nichts tun, wir sind aktuell
return;
} else {
// Seite neu laden und somit Display neu aufbauen
location.reload(true);
}
}
};
}
}
// Hinweistexte darstellen
function hinweistexte()
{
zahlhinweistexte = parseInt(document.getElementById("zahlhinweistexte").value);
// Prüfen, ob wir noch einen nächsten Text haben oder wieder von vorne beginnen.
if (aktuellerhinweistext < zahlhinweistexte)
{ aktuellerhinweistext++ } else {aktuellerhinweistext=0;}
if (zahlhinweistexte > 1)
{
// Nächsten Text anzeigen.
hinweistext.innerHTML = document.getElementById("text-"+aktuellerhinweistext).value;
// Fortschrittsbummerl machen
var fortschritt = '';
for (var i = 1; i <= zahlhinweistexte; i++)
{
if (i==aktuellerhinweistext)
{
fortschritt = fortschritt + "<span style='color: #F00;'>• </span>";
} else {
fortschritt = fortschritt + "<span style='color: #FFF;'>• </span>";
}
}
document.getElementById("fortschritt").innerHTML = fortschritt;
}
}
// Start-Funktion, wird von jeder Seite mit body.onload() aufgerufen
function start(bildist, aktualisierungszeit, hinweisanzeigedauer)
{
time();
window.setInterval("time()", 1000);
// Updatecheck. Wir übergeben dem Updatechecker auch das aktuelle Bild
window.setInterval("checkupdate('"+bildist+"')", aktualisierungszeit);
// Wenn wir das Hinweismodul ausführen, müssen wir die Texte aktualisieren.
if (hinweistext = document.getElementById("hinweistext")) {window.setInterval("hinweistexte()", hinweisanzeigedauer);}
}
|
/**
* Created by PRadostev on 20.02.2015.
*/
L.WFST.include({
gmlFeature: function (layer) {
var featureNode = L.XmlUtil.createElementNS(this.options.typeNSName, {}, {uri: this.options.namespaceUri});
var feature = layer.feature;
for (var propertyName in feature.properties) {
featureNode.appendChild(this.gmlProperty(propertyName,
feature.properties[propertyName]));
}
featureNode.appendChild(this.gmlProperty(this.options.geometryField,
layer.toGml(this.options.crs)));
return featureNode;
},
gmlProperty: function (name, value) {
var propertyNode = L.XmlUtil.createElementNS(this.namespaceName(name));
if (value instanceof Element) {
propertyNode.appendChild(value);
}
else {
propertyNode.appendChild(L.XmlUtil.createTextNode(value || ''));
}
return propertyNode;
},
wfsProperty: function (name, value) {
var propertyNode = L.XmlUtil.createElementNS('wfs:Property');
propertyNode.appendChild(L.XmlUtil.createElementNS('wfs:Name', {}, {value: name}));
var valueNode = L.XmlUtil.createElementNS('wfs:Value');
if (value instanceof Element) {
valueNode.appendChild(value);
}
else {
valueNode.appendChild(L.XmlUtil.createTextNode(value || ''));
}
propertyNode.appendChild(valueNode);
return propertyNode;
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.