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
|
---|---|---|---|---|---|
// Copyright 2008 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
var a = [0,1,2,3];
assertEquals(0, a.length = 0);
assertEquals('undefined', typeof a[0]);
assertEquals('undefined', typeof a[1]);
assertEquals('undefined', typeof a[2]);
assertEquals('undefined', typeof a[3]);
var a = [0,1,2,3];
assertEquals(2, a.length = 2);
assertEquals(0, a[0]);
assertEquals(1, a[1]);
assertEquals('undefined', typeof a[2]);
assertEquals('undefined', typeof a[3]);
var a = new Array();
a[0] = 0;
a[1000] = 1000;
a[1000000] = 1000000;
a[2000000] = 2000000;
assertEquals(2000001, a.length);
assertEquals(0, a.length = 0);
assertEquals(0, a.length);
assertEquals('undefined', typeof a[0]);
assertEquals('undefined', typeof a[1000]);
assertEquals('undefined', typeof a[1000000]);
assertEquals('undefined', typeof a[2000000]);
var a = new Array();
a[0] = 0;
a[1000] = 1000;
a[1000000] = 1000000;
a[2000000] = 2000000;
assertEquals(2000001, a.length);
assertEquals(2000, a.length = 2000);
assertEquals(2000, a.length);
assertEquals(0, a[0]);
assertEquals(1000, a[1000]);
assertEquals('undefined', typeof a[1000000]);
assertEquals('undefined', typeof a[2000000]);
var a = new Array();
a[Math.pow(2,31)-1] = 0;
a[Math.pow(2,30)-1] = 0;
assertEquals(Math.pow(2,31), a.length);
var a = new Array();
a[0] = 0;
a[1000] = 1000;
a[Math.pow(2,30)-1] = Math.pow(2,30)-1;
a[Math.pow(2,31)-1] = Math.pow(2,31)-1;
a[Math.pow(2,32)-2] = Math.pow(2,32)-2;
assertEquals(Math.pow(2,30)-1, a[Math.pow(2,30)-1]);
assertEquals(Math.pow(2,31)-1, a[Math.pow(2,31)-1]);
assertEquals(Math.pow(2,32)-2, a[Math.pow(2,32)-2]);
assertEquals(Math.pow(2,32)-1, a.length);
assertEquals(Math.pow(2,30) + 1, a.length = Math.pow(2,30)+1); // not a smi!
assertEquals(Math.pow(2,30)+1, a.length);
assertEquals(0, a[0]);
assertEquals(1000, a[1000]);
assertEquals(Math.pow(2,30)-1, a[Math.pow(2,30)-1]);
assertEquals('undefined', typeof a[Math.pow(2,31)-1]);
assertEquals('undefined', typeof a[Math.pow(2,32)-2], "top");
var a = new Array();
assertEquals(Object(12), a.length = new Number(12));
assertEquals(12, a.length);
Number.prototype.valueOf = function() { return 10; }
var n = new Number(100);
assertEquals(n, a.length = n);
assertEquals(10, a.length);
n.valueOf = function() { return 20; }
assertEquals(n, a.length = n);
assertEquals(20, a.length);
var o = { length: -23 };
Array.prototype.pop.apply(o);
assertEquals(4294967272, o.length);
// Check case of compiled stubs.
var a = [];
for (var i = 0; i < 7; i++) {
assertEquals(3, a.length = 3);
var t = 239;
t = a.length = 7;
assertEquals(7, t);
}
(function () {
"use strict";
var frozen_object = Object.freeze({__proto__:[]});
assertThrows(function () { frozen_object.length = 10 });
})();
| victorzhao/miniblink49 | v8_4_5/test/mjsunit/array-length.js | JavaScript | gpl-3.0 | 4,264 |
define(['angular'], function(angular) {
'use strict';
return angular.module('superdesk.services.storage', [])
/**
* LocalStorage wrapper
*
* it stores data as json to keep its type
*/
.service('storage', function() {
/**
* Get item from storage
*
* @param {string} key
* @returns {mixed}
*/
this.getItem = function(key) {
return angular.fromJson(localStorage.getItem(key));
};
/**
* Set storage item
*
* @param {string} key
* @param {mixed} data
*/
this.setItem = function(key, data) {
localStorage.setItem(key, angular.toJson(data));
};
/**
* Remove item from storage
*
* @param {string} key
*/
this.removeItem = function(key) {
localStorage.removeItem(key);
};
/**
* Remove all items from storage
*/
this.clear = function() {
localStorage.clear();
};
});
});
| plamut/superdesk | client/app/scripts/superdesk/services/storage.js | JavaScript | agpl-3.0 | 1,250 |
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
erpnext.POS = Class.extend({
init: function(wrapper, frm) {
this.wrapper = wrapper;
this.frm = frm;
this.wrapper.html('<div class="container">\
<div class="row" style="margin: -9px 0px 10px -30px; border-bottom: 1px solid #c7c7c7;">\
<div class="party-area col-sm-3 col-xs-6"></div>\
<div class="barcode-area col-sm-3 col-xs-6"></div>\
<div class="search-area col-sm-3 col-xs-6"></div>\
<div class="item-group-area col-sm-3 col-xs-6"></div>\
</div>\
<div class="row">\
<div class="col-sm-6">\
<div class="pos-bill">\
<div class="item-cart">\
<table class="table table-condensed table-hover" id="cart" style="table-layout: fixed;">\
<thead>\
<tr>\
<th style="width: 40%">Item</th>\
<th style="width: 9%"></th>\
<th style="width: 17%; text-align: right;">Qty</th>\
<th style="width: 9%"></th>\
<th style="width: 25%; text-align: right;">Rate</th>\
</tr>\
</thead>\
<tbody>\
</tbody>\
</table>\
</div>\
<br>\
<div class="totals-area" style="margin-left: 40%;">\
<table class="table table-condensed">\
<tr>\
<td><b>Net Total</b></td>\
<td style="text-align: right;" class="net-total"></td>\
</tr>\
</table>\
<div class="tax-table" style="display: none;">\
<table class="table table-condensed">\
<thead>\
<tr>\
<th style="width: 60%">Taxes</th>\
<th style="width: 40%; text-align: right;"></th>\
</tr>\
</thead>\
<tbody>\
</tbody>\
</table>\
</div>\
<div class="grand-total-area">\
<table class="table table-condensed">\
<tr>\
<td style="vertical-align: middle;"><b>Grand Total</b></td>\
<td style="text-align: right; font-size: 200%; \
font-size: bold;" class="grand-total"></td>\
</tr>\
</table>\
</div>\
</div>\
</div>\
<br><br>\
<div class="row">\
<div class="col-sm-9">\
<button class="btn btn-success btn-lg make-payment">\
<i class="icon-money"></i> Make Payment</button>\
</div>\
<div class="col-sm-3">\
<button class="btn btn-default btn-lg remove-items" style="display: none;">\
<i class="icon-trash"></i> Del</button>\
</div>\
</div>\
<br><br>\
</div>\
<div class="col-sm-6">\
<div class="item-list-area">\
<div class="col-sm-12">\
<div class="row item-list"></div></div>\
</div>\
</div>\
</div></div>');
this.check_transaction_type();
this.make();
var me = this;
$(this.frm.wrapper).on("refresh-fields", function() {
me.refresh();
});
this.call_function("remove-items", function() {me.remove_selected_items();});
this.call_function("make-payment", function() {me.make_payment();});
},
check_transaction_type: function() {
var me = this;
// Check whether the transaction is "Sales" or "Purchase"
if (wn.meta.has_field(cur_frm.doc.doctype, "customer")) {
this.set_transaction_defaults("Customer", "export");
}
else if (wn.meta.has_field(cur_frm.doc.doctype, "supplier")) {
this.set_transaction_defaults("Supplier", "import");
}
},
set_transaction_defaults: function(party, export_or_import) {
var me = this;
this.party = party;
this.price_list = (party == "Customer" ?
this.frm.doc.selling_price_list : this.frm.doc.buying_price_list);
this.sales_or_purchase = (party == "Customer" ? "Sales" : "Purchase");
this.net_total = "net_total_" + export_or_import;
this.grand_total = "grand_total_" + export_or_import;
this.amount = export_or_import + "_amount";
this.rate = export_or_import + "_rate";
},
call_function: function(class_name, fn, event_name) {
this.wrapper.find("." + class_name).on(event_name || "click", fn);
},
make: function() {
this.make_party();
this.make_item_group();
this.make_search();
this.make_barcode();
this.make_item_list();
},
make_party: function() {
var me = this;
this.party_field = wn.ui.form.make_control({
df: {
"fieldtype": "Link",
"options": this.party,
"label": this.party,
"fieldname": "pos_party",
"placeholder": this.party
},
parent: this.wrapper.find(".party-area"),
only_input: true,
});
this.party_field.make_input();
this.party_field.$input.on("change", function() {
if(!me.party_field.autocomplete_open)
wn.model.set_value(me.frm.doctype, me.frm.docname,
me.party.toLowerCase(), this.value);
});
},
make_item_group: function() {
var me = this;
this.item_group = wn.ui.form.make_control({
df: {
"fieldtype": "Link",
"options": "Item Group",
"label": "Item Group",
"fieldname": "pos_item_group",
"placeholder": "Item Group"
},
parent: this.wrapper.find(".item-group-area"),
only_input: true,
});
this.item_group.make_input();
this.item_group.$input.on("change", function() {
if(!me.item_group.autocomplete_open)
me.make_item_list();
});
},
make_search: function() {
var me = this;
this.search = wn.ui.form.make_control({
df: {
"fieldtype": "Data",
"label": "Item",
"fieldname": "pos_item",
"placeholder": "Search Item"
},
parent: this.wrapper.find(".search-area"),
only_input: true,
});
this.search.make_input();
this.search.$input.on("keypress", function() {
if(!me.search.autocomplete_open)
if(me.item_timeout)
clearTimeout(me.item_timeout);
me.item_timeout = setTimeout(function() { me.make_item_list(); }, 1000);
});
},
make_barcode: function() {
var me = this;
this.barcode = wn.ui.form.make_control({
df: {
"fieldtype": "Data",
"label": "Barcode",
"fieldname": "pos_barcode",
"placeholder": "Barcode / Serial No"
},
parent: this.wrapper.find(".barcode-area"),
only_input: true,
});
this.barcode.make_input();
this.barcode.$input.on("keypress", function() {
if(me.barcode_timeout)
clearTimeout(me.barcode_timeout);
me.barcode_timeout = setTimeout(function() { me.add_item_thru_barcode(); }, 1000);
});
},
make_item_list: function() {
var me = this;
me.item_timeout = null;
wn.call({
method: 'accounts.doctype.sales_invoice.pos.get_items',
args: {
sales_or_purchase: this.sales_or_purchase,
price_list: this.price_list,
item_group: this.item_group.$input.val(),
item: this.search.$input.val()
},
callback: function(r) {
var $wrap = me.wrapper.find(".item-list");
me.wrapper.find(".item-list").empty();
if (r.message) {
$.each(r.message, function(index, obj) {
if (obj.image)
image = '<img src="' + obj.image + '" class="img-responsive" \
style="border:1px solid #eee; max-height: 140px;">';
else
image = '<div class="missing-image"><i class="icon-camera"></i></div>';
$(repl('<div class="col-xs-3 pos-item" data-item_code="%(item_code)s">\
<div style="height: 140px; overflow: hidden;">%(item_image)s</div>\
<div class="small">%(item_code)s</div>\
<div class="small">%(item_name)s</div>\
<div class="small">%(item_price)s</div>\
</div>',
{
item_code: obj.name,
item_price: format_currency(obj.ref_rate, obj.currency),
item_name: obj.name===obj.item_name ? "" : obj.item_name,
item_image: image
})).appendTo($wrap);
});
}
// if form is local then allow this function
$(me.wrapper).find("div.pos-item").on("click", function() {
if(me.frm.doc.docstatus==0) {
if(!me.frm.doc[me.party.toLowerCase()] && ((me.frm.doctype == "Quotation" &&
me.frm.doc.quotation_to == "Customer")
|| me.frm.doctype != "Quotation")) {
msgprint("Please select " + me.party + " first.");
return;
}
else
me.add_to_cart($(this).attr("data-item_code"));
}
});
}
});
},
add_to_cart: function(item_code, serial_no) {
var me = this;
var caught = false;
// get no_of_items
var no_of_items = me.wrapper.find("#cart tbody tr").length;
// check whether the item is already added
if (no_of_items != 0) {
$.each(wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name,
this.frm.cscript.fname, this.frm.doctype), function(i, d) {
if (d.item_code == item_code) {
caught = true;
if (serial_no) {
d.serial_no += '\n' + serial_no;
me.frm.script_manager.trigger("serial_no", d.doctype, d.name);
}
else {
d.qty += 1;
me.frm.script_manager.trigger("qty", d.doctype, d.name);
}
}
});
}
// if item not found then add new item
if (!caught) {
this.add_new_item_to_grid(item_code, serial_no);
}
this.refresh();
this.refresh_search_box();
},
add_new_item_to_grid: function(item_code, serial_no) {
var me = this;
var child = wn.model.add_child(me.frm.doc, this.frm.doctype + " Item",
this.frm.cscript.fname);
child.item_code = item_code;
if (serial_no)
child.serial_no = serial_no;
this.frm.script_manager.trigger("item_code", child.doctype, child.name);
},
refresh_search_box: function() {
var me = this;
// Clear Item Box and remake item list
if (this.search.$input.val()) {
this.search.set_input("");
this.make_item_list();
}
},
update_qty: function(item_code, qty) {
var me = this;
$.each(wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name,
this.frm.cscript.fname, this.frm.doctype), function(i, d) {
if (d.item_code == item_code) {
if (qty == 0) {
wn.model.clear_doc(d.doctype, d.name);
me.refresh_grid();
} else {
d.qty = qty;
me.frm.script_manager.trigger("qty", d.doctype, d.name);
}
}
});
me.refresh();
},
refresh: function() {
var me = this;
this.party_field.set_input(this.frm.doc[this.party.toLowerCase()]);
this.barcode.set_input("");
this.show_items_in_item_cart();
this.show_taxes();
this.set_totals();
// if form is local then only run all these functions
if (this.frm.doc.docstatus===0) {
this.call_when_local();
}
this.disable_text_box_and_button();
this.hide_payment_button();
// If quotation to is not Customer then remove party
if (this.frm.doctype == "Quotation") {
this.party_field.$wrapper.remove();
if (this.frm.doc.quotation_to == "Customer")
this.make_party();
}
},
show_items_in_item_cart: function() {
var me = this;
var $items = this.wrapper.find("#cart tbody").empty();
$.each(wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name,
this.frm.cscript.fname, this.frm.doctype), function(i, d) {
$(repl('<tr id="%(item_code)s" data-selected="false">\
<td>%(item_code)s%(item_name)s</td>\
<td style="vertical-align:middle;" align="right">\
<div class="decrease-qty" style="cursor:pointer;">\
<i class="icon-minus-sign icon-large text-danger"></i>\
</div>\
</td>\
<td style="vertical-align:middle;"><input type="text" value="%(qty)s" \
class="form-control qty" style="text-align: right;"></td>\
<td style="vertical-align:middle;cursor:pointer;">\
<div class="increase-qty" style="cursor:pointer;">\
<i class="icon-plus-sign icon-large text-success"></i>\
</div>\
</td>\
<td style="text-align: right;"><b>%(amount)s</b><br>%(rate)s</td>\
</tr>',
{
item_code: d.item_code,
item_name: d.item_name===d.item_code ? "" : ("<br>" + d.item_name),
qty: d.qty,
rate: format_currency(d[me.rate], me.frm.doc.currency),
amount: format_currency(d[me.amount], me.frm.doc.currency)
}
)).appendTo($items);
});
this.wrapper.find(".increase-qty, .decrease-qty").on("click", function() {
var item_code = $(this).closest("tr").attr("id");
me.selected_item_qty_operation(item_code, $(this).attr("class"));
});
},
show_taxes: function() {
var me = this;
var taxes = wn.model.get_children(this.sales_or_purchase + " Taxes and Charges",
this.frm.doc.name, this.frm.cscript.other_fname, this.frm.doctype);
$(this.wrapper).find(".tax-table")
.toggle((taxes && taxes.length) ? true : false)
.find("tbody").empty();
$.each(taxes, function(i, d) {
if (d.tax_amount) {
$(repl('<tr>\
<td>%(description)s %(rate)s</td>\
<td style="text-align: right;">%(tax_amount)s</td>\
<tr>', {
description: d.description,
rate: ((d.charge_type == "Actual") ? '' : ("(" + d.rate + "%)")),
tax_amount: format_currency(flt(d.tax_amount)/flt(me.frm.doc.conversion_rate),
me.frm.doc.currency)
})).appendTo(".tax-table tbody");
}
});
},
set_totals: function() {
var me = this;
this.wrapper.find(".net-total").text(format_currency(this.frm.doc[this.net_total],
me.frm.doc.currency));
this.wrapper.find(".grand-total").text(format_currency(this.frm.doc[this.grand_total],
me.frm.doc.currency));
},
call_when_local: function() {
var me = this;
// append quantity to the respective item after change from input box
$(this.wrapper).find("input.qty").on("change", function() {
var item_code = $(this).closest("tr")[0].id;
me.update_qty(item_code, $(this).val());
});
// on td click toggle the highlighting of row
$(this.wrapper).find("#cart tbody tr td").on("click", function() {
var row = $(this).closest("tr");
if (row.attr("data-selected") == "false") {
row.attr("class", "warning");
row.attr("data-selected", "true");
}
else {
row.prop("class", null);
row.attr("data-selected", "false");
}
me.refresh_delete_btn();
});
me.refresh_delete_btn();
this.barcode.$input.focus();
},
disable_text_box_and_button: function() {
var me = this;
// if form is submitted & cancelled then disable all input box & buttons
if (this.frm.doc.docstatus>=1) {
$(this.wrapper).find('input, button').each(function () {
$(this).prop('disabled', true);
});
$(this.wrapper).find(".remove-items").hide();
$(this.wrapper).find(".make-payment").hide();
}
else {
$(this.wrapper).find('input, button').each(function () {
$(this).prop('disabled', false);
});
$(this.wrapper).find(".make-payment").show();
}
},
hide_payment_button: function() {
var me = this;
// Show Make Payment button only in Sales Invoice
if (this.frm.doctype != "Sales Invoice")
$(this.wrapper).find(".make-payment").hide();
},
refresh_delete_btn: function() {
$(this.wrapper).find(".remove-items").toggle($(".item-cart .warning").length ? true : false);
},
add_item_thru_barcode: function() {
var me = this;
me.barcode_timeout = null;
wn.call({
method: 'accounts.doctype.sales_invoice.pos.get_item_code',
args: {barcode_serial_no: this.barcode.$input.val()},
callback: function(r) {
if (r.message) {
if (r.message[1] == "serial_no")
me.add_to_cart(r.message[0][0].item_code, r.message[0][0].name);
else
me.add_to_cart(r.message[0][0].name);
}
else
msgprint(wn._("Invalid Barcode"));
me.refresh();
}
});
},
remove_selected_items: function() {
var me = this;
var selected_items = [];
var no_of_items = $(this.wrapper).find("#cart tbody tr").length;
for(var x=0; x<=no_of_items - 1; x++) {
var row = $(this.wrapper).find("#cart tbody tr:eq(" + x + ")");
if(row.attr("data-selected") == "true") {
selected_items.push(row.attr("id"));
}
}
var child = wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name,
this.frm.cscript.fname, this.frm.doctype);
$.each(child, function(i, d) {
for (var i in selected_items) {
if (d.item_code == selected_items[i]) {
wn.model.clear_doc(d.doctype, d.name);
}
}
});
this.refresh_grid();
},
refresh_grid: function() {
this.frm.fields_dict[this.frm.cscript.fname].grid.refresh();
this.frm.script_manager.trigger("calculate_taxes_and_totals");
this.refresh();
},
selected_item_qty_operation: function(item_code, operation) {
var me = this;
var child = wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name,
this.frm.cscript.fname, this.frm.doctype);
$.each(child, function(i, d) {
if (d.item_code == item_code) {
if (operation == "increase-qty")
d.qty += 1;
else if (operation == "decrease-qty")
d.qty != 1 ? d.qty -= 1 : d.qty = 1;
me.refresh();
}
});
},
make_payment: function() {
var me = this;
var no_of_items = $(this.wrapper).find("#cart tbody tr").length;
var mode_of_payment = [];
if (no_of_items == 0)
msgprint(wn._("Payment cannot be made for empty cart"));
else {
wn.call({
method: 'accounts.doctype.sales_invoice.pos.get_mode_of_payment',
callback: function(r) {
for (x=0; x<=r.message.length - 1; x++) {
mode_of_payment.push(r.message[x].name);
}
// show payment wizard
var dialog = new wn.ui.Dialog({
width: 400,
title: 'Payment',
fields: [
{fieldtype:'Data', fieldname:'total_amount', label:'Total Amount', read_only:1},
{fieldtype:'Select', fieldname:'mode_of_payment', label:'Mode of Payment',
options:mode_of_payment.join('\n'), reqd: 1},
{fieldtype:'Button', fieldname:'pay', label:'Pay'}
]
});
dialog.set_values({
"total_amount": $(".grand-total").text()
});
dialog.show();
dialog.get_input("total_amount").prop("disabled", true);
dialog.fields_dict.pay.input.onclick = function() {
me.frm.set_value("mode_of_payment", dialog.get_values().mode_of_payment);
me.frm.set_value("paid_amount", dialog.get_values().total_amount);
me.frm.cscript.mode_of_payment(me.frm.doc);
me.frm.save();
dialog.hide();
me.refresh();
};
}
});
}
},
}); | Tejal011089/Medsyn2_app | accounts/doctype/sales_invoice/pos.js | JavaScript | agpl-3.0 | 17,987 |
require('jasmine-beforeall');
var h = require('./helpers.js');
describe('', function() {
afterAll(function(){
h.afterAllTeardown();
});
// This UI test suite expects to be run as part of hack/test-end-to-end.sh
// It requires the example project be created with all of its resources in order to pass
describe('unauthenticated user', function() {
beforeEach(function() {
h.commonSetup();
});
afterEach(function() {
h.commonTeardown();
});
it('should be able to log in', function() {
browser.get('/');
// The login page doesn't use angular, so we have to use the underlying WebDriver instance
var driver = browser.driver;
driver.wait(function() {
return driver.isElementPresent(by.name("username"));
}, 3000);
expect(browser.driver.getCurrentUrl()).toMatch(/\/login/);
expect(browser.driver.getTitle()).toMatch(/Login -/);
h.login(true);
expect(browser.getTitle()).toEqual("OpenShift Web Console");
expect(element(by.css(".navbar-utility .username")).getText()).toEqual("e2e-user");
});
});
describe('authenticated e2e-user', function() {
beforeEach(function() {
h.commonSetup();
h.login();
});
afterEach(function() {
h.commonTeardown();
});
describe('with test project', function() {
it('should be able to list the test project', function() {
browser.get('/').then(function() {
h.waitForPresence('h2.project', 'test');
});
});
it('should have access to the test project', function() {
h.goToPage('/project/test');
h.waitForPresence('h1', 'test');
h.waitForPresence('.component .service', 'database');
h.waitForPresence('.component .service', 'frontend');
h.waitForPresence('.component .route', 'www.example.com');
h.waitForPresence('.pod-template-build a', '#1');
h.waitForPresence('.deployment-trigger', 'from image change');
// Check the pod count inside the donut chart for each rc.
h.waitForPresence('#service-database .pod-count', '1');
h.waitForPresence('#service-frontend .pod-count', '2');
// TODO: validate correlated images, builds, source
});
});
});
});
| mnagy/origin | assets/test/integration/e2e.js | JavaScript | apache-2.0 | 2,284 |
// Copyright JS Foundation and other contributors, http://js.foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const obj = {};
var a = { a : (o) = 1 } = obj;
assert (a === obj);
assert (o === 1);
| jerryscript-project/jerryscript | tests/jerry/regression-test-issue-3935.js | JavaScript | apache-2.0 | 716 |
// This file was procedurally generated from the following sources:
// - src/dstr-binding-for-await/obj-ptrn-prop-ary.case
// - src/dstr-binding-for-await/default/for-await-of-async-func-var.template
/*---
description: Object binding pattern with "nested" array binding pattern not using initializer (for-await-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
features: [destructuring-binding, async-iteration]
flags: [generated, async]
info: |
IterationStatement :
for await ( var ForBinding of AssignmentExpression ) Statement
[...]
2. Return ? ForIn/OfBodyEvaluation(ForBinding, Statement, keyResult,
varBinding, labelSet, async).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
4. Let destructuring be IsDestructuring of lhs.
[...]
6. Repeat
[...]
j. If destructuring is false, then
[...]
k. Else
i. If lhsKind is assignment, then
[...]
ii. Else if lhsKind is varBinding, then
1. Assert: lhs is a ForBinding.
2. Let status be the result of performing BindingInitialization
for lhs passing nextValue and undefined as the arguments.
[...]
13.3.3.7 Runtime Semantics: KeyedBindingInitialization
[...]
3. If Initializer is present and v is undefined, then
[...]
4. Return the result of performing BindingInitialization for BindingPattern
passing v and environment as arguments.
---*/
var iterCount = 0;
async function fn() {
for await (var { w: [x, y, z] = [4, 5, 6] } of [{ w: [7, undefined, ] }]) {
assert.sameValue(x, 7);
assert.sameValue(y, undefined);
assert.sameValue(z, undefined);
assert.throws(ReferenceError, function() {
w;
});
iterCount += 1;
}
}
fn()
.then(() => assert.sameValue(iterCount, 1, 'iteration occurred as expected'), $DONE)
.then($DONE, $DONE);
| sebastienros/jint | Jint.Tests.Test262/test/language/statements/for-await-of/async-func-dstr-var-obj-ptrn-prop-ary.js | JavaScript | bsd-2-clause | 1,967 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: Operator x ^ y returns ToNumber(x) ^ ToNumber(y)
es5id: 11.10.2_A3_T2.3
description: >
Type(x) is different from Type(y) and both types vary between
Number (primitive or object) and Null
---*/
//CHECK#1
if ((1 ^ null) !== 1) {
$ERROR('#1: (1 ^ null) === 1. Actual: ' + ((1 ^ null)));
}
//CHECK#2
if ((null ^ 1) !== 1) {
$ERROR('#2: (null ^ 1) === 1. Actual: ' + ((null ^ 1)));
}
//CHECK#3
if ((new Number(1) ^ null) !== 1) {
$ERROR('#3: (new Number(1) ^ null) === 1. Actual: ' + ((new Number(1) ^ null)));
}
//CHECK#4
if ((null ^ new Number(1)) !== 1) {
$ERROR('#4: (null ^ new Number(1)) === 1. Actual: ' + ((null ^ new Number(1))));
}
| PiotrDabkowski/Js2Py | tests/test_cases/language/expressions/bitwise-xor/S11.10.2_A3_T2.3.js | JavaScript | mit | 802 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
tslib_1.__exportStar(require("./2.9/type"), exports);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInR5cGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7O0FBQUEscURBQTJCIn0= | AxelSparkster/axelsparkster.github.io | node_modules/tsutils/typeguard/type.js | JavaScript | mit | 357 |
var assert = require('assert');
var jsv = require('jsverify');
var R = require('..');
var eq = require('./shared/eq');
describe('compose', function() {
it('is a variadic function', function() {
eq(typeof R.compose, 'function');
eq(R.compose.length, 0);
});
it('performs right-to-left function composition', function() {
// f :: (String, Number?) -> ([Number] -> [Number])
var f = R.compose(R.map, R.multiply, parseInt);
eq(f.length, 2);
eq(f('10')([1, 2, 3]), [10, 20, 30]);
eq(f('10', 2)([1, 2, 3]), [2, 4, 6]);
});
it('passes context to functions', function() {
function x(val) {
return this.x * val;
}
function y(val) {
return this.y * val;
}
function z(val) {
return this.z * val;
}
var context = {
a: R.compose(x, y, z),
x: 4,
y: 2,
z: 1
};
eq(context.a(5), 40);
});
it('throws if given no arguments', function() {
assert.throws(
function() { R.compose(); },
function(err) {
return err.constructor === Error &&
err.message === 'compose requires at least one argument';
}
);
});
it('can be applied to one argument', function() {
var f = function(a, b, c) { return [a, b, c]; };
var g = R.compose(f);
eq(g.length, 3);
eq(g(1, 2, 3), [1, 2, 3]);
});
});
describe('compose properties', function() {
jsv.property('composes two functions', jsv.fn(), jsv.fn(), jsv.nat, function(f, g, x) {
return R.equals(R.compose(f, g)(x), f(g(x)));
});
jsv.property('associative', jsv.fn(), jsv.fn(), jsv.fn(), jsv.nat, function(f, g, h, x) {
var result = f(g(h(x)));
return R.all(R.equals(result), [
R.compose(f, g, h)(x),
R.compose(f, R.compose(g, h))(x),
R.compose(R.compose(f, g), h)(x)
]);
});
});
| angeloocana/ramda | test/compose.js | JavaScript | mit | 1,837 |
var Emitter = require("events").EventEmitter;
var shared;
function Bank(options) {
this.address = options.address;
this.io = options.io;
this.io.i2cConfig();
}
Bank.prototype.read = function(register, numBytes, callback) {
if (register) {
this.io.i2cRead(this.address, register, numBytes, callback);
} else {
this.io.i2cRead(this.address, numBytes, callback);
}
};
Bank.prototype.write = function(register, bytes) {
if (!Array.isArray(bytes)) {
bytes = [bytes];
}
this.io.i2cWrite(this.address, register, bytes);
};
// http://www.nr.edu/csc200/labs-ev3/ev3-user-guide-EN.pdf
function EVS(options) {
if (shared) {
return shared;
}
this.bank = {
a: new Bank({
address: EVS.BANK_A,
io: options.io,
}),
b: new Bank({
address: EVS.BANK_B,
io: options.io,
})
};
shared = this;
}
EVS.shieldPort = function(pin) {
var port = EVS[pin];
if (port === undefined) {
throw new Error("Invalid EVShield pin name");
}
var address, analog, bank, motor, mode, offset, sensor;
var endsWithS1 = false;
if (pin.startsWith("BA")) {
address = EVS.BANK_A;
bank = "a";
} else {
address = EVS.BANK_B;
bank = "b";
}
if (pin.includes("M")) {
motor = pin.endsWith("M1") ? EVS.S1 : EVS.S2;
}
if (pin.includes("S")) {
endsWithS1 = pin.endsWith("S1");
// Used for reading 2 byte integer values from raw sensors
analog = endsWithS1 ? EVS.S1_ANALOG : EVS.S2_ANALOG;
// Sensor Mode (1 or 2?)
mode = endsWithS1 ? EVS.S1_MODE : EVS.S2_MODE;
// Used for read registers
offset = endsWithS1 ? EVS.S1_OFFSET : EVS.S2_OFFSET;
// Used to address "sensor type"
sensor = endsWithS1 ? EVS.S1 : EVS.S2;
}
return {
address: address,
analog: analog,
bank: bank,
mode: mode,
motor: motor,
offset: offset,
port: port,
sensor: sensor,
};
};
EVS.isRawSensor = function(port) {
return port.analog === EVS.S1_ANALOG || port.analog === EVS.S2_ANALOG;
};
EVS.prototype = Object.create(Emitter.prototype, {
constructor: {
value: EVS
}
});
EVS.prototype.setup = function(port, type) {
this.bank[port.bank].write(port.mode, [type]);
};
EVS.prototype.read = function(port, register, numBytes, callback) {
if (port.sensor && port.offset && !EVS.isRawSensor(port)) {
register += port.offset;
}
this.bank[port.bank].read(register, numBytes, callback);
};
EVS.prototype.write = function(port, register, data) {
this.bank[port.bank].write(register, data);
};
/*
* Shield Registers
*/
EVS.BAS1 = 0x01;
EVS.BAS2 = 0x02;
EVS.BBS1 = 0x03;
EVS.BBS2 = 0x04;
EVS.BAM1 = 0x05;
EVS.BAM2 = 0x06;
EVS.BBM1 = 0x07;
EVS.BBM2 = 0x08;
EVS.BANK_A = 0x1A;
EVS.BANK_B = 0x1B;
EVS.S1 = 0x01;
EVS.S2 = 0x02;
EVS.M1 = 0x01;
EVS.M2 = 0x02;
EVS.MM = 0x03;
EVS.Type_NONE = 0x00;
EVS.Type_SWITCH = 0x01;
EVS.Type_ANALOG = 0x02;
EVS.Type_I2C = 0x09;
/*
* Sensor Mode NXT
*/
EVS.Type_NXT_LIGHT_REFLECTED = 0x03;
EVS.Type_NXT_LIGHT = 0x04;
EVS.Type_NXT_COLOR = 0x0D;
EVS.Type_NXT_COLOR_RGBRAW = 0x04;
EVS.Type_NXT_COLORRED = 0x0E;
EVS.Type_NXT_COLORGREEN = 0x0F;
EVS.Type_NXT_COLORBLUE = 0x10;
EVS.Type_NXT_COLORNONE = 0x11;
EVS.Type_DATABIT0_HIGH = 0x40;
/*
* Sensor Port Controls
*/
EVS.S1_MODE = 0x6F;
// EVS.S1_EV3_MODE = 0x6F;
EVS.S1_ANALOG = 0x70;
EVS.S1_OFFSET = 0;
EVS.S2_MODE = 0xA3;
// EVS.S2_EV3_MODE = 0x6F;
EVS.S2_ANALOG = 0xA4;
EVS.S2_OFFSET = 52;
/*
* Sensor Mode EV3
*/
EVS.Type_EV3_LIGHT_REFLECTED = 0x00;
EVS.Type_EV3_LIGHT = 0x01;
EVS.Type_EV3_COLOR = 0x02;
EVS.Type_EV3_COLOR_REFRAW = 0x03;
EVS.Type_EV3_COLOR_RGBRAW = 0x04;
EVS.Type_EV3_TOUCH = 0x12;
EVS.Type_EV3 = 0x13;
/*
* Sensor Read Registers
*/
EVS.Light = 0x83;
EVS.Bump = 0x84;
EVS.ColorMeasure = 0x83;
EVS.Proximity = 0x83;
EVS.Touch = 0x83;
EVS.Ultrasonic = 0x81;
EVS.Mode = 0x81;
/*
* Sensor Read Byte Counts
*/
EVS.Light_Bytes = 2;
EVS.Analog_Bytes = 2;
EVS.Bump_Bytes = 1;
EVS.ColorMeasure_Bytes = 2;
EVS.Proximity_Bytes = 2;
EVS.Touch_Bytes = 1;
/*
* Motor selection
*/
EVS.Motor_1 = 0x01;
EVS.Motor_2 = 0x02;
EVS.Motor_Both = 0x03;
/*
* Motor next action
*/
// stop and let the motor coast.
EVS.Motor_Next_Action_Float = 0x00;
// apply brakes, and resist change to tachometer, but if tach position is forcibly changed, do not restore position
EVS.Motor_Next_Action_Brake = 0x01;
// apply brakes, and restore externally forced change to tachometer
EVS.Motor_Next_Action_BrakeHold = 0x02;
EVS.Motor_Stop = 0x60;
EVS.Motor_Reset = 0x52;
/*
* Motor direction
*/
EVS.Motor_Reverse = 0x00;
EVS.Motor_Forward = 0x01;
/*
* Motor Tachometer movement
*/
// Move the tach to absolute value provided
EVS.Motor_Move_Absolute = 0x00;
// Move the tach relative to previous position
EVS.Motor_Move_Relative = 0x01;
/*
* Motor completion
*/
EVS.Motor_Completion_Dont_Wait = 0x00;
EVS.Motor_Completion_Wait_For = 0x01;
/*
* 0-100
*/
EVS.Speed_Full = 90;
EVS.Speed_Medium = 60;
EVS.Speed_Slow = 25;
/*
* Motor Port Controls
*/
EVS.CONTROL_SPEED = 0x01;
EVS.CONTROL_RAMP = 0x02;
EVS.CONTROL_RELATIVE = 0x04;
EVS.CONTROL_TACHO = 0x08;
EVS.CONTROL_BRK = 0x10;
EVS.CONTROL_ON = 0x20;
EVS.CONTROL_TIME = 0x40;
EVS.CONTROL_GO = 0x80;
EVS.STATUS_SPEED = 0x01;
EVS.STATUS_RAMP = 0x02;
EVS.STATUS_MOVING = 0x04;
EVS.STATUS_TACHO = 0x08;
EVS.STATUS_BREAK = 0x10;
EVS.STATUS_OVERLOAD = 0x20;
EVS.STATUS_TIME = 0x40;
EVS.STATUS_STALL = 0x80;
EVS.COMMAND = 0x41;
EVS.VOLTAGE = 0x6E;
EVS.SETPT_M1 = 0x42;
EVS.SPEED_M1 = 0x46;
EVS.TIME_M1 = 0x47;
EVS.CMD_B_M1 = 0x48;
EVS.CMD_A_M1 = 0x49;
EVS.SETPT_M2 = 0x4A;
EVS.SPEED_M2 = 0x4E;
EVS.TIME_M2 = 0x4F;
EVS.CMD_B_M2 = 0x50;
EVS.CMD_A_M2 = 0x51;
/*
* Motor Read registers.
*/
EVS.POSITION_M1 = 0x52;
EVS.POSITION_M2 = 0x56;
EVS.STATUS_M1 = 0x5A;
EVS.STATUS_M2 = 0x5B;
EVS.TASKS_M1 = 0x5C;
EVS.TASKS_M2 = 0x5D;
EVS.ENCODER_PID = 0x5E;
EVS.SPEED_PID = 0x64;
EVS.PASS_COUNT = 0x6A;
EVS.TOLERANCE = 0x6B;
/*
* Built-in components
*/
EVS.BTN_PRESS = 0xDA;
EVS.RGB_LED = 0xD7;
EVS.CENTER_RGB_LED = 0xDE;
module.exports = EVS;
| manorius/printing_with_node | node_modules/johnny-five/lib/evshield.js | JavaScript | mit | 6,044 |
var app = angular.module('site', ['ui.bootstrap', 'ngAria']);
app.factory('Backend', ['$http',
function($http) {
var get = function(url) {
return function() {
return $http.get(url).then(function(resp) {
return resp.data;
});
}
};
return {
featured: get('data/featured.json'),
orgs: get('data/organization.json')
}
}
])
.controller('MainCtrl', ['Backend', '$scope', 'filterFilter',
function(Backend, $scope, filterFilter) {
var self = this;
Backend.orgs().then(function(data) {
self.orgs = data;
});
Backend.featured().then(function(data) {
self.featured = data;
$.ajax({
url: 'https://popularrepostg.blob.core.windows.net/popularrepos/projects.json',
dataType: 'jsonp',
jsonpCallback: 'JSON_CALLBACK',
success: function(data) {
var projects = data[0].AllProjects;
$scope.currentPage = 1; //current page
$scope.maxSize = 5; //pagination max size
$scope.entryLimit = 36; //max rows for data table
/* init pagination with $scope.list */
$scope.noOfRepos = projects.length;
$scope.noOfPages = Math.ceil($scope.noOfRepos / $scope.entryLimit);
$scope.resultsSectionTitle = 'All Repos';
$scope.$watch('searchText', function(term) {
// Create $scope.filtered and then calculate $scope.noOfPages, no racing!
$scope.filtered = filterFilter(projects, term);
$scope.noOfRepos = $scope.filtered.length;
$scope.noOfPages = Math.ceil($scope.noOfRepos / $scope.entryLimit);
$scope.resultsSectionTitle = (!term) ? 'All Repos' : (($scope.noOfRepos == 0) ? 'Search results' : ($scope.noOfRepos + ' repositories found'));
});
var featuredProjects = new Array();
self.featured.forEach(function (name) {
for (var i = 0; i < projects.length; i++) {
var project = projects[i];
if (project.Name == name) {
featuredProjects.push(project);
return;
}
}
});
self.projects = projects;
self.featuredProjects = featuredProjects;
$scope.$apply();
}
});
$.ajax({
url: 'https://popularrepostg.blob.core.windows.net/popularrepos/projectssummary.json',
dataType: 'jsonp',
jsonpCallback: 'JSON_CALLBACK',
success: function (stats) {
if (stats != null) {
$scope.overAllStats = stats[0];
}
}
})
});
}
])
.filter('startFrom', function() {
return function(input, start) {
if (input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});
| Gelvazio/ORGANIZACOES | microsoft.github.io/microsoft.github.io-master/js/main.js | JavaScript | gpl-2.0 | 3,518 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
define([
'intern',
'intern!object',
'intern/chai!assert',
'require',
'intern/node_modules/dojo/node!xmlhttprequest',
'app/bower_components/fxa-js-client/fxa-client',
'tests/lib/helpers',
'tests/functional/lib/helpers',
'tests/functional/lib/fx-desktop'
], function (intern, registerSuite, assert, require, nodeXMLHttpRequest,
FxaClient, TestHelpers, FunctionalHelpers, FxDesktopHelpers) {
var config = intern.config;
var AUTH_SERVER_ROOT = config.fxaAuthRoot;
var SYNC_URL = config.fxaContentRoot + 'signin?context=fx_desktop_v1&service=sync';
var PASSWORD = 'password';
var TOO_YOUNG_YEAR = new Date().getFullYear() - 13;
var OLD_ENOUGH_YEAR = TOO_YOUNG_YEAR - 1;
var email;
var client;
var ANIMATION_DELAY_MS = 1000;
var CHANNEL_DELAY = 4000; // how long it takes for the WebChannel indicator to appear
var TIMEOUT = 90 * 1000;
var listenForSyncCommands = FxDesktopHelpers.listenForFxaCommands;
var testIsBrowserNotifiedOfSyncLogin = FxDesktopHelpers.testIsBrowserNotifiedOfLogin;
/**
* This suite tests the WebChannel functionality for delivering encryption keys
* in the OAuth signin and signup cases. It uses a CustomEvent "WebChannelMessageToChrome"
* to finish OAuth flows
*/
function testIsBrowserNotifiedOfLogin(context, options) {
options = options || {};
return FunctionalHelpers.testIsBrowserNotified(context, 'oauth_complete', function (data) {
assert.ok(data.redirect);
assert.ok(data.code);
assert.ok(data.state);
// All of these flows should produce encryption keys.
assert.ok(data.keys);
assert.equal(data.closeWindow, options.shouldCloseTab);
});
}
function openFxaFromRpAndRequestKeys(context, page, additionalQueryParams) {
var queryParams = '&webChannelId=test&keys=true';
for (var key in additionalQueryParams) {
queryParams += ('&' + key + '=' + additionalQueryParams[key]);
}
return FunctionalHelpers.openFxaFromRp(context, page, queryParams);
}
registerSuite({
name: 'oauth web channel keys',
beforeEach: function () {
email = TestHelpers.createEmail();
client = new FxaClient(AUTH_SERVER_ROOT, {
xhr: nodeXMLHttpRequest.XMLHttpRequest
});
return FunctionalHelpers.clearBrowserState(this, {
contentServer: true,
'123done': true
});
},
'signup, verify same browser, in a different tab, with original tab open': function () {
var self = this;
self.timeout = TIMEOUT;
var messageReceived = false;
return openFxaFromRpAndRequestKeys(self, 'signup')
.execute(FunctionalHelpers.listenForWebChannelMessage)
.then(function () {
return FunctionalHelpers.fillOutSignUp(self, email, PASSWORD, OLD_ENOUGH_YEAR);
})
.findByCssSelector('#fxa-confirm-header')
.end()
.then(function () {
return FunctionalHelpers.openVerificationLinkSameBrowser(
self, email, 0);
})
.switchToWindow('newwindow')
.execute(FunctionalHelpers.listenForWebChannelMessage)
// wait for the verified window in the new tab
.findById('fxa-sign-up-complete-header')
.setFindTimeout(CHANNEL_DELAY)
.then(testIsBrowserNotifiedOfLogin(self, { shouldCloseTab: false }))
.end()
.then(function () {
messageReceived = true;
}, function () {
// element was not found
})
.closeCurrentWindow()
// switch to the original window
.switchToWindow('')
.setFindTimeout(CHANNEL_DELAY)
.then(testIsBrowserNotifiedOfLogin(self, { shouldCloseTab: false }))
.then(function () {
messageReceived = true;
}, function () {
// element was not found
})
.then(function () {
assert.isTrue(messageReceived, 'expected to receive a WebChannel event in either tab');
})
.setFindTimeout(config.pageLoadTimeout)
.findById('fxa-sign-up-complete-header')
.end();
},
'signup, verify same browser, original tab closed navigated to another page': function () {
var self = this;
self.timeout = TIMEOUT;
return openFxaFromRpAndRequestKeys(self, 'signup')
.then(function () {
return FunctionalHelpers.fillOutSignUp(self, email, PASSWORD, OLD_ENOUGH_YEAR);
})
.findByCssSelector('#fxa-confirm-header')
.end()
.then(FunctionalHelpers.openExternalSite(self))
.then(function () {
return FunctionalHelpers.openVerificationLinkSameBrowser(self, email, 0);
})
.switchToWindow('newwindow')
.execute(FunctionalHelpers.listenForWebChannelMessage)
.then(testIsBrowserNotifiedOfLogin(self, { shouldCloseTab: false }))
.findById('fxa-sign-up-complete-header')
.end()
.closeCurrentWindow()
// switch to the original window
.switchToWindow('');
},
'signup, verify same browser, replace original tab': function () {
var self = this;
self.timeout = TIMEOUT;
return openFxaFromRpAndRequestKeys(self, 'signup')
.then(function () {
return FunctionalHelpers.fillOutSignUp(self, email, PASSWORD, OLD_ENOUGH_YEAR);
})
.findByCssSelector('#fxa-confirm-header')
.end()
.then(function () {
return FunctionalHelpers.getVerificationLink(email, 0);
})
.then(function (verificationLink) {
return self.remote.get(require.toUrl(verificationLink))
.execute(FunctionalHelpers.listenForWebChannelMessage);
})
.then(testIsBrowserNotifiedOfLogin(self, { shouldCloseTab: false }))
.findById('fxa-sign-up-complete-header')
.end();
},
'signup, verify different browser, from original tab\'s P.O.V.': function () {
var self = this;
self.timeout = TIMEOUT;
return openFxaFromRpAndRequestKeys(self, 'signup')
.execute(FunctionalHelpers.listenForWebChannelMessage)
.then(function () {
return FunctionalHelpers.fillOutSignUp(self, email, PASSWORD, OLD_ENOUGH_YEAR);
})
.findByCssSelector('#fxa-confirm-header')
.end()
.then(function () {
return FunctionalHelpers.openVerificationLinkDifferentBrowser(client, email);
})
.then(testIsBrowserNotifiedOfLogin(self, { shouldCloseTab: false }))
.findById('fxa-sign-up-complete-header')
.end();
},
'password reset, verify same browser': function () {
var self = this;
self.timeout = TIMEOUT;
var messageReceived = false;
return openFxaFromRpAndRequestKeys(self, 'signin')
.execute(FunctionalHelpers.listenForWebChannelMessage)
.then(function () {
return client.signUp(email, PASSWORD, { preVerified: true });
})
.findByCssSelector('.reset-password')
.click()
.end()
.then(function () {
return FunctionalHelpers.fillOutResetPassword(self, email);
})
.findByCssSelector('#fxa-confirm-reset-password-header')
.end()
.then(function () {
return FunctionalHelpers.openVerificationLinkSameBrowser(
self, email, 0);
})
// Complete the password reset in the new tab
.switchToWindow('newwindow')
.execute(FunctionalHelpers.listenForWebChannelMessage)
.then(function () {
return FunctionalHelpers.fillOutCompleteResetPassword(
self, PASSWORD, PASSWORD);
})
// this tab should get the reset password complete header.
.findByCssSelector('#fxa-reset-password-complete-header')
.end()
.setFindTimeout(CHANNEL_DELAY)
.then(testIsBrowserNotifiedOfLogin(self, { shouldCloseTab: false }))
.end()
.then(function () {
messageReceived = true;
}, function () {
// element was not found
})
.sleep(ANIMATION_DELAY_MS)
.findByCssSelector('.error').isDisplayed()
.then(function (isDisplayed) {
assert.isFalse(isDisplayed);
})
.end()
.closeCurrentWindow()
// switch to the original window
.switchToWindow('')
.setFindTimeout(CHANNEL_DELAY)
.then(testIsBrowserNotifiedOfLogin(self, { shouldCloseTab: false }))
.then(function () {
messageReceived = true;
}, function () {
// element was not found
})
.then(function () {
assert.isTrue(messageReceived, 'expected to receive a WebChannel event in either tab');
})
.setFindTimeout(config.pageLoadTimeout)
// the original tab should automatically sign in
.findByCssSelector('#fxa-reset-password-complete-header')
.end();
},
'password reset, verify same browser, original tab closed': function () {
var self = this;
self.timeout = TIMEOUT;
return openFxaFromRpAndRequestKeys(self, 'signin')
.then(function () {
return client.signUp(email, PASSWORD, { preVerified: true });
})
.findByCssSelector('.reset-password')
.click()
.end()
.then(function () {
return FunctionalHelpers.fillOutResetPassword(self, email);
})
.findByCssSelector('#fxa-confirm-reset-password-header')
.end()
.then(FunctionalHelpers.openExternalSite(self))
.then(function () {
return FunctionalHelpers.openVerificationLinkSameBrowser(self, email, 0);
})
.switchToWindow('newwindow')
.execute(FunctionalHelpers.listenForWebChannelMessage)
.then(function () {
return FunctionalHelpers.fillOutCompleteResetPassword(
self, PASSWORD, PASSWORD);
})
// the tab should automatically sign in
.then(testIsBrowserNotifiedOfLogin(self, { shouldCloseTab: false }))
.findByCssSelector('#fxa-reset-password-complete-header')
.end()
.closeCurrentWindow()
// switch to the original window
.switchToWindow('');
},
'password reset, verify same browser, replace original tab': function () {
var self = this;
self.timeout = TIMEOUT;
return openFxaFromRpAndRequestKeys(self, 'signin')
.then(function () {
return client.signUp(email, PASSWORD, { preVerified: true });
})
.findByCssSelector('.reset-password')
.click()
.end()
.then(function () {
return FunctionalHelpers.fillOutResetPassword(self, email);
})
.findByCssSelector('#fxa-confirm-reset-password-header')
.end()
.then(function () {
return FunctionalHelpers.getVerificationLink(email, 0);
})
.then(function (verificationLink) {
return self.remote.get(require.toUrl(verificationLink))
.execute(FunctionalHelpers.listenForWebChannelMessage);
})
.then(function () {
return FunctionalHelpers.fillOutCompleteResetPassword(
self, PASSWORD, PASSWORD);
})
// the tab should automatically sign in
.then(testIsBrowserNotifiedOfLogin(self, { shouldCloseTab: false }))
.findByCssSelector('#fxa-reset-password-complete-header')
.end();
},
'password reset, verify in different browser, from the original tab\'s P.O.V.': function () {
var self = this;
self.timeout = TIMEOUT;
return openFxaFromRpAndRequestKeys(self, 'signin')
.execute(FunctionalHelpers.listenForWebChannelMessage)
.then(function () {
return client.signUp(email, PASSWORD, { preVerified: true });
})
.findByCssSelector('.reset-password')
.click()
.end()
.then(function () {
return FunctionalHelpers.fillOutResetPassword(self, email);
})
.findByCssSelector('#fxa-confirm-reset-password-header')
.end()
.then(function () {
return FunctionalHelpers.openPasswordResetLinkDifferentBrowser(
client, email, PASSWORD);
})
// user verified in a new browser, they have to enter
// their updated credentials in the original tab.
.findByCssSelector('#fxa-signin-header')
.end()
.then(FunctionalHelpers.visibleByQSA('.success'))
.end()
.findByCssSelector('#password')
.type(PASSWORD)
.end()
.findByCssSelector('button[type=submit]')
.click()
.end()
// user is signed in
.then(testIsBrowserNotifiedOfLogin(self, { shouldCloseTab: true }))
// no screen transition, Loop will close this screen.
.findByCssSelector('#fxa-signin-header')
.end();
},
'signin a verified account and requesting keys after signing in to sync': function () {
var self = this;
self.timeout = TIMEOUT;
return client.signUp(email, PASSWORD, { preVerified: true })
.then(function () {
return self.remote
.get(require.toUrl(SYNC_URL))
.setFindTimeout(intern.config.pageLoadTimeout)
.execute(listenForSyncCommands)
.findByCssSelector('#fxa-signin-header')
.end()
.then(function () {
return FunctionalHelpers.fillOutSignIn(self, email, PASSWORD);
})
.then(function () {
return testIsBrowserNotifiedOfSyncLogin(self, email, { checkVerified: true });
})
.then(function () {
return openFxaFromRpAndRequestKeys(self, 'signin');
})
.findByCssSelector('#fxa-signin-header')
.end()
.execute(FunctionalHelpers.listenForWebChannelMessage)
// In a keyless oauth flow, the user could just click to confirm
// without re-entering their password. Since we need the password
// to derive the keys, this flow must prompt for it.
.findByCssSelector('input[type=password]')
.click()
.clearValue()
.type(PASSWORD)
.end()
.findByCssSelector('button[type="submit"]')
.click()
.end()
.then(testIsBrowserNotifiedOfLogin(self, { shouldCloseTab: true }));
});
}
});
});
| riadhchtara/fxa-password-manager | tests/functional/oauth_webchannel_keys.js | JavaScript | mpl-2.0 | 14,818 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
define([
'intern',
'intern!object',
'intern/chai!assert',
'require',
'intern/node_modules/dojo/node!xmlhttprequest',
'app/bower_components/fxa-js-client/fxa-client',
'tests/lib/helpers',
'tests/functional/lib/helpers'
], function (intern, registerSuite, assert, require, nodeXMLHttpRequest, FxaClient, TestHelpers, FunctionalHelpers) {
var config = intern.config;
var AUTH_SERVER_ROOT = config.fxaAuthRoot;
var FORCE_AUTH_URL = config.fxaContentRoot + 'force_auth';
var PASSWORD = 'password';
var email;
var client;
function openFxa(context, email) {
return context.remote
.setFindTimeout(intern.config.pageLoadTimeout)
.get(require.toUrl(FORCE_AUTH_URL + '?email=' + email))
.findByCssSelector('#fxa-force-auth-header')
.end();
}
function attemptSignIn(context) {
return context.remote
// user should be at the force-auth screen
.findByCssSelector('#fxa-force-auth-header')
.end()
.findByCssSelector('input[type=password]')
.click()
.type(PASSWORD)
.end()
.findByCssSelector('button[type="submit"]')
.click()
.end();
}
registerSuite({
name: 'force_auth with an existing user',
beforeEach: function () {
email = TestHelpers.createEmail();
client = new FxaClient(AUTH_SERVER_ROOT, {
xhr: nodeXMLHttpRequest.XMLHttpRequest
});
var self = this;
return client.signUp(email, PASSWORD, { preVerified: true })
.then(function () {
// clear localStorage to avoid polluting other tests.
return FunctionalHelpers.clearBrowserState(self);
});
},
'sign in via force-auth': function () {
var self = this;
return openFxa(self, email)
.then(function () {
return attemptSignIn(self);
})
.findById('fxa-settings-header')
.end();
},
'forgot password flow via force-auth goes directly to confirm email screen': function () {
var self = this;
return openFxa(self, email)
.findByCssSelector('.reset-password')
.click()
.end()
.findById('fxa-confirm-reset-password-header')
.end()
// user remembers her password, clicks the "sign in" link. They
// should go back to the /force_auth screen.
.findByClassName('sign-in')
.click()
.end()
.findById('fxa-force-auth-header');
},
'visiting the tos/pp links saves information for return': function () {
var self = this;
return testRepopulateFields.call(self, '/legal/terms', 'fxa-tos-header')
.then(function () {
return testRepopulateFields.call(self, '/legal/privacy', 'fxa-pp-header');
});
}
});
registerSuite({
name: 'force_auth with an unregistered user',
beforeEach: function () {
email = TestHelpers.createEmail();
// clear localStorage to avoid polluting other tests.
return FunctionalHelpers.clearBrowserState(this);
},
'sign in shows an error message': function () {
var self = this;
return openFxa(self, email)
.then(function () {
return attemptSignIn(self);
})
.then(FunctionalHelpers.visibleByQSA('.error'))
.end();
},
'reset password shows an error message': function () {
var self = this;
return openFxa(self, email)
.findByCssSelector('a[href="/confirm_reset_password"]')
.click()
.end()
.then(FunctionalHelpers.visibleByQSA('.error'))
.end();
}
});
function testRepopulateFields(dest, header) {
var self = this;
return openFxa(self, email)
.findByCssSelector('input[type=password]')
.clearValue()
.click()
.type(PASSWORD)
.end()
.findByCssSelector('a[href="' + dest + '"]')
.click()
.end()
.findById(header)
.end()
.findByCssSelector('.back')
.click()
.end()
.findById('fxa-force-auth-header')
.end()
.findByCssSelector('input[type=password]')
.getProperty('value')
.then(function (resultText) {
// check the email address was re-populated
assert.equal(resultText, PASSWORD);
})
.end();
}
});
| riadhchtara/fxa-password-manager | tests/functional/force_auth.js | JavaScript | mpl-2.0 | 4,537 |
//// [crashIntypeCheckInvocationExpression.ts]
var nake;
function doCompile<P0, P1, P2>(fileset: P0, moduleType: P1) {
return undefined;
}
export var compileServer = task<number, number, any>(<P0, P1, P2>() => {
var folder = path.join(),
fileset = nake.fileSetSync<number, number, any>(folder)
return doCompile<number, number, any>(fileset, moduleType);
});
//// [crashIntypeCheckInvocationExpression.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
exports.compileServer = void 0;
var nake;
function doCompile(fileset, moduleType) {
return undefined;
}
exports.compileServer = task(function () {
var folder = path.join(), fileset = nake.fileSetSync(folder);
return doCompile(fileset, moduleType);
});
});
| Microsoft/TypeScript | tests/baselines/reference/crashIntypeCheckInvocationExpression.js | JavaScript | apache-2.0 | 858 |
/*
* 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.
*/
import angular from 'angular';
import igniteDialog from './dialog.directive';
import igniteDialogTitle from './dialog-title.directive';
import igniteDialogContent from './dialog-content.directive';
import IgniteDialog from './dialog.factory';
angular
.module('ignite-console.dialog', [
])
.factory('IgniteDialog', IgniteDialog)
.directive('igniteDialog', igniteDialog)
.directive('igniteDialogTitle', igniteDialogTitle)
.directive('igniteDialogContent', igniteDialogContent);
| ilantukh/ignite | modules/web-console/frontend/app/modules/dialog/dialog.module.js | JavaScript | apache-2.0 | 1,283 |
/* global CodeMirror */
/* global define */
(function(mod) {
'use strict';
if (typeof exports === 'object' && typeof module === 'object') // CommonJS
mod(require('../../lib/codemirror'));
else if (typeof define === 'function' && define.amd) // AMD
define(['../../lib/codemirror'], mod);
else
mod(CodeMirror);
})(function(CodeMirror) {
'use strict';
var SearchOnly;
CodeMirror.defineOption('searchonly', false, function(cm) {
if (!SearchOnly){
SearchOnly = new SearchOnlyBox(cm);
}
});
function SearchOnlyBox(cm) {
var self = this;
var el = self.element = document;
init();
function initElements(el) {
self.searchBox = el.querySelector('.div-search');
self.searchInput = el.querySelector('.log-search');
}
function init() {
initElements(el);
bindKeys();
self.$onChange = delayedCall(function() {
self.find(false, false);
});
el.addEventListener('click', function(e) {
var t = e.target || e.srcElement;
var action = t.getAttribute('action');
if (action && self[action])
self[action]();
e.stopPropagation();
});
self.searchInput.addEventListener('input', function() {
self.$onChange.schedule(20);
});
self.searchInput.addEventListener('focus', function() {
self.activeInput = self.searchInput;
});
self.$onChange = delayedCall(function() {
self.find(false, false);
});
}
function bindKeys() {
var sb = self,
obj = {
'Enter': function() {
sb.findNext();
}
};
self.element.addEventListener('keydown', function(event) {
Object.keys(obj).some(function(name) {
var is = key(name, event);
if (is) {
event.stopPropagation();
event.preventDefault();
obj[name](event);
}
return is;
});
});
}
this.find = function(skipCurrent, backwards) {
var value = this.searchInput.value,
options = {
skipCurrent: skipCurrent,
backwards: backwards
};
find(value, options, function(searchCursor) {
var current = searchCursor.matches(false, searchCursor.from());
cm.setSelection(current.from, current.to);
});
};
this.findNext = function() {
this.find(true, false);
};
this.findPrev = function() {
this.find(true, true);
};
function find(value, options, callback) {
var done,
noMatch, searchCursor, next, prev, matches, cursor,
position,
val = value,
o = options,
is = true,
caseSensitive = o.caseSensitive,
regExp = o.regExp,
wholeWord = o.wholeWord;
if (regExp || wholeWord) {
if (options.wholeWord)
val = '\\b' + val + '\\b';
val = RegExp(val);
}
if (o.backwards)
position = o.skipCurrent ? 'from': 'to';
else
position = o.skipCurrent ? 'to' : 'from';
cursor = cm.getCursor(position);
searchCursor = cm.getSearchCursor(val, cursor, !caseSensitive);
next = searchCursor.findNext.bind(searchCursor),
prev = searchCursor.findPrevious.bind(searchCursor),
matches = searchCursor.matches.bind(searchCursor);
if (o.backwards && !prev()) {
is = next();
if (is) {
cm.setCursor(cm.doc.size - 1, 0);
find(value, options, callback);
done = true;
}
} else if (!o.backwards && !next()) {
is = prev();
if (is) {
cm.setCursor(0, 0);
find(value, options, callback);
done = true;
}
}
noMatch = !is && self.searchInput.value;
setCssClass(self.searchInput, 'no_result_found', noMatch);
if (!done && is)
callback(searchCursor);
}
function setCssClass(el, className, condition) {
var list = el.classList;
list[condition ? 'add' : 'remove'](className);
}
function delayedCall(fcn, defaultTimeout) {
var timer,
callback = function() {
timer = null;
fcn();
},
_self = function(timeout) {
if (!timer)
timer = setTimeout(callback, timeout || defaultTimeout);
};
_self.delay = function(timeout) {
timer && clearTimeout(timer);
timer = setTimeout(callback, timeout || defaultTimeout);
};
_self.schedule = _self;
_self.call = function() {
this.cancel();
fcn();
};
_self.cancel = function() {
timer && clearTimeout(timer);
timer = null;
};
_self.isPending = function() {
return timer;
};
return _self;
}
/* https://github.com/coderaiser/key */
function key(str, event) {
var right,
KEY = {
BACKSPACE : 8,
TAB : 9,
ENTER : 13,
ESC : 27,
SPACE : 32,
PAGE_UP : 33,
PAGE_DOWN : 34,
END : 35,
HOME : 36,
UP : 38,
DOWN : 40,
INSERT : 45,
DELETE : 46,
INSERT_MAC : 96,
ASTERISK : 106,
PLUS : 107,
MINUS : 109,
F1 : 112,
F2 : 113,
F3 : 114,
F4 : 115,
F5 : 116,
F6 : 117,
F7 : 118,
F8 : 119,
F9 : 120,
F10 : 121,
SLASH : 191,
TRA : 192, /* Typewritten Reverse Apostrophe (`) */
BACKSLASH : 220
};
keyCheck(str, event);
right = str.split('|').some(function(combination) {
var wrong;
wrong = combination.split('-').some(function(key) {
var right;
switch(key) {
case 'Ctrl':
right = event.ctrlKey;
break;
case 'Shift':
right = event.shiftKey;
break;
case 'Alt':
right = event.altKey;
break;
case 'Cmd':
right = event.metaKey;
break;
default:
if (key.length === 1)
right = event.keyCode === key.charCodeAt(0);
else
Object.keys(KEY).some(function(name) {
var up = key.toUpperCase();
if (up === name)
right = event.keyCode === KEY[name];
});
break;
}
return !right;
});
return !wrong;
});
return right;
}
function keyCheck(str, event) {
if (typeof str !== 'string')
throw(Error('str should be string!'));
if (typeof event !== 'object')
throw(Error('event should be object!'));
}
}
});
| hisamith/app-cloud | modules/jaggeryapps/appmgt/src/site/themes/default/js/CodeMirror-5.7.0/addon/search/searchonly.js | JavaScript | apache-2.0 | 9,107 |
/*-----------------------------------------------------------------------------
Orderable plugin
-----------------------------------------------------------------------------*/
jQuery.fn.symphonyOrderable = function(custom_settings) {
var objects = this;
var settings = {
items: 'li',
handles: '*',
delay_initialize: false
};
jQuery.extend(settings, custom_settings);
/*-------------------------------------------------------------------------
Orderable
-------------------------------------------------------------------------*/
objects = objects.map(function() {
var object = this;
var state = null;
var start = function() {
state = {
item: jQuery(this).parents(settings.items),
min: null,
max: null,
delta: 0
};
jQuery(document).mousemove(change);
jQuery(document).mouseup(stop);
jQuery(document).mousemove();
return false;
};
var change = function(event) {
var item = state.item;
var target, next, top = event.pageY;
var a = item.height();
var b = item.offset().top;
var prev = item.prev();
state.min = Math.min(b, a + (prev.size() > 0 ? prev.offset().top : -Infinity));
state.max = Math.max(a + b, b + (item.next().height() || Infinity));
if (!object.is('.ordering')) {
object.addClass('ordering');
item.addClass('ordering');
object.trigger('orderstart', [state.item]);
}
if (top < state.min) {
target = item.prev(settings.items);
while (true) {
state.delta--;
next = target.prev(settings.items);
if (next.length === 0 || top >= (state.min -= next.height())) {
item.insertBefore(target); break;
}
target = next;
}
}
else if (top > state.max) {
target = item.next(settings.items);
while (true) {
state.delta++;
next = target.next(settings.items);
if (next.length === 0 || top <= (state.max += next.height())) {
item.insertAfter(target); break;
}
target = next;
}
}
object.trigger('orderchange', [state.item]);
return false;
};
var stop = function() {
jQuery(document).unbind('mousemove', change);
jQuery(document).unbind('mouseup', stop);
if (state != null) {
object.removeClass('ordering');
state.item.removeClass('ordering');
object.trigger('orderstop', [state.item]);
state = null;
}
return false;
};
/*-------------------------------------------------------------------*/
if (object instanceof jQuery === false) {
object = jQuery(object);
}
object.orderable = {
cancel: function() {
jQuery(document).unbind('mousemove', change);
jQuery(document).unbind('mouseup', stop);
if (state != null) {
object.removeClass('ordering');
state.item.removeClass('ordering');
object.trigger('ordercancel', [state.item]);
state = null;
}
},
initialize: function() {
object.addClass('orderable');
object.find(settings.items).each(function() {
var item = jQuery(this);
var handle = item.find(settings.handles);
handle.unbind('mousedown', start);
handle.bind('mousedown', start);
});
}
};
if (settings.delay_initialize !== true) {
object.orderable.initialize();
}
return object;
});
return objects;
};
/*---------------------------------------------------------------------------*/
| bauhouse/sym-intranet | symphony/assets/symphony.orderable.js | JavaScript | mit | 3,588 |
// wrapped by build app
define("d3/src/scale/ordinal", ["dojo","dijit","dojox"], function(dojo,dijit,dojox){
import "../arrays/map";
import "../arrays/range";
import "scale";
d3.scale.ordinal = function() {
return d3_scale_ordinal([], {t: "range", a: [[]]});
};
function d3_scale_ordinal(domain, ranger) {
var index,
range,
rangeBand;
function scale(x) {
return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length];
}
function steps(start, step) {
return d3.range(domain.length).map(function(i) { return start + step * i; });
}
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = [];
index = new d3_Map;
var i = -1, n = x.length, xi;
while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi));
return scale[ranger.t].apply(scale, ranger.a);
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
rangeBand = 0;
ranger = {t: "range", a: arguments};
return scale;
};
scale.rangePoints = function(x, padding) {
if (arguments.length < 2) padding = 0;
var start = x[0],
stop = x[1],
step = domain.length < 2 ? (start = (start + stop) / 2, 0) : (stop - start) / (domain.length - 1 + padding);
range = steps(start + step * padding / 2, step);
rangeBand = 0;
ranger = {t: "rangePoints", a: arguments};
return scale;
};
scale.rangeRoundPoints = function(x, padding) {
if (arguments.length < 2) padding = 0;
var start = x[0],
stop = x[1],
step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), 0) : (stop - start) / (domain.length - 1 + padding) | 0; // bitwise floor for symmetry
range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step);
rangeBand = 0;
ranger = {t: "rangeRoundPoints", a: arguments};
return scale;
};
scale.rangeBands = function(x, padding, outerPadding) {
if (arguments.length < 2) padding = 0;
if (arguments.length < 3) outerPadding = padding;
var reverse = x[1] < x[0],
start = x[reverse - 0],
stop = x[1 - reverse],
step = (stop - start) / (domain.length - padding + 2 * outerPadding);
range = steps(start + step * outerPadding, step);
if (reverse) range.reverse();
rangeBand = step * (1 - padding);
ranger = {t: "rangeBands", a: arguments};
return scale;
};
scale.rangeRoundBands = function(x, padding, outerPadding) {
if (arguments.length < 2) padding = 0;
if (arguments.length < 3) outerPadding = padding;
var reverse = x[1] < x[0],
start = x[reverse - 0],
stop = x[1 - reverse],
step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding));
range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step);
if (reverse) range.reverse();
rangeBand = Math.round(step * (1 - padding));
ranger = {t: "rangeRoundBands", a: arguments};
return scale;
};
scale.rangeBand = function() {
return rangeBand;
};
scale.rangeExtent = function() {
return d3_scaleExtent(ranger.a[0]);
};
scale.copy = function() {
return d3_scale_ordinal(domain, ranger);
};
return scale.domain(domain);
}
});
| hyoo/p3_web | public/js/release/d3/src/scale/ordinal.js | JavaScript | mit | 3,374 |
var ITEM_TPL_CONTENT_ANCHOR =
'<a class="item-content" ng-href="{{$href()}}" target="{{$target()}}"></a>';
var ITEM_TPL_CONTENT =
'<div class="item-content"></div>';
/**
* @ngdoc directive
* @name ionItem
* @parent ionic.directive:ionList
* @module ionic
* @restrict E
* Creates a list-item that can easily be swiped,
* deleted, reordered, edited, and more.
*
* See {@link ionic.directive:ionList} for a complete example & explanation.
*
* Can be assigned any item class name. See the
* [list CSS documentation](/docs/components/#list).
*
* @usage
*
* ```html
* <ion-list>
* <ion-item>Hello!</ion-item>
* </ion-list>
* ```
*/
IonicModule
.directive('ionItem', [
'$animate',
'$compile',
function($animate, $compile) {
return {
restrict: 'E',
controller: ['$scope', '$element', function($scope, $element) {
this.$scope = $scope;
this.$element = $element;
}],
scope: true,
compile: function($element, $attrs) {
var isAnchor = angular.isDefined($attrs.href) ||
angular.isDefined($attrs.ngHref) ||
angular.isDefined($attrs.uiSref);
var isComplexItem = isAnchor ||
//Lame way of testing, but we have to know at compile what to do with the element
/ion-(delete|option|reorder)-button/i.test($element.html());
if (isComplexItem) {
var innerElement = jqLite(isAnchor ? ITEM_TPL_CONTENT_ANCHOR : ITEM_TPL_CONTENT);
innerElement.append($element.contents());
$element.append(innerElement);
$element.addClass('item item-complex');
} else {
$element.addClass('item');
}
return function link($scope, $element, $attrs) {
$scope.$href = function() {
return $attrs.href || $attrs.ngHref;
};
$scope.$target = function() {
return $attrs.target || '_self';
};
};
}
};
}]);
| frangucc/gamify | www/sandbox/pals/app/bower_components/ionic/js/angular/directive/item.js | JavaScript | mit | 1,904 |
import glCore from 'pixi-gl-core';
import createIndicesForQuads from '../../core/utils/createIndicesForQuads';
/**
* @author Mat Groves
*
* Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
* for creating the original pixi version!
* Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that
* they now share 4 bytes on the vertex buffer
*
* Heavily inspired by LibGDX's ParticleBuffer:
* https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java
*/
/**
* The particle buffer manages the static and dynamic buffers for a particle container.
*
* @class
* @private
* @memberof PIXI
*/
export default class ParticleBuffer
{
/**
* @param {WebGLRenderingContext} gl - The rendering context.
* @param {object} properties - The properties to upload.
* @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic.
* @param {number} size - The size of the batch.
*/
constructor(gl, properties, dynamicPropertyFlags, size)
{
/**
* The current WebGL drawing context.
*
* @member {WebGLRenderingContext}
*/
this.gl = gl;
/**
* Size of a single vertex.
*
* @member {number}
*/
this.vertSize = 2;
/**
* Size of a single vertex in bytes.
*
* @member {number}
*/
this.vertByteSize = this.vertSize * 4;
/**
* The number of particles the buffer can hold
*
* @member {number}
*/
this.size = size;
/**
* A list of the properties that are dynamic.
*
* @member {object[]}
*/
this.dynamicProperties = [];
/**
* A list of the properties that are static.
*
* @member {object[]}
*/
this.staticProperties = [];
for (let i = 0; i < properties.length; ++i)
{
let property = properties[i];
// Make copy of properties object so that when we edit the offset it doesn't
// change all other instances of the object literal
property = {
attribute: property.attribute,
size: property.size,
uploadFunction: property.uploadFunction,
offset: property.offset,
};
if (dynamicPropertyFlags[i])
{
this.dynamicProperties.push(property);
}
else
{
this.staticProperties.push(property);
}
}
this.staticStride = 0;
this.staticBuffer = null;
this.staticData = null;
this.dynamicStride = 0;
this.dynamicBuffer = null;
this.dynamicData = null;
this.initBuffers();
}
/**
* Sets up the renderer context and necessary buffers.
*
* @private
*/
initBuffers()
{
const gl = this.gl;
let dynamicOffset = 0;
/**
* Holds the indices of the geometry (quads) to draw
*
* @member {Uint16Array}
*/
this.indices = createIndicesForQuads(this.size);
this.indexBuffer = glCore.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW);
this.dynamicStride = 0;
for (let i = 0; i < this.dynamicProperties.length; ++i)
{
const property = this.dynamicProperties[i];
property.offset = dynamicOffset;
dynamicOffset += property.size;
this.dynamicStride += property.size;
}
this.dynamicData = new Float32Array(this.size * this.dynamicStride * 4);
this.dynamicBuffer = glCore.GLBuffer.createVertexBuffer(gl, this.dynamicData, gl.STREAM_DRAW);
// static //
let staticOffset = 0;
this.staticStride = 0;
for (let i = 0; i < this.staticProperties.length; ++i)
{
const property = this.staticProperties[i];
property.offset = staticOffset;
staticOffset += property.size;
this.staticStride += property.size;
}
this.staticData = new Float32Array(this.size * this.staticStride * 4);
this.staticBuffer = glCore.GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW);
this.vao = new glCore.VertexArrayObject(gl)
.addIndex(this.indexBuffer);
for (let i = 0; i < this.dynamicProperties.length; ++i)
{
const property = this.dynamicProperties[i];
this.vao.addAttribute(
this.dynamicBuffer,
property.attribute,
gl.FLOAT,
false,
this.dynamicStride * 4,
property.offset * 4
);
}
for (let i = 0; i < this.staticProperties.length; ++i)
{
const property = this.staticProperties[i];
this.vao.addAttribute(
this.staticBuffer,
property.attribute,
gl.FLOAT,
false,
this.staticStride * 4,
property.offset * 4
);
}
}
/**
* Uploads the dynamic properties.
*
* @param {PIXI.DisplayObject[]} children - The children to upload.
* @param {number} startIndex - The index to start at.
* @param {number} amount - The number to upload.
*/
uploadDynamic(children, startIndex, amount)
{
for (let i = 0; i < this.dynamicProperties.length; i++)
{
const property = this.dynamicProperties[i];
property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset);
}
this.dynamicBuffer.upload();
}
/**
* Uploads the static properties.
*
* @param {PIXI.DisplayObject[]} children - The children to upload.
* @param {number} startIndex - The index to start at.
* @param {number} amount - The number to upload.
*/
uploadStatic(children, startIndex, amount)
{
for (let i = 0; i < this.staticProperties.length; i++)
{
const property = this.staticProperties[i];
property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset);
}
this.staticBuffer.upload();
}
/**
* Destroys the ParticleBuffer.
*
*/
destroy()
{
this.dynamicProperties = null;
this.dynamicData = null;
this.dynamicBuffer.destroy();
this.staticProperties = null;
this.staticData = null;
this.staticBuffer.destroy();
}
}
| jpweeks/pixi.js | src/particles/webgl/ParticleBuffer.js | JavaScript | mit | 6,828 |
"use strict";
/*jshint -W079*/
var chai = require("chai"),
expect = chai.expect,
ncp = require('ncp').ncp,
grunt = require("grunt"),
JsBeautifierTask = require("../lib/jsbeautifier"),
createMockTask = require("./mockTask");
chai.use(require('chai-fs'));
/*jshint -W030*/
describe("JsBeautifier: Config file test", function() {
var mockTask;
beforeEach(function(done) {
grunt.file.mkdir("tmp/configFile");
ncp("test/fixtures/configFile", "tmp/configFile", done);
});
afterEach(function() {
mockTask = null;
grunt.file.delete("tmp");
});
function assertBeautifiedFile(actualFile, expectedFile) {
var actual = "tmp/configFile/" + actualFile,
expected = grunt.file.read("tmp/configFile/" + expectedFile);
expect(actual).to.have.content(expected, "should beautify js " + actualFile + " using config file");
}
it("beautification of js, css & html file using settings from config file", function(done) {
var task;
mockTask = createMockTask({
config: "tmp/configFile/jsbeautifyrc.json"
}, ["tmp/configFile/test.js", "tmp/configFile/test.css", "tmp/configFile/test.html"], function() {
assertBeautifiedFile("test.js", "expected/test_expected.js");
assertBeautifiedFile("test.css", "expected/test_expected.css");
assertBeautifiedFile("test.html", "expected/test_expected.html");
done();
});
task = new JsBeautifierTask(mockTask);
task.run();
});
it("beautification of js, css & html file using settings from flat config file", function(done) {
var task;
mockTask = createMockTask({
config: "tmp/configFile/jsbeautifyrc_flat.json"
}, ["tmp/configFile/test.js", "tmp/configFile/test.css", "tmp/configFile/test.html"], function() {
assertBeautifiedFile("test.js", "expected/test_expected.js");
assertBeautifiedFile("test.css", "expected/test_expected.css");
assertBeautifiedFile("test.html", "expected/test_expected.html");
done();
});
task = new JsBeautifierTask(mockTask);
task.run();
});
it("beautification of js, css & html file using settings from config file and gruntfile", function(done) {
var task;
mockTask = createMockTask({
config: "tmp/configFile/jsbeautifyrc_flat.json",
css: {
indentSize: 5
},
html: {
indentSize: 7
}
}, ["tmp/configFile/test.js", "tmp/configFile/test.css", "tmp/configFile/test.html"], function() {
assertBeautifiedFile("test.js", "expected/withGruntFileOptions/test_expected.js");
assertBeautifiedFile("test.css", "expected/withGruntFileOptions/test_expected.css");
assertBeautifiedFile("test.html", "expected/withGruntFileOptions/test_expected.html");
done();
});
task = new JsBeautifierTask(mockTask);
task.run();
});
});
| vkadam/grunt-jsbeautifier | test/configFile_spec.js | JavaScript | mit | 3,091 |
'use strict';
var Command = require('../models/command');
var Watcher = require('../models/watcher');
var Builder = require('../models/builder');
var SilentError = require('silent-error');
var path = require('path');
var win = require('../utilities/windows-admin');
var existsSync = require('exists-sync');
var defaultPort = 7357;
module.exports = Command.extend({
name: 'test',
description: 'Runs your app\'s test suite.',
aliases: ['t'],
availableOptions: [
{ name: 'environment', type: String, default: 'test', aliases: ['e'] },
{ name: 'config-file', type: String, aliases: ['c', 'cf']},
{ name: 'server', type: Boolean, default: false, aliases: ['s'] },
{ name: 'host', type: String, aliases: ['H'] },
{ name: 'test-port', type: Number, default: defaultPort, aliases: ['tp'], description: 'The test port to use when running with --server.' },
{ name: 'filter', type: String, aliases: ['f'], description: 'A string to filter tests to run' },
{ name: 'module', type: String, aliases: ['m'], description: 'The name of a test module to run' },
{ name: 'watcher', type: String, default: 'events', aliases: ['w'] },
{ name: 'launch', type: String, default: false, description: 'A comma separated list of browsers to launch for tests.' },
{ name: 'reporter', type: String, aliases: ['r'], description: 'Test reporter to use [tap|dot|xunit] (default: tap)' },
{ name: 'silent', type: Boolean, default: false, description: 'Suppress any output except for the test report' },
{ name: 'test-page', type: String, description: 'Test page to invoke' },
{ name: 'path', type: 'Path', description: 'Reuse an existing build at given path.' },
{ name: 'query', type: String, description: 'A query string to append to the test page URL.' }
],
init: function() {
this.assign = require('lodash/assign');
this.quickTemp = require('quick-temp');
this.Builder = this.Builder || Builder;
this.Watcher = this.Watcher || Watcher;
if (!this.testing) {
process.env.EMBER_CLI_TEST_COMMAND = true;
}
},
tmp: function() {
return this.quickTemp.makeOrRemake(this, '-testsDist');
},
rmTmp: function() {
this.quickTemp.remove(this, '-testsDist');
this.quickTemp.remove(this, '-customConfigFile');
},
_generateCustomConfigs: function(options) {
var config = {};
if (!options.filter && !options.module && !options.launch && !options.query && !options['test-page']) { return config; }
var testPage = options['test-page'];
var queryString = this.buildTestPageQueryString(options);
if (testPage) {
var containsQueryString = testPage.indexOf('?') > -1;
var testPageJoinChar = containsQueryString ? '&' : '?';
config.testPage = testPage + testPageJoinChar + queryString;
}
if (queryString) {
config.queryString = queryString;
}
if (options.launch) {
config.launch = options.launch;
}
return config;
},
_generateTestPortNumber: function(options) {
if (options.port && options.testPort !== defaultPort || !isNaN(parseInt(options.testPort)) && !options.port) { return options.testPort; }
if (options.port) { return parseInt(options.port, 10) + 1; }
},
buildTestPageQueryString: function(options) {
var params = [];
if (options.module) {
params.push('module=' + options.module);
}
if (options.filter) {
params.push('filter=' + options.filter.toLowerCase());
}
if (options.query) {
params.push(options.query);
}
return params.join('&');
},
run: function(commandOptions) {
var hasBuild = !!commandOptions.path;
var outputPath;
if (hasBuild) {
outputPath = path.resolve(commandOptions.path);
if (!existsSync(outputPath)) {
throw new SilentError('The path ' + commandOptions.path + ' does not exist. Please specify a valid build directory to test.');
}
} else {
outputPath = this.tmp();
}
process.env['EMBER_CLI_TEST_OUTPUT'] = outputPath;
var testOptions = this.assign({}, commandOptions, {
ui: this.ui,
outputPath: outputPath,
project: this.project,
port: this._generateTestPortNumber(commandOptions)
}, this._generateCustomConfigs(commandOptions));
var options = {
ui: this.ui,
analytics: this.analytics,
project: this.project
};
return win.checkWindowsElevation(this.ui).then(function() {
var session;
if (commandOptions.server) {
if (hasBuild) {
throw new SilentError('Specifying a build is not allowed with the `--server` option.');
}
var TestServerTask = this.tasks.TestServer;
var testServer = new TestServerTask(options);
var builder = new this.Builder(testOptions);
testOptions.watcher = new this.Watcher(this.assign(options, {
builder: builder,
verbose: false,
options: commandOptions
}));
session = testServer.run(testOptions).finally(function() {
return builder.cleanup();
});
} else {
var TestTask = this.tasks.Test;
var test = new TestTask(options);
if (hasBuild) {
session = test.run(testOptions);
} else {
var BuildTask = this.tasks.Build;
var build = new BuildTask(options);
session = build.run({
environment: commandOptions.environment,
outputPath: outputPath
})
.then(function() {
return test.run(testOptions);
})
}
}
return session.finally(this.rmTmp.bind(this));
}.bind(this));
}
});
| r0zar/ember-rails-stocks | stocks/node_modules/ember-cli/lib/commands/test.js | JavaScript | mit | 6,146 |
"use strict";
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
var Test = function Test() {
_classCallCheck(this, Test);
arr.map(x => x * x);
}; | lydell/babel | test/fixtures/transformation/api/blacklist/expected.js | JavaScript | mit | 264 |
module.exports={title:"Logstash",hex:"005571",source:"https://www.elastic.co/brand",svg:'<svg aria-labelledby="simpleicons-logstash-icon" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title id="simpleicons-logstash-icon">Logstash icon</title><path d="M12.6 7.2V24c-5.2 0-10.8-4-10.8-9.3V0h3.6c3.8 0 7.2 3.4 7.2 7.2zm2.4 6V24h7.2V13.2z"/></svg>\n'}; | cdnjs/cdnjs | ajax/libs/simple-icons/1.9.9/logstash.min.js | JavaScript | mit | 369 |
CKEDITOR.plugins.setLang("imagebase","en-au",{captionPlaceholder:"Enter image caption"}); | cdnjs/cdnjs | ajax/libs/ckeditor/4.17.2/plugins/imagebase/lang/en-au.min.js | JavaScript | mit | 89 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DataSource = (function () {
function DataSource() {
}
return DataSource;
}());
exports.DataSource = DataSource;
| cdnjs/cdnjs | ajax/libs/deeplearn/0.6.0-alpha6/contrib/data/datasource.js | JavaScript | mit | 205 |
//=set test "Test" | AlexanderDolgan/juliawp | wp-content/themes/node_modules/gulp-rigger/node_modules/rigger/test/input-settings/stringval.js | JavaScript | gpl-2.0 | 18 |
/*
* Copyright (C) 2011 JTalks.org Team
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
var Utils = {};
function quote(postId, postNumber) {
var callback = function (text) {
$('#post').focus();
console.log(text);
var answer = $('#postBody');
answer.focus();
if (answer) {
answer.val(answer.val() + text);
}
}
$.ajax({
url: baseUrl + '/posts/' + postId + '/quote',
type: 'POST',
data: {
selection: getSelectedPostText(postNumber)
},
success: function (data) {
callback(data.result);
},
error: function () {
callback('');
}
});
}
function getSelectedPostText(postNumber) {
var txt = '';
if (window.getSelection) {
if (window.getSelection().toString().length > 0 && isRangeInPost(window.getSelection().getRangeAt(0))
&& isSelectedPostQuoted(postNumber)) {
txt = window.getSelection().toString();
}
}
else if (document.selection) {
if (isRangeInPost(document.selection.createRange()) && isSelectedPostQuoted(postNumber)) {
txt = document.selection.createRange().text;
}
}
return txt;
}
/**
* Checks if selected document fragment is a part of the post content.
* @param {Range} range Range object which represent current selection.
* @return {boolean} <b>true</b> if if selected document fragment is a part of the post content
* <b>false</b> otherwise.
*/
function isRangeInPost(range) {
return $(range.startContainer).closest(".post-content-body").length > 0;
}
/**
* Checks if "quote" button pressed on the post which was selected.
* @param {Number} postNumber number of the post on the page which "quote" button was pressed.
* @return {boolean} <b>true</> if selected text is a part of the post which will be quoted
* <b>false</b> otherwise.
*/
function isSelectedPostQuoted(postNumber) {
return $(window.getSelection().getRangeAt(0).startContainer).closest('.post').prevAll().length == postNumber;
}
/**
* Encodes given string by escaping special HTML characters
*
* @param s string to be encoded
*/
Utils.htmlEncode = function (s) {
return $('<div/>').text(s).html();
};
/**
* Do focus to element
*
* @param target selector of element to focus
*/
Utils.focusFirstEl = function (target) {
$(target).focus();
}
/**
* Replaces all \n characters by <br> tags. Used for review comments.
*
* @param s string where perform replacing
*/
Utils.lf2br = function (s) {
return s.replace(/\n/g, "<br>");
}
/**
* Replaces all \<br> tags by \n characters. Used for review comments.
*
* @param s string where perform replacing
*/
Utils.br2lf = function (s) {
return s.replace(/<br>/gi, "\n");
}
/**
* Create form field with given label(placeholder), id, type, class and style.
*/
Utils.createFormElement = function (label, id, type, cls, style) {
var elementHtml = ' \
<div class="control-group"> \
<div class="controls"> \
<input type="' + type + '" id="' + id + '" name="' + id + '" placeholder="' + label + '" class="input-xlarge ' + cls + '" style="'+ style +'" /> \
</div> \
</div> \
';
return elementHtml;
}
/**
* Handling "onError" event for images if it's can't loaded. Invoke in config kefirbb.xml for [img] bbtag.
* */
function imgError(image) {
var imageDefault = baseUrl + "/resources/images/noimage.jpg";
image.src = imageDefault;
image.className = "thumbnail-default";
image.parentNode.href = imageDefault;
image.onerror = "";
} | illerax/jcommune | jcommune-view/jcommune-web-view/src/main/webapp/resources/javascript/app/utils.js | JavaScript | lgpl-2.1 | 4,376 |
'use strict';
/**
* @module br/util/Number
*/
var StringUtility = require('br/util/StringUtility');
/**
* @class
* @alias module:br/util/Number
*
* @classdesc
* Utility methods for numbers
*/
function NumberUtil() {
}
/**
* Returns a numeric representation of the sign on the number.
*
* @param {Number} n The number (or a number as a string)
* @return {int} 1 for positive values, -1 for negative values, or the original value for zero and non-numeric values.
*/
NumberUtil.sgn = function(n) {
return n > 0 ? 1 : n < 0 ? -1 : n;
};
/**
* @param {Object} n
* @return {boolean} true for numbers and their string representations and false for other values including non-numeric
* strings, null, Infinity, NaN.
*/
NumberUtil.isNumber = function(n) {
if (typeof n === 'string') {
n = n.trim();
}
return n != null && n !== '' && n - n === 0;
};
/**
* Formats the number to the specified number of decimal places.
*
* @param {Number} n The number (or a number as a string).
* @param {Number} dp The number of decimal places.
* @return {String} The formatted number.
*/
NumberUtil.toFixed = function(n, dp) {
//return this.isNumber(n) && dp != null ? Number(n).toFixed(dp) : n;
//Workaround for IE8/7/6 where toFixed returns 0 for (0.5).toFixed(0) and 0.0 for (0.05).toFixed(1)
if (this.isNumber(n) && dp != null) {
var sgn = NumberUtil.sgn(n);
n = sgn * n;
var nFixed = (Math.round(Math.pow(10, dp)*n)/Math.pow(10, dp)).toFixed(dp);
return (sgn * nFixed).toFixed(dp);
}
return n;
};
/**
* Formats the number to the specified number of significant figures. This fixes the bugs in the native Number function
* of the same name that are prevalent in various browsers. If the number of significant figures is less than one,
* then the function has no effect.
*
* @param {Number} n The number (or a number as a string).
* @param {Number} sf The number of significant figures.
* @return {String} The formatted number.
*/
NumberUtil.toPrecision = function(n, sf) {
return this.isNumber(n) && sf > 0 ? Number(n).toPrecision(sf) : n;
};
/**
* Formats the number to the specified number of decimal places, omitting any trailing zeros.
*
* @param {Number} n The number (or a number as a string).
* @param {Number} rounding The number of decimal places to round.
* @return {String} The rounded number.
*/
NumberUtil.toRounded = function(n, rounding) {
//return this.isNumber(n) && rounding != null ? String(Number(Number(n).toFixed(rounding))) : n;
//Workaround for IE8/7/6 where toFixed returns 0 for (0.5).toFixed(0) and 0.0 for (0.05).toFixed(1)
if (this.isNumber(n) && rounding != null) {
var sgn = NumberUtil.sgn(n);
n = sgn * n;
var nRounded = (Math.round(Math.pow(10, rounding)*n)/Math.pow(10, rounding)).toFixed(rounding);
return sgn * nRounded;
}
return n;
};
/**
* Logarithm to base 10.
*
* @param {Number} n The number (or a number as a string).
* @return {Number} The logarithm to base 10.
*/
NumberUtil.log10 = function(n) {
return Math.log(n) / Math.LN10;
};
/**
* Rounds a floating point number
*
* @param {Number} n The number (or a number as a string).
* @return {Number} The formatted number.
*/
NumberUtil.round = function(n) {
var dp = 13 - (n ? Math.ceil(this.log10(Math.abs(n))) : 0);
return this.isNumber(n) ? Number(Number(n).toFixed(dp)) : n;
};
/**
* Pads the integer part of a number with zeros to reach the specified length.
*
* @param {Number} value The number (or a number as a string).
* @param {Number} numLength The required length of the number.
* @return {String} The formatted number.
*/
NumberUtil.pad = function(value, numLength) {
if (this.isNumber(value)) {
var nAbsolute = Math.abs(value);
var sInteger = new String(parseInt(nAbsolute));
var nSize = numLength || 0;
var sSgn = value < 0 ? "-" : "";
value = sSgn + StringUtility.repeat("0", nSize - sInteger.length) + nAbsolute;
}
return value;
};
/**
* Counts the amount of decimal places within a number.
* Also supports scientific notations
*
* @param {Number} n The number (or a number as a string).
* @return {Number} The number of decimal places
*/
NumberUtil.decimalPlaces = function(n) {
var match = (''+n).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));
}
module.exports = NumberUtil;
| andreoid/testing | brjs-sdk/workspace/sdk/libs/javascript/br-util/src/br/util/Number.js | JavaScript | lgpl-3.0 | 4,499 |
//// [tests/cases/compiler/moduleAugmentationsImports4.ts] ////
//// [a.ts]
export class A {}
//// [b.ts]
export class B {x: number;}
//// [c.d.ts]
declare module "C" {
class Cls {y: string; }
}
//// [d.d.ts]
declare module "D" {
import {A} from "a";
import {B} from "b";
module "a" {
interface A {
getB(): B;
}
}
}
//// [e.d.ts]
/// <reference path="c.d.ts"/>
declare module "E" {
import {A} from "a";
import {Cls} from "C";
module "a" {
interface A {
getCls(): Cls;
}
}
}
//// [main.ts]
/// <reference path="d.d.ts"/>
/// <reference path="e.d.ts"/>
import {A} from "./a";
import "D";
import "E";
let a: A;
let b = a.getB().x.toFixed();
let c = a.getCls().y.toLowerCase();
//// [f.js]
define("a", ["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
var A = /** @class */ (function () {
function A() {
}
return A;
}());
exports.A = A;
});
define("b", ["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
var B = /** @class */ (function () {
function B() {
}
return B;
}());
exports.B = B;
});
define("main", ["require", "exports", "D", "E"], function (require, exports) {
"use strict";
exports.__esModule = true;
var a;
var b = a.getB().x.toFixed();
var c = a.getCls().y.toLowerCase();
});
//// [f.d.ts]
/// <reference path="tests/cases/compiler/d.d.ts" />
/// <reference path="tests/cases/compiler/e.d.ts" />
declare module "a" {
export class A {
}
}
declare module "b" {
export class B {
x: number;
}
}
declare module "main" {
import "D";
import "E";
}
| weswigham/TypeScript | tests/baselines/reference/moduleAugmentationsImports4.js | JavaScript | apache-2.0 | 1,844 |
//// [augmentedTypesExternalModule1.ts]
export var a = 1;
class c5 { public foo() { } }
module c5 { } // should be ok everywhere
//// [augmentedTypesExternalModule1.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
exports.a = 1;
var c5 = /** @class */ (function () {
function c5() {
}
c5.prototype.foo = function () { };
return c5;
}());
});
| domchen/typescript-plus | tests/baselines/reference/augmentedTypesExternalModule1.js | JavaScript | apache-2.0 | 467 |
goog.provide('ol.test.extent');
goog.require('ol.extent');
goog.require('ol.proj');
describe('ol.extent', function() {
describe('buffer', function() {
it('buffers an extent by some value', function() {
var extent = [-10, -20, 10, 20];
expect(ol.extent.buffer(extent, 15)).to.eql([-25, -35, 25, 35]);
});
});
describe('clone', function() {
it('creates a copy of an extent', function() {
var extent = ol.extent.createOrUpdate(1, 2, 3, 4);
var clone = ol.extent.clone(extent);
expect(ol.extent.equals(extent, clone)).to.be(true);
ol.extent.extendCoordinate(extent, [10, 20]);
expect(ol.extent.equals(extent, clone)).to.be(false);
});
});
describe('closestSquaredDistanceXY', function() {
it('returns correct result when x left of extent', function() {
var extent = ol.extent.createOrUpdate(0, 0, 1, 1);
var x = -2;
var y = 0;
expect(ol.extent.closestSquaredDistanceXY(extent, x, y)).to.be(4);
});
it('returns correct result when x right of extent', function() {
var extent = ol.extent.createOrUpdate(0, 0, 1, 1);
var x = 3;
var y = 0;
expect(ol.extent.closestSquaredDistanceXY(extent, x, y)).to.be(4);
});
it('returns correct result for other x values', function() {
var extent = ol.extent.createOrUpdate(0, 0, 1, 1);
var x = 0.5;
var y = 3;
expect(ol.extent.closestSquaredDistanceXY(extent, x, y)).to.be(4);
});
it('returns correct result when y below extent', function() {
var extent = ol.extent.createOrUpdate(0, 0, 1, 1);
var x = 0;
var y = -2;
expect(ol.extent.closestSquaredDistanceXY(extent, x, y)).to.be(4);
});
it('returns correct result when y above extent', function() {
var extent = ol.extent.createOrUpdate(0, 0, 1, 1);
var x = 0;
var y = 3;
expect(ol.extent.closestSquaredDistanceXY(extent, x, y)).to.be(4);
});
it('returns correct result for other y values', function() {
var extent = ol.extent.createOrUpdate(0, 0, 1, 1);
var x = 3;
var y = 0.5;
expect(ol.extent.closestSquaredDistanceXY(extent, x, y)).to.be(4);
});
});
describe('createOrUpdateFromCoordinate', function() {
it('works when no extent passed', function() {
var coords = [0, 1];
var expected = [0, 1, 0, 1];
var got = ol.extent.createOrUpdateFromCoordinate(coords);
expect(got).to.eql(expected);
});
it('updates a passed extent', function() {
var extent = ol.extent.createOrUpdate(-4, -7, -3, -6);
var coords = [0, 1];
var expected = [0, 1, 0, 1];
ol.extent.createOrUpdateFromCoordinate(coords, extent);
expect(extent).to.eql(expected);
});
});
describe('createOrUpdateFromCoordinates', function() {
it('works when single coordinate and no extent passed', function() {
var coords = [[0, 1]];
var expected = [0, 1, 0, 1];
var got = ol.extent.createOrUpdateFromCoordinates(coords);
expect(got).to.eql(expected);
});
it('changes the passed extent when single coordinate', function() {
var extent = ol.extent.createOrUpdate(-4, -7, -3, -6);
var coords = [[0, 1]];
var expected = [0, 1, 0, 1];
ol.extent.createOrUpdateFromCoordinates(coords, extent);
expect(extent).to.eql(expected);
});
it('works when multiple coordinates and no extent passed', function() {
var coords = [[0, 1], [2, 3]];
var expected = [0, 1, 2, 3];
var got = ol.extent.createOrUpdateFromCoordinates(coords);
expect(got).to.eql(expected);
});
it('changes the passed extent when multiple coordinates given', function() {
var extent = ol.extent.createOrUpdate(-4, -7, -3, -6);
var coords = [[0, 1], [-2, -1]];
var expected = [-2, -1, 0, 1];
ol.extent.createOrUpdateFromCoordinates(coords, extent);
expect(extent).to.eql(expected);
});
});
describe('createOrUpdateFromRings', function() {
it('works when single ring and no extent passed', function() {
var ring = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]];
var rings = [ring];
var expected = [0, 0, 2, 2];
var got = ol.extent.createOrUpdateFromRings(rings);
expect(got).to.eql(expected);
});
it('changes the passed extent when single ring given', function() {
var ring = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]];
var rings = [ring];
var extent = [1, 1, 4, 7];
var expected = [0, 0, 2, 2];
ol.extent.createOrUpdateFromRings(rings, extent);
expect(extent).to.eql(expected);
});
it('works when multiple rings and no extent passed', function() {
var ring1 = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]];
var ring2 = [[1, 1], [1, 3], [3, 3], [3, 1], [1, 1]];
var rings = [ring1, ring2];
var expected = [0, 0, 3, 3];
var got = ol.extent.createOrUpdateFromRings(rings);
expect(got).to.eql(expected);
});
it('changes the passed extent when multiple rings given', function() {
var ring1 = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]];
var ring2 = [[1, 1], [1, 3], [3, 3], [3, 1], [1, 1]];
var rings = [ring1, ring2];
var extent = [1, 1, 4, 7];
var expected = [0, 0, 3, 3];
ol.extent.createOrUpdateFromRings(rings, extent);
expect(extent).to.eql(expected);
});
});
describe('forEachCorner', function() {
var callbackFalse;
var callbackTrue;
beforeEach(function() {
callbackFalse = sinon.spy(function() {
return false;
});
callbackTrue = sinon.spy(function() {
return true;
});
});
it('calls the passed callback for each corner', function() {
var extent = [1, 2, 3, 4];
ol.extent.forEachCorner(extent, callbackFalse);
expect(callbackFalse.callCount).to.be(4);
});
it('calls the passed callback with each corner', function() {
var extent = [1, 2, 3, 4];
ol.extent.forEachCorner(extent, callbackFalse);
var firstCallFirstArg = callbackFalse.args[0][0];
var secondCallFirstArg = callbackFalse.args[1][0];
var thirdCallFirstArg = callbackFalse.args[2][0];
var fourthCallFirstArg = callbackFalse.args[3][0];
expect(firstCallFirstArg).to.eql([1, 2]); // bl
expect(secondCallFirstArg).to.eql([3, 2]); // br
expect(thirdCallFirstArg).to.eql([3, 4]); // tr
expect(fourthCallFirstArg).to.eql([1, 4]); // tl
});
it('calls a truthy callback only once', function() {
var extent = [1, 2, 3, 4];
ol.extent.forEachCorner(extent, callbackTrue);
expect(callbackTrue.callCount).to.be(1);
});
it('ensures that any corner can cancel the callback execution', function() {
var extent = [1, 2, 3, 4];
var bottomLeftSpy = sinon.spy(function(corner) {
return (corner[0] === 1 && corner[1] === 2) ? true : false;
});
var bottomRightSpy = sinon.spy(function(corner) {
return (corner[0] === 3 && corner[1] === 2) ? true : false;
});
var topRightSpy = sinon.spy(function(corner) {
return (corner[0] === 3 && corner[1] === 4) ? true : false;
});
var topLeftSpy = sinon.spy(function(corner) {
return (corner[0] === 1 && corner[1] === 4) ? true : false;
});
ol.extent.forEachCorner(extent, bottomLeftSpy);
ol.extent.forEachCorner(extent, bottomRightSpy);
ol.extent.forEachCorner(extent, topRightSpy);
ol.extent.forEachCorner(extent, topLeftSpy);
expect(bottomLeftSpy.callCount).to.be(1);
expect(bottomRightSpy.callCount).to.be(2);
expect(topRightSpy.callCount).to.be(3);
expect(topLeftSpy.callCount).to.be(4);
});
it('returns false eventually, if no invocation returned a truthy value',
function() {
var extent = [1, 2, 3, 4];
var spy = sinon.spy(); // will return undefined for each corner
var got = ol.extent.forEachCorner(extent, spy);
expect(spy.callCount).to.be(4);
expect(got).to.be(false);
}
);
it('calls the callback with given scope', function() {
var extent = [1, 2, 3, 4];
var scope = {humpty: 'dumpty'};
ol.extent.forEachCorner(extent, callbackTrue, scope);
expect(callbackTrue.calledOn(scope)).to.be(true);
});
});
describe('getArea', function() {
it('returns zero for empty extents', function() {
var emptyExtent = ol.extent.createEmpty();
var areaEmpty = ol.extent.getArea(emptyExtent);
expect(areaEmpty).to.be(0);
var extentDeltaXZero = [45, 67, 45, 78];
var areaDeltaXZero = ol.extent.getArea(extentDeltaXZero);
expect(areaDeltaXZero).to.be(0);
var extentDeltaYZero = [11, 67, 45, 67];
var areaDeltaYZero = ol.extent.getArea(extentDeltaYZero);
expect(areaDeltaYZero).to.be(0);
});
it('calculates correct area for other extents', function() {
var extent = [0, 0, 10, 10];
var area = ol.extent.getArea(extent);
expect(area).to.be(100);
});
});
describe('getIntersection()', function() {
it('returns the intersection of two extents', function() {
var world = [-180, -90, 180, 90];
var north = [-180, 0, 180, 90];
var farNorth = [-180, 45, 180, 90];
var east = [0, -90, 180, 90];
var farEast = [90, -90, 180, 90];
var south = [-180, -90, 180, 0];
var farSouth = [-180, -90, 180, -45];
var west = [-180, -90, 0, 90];
var farWest = [-180, -90, -90, 90];
var none = ol.extent.createEmpty();
expect(ol.extent.getIntersection(world, none)).to.eql(none);
expect(ol.extent.getIntersection(world, north)).to.eql(north);
expect(ol.extent.getIntersection(world, east)).to.eql(east);
expect(ol.extent.getIntersection(world, south)).to.eql(south);
expect(ol.extent.getIntersection(world, west)).to.eql(west);
expect(ol.extent.getIntersection(farEast, farWest)).to.eql(none);
expect(ol.extent.getIntersection(farNorth, farSouth)).to.eql(none);
expect(ol.extent.getIntersection(north, west)).to.eql([-180, 0, 0, 90]);
expect(ol.extent.getIntersection(east, south)).to.eql([0, -90, 180, 0]);
});
});
describe('containsCoordinate', function() {
describe('positive', function() {
it('returns true', function() {
var extent = [1, 2, 3, 4];
expect(ol.extent.containsCoordinate(extent, [1, 2])).to.be.ok();
expect(ol.extent.containsCoordinate(extent, [1, 3])).to.be.ok();
expect(ol.extent.containsCoordinate(extent, [1, 4])).to.be.ok();
expect(ol.extent.containsCoordinate(extent, [2, 2])).to.be.ok();
expect(ol.extent.containsCoordinate(extent, [2, 3])).to.be.ok();
expect(ol.extent.containsCoordinate(extent, [2, 4])).to.be.ok();
expect(ol.extent.containsCoordinate(extent, [3, 2])).to.be.ok();
expect(ol.extent.containsCoordinate(extent, [3, 3])).to.be.ok();
expect(ol.extent.containsCoordinate(extent, [3, 4])).to.be.ok();
});
});
describe('negative', function() {
it('returns false', function() {
var extent = [1, 2, 3, 4];
expect(ol.extent.containsCoordinate(extent, [0, 1])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [0, 2])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [0, 3])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [0, 4])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [0, 5])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [1, 1])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [1, 5])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [2, 1])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [2, 5])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [3, 1])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [3, 5])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [4, 1])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [4, 2])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [4, 3])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [4, 4])).to.not.be();
expect(ol.extent.containsCoordinate(extent, [4, 5])).to.not.be();
});
});
});
describe('coordinateRelationship()', function() {
var extent = [-180, -90, 180, 90];
var INTERSECTING = 1;
var ABOVE = 2;
var RIGHT = 4;
var BELOW = 8;
var LEFT = 16;
it('returns intersecting for within', function() {
var rel = ol.extent.coordinateRelationship(extent, [0, 0]);
expect(rel).to.be(INTERSECTING);
});
it('returns intersecting for touching top', function() {
var rel = ol.extent.coordinateRelationship(extent, [0, 90]);
expect(rel).to.be(INTERSECTING);
});
it('returns intersecting for touching right', function() {
var rel = ol.extent.coordinateRelationship(extent, [180, 0]);
expect(rel).to.be(INTERSECTING);
});
it('returns intersecting for touching bottom', function() {
var rel = ol.extent.coordinateRelationship(extent, [0, -90]);
expect(rel).to.be(INTERSECTING);
});
it('returns intersecting for touching left', function() {
var rel = ol.extent.coordinateRelationship(extent, [-180, 0]);
expect(rel).to.be(INTERSECTING);
});
it('above for north', function() {
var rel = ol.extent.coordinateRelationship(extent, [0, 100]);
expect(rel).to.be(ABOVE);
});
it('above and right for northeast', function() {
var rel = ol.extent.coordinateRelationship(extent, [190, 100]);
expect(rel & ABOVE).to.be(ABOVE);
expect(rel & RIGHT).to.be(RIGHT);
});
it('right for east', function() {
var rel = ol.extent.coordinateRelationship(extent, [190, 0]);
expect(rel).to.be(RIGHT);
});
it('below and right for southeast', function() {
var rel = ol.extent.coordinateRelationship(extent, [190, -100]);
expect(rel & BELOW).to.be(BELOW);
expect(rel & RIGHT).to.be(RIGHT);
});
it('below for south', function() {
var rel = ol.extent.coordinateRelationship(extent, [0, -100]);
expect(rel).to.be(BELOW);
});
it('below and left for southwest', function() {
var rel = ol.extent.coordinateRelationship(extent, [-190, -100]);
expect(rel & BELOW).to.be(BELOW);
expect(rel & LEFT).to.be(LEFT);
});
it('left for west', function() {
var rel = ol.extent.coordinateRelationship(extent, [-190, 0]);
expect(rel).to.be(LEFT);
});
it('above and left for northwest', function() {
var rel = ol.extent.coordinateRelationship(extent, [-190, 100]);
expect(rel & ABOVE).to.be(ABOVE);
expect(rel & LEFT).to.be(LEFT);
});
});
describe('getCenter', function() {
it('returns the expected center', function() {
var extent = [1, 2, 3, 4];
var center = ol.extent.getCenter(extent);
expect(center[0]).to.eql(2);
expect(center[1]).to.eql(3);
});
it('returns [NaN, NaN] for empty extents', function() {
var extent = ol.extent.createEmpty();
var center = ol.extent.getCenter(extent);
expect('' + center[0]).to.be('NaN');
expect('' + center[1]).to.be('NaN');
});
});
describe('getCorner', function() {
var extent = [1, 2, 3, 4];
it('gets the bottom left', function() {
var corner = 'bottom-left';
expect(ol.extent.getCorner(extent, corner)).to.eql([1, 2]);
});
it('gets the bottom right', function() {
var corner = 'bottom-right';
expect(ol.extent.getCorner(extent, corner)).to.eql([3, 2]);
});
it('gets the top left', function() {
var corner = 'top-left';
expect(ol.extent.getCorner(extent, corner)).to.eql([1, 4]);
});
it('gets the top right', function() {
var corner = 'top-right';
expect(ol.extent.getCorner(extent, corner)).to.eql([3, 4]);
});
it('throws exception for unexpected corner', function() {
expect(function() {
ol.extent.getCorner(extent, 'foobar');
}).to.throwException();
});
});
describe('getEnlargedArea', function() {
it('returns enlarged area of two extents', function() {
var extent1 = [-1, -1, 0, 0];
var extent2 = [0, 0, 1, 1];
var enlargedArea = ol.extent.getEnlargedArea(extent1, extent2);
expect(enlargedArea).to.be(4);
});
});
describe('getForViewAndSize', function() {
it('works for a unit square', function() {
var extent = ol.extent.getForViewAndSize(
[0, 0], 1, 0, [1, 1]);
expect(extent[0]).to.be(-0.5);
expect(extent[2]).to.be(0.5);
expect(extent[1]).to.be(-0.5);
expect(extent[3]).to.be(0.5);
});
it('works for center', function() {
var extent = ol.extent.getForViewAndSize(
[5, 10], 1, 0, [1, 1]);
expect(extent[0]).to.be(4.5);
expect(extent[2]).to.be(5.5);
expect(extent[1]).to.be(9.5);
expect(extent[3]).to.be(10.5);
});
it('works for rotation', function() {
var extent = ol.extent.getForViewAndSize(
[0, 0], 1, Math.PI / 4, [1, 1]);
expect(extent[0]).to.roughlyEqual(-Math.sqrt(0.5), 1e-9);
expect(extent[2]).to.roughlyEqual(Math.sqrt(0.5), 1e-9);
expect(extent[1]).to.roughlyEqual(-Math.sqrt(0.5), 1e-9);
expect(extent[3]).to.roughlyEqual(Math.sqrt(0.5), 1e-9);
});
it('works for resolution', function() {
var extent = ol.extent.getForViewAndSize(
[0, 0], 2, 0, [1, 1]);
expect(extent[0]).to.be(-1);
expect(extent[2]).to.be(1);
expect(extent[1]).to.be(-1);
expect(extent[3]).to.be(1);
});
it('works for size', function() {
var extent = ol.extent.getForViewAndSize(
[0, 0], 1, 0, [10, 5]);
expect(extent[0]).to.be(-5);
expect(extent[2]).to.be(5);
expect(extent[1]).to.be(-2.5);
expect(extent[3]).to.be(2.5);
});
});
describe('getSize', function() {
it('returns the expected size', function() {
var extent = [0, 1, 2, 4];
var size = ol.extent.getSize(extent);
expect(size).to.eql([2, 3]);
});
});
describe('getIntersectionArea', function() {
it('returns correct area when extents intersect', function() {
var extent1 = [0, 0, 2, 2];
var extent2 = [1, 1, 3, 3];
var intersectionArea = ol.extent.getIntersectionArea(extent1, extent2);
expect(intersectionArea).to.be(1);
});
it('returns 0 when extents do not intersect', function() {
var extent1 = [0, 0, 1, 1];
var extent2 = [2, 2, 3, 3];
var intersectionArea = ol.extent.getIntersectionArea(extent1, extent2);
expect(intersectionArea).to.be(0);
});
});
describe('getMargin', function() {
it('returns the correct margin (sum of width and height)', function() {
var extent = [1, 2, 3, 4];
expect(ol.extent.getMargin(extent)).to.be(4);
});
});
describe('intersects', function() {
it('returns the expected value', function() {
var intersects = ol.extent.intersects;
var extent = [50, 50, 100, 100];
expect(intersects(extent, extent)).to.be(true);
expect(intersects(extent, [20, 20, 80, 80])).to.be(true);
expect(intersects(extent, [20, 50, 80, 100])).to.be(true);
expect(intersects(extent, [20, 80, 80, 120])).to.be(true);
expect(intersects(extent, [50, 20, 100, 80])).to.be(true);
expect(intersects(extent, [50, 80, 100, 120])).to.be(true);
expect(intersects(extent, [80, 20, 120, 80])).to.be(true);
expect(intersects(extent, [80, 50, 120, 100])).to.be(true);
expect(intersects(extent, [80, 80, 120, 120])).to.be(true);
expect(intersects(extent, [20, 20, 120, 120])).to.be(true);
expect(intersects(extent, [70, 70, 80, 80])).to.be(true);
expect(intersects(extent, [10, 10, 30, 30])).to.be(false);
expect(intersects(extent, [30, 10, 70, 30])).to.be(false);
expect(intersects(extent, [50, 10, 100, 30])).to.be(false);
expect(intersects(extent, [80, 10, 120, 30])).to.be(false);
expect(intersects(extent, [120, 10, 140, 30])).to.be(false);
expect(intersects(extent, [10, 30, 30, 70])).to.be(false);
expect(intersects(extent, [120, 30, 140, 70])).to.be(false);
expect(intersects(extent, [10, 50, 30, 100])).to.be(false);
expect(intersects(extent, [120, 50, 140, 100])).to.be(false);
expect(intersects(extent, [10, 80, 30, 120])).to.be(false);
expect(intersects(extent, [120, 80, 140, 120])).to.be(false);
expect(intersects(extent, [10, 120, 30, 140])).to.be(false);
expect(intersects(extent, [30, 120, 70, 140])).to.be(false);
expect(intersects(extent, [50, 120, 100, 140])).to.be(false);
expect(intersects(extent, [80, 120, 120, 140])).to.be(false);
expect(intersects(extent, [120, 120, 140, 140])).to.be(false);
});
});
describe('scaleFromCenter', function() {
it('scales the extent from its center', function() {
var extent = [1, 1, 3, 3];
ol.extent.scaleFromCenter(extent, 2);
expect(extent[0]).to.eql(0);
expect(extent[2]).to.eql(4);
expect(extent[1]).to.eql(0);
expect(extent[3]).to.eql(4);
});
});
describe('intersectsSegment()', function() {
var extent = [-180, -90, 180, 90];
var north = [0, 100];
var northeast = [190, 100];
var east = [190, 0];
var southeast = [190, -100];
var south = [0, -100];
var southwest = [-190, -100];
var west = [-190, 0];
var northwest = [-190, 100];
var center = [0, 0];
var top = [0, 90];
var right = [180, 0];
var bottom = [-90, 0];
var left = [-180, 0];
var inside = [10, 10];
it('returns true if contained', function() {
var intersects = ol.extent.intersectsSegment(extent, center, inside);
expect(intersects).to.be(true);
});
it('returns true if crosses top', function() {
var intersects = ol.extent.intersectsSegment(extent, center, north);
expect(intersects).to.be(true);
});
it('returns true if crosses right', function() {
var intersects = ol.extent.intersectsSegment(extent, center, east);
expect(intersects).to.be(true);
});
it('returns true if crosses bottom', function() {
var intersects = ol.extent.intersectsSegment(extent, center, south);
expect(intersects).to.be(true);
});
it('returns true if crosses left', function() {
var intersects = ol.extent.intersectsSegment(extent, center, west);
expect(intersects).to.be(true);
});
it('returns false if above', function() {
var intersects = ol.extent.intersectsSegment(extent, northwest, north);
expect(intersects).to.be(false);
});
it('returns false if right', function() {
var intersects = ol.extent.intersectsSegment(extent, northeast, east);
expect(intersects).to.be(false);
});
it('returns false if below', function() {
var intersects = ol.extent.intersectsSegment(extent, south, southwest);
expect(intersects).to.be(false);
});
it('returns false if left', function() {
var intersects = ol.extent.intersectsSegment(extent, west, southwest);
expect(intersects).to.be(false);
});
it('returns true if crosses top to bottom', function() {
var intersects = ol.extent.intersectsSegment(extent, north, south);
expect(intersects).to.be(true);
});
it('returns true if crosses bottom to top', function() {
var intersects = ol.extent.intersectsSegment(extent, south, north);
expect(intersects).to.be(true);
});
it('returns true if crosses left to right', function() {
var intersects = ol.extent.intersectsSegment(extent, west, east);
expect(intersects).to.be(true);
});
it('returns true if crosses right to left', function() {
var intersects = ol.extent.intersectsSegment(extent, east, west);
expect(intersects).to.be(true);
});
it('returns true if crosses northwest to east', function() {
var intersects = ol.extent.intersectsSegment(extent, northwest, east);
expect(intersects).to.be(true);
});
it('returns true if crosses south to west', function() {
var intersects = ol.extent.intersectsSegment(extent, south, west);
expect(intersects).to.be(true);
});
it('returns true if touches top', function() {
var intersects = ol.extent.intersectsSegment(extent, northwest, top);
expect(intersects).to.be(true);
});
it('returns true if touches right', function() {
var intersects = ol.extent.intersectsSegment(extent, southeast, right);
expect(intersects).to.be(true);
});
it('returns true if touches bottom', function() {
var intersects = ol.extent.intersectsSegment(extent, bottom, south);
expect(intersects).to.be(true);
});
it('returns true if touches left', function() {
var intersects = ol.extent.intersectsSegment(extent, left, west);
expect(intersects).to.be(true);
});
it('works for zero length inside', function() {
var intersects = ol.extent.intersectsSegment(extent, center, center);
expect(intersects).to.be(true);
});
it('works for zero length outside', function() {
var intersects = ol.extent.intersectsSegment(extent, north, north);
expect(intersects).to.be(false);
});
it('works for left/right intersection spanning top to bottom', function() {
var extent = [2, 1, 3, 4];
var start = [0, 0];
var end = [5, 5];
expect(ol.extent.intersectsSegment(extent, start, end)).to.be(true);
expect(ol.extent.intersectsSegment(extent, end, start)).to.be(true);
});
it('works for top/bottom intersection spanning left to right', function() {
var extent = [1, 2, 4, 3];
var start = [0, 0];
var end = [5, 5];
expect(ol.extent.intersectsSegment(extent, start, end)).to.be(true);
expect(ol.extent.intersectsSegment(extent, end, start)).to.be(true);
});
});
describe('#applyTransform()', function() {
it('does transform', function() {
var transformFn = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
var sourceExtent = [-15, -30, 45, 60];
var destinationExtent = ol.extent.applyTransform(
sourceExtent, transformFn);
expect(destinationExtent).not.to.be(undefined);
expect(destinationExtent).not.to.be(null);
// FIXME check values with third-party tool
expect(destinationExtent[0])
.to.roughlyEqual(-1669792.3618991037, 1e-9);
expect(destinationExtent[2]).to.roughlyEqual(5009377.085697311, 1e-9);
expect(destinationExtent[1]).to.roughlyEqual(-3503549.843504376, 1e-8);
expect(destinationExtent[3]).to.roughlyEqual(8399737.889818361, 1e-8);
});
it('takes arbitrary function', function() {
var transformFn = function(input, output, opt_dimension) {
var dimension = opt_dimension !== undefined ? opt_dimension : 2;
if (output === undefined) {
output = new Array(input.length);
}
var n = input.length;
var i;
for (i = 0; i < n; i += dimension) {
output[i] = -input[i];
output[i + 1] = -input[i + 1];
}
return output;
};
var sourceExtent = [-15, -30, 45, 60];
var destinationExtent = ol.extent.applyTransform(
sourceExtent, transformFn);
expect(destinationExtent).not.to.be(undefined);
expect(destinationExtent).not.to.be(null);
expect(destinationExtent[0]).to.be(-45);
expect(destinationExtent[2]).to.be(15);
expect(destinationExtent[1]).to.be(-60);
expect(destinationExtent[3]).to.be(30);
});
});
});
| wet-boew/openlayers-dist | test/spec/ol/extent.test.js | JavaScript | bsd-2-clause | 27,991 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* This view displays options for exporting the captured data.
*/
var ExportView = (function() {
'use strict';
// We inherit from DivView.
var superClass = DivView;
/**
* @constructor
*/
function ExportView() {
assertFirstConstructorCall(ExportView);
// Call superclass's constructor.
superClass.call(this, ExportView.MAIN_BOX_ID);
var privacyStrippingCheckbox = $(ExportView.PRIVACY_STRIPPING_CHECKBOX_ID);
privacyStrippingCheckbox.onclick =
this.onSetPrivacyStripping_.bind(this, privacyStrippingCheckbox);
this.saveFileButton_ = $(ExportView.SAVE_FILE_BUTTON_ID);
this.saveFileButton_.onclick = this.onSaveFile_.bind(this);
this.saveStatusText_ = $(ExportView.SAVE_STATUS_TEXT_ID);
this.userCommentsTextArea_ = $(ExportView.USER_COMMENTS_TEXT_AREA_ID);
// Track blob for previous log dump so it can be revoked when a new dump is
// saved.
this.lastBlobURL_ = null;
// Cached copy of the last loaded log dump, for use when exporting.
this.loadedLogDump_ = null;
}
// ID for special HTML element in category_tabs.html
ExportView.TAB_HANDLE_ID = 'tab-handle-export';
// IDs for special HTML elements in export_view.html
ExportView.MAIN_BOX_ID = 'export-view-tab-content';
ExportView.DOWNLOAD_ANCHOR_ID = 'export-view-download-anchor';
ExportView.SAVE_FILE_BUTTON_ID = 'export-view-save-log-file';
ExportView.SAVE_STATUS_TEXT_ID = 'export-view-save-status-text';
ExportView.PRIVACY_STRIPPING_CHECKBOX_ID =
'export-view-privacy-stripping-checkbox';
ExportView.USER_COMMENTS_TEXT_AREA_ID = 'export-view-user-comments';
ExportView.PRIVACY_WARNING_ID = 'export-view-privacy-warning';
cr.addSingletonGetter(ExportView);
ExportView.prototype = {
// Inherit the superclass's methods.
__proto__: superClass.prototype,
/**
* Depending on the value of the checkbox, enables or disables stripping
* cookies and passwords from log dumps and displayed events.
*/
onSetPrivacyStripping_: function(privacyStrippingCheckbox) {
SourceTracker.getInstance().setPrivacyStripping(
privacyStrippingCheckbox.checked);
},
/**
* When loading a log dump, cache it for future export and continue showing
* the ExportView.
*/
onLoadLogFinish: function(polledData, tabData, logDump) {
this.loadedLogDump_ = logDump;
this.setUserComments_(logDump.userComments);
return true;
},
/**
* Sets the save to file status text, displayed below the save to file
* button, to |text|. Also enables or disables the save button based on the
* value of |isSaving|, which must be true if the save process is still
* ongoing, and false when the operation has stopped, regardless of success
* of failure.
*/
setSaveFileStatus: function(text, isSaving) {
this.enableSaveFileButton_(!isSaving);
this.saveStatusText_.textContent = text;
},
enableSaveFileButton_: function(enabled) {
this.saveFileButton_.disabled = !enabled;
},
showPrivacyWarning: function() {
setNodeDisplay($(ExportView.PRIVACY_WARNING_ID), true);
$(ExportView.PRIVACY_STRIPPING_CHECKBOX_ID).checked = false;
$(ExportView.PRIVACY_STRIPPING_CHECKBOX_ID).disabled = true;
// Updating the checkbox doesn't actually disable privacy stripping, since
// the onclick function will not be called.
this.onSetPrivacyStripping_($(ExportView.PRIVACY_STRIPPING_CHECKBOX_ID));
},
/**
* If not already busy saving a log dump, triggers asynchronous
* generation of log dump and starts waiting for it to complete.
*/
onSaveFile_: function() {
if (this.saveFileButton_.disabled)
return;
// Clean up previous blob, if any, to reduce resource usage.
if (this.lastBlobURL_) {
window.webkitURL.revokeObjectURL(this.lastBlobURL_);
this.lastBlobURL_ = null;
}
this.createLogDump_(this.onLogDumpCreated_.bind(this));
},
/**
* Creates a log dump, and either synchronously or asynchronously calls
* |callback| if it succeeds. Separate from onSaveFile_ for unit tests.
*/
createLogDump_: function(callback) {
// Get an explanation for the dump file (this is mandatory!)
var userComments = this.getNonEmptyUserComments_();
if (userComments == undefined) {
return;
}
this.setSaveFileStatus('Preparing data...', true);
var privacyStripping = SourceTracker.getInstance().getPrivacyStripping();
// If we have a cached log dump, update it synchronously.
if (this.loadedLogDump_) {
var dumpText = log_util.createUpdatedLogDump(userComments,
this.loadedLogDump_,
privacyStripping);
callback(dumpText);
return;
}
// Otherwise, poll information from the browser before creating one.
log_util.createLogDumpAsync(userComments,
callback,
privacyStripping);
},
/**
* Sets the user comments.
*/
setUserComments_: function(userComments) {
this.userCommentsTextArea_.value = userComments;
},
/**
* Fetches the user comments for this dump. If none were entered, warns the
* user and returns undefined. Otherwise returns the comments text.
*/
getNonEmptyUserComments_: function() {
var value = this.userCommentsTextArea_.value;
// Reset the class name in case we had hilighted it earlier.
this.userCommentsTextArea_.className = '';
// We don't accept empty explanations. We don't care what is entered, as
// long as there is something (a single whitespace would work).
if (value == '') {
// Put a big obnoxious red border around the text area.
this.userCommentsTextArea_.className =
'export-view-explanation-warning';
alert('Please fill in the text field!');
return undefined;
}
return value;
},
/**
* Creates a blob url and starts downloading it.
*/
onLogDumpCreated_: function(dumpText) {
var textBlob = new Blob([dumpText], {type: 'octet/stream'});
this.lastBlobURL_ = window.webkitURL.createObjectURL(textBlob);
// Update the anchor tag and simulate a click on it to start the
// download.
var downloadAnchor = $(ExportView.DOWNLOAD_ANCHOR_ID);
downloadAnchor.href = this.lastBlobURL_;
downloadAnchor.click();
this.setSaveFileStatus('Dump successful', false);
}
};
return ExportView;
})();
| zcbenz/cefode-chromium | chrome/browser/resources/net_internals/export_view.js | JavaScript | bsd-3-clause | 6,896 |
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Variable = void 0;
const variable_1 = __importDefault(require("eslint-scope/lib/variable"));
const Variable = variable_1.default;
exports.Variable = Variable;
//# sourceMappingURL=Variable.js.map | ChromeDevTools/devtools-frontend | node_modules/@typescript-eslint/experimental-utils/dist/ts-eslint-scope/Variable.js | JavaScript | bsd-3-clause | 419 |
/*jslint sloppy: true, nomen: true */
/*global exports:true */
/*
This file is part of the PhantomJS project from Ofi Labs.
Copyright (C) 2013 Joseph Rollinson, [email protected]
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* Takes in a QtCookieJar and decorates it with useful functions. */
function decorateCookieJar(jar) {
/* Allows one to add a cookie to the cookie jar from inside JavaScript */
jar.addCookie = function(cookie) {
jar.addCookieFromMap(cookie);
};
/* Getting and Setting jar.cookies gets and sets all the cookies in the
* cookie jar.
*/
jar.__defineGetter__('cookies', function() {
return this.cookiesToMap();
});
jar.__defineSetter__('cookies', function(cookies) {
this.addCookiesFromMap(cookies);
});
return jar;
}
/* Creates and decorates a new cookie jar.
* path is the file path where Phantomjs will store the cookie jar persistently.
* path is not mandatory.
*/
exports.create = function (path) {
if (arguments.length < 1) {
path = "";
}
return decorateCookieJar(phantom.createCookieJar(path));
};
/* Exports the decorateCookieJar function */
exports.decorate = decorateCookieJar;
| tianzhihen/phantomjs | src/modules/cookiejar.js | JavaScript | bsd-3-clause | 2,651 |
import { Directive, EventEmitter } from '@angular/core';
import { KmlLayerManager } from './../services/managers/kml-layer-manager';
var layerId = 0;
export var SebmGoogleMapKmlLayer = (function () {
function SebmGoogleMapKmlLayer(_manager) {
this._manager = _manager;
this._addedToManager = false;
this._id = (layerId++).toString();
this._subscriptions = [];
/**
* If true, the layer receives mouse events. Default value is true.
*/
this.clickable = true;
/**
* By default, the input map is centered and zoomed to the bounding box of the contents of the
* layer.
* If this option is set to true, the viewport is left unchanged, unless the map's center and zoom
* were never set.
*/
this.preserveViewport = false;
/**
* Whether to render the screen overlays. Default true.
*/
this.screenOverlays = true;
/**
* Suppress the rendering of info windows when layer features are clicked.
*/
this.suppressInfoWindows = false;
/**
* The URL of the KML document to display.
*/
this.url = null;
/**
* The z-index of the layer.
*/
this.zIndex = null;
/**
* This event is fired when a feature in the layer is clicked.
*/
this.layerClick = new EventEmitter();
/**
* This event is fired when the KML layers default viewport has changed.
*/
this.defaultViewportChange = new EventEmitter();
/**
* This event is fired when the KML layer has finished loading.
* At this point it is safe to read the status property to determine if the layer loaded
* successfully.
*/
this.statusChange = new EventEmitter();
}
SebmGoogleMapKmlLayer.prototype.ngOnInit = function () {
if (this._addedToManager) {
return;
}
this._manager.addKmlLayer(this);
this._addedToManager = true;
this._addEventListeners();
};
SebmGoogleMapKmlLayer.prototype.ngOnChanges = function (changes) {
if (!this._addedToManager) {
return;
}
this._updatePolygonOptions(changes);
};
SebmGoogleMapKmlLayer.prototype._updatePolygonOptions = function (changes) {
var options = Object.keys(changes)
.filter(function (k) { return SebmGoogleMapKmlLayer._kmlLayerOptions.indexOf(k) !== -1; })
.reduce(function (obj, k) {
obj[k] = changes[k].currentValue;
return obj;
}, {});
if (Object.keys(options).length > 0) {
this._manager.setOptions(this, options);
}
};
SebmGoogleMapKmlLayer.prototype._addEventListeners = function () {
var _this = this;
var listeners = [
{ name: 'click', handler: function (ev) { return _this.layerClick.emit(ev); } },
{ name: 'defaultviewport_changed', handler: function () { return _this.defaultViewportChange.emit(); } },
{ name: 'status_changed', handler: function () { return _this.statusChange.emit(); } },
];
listeners.forEach(function (obj) {
var os = _this._manager.createEventObservable(obj.name, _this).subscribe(obj.handler);
_this._subscriptions.push(os);
});
};
/** @internal */
SebmGoogleMapKmlLayer.prototype.id = function () { return this._id; };
/** @internal */
SebmGoogleMapKmlLayer.prototype.toString = function () { return "SebmGoogleMapKmlLayer-" + this._id.toString(); };
/** @internal */
SebmGoogleMapKmlLayer.prototype.ngOnDestroy = function () {
this._manager.deleteKmlLayer(this);
// unsubscribe all registered observable subscriptions
this._subscriptions.forEach(function (s) { return s.unsubscribe(); });
};
SebmGoogleMapKmlLayer._kmlLayerOptions = ['clickable', 'preserveViewport', 'screenOverlays', 'suppressInfoWindows', 'url', 'zIndex'];
SebmGoogleMapKmlLayer.decorators = [
{ type: Directive, args: [{
selector: 'sebm-google-map-kml-layer',
inputs: ['clickable', 'preserveViewport', 'screenOverlays', 'suppressInfoWindows', 'url', 'zIndex'],
outputs: ['layerClick', 'defaultViewportChange', 'statusChange']
},] },
];
/** @nocollapse */
SebmGoogleMapKmlLayer.ctorParameters = function () { return [
{ type: KmlLayerManager, },
]; };
return SebmGoogleMapKmlLayer;
}());
//# sourceMappingURL=google-map-kml-layer.js.map | Oussemalaamiri/guidemeAngular | src/node_modules/angular2-google-maps/esm/core/directives/google-map-kml-layer.js | JavaScript | mit | 4,685 |
function makeData() {
"use strict";
return [makeRandomData(10), makeRandomData(10)];
}
function run(svg, data, Plottable) {
"use strict";
var largeX = function(d, i){
d.x = Math.pow(10, i);
};
var bigNumbers = [];
deepCopy(data[0], bigNumbers);
bigNumbers.forEach(largeX);
var dataseries1 = new Plottable.Dataset(bigNumbers);
//Axis
var xScale = new Plottable.Scales.Linear();
var yScale = new Plottable.Scales.Linear();
var xAxis = new Plottable.Axes.Numeric(xScale, "bottom");
var yAxis = new Plottable.Axes.Numeric(yScale, "left");
var IdTitle = new Plottable.Components.Label("Identity");
var GenTitle = new Plottable.Components.Label("General");
var FixTitle = new Plottable.Components.Label("Fixed");
var CurrTitle = new Plottable.Components.Label("Currency");
var PerTitle = new Plottable.Components.Label("Percentage");
var SITitle = new Plottable.Components.Label("SI");
var SSTitle = new Plottable.Components.Label("Short Scale");
var plot = new Plottable.Plots.Line().addDataset(dataseries1);
plot.x(function(d) { return d.x; }, xScale).y(function(d) { return d.y; }, yScale);
var basicTable = new Plottable.Components.Table([[yAxis, plot], [null, xAxis]]);
var formatChoices = new Plottable.Components.Table([[IdTitle, GenTitle, FixTitle], [CurrTitle, null, PerTitle], [SITitle, null, SSTitle]]);
var bigTable = new Plottable.Components.Table([[basicTable], [formatChoices]]);
formatChoices.xAlignment("center");
bigTable.renderTo(svg);
function useIdentityFormatter() {
xAxis.formatter(Plottable.Formatters.identity(2.1));
yAxis.formatter(Plottable.Formatters.identity());
}
function useGeneralFormatter() {
xAxis.formatter(Plottable.Formatters.general(7));
yAxis.formatter(Plottable.Formatters.general(3));
}
function useFixedFormatter() {
xAxis.formatter(Plottable.Formatters.fixed(2.00));
yAxis.formatter(Plottable.Formatters.fixed(7.00));
}
function useCurrencyFormatter() {
xAxis.formatter(Plottable.Formatters.currency(3, "$", true));
yAxis.formatter(Plottable.Formatters.currency(3, "$", true));
}
function usePercentageFormatter() {
xAxis.formatter(Plottable.Formatters.percentage(12.3 - 11.3));
yAxis.formatter(Plottable.Formatters.percentage(2.5 + 1.5));
}
function useSIFormatter() {
xAxis.formatter(Plottable.Formatters.siSuffix(7));
yAxis.formatter(Plottable.Formatters.siSuffix(14));
}
function useSSFormatter() {
xAxis.formatter(Plottable.Formatters.shortScale(0));
yAxis.formatter(Plottable.Formatters.shortScale(0));
}
new Plottable.Interactions.Click().onClick(useIdentityFormatter).attachTo(IdTitle);
new Plottable.Interactions.Click().onClick(useGeneralFormatter).attachTo(GenTitle);
new Plottable.Interactions.Click().onClick(useFixedFormatter).attachTo(FixTitle);
new Plottable.Interactions.Click().onClick(useCurrencyFormatter).attachTo(CurrTitle);
new Plottable.Interactions.Click().onClick(usePercentageFormatter).attachTo(PerTitle);
new Plottable.Interactions.Click().onClick(useSIFormatter).attachTo(SITitle);
new Plottable.Interactions.Click().onClick(useSSFormatter).attachTo(SSTitle);
}
| iobeam/plottable | quicktests/overlaying/tests/functional/formatter.js | JavaScript | mit | 3,212 |
JsonRoutes.add('post', '/' + Meteor.settings.private.stripe.webhookEndpoint, function (req, res) {
Letterpress.Services.Buy.handleEvent(req.body);
JsonRoutes.sendResult(res, 200);
}); | FleetingClouds/Letterpress | server/api/webhooks-api.js | JavaScript | mit | 187 |
'use strict';
var spawn = require('child_process').spawn;
var os = require('os');
var pathlib = require('path');
var fs = require('fs');
var net = require('net');
var crypto = require('crypto');
var which = require('which');
var pathOpenSSL;
var tempDir = process.env.PEMJS_TMPDIR || (os.tmpdir || os.tmpDir) && (os.tmpdir || os.tmpDir)() || '/tmp';
module.exports.createPrivateKey = createPrivateKey;
module.exports.createDhparam = createDhparam;
module.exports.createCSR = createCSR;
module.exports.createCertificate = createCertificate;
module.exports.readCertificateInfo = readCertificateInfo;
module.exports.getPublicKey = getPublicKey;
module.exports.getFingerprint = getFingerprint;
module.exports.getModulus = getModulus;
module.exports.config = config;
// PUBLIC API
/**
* Creates a private key
*
* @param {Number} [keyBitsize=2048] Size of the key, defaults to 2048bit
* @param {Object} [options] object of cipher and password {cipher:'aes128',password:'xxx'}, defaults empty object
* @param {Function} callback Callback function with an error object and {key}
*/
function createPrivateKey(keyBitsize, options, callback) {
var clientKeyPassword;
if (!callback && !options && typeof keyBitsize === 'function') {
callback = keyBitsize;
keyBitsize = undefined;
options = {};
}
else if (!callback && keyBitsize && typeof options === 'function') {
callback = options;
options = {};
}
keyBitsize = Number(keyBitsize) || 2048;
var params = ['genrsa',
'-rand',
'/var/log/mail:/var/log/messages'
];
var cipher = ["aes128", "aes192", "aes256", "camellia128", "camellia192", "camellia256", "des", "des3", "idea"];
if (options && options.cipher && ( -1 !== Number(cipher.indexOf(options.cipher)) ) && options.password){
clientKeyPassword = pathlib.join(tempDir, crypto.randomBytes(20).toString('hex'));
fs.writeFileSync(clientKeyPassword, options.password);
params.push( '-' + options.cipher );
params.push( '-passout' );
params.push( 'file:' + clientKeyPassword );
}
params.push(keyBitsize);
execOpenSSL(params, 'RSA PRIVATE KEY', function(error, key) {
if(clientKeyPassword) {
fs.unlink(clientKeyPassword);
}
if (error) {
return callback(error);
}
return callback(null, {
key: key
});
});
}
/**
* Creates a dhparam key
*
* @param {Number} [keyBitsize=512] Size of the key, defaults to 512bit
* @param {Function} callback Callback function with an error object and {dhparam}
*/
function createDhparam(keyBitsize, callback) {
if (!callback && typeof keyBitsize === 'function') {
callback = keyBitsize;
keyBitsize = undefined;
}
keyBitsize = Number(keyBitsize) || 512;
var params = ['dhparam',
'-outform',
'PEM',
keyBitsize
];
execOpenSSL(params, 'DH PARAMETERS', function(error, dhparam) {
if (error) {
return callback(error);
}
return callback(null, {
dhparam: dhparam
});
});
}
/**
* Creates a Certificate Signing Request
*
* If client key is undefined, a new key is created automatically. The used key is included
* in the callback return as clientKey
*
* @param {Object} [options] Optional options object
* @param {String} [options.clientKey] Optional client key to use
* @param {Number} [options.keyBitsize] If clientKey is undefined, bit size to use for generating a new key (defaults to 2048)
* @param {String} [options.hash] Hash function to use (either md5 sha1 or sha256, defaults to sha256)
* @param {String} [options.country] CSR country field
* @param {String} [options.state] CSR state field
* @param {String} [options.locality] CSR locality field
* @param {String} [options.organization] CSR organization field
* @param {String} [options.organizationUnit] CSR organizational unit field
* @param {String} [options.commonName='localhost'] CSR common name field
* @param {String} [options.emailAddress] CSR email address field
* @param {Array} [options.altNames] is a list of subjectAltNames in the subjectAltName field
* @param {Function} callback Callback function with an error object and {csr, clientKey}
*/
function createCSR(options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
options = options || {};
// http://stackoverflow.com/questions/14089872/why-does-node-js-accept-ip-addresses-in-certificates-only-for-san-not-for-cn
if (options.commonName && (net.isIPv4(options.commonName) || net.isIPv6(options.commonName))) {
if (!options.altNames) {
options.altNames = [options.commonName];
} else if (options.altNames.indexOf(options.commonName) === -1) {
options.altNames = options.altNames.concat([options.commonName]);
}
}
if (!options.clientKey) {
createPrivateKey(options.keyBitsize || 2048, function(error, keyData) {
if (error) {
return callback(error);
}
options.clientKey = keyData.key;
createCSR(options, callback);
});
return;
}
var params = ['req',
'-new',
'-' + (options.hash || 'sha256'),
'-subj',
generateCSRSubject(options),
'-key',
'--TMPFILE--'
];
var tmpfiles = [options.clientKey];
var config = null;
if (options.altNames) {
params.push('-extensions');
params.push('v3_req');
params.push('-config');
params.push('--TMPFILE--');
var altNamesRep = [];
for (var i = 0; i < options.altNames.length; i++) {
altNamesRep.push((net.isIP(options.altNames[i]) ? 'IP' : 'DNS') + '.' + (i + 1) + ' = ' + options.altNames[i]);
}
tmpfiles.push(config = [
'[req]',
'req_extensions = v3_req',
'distinguished_name = req_distinguished_name',
'[v3_req]',
'subjectAltName = @alt_names',
'[alt_names]',
altNamesRep.join('\n'),
'[req_distinguished_name]',
'commonName = Common Name',
'commonName_max = 64',
].join('\n'));
}
var passwordFilePath = null;
if (options.clientKeyPassword) {
passwordFilePath = pathlib.join(tempDir, crypto.randomBytes(20).toString('hex'));
fs.writeFileSync(passwordFilePath, options.clientKeyPassword);
params.push('-passin');
params.push('file:' + passwordFilePath);
}
execOpenSSL(params, 'CERTIFICATE REQUEST', tmpfiles, function(error, data) {
if (passwordFilePath) {
fs.unlink(passwordFilePath);
}
if (error) {
return callback(error);
}
var response = {
csr: data,
config: config,
clientKey: options.clientKey
};
return callback(null, response);
});
}
/**
* Creates a certificate based on a CSR. If CSR is not defined, a new one
* will be generated automatically. For CSR generation all the options values
* can be used as with createCSR.
*
* @param {Object} [options] Optional options object
* @param {String} [options.serviceKey] Private key for signing the certificate, if not defined a new one is generated
* @param {Boolean} [options.selfSigned] If set to true and serviceKey is not defined, use clientKey for signing
* @param {String} [options.hash] Hash function to use (either md5 sha1 or sha256, defaults to sha256)
* @param {String} [options.csr] CSR for the certificate, if not defined a new one is generated
* @param {Number} [options.days] Certificate expire time in days
* @param {Function} callback Callback function with an error object and {certificate, csr, clientKey, serviceKey}
*/
function createCertificate(options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
options = options || {};
if (!options.csr) {
createCSR(options, function(error, keyData) {
if (error) {
return callback(error);
}
options.csr = keyData.csr;
options.config = keyData.config;
options.clientKey = keyData.clientKey;
createCertificate(options, callback);
});
return;
}
if (!options.serviceKey) {
if (options.selfSigned) {
options.serviceKey = options.clientKey;
} else {
createPrivateKey(options.keyBitsize || 2048, function(error, keyData) {
if (error) {
return callback(error);
}
options.serviceKey = keyData.key;
createCertificate(options, callback);
});
return;
}
}
var params = ['x509',
'-req',
'-' + (options.hash || 'sha256'),
'-days',
Number(options.days) || '365',
'-in',
'--TMPFILE--'
];
var tmpfiles = [options.csr];
if (options.serviceCertificate) {
if (!options.serial) {
return callback(new Error('serial option required for CA signing'));
}
params.push('-CA');
params.push('--TMPFILE--');
params.push('-CAkey');
params.push('--TMPFILE--');
params.push('-set_serial');
params.push('0x' + ('00000000' + options.serial.toString(16)).slice(-8));
tmpfiles.push(options.serviceCertificate);
tmpfiles.push(options.serviceKey);
} else {
params.push('-signkey');
params.push('--TMPFILE--');
tmpfiles.push(options.serviceKey);
}
if (options.config) {
params.push('-extensions');
params.push('v3_req');
params.push('-extfile');
params.push('--TMPFILE--');
tmpfiles.push(options.config);
}
execOpenSSL(params, 'CERTIFICATE', tmpfiles, function(error, data) {
if (error) {
return callback(error);
}
var response = {
csr: options.csr,
clientKey: options.clientKey,
certificate: data,
serviceKey: options.serviceKey
};
return callback(null, response);
});
}
/**
* Exports a public key from a private key, CSR or certificate
*
* @param {String} certificate PEM encoded private key, CSR or certificate
* @param {Function} callback Callback function with an error object and {publicKey}
*/
function getPublicKey(certificate, callback) {
if (!callback && typeof certificate === 'function') {
callback = certificate;
certificate = undefined;
}
certificate = (certificate || '').toString();
var params;
if (certificate.match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)) {
params = ['req',
'-in',
'--TMPFILE--',
'-pubkey',
'-noout'
];
} else if (certificate.match(/BEGIN RSA PRIVATE KEY/)) {
params = ['rsa',
'-in',
'--TMPFILE--',
'-pubout'
];
} else {
params = ['x509',
'-in',
'--TMPFILE--',
'-pubkey',
'-noout'
];
}
execOpenSSL(params, 'PUBLIC KEY', certificate, function(error, key) {
if (error) {
return callback(error);
}
return callback(null, {
publicKey: key
});
});
}
/**
* Reads subject data from a certificate or a CSR
*
* @param {String} certificate PEM encoded CSR or certificate
* @param {Function} callback Callback function with an error object and {country, state, locality, organization, organizationUnit, commonName, emailAddress}
*/
function readCertificateInfo(certificate, callback) {
if (!callback && typeof certificate === 'function') {
callback = certificate;
certificate = undefined;
}
certificate = (certificate || '').toString();
var type = certificate.match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/) ? 'req' : 'x509',
params = [type,
'-noout',
'-text',
'-in',
'--TMPFILE--'
];
spawnWrapper(params, certificate, function(err, code, stdout) {
if (err) {
return callback(err);
}
return fetchCertificateData(stdout, callback);
});
}
/**
* get the modulus from a certificate, a CSR or a private key
*
* @param {String} certificate PEM encoded, CSR PEM encoded, or private key
* @param {Function} callback Callback function with an error object and {modulus}
*/
function getModulus(certificate, callback) {
certificate = Buffer.isBuffer(certificate) && certificate.toString() || certificate;
var type = '';
if (certificate.match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)) {
type = 'req';
} else if (certificate.match(/BEGIN RSA PRIVATE KEY/)) {
type = 'rsa';
} else {
type = 'x509';
}
var params = [type,
'-noout',
'-modulus',
'-in',
'--TMPFILE--'
];
spawnWrapper(params, certificate, function(err, code, stdout) {
if (err) {
return callback(err);
}
var match = stdout.match(/Modulus=([0-9a-fA-F]+)$/m);
if (match) {
return callback(null, {
modulus: match[1]
});
} else {
return callback(new Error('No modulus'));
}
});
}
/**
* config the pem module
* @param {Object} options
*/
function config(options) {
if (options.pathOpenSSL) {
pathOpenSSL = options.pathOpenSSL;
}
}
/**
* Gets the fingerprint for a certificate
*
* @param {String} PEM encoded certificate
* @param {Function} callback Callback function with an error object and {fingerprint}
*/
function getFingerprint(certificate, hash, callback) {
if (!callback && typeof hash === 'function') {
callback = hash;
hash = undefined;
}
hash = hash || 'sha1';
var params = ['x509',
'-in',
'--TMPFILE--',
'-fingerprint',
'-noout',
'-' + hash
];
spawnWrapper(params, certificate, function(err, code, stdout) {
if (err) {
return callback(err);
}
var match = stdout.match(/Fingerprint=([0-9a-fA-F:]+)$/m);
if (match) {
return callback(null, {
fingerprint: match[1]
});
} else {
return callback(new Error('No fingerprint'));
}
});
}
// HELPER FUNCTIONS
function fetchCertificateData(certData, callback) {
certData = (certData || '').toString();
var subject, subject2, extra, tmp, certValues = {};
var validity = {};
var san;
if ((subject = certData.match(/Subject:([^\n]*)\n/)) && subject.length > 1) {
subject2 = linebrakes(subject[1] + '\n');
subject = subject[1];
extra = subject.split('/');
subject = extra.shift() + '\n';
extra = extra.join('/') + '\n';
// country
tmp = subject2.match(/\sC=([^\n].*?)[\n]/);
certValues.country = tmp && tmp[1] || '';
// state
tmp = subject2.match(/\sST=([^\n].*?)[\n]/);
certValues.state = tmp && tmp[1] || '';
// locality
tmp = subject2.match(/\sL=([^\n].*?)[\n]/);
certValues.locality = tmp && tmp[1] || '';
// organization
tmp = subject2.match(/\sO=([^\n].*?)[\n]/);
certValues.organization = tmp && tmp[1] || '';
// unit
tmp = subject2.match(/\sOU=([^\n].*?)[\n]/);
certValues.organizationUnit = tmp && tmp[1] || '';
// common name
tmp = subject2.match(/\sCN=([^\n].*?)[\n]/);
certValues.commonName = tmp && tmp[1] || '';
//email
tmp = extra.match(/emailAddress=([^\n\/].*?)[\n\/]/);
certValues.emailAddress = tmp && tmp[1] || '';
}
if ((san = certData.match(/X509v3 Subject Alternative Name: \n([^\n]*)\n/)) && san.length > 1) {
san = san[1].trim() + '\n';
certValues.san = {};
// country
tmp = preg_match_all('DNS:([^,\\n].*?)[,\\n]', san);
certValues.san.dns = tmp || '';
// country
tmp = preg_match_all('IP Address:([^,\\n].*?)[,\\n\\s]', san);
certValues.san.ip = tmp || '';
}
if ((tmp = certData.match(/Not Before\s?:\s?([^\n]*)\n/)) && tmp.length > 1) {
validity.start = Date.parse(tmp && tmp[1] || '');
}
if ((tmp = certData.match(/Not After\s?:\s?([^\n]*)\n/)) && tmp.length > 1) {
validity.end = Date.parse(tmp && tmp[1] || '');
}
if (validity.start && validity.end) {
certValues.validity = validity;
}
callback(null, certValues);
}
function linebrakes(content) {
var helper_x, p, subject;
helper_x = content.replace(/(C|L|O|OU|ST|CN)=/g, '\n$1=');
helper_x = preg_match_all('((C|L|O|OU|ST|CN)=[^\n].*)', helper_x);
for (p in helper_x) {
subject = helper_x[p].trim();
content = subject.split('/');
subject = content.shift();
helper_x[p] = rtrim(subject, ',');
}
return ' ' + helper_x.join('\n') + '\n';
}
function rtrim(str, charlist) {
charlist = !charlist ? ' \\s\u00A0' : (charlist + '')
.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\\$1');
var re = new RegExp('[' + charlist + ']+$', 'g');
return (str + '')
.replace(re, '');
}
function preg_match_all(regex, haystack) {
var globalRegex = new RegExp(regex, 'g');
var globalMatch = haystack.match(globalRegex);
var matchArray = [],
nonGlobalRegex, nonGlobalMatch;
for (var i in globalMatch) {
nonGlobalRegex = new RegExp(regex);
nonGlobalMatch = globalMatch[i].match(nonGlobalRegex);
matchArray.push(nonGlobalMatch[1]);
}
return matchArray;
}
function generateCSRSubject(options) {
options = options || {};
var csrData = {
C: options.country || options.C || '',
ST: options.state || options.ST || '',
L: options.locality || options.L || '',
O: options.organization || options.O || '',
OU: options.organizationUnit || options.OU || '',
CN: options.commonName || options.CN || 'localhost',
emailAddress: options.emailAddress || ''
},
csrBuilder = [];
Object.keys(csrData).forEach(function(key) {
if (csrData[key]) {
csrBuilder.push('/' + key + '=' + csrData[key].replace(/[^\w \.\*\-@]+/g, ' ').trim());
}
});
return csrBuilder.join('');
}
/**
* Generically spawn openSSL, without processing the result
*
* @param {Array} params The parameters to pass to openssl
* @param {String|Array} tmpfiles Stuff to pass to tmpfiles
* @param {Function} callback Called with (error, exitCode, stdout, stderr)
*/
function spawnOpenSSL(params, callback) {
var pathBin = pathOpenSSL || process.env.OPENSSL_BIN || 'openssl';
testOpenSSLPath(pathBin, function(err) {
if (err) {
return callback(err);
}
var openssl = spawn(pathBin, params),
stdout = '',
stderr = '';
openssl.stdout.on('data', function(data) {
stdout += (data || '').toString('binary');
});
openssl.stderr.on('data', function(data) {
stderr += (data || '').toString('binary');
});
// We need both the return code and access to all of stdout. Stdout isn't
// *really* available until the close event fires; the timing nuance was
// making this fail periodically.
var needed = 2; // wait for both exit and close.
var code = -1;
var finished = false;
var done = function(err) {
if (finished) {
return;
}
if (err) {
finished = true;
return callback(err);
}
if (--needed < 1) {
finished = true;
if (code) {
callback(new Error('Invalid openssl exit code: ' + code + '\n% openssl ' + params.join(' ') + '\n' + stderr), code);
} else {
callback(null, code, stdout, stderr);
}
}
};
openssl.on('error', done);
openssl.on('exit', function(ret) {
code = ret;
done();
});
openssl.on('close', function() {
stdout = new Buffer(stdout, 'binary').toString('utf-8');
stderr = new Buffer(stderr, 'binary').toString('utf-8');
done();
});
});
}
function spawnWrapper(params, tmpfiles, callback) {
var files = [];
var toUnlink = [];
if (tmpfiles) {
tmpfiles = [].concat(tmpfiles || []);
params.forEach(function(value, i) {
var fpath;
if (value === '--TMPFILE--') {
fpath = pathlib.join(tempDir, crypto.randomBytes(20).toString('hex'));
files.push({
path: fpath,
contents: tmpfiles.shift()
});
params[i] = fpath;
}
});
}
var processFiles = function() {
var file = files.shift();
if (!file) {
return spawnSSL();
}
fs.writeFile(file.path, file.contents, function() {
toUnlink.push(file.path);
processFiles();
});
};
var spawnSSL = function() {
spawnOpenSSL(params, function(err, code, stdout, stderr) {
toUnlink.forEach(function(filePath) {
fs.unlink(filePath);
});
callback(err, code, stdout, stderr);
});
};
processFiles();
}
/**
* Spawn an openssl command
*/
function execOpenSSL(params, searchStr, tmpfiles, callback) {
if (!callback && typeof tmpfiles === 'function') {
callback = tmpfiles;
tmpfiles = false;
}
spawnWrapper(params, tmpfiles, function(err, code, stdout, stderr) {
var start, end;
if (err) {
return callback(err);
}
if ((start = stdout.match(new RegExp('\\-+BEGIN ' + searchStr + '\\-+$', 'm')))) {
start = start.index;
} else {
start = -1;
}
if ((end = stdout.match(new RegExp('^\\-+END ' + searchStr + '\\-+', 'm')))) {
end = end.index + (end[0] || '').length;
} else {
end = -1;
}
if (start >= 0 && end >= 0) {
return callback(null, stdout.substring(start, end));
} else {
return callback(new Error(searchStr + ' not found from openssl output:\n---stdout---\n' + stdout + '\n---stderr---\n' + stderr + '\ncode: ' + code));
}
});
}
/**
* Validates the pathBin for the openssl command.
*
* @param {String} pathBin The path to OpenSSL Bin
* @param {Function} callback Callback function with an error object
*/
function testOpenSSLPath(pathBin, callback) {
which(pathBin, function(error) {
if (error) {
return callback(new Error('Could not find openssl on your system on this path: ' + pathBin));
}
callback();
});
} | rishigb/NodeProject_IOTstyle | socketIo/VideoLiveStreamSockets/node_modules/exprestify/node_modules/pem/lib/pem.js | JavaScript | mit | 24,288 |
/** @license React v16.3.0
* react-dom-test-utils.development.js
*
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
if (process.env.NODE_ENV !== "production") {
(function() {
'use strict';
var _assign = require('object-assign');
var React = require('react');
var ReactDOM = require('react-dom');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var emptyFunction = require('fbjs/lib/emptyFunction');
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
/**
* WARNING: DO NOT manually require this module.
* This is a replacement for `invariant(...)` used by the error code system
* and will _only_ be required by the corresponding babel pass.
* It always throws.
*/
/**
* `ReactInstanceMap` maintains a mapping from a public facing stateful
* instance (key) and the internal representation (value). This allows public
* methods to accept the user facing instance as an argument and map them back
* to internal methods.
*
* Note that this module is currently shared and assumed to be stateless.
* If this becomes an actual Map, that will break.
*/
/**
* This API should be called `delete` but we'd have to make sure to always
* transform these to strings for IE support. When this transform is fully
* supported we can rename it.
*/
function get(key) {
return key._reactInternalFiber;
}
var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
var ReactCurrentOwner = ReactInternals.ReactCurrentOwner;
var ReactDebugCurrentFrame = ReactInternals.ReactDebugCurrentFrame;
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
// Before we know whether it is functional or class
var FunctionalComponent = 1;
var ClassComponent = 2;
var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
// A subtree. Could be an entry point to a different renderer.
var HostComponent = 5;
var HostText = 6;
// Don't change these two values. They're used by React Dev Tools.
var NoEffect = /* */0;
// You can change the rest (and add more).
var Placement = /* */2;
// Union of all host effects
var MOUNTING = 1;
var MOUNTED = 2;
var UNMOUNTED = 3;
function isFiberMountedImpl(fiber) {
var node = fiber;
if (!fiber.alternate) {
// If there is no alternate, this might be a new tree that isn't inserted
// yet. If it is, then it will have a pending insertion effect on it.
if ((node.effectTag & Placement) !== NoEffect) {
return MOUNTING;
}
while (node['return']) {
node = node['return'];
if ((node.effectTag & Placement) !== NoEffect) {
return MOUNTING;
}
}
} else {
while (node['return']) {
node = node['return'];
}
}
if (node.tag === HostRoot) {
// TODO: Check if this was a nested HostRoot when used with
// renderContainerIntoSubtree.
return MOUNTED;
}
// If we didn't hit the root, that means that we're in an disconnected tree
// that has been unmounted.
return UNMOUNTED;
}
function assertIsMounted(fiber) {
!(isFiberMountedImpl(fiber) === MOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
}
function findCurrentFiberUsingSlowPath(fiber) {
var alternate = fiber.alternate;
if (!alternate) {
// If there is no alternate, then we only need to check if it is mounted.
var state = isFiberMountedImpl(fiber);
!(state !== UNMOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
if (state === MOUNTING) {
return null;
}
return fiber;
}
// If we have two possible branches, we'll walk backwards up to the root
// to see what path the root points to. On the way we may hit one of the
// special cases and we'll deal with them.
var a = fiber;
var b = alternate;
while (true) {
var parentA = a['return'];
var parentB = parentA ? parentA.alternate : null;
if (!parentA || !parentB) {
// We're at the root.
break;
}
// If both copies of the parent fiber point to the same child, we can
// assume that the child is current. This happens when we bailout on low
// priority: the bailed out fiber's child reuses the current child.
if (parentA.child === parentB.child) {
var child = parentA.child;
while (child) {
if (child === a) {
// We've determined that A is the current branch.
assertIsMounted(parentA);
return fiber;
}
if (child === b) {
// We've determined that B is the current branch.
assertIsMounted(parentA);
return alternate;
}
child = child.sibling;
}
// We should never have an alternate for any mounting node. So the only
// way this could possibly happen is if this was unmounted, if at all.
invariant(false, 'Unable to find node on an unmounted component.');
}
if (a['return'] !== b['return']) {
// The return pointer of A and the return pointer of B point to different
// fibers. We assume that return pointers never criss-cross, so A must
// belong to the child set of A.return, and B must belong to the child
// set of B.return.
a = parentA;
b = parentB;
} else {
// The return pointers point to the same fiber. We'll have to use the
// default, slow path: scan the child sets of each parent alternate to see
// which child belongs to which set.
//
// Search parent A's child set
var didFindChild = false;
var _child = parentA.child;
while (_child) {
if (_child === a) {
didFindChild = true;
a = parentA;
b = parentB;
break;
}
if (_child === b) {
didFindChild = true;
b = parentA;
a = parentB;
break;
}
_child = _child.sibling;
}
if (!didFindChild) {
// Search parent B's child set
_child = parentB.child;
while (_child) {
if (_child === a) {
didFindChild = true;
a = parentB;
b = parentA;
break;
}
if (_child === b) {
didFindChild = true;
b = parentB;
a = parentA;
break;
}
_child = _child.sibling;
}
!didFindChild ? invariant(false, 'Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.') : void 0;
}
}
!(a.alternate === b) ? invariant(false, 'Return fibers should always be each others\' alternates. This error is likely caused by a bug in React. Please file an issue.') : void 0;
}
// If the root is not a host container, we're in a disconnected tree. I.e.
// unmounted.
!(a.tag === HostRoot) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
if (a.stateNode.current === a) {
// We've determined that A is the current branch.
return fiber;
}
// Otherwise B has to be current branch.
return alternate;
}
/* eslint valid-typeof: 0 */
var didWarnForAddedNewProperty = false;
var EVENT_POOL_SIZE = 10;
var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances'];
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var EventInterface = {
type: null,
target: null,
// currentTarget is set when dispatching; no use in copying it here
currentTarget: emptyFunction.thatReturnsNull,
eventPhase: null,
bubbles: null,
cancelable: null,
timeStamp: function (event) {
return event.timeStamp || Date.now();
},
defaultPrevented: null,
isTrusted: null
};
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {*} targetInst Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @param {DOMEventTarget} nativeEventTarget Target node.
*/
function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
{
// these have a getter/setter for warnings
delete this.nativeEvent;
delete this.preventDefault;
delete this.stopPropagation;
}
this.dispatchConfig = dispatchConfig;
this._targetInst = targetInst;
this.nativeEvent = nativeEvent;
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (!Interface.hasOwnProperty(propName)) {
continue;
}
{
delete this[propName]; // this has a getter/setter for warnings
}
var normalize = Interface[propName];
if (normalize) {
this[propName] = normalize(nativeEvent);
} else {
if (propName === 'target') {
this.target = nativeEventTarget;
} else {
this[propName] = nativeEvent[propName];
}
}
}
var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
if (defaultPrevented) {
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
} else {
this.isDefaultPrevented = emptyFunction.thatReturnsFalse;
}
this.isPropagationStopped = emptyFunction.thatReturnsFalse;
return this;
}
_assign(SyntheticEvent.prototype, {
preventDefault: function () {
this.defaultPrevented = true;
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.preventDefault) {
event.preventDefault();
} else if (typeof event.returnValue !== 'unknown') {
event.returnValue = false;
}
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
},
stopPropagation: function () {
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.stopPropagation) {
event.stopPropagation();
} else if (typeof event.cancelBubble !== 'unknown') {
// The ChangeEventPlugin registers a "propertychange" event for
// IE. This event does not support bubbling or cancelling, and
// any references to cancelBubble throw "Member not found". A
// typeof check of "unknown" circumvents this issue (and is also
// IE specific).
event.cancelBubble = true;
}
this.isPropagationStopped = emptyFunction.thatReturnsTrue;
},
/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/
persist: function () {
this.isPersistent = emptyFunction.thatReturnsTrue;
},
/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/
isPersistent: emptyFunction.thatReturnsFalse,
/**
* `PooledClass` looks for `destructor` on each instance it releases.
*/
destructor: function () {
var Interface = this.constructor.Interface;
for (var propName in Interface) {
{
Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
}
}
for (var i = 0; i < shouldBeReleasedProperties.length; i++) {
this[shouldBeReleasedProperties[i]] = null;
}
{
Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction));
Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction));
}
}
});
SyntheticEvent.Interface = EventInterface;
/**
* Helper to reduce boilerplate when creating subclasses.
*/
SyntheticEvent.extend = function (Interface) {
var Super = this;
var E = function () {};
E.prototype = Super.prototype;
var prototype = new E();
function Class() {
return Super.apply(this, arguments);
}
_assign(prototype, Class.prototype);
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.Interface = _assign({}, Super.Interface, Interface);
Class.extend = Super.extend;
addEventPoolingTo(Class);
return Class;
};
/** Proxying after everything set on SyntheticEvent
* to resolve Proxy issue on some WebKit browsers
* in which some Event properties are set to undefined (GH#10010)
*/
{
var isProxySupported = typeof Proxy === 'function' &&
// https://github.com/facebook/react/issues/12011
!Object.isSealed(new Proxy({}, {}));
if (isProxySupported) {
/*eslint-disable no-func-assign */
SyntheticEvent = new Proxy(SyntheticEvent, {
construct: function (target, args) {
return this.apply(target, Object.create(target.prototype), args);
},
apply: function (constructor, that, args) {
return new Proxy(constructor.apply(that, args), {
set: function (target, prop, value) {
if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) {
warning(didWarnForAddedNewProperty || target.isPersistent(), "This synthetic event is reused for performance reasons. If you're " + "seeing this, you're adding a new property in the synthetic event object. " + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.');
didWarnForAddedNewProperty = true;
}
target[prop] = value;
return true;
}
});
}
});
/*eslint-enable no-func-assign */
}
}
addEventPoolingTo(SyntheticEvent);
/**
* Helper to nullify syntheticEvent instance properties when destructing
*
* @param {String} propName
* @param {?object} getVal
* @return {object} defineProperty object
*/
function getPooledWarningPropertyDefinition(propName, getVal) {
var isFunction = typeof getVal === 'function';
return {
configurable: true,
set: set,
get: get
};
function set(val) {
var action = isFunction ? 'setting the method' : 'setting the property';
warn(action, 'This is effectively a no-op');
return val;
}
function get() {
var action = isFunction ? 'accessing the method' : 'accessing the property';
var result = isFunction ? 'This is a no-op function' : 'This is set to null';
warn(action, result);
return getVal;
}
function warn(action, result) {
var warningCondition = false;
warning(warningCondition, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result);
}
}
function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
var EventConstructor = this;
if (EventConstructor.eventPool.length) {
var instance = EventConstructor.eventPool.pop();
EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
return instance;
}
return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
}
function releasePooledEvent(event) {
var EventConstructor = this;
!(event instanceof EventConstructor) ? invariant(false, 'Trying to release an event instance into a pool of a different type.') : void 0;
event.destructor();
if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
EventConstructor.eventPool.push(event);
}
}
function addEventPoolingTo(EventConstructor) {
EventConstructor.eventPool = [];
EventConstructor.getPooled = getPooledEvent;
EventConstructor.release = releasePooledEvent;
}
var SyntheticEvent$1 = SyntheticEvent;
/**
* Generate a mapping of standard vendor prefixes using the defined style property and event name.
*
* @param {string} styleProp
* @param {string} eventName
* @returns {object}
*/
function makePrefixMap(styleProp, eventName) {
var prefixes = {};
prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
prefixes['Webkit' + styleProp] = 'webkit' + eventName;
prefixes['Moz' + styleProp] = 'moz' + eventName;
prefixes['ms' + styleProp] = 'MS' + eventName;
prefixes['O' + styleProp] = 'o' + eventName.toLowerCase();
return prefixes;
}
/**
* A list of event names to a configurable list of vendor prefixes.
*/
var vendorPrefixes = {
animationend: makePrefixMap('Animation', 'AnimationEnd'),
animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
animationstart: makePrefixMap('Animation', 'AnimationStart'),
transitionend: makePrefixMap('Transition', 'TransitionEnd')
};
/**
* Event names that have already been detected and prefixed (if applicable).
*/
var prefixedEventNames = {};
/**
* Element to check for prefixes on.
*/
var style = {};
/**
* Bootstrap if a DOM exists.
*/
if (ExecutionEnvironment.canUseDOM) {
style = document.createElement('div').style;
// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are usable, and if not remove them from the map.
if (!('AnimationEvent' in window)) {
delete vendorPrefixes.animationend.animation;
delete vendorPrefixes.animationiteration.animation;
delete vendorPrefixes.animationstart.animation;
}
// Same as above
if (!('TransitionEvent' in window)) {
delete vendorPrefixes.transitionend.transition;
}
}
/**
* Attempts to determine the correct vendor prefixed event name.
*
* @param {string} eventName
* @returns {string}
*/
function getVendorPrefixedEventName(eventName) {
if (prefixedEventNames[eventName]) {
return prefixedEventNames[eventName];
} else if (!vendorPrefixes[eventName]) {
return eventName;
}
var prefixMap = vendorPrefixes[eventName];
for (var styleProp in prefixMap) {
if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
return prefixedEventNames[eventName] = prefixMap[styleProp];
}
}
return eventName;
}
/**
* Types of raw signals from the browser caught at the top level.
*
* For events like 'submit' or audio/video events which don't consistently
* bubble (which we trap at a lower node than `document`), binding
* at `document` would cause duplicate events so we don't include them here.
*/
var topLevelTypes = {
topAnimationEnd: getVendorPrefixedEventName('animationend'),
topAnimationIteration: getVendorPrefixedEventName('animationiteration'),
topAnimationStart: getVendorPrefixedEventName('animationstart'),
topBlur: 'blur',
topCancel: 'cancel',
topChange: 'change',
topClick: 'click',
topClose: 'close',
topCompositionEnd: 'compositionend',
topCompositionStart: 'compositionstart',
topCompositionUpdate: 'compositionupdate',
topContextMenu: 'contextmenu',
topCopy: 'copy',
topCut: 'cut',
topDoubleClick: 'dblclick',
topDrag: 'drag',
topDragEnd: 'dragend',
topDragEnter: 'dragenter',
topDragExit: 'dragexit',
topDragLeave: 'dragleave',
topDragOver: 'dragover',
topDragStart: 'dragstart',
topDrop: 'drop',
topFocus: 'focus',
topInput: 'input',
topKeyDown: 'keydown',
topKeyPress: 'keypress',
topKeyUp: 'keyup',
topLoad: 'load',
topLoadStart: 'loadstart',
topMouseDown: 'mousedown',
topMouseMove: 'mousemove',
topMouseOut: 'mouseout',
topMouseOver: 'mouseover',
topMouseUp: 'mouseup',
topPaste: 'paste',
topScroll: 'scroll',
topSelectionChange: 'selectionchange',
topTextInput: 'textInput',
topToggle: 'toggle',
topTouchCancel: 'touchcancel',
topTouchEnd: 'touchend',
topTouchMove: 'touchmove',
topTouchStart: 'touchstart',
topTransitionEnd: getVendorPrefixedEventName('transitionend'),
topWheel: 'wheel'
};
// There are so many media events, it makes sense to just
// maintain a list of them. Note these aren't technically
// "top-level" since they don't bubble. We should come up
// with a better naming convention if we come to refactoring
// the event system.
var mediaEventTypes = {
topAbort: 'abort',
topCanPlay: 'canplay',
topCanPlayThrough: 'canplaythrough',
topDurationChange: 'durationchange',
topEmptied: 'emptied',
topEncrypted: 'encrypted',
topEnded: 'ended',
topError: 'error',
topLoadedData: 'loadeddata',
topLoadedMetadata: 'loadedmetadata',
topLoadStart: 'loadstart',
topPause: 'pause',
topPlay: 'play',
topPlaying: 'playing',
topProgress: 'progress',
topRateChange: 'ratechange',
topSeeked: 'seeked',
topSeeking: 'seeking',
topStalled: 'stalled',
topSuspend: 'suspend',
topTimeUpdate: 'timeupdate',
topVolumeChange: 'volumechange',
topWaiting: 'waiting'
};
var findDOMNode = ReactDOM.findDOMNode;
var _ReactDOM$__SECRET_IN = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
var EventPluginHub = _ReactDOM$__SECRET_IN.EventPluginHub;
var EventPluginRegistry = _ReactDOM$__SECRET_IN.EventPluginRegistry;
var EventPropagators = _ReactDOM$__SECRET_IN.EventPropagators;
var ReactControlledComponent = _ReactDOM$__SECRET_IN.ReactControlledComponent;
var ReactDOMComponentTree = _ReactDOM$__SECRET_IN.ReactDOMComponentTree;
var ReactDOMEventListener = _ReactDOM$__SECRET_IN.ReactDOMEventListener;
function Event(suffix) {}
/**
* @class ReactTestUtils
*/
function findAllInRenderedFiberTreeInternal(fiber, test) {
if (!fiber) {
return [];
}
var currentParent = findCurrentFiberUsingSlowPath(fiber);
if (!currentParent) {
return [];
}
var node = currentParent;
var ret = [];
while (true) {
if (node.tag === HostComponent || node.tag === HostText || node.tag === ClassComponent || node.tag === FunctionalComponent) {
var publicInst = node.stateNode;
if (test(publicInst)) {
ret.push(publicInst);
}
}
if (node.child) {
node.child['return'] = node;
node = node.child;
continue;
}
if (node === currentParent) {
return ret;
}
while (!node.sibling) {
if (!node['return'] || node['return'] === currentParent) {
return ret;
}
node = node['return'];
}
node.sibling['return'] = node['return'];
node = node.sibling;
}
}
/**
* Utilities for making it easy to test React components.
*
* See https://reactjs.org/docs/test-utils.html
*
* Todo: Support the entire DOM.scry query syntax. For now, these simple
* utilities will suffice for testing purposes.
* @lends ReactTestUtils
*/
var ReactTestUtils = {
renderIntoDocument: function (element) {
var div = document.createElement('div');
// None of our tests actually require attaching the container to the
// DOM, and doing so creates a mess that we rely on test isolation to
// clean up, so we're going to stop honoring the name of this method
// (and probably rename it eventually) if no problems arise.
// document.documentElement.appendChild(div);
return ReactDOM.render(element, div);
},
isElement: function (element) {
return React.isValidElement(element);
},
isElementOfType: function (inst, convenienceConstructor) {
return React.isValidElement(inst) && inst.type === convenienceConstructor;
},
isDOMComponent: function (inst) {
return !!(inst && inst.nodeType === 1 && inst.tagName);
},
isDOMComponentElement: function (inst) {
return !!(inst && React.isValidElement(inst) && !!inst.tagName);
},
isCompositeComponent: function (inst) {
if (ReactTestUtils.isDOMComponent(inst)) {
// Accessing inst.setState warns; just return false as that'll be what
// this returns when we have DOM nodes as refs directly
return false;
}
return inst != null && typeof inst.render === 'function' && typeof inst.setState === 'function';
},
isCompositeComponentWithType: function (inst, type) {
if (!ReactTestUtils.isCompositeComponent(inst)) {
return false;
}
var internalInstance = get(inst);
var constructor = internalInstance.type;
return constructor === type;
},
findAllInRenderedTree: function (inst, test) {
if (!inst) {
return [];
}
!ReactTestUtils.isCompositeComponent(inst) ? invariant(false, 'findAllInRenderedTree(...): instance must be a composite component') : void 0;
var internalInstance = get(inst);
return findAllInRenderedFiberTreeInternal(internalInstance, test);
},
/**
* Finds all instance of components in the rendered tree that are DOM
* components with the class name matching `className`.
* @return {array} an array of all the matches.
*/
scryRenderedDOMComponentsWithClass: function (root, classNames) {
return ReactTestUtils.findAllInRenderedTree(root, function (inst) {
if (ReactTestUtils.isDOMComponent(inst)) {
var className = inst.className;
if (typeof className !== 'string') {
// SVG, probably.
className = inst.getAttribute('class') || '';
}
var classList = className.split(/\s+/);
if (!Array.isArray(classNames)) {
!(classNames !== undefined) ? invariant(false, 'TestUtils.scryRenderedDOMComponentsWithClass expects a className as a second argument.') : void 0;
classNames = classNames.split(/\s+/);
}
return classNames.every(function (name) {
return classList.indexOf(name) !== -1;
});
}
return false;
});
},
/**
* Like scryRenderedDOMComponentsWithClass but expects there to be one result,
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactDOMComponent} The one match.
*/
findRenderedDOMComponentWithClass: function (root, className) {
var all = ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className);
if (all.length !== 1) {
throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for class:' + className);
}
return all[0];
},
/**
* Finds all instance of components in the rendered tree that are DOM
* components with the tag name matching `tagName`.
* @return {array} an array of all the matches.
*/
scryRenderedDOMComponentsWithTag: function (root, tagName) {
return ReactTestUtils.findAllInRenderedTree(root, function (inst) {
return ReactTestUtils.isDOMComponent(inst) && inst.tagName.toUpperCase() === tagName.toUpperCase();
});
},
/**
* Like scryRenderedDOMComponentsWithTag but expects there to be one result,
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactDOMComponent} The one match.
*/
findRenderedDOMComponentWithTag: function (root, tagName) {
var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName);
if (all.length !== 1) {
throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for tag:' + tagName);
}
return all[0];
},
/**
* Finds all instances of components with type equal to `componentType`.
* @return {array} an array of all the matches.
*/
scryRenderedComponentsWithType: function (root, componentType) {
return ReactTestUtils.findAllInRenderedTree(root, function (inst) {
return ReactTestUtils.isCompositeComponentWithType(inst, componentType);
});
},
/**
* Same as `scryRenderedComponentsWithType` but expects there to be one result
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactComponent} The one match.
*/
findRenderedComponentWithType: function (root, componentType) {
var all = ReactTestUtils.scryRenderedComponentsWithType(root, componentType);
if (all.length !== 1) {
throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for componentType:' + componentType);
}
return all[0];
},
/**
* Pass a mocked component module to this method to augment it with
* useful methods that allow it to be used as a dummy React component.
* Instead of rendering as usual, the component will become a simple
* <div> containing any provided children.
*
* @param {object} module the mock function object exported from a
* module that defines the component to be mocked
* @param {?string} mockTagName optional dummy root tag name to return
* from render method (overrides
* module.mockTagName if provided)
* @return {object} the ReactTestUtils object (for chaining)
*/
mockComponent: function (module, mockTagName) {
mockTagName = mockTagName || module.mockTagName || 'div';
module.prototype.render.mockImplementation(function () {
return React.createElement(mockTagName, null, this.props.children);
});
return this;
},
/**
* Simulates a top level event being dispatched from a raw event that occurred
* on an `Element` node.
* @param {Object} topLevelType A type from `BrowserEventConstants.topLevelTypes`
* @param {!Element} node The dom to simulate an event occurring on.
* @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
*/
simulateNativeEventOnNode: function (topLevelType, node, fakeNativeEvent) {
fakeNativeEvent.target = node;
ReactDOMEventListener.dispatchEvent(topLevelType, fakeNativeEvent);
},
/**
* Simulates a top level event being dispatched from a raw event that occurred
* on the `ReactDOMComponent` `comp`.
* @param {Object} topLevelType A type from `BrowserEventConstants.topLevelTypes`.
* @param {!ReactDOMComponent} comp
* @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
*/
simulateNativeEventOnDOMComponent: function (topLevelType, comp, fakeNativeEvent) {
ReactTestUtils.simulateNativeEventOnNode(topLevelType, findDOMNode(comp), fakeNativeEvent);
},
nativeTouchData: function (x, y) {
return {
touches: [{ pageX: x, pageY: y }]
};
},
Simulate: null,
SimulateNative: {}
};
/**
* Exports:
*
* - `ReactTestUtils.Simulate.click(Element)`
* - `ReactTestUtils.Simulate.mouseMove(Element)`
* - `ReactTestUtils.Simulate.change(Element)`
* - ... (All keys from event plugin `eventTypes` objects)
*/
function makeSimulator(eventType) {
return function (domNode, eventData) {
!!React.isValidElement(domNode) ? invariant(false, 'TestUtils.Simulate expected a DOM node as the first argument but received a React element. Pass the DOM node you wish to simulate the event on instead. Note that TestUtils.Simulate will not work if you are using shallow rendering.') : void 0;
!!ReactTestUtils.isCompositeComponent(domNode) ? invariant(false, 'TestUtils.Simulate expected a DOM node as the first argument but received a component instance. Pass the DOM node you wish to simulate the event on instead.') : void 0;
var dispatchConfig = EventPluginRegistry.eventNameDispatchConfigs[eventType];
var fakeNativeEvent = new Event();
fakeNativeEvent.target = domNode;
fakeNativeEvent.type = eventType.toLowerCase();
// We don't use SyntheticEvent.getPooled in order to not have to worry about
// properly destroying any properties assigned from `eventData` upon release
var targetInst = ReactDOMComponentTree.getInstanceFromNode(domNode);
var event = new SyntheticEvent$1(dispatchConfig, targetInst, fakeNativeEvent, domNode);
// Since we aren't using pooling, always persist the event. This will make
// sure it's marked and won't warn when setting additional properties.
event.persist();
_assign(event, eventData);
if (dispatchConfig.phasedRegistrationNames) {
EventPropagators.accumulateTwoPhaseDispatches(event);
} else {
EventPropagators.accumulateDirectDispatches(event);
}
ReactDOM.unstable_batchedUpdates(function () {
// Normally extractEvent enqueues a state restore, but we'll just always
// do that since we we're by-passing it here.
ReactControlledComponent.enqueueStateRestore(domNode);
EventPluginHub.runEventsInBatch(event, true);
});
ReactControlledComponent.restoreStateIfNeeded();
};
}
function buildSimulators() {
ReactTestUtils.Simulate = {};
var eventType = void 0;
for (eventType in EventPluginRegistry.eventNameDispatchConfigs) {
/**
* @param {!Element|ReactDOMComponent} domComponentOrNode
* @param {?object} eventData Fake event data to use in SyntheticEvent.
*/
ReactTestUtils.Simulate[eventType] = makeSimulator(eventType);
}
}
// Rebuild ReactTestUtils.Simulate whenever event plugins are injected
var oldInjectEventPluginOrder = EventPluginHub.injection.injectEventPluginOrder;
EventPluginHub.injection.injectEventPluginOrder = function () {
oldInjectEventPluginOrder.apply(this, arguments);
buildSimulators();
};
var oldInjectEventPlugins = EventPluginHub.injection.injectEventPluginsByName;
EventPluginHub.injection.injectEventPluginsByName = function () {
oldInjectEventPlugins.apply(this, arguments);
buildSimulators();
};
buildSimulators();
/**
* Exports:
*
* - `ReactTestUtils.SimulateNative.click(Element/ReactDOMComponent)`
* - `ReactTestUtils.SimulateNative.mouseMove(Element/ReactDOMComponent)`
* - `ReactTestUtils.SimulateNative.mouseIn/ReactDOMComponent)`
* - `ReactTestUtils.SimulateNative.mouseOut(Element/ReactDOMComponent)`
* - ... (All keys from `BrowserEventConstants.topLevelTypes`)
*
* Note: Top level event types are a subset of the entire set of handler types
* (which include a broader set of "synthetic" events). For example, onDragDone
* is a synthetic event. Except when testing an event plugin or React's event
* handling code specifically, you probably want to use ReactTestUtils.Simulate
* to dispatch synthetic events.
*/
function makeNativeSimulator(eventType) {
return function (domComponentOrNode, nativeEventData) {
var fakeNativeEvent = new Event(eventType);
_assign(fakeNativeEvent, nativeEventData);
if (ReactTestUtils.isDOMComponent(domComponentOrNode)) {
ReactTestUtils.simulateNativeEventOnDOMComponent(eventType, domComponentOrNode, fakeNativeEvent);
} else if (domComponentOrNode.tagName) {
// Will allow on actual dom nodes.
ReactTestUtils.simulateNativeEventOnNode(eventType, domComponentOrNode, fakeNativeEvent);
}
};
}
var eventKeys = [].concat(Object.keys(topLevelTypes), Object.keys(mediaEventTypes));
eventKeys.forEach(function (eventType) {
// Event type is stored as 'topClick' - we transform that to 'click'
var convenienceName = eventType.indexOf('top') === 0 ? eventType.charAt(3).toLowerCase() + eventType.substr(4) : eventType;
/**
* @param {!Element|ReactDOMComponent} domComponentOrNode
* @param {?Event} nativeEventData Fake native event to use in SyntheticEvent.
*/
ReactTestUtils.SimulateNative[convenienceName] = makeNativeSimulator(eventType);
});
var ReactTestUtils$2 = Object.freeze({
default: ReactTestUtils
});
var ReactTestUtils$3 = ( ReactTestUtils$2 && ReactTestUtils ) || ReactTestUtils$2;
// TODO: decide on the top-level export form.
// This is hacky but makes it work with both Rollup and Jest.
var testUtils = ReactTestUtils$3['default'] ? ReactTestUtils$3['default'] : ReactTestUtils$3;
module.exports = testUtils;
})();
}
| ahocevar/cdnjs | ajax/libs/react-dom/16.3.0/cjs/react-dom-test-utils.development.js | JavaScript | mit | 36,533 |
// DOM elements
var $source;
var $photographer;
var $save;
var $textColor;
var $logo;
var $crop;
var $logoColor;
var $imageLoader;
var $imageLink;
var $imageLinkButton;
var $canvas;
var canvas;
var $qualityQuestions;
var $copyrightHolder;
var $dragHelp;
var $filename;
var $fileinput;
var $customFilename;
// Constants
var IS_MOBILE = Modernizr.touch && Modernizr.mq('screen and max-width(700px)');
var MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'];
// state
var scaledImageHeight;
var scaledImageWidth;
var previewScale = IS_MOBILE ? 0.32 : 0.64;
var dy = 0;
var dx = 0;
var image;
var imageFilename = 'image';
var currentCopyright;
var credit = 'Belal Khan/Flickr'
var shallowImage = false;
// JS objects
var ctx;
var img = new Image();
var logo = new Image();
var onDocumentLoad = function(e) {
$source = $('#source');
$photographer = $('#photographer');
$canvas = $('#imageCanvas');
canvas = $canvas[0];
$imageLoader = $('#imageLoader');
$imageLink = $('#imageLink');
$imageLinkButton = $('#imageLinkButton');
ctx = canvas.getContext('2d');
$save = $('.save-btn');
$textColor = $('input[name="textColor"]');
$crop = $('input[name="crop"]');
$logoColor = $('input[name="logoColor"]');
$qualityQuestions = $('.quality-question');
$copyrightHolder = $('.copyright-holder');
$dragHelp = $('.drag-help');
$filename = $('.fileinput-filename');
$fileinput = $('.fileinput');
$customFilename = $('.custom-filename');
$logosWrapper = $('.logos-wrapper');
img.src = defaultImage;
img.onload = onImageLoad;
logo.src = defaultLogo;
logo.onload = renderCanvas;
$photographer.on('keyup', renderCanvas);
$source.on('keyup', renderCanvas);
$imageLoader.on('change', handleImage);
$imageLinkButton.on('click', handleImageLink);
$save.on('click', onSaveClick);
$textColor.on('change', onTextColorChange);
$logoColor.on('change', onLogoColorChange);
$crop.on('change', onCropChange);
$canvas.on('mousedown touchstart', onDrag);
$copyrightHolder.on('change', onCopyrightChange);
$customFilename.on('click', function(e) {
e.stopPropagation();
})
$("body").on("contextmenu", "canvas", function(e) {
return false;
});
$imageLink.keypress(function(e) {
if (e.keyCode == 13) {
handleImageLink();
}
});
// $imageLink.on('paste', handleImageLink);
$(window).on('resize', resizeCanvas);
resizeCanvas();
buildForm();
}
var resizeCanvas = function() {
var scale = $('.canvas-cell').width() / canvasWidth;
$canvas.css({
'webkitTransform': 'scale(' + scale + ')',
'MozTransform': 'scale(' + scale + ')',
'msTransform': 'scale(' + scale + ')',
'OTransform': 'scale(' + scale + ')',
'transform': 'scale(' + scale + ')'
});
renderCanvas();
}
var buildForm = function() {
var copyrightKeys = Object.keys(copyrightOptions);
var logoKeys = Object.keys(logos);
for (var i = 0; i < copyrightKeys.length; i++) {
var key = copyrightKeys[i];
var display = copyrightOptions[key]['display'];
$copyrightHolder.append('<option value="' + key + '">' + display + '</option>');
}
if (logoKeys.length > 1) {
$logosWrapper.append('<div class="btn-group btn-group-justified btn-group-sm logos" data-toggle="buttons"></div>');
var $logos = $('.logos');
for (var j = 0; j < logoKeys.length; j++) {
var key = logoKeys[j];
var display = logos[key]['display']
$logos.append('<label class="btn btn-primary"><input type="radio" name="logo" id="' + key + '" value="' + key + '">' + display + '</label>');
disableLogo();
if (key === currentLogo) {
$('#' + key).attr('checked', true);
$('#' + key).parent('.btn').addClass('active');
}
}
$logo = $('input[name="logo"]');
$logo.on('change', onLogoChange);
} else {
$logosWrapper.hide();
}
}
/*
* Draw the image, then the logo, then the text
*/
var renderCanvas = function() {
// canvas is always the same width
canvas.width = canvasWidth;
// if we're cropping, use the aspect ratio for the height
if (currentCrop !== 'original') {
canvas.height = canvasWidth / (16/9);
}
// clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
// determine height of canvas and scaled image, then draw the image
var imageAspect = img.width / img.height;
if (currentCrop === 'original') {
canvas.height = canvasWidth / imageAspect;
scaledImageHeight = canvas.height;
ctx.drawImage(
img,
0,
0,
canvasWidth,
scaledImageHeight
);
} else {
if (img.width / img.height > canvas.width / canvas.height) {
shallowImage = true;
scaledImageHeight = canvasWidth / imageAspect;
scaledImageWidth = canvas.height * (img.width / img.height)
ctx.drawImage(
img,
0,
0,
img.width,
img.height,
dx,
dy,
scaledImageWidth,
canvas.height
);
} else {
shallowImage = false;
scaledImageHeight = canvasWidth / imageAspect;
ctx.drawImage(
img,
0,
0,
img.width,
img.height,
dx,
dy,
canvasWidth,
scaledImageHeight
);
}
}
// set alpha channel, draw the logo
if (currentLogoColor === 'white') {
ctx.globalAlpha = whiteLogoAlpha;
} else {
ctx.globalAlpha = blackLogoAlpha;
}
ctx.drawImage(
logo,
elementPadding,
currentLogo === 'npr'? elementPadding : elementPadding - 14,
logos[currentLogo]['w'],
logos[currentLogo]['h']
);
// reset alpha channel so text is not translucent
ctx.globalAlpha = "1";
// draw the text
ctx.textBaseline = 'bottom';
ctx.textAlign = 'left';
ctx.fillStyle = currentTextColor;
ctx.font = fontWeight + ' ' + fontSize + ' ' + fontFace;
if (currentTextColor === 'white') {
ctx.shadowColor = fontShadow;
ctx.shadowOffsetX = fontShadowOffsetX;
ctx.shadowOffsetY = fontShadowOffsetY;
ctx.shadowBlur = fontShadowBlur;
}
if (currentCopyright) {
credit = buildCreditString();
}
var creditWidth = ctx.measureText(credit);
ctx.fillText(
credit,
canvas.width - (creditWidth.width + elementPadding),
canvas.height - elementPadding
);
validateForm();
}
/*
* Build the proper format for the credit based on current copyright
*/
var buildCreditString = function() {
var creditString;
var val = $copyrightHolder.val();
if ($photographer.val() !== '') {
if (copyrightOptions[val]['source']) {
creditString = $photographer.val() + '/' + copyrightOptions[val]['source'];
} else {
creditString = $photographer.val() + '/' + $source.val();
}
} else {
if (copyrightOptions[val]['source']) {
creditString = copyrightOptions[val]['source'];
} else {
creditString = $source.val();
}
}
if (copyrightOptions[val]['photographerRequired']) {
if ($photographer.val() !== '') {
$photographer.parents('.form-group').removeClass('has-warning');
} else {
$photographer.parents('.form-group').addClass('has-warning');
}
}
if (copyrightOptions[val]['sourceRequired']) {
if ($source.val() !== '') {
$source.parents('.form-group').removeClass('has-warning');
} else {
$source.parents('.form-group').addClass('has-warning');
}
}
return creditString;
}
/*
* Check to see if any required fields have not been
* filled out before enabling saving
*/
var validateForm = function() {
if ($('.has-warning').length === 0 && currentCopyright) {
$save.removeAttr('disabled');
$("body").off("contextmenu", "canvas");
} else {
$save.attr('disabled', '');
$("body").on("contextmenu", "canvas", function(e) {
return false;
});
}
}
/*
* Handle dragging the image for crops when applicable
*/
var onDrag = function(e) {
e.preventDefault();
var originY = e.clientY||e.originalEvent.targetTouches[0].clientY;
originY = originY/previewScale;
var originX = e.clientX||e.originalEvent.targetTouches[0].clientX;
originX = originX/previewScale;
var startY = dy;
var startX = dx;
if (currentCrop === 'original') {
return;
}
function update(e) {
var dragY = e.clientY||e.originalEvent.targetTouches[0].clientY;
dragY = dragY/previewScale;
var dragX = e.clientX||e.originalEvent.targetTouches[0].clientX;
dragX = dragX/previewScale;
if (shallowImage === false) {
if (Math.abs(dragY - originY) > 1) {
dy = startY - (originY - dragY);
// Prevent dragging image below upper bound
if (dy > 0) {
dy = 0;
return;
}
// Prevent dragging image above lower bound
if (dy < canvas.height - scaledImageHeight) {
dy = canvas.height - scaledImageHeight;
return;
}
renderCanvas();
}
} else {
if (Math.abs(dragX - originX) > 1) {
dx = startX - (originX - dragX);
// Prevent dragging image below left bound
if (dx > 0) {
dx = 0;
return;
}
// Prevent dragging image above right bound
if (dx < canvas.width - scaledImageWidth) {
dx = canvas.width - scaledImageWidth;
return;
}
renderCanvas();
}
}
}
// Perform drag sequence:
$(document).on('mousemove.drag touchmove', _.debounce(update, 5, true))
.on('mouseup.drag touchend', function(e) {
$(document).off('mouseup.drag touchmove mousemove.drag');
update(e);
});
}
/*
* Take an image from file input and load it
*/
var handleImage = function(e) {
var reader = new FileReader();
reader.onload = function(e){
// reset dy value
dy = 0;
dx = 0;
image = e.target.result;
imageFilename = $('.fileinput-filename').text().split('.')[0];
img.src = image;
$customFilename.text(imageFilename);
$customFilename.parents('.form-group').addClass('has-file');
$imageLink.val('');
$imageLink.parents('.form-group').removeClass('has-file');
}
reader.readAsDataURL(e.target.files[0]);
}
/*
* Load a remote image
*/
var handleImageLink = function(e) {
var requestStatus =
// Test if image URL returns a 200
$.ajax({
url: $imageLink.val(),
success: function(data, status, xhr) {
var responseType = xhr.getResponseHeader('content-type').toLowerCase();
// if content type is jpeg, gif or png, load the image into the canvas
if (MIME_TYPES.indexOf(responseType) >= 0) {
// reset dy value
dy = 0;
dx = 0;
$fileinput.fileinput('clear');
$imageLink.parents('.form-group').addClass('has-file').removeClass('has-error');
$imageLink.parents('.input-group').next().text('Click to edit name');
img.src = $imageLink.val();
img.crossOrigin = "anonymous"
var filename = $imageLink.val().split('/');
imageFilename = filename[filename.length - 1].split('.')[0];
$imageLink.val(imageFilename);
// otherwise, display an error
} else {
$imageLink.parents('.form-group').addClass('has-error');
$imageLink.parents('.input-group').next().text('Not a valid image URL');
return;
}
},
error: function(data) {
$imageLink.parents('.form-group').addClass('has-error');
$imageLink.parents('.input-group').next().text('Not a valid image URL');
}
});
}
/*
* Set dragging status based on image aspect ratio and render canvas
*/
var onImageLoad = function(e) {
renderCanvas();
onCropChange();
}
/*
* Load the logo based on radio buttons
*/
var loadLogo = function() {
if (currentLogoColor === 'white') {
logo.src = logos[currentLogo]['whitePath'];
} else {
logo.src = logos[currentLogo]['blackPath'];
}
disableLogo();
}
/*
* If image paths not defined for the logo, grey it out
*/
var disableLogo = function(){
var whiteLogo = logos[currentLogo]['whitePath']
var blackLogo = logos[currentLogo]['blackPath']
if(typeof(whiteLogo) == "undefined"){
$("#whiteLogo").parent().addClass("disabled")
}else{
$("#whiteLogo").parent().removeClass("disabled")
}
if(typeof(blackLogo) == "undefined"){
$("#blackLogo").parent().addClass("disabled")
}else{
$("#blackLogo").parent().removeClass("disabled")
}
}
/*
* Download the image on save click
*/
var onSaveClick = function(e) {
e.preventDefault();
/// create an "off-screen" anchor tag
var link = document.createElement('a'),
e;
/// the key here is to set the download attribute of the a tag
if ($customFilename.text()) {
imageFilename = $customFilename.text();
}
if ($imageLink.val() !== "") {
var filename = $imageLink.val().split('/');
imageFilename = filename[filename.length - 1].split('.')[0];
}
link.download = 'waterbug-' + imageFilename + '.png';
/// convert canvas content to data-uri for link. When download
/// attribute is set the content pointed to by link will be
/// pushed as "download" in HTML5 capable browsers
link.href = canvas.toDataURL();
link.target = "_blank";
/// create a "fake" click-event to trigger the download
if (document.createEvent) {
e = document.createEvent("MouseEvents");
e.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false,
false, 0, null);
link.dispatchEvent(e);
} else if (link.fireEvent) {
link.fireEvent("onclick");
}
}
/*
* Handle logo radio button clicks
*/
var onLogoColorChange = function(e) {
currentLogoColor = $(this).val();
loadLogo();
renderCanvas();
}
/*
* Handle text color radio button clicks
*/
var onTextColorChange = function(e) {
currentTextColor = $(this).val();
renderCanvas();
}
/*
* Handle logo radio button clicks
*/
var onLogoChange = function(e) {
currentLogo = $(this).val();
loadLogo();
renderCanvas();
}
/*
* Handle crop radio button clicks
*/
var onCropChange = function() {
currentCrop = $crop.filter(':checked').val();
if (currentCrop !== 'original') {
var dragClass = shallowImage ? 'is-draggable shallow' : 'is-draggable';
$canvas.addClass(dragClass);
$dragHelp.show();
} else {
$canvas.removeClass('is-draggable shallow');
$dragHelp.hide();
}
renderCanvas();
}
/*
* Show the appropriate fields based on the chosen copyright
*/
var onCopyrightChange = function() {
currentCopyright = $copyrightHolder.val();
$photographer.parents('.form-group').removeClass('has-warning');
$source.parents('.form-group').removeClass('has-warning');
if (copyrightOptions[currentCopyright]) {
if (copyrightOptions[currentCopyright]['showPhotographer']) {
$photographer.parents('.form-group').slideDown();
if (copyrightOptions[currentCopyright]['photographerRequired']) {
$photographer.parents('.form-group').addClass('has-warning required');
} else {
$photographer.parents('.form-group').removeClass('required')
}
} else {
$photographer.parents('.form-group').slideUp();
}
if (copyrightOptions[currentCopyright]['showSource']) {
$source.parents('.form-group').slideDown();
if (copyrightOptions[currentCopyright]['sourceRequired']) {
$source.parents('.form-group').addClass('has-warning required');
} else {
$source.parents('.form-group').removeClass('required')
}
} else {
$source.parents('.form-group').slideUp();
}
} else {
$photographer.parents('.form-group').slideUp();
$source.parents('.form-group').slideUp();
credit = '';
}
// if (currentCopyright === 'npr') {
// $photographer.parents('.form-group').removeClass('required').slideDown();
// $source.parents('.form-group').slideUp();
// } else if (currentCopyright === 'freelance') {
// $photographer.parents('.form-group').slideDown();
// $source.parents('.form-group').slideUp();
// $photographer.parents('.form-group').addClass('has-warning required');
// } else if (currentCopyright === 'ap' || currentCopyright === 'getty') {
// $photographer.parents('.form-group').removeClass('required').slideDown();
// $source.parents('.form-group')
// .slideUp()
// .removeClass('has-warning required');
// } else if (currentCopyright === 'third-party') {
// $photographer.parents('.form-group').removeClass('required').slideDown();
// $source.parents('.form-group').slideDown();
// $source.parents('.form-group').addClass('has-warning required');
// } else {
// credit = '';
// $photographer.parents('.form-group').slideUp();
// $source.parents('.form-group')
// .slideUp()
// .parents('.form-group').removeClass('has-warning required');
// }
renderCanvas();
}
$(onDocumentLoad);
| mcclatchy/lunchbox | www/js/waterbug.js | JavaScript | mit | 18,520 |
/**
* @license @product.name@ JS [email protected]@ (@product.date@)
*
* Money Flow Index indicator for Highstock
*
* (c) 2010-2019 Grzegorz Blachliński
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../indicators/mfi.src.js';
| blue-eyed-devil/testCMS | externals/highcharts/es-modules/masters/indicators/mfi.src.js | JavaScript | gpl-3.0 | 258 |
//>>built
define("dgrid/extensions/nls/zh-cn/columnHider",{popupLabel:"\u663e\u793a\u6216\u9690\u85cf\u5217"}); | aconyteds/Esri-Ozone-Map-Widget | vendor/js/esri/arcgis_js_api/library/3.12/3.12compact/dgrid/extensions/nls/zh-cn/columnHider.js | JavaScript | apache-2.0 | 111 |
/**
* Copyright 2017 The AMP HTML 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.
*/
import {
LayoutRectDef,
layoutRectFromDomRect,
layoutRectLtwh,
} from '../../src/layout-rect';
import {
centerFrameUnderVsyncMutate,
collapseFrameUnderVsyncMutate,
expandFrameUnderVsyncMutate,
} from '../../src/full-overlay-frame-helper';
import {restrictedVsync, timer} from './util';
const CENTER_TRANSITION_TIME_MS = 500;
const CENTER_TRANSITION_END_WAIT_TIME_MS = 200;
/**
* Places the child frame in full overlay mode.
* @param {!Window} win Host window.
* @param {!HTMLIFrameElement} iframe
* @param {function(!LayoutRectDef, !LayoutRectDef)} onFinish
* @private
*/
const expandFrameImpl = function(win, iframe, onFinish) {
restrictedVsync(win, {
measure(state) {
state.viewportSize = {
width: win./*OK*/innerWidth,
height: win./*OK*/innerHeight,
};
state.rect = iframe./*OK*/getBoundingClientRect();
},
mutate(state) {
const collapsedRect = layoutRectFromDomRect(state.rect);
const expandedRect = layoutRectLtwh(
0, 0, state.viewportSize.width, state.viewportSize.height);
centerFrameUnderVsyncMutate(iframe, state.rect, state.viewportSize,
CENTER_TRANSITION_TIME_MS);
timer(() => {
restrictedVsync(win, {
mutate() {
expandFrameUnderVsyncMutate(iframe);
onFinish(collapsedRect, expandedRect);
},
});
}, CENTER_TRANSITION_TIME_MS + CENTER_TRANSITION_END_WAIT_TIME_MS);
},
}, {});
};
/**
* Resets the frame from full overlay mode.
* @param {!Window} win Host window.
* @param {!HTMLIFrameElement} iframe
* @param {function()} onFinish
* @param {function(!LayoutRectDef)} onMeasure
* @private
*/
const collapseFrameImpl = function(win, iframe, onFinish, onMeasure) {
restrictedVsync(win, {
mutate() {
collapseFrameUnderVsyncMutate(iframe);
onFinish();
// remeasure so client knows about updated dimensions
restrictedVsync(win, {
measure() {
onMeasure(
layoutRectFromDomRect(iframe./*OK*/getBoundingClientRect()));
},
});
},
});
};
/**
* Places the child frame in full overlay mode.
* @param {!Window} win Host window.
* @param {!HTMLIFrameElement} iframe
* @param {function(!LayoutRectDef, !LayoutRectDef)} onFinish
*/
export let expandFrame = expandFrameImpl;
/**
* @param {!Function} implFn
* @visibleForTesting
*/
export function stubExpandFrameForTesting(implFn) {
expandFrame = implFn;
}
/**
* @visibleForTesting
*/
export function resetExpandFrameForTesting() {
expandFrame = expandFrameImpl;
}
/**
* Places the child frame in full overlay mode.
* @param {!Window} win Host window.
* @param {!HTMLIFrameElement} iframe
* @param {function()} onFinish
* @param {function(!LayoutRectDef)} onMeasure
*/
export let collapseFrame = collapseFrameImpl;
/**
* @param {!Function} implFn
* @visibleForTesting
*/
export function stubCollapseFrameForTesting(implFn) {
collapseFrame = implFn;
}
/**
* @visibleForTesting
*/
export function resetCollapseFrameForTesting() {
collapseFrame = collapseFrameImpl;
}
| donttrustthisbot/amphtml | ads/inabox/frame-overlay-helper.js | JavaScript | apache-2.0 | 3,755 |
/**
* Sticky Notes
*
* An open source lightweight pastebin application
*
* @package StickyNotes
* @author Sayak Banerjee
* @copyright (c) 2014 Sayak Banerjee <[email protected]>. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php
* @link http://sayakbanerjee.com/sticky-notes
* @since Version 1.0
* @filesource
*/
/**
* Stores the current URL
*
* @var string
*/
var currentUrl = $(location).attr('href');
/**
* Timer container
*
* @var array
*/
var timers = new Array();
/**
* Instance counter
*
* @var int
*/
var instance = 0;
/**
* This is the main entry point of the script
*
* @return void
*/
function initMain()
{
// Initialize a new instance
initInstance();
// Initialize AJAX components
initAjaxComponents();
// Initialize AJAX navigation
initAjaxNavigation();
// Initialize addons
initAddons();
}
/**
* This initializes all JS addons
*
* @return void
*/
function initAddons()
{
// Initialize code wrapping
initWrapToggle();
// Initialize the code editor
initEditor();
// Initialize tab persistence
initTabPersistence();
// Initialize line reference
initLineReference();
// Initialize bootstrap components
initBootstrap();
}
/**
* Initializes a new instance of the JS library
*
* @return void
*/
function initInstance()
{
// Clear all timers
if (timers[instance] !== undefined)
{
for (idx in timers[instance])
{
clearInterval(timers[instance][idx]);
}
}
// Create a new instance and timer container
instance++;
timers[instance] = new Array();
}
/**
* Starts a new timed operation
*
* @param operation
* @param callback
* @param interval
* @return void
*/
function initTimer(operation, callback, interval)
{
switch (operation)
{
case 'once':
setTimeout(callback, interval);
break;
case 'repeat':
timers[instance].push(setInterval(callback, interval));
break;
}
}
/**
* Scans for and processes AJAX components
*
* Each AJAX component can have 4 parameters:
* - realtime : Indicates if the component involves realtime data
* - onload : The AJAX request will be triggered automatically
* - component : The utility component to request
* - extra : Any extra data that will be sent to the server
*
* @return void
*/
function initAjaxComponents()
{
var count = 1;
// Setup AJAX requests
$('[data-toggle="ajax"]').each(function()
{
var id = 'stickynotes-' + count++;
var onload = $(this).attr('data-onload') === 'true';
var realtime = $(this).attr('data-realtime') === 'true';
var component = $(this).attr('data-component');
var extra = $(this).attr('data-extra');
// Set the id of this element
$(this).attr('data-id', id);
// AJAX URL and component must be defined
if (ajaxUrl !== undefined && component !== undefined)
{
var getUrl = ajaxUrl + '/' + component + (extra !== undefined ? '/' + extra : '');
var callback = function(e)
{
// Add the loading icon
$(this).html('<span class="glyphicon glyphicon-refresh"></span>');
// Send the AJAX request
$.ajax({
url: getUrl,
data: { key: Math.random(), ajax: 1 },
context: $('[data-id="' + id + '"]'),
success: function(response)
{
// Dump the HTML in the element
$(this).html(response);
// If response is link, set it as href as well
if (response.indexOf('http') === 0)
{
$(this).attr('href', response);
$(this).removeAttr('data-toggle');
$(this).off('click');
}
// Load addons again
initAddons();
}
});
if (e !== undefined)
{
e.preventDefault();
}
};
// Execute the AJAX callback
if (onload)
{
if (realtime)
{
initTimer('repeat', callback, 5000);
}
initTimer('once', callback, 0);
}
else
{
$(this).off('click').on('click', callback);
}
}
});
}
/**
* Enabled AJAX navigation across the site
*
* @return void
*/
function initAjaxNavigation()
{
if (ajaxNav !== undefined && ajaxNav && $.support.cors)
{
// AJAX callback
var callback = function(e)
{
var navMethod = $(this).prop('tagName') == 'A' ? 'GET' : 'POST';
var seek = $(this).attr('data-seek');
// Set up data based on method
switch (navMethod)
{
case 'GET':
navUrl = $(this).attr('href');
payload = 'ajax=1';
break;
case 'POST':
navUrl = $(this).attr('action');
payload = $(this).serialize() + '&ajax=1';
break;
}
// Send an AJAX request for all but anchor links
if (navUrl !== undefined && !$('.loader').is(':visible'))
{
$('.loader').show();
$.ajax({
url: navUrl,
method: navMethod,
context: $('body'),
data: payload,
success: function(response, status, info)
{
var isPageSection = response.indexOf('<!DOCTYPE html>') == -1;
var isHtmlContent = info.getResponseHeader('Content-Type').indexOf('text/html') != -1;
// Change the page URL
currentUrl = info.getResponseHeader('StickyNotes-Url');
window.history.pushState({ html: response }, null, currentUrl);
// Handle the response
if (isPageSection && isHtmlContent)
{
$(this).html(response);
}
else if (isHtmlContent)
{
dom = $(document.createElement('html'));
dom[0].innerHTML = response;
$(this).html(dom.find('body').html());
}
else
{
window.location = navUrl;
}
// Seek to top of the page
$.scrollTo(0, 200);
// Load JS triggers again
initMain();
},
error: function()
{
window.location = navUrl;
}
});
e.preventDefault();
}
};
// Execute callback on all links, excluding some
$('body').find('a' +
':not([href*="/admin"])' +
':not([href*="/attachment"])' +
':not([href*="#"])' +
':not([href*="mailto:"])' +
':not([onclick])'
).off('click').on('click', callback);
// Execute callback on all designated forms
$('body').find('form[data-navigate="ajax"]').off('submit').on('submit', callback);
// URL change monitor
initTimer('repeat', function()
{
var href = $(location).attr('href');
// Trim the trailing slash from currentUrl
if (currentUrl.substr(-1) == '/')
{
currentUrl = currentUrl.substr(0, currentUrl.length - 1);
}
// Trim the trailing slash from href
if (href.substr(-1) == '/')
{
href = href.substr(0, href.length - 1);
}
// Reload page if URL changed
if (currentUrl != href && href.indexOf('#') == -1)
{
currentUrl = href;
// Load the selected page
$('.loader').show();
$.get(href, function(response)
{
dom = $(document.createElement('html'));
dom[0].innerHTML = response;
$('body').html(dom.find('body').html());
});
}
}, 300);
}
}
/**
* Activates the code wrapping toggle function
*
* @return void
*/
function initWrapToggle()
{
$('[data-toggle="wrap"]').off('click').on('click', function(e)
{
var isWrapped = $('.pre div').css('white-space') != 'nowrap';
var newValue = isWrapped ? 'nowrap' : 'inherit';
$('.pre div').css('white-space', newValue);
e.preventDefault();
});
}
/**
* Activates the paste editor
*
* @return void
*/
function initEditor()
{
// Insert tab in the code box
$('[name="data"]').off('keydown').on('keydown', function (e)
{
if (e.keyCode == 9)
{
var myValue = "\t";
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
e.preventDefault();
}
});
// Tick the private checkbox if password is entered
$('[name="password"]').off('keyup').on('keyup', function()
{
$('[name="private"]').attr('checked', $(this).val().length > 0);
});
}
/**
* Activates some bootstrap components
*
* @return void
*/
function initBootstrap()
{
// Activate tooltips
$('[data-toggle="tooltip"]').tooltip();
}
/**
* Saves the tab state on all pages
*
* @return void
*/
function initTabPersistence()
{
// Restore the previous tab state
$('.nav-tabs').each(function()
{
var id = $(this).attr('id');
var index = $.cookie('stickynotes_tabstate');
if (index !== undefined)
{
$('.nav-tabs > li:eq(' + index + ') a').tab('show');
}
});
// Save the current tab state
$('.nav-tabs > li > a').on('shown.bs.tab', function (e)
{
var id = $(this).parents('.nav-tabs').attr('id');
var index = $(this).parents('li').index();
$.cookie('stickynotes_tabstate', index);
})
// Clear tab state when navigated to a different page
if ($('.nav-tabs').length == 0)
{
$.cookie('stickynotes_tabstate', null);
}
}
/**
* Highlights lines upon clicking them on the #show page
*
* @return void
*/
function initLineReference()
{
if ($('section#show').length != 0)
{
var line = 1;
// First, we allocate unique IDs to all lines
$('.pre li').each(function()
{
$(this).attr('id', 'line-' + line++);
});
// Next, navigate to an ID if the user requested it
var anchor = window.location.hash;
if (anchor.length > 0)
{
var top = $(anchor).offset().top;
// Scroll to the anchor
$.scrollTo(top, 200);
// Highlight the anchor
$(anchor).addClass('highlight');
}
// Click to change anchor
$('.pre li').off('mouseup').on('mouseup', function()
{
if (window.getSelection() == '')
{
var id = $(this).attr('id');
var top = $(this).offset().top;
// Scroll to the anchor
$.scrollTo(top, 200, function() {
window.location.hash = '#' + id;
});
// Highlight the anchor
$('.pre li').removeClass('highlight');
$(this).addClass('highlight');
}
});
}
}
/**
* Draws a Google chart in a container
*
* @return void
*/
function initAreaChart()
{
if (chartData !== undefined && chartContainer !== undefined)
{
// Create an instance of line chart
var chart = new google.visualization.AreaChart(chartContainer);
// Define chart options
var options = {
colors: [ '#428bca', '#d9534f' ],
areaOpacity: 0.1,
lineWidth: 4,
pointSize: 8,
hAxis: {
textStyle: {
color: '#666'
},
gridlines: {
color: 'transparent'
},
baselineColor: '#eeeeee',
format:'MMM d'
},
vAxis: {
textStyle: {
color: '#666'
},
gridlines: {
color: '#eee'
}
},
chartArea: {
left: 50,
top: 10,
width: '100%',
height: 210
},
legend: {
position: 'bottom'
}
};
// Draw the line chart
chart.draw(chartData, options);
}
// Redraw chart on window resize
$(window).off('resize').on('resize', initAreaChart);
}
/**
* Invoke the entry point on DOM ready
*/
$(initMain);
| solitaryr/sticky-notes | public/assets/pbr/js/stickynotes.js | JavaScript | bsd-2-clause | 10,960 |
description("This tests that page scaling does not affect mouse event pageX and pageY coordinates.");
var html = document.documentElement;
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.backgroundColor = "blue";
var eventLog = "";
function appendEventLog() {
var msg = event.type + "(" + event.pageX + ", " + event.pageY + ")";
if (window.eventSender) {
eventLog += msg;
} else {
debug(msg);
}
}
function clearEventLog() {
eventLog = "";
}
div.addEventListener("click", appendEventLog, false);
document.body.insertBefore(div, document.body.firstChild);
function sendEvents(button) {
if (!window.eventSender) {
debug("This test requires DumpRenderTree. Click on the blue rect with the left mouse button to log the mouse coordinates.")
return;
}
eventSender.mouseDown(button);
eventSender.mouseUp(button);
}
function testEvents(button, description, expectedString) {
sendEvents(button);
debug(description);
shouldBeEqualToString("eventLog", expectedString);
debug("");
clearEventLog();
}
if (window.eventSender) {
eventSender.mouseMoveTo(10, 10);
// We are clicking in the same position on screen. As we scale or transform the page,
// we expect the pageX and pageY event coordinates to change because different
// parts of the document are under the mouse.
testEvents(0, "Unscaled", "click(10, 10)");
window.eventSender.setPageScaleFactorLimits(0.5, 0.5);
window.eventSender.setPageScaleFactor(0.5, 0, 0);
testEvents(0, "setPageScale(0.5)", "click(20, 20)");
}
| modulexcite/blink | LayoutTests/fast/events/script-tests/page-scaled-mouse-click.js | JavaScript | bsd-3-clause | 1,651 |
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var React;
describe('ReactES6Class', function() {
var container;
var Inner;
var attachedListener = null;
var renderedName = null;
beforeEach(function() {
React = require('React');
container = document.createElement('div');
attachedListener = null;
renderedName = null;
Inner = class extends React.Component {
getName() {
return this.props.name;
}
render() {
attachedListener = this.props.onClick;
renderedName = this.props.name;
return <div className={this.props.name} />;
}
};
});
function test(element, expectedTag, expectedClassName) {
var instance = React.render(element, container);
expect(container.firstChild).not.toBeNull();
expect(container.firstChild.tagName).toBe(expectedTag);
expect(container.firstChild.className).toBe(expectedClassName);
return instance;
}
it('preserves the name of the class for use in error messages', function() {
class Foo extends React.Component { }
expect(Foo.name).toBe('Foo');
});
it('throws if no render function is defined', function() {
class Foo extends React.Component { }
expect(() => React.render(<Foo />, container)).toThrow();
});
it('renders a simple stateless component with prop', function() {
class Foo {
render() {
return <Inner name={this.props.bar} />;
}
}
test(<Foo bar="foo" />, 'DIV', 'foo');
test(<Foo bar="bar" />, 'DIV', 'bar');
});
it('renders based on state using initial values in this.props', function() {
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = {bar: this.props.initialValue};
}
render() {
return <span className={this.state.bar} />;
}
}
test(<Foo initialValue="foo" />, 'SPAN', 'foo');
});
it('renders based on state using props in the constructor', function() {
class Foo extends React.Component {
constructor(props) {
this.state = {bar: props.initialValue};
}
changeState() {
this.setState({bar: 'bar'});
}
render() {
if (this.state.bar === 'foo') {
return <div className="foo" />;
}
return <span className={this.state.bar} />;
}
}
var instance = test(<Foo initialValue="foo" />, 'DIV', 'foo');
instance.changeState();
test(<Foo />, 'SPAN', 'bar');
});
it('renders based on context in the constructor', function() {
class Foo extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {tag: context.tag, className: this.context.className};
}
render() {
var Tag = this.state.tag;
return <Tag className={this.state.className} />;
}
}
Foo.contextTypes = {
tag: React.PropTypes.string,
className: React.PropTypes.string
};
class Outer extends React.Component {
getChildContext() {
return {tag: 'span', className: 'foo'};
}
render() {
return <Foo />;
}
}
Outer.childContextTypes = {
tag: React.PropTypes.string,
className: React.PropTypes.string
};
test(<Outer />, 'SPAN', 'foo');
});
it('renders only once when setting state in componentWillMount', function() {
var renderCount = 0;
class Foo extends React.Component {
constructor(props) {
this.state = {bar: props.initialValue};
}
componentWillMount() {
this.setState({bar: 'bar'});
}
render() {
renderCount++;
return <span className={this.state.bar} />;
}
}
test(<Foo initialValue="foo" />, 'SPAN', 'bar');
expect(renderCount).toBe(1);
});
it('should throw with non-object in the initial state property', function() {
[['an array'], 'a string', 1234].forEach(function(state) {
class Foo {
constructor() {
this.state = state;
}
render() {
return <span />;
}
}
expect(() => test(<Foo />, 'span', '')).toThrow(
'Invariant Violation: Foo.state: ' +
'must be set to an object or null'
);
});
});
it('should render with null in the initial state property', function() {
class Foo extends React.Component {
constructor() {
this.state = null;
}
render() {
return <span />;
}
}
test(<Foo />, 'SPAN', '');
});
it('setState through an event handler', function() {
class Foo extends React.Component {
constructor(props) {
this.state = {bar: props.initialValue};
}
handleClick() {
this.setState({bar: 'bar'});
}
render() {
return (
<Inner
name={this.state.bar}
onClick={this.handleClick.bind(this)}
/>
);
}
}
test(<Foo initialValue="foo" />, 'DIV', 'foo');
attachedListener();
expect(renderedName).toBe('bar');
});
it('should not implicitly bind event handlers', function() {
class Foo extends React.Component {
constructor(props) {
this.state = {bar: props.initialValue};
}
handleClick() {
this.setState({bar: 'bar'});
}
render() {
return (
<Inner
name={this.state.bar}
onClick={this.handleClick}
/>
);
}
}
test(<Foo initialValue="foo" />, 'DIV', 'foo');
expect(attachedListener).toThrow();
});
it('renders using forceUpdate even when there is no state', function() {
class Foo extends React.Component {
constructor(props) {
this.mutativeValue = props.initialValue;
}
handleClick() {
this.mutativeValue = 'bar';
this.forceUpdate();
}
render() {
return (
<Inner
name={this.mutativeValue}
onClick={this.handleClick.bind(this)}
/>
);
}
}
test(<Foo initialValue="foo" />, 'DIV', 'foo');
attachedListener();
expect(renderedName).toBe('bar');
});
it('will call all the normal life cycle methods', function() {
var lifeCycles = [];
class Foo {
constructor() {
this.state = {};
}
componentWillMount() {
lifeCycles.push('will-mount');
}
componentDidMount() {
lifeCycles.push('did-mount');
}
componentWillReceiveProps(nextProps) {
lifeCycles.push('receive-props', nextProps);
}
shouldComponentUpdate(nextProps, nextState) {
lifeCycles.push('should-update', nextProps, nextState);
return true;
}
componentWillUpdate(nextProps, nextState) {
lifeCycles.push('will-update', nextProps, nextState);
}
componentDidUpdate(prevProps, prevState) {
lifeCycles.push('did-update', prevProps, prevState);
}
componentWillUnmount() {
lifeCycles.push('will-unmount');
}
render() {
return <span className={this.props.value} />;
}
}
test(<Foo value="foo" />, 'SPAN', 'foo');
expect(lifeCycles).toEqual([
'will-mount',
'did-mount'
]);
lifeCycles = []; // reset
test(<Foo value="bar" />, 'SPAN', 'bar');
expect(lifeCycles).toEqual([
'receive-props', {value: 'bar'},
'should-update', {value: 'bar'}, {},
'will-update', {value: 'bar'}, {},
'did-update', {value: 'foo'}, {}
]);
lifeCycles = []; // reset
React.unmountComponentAtNode(container);
expect(lifeCycles).toEqual([
'will-unmount'
]);
});
it('warns when classic properties are defined on the instance, ' +
'but does not invoke them.', function() {
spyOn(console, 'error');
var getInitialStateWasCalled = false;
class Foo extends React.Component {
constructor() {
this.contextTypes = {};
this.propTypes = {};
}
getInitialState() {
getInitialStateWasCalled = true;
return {};
}
render() {
return <span className="foo" />;
}
}
test(<Foo />, 'SPAN', 'foo');
expect(getInitialStateWasCalled).toBe(false);
expect(console.error.calls.length).toBe(3);
expect(console.error.calls[0].args[0]).toContain(
'getInitialState was defined on Foo, a plain JavaScript class.'
);
expect(console.error.calls[1].args[0]).toContain(
'propTypes was defined as an instance property on Foo.'
);
expect(console.error.calls[2].args[0]).toContain(
'contextTypes was defined as an instance property on Foo.'
);
});
it('should warn when mispelling shouldComponentUpdate', function() {
spyOn(console, 'error');
class NamedComponent {
componentShouldUpdate() {
return false;
}
render() {
return <span className="foo" />;
}
}
test(<NamedComponent />, 'SPAN', 'foo');
expect(console.error.calls.length).toBe(1);
expect(console.error.calls[0].args[0]).toBe(
'Warning: ' +
'NamedComponent has a method called componentShouldUpdate(). Did you ' +
'mean shouldComponentUpdate()? The name is phrased as a question ' +
'because the function is expected to return a value.'
);
});
it('should throw AND warn when trying to access classic APIs', function() {
spyOn(console, 'error');
var instance = test(<Inner name="foo" />, 'DIV', 'foo');
expect(() => instance.getDOMNode()).toThrow();
expect(() => instance.replaceState({})).toThrow();
expect(() => instance.isMounted()).toThrow();
expect(() => instance.setProps({name: 'bar'})).toThrow();
expect(() => instance.replaceProps({name: 'bar'})).toThrow();
expect(console.error.calls.length).toBe(5);
expect(console.error.calls[0].args[0]).toContain(
'getDOMNode(...) is deprecated in plain JavaScript React classes'
);
expect(console.error.calls[1].args[0]).toContain(
'replaceState(...) is deprecated in plain JavaScript React classes'
);
expect(console.error.calls[2].args[0]).toContain(
'isMounted(...) is deprecated in plain JavaScript React classes'
);
expect(console.error.calls[3].args[0]).toContain(
'setProps(...) is deprecated in plain JavaScript React classes'
);
expect(console.error.calls[4].args[0]).toContain(
'replaceProps(...) is deprecated in plain JavaScript React classes'
);
});
it('supports this.context passed via getChildContext', function() {
class Bar {
render() {
return <div className={this.context.bar} />;
}
}
Bar.contextTypes = {bar: React.PropTypes.string};
class Foo {
getChildContext() {
return {bar: 'bar-through-context'};
}
render() {
return <Bar />;
}
}
Foo.childContextTypes = {bar: React.PropTypes.string};
test(<Foo />, 'DIV', 'bar-through-context');
});
it('supports classic refs', function() {
class Foo {
render() {
return <Inner name="foo" ref="inner" />;
}
}
var instance = test(<Foo />, 'DIV', 'foo');
expect(instance.refs.inner.getName()).toBe('foo');
});
it('supports drilling through to the DOM using findDOMNode', function() {
var instance = test(<Inner name="foo" />, 'DIV', 'foo');
var node = React.findDOMNode(instance);
expect(node).toBe(container.firstChild);
});
});
| AlexJeng/react | src/modern/class/__tests__/ReactES6Class-test.js | JavaScript | bsd-3-clause | 11,780 |
// Generated by CoffeeScript 1.3.3
(function() {
define(["smog/server", "smog/notify", "templates/connect"], function(server, notify, templ) {
return {
show: function() {
$('#content').html(templ());
$('#connect-modal').modal({
backdrop: false
});
return $('#connect-button').click(function() {
var host;
host = $('#host').val();
return server.connect(host, function(err, okay) {
if (err != null) {
if (typeof err === 'object' && Object.keys(err).length === 0) {
err = "Server unavailable";
}
return notify.error("Connection error: " + (err.err || err));
} else {
$('#connect-modal').modal('hide');
return window.location.hash = '#/home';
}
});
});
}
};
});
}).call(this);
| wearefractal/smog | public/js/routes/index.js | JavaScript | mit | 911 |
/**
* Creates a new instance of Emitter.
* @class
* @returns {Object} Returns a new instance of Emitter.
* @example
* // Creates a new instance of Emitter.
* var Emitter = require('emitter');
*
* var emitter = new Emitter();
*/
class Emitter {
/**
* Adds a listener to the collection for the specified event.
* @memberof! Emitter.prototype
* @function
* @param {String} event - The event name.
* @param {Function} listener - A listener function to add.
* @returns {Object} Returns an instance of Emitter.
* @example
* // Add an event listener to "foo" event.
* emitter.on('foo', listener);
*/
on(event, listener) {
// Use the current collection or create it.
this._eventCollection = this._eventCollection || {};
// Use the current collection of an event or create it.
this._eventCollection[event] = this._eventCollection[event] || [];
// Appends the listener into the collection of the given event
this._eventCollection[event].push(listener);
return this;
}
/**
* Adds a listener to the collection for the specified event that will be called only once.
* @memberof! Emitter.prototype
* @function
* @param {String} event - The event name.
* @param {Function} listener - A listener function to add.
* @returns {Object} Returns an instance of Emitter.
* @example
* // Will add an event handler to "foo" event once.
* emitter.once('foo', listener);
*/
once(event, listener) {
const self = this;
function fn() {
self.off(event, fn);
listener.apply(this, arguments);
}
fn.listener = listener;
this.on(event, fn);
return this;
}
/**
* Removes a listener from the collection for the specified event.
* @memberof! Emitter.prototype
* @function
* @param {String} event - The event name.
* @param {Function} listener - A listener function to remove.
* @returns {Object} Returns an instance of Emitter.
* @example
* // Remove a given listener.
* emitter.off('foo', listener);
*/
off(event, listener) {
let listeners;
// Defines listeners value.
if (!this._eventCollection || !(listeners = this._eventCollection[event])) {
return this;
}
listeners.forEach((fn, i) => {
if (fn === listener || fn.listener === listener) {
// Removes the given listener.
listeners.splice(i, 1);
}
});
// Removes an empty event collection.
if (listeners.length === 0) {
delete this._eventCollection[event];
}
return this;
}
/**
* Execute each item in the listener collection in order with the specified data.
* @memberof! Emitter.prototype
* @function
* @param {String} event - The name of the event you want to emit.
* @param {...Object} data - Data to pass to the listeners.
* @returns {Object} Returns an instance of Emitter.
* @example
* // Emits the "foo" event with 'param1' and 'param2' as arguments.
* emitter.emit('foo', 'param1', 'param2');
*/
emit(event, ...args) {
let listeners;
// Defines listeners value.
if (!this._eventCollection || !(listeners = this._eventCollection[event])) {
return this;
}
// Clone listeners
listeners = listeners.slice(0);
listeners.forEach(fn => fn.apply(this, args));
return this;
}
}
/**
* Exports Emitter
*/
export default Emitter;
| sinfin/folio | vendor/assets/bower_components/emitter-es6/src/index.js | JavaScript | mit | 3,401 |
var expect = require('expect.js'),
defaultOpts = require('..').prototype.options,
_ = require('lodash'),
parse = require('../lib/parse'),
render = require('../lib/render');
var html = function(str, options) {
options = _.defaults(options || {}, defaultOpts);
var dom = parse(str, options);
return render(dom);
};
var xml = function(str, options) {
options = _.defaults(options || {}, defaultOpts);
options.xmlMode = true;
var dom = parse(str, options);
return render(dom, options);
};
describe('render', function() {
describe('(html)', function() {
it('should render <br /> tags correctly', function() {
var str = '<br />';
expect(html(str)).to.equal('<br>');
});
it('should handle double quotes within single quoted attributes properly', function() {
var str = '<hr class=\'an "edge" case\' />';
expect(html(str)).to.equal('<hr class="an "edge" case">');
});
it('should retain encoded HTML content within attributes', function() {
var str = '<hr class="cheerio & node = happy parsing" />';
expect(html(str)).to.equal('<hr class="cheerio & node = happy parsing">');
});
it('should shorten the "checked" attribute when it contains the value "checked"', function() {
var str = '<input checked/>';
expect(html(str)).to.equal('<input checked>');
});
it('should not shorten the "name" attribute when it contains the value "name"', function() {
var str = '<input name="name"/>';
expect(html(str)).to.equal('<input name="name">');
});
it('should render comments correctly', function() {
var str = '<!-- comment -->';
expect(html(str)).to.equal('<!-- comment -->');
});
it('should render whitespace by default', function() {
var str = '<a href="./haha.html">hi</a> <a href="./blah.html">blah</a>';
expect(html(str)).to.equal(str);
});
it('should normalize whitespace if specified', function() {
var str = '<a href="./haha.html">hi</a> <a href="./blah.html">blah </a>';
expect(html(str, { normalizeWhitespace: true })).to.equal('<a href="./haha.html">hi</a> <a href="./blah.html">blah </a>');
});
it('should preserve multiple hyphens in data attributes', function() {
var str = '<div data-foo-bar-baz="value"></div>';
expect(html(str)).to.equal('<div data-foo-bar-baz="value"></div>');
});
it('should render CDATA correctly', function() {
var str = '<a> <b> <![CDATA[ asdf&asdf ]]> <c/> <![CDATA[ asdf&asdf ]]> </b> </a>';
expect(xml(str)).to.equal(str);
});
});
});
| JHand93/WebPerformanceTestSuite | webpagetest-charts-api/node_modules/cheerio/test/render.js | JavaScript | mit | 2,628 |
"use strict";
var path = require('canonical-path');
var packagePath = __dirname;
var Package = require('dgeni').Package;
// Create and export a new Dgeni package called angularjs. This package depends upon
// the ngdoc, nunjucks, and examples packages defined in the dgeni-packages npm module.
module.exports = new Package('angularjs', [
require('dgeni-packages/ngdoc'),
require('dgeni-packages/nunjucks'),
require('dgeni-packages/examples'),
require('dgeni-packages/git')
])
.factory(require('./services/errorNamespaceMap'))
.factory(require('./services/getMinerrInfo'))
.factory(require('./services/getVersion'))
.factory(require('./services/deployments/debug'))
.factory(require('./services/deployments/default'))
.factory(require('./services/deployments/jquery'))
.factory(require('./services/deployments/production'))
.factory(require('./inline-tag-defs/type'))
.processor(require('./processors/error-docs'))
.processor(require('./processors/index-page'))
.processor(require('./processors/keywords'))
.processor(require('./processors/pages-data'))
.processor(require('./processors/versions-data'))
.config(function(dgeni, log, readFilesProcessor, writeFilesProcessor) {
dgeni.stopOnValidationError = true;
dgeni.stopOnProcessingError = true;
log.level = 'info';
readFilesProcessor.basePath = path.resolve(__dirname,'../..');
readFilesProcessor.sourceFiles = [
{ include: 'src/**/*.js', exclude: 'src/angular.bind.js', basePath: 'src' },
{ include: 'docs/content/**/*.ngdoc', basePath: 'docs/content' }
];
writeFilesProcessor.outputFolder = 'build/docs';
})
.config(function(parseTagsProcessor) {
parseTagsProcessor.tagDefinitions.push(require('./tag-defs/tutorial-step'));
parseTagsProcessor.tagDefinitions.push(require('./tag-defs/sortOrder'));
})
.config(function(inlineTagProcessor, typeInlineTagDef) {
inlineTagProcessor.inlineTagDefinitions.push(typeInlineTagDef);
})
.config(function(templateFinder, renderDocsProcessor, gitData) {
templateFinder.templateFolders.unshift(path.resolve(packagePath, 'templates'));
renderDocsProcessor.extraData.git = gitData;
})
.config(function(computePathsProcessor, computeIdsProcessor) {
computePathsProcessor.pathTemplates.push({
docTypes: ['error'],
pathTemplate: 'error/${namespace}/${name}',
outputPathTemplate: 'partials/error/${namespace}/${name}.html'
});
computePathsProcessor.pathTemplates.push({
docTypes: ['errorNamespace'],
pathTemplate: 'error/${name}',
outputPathTemplate: 'partials/error/${name}.html'
});
computePathsProcessor.pathTemplates.push({
docTypes: ['overview', 'tutorial'],
getPath: function(doc) {
var docPath = path.dirname(doc.fileInfo.relativePath);
if ( doc.fileInfo.baseName !== 'index' ) {
docPath = path.join(docPath, doc.fileInfo.baseName);
}
return docPath;
},
outputPathTemplate: 'partials/${path}.html'
});
computePathsProcessor.pathTemplates.push({
docTypes: ['e2e-test'],
getPath: function() {},
outputPathTemplate: 'ptore2e/${example.id}/${deployment.name}_test.js'
});
computePathsProcessor.pathTemplates.push({
docTypes: ['indexPage'],
pathTemplate: '.',
outputPathTemplate: '${id}.html'
});
computePathsProcessor.pathTemplates.push({
docTypes: ['module' ],
pathTemplate: '${area}/${name}',
outputPathTemplate: 'partials/${area}/${name}.html'
});
computePathsProcessor.pathTemplates.push({
docTypes: ['componentGroup' ],
pathTemplate: '${area}/${moduleName}/${groupType}',
outputPathTemplate: 'partials/${area}/${moduleName}/${groupType}.html'
});
computeIdsProcessor.idTemplates.push({
docTypes: ['overview', 'tutorial', 'e2e-test', 'indexPage'],
getId: function(doc) { return doc.fileInfo.baseName; },
getAliases: function(doc) { return [doc.id]; }
});
computeIdsProcessor.idTemplates.push({
docTypes: ['error'],
getId: function(doc) { return 'error:' + doc.namespace + ':' + doc.name; },
getAliases: function(doc) { return [doc.name, doc.namespace + ':' + doc.name, doc.id]; }
},
{
docTypes: ['errorNamespace'],
getId: function(doc) { return 'error:' + doc.name; },
getAliases: function(doc) { return [doc.id]; }
}
);
})
.config(function(checkAnchorLinksProcessor) {
checkAnchorLinksProcessor.base = '/';
// We are only interested in docs that have an area (i.e. they are pages)
checkAnchorLinksProcessor.checkDoc = function(doc) { return doc.area; };
})
.config(function(
generateIndexPagesProcessor,
generateProtractorTestsProcessor,
generateExamplesProcessor,
debugDeployment, defaultDeployment,
jqueryDeployment, productionDeployment) {
generateIndexPagesProcessor.deployments = [
debugDeployment,
defaultDeployment,
jqueryDeployment,
productionDeployment
];
generateProtractorTestsProcessor.deployments = [
defaultDeployment,
jqueryDeployment
];
generateProtractorTestsProcessor.basePath = 'build/docs/';
generateExamplesProcessor.deployments = [
debugDeployment,
defaultDeployment,
jqueryDeployment,
productionDeployment
];
})
.config(function(generateKeywordsProcessor) {
generateKeywordsProcessor.docTypesToIgnore = ['componentGroup'];
});
| JonFerrera/angular.js | docs/config/index.js | JavaScript | mit | 5,289 |
var debug = require('debug')('keystone:core:openDatabaseConnection');
module.exports = function openDatabaseConnection (callback) {
var keystone = this;
var mongoConnectionOpen = false;
// support replica sets for mongoose
if (keystone.get('mongo replica set')) {
if (keystone.get('logger')) {
console.log('\nWarning: using the `mongo replica set` option has been deprecated and will be removed in'
+ ' a future version.\nInstead set the `mongo` connection string with your host details, e.g.'
+ ' mongodb://username:password@host:port,host:port,host:port/database and set any replica set options'
+ ' in `mongo options`.\n\nRefer to https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html'
+ ' for more details on the connection settings.');
}
debug('setting up mongo replica set');
var replicaData = keystone.get('mongo replica set');
var replica = '';
var credentials = (replicaData.username && replicaData.password) ? replicaData.username + ':' + replicaData.password + '@' : '';
replicaData.db.servers.forEach(function (server) {
replica += 'mongodb://' + credentials + server.host + ':' + server.port + '/' + replicaData.db.name + ',';
});
var options = {
auth: { authSource: replicaData.authSource },
replset: {
rs_name: replicaData.db.replicaSetOptions.rs_name,
readPreference: replicaData.db.replicaSetOptions.readPreference,
},
};
debug('connecting to replicate set');
keystone.mongoose.connect(replica, options);
} else {
debug('connecting to mongo');
keystone.mongoose.connect(keystone.get('mongo'), keystone.get('mongo options'));
}
keystone.mongoose.connection.on('error', function (err) {
if (keystone.get('logger')) {
console.log('------------------------------------------------');
console.log('Mongo Error:\n');
console.log(err);
}
if (mongoConnectionOpen) {
if (err.name === 'ValidationError') return;
throw err;
} else {
throw new Error('KeystoneJS (' + keystone.get('name') + ') failed to start - Check that you are running `mongod` in a separate process.');
}
}).on('open', function () {
debug('mongo connection open');
mongoConnectionOpen = true;
var connected = function () {
if (keystone.get('auto update')) {
debug('applying auto update');
keystone.applyUpdates(callback);
} else {
callback();
}
};
if (keystone.sessionStorePromise) {
keystone.sessionStorePromise.then(connected);
} else {
connected();
}
});
return this;
};
| andreufirefly/keystone | lib/core/openDatabaseConnection.js | JavaScript | mit | 2,539 |
// Zepto.js
// (c) 2010-2015 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
var Zepto = (function() {
var undefined, key, $, classList, emptyArray = [], concat = emptyArray.concat, filter = emptyArray.filter, slice = emptyArray.slice,
document = window.document,
elementDisplay = {}, classCache = {},
cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 },
fragmentRE = /^\s*<(\w+|!)[^>]*>/,
singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rootNodeRE = /^(?:body|html)$/i,
capitalRE = /([A-Z])/g,
// special attributes that should be get/set via method calls
methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],
adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ],
table = document.createElement('table'),
tableRow = document.createElement('tr'),
containers = {
'tr': document.createElement('tbody'),
'tbody': table, 'thead': table, 'tfoot': table,
'td': tableRow, 'th': tableRow,
'*': document.createElement('div')
},
readyRE = /complete|loaded|interactive/,
simpleSelectorRE = /^[\w-]*$/,
class2type = {},
toString = class2type.toString,
zepto = {},
camelize, uniq,
tempParent = document.createElement('div'),
propMap = {
'tabindex': 'tabIndex',
'readonly': 'readOnly',
'for': 'htmlFor',
'class': 'className',
'maxlength': 'maxLength',
'cellspacing': 'cellSpacing',
'cellpadding': 'cellPadding',
'rowspan': 'rowSpan',
'colspan': 'colSpan',
'usemap': 'useMap',
'frameborder': 'frameBorder',
'contenteditable': 'contentEditable'
},
isArray = Array.isArray ||
function(object){ return object instanceof Array }
zepto.matches = function(element, selector) {
if (!selector || !element || element.nodeType !== 1) return false
var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||
element.oMatchesSelector || element.matchesSelector
if (matchesSelector) return matchesSelector.call(element, selector)
// fall back to performing a selector:
var match, parent = element.parentNode, temp = !parent
if (temp) (parent = tempParent).appendChild(element)
match = ~zepto.qsa(parent, selector).indexOf(element)
temp && tempParent.removeChild(element)
return match
}
function type(obj) {
return obj == null ? String(obj) :
class2type[toString.call(obj)] || "object"
}
function isFunction(value) { return type(value) == "function" }
function isWindow(obj) { return obj != null && obj == obj.window }
function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }
function isObject(obj) { return type(obj) == "object" }
function isPlainObject(obj) {
return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
}
function likeArray(obj) { return typeof obj.length == 'number' }
function compact(array) { return filter.call(array, function(item){ return item != null }) }
function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array }
camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
function dasherize(str) {
return str.replace(/::/g, '/')
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
.replace(/_/g, '-')
.toLowerCase()
}
uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) }
function classRE(name) {
return name in classCache ?
classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)'))
}
function maybeAddPx(name, value) {
return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value
}
function defaultDisplay(nodeName) {
var element, display
if (!elementDisplay[nodeName]) {
element = document.createElement(nodeName)
document.body.appendChild(element)
display = getComputedStyle(element, '').getPropertyValue("display")
element.parentNode.removeChild(element)
display == "none" && (display = "block")
elementDisplay[nodeName] = display
}
return elementDisplay[nodeName]
}
function children(element) {
return 'children' in element ?
slice.call(element.children) :
$.map(element.childNodes, function(node){ if (node.nodeType == 1) return node })
}
function Z(dom, selector) {
var i, len = dom ? dom.length : 0
for (i = 0; i < len; i++) this[i] = dom[i]
this.length = len
this.selector = selector || ''
}
// `$.zepto.fragment` takes a html string and an optional tag name
// to generate DOM nodes nodes from the given html string.
// The generated DOM nodes are returned as an array.
// This function can be overriden in plugins for example to make
// it compatible with browsers that don't support the DOM fully.
zepto.fragment = function(html, name, properties) {
var dom, nodes, container
// A special case optimization for a single tag
if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1))
if (!dom) {
if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")
if (name === undefined) name = fragmentRE.test(html) && RegExp.$1
if (!(name in containers)) name = '*'
container = containers[name]
container.innerHTML = '' + html
dom = $.each(slice.call(container.childNodes), function(){
container.removeChild(this)
})
}
if (isPlainObject(properties)) {
nodes = $(dom)
$.each(properties, function(key, value) {
if (methodAttributes.indexOf(key) > -1) nodes[key](value)
else nodes.attr(key, value)
})
}
return dom
}
// `$.zepto.Z` swaps out the prototype of the given `dom` array
// of nodes with `$.fn` and thus supplying all the Zepto functions
// to the array. This method can be overriden in plugins.
zepto.Z = function(dom, selector) {
return new Z(dom, selector)
}
// `$.zepto.isZ` should return `true` if the given object is a Zepto
// collection. This method can be overriden in plugins.
zepto.isZ = function(object) {
return object instanceof zepto.Z
}
// `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and
// takes a CSS selector and an optional context (and handles various
// special cases).
// This method can be overriden in plugins.
zepto.init = function(selector, context) {
var dom
// If nothing given, return an empty Zepto collection
if (!selector) return zepto.Z()
// Optimize for string selectors
else if (typeof selector == 'string') {
selector = selector.trim()
// If it's a html fragment, create nodes from it
// Note: In both Chrome 21 and Firefox 15, DOM error 12
// is thrown if the fragment doesn't begin with <
if (selector[0] == '<' && fragmentRE.test(selector))
dom = zepto.fragment(selector, RegExp.$1, context), selector = null
// If there's a context, create a collection on that context first, and select
// nodes from there
else if (context !== undefined) return $(context).find(selector)
// If it's a CSS selector, use it to select nodes.
else dom = zepto.qsa(document, selector)
}
// If a function is given, call it when the DOM is ready
else if (isFunction(selector)) return $(document).ready(selector)
// If a Zepto collection is given, just return it
else if (zepto.isZ(selector)) return selector
else {
// normalize array if an array of nodes is given
if (isArray(selector)) dom = compact(selector)
// Wrap DOM nodes.
else if (isObject(selector))
dom = [selector], selector = null
// If it's a html fragment, create nodes from it
else if (fragmentRE.test(selector))
dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null
// If there's a context, create a collection on that context first, and select
// nodes from there
else if (context !== undefined) return $(context).find(selector)
// And last but no least, if it's a CSS selector, use it to select nodes.
else dom = zepto.qsa(document, selector)
}
// create a new Zepto collection from the nodes found
return zepto.Z(dom, selector)
}
// `$` will be the base `Zepto` object. When calling this
// function just call `$.zepto.init, which makes the implementation
// details of selecting nodes and creating Zepto collections
// patchable in plugins.
$ = function(selector, context){
return zepto.init(selector, context)
}
function extend(target, source, deep) {
for (key in source)
if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
if (isPlainObject(source[key]) && !isPlainObject(target[key]))
target[key] = {}
if (isArray(source[key]) && !isArray(target[key]))
target[key] = []
extend(target[key], source[key], deep)
}
else if (source[key] !== undefined) target[key] = source[key]
}
// Copy all but undefined properties from one or more
// objects to the `target` object.
$.extend = function(target){
var deep, args = slice.call(arguments, 1)
if (typeof target == 'boolean') {
deep = target
target = args.shift()
}
args.forEach(function(arg){ extend(target, arg, deep) })
return target
}
// `$.zepto.qsa` is Zepto's CSS selector implementation which
// uses `document.querySelectorAll` and optimizes for some special cases, like `#id`.
// This method can be overriden in plugins.
zepto.qsa = function(element, selector){
var found,
maybeID = selector[0] == '#',
maybeClass = !maybeID && selector[0] == '.',
nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked
isSimple = simpleSelectorRE.test(nameOnly)
return (element.getElementById && isSimple && maybeID) ? // Safari DocumentFragment doesn't have getElementById
( (found = element.getElementById(nameOnly)) ? [found] : [] ) :
(element.nodeType !== 1 && element.nodeType !== 9 && element.nodeType !== 11) ? [] :
slice.call(
isSimple && !maybeID && element.getElementsByClassName ? // DocumentFragment doesn't have getElementsByClassName/TagName
maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class
element.getElementsByTagName(selector) : // Or a tag
element.querySelectorAll(selector) // Or it's not simple, and we need to query all
)
}
function filtered(nodes, selector) {
return selector == null ? $(nodes) : $(nodes).filter(selector)
}
$.contains = document.documentElement.contains ?
function(parent, node) {
return parent !== node && parent.contains(node)
} :
function(parent, node) {
while (node && (node = node.parentNode))
if (node === parent) return true
return false
}
function funcArg(context, arg, idx, payload) {
return isFunction(arg) ? arg.call(context, idx, payload) : arg
}
function setAttribute(node, name, value) {
value == null ? node.removeAttribute(name) : node.setAttribute(name, value)
}
// access className property while respecting SVGAnimatedString
function className(node, value){
var klass = node.className || '',
svg = klass && klass.baseVal !== undefined
if (value === undefined) return svg ? klass.baseVal : klass
svg ? (klass.baseVal = value) : (node.className = value)
}
// "true" => true
// "false" => false
// "null" => null
// "42" => 42
// "42.5" => 42.5
// "08" => "08"
// JSON => parse if valid
// String => self
function deserializeValue(value) {
try {
return value ?
value == "true" ||
( value == "false" ? false :
value == "null" ? null :
+value + "" == value ? +value :
/^[\[\{]/.test(value) ? $.parseJSON(value) :
value )
: value
} catch(e) {
return value
}
}
$.type = type
$.isFunction = isFunction
$.isWindow = isWindow
$.isArray = isArray
$.isPlainObject = isPlainObject
$.isEmptyObject = function(obj) {
var name
for (name in obj) return false
return true
}
$.inArray = function(elem, array, i){
return emptyArray.indexOf.call(array, elem, i)
}
$.camelCase = camelize
$.trim = function(str) {
return str == null ? "" : String.prototype.trim.call(str)
}
// plugin compatibility
$.uuid = 0
$.support = { }
$.expr = { }
$.noop = function() {}
$.map = function(elements, callback){
var value, values = [], i, key
if (likeArray(elements))
for (i = 0; i < elements.length; i++) {
value = callback(elements[i], i)
if (value != null) values.push(value)
}
else
for (key in elements) {
value = callback(elements[key], key)
if (value != null) values.push(value)
}
return flatten(values)
}
$.each = function(elements, callback){
var i, key
if (likeArray(elements)) {
for (i = 0; i < elements.length; i++)
if (callback.call(elements[i], i, elements[i]) === false) return elements
} else {
for (key in elements)
if (callback.call(elements[key], key, elements[key]) === false) return elements
}
return elements
}
$.grep = function(elements, callback){
return filter.call(elements, callback)
}
if (window.JSON) $.parseJSON = JSON.parse
// Populate the class2type map
$.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase()
})
// Define methods that will be available on all
// Zepto collections
$.fn = {
constructor: zepto.Z,
length: 0,
// Because a collection acts like an array
// copy over these useful array functions.
forEach: emptyArray.forEach,
reduce: emptyArray.reduce,
push: emptyArray.push,
sort: emptyArray.sort,
splice: emptyArray.splice,
indexOf: emptyArray.indexOf,
concat: function(){
var i, value, args = []
for (i = 0; i < arguments.length; i++) {
value = arguments[i]
args[i] = zepto.isZ(value) ? value.toArray() : value
}
return concat.apply(zepto.isZ(this) ? this.toArray() : this, args)
},
// `map` and `slice` in the jQuery API work differently
// from their array counterparts
map: function(fn){
return $($.map(this, function(el, i){ return fn.call(el, i, el) }))
},
slice: function(){
return $(slice.apply(this, arguments))
},
ready: function(callback){
// need to check if document.body exists for IE as that browser reports
// document ready when it hasn't yet created the body element
if (readyRE.test(document.readyState) && document.body) callback($)
else document.addEventListener('DOMContentLoaded', function(){ callback($) }, false)
return this
},
get: function(idx){
return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length]
},
toArray: function(){ return this.get() },
size: function(){
return this.length
},
remove: function(){
return this.each(function(){
if (this.parentNode != null)
this.parentNode.removeChild(this)
})
},
each: function(callback){
emptyArray.every.call(this, function(el, idx){
return callback.call(el, idx, el) !== false
})
return this
},
filter: function(selector){
if (isFunction(selector)) return this.not(this.not(selector))
return $(filter.call(this, function(element){
return zepto.matches(element, selector)
}))
},
add: function(selector,context){
return $(uniq(this.concat($(selector,context))))
},
is: function(selector){
return this.length > 0 && zepto.matches(this[0], selector)
},
not: function(selector){
var nodes=[]
if (isFunction(selector) && selector.call !== undefined)
this.each(function(idx){
if (!selector.call(this,idx)) nodes.push(this)
})
else {
var excludes = typeof selector == 'string' ? this.filter(selector) :
(likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector)
this.forEach(function(el){
if (excludes.indexOf(el) < 0) nodes.push(el)
})
}
return $(nodes)
},
has: function(selector){
return this.filter(function(){
return isObject(selector) ?
$.contains(this, selector) :
$(this).find(selector).size()
})
},
eq: function(idx){
return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1)
},
first: function(){
var el = this[0]
return el && !isObject(el) ? el : $(el)
},
last: function(){
var el = this[this.length - 1]
return el && !isObject(el) ? el : $(el)
},
find: function(selector){
var result, $this = this
if (!selector) result = $()
else if (typeof selector == 'object')
result = $(selector).filter(function(){
var node = this
return emptyArray.some.call($this, function(parent){
return $.contains(parent, node)
})
})
else if (this.length == 1) result = $(zepto.qsa(this[0], selector))
else result = this.map(function(){ return zepto.qsa(this, selector) })
return result
},
closest: function(selector, context){
var node = this[0], collection = false
if (typeof selector == 'object') collection = $(selector)
while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector)))
node = node !== context && !isDocument(node) && node.parentNode
return $(node)
},
parents: function(selector){
var ancestors = [], nodes = this
while (nodes.length > 0)
nodes = $.map(nodes, function(node){
if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) {
ancestors.push(node)
return node
}
})
return filtered(ancestors, selector)
},
parent: function(selector){
return filtered(uniq(this.pluck('parentNode')), selector)
},
children: function(selector){
return filtered(this.map(function(){ return children(this) }), selector)
},
contents: function() {
return this.map(function() { return this.contentDocument || slice.call(this.childNodes) })
},
siblings: function(selector){
return filtered(this.map(function(i, el){
return filter.call(children(el.parentNode), function(child){ return child!==el })
}), selector)
},
empty: function(){
return this.each(function(){ this.innerHTML = '' })
},
// `pluck` is borrowed from Prototype.js
pluck: function(property){
return $.map(this, function(el){ return el[property] })
},
show: function(){
return this.each(function(){
this.style.display == "none" && (this.style.display = '')
if (getComputedStyle(this, '').getPropertyValue("display") == "none")
this.style.display = defaultDisplay(this.nodeName)
})
},
replaceWith: function(newContent){
return this.before(newContent).remove()
},
wrap: function(structure){
var func = isFunction(structure)
if (this[0] && !func)
var dom = $(structure).get(0),
clone = dom.parentNode || this.length > 1
return this.each(function(index){
$(this).wrapAll(
func ? structure.call(this, index) :
clone ? dom.cloneNode(true) : dom
)
})
},
wrapAll: function(structure){
if (this[0]) {
$(this[0]).before(structure = $(structure))
var children
// drill down to the inmost element
while ((children = structure.children()).length) structure = children.first()
$(structure).append(this)
}
return this
},
wrapInner: function(structure){
var func = isFunction(structure)
return this.each(function(index){
var self = $(this), contents = self.contents(),
dom = func ? structure.call(this, index) : structure
contents.length ? contents.wrapAll(dom) : self.append(dom)
})
},
unwrap: function(){
this.parent().each(function(){
$(this).replaceWith($(this).children())
})
return this
},
clone: function(){
return this.map(function(){ return this.cloneNode(true) })
},
hide: function(){
return this.css("display", "none")
},
toggle: function(setting){
return this.each(function(){
var el = $(this)
;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide()
})
},
prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') },
next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') },
html: function(html){
return 0 in arguments ?
this.each(function(idx){
var originHtml = this.innerHTML
$(this).empty().append( funcArg(this, html, idx, originHtml) )
}) :
(0 in this ? this[0].innerHTML : null)
},
text: function(text){
return 0 in arguments ?
this.each(function(idx){
var newText = funcArg(this, text, idx, this.textContent)
this.textContent = newText == null ? '' : ''+newText
}) :
(0 in this ? this[0].textContent : null)
},
attr: function(name, value){
var result
return (typeof name == 'string' && !(1 in arguments)) ?
(!this.length || this[0].nodeType !== 1 ? undefined :
(!(result = this[0].getAttribute(name)) && name in this[0]) ? this[0][name] : result
) :
this.each(function(idx){
if (this.nodeType !== 1) return
if (isObject(name)) for (key in name) setAttribute(this, key, name[key])
else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name)))
})
},
removeAttr: function(name){
return this.each(function(){ this.nodeType === 1 && name.split(' ').forEach(function(attribute){
setAttribute(this, attribute)
}, this)})
},
prop: function(name, value){
name = propMap[name] || name
return (1 in arguments) ?
this.each(function(idx){
this[name] = funcArg(this, value, idx, this[name])
}) :
(this[0] && this[0][name])
},
data: function(name, value){
var attrName = 'data-' + name.replace(capitalRE, '-$1').toLowerCase()
var data = (1 in arguments) ?
this.attr(attrName, value) :
this.attr(attrName)
return data !== null ? deserializeValue(data) : undefined
},
val: function(value){
return 0 in arguments ?
this.each(function(idx){
this.value = funcArg(this, value, idx, this.value)
}) :
(this[0] && (this[0].multiple ?
$(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') :
this[0].value)
)
},
offset: function(coordinates){
if (coordinates) return this.each(function(index){
var $this = $(this),
coords = funcArg(this, coordinates, index, $this.offset()),
parentOffset = $this.offsetParent().offset(),
props = {
top: coords.top - parentOffset.top,
left: coords.left - parentOffset.left
}
if ($this.css('position') == 'static') props['position'] = 'relative'
$this.css(props)
})
if (!this.length) return null
if (!$.contains(document.documentElement, this[0]))
return {top: 0, left: 0}
var obj = this[0].getBoundingClientRect()
return {
left: obj.left + window.pageXOffset,
top: obj.top + window.pageYOffset,
width: Math.round(obj.width),
height: Math.round(obj.height)
}
},
css: function(property, value){
if (arguments.length < 2) {
var computedStyle, element = this[0]
if(!element) return
computedStyle = getComputedStyle(element, '')
if (typeof property == 'string')
return element.style[camelize(property)] || computedStyle.getPropertyValue(property)
else if (isArray(property)) {
var props = {}
$.each(property, function(_, prop){
props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop))
})
return props
}
}
var css = ''
if (type(property) == 'string') {
if (!value && value !== 0)
this.each(function(){ this.style.removeProperty(dasherize(property)) })
else
css = dasherize(property) + ":" + maybeAddPx(property, value)
} else {
for (key in property)
if (!property[key] && property[key] !== 0)
this.each(function(){ this.style.removeProperty(dasherize(key)) })
else
css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';'
}
return this.each(function(){ this.style.cssText += ';' + css })
},
index: function(element){
return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0])
},
hasClass: function(name){
if (!name) return false
return emptyArray.some.call(this, function(el){
return this.test(className(el))
}, classRE(name))
},
addClass: function(name){
if (!name) return this
return this.each(function(idx){
if (!('className' in this)) return
classList = []
var cls = className(this), newName = funcArg(this, name, idx, cls)
newName.split(/\s+/g).forEach(function(klass){
if (!$(this).hasClass(klass)) classList.push(klass)
}, this)
classList.length && className(this, cls + (cls ? " " : "") + classList.join(" "))
})
},
removeClass: function(name){
return this.each(function(idx){
if (!('className' in this)) return
if (name === undefined) return className(this, '')
classList = className(this)
funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){
classList = classList.replace(classRE(klass), " ")
})
className(this, classList.trim())
})
},
toggleClass: function(name, when){
if (!name) return this
return this.each(function(idx){
var $this = $(this), names = funcArg(this, name, idx, className(this))
names.split(/\s+/g).forEach(function(klass){
(when === undefined ? !$this.hasClass(klass) : when) ?
$this.addClass(klass) : $this.removeClass(klass)
})
})
},
scrollTop: function(value){
if (!this.length) return
var hasScrollTop = 'scrollTop' in this[0]
if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset
return this.each(hasScrollTop ?
function(){ this.scrollTop = value } :
function(){ this.scrollTo(this.scrollX, value) })
},
scrollLeft: function(value){
if (!this.length) return
var hasScrollLeft = 'scrollLeft' in this[0]
if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset
return this.each(hasScrollLeft ?
function(){ this.scrollLeft = value } :
function(){ this.scrollTo(value, this.scrollY) })
},
position: function() {
if (!this.length) return
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset()
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( $(elem).css('margin-top') ) || 0
offset.left -= parseFloat( $(elem).css('margin-left') ) || 0
// Add offsetParent borders
parentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0
parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
}
},
offsetParent: function() {
return this.map(function(){
var parent = this.offsetParent || document.body
while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static")
parent = parent.offsetParent
return parent
})
}
}
// for now
$.fn.detach = $.fn.remove
// Generate the `width` and `height` functions
;['width', 'height'].forEach(function(dimension){
var dimensionProperty =
dimension.replace(/./, function(m){ return m[0].toUpperCase() })
$.fn[dimension] = function(value){
var offset, el = this[0]
if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] :
isDocument(el) ? el.documentElement['scroll' + dimensionProperty] :
(offset = this.offset()) && offset[dimension]
else return this.each(function(idx){
el = $(this)
el.css(dimension, funcArg(this, value, idx, el[dimension]()))
})
}
})
function traverseNode(node, fun) {
fun(node)
for (var i = 0, len = node.childNodes.length; i < len; i++)
traverseNode(node.childNodes[i], fun)
}
// Generate the `after`, `prepend`, `before`, `append`,
// `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods.
adjacencyOperators.forEach(function(operator, operatorIndex) {
var inside = operatorIndex % 2 //=> prepend, append
$.fn[operator] = function(){
// arguments can be nodes, arrays of nodes, Zepto objects and HTML strings
var argType, nodes = $.map(arguments, function(arg) {
argType = type(arg)
return argType == "object" || argType == "array" || arg == null ?
arg : zepto.fragment(arg)
}),
parent, copyByClone = this.length > 1
if (nodes.length < 1) return this
return this.each(function(_, target){
parent = inside ? target : target.parentNode
// convert all methods to a "before" operation
target = operatorIndex == 0 ? target.nextSibling :
operatorIndex == 1 ? target.firstChild :
operatorIndex == 2 ? target :
null
var parentInDocument = $.contains(document.documentElement, parent)
nodes.forEach(function(node){
if (copyByClone) node = node.cloneNode(true)
else if (!parent) return $(node).remove()
parent.insertBefore(node, target)
if (parentInDocument) traverseNode(node, function(el){
if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' &&
(!el.type || el.type === 'text/javascript') && !el.src)
window['eval'].call(window, el.innerHTML)
})
})
})
}
// after => insertAfter
// prepend => prependTo
// before => insertBefore
// append => appendTo
$.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){
$(html)[operator](this)
return this
}
})
zepto.Z.prototype = Z.prototype = $.fn
// Export internal API functions in the `$.zepto` namespace
zepto.uniq = uniq
zepto.deserializeValue = deserializeValue
$.zepto = zepto
return $
})()
// If `$` is not yet defined, point it to `Zepto`
window.Zepto = Zepto
window.$ === undefined && (window.$ = Zepto)
// Zepto.js
// (c) 2010-2015 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
;(function($){
var jsonpID = 0,
document = window.document,
key,
name,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
scriptTypeRE = /^(?:text|application)\/javascript/i,
xmlTypeRE = /^(?:text|application)\/xml/i,
jsonType = 'application/json',
htmlType = 'text/html',
blankRE = /^\s*$/,
originAnchor = document.createElement('a')
originAnchor.href = window.location.href
// trigger a custom event and return false if it was cancelled
function triggerAndReturn(context, eventName, data) {
var event = $.Event(eventName)
$(context).trigger(event, data)
return !event.isDefaultPrevented()
}
// trigger an Ajax "global" event
function triggerGlobal(settings, context, eventName, data) {
if (settings.global) return triggerAndReturn(context || document, eventName, data)
}
// Number of active Ajax requests
$.active = 0
function ajaxStart(settings) {
if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart')
}
function ajaxStop(settings) {
if (settings.global && !(--$.active)) triggerGlobal(settings, null, 'ajaxStop')
}
// triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable
function ajaxBeforeSend(xhr, settings) {
var context = settings.context
if (settings.beforeSend.call(context, xhr, settings) === false ||
triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false)
return false
triggerGlobal(settings, context, 'ajaxSend', [xhr, settings])
}
function ajaxSuccess(data, xhr, settings, deferred) {
var context = settings.context, status = 'success'
settings.success.call(context, data, status, xhr)
if (deferred) deferred.resolveWith(context, [data, status, xhr])
triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data])
ajaxComplete(status, xhr, settings)
}
// type: "timeout", "error", "abort", "parsererror"
function ajaxError(error, type, xhr, settings, deferred) {
var context = settings.context
settings.error.call(context, xhr, type, error)
if (deferred) deferred.rejectWith(context, [xhr, type, error])
triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error || type])
ajaxComplete(type, xhr, settings)
}
// status: "success", "notmodified", "error", "timeout", "abort", "parsererror"
function ajaxComplete(status, xhr, settings) {
var context = settings.context
settings.complete.call(context, xhr, status)
triggerGlobal(settings, context, 'ajaxComplete', [xhr, settings])
ajaxStop(settings)
}
// Empty function, used as default callback
function empty() {}
$.ajaxJSONP = function(options, deferred){
if (!('type' in options)) return $.ajax(options)
var _callbackName = options.jsonpCallback,
callbackName = ($.isFunction(_callbackName) ?
_callbackName() : _callbackName) || ('jsonp' + (++jsonpID)),
script = document.createElement('script'),
originalCallback = window[callbackName],
responseData,
abort = function(errorType) {
$(script).triggerHandler('error', errorType || 'abort')
},
xhr = { abort: abort }, abortTimeout
if (deferred) deferred.promise(xhr)
$(script).on('load error', function(e, errorType){
clearTimeout(abortTimeout)
$(script).off().remove()
if (e.type == 'error' || !responseData) {
ajaxError(null, errorType || 'error', xhr, options, deferred)
} else {
ajaxSuccess(responseData[0], xhr, options, deferred)
}
window[callbackName] = originalCallback
if (responseData && $.isFunction(originalCallback))
originalCallback(responseData[0])
originalCallback = responseData = undefined
})
if (ajaxBeforeSend(xhr, options) === false) {
abort('abort')
return xhr
}
window[callbackName] = function(){
responseData = arguments
}
script.src = options.url.replace(/\?(.+)=\?/, '?$1=' + callbackName)
document.head.appendChild(script)
if (options.timeout > 0) abortTimeout = setTimeout(function(){
abort('timeout')
}, options.timeout)
return xhr
}
$.ajaxSettings = {
// Default type of request
type: 'GET',
// Callback that is executed before request
beforeSend: empty,
// Callback that is executed if the request succeeds
success: empty,
// Callback that is executed the the server drops error
error: empty,
// Callback that is executed on request complete (both: error and success)
complete: empty,
// The context for the callbacks
context: null,
// Whether to trigger "global" Ajax events
global: true,
// Transport
xhr: function () {
return new window.XMLHttpRequest()
},
// MIME types mapping
// IIS returns Javascript as "application/x-javascript"
accepts: {
script: 'text/javascript, application/javascript, application/x-javascript',
json: jsonType,
xml: 'application/xml, text/xml',
html: htmlType,
text: 'text/plain'
},
// Whether the request is to another domain
crossDomain: false,
// Default timeout
timeout: 0,
// Whether data should be serialized to string
processData: true,
// Whether the browser should be allowed to cache GET responses
cache: true
}
function mimeToDataType(mime) {
if (mime) mime = mime.split(';', 2)[0]
return mime && ( mime == htmlType ? 'html' :
mime == jsonType ? 'json' :
scriptTypeRE.test(mime) ? 'script' :
xmlTypeRE.test(mime) && 'xml' ) || 'text'
}
function appendQuery(url, query) {
if (query == '') return url
return (url + '&' + query).replace(/[&?]{1,2}/, '?')
}
// serialize payload and append it to the URL for GET requests
function serializeData(options) {
if (options.processData && options.data && $.type(options.data) != "string")
options.data = $.param(options.data, options.traditional)
if (options.data && (!options.type || options.type.toUpperCase() == 'GET'))
options.url = appendQuery(options.url, options.data), options.data = undefined
}
$.ajax = function(options){
var settings = $.extend({}, options || {}),
deferred = $.Deferred && $.Deferred(),
urlAnchor, hashIndex
for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key]
ajaxStart(settings)
if (!settings.crossDomain) {
urlAnchor = document.createElement('a')
urlAnchor.href = settings.url
urlAnchor.href = urlAnchor.href
settings.crossDomain = (originAnchor.protocol + '//' + originAnchor.host) !== (urlAnchor.protocol + '//' + urlAnchor.host)
}
if (!settings.url) settings.url = window.location.toString()
if ((hashIndex = settings.url.indexOf('#')) > -1) settings.url = settings.url.slice(0, hashIndex)
serializeData(settings)
var dataType = settings.dataType, hasPlaceholder = /\?.+=\?/.test(settings.url)
if (hasPlaceholder) dataType = 'jsonp'
if (settings.cache === false || (
(!options || options.cache !== true) &&
('script' == dataType || 'jsonp' == dataType)
))
settings.url = appendQuery(settings.url, '_=' + Date.now())
if ('jsonp' == dataType) {
if (!hasPlaceholder)
settings.url = appendQuery(settings.url,
settings.jsonp ? (settings.jsonp + '=?') : settings.jsonp === false ? '' : 'callback=?')
return $.ajaxJSONP(settings, deferred)
}
var mime = settings.accepts[dataType],
headers = { },
setHeader = function(name, value) { headers[name.toLowerCase()] = [name, value] },
protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol,
xhr = settings.xhr(),
nativeSetHeader = xhr.setRequestHeader,
abortTimeout
if (deferred) deferred.promise(xhr)
if (!settings.crossDomain) setHeader('X-Requested-With', 'XMLHttpRequest')
setHeader('Accept', mime || '*/*')
if (mime = settings.mimeType || mime) {
if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0]
xhr.overrideMimeType && xhr.overrideMimeType(mime)
}
if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET'))
setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded')
if (settings.headers) for (name in settings.headers) setHeader(name, settings.headers[name])
xhr.setRequestHeader = setHeader
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
xhr.onreadystatechange = empty
clearTimeout(abortTimeout)
var result, error = false
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) {
dataType = dataType || mimeToDataType(settings.mimeType || xhr.getResponseHeader('content-type'))
result = xhr.responseText
try {
// http://perfectionkills.com/global-eval-what-are-the-options/
if (dataType == 'script') (1,eval)(result)
else if (dataType == 'xml') result = xhr.responseXML
else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result)
} catch (e) { error = e }
if (error) ajaxError(error, 'parsererror', xhr, settings, deferred)
else ajaxSuccess(result, xhr, settings, deferred)
} else {
ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr, settings, deferred)
}
}
}
if (ajaxBeforeSend(xhr, settings) === false) {
xhr.abort()
ajaxError(null, 'abort', xhr, settings, deferred)
return xhr
}
if (settings.xhrFields) for (name in settings.xhrFields) xhr[name] = settings.xhrFields[name]
var async = 'async' in settings ? settings.async : true
xhr.open(settings.type, settings.url, async, settings.username, settings.password)
for (name in headers) nativeSetHeader.apply(xhr, headers[name])
if (settings.timeout > 0) abortTimeout = setTimeout(function(){
xhr.onreadystatechange = empty
xhr.abort()
ajaxError(null, 'timeout', xhr, settings, deferred)
}, settings.timeout)
// avoid sending empty string (#319)
xhr.send(settings.data ? settings.data : null)
return xhr
}
// handle optional data/success arguments
function parseArguments(url, data, success, dataType) {
if ($.isFunction(data)) dataType = success, success = data, data = undefined
if (!$.isFunction(success)) dataType = success, success = undefined
return {
url: url
, data: data
, success: success
, dataType: dataType
}
}
$.get = function(/* url, data, success, dataType */){
return $.ajax(parseArguments.apply(null, arguments))
}
$.post = function(/* url, data, success, dataType */){
var options = parseArguments.apply(null, arguments)
options.type = 'POST'
return $.ajax(options)
}
$.getJSON = function(/* url, data, success */){
var options = parseArguments.apply(null, arguments)
options.dataType = 'json'
return $.ajax(options)
}
$.fn.load = function(url, data, success){
if (!this.length) return this
var self = this, parts = url.split(/\s/), selector,
options = parseArguments(url, data, success),
callback = options.success
if (parts.length > 1) options.url = parts[0], selector = parts[1]
options.success = function(response){
self.html(selector ?
$('<div>').html(response.replace(rscript, "")).find(selector)
: response)
callback && callback.apply(self, arguments)
}
$.ajax(options)
return this
}
var escape = encodeURIComponent
function serialize(params, obj, traditional, scope){
var type, array = $.isArray(obj), hash = $.isPlainObject(obj)
$.each(obj, function(key, value) {
type = $.type(value)
if (scope) key = traditional ? scope :
scope + '[' + (hash || type == 'object' || type == 'array' ? key : '') + ']'
// handle data in serializeArray() format
if (!scope && array) params.add(value.name, value.value)
// recurse into nested objects
else if (type == "array" || (!traditional && type == "object"))
serialize(params, value, traditional, key)
else params.add(key, value)
})
}
$.param = function(obj, traditional){
var params = []
params.add = function(key, value) {
if ($.isFunction(value)) value = value()
if (value == null) value = ""
this.push(escape(key) + '=' + escape(value))
}
serialize(params, obj, traditional)
return params.join('&').replace(/%20/g, '+')
}
})(Zepto)
// Zepto.js
// (c) 2010-2015 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
;(function($){
var _zid = 1, undefined,
slice = Array.prototype.slice,
isFunction = $.isFunction,
isString = function(obj){ return typeof obj == 'string' },
handlers = {},
specialEvents={},
focusinSupported = 'onfocusin' in window,
focus = { focus: 'focusin', blur: 'focusout' },
hover = { mouseenter: 'mouseover', mouseleave: 'mouseout' }
specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents'
function zid(element) {
return element._zid || (element._zid = _zid++)
}
function findHandlers(element, event, fn, selector) {
event = parse(event)
if (event.ns) var matcher = matcherFor(event.ns)
return (handlers[zid(element)] || []).filter(function(handler) {
return handler
&& (!event.e || handler.e == event.e)
&& (!event.ns || matcher.test(handler.ns))
&& (!fn || zid(handler.fn) === zid(fn))
&& (!selector || handler.sel == selector)
})
}
function parse(event) {
var parts = ('' + event).split('.')
return {e: parts[0], ns: parts.slice(1).sort().join(' ')}
}
function matcherFor(ns) {
return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)')
}
function eventCapture(handler, captureSetting) {
return handler.del &&
(!focusinSupported && (handler.e in focus)) ||
!!captureSetting
}
function realEvent(type) {
return hover[type] || (focusinSupported && focus[type]) || type
}
function add(element, events, fn, data, selector, delegator, capture){
var id = zid(element), set = (handlers[id] || (handlers[id] = []))
events.split(/\s/).forEach(function(event){
if (event == 'ready') return $(document).ready(fn)
var handler = parse(event)
handler.fn = fn
handler.sel = selector
// emulate mouseenter, mouseleave
if (handler.e in hover) fn = function(e){
var related = e.relatedTarget
if (!related || (related !== this && !$.contains(this, related)))
return handler.fn.apply(this, arguments)
}
handler.del = delegator
var callback = delegator || fn
handler.proxy = function(e){
e = compatible(e)
if (e.isImmediatePropagationStopped()) return
e.data = data
var result = callback.apply(element, e._args == undefined ? [e] : [e].concat(e._args))
if (result === false) e.preventDefault(), e.stopPropagation()
return result
}
handler.i = set.length
set.push(handler)
if ('addEventListener' in element)
element.addEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
})
}
function remove(element, events, fn, selector, capture){
var id = zid(element)
;(events || '').split(/\s/).forEach(function(event){
findHandlers(element, event, fn, selector).forEach(function(handler){
delete handlers[id][handler.i]
if ('removeEventListener' in element)
element.removeEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
})
})
}
$.event = { add: add, remove: remove }
$.proxy = function(fn, context) {
var args = (2 in arguments) && slice.call(arguments, 2)
if (isFunction(fn)) {
var proxyFn = function(){ return fn.apply(context, args ? args.concat(slice.call(arguments)) : arguments) }
proxyFn._zid = zid(fn)
return proxyFn
} else if (isString(context)) {
if (args) {
args.unshift(fn[context], fn)
return $.proxy.apply(null, args)
} else {
return $.proxy(fn[context], fn)
}
} else {
throw new TypeError("expected function")
}
}
$.fn.bind = function(event, data, callback){
return this.on(event, data, callback)
}
$.fn.unbind = function(event, callback){
return this.off(event, callback)
}
$.fn.one = function(event, selector, data, callback){
return this.on(event, selector, data, callback, 1)
}
var returnTrue = function(){return true},
returnFalse = function(){return false},
ignoreProperties = /^([A-Z]|returnValue$|layer[XY]$)/,
eventMethods = {
preventDefault: 'isDefaultPrevented',
stopImmediatePropagation: 'isImmediatePropagationStopped',
stopPropagation: 'isPropagationStopped'
}
function compatible(event, source) {
if (source || !event.isDefaultPrevented) {
source || (source = event)
$.each(eventMethods, function(name, predicate) {
var sourceMethod = source[name]
event[name] = function(){
this[predicate] = returnTrue
return sourceMethod && sourceMethod.apply(source, arguments)
}
event[predicate] = returnFalse
})
if (source.defaultPrevented !== undefined ? source.defaultPrevented :
'returnValue' in source ? source.returnValue === false :
source.getPreventDefault && source.getPreventDefault())
event.isDefaultPrevented = returnTrue
}
return event
}
function createProxy(event) {
var key, proxy = { originalEvent: event }
for (key in event)
if (!ignoreProperties.test(key) && event[key] !== undefined) proxy[key] = event[key]
return compatible(proxy, event)
}
$.fn.delegate = function(selector, event, callback){
return this.on(event, selector, callback)
}
$.fn.undelegate = function(selector, event, callback){
return this.off(event, selector, callback)
}
$.fn.live = function(event, callback){
$(document.body).delegate(this.selector, event, callback)
return this
}
$.fn.die = function(event, callback){
$(document.body).undelegate(this.selector, event, callback)
return this
}
$.fn.on = function(event, selector, data, callback, one){
var autoRemove, delegator, $this = this
if (event && !isString(event)) {
$.each(event, function(type, fn){
$this.on(type, selector, data, fn, one)
})
return $this
}
if (!isString(selector) && !isFunction(callback) && callback !== false)
callback = data, data = selector, selector = undefined
if (callback === undefined || data === false)
callback = data, data = undefined
if (callback === false) callback = returnFalse
return $this.each(function(_, element){
if (one) autoRemove = function(e){
remove(element, e.type, callback)
return callback.apply(this, arguments)
}
if (selector) delegator = function(e){
var evt, match = $(e.target).closest(selector, element).get(0)
if (match && match !== element) {
evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element})
return (autoRemove || callback).apply(match, [evt].concat(slice.call(arguments, 1)))
}
}
add(element, event, callback, data, selector, delegator || autoRemove)
})
}
$.fn.off = function(event, selector, callback){
var $this = this
if (event && !isString(event)) {
$.each(event, function(type, fn){
$this.off(type, selector, fn)
})
return $this
}
if (!isString(selector) && !isFunction(callback) && callback !== false)
callback = selector, selector = undefined
if (callback === false) callback = returnFalse
return $this.each(function(){
remove(this, event, callback, selector)
})
}
$.fn.trigger = function(event, args){
event = (isString(event) || $.isPlainObject(event)) ? $.Event(event) : compatible(event)
event._args = args
return this.each(function(){
// handle focus(), blur() by calling them directly
if (event.type in focus && typeof this[event.type] == "function") this[event.type]()
// items in the collection might not be DOM elements
else if ('dispatchEvent' in this) this.dispatchEvent(event)
else $(this).triggerHandler(event, args)
})
}
// triggers event handlers on current element just as if an event occurred,
// doesn't trigger an actual event, doesn't bubble
$.fn.triggerHandler = function(event, args){
var e, result
this.each(function(i, element){
e = createProxy(isString(event) ? $.Event(event) : event)
e._args = args
e.target = element
$.each(findHandlers(element, event.type || event), function(i, handler){
result = handler.proxy(e)
if (e.isImmediatePropagationStopped()) return false
})
})
return result
}
// shortcut methods for `.bind(event, fn)` for each event type
;('focusin focusout focus blur load resize scroll unload click dblclick '+
'mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave '+
'change select keydown keypress keyup error').split(' ').forEach(function(event) {
$.fn[event] = function(callback) {
return (0 in arguments) ?
this.bind(event, callback) :
this.trigger(event)
}
})
$.Event = function(type, props) {
if (!isString(type)) props = type, type = props.type
var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true
if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name])
event.initEvent(type, bubbles, true)
return compatible(event)
}
})(Zepto)
// Zepto.js
// (c) 2010-2015 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
;(function($){
$.fn.serializeArray = function() {
var name, type, result = [],
add = function(value) {
if (value.forEach) return value.forEach(add)
result.push({ name: name, value: value })
}
if (this[0]) $.each(this[0].elements, function(_, field){
type = field.type, name = field.name
if (name && field.nodeName.toLowerCase() != 'fieldset' &&
!field.disabled && type != 'submit' && type != 'reset' && type != 'button' && type != 'file' &&
((type != 'radio' && type != 'checkbox') || field.checked))
add($(field).val())
})
return result
}
$.fn.serialize = function(){
var result = []
this.serializeArray().forEach(function(elm){
result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value))
})
return result.join('&')
}
$.fn.submit = function(callback) {
if (0 in arguments) this.bind('submit', callback)
else if (this.length) {
var event = $.Event('submit')
this.eq(0).trigger(event)
if (!event.isDefaultPrevented()) this.get(0).submit()
}
return this
}
})(Zepto)
// Zepto.js
// (c) 2010-2015 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
;(function($, undefined){
var prefix = '', eventPrefix,
vendors = { Webkit: 'webkit', Moz: '', O: 'o' },
testEl = document.createElement('div'),
supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,
transform,
transitionProperty, transitionDuration, transitionTiming, transitionDelay,
animationName, animationDuration, animationTiming, animationDelay,
cssReset = {}
function dasherize(str) { return str.replace(/([a-z])([A-Z])/, '$1-$2').toLowerCase() }
function normalizeEvent(name) { return eventPrefix ? eventPrefix + name : name.toLowerCase() }
$.each(vendors, function(vendor, event){
if (testEl.style[vendor + 'TransitionProperty'] !== undefined) {
prefix = '-' + vendor.toLowerCase() + '-'
eventPrefix = event
return false
}
})
transform = prefix + 'transform'
cssReset[transitionProperty = prefix + 'transition-property'] =
cssReset[transitionDuration = prefix + 'transition-duration'] =
cssReset[transitionDelay = prefix + 'transition-delay'] =
cssReset[transitionTiming = prefix + 'transition-timing-function'] =
cssReset[animationName = prefix + 'animation-name'] =
cssReset[animationDuration = prefix + 'animation-duration'] =
cssReset[animationDelay = prefix + 'animation-delay'] =
cssReset[animationTiming = prefix + 'animation-timing-function'] = ''
$.fx = {
off: (eventPrefix === undefined && testEl.style.transitionProperty === undefined),
speeds: { _default: 400, fast: 200, slow: 600 },
cssPrefix: prefix,
transitionEnd: normalizeEvent('TransitionEnd'),
animationEnd: normalizeEvent('AnimationEnd')
}
$.fn.animate = function(properties, duration, ease, callback, delay){
if ($.isFunction(duration))
callback = duration, ease = undefined, duration = undefined
if ($.isFunction(ease))
callback = ease, ease = undefined
if ($.isPlainObject(duration))
ease = duration.easing, callback = duration.complete, delay = duration.delay, duration = duration.duration
if (duration) duration = (typeof duration == 'number' ? duration :
($.fx.speeds[duration] || $.fx.speeds._default)) / 1000
if (delay) delay = parseFloat(delay) / 1000
return this.anim(properties, duration, ease, callback, delay)
}
$.fn.anim = function(properties, duration, ease, callback, delay){
var key, cssValues = {}, cssProperties, transforms = '',
that = this, wrappedCallback, endEvent = $.fx.transitionEnd,
fired = false
if (duration === undefined) duration = $.fx.speeds._default / 1000
if (delay === undefined) delay = 0
if ($.fx.off) duration = 0
if (typeof properties == 'string') {
// keyframe animation
cssValues[animationName] = properties
cssValues[animationDuration] = duration + 's'
cssValues[animationDelay] = delay + 's'
cssValues[animationTiming] = (ease || 'linear')
endEvent = $.fx.animationEnd
} else {
cssProperties = []
// CSS transitions
for (key in properties)
if (supportedTransforms.test(key)) transforms += key + '(' + properties[key] + ') '
else cssValues[key] = properties[key], cssProperties.push(dasherize(key))
if (transforms) cssValues[transform] = transforms, cssProperties.push(transform)
if (duration > 0 && typeof properties === 'object') {
cssValues[transitionProperty] = cssProperties.join(', ')
cssValues[transitionDuration] = duration + 's'
cssValues[transitionDelay] = delay + 's'
cssValues[transitionTiming] = (ease || 'linear')
}
}
wrappedCallback = function(event){
if (typeof event !== 'undefined') {
if (event.target !== event.currentTarget) return // makes sure the event didn't bubble from "below"
$(event.target).unbind(endEvent, wrappedCallback)
} else
$(this).unbind(endEvent, wrappedCallback) // triggered by setTimeout
fired = true
$(this).css(cssReset)
callback && callback.call(this)
}
if (duration > 0){
this.bind(endEvent, wrappedCallback)
// transitionEnd is not always firing on older Android phones
// so make sure it gets fired
setTimeout(function(){
if (fired) return
wrappedCallback.call(that)
}, ((duration + delay) * 1000) + 25)
}
// trigger page reflow so new elements can animate
this.size() && this.get(0).clientLeft
this.css(cssValues)
if (duration <= 0) setTimeout(function() {
that.each(function(){ wrappedCallback.call(this) })
}, 0)
return this
}
testEl = null
})(Zepto)
// Zepto.js
// (c) 2010-2015 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
;(function($, undefined){
var document = window.document, docElem = document.documentElement,
origShow = $.fn.show, origHide = $.fn.hide, origToggle = $.fn.toggle
function anim(el, speed, opacity, scale, callback) {
if (typeof speed == 'function' && !callback) callback = speed, speed = undefined
var props = { opacity: opacity }
if (scale) {
props.scale = scale
el.css($.fx.cssPrefix + 'transform-origin', '0 0')
}
return el.animate(props, speed, null, callback)
}
function hide(el, speed, scale, callback) {
return anim(el, speed, 0, scale, function(){
origHide.call($(this))
callback && callback.call(this)
})
}
$.fn.show = function(speed, callback) {
origShow.call(this)
if (speed === undefined) speed = 0
else this.css('opacity', 0)
return anim(this, speed, 1, '1,1', callback)
}
$.fn.hide = function(speed, callback) {
if (speed === undefined) return origHide.call(this)
else return hide(this, speed, '0,0', callback)
}
$.fn.toggle = function(speed, callback) {
if (speed === undefined || typeof speed == 'boolean')
return origToggle.call(this, speed)
else return this.each(function(){
var el = $(this)
el[el.css('display') == 'none' ? 'show' : 'hide'](speed, callback)
})
}
$.fn.fadeTo = function(speed, opacity, callback) {
return anim(this, speed, opacity, null, callback)
}
$.fn.fadeIn = function(speed, callback) {
var target = this.css('opacity')
if (target > 0) this.css('opacity', 0)
else target = 1
return origShow.call(this).fadeTo(speed, target, callback)
}
$.fn.fadeOut = function(speed, callback) {
return hide(this, speed, null, callback)
}
$.fn.fadeToggle = function(speed, callback) {
return this.each(function(){
var el = $(this)
el[
(el.css('opacity') == 0 || el.css('display') == 'none') ? 'fadeIn' : 'fadeOut'
](speed, callback)
})
}
})(Zepto)
// Zepto.js
// (c) 2010-2015 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
;(function(){
// getComputedStyle shouldn't freak out when called
// without a valid element as argument
try {
getComputedStyle(undefined)
} catch(e) {
var nativeGetComputedStyle = getComputedStyle;
window.getComputedStyle = function(element){
try {
return nativeGetComputedStyle(element)
} catch(e) {
return null
}
}
}
})()
// Zepto.js
// (c) 2010-2015 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
;(function($){
var touch = {},
touchTimeout, tapTimeout, swipeTimeout, longTapTimeout,
longTapDelay = 750,
gesture
function swipeDirection(x1, x2, y1, y2) {
return Math.abs(x1 - x2) >=
Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down')
}
function longTap() {
longTapTimeout = null
if (touch.last) {
touch.el.trigger('longTap')
touch = {}
}
}
function cancelLongTap() {
if (longTapTimeout) clearTimeout(longTapTimeout)
longTapTimeout = null
}
function cancelAll() {
if (touchTimeout) clearTimeout(touchTimeout)
if (tapTimeout) clearTimeout(tapTimeout)
if (swipeTimeout) clearTimeout(swipeTimeout)
if (longTapTimeout) clearTimeout(longTapTimeout)
touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null
touch = {}
}
function isPrimaryTouch(event){
return (event.pointerType == 'touch' ||
event.pointerType == event.MSPOINTER_TYPE_TOUCH)
&& event.isPrimary
}
function isPointerEventType(e, type){
return (e.type == 'pointer'+type ||
e.type.toLowerCase() == 'mspointer'+type)
}
$(document).ready(function(){
var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType
if ('MSGesture' in window) {
gesture = new MSGesture()
gesture.target = document.body
}
$(document)
.bind('MSGestureEnd', function(e){
var swipeDirectionFromVelocity =
e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null;
if (swipeDirectionFromVelocity) {
touch.el.trigger('swipe')
touch.el.trigger('swipe'+ swipeDirectionFromVelocity)
}
})
.on('touchstart MSPointerDown pointerdown', function(e){
if((_isPointerType = isPointerEventType(e, 'down')) &&
!isPrimaryTouch(e)) return
firstTouch = _isPointerType ? e : e.touches[0]
if (e.touches && e.touches.length === 1 && touch.x2) {
// Clear out touch movement data if we have it sticking around
// This can occur if touchcancel doesn't fire due to preventDefault, etc.
touch.x2 = undefined
touch.y2 = undefined
}
now = Date.now()
delta = now - (touch.last || now)
touch.el = $('tagName' in firstTouch.target ?
firstTouch.target : firstTouch.target.parentNode)
touchTimeout && clearTimeout(touchTimeout)
touch.x1 = firstTouch.pageX
touch.y1 = firstTouch.pageY
if (delta > 0 && delta <= 250) touch.isDoubleTap = true
touch.last = now
longTapTimeout = setTimeout(longTap, longTapDelay)
// adds the current touch contact for IE gesture recognition
if (gesture && _isPointerType) gesture.addPointer(e.pointerId);
})
.on('touchmove MSPointerMove pointermove', function(e){
if((_isPointerType = isPointerEventType(e, 'move')) &&
!isPrimaryTouch(e)) return
firstTouch = _isPointerType ? e : e.touches[0]
cancelLongTap()
touch.x2 = firstTouch.pageX
touch.y2 = firstTouch.pageY
deltaX += Math.abs(touch.x1 - touch.x2)
deltaY += Math.abs(touch.y1 - touch.y2)
})
.on('touchend MSPointerUp pointerup', function(e){
if((_isPointerType = isPointerEventType(e, 'up')) &&
!isPrimaryTouch(e)) return
cancelLongTap()
// swipe
if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) ||
(touch.y2 && Math.abs(touch.y1 - touch.y2) > 30))
swipeTimeout = setTimeout(function() {
touch.el.trigger('swipe')
touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)))
touch = {}
}, 0)
// normal tap
else if ('last' in touch)
// don't fire tap when delta position changed by more than 30 pixels,
// for instance when moving to a point and back to origin
if (deltaX < 30 && deltaY < 30) {
// delay by one tick so we can cancel the 'tap' event if 'scroll' fires
// ('tap' fires before 'scroll')
tapTimeout = setTimeout(function() {
// trigger universal 'tap' with the option to cancelTouch()
// (cancelTouch cancels processing of single vs double taps for faster 'tap' response)
var event = $.Event('tap')
event.cancelTouch = cancelAll
touch.el.trigger(event)
// trigger double tap immediately
if (touch.isDoubleTap) {
if (touch.el) touch.el.trigger('doubleTap')
touch = {}
}
// trigger single tap after 250ms of inactivity
else {
touchTimeout = setTimeout(function(){
touchTimeout = null
if (touch.el) touch.el.trigger('singleTap')
touch = {}
}, 250)
}
}, 0)
} else {
touch = {}
}
deltaX = deltaY = 0
})
// when the browser window loses focus,
// for example when a modal dialog is shown,
// cancel all ongoing events
.on('touchcancel MSPointerCancel pointercancel', cancelAll)
// scrolling the window indicates intention of the user
// to scroll, not tap or swipe, so cancel all ongoing events
$(window).on('scroll', cancelAll)
})
;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown',
'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(eventName){
$.fn[eventName] = function(callback){ return this.on(eventName, callback) }
})
})(Zepto)
| nongfadai/front_demo | web/src/notuse/app/lib/zepto/zepto.js | JavaScript | mit | 69,690 |
var kunstmaanbundles = kunstmaanbundles || {};
kunstmaanbundles.datepicker = (function($, window, undefined) {
var init, reInit, _setDefaultDate, _initDatepicker;
var _today = window.moment(),
_tomorrow = window.moment(_today).add(1, 'days');
var defaultFormat = 'DD-MM-YYYY',
defaultCollapse = true,
defaultKeepOpen = false,
defaultMinDate = false,
defaultShowDefaultDate = false,
defaultStepping = 1;
init = function() {
$('.js-datepicker').each(function() {
_initDatepicker($(this));
});
};
reInit = function(el) {
if (el) {
_initDatepicker($(el));
} else {
$('.js-datepicker').each(function() {
if (!$(this).hasClass('datepicker--enabled')) {
_initDatepicker($(this));
}
});
}
};
_setDefaultDate = function(elMinDate) {
if(elMinDate === 'tomorrow') {
return _tomorrow;
} else {
return _today;
}
};
_initDatepicker = function($el) {
// Get Settings
var elFormat = $el.data('format'),
elCollapse = $el.data('collapse'),
elKeepOpen = $el.data('keep-open'),
elMinDate = $el.data('min-date'),
elShowDefaultDate = $el.data('default-date'),
elStepping = $el.data('stepping');
// Set Settings
var format = (elFormat !== undefined) ? elFormat : defaultFormat,
collapse = (elCollapse !== undefined) ? elCollapse : defaultCollapse,
keepOpen = (elKeepOpen !== undefined) ? elKeepOpen : defaultKeepOpen,
minDate = (elMinDate === 'tomorrow') ? _tomorrow : (elMinDate === 'today') ? _today : defaultMinDate,
defaultDate = (elShowDefaultDate) ? _setDefaultDate(elMinDate) : defaultShowDefaultDate,
stepping = (elStepping !== undefined) ? elStepping : defaultStepping;
// Setup
var $input = $el.find('input'),
$addon = $el.find('.input-group-addon'),
linkedDatepickerID = $el.data('linked-datepicker') || false;
if (format.indexOf('HH:mm') === -1) {
// Drop time if not necessary
if (minDate) {
minDate = minDate.clone().startOf('day'); // clone() because otherwise .startOf() mutates the original moment object
}
if (defaultDate) {
defaultDate = defaultDate.clone().startOf('day');
}
}
$input.datetimepicker({
format: format,
collapse: collapse,
keepOpen: keepOpen,
minDate: minDate,
defaultDate: defaultDate,
widgetPositioning: {
horizontal: 'left',
vertical: 'auto'
},
widgetParent: $el,
icons: {
time: 'fa fa-clock',
date: 'fa fa-calendar',
up: 'fa fa-chevron-up',
down: 'fa fa-chevron-down',
previous: 'fa fa-arrow-left',
next: 'fa fa-arrow-right',
today: 'fa fa-crosshairs',
clear: 'fa fa-trash'
},
stepping: stepping
});
$el.addClass('datepicker--enabled');
$addon.on('click', function() {
$input.focus();
});
// Linked datepickers - allow future datetime only - (un)publish modal
if (linkedDatepickerID) {
// set min time only if selected date = today
$(document).on('dp.change', linkedDatepickerID, function(e) {
if (e.target.value === _today.format('DD-MM-YYYY')) {
var selectedTime = window.moment($input.val(), 'HH:mm');
// Force user to select new time, if current time isn't valid anymore
selectedTime.isBefore(_today) && $input.data('DateTimePicker').show();
$input.data('DateTimePicker').minDate(_today);
} else {
$input.data('DateTimePicker').minDate(false);
}
});
}
};
return {
init: init,
reInit: reInit
};
})(jQuery, window);
| mwoynarski/KunstmaanBundlesCMS | src/Kunstmaan/AdminBundle/Resources/ui/js/_datepicker.js | JavaScript | mit | 4,312 |
/**
* Copyright 2015 IBM Corp.
*
* 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 when = require("when");
var clone = require("clone");
var typeRegistry = require("../registry");
var Log = require("../../log");
var redUtil = require("../../util");
var flowUtil = require("./util");
function Flow(global,flow) {
if (typeof flow === 'undefined') {
flow = global;
}
var activeNodes = {};
var subflowInstanceNodes = {};
var catchNodeMap = {};
var statusNodeMap = {};
this.start = function(diff) {
var node;
var newNode;
var id;
catchNodeMap = {};
statusNodeMap = {};
for (id in flow.configs) {
if (flow.configs.hasOwnProperty(id)) {
node = flow.configs[id];
if (!activeNodes[id]) {
newNode = createNode(node.type,node);
if (newNode) {
activeNodes[id] = newNode;
}
}
}
}
if (diff && diff.rewired) {
for (var j=0;j<diff.rewired.length;j++) {
var rewireNode = activeNodes[diff.rewired[j]];
if (rewireNode) {
rewireNode.updateWires(flow.nodes[rewireNode.id].wires);
}
}
}
for (id in flow.nodes) {
if (flow.nodes.hasOwnProperty(id)) {
node = flow.nodes[id];
if (!node.subflow) {
if (!activeNodes[id]) {
newNode = createNode(node.type,node);
if (newNode) {
activeNodes[id] = newNode;
}
}
} else {
if (!subflowInstanceNodes[id]) {
try {
var nodes = createSubflow(flow.subflows[node.subflow]||global.subflows[node.subflow],node,flow.subflows,global.subflows,activeNodes);
subflowInstanceNodes[id] = nodes.map(function(n) { return n.id});
for (var i=0;i<nodes.length;i++) {
if (nodes[i]) {
activeNodes[nodes[i].id] = nodes[i];
}
}
} catch(err) {
console.log(err.stack)
}
}
}
}
}
for (id in activeNodes) {
if (activeNodes.hasOwnProperty(id)) {
node = activeNodes[id];
if (node.type === "catch") {
catchNodeMap[node.z] = catchNodeMap[node.z] || [];
catchNodeMap[node.z].push(node);
} else if (node.type === "status") {
statusNodeMap[node.z] = statusNodeMap[node.z] || [];
statusNodeMap[node.z].push(node);
}
}
}
}
this.stop = function(stopList) {
return when.promise(function(resolve) {
var i;
if (stopList) {
for (i=0;i<stopList.length;i++) {
if (subflowInstanceNodes[stopList[i]]) {
// The first in the list is the instance node we already
// know about
stopList = stopList.concat(subflowInstanceNodes[stopList[i]].slice(1))
}
}
} else {
stopList = Object.keys(activeNodes);
}
var promises = [];
for (i=0;i<stopList.length;i++) {
var node = activeNodes[stopList[i]];
if (node) {
delete activeNodes[stopList[i]];
if (subflowInstanceNodes[stopList[i]]) {
delete subflowInstanceNodes[stopList[i]];
}
try {
var p = node.close();
if (p) {
promises.push(p);
}
} catch(err) {
node.error(err);
}
}
}
when.settle(promises).then(function() {
resolve();
});
});
}
this.update = function(_global,_flow) {
global = _global;
flow = _flow;
}
this.getNode = function(id) {
return activeNodes[id];
}
this.getActiveNodes = function() {
return activeNodes;
}
this.handleStatus = function(node,statusMessage) {
var targetStatusNodes = null;
var reportingNode = node;
var handled = false;
while(reportingNode && !handled) {
targetStatusNodes = statusNodeMap[reportingNode.z];
if (targetStatusNodes) {
targetStatusNodes.forEach(function(targetStatusNode) {
if (targetStatusNode.scope && targetStatusNode.scope.indexOf(node.id) === -1) {
return;
}
var message = {
status: {
text: "",
source: {
id: node.id,
type: node.type,
name: node.name
}
}
};
if (statusMessage.text) {
message.status.text = statusMessage.text;
}
targetStatusNode.receive(message);
handled = true;
});
}
if (!handled) {
reportingNode = activeNodes[reportingNode.z];
}
}
}
this.handleError = function(node,logMessage,msg) {
var count = 1;
if (msg && msg.hasOwnProperty("error")) {
if (msg.error.hasOwnProperty("source")) {
if (msg.error.source.id === node.id) {
count = msg.error.source.count+1;
if (count === 10) {
node.warn(Log._("nodes.flow.error-loop"));
return;
}
}
}
}
var targetCatchNodes = null;
var throwingNode = node;
var handled = false;
while (throwingNode && !handled) {
targetCatchNodes = catchNodeMap[throwingNode.z];
if (targetCatchNodes) {
targetCatchNodes.forEach(function(targetCatchNode) {
if (targetCatchNode.scope && targetCatchNode.scope.indexOf(throwingNode.id) === -1) {
return;
}
var errorMessage;
if (msg) {
errorMessage = redUtil.cloneMessage(msg);
} else {
errorMessage = {};
}
if (errorMessage.hasOwnProperty("error")) {
errorMessage._error = errorMessage.error;
}
errorMessage.error = {
message: logMessage.toString(),
source: {
id: node.id,
type: node.type,
name: node.name,
count: count
}
};
targetCatchNode.receive(errorMessage);
handled = true;
});
}
if (!handled) {
throwingNode = activeNodes[throwingNode.z];
}
}
}
}
var EnvVarPropertyRE = /^\$\((\S+)\)$/;
function mapEnvVarProperties(obj,prop) {
if (Buffer.isBuffer(obj[prop])) {
return;
} else if (Array.isArray(obj[prop])) {
for (var i=0;i<obj[prop].length;i++) {
mapEnvVarProperties(obj[prop],i);
}
} else if (typeof obj[prop] === 'string') {
var m;
if ( (m = EnvVarPropertyRE.exec(obj[prop])) !== null) {
if (process.env.hasOwnProperty(m[1])) {
obj[prop] = process.env[m[1]];
}
}
} else {
for (var p in obj[prop]) {
if (obj[prop].hasOwnProperty) {
mapEnvVarProperties(obj[prop],p);
}
}
}
}
function createNode(type,config) {
var nn = null;
var nt = typeRegistry.get(type);
if (nt) {
var conf = clone(config);
delete conf.credentials;
for (var p in conf) {
if (conf.hasOwnProperty(p)) {
mapEnvVarProperties(conf,p);
}
}
try {
nn = new nt(conf);
}
catch (err) {
Log.log({
level: Log.ERROR,
id:conf.id,
type: type,
msg: err
});
}
} else {
Log.error(Log._("nodes.flow.unknown-type", {type:type}));
}
return nn;
}
function createSubflow(sf,sfn,subflows,globalSubflows,activeNodes) {
//console.log("CREATE SUBFLOW",sf.id,sfn.id);
var nodes = [];
var node_map = {};
var newNodes = [];
var node;
var wires;
var i,j,k;
var createNodeInSubflow = function(def) {
node = clone(def);
var nid = redUtil.generateId();
node_map[node.id] = node;
node._alias = node.id;
node.id = nid;
node.z = sfn.id;
newNodes.push(node);
}
// Clone all of the subflow node definitions and give them new IDs
for (i in sf.configs) {
if (sf.configs.hasOwnProperty(i)) {
createNodeInSubflow(sf.configs[i]);
}
}
// Clone all of the subflow node definitions and give them new IDs
for (i in sf.nodes) {
if (sf.nodes.hasOwnProperty(i)) {
createNodeInSubflow(sf.nodes[i]);
}
}
// Look for any catch/status nodes and update their scope ids
// Update all subflow interior wiring to reflect new node IDs
for (i=0;i<newNodes.length;i++) {
node = newNodes[i];
if (node.wires) {
var outputs = node.wires;
for (j=0;j<outputs.length;j++) {
wires = outputs[j];
for (k=0;k<wires.length;k++) {
outputs[j][k] = node_map[outputs[j][k]].id
}
}
if ((node.type === 'catch' || node.type === 'status') && node.scope) {
node.scope = node.scope.map(function(id) {
return node_map[id]?node_map[id].id:""
})
} else {
for (var prop in node) {
if (node.hasOwnProperty(prop) && prop !== '_alias') {
if (node_map[node[prop]]) {
//console.log("Mapped",node.type,node.id,prop,node_map[node[prop]].id);
node[prop] = node_map[node[prop]].id;
}
}
}
}
}
}
// Create a subflow node to accept inbound messages and route appropriately
var Node = require("../Node");
var subflowInstance = {
id: sfn.id,
type: sfn.type,
z: sfn.z,
name: sfn.name,
wires: []
}
if (sf.in) {
subflowInstance.wires = sf.in.map(function(n) { return n.wires.map(function(w) { return node_map[w.id].id;})})
subflowInstance._originalWires = clone(subflowInstance.wires);
}
var subflowNode = new Node(subflowInstance);
subflowNode.on("input", function(msg) { this.send(msg);});
subflowNode._updateWires = subflowNode.updateWires;
subflowNode.updateWires = function(newWires) {
// Wire the subflow outputs
if (sf.out) {
var node,wires,i,j;
// Restore the original wiring to the internal nodes
subflowInstance.wires = clone(subflowInstance._originalWires);
for (i=0;i<sf.out.length;i++) {
wires = sf.out[i].wires;
for (j=0;j<wires.length;j++) {
if (wires[j].id != sf.id) {
node = node_map[wires[j].id];
if (node._originalWires) {
node.wires = clone(node._originalWires);
}
}
}
}
var modifiedNodes = {};
var subflowInstanceModified = false;
for (i=0;i<sf.out.length;i++) {
wires = sf.out[i].wires;
for (j=0;j<wires.length;j++) {
if (wires[j].id === sf.id) {
subflowInstance.wires[wires[j].port] = subflowInstance.wires[wires[j].port].concat(newWires[i]);
subflowInstanceModified = true;
} else {
node = node_map[wires[j].id];
node.wires[wires[j].port] = node.wires[wires[j].port].concat(newWires[i]);
modifiedNodes[node.id] = node;
}
}
}
Object.keys(modifiedNodes).forEach(function(id) {
var node = modifiedNodes[id];
subflowNode.instanceNodes[id].updateWires(node.wires);
});
if (subflowInstanceModified) {
subflowNode._updateWires(subflowInstance.wires);
}
}
}
nodes.push(subflowNode);
// Wire the subflow outputs
if (sf.out) {
var modifiedNodes = {};
for (i=0;i<sf.out.length;i++) {
wires = sf.out[i].wires;
for (j=0;j<wires.length;j++) {
if (wires[j].id === sf.id) {
// A subflow input wired straight to a subflow output
subflowInstance.wires[wires[j].port] = subflowInstance.wires[wires[j].port].concat(sfn.wires[i])
subflowNode._updateWires(subflowInstance.wires);
} else {
node = node_map[wires[j].id];
modifiedNodes[node.id] = node;
if (!node._originalWires) {
node._originalWires = clone(node.wires);
}
node.wires[wires[j].port] = (node.wires[wires[j].port]||[]).concat(sfn.wires[i]);
}
}
}
}
// Instantiate the nodes
for (i=0;i<newNodes.length;i++) {
node = newNodes[i];
var type = node.type;
var m = /^subflow:(.+)$/.exec(type);
if (!m) {
var newNode = createNode(type,node);
if (newNode) {
activeNodes[node.id] = newNode;
nodes.push(newNode);
}
} else {
var subflowId = m[1];
nodes = nodes.concat(createSubflow(subflows[subflowId]||globalSubflows[subflowId],node,subflows,globalSubflows,activeNodes));
}
}
subflowNode.instanceNodes = {};
nodes.forEach(function(node) {
subflowNode.instanceNodes[node.id] = node;
});
return nodes;
}
module.exports = {
create: function(global,conf) {
return new Flow(global,conf);
}
}
| lemio/w-esp | w-esp-node-red/red/runtime/nodes/flows/Flow.js | JavaScript | gpl-3.0 | 16,004 |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'removeformat', 'en-gb', {
toolbar: 'Remove Format'
} );
| gmuro/dolibarr | htdocs/includes/ckeditor/ckeditor/_source/plugins/removeformat/lang/en-gb.js | JavaScript | gpl-3.0 | 227 |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'flash', 'ku', {
access: 'دەستپێگەیشتنی نووسراو',
accessAlways: 'هەمیشه',
accessNever: 'هەرگیز',
accessSameDomain: 'هەمان دۆمەین',
alignAbsBottom: 'له ژێرەوه',
alignAbsMiddle: 'لەناوەند',
alignBaseline: 'هێڵەبنەڕەت',
alignTextTop: 'دەق لەسەرەوه',
bgcolor: 'ڕەنگی پاشبنەما',
chkFull: 'ڕێپێدان بە پڕی شاشه',
chkLoop: 'گرێ',
chkMenu: 'چالاککردنی لیستەی فلاش',
chkPlay: 'پێکردنی یان لێدانی خۆکار',
flashvars: 'گۆڕاوەکان بۆ فلاش',
hSpace: 'بۆشایی ئاسۆیی',
properties: 'خاسیەتی فلاش',
propertiesTab: 'خاسیەت',
quality: 'جۆرایەتی',
qualityAutoHigh: 'بەرزی خۆکار',
qualityAutoLow: 'نزمی خۆکار',
qualityBest: 'باشترین',
qualityHigh: 'بەرزی',
qualityLow: 'نزم',
qualityMedium: 'مامناوەند',
scale: 'پێوانه',
scaleAll: 'نیشاندانی هەموو',
scaleFit: 'بەوردی بگونجێت',
scaleNoBorder: 'بێ پەراوێز',
title: 'خاسیەتی فلاش',
vSpace: 'بۆشایی ئەستونی',
validateHSpace: 'بۆشایی ئاسۆیی دەبێت ژمارە بێت.',
validateSrc: 'ناونیشانی بەستەر نابێت خاڵی بێت',
validateVSpace: 'بۆشایی ئەستونی دەبێت ژماره بێت.',
windowMode: 'شێوازی پەنجەره',
windowModeOpaque: 'ناڕوون',
windowModeTransparent: 'ڕۆشن',
windowModeWindow: 'پەنجەره'
} );
| gmuro/dolibarr | htdocs/includes/ckeditor/ckeditor/_source/plugins/flash/lang/ku.js | JavaScript | gpl-3.0 | 1,731 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
const path = require("path");
const util = require("util");
const _ = require("lodash");
const webpack = require("webpack");
const TARGET_NAME = "webpack4-babel7";
module.exports = exports = async function(tests, dirname) {
const fixtures = [];
for (const [name, input] of tests) {
if (/typescript-/.test(name)) {
continue;
}
const testFnName = _.camelCase(`${TARGET_NAME}-${name}`);
const evalMaps = name.match(/-eval/);
const babelEnv = !name.match(/-es6/);
const babelModules = name.match(/-cjs/);
console.log(`Building ${TARGET_NAME} test ${name}`);
const scriptPath = path.join(dirname, "output", TARGET_NAME, `${name}.js`);
const result = await util.promisify(webpack)({
mode: "development",
context: path.dirname(input),
entry: `./${path.basename(input)}`,
output: {
path: path.dirname(scriptPath),
filename: path.basename(scriptPath),
devtoolModuleFilenameTemplate: `${TARGET_NAME}://./${name}/[resource-path]`,
libraryTarget: "var",
library: testFnName,
libraryExport: "default"
},
devtool: evalMaps ? "eval-source-map" : "source-map",
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: require.resolve("babel-loader"),
options: {
babelrc: false,
plugins: [
require.resolve("@babel/plugin-proposal-class-properties")
],
presets: [
require.resolve("@babel/preset-flow"),
babelEnv
? [
require.resolve("@babel/preset-env"),
{ modules: babelModules ? "commonjs" : false }
]
: null
].filter(Boolean)
}
}
].filter(Boolean)
}
});
fixtures.push({
name,
testFnName: testFnName,
scriptPath,
assets: [scriptPath, evalMaps ? null : `${scriptPath}.map`].filter(
Boolean
)
});
}
return {
target: TARGET_NAME,
fixtures
};
};
| darkwing/debugger.html | test/mochitest/examples/sourcemapped/builds/webpack4-babel7/index.js | JavaScript | mpl-2.0 | 2,374 |
// DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py.
// OffscreenCanvas test in a worker:2d.gradient.interpolate.solid
// Description:
// Note:
importScripts("/resources/testharness.js");
importScripts("/html/canvas/resources/canvas-tests.js");
var t = async_test("");
var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
throw reason;
});
t.step(function() {
var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');
var g = ctx.createLinearGradient(0, 0, 100, 0);
g.addColorStop(0, '#0f0');
g.addColorStop(1, '#0f0');
ctx.fillStyle = g;
ctx.fillRect(0, 0, 100, 50);
_assertPixel(offscreenCanvas, 50,25, 0,255,0,255, "50,25", "0,255,0,255");
t.done();
});
done();
| nwjs/chromium.src | third_party/blink/web_tests/external/wpt/html/canvas/offscreen/fill-and-stroke-styles/2d.gradient.interpolate.solid.worker.js | JavaScript | bsd-3-clause | 758 |
// 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.
// Copyright 2007 Google Inc. All Rights Reserved.
/**
* @fileoverview A color palette with a button for adding additional colors
* manually.
*
*/
goog.provide('goog.ui.CustomColorPalette');
goog.require('goog.color');
goog.require('goog.dom');
goog.require('goog.ui.ColorPalette');
/**
* A custom color palette is a grid of color swatches and a button that allows
* the user to add additional colors to the palette
*
* @param {Array.<string>} initColors Array of initial colors to populate the
* palette with.
* @param {goog.ui.PaletteRenderer} opt_renderer Renderer used to render or
* decorate the palette; defaults to {@link goog.ui.PaletteRenderer}.
* @param {goog.dom.DomHelper} opt_domHelper Optional DOM helper, used for
* document interaction.
* @constructor
* @extends {goog.ui.ColorPalette}
*/
goog.ui.CustomColorPalette = function(initColors, opt_renderer, opt_domHelper) {
goog.ui.ColorPalette.call(this, initColors, opt_renderer, opt_domHelper);
this.setSupportedState(goog.ui.Component.State.OPENED, true);
};
goog.inherits(goog.ui.CustomColorPalette, goog.ui.ColorPalette);
/**
* Returns an array of DOM nodes for each color, and an additional cell with a
* '+'.
* @return {Array.<Node>} Array of div elements.
* @private
*/
goog.ui.CustomColorPalette.prototype.createColorNodes_ = function() {
/** @desc Hover caption for the button that allows the user to add a color. */
var MSG_CLOSURE_CUSTOM_COLOR_BUTTON = goog.getMsg('Add a color');
var nl = goog.ui.CustomColorPalette.superClass_.createColorNodes_.call(this);
nl.push(goog.dom.createDom('div', {
'class': goog.getCssName('goog-palette-customcolor'),
'title': MSG_CLOSURE_CUSTOM_COLOR_BUTTON
}, '+'));
return nl;
};
/**
* @inheritDoc
* @param {goog.events.Event} e Mouse or key event that triggered the action.
* @return {boolean} True if the action was allowed to proceed, false otherwise.
*/
goog.ui.CustomColorPalette.prototype.performActionInternal = function(e) {
var item = /** @type {Element} */ (this.getHighlightedItem());
if (item) {
if (goog.dom.classes.has(
item, goog.getCssName('goog-palette-customcolor'))) {
// User activated the special "add custom color" swatch.
this.promptForCustomColor();
} else {
// User activated a normal color swatch.
this.setSelectedItem(item);
return this.dispatchEvent(goog.ui.Component.EventType.ACTION);
}
}
return false;
};
/**
* Prompts the user to enter a custom color. Currently uses a window.prompt
* but could be updated to use a dialog box with a WheelColorPalette.
*/
goog.ui.CustomColorPalette.prototype.promptForCustomColor = function() {
/** @desc Default custom color dialog. */
var MSG_CLOSURE_CUSTOM_COLOR_PROMPT = goog.getMsg(
'Input custom color, i.e. pink, #F00, #D015FF or rgb(100, 50, 25)');
// A CustomColorPalette is considered "open" while the color selection prompt
// is open. Enabling state transition events for the OPENED state and
// listening for OPEN events allows clients to save the selection before
// it is destroyed (see e.g. bug 1064701).
var response = null;
this.setOpen(true);
if (this.isOpen()) {
// The OPEN event wasn't canceled; prompt for custom color.
response = window.prompt(MSG_CLOSURE_CUSTOM_COLOR_PROMPT, '#FFFFFF');
this.setOpen(false);
}
if (!response) {
// The user hit cancel
return;
}
var color;
/** @preserveTry */
try {
color = goog.color.parse(response).hex;
} catch (er) {
/** @desc Alert message sent when the input string is not a valid color. */
var MSG_CLOSURE_CUSTOM_COLOR_INVALID_INPUT = goog.getMsg(
'ERROR: "{$color}" is not a valid color.', {'color': response});
alert(MSG_CLOSURE_CUSTOM_COLOR_INVALID_INPUT);
return;
}
// TODO: This is relatively inefficient. Consider adding
// functionality to palette to add individual items after render time.
var colors = this.getColors();
colors.push(color)
this.setColors(colors);
// Set the selected color to the new color and notify listeners of the action.
this.setSelectedColor(color);
this.dispatchEvent(goog.ui.Component.EventType.ACTION);
};
| yesudeep/puppy | tools/google-closure-library/closure/goog/ui/customcolorpalette.js | JavaScript | mit | 4,792 |
/**
* Utility to register editors and common namespace for keeping reference to all editor classes
*/
import Handsontable from './browser';
import {toUpperCaseFirst} from './helpers/string';
export {registerEditor, getEditor, hasEditor, getEditorConstructor};
var
registeredEditorNames = {},
registeredEditorClasses = new WeakMap();
// support for older versions of Handsontable
Handsontable.editors = Handsontable.editors || {};
Handsontable.editors.registerEditor = registerEditor;
Handsontable.editors.getEditor = getEditor;
function RegisteredEditor(editorClass) {
var Clazz, instances;
instances = {};
Clazz = editorClass;
this.getConstructor = function() {
return editorClass;
};
this.getInstance = function(hotInstance) {
if (!(hotInstance.guid in instances)) {
instances[hotInstance.guid] = new Clazz(hotInstance);
}
return instances[hotInstance.guid];
};
}
/**
* Registers editor under given name
* @param {String} editorName
* @param {Function} editorClass
*/
function registerEditor(editorName, editorClass) {
var editor = new RegisteredEditor(editorClass);
if (typeof editorName === 'string') {
registeredEditorNames[editorName] = editor;
Handsontable.editors[toUpperCaseFirst(editorName) + 'Editor'] = editorClass;
}
registeredEditorClasses.set(editorClass, editor);
}
/**
* Returns instance (singleton) of editor class
*
* @param {String} editorName
* @param {Object} hotInstance
* @returns {Function} editorClass
*/
function getEditor(editorName, hotInstance) {
var editor;
if (typeof editorName == 'function') {
if (!(registeredEditorClasses.get(editorName))) {
registerEditor(null, editorName);
}
editor = registeredEditorClasses.get(editorName);
} else if (typeof editorName == 'string') {
editor = registeredEditorNames[editorName];
} else {
throw Error('Only strings and functions can be passed as "editor" parameter ');
}
if (!editor) {
throw Error('No editor registered under name "' + editorName + '"');
}
return editor.getInstance(hotInstance);
}
/**
* Get editor constructor class
*
* @param {String} editorName
* @returns {Function}
*/
function getEditorConstructor(editorName) {
var editor;
if (typeof editorName == 'string') {
editor = registeredEditorNames[editorName];
} else {
throw Error('Only strings and functions can be passed as "editor" parameter ');
}
if (!editor) {
throw Error('No editor registered under name "' + editorName + '"');
}
return editor.getConstructor();
}
/**
* @param editorName
* @returns {Boolean}
*/
function hasEditor(editorName) {
return registeredEditorNames[editorName] ? true : false;
}
| Growmies/handsontable | src/editors.js | JavaScript | mit | 2,723 |
"use strict";
var index_1 = require("../../models/types/index");
function createReferenceType(context, symbol, includeParent) {
var checker = context.checker;
var id = context.getSymbolID(symbol);
var name = checker.symbolToString(symbol);
if (includeParent && symbol.parent) {
name = checker.symbolToString(symbol.parent) + '.' + name;
}
return new index_1.ReferenceType(name, id);
}
exports.createReferenceType = createReferenceType;
//# sourceMappingURL=reference.js.map | glamb/TCMS-Frontend | node_modules/typedoc/lib/converter/factories/reference.js | JavaScript | mit | 505 |
/**
* @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 tape = require( 'tape' );
var mgf = require( './../lib' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.strictEqual( typeof mgf, 'function', 'main export is a function' );
t.end();
});
tape( 'attached to the main export is a factory method for generating `mgf` functions', function test( t ) {
t.equal( typeof mgf.factory, 'function', 'exports a factory method' );
t.end();
});
| stdlib-js/stdlib | lib/node_modules/@stdlib/stats/base/dists/weibull/mgf/test/test.js | JavaScript | apache-2.0 | 1,090 |
/*global app: true, env: true */
/**
Define tags that are known in JSDoc.
@module jsdoc/tag/dictionary/definitions
@author Michael Mathews <[email protected]>
@license Apache License 2.0 - See file 'LICENSE.md' in this project.
*/
'use strict';
var logger = require('jsdoc/util/logger');
var path = require('jsdoc/path');
var Syntax = require('jsdoc/src/syntax').Syntax;
function getSourcePaths() {
var sourcePaths = env.sourceFiles.slice(0) || [];
if (env.opts._) {
env.opts._.forEach(function(sourcePath) {
var resolved = path.resolve(env.pwd, sourcePath);
if (sourcePaths.indexOf(resolved) === -1) {
sourcePaths.push(resolved);
}
});
}
return sourcePaths;
}
function filepathMinusPrefix(filepath) {
var sourcePaths = getSourcePaths();
var commonPrefix = path.commonPrefix(sourcePaths);
var result = '';
if (filepath) {
// always use forward slashes
result = (filepath + path.sep).replace(commonPrefix, '')
.replace(/\\/g, '/');
}
if (result.length > 0 && result[result.length - 1] !== '/') {
result += '/';
}
return result;
}
/** @private */
function setDocletKindToTitle(doclet, tag) {
doclet.addTag( 'kind', tag.title );
}
function setDocletScopeToTitle(doclet, tag) {
try {
doclet.setScope(tag.title);
}
catch(e) {
logger.error(e.message);
}
}
function setDocletNameToValue(doclet, tag) {
if (tag.value && tag.value.description) { // as in a long tag
doclet.addTag( 'name', tag.value.description);
}
else if (tag.text) { // or a short tag
doclet.addTag('name', tag.text);
}
}
function setDocletNameToValueName(doclet, tag) {
if (tag.value && tag.value.name) {
doclet.addTag('name', tag.value.name);
}
}
function setDocletDescriptionToValue(doclet, tag) {
if (tag.value) {
doclet.addTag( 'description', tag.value );
}
}
function setDocletTypeToValueType(doclet, tag) {
if (tag.value && tag.value.type) {
doclet.type = tag.value.type;
}
}
function setNameToFile(doclet, tag) {
var name;
if (doclet.meta.filename) {
name = filepathMinusPrefix(doclet.meta.path) + doclet.meta.filename;
doclet.addTag('name', name);
}
}
function setDocletMemberof(doclet, tag) {
if (tag.value && tag.value !== '<global>') {
doclet.setMemberof(tag.value);
}
}
function applyNamespace(docletOrNs, tag) {
if (typeof docletOrNs === 'string') { // ns
tag.value = app.jsdoc.name.applyNamespace(tag.value, docletOrNs);
}
else { // doclet
if (!docletOrNs.name) {
return; // error?
}
//doclet.displayname = doclet.name;
docletOrNs.longname = app.jsdoc.name.applyNamespace(docletOrNs.name, tag.title);
}
}
function setDocletNameToFilename(doclet, tag) {
var name = '';
if (doclet.meta.path) {
name = filepathMinusPrefix(doclet.meta.path);
}
name += doclet.meta.filename.replace(/\.js$/i, '');
doclet.name = name;
}
function parseBorrows(doclet, tag) {
var m = /^(\S+)(?:\s+as\s+(\S+))?$/.exec(tag.text);
if (m) {
if (m[1] && m[2]) {
return { target: m[1], source: m[2] };
}
else if (m[1]) {
return { target: m[1] };
}
} else {
return {};
}
}
function firstWordOf(string) {
var m = /^(\S+)/.exec(string);
if (m) { return m[1]; }
else { return ''; }
}
/** Populate the given dictionary with all known JSDoc tag definitions.
@param {module:jsdoc/tag/dictionary} dictionary
*/
exports.defineTags = function(dictionary) {
dictionary.defineTag('abstract', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
// since "abstract" is reserved word in JavaScript let's use "virtual" in code
doclet.virtual = true;
}
})
.synonym('virtual');
dictionary.defineTag('access', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
// only valid values are private and protected, public is default
if ( /^(private|protected)$/i.test(tag.value) ) {
doclet.access = tag.value.toLowerCase();
}
else {
delete doclet.access;
}
}
});
dictionary.defineTag('alias', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet.alias = tag.value;
}
});
// Special separator tag indicating that multiple doclets should be generated for the same
// comment. Used internally (and by some JSDoc users, although it's not officially supported).
//
// In the following example, the parser will replace `//**` with an `@also` tag:
//
// /**
// * Foo.
// *//**
// * Foo with a param.
// * @param {string} bar
// */
// function foo(bar) {}
dictionary.defineTag('also', {
onTagged: function(doclet, tag) {
// let the parser handle it; we define the tag here to avoid "not a known tag" errors
}
});
// this symbol inherits from the specified symbol
dictionary.defineTag('augments', {
mustHaveValue: true,
// Allow augments value to be specified as a normal type, e.g. {Type}
onTagText: function(text) {
var type = require('jsdoc/tag/type'),
tagType = type.parse(text, false, true);
return tagType.typeExpression || text;
},
onTagged: function(doclet, tag) {
doclet.augment( firstWordOf(tag.value) );
}
})
.synonym('extends');
dictionary.defineTag('author', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
if (!doclet.author) { doclet.author = []; }
doclet.author.push(tag.value);
}
});
// this symbol has a member that should use the same docs as another symbol
dictionary.defineTag('borrows', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
var borrows = parseBorrows(doclet, tag);
doclet.borrow(borrows.target, borrows.source);
}
});
dictionary.defineTag('class', {
onTagged: function(doclet, tag) {
doclet.addTag('kind', 'class');
// handle special case where both @class and @constructor tags exist in same doclet
if (tag.originalTitle === 'class') {
var looksLikeDesc = (tag.value || '').match(/\S+\s+\S+/); // multiple words after @class?
if ( looksLikeDesc || /@construct(s|or)\b/i.test(doclet.comment) ) {
doclet.classdesc = tag.value; // treat the @class tag as a @classdesc tag instead
return;
}
}
setDocletNameToValue(doclet, tag);
}
})
.synonym('constructor');
dictionary.defineTag('classdesc', {
onTagged: function(doclet, tag) {
doclet.classdesc = tag.value;
}
});
dictionary.defineTag('constant', {
canHaveType: true,
canHaveName: true,
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
setDocletNameToValueName(doclet, tag);
setDocletTypeToValueType(doclet, tag);
}
})
.synonym('const');
dictionary.defineTag('constructs', {
onTagged: function(doclet, tag) {
var ownerClassName;
if (!tag.value) {
ownerClassName = '{@thisClass}'; // this can be resolved later in the handlers
}
else {
ownerClassName = firstWordOf(tag.value);
}
doclet.addTag('alias', ownerClassName);
doclet.addTag('kind', 'class');
}
});
dictionary.defineTag('copyright', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet.copyright = tag.value;
}
});
dictionary.defineTag('default', {
onTagged: function(doclet, tag) {
var type;
var value;
if (tag.value) {
doclet.defaultvalue = tag.value;
}
else if (doclet.meta && doclet.meta.code && doclet.meta.code.value) {
type = doclet.meta.code.type;
value = doclet.meta.code.value;
if (type === Syntax.Literal) {
doclet.defaultvalue = String(value);
}
// TODO: reenable the changes for https://github.com/jsdoc3/jsdoc/pull/419
/*
else if (doclet.meta.code.type === 'OBJECTLIT') {
doclet.defaultvalue = String(doclet.meta.code.node.toSource());
doclet.defaultvaluetype = 'object';
}
*/
}
}
})
.synonym('defaultvalue');
dictionary.defineTag('deprecated', {
// value is optional
onTagged: function(doclet, tag) {
doclet.deprecated = tag.value || true;
}
});
dictionary.defineTag('description', {
mustHaveValue: true
})
.synonym('desc');
dictionary.defineTag('enum', {
canHaveType: true,
onTagged: function(doclet, tag) {
doclet.kind = 'member';
doclet.isEnum = true;
setDocletTypeToValueType(doclet, tag);
}
});
dictionary.defineTag('event', {
isNamespace: true,
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
setDocletNameToValue(doclet, tag);
}
});
dictionary.defineTag('example', {
keepsWhitespace: true,
removesIndent: true,
mustHaveValue: true,
onTagged: function(doclet, tag) {
if (!doclet.examples) { doclet.examples = []; }
doclet.examples.push(tag.value);
}
});
dictionary.defineTag('exception', {
mustHaveValue: true,
canHaveType: true,
onTagged: function(doclet, tag) {
if (!doclet.exceptions) { doclet.exceptions = []; }
doclet.exceptions.push(tag.value);
setDocletTypeToValueType(doclet, tag);
}
})
.synonym('throws');
dictionary.defineTag('exports', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
var modName = firstWordOf(tag.value);
doclet.addTag('alias', modName);
doclet.addTag('kind', 'module');
}
});
dictionary.defineTag('external', {
canHaveType: true,
isNamespace: true,
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
if (tag.value && tag.value.type) {
setDocletTypeToValueType(doclet, tag);
doclet.addTag('name', doclet.type.names[0]);
}
}
})
.synonym('host');
dictionary.defineTag('file', {
onTagged: function(doclet, tag) {
setNameToFile(doclet, tag);
setDocletKindToTitle(doclet, tag);
setDocletDescriptionToValue(doclet, tag);
doclet.preserveName = true;
}
})
.synonym('fileoverview')
.synonym('overview');
dictionary.defineTag('fires', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
if (!doclet.fires) { doclet.fires = []; }
applyNamespace('event', tag);
doclet.fires.push(tag.value);
}
})
.synonym('emits');
dictionary.defineTag('function', {
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
setDocletNameToValue(doclet, tag);
}
})
.synonym('func')
.synonym('method');
dictionary.defineTag('global', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
doclet.scope = 'global';
delete doclet.memberof;
}
});
dictionary.defineTag('ignore', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
doclet.ignore = true;
}
});
dictionary.defineTag('inner', {
onTagged: function(doclet, tag) {
setDocletScopeToTitle(doclet, tag);
}
});
dictionary.defineTag('instance', {
onTagged: function(doclet, tag) {
setDocletScopeToTitle(doclet, tag);
}
});
dictionary.defineTag('kind', {
mustHaveValue: true
});
dictionary.defineTag('lends', {
onTagged: function(doclet, tag) {
var GLOBAL_LONGNAME = require('jsdoc/doclet').GLOBAL_LONGNAME;
doclet.alias = tag.value || GLOBAL_LONGNAME;
doclet.addTag('undocumented');
}
});
dictionary.defineTag('license', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet.license = tag.value;
}
});
dictionary.defineTag('listens', {
mustHaveValue: true,
onTagged: function (doclet, tag) {
if (!doclet.listens) { doclet.listens = []; }
applyNamespace('event', tag);
doclet.listens.push(tag.value);
// TODO: verify that parameters match the event parameters?
}
});
dictionary.defineTag('member', {
canHaveType: true,
canHaveName: true,
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
setDocletNameToValueName(doclet, tag);
setDocletTypeToValueType(doclet, tag);
}
})
.synonym('var');
dictionary.defineTag('memberof', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
var GLOBAL_LONGNAME = require('jsdoc/doclet').GLOBAL_LONGNAME;
if (tag.originalTitle === 'memberof!') {
doclet.forceMemberof = true;
if (tag.value === GLOBAL_LONGNAME) {
doclet.addTag('global');
delete doclet.memberof;
}
}
setDocletMemberof(doclet, tag);
}
})
.synonym('memberof!');
// this symbol mixes in all of the specified object's members
dictionary.defineTag('mixes', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
var source = firstWordOf(tag.value);
doclet.mix(source);
}
});
dictionary.defineTag('mixin', {
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
setDocletNameToValue(doclet, tag);
}
});
dictionary.defineTag('module', {
canHaveType: true,
isNamespace: true,
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
setDocletNameToValue(doclet, tag);
if (!doclet.name) {
setDocletNameToFilename(doclet, tag);
}
setDocletTypeToValueType(doclet, tag);
}
});
dictionary.defineTag('name', {
mustHaveValue: true
});
dictionary.defineTag('namespace', {
canHaveType: true,
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
setDocletNameToValue(doclet, tag);
setDocletTypeToValueType(doclet, tag);
}
});
dictionary.defineTag('param', {
//mustHaveValue: true, // param name can be found in the source code if not provided
canHaveType: true,
canHaveName: true,
onTagged: function(doclet, tag) {
if (!doclet.params) { doclet.params = []; }
doclet.params.push(tag.value||{});
}
})
.synonym('argument')
.synonym('arg');
dictionary.defineTag('private', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
doclet.access = 'private';
}
});
dictionary.defineTag('property', {
mustHaveValue: true,
canHaveType: true,
canHaveName: true,
onTagged: function(doclet, tag) {
if (!doclet.properties) { doclet.properties = []; }
doclet.properties.push(tag.value);
}
})
.synonym('prop');
dictionary.defineTag('protected', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
doclet.access = 'protected';
}
});
dictionary.defineTag('public', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
delete doclet.access; // public is default
}
});
// use this instead of old deprecated @final tag
dictionary.defineTag('readonly', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
doclet.readonly = true;
}
});
dictionary.defineTag('requires', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
var requiresName;
var MODULE_PREFIX = require('jsdoc/name').MODULE_PREFIX;
// inline link tags are passed through as-is so that `@requires {@link foo}` works
if ( require('jsdoc/tag/inline').isInlineTag(tag.value, 'link\\S*') ) {
requiresName = tag.value;
}
// otherwise, assume it's a module
else {
requiresName = firstWordOf(tag.value);
if (requiresName.indexOf(MODULE_PREFIX) !== 0) {
requiresName = MODULE_PREFIX + requiresName;
}
}
if (!doclet.requires) { doclet.requires = []; }
doclet.requires.push(requiresName);
}
});
dictionary.defineTag('returns', {
mustHaveValue: true,
canHaveType: true,
onTagged: function(doclet, tag) {
if (!doclet.returns) { doclet.returns = []; }
doclet.returns.push(tag.value);
}
})
.synonym('return');
dictionary.defineTag('see', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
if (!doclet.see) { doclet.see = []; }
doclet.see.push(tag.value);
}
});
dictionary.defineTag('since', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet.since = tag.value;
}
});
dictionary.defineTag('static', {
onTagged: function(doclet, tag) {
setDocletScopeToTitle(doclet, tag);
}
});
dictionary.defineTag('summary', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet.summary = tag.value;
}
});
dictionary.defineTag('this', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet['this'] = firstWordOf(tag.value);
}
});
dictionary.defineTag('todo', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
if (!doclet.todo) { doclet.todo = []; }
doclet.todo.push(tag.value);
}
});
dictionary.defineTag('tutorial', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
if (!doclet.tutorials) { doclet.tutorials = []; }
doclet.tutorials.push(tag.value);
}
});
dictionary.defineTag('type', {
mustHaveValue: true,
canHaveType: true,
onTagText: function(text) {
// remove line breaks so we can parse the type expression correctly
text = text.replace(/[\n\r]/g, '');
// any text must be formatted as a type, but for back compat braces are optional
if ( !/^\{[\s\S]+\}$/.test(text) ) {
text = '{' + text + '}';
}
return text;
},
onTagged: function(doclet, tag) {
if (tag.value && tag.value.type) {
setDocletTypeToValueType(doclet, tag);
// for backwards compatibility, we allow @type for functions to imply return type
if (doclet.kind === 'function') {
doclet.addTag('returns', tag.text);
}
}
}
});
dictionary.defineTag('typedef', {
canHaveType: true,
canHaveName: true,
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
if (tag.value) {
setDocletNameToValueName(doclet, tag);
// callbacks are always type {function}
if (tag.originalTitle === 'callback') {
doclet.type = {
names: [
'function'
]
};
}
else {
setDocletTypeToValueType(doclet, tag);
}
}
}
})
.synonym('callback');
dictionary.defineTag('undocumented', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
doclet.undocumented = true;
doclet.comment = '';
}
});
dictionary.defineTag('variation', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet.variation = tag.value;
}
});
dictionary.defineTag('version', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet.version = tag.value;
}
});
};
| ad-l/djcl | tools/jsdoc/lib/jsdoc/tag/dictionary/definitions.js | JavaScript | bsd-2-clause | 21,625 |
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
* @emails oncall+javascript_foundation
*/
'use strict';
jest.mock('fs');
const getProjectConfig = require('../../ios').projectConfig;
const fs = require('fs');
const projects = require('../../__fixtures__/projects');
describe('ios::getProjectConfig', () => {
const userConfig = {};
beforeEach(() => {
fs.__setMockFilesystem({testDir: projects});
});
it('returns an object with ios project configuration', () => {
const folder = '/testDir/nested';
expect(getProjectConfig(folder, userConfig)).not.toBeNull();
expect(typeof getProjectConfig(folder, userConfig)).toBe('object');
});
it('returns `null` if ios project was not found', () => {
const folder = '/testDir/empty';
expect(getProjectConfig(folder, userConfig)).toBeNull();
});
it('returns normalized shared library names', () => {
const projectConfig = getProjectConfig('/testDir/nested', {
sharedLibraries: ['libc++', 'libz.tbd', 'HealthKit', 'HomeKit.framework'],
});
expect(projectConfig.sharedLibraries).toEqual([
'libc++.tbd',
'libz.tbd',
'HealthKit.framework',
'HomeKit.framework',
]);
});
});
| Bhullnatik/react-native | local-cli/core/__tests__/ios/getProjectConfig.spec.js | JavaScript | bsd-3-clause | 1,475 |
// Test that constructor for the node with name |nodeName| handles the
// various possible values for channelCount, channelCountMode, and
// channelInterpretation.
// The |should| parameter is the test function from new |Audit|.
function testAudioNodeOptions(should, context, nodeName, expectedNodeOptions) {
if (expectedNodeOptions === undefined)
expectedNodeOptions = {};
let node;
// Test that we can set channelCount and that errors are thrown for
// invalid values
let testChannelCount = 17;
if (expectedNodeOptions.channelCount) {
testChannelCount = expectedNodeOptions.channelCount.value;
}
should(
() => {
node = new window[nodeName](
context, Object.assign({}, expectedNodeOptions.additionalOptions, {
channelCount: testChannelCount
}));
},
'new ' + nodeName + '(c, {channelCount: ' + testChannelCount + '}}')
.notThrow();
should(node.channelCount, 'node.channelCount').beEqualTo(testChannelCount);
if (expectedNodeOptions.channelCount &&
expectedNodeOptions.channelCount.isFixed) {
// The channel count is fixed. Verify that we throw an error if
// we try to change it. Arbitrarily set the count to be one more
// than the expected value.
testChannelCount = expectedNodeOptions.channelCount.value + 1;
should(
() => {
node = new window[nodeName](
context,
Object.assign(
{}, expectedNodeOptions.additionalOptions,
{channelCount: testChannelCount}));
},
'new ' + nodeName + '(c, {channelCount: ' + testChannelCount + '}}')
.throw(expectedNodeOptions.channelCount.errorType || TypeError);
} else {
// The channel count is not fixed. Try to set the count to invalid
// values and make sure an error is thrown.
[0, 99].forEach(testValue => {
should(() => {
node = new window[nodeName](
context, Object.assign({}, expectedNodeOptions.additionalOptions, {
channelCount: testValue
}));
}, `new ${nodeName}(c, {channelCount: ${testValue}})`)
.throw(DOMException, 'NotSupportedError');
});
}
// Test channelCountMode
let testChannelCountMode = 'max';
if (expectedNodeOptions.channelCountMode) {
testChannelCountMode = expectedNodeOptions.channelCountMode.value;
}
should(
() => {
node = new window[nodeName](
context, Object.assign({}, expectedNodeOptions.additionalOptions, {
channelCountMode: testChannelCountMode
}));
},
'new ' + nodeName + '(c, {channelCountMode: "' + testChannelCountMode +
'"}')
.notThrow();
should(node.channelCountMode, 'node.channelCountMode')
.beEqualTo(testChannelCountMode);
if (expectedNodeOptions.channelCountMode &&
expectedNodeOptions.channelCountMode.isFixed) {
// Channel count mode is fixed. Test setting to something else throws.
['max', 'clamped-max', 'explicit'].forEach(testValue => {
if (testValue !== expectedNodeOptions.channelCountMode.value) {
should(
() => {
node = new window[nodeName](
context,
Object.assign(
{}, expectedNodeOptions.additionalOptions,
{channelCountMode: testValue}));
},
`new ${nodeName}(c, {channelCountMode: "${testValue}"})`)
.throw(expectedNodeOptions.channelCountMode.errorType);
}
});
} else {
// Mode is not fixed. Verify that we can set the mode to all valid
// values, and that we throw for invalid values.
let testValues = ['max', 'clamped-max', 'explicit'];
testValues.forEach(testValue => {
should(() => {
node = new window[nodeName](
context, Object.assign({}, expectedNodeOptions.additionalOptions, {
channelCountMode: testValue
}));
}, `new ${nodeName}(c, {channelCountMode: "${testValue}"})`).notThrow();
should(
node.channelCountMode, 'node.channelCountMode after valid setter')
.beEqualTo(testValue);
});
should(
() => {
node = new window[nodeName](
context,
Object.assign(
{}, expectedNodeOptions.additionalOptions,
{channelCountMode: 'foobar'}));
},
'new ' + nodeName + '(c, {channelCountMode: "foobar"}')
.throw(TypeError);
should(node.channelCountMode, 'node.channelCountMode after invalid setter')
.beEqualTo(testValues[testValues.length - 1]);
}
// Test channelInterpretation
if (expectedNodeOptions.channelInterpretation &&
expectedNodeOptions.channelInterpretation.isFixed) {
// The channel interpretation is fixed. Verify that we throw an
// error if we try to change it.
['speakers', 'discrete'].forEach(testValue => {
if (testValue !== expectedNodeOptions.channelInterpretation.value) {
should(
() => {
node = new window[nodeName](
context,
Object.assign(
{}, expectedNodeOptions.additionOptions,
{channelInterpretation: testValue}));
},
`new ${nodeName}(c, {channelInterpretation: "${testValue}"})`)
.throw(expectedNodeOptions.channelInterpretation.errorType);
}
});
} else {
// Channel interpretation is not fixed. Verify that we can set it
// to all possible values.
should(
() => {
node = new window[nodeName](
context,
Object.assign(
{}, expectedNodeOptions.additionalOptions,
{channelInterpretation: 'speakers'}));
},
'new ' + nodeName + '(c, {channelInterpretation: "speakers"})')
.notThrow();
should(node.channelInterpretation, 'node.channelInterpretation')
.beEqualTo('speakers');
should(
() => {
node = new window[nodeName](
context,
Object.assign(
{}, expectedNodeOptions.additionalOptions,
{channelInterpretation: 'discrete'}));
},
'new ' + nodeName + '(c, {channelInterpretation: "discrete"})')
.notThrow();
should(node.channelInterpretation, 'node.channelInterpretation')
.beEqualTo('discrete');
should(
() => {
node = new window[nodeName](
context,
Object.assign(
{}, expectedNodeOptions.additionalOptions,
{channelInterpretation: 'foobar'}));
},
'new ' + nodeName + '(c, {channelInterpretation: "foobar"})')
.throw(TypeError);
should(
node.channelInterpretation,
'node.channelInterpretation after invalid setter')
.beEqualTo('discrete');
}
}
function initializeContext(should) {
let c;
should(() => {
c = new OfflineAudioContext(1, 1, 48000);
}, 'context = new OfflineAudioContext(...)').notThrow();
return c;
}
function testInvalidConstructor(should, name, context) {
should(() => {
new window[name]();
}, 'new ' + name + '()').throw(TypeError);
should(() => {
new window[name](1);
}, 'new ' + name + '(1)').throw(TypeError);
should(() => {
new window[name](context, 42);
}, 'new ' + name + '(context, 42)').throw(TypeError);
}
function testDefaultConstructor(should, name, context, options) {
let node;
let message = options.prefix + ' = new ' + name + '(context';
if (options.constructorOptions)
message += ', ' + JSON.stringify(options.constructorOptions);
message += ')'
should(() => {
node = new window[name](context, options.constructorOptions);
}, message).notThrow();
should(node instanceof window[name], options.prefix + ' instanceof ' + name)
.beEqualTo(true);
should(node.numberOfInputs, options.prefix + '.numberOfInputs')
.beEqualTo(options.numberOfInputs);
should(node.numberOfOutputs, options.prefix + '.numberOfOutputs')
.beEqualTo(options.numberOfOutputs);
should(node.channelCount, options.prefix + '.channelCount')
.beEqualTo(options.channelCount);
should(node.channelCountMode, options.prefix + '.channelCountMode')
.beEqualTo(options.channelCountMode);
should(node.channelInterpretation, options.prefix + '.channelInterpretation')
.beEqualTo(options.channelInterpretation);
return node;
}
function testDefaultAttributes(should, node, prefix, items) {
items.forEach((item) => {
let attr = node[item.name];
if (attr instanceof AudioParam) {
should(attr.value, prefix + '.' + item.name + '.value')
.beEqualTo(item.value);
} else {
should(attr, prefix + '.' + item.name).beEqualTo(item.value);
}
});
}
| scheib/chromium | third_party/blink/web_tests/webaudio/resources/audionodeoptions.js | JavaScript | bsd-3-clause | 8,919 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is JavaScript Engine testing utilities.
*
* The Initial Developer of the Original Code is
* Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Norris Boyd
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
//-----------------------------------------------------------------------------
var BUGNUMBER = 392308;
var summary = 'StopIteration should be catchable';
var actual = '';
var expect = '';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
function testStop() {
function yielder() {
actual += 'before, ';
yield;
actual += 'after, ';
}
expect = 'before, after, iteration terminated normally';
try {
var gen = yielder();
result = gen.next();
gen.send(result);
} catch (x if x instanceof StopIteration) {
actual += 'iteration terminated normally';
} catch (x2) {
actual += 'unexpected throw: ' + x2;
}
}
testStop();
reportCompare(expect, actual, summary);
exitFunc ('test');
}
| darkrsw/safe | tests/browser_extensions/js1_7/extensions/XXXregress-392308.js | JavaScript | bsd-3-clause | 2,774 |
/**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
goog.module('goog.dom.SavedCaretRangeTest');
goog.setTestOnly();
const Range = goog.require('goog.dom.Range');
const SavedCaretRange = goog.require('goog.dom.SavedCaretRange');
const dom = goog.require('goog.dom');
const testSuite = goog.require('goog.testing.testSuite');
const testingDom = goog.require('goog.testing.dom');
const userAgent = goog.require('goog.userAgent');
/*
TODO(user): Look into why removeCarets test doesn't pass.
function testRemoveCarets() {
var def = goog.dom.getElement('def');
var jkl = goog.dom.getElement('jkl');
var range = goog.dom.Range.createFromNodes(
def.firstChild, 1, jkl.firstChild, 2);
range.select();
var saved = range.saveUsingCarets();
assertHTMLEquals(
"d<span id="" + saved.startCaretId_ + ""></span>ef", def.innerHTML);
assertHTMLEquals(
"jk<span id="" + saved.endCaretId_ + ""></span>l", jkl.innerHTML);
saved.removeCarets();
assertHTMLEquals("def", def.innerHTML);
assertHTMLEquals("jkl", jkl.innerHTML);
var selection = goog.dom.Range.createFromWindow(window);
assertEquals('Wrong start node', def.firstChild, selection.getStartNode());
assertEquals('Wrong end node', jkl.firstChild, selection.getEndNode());
assertEquals('Wrong start offset', 1, selection.getStartOffset());
assertEquals('Wrong end offset', 2, selection.getEndOffset());
}
*/
/**
* Clear the selection by re-parsing the DOM. Then restore the saved
* selection.
* @param {Node} parent The node containing the current selection.
* @param {dom.SavedRange} saved The saved range.
* @return {dom.AbstractRange} Restored range.
*/
function clearSelectionAndRestoreSaved(parent, saved) {
Range.clearSelection();
assertFalse(Range.hasSelection(window));
const range = saved.restore();
assertTrue(Range.hasSelection(window));
return range;
}
testSuite({
setUp() {
document.body.normalize();
},
/** @bug 1480638 */
testSavedCaretRangeDoesntChangeSelection() {
// NOTE(nicksantos): We cannot detect this bug programatically. The only
// way to detect it is to run this test manually and look at the selection
// when it ends.
const div = dom.getElement('bug1480638');
const range = Range.createFromNodes(div.firstChild, 0, div.lastChild, 1);
range.select();
// Observe visible selection. Then move to next line and see it change.
// If the bug exists, it starts with "foo" selected and ends with
// it not selected.
// debugger;
const saved = range.saveUsingCarets();
},
/**
@suppress {strictMissingProperties} suppression added to enable type
checking
*/
testSavedCaretRange() {
if (userAgent.IE && !userAgent.isDocumentModeOrHigher(8)) {
// testSavedCaretRange fails in IE7 unless the source files are loaded in
// a certain order. Adding goog.require('goog.dom.classes') to dom.js or
// goog.require('goog.array') to savedcaretrange_test.js after the
// goog.require('goog.dom') line fixes the test, but it's better to not
// rely on such hacks without understanding the reason of the failure.
return;
}
const parent = dom.getElement('caretRangeTest');
let def = dom.getElement('def');
let jkl = dom.getElement('jkl');
const range = Range.createFromNodes(def.firstChild, 1, jkl.firstChild, 2);
assertFalse(range.isReversed());
range.select();
const saved = range.saveUsingCarets();
assertHTMLEquals(
'd<span id="' + saved.startCaretId_ + '"></span>ef', def.innerHTML);
assertHTMLEquals(
'jk<span id="' + saved.endCaretId_ + '"></span>l', jkl.innerHTML);
testingDom.assertRangeEquals(
def.childNodes[1], 0, jkl.childNodes[1], 0, saved.toAbstractRange());
def = dom.getElement('def');
jkl = dom.getElement('jkl');
const restoredRange = clearSelectionAndRestoreSaved(parent, saved);
assertFalse(restoredRange.isReversed());
testingDom.assertRangeEquals(def, 1, jkl, 1, restoredRange);
const selection = Range.createFromWindow(window);
assertHTMLEquals('def', def.innerHTML);
assertHTMLEquals('jkl', jkl.innerHTML);
// def and jkl now contain fragmented text nodes.
const endNode = selection.getEndNode();
if (endNode == jkl.childNodes[0]) {
// Webkit (up to Chrome 57) and IE < 9.
testingDom.assertRangeEquals(
def.childNodes[1], 0, jkl.childNodes[0], 2, selection);
} else if (endNode == jkl.childNodes[1]) {
// Opera
testingDom.assertRangeEquals(
def.childNodes[1], 0, jkl.childNodes[1], 0, selection);
} else {
// Gecko, newer Chromes
testingDom.assertRangeEquals(def, 1, jkl, 1, selection);
}
},
testReversedSavedCaretRange() {
const parent = dom.getElement('caretRangeTest');
const def = dom.getElement('def-5');
const jkl = dom.getElement('jkl-5');
const range = Range.createFromNodes(jkl.firstChild, 1, def.firstChild, 2);
assertTrue(range.isReversed());
range.select();
const saved = range.saveUsingCarets();
const restoredRange = clearSelectionAndRestoreSaved(parent, saved);
assertTrue(restoredRange.isReversed());
testingDom.assertRangeEquals(def, 1, jkl, 1, restoredRange);
},
testRemoveContents() {
const def = dom.getElement('def-4');
const jkl = dom.getElement('jkl-4');
// Sanity check.
const container = dom.getElement('removeContentsTest');
assertEquals(7, container.childNodes.length);
assertEquals('def', def.innerHTML);
assertEquals('jkl', jkl.innerHTML);
const range = Range.createFromNodes(def.firstChild, 1, jkl.firstChild, 2);
range.select();
const saved = range.saveUsingCarets();
const restored = saved.restore();
restored.removeContents();
assertEquals(6, container.childNodes.length);
assertEquals('d', def.innerHTML);
assertEquals('l', jkl.innerHTML);
},
testHtmlEqual() {
const parent = dom.getElement('caretRangeTest-2');
const def = dom.getElement('def-2');
const jkl = dom.getElement('jkl-2');
const range = Range.createFromNodes(def.firstChild, 1, jkl.firstChild, 2);
range.select();
const saved = range.saveUsingCarets();
const html1 = parent.innerHTML;
saved.removeCarets();
const saved2 = range.saveUsingCarets();
const html2 = parent.innerHTML;
saved2.removeCarets();
assertNotEquals(
'Same selection with different saved caret range carets ' +
'must have different html.',
html1, html2);
assertTrue(
'Same selection with different saved caret range carets must ' +
'be considered equal by htmlEqual',
SavedCaretRange.htmlEqual(html1, html2));
saved.dispose();
saved2.dispose();
},
testStartCaretIsAtEndOfParent() {
const parent = dom.getElement('caretRangeTest-3');
const def = dom.getElement('def-3');
const jkl = dom.getElement('jkl-3');
let range = Range.createFromNodes(def, 1, jkl, 1);
range.select();
const saved = range.saveUsingCarets();
clearSelectionAndRestoreSaved(parent, saved);
range = Range.createFromWindow();
assertEquals('ghijkl', range.getText().replace(/\s/g, ''));
},
});
| nwjs/chromium.src | third_party/google-closure-library/closure/goog/dom/savedcaretrange_test.js | JavaScript | bsd-3-clause | 7,324 |
// This file was generated by the _js_query_arg_file Skylark rule defined in
// maps/vectortown/performance/script/build_defs.bzl.
var testConfig = "overridePixelRatio=1&title=chrome_smoothness_performancetest_config&nobudget=false&nodraw=false&noprefetch=true&viewport=basic&wait=true";
| scheib/chromium | tools/perf/page_sets/maps_perf_test/config.js | JavaScript | bsd-3-clause | 289 |
var assert = require('assert');
var appHelper = require('./helpers/appHelper');
var path = require('path');
var fs = require('fs');
describe('Configs', function() {
this.timeout(30000);
var appName = 'testApp';
var config;
var sailsserver;
var up = false;
describe('in production env', function () {
before(function(done) {
// build app
appHelper.build(function(err) {
if (err) return done(err);
process.chdir(appName);
// Start sails and pass it command line arguments
require(path.resolve('./../lib')).lift({
// Override memorystore with `{session:{adapter: null}}`
session: {
adapter: null
}
}, function(err, sails) {
if (err) return done(err);
up = true;
config = sails.config;
sailsserver = sails;
done();
});
});
});
after(function() {
sailsserver.lower(function() {
// Not sure why this runs multiple times, but checking "up" makes
// sure we only do chdir once
sailsserver.removeAllListeners();
if (up === true) {
up = false;
process.chdir('../');
appHelper.teardown();
}
});
});
it('should retain legacy `config.adapters` for backwards compat.', function() {
var legacyConfig = config.adapters;
assert(legacyConfig.custom && legacyConfig.custom.module === 'sails-disk');
assert(legacyConfig.sqlite.module === 'sails-sqlite');
assert(legacyConfig.sqlite.host === 'sqliteHOST');
assert(legacyConfig.sqlite.user === 'sqliteUSER');
});
// it('should load connection configs', function() {
// var connectionsConfig = config.connections;
// assert(config.model.adapter === 'sails-disk');
// assert(connectionsConfig.custom && connectionsConfig.custom.module === 'sails-disk');
// assert(connectionsConfig.sqlite.module === 'sails-sqlite');
// assert(connectionsConfig.sqlite.host === 'sqliteHOST');
// assert(connectionsConfig.sqlite.user === 'sqliteUSER');
// });
it('should load application configs', function() {
assert(config.port === 1702);
assert(config.host === 'localhost');
// this should have been overriden by the local conf file
assert(config.appName === 'portal2');
assert(config.environment === 'production');
assert(config.cache.maxAge === 9001);
assert(config.globals._ === false);
});
it('should load the controllers configs', function() {
var conf = config.controllers;
assert(conf.routes.actions === false);
assert(conf.routes.prefix === 'Z');
assert(conf.routes.expectIntegerId === true);
assert(conf.csrf === true);
});
it('should load the io configs', function() {
var conf = config.sockets;
assert(conf.adapter === 'disk');
assert(conf.transports[0] === 'websocket');
assert(conf.origins === '*:1337');
assert(conf.heartbeats === false);
assert(conf['close timeout'] === 10);
assert(conf.authorization === false);
assert(conf['log level'] === 'error');
assert(conf['log colors'] === true);
assert(conf.static === false);
assert(conf.resource === '/all/the/sockets');
});
it('should override configs with locals config', function() {
assert(config.appName === 'portal2');
});
it('should load the log configs', function() {
assert(config.log.level === 'error');
});
it('should load the poly configs', function() {
assert(config.policies['*'] === false);
});
it('should load the routes configs', function() {
assert(typeof config.routes['/'] === 'function');
});
it('should load the session configs', function() {
assert(config.session.secret === '1234567');
assert(config.session.key === 'sails.sid');
});
it('should load the views config', function() {
var conf = config.views;
assert(conf.engine.ext === 'ejs');
assert(conf.blueprints === false);
assert(conf.layout === false);
});
});
}); | BlueHotDog/sails-migrations | test/fixtures/sample_apps/0.9.8/node_modules/sails/test/config/integration/load.test.js | JavaScript | mit | 3,853 |
testTransport = function(transports)
{
var prefix = "socketio - " + transports + ": ";
connect = function(transports)
{
// Force transport
io.transports = transports;
deepEqual(io.transports, transports, "Force transports");
var options = { 'force new connection': true }
return io.connect('/test', options);
}
asyncTest(prefix + "Connect", function() {
expect(4);
test = connect(transports);
test.on('connect', function () {
ok( true, "Connected with transport: " + test.socket.transport.name );
test.disconnect();
});
test.on('disconnect', function (reason) {
ok( true, "Disconnected - " + reason );
test.socket.disconnect();
start();
});
test.on('connect_failed', function () {
ok( false, "Connection failed");
start();
});
});
asyncTest(prefix + "Emit with ack", function() {
expect(3);
test = connect(transports);
test.emit('requestack', 1, function (val1, val2) {
equal(val1, 1);
equal(val2, "ack");
test.disconnect();
test.socket.disconnect();
start();
});
});
asyncTest(prefix + "Emit with ack one return value", function() {
expect(2);
test = connect(transports);
test.emit('requestackonevalue', 1, function (val1) {
equal(val1, 1);
test.disconnect();
test.socket.disconnect();
start();
});
});
}
transports = [io.transports];
// Validate individual transports
for(t in io.transports)
{
if(io.Transport[io.transports[t]].check()) {
transports.push([io.transports[t]]);
}
}
for(t in transports)
{
testTransport(transports[t])
}
| grokcore/dev.lexycross | wordsmithed/src/gevent-socketio/tests/jstests/tests/suite.js | JavaScript | mit | 1,679 |
import Mmenu from '../../core/oncanvas/mmenu.oncanvas';
import * as DOM from '../../core/_dom';
// DEPRECATED
// Will be removed in version 8.2
export default function (navbar) {
// Add content
var next = DOM.create('a.mm-btn.mm-btn_next.mm-navbar__btn');
navbar.append(next);
// Update to opened panel
var org;
var _url, _txt;
this.bind('openPanel:start', (panel) => {
org = panel.querySelector('.' + this.conf.classNames.navbars.panelNext);
_url = org ? org.getAttribute('href') : '';
_txt = org ? org.innerHTML : '';
if (_url) {
next.setAttribute('href', _url);
}
else {
next.removeAttribute('href');
}
next.classList[_url || _txt ? 'remove' : 'add']('mm-hidden');
next.innerHTML = _txt;
});
// Add screenreader / aria support
this.bind('openPanel:start:sr-aria', (panel) => {
Mmenu.sr_aria(next, 'hidden', next.matches('mm-hidden'));
Mmenu.sr_aria(next, 'owns', (next.getAttribute('href') || '').slice(1));
});
}
| extend1994/cdnjs | ajax/libs/jQuery.mmenu/8.2.3/addons/navbars/_navbar.next.js | JavaScript | mit | 1,073 |
// SERVER-2282 $or de duping with sparse indexes
t = db.jstests_org;
t.drop();
t.ensureIndex( {a:1}, {sparse:true} );
t.ensureIndex( {b:1} );
t.remove();
t.save( {a:1,b:2} );
assert.eq( 1, t.count( {$or:[{a:1},{b:2}]} ) );
t.remove();
t.save( {a:null,b:2} );
assert.eq( 1, t.count( {$or:[{a:null},{b:2}]} ) );
t.remove();
t.save( {b:2} );
assert.eq( 1, t.count( {$or:[{a:null},{b:2}]} ) );
| barakav/robomongo | src/third-party/mongodb/jstests/org.js | JavaScript | gpl-3.0 | 395 |
var searchData=
[
['print',['PRINT',['../_m_d___parola__lib_8h.html#a1696fc35fb931f8c876786fbc1078ac4',1,'MD_Parola_lib.h']]],
['print_5fstate',['PRINT_STATE',['../_m_d___parola__lib_8h.html#a3fda4e1a5122a16a21bd96ae5217402c',1,'MD_Parola_lib.h']]],
['prints',['PRINTS',['../_m_d___parola__lib_8h.html#ad68f35c3cfe67be8d09d1cea8e788e13',1,'MD_Parola_lib.h']]],
['printx',['PRINTX',['../_m_d___parola__lib_8h.html#abf55b44e8497cbc3addccdeb294138cc',1,'MD_Parola_lib.h']]]
];
| javastraat/arduino | libraries/MD_Parola/doc/html/search/defines_70.js | JavaScript | gpl-3.0 | 482 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
const mapValuesByKeys = require('../../../js/lib/functional').mapValuesByKeys
const _ = null
const ExtensionConstants = {
BROWSER_ACTION_REGISTERED: _,
BROWSER_ACTION_UPDATED: _,
EXTENSION_INSTALLED: _,
EXTENSION_UNINSTALLED: _,
EXTENSION_ENABLED: _,
EXTENSION_DISABLED: _,
CONTEXT_MENU_CREATED: _,
CONTEXT_MENU_ALL_REMOVED: _,
CONTEXT_MENU_CLICKED: _
}
module.exports = mapValuesByKeys(ExtensionConstants)
| timborden/browser-laptop | app/common/constants/extensionConstants.js | JavaScript | mpl-2.0 | 633 |
import { __platform_browser_private__ as r } from '@angular/platform-browser';
export var getDOM = r.getDOM;
//# sourceMappingURL=platform_browser_private.js.map | evandor/skysail-webconsole | webconsole.client/client/dist/lib/@angular/platform-browser-dynamic/esm/platform_browser_private.js | JavaScript | apache-2.0 | 161 |
exports.x = "d";
| g0ddish/webpack | test/cases/parsing/harmony-duplicate-export/d.js | JavaScript | mit | 17 |
var test = require("tap").test
var server = require("./lib/server.js")
var common = require("./lib/common.js")
var client = common.freshClient()
var cache = require("./fixtures/underscore/cache.json")
function nop () {}
var URI = "https://npm.registry:8043/rewrite"
var STARRED = true
var USERNAME = "username"
var PASSWORD = "%1234@asdf%"
var EMAIL = "[email protected]"
var AUTH = {
username : USERNAME,
password : PASSWORD,
email : EMAIL
}
var PARAMS = {
starred : STARRED,
auth : AUTH
}
test("star call contract", function (t) {
t.throws(function () {
client.star(undefined, PARAMS, nop)
}, "requires a URI")
t.throws(function () {
client.star([], PARAMS, nop)
}, "requires URI to be a string")
t.throws(function () {
client.star(URI, undefined, nop)
}, "requires params object")
t.throws(function () {
client.star(URI, "", nop)
}, "params must be object")
t.throws(function () {
client.star(URI, PARAMS, undefined)
}, "requires callback")
t.throws(function () {
client.star(URI, PARAMS, "callback")
}, "callback must be function")
t.throws(
function () {
var params = {
starred : STARRED
}
client.star(URI, params, nop)
},
{ name : "AssertionError", message : "must pass auth to star" },
"params must include auth"
)
t.test("token auth disallowed in star", function (t) {
var params = {
auth : {
token : "lol"
}
}
client.star(URI, params, function (err) {
t.equal(
err && err.message,
"This operation is unsupported for token-based auth",
"star doesn't support token-based auth"
)
t.end()
})
})
t.end()
})
test("star a package", function (t) {
server.expect("GET", "/underscore?write=true", function (req, res) {
t.equal(req.method, "GET")
res.json(cache)
})
server.expect("PUT", "/underscore", function (req, res) {
t.equal(req.method, "PUT")
var b = ""
req.setEncoding("utf8")
req.on("data", function (d) {
b += d
})
req.on("end", function () {
var updated = JSON.parse(b)
var already = [
"vesln", "mvolkmann", "lancehunt", "mikl", "linus", "vasc", "bat",
"dmalam", "mbrevoort", "danielr", "rsimoes", "thlorenz"
]
for (var i = 0; i < already.length; i++) {
var current = already[i]
t.ok(
updated.users[current],
current + " still likes this package"
)
}
t.ok(updated.users[USERNAME], "user is in the starred list")
res.statusCode = 201
res.json({starred:true})
})
})
var params = {
starred : STARRED,
auth : AUTH
}
client.star("http://localhost:1337/underscore", params, function (error, data) {
t.ifError(error, "no errors")
t.ok(data.starred, "was starred")
t.end()
})
})
| lwthatcher/Compass | web/node_modules/npm/node_modules/npm-registry-client/test/star.js | JavaScript | mit | 2,885 |
module.exports = {
"env": {
"node": true,
"commonjs": true,
"es6": true
},
"ecmaFeatures": {
"arrowFunctions": true,
"binaryLiterals": false,
"blockBindings": true,
"classes": false,
"defaultParams": true,
"destructuring": true,
"forOf": false,
"generators": false,
"modules": true,
"objectLiteralComputedProperties": false,
"objectLiteralDuplicateProperties": false,
"objectLiteralShorthandMethods": true,
"objectLiteralShorthandProperties": true,
"octalLiterals": false,
"regexUFlag": false,
"regexYFlag": false,
"restParams": true,
"spread": true,
"superInFunctions": true,
"templateStrings": true,
"unicodeCodePointEscapes": false,
"globalReturns": false,
"jsx": true,
"experimentalObjectRestSpread": true
},
"parser": "babel-eslint",
"rules": {
"array-bracket-spacing": [ 2, "always" ],
"arrow-body-style": [ 2, "as-needed" ],
"arrow-parens": [ 2, "as-needed" ],
"block-scoped-var": 2,
"block-spacing": [ 2, "always" ],
"brace-style": [ 2, "1tbs", {
"allowSingleLine": false
} ],
"comma-dangle": [ 2, "never" ],
"comma-spacing": [ 2, {
"after": true,
"before": false
} ],
"consistent-return": 2,
"consistent-this": [ 2, "self" ],
"constructor-super": 2,
"curly": [ 2, "all" ],
"dot-location": [ 2, "property" ],
"dot-notation": 2,
"eol-last": 2,
"indent": [ 2, 2, {
"SwitchCase": 1
} ],
"jsx-quotes": [ 2, "prefer-double" ],
"max-len": [ 2, 125, 2, {
"ignorePattern": "((^import[^;]+;$)|(^\\s*it\\())",
"ignoreUrls": true
} ],
"new-cap": 2,
"no-alert": 2,
"no-confusing-arrow": 2,
"no-caller": 2,
"no-class-assign": 2,
"no-cond-assign": [ 2, "always" ],
"no-console": 1,
"no-const-assign": 2,
"no-constant-condition": 2,
"no-control-regex": 2,
"no-debugger": 1,
"no-dupe-args": 2,
"no-dupe-class-members": 2,
"no-dupe-keys": 2,
"no-duplicate-case": 2,
"no-else-return": 2,
"no-empty": 2,
"no-empty-character-class": 2,
"no-eq-null": 2,
"no-eval": 2,
"no-ex-assign": 2,
"no-extend-native": 2,
"no-extra-bind": 2,
"no-extra-boolean-cast": 2,
"no-extra-parens": [ 2, "functions" ],
"no-extra-semi": 2,
"no-func-assign": 2,
"no-implicit-coercion": [ 2, {
"boolean": true,
"number": true,
"string": true
} ],
"no-implied-eval": 2,
"no-inner-declarations": [ 2, "both" ],
"no-invalid-regexp": 2,
"no-invalid-this": 2,
"no-irregular-whitespace": 2,
"no-lonely-if": 2,
"no-negated-condition": 2,
"no-negated-in-lhs": 2,
"no-new": 2,
"no-new-func": 2,
"no-new-object": 2,
"no-obj-calls": 2,
"no-proto": 2,
"no-redeclare": 2,
"no-regex-spaces": 2,
"no-return-assign": 2,
"no-self-compare": 2,
"no-sequences": 2,
"no-sparse-arrays": 2,
"no-this-before-super": 2,
"no-trailing-spaces": 2,
"no-undef": 2,
"no-unexpected-multiline": 2,
"no-unneeded-ternary": 2,
"no-unreachable": 2,
"no-unused-vars": [ 1, {
"args": "after-used",
"vars": "all",
"varsIgnorePattern": "React"
} ],
"no-use-before-define": 2,
"no-useless-call": 2,
"no-useless-concat": 2,
"no-var": 2,
"no-warning-comments": [ 1, {
"location": "anywhere",
"terms": [
"todo"
]
} ],
"no-with": 2,
"object-curly-spacing": [ 2, "always" ],
"object-shorthand": 2,
"one-var": [ 2, "never" ],
"prefer-arrow-callback": 2,
"prefer-const": 2,
"prefer-spread": 2,
"prefer-template": 2,
"radix": 2,
"semi": 2,
"sort-vars": [ 2, {
"ignoreCase": true
} ],
"keyword-spacing": 2,
"space-before-blocks": [ 2, "always" ],
"space-before-function-paren": [ 2, "never" ],
"space-infix-ops": [ 2, {
"int32Hint": false
} ],
"use-isnan": 2,
"valid-typeof": 2,
"vars-on-top": 2,
"yoda": [ 2, "never" ]
}
};
| dgilroy77/Car.ly | node_modules/eslint-plugin-jsx-a11y/.eslintrc.js | JavaScript | mit | 4,092 |
var class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_flag_foreground_color_procedure =
[
[ "GetFlagForegroundColorProcedure", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_flag_foreground_color_procedure.html#a406f266327939d646d9baeab2c4a403c", null ],
[ "GetFlagForegroundColorProcedure", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_flag_foreground_color_procedure.html#abcd56ea5e3f8fb6f13a707c5831364ea", null ],
[ "Execute", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_flag_foreground_color_procedure.html#a41b396d64cf0ca99e98589f3ed915e9b", null ],
[ "ObjectName", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_flag_foreground_color_procedure.html#a495d5b167f46543baea7d9cf712e180c", null ],
[ "ObjectNamespace", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_flag_foreground_color_procedure.html#abc8aeaedbf5be1aa716bedc14e8368b8", null ],
[ "_LoginId", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_flag_foreground_color_procedure.html#a89488d582ef1c66a823d613c7725a88a", null ],
[ "_UserId", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_flag_foreground_color_procedure.html#aaf895d27f639c2af0dca31c3c2942180", null ],
[ "Catalog", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_flag_foreground_color_procedure.html#a10643564bca344c9ecc3c599a41ecb82", null ],
[ "FlagTypeId", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_flag_foreground_color_procedure.html#ae78c6bd596b5c7cada303842dcc96c2b", null ]
]; | mixerp/mixerp | docs/api/class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_flag_foreground_color_procedure.js | JavaScript | gpl-3.0 | 1,615 |
/**
* @fileoverview Rule to enforce spacing around embedded expressions of template strings
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const OPEN_PAREN = /\$\{$/u;
const CLOSE_PAREN = /^\}/u;
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "layout",
docs: {
description: "require or disallow spacing around embedded expressions of template strings",
category: "ECMAScript 6",
recommended: false,
url: "https://eslint.org/docs/rules/template-curly-spacing"
},
fixable: "whitespace",
schema: [
{ enum: ["always", "never"] }
],
messages: {
expectedBefore: "Expected space(s) before '}'.",
expectedAfter: "Expected space(s) after '${'.",
unexpectedBefore: "Unexpected space(s) before '}'.",
unexpectedAfter: "Unexpected space(s) after '${'."
}
},
create(context) {
const sourceCode = context.getSourceCode();
const always = context.options[0] === "always";
const prefix = always ? "expected" : "unexpected";
/**
* Checks spacing before `}` of a given token.
* @param {Token} token A token to check. This is a Template token.
* @returns {void}
*/
function checkSpacingBefore(token) {
const prevToken = sourceCode.getTokenBefore(token);
if (prevToken &&
CLOSE_PAREN.test(token.value) &&
astUtils.isTokenOnSameLine(prevToken, token) &&
sourceCode.isSpaceBetweenTokens(prevToken, token) !== always
) {
context.report({
loc: token.loc.start,
messageId: `${prefix}Before`,
fix(fixer) {
if (always) {
return fixer.insertTextBefore(token, " ");
}
return fixer.removeRange([
prevToken.range[1],
token.range[0]
]);
}
});
}
}
/**
* Checks spacing after `${` of a given token.
* @param {Token} token A token to check. This is a Template token.
* @returns {void}
*/
function checkSpacingAfter(token) {
const nextToken = sourceCode.getTokenAfter(token);
if (nextToken &&
OPEN_PAREN.test(token.value) &&
astUtils.isTokenOnSameLine(token, nextToken) &&
sourceCode.isSpaceBetweenTokens(token, nextToken) !== always
) {
context.report({
loc: {
line: token.loc.end.line,
column: token.loc.end.column - 2
},
messageId: `${prefix}After`,
fix(fixer) {
if (always) {
return fixer.insertTextAfter(token, " ");
}
return fixer.removeRange([
token.range[1],
nextToken.range[0]
]);
}
});
}
}
return {
TemplateElement(node) {
const token = sourceCode.getFirstToken(node);
checkSpacingBefore(token);
checkSpacingAfter(token);
}
};
}
};
| BigBoss424/portfolio | v8/development/node_modules/gatsby/node_modules/eslint/lib/rules/template-curly-spacing.js | JavaScript | apache-2.0 | 4,149 |
/*
*
* 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 server = {};
(function (server) {
var USER = 'server.user';
var log = new Log();
/**
* Returns the currently logged in user
*/
server.current = function (session, user) {
if (arguments.length > 1) {
session.put(USER, user);
return user;
}
return session.get(USER);
};
}(server));
| hsbhathiya/stratos | components/org.apache.stratos.manager.console/modules/console/scripts/server.js | JavaScript | apache-2.0 | 1,188 |
var get = Ember.get;
Ember._ResolvedState = Ember.Object.extend({
manager: null,
state: null,
match: null,
object: Ember.computed(function(key) {
if (this._object) {
return this._object;
} else {
var state = get(this, 'state'),
match = get(this, 'match'),
manager = get(this, 'manager');
return state.deserialize(manager, match.hash);
}
}),
hasPromise: Ember.computed(function() {
return Ember.canInvoke(get(this, 'object'), 'then');
}).property('object'),
promise: Ember.computed(function() {
var object = get(this, 'object');
if (Ember.canInvoke(object, 'then')) {
return object;
} else {
return {
then: function(success) { success(object); }
};
}
}).property('object'),
transition: function() {
var manager = get(this, 'manager'),
path = get(this, 'state.path'),
object = get(this, 'object');
manager.transitionTo(path, object);
}
});
| teddyzeenny/ember.js | packages/ember-old-router/lib/resolved_state.js | JavaScript | mit | 985 |
require('mocha');
require('should');
var assert = require('assert');
var support = require('./support');
var App = support.resolve();
var app;
describe('app.option', function() {
beforeEach(function() {
app = new App();
});
it('should set a key-value pair on options:', function() {
app.option('a', 'b');
assert(app.options.a === 'b');
});
it('should set an object on options:', function() {
app.option({c: 'd'});
assert(app.options.c === 'd');
});
it('should set an option.', function() {
app.option('a', 'b');
app.options.should.have.property('a');
});
it('should get an option.', function() {
app.option('a', 'b');
app.option('a').should.equal('b');
});
it('should extend the `options` object.', function() {
app.option({x: 'xxx', y: 'yyy', z: 'zzz'});
app.option('x').should.equal('xxx');
app.option('y').should.equal('yyy');
app.option('z').should.equal('zzz');
});
it('options should be on the `options` object.', function() {
app.option({x: 'xxx', y: 'yyy', z: 'zzz'});
app.options.x.should.equal('xxx');
app.options.y.should.equal('yyy');
app.options.z.should.equal('zzz');
});
it('should be chainable.', function() {
app.option({x: 'xxx', y: 'yyy', z: 'zzz'});
app.option({a: 'aaa', b: 'bbb', c: 'ccc'});
app.option('x').should.equal('xxx');
app.option('a').should.equal('aaa');
});
it('should extend the `options` object when the first param is a string.', function() {
app.option('foo', {x: 'xxx', y: 'yyy', z: 'zzz'});
app.option('bar', {a: 'aaa', b: 'bbb', c: 'ccc'});
app.option('foo').should.have.property('x');
app.option('bar').should.have.property('a');
app.options.foo.should.have.property('x');
app.options.bar.should.have.property('a');
});
it('should set an option.', function() {
app.option('a', 'b');
app.options.should.have.property('a');
});
it('should get an option.', function() {
app.option('a', 'b');
app.option('a').should.equal('b');
});
it('should extend the `options` object.', function() {
app.option({x: 'xxx', y: 'yyy', z: 'zzz'});
app.option('x').should.equal('xxx');
app.option('y').should.equal('yyy');
app.option('z').should.equal('zzz');
});
it('options should be on the `options` object.', function() {
app.option({x: 'xxx', y: 'yyy', z: 'zzz'});
app.options.x.should.equal('xxx');
app.options.y.should.equal('yyy');
app.options.z.should.equal('zzz');
});
it('should be chainable.', function() {
app
.option({x: 'xxx', y: 'yyy', z: 'zzz'})
.option({a: 'aaa', b: 'bbb', c: 'ccc'});
app.option('x').should.equal('xxx');
app.option('a').should.equal('aaa');
});
});
| Gargitier5/tier5portal | vendors/update/test/app.option.js | JavaScript | mit | 2,760 |
Proj4js.defs["EPSG:2246"] = "+proj=lcc +lat_1=37.96666666666667 +lat_2=38.96666666666667 +lat_0=37.5 +lon_0=-84.25 +x_0=500000.0001016001 +y_0=0 +ellps=GRS80 +datum=NAD83 +to_meter=0.3048006096012192 +no_defs"; | debard/georchestra-ird | mapfishapp/src/main/webapp/lib/proj4js/lib/defs/EPSG2246.js | JavaScript | gpl-3.0 | 210 |
tinyMCE.addI18n('ka.wordcount',{words:"Words: "}); | freaxmind/miage-l3 | web/blog Tim Burton/tim_burton/protected/extensions/tinymce/assets/tiny_mce/plugins/wordc/langs/ka_dlg.js | JavaScript | gpl-3.0 | 50 |
/*
* 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.
*/
let nativeModules = {}
// for testing
/**
* for testing
*/
export function getModule (moduleName) {
return nativeModules[moduleName]
}
/**
* for testing
*/
export function clearModules () {
nativeModules = {}
}
// for framework
/**
* init modules for an app instance
* the second param determines whether to replace an existed method
*/
export function initModules (modules, ifReplace) {
for (const moduleName in modules) {
// init `modules[moduleName][]`
let methods = nativeModules[moduleName]
if (!methods) {
methods = {}
nativeModules[moduleName] = methods
}
// push each non-existed new method
modules[moduleName].forEach(function (method) {
if (typeof method === 'string') {
method = {
name: method
}
}
if (!methods[method.name] || ifReplace) {
methods[method.name] = method
}
})
}
}
/**
* init app methods
*/
export function initMethods (Vm, apis) {
const p = Vm.prototype
for (const apiName in apis) {
if (!p.hasOwnProperty(apiName)) {
p[apiName] = apis[apiName]
}
}
}
/**
* get a module of methods for an app instance
*/
export function requireModule (app, name) {
const methods = nativeModules[name]
const target = {}
for (const methodName in methods) {
Object.defineProperty(target, methodName, {
configurable: true,
enumerable: true,
get: function moduleGetter () {
return (...args) => app.callTasks({
module: name,
method: methodName,
args: args
})
},
set: function moduleSetter (value) {
if (typeof value === 'function') {
return app.callTasks({
module: name,
method: methodName,
args: [value]
})
}
}
})
}
return target
}
/**
* get a custom component options
*/
export function requireCustomComponent (app, name) {
const { customComponentMap } = app
return customComponentMap[name]
}
/**
* register a custom component options
*/
export function registerCustomComponent (app, name, def) {
const { customComponentMap } = app
if (customComponentMap[name]) {
console.error(`[JS Framework] define a component(${name}) that already exists`)
return
}
customComponentMap[name] = def
}
| cxfeng1/incubator-weex | runtime/frameworks/legacy/app/register.js | JavaScript | apache-2.0 | 3,146 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(function() {
// We are going to kill all of the builtins, so hold onto the ones we need.
var defineGetter = Object.prototype.__defineGetter__;
var defineSetter = Object.prototype.__defineSetter__;
var Error = window.Error;
var forEach = Array.prototype.forEach;
var push = Array.prototype.push;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var stringify = JSON.stringify;
// Kill all of the builtins functions to give us a fairly high confidence that
// the environment our bindings run in can't interfere with our code.
// These are taken from the ECMAScript spec.
var builtinTypes = [
Object, Function, Array, String, Boolean, Number, Math, Date, RegExp, JSON,
];
function clobber(obj, name, qualifiedName) {
// Clobbering constructors would break everything.
// Clobbering toString is annoying.
// Clobbering __proto__ breaks in ways that grep can't find.
// Clobbering function name will break because
// SafeBuiltins does not support getters yet. See crbug.com/463526.
// Clobbering Function.call would make it impossible to implement these tests.
// Clobbering Object.valueOf breaks v8.
// Clobbering %FunctionPrototype%.caller and .arguments will break because
// these properties are poisoned accessors in ES6.
if (name == 'constructor' ||
name == 'toString' ||
name == '__proto__' ||
name == 'name' && typeof obj == 'function' ||
qualifiedName == 'Function.call' ||
(obj !== Function && qualifiedName == 'Function.caller') ||
(obj !== Function && qualifiedName == 'Function.arguments') ||
qualifiedName == 'Object.valueOf') {
return;
}
if (typeof obj[name] == 'function') {
obj[name] = function() {
throw new Error('Clobbered ' + qualifiedName + ' function');
};
} else {
defineGetter.call(obj, name, function() {
throw new Error('Clobbered ' + qualifiedName + ' getter');
});
}
}
forEach.call(builtinTypes, function(builtin) {
var prototype = builtin.prototype;
var typename = '<unknown>';
if (prototype) {
typename = prototype.constructor.name;
forEach.call(getOwnPropertyNames(prototype), function(name) {
clobber(prototype, name, typename + '.' + name);
});
}
forEach.call(getOwnPropertyNames(builtin), function(name) {
clobber(builtin, name, typename + '.' + name);
});
if (builtin.name)
clobber(window, builtin.name, 'window.' + builtin.name);
});
// Codes for test results. Must match ExternallyConnectableMessagingTest::Result
// in c/b/extensions/extension_messages_apitest.cc.
var results = {
OK: 0,
NAMESPACE_NOT_DEFINED: 1,
FUNCTION_NOT_DEFINED: 2,
COULD_NOT_ESTABLISH_CONNECTION_ERROR: 3,
OTHER_ERROR: 4,
INCORRECT_RESPONSE_SENDER: 5,
INCORRECT_RESPONSE_MESSAGE: 6,
};
// Make the messages sent vaguely complex, but unambiguously JSON-ifiable.
var kMessage = [{'a': {'b': 10}}, 20, 'c\x10\x11'];
// Our tab's location. Normally this would be our document's location but if
// we're an iframe it will be the location of the parent - in which case,
// expect to be told.
var tabLocationHref = null;
if (parent == window) {
tabLocationHref = document.location.href;
} else {
window.addEventListener('message', function listener(event) {
window.removeEventListener('message', listener);
tabLocationHref = event.data;
});
}
function checkLastError(reply) {
if (!chrome.runtime.lastError)
return true;
var kCouldNotEstablishConnection =
'Could not establish connection. Receiving end does not exist.';
if (chrome.runtime.lastError.message == kCouldNotEstablishConnection)
reply(results.COULD_NOT_ESTABLISH_CONNECTION_ERROR);
else
reply(results.OTHER_ERROR);
return false;
}
function checkResponse(response, reply, expectedMessage, isApp) {
// The response will be an echo of both the original message *and* the
// MessageSender (with the tab field stripped down).
//
// First check the sender was correct.
var incorrectSender = false;
if (!isApp) {
// Only extensions get access to a 'tab' property.
if (!hasOwnProperty.call(response.sender, 'tab')) {
console.warn('Expected a tab, got none');
incorrectSender = true;
}
if (response.sender.tab.url != tabLocationHref) {
console.warn('Expected tab url ' + tabLocationHref + ' got ' +
response.sender.tab.url);
incorrectSender = true;
}
}
if (hasOwnProperty.call(response.sender, 'id')) {
console.warn('Expected no id, got "' + response.sender.id + '"');
incorrectSender = true;
}
if (response.sender.url != document.location.href) {
console.warn('Expected url ' + document.location.href + ' got ' +
response.sender.url);
incorrectSender = true;
}
if (incorrectSender) {
reply(results.INCORRECT_RESPONSE_SENDER);
return false;
}
// Check the correct content was echoed.
var expectedJson = stringify(expectedMessage);
var actualJson = stringify(response.message);
if (actualJson == expectedJson)
return true;
console.warn('Expected message ' + expectedJson + ' got ' + actualJson);
reply(results.INCORRECT_RESPONSE_MESSAGE);
return false;
}
function sendToBrowser(msg) {
domAutomationController.send(msg);
}
function sendToBrowserForTlsChannelId(result) {
// Because the TLS channel ID tests read the TLS either an error code or the
// TLS channel ID string from the same value, they require the result code
// to be sent as a string.
// String() is clobbered, so coerce string creation with +.
sendToBrowser("" + result);
}
function checkRuntime(reply) {
if (!reply)
reply = sendToBrowser;
if (!chrome.runtime) {
reply(results.NAMESPACE_NOT_DEFINED);
return false;
}
if (!chrome.runtime.connect || !chrome.runtime.sendMessage) {
reply(results.FUNCTION_NOT_DEFINED);
return false;
}
return true;
}
function checkRuntimeForTlsChannelId() {
return checkRuntime(sendToBrowserForTlsChannelId);
}
function checkTlsChannelIdResponse(response) {
if (chrome.runtime.lastError) {
if (chrome.runtime.lastError.message == kCouldNotEstablishConnection)
sendToBrowserForTlsChannelId(
results.COULD_NOT_ESTABLISH_CONNECTION_ERROR);
else
sendToBrowserForTlsChannelId(results.OTHER_ERROR);
return;
}
if (response.sender.tlsChannelId !== undefined)
sendToBrowserForTlsChannelId(response.sender.tlsChannelId);
else
sendToBrowserForTlsChannelId('');
}
window.actions = {
appendIframe: function(src) {
var iframe = document.createElement('iframe');
// When iframe has loaded, notify it of our tab location (probably
// document.location) to use in its assertions, then continue.
iframe.addEventListener('load', function listener() {
iframe.removeEventListener('load', listener);
iframe.contentWindow.postMessage(tabLocationHref, '*');
sendToBrowser(true);
});
iframe.src = src;
document.body.appendChild(iframe);
}
};
window.assertions = {
canConnectAndSendMessages: function(extensionId, isApp, message) {
if (!checkRuntime())
return;
if (!message)
message = kMessage;
function canSendMessage(reply) {
chrome.runtime.sendMessage(extensionId, message, function(response) {
if (checkLastError(reply) &&
checkResponse(response, reply, message, isApp)) {
reply(results.OK);
}
});
}
function canConnectAndSendMessages(reply) {
var port = chrome.runtime.connect(extensionId);
port.postMessage(message, function() {
checkLastError(reply);
});
port.postMessage(message, function() {
checkLastError(reply);
});
var pendingResponses = 2;
var ok = true;
port.onMessage.addListener(function(response) {
pendingResponses--;
ok = ok && checkLastError(reply) &&
checkResponse(response, reply, message, isApp);
if (pendingResponses == 0 && ok)
reply(results.OK);
});
}
canSendMessage(function(result) {
if (result != results.OK)
sendToBrowser(result);
else
canConnectAndSendMessages(sendToBrowser);
});
},
trySendMessage: function(extensionId) {
chrome.runtime.sendMessage(extensionId, kMessage, function(response) {
// The result is unimportant. All that matters is the attempt.
});
},
tryIllegalArguments: function() {
// Tests that illegal arguments to messaging functions throw exceptions.
// Regression test for crbug.com/472700, where they crashed the renderer.
function runIllegalFunction(fun) {
try {
fun();
} catch(e) {
return true;
}
console.error('Function did not throw exception: ' + fun);
sendToBrowser(false);
return false;
}
var result =
runIllegalFunction(chrome.runtime.connect) &&
runIllegalFunction(function() {
chrome.runtime.connect('');
}) &&
runIllegalFunction(function() {
chrome.runtime.connect(42);
}) &&
runIllegalFunction(function() {
chrome.runtime.connect('', 42);
}) &&
runIllegalFunction(function() {
chrome.runtime.connect({name: 'noname'});
}) &&
runIllegalFunction(chrome.runtime.sendMessage) &&
runIllegalFunction(function() {
chrome.runtime.sendMessage('');
}) &&
runIllegalFunction(function() {
chrome.runtime.sendMessage(42);
}) &&
runIllegalFunction(function() {
chrome.runtime.sendMessage('', 42);
}) &&
sendToBrowser(true);
},
areAnyRuntimePropertiesDefined: function(names) {
var result = false;
if (chrome.runtime) {
forEach.call(names, function(name) {
if (chrome.runtime[name]) {
console.log('runtime.' + name + ' is defined');
result = true;
}
});
}
sendToBrowser(result);
},
getTlsChannelIdFromPortConnect: function(extensionId, includeTlsChannelId,
message) {
if (!checkRuntimeForTlsChannelId())
return;
if (!message)
message = kMessage;
var port = chrome.runtime.connect(extensionId,
{'includeTlsChannelId': includeTlsChannelId});
port.onMessage.addListener(checkTlsChannelIdResponse);
port.postMessage(message);
},
getTlsChannelIdFromSendMessage: function(extensionId, includeTlsChannelId,
message) {
if (!checkRuntimeForTlsChannelId())
return;
if (!message)
message = kMessage;
chrome.runtime.sendMessage(extensionId, message,
{'includeTlsChannelId': includeTlsChannelId},
checkTlsChannelIdResponse);
}
};
}());
| Chilledheart/chromium | chrome/test/data/extensions/api_test/messaging/externally_connectable/sites/assertions.js | JavaScript | bsd-3-clause | 11,033 |
// Copyright 2012 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 goog.events.EventTarget tester.
*/
goog.provide('goog.events.eventTargetTester');
goog.setTestOnly('goog.events.eventTargetTester');
goog.provide('goog.events.eventTargetTester.KeyType');
goog.setTestOnly('goog.events.eventTargetTester.KeyType');
goog.provide('goog.events.eventTargetTester.UnlistenReturnType');
goog.setTestOnly('goog.events.eventTargetTester.UnlistenReturnType');
goog.require('goog.array');
goog.require('goog.events');
goog.require('goog.events.Event');
goog.require('goog.events.EventTarget');
goog.require('goog.testing.asserts');
goog.require('goog.testing.recordFunction');
/**
* Setup step for the test functions. This needs to be called from the
* test setUp.
* @param {Function} listenFn Function that, given the same signature
* as goog.events.listen, will add listener to the given event
* target.
* @param {Function} unlistenFn Function that, given the same
* signature as goog.events.unlisten, will remove listener from
* the given event target.
* @param {Function} unlistenByKeyFn Function that, given 2
* parameters: src and key, will remove the corresponding
* listener.
* @param {Function} listenOnceFn Function that, given the same
* signature as goog.events.listenOnce, will add a one-time
* listener to the given event target.
* @param {Function} dispatchEventFn Function that, given the same
* signature as goog.events.dispatchEvent, will dispatch the event
* on the given event target.
* @param {Function} removeAllFn Function that, given the same
* signature as goog.events.removeAll, will remove all listeners
* according to the contract of goog.events.removeAll.
* @param {Function} getListenersFn Function that, given the same
* signature as goog.events.getListeners, will retrieve listeners.
* @param {Function} getListenerFn Function that, given the same
* signature as goog.events.getListener, will retrieve the
* listener object.
* @param {Function} hasListenerFn Function that, given the same
* signature as goog.events.hasListener, will determine whether
* listeners exist.
* @param {goog.events.eventTargetTester.KeyType} listenKeyType The
* key type returned by listen call.
* @param {goog.events.eventTargetTester.UnlistenReturnType}
* unlistenFnReturnType
* Whether we should check return value from
* unlisten call. If unlisten does not return a value, this should
* be set to false.
* @param {boolean} objectListenerSupported Whether listener of type
* Object is supported.
*/
goog.events.eventTargetTester.setUp = function(
listenFn, unlistenFn, unlistenByKeyFn, listenOnceFn,
dispatchEventFn, removeAllFn,
getListenersFn, getListenerFn, hasListenerFn,
listenKeyType, unlistenFnReturnType, objectListenerSupported) {
listen = listenFn;
unlisten = unlistenFn;
unlistenByKey = unlistenByKeyFn;
listenOnce = listenOnceFn;
dispatchEvent = dispatchEventFn;
removeAll = removeAllFn;
getListeners = getListenersFn;
getListener = getListenerFn;
hasListener = hasListenerFn;
keyType = listenKeyType;
unlistenReturnType = unlistenFnReturnType;
objectTypeListenerSupported = objectListenerSupported;
listeners = [];
for (var i = 0; i < goog.events.eventTargetTester.MAX_; i++) {
listeners[i] = createListener();
}
eventTargets = [];
for (i = 0; i < goog.events.eventTargetTester.MAX_; i++) {
eventTargets[i] = new goog.events.EventTarget();
}
};
/**
* Teardown step for the test functions. This needs to be called from
* test teardown.
*/
goog.events.eventTargetTester.tearDown = function() {
for (var i = 0; i < goog.events.eventTargetTester.MAX_; i++) {
goog.dispose(eventTargets[i]);
}
};
/**
* The type of key returned by key-returning functions (listen).
* @enum {number}
*/
goog.events.eventTargetTester.KeyType = {
/**
* Returns number for key.
*/
NUMBER: 0,
/**
* Returns undefined (no return value).
*/
UNDEFINED: 1
};
/**
* The type of unlisten function's return value.
*/
goog.events.eventTargetTester.UnlistenReturnType = {
/**
* Returns boolean indicating whether unlisten is successful.
*/
BOOLEAN: 0,
/**
* Returns undefind (no return value).
*/
UNDEFINED: 1
};
/**
* Expando property used on "listener" function to determine if a
* listener has already been checked. This is what allows us to
* implement assertNoOtherListenerIsCalled.
* @type {string}
*/
goog.events.eventTargetTester.ALREADY_CHECKED_PROP = '__alreadyChecked';
/**
* Expando property used on "listener" function to record the number
* of times it has been called the last time assertListenerIsCalled is
* done. This allows us to verify that it has not been called more
* times in assertNoOtherListenerIsCalled.
*/
goog.events.eventTargetTester.NUM_CALLED_PROP = '__numCalled';
/**
* The maximum number of initialized event targets (in eventTargets
* array) and listeners (in listeners array).
* @type {number}
* @private
*/
goog.events.eventTargetTester.MAX_ = 10;
/**
* Contains test event types.
* @enum {string}
*/
var EventType = {
A: goog.events.getUniqueId('a'),
B: goog.events.getUniqueId('b'),
C: goog.events.getUniqueId('c')
};
var listen, unlisten, unlistenByKey, listenOnce, dispatchEvent;
var removeAll, getListeners, getListener, hasListener;
var keyType, unlistenReturnType, objectTypeListenerSupported;
var eventTargets, listeners;
/**
* Custom event object for testing.
* @constructor
* @extends {goog.events.Event}
*/
var TestEvent = function() {
goog.base(this, EventType.A);
};
goog.inherits(TestEvent, goog.events.Event);
/**
* Creates a listener that executes the given function (optional).
* @param {!Function=} opt_listenerFn The optional function to execute.
* @return {!Function} The listener function.
*/
function createListener(opt_listenerFn) {
return goog.testing.recordFunction(opt_listenerFn);
}
/**
* Asserts that the given listener is called numCount number of times.
* @param {!Function} listener The listener to check.
* @param {number} numCount The number of times. See also the times()
* function below.
*/
function assertListenerIsCalled(listener, numCount) {
assertEquals('Listeners is not called the correct number of times.',
numCount, listener.getCallCount());
listener[goog.events.eventTargetTester.ALREADY_CHECKED_PROP] = true;
listener[goog.events.eventTargetTester.NUM_CALLED_PROP] = numCount;
}
/**
* Asserts that no other listeners, other than those verified via
* assertListenerIsCalled, have been called since the last
* resetListeners().
*/
function assertNoOtherListenerIsCalled() {
goog.array.forEach(listeners, function(l, index) {
if (!l[goog.events.eventTargetTester.ALREADY_CHECKED_PROP]) {
assertEquals(
'Listeners ' + index + ' is unexpectedly called.',
0, l.getCallCount());
} else {
assertEquals(
'Listeners ' + index + ' is unexpectedly called.',
l[goog.events.eventTargetTester.NUM_CALLED_PROP], l.getCallCount());
}
});
}
/**
* Resets all listeners call count to 0.
*/
function resetListeners() {
goog.array.forEach(listeners, function(l) {
l.reset();
l[goog.events.eventTargetTester.ALREADY_CHECKED_PROP] = false;
});
}
/**
* The number of times a listener should have been executed. This
* exists to make assertListenerIsCalled more readable. This is used
* like so: assertListenerIsCalled(listener, times(2));
* @param {number} n The number of times a listener should have been
* executed.
* @return {number} The number n.
*/
function times(n) {
return n;
}
function testNoListener() {
dispatchEvent(eventTargets[0], EventType.A);
assertNoOtherListenerIsCalled();
}
function testOneListener() {
listen(eventTargets[0], EventType.A, listeners[0]);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertNoOtherListenerIsCalled();
resetListeners();
dispatchEvent(eventTargets[0], EventType.B);
dispatchEvent(eventTargets[0], EventType.C);
assertNoOtherListenerIsCalled();
}
function testTwoListenersOfSameType() {
var key1 = listen(eventTargets[0], EventType.A, listeners[0]);
var key2 = listen(eventTargets[0], EventType.A, listeners[1]);
if (keyType == goog.events.eventTargetTester.KeyType.NUMBER) {
assertNotEquals(key1, key2);
} else {
assertUndefined(key1);
assertUndefined(key2);
}
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertListenerIsCalled(listeners[1], times(1));
assertNoOtherListenerIsCalled();
}
function testInstallingSameListeners() {
var key1 = listen(eventTargets[0], EventType.A, listeners[0]);
var key2 = listen(eventTargets[0], EventType.A, listeners[0]);
var key3 = listen(eventTargets[0], EventType.B, listeners[0]);
if (keyType == goog.events.eventTargetTester.KeyType.NUMBER) {
assertEquals(key1, key2);
assertNotEquals(key1, key3);
} else {
assertUndefined(key1);
assertUndefined(key2);
assertUndefined(key3);
}
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
dispatchEvent(eventTargets[0], EventType.B);
assertListenerIsCalled(listeners[0], times(2));
assertNoOtherListenerIsCalled();
}
function testScope() {
listeners[0] = createListener(function(e) {
assertEquals('Wrong scope with undefined scope', eventTargets[0], this);
});
listeners[1] = createListener(function(e) {
assertEquals('Wrong scope with null scope', eventTargets[0], this);
});
var scope = {};
listeners[2] = createListener(function(e) {
assertEquals('Wrong scope with specific scope object', scope, this);
});
listen(eventTargets[0], EventType.A, listeners[0]);
listen(eventTargets[0], EventType.A, listeners[1], false, null);
listen(eventTargets[0], EventType.A, listeners[2], false, scope);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertListenerIsCalled(listeners[1], times(1));
assertListenerIsCalled(listeners[2], times(1));
}
function testDispatchEventDoesNotThrowWithDisposedEventTarget() {
goog.dispose(eventTargets[0]);
assertTrue(dispatchEvent(eventTargets[0], EventType.A));
}
function testDispatchEventWithObjectLiteral() {
listen(eventTargets[0], EventType.A, listeners[0]);
assertTrue(dispatchEvent(eventTargets[0], {type: EventType.A}));
assertListenerIsCalled(listeners[0], times(1));
assertNoOtherListenerIsCalled();
}
function testDispatchEventWithCustomEventObject() {
listen(eventTargets[0], EventType.A, listeners[0]);
var e = new TestEvent();
assertTrue(dispatchEvent(eventTargets[0], e));
assertListenerIsCalled(listeners[0], times(1));
assertNoOtherListenerIsCalled();
var actualEvent = listeners[0].getLastCall().getArgument(0);
assertEquals(e, actualEvent);
assertEquals(eventTargets[0], actualEvent.target);
}
function testDisposingEventTargetRemovesListeners() {
listen(eventTargets[0], EventType.A, listeners[0]);
goog.dispose(eventTargets[0]);
dispatchEvent(eventTargets[0], EventType.A);
assertNoOtherListenerIsCalled();
}
/**
* Unlisten/unlistenByKey should still work after disposal. There are
* many circumstances when this is actually necessary. For example, a
* user may have listened to an event target and stored the key
* (e.g. in a goog.events.EventHandler) and only unlisten after the
* target has been disposed.
*/
function testUnlistenWorksAfterDisposal() {
var key = listen(eventTargets[0], EventType.A, listeners[0]);
goog.dispose(eventTargets[0]);
unlisten(eventTargets[0], EventType.A, listeners[1]);
if (unlistenByKey) {
unlistenByKey(eventTargets[0], key);
}
}
function testRemovingListener() {
var ret1 = unlisten(eventTargets[0], EventType.A, listeners[0]);
listen(eventTargets[0], EventType.A, listeners[0]);
var ret2 = unlisten(eventTargets[0], EventType.A, listeners[1]);
var ret3 = unlisten(eventTargets[0], EventType.B, listeners[0]);
var ret4 = unlisten(eventTargets[1], EventType.A, listeners[0]);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
var ret5 = unlisten(eventTargets[0], EventType.A, listeners[0]);
var ret6 = unlisten(eventTargets[0], EventType.A, listeners[0]);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertNoOtherListenerIsCalled();
if (unlistenReturnType ==
goog.events.eventTargetTester.UnlistenReturnType.BOOLEAN) {
assertFalse(ret1);
assertFalse(ret2);
assertFalse(ret3);
assertFalse(ret4);
assertTrue(ret5);
assertFalse(ret6);
} else {
assertUndefined(ret1);
assertUndefined(ret2);
assertUndefined(ret3);
assertUndefined(ret4);
assertUndefined(ret5);
assertUndefined(ret6);
}
}
function testCapture() {
eventTargets[0].setParentEventTarget(eventTargets[1]);
eventTargets[1].setParentEventTarget(eventTargets[2]);
eventTargets[9].setParentEventTarget(eventTargets[0]);
var ordering = 0;
listeners[0] = createListener(
function(e) {
assertEquals(eventTargets[2], e.currentTarget);
assertEquals(eventTargets[0], e.target);
assertEquals('First capture listener is not called first', 0, ordering);
ordering++;
});
listeners[1] = createListener(
function(e) {
assertEquals(eventTargets[1], e.currentTarget);
assertEquals(eventTargets[0], e.target);
assertEquals('2nd capture listener is not called 2nd', 1, ordering);
ordering++;
});
listeners[2] = createListener(
function(e) {
assertEquals(eventTargets[0], e.currentTarget);
assertEquals(eventTargets[0], e.target);
assertEquals('3rd capture listener is not called 3rd', 2, ordering);
ordering++;
});
listen(eventTargets[2], EventType.A, listeners[0], true);
listen(eventTargets[1], EventType.A, listeners[1], true);
listen(eventTargets[0], EventType.A, listeners[2], true);
// These should not be called.
listen(eventTargets[3], EventType.A, listeners[3], true);
listen(eventTargets[0], EventType.B, listeners[4], true);
listen(eventTargets[0], EventType.C, listeners[5], true);
listen(eventTargets[1], EventType.B, listeners[6], true);
listen(eventTargets[1], EventType.C, listeners[7], true);
listen(eventTargets[2], EventType.B, listeners[8], true);
listen(eventTargets[2], EventType.C, listeners[9], true);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertListenerIsCalled(listeners[1], times(1));
assertListenerIsCalled(listeners[2], times(1));
assertNoOtherListenerIsCalled();
}
function testBubble() {
eventTargets[0].setParentEventTarget(eventTargets[1]);
eventTargets[1].setParentEventTarget(eventTargets[2]);
eventTargets[9].setParentEventTarget(eventTargets[0]);
var ordering = 0;
listeners[0] = createListener(
function(e) {
assertEquals(eventTargets[0], e.currentTarget);
assertEquals(eventTargets[0], e.target);
assertEquals('First bubble listener is not called first', 0, ordering);
ordering++;
});
listeners[1] = createListener(
function(e) {
assertEquals(eventTargets[1], e.currentTarget);
assertEquals(eventTargets[0], e.target);
assertEquals('2nd bubble listener is not called 2nd', 1, ordering);
ordering++;
});
listeners[2] = createListener(
function(e) {
assertEquals(eventTargets[2], e.currentTarget);
assertEquals(eventTargets[0], e.target);
assertEquals('3rd bubble listener is not called 3rd', 2, ordering);
ordering++;
});
listen(eventTargets[0], EventType.A, listeners[0]);
listen(eventTargets[1], EventType.A, listeners[1]);
listen(eventTargets[2], EventType.A, listeners[2]);
// These should not be called.
listen(eventTargets[3], EventType.A, listeners[3]);
listen(eventTargets[0], EventType.B, listeners[4]);
listen(eventTargets[0], EventType.C, listeners[5]);
listen(eventTargets[1], EventType.B, listeners[6]);
listen(eventTargets[1], EventType.C, listeners[7]);
listen(eventTargets[2], EventType.B, listeners[8]);
listen(eventTargets[2], EventType.C, listeners[9]);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertListenerIsCalled(listeners[1], times(1));
assertListenerIsCalled(listeners[2], times(1));
assertNoOtherListenerIsCalled();
}
function testCaptureAndBubble() {
eventTargets[0].setParentEventTarget(eventTargets[1]);
eventTargets[1].setParentEventTarget(eventTargets[2]);
listen(eventTargets[0], EventType.A, listeners[0], true);
listen(eventTargets[1], EventType.A, listeners[1], true);
listen(eventTargets[2], EventType.A, listeners[2], true);
listen(eventTargets[0], EventType.A, listeners[3]);
listen(eventTargets[1], EventType.A, listeners[4]);
listen(eventTargets[2], EventType.A, listeners[5]);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertListenerIsCalled(listeners[1], times(1));
assertListenerIsCalled(listeners[2], times(1));
assertListenerIsCalled(listeners[3], times(1));
assertListenerIsCalled(listeners[4], times(1));
assertListenerIsCalled(listeners[5], times(1));
assertNoOtherListenerIsCalled();
}
function testPreventDefaultByReturningFalse() {
listeners[0] = createListener(function(e) { return false; });
listeners[1] = createListener(function(e) { return true; });
listen(eventTargets[0], EventType.A, listeners[0]);
listen(eventTargets[0], EventType.A, listeners[1]);
var result = dispatchEvent(eventTargets[0], EventType.A);
assertFalse(result);
}
function testPreventDefault() {
listeners[0] = createListener(function(e) { e.preventDefault(); });
listeners[1] = createListener(function(e) { return true; });
listen(eventTargets[0], EventType.A, listeners[0]);
listen(eventTargets[0], EventType.A, listeners[1]);
var result = dispatchEvent(eventTargets[0], EventType.A);
assertFalse(result);
}
function testPreventDefaultAtCapture() {
listeners[0] = createListener(function(e) { e.preventDefault(); });
listeners[1] = createListener(function(e) { return true; });
listen(eventTargets[0], EventType.A, listeners[0], true);
listen(eventTargets[0], EventType.A, listeners[1], true);
var result = dispatchEvent(eventTargets[0], EventType.A);
assertFalse(result);
}
function testStopPropagation() {
eventTargets[0].setParentEventTarget(eventTargets[1]);
eventTargets[1].setParentEventTarget(eventTargets[2]);
listeners[0] = createListener(function(e) { e.stopPropagation(); });
listen(eventTargets[0], EventType.A, listeners[0]);
listen(eventTargets[0], EventType.A, listeners[1]);
listen(eventTargets[1], EventType.A, listeners[2]);
listen(eventTargets[2], EventType.A, listeners[3]);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertListenerIsCalled(listeners[1], times(1));
assertNoOtherListenerIsCalled();
}
function testStopPropagation2() {
eventTargets[0].setParentEventTarget(eventTargets[1]);
eventTargets[1].setParentEventTarget(eventTargets[2]);
listeners[1] = createListener(function(e) { e.stopPropagation(); });
listen(eventTargets[0], EventType.A, listeners[0]);
listen(eventTargets[0], EventType.A, listeners[1]);
listen(eventTargets[1], EventType.A, listeners[2]);
listen(eventTargets[2], EventType.A, listeners[3]);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertListenerIsCalled(listeners[1], times(1));
assertNoOtherListenerIsCalled();
}
function testStopPropagation3() {
eventTargets[0].setParentEventTarget(eventTargets[1]);
eventTargets[1].setParentEventTarget(eventTargets[2]);
listeners[2] = createListener(function(e) { e.stopPropagation(); });
listen(eventTargets[0], EventType.A, listeners[0]);
listen(eventTargets[0], EventType.A, listeners[1]);
listen(eventTargets[1], EventType.A, listeners[2]);
listen(eventTargets[2], EventType.A, listeners[3]);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertListenerIsCalled(listeners[1], times(1));
assertListenerIsCalled(listeners[2], times(1));
assertNoOtherListenerIsCalled();
}
function testStopPropagationAtCapture() {
eventTargets[0].setParentEventTarget(eventTargets[1]);
eventTargets[1].setParentEventTarget(eventTargets[2]);
listeners[0] = createListener(function(e) { e.stopPropagation(); });
listen(eventTargets[2], EventType.A, listeners[0], true);
listen(eventTargets[1], EventType.A, listeners[1], true);
listen(eventTargets[0], EventType.A, listeners[2], true);
listen(eventTargets[0], EventType.A, listeners[3]);
listen(eventTargets[1], EventType.A, listeners[4]);
listen(eventTargets[2], EventType.A, listeners[5]);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertNoOtherListenerIsCalled();
}
function testHandleEvent() {
if (!objectTypeListenerSupported) {
return;
}
var obj = {};
obj.handleEvent = goog.testing.recordFunction();
listen(eventTargets[0], EventType.A, obj);
dispatchEvent(eventTargets[0], EventType.A);
assertEquals(1, obj.handleEvent.getCallCount());
}
function testListenOnce() {
if (!listenOnce) {
return;
}
listenOnce(eventTargets[0], EventType.A, listeners[0], true);
listenOnce(eventTargets[0], EventType.A, listeners[1]);
listenOnce(eventTargets[0], EventType.B, listeners[2]);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertListenerIsCalled(listeners[1], times(1));
assertListenerIsCalled(listeners[2], times(0));
assertNoOtherListenerIsCalled();
resetListeners();
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(0));
assertListenerIsCalled(listeners[1], times(0));
assertListenerIsCalled(listeners[2], times(0));
dispatchEvent(eventTargets[0], EventType.B);
assertListenerIsCalled(listeners[2], times(1));
assertNoOtherListenerIsCalled();
}
function testUnlistenInListen() {
listeners[1] = createListener(
function(e) {
unlisten(eventTargets[0], EventType.A, listeners[1]);
unlisten(eventTargets[0], EventType.A, listeners[2]);
});
listen(eventTargets[0], EventType.A, listeners[0]);
listen(eventTargets[0], EventType.A, listeners[1]);
listen(eventTargets[0], EventType.A, listeners[2]);
listen(eventTargets[0], EventType.A, listeners[3]);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertListenerIsCalled(listeners[1], times(1));
assertListenerIsCalled(listeners[2], times(0));
assertListenerIsCalled(listeners[3], times(1));
assertNoOtherListenerIsCalled();
resetListeners();
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertListenerIsCalled(listeners[1], times(0));
assertListenerIsCalled(listeners[2], times(0));
assertListenerIsCalled(listeners[3], times(1));
assertNoOtherListenerIsCalled();
}
function testUnlistenByKeyInListen() {
if (!unlistenByKey) {
return;
}
var key1, key2;
listeners[1] = createListener(
function(e) {
unlistenByKey(eventTargets[0], key1);
unlistenByKey(eventTargets[0], key2);
});
listen(eventTargets[0], EventType.A, listeners[0]);
key1 = listen(eventTargets[0], EventType.A, listeners[1]);
key2 = listen(eventTargets[0], EventType.A, listeners[2]);
listen(eventTargets[0], EventType.A, listeners[3]);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertListenerIsCalled(listeners[1], times(1));
assertListenerIsCalled(listeners[2], times(0));
assertListenerIsCalled(listeners[3], times(1));
assertNoOtherListenerIsCalled();
resetListeners();
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertListenerIsCalled(listeners[1], times(0));
assertListenerIsCalled(listeners[2], times(0));
assertListenerIsCalled(listeners[3], times(1));
assertNoOtherListenerIsCalled();
}
function testSetParentEventTarget() {
assertNull(eventTargets[0].getParentEventTarget());
eventTargets[0].setParentEventTarget(eventTargets[1]);
assertEquals(eventTargets[1], eventTargets[0].getParentEventTarget());
assertNull(eventTargets[1].getParentEventTarget());
eventTargets[0].setParentEventTarget(null);
assertNull(eventTargets[0].getParentEventTarget());
}
function testListenOnceAfterListenDoesNotChangeExistingListener() {
if (!listenOnce) {
return;
}
listen(eventTargets[0], EventType.A, listeners[0]);
listenOnce(eventTargets[0], EventType.A, listeners[0]);
dispatchEvent(eventTargets[0], EventType.A);
dispatchEvent(eventTargets[0], EventType.A);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(3));
assertNoOtherListenerIsCalled();
}
function testListenOnceAfterListenOnceDoesNotChangeExistingListener() {
if (!listenOnce) {
return;
}
listenOnce(eventTargets[0], EventType.A, listeners[0]);
listenOnce(eventTargets[0], EventType.A, listeners[0]);
dispatchEvent(eventTargets[0], EventType.A);
dispatchEvent(eventTargets[0], EventType.A);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(1));
assertNoOtherListenerIsCalled();
}
function testListenAfterListenOnceRemoveOnceness() {
if (!listenOnce) {
return;
}
listenOnce(eventTargets[0], EventType.A, listeners[0]);
listen(eventTargets[0], EventType.A, listeners[0]);
dispatchEvent(eventTargets[0], EventType.A);
dispatchEvent(eventTargets[0], EventType.A);
dispatchEvent(eventTargets[0], EventType.A);
assertListenerIsCalled(listeners[0], times(3));
assertNoOtherListenerIsCalled();
}
function testUnlistenAfterListenOnce() {
if (!listenOnce) {
return;
}
listenOnce(eventTargets[0], EventType.A, listeners[0]);
unlisten(eventTargets[0], EventType.A, listeners[0]);
dispatchEvent(eventTargets[0], EventType.A);
listen(eventTargets[0], EventType.A, listeners[0]);
listenOnce(eventTargets[0], EventType.A, listeners[0]);
unlisten(eventTargets[0], EventType.A, listeners[0]);
dispatchEvent(eventTargets[0], EventType.A);
listenOnce(eventTargets[0], EventType.A, listeners[0]);
listen(eventTargets[0], EventType.A, listeners[0]);
unlisten(eventTargets[0], EventType.A, listeners[0]);
dispatchEvent(eventTargets[0], EventType.A);
listenOnce(eventTargets[0], EventType.A, listeners[0]);
listenOnce(eventTargets[0], EventType.A, listeners[0]);
unlisten(eventTargets[0], EventType.A, listeners[0]);
dispatchEvent(eventTargets[0], EventType.A);
assertNoOtherListenerIsCalled();
}
function testRemoveAllWithType() {
if (!removeAll) {
return;
}
listen(eventTargets[0], EventType.A, listeners[0], true);
listen(eventTargets[0], EventType.A, listeners[1]);
listen(eventTargets[0], EventType.C, listeners[2], true);
listen(eventTargets[0], EventType.C, listeners[3]);
listen(eventTargets[0], EventType.B, listeners[4], true);
listen(eventTargets[0], EventType.B, listeners[5], true);
listen(eventTargets[0], EventType.B, listeners[6]);
listen(eventTargets[0], EventType.B, listeners[7]);
assertEquals(4, removeAll(eventTargets[0], EventType.B));
dispatchEvent(eventTargets[0], EventType.A);
dispatchEvent(eventTargets[0], EventType.B);
dispatchEvent(eventTargets[0], EventType.C);
assertListenerIsCalled(listeners[0], times(1));
assertListenerIsCalled(listeners[1], times(1));
assertListenerIsCalled(listeners[2], times(1));
assertListenerIsCalled(listeners[3], times(1));
assertNoOtherListenerIsCalled();
}
function testRemoveAll() {
if (!removeAll) {
return;
}
listen(eventTargets[0], EventType.A, listeners[0], true);
listen(eventTargets[0], EventType.A, listeners[1]);
listen(eventTargets[0], EventType.C, listeners[2], true);
listen(eventTargets[0], EventType.C, listeners[3]);
listen(eventTargets[0], EventType.B, listeners[4], true);
listen(eventTargets[0], EventType.B, listeners[5], true);
listen(eventTargets[0], EventType.B, listeners[6]);
listen(eventTargets[0], EventType.B, listeners[7]);
assertEquals(8, removeAll(eventTargets[0]));
dispatchEvent(eventTargets[0], EventType.A);
dispatchEvent(eventTargets[0], EventType.B);
dispatchEvent(eventTargets[0], EventType.C);
assertNoOtherListenerIsCalled();
}
function testGetListeners() {
if (!getListeners) {
return;
}
listen(eventTargets[0], EventType.A, listeners[0], true);
listen(eventTargets[0], EventType.A, listeners[1], true);
listen(eventTargets[0], EventType.A, listeners[2]);
listen(eventTargets[0], EventType.A, listeners[3]);
var l = getListeners(eventTargets[0], EventType.A, true);
assertEquals(2, l.length);
assertEquals(listeners[0], l[0].listener);
assertEquals(listeners[1], l[1].listener);
l = getListeners(eventTargets[0], EventType.A, false);
assertEquals(2, l.length);
assertEquals(listeners[2], l[0].listener);
assertEquals(listeners[3], l[1].listener);
l = getListeners(eventTargets[0], EventType.B, true);
assertEquals(0, l.length);
}
function testGetListener() {
if (!getListener) {
return;
}
listen(eventTargets[0], EventType.A, listeners[0], true);
assertNotNull(getListener(eventTargets[0], EventType.A, listeners[0], true));
assertNull(
getListener(eventTargets[0], EventType.A, listeners[0], true, {}));
assertNull(getListener(eventTargets[1], EventType.A, listeners[0], true));
assertNull(getListener(eventTargets[0], EventType.B, listeners[0], true));
assertNull(getListener(eventTargets[0], EventType.A, listeners[1], true));
}
function testHasListener() {
if (!hasListener) {
return;
}
assertFalse(hasListener(eventTargets[0]));
listen(eventTargets[0], EventType.A, listeners[0], true);
assertTrue(hasListener(eventTargets[0]));
assertTrue(hasListener(eventTargets[0], EventType.A));
assertTrue(hasListener(eventTargets[0], EventType.A, true));
assertTrue(hasListener(eventTargets[0], undefined, true));
assertFalse(hasListener(eventTargets[0], EventType.A, false));
assertFalse(hasListener(eventTargets[0], undefined, false));
assertFalse(hasListener(eventTargets[0], EventType.B));
assertFalse(hasListener(eventTargets[0], EventType.B, true));
assertFalse(hasListener(eventTargets[1]));
}
function testFiringEventBeforeDisposeInternalWorks() {
/**
* @extends {goog.events.EventTarget}
* @constructor
*/
var MockTarget = function() {
goog.base(this);
};
goog.inherits(MockTarget, goog.events.EventTarget);
MockTarget.prototype.disposeInternal = function() {
dispatchEvent(this, EventType.A);
goog.base(this, 'disposeInternal');
};
var t = new MockTarget();
try {
listen(t, EventType.A, listeners[0]);
t.dispose();
assertListenerIsCalled(listeners[0], times(1));
} catch (e) {
goog.dispose(t);
}
}
function testLoopDetection() {
var target = new goog.events.EventTarget();
target.setParentEventTarget(target);
try {
target.dispatchEvent('string');
fail('expected error');
} catch (e) {
assertContains('infinite', e.message);
}
}
| odajima-yu/closure-rails | vendor/assets/javascripts/goog/events/eventtargettester.js | JavaScript | mit | 32,410 |
// No generics for getters and setters
({ set foo<T>(newFoo) {} })
| facebook/flow | src/parser/test/flow/invalid_syntax/migrated_0012.js | JavaScript | mit | 67 |
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs');
var morgan = require('morgan');
var routes = require('./routes/index');
var number = require('./routes/number');
var array = require('./routes/array');
var bool = require('./routes/bool');
var integer = require('./routes/int');
var string = require('./routes/string');
var byte = require('./routes/byte');
var date = require('./routes/date');
var datetime = require('./routes/datetime');
var datetimeRfc1123 = require('./routes/datetime-rfc1123');
var duration = require('./routes/duration');
var complex = require('./routes/complex');
var report = require('./routes/report');
var dictionary = require('./routes/dictionary');
var paths = require('./routes/paths');
var queries = require('./routes/queries');
var pathitem = require('./routes/pathitem');
var header = require('./routes/header');
var reqopt = require('./routes/reqopt');
var httpResponses = require('./routes/httpResponses');
var files = require('./routes/files');
var formData = require('./routes/formData');
var lros = require('./routes/lros');
var paging = require('./routes/paging');
var modelFlatten = require('./routes/model-flatten');
var azureUrl = require('./routes/azureUrl');
var azureSpecial = require('./routes/azureSpecials');
var parameterGrouping = require('./routes/azureParameterGrouping.js');
var validation = require('./routes/validation.js');
var customUri = require('./routes/customUri.js');
var xml = require('./routes/xml.js'); // XML serialization
var util = require('util');
var app = express();
//set up server log
var now = new Date();
var logFileName = 'AccTestServer-' + now.getHours() +
now.getMinutes() + now.getSeconds() + '.log';
var testResultDir = path.join(__dirname, '../../../../TestResults');
if (!fs.existsSync(testResultDir)) {
fs.mkdirSync(testResultDir);
}
var logfile = fs.createWriteStream(path.join(testResultDir, logFileName), {flags: 'a'});
app.use(morgan('combined', {stream: logfile}));
var azurecoverage = {};
var optionalCoverage = {};
var coverage = {
"getArrayNull": 0,
"getArrayEmpty": 0,
"putArrayEmpty": 0,
"getArrayInvalid": 0,
"getArrayBooleanValid": 0,
"putArrayBooleanValid": 0,
"getArrayBooleanWithNull": 0,
"getArrayBooleanWithString": 0,
"getArrayIntegerValid": 0,
"putArrayIntegerValid": 0,
"getArrayIntegerWithNull": 0,
"getArrayIntegerWithString": 0,
"getArrayLongValid": 0,
"putArrayLongValid": 0,
"getArrayLongWithNull": 0,
"getArrayLongWithString": 0,
"getArrayFloatValid": 0,
"putArrayFloatValid": 0,
"getArrayFloatWithNull": 0,
"getArrayFloatWithString": 0,
"getArrayDoubleValid": 0,
"putArrayDoubleValid": 0,
"getArrayDoubleWithNull": 0,
"getArrayDoubleWithString": 0,
"getArrayStringValid": 0,
"putArrayStringValid": 0,
"getArrayStringWithNull": 0,
"getArrayStringWithNumber": 0,
"getArrayDateValid": 0,
"putArrayDateValid": 0,
"getArrayDateWithNull": 0,
"getArrayDateWithInvalidChars": 0,
"getArrayDateTimeValid": 0,
"putArrayDateTimeValid": 0,
"getArrayDateTimeWithNull": 0,
"getArrayDateTimeWithInvalidChars": 0,
"getArrayDateTimeRfc1123Valid": 0,
"putArrayDateTimeRfc1123Valid": 0,
"getArrayDurationValid": 0,
"putArrayDurationValid": 0,
"getArrayUuidValid": 0,
"getArrayUuidWithInvalidChars": 0,
"putArrayUuidValid": 0,
"getArrayByteValid": 0,
"putArrayByteValid": 0,
"getArrayByteWithNull": 0,
"getArrayArrayNull": 0,
"getArrayArrayEmpty": 0,
"getArrayArrayItemNull": 0,
"getArrayArrayItemEmpty": 0,
"getArrayArrayValid": 0,
"putArrayArrayValid": 0,
"getArrayComplexNull": 0,
"getArrayComplexEmpty": 0,
"getArrayComplexItemNull": 0,
"getArrayComplexItemEmpty": 0,
"getArrayComplexValid": 0,
"putArrayComplexValid": 0,
"getArrayDictionaryNull": 0,
"getArrayDictionaryEmpty": 0,
"getArrayDictionaryItemNull": 0,
"getArrayDictionaryItemEmpty": 0,
"getArrayDictionaryValid": 0,
"putArrayDictionaryValid": 0,
"getBoolTrue" : 0,
"putBoolTrue" : 0,
"getBoolFalse" : 0,
"putBoolFalse" : 0,
"getBoolInvalid" : 0,
"getBoolNull" : 0,
"getByteNull": 0,
"getByteEmpty": 0,
"getByteNonAscii": 0,
"putByteNonAscii": 0,
"getByteInvalid": 0,
"getDateNull": 0,
"getDateInvalid": 0,
"getDateOverflow": 0,
"getDateUnderflow": 0,
"getDateMax": 0,
"putDateMax": 0,
"getDateMin": 0,
"putDateMin": 0,
"getDateTimeNull": 0,
"getDateTimeInvalid": 0,
"getDateTimeOverflow": 0,
"getDateTimeUnderflow": 0,
"putDateTimeMaxUtc": 0,
"getDateTimeMaxUtcLowercase": 0,
"getDateTimeMaxUtcUppercase": 0,
"getDateTimeMaxLocalPositiveOffsetLowercase": 0,
"getDateTimeMaxLocalPositiveOffsetUppercase": 0,
"getDateTimeMaxLocalNegativeOffsetLowercase": 0,
"getDateTimeMaxLocalNegativeOffsetUppercase": 0,
"getDateTimeMinUtc": 0,
"putDateTimeMinUtc": 0,
"getDateTimeMinLocalPositiveOffset": 0,
"getDateTimeMinLocalNegativeOffset": 0,
"getDateTimeRfc1123Null": 0,
"getDateTimeRfc1123Invalid": 0,
"getDateTimeRfc1123Overflow": 0,
"getDateTimeRfc1123Underflow": 0,
"getDateTimeRfc1123MinUtc": 0,
"putDateTimeRfc1123Max": 0,
"putDateTimeRfc1123Min": 0,
"getDateTimeRfc1123MaxUtcLowercase": 0,
"getDateTimeRfc1123MaxUtcUppercase": 0,
"getIntegerNull": 0,
"getIntegerInvalid": 0,
"getIntegerOverflow" : 0,
"getIntegerUnderflow": 0,
"getLongOverflow": 0,
"getLongUnderflow": 0,
"putIntegerMax": 0,
"putLongMax": 0,
"putIntegerMin": 0,
"putLongMin": 0,
"getNumberNull": 0,
"getFloatInvalid": 0,
"getDoubleInvalid": 0,
"getFloatBigScientificNotation": 0,
"putFloatBigScientificNotation": 0,
"getDoubleBigScientificNotation": 0,
"putDoubleBigScientificNotation": 0,
"getDoubleBigPositiveDecimal" : 0,
"putDoubleBigPositiveDecimal" : 0,
"getDoubleBigNegativeDecimal" : 0,
"putDoubleBigNegativeDecimal" : 0,
"getFloatSmallScientificNotation" : 0,
"putFloatSmallScientificNotation" : 0,
"getDoubleSmallScientificNotation" : 0,
"putDoubleSmallScientificNotation" : 0,
"getStringNull": 0,
"putStringNull": 0,
"getStringEmpty": 0,
"putStringEmpty": 0,
"getStringMultiByteCharacters": 0,
"putStringMultiByteCharacters": 0,
"getStringWithLeadingAndTrailingWhitespace" : 0,
"putStringWithLeadingAndTrailingWhitespace" : 0,
"getStringNotProvided": 0,
"getEnumNotExpandable": 0,
"putEnumNotExpandable":0,
"putComplexBasicValid": 0,
"getComplexBasicValid": 0,
"getComplexBasicEmpty": 0,
"getComplexBasicNotProvided": 0,
"getComplexBasicNull": 0,
"getComplexBasicInvalid": 0,
"putComplexPrimitiveInteger": 0,
"putComplexPrimitiveLong": 0,
"putComplexPrimitiveFloat": 0,
"putComplexPrimitiveDouble": 0,
"putComplexPrimitiveBool": 0,
"putComplexPrimitiveString": 0,
"putComplexPrimitiveDate": 0,
"putComplexPrimitiveDateTime": 0,
"putComplexPrimitiveDateTimeRfc1123": 0,
"putComplexPrimitiveDuration": 0,
"putComplexPrimitiveByte": 0,
"getComplexPrimitiveInteger": 0,
"getComplexPrimitiveLong": 0,
"getComplexPrimitiveFloat": 0,
"getComplexPrimitiveDouble": 0,
"getComplexPrimitiveBool": 0,
"getComplexPrimitiveString": 0,
"getComplexPrimitiveDate": 0,
"getComplexPrimitiveDateTime": 0,
"getComplexPrimitiveDateTimeRfc1123": 0,
"getComplexPrimitiveDuration": 0,
"getComplexPrimitiveByte": 0,
"putComplexArrayValid": 0,
"putComplexArrayEmpty": 0,
"getComplexArrayValid": 0,
"getComplexArrayEmpty": 0,
"getComplexArrayNotProvided": 0,
"putComplexDictionaryValid": 0,
"putComplexDictionaryEmpty": 0,
"getComplexDictionaryValid": 0,
"getComplexDictionaryEmpty": 0,
"getComplexDictionaryNull": 0,
"getComplexDictionaryNotProvided": 0,
"putComplexInheritanceValid": 0,
"getComplexInheritanceValid": 0,
"putComplexPolymorphismValid": 0,
"getComplexPolymorphismValid": 0,
"putComplexPolymorphicRecursiveValid": 0,
"getComplexPolymorphicRecursiveValid": 0,
"putComplexReadOnlyPropertyValid": 0,
"UrlPathsBoolFalse": 0,
"UrlPathsBoolTrue": 0,
"UrlPathsIntPositive": 0,
"UrlPathsIntNegative": 0,
"UrlPathsLongPositive": 0,
"UrlPathsLongNegative": 0,
"UrlPathsFloatPositive": 0,
"UrlPathsFloatNegative": 0,
"UrlPathsDoublePositive": 0,
"UrlPathsDoubleNegative": 0,
"UrlPathsStringUrlEncoded": 0,
"UrlPathsStringEmpty": 0,
"UrlPathsEnumValid":0,
"UrlPathsByteMultiByte": 0,
"UrlPathsByteEmpty": 0,
"UrlPathsDateValid": 0,
"UrlPathsDateTimeValid": 0,
"UrlQueriesBoolFalse": 0,
"UrlQueriesBoolTrue": 0,
"UrlQueriesBoolNull": 0,
"UrlQueriesIntPositive": 0,
"UrlQueriesIntNegative": 0,
"UrlQueriesIntNull": 0,
"UrlQueriesLongPositive": 0,
"UrlQueriesLongNegative": 0,
"UrlQueriesLongNull": 0,
"UrlQueriesFloatPositive": 0,
"UrlQueriesFloatNegative": 0,
"UrlQueriesFloatNull": 0,
"UrlQueriesDoublePositive": 0,
"UrlQueriesDoubleNegative": 0,
"UrlQueriesDoubleNull": 0,
"UrlQueriesStringUrlEncoded": 0,
"UrlQueriesStringEmpty": 0,
"UrlQueriesStringNull": 0,
"UrlQueriesEnumValid": 0,
"UrlQueriesEnumNull": 0,
"UrlQueriesByteMultiByte": 0,
"UrlQueriesByteEmpty": 0,
"UrlQueriesByteNull": 0,
"UrlQueriesDateValid": 0,
"UrlQueriesDateNull": 0,
"UrlQueriesDateTimeValid": 0,
"UrlQueriesDateTimeNull": 0,
"UrlQueriesArrayCsvNull": 0,
"UrlQueriesArrayCsvEmpty": 0,
"UrlQueriesArrayCsvValid": 0,
//Once all the languages implement this test, the scenario counter should be reset to zero. It is currently implemented in C# and Python
"UrlQueriesArrayMultiNull": 1,
"UrlQueriesArrayMultiEmpty": 1,
"UrlQueriesArrayMultiValid": 1,
"UrlQueriesArraySsvValid": 0,
"UrlQueriesArrayPipesValid": 0,
"UrlQueriesArrayTsvValid": 0,
"UrlPathItemGetAll": 0,
"UrlPathItemGetGlobalNull": 0,
"UrlPathItemGetGlobalAndLocalNull": 0,
"UrlPathItemGetPathItemAndLocalNull": 0,
"putDictionaryEmpty": 0,
"getDictionaryNull": 0,
"getDictionaryEmpty": 0,
"getDictionaryInvalid": 0,
"getDictionaryNullValue": 0,
"getDictionaryNullkey": 0,
"getDictionaryKeyEmptyString": 0,
"getDictionaryBooleanValid": 0,
"getDictionaryBooleanWithNull": 0,
"getDictionaryBooleanWithString": 0,
"getDictionaryIntegerValid": 0,
"getDictionaryIntegerWithNull": 0,
"getDictionaryIntegerWithString": 0,
"getDictionaryLongValid": 0,
"getDictionaryLongWithNull": 0,
"getDictionaryLongWithString": 0,
"getDictionaryFloatValid": 0,
"getDictionaryFloatWithNull": 0,
"getDictionaryFloatWithString": 0,
"getDictionaryDoubleValid": 0,
"getDictionaryDoubleWithNull": 0,
"getDictionaryDoubleWithString": 0,
"getDictionaryStringValid": 0,
"getDictionaryStringWithNull": 0,
"getDictionaryStringWithNumber": 0,
"getDictionaryDateValid": 0,
"getDictionaryDateWithNull": 0,
"getDictionaryDateWithInvalidChars": 0,
"getDictionaryDateTimeValid": 0,
"getDictionaryDateTimeWithNull": 0,
"getDictionaryDateTimeWithInvalidChars": 0,
"getDictionaryDateTimeRfc1123Valid": 0,
"getDictionaryDurationValid": 0,
"getDictionaryByteValid": 0,
"getDictionaryByteWithNull": 0,
"putDictionaryBooleanValid": 0,
"putDictionaryIntegerValid": 0,
"putDictionaryLongValid": 0,
"putDictionaryFloatValid": 0,
"putDictionaryDoubleValid": 0,
"putDictionaryStringValid": 0,
"putDictionaryDateValid": 0,
"putDictionaryDateTimeValid": 0,
"putDictionaryDateTimeRfc1123Valid": 0,
"putDictionaryDurationValid": 0,
"putDictionaryByteValid": 0,
"getDictionaryComplexNull": 0,
"getDictionaryComplexEmpty": 0,
"getDictionaryComplexItemNull": 0,
"getDictionaryComplexItemEmpty": 0,
"getDictionaryComplexValid": 0,
"putDictionaryComplexValid": 0,
"getDictionaryArrayNull": 0,
"getDictionaryArrayEmpty": 0,
"getDictionaryArrayItemNull": 0,
"getDictionaryArrayItemEmpty": 0,
"getDictionaryArrayValid": 0,
"putDictionaryArrayValid": 0,
"getDictionaryDictionaryNull": 0,
"getDictionaryDictionaryEmpty": 0,
"getDictionaryDictionaryItemNull": 0,
"getDictionaryDictionaryItemEmpty": 0,
"getDictionaryDictionaryValid": 0,
"putDictionaryDictionaryValid": 0,
"putDurationPositive": 0,
"getDurationNull": 0,
"getDurationInvalid": 0,
"getDurationPositive": 0,
"HeaderParameterExistingKey": 0,
"HeaderResponseExistingKey": 0,
"HeaderResponseProtectedKey": 0,
"HeaderParameterIntegerPositive": 0,
"HeaderParameterIntegerNegative": 0,
"HeaderParameterLongPositive": 0,
"HeaderParameterLongNegative": 0,
"HeaderParameterFloatPositive": 0,
"HeaderParameterFloatNegative": 0,
"HeaderParameterDoublePositive": 0,
"HeaderParameterDoubleNegative": 0,
"HeaderParameterBoolTrue": 0,
"HeaderParameterBoolFalse": 0,
"HeaderParameterStringValid": 0,
"HeaderParameterStringNull": 0,
"HeaderParameterStringEmpty": 0,
"HeaderParameterDateValid": 0,
"HeaderParameterDateMin": 0,
"HeaderParameterDateTimeValid": 0,
"HeaderParameterDateTimeMin": 0,
"HeaderParameterDateTimeRfc1123Valid": 0,
"HeaderParameterDateTimeRfc1123Min": 0,
"HeaderParameterBytesValid": 0,
"HeaderParameterDurationValid": 0,
"HeaderResponseIntegerPositive": 0,
"HeaderResponseIntegerNegative": 0,
"HeaderResponseLongPositive": 0,
"HeaderResponseLongNegative": 0,
"HeaderResponseFloatPositive": 0,
"HeaderResponseFloatNegative": 0,
"HeaderResponseDoublePositive": 0,
"HeaderResponseDoubleNegative": 0,
"HeaderResponseBoolTrue": 0,
"HeaderResponseBoolFalse": 0,
"HeaderResponseStringValid": 0,
"HeaderResponseStringNull": 0,
"HeaderResponseStringEmpty": 0,
"HeaderParameterEnumValid": 0,
"HeaderParameterEnumNull": 0,
"HeaderResponseEnumValid": 0,
"HeaderResponseEnumNull": 0,
"HeaderResponseDateValid": 0,
"HeaderResponseDateMin": 0,
"HeaderResponseDateTimeValid": 0,
"HeaderResponseDateTimeMin": 0,
"HeaderResponseDateTimeRfc1123Valid": 0,
"HeaderResponseDateTimeRfc1123Min": 0,
"HeaderResponseBytesValid": 0,
"HeaderResponseDurationValid": 0,
"FormdataStreamUploadFile": 0,
"StreamUploadFile": 0,
"ConstantsInPath": 0,
"ConstantsInBody": 0,
"CustomBaseUri": 0,
//Once all the languages implement this test, the scenario counter should be reset to zero. It is currently implemented in C#, Python and node.js
"CustomBaseUriMoreOptions": 1,
'getModelFlattenArray': 0,
'putModelFlattenArray': 0,
'getModelFlattenDictionary': 0,
'putModelFlattenDictionary': 0,
'getModelFlattenResourceCollection': 0,
'putModelFlattenResourceCollection': 0,
'putModelFlattenCustomBase': 0,
'postModelFlattenCustomParameter': 0,
'putModelFlattenCustomGroupedParameter': 0,
/* TODO: only C#, Python and node.js support the base64url format currently. Exclude these tests from code coverage until it is implemented in other languages */
"getStringBase64Encoded": 1,
"getStringBase64UrlEncoded": 1,
"putStringBase64UrlEncoded": 1,
"getStringNullBase64UrlEncoding": 1,
"getArrayBase64Url": 1,
"getDictionaryBase64Url": 1,
"UrlPathsStringBase64Url": 1,
"UrlPathsArrayCSVInPath": 1,
/* TODO: only C# and Python support the unixtime format currently. Exclude these tests from code coverage until it is implemented in other languages */
"getUnixTime": 1,
"getInvalidUnixTime": 1,
"getNullUnixTime": 1,
"putUnixTime": 1,
"UrlPathsIntUnixTime": 1,
/* TODO: Once all the languages implement these tests, the scenario counters should be reset to zero. It is currently implemented in Python */
"getDecimalInvalid": 1,
"getDecimalBig": 1,
"getDecimalSmall": 1,
"getDecimalBigPositiveDecimal" : 1,
"getDecimalBigNegativeDecimal" : 1,
"putDecimalBig": 1,
"putDecimalSmall": 1,
"putDecimalBigPositiveDecimal" : 1,
"getEnumReferenced" : 1,
"putEnumReferenced" : 1,
"getEnumReferencedConstant" : 1,
"putEnumReferencedConstant" : 1
};
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json({strict: false}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/bool', new bool(coverage).router);
app.use('/int', new integer(coverage).router);
app.use('/number', new number(coverage).router);
app.use('/string', new string(coverage).router);
app.use('/byte', new byte(coverage).router);
app.use('/date', new date(coverage).router);
app.use('/datetime', new datetime(coverage, optionalCoverage).router);
app.use('/datetimeRfc1123', new datetimeRfc1123(coverage).router);
app.use('/duration', new duration(coverage, optionalCoverage).router);
app.use('/array', new array(coverage).router);
app.use('/complex', new complex(coverage).router);
app.use('/dictionary', new dictionary(coverage).router);
app.use('/paths', new paths(coverage).router);
app.use('/queries', new queries(coverage).router);
app.use('/pathitem', new pathitem(coverage).router);
app.use('/header', new header(coverage, optionalCoverage).router);
app.use('/reqopt', new reqopt(coverage).router);
app.use('/files', new files(coverage).router);
app.use('/formdata', new formData(coverage).router);
app.use('/http', new httpResponses(coverage, optionalCoverage).router);
app.use('/model-flatten', new modelFlatten(coverage).router);
app.use('/lro', new lros(azurecoverage).router);
app.use('/paging', new paging(azurecoverage).router);
app.use('/azurespecials', new azureSpecial(azurecoverage).router);
app.use('/report', new report(coverage, azurecoverage).router);
app.use('/subscriptions', new azureUrl(azurecoverage).router);
app.use('/parameterGrouping', new parameterGrouping(azurecoverage).router);
app.use('/validation', new validation(coverage).router);
app.use('/customUri', new customUri(coverage).router);
app.use('/xml', new xml().router);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.end(JSON.stringify(err));
});
module.exports = app;
| lmazuel/autorest | src/dev/TestServer/server/app.js | JavaScript | mit | 18,237 |
//// [tests/cases/compiler/pathMappingBasedModuleResolution5_classic.ts] ////
//// [file1.ts]
import {x} from "folder2/file1"
import {y} from "folder3/file2"
import {z} from "components/file3"
import {z1} from "file4"
declare function use(a: any): void;
use(x.toExponential());
use(y.toExponential());
use(z.toExponential());
use(z1.toExponential());
//// [file1.ts]
export var x = 1;
//// [file2.ts]
export var y = 1;
//// [file3.ts]
export var z = 1;
//// [file4.ts]
export var z1 = 1;
//// [file1.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
exports.x = 1;
});
//// [file2.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
exports.y = 1;
});
//// [file3.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
exports.z = 1;
});
//// [file4.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
exports.z1 = 1;
});
//// [file1.js]
define(["require", "exports", "folder2/file1", "folder3/file2", "components/file3", "file4"], function (require, exports, file1_1, file2_1, file3_1, file4_1) {
"use strict";
exports.__esModule = true;
use(file1_1.x.toExponential());
use(file2_1.y.toExponential());
use(file3_1.z.toExponential());
use(file4_1.z1.toExponential());
});
| weswigham/TypeScript | tests/baselines/reference/pathMappingBasedModuleResolution5_classic.js | JavaScript | apache-2.0 | 1,513 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
typeof define === 'function' && define.amd ? define(factory) :
(factory());
}(this, (function () { 'use strict';
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
Zone.__load_patch('bluebird', function (global, Zone) {
// TODO: @JiaLiPassion, we can automatically patch bluebird
// if global.Promise = Bluebird, but sometimes in nodejs,
// global.Promise is not Bluebird, and Bluebird is just be
// used by other libraries such as sequelize, so I think it is
// safe to just expose a method to patch Bluebird explicitly
var BLUEBIRD = 'bluebird';
Zone[Zone.__symbol__(BLUEBIRD)] = function patchBluebird(Bluebird) {
Bluebird.setScheduler(function (fn) {
Zone.current.scheduleMicroTask(BLUEBIRD, fn);
});
};
});
})));
| Geovanny0401/bookStore | bookstore-front/node_modules/zone.js/dist/zone-bluebird.js | JavaScript | apache-2.0 | 1,237 |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright
* (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your choice: -
* GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License
* Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html -
* Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE ==
*
* Useful functions used by almost all dialog window pages. Dialogs should link
* to this file as the very first script on the page.
*/
// Automatically detect the correct document.domain (#123).
(function() {
var d = document.domain;
while (true) {
// Test if we can access a parent property.
try {
var test = window.parent.document.domain;
break;
} catch (e) {
}
// Remove a domain part: www.mytest.example.com => mytest.example.com =>
// example.com ...
d = d.replace(/.*?(?:\.|$)/, '');
if (d.length == 0)
break; // It was not able to detect the domain.
try {
document.domain = d;
} catch (e) {
break;
}
}
})();
// Attention: FCKConfig must be available in the page.
function GetCommonDialogCss(prefix) {
// CSS minified by http://iceyboard.no-ip.org/projects/css_compressor (see
// _dev/css_compression.txt).
return FCKConfig.BasePath
+ 'dialog/common/'
+ '|.ImagePreviewArea{border:#000 1px solid;overflow:auto;width:100%;height:170px;background-color:#fff}.FlashPreviewArea{border:#000 1px solid;padding:5px;overflow:auto;width:100%;height:170px;background-color:#fff}.BtnReset{float:left;background-position:center center;background-image:url(images/reset.gif);width:16px;height:16px;background-repeat:no-repeat;border:1px none;font-size:1px}.BtnLocked,.BtnUnlocked{float:left;background-position:center center;background-image:url(images/locked.gif);width:16px;height:16px;background-repeat:no-repeat;border:none 1px;font-size:1px}.BtnUnlocked{background-image:url(images/unlocked.gif)}.BtnOver{border:outset 1px;cursor:pointer;cursor:hand}';
}
// Gets a element by its Id. Used for shorter coding.
function GetE(elementId) {
return document.getElementById(elementId);
}
function ShowE(element, isVisible) {
if (typeof(element) == 'string')
element = GetE(element);
element.style.display = isVisible ? '' : 'none';
}
function SetAttribute(element, attName, attValue) {
if (attValue == null || attValue.length == 0)
element.removeAttribute(attName, 0); // 0 : Case Insensitive
else
element.setAttribute(attName, attValue, 0); // 0 : Case Insensitive
}
function GetAttribute(element, attName, valueIfNull) {
var oAtt = element.attributes[attName];
if (oAtt == null || !oAtt.specified)
return valueIfNull ? valueIfNull : '';
var oValue = element.getAttribute(attName, 2);
if (oValue == null)
oValue = oAtt.nodeValue;
return (oValue == null ? valueIfNull : oValue);
}
function SelectField(elementId) {
var element = GetE(elementId);
element.focus();
// element.select may not be available for some fields (like <select>).
if (element.select)
element.select();
}
// Functions used by text fields to accept numbers only.
var IsDigit = (function() {
var KeyIdentifierMap = {
End : 35,
Home : 36,
Left : 37,
Right : 39,
'U+00007F' : 46
// Delete
};
return function(e) {
if (!e)
e = event;
var iCode = (e.keyCode || e.charCode);
if (!iCode && e.keyIdentifier && (e.keyIdentifier in KeyIdentifierMap))
iCode = KeyIdentifierMap[e.keyIdentifier];
return ((iCode >= 48 && iCode <= 57) // Numbers
|| (iCode >= 35 && iCode <= 40) // Arrows, Home, End
|| iCode == 8 // Backspace
|| iCode == 46 // Delete
|| iCode == 9 // Tab
);
}
})();
String.prototype.Trim = function() {
return this.replace(/(^\s*)|(\s*$)/g, '');
}
String.prototype.StartsWith = function(value) {
return (this.substr(0, value.length) == value);
}
String.prototype.Remove = function(start, length) {
var s = '';
if (start > 0)
s = this.substring(0, start);
if (start + length < this.length)
s += this.substring(start + length, this.length);
return s;
}
String.prototype.ReplaceAll = function(searchArray, replaceArray) {
var replaced = this;
for (var i = 0; i < searchArray.length; i++) {
replaced = replaced.replace(searchArray[i], replaceArray[i]);
}
return replaced;
}
function OpenFileBrowser(url, width, height) {
// oEditor must be defined.
var iLeft = (oEditor.FCKConfig.ScreenWidth - width) / 2;
var iTop = (oEditor.FCKConfig.ScreenHeight - height) / 2;
var sOptions = "toolbar=no,status=no,resizable=yes,dependent=yes,scrollbars=yes";
sOptions += ",width=" + width;
sOptions += ",height=" + height;
sOptions += ",left=" + iLeft;
sOptions += ",top=" + iTop;
window.open(url, 'FCKBrowseWindow', sOptions);
}
/**
* Utility function to create/update an element with a name attribute in IE, so
* it behaves properly when moved around It also allows to change the name or
* other special attributes in an existing node oEditor : instance of FCKeditor
* where the element will be created oOriginal : current element being edited or
* null if it has to be created nodeName : string with the name of the element
* to create oAttributes : Hash object with the attributes that must be set at
* creation time in IE Those attributes will be set also after the element has
* been created for any other browser to avoid redudant code
*/
function CreateNamedElement(oEditor, oOriginal, nodeName, oAttributes) {
var oNewNode;
// IE doesn't allow easily to change properties of an existing object,
// so remove the old and force the creation of a new one.
var oldNode = null;
if (oOriginal && oEditor.FCKBrowserInfo.IsIE) {
// Force the creation only if some of the special attributes have
// changed:
var bChanged = false;
for (var attName in oAttributes)
bChanged |= (oOriginal.getAttribute(attName, 2) != oAttributes[attName]);
if (bChanged) {
oldNode = oOriginal;
oOriginal = null;
}
}
// If the node existed (and it's not IE), then we just have to update its
// attributes
if (oOriginal) {
oNewNode = oOriginal;
} else {
// #676, IE doesn't play nice with the name or type attribute
if (oEditor.FCKBrowserInfo.IsIE) {
var sbHTML = [];
sbHTML.push('<' + nodeName);
for (var prop in oAttributes) {
sbHTML.push(' ' + prop + '="' + oAttributes[prop] + '"');
}
sbHTML.push('>');
if (!oEditor.FCKListsLib.EmptyElements[nodeName.toLowerCase()])
sbHTML.push('</' + nodeName + '>');
oNewNode = oEditor.FCK.EditorDocument
.createElement(sbHTML.join(''));
// Check if we are just changing the properties of an existing node:
// copy its properties
if (oldNode) {
CopyAttributes(oldNode, oNewNode, oAttributes);
oEditor.FCKDomTools.MoveChildren(oldNode, oNewNode);
oldNode.parentNode.removeChild(oldNode);
oldNode = null;
if (oEditor.FCK.Selection.SelectionData) {
// Trick to refresh the selection object and avoid error in
// fckdialog.html Selection.EnsureSelection
var oSel = oEditor.FCK.EditorDocument.selection;
oEditor.FCK.Selection.SelectionData = oSel.createRange(); // Now
// oSel.type
// will
// be
// 'None'
// reflecting
// the
// real
// situation
}
}
oNewNode = oEditor.FCK.InsertElement(oNewNode);
// FCK.Selection.SelectionData is broken by now since we've
// deleted the previously selected element. So we need to reassign
// it.
if (oEditor.FCK.Selection.SelectionData) {
var range = oEditor.FCK.EditorDocument.body
.createControlRange();
range.add(oNewNode);
oEditor.FCK.Selection.SelectionData = range;
}
} else {
oNewNode = oEditor.FCK.InsertElement(nodeName);
}
}
// Set the basic attributes
for (var attName in oAttributes)
oNewNode.setAttribute(attName, oAttributes[attName], 0); // 0 : Case
// Insensitive
return oNewNode;
}
// Copy all the attributes from one node to the other, kinda like a clone
// But oSkipAttributes is an object with the attributes that must NOT be copied
function CopyAttributes(oSource, oDest, oSkipAttributes) {
var aAttributes = oSource.attributes;
for (var n = 0; n < aAttributes.length; n++) {
var oAttribute = aAttributes[n];
if (oAttribute.specified) {
var sAttName = oAttribute.nodeName;
// We can set the type only once, so do it with the proper value,
// not copying it.
if (sAttName in oSkipAttributes)
continue;
var sAttValue = oSource.getAttribute(sAttName, 2);
if (sAttValue == null)
sAttValue = oAttribute.nodeValue;
oDest.setAttribute(sAttName, sAttValue, 0); // 0 : Case Insensitive
}
}
// The style:
oDest.style.cssText = oSource.style.cssText;
}
| zhangjunfang/eclipse-dir | nsp/src/main/webapp/scripts/lib/fckeditor/editor/dialog/common/fck_dialog_common.js | JavaScript | bsd-2-clause | 8,894 |
/*
* Copyright 2016 Rethink Robotics
*
* Copyright 2016 Chris Smith
*
* 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';
let fs = require('fs');
let path = require('path');
let cmakePath = process.env.CMAKE_PREFIX_PATH;
let cmakePaths = cmakePath.split(':');
let jsMsgPath = 'share/gennodejs/ros';
let packagePaths = {};
module.exports = function (messagePackage) {
if (packagePaths.hasOwnProperty(messagePackage)) {
return packagePaths[messagePackage];
}
// else
const found = cmakePaths.some((cmakePath) => {
let path_ = path.join(cmakePath, jsMsgPath, messagePackage, '_index.js');
if (fs.existsSync(path_)) {
packagePaths[messagePackage] = require(path_);
return true;
}
return false;
});
if (found) {
return packagePaths[messagePackage];
}
// else
throw new Error('Unable to find message package ' + messagePackage + ' from CMAKE_PREFIX_PATH');
};
| tarquasso/softroboticfish6 | fish/pi/ros/catkin_ws/src/rosserial/devel/share/gennodejs/ros/rosserial_msgs/find.js | JavaScript | mit | 1,464 |
/**
* @fileoverview Rule to flag wrapping non-iife in parens
* @author Gyandeep Singh
*/
"use strict";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Checks whether or not a given node is an `Identifier` node which was named a given name.
* @param {ASTNode} node - A node to check.
* @param {string} name - An expected name of the node.
* @returns {boolean} `true` if the node is an `Identifier` node which was named as expected.
*/
function isIdentifier(node, name) {
return node.type === "Identifier" && node.name === name;
}
/**
* Checks whether or not a given node is an argument of a specified method call.
* @param {ASTNode} node - A node to check.
* @param {number} index - An expected index of the node in arguments.
* @param {string} object - An expected name of the object of the method.
* @param {string} property - An expected name of the method.
* @returns {boolean} `true` if the node is an argument of the specified method call.
*/
function isArgumentOfMethodCall(node, index, object, property) {
const parent = node.parent;
return (
parent.type === "CallExpression" &&
parent.callee.type === "MemberExpression" &&
parent.callee.computed === false &&
isIdentifier(parent.callee.object, object) &&
isIdentifier(parent.callee.property, property) &&
parent.arguments[index] === node
);
}
/**
* Checks whether or not a given node is a property descriptor.
* @param {ASTNode} node - A node to check.
* @returns {boolean} `true` if the node is a property descriptor.
*/
function isPropertyDescriptor(node) {
// Object.defineProperty(obj, "foo", {set: ...})
if (isArgumentOfMethodCall(node, 2, "Object", "defineProperty") ||
isArgumentOfMethodCall(node, 2, "Reflect", "defineProperty")
) {
return true;
}
/*
* Object.defineProperties(obj, {foo: {set: ...}})
* Object.create(proto, {foo: {set: ...}})
*/
const grandparent = node.parent.parent;
return grandparent.type === "ObjectExpression" && (
isArgumentOfMethodCall(grandparent, 1, "Object", "create") ||
isArgumentOfMethodCall(grandparent, 1, "Object", "defineProperties")
);
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "enforce getter and setter pairs in objects",
category: "Best Practices",
recommended: false,
url: "https://eslint.org/docs/rules/accessor-pairs"
},
schema: [{
type: "object",
properties: {
getWithoutSet: {
type: "boolean"
},
setWithoutGet: {
type: "boolean"
}
},
additionalProperties: false
}],
messages: {
getter: "Getter is not present.",
setter: "Setter is not present."
}
},
create(context) {
const config = context.options[0] || {};
const checkGetWithoutSet = config.getWithoutSet === true;
const checkSetWithoutGet = config.setWithoutGet !== false;
/**
* Checks a object expression to see if it has setter and getter both present or none.
* @param {ASTNode} node The node to check.
* @returns {void}
* @private
*/
function checkLonelySetGet(node) {
let isSetPresent = false;
let isGetPresent = false;
const isDescriptor = isPropertyDescriptor(node);
for (let i = 0, end = node.properties.length; i < end; i++) {
const property = node.properties[i];
let propToCheck = "";
if (property.kind === "init") {
if (isDescriptor && !property.computed) {
propToCheck = property.key.name;
}
} else {
propToCheck = property.kind;
}
switch (propToCheck) {
case "set":
isSetPresent = true;
break;
case "get":
isGetPresent = true;
break;
default:
// Do nothing
}
if (isSetPresent && isGetPresent) {
break;
}
}
if (checkSetWithoutGet && isSetPresent && !isGetPresent) {
context.report({ node, messageId: "getter" });
} else if (checkGetWithoutSet && isGetPresent && !isSetPresent) {
context.report({ node, messageId: "setter" });
}
}
return {
ObjectExpression(node) {
if (checkSetWithoutGet || checkGetWithoutSet) {
checkLonelySetGet(node);
}
}
};
}
};
| EdwardStudy/myghostblog | versions/1.25.7/node_modules/eslint/lib/rules/accessor-pairs.js | JavaScript | mit | 5,257 |
//used for the media picker dialog
angular.module("umbraco")
.controller("Umbraco.Dialogs.MediaPickerController",
function ($scope, mediaResource, umbRequestHelper, entityResource, $log, mediaHelper, eventsService, treeService, $cookies, $element, $timeout, notificationsService) {
var dialogOptions = $scope.dialogOptions;
$scope.onlyImages = dialogOptions.onlyImages;
$scope.showDetails = dialogOptions.showDetails;
$scope.multiPicker = (dialogOptions.multiPicker && dialogOptions.multiPicker !== "0") ? true : false;
$scope.startNodeId = dialogOptions.startNodeId ? dialogOptions.startNodeId : -1;
$scope.cropSize = dialogOptions.cropSize;
$scope.filesUploading = 0;
$scope.dropping = false;
$scope.progress = 0;
$scope.options = {
url: umbRequestHelper.getApiUrl("mediaApiBaseUrl", "PostAddFile") + "?origin=blueimp",
autoUpload: true,
dropZone: $element.find(".umb-dialogs-mediapicker.browser"),
fileInput: $element.find("input.uploader"),
formData: {
currentFolder: -1
}
};
//preload selected item
$scope.target = undefined;
if(dialogOptions.currentTarget){
$scope.target = dialogOptions.currentTarget;
}
$scope.submitFolder = function(e) {
if (e.keyCode === 13) {
e.preventDefault();
$scope.showFolderInput = false;
mediaResource
.addFolder($scope.newFolderName, $scope.options.formData.currentFolder)
.then(function(data) {
//we've added a new folder so lets clear the tree cache for that specific item
treeService.clearCache({
cacheKey: "__media", //this is the main media tree cache key
childrenOf: data.parentId //clear the children of the parent
});
$scope.gotoFolder(data);
});
}
};
$scope.gotoFolder = function(folder) {
if(!folder){
folder = {id: -1, name: "Media", icon: "icon-folder"};
}
if (folder.id > 0) {
entityResource.getAncestors(folder.id, "media")
.then(function(anc) {
// anc.splice(0,1);
$scope.path = _.filter(anc, function (f) {
return f.path.indexOf($scope.startNodeId) !== -1;
});
});
}
else {
$scope.path = [];
}
//mediaResource.rootMedia()
mediaResource.getChildren(folder.id)
.then(function(data) {
$scope.searchTerm = "";
$scope.images = data.items ? data.items : [];
});
$scope.options.formData.currentFolder = folder.id;
$scope.currentFolder = folder;
};
//This executes prior to the whole processing which we can use to get the UI going faster,
//this also gives us the start callback to invoke to kick of the whole thing
$scope.$on('fileuploadadd', function (e, data) {
$scope.$apply(function () {
$scope.filesUploading++;
});
});
//when one is finished
$scope.$on('fileuploaddone', function (e, data) {
$scope.filesUploading--;
if ($scope.filesUploading == 0) {
$scope.$apply(function () {
$scope.progress = 0;
$scope.gotoFolder($scope.currentFolder);
});
}
//Show notifications!!!!
if (data.result && data.result.notifications && angular.isArray(data.result.notifications)) {
for (var n = 0; n < data.result.notifications.length; n++) {
notificationsService.showNotification(data.result.notifications[n]);
}
}
});
// All these sit-ups are to add dropzone area and make sure it gets removed if dragging is aborted!
$scope.$on('fileuploaddragover', function (e, data) {
if (!$scope.dragClearTimeout) {
$scope.$apply(function () {
$scope.dropping = true;
});
}
else {
$timeout.cancel($scope.dragClearTimeout);
}
$scope.dragClearTimeout = $timeout(function () {
$scope.dropping = null;
$scope.dragClearTimeout = null;
}, 300);
});
$scope.clickHandler = function(image, ev, select) {
ev.preventDefault();
if (image.isFolder && !select) {
$scope.gotoFolder(image);
}else{
eventsService.emit("dialogs.mediaPicker.select", image);
//we have 3 options add to collection (if multi) show details, or submit it right back to the callback
if ($scope.multiPicker) {
$scope.select(image);
image.cssclass = ($scope.dialogData.selection.indexOf(image) > -1) ? "selected" : "";
}else if($scope.showDetails) {
$scope.target= image;
$scope.target.url = mediaHelper.resolveFile(image);
}else{
$scope.submit(image);
}
}
};
$scope.exitDetails = function(){
if(!$scope.currentFolder){
$scope.gotoFolder();
}
$scope.target = undefined;
};
//default root item
if(!$scope.target){
$scope.gotoFolder({ id: $scope.startNodeId, name: "Media", icon: "icon-folder" });
}
}); | gregoriusxu/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/views/common/dialogs/mediapicker.controller.js | JavaScript | mit | 6,762 |
/*
*********************************************************************************************
System Loader Implementation
- Implemented to https://github.com/jorendorff/js-loaders/blob/master/browser-loader.js
- <script type="module"> supported
*********************************************************************************************
*/
var System;
function SystemLoader() {
Loader.call(this);
this.paths = {};
}
// NB no specification provided for System.paths, used ideas discussed in https://github.com/jorendorff/js-loaders/issues/25
function applyPaths(paths, name) {
// most specific (most number of slashes in path) match wins
var pathMatch = '', wildcard, maxSlashCount = 0;
// check to see if we have a paths entry
for (var p in paths) {
var pathParts = p.split('*');
if (pathParts.length > 2)
throw new TypeError('Only one wildcard in a path is permitted');
// exact path match
if (pathParts.length == 1) {
if (name == p) {
pathMatch = p;
break;
}
}
// wildcard path match
else {
var slashCount = p.split('/').length;
if (slashCount >= maxSlashCount &&
name.substr(0, pathParts[0].length) == pathParts[0] &&
name.substr(name.length - pathParts[1].length) == pathParts[1]) {
maxSlashCount = slashCount;
pathMatch = p;
wildcard = name.substr(pathParts[0].length, name.length - pathParts[1].length - pathParts[0].length);
}
}
}
var outPath = paths[pathMatch] || name;
if (typeof wildcard == 'string')
outPath = outPath.replace('*', wildcard);
return outPath;
}
// inline Object.create-style class extension
function LoaderProto() {}
LoaderProto.prototype = Loader.prototype;
SystemLoader.prototype = new LoaderProto();
| nfl/es6-module-loader | src/system.js | JavaScript | mit | 1,825 |
/**
* This component provides a grid holding selected items from a second store of potential
* members. The `store` of this component represents the selected items. The `searchStore`
* represents the potentially selected items.
*
* The default view defined by this class is intended to be easily replaced by deriving a
* new class and overriding the appropriate methods. For example, the following is a very
* different view that uses a date range and a data view:
*
* Ext.define('App.view.DateBoundSearch', {
* extend: 'Ext.view.MultiSelectorSearch',
*
* makeDockedItems: function () {
* return {
* xtype: 'toolbar',
* items: [{
* xtype: 'datefield',
* emptyText: 'Start date...',
* flex: 1
* },{
* xtype: 'datefield',
* emptyText: 'End date...',
* flex: 1
* }]
* };
* },
*
* makeItems: function () {
* return [{
* xtype: 'dataview',
* itemSelector: '.search-item',
* selModel: 'rowselection',
* store: this.store,
* scrollable: true,
* tpl:
* '<tpl for=".">' +
* '<div class="search-item">' +
* '<img src="{icon}">' +
* '<div>{name}</div>' +
* '</div>' +
* '</tpl>'
* }];
* },
*
* getSearchStore: function () {
* return this.items.getAt(0).getStore();
* },
*
* selectRecords: function (records) {
* var view = this.items.getAt(0);
* return view.getSelectionModel().select(records);
* }
* });
*
* **Important**: This class assumes there are two components with specific `reference`
* names assigned to them. These are `"searchField"` and `"searchGrid"`. These components
* are produced by the `makeDockedItems` and `makeItems` method, respectively. When
* overriding these it is important to remember to place these `reference` values on the
* appropriate components.
*/
Ext.define('Ext.view.MultiSelectorSearch', {
extend: 'Ext.panel.Panel',
xtype: 'multiselector-search',
layout: 'fit',
floating: true,
resizable: true,
minWidth: 200,
minHeight: 200,
border: true,
defaultListenerScope: true,
referenceHolder: true,
/**
* @cfg {String} searchText
* This text is displayed as the "emptyText" of the search `textfield`.
*/
searchText: 'Search...',
initComponent: function () {
var me = this,
owner = me.owner,
items = me.makeItems(),
i, item, records, store;
me.dockedItems = me.makeDockedItems();
me.items = items;
store = Ext.data.StoreManager.lookup(me.store);
for (i = items.length; i--; ) {
if ((item = items[i]).xtype === 'grid') {
item.store = store;
item.isSearchGrid = true;
item.selModel = item.selModel || {
type: 'checkboxmodel',
pruneRemoved: false,
listeners: {
selectionchange: 'onSelectionChange'
}
};
Ext.merge(item, me.grid);
if (!item.columns) {
item.hideHeaders = true;
item.columns = [{
flex: 1,
dataIndex: me.field
}];
}
break;
}
}
me.callParent();
records = me.getOwnerStore().getRange();
if (!owner.convertSelectionRecord.$nullFn) {
for (i = records.length; i--; ) {
records[i] = owner.convertSelectionRecord(records[i]);
}
}
if (store.isLoading() || (store.loadCount === 0 && !store.getCount())) {
store.on('load', function() {
if (!me.isDestroyed) {
me.selectRecords(records);
}
}, null, {single: true});
} else {
me.selectRecords(records);
}
},
getOwnerStore: function() {
return this.owner.getStore();
},
afterShow: function () {
var searchField = this.lookupReference('searchField');
this.callParent(arguments);
if (searchField) {
searchField.focus();
}
},
/**
* Returns the store that holds search results. By default this comes from the
* "search grid". If this aspect of the view is changed sufficiently so that the
* search grid cannot be found, this method should be overridden to return the proper
* store.
* @return {Ext.data.Store}
*/
getSearchStore: function () {
var searchGrid = this.lookupReference('searchGrid');
return searchGrid.getStore();
},
makeDockedItems: function () {
return [{
xtype: 'textfield',
reference: 'searchField',
dock: 'top',
hideFieldLabel: true,
emptyText: this.searchText,
triggers: {
clear: {
cls: Ext.baseCSSPrefix + 'form-clear-trigger',
handler: 'onClearSearch',
hidden: true
}
},
listeners: {
change: 'onSearchChange',
buffer: 300
}
}];
},
makeItems: function () {
return [{
xtype: 'grid',
reference: 'searchGrid',
trailingBufferZone: 2,
leadingBufferZone: 2,
viewConfig: {
deferEmptyText: false,
emptyText: 'No results.'
}
}];
},
selectRecords: function (records) {
var searchGrid = this.lookupReference('searchGrid');
return searchGrid.getSelectionModel().select(records);
},
deselectRecords: function(records) {
var searchGrid = this.lookupReference('searchGrid');
return searchGrid.getSelectionModel().deselect(records);
},
search: function (text) {
var me = this,
filter = me.searchFilter,
filters = me.getSearchStore().getFilters();
if (text) {
filters.beginUpdate();
if (filter) {
filter.setValue(text);
} else {
me.searchFilter = filter = new Ext.util.Filter({
id: 'search',
property: me.field,
value: text
});
}
filters.add(filter);
filters.endUpdate();
} else if (filter) {
filters.remove(filter);
}
},
privates: {
onClearSearch: function () {
var searchField = this.lookupReference('searchField');
searchField.setValue(null);
searchField.focus();
},
onSearchChange: function (searchField) {
var value = searchField.getValue(),
trigger = searchField.getTrigger('clear');
trigger.setHidden(!value);
this.search(value);
},
onSelectionChange: function (selModel, selection) {
var owner = this.owner,
store = owner.getStore(),
data = store.data,
remove = 0,
map = {},
add, i, id, record;
for (i = selection.length; i--; ) {
record = selection[i];
id = record.id;
map[id] = record;
if (!data.containsKey(id)) {
(add || (add = [])).push(owner.convertSearchRecord(record));
}
}
for (i = data.length; i--; ) {
record = data.getAt(i);
if (!map[record.id]) {
(remove || (remove = [])).push(record);
}
}
if (add || remove) {
data.splice(data.length, remove, add);
}
}
}
});
| department-of-veterans-affairs/ChartReview | web-app/js/ext-5.1.0/src/view/MultiSelectorSearch.js | JavaScript | apache-2.0 | 8,477 |
//
// Copyright (c) Microsoft and contributors. 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 assert = require('assert');
var fs = require('fs');
var path = require('path');
var util = require('util');
var sinon = require('sinon');
var url = require('url');
var request = require('request');
// Test includes
var testutil = require('../../util/util');
var blobtestutil = require('../../framework/blob-test-utils');
// Lib includes
var common = require('azure-common');
var storage = testutil.libRequire('services/legacyStorage');
var azureutil = common.util;
var azure = testutil.libRequire('azure');
var WebResource = common.WebResource;
var SharedAccessSignature = storage.SharedAccessSignature;
var BlobService = storage.BlobService;
var ServiceClient = common.ServiceClient;
var ExponentialRetryPolicyFilter = common.ExponentialRetryPolicyFilter;
var Constants = common.Constants;
var BlobConstants = Constants.BlobConstants;
var HttpConstants = Constants.HttpConstants;
var ServiceClientConstants = common.ServiceClientConstants;
var QueryStringConstants = Constants.QueryStringConstants;
var containerNames = [];
var containerNamesPrefix = 'cont';
var blobNames = [];
var blobNamesPrefix = 'blob';
var testPrefix = 'blobservice-tests';
var blobService;
var suiteUtil;
describe('BlobService', function () {
before(function (done) {
blobService = storage.createBlobService()
.withFilter(new common.ExponentialRetryPolicyFilter());
suiteUtil = blobtestutil.createBlobTestUtils(blobService, testPrefix);
suiteUtil.setupSuite(done);
});
after(function (done) {
suiteUtil.teardownSuite(done);
});
beforeEach(function (done) {
suiteUtil.setupTest(done);
});
afterEach(function (done) {
suiteUtil.teardownTest(done);
});
describe('createContainer', function () {
it('should detect incorrect container names', function (done) {
assert.throws(function () { blobService.createContainer(null, function () { }); },
BlobService.incorrectContainerNameErr);
assert.throws(function () { blobService.createContainer('', function () { }); },
BlobService.incorrectContainerNameErr);
assert.throws(function () { blobService.createContainer('as', function () { }); },
BlobService.incorrectContainerNameFormatErr);
assert.throws(function () { blobService.createContainer('a--s', function () { }); },
BlobService.incorrectContainerNameFormatErr);
assert.throws(function () { blobService.createContainer('cont-', function () { }); },
BlobService.incorrectContainerNameFormatErr);
assert.throws(function () { blobService.createContainer('conTain', function () { }); },
BlobService.incorrectContainerNameFormatErr);
done();
});
it('should work', function (done) {
var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
blobService.createContainer(containerName, function (createError, container1, createContainerResponse) {
assert.equal(createError, null);
assert.notEqual(container1, null);
if (container1) {
assert.notEqual(container1.name, null);
assert.notEqual(container1.etag, null);
assert.notEqual(container1.lastModified, null);
}
assert.equal(createContainerResponse.statusCode, HttpConstants.HttpResponseCodes.Created);
// creating again will result in a duplicate error
blobService.createContainer(containerName, function (createError2, container2) {
assert.equal(createError2.code, Constants.BlobErrorCodeStrings.CONTAINER_ALREADY_EXISTS);
assert.equal(container2, null);
done();
});
});
});
});
describe('blobExists', function () {
it('should detect incorrect blob names', function (done) {
assert.throws(function () { blobService.blobExists('container', null, function () { }); },
BlobService.incorrectBlobNameFormatErr);
assert.throws(function () { blobService.blobExists('container', '', function () { }); },
BlobService.incorrectBlobNameFormatErr);
done();
});
});
describe('getServiceProperties', function () {
it('should get blob service properties', function (done) {
blobService.getServiceProperties(function (error, serviceProperties) {
assert.equal(error, null);
assert.notEqual(serviceProperties, null);
if (serviceProperties) {
assert.notEqual(serviceProperties.Logging, null);
if (serviceProperties.Logging) {
assert.notEqual(serviceProperties.Logging.RetentionPolicy);
assert.notEqual(serviceProperties.Logging.Version);
}
if (serviceProperties.Metrics) {
assert.notEqual(serviceProperties.Metrics, null);
assert.notEqual(serviceProperties.Metrics.RetentionPolicy);
assert.notEqual(serviceProperties.Metrics.Version);
}
}
done();
});
});
});
describe('getServiceProperties', function () {
it('should set blob service properties', function (done) {
blobService.getServiceProperties(function (error, serviceProperties) {
assert.equal(error, null);
serviceProperties.DefaultServiceVersion = '2009-09-19';
serviceProperties.Logging.Read = true;
blobService.setServiceProperties(serviceProperties, function (error2) {
assert.equal(error2, null);
blobService.getServiceProperties(function (error3, serviceProperties2) {
assert.equal(error3, null);
assert.equal(serviceProperties2.DefaultServiceVersion, '2009-09-19');
assert.equal(serviceProperties2.Logging.Read, true);
done();
});
});
});
});
});
describe('listContainers', function () {
it('should work', function (done) {
var containerName1 = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var metadata1 = {
color: 'orange',
containernumber: '01',
somemetadataname: 'SomeMetadataValue'
};
var containerName2 = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var metadata2 = {
color: 'pink',
containernumber: '02',
somemetadataname: 'SomeMetadataValue'
};
var containerName3 = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var metadata3 = {
color: 'brown',
containernumber: '03',
somemetadataname: 'SomeMetadataValue'
};
var containerName4 = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var metadata4 = {
color: 'blue',
containernumber: '04',
somemetadataname: 'SomeMetadataValue'
};
var validateContainers = function (containers, entries) {
containers.forEach(function (container) {
if (container.name == containerName1) {
assert.equal(container.metadata.color, metadata1.color);
assert.equal(container.metadata.containernumber, metadata1.containernumber);
assert.equal(container.metadata.somemetadataname, metadata1.somemetadataname);
entries.push(container.name);
}
else if (container.name == containerName2) {
assert.equal(container.metadata.color, metadata2.color);
assert.equal(container.metadata.containernumber, metadata2.containernumber);
assert.equal(container.metadata.somemetadataname, metadata2.somemetadataname);
entries.push(container.name);
}
else if (container.name == containerName3) {
assert.equal(container.metadata.color, metadata3.color);
assert.equal(container.metadata.containernumber, metadata3.containernumber);
assert.equal(container.metadata.somemetadataname, metadata3.somemetadataname);
entries.push(container.name);
}
else if (container.name == containerName4) {
assert.equal(container.metadata.color, metadata4.color);
assert.equal(container.metadata.containernumber, metadata4.containernumber);
assert.equal(container.metadata.somemetadataname, metadata4.somemetadataname);
entries.push(container.name);
}
});
return entries;
};
blobService.createContainer(containerName1, { metadata: metadata1 }, function (createError1, createContainer1, createResponse1) {
assert.equal(createError1, null);
assert.notEqual(createContainer1, null);
assert.ok(createResponse1.isSuccessful);
blobService.createContainer(containerName2, { metadata: metadata2 }, function (createError2, createContainer2, createResponse2) {
assert.equal(createError2, null);
assert.notEqual(createContainer2, null);
assert.ok(createResponse2.isSuccessful);
blobService.createContainer(containerName3, { metadata: metadata3 }, function (createError3, createContainer3, createResponse3) {
assert.equal(createError3, null);
assert.notEqual(createContainer3, null);
assert.ok(createResponse3.isSuccessful);
blobService.createContainer(containerName4, { metadata: metadata4 }, function (createError4, createContainer4, createResponse4) {
assert.equal(createError4, null);
assert.notEqual(createContainer4, null);
assert.ok(createResponse4.isSuccessful);
var options = {
'maxresults': 3,
'include': 'metadata'
};
blobService.listContainers(options, function (listError, containers, containersContinuation, listResponse) {
assert.equal(listError, null);
assert.ok(listResponse.isSuccessful);
assert.equal(containers.length, 3);
var entries = validateContainers(containers, []);
assert.equal(containersContinuation.hasNextPage(), true);
containersContinuation.getNextPage(function (listErrorContinuation, containers2) {
assert.equal(listErrorContinuation, null);
assert.ok(listResponse.isSuccessful);
validateContainers(containers2, entries);
assert.equal(entries.length, 4);
done();
});
});
});
});
});
});
});
it('should work with optional parameters', function (done) {
blobService.listContainers(null, function (err) {
assert.equal(err, null);
done();
});
});
it('should work with prefix parameter', function (done) {
blobService.listContainers({ prefix : '中文' }, function (err) {
assert.equal(err, null);
done();
});
});
});
describe('createContainerIfNotExists', function() {
it('should create a container if not exists', function (done) {
var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
blobService.createContainer(containerName, function (createError, container1, createContainerResponse) {
assert.equal(createError, null);
assert.notEqual(container1, null);
if (container1) {
assert.notEqual(container1.name, null);
assert.notEqual(container1.etag, null);
assert.notEqual(container1.lastModified, null);
}
assert.equal(createContainerResponse.statusCode, HttpConstants.HttpResponseCodes.Created);
// creating again will result in a duplicate error
blobService.createContainerIfNotExists(containerName, function (createError2, isCreated) {
assert.equal(createError2, null);
assert.equal(isCreated, false);
done();
});
});
});
it('should throw if called with a callback', function (done) {
assert.throws(function () { blobService.createContainerIfNotExists('name'); },
Error
);
done();
});
});
describe('container', function () {
var containerName;
var metadata;
beforeEach(function (done) {
containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
metadata = { color: 'blue' };
blobService.createContainer(containerName, { metadata: metadata }, done);
});
describe('getContainerProperties', function () {
it('should work', function (done) {
blobService.getContainerProperties(containerName, function (getError, container2, getResponse) {
assert.equal(getError, null);
assert.notEqual(container2, null);
if (container2) {
assert.equal('unlocked', container2.leaseStatus);
assert.equal('available', container2.leaseState);
assert.equal(null, container2.leaseDuration);
assert.notEqual(null, container2.requestId);
assert.equal(container2.metadata.color, metadata.color);
}
assert.notEqual(getResponse, null);
assert.equal(getResponse.isSuccessful, true);
done();
});
});
});
describe('setContainerMetadata', function () {
it('should work', function (done) {
var metadata = { 'class': 'test' };
blobService.setContainerMetadata(containerName, metadata, function (setMetadataError, setMetadataResponse) {
assert.equal(setMetadataError, null);
assert.ok(setMetadataResponse.isSuccessful);
blobService.getContainerMetadata(containerName, function (getMetadataError, containerMetadata, getMetadataResponse) {
assert.equal(getMetadataError, null);
assert.notEqual(containerMetadata, null);
assert.notEqual(containerMetadata.metadata, null);
if (containerMetadata.metadata) {
assert.equal(containerMetadata.metadata.class, 'test');
}
assert.ok(getMetadataResponse.isSuccessful);
done();
});
});
});
});
describe('getContainerAcl', function () {
it('should work', function (done) {
blobService.getContainerAcl(containerName, function (containerAclError, containerBlob, containerAclResponse) {
assert.equal(containerAclError, null);
assert.notEqual(containerBlob, null);
if (containerBlob) {
assert.equal(containerBlob.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.OFF);
}
assert.equal(containerAclResponse.isSuccessful, true);
done();
});
});
});
describe('setContainerAcl', function () {
it('should work', function (done) {
blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.BLOB, function (setAclError, setAclContainer1, setResponse1) {
assert.equal(setAclError, null);
assert.notEqual(setAclContainer1, null);
assert.ok(setResponse1.isSuccessful);
blobService.getContainerAcl(containerName, function (getAclError, getAclContainer1, getResponse1) {
assert.equal(getAclError, null);
assert.notEqual(getAclContainer1, null);
if (getAclContainer1) {
assert.equal(getAclContainer1.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.BLOB);
}
assert.ok(getResponse1.isSuccessful);
blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.CONTAINER, function (setAclError2, setAclContainer2, setResponse2) {
assert.equal(setAclError2, null);
assert.notEqual(setAclContainer2, null);
assert.ok(setResponse2.isSuccessful);
setTimeout(function () {
blobService.getContainerAcl(containerName, function (getAclError2, getAclContainer2, getResponse3) {
assert.equal(getAclError2, null);
assert.notEqual(getAclContainer2, null);
if (getAclContainer2) {
assert.equal(getAclContainer2.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.CONTAINER);
}
assert.ok(getResponse3.isSuccessful);
done();
});
}, (suiteUtil.isMocked && !suiteUtil.isRecording) ? 0 : 5000);
});
});
});
});
it('should work with policies', function (done) {
var readWriteStartDate = new Date(Date.UTC(2012, 10, 10));
var readWriteExpiryDate = new Date(readWriteStartDate);
readWriteExpiryDate.setMinutes(readWriteStartDate.getMinutes() + 10);
readWriteExpiryDate.setMilliseconds(999);
var readWriteSharedAccessPolicy = {
Id: 'readwrite',
AccessPolicy: {
Start: readWriteStartDate,
Expiry: readWriteExpiryDate,
Permissions: 'rw'
}
};
var readSharedAccessPolicy = {
Id: 'read',
AccessPolicy: {
Expiry: readWriteStartDate,
Permissions: 'r'
}
};
var options = {};
options.signedIdentifiers = [readWriteSharedAccessPolicy, readSharedAccessPolicy];
blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.BLOB, options, function (setAclError, setAclContainer1, setResponse1) {
assert.equal(setAclError, null);
assert.notEqual(setAclContainer1, null);
assert.ok(setResponse1.isSuccessful);
blobService.getContainerAcl(containerName, function (getAclError, getAclContainer1, getResponse1) {
assert.equal(getAclError, null);
assert.notEqual(getAclContainer1, null);
if (getAclContainer1) {
assert.equal(getAclContainer1.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.BLOB);
assert.equal(getAclContainer1.signedIdentifiers[0].AccessPolicy.Expiry.getTime(), readWriteExpiryDate.getTime());
}
assert.ok(getResponse1.isSuccessful);
blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.CONTAINER, function (setAclError2, setAclContainer2, setResponse2) {
assert.equal(setAclError2, null);
assert.notEqual(setAclContainer2, null);
assert.ok(setResponse2.isSuccessful);
blobService.getContainerAcl(containerName, function (getAclError2, getAclContainer2, getResponse3) {
assert.equal(getAclError2, null);
assert.notEqual(getAclContainer2, null);
if (getAclContainer2) {
assert.equal(getAclContainer2.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.CONTAINER);
}
assert.ok(getResponse3.isSuccessful);
done();
});
});
});
});
});
it('should work with signed identifiers', function (done) {
var options = {};
options.signedIdentifiers = [
{ Id: 'id1',
AccessPolicy: {
Start: '2009-10-10T00:00:00.123Z',
Expiry: '2009-10-11T00:00:00.456Z',
Permissions: 'r'
}
},
{ Id: 'id2',
AccessPolicy: {
Start: '2009-11-10T00:00:00.006Z',
Expiry: '2009-11-11T00:00:00.4Z',
Permissions: 'w'
}
}];
blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.OFF, options, function (setAclError, setAclContainer, setAclResponse) {
assert.equal(setAclError, null);
assert.notEqual(setAclContainer, null);
assert.ok(setAclResponse.isSuccessful);
blobService.getContainerAcl(containerName, function (getAclError, containerAcl, getAclResponse) {
assert.equal(getAclError, null);
assert.notEqual(containerAcl, null);
assert.notEqual(getAclResponse, null);
if (getAclResponse) {
assert.equal(getAclResponse.isSuccessful, true);
}
var entries = 0;
if (containerAcl) {
if (containerAcl.signedIdentifiers) {
containerAcl.signedIdentifiers.forEach(function (identifier) {
if (identifier.Id === 'id1') {
assert.equal(identifier.AccessPolicy.Start.getTime(), new Date('2009-10-10T00:00:00.123Z').getTime());
assert.equal(identifier.AccessPolicy.Expiry.getTime(), new Date('2009-10-11T00:00:00.456Z').getTime());
assert.equal(identifier.AccessPolicy.Permission, 'r');
entries += 1;
}
else if (identifier.Id === 'id2') {
assert.equal(identifier.AccessPolicy.Start.getTime(), new Date('2009-11-10T00:00:00.006Z').getTime());
assert.equal(identifier.AccessPolicy.Start.getMilliseconds(), 6);
assert.equal(identifier.AccessPolicy.Expiry.getTime(), new Date('2009-11-11T00:00:00.4Z').getTime());
assert.equal(identifier.AccessPolicy.Expiry.getMilliseconds(), 400);
assert.equal(identifier.AccessPolicy.Permission, 'w');
entries += 2;
}
});
}
}
assert.equal(entries, 3);
done();
});
});
});
});
describe('createBlockBlobFromText', function () {
it('should work', function (done) {
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var blobText = 'Hello World';
blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blob, uploadResponse) {
assert.equal(uploadError, null);
assert.ok(uploadResponse.isSuccessful);
blobService.getBlobToText(containerName, blobName, function (downloadErr, blobTextResponse) {
assert.equal(downloadErr, null);
assert.equal(blobTextResponse, blobText);
done();
});
});
});
});
describe('createBlobSnapshot', function () {
it('should work', function (done) {
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var blobText = 'Hello World';
blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blob, putResponse) {
assert.equal(uploadError, null);
assert.notEqual(putResponse, null);
if (putResponse) {
assert.ok(putResponse.isSuccessful);
}
blobService.createBlobSnapshot(containerName, blobName, function (snapshotError, snapshotId, snapshotResponse) {
assert.equal(snapshotError, null);
assert.notEqual(snapshotResponse, null);
assert.notEqual(snapshotId, null);
if (snapshotResponse) {
assert.ok(snapshotResponse.isSuccessful);
}
blobService.getBlobToText(containerName, blobName, function (getError, content, blockBlob, getResponse) {
assert.equal(getError, null);
assert.notEqual(blockBlob, null);
assert.notEqual(getResponse, null);
if (getResponse) {
assert.ok(getResponse.isSuccessful);
}
assert.equal(blobText, content);
done();
});
});
});
});
});
describe('acquireLease', function () {
it('should work', function (done) {
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var blobText = 'hello';
blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blob, uploadResponse) {
assert.equal(uploadError, null);
assert.notEqual(blob, null);
assert.ok(uploadResponse.isSuccessful);
// Acquire a lease
blobService.acquireLease(containerName, blobName, function (leaseBlobError, lease, leaseBlobResponse) {
assert.equal(leaseBlobError, null);
assert.notEqual(lease, null);
if (lease) {
assert.ok(lease.id);
}
assert.notEqual(leaseBlobResponse, null);
if (leaseBlobResponse) {
assert.ok(leaseBlobResponse.isSuccessful);
}
// Second lease should not be possible
blobService.acquireLease(containerName, blobName, function (secondLeaseBlobError, secondLease, secondLeaseBlobResponse) {
assert.equal(secondLeaseBlobError.code, 'LeaseAlreadyPresent');
assert.equal(secondLease, null);
assert.equal(secondLeaseBlobResponse.isSuccessful, false);
// Delete should not be possible
blobService.deleteBlob(containerName, blobName, function (deleteError, deleted, deleteResponse) {
assert.equal(deleteError.code, 'LeaseIdMissing');
assert.equal(deleteResponse.isSuccessful, false);
done();
});
});
});
});
});
});
describe('getBlobProperties', function () {
it('should work', function (done) {
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var metadata = {
color: 'blue'
};
blobService.createBlockBlobFromText(containerName, blobName, 'hello', { metadata: metadata }, function (blobErr) {
assert.equal(blobErr, null);
blobService.getBlobProperties(containerName, blobName, function (getErr, blob) {
assert.equal(getErr, null);
assert.notEqual(blob, null);
if (blob) {
assert.notEqual(blob.metadata, null);
if (blob.metadata) {
assert.equal(blob.metadata.color, metadata.color);
}
}
done();
});
});
});
});
describe('setBlobProperties', function () {
it('should work', function (done) {
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var text = 'hello';
blobService.createBlockBlobFromText(containerName, blobName, text, function (blobErr) {
assert.equal(blobErr, null);
var options = {};
options.contentType = 'text';
options.contentEncoding = 'utf8';
options.contentLanguage = 'pt';
options.cacheControl = 'true';
blobService.setBlobProperties(containerName, blobName, options, function (setErr) {
assert.equal(setErr, null);
blobService.getBlobProperties(containerName, blobName, function (getErr, blob) {
assert.equal(getErr, null);
assert.notEqual(blob, null);
if (blob) {
assert.equal(blob.contentLength, text.length);
assert.equal(blob.contentType, options.contentType);
assert.equal(blob.contentEncoding, options.contentEncoding);
assert.equal(blob.contentLanguage, options.contentLanguage);
assert.equal(blob.cacheControl, options.cacheControl);
}
done();
});
});
});
});
});
describe('getBlobMetadata', function () {
it('should work', function (done) {
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var metadata = { color: 'blue' };
blobService.createBlockBlobFromText(containerName, blobName, 'hello', { metadata: metadata }, function (blobErr) {
assert.equal(blobErr, null);
blobService.getBlobMetadata(containerName, blobName, function (getErr, blob) {
assert.equal(getErr, null);
assert.notEqual(blob, null);
if (blob) {
assert.notEqual(blob.metadata, null);
if (blob.metadata) {
assert.equal(blob.metadata.color, metadata.color);
}
}
done();
});
});
});
});
describe('pageBlob', function () {
it('should work', function (done) {
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var data1 = 'Hello, World!' + repeat(' ', 1024 - 13);
var data2 = 'Hello, World!' + repeat(' ', 512 - 13);
// Create the empty page blob
blobService.createPageBlob(containerName, blobName, 1024, function (err) {
assert.equal(err, null);
// Upload all data
blobService.createBlobPagesFromText(containerName, blobName, data1, 0, 1023, function (err2) {
assert.equal(err2, null);
// Verify contents
blobService.getBlobToText(containerName, blobName, function (err3, content1) {
assert.equal(err3, null);
assert.equal(content1, data1);
// Clear the page blob
blobService.clearBlobPages(containerName, blobName, 0, 1023, function (err4) {
assert.equal(err4);
// Upload other data in 2 pages
blobService.createBlobPagesFromText(containerName, blobName, data2, 0, 511, function (err5) {
assert.equal(err5, null);
blobService.createBlobPagesFromText(containerName, blobName, data2, 512, 1023, function (err6) {
assert.equal(err6, null);
blobService.getBlobToText(containerName, blobName, function (err7, content2) {
assert.equal(err7, null);
assert.equal(data2 + data2, content2);
done();
});
});
});
});
});
});
});
});
});
describe('createBlockBlobFromText', function () {
it('should work with access condition', function (done) {
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var blobText = 'hello';
blobService.createBlockBlobFromText(containerName, blobName, blobText, function (error2) {
assert.equal(error2, null);
blobService.getBlobProperties(containerName, blobName, function (error4, blobProperties) {
assert.equal(error4, null);
var options = { accessConditions: { 'if-none-match': blobProperties.etag} };
blobService.createBlockBlobFromText(containerName, blobName, blobText, options, function (error3) {
assert.notEqual(error3, null);
assert.equal(error3.code, Constants.StorageErrorCodeStrings.CONDITION_NOT_MET);
done();
});
});
});
});
it('should work for small size from file', function (done) {
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked) + ' a';
var blobText = 'Hello World';
blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blobResponse, uploadResponse) {
assert.equal(uploadError, null);
assert.notEqual(blobResponse, null);
assert.ok(uploadResponse.isSuccessful);
blobService.getBlobToText(containerName, blobName, function (downloadErr, blobTextResponse) {
assert.equal(downloadErr, null);
assert.equal(blobTextResponse, blobText);
done();
});
});
});
});
describe('getBlobRange', function () {
it('should work', function (done) {
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var data1 = 'Hello, World!';
// Create the empty page blob
blobService.createBlockBlobFromText(containerName, blobName, data1, function (err) {
assert.equal(err, null);
blobService.getBlobToText(containerName, blobName, { rangeStart: 2, rangeEnd: 3 }, function (err3, content1) {
assert.equal(err3, null);
// get the double ll's in the hello
assert.equal(content1, 'll');
done();
});
});
});
});
describe('getBlobRangeOpenEnded', function () {
it('should work', function (done) {
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var data1 = 'Hello, World!';
// Create the empty page blob
blobService.createBlockBlobFromText(containerName, blobName, data1, function (err) {
assert.equal(err, null);
blobService.getBlobToText(containerName, blobName, { rangeStart: 2 }, function (err3, content1) {
assert.equal(err3, null);
// get the last bytes from the message
assert.equal(content1, 'llo, World!');
done();
});
});
});
});
describe('setBlobMime', function () {
it('should work', function (done) {
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var fileNameSource = testutil.generateId('file') + '.bmp'; // fake bmp file with text...
var blobText = 'Hello World!';
fs.writeFile(fileNameSource, blobText, function () {
// Create the empty page blob
var blobOptions = {blockIdPrefix : 'blockId' };
blobService.createBlockBlobFromFile(containerName, blobName, fileNameSource, blobOptions, function (err) {
assert.equal(err, null);
blobService.getBlobToText(containerName, blobName, { rangeStart: 2 }, function (err3, content1, blob) {
assert.equal(err3, null);
// get the last bytes from the message
assert.equal(content1, 'llo World!');
assert.ok(blob.contentType === 'image/bmp' || blob.contentType === 'image/x-ms-bmp');
fs.unlink(fileNameSource, function () {
done();
});
});
});
});
});
it('should work with skip', function (done) {
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var fileNameSource = testutil.generateId('prefix') + '.bmp'; // fake bmp file with text...
var blobText = 'Hello World!';
fs.writeFile(fileNameSource, blobText, function () {
// Create the empty page blob
blobService.createBlockBlobFromFile(containerName, blobName, fileNameSource, { contentType: null, contentTypeHeader: null, blockIdPrefix : 'blockId' }, function (err) {
assert.equal(err, null);
blobService.getBlobToText(containerName, blobName, { rangeStart: 2 }, function (err3, content1, blob) {
assert.equal(err3, null);
// get the last bytes from the message
assert.equal(content1, 'llo World!');
assert.equal(blob.contentType, 'application/octet-stream');
fs.unlink(fileNameSource, function () {
done();
});
});
});
});
});
});
});
describe('copyBlob', function () {
it('should work', function (done) {
var sourceContainerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var targetContainerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var sourceBlobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var targetBlobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var blobText = 'hi there';
blobService.createContainer(sourceContainerName, function (createErr1) {
assert.equal(createErr1, null);
blobService.createContainer(targetContainerName, function (createErr2) {
assert.equal(createErr2, null);
blobService.createBlockBlobFromText(sourceContainerName, sourceBlobName, blobText, function (uploadErr) {
assert.equal(uploadErr, null);
blobService.copyBlob(blobService.getBlobUrl(sourceContainerName, sourceBlobName), targetContainerName, targetBlobName, function (copyErr) {
assert.equal(copyErr, null);
blobService.getBlobToText(targetContainerName, targetBlobName, function (downloadErr, text) {
assert.equal(downloadErr, null);
assert.equal(text, blobText);
done();
});
});
});
});
});
});
});
describe('listBlobs', function () {
var containerName;
beforeEach(function (done) {
containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
blobService.createContainer(containerName, done);
});
it('should work', function (done) {
var blobName1 = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var blobName2 = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var blobText1 = 'hello1';
var blobText2 = 'hello2';
// Test listing 0 blobs
blobService.listBlobs(containerName, function (listErrNoBlobs, listNoBlobs) {
assert.equal(listErrNoBlobs, null);
assert.notEqual(listNoBlobs, null);
if (listNoBlobs) {
assert.equal(listNoBlobs.length, 0);
}
blobService.createBlockBlobFromText(containerName, blobName1, blobText1, function (blobErr1) {
assert.equal(blobErr1, null);
// Test listing 1 blob
blobService.listBlobs(containerName, function (listErr, listBlobs) {
assert.equal(listErr, null);
assert.notEqual(listBlobs, null);
assert.equal(listBlobs.length, 1);
blobService.createBlockBlobFromText(containerName, blobName2, blobText2, function (blobErr2) {
assert.equal(blobErr2, null);
// Test listing multiple blobs
blobService.listBlobs(containerName, function (listErr2, listBlobs2) {
assert.equal(listErr2, null);
assert.notEqual(listBlobs2, null);
if (listBlobs2) {
assert.equal(listBlobs2.length, 2);
var entries = 0;
listBlobs2.forEach(function (blob) {
if (blob.name === blobName1) {
entries += 1;
}
else if (blob.name === blobName2) {
entries += 2;
}
});
assert.equal(entries, 3);
}
blobService.createBlobSnapshot(containerName, blobName1, function (snapErr) {
assert.equal(snapErr, null);
// Test listing without requesting snapshots
blobService.listBlobs(containerName, function (listErr3, listBlobs3) {
assert.equal(listErr3, null);
assert.notEqual(listBlobs3, null);
if (listBlobs3) {
assert.equal(listBlobs3.length, 2);
}
// Test listing including snapshots
blobService.listBlobs(containerName, { include: BlobConstants.BlobListingDetails.SNAPSHOTS }, function (listErr4, listBlobs4) {
assert.equal(listErr4, null);
assert.notEqual(listBlobs4, null);
if (listBlobs3) {
assert.equal(listBlobs4.length, 3);
}
done();
});
});
});
});
});
});
});
});
});
});
describe('getPageRegions', function () {
var containerName;
beforeEach(function (done) {
containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
blobService.createContainer(containerName, done);
});
it('should work', function (done) {
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var data = 'Hello, World!' + repeat(' ', 512 - 13);
// Upload contents in 2 parts
blobService.createPageBlob(containerName, blobName, 1024 * 1024 * 1024, function (err) {
assert.equal(err, null);
// Upload all data
blobService.createBlobPagesFromText(containerName, blobName, data, 0, 511, function (err2) {
assert.equal(err2, null);
// Only one region present
blobService.listBlobRegions(containerName, blobName, 0, null, function (error, regions) {
assert.equal(error, null);
assert.notEqual(regions, null);
if (regions) {
assert.equal(regions.length, 1);
var entries = 0;
regions.forEach(function (region) {
if (region.start === 0) {
assert.equal(region.end, 511);
entries += 1;
}
});
assert.equal(entries, 1);
}
blobService.createBlobPagesFromText(containerName, blobName, data, 1048576, 1049087, null, function (err3) {
assert.equal(err3, null);
// Get page regions
blobService.listBlobRegions(containerName, blobName, 0, null, function (error5, regions) {
assert.equal(error5, null);
assert.notEqual(regions, null);
if (regions) {
assert.equal(regions.length, 2);
var entries = 0;
regions.forEach(function (region) {
if (region.start === 0) {
assert.equal(region.end, 511);
entries += 1;
}
else if (region.start === 1048576) {
assert.equal(region.end, 1049087);
entries += 2;
}
});
assert.equal(entries, 3);
}
done();
});
});
});
});
});
});
});
it('CreateBlobWithBars', function (done) {
var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var blobName = 'blobs/' + testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var blobText = 'Hello World!';
blobService.createContainer(containerName, function (createError) {
assert.equal(createError, null);
// Create the empty page blob
blobService.createBlockBlobFromText(containerName, blobName, blobText, function (err) {
assert.equal(err, null);
blobService.getBlobProperties(containerName, blobName, function (error, properties) {
assert.equal(error, null);
assert.equal(properties.container, containerName);
assert.equal(properties.blob, blobName);
done();
});
});
});
});
it('works with files without specifying content type', function (done) {
// This test ensures that blocks can be created from files correctly
// and was created to ensure that the request module does not magically add
// a content type to the request when the user did not specify one.
var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var fileName= testutil.generateId('prefix') + '.txt';
var blobText = 'Hello World!';
try { fs.unlinkSync(fileName); } catch (e) {}
fs.writeFileSync(fileName, blobText);
var stat = fs.statSync(fileName);
blobService.createContainer(containerName, function (createErr1) {
assert.equal(createErr1, null);
blobService.createBlobBlockFromStream('test', containerName, blobName, fs.createReadStream(fileName), stat.size, function (error) {
try { fs.unlinkSync(fileName); } catch (e) {}
assert.equal(error, null);
done();
});
});
});
it('CommitBlockList', function (done) {
var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
blobService.createContainer(containerName, function (error) {
assert.equal(error, null);
blobService.createBlobBlockFromText('id1', containerName, blobName, 'id1', function (error2) {
assert.equal(error2, null);
blobService.createBlobBlockFromText('id2', containerName, blobName, 'id2', function (error3) {
assert.equal(error3, null);
var blockList = {
LatestBlocks: ['id1'],
UncommittedBlocks: ['id2']
};
blobService.commitBlobBlocks(containerName, blobName, blockList, function (error4) {
assert.equal(error4, null);
blobService.listBlobBlocks(containerName, blobName, BlobConstants.BlockListFilter.ALL, function (error5, list) {
assert.equal(error5, null);
assert.notEqual(list, null);
assert.notEqual(list.CommittedBlocks, null);
assert.equal(list.CommittedBlocks.length, 2);
done();
});
});
});
});
});
});
describe('shared access signature', function () {
describe('getBlobUrl', function () {
it('should work', function (done) {
var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var blobServiceassert = storage.createBlobService('storageAccount', 'storageAccessKey', 'host.com:80');
var blobUrl = blobServiceassert.getBlobUrl(containerName);
assert.equal(blobUrl, 'https://host.com:80/' + containerName);
blobUrl = blobServiceassert.getBlobUrl(containerName, blobName);
assert.equal(blobUrl, 'https://host.com:80/' + containerName + '/' + blobName);
done();
});
it('should work with shared access policy', function (done) {
var containerName = 'container';
var blobName = 'blob';
var blobServiceassert = storage.createBlobService('storageAccount', 'storageAccessKey', 'host.com:80');
var sharedAccessPolicy = {
AccessPolicy: {
Expiry: new Date('October 12, 2011 11:53:40 am GMT')
}
};
var blobUrl = blobServiceassert.getBlobUrl(containerName, blobName, sharedAccessPolicy);
assert.equal(blobUrl, 'https://host.com:80/' + containerName + '/' + blobName + '?se=2011-10-12T11%3A53%3A40Z&sr=b&sv=2012-02-12&sig=gDOuwDoa4F7hhQJW9ReCimoHN2qp7NF1Nu3sdHjwIfs%3D');
done();
});
it('should work with container acl permissions and spaces in name', function (done) {
var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked) + ' foobar';
var blobText = 'Hello World';
var fileNameSource = testutil.generateId('prefix') + '.txt'; // fake bmp file with text...
blobService.createContainer(containerName, function (err) {
assert.equal(err, null);
var startTime = new Date('April 15, 2013 11:53:40 am GMT');
var readWriteSharedAccessPolicy = {
Id: 'readwrite',
AccessPolicy: {
Start: startTime,
Permissions: 'rwdl'
}
};
blobService.setContainerAcl(containerName, null, { signedIdentifiers: [ readWriteSharedAccessPolicy ] }, function (err) {
assert.equal(err, null);
blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blob, uploadResponse) {
assert.equal(uploadError, null);
assert.ok(uploadResponse.isSuccessful);
var blobUrl = blobService.getBlobUrl(containerName, blobName, {
Id: 'readwrite',
AccessPolicy: {
Expiry: new Date('April 15, 2099 11:53:40 am GMT')
}
});
function responseCallback(err, rsp) {
assert.equal(rsp.statusCode, 200);
assert.equal(err, null);
fs.unlink(fileNameSource, done);
}
request.get(blobUrl, responseCallback).pipe(fs.createWriteStream(fileNameSource));
});
});
});
});
it('should work with container acl permissions', function (done) {
var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var fileNameSource = testutil.generateId('prefix') + '.bmp'; // fake bmp file with text...
var blobText = 'Hello World!';
blobService.createContainer(containerName, function (error) {
assert.equal(error, null);
var startTime = new Date('April 15, 2013 11:53:40 am GMT');
var readWriteSharedAccessPolicy = {
Id: 'readwrite',
AccessPolicy: {
Start: startTime,
Permissions: 'rwdl'
}
};
blobService.setContainerAcl(containerName, null, { signedIdentifiers: [ readWriteSharedAccessPolicy ] }, function (err) {
assert.equal(err, null);
blobService.createBlockBlobFromText(containerName, blobName, blobText, function (err) {
assert.equal(err, null);
var blobUrl = blobService.getBlobUrl(containerName, blobName, {
Id: 'readwrite',
AccessPolicy: {
Expiry: new Date('April 15, 2099 11:53:40 am GMT')
}
});
function responseCallback(err, rsp) {
assert.equal(rsp.statusCode, 200);
assert.equal(err, null);
fs.unlink(fileNameSource, done);
}
request.get(blobUrl, responseCallback).pipe(fs.createWriteStream(fileNameSource));
});
});
});
});
it('should work with duration', function (done) {
var containerName = 'container';
var blobName = 'blob';
var blobServiceassert = storage.createBlobService('storageAccount', 'storageAccessKey', 'host.com:80');
// Mock Date just to ensure a fixed signature
this.clock = sinon.useFakeTimers(0);
var sharedAccessPolicy = {
AccessPolicy: {
Expiry: storage.date.minutesFromNow(10)
}
};
this.clock.restore();
var blobUrl = blobServiceassert.getBlobUrl(containerName, blobName, sharedAccessPolicy);
assert.equal(blobUrl, 'https://host.com:80/' + containerName + '/' + blobName + '?se=1970-01-01T00%3A10%3A00Z&sr=b&sv=2012-02-12&sig=ca700zLsjqapO1sUBVHIBblj2XoJCON1V4gMSfyQZc8%3D');
done();
});
});
it('GenerateSharedAccessSignature', function (done) {
var containerName = 'images';
var blobName = 'pic1.png';
var devStorageBlobService = storage.createBlobService(ServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT, ServiceClientConstants.DEVSTORE_STORAGE_ACCESS_KEY);
var sharedAccessPolicy = {
AccessPolicy: {
Permissions: BlobConstants.SharedAccessPermissions.READ,
Start: new Date('October 11, 2011 11:03:40 am GMT'),
Expiry: new Date('October 12, 2011 11:53:40 am GMT')
}
};
var sharedAccessSignature = devStorageBlobService.generateSharedAccessSignature(containerName, blobName, sharedAccessPolicy);
assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_START], '2011-10-11T11:03:40Z');
assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_EXPIRY], '2011-10-12T11:53:40Z');
assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_RESOURCE], BlobConstants.ResourceTypes.BLOB);
assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_PERMISSIONS], BlobConstants.SharedAccessPermissions.READ);
assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_VERSION], '2012-02-12');
assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNATURE], 'ju4tX0G79vPxMOkBb7UfNVEgrj9+ZnSMutpUemVYHLY=');
done();
});
});
it('responseEmits', function (done) {
var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var responseReceived = false;
blobService.on('response', function (response) {
assert.notEqual(response, null);
responseReceived = true;
blobService.removeAllListeners('response');
});
blobService.createContainer(containerName, function (error) {
assert.equal(error, null);
blobService.createBlobBlockFromText('id1', containerName, blobName, 'id1', function (error2) {
assert.equal(error2, null);
// By the time the complete callback is processed the response header callback must have been called before
assert.equal(responseReceived, true);
done();
});
});
});
it('getBlobToStream', function (done) {
var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var fileNameTarget = testutil.generateId('getBlobFile', [], suiteUtil.isMocked) + '.test';
var blobText = 'Hello World';
blobService.createContainer(containerName, function (createError1, container1) {
assert.equal(createError1, null);
assert.notEqual(container1, null);
blobService.createBlockBlobFromText(containerName, blobName, blobText, function (error1) {
assert.equal(error1, null);
blobService.getBlobToFile(containerName, blobName, fileNameTarget, function (error2) {
assert.equal(error2, null);
var exists = azureutil.pathExistsSync(fileNameTarget);
assert.equal(exists, true);
fs.readFile(fileNameTarget, function (err, fileText) {
assert.equal(blobText, fileText);
done();
});
});
});
});
});
it('SmallUploadBlobFromFile', function (done) {
var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);
var fileNameSource = testutil.generateId('getBlobFile', [], suiteUtil.isMocked) + '.test';
var blobText = 'Hello World';
fs.writeFile(fileNameSource, blobText, function () {
blobService.createContainer(containerName, function (createError1, container1, createResponse1) {
assert.equal(createError1, null);
assert.notEqual(container1, null);
assert.ok(createResponse1.isSuccessful);
assert.equal(createResponse1.statusCode, HttpConstants.HttpResponseCodes.Created);
var blobOptions = { contentType: 'text', blockIdPrefix : 'blockId' };
blobService.createBlockBlobFromFile(containerName, blobName, fileNameSource, blobOptions, function (uploadError, blobResponse, uploadResponse) {
assert.equal(uploadError, null);
assert.notEqual(blobResponse, null);
assert.ok(uploadResponse.isSuccessful);
blobService.getBlobToText(containerName, blobName, function (downloadErr, blobTextResponse) {
assert.equal(downloadErr, null);
assert.equal(blobTextResponse, blobText);
blobService.getBlobProperties(containerName, blobName, function (getBlobPropertiesErr, blobGetResponse) {
assert.equal(getBlobPropertiesErr, null);
assert.notEqual(blobGetResponse, null);
if (blobGetResponse) {
assert.equal(blobOptions.contentType, blobGetResponse.contentType);
}
done();
});
});
});
});
});
});
it('storageConnectionStrings', function (done) {
var key = 'AhlzsbLRkjfwObuqff3xrhB2yWJNh1EMptmcmxFJ6fvPTVX3PZXwrG2YtYWf5DPMVgNsteKStM5iBLlknYFVoA==';
var connectionString = 'DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=' + key;
var blobService = storage.createBlobService(connectionString);
assert.equal(blobService.storageAccount, 'myaccount');
assert.equal(blobService.storageAccessKey, key);
assert.equal(blobService.protocol, 'https:');
assert.equal(blobService.host, 'myaccount.blob.core.windows.net');
done();
});
it('storageConnectionStringsDevStore', function (done) {
var connectionString = 'UseDevelopmentStorage=true';
var blobService = storage.createBlobService(connectionString);
assert.equal(blobService.storageAccount, ServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT);
assert.equal(blobService.storageAccessKey, ServiceClientConstants.DEVSTORE_STORAGE_ACCESS_KEY);
assert.equal(blobService.protocol, 'http:');
assert.equal(blobService.host, '127.0.0.1');
assert.equal(blobService.port, '10000');
done();
});
it('should be creatable from config', function (done) {
var key = 'AhlzsbLRkjfwObuqff3xrhB2yWJNh1EMptmcmxFJ6fvPTVX3PZXwrG2YtYWf5DPMVgNsteKStM5iBLlknYFVoA==';
var connectionString = 'DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=' + key;
var config = common.configure('testenvironment', function (c) {
c.storage(connectionString);
});
var blobService = storage.createBlobService(common.config('testenvironment'));
assert.equal(blobService.storageAccount, 'myaccount');
assert.equal(blobService.storageAccessKey, key);
assert.equal(blobService.protocol, 'https:');
assert.equal(blobService.host, 'myaccount.blob.core.windows.net');
done();
});
});
function repeat(s, n) {
var ret = '';
for (var i = 0; i < n; i++) {
ret += s;
}
return ret;
}
| begoldsm/azure-sdk-for-node | test/services/blob/blobservice-tests.js | JavaScript | apache-2.0 | 59,746 |
Subsets and Splits