<commit_before>(function () {
    'use strict';

    var owlCarouselDirective = function owlCarouselDirective() {
        return {
            restrict: 'A',
            templateUrl: '/app/project-details-page/owl-carousel-directive.html',
            scope: {
                images: '='
            },
            link: function (scope, element) {
                scope.$watch('images', function (images) {
                    if (images && images.length && images.length > 0) {
                        var slider = element.children(":first");

                        var options = slider.attr('data-plugin-options');

                        var defaults = {
                            items: images.length > 4 ? 4 : images.length,
                            itemsCustom: false,
                            itemsDesktop: [1199, 4],
                            itemsDesktopSmall: [980, 3],
                            itemsTablet: [768, 2],
                            itemsTabletSmall: false,
                            itemsMobile: [479, 1],
                            singleItem: true,
                            itemsScaleUp: false,

                            slideSpeed: 200,
                            paginationSpeed: 800,
                            rewindSpeed: 1000,

                            autoPlay: false,
                            stopOnHover: false,

                            navigation: false,
                            navigationText: [
                                                '',
                                                ''
                            ],
                            rewindNav: true,
                            scrollPerPage: false,

                            pagination: true,
                            paginationNumbers: false,

                            responsive: true,
                            responsiveRefreshRate: 200,
                            responsiveBaseWidth: window,

                            baseClass: "owl-carousel",
                            theme: "owl-theme",

                            lazyLoad: false,
                            lazyFollow: true,
                            lazyEffect: "fade",

                            autoHeight: false,

                            jsonPath: false,
                            jsonSuccess: false,

                            dragBeforeAnimFinish: true,
                            mouseDrag: true,
                            touchDrag: true,

                            transitionStyle: false,

                            addClassActive: false,

                            beforeUpdate: false,
                            afterUpdate: false,
                            beforeInit: false,
                            afterInit: false,
                            beforeMove: false,
                            afterMove: false,
                            afterAction: false,
                            startDragging: false,
                            afterLazyLoad: false
                        };

                        var config = jQuery.extend({}, defaults, options, slider.data("plugin-options"));
                        slider.owlCarousel(config).addClass("owl-carousel-init");

                        jQuery.extend(true, jQuery.magnificPopup.defaults, {
                            tClose: 'Close',
                            tLoading: 'Loading...',
                            gallery: {
                                tPrev: 'Previous',
                                tNext: 'Next',
                                tCounter: '%curr% / %total%'
                            },
                            image: {
                                tError: 'Image not loaded!'
                            },
                            ajax: {
                                tError: 'Content not loaded!'
                            }
                        });

                        config = {};
			            var defaultSettings = {
			                    type: 'image',
			                    fixedContentPos: false,
			                    fixedBgPos: false,
			                    mainClass: 'mfp-no-margins mfp-with-zoom',
			                    image: {
			                        verticalFit: true
			                    },

			                    zoom: {
			                        enabled: false,
			                        duration: 300
			                    },

			                    gallery: {
			                        enabled: false,
			                        navigateByImgClick: true,
			                        preload: [0, 1],
			                        arrowMarkup: '<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>',
			                        tPrev: 'Previou',
			                        tNext: 'Next',
			                        tCounter: '%curr% / %total%'
			                    },
			                };

                        if (slider.data("plugin-options")) {
                            config = jQuery.extend({}, defaultSettings, options, slider.data("plugin-options"));
                        }

                        jQuery(element).magnificPopup(config);
                    }
                });
            }
        };
    };

    angular
        .module('showcaseSystem.directives')
        .directive('owlCarousel', ['jQuery', owlCarouselDirective]);
}());<commit_msg>Project images fixed to 4 in owl carousel<commit_after>(function () {
    'use strict';

    var owlCarouselDirective = function owlCarouselDirective() {
        return {
            restrict: 'A',
            templateUrl: '/app/project-details-page/owl-carousel-directive.html',
            scope: {
                images: '='
            },
            link: function (scope, element) {
                scope.$watch('images', function (images) {
                    if (images && images.length && images.length > 0) {
                        var slider = element.children(":first");

                        var options = slider.attr('data-plugin-options');

                        var defaults = {
                            items: 4,
                            itemsCustom: false,
                            itemsDesktop: [1199, 4],
                            itemsDesktopSmall: [980, 3],
                            itemsTablet: [768, 2],
                            itemsTabletSmall: false,
                            itemsMobile: [479, 1],
                            singleItem: true,
                            itemsScaleUp: false,

                            slideSpeed: 200,
                            paginationSpeed: 800,
                            rewindSpeed: 1000,

                            autoPlay: false,
                            stopOnHover: false,

                            navigation: false,
                            navigationText: [
                                                '',
                                                ''
                            ],
                            rewindNav: true,
                            scrollPerPage: false,

                            pagination: true,
                            paginationNumbers: false,

                            responsive: true,
                            responsiveRefreshRate: 200,
                            responsiveBaseWidth: window,

                            baseClass: "owl-carousel",
                            theme: "owl-theme",

                            lazyLoad: false,
                            lazyFollow: true,
                            lazyEffect: "fade",

                            autoHeight: false,

                            jsonPath: false,
                            jsonSuccess: false,

                            dragBeforeAnimFinish: true,
                            mouseDrag: true,
                            touchDrag: true,

                            transitionStyle: false,

                            addClassActive: false,

                            beforeUpdate: false,
                            afterUpdate: false,
                            beforeInit: false,
                            afterInit: false,
                            beforeMove: false,
                            afterMove: false,
                            afterAction: false,
                            startDragging: false,
                            afterLazyLoad: false
                        };

                        var config = jQuery.extend({}, defaults, options, slider.data("plugin-options"));
                        slider.owlCarousel(config).addClass("owl-carousel-init");

                        jQuery.extend(true, jQuery.magnificPopup.defaults, {
                            tClose: 'Close',
                            tLoading: 'Loading...',
                            gallery: {
                                tPrev: 'Previous',
                                tNext: 'Next',
                                tCounter: '%curr% / %total%'
                            },
                            image: {
                                tError: 'Image not loaded!'
                            },
                            ajax: {
                                tError: 'Content not loaded!'
                            }
                        });

                        config = {};
			            var defaultSettings = {
			                    type: 'image',
			                    fixedContentPos: false,
			                    fixedBgPos: false,
			                    mainClass: 'mfp-no-margins mfp-with-zoom',
			                    image: {
			                        verticalFit: true
			                    },

			                    zoom: {
			                        enabled: false,
			                        duration: 300
			                    },

			                    gallery: {
			                        enabled: false,
			                        navigateByImgClick: true,
			                        preload: [0, 1],
			                        arrowMarkup: '<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>',
			                        tPrev: 'Previou',
			                        tNext: 'Next',
			                        tCounter: '%curr% / %total%'
			                    },
			                };

                        if (slider.data("plugin-options")) {
                            config = jQuery.extend({}, defaultSettings, options, slider.data("plugin-options"));
                        }

                        jQuery(element).magnificPopup(config);
                    }
                });
            }
        };
    };

    angular
        .module('showcaseSystem.directives')
        .directive('owlCarousel', ['jQuery', owlCarouselDirective]);
}());<|endoftext|>


<commit_before>module( "Popcorn Text Plugin" );

test( "Text", function() {

  var popped = Popcorn( "#video" ),
      expects = 10,
      count = 0,
      setupId,
      textdiv = document.getElementById( "textdiv" ),
      childElem;

  var strings = {
    PLAIN: "This is plain text",
    HTML: "
This is HTML text
",
    ESCAPED: "<p>This is <em>HTML</em> text</p>",
    MULTILINE_NO_BREAKS: "a\nb\r\nc",
    MULTILINE_BREAKS: "a
b
c"
  };

  expect( expects );

  function plus() {
    if ( ++count === expects ) {
      popped.on( "pause", function onPause(){
        this.off( "pause", onPause );
        this.destroy();
        start();
      }).currentTime( 0 ).pause();
    }
  }

  function injectString( s ) {
    var elem = document.createElement( "div" );
    elem.innerHTML = s;
    return elem.innerHTML;
  }

  stop();

  ok( "text" in popped, "text is a mehtod of the popped instance" );
  plus();

  equal( textdiv.childElementCount, 0, "initially, there is nothing inside textdiv" );
  plus();

  // Simple text
  popped.text( {
    start: 1,
    end: 3,
    text: strings.PLAIN,
    target: 'textdiv'
  } )
  .cue( 2, function() {
    equal( textdiv.childElementCount, 1, "textdiv now has two inner elements" );
    plus();

    childElem = textdiv.children[ 0 ];
    equal( childElem.innerHTML, strings.PLAIN, "textdiv correctly displaying plain text" );
    plus();
    equal( childElem.style.display, "inline", "textdiv is visible on the page" );
    plus();
  } )
  .cue( 4, function() {
    equal( childElem && childElem.style.display, "none", "textdiv is hidden again" );
    plus();

    popped.pause();
  } )

  // Setup the rest of events (first tests only want 1 text event)
  .on( "pause", function secondarySetup() {
    popped.off( "pause", secondarySetup )

    // HTML text, rendered as HTML
    .text( {
      start: 5,
      end: 7,
      text: strings.HTML,
      target: 'textdiv'
    } )
    .cue( 6, function() {
      equal(
        textdiv.children[ 1 ].innerHTML,
        injectString( strings.HTML ),
        "textdiv correctly displaying HTML text"
      );
      plus();
    } )

    // HTML text, escaped and rendered as plain text
    .text( {
      start: 8,
      end: 10,
      text: strings.HTML,
      escape: true,
      target: 'textdiv'
    } )
    .cue( 9, function() {
      equal(
        textdiv.children[ 2 ].innerHTML,
        injectString( strings.ESCAPED ),
        "textdiv correctly displaying escaped HTML text"
      );
      plus();
    } )

    // Multi-Line HTML text, escaped and rendered as plain text without breaks
    .text( {
      start: 11,
      end: 13,
      text: strings.MULTILINE_NO_BREAKS,
      target: 'textdiv'
    } )
    .cue( 12, function() {
      equal(
        textdiv.children[ 3 ].innerHTML,
        injectString( strings.MULTILINE_NO_BREAKS ),
        "textdiv correctly displaying multiline with no breaks"
      );
      plus();
    } )

    // Multi-Line HTML text, escaped and rendered as plain text with breaks
    .text( {
      start: 14,
      end: 16,
      text: strings.MULTILINE_NO_BREAKS,
      multiline: true,
      target: 'textdiv'
    } )
    .cue( 15, function() {
      equal(
        textdiv.children[ 4 ].innerHTML,
        injectString( strings.MULTILINE_BREAKS ),
        "textdiv correctly displaying multiline with breaks"
      );
      plus();

      // Test is done
      popped.pause();
    } );

    // Continue tests
    popped.play();
  } );

  // Start tests
  popped.play().volume( 0 );

});

asyncTest( "Subtitle", function() {

  var popped = Popcorn( "#video" ),
      popped2 = Popcorn( "#video2" ),
      expects = 11,
      count = 0,
      subTop = 9001,
      subLeft = 9001,
      subtitlediv,
      subtitle2div;

  expect( expects );

  function plus() {
    if ( ++count === expects ) {
      popped.destroy();
      start();
    }
  }

  popped.text({
    start: 0,
    end: 2,
    text: "this is the first subtitle of 2011"
  })
  .text({
    start: 2,
    end: 4,
    text: "this is the second subtitle of 2011"
  })
  .text({
    start: 5,
    end: 7,
    text: "this is the third subtitle of 2011"
  })
  .text({
    start: 7,
    end: 9,
    text: "instance one test"
  }).volume( 0 ).play();

  popped2.text({
    start: 7,
    end: 9,
    text: "instance two test"
  }).volume( 0 );

  subtitlediv = popped.container;
  subtitle2div = popped2.container;

  popped.cue( 1, function() {

    popped.on( "pause", function onPause() {
      this.off( "pause", onPause );
      equal( subtitlediv.children[ 0 ].innerHTML, "this is the first subtitle of 2011", "subtitle displaying correct information" );
      plus();

      // capturing location now, to check against later,
      // a subtitle must be displayed to get valid data
      // which is why we do this in cue
      subLeft = subtitlediv.style.left;
      subTop  = subtitlediv.style.top;

      // changing position
      this.media.style.position = "absolute";
      this.media.style.left = "400px";
      this.media.style.top = "600px";
      this.play();
    }).pause();

  });

  popped.cue( 3, function() {

    this.on( "pause", function onPause() {
      this.off( "pause", onPause );
      // check position of subtitle that should have moved with video,
      // a subtitle must be displayed to get valid data
      ok( subtitlediv.style.left !== subLeft, "subtitle's left position has changed" );
      plus();
      ok( subtitlediv.style.top !== subTop, "subtitle's top position has changed" );
      plus();

      // we know values have changed, but how accurate are they?
      // check values against the video's values
      // we need four checks because if we just check against video's position,
      // and video's position hasn't updated either, we'll pass when we should fail
      equal( subtitlediv.style.left, this.position().left + "px", "subtitle left position moved" );
      plus();
      ok( Popcorn.position( subtitlediv ).top > this.position().top, "subtitle top position moved" );
      plus();

      equal( subtitlediv.children[ 1 ].innerHTML, "this is the second subtitle of 2011", "subtitle displaying correct information" );
      plus();

      this.play();
    }).pause();
  });

  popped.cue( 4, function() {

    this.on( "pause", function onPause() {
      this.off( "pause", onPause );
      equal( subtitlediv.children[ 1 ].style.display, "none", "subtitle is hidden" );
      plus();

      this.play();
    }).pause();
  });

  popped.cue( 8, function() {

    this.on( "pause", function onPause() {
      this.off( "pause", onPause );
      popped2.currentTime( 8 ).play();

    }).pause();
  });

  popped2.cue( 8, function() {

    this.on( "pause", function onPause() {
      this.off( "pause", onPause );
      equal( subtitlediv.children[ 3 ].innerHTML, "instance one test", "subtitle displaying correct information" );
      plus();
      equal( subtitle2div.children[ 0 ].innerHTML, "instance two test", "subtitle displaying correct information" );
      plus();
      popped.play();

    }).pause();
  });

  popped.cue( 10, function() {
    ok( subtitlediv.children[ 0 ].style.display === "none" &&
        subtitlediv.children[ 1 ].style.display === "none" &&
        subtitlediv.children[ 2 ].style.display === "none", "All subtitles are no longer visible" );
    plus();

    this.on( "pause", function onPause() {
      this.off( "pause", onPause );
      this.removeTrackEvent( this.data.trackEvents.byStart[ 6 ]._id );

      // There were 4 subtitles, should be three now
      ok( subtitlediv.children.length === 3 , "subtitle div was destroyed"  );
      plus();

    }).pause();
  });
});

asyncTest( "Subtitle data tests", 1, function() {

  var popped = Popcorn( "#video" );

  popped.text({
    start: 0,
    end: 10
  });

  equal( popped.container.children[ 0 ].innerHTML, "", "text with no `text` attribute defaults to an empty string" );

  popped.destroy();
  start();
});

asyncTest( "Subtitle container creation tests", 3, function() {

  var popped = Popcorn( "#video" ),
      containerAtLoad = document.getElementById( "divThatDoesntExist" ),
      containerAfterParse;

  popped.text({
    start: 0,
    end: 10,
    text: "My Text",
    target: "divThatDoesntExist"
  });

  containerAfterParse = document.getElementById( "divThatDoesntExist" );

  equal( !!containerAtLoad, false, "Container doesn't exist initially" );
  equal( !!containerAfterParse, true, "Container exists now" );
  equal( containerAfterParse.children[ 0 ].innerHTML, "My Text", "Subtitle text displayed in created container" );

  popped.destroy();
  start();
});
<commit_msg>Make text plugin tests more friendly with Opera [t1089]<commit_after>module( "Popcorn Text Plugin" );

test( "Text", function() {

  var popped = Popcorn( "#video" ),
      expects = 10,
      count = 0,
      setupId,
      textdiv = document.getElementById( "textdiv" ),
      childElem;

  var strings = {
    PLAIN: "This is plain text",
    HTML: "
This is HTML text
",
    ESCAPED: "<p>This is <em>HTML</em> text</p>",
    MULTILINE_NO_BREAKS: "a\nb\r\nc",
    MULTILINE_BREAKS: "a
b
c"
  };

  expect( expects );

  function plus() {
    if ( ++count === expects ) {
      popped.on( "pause", function onPause(){
        this.off( "pause", onPause );
        this.destroy();
        start();
      }).pause();
    }
  }

  function injectString( s ) {
    var elem = document.createElement( "div" );
    elem.innerHTML = s;
    return elem.innerHTML;
  }

  stop();

  ok( "text" in popped, "text is a mehtod of the popped instance" );
  plus();

  equal( textdiv.childElementCount, 0, "initially, there is nothing inside textdiv" );
  plus();

  // Simple text
  popped.text( {
    start: 1,
    end: 3,
    text: strings.PLAIN,
    target: 'textdiv'
  } )
  .cue( 2, function() {
    equal( textdiv.childElementCount, 1, "textdiv now has two inner elements" );
    plus();

    childElem = textdiv.children[ 0 ];
    equal( childElem.innerHTML, strings.PLAIN, "textdiv correctly displaying plain text" );
    plus();
    equal( childElem.style.display, "inline", "textdiv is visible on the page" );
    plus();
  } )
  .cue( 4, function() {
    equal( childElem && childElem.style.display, "none", "textdiv is hidden again" );
    plus();

    popped.pause();
  } )

  // Setup the rest of events (first tests only want 1 text event)
  .on( "pause", function secondarySetup() {
    popped.off( "pause", secondarySetup )

    // HTML text, rendered as HTML
    .text( {
      start: 5,
      end: 7,
      text: strings.HTML,
      target: 'textdiv'
    } )
    .cue( 6, function() {
      equal(
        textdiv.children[ 1 ].innerHTML,
        injectString( strings.HTML ),
        "textdiv correctly displaying HTML text"
      );
      plus();
    } )

    // HTML text, escaped and rendered as plain text
    .text( {
      start: 8,
      end: 10,
      text: strings.HTML,
      escape: true,
      target: 'textdiv'
    } )
    .cue( 9, function() {
      equal(
        textdiv.children[ 2 ].innerHTML,
        injectString( strings.ESCAPED ),
        "textdiv correctly displaying escaped HTML text"
      );
      plus();
    } )

    // Multi-Line HTML text, escaped and rendered as plain text without breaks
    .text( {
      start: 11,
      end: 13,
      text: strings.MULTILINE_NO_BREAKS,
      target: 'textdiv'
    } )
    .cue( 12, function() {
      equal(
        textdiv.children[ 3 ].innerHTML,
        injectString( strings.MULTILINE_NO_BREAKS ),
        "textdiv correctly displaying multiline with no breaks"
      );
      plus();
    } )

    // Multi-Line HTML text, escaped and rendered as plain text with breaks
    .text( {
      start: 14,
      end: 16,
      text: strings.MULTILINE_NO_BREAKS,
      multiline: true,
      target: 'textdiv'
    } )
    .cue( 15, function() {
      equal(
        textdiv.children[ 4 ].innerHTML,
        injectString( strings.MULTILINE_BREAKS ),
        "textdiv correctly displaying multiline with breaks"
      );
      plus();

      // Test is done
      popped.pause();
    } );

    // Continue tests
    popped.play();
  } );

  // Start tests
  popped.play().volume( 0 );

});

asyncTest( "Subtitle", function() {

  var popped = Popcorn( "#video" ),
      popped2 = Popcorn( "#video2" ),
      expects = 11,
      count = 0,
      subTop = 9001,
      subLeft = 9001,
      subtitlediv,
      subtitle2div;

  expect( expects );

  function plus() {
    if ( ++count === expects ) {
      popped.destroy();
      start();
    }
  }

  popped.text({
    start: 0,
    end: 2,
    text: "this is the first subtitle of 2011"
  })
  .text({
    start: 2,
    end: 4,
    text: "this is the second subtitle of 2011"
  })
  .text({
    start: 5,
    end: 7,
    text: "this is the third subtitle of 2011"
  })
  .text({
    start: 7,
    end: 9,
    text: "instance one test"
  }).volume( 0 ).play();

  popped2.text({
    start: 7,
    end: 9,
    text: "instance two test"
  }).volume( 0 );

  subtitlediv = popped.container;
  subtitle2div = popped2.container;

  popped.cue( 1, function() {

    popped.on( "pause", function onPause() {
      this.off( "pause", onPause );
      equal( subtitlediv.children[ 0 ].innerHTML, "this is the first subtitle of 2011", "subtitle displaying correct information" );
      plus();

      // capturing location now, to check against later,
      // a subtitle must be displayed to get valid data
      // which is why we do this in cue
      subLeft = subtitlediv.style.left;
      subTop  = subtitlediv.style.top;

      // changing position
      this.media.style.position = "absolute";
      this.media.style.left = "400px";
      this.media.style.top = "600px";
      this.play();
    }).pause();

  });

  popped.cue( 3, function() {

    this.on( "pause", function onPause() {
      this.off( "pause", onPause );
      // check position of subtitle that should have moved with video,
      // a subtitle must be displayed to get valid data
      ok( subtitlediv.style.left !== subLeft, "subtitle's left position has changed" );
      plus();
      ok( subtitlediv.style.top !== subTop, "subtitle's top position has changed" );
      plus();

      // we know values have changed, but how accurate are they?
      // check values against the video's values
      // we need four checks because if we just check against video's position,
      // and video's position hasn't updated either, we'll pass when we should fail
      equal( subtitlediv.style.left, this.position().left + "px", "subtitle left position moved" );
      plus();
      ok( Popcorn.position( subtitlediv ).top > this.position().top, "subtitle top position moved" );
      plus();

      equal( subtitlediv.children[ 1 ].innerHTML, "this is the second subtitle of 2011", "subtitle displaying correct information" );
      plus();

      this.play();
    }).pause();
  });

  popped.cue( 4, function() {

    this.on( "pause", function onPause() {
      this.off( "pause", onPause );
      equal( subtitlediv.children[ 1 ].style.display, "none", "subtitle is hidden" );
      plus();

      this.play();
    }).pause();
  });

  popped.cue( 8, function() {

    this.on( "pause", function onPause() {
      this.off( "pause", onPause );
      popped2.currentTime( 8 ).play();

    }).pause();
  });

  popped2.cue( 8, function() {

    this.on( "pause", function onPause() {
      this.off( "pause", onPause );
      equal( subtitlediv.children[ 3 ].innerHTML, "instance one test", "subtitle displaying correct information" );
      plus();
      equal( subtitle2div.children[ 0 ].innerHTML, "instance two test", "subtitle displaying correct information" );
      plus();
      popped.play();

    }).pause();
  });

  popped.cue( 10, function() {
    ok( subtitlediv.children[ 0 ].style.display === "none" &&
        subtitlediv.children[ 1 ].style.display === "none" &&
        subtitlediv.children[ 2 ].style.display === "none", "All subtitles are no longer visible" );
    plus();

    this.on( "pause", function onPause() {
      this.off( "pause", onPause );
      this.removeTrackEvent( this.data.trackEvents.byStart[ 6 ]._id );

      // There were 4 subtitles, should be three now
      ok( subtitlediv.children.length === 3 , "subtitle div was destroyed"  );
      plus();

    }).pause();
  });

  popped.play( 0 );
});

asyncTest( "Subtitle data tests", 1, function() {

  var popped = Popcorn( "#video" );

  popped.text({
    start: 0,
    end: 10
  });

  equal( popped.container.children[ 0 ].innerHTML, "", "text with no `text` attribute defaults to an empty string" );

  popped.destroy();
  start();
});

asyncTest( "Subtitle container creation tests", 3, function() {

  var popped = Popcorn( "#video" ),
      containerAtLoad = document.getElementById( "divThatDoesntExist" ),
      containerAfterParse;

  popped.text({
    start: 0,
    end: 10,
    text: "My Text",
    target: "divThatDoesntExist"
  });

  containerAfterParse = document.getElementById( "divThatDoesntExist" );

  equal( !!containerAtLoad, false, "Container doesn't exist initially" );
  equal( !!containerAfterParse, true, "Container exists now" );
  equal( containerAfterParse.children[ 0 ].innerHTML, "My Text", "Subtitle text displayed in created container" );

  popped.destroy();
  start();
});
<|endoftext|>


<commit_before>/*
 * Purchase object that handles all the functions related to
 * contract purchase response
 */

var Purchase = (function () {
    'use strict';

    var purchase_data = {};

    var display = function (details) {
        purchase_data = details;

        var receipt = details['buy'],
            passthrough = details['echo_req']['passthrough'],
            container = document.getElementById('contract_confirmation_container'),
            message_container = document.getElementById('confirmation_message'),
            heading = document.getElementById('contract_purchase_heading'),
            descr = document.getElementById('contract_purchase_descr'),
            reference = document.getElementById('contract_purchase_reference'),
            chart = document.getElementById('tick_chart'),
            balance = document.getElementById('contract_purchase_balance'),
            payout = document.getElementById('contract_purchase_payout'),
            cost = document.getElementById('contract_purchase_cost'),
            profit = document.getElementById('contract_purchase_profit'),
            spots = document.getElementById('contract_purchase_spots'),
            confirmation_error = document.getElementById('confirmation_error'),
            contracts_list = document.getElementById('contracts_list'),
            button = document.getElementById('contract_purchase_button');

        var error = details['error'];
        var show_chart = !error && passthrough['duration']<=10 && passthrough['duration_unit']==='t' && (sessionStorage.formname === 'risefall' || sessionStorage.formname === 'higherlower' || sessionStorage.formname === 'asian');

        contracts_list.style.display = 'none';

        if (error) {
            container.style.display = 'block';
            message_container.hide();
            confirmation_error.show();
            confirmation_error.textContent = error['message'];
        } else {
            document.getElementById('guideBtn').style.display = 'none';
            container.style.display = 'table-row';
            message_container.show();
            confirmation_error.hide();

            heading.textContent = Content.localize().textContractConfirmationHeading;
            descr.textContent = receipt['longcode'];
            reference.textContent = Content.localize().textContractConfirmationReference + ' ' + receipt['transaction_id'];

            var payout_value, cost_value, profit_value;

            if(passthrough['basis'] === "payout"){
                payout_value = passthrough['amount'];
                cost_value = passthrough['ask-price'];
            }
            else{
                cost_value = passthrough['amount'];
                var match = receipt['longcode'].match(/[\d\,]+\.\d\d/);
                payout_value = match[0].replace(',','');
            }
            profit_value = Math.round((payout_value - cost_value)*100)/100;

            if(sessionStorage.getItem('formname')==='spreads'){
                payout.innerHTML = Content.localize().textStopLoss + '
' + receipt.stop_loss_level + '
';
                cost.innerHTML = Content.localize().textAmountPerPoint + '
' + receipt.amount_per_point + '
';
                profit.innerHTML = Content.localize().textStopProfit + '
' + receipt.stop_profit_level + '
';
            }
            else {
                payout.innerHTML = Content.localize().textContractConfirmationPayout + '
' + payout_value + '
';
                cost.innerHTML = Content.localize().textContractConfirmationCost + '
' + cost_value + '
';
                profit.innerHTML = Content.localize().textContractConfirmationProfit + '
' + profit_value + '
';
            }

            balance.textContent = Content.localize().textContractConfirmationBalance + ' ' + TUser.get().currency + ' ' + Math.round(receipt['balance_after']*100)/100;

            if(show_chart){
                chart.show();
            }
            else{
                chart.hide();
            }

            if(Contract.form() === 'digits'){
                spots.textContent = '';
                spots.className = '';
                spots.show();
            }
            else{
                spots.hide();
            }

            if(Contract.form() !== 'digits' && !show_chart){
                button.textContent = Content.localize().textContractConfirmationButton;
                button.setAttribute('contract_id', receipt['contract_id']);
                button.show();
            }
            else{
                button.hide();
            }
        }

        if(show_chart){
            var contract_sentiment;
            if(passthrough['contract_type']==='CALL' || passthrough['contract_type']==='ASIANU'){
                contract_sentiment = 'up';
            }
            else{
                contract_sentiment = 'down';
            }
            WSTickDisplay.initialize({
                symbol:passthrough.symbol,
                number_of_ticks:passthrough.duration,
                previous_tick_epoch:receipt['start_time'],
                contract_category:sessionStorage.getItem('formname')==='asian' ? 'asian' : 'callput',
                display_symbol:Symbols.getName(passthrough.symbol),
                contract_start:receipt['start_time'],
                decimal:3,
                contract_sentiment:contract_sentiment,
                price:passthrough['ask-price'],
                payout:passthrough['amount'],
                show_contract_result:1,
                width: $('#confirmation_message').width(),
            });
            WSTickDisplay.spots_list = {};
        }
    };

    var update_spot_list = function(data){

        if($('#contract_purchase_spots:hidden').length){
            return;
        }

        var duration = purchase_data.echo_req.passthrough['duration'];

        if(!duration){
            return;
        }

        var spots = document.getElementById('contract_purchase_spots');
        var spots2 = Tick.spots();
        var epoches = Object.keys(spots2).sort(function(a,b){return a-b;});
        spots.textContent = '';

        var replace = function(d){d1 = d; return ''+d+'';};
        for(var s=0; s<epoches.length; s++){
            var tick_d = {
                epoch: epoches[s],
                quote: spots2[epoches[s]]
            };

            if(isVisible(spots) && tick_d.epoch && tick_d.epoch > purchase_data.buy.start_time){
                var fragment = document.createElement('div');
                fragment.classList.add('row');

                var el1 = document.createElement('div');
                el1.classList.add('col');
                el1.textContent = Content.localize().textTickResultLabel + " " + (spots.getElementsByClassName('row').length+1);
                fragment.appendChild(el1);

                var el2 = document.createElement('div');
                el2.classList.add('col');
                var date = new Date(tick_d.epoch*1000);
                var hours = date.getUTCHours() < 10 ? '0'+date.getUTCHours() : date.getUTCHours();
                var minutes = date.getUTCMinutes() < 10 ? '0'+date.getUTCMinutes() : date.getUTCMinutes();
                var seconds = date.getUTCSeconds() < 10 ? '0'+date.getUTCSeconds() : date.getUTCSeconds();
                el2.textContent = hours+':'+minutes+':'+seconds;
                fragment.appendChild(el2);

                var d1;
                var tick = tick_d.quote.replace(/\d$/,replace);
                var el3 = document.createElement('div');
                el3.classList.add('col');
                el3.innerHTML = tick;
                fragment.appendChild(el3);

                spots.appendChild(fragment);
                spots.scrollTop = spots.scrollHeight;

                if(d1 && duration===1){
                    var contract_status,
                        final_price,
                        pnl;

                    if  (  purchase_data.echo_req.passthrough.contract_type==="DIGITMATCH" && d1==purchase_data.echo_req.passthrough.barrier || purchase_data.echo_req.passthrough.contract_type==="DIGITDIFF" && d1!=purchase_data.echo_req.passthrough.barrier || purchase_data.echo_req.passthrough.contract_type==="DIGITEVEN" && d1%2===0 || purchase_data.echo_req.passthrough.contract_type==="DIGITODD" && d1%2 || purchase_data.echo_req.passthrough.contract_type==="DIGITOVER" && d1>purchase_data.echo_req.passthrough.barrier || purchase_data.echo_req.passthrough.contract_type==="DIGITUNDER" && d1<purchase_data.echo_req.passthrough.barrier){
                        spots.className = 'won';
                        final_price = $('#contract_purchase_payout p').text();
                        pnl = $('#contract_purchase_cost p').text();
                        contract_status = Content.localize().textContractStatusWon;
                    }
                    else{
                        spots.className = 'lost';
                        final_price = 0;
                        pnl = -$('#contract_purchase_cost p').text();
                        contract_status = Content.localize().textContractStatusLost;
                    }

                    updatePurchaseStatus(final_price, pnl, contract_status);
                }

                duration--;
                if(!duration){
                    purchase_data.echo_req.passthrough['duration'] = 0;
                }
            }

        }

    };

    return {
        display: display,
        update_spot_list: update_spot_list
    };

})();
<commit_msg>Fix the error when the guideBtn is missing on trading page<commit_after>/*
 * Purchase object that handles all the functions related to
 * contract purchase response
 */

var Purchase = (function () {
    'use strict';

    var purchase_data = {};

    var display = function (details) {
        purchase_data = details;

        var receipt = details['buy'],
            passthrough = details['echo_req']['passthrough'],
            container = document.getElementById('contract_confirmation_container'),
            message_container = document.getElementById('confirmation_message'),
            heading = document.getElementById('contract_purchase_heading'),
            descr = document.getElementById('contract_purchase_descr'),
            reference = document.getElementById('contract_purchase_reference'),
            chart = document.getElementById('tick_chart'),
            balance = document.getElementById('contract_purchase_balance'),
            payout = document.getElementById('contract_purchase_payout'),
            cost = document.getElementById('contract_purchase_cost'),
            profit = document.getElementById('contract_purchase_profit'),
            spots = document.getElementById('contract_purchase_spots'),
            confirmation_error = document.getElementById('confirmation_error'),
            contracts_list = document.getElementById('contracts_list'),
            button = document.getElementById('contract_purchase_button');

        var error = details['error'];
        var show_chart = !error && passthrough['duration']<=10 && passthrough['duration_unit']==='t' && (sessionStorage.formname === 'risefall' || sessionStorage.formname === 'higherlower' || sessionStorage.formname === 'asian');

        contracts_list.style.display = 'none';

        if (error) {
            container.style.display = 'block';
            message_container.hide();
            confirmation_error.show();
            confirmation_error.textContent = error['message'];
        } else {
            var guideBtn = document.getElementById('guideBtn');
            if(guideBtn) {
                guideBtn.style.display = 'none';
            }
            container.style.display = 'table-row';
            message_container.show();
            confirmation_error.hide();

            heading.textContent = Content.localize().textContractConfirmationHeading;
            descr.textContent = receipt['longcode'];
            reference.textContent = Content.localize().textContractConfirmationReference + ' ' + receipt['transaction_id'];

            var payout_value, cost_value, profit_value;

            if(passthrough['basis'] === "payout"){
                payout_value = passthrough['amount'];
                cost_value = passthrough['ask-price'];
            }
            else{
                cost_value = passthrough['amount'];
                var match = receipt['longcode'].match(/[\d\,]+\.\d\d/);
                payout_value = match[0].replace(',','');
            }
            profit_value = Math.round((payout_value - cost_value)*100)/100;

            if(sessionStorage.getItem('formname')==='spreads'){
                payout.innerHTML = Content.localize().textStopLoss + '
' + receipt.stop_loss_level + '
';
                cost.innerHTML = Content.localize().textAmountPerPoint + '
' + receipt.amount_per_point + '
';
                profit.innerHTML = Content.localize().textStopProfit + '
' + receipt.stop_profit_level + '
';
            }
            else {
                payout.innerHTML = Content.localize().textContractConfirmationPayout + '
' + payout_value + '
';
                cost.innerHTML = Content.localize().textContractConfirmationCost + '
' + cost_value + '
';
                profit.innerHTML = Content.localize().textContractConfirmationProfit + '
' + profit_value + '
';
            }

            balance.textContent = Content.localize().textContractConfirmationBalance + ' ' + TUser.get().currency + ' ' + Math.round(receipt['balance_after']*100)/100;

            if(show_chart){
                chart.show();
            }
            else{
                chart.hide();
            }

            if(Contract.form() === 'digits'){
                spots.textContent = '';
                spots.className = '';
                spots.show();
            }
            else{
                spots.hide();
            }

            if(Contract.form() !== 'digits' && !show_chart){
                button.textContent = Content.localize().textContractConfirmationButton;
                button.setAttribute('contract_id', receipt['contract_id']);
                button.show();
            }
            else{
                button.hide();
            }
        }

        if(show_chart){
            var contract_sentiment;
            if(passthrough['contract_type']==='CALL' || passthrough['contract_type']==='ASIANU'){
                contract_sentiment = 'up';
            }
            else{
                contract_sentiment = 'down';
            }
            WSTickDisplay.initialize({
                symbol:passthrough.symbol,
                number_of_ticks:passthrough.duration,
                previous_tick_epoch:receipt['start_time'],
                contract_category:sessionStorage.getItem('formname')==='asian' ? 'asian' : 'callput',
                display_symbol:Symbols.getName(passthrough.symbol),
                contract_start:receipt['start_time'],
                decimal:3,
                contract_sentiment:contract_sentiment,
                price:passthrough['ask-price'],
                payout:passthrough['amount'],
                show_contract_result:1,
                width: $('#confirmation_message').width(),
            });
            WSTickDisplay.spots_list = {};
        }
    };

    var update_spot_list = function(data){

        if($('#contract_purchase_spots:hidden').length){
            return;
        }

        var duration = purchase_data.echo_req.passthrough['duration'];

        if(!duration){
            return;
        }

        var spots = document.getElementById('contract_purchase_spots');
        var spots2 = Tick.spots();
        var epoches = Object.keys(spots2).sort(function(a,b){return a-b;});
        spots.textContent = '';

        var replace = function(d){d1 = d; return ''+d+'';};
        for(var s=0; s<epoches.length; s++){
            var tick_d = {
                epoch: epoches[s],
                quote: spots2[epoches[s]]
            };

            if(isVisible(spots) && tick_d.epoch && tick_d.epoch > purchase_data.buy.start_time){
                var fragment = document.createElement('div');
                fragment.classList.add('row');

                var el1 = document.createElement('div');
                el1.classList.add('col');
                el1.textContent = Content.localize().textTickResultLabel + " " + (spots.getElementsByClassName('row').length+1);
                fragment.appendChild(el1);

                var el2 = document.createElement('div');
                el2.classList.add('col');
                var date = new Date(tick_d.epoch*1000);
                var hours = date.getUTCHours() < 10 ? '0'+date.getUTCHours() : date.getUTCHours();
                var minutes = date.getUTCMinutes() < 10 ? '0'+date.getUTCMinutes() : date.getUTCMinutes();
                var seconds = date.getUTCSeconds() < 10 ? '0'+date.getUTCSeconds() : date.getUTCSeconds();
                el2.textContent = hours+':'+minutes+':'+seconds;
                fragment.appendChild(el2);

                var d1;
                var tick = tick_d.quote.replace(/\d$/,replace);
                var el3 = document.createElement('div');
                el3.classList.add('col');
                el3.innerHTML = tick;
                fragment.appendChild(el3);

                spots.appendChild(fragment);
                spots.scrollTop = spots.scrollHeight;

                if(d1 && duration===1){
                    var contract_status,
                        final_price,
                        pnl;

                    if  (  purchase_data.echo_req.passthrough.contract_type==="DIGITMATCH" && d1==purchase_data.echo_req.passthrough.barrier || purchase_data.echo_req.passthrough.contract_type==="DIGITDIFF" && d1!=purchase_data.echo_req.passthrough.barrier || purchase_data.echo_req.passthrough.contract_type==="DIGITEVEN" && d1%2===0 || purchase_data.echo_req.passthrough.contract_type==="DIGITODD" && d1%2 || purchase_data.echo_req.passthrough.contract_type==="DIGITOVER" && d1>purchase_data.echo_req.passthrough.barrier || purchase_data.echo_req.passthrough.contract_type==="DIGITUNDER" && d1<purchase_data.echo_req.passthrough.barrier){
                        spots.className = 'won';
                        final_price = $('#contract_purchase_payout p').text();
                        pnl = $('#contract_purchase_cost p').text();
                        contract_status = Content.localize().textContractStatusWon;
                    }
                    else{
                        spots.className = 'lost';
                        final_price = 0;
                        pnl = -$('#contract_purchase_cost p').text();
                        contract_status = Content.localize().textContractStatusLost;
                    }

                    updatePurchaseStatus(final_price, pnl, contract_status);
                }

                duration--;
                if(!duration){
                    purchase_data.echo_req.passthrough['duration'] = 0;
                }
            }

        }

    };

    return {
        display: display,
        update_spot_list: update_spot_list
    };

})();
<|endoftext|>


<commit_before>suite('effect-callback', function() {
  setup(function() {
    document.timeline._animations = [];
    webAnimations1.timeline._animations = [];
  });

  test('animations starting in the future are not in effect', function() {
    var fractions = [];
    tick(100);
    var effect = new KeyframeEffect(null, [], 1000);
    effect.onSample = function(fraction) {
      fractions.push(fraction);
    };
    var animation = document.timeline.play(effect);
    animation.startTime = 1000;
    tick(200);
    tick(1000);
    tick(1100);
    assert.deepEqual(fractions, [0, 0.1]);
  });

  test('duration 0 animations get sampled at least once', function() {
    var timeFraction;
    tick(0);
    var effect = new KeyframeEffect(null, [], {duration: 0, fill: 'both'});
    effect.onSample = function(t) {
      timeFraction = t;
    };
    var animation = document.timeline.play(effect);
    tick(100);
    assert.equal(timeFraction, 1);
    assert.equal(isTicking(), false);
  });

  test('animations added during custom effect callbacks get updated in the same tick', function() {
    var animation;
    var called = false;
    tick(0);
    var effect = new KeyframeEffect(null, [], 2);
    var effect2 = new KeyframeEffect(null, [], 1);
    effect.onSample = function() {
      animation = document.timeline.play(effect2);
    };
    effect2.onSample = function() {
        called = true;
    };
    document.timeline.play(effect);
    tick(1);
    assert.isTrue(animation.startTime >= 0);
    assert.isFalse(called);
  });

  test('custom effect should be called after cancel', function() {
    var fractions = [];
    var effect = new KeyframeEffect(null, [], 1000);
    effect.onSample = function(fraction) {
      fractions.push(fraction);
    };
    var animation = document.timeline.play(effect);
    tick(0);
    tick(500);
    animation.cancel();
    tick(501);
    assert.deepEqual(fractions, [0, 0.5, null]);
  });

  test('Custom callback is given effect and animation', function() {
    var callbackEffect;
    var callbackAnim;
    var effect = new KeyframeEffect(document.body, [], 100);
    effect.onSample = function(t, e, a) {
      callbackEffect = e;
      callbackAnim = a;
    };
    var animation = document.timeline.play(effect);
    tick(50);
    tick(150);
    assert.equal(isTicking(), false);
    assert.equal(callbackAnim, animation);
    assert.equal(callbackEffect.target, document.body);
  });

  test('animations starting in the future are not in effect (old version)', function() {
    var fractions = [];
    tick(100);
    var animation = document.body.animate(function(fraction) { fractions.push(fraction); }, 1000);
    animation.startTime = 1000;
    tick(200);
    tick(1000);
    tick(1100);
    assert.deepEqual(fractions, [0, 0.1]);
  });

  test('duration 0 animations get sampled at least once (old version)', function() {
    var timeFraction;
    tick(0);
    var animation = document.body.animate(function(t) {
      timeFraction = t;
    }, {duration: 0, fill: 'both'});
    tick(100);
    assert.equal(timeFraction, 1);
    assert.equal(isTicking(), false);
  });

  test('animations added during custom effect callbacks get updated in the same tick (old version)', function() {
    var animation;
    var called = false;
    tick(0);
    document.body.animate(function() {
      animation = document.body.animate(function() {
        called = true;
      }, 1);
    }, 2);
    tick(1);
    assert.isTrue(animation.startTime >= 0);
    assert.isFalse(called);
  });

  test('custom effect should be called after cancel (old version)', function() {
    var fractions = [];
    var animation = document.body.animate(function(fraction) { fractions.push(fraction); }, 1000);
    tick(0);
    tick(500);
    animation.cancel();
    tick(501);
    assert.deepEqual(fractions, [0, 0.5, null]);
  });

  test('element.animate is given effect (old version)', function() {
    var callbackAnim;
    var animation = document.body.animate(function(t, target, a) {
      callbackAnim = a;
    }, 100);
    tick(50);
    tick(150);
    assert.equal(isTicking(), false);
    assert(callbackAnim, 'callback should be set');
    assert.equal(callbackAnim.target, document.body);
  });

  test('custom callback on effect is given source effect (old version)', function() {
    var callbackAnim;
    var effect = new KeyframeEffect(document.body, function(t, target, a) {
      callbackAnim = a;
    }, 1000);
    var animation = document.timeline.play(effect);
    tick(50);
    tick(550);
    assert.equal(animation.currentTime, 500);
    assert.equal(callbackAnim, effect);
  });
});
<commit_msg>Linter<commit_after>suite('effect-callback', function() {
  setup(function() {
    document.timeline._animations = [];
    webAnimations1.timeline._animations = [];
  });

  test('animations starting in the future are not in effect', function() {
    var fractions = [];
    tick(100);
    var effect = new KeyframeEffect(null, [], 1000);
    effect.onSample = function(fraction) {
      fractions.push(fraction);
    };
    var animation = document.timeline.play(effect);
    animation.startTime = 1000;
    tick(200);
    tick(1000);
    tick(1100);
    assert.deepEqual(fractions, [0, 0.1]);
  });

  test('duration 0 animations get sampled at least once', function() {
    var timeFraction;
    tick(0);
    var effect = new KeyframeEffect(null, [], {duration: 0, fill: 'both'});
    effect.onSample = function(t) {
      timeFraction = t;
    };
    var animation = document.timeline.play(effect);
    tick(100);
    assert.equal(timeFraction, 1);
    assert.equal(isTicking(), false);
  });

  test('animations added during custom effect callbacks get updated in the same tick', function() {
    var animation;
    var called = false;
    tick(0);
    var effect = new KeyframeEffect(null, [], 2);
    var effect2 = new KeyframeEffect(null, [], 1);
    effect.onSample = function() {
      animation = document.timeline.play(effect2);
    };
    effect2.onSample = function() {
      called = true;
    };
    document.timeline.play(effect);
    tick(1);
    assert.isTrue(animation.startTime >= 0);
    assert.isFalse(called);
  });

  test('custom effect should be called after cancel', function() {
    var fractions = [];
    var effect = new KeyframeEffect(null, [], 1000);
    effect.onSample = function(fraction) {
      fractions.push(fraction);
    };
    var animation = document.timeline.play(effect);
    tick(0);
    tick(500);
    animation.cancel();
    tick(501);
    assert.deepEqual(fractions, [0, 0.5, null]);
  });

  test('Custom callback is given effect and animation', function() {
    var callbackEffect;
    var callbackAnim;
    var effect = new KeyframeEffect(document.body, [], 100);
    effect.onSample = function(t, e, a) {
      callbackEffect = e;
      callbackAnim = a;
    };
    var animation = document.timeline.play(effect);
    tick(50);
    tick(150);
    assert.equal(isTicking(), false);
    assert.equal(callbackAnim, animation);
    assert.equal(callbackEffect.target, document.body);
  });

  test('animations starting in the future are not in effect (old version)', function() {
    var fractions = [];
    tick(100);
    var animation = document.body.animate(function(fraction) { fractions.push(fraction); }, 1000);
    animation.startTime = 1000;
    tick(200);
    tick(1000);
    tick(1100);
    assert.deepEqual(fractions, [0, 0.1]);
  });

  test('duration 0 animations get sampled at least once (old version)', function() {
    var timeFraction;
    tick(0);
    var animation = document.body.animate(function(t) {
      timeFraction = t;
    }, {duration: 0, fill: 'both'});
    tick(100);
    assert.equal(timeFraction, 1);
    assert.equal(isTicking(), false);
  });

  test('animations added during custom effect callbacks get updated in the same tick (old version)', function() {
    var animation;
    var called = false;
    tick(0);
    document.body.animate(function() {
      animation = document.body.animate(function() {
        called = true;
      }, 1);
    }, 2);
    tick(1);
    assert.isTrue(animation.startTime >= 0);
    assert.isFalse(called);
  });

  test('custom effect should be called after cancel (old version)', function() {
    var fractions = [];
    var animation = document.body.animate(function(fraction) { fractions.push(fraction); }, 1000);
    tick(0);
    tick(500);
    animation.cancel();
    tick(501);
    assert.deepEqual(fractions, [0, 0.5, null]);
  });

  test('element.animate is given effect (old version)', function() {
    var callbackAnim;
    var animation = document.body.animate(function(t, target, a) {
      callbackAnim = a;
    }, 100);
    tick(50);
    tick(150);
    assert.equal(isTicking(), false);
    assert(callbackAnim, 'callback should be set');
    assert.equal(callbackAnim.target, document.body);
  });

  test('custom callback on effect is given source effect (old version)', function() {
    var callbackAnim;
    var effect = new KeyframeEffect(document.body, function(t, target, a) {
      callbackAnim = a;
    }, 1000);
    var animation = document.timeline.play(effect);
    tick(50);
    tick(550);
    assert.equal(animation.currentTime, 500);
    assert.equal(callbackAnim, effect);
  });
});
<|endoftext|>


<commit_before>var async = require('async'),
    http = require('http'),
    querystring = require('querystring'),
    parse = require('url').parse,
    fields = require('./fields');

exports.widgets = require('./widgets');
exports.fields = require('./fields');
exports.render = require('./render');
exports.validators = require('./validators');

/**
 * Create a new form.
 *
 * @param {callback}
 *   A function returning accepting {param} and a callback that passes  a form
 *   definition in the form of an object. See README for more information.
 *
 * @param {param}
 *   A parameter to pass on to the definition function.
 */
var Form = function(callback, param) {
    this.onBuildCallbacks = [];
    // Allow asynchronous loading of the form definition.
    // TODO: Error handling.
    var that = this;
    callback(param, function(err, definition) {
        that.def = definition;
        // Resolve fields right away.
        that.def.fields = that.def.fields();
        that.triggerOnBuild();
    });
};

/**
 * Queue functions to be triggered as soon as form definition is available.
 *
 * Callback is executed immediately if form is built.
 */
Form.prototype.onBuild = function(callback) {
    if (this.def) {
        callback();
    }
    else {
        this.onBuildCallbacks.unshift(callback);
    }
}

/**
 * Trigger callbacks queued with onBuild().
 */
Form.prototype.triggerOnBuild = function() {
    for (var i = 0; i < this.onBuildCallbacks.length; i++) {
        (this.onBuildCallbacks[i])();
    }
}

/**
 * Handles GET and POST requests.
 */
Form.prototype.handle = function(request, response, next) {
    var that = this;
    switch (request.method) {
    case 'GET':
        // TODO: assumption that ANY query parameters are a valid submission is
        // too wide.
        var data = parse(request.url, 1).query;
        if (data) {
            this.process(data, request, response, next);
        }
        // If no data has been submitted, render form.
        else {
            this.onBuild(function() {
                that.def.render(that, request, response, next);
            });
        }
        return;
    case 'POST':
        var buffer = '';
        request.addListener('data', function(chunk){
            buffer += chunk;
        });
        request.addListener('end', function(){
            var data = querystring.parse(buffer);
            that.process(data, request, response, next);
        });
        return;
    default:
        // Invalid request, send a 404.
        response.send(404);
    }
};

/**
 * Process form submission.
 */
Form.prototype.process = function(data, request, response, next) {
    var that = this;
    this.onBuild(function() {
        // Copy submitted data to field definition.
        Object.keys(that.def.fields).forEach(function(k) {
            that.def.fields[k].bind(data[k]);
        });
        // Validate form, submit or render depending on errors.
        that.validate(function(err) {
            var submitted = false;
            if (that.isValid()) {
                // Call submit handlers of clicked buttons.
                // TODO: Currently any submit handler on a non-empty
                // field will be clicked.
                Object.keys(that.def.fields).forEach(function(k) {
                    if (that.def.fields[k].submit &&
                        data[k]) {
                        that.def.fields[k].submit(that, request, response, next);
                        submitted = true;
                    }
                });
                // TODO: Throw / show error if submission failed.
            }
            if (!submitted) {
                that.def.render(that, request, response, next);
            }
        });
    });
};

/**
 * Validate form.
 */
Form.prototype.validate = function(callback) {
    var that = this;
    async.forEach(Object.keys(this.def.fields), function(k, callback) {
        that.def.fields[k].validate(that, function(err) {
            callback(err);
        });
    }, function(err) {
        callback(err);
    });
};

/**
 * After validation, determine whether form is valid or not.
 *
 * TODO: Could this method be avoided by using the 'err' value passed
 * out from validate() ?
 */
Form.prototype.isValid = function(callback) {
    var that = this;
    return Object.keys(this.def.fields).every(function(k){
        return that.def.fields[k].error == null;
    });
};

/**
 * Renders form as HTML.
 */
Form.prototype.toHTML = function(iterator) {
    var that = this;
    var html = Object.keys(this.def.fields).reduce(function(html, k) {
        return html + that.def.fields[k].toHTML(k, iterator);
    }, '');
    var action = this.def.action || '';
    var method = this.def.method || 'POST';
    return '<form action="' + action +'" method="' + method +'">'
        + html
        + '<form>';
};

/**
 * Export Form object.
 */
exports.Form = Form;

/**
 * Obsolete code.
 *
exports.create = function(fields){
    var f = {
        fields: fields,
        bind: function(data){
            var b = {};
            b.toHTML = f.toHTML;
            b.fields = f.fields;
            Object.keys(b.fields).forEach(function(k){
                b.fields[k] = f.fields[k].bind(data[k]);
            });
            b.data = Object.keys(b.fields).reduce(function(a,k){
                a[k] = b.fields[k].data;
                return a;
            }, {});
            b.validate = function(callback){
                async.forEach(Object.keys(b.fields), function(k, callback){
                    f.fields[k].validate(b, function(err, bound_field){
                        b.fields[k] = bound_field;
                        callback(err);
                    });
                }, function(err){
                    callback(err, b);
                });
            };
            b.isValid = function(){
                var form = this;
                return Object.keys(form.fields).every(function(k){
                    return form.fields[k].error == null;
                });
            };
            return b;
        },
        handle: function(obj, callbacks){
            if(obj === undefined || obj === null){
                (callbacks.empty || callbacks.other)(f);
            }
            else if(obj instanceof http.IncomingMessage){
                if(obj.method === 'GET'){
                    f.handle(parse(obj.url, 1).query, callbacks);
                }
                else if(obj.method === 'POST'){
                    var buffer = '';
                    obj.addListener('data', function(chunk){
                        buffer += chunk;
                    });
                    obj.addListener('end', function(){
                        f.handle(querystring.parse(buffer), callbacks);
                    });
                }
                else throw new Error(
                    'Cannot handle request method: ' + obj.method
                );
            }
            else if(typeof obj === 'object'){
                f.bind(obj).validate(function(err, f){
                    if(f.isValid()){
                        (callbacks.success || callbacks.other)(f);
                    }
                    else {
                        (callbacks.error || callbacks.other)(f);
                    }
                });
            }
            else throw new Error('Cannot handle type: ' + typeof obj);
        },
        toHTML: function(iterator){
            var form = this;
            return Object.keys(form.fields).reduce(function(html, k){
                return html + form.fields[k].toHTML(k, iterator);
            }, '');
        }
    };
    return f;
};
*/<commit_msg>Throw out obsolete code.<commit_after>var async = require('async'),
    http = require('http'),
    querystring = require('querystring'),
    parse = require('url').parse,
    fields = require('./fields');

exports.widgets = require('./widgets');
exports.fields = require('./fields');
exports.render = require('./render');
exports.validators = require('./validators');

/**
 * Create a new form.
 *
 * @param {callback}
 *   A function returning accepting {param} and a callback that passes  a form
 *   definition in the form of an object. See README for more information.
 *
 * @param {param}
 *   A parameter to pass on to the definition function.
 */
var Form = function(callback, param) {
    this.onBuildCallbacks = [];
    // Allow asynchronous loading of the form definition.
    // TODO: Error handling.
    var that = this;
    callback(param, function(err, definition) {
        that.def = definition;
        // Resolve fields right away.
        that.def.fields = that.def.fields();
        that.triggerOnBuild();
    });
};

/**
 * Queue functions to be triggered as soon as form definition is available.
 *
 * Callback is executed immediately if form is built.
 */
Form.prototype.onBuild = function(callback) {
    if (this.def) {
        callback();
    }
    else {
        this.onBuildCallbacks.unshift(callback);
    }
}

/**
 * Trigger callbacks queued with onBuild().
 */
Form.prototype.triggerOnBuild = function() {
    for (var i = 0; i < this.onBuildCallbacks.length; i++) {
        (this.onBuildCallbacks[i])();
    }
}

/**
 * Handles GET and POST requests.
 */
Form.prototype.handle = function(request, response, next) {
    var that = this;
    switch (request.method) {
    case 'GET':
        // TODO: assumption that ANY query parameters are a valid submission is
        // too wide.
        var data = parse(request.url, 1).query;
        if (data) {
            this.process(data, request, response, next);
        }
        // If no data has been submitted, render form.
        else {
            this.onBuild(function() {
                that.def.render(that, request, response, next);
            });
        }
        return;
    case 'POST':
        var buffer = '';
        request.addListener('data', function(chunk){
            buffer += chunk;
        });
        request.addListener('end', function(){
            var data = querystring.parse(buffer);
            that.process(data, request, response, next);
        });
        return;
    default:
        // Invalid request, send a 404.
        response.send(404);
    }
};

/**
 * Process form submission.
 */
Form.prototype.process = function(data, request, response, next) {
    var that = this;
    this.onBuild(function() {
        // Copy submitted data to field definition.
        Object.keys(that.def.fields).forEach(function(k) {
            that.def.fields[k].bind(data[k]);
        });
        // Validate form, submit or render depending on errors.
        that.validate(function(err) {
            var submitted = false;
            if (that.isValid()) {
                // Call submit handlers of clicked buttons.
                // TODO: Currently any submit handler on a non-empty
                // field will be clicked.
                Object.keys(that.def.fields).forEach(function(k) {
                    if (that.def.fields[k].submit &&
                        data[k]) {
                        that.def.fields[k].submit(that, request, response, next);
                        submitted = true;
                    }
                });
                // TODO: Throw / show error if submission failed.
            }
            if (!submitted) {
                that.def.render(that, request, response, next);
            }
        });
    });
};

/**
 * Validate form.
 */
Form.prototype.validate = function(callback) {
    var that = this;
    async.forEach(Object.keys(this.def.fields), function(k, callback) {
        that.def.fields[k].validate(that, function(err) {
            callback(err);
        });
    }, function(err) {
        callback(err);
    });
};

/**
 * After validation, determine whether form is valid or not.
 *
 * TODO: Could this method be avoided by using the 'err' value passed
 * out from validate() ?
 */
Form.prototype.isValid = function(callback) {
    var that = this;
    return Object.keys(this.def.fields).every(function(k){
        return that.def.fields[k].error == null;
    });
};

/**
 * Renders form as HTML.
 */
Form.prototype.toHTML = function(iterator) {
    var that = this;
    var html = Object.keys(this.def.fields).reduce(function(html, k) {
        return html + that.def.fields[k].toHTML(k, iterator);
    }, '');
    var action = this.def.action || '';
    var method = this.def.method || 'POST';
    return '<form action="' + action +'" method="' + method +'">'
        + html
        + '<form>';
};

/**
 * Export Form object.
 */
exports.Form = Form;
<|endoftext|>


<commit_before>var express = require('express');
var http = require('http');
var favicon = require('serve-favicon');
var nconf = require('nconf');
var path = require('path');
var morgan = require('morgan');
var routes = require('./routes/home');
var winston = require('winston');
var bodyParser = require('body-parser');
var redis = require('redis');
var util = require('util');

// read in keys and secrets.  You can store these in a variety of ways.  I like to use a keys.json
// file that is in the .gitignore file, but you can also store them in the env
nconf.argv().env().file('keys.json');

var universe = "universe";

// set up a single instance of a winston logger
var logger = new (winston.Logger)({
    transports: [
        new (winston.transports.Console)()
    ]
});
logger.info('Started wazstagram frontend process');

function createRedisClient() {
    return redis.createClient(
        6379,
        nconf.get('redisHost'),
        {
            auth_pass: nconf.get('redisKey'),
            return_buffers: true
        }
    ).on("error", function (err) {
        logger.error("ERR:REDIS: " + err);
    });
}

// create redis clients for the publisher and the subscriber
var redisSubClient = createRedisClient();
var redisPubClient = createRedisClient();

// configure the web server
var app = express();

// view engine setup
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(morgan('dev'));
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(function(req, res, next) {
    res.locals.nconf = nconf;
    res.locals.logger = logger;
    res.locals.publishFunc = publishImage;
    next();
});
app.use('/', routes)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    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);
    logger.error(err.message);
    res.end();
});

// start socket.io server
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(app.get('port'), function(){
  logger.info('Express server listening on port ' + app.get('port'));
});

io.sockets.on('connection', function (socket) {
    socket.on('setCity', function (data) {
        logger.info('new connection: ' + data.city);
        redisPubClient.lrange(data.city, 0, 100, function(err, picCache) {
            if (err) {
                logger.error(err);
                return;
            }
            logger.info("cache length: " + picCache.length);
            for (var i = 0; i < picCache.length; i++) {
                logger.info("PIC: " + JSON.parse(picCache[i].toString()).data[0].link);
                socket.emit('newPic', picCache[i].toString());
            }
            socket.join(data.city);
        });
    });
});

// listen to new images from redis pub/sub
redisSubClient.on('message', function(channel, message) {
    logger.verbose('channel: ' + channel + " ; message: " + message);
    var m = JSON.parse(message.toString());
    io.sockets.in (m.city).emit('newPic', m.pic);
    io.sockets.in (universe).emit('newPic', m.pic);
}).subscribe('pics');

// send an event to redis letting all clients know there
// is a new image available
function publishImage(message) {
    logger.info('new pic published from: ' + message.city);
    logger.info(message.pic.data);
    redisPubClient.publish('pics', JSON.stringify(message));

    // cache results to ensure users get an initial blast of (n) images per city
    redisPubClient.lpush(message.city, message.pic);
    redisPubClient.ltrim(message.city, 0, 100);
    redisPubClient.lpush(universe, message.pic);
    redisPubClient.ltrim(universe, 0, 100);
}

module.exports = app;
<commit_msg>add debug info for writes<commit_after>var express = require('express');
var http = require('http');
var favicon = require('serve-favicon');
var nconf = require('nconf');
var path = require('path');
var morgan = require('morgan');
var routes = require('./routes/home');
var winston = require('winston');
var bodyParser = require('body-parser');
var redis = require('redis');
var util = require('util');

// read in keys and secrets.  You can store these in a variety of ways.  I like to use a keys.json
// file that is in the .gitignore file, but you can also store them in the env
nconf.argv().env().file('keys.json');

var universe = "universe";

// set up a single instance of a winston logger
var logger = new (winston.Logger)({
    transports: [
        new (winston.transports.Console)()
    ]
});
logger.info('Started wazstagram frontend process');

function createRedisClient() {
    return redis.createClient(
        6379,
        nconf.get('redisHost'),
        {
            auth_pass: nconf.get('redisKey'),
            return_buffers: true
        }
    ).on("error", function (err) {
        logger.error("ERR:REDIS: " + err);
    });
}

// create redis clients for the publisher and the subscriber
var redisSubClient = createRedisClient();
var redisPubClient = createRedisClient();

// configure the web server
var app = express();

// view engine setup
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(morgan('dev'));
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(function(req, res, next) {
    res.locals.nconf = nconf;
    res.locals.logger = logger;
    res.locals.publishFunc = publishImage;
    next();
});
app.use('/', routes)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    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);
    logger.error(err.message);
    res.end();
});

// start socket.io server
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(app.get('port'), function(){
  logger.info('Express server listening on port ' + app.get('port'));
});

io.sockets.on('connection', function (socket) {
    socket.on('setCity', function (data) {
        logger.info('new connection: ' + data.city);
        redisPubClient.lrange(data.city, 0, 100, function(err, picCache) {
            if (err) {
                logger.error(err);
                return;
            }
            logger.info("cache length: " + picCache.length);
            for (var i = 0; i < picCache.length; i++) {
                logger.info("PIC: " + JSON.parse(picCache[i].toString()).data[0].link);
                socket.emit('newPic', picCache[i].toString());
            }
            socket.join(data.city);
        });
    });
});

// listen to new images from redis pub/sub
redisSubClient.on('message', function(channel, message) {
    logger.verbose('channel: ' + channel + " ; message: " + message);
    var m = JSON.parse(message.toString());
    io.sockets.in (m.city).emit('newPic', m.pic);
    io.sockets.in (universe).emit('newPic', m.pic);
}).subscribe('pics');

// send an event to redis letting all clients know there
// is a new image available
function publishImage(message) {
    logger.info('new pic published from: ' + message.city);
    logger.info(message.pic);
    redisPubClient.publish('pics', JSON.stringify(message));

    // cache results to ensure users get an initial blast of (n) images per city
    redisPubClient.lpush(message.city, message.pic);
    redisPubClient.ltrim(message.city, 0, 100);
    redisPubClient.lpush(universe, message.pic);
    redisPubClient.ltrim(universe, 0, 100);
}

module.exports = app;
<|endoftext|>


<commit_before>'use strict';

angular.module('copayApp.controllers').controller('collectEmailController', function($scope, $state, $stateParams, $ionicScrollDelegate, profileService, configService, walletService, platformInfo) {

  var isCordova = platformInfo.isCordova;
  var isWP = platformInfo.isWP;
  var usePushNotifications = isCordova && !isWP;

  var wallet = profileService.getWallet($stateParams.walletId);
  var walletId = wallet.credentials.walletId;

  var config = configService.getSync();
  config.emailFor = config.emailFor || {};
  $scope.email = config.emailFor && config.emailFor[walletId];

  $scope.save = function(form) {
    var opts = {
      emailFor: {}
    };
    opts.emailFor[walletId] = $scope.email;

    walletService.updateRemotePreferences(wallet, {
      email: $scope.email,
    }, function(err) {
      if (err) $log.warn(err);
      configService.set(opts, function(err) {
        if (err) $log.warn(err);
        if (!usePushNotifications) $state.go('onboarding.backupRequest', {walletId: walletId});
        else $state.go('onboarding.notifications', {walletId: walletId});
      });
    });
  };

  $scope.onboardingMailSkip = function() {
    $state.go('onboarding.backupRequest', {walletId: walletId});
  };
});
<commit_msg>Removes ionicscrolldelegate<commit_after>'use strict';

angular.module('copayApp.controllers').controller('collectEmailController', function($scope, $state, $stateParams, profileService, configService, walletService, platformInfo) {

  var isCordova = platformInfo.isCordova;
  var isWP = platformInfo.isWP;
  var usePushNotifications = isCordova && !isWP;

  var wallet = profileService.getWallet($stateParams.walletId);
  var walletId = wallet.credentials.walletId;

  var config = configService.getSync();
  config.emailFor = config.emailFor || {};
  $scope.email = config.emailFor && config.emailFor[walletId];

  $scope.save = function(form) {
    var opts = {
      emailFor: {}
    };
    opts.emailFor[walletId] = $scope.email;

    walletService.updateRemotePreferences(wallet, {
      email: $scope.email,
    }, function(err) {
      if (err) $log.warn(err);
      configService.set(opts, function(err) {
        if (err) $log.warn(err);
        if (!usePushNotifications) $state.go('onboarding.backupRequest', {walletId: walletId});
        else $state.go('onboarding.notifications', {walletId: walletId});
      });
    });
  };

  $scope.onboardingMailSkip = function() {
    $state.go('onboarding.backupRequest', {walletId: walletId});
  };
});
<|endoftext|>


<commit_before>
test( 'parse' , function ( assert ) {

	assert.throws( integer.parse.bind( null , 16 , 16 , '!00b0C0def' ) , /invalid/ ) ;
	assert.throws( integer.parse.bind( null , 37 , 37 , '!' ) , /not implemented/ ) ;

	assert.deepEqual( integer.parse( 2 , 2 , '0' ) , [ 0 ] ) ;
	assert.deepEqual( integer.parse( 2 , 2 , '1' ) , [ 1 ] ) ;
	assert.deepEqual( integer.parse( 2 , 2 , '10' ) , [ 1 , 0 ] ) ;
	assert.deepEqual( integer.parse( 2 , 2 , '11' ) , [ 1 , 1 ] ) ;

	assert.deepEqual( integer.parse( 2 , 2 , '1001010111' ) , [ 1 , 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 1 ] ) ;

	assert.deepEqual( integer.parse( 16 , 16 , '0' ) , [ 0 ] ) ;
	assert.deepEqual( integer.parse( 16 , 16 , 'a' ) , [ 10 ] ) ;
	assert.deepEqual( integer.parse( 16 , 16 , 'A0' ) , [ 10 , 0 ] ) ;
	assert.deepEqual( integer.parse( 16 , 16 , 'a1' ) , [ 10 , 1 ] ) ;

	assert.deepEqual( integer.parse( 16 , 16 , 'a00b0C0def' ) , [ 10 , 0 , 0 , 11 , 0 , 12 , 0 , 13 , 14 , 15 ] ) ;

	assert.deepEqual( integer.parse( 2 , 16 , '11' ) , [ 3 ] ) ;
	assert.deepEqual( integer.parse( 16 , 2 , '3' ) , [ 0 , 0 , 1 , 1 ] ) ;

	assert.deepEqual( integer.parse( 2 , 16 , '10001' ) , [ 1 , 1 ] ) ;
	assert.deepEqual( integer.parse( 16 , 2 , '11' ) , [ 0 , 0 , 0 , 1 , 0 , 0 , 0 , 1 ] ) ;

	assert.deepEqual( integer.parse( 2 , 10 , '11' ) , [ 3 ] ) ;
	assert.deepEqual( integer.parse( 10 , 2 , '3' ) , [ 0 , 0 , 1 , 1 ] ) ;

	assert.deepEqual( integer.parse( 10 , 16 , '256' ) , [ 1 , 0 , 0 ] ) ;
	assert.deepEqual( integer.parse( 16 , 10 , '100' ) , [ 0 , 2 , 5 , 6 ] ) ;

	assert.deepEqual( integer.parse( 10 , 16 , '255' ) , [ 0 , 15 , 15 ] ) ;
	assert.deepEqual( integer.parse( 16 , 10 , 'ff' ) , [ 2 , 5 , 5 ] ) ;

	assert.deepEqual( integer.parse( 16 , 100 , 'ff' ) , [ 2 , 55 ] ) ;
	assert.deepEqual( integer.parse( 16 , 1000 , 'ff' ) , [ 255 ] ) ;
	assert.deepEqual( integer.parse( 16 , 10000 , 'ff' ) , [ 255 ] ) ;

	assert.deepEqual( integer.parse( 16 , 100 , 'fedcba9876543210' ) , [ 18 , 36 , 47 , 58 , 54 , 44 , 93 , 06 , 47 , 20 ] ) ;
	assert.deepEqual(
		integer.parse( 36 , 10000 , '1234567890azertyuiopqsdfghjklmwxcvbn' ) ,
		[ 0,312,6485,6500,0280,6599,6167,8564,7451,522,8125,564,4362,6409,4355]
	) ;

} ) ;
<commit_msg>remove useless zero<commit_after>
test( 'parse' , function ( assert ) {

	assert.throws( integer.parse.bind( null , 16 , 16 , '!00b0C0def' ) , /invalid/ ) ;
	assert.throws( integer.parse.bind( null , 37 , 37 , '!' ) , /not implemented/ ) ;

	assert.deepEqual( integer.parse( 2 , 2 , '0' ) , [ 0 ] ) ;
	assert.deepEqual( integer.parse( 2 , 2 , '1' ) , [ 1 ] ) ;
	assert.deepEqual( integer.parse( 2 , 2 , '10' ) , [ 1 , 0 ] ) ;
	assert.deepEqual( integer.parse( 2 , 2 , '11' ) , [ 1 , 1 ] ) ;

	assert.deepEqual( integer.parse( 2 , 2 , '1001010111' ) , [ 1 , 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 1 ] ) ;

	assert.deepEqual( integer.parse( 16 , 16 , '0' ) , [ 0 ] ) ;
	assert.deepEqual( integer.parse( 16 , 16 , 'a' ) , [ 10 ] ) ;
	assert.deepEqual( integer.parse( 16 , 16 , 'A0' ) , [ 10 , 0 ] ) ;
	assert.deepEqual( integer.parse( 16 , 16 , 'a1' ) , [ 10 , 1 ] ) ;

	assert.deepEqual( integer.parse( 16 , 16 , 'a00b0C0def' ) , [ 10 , 0 , 0 , 11 , 0 , 12 , 0 , 13 , 14 , 15 ] ) ;

	assert.deepEqual( integer.parse( 2 , 16 , '11' ) , [ 3 ] ) ;
	assert.deepEqual( integer.parse( 16 , 2 , '3' ) , [ 0 , 0 , 1 , 1 ] ) ;

	assert.deepEqual( integer.parse( 2 , 16 , '10001' ) , [ 1 , 1 ] ) ;
	assert.deepEqual( integer.parse( 16 , 2 , '11' ) , [ 0 , 0 , 0 , 1 , 0 , 0 , 0 , 1 ] ) ;

	assert.deepEqual( integer.parse( 2 , 10 , '11' ) , [ 3 ] ) ;
	assert.deepEqual( integer.parse( 10 , 2 , '3' ) , [ 0 , 0 , 1 , 1 ] ) ;

	assert.deepEqual( integer.parse( 10 , 16 , '256' ) , [ 1 , 0 , 0 ] ) ;
	assert.deepEqual( integer.parse( 16 , 10 , '100' ) , [ 0 , 2 , 5 , 6 ] ) ;

	assert.deepEqual( integer.parse( 10 , 16 , '255' ) , [ 0 , 15 , 15 ] ) ;
	assert.deepEqual( integer.parse( 16 , 10 , 'ff' ) , [ 2 , 5 , 5 ] ) ;

	assert.deepEqual( integer.parse( 16 , 100 , 'ff' ) , [ 2 , 55 ] ) ;
	assert.deepEqual( integer.parse( 16 , 1000 , 'ff' ) , [ 255 ] ) ;
	assert.deepEqual( integer.parse( 16 , 10000 , 'ff' ) , [ 255 ] ) ;

	assert.deepEqual( integer.parse( 16 , 100 , 'fedcba9876543210' ) , [ 18 , 36 , 47 , 58 , 54 , 44 , 93 , 06 , 47 , 20 ] ) ;
	assert.deepEqual(
		integer.parse( 36 , 10000 , '1234567890azertyuiopqsdfghjklmwxcvbn' ) ,
		[ 0,312,6485,6500,280,6599,6167,8564,7451,522,8125,564,4362,6409,4355]
	) ;

} ) ;
<|endoftext|>