code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = _default;
exports.messages = exports.ruleName = void 0;
var _utils = require("../../utils");
var _stylelint = require("stylelint");
var ruleName = (0, _utils.namespace)("double-slash-comment-inline");
exports.ruleName = ruleName;
var messages = _stylelint.utils.ruleMessages(ruleName, {
expected: "Expected //-comment to be inline comment",
rejected: "Unexpected inline //-comment"
});
exports.messages = messages;
var stylelintCommandPrefix = "stylelint-";
function _default(expectation, options) {
return function (root, result) {
var validOptions = _stylelint.utils.validateOptions(result, ruleName, {
actual: expectation,
possible: ["always", "never"]
}, {
actual: options,
possible: {
ignore: ["stylelint-commands"]
},
optional: true
});
if (!validOptions) {
return;
}
(0, _utils.eachRoot)(root, checkRoot);
function checkRoot(root) {
var rootString = root.source.input.css;
if (rootString.trim() === "") {
return;
}
var comments = (0, _utils.findCommentsInRaws)(rootString);
comments.forEach(function (comment) {
// Only process // comments
if (comment.type !== "double-slash") {
return;
} // Optionally ignore stylelint commands
if (comment.text.indexOf(stylelintCommandPrefix) === 0 && (0, _utils.optionsHaveIgnored)(options, "stylelint-commands")) {
return;
}
var isInline = comment.inlineAfter || comment.inlineBefore;
var message;
if (isInline && expectation === "never") {
message = messages.rejected;
} else if (!isInline && expectation === "always") {
message = messages.expected;
} else {
return;
}
_stylelint.utils.report({
message: message,
node: root,
index: comment.source.start,
result: result,
ruleName: ruleName
});
});
}
};
} | kyleterry/sufr | pkg/ui/node_modules/stylelint-scss/dist/rules/double-slash-comment-inline/index.js | JavaScript | apache-2.0 | 2,103 |
// 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 g_mySession = null;
var g_sessionKey = null;
var g_role = null; // roles - root, domain-admin, ro-admin, user
var g_username = null;
var g_account = null;
var g_domainid = null;
var g_loginCmdText = null;
var g_enableLogging = false;
var g_timezoneoffset = null;
var g_timezone = null;
var g_supportELB = null;
var g_KVMsnapshotenabled = null;
var g_regionsecondaryenabled = null;
var g_userPublicTemplateEnabled = "true";
var g_cloudstackversion = null;
var g_queryAsyncJobResultInterval = 3000;
//keyboard keycode
var keycode_Enter = 13;
//XMLHttpResponse.status
var ERROR_ACCESS_DENIED_DUE_TO_UNAUTHORIZED = 401;
var ERROR_INTERNET_NAME_NOT_RESOLVED = 12007;
var ERROR_INTERNET_CANNOT_CONNECT = 12029;
var ERROR_VMOPS_ACCOUNT_ERROR = 531;
// Default password is MD5 hashed. Set the following variable to false to disable this.
var md5Hashed = false;
var md5HashedLogin = false;
//page size for API call (e.g."listXXXXXXX&pagesize=N" )
var pageSize = 20;
var rootAccountId = 1;
//async action
var pollAsyncJobResult = function(args) {
$.ajax({
url: createURL("queryAsyncJobResult&jobId=" + args._custom.jobId),
dataType: "json",
async: false,
success: function(json) {
var result = json.queryasyncjobresultresponse;
if (result.jobstatus == 0) {
return; //Job has not completed
} else {
if (result.jobstatus == 1) { // Succeeded
if (args._custom.getUpdatedItem != null && args._custom.getActionFilter != null) {
args.complete({
data: args._custom.getUpdatedItem(json),
actionFilter: args._custom.getActionFilter()
});
} else if (args._custom.getUpdatedItem != null && args._custom.getActionFilter == null) {
args.complete({
data: args._custom.getUpdatedItem(json)
});
} else {
args.complete({
data: json.queryasyncjobresultresponse.jobresult
});
}
if (args._custom.fullRefreshAfterComplete == true) {
setTimeout(function() {
$(window).trigger('cloudStack.fullRefresh');
}, 500);
}
if (args._custom.onComplete) {
args._custom.onComplete(json, args._custom);
}
} else if (result.jobstatus == 2) { // Failed
var msg = (result.jobresult.errortext == null) ? "" : result.jobresult.errortext;
if (args._custom.getUpdatedItemWhenAsyncJobFails != null && args._custom.getActionFilter != null) {
args.error({
message: msg,
updatedData: args._custom.getUpdatedItemWhenAsyncJobFails(),
actionFilter: args._custom.getActionFilter()
});
} else if (args._custom.getUpdatedItemWhenAsyncJobFails != null && args._custom.getActionFilter == null) {
args.error({
message: msg,
updatedData: args._custom.getUpdatedItemWhenAsyncJobFails()
});
} else {
args.error({
message: msg
});
}
}
}
},
error: function(XMLHttpResponse) {
args.error({
message: parseXMLHttpResponse(XMLHttpResponse)
});
}
});
}
//API calls
function createURL(apiName, options) {
if (!options) options = {};
var urlString = clientApiUrl + "?" + "command=" + apiName + "&response=json&sessionkey=" + g_sessionKey;
if (cloudStack.context && cloudStack.context.projects && !options.ignoreProject) {
urlString = urlString + '&projectid=' + cloudStack.context.projects[0].id;
}
return urlString;
}
function todb(val) {
return encodeURIComponent(val);
}
//LB provider map
var lbProviderMap = {
"publicLb": {
"non-vpc": ["VirtualRouter", "Netscaler", "F5"],
"vpc": ["VpcVirtualRouter", "Netscaler"]
},
"internalLb": {
"non-vpc": [],
"vpc": ["InternalLbVm"]
}
};
//Add Guest Network in Advanced zone (for root-admin only)
var addGuestNetworkDialog = {
zoneObjs: [],
physicalNetworkObjs: [],
networkOfferingObjs: [],
def: {
label: 'label.add.guest.network',
messages: {
notification: function(args) {
return 'label.add.guest.network';
}
},
preFilter: function(args) {
if (isAdmin())
return true;
else
return false;
},
createForm: {
title: 'label.add.guest.network', //Add Shared Network in advanced zone
preFilter: function(args) {
if ('zones' in args.context) { //Infrastructure menu > zone detail > guest traffic type > network tab (only shown in advanced zone) > add guest network dialog
args.$form.find('.form-item[rel=zoneId]').hide();
args.$form.find('.form-item[rel=physicalNetworkId]').hide();
} else { //Network menu > guest network section > add guest network dialog
args.$form.find('.form-item[rel=zoneId]').css('display', 'inline-block');
args.$form.find('.form-item[rel=physicalNetworkId]').css('display', 'inline-block');
}
},
fields: {
name: {
docID: 'helpGuestNetworkZoneName',
label: 'label.name',
validation: {
required: true
}
},
description: {
label: 'label.description',
docID: 'helpGuestNetworkZoneDescription',
validation: {
required: true
}
},
zoneId: {
label: 'label.zone',
validation: {
required: true
},
docID: 'helpGuestNetworkZone',
select: function(args) {
if ('zones' in args.context) { //Infrastructure menu > zone detail > guest traffic type > network tab (only shown in advanced zone) > add guest network dialog
addGuestNetworkDialog.zoneObjs = args.context.zones; //i.e. only one zone entry
} else { //Network menu > guest network section > add guest network dialog
$.ajax({
url: createURL('listZones'),
async: false,
success: function(json) {
addGuestNetworkDialog.zoneObjs = []; //reset
var items = json.listzonesresponse.zone;
if (items != null) {
for (var i = 0; i < items.length; i++) {
if (items[i].networktype == 'Advanced') {
addGuestNetworkDialog.zoneObjs.push(items[i]);
}
}
}
}
});
}
args.response.success({
data: $.map(addGuestNetworkDialog.zoneObjs, function(zone) {
return {
id: zone.id,
description: zone.name
};
})
});
},
isHidden: true
},
physicalNetworkId: {
label: 'label.physical.network',
dependsOn: 'zoneId',
select: function(args) {
if ('physicalNetworks' in args.context) { //Infrastructure menu > zone detail > guest traffic type > network tab (only shown in advanced zone) > add guest network dialog
addGuestNetworkDialog.physicalNetworkObjs = args.context.physicalNetworks;
} else { //Network menu > guest network section > add guest network dialog
var selectedZoneId = args.$form.find('.form-item[rel=zoneId]').find('select').val();
$.ajax({
url: createURL('listPhysicalNetworks'),
data: {
zoneid: selectedZoneId
},
async: false,
success: function(json) {
var items = [];
var physicalnetworks = json.listphysicalnetworksresponse.physicalnetwork;
if (physicalnetworks != null) {
for (var i = 0; i < physicalnetworks.length; i++) {
$.ajax({
url: createURL('listTrafficTypes'),
data: {
physicalnetworkid: physicalnetworks[i].id
},
async: false,
success: function(json) {
var traffictypes = json.listtraffictypesresponse.traffictype;
if (traffictypes != null) {
for (var k = 0; k < traffictypes.length; k++) {
if (traffictypes[k].traffictype == 'Guest') {
items.push(physicalnetworks[i]);
break;
}
}
}
}
});
}
}
addGuestNetworkDialog.physicalNetworkObjs = items;
}
});
}
var items = [];
if (addGuestNetworkDialog.physicalNetworkObjs != null) {
for (var i = 0; i < addGuestNetworkDialog.physicalNetworkObjs.length; i++) {
items.push({
id: addGuestNetworkDialog.physicalNetworkObjs[i].id,
description: addGuestNetworkDialog.physicalNetworkObjs[i].name
});
}
}
args.response.success({
data: items
});
},
isHidden: true
},
vlanId: {
label: 'label.vlan.id',
docID: 'helpGuestNetworkZoneVLANID'
},
isolatedpvlanId: {
label: 'Secondary Isolated VLAN ID'
},
scope: {
label: 'label.scope',
docID: 'helpGuestNetworkZoneScope',
select: function(args) {
var selectedZoneId = args.$form.find('.form-item[rel=zoneId]').find('select').val();
var selectedZoneObj = {};
if (addGuestNetworkDialog.zoneObjs != null && selectedZoneId != "") {
for (var i = 0; i < addGuestNetworkDialog.zoneObjs.length; i++) {
if (addGuestNetworkDialog.zoneObjs[i].id == selectedZoneId) {
selectedZoneObj = addGuestNetworkDialog.zoneObjs[i];
break;
}
}
}
var array1 = [];
if (selectedZoneObj.networktype == "Advanced" && selectedZoneObj.securitygroupsenabled == true) {
array1.push({
id: 'zone-wide',
description: 'All'
});
} else {
array1.push({
id: 'zone-wide',
description: 'All'
});
array1.push({
id: 'domain-specific',
description: 'Domain'
});
array1.push({
id: 'account-specific',
description: 'Account'
});
array1.push({
id: 'project-specific',
description: 'Project'
});
}
args.response.success({
data: array1
});
args.$select.change(function() {
var $form = $(this).closest('form');
if ($(this).val() == "zone-wide") {
$form.find('.form-item[rel=domainId]').hide();
$form.find('.form-item[rel=subdomainaccess]').hide();
$form.find('.form-item[rel=account]').hide();
$form.find('.form-item[rel=projectId]').hide();
} else if ($(this).val() == "domain-specific") {
$form.find('.form-item[rel=domainId]').css('display', 'inline-block');
$form.find('.form-item[rel=subdomainaccess]').css('display', 'inline-block');
$form.find('.form-item[rel=account]').hide();
$form.find('.form-item[rel=projectId]').hide();
} else if ($(this).val() == "account-specific") {
$form.find('.form-item[rel=domainId]').css('display', 'inline-block');
$form.find('.form-item[rel=subdomainaccess]').hide();
$form.find('.form-item[rel=account]').css('display', 'inline-block');
$form.find('.form-item[rel=projectId]').hide();
} else if ($(this).val() == "project-specific") {
$form.find('.form-item[rel=domainId]').css('display', 'inline-block');
$form.find('.form-item[rel=subdomainaccess]').hide();
$form.find('.form-item[rel=account]').hide();
$form.find('.form-item[rel=projectId]').css('display', 'inline-block');
}
});
}
},
domainId: {
label: 'label.domain',
validation: {
required: true
},
select: function(args) {
var items = [];
var selectedZoneId = args.$form.find('.form-item[rel=zoneId]').find('select').val();
var selectedZoneObj = {};
if (addGuestNetworkDialog.zoneObjs != null && selectedZoneId != "") {
for (var i = 0; i < addGuestNetworkDialog.zoneObjs.length; i++) {
if (addGuestNetworkDialog.zoneObjs[i].id == selectedZoneId) {
selectedZoneObj = addGuestNetworkDialog.zoneObjs[i];
break;
}
}
}
if (selectedZoneObj.domainid != null) { //list only domains under selectedZoneObj.domainid
$.ajax({
url: createURL("listDomainChildren&id=" + selectedZoneObj.domainid + "&isrecursive=true"),
dataType: "json",
async: false,
success: function(json) {
var domainObjs = json.listdomainchildrenresponse.domain;
$(domainObjs).each(function() {
items.push({
id: this.id,
description: this.path
});
});
}
});
$.ajax({
url: createURL("listDomains&id=" + selectedZoneObj.domainid),
dataType: "json",
async: false,
success: function(json) {
var domainObjs = json.listdomainsresponse.domain;
$(domainObjs).each(function() {
items.push({
id: this.id,
description: this.path
});
});
}
});
} else { //list all domains
$.ajax({
url: createURL("listDomains&listAll=true"),
dataType: "json",
async: false,
success: function(json) {
var domainObjs = json.listdomainsresponse.domain;
$(domainObjs).each(function() {
items.push({
id: this.id,
description: this.path
});
});
}
});
}
args.response.success({
data: items
});
}
},
subdomainaccess: {
label: 'label.subdomain.access',
isBoolean: true,
isHidden: true,
},
account: {
label: 'label.account'
},
projectId: {
label: 'label.project',
validation: {
required: true
},
select: function(args) {
var items = [];
$.ajax({
url: createURL("listProjects&listAll=true"),
dataType: "json",
async: false,
success: function(json) {
projectObjs = json.listprojectsresponse.project;
$(projectObjs).each(function() {
items.push({
id: this.id,
description: this.name
});
});
}
});
args.response.success({
data: items
});
}
},
networkOfferingId: {
label: 'label.network.offering',
docID: 'helpGuestNetworkZoneNetworkOffering',
dependsOn: ['zoneId', 'scope'],
select: function(args) {
if(args.$form.find('.form-item[rel=zoneId]').find('select').val() == null || args.$form.find('.form-item[rel=zoneId]').find('select').val().length == 0) {
args.response.success({
data: null
});
return;
}
var data = {
state: 'Enabled',
zoneid: args.$form.find('.form-item[rel=zoneId]').find('select').val()
};
var selectedPhysicalNetworkObj = [];
var selectedPhysicalNetworkId = args.$form.find('.form-item[rel=physicalNetworkId]').find('select').val();
if (addGuestNetworkDialog.physicalNetworkObjs != null) {
for (var i = 0; i < addGuestNetworkDialog.physicalNetworkObjs.length; i++) {
if (addGuestNetworkDialog.physicalNetworkObjs[i].id == selectedPhysicalNetworkId) {
selectedPhysicalNetworkObj = addGuestNetworkDialog.physicalNetworkObjs[i];
break;
}
}
}
if (selectedPhysicalNetworkObj.tags != null && selectedPhysicalNetworkObj.tags.length > 0) {
$.extend(data, {
tags: selectedPhysicalNetworkObj.tags
});
}
//Network tab in Guest Traffic Type in Infrastructure menu is only available when it's under Advanced zone.
//zone dropdown in add guest network dialog includes only Advanced zones.
if (args.scope == "zone-wide" || args.scope == "domain-specific") {
$.extend(data, {
guestiptype: 'Shared'
});
}
var items = [];
$.ajax({
url: createURL('listNetworkOfferings'),
data: data,
async: false,
success: function(json) {
addGuestNetworkDialog.networkOfferingObjs = json.listnetworkofferingsresponse.networkoffering;
if (addGuestNetworkDialog.networkOfferingObjs != null && addGuestNetworkDialog.networkOfferingObjs.length > 0) {
var selectedZoneId = args.$form.find('.form-item[rel=zoneId]').find('select').val();
var selectedZoneObj = {};
if (addGuestNetworkDialog.zoneObjs != null && selectedZoneId != "") {
for (var i = 0; i < addGuestNetworkDialog.zoneObjs.length; i++) {
if (addGuestNetworkDialog.zoneObjs[i].id == selectedZoneId) {
selectedZoneObj = addGuestNetworkDialog.zoneObjs[i];
break;
}
}
}
for (var i = 0; i < addGuestNetworkDialog.networkOfferingObjs.length; i++) {
//for zone-wide network in Advanced SG-enabled zone, list only SG network offerings
if (selectedZoneObj.networktype == 'Advanced' && selectedZoneObj.securitygroupsenabled == true) {
if (args.scope == "zone-wide") {
var includingSecurityGroup = false;
var serviceObjArray = addGuestNetworkDialog.networkOfferingObjs[i].service;
for (var k = 0; k < serviceObjArray.length; k++) {
if (serviceObjArray[k].name == "SecurityGroup") {
includingSecurityGroup = true;
break;
}
}
if (includingSecurityGroup == false)
continue; //skip to next network offering
}
}
items.push({
id: addGuestNetworkDialog.networkOfferingObjs[i].id,
description: addGuestNetworkDialog.networkOfferingObjs[i].displaytext
});
}
}
}
});
args.response.success({
data: items
});
args.$select.change(function() {
var $form = $(this).closest("form");
var selectedNetworkOfferingId = $(this).val();
$(addGuestNetworkDialog.networkOfferingObjs).each(function() {
if (this.id == selectedNetworkOfferingId) {
if (this.specifyvlan == false) {
$form.find('.form-item[rel=vlanId]').hide();
cloudStack.dialog.createFormField.validation.required.remove($form.find('.form-item[rel=vlanId]')); //make vlanId optional
$form.find('.form-item[rel=isolatedpvlanId]').hide();
} else {
$form.find('.form-item[rel=vlanId]').css('display', 'inline-block');
cloudStack.dialog.createFormField.validation.required.add($form.find('.form-item[rel=vlanId]')); //make vlanId required
$form.find('.form-item[rel=isolatedpvlanId]').css('display', 'inline-block');
}
return false; //break each loop
}
});
});
}
},
//IPv4 (begin)
ip4gateway: {
label: 'IPv4 Gateway',
docID: 'helpGuestNetworkZoneGateway'
},
ip4Netmask: {
label: 'IPv4 Netmask',
docID: 'helpGuestNetworkZoneNetmask'
},
startipv4: {
label: 'IPv4 Start IP',
docID: 'helpGuestNetworkZoneStartIP'
},
endipv4: {
label: 'IPv4 End IP',
docID: 'helpGuestNetworkZoneEndIP'
},
//IPv4 (end)
//IPv6 (begin)
ip6gateway: {
label: 'IPv6 Gateway',
docID: 'helpGuestNetworkZoneGateway'
},
ip6cidr: {
label: 'IPv6 CIDR'
},
startipv6: {
label: 'IPv6 Start IP',
docID: 'helpGuestNetworkZoneStartIP'
},
endipv6: {
label: 'IPv6 End IP',
docID: 'helpGuestNetworkZoneEndIP'
},
//IPv6 (end)
networkdomain: {
label: 'label.network.domain',
docID: 'helpGuestNetworkZoneNetworkDomain'
}
}
},
action: function(args) { //Add guest network in advanced zone
if (
((args.data.ip4gateway.length == 0) && (args.data.ip4Netmask.length == 0) && (args.data.startipv4.length == 0) && (args.data.endipv4.length == 0)) &&
((args.data.ip6gateway.length == 0) && (args.data.ip6cidr.length == 0) && (args.data.startipv6.length == 0) && (args.data.endipv6.length == 0))
) {
args.response.error("Either IPv4 fields or IPv6 fields need to be filled when adding a guest network");
return;
}
var $form = args.$form;
var array1 = [];
array1.push("&zoneId=" + args.data.zoneId);
array1.push("&networkOfferingId=" + args.data.networkOfferingId);
//Pass physical network ID to createNetwork API only when network offering's guestiptype is Shared.
var selectedNetworkOfferingObj;
if (addGuestNetworkDialog.networkOfferingObjs != null) {
for (var i = 0; i < addGuestNetworkDialog.networkOfferingObjs.length; i++) {
if (addGuestNetworkDialog.networkOfferingObjs[i].id == args.data.networkOfferingId) {
selectedNetworkOfferingObj = addGuestNetworkDialog.networkOfferingObjs[i]
break;
}
}
}
if (selectedNetworkOfferingObj.guestiptype == "Shared")
array1.push("&physicalnetworkid=" + args.data.physicalNetworkId);
array1.push("&name=" + todb(args.data.name));
array1.push("&displayText=" + todb(args.data.description));
if (($form.find('.form-item[rel=vlanId]').css("display") != "none") && (args.data.vlanId != null && args.data.vlanId.length > 0))
array1.push("&vlan=" + todb(args.data.vlanId));
if (($form.find('.form-item[rel=isolatedpvlanId]').css("display") != "none") && (args.data.isolatedpvlanId != null && args.data.isolatedpvlanId.length > 0))
array1.push("&isolatedpvlan=" + todb(args.data.isolatedpvlanId));
if ($form.find('.form-item[rel=domainId]').css("display") != "none") {
array1.push("&domainId=" + args.data.domainId);
if ($form.find('.form-item[rel=account]').css("display") != "none") { //account-specific
array1.push("&account=" + args.data.account);
array1.push("&acltype=account");
} else if ($form.find('.form-item[rel=projectId]').css("display") != "none") { //project-specific
array1.push("&projectid=" + args.data.projectId);
array1.push("&acltype=account");
} else { //domain-specific
array1.push("&acltype=domain");
if ($form.find('.form-item[rel=subdomainaccess]:visible input:checked').size())
array1.push("&subdomainaccess=true");
else
array1.push("&subdomainaccess=false");
}
} else { //zone-wide
array1.push("&acltype=domain"); //server-side will make it Root domain (i.e. domainid=1)
}
//IPv4 (begin)
if (args.data.ip4gateway != null && args.data.ip4gateway.length > 0)
array1.push("&gateway=" + args.data.ip4gateway);
if (args.data.ip4Netmask != null && args.data.ip4Netmask.length > 0)
array1.push("&netmask=" + args.data.ip4Netmask);
if (($form.find('.form-item[rel=startipv4]').css("display") != "none") && (args.data.startipv4 != null && args.data.startipv4.length > 0))
array1.push("&startip=" + args.data.startipv4);
if (($form.find('.form-item[rel=endipv4]').css("display") != "none") && (args.data.endipv4 != null && args.data.endipv4.length > 0))
array1.push("&endip=" + args.data.endipv4);
//IPv4 (end)
//IPv6 (begin)
if (args.data.ip6gateway != null && args.data.ip6gateway.length > 0)
array1.push("&ip6gateway=" + args.data.ip6gateway);
if (args.data.ip6cidr != null && args.data.ip6cidr.length > 0)
array1.push("&ip6cidr=" + args.data.ip6cidr);
if (($form.find('.form-item[rel=startipv6]').css("display") != "none") && (args.data.startipv6 != null && args.data.startipv6.length > 0))
array1.push("&startipv6=" + args.data.startipv6);
if (($form.find('.form-item[rel=endipv6]').css("display") != "none") && (args.data.endipv6 != null && args.data.endipv6.length > 0))
array1.push("&endipv6=" + args.data.endipv6);
//IPv6 (end)
if (args.data.networkdomain != null && args.data.networkdomain.length > 0)
array1.push("&networkdomain=" + todb(args.data.networkdomain));
$.ajax({
url: createURL("createNetwork" + array1.join("")),
dataType: "json",
success: function(json) {
var item = json.createnetworkresponse.network;
args.response.success({
data: item
});
},
error: function(XMLHttpResponse) {
var errorMsg = parseXMLHttpResponse(XMLHttpResponse);
args.response.error(errorMsg);
}
});
},
notification: {
poll: function(args) {
args.complete();
}
}
}
}
// Role Functions
function isAdmin() {
return (g_role == 1);
}
function isDomainAdmin() {
return (g_role == 2);
}
function isUser() {
return (g_role == 0);
}
function isSelfOrChildDomainUser(username, useraccounttype, userdomainid, iscallerchilddomain) {
if (username == g_username) { //is self
return true;
} else if (isDomainAdmin() && !iscallerchilddomain && (useraccounttype == 0)) { //domain admin to user
return true;
} else if (isDomainAdmin() && iscallerchilddomain && (userdomainid != g_domainid)) { //domain admin to subdomain admin and user
return true;
} else {
return false;
}
}
// FUNCTION: Handles AJAX error callbacks. You can pass in an optional function to
// handle errors that are not already handled by this method.
function handleError(XMLHttpResponse, handleErrorCallback) {
// User Not authenticated
if (XMLHttpResponse.status == ERROR_ACCESS_DENIED_DUE_TO_UNAUTHORIZED) {
$("#dialog_session_expired").dialog("open");
} else if (XMLHttpResponse.status == ERROR_INTERNET_NAME_NOT_RESOLVED) {
$("#dialog_error_internet_not_resolved").dialog("open");
} else if (XMLHttpResponse.status == ERROR_INTERNET_CANNOT_CONNECT) {
$("#dialog_error_management_server_not_accessible").dialog("open");
} else if (XMLHttpResponse.status == ERROR_VMOPS_ACCOUNT_ERROR && handleErrorCallback != undefined) {
handleErrorCallback();
} else if (handleErrorCallback != undefined) {
handleErrorCallback();
} else {
var errorMsg = parseXMLHttpResponse(XMLHttpResponse);
$("#dialog_error").text(_s(errorMsg)).dialog("open");
}
}
function parseXMLHttpResponse(XMLHttpResponse) {
if (isValidJsonString(XMLHttpResponse.responseText) == false) {
return "";
}
//var json = jQuery.parseJSON(XMLHttpResponse.responseText);
var json = JSON.parse(XMLHttpResponse.responseText);
if (json != null) {
var property;
for (property in json) {
var errorObj = json[property];
if (errorObj.errorcode == 401 && errorObj.errortext == "unable to verify user credentials and/or request signature")
return _l('label.session.expired');
else
return _s(errorObj.errortext);
}
} else {
return "";
}
}
function isValidJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
cloudStack.validate = {
vmHostName: function(args) {
// 1 ~ 63 characters long
// ASCII letters 'a' through 'z', 'A' through 'Z', digits '0' through '9', hyphen ('-')
// must start with a letter
// must end with a letter or a digit (must not end with a hyphen)
var regexp = /^[a-zA-Z]{1}[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]{0,1}$/;
var b = regexp.test(args); //true or false
if (b == false)
cloudStack.dialog.notice({
message: 'message.validate.instance.name'
});
return b;
}
}
cloudStack.preFilter = {
createTemplate: function(args) {
if (isAdmin()) {
args.$form.find('.form-item[rel=isPublic]').css('display', 'inline-block');
args.$form.find('.form-item[rel=isFeatured]').css('display', 'inline-block');
args.$form.find('.form-item[rel=isrouting]').css('display', 'inline-block');
} else {
if (g_userPublicTemplateEnabled == "true") {
args.$form.find('.form-item[rel=isPublic]').css('display', 'inline-block');
} else {
args.$form.find('.form-item[rel=isPublic]').hide();
}
args.$form.find('.form-item[rel=isFeatured]').hide();
args.$form.find('.form-item[rel=xenserverToolsVersion61plus]').hide();
}
},
addLoadBalancerDevice: function(args) { //add netscaler device OR add F5 device
args.$form.find('.form-item[rel=dedicated]').bind('change', function() {
var $dedicated = args.$form.find('.form-item[rel=dedicated]');
var $capacity = args.$form.find('.form-item[rel=capacity]');
if ($dedicated.find('input[type=checkbox]:checked').length > 0) {
$capacity.hide();
$capacity.find('input[type=text]').val('1');
} else if ($dedicated.find('input[type=checkbox]:unchecked').length > 0) {
$capacity.css('display', 'inline-block');
$capacity.find('input[type=text]').val('');
}
});
args.$form.change();
}
}
cloudStack.actionFilter = {
guestNetwork: function(args) {
var jsonObj = args.context.item;
var allowedActions = [];
allowedActions.push('replaceacllist');
if (jsonObj.type == 'Isolated') {
allowedActions.push('edit'); //only Isolated network is allowed to upgrade to a different network offering (Shared network is not allowed to)
allowedActions.push('restart');
allowedActions.push('remove');
} else if (jsonObj.type == 'Shared') {
if (isAdmin()) {
allowedActions.push('restart');
allowedActions.push('remove');
}
}
return allowedActions;
}
}
var roleTypeUser = "0";
var roleTypeAdmin = "1";
var roleTypeDomainAdmin = "2";
cloudStack.converters = {
convertBytes: function(bytes) {
if (bytes < 1024 * 1024) {
return (bytes / 1024).toFixed(2) + " KB";
} else if (bytes < 1024 * 1024 * 1024) {
return (bytes / 1024 / 1024).toFixed(2) + " MB";
} else if (bytes < 1024 * 1024 * 1024 * 1024) {
return (bytes / 1024 / 1024 / 1024).toFixed(2) + " GB";
} else {
return (bytes / 1024 / 1024 / 1024 / 1024).toFixed(2) + " TB";
}
},
toLocalDate: function(UtcDate) {
var localDate = "";
if (UtcDate != null && UtcDate.length > 0) {
var disconnected = new Date();
disconnected.setISO8601(UtcDate);
if (g_timezoneoffset != null)
localDate = disconnected.getTimePlusTimezoneOffset(g_timezoneoffset);
else
localDate = disconnected.toUTCString();
// localDate = disconnected.getTimePlusTimezoneOffset(0);
}
return localDate;
},
toBooleanText: function(booleanValue) {
if (booleanValue == true)
return "Yes";
return "No";
},
convertHz: function(hz) {
if (hz == null)
return "";
if (hz < 1000) {
return hz + " MHz";
} else {
return (hz / 1000).toFixed(2) + " GHz";
}
},
toDayOfWeekDesp: function(dayOfWeek) {
if (dayOfWeek == "1")
return "Sunday";
else if (dayOfWeek == "2")
return "Monday";
else if (dayOfWeek == "3")
return "Tuesday";
else if (dayOfWeek == "4")
return "Wednesday";
else if (dayOfWeek == "5")
return "Thursday"
else if (dayOfWeek == "6")
return "Friday";
else if (dayOfWeek == "7")
return "Saturday";
},
toDayOfWeekDesp: function(dayOfWeek) {
if (dayOfWeek == "1")
return "Sunday";
else if (dayOfWeek == "2")
return "Monday";
else if (dayOfWeek == "3")
return "Tuesday";
else if (dayOfWeek == "4")
return "Wednesday";
else if (dayOfWeek == "5")
return "Thursday"
else if (dayOfWeek == "6")
return "Friday";
else if (dayOfWeek == "7")
return "Saturday";
},
toNetworkType: function(usevirtualnetwork) {
if (usevirtualnetwork == true || usevirtualnetwork == "true")
return "Public";
else
return "Direct";
},
toRole: function(type) {
if (type == roleTypeUser) {
return "User";
} else if (type == roleTypeAdmin) {
return "Admin";
} else if (type == roleTypeDomainAdmin) {
return "Domain-Admin";
}
},
toAlertType: function(alertCode) {
switch (alertCode) {
case 0:
return _l('label.memory');
case 1:
return _l('label.cpu');
case 2:
return _l('label.storage');
case 3:
return _l('label.primary.storage');
case 4:
return _l('label.public.ips');
case 5:
return _l('label.management.ips');
case 6:
return _l('label.secondary.storage');
case 7:
return _l('label.host');
case 9:
return _l('label.domain.router');
case 10:
return _l('label.console.proxy');
// These are old values -- can be removed in the future
case 8:
return "User VM";
case 11:
return "Routing Host";
case 12:
return "Storage";
case 13:
return "Usage Server";
case 14:
return "Management Server";
case 15:
return "Domain Router";
case 16:
return "Console Proxy";
case 17:
return "User VM";
case 18:
return "VLAN";
case 19:
return "Secondary Storage VM";
case 20:
return "Usage Server";
case 21:
return "Storage";
case 22:
return "Update Resource Count";
case 23:
return "Usage Sanity Result";
case 24:
return "Direct Attached Public IP";
case 25:
return "Local Storage";
case 26:
return "Resource Limit Exceeded";
}
},
toCapacityCountType: function(capacityCode) {
switch (capacityCode) {
case 0:
return _l('label.memory');
case 1:
return _l('label.cpu');
case 2:
return _l('label.storage');
case 3:
return _l('label.primary.storage');
case 4:
return _l('label.public.ips');
case 5:
return _l('label.management.ips');
case 6:
return _l('label.secondary.storage');
case 7:
return _l('label.vlan');
case 8:
return _l('label.direct.ips');
case 9:
return _l('label.local.storage');
case 10:
return "Routing Host";
case 11:
return "Storage";
case 12:
return "Usage Server";
case 13:
return "Management Server";
case 14:
return "Domain Router";
case 15:
return "Console Proxy";
case 16:
return "User VM";
case 17:
return "VLAN";
case 18:
return "Secondary Storage VM";
}
},
convertByType: function(alertCode, value) {
switch (alertCode) {
case 0:
return cloudStack.converters.convertBytes(value);
case 1:
return cloudStack.converters.convertHz(value);
case 2:
return cloudStack.converters.convertBytes(value);
case 3:
return cloudStack.converters.convertBytes(value);
case 6:
return cloudStack.converters.convertBytes(value);
case 9:
return cloudStack.converters.convertBytes(value);
case 11:
return cloudStack.converters.convertBytes(value);
}
return value;
}
}
//data parameter passed to API call in listView
function listViewDataProvider(args, data) {
//search
if (args.filterBy != null) {
if (args.filterBy.advSearch != null && typeof(args.filterBy.advSearch) == "object") { //advanced search
for (var key in args.filterBy.advSearch) {
if (key == 'tagKey' && args.filterBy.advSearch[key].length > 0) {
$.extend(data, {
'tags[0].key': args.filterBy.advSearch[key]
});
} else if (key == 'tagValue' && args.filterBy.advSearch[key].length > 0) {
$.extend(data, {
'tags[0].value': args.filterBy.advSearch[key]
});
} else if (args.filterBy.advSearch[key] != null && args.filterBy.advSearch[key].length > 0) {
data[key] = args.filterBy.advSearch[key]; //do NOT use $.extend(data, { key: args.filterBy.advSearch[key] }); which will treat key variable as "key" string
}
}
} else if (args.filterBy.search != null && args.filterBy.search.by != null && args.filterBy.search.value != null) { //basic search
switch (args.filterBy.search.by) {
case "name":
if (args.filterBy.search.value.length > 0) {
$.extend(data, {
keyword: args.filterBy.search.value
});
}
break;
}
}
}
//pagination
$.extend(data, {
listAll: true,
page: args.page,
pagesize: pageSize
});
}
//used by infrastructure page and network page
var addExtraPropertiesToGuestNetworkObject = function(jsonObj) {
jsonObj.networkdomaintext = jsonObj.networkdomain;
jsonObj.networkofferingidText = jsonObj.networkofferingid;
if (jsonObj.acltype == "Domain") {
if (jsonObj.domainid == rootAccountId)
jsonObj.scope = "All";
else
jsonObj.scope = "Domain (" + jsonObj.domain + ")";
} else if (jsonObj.acltype == "Account") {
if (jsonObj.project != null)
jsonObj.scope = "Account (" + jsonObj.domain + ", " + jsonObj.project + ")";
else
jsonObj.scope = "Account (" + jsonObj.domain + ", " + jsonObj.account + ")";
}
if (jsonObj.vlan == null && jsonObj.broadcasturi != null) {
jsonObj.vlan = jsonObj.broadcasturi.replace("vlan://", "");
}
}
//used by infrastructure page
var addExtraPropertiesToUcsBladeObject = function(jsonObj) {
var array1 = jsonObj.bladedn.split('/');
jsonObj.chassis = array1[1];
jsonObj.bladeid = array1[2];
}
//find service object in network object
function ipFindNetworkServiceByName(pName, networkObj) {
if (networkObj == null)
return null;
if (networkObj.service != null) {
for (var i = 0; i < networkObj.service.length; i++) {
var networkServiceObj = networkObj.service[i];
if (networkServiceObj.name == pName)
return networkServiceObj;
}
}
return null;
}
//find capability object in service object in network object
function ipFindCapabilityByName(pName, networkServiceObj) {
if (networkServiceObj == null)
return null;
if (networkServiceObj.capability != null) {
for (var i = 0; i < networkServiceObj.capability.length; i++) {
var capabilityObj = networkServiceObj.capability[i];
if (capabilityObj.name == pName)
return capabilityObj;
}
}
return null;
}
//compose URL for adding primary storage
function nfsURL(server, path) {
var url;
if (server.indexOf("://") == -1)
url = "nfs://" + server + path;
else
url = server + path;
return url;
}
function presetupURL(server, path) {
var url;
if (server.indexOf("://") == -1)
url = "presetup://" + server + path;
else
url = server + path;
return url;
}
function ocfs2URL(server, path) {
var url;
if (server.indexOf("://") == -1)
url = "ocfs2://" + server + path;
else
url = server + path;
return url;
}
function SharedMountPointURL(server, path) {
var url;
if (server.indexOf("://") == -1)
url = "SharedMountPoint://" + server + path;
else
url = server + path;
return url;
}
function rbdURL(monitor, pool, id, secret) {
var url;
/*
Replace the + and / symbols by - and _ to have URL-safe base64 going to the API
It's hacky, but otherwise we'll confuse java.net.URI which splits the incoming URI
*/
secret = secret.replace("+", "-");
secret = secret.replace("/", "_");
if (id != null && secret != null) {
monitor = id + ":" + secret + "@" + monitor;
}
if (pool.substring(0, 1) != "/")
pool = "/" + pool;
if (monitor.indexOf("://") == -1)
url = "rbd://" + monitor + pool;
else
url = monitor + pool;
return url;
}
function clvmURL(vgname) {
var url;
if (vgname.indexOf("://") == -1)
url = "clvm://localhost/" + vgname;
else
url = vgname;
return url;
}
function vmfsURL(server, path) {
var url;
if (server.indexOf("://") == -1)
url = "vmfs://" + server + path;
else
url = server + path;
return url;
}
function iscsiURL(server, iqn, lun) {
var url;
if (server.indexOf("://") == -1)
url = "iscsi://" + server + iqn + "/" + lun;
else
url = server + iqn + "/" + lun;
return url;
}
//VM Instance
function getVmName(p_vmName, p_vmDisplayname) {
if (p_vmDisplayname == null)
return _s(p_vmName);
var vmName = null;
if (p_vmDisplayname != p_vmName) {
vmName = _s(p_vmName) + " (" + _s(p_vmDisplayname) + ")";
} else {
vmName = _s(p_vmName);
}
return vmName;
}
var timezoneMap = new Object();
timezoneMap["Etc/GMT+12"] = "Etc/GMT+12 [GMT-12:00]";
timezoneMap["Etc/GMT+11"] = "Etc/GMT+11 [GMT-11:00]";
timezoneMap["Pacific/Midway"] = "Pacific/Midway [Samoa Standard Time]";
timezoneMap["Pacific/Niue"] = "Pacific/Niue [Niue Time]";
timezoneMap["Pacific/Pago_Pago"] = "Pacific/Pago_Pago [Samoa Standard Time]";
timezoneMap["Pacific/Samoa"] = "Pacific/Samoa [Samoa Standard Time]";
timezoneMap["US/Samoa"] = "US/Samoa [Samoa Standard Time]";
timezoneMap["America/Adak"] = "America/Adak [Hawaii-Aleutian Standard Time]";
timezoneMap["America/Atka"] = "America/Atka [Hawaii-Aleutian Standard Time]";
timezoneMap["Etc/GMT+10"] = "Etc/GMT+10 [GMT-10:00]";
timezoneMap["HST"] = "HST [Hawaii Standard Time]";
timezoneMap["Pacific/Honolulu"] = "Pacific/Honolulu [Hawaii Standard Time]";
timezoneMap["Pacific/Johnston"] = "Pacific/Johnston [Hawaii Standard Time]";
timezoneMap["Pacific/Rarotonga"] = "Pacific/Rarotonga [Cook Is. Time]";
timezoneMap["Pacific/Tahiti"] = "Pacific/Tahiti [Tahiti Time]";
timezoneMap["SystemV/HST10"] = "SystemV/HST10 [Hawaii Standard Time]";
timezoneMap["US/Aleutian"] = "US/Aleutian [Hawaii-Aleutian Standard Time]";
timezoneMap["US/Hawaii"] = "US/Hawaii [Hawaii Standard Time]";
timezoneMap["Pacific/Marquesas"] = "Pacific/Marquesas [Marquesas Time]";
timezoneMap["AST"] = "AST [Alaska Standard Time]";
timezoneMap["America/Anchorage"] = "America/Anchorage [Alaska Standard Time]";
timezoneMap["America/Juneau"] = "America/Juneau [Alaska Standard Time]";
timezoneMap["America/Nome"] = "America/Nome [Alaska Standard Time]";
timezoneMap["America/Sitka"] = "America/Sitka [GMT-09:00]";
timezoneMap["America/Yakutat"] = "America/Yakutat [Alaska Standard Time]";
timezoneMap["Etc/GMT+9"] = "Etc/GMT+9 [GMT-09:00]";
timezoneMap["Pacific/Gambier"] = "Pacific/Gambier [Gambier Time]";
timezoneMap["SystemV/YST9"] = "SystemV/YST9 [Alaska Standard Time]";
timezoneMap["SystemV/YST9YDT"] = "SystemV/YST9YDT [Alaska Standard Time]";
timezoneMap["US/Alaska"] = "US/Alaska [Alaska Standard Time]";
timezoneMap["America/Dawson"] = "America/Dawson [Pacific Standard Time]";
timezoneMap["America/Ensenada"] = "America/Ensenada [Pacific Standard Time]";
timezoneMap["America/Los_Angeles"] = "America/Los_Angeles [Pacific Standard Time]";
timezoneMap["America/Metlakatla"] = "America/Metlakatla [GMT-08:00]";
timezoneMap["America/Santa_Isabel"] = "America/Santa_Isabel [Pacific Standard Time]";
timezoneMap["America/Tijuana"] = "America/Tijuana [Pacific Standard Time]";
timezoneMap["America/Vancouver"] = "America/Vancouver [Pacific Standard Time]";
timezoneMap["America/Whitehorse"] = "America/Whitehorse [Pacific Standard Time]";
timezoneMap["Canada/Pacific"] = "Canada/Pacific [Pacific Standard Time]";
timezoneMap["Canada/Yukon"] = "Canada/Yukon [Pacific Standard Time]";
timezoneMap["Etc/GMT+8"] = "Etc/GMT+8 [GMT-08:00]";
timezoneMap["Mexico/BajaNorte"] = "Mexico/BajaNorte [Pacific Standard Time]";
timezoneMap["PST"] = "PST [Pacific Standard Time]";
timezoneMap["PST8PDT"] = "PST8PDT [Pacific Standard Time]";
timezoneMap["Pacific/Pitcairn"] = "Pacific/Pitcairn [Pitcairn Standard Time]";
timezoneMap["SystemV/PST8"] = "SystemV/PST8 [Pacific Standard Time]";
timezoneMap["SystemV/PST8PDT"] = "SystemV/PST8PDT [Pacific Standard Time]";
timezoneMap["US/Pacific"] = "US/Pacific [Pacific Standard Time]";
timezoneMap["US/Pacific-New"] = "US/Pacific-New [Pacific Standard Time]";
timezoneMap["America/Boise"] = "America/Boise [Mountain Standard Time]";
timezoneMap["America/Cambridge_Bay"] = "America/Cambridge_Bay [Mountain Standard Time]";
timezoneMap["America/Chihuahua"] = "America/Chihuahua [Mountain Standard Time]";
timezoneMap["America/Creston"] = "America/Creston [GMT-07:00]";
timezoneMap["America/Dawson_Creek"] = "America/Dawson_Creek [Mountain Standard Time]";
timezoneMap["America/Denver"] = "America/Denver [Mountain Standard Time]";
timezoneMap["America/Edmonton"] = "America/Edmonton [Mountain Standard Time]";
timezoneMap["America/Hermosillo"] = "America/Hermosillo [Mountain Standard Time]";
timezoneMap["America/Inuvik"] = "America/Inuvik [Mountain Standard Time]";
timezoneMap["America/Mazatlan"] = "America/Mazatlan [Mountain Standard Time]";
timezoneMap["America/Ojinaga"] = "America/Ojinaga [Mountain Standard Time]";
timezoneMap["America/Phoenix"] = "America/Phoenix [Mountain Standard Time]";
timezoneMap["America/Shiprock"] = "America/Shiprock [Mountain Standard Time]";
timezoneMap["America/Yellowknife"] = "America/Yellowknife [Mountain Standard Time]";
timezoneMap["Canada/Mountain"] = "Canada/Mountain [Mountain Standard Time]";
timezoneMap["Etc/GMT+7"] = "Etc/GMT+7 [GMT-07:00]";
timezoneMap["MST"] = "MST [Mountain Standard Time]";
timezoneMap["MST7MDT"] = "MST7MDT [Mountain Standard Time]";
timezoneMap["Mexico/BajaSur"] = "Mexico/BajaSur [Mountain Standard Time]";
timezoneMap["Navajo"] = "Navajo [Mountain Standard Time]";
timezoneMap["PNT"] = "PNT [Mountain Standard Time]";
timezoneMap["SystemV/MST7"] = "SystemV/MST7 [Mountain Standard Time]";
timezoneMap["SystemV/MST7MDT"] = "SystemV/MST7MDT [Mountain Standard Time]";
timezoneMap["US/Arizona"] = "US/Arizona [Mountain Standard Time]";
timezoneMap["US/Mountain"] = "US/Mountain [Mountain Standard Time]";
timezoneMap["America/Bahia_Banderas"] = "America/Bahia_Banderas [GMT-06:00]";
timezoneMap["America/Belize"] = "America/Belize [Central Standard Time]";
timezoneMap["America/Cancun"] = "America/Cancun [Central Standard Time]";
timezoneMap["America/Chicago"] = "America/Chicago [Central Standard Time]";
timezoneMap["America/Costa_Rica"] = "America/Costa_Rica [Central Standard Time]";
timezoneMap["America/El_Salvador"] = "America/El_Salvador [Central Standard Time]";
timezoneMap["America/Guatemala"] = "America/Guatemala [Central Standard Time]";
timezoneMap["America/Indiana/Knox"] = "America/Indiana/Knox [Central Standard Time]";
timezoneMap["America/Indiana/Tell_City"] = "America/Indiana/Tell_City [Central Standard Time]";
timezoneMap["America/Knox_IN"] = "America/Knox_IN [Central Standard Time]";
timezoneMap["America/Managua"] = "America/Managua [Central Standard Time]";
timezoneMap["America/Matamoros"] = "America/Matamoros [Central Standard Time]";
timezoneMap["America/Menominee"] = "America/Menominee [Central Standard Time]";
timezoneMap["America/Merida"] = "America/Merida [Central Standard Time]";
timezoneMap["America/Mexico_City"] = "America/Mexico_City [Central Standard Time]";
timezoneMap["America/Monterrey"] = "America/Monterrey [Central Standard Time]";
timezoneMap["America/North_Dakota/Beulah"] = "America/North_Dakota/Beulah [GMT-06:00]";
timezoneMap["America/North_Dakota/Center"] = "America/North_Dakota/Center [Central Standard Time]";
timezoneMap["America/North_Dakota/New_Salem"] = "America/North_Dakota/New_Salem [Central Standard Time]";
timezoneMap["America/Rainy_River"] = "America/Rainy_River [Central Standard Time]";
timezoneMap["America/Rankin_Inlet"] = "America/Rankin_Inlet [Central Standard Time]";
timezoneMap["America/Regina"] = "America/Regina [Central Standard Time]";
timezoneMap["America/Resolute"] = "America/Resolute [Eastern Standard Time]";
timezoneMap["America/Swift_Current"] = "America/Swift_Current [Central Standard Time]";
timezoneMap["America/Tegucigalpa"] = "America/Tegucigalpa [Central Standard Time]";
timezoneMap["America/Winnipeg"] = "America/Winnipeg [Central Standard Time]";
timezoneMap["CST"] = "CST [Central Standard Time]";
timezoneMap["CST6CDT"] = "CST6CDT [Central Standard Time]";
timezoneMap["Canada/Central"] = "Canada/Central [Central Standard Time]";
timezoneMap["Canada/East-Saskatchewan"] = "Canada/East-Saskatchewan [Central Standard Time]";
timezoneMap["Canada/Saskatchewan"] = "Canada/Saskatchewan [Central Standard Time]";
timezoneMap["Chile/EasterIsland"] = "Chile/EasterIsland [Easter Is. Time]";
timezoneMap["Etc/GMT+6"] = "Etc/GMT+6 [GMT-06:00]";
timezoneMap["Mexico/General"] = "Mexico/General [Central Standard Time]";
timezoneMap["Pacific/Easter"] = "Pacific/Easter [Easter Is. Time]";
timezoneMap["Pacific/Galapagos"] = "Pacific/Galapagos [Galapagos Time]";
timezoneMap["SystemV/CST6"] = "SystemV/CST6 [Central Standard Time]";
timezoneMap["SystemV/CST6CDT"] = "SystemV/CST6CDT [Central Standard Time]";
timezoneMap["US/Central"] = "US/Central [Central Standard Time]";
timezoneMap["US/Indiana-Starke"] = "US/Indiana-Starke [Central Standard Time]";
timezoneMap["America/Atikokan"] = "America/Atikokan [Eastern Standard Time]";
timezoneMap["America/Bogota"] = "America/Bogota [Colombia Time]";
timezoneMap["America/Cayman"] = "America/Cayman [Eastern Standard Time]";
timezoneMap["America/Coral_Harbour"] = "America/Coral_Harbour [Eastern Standard Time]";
timezoneMap["America/Detroit"] = "America/Detroit [Eastern Standard Time]";
timezoneMap["America/Fort_Wayne"] = "America/Fort_Wayne [Eastern Standard Time]";
timezoneMap["America/Grand_Turk"] = "America/Grand_Turk [Eastern Standard Time]";
timezoneMap["America/Guayaquil"] = "America/Guayaquil [Ecuador Time]";
timezoneMap["America/Havana"] = "America/Havana [Cuba Standard Time]";
timezoneMap["America/Indiana/Indianapolis"] = "America/Indiana/Indianapolis [Eastern Standard Time]";
timezoneMap["America/Indiana/Marengo"] = "America/Indiana/Marengo [Eastern Standard Time]";
timezoneMap["America/Indiana/Petersburg"] = "America/Indiana/Petersburg [Eastern Standard Time]";
timezoneMap["America/Indiana/Vevay"] = "America/Indiana/Vevay [Eastern Standard Time]";
timezoneMap["America/Indiana/Vincennes"] = "America/Indiana/Vincennes [Eastern Standard Time]";
timezoneMap["America/Indiana/Winamac"] = "America/Indiana/Winamac [Eastern Standard Time]";
timezoneMap["America/Indianapolis"] = "America/Indianapolis [Eastern Standard Time]";
timezoneMap["America/Iqaluit"] = "America/Iqaluit [Eastern Standard Time]";
timezoneMap["America/Jamaica"] = "America/Jamaica [Eastern Standard Time]";
timezoneMap["America/Kentucky/Louisville"] = "America/Kentucky/Louisville [Eastern Standard Time]";
timezoneMap["America/Kentucky/Monticello"] = "America/Kentucky/Monticello [Eastern Standard Time]";
timezoneMap["America/Lima"] = "America/Lima [Peru Time]";
timezoneMap["America/Louisville"] = "America/Louisville [Eastern Standard Time]";
timezoneMap["America/Montreal"] = "America/Montreal [Eastern Standard Time]";
timezoneMap["America/Nassau"] = "America/Nassau [Eastern Standard Time]";
timezoneMap["America/New_York"] = "America/New_York [Eastern Standard Time]";
timezoneMap["America/Nipigon"] = "America/Nipigon [Eastern Standard Time]";
timezoneMap["America/Panama"] = "America/Panama [Eastern Standard Time]";
timezoneMap["America/Pangnirtung"] = "America/Pangnirtung [Eastern Standard Time]";
timezoneMap["America/Port-au-Prince"] = "America/Port-au-Prince [Eastern Standard Time]";
timezoneMap["America/Thunder_Bay"] = "America/Thunder_Bay [Eastern Standard Time]";
timezoneMap["America/Toronto"] = "America/Toronto [Eastern Standard Time]";
timezoneMap["Canada/Eastern"] = "Canada/Eastern [Eastern Standard Time]";
timezoneMap["Cuba"] = "Cuba [Cuba Standard Time]";
timezoneMap["EST"] = "EST [Eastern Standard Time]";
timezoneMap["EST5EDT"] = "EST5EDT [Eastern Standard Time]";
timezoneMap["Etc/GMT+5"] = "Etc/GMT+5 [GMT-05:00]";
timezoneMap["IET"] = "IET [Eastern Standard Time]";
timezoneMap["Jamaica"] = "Jamaica [Eastern Standard Time]";
timezoneMap["SystemV/EST5"] = "SystemV/EST5 [Eastern Standard Time]";
timezoneMap["SystemV/EST5EDT"] = "SystemV/EST5EDT [Eastern Standard Time]";
timezoneMap["US/East-Indiana"] = "US/East-Indiana [Eastern Standard Time]";
timezoneMap["US/Eastern"] = "US/Eastern [Eastern Standard Time]";
timezoneMap["US/Michigan"] = "US/Michigan [Eastern Standard Time]";
timezoneMap["America/Caracas"] = "America/Caracas [Venezuela Time]";
timezoneMap["America/Anguilla"] = "America/Anguilla [Atlantic Standard Time]";
timezoneMap["America/Antigua"] = "America/Antigua [Atlantic Standard Time]";
timezoneMap["America/Argentina/San_Luis"] = "America/Argentina/San_Luis [Western Argentine Time]";
timezoneMap["America/Aruba"] = "America/Aruba [Atlantic Standard Time]";
timezoneMap["America/Asuncion"] = "America/Asuncion [Paraguay Time]";
timezoneMap["America/Barbados"] = "America/Barbados [Atlantic Standard Time]";
timezoneMap["America/Blanc-Sablon"] = "America/Blanc-Sablon [Atlantic Standard Time]";
timezoneMap["America/Boa_Vista"] = "America/Boa_Vista [Amazon Time]";
timezoneMap["America/Campo_Grande"] = "America/Campo_Grande [Amazon Time]";
timezoneMap["America/Cuiaba"] = "America/Cuiaba [Amazon Time]";
timezoneMap["America/Curacao"] = "America/Curacao [Atlantic Standard Time]";
timezoneMap["America/Dominica"] = "America/Dominica [Atlantic Standard Time]";
timezoneMap["America/Eirunepe"] = "America/Eirunepe [Amazon Time]";
timezoneMap["America/Glace_Bay"] = "America/Glace_Bay [Atlantic Standard Time]";
timezoneMap["America/Goose_Bay"] = "America/Goose_Bay [Atlantic Standard Time]";
timezoneMap["America/Grenada"] = "America/Grenada [Atlantic Standard Time]";
timezoneMap["America/Guadeloupe"] = "America/Guadeloupe [Atlantic Standard Time]";
timezoneMap["America/Guyana"] = "America/Guyana [Guyana Time]";
timezoneMap["America/Halifax"] = "America/Halifax [Atlantic Standard Time]";
timezoneMap["America/Kralendijk"] = "America/Kralendijk [GMT-04:00]";
timezoneMap["America/La_Paz"] = "America/La_Paz [Bolivia Time]";
timezoneMap["America/Lower_Princes"] = "America/Lower_Princes [GMT-04:00]";
timezoneMap["America/Manaus"] = "America/Manaus [Amazon Time]";
timezoneMap["America/Marigot"] = "America/Marigot [Atlantic Standard Time]";
timezoneMap["America/Martinique"] = "America/Martinique [Atlantic Standard Time]";
timezoneMap["America/Moncton"] = "America/Moncton [Atlantic Standard Time]";
timezoneMap["America/Montserrat"] = "America/Montserrat [Atlantic Standard Time]";
timezoneMap["America/Port_of_Spain"] = "America/Port_of_Spain [Atlantic Standard Time]";
timezoneMap["America/Porto_Acre"] = "America/Porto_Acre [Amazon Time]";
timezoneMap["America/Porto_Velho"] = "America/Porto_Velho [Amazon Time]";
timezoneMap["America/Puerto_Rico"] = "America/Puerto_Rico [Atlantic Standard Time]";
timezoneMap["America/Rio_Branco"] = "America/Rio_Branco [Amazon Time]";
timezoneMap["America/Santiago"] = "America/Santiago [Chile Time]";
timezoneMap["America/Santo_Domingo"] = "America/Santo_Domingo [Atlantic Standard Time]";
timezoneMap["America/St_Barthelemy"] = "America/St_Barthelemy [Atlantic Standard Time]";
timezoneMap["America/St_Kitts"] = "America/St_Kitts [Atlantic Standard Time]";
timezoneMap["America/St_Lucia"] = "America/St_Lucia [Atlantic Standard Time]";
timezoneMap["America/St_Thomas"] = "America/St_Thomas [Atlantic Standard Time]";
timezoneMap["America/St_Vincent"] = "America/St_Vincent [Atlantic Standard Time]";
timezoneMap["America/Thule"] = "America/Thule [Atlantic Standard Time]";
timezoneMap["America/Tortola"] = "America/Tortola [Atlantic Standard Time]";
timezoneMap["America/Virgin"] = "America/Virgin [Atlantic Standard Time]";
timezoneMap["Antarctica/Palmer"] = "Antarctica/Palmer [Chile Time]";
timezoneMap["Atlantic/Bermuda"] = "Atlantic/Bermuda [Atlantic Standard Time]";
timezoneMap["Brazil/Acre"] = "Brazil/Acre [Amazon Time]";
timezoneMap["Brazil/West"] = "Brazil/West [Amazon Time]";
timezoneMap["Canada/Atlantic"] = "Canada/Atlantic [Atlantic Standard Time]";
timezoneMap["Chile/Continental"] = "Chile/Continental [Chile Time]";
timezoneMap["Etc/GMT+4"] = "Etc/GMT+4 [GMT-04:00]";
timezoneMap["PRT"] = "PRT [Atlantic Standard Time]";
timezoneMap["SystemV/AST4"] = "SystemV/AST4 [Atlantic Standard Time]";
timezoneMap["SystemV/AST4ADT"] = "SystemV/AST4ADT [Atlantic Standard Time]";
timezoneMap["America/St_Johns"] = "America/St_Johns [Newfoundland Standard Time]";
timezoneMap["CNT"] = "CNT [Newfoundland Standard Time]";
timezoneMap["Canada/Newfoundland"] = "Canada/Newfoundland [Newfoundland Standard Time]";
timezoneMap["AGT"] = "AGT [Argentine Time]";
timezoneMap["America/Araguaina"] = "America/Araguaina [Brasilia Time]";
timezoneMap["America/Argentina/Buenos_Aires"] = "America/Argentina/Buenos_Aires [Argentine Time]";
timezoneMap["America/Argentina/Catamarca"] = "America/Argentina/Catamarca [Argentine Time]";
timezoneMap["America/Argentina/ComodRivadavia"] = "America/Argentina/ComodRivadavia [Argentine Time]";
timezoneMap["America/Argentina/Cordoba"] = "America/Argentina/Cordoba [Argentine Time]";
timezoneMap["America/Argentina/Jujuy"] = "America/Argentina/Jujuy [Argentine Time]";
timezoneMap["America/Argentina/La_Rioja"] = "America/Argentina/La_Rioja [Argentine Time]";
timezoneMap["America/Argentina/Mendoza"] = "America/Argentina/Mendoza [Argentine Time]";
timezoneMap["America/Argentina/Rio_Gallegos"] = "America/Argentina/Rio_Gallegos [Argentine Time]";
timezoneMap["America/Argentina/Salta"] = "America/Argentina/Salta [Argentine Time]";
timezoneMap["America/Argentina/San_Juan"] = "America/Argentina/San_Juan [Argentine Time]";
timezoneMap["America/Argentina/Tucuman"] = "America/Argentina/Tucuman [Argentine Time]";
timezoneMap["America/Argentina/Ushuaia"] = "America/Argentina/Ushuaia [Argentine Time]";
timezoneMap["America/Bahia"] = "America/Bahia [Brasilia Time]";
timezoneMap["America/Belem"] = "America/Belem [Brasilia Time]";
timezoneMap["America/Buenos_Aires"] = "America/Buenos_Aires [Argentine Time]";
timezoneMap["America/Catamarca"] = "America/Catamarca [Argentine Time]";
timezoneMap["America/Cayenne"] = "America/Cayenne [French Guiana Time]";
timezoneMap["America/Cordoba"] = "America/Cordoba [Argentine Time]";
timezoneMap["America/Fortaleza"] = "America/Fortaleza [Brasilia Time]";
timezoneMap["America/Godthab"] = "America/Godthab [Western Greenland Time]";
timezoneMap["America/Jujuy"] = "America/Jujuy [Argentine Time]";
timezoneMap["America/Maceio"] = "America/Maceio [Brasilia Time]";
timezoneMap["America/Mendoza"] = "America/Mendoza [Argentine Time]";
timezoneMap["America/Miquelon"] = "America/Miquelon [Pierre & Miquelon Standard Time]";
timezoneMap["America/Montevideo"] = "America/Montevideo [Uruguay Time]";
timezoneMap["America/Paramaribo"] = "America/Paramaribo [Suriname Time]";
timezoneMap["America/Recife"] = "America/Recife [Brasilia Time]";
timezoneMap["America/Rosario"] = "America/Rosario [Argentine Time]";
timezoneMap["America/Santarem"] = "America/Santarem [Brasilia Time]";
timezoneMap["America/Sao_Paulo"] = "America/Sao_Paulo [Brasilia Time]";
timezoneMap["Antarctica/Rothera"] = "Antarctica/Rothera [Rothera Time]";
timezoneMap["Atlantic/Stanley"] = "Atlantic/Stanley [Falkland Is. Time]";
timezoneMap["BET"] = "BET [Brasilia Time]";
timezoneMap["Brazil/East"] = "Brazil/East [Brasilia Time]";
timezoneMap["Etc/GMT+3"] = "Etc/GMT+3 [GMT-03:00]";
timezoneMap["America/Noronha"] = "America/Noronha [Fernando de Noronha Time]";
timezoneMap["Atlantic/South_Georgia"] = "Atlantic/South_Georgia [South Georgia Standard Time]";
timezoneMap["Brazil/DeNoronha"] = "Brazil/DeNoronha [Fernando de Noronha Time]";
timezoneMap["Etc/GMT+2"] = "Etc/GMT+2 [GMT-02:00]";
timezoneMap["America/Scoresbysund"] = "America/Scoresbysund [Eastern Greenland Time]";
timezoneMap["Atlantic/Azores"] = "Atlantic/Azores [Azores Time]";
timezoneMap["Atlantic/Cape_Verde"] = "Atlantic/Cape_Verde [Cape Verde Time]";
timezoneMap["Etc/GMT+1"] = "Etc/GMT+1 [GMT-01:00]";
timezoneMap["Africa/Abidjan"] = "Africa/Abidjan [Greenwich Mean Time]";
timezoneMap["Africa/Accra"] = "Africa/Accra [Ghana Mean Time]";
timezoneMap["Africa/Bamako"] = "Africa/Bamako [Greenwich Mean Time]";
timezoneMap["Africa/Banjul"] = "Africa/Banjul [Greenwich Mean Time]";
timezoneMap["Africa/Bissau"] = "Africa/Bissau [Greenwich Mean Time]";
timezoneMap["Africa/Casablanca"] = "Africa/Casablanca [Western European Time]";
timezoneMap["Africa/Conakry"] = "Africa/Conakry [Greenwich Mean Time]";
timezoneMap["Africa/Dakar"] = "Africa/Dakar [Greenwich Mean Time]";
timezoneMap["Africa/El_Aaiun"] = "Africa/El_Aaiun [Western European Time]";
timezoneMap["Africa/Freetown"] = "Africa/Freetown [Greenwich Mean Time]";
timezoneMap["Africa/Lome"] = "Africa/Lome [Greenwich Mean Time]";
timezoneMap["Africa/Monrovia"] = "Africa/Monrovia [Greenwich Mean Time]";
timezoneMap["Africa/Nouakchott"] = "Africa/Nouakchott [Greenwich Mean Time]";
timezoneMap["Africa/Ouagadougou"] = "Africa/Ouagadougou [Greenwich Mean Time]";
timezoneMap["Africa/Sao_Tome"] = "Africa/Sao_Tome [Greenwich Mean Time]";
timezoneMap["Africa/Timbuktu"] = "Africa/Timbuktu [Greenwich Mean Time]";
timezoneMap["America/Danmarkshavn"] = "America/Danmarkshavn [Greenwich Mean Time]";
timezoneMap["Atlantic/Canary"] = "Atlantic/Canary [Western European Time]";
timezoneMap["Atlantic/Faeroe"] = "Atlantic/Faeroe [Western European Time]";
timezoneMap["Atlantic/Faroe"] = "Atlantic/Faroe [Western European Time]";
timezoneMap["Atlantic/Madeira"] = "Atlantic/Madeira [Western European Time]";
timezoneMap["Atlantic/Reykjavik"] = "Atlantic/Reykjavik [Greenwich Mean Time]";
timezoneMap["Atlantic/St_Helena"] = "Atlantic/St_Helena [Greenwich Mean Time]";
timezoneMap["Eire"] = "Eire [Greenwich Mean Time]";
timezoneMap["Etc/GMT"] = "Etc/GMT [GMT+00:00]";
timezoneMap["Etc/GMT+0"] = "Etc/GMT+0 [GMT+00:00]";
timezoneMap["Etc/GMT-0"] = "Etc/GMT-0 [GMT+00:00]";
timezoneMap["Etc/GMT0"] = "Etc/GMT0 [GMT+00:00]";
timezoneMap["Etc/Greenwich"] = "Etc/Greenwich [Greenwich Mean Time]";
timezoneMap["Etc/UCT"] = "Etc/UCT [Coordinated Universal Time]";
timezoneMap["Etc/UTC"] = "Etc/UTC [Coordinated Universal Time]";
timezoneMap["Etc/Universal"] = "Etc/Universal [Coordinated Universal Time]";
timezoneMap["Etc/Zulu"] = "Etc/Zulu [Coordinated Universal Time]";
timezoneMap["Europe/Belfast"] = "Europe/Belfast [Greenwich Mean Time]";
timezoneMap["Europe/Dublin"] = "Europe/Dublin [Greenwich Mean Time]";
timezoneMap["Europe/Guernsey"] = "Europe/Guernsey [Greenwich Mean Time]";
timezoneMap["Europe/Isle_of_Man"] = "Europe/Isle_of_Man [Greenwich Mean Time]";
timezoneMap["Europe/Jersey"] = "Europe/Jersey [Greenwich Mean Time]";
timezoneMap["Europe/Lisbon"] = "Europe/Lisbon [Western European Time]";
timezoneMap["Europe/London"] = "Europe/London [Greenwich Mean Time]";
timezoneMap["GB"] = "GB [Greenwich Mean Time]";
timezoneMap["GB-Eire"] = "GB-Eire [Greenwich Mean Time]";
timezoneMap["GMT"] = "GMT [Greenwich Mean Time]";
timezoneMap["GMT0"] = "GMT0 [GMT+00:00]";
timezoneMap["Greenwich"] = "Greenwich [Greenwich Mean Time]";
timezoneMap["Iceland"] = "Iceland [Greenwich Mean Time]";
timezoneMap["Portugal"] = "Portugal [Western European Time]";
timezoneMap["UCT"] = "UCT [Coordinated Universal Time]";
timezoneMap["UTC"] = "UTC [Coordinated Universal Time]";
timezoneMap["Universal"] = "Universal [Coordinated Universal Time]";
timezoneMap["WET"] = "WET [Western European Time]";
timezoneMap["Zulu"] = "Zulu [Coordinated Universal Time]";
timezoneMap["Africa/Algiers"] = "Africa/Algiers [Central European Time]";
timezoneMap["Africa/Bangui"] = "Africa/Bangui [Western African Time]";
timezoneMap["Africa/Brazzaville"] = "Africa/Brazzaville [Western African Time]";
timezoneMap["Africa/Ceuta"] = "Africa/Ceuta [Central European Time]";
timezoneMap["Africa/Douala"] = "Africa/Douala [Western African Time]";
timezoneMap["Africa/Kinshasa"] = "Africa/Kinshasa [Western African Time]";
timezoneMap["Africa/Lagos"] = "Africa/Lagos [Western African Time]";
timezoneMap["Africa/Libreville"] = "Africa/Libreville [Western African Time]";
timezoneMap["Africa/Luanda"] = "Africa/Luanda [Western African Time]";
timezoneMap["Africa/Malabo"] = "Africa/Malabo [Western African Time]";
timezoneMap["Africa/Ndjamena"] = "Africa/Ndjamena [Western African Time]";
timezoneMap["Africa/Niamey"] = "Africa/Niamey [Western African Time]";
timezoneMap["Africa/Porto-Novo"] = "Africa/Porto-Novo [Western African Time]";
timezoneMap["Africa/Tripoli"] = "Africa/Tripoli [Eastern European Time]";
timezoneMap["Africa/Tunis"] = "Africa/Tunis [Central European Time]";
timezoneMap["Africa/Windhoek"] = "Africa/Windhoek [Western African Time]";
timezoneMap["Arctic/Longyearbyen"] = "Arctic/Longyearbyen [Central European Time]";
timezoneMap["Atlantic/Jan_Mayen"] = "Atlantic/Jan_Mayen [Central European Time]";
timezoneMap["CET"] = "CET [Central European Time]";
timezoneMap["ECT"] = "ECT [Central European Time]";
timezoneMap["Etc/GMT-1"] = "Etc/GMT-1 [GMT+01:00]";
timezoneMap["Europe/Amsterdam"] = "Europe/Amsterdam [Central European Time]";
timezoneMap["Europe/Andorra"] = "Europe/Andorra [Central European Time]";
timezoneMap["Europe/Belgrade"] = "Europe/Belgrade [Central European Time]";
timezoneMap["Europe/Berlin"] = "Europe/Berlin [Central European Time]";
timezoneMap["Europe/Bratislava"] = "Europe/Bratislava [Central European Time]";
timezoneMap["Europe/Brussels"] = "Europe/Brussels [Central European Time]";
timezoneMap["Europe/Budapest"] = "Europe/Budapest [Central European Time]";
timezoneMap["Europe/Busingen"] = "Europe/Busingen [GMT+01:00]";
timezoneMap["Europe/Copenhagen"] = "Europe/Copenhagen [Central European Time]";
timezoneMap["Europe/Gibraltar"] = "Europe/Gibraltar [Central European Time]";
timezoneMap["Europe/Ljubljana"] = "Europe/Ljubljana [Central European Time]";
timezoneMap["Europe/Luxembourg"] = "Europe/Luxembourg [Central European Time]";
timezoneMap["Europe/Madrid"] = "Europe/Madrid [Central European Time]";
timezoneMap["Europe/Malta"] = "Europe/Malta [Central European Time]";
timezoneMap["Europe/Monaco"] = "Europe/Monaco [Central European Time]";
timezoneMap["Europe/Oslo"] = "Europe/Oslo [Central European Time]";
timezoneMap["Europe/Paris"] = "Europe/Paris [Central European Time]";
timezoneMap["Europe/Podgorica"] = "Europe/Podgorica [Central European Time]";
timezoneMap["Europe/Prague"] = "Europe/Prague [Central European Time]";
timezoneMap["Europe/Rome"] = "Europe/Rome [Central European Time]";
timezoneMap["Europe/San_Marino"] = "Europe/San_Marino [Central European Time]";
timezoneMap["Europe/Sarajevo"] = "Europe/Sarajevo [Central European Time]";
timezoneMap["Europe/Skopje"] = "Europe/Skopje [Central European Time]";
timezoneMap["Europe/Stockholm"] = "Europe/Stockholm [Central European Time]";
timezoneMap["Europe/Tirane"] = "Europe/Tirane [Central European Time]";
timezoneMap["Europe/Vaduz"] = "Europe/Vaduz [Central European Time]";
timezoneMap["Europe/Vatican"] = "Europe/Vatican [Central European Time]";
timezoneMap["Europe/Vienna"] = "Europe/Vienna [Central European Time]";
timezoneMap["Europe/Warsaw"] = "Europe/Warsaw [Central European Time]";
timezoneMap["Europe/Zagreb"] = "Europe/Zagreb [Central European Time]";
timezoneMap["Europe/Zurich"] = "Europe/Zurich [Central European Time]";
timezoneMap["Libya"] = "Libya [Eastern European Time]";
timezoneMap["MET"] = "MET [Middle Europe Time]";
timezoneMap["ART"] = "ART [Eastern European Time]";
timezoneMap["Africa/Blantyre"] = "Africa/Blantyre [Central African Time]";
timezoneMap["Africa/Bujumbura"] = "Africa/Bujumbura [Central African Time]";
timezoneMap["Africa/Cairo"] = "Africa/Cairo [Eastern European Time]";
timezoneMap["Africa/Gaborone"] = "Africa/Gaborone [Central African Time]";
timezoneMap["Africa/Harare"] = "Africa/Harare [Central African Time]";
timezoneMap["Africa/Johannesburg"] = "Africa/Johannesburg [South Africa Standard Time]";
timezoneMap["Africa/Kigali"] = "Africa/Kigali [Central African Time]";
timezoneMap["Africa/Lubumbashi"] = "Africa/Lubumbashi [Central African Time]";
timezoneMap["Africa/Lusaka"] = "Africa/Lusaka [Central African Time]";
timezoneMap["Africa/Maputo"] = "Africa/Maputo [Central African Time]";
timezoneMap["Africa/Maseru"] = "Africa/Maseru [South Africa Standard Time]";
timezoneMap["Africa/Mbabane"] = "Africa/Mbabane [South Africa Standard Time]";
timezoneMap["Asia/Amman"] = "Asia/Amman [Eastern European Time]";
timezoneMap["Asia/Beirut"] = "Asia/Beirut [Eastern European Time]";
timezoneMap["Asia/Damascus"] = "Asia/Damascus [Eastern European Time]";
timezoneMap["Asia/Gaza"] = "Asia/Gaza [Eastern European Time]";
timezoneMap["Asia/Hebron"] = "Asia/Hebron [GMT+02:00]";
timezoneMap["Asia/Istanbul"] = "Asia/Istanbul [Eastern European Time]";
timezoneMap["Asia/Jerusalem"] = "Asia/Jerusalem [Israel Standard Time]";
timezoneMap["Asia/Nicosia"] = "Asia/Nicosia [Eastern European Time]";
timezoneMap["Asia/Tel_Aviv"] = "Asia/Tel_Aviv [Israel Standard Time]";
timezoneMap["CAT"] = "CAT [Central African Time]";
timezoneMap["EET"] = "EET [Eastern European Time]";
timezoneMap["Egypt"] = "Egypt [Eastern European Time]";
timezoneMap["Etc/GMT-2"] = "Etc/GMT-2 [GMT+02:00]";
timezoneMap["Europe/Athens"] = "Europe/Athens [Eastern European Time]";
timezoneMap["Europe/Bucharest"] = "Europe/Bucharest [Eastern European Time]";
timezoneMap["Europe/Chisinau"] = "Europe/Chisinau [Eastern European Time]";
timezoneMap["Europe/Helsinki"] = "Europe/Helsinki [Eastern European Time]";
timezoneMap["Europe/Istanbul"] = "Europe/Istanbul [Eastern European Time]";
timezoneMap["Europe/Kiev"] = "Europe/Kiev [Eastern European Time]";
timezoneMap["Europe/Mariehamn"] = "Europe/Mariehamn [Eastern European Time]";
timezoneMap["Europe/Nicosia"] = "Europe/Nicosia [Eastern European Time]";
timezoneMap["Europe/Riga"] = "Europe/Riga [Eastern European Time]";
timezoneMap["Europe/Simferopol"] = "Europe/Simferopol [Eastern European Time]";
timezoneMap["Europe/Sofia"] = "Europe/Sofia [Eastern European Time]";
timezoneMap["Europe/Tallinn"] = "Europe/Tallinn [Eastern European Time]";
timezoneMap["Europe/Tiraspol"] = "Europe/Tiraspol [Eastern European Time]";
timezoneMap["Europe/Uzhgorod"] = "Europe/Uzhgorod [Eastern European Time]";
timezoneMap["Europe/Vilnius"] = "Europe/Vilnius [Eastern European Time]";
timezoneMap["Europe/Zaporozhye"] = "Europe/Zaporozhye [Eastern European Time]";
timezoneMap["Israel"] = "Israel [Israel Standard Time]";
timezoneMap["Turkey"] = "Turkey [Eastern European Time]";
timezoneMap["Africa/Addis_Ababa"] = "Africa/Addis_Ababa [Eastern African Time]";
timezoneMap["Africa/Asmara"] = "Africa/Asmara [Eastern African Time]";
timezoneMap["Africa/Asmera"] = "Africa/Asmera [Eastern African Time]";
timezoneMap["Africa/Dar_es_Salaam"] = "Africa/Dar_es_Salaam [Eastern African Time]";
timezoneMap["Africa/Djibouti"] = "Africa/Djibouti [Eastern African Time]";
timezoneMap["Africa/Juba"] = "Africa/Juba [GMT+03:00]";
timezoneMap["Africa/Kampala"] = "Africa/Kampala [Eastern African Time]";
timezoneMap["Africa/Khartoum"] = "Africa/Khartoum [Eastern African Time]";
timezoneMap["Africa/Mogadishu"] = "Africa/Mogadishu [Eastern African Time]";
timezoneMap["Africa/Nairobi"] = "Africa/Nairobi [Eastern African Time]";
timezoneMap["Antarctica/Syowa"] = "Antarctica/Syowa [Syowa Time]";
timezoneMap["Asia/Aden"] = "Asia/Aden [Arabia Standard Time]";
timezoneMap["Asia/Baghdad"] = "Asia/Baghdad [Arabia Standard Time]";
timezoneMap["Asia/Bahrain"] = "Asia/Bahrain [Arabia Standard Time]";
timezoneMap["Asia/Kuwait"] = "Asia/Kuwait [Arabia Standard Time]";
timezoneMap["Asia/Qatar"] = "Asia/Qatar [Arabia Standard Time]";
timezoneMap["Asia/Riyadh"] = "Asia/Riyadh [Arabia Standard Time]";
timezoneMap["EAT"] = "EAT [Eastern African Time]";
timezoneMap["Etc/GMT-3"] = "Etc/GMT-3 [GMT+03:00]";
timezoneMap["Europe/Kaliningrad"] = "Europe/Kaliningrad [Eastern European Time]";
timezoneMap["Europe/Minsk"] = "Europe/Minsk [Eastern European Time]";
timezoneMap["Indian/Antananarivo"] = "Indian/Antananarivo [Eastern African Time]";
timezoneMap["Indian/Comoro"] = "Indian/Comoro [Eastern African Time]";
timezoneMap["Indian/Mayotte"] = "Indian/Mayotte [Eastern African Time]";
timezoneMap["Asia/Riyadh87"] = "Asia/Riyadh87 [GMT+03:07]";
timezoneMap["Asia/Riyadh88"] = "Asia/Riyadh88 [GMT+03:07]";
timezoneMap["Asia/Riyadh89"] = "Asia/Riyadh89 [GMT+03:07]";
timezoneMap["Mideast/Riyadh87"] = "Mideast/Riyadh87 [GMT+03:07]";
timezoneMap["Mideast/Riyadh88"] = "Mideast/Riyadh88 [GMT+03:07]";
timezoneMap["Mideast/Riyadh89"] = "Mideast/Riyadh89 [GMT+03:07]";
timezoneMap["Asia/Tehran"] = "Asia/Tehran [Iran Standard Time]";
timezoneMap["Iran"] = "Iran [Iran Standard Time]";
timezoneMap["Asia/Baku"] = "Asia/Baku [Azerbaijan Time]";
timezoneMap["Asia/Dubai"] = "Asia/Dubai [Gulf Standard Time]";
timezoneMap["Asia/Muscat"] = "Asia/Muscat [Gulf Standard Time]";
timezoneMap["Asia/Tbilisi"] = "Asia/Tbilisi [Georgia Time]";
timezoneMap["Asia/Yerevan"] = "Asia/Yerevan [Armenia Time]";
timezoneMap["Etc/GMT-4"] = "Etc/GMT-4 [GMT+04:00]";
timezoneMap["Europe/Moscow"] = "Europe/Moscow [Moscow Standard Time]";
timezoneMap["Europe/Samara"] = "Europe/Samara [Samara Time]";
timezoneMap["Europe/Volgograd"] = "Europe/Volgograd [Volgograd Time]";
timezoneMap["Indian/Mahe"] = "Indian/Mahe [Seychelles Time]";
timezoneMap["Indian/Mauritius"] = "Indian/Mauritius [Mauritius Time]";
timezoneMap["Indian/Reunion"] = "Indian/Reunion [Reunion Time]";
timezoneMap["NET"] = "NET [Armenia Time]";
timezoneMap["W-SU"] = "W-SU [Moscow Standard Time]";
timezoneMap["Asia/Kabul"] = "Asia/Kabul [Afghanistan Time]";
timezoneMap["Antarctica/Mawson"] = "Antarctica/Mawson [Mawson Time]";
timezoneMap["Asia/Aqtau"] = "Asia/Aqtau [Aqtau Time]";
timezoneMap["Asia/Aqtobe"] = "Asia/Aqtobe [Aqtobe Time]";
timezoneMap["Asia/Ashgabat"] = "Asia/Ashgabat [Turkmenistan Time]";
timezoneMap["Asia/Ashkhabad"] = "Asia/Ashkhabad [Turkmenistan Time]";
timezoneMap["Asia/Dushanbe"] = "Asia/Dushanbe [Tajikistan Time]";
timezoneMap["Asia/Karachi"] = "Asia/Karachi [Pakistan Time]";
timezoneMap["Asia/Oral"] = "Asia/Oral [Oral Time]";
timezoneMap["Asia/Samarkand"] = "Asia/Samarkand [Uzbekistan Time]";
timezoneMap["Asia/Tashkent"] = "Asia/Tashkent [Uzbekistan Time]";
timezoneMap["Etc/GMT-5"] = "Etc/GMT-5 [GMT+05:00]";
timezoneMap["Indian/Kerguelen"] = "Indian/Kerguelen [French Southern & Antarctic Lands Time]";
timezoneMap["Indian/Maldives"] = "Indian/Maldives [Maldives Time]";
timezoneMap["PLT"] = "PLT [Pakistan Time]";
timezoneMap["Asia/Calcutta"] = "Asia/Calcutta [India Standard Time]";
timezoneMap["Asia/Colombo"] = "Asia/Colombo [India Standard Time]";
timezoneMap["Asia/Kolkata"] = "Asia/Kolkata [India Standard Time]";
timezoneMap["IST"] = "IST [India Standard Time]";
timezoneMap["Asia/Kathmandu"] = "Asia/Kathmandu [Nepal Time]";
timezoneMap["Asia/Katmandu"] = "Asia/Katmandu [Nepal Time]";
timezoneMap["Antarctica/Vostok"] = "Antarctica/Vostok [Vostok Time]";
timezoneMap["Asia/Almaty"] = "Asia/Almaty [Alma-Ata Time]";
timezoneMap["Asia/Bishkek"] = "Asia/Bishkek [Kirgizstan Time]";
timezoneMap["Asia/Dacca"] = "Asia/Dacca [Bangladesh Time]";
timezoneMap["Asia/Dhaka"] = "Asia/Dhaka [Bangladesh Time]";
timezoneMap["Asia/Qyzylorda"] = "Asia/Qyzylorda [Qyzylorda Time]";
timezoneMap["Asia/Thimbu"] = "Asia/Thimbu [Bhutan Time]";
timezoneMap["Asia/Thimphu"] = "Asia/Thimphu [Bhutan Time]";
timezoneMap["Asia/Yekaterinburg"] = "Asia/Yekaterinburg [Yekaterinburg Time]";
timezoneMap["BST"] = "BST [Bangladesh Time]";
timezoneMap["Etc/GMT-6"] = "Etc/GMT-6 [GMT+06:00]";
timezoneMap["Indian/Chagos"] = "Indian/Chagos [Indian Ocean Territory Time]";
timezoneMap["Asia/Rangoon"] = "Asia/Rangoon [Myanmar Time]";
timezoneMap["Indian/Cocos"] = "Indian/Cocos [Cocos Islands Time]";
timezoneMap["Antarctica/Davis"] = "Antarctica/Davis [Davis Time]";
timezoneMap["Asia/Bangkok"] = "Asia/Bangkok [Indochina Time]";
timezoneMap["Asia/Ho_Chi_Minh"] = "Asia/Ho_Chi_Minh [Indochina Time]";
timezoneMap["Asia/Hovd"] = "Asia/Hovd [Hovd Time]";
timezoneMap["Asia/Jakarta"] = "Asia/Jakarta [West Indonesia Time]";
timezoneMap["Asia/Novokuznetsk"] = "Asia/Novokuznetsk [Novosibirsk Time]";
timezoneMap["Asia/Novosibirsk"] = "Asia/Novosibirsk [Novosibirsk Time]";
timezoneMap["Asia/Omsk"] = "Asia/Omsk [Omsk Time]";
timezoneMap["Asia/Phnom_Penh"] = "Asia/Phnom_Penh [Indochina Time]";
timezoneMap["Asia/Pontianak"] = "Asia/Pontianak [West Indonesia Time]";
timezoneMap["Asia/Saigon"] = "Asia/Saigon [Indochina Time]";
timezoneMap["Asia/Vientiane"] = "Asia/Vientiane [Indochina Time]";
timezoneMap["Etc/GMT-7"] = "Etc/GMT-7 [GMT+07:00]";
timezoneMap["Indian/Christmas"] = "Indian/Christmas [Christmas Island Time]";
timezoneMap["VST"] = "VST [Indochina Time]";
timezoneMap["Antarctica/Casey"] = "Antarctica/Casey [Western Standard Time (Australia)]";
timezoneMap["Asia/Brunei"] = "Asia/Brunei [Brunei Time]";
timezoneMap["Asia/Choibalsan"] = "Asia/Choibalsan [Choibalsan Time]";
timezoneMap["Asia/Chongqing"] = "Asia/Chongqing [China Standard Time]";
timezoneMap["Asia/Chungking"] = "Asia/Chungking [China Standard Time]";
timezoneMap["Asia/Harbin"] = "Asia/Harbin [China Standard Time]";
timezoneMap["Asia/Hong_Kong"] = "Asia/Hong_Kong [Hong Kong Time]";
timezoneMap["Asia/Kashgar"] = "Asia/Kashgar [China Standard Time]";
timezoneMap["Asia/Krasnoyarsk"] = "Asia/Krasnoyarsk [Krasnoyarsk Time]";
timezoneMap["Asia/Kuala_Lumpur"] = "Asia/Kuala_Lumpur [Malaysia Time]";
timezoneMap["Asia/Kuching"] = "Asia/Kuching [Malaysia Time]";
timezoneMap["Asia/Macao"] = "Asia/Macao [China Standard Time]";
timezoneMap["Asia/Macau"] = "Asia/Macau [China Standard Time]";
timezoneMap["Asia/Makassar"] = "Asia/Makassar [Central Indonesia Time]";
timezoneMap["Asia/Manila"] = "Asia/Manila [Philippines Time]";
timezoneMap["Asia/Shanghai"] = "Asia/Shanghai [China Standard Time]";
timezoneMap["Asia/Singapore"] = "Asia/Singapore [Singapore Time]";
timezoneMap["Asia/Taipei"] = "Asia/Taipei [China Standard Time]";
timezoneMap["Asia/Ujung_Pandang"] = "Asia/Ujung_Pandang [Central Indonesia Time]";
timezoneMap["Asia/Ulaanbaatar"] = "Asia/Ulaanbaatar [Ulaanbaatar Time]";
timezoneMap["Asia/Ulan_Bator"] = "Asia/Ulan_Bator [Ulaanbaatar Time]";
timezoneMap["Asia/Urumqi"] = "Asia/Urumqi [China Standard Time]";
timezoneMap["Australia/Perth"] = "Australia/Perth [Western Standard Time (Australia)]";
timezoneMap["Australia/West"] = "Australia/West [Western Standard Time (Australia)]";
timezoneMap["CTT"] = "CTT [China Standard Time]";
timezoneMap["Etc/GMT-8"] = "Etc/GMT-8 [GMT+08:00]";
timezoneMap["Hongkong"] = "Hongkong [Hong Kong Time]";
timezoneMap["PRC"] = "PRC [China Standard Time]";
timezoneMap["Singapore"] = "Singapore [Singapore Time]";
timezoneMap["Australia/Eucla"] = "Australia/Eucla [Central Western Standard Time (Australia)]";
timezoneMap["Asia/Dili"] = "Asia/Dili [Timor-Leste Time]";
timezoneMap["Asia/Irkutsk"] = "Asia/Irkutsk [Irkutsk Time]";
timezoneMap["Asia/Jayapura"] = "Asia/Jayapura [East Indonesia Time]";
timezoneMap["Asia/Pyongyang"] = "Asia/Pyongyang [Korea Standard Time]";
timezoneMap["Asia/Seoul"] = "Asia/Seoul [Korea Standard Time]";
timezoneMap["Asia/Tokyo"] = "Asia/Tokyo [Japan Standard Time]";
timezoneMap["Etc/GMT-9"] = "Etc/GMT-9 [GMT+09:00]";
timezoneMap["JST"] = "JST [Japan Standard Time]";
timezoneMap["Japan"] = "Japan [Japan Standard Time]";
timezoneMap["Pacific/Palau"] = "Pacific/Palau [Palau Time]";
timezoneMap["ROK"] = "ROK [Korea Standard Time]";
timezoneMap["ACT"] = "ACT [Central Standard Time (Northern Territory)]";
timezoneMap["Australia/Adelaide"] = "Australia/Adelaide [Central Standard Time (South Australia)]";
timezoneMap["Australia/Broken_Hill"] = "Australia/Broken_Hill [Central Standard Time (South Australia/New South Wales)]";
timezoneMap["Australia/Darwin"] = "Australia/Darwin [Central Standard Time (Northern Territory)]";
timezoneMap["Australia/North"] = "Australia/North [Central Standard Time (Northern Territory)]";
timezoneMap["Australia/South"] = "Australia/South [Central Standard Time (South Australia)]";
timezoneMap["Australia/Yancowinna"] = "Australia/Yancowinna [Central Standard Time (South Australia/New South Wales)]";
timezoneMap["AET"] = "AET [Eastern Standard Time (New South Wales)]";
timezoneMap["Antarctica/DumontDUrville"] = "Antarctica/DumontDUrville [Dumont-d'Urville Time]";
timezoneMap["Asia/Khandyga"] = "Asia/Khandyga [GMT+10:00]";
timezoneMap["Asia/Yakutsk"] = "Asia/Yakutsk [Yakutsk Time]";
timezoneMap["Australia/ACT"] = "Australia/ACT [Eastern Standard Time (New South Wales)]";
timezoneMap["Australia/Brisbane"] = "Australia/Brisbane [Eastern Standard Time (Queensland)]";
timezoneMap["Australia/Canberra"] = "Australia/Canberra [Eastern Standard Time (New South Wales)]";
timezoneMap["Australia/Currie"] = "Australia/Currie [Eastern Standard Time (New South Wales)]";
timezoneMap["Australia/Hobart"] = "Australia/Hobart [Eastern Standard Time (Tasmania)]";
timezoneMap["Australia/Lindeman"] = "Australia/Lindeman [Eastern Standard Time (Queensland)]";
timezoneMap["Australia/Melbourne"] = "Australia/Melbourne [Eastern Standard Time (Victoria)]";
timezoneMap["Australia/NSW"] = "Australia/NSW [Eastern Standard Time (New South Wales)]";
timezoneMap["Australia/Queensland"] = "Australia/Queensland [Eastern Standard Time (Queensland)]";
timezoneMap["Australia/Sydney"] = "Australia/Sydney [Eastern Standard Time (New South Wales)]";
timezoneMap["Australia/Tasmania"] = "Australia/Tasmania [Eastern Standard Time (Tasmania)]";
timezoneMap["Australia/Victoria"] = "Australia/Victoria [Eastern Standard Time (Victoria)]";
timezoneMap["Etc/GMT-10"] = "Etc/GMT-10 [GMT+10:00]";
timezoneMap["Pacific/Chuuk"] = "Pacific/Chuuk [GMT+10:00]";
timezoneMap["Pacific/Guam"] = "Pacific/Guam [Chamorro Standard Time]";
timezoneMap["Pacific/Port_Moresby"] = "Pacific/Port_Moresby [Papua New Guinea Time]";
timezoneMap["Pacific/Saipan"] = "Pacific/Saipan [Chamorro Standard Time]";
timezoneMap["Pacific/Truk"] = "Pacific/Truk [Truk Time]";
timezoneMap["Pacific/Yap"] = "Pacific/Yap [Truk Time]";
timezoneMap["Australia/LHI"] = "Australia/LHI [Lord Howe Standard Time]";
timezoneMap["Australia/Lord_Howe"] = "Australia/Lord_Howe [Lord Howe Standard Time]";
timezoneMap["Antarctica/Macquarie"] = "Antarctica/Macquarie [Macquarie Island Time]";
timezoneMap["Asia/Sakhalin"] = "Asia/Sakhalin [Sakhalin Time]";
timezoneMap["Asia/Ust-Nera"] = "Asia/Ust-Nera [GMT+11:00]";
timezoneMap["Asia/Vladivostok"] = "Asia/Vladivostok [Vladivostok Time]";
timezoneMap["Etc/GMT-11"] = "Etc/GMT-11 [GMT+11:00]";
timezoneMap["Pacific/Efate"] = "Pacific/Efate [Vanuatu Time]";
timezoneMap["Pacific/Guadalcanal"] = "Pacific/Guadalcanal [Solomon Is. Time]";
timezoneMap["Pacific/Kosrae"] = "Pacific/Kosrae [Kosrae Time]";
timezoneMap["Pacific/Noumea"] = "Pacific/Noumea [New Caledonia Time]";
timezoneMap["Pacific/Pohnpei"] = "Pacific/Pohnpei [GMT+11:00]";
timezoneMap["Pacific/Ponape"] = "Pacific/Ponape [Ponape Time]";
timezoneMap["SST"] = "SST [Solomon Is. Time]";
timezoneMap["Pacific/Norfolk"] = "Pacific/Norfolk [Norfolk Time]";
timezoneMap["Antarctica/McMurdo"] = "Antarctica/McMurdo [New Zealand Standard Time]";
timezoneMap["Antarctica/South_Pole"] = "Antarctica/South_Pole [New Zealand Standard Time]";
timezoneMap["Asia/Anadyr"] = "Asia/Anadyr [Anadyr Time]";
timezoneMap["Asia/Kamchatka"] = "Asia/Kamchatka [Petropavlovsk-Kamchatski Time]";
timezoneMap["Asia/Magadan"] = "Asia/Magadan [Magadan Time]";
timezoneMap["Etc/GMT-12"] = "Etc/GMT-12 [GMT+12:00]";
timezoneMap["Kwajalein"] = "Kwajalein [Marshall Islands Time]";
timezoneMap["NST"] = "NST [New Zealand Standard Time]";
timezoneMap["NZ"] = "NZ [New Zealand Standard Time]";
timezoneMap["Pacific/Auckland"] = "Pacific/Auckland [New Zealand Standard Time]";
timezoneMap["Pacific/Fiji"] = "Pacific/Fiji [Fiji Time]";
timezoneMap["Pacific/Funafuti"] = "Pacific/Funafuti [Tuvalu Time]";
timezoneMap["Pacific/Kwajalein"] = "Pacific/Kwajalein [Marshall Islands Time]";
timezoneMap["Pacific/Majuro"] = "Pacific/Majuro [Marshall Islands Time]";
timezoneMap["Pacific/Nauru"] = "Pacific/Nauru [Nauru Time]";
timezoneMap["Pacific/Tarawa"] = "Pacific/Tarawa [Gilbert Is. Time]";
timezoneMap["Pacific/Wake"] = "Pacific/Wake [Wake Time]";
timezoneMap["Pacific/Wallis"] = "Pacific/Wallis [Wallis & Futuna Time]";
timezoneMap["NZ-CHAT"] = "NZ-CHAT [Chatham Standard Time]";
timezoneMap["Pacific/Chatham"] = "Pacific/Chatham [Chatham Standard Time]";
timezoneMap["Etc/GMT-13"] = "Etc/GMT-13 [GMT+13:00]";
timezoneMap["MIT"] = "MIT [West Samoa Time]";
timezoneMap["Pacific/Apia"] = "Pacific/Apia [West Samoa Time]";
timezoneMap["Pacific/Enderbury"] = "Pacific/Enderbury [Phoenix Is. Time]";
timezoneMap["Pacific/Fakaofo"] = "Pacific/Fakaofo [Tokelau Time]";
timezoneMap["Pacific/Tongatapu"] = "Pacific/Tongatapu [Tonga Time]";
timezoneMap["Etc/GMT-14"] = "Etc/GMT-14 [GMT+14:00]";
timezoneMap["Pacific/Kiritimati"] = "Pacific/Kiritimati [Line Is. Time]";
// CloudStack common API helpers
cloudStack.api = {
actions: {
sort: function(updateCommand, objType) {
var action = function(args) {
$.ajax({
url: createURL(updateCommand),
data: {
id: args.context[objType].id,
sortKey: args.index
},
success: function(json) {
args.response.success();
},
error: function(json) {
args.response.error(parseXMLHttpResponse(json));
}
});
};
return {
moveTop: {
action: action
},
moveBottom: {
action: action
},
moveUp: {
action: action
},
moveDown: {
action: action
},
moveDrag: {
action: action
}
}
}
},
tags: function(args) {
var resourceType = args.resourceType;
var contextId = args.contextId;
return {
actions: {
add: function(args) {
var data = args.data;
var resourceId = args.context[contextId][0].id;
$.ajax({
url: createURL('createTags'),
data: {
'tags[0].key': data.key,
'tags[0].value': data.value,
resourceIds: resourceId,
resourceType: resourceType
},
success: function(json) {
args.response.success({
_custom: {
jobId: json.createtagsresponse.jobid
},
notification: {
desc: 'Add tag for ' + resourceType,
poll: pollAsyncJobResult
}
});
}
});
},
remove: function(args) {
var data = args.context.tagItems[0];
var resourceId = args.context[contextId][0].id;
$.ajax({
url: createURL('deleteTags'),
data: {
'tags[0].key': data.key,
'tags[0].value': data.value,
resourceIds: resourceId,
resourceType: resourceType
},
success: function(json) {
args.response.success({
_custom: {
jobId: json.deletetagsresponse.jobid
},
notification: {
desc: 'Remove tag for ' + resourceType,
poll: pollAsyncJobResult
}
});
}
});
}
},
dataProvider: function(args) {
var resourceId = args.context[contextId][0].id;
var data = {
resourceId: resourceId,
resourceType: resourceType
};
if (isAdmin() || isDomainAdmin()) {
data.listAll = true;
}
if (args.context.projects) {
data.projectid = args.context.projects[0].id;
}
if (args.jsonObj != null && args.jsonObj.projectid != null && data.projectid == null) {
data.projectid = args.jsonObj.projectid;
}
$.ajax({
url: createURL('listTags'),
data: data,
success: function(json) {
args.response.success({
data: json.listtagsresponse ? json.listtagsresponse.tag : []
});
},
error: function(json) {
args.response.error(parseXMLHttpResponse(json));
}
});
}
};
}
};
| mufaddalq/cloudstack-datera-driver | ui/scripts/sharedFunctions.js | JavaScript | apache-2.0 | 103,875 |
import authReducer, { authTypes } from '../../../src/redux/modules/auth';
describe('(Reducer) auth', () => {
let reducer;
it('returns the initial state', () => {
reducer = authReducer(undefined, {});
expect(reducer).to.deep.equal({
isAuthenticated: false,
isFetching: false,
isLoggingOut: false,
idToken: null,
accessToken: null,
profile: {},
error: null,
});
});
it('handles NOT_LOGGED_IN', () => {
reducer = authReducer(undefined, {
type: authTypes.NOT_LOGGED_IN,
});
expect(reducer).to.deep.equal({
isAuthenticated: false,
isFetching: false,
isLoggingOut: false,
idToken: null,
accessToken: null,
profile: {},
error: null,
});
});
it('handles IS_LOGGED_IN', () => {
reducer = authReducer(undefined, {
type: authTypes.IS_LOGGED_IN,
});
expect(reducer).to.deep.equal({
isAuthenticated: false,
isFetching: false,
isLoggingOut: false,
idToken: null,
accessToken: null,
profile: {},
error: null,
});
});
it('handles LOGIN_STATUS', () => {
reducer = authReducer(undefined, {
type: authTypes.LOGIN_STATUS,
});
expect(reducer).to.deep.equal({
isAuthenticated: false,
isFetching: false,
isLoggingOut: false,
idToken: null,
accessToken: null,
profile: {},
error: null,
});
});
it('handles LOGIN_REQUEST', () => {
reducer = authReducer(undefined, {
type: authTypes.LOGIN_REQUEST,
});
expect(reducer).to.deep.equal({
isAuthenticated: false,
isFetching: true,
isLoggingOut: false,
idToken: null,
accessToken: null,
profile: {},
error: null,
});
});
it('handles LOGIN_SUCCESS', () => {
reducer = authReducer(undefined, {
type: authTypes.LOGIN_SUCCESS,
idToken: 'foo',
accessToken: 'bar',
profile: { fakeProperty: 'fakeValue' },
});
expect(reducer).to.deep.equal({
isAuthenticated: true,
isFetching: false,
isLoggingOut: false,
idToken: 'foo',
accessToken: 'bar',
profile: { fakeProperty: 'fakeValue' },
error: null,
});
});
it('handles LOGIN_ERROR', () => {
reducer = authReducer(undefined, {
type: authTypes.LOGIN_ERROR,
error: 'fakeError',
});
expect(reducer).to.deep.equal({
isAuthenticated: false,
isFetching: false,
isLoggingOut: false,
idToken: null,
accessToken: null,
profile: {},
error: 'fakeError',
});
});
it('handles LOGOUT_REQUEST', () => {
reducer = authReducer(undefined, {
type: authTypes.LOGOUT_REQUEST,
});
expect(reducer).to.deep.equal({
isAuthenticated: false,
isFetching: false,
isLoggingOut: true,
idToken: null,
accessToken: null,
profile: {},
error: null,
});
});
it('handles LOGOUT_SUCCESS', () => {
reducer = authReducer(undefined, {
type: authTypes.LOGOUT_SUCCESS,
isLoggingOut: false,
error: 'fakeError',
});
expect(reducer).to.deep.equal({
isAuthenticated: false,
isFetching: false,
isLoggingOut: false,
idToken: null,
accessToken: null,
profile: {},
error: null,
});
});
});
| deafchi/signsfive-web | tests/redux/auth/reducer.test.js | JavaScript | apache-2.0 | 3,344 |
var mttt = {};
(function() {
// application state variables are held in this namespace.
// Like the current app window, for instance, which is created in app.js
mttt.app = {};
// app-parameters
mttt.app.screenWidth = Ti.Platform.displayCaps.platformWidth;
mttt.app.screenHeight = Ti.Platform.displayCaps.platformHeight;
})();
//Include additional namespaces
Ti.include(
'/config/config.js',
'/ui/ui.js',
'/model/model.js',
'/GameServerProxy.js'
); | asattler/MobileTicTacToe | Resources/mttt.js | JavaScript | apache-2.0 | 462 |
$(function () {
'use strict';
//下拉刷新页面
$(document).on("pageInit", "#page-ptr", function(e, id, page) {
var $content = $(page).find(".content").on('refresh', function(e) {
// 模拟2s的加载过程
setTimeout(function() {
var cardHTML = '<div class="card">' +
'<div class="card-header">标题</div>' +
'<div class="card-content">' +
'<div class="card-content-inner">内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容' +
'</div>' +
'</div>' +
'</div>';
$content.find('.card-container').prepend(cardHTML);
// 加载完毕需要重置
$.pullToRefreshDone($content);
}, 2000);
});
});
//无限滚动
$(document).on("pageInit", "#page-infinite-scroll", function(e, id, page) {
function addItems(number, lastIndex) {
// 生成新条目的HTML
var html = '';
for (var i = 0; i < 20; i++) {
html += '<li class="item-content"><div class="item-inner"><div class="item-title">新条目</div></div></li>';
}
// 添加新条目
$('.infinite-scroll .list-container').append(html);
}
var loading = false;
$(page).on('infinite', function() {
// 如果正在加载,则退出
if (loading) return;
// 设置flag
loading = true;
// 模拟1s的加载过程
setTimeout(function() {
// 重置加载flag
loading = false;
addItems();
$.refreshScroller();
}, 1000);
});
});
//图片浏览器
$(document).on("pageInit", "#page-photo-browser", function(e, id, page) {
var myPhotoBrowserStandalone = $.photoBrowser({
photos : [
'//img.alicdn.com/tps/i3/TB1kt4wHVXXXXb_XVXX0HY8HXXX-1024-1024.jpeg',
'//img.alicdn.com/tps/i1/TB1SKhUHVXXXXb7XXXX0HY8HXXX-1024-1024.jpeg',
'//img.alicdn.com/tps/i4/TB1AdxNHVXXXXasXpXX0HY8HXXX-1024-1024.jpeg',
]
});
//点击时打开图片浏览器
$(page).on('click','.pb-standalone',function () {
myPhotoBrowserStandalone.open();
});
/*=== Popup ===*/
var myPhotoBrowserPopup = $.photoBrowser({
photos : [
'//img.alicdn.com/tps/i3/TB1kt4wHVXXXXb_XVXX0HY8HXXX-1024-1024.jpeg',
'//img.alicdn.com/tps/i1/TB1SKhUHVXXXXb7XXXX0HY8HXXX-1024-1024.jpeg',
'//img.alicdn.com/tps/i4/TB1AdxNHVXXXXasXpXX0HY8HXXX-1024-1024.jpeg',
],
type: 'popup'
});
$(page).on('click','.pb-popup',function () {
myPhotoBrowserPopup.open();
});
/*=== 有标题 ===*/
var myPhotoBrowserCaptions = $.photoBrowser({
photos : [
{
url: '//img.alicdn.com/tps/i3/TB1kt4wHVXXXXb_XVXX0HY8HXXX-1024-1024.jpeg',
caption: 'Caption 1 Text'
},
{
url: '//img.alicdn.com/tps/i1/TB1SKhUHVXXXXb7XXXX0HY8HXXX-1024-1024.jpeg',
caption: 'Second Caption Text'
},
// 这个没有标题
{
url: '//img.alicdn.com/tps/i4/TB1AdxNHVXXXXasXpXX0HY8HXXX-1024-1024.jpeg',
},
],
theme: 'dark',
type: 'standalone'
});
$(page).on('click','.pb-standalone-captions',function () {
myPhotoBrowserCaptions.open();
});
});
//对话框
$(document).on("pageInit", "#page-modal", function(e, id, page) {
var $content = $(page).find('.content');
$content.on('click','.alert-text',function () {
$.alert('这是一段提示消息');
});
$content.on('click','.alert-text-title', function () {
$.alert('这是一段提示消息', '这是自定义的标题!');
});
$content.on('click', '.alert-text-title-callback',function () {
$.alert('这是自定义的文案', '这是自定义的标题!', function () {
$.alert('你点击了确定按钮!')
});
});
$content.on('click','.confirm-ok', function () {
$.confirm('你确定吗?', function () {
$.alert('你点击了确定按钮!');
});
});
$content.on('click','.prompt-ok', function () {
$.prompt('你叫什么问题?', function (value) {
$.alert('你输入的名字是"' + value + '"');
});
});
});
//操作表
$(document).on("pageInit", "#page-action", function(e, id, page) {
$(page).on('click','.create-actions', function () {
var buttons1 = [
{
text: '请选择',
label: true
},
{
text: '卖出',
bold: true,
color: 'danger',
onClick: function() {
$.alert("你选择了“卖出“");
}
},
{
text: '买入',
onClick: function() {
$.alert("你选择了“买入“");
}
}
];
var buttons2 = [
{
text: '取消',
bg: 'danger'
}
];
var groups = [buttons1, buttons2];
$.actions(groups);
});
});
//加载提示符
$(document).on("pageInit", "#page-preloader", function(e, id, page) {
$(page).on('click','.open-preloader-title', function () {
$.showPreloader('加载中...')
setTimeout(function () {
$.hidePreloader();
}, 2000);
});
$(page).on('click','.open-indicator', function () {
$.showIndicator();
setTimeout(function () {
$.hideIndicator();
}, 2000);
});
});
//选择颜色主题
$(document).on("click", ".select-color", function(e) {
var b = $(e.target);
document.body.className = "theme-" + (b.data("color") || "");
b.parent().find(".active").removeClass("active");
b.addClass("active");
});
//picker
$(document).on("pageInit", "#page-picker", function(e, id, page) {
$("#picker").picker({
toolbarTemplate: '<header class="bar bar-nav">\
<button class="button button-link pull-left">\
按钮\
</button>\
<button class="button button-link pull-right close-picker">\
确定\
</button>\
<h1 class="title">标题</h1>\
</header>',
cols: [
{
textAlign: 'center',
values: ['iPhone 4', 'iPhone 4S', 'iPhone 5', 'iPhone 5S', 'iPhone 6', 'iPhone 6 Plus', 'iPad 2', 'iPad Retina', 'iPad Air', 'iPad mini', 'iPad mini 2', 'iPad mini 3']
}
]
});
$("#picker-name").picker({
toolbarTemplate: '<header class="bar bar-nav">\
<button class="button button-link pull-right close-picker">确定</button>\
<h1 class="title">请选择称呼</h1>\
</header>',
cols: [
{
textAlign: 'center',
values: ['赵', '钱', '孙', '李', '周', '吴', '郑', '王']
},
{
textAlign: 'center',
values: ['杰伦', '磊', '明', '小鹏', '燕姿', '菲菲', 'Baby']
},
{
textAlign: 'center',
values: ['先生', '小姐']
}
]
});
});
$(document).on("pageInit", "#page-datetime-picker", function(e) {
$("#datetime-picker").datetimePicker({
toolbarTemplate: '<header class="bar bar-nav">\
<button class="button button-link pull-right close-picker">确定</button>\
<h1 class="title">选择日期和时间</h1>\
</header>'
});
});
$(document).on("pageInit", "#page-city-picker", function(e) {
$("#city-picker").cityPicker({});
});
$.init();
});
| sdc-alibaba/generator-msui | app/templates/without_compile/docs/assets/js/demos.js | JavaScript | apache-2.0 | 7,450 |
const test = require('../testlib');
test.run(async function () {
await test('admin', async function (assert, req) {
//Try to set soa for non exitent domain
var res = await req({
url: '/domains/100/soa',
method: 'put',
data: {
primary: 'ns1.example.com',
email: 'hostmaster@example.com',
refresh: 3600,
retry: 900,
expire: 604800,
ttl: 86400
}
});
assert.equal(res.status, 404, 'Updating SOA for not existing domain should fail');
//Try to set soa for slave domain
var res = await req({
url: '/domains/2/soa',
method: 'put',
data: {
primary: 'ns1.example.com',
email: 'hostmaster@example.com',
refresh: 3600,
retry: 900,
expire: 604800,
ttl: 86400
}
});
assert.equal(res.status, 405, 'Updating SOA for slave domain should fail');
//Try to set soa with missing fields
var res = await req({
url: '/domains/2/soa',
method: 'put',
data: {
primary: 'ns1.example.com',
retry: 900,
expire: 604800,
ttl: 86400
}
});
assert.equal(res.status, 422, 'Updating SOA with missing fields should fail.');
//Getting soa data from master zone without soa should fail
var res = await req({
url: '/domains/4/soa',
method: 'get'
});
assert.equal(res.status, 404, 'Not existing soa should trigger error');
//Getting soa data from slave zone should fail
var res = await req({
url: '/domains/2/soa',
method: 'get'
});
assert.equal(res.status, 404, 'Geting soa from slave should trigger error');
//Soa data for test
var soaData = {
primary: 'ns1.example.com',
email: 'hostmaster@example.com',
refresh: 3600,
retry: 900,
expire: 604800,
ttl: 86400
};
//Set soa for zone without one
var res = await req({
url: '/domains/1/soa',
method: 'put',
data: soaData
});
assert.equal(res.status, 204, 'Updating SOA for Zone without one should succeed.');
//Get the new soa
var res = await req({
url: '/domains/1/soa',
method: 'get'
});
assert.equal(res.status, 200, 'Getting soa should succeed.');
const firstSerial = res.data.serial;
delete res.data['serial'];
assert.equal(res.data, soaData, 'The set and get data should be equal');
//Soa data for update test
soaData = {
primary: 'ns2.example.com',
email: 'hostmasterFoo@example.com',
refresh: 3601,
retry: 901,
expire: 604801,
ttl: 86401
};
//Update soa with new values
var res = await req({
url: '/domains/1/soa',
method: 'put',
data: soaData
});
assert.equal(res.status, 204, 'Updating SOA for Zone should succeed.');
//Check if update suceeded
var res = await req({
url: '/domains/1/soa',
method: 'get'
});
assert.equal(res.status, 200, 'Getting updated soa should succeed.');
assert.true(firstSerial < res.data.serial, 'Serial value should increase with update');
delete res.data['serial'];
assert.equal(res.data, soaData, 'The set and get data should be equal after update');
});
await test('user', async function (assert, req) {
//Soa data for test
var soaData = {
primary: 'ns1.example.com',
email: 'hostmaster@example.com',
refresh: 3600,
retry: 900,
expire: 604800,
ttl: 86400
};
//Updating soa for domain with permissions should work
var res = await req({
url: '/domains/1/soa',
method: 'put',
data: soaData
});
assert.equal(res.status, 204, 'Updating SOA for Zone should succeed for user.');
//Get the updated soa
var res = await req({
url: '/domains/1/soa',
method: 'get'
});
assert.equal(res.status, 200, 'Getting soa should succeed for user.');
delete res.data['serial'];
assert.equal(res.data, soaData, 'The set and get data should be equal');
//Updating soa for domain with permissions should work
var res = await req({
url: '/domains/4/soa',
method: 'put',
data: soaData
});
assert.equal(res.status, 403, 'Updating SOA for Zone without permissions should fail.');
});
}); | loewexy/pdnsmanager | backend/test/tests/domain-soa.js | JavaScript | apache-2.0 | 5,046 |
/**
* Copyright (c) Microsoft. 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.
*/
var common = require('../common');
var fs = require('fs');
var path = require('path');
var url = require('url');
var pfx2pem = require('../util/certificates/pkcs').pfx2pem;
var Channel = require('../channel');
var utils = require('../utils');
var uuid = require('node-uuid');
exports.init = function (cli) {
var log = cli.output;
function getSqlChannel(options) {
options.subscription = options.subscription || cli.category('account').lookupSubscriptionId(options.subscription);
var account = cli.category('account');
var managementEndpoint = url.parse(utils.getSqlManagementEndpointUrl());
var pem = account.managementCertificate();
var host = managementEndpoint.hostname;
var port = managementEndpoint.port;
var channel = new Channel({
host: host,
port: port,
key: pem.key,
cert: pem.cert
}).header('x-ms-version', '1.0')
.path(options.subscription)
return channel;
}
function getBaseChannel(options) {
options.subscription = options.subscription || cli.category('account').lookupSubscriptionId(options.subscription);
var account = cli.category('account');
var managementEndpoint = url.parse(utils.getManagementEndpointUrl(account.managementEndpointUrl()));
var pem = account.managementCertificate();
var host = managementEndpoint.hostname;
var port = managementEndpoint.port;
var channel = new Channel({
host: host,
port: port,
key: pem.key,
cert: pem.cert
}).header('x-ms-version', '2012-03-01')
.path(options.subscription)
return channel;
}
function getMobileChannel(options) {
var channel = getBaseChannel(options)
.header('Accept', 'application/json')
.path('services')
.path('mobileservices');
return channel;
}
function getAppManagerChannel(options) {
var channel = getBaseChannel(options)
.header('Accept', 'application/xml')
.path('applications');
return channel;
}
var mobile = cli.category('mobile')
.description('Commands to manage your Azure mobile services');
mobile.getRegions = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('regions');
channel.GET(callback);
};
mobile.listServices = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices');
channel.GET(callback);
};
mobile.getService = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename);
channel.GET(callback);
};
mobile.getServiceSettings = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('settings');
channel.GET(callback);
};
mobile.setServiceSettings = function (options, settings, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('settings')
.header('Content-Type', 'application/json');
channel.send('PATCH', settings, callback);
};
mobile.getLiveSettings = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('livesettings');
channel.GET(callback);
};
mobile.setLiveSettings = function (options, settings, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('livesettings')
.header('Content-Type', 'application/json');
channel.PUT(settings, callback);
};
mobile.getAuthSettings = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('authsettings');
channel.GET(callback);
};
mobile.setAuthSettings = function (options, settings, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('authsettings')
.header('Content-Type', 'application/json');
log.silly('NEW AUTH SETTINGS:');
log.silly(settings);
channel.PUT(settings, callback);
};
mobile.getApnsSettings = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('apns')
.path('settings');
channel.GET(callback);
};
mobile.setApnsSettings = function (options, settings, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('apns')
.path('settings')
.header('Content-Type', 'application/json');
channel.POST(settings, callback);
};
mobile.regenerateKey = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('regenerateKey')
.query('type', options.type);
channel.POST(null, callback);
};
mobile.restartService = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('redeploy');
var progress = cli.progress('Restarting mobile service');
try {
channel.POST(null, function (error, result) {
progress.end();
callback(error, result);
});
}
catch (e) {
progress.end();
throw e;
}
};
mobile.getLogs = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('logs');
if (options.query) {
options.query.split('&').forEach(function (keyvalue) {
var kv = keyvalue.split('=');
if (kv.length === 2) {
channel.query(kv[0], kv[1]);
}
else {
return callback(new Error('Invalid format of query parameter'));
}
})
}
else {
channel.query('$top', options.top || 10);
if (options.skip) {
channel.query('$skip', options.skip)
}
if (options.type) {
channel.query('$filter', "Type eq '" + options.type + "'");
}
}
channel.GET(callback);
};
mobile.listTables = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables');
channel.GET(callback);
};
mobile.getApnsScript = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('apns')
.path('scripts')
.path('feedback');
channel.GET(callback);
};
mobile.setApnsScript = function (options, script, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('apns')
.path('scripts')
.path('feedback')
.header('Content-Type', 'text/plain');
channel.PUT(script, callback);
};
mobile.deleteApnsScript = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('apns')
.path('scripts')
.path('feedback');
channel.DELETE(callback);
};
mobile.getSharedScripts = function (options, callback) {
log.verbose('Subscription', options.subscription);
mobile.getApnsScript(options, function (error, script) {
if (error) {
return callback(error);
}
callback(null, [{ name: 'apnsFeedback', sizeBytes: Buffer.byteLength(script, 'utf8') }]);
});
};
mobile.getSharedScript = function (options, callback) {
log.verbose('Subscription', options.subscription);
if (options.script.shared.name !== 'apnsFeedback') {
return callback(new Error('Unsupported shared script name: ' + options.script.shared.name));
}
mobile.getApnsScript(options, callback);
};
mobile.setSharedScript = function (options, script, callback) {
log.verbose('Subscription', options.subscription);
if (options.script.shared.name !== 'apnsFeedback') {
return callback(new Error('Unsupported shared script name: ' + options.script.shared.name));
}
mobile.setApnsScript(options, script, callback);
};
mobile.deleteSharedScript = function (options, callback) {
log.verbose('Subscription', options.subscription);
if (options.script.shared.name !== 'apnsFeedback') {
return callback(new Error('Unsupported shared script name: ' + options.script.shared.name));
}
mobile.deleteApnsScript(options, callback);
};
mobile.getSchedulerScripts = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('scheduler')
.path('jobs');
channel.GET(callback);
};
mobile.getSchedulerScript = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('scheduler')
.path('jobs')
.path(options.script.scheduler.name)
.path('script');
channel.GET(callback);
};
mobile.setSchedulerScript = function (options, script, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('scheduler')
.path('jobs')
.path(options.script.scheduler.name)
.path('script')
.header('Content-Type', 'text/plain');
channel.PUT(script, callback);
};
mobile.deleteSchedulerScript = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('scheduler')
.path('jobs')
.path(options.script.scheduler.name);
channel.DELETE(callback);
};
mobile.getTableScripts = function (options, table, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.path(table)
.path('scripts');
channel.GET(callback);
};
mobile.getTableScript = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.path(options.script.table.name)
.path('scripts')
.path(options.script.table.operation)
.path('code');
channel.GET(callback);
};
mobile.setTableScript = function (options, script, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.path(options.script.table.name)
.path('scripts')
.path(options.script.table.operation)
.path('code')
.header('Content-Type', 'text/plain');
channel.PUT(script, callback);
};
mobile.deleteTableScript = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.path(options.script.table.name)
.path('scripts')
.path(options.script.table.operation);
channel.DELETE(callback);
};
mobile.getAllTableScripts = function (options, callback) {
log.verbose('Subscription', options.subscription);
var results = [];
mobile.listTables(options, function (error, tables) {
if (error || tables.length == 0) {
return callback(error, tables);
}
var resultCount = 0;
var finalError;
tables.forEach(function (table) {
mobile.getTableScripts(options, table.name, function (error, scripts) {
finalError = finalError || error;
if (Array.isArray(scripts)) {
scripts.forEach(function (script) {
script.table = table.name;
results.push(script);
});
}
if (++resultCount == tables.length) {
callback(finalError, results);
}
});
});
});
};
mobile.getTable = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.path(options.tablename);
channel.GET(callback);
};
mobile.createTable = function (options, settings, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.header('Content-Type', 'application/json');
channel.POST(settings, callback);
};
mobile.deleteTable = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.path(options.tablename);
channel.DELETE(callback);
};
mobile.getPermissions = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.path(options.tablename)
.path('permissions');
channel.GET(callback);
};
mobile.updatePermissions = function (options, newPermissions, callback) {
log.verbose('Subscription', options.subscription);
mobile.getPermissions(options, function (error, currentPermissions) {
if (error) {
return callback(error);
}
for (var i in currentPermissions) {
if (!newPermissions[i]) {
newPermissions[i] = currentPermissions[i];
}
}
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.path(options.tablename)
.path('permissions')
.header('Content-Type', 'application/json');
channel.PUT(JSON.stringify(newPermissions), callback);
});
};
mobile.getScripts = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.path(options.tablename)
.path('scripts');
channel.GET(callback);
};
mobile.getColumns = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.path(options.tablename)
.path('columns');
channel.GET(callback);
};
mobile.deleteColumn = function (options, column, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.path(options.tablename)
.path('columns')
.path(column);
channel.DELETE(callback);
};
mobile.createIndex = function (options, column, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.path(options.tablename)
.path('indexes')
.path(column);
channel.PUT(null, callback);
};
mobile.deleteIndex = function (options, column, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.path(options.tablename)
.path('indexes')
.path(column);
channel.DELETE(callback);
};
mobile.getMobileServiceApplication = function (options, callback) {
var channel = getAppManagerChannel(options)
.path(options.servicename + 'mobileservice')
.header('Content-Type', 'application/xml');
channel.GET(callback);
};
mobile.deleteMobileServiceApplication = function (options, callback) {
var channel = getAppManagerChannel(options)
.path(options.servicename + 'mobileservice')
.header('Content-Type', 'application/xml');
channel.DELETE(function (error, body, res) {
if (error) {
log.silly('Delete mobile service application error: ' + JSON.stringify(error, null, 2));
return callback(error);
}
mobile.trackAsyncOperation(options, res.headers['x-ms-request-id'], function (error) {
log.silly('Delete mobile service application result: ' + error ? JSON.stringify(error, null, 2) : 'ok');
callback(error);
});
});
};
mobile.getData = function (options, callback) {
log.verbose('Subscription', options.subscription);
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
.path('tables')
.path(options.tablename)
.path('data');
if (options.query) {
options.query.split('&').forEach(function (keyvalue) {
var kv = keyvalue.split('=');
if (kv.length === 2) {
channel.query(kv[0], kv[1]);
}
else {
return callback(new Error('Invalid format of query parameter'));
}
})
}
else {
channel.query('$top', options.top || 10);
if (options.skip) {
channel.query('$skip', options.skip)
}
}
channel.GET(callback);
}
mobile.trackAsyncOperation = function (options, requestId, callback) {
function waitOne() {
var asyncChannel = getBaseChannel(options)
.path('operations')
.path(requestId)
.header('Accept', 'application/json');
asyncChannel.GET(function (error, body) {
if (error) {
return callback(new Error('Unable to determine the status of the async operation. ' +
'Please check the status on the management portal.'));
}
log.silly('Operation status: ' + body.Status);
if (body.Status === 'Succeeded') {
callback();
}
else if (body.Status === 'Failed') {
callback(new Error('Operation failed. ' +
'Please confirm the status on the management portal.'))
}
else if (body.Status !== 'InProgress') {
callback(new Error('Unexpected response from Windows Azure. ' +
'Please confirm the status of the mobile service n the management portal.'))
}
else {
setTimeout(waitOne(), 5000);
}
});
}
waitOne();
};
var resourceTypeView = {
'Microsoft.WindowsAzure.MobileServices.MobileService': 'Mobile service',
'Microsoft.WindowsAzure.SQLAzure.DataBase': 'SQL database',
'Microsoft.WindowsAzure.SQLAzure.Server': 'SQL server'
};
mobile.getFlatApplicationDescription = function (description) {
var result = {
State: description.State,
Name: description.Name,
Label: description.Label,
Resources: []
};
function flatten(resource) {
var list;
if (Array.isArray(resource))
list = resource;
else if (typeof resource == 'object')
list = [ resource ];
if (list) {
list.forEach(function (item) {
result.Resources.push(item);
item.TypeView = resourceTypeView[item.Type];
item.NameView = item.Label || item.Name;
if (typeof item.FailureCode === 'string') {
var match = item.FailureCode.match(/\<Message\>([^\<]*)\<\/Message\>/);
item.Error = match ? match[1] : item.FailureCode;
}
});
}
}
flatten(description.InternalResources.InternalResource);
flatten(description.ExternalResources.ExternalResource);
return result;
};
mobile.deleteService = function (options, callback) {
var channel = getMobileChannel(options)
.path('mobileservices')
.path(options.servicename)
if (options.deleteData) {
channel.query('deletedata', 'true');
}
channel.DELETE(function (error, body, ret) {
log.silly('Delete mobile service:');
log.silly(JSON.stringify(error, null, 2));
log.silly(JSON.stringify(body, null, 2));
callback(error);
});
};
mobile.deleteSqlServer = function (options, resource, callback) {
var channel = getSqlChannel(options)
.path('servers')
.path(resource.Name);
channel.DELETE(function (error, body, ret) {
log.silly('Delete SQL server:');
log.silly(JSON.stringify(error, null, 2));
log.silly(JSON.stringify(body, null, 2));
callback(error);
});
};
var createMobileServiceApplicationTemplate = (function () {/*
<?xml version="1.0" encoding="utf-8"?>
<Application xmlns="http://schemas.microsoft.com/windowsazure">
<Name>##name##</Name>
<Label>##label##</Label>
<Description>##description##</Description>
<Configuration>##spec##</Configuration>
</Application>
~*/}).toString().match(/[^\n]\n([^\~]*)/)[1];
mobile.createService = function (options, callback) {
var channel = getAppManagerChannel(options)
.header('Content-Type', 'application/xml');
var serverRefName = "ZumoSqlServer_" + uuid.v4().replace(/-/g,'');
var serverSpec;
if (options.sqlServer) {
// use existing SQL server
serverSpec = {
"Name": serverRefName,
"Type": "Microsoft.WindowsAzure.SQLAzure.Server",
"URI": 'https://management.core.windows.net:8443/'
+ options.subscription + '/services/sqlservers/servers/' + options.sqlServer
};
}
else {
// create new SQL server
serverSpec = {
"ProvisioningParameters": {
"AdministratorLogin": options.username,
"AdministratorLoginPassword": options.password,
"Location": options.sqlLocation
},
"ProvisioningConfigParameters": {
"FirewallRules": [
{
"Name": "AllowAllWindowsAzureIps",
"StartIPAddress": "0.0.0.0",
"EndIPAddress": "0.0.0.0"
}
]
},
"Version": "1.0",
"Name": serverRefName,
"Type": "Microsoft.WindowsAzure.SQLAzure.Server"
};
}
var dbRefName = "ZumoSqlDatabase_" + uuid.v4().replace(/-/g,'');
var dbSpec;
if (options.sqlDb) {
// use existing SQL database
dbSpec = {
"Name": dbRefName,
"Type": "Microsoft.WindowsAzure.SQLAzure.DataBase",
"URI": 'https://management.core.windows.net:8443/'
+ options.subscription + '/services/sqlservers/servers/' + options.sqlServer
+ '/databases/' + options.sqlDb
};
}
else {
// create a new SQL database
dbSpec = {
"ProvisioningParameters": {
"Name": options.servicename + "_db",
"Edition": "WEB",
"MaxSizeInGB": "1",
"DBServer": {
"ResourceReference": serverRefName + ".Name"
},
"CollationName": "SQL_Latin1_General_CP1_CI_AS"
},
"Version": "1.0",
"Name": dbRefName,
"Type": "Microsoft.WindowsAzure.SQLAzure.DataBase"
};
}
var spec = {
"SchemaVersion": "2012-05.1.0",
"Location": "West US",
"ExternalResources": {},
"InternalResources": {
"ZumoMobileService": {
"ProvisioningParameters": {
"Name": options.servicename,
"Location": options.location
},
"ProvisioningConfigParameters": {
"Server": {
"StringConcat": [
{
"ResourceReference": serverRefName + ".Name"
},
".database.windows.net"
]
},
"Database": {
"ResourceReference": dbRefName + ".Name"
},
"AdministratorLogin": options.username,
"AdministratorLoginPassword": options.password
},
"Version": "2012-05-21.1.0",
"Name": "ZumoMobileService",
"Type": "Microsoft.WindowsAzure.MobileServices.MobileService"
}
}
};
if (options.sqlServer) {
// use existing SQL server as an external resource
spec.ExternalResources[serverRefName] = serverSpec;
}
else {
// create a new SQL server as in internal resource
spec.InternalResources[serverRefName] = serverSpec;
}
if (options.sqlDb) {
spec.ExternalResources[dbRefName] = dbSpec;
}
else {
// create a new SQL database as an internal resource
spec.InternalResources[dbRefName] = dbSpec;
}
log.silly('New mobile service application specification:');
log.silly(JSON.stringify(spec, null, 2));
var encodedSpec = new Buffer(JSON.stringify(spec)).toString('base64');
var payload = createMobileServiceApplicationTemplate
.replace('##name##', options.servicename + 'mobileservice')
.replace('##label##', options.servicename)
.replace('##description##', options.servicename)
.replace('##spec##', encodedSpec);
log.silly('New mobile service request body:');
log.silly(payload);
var progress = cli.progress('Creating mobile service');
try {
channel.POST(payload, function (error, body, res) {
if (error) {
progress.end();
return callback(error);
}
log.silly('Create mobile app HTTP response: ' + res.statusCode);
log.silly(JSON.stringify(res.headers, null, 2));
// async operation, wait for completion
mobile.trackAsyncOperation(options, res.headers['x-ms-request-id'], function (error) {
if (error) {
progress.end();
return callback(error);
}
// get the application specification and confirm the status of individual components
var channel = getAppManagerChannel(options)
.path(options.servicename + 'mobileservice');
channel.GET(function (error, body, res) {
progress.end();
if (error) {
return callback(error);
}
if (log.format().json) {
log.json(body);
}
else {
log.silly(JSON.stringify(body, null, 2));
var flat = mobile.getFlatApplicationDescription(body);
var logger = flat.State == 'Healthy' ? log.info : log.error;
log.silly(JSON.stringify(flat, null, 2));
logger('Overall application state: ' + flat.State);
flat.Resources.forEach(function (resource) {
logger(resource.TypeView + (resource.NameView ? ' (' + resource.NameView + ')' : '')
+ ' state: ' + resource.State);
if (resource.Error) {
logger(resource.Error);
}
});
}
callback(body.State === 'Healthy' ? null : new Error('Creation of a mobile service failed.'));
});
});
});
}
catch (e) {
progress.end();
throw e;
}
};
mobile.command('locations')
.usage('[options]')
.whiteListPowershell()
.description('List available mobile service locations')
.option('-s, --subscription <id>', 'use the subscription id')
.execute(function (options, callback) {
mobile.getRegions(options, function (error, result) {
if (error) {
return callback(error);
}
if (log.format().json) {
log.json(result);
}
else {
result.forEach(function (region, index) {
log.info(region.region + (index === 0 ? ' (default)' : ''));
});
}
});
});
mobile.command('create [servicename] [username] [password]')
.usage('[options] [servicename] [sqlAdminUsername] [sqlAdminPassword]')
.whiteListPowershell()
.description('Create a new mobile service')
.option('-s, --subscription <id>', 'use the subscription id')
.option('-r, --sqlServer <sqlServer>', 'use existing SQL server')
.option('-d, --sqlDb <sqlDb>', 'use existing SQL database')
.option('-l, --location <location>', 'create the service in a particular location; run azure mobile locations to get available locations')
.option('--sqlLocation <location>', 'create the SQL server in a particular location; defaults to mobile service location')
.execute(function (servicename, username, password, options, callback) {
if (options.sqlDb && !options.sqlServer) {
return callback('To use an existnig SQL database, you must specify the name of an existing SQL server using the --sqlServer parameter.');
}
options.location ? ensuredLocation(options.location) : getDefaultLocation();
function getDefaultLocation() {
mobile.getRegions(options, function (error, result) {
if (error) {
return callback(error);
}
if (!Array.isArray(result) || result.length == 0 || !result[0].region) {
return callback(new Error('Unable to determine the default mobile service location.'));
}
ensuredLocation(result[0].region);
});
}
function ensuredLocation(location) {
options.location = location;
options.sqlLocation = options.sqlLocation || options.location;
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
username ? ensuredUsername(username) : promptUsername();
function promptUsername() {
cli.prompt('SQL administrator user name: ', function (username) {
if (username.length > 0) {
ensuredUsername(username);
}
else {
log.warn('SQL administrator user name cannot be empty');
promptUsername();
}
});
}
function ensuredUsername(username) {
options.username = username;
if (!isUsernameValid(username)) {
return callback('Invalid username');
}
password ? ensuredPassword(password) : promptPassword();
function promptPassword() {
cli.password('SQL administrator password: ', '*', function (password) {
if (isPasswordValid(options.username, password)) {
ensuredPassword(password);
}
else {
promptPassword();
}
});
}
function ensuredPassword(password) {
options.password = password;
if (!isPasswordValid(options.username, password)) {
return callback('Invalid password');
}
mobile.createService(options, callback);
}
}
}
}
function isPasswordValid(username, password) {
// More than eight characters in length
// Does not contain all or part of the username
// Contains characters from at least 3 of the categories
// - A-Z
// - a-z
// - 0-9
// - Non-alphanumeric: !$#%
var matches = 0;
[ new RegExp('[A-Z]'),
new RegExp('[a-z]'),
new RegExp('[0-9]'),
new RegExp('[\\~\\`\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\_\\-\\+\\=\\{\\[\\}\\]\\|\\\\:\\;\\"\\\'\\<\\,\\>\\.\\?\\/]')
].forEach(function (regex) {
if (password.match(regex))
matches++;
});
if (password.length > 8 && password.indexOf(username) == -1 && matches > 2) {
return true;
}
else {
log.warn('Password must:');
log.warn('- be more than 8 characters long,');
log.warn('- not contain the username,');
log.warn('- contain characters from at least 3 of the categories:');
log.warn(' - uppercase letter [A-Z],');
log.warn(' - lowecase letter [a-z],');
log.warn(' - digit [0-9],');
log.warn(' - special character (e.g. !@#$%^&).');
return false;
}
}
function isUsernameValid(username) {
if (username.length > 0) {
return true;
}
else {
log.warn('User name cannot be empty');
return false;
}
}
});
mobile.command('delete [servicename]')
.usage('[options] [servicename]')
.whiteListPowershell()
.description('Delete a mobile service')
.option('-s, --subscription <id>', 'use the subscription id')
.option('-d, --deleteData', 'delete all data from the database')
.option('-a, --deleteAll', 'delete all data, SQL database, and SQL server')
.option('-q, --quiet', 'do not prompt for confirmation')
.execute(function (servicename, username, password, options, callback) {
var prompt;
if (options.deleteAll) {
prompt = ' with all data, SQL database, and the SQL server';
options.deleteSqlDb = options.deleteData = true;
}
else if (options.deleteSqlDb) {
prompt = ' with all data and the SQL database, but leave SQL server intact';
options.deleteData = true;
}
else if (options.deleteData) {
prompt = ' with all data but leave SQL database and SQL server intact';
}
else {
prompt = ' but leave all data, SQL database, and SQL server intact';
}
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
mobile.getMobileServiceApplication(options, function (error, result) {
if (error) {
return callback(error);
}
var resources = {};
var flat = mobile.getFlatApplicationDescription(result);
log.silly(JSON.stringify(flat, null, 2));
flat.Resources.forEach(function (resource) {
if (!log.format().json) {
log.data(resource.TypeView, resource.NameView ? resource.NameView.green : 'N/A'.green);
}
resources[resource.Type] = resource;
});
options.quiet ? doProceed('yes') :
cli.prompt('Do you want to delete the mobile service' + prompt + '? (yes/no): ', doProceed);
function doProceed(decision) {
if (decision !== 'yes') {
log.info('Deletion terminated with no changes made');
return callback();
}
var plan = [];
// delete mobile service
plan.push({
progress: 'Deleting mobile service',
success: 'Deleted mobile service',
failure: 'Failed to delete mobile service',
handler: function (callback) {
mobile.deleteService(options, callback);
}
});
// delete SQL server
if (options.deleteAll) {
plan.push({
progress: 'Deleting SQL server',
success: 'Deleted SQL server',
failure: 'Failed to delete SQL server',
handler: function (callback) {
mobile.deleteSqlServer(options, resources['Microsoft.WindowsAzure.SQLAzure.Server'], callback);
}
});
}
// delete application
plan.push({
progress: 'Deleting mobile application',
success: 'Deleted mobile application',
failure: 'Failed to delete mobile application',
handler: function (callback) {
mobile.deleteMobileServiceApplication(options, callback);
}
});
// execute plan
var failures = 0;
function doStep(stepIndex) {
if (stepIndex == plan.length) {
return callback(failures > 0 ? 'Not all delete operations completed successfuly.' : null);
}
var step = plan[stepIndex];
var progress = cli.progress(step.progress);
try {
step.handler(function (error) {
progress.end();
if (error) {
log.error(step.failure);
failures++;
}
else {
log.info(step.success);
}
doStep(stepIndex + 1);
});
}
catch (e) {
progress.end();
failures++;
doStep(stepIndex + 1);
}
}
doStep(0);
}
});
}
});
mobile.command('list')
.usage('[options]')
.whiteListPowershell()
.description('List your mobile services')
.option('-s, --subscription <id>', 'use the subscription id')
.execute(function (options, callback) {
mobile.listServices(options, function (error, services) {
if (error) {
return callback(error);
}
if (services && services.length > 0) {
log.table(services, function (row, s) {
row.cell('Name', s.name);
row.cell('State', s.state);
row.cell('URL', s.applicationUrl);
});
} else {
log.info('No mobile services created yet. You can create new mobile services through the portal.');
}
callback();
});
});
mobile.command('show [servicename]')
.usage('[options] [servicename]')
.whiteListPowershell()
.description('Show details for a mobile service')
.option('-s, --subscription <id>', 'use the subscription id')
.execute(function (servicename, options, callback) {
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
var results = {};
var resultCount = 0;
var progress = cli.progress('Getting information');
function tryFinish() {
if (++resultCount < 2) {
return;
}
progress.end();
log.silly('Results:');
log.silly(JSON.stringify(results, null, 2));
if (log.format().json) {
log.json(results);
}
else {
if (results.application) {
log.info('Mobile application'.blue)
var flat = mobile.getFlatApplicationDescription(results.application);
log.silly(JSON.stringify(flat, null, 2));
log.data('status', flat.State == 'Healthy' ? 'Healthy'.green : flat.State.red);
flat.Resources.forEach(function (resource) {
log.data(resource.TypeView + ' name', resource.NameView ? resource.NameView.green : 'N/A'.green);
if (resource.Error) {
log.data(resource.TypeView + ' status', resource.State.red);
log.data(resource.TypeView + ' error', resource.Error.red);
}
else {
log.data(resource.TypeView + ' status', resource.State.green);
}
});
}
if (results.service) {
log.info('Mobile service'.blue);
['name', 'state', 'applicationUrl', 'applicationKey', 'masterKey', 'webspace', 'region']
.forEach(function (item) {
if (results.service[item]) {
log.data(item, results.service[item].toString().green);
}
});
if (results.service.tables.length > 0)
{
var tables = '';
results.service.tables.forEach(function (table) { tables += (tables.length > 0 ? ',' : '') + table.name ; });
log.data('tables', tables.green);
}
else {
log.info('No tables are created. Use azure mobile table command to create tables.');
}
}
}
if (!results.service && !results.application) {
return callback('Cannot obtain informaton about the service ' + options.servicename
+ '. Use azure mobile list to check if it exists.');
}
else {
return callback();
}
}
function createCallback(name) {
return function (error, result) {
log.silly(name, error);
if (!error) {
results[name] = result;
}
tryFinish();
}
}
try {
mobile.getService(options, createCallback('service'));
mobile.getMobileServiceApplication(options, createCallback('application'));
}
catch (e) {
progress.end();
callback(e);
}
}
});
mobile.command('restart [servicename]')
.usage('[options] [servicename]')
.whiteListPowershell()
.description('Restart a mobile service')
.option('-s, --subscription <id>', 'use the subscription id')
.execute(function (servicename, options, callback) {
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
mobile.restartService(options, function (error, service) {
if (error) {
return callback(error);
}
if (log.format().json) {
log.json({});
}
else {
log.info('Service was restarted.');
}
callback();
});
}
});
var mobileKey = mobile.category('key')
.description('Commands to manage your Azure mobile service keys');
var keyTypes = ['application', 'master'];
mobileKey.command('regenerate [servicename] [type]')
.usage('[options] [servicename] [type]')
.whiteListPowershell()
.description('Regenerate the mobile service key')
.option('-s, --subscription <id>', 'use the subscription id')
.execute(function (servicename, type, options, callback) {
if (type) {
ensuredType(type);
}
else {
log.help('Choose key type:');
cli.choose(keyTypes, function (i) { ensuredType(keyTypes[i]); });
}
function ensuredType(type) {
if (type !== 'application' && type !== 'master') {
return callback(new Error('The key type must be "application" or "master".'))
}
options.type = type;
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
mobile.regenerateKey(options, function (error, result) {
if (error) {
return callback(error);
}
if (log.format().json) {
log.json(result);
}
else {
log.info('New ' + type + ' key is ' + result[type + 'Key']);
}
callback();
});
}
}
});
mobile.command('log [servicename]')
.usage('[options] [servicename]')
.whiteListPowershell()
.description('Get mobile service logs')
.option('-s, --subscription <id>', 'use the subscription id')
.option('-r, --query <query>', 'log query; takes precedence over --type, --skip, and --top')
.option('-t, --type <type>', 'filter by entry <type>')
.option('-k, --skip <skip>', 'skip the first <skip> number of rows')
.option('-p, --top <top>', 'return the first <top> number of remaining rows')
.execute(function (servicename, options, callback) {
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
mobile.getLogs(options, function (error, logs) {
if (error) {
return callback(error);
}
if (log.format().json) {
log.json(logs);
}
else {
if (logs && logs.results && logs.results.length > 0) {
logs.results.forEach(function (entry) {
log.data('', '');
for (var i in entry) {
log.data(i, entry[i]);
}
});
log.data('', '');
}
else {
log.info('There are no matching log entries.')
}
}
callback();
});
}
});
var mobileConfig = mobile.category('config')
.description('Commands to manage your Azure mobile service configuration');
mobileConfig.command('list [servicename]')
.usage('[options] [servicename]')
.description('Show your mobile service configuration settings')
.option('-s, --subscription <id>', 'use the subscription id')
.execute(function (servicename, options, callback) {
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
// unlike async.parallel, we want all operations to execute regardless if some have errors
var progress = cli.progress('Getting mobile service configuration');
var results = {};
var operationCount = 0;
function tryFinish() {
if (++operationCount < 4) {
return;
}
progress.end();
if (log.format().json) {
log.json(results);
}
else {
var settings = {};
[ 'dynamicSchemaEnabled',
'microsoftAccountClientSecret',
'microsoftAccountClientId',
'microsoftAccountPackageSID',
'facebookClientId',
'facebookClientSecret',
'twitterClientId',
'twitterClientSecret',
'googleClientId',
'googleClientSecret',
'apnsMode',
'apnsPassword',
'apnsCertifcate'
].forEach(function (name) {
settings[name] = 'Unable to obtain the value of this setting';
});
if (results.service) {
if (typeof results.service.dynamicSchemaEnabled == 'boolean') {
settings.dynamicSchemaEnabled = results.service.dynamicSchemaEnabled.toString();
}
else {
settings.dynamicSchemaEnabled = 'Not configured';
}
}
if (results.live) {
settings.microsoftAccountClientSecret = results.live.clientSecret || 'Not configured';
settings.microsoftAccountClientId = results.live.clientID || 'Not configured';
settings.microsoftAccountPackageSID = results.live.packageSID || 'Not configured';
}
if (results.apns) {
settings.apnsMode = results.apns.mode || 'Not configured';
settings.apnsPassword = results.apns.password || 'Not configured';
settings.apnsCertifcate = results.apns.certificate || 'Not configured';
}
if (Array.isArray(results.auth)) {
['twitter', 'facebook', 'google'].forEach(function (provider) {
settings[provider + 'ClientId'] = 'Not configured';
settings[provider + 'ClientSecret'] = 'Not configured';
});
results.auth.forEach(function (creds) {
settings[creds.provider + 'ClientId'] = creds.appId;
settings[creds.provider + 'ClientSecret'] = creds.secret;
});
}
for (var i in settings) {
if (settings[i] == 'Not configured') {
log.data(i, settings[i].blue);
}
else if (settings[i] == 'Unable to obtain the value of this setting') {
log.data(i, settings[i].red);
}
else {
log.data(i, settings[i].green);
}
}
}
callback();
}
function createCallback(name) {
return function (error, result) {
log.silly(name, error);
if (!error) {
results[name] = result;
}
tryFinish();
}
}
try {
mobile.getServiceSettings(options, createCallback('service'));
mobile.getLiveSettings(options, createCallback('live'));
mobile.getAuthSettings(options, createCallback('auth'));
mobile.getApnsSettings(options, createCallback('apns'));
}
catch (e) {
progress.end();
callback(e);
}
}
});
function createSetConfigHandler(coreGetHandler, coreSetHandler, picker1, picker2) {
return function (options, newValue, callback) {
coreGetHandler(options, function (error, result) {
if (error) {
return callback(error);
}
if (picker2) {
if (Array.isArray(result)) {
var found;
for (var i = 0; i < result.length; i++) {
if (result[i].provider == picker1) {
result[i][picker2] = newValue;
found = true;
break;
}
}
if (!found) {
var newProvider = { provider: picker1, appId: '', secret: '' };
newProvider[picker2] = newValue;
result.push(newProvider);
}
}
}
else {
result[picker1] = newValue;
}
result = JSON.stringify(result);
coreSetHandler(options, result, callback);
});
}
}
var setConfigHandlers = {
'dynamicSchemaEnabled': createSetConfigHandler(mobile.getServiceSettings, mobile.setServiceSettings, 'dynamicSchemaEnabled'),
'microsoftAccountClientSecret': createSetConfigHandler(mobile.getLiveSettings, mobile.setLiveSettings, 'clientSecret'),
'microsoftAccountClientId': createSetConfigHandler(mobile.getLiveSettings, mobile.setLiveSettings, 'clientID'),
'microsoftAccountPackageSID': createSetConfigHandler(mobile.getLiveSettings, mobile.setLiveSettings, 'packageSID'),
'facebookClientId': createSetConfigHandler(mobile.getAuthSettings, mobile.setAuthSettings, 'facebook', 'appId'),
'facebookClientSecret': createSetConfigHandler(mobile.getAuthSettings, mobile.setAuthSettings, 'facebook', 'secret'),
'twitterClientId': createSetConfigHandler(mobile.getAuthSettings, mobile.setAuthSettings, 'twitter', 'appId'),
'twitterClientSecret': createSetConfigHandler(mobile.getAuthSettings, mobile.setAuthSettings, 'twitter', 'secret'),
'googleClientId': createSetConfigHandler(mobile.getAuthSettings, mobile.setAuthSettings, 'google', 'appId'),
'googleClientSecret': createSetConfigHandler(mobile.getAuthSettings, mobile.setAuthSettings, 'google', 'secret'),
'apnsMode': createSetConfigHandler(mobile.getApnsSettings, mobile.setApnsSettings, 'mode'),
'apnsPassword': createSetConfigHandler(mobile.getApnsSettings, mobile.setApnsSettings, 'password'),
'apnsCertifcate': createSetConfigHandler(mobile.getApnsSettings, mobile.setApnsSettings, 'certificate')
};
mobileConfig.command('set <servicename> <key> [value]')
.usage('[options] <servicename> <key> [value]')
.description('Set a mobile service configuration setting')
.option('-s, --subscription <id>', 'use the subscription id')
.option('-f, --file <file>', 'read the value of the setting from a file')
.execute(function (servicename, key, value, options, callback) {
if (!getConfigHandlers[key]) {
log.info('Supported keys:')
for (var i in getConfigHandlers) {
log.info(i.blue);
}
return callback('Unsupported key ' + key.red);
}
else if (!value && !options.file) {
return callback('Either value parameter must be provided or --file option specified');
}
else {
if (!value && options.file) {
value = fs.readFileSync(options.file, key == 'apnsCertificate' ? 'base64' : 'utf8');
log.info('Value was read from ' + options.file);
}
if (key === 'dynamicSchemaEnabled') {
if (value === 'true') {
value = true;
}
else if (value === 'false') {
value = false;
}
else {
return callback('The value must be either true or false');
}
}
options.servicename = servicename;
setConfigHandlers[key](options, value, callback);
}
});
function createGetConfigHandler(coreHandler, picker1, picker2) {
return function (options, callback) {
coreHandler(options, function (error, result) {
if (error) {
return callback(error);
}
if (picker2) {
if (Array.isArray(result)) {
for (var i = 0; i < result.length; i++) {
if (result[i].provider == picker1) {
return callback(null, result[i][picker2]);
}
}
}
callback(null, null);
}
else {
callback(null, result[picker1]);
}
});
}
}
var getConfigHandlers = {
'dynamicSchemaEnabled': createGetConfigHandler(mobile.getServiceSettings, 'dynamicSchemaEnabled'),
'microsoftAccountClientSecret': createGetConfigHandler(mobile.getLiveSettings, 'clientSecret'),
'microsoftAccountClientId': createGetConfigHandler(mobile.getLiveSettings, 'clientID'),
'microsoftAccountPackageSID': createGetConfigHandler(mobile.getLiveSettings, 'packageSID'),
'facebookClientId': createGetConfigHandler(mobile.getAuthSettings, 'facebook', 'appId'),
'facebookClientSecret': createGetConfigHandler(mobile.getAuthSettings, 'facebook', 'secret'),
'twitterClientId': createGetConfigHandler(mobile.getAuthSettings, 'twitter', 'appId'),
'twitterClientSecret': createGetConfigHandler(mobile.getAuthSettings, 'twitter', 'secret'),
'googleClientId': createGetConfigHandler(mobile.getAuthSettings, 'google', 'appId'),
'googleClientSecret': createGetConfigHandler(mobile.getAuthSettings, 'google', 'secret'),
'apnsMode': createGetConfigHandler(mobile.getApnsSettings, 'mode'),
'apnsPassword': createGetConfigHandler(mobile.getApnsSettings, 'password'),
'apnsCertifcate': createGetConfigHandler(mobile.getApnsSettings, 'certificate')
};
mobileConfig.command('get <servicename> <key>')
.usage('[options] <servicename> <key>')
.description('Get a mobile service configuration setting')
.option('-s, --subscription <id>', 'use the subscription id')
.option('-f, --file <file>', 'save the value of the setting to a file')
.execute(function (servicename, key, options, callback) {
if (!getConfigHandlers[key]) {
log.info('Supported keys:')
for (var i in getConfigHandlers) {
log.info(i.blue);
}
return callback('Unsupported key ' + key.red);
}
else {
options.servicename = servicename;
getConfigHandlers[key](options, function (error, result) {
if (error) {
return callback(error);
}
if (log.format().json) {
var value = {};
value[key] = result;
log.json(value);
}
else if (result) {
if (typeof options.file === 'string') {
fs.writeFileSync(options.file, result, key == 'apnsCertifcate' ? 'base64' : 'utf8');
log.info('Written value to ' + options.file);
}
else {
log.data(key, result.toString().green);
}
}
else {
log.warn('Setting is not configured'.blue)
}
return callback();
});
}
});
var mobileTable = mobile.category('table')
.description('Commands to manage your Azure mobile service tables');
mobileTable.command('list [servicename]')
.usage('[options] [servicename]')
.description('List mobile service tables')
.option('-s, --subscription <id>', 'use the subscription id')
.execute(function (servicename, options, callback) {
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
mobile.listTables(options, function (error, tables) {
if (error) {
return callback(error);
}
if (log.format().json) {
log.json(tables);
}
else if (tables && tables.length > 0) {
log.table(tables, function (row, s) {
row.cell('Name', s.name);
row.cell('Indexes', s.metrics.indexCount);
row.cell('Rows', s.metrics.recordCount);
});
} else {
log.info('No tables created yet. You can create a mobile service table using azure mobile table create command.');
}
callback();
});
}
});
mobileTable.command('show [servicename] [tablename]')
.usage('[options] [servicename] [tablename]')
.description('Show details for a mobile service table')
.option('-s, --subscription <id>', 'use the subscription id')
.execute(function (servicename, tablename, options, callback) {
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
tablename ? ensuredTableName(tablename) : cli.prompt('Table name: ', ensuredTableName);
function ensuredTableName(tablename) {
options.tablename = tablename;
// unlike async.parallel, we want all operations to execute regardless if some have errors
var progress = cli.progress('Getting table information');
var results = {};
var operationCount = 0;
function tryFinish() {
if (++operationCount < 4) {
return;
}
progress.end();
if (log.format().json) {
log.json(results);
}
else if (!results.table) {
return callback('Table ' + tablename + ' or mobile service ' + servicename + ' does not exist.')
}
else {
log.info('Table statistics:'.green);
log.data('Number of records', results.table.metrics.recordCount.toString().green);
log.info('Table operations:'.green);
log.table(['insert', 'read', 'update', 'delete'], function (row, s) {
row.cell('Operation', s);
var script;
if (results.scripts) {
for (var i = 0; i < results.scripts.length; i++) {
if (results.scripts[i].operation === s) {
script = results.scripts[i];
break;
}
}
row.cell('Script', script ? script.sizeBytes.toString() + ' bytes' : 'Not defined');
}
else {
row.cell('Script', 'N/A');
}
if (results.permissions) {
row.cell('Permissions', results.permissions[s] || 'default');
}
else {
row.cell('Permissions', 'N/A');
}
});
if (results.columns) {
log.info('Table columns:'.green);
log.table(results.columns, function (row, s) {
row.cell('Name', s.name);
row.cell('Type', s.type);
row.cell('Indexed', s.indexed ? 'Yes' : '');
});
}
else {
log.error('Unable to obtain table columns')
}
}
callback();
}
function createCallback(name) {
return function (error, result) {
log.silly(name, error);
if (!error) {
results[name] = result;
}
tryFinish();
}
}
try {
mobile.getTable(options, createCallback('table'));
mobile.getPermissions(options, createCallback('permissions'));
mobile.getColumns(options, createCallback('columns'));
mobile.getScripts(options, createCallback('scripts'));
}
catch (e) {
progress.end();
callback(e);
}
}
}
});
var roles = ['user', 'public', 'application', 'admin'];
var operations = ['insert', 'read', 'update', 'delete'];
function parsePermissions(permissions) {
var result = {};
if (typeof permissions == 'string') {
permissions.split(',').forEach(function (pair) {
var match = pair.match(/^([^\=]+)\=(.+)$/);
if (!match) {
throw new Error('Syntax error in parsing the permission pair "' + pair + '"');
}
if (match[1] !== '*' && !operations.some(function (operation) { return operation === match[1]; })) {
throw new Error('Unsupported operation name "' + match[1] + '". Operation must be one of *, ' + operations.join(', '));
}
if (!roles.some(function (role) { return role === match[2]; })) {
throw new Error('Unsupported permission value "' + match[2] + '". Permission must be one of ' + roles.join(', '));
}
if (match[1] === '*') {
operations.forEach(function (operation) {
result[operation] = match[2];
});
}
else {
result[match[1]] = match[2];
}
})
}
return result;
}
mobileTable.command('create [servicename] [tablename]')
.usage('[options] [servicename] [tablename]')
.description('List your mobile service tables')
.option('-s, --subscription <id>', 'use the subscription id')
.option('-p, --permissions <permissions>', 'comma delimited list of <operation>=<permission> pairs')
.execute(function (servicename, tablename, options, callback) {
var settings;
try {
settings = parsePermissions(options.permissions);
}
catch (e) {
log.error('Permissions must be specified as a comma delimited list of <operation>=<permission> pairs.');
log.error('<operation> must be one of ' + operations.join(', '));
log.error('<permission> must be one of ' + roles.join(', '));
return callback(e);
}
// default table permissions to 'application'
operations.forEach(function (operation) {
if (!settings[operation]) {
settings[operation] = 'application';
}
});
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
tablename ? ensuredTableName(tablename) : cli.prompt('Table name: ', ensuredTableName);
function ensuredTableName(tablename) {
options.tablename = tablename;
settings.name = tablename;
var progress = cli.progress('Creating table');
try {
mobile.createTable(options, JSON.stringify(settings), function (error) {
progress.end();
callback(error);
});
}
catch (e) {
progress.end();
throw e;
}
}
};
});
mobileTable.command('update [servicename] [tablename]')
.usage('[options] [servicename] [tablename]')
.description('Update mobile service table properties')
.option('-s, --subscription <id>', 'use the subscription id')
.option('-p, --permissions <permissions>', 'comma delimited list of <operation>=<permission> pairs')
.option('--deleteColumn <columns>', 'comma separated list of columns to delete')
.option('-q, --quiet', 'do not prompt for confirmation of column deletion')
.option('--addIndex <columns>', 'comma separated list of columns to create an index on')
.option('--deleteIndex <columns>', 'comma separated list of columns to delete an index from')
.execute(function (servicename, tablename, options, callback) {
try {
options.permissions = parsePermissions(options.permissions);
}
catch (e) {
log.error('Permissions must be specified as a comma delimited list of <operation>=<permission> pairs.');
log.error('<operation> must be one of ' + operations.join(', '));
log.error('<permission> must be one of ' + roles.join(', '));
return callback(e);
}
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
tablename ? ensuredTableName(tablename) : cli.prompt('Table name: ', ensuredTableName);
function ensuredTableName(tablename) {
options.tablename = tablename;
if (typeof options.deleteColumn !== 'string' || options.quiet) {
doProceed('yes');
}
else {
cli.prompt('Do you really want to delete the column(s) (yes/no): ', doProceed);
}
function doProceed(decision) {
if (decision !== 'yes') {
log.info('Update terminated with no changes made');
callback();
}
else {
var plan = [];
// add permission update to plan
if (Object.getOwnPropertyNames(options.permissions).length > 0) {
plan.push({
progress: 'Updating permissions',
success: 'Updated permissions',
failure: 'Failed to update permissions',
handler: function (callback) {
mobile.updatePermissions(options, options.permissions, callback);
}
});
}
// add index deletion to plan
if (options.deleteIndex) {
options.deleteIndex.split(',').forEach(function (column) {
plan.push({
progress: 'Deleting index from column ' + column,
success: 'Deleted index from column ' + column,
failure: 'Failed to delete index from column ' + column,
handler: function (callback) {
mobile.deleteIndex(options, column, callback);
}
});
});
}
// add index addition to plan
if (options.addIndex) {
options.addIndex.split(',').forEach(function (column) {
plan.push({
progress: 'Adding index to column ' + column,
success: 'Added index to column ' + column,
failure: 'Failed to add index to column ' + column,
handler: function (callback) {
mobile.createIndex(options, column, callback);
}
});
});
}
// add column deletion to plan
if (options.deleteColumn) {
options.deleteColumn.split(',').forEach(function (column) {
plan.push({
progress: 'Deleting column ' + column,
success: 'Deleted column ' + column,
failure: 'Failed to delete column ' + column,
handler: function (callback) {
mobile.deleteColumn(options, column, callback);
}
});
});
}
// execute plan
if (plan.length == 0) {
log.info('No updates performed. Check the list of available updates with --help.');
}
else {
var failures = 0;
function doStep(stepIndex) {
if (stepIndex == plan.length) {
return callback(failures > 0 ? 'Not all update operations completed successfuly.' : null);
}
var step = plan[stepIndex];
var progress = cli.progress(step.progress);
try {
step.handler(function (error) {
progress.end();
if (error) {
log.error(step.failure);
failures++;
}
else {
log.info(step.success);
}
doStep(stepIndex + 1);
});
}
catch (e) {
progress.end();
failures++;
doStep(stepIndex + 1);
}
}
doStep(0);
}
}
}
}
}
});
mobileTable.command('delete [servicename] [tablename]')
.usage('[options] [servicename] [tablename]')
.description('Delete a mobile service table')
.option('-s, --subscription <id>', 'use the subscription id')
.option('-q, --quiet', 'do not prompt for confirmation')
.execute(function (servicename, tablename, options, callback) {
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
tablename ? ensuredTableName(tablename) : cli.prompt('Table name: ', ensuredTableName);
function ensuredTableName(tablename) {
options.tablename = tablename;
options.quiet ? doDelete('yes') : cli.prompt('Do you really want to delete the table (yes/no): ', doDelete);
function doDelete(decision) {
if (decision === 'yes') {
var progress = cli.progress('Deleting table');
try {
mobile.deleteTable(options, function (error) {
progress.end();
callback(error);
});
}
catch (e) {
progress.end();
throw e;
}
}
else {
log.info('Table was not deleted');
callback();
}
}
}
}
});
var mobileData = mobile.category('data')
.description('Commands to manage the data in your mobile service tables');
mobileData.command('read [servicename] [tablename] [query]')
.usage('[options] [servicename] [tablename] [query]')
.description('Query data from a mobile service table')
.option('-s, --subscription <id>', 'use the subscription id')
.option('-k, --skip <top>', 'skip the first <skip> number of rows')
.option('-t, --top <top>', 'return the first <top> number of remaining rows')
.option('-l, --list', 'display results in list format')
.execute(function (servicename, tablename, query, options, callback) {
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
tablename ? ensuredTableName(tablename) : cli.prompt('Table name: ', ensuredTableName);
function ensuredTableName(tablename) {
options.tablename = tablename;
options.query = query;
mobile.getData(options, function (error, data) {
if (error) {
return callback(error);
}
if (log.format().json) {
log.json(data);
}
else if (!Array.isArray(data) || data.length == 0) {
log.info("No matching records found");
}
else if (options.list) {
data.forEach(function (record) {
log.data('', '');
for (var i in record) {
log.data(i, record[i] === null ? '<null>'.green : record[i].toString().green);
}
});
log.data('', '');
}
else {
log.table(data, function (row, s) {
for (var i in s) {
row.cell(i, s[i]);
}
});
}
callback();
});
}
}
});
var mobileScript = mobile.category('script')
.description('Commands to manage your Azure mobile service scripts');
mobileScript.command('list [servicename]')
.usage('[options] [servicename]')
.description('List mobile service scripts')
.option('-s, --subscription <id>', 'use the subscription id')
.execute(function (servicename, options, callback) {
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
// unlike async.parallel, we want all operations to execute regardless if some have errors
var progress = cli.progress('Getting script information');
var results = {};
var operationCount = 0;
function tryFinish() {
if (++operationCount < 3) {
return;
}
progress.end();
if (log.format().json) {
log.json(results);
}
else {
if (!results.table) {
log.error('Unable to get table scripts');
}
else if (!Array.isArray(results.table) || results.table.length == 0) {
log.info('There are no table scripts. Create scripts using azure mobile script upload command.');
}
else {
log.info('Table scripts'.green);
log.table(results.table, function (row, s) {
row.cell('Name', 'table/' + s.table + '.' + s.operation);
row.cell('Size', s.sizeBytes);
});
}
if (!results.shared) {
log.error('Unable to get shared scripts');
}
else if (!Array.isArray(results.shared) || results.shared.length == 0) {
log.info('There are no shared scripts. Create scripts using azure mobile script upload command.');
}
else {
log.info('Shared scripts'.green);
log.table(results.table, function (row, s) {
row.cell('Name', s.name);
row.cell('Size', s.sizeBytes);
});
}
if (!results.scheduler) {
log.error('Unable to get scheduler scripts');
}
else if (!Array.isArray(results.scheduler) || results.scheduler.length == 0) {
log.info('There are no scheduler scripts. Create scheduler scripts using azure mobile scheduler command.');
}
else {
log.info('Scheduler scripts'.green);
log.table(results.table, function (row, s) {
row.cell('Name', 'scheduler/' + s.name);
row.cell('Status', s.status);
row.cell('Interval', s.interval);
row.cell('Last run', s.lastRun);
row.cell('Next run', s.nextRun);
});
}
}
callback();
}
function createCallback(name) {
return function (error, result) {
log.silly(name, error);
if (!error) {
results[name] = result;
}
tryFinish();
}
}
try {
mobile.getAllTableScripts(options, createCallback('table'));
mobile.getSharedScripts(options, createCallback('shared'));
mobile.getSchedulerScripts(options, createCallback('scheduler'));
}
catch (e) {
progress.end();
callback(e);
}
}
});
function parseScriptName(scriptname) {
var result;
var match = scriptname.match(/^table\/([^\.]+)\.(insert|read|update|delete)(?:$|\.js$)/);
if (match) {
result = { type: 'table', table: { name: match[1], operation: match[2] } };
}
else {
match = scriptname.match(/^scheduler\/([^\.]+)(?:$|\.js$)/);
if (match) {
result = { type: 'scheduler', scheduler: { name: match[1] } };
}
else {
match = scriptname.match(/^shared\/apnsFeedback(?:$|\.js$)/);
if (match) {
result = { type: 'shared', shared: { name: 'apnsFeedback' } };
}
}
}
return result;
}
function saveScriptFile(scriptSpec, script, output, force) {
var file;
var dir;
if (output) {
file = output;
}
else {
dir = './' + scriptSpec.type;
file = dir + '/';
if (scriptSpec.type == 'table') {
file += scriptSpec.table.name + '.' + scriptSpec.table.operation + '.js';
}
else {
file += scriptSpec[scriptSpec.type].name + '.js';
}
}
if (utils.pathExistsSync(file) && !force) {
return 'File ' + file + ' already exists. Use --override to override.';
}
else {
try {
if (!output) {
if (!utils.pathExistsSync(dir)) {
fs.mkdirSync(dir);
}
}
fs.writeFileSync(file, script, 'utf8');
log.info('Saved script to ' + file);
}
catch (e) {
return 'Unable to save file ' + file;
}
}
return null;
}
var getScriptHandlers = {
table: mobile.getTableScript,
scheduler: mobile.getSchedulerScript,
shared: mobile.getSharedScript
};
mobileScript.command('download [servicename] [scriptname]')
.usage('[options] [servicename] [scriptname]')
.description('Downloads mobile service script')
.option('-s, --subscription <id>', 'use the subscription id')
.option('-p, --path <path>', 'filesystem location to save the script or scripts to; working directory by default')
.option('-f, --file <file>', 'file to save the script to')
.option('-o, --override', 'override existing files')
.option('-c, --console', 'write the script to the console instead of a file')
.execute(function (servicename, scriptname, options, callback) {
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
scriptname ? ensuredScriptName(scriptname) : cli.prompt('Script name: ', ensuredScriptName);
function ensuredScriptName(scriptname) {
options.scriptname = scriptname;
options.script = parseScriptName(options.scriptname);
if (!options.script) {
log.info('For table script, specify table/<tableName>.{insert|read|update|delete}');
log.info('For APNS script, specify shared/apnsFeedback');
log.info('For scheduler script, specify scheduler/<scriptName>');
return callback('Invalid script name ' + options.scriptname);
}
getScriptHandlers[options.script.type](options, function (error, script) {
if (error) {
return callback(error);
}
if (options.console) {
console.log(script);
}
else {
callback(saveScriptFile(options.script, script, options.file, options.override));
}
});
}
}
});
var setScriptHandlers = {
table: mobile.setTableScript,
scheduler: mobile.setSchedulerScript,
shared: mobile.setSharedScript
};
mobileScript.command('upload [servicename] [scriptname]')
.usage('[options] [servicename] [scriptname]')
.description('Uploads mobile service script')
.option('-s, --subscription <id>', 'use the subscription id')
.option('-f, --file <file>', 'file to read the script from')
.execute(function (servicename, scriptname, options, callback) {
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
scriptname ? ensuredScriptName(scriptname) : cli.prompt('Script name: ', ensuredScriptName);
function ensuredScriptName(scriptname) {
options.scriptname = scriptname;
options.script = parseScriptName(options.scriptname);
if (!options.script) {
log.info('For table script, specify table/<tableName>.{insert|read|update|delete}');
log.info('For APNS script, specify shared/apnsFeedback');
log.info('For scheduler script, specify scheduler/<scriptName>');
return callback('Invalid script name ' + options.scriptname);
}
if (!options.file) {
options.file = './' + options.script.type + '/';
if (options.script.table) {
options.file += options.script.table.name + '.' + options.script.table.operation + '.js';
}
else {
options.file += options[options.script.type].name + '.js';
}
}
var script;
try {
script = fs.readFileSync(options.file, 'utf8');
}
catch (e) {
return callback('Unable to read script from file ' + options.file);
}
setScriptHandlers[options.script.type](options, script, callback);
}
}
});
var deleteScriptHandlers = {
table: mobile.deleteTableScript,
scheduler: mobile.deleteSchedulerScript,
shared: mobile.deleteSharedScript
};
mobileScript.command('delete [servicename] [scriptname]')
.usage('[options] [servicename] [scriptname]')
.description('Deletes mobile service script or scripts')
.option('-s, --subscription <id>', 'use the subscription id')
.execute(function (servicename, scriptname, options, callback) {
servicename ? ensuredServiceName(servicename) : cli.prompt('Mobile service name: ', ensuredServiceName);
function ensuredServiceName(servicename) {
options.servicename = servicename;
scriptname ? ensuredScriptName(scriptname) : cli.prompt('Script name: ', ensuredScriptName);
function ensuredScriptName(scriptname) {
options.scriptname = scriptname;
options.script = parseScriptName(options.scriptname);
if (!options.script) {
log.info('For table script, specify tables/<tableName>.{insert|read|update|delete}');
log.info('For APNS script, specify shared/apnsFeedback');
log.info('For scheduler script, specify scheduler/<scriptName>');
return callback('Invalid script name ' + options.scriptname);
}
deleteScriptHandlers[options.script.type](options, callback);
}
}
});
};
| mwinkle/azure-sdk-tools-xplat | lib/commands/mobile.js | JavaScript | apache-2.0 | 90,981 |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
'use strict';
function main(parent, page) {
// [START dialogflow_v3beta1_generated_Pages_CreatePage_async]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* Required. The flow to create a page for.
* Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
* ID>/flows/<Flow ID>`.
*/
// const parent = 'abc123'
/**
* Required. The page to create.
*/
// const page = {}
/**
* The language of the following fields in `page`:
* * `Page.entry_fulfillment.messages`
* * `Page.entry_fulfillment.conditional_cases`
* * `Page.event_handlers.trigger_fulfillment.messages`
* * `Page.event_handlers.trigger_fulfillment.conditional_cases`
* * `Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`
* *
* `Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`
* * `Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`
* *
* `Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`
* * `Page.transition_routes.trigger_fulfillment.messages`
* * `Page.transition_routes.trigger_fulfillment.conditional_cases`
* If not specified, the agent's default language is used.
* Many
* languages (https://cloud.google.com/dialogflow/cx/docs/reference/language)
* are supported.
* Note: languages must be enabled in the agent before they can be used.
*/
// const languageCode = 'abc123'
// Imports the Cx library
const {PagesClient} = require('@google-cloud/dialogflow-cx').v3beta1;
// Instantiates a client
const cxClient = new PagesClient();
async function callCreatePage() {
// Construct request
const request = {
parent,
page,
};
// Run request
const response = await cxClient.createPage(request);
console.log(response);
}
callCreatePage();
// [END dialogflow_v3beta1_generated_Pages_CreatePage_async]
}
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
| googleapis/nodejs-dialogflow-cx | samples/generated/v3beta1/pages.create_page.js | JavaScript | apache-2.0 | 2,920 |
export { default as AreaChartGraph } from './areaChart';
export { default as DonutChartGraph } from './donutChart';
export { default as GroupBarChart } from './groupChart';
export { default as GroupHorizontalBarChart } from './groupHorizontalChart';
export { default as LineChartGraph } from './lineChart';
export { default as PieChartGraph } from './pieChart';
export { default as StackAreaChart } from './stackedAreaChart';
export { default as StackBarChartGraph } from './stackBarChart';
export { default as StackHorizontalChart } from './stackHorizontalChart';
| ManageIQ/manageiq-ui-classic | app/javascript/components/carbon-charts/index.js | JavaScript | apache-2.0 | 565 |
// 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 _ from 'lodash';
import $ from 'jquery';
import Backbone from "backbone";
const $param = $.param;
//PagingCollection
//----------------
// A PagingCollection knows how to build appropriate requests to the
// CouchDB-like server and how to fetch. The Collection will always contain a
// single page of documents.
export const PagingCollection = Backbone.Collection.extend({
// initialize parameters and page size
constructor: function() {
Backbone.Collection.apply(this, arguments);
this.configure.apply(this, arguments);
},
configure: function(collections, options) {
var querystring = _.result(this, "url").split("?")[1] || "";
this.paging = _.defaults((options.paging || {}), {
defaultParams: _.defaults({}, options.params, this._parseQueryString(querystring)),
hasNext: false,
hasPrevious: false,
params: {},
pageSize: 20,
direction: undefined
});
this.paging.params = _.clone(this.paging.defaultParams);
this.updateUrlQuery(this.paging.defaultParams);
},
calculateParams: function(currentParams, skipIncrement, limitIncrement) {
var params = _.clone(currentParams);
params.skip = (parseInt(currentParams.skip, 10) || 0) + skipIncrement;
// guard against hard limits
if(this.paging.defaultParams.limit) {
params.limit = Math.min(this.paging.defaultParams.limit, params.limit);
}
// request an extra row so we know that there are more results
params.limit = limitIncrement + 1;
// prevent illegal skip values
params.skip = Math.max(params.skip, 0);
return params;
},
pageSizeReset: function(pageSize, opts) {
var options = _.defaults((opts || {}), {fetch: true});
this.paging.direction = undefined;
this.paging.pageSize = pageSize;
this.paging.params = this.paging.defaultParams;
this.paging.params.limit = pageSize;
this.updateUrlQuery(this.paging.params);
if (options.fetch) {
return this.fetch();
}
},
_parseQueryString: function(uri) {
var queryString = decodeURI(uri).split(/&/);
return _.reduce(queryString, function (parsedQuery, item) {
var nameValue = item.split(/=/);
if (nameValue.length === 2) {
parsedQuery[nameValue[0]] = nameValue[1];
}
return parsedQuery;
}, {});
},
_iterate: function(offset, opts) {
var options = _.defaults((opts || {}), {fetch: true});
this.paging.params = this.calculateParams(this.paging.params, offset, this.paging.pageSize);
// Fetch the next page of documents
this.updateUrlQuery(this.paging.params);
if (options.fetch) {
return this.fetch({reset: true});
}
},
// `next` is called with the number of items for the next page.
// It returns the fetch promise.
next: function(options){
this.paging.direction = "next";
return this._iterate(this.paging.pageSize, options);
},
// `previous` is called with the number of items for the previous page.
// It returns the fetch promise.
previous: function(options){
this.paging.direction = "previous";
return this._iterate(0 - this.paging.pageSize, options);
},
shouldStringify: function (val) {
try {
JSON.parse(val);
return false;
} catch(e) {
return true;
}
},
// Encodes the parameters so that couchdb will understand them
// and then sets the url with the new url.
updateUrlQuery: function (params) {
var url = _.result(this, "url").split("?")[0];
_.each(['startkey', 'endkey', 'key'], function (key) {
if (_.has(params, key) && this.shouldStringify(params[key])) {
params[key] = JSON.stringify(params[key]);
}
}, this);
this.url = url + '?' + $param(params);
},
fetch: function () {
// if this is a fetch for the first time, fetch one extra to see if there is a next
if (!this.paging.direction && this.paging.params.limit > 0) {
this.paging.direction = 'fetch';
this.paging.params.limit = this.paging.params.limit + 1;
this.updateUrlQuery(this.paging.params);
}
return Backbone.Collection.prototype.fetch.apply(this, arguments);
},
parse: function (resp) {
var rows = resp.rows;
this.paging.hasNext = this.paging.hasPrevious = false;
this.viewMeta = {
total_rows: resp.total_rows,
offset: resp.offset,
update_seq: resp.update_seq
};
var skipLimit = this.paging.defaultParams.skip || 0;
if(this.paging.params.skip > skipLimit) {
this.paging.hasPrevious = true;
}
if(rows.length === this.paging.pageSize + 1) {
this.paging.hasNext = true;
// remove the next page marker result
rows.pop();
this.viewMeta.total_rows = this.viewMeta.total_rows - 1;
}
return rows;
},
hasNext: function() {
return this.paging.hasNext;
},
hasPrevious: function() {
return this.paging.hasPrevious;
}
});
export default PagingCollection;
// if (exports) {
// // Overload the Backbone.ajax method, this allows PagingCollection to be able to
// // work in node.js
// exports.setAjax = function (ajax) {
// Backbone.ajax = ajax;
// };
// exports.PagingCollection = PagingCollection;
// }
// return PagingCollection;
// }));
| garrensmith/couchdb-fauxton | assets/js/plugins/cloudant.pagingcollection.js | JavaScript | apache-2.0 | 5,832 |
/*! demo 2017-09-04 */
PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[\t\n\r \xA0]+/,null,"\t\n\r "],[PR.PR_PLAIN,/^(?:\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)|\'(?:[^\'\\]|\\[\s\S])+(?:\'|$)|`[^`]*(?:`|$))/,null,"\"'"]],[[PR.PR_COMMENT,/^(?:\/\/[^\r\n]*|\/\*[\s\S]*?\*\/)/],[PR.PR_PLAIN,/^(?:[^\/\"\'`]|\/(?![\/\*]))+/i]]),["go"]); | okboy5555/demo | 基于angular的图书管理/dest/src-min/framework/angular-1.5.8/docs/components/google-code-prettify-1.0.1/src/lang-go.min.js | JavaScript | apache-2.0 | 340 |
var Application = require("../");
describe('Application', function() {
});
| HappyRhino/hr.app | tests/index.js | JavaScript | apache-2.0 | 78 |
(function($) {
/**
* twentyc.edit module that provides inline editing tools and functionality
* for web content
*
* @module twentyc
* @class editable
* @static
*/
twentyc.editable = {
/**
* initialze all edit-enabled content
*
* called automatically on page load
*
* @method init
* @private
*/
init : function() {
if(this.initialized)
return;
this.templates.init();
$('[data-edit-target]').editable();
// hook into data load so we can update selects with matching datasets
$(twentyc.data).on("load", function(ev, payload) {
$('select[data-edit-data="'+payload.id+'"]').each(function(idx) {
$(this).data("edit-input").load(payload.data)
});
});
// init modules
$('[data-edit-module]').each(function(idx) {
var module = twentyc.editable.module.instantiate($(this));
module.init();
});
// initialize always toggled inputs
$('.editable.always').not(".auto-toggled").each(function(idx) {
var container = $(this);
container.find('[data-edit-type]').editable(
'filter', { belongs : container }
).each(function(idx) {
$(this).data("edit-always", true);
twentyc.editable.input.manage($(this), container);
});
});
this.initialized = true;
}
}
/**
* humanize editable errors
*
* @module twentyc
* @namespace editable
* @class error
* @static
*/
twentyc.editable.error = {
/**
* humanize the error of the specified type
*
* @method humanize
* @param {String} errorType error type string (e.g. "ValidationErrors")
* @returns {String} humanizedString
*/
humanize : function(errorType) {
switch(errorType) {
case "ValidationErrors":
return "Some of the fields contain invalid values - please correct and try again.";
break;
default:
return "Something went wrong.";
break;
}
}
}
/**
* container for action handler
*
* @module twentyc
* @namespace editable
* @class action
* @extends twentyc.cls.Registry
* @static
*/
twentyc.editable.action = new twentyc.cls.Registry();
twentyc.editable.action.register(
"base",
{
name : function() {
return this._meta.name;
},
execute : function(trigger, container) {
this.trigger = trigger
this.container = container;
if(this.loading_shim)
this.container.children('.editable.loading-shim').show();
},
signal_error : function(container, error) {
var payload = {
reason : error.type,
info : error.info,
data : error.data
}
container.trigger("action-error", payload);
container.trigger("action-error:"+this.name(), payload);
$(this).trigger("error", payload);
if(this.loading_shim)
this.container.children('.editable.loading-shim').hide();
},
signal_success : function(container, payload) {
container.trigger("action-success", payload);
container.trigger("action-success:"+this.name(), payload);
$(this).trigger("success", payload);
if(this.loading_shim)
this.container.children('.editable.loading-shim').hide();
}
}
);
twentyc.editable.action.register(
"toggle-edit",
{
execute : function(trigger, container) {
this.base_execute(trigger, container);
container.editable("toggle");
container.trigger("action-success:toggle", { mode : container.data("edit-mode") });
}
},
"base"
);
twentyc.editable.action.register(
"reset",
{
execute : function(trigger, container) {
container.editable("reset");
this.signal_success(container, {});
}
},
"base"
);
twentyc.editable.action.register(
"submit",
{
loading_shim : true,
execute : function(trigger, container) {
this.base_execute(trigger, container);
var me = this,
modules = [],
targets = 1,
changed,
status={"error":false},
i;
var dec_targets = function(ev,data,error) {
targets--;
if(error)
status.error = true;
if(!targets) {
if(!status.error && !me.noToggle) {
if(data)
container.editable("toggle", { data:data });
else
container.editable("toggle");
}
/*
if(!status.error && container.data("edit-always")) {
// if container is always toggled to edit mode
// update the original_value property of the
// input instance, so we can properly pick up
// changes for future edits
container.editable("accept-values");
}
*/
container.editable("loading-shim", "hide");
}
}
try {
// try creating target - this automatically parses form data
// into object literal
var target = twentyc.editable.target.instantiate(container);
changed = target.data._changed;
// prepare modules
container.find("[data-edit-module]").
//editable("filter", { belongs : container }).
each(function(idx) {
var module = twentyc.editable.module.instantiate($(this));
if(!module.has_action("submit")) {
module.prepare();
if(module.pending_submit.length) {
targets+=module.pending_submit.length;
modules.push([module, $(this)])
}
}
});
} catch(error) {
// we need to catch editable errors (identified by having type
// set and fire off an event in case of failure - this also
// catches validation errors
if(error.type) {
return this.signal_error(container, error);
} else {
// unknown errors are re-thrown so the browser can catch
// them properly
throw(error);
}
}
var grouped = container.editable("filter", { grouped : true }).not("[data-edit-module]");
targets += grouped.length;
if(changed || container.data("edit-always-submit") == "yes"){
$(target).on("success", function(ev, data) {
me.signal_success(container, data);
});
$(target).on("error", function(ev, error) {
me.signal_error(container, error);
dec_targets({}, {}, true);
});
$(target).on("success", dec_targets);
// submit main target
var result = target.execute();
} else
dec_targets({}, {});
// submit grouped targets
grouped.each(function(idx) {
var other = $(this);
var action = new (twentyc.editable.action.get("submit"))();
action.noToggle = true;
$(action).on("success",dec_targets);
$(action).on("error", function(){dec_targets({},{},true);});
action.execute(trigger, other);
});
// submit modules
for(i in modules) {
$(modules[i][0]).on("success", dec_targets);
$(modules[i][0]).on("error", function(){dec_targets({},{},true);});
modules[i][0].execute(trigger, modules[i][1]);
}
return result;
}
},
"base"
);
twentyc.editable.action.register(
"module-action",
{
name : function() {
return this.module._meta.name+"."+this.actionName;
},
execute : function(module, action, trigger, container) {
this.base_execute(trigger, container);
this.module = module;
this.actionName = action;
module.action = this;
$(module.target).on("success", function(ev, d) {
module.action.signal_success(container, d);
$(module).trigger("success", [d]);
});
$(module.target).on("error", function(ev, error) {
module.action.signal_error(container, error);
$(module).trigger("error", [error]);
});
try {
this.module["execute_"+action](trigger, container);
} catch(error) {
if(error.type) {
return this.signal_error(container, error);
} else {
// unknown errors are re-thrown so the browser can catch
// them properly
throw(error);
}
}
}
},
"base"
);
/**
* container for module handler
*
* @module twentyc
* @namespace editable
* @class module
* @extends twentyc.cls.Registry
* @static
*/
twentyc.editable.module = new twentyc.cls.Registry();
twentyc.editable.module.instantiate = function(container) {
var module = new (this.get(container.data("edit-module")))(container);
return module;
};
/**
* base module to use for all editable modules
*
* modules allow you add custom behaviour to forms / editing process
*
* @class base
* @namespace twentuc.editable.module
* @constructor
*/
twentyc.editable.module.register(
"base",
{
init : function() {
return;
},
has_action : function(action) {
return this.container.find('[data-edit-action="'+action+'"]').length > 0;
},
base : function(container) {
var comp = this.components = {};
container.find("[data-edit-component]").editable("filter",{belongs:container}).each(function(idx) {
var c = $(this);
comp[c.data("edit-component")] = c;
});
this.container = container;
container.data("edit-module-instance", this);
},
get_target : function(container) {
return twentyc.editable.target.instantiate(container || this.container);
},
execute : function(trigger, container) {
var me = $(this), action = trigger.data("edit-action");
this.trigger = trigger;
this.target = twentyc.editable.target.instantiate(container);
handler = new (twentyc.editable.action.get("module-action"))
handler.loading_shim = this.loading_shim;
handler.execute(this, action, trigger, container);
},
prepare : function() { this.prepared = true },
execute_submit : function(trigger, container) {
return;
}
}
);
/**
* this module allows you maintain a listing of items with functionality
* to add, remove and change the items.
*
* @class listing
* @namespace twentyc.editable.module
* @constructor
* @extends twentyc.editable.module.base
*/
twentyc.editable.module.register(
"listing",
{
pending_submit : [],
init : function() {
// a template has been specified for the add form
// try to build add row form from it
if(this.components.add && this.components.add.data("edit-template")) {
var addrow = twentyc.editable.templates.copy(this.components.add.data("edit-template"));
this.components.add.prepend(addrow);
}
if(this.container.data("edit-always")) {
var me = this;
this.container.on("listing:row-submit", function() {
me.components.list.editable("accept-values");
});
}
},
prepare : function() {
if(this.prepared)
return;
var pending = this.pending_submit = [];
var me = this;
this.components.list.children().each(function(idx) {
var row = $(this),
data = {};
var changedFields = row.find("[data-edit-type]").
editable("filter", "changed").
editable("filter", { belongs : me.components.list }, true);
if(changedFields.length == 0)
return;
row.find("[data-edit-type]").editable("filter", { belongs : me.components.list }).editable("export-fields", data);
row.editable("collect-payload", data);
pending.push({ row : row, data : data, id : row.data("edit-id")});
});
this.base_prepare();
},
row : function(trigger) {
return trigger.closest("[data-edit-id]").first();
},
row_id : function(trigger) {
return this.row(trigger).data("edit-id")
},
clear : function() {
this.components.list.empty();
},
add : function(rowId, trigger, container, data) {
var row = twentyc.editable.templates.copy(this.components.list.data("edit-template"))
var k;
row.attr("data-edit-id", rowId);
row.data("edit-id", rowId);
for(k in data) {
row.find('[data-edit-name="'+k+'"]').each(function(idx) {
$(this).text(data[k]);
$(this).data("edit-value", data[k]);
});
}
row.appendTo(this.components.list);
row.addClass("newrow");
container.editable("sync");
if(this.action)
this.action.signal_success(container, rowId);
container.trigger("listing:row-add", [rowId, row, data, this]);
this.components.list.scrollTop(function() { return this.scrollHeight; });
},
remove : function(rowId, row, trigger, container) {
row.detach();
if(this.action)
this.action.signal_success(container, rowId);
container.trigger("listing:row-remove", [rowId, row, this]);
},
submit : function(rowId, data, row, trigger, container) {
if(this.action)
this.action.signal_success(container, rowId);
container.trigger("listing:row-submit", [rowId, row, data, this]);
},
execute_submit : function(trigger, container) {
var i, P;
this.prepare();
if(!this.pending_submit.length) {
if(this.action)
this.action.signal_success(container);
return;
}
for(i in this.pending_submit) {
P = this.pending_submit[i];
this.submit(P.id, P.data, P.row, trigger, container);
}
},
execute_add : function(trigger, container) {
var data = {};
this.components.add.editable("export", data);
this.data = data
this.add(null,trigger, container, data);
},
execute_remove : function(trigger, container) {
var row = trigger.closest("[data-edit-id]").first();
this.remove(row.data("edit-id"), row, trigger, container);
}
},
"base"
);
/**
* allows you to setup and manage target handlers
*
* @module twentyc
* @namespace editable
* @class target
* @static
*/
twentyc.editable.target = new twentyc.cls.Registry();
twentyc.editable.target.error_handlers = {};
twentyc.editable.target.instantiate = function(container) {
var handler,
targetParam = container.data("edit-target").split(":")
// check if specified target has a handler, if not use standard XHR hander
if(!twentyc.editable.target.has(targetParam[0]))
handler = twentyc.editable.target.get("XHRPost")
else
handler = twentyc.editable.target.get(targetParam[0])
// try creating target - this automatically parses form data
// into object literal
return new handler(targetParam, container);
}
twentyc.editable.target.register(
"base",
{
base : function(target, sender) {
this.args = target;
this.label = this.args[0];
this.sender = sender;
this.data = {}
sender.editable("export", this.data)
},
data_clean : function(removeEmpty) {
var i, r = {};
for(i in this.data) {
if(removeEmpty && (this.data[i] === null || this.data[i] === ""))
continue;
if(i.charAt(0) != "_")
r[i] = this.data[i];
}
return r;
},
data_valid : function() {
return (this.data && this.data["_valid"]);
},
execute : function() {}
}
);
twentyc.editable.target.register(
"XHRPost",
{
execute : function(appendUrl, context, onSuccess, onFailure) {
var me = $(this), data = this.data;
if(context)
this.context = context;
if(this.context)
var sender = this.context;
else
var sender = this.sender;
$.ajax({
url : this.args[0]+(appendUrl?"/"+appendUrl:""),
method : "POST",
data : this.data_clean(this.data),
success : function(response) {
data.xhr_response = response;
me.trigger("success", data);
if(onSuccess)
onSuccess(response, data)
}
}).fail(function(response) {
twentyc.editable.target.error_handlers.http_json(response, me, sender);
if(onFailure)
onFailure(response)
});
}
},
"base"
)
twentyc.editable.target.error_handlers.http_json = function(response, me, sender) {
var info = [response.status + " " + response.statusText]
if(response.status == 400) {
var msg, k, i, info= ["The server rejected your data"];
for(k in response.responseJSON) {
sender.find('[data-edit-name="'+k+'"]').each(function(idx) {
var input = $(this).data("edit-input-instance");
if(input) {
msg = response.responseJSON[k];
if(typeof msg == "object" && msg.join)
msg = msg.join(",");
input.show_validation_error(msg);
}
});
if(k == "non_field_errors") {
for(i in response.responseJSON[k])
info.push(response.responseJSON[k][i]);
}
}
} else {
if(response.responseJSON && response.responseJSON.non_field_errors) {
info = [];
var i;
for(i in response.responseJSON.non_field_errors)
info.push(response.responseJSON.non_field_errors[i]);
}
}
me.trigger(
"error",
{
type : "HTTPError",
info : info.join("<br />")
}
);
}
/**
* allows you to setup and manage input types
*
* @module twentyc
* @namespace editble
* @class input
* @static
*/
twentyc.editable.input = new (twentyc.cls.extend(
"InputRegistry",
{
frame : function() {
var frame = $('<div class="editable input-frame"></div>');
return frame;
},
wire : function(it, element, container) {
var action = container.data("edit-enter-action");
if(it.action_on_enter && action) {
element.on("keydown", function(e) {
if(e.which == 13) {
handler = new (twentyc.editable.action.get(action));
handler.execute(element, container);
}
});
}
it.element.focus(function(ev) {
it.reset();
});
if(it.wire)
it.wire();
},
manage : function(element, container) {
var it = new (this.get(element.data("edit-type")));
var par = element.parent()
it.container = container;
it.source = element;
it.element = element;
it.frame = this.frame();
it.frame.insertBefore(element);
it.frame.append(element);
it.original_value = it.get();
this.wire(it, it.element, container);
element.data("edit-input-instance", it);
return it;
},
create : function(name, source, container) {
var it = new (this.get(name));
it.source = source
it.container = container
it.element = it.make();
it.frame = this.frame();
it.frame.append(it.element);
it.set(source.data("edit-value"));
it.original_value = it.get();
if(source.data().hasOwnProperty("editResetValue")) {
it.reset_value = source.data("edit-reset-value") || null;
} else {
it.reset_value = it.original_value;
}
if(it.placeholder)
it.element.attr("placeholder", it.placeholder)
else if(it.source.data("edit-placeholder"))
it.element.attr("placeholder", it.source.data("edit-placeholder"))
this.wire(it, it.element, container);
return it;
}
},
twentyc.cls.Registry
));
twentyc.editable.input.register(
"base",
{
action_on_enter : false,
set : function(value) {
if(value == undefined) {
this.element.val(this.source.text().trim());
} else
this.element.val(value);
},
get : function() {
return this.element.val();
},
changed : function() {
return (this.original_value != this.get());
},
export : function() {
return this.get()
},
make : function() {
return $('<input type="text"></input>');
},
blank : function() {
return (this.element.val() === "");
},
validate : function() {
return true;
},
validation_message : function() {
return "Invalid value"
},
required_message : function() {
return "Input required"
},
load : function() {
return;
},
apply : function(value) {
if(!this.source.data("edit-template"))
this.source.html(this.get());
else {
var tmplId = this.source.data("edit-template");
var tmpl = twentyc.editable.templates.get(tmplId);
var node = tmpl.clone(true);
if(this.template_handlers[tmplId]) {
this.template_handlers[tmplId](value, node, this);
}
this.source.empty().append(node);
}
},
show_note : function(txt, classes) {
var note = $('<div class="editable input-note"></div>');
note.text(txt)
note.addClass(classes);
if(this.element.hasClass('input-note-relative'))
note.insertAfter(this.element);
else
note.insertBefore(this.element);
this.note = note;
return note;
},
close_note : function() {
if(this.note) {
this.note.detach();
this.note = null;
}
},
show_validation_error : function(msg) {
this.show_note(msg || this.validation_message(), "validation-error");
this.element.addClass("validation-error");
},
reset : function(resetValue) {
this.close_note();
this.element.removeClass("validation-error");
if(resetValue) {
this.source.data("edit-value", this.reset_value);
this.set(this.reset_value);
}
},
template_handlers : {}
}
);
twentyc.editable.input.register(
"string",
{
action_on_enter : true
},
"base"
);
twentyc.editable.input.register(
"password",
{
make : function() {
return $('<input type="password"></input>');
},
validate : function() {
var conf = this.source.data("edit-confirm-with")
if(conf) {
return (this.container.find('[data-edit-name="'+conf+'"]').data("edit-input-instance").get() == this.get());
} else
return true;
},
validation_message : function() {
return "Needs to match password"
}
},
"string"
);
twentyc.editable.input.register(
"email",
{
placeholder : "name@example.com",
validate : function() {
if(this.get() === "")
return true
return this.get().match(/@/);
},
validation_message : function() {
return "Needs to be a valid email address";
},
template_handlers : {
"link" : function(value, node) {
node.attr("href", "mailto:"+value).html(value);
}
}
},
"string"
);
twentyc.editable.input.register(
"url",
{
placeholder : "http://www.example.com",
validate : function() {
var url = this.get()
if(url === "")
return true
if(!url.match(/^[a-zA-Z]+:\/\/.+/)) {
url = "http://"+url;
this.set(url);
}
if(url.match(/\s/))
return false;
return true;
},
validation_message : function() {
return "Needs to be a valid url";
},
template_handlers : {
"link" : function(value, node) {
node.attr("href", value).html(value);
}
}
},
"string"
);
twentyc.editable.input.register(
"number",
{
validate : function() {
return this.element.val().match(/^[\d\.\,-]+$/)
},
validation_message : function() {
return "Needs to be a number"
}
},
"string"
);
twentyc.editable.input.register(
"bool",
{
value_to_label : function() {
return (this.element.prop("checked") ? "Yes" : "No");
},
make : function() {
return $('<input class="editable input-note-relative" type="checkbox"></input>');
},
get : function() {
return this.element.prop("checked");
},
set : function(value) {
if(value == true || (typeof value == "string" && value.toLowerCase() == "true"))
this.element.prop("checked", true);
else
this.element.prop("checked", false);
},
required_message : function() {
return "Check required"
},
blank : function() {
return this.get() != true;
},
apply : function(value) {
this.source.data("edit-value", this.get());
if(!this.source.data("edit-template")) {
this.source.html(this.value_to_label());
} else {
var tmplId = this.source.data("edit-template");
var tmpl = twentyc.editable.templates.get(tmplId);
var node = tmpl.clone(true);
if(this.template_handlers[tmplId]) {
this.template_handlers[tmplId](value, node, this);
}
this.source.empty().append(node);
}
}
},
"base"
);
twentyc.editable.input.register(
"text",
{
make : function() {
return $('<textarea></textarea>');
}
},
"base"
);
twentyc.editable.input.register(
"select",
{
make : function() {
var node = $('<select></select>');
if(this.source.data("edit-multiple") == "yes")
node.prop("multiple", true);
if(this.source.data("edit-data"))
node.attr("data-edit-data", this.source.data("edit-data"))
return node;
},
set : function() {
var dataId, me = this;
if(dataId=this.source.data("edit-data")) {
twentyc.data.load(dataId, {
callback : function(payload) {
me.load(payload.data);
me.original_value = me.get()
}
});
}
},
value_to_label : function() {
return this.element.children('option:selected').text();
},
apply : function(value) {
this.source.data("edit-value", this.get());
this.source.html(this.value_to_label());
},
add_opt : function(id, name) {
var opt = $('<option></option>');
opt.val(id);
opt.text(name);
var value = this.source.data("edit-value")
if(this.source.data("edit-multiple") == "yes") {
if(value && $.inArray(id, value.split(",")) > -1)
opt.prop("selected", true);
} else {
if(id == value)
opt.prop("selected", true);
}
this.element.append(opt);
},
load : function(data) {
var k, v, opt;
this.element.empty();
if(this.source.data("edit-data-all-entry")) {
var allEntry = this.source.data("edit-data-all-entry").split(":")
this.add_opt(allEntry[0], allEntry[1]);
}
for(k in data) {
v = data[k];
this.add_opt(v.id, v.name);
}
this.element.trigger("change");
}
},
"base"
);
/**
* class that managed DOM templates
*
* @class templates
* @namespace twentyc.editable.templates
* @static
*/
twentyc.editable.templates = {
_templates : {},
register : function(id, node) {
if(this._templates[id])
throw("Duplicate template id: "+id);
this._templates[id] = node;
},
get : function(id) {
if(!this._templates[id])
throw("Tried to retrieve unknown template: "+id);
return this._templates[id];
},
copy : function(id) {
return this.get(id).clone().attr("id", null);
},
copy_and_replace : function(id, data, setEditValue) {
var k, tmpl=this.copy(id);
for(k in data) {
tmpl.find('[data-edit-name="'+k+'"]').each(function() {
$(this).text(data[k]);
if(setEditValue)
$(this).data("edit-value", data[k])
});
}
return tmpl;
},
init : function() {
if(this.initialized)
return;
$('#editable-templates, .editable-templates').children().each(function(idx) {
twentyc.editable.templates.register(
this.id,
$(this)
);
});
this.initialized = true;
}
}
twentyc.editable.templates.register("link", $('<a></a>'));
/*
* jQuery functions
*/
$.fn.editable = function(action, arg, dbg) {
/******************************************************************************
* FILTERS
*/
if(action == "filter") {
// filter jquery result
var matched = [];
if(arg) {
// only proceed if arguments are provided
var i = 0,
l = this.length,
input,
node,
nodes,
closest,
result
// BELONGS (container), shortcut for first_closest:["data-edit-target", target]
if(arg.belongs) {
arg.first_closest = ["[data-edit-target], [data-edit-component]", arg.belongs]
}
// FIRST CLOSEST, first_closest:[selector, result]
if(arg.first_closest) {
for(; i < l; i++) {
closest = $(this[i]).parent().closest(arg.first_closest[0]);
if(closest.length && closest.get(0) == arg.first_closest[1].get(0))
matched.push(this[i])
}
}
// GROUPED
else if(arg.grouped) {
for(; i < l; i++) {
node = $(this[i]);
if(node.data("edit-group"))
continue;
nodes = $('[data-edit-group]').each(function(idx) {
var other = $($(this).data("edit-group"));
if(other.get(0) == node.get(0))
matched.push(this);
});
}
}
// CHANGED FIELDS
else if(arg == "changed") {
for(; i < l; i++) {
node = $(this[i]);
input = node.data("edit-input-instance")
if(input && input.changed()) {
matched.push(this[i])
}
}
}
}
return this.pushStack(matched);
} else if(action == "export-fields") {
// track validation errors in here
var validationErrors = {};
arg["_valid"] = true;
// collect values from editable fields
this.each(function(idx) {
try {
$(this).editable("export", arg)
} catch(error) {
if(error.type == "ValidationError") {
validationErrors[error.field] = error.message;
arg["_valid"] = false
} else {
throw(error);
}
}
});
arg["_validationErrors"] = validationErrors;
if(!arg["_valid"]) {
throw({type:"ValidationErrors", data:arg});
}
} else if(action == "collect-payload") {
this.find(".payload").children('[data-edit-name]').each(function(idx) {
var plel = $(this);
arg[plel.data("edit-name")] = plel.text().trim();
});
}
/******************************************************************************
* ACTIONS
*/
this.each(function(idx) {
var me = $(this);
var hasTarget = (me.data("edit-target") != null);
var isComponent = (me.data("edit-component") != null);
var isContainer = (hasTarget || isComponent);
var hasAction = (me.data("edit-action") != null);
var hasType = (me.data("edit-type") != null);
/****************************************************************************
* INIT
**/
if(!action && !me.data("edit-initialized")) {
// mark as initialized so there is no duplicate init
me.data("edit-initialized", true);
// CONTAINER
if(hasTarget) {
if(me.hasClass("always")) {
me.data("edit-mode", "edit");
me.data("edit-always", true);
} else
me.data("edit-mode", "view");
me.editable("sync");
// create error message container
var errorContainer = $('<div class="editable popin error"><div class="main"></div><div class="extra"></div></div>');
errorContainer.hide();
me.prepend(errorContainer)
me.data("edit-error-container", errorContainer);
// create loading shim
var loadingShim = $('<div class="editable loading-shim"></div>');
loadingShim.hide();
me.prepend(loadingShim)
me.data("edit-loading-shim", loadingShim);
// whenever an action signals an error we want to update and show
// the error container
me.on("action-error", function(e, payload) {
var popin = $(this).find(".editable.popin.error").editable("filter", { belongs : $(this) });
popin.find('.main').html(twentyc.editable.error.humanize(payload.reason));
popin.find('.extra').html(payload.info || "");
popin.show();
return false;
});
}
// INTERACTIVE ELEMENT
if(hasAction) {
me.data("edit-parent", arg);
var eventName = "click"
if(
me.data("edit-type") == "bool" ||
me.data("edit-type") == "list" ||
me.data("edit-type") == "select"
)
{
eventName = "change";
}
// bind action event
me.on(eventName, function() {
var handler, a = $(this).data("edit-action");
var container = $(this).closest("[data-edit-target]");
/*
if(!twentyc.editable.action.has(a)) {
if(container.data("edit-module")) {
handler = twentyc.editable.module.instantiate(container);
}
if(!handler)
throw("Unknown action: " + a);
} else
handler = new (twentyc.editable.action.get(a));
*/
if(container.data("edit-module")) {
handler = twentyc.editable.module.instantiate(container);
}
if(!handler)
handler = new (twentyc.editable.action.get(a));
var r = handler.execute($(this), container);
me.trigger("action:"+a, r);
});
me.data("edit-parent", arg);
}
// EDITABLE ELEMENT
if(hasType) {
// editable element
me.data("edit-parent", arg);
}
}
/****************************************************************************
* RESET FORM
*/
else if(action == "reset") {
me.find("[data-edit-type]").
editable("filter", { belongs : me }).
each(function(idx) {
$(this).data("edit-input-instance").reset(true);
});
me.editable("filter", {grouped:true}).not("[data-edit-module]").editable("reset");
me.find("[data-edit-module]").editable("filter", { belongs : me }).editable("reset");
me.find("[data-edit-component]").editable("filter", { belongs : me }).editable("reset");
}
/****************************************************************************
* SYNC
**/
else if(action == "sync") {
var mode = me.data("edit-mode") || "view";
// init contained interactive elements
me.find("[data-edit-action]").
filter("a, input, select").
editable("filter", {belongs:me}).
each(function(idx) {
var child = $(this);
if(!child.data("edit-parent"))
child.editable(null, me)
});
// init contained editable elements
me.find("[data-edit-type]").
editable("filter", { belongs : me }).
each(function(idx) {
var child = $(this);
if(!child.data("edit-parent"))
child.editable(null, me)
if((child.data("edit-mode")||"view") != mode) {
child.editable("toggle");
}
});
// load required data-sets
me.find('[data-edit-data]').
editable('filter', { belongs : me }).
each(function(idx) {
var dataId = $(this).data("edit-data");
twentyc.data.load(dataId);
});
// toggle mode-toggled content
me.find('[data-edit-toggled]').
editable('filter', { belongs : me }).
each(function(idx) {
var child = $(this);
if(child.data("edit-toggled") != mode)
child.hide()
else
child.show()
});
// sync components
me.find('[data-edit-component]').editable("filter", { belongs : me }).each(function() {
var comp = $(this);
comp.data("edit-mode", mode);
comp.editable("sync");
});
}
/****************************************************************************
* TOGGLE
**/
else if(action == "toggle") {
// toggle edit mode on or off
var mode = me.data("edit-mode")
if(me.hasClass("always"))
return;
if(isContainer) {
// CONTAINER
if(mode == "edit") {
me.find('[data-edit-toggled="edit"]').editable("filter", { belongs : me }).hide();
me.find('[data-edit-toggled="view"]').editable("filter", { belongs : me }).show();
mode = "view";
me.removeClass("mode-edit")
if(!arg)
me.trigger("edit-cancel");
} else {
me.find('[data-edit-toggled="edit"]').editable("filter", { belongs : me }).show();
me.find('[data-edit-toggled="view"]').editable("filter", { belongs : me }).hide();
mode = "edit";
me.addClass("mode-edit")
}
// hide pop-ins
me.find('.editable.popin').editable("filter", { belongs : me }).hide();
// toggled editable elements
me.find("[data-edit-type], [data-edit-component]").editable("filter", { belongs : me }).editable("toggle", arg);
// toggle other containers that are flagged to be toggled by this container
me.editable("filter", { grouped : 1 }).each(function(idx) {
$(this).editable("toggle", arg);
});
} else if(hasType) {
// EDITABLE ELEMENT
var input;
if(me.data("edit-always"))
return;
if(mode == "edit") {
// element is currently editable, switch it back to view-only
// mode
input = me.data("edit-input-instance")
input.reset();
if(arg && !$.isEmptyObject(arg.data))
input.apply(arg.data[me.data("edit-name")])
else
me.html(me.data("edit-content-backup"))
me.data("edit-input-instance", null);
mode = "view";
} else {
// element is currently not editable, switch it to edit mode
input = twentyc.editable.input.create(
me.data('edit-type'),
me,
me.closest("[data-edit-target]")
);
input.element.data('edit-input', input);
input.element.data('edit-name', me.data('edit-name'));
input.element.data('edit-type', me.data('edit-type'));
input.element.addClass("editable "+ me.data("edit-type"));
// store old content so we can switch back to it
// in case of edit-cancel event
me.data("edit-content-backup", me.html());
// replace content with input
me.data("edit-input-instance", input);
me.empty();
me.append(input.frame);
mode = "edit";
}
}
me.data("edit-mode", mode);
me.trigger("toggle", [mode]);
}
/****************************************************************************
* TOGGLE LOADING SHIM
**/
else if(action == "loading-shim") {
if(arg == "show" || arg == "hide") {
me.children(".editable.loading-shim")[arg]();
}
}
/****************************************************************************
* REMOVE ERROR POPINS
*/
else if(action == "clear-error-popins") {
me.find('.editable.popin').editable("filter", { belongs : me }).hide();
}
/****************************************************************************
* ACCEPT VALUES
* This sets the original_values of all input instances within the container
* to the current input value
*/
else if(action == "accept-values") {
me.find("[data-edit-type]").editable("filter", { belongs : me }).each(function() {
var input = $(this).data("edit-input-instance");
if(input)
input.original_value = input.get();
});
}
/****************************************************************************
* ADD PAYLOAD
**/
else if(action == "payload") {
var payload = me.children(".payload")
if(!payload.length) {
payload = $('<div></div>')
payload.addClass("editable");
payload.addClass("payload");
me.prepend(payload);
}
var i, node;
for(i in arg) {
node = payload.children('[data-edit-name="'+i+'"]')
if(!node.length) {
node = $('<div></div>')
node.attr("data-edit-name", i)
payload.append(node);
}
node.text(arg[i]);
}
}
/****************************************************************************
* EXPORT FORM DATA
**/
else if(action == "export") {
// export form data to object literal
if(isContainer) {
// container, find all inputs within, exit if not in edit mode
if(me.data("edit-mode") != "edit" && !me.hasClass("always"))
return;
// export all the fields that belong to this container
me.find('[data-edit-type]').
editable("filter", { belongs : me }).
editable("export-fields", arg);
// if data-edit-id is specified make sure to copy it to exported data
// under _id
if(me.data("edit-id") != undefined) {
arg["_id"] = me.data("edit-id");
}
// check if payload element exists, and if it does add the data from
// it to the exported data
me.editable("collect-payload", arg);
me.trigger("export", [arg])
} else if(hasType) {
// editable element, see if input element exists and retrieve value
var input;
if(input=me.data("edit-input-instance")) {
input.reset();
// if input is required make sure it is not blank
if(me.data("edit-required") == "yes") {
if(input.blank()) {
input.show_validation_error(input.required_message());
throw({type:"ValidationError", field:me.data("edit-name"), message:input.required_message()})
}
}
// validate input
if(!input.validate()) {
input.show_validation_error();
throw({type:"ValidationError", field:me.data("edit-name"), message:input.validation_message()})
}
arg[me.data("edit-name")] = input.export();
if(typeof arg["_changed"] == "undefined") {
arg["_changed"] = input.changed() ? 1: 0;
} else {
arg["_changed"] += input.changed() ? 1 : 0;
}
}
}
}
});
};
/*
* Init
*/
$(document).ready(function() {
twentyc.editable.init();
});
})(jQuery);
| 20c/js-edit | src/twentyc.edit.js | JavaScript | apache-2.0 | 42,479 |
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* 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 { PureComponent } from 'react';
import Immutable from 'immutable';
import PropTypes from 'prop-types';
import Radium from 'radium';
import jobsUtils from 'utils/jobsUtils';
import FileUtils from 'utils/FileUtils';
import HoverHelp from 'components/HoverHelp';
@Radium
class Quote extends PureComponent {
static propTypes = {
jobIOData: PropTypes.instanceOf(Immutable.Map).isRequired
};
constructor(props) {
super(props);
}
render() {
const { jobIOData } = this.props;
if (!jobIOData.get('inputBytes') && !jobIOData.get('outputBytes')) {
return null;
}
return (
<div className='quote-holder' style={[styles.base]}>
<div style={[styles.input]}>
<h5>Input</h5>
<table>
<tbody>
<tr className='quote-wrap' style={styles.row}>
<td style={styles.fieldInput}>Input Bytes:</td>
<td style={styles.value}>{FileUtils.getFormattedBytes(jobIOData.get('inputBytes'))}</td>
</tr>
<tr className='quote-wrap' style={styles.row}>
<td style={[styles.inputRecords, styles.fieldInput]}>
Input Records:
</td>
<td style={styles.value}>{jobsUtils.getFormattedRecords(jobIOData.get('inputRecords'))}</td>
</tr>
</tbody>
</table>
</div>
<div style={[styles.output]}>
<h5>Output</h5>
<table>
<tbody>
<tr className='quote-wrap' style={styles.row}>
<td style={styles.fieldOutput}>Output Bytes:</td>
<td style={styles.value}>{FileUtils.getFormattedBytes(jobIOData.get('outputBytes'))}</td>
<td></td>
</tr>
<tr className='quote-wrap' style={styles.row}>
<td style={styles.fieldOutput}>Output Records:</td>
<td style={styles.value}>{jobsUtils.getFormattedRecords(jobIOData.get('outputRecords'))}</td>
<td style={styles.truncated}> {jobIOData.get('isOutputLimited') ?
<div style={styles.truncatedText}> Automatic Truncation <HoverHelp style={styles.truncatedHover} content={la('UI Jobs are automatically truncated.')}/></div> : ''}
</td>
</tr>
</tbody>
</table>
</div>
</div>
);
}
}
export default Quote;
const styles = {
base: {
display: 'flex',
justifyContent: 'flex-start'
},
input: {
minWidth: 155
},
fieldOutput: {
width: 100,
paddingBottom: 5,
color: '#999'
},
truncated: {
paddingBottom: 5,
color: '#999',
position: 'relative'
},
truncatedText: {
display: 'flex',
alignItems: 'center'
},
truncatedHover: {
display: 'inline-block',
position: 'absolute',
top: -5,
right: -24,
color: 'black'
},
inputRecords: {
marginRight: 2
},
fieldInput: {
width: 100,
paddingBottom: 5,
color: '#999'
},
output: {
marginLeft: 20
},
value: {
flexGrow: 1,
textAlign: 'right',
paddingBottom: 5
}
};
| dremio/dremio-oss | dac/ui/src/pages/JobPage/components/JobDetails/Quote.js | JavaScript | apache-2.0 | 3,758 |
'use strict';
module.exports = function(config) {
config.set({
basePath: '../',
proxies: {
'/': 'http://localhost:9876/'
},
urlRoot: '/__karma__/',
browsers: [
'Chrome'
],
frameworks: [
'browserify',
'jasmine'
],
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'src/main.js',
'test/unit/**/*.js'
],
preprocessors: {
'test/unit/**/*.js': ['browserify'],
'src/**/*.js': ['browserify']
},
browserify: {
debug: true
},
plugins: [
'karma-jasmine',
'karma-browserify',
'karma-chrome-launcher'
]
});
};
| OnOneLeg/O1l-frontend | myapp/node_modules/ng-firebase-auth/package/test/karma.conf.js | JavaScript | apache-2.0 | 702 |
(function () {
'use strict';
angular
.module('woodstock24App')
/*
Languages codes are ISO_639-1 codes, see http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
They are written in English to avoid character encoding issues (not a perfect solution)
*/
.constant('LANGUAGES', [
'en',
'nl',
'de',
'ru',
'sv'
// jhipster-needle-i18n-language-constant - JHipster will add/remove languages in this array
]
);
})();
| solairerove/woodstock | src/main/webapp/app/components/language/language.constants.js | JavaScript | apache-2.0 | 554 |
const path = require('path')
const chalk = require('chalk')
const fs = require('fs')
const DEFAULT_OPTIONS = {
appName: 'app',
outputPath: './target/webpack/assets/',
outputPublicPath: '/assets/',
srcPath: './src',
entry: './src/main/index.js',
playgroundEntry: './src/playground/index.js',
devPort: 3000,
uglify: true,
createSourceMap: true,
createIndexHtml: true,
autoprefixerBrowser: ['>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 11'],
tsDevTypeChecking: false,
tsAwesomeTypescriptLoader: false,
isLibrary: false,
outputLibraryPath: './dist/',
}
const validate = options => {
if (options.hasOwnProperty('hotReloadPort')) {
console.log(chalk.red('The property hotReloadPort is not needed any more. Please remove it.'))
}
if (options.hasOwnProperty('devtool')) {
console.log(chalk.red('The property devtool is not supported any longer. Please remove it.'))
}
if (options.hasOwnProperty('babelLoaderProdPlugins')) {
console.log(chalk.red('The property babelLoaderProdPlugins is not supported any longer. Please remove it.'))
}
if (options.hasOwnProperty('mainJs')) {
console.log(chalk.red('The property mainJs was replaced by entry. Please change it.'))
}
if (options.hasOwnProperty('playgroundJs')) {
console.log(chalk.red('The property playgroundJs was replaced by playgroundEntry. Please change it.'))
}
}
const createOptions = (userOptions) => {
userOptions.isLibrary = userOptions.isLibrary || userOptions.isReactLibrary
userOptions.tsconfigPath = path.join(process.cwd(), 'tsconfig.json')
userOptions.tslintPath = path.join(process.cwd(), 'tslint.json')
userOptions.srcPath = path.join(process.cwd(), 'src')
userOptions.isTypescript = fs.existsSync(userOptions.tsconfigPath)
const options = Object.assign({}, DEFAULT_OPTIONS, userOptions)
validate(options)
return options
}
module.exports = createOptions
| Indoqa/indoqa-webpack | src/createOptions.js | JavaScript | apache-2.0 | 1,917 |
onmessage = function(e){
const start = Date.now();
const links = e.data.links;
const dm = e.data.matrix;
const labels = Object.keys(dm);
const epsilon = Math.pow(10, e.data.epsilon);
const metric = e.data.metric;
const n = labels.length
const m = links.length;
let output = new Uint8Array(m);
let matrix = [];
let map = [];
for (let i = 0; i < n; i++) {
let minDist = Number.MAX_VALUE;
let targets = [];
const nodeid = labels[i];
const row = dm[nodeid];
for (let j = 0; j < n; j++) {
let cell = row[labels[j]];
if(!cell) {
targets.push(0);
continue;
};
let value = cell[metric];
targets.push(value);
}
matrix.push(targets);
map.push(nodeid);
}
const mst = primMST(matrix);
const nng = nearest_neighbour_graph(matrix, mst, epsilon);
for (let i = 0; i < n; i++) {
const source = map[i];
nng[i].push(mst[i]);
Array.from(new Set(nng[i])).forEach((u, index) => {
const target = map[u];
for(let k = 0; k < m; k++){
let l = links[k];
if((l.source == source && l.target == target) || (l.source == target && l.target == source)) {
output[k] = 1;
}
}
})
}
console.log('MST Compute time: ', (Date.now()-start).toLocaleString(), 'ms');
postMessage({links: output.buffer, start: Date.now()}, [output.buffer]);
close();
};
const minKey = (key, mstSet, V) => {
let min = Number.MAX_VALUE;
let min_index = -1;
for (let v = 0; v < V; v++)
if (!mstSet[v] && key[v] < min) {
min = key[v];
min_index = v;
}
return min_index;
}
const primMST = (graph) => {
const V = graph.length;
let parent = [];
let key = [];
let mstSet = [];
for (let i = 0; i < V; i++) {
key[i] = Number.MAX_VALUE;
mstSet[i] = false;
}
key[0] = 0.0;
parent[0] = -1;
for (let count = 0; count < V-1; count++) {
let u = minKey(key, mstSet, V);
if (u < 0) continue;
mstSet[u] = true;
if (graph[u].reduce((a, b) => a + b, 0) === 0 && u != 0) continue;
for (let v = 0; v < V; v++) {
if (graph[u][v] >= 0 && !mstSet[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
return parent;
}
const nearest_neighbour_graph = (graph, mst_parents, epsilon) => {
const V = graph.length;
let mst = [];
for (let i=0; i<V; ++i) {
mst.push([]);
}
for (let i=1; i<V; ++i) {
mst[i].push(mst_parents[i]);
mst[mst_parents[i]].push(i);
}
let nng = [];
let longest_edge = [];
for (let i=0; i<V; ++i) {
nng.push([]);
longest_edge.push([]);
for (let j=0; j<V; ++j) {
longest_edge[i][j] = 0;
}
}
for (let i=0; i<V; ++i) {
bfs_update_matrix(mst, graph, i, longest_edge);
}
for (let i=0; i<V; ++i) {
for (let j=0; j<V; ++j) {
if ((graph[i][j] > 0 ) && (graph[i][j] <= (longest_edge[i][j] * (1.0 + epsilon)))) {
nng[i].push(j);
nng[j].push(i);
}
}
}
return nng;
}
const bfs_update_matrix = (mst, weights, root, longest_edge) => {
let visited = [];
let queue = [];
queue.push(root);
while (queue.length) {
let v = queue.shift();
visited[v] = true;
mst[v].forEach((u, index) => {
if(visited[u]) return;
queue.push(u);
const value = Math.max(weights[v][u], Math.max(longest_edge[root][u], longest_edge[root][v]));
longest_edge[root][u] = value;
longest_edge[u][root] = value;
})
}
} | CDCgov/MicrobeTRACE | workers/compute-mst.js | JavaScript | apache-2.0 | 3,653 |
var structqt__meta__stringdata___my_device__t =
[
[ "data", "structqt__meta__stringdata___my_device__t.html#abbaa330742df766fe3dba9f355ec3cbc", null ],
[ "stringdata0", "structqt__meta__stringdata___my_device__t.html#af8cfff3ab861a8d6e52b4e876dbb73e6", null ]
]; | zvebabi/Analizer_LED_ms_HT | doxygen/html/structqt__meta__stringdata___my_device__t.js | JavaScript | apache-2.0 | 270 |
exports.definition = {
config: {
adapter: {
type: "restapi2",
collection_name: "address",
idAttribute: "id"
},
columns: {
id: "int"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
url: function() {
return "https://api.sohnar.com/TrafficLiteServer/openapi/crm/client/address/" + this.id;
},
parse: function(_resp, xhr) {
return _resp;
},
getPrintableAddress: function(separator, showAddressName) {
var addressArray = [];
showAddressName && addressArray.push(this.attributes.name);
addressArray.push(this.attributes.address.lineOne);
addressArray.push(this.attributes.address.lineTwo);
addressArray.push(this.attributes.address.lineThree);
addressArray.push(this.attributes.address.city);
addressArray.push(this.attributes.address.postCode);
addressArray.push(this.attributes.address.country.printableName);
var addressAsText = "";
for (var i = 0, j = addressArray.length; i < j; i++) addressArray[i] && (addressAsText += addressArray[i] + separator);
return addressAsText;
}
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
url: function() {
return "https://api.sohnar.com/TrafficLiteServer/openapi/crm/client/" + this.parentCRMEntryId + "/locations/";
},
parse: function(_resp, xhr) {
return _resp;
}
});
return Collection;
}
};
var Alloy = require("alloy"), _ = require("alloy/underscore")._, model, collection;
model = Alloy.M("address", exports.definition, []);
collection = Alloy.C("address", exports.definition, model);
exports.Model = model;
exports.Collection = collection; | fryertom44/TrafficContacts | Resources/alloy/models/Address.js | JavaScript | apache-2.0 | 2,059 |
/**
* [Up one level](/lib/index.html)
* ### Users CLI
* See the disqus-node [Users API](/lib/api/trends.html).
*
* See the [Users API on Disqus.com](https://disqus.com/api/docs/trends/).
*/
var container = require('../container');
var Command = container.get('commander').Command;
var users = new Command('disqus users');
users
.usage('<cmd> [options]');
/**
* ### listPosts
* Returns a list of trending threads.
*
* Output of `disqus users listPosts --help`:
* ```
Usage: disqus users listPosts [options]
Options:
-C, --cursor [string] Defaults to null.
-H, --https [boolean] Whether to use https. Defaults to true.
-i, --include [array] Defaults to ["approved"]. Choices: unapproved, approved, spam, deleted, flagged, highlighted.'
-l, --limit [number] Defaults to 25. Maximum value of 100.'
-L, --logLevel [string] Output log level. Choices: debug, info, notice, warning, error, critical, alert, emergency.
-o, --order [string] Defaults to "desc". Choices: asc, desc.
-r, --related [array] You may specify relations to include with your response. Choices: forum, thread.
-S, --api_secret <string> Your application\'s api_secret.
-s, --since [string] Defaults to null. Unix timestamp (or ISO datetime standard).
-u, --user <number|string> Looks up a user by ID or username.
* ```
*/
users
.command('listPosts')
.description('Returns a list of posts.')
.option('-C, --cursor [string]', 'Defaults to null.', null)
.option('-H, --https [boolean]', 'Whether to use https. Defaults to true.', true)
.option('-i, --include [array]', 'Defaults to ["approved"]. Choices: unapproved, approved, spam, deleted, flagged, highlighted.', ['approved'])
.option('-l, --limit [number]', 'Defaults to 25. Maximum value of 100.', 25)
.option('-L, --logLevel [string]', 'Output log level. Choices: debug, info, notice, warning, error, critical, alert, emergency.', 'info')
.option('-o, --order [string]', 'Defaults to "desc". Choices: asc, desc.', 'desc')
.option('-r, --related [array]', 'You may specify relations to include with your response. Choices: forum, thread.', [])
.option('-S, --api_secret <string>', 'Your application\'s api_secret.')
.option('-s, --since [string]', 'Defaults to null. Unix timestamp (or ISO datetime standard).', null)
.option('-u, --user <number|string>', 'Looks up a user by ID or username.')
.action(function (options) {
var Disqus = container.get('Disqus');
new Disqus(options).users.listPosts(options, container.get('util').printCliResult);
});
module.exports = users;
| jmdobry/disqus-node | lib/cli/users.js | JavaScript | apache-2.0 | 2,625 |
define([
"dojo/_base/declare",
"dijit/_WidgetBase",
"dijit/_TemplatedMixin",
"dijit/_WidgetsInTemplateMixin",
"dojo/topic",
"dojo/on",
"dojo/dom",
"dojo/dom-style",
"dojo/dom-class",
"dojo/dom-attr",
"dojo/_base/lang",
"dojo/_base/fx",
"dojo/text!./Wizard/templates/Wizard.html",
"dojo/i18n!./Wizard/nls/Strings",
"dijit/registry",
"dijit/form/Button",
"dijit/form/DropDownButton",
"dijit/DropDownMenu",
"dijit/MenuItem",
"dijit/form/Select",
"dijit/form/TextBox",
"dijit/form/RadioButton",
"dijit/form/CheckBox"
],
function (
declare, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin,
topic, on, dom, domStyle, domClass, domAttr, lang, fx,
template, i18n,
registry, Button, DropDownButton, DropDownMenu, MenuItem, Select, TextBox, RadioButton, CheckBox,
ProjectType, Route, MapSketch, Details, Cost, Score, Summary,
enums
) {
//anonymous function to load CSS files required for this module
(function () {
var css = [require.toUrl("./js/app/WorkflowManager/widgets/Wizard/css/Wizard.css")];
var head = document.getElementsByTagName("head").item(0),
link;
for (var i = 0, il = css.length; i < il; i++) {
link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = css[i].toString();
head.appendChild(link);
}
}());
return declare("app.Form", [_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
templateString: template,
widgetsInTemplate: true,
i18n: i18n,
currentStep: 1,
postCreate: function () {
this.inherited(arguments);
/*
this.stepItems = [
{ title: "Project type", widget: null },
{ title: "Route", widget: null },
{ title: "Map Sketch", widget: null },
{ title: "Details", widget: null },
{ title: "Cost", widget: null },
{ title: "Score", widget: null },
{ title: "Summary", widget: null }
];
// this object stores all input data from each step
this.projectData = [];
domStyle.set(this.saveDialogButton.domNode, "display", "none");
on(this.previousButton, "click", lang.hitch(this, this.GoToPreviousStep));
on(this.nextButton, "click", lang.hitch(this, this.GoToNextStep));
on(this.submitButton, "click", lang.hitch(this, this.SubmitProject));
// add step 1's content to form's body
this.GoToNthStep(0, 1);
// subcribe to topics
topic.subscribe("createNewProject/canceled", lang.hitch(this, function () {
this.hide();
}));
topic.subscribe("ProjectCard/StepChanged", lang.hitch(this, function (sender, args) {
this.currentStep = args.to;
this.GoToNthStep(args.from, args.to, args.status);
}));
*/
// show
//this.show();
},
startup: function () {
console.log("Wizard started");
},
show: function () {
domStyle.set(this.domNode, "display", "block");
//domStyle.set(this.ProjectCardContainer, { "opacity": 1, "left": "0" });
/*
fx.animateProperty({
node: this.domNode,
duration: 500,
properties: {
opacity: 1,
left: { end: 250, start: 300, units: "px" }
}
}).play();
*/
},
hide: function(){
fx.animateProperty({
node: this.domNode,
duration: 500,
properties: {
opacity: 0,
left: { end: 450, start: 400, units: "px" }
},
onEnd: lang.hitch(this, function () {
domStyle.set(this.domNode, "display", "none");
})
}).play();
},
// Page navigations
GoToPreviousStep: function () {
this.currentStep -= 1;
this.GoToNthStep(this.currentStep + 1, this.currentStep, "uncompleted");
},
GoToNextStep: function () {
var self = lang.hitch(this);
if (this.stepItems) {
var formValues = this.stepItems[this.currentStep - 1].widget.getFormValues();
// push into projectData
if (!this.projectData[this.currentStep - 1]) {
this.projectData.push({ stepName: this.stepItems[this.currentStep - 1].title, data: formValues });
} else {
this.projectData[this.currentStep - 1] = { stepName: this.stepItems[this.currentStep - 1].title, data: formValues };
}
console.log(this.projectData);
topic.publish("Form/StepCompleted", this, formValues);
}
},
GoToNthStep: function (from, to, status) {
// show/hide "previous" button
if (to > 1) {
domStyle.set(this.previousButton.domNode, "display", "block");
} else {
domStyle.set(this.previousButton.domNode, "display", "none");
}
// reposition the left arrow
domStyle.set(this.stepArrow, "top", 116 + 54 * (to - 1) + "px");
// update title
this.stepNumber.innerHTML = to;
this.stepTitle.innerHTML = this.stepItems[to - 1].title;
// update form body
this.updateFormBody(to);
topic.publish("Form/StepChanged", this, { from: from - 1, to: to - 1, status: status });
},
updateFormBody: function (n) {
//hide previous step's content
if (this.visibleStepWidget) {
domStyle.set(this.visibleStepWidget.domNode, "display", "none");
}
if (!this.stepItems[n - 1].widget) {
var step;
switch (this.stepItems[n - 1].title) { //TODO: put titles in an enum
case "Project type":
step = new ProjectType({mode: this.projectMode}, this.formBody);
break;
case "Route":
step = new Route({mode: this.projectMode, highwayImprovementType: this.mapMode}).placeAt(this.stepItems[n - 2].widget, "after");
break;
case "Map Sketch":
step = new MapSketch({ mode: this.projectMode }).placeAt(this.stepItems[n - 2].widget, "after");
this.switchToMapSketch();
break;
case "Details":
step = new Details({ mode: this.projectMode, detailsMode: this.detailsMode, improvementTypeId: this.improvementTypeId}).placeAt(this.stepItems[n - 2].widget, "after");
break;
case "Cost":
step = new Cost({ mode: this.projectMode }).placeAt(this.stepItems[n - 2].widget, "after");
this.switchToCost();
break;
case "Score":
step = new Score({ mode: this.projectMode, scoreMode: this.scoreMode }).placeAt(this.stepItems[n - 2].widget, "after");
this.switchToScore();
break;
case "Summary":
step = new Summary({ data: this.projectData }).placeAt(this.stepItems[n - 2].widget, "after");
this.switchToSummary();
break;
}
step.startup();
this.stepItems[n - 1].widget = step;
this.visibleStepWidget = step;
} else {
this.visibleStepWidget = this.stepItems[n - 1].widget;
domStyle.set(this.stepItems[n - 1].widget.domNode, "display", "");
// switch to map while in the "Map Sketch" step
if (n == 3) {
this.switchToMapSketch();
} else if (n == 5) {
this.switchToCost();
} else if (n == 6) {
this.switchToScore();
} else if (n == 7) {
this.stepItems[6].widget.toggleProjectMode(this.projectData);
this.switchToSummary();
}
}
},
});
}); | Esri/workflowmanager-viewer-js | js/app/WorkflowManager/widgets/Wizard.js | JavaScript | apache-2.0 | 9,484 |
"use strict";
function Cargar() {
var id = localStorage["a8d7f0a88sdfa7s0d8"];
var url = 'http://heylistenapi.azurewebsites.net/canciones/'+id;
$.ajax({
url: url,
type: 'GET',
contentType: "application/json;chartset=utf-8",
success: function(tracks){
$('#listaCanciones').empty();
var canciones = "";
$.each(tracks.canciones, function(i , track)
{
canciones += '<li class="estiloListas stroke" cancion="'+ track.id +'"><a href="'+ track.url +'">'+track.nombre+'</a></li><button cancion="'+ track.id +'" class="guardar btnGuardar">Eliminar</button>';
})
$('#listaCanciones').html(canciones);
},
});
}
function Eliminar(id) {
var url = 'http://heylistenapi.azurewebsites.net/canciones/'+id;
$.ajax({
url: url,
type: 'DELETE',
contentType: "application/json;chartset=utf-8",
statusCode: {
success: function () {
$('li[cancion='+id+'],button[cancion='+id+']').remove();
},
error: function () {
alertify.error("No se puedo eliminar");
}
}
});
$('li[cancion='+id+'],button[cancion='+id+']').remove();
alertify.success("Cancion eliminada");
}
$('ul').on('click', 'button', function(event) {
event.preventDefault();
var id = $(this).attr('cancion');
alertify.confirm("¿Estas seguro?", function (e) {
if (e) {
Eliminar(id);
}
});
});
$(document).ready(function() {
Cargar();
});
| LagunaJS/HeyListen | js/canciones.js | JavaScript | apache-2.0 | 1,413 |
var id_pool_8h =
[
[ "id_pool_add", "id-pool_8h.html#af725f2391fa8ca67cdb2b5d5b54683d7", null ],
[ "id_pool_alloc_id", "id-pool_8h.html#ad5e60f7e381aa6266beb23baf565e6d9", null ],
[ "id_pool_create", "id-pool_8h.html#abcfa9c69c041c0c91fdabd1de0468eed", null ],
[ "id_pool_destroy", "id-pool_8h.html#a82a5bb61a12de01a80a55abb7c612800", null ],
[ "id_pool_free_id", "id-pool_8h.html#a279f9894f83c3648fd38631bbfdbfb13", null ]
]; | vladn-ma/vladn-ovs-doc | doxygen/ovs_all/html/id-pool_8h.js | JavaScript | apache-2.0 | 446 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import PropTypes from 'prop-types';
import styled, { keyframes } from 'styled-components';
import { CSSTransition } from 'react-transition-group';
import { useRef } from '@googleforcreators/react';
const wrapperRotation = keyframes`
100% { transform: rotate(360deg) }
`;
const circleRotation = keyframes`
0% {
stroke-dasharray: 1, 200;
stroke-dashoffset: 0;
}
50% {
stroke-dasharray: 100, 200;
stroke-dashoffset: -15;
}
100% {
stroke-dasharray: 100, 200;
stroke-dashoffset: -125;
}
`;
const Wrapper = styled.div.attrs({
role: 'progressbar',
})`
width: ${({ size }) => `${size}px`};
height: ${({ size }) => `${size}px`};
animation: ${wrapperRotation} 1.4s linear infinite;
`;
const StyledSpinner = styled.svg`
display: block;
`;
const StyledCircle = styled.circle`
animation: ${circleRotation} 1.4s ease-in-out infinite;
stroke: ${({ theme }) => `${theme.colors.accent.secondary}`};
`;
function CircularProgress({ size, thickness }) {
const nodeRef = useRef();
return (
<CSSTransition nodeRef={nodeRef} in appear timeout={0}>
<Wrapper ref={nodeRef} size={size}>
<StyledSpinner viewBox={`${size / 2} ${size / 2} ${size} ${size}`}>
<StyledCircle
cx={size}
cy={size}
r={(size - thickness) / 2}
fill="none"
strokeWidth={thickness}
stroke="currentColor"
/>
</StyledSpinner>
</Wrapper>
</CSSTransition>
);
}
CircularProgress.propTypes = {
size: PropTypes.number,
thickness: PropTypes.number,
};
CircularProgress.defaultProps = {
size: 24,
thickness: 2,
};
export default CircularProgress;
| GoogleForCreators/web-stories-wp | packages/story-editor/src/components/circularProgress/index.js | JavaScript | apache-2.0 | 2,341 |
#! /usr/bin/env node
if (!process.env.TRAVIS_REPO_SLUG) {
process.exit(0);
}
const https = require('https');
const postData = `{\"body\": \"**Snapshot Tests**\\nReport: https://happo.io/a/27/report/${process.env.GIT_SHA}-android26\\nDiff: https://happo.io/a/27/compare/master-android26/${process.env.GIT_SHA}-android26\"}`
const options = {
hostname: 'api.github.com',
path: `/repos/${process.env.TRAVIS_REPO_SLUG}/issues/${process.env.TRAVIS_PULL_REQUEST}/comments`,
port: 443,
method: 'POST',
headers: {
Authorization: `token ${process.env.GITHUB_ACCESS_TOKEN}`,
'Content-Length': postData.length,
'User-Agent': 'Travis/1.6.8 (Mac OS X 10.9.2 like Darwin; Ruby 2.1.1; RubyGems 2.0.14) Faraday/0.8.9 Typhoeus/0.6.7.'
}
};
const req = https.request(options, res => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', d => {
process.stdout.write(d);
});
res.on('error', e => {
process.stderr.write(e);
})
})
req.write(postData);
req.end(); | airbnb/lottie-android | post_pr_comment.js | JavaScript | apache-2.0 | 1,036 |
define([
'../util',
'dojo/has',
'dojo/has!host-node?dojo/node!istanbul/lib/collector',
'dojo/has!host-node?dojo/node!istanbul/lib/report/text'
], function (util, has, Collector, Reporter) {
if (typeof console !== 'object') {
// IE<10 does not provide a global console object when Developer Tools is turned off
return {};
}
var hasGrouping = 'group' in console && 'groupEnd' in console;
var consoleReporter = {
'/suite/start': hasGrouping ? function (suite) {
console.group(suite.name);
} : null,
'/suite/end': function (suite) {
var numTests = suite.numTests,
numFailedTests = suite.numFailedTests;
console[numFailedTests ? 'warn' : 'info'](numTests - numFailedTests + '/' + numTests + ' tests passed');
hasGrouping && console.groupEnd(suite.name);
},
'/suite/error': function (suite) {
console.warn('SUITE ERROR: in ' + suite.id);
util.logError(suite.error);
if (suite.error.relatedTest) {
console.error('Related test: ' +
(hasGrouping ? suite.error.relatedTest.name : suite.error.relatedTest.id));
}
},
'/test/pass': function (test) {
console.log('PASS: ' + (hasGrouping ? test.name : test.id) + ' (' + test.timeElapsed + 'ms)');
},
'/test/fail': function (test) {
console.error('FAIL: ' + (hasGrouping ? test.name : test.id) + ' (' + test.timeElapsed + 'ms)');
util.logError(test.error);
}
};
if (has('host-node')) {
consoleReporter['/coverage'] = function (sessionId, coverage) {
var collector = new Collector();
collector.add(coverage);
// add a newline between test results and coverage results for prettier output
console.log('');
(new Reporter()).writeReport(collector, true);
};
}
return consoleReporter;
});
| timdown/log4javascript2 | node_modules/intern/lib/reporters/console.js | JavaScript | apache-2.0 | 1,729 |
'use strict';
var express = require('express'),
bodyParser = require('body-parser'),
expressSession = require('express-session'),
cookieParser = require('cookie-parser'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
path = require('path'),
routes = require('./routes'),
mainSocket = require('./sockets/mainSocket');
var Registry = require('./lib/registry').Registry;
var sessionsList = new Registry();
var playersList = new Registry();
// static
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'bower_components')));
// all environments
app.set('port', process.env.HTTP_PORT || 9003);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser());
app.use(cookieParser());
app.use(expressSession({secret:'some-secret_token=here'}));
app.get('/', routes.index);
app.get('/logon', function(req, res){
if (req.session.roomName) {
res.redirect('/');
} else {
res.render('logon');
}
});
app.post('/logon', function(req, res){
// set new session
req.session.roomName = req.body.roomName;
sessionsList.register(req.session.id, req.session.roomName);
// go to index
res.redirect('/');
});
// start socket
mainSocket.startSockets(io, sessionsList, playersList);
server.listen(process.env.HTTP_PORT);
| saitodisse/socket-io-server | app.js | JavaScript | apache-2.0 | 1,418 |
// Generated on 2013-07-16 using generator-angular 0.3.0
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// load all grunt tasks
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
// configurable paths
grunt.initConfig({
config : {
app: 'app',
build: 'build'
},
clean: {
dist: {
files: [
{
dot: true,
src: [
'.tmp',
'<%= config.build %>/*'
]
}
]
}
},
jasmine_node: {
//coverage: {
//},
specNameMatcher: "Spec", // load only specs containing specNameMatcher
projectRoot: ".",
teamcity: grunt.option('ci.build') && grunt.option('ci.build') === true,
requirejs: false,
forceExit: true,
jUnit: {
report: true,
savePath : "./build/reports/jasmine/",
useDotNotation: true,
consolidate: true
}
}
});
grunt.loadNpmTasks('grunt-jasmine-node');
//grunt.loadNpmTasks('grunt-jasmine-node-coverage');
grunt.registerTask('test', [
'jasmine_node',
]);
grunt.registerTask('build', [
'clean:dist',
'jasmine_node'
]);
grunt.registerTask('default', ['build']);
};
| stuforbes/substeps.js | Gruntfile.js | JavaScript | apache-2.0 | 1,434 |
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Node, Parser} from 'commonmark';
import Renderer from 'commonmark-react-renderer';
import PropTypes from 'prop-types';
import React, {PureComponent} from 'react';
import {Platform, Text, View} from 'react-native';
import Emoji from '@components/emoji';
import FormattedText from '@components/formatted_text';
import {blendColors, concatStyles, makeStyleSheetFromTheme} from '@utils/theme';
export default class MarkdownEmoji extends PureComponent {
static propTypes = {
baseTextStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.number, PropTypes.array]),
isEdited: PropTypes.bool,
isJumboEmoji: PropTypes.bool.isRequired,
theme: PropTypes.object.isRequired,
value: PropTypes.string.isRequired,
};
constructor(props) {
super(props);
this.parser = this.createParser();
this.renderer = this.createRenderer();
}
createParser = () => {
return new Parser();
};
createRenderer = () => {
return new Renderer({
renderers: {
editedIndicator: this.renderEditedIndicator,
emoji: this.renderEmoji,
paragraph: this.renderParagraph,
document: this.renderParagraph,
text: this.renderText,
hardbreak: this.renderNewLine,
},
});
};
computeTextStyle = (baseStyle) => {
if (!this.props.isJumboEmoji) {
return baseStyle;
}
const style = getStyleSheet(this.props.theme);
return concatStyles(baseStyle, style.jumboEmoji);
};
renderEmoji = ({context, emojiName, literal}) => {
return (
<Emoji
emojiName={emojiName}
literal={literal}
testID='markdown_emoji'
textStyle={this.computeTextStyle(this.props.baseTextStyle, context)}
/>
);
};
renderParagraph = ({children}) => {
const style = getStyleSheet(this.props.theme);
return (
<View style={style.block}><Text>{children}</Text></View>
);
};
renderText = ({context, literal}) => {
const style = this.computeTextStyle(this.props.baseTextStyle, context);
return <Text style={style}>{literal}</Text>;
};
renderNewLine = ({context}) => {
const style = this.computeTextStyle(this.props.baseTextStyle, context);
return <Text style={style}>{'\n'}</Text>;
};
renderEditedIndicator = ({context}) => {
let spacer = '';
if (context[0] === 'paragraph') {
spacer = ' ';
}
const style = getStyleSheet(this.props.theme);
const styles = [
this.props.baseTextStyle,
style.editedIndicatorText,
];
return (
<Text style={styles}>
{spacer}
<FormattedText
id='post_message_view.edited'
defaultMessage='(edited)'
/>
</Text>
);
};
render() {
const ast = this.parser.parse(this.props.value.replace(/\n*$/, ''));
if (this.props.isEdited) {
const editIndicatorNode = new Node('edited_indicator');
if (ast.lastChild && ['heading', 'paragraph'].includes(ast.lastChild.type)) {
ast.appendChild(editIndicatorNode);
} else {
const node = new Node('paragraph');
node.appendChild(editIndicatorNode);
ast.appendChild(node);
}
}
return this.renderer.render(ast);
}
}
const getStyleSheet = makeStyleSheetFromTheme((theme) => {
// Android has trouble giving text transparency depending on how it's nested,
// so we calculate the resulting colour manually
const editedOpacity = Platform.select({
ios: 0.3,
android: 1.0,
});
const editedColor = Platform.select({
ios: theme.centerChannelColor,
android: blendColors(theme.centerChannelBg, theme.centerChannelColor, 0.3),
});
return {
block: {
alignItems: 'flex-start',
flexDirection: 'row',
flexWrap: 'wrap',
},
editedIndicatorText: {
color: editedColor,
opacity: editedOpacity,
},
jumboEmoji: {
fontSize: 40,
lineHeight: 50,
},
};
});
| mattermost/mattermost-mobile | app/components/markdown/markdown_emoji/markdown_emoji.js | JavaScript | apache-2.0 | 4,582 |
const conf = require('@vue/cli-service/webpack.config.js');
conf.entry = {
tests: ['./test.js']
}
module.exports = conf;
| stryker-mutator/stryker | e2e/test/vue-cli-typescript-mocha/webpack.test.config.js | JavaScript | apache-2.0 | 123 |
var handlebars = require("../app/node_modules/handlebars");
document.getElementById('filetoload').onchange = function(){
return loadFileAsText();
}
function loadFileAsText() {
var file = document.getElementById("filetoload");
var fileToLoad = document.getElementById("filetoload").files[0];
var filename = document.getElementById('filename');
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var textFromFileLoaded = fileLoadedEvent.target.result;
codemirror.getDoc().setValue(textFromFileLoaded);
filename.value = file.value.split('/').pop().replace('.md','');
document.getElementById('editor').value = codemirror.getValue();
document.getElementById('output').innerHTML = marked(document.getElementById('editor').value);
};
fileReader.readAsText(fileToLoad, "UTF-8");
setTimeout(function(){word_counter();}, 500);
}
document.getElementById('saveMd').onclick = function(){
return saveFileAsText();
}
function saveFileAsText() {
var textToWrite = codemirror.getValue();
var textFileAsBlob = new Blob([textToWrite], {type:'text/x-markdown'});
var fileNameToSaveAs = document.getElementById('filename').value + '.md';
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.click();
}
document.getElementById('saveHTML').onclick = function(){
return saveFileAsHTML();
}
function saveFileAsHTML() {
var source = $("#templateHTML").html();
var template = handlebars.compile(source);
var context = {
title: document.getElementById('filename').value,
highlightcss: highlight_theme,
content: document.getElementById('output').innerHTML
};
var textToWrite = template(context);
var textFileAsBlob = new Blob([textToWrite], {type:'text/html'});
var fileNameToSaveAs = document.getElementById('filename').value + '.html';
var downloadHTML = document.createElement("a");
downloadHTML.download = fileNameToSaveAs;
downloadHTML.innerHTML = "Download File";
downloadHTML.href = window.URL.createObjectURL(textFileAsBlob);
downloadHTML.click();
}
function destroyClickedElement(event) {
document.body.removeChild(event.target);
}
| kurai021/MDWriter | app/assets/js/file.js | JavaScript | apache-2.0 | 2,319 |
/*global define*/
define(function() {
'use strict';
// The routes for the application. This module returns a function.
// `match` is match method of the Router
return function(match) {
match('', 'home#show');
match('browse(/:section)', 'browse#show');
match('download', 'download#show');
match('*anything', '404#show');
};
});
| danielefenix/chaplinjs-boilerplate | src/js/routes.js | JavaScript | apache-2.0 | 354 |
'use strict';
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('classActApp'));
beforeEach(module('socketMock'));
var MainCtrl,
scope,
$httpBackend;
// Initialize the controller and a mock scope
beforeEach(inject(function (_$httpBackend_, $controller, $rootScope) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('/api/classified')
.respond(['HTML5 Boilerplate', 'AngularJS', 'Karma', 'Express']);
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
it('should attach a list of classifieds to the scope', function () {
$httpBackend.flush();
expect(scope.classifiedsList.length).toBe(4);
});
});
| AdeelMufti/ClassAct | client/app/main/main.controller.spec.js | JavaScript | apache-2.0 | 761 |
var messageFactory = {
msjIniciarJuego: function(){
return JSON.stringify({
operacion: "iniciarJuego",
session: currentSession
});
},
msjConectar: function(datosLoginJugador){
return JSON.stringify({
operacion: "conectarJugador",
datosLoginJugador: datosLoginJugador
});
},
msjRobarCartas: function(cantidad){
return JSON.stringify({
operacion: "robarCartas",
cantidad: cantidad,
session: currentSession
});
}
} | tmilar/heroic-spirits | client/js/app/messageFactory.js | JavaScript | apache-2.0 | 474 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/base/randu' );
var isArray = require( '@stdlib/assert/is-array' );
var minabs = require( '@stdlib/math/base/special/minabs' );
var maxabs = require( '@stdlib/math/base/special/maxabs' );
var pkg = require( './../package.json' ).name;
var minmaxabs = require( './../lib' );
// MAIN //
bench( pkg, function benchmark( b ) {
var x;
var y;
var z;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
x = ( randu()*1000.0 ) - 500.0;
y = ( randu()*1000.0 ) - 500.0;
z = minmaxabs( x, y );
if ( z.length !== 2 ) {
b.fail( 'should have expected length' );
}
}
b.toc();
if ( !isArray( z ) ) {
b.fail( 'should return an array' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+'::memory_reuse', function benchmark( b ) {
var out;
var x;
var y;
var z;
var i;
out = [ 0.0, 0.0 ];
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
x = ( randu()*1000.0 ) - 500.0;
y = ( randu()*1000.0 ) - 500.0;
z = minmaxabs( out, x, y );
if ( z.length !== 2 ) {
b.fail( 'should have expected length' );
}
}
b.toc();
if ( !isArray( z ) ) {
b.fail( 'should return an array' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+'::minabs,maxabs', function benchmark( b ) {
var x;
var y;
var z;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
x = ( randu()*1000.0 ) - 500.0;
y = ( randu()*1000.0 ) - 500.0;
z = [ minabs( x, y ), maxabs( x, y ) ];
if ( z.length !== 2 ) {
b.fail( 'should have expected length' );
}
}
b.toc();
if ( !isArray( z ) ) {
b.fail( 'should return an array' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+'::minabs,maxabs,memory_reuse', function benchmark( b ) {
var x;
var y;
var z;
var i;
z = [ 0.0, 0.0 ];
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
x = ( randu()*1000.0 ) - 500.0;
y = ( randu()*1000.0 ) - 500.0;
z[ 0 ] = minabs( x, y );
z[ 1 ] = maxabs( x, y );
if ( z.length !== 2 ) {
b.fail( 'should have expected length' );
}
}
b.toc();
if ( !isArray( z ) ) {
b.fail( 'should return an array' );
}
b.pass( 'benchmark finished' );
b.end();
});
| stdlib-js/stdlib | lib/node_modules/@stdlib/math/base/special/minmaxabs/benchmark/benchmark.js | JavaScript | apache-2.0 | 2,836 |
sap.ui.define([ 'sap/ui/core/UIComponent' ], function(UIComponent) {
"use strict";
var Component = UIComponent.extend("sap.m.sample.FeedContent.Component", {
metadata : {
manifest: "json"
}
});
return Component;
}); | SAP/openui5 | src/sap.m/test/sap/m/demokit/sample/FeedContent/Component.js | JavaScript | apache-2.0 | 226 |
/**
* Created by Aleksey on 05.05.2016.
*/
/****************************************************
* @Discription ��������� �������
*
* - OnClick
* - OnMouseMove
* - OnMouseDown
* - OnDblClick
****************************************************/
function Events() {
var wsbone = wsBone;
var FocusElement = wsBone.FocusElement;
var widgets = wsbone.widgets;
///----------------------------------OnClick --------------------------------------///
this.OnClick = null;
mainConvas.addEventListener("click", function (event) {
for (var i = 0; i < widgets.length; i++) {
if (widgets[i].mouseClick(event)) {
if (FocusElement != null) {
FocusElement.focus = false;
}
FocusElement = wsbone.widgets[i];
widgets.splice(widgets.indexOf(FocusElement), 1);
widgets.push(FocusElement);
FocusElement.focus = true;
}
}
}, false);
this.mouseClick = function (event) {
var mPos = getMousePos(this.convas, event);
if (this.testHit(mPos.x, mPos.y)) {
if (this.OnClick != null)
this.OnClick(event);
return true;
}
};
///----------------------------------OnClick End-----------------------------------------///
///----------------------------------OnMouseMove ----------------------------------------///
this.OnMouseMove = null;
mainConvas.addEventListener("mousemove", function (event) {
for (var i = 0; i < widgets.length; i++) {
widgets[i].mouseMove(event);
}
});
this.mouseMove = function (event) {
var mPos = getMousePos(this.convas, event);
if (this.testHit(mPos.x, mPos.y)) {
if (this.OnMouseMove != null)
this.OnMouseMove(event);
return true;
}
};
///----------------------------------OnMouseMove End--------------------------------------///
///----------------------------------OnMouseDown------------------------------------------///
this.OnMouseDown = null;
mainConvas.addEventListener("mousedown", function (event) {
for (var i = 0; i < widgets.length; i++) {
widgets[i].mouseDown(event);
}
});
this.mouseDown = function (event) {
var mPos = getMousePos(this.convas, event);
if (this.testHit(mPos.x, mPos.y)) {
if (this.OnMouseDown != null)
this.OnMouseDown(event);
return true;
}
};
///----------------------------------OnMouseDown End--------------------------------------///
///----------------------------------mouseDblClick--------------------------------------///
this.OnDblClick = null;
mainConvas.addEventListener("dblclick", function (event) {
for (var i = 0; i < widgets.length; i++) {
widgets[i].mouseDblClick(event);
}
});
this.mouseDblClick = function (event) {
var mPos = getMousePos(this.convas, event);
if (this.testHit(mPos.x, mPos.y)) {
if (this.OnDblClick != null)
this.OnDblClick(event);
return true;
}
};
///----------------------------------mouseDblClick End--------------------------------------///
}
| akainq/wsBone | js/events.js | JavaScript | apache-2.0 | 3,413 |
var db = ( function() {
var api = {};
var conn;
// = Ti.Database.open('mytime');
// conn.close();
api.open = function() {
if (conn == null) {
conn = Ti.Database.open('alarm');
}
}
api.close = function() {
if (conn != null) {
conn.close();
conn = null;
}
}
api.addAlarm = function(title, date) {
conn.execute('INSERT INTO alarms("title", "dt") VALUES(?, ?)', title, date);
}
api.getAll = function() {
var resultSet = conn.execute("select * from alarms");
var results = [];
while (resultSet.isValidRow()) {
results.push({
title : resultSet.fieldByName('title'),
date : resultSet.fieldByName('dt'),
});
resultSet.next();
}
resultSet.close();
return results;
};
return api;
}());
| bennydtown/android-alert | Resources/database/database.js | JavaScript | apache-2.0 | 785 |
var map;
$(document).ready(function() {
map = new SuperMap.Map("mapDiv", { controls:[
new SuperMap.Control.ScaleLine(),
new SuperMap.Control.PanZoomBar({showSlider: true}),
new SuperMap.Control.MousePosition(),
//new SuperMap.Control.LayerSwitcher(),
new SuperMap.Control.OverviewMap({maximized: false}),
new SuperMap.Control.Navigation({
dragPanOptions:{
enableKinetic:true
}
})],
//scales: [1 / 13000000, 1 / 9750000, 1 / 6500000, 1 / 3250000, 1 / 1625000, 1 / 812500, 1 / 406250, 1 / 203125, 1 / 100000, 1 / 50000, 1 / 25000, 1 / 10000, 1 / 5000, 1 / 2000],
allOverlays: true
});
var baseLayer = new SuperMap.Layer.TiledDynamicRESTLayer(SuperMap.MapConfig.LayerNames.baseLayer, SuperMap.MapConfig.MapServer.baseLayerServer, {transparent: true, cacheEnabled: true}, {maxResolution:"auto"});
baseLayer.events.on({"layerInitialized": function(layer) {
map.addLayer(layer);
map.setCenter(new SuperMap.LonLat(113.53818, 22.26929), 4);
//map.zoomToMaxExtent();
}});
}); | lrs2016/nphitech | src/main/webapp/static/supermap/MapContainer.js | JavaScript | apache-2.0 | 1,041 |
(function(a){a.fn.datetimepicker.dates.az={days:"Bazar;Bazar ertəsi;Çərşənbə axşamı;Çərşənbə;Cümə axşamı;Cümə;Şənbə;Bazar".split(";"),daysShort:"B Be Ça Ç Ca C Ş B".split(" "),daysMin:"B Be Ça Ç Ca C Ş B".split(" "),months:"Yanvar Fevral Mart Aprel May İyun İyul Avqust Sentyabr Oktyabr Noyabr Dekabr".split(" "),monthsShort:"Yan Fev Mar Apr May İyun İyul Avq Sen Okt Noy Dek".split(" "),today:"Bugün",suffix:[],meridiem:[]}})(jQuery);
| phax/ph-oton | ph-oton-bootstrap3-uictrls/src/main/resources/bootstrap/datetimepicker/locales/bootstrap-datetimepicker.az.min.js | JavaScript | apache-2.0 | 469 |
'use strict';
export function vertexSource() {
const vsSource = `#version 300 es
in vec3 a_position;
uniform mat4 u_model_view_matrix;
uniform mat4 u_projection_matrix;
//varying
out vec3 v_w_position;
void main(void) {
v_w_position = a_position;
gl_Position = u_projection_matrix * u_model_view_matrix * vec4(a_position, 1.0);
}
`;
return vsSource;
} | shausoftware/SHAU_GL | src/main/js/shaders/glow_vertex_shader.js | JavaScript | apache-2.0 | 424 |
'use strict';
var clone = require('../../util/object').clone;
var format = require('../../util/string').format;
function factory (type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var DenseMatrix = type.DenseMatrix,
SparseMatrix = type.SparseMatrix;
/**
* Transpose a matrix. All values of the matrix are reflected over its
* main diagonal. Only two dimensional matrices are supported.
*
* Syntax:
*
* math.transpose(x)
*
* Examples:
*
* var 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
*/
var transpose = typed('transpose', {
'Array': function (x) {
// use dense matrix implementation
return transpose(matrix(x)).valueOf();
},
'Matrix': function (x) {
// matrix size
var size = x.size();
// result
var c;
// process dimensions
switch (size.length) {
case 1:
// vector
c = x.clone();
break;
case 2:
// rows and columns
var rows = size[0];
var 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);
}
});
var _denseTranspose = function (m, rows, columns) {
// matrix array
var data = m._data;
// transposed matrix data
var transposed = [];
var transposedRow;
// loop columns
for (var j = 0; j < columns; j++) {
// initialize row
transposedRow = transposed[j] = [];
// loop rows
for (var i = 0; i < rows; i++) {
// set data
transposedRow[i] = clone(data[i][j]);
}
}
// return matrix
return new DenseMatrix({
data: transposed,
size: [columns, rows],
datatype: m._datatype
});
};
var _sparseTranspose = function (m, rows, columns) {
// matrix arrays
var values = m._values;
var index = m._index;
var ptr = m._ptr;
// result matrices
var cvalues = values ? [] : undefined;
var cindex = [];
var cptr = [];
// row counts
var w = [];
for (var x = 0; x < rows; x++)
w[x] = 0;
// vars
var 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
var sum = 0;
// initialize cptr with the cummulative sum of row counts
for (var 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 (var k0 = ptr[j], k1 = ptr[j + 1], k = k0; k < k1; k++) {
// C values & index
var 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 new SparseMatrix({
values: cvalues,
index: cindex,
ptr: cptr,
size: [columns, rows],
datatype: m._datatype
});
};
return transpose;
}
exports.name = 'transpose';
exports.factory = factory;
| mikberg/mathjs | lib/function/matrix/transpose.js | JavaScript | apache-2.0 | 4,209 |
(function(a){var c=window.Modernizr,h=a.webshims,f=h.bugs,i=a('<form action="#" style="width: 1px; height: 1px; overflow: hidden;"><select name="b" required="" /><input type="date" required="" name="a" /><input type="submit" /></form>'),n=function(){if(i[0].querySelector)try{f.findRequired=!i[0].querySelector("select:required")}catch(a){f.findRequired=!1}};f.findRequired=!1;f.validationMessage=!1;f.valueAsNumberSet=!1;h.capturingEventPrevented=function(g){if(!g._isPolyfilled){var c=g.isDefaultPrevented,
h=g.preventDefault;g.preventDefault=function(){clearTimeout(a.data(g.target,g.type+"DefaultPrevented"));a.data(g.target,g.type+"DefaultPrevented",setTimeout(function(){a.removeData(g.target,g.type+"DefaultPrevented")},30));return h.apply(this,arguments)};g.isDefaultPrevented=function(){return!(!c.apply(this,arguments)&&!a.data(g.target,g.type+"DefaultPrevented"))};g._isPolyfilled=!0}};if(!c.formvalidation||f.bustedValidity)n();else if(h.capturingEvents(["input"]),h.capturingEvents(["invalid"],!0),
c.bugfreeformvalidation=!0,window.opera||a.browser.webkit||window.testGoodWithFix){var l=a("input",i).eq(0),p,r=function(a){h.loader.loadList(["dom-extend"]);h.ready("dom-extend",a)},j=function(g){var f=["form-extend","form-message","form-native-fix"];g&&(g.preventDefault(),g.stopImmediatePropagation());clearTimeout(p);setTimeout(function(){i&&(i.remove(),i=l=null)},9);if(!c.bugfreeformvalidation)h.addPolyfill("form-native-fix",{f:"forms",d:["form-extend"]}),h.modules["form-extend"].test=a.noop;h.isReady("form-number-date-api")&&
f.push("form-number-date-api");h.reTest(f);if(l)try{l.prop({disabled:!0,value:""}).prop("disabled",!1).is(":valid")&&r(function(){h.onNodeNamesPropertyModify(["input","textarea"],["disabled","readonly"],{set:function(c){!c&&this&&a.prop(this,"value",a.prop(this,"value"))}});h.onNodeNamesPropertyModify(["select"],["disabled","readonly"],{set:function(c){if(!c&&this)c=a(this).val(),(a("option:last-child",this)[0]||{}).selected=!0,a(this).val(c)}})})}catch(j){}(a.browser.opera||window.testGoodWithFix)&&
r(function(){var c=function(a){a.preventDefault()};["form","input","textarea","select"].forEach(function(g){var f=h.defineNodeNameProperty(g,"checkValidity",{prop:{value:function(){h.fromSubmit||a(this).bind("invalid.checkvalidity",c);h.fromCheckValidity=!0;var b=f.prop._supvalue.apply(this,arguments);h.fromSubmit||a(this).unbind("invalid.checkvalidity",c);h.fromCheckValidity=!1;return b}}})})})};i.appendTo("head");if(window.opera||window.testGoodWithFix){n();f.validationMessage=!l.prop("validationMessage");
if((c.inputtypes||{}).date){try{l.prop("valueAsNumber",0)}catch(q){}f.valueAsNumberSet="1970-01-01"!=l.prop("value")}l.prop("value","")}i.bind("submit",function(a){c.bugfreeformvalidation=!1;j(a)});p=setTimeout(function(){i&&i.triggerHandler("submit")},9);a("input, select",i).bind("invalid",j).filter('[type="submit"]').bind("click",function(a){a.stopImmediatePropagation()}).trigger("click")}})(jQuery);
jQuery.webshims.register("form-core",function(a,c,h,f,i,n){var l={radio:1},p={checkbox:1,radio:1},r=a([]),j=c.bugs,q=function(b){var b=a(b),d,c;d=r;if(l[b[0].type])c=b.prop("form"),d=(d=b[0].name)?c?a(c[d]):a(f.getElementsByName(d)).filter(function(){return!a.prop(this,"form")}):b,d=d.filter('[type="radio"]');return d},g=c.getContentValidationMessage=function(b,d,c){var e=a(b).data("errormessage")||b.getAttribute("x-moz-errormessage")||"";c&&e[c]&&(e=e[c]);"object"==typeof e&&(d=d||a.prop(b,"validity")||
{valid:1},d.valid||a.each(d,function(a,b){if(b&&"valid"!=a&&e[a])return e=e[a],!1}));if("object"==typeof e)e=e.defaultMessage;return e||""},s={number:1,range:1,date:1};a.extend(a.expr.filters,{"valid-element":function(b){return!(!a.prop(b,"willValidate")||!(a.prop(b,"validity")||{valid:1}).valid)},"invalid-element":function(b){return!(!a.prop(b,"willValidate")||(a.prop(b,"validity")||{valid:1}).valid)},"required-element":function(b){return!(!a.prop(b,"willValidate")||!a.prop(b,"required"))},"optional-element":function(b){return!!(a.prop(b,
"willValidate")&&!1===a.prop(b,"required"))},"in-range":function(b){if(!s[a.prop(b,"type")]||!a.prop(b,"willValidate"))return!1;b=a.prop(b,"validity");return!(!b||b.rangeOverflow||b.rangeUnderflow)},"out-of-range":function(b){if(!s[a.prop(b,"type")]||!a.prop(b,"willValidate"))return!1;b=a.prop(b,"validity");return!(!b||!b.rangeOverflow&&!b.rangeUnderflow)}});["valid","invalid","required","optional"].forEach(function(b){a.expr.filters[b]=a.expr.filters[b+"-element"]});a.expr.filters.focus=function(a){try{var d=
a.ownerDocument;return a===d.activeElement&&(!d.hasFocus||d.hasFocus())}catch(c){}return!1};var o=a.event.customEvent||{};(j.bustedValidity||j.findRequired||!Modernizr.bugfreeformvalidation)&&function(){var b=a.find,d=a.find.matchesSelector,c=/(\:valid|\:invalid|\:optional|\:required|\:in-range|\:out-of-range)(?=[\s\[\~\.\+\>\:\#*]|$)/ig,e=function(a){return a+"-element"};a.find=function(){var a=Array.prototype.slice,d=function(d){var k=arguments,k=a.call(k,1,k.length);k.unshift(d.replace(c,e));return b.apply(this,
k)},k;for(k in b)b.hasOwnProperty(k)&&(d[k]=b[k]);return d}();if(!Modernizr.prefixed||Modernizr.prefixed("matchesSelector",f.documentElement))a.find.matchesSelector=function(a,b){b=b.replace(c,e);return d.call(this,a,b)}}();var t=a.prop,u={selectedIndex:1,value:1,checked:1,disabled:1,readonly:1};a.prop=function(b,d,c){var e=t.apply(this,arguments);if(b&&"form"in b&&u[d]&&c!==i&&a(b).hasClass("form-ui-invalid")&&(a.prop(b,"validity")||{valid:1}).valid)a(b).getShadowElement().removeClass("form-ui-invalid"),
"checked"==d&&c&&q(b).not(b).removeClass("form-ui-invalid").removeAttr("aria-invalid");return e};var v=function(b,d){var c;a.each(b,function(b,f){if(f)return c="customError"==b?a.prop(d,"validationMessage"):b,!1});return c};a(f).bind(n.validityUIEvents||"focusout change refreshvalidityui",function(b){var d,c;if(b.target&&(d=a(b.target).getNativeElement()[0],"submit"!=d.type&&a.prop(d,"willValidate"))){c=a.data(d,"webshimsswitchvalidityclass");var e=function(){var c=a.prop(d,"validity"),e=a(d).getShadowElement(),
k,f,g,h;a(d).trigger("refreshCustomValidityRules");c.valid?e.hasClass("form-ui-valid")||(k="form-ui-valid",f="form-ui-invalid",h="changedvaliditystate",g="changedvalid",p[d.type]&&d.checked&&q(d).not(d).removeClass(f).addClass(k).removeAttr("aria-invalid"),a.removeData(d,"webshimsinvalidcause")):(c=v(c,d),a.data(d,"webshimsinvalidcause")!=c&&(a.data(d,"webshimsinvalidcause",c),h="changedvaliditystate"),e.hasClass("form-ui-invalid")||(k="form-ui-invalid",f="form-ui-valid",p[d.type]&&!d.checked&&q(d).not(d).removeClass(f).addClass(k),
g="changedinvalid"));k&&(e.addClass(k).removeClass(f),setTimeout(function(){a(d).trigger(g)},0));h&&setTimeout(function(){a(d).trigger(h)},0);a.removeData(b.target,"webshimsswitchvalidityclass")};c&&clearTimeout(c);"refreshvalidityui"==b.type?e():a.data(b.target,"webshimsswitchvalidityclass",setTimeout(e,9))}});o.changedvaliditystate=!0;o.refreshCustomValidityRules=!0;o.changedvalid=!0;o.changedinvalid=!0;o.refreshvalidityui=!0;c.triggerInlineForm=function(b,d){a(b).trigger(d)};c.modules["form-core"].getGroupElements=
q;j=function(){c.scrollRoot=a.browser.webkit||"BackCompat"==f.compatMode?a(f.body):a(f.documentElement)};j();c.ready("DOM",j);c.getRelOffset=function(b,d){var b=a(b),c=a(d).offset(),e;a.swap(a(b)[0],{visibility:"hidden",display:"inline-block",left:0,top:0},function(){e=b.offset()});c.top-=e.top;c.left-=e.left;return c};c.validityAlert=function(){var b=!a.browser.msie||7<parseInt(a.browser.version,10)?"span":"label",d,i=!1,e=!1,l,m={hideDelay:5E3,showFor:function(b,c,f,g){m._create();var b=a(b),j=
a(b).getShadowElement(),n=m.getOffsetFromBody(j);m.clear();g?this.hide():(this.getMessage(b,c),this.position(j,n),d.css({fontSize:b.css("fontSize"),fontFamily:b.css("fontFamily")}),this.show(),this.hideDelay&&(i=setTimeout(l,this.hideDelay)),a(h).bind("resize.validityalert orientationchange.validityalert emchange.validityalert",function(){clearTimeout(e);e=setTimeout(function(){m.position(j)},9)}));f||this.setFocus(j,n)},getOffsetFromBody:function(a){return c.getRelOffset(d,a)},setFocus:function(e,
g){var h=a(e).getShadowFocusElement(),i=c.scrollRoot.scrollTop(),j=(g||h.offset()).top-30,m;c.getID&&"label"==b&&d.attr("for",c.getID(h));i>j&&(c.scrollRoot.animate({scrollTop:j-5},{queue:!1,duration:Math.max(Math.min(600,1.5*(i-j)),80)}),m=!0);try{h[0].focus()}catch(n){}m&&(c.scrollRoot.scrollTop(i),setTimeout(function(){c.scrollRoot.scrollTop(i)},0));setTimeout(function(){a(f).bind("focusout.validityalert",l)},10)},getMessage:function(b,c){c||(c=g(b[0])||b.prop("validationMessage"));c?a("span.va-box",
d).text(c):this.hide()},position:function(b,c){c=c?a.extend({},c):m.getOffsetFromBody(b);c.top+=b.outerHeight();d.css(c)},show:function(){"none"===d.css("display")&&d.css({opacity:0}).show();d.addClass("va-visible").fadeTo(400,1)},hide:function(){d.removeClass("va-visible").fadeOut()},clear:function(){clearTimeout(!1);clearTimeout(i);a(f).unbind(".validityalert");a(h).unbind(".validityalert");d.stop().removeAttr("for")},_create:function(){if(!d)d=m.errorBubble=a("<"+b+' class="validity-alert-wrapper" role="alert"><span class="validity-alert"><span class="va-arrow"><span class="va-arrow-box"></span></span><span class="va-box"></span></span></'+
b+">").css({position:"absolute",display:"none"}),c.ready("DOM",function(){d.appendTo("body");a.fn.bgIframe&&a.browser.msie&&7>parseInt(a.browser.version,10)&&d.bgIframe()})}};l=a.proxy(m,"hide");return m}();(function(){var b,c=[],h;a(f).bind("invalid",function(e){if(!e.wrongWebkitInvalid){var g=a(e.target),i=g.getShadowElement();i.hasClass("form-ui-invalid")||(i.addClass("form-ui-invalid").removeClass("form-ui-valid"),setTimeout(function(){a(e.target).trigger("changedinvalid").trigger("changedvaliditystate")},
0));if(!b)b=a.Event("firstinvalid"),b.isInvalidUIPrevented=e.isDefaultPrevented,i=a.Event("firstinvalidsystem"),a(f).triggerHandler(i,{element:e.target,form:e.target.form,isInvalidUIPrevented:e.isDefaultPrevented}),g.trigger(b);b&&b.isDefaultPrevented()&&e.preventDefault();c.push(e.target);e.extraData="fix";clearTimeout(h);h=setTimeout(function(){var f={type:"lastinvalid",cancelable:!1,invalidlist:a(c)};b=!1;c=[];a(e.target).trigger(f,f)},9);i=g=null}})})();a.fn.getErrorMessage=function(){var b="",
c=this[0];c&&(b=g(c)||a.prop(c,"customValidationMessage")||a.prop(c,"validationMessage"));return b};n.replaceValidationUI&&c.ready("DOM forms",function(){a(f).bind("firstinvalid",function(b){b.isInvalidUIPrevented()||(b.preventDefault(),a.webshims.validityAlert.showFor(b.target,a(b.target).prop("customValidationMessage")))})})});
| mdia/OneCalendar | public/javascripts/lib/js-webshim/minified/shims/form-core.js | JavaScript | apache-2.0 | 10,679 |
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/home/home.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
// TODO: Initialize the page here.
WinJS.Utilities.query("a").listen("click", this.linkClickEventHandler, false);
},
unload: function () {
// TODO: Respond to navigations away from this page.
},
updateLayout: function (element, viewState, lastViewState) {
/// <param name="element" domElement="true" />
// TODO: Respond to changes in viewState.
},
linkClickEventHandler: function (eventInfo) {
eventInfo.preventDefault();
var link = eventInfo.target;
WinJS.Navigation.navigate(link.href);
},
});
})();
| DeveloperInfra/HelloWorld-Win8-UsingJQuery | src/HelloWorld-Win8-UsingJQuery/pages/home/home.js | JavaScript | apache-2.0 | 936 |
var connection;
var onMessageCallbacks = {};
var SIGNALING_SERVER = window.location.origin;
var role;
// onNewSession can be fired multiple times for same session
// to handle such issues; storing session-ids in an object
var sessions = { };
var iceServers = [];
iceServers.push({
url: 'stun:stun.google.com:19302'
});
iceServers.push({
url: 'stun:stun.anyfirewall.com:3478'
});
//iceServers.push({
// url: 'turn:turn.bistri.com:80',
// credential: 'homeo',
// username: 'homeo'
//});
//
//iceServers.push({
// url: 'turn:turn.anyfirewall.com:443?transport=tcp',
// credential: 'webrtc',
// username: 'webrtc'
//});
$(document).ready(function(){
if(typeof roomName !== 'undefined' && roomName !== '') {
if(typeof newRoom !== 'undefined' && newRoom === 'yes')
role = 'Room Moderator';
else role = 'Broadcaster';
connection = new RTCMultiConnection(roomName);
// this line disables xirsys servers
connection.getExternalIceServers = false;
connection.iceServers = [];// prevents all "predefined" ice servers
connection.iceServers = iceServers;
// www.rtcmulticonnection.org/docs/sdpConstraints/
connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
};
// easiest way to customize what you need!
connection.session = {
audio: true,
video: true,
data: true,
oneway: role === 'Anonymous Viewer'
};
connection.mediaConstraints.mandatory = {
minWidth: 320,
maxWidth: 640,
minHeight: 180,
maxHeight: 480,
minFrameRate: 24
};
connection.bandwidth = {
audio: 50,
video: 512,
data: 1638400,
screen: 300 // 300kbps
};
// overriding "openSignalingChannel" method
connection.openSignalingChannel = function (config) {
console.log('______ openSignalingChannel');
var channel = config.channel || this.channel;//channel is same sessionid
var sender = Math.round(Math.random() * 9999999999) + 9999999999;
io.connect(SIGNALING_SERVER).emit('new-channel', {
channel: channel,
sender: sender
});
var socket = io.connect(SIGNALING_SERVER +'/'+ channel);
socket.channel = channel;
socket.on('connect', function () {
console.log('socket.on(connect);');
if (config.callback) config.callback(socket);
});
socket.send = function (message) {
console.log('>>>Client is sending message: ', message);
socket.emit('message', {
sender: sender,
data: message
});
};
socket.on('message', config.onmessage);
};
connection.getDevices(function (devices) {
for(var device in devices){
device = devices[device];
console.log('device: ', device);
}
});
connection.onopen = function(e){
// e.userid
// e.extra
console.log('_____onOpen', e);
}
// on getting local or remote media stream
connection.onstream = function (e) {
console.log('_____onstream: ', e);
if (e.type === 'local' && role === 'Anonymous Viewer');
else {
var $divVideo = $('<div class="col-sm-4 col-md-4">'+
'<div class="wow fadeInLeft" data-wow-delay="0.2s">'+
'<div class="service-box">'+
// Video Div
'<div class="video" id= '+e.userid+'>'+
//Control div
'<div class="controls">'+
'<div class="form-group">'+
// '<button id="sdDisplay" class="btn btn-default">'+
// '<i class="fa fa-comment-o"></i>'+
// '</button>'+
// '<button id="hdDisplay" class="btn btn-default" >'+
// '<i class="fa fa-bell"></i>'+
// '</button>'+
'<button id="muteVideo" class="btn btn-default">'+
'<i class="fa fa-video-camera"></i>'+
'</button>'+
'<button id="muteAudio" class="btn btn-default">'+
'<i class="fa fa-microphone"></i>'+
'</button>'+
'</div>'+
'</div>'+
//Video Tag
'<video class="img img-responsive" autoplay width="640" height="480" src='+e.blobURL+' id='+e.streamid+' controls muted>'+
'</video>'+
' </div>'+
'</div>'+
'</div>'+
'</div>');
//var $divVideo = $('<div class="video" id= '+e.userid+' >' + '</div>');
/* var $eVideo = $('<video class="img img-responsive" autoplay width="480" height="320" controls muted></video>');
$eVideo.attr({'src': e.blobURL, 'id': e.streamid});
$divVideo.append($eVideo);
$divVideo.append($divControls);*/
$('#videoEle').append($divVideo);
if(e.type === 'local'){
$('<div class="hidden" id="poster">' +
'<i class="fa fa-pause"></i>'+
'</div>').appendTo('.video');
}
$( ".video" ).draggable({ containment: "#chatarea" });//allow video element can drag and drop
videoElementEvent();
$( ".video").resizable({ handles: "n, e, s, w",
aspectRatio: 4 / 3});
// alert('streamId ' + e.streamid + ' has just joined');
console.log('_______ add streamId: ', e.streamid);
}
if (e.type === 'remote' && role === 'Anonymous Viewer') {
// because "viewer" joined room as "oneway:true"
// initiator will NEVER share participants
// to manually ask for participants;
// call "askToShareParticipants" method.
connection.askToShareParticipants();
}
// if you're moderator
// if stream-type is 'remote'
// if target user is broadcaster!
if (connection.isInitiator && e.type === 'remote' && !e.session.oneway) {
// call "shareParticipants" to manually share participants with all connected users!
connection.shareParticipants({
dontShareWith: e.userid
});
}
};
connection.onaddstream = function(e){
console.log('__________onaddstream: ', e);
}
//======= when remote user closed the stream
connection.onstreamended = function(e){
$('#'+ e.streamid).parent().remove();
connection.peers[e.userid].drop(); //This method allows you drop call same like skype! It removes all media stream from both users' sides
console.log('____________streamId ' + e.streamid + ' has just left');
}
// "ondrop" is fired; if media-connection is droppped by other user
connection.ondrop = function(e) {
console.log('_____ondrop streamid: ', e);
};
// "onNewSession" is called as soon as signaling channel transmits session details
connection.onNewSession = function (session) {
console.log('______ onNewSession');
if (sessions[session.sessionid]) return; // if session is already passed over "onNewSession" event
sessions[session.sessionid] = session; // storing session in a global object
console.log('_____session: ', session);
if (role === 'Anonymous Viewer') {
session.join({ oneway: true });
}
if (role === 'Broadcaster') {
session.join();
}
// session.join(); // join session as it is!
// session.join({audio: true}); // join session while allowing only audio
// session.join({video: true}); // join session while allowing only video
// session.join({screen: true}); // join session while allowing only screen
// session.join({audio: true, video: true}); // join session while allowing both audio and video
// session.join({oneway: true}); // to join with no stream!
};
if (role === 'Room Moderator') {
var sessionDescription = connection.open(connection.channel);
}
else {
connection.join(connection.channel);
}
connection.onerror = function(err) {
console.log('_____Error: ', err);
};
connection.onlog = function(log){
var div = $('div');
div.html(JSON.stringify(log, null, ''));
$('#divLog').append(div);
}
//===== "onMediaError" event is fired if getUserMedia request is failed
connection.onMediaError = function(err){
console.log('_____onMediaError: ', err);
}
//====== send message
$(document).keypress(function(e) {
if(e.which == 13) {//check if enter was hit
var tbChat = $('#tbChat');
var message = tbChat.val();
if(tbChat.is(document.activeElement) && message !== ''){//check to see if tbChat is focus
var liElement = '<div class="popover left">' +
'<div class="arrow"></div>' +
'<div class="popover-content">' +
'<p>' + message + '</p>' +
'</div>' +
'</div>';
var eMessage =$('<div class="popover top popup">' +
'<div class="arrow"></div>' +
'<div class="popover-content">' +
'<p>' + message + '</p>' +
'</div>' +
'</div>');
$('#chatList').append(liElement);
if($( ".popup").is(":visible"))
{
$( ".popup").remove();
}
$('#'+ connection.userid).append(eMessage);
setTimeout(function() {
$( ".popup" ).removeAttr( "style" ).hide();
}, 6000 );
var scroll = function(div) {
var totalHeight = 0;
div.find('.popover').each(function(){
totalHeight += ($(this).outerHeight()+20);
});
div.scrollTop(totalHeight);
}
// call it:
scroll($('#chatList'));
/*$('#chatList').animate({
scrollTo: $('#chatList .popover:last-child')
}, 1000);*/
connection.send(message);
tbChat.val('');
}
}
});
//====== reveice message from peer
connection.onmessage = function(e){
var liElement = '<div class="popover right">' +
'<div class="arrow"></div>' +
'<div class="popover-content">' +
'<p>' + e.data + '</p>' +
'</div>' +
'</div>';
var eMessage =$('<div class="popover top popup">' +
'<div class="arrow"></div>' +
'<div class="popover-content">' +
'<p>' + e.data + '</p>' +
'</div>' +
'</div>');
$('#chatList').append(liElement);
var scroll = function(div) {
var totalHeight = 0;
div.find('.popover').each(function(){
totalHeight += ($(this).outerHeight()+20);
});
div.scrollTop(totalHeight);
}
// call it:
scroll($('#chatList'));
if($( ".popup").is(":visible"))
{
$( ".popup").remove();
}
$('#'+e.userid).append(eMessage);
setTimeout(function() {
$( ".popup" ).removeAttr( "style" ).hide();
}, 6000);
$("#chatContent").show();
document.getElementById('chatSoundEffect').play();
}
connection.onmute = function(e){
if(e.isVideo){
alert('Your friend has just muted video stream!');
}else{
alert('our friend has just muted audio stream!');
}
console.log('____e: ', e);
}
connection.onunmute = function(e){
if(e.isVideo){
$('#poster').addClass('hidden');
}else{
alert('unmute audio');
}
console.log('____e: ', e);
}
}// End if
}); | mrphanlinhuit/Vchat | public/js/RTCSignaling.js | JavaScript | apache-2.0 | 14,871 |
import React from "react";
import { Field, reduxForm } from "redux-form";
import * as _ from "lodash";
import ModalForm from "../components/ModalForm";
import { Term, GradeLevel } from "../molecules/AutoCompleteFor";
import { connect } from "react-redux";
import { createCourse } from "../redux/modules/course";
class CourseModal extends React.Component {
handleSubmit = data => {
data.terms = [data.termId];
return this.props.create(data);
};
render() {
return (
<ModalForm {...this.props} title="Course" onSubmitAsync={this.handleSubmit}>
<div className="field">
<label>Name</label>
<Field name="name" component="input" type="text" />
</div>
<div className="field">
<label>Grade Level</label>
<Field name="levelId" component={GradeLevel} />
</div>
<div className="field">
<label>Terms</label>
<Field name="termId" className="inline" component={Term} />
</div>
</ModalForm>
);
}
}
const mapStateToProps = (state, ownProps) => {
return {
terms: Object.values(state.entities.terms),
initialValues: {
...ownProps.initialValues,
...ownProps.termId,
..._.get(state.entities.courses, ownProps.courseId, {})
}
};
};
export default connect(
mapStateToProps,
dispatch => {
return {
create: course => {
course.terms = [{ termId: course.termId }];
dispatch(createCourse(course));
}
};
}
)(
reduxForm({
form: "course" // a unique identifier for this form
})(CourseModal)
);
| gogrademe/WebApp | src/js/modals/Course.js | JavaScript | apache-2.0 | 1,593 |
/** @ngInject */
export function ShoppingCartFactory ($rootScope, CollectionsApi, $q, lodash, RBAC) {
var state = null
var service = {
add: add,
reset: reset,
delete: deleteCart,
reload: reload,
count: count,
removeItem: removeItem,
submit: submit,
state: function () {
return state
},
allowed: allowed,
isDuplicate: isDuplicate
}
var persistence = {
// an array of items already in the basket
getItems: function () {
return CollectionsApi.query('service_orders/cart/service_requests', {
expand: 'resources'
})
.catch(function (err) {
// 404 means cart doesn't exist yet, we can simply create it
if (err.status !== 404) {
return $q.reject(err)
}
return CollectionsApi.post('service_orders', null, {}, { state: 'cart' })
.then(function () {
// we just care it's been successfully created
return {}
})
})
.then(function (response) {
return response.resources || []
})
},
// order the cart
orderCart: function () {
return CollectionsApi.post('service_orders', 'cart', null, {
action: 'order'
})
},
// clear the cart
clearCart: function () {
return CollectionsApi.post('service_orders', 'cart', null, {
action: 'clear'
})
},
// add a thingy to the cart
addItem: function (request) {
return CollectionsApi.post('service_orders/cart/service_requests', null, null, {
action: 'add',
resources: [ request ]
})
.then(function (response) {
// handle failure
if (response.results[0].success === false) {
return $q.reject(response.results[0].message)
}
return response.results[0]
})
},
// remove a thingy from the cart
removeItem: function (requestId) {
return new Promise((resolve, reject) => {
CollectionsApi.post('service_orders/cart/service_requests', null, null, {
action: 'remove',
resources: [ { id: requestId } ]
})
.then(function (response) {
// handle failure
if (response.results[0].success === false) {
reject(response.results[0].message)
}
resolve(response.results[0])
})
})
}
}
doReset()
return service
function add (item) {
return persistence.addItem(item.data)
.then(function (response) {
var newItem = {
id: response.service_request_id,
description: item.description,
// for duplicate detection
data: clientToCommon(item.data)
}
state.items.push(newItem)
dedup()
notify()
return newItem
})
}
function deleteCart () {
persistence.getItems()
return CollectionsApi.delete('service_orders', 'cart', null)
}
function reload () {
return persistence.getItems()
.then(function (items) {
state = {
items: items.map(function (o) {
return {
id: o.id,
description: o.description,
data: apiToCommon(o.options)
}
})
}
dedup()
notify()
})
}
function doReset () {
state = {
items: []
}
}
function reset () {
return persistence.clearCart()
.then(reload)
}
function removeItem (item) {
return persistence.removeItem(item.id)
.then(function () {
state.items = lodash.filter(state.items, function (i) {
return i.id !== item.id
})
dedup()
notify()
})
}
function submit () {
return persistence.orderCart()
.then(reload)
}
function count () {
return state.items.length
}
function notify () {
$rootScope.$broadcast('shoppingCartUpdated')
}
function allowed () {
return RBAC.has(RBAC.FEATURES.SHOPPING_CART.ORDER)
}
function dedup () {
var potential = []
state.items.forEach(function (item) {
if (!item.data) {
return
}
item.duplicate = []
potential.push(item)
})
for (var i = 0; i < potential.length - 1; i++) {
for (var j = i + 1; j < potential.length; j++) {
var a = potential[i]
var b = potential[j]
if (angular.equals(a.data, b.data)) {
a.duplicate.push(b.id)
b.duplicate.push(a.id)
}
}
}
potential.forEach(function (item) {
if (item.duplicate && !item.duplicate.length) {
delete item.duplicate
}
})
}
function isDuplicate (item) {
var data = clientToCommon(item)
for (var i in state.items) {
if (!state.items[i].data) {
continue
}
if (angular.equals(data, state.items[i].data)) {
return true
}
}
return false
}
// convert options value from the API to the format used when sending - for deduplication across reloads
function apiToCommon (options) {
var data = { 'service_template_href': '/api/service_templates/' + options.src_id }
lodash.each(options.dialog, function (value, key) {
data[ key.replace(/^dialog_/, '') ] = value
})
return data
}
// remove falsy fields from data, to achieve compatibility with data received back from the API
function clientToCommon (data) {
data = angular.copy(data)
lodash.each(data, function (value, key) {
if (!value) {
delete data[key]
}
})
return data
}
}
| AllenBW/manageiq-ui-service | client/app/core/shopping-cart.service.js | JavaScript | apache-2.0 | 5,500 |
/**
* @license Copyright 2016 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
const {version: lighthouseVersion} = require('../../package.json');
const NO_THROTTLING_METRICS = {
latency: 0,
downloadThroughput: 0,
uploadThroughput: 0,
offline: false,
};
const NO_CPU_THROTTLE_METRICS = {
rate: 1,
};
/**
* @param {string} userAgent
* @param {LH.Config.Settings['formFactor']} formFactor
* @return {LH.Crdp.Emulation.SetUserAgentOverrideRequest['userAgentMetadata']}
*/
function parseUseragentIntoMetadata(userAgent, formFactor) {
const match = userAgent.match(/Chrome\/([\d.]+)/); // eg 'Chrome/(71.0.3577.0)'
const fullVersion = match?.[1] || '99.0.1234.0';
const [version] = fullVersion.split('.', 1);
const brands = [
{brand: 'Chromium', version},
{brand: 'Google Chrome', version},
{brand: 'Lighthouse', version: lighthouseVersion},
];
const motoG4Details = {
platform: 'Android',
platformVersion: '6.0',
architecture: '',
model: 'Moto G4',
};
const macDesktopDetails = {
platform: 'macOS',
platformVersion: '10.15.7',
architecture: 'x86',
model: '',
};
const mobile = formFactor === 'mobile';
return {
brands,
fullVersion,
// Since config users can supply a custom useragent, they likely are emulating something
// other than Moto G4 and MacOS Desktop.
// TODO: Determine how to thoughtfully expose this metadata/client-hints configurability.
...(mobile ? motoG4Details : macDesktopDetails),
mobile,
};
}
/**
* @param {LH.Gatherer.FRProtocolSession} session
* @param {LH.Config.Settings} settings
* @return {Promise<void>}
*/
async function emulate(session, settings) {
if (settings.emulatedUserAgent !== false) {
const userAgent = /** @type {string} */ (settings.emulatedUserAgent);
await session.sendCommand('Network.setUserAgentOverride', {
userAgent,
userAgentMetadata: parseUseragentIntoMetadata(userAgent, settings.formFactor),
});
}
// See devtools-entry for one usecase for disabling screenEmulation
if (settings.screenEmulation.disabled !== true) {
const {width, height, deviceScaleFactor, mobile} = settings.screenEmulation;
const params = {width, height, deviceScaleFactor, mobile};
await session.sendCommand('Emulation.setDeviceMetricsOverride', params);
await session.sendCommand('Emulation.setTouchEmulationEnabled', {
enabled: params.mobile,
});
}
}
/**
* Sets the throttling options specified in config settings, clearing existing network throttling if
* throttlingMethod is not `devtools` (but not CPU throttling, suspected requirement of WPT-compat).
*
* @param {LH.Gatherer.FRProtocolSession} session
* @param {LH.Config.Settings} settings
* @return {Promise<void>}
*/
async function throttle(session, settings) {
if (settings.throttlingMethod !== 'devtools') return clearNetworkThrottling(session);
await Promise.all([
enableNetworkThrottling(session, settings.throttling),
enableCPUThrottling(session, settings.throttling),
]);
}
/**
* @param {LH.Gatherer.FRProtocolSession} session
* @return {Promise<void>}
*/
async function clearThrottling(session) {
await Promise.all([clearNetworkThrottling(session), clearCPUThrottling(session)]);
}
/**
* @param {LH.Gatherer.FRProtocolSession} session
* @param {Required<LH.ThrottlingSettings>} throttlingSettings
* @return {Promise<void>}
*/
function enableNetworkThrottling(session, throttlingSettings) {
/** @type {LH.Crdp.Network.EmulateNetworkConditionsRequest} */
const conditions = {
offline: false,
latency: throttlingSettings.requestLatencyMs || 0,
downloadThroughput: throttlingSettings.downloadThroughputKbps || 0,
uploadThroughput: throttlingSettings.uploadThroughputKbps || 0,
};
// DevTools expects throughput in bytes per second rather than kbps
conditions.downloadThroughput = Math.floor(conditions.downloadThroughput * 1024 / 8);
conditions.uploadThroughput = Math.floor(conditions.uploadThroughput * 1024 / 8);
return session.sendCommand('Network.emulateNetworkConditions', conditions);
}
/**
* @param {LH.Gatherer.FRProtocolSession} session
* @return {Promise<void>}
*/
function clearNetworkThrottling(session) {
return session.sendCommand('Network.emulateNetworkConditions', NO_THROTTLING_METRICS);
}
/**
* @param {LH.Gatherer.FRProtocolSession} session
* @param {Required<LH.ThrottlingSettings>} throttlingSettings
* @return {Promise<void>}
*/
function enableCPUThrottling(session, throttlingSettings) {
const rate = throttlingSettings.cpuSlowdownMultiplier;
return session.sendCommand('Emulation.setCPUThrottlingRate', {rate});
}
/**
* @param {LH.Gatherer.FRProtocolSession} session
* @return {Promise<void>}
*/
function clearCPUThrottling(session) {
return session.sendCommand('Emulation.setCPUThrottlingRate', NO_CPU_THROTTLE_METRICS);
}
module.exports = {
emulate,
throttle,
clearThrottling,
enableNetworkThrottling,
clearNetworkThrottling,
enableCPUThrottling,
clearCPUThrottling,
};
| GoogleChrome/lighthouse | lighthouse-core/lib/emulation.js | JavaScript | apache-2.0 | 5,597 |
/**
* 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 stringUtils = require('utils/string_utils');
/**
* Remove spaces at beginning and ending of line.
* @example
* var str = " I'm a string "
* str.trim() // return "I'm a string"
* @method trim
* @return {string}
*/
String.prototype.trim = function () {
return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};
/**
* Determines whether string end within another string.
*
* @method endsWith
* @param suffix {string} substring for search
* @return {boolean}
*/
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
/**
* Determines whether string start within another string.
*
* @method startsWith
* @param prefix {string} substring for search
* @return {boolean}
*/
String.prototype.startsWith = function (prefix){
return this.indexOf(prefix) == 0;
};
/**
* Determines whether string founded within another string.
*
* @method contains
* @param substring {string} substring for search
* @return {boolean}
*/
String.prototype.contains = function(substring) {
return this.indexOf(substring) != -1;
};
/**
* Capitalize the first letter of string.
* @method capitalize
* @return {string}
*/
String.prototype.capitalize = function () {
return this.charAt(0).toUpperCase() + this.slice(1);
};
/**
* Capitalize the first letter of string.
* And set to lowercase other part of string
* @method toCapital
* @return {string}
*/
String.prototype.toCapital = function () {
return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
};
/**
* Finds the value in an object where this string is a key.
* Optionally, the index of the key can be provided where the
* value of the nth key in the hierarchy is returned.
*
* Example:
* var tofind = 'smart';
* var person = {'name': 'Bob Bob', 'smart': 'no', 'age': '28', 'personality': {'smart': 'yes', 'funny': 'yes', 'emotion': 'happy'} };
* tofind.findIn(person); // 'no'
* tofind.findIn(person, 0); // 'no'
* tofind.findIn(person, 1); // 'yes'
* tofind.findIn(person, 2); // null
*
* @method findIn
* @param multi {object}
* @param index {number} Occurrence count of this key
* @return {*} Value of key at given index
*/
String.prototype.findIn = function(multi, index, _foundValues) {
if (!index) {
index = 0;
}
if (!_foundValues) {
_foundValues = [];
}
multi = multi || '';
var value = null;
var str = this.valueOf();
if (typeof multi == 'object') {
for ( var key in multi) {
if (value != null) {
break;
}
if (key == str) {
_foundValues.push(multi[key]);
}
if (_foundValues.length - 1 == index) {
// Found the value
return _foundValues[index];
}
if (typeof multi[key] == 'object') {
value = value || this.findIn(multi[key], index, _foundValues);
}
}
}
return value;
};
/**
* Replace {i} with argument. where i is number of argument to replace with.
* @example
* var str = "{0} world{1}";
* str.format("Hello", "!") // return "Hello world!"
*
* @method format
* @return {string}
*/
String.prototype.format = function () {
var args = arguments;
return this.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined' ? args[number] : match;
});
};
/**
* Wrap words in string within template.
*
* @method highlight
* @param {string[]} words - words to wrap
* @param {string} [highlightTemplate="<b>{0}</b>"] - template for wrapping
* @return {string}
*/
String.prototype.highlight = function (words, highlightTemplate) {
var self = this;
highlightTemplate = highlightTemplate ? highlightTemplate : "<b>{0}</b>";
words.forEach(function (word) {
var searchRegExp = new RegExp("\\b" + word + "\\b", "gi");
self = self.replace(searchRegExp, function (found) {
return highlightTemplate.format(found);
});
});
return self;
};
/**
* Convert time in milliseconds to object contained days, hours and minutes.
* @typedef ConvertedTime
* @type {Object}
* @property {number} d - days
* @property {number} h - hours
* @property {string} m - minutes
* @example
* var time = 1000000000;
* time.toDaysHoursMinutes() // {d: 11, h: 13, m: "46.67"}
*
* @method toDaysHoursMinutes
* @return {object}
*/
Number.prototype.toDaysHoursMinutes = function () {
var formatted = {},
dateDiff = this,
secK = 1000, //ms
minK = 60 * secK, // sec
hourK = 60 * minK, // sec
dayK = 24 * hourK;
dateDiff = parseInt(dateDiff);
formatted.d = Math.floor(dateDiff / dayK);
dateDiff -= formatted.d * dayK;
formatted.h = Math.floor(dateDiff / hourK);
dateDiff -= formatted.h * hourK;
formatted.m = (dateDiff / minK).toFixed(2);
return formatted;
};
/**
Sort an array by the key specified in the argument.
Handle only native js objects as element of array, not the Ember's object.
Can be used as alternative to sortProperty method of Ember library
in order to speed up executing on large data volumes
@method sortBy
@param {String} path name(s) to sort on
@return {Array} The sorted array.
*/
Array.prototype.sortPropertyLight = function (path) {
var realPath = (typeof path === "string") ? path.split('.') : [];
this.sort(function (a, b) {
var aProperty = a;
var bProperty = b;
realPath.forEach(function (key) {
aProperty = aProperty[key];
bProperty = bProperty[key];
});
if (aProperty > bProperty) return 1;
if (aProperty < bProperty) return -1;
return 0;
});
return this;
};
/** @namespace Em **/
Em.CoreObject.reopen({
t:function (key, attrs) {
return Em.I18n.t(key, attrs)
}
});
Em.TextArea.reopen(Em.I18n.TranslateableAttributes);
/** @namespace Em.Handlebars **/
Em.Handlebars.registerHelper('log', function (variable) {
console.log(variable);
});
Em.Handlebars.registerHelper('warn', function (variable) {
console.warn(variable);
});
Em.Handlebars.registerHelper('highlight', function (property, words, fn) {
var context = (fn.contexts && fn.contexts[0]) || this;
property = Em.Handlebars.getPath(context, property, fn);
words = words.split(";");
// if (highlightTemplate == undefined) {
var highlightTemplate = "<b>{0}</b>";
// }
words.forEach(function (word) {
var searchRegExp = new RegExp("\\b" + word + "\\b", "gi");
property = property.replace(searchRegExp, function (found) {
return highlightTemplate.format(found);
});
});
return new Em.Handlebars.SafeString(property);
});
/**
* @namespace App
*/
App = require('app');
/**
* Certain variables can have JSON in string
* format, or in JSON format itself.
*
* @memberof App
* @function parseJson
* @param {string|object}
* @return {object}
*/
App.parseJSON = function (value) {
if (typeof value == "string") {
return jQuery.parseJSON(value);
}
return value;
};
/**
* Check for empty <code>Object</code>, built in Em.isEmpty()
* doesn't support <code>Object</code> type
*
* @memberof App
* @method isEmptyObject
* @param obj {Object}
* @return {Boolean}
*/
App.isEmptyObject = function(obj) {
var empty = true;
for (var prop in obj) { if (obj.hasOwnProperty(prop)) {empty = false; break;} }
return empty;
}
/**
* Convert object under_score keys to camelCase
*
* @param {Object} object
* @return {Object}
**/
App.keysUnderscoreToCamelCase = function(object) {
var tmp = {};
for (var key in object) {
tmp[stringUtils.underScoreToCamelCase(key)] = object[key];
}
return tmp;
};
/**
* Convert dotted keys to camelcase
*
* @param {Object} object
* @return {Object}
**/
App.keysDottedToCamelCase = function(object) {
var tmp = {};
for (var key in object) {
tmp[key.split('.').reduce(function(p, c) { return p + c.capitalize()})] = object[key];
}
return tmp;
};
/**
* Returns object with defined keys only.
*
* @memberof App
* @method permit
* @param {Object} obj - input object
* @param {String|Array} keys - allowed keys
* @return {Object}
*/
App.permit = function(obj, keys) {
var result = {};
if (typeof obj !== 'object' || App.isEmptyObject(obj)) return result;
if (typeof keys == 'string') keys = Array(keys);
keys.forEach(function(key) {
if (obj.hasOwnProperty(key))
result[key] = obj[key];
});
return result;
};
/**
*
* @namespace App
* @namespace App.format
*/
App.format = {
/**
* @memberof App.format
* @type {object}
* @property components
*/
components: {
'API': 'API',
'DECOMMISSION_DATANODE': 'Update Exclude File',
'DRPC': 'DRPC',
'FLUME_HANDLER': 'Flume',
'GLUSTERFS': 'GLUSTERFS',
'HBASE': 'HBase',
'HBASE_REGIONSERVER': 'RegionServer',
'HCAT': 'HCat Client',
'HDFS': 'HDFS',
'HISTORYSERVER': 'History Server',
'HIVE_SERVER': 'HiveServer2',
'JCE': 'JCE',
'MAPREDUCE': 'MapReduce',
'MAPREDUCE2': 'MapReduce2',
'MYSQL': 'MySQL',
'REST': 'REST',
'SECONDARY_NAMENODE': 'SNameNode',
'STORM_REST_API': 'Storm REST API Server',
'WEBHCAT': 'WebHCat',
'YARN': 'YARN',
'UI': 'UI',
'ZKFC': 'ZKFailoverController',
'ZOOKEEPER': 'ZooKeeper',
'ZOOKEEPER_QUORUM_SERVICE_CHECK': 'ZK Quorum Service Check'
},
/**
* @memberof App.format
* @property command
* @type {object}
*/
command: {
'INSTALL': 'Install',
'UNINSTALL': 'Uninstall',
'START': 'Start',
'STOP': 'Stop',
'EXECUTE': 'Execute',
'ABORT': 'Abort',
'UPGRADE': 'Upgrade',
'RESTART': 'Restart',
'SERVICE_CHECK': 'Check',
'Excluded:': 'Decommission:',
'Included:': 'Recommission:'
},
/**
* convert role to readable string
*
* @memberof App.format
* @method role
* @param {string} role
* return {string}
*/
role:function (role) {
var result;
var models = [App.StackService, App.StackServiceComponent];
models.forEach(function(model){
var instance = model.find().findProperty('id',role);
if (instance) {
result = instance.get('displayName');
}
},this);
if (!result) {
result = this.normalizeName(role);
}
return result;
},
/**
* Try to format non predefined names to readable format.
*
* @method normalizeName
* @param name {String} - name to format
* @return {String}
*/
normalizeName: function(name) {
if (!name || typeof name != 'string') return '';
if (this.components[name]) return this.components[name];
name = name.toLowerCase();
var suffixNoSpaces = ['node','tracker','manager'];
var suffixRegExp = new RegExp('(\\w+)(' + suffixNoSpaces.join('|') + ')', 'gi');
if (/_/g.test(name)) {
name = name.split('_').map(function(singleName) {
return this.normalizeName(singleName.toUpperCase());
}, this).join(' ');
} else if(suffixRegExp.test(name)) {
suffixRegExp.lastIndex = 0;
var matches = suffixRegExp.exec(name);
name = matches[1].capitalize() + matches[2].capitalize();
}
return name.capitalize();
},
/**
* convert command_detail to readable string, show the string for all tasks name
*
* @memberof App.format
* @method commandDetail
* @param {string} command_detail
* @param {string} request_inputs
* @return {string}
*/
commandDetail: function (command_detail, request_inputs) {
var detailArr = command_detail.split(' ');
var self = this;
var result = '';
detailArr.forEach( function(item) {
// if the item has the pattern SERVICE/COMPONENT, drop the SERVICE part
if (item.contains('/')) {
item = item.split('/')[1];
}
if (item == 'DECOMMISSION,') {
// ignore text 'DECOMMISSION,'( command came from 'excluded/included'), here get the component name from request_inputs
item = (jQuery.parseJSON(request_inputs)) ? jQuery.parseJSON(request_inputs).slave_type : '';
}
if (self.components[item]) {
result = result + ' ' + self.components[item];
} else if (self.command[item]) {
result = result + ' ' + self.command[item];
} else {
result = result + ' ' + self.role(item);
}
});
if (result.indexOf('Decommission:') > -1 || result.indexOf('Recommission:') > -1) {
// for Decommission command, make sure the hostname is in lower case
result = result.split(':')[0] + ': ' + result.split(':')[1].toLowerCase();
}
if (result === ' Nagios Update Ignore Actionexecute') {
result = Em.I18n.t('common.maintenance.task');
}
if (result === ' Rebalancehdfs NameNode') {
result = Em.I18n.t('services.service.actions.run.rebalanceHdfsNodes.title');
}
return result;
},
/**
* Convert uppercase status name to lowercase.
* <br>
* <br>PENDING - Not queued yet for a host
* <br>QUEUED - Queued for a host
* <br>IN_PROGRESS - Host reported it is working
* <br>COMPLETED - Host reported success
* <br>FAILED - Failed
* <br>TIMEDOUT - Host did not respond in time
* <br>ABORTED - Operation was abandoned
*
* @memberof App.format
* @method taskStatus
* @param {string} _taskStatus
* @return {string}
*
*/
taskStatus:function (_taskStatus) {
return _taskStatus.toLowerCase();
}
};
/**
* wrapper to bootstrap popover
* fix issue when popover stuck on view routing
*
* @memberof App
* @method popover
* @param {DOMElement} self
* @param {object} options
*/
App.popover = function (self, options) {
self.popover(options);
self.on("remove", function () {
$(this).trigger('mouseleave');
});
};
/**
* wrapper to bootstrap tooltip
* fix issue when tooltip stuck on view routing
* @memberof App
* @method tooltip
* @param {DOMElement} self
* @param {object} options
*/
App.tooltip = function (self, options) {
self.tooltip(options);
/* istanbul ignore next */
self.on("remove", function () {
$(this).trigger('mouseleave');
});
};
/**
* wrapper to Date().getTime()
* fix issue when client clock and server clock not sync
*
* @memberof App
* @method dateTime
* @return {Number} timeStamp of current server clock
*/
App.dateTime = function() {
return new Date().getTime() + App.clockDistance;
};
/**
* Helper function for bound property helper registration
* @memberof App
* @method registerBoundHelper
* @param name {String} name of helper
* @param view {Em.View} view
*/
App.registerBoundHelper = function(name, view) {
Em.Handlebars.registerHelper(name, function(property, options) {
options.hash.contentBinding = property;
return Em.Handlebars.helpers.view.call(this, view, options);
});
};
/*
* Return singular or plural word based on Em.I18n, view|controller context property key.
*
* Example: {{pluralize hostsCount singular="t:host" plural="t:hosts"}}
* {{pluralize hostsCount singular="@view.hostName"}}
*/
App.registerBoundHelper('pluralize', Em.View.extend({
tagName: 'span',
template: Em.Handlebars.compile('{{view.wordOut}}'),
wordOut: function() {
var count, singular, plural;
count = this.get('content');
singular = this.get('singular');
plural = this.get('plural');
return this.getWord(count, singular, plural);
}.property('content'),
/**
* Get computed word.
*
* @param {Number} count
* @param {String} singular
* @param {String} [plural]
* @return {String}
* @method getWord
*/
getWord: function(count, singular, plural) {
singular = this.parseValue(singular);
// if plural not passed
if (!plural) plural = singular + 's';
else plural = this.parseValue(plural);
if (singular && plural) {
if (count > 1) {
return plural;
} else {
return singular;
}
}
return '';
},
/**
* Detect and return value from its instance.
*
* @param {String} value
* @return {*}
* @method parseValue
**/
parseValue: function(value) {
switch (value[0]) {
case '@':
value = this.getViewPropertyValue(value);
break;
case 't':
value = this.tDetect(value);
break;
default:
break;
}
return value;
},
/*
* Detect for Em.I18n.t reference call
* @params word {String}
* return {String}
*/
tDetect: function(word) {
var splitted = word.split(':');
if (splitted.length > 1 && splitted[0] == 't') {
return Em.I18n.t(splitted[1]);
} else {
return splitted[0];
}
},
/**
* Get property value from view|controller by its key path.
*
* @param {String} value - key path
* @return {*}
* @method getViewPropertyValue
**/
getViewPropertyValue: function(value) {
value = value.substr(1);
var keyword = value.split('.')[0]; // return 'controller' or 'view'
switch (keyword) {
case 'controller':
return Em.get(this, value);
case 'view':
return Em.get(this, value.replace(/^view/, 'parentView'))
default:
break;
}
}
})
);
/**
* Return defined string instead of empty if value is null/undefined
* by default is `n/a`.
*
* @param empty {String} - value instead of empty string (not required)
* can be used with Em.I18n pass value started with't:'
*
* Examples:
*
* default value will be returned
* {{formatNull service.someValue}}
*
* <code>empty<code> will be returned
* {{formatNull service.someValue empty="I'm empty"}}
*
* Em.I18n translation will be returned
* {{formatNull service.someValue empty="t:my.key.to.translate"
*/
App.registerBoundHelper('formatNull', Em.View.extend({
tagName: 'span',
template: Em.Handlebars.compile('{{view.result}}'),
result: function() {
var emptyValue = this.get('empty') ? this.get('empty') : Em.I18n.t('services.service.summary.notAvailable');
emptyValue = emptyValue.startsWith('t:') ? Em.I18n.t(emptyValue.substr(2, emptyValue.length)) : emptyValue;
return (this.get('content') || this.get('content') == 0) ? this.get('content') : emptyValue;
}.property('content')
}));
/**
* Return formatted string with inserted <code>wbr</code>-tag after each dot
*
* @param {String} content
*
* Examples:
*
* returns 'apple'
* {{formatWordBreak 'apple'}}
*
* returns 'apple.<wbr />banana'
* {{formatWordBreak 'apple.banana'}}
*
* returns 'apple.<wbr />banana.<wbr />uranium'
* {{formatWordBreak 'apple.banana.uranium'}}
*/
App.registerBoundHelper('formatWordBreak', Em.View.extend({
tagName: 'span',
template: Em.Handlebars.compile('{{{view.result}}}'),
/**
* @type {string}
*/
result: function() {
return this.get('content') && this.get('content').replace(/\./g, '.<wbr />');
}.property('content')
}));
/**
* Ambari overrides the default date transformer.
* This is done because of the non-standard data
* sent. For example Nagios sends date as "12345678".
* The problem is that it is a String and is represented
* only in seconds whereas Javascript's Date needs
* milliseconds representation.
*/
DS.attr.transforms.date = {
from: function (serialized) {
var type = typeof serialized;
if (type === Em.I18n.t('common.type.string')) {
serialized = parseInt(serialized);
type = typeof serialized;
}
if (type === Em.I18n.t('common.type.number')) {
if (!serialized ){ //serialized timestamp = 0;
return 0;
}
// The number could be seconds or milliseconds.
// If seconds, then the length is 10
// If milliseconds, the length is 13
if (serialized.toString().length < 13) {
serialized = serialized * 1000;
}
return new Date(serialized);
} else if (serialized === null || serialized === undefined) {
// if the value is not present in the data,
// return undefined, not null.
return serialized;
} else {
return null;
}
},
to: function (deserialized) {
if (deserialized instanceof Date) {
return deserialized.getTime();
} else if (deserialized === undefined) {
return undefined;
} else {
return null;
}
}
};
DS.attr.transforms.object = {
from: function(serialized) {
return Ember.none(serialized) ? null : Object(serialized);
},
to: function(deserialized) {
return Ember.none(deserialized) ? null : Object(deserialized);
}
};
/**
* Allows EmberData models to have array properties.
*
* Declare the property as <code>
* operations: DS.attr('array'),
* </code> and
* during load provide a JSON array for value.
*
* This transform simply assigns the same array in both directions.
*/
DS.attr.transforms.array = {
from : function(serialized) {
return serialized;
},
to : function(deserialized) {
return deserialized;
}
};
/**
* Utility method to delete all existing records of a DS.Model type from the model's associated map and
* store's persistence layer (recordCache)
* @param type DS.Model Class
*/
App.resetDsStoreTypeMap = function(type) {
var allRecords = App.get('store.recordCache'); //This fetches all records in the ember-data persistence layer
var typeMaps = App.get('store.typeMaps');
var guidForType = Em.guidFor(type);
var typeMap = typeMaps[guidForType];
if (typeMap) {
var idToClientIdMap = typeMap.idToCid;
for (var id in idToClientIdMap) {
if (idToClientIdMap.hasOwnProperty(id) && idToClientIdMap[id]) {
delete allRecords[idToClientIdMap[id]]; // deletes the cached copy of the record from the store
}
}
typeMaps[guidForType] = {
idToCid: {},
clientIds: [],
cidToHash: {},
recordArrays: []
};
}
};
| keedio/ambari-web | app/utils/helper.js | JavaScript | apache-2.0 | 22,366 |
/**
* HotelsController
*
* @description :: Server-side logic for managing users
*/
module.exports = {
getUser: function(req, res){
User.findOne({id : req.params.id}).populateAll().exec(function(err, user){
if (err){
return res.json({error: 'Unexpected error'}, 500);
}
if (!user){
return res.json({error: 'Invalid user ID'});
}
return res.send(user);
});
},
addUser: function(req, res){
if(!req.body){
return res.json({error: 'Invalid User'});
}
User.create(req.body).exec(function(err, user){
if (err){
return res.json({error: 'Cannot create the User'}, 500);
}
return res.send(user);
})
},
updateUser: function(req, res){
return res.json({
todo: 'Not implemented yet!'
});
},
removeUser: function(req, res){
User.destroy({id : req.params.id}).populateAll().exec(function(err, user){
if (err){
return res.json({error: 'Unexpected error'}, 500);
}
if (!hotel){
return res.json({error: 'Invalid user ID'});
}
return res.send(user);
});
},
login: function(req, res) {
var bcrypt = require('bcrypt-nodejs');
//var crypto = require('crypto');
User.findOneByUsername(req.body.username).exec(function(err, user) {
if (err)
return res.json({error: 'Unexpected error'}, 500);
if (user) {
bcrypt.compare(req.body.password, user.password, function(err, match) {
if (err)
return res.json({error: 'Unexpected error'}, 500);
if (match) {
// password match
// Not sure if id must be hashed.
//var hash = crypto.createHash('md5')
// .update(user.id + Date.now()).digest('hex');
//user.hash = hash;
req.session.user = user.id;
delete user.password;
return res.json(user);
} else {
// invalid password
req.session.user = null;
return res.json({error: 'Invalid username/password'}, 400);
}
});
} else {
return res.json({error: 'Invalid username/password'}, 400);
}
});
},
logout: function(req, res) {
req.session.user = null;
return res.json({ sucess : 'User successfuly logged out'}, 200);
}
};
| adriannieto/shuffle-a-hotel | api/controllers/UserController.js | JavaScript | apache-2.0 | 2,231 |
if(Ti.Platform.osname == 'android') {
Ti.include('/lib/jsdeferred.js');
} else {
Ti.include("../../../../../../../../../lib/jsdeferred.js");
}
Deferred.define();
var DEFAULT_BAR_COLOR = "#000";
var useThisBackgroundColor='#ffffff';
var useThisBarColor='#026091';
function noNetworkAlert() {
Ti.App.fireEvent('hide_indicator',{});
Ti.UI.createAlertDialog({
title:Ti.Locale.getString('no_network_title'),
message:Ti.Locale.getString('no_network_msg')
}).show();
};
function isAndroid(){
return (Ti.Platform.name == 'android');
};
function isLogin(){
return (Ti.App.Properties.getString('email') != null && Ti.App.Properties.getString('password') != null);
};
var indicatorShowing = false;
var indWin = null;
var actInd = null;
function showIndicator(title) {
indicatorShowing = true;
Ti.API.info("showIndicator with title " + title);
// window container
indWin = Ti.UI.createWindow({
height:150,
width:150
});
// black view
var indView = Ti.UI.createView({
height:150,
width:150,
backgroundColor:'#000',
borderRadius:10,
opacity:0.7
});
indWin.add(indView);
// loading indicator
actInd = Ti.UI.createActivityIndicator({
style:Ti.UI.iPhone.ActivityIndicatorStyle.BIG,
height:30,
width:30
});
indWin.add(actInd);
// message
var message = Ti.UI.createLabel({
text:title,
color:'#fff',
width:'auto',
height:'auto',
font:{fontSize:20,fontWeight:'bold'},
bottom:20
});
indWin.add(message);
indWin.open();
actInd.show();
};
var droidActInd = Ti.UI.createActivityIndicator({height:30,width:30,message:'Loading...'});
function hideIndicator() {
if(Ti.Platform.osname == 'android'){
droidActInd.hide();
}else{
if (actInd && actInd !== null) {
actInd.hide();
}
if (indWin && indWin !== null) {
indWin.close({opacity:0,duration:500});
}
indicatorShowing = false;
}
};
Ti.App.addEventListener('show_indicator', function(e) {
if(Ti.Platform.osname == 'android') {
if(e.title == null) {
droidActInd.message = 'Loading...';
} else {
droidActInd.message = e.title;
}
droidActInd.show();
}else{
if(e.title == null) {
e.title = 'Loading';
}
if(indicatorShowing) {
hideIndicator();
}
showIndicator(e.title);
}
});
Ti.App.addEventListener('change_title', function(e) {
if(e.title) {
hideIndicator();
showIndicator(e.title);
}
});
Ti.App.addEventListener('hide_indicator', function(e) {
hideIndicator();
});
Ti.App.addEventListener('show_snap', function(e) {
var photo_detailwin = Titanium.UI.createWindow({
url:'../javascript/photo_detail.js',
title:'Photo Detail',
backgroundColor:useThisBackgroundColor,
userimageUrl: e.userimage_url,
mediumimageUrl: e.mediumimage_url,
snapId: e.snap_id,
userId: e.user_id,
userName: e.user_name,
snapTitle: e.snap_title,
createdAt: e.created_at
});
Ti.UI.currentTab.open(photo_detailwin, {animated : true});
});
var HanduplistDB = function() {
this.dbName = 'handuplistdb';
this.open = function () {
this.db = Titanium.Database.open(this.dbName);
};
this.close = function () {
this.db.close();
};
this.selectUser = function(){
this.open();
var rows = this.db.execute('SELECT * FROM users');
this.close();
return rows;
};
this.deleteUser = function () {
this.open();
var res = this.db.execute('DELETE FROM users');
this.close();
return true;
};
this.addUser = function (user, input_password) {
this.open();
var res = this.db.execute(
'INSERT INTO users (id, email, password, name, photo) VALUES(?,?,?,?,?)',
user.id,
user.email,
input_password,
user.name,
user.photo
);
Ti.API.debug('Add to DB');
this.close();
return true;
};
this.open();
this.db.execute('CREATE TABLE IF NOT EXISTS users (id TEXT, email TEXT, password TEXT, name TEXT, photo TEXT)');
this.close();
};
var ImageWithCache = function(){
this.addImage = function(imageDirectoryName, image_url, id, imageViewObject){
image_url = image_url.replace(/\?[0-9]+$/, '');
var cacheFilePath = Titanium.Filesystem.applicationDataDirectory + '/' + imageDirectoryName + '/' + id;
var cacheFile = Ti.Filesystem.getFile(cacheFilePath);
if (cacheFile.exists()) {
//Ti.API.info('foundcache:' + cacheFilePath + ' [' + cacheFile.modificationTimestamp() + ']');
imageViewObject.image = cacheFilePath;
}
else {
//Ti.API.info('createcache:' + cacheFilePath);
var dir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, imageDirectoryName);
if (!dir.exists()) {
dir.createDirectory();
};
cacheFile = Ti.Filesystem.getFile(cacheFilePath);
if (!cacheFile.exists()) {
var xhr = Ti.Network.createHTTPClient();
(function() {
var deferred = new Deferred();
xhr.onload = function()
{
if (xhr.status == 200)
{
cacheFile.write(xhr.responseData);
deferred.call();
};
};
xhr.open('GET',image_url);
xhr.send();
return deferred;
})().next(function(){
//Ti.API.info('complete cache:' + cacheFilePath);
imageViewObject.image = cacheFilePath;
});
}
}
//Ti.API.info('addImage return: ' + cacheFilePath);
return true;
};
};
var LikeSnap = function(){
this.addLike = function(input_snap_id, input_email, input_password, input_userimage_url, input_mediumimage_url, input_user_id, input_user_name,input_snap_title, input_created_at){
if(!Ti.Network.online){
noNetworkAlert();
}
//progresslavel.text = 'Wait...';
Ti.App.fireEvent('show_indicator',{title:'Wait...'});
var xhr = Ti.Network.createHTTPClient();
(function() {
var deferred = new Deferred();
xhr.onload = function()
{
var json = this.responseText;
var data = JSON.parse(json);
if (data.status == 200)
{
//Titanium.API.info(data.response);
//progresslavel.text = 'Done';
}
else
{
//Titanium.API.info(data.response);
//progresslavel.text = 'Error';
Ti.App.fireEvent('hide_indicator',{});
}
deferred.call();
};
xhr.onerror = function()
{
var json = this.responseText;
var data = JSON.parse(json);
//progresslavel.text = 'Error';
Ti.App.fireEvent('hide_indicator',{});
};
var url = 'https://handuplist.com/like.json';
xhr.onsendstream = function(e){
Ti.API.info(e.progress);
};
xhr.open('POST',url);
postjson = {
email: input_email,
password: input_password,
like: {
snap_id: input_snap_id
}
};
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(JSON.stringify(postjson));
return deferred;
})().next(function(){
Ti.App.fireEvent('hide_indicator',{});
Ti.App.fireEvent('show_snap',{
userimage_url:input_userimage_url,
mediumimage_url:input_mediumimage_url,
snap_id:input_snap_id,
user_id:input_user_id,
user_name:input_user_name,
snap_title:input_snap_title,
created_at:input_created_at});
});
};
};
var CommentSnap = function(){
this.addComment = function(input_snap_id, input_comment, input_email, input_password, input_userimage_url, input_mediumimage_url, input_user_id, input_user_name,input_snap_title, input_created_at){
if(!Ti.Network.online){
noNetworkAlert();
}
//progresslavel.text = 'Wait...';
//Ti.App.fireEvent('show_indicator',{title:'Wait...'});
var xhr = Ti.Network.createHTTPClient();
(function() {
var deferred = new Deferred();
xhr.onload = function()
{
Ti.API.info('comment:onload');
var json = this.responseText;
var data = JSON.parse(json);
if (data.status == 200)
{
//Titanium.API.info(data.response);
//progresslavel.text = 'Done';
}
else
{
//Titanium.API.info(data.response);
//progresslavel.text = 'Error';
Ti.App.fireEvent('hide_indicator',{});
}
deferred.call();
};
xhr.onerror = function()
{
Ti.API.info('comment:onerror');
var json = this.responseText;
var data = JSON.parse(json);
//progresslavel.text = 'Error';
Ti.App.fireEvent('hide_indicator',{});
};
var url = 'https://handuplist.com/comment.json';
xhr.onsendstream = function(e){
Ti.API.info(e.progress);
};
xhr.open('POST',url);
Ti.API.info('comment:' + url);
postjson = {
email: input_email,
password: input_password,
comment: {
snap_id: input_snap_id,
content: input_comment
}
};
xhr.setRequestHeader("Content-Type","application/json");
//Ti.API.info('111');
xhr.send(JSON.stringify(postjson));
return deferred;
})().next(function(){
Ti.App.fireEvent('hide_indicator',{});
//Ti.App.fireEvent('show_snap',{
// userimage_url:input_userimage_url,
// mediumimage_url:input_mediumimage_url,
// snap_id:input_snap_id,
// user_id:input_user_id,
// user_name:input_user_name,
// snap_title:input_snap_title,
// created_at:input_created_at});
});
};
};
| neojjang/sociallist_titanium | Resources/javascript/application.js | JavaScript | apache-2.0 | 9,706 |
/**
* Handlers for the sort menu in the dashboard-list.html template.a
*/
$(document).on('click', 'ul.ds-dashboard-sort-menu li', function(e) {
var column = e.target.getAttribute('data-ds-sort-col')
var order = e.target.getAttribute('data-ds-sort-order')
var url = URI(window.location)
if (column) {
url.setQuery('sort', column)
}
if (order) {
url.setQuery('order', order)
}
window.location = url.href()
})
$(document).ready(function() {
var params = URI(window.location).search(true)
if (params.sort !== 'default' ) {
$('ul.ds-dashboard-sort-menu li').removeClass('active')
$('[data-ds-sort-col="' + params.sort + '"][data-ds-sort-order="' + (params.order || 'asc') + '"]')
.parent()
.addClass('active')
}
})
| filippog/tessera | js/app/handlers/menu-dashboard-sort.js | JavaScript | apache-2.0 | 825 |
var config = {
apiKey: "AIzaSyCRLXkE0Upwk_0qnHiR1WPfYg2SZcIzYlg",
authDomain: "bloc-chat-9fbea.firebaseapp.com",
databaseURL: "https://bloc-chat-9fbea.firebaseio.com",
storageBucket: "bloc-chat-9fbea.appspot.com",
messagingSenderId: "731453641152"
};
firebase.initializeApp(config);
| jaysonbucy/bloc-chat | app/scripts/firebaseAuth.js | JavaScript | apache-2.0 | 293 |
var searchData=
[
['name',['name',['../classMarkerSet.html#aeb43b9a16f038d8c55fc05a94022c9fb',1,'MarkerSet::name()'],['../classNatNetSender.html#a8c2d5cf1a46cfbb1fadc347dedad6f14',1,'NatNetSender::name()']]],
['natnet',['NatNet',['../classNatNet.html',1,'']]],
['natnetmessageid',['NatNetMessageID',['../classNatNetPacket.html#af9a3198d39270f9703a36c414079ab51',1,'NatNetPacket']]],
['natnetpacket',['NatNetPacket',['../classNatNetPacket.html',1,'NatNetPacket'],['../classNatNetPacket.html#aa6da2fc5f50d6ed960333a7dbeee2c22',1,'NatNetPacket::NatNetPacket()'],['../classNatNetPacket.html#a1276bae8a1f3864764897747ee67b90c',1,'NatNetPacket::NatNetPacket(NatNetPacket const &other)']]],
['natnetsender',['NatNetSender',['../classNatNetSender.html',1,'NatNetSender'],['../classNatNetSender.html#aa3801cb63269a920edc55a6e78fec4e6',1,'NatNetSender::NatNetSender()'],['../classNatNetSender.html#ad28a14e9e6696252263655e0325a2199',1,'NatNetSender::NatNetSender(NatNetSender const &other)']]],
['natnetversion',['natNetVersion',['../classNatNetSender.html#a89bfa0c1137ad221c54be093a0966088',1,'NatNetSender']]],
['ndatabytes',['nDataBytes',['../classNatNetPacket.html#aff2c08650945030907a0fcc5c11c2b84',1,'NatNetPacket']]]
];
| robinzhoucmu/MLab_EXP | Mocap/NatNetLinux-master/include/NatNetLinux/html/search/all_6e.js | JavaScript | apache-2.0 | 1,239 |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
'use strict';
function main(name, outputConfig) {
// [START automl_v1beta1_generated_AutoMl_ExportModel_async]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* Required. The resource name of the model to export.
*/
// const name = 'abc123'
/**
* Required. The desired output location and configuration.
*/
// const outputConfig = {}
// Imports the Automl library
const {AutoMlClient} = require('@google-cloud/automl').v1beta1;
// Instantiates a client
const automlClient = new AutoMlClient();
async function callExportModel() {
// Construct request
const request = {
name,
outputConfig,
};
// Run request
const [operation] = await automlClient.exportModel(request);
const [response] = await operation.promise();
console.log(response);
}
callExportModel();
// [END automl_v1beta1_generated_AutoMl_ExportModel_async]
}
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
| googleapis/nodejs-automl | samples/generated/v1beta1/auto_ml.export_model.js | JavaScript | apache-2.0 | 1,871 |
import React, { Component } from 'react';
import {
View,
Dimensions,
Text
} from 'react-native';
var {height, width} = Dimensions.get('window');
class InfoBox extends Component {
render(){
return(
<View style={styles.box}>
<View style={styles.titleContainer}>
<Text style={styles.textTitle}>{this.props.title}</Text>
</View>
<Text style={styles.textBox}>{this.props.content}</Text>
</View>
)
}
}
const styles = {
box:{
borderRadius: 3,
borderWidth: 0.5,
borderColor: '#d6d7da',
backgroundColor: '#ffffff',
margin: 5,
marginVertical: 1,
overflow: 'hidden',
elevation:2
},
titleContainer:{
borderBottomWidth: 0.5,
borderTopLeftRadius: 3,
borderTopRightRadius: 2.5,
borderBottomColor: '#d6d7da',
backgroundColor: '#f6f7f8',
paddingHorizontal: 10,
paddingVertical: 5,
elevation:1
},
textTitle:{
color:'black',
paddingLeft:20,
fontSize:15,
fontWeight:'bold'
},
textBox:{
fontSize:15,
padding:10,
paddingLeft:30,
color:'black'
},
};
export {InfoBox};
| khanhqd/ProjectOT1 | StarterRNP/src/screens/common/InfoBox.js | JavaScript | apache-2.0 | 1,111 |
// 编译html代码
DYC.filter('html', function($sce) {
return function(text) {
return $sce.trustAsHtml(text);
};
});
// 过滤html代码
DYC.filter('text', function($sce) {
return function(text) {
return text.replace(/<\/?[^>]*>/g, '');
};
});
// 加粗匹配文本
DYC.filter('matchText', function($sce) {
return function(text, argKey) {
let tmpl = '<b>' + argKey + '</b>';
let reg = /([[\](){}*?+^$.|\\])/ig;
let str = argKey.replace(reg, '\\$1');
text = text.replace(new RegExp(str, 'ig'), tmpl);
return $sce.trustAsHtml(text);
};
}); | LinJieLinLin/myWebpack | src/common/filter/html.js | JavaScript | apache-2.0 | 618 |
(function () {
'use strict';
var app = angular.module('OrganizationModule');
function OrganizationController($scope, $mdDialog, TreeFactory, $stateParams, OrganizationFactory) {
var vm = this;
vm.organization = $stateParams.organization;
vm.linkedNodeIds = ['organizationNode', 'objectiveNode', 'keyResultNode', 'taskNode'];
TreeFactory.getTrees(vm.organization)
.then(function (response) {
vm.trees = TreeFactory.formatTrees(response.data.Success);
});
vm.openOrganizationMembersModal = function ($event) {
$mdDialog.show({
targetEvent: $event,
templateUrl: 'app/shared/members-modal/members-modal.tpl.html',
controller: 'MembersModalController',
controllerAs: 'modal',
locals: {
members: vm.orgMembers,
apiFactory: OrganizationFactory,
node: vm.organization
}
}).then(function (response) {
vm.orgMembers = response;
});
};
vm.openAddTreeModal = function ($event) {
$mdDialog.show({
targetEvent: $event,
templateUrl: 'app/organization/add-tree-modal.tpl.html',
controller: 'AddTreeModalController',
controllerAs: 'modal',
locals: {
organization: vm.organization
}
}).then(function (response) {
if (response && !response.Error) {
vm.formattedTrees = angular.copy(vm.trees);
vm.formattedTrees.push(response.Success);
vm.formattedTrees = _.flatten(vm.formattedTrees);
vm.trees = TreeFactory.formatTrees(vm.formattedTrees);
}
});
};
}
OrganizationController.$inject = ['$scope', '$mdDialog', 'TreeFactory', '$stateParams', 'OrganizationFactory'];
app.controller('OrganizationController', OrganizationController);
})();
| dmonay/okra_client | src/app/organization/OrganizationController.js | JavaScript | apache-2.0 | 2,126 |
define(['ash', 'game/constants/UpgradeConstants', 'game/vos/UpgradeVO', 'game/vos/BlueprintVO'],
function (Ash, UpgradeConstants, UpgradeVO, BlueprintVO) {
var UpgradesComponent = Ash.Class.extend({
boughtUpgrades: [],
newBlueprints: [],
availableBlueprints: [],
constructor: function () {
this.boughtUpgrades = [];
this.newBlueprints = [];
this.availableBlueprints = [];
},
addUpgrade: function (upgrade) {
if (!this.hasUpgrade(upgrade)) {
this.boughtUpgrades.push(upgrade);
this.removeBlueprints(upgrade);
}
},
hasUpgrade: function (upgrade) {
return this.boughtUpgrades.indexOf(upgrade) >= 0;
},
createBlueprint: function (upgradeID) {
var blueprintVO = this.getBlueprint(upgradeID);
if (blueprintVO) {
blueprintVO.completed = true;
}
},
useBlueprint: function (upgradeID) {
var blueprintVO = this.getBlueprint(upgradeID);
if (blueprintVO) {
this.newBlueprints.splice(this.newBlueprints.indexOf(blueprintVO), 1);
this.availableBlueprints.push(blueprintVO);
} else {
log.w("No such blueprint found: " + upgradeID);
}
},
addNewBlueprintPiece: function (upgradeID) {
if (this.hasUpgrade(upgradeID)) return;
var blueprintVO = this.getBlueprint(upgradeID);
if (!blueprintVO) {
var maxPieces = UpgradeConstants.getMaxPiecesForBlueprint(upgradeID);
blueprintVO = new BlueprintVO(upgradeID, maxPieces);
this.newBlueprints.push(blueprintVO);
}
blueprintVO.currentPieces++;
},
hasBlueprint: function (upgradeID) {
return this.getBlueprint(upgradeID) !== null;
},
getBlueprint: function (upgradeID) {
for (let i = 0; i < this.newBlueprints.length; i++) {
if (this.newBlueprints[i].upgradeID === upgradeID) return this.newBlueprints[i];
}
for (let j = 0; j < this.availableBlueprints.length; j++) {
if (this.availableBlueprints[j].upgradeID === upgradeID) return this.availableBlueprints[j];
}
return null;
},
hasAvailableBlueprint: function (upgradeID) {
return this.availableBlueprints.indexOf(this.getBlueprint(upgradeID)) >= 0;
},
hasAllPieces: function (upgradeID) {
var blueprintVO = this.getBlueprint(upgradeID);
if (!blueprintVO) return false;
return blueprintVO.currentPieces >= blueprintVO.maxPieces;
},
hasNewBlueprint: function (upgradeID) {
var blueprintVO = this.getBlueprint(upgradeID);
return blueprintVO && blueprintVO.completed && this.newBlueprints.indexOf(blueprintVO) >= 0;
},
hasUnfinishedBlueprint: function (upgradeID) {
var blueprintVO = this.getBlueprint(upgradeID);
return blueprintVO;// && !blueprintVO.completed && this.newBlueprints.indexOf(blueprintVO) >= 0;
},
getUnfinishedBlueprints: function () {
var unfinished = [];
for (let i = 0; i < this.newBlueprints.length; i++) {
if (!this.newBlueprints[i].completed) unfinished.push(this.newBlueprints[i]);
}
return unfinished;
},
getNewBlueprints: function () {
return this.newBlueprints;
},
removeBlueprints: function (upgradeID) {
for (let i = 0; i < this.newBlueprints.length; i++) {
if (this.newBlueprints[i].upgradeID === upgradeID) {
this.newBlueprints.splice(i, 1);
break;
}
}
for (let j = 0; j < this.availableBlueprints.length; j++) {
if (this.availableBlueprints[j].upgradeID === upgradeID) {
this.availableBlueprints.splice(j, 1);
break;
}
}
},
getSaveKey: function () {
return "Upgrades";
},
});
return UpgradesComponent;
});
| nroutasuo/level13 | src/game/components/tribe/UpgradesComponent.js | JavaScript | apache-2.0 | 3,515 |
module.exports = function (math) {
var util = require('../../util/index'),
BigNumber = math.type.BigNumber,
Complex = require('../../type/Complex'),
Matrix = require('../../type/Matrix'),
Unit = require('../../type/Unit'),
collection = require('../../type/collection'),
isBoolean = util['boolean'].isBoolean,
isNumber = util.number.isNumber,
isComplex = Complex.isComplex,
isUnit = Unit.isUnit,
isCollection = collection.isCollection;
/**
* Subtract two values
*
* x - y
* subtract(x, y)
*
* For matrices, the function is evaluated element wise.
*
* @param {Number | BigNumber | Boolean | Complex | Unit | Array | Matrix} x
* @param {Number | BigNumber | Boolean | Complex | Unit | Array | Matrix} y
* @return {Number | BigNumber | Complex | Unit | Array | Matrix} res
*/
math.subtract = function subtract(x, y) {
if (arguments.length != 2) {
throw new math.error.ArgumentsError('subtract', arguments.length, 2);
}
if (isNumber(x)) {
if (isNumber(y)) {
// number - number
return x - y;
}
else if (isComplex(y)) {
// number - complex
return new Complex (
x - y.re,
- y.im
);
}
}
else if (isComplex(x)) {
if (isNumber(y)) {
// complex - number
return new Complex (
x.re - y,
x.im
)
}
else if (isComplex(y)) {
// complex - complex
return new Complex (
x.re - y.re,
x.im - y.im
)
}
}
if (x instanceof BigNumber) {
// try to convert to big number
if (isNumber(y)) {
y = BigNumber.convert(y);
}
else if (isBoolean(y)) {
y = new BigNumber(y ? 1 : 0);
}
if (y instanceof BigNumber) {
return x.minus(y);
}
// downgrade to Number
return subtract(x.toNumber(), y);
}
if (y instanceof BigNumber) {
// try to convert to big number
if (isNumber(x)) {
x = BigNumber.convert(x);
}
else if (isBoolean(x)) {
x = new BigNumber(x ? 1 : 0);
}
if (x instanceof BigNumber) {
return x.minus(y)
}
// downgrade to Number
return subtract(x, y.toNumber());
}
if (isUnit(x)) {
if (isUnit(y)) {
if (x.value == null) {
throw new Error('Parameter x contains a unit with undefined value');
}
if (y.value == null) {
throw new Error('Parameter y contains a unit with undefined value');
}
if (!x.equalBase(y)) {
throw new Error('Units do not match');
}
var res = x.clone();
res.value -= y.value;
res.fixPrefix = false;
return res;
}
}
if (isCollection(x) || isCollection(y)) {
return collection.deepMap2(x, y, subtract);
}
if (isBoolean(x)) {
return subtract(+x, y);
}
if (isBoolean(y)) {
return subtract(x, +y);
}
throw new math.error.UnsupportedTypeError('subtract', math['typeof'](x), math['typeof'](y));
};
};
| npmcomponent/josdejong-mathjs | lib/function/arithmetic/subtract.js | JavaScript | apache-2.0 | 3,192 |
/**
* Copyright 2020 Phenix Real Time Solutions, 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.
*/
define([
'sdk/express/PCastExpress',
'sdk/AdminApiProxyClient',
'../../../test/mock/HttpStubber',
'../../../test/mock/WebSocketStubber',
'../../../test/mock/ChromeRuntimeStubber',
'../../../test/mock/PeerConnectionStubber',
'../../../test/mock/UserMediaStubber',
'sdk/streaming/PeerConnectionMonitor'
], function(PCastExpress, AdminApiProxyClient, HttpStubber, WebSocketStubber, ChromeRuntimeStubber, PeerConnectionStubber, UserMediaStubber, PeerConnectionMonitor) {
describe('When Publishing with Express PCast', function() {
var httpStubber;
var websocketStubber;
var chromeRuntimeStubber = new ChromeRuntimeStubber();
var peerConnectionStubber = new PeerConnectionStubber();
var pcastExpress;
var clientFailureReason = 'client-side-failure';
before(function() {
chromeRuntimeStubber.stub();
peerConnectionStubber.stub();
});
beforeEach(function() {
httpStubber = new HttpStubber();
httpStubber.stubAuthRequest();
httpStubber.stubStreamRequest();
websocketStubber = new WebSocketStubber();
websocketStubber.stubAuthRequest();
pcastExpress = new PCastExpress({
authToken: 'DIGEST:eyJhcHBsaWNhdGlvbklkIjoiZGVtbyIsImRpZ2VzdCI6IjZ3ODQ3S3N2ZFh5WjhRNnlyNWNzMnh0YjMxdFQ0TFR3bHAyeUZyZ0t2K0pDUEJyYkI4Qnd5a3dyT2NIWE52OXQ5eU5qYkFNT2tuQ1N1VnE5eGdBZjdRPT0iLCJ0b2tlbiI6IntcImV4cGlyZXNcIjoxOTI5NjA5NjcwMjI1LFwiY2FwYWJpbGl0aWVzXCI6W1wiYXVkaW8tb25seVwiXSxcInJlcXVpcmVkVGFnXCI6XCJyb29tSWQ6ZXVyb3BlLWNlbnRyYWwjZGVtbyNtdWx0aXBhcnR5Q2hhdERlbW9Sb29tLlpwcWJKNG1Oa2g2dVwifSJ9',
uri: 'wss://mockURI'
});
websocketStubber.stubSetupStream();
});
after(function() {
chromeRuntimeStubber.restore();
peerConnectionStubber.restore();
});
afterEach(function() {
httpStubber.restore();
websocketStubber.restore();
pcastExpress.dispose();
});
it('Has method publish', function() {
expect(pcastExpress.publish).to.be.a('function');
});
it('Expect publisher to be returned in subscribe callback', function(done) {
pcastExpress.publish({
streamToken: 'DIGEST:eyJhcHBsaWNhdGlvbklkIjoiZGVtbyIsImRpZ2VzdCI6IjZ3ODQ3S3N2ZFh5WjhRNnlyNWNzMnh0YjMxdFQ0TFR3bHAyeUZyZ0t2K0pDUEJyYkI4Qnd5a3dyT2NIWE52OXQ5eU5qYkFNT2tuQ1N1VnE5eGdBZjdRPT0iLCJ0b2tlbiI6IntcImV4cGlyZXNcIjoxOTI5NjA5NjcwMjI1LFwiY2FwYWJpbGl0aWVzXCI6W1wiYXVkaW8tb25seVwiXSxcInJlcXVpcmVkVGFnXCI6XCJyb29tSWQ6ZXVyb3BlLWNlbnRyYWwjZGVtbyNtdWx0aXBhcnR5Q2hhdERlbW9Sb29tLlpwcWJKNG1Oa2g2dVwifSJ9',
userMediaStream: UserMediaStubber.getMockMediaStream()
}, function(error, response) {
expect(response.publisher).to.be.a('object');
done();
});
});
it('Expect monitor to return a response with retry', function(done) {
var startClone = PeerConnectionMonitor.prototype.start;
PeerConnectionMonitor.prototype.start = function(options, activeCallback, monitorCallback) {
monitorCallback(null, {type: clientFailureReason});
};
pcastExpress.publish({
streamToken: 'DIGEST:eyJhcHBsaWNhdGlvbklkIjoiZGVtbyIsImRpZ2VzdCI6IjZ3ODQ3S3N2ZFh5WjhRNnlyNWNzMnh0YjMxdFQ0TFR3bHAyeUZyZ0t2K0pDUEJyYkI4Qnd5a3dyT2NIWE52OXQ5eU5qYkFNT2tuQ1N1VnE5eGdBZjdRPT0iLCJ0b2tlbiI6IntcImV4cGlyZXNcIjoxOTI5NjA5NjcwMjI1LFwiY2FwYWJpbGl0aWVzXCI6W1wiYXVkaW8tb25seVwiXSxcInJlcXVpcmVkVGFnXCI6XCJyb29tSWQ6ZXVyb3BlLWNlbnRyYWwjZGVtbyNtdWx0aXBhcnR5Q2hhdERlbW9Sb29tLlpwcWJKNG1Oa2g2dVwifSJ9',
userMediaStream: UserMediaStubber.getMockMediaStream(),
monitor: {
conditionCountForNotificationThreshold: 0,
callback: function(error, response) {
if (response.status !== clientFailureReason) {
return;
}
expect(response.retry).to.be.a('function');
PeerConnectionMonitor.prototype.start = startClone;
done();
}
}
}, function() {});
});
it('Expect monitor retry to setup a new publisher', function(done) {
var startClone = PeerConnectionMonitor.prototype.start;
var subscribeCount = 0;
PeerConnectionMonitor.prototype.start = function(options, activeCallback, monitorCallback) {
setTimeout(function() {
if (subscribeCount < 2) {
monitorCallback(null, {type: clientFailureReason});
}
}, 10);
};
pcastExpress.publish({
streamToken: 'DIGEST:eyJhcHBsaWNhdGlvbklkIjoiZGVtbyIsImRpZ2VzdCI6IjZ3ODQ3S3N2ZFh5WjhRNnlyNWNzMnh0YjMxdFQ0TFR3bHAyeUZyZ0t2K0pDUEJyYkI4Qnd5a3dyT2NIWE52OXQ5eU5qYkFNT2tuQ1N1VnE5eGdBZjdRPT0iLCJ0b2tlbiI6IntcImV4cGlyZXNcIjoxOTI5NjA5NjcwMjI1LFwiY2FwYWJpbGl0aWVzXCI6W1wiYXVkaW8tb25seVwiXSxcInJlcXVpcmVkVGFnXCI6XCJyb29tSWQ6ZXVyb3BlLWNlbnRyYWwjZGVtbyNtdWx0aXBhcnR5Q2hhdERlbW9Sb29tLlpwcWJKNG1Oa2g2dVwifSJ9',
userMediaStream: UserMediaStubber.getMockMediaStream(),
monitor: {
conditionCountForNotificationThreshold: 0,
callback: function(error, response) {
if (response.status !== clientFailureReason) {
return;
}
response.retry();
PeerConnectionMonitor.prototype.start = startClone;
}
}
}, function() {
subscribeCount++;
if (subscribeCount > 1) {
expect(subscribeCount).to.be.equal(2);
done();
}
});
});
});
describe('When Publishing with Express PCast and adminApi', function() {
var mockBackendUri = 'https://mockUri';
var mockAuthData = {
name: 'mockUser',
password: 'somePassword'
};
var httpStubber;
var websocketStubber;
var chromeRuntimeStubber = new ChromeRuntimeStubber();
var peerConnectionStubber = new PeerConnectionStubber();
var pcastExpress;
var clientFailureReason = 'client-side-failure';
before(function() {
chromeRuntimeStubber.stub();
peerConnectionStubber.stub();
});
beforeEach(function() {
var adminApiProxyClient = new AdminApiProxyClient();
adminApiProxyClient.setBackendUri(mockBackendUri);
adminApiProxyClient.setAuthenticationData(mockAuthData);
httpStubber = new HttpStubber();
httpStubber.stubAuthRequest();
httpStubber.stubStreamRequest();
websocketStubber = new WebSocketStubber();
websocketStubber.stubAuthRequest();
pcastExpress = new PCastExpress({
adminApiProxyClient,
uri: 'wss://mockURI'
});
websocketStubber.stubSetupStream();
});
after(function() {
chromeRuntimeStubber.restore();
peerConnectionStubber.restore();
});
afterEach(function() {
httpStubber.restore();
websocketStubber.restore();
pcastExpress.dispose();
});
it('Expect monitor retry with unauthorized status for setupStream to trigger request one time to get new streamToken', function(done) {
httpStubber.stubStreamRequest(null, 'DIGEST:eyJ0b2tlbiI6IntcImNhcGFiaWxpdGllc1wiOltdfSJ9');
var startClone = PeerConnectionMonitor.prototype.start;
var subscribeCount = 0;
PeerConnectionMonitor.prototype.start = function(options, activeCallback, monitorCallback) {
setTimeout(function() {
if (subscribeCount < 2) {
websocketStubber.stubResponse('pcast.SetupStream', {status: 'unauthorized'});
monitorCallback(null, {type: clientFailureReason});
}
}, 10);
};
pcastExpress.publish({
capabilities: [],
enableWildcardCapability: true,
userMediaStream: UserMediaStubber.getMockMediaStream(),
monitor: {
conditionCountForNotificationThreshold: 0,
callback: function(error, response) {
if (response.status !== clientFailureReason) {
return;
}
response.retry();
PeerConnectionMonitor.prototype.start = startClone;
}
}
}, function(error, response) {
subscribeCount++;
if (subscribeCount > 1) {
expect(response.status).to.be.equal('unauthorized');
done();
}
});
});
});
}); | PhenixP2P/WebSDK | test/sdk/express/WhenPublishingWithExpressPCast.js | JavaScript | apache-2.0 | 9,984 |
'use strict';
var inherits = require('util').inherits;
var EventEmitter = require('events').EventEmitter;
var once = require('./util/once').once;
module.exports = {
Characteristic: Characteristic
};
/**
* Characteristic represents a particular typed variable that can be assigned to a Service. For instance, a
* "Hue" Characteristic might store a 'float' value of type 'arcdegrees'. You could add the Hue Characteristic
* to a Service in order to store that value. A particular Characteristic is distinguished from others by its
* UUID. HomeKit provides a set of known Characteristic UUIDs defined in HomeKitTypes.js along with a
* corresponding concrete subclass.
*
* You can also define custom Characteristics by providing your own UUID. Custom Characteristics can be added
* to any native or custom Services, but Siri will likely not be able to work with these.
*
* Note that you can get the "value" of a Characteristic by accessing the "value" property directly, but this
* is really a "cached value". If you want to fetch the latest value, which may involve doing some work, then
* call getValue().
*
* @event 'get' => function(callback(err, newValue), context) { }
* Emitted when someone calls getValue() on this Characteristic and desires the latest non-cached
* value. If there are any listeners to this event, one of them MUST call the callback in order
* for the value to ever be delivered. The `context` object is whatever was passed in by the initiator
* of this event (for instance whomever called `getValue`).
*
* @event 'set' => function(newValue, callback(err), context) { }
* Emitted when someone calls setValue() on this Characteristic with a desired new value. If there
* are any listeners to this event, one of them MUST call the callback in order for this.value to
* actually be set. The `context` object is whatever was passed in by the initiator of this change
* (for instance, whomever called `setValue`).
*
* @event 'change' => function({ oldValue, newValue, context }) { }
* Emitted after a change in our value has occurred. The new value will also be immediately accessible
* in this.value. The event object contains the new value as well as the context object originally
* passed in by the initiator of this change (if known).
*/
function Characteristic(displayName, UUID, props) {
this.displayName = displayName;
this.UUID = UUID;
this.iid = null; // assigned by our containing Service
this.value = null;
this.props = props || {
format: null,
unit: null,
minValue: null,
maxValue: null,
minStep: null,
perms: []
};
}
inherits(Characteristic, EventEmitter);
// Known HomeKit formats
Characteristic.Formats = {
BOOL: 'bool',
INT: 'int',
FLOAT: 'float',
STRING: 'string',
ARRAY: 'array', // unconfirmed
DICTIONARY: 'dictionary', // unconfirmed
UINT8: 'uint8',
UINT16: 'uint16',
UINT32: 'uint32',
UINT64: 'uint64',
DATA: 'data', // unconfirmed
TLV8: 'tlv8'
}
// Known HomeKit unit types
Characteristic.Units = {
// HomeKit only defines Celsius, for Fahrenheit, it requires iOS app to do the conversion.
CELSIUS: 'celsius',
PERCENTAGE: 'percentage',
ARC_DEGREE: 'arcdegrees',
LUX: 'lux',
SECONDS: 'seconds'
}
// Known HomeKit permission types
Characteristic.Perms = {
READ: 'pr',
WRITE: 'pw',
NOTIFY: 'ev',
HIDDEN: 'hd'
}
/**
* Copies the given properties to our props member variable,
* and returns 'this' for chaining.
*
* @param 'props' {
* format: <one of Characteristic.Formats>,
* unit: <one of Characteristic.Units>,
* minValue: <minimum value for numeric characteristics>,
* maxValue: <maximum value for numeric characteristics>,
* minStep: <smallest allowed increment for numeric characteristics>,
* perms: array of [Characteristic.Perms] like [Characteristic.Perms.READ, Characteristic.Perms.WRITE]
* }
*/
Characteristic.prototype.setProps = function(props) {
for (var key in (props || {}))
if (Object.prototype.hasOwnProperty.call(props, key))
this.props[key] = props[key];
return this;
}
Characteristic.prototype.getValue = function(callback, context, connectionID) {
if (this.listeners('get').length > 0) {
// allow a listener to handle the fetching of this value, and wait for completion
this.emit('get', once(function(err, newValue) {
if (err) {
// pass the error along to our callback
if (callback) callback(err);
}
else {
if (newValue === undefined || newValue === null)
newValue = this.getDefaultValue();
// getting the value was a success; we can pass it along and also update our cached value
var oldValue = this.value;
this.value = newValue;
if (callback) callback(null, newValue);
// emit a change event if necessary
if (oldValue !== newValue)
this.emit('change', { oldValue:oldValue, newValue:newValue, context:context });
}
}.bind(this)), context, connectionID);
}
else {
// no one is listening to the 'get' event, so just return the cached value
if (callback)
callback(null, this.value);
}
}
Characteristic.prototype.setValue = function(newValue, callback, context, connectionID) {
if (this.listeners('set').length > 0) {
// allow a listener to handle the setting of this value, and wait for completion
this.emit('set', newValue, once(function(err) {
if (err) {
// pass the error along to our callback
if (callback) callback(err);
}
else {
if (newValue === undefined || newValue === null)
newValue = this.getDefaultValue();
// setting the value was a success; so we can cache it now
var oldValue = this.value;
this.value = newValue;
if (callback) callback();
if (oldValue !== newValue)
this.emit('change', { oldValue:oldValue, newValue:newValue, context:context });
}
}.bind(this)), context, connectionID);
}
else {
if (newValue === undefined || newValue === null)
newValue = this.getDefaultValue();
// no one is listening to the 'set' event, so just assign the value blindly
var oldValue = this.value;
this.value = newValue;
if (callback) callback();
if (oldValue !== newValue)
this.emit('change', { oldValue:oldValue, newValue:newValue, context:context });
}
return this; // for chaining
}
Characteristic.prototype.updateValue = function(newValue, callback, context) {
if (newValue === undefined || newValue === null)
newValue = this.getDefaultValue();
// no one is listening to the 'set' event, so just assign the value blindly
var oldValue = this.value;
this.value = newValue;
if (callback) callback();
if (oldValue !== newValue)
this.emit('change', { oldValue:oldValue, newValue:newValue, context:context });
return this; // for chaining
}
Characteristic.prototype.getDefaultValue = function() {
switch (this.props.format) {
case Characteristic.Formats.BOOL: return false;
case Characteristic.Formats.STRING: return "";
case Characteristic.Formats.ARRAY: return []; // who knows!
case Characteristic.Formats.DICTIONARY: return {}; // who knows!
case Characteristic.Formats.DATA: return ""; // who knows!
case Characteristic.Formats.TLV8: return ""; // who knows!
default: return this.props.minValue || 0;
}
}
Characteristic.prototype._assignID = function(identifierCache, accessoryName, serviceUUID, serviceSubtype) {
// generate our IID based on our UUID
this.iid = identifierCache.getIID(accessoryName, serviceUUID, serviceSubtype, this.UUID);
}
/**
* Returns a JSON representation of this Accessory suitable for delivering to HAP clients.
*/
Characteristic.prototype.toHAP = function(opt) {
// ensure our value fits within our constraints if present
var value = this.value;
if (this.props.minValue != null && value < this.props.minValue) value = this.props.minValue;
if (this.props.maxValue != null && value > this.props.maxValue) value = this.props.maxValue;
if (this.props.format != null) {
if (this.props.format === Characteristic.Formats.INT)
value = parseInt(value);
else if (this.props.format === Characteristic.Formats.UINT8)
value = parseInt(value);
else if (this.props.format === Characteristic.Formats.UINT16)
value = parseInt(value);
else if (this.props.format === Characteristic.Formats.UINT32)
value = parseInt(value);
else if (this.props.format === Characteristic.Formats.UINT64)
value = parseInt(value);
else if (this.props.format === Characteristic.Formats.FLOAT) {
value = parseFloat(value);
if (this.props.minStep != null) {
var pow = Math.pow(10, decimalPlaces(this.props.minStep));
value = Math.round(value * pow) / pow;
}
}
}
var hap = {
iid: this.iid,
type: this.UUID,
perms: this.props.perms,
format: this.props.format,
value: value,
description: this.displayName
// These properties used to be sent but do not seem to be used:
//
// events: false,
// bonjour: false
};
if (this.props.validValues != null && this.props.validValues.length > 0) {
hap['valid-values'] = this.props.validValues;
}
if (this.props.validValueRanges != null && this.props.validValueRanges.length > 0 && !(this.props.validValueRanges.length & 1)) {
hap['valid-values-range'] = this.props.validValueRanges;
}
// extra properties
if (this.props.unit != null) hap.unit = this.props.unit;
if (this.props.maxValue != null) hap.maxValue = this.props.maxValue;
if (this.props.minValue != null) hap.minValue = this.props.minValue;
if (this.props.minStep != null) hap.minStep = this.props.minStep;
// add maxLen if string length is > 64 bytes and trim to max 256 bytes
if (this.props.format === Characteristic.Formats.STRING) {
var str = new Buffer(value, 'utf8'),
len = str.byteLength;
if (len > 256) { // 256 bytes is the max allowed length
hap.value = str.toString('utf8', 0, 256);
hap.maxLen = 256;
} else if (len > 64) { // values below can be ommited
hap.maxLen = len;
}
}
// if we're not readable, omit the "value" property - otherwise iOS will complain about non-compliance
if (this.props.perms.indexOf(Characteristic.Perms.READ) == -1)
delete hap.value;
// delete the "value" property anyway if we were asked to
if (opt && opt.omitValues)
delete hap.value;
return hap;
}
// Mike Samuel
// http://stackoverflow.com/questions/10454518/javascript-how-to-retrieve-the-number-of-decimals-of-a-string-number
function decimalPlaces(num) {
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0));
}
| polo14va/HAP-NodeJS | lib/Characteristic.js | JavaScript | apache-2.0 | 11,072 |
/**
* ReMooz - Zoomer
*
* Inspired by so many boxes and zooms
*
* @version 1.0.4 + modified version for AppDen
*
* @license MIT-style license
* @author Harald Kirschner <mail [at] digitarald.de>
* @copyright Author
*/
var ReMooz = new Class({
Implements: [Events, Options, Chain],
options: {
link: null,
type: 'image',
container: null,
className: null,
centered: false,
dragging: true,
draggable: true,
closeOnClick: true,
shadow: (Browser.Engine.trident) ? 'onOpenEnd' : 'onOpen', // performance
resize: true,
margin: 20,
resizeFactor: 0.95,
resizeLimit: false, // {x: 640, y: 640}
fixedSize: false,
cutOut: true,
addClick: true,
opacityLoad: 0.6,
opacityResize: 1,
opacityTitle: 0.9,
resizeOptions: {},
fxOptions: {},
closer: true,
parse: false, // 'rel'
parseSecure: false,
temporary: false,
onBuild: $empty,
onLoad: $empty,
onOpen: $empty,
onOpenEnd: $empty,
onClose: $empty,
onCloseEnd: $empty,
generateTitle: function(el) {
var text = el.get('title');
if (!text) return false;
var title = text.split(' :: ');
var head = new Element('h6', {'html': title[0]});
return (title[1]) ? [head, new Element('p', {'html': title[1]})] : head;
}
},
initialize: function(element, options) {
this.element = $(element);
this.setOptions(options);
if (this.options.parse) {
var obj = this.element.getProperty(this.options.parse);
if (obj && (obj = JSON.decode(obj, this.options.parseSecure))) this.setOptions(obj);
}
var origin = this.options.origin;
this.origin = ((origin) ? $(origin) || this.element.getElement(origin) : null) || this.element;
this.link = this.options.link || this.element.get('href') || this.element.get('src');
this.container = $(this.options.container) || this.element.getDocument();
this.bound = {
'click': function(e) {
this.open.delay(1, this);
return false;
}.bind(this),
'close': this.close.bind(this),
'dragClose': function(e) {
if (e.rightClick) return;
this.close();
}.bind(this)
};
if (this.options.addClick) this.bindToElement();
},
destroy: function() {
if (this.box) this.box.destroy();
this.box = this.tweens = this.body = this.content = null;
},
bindToElement: function(element) {
($(element) || this.element).addClass('remooz-element').addEvent('click', this.bound.click);
return this;
},
getOriginCoordinates: function() {
var coords = this.origin.getCoordinates();
delete coords.right;
delete coords.bottom;
return coords;
},
open: function(e) {
if (this.opened) return (e) ? this.close() : this;
this.opened = this.loading = true;
if (!this.box) this.build();
this.coords = this.getOriginCoordinates();
this.coords.opacity = this.options.opacityLoad;
this.coords.display = '';
this.tweens.box.set(this.coords);
this.box.addClass('remooz-loading');
ReMooz.open(this.fireEvent('onLoad'));
this['open' + this.options.type.capitalize()]();
return this;
},
finishOpen: function() {
this.tweens.fade.start(0, 1);
if (this.options.draggable) this.drag.attach();
this.fireEvent('onOpenEnd').callChain();
},
close: function() {
if (!this.opened) return this;
this.opened = false;
ReMooz.close(this.fireEvent('onClose'));
if (this.loading) {
this.box.setStyle('display', 'none');
return this;
}
if (this.options.draggable) this.drag.detach();
this.tweens.fade.cancel().set(0).fireEvent('onComplete');
if (this.tweens.box.timer) this.tweens.box.clearChain();
var vars = this.getOriginCoordinates();
if (this.options.opacityResize != 1) vars.opacity = this.options.opacityResize;
this.tweens.box.start(vars).chain(this.closeEnd.bind(this));
return this;
},
closeEnd: function() {
if (this.options.cutOut) this.element.setStyle('visibility', 'visible');
this.box.setStyle('display', 'none');
this.fireEvent('onCloseEnd').callChain();
if (this.options.temporary) this.destroy();
},
openImage: function() {
var tmp = new Image();
tmp.onload = tmp.onabort = tmp.onerror = function(fast) {
this.loading = tmp.onload = tmp.onabort = tmp.onerror = null;
if (!tmp.width || !this.opened) {
this.fireEvent('onError').close();
return;
}
var to = {x: tmp.width, y: tmp.height};
if (!this.content) this.content = $(tmp).inject(this.body);
else tmp = null;
this[(this.options.resize) ? 'zoomRelativeTo' : 'zoomTo'].create({
'delay': (tmp && fast !== true) ? 1 : null,
'arguments': [to],
'bind': this
})();
}.bind(this);
tmp.src = this.link;
if (tmp && tmp.complete && tmp.onload) tmp.onload(true);
},
/**
* @todo Test implementation
*/
openElement: function() {
this.content = this.content || $(this.link) || $E(this.link);
if (!this.content) {
this.fireEvent('onError').close();
return;
}
this.content.inject(this.body);
this.zoomTo({x: this.content.scrollWidth, y: this.content.scrollHeight});
},
zoomRelativeTo: function(to) {
var scale = this.options.resizeLimit;
if (!scale) {
scale = this.container.getSize();
scale.x *= this.options.resizeFactor;
scale.y *= this.options.resizeFactor;
}
for (var i = 2; i--;) {
if (to.x > scale.x) {
to.y *= scale.x / to.x;
to.x = scale.x;
} else if (to.y > scale.y) {
to.x *= scale.y / to.y;
to.y = scale.y;
}
}
return this.zoomTo({x: to.x.toInt(), y: to.y.toInt()});
},
zoomTo: function(to) {
to = this.options.fixedSize || to;
var box = this.container.getSize(), scroll = this.container.getScroll();
var pos = (!this.options.centered) ? {
x: (this.coords.left + (this.coords.width / 2) - to.x / 2).toInt()
.limit(scroll.x + this.options.margin, scroll.x + box.x - this.options.margin - to.x),
y: (this.coords.top + (this.coords.height / 2) - to.y / 2).toInt()
.limit(scroll.y + this.options.margin, scroll.y + box.y - this.options.margin - to.y)
} : {
x: scroll.x + ((box.x - to.x) / 2).toInt(),
y: scroll.y + ((box.y - to.y) / 2).toInt()
};
if (this.options.cutOut) this.element.setStyle('visibility', 'hidden');
this.box.removeClass('remooz-loading');
var vars = {left: pos.x, top: pos.y, width: to.x, height: to.y};
if (this.options.opacityResize != 1) vars.opacity = [this.options.opacityResize, 1];
else this.box.set('opacity', 1);
this.tweens.box.start(vars).chain(this.finishOpen.bind(this));
this.fireEvent('onOpen');
},
build: function() {
this.addEvent('onBlur', function() {
this.focused = false;
this.box.removeClass('remooz-box-focus').setStyle('z-index', ReMooz.options.zIndex);
}, true);
this.addEvent('onFocus', function() {
this.focused = true;
this.box.addClass('remooz-box-focus').setStyle('z-index', ReMooz.options.zIndexFocus);
}, true);
var classes = ['remooz-box', 'remooz-type-' + this.options.type, 'remooz-engine-' + Browser.Engine.name + Browser.Engine.version];
if (this.options.className) classes.push(this.options.className);
this.box = new Element('div', {
'class': classes.join(' '),
'styles': {
'display': 'none',
'top': 0,
'left': 0,
'zIndex': ReMooz.options.zIndex
}
});
this.tweens = {
'box': new Fx.Morph(this.box, $merge({
'duration': 400,
'unit': 'px',
'transition': Fx.Transitions.Quart.easeOut,
'chain': 'cancel'
}, this.options.resizeOptions)
),
'fade': new Fx.Tween(null, $merge({
'property': 'opacity',
'duration': (Browser.Engine.trident) ? 0 : 300,
'chain': 'cancel'
}, this.options.fxOptions)).addEvents({
'onComplete': function() {
if (!this.element.get('opacity')) this.element.setStyle('display', 'none');
},
'onStart': function() {
if (!this.element.get('opacity')) this.element.setStyle('display', '');
}
}
)
};
this.tweens.fade.element = $$();
if (this.options.shadow) {
if (Browser.Engine.webkit420) {
this.box.setStyle('-webkit-box-shadow', '0 0 10px rgba(0, 0, 0, 0.7)');
} else if (!Browser.Engine.trident4) {
var shadow = new Element('div', {'class': 'remooz-bg-wrap'}).inject(this.box);
['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'].each(function(dir) {
new Element('div', {'class': 'remooz-bg remooz-bg-' + dir}).inject(shadow);
});
this.tweens.bg = new Fx.Tween(shadow, {
'property': 'opacity',
'chain': 'cancel'
}).set(0);
this.addEvent(this.options.shadow, this.tweens.bg.set.bind(this.tweens.bg, 1), true);
this.addEvent('onClose', this.tweens.bg.set.bind(this.tweens.bg, 0), true);
}
}
if (this.options.closer) {
var closer = new Element('a', {
'class': 'remooz-btn-close',
'events': {'click': this.bound.close}
}).inject(this.box);
this.tweens.fade.element.push(closer);
}
this.body = new Element('div', {'class': 'remooz-body'}).inject(this.box);
var title = this.options.title || this.options.generateTitle.call(this, this.element);
if (title) { // thx ie6
var title = new Element('div', {'class': 'remooz-title'}).adopt(
new Element('div', {'class': 'remooz-title-bg', 'opacity': this.options.opacityTitle}),
new Element('div', {'class': 'remooz-title-content'}).adopt(title)
).inject(this.box);
this.tweens.fade.element.push(title);
}
this.tweens.fade.set(0).fireEvent('onComplete');
if (this.options.draggable) {
this.drag = new Drag.Move(this.box, {
'snap': 15,
'preventDefault': true,
'onBeforeStart': function() {
if (!this.focused && !this.loading) ReMooz.focus(this);
else if (this.loading || this.options.closeOnClick) this.box.addEvent('mouseup', this.bound.dragClose);
}.bind(this),
'onSnap': function() {
this.box.removeEvent('mouseup', this.bound.dragClose);
if (!this.options.dragging) this.drag.stop();
else this.box.addClass('remooz-box-dragging');
}.bind(this),
'onComplete': function() {
this.box.removeClass('remooz-box-dragging');
}.bind(this)
});
this.drag.detach();
}
this.fireEvent('onBuild', [this.box, this.element]);
this.box.inject(this.element.getDocument().body);
}
});
ReMooz.factory = function(extended) {
return $extend(this, extended);
};
ReMooz.factory(new Options).factory({
options: {
zIndex: 41,
zIndexFocus: 42,
query: 'a.remooz',
modal: false
},
assign: function(elements, options) {
return $$(elements).map(function(element) {
return new ReMooz(element, options);
}, this);
},
stack: [],
open: function(obj) {
var last = this.stack.getLast();
this.focus(obj);
if (last && this.options.modal) last.close();
},
close: function(obj) {
var length = this.stack.length - 1;
if (length > 1 && this.stack[length] == obj) this.focus(this.stack[length - 1]);
this.stack.erase(obj);
},
focus: function(obj) {
var last = this.stack.getLast();
obj.fireEvent('onFocus', [obj]);
if (last == obj) return;
if (last) last.fireEvent('onBlur', [last]);
this.stack.erase(obj).push(obj);
}
}); | yuanyangwu/yuanyangwu.github.io | remooz/ReMooz.js | JavaScript | apache-2.0 | 10,976 |
ctx.fillStyle = '#000000';
ctx.strokeStyle = "blue";
ctx.moveTo(125*ratio, 10*ratio);
ctx.lineTo(125*ratio, 300*ratio);
ctx.stroke();
ctx.font = 15*ratio+"px Arial-MT";
ctx.textAlign = "start";
ctx.fillText("textAlign=start", 125*ratio, 10*ratio);
ctx.textAlign = "end";
ctx.fontSize = 15**ratio+'px';
ctx.fillText("textAlign=end", 125*ratio, 50*ratio);
ctx.textAlign = "left";
ctx.fillText("textAlign=left", 125*ratio, 100*ratio);
ctx.textAlign = "center";
ctx.fillText("textAlign=center", 125*ratio, 150*ratio);
ctx.textAlign = "right";
ctx.fillText("textAlign=right", 125*ratio, 200*ratio);
| jwxbond/GCanvas | core/test/benchmarks/font/tc_2d_text_textAlign.js | JavaScript | apache-2.0 | 594 |
// flow-typed signature: 87555178eb3cd25af282c797a3e80cb3
// flow-typed version: <<STUB>>/gulp-rename_v1.2.2/flow_v0.41.0
/**
* This is an autogenerated libdef stub for:
*
* 'gulp-rename'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'gulp-rename' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
// Filename aliases
declare module 'gulp-rename/index' {
declare module.exports: $Exports<'gulp-rename'>;
}
declare module 'gulp-rename/index.js' {
declare module.exports: $Exports<'gulp-rename'>;
}
| kjirou/developers-defense | flow-typed/npm/gulp-rename_vx.x.x.js | JavaScript | apache-2.0 | 855 |
window.LT = {
alert: function(data){
alert(data);
},
confirm: function(data){
if(confirm(data)){
return true;
}
return false;
},
host: '/live-test/'
};
//鼠标经过用户中心
$('.user-center').mouseover(function(){
$('.user-center-sub').show();
});
$('.user-center').mouseout(function(){
$('.user-center-sub').hide();
}); | huolong1992/live-test | scripts/js/module/common.js | JavaScript | apache-2.0 | 397 |
$(function() {
$(window).on('load', function() {
waterfall();
//存储将要加载的图片路径集合
var dataInt = { 'data': [{ 'src': '0.jpg' }, { 'src': '1.jpg' }, { 'src': '2.jpg' }, { 'src': '3.jpg' }] };
$(window).on("scroll", function() {
if (ckeckScrollSlide()) { //判断是否需要加载图片
$(dataInt.data).each(function(index, value) {
var mainBox = $('#main');
var oPin = $('<div>').addClass('pin').appendTo($(mainBox));
var oBox = $('<div>').addClass('box').appendTo($(oPin));
$('<img>').attr('src', './images/' + $(value).attr('src')).appendTo($(oBox));
})
waterfall();
}
});
// 浏览器窗口大小发生改变时,重新布局
$(window).resize(function(event) {
waterfall();
});
});
});
//将图片瀑布流布局的函数
function waterfall() {
var $oPins = $('#main>div');
var pinW = $oPins.eq(0).outerWidth(); //包裹图片最外层盒子的宽度
var cols = Math.floor($(window).width() / pinW); //图片排列的列数
$('#main').width(cols * pinW).css('margin', '0 auto');
var attrH = []; //放置每一个包裹图片最外层盒子的高度
$oPins.each(function(index, value) {
value.style.cssText ='';
if (index < cols) {
attrH.push($oPins.eq(index).outerHeight()); //排列第一行
} else {
var minH = Math.min.apply(null, attrH); //找出高度中的最小值
var minHIndex = $.inArray(minH, attrH); //最小值对应的索引
$(value).css({
'position': 'absolute',
'top': minH + 'px',
'left': minHIndex * pinW + 'px'
});
attrH[minHIndex] += $oPins.eq(index).outerHeight(); //改变最小值的高度
}
})
}
//判断是否需要加载图片的函数
function ckeckScrollSlide() {
var lastBox = $('#main>div').last();
var lastDis = lastBox.offset().top + Math.floor($(lastBox).outerHeight() / 3);
var scrollUp = $(window).scrollTop();
var height = $(window).height();
return (lastDis < scrollUp + height) ? true : false;
}
| despise-all/front-demo | water fall/js/waterfall.js | JavaScript | apache-2.0 | 2,299 |
/*
* Copyright 2015 Caleb Brose, Chris Fogerty, Rob Sheehy, Zach Taylor, Nick Miller
*
* 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.
*/
/*
* instances/containerController.js
* Manages interactions for a single Docker container
*/
function containerController($scope, $routeParams, $sce, $timeout, $interval, dockerService, instanceModel) {
'use strict';
$scope.host = $routeParams.host;
$scope.id = $routeParams.id;
$scope.logs = "";
dockerService.d('containers.inspect', {
host: $scope.host,
id: $scope.id
});
var loadLogs = function() {
dockerService.d('containers.logs', {
host: $scope.host,
id: $scope.id,
responseType: 'text',
query: {
stderr: '1',
stdout: '1',
timestamps: '0',
follow: '0'
}
});
};
loadLogs();
var logInterval, logsElement = $('.logs');
$scope.$listenTo(instanceModel, function () {
$scope.info = instanceModel.getContainer($scope.id);
$scope.logs = $sce.trustAsHtml(instanceModel.getContainerLogs($scope.id));
if ($scope.follow) {
$timeout(function () {
logsElement.scrollTop(logsElement[0].scrollHeight);
}, 0);
}
if ($scope.info) {
var ds = $scope.info.State;
$scope.state = {
running: ds.Running && !ds.Paused,
paused: ds.Paused,
restarting: ds.Restarting,
stopped: !(ds.Running || ds.Paused || ds.Restarting)
};
}
});
$scope.followLogs = function (_id) {
if ($scope.follow) {
logInterval = $interval(loadLogs, 750);
logsElement.scrollTop(logsElement[0].scrollHeight);
} else {
$interval.cancel(logInterval);
logInterval = undefined;
}
};
$scope.start = function (_id) {
dockerService.d('containers.start', {
host: $scope.host,
id: _id
});
};
$scope.stop = function (_id) {
dockerService.d('containers.stop', {
host: $scope.host,
id: _id
});
};
$scope.pause = function (_id) {
dockerService.d('containers.pause', {
host: $scope.host,
id: _id
});
};
$scope.unpause = function (_id) {
dockerService.d('containers.unpause', {
host: $scope.host,
id: _id
});
};
$scope.$on('$destroy', function() {
if (!_.isUndefined(logInterval)) {
$interval.cancel(logInterval);
logInterval = undefined;
}
});
}
containerController.$inject = ['$scope', '$routeParams', '$sce', '$timeout', '$interval', 'dockerService', 'instanceModel'];
module.exports = containerController;
| lighthouse/harbor | app/js/instances/containerController.js | JavaScript | apache-2.0 | 3,438 |
"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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var Path = require("path");
var FS = require("fs");
var _ = require("lodash");
var component_1 = require("../../component");
var options_1 = require("../options");
var declaration_1 = require("../declaration");
var typescript_1 = require("../sources/typescript");
var TSConfigReader = (function (_super) {
__extends(TSConfigReader, _super);
function TSConfigReader() {
_super.apply(this, arguments);
}
TSConfigReader.prototype.initialize = function () {
this.listenTo(this.owner, options_1.DiscoverEvent.DISCOVER, this.onDiscover, -100);
};
TSConfigReader.prototype.onDiscover = function (event) {
if (TSConfigReader.OPTIONS_KEY in event.data) {
this.load(event, event.data[TSConfigReader.OPTIONS_KEY]);
}
else if (this.application.isCLI) {
var file = Path.resolve('tsconfig.json');
if (FS.existsSync(file)) {
this.load(event, file);
}
}
};
TSConfigReader.prototype.load = function (event, fileName) {
if (!FS.existsSync(fileName)) {
event.addError('The tsconfig file %s does not exist.', fileName);
return;
}
var data = require(fileName);
if (typeof data !== "object") {
event.addError('The tsconfig file %s does not return an object.', fileName);
return;
}
if ("files" in data && _.isArray(data.files)) {
event.inputFiles = data.files;
}
if ("compilerOptions" in data) {
var ignored = typescript_1.TypeScriptSource.IGNORED;
var compilerOptions = _.clone(data.compilerOptions);
for (var _i = 0, ignored_1 = ignored; _i < ignored_1.length; _i++) {
var key = ignored_1[_i];
delete compilerOptions[key];
}
_.merge(event.data, compilerOptions);
}
if ("typedocOptions" in data) {
_.merge(event.data, data.typedocOptions);
}
};
TSConfigReader.OPTIONS_KEY = 'tsconfig';
__decorate([
component_1.Option({
name: TSConfigReader.OPTIONS_KEY,
help: 'Specify a js option file that should be loaded. If not specified TypeDoc will look for \'typedoc.js\' in the current directory.',
type: declaration_1.ParameterType.String,
hint: declaration_1.ParameterHint.File
})
], TSConfigReader.prototype, "options", void 0);
TSConfigReader = __decorate([
component_1.Component({ name: "options:tsconfig" })
], TSConfigReader);
return TSConfigReader;
}(options_1.OptionsComponent));
exports.TSConfigReader = TSConfigReader;
| SierraSoftworks/typedoc | lib/utils/options/readers/tsconfig.js | JavaScript | apache-2.0 | 3,540 |
'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import Tree from '../src';
$.getJSON('./data.json',(data) => {
let treeDatas = data.datas.code.rows;
ReactDOM.render(<Tree
data={treeDatas}
multiple={false}
showIcon={true}
defaultExpandAll={true}
defaultSelectedKeys={["000012", "000406", "000001"]}
/>, document.getElementById('main'));
});
| wisedu/bh-react | src/tree/examples/tree.js | JavaScript | apache-2.0 | 422 |
let pre1 = new Preview({ el: $('.js-upload') }).show()
$('.js-label').on('click', evt => {
$('.js-label').removeClass('active')
$(evt.target).addClass('active')
})
new Counter({ el: $('.js-counter') })
| Re-Rabbit/pandora | pages/ysd/box.js | JavaScript | apache-2.0 | 212 |
/*jslint devel: true, node: true, bitwise: false, debug: false, eqeq: false,
evil: false, forin: false, newcap: false, nomen: false, plusplus: false,
regexp: false, sub: false, vars: false, undef: false, unused: false,
white: false, quotmark: single, indent: 2, maxlen: 80 */
'use strict';
// node built in libraries.
var fs = require('fs');
var sys = require('sys');
var exec = require('child_process').exec;
var stdin = process.openStdin();
var path = require('path');
// node modules.
var _ = require('underscore');
// helper libraries
var strings = require('./strings.js');
// output result to standard console.
function puts(error, stdout, stderr) {
sys.puts(stdout);
}
// path where your Android apk is build with Titanium.
// absolute paths
var androidSrcPath = strings.androidSrcPath,
androidSrcFilename = strings.androidSrcFilename,
androidDestPath = path.resolve(process.cwd(),
strings.androidDestPath),
androidDestFilename = strings.androidDestFilename,
remaxMaxVersionNumber = strings.remaxMaxVersionNumber,
unencryptedPath = path.resolve(process.cwd(),
strings.unencryptedPath),
unencryptedFilename = strings.unencryptedFilename;
var commands = {
'git' : function () {
exec('git pull', puts);
// add a promise here.
exec('git status', puts);
},
'build' : function (args) {
// cmd : build <android | iphone | ipad>
// build for android, ios, iphone, ipad -
// defaulted to android in this case.
var buildDevice = (args[0] || 'android' || 'iphone' || 'ipad');
exec('titanium build -p ' + buildDevice + ' -b', puts);
},
'copy' : function () {
// from - androidSrcPath + androidSrcFilename
fs.readFile(androidSrcPath + androidSrcFilename, function (err, data) {
if (err) throw err;
// var androidDestFilename;
fs.readdir(androidDestPath, function (err, files) {
var version, versionNum = [];
_.each(files, function (file) {
version = file.split('-')[4];
if (version) {
versionNum.push((+(version).split('.')[2]));
}
});
remaxMaxVersionNumber = (+_.max(versionNum));
androidDestFilename =
'homes-app-remax-alloy-v0.2.' + (remaxMaxVersionNumber + (+1)) + '.apk';
// write 'data' to (destination)
// - androidDestPath + androidDestFilename
fs.writeFile(androidDestPath + '/' + androidDestFilename, data,
function (err) {
if (err) throw err;
console.log('copy completed.');
});
});
});
},
'append' : function () {
// append : appends the link, version entry
// to apps.html
var unencryptedData, length, remaxHttpLink;
unencryptedData = require(unencryptedPath + unencryptedFilename).apps;
if (unencryptedData[0].name === 'Remax') {
if (unencryptedData[0].Versions[1].name === 'Android') {
// add dynamically.
remaxHttpLink =
'{"link":"http://apptest.homes.com/remax/v2.0/android/' +
'homes-app-remax-alloy-v0.2.' + (remaxMaxVersionNumber + (+1)) +
'apk","version":"v0.2.' + (remaxMaxVersionNumber + (+1)) + '"}';
length = unencryptedData[0].Versions[1].links.length;
unencryptedData[0].Versions[1].links[length] =
JSON.parse(remaxHttpLink);
// Writing as a Javascript export variable.
unencryptedData = 'var apps = ' +
JSON.stringify(unencryptedData, null, 2) +
';exports.apps = apps;';
// Write to - unencryptedPath + unencryptedFilename with
// updated unencryptedData.
fs.writeFile(unencryptedPath + unencryptedFilename, unencryptedData,
function (err) {
if (err) throw err;
console.log('update complete');
});
}
}
}
};
console.log('Enter Your Choice.\n' +
'1. Pull latest code from git');
stdin.on('data', function (input) {
console.log('User Choice is ' + input.toString());
var
matches = input.toString().match(/(\w+)(.*)/),
command = matches[1].toLowerCase(),
args = matches[2].trim().split(/\s+/);
commands[command](args);
});
| rnagella/02_orientation | tibuildautomation.js | JavaScript | apache-2.0 | 4,185 |
import BreadcrumbSegment
from "../../../../../../../src/js/components/BreadcrumbSegment";
import MesosStateStore
from "../../../../../../../src/js/stores/MesosStateStore";
class TaskDetailBreadcrumb extends BreadcrumbSegment {
constructor() {
super(...arguments);
this.store_listeners = [
{ name: "state", events: ["success"], listenAlways: false }
];
}
componentDidMount() {
this.updateCrumbStatus();
}
componentWillReceiveProps() {
this.updateCrumbStatus();
}
onStateStoreSuccess() {
this.setState({ isLoadingCrumb: false });
}
updateCrumbStatus() {
const taskID = this.getTaskName();
if (taskID) {
this.setState({ isLoadingCrumb: false });
}
}
getTaskName() {
const { taskID } = this.props.params;
if (MesosStateStore.get("lastMesosState").slaves == null) {
return null;
}
return MesosStateStore.getTaskFromTaskID(taskID).getName();
}
getCrumbLabel() {
return this.getTaskName();
}
}
module.exports = TaskDetailBreadcrumb;
| jcloud-shengtai/dcos-ui_CN | plugins/services/src/js/pages/nodes/breadcrumbs/TaskDetailBreadcrumb.js | JavaScript | apache-2.0 | 1,044 |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
'use strict';
function main(resource) {
// [START securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_async]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* REQUIRED: The resource for which the policy is being requested.
* See the operation documentation for the appropriate value for this field.
*/
// const resource = 'abc123'
/**
* OPTIONAL: A `GetPolicyOptions` object for specifying options to
* `GetIamPolicy`. This field is only used by Cloud IAM.
*/
// const options = {}
// Imports the Securitycenter library
const {SecurityCenterClient} = require('@google-cloud/security-center').v1beta1;
// Instantiates a client
const securitycenterClient = new SecurityCenterClient();
async function callGetIamPolicy() {
// Construct request
const request = {
resource,
};
// Run request
const response = await securitycenterClient.getIamPolicy(request);
console.log(response);
}
callGetIamPolicy();
// [END securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_async]
}
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
| googleapis/nodejs-security-center | samples/generated/v1beta1/security_center.get_iam_policy.js | JavaScript | apache-2.0 | 2,036 |
import {firstDefinedValue} from "utilities.js";
// ${makeTab("?mock_urls.blockpy", "URL Data", true)}
const makeTab = function(filename, friendlyName, hideIfEmpty, notInstructor) {
if (friendlyName === undefined) {
friendlyName = filename;
}
let instructorFileClass = "";
let hideIfNotInstructor = "true";
if (!notInstructor) {
instructorFileClass = "blockpy-file-instructor";
hideIfNotInstructor = "display.instructor()";
}
return `
<li class="nav-item ${instructorFileClass}">
<a class="nav-link" href="#"
data-toggle="tab"
data-bind="css: {active: display.filename() === '${filename}'},
click: display.filename.bind($data, '${filename}'),
visible: (!${hideIfEmpty} || ui.files.hasContents('${filename}')) && ${hideIfNotInstructor}">
${friendlyName}</a>
</li>`;
};
export let FILES_HTML = `
<div class="col-md-12 blockpy-panel blockpy-files"
data-bind="visible: ui.files.visible">
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item">
<strong>View: </strong>
</li>
${makeTab("answer.py", undefined, undefined, true)}
${makeTab("!instructions.md", "Instructions")}
${makeTab("!assignment_settings.blockpy", "Settings")}
${makeTab("^starting_code.py", "Starting Code")}
${makeTab("!on_run.py", "On Run")}
${makeTab("!on_change.py", "On Change", true)}
${makeTab("!on_eval.py", "On Eval", true)}
${makeTab("!sample_submissions.blockpy", "Sample Submissions", true)}
${makeTab("!tags.blockpy", "Tags", true)}
<!-- ko foreach: assignment.extraInstructorFiles -->
<li class="nav-item"
data-bind="css: {'blockpy-file-instructor': !filename().startsWith('&')},
visible: filename().startsWith('&') || $root.display.instructor() ">
<a class="nav-link" href="#"
data-toggle="tab"
data-bind="css: {active: $root.display.filename() === filename(),
uneditable: filename().startsWith('&')},
click: $root.display.filename.bind($data, filename()),
text: $root.ui.files.displayFilename(filename())">
</a>
</li>
<!-- /ko -->
<!-- ko foreach: assignment.extraStartingFiles -->
<li class="nav-item blockpy-file-instructor"
data-bind="visible: $root.display.instructor()">
<a class="nav-link" href="#"
data-toggle="tab"
data-bind="css: {active: $root.display.filename() === filename()},
click: $root.display.filename.bind($data, filename()),
text: filename">
</a>
</li>
<!-- /ko -->
<!-- ko foreach: submission.extraFiles -->
<li class="nav-item">
<a class="nav-link" href="#"
data-toggle="tab"
data-bind="css: {active: $root.display.filename() === filename()},
click: $root.display.filename.bind($data, filename()),
text: $root.ui.files.displayFilename(filename())">
</a>
</li>
<!-- /ko -->
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown"
role="button" aria-haspopup="true" aria-expanded="false">Add New</a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item blockpy-file-instructor" href="#"
data-bind="hidden: ui.files.hasContents('?mock_urls.blockpy'),
click: ui.files.add.bind($data, '?mock_urls.blockpy')">URL Data</a>
<a class="dropdown-item blockpy-file-instructor" href="#"
data-bind="hidden: ui.files.hasContents('?tags.blockpy')">Tags</a>
<a class="dropdown-item blockpy-file-instructor" href="#"
data-bind="hidden: ui.files.hasContents('?sample_submissions.blockpy')">Sample Submissions</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item blockpy-file-instructor" href="#"
data-bind="hidden: assignment.onChange,
click: ui.files.add.bind($data, '!on_change.py')">On Change</a>
<a class="dropdown-item blockpy-file-instructor" href="#"
data-bind="hidden: assignment.onEval,
click: ui.files.add.bind($data, '!on_eval.py')">On Eval</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item blockpy-file-instructor" href="#"
data-bind="click: ui.files.add.bind($data, 'starting')">Starting File</a>
<a class="dropdown-item blockpy-file-instructor" href="#"
data-bind="click: ui.files.add.bind($data, 'instructor')">Instructor File</a>
<a class="dropdown-item" href="#"
data-bind="click: ui.files.add.bind($data, 'student')">Student File</a>
</div>
</li>
</ul>
</div>
`;
const NEW_INSTRUCTOR_FILE_DIALOG_HTML = `
<form>
<div class="form-group row">
<!-- Filename -->
<div class="col-sm-2 text-right">
<label for="blockpy-instructor-file-dialog-filename">Filename:</label>
</div>
<div class="col-sm-10">
<input type="text" class="form-control blockpy-instructor-file-dialog-filename"
id="blockpy-instructor-file-dialog-filename">
</div>
<!-- Filetype -->
<div class="col-sm-2 text-right mt-2">
<label for="blockpy-instructor-file-dialog-filetype">Filetype: </label>
</div>
<div class="col-sm-10">
<span class="blockpy-instructor-file-dialog-filetype"
id="blockpy-instructor-file-dialog-filetype"></span>
</div>
<!-- Inaccessible to student? -->
<div class="col-sm-2 text-right mt-2">
<label for="blockpy-instructor-file-dialog-namespace">Namespace: </label>
</div>
<div class="col-sm-4">
<select class="form-control blockpy-instructor-file-dialog-namespace"
id="blockpy-instructor-file-dialog-namespace">
<option value="!">Completely inaccessible</option>
<option value="?">Hidden from student, accessible programatically</option>
<option value="&">Visible to student, but not editable</option>
</select>
</div>
</div>
</form>
`;
/**
* Filenames live in one of five possible namespaces:
* Instructor (!): Invisible to the student under all circumstances
* Start Space (^): Used to reset the student namespace
* Student Space (): Visible to the student when display.hideFiles is not true, able to be edited
* Hidden Space (?): Not directly visible to the student, but accessible programmatically
* Read-only Space (&): An instructor file type visible to the student, but is uneditable by them
* Secret Space ($): Not visible from the menu at all, some other mechanism controls it
* Generated Space (*): Visible to the student, but destroyed after Engine.Clear. Can shadow an actual file.
* Concatenated Space (#): Used when bundling a space for the server.
*/
export let STARTING_FILES = [
// Submission
"answer.py",
// Instructor files
"!instructions.md",
"!assignment_settings.blockpy",
"^starting_code.py",
"!on_run.py",
"$settings.blockpy",
];
export const BASIC_NEW_FILES = [
"!on_change.py",
"!on_eval.py",
"?mock_urls.blockpy",
"!tags.blockpy",
"!sample_submissions.blockpy"
];
const INSTRUCTOR_DIRECTORY = "_instructor/";
const STUDENT_DIRECTORY = "_student/";
const SearchModes = {
EVERYWHERE: "EVERYWHERE",
START_WITH_INSTRUCTOR: "START_WITH_INSTRUCTOR",
ONLY_STUDENT_FILES: "ONLY_STUDENT_FILES"
};
const DELETABLE_SIMPLE_FILES = ["!on_change.py", "!on_eval.py"];
export const UNDELETABLE_FILES = ["answer.py", "!instructions.md", "!assignment_settings.py",
"^starting_code.py", "!on_run.py", "$settings.blockpy"];
export const UNRENAMABLE_FILES = ["answer.py", "!instructions.md", "!assignment_settings.py",
"^starting_code.py", "!on_run.py", "$settings.blockpy",
"!on_change.py", "!on_eval.py", "?mock_urls.blockpy",
"!tags.blockpy", "!sample_submissions.blockpy"];
class BlockPyFile {
constructor(main, filename, contents) {
this.main = main;
this.filename = filename;
this.contents = contents || "";
this.owner = null;
this.handle = null;
}
}
export function makeModelFile(filename, contents) {
return {"filename": ko.observable(filename), contents: ko.observable(contents || "")};
}
function makeMockModelFile(filename, contents) {
return { filename: () => filename, contents: () => contents };
}
export function loadConcatenatedFile(concatenatedFile, modelFileList) {
if (concatenatedFile) {
let files = JSON.parse(concatenatedFile);
let modelFiles = [];
for (let filename in files) {
if (files.hasOwnProperty(filename)) {
modelFiles.push(makeModelFile(filename, files[filename]));
}
}
//files = files.map(file => makeModelFile(file.filename, file.contents));
modelFileList(modelFiles);
} else {
modelFileList([]);
}
}
export function createConcatenatedFile(modelFileList) {
return JSON.stringify(modelFileList().map(file => {
return {
filename: file.filename(),
contents: file.contents()
};
}));
}
export function observeConcatenatedFile(modelFileList) {
return ko.pureComputed(() => {
let result = {};
modelFileList().forEach(file =>
result[file.filename()] = file.contents());
return JSON.stringify(result);
});
}
/**
* Abstracts away database logic
*/
export class BlockPyFileSystem {
constructor(main) {
this.main = main;
this.files_ = {};
this.mountFiles();
this.watchModel();
this.watches_ = {};
this.main.model.display.instructor.subscribe((visiblity)=> {
$(".blockpy-file-instructor").toggle(visiblity);
});
}
watchFile(filename, callback) {
if (!(filename in this.watches_)) {
this.watches_[filename] = [];
}
this.watches_[filename].push(callback);
}
stopWatchingFile(filename) {
delete this.watches_[filename];
}
watchModel() {
let filesystem = this;
[this.main.model.submission.extraFiles,
this.main.model.assignment.extraStartingFiles,
this.main.model.assignment.extraInstructorFiles].forEach(fileArray =>
fileArray.subscribe(function(changes) {
changes.forEach(function (change) {
let modelFile = change.value;
if (change.status === "added") {
// Track new file
let file = filesystem.newFile(modelFile.filename(), modelFile.contents(), modelFile.contents);
filesystem.notifyWatches(file);
} else if (change.status === "deleted") {
// Delete file
filesystem.deleteFileLocally_(modelFile.filename);
}
});
}, this, "arrayChange")
);
}
// answer.py
// => subscribe to first element of submission.code)
// !on_run.py, !on_change.py, !on_eval.py
// => subscribe to relevant assignment.<whatever>
// ^starting_code.py
// => subscribe to first element of assignment.startingCode
// ^whatever
// => subscribe to rest of the elements of assignment.startingCode
// !whatever or ?whatever
// => subscribe to elements of assignment.extraFiles
// Otherwise:
// => subscribe to rest of the elements of submission.code
/**
* New special files need to be registered here
* @param file {BlockPyFile}
* @private
*/
observeFile_(file) {
if (file.filename === "answer.py") {
file.handle = this.main.model.submission.code;
} else if (file.filename === "!on_run.py") {
file.handle = this.main.model.assignment.onRun;
} else if (file.filename === "!on_change.py") {
file.handle = this.main.model.assignment.onChange;
} else if (file.filename === "!on_eval.py") {
file.handle = this.main.model.assignment.onEval;
} else if (file.filename === "!instructions.md") {
file.handle = this.main.model.assignment.instructions;
} else if (file.filename === "^starting_code.py") {
file.handle = this.main.model.assignment.startingCode;
} else if (file.filename === "?mock_urls.blockpy") {
this.observeInArray_(file, this.main.model.assignment.extraInstructorFiles);
} else if (file.filename === "!tags.blockpy") {
file.handle = this.main.model.assignment.tags;
} else if (file.filename === "!assignment_settings.blockpy") {
file.handle = this.main.model.assignment.settings;
} else if (file.filename === "$settings.blockpy") {
file.handle = this.main.model.display;
} else if (file.filename.startsWith("^")) {
this.observeInArray_(file, this.main.model.assignment.extraStartingFiles);
} else if (file.filename.startsWith("!") ||
file.filename.startsWith("?") ||
file.filename.startsWith("&")) {
this.observeInArray_(file, this.main.model.assignment.extraInstructorFiles);
} else {
this.observeInArray_(file, this.main.model.submission.extraFiles);
}
}
observeInArray_(file, array) {
file.owner = array;
let codeBundle = file.owner();
for (let i=0; i < codeBundle.length; i++) {
if (codeBundle[i].filename() === file.filename) {
file.handle = codeBundle[i].contents;
}
}
if (file.handle === null) {
let newFile = makeModelFile(file.filename);
file.handle = newFile.contents;
array.push(newFile);
}
}
mountFiles() {
this.newFile("answer.py");
this.newFile("^starting_code.py");
this.newFile("!on_run.py");
this.newFile("!instructions.md");
this.newFile("!assignment_settings.blockpy");
}
dismountExtraFiles() {
for (let name in this.files_) {
if (this.files_.hasOwnProperty(name)) {
if (UNDELETABLE_FILES.indexOf(name) === -1) {
delete this.files_[name];
delete this.watches_[name];
}
}
}
// submission.codeTODO: Shouldn't we notify the UI that the file was deleted?
}
newFile(filename, contents, modelFile) {
if (filename in this.files_) {
// File already exists! Just update its handle
let existingFile = this.files_[filename];
if (modelFile === undefined) {
this.observeFile_(existingFile);
} else {
existingFile.handle = modelFile;
}
existingFile.handle(contents || "");
return existingFile;
} else {
// File does not exist
let newFile = new BlockPyFile(this.main, filename);
this.files_[filename] = newFile;
if (modelFile === undefined) {
this.observeFile_(newFile);
} else {
newFile.handle = modelFile;
}
if (contents !== undefined) {
newFile.handle(contents);
}
return newFile;
}
}
writeFile(filename, contents) {
contents = contents || "";
this.files_[filename].handle(contents);
}
readFile(filename) {
return this.files_[filename].handle();
}
getFile(filename) {
return this.files_[filename];
}
/**
*
* @param filename
* @returns {boolean|object} The info about the file, or false if it could not be deleted
*/
deleteFile(filename) {
if (DELETABLE_SIMPLE_FILES.indexOf(filename) !== -1) {
let file = this.deleteFileLocally_(filename);
file.handle(null);
return true;
} else if (this.files_[filename].owner === null) {
return false;
} else {
// Triggers a callback to eventually call deleteFileLocally_
let found = this.files_[filename].owner.remove(modelFile => modelFile.filename === filename);
return found || false;
}
}
deleteFileLocally_(filename) {
let file = this.files_[filename];
delete this.files_[filename];
if (filename in this.watches_) {
this.watches_[filename].forEach(callback => callback.deleted());
}
return file;
}
notifyWatches(file) {
if (file.filename in this.watches_) {
this.watches_[file.filename].forEach(callback => callback.updated(file));
}
}
searchForFile(name, studentSearch) {
/*
files.*
_instructor/files.*
_student/files.*
If a student searches for a file, it checks the "?", "&", "*", "" namespaces
import helper => "./helper.py"
open("external.json") => "external.json"
If an instructor searches for a file, it checks "!", "^", "?", "&", "*", "" namespaces
To explicitly search instructor namespaces first
import _instructor.helper => "./instructor/helper.py"
open("_instructor/external.json") => "_instructor/external.json"
to allow student files to override:
import helper => "./helper.py"
open("external.json") => "external.json"
to only check student files, prepend with _student
*/
// Chop off starting "./"
if (name.startsWith("./")) {
name = name.slice(2);
}
let searchMode = SearchModes.EVERYWHERE;
// Should the search be start with instructor side?
if (name.startsWith(INSTRUCTOR_DIRECTORY)) {
name = name.slice(INSTRUCTOR_DIRECTORY.length);
searchMode = SearchModes.START_WITH_INSTRUCTOR;
}
// Should the search be limited to the student mode?
if (name.startsWith(STUDENT_DIRECTORY)) {
name = name.slice(STUDENT_DIRECTORY.length);
searchMode = SearchModes.ONLY_STUDENT_FILES;
} else if (studentSearch) {
searchMode = SearchModes.ONLY_STUDENT_FILES;
}
// Shortcut for instructor versions
let extraStudentFiles = this.main.model.submission.extraFiles();
let extraInstructorFiles = this.main.model.assignment.extraInstructorFiles();
let extraStartingFiles = this.main.model.assignment.extraStartingFiles();
// Check special files (TODO: how would an instructor access "./_instructor/answer.py"?
let specialFile = this.searchForSpecialFiles_(name, searchMode);
if (specialFile !== undefined) {
return specialFile;
}
// Start looking through possible files
let studentVersion = this.searchForFileInList_(extraStudentFiles, name);
let generatedVersion = this.searchForFileInList_(extraStudentFiles, "*"+name);
let defaultVersion = this.searchForFileInList_(extraInstructorFiles, "&"+name);
if (searchMode === SearchModes.ONLY_STUDENT_FILES) {
return firstDefinedValue(defaultVersion, studentVersion, generatedVersion);
}
let instructorVersion = this.searchForFileInList_(extraInstructorFiles, "!"+name);
let hiddenVersion = this.searchForFileInList_(extraInstructorFiles, "?"+name);
let startingVersion = this.searchForFileInList_(extraStartingFiles, "^"+name);
if (searchMode === SearchModes.START_WITH_INSTRUCTOR) {
return firstDefinedValue(instructorVersion, hiddenVersion, startingVersion,
defaultVersion, studentVersion, generatedVersion);
} else if (searchMode === SearchModes.EVERYWHERE) {
return firstDefinedValue(defaultVersion, studentVersion, generatedVersion,
instructorVersion, hiddenVersion, startingVersion);
}
}
searchForFileInList_(modelList, filename) {
for (let i=0; i < modelList.length; i++) {
if (modelList[i].filename() === filename) {
return modelList[i];
}
}
return undefined;
}
searchForSpecialFiles_(filename, searchMode) {
if (searchMode === SearchModes.ONLY_STUDENT_FILES) {
if (filename === "answer.py") {
return makeMockModelFile("_instructor/answer.py", this.main.model.submission.code());
}
return undefined;
}
switch (filename) {
case "answer.py":
return makeMockModelFile("_instructor/answer.py", this.main.model.submission.code());
case "on_run.py":
return makeMockModelFile("_instructor/on_run.py", this.main.model.assignment.onRun());
case "on_change.py":
return makeMockModelFile("_instructor/on_change.py", this.main.model.assignment.onChange());
case "on_eval.py":
return makeMockModelFile("_instructor/on_eval.md", this.main.model.assignment.onEval());
case "instructions.md":
return makeMockModelFile("_instructor/instructions.md", this.main.model.assignment.instructions());
case "starting_code.py":
return makeMockModelFile("_instructor/starting_code.py", this.main.model.assignment.startingCode());
}
return undefined;
}
newFileDialog(kind) {
let body = $(NEW_INSTRUCTOR_FILE_DIALOG_HTML);
let filename = body.find(".blockpy-instructor-file-dialog-filename");
let filetype = body.find(".blockpy-instructor-file-dialog-filetype");
let namespace = body.find(".blockpy-instructor-file-dialog-namespace");
let extensionRegex = /(?:\.([^.]+))?$/;
filename.on("input", () => {
let extension = extensionRegex.exec(filename.val())[1];
extension = extension === undefined ? "No extension" : extension;
//TODO: this.main.components.editors.getEditorFromExtension(extension);
filetype.text(extension);
});
let yes = () => {
let prefix = "";
if (kind === "instructor") {
prefix = namespace.val();
} else if (kind === "starting") {
prefix = "^";
}
if (filename.val()) {
filename = prefix+filename.val();
this.newFile(filename);
}
};
body.submit((e) => {
e.preventDefault();
yes();
this.main.components.dialog.close();
});
this.main.components.dialog.confirm("Make New File", body, yes, ()=>{}, "Add");
}
} | RealTimeWeb/blockpy | src/files.js | JavaScript | apache-2.0 | 23,518 |
ProductBuyWindow = function(_product){
var backButton = Ti.UI.createButton({
backgroundImage:'images/back_button.png',
width:57,height:34
});
var self = Ti.UI.createWindow({
title: 'Product',
barImage: 'images/nav_bg_w_pattern.png',
backgroundImage: 'images/bg.png',
leftNavButton: backButton
});
var scrollView = Ti.UI.createScrollView({
contentWidth: 'auto',
contentHeight: 'auto',
showVerticalScrollIndicator: true,
showHorizontalScrollIndicator: false,
});
backButton.addEventListener('click', function(){
self.close();
});
var productImageView = Ti.UI.createView({
top: 20,
width: 241,
height: 237,
zIndex: 3
});
var productImage = Ti.UI.createImageView({
image: _product.productImage,
top: 0,
width: 181,
height: 237,
borderColor: 'white',
borderWidth: 5
});
productImageView.add(productImage);
var priceView = Ti.UI.createView({
top: 10,
right: 0,
width: 62,
height: 62,
backgroundImage: 'images/product/price.png'
});
productImageView.add(priceView);
var price = Ti.UI.createLabel({
top: 20,
right: 5,
text: _product.price,
font: { fontSize: 18, fontFamily: 'Helvetica Neue', fontWeight: 'bold' },
shadowColor:'#666666',
shadowOffset:{x:1,y:1},
color: 'white'
});
priceView.add(price);
var barOfProduct = Ti.UI.createImageView({
image: 'images/product/barofproduct.png',
top: 252
});
var productDetailView = Ti.UI.createView({
top:300,
bottom: 10,
width: 298,
height: 264,
left: 10,
right: 10,
backgroundImage: 'images/product/productdetail.png'
});
var productDetailButton = Ti.UI.createImageView({
image: 'images/product/productdetail_button.png',
width: 110,
height: 32,
top: 13,
left: 15
});
productDetailView.add(productDetailButton);
var buyNowButton = Ti.UI.createButton({
backgroundImage: 'images/product/buynow_button.png',
width: 72,
height: 32,
top: 13,
left: 125
});
productDetailView.add(buyNowButton);
buyNowButton.addEventListener('click',function(){
Ti.Platform.openURL(_product.link);
});
var productName = Ti.UI.createLabel({
top: 60,
text: _product.productName,
font: { fontSize: 24, fontFamily: 'Helvetica Neue', fontWeight: 'bold'},
left: 15
});
productDetailView.add(productName);
var productNameWidth = productName.toImage().width;
var productNameHeight = productName.toImage().height;
var numLines = Math.ceil(productNameWidth / ONE_LINE_LENGTH);
var productDescTopIndent = numLines * productNameHeight;
var productDescription = Ti.UI.createLabel({
top: productDescTopIndent+70,
width: 270,
height: 50,
text: 'Description: '+_product.description,
font: { fontSize: 14, fontFamily: 'Helvetica Neue'},
left: 15
});
productDetailView.add(productDescription);
self.add(scrollView);
scrollView.add(productImageView);
scrollView.add(barOfProduct);
scrollView.add(productDetailView);
return self;
}
module.exports = ProductBuyWindow;
| noonswoon/social-tv-base | Resources/ui/common/Pd_ProductBuyWindow.js | JavaScript | apache-2.0 | 2,993 |
/*
* Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
*/
define([
'underscore',
'contrail-model'
], function (_, ContrailModel) {
var self;
var ruleModel = ContrailModel.extend({
defaultConfig: {
'action_list':{'simple_action':'pass',
'apply_service':null,
'gateway_name':null,
'log':false,
'mirror_to':{'analyzer_name':null},
'qos_action': null},
'log_checked':false,
'apply_service_check' : false,
'mirror_to_check' : false,
'qos_action_check': false,
'application':[],
'direction': '<>',
'protocol': 'any',
'dst_addresses': [],
'dst_address' : 'any' + cowc.DROPDOWN_VALUE_SEPARATOR + 'virtual_network',
'dst_ports':[],
'dst_ports_text':"ANY",
'src_addresses':[],
'src_address' : 'any' + cowc.DROPDOWN_VALUE_SEPARATOR + 'virtual_network',
'src_ports':[],
'src_ports_text': 'ANY',
'simple_action': 'pass',
'apply_service': '',
'service_instance':'',
'mirror':'',
'qos':null,
'rule_uuid':'',
'analyzer_name':'',
'rule_sequence':{
'major': -1,
'minor': -1
},
'src_addresses_arr': {
"security_group": null,
"virtual_network": "any",
"network_policy": null,
"subnet": null
},
'dst_addresses_arr': {
"security_group": null,
"virtual_network": "any",
"network_policy": null,
"subnet": null
}
},
formatModelConfig: function (modelConfig) {
self = this;
var protocol = getValueByJsonPath(modelConfig, "protocol", "");
var simpleAction = getValueByJsonPath(modelConfig, "action_list;simple_action", "");
if (simpleAction != "") {
simpleAction = simpleAction.toUpperCase();
modelConfig["simple_action"] = simpleAction
}
if (protocol != "") {
modelConfig["protocol"] = (protocol).toUpperCase();
}
var applyService = getValueByJsonPath(modelConfig,
"action_list;apply_service", []);
if (applyService.length > 0) {
modelConfig["service_instance"] =
applyService.join(cowc.DROPDOWN_VALUE_SEPARATOR);
modelConfig["apply_service_check"] = true;
} else {
modelConfig["service_instance"] = null;
modelConfig["apply_service_check"] = false;
}
var srcAddress = getValueByJsonPath(modelConfig, "src_addresses;0","");
if (srcAddress != "") {
var addressObj = self.getAddress(srcAddress);
modelConfig["src_address"] = addressObj.addres;
modelConfig["src_addresses"] = addressObj.address;
}
var dstAddress = getValueByJsonPath(modelConfig, "dst_addresses;0","");
if (dstAddress != "") {
var addressObj = self.getAddress(dstAddress);
modelConfig["dst_address"] = addressObj.addres;
modelConfig["dst_addresses"] = addressObj.address;
}
var src_ports_text = "";
src_ports_text = this.formatPortAddress(modelConfig["src_ports"]);
modelConfig["src_ports_text"] = src_ports_text;
var dst_ports_text = "";
dst_ports_text = this.formatPortAddress(modelConfig["dst_ports"]);
modelConfig["dst_ports_text"] = dst_ports_text;
return modelConfig;
},
validateAttr: function (attributePath, validation, data) {
var model = data.model().attributes.model(),
attr = cowu.getAttributeFromPath(attributePath),
errors = model.get(cowc.KEY_MODEL_ERRORS),
attrErrorObj = {}, isValid;
isValid = model.isValid(attributePath, validation);
attrErrorObj[attr + cowc.ERROR_SUFFIX_ID] =
(isValid == true) ? false : isValid;
errors.set(attrErrorObj);
},
validations: {
ruleValidation: {
'service_instance': function(val, attr, data) {
if (data.apply_service_check != true) {
return;
}
if (val == "" || val == null) {
return "Select atleast one service to apply.";
}
var valArr = val.split(",");
var valArrLen = valArr.length;
var inNetworkTypeCount = 0;
for (var i = 0; i < valArrLen; i++) {
var SIValue = valArr[i].split(" ");
if (SIValue.length >= 2 && SIValue[1] == "in-network-nat") {
inNetworkTypeCount++;
if (inNetworkTypeCount >= 2) {
return "Cannot have more than one 'in-network-nat'\
services."
}
}
}
var SIValue = valArr[valArrLen-1].split(" ");
if (inNetworkTypeCount >= 1 && SIValue[1] != "in-network-nat") {
return "Last instance should be of 'in-network-nat'\
service mode while applying services."
}
var error = self.isBothSrcDscCIDR(data);
if (error != "") {
return error;
}
var result = self.checkAnyOrLocal(data, "src_address");
if(result == true) {
return "Source network cannot be 'any' while applying services.";
}
result = self.checkAnyOrLocal(data, "dst_address");
if(result == true) {
return "Destination network cannot be 'any' or 'local' while applying services.";
}
},
'src_address': function(val, attr, data) {
var result = self.validateAddressFormat(val, "Source");
if (result != "") {
return result
}
var error = self.isBothSrcDscCIDR(data);
if (error != "") {
return error;
}
var result = self.checkAnyOrLocal(data, "src_address");
if(result == true) {
return "Source network cannot be 'any' or 'local' while applying services.";
}
},
'dst_address': function(val, attr, data) {
var result = self.validateAddressFormat(val, "Destination");
if (result != "") {
return result
}
var error = self.isBothSrcDscCIDR(data);
if (error != "") {
return error;
}
var result = self.checkAnyOrLocal(data, "dst_address");
if(result == true) {
return "Destination network cannot be 'any' or 'local' while applying services.";
}
},
'protocol' : function(val, attr, data) {
if (val.trim() == "") {
return "Select a valid Protocol.";
}
var protocolValue = val.trim().toUpperCase();
var allProtocol = ['ANY', 'ICMP', 'TCP', 'UDP', 'ICMP6'];
if (allProtocol.indexOf(protocolValue) < 0) {
if (!isNumber(protocolValue)) {
return "Rule with invalid protocol " + protocolValue;
}
protocolValue = Number(protocolValue);
if (protocolValue % 1 != 0 || protocolValue < 0 || protocolValue > 255) {
return "Rule with invalid protocol " + protocolValue;
}
}
},
'simple_action' : function(val, attr, data) {
if (val == "") {
return "Select a valid Action.";
}
},
'mirror': function(val, attr, data) {
if (data.mirror_to_check != true) {
return;
}
var error = self.isBothSrcDscCIDR(data);
if (error != "") {
return error;
}
var srcProt = getValueByJsonPath(data, "src_ports_text", "");
if(srcProt.toUpperCase() != "ANY") {
return "Only 'ANY' protocol allowed while mirroring services."
}
var dscProt = getValueByJsonPath(data, "dst_ports_text", "");
if(dscProt.toUpperCase() != "ANY") {
return "Only 'ANY' protocol allowed while mirroring services."
}
},
'src_ports_text' : function(val, attr, data) {
var result = self.validatePort(val);
if (result != "") {
return result;
}
},
'dst_ports_text' : function(val, attr, data) {
var result = self.validatePort(val);
if (result != "") {
return result;
}
}
}
},
validatePort: function(port) {
if (_.isString(port)) {
if (port.toUpperCase() != "ANY") {
var portArr = port.split(",");
for (var i = 0; i < portArr.length; i++) {
var portSplit = portArr[i].split("-");
if (portSplit.length > 2) {
return "Invalid Port Data";
}
for (var j = 0; j < portSplit.length; j++) {
if (portSplit[j] == "") {
return "Port has to be a number";
}
if (!isNumber(portSplit[j])) {
return "Port has to be a number";
}
if (portSplit[j] % 1 != 0) {
return "Port has to be a number";
}
}
}
}
} else if (!isNumber(port)) {
return "Port has to be a number";
}
return "";
},
isBothSrcDscCIDR: function(data) {
var msg = "";
if (data.apply_service_check != true) {
return msg;
}
var sourceAddress = getValueByJsonPath(data, "src_address", "");
var destAddress = getValueByJsonPath(data, "dst_address", "");
var sourceAddressArr = sourceAddress.split(cowc.DROPDOWN_VALUE_SEPARATOR);
var destAddressArr = destAddress.split(cowc.DROPDOWN_VALUE_SEPARATOR);
if (sourceAddressArr[1] == "subnet" && destAddressArr[1] == "subnet") {
msg = "Both Source and Destination cannot be CIDRs\
while applying/mirroring services.";
}
return msg;
},
checkAnyOrLocal: function(data, path) {
if (data.apply_service_check != true) {
return false;
}
var address = getValueByJsonPath(data, path, "");
var addressArr = address.split(cowc.DROPDOWN_VALUE_SEPARATOR);
if (addressArr.length >= 2 &&
addressArr[1] == "virtual_network" &&
(addressArr[0] == "any" ||
addressArr[0] == "local")) {
return true
}
return false;
},
getAddress: function(address) {
var returnObject = {},
virtualNetwork = getValueByJsonPath(address, "virtual_network", "");
var vnText = virtualNetwork;
if (vnText == "any") {
vnText = "ANY (All Networks in Current Project)";
} else if (vnText == "local") {
vnText = "LOCAL (All Networks to which this policy is associated)";
}
var value = virtualNetwork + cowc.DROPDOWN_VALUE_SEPARATOR + "virtual_network";
returnObject.addres = value;
returnObject.address = value;
return returnObject;
},
validateAddressFormat: function(val, srcOrDesString) {
if (val == "") {
return "Enter a valid " + srcOrDesString + " Address";
}
var address = val.split(cowc.DROPDOWN_VALUE_SEPARATOR);
if (address.length == 2) {
var value = address[0].trim(), group = address[1],
vnSubnetObj, addValue;
addValue = value.split(":");
if (addValue && addValue.length != 1 && addValue.length != 3) {
var groupSelectedString = "";
if (group == "virtual_network") {
groupSelectedString = "Network";
} else if (group == "network_policy") {
groupSelectedString = "Policy";
}
return "Fully Qualified Name of "+srcOrDesString+ " " +
groupSelectedString +
" should be in the format \
Domain:Project:NetworkName.";
}
}
return "";
},
formatPortAddress: function(portArr) {
var ports_text = "";
if (portArr != "" && portArr.length > 0) {
var ports_len = portArr.length;
for (var i=0;i< ports_len; i++) {
if (ports_text != "") ports_text += ", ";
if (portArr[i]["start_port"] == -1 &&
portArr[i]["end_port"] == -1) {
ports_text = "ANY";
} else {
ports_text +=
portArr[i]["start_port"]
+ " - "
+ portArr[i]["end_port"]
}
}
}
if (ports_text == "") {
ports_text = "ANY";
}
return ports_text;
}
});
return ruleModel;
});
| biswajit-mandal/contrail-web-controller | webroot/config/gohanUi/networkpolicy/ui/js/models/gcRuleModel.js | JavaScript | apache-2.0 | 15,387 |
$(function () {
//$("#submit").on("mousedown", function (e) {
// //console.log(tinyMCE.activeEditor.getContent());
// //Gets text from active editor
// var content = tinyMCE.activeEditor.getContent();
// $("#hTitle").val($("#titleDisp").html());
//})
$(".edit").on("blur", function (e) {
console.log(e);
//Gets text from active editor
var content = tinyMCE.activeEditor.getContent();
if (e.target.id === "descriptionDisp") {
$("#hDescription").val(content);
}
else if (e.target.id === "titleDisp") {
$("#hTitle").val(content);
}
})
}); | DACunningham/DeanAndSons | DeanAndSons/DeanAndSons/Scripts/Custom/CMSEditProp.js | JavaScript | apache-2.0 | 686 |
var Alloy = require("alloy");
var definition = {
config: {
columns: {
id: "INTEGER PRIMARY KEY",
title: "TEXT",
author: "TEXT",
read: "INTEGER"
},
adapter: {
type: "sql",
collection_name: "book",
db_name: Alloy.CFG.db_name,
idAttribute: "id"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
toString: function() {
return String.format("%s (%s)", this.get("title"), this.get("author"));
},
isRead: function() {
return 1 === this.get("read");
},
markAsRead: function() {
this.set("read", 1);
}
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
fetchRead: function() {
var table = definition.config.adapter.collection_name;
this.fetch({
query: "SELECT * from " + table + " where read=1"
});
}
});
return Collection;
}
};
exports.definition = definition;
var Alloy = require("alloy"), _ = require("alloy/underscore")._, model, collection;
model = Alloy.M("book", exports.definition, []);
collection = Alloy.C("book", exports.definition, model);
exports.Model = model;
exports.Collection = collection; | dharmik/TiJasmin | Resources/alloy/models/Book.js | JavaScript | apache-2.0 | 1,475 |
//
// app.js
// gb-chat
//
// Created by Luka Mirosevic on 17/04/2014.
// Copyright (c) 2014 Goonbee. All rights reserved.
//
//lm might need to add a different message type like "status" to enable things like "luka change the room topic to 'blabla'"
//lm add heartbeat oneway message
var nconf = require('nconf'),
api = require('gb-api'),
GBChatService = require('./thrift/gen-nodejs/GoonbeeChatService'),
ttypes = require('./thrift/gen-nodejs/GoonbeeChatService_types'),
ttypesShared = require('./thrift/gen-nodejs/GoonbeeShared_types');
// Config
nconf.argv()
.env()
.file({file: './config/defaults.json'});
api.errors.setShouldLogOutput(nconf.get('LOG_OUTPUT'));
api.errors.setShouldLogCalls(nconf.get('LOG_CALLS'));
api.errors.setShouldLogErrors(nconf.get('LOG_ERRORS'));
// Error mapping from application -> thrift
api.errors.setErrorMapping(
{
GenericError: ttypesShared.ResponseStatus.GENERIC,
MalformedRequestError: ttypesShared.ResponseStatus.MALFORMED_REQUEST,
AuthenticationError: ttypesShared.ResponseStatus.AUTHENTICATION,
AuthorizationError: ttypesShared.ResponseStatus.AUTHORIZATION,
PhasedOutError: ttypesShared.ResponseStatus.PHASED_OUT,
},
function(status, message) {
return new ttypesShared.RequestError({status: status, message: message});// passes through original error message to client, this is desired in the case of the mapped errors above
},
new ttypesShared.RequestError({status: ttypesShared.ResponseStatus.GENERIC, message: 'A generic error occured.'})
);
// Persistence layer
var persistence = require('./lib/persistence/' + nconf.get('PERSISTENCE').type);
// Server implementation
var ChatServiceImplementation = function() {
/**
* GoonbeeShared BaseService
*/
this.alive = function(result) {
result('777');
};
/**
* Goonbee Chat Service
*/
this.isUsernameAvailable = function(username, result) {
persistence.isUsernameAvailable(username, result);
};
this.registerUsername = function(userId, username, result) {
persistence.setUser(userId, username, result);
};
this.setChatOptions = this.newChat = function(userId, chatId, chatOptions, result) {
persistence.setChatOptions(userId, chatId, chatOptions, result);
};
this.chats = function(sorting, range, result) {
persistence.getChats(sorting, range, result);
};
this.chat = function(userId, chatId, result) {
persistence.getChat(userId, chatId, result);
};
this.newMessage = function(userId, chatId, content, result) {
persistence.newMessage(userId, chatId, content, result);
};
this.messages = function(userId, chatId, range, result) {
persistence.getMessages(userId, chatId, range, result);
};
this.globalUserCount = function(result) {
persistence.getUserCount(result);
};
};
// Start server
api.createThriftServer(GBChatService, new ChatServiceImplementation()).listen(nconf.get('PORT'));
console.log("Chat server started on port " + nconf.get('PORT'));
| lmirosevic/gb-chat | app.js | JavaScript | apache-2.0 | 3,014 |
'use strict';
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
factory((root.jsonTreeBuilder = {}));
}
}(this, function (exports) {
// If enabled, expressions are wrapped in ExpressionStatement nodes, making
// it possible to satisfy Statement type requirements.
// This increases the filesize of the binary representation significantly, though.
var GenerateExpressionStatements = false;
function JsonTreeBuilder () {
this.protos = Object.create(null);
};
JsonTreeBuilder.prototype.makeProto = function (type) {
return new Object();
};
JsonTreeBuilder.prototype.make = function (type) {
var proto = this.protos[type];
if (!proto) {
this.protos[type] = proto = this.makeProto(type);
proto.type = type;
}
var result = Object.create(proto);
// HACK For debugging and JSON.stringify
result.type = type;
return result;
};
JsonTreeBuilder.prototype.pushScope = function () {
};
JsonTreeBuilder.prototype.popScope = function () {
};
JsonTreeBuilder.prototype._makeBlock = function (typeTag) {
this.pushScope();
var result = this.make(typeTag);
result.statements = [];
return result;
};
JsonTreeBuilder.prototype.appendToBlock = function (block, statement) {
block.statements.push(statement);
};
// You must call this after you finish appending stuff to a block
JsonTreeBuilder.prototype.finishBlock = function (block) {
this.popScope();
return this.finalize(block);
};
// Note that this isn't finalized yet. Use finishBlock.
JsonTreeBuilder.prototype.makeTopLevelBlock = function () {
return this._makeBlock("TopLevel");
};
// Note that this isn't finalized yet. Use finishBlock.
JsonTreeBuilder.prototype.makeBlock = function () {
return this._makeBlock("Block");
};
JsonTreeBuilder.prototype.finalize = function (obj) {
return obj;
};
JsonTreeBuilder.prototype.makeExpressionStatement = function (expression) {
if (
!expression ||
(typeof (expression.type) !== "string")
) {
console.log(expression);
throw new Error("Expected an expression");
} else if (expression.type.indexOf("Statement") >= 0) {
console.log(expression);
throw new Error("Cannot wrap a statement in an expression statement");
}
if (GenerateExpressionStatements) {
var result = this.make("ExpressionStatement");
result.expression = expression;
return this.finalize(result);
} else {
return expression;
}
};
JsonTreeBuilder.prototype.makeLabelStatement = function (labels, labelled) {
var result;
if (labels.length === 1) {
result = this.make("LabelStatement");
result.label = labels[0];
} else if (labels.length === 0) {
throw new Error("No labels");
} else {
result = this.make("MultiLabelStatement");
result.labels = labels;
}
result.labelled = labelled;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeIfStatement = function (condition, trueStatement, falseStatement) {
var result = this.make("IfStatement");
result.condition = condition;
result.trueStatement = trueStatement;
result.falseStatement = falseStatement;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeForStatement = function (initialize, update, condition, body) {
var result = this.make("ForStatement");
result.initialize = initialize;
result.update = update;
result.condition = condition;
result.body = body;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeForInStatement = function (declaration, body) {
var result = this.make("ForInStatement");
result.declaration = declaration;
result.body = body;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeWhileStatement = function (condition, body) {
var result = this.make("WhileStatement");
result.condition = condition;
result.body = body;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeDoWhileStatement = function (condition, body) {
var result = this.make("DoWhileStatement");
result.condition = condition;
result.body = body;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeNullStatement = function () {
var result = this.make("NullStatement");
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeFunctionStatement = function (functionExpression) {
var result = this.make("FunctionStatement");
result.functionExpression = functionExpression;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeDeclarationStatement = function (declarations) {
var result = this.make("DeclarationStatement");
result.declarations = declarations;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeDeclaration = function (name, initialValue) {
var result = this.make("Declaration");
result.name = name;
result.initialValue = initialValue || null;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeForInDeclaration = function (variableName, sequenceExpression) {
var result = this.make("ForInDeclaration");
result.variableName = variableName;
result.sequenceExpression = sequenceExpression;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeReturnStatement = function (expression) {
var result = this.make("ReturnStatement");
result.expression = expression;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeBreakStatement = function (label) {
var result = this.make("BreakStatement");
result.label = label;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeContinueStatement = function (label) {
var result = this.make("ContinueStatement");
result.label = label;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeThrowStatement = function (expression) {
var result = this.make("ThrowStatement");
result.expression = expression;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeSwitchStatement = function (value, cases) {
var result = this.make("SwitchStatement");
result.value = value;
result.cases = cases;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeSwitchCase = function (value, body) {
var result = this.make("SwitchCase");
result.value = value;
result.body = body;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeTryStatement = function (body, catchExpression, catchBlock, finallyBlock) {
var result = this.make("TryStatement");
result.body = body;
result.catchExpression = catchExpression;
result.catchBlock = catchBlock;
result.finallyBlock = finallyBlock;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeCommaExpression = function (expressions) {
var result = this.make("Comma");
result.expressions = expressions;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeFunctionExpression = function (name, argumentNames, body) {
var result = this.make("Function");
result.name = name;
result.argumentNames = argumentNames;
result.body = body;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeRegExpLiteralExpression = function (pattern, flags) {
var result = this.make("RegExpLiteral");
result.pattern = pattern;
result.flags = flags;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeLiteralExpression = function (type, value) {
var titleCaseType = type[0].toUpperCase() + type.substr(1);
if (type === "regexp")
throw new Error("Invalid");
var result = this.make(titleCaseType + "Literal");
result.value = value;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeArrayLiteralExpression = function (elements) {
var result = this.make("ArrayLiteral");
result.elements = elements;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeObjectLiteralExpression = function (pairs) {
var result = this.make("ObjectLiteral");
result.pairs = pairs;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makePair = function (key, value) {
var keyType = typeof(key);
keyType = keyType[0].toUpperCase() + keyType.substr(1);
var result = this.make(keyType + "Pair");
result.key = key;
result.value = value;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeIdentifierExpression = function (identifier) {
var result = this.make("Identifier");
result.identifier = identifier;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makePrefixMutationExpression = function (operator, rhs) {
var result = this.make("PrefixMutation");
result.operator = operator;
result.rhs = rhs;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makePostfixMutationExpression = function (operator, lhs) {
var result = this.make("PostfixMutation");
result.operator = operator;
result.lhs = lhs;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeUnaryOperatorExpression = function (operator, rhs) {
var result = this.make("UnaryOperator");
result.operator = operator;
result.rhs = rhs;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeBinaryOperatorExpression = function (operator, lhs, rhs) {
var result = this.make("BinaryOperator");
result.operator = operator;
result.lhs = lhs;
result.rhs = rhs;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeAssignmentOperatorExpression = function (operator, lhs, rhs) {
var result = this.make("AssignmentOperator");
result.operator = operator;
result.lhs = lhs;
result.rhs = rhs;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeComputedMemberAccessExpression = function (lhs, rhs) {
var result = this.make("ComputedMemberAccess");
result.lhs = lhs;
result.rhs = rhs;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeTernaryOperatorExpression = function (condition, trueExpression, falseExpression) {
var result = this.make("TernaryOperator");
result.condition = condition;
result.trueExpression = trueExpression;
result.falseExpression = falseExpression;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeMemberAccessExpression = function (lhs, memberName) {
var result = this.make("MemberAccess");
result.lhs = lhs;
result.memberName = memberName;
return this.finalize(result);
};
JsonTreeBuilder.prototype.makeInvocationExpression = function (callee, argumentValues) {
var result = this.make("Invocation");
result.callee = callee;
result.argumentValues = argumentValues;
return this.finalize(result);
};
exports.Builder = JsonTreeBuilder;
})); | WebAssembly/js-astcompressor-prototype | parse/json-treebuilder.js | JavaScript | apache-2.0 | 11,156 |
import createCallbacks from 'uni-helpers/callbacks'
import {
getCurrentPageId
} from '../../platform'
import {
invoke
} from '../../bridge'
const getSelectedTextRangeEventCallbacks = createCallbacks('getSelectedTextRangeEvent')
UniServiceJSBridge.subscribe('onGetSelectedTextRange', ({
callbackId,
data
}) => {
console.log('onGetSelectedTextRange')
const callback = getSelectedTextRangeEventCallbacks.pop(callbackId)
if (callback) {
callback(data)
}
})
export function getSelectedTextRange (_, callbackId) {
const pageId = getCurrentPageId()
UniServiceJSBridge.publishHandler('getSelectedTextRange', {
pageId,
callbackId: getSelectedTextRangeEventCallbacks.push(function (res) {
invoke(callbackId, res)
})
}, pageId)
}
| dcloudio/uni-app | src/core/service/api/keyboard/get-selected-text-range.js | JavaScript | apache-2.0 | 766 |
var woordnlContextFinder = require('./woordnl-context-finder'),
immixContextFinder = require('./immix-context-finder'),
anefoContextFinder = require('./anefo-context-finder');
var msgQueue = {};
module.exports = {
queryContexts : function(query, msg, sources, callback) {
//add all the sources to the (to be) called array
msgQueue[msg.id] = {'toBeCalled' : sources, 'msg' : msg, 'callback' : callback, 'data' : {}};
//for each source call the corresponding context finder
for(s in sources) {
switch(sources[s]) {
case 'woordnl' :
woordnlContextFinder.search(query, msg, this.contextFetched.bind(this));
break;
case 'immix' :
immixContextFinder.search(query, msg, this.contextFetched.bind(this));
break;
case 'anefo' :
anefoContextFinder.search(query, msg, this.contextFetched.bind(this));
break;
}
}
},
contextFetched : function(msg, queryString, data, source) {
if(msgQueue[msg.id]) {
//aggregate the results to the return data (as JSON object)
if(data == null) {
msgQueue[msg.id].data[source] = {'queryString' : queryString, 'data' : null};
} else {
msgQueue[msg.id].data[source] = {'queryString' : queryString, 'data' : data};
}
//mark the context source as finished
msgQueue[msg.id].toBeCalled.splice(msgQueue[msg.id].toBeCalled.indexOf(source), 1);
//when all context data is available call back the service with the aggregated data
if(msgQueue[msg.id].toBeCalled.length == 0) {
//call back the service
msgQueue[msg.id].callback(msgQueue[msg.id]);
//remove the message from the queue
delete msgQueue[msg.id];
}
}
}
} | beeldengeluid/labs-nodejs | node/context-finder/context-aggregator.js | JavaScript | apache-2.0 | 1,675 |
'use strict';
describe('Controller Tests', function() {
describe('Subscriber Management Detail Controller', function() {
var $scope, $rootScope;
var MockEntity, MockPreviousState, MockSubscriber;
var createController;
beforeEach(inject(function($injector) {
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
MockEntity = jasmine.createSpy('MockEntity');
MockPreviousState = jasmine.createSpy('MockPreviousState');
MockSubscriber = jasmine.createSpy('MockSubscriber');
var locals = {
'$scope': $scope,
'$rootScope': $rootScope,
'entity': MockEntity,
'previousState': MockPreviousState,
'Subscriber': MockSubscriber
};
createController = function() {
$injector.get('$controller')("SubscriberDetailController", locals);
};
}));
describe('Root Scope Listening', function() {
it('Unregisters root scope listener upon scope destruction', function() {
var eventType = 'sentryApp:subscriberUpdate';
createController();
expect($rootScope.$$listenerCount[eventType]).toEqual(1);
$scope.$destroy();
expect($rootScope.$$listenerCount[eventType]).toBeUndefined();
});
});
});
});
| quanticc/sentry | src/test/javascript/spec/app/entities/subscriber/subscriber-detail.controller.spec.js | JavaScript | apache-2.0 | 1,481 |
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkID=397704
// To debug code on page load in Ripple or on Android devices/emulators: launch your app, set breakpoints,
// and then run "window.location.reload()" in the JavaScript Console.
(function () {
"use strict";
document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false );
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
var socket = io('http://finditbackend.cloudapp.net:3000');
socket.on('connect', function () {
});
socket.on('Welcome', function (data) {
navigator.notification.alert(
data.SocketId,
alertDismissed,
'Welcome',
'Done'
);
});
};
function alertDismissed() {
// do something
}
function onPause() {
// TODO: This application has been suspended. Save application state here.
};
function onResume() {
// TODO: This application has been reactivated. Restore application state here.
};
} )(); | BlackSharkIO/FindIt | FrontEndApp/FindItCordova/FindItCordova/www/scripts/index.js | JavaScript | apache-2.0 | 1,462 |
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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 charts = [
{
name: "MESSAGE_LEVEL_ERROR",
columns: ["timestamp", "messageCount", "message"],
additionalColumns: ["week"],
orderedField: "messageCount",
schema: [{
"metadata": {
"names": ["day", "count", "message", "ID"],
"types": ["ordinal", "linear", "ordinal", "linear"]
},
"data": []
}],
"chartConfig": {
type: "bar",
x: "day",
colorScale: [],
colorDomain: [],
xAxisAngle: true,
color: "message",
charts: [{type: "bar", y: "count", mode: "stack"}],
width: $(document).width()/1.27,
height: $(document).height()/1.2,
padding: {"top": 10, "left": 80, "bottom": 70, "right": 50},
legend: false,
tooltip: {
"enabled": true,
"color": "#e5f2ff",
"type": "symbol",
"content": ["ID", "count", "day"],
"label": true
}
}
},
{
name: "CLASS_LEVEL_ERROR",
columns: ["timestamp", "classCount", "class"],
additionalColumns: ["week"],
orderedField: "classCount",
schema: [{
"metadata": {
"names": ["day", "count", "class", "ID"],
"types": ["ordinal", "linear", "ordinal", "linear"]
},
"data": []
}],
"chartConfig": {
type: "bar",
x: "day",
colorScale: [],
colorDomain: [],
xAxisAngle: true,
color: "class",
charts: [{type: "bar", y: "count", mode: "stack"}],
width: $(document).width()/1.27,
height: $(document).height()/1.2,
padding: {"top": 10, "left": 80, "bottom": 70, "right": 50},
legend: false,
tooltip: {
"enabled": true,
"color": "#e5f2ff",
"type": "symbol",
"content": ["ID", "count", "day"],
"label": true
}
}
}
];
| ksdperera/shared-analytics | features/log-analyzer/org.wso2.carbon.analytics.shared.la.common.feature/src/main/resources/gadgets/LogErrorBarChart/js/gadgetconf.js | JavaScript | apache-2.0 | 2,841 |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file defines a loose mock implementation.
*/
goog.setTestOnly('goog.testing.LooseExpectationCollection');
goog.provide('goog.testing.LooseExpectationCollection');
goog.provide('goog.testing.LooseMock');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.structs.Map');
goog.require('goog.structs.Set');
goog.require('goog.testing.Mock');
/**
* This class is an ordered collection of expectations for one method. Since
* the loose mock does most of its verification at the time of $verify, this
* class is necessary to manage the return/throw behavior when the mock is
* being called.
* @constructor
* @final
*/
goog.testing.LooseExpectationCollection = function() {
/**
* The list of expectations. All of these should have the same name.
* @type {Array<goog.testing.MockExpectation>}
* @private
*/
this.expectations_ = [];
};
/**
* Adds an expectation to this collection.
* @param {goog.testing.MockExpectation} expectation The expectation to add.
*/
goog.testing.LooseExpectationCollection.prototype.addExpectation = function(
expectation) {
this.expectations_.push(expectation);
};
/**
* Gets the list of expectations in this collection.
* @return {Array<goog.testing.MockExpectation>} The array of expectations.
*/
goog.testing.LooseExpectationCollection.prototype.getExpectations = function() {
return this.expectations_;
};
/**
* This is a mock that does not care about the order of method calls. As a
* result, it won't throw exceptions until verify() is called. The only
* exception is that if a method is called that has no expectations, then an
* exception will be thrown.
* @param {Object|Function} objectToMock The object that should be mocked, or
* the constructor of an object to mock.
* @param {boolean=} opt_ignoreUnexpectedCalls Whether to ignore unexpected
* calls.
* @param {boolean=} opt_mockStaticMethods An optional argument denoting that
* a mock should be constructed from the static functions of a class.
* @param {boolean=} opt_createProxy An optional argument denoting that
* a proxy for the target mock should be created.
* @constructor
* @extends {goog.testing.Mock}
*/
goog.testing.LooseMock = function(
objectToMock, opt_ignoreUnexpectedCalls, opt_mockStaticMethods,
opt_createProxy) {
goog.testing.Mock.call(
this, objectToMock, opt_mockStaticMethods, opt_createProxy);
/**
* A map of method names to a LooseExpectationCollection for that method.
* @type {goog.structs.Map}
* @private
*/
this.$expectations_ = new goog.structs.Map();
/** @private {!goog.structs.Set<!goog.testing.MockExpectation>} */
this.awaitingExpectations_ = new goog.structs.Set();
/**
* The calls that have been made; we cache them to verify at the end. Each
* element is an array where the first element is the name, and the second
* element is the arguments.
* @type {Array<Array<*>>}
* @private
*/
this.$calls_ = [];
/**
* Whether to ignore unexpected calls.
* @type {boolean}
* @private
*/
this.$ignoreUnexpectedCalls_ = !!opt_ignoreUnexpectedCalls;
};
goog.inherits(goog.testing.LooseMock, goog.testing.Mock);
/**
* A setter for the ignoreUnexpectedCalls field.
* @param {boolean} ignoreUnexpectedCalls Whether to ignore unexpected calls.
* @return {!goog.testing.LooseMock} This mock object.
*/
goog.testing.LooseMock.prototype.$setIgnoreUnexpectedCalls = function(
ignoreUnexpectedCalls) {
this.$ignoreUnexpectedCalls_ = ignoreUnexpectedCalls;
return this;
};
/** @override */
goog.testing.LooseMock.prototype.$recordExpectation = function() {
if (!this.$expectations_.containsKey(this.$pendingExpectation.name)) {
this.$expectations_.set(
this.$pendingExpectation.name,
new goog.testing.LooseExpectationCollection());
}
var collection = this.$expectations_.get(this.$pendingExpectation.name);
collection.addExpectation(this.$pendingExpectation);
if (this.$pendingExpectation) {
this.awaitingExpectations_.add(this.$pendingExpectation);
}
};
/** @override */
goog.testing.LooseMock.prototype.$recordCall = function(name, args) {
if (!this.$expectations_.containsKey(name)) {
if (this.$ignoreUnexpectedCalls_) {
return;
}
this.$throwCallException(name, args);
}
// Start from the beginning of the expectations for this name,
// and iterate over them until we find an expectation that matches
// and also has calls remaining.
var collection = this.$expectations_.get(name);
var matchingExpectation = null;
var expectations = collection.getExpectations();
for (var i = 0; i < expectations.length; i++) {
var expectation = expectations[i];
if (this.$verifyCall(expectation, name, args)) {
matchingExpectation = expectation;
if (expectation.actualCalls < expectation.maxCalls) {
break;
} // else continue and see if we can find something that does match
}
}
if (matchingExpectation == null) {
this.$throwCallException(name, args, expectation);
}
matchingExpectation.actualCalls++;
if (matchingExpectation.actualCalls > matchingExpectation.maxCalls) {
this.$throwException(
'Too many calls to ' + matchingExpectation.name + '\nExpected: ' +
matchingExpectation.maxCalls + ' but was: ' +
matchingExpectation.actualCalls);
}
if (matchingExpectation.actualCalls >= matchingExpectation.minCalls) {
this.awaitingExpectations_.remove(matchingExpectation);
this.maybeFinishedWithExpectations_();
}
this.$calls_.push([name, args]);
return this.$do(matchingExpectation, args);
};
/** @override */
goog.testing.LooseMock.prototype.$reset = function() {
goog.testing.LooseMock.superClass_.$reset.call(this);
this.$expectations_ = new goog.structs.Map();
this.awaitingExpectations_ = new goog.structs.Set();
this.$calls_ = [];
};
/** @override */
goog.testing.LooseMock.prototype.$replay = function() {
goog.testing.LooseMock.superClass_.$replay.call(this);
// Verify that there are no expectations that can never be reached.
// This can't catch every situation, but it is a decent sanity check
// and it's similar to the behavior of EasyMock in java.
var collections = this.$expectations_.getValues();
for (var i = 0; i < collections.length; i++) {
var expectations = collections[i].getExpectations();
for (var j = 0; j < expectations.length; j++) {
var expectation = expectations[j];
// If this expectation can be called infinite times, then
// check if any subsequent expectation has the exact same
// argument list.
if (!isFinite(expectation.maxCalls)) {
for (var k = j + 1; k < expectations.length; k++) {
var laterExpectation = expectations[k];
if (laterExpectation.minCalls > 0 &&
goog.array.equals(
expectation.argumentList, laterExpectation.argumentList)) {
var name = expectation.name;
var argsString = this.$argumentsAsString(expectation.argumentList);
this.$throwException([
'Expected call to ', name, ' with arguments ', argsString,
' has an infinite max number of calls; can\'t expect an',
' identical call later with a positive min number of calls'
].join(''));
}
}
}
}
}
};
/** @override */
goog.testing.LooseMock.prototype.$waitAndVerify = function() {
var keys = this.$expectations_.getKeys();
for (var i = 0; i < keys.length; i++) {
var expectations = this.$expectations_.get(keys[i]).getExpectations();
for (var j = 0; j < expectations.length; j++) {
var expectation = expectations[j];
goog.asserts.assert(
!isFinite(expectation.maxCalls) ||
expectation.minCalls == expectation.maxCalls,
'Mock expectations cannot have a loose number of expected calls to ' +
'use $waitAndVerify.');
}
}
var promise = goog.testing.LooseMock.base(this, '$waitAndVerify');
this.maybeFinishedWithExpectations_();
return promise;
};
/**
* @private
*/
goog.testing.LooseMock.prototype.maybeFinishedWithExpectations_ = function() {
if (this.awaitingExpectations_.isEmpty() && this.waitingForExpectations) {
this.waitingForExpectations.resolve();
}
};
/** @override */
goog.testing.LooseMock.prototype.$verify = function() {
goog.testing.LooseMock.superClass_.$verify.call(this);
var collections = this.$expectations_.getValues();
for (var i = 0; i < collections.length; i++) {
var expectations = collections[i].getExpectations();
for (var j = 0; j < expectations.length; j++) {
var expectation = expectations[j];
if (expectation.actualCalls > expectation.maxCalls) {
this.$throwException(
'Too many calls to ' + expectation.name + '\nExpected: ' +
expectation.maxCalls + ' but was: ' + expectation.actualCalls);
} else if (expectation.actualCalls < expectation.minCalls) {
this.$throwException(
'Not enough calls to ' + expectation.name + '\nExpected: ' +
expectation.minCalls + ' but was: ' + expectation.actualCalls);
}
}
}
};
| teppeis/closure-library | closure/goog/testing/loosemock.js | JavaScript | apache-2.0 | 9,901 |
/** mobile web toast、alert、confirm提示框
* 2016.05.25 ghb
* toast使用方式:
* webToast("屌丝逆袭了","bottom",1000);
* webToast("出任SEO","bottom");
* webToast("赢取白富美",1000);
* webToast("走向人生巅峰");
*
* alert、confirm使用方式:
* popTipShow.alert('弹窗标题',['知道了'],function(e){//do something})
* popTipShow.confirm('弹窗标题','自定义弹窗内容,居左对齐显示,告知需要确认的信息等',['确 定','取 消'],function(e){//do something})
*/
function compareVersion(v1, v2) {
v1 = v1.toString().split(".");
v2 = v2.toString().split(".");
for (var i = 0; i < v1.length || i < v2.length; i++) {
var n1 = parseInt(v1[i], 10),
n2 = parseInt(v2[i], 10);
if (window.isNaN(n1)) {
n1 = 0
}
if (window.isNaN(n2)) {
n2 = 0
}
if (n1 < n2) {
return -1
} else {
if (n1 > n2) {
return 1
}
}
}
return 0
}
function callback(func, result) {
var ua = navigator.userAgent,
isAndroid = (/Android/i).test(ua),
osVersion = ua.match(/(?:OS|Android)[\/\s](\d+[._]\d+(?:[._]\d+)?)/i)
if (isAndroid && compareVersion(osVersion, "2.4.0") < 0) {
setTimeout(function() {
func && func(result)
}, 1)
} else {
func && func(result)
}
}
(function(e) {
if (void 0 == window.define) {
var d = {},
h = d.exports = {};
e(null, h, d);
window.popTipShow = window.notification = d.exports
} else define(e)
})(function(require, exports, module) {
function e(a) {
this._options = d.extend({
mode: "msg",
text: "\u7f51\u9875\u63d0\u793a",
useTap: !1
}, a || {});
this._init()
}
var d = $,
h = d(window),
c = d('<div class="c-float-popWrap msgMode hide">'+
'<div class="weui_mask_transparent"></div>'+
'<div class="c-float-modePop">'+
'<div class="warnMsg"></div>'+
'<div class="content"></div>'+
'<div class="doBtn">'+
'<button class="cancel">\u53d6\u6d88</button>'+
'<button class="ok">\u786e\u5b9a</button>'+
'</div>'+
'</div>'+
'</div>'),
//c = d('<div class="error-tips hide"><p class="warnMsg"></p></div>'),
m = c.find(".warnMsg"),
n = c.find(".content"),
o = c.find(".doBtn .ok"),
p = c.find(".doBtn .cancel"),
j = !1,
f;
d.extend(e.prototype, {
_init: function() {
var a = this,
b = a._options,
g = b.mode,
k = b.text,
e = b.content,
f = b.callback,
l = b.background,
t = b.btns,
b = b.useTap ? "tap" : "click",
i = c.attr("class"),
i = i.replace(/(msg|alert|confirm)Mode/i, g + "Mode");
c.attr("class", i);
l && c.css("background", l);
k && m.html(k);
e && n.html(e);
t && o.html(t[0]);
t && p.html(t[1]);
if("alert"==g){//解决一个按钮时的宽度
o.css("width", "100%");
}else{
o.css("width", "");
}
o.off(b).on(b, function(b) {
f.call(a, b, !0);
});
p.off(b).on(b, function(b) {
f.call(a, b, !1)
});
j || (j = !0, d("body").append(c), h.on("resize",
function() {
setTimeout(function() {
a._pos()
}, 500)
}))
},
_pos: function() {
var a = document,
b = a.documentElement,
g = a.body,
e, d, f;
this.isHide() || (a = g.scrollTop, g = g.scrollLeft, e = b.clientWidth, b = b.clientHeight, d = c.width(), f = c.height(), c.css({
top: a + (b - f) / 2,
left: g + (e - d) / 2
}))
},
isShow: function() {
return c.hasClass("show")
},
isHide: function() {
return c.hasClass("hide")
},
_cbShow: function() {
var a = this._options.onShow;
c.css("opacity", "1").addClass("show");
a && a.call(this)
},
show: function() {
var a = this;
f && (clearTimeout(f), f = void 0);
a.isShow() ? a._cbShow() : (c.css("opacity", "0").removeClass("hide"), a._pos(), setTimeout(function() {
a._cbShow()
}, 300), setTimeout(function() {
c.animate({
opacity: "1"
}, 300, "linear")
}, 1))
},
_cbHide: function() {
var a = this._options.onHide;
c.css("opacity", "0").addClass("hide");
a && a.call(this)
},
hide: function() {
var a = this;
a.isHide() ? a._cbHide() : (c.css("opacity", "1").removeClass("show"), setTimeout(function() {
a._cbHide()
}, 300), setTimeout(function() {
c.animate({
opacity: "0"
}, 300, "linear")
}, 1))
},
flash: function(a) {
var b = this;
opt = b._options;
opt.onShow = function() {
f = setTimeout(function() {
f && b.hide()
}, a)
};
b.show()
}
});
module.exports = new function() {
this.simple = function(a, b, c) {
2 == arguments.length && "number" == typeof arguments[1] && (c = arguments[1], b = void 0);
var d = new e({
mode: "msg",
text: a,
background: b
});
d.flash(c || 2E3);
return d
};
this.msg = function(a, b) {
var d = new e({
mode: "msg",
text: a
});
d.show();
return d
};
this.alert = function(a, s, b, c) {
var d = new e({
mode: "alert",
text: a,
content: s,
btns:b,
callback: c
});
d.show();
return d
};
this.confirm = function(a, b, c, f) {
var d = new e({
mode: "confirm",
text: a,
content: b,
btns:c,
callback: f
});
d.show();
return d
};
this.pop = function(a) {
return new e(a)
}
}
});
/** mobile web toast提示框
* 使用方式:
* webToast("屌丝逆袭了","bottom",1000);
* webToast("出任SEO","bottom");
* webToast("赢取白富美",1000);
* webToast("走向人生巅峰");
*/
function webToast() {
//默认设置
var dcfg={
msg:"提示信息",
postion:"top",//展示位置,可能值:bottom,top,middle,默认top:是因为在mobile web环境下,输入法在底部会遮挡toast提示框
time:3000,//展示时间
};
//*********************以下为参数处理******************
var len = arguments.length;
var arg0 =arguments[0];
if(arguments.length>0){
dcfg.msg =arguments[0];
dcfg.msg=arg0;
var arg1 =arguments[1];
var regx = /(bottom|top|middle)/i;
var numRegx = /[1-9]\d*/;
if(regx.test(arg1)){
dcfg.postion=arg1;
}else if(numRegx.test(arg1)){
dcfg.time=arg1;
}
var arg2 =arguments[2];
var numRegx = /[1-9]\d*/;
if(numRegx.test(arg2)){
dcfg.time=arg2;
}
}
//*********************以上为参数处理******************
var ret = "<div class='web_toast'><div class='cx_mask_transparent'></div>" + dcfg.msg + "</div>";
if ($(".web_toast").length <= 0) {
$("body").append(ret);
} else {//如果页面有web_toast 先清除之前的样式
$(".web_toast").css("left","");
ret = "<div class='cx_mask_transparent'></div>" + dcfg.msg;
$(".web_toast").html(ret);
}
var w = $(".web_toast").width(),ww = $(window).width();
$(".web_toast").fadeIn();
$(".web_toast").css("left",(ww-w)/2-20);
if("bottom"==dcfg.postion){
$(".web_toast").css("bottom",50);
$(".web_toast").css("top","");//这里为什么要置空,自己琢磨,我就不告诉
}else if("top"==dcfg.postion){
$(".web_toast").css("bottom","");
$(".web_toast").css("top",50);
}else if("middle"==dcfg.postion){
$(".web_toast").css("bottom","");
$(".web_toast").css("top","");
var h = $(".web_toast").height(),hh = $(window).height();
$(".web_toast").css("bottom",(hh-h)/2-20);
}
setTimeout(function() {
$(".web_toast").fadeOut();
}, dcfg.time);
} | godmeir/frontWidget | dialog/jqueryAlert/alertPopShow.js | JavaScript | apache-2.0 | 9,014 |
/* test commander component
* To use add require('../cmds/test.js')(program) to your commander.js based node executable before program.parse
*/
'use strict';
var pushbots = require('pushbots-api');
var fs = require('fs');
var jf = require('jsonfile')
var figlet = require('figlet');
var _ = require('underscore');
var clc = require('cli-color');
module.exports = function(program) {
program
.command('test')
.version('0.0.0')
.description('test push notifications ')
.action(function( msg ) {
//console.log(msg);
// Your code goes here
figlet('Pushbots', function(err, data) {
if (err) {
console.log('Something went wrong...');
console.dir(err);
return;
}
console.log(data);
console.log(clc.red('Sending a test push notification using PushBots API and the pushbots.json file generated through pushbots config command.'));
if (fs.existsSync("pushbots.json")) {
var settings = jf.readFileSync("pushbots.json");
//console.log(settings);
var settings = jf.readFileSync("pushbots.json");
var Pushbots = new pushbots.api({
id: settings.App_ID,
secret: settings.App_Secret
});
var m = _.isObject(msg)?'hi there':msg;
Pushbots.setMessage(m, [0, 1]);
Pushbots.push(function(response) {
});
} else {
console.log('no settings file');
}
});
});
}; | Shadowz3n/Clube-do-Assinante-Abril | node_modules/pushbots-cli/cmds/test.js | JavaScript | apache-2.0 | 1,796 |
import { ReactiveVar } from 'meteor/reactive-var';
import { SubsManager } from 'meteor/meteorhacks:subs-manager';
import { Template } from 'meteor/templating';
import { CareerGoals } from '../../../api/career/CareerGoalCollection';
import { Slugs } from '../../../api/slug/SlugCollection';
import { Interests } from '../../../api/interest/InterestCollection';
import { Courses } from '../../../api/course/CourseCollection';
import { AcademicPlans } from '../../../api/degree-plan/AcademicPlanCollection';
import { Opportunities } from '../../../api/opportunity/OpportunityCollection';
import { OpportunityTypes } from '../../../api/opportunity/OpportunityTypeCollection';
import { InterestTypes } from '../../../api/interest/InterestTypeCollection';
import { Semesters } from '../../../api/semester/SemesterCollection';
import { Teasers } from '../../../api/teaser/TeaserCollection';
/* eslint-disable object-shorthand */
const landingSubs = new SubsManager({ cacheLimit: 11, expireIn: 30 });
Template.With_Landing_Subscriptions.onCreated(function withlandingsubscriptionsOnCreated() {
// console.log('WithLandingSubscriptions.onCreated')
const self = this;
self.ready = new ReactiveVar();
self.autorun(function () {
landingSubs.subscribe(AcademicPlans.getPublicationName());
landingSubs.subscribe(CareerGoals.getPublicationName());
landingSubs.subscribe(Courses.getPublicationName());
landingSubs.subscribe(Interests.getPublicationName());
landingSubs.subscribe(InterestTypes.getPublicationName());
landingSubs.subscribe(Opportunities.getPublicationName());
landingSubs.subscribe(OpportunityTypes.getPublicationName());
landingSubs.subscribe(Semesters.getPublicationName());
landingSubs.subscribe(Slugs.getPublicationName());
landingSubs.subscribe(Teasers.getPublicationName());
self.ready.set(landingSubs.ready());
});
});
Template.With_Landing_Subscriptions.helpers({
subsReady: function () {
// console.log('landing ready', Template.instance().ready.get(), Slugs.count());
return Template.instance().ready.get();
},
});
| radgrad/radgrad | app/imports/ui/layouts/shared/with-landing-subscriptions.js | JavaScript | apache-2.0 | 2,094 |
import React from 'react';
import { Link } from 'react-router';
const Pager = ({ path, page, per, total }) => {
const last = Math.ceil(total / per);
const prev = page - 1 > 0 ? page - 1 : false;
const next = page < last ? page + 1 : false;
return (
<ul>
<li><Link to={path} query={{page: 1}}>first</Link></li>
<li><Link to={path} query={{page: prev || 1}}>prev</Link></li>
<li><Link to={path} query={{page: next || last}}>next</Link></li>
<li><Link to={path} query={{page: last}}>last</Link></li>
</ul>
);
};
Pager.propTypes = {
page: React.PropTypes.number,
per: React.PropTypes.number,
total: React.PropTypes.number
};
export default Pager;
| iris-dni/iris-frontend | src/components/Pager/index.js | JavaScript | apache-2.0 | 695 |
/*
* grunt-include-source
* https://github.com/jwvdiermen/grunt-include-source
*
* Copyright (c) 2013 Jan Willem van Diermen
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp'],
},
// Variables to be used in templates.
vars: {
hello: 'world',
testFilesPath: 'test/files',
multipleBasePath: [
'<%= vars.testFilesPath %>',
'test/multiple-paths'
],
cssPath: 'css',
lessPath: 'less',
scssPath: 'scss',
jsPath: 'js',
jsArray: [
'js/_first.js',
'js/lib/**/*.js',
'<%= vars.jsPath %>/main.js',
],
tsPath: 'ts'
},
// Configuration to be run (and then tested).
// For testing, we simply execute some tasks and validate the output.
includeSource: {
options: {
basePath: '<%= vars.testFilesPath %>',
baseUrl: ''
},
htmlTest: {
files: {
'tmp/index.html': '<%= vars.testFilesPath %>/index.html'
}
},
overwriteTest: {
files: {
'tmp/overwrite.html': '<%= vars.testFilesPath %>/overwrite.html'
}
},
cshtmlTest: {
files: {
'tmp/index.cshtml': '<%= vars.testFilesPath %>/index.cshtml'
}
},
hamlTest: {
files: {
'tmp/index.haml': '<%= vars.testFilesPath %>/index.haml'
}
},
jadeTest: {
files: {
'tmp/index.jade': '<%= vars.testFilesPath %>/index.jade'
}
},
lessTest: {
files: {
'tmp/main.less': '<%= vars.testFilesPath %>/main.less'
}
},
scssTest: {
files: {
'tmp/main.scss': '<%= vars.testFilesPath %>/main.scss'
}
},
tsTest: {
files: {
'tmp/references.ts': '<%= vars.testFilesPath %>/references.ts'
}
}
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js'],
},
lineending: {
options: {
eol: 'lf',
overwrite: true
},
files: ['test/expected/*.*', 'test/files/*.*']
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-lineending');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'includeSource', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test']);
};
| benyi09/mopidy-jukebox | src/node_modules/grunt-include-source/Gruntfile.js | JavaScript | apache-2.0 | 2,747 |
'use strict';
describe('Controller: CurrentListCtrl', function () {
// load the controller's module
beforeEach(module('sightWordsApp'));
var CurrentListCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
CurrentListCtrl = $controller('CurrentListCtrl', {
$scope: scope
// place here mocked dependencies
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(CurrentListCtrl.awesomeThings.length).toBe(3);
});
});
| kiranw06/sight-words | test/spec/controllers/current-list.js | JavaScript | apache-2.0 | 587 |
// This file has been autogenerated.
var profile = require('../../../lib/util/profile');
exports.getMockedProfile = function () {
var newProfile = new profile.Profile();
newProfile.addSubscription(new profile.Subscription({
id: 'bab71ab8-daff-4f58-8dfc-ed0d61a3fa6b',
name: 'KasotaTest-001',
user: {
name: 'user@domain.example',
type: 'user'
},
tenantId: '72f988bf-86f1-41af-91ab-2d7cd011db47',
state: 'Enabled',
registeredProviders: [],
_eventsCount: '1',
isDefault: true
}, newProfile.environments['AzureCloud']));
return newProfile;
};
exports.setEnvironment = function() {
process.env['AZURE_ARM_TEST_LOCATION'] = 'East US 2';
process.env['AZURE_ARM_TEST_RESOURCE_GROUP_1'] = 'xplattestadlsrg01';
process.env['AZURE_ARM_TEST_CDN_PROFILE_1'] = 'cliTestProfile01';
process.env['AZURE_ARM_TEST_RESOURCE_GROUP_2'] = 'xplattestadlsrg02';
process.env['AZURE_ARM_TEST_CDN_PROFILE_2'] = 'cliTestProfile02';
process.env['AZURE_ARM_TEST_CDN_ENDPOINT_1'] = 'cliTestEndpoint01';
process.env['AZURE_ARM_TEST_CDN_ENDPOINT_2'] = 'cliTestEndpoint02';
process.env['AZURE_ARM_TEST_CDN_ORIGIN_1'] = 'cliTestOrigin01';
process.env['AZURE_ARM_TEST_CDN_ORIGIN_2'] = 'cliTestOrigin02';
process.env['AZURE_ARM_TEST_ENDPOINT_TEST_LOCATION_1'] = 'eastus';
process.env['AZURE_ARM_TEST_CUSTOM_DOMAIN_NAME_1'] = 'cliTestCustomDomain01';
process.env['AZURE_ARM_TEST_CUSTOM_DOMAIN_HOST_NAME_1'] = 'cli-1-406f580d-a634-4077-9b11-216a70c5998d.azureedge-test.net';
};
exports.scopes = [[function (nock) {
var result =
nock('http://management.azure.com:443')
.delete('/subscriptions/bab71ab8-daff-4f58-8dfc-ed0d61a3fa6b/resourceGroups/xplattestadlsrg01/providers/Microsoft.Cdn/profiles/cliTestProfile01/endpoints/cliTestEndpoint02/customDomains/cliTestCustomDomain01?api-version=2015-06-01')
.reply(202, "", { 'cache-control': 'no-cache',
pragma: 'no-cache',
'content-length': '0',
expires: '-1',
location: 'https://management.azure.com/subscriptions/bab71ab8-daff-4f58-8dfc-ed0d61a3fa6b/resourcegroups/xplattestadlsrg01/providers/Microsoft.Cdn/operationresults/35432a4f-a053-4636-bcd2-5457c7046acd/profileresults/cliTestProfile01/endpointresults/cliTestEndpoint02/customdomainresults/cliTestCustomDomain01?api-version=2015-06-01',
'retry-after': '10',
'x-ms-request-id': 'c07bcda5-b5ce-42f3-a12b-638eb3f9da5a',
'x-ms-client-request-id': 'ca671b99-f1f2-4c1b-bce8-a2cdde801cf6',
'azure-asyncoperation': 'https://management.azure.com/subscriptions/bab71ab8-daff-4f58-8dfc-ed0d61a3fa6b/resourcegroups/xplattestadlsrg01/providers/Microsoft.Cdn/operationresults/35432a4f-a053-4636-bcd2-5457c7046acd?api-version=2015-06-01',
'strict-transport-security': 'max-age=31536000; includeSubDomains',
server: 'Microsoft-IIS/8.5',
'x-aspnet-version': '4.0.30319',
'x-powered-by': 'ASP.NET',
'x-ms-ratelimit-remaining-subscription-writes': '1197',
'x-ms-correlation-request-id': 'c09cb4af-ab0a-447b-8cf4-f6662321f597',
'x-ms-routing-request-id': 'WESTUS:20160317T184105Z:c09cb4af-ab0a-447b-8cf4-f6662321f597',
date: 'Thu, 17 Mar 2016 18:41:05 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('https://management.azure.com:443')
.delete('/subscriptions/bab71ab8-daff-4f58-8dfc-ed0d61a3fa6b/resourceGroups/xplattestadlsrg01/providers/Microsoft.Cdn/profiles/cliTestProfile01/endpoints/cliTestEndpoint02/customDomains/cliTestCustomDomain01?api-version=2015-06-01')
.reply(202, "", { 'cache-control': 'no-cache',
pragma: 'no-cache',
'content-length': '0',
expires: '-1',
location: 'https://management.azure.com/subscriptions/bab71ab8-daff-4f58-8dfc-ed0d61a3fa6b/resourcegroups/xplattestadlsrg01/providers/Microsoft.Cdn/operationresults/35432a4f-a053-4636-bcd2-5457c7046acd/profileresults/cliTestProfile01/endpointresults/cliTestEndpoint02/customdomainresults/cliTestCustomDomain01?api-version=2015-06-01',
'retry-after': '10',
'x-ms-request-id': 'c07bcda5-b5ce-42f3-a12b-638eb3f9da5a',
'x-ms-client-request-id': 'ca671b99-f1f2-4c1b-bce8-a2cdde801cf6',
'azure-asyncoperation': 'https://management.azure.com/subscriptions/bab71ab8-daff-4f58-8dfc-ed0d61a3fa6b/resourcegroups/xplattestadlsrg01/providers/Microsoft.Cdn/operationresults/35432a4f-a053-4636-bcd2-5457c7046acd?api-version=2015-06-01',
'strict-transport-security': 'max-age=31536000; includeSubDomains',
server: 'Microsoft-IIS/8.5',
'x-aspnet-version': '4.0.30319',
'x-powered-by': 'ASP.NET',
'x-ms-ratelimit-remaining-subscription-writes': '1197',
'x-ms-correlation-request-id': 'c09cb4af-ab0a-447b-8cf4-f6662321f597',
'x-ms-routing-request-id': 'WESTUS:20160317T184105Z:c09cb4af-ab0a-447b-8cf4-f6662321f597',
date: 'Thu, 17 Mar 2016 18:41:05 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('http://management.azure.com:443')
.get('/subscriptions/bab71ab8-daff-4f58-8dfc-ed0d61a3fa6b/resourcegroups/xplattestadlsrg01/providers/Microsoft.Cdn/operationresults/35432a4f-a053-4636-bcd2-5457c7046acd?api-version=2015-06-01')
.reply(200, "{\r\n \"status\":\"Succeeded\",\"error\":{\r\n \"code\":\"None\",\"message\":null\r\n }\r\n}", { 'cache-control': 'no-cache',
pragma: 'no-cache',
'content-length': '77',
'content-type': 'application/json; odata.metadata=minimal; odata.streaming=true',
expires: '-1',
'x-ms-request-id': 'a5217732-9c02-4bc3-91a3-bc926cc71716',
'x-ms-client-request-id': '58f9d4b1-2b6b-4c64-9167-10378f4fb078',
'odata-version': '4.0',
'strict-transport-security': 'max-age=31536000; includeSubDomains',
server: 'Microsoft-IIS/8.5',
'x-aspnet-version': '4.0.30319',
'x-powered-by': 'ASP.NET',
'x-ms-ratelimit-remaining-subscription-reads': '14998',
'x-ms-correlation-request-id': 'fe2e766a-c3c3-4830-8cfe-9315c27e2bd1',
'x-ms-routing-request-id': 'WESTUS:20160317T184136Z:fe2e766a-c3c3-4830-8cfe-9315c27e2bd1',
date: 'Thu, 17 Mar 2016 18:41:35 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('https://management.azure.com:443')
.get('/subscriptions/bab71ab8-daff-4f58-8dfc-ed0d61a3fa6b/resourcegroups/xplattestadlsrg01/providers/Microsoft.Cdn/operationresults/35432a4f-a053-4636-bcd2-5457c7046acd?api-version=2015-06-01')
.reply(200, "{\r\n \"status\":\"Succeeded\",\"error\":{\r\n \"code\":\"None\",\"message\":null\r\n }\r\n}", { 'cache-control': 'no-cache',
pragma: 'no-cache',
'content-length': '77',
'content-type': 'application/json; odata.metadata=minimal; odata.streaming=true',
expires: '-1',
'x-ms-request-id': 'a5217732-9c02-4bc3-91a3-bc926cc71716',
'x-ms-client-request-id': '58f9d4b1-2b6b-4c64-9167-10378f4fb078',
'odata-version': '4.0',
'strict-transport-security': 'max-age=31536000; includeSubDomains',
server: 'Microsoft-IIS/8.5',
'x-aspnet-version': '4.0.30319',
'x-powered-by': 'ASP.NET',
'x-ms-ratelimit-remaining-subscription-reads': '14998',
'x-ms-correlation-request-id': 'fe2e766a-c3c3-4830-8cfe-9315c27e2bd1',
'x-ms-routing-request-id': 'WESTUS:20160317T184136Z:fe2e766a-c3c3-4830-8cfe-9315c27e2bd1',
date: 'Thu, 17 Mar 2016 18:41:35 GMT',
connection: 'close' });
return result; }]]; | vivsriaus/azure-xplat-cli | test/recordings/arm-cli-cdn-management-tests/arm_Cdn_Custom_Domains_delete_command_should_successfully_delete_the_custom_domain.nock.js | JavaScript | apache-2.0 | 7,190 |
/* Copyright© 2000 - 2022 SuperMap Software Co.Ltd. All rights reserved.*/
(function () {
var r = new RegExp("(^|(.*?\\/))(include-web\.js)(\\?|$)"),
s = document.getElementsByTagName('script'), targetScript;
for (var i = 0; i < s.length; i++) {
var src = s[i].getAttribute('src');
if (src) {
var m = src.match(r);
if (m) {
targetScript = s[i];
break;
}
}
}
function inputScript(url) {
var script = '<script type="text/javascript" src="' + url + '"><' + '/script>';
document.writeln(script);
}
function inputCSS(url) {
var css = '<link rel="stylesheet" href="' + url + '">';
document.writeln(css);
}
function inArray(arr, item) {
for (i in arr) {
if (arr[i] == item) {
return true;
}
}
return false;
}
//加载类库资源文件
function load() {
var includes = (targetScript.getAttribute('include') || "").split(",");
var excludes = (targetScript.getAttribute('exclude') || "").split(",");
inputScript("../js/tokengenerator.js");
var jQueryInclude = false;
if (!inArray(excludes, 'example-i18n')) {
inputScript("https://iclient.supermap.io/web/libs/jquery/jquery.min.js");
inputScript("https://iclient.supermap.io/web/libs/i18next/i18next.min.js");
inputScript("https://iclient.supermap.io/web/libs/jquery-i18next/jquery-i18next.min.js");
inputScript("../js/utils.js");
inputScript("../js/localization.js");
document.writeln("<script>Localization.initializeI18N('../', function () {Localization.localize();Localization.initGlobal();}); </script>");
jQueryInclude = true;
}
if (inArray(includes, 'jquery') && !jQueryInclude) {
inputScript("https://iclient.supermap.io/web/libs/jquery/jquery.min.js");
}
if (inArray(includes, 'bootstrap')) {
inputScript("https://iclient.supermap.io/web/libs/jquery/jquery.min.js");
inputCSS("https://iclient.supermap.io/web/libs/bootstrap/css/bootstrap.min.css");
inputScript("https://iclient.supermap.io/web/libs/bootstrap/js/bootstrap.min.js");
}
if (inArray(includes, 'bootstrap-css')) {
inputCSS("https://iclient.supermap.io/web/libs/bootstrap/css/bootstrap.min.css")
}
if (inArray(includes, 'bootstrap-js')) {
inputScript("https://iclient.supermap.io/web/libs/bootstrap/js/bootstrap.min.js");
}
if (inArray(includes, 'jquery-ui')) {
inputCSS("https://iclient.supermap.io/web/libs/jquery-ui/1.12.1/jquery-ui.css");
inputScript("https://iclient.supermap.io/web/libs/jquery-ui/1.12.1/jquery-ui.min.js");
}
if (inArray(includes, 'template')) {
inputScript("https://iclient.supermap.io/web/libs/art-template/template-web.js");
}
if (inArray(includes, 'randomcolor')) {
inputScript("https://iclient.supermap.io/web/libs/randomcolor/randomColor.min.js");
}
if (inArray(includes, 'papaparse')) {
inputScript("https://iclient.supermap.io/web/libs/papaparse/papaparse.min.js");
}
if (inArray(includes, 'moment')) {
inputScript("https://iclient.supermap.io/web/libs/moment/2.29.1/moment.min.js");
inputScript("https://iclient.supermap.io/web/libs/moment/2.29.1/zh-cn.js");
}
if (inArray(includes, 'bootstrap-datetimepicker')) {
inputCSS("https://iclient.supermap.io/web/libs/bootstrap-datetimepicker/bootstrap-datetimepicker.min.css");
inputScript("https://iclient.supermap.io/web/libs/bootstrap-datetimepicker/bootstrap-datetimepicker.min.js");
}
if (inArray(includes, 'bootstrap-select')) {
inputCSS("https://iclient.supermap.io/web/libs/bootstrap-select/bootstrap-select.min.css");
inputScript("https://iclient.supermap.io/web/libs/bootstrap-select/bootstrap-select.min.js");
}
if (inArray(includes, 'geohash')) {
inputScript("https://iclient.supermap.io/web/libs/geohash/geohash.js");
}
if (inArray(includes, 'dat-gui')) {
inputScript("https://iclient.supermap.io/web/libs/dat-gui/0.7.6/dat.gui.min.js");
datGuiI18N();
}
if (inArray(includes, 'admin-lte')) {
inputCSS("https://iclient.supermap.io/web/libs/admin-lte/css/AdminLTE.min.css");
inputCSS("https://iclient.supermap.io/web/libs/admin-lte/css/skins/skin-blue.min.css");
inputCSS("https://iclient.supermap.io/web/libs/font-awesome/css/font-awesome.min.css");
inputScript("https://iclient.supermap.io/web/libs/admin-lte/js/app.min.js");
}
if (inArray(includes, 'jquery.scrollto')) {
inputScript("https://iclient.supermap.io/web/libs/jquery.scrollto/jquery.scrollTo.min.js");
}
if (inArray(includes, 'ace')) {
inputScript("https://iclient.supermap.io/web/libs/ace/ace.js");
}
if (inArray(includes, 'widgets.alert')) {
inputScript("../js/widgets.js");
}
if (inArray(includes, 'widgets')) {
inputCSS("https://iclient.supermap.io/web/libs/css-loader/css-loader.css");
inputScript("../js/widgets.js");
}
if (inArray(includes, 'zTree')) {
inputCSS("https://iclient.supermap.io/web/libs/iclient8c/examples/js/plottingPanel/zTree/css/zTreeStyle.css");
inputScript("https://iclient.supermap.io/web/libs/iclient8c/examples/js/plottingPanel/zTree/jquery.ztree.core.js");
}
if (inArray(includes, 'jquery-scontextMenu')) {
inputCSS("https://iclient.supermap.io/web/libs/jquery.contextMenu/jquery.contextMenu.min.css");
inputScript("https://iclient.supermap.io/web/libs/jquery.contextMenu/jquery.contextMenu.min.js");
}
if (inArray(includes, 'colorpicker')) {
inputScript("https://iclient.supermap.io/web/libs/iclient8c/examples/js/jquery.js");
inputScript("https://iclient.supermap.io/web/libs/iclient8c/examples/js/jquery.colorpicker.js");
}
if (inArray(includes, 'fileupLoad')) {
inputScript("https://iclient.supermap.io/web/libs/iclient8c/examples/js/jquery.js");
inputScript("https://iclient.supermap.io/web/libs/iclient8c/examples/js/fileupLoad.js");
}
if (inArray(includes, 'sticklr')) {
inputCSS("https://iclient.supermap.io/web/libs/iclient8c/examples/css/jquery-sticklr.css");
inputCSS("https://iclient.supermap.io/web/libs/iclient8c/examples/css/icon.css");
}
if (inArray(includes, 'responsive')) {
inputCSS("https://iclient.supermap.io/web/libs/iclient8c/examples/css/bootstrap-responsive.min.css");
}
if (inArray(includes, 'lazyload')) {
inputScript("https://iclient.supermap.io/web/libs/lazyload/jquery.lazyload.min.js");
}
if (inArray(includes, 'i18n')) {
inputScript("https://iclient.supermap.io/web/libs/i18next/i18next.min.js");
inputScript("https://iclient.supermap.io/web/libs/jquery-i18next/jquery-i18next.min.js");
}
if (inArray(includes, 'react')) {
inputScript("https://iclient.supermap.io/web/libs/react/16.4.2/react.production.min.js");
inputScript("https://iclient.supermap.io/web/libs/react/16.4.2/react-dom.production.min.js");
inputScript("https://iclient.supermap.io/web/libs/babel/6.26.0/babel.min.js");
}
if (inArray(includes, 'vue')) {
inputScript("https://iclient.supermap.io/web/libs/vue/2.5.17/vue.min.js");
}
if (inArray(includes, 'ionRangeSlider')) {
inputCSS("https://iclient.supermap.io/web/libs/ionRangeSlider/2.2.0/css/ion.rangeSlider.css");
inputCSS("https://iclient.supermap.io/web/libs/ionRangeSlider/2.2.0/css/normalize.css");
inputCSS("https://iclient.supermap.io/web/libs/ionRangeSlider/2.2.0/css/ion.rangeSlider.skinHTML5.css");
inputScript("https://iclient.supermap.io/web/libs/ionRangeSlider/2.2.0/js/ion.rangeSlider.min.js");
}
if (inArray(includes, 'plottingPanel')) {
inputScript("https://iclient.supermap.io/web/libs/iclient8c/examples/js/plottingPanel/zTree/jquery.ztree.core.js");
inputCSS("https://iclient.supermap.io/web/libs/iclient8c/examples/js/plottingPanel/zTree/css/zTreeStyle.css");
inputScript("https://iclient.supermap.io/web/libs/iclient8c/examples/js/plottingPanel/jquery-easyui-1.4.4/jquery.easyui.min.js");
inputCSS("https://iclient.supermap.io/web/libs/iclient8c/examples/js/plottingPanel/jquery-easyui-1.4.4/css/easyui.css");
inputScript("https://iclient.supermap.io/web/libs/iclient8c/examples/js/plottingPanel/colorpicker/js/colorpicker.js");
inputCSS("https://iclient.supermap.io/web/libs/iclient8c/examples/js/plottingPanel/colorpicker/css/colorpicker.css");
}
}
function datGuiI18N() {
document.writeln("<script>function registerEventListener(evt,fn){" +
"if(window.attachEvent){window.attachEvent('on'+evt,fn);}" +
"else{window.addEventListener(evt,fn,false);}" +
"}</script>");
document.writeln("<script>registerEventListener('load',function() { " +
"dat.GUI.TEXT_CLOSED=resources.text_close;dat.GUI.TEXT_OPEN=resources.text_open;" +
"})</script>")
}
load();
window.isLocal = false;
window.server = document.location.toString().match(/file:\/\//) ? "http://localhost:8090" : document.location.protocol + "//" + document.location.host;
window.version = "10.2.1";
window.preRelease = "";
})();
| SuperMap/iClient9 | examples/js/include-web.js | JavaScript | apache-2.0 | 10,005 |
/**
cache.js
Basic caching for server. Entries consist of:
• key: cache key for reference
• type: file type (for sending)
• val: value
Middleware creates a cache key based on the route and returns the entry if available.
**/
var get = require("lodash/get");
var Utils = require("./utils");
var Renderers = require("./renderers");
var minimatch = require("minimatch");
var Cache = module.exports = {
enabled: true,
store: require("lru-cache")({
max: get(global.shipp, "config.cache.sizeLimit"),
length: function(cached, key) {
var val = cached.val;
// Assume vanilla types have byte size 4, calculate all others
var size = 4;
if (Buffer.isBuffer(val))
size = val.length;
else if ("string" === typeof(val))
size = Buffer.byteLength(val);
// Object keys = 7 (string length of type, val)
return size + 7 + Buffer.byteLength(key) + Buffer.byteLength(cached.type || "");
}
}),
has: function(key) {
return Cache.store.has(key);
},
length: function() {
return Cache.store.length;
},
/**
Gets an object from the cache.
@param {String} key The key of the object
@returns {*} The object
**/
get: function(key) {
return Cache.store.get(key);
},
/**
Sets an object in the cache.
@param {String} key The key of the object
@param {Object} value The object to store
**/
set: function(key, value) {
if (!Cache.enabled) return;
if ("undefined" === typeof value)
Cache.unset(key);
else
Cache.store.set(key, value);
},
/**
Unsets an object in the cache.
@param {String} key The key of the object
**/
unset: function(key) {
if (!Cache.enabled) return;
Cache.store.del(key);
},
/**
Warms a route
!!! TODO: This function should not currently be used
@param {String} id Route id
@param {String} method Compression method (defaults to gzip)
@param {Object} params query parameters (defaults to {})
@returns {Promise} Resolves after warming and returns cache key
**/
warm: function(id, method, params) {
// Unset existing cache
method = method || "gzip";
var cacheKey = method + ":" + id;
Cache.unset(cacheKey);
// Get renderer and exit if not found
var renderer = Renderers.getRenderer(id);
if ("undefined" === typeof(renderer)) return;
// Run renderer and store results
return renderer.fn(params || {}, method, false)
.then(function(results) {
global.shipp.debug(`event: cache-warm, key: ${cacheKey}`);
Cache.set(cacheKey, { val: results.contents, type: renderer.type });
return cacheKey;
});
},
/**
Cools a route
@param {String} id Route id
@param {String} method Compression method (defaults to gzip)
@returns {String} Cache key
**/
cool: function(id, method) {
method = method || "gzip";
var cacheKey = method + ":" + id;
Cache.unset(cacheKey);
},
/**
Invalidates objects in the cache via glob matching.
@param {String} pattern Glob pattern (see https://github.com/isaacs/minimatch)
@param {Boolean} [ignoreCase] When true, performs case insensitive match (default: true)
@returns {Array} Array of strings invalidated
**/
invalidate: function(pattern, ignoreCase) {
var keys = Cache.store.keys(),
matches = [],
re;
ignoreCase = (false === ignoreCase) ? false : true;
// minimatch.match seems to have issues with matching slashes. Use its RegExp instead.
// We prefix gzip, etc. in order to allow the user to think of patterns in terms of "routes".
if ("string" === typeof pattern)
re = minimatch.makeRe("?(gzip:|identity:|deflate:)" + pattern, { nocase: ignoreCase });
else
re = pattern;
if (re instanceof RegExp)
matches = keys.filter(function(key) {
return re.test(key);
});
else
throw new Error("Pattern must be string (glob) or RegExp");
// Delete from cache
matches.forEach(Cache.unset);
global.shipp.debug("Invalidated " + matches.length + " route(s) given " + pattern);
return matches;
},
/**
Clear the cache entirely, throwing away all values.
**/
reset: function() {
return Cache.store.reset();
},
/**
Return an array of the keys in the cache.
**/
keys: function() {
return Cache.store.keys();
},
/**
Middleware
Note: we do not currently use query strings as part of caching. To do this effectively,
certain parameters (such as those used in web tracking) must be removed.
**/
middleware: function() {
var router = global.shipp.router();
router.use("*", function(req, res, next) {
if (res.locals.bypassCache) {
next()
return
}
var compression = req.acceptsEncodings(["gzip", "deflate", "identity"]) || "identity";
// Attach cacheKey to the request
var cacheKey = res.locals.cacheKey = compression + ":" + req.originalUrl;
if (Cache.has(cacheKey)) {
global.shipp.debug("Cache hit for " + cacheKey);
var cached = Cache.get(cacheKey);
Utils.send(res, cached.type, cached.val, compression);
} else {
next();
}
})
global.shipp.debug("Caching middleware added");
return router;
}
};
| shippjs/shipp-server | lib/cache.js | JavaScript | apache-2.0 | 5,419 |
// ==UserScript==
// @name BroniesNL - Finfobar removal
// @namespace http://frankkie.nl/
// @version 0.1
// @description remove finfobar (bar below post)
// @author FrankkieNL
// @match http*://bronies.nl/e107_plugins/forum/forum_viewtopic.php?*
// @grant none
// @downloadURL https://github.com/frankkienl/BroniesNL-Tampermonkey-Scripts/raw/master/broniesnl_finfobar_removal.user.js
// @supportURL https://github.com/frankkienl/BroniesNL-Tampermonkey-Scripts/
// ==/UserScript==
var finfos = document.getElementsByClassName('finfobar');
for (var i=0;i<finfos.length; i++){finfos[i].style.display='none';}
| frankkienl/BroniesNL-Tampermonkey-Scripts | broniesnl_finfobar_removal.user.js | JavaScript | apache-2.0 | 648 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
//import * as moment from "moment";
const luxon = tslib_1.__importStar(require("luxon"));
const bluebird_1 = tslib_1.__importDefault(require("bluebird"));
/**
* abstract class used for elements stored in the AtomicCache object
*/
class AtomicCacheItem {
constructor(key,
/** max amount of time between uses of the cacheItem before we dispose it */
_maxUnusedDuration,
/** max amount of time between sync's */
_maxDesyncedDuration,
/** if set, and the first sync (during initialization) fails, all future .get() calls within the given duration will return rejected with the same error originally returned from sync.
This is useful if for example, the user requests a key that does not exist.
If you use this, be sure you put retry logic into your doSyncWithMaster functions.
*/
_blacklistIfFirstSyncFailsDuration = null) {
this.key = key;
this._maxUnusedDuration = _maxUnusedDuration;
this._maxDesyncedDuration = _maxDesyncedDuration;
this._blacklistIfFirstSyncFailsDuration = _blacklistIfFirstSyncFailsDuration;
this._syncPending = bluebird_1.default.resolve();
/** private helper to know when we have read the state from datastore */
this._isInitialized = false;
/** private helper to know when this should not be used again */
this._isDisposed = false;
this._lastUsedTime = luxon.DateTime.utc();
this._trySyncWithMaster();
}
/** read only: the last time this was used */
get lastUsedTime() {
return this._lastUsedTime;
}
/**
* if it's time to resync
*/
isTimeToResync() {
let now = luxon.DateTime.utc();
if (this._lastSyncTime.plus(this._maxDesyncedDuration) <= now) {
//out of sync
return true;
}
return false;
}
/**
* attempts to sync with master, if there is any sync work to be done
*/
_trySyncWithMaster(forceSync = false) {
if (this._syncPending.isResolved() !== true) {
//another sync is in progress, so lets return that one's bb;
return this._syncPending;
}
if (this._isInitialized !== true) {
//this is the initialization
//no need to do a full sync, just read
this._syncPending = this.doSyncWithMaster_Helper_Read()
.catch((initError) => {
//handle _blacklistIfFirstSyncFails logic if set (via ctor)
if (this._blacklistIfFirstSyncFailsDuration != null) {
this._blacklistIfFirstSyncFails_Timeout = luxon.DateTime.utc().plus(this._blacklistIfFirstSyncFailsDuration);
this._blacklistIfFirstSyncFails_InitError = initError;
}
return bluebird_1.default.reject(initError);
})
.then((readSyncResults) => {
this._isInitialized = true;
this._lastSyncTime = luxon.DateTime.utc();
if (this.hasDataToWrite() === true) {
//async update a full sync
this.doSyncWithMaster_Helper_Full().then(() => {
this._lastSyncTime = luxon.DateTime.utc();
});
}
return bluebird_1.default.resolve(readSyncResults);
});
return this._syncPending;
}
else {
//already initialized
if (this.hasDataToWrite() === true && (this.isTimeToResync() === true || forceSync === true)) {
//time to sync and have data to write, so need to do full sync
this._syncPending = this.doSyncWithMaster_Helper_Full()
.then((fullResults) => {
this._lastSyncTime = luxon.DateTime.utc();
return bluebird_1.default.resolve(fullResults);
});
return this._syncPending;
}
else if (forceSync === true || this.isTimeToResync() === true) {
//time to sync and have NO data to write, so just read
this._syncPending = this.doSyncWithMaster_Helper_Read()
.then((fullResults) => {
this._lastSyncTime = luxon.DateTime.utc();
return bluebird_1.default.resolve(fullResults);
});
return this._syncPending;
}
else {
//no data to write and not desynced
return bluebird_1.default.resolve();
}
}
}
get() {
return bluebird_1.default.try(() => {
if (this._isDisposed === true) {
throw new Error("already disposed");
}
this._lastUsedTime = luxon.DateTime.utc();
if (this._blacklistIfFirstSyncFails_InitError != null) {
if (this._blacklistIfFirstSyncFails_Timeout < luxon.DateTime.utc()) {
return bluebird_1.default.reject(this._blacklistIfFirstSyncFails_InitError);
}
else {
//clear out the error
this._blacklistIfFirstSyncFails_InitError = null;
}
}
//let toReturn: TValue;
if (this._isInitialized !== true) {
//no sync yet, so wait for that
return this._trySyncWithMaster()
.then(() => {
//let currentData = this._creditBalance.data;
let toReturn = this.calculateCurrentValue();
return bluebird_1.default.resolve(toReturn);
});
}
else {
//return current balance data
let toReturn = this.calculateCurrentValue();
this._trySyncWithMaster();
return bluebird_1.default.resolve(toReturn);
}
});
}
getForceSync() {
if (this._isDisposed === true) {
throw new Error("already disposed");
}
this._lastUsedTime = luxon.DateTime.utc();
if (this._blacklistIfFirstSyncFails_InitError != null) {
if (this._blacklistIfFirstSyncFails_Timeout < luxon.DateTime.utc()) {
return bluebird_1.default.reject(this._blacklistIfFirstSyncFails_InitError);
}
else {
//clear out the error
this._blacklistIfFirstSyncFails_InitError = null;
}
}
return this._trySyncWithMaster(true)
.then(() => {
return this.get();
});
}
modify(params) {
if (this._isDisposed === true) {
throw new Error("already disposed");
}
this._lastUsedTime = luxon.DateTime.utc();
this.cacheModificationsLocally(params);
if (this._blacklistIfFirstSyncFails_InitError != null) {
if (this._blacklistIfFirstSyncFails_Timeout < luxon.DateTime.utc()) {
return;
}
else {
//clear out the error
this._blacklistIfFirstSyncFails_InitError = null;
}
}
this._trySyncWithMaster(); //async attempt
}
/**
* if last use is too old, will return true and dispose.
*/
tryDisposeIfTooOld(forceDisposeNow = false) {
if (forceDisposeNow === true) {
this._dispose();
return true;
}
let disposeAfter = this._lastUsedTime.plus(this._maxUnusedDuration);
if (disposeAfter >= luxon.DateTime.utc()) {
return false;
}
//dispose
this._dispose();
return true;
}
/**
* do a final sync with the master and mark this object as unusable
*/
_dispose() {
if (this._isDisposed === true) {
throw new Error("already disposed");
}
this._isDisposed = true;
if (this.hasDataToWrite() === true) {
//do a final sync
this._trySyncWithMaster();
}
}
}
exports.AtomicCacheItem = AtomicCacheItem;
/**
* allows for local caching of values, plus ability to atomically synchronize modifications with the master
* this pattern is known to work with google datastore (via transactions) so can probably be adapted to anything else too.
* this is useful for data that is tollerant of eventual-consistency. not so useful as-is for immediate/atomic consistency needs.
*/
class AtomicCache {
constructor(_cacheItemCtor, _autoTryCleanupInterval) {
this._cacheItemCtor = _cacheItemCtor;
this._autoTryCleanupInterval = _autoTryCleanupInterval;
this._storage = {};
this._nextInspectIndex = 0;
this._inspectKeys = [];
setInterval(() => {
this._tryCleanupOne();
}, this._autoTryCleanupInterval.as("millisecond"));
}
_tryCleanupOne(/** set to true to force cleaning up all keys immediately for testing "new apiKey" roundtrip times. default false. */ testingForceDispose = false) {
if (this._nextInspectIndex >= this._inspectKeys.length) {
//past end, re-aquire
this._nextInspectIndex = 0;
this._inspectKeys = Object.keys(this._storage);
}
if (this._inspectKeys.length < 1) {
return; //nothing to do;
}
//try to clean up (dispose) an item that's too old
let currentIndex = this._nextInspectIndex;
this._nextInspectIndex++;
let key = this._inspectKeys[currentIndex];
if (this._storage[key].tryDisposeIfTooOld(testingForceDispose) === true) {
// tslint:disable-next-line: no-dynamic-delete
delete this._storage[key];
//since we clean up 1, try to clean another (keep going till we hit 1 that doesn't cleanup)
setTimeout(() => {
//log.info("disposing " + key);
this._tryCleanupOne(testingForceDispose);
return;
});
}
}
_getItem(key) {
let item = this._storage[key];
if (item == null || item.tryDisposeIfTooOld() === true) {
item = this._cacheItemCtor(key); // new CacheItem(key);
this._storage[key] = item;
}
return item;
}
getTestForceNew(key) {
let item = this._getItem(key);
let toReturn = item.get().then((value) => {
setTimeout(() => {
this._tryCleanupOne(true);
});
return value;
});
//force invalidate to test
//item.lastUsedTime = moment(0);
//item._dispose();
return toReturn;
}
get(apiKey) {
let item = this._getItem(apiKey);
let toReturn = item.get().then((value) => {
setTimeout(() => {
this._tryCleanupOne();
});
return value;
});
return toReturn;
}
getForceRefresh(apiKey) {
let item = this._getItem(apiKey);
let toReturn = item.getForceSync().then((value) => {
setTimeout(() => {
this._tryCleanupOne();
});
return value;
});
return toReturn;
}
modify(key, params) {
let item = this._getItem(key);
item.modify(params);
//let toReturn = item.getBalance();
//this._tryCleanupOne();
//return toReturn;
//
return item.get();
}
}
exports.AtomicCache = AtomicCache;
//# sourceMappingURL=atomic-cache.js.map | Novaleaf/xlib | _obsolete/xlib-v17/built/_obsolete/atomic-cache.js | JavaScript | apache-2.0 | 11,706 |
/**
* @author Diego Resendez <diego.resendez@zero-oneit.com>
*/
var exceptions = require("../exceptions/zoExceptions");
var u = require("underscore")._;
(function ($){
var config = function(settings){
settings = settings || {};
var self = {}
u.extend(self, settings);
self.isBatch = self.isBatch || false;
self.Default_Class = self.Default_Class || 'main';
self.actualPath = process.cwd();
self.responses_dir = '/responses/';
self.JSON_RPC = "2.0";
return self;
}
$.config = config;
}(typeof window === 'undefined' ? exports:window));
| zerooneit/zoServices-JS | server/classes/zoConfig.js | JavaScript | apache-2.0 | 563 |