code stringlengths 2 1.05M |
|---|
$.testHelper.delayStart();
/*
* mobile navigation unit tests
*/
(function($){
// TODO move siteDirectory over to the nav path helper
var changePageFn = $.mobile.changePage,
originalTitle = document.title,
originalLinkBinding = $.mobile.linkBindingEnabled,
siteDirectory = location.pathname.replace( /[^/]+$/, "" ),
home = $.mobile.path.parseUrl(location.pathname).directory,
homeWithSearch = home + location.search,
search = location.search;
navigateTestRoot = function(){
$.testHelper.openPage( "#" + location.pathname + location.search );
};
module('jquery.mobile.navigation.js', {
setup: function() {
$.mobile.navigate.history.stack = [];
$.mobile.navigate.history.activeIndex = 0;
$.testHelper.navReset( homeWithSearch );
},
teardown: function() {
$.Event.prototype.which = undefined;
$.mobile.linkBindingEnabled = originalLinkBinding;
$.mobile.changePage = changePageFn;
document.title = originalTitle;
}
});
asyncTest( "window.history.back() from external to internal page", function(){
$.testHelper.pageSequence([
// open our test page
function() {
$.testHelper.openPage("#active-state-page1");
},
function(){
ok( $.mobile.activePage[0] === $( "#active-state-page1" )[ 0 ], "successful navigation to internal page." );
$.testHelper.openPage("#/tests/integration/navigation/external.html");
},
function() {
ok( $.mobile.activePage.attr("id"), "external-test", "successful navigation to external page." );
window.history.back();
},
function() {
ok( $.mobile.activePage[0] === $( "#active-state-page1" )[ 0 ], "successful navigation back to internal page." );
start();
}
]);
});
asyncTest( "external empty page does not result in any contents", function() {
$.testHelper.pageSequence([
function() {
$.mobile.changePage( "blank.html" );
},
function() {
deepEqual( $.mobile.activePage.contents().length, 0, "A blank page has no contents" );
$.mobile.back();
},
function() {
start();
}
]);
});
asyncTest( "external page is removed from the DOM after pagehide", function(){
$.testHelper.pageSequence([
function() {
$.mobile.changePage( "external.html" );
},
// page is pulled and displayed in the dom
function() {
deepEqual( $( "#external-test" ).length, 1 );
window.history.back();
},
// external-test is *NOT* cached in the dom after transitioning away
function( timedOut ) {
deepEqual( $( "#external-test" ).length, 0 );
start();
}
]);
});
asyncTest( "preventDefault on pageremove event can prevent external page from being removed from the DOM", function(){
var preventRemoval = true,
removeCallback = function( e ) {
if ( preventRemoval ) {
e.preventDefault();
}
};
$( document ).bind( "pageremove", removeCallback );
$.testHelper.pageSequence([
function(){
$.mobile.changePage( "external.html" );
},
// page is pulled and displayed in the dom
function(){
deepEqual( $( "#external-test" ).length, 1 );
window.history.back();
},
// external-test *IS* cached in the dom after transitioning away
function() {
deepEqual( $( "#external-test" ).length, 1 );
// Switch back to the page again!
$.mobile.changePage( "external.html" );
},
// page is still present and displayed in the dom
function() {
deepEqual( $( "#external-test" ).length, 1 );
// Now turn off our removal prevention.
preventRemoval = false;
window.history.back();
},
// external-test is *NOT* cached in the dom after transitioning away
function() {
deepEqual( $( "#external-test" ).length, 0, "#external-test is gone" );
$( document ).unbind( "pageremove", removeCallback );
start();
}
]);
});
asyncTest( "external page is cached in the DOM after pagehide", function(){
$.testHelper.pageSequence([
function(){
$.mobile.changePage( "cached-external.html" );
},
// page is pulled and displayed in the dom
function(){
deepEqual( $( "#external-test-cached" ).length, 1 );
window.history.back();
},
// external test page is cached in the dom after transitioning away
function(){
deepEqual( $( "#external-test-cached" ).length, 1 );
start();
}
]);
});
asyncTest( "external page is cached in the DOM after pagehide when option is set globally", function(){
$.testHelper.pageSequence([
function(){
$.mobile.page.prototype.options.domCache = true;
$.mobile.changePage( "external.html" );
},
// page is pulled and displayed in the dom
function(){
deepEqual( $( "#external-test" ).length, 1 );
window.history.back();
},
// external test page is cached in the dom after transitioning away
function(){
deepEqual( $( "#external-test" ).length, 1 );
$.mobile.page.prototype.options.domCache = false;
$( "#external-test" ).remove();
start();
}]);
});
asyncTest( "page last scroll distance is remembered while navigating to and from pages", function(){
$.testHelper.pageSequence([
function(){
$( "body" ).height( $( window ).height() + 500 );
$.mobile.changePage( "external.html" );
},
function(){
// wait for the initial scroll to 0
setTimeout( function() {
window.scrollTo( 0, 300 );
deepEqual( $(window).scrollTop(), 300, "scrollTop is 300 after setting it" );
}, 300);
// wait for the scrollstop to fire and for the scroll to be
// recorded 100 ms afterward (see changes made to handle hash
// scrolling in some browsers)
setTimeout( navigateTestRoot, 500 );
},
function(){
history.back();
},
function(){
// Give the silentScroll function some time to kick in.
setTimeout(function() {
deepEqual( $(window).scrollTop(), 300, "scrollTop is 300 after returning to the page" );
$( "body" ).height( "" );
start();
}, 300 );
}
]);
});
asyncTest( "forms with data attribute ajax set to false will not call changePage", function(){
var called = false;
var newChangePage = function(){
called = true;
};
$.testHelper.sequence([
// avoid initial page load triggering changePage early
function(){
$.mobile.changePage = newChangePage;
$('#non-ajax-form').one('submit', function(event){
ok(true, 'submit callbacks are fired');
event.preventDefault();
}).submit();
},
function(){
ok(!called, "change page should not be called");
start();
}], 1000);
});
asyncTest( "forms with data attribute ajax not set or set to anything but false will call changePage", function(){
var called = 0,
newChangePage = function(){
called++;
};
$.testHelper.sequence([
// avoid initial page load triggering changePage early
function(){
$.mobile.changePage = newChangePage;
$('#ajax-form, #rand-ajax-form').submit();
},
function(){
ok(called >= 2, "change page should be called at least twice");
start();
}], 300);
});
asyncTest( "anchors with no href attribute will do nothing when clicked", function(){
var fired = false;
$(window).bind("hashchange.temp", function(){
fired = true;
});
$( "<a>test</a>" ).appendTo( $.mobile.firstPage ).click();
setTimeout(function(){
deepEqual(fired, false, "hash shouldn't change after click");
$(window).unbind("hashchange.temp");
start();
}, 500);
});
test( "urlHistory is working properly", function(){
//urlHistory
deepEqual( $.type( $.mobile.navigate.history.stack ), "array", "urlHistory.stack is an array" );
//preload the stack
$.mobile.navigate.history.stack[0] = { url: "foo", transition: "bar" };
$.mobile.navigate.history.stack[1] = { url: "baz", transition: "shizam" };
$.mobile.navigate.history.stack[2] = { url: "shizoo", transition: "shizaah" };
//active index
deepEqual( $.mobile.navigate.history.activeIndex , 0, "urlHistory.activeIndex is 0" );
//getActive
deepEqual( $.type( $.mobile.navigate.history.getActive() ) , "object", "active item is an object" );
deepEqual( $.mobile.navigate.history.getActive().url , "foo", "active item has url foo" );
deepEqual( $.mobile.navigate.history.getActive().transition , "bar", "active item has transition bar" );
//get prev / next
deepEqual( $.mobile.navigate.history.getPrev(), undefined, "urlHistory.getPrev() is undefined when active index is 0" );
$.mobile.navigate.history.activeIndex = 1;
deepEqual( $.mobile.navigate.history.getPrev().url, "foo", "urlHistory.getPrev() has url foo when active index is 1" );
$.mobile.navigate.history.activeIndex = 0;
deepEqual( $.mobile.navigate.history.getNext().url, "baz", "urlHistory.getNext() has url baz when active index is 0" );
//add new
$.mobile.navigate.history.activeIndex = 2;
$.mobile.navigate.history.add("test");
deepEqual( $.mobile.navigate.history.stack.length, 4, "urlHistory.addNew() adds an item after the active index" );
deepEqual( $.mobile.navigate.history.activeIndex, 3, "urlHistory.addNew() moves the activeIndex to the newly added item" );
//clearForward
$.mobile.navigate.history.activeIndex = 0;
$.mobile.navigate.history.clearForward();
deepEqual( $.mobile.navigate.history.stack.length, 1, "urlHistory.clearForward() clears the url stack after the active index" );
});
//url listening
function testListening( prop ){
var stillListening = false;
$(document).bind("pagebeforehide", function(){
stillListening = true;
});
location.hash = "foozball";
setTimeout(function(){
ok( prop == stillListening, prop + " = false disables default hashchange event handler");
location.hash = "";
prop = true;
start();
}, 1000);
}
asyncTest( "ability to disable our hash change event listening internally", function(){
testListening( !$.mobile.navigate.history.ignoreNextHashChange );
});
asyncTest( "ability to disable our hash change event listening globally", function(){
testListening( $.mobile.hashListeningEnabled );
});
var testDataUrlHash = function( linkSelector, matches ) {
$.testHelper.pageSequence([
function(){ window.location.hash = ""; },
function(){ $(linkSelector).click(); },
function(){
$.testHelper.assertUrlLocation(
$.extend(matches, {
report: "url or hash should match"
})
);
start();
}
]);
stop();
};
test( "when loading a page where data-url is not defined on a sub element hash defaults to the url", function(){
testDataUrlHash( "#non-data-url a", {hashOrPush: siteDirectory + "data-url-tests/non-data-url.html"} );
});
test( "data url works for nested paths", function(){
var url = "foo/bar.html";
testDataUrlHash( "#nested-data-url a", {hashOrPush: home + url });
});
test( "data url works for single quoted paths and roles", function(){
var url = "foo/bar/single.html";
testDataUrlHash( "#single-quotes-data-url a", {hashOrPush: home + url } );
});
test( "data url works when role and url are reversed on the page element", function(){
var url = "foo/bar/reverse.html";
testDataUrlHash( "#reverse-attr-data-url a", {hashOrPush: home + url } );
});
asyncTest( "last entry chosen amongst multiple identical url history stack entries on hash change", function(){
var stackLength = $.mobile.navigate.history.stack.length;
$.testHelper.pageSequence([
function(){ $.testHelper.openPage("#dup-history-first"); },
function(){ $("#dup-history-first a").click(); },
function(){ $("#dup-history-second a:first").click(); },
function(){ $("#dup-history-first a").click(); },
function(){ $("#dup-history-second a:last").click(); },
function(){
$("#dup-history-dialog a:contains('Close')").click();
},
function(){
// it should be the third page after whatever is in the stack to start with
// [wherever this test starts] -> #dup-history-first -> #dup-history-second -> #dup-history-first -> #dup-history-second -> dialog --close/back button--> [first #dup-history-second-entry]
deepEqual($.mobile.navigate.history.activeIndex, 3 + stackLength, "should be the fourth page in the stack");
start();
}]);
});
asyncTest( "going back from a page entered from a dialog skips the dialog and goes to the previous page", function(){
$.testHelper.pageSequence([
// setup
function(){
$.mobile.changePage("#skip-dialog-first");
},
// transition to the dialog
function(){
$("#skip-dialog-first a").click();
},
// transition to the second page
function(){
$("#skip-dialog a").click();
},
// transition past the dialog via data-rel=back link on the second page
function(){
$("#skip-dialog-second a").click();
},
// make sure we're at the first page and not the dialog
function(){
$.testHelper.assertUrlLocation({
hash: "skip-dialog-first",
push: homeWithSearch + "#skip-dialog-first",
report: "should be the first page in the sequence"
});
start();
}
]);
});
asyncTest( "going forward from a page entered from a dialog skips the dialog and goes to the next page", function(){
$.testHelper.pageSequence([
// setup
function(){ $.testHelper.openPage("#skip-dialog-first"); },
// transition to the dialog
function(){ $("#skip-dialog-first a").click(); },
// transition to the second page
function(){ $("#skip-dialog a").click(); },
// transition to back past the dialog
function(){ window.history.back(); },
// transition to the second page past the dialog through history
function(){ window.history.forward(); },
// make sure we're on the second page and not the dialog
function(){
$.testHelper.assertUrlLocation({
hash: "skip-dialog-second",
push: homeWithSearch + "#skip-dialog-second",
report: "should be the second page after the dialog"
});
start();
}]);
});
asyncTest( "going back from a stale dialog history entry does not cause the base tag to be reset", function() {
var baseHRef;
expect( 1 );
$.testHelper.pageSequence([
// setup
function() { $.testHelper.openPage( "#dialog-base-tag-test-page" ); },
// go to page that launches dialog
function() { $( "#dialog-base-tag-test-page a" ).click(); },
// record the base href and launch the dialog
function( timedOut ) {
baseHRef = $( "base" ).attr( "href" );
$( "a#go-to-dialog" ).click();
},
// close the dialog - this assumes a close button link will be added to the dialog as part of the enhancement process
function( timedOut ) {
$( "#dialog-base-tag-test a" ).click();
},
function(timedOut) {
// $.testHelper.pageSequence cannot be used here because no page changes occur
$.testHelper.sequence([
// Go forward to reach the now-stale dialogHashKey history entry
function() { window.history.forward(); },
// Go back
function() { window.history.back(); },
// Make sure the base href is unchanged from the recorded value, and back up to the start page
function() {
deepEqual( $( "base" ).attr( "href" ), baseHRef, "href of base tag is unchanged" );
// Return to start page
$.testHelper.pageSequence([
// Go back to the setup page
function() { window.history.back(); },
// Go back to the start page
function() { window.history.back(); },
// Conclude the test
function() { start(); }
]);
}
], 2000);
}
]);
});
asyncTest( "opening a dialog, closing it, moving forward, and opening it again, does not result in a dialog that needs to be closed twice", function() {
$.testHelper.pageSequence([
// setup
function(){ $.testHelper.openPage("#dialog-double-hash-test"); },
// transition to the dialog
function(){ $("#dialog-double-hash-test a").click(); },
// close the dialog
function(){ $("#dialog-double-hash-test-dialog a").click(); },
// Go forward
function(){ window.history.forward(); },
// transition to the dialog
function(){ $("#dialog-double-hash-test a").click(); },
// close the dialog
function(){
$("#dialog-double-hash-test-dialog a").click();
},
// make sure the dialog is closed
function() {
setTimeout( function() {
deepEqual($("#dialog-double-hash-test")[0], $.mobile.activePage[0], "should be back to the test page");
start();
}, 800);
}
]);
});
asyncTest( "going back from a dialog triggered from a dialog should result in the first dialog ", function(){
$.testHelper.pageSequence([
function(){
$.testHelper.openPage("#nested-dialog-page");
},
// transition to the dialog
function(){ $("#nested-dialog-page a").click(); },
// transition to the second dialog
function(){
$("#nested-dialog-first a").click();
},
// transition to back to the first dialog
function(){
window.history.back();
},
// make sure we're on first dialog
function(){
deepEqual($(".ui-page-active")[0], $("#nested-dialog-first")[0], "should be the first dialog");
start();
}]);
});
asyncTest( "loading a relative file path after an embeded page works", function(){
$.testHelper.pageSequence([
// transition second page
function(){ $.testHelper.openPage("#relative-after-embeded-page-first"); },
// transition second page
function(){ $("#relative-after-embeded-page-first a").click(); },
// transition to the relative ajax loaded page
function(){ $("#relative-after-embeded-page-second a").click(); },
// make sure the page was loaded properly via ajax
function(){
// data attribute intentionally left without namespace
deepEqual($(".ui-page-active").data("other"), "for testing", "should be relative ajax loaded page");
start();
}]);
});
asyncTest( "Page title updates properly when clicking back to previous page", function(){
$.testHelper.pageSequence([
function(){
$.testHelper.openPage("#relative-after-embeded-page-first");
},
function(){
window.history.back();
},
function(){
deepEqual(document.title, "jQuery Mobile Navigation Test Suite");
start();
}
]);
});
asyncTest( "Page title updates properly when clicking a link back to first page", function(){
var title = document.title;
$.testHelper.pageSequence([
function(){
$.testHelper.openPage("#ajax-title-page");
},
function(){
$("#titletest1").click();
},
function(){
deepEqual(document.title, "Title Tag");
$.mobile.activePage.find("#title-check-link").click();
},
function(){
deepEqual(document.title, title);
start();
}
]);
});
asyncTest( "Page title updates properly from title tag when loading an external page", function(){
$.testHelper.pageSequence([
function(){
$.testHelper.openPage("#ajax-title-page");
},
function(){
$("#titletest1").click();
},
function(){
deepEqual(document.title, "Title Tag");
start();
}
]);
});
asyncTest( "Page title updates properly from data-title attr when loading an external page", function(){
$.testHelper.pageSequence([
function(){
$.testHelper.openPage("#ajax-title-page");
},
function(){
$("#titletest2").click();
},
function(){
deepEqual(document.title, "Title Attr");
start();
}
]);
});
asyncTest( "Page title updates properly from heading text in header when loading an external page", function(){
$.testHelper.pageSequence([
function(){
$.testHelper.openPage("#ajax-title-page");
},
function(){
$("#titletest3").click();
},
function(){
deepEqual(document.title, "Title Heading");
start();
}
]);
});
asyncTest( "Page links to the current active page result in the same active page", function(){
$.testHelper.pageSequence([
function(){
$.testHelper.openPage("#self-link");
},
function(){
$("a[href='#self-link']").click();
},
function(){
deepEqual($.mobile.activePage[0], $("#self-link")[0], "self-link page is still the active page" );
start();
}
]);
});
asyncTest( "links on subdirectory pages with query params append the params and load the page", function(){
$.testHelper.pageSequence([
function(){
$.testHelper.openPage("#data-url-tests/non-data-url.html");
},
function(){
$("#query-param-anchor").click();
},
function(){
$.testHelper.assertUrlLocation({
// TODO note there's no guarantee that the query params will remain in this order
// we should fix the comparison to take a callback and do something more complex
hashOrPush: home + "data-url-tests/non-data-url.html?foo=bar",
report: "the hash or url has query params"
});
ok($(".ui-page-active").jqmData("url").indexOf("?foo=bar") > -1, "the query params are in the data url");
start();
}
]);
});
asyncTest( "identical query param link doesn't add additional set of query params", function(){
$.testHelper.pageSequence([
function(){
$.testHelper.openPage("#data-url-tests/non-data-url.html");
},
function(){
$("#query-param-anchor").click();
},
function(){
$.testHelper.assertUrlLocation({
// TODO note there's no guarantee that the query params will remain in this order
// we should fix the comparison to take a callback and do something more complex
hashOrPush: home + "data-url-tests/non-data-url.html?foo=bar",
report: "the hash or url has query params"
});
$("#query-param-anchor").click();
},
function(){
$.testHelper.assertUrlLocation({
// TODO note there's no guarantee that the query params will remain in this order
// we should fix the comparison to take a callback and do something more complex
hashOrPush: home + "data-url-tests/non-data-url.html?foo=bar",
report: "the hash or url still has query params"
});
start();
}
]);
});
// Special handling inside navigation because query params must be applied to the hash
// or absolute reference and dialogs apply extra information int the hash that must be removed
asyncTest( "query param link from a dialog to itself should be a not add another dialog", function(){
var firstDialogLoc;
$.testHelper.pageSequence([
// open our test page
function(){
$.testHelper.openPage("#dialog-param-link");
},
// navigate to the subdirectory page with the query link
function(){
$("#dialog-param-link a").click();
},
// navigate to the query param self reference link
function(){
$("#dialog-param-link-page a").click();
},
// attempt to navigate to the same link
function(){
// store the current hash for comparison (with one dialog hash key)
firstDialogLoc = location.hash || location.href;
$("#dialog-param-link-page a").click();
},
function(){
deepEqual(location.hash || location.href, firstDialogLoc, "additional dialog hash key not added");
start();
}
]);
});
asyncTest( "query data passed as a string to changePage is appended to URL", function(){
$.testHelper.pageSequence([
// open our test page
function(){
$.mobile.changePage( "form-tests/changepage-data.html", {
data: "foo=1&bar=2"
});
},
function(){
$.testHelper.assertUrlLocation({
hashOrPush: home + "form-tests/changepage-data.html?foo=1&bar=2",
report: "the hash or url still has query params"
});
start();
}
]);
});
asyncTest( "query data passed as an object to changePage is appended to URL", function(){
$.testHelper.pageSequence([
// open our test page
function(){
$.mobile.changePage( "form-tests/changepage-data.html", {
data: {
foo: 3,
bar: 4
}
});
},
function(){
$.testHelper.assertUrlLocation({
hashOrPush: home + "form-tests/changepage-data.html?foo=3&bar=4",
report: "the hash or url still has query params"
});
start();
}
]);
});
asyncTest( "refresh of a dialog url should not duplicate page", function(){
$.testHelper.pageSequence([
// open our test page
function(){
deepEqual($(".foo-class").length, 1, "should only have one instance of foo-class in the document");
location.hash = "#foo&ui-state=dialog";
},
function(){
$.testHelper.assertUrlLocation({
hash: "foo&ui-state=dialog",
push: homeWithSearch + "#foo&ui-state=dialog",
report: "hash should match what was loaded"
});
deepEqual( $(".foo-class").length, 1, "should only have one instance of foo-class in the document" );
start();
}
]);
});
asyncTest( "internal form with no action submits to document URL", function(){
$.testHelper.pageSequence([
// open our test page
function(){
$.testHelper.openPage("#internal-no-action-form-page");
},
function(){
$("#internal-no-action-form-page form").eq(0).submit();
},
function(){
$.testHelper.assertUrlLocation({
hashOrPush: home + "?foo=1&bar=2",
report: "hash should match what was loaded"
});
start();
}
]);
});
asyncTest( "external page containing form with no action submits to page URL", function(){
$.testHelper.pageSequence([
// open our test page
function(){
$.testHelper.openPage("#internal-no-action-form-page");
},
function(){
$("#internal-no-action-form-page a").eq(0).click();
},
function(){
$("#external-form-no-action-page form").eq(0).submit();
},
function(){
$.testHelper.assertUrlLocation({
hashOrPush: home + "form-tests/form-no-action.html?foo=1&bar=2",
report: "hash should match page url and not document url"
});
start();
}
]);
});
asyncTest( "handling of active button state when navigating", 1, function(){
$.testHelper.pageSequence([
// open our test page
function(){
$.testHelper.openPage("#active-state-page1");
},
function(){
$("#active-state-page1 a").eq(0).click();
},
function(){
$("#active-state-page2 a").eq(0).click();
},
function(){
ok(!$("#active-state-page1 a").hasClass( $.mobile.activeBtnClass ), "No button should not have class " + $.mobile.activeBtnClass );
start();
}
]);
});
// issue 2444 https://github.com/jquery/jquery-mobile/issues/2444
// results from preventing spurious hash changes
asyncTest( "dialog should return to its parent page when open and closed multiple times", function() {
$.testHelper.pageSequence([
// open our test page
function(){
$.testHelper.openPage("#default-trans-dialog");
},
function(){
$.mobile.activePage.find( "a" ).click();
},
function(){
window.history.back();
},
function(){
deepEqual( $.mobile.activePage[0], $( "#default-trans-dialog" )[0] );
$.mobile.activePage.find( "a" ).click();
},
function(){
window.history.back();
},
function(){
deepEqual( $.mobile.activePage[0], $( "#default-trans-dialog" )[0] );
start();
}
]);
});
asyncTest( "clicks with middle mouse button are ignored", function() {
$.testHelper.pageSequence([
function() {
$.testHelper.openPage( "#odd-clicks-page" );
},
function() {
$( "#right-or-middle-click" ).click();
},
// make sure the page is opening first without the mocked button click value
// only necessary to prevent issues with test specific fixtures
function() {
deepEqual($.mobile.activePage[0], $("#odd-clicks-page-dest")[0]);
$.testHelper.openPage( "#odd-clicks-page" );
// mock the which value to simulate a middle click
$.Event.prototype.which = 2;
},
function() {
$( "#right-or-middle-click" ).click();
},
function( timeout ) {
ok( timeout, "page event handler timed out due to ignored click" );
ok($.mobile.activePage[0] !== $("#odd-clicks-page-dest")[0], "pages are not the same");
start();
}
]);
});
asyncTest( "disabling link binding disables navigation via links and highlighting", function() {
$.mobile.linkBindingEnabled = false;
$.testHelper.pageSequence([
function() {
$.testHelper.openPage("#bar");
},
function() {
$.mobile.activePage.find( "a" ).click();
},
function( timeout ) {
ok( !$.mobile.activePage.find( "a" ).hasClass( $.mobile.activeBtnClass ), "vlick handler doesn't add the activebtn class" );
ok( timeout, "no page change was fired" );
start();
}
]);
});
asyncTest( "handling of button active state when navigating by clicking back button", 1, function(){
$.testHelper.pageSequence([
// open our test page
function(){
$.testHelper.openPage("#active-state-page1");
},
function(){
$("#active-state-page1 a").eq(0).click();
},
function(){
$("#active-state-page2 a").eq(1).click();
},
function(){
$("#active-state-page1 a").eq(0).click();
},
function(){
ok(!$("#active-state-page2 a").hasClass( $.mobile.activeBtnClass ), "No button should not have class " + $.mobile.activeBtnClass );
start();
}
]);
});
asyncTest( "can navigate to dynamically injected page with dynamically injected link", function(){
$.testHelper.pageSequence([
// open our test page
function(){
$.testHelper.openPage("#inject-links-page");
},
function(){
var $ilpage = $( "#inject-links-page" ),
$link = $( "<a href='#injected-test-page'>injected-test-page link</a>" );
// Make sure we actually navigated to the expected page.
ok( $.mobile.activePage[ 0 ] == $ilpage[ 0 ], "navigated successfully to #inject-links-page" );
// Now dynamically insert a page.
$ilpage.parent().append( "<div data-role='page' id='injected-test-page'>testing...</div>" );
// Now inject a link to this page dynamically and attempt to navigate
// to the page we just inserted.
$link.appendTo( $ilpage ).click();
},
function(){
// Make sure we actually navigated to the expected page.
ok( $.mobile.activePage[ 0 ] == $( "#injected-test-page" )[ 0 ], "navigated successfully to #injected-test-page" );
start();
}
]);
});
asyncTest( "application url with dialogHashKey loads application's first page", function(){
$.testHelper.pageSequence([
// open our test page
function(){
// Navigate to any page except the first page of the application.
$.testHelper.openPage("#foo");
},
function(){
ok( $.mobile.activePage[ 0 ] === $( "#foo" )[ 0 ], "navigated successfully to #foo" );
// Now navigate to an hash that contains just a dialogHashKey.
$.mobile.changePage("#" + $.mobile.dialogHashKey);
},
function(){
// Make sure we actually navigated to the first page.
ok( $.mobile.activePage[ 0 ] === $.mobile.firstPage[ 0 ], "navigated successfully to first-page" );
// Now make sure opening the page didn't result in page duplication.
ok( $.mobile.firstPage.hasClass( "first-page" ), "first page has expected class" );
deepEqual( $( ".first-page" ).length, 1, "first page was not duplicated" );
start();
}
]);
});
asyncTest( "navigate to non-existent internal page throws pagechangefailed", function(){
var pagechangefailed = false,
pageChangeFailedCB = function( e ) {
pagechangefailed = true;
}
$( document ).bind( "pagechangefailed", pageChangeFailedCB );
$.testHelper.pageSequence([
// open our test page
function(){
// Make sure there's only one copy of the first-page in the DOM to begin with.
ok( $.mobile.firstPage.hasClass( "first-page" ), "first page has expected class" );
deepEqual( $( ".first-page" ).length, 1, "first page was not duplicated" );
// Navigate to any page except the first page of the application.
$.testHelper.openPage("#foo");
},
function(){
var $foo = $( "#foo" );
ok( $.mobile.activePage[ 0 ] === $foo[ 0 ], "navigated successfully to #foo" );
deepEqual( pagechangefailed, false, "no page change failures" );
// Now navigate to a non-existent page.
$foo.find( "#bad-internal-page-link" ).click();
},
function(){
// Make sure a pagechangefailed event was triggered.
deepEqual( pagechangefailed, true, "pagechangefailed dispatched" );
// Make sure we didn't navigate away from #foo.
ok( $.mobile.activePage[ 0 ] === $( "#foo" )[ 0 ], "did not navigate away from #foo" );
// Now make sure opening the page didn't result in page duplication.
deepEqual( $( ".first-page" ).length, 1, "first page was not duplicated" );
$( document ).unbind( "pagechangefailed", pageChangeFailedCB );
start();
}
]);
});
asyncTest( "prefetched links with data rel dialog result in a dialog", function() {
$.testHelper.pageSequence([
// open our test page
function(){
// Navigate to any page except the first page of the application.
$.testHelper.openPage("#prefetched-dialog-page");
},
function() {
$("#prefetched-dialog-link").click();
},
function() {
ok( $.mobile.activePage.is(".ui-dialog"), "prefetched page is rendered as a dialog" );
start();
}
]);
});
asyncTest( "first page gets reloaded if pruned from the DOM", function(){
var hideCallbackTriggered = false;
function hideCallback( e, data )
{
var page = e.target;
ok( ( page === $.mobile.firstPage[ 0 ] ), "hide called with prevPage set to firstPage");
if ( page === $.mobile.firstPage[ 0 ] ) {
$( page ).remove();
}
hideCallbackTriggered = true;
}
$(document).bind('pagehide', hideCallback);
$.testHelper.pageSequence([
function(){
// Make sure the first page is actually in the DOM.
ok( $.mobile.firstPage.parent().length !== 0, "first page is currently in the DOM" );
// Make sure the first page is the active page.
ok( $.mobile.activePage[ 0 ] === $.mobile.firstPage[ 0 ], "first page is the active page" );
// Now make sure the first page has an id that we can use to reload it.
ok( $.mobile.firstPage[ 0 ].id, "first page has an id" );
// Make sure there is only one first page in the DOM.
deepEqual( $( ".first-page" ).length, 1, "only one instance of the first page in the DOM" );
// Navigate to any page except the first page of the application.
$.testHelper.openPage("#foo");
},
function(){
// Make sure the active page is #foo.
ok( $.mobile.activePage[ 0 ] === $( "#foo" )[ 0 ], "navigated successfully to #foo" );
// Make sure our hide callback was triggered.
ok( hideCallbackTriggered, "hide callback was triggered" );
// Make sure the first page was actually pruned from the document.
ok( $.mobile.firstPage.parent().length === 0, "first page was pruned from the DOM" );
deepEqual( $( ".first-page" ).length, 0, "no instance of the first page in the DOM" );
// Remove our hideCallback.
$(document).unbind('pagehide', hideCallback);
// Navigate back to the first page!
$.testHelper.openPage( "#" + $.mobile.firstPage[0].id );
},
function(){
var firstPage = $( ".first-page" );
// We should only have one first page in the document at any time!
deepEqual( firstPage.length, 1, "single instance of first page recreated in the DOM" );
// Make sure the first page in the DOM is actually a different DOM element than the original
// one we started with.
ok( $.mobile.firstPage[ 0 ] !== firstPage[ 0 ], "first page is a new DOM element");
// Make sure we actually navigated to the new first page.
ok( $.mobile.activePage[ 0 ] === firstPage[ 0 ], "navigated successfully to new first-page");
// Reset the $.mobile.firstPage for subsequent tests.
// XXX: Should we just get rid of the new one and restore the old?
$.mobile.firstPage = $.mobile.activePage;
start();
}
]);
});
asyncTest( "test that clicks are ignored where data-ajax='false' parents exist", function() {
var $disabledByParent = $( "#unhijacked-link-by-parent" ),
$disabledByAttr = $( "#unhijacked-link-by-attr" );
$.mobile.ignoreContentEnabled = true;
$.testHelper.pageSequence([
function() {
$.mobile.changePage( "#link-hijacking-test" );
},
function() {
$( "#hijacked-link" ).trigger( 'click' );
},
function() {
ok( $.mobile.activePage.is("#link-hijacking-destination"), "nav works for links to hijacking destination" );
window.history.back();
},
function() {
$disabledByParent.trigger( 'click' );
},
function() {
ok( $.mobile.activePage.is("#link-hijacking-test"), "click should be ignored keeping the active mobile page the same as before" );
},
function() {
$disabledByAttr.trigger( 'click' );
},
function() {
ok( $.mobile.activePage.is("#link-hijacking-test"), "click should be ignored keeping the active mobile page the same as before" );
$.mobile.ignoreContentEnabled = false;
start();
}
]);
});
asyncTest( "vclicks are ignored where data-ajax='false' parents exist", function() {
var $disabledByParent = $( "#unhijacked-link-by-parent" ),
$disabledByAttr = $( "#unhijacked-link-by-attr" ),
$hijacked = $( "#hijacked-link" );
$.mobile.ignoreContentEnabled = true;
$.testHelper.pageSequence([
function() {
$.mobile.changePage( "#link-hijacking-test" );
},
function() {
// force the active button class
$hijacked.addClass( $.mobile.activeBtnClass );
$hijacked.trigger( 'vclick' );
ok( $hijacked.hasClass( $.mobile.activeBtnClass ), "active btn class is added to the link per normal" );
$disabledByParent.trigger( 'vclick' );
ok( !$disabledByParent.hasClass( $.mobile.activeBtnClass ), "active button class is never added to the link" );
$disabledByAttr.trigger( 'vclick' );
ok( !$disabledByAttr.hasClass( $.mobile.activeBtnClass ), "active button class is never added to the link" );
$.mobile.ignoreContentEnabled = false;
start();
}
]);
});
asyncTest( "data-urls with parens work properly (avoid jqmData regex)", function() {
$.testHelper.pageSequence([
function() {
$.mobile.changePage( "data-url-tests/parentheses.html?foo=(bar)" );
},
function() {
window.history.back();
},
function( timedOut ) {
ok( !timedOut, "the call to back didn't time out" );
window.history.forward();
},
function() {
equal( $.trim($.mobile.activePage.text()), "Parens!", "the page loaded" );
start();
}
]);
});
asyncTest( "loading an embeded page with query params works", function() {
$.testHelper.pageSequence([
function() {
$.mobile.changePage( "#bar?baz=bak", { dataUrl: false } );
},
function() {
ok( location.hash.indexOf( "bar?baz=bak" ) >= -1, "the hash is targeted at the page to be loaded" );
ok( $.mobile.activePage.attr( "id" ), "bar", "the correct page is loaded" );
start();
}
]);
});
asyncTest( "external page is accessed correctly even if it has a space in the url", function(){
$.testHelper.pageSequence([
function(){
$.mobile.changePage( " external.html" );
},
function(){
equal( $.mobile.activePage.attr( "id" ), "external-test", "the correct page is loaded" );
start();
}
]);
});
var absHomeUrl = $.mobile.path.parseLocation().hrefNoHash,
homeDomain = $.mobile.path.parseLocation().domain;
asyncTest( "page load events are providided with the absolute url for the content", function() {
var requestPath;
expect( 3 );
$( document ).one( "pagebeforechange", function( event, data ) {
equal( data.absUrl, absHomeUrl + "#bar");
});
$( document ).one( "pagechange", function( event, data ) {
equal( data.absUrl, absHomeUrl + "#bar" );
});
$.mobile.changePage( "#bar" );
requestPath = "/theres/no/way/this/page/exists.html";
$( document ).one( "pagechangefailed", function( event, data ) {
equal( data.absUrl, homeDomain + requestPath );
start();
});
$.mobile.changePage( requestPath );
});
})(jQuery);
|
/*! jQuery UI - v1.10.3 - 2013-10-10
* http://jqueryui.com
* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function (t) {
t.datepicker.regional.af = {closeText: "Selekteer", prevText: "Vorige", nextText: "Volgende", currentText: "Vandag", monthNames: ["Januarie", "Februarie", "Maart", "April", "Mei", "Junie", "Julie", "Augustus", "September", "Oktober", "November", "Desember"], monthNamesShort: ["Jan", "Feb", "Mrt", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Des"], dayNames: ["Sondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrydag", "Saterdag"], dayNamesShort: ["Son", "Maa", "Din", "Woe", "Don", "Vry", "Sat"], dayNamesMin: ["So", "Ma", "Di", "Wo", "Do", "Vr", "Sa"], weekHeader: "Wk", dateFormat: "dd/mm/yy", firstDay: 1, isRTL: !1, showMonthAfterYear: !1, yearSuffix: ""}, t.datepicker.setDefaults(t.datepicker.regional.af)
}); |
import React, {PropTypes} from 'react';
import {InputButton} from '../input-button/InputButton';
const nodePropTypes = PropTypes.shape({
text: PropTypes.string.isRequired,
id: PropTypes.string.isRequired
});
nodePropTypes.children = PropTypes.arrayOf(nodePropTypes);
export class Node extends React.Component {
static propTypes = {
data: nodePropTypes,
onAddCategory: PropTypes.func,
onEditCategory: PropTypes.func,
onDeleteCategory: PropTypes.func,
onMoveToCategory: PropTypes.func
};
constructor() {
super();
this.state = {
//Todo create compone combining button and inputbutton to avoid duptication of hide,show logic
addCategoryInputVisible: false,
editCategoryInputVisible: false
};
}
render() {
const addCategoryInput = this.state.addCategoryInputVisible
? this.getActionCategoryInput('Add', this.onAdd.bind(this))
: '';
const editCategoryInput = this.state.editCategoryInputVisible
? this.getActionCategoryInput('Edit', this.onEdit.bind(this))
: '';
return (
<div className={`text-node ${this.getClass()}`} onClick={this.props.onClick}>
<span>{this.props.data.text}</span>
<div className="action-subcategory-wrapper">
<button onClick={this.toggleAddCategoryInput.bind(this)}>+</button>
{addCategoryInput}
</div>
<div className="action-subcategory-wrapper">
<button onClick={this.toggleEditCategoryInput.bind(this)}>Edit</button>
{editCategoryInput}
</div>
<button onClick={this.onDelete.bind(this)}>Delete</button>
</div>
);
}
getClass() {
return this.props.selected ? 'selected' : '';
}
getActionCategoryInput(text, action) {
return (
<div className="add-subcategory-input">
<InputButton onButtonClick={action}>{text}</InputButton>
</div>
);
}
onAdd(text) {
this.props.onAddCategory(text);
this.toggleAddCategoryInput();
}
onEdit(text) {
this.props.onEditCategory(text);
this.toggleEditCategoryInput();
}
onDelete(event) {
event && event.stopPropagation();
this.props.onDeleteCategory();
}
toggleAddCategoryInput(event) {
//TODO investigate why event in undefined from time to time
event && event.stopPropagation();
this.setState({addCategoryInputVisible: !this.state.addCategoryInputVisible});
}
toggleEditCategoryInput(event) {
//TODO investigate why event in undefined from time to time
event && event.stopPropagation();
this.setState({editCategoryInputVisible: !this.state.editCategoryInputVisible});
}
}
|
/*!
* clipboard.js v1.5.9
* https://zenorocha.github.io/clipboard.js
*
* Licensed MIT © Zeno Rocha
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Clipboard = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var matches = require('matches-selector')
module.exports = function (element, selector, checkYoSelf) {
var parent = checkYoSelf ? element : element.parentNode
while (parent && parent !== document) {
if (matches(parent, selector)) return parent;
parent = parent.parentNode
}
}
},{"matches-selector":5}],2:[function(require,module,exports){
var closest = require('closest');
/**
* Delegates event to a selector.
*
* @param {Element} element
* @param {String} selector
* @param {String} type
* @param {Function} callback
* @param {Boolean} useCapture
* @return {Object}
*/
function delegate(element, selector, type, callback, useCapture) {
var listenerFn = listener.apply(this, arguments);
element.addEventListener(type, listenerFn, useCapture);
return {
destroy: function() {
element.removeEventListener(type, listenerFn, useCapture);
}
}
}
/**
* Finds closest match and invokes callback.
*
* @param {Element} element
* @param {String} selector
* @param {String} type
* @param {Function} callback
* @return {Function}
*/
function listener(element, selector, type, callback) {
return function(e) {
e.delegateTarget = closest(e.target, selector, true);
if (e.delegateTarget) {
callback.call(element, e);
}
}
}
module.exports = delegate;
},{"closest":1}],3:[function(require,module,exports){
/**
* Check if argument is a HTML element.
*
* @param {Object} value
* @return {Boolean}
*/
exports.node = function(value) {
return value !== undefined
&& value instanceof HTMLElement
&& value.nodeType === 1;
};
/**
* Check if argument is a list of HTML elements.
*
* @param {Object} value
* @return {Boolean}
*/
exports.nodeList = function(value) {
var type = Object.prototype.toString.call(value);
return value !== undefined
&& (type === '[object NodeList]' || type === '[object HTMLCollection]')
&& ('length' in value)
&& (value.length === 0 || exports.node(value[0]));
};
/**
* Check if argument is a string.
*
* @param {Object} value
* @return {Boolean}
*/
exports.string = function(value) {
return typeof value === 'string'
|| value instanceof String;
};
/**
* Check if argument is a function.
*
* @param {Object} value
* @return {Boolean}
*/
exports.fn = function(value) {
var type = Object.prototype.toString.call(value);
return type === '[object Function]';
};
},{}],4:[function(require,module,exports){
var is = require('./is');
var delegate = require('delegate');
/**
* Validates all params and calls the right
* listener function based on its target type.
*
* @param {String|HTMLElement|HTMLCollection|NodeList} target
* @param {String} type
* @param {Function} callback
* @return {Object}
*/
function listen(target, type, callback) {
if (!target && !type && !callback) {
throw new Error('Missing required arguments');
}
if (!is.string(type)) {
throw new TypeError('Second argument must be a String');
}
if (!is.fn(callback)) {
throw new TypeError('Third argument must be a Function');
}
if (is.node(target)) {
return listenNode(target, type, callback);
}
else if (is.nodeList(target)) {
return listenNodeList(target, type, callback);
}
else if (is.string(target)) {
return listenSelector(target, type, callback);
}
else {
throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList');
}
}
/**
* Adds an event listener to a HTML element
* and returns a remove listener function.
*
* @param {HTMLElement} node
* @param {String} type
* @param {Function} callback
* @return {Object}
*/
function listenNode(node, type, callback) {
node.addEventListener(type, callback);
return {
destroy: function() {
node.removeEventListener(type, callback);
}
}
}
/**
* Add an event listener to a list of HTML elements
* and returns a remove listener function.
*
* @param {NodeList|HTMLCollection} nodeList
* @param {String} type
* @param {Function} callback
* @return {Object}
*/
function listenNodeList(nodeList, type, callback) {
Array.prototype.forEach.call(nodeList, function(node) {
node.addEventListener(type, callback);
});
return {
destroy: function() {
Array.prototype.forEach.call(nodeList, function(node) {
node.removeEventListener(type, callback);
});
}
}
}
/**
* Add an event listener to a selector
* and returns a remove listener function.
*
* @param {String} selector
* @param {String} type
* @param {Function} callback
* @return {Object}
*/
function listenSelector(selector, type, callback) {
return delegate(document.body, selector, type, callback);
}
module.exports = listen;
},{"./is":3,"delegate":2}],5:[function(require,module,exports){
/**
* Element prototype.
*/
var proto = Element.prototype;
/**
* Vendor function.
*/
var vendor = proto.matchesSelector
|| proto.webkitMatchesSelector
|| proto.mozMatchesSelector
|| proto.msMatchesSelector
|| proto.oMatchesSelector;
/**
* Expose `match()`.
*/
module.exports = match;
/**
* Match `el` to `selector`.
*
* @param {Element} el
* @param {String} selector
* @return {Boolean}
* @api public
*/
function match(el, selector) {
if (vendor) return vendor.call(el, selector);
var nodes = el.parentNode.querySelectorAll(selector);
for (var i = 0; i < nodes.length; ++i) {
if (nodes[i] == el) return true;
}
return false;
}
},{}],6:[function(require,module,exports){
function select(element) {
var selectedText;
if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
element.focus();
element.setSelectionRange(0, element.value.length);
selectedText = element.value;
}
else {
if (element.hasAttribute('contenteditable')) {
element.focus();
}
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
selectedText = selection.toString();
}
return selectedText;
}
module.exports = select;
},{}],7:[function(require,module,exports){
function E () {
// Keep this empty so it's easier to inherit from
// (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)
}
E.prototype = {
on: function (name, callback, ctx) {
var e = this.e || (this.e = {});
(e[name] || (e[name] = [])).push({
fn: callback,
ctx: ctx
});
return this;
},
once: function (name, callback, ctx) {
var self = this;
function listener () {
self.off(name, listener);
callback.apply(ctx, arguments);
};
listener._ = callback
return this.on(name, listener, ctx);
},
emit: function (name) {
var data = [].slice.call(arguments, 1);
var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
var i = 0;
var len = evtArr.length;
for (i; i < len; i++) {
evtArr[i].fn.apply(evtArr[i].ctx, data);
}
return this;
},
off: function (name, callback) {
var e = this.e || (this.e = {});
var evts = e[name];
var liveEvents = [];
if (evts && callback) {
for (var i = 0, len = evts.length; i < len; i++) {
if (evts[i].fn !== callback && evts[i].fn._ !== callback)
liveEvents.push(evts[i]);
}
}
// Remove event from queue to prevent memory leak
// Suggested by https://github.com/lazd
// Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910
(liveEvents.length)
? e[name] = liveEvents
: delete e[name];
return this;
}
};
module.exports = E;
},{}],8:[function(require,module,exports){
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['module', 'select'], factory);
} else if (typeof exports !== "undefined") {
factory(module, require('select'));
} else {
var mod = {
exports: {}
};
factory(mod, global.select);
global.clipboardAction = mod.exports;
}
})(this, function (module, _select) {
'use strict';
var _select2 = _interopRequireDefault(_select);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var ClipboardAction = function () {
/**
* @param {Object} options
*/
function ClipboardAction(options) {
console.log('options');
console.log(options);
_classCallCheck(this, ClipboardAction);
this.resolveOptions(options);
this.initSelection();
}
/**
* Defines base properties passed from constructor.
* @param {Object} options
*/
ClipboardAction.prototype.resolveOptions = function resolveOptions() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
this.action = options.action;
this.emitter = options.emitter;
this.target = options.target;
this.text = options.text;
this.trigger = options.trigger;
this.selectedText = '';
};
ClipboardAction.prototype.initSelection = function initSelection() {
if (this.text && this.target) {
throw new Error('Multiple attributes declared, use either "target" or "text"');
} else if (this.text) {
this.selectFake();
} else if (this.target) {
this.selectTarget();
} else {
throw new Error('Missing required attributes, use either "target" or "text"');
}
};
ClipboardAction.prototype.selectFake = function selectFake() {
var _this = this;
var isRTL = document.documentElement.getAttribute('dir') == 'rtl';
this.removeFake();
this.fakeHandler = document.body.addEventListener('click', function () {
return _this.removeFake();
});
this.fakeElem = document.createElement('textarea');
// Prevent zooming on iOS
this.fakeElem.style.fontSize = '12pt';
// Reset box model
this.fakeElem.style.border = '0';
this.fakeElem.style.padding = '0';
this.fakeElem.style.margin = '0';
// Move element out of screen horizontally
this.fakeElem.style.position = 'fixed';
this.fakeElem.style[isRTL ? 'right' : 'left'] = '-9999px';
// Move element to the same position vertically
this.fakeElem.style.top = (window.pageYOffset || document.documentElement.scrollTop) + 'px';
this.fakeElem.setAttribute('readonly', '');
this.fakeElem.value = this.text;
document.body.appendChild(this.fakeElem);
this.selectedText = (0, _select2.default)(this.fakeElem);
this.copyText();
};
ClipboardAction.prototype.removeFake = function removeFake() {
if (this.fakeHandler) {
document.body.removeEventListener('click');
this.fakeHandler = null;
}
if (this.fakeElem) {
document.body.removeChild(this.fakeElem);
this.fakeElem = null;
}
};
ClipboardAction.prototype.selectTarget = function selectTarget() {
this.selectedText = (0, _select2.default)(this.target);
this.copyText();
};
ClipboardAction.prototype.copyText = function copyText() {
var succeeded = undefined;
try {
succeeded = document.execCommand(this.action);
} catch (err) {
succeeded = false;
}
this.handleResult(succeeded);
};
ClipboardAction.prototype.handleResult = function handleResult(succeeded) {
if (succeeded) {
this.emitter.emit('success', {
action: this.action,
text: this.selectedText,
trigger: this.trigger,
clearSelection: this.clearSelection.bind(this)
});
} else {
this.emitter.emit('error', {
action: this.action,
trigger: this.trigger,
clearSelection: this.clearSelection.bind(this)
});
}
};
ClipboardAction.prototype.clearSelection = function clearSelection() {
if (this.target) {
this.target.blur();
}
window.getSelection().removeAllRanges();
};
ClipboardAction.prototype.destroy = function destroy() {
this.removeFake();
};
_createClass(ClipboardAction, [{
key: 'action',
set: function set() {
var action = arguments.length <= 0 || arguments[0] === undefined ? 'copy' : arguments[0];
this._action = action;
if (this._action !== 'copy' && this._action !== 'cut') {
throw new Error('Invalid "action" value, use either "copy" or "cut"');
}
},
get: function get() {
return this._action;
}
}, {
key: 'target',
set: function set(target) {
if (target !== undefined) {
if (target && (typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object' && target.nodeType === 1) {
this._target = target;
} else {
throw new Error('Invalid "target" value, use a valid Element');
}
}
},
get: function get() {
return this._target;
}
}]);
return ClipboardAction;
}();
module.exports = ClipboardAction;
});
},{"select":6}],9:[function(require,module,exports){
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['module', './clipboard-action', 'tiny-emitter', 'good-listener'], factory);
} else if (typeof exports !== "undefined") {
factory(module, require('./clipboard-action'), require('tiny-emitter'), require('good-listener'));
} else {
var mod = {
exports: {}
};
factory(mod, global.clipboardAction, global.tinyEmitter, global.goodListener);
global.clipboard = mod.exports;
}
})(this, function (module, _clipboardAction, _tinyEmitter, _goodListener) {
'use strict';
var _clipboardAction2 = _interopRequireDefault(_clipboardAction);
var _tinyEmitter2 = _interopRequireDefault(_tinyEmitter);
var _goodListener2 = _interopRequireDefault(_goodListener);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Clipboard = function (_Emitter) {
_inherits(Clipboard, _Emitter);
/**
* @param {String|HTMLElement|HTMLCollection|NodeList} trigger
* @param {Object} options
*/
function Clipboard(trigger, options) {
console.log('new Clipboard - options');
console.log(options);
_classCallCheck(this, Clipboard);
var _this = _possibleConstructorReturn(this, _Emitter.call(this));
_this.resolveOptions(options);
_this.listenClick(trigger);
return _this;
}
/**
* Defines if attributes would be resolved using internal setter functions
* or custom functions that were passed in the constructor.
* @param {Object} options
*/
Clipboard.prototype.resolveOptions = function resolveOptions() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
this.action = typeof options.action === 'function' ? options.action : this.defaultAction;
this.target = typeof options.target === 'function' ? options.target : this.defaultTarget;
this.text = typeof options.text === 'function' ? options.text : this.defaultText;
};
Clipboard.prototype.listenClick = function listenClick(trigger) {
var _this2 = this;
this.listener = (0, _goodListener2.default)(trigger, 'click', function (e) {
return _this2.onClick(e);
});
};
Clipboard.prototype.onClick = function onClick(e) {
var trigger = e.delegateTarget || e.currentTarget;
if (this.clipboardAction) {
this.clipboardAction = null;
}
this.clipboardAction = new _clipboardAction2.default({
action: this.action(trigger),
target: this.target(trigger),
text: this.text(trigger),
trigger: trigger,
emitter: this
});
};
Clipboard.prototype.defaultAction = function defaultAction(trigger) {
return getAttributeValue('action', trigger);
};
Clipboard.prototype.defaultTarget = function defaultTarget(trigger) {
var selector = getAttributeValue('target', trigger);
if (selector) {
return document.querySelector(selector);
}
};
Clipboard.prototype.defaultText = function defaultText(trigger) {
return getAttributeValue('text', trigger);
};
Clipboard.prototype.destroy = function destroy() {
this.listener.destroy();
if (this.clipboardAction) {
this.clipboardAction.destroy();
this.clipboardAction = null;
}
};
return Clipboard;
}(_tinyEmitter2.default);
/**
* Helper function to retrieve attribute value.
* @param {String} suffix
* @param {Element} element
*/
function getAttributeValue(suffix, element) {
var attribute = 'data-clipboard-' + suffix;
if (!element.hasAttribute(attribute)) {
return;
}
return element.getAttribute(attribute);
}
module.exports = Clipboard;
});
},{"./clipboard-action":8,"good-listener":4,"tiny-emitter":7}]},{},[9])(9)
}); |
import angular from 'angular';
class PhotosController {
/** @ngInject */
constructor($scope, $stateParams, $state, photosGallery) {
this.$scope = $scope;
this.$stateParams = $stateParams;
this.$state = $state;
this.photosGallery = photosGallery;
this.photosByMonth = {};
this.initWatchers();
this.showPhotos();
}
initWatchers() {
this.$scope.$watch(() => this.photosGallery.photos, this.groupPhotosByMonth.bind(this));
}
showPhoto(id) {
this.$state.go('photo-detail', { id });
}
showPage(page) {
this.$state.go(
'photos',
{ page, search: this.photosGallery.search },
{ location: 'replace' }
);
}
showPhotos() {
const page = parseInt(this.$stateParams.page, 10) || undefined
const search = this.$stateParams.search
this.photosGallery.showPhotos({ page, search });
}
pageButtonClass(page) {
if (page === this.photosGallery.currentPage) {
return 'md-raised md-primary';
}
return 'md-raised custom';
}
groupPhotosByMonth(photos) {
const res = {};
photos.forEach((photo) => {
const month = this.monthLabel(photo);
if (!res[month]) {
res[month] = [];
}
res[month].push(photo);
});
this.photosByMonth = res;
console.log("PhotosController.groupPhotosByMonth: \n", this.photosByMonth);
}
monthLabel(photo) {
const date = new Date(photo.metadata.createDate);
const month = date.toLocaleString('en', { month: 'short' });
return `${month} ${date.getFullYear()} `;
}
}
export default angular.module('photos.controller', [])
.controller('photosController', PhotosController);
|
'use strict';
angular.module('myApp.header',['myApp.signup'])
.controller('HeaderCtrl',['$scope','UserDataService',function($scope, UserDataService){
$scope.username = UserDataService.getUser();
/* if($scope.username){
$("#signupHead").text($scope.username);
}*/
}]); |
var _ = require('underscore');
var $ = require('jquery'),
Backbone = require('backbone'),
menuBarTemplate = require('../templates/_barProject.tpl'),
chatFormTemplate = require('../templates/_formProjectChat.tpl'),
FormView = require('./__FormView'),
ProjectStatus = require('../models/ProjectStatus');
var config = require('../conf');
Backbone.$ = $;
exports = module.exports = FormView.extend({
className: 'bottom-bar',
initialize: function(options) {
this.id = options.id;
this.project = options.project;
this.account = options.account;
this.socketEvents = options.socketEvents;
this.parentView = options.parentView;
},
barToggle: true,
events: {
'submit form': 'sendText',
'click .send-file': 'showFileExplorer',
'change input[name=file]': 'sendFile',
'click .chat-toggle': 'changeToolbar'
},
sendText: function() {
var that = this;
var text = $('input[name=chat]').val();
if (text && /[^\s]+/.test(text)) {
var projectStatus = new ProjectStatus({
pid: that.id
});
projectStatus.set('type', 'text');
projectStatus.set('content', {
body: text
});
if (projectStatus.isValid()) {
var xhr = projectStatus.save(null, {
xhrFields: {
withCredentials: true
},
});
if (xhr) {
xhr
.success(function(data) {
if (!!data.code) return console.log(data);
$('input[name=chat]').val('');
//update UI
that.done(new ProjectStatus(data));
//trigger socket.io
that.socketEvents.trigger('socket:out:project',{
to: {
id: that.id
},
content: projectStatus.toJSON(),
});
})
.error(function(xhr) {
console.log(xhr);
});
}
}
}
return false;
},
showFileExplorer: function() {
$('input[name=file]').click();
return false;
},
sendFile: function(evt) {
var that = this;
var formData = new FormData();
formData.append('files', evt.currentTarget.files[0]);
$.ajax({
url: config.api.host + '/attachments',
type: 'POST',
xhrFields: {
withCredentials: true
},
crossDomain: true,
data: formData,
cache: false, //MUST be false
processData: false, //MUST be false
contentType: false, //MUST be false
}).done(function(data) {
if (data && data.type) {
var projectStatus = new ProjectStatus({
pid: that.id
});
projectStatus.set('type', 'image');
projectStatus.set('content', {
urls: config.api.host + data.filename,
});
// that.socketEvents.trigger('socket:out:project', {
// to: {
// id: that.id
// },
// content: projectStatus.toJSON(),
// });
// }
var xhr = projectStatus.save(null, {
xhrFields: {
withCredentials: true
},
});
if (xhr) {
xhr
.success(function(data) {
if (!!data.code) return console.log(data);
that.done(new ProjectStatus(data));
})
.error(function(xhr) {
console.log(xhr);
});
}
}
that.$('input[name=file]').val('');
}).fail(function(err) {
that.$('input[name=file]').val('');
console.log(err);
});
return false;
},
changeToolbar: function() {
this.barToggle = !this.barToggle;
if (this.barToggle) {
window.location.hash = 'project/chat/' + this.id;
}
this.render();
return false;
},
render: function() {
if (this.barToggle) {
this.$el.html(chatFormTemplate({
project: this.project.toJSON()
}));
} else {
this.$el.html(menuBarTemplate({
id: this.id
}));
}
return this;
}
}); |
var global = require('../../global');
module.exports = function (unitReceiptNote) {
var items = [].concat.apply([], unitReceiptNote.items);
var iso = "FM-AG2-00-GU-06-004";
var number = unitReceiptNote.no;
var locale = global.config.locale;
var moment = require('moment');
moment.locale(locale.name);
var header = [{
alignment: "center",
text: 'BON PENERIMAAN BARANG',
style: ['size10', 'bold']
}, {
columns: [
{
columns: [{
width: '*',
stack: [{
text: 'PT. AMBASSADOR GARMINDO',
style: ['size15', 'bold']
}, {
text: 'BANARAN, GROGOL, SUKOHARJO',
style: ['size09']
}]
}]
},
{
columns: [{
width: '*',
stack: [{
alignment: "right",
text: ' ',
style: ['size15', 'bold']
}, {
alignment: "right",
text: iso,
style: ['size08', 'bold']
}]
}]
}]
}];
var subHeader = [{
columns: [
{
width: '50%',
stack: [{
columns: [{
width: '25%',
text: 'Tanggal'
}, {
width: '5%',
text: ':'
}, {
width: '*',
text: `${moment(unitReceiptNote.date).format(locale.date.format)}`
}]
}, {
columns: [{
width: '25%',
text: 'Diterima dari'
}, {
width: '5%',
text: ':'
}, {
width: '*',
text: unitReceiptNote.supplier.name
}]
}
],
style: ['size08']
},
{
width: '10%',
text: ''
},
{
width: '40%',
stack: [{
columns: [{
width: '25%',
text: 'Bagian'
}, {
width: '5%',
text: ':'
}, {
width: '*',
text: unitReceiptNote.unit.name
}]
}, {
columns: [{
width: '25%',
text: 'No.'
}, {
width: '5%',
text: ':'
}, {
width: '*',
text: unitReceiptNote.no
}]
}],
style: ['size08']
}
]
}, '\n'];
var line = [{
canvas: [{
type: 'line',
x1: 0,
y1: 5,
x2: 378,
y2: 5,
lineWidth: 0.5
}
]
}, '\n'];
var thead = [{
text: 'No.',
style: 'tableHeader'
}, {
text: 'Nama barang',
style: 'tableHeader'
}, {
text: 'Jumlah',
style: 'tableHeader'
}, {
text: 'Satuan',
style: 'tableHeader'
}, {
text: 'Keterangan',
style: 'tableHeader'
}];
var tbody = items.map(function (item, index) {
return [{
text: (index + 1).toString() || '',
style: ['size08', 'center']
}, {
text: item.product.code + " - " + item.product.name,
style: ['size08', 'left']
}, {
text: parseFloat(item.deliveredQuantity).toLocaleString(locale, locale.decimal),
style: ['size08', 'center']
}, {
text: item.deliveredUom.unit,
style: ['size08', 'center']
}, {
text: item.remark || '',
style: ['size08', 'left']
}];
});
tbody = tbody.length > 0 ? tbody : [
[{
text: "tidak ada barang",
style: ['size08', 'center'],
colSpan: 5
}, "", "", "", ""]
];
var table = [{
table: {
widths: ['5%', '40%', '20%', '10%', '25%'],
headerRows: 1,
body: [].concat([thead], tbody)
}
}];
var footer = [
'\n', {
stack: [{
text: `Sukoharjo, ${moment(unitReceiptNote.date).format(locale.date.format)}`,
alignment: "right"
}, {
columns: [{
width: '35%',
stack: ['Mengetahui\n\n\n\n\n', '(_______________________)'],
style: 'center'
}, {
width: '30%',
text: ''
}, {
width: '35%',
stack: ['Yang Menerima\n\n\n\n\n', '(_______________________)'],
style: 'center'
}]
}
],
style: ['size08']
}
];
var dd = {
pageSize: 'A6',
pageOrientation: 'landscape',
pageMargins: 20,
content: [].concat(header, line, subHeader, table, footer),
styles: {
size06: {
fontSize: 6
},
size07: {
fontSize: 7
},
size08: {
fontSize: 8
},
size09: {
fontSize: 9
},
size10: {
fontSize: 10
},
size15: {
fontSize: 15
},
bold: {
bold: true
},
center: {
alignment: 'center'
},
left: {
alignment: 'left'
},
right: {
alignment: 'right'
},
justify: {
alignment: 'justify'
},
tableHeader: {
bold: true,
fontSize: 8,
color: 'black',
alignment: 'center'
}
}
};
return dd;
} |
'use strict';
angular.module('myApp.form', ['ngRoute'])
.controller('FormCtrl', ["$location", "config", 'cardsServicesRequests', function ($location, config, cardsServicesRequests) {
var vm = this;
vm.errors={};
vm.card = {};
vm.sendPost = function () {
cardsServicesRequests.postCard(vm.card).then(function (response) {
vm.data = response.data;
$location.path('/success');
}, function (response) {
vm.errors = response.data.errors;
});
}
vm.submitCard=function() {
try{
if(vm.card_date) {
vm.card.exp_month=vm.card_date.getMonth()+1;
vm.card.exp_year=vm.card_date.getFullYear();
}
else {
vm.card.exp_month=null;
vm.card.exp_year=null;
}
if(vm.card_limit) {
vm.card.limit=vm.card_limit*100;
}
else {
vm.card.limit=null;
}
vm.sendPost();
}
catch(err){
$location.path('/error');
}
}
}]);
|
module.exports = {
extend: function(a, b) {
var newvar = this.clone(a);
for(var x in b) {
newvar[x] = b[x];
}
return newvar;
},
clone: function(obj) {
var newobj = {};
for(var keys = Object.keys(obj), l = keys.length; l; --l) {
newobj[keys[l-1]] = obj[keys[l-1]];
}
return newobj;
}
} |
require([
"inc/audio-listener",
"inc/duckbox-client",
"inc/impulse",
"inc/looping-impulse",
"inc/renderer",
"inc/settings"
], function(AudioListener, DuckboxClient, Impulse, LoopingImpulse, Renderer) {
var audioListener = new AudioListener()
, apiClient
, renderer
, groupRanges
, lastDate
, refreshTrackInterval
, refreshTimeInterval
, info = document.getElementsByClassName('info')[0]
, track = document.getElementsByClassName('track')[0]
, currentTrack = { artist: "Unknown Artist", title: "Unknown Track" }
/**
Access the microphone. If a source identifier is specified it will try to access
the corresponding device. Otherwise it will just get the system default.
*/
function requestAudio(sourceIdentifier) {
navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
console.log('Requesting access to audio device:', sourceIdentifier)
if (navigator.getUserMedia) {
audioListener.reset()
var options = {
audio: (sourceIdentifier ? { optional: [{sourceId: sourceIdentifier}] } : true),
video: false
}
navigator.getUserMedia(options, audioListener.init.bind(audioListener),
function(error) {
console.log('Something went wrong. (error code ' + error.code + ')')
return
}
);
}
else {
console.log('Sorry, the browser you are using doesn\'t support getUserMedia')
return
}
}
/**
Initialises the API client and triggers the continious update of the track info
*/
function initDuckboxAPI(baseURL, identifier) {
if (apiClient) {
apiClient.destroy()
}
apiClient = new DuckboxClient(baseURL, identifier)
apiClient.getCurrentTrack(updateTrackInfo)
clearInterval(refreshTrackInterval)
refreshTrackInterval = setInterval(function() { apiClient.getCurrentTrack(updateTrackInfo) }, 3 * 1000)
}
/**
Load SVG pattern and add it to the display hierarchy
*/
function loadPattern() {
var request = new XMLHttpRequest()
request.onload = function() {
var container = document.getElementById('background')
container.innerHTML = this.responseText
var groups = [
container.querySelector('g#BirdSmall').getElementsByTagName('polygon'),
container.querySelector('g#BirdMedium').getElementsByTagName('polygon'),
container.querySelector('g#BirdLarge').getElementsByTagName('polygon'),
]
groups = groups.concat(groupsForTimeElement(container.querySelector('g#Time')))
groupRanges = {
sound: {
start: 0,
end: 2
},
time: {
start: 3,
end: groups.length - 1
}
}
renderer = window.renderer = new Renderer(groups)
renderer.start()
// Add initial impulses. We use different types for the sound reactive and the time shapes.
for (var i = groups.length - 1; i >= 0; i--) {
var impulse = (i <= groupRanges.sound.end) ? new LoopingImpulse() : new Impulse()
renderer.addImpulse(impulse, i)
}
refreshTimeInterval = setInterval(updateTime, 1000)
}
request.open('GET', 'img/pattern.svg', true)
request.send()
}
/**
Returns array of groups for each digit. The SVG is organised as a tree with nodes for
each character in the HH:MM time format. Hours and minutes have digits with ranges of
0-2 (ten-digit), 0-9 (one-digit) and 0-5 (ten-digit), 0-9 (one-digit). The separator
':' has its own group. As a consequence the array has the following distribution:
0-2 hours (ten-digit)
3-12 hours (one-digit)
13 separator ':'
14-19 minutes (ten-digit)
20-29 minutes (one-digit)
*/
function groupsForTimeElement(element) {
var keys = ['g#HH', 'g#H', 'g#Separator', 'g#MM', 'g#M']
var groups = []
for (var i = 0; i < keys.length; i++) {
var digits = element.querySelector(keys[i]).getElementsByTagName('g')
for (var j = 0; j < digits.length; j++) {
groups.push(digits[j].getElementsByTagName('polygon'))
}
}
return groups
}
/**
Triggers an impulse on all time shapes every minute.
*/
function updateTime() {
var date = new Date()
if (lastDate && date.getMinutes() == lastDate.getMinutes()) {
return
}
// see groupsForTimeElement(element) for details about the offset value
var components = [
{ value: Math.floor(date.getHours() / 10), offset: 0 },
{ value: date.getHours() % 10, offset: 3 },
{ value: ':', offset: 13 },
{ value: Math.floor(date.getMinutes() / 10), offset: 14 },
{ value: date.getMinutes() % 10, offset: 20 }
]
for (var i = components.length - 1; i >= 0; i--) {
var value = (isNaN(components[i].value) ? 0 : components[i].value) + components[i].offset
var index = value + groupRanges.time.start
renderer.addImpulse(new Impulse(), index)
}
lastDate = date
}
function updateTrackInfo(value) {
if (value == currentTrack || (value && currentTrack && currentTrack.identifier == value.identifier)) {
return
}
currentTrack = value
var previous = document.getElementsByClassName('track-previous')[0]
, title = track.querySelector('.track-title')
, separator = track.querySelector('.track-separator')
, artist = track.querySelector('.track-artist')
if (previous) {
previous.remove()
}
previous = track.cloneNode(true)
track.parentNode.appendChild(previous)
setTimeout(function() { previous.classList.add('track-previous') }, 100)
if (value) {
title.innerHTML = value.title || 'Untitled'
if (value.artist) {
artist.innerHTML = value.artist
separator.classList.remove('hidden')
}
else {
separator.classList.add('hidden')
artist.innerHTML = ''
}
track.classList.add('track-hidden')
setTimeout(function() { track.classList.remove('track-hidden') }, 100)
}
else {
separator.classList.add('hidden')
title.innerHTML = ''
artist.innerHTML = ''
}
}
// Event listeners
audioListener.onchange = function(values) {
if (!renderer) return
var date = Date.now()
// Gate the incoming frequencies to ignore all empty values (values of less than 10)
var activeRange = { start:0, end: values.length - 1 }
for (var i = 0; i < values.length; i++) {
var j = values.length - i - 1
if (i >= j - 1) {
break
}
if (values[i] / 100 < 0.1 && activeRange.start >= (i - 1)) {
activeRange.start++
}
if (values[j] / 100 < 0.1 && activeRange.end <= (j + 1)) {
activeRange.end--
}
}
// Calculate the average strenghts of different frequency ranges. Ranges are roughly a third of the active range, however they do overlap slightly to make it more natural.
var strengths = []
var length = Math.floor((activeRange.end - activeRange.start) / 3)
var overlap = Math.floor(length / 4)
var ranges = [
{ start: activeRange.start, end: activeRange.start + length + overlap },
{ start: activeRange.start + length - overlap, end: activeRange.start + length * 2 + overlap },
{ start: activeRange.start + length * 2 - overlap, end: activeRange.end }
]
for (var i = 0; i < ranges.length; i++) {
var r = ranges[i]
var rangeValues = values.subarray(r.start, r.end + 1)
var avg = averageValue(rangeValues)
var amp = document.querySelector('#bar-' + (i + 1) + ' .amplitude')
amp.style.height = Math.min(avg, 100) + '%'
strengths.push(Math.min(1.0, avg / 100))
}
renderer.update(strengths)
}
function onWindowUpdate() {
var body = document.getElementsByTagName('body')[0]
, currentWindow = chrome.app.window.current()
body.className = currentWindow.isFullscreen() ? 'is-fullscreen' : ''
}
chrome.storage.sync.get(['audioInput', 'baseURL', 'identifier'], function(items) {
requestAudio(items.audioInput)
initDuckboxAPI(items.baseURL, items.identifier)
})
chrome.storage.onChanged.addListener(function(changes, areaName) {
if (changes.audioInput) {
chrome.storage.sync.get('audioInput', function(items) {
requestAudio(items.audioInput)
})
}
if (changes.identifier || changes.baseURL) {
chrome.storage.sync.get(['baseURL', 'identifier'], function(items) {
initDuckboxAPI(items.baseURL, items.identifier)
})
}
})
chrome.app.window.current().onBoundsChanged.addListener(onWindowUpdate)
chrome.app.window.current().onFullscreened.addListener(onWindowUpdate)
chrome.app.window.current().onMaximized.addListener(onWindowUpdate)
// Main initialisation
onWindowUpdate()
loadPattern()
// Helpers
function averageValue(values) {
var sum = 0
for (var i = 0; i < values.length; i++) {
sum += values[i]
}
return sum / values.length
}
})(); |
version https://git-lfs.github.com/spec/v1
oid sha256:8f1636e3111e06b42fc2a2868ed721784ad757c53f76006e190023240767f199
size 21734
|
import React from 'react';
import {
StyleSheet,
Text,
TouchableOpacity,
View,
Animated
} from 'react-native';
const propTypes = {
goToPage: React.PropTypes.func,
activeTab: React.PropTypes.number,
tabs: React.PropTypes.array,
underlineColor: React.PropTypes.string,
backgroundColor: React.PropTypes.string,
activeTextColor: React.PropTypes.string,
inactiveTextColor: React.PropTypes.string
};
class CustomTabBar extends React.Component {
renderTabOption(name, page) {
var isTabActive = this.props.activeTab === page;
var activeTextColor = this.props.activeTextColor || "navy";
var inactiveTextColor = this.props.inactiveTextColor || "black";
return (
<TouchableOpacity style={[styles.tab]} key={name} onPress={() => this.props.goToPage(page)}>
<View>
<Text style={{color: isTabActive ? activeTextColor : inactiveTextColor, fontSize: 16}}>
{name}
</Text>
</View>
</TouchableOpacity>
);
}
render() {
var containerWidth = this.props.containerWidth;
var numberOfTabs = this.props.tabs.length;
let tabUnderlineStyle = {
position: 'absolute',
width: containerWidth / numberOfTabs,
height: 2,
backgroundColor: this.props.underlineColor || "navy",
bottom: 0
};
var left = this.props.scrollValue.interpolate({
inputRange: [0, 1], outputRange: [0, containerWidth / numberOfTabs]
});
return (
<View style={[styles.tabs, {backgroundColor: this.props.backgroundColor || null}]}>
{this.props.tabs.map((tab, i) => this.renderTabOption(tab, i))}
<Animated.View style={[tabUnderlineStyle, {left}]} />
</View>
);
}
}
let styles = StyleSheet.create({
tab: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
tabs: {
height: 50,
flexDirection: 'row',
justifyContent: 'space-around',
borderWidth: 1,
borderTopWidth: 0,
borderLeftWidth: 0,
borderRightWidth: 0,
borderBottomColor: '#ccc'
}
});
CustomTabBar.propTypes = propTypes;
export default CustomTabBar; |
document.body.innerHTML = '';
var span = document.createElement('span');
span.style.fontSize = '200%';
span.style.fontWeight = 'bold';
span.textContent = 'This is created by JS in PNG.';
document.body.appendChild(span);
|
import Ember from 'ember';
import Resolver from './resolver';
import loadInitializers from 'ember-load-initializers';
import config from './config/environment';
let App;
Ember.MODEL_FACTORY_INJECTIONS = true;
if (config.environment === "development") {
Ember.run.backburner.DEBUG = true;
}
App = Ember.Application.extend({
modulePrefix: config.modulePrefix,
podModulePrefix: config.podModulePrefix,
Resolver
});
loadInitializers(App, config.modulePrefix);
export default App;
|
(function() {
var app = angular.module('colApp', ['collectionDirectives']);
// Controller to work with the Collection object
app.controller('CollectionController', ['$http','$location', function($http, $location){
var c = this;
c.collection = {};
// Initialization
// When the app ploads, it connects to the entry point of the API, "/api", to get a collection object
// The collection object is stored in "c.collection"
//Para que funcione en Openshift
////////////////////////////////////////////////////////////////////
$http.get('../api').success(function(data){
// Store the collection data
c.collection = data.collection;
// Create an empty edit template for editing items
c.collection.editTemplate = {};
// Create a history point for navigation purposes
// http://html5demos.com/history
$location.path('./collection-example.json');
// Replace current location (only on initialization)
$location.replace();
});
// Method to do a GET request to a URL
// It must be called when the user clicks on a LINK
// href: URL of the selected link (the "href" property of the link)
// http://amundsen.com/media-types/collection/format/#general
this.readCollection = function(href) {
$http.get(href).success(function(data){
// Store the collection
c.collection = data.collection;
// Create an empty edit template for editing items
c.collection.editTemplate = {};
$location.path(href);
});
};
// Method to do a POST request to create an item in a collection
// The POST request must be sent to the "href" property of the collection object
// It must be called when the user clicks on the CREATE ITEM button
// It must send the TEMPLATE object of the collection with the data filled by the user
// http://amundsen.com/media-types/collection/examples/#ex-write
this.createItem = function() {
var datos_a_enviar = {template: c.collection.template};
// TODO
/*alert("ENVIADO");*/
$http.post(c.collection.href, datos_a_enviar).success(function(data){
c.readCollection(c.collection.href);
});
};
// Method to create a template object to edit the item
// It must create a new TEMPLATE object (copying the one stored in c.collection.template) and fill in the item data
// The edit template object must be stored in c.collection.editTemplate
this.buildEditForm = function(item) {
c.collection.editTemplate.data = [];
for (var i = 0; i < item.data.length; i++)
{
c.collection.editTemplate.data[i] = item.data[i];
}
c.collection.editTemplate.href = item.href;
}
/*
for (var i = 0; i < c.collection.template.length; i++)
{
c.collection.editTemplate.data[i] = c.collection.template.data[i];
c.collection.editTemplate.data[i].value = item.data[i].value;
}
*/
// Method to do a PUT request to edit an item
// href: URL of the selected item (the "href" property of the item)
// It must be called when the user clicks on the EDIT ITEM button for a given item
// It must send c.csollection.editTemplate
// http://amundsen.com/media-types/collection/format/#general
// http://amundsen.com/media-types/collection/examples/#ex-write
this.editItem = function(href) {
var datos_a_cargar = {template: c.collection.editTemplate};
$http.put(href, datos_a_cargar).success(function(data){
c.readCollection(c.collection.href);
});
};
// Method to do a DELETE request to delete an item
// href: URL of the selected item (the "href" property of the item)
// It must be called when the user clicks on the DELETE ITEM button for a given item
// It must create a new TEMPLATE object (copying the one stored in c.collection.template) and fill in the item data
// http://amundsen.com/media-types/collection/format/#general
this.deleteItem = function(href) {
// TODO
$http.delete(href).success(function(data){
c.readCollection(c.collection.href);
});
};
}]);
})();
|
/* Set the defaults for DataTables initialisation */
$.extend( true, $.fn.dataTable.defaults, {
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page"
}
} );
/* Default class modification */
$.extend( $.fn.dataTableExt.oStdClasses, {
"sWrapper": "dataTables_wrapper form-inline"
} );
/* API method to get paging information */
$.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
return {
"iStart": oSettings._iDisplayStart,
"iEnd": oSettings.fnDisplayEnd(),
"iLength": oSettings._iDisplayLength,
"iTotal": oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage": oSettings._iDisplayLength === -1 ?
0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
"iTotalPages": oSettings._iDisplayLength === -1 ?
0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
};
};
/* Bootstrap style pagination control */
$.extend( $.fn.dataTableExt.oPagination, {
"bootstrap": {
"fnInit": function( oSettings, nPaging, fnDraw ) {
var oLang = oSettings.oLanguage.oPaginate;
var fnClickHandler = function ( e ) {
e.preventDefault();
if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
fnDraw( oSettings );
}
};
$(nPaging).addClass('pagination').append(
'<ul>'+
'<li class="prev disabled"><a href="#">← '+oLang.sPrevious+'</a></li>'+
'<li class="next disabled"><a href="#">'+oLang.sNext+' → </a></li>'+
'</ul>'
);
var els = $('a', nPaging);
$(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler );
$(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler );
},
"fnUpdate": function ( oSettings, fnDraw ) {
var iListLength = 5;
var oPaging = oSettings.oInstance.fnPagingInfo();
var an = oSettings.aanFeatures.p;
var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);
if ( oPaging.iTotalPages < iListLength) {
iStart = 1;
iEnd = oPaging.iTotalPages;
}
else if ( oPaging.iPage <= iHalf ) {
iStart = 1;
iEnd = iListLength;
} else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
iStart = oPaging.iTotalPages - iListLength + 1;
iEnd = oPaging.iTotalPages;
} else {
iStart = oPaging.iPage - iHalf + 1;
iEnd = iStart + iListLength - 1;
}
for ( i=0, ien=an.length ; i<ien ; i++ ) {
// Remove the middle elements
$('li:gt(0)', an[i]).filter(':not(:last)').remove();
// Add the new list items and their event handlers
for ( j=iStart ; j<=iEnd ; j++ ) {
sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
$('<li '+sClass+'><a href="#">'+j+'</a></li>')
.insertBefore( $('li:last', an[i])[0] )
.bind('click', function (e) {
e.preventDefault();
oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
fnDraw( oSettings );
} );
}
// Add / remove disabled classes from the static elements
if ( oPaging.iPage === 0 ) {
$('li:first', an[i]).addClass('disabled');
} else {
$('li:first', an[i]).removeClass('disabled');
}
if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
$('li:last', an[i]).addClass('disabled');
} else {
$('li:last', an[i]).removeClass('disabled');
}
}
}
}
} );
/*
* TableTools Bootstrap compatibility
* Required TableTools 2.1+
*/
if ( $.fn.DataTable.TableTools ) {
// Set the classes that TableTools uses to something suitable for Bootstrap
$.extend( true, $.fn.DataTable.TableTools.classes, {
"container": "DTTT btn-group",
"buttons": {
"normal": "btn",
"disabled": "disabled"
},
"collection": {
"container": "DTTT_dropdown dropdown-menu",
"buttons": {
"normal": "",
"disabled": "disabled"
}
},
"print": {
"info": "DTTT_print_info modal"
},
"select": {
"row": "active"
}
} );
// Have the collection use a bootstrap compatible dropdown
$.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
"collection": {
"container": "ul",
"button": "li",
"liner": "a"
}
} );
}
$(document).ready(function() {
$('#de').click(function(){
alert('Sign new href executed.');
});
$('#list').dataTable( {
"sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page"
}
} );
$( "#wlm_Operationbundle_Operationtype_code" ).keypress(function( event ) {
console.log("sd");
});
//\\//\\ *** location return functions *** //\\//\\
$(".locationReturned").each(function (i) {
if($(this).attr('status')=="in"){
$(this).attr('checked',true);
}
else{
$(this).attr('checked',false);
}
});
$(".locationReturned").click(function () {
if($(this).is(':checked')){
$.ajax({
url: $(this).attr('pathSetIn'),
type: 'POST',
async: true,
error: function(){
return true;
},
success: function(){
$('.modal-body').html('sdd');
$('#alertModal').modal('show');
return true;
}
});
}
else{
$.ajax({
url: $(this).attr('pathSetOut'),
type: 'POST',
async: true,
error: function(){
return true;
},
success: function(){
return true;
}
});
}
//location.reload();
});
//\\//\\ *** ************************** *** //\\//\\
//\\//\\ *** ************************** *** //\\//\\
//\\//\\ *** payment functions *** //\\//\\
$('#payButton').click(function(e) {
e.preventDefault();
$total = 0;
$('div .price').each(function(){
if ($(this).parents('tr').is(":visible")){
$total = $total + parseFloat($(this).html());
$.post($(this).attr('pathAtt'));
}
});
location.reload();
});
//\\//\\ *** ************************** *** //\\//\\
//\\//\\ *** petit cheni*** //\\//\\
$("#modal-form-submit").click(function() {
$("#modal-form").submit();
});
$("form input.date").datepicker({
format: 'dd-mm-yyyy'
});
$('#modal').modal('show');
$('a.tip-top').on('click', function(e) {
e.preventDefault();
$(this).parents('tr').hide();
calcAmount();
});
$('a.reload-facturation').on('click', function(e) {
e.preventDefault();
$('a.tip-top').parents('tr').show();
calcAmount();
});
function calcAmount() {
$total = 0;
$('div .price').each(function(){
if ($(this).parents('tr').is(":visible")){
$total = $total + parseFloat($(this).html());
}
});
$("#total").html($total);
}
//\\//\\ *** ************************** *** //\\//\\
//\\//\\ *** add location functions *** //\\//\\
var barcode = $('.barcode-id');
var outDate = $('.outDate-id');
var inDate = $('.inDate-id');
var table = $('.table');
entityArray = new Array(outDate,inDate,barcode);
writeIndexData(entityArray);
$("#btn_add").on('click', function(e) {
e.preventDefault();
addForm(entityArray, table);
// add datepicker to the new input date
$("form input.date").datepicker({
format: 'dd-mm-yyyy'
});
$('[rel=tooltip]').tooltip();
$('a.tip-top').on('click', function(e) {
e.preventDefault();
$(this).parents('tr').remove();
indexMinus(entityArray);
});
//\\//\\ *** equipment query *** //\\//\\
$("form input.barcode-id").keypress(function(){
alert_modal.warning('Your text goes here');
console.log('asda');
});
});
function addForm(entityArray) {
var newRow = '<tr>';
for ( var i in entityArray ) {
var newForm = getForm(entityArray[i]);
newRow = newRow + '<td>'+newForm+'</td>';
}
newRow = newRow + '<td class="taskOptions"> \
<a href="#" rel="tooltip" data-toggle="modal" class="tip-top" data-original-title="Delete Row">\
<i class="icon-remove"></i>\
</a>\
</td> \
</tr>';
newRow = $(newRow);
newRow.appendTo($('#addLocationTable'));
}
function getForm(entity){
var index = entity.data('index');
console.log(index);
var prototype = entity.attr('data-prototype');
var form = '<div class="span1">'+prototype.replace(/__name__/g, index)+"</div>";
entity.data('index', index + 1);
return form;
}
function writeIndexData(myArray){
for ( var i in myArray ) {
myArray[i].data('index', myArray[i].find(':input').length);
}
}
function indexMinus(myArray){
for ( var i in myArray ) {
var index = myArray[i].data('index');
myArray[i].data('index', index-1 );
}
}
//\\//\\ *** ************************** *** //\\//\\
});
|
/**
* angular-strap
* @version v2.3.8 - 2016-04-05
* @link http://mgcrea.github.io/angular-strap
* @author Olivier Louvignes <olivier@mg-crea.com> (https://github.com/mgcrea)
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
'use strict';angular.version.minor<3&&angular.version.dot<14&&angular.module('ng').factory('$$rAF',['$window','$timeout',function(n,e){var a=n.requestAnimationFrame||n.webkitRequestAnimationFrame||n.mozRequestAnimationFrame,t=n.cancelAnimationFrame||n.webkitCancelAnimationFrame||n.mozCancelAnimationFrame||n.webkitCancelRequestAnimationFrame,i=!!a,r=i?function(n){var e=a(n);return function(){t(e)}}:function(n){var a=e(n,16.66,!1);return function(){e.cancel(a)}};return r.supported=i,r}]);
//# sourceMappingURL=raf.min.js.map
|
var config = {}
//The published google spreadsheet with the data.
config.spreadsheet = 'https://docs.google.com/spreadsheets/d/1VtWYSW7Z-Dzjgln3MKWhYL3gEQo5J450aepk9NPv7KA/pubhtml'
//Each sheet in the spreadsheet gets its own .JSON file
config.sections = ['site', 'social', 'staff', 'map'];
//Change for local v. production
config.port = process.env.PORT || '3000';
//Timer for how often to update the JSON data
//20000 = 20 seconds; 60000 = 1 minute ; 300000 = 5 minutes
config.timer = 10000;
config.analytics = 'UA-1111111111-1';
module.exports = config;
|
pagerun.newTask('domtime', function(){
var task = this;
var doc = document;
var win = window;
var startTime, readyTime;
startTime = (new Date()).getTime();
DOMContentLoaded = function() {
if (doc.addEventListener) {
doc.removeEventListener("DOMContentLoaded", DOMContentLoaded, false);
readyTriggered();
} else if (doc.readyState === "complete") {
doc.detachEvent("onreadystatechange", DOMContentLoaded);
readyTriggered();
}
}
var isReady = false;
function readyTriggered() {
if (isReady === false) {
isReady = true;
readyTime = (new Date()).getTime() - startTime;
}
}
function loadTriggered() {
var headerTime = domtimeHeaderEndTime - startTime;
var footerTime = domtimeFooterEndTime - startTime;
var loadTime = (new Date()).getTime() - startTime;
task.info({
'url': location.href,
'header': headerTime,
'footer': footerTime,
'ready': readyTime,
'load': loadTime
});
task.end();
}
if (doc.addEventListener) {
doc.addEventListener("DOMContentLoaded", DOMContentLoaded, false);
win.addEventListener("load", readyTriggered, false);
win.addEventListener("load", loadTriggered, false);
} else {
doc.attachEvent("onreadystatechange", DOMContentLoaded);
win.attachEvent("onload", readyTriggered);
win.attachEvent("onload", loadTriggered);
var top = false;
try {
top = win.frameElement == null && doc.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !isReady ) {
try {
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
DOMContentLoaded();
}
})();
}
}
}); |
/*
* @author paper
*/
var imageSign=(function(){
var o = {}, odiv, key = false, clickOther = false, $imageWrap = BJ('imageWrap'),
curIndex=+BJ('#curZIndex').value,
setStyle = function(elem, obj){
for (var i in obj) {
elem.style[i] = obj[i];
}
}, asynInnerHTML = function(HTML, doingCallback, endCallback){
var temp = document.createElement('div'), frag = document.createDocumentFragment();
temp.innerHTML = HTML;
(function(){
if (temp.firstChild) {
frag.appendChild(temp.firstChild);
doingCallback(frag);
setTimeout(arguments.callee, 0);
}
else {
if (endCallback)
endCallback(frag);
}
})();
}, localStorageFn = (function(){
if (BJ.isIE()) {
documentElement = document.documentElement;
documentElement.addBehavior('#default#userdata');
return {
set: function(key, value){
documentElement.setAttribute('value', value);
documentElement.save(key);
},
get: function(key){
documentElement.load(key);
return documentElement.getAttribute('value');
},
remove: function(key){
documentElement.removeAttribute('value');
documentElement.save(key);
}
}
}
return {
set: function(key, value){
localStorage[key] = value;
},
get: function(key){
return localStorage[key];
},
remove: function(key){
key == undefined ? localStorage.clear() : delete localStorage[key];
}
};
})(),
saveSign=function(){
//保存起来
var sa=BJ('#imageWrap').innerHTML.toString();
localStorageFn.set('m',sa);
};
//localStorageFn.remove('m');
//load
try{
if(localStorageFn.get('m')){
BJ('#imageWrap').innerHTML=localStorageFn.get('m');
}
}catch(e){
alert(e);
}
$imageWrap.bind({
'mousedown':function(e){
key=true;
o.wrapLeft=$imageWrap.getElementPos().x;
o.wrapTop=$imageWrap.getElementPos().y;
while(BJ('#imageSignCreateTemp'))
BJ('imageSignCreateTemp').remove();
while(BJ('#imageSignCreateTemp_text'))
BJ('imageSignCreateTemp_text').remove();
var getMouse=BJ.getMouse(e);
o.beginX=getMouse.x;
o.beginY=getMouse.y;
o.left=o.beginX-o.wrapLeft,
o.top=o.beginY-o.wrapTop;
odiv=document.createElement('div');
odiv.setAttribute('id','imageSignCreateTemp');
setStyle(odiv,{
'left':o.left+'px',
'top':o.top+'px',
'border':'1px dashed #fff',
'position':'absolute',
'display':'block',
'position':'absolute',
'filter':'alpha(opacity=40)',
'opacity':0.4,
'background':'#000',
'zIndex':++curIndex,
'overflow':'hidden'
});
$imageWrap.append(odiv);
},
'mousemove':function(e){
if(!key) return;
var getMouse=BJ.getMouse(e);
o.endX=getMouse.x,
o.endY=getMouse.y;
setStyle(odiv,{
'width':Math.abs(o.endX-o.beginX)+'px',
'height':Math.abs(o.endY-o.beginY)+'px'
});
if(o.endX<=o.beginX){
if(o.endY<=o.beginY){
setStyle(odiv,{
'left':o.endX-o.wrapLeft+'px',
'top':o.endY-o.wrapTop+'px'
});
}else{
setStyle(odiv,{
'left':o.endX-o.wrapLeft+'px',
'top':o.top+'px'
});
}
}else{
if(o.endY<=o.beginY){
setStyle(odiv,{
'left':o.left+'px',
'top':o.endY-o.wrapTop+'px'
});
}else{
//do nothing...
}
}
},
'mouseup':function(e){
key=false;
if(!BJ('#imageSignCreateTemp'))return;
if(parseInt(BJ('#imageSignCreateTemp').style.height)<30 || parseInt(BJ('#imageSignCreateTemp').style.width)<54){
BJ('imageSignCreateTemp').remove();
return;
}
//生成text
var h=parseInt(BJ('#imageSignCreateTemp').style.height) || 0,
t=parseInt(BJ('#imageSignCreateTemp').style.top)+h+5,
l=parseInt(BJ('#imageSignCreateTemp').style.left),
html='<div class="imageSignCreateTemp-text" id="imageSignCreateTemp_text" style="filter:alpha(opacity=60);opacity:0.6;background-color:#FFFFFF;border:1px solid #000000;height:60px;top:'+t+'px;left:'+l+'px;overflow:hidden;position:absolute;width:230px;z-index:99999;">'+
'<div class="t">'+
'<textarea id="imageSignCreateTemp_textarea"></textarea>'+
'</div>'+
'<div class="b">'+
'<div class="word-limit"><span id="word_limit_num">1</span>/<span id="word_limit_max">30</span></div>'+
'<div class="word-ok">'+
'<a href="javascript:;" id="imageSignCreateTemp_ok">OK</a>'+
'</div>'+
'</div>'+
'</div>';
if(h==0) return;
asynInnerHTML(html,function(g){
$imageWrap.append(g);
},function(g){
BJ('imageSignCreateTemp_text').bind({
'mousedown':function(e){
BJ.stopBubble(e);
},
'mouseup':function(e){
BJ.stopBubble(e);
}
});
//限制字数
var otextarea = BJ('#imageSignCreateTemp_textarea'),
maxlen = +BJ('#word_limit_max').innerHTML;
otextarea.onkeyup = function(){
var otextarea_value = otextarea.value;
BJ('#word_limit_num').innerHTML = otextarea_value.length;
if (otextarea_value.length > maxlen) {
otextarea.value = otextarea_value.substring(0, maxlen);
}
};
otextarea.focus();
//点击OK保存
BJ('#imageSignCreateTemp_ok').onclick = function(e){
//留下区域框
var imageSignCreateTempCopy = BJ('#imageSignCreateTemp').cloneNode(true), d = +new Date();
setStyle(imageSignCreateTempCopy, {
'border': '1px solid #fff',
'filter': 'alpha(opacity=30)',
'opacity': 0.3
});
imageSignCreateTempCopy.setAttribute('id', 'imageSignCreateTemp' + d);
BJ('imageSignCreateTemp').remove();
$imageWrap.append(imageSignCreateTempCopy);
imageSignCreateTempCopy.setAttribute('onmouseover','imageSign.showChildren(this);');
imageSignCreateTempCopy.setAttribute('onmouseout','imageSign.hideChildren(this);');
imageSignCreateTempCopy.setAttribute('onmousedown','imageSign.stopD(event)');
//生成移除按钮
var imageSignCreateTemp_close = document.createElement('a');
imageSignCreateTemp_close.href = 'javascript:;';
imageSignCreateTemp_close.title = '删除这个';
imageSignCreateTemp_close.innerHTML = 'remove';
imageSignCreateTemp_close.setAttribute('onclick','imageSign.rm(this,event)');
imageSignCreateTemp_close.setAttribute('onmousedown','imageSign.stopD(event)');
setStyle(imageSignCreateTemp_close, {
'position': 'absolute',
'display': 'none',
'right': '5px',
'top': '5px',
'fontWeight': 'bold',
'color': '#fff',
'textDecoration': 'underline'
});
BJ(imageSignCreateTempCopy).append(imageSignCreateTemp_close);
BJ(imageSignCreateTempCopy).bind({
'mouseover':function(){
//BJ(imageSignCreateTemp_close).show();
imageSign.showChildren(this);
},
'mouseout':function(){
imageSign.hideChildren(this);
//BJ(imageSignCreateTemp_close).hide();
},
'mousedown':function(e){
BJ.stopBubble(e);
}
});
BJ(imageSignCreateTemp_close).bind({
'click':function(e){
BJ.stopBubble(e);
var p=BJ(this).parent();
p.next().remove();
p.remove();
},
'mousedown':function(e){
BJ.stopBubble(e);
}
});
//留下文字
var v = BJ('#imageSignCreateTemp_textarea').value || '什么都没填~~',
otxt = document.createElement('div'),
l = BJ('#imageSignCreateTemp_text').style.left,
t = BJ('#imageSignCreateTemp_text').style.top;
setStyle(otxt, {
'border': '1px solid #fff',
'filter': 'alpha(opacity=40)',
'opacity': 0.4,
'left': l,
'top': t,
'padding': '5px',
'position': 'absolute',
'color': '#fff',
'backgroundColor': '#000'
});
otxt.innerHTML = v;
BJ('imageSignCreateTemp_text').remove();
$imageWrap.append(otxt);
saveSign();
};
});
}
});
document.onmouseup=function(){
key=false;
};
return {
rm:function(me,e){
BJ.stopBubble(e);
var p=BJ(me).parent();
p.next().remove();
p.remove();
saveSign();
},
showChildren:function(me){
var fc=BJ(me).children(1);
fc.show();
var z=+BJ('#curZIndex').value+1;
me.style.zIndex=z;
BJ(me).next().getElem().style.zIndex=z;
BJ('#curZIndex').value=z;
BJ(me).next().setOpacity(60);
BJ(me).setOpacity(60);
},
hideChildren:function(me){
BJ(me).children().hide();
BJ(me).next().setOpacity(30);
BJ(me).setOpacity(30);
},
stopD:function(e){
BJ.stopBubble(e);
},
removeAll:function(){
localStorageFn.remove('m');
}
};
})();
|
'use strict'
const chai = require('chai')
const expect = chai.expect
const sinon = require('sinon')
chai.use(require('sinon-chai'))
chai.use(require('dirty-chai'))
chai.use(require('chai-as-promised'))
chai.should()
const { TlsAuthenticator } = require('../../lib/models/authenticator')
const SolidHost = require('../../lib/models/solid-host')
const AccountManager = require('../../lib/models/account-manager')
const host = SolidHost.from({ serverUri: 'https://example.com' })
const accountManager = AccountManager.from({ host, multiuser: true })
describe('TlsAuthenticator', () => {
describe('fromParams()', () => {
let req = {
connection: {}
}
let options = { accountManager }
it('should return a TlsAuthenticator instance', () => {
let tlsAuth = TlsAuthenticator.fromParams(req, options)
expect(tlsAuth.accountManager).to.equal(accountManager)
expect(tlsAuth.connection).to.equal(req.connection)
})
})
describe('findValidUser()', () => {
let webId = 'https://alice.example.com/#me'
let certificate = { uri: webId }
let connection = {
renegotiate: sinon.stub().yields(),
getPeerCertificate: sinon.stub().returns(certificate)
}
let options = { accountManager, connection }
let tlsAuth = new TlsAuthenticator(options)
tlsAuth.extractWebId = sinon.stub().resolves(webId)
sinon.spy(tlsAuth, 'renegotiateTls')
sinon.spy(tlsAuth, 'loadUser')
return tlsAuth.findValidUser()
.then(validUser => {
expect(tlsAuth.renegotiateTls).to.have.been.called()
expect(connection.getPeerCertificate).to.have.been.called()
expect(tlsAuth.extractWebId).to.have.been.calledWith(certificate)
expect(tlsAuth.loadUser).to.have.been.calledWith(webId)
expect(validUser.webId).to.equal(webId)
})
})
describe('renegotiateTls()', () => {
it('should reject if an error occurs while renegotiating', () => {
let connection = {
renegotiate: sinon.stub().yields(new Error('Error renegotiating'))
}
let tlsAuth = new TlsAuthenticator({ connection })
expect(tlsAuth.renegotiateTls()).to.be.rejectedWith(/Error renegotiating/)
})
it('should resolve if no error occurs', () => {
let connection = {
renegotiate: sinon.stub().yields(null)
}
let tlsAuth = new TlsAuthenticator({ connection })
expect(tlsAuth.renegotiateTls()).to.be.fulfilled()
})
})
describe('getCertificate()', () => {
it('should throw on a non-existent certificate', () => {
let connection = {
getPeerCertificate: sinon.stub().returns(null)
}
let tlsAuth = new TlsAuthenticator({ connection })
expect(() => tlsAuth.getCertificate()).to.throw(/No client certificate detected/)
})
it('should throw on an empty certificate', () => {
let connection = {
getPeerCertificate: sinon.stub().returns({})
}
let tlsAuth = new TlsAuthenticator({ connection })
expect(() => tlsAuth.getCertificate()).to.throw(/No client certificate detected/)
})
it('should return a certificate if no error occurs', () => {
let certificate = { uri: 'https://alice.example.com/#me' }
let connection = {
getPeerCertificate: sinon.stub().returns(certificate)
}
let tlsAuth = new TlsAuthenticator({ connection })
expect(tlsAuth.getCertificate()).to.equal(certificate)
})
})
describe('extractWebId()', () => {
it('should reject if an error occurs verifying certificate', () => {
let tlsAuth = new TlsAuthenticator({})
tlsAuth.verifyWebId = sinon.stub().yields(new Error('Error processing certificate'))
expect(tlsAuth.extractWebId()).to.be.rejectedWith(/Error processing certificate/)
})
it('should resolve with a verified web id', () => {
let tlsAuth = new TlsAuthenticator({})
let webId = 'https://alice.example.com/#me'
tlsAuth.verifyWebId = sinon.stub().yields(null, webId)
let certificate = { uri: webId }
expect(tlsAuth.extractWebId(certificate)).to.become(webId)
})
})
describe('loadUser()', () => {
it('should return a user instance if the webid is local', () => {
let tlsAuth = new TlsAuthenticator({ accountManager })
let webId = 'https://alice.example.com/#me'
let user = tlsAuth.loadUser(webId)
expect(user.username).to.equal('alice')
expect(user.webId).to.equal(webId)
})
it('should return a user instance if external user and this server is authorized provider', () => {
let tlsAuth = new TlsAuthenticator({ accountManager })
let externalWebId = 'https://alice.someothersite.com#me'
tlsAuth.discoverProviderFor = sinon.stub().resolves('https://example.com')
let user = tlsAuth.loadUser(externalWebId)
expect(user.username).to.equal(externalWebId)
expect(user.webId).to.equal(externalWebId)
})
})
describe('verifyWebId()', () => {
it('should yield an error if no cert is given', done => {
let tlsAuth = new TlsAuthenticator({})
tlsAuth.verifyWebId(null, (error) => {
expect(error.message).to.equal('No certificate given')
done()
})
})
})
})
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define({"esri/widgets/Editor/nls/Editor":{widgetLabel:"Editor",multipleFeaturesTemplate:"Flera geoobjekt ({total})",untitledFeatureTemplate:"Titell\u00f6st geoobjekt {id}",editFeatures:"Redigera geoobjekt",editFeature:"Redigera geoobjekt",addFeature:"L\u00e4gg till geoobjekt",featureAttachments:"\u00c5_Feature attachments____________________\u00f6",attachmentsButtonLabel:"\u00c5_Attachments____________\u00f6",attachments:"\u00c5_Attachments____________\u00f6",addAttachment:"\u00c5_Add attachment_______________\u00f6",
editAttachment:"\u00c5_Manage attachment__________________\u00f6",selectTemplate:"V\u00e4lj en geoobjekttyp",selectFeatureToEdit:"V\u00e4lj ett geoobjekt f\u00f6r att redigera det.",selectFeature:"V\u00e4lj geoobjekt",placeFeature:"Placera geoobjekt",placeFeatureOnMap:"Placera geoobjekt p\u00e5 kartan.",add:"L\u00e4gg till",discardEdits:"Ignorera redigeringar",discardFeature:"Ignorera geoobjekt",edit:"Redigera",keepAttachment:"\u00c5_Keep attachment________________\u00f6",keepFeature:"Beh\u00e5ll geoobjekt",
continueAdding:"Forts\u00e4tt l\u00e4gga till",continueEditing:"Forts\u00e4tt redigera",editing:"Redigering",warning:"Meddelande",retry:"F\u00f6rs\u00f6k igen",ignore:"Ignorera",deleteWarningTitle:"Ta bort geoobjektet?",deleteAttachmentWarningTitle:"\u00c5_Delete this attachment________________________\u00f6?",deleteWarningMessage:"Geoobjektet tas bort helt.",deleteAttachmentWarningMessage:"\u00c5_This attachment will be permanently removed_______________________\u00f6.",cancelEditTitle:"Ta bort redigeringar?",
cancelAddTitle:"Ignorera geoobjekt?",cancelAddWarningMessage:"Detta geoobjekt g\u00e5r f\u00f6rlorat.",cancelEditWarningMessage:"Uppdateringar av geoobjektet g\u00e5r f\u00f6rlorade.",cancelRequestTitle:"Avbryt arbetsfl\u00f6de?",cancelRequestWarningMessage:"En f\u00f6rfr\u00e5gan har skickats om att avbryta arbetsfl\u00f6det.",errorWarningTitle:"Det uppstod ett fel",errorWarningMessageTemplate:"\u00c4ndringarna kunde inte sparas: {errorMessage}",clickToFinishTemplate:"Klicka p\u00e5 {button} f\u00f6r att avsluta.",
tips:{clickToStart:"Klicka f\u00f6r att b\u00f6rja rita.",clickToContinue:"Klicka f\u00f6r att forts\u00e4tta rita.",clickToAddPoint:"Klicka om du vill l\u00e4gga till en punkt.",clickToContinueThenDoubleClickToEnd:"Klicka f\u00f6r att forts\u00e4tta rita och dubbelklicka f\u00f6r att slutf\u00f6ra.",clickToAddFeature:"Klicka f\u00f6r att l\u00e4gga till ett geoobjekt."},_localized:{}},"esri/widgets/FeatureTemplates/nls/FeatureTemplates":{widgetLabel:"Geoobjektmallar",filterPlaceholder:"Filtertyper",
noMatches:"Inga objekt hittades",noItems:"Inga mallar att visa",_localized:{}},"esri/widgets/FeatureForm/nls/FeatureForm":{widgetLabel:"Geoobjektets form",empty:"- tom -",validationErrors:{cannotBeNull:"Ange ett v\u00e4rde",outsideRange:"V\u00e4rdet ska vara mellan: {min} och {max}",invalidCodedValue:"V\u00e4rdet ska vara ett av v\u00e4rdena i listan.",invalidType:"Inte ett giltigt v\u00e4rde"},_localized:{}},"dojo/cldr/nls/gregorian":{"dateFormatItem-Ehm":"E h:mm a","days-standAlone-short":"S\u00f6 M\u00e5 Ti On To Fr L\u00f6".split(" "),
"months-format-narrow":"JFMAMJJASOND".split(""),"field-second-relative+0":"nu","quarters-standAlone-narrow":["1","2","3","4"],"field-weekday":"Veckodag","dateFormatItem-yQQQ":"y QQQ","dateFormatItem-yMEd":"E, y-MM-dd","field-wed-relative+0":"onsdag denna vecka","field-wed-relative+1":"onsdag n\u00e4sta vecka","dateFormatItem-GyMMMEd":"E d MMM y G","dateFormatItem-MMMEd":"E d MMM",eraNarrow:["f.Kr.","fvt","e.Kr.","vt"],"field-tue-relative+-1":"tisdag f\u00f6rra veckan","days-format-short":"s\u00f6 m\u00e5 ti on to fr l\u00f6".split(" "),
"dateTimeFormats-appendItem-Day-Of-Week":"{0} {1}","dateFormat-long":"d MMMM y","field-fri-relative+-1":"fredag f\u00f6rra veckan","field-wed-relative+-1":"onsdag f\u00f6rra veckan","months-format-wide":"januari februari mars april maj juni juli augusti september oktober november december".split(" "),"dateTimeFormat-medium":"{1} {0}","dayPeriods-format-wide-pm":"em","dateFormat-full":"EEEE d MMMM y","field-thu-relative+-1":"torsdag f\u00f6rra veckan","dateFormatItem-Md":"d/M","dayPeriods-format-abbr-am":"FM",
"dateTimeFormats-appendItem-Second":"{0} ({2}: {1})","dayPeriods-format-wide-noon":"noon","dateFormatItem-yMd":"y-MM-dd","field-era":"Era","dateFormatItem-yM":"y-MM","months-standAlone-wide":"Januari Februari Mars April Maj Juni Juli Augusti September Oktober November December".split(" "),"timeFormat-short":"HH:mm","quarters-format-wide":["1:a kvartalet","2:a kvartalet","3:e kvartalet","4:e kvartalet"],"dateFormatItem-yQQQQ":"y QQQQ","timeFormat-long":"HH:mm:ss z","field-year":"\u00c5r","dateFormatItem-yMMM":"MMM y",
"dateTimeFormats-appendItem-Era":"{1} {0}","field-hour":"Timme","months-format-abbr":"jan. feb. mars apr. maj juni juli aug. sep. okt. nov. dec.".split(" "),"field-sat-relative+0":"l\u00f6rdag denna vecka","field-sat-relative+1":"l\u00f6rdag n\u00e4sta vecka","timeFormat-full":"'kl'. HH:mm:ss zzzz","dateTimeFormats-appendItem-Week":"{0} ({2}: {1})","field-day-relative+0":"i dag","field-thu-relative+0":"torsdag denna vecka","field-day-relative+1":"i morgon","field-thu-relative+1":"torsdag n\u00e4sta vecka",
"dateFormatItem-GyMMMd":"d MMM y G","dateFormatItem-H":"HH","months-standAlone-abbr":"Jan. Feb. Mars Apr. Maj Juni Juli Aug. Sep. Okt. Nov. Dec.".split(" "),"quarters-format-abbr":["K1","K2","K3","K4"],"quarters-standAlone-wide":["1:a kvartalet","2:a kvartalet","3:e kvartalet","4:e kvartalet"],"dateFormatItem-Gy":"y G","dateFormatItem-M":"L","days-standAlone-wide":"S\u00f6ndag M\u00e5ndag Tisdag Onsdag Torsdag Fredag L\u00f6rdag".split(" "),"dayPeriods-format-abbr-noon":"noon","timeFormat-medium":"HH:mm:ss",
"field-sun-relative+0":"s\u00f6ndag denna vecka","dateFormatItem-Hm":"HH:mm","field-sun-relative+1":"s\u00f6ndag n\u00e4sta vecka","quarters-standAlone-abbr":["K1","K2","K3","K4"],eraAbbr:["f.Kr.","e.Kr."],"field-minute":"Minut","field-dayperiod":"fm/em","days-standAlone-abbr":"S\u00f6n M\u00e5n Tis Ons Tor Fre L\u00f6r".split(" "),"dateFormatItem-d":"d","dateFormatItem-ms":"mm:ss","quarters-format-narrow":["1","2","3","4"],"field-day-relative+-1":"i g\u00e5r","dateTimeFormat-long":"{1} {0}","dayPeriods-format-narrow-am":"f",
"dateFormatItem-h":"h a","dateFormatItem-MMMd":"d MMM","dateFormatItem-MEd":"E d/M","dateTimeFormat-full":"{1} {0}","field-fri-relative+0":"fredag denna vecka","field-fri-relative+1":"fredag n\u00e4sta vecka","field-day":"Dag","days-format-wide":"s\u00f6ndag m\u00e5ndag tisdag onsdag torsdag fredag l\u00f6rdag".split(" "),"field-zone":"Tidszon","months-standAlone-narrow":"JFMAMJJASOND".split(""),"dateFormatItem-y":"y","dateTimeFormats-appendItem-Day":"{0} ({2}: {1})","field-year-relative+-1":"i fjol",
"field-month-relative+-1":"f\u00f6rra m\u00e5naden","dateTimeFormats-appendItem-Year":"{1} {0}","dateFormatItem-hm":"h:mm a","dateTimeFormats-appendItem-Hour":"{0} ({2}: {1})","dayPeriods-format-abbr-pm":"EM","days-format-abbr":"s\u00f6n m\u00e5n tis ons tors fre l\u00f6r".split(" "),eraNames:["f\u00f6re Kristus","efter Kristus"],"dateFormatItem-yMMMd":"d MMM y","days-format-narrow":"SMTOTFL".split(""),"field-month":"M\u00e5nad","days-standAlone-narrow":"SMTOTFL".split(""),"dateFormatItem-MMM":"LLL",
"field-tue-relative+0":"tisdag denna vecka","dateTimeFormats-appendItem-Quarter":"{0} ({2}: {1})","field-tue-relative+1":"tisdag n\u00e4sta vecka","dayPeriods-format-wide-am":"fm","dateTimeFormats-appendItem-Month":"{0} ({2}: {1})","dateTimeFormats-appendItem-Minute":"{0} ({2}: {1})","dateFormatItem-EHm":"E HH:mm","field-mon-relative+0":"m\u00e5ndag denna vecka","field-mon-relative+1":"m\u00e5ndag n\u00e4sta vecka","dateFormat-short":"y-MM-dd","dateFormatItem-EHms":"E HH:mm:ss","dateFormatItem-Ehms":"E h:mm:ss a",
"dayPeriods-format-narrow-noon":"n","field-second":"Sekund","field-sat-relative+-1":"l\u00f6rdag f\u00f6rra veckan","dateFormatItem-yMMMEd":"E d MMM y","field-sun-relative+-1":"s\u00f6ndag f\u00f6rra veckan","field-month-relative+0":"denna m\u00e5nad","field-month-relative+1":"n\u00e4sta m\u00e5nad","dateTimeFormats-appendItem-Timezone":"{0} {1}","dateFormatItem-Ed":"E d","field-week":"Vecka","dateFormat-medium":"d MMM y","field-week-relative+-1":"f\u00f6rra veckan","field-year-relative+0":"i \u00e5r",
"field-year-relative+1":"n\u00e4sta \u00e5r","dayPeriods-format-narrow-pm":"e","dateTimeFormat-short":"{1} {0}","dateFormatItem-Hms":"HH:mm:ss","dateFormatItem-hms":"h:mm:ss a","dateFormatItem-GyMMM":"MMM y G","field-mon-relative+-1":"m\u00e5ndag f\u00f6rra veckan","field-week-relative+0":"denna vecka","field-week-relative+1":"n\u00e4sta vecka","dateFormatItem-yMM":"y-MM","dateFormatItem-MMdd":"dd/MM","field-day-relative+2":"i \u00f6vermorgon","dateFormatItem-MMMMd":"d MMMM","field-day-relative+-2":"i f\u00f6rrg\u00e5r",
"dateFormatItem-MMMMEd":"E d MMMM","dateFormatItem-MMd":"d/M",_localized:{}}}); |
var express = require('express');//加载express
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');//加载morgan,主要功能是在控制台中,显示req请求的信息
var cookieParser = require('cookie-parser');//支持cookie
var bodyParser = require('body-parser');
var ejs = require('ejs');
var util = require('util');
var myUtils = require('./util/baseUtils');
var tokenUtils = require('./util/tokenUtils');
var RestResult = require('./RestResult');
var config = require('./config/config');
var routes = require('./routes/index');
var userRouter = require('./routes/user');//引入自定义的user路由中间件
var statusRouter = require('./routes/status');
var UserEntity = require('./models/User').UserEntity;
var app = express();//创建app
// view engine setup
app.set('views', path.join(__dirname, 'views'));//设置模板文件路径
app.engine('.html', ejs.__express);
app.set('view engine', 'html');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'bower_components')));
//app访问预处理中间件
app.use(function (req, res, next) {
res.error = function (errorCode, errorReason) {
var restResult = new RestResult();
restResult.errorCode = errorCode;
restResult.errorReason = errorReason;
res.send(restResult);
};
res.success = function (returnValue) {
var restResult = new RestResult();
restResult.errorCode = RestResult.NO_ERROR;
restResult.returnValue = returnValue || {};
res.send(restResult);
};
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress; //设置ip
req.ip = ip;//将解析后的ip放入req中,一遍方便使用
var needLogin = false;
var requestUrl = req.url;
myUtils.ArrayUtils.each(config.needLoginUrlRegs, function (urlReg) {//片段请求路径是否为安全路径
if (urlReg.test(requestUrl)) {
needLogin = true;
return false;//返回false表示结束数组的遍历
}
});
if (needLogin) {
var token = req.headers.token;
var result;
if (myUtils.StringUtils.isNotEmpty(token) && (result = tokenUtils.parseLoginAutoToken(token))) {
var timestamp = result.timestamp;
//todo 如果对token的时间有限制,可以在这里做处理
var userId = result.userId;
UserEntity.findById(userId, '_id', function (err, user) {
if (!user) {
res.error(RestResult.AUTH_ERROR_CODE, "用户不存在");
} else {
//跟新最后活动时间和ip地址
UserEntity.update({_id: userId}, {$set: {lastActionTime: new Date()}, ip: ip}).exec();
//将当前登陆的用户id设置到req中
req.loginUserId = userId;
//进入路由中间件
next();
}
})
} else {
res.error(RestResult.AUTH_ERROR_CODE, "无效的token");
}
} else {
next();
}
});
app.use('/', routes);
app.use('/user', userRouter);//挂载user模块路由中间件
app.use('/status',statusRouter);//挂载微博模块路由中间件
// catch 404 and forward to error handler
app.use(function (req, res, next) {//404中间件
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {//异常中间件
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
import React from 'react';
import PropTypes from 'prop-types';
export const Slider = props => (
<div className='slider'>
<label htmlFor='amount'>{ props.label }</label>
<input type='range'
className='slider__range'
name='amount'
min={ props.min }
max={ props.max }
value={ props.value }
onChange={ props.onChange } />
<input type='number'
className='slider__number'
name='amount'
step={ props.step }
min={ props.min }
max={ props.max }
placeholder='1'
onChange={ props.onChange }
value={ props.value } />
</div>
);
Slider.propTypes = {
label: PropTypes.string,
value: PropTypes.number.isRequired,
step: PropTypes.string.isRequired,
min: PropTypes.string.isRequired,
max: PropTypes.oneOfType([PropTypes.string, PropTypes.number.isRequired]).isRequired,
onChange: PropTypes.func.isRequired
};
|
module.exports = {
port: process.env.PORT || 3000,
db: process.env.MONGODB || 'mongodb://localhost:27017/productsfinder',
// db: "mongodb://admin:ZBTTYquBL0OprSCJ@productsfinder-shard-00-00-ipql1.mongodb.net:27017,productsfinder-shard-00-01-ipql1.mongodb.net:27017,productsfinder-shard-00-02-ipql1.mongodb.net:27017/test?ssl=true&replicaSet=productsfinder-shard-0&authSource=admin",
secretUser : 'ZXM4C5WM5ZX85WKJV7C52S6W45BUX69BP65YUJ5DUUGGEAYE4TPC5B7C52S5AYG'
} |
// configuration
var database = "moita"; // database name
var output = "totalUnallocatedClassesByCampus"; // output collection name (for shell usage)
var semester = "20161"; // desired semester
// code
db = db.getSiblingDB(database);
var map = function() {
for (var j in this.classes) {
var _class = this.classes[j]; // class is a reserved word. WHY?????
for (var k in _class.timetable) {
var time = _class.timetable[k];
if (time.room == "AUX-ALOCAR") {
emit(this.campus, 1);
break;
}
}
}
};
var reduce = function(key, values) {
return Array.sum(values);
};
var options = { query: { semester: semester }, out: output };
db.moita.mapReduce(map, reduce, options);
db[output].find().forEach(printjson);
|
import { createIterator } from '../helpers/helpers';
QUnit.test('AsyncIterator#asIndexedPairs', assert => {
assert.expect(10);
const async = assert.async();
const { asIndexedPairs } = AsyncIterator.prototype;
assert.isFunction(asIndexedPairs);
assert.arity(asIndexedPairs, 0);
assert.name(asIndexedPairs, 'asIndexedPairs');
assert.looksNative(asIndexedPairs);
assert.nonEnumerable(AsyncIterator.prototype, 'asIndexedPairs');
asIndexedPairs.call(createIterator(['a', 'b', 'c'])).toArray().then(it => {
assert.same(it.toString(), '0,a,1,b,2,c', 'basic functionality');
async();
});
assert.throws(() => asIndexedPairs.call(undefined, () => { /* empty */ }), TypeError);
assert.throws(() => asIndexedPairs.call(null, () => { /* empty */ }), TypeError);
assert.throws(() => asIndexedPairs.call({}, () => { /* empty */ }), TypeError);
assert.throws(() => asIndexedPairs.call([], () => { /* empty */ }), TypeError);
});
|
/// <reference path="Xrm.js" />
var EntityLogicalName = "importmap";
var Form_71b19870_5e4e_4a19_8d4d_1cde7322d566_Properties = {
createdby: "createdby",
createdon: "createdon",
description: "description",
modifiedby: "modifiedby",
modifiedon: "modifiedon",
name: "name",
ownerid: "ownerid"
};
var Form_71b19870_5e4e_4a19_8d4d_1cde7322d566_Controls = {
createdby: "createdby",
createdon: "createdon",
description: "description",
modifiedby: "modifiedby",
modifiedon: "modifiedon",
name: "name",
ownerid: "ownerid"
};
var pageData = {
"Event": "none",
"SaveMode": 1,
"EventSource": null,
"AuthenticationHeader": "",
"CurrentTheme": "Default",
"OrgLcid": 1033,
"OrgUniqueName": "",
"QueryStringParameters": {
"_gridType": "4411",
"etc": "4411",
"id": "",
"pagemode": "iframe",
"preloadcache": "1344548892170",
"rskey": "141637534"
},
"ServerUrl": "",
"UserId": "",
"UserLcid": 1033,
"UserRoles": [""],
"isOutlookClient": false,
"isOutlookOnline": true,
"DataXml": "",
"EntityName": "importmap",
"Id": "",
"IsDirty": false,
"CurrentControl": "",
"CurrentForm": null,
"Forms": [],
"FormType": 2,
"ViewPortHeight": 558,
"ViewPortWidth": 1231,
"Attributes": [{
"Name": "createdby",
"Value": [{
"entityType": "Unknown",
"id": "{27ACAE0A-5D79-E111-BBD3-2657AEB3167B}",
"name": "Temp"
}],
"Type": "lookup",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": false,
"canCreate": false
},
"Controls": [{
"Name": "createdby"
}]
},
{
"Name": "createdon",
"Value": null,
"Type": "datetime",
"Format": "date",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": false,
"canCreate": false
},
"Controls": [{
"Name": "createdon"
}]
},
{
"Name": "description",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 2000,
"Controls": [{
"Name": "description"
}]
},
{
"Name": "modifiedby",
"Value": [{
"entityType": "Unknown",
"id": "{27ACAE0A-5D79-E111-BBD3-2657AEB3167B}",
"name": "Temp"
}],
"Type": "lookup",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": false,
"canCreate": false
},
"Controls": [{
"Name": "modifiedby"
}]
},
{
"Name": "modifiedon",
"Value": null,
"Type": "datetime",
"Format": "date",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": false,
"canCreate": false
},
"Controls": [{
"Name": "modifiedon"
}]
},
{
"Name": "name",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 320,
"Controls": [{
"Name": "name"
}]
},
{
"Name": "ownerid",
"Value": [{
"entityType": "Unknown",
"id": "{27ACAE0A-5D79-E111-BBD3-2657AEB3167B}",
"name": "Temp"
}],
"Type": "lookup",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"Controls": [{
"Name": "ownerid"
}]
}],
"AttributesLength": 7,
"Controls": [{
"Name": "createdby",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Created By",
"Attribute": "createdby"
},
{
"Name": "createdon",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Created On",
"Attribute": "createdon"
},
{
"Name": "description",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Description",
"Attribute": "description"
},
{
"Name": "modifiedby",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Modified By",
"Attribute": "modifiedby"
},
{
"Name": "modifiedon",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Modified On",
"Attribute": "modifiedon"
},
{
"Name": "name",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Name",
"Attribute": "name"
},
{
"Name": "ownerid",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Owner",
"Attribute": "ownerid"
}],
"ControlsLength": 7,
"Navigation": [],
"Tabs": [{
"Label": "General",
"Name": "null",
"DisplayState": "expanded",
"Visible": true,
"Sections": [{
"Label": "General",
"Name": "general",
"Visible": true,
"Controls": [{
"Name": "name"
}]
},
{
"Label": "Description",
"Name": "description",
"Visible": true,
"Controls": [{
"Name": "description"
}]
},
{
"Label": "Other",
"Name": "other",
"Visible": true,
"Controls": [{
"Name": "ownerid"
},
{
"Name": "modifiedby"
},
{
"Name": "modifiedon"
},
{
"Name": "createdby"
},
{
"Name": "createdon"
}]
}]
}]
};
var Xrm = new _xrm(pageData); |
describe("mockAjax", function() {
it("throws an error if installed multiple times", function() {
var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'),
fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest },
mockAjax = new window.MockAjax(fakeGlobal);
function doubleInstall() {
mockAjax.install();
mockAjax.install();
}
expect(doubleInstall).toThrow();
});
it("does not throw an error if uninstalled between installs", function() {
var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'),
fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest },
mockAjax = new window.MockAjax(fakeGlobal);
function sequentialInstalls() {
mockAjax.install();
mockAjax.uninstall();
mockAjax.install();
}
expect(sequentialInstalls).not.toThrow();
});
it("does throw an error if uninstalled without a current install", function() {
var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'),
fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest },
mockAjax = new window.MockAjax(fakeGlobal);
function sequentialUninstalls() {
mockAjax.install();
mockAjax.uninstall();
mockAjax.uninstall();
}
expect(sequentialUninstalls).toThrow();
});
it("does not replace XMLHttpRequest until it is installed", function() {
var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'),
fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest },
mockAjax = new window.MockAjax(fakeGlobal);
fakeGlobal.XMLHttpRequest('foo');
expect(fakeXmlHttpRequest).toHaveBeenCalledWith('foo');
fakeXmlHttpRequest.calls.reset();
mockAjax.install();
fakeGlobal.XMLHttpRequest('foo');
expect(fakeXmlHttpRequest).not.toHaveBeenCalled();
});
it("replaces the global XMLHttpRequest on uninstall", function() {
var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'),
fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest },
mockAjax = new window.MockAjax(fakeGlobal);
mockAjax.install();
mockAjax.uninstall();
fakeGlobal.XMLHttpRequest('foo');
expect(fakeXmlHttpRequest).toHaveBeenCalledWith('foo');
});
it("clears requests and stubs upon uninstall", function() {
var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'),
fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest },
mockAjax = new window.MockAjax(fakeGlobal);
mockAjax.install();
mockAjax.requests.track({url: '/testurl'});
mockAjax.stubRequest('/bobcat');
expect(mockAjax.requests.count()).toEqual(1);
expect(mockAjax.stubs.findStub('/bobcat')).toBeDefined();
mockAjax.uninstall();
expect(mockAjax.requests.count()).toEqual(0);
expect(mockAjax.stubs.findStub('/bobcat')).not.toBeDefined();
});
it("allows the httpRequest to be retrieved", function() {
var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'),
fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest },
mockAjax = new window.MockAjax(fakeGlobal);
mockAjax.install();
var request = new fakeGlobal.XMLHttpRequest();
expect(mockAjax.requests.count()).toBe(1);
expect(mockAjax.requests.mostRecent()).toBe(request);
});
it("allows the httpRequests to be cleared", function() {
var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'),
fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest },
mockAjax = new window.MockAjax(fakeGlobal);
mockAjax.install();
var request = new fakeGlobal.XMLHttpRequest();
expect(mockAjax.requests.mostRecent()).toBe(request);
mockAjax.requests.reset();
expect(mockAjax.requests.count()).toBe(0);
});
});
|
/**
* Fetch the primary records. This mutates `context.response`
* for the next method.
*
* @return {Promise}
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = function (context) {
var adapter = this.adapter;
var _context$request = context.request;
var type = _context$request.type;
var ids = _context$request.ids;
var options = _context$request.options;
var meta = _context$request.meta;
if (!type) return context;
var args = [type, ids];
args.push(options ? options : null);
if (meta) args.push(meta);
return adapter.find.apply(adapter, args).then(function (records) {
Object.defineProperty(context.response, 'records', {
configurable: true,
value: records
});
return context;
});
};
module.exports = exports['default']; |
//home.js
//Used by the external pages (simple UI stuff)
var skyColor = "#64a7eb";
//Lifesaver
function _g(id) {
return document.getElementById(id);
}
//Elements
function fadeInElement(ele, step, speed) {
step = typeof(step) != 'undefined' ? step : 1;
speed = typeof(speed) != 'undefined' ? speed : 5;
for (i=0;i<100;i=i+step) {
setTimeout("_g('"+ele.id+"').style.opacity = " + (i / 100) + ";", i * speed);
}
}
var cloudarray = new Array();
function addCloud(left, dir) {
var sky = _g("sky");
var cloud = document.createElement('div');
cloud.className = "cloud";
cloud.id = "cloud_" + Math.round((Math.random() * 10000));
cloud.style.left = left + "px";
cloud.style.backgroundSize = 60 + (Math.random() * 90) + "px";
cloud.setAttribute("data-direction", dir);
sky.appendChild(cloud);
cloudarray.push(cloud.id);
}
var planearray = new Array();
function addPlane(caption) {
var sky = _g("sky");
var plane = document.createElement('div');
plane.className = "plane";
plane.id = "plane_" + Math.round((Math.random() * 10000));
plane.style.left = "2500px";
plane.style.width = (28 * caption.length) + "px";
plane.innerHTML = "<img src='img/plane.png' style='float:left'><div class='banner'>"+caption+"</div>";
sky.appendChild(plane);
planearray.push(plane.id);
var x = 2000;
for (i = 0; i < 2500; i++) {
setTimeout("_g('"+plane.id+"').style.left="+x+" + 'px';", i * 7);
x--;
}
}
function animate() {
for (i = 0; i < cloudarray.length; i++) {
var cloud = _g(cloudarray[i]);
var left = parseFloat(cloud.style.left.replace("px", ""));
left += parseFloat(cloud.getAttribute("data-direction"));
if (left > 2000)
left = -200;
if (left < -200)
left = 2000;
cloud.style.left = left + "px";
}
}
setInterval("animate();",50);
function renderSky() {
addCloud(-100, 1);
addCloud(200, 2);
addCloud(600, 1);
addCloud(800, -2);
addCloud(900, 1);
for (var i = 0; i < Math.random() * 2; i++) {
addCloud(Math.random() * 2000, 1);
addCloud(Math.random() * 2000, -2);
addCloud(Math.random() * 2000, 1);
}
setSkyColor(skyColor);
}
function setSkyColor(skyColor) {
var sky = _g("sky");
sky.style.backgroundColor = skyColor;
var prefixes = ["","-webkit-","-o-","-moz-","-ms-"];
for (n in prefixes) {
sky.style.backgroundImage = prefixes[n] + "linear-gradient(rgba(255,255,255,0.7) 0%, "+skyColor+" 100%)";
}
fadeInElement(sky);
} |
var cutX;
var cutY;
var cutW;
var cutH;
var imgWidth;
var imgHeight;
function fileChange(imgSrc) {
$("#target").attr("src", "../../images/nohead.png");
var filepath = $("#uploadFile").val();
var extStart = filepath.lastIndexOf(".");
var ext = filepath.substring(extStart, filepath.length).toUpperCase();
if (ext != ".JPG") {
alert("请选择为(.jpg)的图片文件!");
//$("#target").attr("src", "../../images/nohead.png");
} else {
$("#uploadHeadImg").form("submit", {
url : "./PicturesAction_upload.action?picturesTime=" + new Date().getTime(),
onSubmit : function(param) {
},
success : function(data) {
var returnUrl = data.substring(2, data.length - 1);
//var randomNum = Math.floor(Math.random() * 10000000);//+'?randomNum='+ randomNum;
var showImgUrl = "./uploadImages" + returnUrl;
$("#target").attr("src", showImgUrl);
$("#target").load(function() {
imgWidth = $("#target").width();
imgHeight = $("#target").height();
if (imgWidth > imgHeight) {
var showH = Math.round(imgHeight * 350 / imgWidth) + "px";
$("#target").css({
"width" : "350px",
"height" : showH
});
} else if (imgWidth < imgHeight) {
var showW = Math.round(imgWidth * 350 / imgHeight) + "px";
$("#target").css({
"width" : showW,
"height" : "350px"
});
} else {
$("#target").css({
"width" : imgWidth,
"height" : imgHeight
});
}
$("#crop_preview").attr("src", showImgUrl);
jcropImg();
});
}
});
}
}
//function loadImage(src){
// var render = new FileReader();
// reader.onload = function(e){
// render(e.target.result);
// };
// render.readAsDataURL(src);
//}
function jcropImg() {
$("#target").Jcrop({
onChange : showPreview,
onSelect : showPreview,
bgColor : "black", //选择后,背景颜色
bgOpacity : 0.4, //背景透明度
setSelect : [0, 0, 180, 180], //默认选择坐标位置。
aspectRatio : 1
});
function showPreview(coords) {
if (parseInt(coords.w) > 0) {
//计算预览区域图片缩放的比例,通过计算显示区域的宽度(与高度)与剪裁的宽度(与高度)之比得到
var rx = $("#preview_box").width() / coords.w;
var ry = $("#preview_box").height() / coords.h;
//通过比例值控制图片的样式与显示
$("#crop_preview").css({
width : Math.round(rx * $("#target").width()) + "px", //预览图片宽度为计算比例值与原图片宽度的乘积
height : Math.round(rx * $("#target").height()) + "px", //预览图片高度为计算比例值与原图片高度的乘积
marginLeft : "-" + Math.round(rx * coords.x) + "px",
marginTop : "-" + Math.round(ry * coords.y) + "px"
});
//alert(coords.x+"-"+coords.y+"-"+coords.x2+"-"+coords.y2+"-"+coords.w+"-"+coords.h);
var picW = imgWidth;
var picH = imgHeight;
if (picW > picH) {
cutX = Math.round(picW * coords.x / 350);
cutY = Math.round(picW * coords.y / 350);
cutW = Math.round(picW * coords.w / 350);
cutH = Math.round(picW * coords.h / 350);
} else if (picW < picH) {
cutX = Math.round(picH * coords.x / 350);
cutY = Math.round(picH * coords.y / 350);
cutW = Math.round(picH * coords.w / 350);
cutH = Math.round(picH * coords.h / 350);
} else {
cutX = coords.x;
cutY = coords.y;
cutW = coords.w;
cutH = coords.h;
}
}
}
}
function cutImgBtn() {
var cutImgUrl = $("#target").attr("src");
//alert(cutX + "--" + cutY + "--" + cutW + "--" + cutH + "--" + cutImgUrl);
$.post("./PicturesAction_cutImg.action?picturesTime=" + new Date().getTime(), {
cutImgX : cutX,
cutImgY : cutY,
cutImgW : cutW,
cutImgH : cutH,
cutImgPath : cutImgUrl
}, function(data) {
var deleteImgUrl = cutImgUrl.substring(15, cutImgUrl.length);
alert(deleteImgUrl);
$.post("./PicturesAction_deletePictures.action?picturesTime=" + new Date().getTime(), {
delPicURL : deleteImgUrl
}, function(data) {
}, "json");
if (data) {
alert("头像保存成功!");
} else {
alert("头像保存失败!");
}
}, "json");
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _reactNative = require('react-native');
var _default = require('../../style/themes/default');
var _default2 = _interopRequireDefault(_default);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports["default"] = _reactNative.StyleSheet.create({
text: {
fontSize: _default2["default"].tabs_font_size_heading
},
tab: {
paddingBottom: 0
},
barTop: {
height: _default2["default"].tabs_height,
borderTopWidth: 0,
borderBottomWidth: 1
},
barBottom: {
height: _default2["default"].tabs_height,
borderTopWidth: 1,
borderBottomWidth: 0
},
underline: {
height: 2
}
});
module.exports = exports['default']; |
'use strict';
const Joi = require('joi');
const Confidence = require('confidence');
const todoSchema = require('../../schemas').todoSchema;
/*
This model is for Demo purposes only.
This must be replaced with actual database api.
*/
exports.row = function (filter, next) {
const ids = Object.keys(this.todosDB);
const todos = {
totalTodoCount: ids.length,
activeTodoCount: 0,
completedTodoCount: 0,
list: []
};
for (let i = 0; i < ids.length; ++i) {
const todo = this.todosDB[ids[i]];
todo.id = ids[i];
if (todo.done) {
++todos.completedTodoCount;
}
else {
++todos.activeTodoCount;
}
if (filter === 'all'
|| (filter === 'active' && !todo.done)
|| (filter === 'completed' && todo.done)) {
todos.list.push(todo);
}
}
return next(null, todos);
};
exports.del = function (id, next) {
const err = Joi.string().validate(id || null).error;
let isDeleted = false;
if (!err) {
if (this.todosDB[id]) {
delete this.todosDB[id];
isDeleted = true;
}
else if (id === 'completed') {
const ids = Object.keys(this.todosDB);
for (let i = 0; i < ids.length; ++i) {
const todo = [ids[i]];
if (this.todosDB[todo].done) {
delete this.todosDB[todo];
}
}
isDeleted = true;
}
}
return next(err, isDeleted);
};
exports.add = function (todo, next) {
const requireContent = todoSchema.requiredKeys('content');
const err = requireContent.validate(todo).error;
const id = Confidence.id.generate().replace(/-/g, '');
if (!err) {
this.todosDB[id] = {
done: todo.done || false,
content: todo.content
};
}
return next(err, id);
};
exports.set = function (todo, next) {
const requireId = todoSchema.requiredKeys('id').or('done', 'content');
const err = requireId.validate(todo).error;
let isUpdated = false;
if (!err) {
if (this.todosDB[todo.id]) {
if (Object.prototype.hasOwnProperty.call(todo, 'done')) {
this.todosDB[todo.id].done = todo.done;
}
if (Object.prototype.hasOwnProperty.call(todo, 'content')) {
this.todosDB[todo.id].content = todo.content;
}
isUpdated = true;
}
else if (todo.id === 'all' && Object.prototype.hasOwnProperty.call(todo, 'done')) {
const ids = Object.keys(this.todosDB);
for (let i = 0; i < ids.length; ++i) {
this.todosDB[ids[i]].done = todo.done;
}
isUpdated = true;
}
}
return next(err, isUpdated);
};
|
nv.models.scatterPlusLineChart = function() {
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var scatter = nv.models.scatter()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend()
, controls = nv.models.legend()
, distX = nv.models.distribution()
, distY = nv.models.distribution()
;
var margin = {top: 30, right: 20, bottom: 50, left: 75}
, width = null
, height = null
, color = nv.utils.defaultColor()
, x = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.xScale()
, y = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.yScale()
, showDistX = false
, showDistY = false
, showLegend = true
, showControls = !!d3.fisheye
, fisheye = 0
, pauseFisheye = false
, tooltips = true
, tooltipX = function(key, x, y) { return '<strong>' + x + '</strong>' }
, tooltipY = function(key, x, y) { return '<strong>' + y + '</strong>' }
, tooltip = function(key, x, y, date) { return '<h3>' + key + '</h3>'
+ '<p>' + date + '</p>' }
//, tooltip = null
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide')
, noData = "No Data Available."
;
scatter
.xScale(x)
.yScale(y)
;
xAxis
.orient('bottom')
.tickPadding(10)
;
yAxis
.orient('left')
.tickPadding(10)
;
distX
.axis('x')
;
distY
.axis('y')
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var x0, y0;
var showTooltip = function(e, offsetElement) {
//TODO: make tooltip style an option between single or dual on axes (maybe on all charts with axes?)
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
top = e.pos[1] + ( offsetElement.offsetTop || 0),
leftX = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
topX = y.range()[0] + margin.top + ( offsetElement.offsetTop || 0),
leftY = x.range()[0] + margin.left + ( offsetElement.offsetLeft || 0 ),
topY = e.pos[1] + ( offsetElement.offsetTop || 0),
xVal = xAxis.tickFormat()(scatter.x()(e.point, e.pointIndex)),
yVal = yAxis.tickFormat()(scatter.y()(e.point, e.pointIndex));
if( tooltipX != null )
nv.tooltip.show([leftX, topX], tooltipX(e.series.key, xVal, yVal, e, chart), 'n', 1, offsetElement, 'x-nvtooltip');
if( tooltipY != null )
nv.tooltip.show([leftY, topY], tooltipY(e.series.key, xVal, yVal, e, chart), 'e', 1, offsetElement, 'y-nvtooltip');
if( tooltip != null )
nv.tooltip.show([left, top], tooltip(e.series.key, xVal, yVal, e.point.tooltip, e, chart), e.value < 0 ? 'n' : 's', null, offsetElement);
};
var controlsData = [
{ key: 'Magnify', disabled: true }
];
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
chart.update = function() { chart(selection) };
chart.container = this;
//------------------------------------------------------------
// Display noData message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Scales
x = scatter.xScale();
y = scatter.yScale();
x0 = x0 || x;
y0 = y0 || y;
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-scatterChart').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatterChart nv-chart-' + scatter.id());
var gEnter = wrapEnter.append('g');
var g = wrap.select('g')
// background for pointer events
gEnter.append('rect').attr('class', 'nvd3 nv-background')
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis');
gEnter.append('g').attr('class', 'nv-scatterWrap');
gEnter.append('g').attr('class', 'nv-regressionLinesWrap');
gEnter.append('g').attr('class', 'nv-distWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
gEnter.append('g').attr('class', 'nv-controlsWrap');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
//------------------------------------------------------------
// Legend
if (showLegend) {
legend.width( availableWidth / 2 );
wrap.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
}
wrap.select('.nv-legendWrap')
.attr('transform', 'translate(' + (availableWidth / 2) + ',' + (-margin.top) +')');
}
//------------------------------------------------------------
//------------------------------------------------------------
// Controls
if (showControls) {
controls.width(180).color(['#444']);
g.select('.nv-controlsWrap')
.datum(controlsData)
.attr('transform', 'translate(0,' + (-margin.top) +')')
.call(controls);
}
//------------------------------------------------------------
//------------------------------------------------------------
// Main Chart Component(s)
scatter
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }))
wrap.select('.nv-scatterWrap')
.datum(data.filter(function(d) { return !d.disabled }))
.call(scatter);
wrap.select('.nv-regressionLinesWrap')
.attr('clip-path', 'url(#nv-edge-clip-' + scatter.id() + ')');
var regWrap = wrap.select('.nv-regressionLinesWrap').selectAll('.nv-regLines')
.data(function(d) { return d });
var reglines = regWrap.enter()
.append('g').attr('class', 'nv-regLines')
.append('line').attr('class', 'nv-regLine')
.style('stroke-opacity', 0);
//d3.transition(regWrap.selectAll('.nv-regLines line'))
regWrap.selectAll('.nv-regLines line')
.attr('x1', x.range()[0])
.attr('x2', x.range()[1])
.attr('y1', function(d,i) { return y(x.domain()[0] * d.slope + d.intercept) })
.attr('y2', function(d,i) { return y(x.domain()[1] * d.slope + d.intercept) })
.style('stroke', function(d,i,j) { return color(d,j) })
.style('stroke-opacity', function(d,i) {
return (d.disabled || typeof d.slope === 'undefined' || typeof d.intercept === 'undefined') ? 0 : 1
});
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Axes
xAxis
.scale(x)
.ticks( xAxis.ticks() ? xAxis.ticks() : availableWidth / 100 )
.tickSize( -availableHeight , 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + y.range()[0] + ')')
.call(xAxis);
yAxis
.scale(y)
.ticks( yAxis.ticks() ? yAxis.ticks() : availableHeight / 36 )
.tickSize( -availableWidth, 0);
g.select('.nv-y.nv-axis')
.call(yAxis);
if (showDistX) {
distX
.getData(scatter.x())
.scale(x)
.width(availableWidth)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }));
gEnter.select('.nv-distWrap').append('g')
.attr('class', 'nv-distributionX');
g.select('.nv-distributionX')
.attr('transform', 'translate(0,' + y.range()[0] + ')')
.datum(data.filter(function(d) { return !d.disabled }))
.call(distX);
}
if (showDistY) {
distY
.getData(scatter.y())
.scale(y)
.width(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }));
gEnter.select('.nv-distWrap').append('g')
.attr('class', 'nv-distributionY');
g.select('.nv-distributionY')
.attr('transform', 'translate(-' + distY.size() + ',0)')
.datum(data.filter(function(d) { return !d.disabled }))
.call(distY);
}
//------------------------------------------------------------
if (d3.fisheye) {
g.select('.nv-background')
.attr('width', availableWidth)
.attr('height', availableHeight);
g.select('.nv-background').on('mousemove', updateFisheye);
g.select('.nv-background').on('click', function() { pauseFisheye = !pauseFisheye;});
scatter.dispatch.on('elementClick.freezeFisheye', function() {
pauseFisheye = !pauseFisheye;
});
}
function updateFisheye() {
if (pauseFisheye) {
g.select('.nv-point-paths').style('pointer-events', 'all');
return false;
}
g.select('.nv-point-paths').style('pointer-events', 'none' );
var mouse = d3.mouse(this);
x.distortion(fisheye).focus(mouse[0]);
y.distortion(fisheye).focus(mouse[1]);
g.select('.nv-scatterWrap')
.datum(data.filter(function(d) { return !d.disabled }))
.call(scatter);
g.select('.nv-x.nv-axis').call(xAxis);
g.select('.nv-y.nv-axis').call(yAxis);
g.select('.nv-distributionX')
.datum(data.filter(function(d) { return !d.disabled }))
.call(distX);
g.select('.nv-distributionY')
.datum(data.filter(function(d) { return !d.disabled }))
.call(distY);
}
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
controls.dispatch.on('legendClick', function(d,i) {
d.disabled = !d.disabled;
fisheye = d.disabled ? 0 : 2.5;
g.select('.nv-background') .style('pointer-events', d.disabled ? 'none' : 'all');
g.select('.nv-point-paths').style('pointer-events', d.disabled ? 'all' : 'none' );
if (d.disabled) {
x.distortion(fisheye).focus(0);
y.distortion(fisheye).focus(0);
g.select('.nv-scatterWrap').call(scatter);
g.select('.nv-x.nv-axis').call(xAxis);
g.select('.nv-y.nv-axis').call(yAxis);
} else {
pauseFisheye = false;
}
chart(selection);
});
legend.dispatch.on('legendClick', function(d,i, that) {
d.disabled = !d.disabled;
if (!data.filter(function(d) { return !d.disabled }).length) {
data.map(function(d) {
d.disabled = false;
wrap.selectAll('.nv-series').classed('disabled', false);
return d;
});
}
chart(selection);
});
/*
legend.dispatch.on('legendMouseover', function(d, i) {
d.hover = true;
chart(selection);
});
legend.dispatch.on('legendMouseout', function(d, i) {
d.hover = false;
chart(selection);
});
*/
scatter.dispatch.on('elementMouseover.tooltip', function(e) {
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex)
.attr('y1', e.pos[1] - availableHeight);
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex)
.attr('x2', e.pos[0] + distX.size());
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e, that.parentNode);
});
//============================================================
//store old scales for use in transitions on update
x0 = x.copy();
y0 = y.copy();
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
scatter.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex)
.attr('y1', 0);
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex)
.attr('x2', distY.size());
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.scatter = scatter;
chart.legend = legend;
chart.controls = controls;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.distX = distX;
chart.distY = distY;
d3.rebind(chart, scatter, 'id', 'interactive', 'pointActive', 'x', 'y', 'shape', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'sizeDomain', 'sizeRange', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'clipRadius', 'useVoronoi');
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
legend.color(color);
distX.color(color);
distY.color(color);
return chart;
};
chart.showDistX = function(_) {
if (!arguments.length) return showDistX;
showDistX = _;
return chart;
};
chart.showDistY = function(_) {
if (!arguments.length) return showDistY;
showDistY = _;
return chart;
};
chart.showControls = function(_) {
if (!arguments.length) return showControls;
showControls = _;
return chart;
};
chart.showLegend = function(_) {
if (!arguments.length) return showLegend;
showLegend = _;
return chart;
};
chart.fisheye = function(_) {
if (!arguments.length) return fisheye;
fisheye = _;
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.tooltipXContent = function(_) {
if (!arguments.length) return tooltipX;
tooltipX = _;
return chart;
};
chart.tooltipYContent = function(_) {
if (!arguments.length) return tooltipY;
tooltipY = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
//============================================================
return chart;
}
|
// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';
module.exports = WebSocketTransportAdapter;
var assert = require('assert');
var BaseMessage = require('../message/base-message');
var BaseTransportAdapter = require('./base-transport-adapter');
var Constants = require('../constants');
var log = require('../log')('WebSocketTransportAdapter');
var PingMessage = require('../message/ping-message');
var util = require('util');
function WebSocketTransportAdapter(options) {
options = options || {};
assert(typeof options.url === 'string', 'Invalid WebSocketTransportAdapter url');
BaseTransportAdapter.call(this, options);
this.name = 'WebSocketTransport';
this.url = options.url;
this._explicitlyClosed = false;
this._nonAckedMessages = [];
this._session = null;
this._status = Constants.TransportStatus.CLOSED;
this._pingTimer = null;
this._inactivityPingInterval = options.inactivityPingInterval ||
Constants.Transport.INACTIVITY_PING_INTERVAL;
this._inactivityPingIntervalVariance = options.inactivityPingIntervalVariance ||
Constants.Transport.INACTIVITY_PING_INTERVAL_VARIANCE;
}
util.inherits(WebSocketTransportAdapter, BaseTransportAdapter);
WebSocketTransportAdapter.prototype.connect = function() {
if (this._status !== Constants.TransportStatus.CLOSED) {
return;
}
this._socket = new WebSocket(this.url);
this._bindSocketEvents();
this._changeStatus(Constants.TransportStatus.CONNECTING);
};
WebSocketTransportAdapter.prototype.disconnect = function() {
if (this._status === Constants.TransportStatus.CLOSED) {
return;
}
this._stopPing();
this._explicitlyClosed = true;
this._session = null;
this._socket.close();
this._socket = null;
};
WebSocketTransportAdapter.prototype.reconnect = function() {
if (this._status !== Constants.TransportStatus.CONNECTED) {
return;
}
this.disconnect();
};
WebSocketTransportAdapter.prototype.sendMessage = function(message) {
try {
// Convert the message to JSON
var json = JSON.stringify(message.toJSON());
if (this._session) {
this._nonAckedMessages.push(message);
}
if (this._status === Constants.TransportStatus.CONNECTED) {
log('Message sent', message);
// Send the message JSON through the socket
this._socket.send(json);
}
} catch(e) {
log.error('Message send error', e, message);
}
};
WebSocketTransportAdapter.prototype.setSession = function(session) {
this._session = session;
this._startPing();
};
WebSocketTransportAdapter.prototype._bindSocketEvents = function() {
this._socket.onopen = this._onSocketOpen.bind(this);
this._socket.onclose = this._onSocketClose.bind(this);
this._socket.onmessage = this._onSocketMessage.bind(this);
};
WebSocketTransportAdapter.prototype._startPing = function() {
this._stopPing();
// Calculate ping delay with variance
var varianceLowerBound = this._inactivityPingInterval - (this._inactivityPingIntervalVariance / 2);
var randomVariance = Math.random() * this._inactivityPingIntervalVariance;
var delay = varianceLowerBound + randomVariance;
this._pingTimer = setTimeout(this._onPing.bind(this), delay);
};
WebSocketTransportAdapter.prototype._stopPing = function() {
clearTimeout(this._pingTimer);
this._pingTimer = null;
};
WebSocketTransportAdapter.prototype._onPing = function() {
var pingMessage = new PingMessage({
session: this._session
});
this.sendMessage(pingMessage);
this._startPing();
};
WebSocketTransportAdapter.prototype._onPingMessage = function(message) {
// Filter non-acked messages before the last ack
this._nonAckedMessages = this._nonAckedMessages.filter(function(m) {
return m.index > message.ack;
});
// Resend non-acked messages
if (message.resendMissing) {
this._nonAckedMessages.forEach(this.sendMessage.bind(this));
}
};
WebSocketTransportAdapter.prototype._onSocketOpen = function() {
this._changeStatus(Constants.TransportStatus.CONNECTED);
// Request missing messages to be resent
if (this._session) {
var pingMessage = new PingMessage({
session: this._session,
resendMissing: true
});
this.sendMessage(pingMessage);
this._startPing();
}
};
WebSocketTransportAdapter.prototype._onSocketClose = function() {
this._changeStatus(Constants.TransportStatus.CLOSED);
this._stopPing();
// Reconnect if the socket was not explicitly closed
if (!this._explicitlyClosed) {
this.connect();
}
};
WebSocketTransportAdapter.prototype._onSocketMessage = function(message) {
var messages = [];
// Parse message JSON data
try {
messages = JSON.parse(message.data);
if (!(messages instanceof Array)) {
messages = [messages];
}
} catch(e) {
log.error('Message parse error', e, message);
}
for (var i = 0; i < messages.length; i++) {
message = BaseMessage.parse(messages[i]);
log('Message received', message);
if (message instanceof PingMessage) {
this._onPingMessage(message);
}
this.emit(Constants.Event.TRANSPORT_ADAPTER_MESSAGE, message);
}
};
|
import VCO, { SINE, PINK_NOISE } from "synth/basics/vco";
import PulseTrigger from "synth/basics/pulseTrigger";
import VCF, { LOWPASS } from "synth/basics/vcf";
import VCA from "synth/basics/vca";
import ADGenerator, { LINEAR } from "synth/basics/ADGenerator";
import { equalPower } from "helpers";
// 0 = conga, 1 = tom
const parameterMap = {
low: [
{
frequencies: [220, 165],
decay: [180, 200]
},
{
frequencies: [100, 80],
decay: [200, 200]
}
],
mid: [
{
frequencies: [310, 250],
decay: [100, 155]
},
{
frequencies: [160, 120],
decay: [130, 155]
}
],
high: [
{
frequencies: [455, 370],
decay: [180, 125]
},
{
frequencies: [220, 165],
decay: [200, 125]
}
]
};
export default function(type) {
return function(audioCtx, destination, time, { level, tuning, selector }) {
// parameters
const {
frequencies: [highFreq, lowFreq],
decay: [oscDecay, noiseDecay]
} = parameterMap[type][selector];
const oscFreq = (tuning / 100) * (highFreq - lowFreq) + lowFreq;
const outputLevel = equalPower(level / 4);
// audio modules
const osc = new VCO(SINE, audioCtx);
osc.frequency.value = oscFreq;
const noiseOsc = new VCO(PINK_NOISE, audioCtx);
const click = new PulseTrigger(audioCtx);
click.gain.amplitude.value = 0.3;
const noiseVCF = new VCF(LOWPASS, audioCtx);
noiseVCF.frequency.value = 10000;
const oscVCA = new VCA(audioCtx);
const noiseVCA = new VCA(audioCtx);
const outputVCA = new VCA(audioCtx);
outputVCA.amplitude.value = outputLevel;
// envelopes
const oscEnv = new ADGenerator(LINEAR, 0.1, oscDecay, 0, 1);
const noiseEnv = new ADGenerator(LINEAR, 0.1, noiseDecay, 0, 0.2);
// audio routing
osc.connect(oscVCA);
oscVCA.connect(outputVCA);
if (selector === 1) {
// only the toms get noise
noiseOsc.connect(noiseVCF);
noiseVCF.connect(noiseVCA);
noiseVCA.connect(outputVCA);
}
click.connect(outputVCA);
// modulation routing
oscEnv.connect(oscVCA.amplitude);
noiseEnv.connect(noiseVCA.amplitude);
// output routing
outputVCA.connect(destination);
// envelope/oscillator triggering
osc.start(time);
noiseOsc.start(time);
click.trigger(time, audioCtx);
oscEnv.trigger(time);
noiseEnv.trigger(time);
// cleanup
window.setTimeout(() => {
osc.stop();
noiseOsc.stop();
outputVCA.disconnect();
}, time - audioCtx.currentTime + 1000);
return outputVCA;
};
}
|
//create variables
var barSpacing = 0;
var barWidth = 0;
var chartHeight = 0;
var chartHeightArea = 0;
var chartScale = 0;
var maxValue = 0;
var highestYlable = 0;
var valueMultiplier = 0;
//create a document ready statement
$(document).ready(function(){
//setting the global variables
window.chartHeight = Number($(".chart-area").height());
window.barWidth = $(".chart-area .chart-bar").width();
window.highestYlable = Number($(".chart-y-axis p").first().html());
window.chartHeightArea = window.chartHeight - Number($("p.axis-value").first().height());
window.chartScale = chartHeightArea/window.highestYlable;
window.barSpacing = Number($(".chart-area").attr("bar-spacing"));
animateChart();
positionBars();
});
function positionBars(){
//create a function that will position the bars
$(".chart-area .chart-bar").each(function(index){
var barPosition = (window.barWidth * index) + (window.barSpacing * index) + window.barSpacing;
$(this).css("left", barPosition + "px");
//add text to bar and axis
$(this).html("<p>"+$(this).attr("bar-value") + "°F</p>");
//x-axis
$('.chart-x-axis').append('<p style="left:'+(barPosition - (window.barWidth/2)) + 'px;">' + $(this).attr('label')+'</p>');
//relative height of bars
var barValue = Number($(this).attr("bar-value"));
if(barValue > window.maxValue){
window.maxValue = barValue;
window.valueMultiplier = window.maxValue / window.highestYlable;
}
})
}
//create a new function that will animate our chart
function animateChart(){
//get each bar to animate to its proper height
$(".chart-area .chart-bar").each(function(index){
//height relative to chart
var revisedValue = Number($(this).attr("bar-value")) * window.chartScale;
//create a variable for delay
var newDelay = 125*index;
//Animate the bar
$(this).delay(newDelay).animate({height:revisedValue}, 1000, function(){
//fadein our <p> tags
$(this).children("p").delay(500).fadeIn(250);
});
});
}
|
export default from './ContextMenu';
|
var class_physics_component =
[
[ "createXmlNode", "class_physics_component.html#a5a2e3761a13d45a4dd38fe3b69253332", null ],
[ "destroyDispatcher", "class_physics_component.html#a3c17f238e0ea725fc91a151591bf9510", null ],
[ "getPosition", "class_physics_component.html#aeee07d4204bae0ff7747f5c0009907a1", null ],
[ "setPosition", "class_physics_component.html#a12d373e7cba22ea2d5925063664fc7e2", null ],
[ "PhysicsSystem", "class_physics_component.html#a6fb7520528fab4a670001f041b872bf2", null ],
[ "myPhysicsSystem", "class_physics_component.html#a975c62b57bcba88f3738edfe308da17b", null ]
]; |
var _ = require('underscore');
var $ = require('jquery'),
Backbone = require('backbone'),
revenueTpl = require('../templates/_entityRevenue.tpl'),
loadingTpl = require('../templates/__loading.tpl');
var config = require('../conf');
Backbone.$ = $;
exports = module.exports = Backbone.View.extend({
el: '#statView',
loadingTemplate: _.template(loadingTpl),
initialize: function(options) {
this.router = options.router;
var page = $(revenueTpl);
var statTemplate = $('#statTemplate', page).html();
this.template = _.template(_.unescape(statTemplate || ''));
this.on('load', this.load, this);
},
events: {
'click .index': 'revenueIndex',
},
load: function() {
var that = this;
this.loaded = true;
this.render();
},
revenueIndex: function(evt){
var id = this.$(evt.currentTarget).parent().attr('id');
this.router.navigate('revenue/index',{trigger: true});
return false;
},
render: function() {
if (!this.loaded) {
this.$el.html(this.loadingTemplate());
} else {
this.$el.html(this.template());
}
return this;
},
}); |
Controllers.controller('VideoController', ['$scope', "$sce", '$routeParams', 'VideoService', function($scope, $sce, $routeParams, VideoService) {
//var videoSrc = "https://github.com/malaba03/testvideo/blob/master/videos/video1.mp4";
var videoSrc = "/videos/"+$routeParams.videoName,
type = "video/"+$routeParams.type,
options = {
'controls' : false,
'autoplay' : false,
'preload' : 'auto',
'width' : '640',
'height': '264',
'data-setup':'{}'
};
$scope.events = [];
$scope.trustSrc = function(src) {
return $sce.trustAsResourceUrl(src);
};
//$scope.videoModel = {src: videoSrc, type: "video/mp4"};
$scope.videoService = new VideoService('video-id', $scope.trustSrc(videoSrc), type, options);
$scope.isPlaying = false;
$scope.play = function(){
$scope.isPlaying = true;
$scope.videoService.player.play();
$scope.events.push({name: "Click Play: video"+videoSrc});
};
$scope.pause = function(){
$scope.videoService.player.pause();
$scope.isPlaying = false;
$scope.events.push({name: "Click Pause: video"+videoSrc});
};
$scope.backward = function(){
var currentTime = $scope.videoService.player.currentTime();
$scope.videoService.player.currentTime(currentTime-5);
$scope.events.push({name: "Click Backward: video"+videoSrc});
};
$scope.forward = function(){
var currentTime = $scope.videoService.player.currentTime();
$scope.videoService.player.currentTime(currentTime+2);
$scope.events.push({name: "Click Forward: video"+videoSrc});
};
}]); |
Space.eventSourcing.Projection.extend('Donations.OrgProjection', {
collections: {
organizations: 'Donations.Organizations'
},
eventSubscriptions() {
return [{
'Donations.OrganizationCreated': this._onOrganizationCreated,
'Donations.LocationAdded': this._onLocationAdded,
'Donations.LocationDetailsChanged': this._onLocationDetailsChanged
}];
},
_onOrganizationCreated(event) {
this.organizations.insert({
_id: event.sourceId.toString(),
adminId: event.adminId.toString(),
name: event.name,
country: event.country.toString(),
contact: {
name: event.contact.name,
email: event.contact.email.toString(),
phone: event.contact.phone
},
locations: []
});
},
_onLocationAdded(event) {
this.organizations.update(event.sourceId.toString(), {
$push: {
locations: this._getPlainLocationDetails(event)
}
});
},
_onLocationDetailsChanged(event) {
let location = {
_id: event.sourceId.toString(),
'locations._id': event.locationId.toString()
};
this.organizations.update(location, {
$set: {
'locations.$': this._getPlainLocationDetails(event)
}
});
},
_getPlainLocationDetails(event) {
return {
_id: event.locationId.toString(),
name: event.name,
address: {
street: event.address.street,
zip: event.address.zip,
city: event.address.city,
country: event.address.country.toString()
},
openingHours: event.openingHours
};
}
});
|
module.exports = require('path').join(__dirname, 'teamcity.js');
|
/**
* @author Rob Taylor [manix84@gmail.com]
*/
define('window/queriesObject', function () {
/**
* Takes the Query/Search String, and parses it into an object.
* @exports window/queriesObject
*
* @return {Object} An object, containing all query keys and values.
*/
var queriesObject = function () {
var query = [],
outputObj = {},
i = 0,
queries;
if (window.location.search) {
queries = window.location.search.substring(1).split('&');
for (; i < queries.length; i++) {
query = queries[i].split('=');
outputObj[query[0]] = query[1] || '';
}
}
return outputObj;
};
return queriesObject;
});
|
'use strict';
const assert = require('assert');
const Browscap = require('../src/index.js');
suite('checking for issue 807. (1 test)', function () {
test('issue-807 ["Mozilla/5.0 (compatible; Orangebot/2.0; support.orangebot@orange.com)"]', function () {
const browscap = new Browscap();
const browser = browscap.getBrowser('Mozilla/5.0 (compatible; Orangebot/2.0; support.orangebot@orange.com)');
assert.strictEqual(browser['Comment'], 'Orangebot', 'Expected actual "Comment" to be \'Orangebot\' (was \'' + browser['Comment'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser'], 'Orangebot', 'Expected actual "Browser" to be \'Orangebot\' (was \'' + browser['Browser'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Type'], 'Bot/Crawler', 'Expected actual "Browser_Type" to be \'Bot/Crawler\' (was \'' + browser['Browser_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Bits'], '0', 'Expected actual "Browser_Bits" to be \'0\' (was \'' + browser['Browser_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Maker'], 'Orange S.A.', 'Expected actual "Browser_Maker" to be \'Orange S.A.\' (was \'' + browser['Browser_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Modus'], 'unknown', 'Expected actual "Browser_Modus" to be \'unknown\' (was \'' + browser['Browser_Modus'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Version'], '2.0', 'Expected actual "Version" to be \'2.0\' (was \'' + browser['Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform'], 'unknown', 'Expected actual "Platform" to be \'unknown\' (was \'' + browser['Platform'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Version'], 'unknown', 'Expected actual "Platform_Version" to be \'unknown\' (was \'' + browser['Platform_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Description'], 'unknown', 'Expected actual "Platform_Description" to be \'unknown\' (was \'' + browser['Platform_Description'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Bits'], '0', 'Expected actual "Platform_Bits" to be \'0\' (was \'' + browser['Platform_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Maker'], 'unknown', 'Expected actual "Platform_Maker" to be \'unknown\' (was \'' + browser['Platform_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Alpha'], false, 'Expected actual "Alpha" to be false (was \'' + browser['Alpha'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Beta'], false, 'Expected actual "Beta" to be false (was \'' + browser['Beta'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Frames'], false, 'Expected actual "Frames" to be false (was \'' + browser['Frames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['IFrames'], false, 'Expected actual "IFrames" to be false (was \'' + browser['IFrames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Tables'], false, 'Expected actual "Tables" to be false (was \'' + browser['Tables'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Cookies'], false, 'Expected actual "Cookies" to be false (was \'' + browser['Cookies'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['JavaScript'], false, 'Expected actual "JavaScript" to be false (was \'' + browser['JavaScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['VBScript'], false, 'Expected actual "VBScript" to be false (was \'' + browser['VBScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['JavaApplets'], false, 'Expected actual "JavaApplets" to be false (was \'' + browser['JavaApplets'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isSyndicationReader'], false, 'Expected actual "isSyndicationReader" to be false (was \'' + browser['isSyndicationReader'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isFake'], false, 'Expected actual "isFake" to be false (was \'' + browser['isFake'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isAnonymized'], false, 'Expected actual "isAnonymized" to be false (was \'' + browser['isAnonymized'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isModified'], false, 'Expected actual "isModified" to be false (was \'' + browser['isModified'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['CssVersion'], '0', 'Expected actual "CssVersion" to be \'0\' (was \'' + browser['CssVersion'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Name'], 'unknown', 'Expected actual "Device_Name" to be \'unknown\' (was \'' + browser['Device_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Maker'], 'unknown', 'Expected actual "Device_Maker" to be \'unknown\' (was \'' + browser['Device_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Type'], 'unknown', 'Expected actual "Device_Type" to be \'unknown\' (was \'' + browser['Device_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Pointing_Method'], 'unknown', 'Expected actual "Device_Pointing_Method" to be \'unknown\' (was \'' + browser['Device_Pointing_Method'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Code_Name'], 'unknown', 'Expected actual "Device_Code_Name" to be \'unknown\' (was \'' + browser['Device_Code_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Brand_Name'], 'unknown', 'Expected actual "Device_Brand_Name" to be \'unknown\' (was \'' + browser['Device_Brand_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Name'], 'unknown', 'Expected actual "RenderingEngine_Name" to be \'unknown\' (was \'' + browser['RenderingEngine_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Version'], 'unknown', 'Expected actual "RenderingEngine_Version" to be \'unknown\' (was \'' + browser['RenderingEngine_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Maker'], 'unknown', 'Expected actual "RenderingEngine_Maker" to be \'unknown\' (was \'' + browser['RenderingEngine_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
});
});
|
'use strict';
var util = require('util');
var fs = require('fs.extra');
var path = require('path');
var yeoman = require('yeoman-generator');
var cheerio = require('cheerio');
var FrontendGenerator = module.exports = function FrontendGenerator(args, options, config) {
yeoman.generators.Base.apply(this, arguments);
this.domUpdate = function domUpdate(html, tagName, content, mode) {
var $ = cheerio.load(html),
container = tagName ? $(tagName) : $.root();
if (content !== undefined) {
if (mode === 'a') {
container.append(content);
} else if (mode === 'p') {
container.prepend(content);
} else if (mode === 'r') {
container.html(content);
} else if (mode === 'd') {
container.remove();
}
return $.html();
} else {
console.error('Please supply valid content to be updated.');
}
};
/**
* Generate a ProcessHtml-handler block.
* Needed for requirejs integration
*
* @param {String} blockType
* @param {String} optimizedPath
* @param {String} filesBlock
* @param {String|Array} searchPath
*/
this.generateRequireBlock = function generateBlock(blockType, optimizedPath, filesBlock, searchPath) {
var blockStart;
var blockEnd;
var blockSearchPath = '';
if (searchPath !== undefined) {
if (util.isArray(searchPath)) {
searchPath = '{' + searchPath.join(',') + '}';
}
blockSearchPath = '(' + searchPath + ')';
}
blockStart = '\n <!-- build:' + blockType + blockSearchPath + ' ' + optimizedPath + ' -->\n';
blockEnd = ' <!-- /build -->\n';
return blockStart + filesBlock + blockEnd;
};
/**
* Append files
* overwrite to add special requirejs block because usemin does not support requirejs anymore
*
* @param {String|Object} htmlOrOptions
* @param {String} fileType
* @param {String} optimizedPath
* @param {Array} sourceFileList
* @param {Object} attrs
* @param {String} searchPath
*/
this.appendFiles = function appendFiles(htmlOrOptions, fileType, optimizedPath, sourceFileList, attrs, searchPath) {
var blocks, updatedContent;
var html = htmlOrOptions;
var files = '';
if (typeof htmlOrOptions === 'object') {
html = htmlOrOptions.html;
fileType = htmlOrOptions.fileType;
optimizedPath = htmlOrOptions.optimizedPath;
sourceFileList = htmlOrOptions.sourceFileList;
attrs = htmlOrOptions.attrs;
searchPath = htmlOrOptions.searchPath;
}
attrs = this.attributes(attrs);
if (fileType === 'require') {
sourceFileList.forEach(function (el) {
files += '<script ' + attrs + ' src="' + el + '"></script>\n';
});
blocks = this.generateRequireBlock('js', optimizedPath, files, searchPath);
updatedContent = this.append(html, '', blocks);
} else if (fileType === 'js' && optimizedPath) {
sourceFileList.forEach(function (el) {
files += '<script ' + attrs + ' src="' + el + '"></script>\n';
});
blocks = this.generateBlock(fileType, optimizedPath, files, searchPath);
updatedContent = this.append(html, '', blocks);
} else if (fileType === 'js' && !optimizedPath) {
sourceFileList.forEach(function (el) {
files += '<script ' + attrs + ' src="' + el + '"></script>\n';
});
updatedContent = this.append(html, '', files);
} else if (fileType === 'css') {
sourceFileList.forEach(function (el) {
files += '<link ' + attrs + ' rel="stylesheet" href="' + el + '">\n';
});
blocks = this.generateBlock('css', optimizedPath, files, searchPath);
updatedContent = this.append(html, '', blocks);
}
// cleanup trailing whitespace
return updatedContent.replace(/[\t ]+$/gm, '');
};
this.indexFile = this.readFileAsString(path.join(this.sourceRoot(), 'index.html'));
this.headerFile = this.readFileAsString(path.join(this.sourceRoot(),'includes', 'head.php'));
this.footerFile = this.readFileAsString(path.join(this.sourceRoot(),'includes', 'footer.php'));
this.mainJsFile = '';
this.skipInstall = options['skip-install'];
this.on('end', function () {
this.installDependencies({ skipInstall: options['skip-install'], callback: function(){
// if using bootstrap, copy icon fonts from bower directory to app
if (this.frameworkSelected === 'bootstrap' && !this.skipInstall) {
var pkg = this.preprocessorSelected === 'sass' ? 'bootstrap-sass-official' : 'bootstrap',
src = this.preprocessorSelected === 'sass' ? path.join(this.destinationRoot(),'app/bower_components/'+pkg+'/assets/fonts') : path.join(this.destinationRoot(),'app/bower_components/'+pkg+'/fonts'),
dest = path.join(this.destinationRoot(),'app/fonts');
fs.copyRecursive(src,dest, function(){});
}
}.bind(this)});
});
this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
this.config.save();
};
util.inherits(FrontendGenerator, yeoman.generators.Base);
FrontendGenerator.prototype.askFor = function askFor() {
var cb = this.async();
// have Yeoman greet the user.
console.log(this.yeoman);
console.log('Out of the box I include HTML5 Boilerplate, jQuery and Modernizr.');
var prompts = [
{
type: 'confirm',
name: 'php2htmlChoice',
message: 'Would you like to convert PHP files to static HTML?',
default: true
},{
type: 'list',
name: 'frameworkChoice',
message: 'Would you like to include a CSS framework?',
choices: [
{
name: 'No Framework',
value: 'noframework'
},
{
name: 'Twitter Bootstrap',
value: 'bootstrap'
},
{
name: 'PureCSS',
value: 'pure'
},
{
name: 'Foundation',
value: 'foundation'
}
]
},
{
type: 'list',
name: 'preprocessorChoice',
message: 'Would you like to use a CSS preprocessor?',
choices: [
{
name: 'No Preprocessor',
value: 'nopreprocessor'
},
{
name: 'Less',
value: 'less'
},
{
name: 'Sass',
value: 'sass'
}
]
},
{
type: 'list',
name: 'loaderChoice',
message: 'Which module loader would you like to use?',
choices: [
{
name: 'RequireJS',
value: 'requirejs',
checked: true
},
{
name: 'Browserify',
value: 'browserify'
}
]
},
{
type: 'checkbox',
name: 'testChoice',
message: 'Which test framework would you like to use?',
choices: [
{
name: 'Mocha',
value: 'mocha',
checked: true
},
{
name: 'Jasmine',
value: 'jasmine'
},
{
name: 'Qunit',
value: 'qunit'
},
{
name: 'DalekJS',
value: 'dalek'
}
]
}
];
function getChoice(props, key, def) {
var choices = props[key] || [],
result = def || null;
for (var i = 0; i < prompts.length; i++) {
var p = prompts[i];
if (p.name === key && p.type === 'list') {
for (var j = 0; j < p.choices.length; j++) {
if (choices.indexOf(p.choices[j].value) !== -1) {
return p.choices[j].value;
}
}
}
}
return result;
}
this.prompt(prompts, function (props) {
// manually deal with the response, get back and store the results.
// we change a bit this way of doing to automatically do this in the self.prompt() method.
this.moduleLoader = getChoice(props,'loaderChoice','requirejs');
this.frameworkSelected = getChoice(props, 'frameworkChoice', 'noframework');
this.preprocessorSelected = getChoice(props, 'preprocessorChoice', 'nopreprocessor');
this.mochaTest = this.jasmineTest = this.qunitTest = this.dalekTest = false;
for (var i in props.testChoice) {
this[props.testChoice[i] + 'Test'] = true;
}
this.layoutChoice = props.layoutChoice;
this.php2htmlChoice = props.php2htmlChoice;
cb();
}.bind(this));
};
// ----------------------------------------------------------------
// Layouts
// ----------------------------------------------------------------
// ----------------------------------------------------------------
FrontendGenerator.prototype.gruntfile = function gruntfile() {
this.template('Gruntfile.js');
};
FrontendGenerator.prototype.packageJSON = function packageJSON() {
this.template('_package.json', 'package.json');
};
FrontendGenerator.prototype.git = function git() {
this.copy('gitignore', '.gitignore');
this.copy('gitattributes', '.gitattributes');
};
FrontendGenerator.prototype.bower = function bower() {
this.copy('bowerrc', '.bowerrc');
this.copy('_bower.json', 'bower.json');
};
FrontendGenerator.prototype.prettifyconfig = function editorConfig() {
};
FrontendGenerator.prototype.h5bp = function h5bp() {
this.copy('404.php', 'app/404.php');
this.copy('robots.txt', 'app/robots.txt');
this.copy('htaccess', 'app/.htaccess');
};
FrontendGenerator.prototype.projectfiles = function projectfiles() {
this.copy('editorconfig', '.editorconfig');
this.copy('jshintrc', '.jshintrc');
this.copy('prettifyrc', '.prettifyrc');
};
FrontendGenerator.prototype.mainStylesheet = function mainStylesheet() {
if(this.preprocessorSelected == 'sass') {
this.copy('_main.scss', 'app/styles/main.scss');
} else if (this.preprocessorSelected == 'less') {
this.copy('_main.less', 'app/styles/main.less');
} else {
this.copy('main.css', 'app/styles/main.css');
}
};
FrontendGenerator.prototype.addLayout = function gruntfile() {
var layoutStr = "<!--yeoman-welcome-->";
if(this.frameworkSelected) {
console.log(this.frameworkSelected +' was chosen');
// a framework was chosen
if(this.frameworkSelected == 'bootstrap'){
layoutStr = this.readFileAsString(path.join(this.sourceRoot(), 'layouts/bootstrap/index.html'));
}else if(this.frameworkSelected == 'pure'){
layoutStr = this.readFileAsString(path.join(this.sourceRoot(), 'layouts/pure/index.html'));
} else if(this.frameworkSelected == 'foundation'){
layoutStr = this.readFileAsString(path.join(this.sourceRoot(), 'layouts/foundation/index.html'));
}
}
// Replace the page logic comment with the layoutString
this.indexFile = this.indexFile.replace("<!--your page logic-->", layoutStr);
};
FrontendGenerator.prototype.browserify = function browserify() {
if (this.moduleLoader !== 'browserify') {
return;
}
this.copy('scripts/'+this.moduleLoader+'/app.'+this.frameworkSelected+'.js','app/scripts/app.js');
this.footerFile = this.appendFiles(this.footerFile, 'js',undefined, ['scripts/main.js']);
// Adds picturefill as separate script
// should be integrated in browserify when https://github.com/scottjehl/picturefill/pull/252 is resolved
this.footerFile = this.appendFiles(this.footerFile, 'js','scripts/vendor/picturefill.js', ['bower_components/picturefill/dist/picturefill.js']);
};
FrontendGenerator.prototype.requirejs = function requirejs() {
if (this.moduleLoader !== 'requirejs') {
return;
}
var requiredScripts = ['app', 'jquery','picturefill'];
var inlineRequire = '';
var logCmd = '';
var templateLibraryPath;
var templateLibraryShim;
if(this.frameworkSelected === 'bootstrap') {
requiredScripts.push('bootstrap');
logCmd = ' log.debug(\' + Bootstrap \', \'3.0.0\');';
if (this.preprocessorSelected === 'sass') {
templateLibraryPath = ',\n bootstrap: \'../bower_components/bootstrap-sass-official/assets/javascripts/bootstrap\'\n },';
} else {
templateLibraryPath = ',\n bootstrap: \'../bower_components/bootstrap/dist/js/bootstrap\'\n },';
}
templateLibraryShim = ' bootstrap: {deps: [\'jquery\'], exports: \'jquery\'}';
} else if(this.frameworkSelected === 'foundation') {
requiredScripts.push('foundation/foundation');
logCmd = ' log.debug(\' + Foundation %s\', Foundation.version);';
templateLibraryPath = ',\n foundation: \'../bower_components/foundation/js/foundation\'\n },';
templateLibraryShim = [
' \'foundation/foundation\' : { deps: [\'jquery\'], exports: \'Foundation\' },',
' \'foundation/foundation.alerts\': { deps: [\'jquery\'], exports: \'Foundation.libs.alerts\' },',
' \'foundation/foundation.clearing\': { deps: [\'jquery\'], exports: \'Foundation.libs.clearing\' },',
' \'foundation/foundation.cookie\': { deps: [\'jquery\'], exports: \'Foundation.libs.cookie\' },',
' \'foundation/foundation.dropdown\': { deps: [\'jquery\'], exports: \'Foundation.libs.dropdown\' },',
' \'foundation/foundation.forms\': { deps: [\'jquery\'], exports: \'Foundation.libs.forms\' },',
' \'foundation/foundation.joyride\': { deps: [\'jquery\'], exports: \'Foundation.libs.joyride\' },',
' \'foundation/foundation.magellan\': { deps: [\'jquery\'], exports: \'Foundation.libs.magellan\' },',
' \'foundation/foundation.orbit\': { deps: [\'jquery\'], exports: \'Foundation.libs.orbit\' },',
' \'foundation/foundation.placeholder\': { deps: [\'jquery\'], exports: \'Foundation.libs.placeholder\' },',
' \'foundation/foundation.reveal\': { deps: [\'jquery\'], exports: \'Foundation.libs.reveal\' },',
' \'foundation/foundation.section\': { deps: [\'jquery\'], exports: \'Foundation.libs.section\' },',
' \'foundation/foundation.tooltips\': { deps: [\'jquery\'], exports: \'Foundation.libs.tooltips\' },',
' \'foundation/foundation.topbar\': { deps: [\'jquery\'], exports: \'Foundation.libs.topbar\' }'
].join('\n');
} else {
templateLibraryShim = '';
templateLibraryPath = '\n },';
}
var requiredScriptsString = '[';
for(var i = 0; i < requiredScripts.length; i++) {
requiredScriptsString += '\''+requiredScripts[i]+'\'';
if((i+1) < requiredScripts.length) {
requiredScriptsString += ', ';
}
}
requiredScriptsString += ']';
this.footerFile = this.appendFiles(this.footerFile, 'require','scripts/main.js', ['scripts/config.js','bower_components/requirejs/require.js'], {
'data-main': 'main'
});
// add a basic config file, rest wiull be done by grunt bower task
this.write('app/scripts/config.js',[
'/* jshint -W098,-W079 */',
'var require = {',
' baseUrl: \'../bower_components\',',
' paths: {',
' main: \'../scripts/main\',',
' app: \'../scripts/app\',',
' component: \'../scripts/component\',',
' library: \'../scripts/library\',',
' jquery: \'jquery/dist/jquery\',',
' loglevel: \'loglevel/dist/loglevel.min\''+templateLibraryPath,
' shim: {',
templateLibraryShim,
' },',
' packages: [',
' {',
' name: \'picturefill\',',
' main: \'dist/picturefill.js\',',
' location: \'picturefill\'',
' }',
' ]',
'};'
].join('\n'));
// add a basic amd module
this.write('app/scripts/app.js', [
'/*global define'+((this.frameworkSelected === 'foundation')?', Foundation':'')+' */',
'define(function (require) {',
' \'use strict\';\n',
' // load dependencies',
' var $ = require(\'jquery\'),',
' log = require(\'loglevel\'),',
' components = {},',
' self = {};\n',
((this.frameworkSelected === 'foundation')?' require(\'foundation/foundation\');\n':
((this.frameworkSelected === 'bootstrap')?' require(\'bootstrap\');\n':'')),
' components.dummy = require(\'component/dummy\');\n',
' // API methods',
' $.extend(self, {\n',
' /**',
' * App initialization',
' */',
' init: function init() {',
' log.setLevel(0);',
' log.debug(\'Running jQuery %s\', $().jquery);',
logCmd,
' log.debug(\'\');',
' log.debug(\'Initializing components ...\');\n',
' for (var key in components) {',
' try {',
' components[key].init();',
' } catch (err) {',
' log.debug(\'initialization failed for component \\\'\' + key + \'\\\'\');',
' log.error(err);',
' }',
' }',
' }',
' });\n',
' return self;',
'});'
].join('\n'));
this.mainJsFile = [
'require(' + requiredScriptsString + ', function (app) {',
' \'use strict\';',
' // use app here',
' app.init();',
'});'
].join('\n');
};
FrontendGenerator.prototype.writeIndex = function writeIndex() {
// prepare default content text
var defaults = ['HTML5 Boilerplate'];
var titleClass = '';
if(this.frameworkSelected == 'pure') {
titleClass = 'splash-head';
}
var contentText = [
' <h1 class="'+titleClass+'">\'Allo, \'Allo!</h1>',
' <p>You now have</p>',
' <ul>'
];
// append styles
// with preprocessor sass bootstrap.scss or foundation.scss get included in main.scss file
// with preprocessor less bootstrap.less gets included
if(this.preprocessorSelected == 'sass' && this.frameworkSelected == 'foundation' ) {
this.headerFile = this.appendStyles(this.headerFile, 'styles/main.css', [
'styles/main.css'
]);
defaults.push('Foundation');
} else if(this.preprocessorSelected == 'sass' && this.frameworkSelected == 'bootstrap') {
this.headerFile = this.appendStyles(this.headerFile, 'styles/main.css', [
'styles/main.css'
]);
defaults.push('Bootstrap');
} else if (this.preprocessorSelected == 'less' && this.frameworkSelected == 'bootstrap') {
this.headerFile = this.appendStyles(this.headerFile, 'styles/main.css', [
'styles/main.css'
]);
defaults.push('Bootstrap');
} else if(this.frameworkSelected == 'bootstrap') {
// Add Twitter Bootstrap scripts
this.headerFile = this.appendStyles(this.headerFile, 'styles/main.css', [
'bower_components/bootstrap/dist/css/bootstrap.css','styles/main.css'
]);
defaults.push('Bootstrap');
} else if(this.frameworkSelected == 'pure') {
this.copy('layouts/pure/stylesheets/marketing.css', 'app/styles/marketing.css');
this.headerFile = this.appendStyles(this.headerFile, 'styles/main.css', [
'styles/marketing.css','bower_components/pure/pure-min.css','styles/main.css'
]);
defaults.push('Pure CSS');
} else if(this.frameworkSelected == 'foundation') {
this.headerFile = this.appendStyles(this.headerFile, 'styles/main.css', [
'bower_components/bower-foundation-css/foundation.min.css','styles/main.css'
]);
defaults.push('Foundation');
} else {
this.headerFile = this.appendStyles(this.headerFile, 'styles/main.css', [
'styles/main.css'
]);
}
defaults.push('RequireJS');
// iterate over defaults and create content string
defaults.forEach(function (el) {
contentText.push(' <li>' + el +'</li>');
});
contentText = contentText.concat([
' </ul>',
' <p>installed.</p>',
' <h3>Enjoy coding!</h3>',
''
]);
// append the default content
contentText = contentText.join('\n');
if(this.frameworkSelected == 'noframework') {
contentText = '<div class="hero-unit">\n' + contentText+'</div>\n';
}
this.indexFile = this.indexFile.replace('<!--yeoman-welcome-->', contentText);
};
FrontendGenerator.prototype.addTests = function gruntfile() {
this.mkdir('app/test');
// jasmine testframework selected
if (this.jasmineTest) {
this.directory('test/'+this.moduleLoader+'/jasmine', 'app/test/jasmine');
}
// qunit testframework selected
if (this.qunitTest) {
this.directory('test/'+this.moduleLoader+'/qunit', 'app/test/qunit');
this.copy('test/'+this.moduleLoader+'/qunit.html', 'app/test/qunit.html');
}
// mocha selected
if (this.mochaTest) {
this.directory('test/'+this.moduleLoader+'/mocha', 'app/test/mocha');
this.copy('test/'+this.moduleLoader+'/mocha.html', 'app/test/mocha.html');
}
// dalek selected
if (this.dalekTest) {
this.directory('test/'+this.moduleLoader+'/dalek', 'app/test/dalek');
}
};
FrontendGenerator.prototype.app = function app() {
this.config.save();
this.mkdir('app');
this.mkdir('app/scripts');
this.mkdir('app/scripts/component');
this.copy('scripts/'+this.moduleLoader+'/dummy.js','app/scripts/component/dummy.js');
this.mkdir('app/scripts/library');
this.copy('scripts/'+this.moduleLoader+'/polyfills.js','app/scripts/library/polyfills.js');
// bootstrap variable tweaking
if (this.preprocessorSelected === 'less' && this.frameworkSelected === 'bootstrap') {
this.copy('less/bootstrap.less','app/styles/bootstrap.less');
this.copy('less/variables.less','app/styles/variables.less');
}
// bootstrap variable tweaking
if (this.preprocessorSelected === 'sass' && (this.frameworkSelected === 'bootstrap' || this.frameworkSelected === 'foundation')) {
this.template('scss/variables.scss', 'app/styles/variables.scss');
}
this.mkdir('app/images');
this.write('app/index.php', this.indexFile);
this.write('app/includes/head.php', this.headerFile);
this.write('app/includes/footer.php', this.footerFile);
this.write('app/scripts/main.js', this.mainJsFile);
};
|
GENTICS.Aloha.Help = new GENTICS.Aloha.Plugin('com.gentics.aloha.plugins.Help');
GENTICS.Aloha.Help.languages = ['en', 'ru'];
GENTICS.Aloha.Help.url = "https://github.com/alohaeditor/Aloha-Editor/wiki";
GENTICS.Aloha.Help.width = 640;
GENTICS.Aloha.Help.height = 480;
GENTICS.Aloha.Help.init = function () {
var that = this;
if (GENTICS.Aloha.Help.settings.url != undefined) {
GENTICS.Aloha.Help.url = GENTICS.Aloha.Help.settings.url
}
if (GENTICS.Aloha.Help.settings.width != undefined) {
GENTICS.Aloha.Help.width = GENTICS.Aloha.Help.settings.width
}
if (GENTICS.Aloha.Help.settings.height != undefined) {
GENTICS.Aloha.Help.height = GENTICS.Aloha.Help.settings.height
}
var stylePath = GENTICS.Aloha.settings.base + '/plugins/com.gentics.aloha.plugins.Help/css/Help.css';
jQuery('<link rel="stylesheet" />').attr('href', stylePath).appendTo('head');
var helpButton = new GENTICS.Aloha.ui.Button({
"iconClass" : "GENTICS_button_help",
"size" : "small",
"onclick": function () {
new Ext.Window({
title: 'Help',
width: GENTICS.Aloha.Help.width,
height: GENTICS.Aloha.Help.height,
html: '<iframe style="overflow:auto;width:100%;height:100%;" frameborder="0" src="'+ GENTICS.Aloha.Help.url +'"></iframe>',
plain: true,
style: {zIndex: '11111 !important'},
shadow: false,
border: false
}).show();
}
});
GENTICS.Aloha.FloatingMenu.addButton(
"GENTICS.Aloha.continuoustext",
helpButton,
that.i18n("floatingmenu.tab.format"), 2
);
}; |
import React, { Component } from 'react'
import { connect } from 'react-redux'
import {Link} from 'react-router-dom'
import Images from '../widget/images'
import Button from '../widget/button'
import Icon from '../widget/icon'
import { setInactiveLoading, setActiveLoading } from '../../action/LoadingAction'
import { setActivePages } from '../../action/MenuAction'
const mapStateToProps = (state, ownProps) => {
return {
loading : state.LoadingReducers.loading,
menu : state.MenuReducers.page,
}
}
const mapDispatchToProps = (dispatch) => {
return {
inactive : () => dispatch(setInactiveLoading()),
active : () => dispatch(setActiveLoading()),
setActive : (key) => dispatch(setActivePages(key))
}
}
@connect(mapStateToProps, mapDispatchToProps)
export default class MainComponent extends Component {
static contextTypes = {
router: React.PropTypes.object.isRequired
};
constructor(props, context) {
super(props, context)
this.state = {
classDiv : `great ${this.props.loading ? ' animated fadeOut' : ' animated fadeIn' }`
}
}
componentWillMount() {
setTimeout(() => {
this.props.inactive()
}, 1000)
this.props.setActive(0)
}
componentDidMount() {
document.title = 'Main Pages'
document.body.removeAttribute("style");
let style = this.props.menu[0].style
for(let a in style) {
document.body.style[a] = style[a]
}
if(this.props.loading == false) {
setTimeout(() => {
this.setState({classDiv : 'great animated fadeIn'})
}, 500)
} else {
this.setState({classDiv : 'great animated fadeOut'})
}
}
componentWillUnmount() {
this.props.active()
}
componentWillReceiveProps(next) {
if(next.loading == false) {
setTimeout(() => {
this.setState({classDiv : 'great animated fadeIn'})
}, 500)
} else {
this.setState({classDiv : 'great animated fadeOut'})
}
}
action(url) {
this.context.router.history.push(url)
}
render() {
return (
<div className={this.state.classDiv}>
<Images src='coffee-vector.png' class='logo inline float-left' responsive='true'/>
<div className='content-text'>
<h1>Coffee</h1>
<h3>I'd rather take coffee than compliments just now.</h3>
<Button type='border radius' onClick={this.action.bind(this, '/article')}
color='secondary' mode='link'>
<Icon type='material' color='#fff' icon='style'></Icon> Look Article
</Button>
</div>
</div>
)
}
} |
import React from 'react'
import { randomColorFor } from '../../utils.js'
import ImageLoadMixin from '../../lib/imageLoadMixin.js'
const ResourceImage = React.createClass({
mixins: [ImageLoadMixin],
propTypes () {
return {
resource: React.PropTypes.object.isRequired
}
},
getInitialState () {
return {
showPlaceholder: true
}
},
componentDidMount () {
// If depiction url loads, hide placeholder
this.loadImage(this.props.resource.depiction, (img) => this.setState({ showPlaceholder: false }))
},
render () {
var style = { position: 'relative', backgroundSize: 'cover' }
var styleLionColor = { color: randomColorFor(this.props.resource.uri) }
if (this.props.resource.depiction) {
style = { background: 'url(' + this.props.resource.depiction + ')', position: 'relative' }
}
var placeholderImage = this.state.showPlaceholder ? <span style={styleLionColor} className='lg-icon nypl-icon-logo-mark agent-listing-image-placeholder'></span> : null
return <div className={this.props.className} style={style}>{placeholderImage}</div>
}
})
export default ResourceImage
|
version https://git-lfs.github.com/spec/v1
oid sha256:3ab14b97c430368f9d0534e7f9284830617bc2287c4245f29b159ef3686cbc5b
size 364
|
/*
* grunt-mcompile
* https://github.com/JohnCashBB/grunt-mcompile
*
* Copyright (c) 2013 John Cashmore
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp','dist'],
},
// Configuration to be run (and then tested).
mcompile: {
testFiles: {
options: {
templateRoot: 'test/',
},
files: {
'tmp/': ['test/testfiles/test.html'],
},
},
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js'],
},
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'mcompile', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test']);
};
|
/**
* User model schema
*
* @author NullDivision
* @version 0.1.0
* @flow
*/
import mongoose from 'mongoose';
const USER_SCHEMA = new mongoose.Schema({name: String, role: {type: String, enum: ['ADMIN', 'USER']}, skills: []});
export default mongoose.model('User', USER_SCHEMA);
|
'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import _ from 'underscore';
import moment from 'moment';
import { history_views } from './globals';
import { Form, FormMixin, Input } from '../libs/bootstrap/form';
import { Panel } from '../libs/bootstrap/panel';
import * as curator from './curator';
var DEFAULT_VALUE = module.exports.DEFAULT_VALUE = 'Not Assessed';
var experimentalTypes = [
'Biochemical Function',
'Protein Interactions',
'Expression',
'Functional Alteration',
'Model Systems',
'Rescue'
];
// Object to track and maintain a single assessment. If you pass null/undefined in 'assessment',
// provide all parameters from 'gdm' and after to properly initialize new assessment, if possible.
class AssessmentTracker {
constructor(assessment, user, evidenceType) {
this.original = assessment ? _.clone(assessment) : null; // Original assessment -- the existing one for a parent object
this.updated = null; // Updated assessment that's been saved to DB.
this.type = assessment ? assessment.evidence_type : evidenceType;
this.user = user; // User object for currently logged-in user.
this.currentVal = assessment ? assessment.value : DEFAULT_VALUE;
}
// Does this assessment show it has been assessed?
isAssessed() {
return !!this.original && this.original.value !== DEFAULT_VALUE;
}
// Get the current (non-saved) value of the assessment; normally from the page's assessment form
getCurrentVal() {
return this.currentVal;
}
// Set the current (non-saved) value of the assessment; normally from the page's assessment form.
// Automatically called when the component sets the current state of the assessment value on
// the assessment form's value change.
setCurrentVal(value) {
this.currentVal = value;
}
}
module.exports.AssessmentTracker = AssessmentTracker;
// Mixin to handle React states for assessments
var AssessmentMixin = module.exports.AssessmentMixin = {
// Do not call; called by React.
getInitialState: function() {
return {
currentAssessmentVal: '' // Currently chosen assessment value in the form
};
},
// Sets the current component's assessment value state. Call at load and when assessment form value changes.
// Also assigns the value to the given assessment object. If no value's given; then the current value
// is taken from the given assessment object.
setAssessmentValue: function(assessmentTracker, value) {
if (!value) {
// No value given; get it from the given assessment object
value = assessmentTracker.getCurrentVal();
} else {
// There was a value given; assign it to the given assessment object in addition to setting
// the component state.
assessmentTracker.setCurrentVal(value);
}
// Set the component state to cause a rerender
this.setState({currentAssessmentVal: value});
},
// When the user changes the assessment value, this gets called
updateAssessmentValue: function(assessmentTracker, value) {
this.setAssessmentValue(assessmentTracker, value);
},
// Write the assessment for the given pathogenicity to the DB, and pass the new assessment in the promise, along
// With a boolean indicating if this is a new assessment or if we updated one. If we don't write an assessment
// (either because we had already written the assessment, and the new assessment's value is no different; or
// because we haven't written an assessment, and the current assessment's value is default), the the promise has
// a null assessment.
// For new assessments, pass in the assessment tracking object, the current GDM object, or null if you know you
// have an assessment already and want to use its existing GDM reference. Also pass in the current evidence object.
// If you don't yet have it, pass nothing or null, but make sure you update with that later. If you want to write
// an existing assessment, pass that in the 'assessment' parameter. This is useful for when you've written the
// assessment without an evidence_id, but now have it. In that case, pass the assessment tracker, null for the
// GDM (use the existing one), the evidence object, and the assessment object to write with the new evidence ID.
saveAssessment: function(assessmentTracker, gdmUuid, evidenceUuid, assessment, historyLabel) {
// Flatten the original assessment if any; will modify with updated values
//var newAssessment = assessment ? curator.flatten(assessment) : (assessmentTracker.original ? curator.flatten(assessmentTracker.original, 'assessment') : {});
var newAssessment = assessment ? curator.flatten(assessment) : (assessmentTracker.original ? curator.flatten(assessmentTracker.original, 'assessment') : {});
newAssessment.value = assessmentTracker.currentVal;
if (evidenceUuid) {
newAssessment.evidence_id = evidenceUuid;
}
if (gdmUuid) {
newAssessment.evidence_gdm = gdmUuid;
}
newAssessment.evidence_type = assessmentTracker.type;
newAssessment.active = true;
// Start a write of the record to the DB, returning a promise object with:
// assessment: fleshed-out assessment as written to the DB.
// update: true if an existing object was updated, false if a new object was written.
return new Promise((resolve, reject) => {
var assessmentPromise;
if (assessment || (assessmentTracker.original && (newAssessment.value !== assessmentTracker.original.value))) {
var assessmentUuid = assessment ? assessment.uuid : assessmentTracker.original.uuid;
// Updating an existing assessment, and the value of the assessment has changed
assessmentPromise = this.putRestData('/assessments/' + assessmentUuid, newAssessment).then(data => {
return Promise.resolve({assessment: data['@graph'][0], update: true});
});
} else if (!assessmentTracker.original && newAssessment.value !== DEFAULT_VALUE) {
// New assessment and form has non-default value; write it to the DB.
assessmentPromise = this.postRestData('/assessments/', newAssessment).then(data => {
return Promise.resolve({assessment: data['@graph'][0], update: false});
});
} else {
// Not writing an assessment
assessmentPromise = Promise.resolve({assessment: null, update: false});
}
// Pass to the next THEN, with null if we didn't write an assessment
resolve(assessmentPromise);
});
},
saveAssessmentHistory: function(assessment, gdm, evidence, update) {
var meta;
if (!assessment) {
return Promise.resolve(null);
}
if (experimentalTypes.indexOf(assessment.evidence_type) >= 0) {
// Experimental assessment
meta = {
assessment: {
operation: 'experimental',
value: assessment.value,
experimental: evidence['@id']
}
};
} else if (assessment.evidence_type === 'Segregation') {
// Family segregation assessment
meta = {
assessment: {
operation: 'segregation',
value: assessment.value,
family: evidence['@id']
}
};
} else if (assessment.evidence_type === 'Pathogenicity') {
// Variant pathogenicity assessment
var variant = (typeof evidence.variant === 'string') ? evidence.variant : evidence.variant['@id'];
meta = {
assessment: {
operation: 'pathogenicity',
value: assessment.value,
gdm: gdm['@id'],
pathogenicity: evidence['@id'],
variant: variant
}
};
} else {
// Something's gone wrong
}
// Write assessment history if ready
if (meta) {
return this.recordHistory(update ? 'modify' : 'add', assessment, meta);
}
return Promise.resolve(null);
}
};
var AssessmentPanel = module.exports.AssessmentPanel = createReactClass({
mixins: [FormMixin],
propTypes: {
ownerNotAssessed: PropTypes.bool, // true if evidence assessed already by its creator
noSeg: PropTypes.bool, // true if evidence is family and there is no segregation data exist.
assessmentTracker: PropTypes.object, // Current value of assessment
//disabled: PropTypes.bool, // TRUE to make assessment dropdown disabled; FALSE to enable it (default)
panelTitle: PropTypes.string, // Title of Assessment panel; 'Assessment' default
label: PropTypes.string, // Label for dropdown; 'Assessment' default
note: PropTypes.oneOfType([ // Note to display below the dropdown
PropTypes.string,
PropTypes.object
]),
updateValue: PropTypes.func.isRequired, // Parent function to call when dropdown changes
assessmentSubmit: PropTypes.func, // Function to call when Save button is clicked; This prop's existence makes the Save button exist
disableDefault: PropTypes.bool, // TRUE to disable the Default (Not Assessed) item
submitBusy: PropTypes.bool, // TRUE while the form submit is running
accordion: PropTypes.bool, // True if the panel should part of an openable accordion
open: PropTypes.bool, // True if the panel should be an openable panel
updateMsg: PropTypes.string // String to display by the Update button if desired
},
componentDidMount: function() {
if (this.props.assessmentTracker && this.props.assessmentTracker.currentVal) {
this.refs.assessment.value = this.props.assessmentTracker.currentVal;
}
},
componentWillReceiveProps: function(nextProps) {
if (this.refs.assessment && nextProps.assessmentTracker && nextProps.assessmentTracker.currentVal == DEFAULT_VALUE) {
this.refs.assessment.resetValue();
}
},
// Called when the dropdown value changes
handleChange: function(assessmentTracker, e) {
if (this.refs.assessment) {
var value = this.refs.assessment.getValue();
this.props.updateValue(assessmentTracker, value);
}
},
render: function() {
var panelTitle = this.props.panelTitle ? this.props.panelTitle : 'Assessment';
var label = this.props.label ? this.props.label : 'Assessment';
//var disabled = (this.props.disabled === true || this.props.disabled === false) ? this.props.disabled : false;
//var disabled = this.props.disabled;
var noSeg = this.props.noSeg;
var value = this.props.assessmentTracker && this.props.assessmentTracker.currentVal ? this.props.assessmentTracker.currentVal : DEFAULT_VALUE;
var ownerNotAssessed = this.props.ownerNotAssessed;
var submitErrClass = 'submit-info pull-right';
//var disable_note_base = 'The option to assess this evidence is not available since ';
//var disable_note_noseg = 'the curator who created it has not yet assessed on it';
//var disbale_note_owner = 'no segregation data entered';
return (
<div>
{this.props.assessmentTracker ?
<Panel title={panelTitle} accordion={this.props.accordion} open={this.props.open}>
<div className="row">
{ ownerNotAssessed ?
<p className="alert alert-info">
The option to assess this evidence does not currently exist since the curator who created it has not yet assessed on it.
</p>
: ( noSeg ?
<p className="alert alert-info">
The option to assess segregation is not available until some segregation data has been entered.
</p>
: null)
}
</div>
<div className="row">
{noSeg ?
<Input type="select" ref="assessment" label={label + ':'} value={value} defaultValue={DEFAULT_VALUE}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputDisabled={true}>
<option value={DEFAULT_VALUE}>Not Assessed</option>
</Input>
:
<Input type="select" ref="assessment" label={label + ':'} value={value} defaultValue={value} handleChange={this.handleChange.bind(null, this.props.assessmentTracker)}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputDisabled={ownerNotAssessed ? true : false}>
<option value={DEFAULT_VALUE} disabled={this.props.disableDefault}>Not Assessed</option>
<option disabled="disabled"></option>
<option value="Supports">Supports</option>
<option value="Review">Review</option>
<option value="Contradicts">Contradicts</option>
</Input>
}
{this.props.note ?
<div className="col-sm-7 col-sm-offset-5">{this.props.note}</div>
: null}
</div>
{this.props.assessmentSubmit ?
<div className="curation-submit clearfix">
<Input type="button" inputClassName="btn-primary pull-right" clickHandler={this.props.assessmentSubmit} title="Update" submitBusy={this.props.submitBusy} inputDisabled={noSeg || ownerNotAssessed ? true : false} />
{this.props.updateMsg ?
<div className="submit-info pull-right">{this.props.updateMsg}</div>
: null}
</div>
: null}
</Panel>
: null}
</div>
);
}
});
// Display a history item for adding or or modifying an assessment
var AssessmentAddModHistory = createReactClass({
propTypes: {
history: PropTypes.object.isRequired, // History object
user: PropTypes.object // User session session ? '&user=' + session.user_properties.uuid : ''
},
render: function() {
var history = this.props.history;
var assessment = history.primary;
var assessmentMeta = history.meta.assessment;
var assessmentRender = null;
switch (assessmentMeta.operation) {
case 'pathogenicity':
var gdm = assessmentMeta.gdm;
var pathogenicity = assessmentMeta.pathogenicity;
var variant = assessmentMeta.variant;
var variantId = variant.clinvarVariantId ? variant.clinvarVariantId : variant.otherDescription;
var user = this.props.user;
var pathogenicityUri = '/variant-curation/?all&gdm=' + gdm.uuid + '&variant=' + variant.uuid + '&pathogenicity=' + pathogenicity.uuid + (user ? '&user=' + user.uuid : '');
assessmentRender = (
<div>
<span>Variant <a href={pathogenicityUri}>{variantId}</a> pathogenicity assessed as <strong>{assessmentMeta.value}</strong></span>
<span>; {moment(history.date_created).format("YYYY MMM DD, h:mm a")}</span>
</div>
);
break;
case 'segregation':
var family = assessmentMeta.family;
assessmentRender = (
<div>
<span>Family <a href={family['@id']}>{family.label}</a> segregation assessed as <strong>{assessmentMeta.value}</strong></span>
<span>; {moment(history.date_created).format("YYYY MMM DD, h:mm a")}</span>
</div>
);
break;
case 'experimental':
var experimental = assessmentMeta.experimental;
assessmentRender = (
<div>
<span>Experimental data <a href={experimental['@id']}>{experimental.label}</a> assessed as <strong>{assessmentMeta.value}</strong></span>
<span>; {moment(history.date_created).format("YYYY MMM DD, h:mm a")}</span>
</div>
);
break;
default:
break;
}
return assessmentRender;
}
});
history_views.register(AssessmentAddModHistory, 'assessment', 'add');
history_views.register(AssessmentAddModHistory, 'assessment', 'modify');
// Display a history item for deleting an assessment
var AssessmentDeleteHistory = createReactClass({
render: function() {
return <div>ASSESSMENTYDELETE</div>;
}
});
history_views.register(AssessmentDeleteHistory, 'assessment', 'delete');
// Return the assessment from the given array of assessments that's owned by the curator with the
// given UUID. The returned assessment is a clone of the original object, so it can be modified
// without side effects.
module.exports.userAssessment = function(assessments, curatorUuid) {
if (curatorUuid) {
return _.chain(assessments).find(function(assessment) {
return assessment.submitted_by.uuid === curatorUuid;
}).clone().value();
}
return null;
};
module.exports.othersAssessed = function(assessments, curatorUuid) {
// See if others have assessed
return !!_(assessments).find(function(assessment) {
return (assessment.submitted_by.uuid !== curatorUuid) && assessment.value !== DEFAULT_VALUE;
});
};
|
export const bindToMinMax = (value, min, max) => Math.min(Math.max(value, min), max);
export const parseValue = (value, min, max) => bindToMinMax(toNumber(value), min, max);
export const toNumber = (rawNumber) => {
let number = parseFloat(rawNumber);
if (isNaN(number) || !isFinite(number)) {
number = 0;
}
return number;
};
|
const path = require('path')
const indexController = {
_init (pathResolver = path) {
this.indexFilePath = pathResolver.join(__dirname, '..', '..', 'client', 'dist', 'index.html')
return this
},
getIndexPage (req, res) {
res.sendFile(this.indexFilePath)
}
}
module.exports = indexController
|
'use strict';
var value = require('../../object/valid-value'),
contains = require('./contains'),
byLength = require('./_compare-by-length'),
filter = Array.prototype.filter,
push = Array.prototype.push,
slice = Array.prototype.slice;
module.exports = function () /*…list*/{
var lists;
if (!arguments.length) slice.call(this);
push.apply(lists = [this], arguments);
lists.forEach(value);
lists.sort(byLength);
return lists.reduce(function (a, b) {
return filter.call(a, function (x) {
return contains.call(b, x);
});
});
};
//# sourceMappingURL=intersection-compiled.js.map |
//~ name a672
alert(a672);
//~ component a673.js
|
"use strict";
System.register(["foo", "foo-bar", "./directory/foo-bar"], function (_export) {
var foo, foo2, bar, bar2, test2;
return {
setters: [function (_foo) {
foo = _foo["default"];
foo2 = _foo;
bar = _foo.bar;
bar2 = _foo.foo;
}, function (_fooBar) {}, function (_directoryFooBar) {}],
execute: function () {
_export("test", test);
test2 = _export("test2", 5);
_export("default", test);
}
};
}); |
define(['jquery', 'underscore', 'backbone', 'text!templates/place.html', 'models/alert', 'views/utils/progress'],
function( $ , _ , Backbone , placeTpl, Alert, ProgressView ){
var PlaceView = Backbone.View.extend({
tagname: 'div',
className: 'row-fluid',
template: _.template( placeTpl ),
initialize: function() {
this.progressView = new ProgressView( {model: new Alert({id: 'place', status: 'progress', msg: 'Loading place...'}) } );
},
render: function(){
if(this.progressView) {
this.progressView.remove();
delete this.progressView;
}
this.$el.html( this.template( this.model.toJSON() ));
return this;
}
});
return PlaceView;
}); |
'use strict';
angular.module('searchResults').directive('searchResults', function(){
return {
restrict: "E",
templateUrl: 'app/search_results/search_results.html'
}
}); |
var group__alchemy__sem =
[
[ "RT_SEM_INFO", "structRT__SEM__INFO.html", [
[ "count", "structRT__SEM__INFO.html#a0b0e81f66b4e936c603f18bf9641a24b", null ],
[ "name", "structRT__SEM__INFO.html#a661011cc10b4fabf562b8ddd92d5dd46", null ],
[ "nwaiters", "structRT__SEM__INFO.html#a456c1a4a5b4c2e192e74b23b79993e71", null ]
] ],
[ "S_PRIO", "group__alchemy__sem.html#gaa156922a223af72f82168d17e844488c", null ],
[ "rt_sem_bind", "group__alchemy__sem.html#ga1520b55854f94b99852d24d1cbd0b29d", null ],
[ "rt_sem_broadcast", "group__alchemy__sem.html#ga4a8963240e68d164a2e5bb148da44fbc", null ],
[ "rt_sem_create", "group__alchemy__sem.html#gaba36e3ac8972ea74feb60640e58d1ceb", null ],
[ "rt_sem_delete", "group__alchemy__sem.html#gaa14cefc4dae46a7c95859e7fe46df888", null ],
[ "rt_sem_inquire", "group__alchemy__sem.html#ga48235bfa78df58a71d7a38582898cb07", null ],
[ "rt_sem_p", "group__alchemy__sem.html#gadd299dfe4a53194870bf4e158ca89d1f", null ],
[ "rt_sem_p_timed", "group__alchemy__sem.html#gabe37d9f5900d80cdb5f729050b74482d", null ],
[ "rt_sem_p_until", "group__alchemy__sem.html#gac481c1f1a2184a998deb2110f2c5b04d", null ],
[ "rt_sem_unbind", "group__alchemy__sem.html#ga851cc0b485d43b52f580f75c72afe2a3", null ],
[ "rt_sem_v", "group__alchemy__sem.html#gaa5a7927862a511a27741223e08e48270", null ]
]; |
require("ember-handlebars/ext");
require("ember-views/views/view");
require("ember-handlebars/controls/text_support");
/**
@module ember
@submodule ember-handlebars
*/
var get = Ember.get, set = Ember.set;
/**
The internal class used to create textarea element when the `{{textarea}}`
helper is used.
See [handlebars.helpers.textarea](/api/classes/Ember.Handlebars.helpers.html#method_textarea) for usage details.
## Layout and LayoutName properties
Because HTML `textarea` elements do not contain inner HTML the `layout` and
`layoutName` properties will not be applied. See [Ember.View](/api/classes/Ember.View.html)'s
layout section for more information.
@class TextArea
@namespace Ember
@extends Ember.Component
@uses Ember.TextSupport
*/
Ember.TextArea = Ember.Component.extend(Ember.TextSupport, {
classNames: ['ember-text-area'],
tagName: "textarea",
attributeBindings: ['rows', 'cols', 'name'],
rows: null,
cols: null,
_updateElementValue: Ember.observer(function() {
// We do this check so cursor position doesn't get affected in IE
var value = get(this, 'value'),
$el = this.$();
if ($el && value !== $el.val()) {
$el.val(value);
}
}, 'value'),
init: function() {
this._super();
this.on("didInsertElement", this, this._updateElementValue);
}
});
|
import invariant from 'invariant';
import { Collection } from 'marsdb';
import OAuthLoginManager from './OAuthLoginManager';
import BasicLoginManager from './BasicLoginManager';
import AccountManager from './AccountManager';
// Internals
let _oauthManager = null;
let _basicManager = null;
let _accManager = null;
let _usersCollection = null;
/**
* Configure accounts support for mars-sync stack.
* @param {Express|Connect} options.middlewareApp
* @param {String} options.rootUrl
* @param {Collection} options.usersColl
*/
export function configure(
{ middlewareApp, rootUrl, usersColl, secretKey, smtpUrl }
) {
invariant(
middlewareApp,
'AccountManager.configure(...): you need to pass express/connect app ' +
'to MarsSync.configure() `middlewareApp` field'
);
_usersCollection = usersColl || new Collection('users');
_accManager = new AccountManager(secretKey, smtpUrl);
_oauthManager = new OAuthLoginManager(_accManager, middlewareApp, rootUrl);
_basicManager = new BasicLoginManager(_accManager, middlewareApp, rootUrl);
}
/**
* Adds new OAuth authentication strategy (Passport.JS).
* Given funtion must to return a Passport.js oauth startegy.
* Function is executed with two arguments: callbackUrl and
* authCallback. Use it to create a strategy object.
* @param {String} provider
* @param {Function} strategyCreatorFn
*/
export function addOAuthStrategy(provider, strategyCreatorFn) {
invariant(
_oauthManager,
'addOAuthStrategy(...): no OAuth login manager found. Did you pass ' +
'AccountManager to `managers` field of `MarsSync.configure()`?'
);
_oauthManager.addStrategy(provider, strategyCreatorFn);
}
/**
* Listen for new user create event. Given callback
* will be executed with user object as first argument.
* You can change user object, changed object will be saved.
* @param {Function} handlerFn
*/
export function listenUserCreate(handlerFn) {
_accManager.on('user:create', handlerFn);
}
export function listenEmailVerify(handlerFn) {
_accManager.on('user:email:verify', handlerFn);
}
/**
* Returns users collection
* @return {Collection}
*/
export function users() {
return _usersCollection;
}
|
ECS.System("inputhandler",
{
order: 0,
init: function(state)
{
var input = state.systems.inputhandler;
input.axis = [0, 0];
input.axisAcc = 25;
input.keysdown = {};
input.dashTime = 0;
input.player = null;
ECS.Events.handle('keyreleased', function(keymap)
{
input.keysdown[keymap] = false;
if (keymap == state.keys.dash)
{
if (input.player != null)
{
ECS.Events.emit('dash', input.player, input.dashTime);
}
input.dashTime = 0;
}
});
ECS.Events.handle('keypressed', function(keymap)
{
if (keymap == state.keys.dash)
{
if (input.player != null)
{
ECS.Events.emit('preparedash', input.player);
}
input.dashTime = 0;
}
input.keysdown[keymap] = true;
});
},
update: function(state, dt)
{
var input = state.systems.inputhandler;
var entities = ECS.Entities.get(ECS.Components.Direction, ECS.Tags.Player);
var e;
var tempAxis = [0, 0];
var key = input.keysdown;
while(e = entities.next())
{
input.player = e;
var direction = e.getDirection();
direction.isMoving = false;
if (key[state.keys.down])
{
tempAxis[1] += 1;
direction.isMoving = true;
}
if (key[state.keys.up])
{
tempAxis[1] -= 1;
direction.isMoving = true;
}
if (key[state.keys.left])
{
tempAxis[0] -= 1;
direction.isMoving = true;
}
if (key[state.keys.right])
{
tempAxis[0] += 1;
direction.isMoving = true;
}
if (direction.isMoving)
{
tempAxis = Util.Vector.normalized(tempAxis);
var acc = input.axisAcc * dt;
input.axis[0] += tempAxis[0] * acc;
input.axis[1] += tempAxis[1] * acc;
direction.direction = Util.Vector.normalized(input.axis);
input.axis = Util.Vector.clampMagnitude(input.axis, 0, 1);
}
direction.isStopping = key[state.keys.still];
if (key[state.keys.still])
{
direction.isMoving = false;
}
if (key[state.keys.dash])
{
input.dashTime += dt;
direction.isMoving = false;
}
}
}
});
|
/* Theme Name:iDea - Clean & Powerful Bootstrap Theme
* Author:HtmlCoder
* Author URI:http://www.htmlcoder.me
* Author e-mail:htmlcoder.me@gmail.com
* Version: 1.2.1
* Created:October 2014
* License URI:http://support.wrapbootstrap.com/
* File Description: Initializations of plugins
*/
(function($){
$(document).ready(function(){
$(window).load(function() {
$("body").removeClass("no-trans");
});
//Show dropdown on hover only for desktop devices
//-----------------------------------------------
var delay=0, setTimeoutConst;
if ((Modernizr.mq('only all and (min-width: 768px)') && !Modernizr.touch) || $("html.ie8").length>0) {
$('.main-navigation .navbar-nav>li.dropdown, .main-navigation li.dropdown>ul>li.dropdown').hover(
function(){
var $this = $(this);
setTimeoutConst = setTimeout(function(){
$this.addClass('open').slideDown();
$this.find('.dropdown-toggle').addClass('disabled');
}, delay);
}, function(){
clearTimeout(setTimeoutConst );
$(this).removeClass('open');
$(this).find('.dropdown-toggle').removeClass('disabled');
});
};
//Show dropdown on click only for mobile devices
//-----------------------------------------------
if (Modernizr.mq('only all and (max-width: 767px)') || Modernizr.touch) {
$('.main-navigation [data-toggle=dropdown], .header-top [data-toggle=dropdown]').on('click', function(event) {
// Avoid following the href location when clicking
event.preventDefault();
// Avoid having the menu to close when clicking
event.stopPropagation();
// close all the siblings
$(this).parent().siblings().removeClass('open');
// close all the submenus of siblings
$(this).parent().siblings().find('[data-toggle=dropdown]').parent().removeClass('open');
// opening the one you clicked on
$(this).parent().toggleClass('open');
});
};
//Main slider
//-----------------------------------------------
//Revolution Slider
if ($(".slider-banner-container").length>0) {
$(".tp-bannertimer").show();
$('.slider-banner-container .slider-banner').show().revolution({
delay:10000,
startwidth:1140,
startheight:520,
navigationArrows:"solo",
navigationStyle: "round",
navigationHAlign:"center",
navigationVAlign:"bottom",
navigationHOffset:0,
navigationVOffset:20,
soloArrowLeftHalign:"left",
soloArrowLeftValign:"center",
soloArrowLeftHOffset:20,
soloArrowLeftVOffset:0,
soloArrowRightHalign:"right",
soloArrowRightValign:"center",
soloArrowRightHOffset:20,
soloArrowRightVOffset:0,
fullWidth:"on",
spinner:"spinner0",
stopLoop:"off",
stopAfterLoops:-1,
stopAtSlide:-1,
onHoverStop: "off",
shuffle:"off",
autoHeight:"off",
forceFullWidth:"off",
hideThumbsOnMobile:"off",
hideNavDelayOnMobile:1500,
hideBulletsOnMobile:"off",
hideArrowsOnMobile:"off",
hideThumbsUnderResolution:0,
hideSliderAtLimit:0,
hideCaptionAtLimit:0,
hideAllCaptionAtLilmit:0,
startWithSlide:0
});
$('.slider-banner-container .slider-banner-2').show().revolution({
delay:10000,
startwidth:1140,
startheight:520,
navigationArrows:"solo",
navigationStyle: "preview4",
navigationHAlign:"center",
navigationVAlign:"bottom",
navigationHOffset:0,
navigationVOffset:20,
soloArrowLeftHalign:"left",
soloArrowLeftValign:"center",
soloArrowLeftHOffset:20,
soloArrowLeftVOffset:0,
soloArrowRightHalign:"right",
soloArrowRightValign:"center",
soloArrowRightHOffset:20,
soloArrowRightVOffset:0,
fullWidth:"on",
spinner:"spinner0",
stopLoop:"off",
stopAfterLoops:-1,
stopAtSlide:-1,
onHoverStop: "off",
shuffle:"off",
autoHeight:"off",
forceFullWidth:"off",
hideThumbsOnMobile:"off",
hideNavDelayOnMobile:1500,
hideBulletsOnMobile:"off",
hideArrowsOnMobile:"off",
hideThumbsUnderResolution:0,
hideSliderAtLimit:0,
hideCaptionAtLimit:0,
hideAllCaptionAtLilmit:0,
startWithSlide:0
});
$('.slider-banner-container .slider-banner-3').show().revolution({
delay:10000,
startwidth:1140,
startheight:520,
dottedOverlay: "twoxtwo",
parallax:"mouse",
parallaxBgFreeze:"on",
parallaxLevels:[3,2,1],
navigationArrows:"solo",
navigationStyle: "preview5",
navigationHAlign:"center",
navigationVAlign:"bottom",
navigationHOffset:0,
navigationVOffset:20,
soloArrowLeftHalign:"left",
soloArrowLeftValign:"center",
soloArrowLeftHOffset:20,
soloArrowLeftVOffset:0,
soloArrowRightHalign:"right",
soloArrowRightValign:"center",
soloArrowRightHOffset:20,
soloArrowRightVOffset:0,
fullWidth:"on",
spinner:"spinner0",
stopLoop:"off",
stopAfterLoops:-1,
stopAtSlide:-1,
onHoverStop: "off",
shuffle:"off",
autoHeight:"off",
forceFullWidth:"off",
hideThumbsOnMobile:"off",
hideNavDelayOnMobile:1500,
hideBulletsOnMobile:"off",
hideArrowsOnMobile:"off",
hideThumbsUnderResolution:0,
hideSliderAtLimit:0,
hideCaptionAtLimit:0,
hideAllCaptionAtLilmit:0,
startWithSlide:0
});
if ($(".transparent.header").length>0 || $(".offcanvas-container").length>0) {
$('.slider-banner-container .slider-banner-fullscreen').show().revolution({
delay:10000,
startwidth:1140,
startheight:520,
fullWidth:"off",
fullScreen:"on",
fullScreenOffsetContainer: "",
fullScreenOffset: "",
navigationArrows:"solo",
navigationStyle: "preview4",
navigationHAlign:"center",
navigationVAlign:"bottom",
navigationHOffset:0,
navigationVOffset:20,
soloArrowLeftHalign:"left",
soloArrowLeftValign:"center",
soloArrowLeftHOffset:20,
soloArrowLeftVOffset:0,
soloArrowRightHalign:"right",
soloArrowRightValign:"center",
soloArrowRightHOffset:20,
soloArrowRightVOffset:0,
spinner:"spinner4",
stopLoop:"off",
stopAfterLoops:-1,
stopAtSlide:-1,
onHoverStop: "off",
shuffle:"off",
hideTimerBar:"on",
autoHeight:"off",
forceFullWidth:"off",
hideThumbsOnMobile:"off",
hideNavDelayOnMobile:1500,
hideBulletsOnMobile:"off",
hideArrowsOnMobile:"off",
hideThumbsUnderResolution:0,
hideSliderAtLimit:0,
hideCaptionAtLimit:0,
hideAllCaptionAtLilmit:0,
startWithSlide:0
});
} else {
$('.slider-banner-container .slider-banner-fullscreen').show().revolution({
delay:10000,
startwidth:1140,
startheight:520,
fullWidth:"off",
fullScreen:"on",
fullScreenOffsetContainer: "",
fullScreenOffset: "82px",
navigationArrows:"solo",
navigationStyle: "preview4",
navigationHAlign:"center",
navigationVAlign:"bottom",
navigationHOffset:0,
navigationVOffset:20,
soloArrowLeftHalign:"left",
soloArrowLeftValign:"center",
soloArrowLeftHOffset:20,
soloArrowLeftVOffset:0,
soloArrowRightHalign:"right",
soloArrowRightValign:"center",
soloArrowRightHOffset:20,
soloArrowRightVOffset:0,
spinner:"spinner4",
stopLoop:"off",
stopAfterLoops:-1,
stopAtSlide:-1,
onHoverStop: "off",
shuffle:"off",
hideTimerBar:"on",
autoHeight:"off",
forceFullWidth:"off",
hideThumbsOnMobile:"off",
hideNavDelayOnMobile:1500,
hideBulletsOnMobile:"off",
hideArrowsOnMobile:"off",
hideThumbsUnderResolution:0,
hideSliderAtLimit:0,
hideCaptionAtLimit:0,
hideAllCaptionAtLilmit:0,
startWithSlide:0
});
};
};
//Owl carousel
//-----------------------------------------------
if ($('.owl-carousel').length>0) {
$(".owl-carousel.carousel").owlCarousel({
items: 4,
pagination: false,
navigation: true,
navigationText: false
});
$(".owl-carousel.carousel-autoplay").owlCarousel({
items: 4,
autoPlay: 5000,
pagination: false,
navigation: true,
navigationText: false
});
$(".owl-carousel.clients").owlCarousel({
items: 4,
autoPlay: true,
pagination: false,
itemsDesktopSmall: [992,5],
itemsTablet: [768,4],
itemsMobile: [479,3]
});
$(".owl-carousel.content-slider").owlCarousel({
singleItem: true,
autoPlay: 5000,
navigation: false,
navigationText: false,
pagination: false
});
$(".owl-carousel.content-slider-with-controls").owlCarousel({
singleItem: true,
autoPlay: false,
navigation: true,
navigationText: false,
pagination: true
});
$(".owl-carousel.content-slider-with-controls-autoplay").owlCarousel({
singleItem: true,
autoPlay: 5000,
navigation: true,
navigationText: false,
pagination: true
});
$(".owl-carousel.content-slider-with-controls-bottom").owlCarousel({
singleItem: true,
autoPlay: false,
navigation: true,
navigationText: false,
pagination: true
});
};
// Animations
//-----------------------------------------------
if (($("[data-animation-effect]").length>0) && !Modernizr.touch) {
$("[data-animation-effect]").each(function() {
var item = $(this),
animationEffect = item.attr("data-animation-effect");
if(Modernizr.mq('only all and (min-width: 768px)') && Modernizr.csstransitions) {
item.appear(function() {
if(item.attr("data-effect-delay")) item.css("effect-delay", delay + "ms");
setTimeout(function() {
item.addClass('animated object-visible ' + animationEffect);
}, item.attr("data-effect-delay"));
}, {accX: 0, accY: -130});
} else {
item.addClass('object-visible');
}
});
};
// Stats Count To
//-----------------------------------------------
if ($(".stats [data-to]").length>0) {
$(".stats [data-to]").each(function() {
var stat_item = $(this),
offset = stat_item.offset().top;
if($(window).scrollTop() > (offset - 800) && !(stat_item.hasClass('counting'))) {
stat_item.addClass('counting');
stat_item.countTo();
};
$(window).scroll(function() {
if($(window).scrollTop() > (offset - 800) && !(stat_item.hasClass('counting'))) {
stat_item.addClass('counting');
stat_item.countTo();
}
});
});
};
// Isotope filters
//-----------------------------------------------
if ($('.isotope-container').length>0 || $('.masonry-grid').length>0 || $('.masonry-grid-fitrows').length>0) {
$(window).load(function() {
$('.masonry-grid').isotope({
itemSelector: '.masonry-grid-item',
layoutMode: 'masonry'
});
$('.masonry-grid-fitrows').isotope({
itemSelector: '.masonry-grid-item',
layoutMode: 'fitRows'
});
$('.isotope-container').fadeIn();
var $container = $('.isotope-container').isotope({
itemSelector: '.isotope-item',
layoutMode: 'masonry',
transitionDuration: '0.6s',
filter: "*"
});
// filter items on button click
$('.filters').on( 'click', 'ul.nav li a', function() {
var filterValue = $(this).attr('data-filter');
$(".filters").find("li.active").removeClass("active");
$(this).parent().addClass("active");
$container.isotope({ filter: filterValue });
return false;
});
});
};
//hc-tabs
//-----------------------------------------------
if ($('.hc-tabs').length>0) {
$(window).load(function() {
var currentTab = $(".hc-tabs .nav.nav-tabs li.active a").attr("href"),
tabsImageAnimation = $(".hc-tabs-top").find("[data-tab='" + currentTab + "']").attr("data-tab-animation-effect");
$(".hc-tabs-top").find("[data-tab='" + currentTab + "']").addClass("current-img show " + tabsImageAnimation + " animated");
$('.hc-tabs .nav.nav-tabs li a').on('click', function(event) {
var currentTab = $(this).attr("href"),
tabsImageAnimation = $(".hc-tabs-top").find("[data-tab='" + currentTab + "']").attr("data-tab-animation-effect");
$(".current-img").removeClass("current-img show " + tabsImageAnimation + " animated");
$(".hc-tabs-top").find("[data-tab='" + currentTab + "']").addClass("current-img show " + tabsImageAnimation + " animated");
});
});
}
// Animated Progress Bars
//-----------------------------------------------
if ($("[data-animate-width]").length>0) {
$("[data-animate-width]").each(function() {
$(this).appear(function() {
$(this).animate({
width: $(this).attr("data-animate-width")
}, 800 );
}, {accX: 0, accY: -100});
});
};
// Animated Progress Bars
//-----------------------------------------------
if ($(".knob").length>0) {
$(".knob").knob();
}
// Magnific popup
//-----------------------------------------------
if (($(".popup-img").length > 0) || ($(".popup-iframe").length > 0) || ($(".popup-img-single").length > 0)) {
$(".popup-img").magnificPopup({
type:"image",
gallery: {
enabled: true,
}
});
$(".popup-img-single").magnificPopup({
type:"image",
gallery: {
enabled: false,
}
});
$('.popup-iframe').magnificPopup({
disableOn: 700,
type: 'iframe',
preloader: false,
fixedContentPos: false
});
};
// Fixed header
//-----------------------------------------------
var headerTopHeight = $(".header-top").outerHeight(),
headerHeight = $("header.header.fixed").outerHeight();
$(window).scroll(function() {
if (($(".header.fixed").length > 0)) {
if(($(this).scrollTop() > headerTopHeight+headerHeight) && ($(window).width() > 767)) {
$("body").addClass("fixed-header-on");
$(".header.fixed").addClass('animated object-visible fadeInDown');
if (!($(".header.transparent").length>0)) {
if ($(".banner:not(.header-top)").length>0) {
$(".banner").css("marginTop", (headerHeight)+"px");
} else if ($(".page-intro").length>0) {
$(".page-intro").css("marginTop", (headerHeight)+"px");
} else if ($(".page-top").length>0) {
$(".page-top").css("marginTop", (headerHeight)+"px");
} else {
$("section.main-container").css("marginTop", (headerHeight)+"px");
}
}
} else {
$("body").removeClass("fixed-header-on");
$("section.main-container").css("marginTop", (0)+"px");
$(".banner").css("marginTop", (0)+"px");
$(".page-intro").css("marginTop", (0)+"px");
$(".page-top").css("marginTop", (0)+"px");
$(".header.fixed").removeClass('animated object-visible fadeInDown');
}
};
});
// Sharrre plugin
//-----------------------------------------------
if ($('#share').length>0) {
$('#share').sharrre({
share: {
twitter: true,
facebook: true,
googlePlus: true
},
template: '<ul class="social-links clearfix"><li class="facebook"><a href="#"><i class="fa fa-facebook"></i></a></li><li class="twitter"><a href="#"><i class="fa fa-twitter"></i></a></li><li class="googleplus"><a href="#"><i class="fa fa-google-plus"></i></a></li></ul>',
enableHover: false,
enableTracking: true,
render: function(api, options){
$(api.element).on('click', '.twitter a', function() {
api.openPopup('twitter');
});
$(api.element).on('click', '.facebook a', function() {
api.openPopup('facebook');
});
$(api.element).on('click', '.googleplus a', function() {
api.openPopup('googlePlus');
});
}
});
};
// Contact forms validation
//-----------------------------------------------
if($("#contact-form").length>0) {
$("#contact-form").validate({
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "php/email-sender.php",
data: {
"name": $("#contact-form #name").val(),
"email": $("#contact-form #email").val(),
"subject": $("#contact-form #subject").val(),
"message": $("#contact-form #message").val()
},
dataType: "json",
success: function (data) {
if (data.sent == "yes") {
$("#MessageSent").removeClass("hidden");
$("#MessageNotSent").addClass("hidden");
$(".submit-button").removeClass("btn-default").addClass("btn-success").prop('value', 'Message Sent');
$("#contact-form .form-control").each(function() {
$(this).prop('value', '').parent().removeClass("has-success").removeClass("has-error");
});
} else {
$("#MessageNotSent").removeClass("hidden");
$("#MessageSent").addClass("hidden");
}
}
});
},
// debug: true,
errorPlacement: function(error, element) {
error.insertBefore( element );
},
onkeyup: false,
onclick: false,
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
subject: {
required: true
},
message: {
required: true,
minlength: 10
}
},
messages: {
name: {
required: "Please specify your name",
minlength: "Your name must be longer than 2 characters"
},
email: {
required: "We need your email address to contact you",
email: "Please enter a valid email address e.g. name@domain.com"
},
subject: {
required: "Please enter a subject"
},
message: {
required: "Please enter a message",
minlength: "Your message must be longer than 10 characters"
}
},
errorElement: "span",
highlight: function (element) {
$(element).parent().removeClass("has-success").addClass("has-error");
$(element).siblings("label").addClass("hide");
},
success: function (element) {
$(element).parent().removeClass("has-error").addClass("has-success");
$(element).siblings("label").removeClass("hide");
}
});
};
if($("#footer-form").length>0) {
$("#footer-form").validate({
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "php/email-sender.php",
data: {
"name": $("#footer-form #name2").val(),
"email": $("#footer-form #email2").val(),
"subject": "Message from contact form",
"message": $("#footer-form #message2").val()
},
dataType: "json",
success: function (data) {
if (data.sent == "yes") {
$("#MessageSent2").removeClass("hidden");
$("#MessageNotSent2").addClass("hidden");
$(".submit-button").removeClass("btn-default").addClass("btn-success").prop('value', 'Message Sent');
$("#footer-form .form-control").each(function() {
$(this).prop('value', '').parent().removeClass("has-success").removeClass("has-error");
});
} else {
$("#MessageNotSent2").removeClass("hidden");
$("#MessageSent2").addClass("hidden");
}
}
});
},
// debug: true,
errorPlacement: function(error, element) {
error.insertAfter( element );
},
onkeyup: false,
onclick: false,
rules: {
name2: {
required: true,
minlength: 2
},
email2: {
required: true,
email: true
},
message2: {
required: true,
minlength: 10
}
},
messages: {
name2: {
required: "Please specify your name",
minlength: "Your name must be longer than 2 characters"
},
email2: {
required: "We need your email address to contact you",
email: "Please enter a valid email address e.g. name@domain.com"
},
message2: {
required: "Please enter a message",
minlength: "Your message must be longer than 10 characters"
}
},
errorElement: "span",
highlight: function (element) {
$(element).parent().removeClass("has-success").addClass("has-error");
$(element).siblings("label").addClass("hide");
},
success: function (element) {
$(element).parent().removeClass("has-error").addClass("has-success");
$(element).siblings("label").removeClass("hide");
}
});
};
if($("#sidebar-form").length>0) {
$("#sidebar-form").validate({
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "php/email-sender.php",
data: {
"name": $("#sidebar-form #name3").val(),
"email": $("#sidebar-form #email3").val(),
"subject": "Message from FAQ page",
"category": $("#sidebar-form #category").val(),
"message": $("#sidebar-form #message3").val()
},
dataType: "json",
success: function (data) {
if (data.sent == "yes") {
$("#MessageSent3").removeClass("hidden");
$("#MessageNotSent3").addClass("hidden");
$(".submit-button").removeClass("btn-default").addClass("btn-success").prop('value', 'Message Sent');
$("#sidebar-form .form-control").each(function() {
$(this).prop('value', '').parent().removeClass("has-success").removeClass("has-error");
});
} else {
$("#MessageNotSent3").removeClass("hidden");
$("#MessageSent3").addClass("hidden");
}
}
});
},
// debug: true,
errorPlacement: function(error, element) {
error.insertAfter( element );
},
onkeyup: false,
onclick: false,
rules: {
name3: {
required: true,
minlength: 2
},
email3: {
required: true,
email: true
},
message3: {
required: true,
minlength: 10
}
},
messages: {
name3: {
required: "Please specify your name",
minlength: "Your name must be longer than 2 characters"
},
email3: {
required: "We need your email address to contact you",
email: "Please enter a valid email address e.g. name@domain.com"
},
message3: {
required: "Please enter a message",
minlength: "Your message must be longer than 10 characters"
}
},
errorElement: "span",
highlight: function (element) {
$(element).parent().removeClass("has-success").addClass("has-error");
},
success: function (element) {
$(element).parent().removeClass("has-error").addClass("has-success");
}
});
};
// Affix plugin
//-----------------------------------------------
if ($("#affix").length>0) {
$(window).load(function() {
var affixBottom = $(".footer").outerHeight(true) + $(".subfooter").outerHeight(true) + $(".blogpost footer").outerHeight(true),
affixTop = $("#affix").offset().top;
if ($(".comments").length>0) {
affixBottom = affixBottom + $(".comments").outerHeight(true);
}
if ($(".comments-form").length>0) {
affixBottom = affixBottom + $(".comments-form").outerHeight(true);
}
if ($(".footer-top").length>0) {
affixBottom = affixBottom + $(".footer-top").outerHeight(true);
}
if ($(".header.fixed").length>0) {
$("#affix").affix({
offset: {
top: affixTop-150,
bottom: affixBottom+100
}
});
} else {
$("#affix").affix({
offset: {
top: affixTop-35,
bottom: affixBottom+100
}
});
}
});
}
if ($(".affix-menu").length>0) {
setTimeout(function () {
var $sideBar = $('.sidebar')
$sideBar.affix({
offset: {
top: function () {
var offsetTop = $sideBar.offset().top
return (this.top = offsetTop - 65)
},
bottom: function () {
var affixBottom = $(".footer").outerHeight(true) + $(".subfooter").outerHeight(true)
if ($(".footer-top").length>0) {
affixBottom = affixBottom + $(".footer-top").outerHeight(true)
}
return (this.bottom = affixBottom+50)
}
}
})
}, 100)
}
//Smooth Scroll
//-----------------------------------------------
if ($(".smooth-scroll").length>0) {
if($(".header.fixed").length>0) {
$('.smooth-scroll a[href*=#]:not([href=#]), a[href*=#]:not([href=#]).smooth-scroll').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top-65
}, 1000);
return false;
}
}
});
} else {
$('.smooth-scroll a[href*=#]:not([href=#]), a[href*=#]:not([href=#]).smooth-scroll').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
}
}
//Scroll Spy
//-----------------------------------------------
if($(".scrollspy").length>0) {
$("body").addClass("scroll-spy");
if($(".fixed.header").length>0) {
$('body').scrollspy({
target: '.scrollspy',
offset: 85
});
} else {
$('body').scrollspy({
target: '.scrollspy',
offset: 20
});
}
}
//Scroll totop
//-----------------------------------------------
$(window).scroll(function() {
if($(this).scrollTop() != 0) {
$(".scrollToTop").fadeIn();
} else {
$(".scrollToTop").fadeOut();
}
});
$(".scrollToTop").click(function() {
$("body,html").animate({scrollTop:0},800);
});
//Modal
//-----------------------------------------------
if($(".modal").length>0) {
$(".modal").each(function() {
$(".modal").prependTo( "body" );
});
}
// Pricing tables popovers
//-----------------------------------------------
if ($(".pricing-tables").length>0) {
$(".plan .pt-popover").popover({
trigger: 'hover'
});
};
// Parallax section
//-----------------------------------------------
if (($(".parallax").length>0) && !Modernizr.touch ){
$(".parallax").parallax("50%", 0.2, false);
};
// Remove Button
//-----------------------------------------------
$(".btn-remove").click(function() {
$(this).closest(".remove-data").remove();
});
// Shipping Checkbox
//-----------------------------------------------
if ($("#shipping-info-check").is(':checked')) {
$("#shipping-information").hide();
}
$("#shipping-info-check").change(function(){
if ($(this).is(':checked')) {
$("#shipping-information").slideToggle();
} else {
$("#shipping-information").slideToggle();
}
});
//This will prevent the event from bubbling up and close the dropdown when you type/click on text boxes (Header Top).
//-----------------------------------------------
$('.header-top .dropdown-menu input').click(function(e) {
e.stopPropagation();
});
// Offcanvas side navbar
//-----------------------------------------------
if ($("#offcanvas").length>0) {
$('#offcanvas').offcanvas({
disableScrolling: false,
toggle: false
});
};
if ($("#offcanvas").length>0) {
$('#offcanvas [data-toggle=dropdown]').on('click', function(event) {
// Avoid following the href location when clicking
event.preventDefault();
// Avoid having the menu to close when clicking
event.stopPropagation();
// close all the siblings
$(this).parent().siblings().removeClass('open');
// close all the submenus of siblings
$(this).parent().siblings().find('[data-toggle=dropdown]').parent().removeClass('open');
// opening the one you clicked on
$(this).parent().toggleClass('open');
});
};
}); // End document ready
})(this.jQuery);
if (jQuery(".btn-print").length>0) {
function print_window() {
var mywindow = window;
mywindow.document.close();
mywindow.focus();
mywindow.print();
mywindow.close();
}
} |
bang! (1, 2, 3)
|
'use strict';
let inspect = require('inspect.js');
let sinon = require('sinon');
inspect.useSinon(sinon);
let CoreIO = require('../src/coreio');
let log = require('logtopus').getLogger('coreio');
log.setLevel('error');
describe('CoreIO.SyncList', function() {
describe('instance', function() {
var initSocketStub,
registerListenerStub;
beforeEach(function() {
initSocketStub = sinon.stub(CoreIO.SyncList.prototype, 'initSocket');
registerListenerStub = sinon.stub(CoreIO.SyncList.prototype, 'registerListener');
});
afterEach(function() {
initSocketStub.restore();
registerListenerStub.restore();
});
it('Should be a SyncList object', function() {
inspect(CoreIO.SyncList).isFunction();
});
it('Should be an instance of SyncList', function() {
var syncList = new CoreIO.SyncList();
inspect(syncList).isInstanceOf(CoreIO.SyncList);
inspect(syncList).isInstanceOf(CoreIO.List);
});
it('Should call List constructor', function() {
var listConstructorStub = sinon.spy(CoreIO, 'List');
var syncList = new CoreIO.SyncList();
inspect(listConstructorStub).wasCalledOnce();
listConstructorStub.restore();
});
it('Should call initSocket method', function() {
var syncList = new CoreIO.SyncList();
inspect(initSocketStub).wasCalledOnce();
});
it('Should call registerListener method', function() {
var syncList = new CoreIO.SyncList();
inspect(registerListenerStub).wasCalledOnce();
});
it('Should have been extended by CoreIO.Event', function() {
var syncList = new CoreIO.SyncList();
inspect(syncList.on).isFunction();
inspect(syncList.off).isFunction();
inspect(syncList.emit).isFunction();
});
});
describe('initSocket', function() {
var SocketStub,
startStub,
registerListenerStub,
syncList;
beforeEach(function() {
SocketStub = sinon.stub(CoreIO, 'Socket');
startStub = sinon.stub();
SocketStub.returns({
start: startStub
});
registerListenerStub = sinon.stub(CoreIO.SyncList.prototype, 'registerListener');
syncList = new CoreIO.SyncList('test', {
port: 1234
});
});
afterEach(function() {
SocketStub.restore();
registerListenerStub.restore();
});
it('Should initialize CoreIO.Socket', function() {
inspect(SocketStub).wasCalledOnce();
inspect(SocketStub).wasCalledWith({
path: 'xqsocket',
channel: 'testlist',
port: 1234
});
inspect(startStub).wasCalledOnce();
});
});
describe('registerListener', function() {
var socketStub,
initSocketStub;
beforeEach(function() {
socketStub = sinon.createStubInstance(CoreIO.Socket);
initSocketStub = sinon.stub(CoreIO.SyncList.prototype, 'initSocket').callsFake(function() {
this.socket = socketStub;
});
});
afterEach(function() {
initSocketStub.restore();
});
it('Should register listener', function() {
var syncList = new CoreIO.SyncList('test', {
isWriteable: true
});
inspect(socketStub.on).hasCallCount(9);
inspect(socketStub.on).wasCalledWith('synclist.register', sinon.match.func);
inspect(socketStub.on).wasCalledWith('synclist.unregister', sinon.match.func);
});
it('Should register a synclist.push listener', function() {
var syncList;
syncList = new CoreIO.SyncList('test', {
isWriteable: true
});
inspect(socketStub.on).wasCalledWith('synclist.push', sinon.match.func);
var pushStub = sinon.stub(syncList, 'push');
socketStub.on.withArgs('synclist.push').yield('Test data');
inspect(pushStub).wasCalledOnce();
inspect(pushStub).wasCalledWith('Test data', {
sync: 'false'
});
pushStub.restore();
});
it('Should register a synclist.unshift listener', function() {
var syncList;
syncList = new CoreIO.SyncList('test', {
isWriteable: true
});
inspect(socketStub.on).wasCalledWith('synclist.unshift', sinon.match.func);
var unshiftStub = sinon.stub(syncList, 'unshift');
socketStub.on.withArgs('synclist.unshift').yield('Test data');
inspect(unshiftStub).wasCalledOnce();
inspect(unshiftStub).wasCalledWith('Test data', {
sync: 'false'
});
unshiftStub.restore();
});
it('Should register a synclist.pop listener', function() {
var syncList;
syncList = new CoreIO.SyncList('test', {
isWriteable: true
});
inspect(socketStub.on).wasCalledWith('synclist.pop', sinon.match.func);
var popStub = sinon.stub(syncList, 'pop');
socketStub.on.withArgs('synclist.pop').yield('Test data');
inspect(popStub).wasCalledOnce();
inspect(popStub).wasCalledWith({
sync: 'false'
});
popStub.restore();
});
it('Should register a synclist.shift listener', function() {
var syncList;
syncList = new CoreIO.SyncList('test', {
isWriteable: true
});
inspect(socketStub.on).wasCalledWith('synclist.shift', sinon.match.func);
var shiftStub = sinon.stub(syncList, 'shift');
socketStub.on.withArgs('synclist.shift').yield('Test data');
inspect(shiftStub).wasCalledOnce();
inspect(shiftStub).wasCalledWith({
sync: 'false'
});
shiftStub.restore();
});
it('Shouldn\'t register any synclist.* listeners if list isn\'t writeable', function() {
var syncList = new CoreIO.SyncList('test', {
isWriteable: false
});
inspect(socketStub.on).wasNeverCalledWith('synclist.push');
inspect(socketStub.on).wasNeverCalledWith('synclist.unshift');
inspect(socketStub.on).wasNeverCalledWith('synclist.pop');
inspect(socketStub.on).wasNeverCalledWith('synclist.shift');
});
});
describe('emitRemote', function() {
var socketStub,
initSocketStub;
beforeEach(function() {
socketStub = sinon.createStubInstance(CoreIO.Socket);
initSocketStub = sinon.stub(CoreIO.SyncList.prototype, 'initSocket').callsFake(function() {
this.socket = socketStub;
});
});
afterEach(function() {
initSocketStub.restore();
});
it('Should emit a socket message to the client', function() {
var syncList = new CoreIO.SyncList('test');
syncList.emitRemote('bla.blubb', 'Test data');
inspect(socketStub.emit).wasCalledOnce();
inspect(socketStub.emit).wasCalledWith('bla.blubb', 'Test data');
});
});
describe('sync', function() {
var socketStub,
initSocketStub;
beforeEach(function() {
socketStub = sinon.createStubInstance(CoreIO.Socket);
initSocketStub = sinon.stub(CoreIO.SyncList.prototype, 'initSocket').callsFake(function() {
this.socket = socketStub;
});
});
afterEach(function() {
initSocketStub.restore();
});
it('Should syncronize model with all client models', function() {
var syncList = new CoreIO.SyncList('test');
var emitRemoteStub = sinon.stub(syncList, 'emitRemote');
syncList.sync('push', {a: 'aa'});
inspect(emitRemoteStub).wasCalledOnce();
inspect(emitRemoteStub).wasCalledWith('synclist.push', {a: 'aa'});
emitRemoteStub.restore();
});
});
});
|
'use strict';
angular.module('sfchecks.project', ['ui.bootstrap', 'sgw.ui.breadcrumb', 'bellows.services', 'sfchecks.services',
'palaso.ui.listview', 'palaso.ui.typeahead', 'palaso.ui.notice', 'palaso.ui.textdrop', 'palaso.ui.jqte',
'ngFileUpload', 'ngRoute'])
.controller('ProjectCtrl', ['$scope', 'textService', 'sessionService', 'breadcrumbService', 'sfchecksLinkService',
'silNoticeService', 'sfchecksProjectService', 'messageService', 'modalService',
function ($scope, textService, ss, breadcrumbService, sfchecksLinkService,
notice, sfchecksProjectService, messageService, modalService) {
$scope.finishedLoading = false;
// Rights
$scope.rights = {};
$scope.rights.archive = false;
$scope.rights.create = false;
$scope.rights.edit = false; //ss.hasSiteRight(ss.domain.PROJECTS, ss.operation.EDIT);
$scope.rights.showControlBar = $scope.rights.archive || $scope.rights.create || $scope.rights.edit;
// Broadcast Messages
// items are in the format of {id: id, subject: subject, content: content}
$scope.messages = [];
/*
function addMessage(id, message) {
messages.push({id: id, message: message});
};
*/
$scope.markMessageRead = function (id) {
for (var i = 0; i < $scope.messages.length; ++i) {
var m = $scope.messages[i];
if (m.id == id) {
$scope.messages.splice(i, 1);
messageService.markRead(id);
break;
}
}
};
// Listview Selection
$scope.newTextCollapsed = true;
$scope.selected = [];
$scope.updateSelection = function (event, item) {
var selectedIndex = $scope.selected.indexOf(item);
var checkbox = event.target;
if (checkbox.checked && selectedIndex == -1) {
$scope.selected.push(item);
} else if (!checkbox.checked && selectedIndex != -1) {
$scope.selected.splice(selectedIndex, 1);
}
};
$scope.isSelected = function (item) {
return item != null && $scope.selected.indexOf(item) >= 0;
};
$scope.texts = [];
// Page Dto
$scope.getPageDto = function () {
sfchecksProjectService.pageDto(function (result) {
if (result.ok) {
$scope.texts = result.data.texts;
$scope.textsCount = $scope.texts.length;
$scope.enhanceDto($scope.texts);
$scope.messages = result.data.broadcastMessages;
// update activity count service
$scope.activityUnreadCount = result.data.activityUnreadCount;
$scope.members = result.data.members;
$scope.project = result.data.project;
$scope.project.url = sfchecksLinkService.project();
// Breadcrumb
breadcrumbService.set('top',
[
{ href: '/app/projects', label: 'My Projects' },
{ href: sfchecksLinkService.project(), label: $scope.project.name }
]
);
var rights = result.data.rights;
$scope.rights.archive = ss.hasRight(rights, ss.domain.TEXTS, ss.operation.ARCHIVE) && !ss.session.project.isArchived;
$scope.rights.create = ss.hasRight(rights, ss.domain.TEXTS, ss.operation.CREATE) && !ss.session.project.isArchived;
$scope.rights.edit = ss.hasRight(rights, ss.domain.TEXTS, ss.operation.EDIT) && !ss.session.project.isArchived;
$scope.rights.showControlBar = $scope.rights.archive || $scope.rights.create || $scope.rights.edit;
$scope.finishedLoading = true;
}
});
};
// Archive Texts
$scope.archiveTexts = function () {
//console.log("archiveTexts()");
var textIds = [];
var message = '';
for (var i = 0, l = $scope.selected.length; i < l; i++) {
textIds.push($scope.selected[i].id);
}
if (textIds.length == 1) {
message = 'Are you sure you want to archive the selected text?';
} else {
message = 'Are you sure you want to archive the ' + textIds.length + ' selected texts?';
}
// The commented modalService below can be used instead of the window.confirm alert, but must change E2E tests using alerts. IJH 2014-06
var modalOptions = {
closeButtonText: 'Cancel',
actionButtonText: 'Archive',
headerText: 'Archive Texts?',
bodyText: message
};
modalService.showModal({}, modalOptions).then(function () {
textService.archive(textIds, function (result) {
if (result.ok) {
$scope.selected = []; // Reset the selection
$scope.getPageDto();
if (textIds.length == 1) {
notice.push(notice.SUCCESS, 'The text was archived successfully');
} else {
notice.push(notice.SUCCESS, 'The texts were archived successfully');
}
}
});
});
};
// Add Text
$scope.addText = function () {
// console.log("addText()");
var model = {};
model.id = '';
model.title = $scope.title;
model.content = $scope.content;
model.startCh = $scope.startCh;
model.startVs = $scope.startVs;
model.endCh = $scope.endCh;
model.endVs = $scope.endVs;
model.fontfamily = $scope.fontfamily;
textService.update(model, function (result) {
if (result.ok) {
notice.push(notice.SUCCESS, 'The text \'' + model.title + '\' was added successfully');
}
$scope.getPageDto();
});
};
$scope.rangeSelectorCollapsed = true;
$scope.toggleRangeSelector = function () {
$scope.rangeSelectorCollapsed = !$scope.rangeSelectorCollapsed;
};
$scope.enhanceDto = function (items) {
for (var i in items) {
if (items.hasOwnProperty(i)) {
items[i].url = sfchecksLinkService.text(items[i].id);
}
}
};
$scope.readUsx = function readUsx(file) {
if (!file || file.$error) return;
var reader = new FileReader();
reader.addEventListener('loadend', function () {
// Basic sanity check: make sure what was uploaded is USX
// First few characters should be optional BOM, optional <?xml ..., then <usx ...
var startOfText = reader.result.slice(0, 1000);
var usxIndex = startOfText.indexOf('<usx');
if (usxIndex != -1) {
$scope.$apply(function () {
$scope.content = reader.result;
});
} else {
notice.push(notice.ERROR, 'Error loading USX file. The file doesn\'t appear to be valid USX.');
$scope.$apply(function () {
$scope.content = '';
});
}
});
reader.readAsText(file);
};
$scope.getPageDto();
}])
;
|
var mongoose = require('mongoose');
var mongooseUniqueValidator = require('mongoose-unique-validator');
var Schema = mongoose.Schema;
var schema = new Schema({
username: {type: String, required: true, unique: true},
password: {type: String, required: true},
email: {type: String, required: true, unique: true},
cookbook: [{type: Schema.Types.ObjectId, ref: 'Recipe'}]
});
schema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('User', schema); |
const path = require('path');
const webpack = require('webpack');
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
module.exports = {
context: __dirname,
entry: [
'webpack-hot-middleware/client',
'./src/client',
],
output: {
path: path.resolve(__dirname, 'public', 'assets'),
publicPath: './assets/',
filename: 'bundle.js',
sourceMapFilename: '[name].map',
},
plugins: [
new WebpackIsomorphicToolsPlugin(
require('./webpack-isomorphic-tools.config')),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.HotModuleReplacementPlugin(),
],
module: {
rules: [
{
test: /\.js$/i,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.(s[ac]|c)ss$/i,
use: [
'style-loader',
'css-loader',
'sass-loader',
],
},
{
test: /\.(png|jpe?g|gif|tiff)?$/,
use: ['file-loader'],
},
{
test: /\.(woff2?|eot|svg|ttf)?$/,
use: ['file-loader'],
},
],
},
};
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var Lorem = 'Material';
exports.default = Lorem;
var lorems = require.context('./', true, /Material\w*.jsx/);
lorems.keys().forEach(function (filename) {
var ipsum = lorems(filename).default;
var ipsumName = filename.replace(/^.\//, '').replace(/.jsx$/, '');
module.exports[ipsumName] = ipsum;
});
|
/* global require, ResearchItemEditorship, Validator, Source */
'use strict';
const BaseModel = require("../lib/BaseModel.js");
const fields = [
{name: 'title'},
{name: 'authorsStr'},
{name: 'yearFrom'},
{name: 'yearTo'},
{name: 'source'},
{name: 'editorshipRole'},
{name: 'researchItem'}
];
module.exports = _.merge({}, BaseModel, {
tableName: 'research_item_editorship',
attributes: {
researchItem: {
model: 'researchitem',
columnName: 'research_item'
},
title: 'STRING',
authorsStr: {
type: 'STRING',
columnName: 'authors_str'
},
yearFrom: {
type: 'STRING',
columnName: 'year_from'
},
yearTo: {
type: 'STRING',
columnName: 'year_to'
},
source: {
model: 'source'
},
editorshipRole: {
type: 'STRING',
columnName: 'editorship_role',
},
isValid() {
const requiredFields = [
'authorsStr',
'yearFrom',
'source',
'researchItem'
];
return _.every(requiredFields, v => this[v])
&& Validator.hasValidAuthorsStr(this)
&& Validator.hasValidYear(this, 'yearFrom')
&& (!this.yearTo || Validator.hasValidYear(this, 'yearTo'));
},
},
getFields() {
return fields.map(f => f.name);
},
async selectData(itemData) {
if (!itemData.yearFrom)
itemData.yearFrom = itemData.year;
if (itemData.source)
itemData.source = await ResearchItemEditorship.getFixedCollection(Source, itemData.source);
return _.pick(itemData, ResearchItemEditorship.getFields());
}
});
|
'use strict'
var EventManager = require('ethereum-remix').lib.EventManager
function Files (storage) {
var event = new EventManager()
this.event = event
var readonly = {}
this.type = 'browser'
this.exists = function (path) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return false
}
return this.isReadOnly(unprefixedpath) || storage.exists(unprefixedpath)
}
this.init = function (cb) {
cb()
}
this.get = function (path, cb) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return null
}
var content = readonly[unprefixedpath] || storage.get(unprefixedpath)
if (cb) {
cb(null, content)
}
return content
}
this.set = function (path, content) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return false
}
if (!this.isReadOnly(unprefixedpath)) {
var exists = storage.exists(unprefixedpath)
if (!storage.set(unprefixedpath, content)) {
return false
}
if (!exists) {
event.trigger('fileAdded', [this.type + '/' + unprefixedpath, false])
} else {
event.trigger('fileChanged', [this.type + '/' + unprefixedpath])
}
return true
}
return false
}
this.addReadOnly = function (path, content) {
var unprefixedpath = this.removePrefix(path)
if (!storage.exists(unprefixedpath)) {
readonly[unprefixedpath] = content
event.trigger('fileAdded', [this.type + '/' + unprefixedpath, true])
return true
}
return false
}
this.isReadOnly = function (path) {
path = this.removePrefix(path)
return readonly[path] !== undefined
}
this.remove = function (path) {
var unprefixedpath = this.removePrefix(path)
if (!this.exists(unprefixedpath)) {
return false
}
if (this.isReadOnly(unprefixedpath)) {
readonly[unprefixedpath] = undefined
} else {
if (!storage.remove(unprefixedpath)) {
return false
}
}
event.trigger('fileRemoved', [this.type + '/' + unprefixedpath])
return true
}
this.rename = function (oldPath, newPath, isFolder) {
var unprefixedoldPath = this.removePrefix(oldPath)
var unprefixednewPath = this.removePrefix(newPath)
if (!this.isReadOnly(unprefixedoldPath) && storage.exists(unprefixedoldPath)) {
if (!storage.rename(unprefixedoldPath, unprefixednewPath)) {
return false
}
event.trigger('fileRenamed', [this.type + '/' + unprefixedoldPath, this.type + '/' + unprefixednewPath, isFolder])
return true
}
return false
}
this.list = function () {
var files = {}
// add r/w files to the list
storage.keys().forEach((path) => {
// NOTE: as a temporary measure do not show the config file
if (path !== '.remix.config') {
files[this.type + '/' + path] = false
}
})
// add r/o files to the list
Object.keys(readonly).forEach((path) => {
files[this.type + '/' + path] = true
})
return files
}
this.removePrefix = function (path) {
return path.indexOf(this.type + '/') === 0 ? path.replace(this.type + '/', '') : path
}
//
// Tree model for files
// {
// 'a': { }, // empty directory 'a'
// 'b': {
// 'c': {}, // empty directory 'b/c'
// 'd': { '/readonly': true, '/content': 'Hello World' } // files 'b/c/d'
// 'e': { '/readonly': false, '/path': 'b/c/d' } // symlink to 'b/c/d'
// 'f': { '/readonly': false, '/content': '<executable>', '/mode': 0755 }
// }
// }
//
this.listAsTree = function () {
function hashmapize (obj, path, val) {
var nodes = path.split('/')
var i = 0
for (; i < nodes.length - 1; i++) {
var node = nodes[i]
if (obj[node] === undefined) {
obj[node] = {}
}
obj = obj[node]
}
obj[nodes[i]] = val
}
var tree = {}
var self = this
// This does not include '.remix.config', because it is filtered
// inside list().
Object.keys(this.list()).forEach(function (path) {
hashmapize(tree, path, {
'/readonly': self.isReadOnly(path),
'/content': self.get(path)
})
})
return tree
}
// rename .browser-solidity.json to .remix.config
if (this.exists('.browser-solidity.json')) {
this.rename('.browser-solidity.json', '.remix.config')
}
}
module.exports = Files
|
/*
* NODE SDK for the KATANA(tm) Framework (http://katana.kusanagi.io)
* Copyright (c) 2016-2018 KUSANAGI S.L. All rights reserved.
*
* Distributed under the MIT license
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code
*
* @link https://github.com/kusanagi/katana-sdk-node
* @license http://www.opensource.org/licenses/mit-license.php MIT License
* @copyright Copyright (c) 2016-2018 KUSANAGI S.L. (http://kusanagi.io)
*/
'use strict';
const semver = require('semver');
/**
* Base Api class
* @see https://github.com/kusanagi/katana-sdk-spec#7-api
*/
class Api {
/**
* Create Api instance
*
* @param {Component} component Base component running this API
* @param {string} path Source file path
* @param {string} name Component name
* @param {string} version Component version
* @param {string} frameworkVersion Framework version
* @param {Object} variables Variables object
* @param {boolean} debug Debug mode
*/
constructor(component, path, name, version, frameworkVersion, variables = {}, debug = false) {
this._component = component;
this._path = path;
this._name = name;
this._version = version;
this._frameworkVersion = frameworkVersion;
this._variables = variables;
this._debug = debug;
this._params = {};
}
/**
*
*/
done() {
if (this._callbackTimeout) {
clearTimeout(this._callbackTimeout);
}
if (this._parentRequest) {
clearTimeout(this._parentRequest._callbackTimeout);
}
const {metadata, 'payload': reply} = this._component._commandReply.getMessage(this);
this._component._replyWith(metadata, reply);
}
/**
*
* @param {String} action Name of the action callback
* @param {Number} timeout Maximum allowed execution time, in milliseconds
* @protected
*/
_setCallbackExecutionTimeout(action, timeout = 10000) {
this.log(`Setting timeout of ${timeout}ms for ${action}`);
this._callbackTimeout = setTimeout(() => {
this._callbackExecutionTimeout(action, timeout);
}, timeout);
}
/**
*
* @param {String} action Name of the action callback
* @param {Number} timeout Maximum allowed execution time, in milliseconds
* @protected
*/
_callbackExecutionTimeout(action, timeout) {
this.log(`Callback timeout on ${action}: ${timeout}ms`);
this._component._replyWithError(
`Timeout in execution of ${this._name} (${this._version}) for asynchronous action: ${action}`,
500,
'Internal Server Error'
);
}
/**
* Returns whether or not the component is currently running in debug mode
*
* @return {boolean}
*/
isDebug() {
return this._debug;
}
/**
* Get framework version
*
* @return {string}
*/
getFrameworkVersion() {
return this._frameworkVersion;
}
/**
* Get user source file path
*
* @return {string}
*/
getPath() {
return this._path;
}
/**
* Get name of the component
*
* @return {string}
*/
getName() {
return this._name;
}
/**
* Get version of the component
*
* @return {string}
*/
getVersion() {
return this._version;
}
/**
* Get variables
*
* @return {Object}
*/
getVariables() {
return this._variables;
}
/**
* Get variable value
*
* @param {string} name Name of the variable
* @return {string}
*/
getVariable(name) {
return this._variables[name] || null;
}
/**
* Determines if a variable as been defined with the given name
*
* @param {string} name Name of the variable
* @return {string}
*/
hasVariable(name) {
return !!this._variables[name];
}
hasResource(name) {
return this._component.hasResource(name);
}
getResource(name) {
return this._component.getResource(name);
}
getServices() {
// Don' include the schema
return this._component.servicesMapping.map((v) => ({name: v.name, version: v.version}));
}
/**
*
* @param {string} name
* @param {string} version
* @return {ServiceSchema}
*/
getServiceSchema(name, version) {
if (!this._component.servicesMapping || this._component.servicesMapping.length === 0) {
throw new Error('Cannot get service schema. No mapping provided');
}
const service = this._component.servicesMapping.find((definition) =>
name === definition.schema.getName()
&&
semver.satisfies(definition.schema.getVersion(), version)
);
if (service) {
return service.schema;
}
throw new Error(`Cannot resolve schema for Service: ${name} (${version})`);
}
/**
*
* @param {*} value
* @return {boolean}
*/
log(value, level) {
return this._component.log(value, level);
}
}
module.exports = Api;
|
/*
Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojo.DeferredList"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojo.DeferredList"] = true;
dojo.provide("dojo.DeferredList");
dojo.DeferredList = function(/*Array*/ list, /*Boolean?*/ fireOnOneCallback, /*Boolean?*/ fireOnOneErrback, /*Boolean?*/ consumeErrors, /*Function?*/ canceller){
// summary:
// Provides event handling for a group of Deferred objects.
// description:
// DeferredList takes an array of existing deferreds and returns a new deferred of its own
// this new deferred will typically have its callback fired when all of the deferreds in
// the given list have fired their own deferreds. The parameters `fireOnOneCallback` and
// fireOnOneErrback, will fire before all the deferreds as appropriate
//
// list:
// The list of deferreds to be synchronizied with this DeferredList
// fireOnOneCallback:
// Will cause the DeferredLists callback to be fired as soon as any
// of the deferreds in its list have been fired instead of waiting until
// the entire list has finished
// fireonOneErrback:
// Will cause the errback to fire upon any of the deferreds errback
// canceller:
// A deferred canceller function, see dojo.Deferred
var resultList = [];
dojo.Deferred.call(this);
var self = this;
if(list.length === 0 && !fireOnOneCallback){
this.resolve([0, []]);
}
var finished = 0;
dojo.forEach(list, function(item, i){
item.then(function(result){
if(fireOnOneCallback){
self.resolve([i, result]);
}else{
addResult(true, result);
}
},function(error){
if(fireOnOneErrback){
self.reject(error);
}else{
addResult(false, error);
}
if(consumeErrors){
return null;
}
throw error;
});
function addResult(succeeded, result){
resultList[i] = [succeeded, result];
finished++;
if(finished === list.length){
self.resolve(resultList);
}
}
});
};
dojo.DeferredList.prototype = new dojo.Deferred();
dojo.DeferredList.prototype.gatherResults= function(deferredList){
// summary:
// Gathers the results of the deferreds for packaging
// as the parameters to the Deferred Lists' callback
var d = new dojo.DeferredList(deferredList, false, true, false);
d.addCallback(function(results){
var ret = [];
dojo.forEach(results, function(result){
ret.push(result[1]);
});
return ret;
});
return d;
};
}
|
export const name = "Triangle by Angle and Orthocenter";
export const L = 3;
export const E = 6;
export const V = 1;
export const init = function() {
return this
.point("A", 0, 2)
.point("X", -1, 0)
.point("Y", 1, 0)
.ray("AX", "A", "X")
.ray("AY", "A", "Y")
.point("H", 0.2, 0)
.hide("X", "Y");
};
export const snapshot = function() {
return this.answer()
.perpendicular("BH", "H", "AY")
.intersection("B", "AX", "BH")
.line("AH", "A", "H")
.perpendicular("line-BC", "AH", "B")
.intersection("C", "line-BC", "AY")
.segment("AB", "A", "B")
.segment("AC", "A", "C")
.segment("BC", "B", "C")
.hide("AH", "BH", "line-BC");
};
export const solveL = function() {
return this.initFinish()
.perpendicular("BH", "H", "AY")
.nextStep()
.intersection("B", "AX", "BH")
.line("AH", "A", "H")
.nextStep()
.perpendicular("line-BC", "AH", "B")
.intersection("C", "line-BC", "AY")
.answer()
.segment("AB", "A", "B")
.segment("AC", "A", "C")
.segment("BC", "B", "C");
};
export const solveE = function() {
return this.initFinish()
.circle("circle-A", "A", "H")
.nextStep()
.point("P", "AY", 1)
.circle("circle-P", "P", "H")
.nextStep()
.intersection("D", "circle-A", "circle-P", "H")
.line("BH", "D", "H")
.nextStep()
.intersection("B", "AX", "BH")
.circle("circle-B", "B", "H")
.nextStep()
.intersection("E", "circle-A", "circle-B", "H")
.line("CH", "E", "H")
.nextStep()
.intersection("C", "CH", "AY")
.line("line-BC", "B", "C")
.answer()
.segment("AB", "A", "B")
.segment("AC", "A", "C")
.segment("BC", "B", "C");
};
|
angular.module('wiz.features.auth.settings')
.controller('SettingsCtrl', [
'$rootScope',
'$scope',
'$timeout',
'$state',
'settings',
'wizSettingsSvc',
'wizMenuSvc',
'STATUS',
function ($rootScope, $scope, $timeout, $state, settings, wizSettingsSvc, wizMenuSvc, STATUS) {
$scope.settings = settings;
$scope.STATUS = STATUS;
$scope.status = STATUS.idle;
$scope.openMenu = function () {
$rootScope.$broadcast('menu-open');
};
$scope.pages = [];
for (var i = 0; i < 20; i++) {
$scope.pages.push(i + 1);
}
$scope.save = function (form) {
$scope.submitted = true;
if (form.$valid) {
$scope.status = STATUS.loading;
wizSettingsSvc.updateSettings($scope.settings).then(function () {
$scope.status = STATUS.success;
$timeout(function () {
$scope.status = STATUS.idle;
}, 1500);
});
}
};
}
]); |
/*
*/
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */
'use strict';
var util = require('util');
var msRest = require('ms-rest');
var ServiceClient = msRest.ServiceClient;
var WebResource = msRest.WebResource;
var models = require('./models');
/**
* @class
* Initializes a new instance of the SwaggerPetstore class.
* @constructor
*
* @param {string} [baseUri] - The base URI of the service.
*
* @param {object} [options] - The parameter options
*
* @param {Array} [options.filters] - Filters to be added to the request pipeline
*
* @param {object} [options.requestOptions] - Options for the underlying request object
* {@link https://github.com/request/request#requestoptions-callback Options doc}
*
* @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy
*
*/
function SwaggerPetstore(baseUri, options) {
if (!options) options = {};
SwaggerPetstore['super_'].call(this, null, options);
this.baseUri = baseUri;
if (!this.baseUri) {
this.baseUri = 'http://petstore.swagger.io/v2';
}
this.models = models;
msRest.addSerializationMixin(this);
}
util.inherits(SwaggerPetstore, ServiceClient);
/**
* @summary Fake endpoint to test byte array in body parameter for adding a
* new pet to the store
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.body] Pet object in the form of byte array
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.addPetUsingByteArray = function (options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var body = (options && options.body !== undefined) ? options.body : undefined;
// Validate
try {
if (body !== null && body !== undefined && typeof body.valueOf() !== 'string') {
throw new Error('body must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'pet';
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
// Serialize Request
var requestContent = null;
var requestModel = null;
try {
if (body !== null && body !== undefined) {
var requestModelMapper = {
required: false,
serializedName: 'body',
type: {
name: 'String'
}
};
requestModel = client.serialize(requestModelMapper, body, 'body');
requestContent = JSON.stringify(requestModel);
}
} catch (error) {
var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' +
'payload - "%s"', error.message, util.inspect(body, {depth: null})));
return callback(serializationError);
}
httpRequest.body = requestContent;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 405) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Add a new pet to the store
*
* Adds a new pet to the store. You may receive an HTTP invalid input if your
* pet is invalid.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.body] Pet object that needs to be added to the
* store
*
* @param {number} [options.body.id] The id of the pet. A more detailed
* description of the id of the pet.
*
* @param {object} [options.body.category]
*
* @param {number} [options.body.category.id]
*
* @param {string} [options.body.category.name]
*
* @param {string} options.body.name
*
* @param {array} options.body.photoUrls
*
* @param {array} [options.body.tags]
*
* @param {string} [options.body.status] pet status in the store. Possible
* values include: 'available', 'pending', 'sold'
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.addPet = function (options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var body = (options && options.body !== undefined) ? options.body : undefined;
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'pet';
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
// Serialize Request
var requestContent = null;
var requestModel = null;
try {
if (body !== null && body !== undefined) {
var requestModelMapper = new client.models['Pet']().mapper();
requestModel = client.serialize(requestModelMapper, body, 'body');
requestContent = JSON.stringify(requestModel);
}
} catch (error) {
var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' +
'payload - "%s"', error.message, util.inspect(body, {depth: null})));
return callback(serializationError);
}
httpRequest.body = requestContent;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 405) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Update an existing pet
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.body] Pet object that needs to be added to the
* store
*
* @param {number} [options.body.id] The id of the pet. A more detailed
* description of the id of the pet.
*
* @param {object} [options.body.category]
*
* @param {number} [options.body.category.id]
*
* @param {string} [options.body.category.name]
*
* @param {string} options.body.name
*
* @param {array} options.body.photoUrls
*
* @param {array} [options.body.tags]
*
* @param {string} [options.body.status] pet status in the store. Possible
* values include: 'available', 'pending', 'sold'
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.updatePet = function (options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var body = (options && options.body !== undefined) ? options.body : undefined;
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'pet';
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'PUT';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
// Serialize Request
var requestContent = null;
var requestModel = null;
try {
if (body !== null && body !== undefined) {
var requestModelMapper = new client.models['Pet']().mapper();
requestModel = client.serialize(requestModelMapper, body, 'body');
requestContent = JSON.stringify(requestModel);
}
} catch (error) {
var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' +
'payload - "%s"', error.message, util.inspect(body, {depth: null})));
return callback(serializationError);
}
httpRequest.body = requestContent;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 405 && statusCode !== 404 && statusCode !== 400) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Finds Pets by status
*
* Multiple status values can be provided with comma seperated strings
*
* @param {object} [options] Optional Parameters.
*
* @param {array} [options.status] Status values that need to be considered
* for filter
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {array} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.findPetsByStatus = function (options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var status = (options && options.status !== undefined) ? options.status : available;
// Validate
try {
if (util.isArray(status)) {
for (var i = 0; i < status.length; i++) {
if (status[i] !== null && status[i] !== undefined && typeof status[i].valueOf() !== 'string') {
throw new Error('status[i] must be of type string.');
}
}
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'pet/findByStatus';
var queryParameters = [];
if (status !== null && status !== undefined) {
queryParameters.push('status=' + encodeURIComponent(status.join(',')));
}
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200 && statusCode !== 400) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = {
required: false,
serializedName: 'parsedResponse',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'PetElementType',
type: {
name: 'Composite',
className: 'Pet'
}
}
}
};
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Finds Pets by tags
*
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
* tag3 for testing.
*
* @param {object} [options] Optional Parameters.
*
* @param {array} [options.tags] Tags to filter by
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {array} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.findPetsByTags = function (options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var tags = (options && options.tags !== undefined) ? options.tags : undefined;
// Validate
try {
if (util.isArray(tags)) {
for (var i = 0; i < tags.length; i++) {
if (tags[i] !== null && tags[i] !== undefined && typeof tags[i].valueOf() !== 'string') {
throw new Error('tags[i] must be of type string.');
}
}
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'pet/findByTags';
var queryParameters = [];
if (tags !== null && tags !== undefined) {
queryParameters.push('tags=' + encodeURIComponent(tags.join(',')));
}
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200 && statusCode !== 400) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = {
required: false,
serializedName: 'parsedResponse',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'PetElementType',
type: {
name: 'Composite',
className: 'Pet'
}
}
}
};
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Fake endpoint to test byte array return by 'Find pet by ID'
*
* Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error
* conditions
*
* @param {number} petId ID of pet that needs to be fetched
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {string} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.findPetsWithByteArray = function (petId, options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (petId === null || petId === undefined || typeof petId !== 'number') {
throw new Error('petId cannot be null or undefined and it must be of type number.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'pet/{petId}';
requestUrl = requestUrl.replace('{petId}', encodeURIComponent(petId.toString()));
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 404 && statusCode !== 200 && statusCode !== 400) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = {
required: false,
serializedName: 'parsedResponse',
type: {
name: 'String'
}
};
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Find pet by ID
*
* Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error
* conditions
*
* @param {number} petId ID of pet that needs to be fetched
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object.
* See {@link Pet} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.getPetById = function (petId, options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (petId === null || petId === undefined || typeof petId !== 'number') {
throw new Error('petId cannot be null or undefined and it must be of type number.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'pet/{petId}';
requestUrl = requestUrl.replace('{petId}', encodeURIComponent(petId.toString()));
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 404 && statusCode !== 200 && statusCode !== 400) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = new client.models['Pet']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Updates a pet in the store with form data
*
* @param {string} petId ID of pet that needs to be updated
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.name] Updated name of the pet
*
* @param {string} [options.status] Updated status of the pet
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.updatePetWithForm = function (petId, options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var name = (options && options.name !== undefined) ? options.name : undefined;
var status = (options && options.status !== undefined) ? options.status : undefined;
// Validate
try {
if (petId === null || petId === undefined || typeof petId.valueOf() !== 'string') {
throw new Error('petId cannot be null or undefined and it must be of type string.');
}
if (name !== null && name !== undefined && typeof name.valueOf() !== 'string') {
throw new Error('name must be of type string.');
}
if (status !== null && status !== undefined && typeof status.valueOf() !== 'string') {
throw new Error('status must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'pet/{petId}';
requestUrl = requestUrl.replace('{petId}', encodeURIComponent(petId));
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/x-www-form-urlencoded';
// Serialize Request
var formData = {};
if (name !== undefined && name !== null) {
formData['name'] = name;
}
if (status !== undefined && status !== null) {
formData['status'] = status;
}
httpRequest.formData = formData;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 405) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Deletes a pet
*
* @param {number} petId Pet id to delete
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.apiKey]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.deletePet = function (petId, options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var apiKey = (options && options.apiKey !== undefined) ? options.apiKey : undefined;
// Validate
try {
if (apiKey !== null && apiKey !== undefined && typeof apiKey.valueOf() !== 'string') {
throw new Error('apiKey must be of type string.');
}
if (petId === null || petId === undefined || typeof petId !== 'number') {
throw new Error('petId cannot be null or undefined and it must be of type number.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'pet/{petId}';
requestUrl = requestUrl.replace('{petId}', encodeURIComponent(petId.toString()));
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'DELETE';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if (apiKey !== undefined && apiKey !== null) {
httpRequest.headers['api_key'] = apiKey;
}
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 400) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* @summary uploads an image
*
* @param {number} petId ID of pet to update
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.additionalMetadata] Additional data to pass to
* server
*
* @param {object} [options.file] file to upload
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.uploadFile = function (petId, options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var additionalMetadata = (options && options.additionalMetadata !== undefined) ? options.additionalMetadata : undefined;
var file = (options && options.file !== undefined) ? options.file : undefined;
// Validate
try {
if (petId === null || petId === undefined || typeof petId !== 'number') {
throw new Error('petId cannot be null or undefined and it must be of type number.');
}
if (additionalMetadata !== null && additionalMetadata !== undefined && typeof additionalMetadata.valueOf() !== 'string') {
throw new Error('additionalMetadata must be of type string.');
}
if (file !== null && file !== undefined && typeof file.valueOf() !== 'object') {
throw new Error('file must be of type object.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'pet/{petId}/uploadImage';
requestUrl = requestUrl.replace('{petId}', encodeURIComponent(petId.toString()));
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'multipart/form-data';
// Serialize Request
var formData = {};
if (additionalMetadata !== undefined && additionalMetadata !== null) {
formData['additionalMetadata'] = additionalMetadata;
}
if (file !== undefined && file !== null) {
formData['file'] = file;
}
httpRequest.formData = formData;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode < 200 || statusCode >= 300) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Returns pet inventories by status
*
* Returns a map of status codes to quantities
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.getInventory = function (options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'store/inventory';
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = {
required: false,
serializedName: 'parsedResponse',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'NumberElementType',
type: {
name: 'Number'
}
}
}
};
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Place an order for a pet
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.body] order placed for purchasing the pet
*
* @param {number} [options.body.petId]
*
* @param {number} [options.body.quantity]
*
* @param {date} [options.body.shipDate]
*
* @param {string} [options.body.status] Order Status. Possible values
* include: 'placed', 'approved', 'delivered'
*
* @param {boolean} [options.body.complete]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object.
* See {@link Order} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.placeOrder = function (options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var body = (options && options.body !== undefined) ? options.body : undefined;
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'store/order';
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
// Serialize Request
var requestContent = null;
var requestModel = null;
try {
if (body !== null && body !== undefined) {
var requestModelMapper = new client.models['Order']().mapper();
requestModel = client.serialize(requestModelMapper, body, 'body');
requestContent = JSON.stringify(requestModel);
}
} catch (error) {
var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' +
'payload - "%s"', error.message, util.inspect(body, {depth: null})));
return callback(serializationError);
}
httpRequest.body = requestContent;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200 && statusCode !== 400) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = new client.models['Order']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Find purchase order by ID
*
* For valid response try integer IDs with value <= 5 or > 10. Other values
* will generated exceptions
*
* @param {string} orderId ID of pet that needs to be fetched
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object.
* See {@link Order} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.getOrderById = function (orderId, options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (orderId === null || orderId === undefined || typeof orderId.valueOf() !== 'string') {
throw new Error('orderId cannot be null or undefined and it must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'store/order/{orderId}';
requestUrl = requestUrl.replace('{orderId}', encodeURIComponent(orderId));
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 404 && statusCode !== 200 && statusCode !== 400) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = new client.models['Order']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Delete purchase order by ID
*
* For valid response try integer IDs with value < 1000. Anything above 1000
* or nonintegers will generate API errors
*
* @param {string} orderId ID of the order that needs to be deleted
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.deleteOrder = function (orderId, options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (orderId === null || orderId === undefined || typeof orderId.valueOf() !== 'string') {
throw new Error('orderId cannot be null or undefined and it must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'store/order/{orderId}';
requestUrl = requestUrl.replace('{orderId}', encodeURIComponent(orderId));
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'DELETE';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 404 && statusCode !== 400) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Create user
*
* This can only be done by the logged in user.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.body] Created user object
*
* @param {number} [options.body.id]
*
* @param {string} [options.body.username]
*
* @param {string} [options.body.firstName]
*
* @param {string} [options.body.lastName]
*
* @param {string} [options.body.email]
*
* @param {string} [options.body.password]
*
* @param {string} [options.body.phone]
*
* @param {number} [options.body.userStatus] User Status
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.createUser = function (options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var body = (options && options.body !== undefined) ? options.body : undefined;
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'user';
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
// Serialize Request
var requestContent = null;
var requestModel = null;
try {
if (body !== null && body !== undefined) {
var requestModelMapper = new client.models['User']().mapper();
requestModel = client.serialize(requestModelMapper, body, 'body');
requestContent = JSON.stringify(requestModel);
}
} catch (error) {
var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' +
'payload - "%s"', error.message, util.inspect(body, {depth: null})));
return callback(serializationError);
}
httpRequest.body = requestContent;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode < 200 || statusCode >= 300) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Creates list of users with given input array
*
* @param {object} [options] Optional Parameters.
*
* @param {array} [options.body] List of user object
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.createUsersWithArrayInput = function (options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var body = (options && options.body !== undefined) ? options.body : undefined;
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'user/createWithArray';
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
// Serialize Request
var requestContent = null;
var requestModel = null;
try {
if (body !== null && body !== undefined) {
var requestModelMapper = {
required: false,
serializedName: 'body',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'UserElementType',
type: {
name: 'Composite',
className: 'User'
}
}
}
};
requestModel = client.serialize(requestModelMapper, body, 'body');
requestContent = JSON.stringify(requestModel);
}
} catch (error) {
var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' +
'payload - "%s"', error.message, util.inspect(body, {depth: null})));
return callback(serializationError);
}
httpRequest.body = requestContent;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode < 200 || statusCode >= 300) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Creates list of users with given input array
*
* @param {object} [options] Optional Parameters.
*
* @param {array} [options.body] List of user object
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.createUsersWithListInput = function (options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var body = (options && options.body !== undefined) ? options.body : undefined;
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'user/createWithList';
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
// Serialize Request
var requestContent = null;
var requestModel = null;
try {
if (body !== null && body !== undefined) {
var requestModelMapper = {
required: false,
serializedName: 'body',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'UserElementType',
type: {
name: 'Composite',
className: 'User'
}
}
}
};
requestModel = client.serialize(requestModelMapper, body, 'body');
requestContent = JSON.stringify(requestModel);
}
} catch (error) {
var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' +
'payload - "%s"', error.message, util.inspect(body, {depth: null})));
return callback(serializationError);
}
httpRequest.body = requestContent;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode < 200 || statusCode >= 300) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Logs user into the system
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.username] The user name for login
*
* @param {string} [options.password] The password for login in clear text
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {string} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.loginUser = function (options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var username = (options && options.username !== undefined) ? options.username : undefined;
var password = (options && options.password !== undefined) ? options.password : undefined;
// Validate
try {
if (username !== null && username !== undefined && typeof username.valueOf() !== 'string') {
throw new Error('username must be of type string.');
}
if (password !== null && password !== undefined && typeof password.valueOf() !== 'string') {
throw new Error('password must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'user/login';
var queryParameters = [];
if (username !== null && username !== undefined) {
queryParameters.push('username=' + encodeURIComponent(username));
}
if (password !== null && password !== undefined) {
queryParameters.push('password=' + encodeURIComponent(password));
}
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200 && statusCode !== 400) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = {
required: false,
serializedName: 'parsedResponse',
type: {
name: 'String'
}
};
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Logs out current logged in user session
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.logoutUser = function (options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'user/logout';
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode < 200 || statusCode >= 300) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Get user by user name
*
* @param {string} username The name that needs to be fetched. Use user1 for
* testing.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object.
* See {@link User} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.getUserByName = function (username, options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (username === null || username === undefined || typeof username.valueOf() !== 'string') {
throw new Error('username cannot be null or undefined and it must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'user/{username}';
requestUrl = requestUrl.replace('{username}', encodeURIComponent(username));
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 404 && statusCode !== 200 && statusCode !== 400) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
var parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
var resultMapper = new client.models['User']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Updated user
*
* This can only be done by the logged in user.
*
* @param {string} username name that need to be deleted
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.body] Updated user object
*
* @param {number} [options.body.id]
*
* @param {string} [options.body.username]
*
* @param {string} [options.body.firstName]
*
* @param {string} [options.body.lastName]
*
* @param {string} [options.body.email]
*
* @param {string} [options.body.password]
*
* @param {string} [options.body.phone]
*
* @param {number} [options.body.userStatus] User Status
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.updateUser = function (username, options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
var body = (options && options.body !== undefined) ? options.body : undefined;
// Validate
try {
if (username === null || username === undefined || typeof username.valueOf() !== 'string') {
throw new Error('username cannot be null or undefined and it must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'user/{username}';
requestUrl = requestUrl.replace('{username}', encodeURIComponent(username));
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'PUT';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
// Serialize Request
var requestContent = null;
var requestModel = null;
try {
if (body !== null && body !== undefined) {
var requestModelMapper = new client.models['User']().mapper();
requestModel = client.serialize(requestModelMapper, body, 'body');
requestContent = JSON.stringify(requestModel);
}
} catch (error) {
var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' +
'payload - "%s"', error.message, util.inspect(body, {depth: null})));
return callback(serializationError);
}
httpRequest.body = requestContent;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 404 && statusCode !== 400) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* @summary Delete user
*
* This can only be done by the logged in user.
*
* @param {string} username The name that needs to be deleted
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SwaggerPetstore.prototype.deleteUser = function (username, options, callback) {
var client = this;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (username === null || username === undefined || typeof username.valueOf() !== 'string') {
throw new Error('username cannot be null or undefined and it must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var baseUrl = this.baseUri;
var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'user/{username}';
requestUrl = requestUrl.replace('{username}', encodeURIComponent(username));
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'DELETE';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 404 && statusCode !== 400) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
'- "%s" for the default response.', defaultError.message, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
module.exports = SwaggerPetstore;
|
// #docregion
(function(global) {
// map tells the System loader where to look for things
var map = {
'app': 'app', // 'dist',
'rxjs': 'node_modules/rxjs',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'@angular': 'node_modules/@angular'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { defaultExtension: 'js' },
};
var packageNames = [
'@angular/common',
'@angular/compiler',
'@angular/core',
'@angular/http',
'@angular/platform-browser',
'@angular/platform-browser-dynamic',
'@angular/router',
'@angular/router-deprecated',
'@angular/testing',
'@angular/upgrade',
];
// add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
packageNames.forEach(function(pkgName) {
packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});
var config = {
map: map,
packages: packages
}
// filterSystemConfig - index.html's chance to modify config before we register it.
if (global.filterSystemConfig) { global.filterSystemConfig(config); }
System.config(config);
})(this);
|
import Message from './Message';
/**
* Message class, used to send a message to multiple chats
*/
export default class BulkMessage extends Message {
/**
* Create a new message
* @param {object} properties Message properties, as defined by Telegram API
*/
constructor(properties = {}) {
super(properties);
this.chats = [];
}
/**
* Set multiple chat_id's for the message
* @param {number} chat
* @return {object} returns the message object
*/
to(...args) {
const chats = args.reduce((a, b) => a.concat(b), []);
this.chats = chats;
return this;
}
/**
* Send the message to all chats
* @param {Bot} bot
* @return {Promise} Resolved when the message is sent to all chats
*/
send(bot) {
const promises = this.chats.map(chat => {
const clone = Object.assign({}, this.properties);
const message = new Message(clone).to(chat);
return message.send(bot);
});
return Promise.all(promises);
}
}
|
import BaseHero from './baseHero'
import OrochiPowerHandler from './powers/heroPowers/orochi/aHandler';
export const heroName = 'Orochi';
export default class Waller extends BaseHero {
constructor(game, name, id) {
super(game, name, id, 'Orochi',
{speed:6, airSpeed:6, jumpStrength:300, rollGroundSpeed:8, rollAirSpeed:7},
{maxHealth:1200, maxMana:7500, manaGain:30},
OrochiPowerHandler);
}
}
|
import faker from 'faker';
const fakeData = {
invalidEmailUser: {
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
username: faker.name.firstName(),
email: 'wrong data',
password: faker.internet.password(),
roleID: 3,
},
invalidPasswordUser: {
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
username: faker.name.firstName(),
email: faker.internet.email(),
password: '',
roleID: 3,
},
adminUser: {
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
username: faker.name.firstName(),
email: faker.internet.email(),
password: faker.internet.password(),
roleID: 1,
},
firstRegularUser: {
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
username: faker.name.firstName(),
email: faker.internet.email(),
password: faker.internet.password(),
roleID: 3,
},
secondRegularUser: {
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
username: faker.name.firstName(),
email: faker.internet.email(),
password: faker.internet.password(),
roleID: 3,
},
thirdRegularUser: {
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
username: faker.name.firstName(),
email: faker.internet.email(),
password: faker.internet.password(),
roleID: 3,
},
emtptyTitleDocument: {
title: '',
content: faker.lorem.paragraphs(),
access: 'public',
},
emtptyContentDocument: {
title: faker.lorem.word(),
content: '',
access: 'public',
},
invalidRoleDocument: {
title: faker.lorem.word(),
content: faker.lorem.paragraphs(),
access: 'random',
},
firstDocument: {
title: faker.lorem.word(),
content: faker.lorem.paragraphs(),
access: 'public',
ownerID: 1,
roleID: 1,
},
secondDocument: {
title: faker.lorem.word(),
content: faker.lorem.paragraphs(),
access: 'private',
ownerID: 3,
roleID: 1,
},
thirdDocument: {
title: faker.lorem.word(),
content: faker.lorem.paragraphs(),
access: 'role',
ownerID: 1,
roleID: 1,
},
fourthDocument: {
title: faker.lorem.word(),
content: faker.lorem.paragraphs(),
access: 'role',
ownerID: 2,
roleID: 3
},
fifthDocument: {
title: faker.lorem.word(),
content: faker.lorem.paragraphs(),
access: 'private',
ownerID: 2,
roleID: 3,
},
sixthDocument: {
title: faker.lorem.word(),
content: faker.lorem.paragraphs(),
access: 'role',
ownerID: 4,
roleID: 3
},
seventhDocument: {
title: faker.lorem.word(),
content: faker.lorem.paragraphs(),
access: 'public',
ownerID: 2,
roleID: 3
},
eightDocument: {
title: faker.lorem.word(),
content: faker.lorem.paragraphs(),
access: 'role',
ownerID: 3,
roleID: 3
},
ninthDocument: {
title: faker.lorem.word(),
content: faker.lorem.paragraphs(),
access: 'private',
ownerID: 2,
roleID: 3,
},
tenthDocument: {
title: faker.lorem.word(),
content: faker.lorem.paragraphs(),
access: 'public',
ownerID: 2,
roleID: 3
},
adminRole: {
name: 'admin'
},
moderatorRole: {
name: 'moderator'
},
regularRole: {
name: 'regular'
},
invalidRole: {
name: '!nv @l!d'
},
emptyRole: {
name: ''
},
generateRandomUser(roleID) {
return {
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
username: faker.name.firstName(),
email: faker.internet.email(),
roleID,
password: faker.internet.password()
};
},
generateRandomRole(roleName) {
return {
name: roleName
};
},
generateRandomDocument(access) {
return {
title: faker.lorem.word(),
content: faker.lorem.paragraphs(),
access,
};
},
};
export default fakeData;
|
/** @flow */
import { INDEX_MODES } from "./constants";
import SearchIndex from "./SearchIndex";
import type { IndexMode } from "./constants";
import type { SearchApiIndex } from "../types";
type UidMap = {
[uid: string]: boolean
};
/**
* Synchronous client-side full-text search utility.
* Forked from JS search (github.com/bvaughn/js-search).
*/
export default class SearchUtility implements SearchApiIndex {
_caseSensitive: boolean;
_indexMode: IndexMode;
_matchAnyToken: boolean;
_searchIndex: SearchIndex;
_tokenizePattern: RegExp;
_uids: UidMap;
/**
* Constructor.
*
* @param indexMode See #setIndexMode
* @param tokenizePattern See #setTokenizePattern
* @param caseSensitive See #setCaseSensitive
* @param matchAnyToken See #setMatchAnyToken
*/
constructor(
{
caseSensitive = false,
indexMode = INDEX_MODES.ALL_SUBSTRINGS,
matchAnyToken = false,
tokenizePattern = /\s+/
}: {
caseSensitive?: boolean,
indexMode?: IndexMode,
matchAnyToken?: boolean,
tokenizePattern?: RegExp
} = {}
) {
this._caseSensitive = caseSensitive;
this._indexMode = indexMode;
this._matchAnyToken = matchAnyToken;
this._tokenizePattern = tokenizePattern;
this._searchIndex = new SearchIndex();
this._uids = {};
}
/**
* Returns a constant representing the current case-sensitive bit.
*/
getCaseSensitive(): boolean {
return this._caseSensitive;
}
/**
* Returns a constant representing the current index mode.
*/
getIndexMode(): string {
return this._indexMode;
}
/**
* Returns a constant representing the current match-any-token bit.
*/
getMatchAnyToken(): boolean {
return this._matchAnyToken;
}
/**
* Returns a constant representing the current tokenize pattern.
*/
getTokenizePattern(): RegExp {
return this._tokenizePattern;
}
/**
* Adds or updates a uid in the search index and associates it with the specified text.
* Note that at this time uids can only be added or updated in the index, not removed.
*
* @param uid Uniquely identifies a searchable object
* @param text Text to associate with uid
*/
indexDocument = (uid: any, text: string): SearchApiIndex => {
this._uids[uid] = true;
var fieldTokens: Array<string> = this._tokenize(this._sanitize(text));
fieldTokens.forEach(fieldToken => {
var expandedTokens: Array<string> = this._expandToken(fieldToken);
expandedTokens.forEach(expandedToken => {
this._searchIndex.indexDocument(expandedToken, uid);
});
});
return this;
};
/**
* Searches the current index for the specified query text.
* Only uids matching all of the words within the text will be accepted,
* unless matchAny is set to true.
* If an empty query string is provided all indexed uids will be returned.
*
* Document searches are case-insensitive by default (e.g. "search" will match "Search").
* Document searches use substring matching by default (e.g. "na" and "me" will both match "name").
*
* @param query Searchable query text
* @return Array of uids
*/
search = (query: string): Array<any> => {
if (!query) {
return Object.keys(this._uids);
} else {
var tokens: Array<string> = this._tokenize(this._sanitize(query));
return this._searchIndex.search(tokens, this._matchAnyToken);
}
};
/**
* Sets a new case-sensitive bit
*/
setCaseSensitive(caseSensitive: boolean): void {
this._caseSensitive = caseSensitive;
}
/**
* Sets a new index mode.
* See util/constants/INDEX_MODES
*/
setIndexMode(indexMode: IndexMode): void {
if (Object.keys(this._uids).length > 0) {
throw Error(
"indexMode cannot be changed once documents have been indexed"
);
}
this._indexMode = indexMode;
}
/**
* Sets a new match-any-token bit
*/
setMatchAnyToken(matchAnyToken: boolean): void {
this._matchAnyToken = matchAnyToken;
}
/**
* Sets a new tokenize pattern (regular expression)
*/
setTokenizePattern(pattern: RegExp): void {
this._tokenizePattern = pattern;
}
/**
* Added to make class adhere to interface. Add cleanup code as needed.
*/
terminate = () => {};
/**
* Index strategy based on 'all-substrings-index-strategy.ts' in github.com/bvaughn/js-search/
*
* @private
*/
_expandToken(token: string): Array<string> {
switch (this._indexMode) {
case INDEX_MODES.EXACT_WORDS:
return [token];
case INDEX_MODES.PREFIXES:
return this._expandPrefixTokens(token);
case INDEX_MODES.ALL_SUBSTRINGS:
default:
return this._expandAllSubstringTokens(token);
}
}
_expandAllSubstringTokens(token: string): Array<string> {
const expandedTokens = [];
// String.prototype.charAt() may return surrogate halves instead of whole characters.
// When this happens in the context of a web-worker it can cause Chrome to crash.
// Catching the error is a simple solution for now; in the future I may try to better support non-BMP characters.
// Resources:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt
// https://mathiasbynens.be/notes/javascript-unicode
try {
for (let i = 0, length = token.length; i < length; ++i) {
let substring: string = "";
for (let j = i; j < length; ++j) {
substring += token.charAt(j);
expandedTokens.push(substring);
}
}
} catch (error) {
console.error(`Unable to parse token "${token}" ${error}`);
}
return expandedTokens;
}
_expandPrefixTokens(token: string): Array<string> {
const expandedTokens = [];
// String.prototype.charAt() may return surrogate halves instead of whole characters.
// When this happens in the context of a web-worker it can cause Chrome to crash.
// Catching the error is a simple solution for now; in the future I may try to better support non-BMP characters.
// Resources:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt
// https://mathiasbynens.be/notes/javascript-unicode
try {
for (let i = 0, length = token.length; i < length; ++i) {
expandedTokens.push(token.substr(0, i + 1));
}
} catch (error) {
console.error(`Unable to parse token "${token}" ${error}`);
}
return expandedTokens;
}
/**
* @private
*/
_sanitize(string: string): string {
return this._caseSensitive
? string.trim()
: string.trim().toLocaleLowerCase();
}
/**
* @private
*/
_tokenize(text: string): Array<string> {
return text.split(this._tokenizePattern).filter(text => text); // Remove empty tokens
}
}
|
// ==========================================================================
// Project: TestApp
// ==========================================================================
/*globals TestApp */
TestApp.main = function main() {
TestApp.getPath('mainPage.mainPane').append() ;
} ;
function main() { TestApp.main(); }
|
class AbstractSection {
constructor() {
this.id = "";
this.active = true;
this.modifiers = [];
this._constructorName = "AbstractSection";
}
getConcreteSections(state) {
logit("Sections need to implement getConcreteSections() " + this._constructorName + "<br />");
return [];
}
concretizeSections(sections, state) {
// Make sure that we only return concrete sections
let result = sections;
let done = false;
do {
done = true;
for (let i = 0; i < result.length; i++) {
if (!(result[i] instanceof Section)) {
done = false;
}
}
if (!done) {
const newResult = [];
for (let i = 0; i < result.length; i++) {
const list = result[i].getConcreteSections(state);
addAll(newResult, list);
}
result = newResult;
}
} while (!done);
return result;
}
renderBatch(state) {
const sections = this.getConcreteSections(state);
for (let concreteSection of sections) {
if (!(concreteSection instanceof Section)) {
logit("Failed to concretize section... " + concreteSection._constructorName + " <br />");
continue;
}
for (const sm of this.modifiers) {
concreteSection = sm.modifySection(concreteSection, state);
}
state.oldSectionTime = state.sectionTime;
if (concreteSection.active) {
concreteSection.renderBatch(state);
}
for (const sm of this.modifiers) {
sm.beforeSectionFinalized(concreteSection, state);
}
for (const sm of this.modifiers) {
sm.sectionRendered(concreteSection, state);
}
}
}
}
class SectionReference extends AbstractSection{
constructor(sectionId) {
super()
this.section = sectionId ? sectionId : "";
this._constructorName = "SectionReference";
}
getConcreteSections(state) {
const theSectionId = getValueOrExpressionValue(this, "section", state.module);
const section = state.module.getSection(theSectionId);
if (!section) {
logit("Could not find section " + theSectionId + "<br />");
return [];
}
const result = this.concretizeSections([section], state);
return result;
}
}
const SectionTempoMode = {
CONSTANT: 0,
CHANGE_CONTROL_CHANNEL: 1,
CONTROL_CHANNEL: 2
};
class Section extends AbstractSection {
constructor() {
super()
this.harmonicRythm = "";
this.voiceLinePlanner = "";
this.figurationPlanner = "";
this.tempoMode = SectionTempoMode.CONSTANT;
this.tempo = 60.0;
this.tempoChannel = "";
this.voiceLines = [];
this.renderLines = [];
this.controlLines = [];
this.suspAntStrategies = [];
this._constructorName = "Section";
}
getConcreteSections(state) {
return [this];
}
addVoiceLine(e) {
this.voiceLines.push(e);
return this;
}
addRenderLine(e) {
this.renderLines.push(e);
return this;
}
addControlLine(e) {
this.controlLines.push(e);
return this;
}
addModifier(e) {
this.modifiers.push(e);
return this;
}
getVoiceLine(id) {
return getObjectWithId(id, this.voiceLines);
}
generateVoiceLineHarmonies(chr, voiceLines, module) {
const result = {};
for (const voiceLine of voiceLines) {
let strategy = null;
for (const s of this.suspAntStrategies) {
if (arrayContains(s.voiceLines, voiceLine.id)) {
strategy = s;
break;
}
}
if (strategy) {
result[voiceLine.id] = strategy.createVoiceLineHarmony(voiceLine, chr, module);
// logit("voice line harmonies: " + valueToJson(result).join("") + "<br />");
}
}
return result;
}
planVoices(chr, voiceLines, module) {
const result = [];
if (this.voiceLinePlanner) {
const theVoiceLinePlannerId = getValueOrExpressionValue(this, "voiceLinePlanner", module);
const planner = module.getVoiceLinePlanner(theVoiceLinePlannerId);
if (!planner) {
logit("Could not find voice line planner '" + theVoiceLinePlannerId + "'<br />");
}
else {
planner.planVoices(voiceLines, chr, module, result);
}
}
else {
for (const line of voiceLines) {
if (line instanceof DoubledVoiceLine) {
// Doubled voice lines are dealt with when there are only ConstantVoiceLineElements (and undefined) left
continue;
}
const lineElements = line.getSingleStepVoiceLineElements(chr, module);
const newLine = new ConstantVoiceLine();
newLine.id = line.id; // So we can find it later by using the same
// original name
for (const e of lineElements) {
if (e instanceof ConstantVoiceLineElement || e instanceof UndefinedVoiceLineElement) {
newLine.add(e);
}
else {
logit("Only supports Constant voice line elements when no voice line planner is selected");
}
}
result.push(newLine);
}
}
// After all the planning is done, take care of the voice lines that are derived from other lines
for (const line of voiceLines) {
if (line instanceof DoubledVoiceLine) {
const doubled = line.doubleVoiceLine(result);
if (doubled) {
result.add(doubled);
}
}
}
// logit("planned voices in section: " + result + "<br />");
return result;
}
renderBatch(state) {
if (!this.active) {
return;
}
// Need a place to store modified sections
state.section = this;
state.oldSectionTime = state.sectionTime;
for (const sm of this.modifiers) {
state.section = sm.modifySection(state.section, state);
}
const harmonyId = getValueOrExpressionValue(state.section, "harmonicRythm", state.module);
const harmony = state.module.getHarmony(harmonyId);
if (harmony) {
state.harmony = harmony;
const theTempo = getValueOrExpressionValue(state.section, "tempo", state.module);
const sectionTempoMode = this.tempoMode;
const harmonyElements = harmony.getConstantHarmonyElements(state.module);
const chr = new ConstantHarmonicRythm(harmonyElements);
// logit(" constant harmony in section: " + chr.get(0).tsNumerator);
// logit(harmonyElements);
state.constantHarmony = chr;
for (const sm of this.modifiers) {
state.constantHarmony = sm.modifyConstantHarmony(state.constantHarmony, state);
}
// Modify the voice line before planning
state.voiceLines = state.section.voiceLines;
// Plan the voices
state.plannedVoiceLines = this.planVoices(state.constantHarmony, state.voiceLines, state.module);
for (const sm of this.modifiers) {
state.plannedVoiceLines = sm.modifyPlannedVoiceLines(state.plannedVoiceLines, state);
}
let che = null
for (let i = 0; i < state.constantHarmony.getCount(); i++) {
che = state.constantHarmony.get(i);
for (const sm of che.sectionModifiers) {
state.plannedVoiceLines = sm.modifyPlannedVoiceLines(state.plannedVoiceLines, state);
}
}
// Generate voice line harmonies
state.voiceLineHarmonies = this.generateVoiceLineHarmonies(state.constantHarmony, state.plannedVoiceLines, state.module);
state.renderLines = state.section.renderLines;
state.controlLines = state.section.controlLines;
// Add section tempo
// logit("Setting tempo event " + state.sectionTempo + " <br />");
// logit("Rendering line " + i);
for (const line of state.renderLines) {
line.renderBatch(state);
}
for (const sm of che.sectionModifiers) {
sm.beforeControlRender(state);
}
perfTimer2.start();
// logit("fsdf " + state.controlLines.length);
for (const line of state.controlLines) {
line.renderBatch(state);
}
perfTimer2.pause();
for (const sm of che.sectionModifiers) {
sm.afterControlRender(state);
}
switch (sectionTempoMode) {
case SectionTempoMode.CONSTANT:
state.data.addEvent(new SetTempoEvent(theTempo, state.sectionTime));
break;
case SectionTempoMode.CHANGE_CONTROL_CHANNEL:
case SectionTempoMode.CONTROL_CHANNEL:
const tempoCh = state.module.getControlChannel(this.tempoChannel);
if (tempoCh) {
const slotData = state.controlSlotDatas[tempoCh.id];
if (slotData) {
const sectionLength = state.constantHarmony.getBeatLength();
const slotBeatFraction = 1.0 / tempoCh.slotsPerBeat;
let oldTempo = 0;
for (let i = 0; i < sectionLength; i++) {
for (let j = 0; j < tempoCh.slotsPerBeat; j++) {
const slot = i * tempoCh.slotsPerBeat + j;
const tempoValue = tempoCh.readDouble(slot, slotData);
const beat = i + slotBeatFraction * j;
const newTempo = Math.round(theTempo * tempoValue);
if (newTempo > 10 && newTempo != oldTempo) {
state.data.addEvent(new SetTempoEvent(newTempo, state.sectionTime + beat));
// logit("Setting tempo to " + newTempo + " value: " + tempoValue + " slot: " + slot);
oldTempo = newTempo;
}
else if (newTempo <= 10) {
logit("Tempo strange " + newTempo + " tempoValue:" + tempoValue + " slot: " + slot);
}
}
}
}
else {
const tempoValue = tempoCh.readDouble(0);
const newTempo = Math.round(theTempo * tempoValue);
state.data.addEvent(new SetTempoEvent(newTempo, state.sectionTime));
// logit("Could not find slot data for channel " + this.tempoChannel);
}
}
else {
logit("Could not find tempo channel " + tempoCh);
state.data.addEvent(new SetTempoEvent(theTempo, state.sectionTime));
}
break;
}
const beatLength = state.constantHarmony.getBeatLength();
for (const ch of state.module.controlChannels) {
let slotData = state.controlSlotDatas[ch.id];
if (!slotData) {
// logit("Could not find any slot data for " + ch.id);
slotData = ch.createSlotData(beatLength);
state.controlSlotDatas[ch.id] = slotData;
}
}
for (const ctrlCh in state.controlSlotDatas) {
const slotData = state.controlSlotDatas[ctrlCh];
const channel = state.module.getControlChannel(ctrlCh);
const ctrlEvents = channel.getControlEvents(slotData, state.sectionTime);
// logit("Got " + ctrlEvents.length + " control events from " + ctrlCh);
addAll(state.data.addEvents(ctrlEvents));
}
for (const sm of this.modifiers) {
sm.beforeSectionFinalized(state.section, state);
}
for (const sm of this.modifiers) {
sm.sectionRendered(state.section, state);
}
// Step forward the section time
state.sectionTime += state.constantHarmony.getBeatLength();
// logit("SEction time: " + state.sectionTime + " " + state.constantHarmony.getBeatLength());
state.controlSlotDatas = {};
}
else {
logit(" could not find harmony "
+ harmonyId);
}
}
}
|
const CSSFlatError = require('./error')
const postcss = require('postcss')
const _ = require('lodash')
const cssnano = require('cssnano')
const getSelectorName = require('./getSelectorName')
const getSelectorType = require('./getSelectorType')
const cacheLocalRuleInfo = {}
const parserPlugin = postcss.plugin('postcss-flat', (options) => {
const {
locals = {},
prefix = 'a',
atRulesConfig,
htmlClass = 'css-flat',
pseudoMap,
declPropMap,
declValueMap,
sourceMap,
inputMap,
} = options
const genMap = sourceMap && inputMap
const localsMap = _.invert(locals)
const localRuleMark = {}
return (css) => {
const exports = {}
// const globalRule = []
css.walkRules((rule) => {
let parentParams = 'normal'
let parentName = ''
if (rule.parent.type === 'atrule') {
parentName = rule.parent.name
if (parentName === 'supports' || parentName === 'media') {
parentParams = rule.parent.params
} else {
return
}
}
rule.selector.split(',').forEach((sel) => {
const selectorType = getSelectorType(sel, localsMap)
const { isGlobal, isClassSelector, selectorHalf = '' } = selectorType
if (isGlobal) {
const globalSel = _.trim(sel)
const cloneRule = rule.clone()
cloneRule.selector = globalSel
// globalRule.push(cloneRule)
} else if (isClassSelector) {
const className = sel.replace(/\.| /g, '').replace(selectorHalf, '')
rule.walkDecls(function (decl) {
const prop = decl.prop.replace('--sourceMap-', '')
const value = decl.value
const newClassName = getSelectorName(decl, {
parentName,
parentParams,
prefix,
atRulesConfig,
selectorHalf,
pseudoMap,
declPropMap,
declValueMap,
})
if (!cacheLocalRuleInfo[newClassName]) {
let propLen = 0
let priority = ''
if (prop[0] !== '-') {
propLen = prop.split('-').length
}
for (let i = 1; i < propLen; i++) {
priority += '.' + htmlClass
}
cacheLocalRuleInfo[newClassName] = {
prop,
value,
newClassName,
selectorHalf, // 伪类后缀
priority: priority + ' ',
parentParams,
}
}
localRuleMark[parentParams] = localRuleMark[parentParams] || {}
localRuleMark[parentParams][newClassName] = cacheLocalRuleInfo[newClassName]
const localsKey = localsMap[className]
exports[localsKey] = (exports[localsKey] || (genMap ? className : '')) + ' ' + newClassName
if (genMap) {
decl.prop = '--sourceMap-' + prop
decl.value = value
}
})
}
if (!genMap && !isGlobal) {
rule.remove()
}
})
})
css.walkAtRules(/media|supports/, rule => {
const atRulesConfigKey = ('@' + rule.name + rule.params).replace(/ /g, '')
for (let newClassName in localRuleMark[rule.params]) {
const { selectorHalf = '', priority: tempP, prop, value } = cacheLocalRuleInfo[newClassName]
const atRulePriority = (atRulesConfig[atRulesConfigKey] || {}).priority || ''
const priority = _.trim(atRulePriority + tempP) + ' '
rule.append(priority + '.' + newClassName + selectorHalf + '{' + prop + ':' + value + '}')
}
})
for (let newClassName in localRuleMark.normal) {
const { selectorHalf = '', priority, prop, value } = cacheLocalRuleInfo[newClassName]
const newSelector = priority + '.' + newClassName + selectorHalf
css.append(newSelector + '{' + prop + ':' + value + '}')
}
options.exports = exports
}
})
module.exports = function processCss(inputSource, inputMap, options, callback) {
const {
minimize,
atRules = [],
htmlClass = 'css-flat',
plugins = [],
sourceMap,
} = options.params || {}
const atRulesConfig = {}
atRules.forEach((atRule, i) => {
for (let key in atRule) {
const value = atRule[key]
atRulesConfig[key.replace(/ /g, '')] = {
suffix: value,
priority: Array(i + 1).fill('.' + htmlClass).join(''),
}
}
})
const parserOptions = _.assign({}, options.params, {
atRulesConfig,
locals: options.locals || {},
inputMap,
})
const pipeline = postcss([
cssnano({
zindex: false,
normalizeUrl: false,
discardUnused: false,
mergeIdents: false,
autoprefixer: false,
reduceTransforms: false,
}),
parserPlugin(parserOptions),
].concat(plugins))
if (minimize) {
const minimizeOptions = _.assign({}, minimize)
;['zindex', 'normalizeUrl', 'discardUnused', 'mergeIdents', 'reduceIdents', 'autoprefixer'].forEach((name) => {
if (typeof minimizeOptions[name] === 'undefined')
minimizeOptions[name] = false
})
pipeline.use(cssnano(minimizeOptions))
}
pipeline.process(inputSource, {
from: '/css-flat-loader!' + options.from,
to: options.to,
map: sourceMap ? {
prev: inputMap,
sourcesContent: true,
inline: false,
annotation: false,
} : null,
}).then(function (result) {
callback(null, {
source: result.css,
map: result.map && result.map.toJSON(),
exports: parserOptions.exports,
})
}).catch((err) => {
console.log(err)
if (err.name === 'CssSyntaxError') {
callback(new CSSFlatError(err))
} else {
callback(err)
}
})
}
|
class MCProcessActionsComponentController {
/*@ngInject*/
constructor(selectItems) {
this.selectItems = selectItems;
this.state = {
createSampleName: '',
process: null,
items: [
{
action: 'create',
kind: 'sample',
files: [],
samples: [],
}
],
};
}
$onChanges(changes) {
if (changes.process) {
this.state.process = angular.copy(changes.process.currentValue);
console.log('process', this.state.process);
this.state.createSampleName = '';
if (this.state.process.samples.length || this.state.process.files.length) {
this.state.items = [];
this.buildExistingActions();
}
}
}
buildExistingActions() {
this.buildExistingSamplesActions();
this.buildExistingFilesActions();
}
buildExistingSamplesActions() {
// Map the in/out direction for the samples. Samples will either appear once with a direction of
// in (use sample) or out (create sample). If a sample appears twice then one of the version has
// a in direction and the other an our direction. These are transformed samples. The code below
// is for consolidating samples to a particular set of directions.
let sampleStates = {};
this.state.process.samples.forEach(s => {
if (!_.has(sampleStates, s.sample_id)) {
sampleStates[s.sample_id] = {
action: s.direction === 'out' ? 'create' : 'use',
name: s.name,
};
} else {
// We have already seen this sample. If a sample appears twice then it must be
// a sample that is transformed.
sampleStates[s.sample_id].action = 'transform';
}
});
// Now that we have all sample directions fill out the items list to contain these
// entries.
_.values(sampleStates).forEach(s => {
this.state.items.push({
action: s.action,
kind: 'sample',
samples: [s],
files: [],
});
});
}
buildExistingFilesActions() {
this.state.process.files.forEach(f => {
this.state.items.push({
action: this.mapFileDirectionToAction(f.direction),
kind: 'file',
samples: [],
files: [f],
});
});
}
mapFileDirectionToAction(direction) {
switch (direction) {
case 'in':
return 'use';
case 'out':
return 'create';
default:
// direction should be blank, default to use
return 'use';
}
}
addNewAction() {
this.state.items.push({
action: 'create',
kind: 'sample',
item: '',
files: [],
samples: [],
});
}
delete(index) {
if (index === 0) {
this.state.items[0].action = 'create';
this.state.items[0].kind = 'sample';
this.state.items[0].files.length = 0;
this.state.items[0].samples = [];
} else {
this.state.items.splice(index, 1);
}
}
addCreateSample(item) {
if (this.state.createSampleName !== '') {
this.onCreateSample({sample: this.state.createSampleName});
item.samples.push({name: angular.copy(this.state.createSampleName)});
this.state.createSampleName = '';
}
}
selectFiles(item) {
this.onSelectFiles().then(selected => {
console.log('selected files =', selected.files);
item.files = [];
selected.files.forEach(file => {
item.files.push(file);
});
});
}
selectSamples(item) {
this.onSelectSamples().then(selected => {
item.samples = [];
selected.samples.forEach(sample => {
sample.versions.filter(s => s.selected).forEach(s => {
// Name in versions is the process name, we want the sample name
console.log('s', s);
s.name = sample.name;
item.samples.push(s);
});
});
let samples = item.samples.map(s => ({sample_id: s.sample_id, property_set_id: s.property_set_id}));
return this.onAddSamples({samples, transform: item.action === 'transform'});
});
}
}
angular.module('materialscommons').component('mcProcessActions', {
controller: MCProcessActionsComponentController,
template: require('./process-actions.html'),
bindings: {
process: '<',
onSelectSamples: '&',
onSelectFiles: '&',
onCreateSample: '&',
onDeleteSample: '&',
onAddSamples: '&',
onAddFile: '&',
onDeleteFile: '&',
}
}); |
"use strict";
let gulp = require('gulp');
let webpackStream = require('webpack-stream');
let nodemon = require('gulp-nodemon');
//let webpack2 = require("webpack");
let webpackConfig = {
devtool: "source-map",
output: {
filename: "app.js"
},
module :{
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: "babel"
},
{
test: /\.css$/,
loaders: ["style-loader", "css-loader"]
},
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' }
]
}
};
let webpack2Config = {
devtool: "source-map",
output: {
filename: "app.js"
}
};
gulp.task("compile:client", function(){
return gulp.src('./client/index.jsx')
.pipe(webpackStream(webpackConfig))
.pipe(gulp.dest('public/js/'));
});
gulp.task("watch:client", function(){
return gulp.src('./client/index.jsx')
.pipe(webpackStream(Object.assign(webpackConfig, {watch:true})))
.pipe(gulp.dest('public/js/'));
});
gulp.task("watch:app", function(){
var stream = nodemon({
script: './app.js',
ext: 'js',
ignore: ["client/*", "public/*"]
});
stream
.on('crash', function(){
stream.emit('restart', 10);
})
});
gulp.task('watch', ['watch:client', 'watch:app']); |
const gulp = require('gulp');
const plugins = require('gulp-load-plugins')();
const pngquant = require('imagemin-pngquant');
const browserSync = require('browser-sync');
const jsDir = [
'./js/*.js',
'./js/render/*.js',
'./js/data/*.js',
'./js/admin/*.js'
];
gulp.task('css', () => {
gulp.src('./scss/*.scss')
.pipe(plugins.sourcemaps.init())
.pipe(plugins.sass({outputStyle: 'compressed'}).on('error', plugins.sass.logError))
.pipe(plugins.sourcemaps.write('./'))
.pipe(gulp.dest('./dist/css'));
});
gulp.task('js', () => {
gulp.src(jsDir)
.pipe(plugins.sourcemaps.init())
.pipe(plugins.uglify())
.pipe(plugins.sourcemaps.write('./'))
.pipe(gulp.dest('./dist/js'));
});
gulp.task('img', () => {
gulp.src('./img/*.{png,jpg,svg,gif}')
.pipe(
plugins.cache(
plugins.imagemin({
optimizationLevel: 5,
progressive: true,
interlaced: true,
multipass: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
})
)
)
.pipe(gulp.dest('./dist/img'));
});
gulp.task('font', () => {
gulp.src('./font/*')
.pipe(gulp.dest('./dist/font'));
});
gulp.task('css-watch', ['css'], browserSync.reload);
gulp.task('js-watch', ['js'], browserSync.reload);
gulp.task('img-watch', ['img'], browserSync.reload);
gulp.task('server', ['css', 'js', 'img', 'font'], () => {
browserSync.init({
server: './'
});
gulp.watch(jsDir, ['js-watch']);
gulp.watch('./scss/*.scss', ['css-watch']);
gulp.watch('./img/*.{png,jpg,svg,gif}', ['img-watch']);
gulp.watch('./index.html').on('change', browserSync.reload);
});
gulp.task('default', ['server']); |
define('dojorama/layers/nls/global-stuff_nb',{
'dojorama/ui/_global/widget/nls/FooterWidget':{}
,
'dojorama/ui/_global/widget/nls/NavigationWidget':{"labelHome":"Dojorama","labelStorage":"Storage","labelReleaseIndex":"Releases"}
}); |
const fs = require("fs");
const path = require("path");
module.exports = {
collectCoverageFrom: ["packages/*/src/**/*.js", "!**/*.ts.js"],
coverageDirectory: "coverage",
coverageReporters: ["html", "lcov", "text"],
coverageThreshold: {
global: {
statements: 80,
branches: 75,
functions: 85,
lines: 85
}
},
globals: {
usingJSDOM: true,
usingJest: true
},
setupFiles: [
"<rootDir>/scripts/test/requestAnimationFrame.js"
],
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json"],
moduleNameMapper: {
"^mangojuice-core(.*)": "<rootDir>/packages/mangojuice-core/src$1",
"^mangojuice-lazy": "<rootDir>/packages/mangojuice-lazy/src",
"^mangojuice-preact": "<rootDir>/packages/mangojuice-preact/src",
"^mangojuice-inferno": "<rootDir>/packages/mangojuice-inferno/src",
"^mangojuice-react-core/tests": "<rootDir>/packages/mangojuice-react-core/__tests__/tests.js",
"^mangojuice-react-core": "<rootDir>/packages/mangojuice-react-core/src",
"^mangojuice-react": "<rootDir>/packages/mangojuice-react/src",
"^mangojuice-test": "<rootDir>/packages/mangojuice-test/src"
},
rootDir: __dirname,
testMatch: [
"<rootDir>/packages/*/**/__tests__/**/*spec.js?(x)",
"<rootDir>/packages/*/**/__tests__/**/*spec.ts?(x)",
"<rootDir>/packages/*/**/__tests__/**/*spec.browser.js?(x)",
"<rootDir>/packages/*/**/__tests__/**/*spec.browser.ts?(x)"
],
transformIgnorePatterns: ["<rootDir>/node_modules/(?!lodash-es)"]
};
|
import { moduleFor, test } from 'ember-qunit';
moduleFor('controller:vote', 'Unit | Controller | vote', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
// Replace this with your real tests.
test('it exists', function(assert) {
let controller = this.subject();
assert.ok(controller);
});
|
$(function () {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
$('.tree li.parent_li > span').on('click', function (e) {
var children = $(this).parent('li.parent_li').find(' > ul > li');
if (children.is(":visible")) {
children.hide('fast');
$(this).attr('title', 'Expand this branch').find(' > i').addClass('glyphicon-plus-sign').removeClass('glyphicon-minus-sign');
} else {
children.show('fast');
$(this).attr('title', 'Collapse this branch').find(' > i').addClass('glyphicon-minus-sign').removeClass('glyphicon-plus-sign');
}
e.stopPropagation();
});
});
|
import browserTools from 'testcafe-browser-tools';
import { killBrowserProcess } from '../../../../utils/process';
import BrowserStarter from '../../utils/browser-starter';
const browserStarter = new BrowserStarter();
function buildChromeArgs (config, cdpPort, platformArgs, profileDir) {
return []
.concat(
cdpPort ? [`--remote-debugging-port=${cdpPort}`] : [],
!config.userProfile ? [`--user-data-dir=${profileDir.path}`] : [],
config.headless ? ['--headless'] : [],
config.userArgs ? [config.userArgs] : [],
platformArgs ? [platformArgs] : []
)
.join(' ');
}
export async function start (pageUrl, { browserName, config, cdpPort, tempProfileDir }) {
const chromeInfo = await browserTools.getBrowserInfo(config.path || browserName);
const chromeOpenParameters = Object.assign({}, chromeInfo);
chromeOpenParameters.cmd = buildChromeArgs(config, cdpPort, chromeOpenParameters.cmd, tempProfileDir);
await browserStarter.startBrowser(chromeOpenParameters, pageUrl);
}
export async function stop ({ browserId }) {
// NOTE: Chrome on Linux closes only after the second SIGTERM signall
if (!await killBrowserProcess(browserId))
await killBrowserProcess(browserId);
}
|
Package.describe({
name: 'evaisse:diacritics',
version: '1.0.1',
// Brief, one-line summary of the package.
summary: 'Removes accents / diacritics from strings, sentences, and paragraphs fast and efficiently.',
// URL to the Git repository containing the source code for this package.
git: 'https://github.com/evaisse/meteor-diacritics',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.1.0.2');
api.addFiles('diacritics.js');
api.export('Diacritics');
});
Package.onTest(function(api) {
api.use('tinytest');
api.use('evaisse:diacritics');
api.addFiles('diacritics-tests.js');
});
|
'use strict';
module.exports = function () {
var self = {
_ttyWrite : function (code, key) { this.ttyWrite.push({ code : code, key : key }); }
, _moveCursor : function (arg) { this.moveCursor.push(arg); }
, _wordLeft : function () { this.wordLeft++; }
, _wordRight : function () { this.wordRight++; }
, _deleteLeft : function () { this.deleteLeft++; }
, _deleteRight : function () { this.deleteRight++; }
, _deleteWordLeft : function () { this.deleteWordLeft++; }
, _deleteWordRight : function () { this.deleteWordRight++; }
, _deleteLineLeft : function () { this.deleteLineLeft++; }
, _deleteLineRight : function () { this.deleteLineRight++; }
, _historyPrev : function () { this.historyPrev++; }
, _historyNext : function () { this.historyNext++; }
, _line : function () { this.lines++; }
, reset: function () {
this.ttyWrite = [];
this.moveCursor = [];
this.wordLeft = 0;
this.wordRight = 0;
this.deleteLeft = 0;
this.deleteRight = 0;
this.deleteWordLeft = 0;
this.deleteWordRight = 0;
this.deleteLineLeft = 0;
this.deleteLineRight = 0;
this.historyPrev = 0;
this.historyNext = 0;
// rli itself has 'line', so we need to call it lines
this.lines = 0;
}
};
self.reset();
return self;
};
|
// 日時取得
var koyomi = require('../..').create();
var to = koyomi.toDatetime.bind(koyomi);
var eq = require('assert').deepEqual;
var D = require('../../date-extra.js');
koyomi.startMonth = 1;
koyomi.startWeek = '日';
eq(to('2015年10月8日 8時15分'), D(2015, 10, 8, 8, 15));
// さらに詳細なテストはutils/to-datetime.jsで |
import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { FormattedMessage } from 'react-intl';
// Import Style
import styles from './Header.css';
export function Header(props, context) {
const languageNodes = props.intl.enabledLanguages.map(
lang => <li key={lang} onClick={() => props.switchLanguage(lang)} className={lang === props.intl.locale ? styles.selected : ''}>{lang}</li>
);
const renderAddPostButton = context.router.isActive ? context.router.isActive() :
context.router.route.location.pathname === '/';
return (
<div className={styles.header}>
<div className={styles['language-switcher']}>
<ul>
<li><FormattedMessage id="switchLanguage" /></li>
{languageNodes}
</ul>
</div>
<div className={styles.content}>
<h1 className={styles['site-title']}>
<Link to="/" ><FormattedMessage id="siteTitle" /></Link>
</h1>
{
renderAddPostButton
? <a className={styles['add-post-button']} href="#" onClick={props.toggleAddPost}><FormattedMessage id="addPost" /></a>
: null
}
</div>
</div>
);
}
Header.contextTypes = {
router: PropTypes.object,
};
Header.propTypes = {
toggleAddPost: PropTypes.func.isRequired,
switchLanguage: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
export default Header;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.