function renderInit() {
    try {
        var params = {};
        if (config.horizonPitch !== undefined)
            params.horizonPitch = config.horizonPitch * Math.PI / 180;
        if (config.horizonRoll !== undefined)
            params.horizonRoll = config.horizonRoll * Math.PI / 180;
        if (config.backgroundColor !== undefined)
            params.backgroundColor = config.backgroundColor;
        renderer.init(panoImage, config.type, config.dynamic, config.haov * Math.PI / 180, config.vaov * Math.PI / 180, config.vOffset * Math.PI / 180, renderInitCallback, params);
        if (config.dynamic !== true) {
            // Allow image to be garbage collected
            panoImage = undefined;
        }
    } catch(event) {
        // Panorama not loaded

        // Display error if there is a bad texture
        if (event.type == 'webgl error' || event.type == 'no webgl') {
            anError();
        } else if (event.type == 'webgl size error') {
            anError(config.strings.textureSizeError.replace('%s', event.width).replace('%s', event.maxWidth));
        } else {
            anError(config.strings.unknownError);
            throw event;
        }
    }
}

function
renderInit
(
)
{
try
{
var
params
=
{
}
;
if
(
config
.
horizonPitch
!==
undefined
)
params
.
horizonPitch
=
config
.
horizonPitch
*
Math
.
PI
/
180
;
if
(
config
.
horizonRoll
!==
undefined
)
params
.
horizonRoll
=
config
.
horizonRoll
*
Math
.
PI
/
180
;
if
(
config
.
backgroundColor
!==
undefined
)
params
.
backgroundColor
=
config
.
backgroundColor
;
renderer
.
init
(
panoImage
,
config
.
type
,
config
.
dynamic
,
config
.
haov
*
Math
.
PI
/
180
,
config
.
vaov
*
Math
.
PI
/
180
,
config
.
vOffset
*
Math
.
PI
/
180
,
renderInitCallback
,
params
)
;
if
(
config
.
dynamic
!==
true
)
{
panoImage
=
undefined
;
}
}
catch
(
event
)
{
if
(
event
.
type
==
'webgl error'
||
event
.
type
==
'no webgl'
)
{
anError
(
)
;
}
else
if
(
event
.
type
==
'webgl size error'
)
{
anError
(
config
.
strings
.
textureSizeError
.
replace
(
'%s'
,
event
.
width
)
.
replace
(
'%s'
,
event
.
maxWidth
)
)
;
}
else
{
anError
(
config
.
strings
.
unknownError
)
;
throw
event
;
}
}
}


function renderInitCallback() {
    // Fade if specified
    if (config.sceneFadeDuration && renderer.fadeImg !== undefined) {
        renderer.fadeImg.style.opacity = 0;
        // Remove image
        var fadeImg = renderer.fadeImg;
        delete renderer.fadeImg;
        setTimeout(function() {
            renderContainer.removeChild(fadeImg);
            fireEvent('scenechangefadedone');
        }, config.sceneFadeDuration);
    }

    // Show compass if applicable
    if (config.compass) {
        compass.style.display = 'inline';
    } else {
        compass.style.display = 'none';
    }

    // Show hotspots
    createHotSpots();

    // Hide loading display
    infoDisplay.load.box.style.display = 'none';
    if (preview !== undefined) {
        renderContainer.removeChild(preview);
        preview = undefined;
    }
    loaded = true;

    fireEvent('load');

    animateInit();
}

function renderInitCallback ( ) { if ( config . sceneFadeDuration && renderer . fadeImg !== undefined ) { renderer . fadeImg . style . opacity = 0 ; var fadeImg = renderer . fadeImg ; delete renderer . fadeImg ; setTimeout ( function ( ) { renderContainer . removeChild ( fadeImg ) ; fireEvent ( 'scenechangefadedone' ) ; } , config . sceneFadeDuration ) ; } if ( config . compass ) { compass . style . display = 'inline' ; } else { compass . style . display = 'none' ; } createHotSpots ( ) ; infoDisplay . load . box . style . display = 'none' ; if ( preview !== undefined ) { renderContainer . removeChild ( preview ) ; preview = undefined ; } loaded = true ; fireEvent ( 'load' ) ; animateInit ( ) ; }

Triggered when render initialization finishes. Handles fading between
scenes as well as showing the compass and hotspots and hiding the loading
display.
@private

Triggered when render initialization finishes . Handles fading between scenes as well as showing the compass and hotspots and hiding the loading display .


function createHotSpots() {
    if (hotspotsCreated) return;

    if (!config.hotSpots) {
        config.hotSpots = [];
    } else {
        // Sort by pitch so tooltip is never obscured by another hot spot
        config.hotSpots = config.hotSpots.sort(function(a, b) {
            return a.pitch < b.pitch;
        });
        config.hotSpots.forEach(createHotSpot);
    }
    hotspotsCreated = true;
    renderHotSpots();
}

function createHotSpots ( ) { if ( hotspotsCreated ) return ; if ( ! config . hotSpots ) { config . hotSpots = [ ] ; } else { config . hotSpots = config . hotSpots . sort ( function ( a , b ) { return a . pitch < b . pitch ; } ) ; config . hotSpots . forEach ( createHotSpot ) ; } hotspotsCreated = true ; renderHotSpots ( ) ; }

Creates hot spot elements for the current scene.
@private

Creates hot spot elements for the current scene .


function destroyHotSpots() {
    var hs = config.hotSpots;
    hotspotsCreated = false;
    delete config.hotSpots;
    if (hs) {
        for (var i = 0; i < hs.length; i++) {
            var current = hs[i].div;
            if (current) {
                while (current.parentNode && current.parentNode != renderContainer) {
                    current = current.parentNode;
                }
                renderContainer.removeChild(current);
            }
            delete hs[i].div;
        }
    }
}

function destroyHotSpots ( ) { var hs = config . hotSpots ; hotspotsCreated = false ; delete config . hotSpots ; if ( hs ) { for ( var i = 0 ; i < hs . length ; i ++ ) { var current = hs [ i ] . div ; if ( current ) { while ( current . parentNode && current . parentNode != renderContainer ) { current = current . parentNode ; } renderContainer . removeChild ( current ) ; } delete hs [ i ] . div ; } } }

Destroys currently created hot spot elements.
@private

Destroys currently created hot spot elements .


function renderHotSpot(hs) {
    var hsPitchSin = Math.sin(hs.pitch * Math.PI / 180),
        hsPitchCos = Math.cos(hs.pitch * Math.PI / 180),
        configPitchSin = Math.sin(config.pitch * Math.PI / 180),
        configPitchCos = Math.cos(config.pitch * Math.PI / 180),
        yawCos = Math.cos((-hs.yaw + config.yaw) * Math.PI / 180);
    var z = hsPitchSin * configPitchSin + hsPitchCos * yawCos * configPitchCos;
    if ((hs.yaw <= 90 && hs.yaw > -90 && z <= 0) ||
      ((hs.yaw > 90 || hs.yaw <= -90) && z <= 0)) {
        hs.div.style.visibility = 'hidden';
    } else {
        var yawSin = Math.sin((-hs.yaw + config.yaw) * Math.PI / 180),
            hfovTan = Math.tan(config.hfov * Math.PI / 360);
        hs.div.style.visibility = 'visible';
        // Subpixel rendering doesn't work in Firefox
        // https://bugzilla.mozilla.org/show_bug.cgi?id=739176
        var canvas = renderer.getCanvas(),
            canvasWidth = canvas.clientWidth,
            canvasHeight = canvas.clientHeight;
        var coord = [-canvasWidth / hfovTan * yawSin * hsPitchCos / z / 2,
            -canvasWidth / hfovTan * (hsPitchSin * configPitchCos -
            hsPitchCos * yawCos * configPitchSin) / z / 2];
        // Apply roll
        var rollSin = Math.sin(config.roll * Math.PI / 180),
            rollCos = Math.cos(config.roll * Math.PI / 180);
        coord = [coord[0] * rollCos - coord[1] * rollSin,
                 coord[0] * rollSin + coord[1] * rollCos];
        // Apply transform
        coord[0] += (canvasWidth - hs.div.offsetWidth) / 2;
        coord[1] += (canvasHeight - hs.div.offsetHeight) / 2;
        var transform = 'translate(' + coord[0] + 'px, ' + coord[1] +
            'px) translateZ(9999px) rotate(' + config.roll + 'deg)';
        hs.div.style.webkitTransform = transform;
        hs.div.style.MozTransform = transform;
        hs.div.style.transform = transform;
    }
}

function
renderHotSpot
(
hs
)
{
var
hsPitchSin
=
Math
.
sin
(
hs
.
pitch
*
Math
.
PI
/
180
)
,
hsPitchCos
=
Math
.
cos
(
hs
.
pitch
*
Math
.
PI
/
180
)
,
configPitchSin
=
Math
.
sin
(
config
.
pitch
*
Math
.
PI
/
180
)
,
configPitchCos
=
Math
.
cos
(
config
.
pitch
*
Math
.
PI
/
180
)
,
yawCos
=
Math
.
cos
(
(
hs
.
yaw
+
config
.
yaw
)
*
Math
.
PI
/
180
)
;
var
z
=
hsPitchSin
*
configPitchSin
+
hsPitchCos
*
yawCos
*
configPitchCos
;
if
(
(
hs
.
yaw
<=
90
&&
hs
.
yaw
>
90
&&
z
<=
0
)
||
(
(
hs
.
yaw
>
90
||
hs
.
yaw
<=
90
)
&&
z
<=
0
)
)
{
hs
.
div
.
style
.
visibility
=
'hidden'
;
}
else
{
var
yawSin
=
Math
.
sin
(
(
hs
.
yaw
+
config
.
yaw
)
*
Math
.
PI
/
180
)
,
hfovTan
=
Math
.
tan
(
config
.
hfov
*
Math
.
PI
/
360
)
;
hs
.
div
.
style
.
visibility
=
'visible'
;
var
canvas
=
renderer
.
getCanvas
(
)
,
canvasWidth
=
canvas
.
clientWidth
,
canvasHeight
=
canvas
.
clientHeight
;
var
coord
=
[
canvasWidth
/
hfovTan
*
yawSin
*
hsPitchCos
/
z
/
2
,
canvasWidth
/
hfovTan
*
(
hsPitchSin
*
configPitchCos
hsPitchCos
*
yawCos
*
configPitchSin
)
/
z
/
2
]
;
var
rollSin
=
Math
.
sin
(
config
.
roll
*
Math
.
PI
/
180
)
,
rollCos
=
Math
.
cos
(
config
.
roll
*
Math
.
PI
/
180
)
;
coord
=
[
coord
[
0
]
*
rollCos
coord
[
1
]
*
rollSin
,
coord
[
0
]
*
rollSin
+
coord
[
1
]
*
rollCos
]
;
coord
[
0
]
+=
(
canvasWidth
hs
.
div
.
offsetWidth
)
/
2
;
coord
[
1
]
+=
(
canvasHeight
hs
.
div
.
offsetHeight
)
/
2
;
var
transform
=
'translate('
+
coord
[
0
]
+
'px, '
+
coord
[
1
]
+
'px) translateZ(9999px) rotate('
+
config
.
roll
+
'deg)'
;
hs
.
div
.
style
.
webkitTransform
=
transform
;
hs
.
div
.
style
.
MozTransform
=
transform
;
hs
.
div
.
style
.
transform
=
transform
;
}
}

Renders hot spot, updating its position and visibility.
@private

Renders hot spot updating its position and visibility .


function mergeConfig(sceneId) {
    config = {};
    var k, s;
    var photoSphereExcludes = ['haov', 'vaov', 'vOffset', 'northOffset', 'horizonPitch', 'horizonRoll'];
    specifiedPhotoSphereExcludes = [];

    // Merge default config
    for (k in defaultConfig) {
        if (defaultConfig.hasOwnProperty(k)) {
            config[k] = defaultConfig[k];
        }
    }

    // Merge default scene config
    for (k in initialConfig.default) {
        if (initialConfig.default.hasOwnProperty(k)) {
            if (k == 'strings') {
                for (s in initialConfig.default.strings) {
                    if (initialConfig.default.strings.hasOwnProperty(s)) {
                        config.strings[s] = escapeHTML(initialConfig.default.strings[s]);
                    }
                }
            } else {
                config[k] = initialConfig.default[k];
                if (photoSphereExcludes.indexOf(k) >= 0) {
                    specifiedPhotoSphereExcludes.push(k);
                }
            }
        }
    }

    // Merge current scene config
    if ((sceneId !== null) && (sceneId !== '') && (initialConfig.scenes) && (initialConfig.scenes[sceneId])) {
        var scene = initialConfig.scenes[sceneId];
        for (k in scene) {
            if (scene.hasOwnProperty(k)) {
                if (k == 'strings') {
                    for (s in scene.strings) {
                        if (scene.strings.hasOwnProperty(s)) {
                            config.strings[s] = escapeHTML(scene.strings[s]);
                        }
                    }
                } else {
                    config[k] = scene[k];
                    if (photoSphereExcludes.indexOf(k) >= 0) {
                        specifiedPhotoSphereExcludes.push(k);
                    }
                }
            }
        }
        config.scene = sceneId;
    }

    // Merge initial config
    for (k in initialConfig) {
        if (initialConfig.hasOwnProperty(k)) {
            if (k == 'strings') {
                for (s in initialConfig.strings) {
                    if (initialConfig.strings.hasOwnProperty(s)) {
                        config.strings[s] = escapeHTML(initialConfig.strings[s]);
                    }
                }
            } else {
                config[k] = initialConfig[k];
                if (photoSphereExcludes.indexOf(k) >= 0) {
                    specifiedPhotoSphereExcludes.push(k);
                }
            }
        }
    }
}

function mergeConfig ( sceneId ) { config = { } ; var k , s ; var photoSphereExcludes = [ 'haov' , 'vaov' , 'vOffset' , 'northOffset' , 'horizonPitch' , 'horizonRoll' ] ; specifiedPhotoSphereExcludes = [ ] ; for ( k in defaultConfig ) { if ( defaultConfig . hasOwnProperty ( k ) ) { config [ k ] = defaultConfig [ k ] ; } } for ( k in initialConfig . default ) { if ( initialConfig . default . hasOwnProperty ( k ) ) { if ( k == 'strings' ) { for ( s in initialConfig . default . strings ) { if ( initialConfig . default . strings . hasOwnProperty ( s ) ) { config . strings [ s ] = escapeHTML ( initialConfig . default . strings [ s ] ) ; } } } else { config [ k ] = initialConfig . default [ k ] ; if ( photoSphereExcludes . indexOf ( k ) >= 0 ) { specifiedPhotoSphereExcludes . push ( k ) ; } } } } if ( ( sceneId !== null ) && ( sceneId !== '' ) && ( initialConfig . scenes ) && ( initialConfig . scenes [ sceneId ] ) ) { var scene = initialConfig . scenes [ sceneId ] ; for ( k in scene ) { if ( scene . hasOwnProperty ( k ) ) { if ( k == 'strings' ) { for ( s in scene . strings ) { if ( scene . strings . hasOwnProperty ( s ) ) { config . strings [ s ] = escapeHTML ( scene . strings [ s ] ) ; } } } else { config [ k ] = scene [ k ] ; if ( photoSphereExcludes . indexOf ( k ) >= 0 ) { specifiedPhotoSphereExcludes . push ( k ) ; } } } } config . scene = sceneId ; } for ( k in initialConfig ) { if ( initialConfig . hasOwnProperty ( k ) ) { if ( k == 'strings' ) { for ( s in initialConfig . strings ) { if ( initialConfig . strings . hasOwnProperty ( s ) ) { config . strings [ s ] = escapeHTML ( initialConfig . strings [ s ] ) ; } } } else { config [ k ] = initialConfig [ k ] ; if ( photoSphereExcludes . indexOf ( k ) >= 0 ) { specifiedPhotoSphereExcludes . push ( k ) ; } } } } }

Merges a scene configuration into the current configuration.
@private
@param {string} sceneId - Identifier of scene configuration to merge in.

Merges a scene configuration into the current configuration .


function toggleFullscreen() {
    if (loaded && !error) {
        if (!fullscreenActive) {
            try {
                if (container.requestFullscreen) {
                    container.requestFullscreen();
                } else if (container.mozRequestFullScreen) {
                    container.mozRequestFullScreen();
                } else if (container.msRequestFullscreen) {
                    container.msRequestFullscreen();
                } else {
                    container.webkitRequestFullScreen();
                }
            } catch(event) {
                // Fullscreen doesn't work
            }
        } else {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitCancelFullScreen) {
                document.webkitCancelFullScreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            }
        }
    }
}

function toggleFullscreen ( ) { if ( loaded && ! error ) { if ( ! fullscreenActive ) { try { if ( container . requestFullscreen ) { container . requestFullscreen ( ) ; } else if ( container . mozRequestFullScreen ) { container . mozRequestFullScreen ( ) ; } else if ( container . msRequestFullscreen ) { container . msRequestFullscreen ( ) ; } else { container . webkitRequestFullScreen ( ) ; } } catch ( event ) { } } else { if ( document . exitFullscreen ) { document . exitFullscreen ( ) ; } else if ( document . mozCancelFullScreen ) { document . mozCancelFullScreen ( ) ; } else if ( document . webkitCancelFullScreen ) { document . webkitCancelFullScreen ( ) ; } else if ( document . msExitFullscreen ) { document . msExitFullscreen ( ) ; } } } }


function onFullScreenChange(resize) {
    if (document.fullscreenElement || document.fullscreen || document.mozFullScreen || document.webkitIsFullScreen || document.msFullscreenElement) {
        controls.fullscreen.classList.add('pnlm-fullscreen-toggle-button-active');
        fullscreenActive = true;
    } else {
        controls.fullscreen.classList.remove('pnlm-fullscreen-toggle-button-active');
        fullscreenActive = false;
    }
    if (resize !== 'resize')
        fireEvent('fullscreenchange', fullscreenActive);
    // Resize renderer (deal with browser quirks and fixes #155)
    renderer.resize();
    setHfov(config.hfov);
    animateInit();
}

function onFullScreenChange ( resize ) { if ( document . fullscreenElement || document . fullscreen || document . mozFullScreen || document . webkitIsFullScreen || document . msFullscreenElement ) { controls . fullscreen . classList . add ( 'pnlm-fullscreen-toggle-button-active' ) ; fullscreenActive = true ; } else { controls . fullscreen . classList . remove ( 'pnlm-fullscreen-toggle-button-active' ) ; fullscreenActive = false ; } if ( resize !== 'resize' ) fireEvent ( 'fullscreenchange' , fullscreenActive ) ; renderer . resize ( ) ; setHfov ( config . hfov ) ; animateInit ( ) ; }

Event handler for fullscreen changes.
@private


function constrainHfov(hfov) {
    // Keep field of view within bounds
    var minHfov = config.minHfov;
    if (config.type == 'multires' && renderer && config.multiResMinHfov) {
        minHfov = Math.min(minHfov, renderer.getCanvas().width / (config.multiRes.cubeResolution / 90 * 0.9));
    }
    if (minHfov > config.maxHfov) {
        // Don't change view if bounds don't make sense
        console.log('HFOV bounds do not make sense (minHfov > maxHfov).')
        return config.hfov;
    }
    var newHfov = config.hfov;
    if (hfov < minHfov) {
        newHfov = minHfov;
    } else if (hfov > config.maxHfov) {
        newHfov = config.maxHfov;
    } else {
        newHfov = hfov;
    }
    // Optionally avoid showing background (empty space) on top or bottom by adapting newHfov
    if (config.avoidShowingBackground && renderer) {
        var canvas = renderer.getCanvas();
        newHfov = Math.min(newHfov,
                           Math.atan(Math.tan((config.maxPitch - config.minPitch) / 360 * Math.PI) /
                                     canvas.height * canvas.width)
                               * 360 / Math.PI);
    }
    return newHfov;
}

Clamps horzontal field of view to viewer's limits.
@private
@param {number} hfov - Input horizontal field of view (in degrees)
@return {number} - Clamped horizontal field of view (in degrees)

Clamps horzontal field of view to viewer s limits .


function stopAnimation() {
    animatedMove = {};
    autoRotateSpeed = config.autoRotate ? config.autoRotate : autoRotateSpeed;
    config.autoRotate = false;
}

function stopAnimation ( ) { animatedMove = { } ; autoRotateSpeed = config . autoRotate ? config . autoRotate : autoRotateSpeed ; config . autoRotate = false ; }

Stops auto rotation and animated moves.
@private

Stops auto rotation and animated moves .


function load() {
    // Since WebGL error handling is very general, first we clear any error box
    // since it is a new scene and the error from previous maybe because of lacking
    // memory etc and not because of a lack of WebGL support etc
    clearError();
    loaded = false;

    controls.load.style.display = 'none';
    infoDisplay.load.box.style.display = 'inline';
    init();
}

function load ( ) { clearError ( ) ; loaded = false ; controls . load . style . display = 'none' ; infoDisplay . load . box . style . display = 'inline' ; init ( ) ; }


function loadScene(sceneId, targetPitch, targetYaw, targetHfov, fadeDone) {
    loaded = false;
    animatedMove = {};

    // Set up fade if specified
    var fadeImg, workingPitch, workingYaw, workingHfov;
    if (config.sceneFadeDuration && !fadeDone) {
        var data = renderer.render(config.pitch * Math.PI / 180, config.yaw * Math.PI / 180, config.hfov * Math.PI / 180, {returnImage: true});
        if (data !== undefined) {
            fadeImg = new Image();
            fadeImg.className = 'pnlm-fade-img';
            fadeImg.style.transition = 'opacity ' + (config.sceneFadeDuration / 1000) + 's';
            fadeImg.style.width = '100%';
            fadeImg.style.height = '100%';
            fadeImg.onload = function() {
                loadScene(sceneId, targetPitch, targetYaw, targetHfov, true);
            };
            fadeImg.src = data;
            renderContainer.appendChild(fadeImg);
            renderer.fadeImg = fadeImg;
            return;
        }
    }

    // Set new pointing
    if (targetPitch === 'same') {
        workingPitch = config.pitch;
    } else {
        workingPitch = targetPitch;
    }
    if (targetYaw === 'same') {
        workingYaw = config.yaw;
    } else if (targetYaw === 'sameAzimuth') {
        workingYaw = config.yaw + (config.northOffset || 0) - (initialConfig.scenes[sceneId].northOffset || 0);
    } else {
        workingYaw = targetYaw;
    }
    if (targetHfov === 'same') {
        workingHfov = config.hfov;
    } else {
        workingHfov = targetHfov;
    }

    // Destroy hot spots from previous scene
    destroyHotSpots();

    // Create the new config for the scene
    mergeConfig(sceneId);

    // Stop motion
    speed.yaw = speed.pitch = speed.hfov = 0;

    // Reload scene
    processOptions();
    if (workingPitch !== undefined) {
        config.pitch = workingPitch;
    }
    if (workingYaw !== undefined) {
        config.yaw = workingYaw;
    }
    if (workingHfov !== undefined) {
        config.hfov = workingHfov;
    }
    fireEvent('scenechange', sceneId);
    load();

    // Properly handle switching to dynamic scenes
    update = config.dynamicUpdate === true;
    if (config.dynamic) {
        panoImage = config.panorama;
        onImageLoad();
    }
}

function
loadScene
(
sceneId
,
targetPitch
,
targetYaw
,
targetHfov
,
fadeDone
)
{
loaded
=
false
;
animatedMove
=
{
}
;
var
fadeImg
,
workingPitch
,
workingYaw
,
workingHfov
;
if
(
config
.
sceneFadeDuration
&&
!
fadeDone
)
{
var
data
=
renderer
.
render
(
config
.
pitch
*
Math
.
PI
/
180
,
config
.
yaw
*
Math
.
PI
/
180
,
config
.
hfov
*
Math
.
PI
/
180
,
{
returnImage
:
true
}
)
;
if
(
data
!==
undefined
)
{
fadeImg
=
new
Image
(
)
;
fadeImg
.
className
=
'pnlm-fade-img'
;
fadeImg
.
style
.
transition
=
'opacity '
+
(
config
.
sceneFadeDuration
/
1000
)
+
's'
;
fadeImg
.
style
.
width
=
'100%'
;
fadeImg
.
style
.
height
=
'100%'
;
fadeImg
.
onload
=
function
(
)
{
loadScene
(
sceneId
,
targetPitch
,
targetYaw
,
targetHfov
,
true
)
;
}
;
fadeImg
.
src
=
data
;
renderContainer
.
appendChild
(
fadeImg
)
;
renderer
.
fadeImg
=
fadeImg
;
return
;
}
}
if
(
targetPitch
===
'same'
)
{
workingPitch
=
config
.
pitch
;
}
else
{
workingPitch
=
targetPitch
;
}
if
(
targetYaw
===
'same'
)
{
workingYaw
=
config
.
yaw
;
}
else
if
(
targetYaw
===
'sameAzimuth'
)
{
workingYaw
=
config
.
yaw
+
(
config
.
northOffset
||
0
)
(
initialConfig
.
scenes
[
sceneId
]
.
northOffset
||
0
)
;
}
else
{
workingYaw
=
targetYaw
;
}
if
(
targetHfov
===
'same'
)
{
workingHfov
=
config
.
hfov
;
}
else
{
workingHfov
=
targetHfov
;
}
destroyHotSpots
(
)
;
mergeConfig
(
sceneId
)
;
speed
.
yaw
=
speed
.
pitch
=
speed
.
hfov
=
0
;
processOptions
(
)
;
if
(
workingPitch
!==
undefined
)
{
config
.
pitch
=
workingPitch
;
}
if
(
workingYaw
!==
undefined
)
{
config
.
yaw
=
workingYaw
;
}
if
(
workingHfov
!==
undefined
)
{
config
.
hfov
=
workingHfov
;
}
fireEvent
(
'scenechange'
,
sceneId
)
;
load
(
)
;
update
=
config
.
dynamicUpdate
===
true
;
if
(
config
.
dynamic
)
{
panoImage
=
config
.
panorama
;
onImageLoad
(
)
;
}
}

Loads scene.
@private
@param {string} sceneId - Identifier of scene configuration to merge in.
@param {number} targetPitch - Pitch viewer should be centered on once scene loads.
@param {number} targetYaw - Yaw viewer should be centered on once scene loads.
@param {number} targetHfov - HFOV viewer should use once scene loads.
@param {boolean} [fadeDone] - If `true`, fade setup is skipped.


function stopOrientation() {
    window.removeEventListener('deviceorientation', orientationListener);
    controls.orientation.classList.remove('pnlm-orientation-button-active');
    orientation = false;
}

function stopOrientation ( ) { window . removeEventListener ( 'deviceorientation' , orientationListener ) ; controls . orientation . classList . remove ( 'pnlm-orientation-button-active' ) ; orientation = false ; }


function fireEvent(type) {
    if (type in externalEventListeners) {
        // Reverse iteration is useful, if event listener is removed inside its definition
        for (var i = externalEventListeners[type].length; i > 0; i--) {
            externalEventListeners[type][externalEventListeners[type].length - i].apply(null, [].slice.call(arguments, 1));
        }
    }
}

function fireEvent ( type ) { if ( type in externalEventListeners ) { for ( var i = externalEventListeners [ type ] . length ; i > 0 ; i -- ) { externalEventListeners [ type ] [ externalEventListeners [ type ] . length - i ] . apply ( null , [ ] . slice . call ( arguments , 1 ) ) ; } } }

Fire listeners attached to specified event.
@private
@param {string} [type] - Type of event to fire listeners for.

Fire listeners attached to specified event .


function(latchFunction, optional_timeoutMessage, optional_timeout) {
  jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments);
}

function ( latchFunction , optional_timeoutMessage , optional_timeout ) { jasmine . getEnv ( ) . currentSpec . waitsFor . apply ( jasmine . getEnv ( ) . currentSpec , arguments ) ; }

Waits for the latchFunction to return true before proceeding to the next block.

@param {Function} latchFunction
@param {String} optional_timeoutMessage
@param {Number} optional_timeout

Waits for the latchFunction to return true before proceeding to the next block .


function $getMouseOffset(target, ev){
    ev = ev || _window.event;
    var docPos    = $getPosition(target);
    var mousePos  = $mouseCoords(ev);
    return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function $getMouseOffset ( target , ev ) { ev = ev || _window . event ; var docPos = $getPosition ( target ) ; var mousePos = $mouseCoords ( ev ) ; return { x : mousePos . x - docPos . x , y : mousePos . y - docPos . y } ; }


function(val, flags){
    number_check(val)
    if(! flags.precision){
        if(! flags.decimal_point){
            flags.precision = 6
        }else{
            flags.precision = 0
        }
    }else{
        flags.precision = parseInt(flags.precision, 10)
        validate_precision(flags.precision)
    }
    return parseFloat(val)
}

function ( val , flags ) { number_check ( val ) if ( ! flags . precision ) { if ( ! flags . decimal_point ) { flags . precision = 6 } else { flags . precision = 0 } } else { flags . precision = parseInt ( flags . precision , 10 ) validate_precision ( flags . precision ) } return parseFloat ( val ) }

converts val to float and sets precision if missing


function(self, other){
    if(_b_.isinstance(other, int)) {
        if(other.__class__ === $B.long_int){
            return $B.long_int.__sub__($B.long_int.$factory(self),
                $B.long_int.$factory(other))
        }
        other = int_value(other)
        if(self > $B.max_int32 || self < $B.min_int32 ||
                other > $B.max_int32 || other < $B.min_int32){
            return $B.long_int.__sub__($B.long_int.$factory(self),
                $B.long_int.$factory(other))
        }
        return self - other
    }
    if(_b_.isinstance(other, _b_.bool)){return self - other}
    var rsub = $B.$getattr(other, "__rsub__", _b_.None)
    if(rsub !== _b_.None){return rsub(self)}
    $err("-", other)
}

function ( self , other ) { if ( _b_ . isinstance ( other , int ) ) { if ( other . __class__ === $B . long_int ) { return $B . long_int . __sub__ ( $B . long_int . $factory ( self ) , $B . long_int . $factory ( other ) ) } other = int_value ( other ) if ( self > $B . max_int32 || self < $B . min_int32 || other > $B . max_int32 || other < $B . min_int32 ) { return $B . long_int . __sub__ ( $B . long_int . $factory ( self ) , $B . long_int . $factory ( other ) ) } return self - other } if ( _b_ . isinstance ( other , _b_ . bool ) ) { return self - other } var rsub = $B . $getattr ( other , "__rsub__" , _b_ . None ) if ( rsub !== _b_ . None ) { return rsub ( self ) } $err ( "-" , other ) }


function(self, other){
    if(_b_.isinstance(other, int)){
        other = int_value(other)
        if(typeof other == "number"){
            var res = self.valueOf() - other.valueOf()
            if(res > $B.min_int && res < $B.max_int){return res}
            else{return $B.long_int.__sub__($B.long_int.$factory(self),
                $B.long_int.$factory(other))}
        }else if(typeof other == "boolean"){
            return other ? self - 1 : self
        }else{
            return $B.long_int.__sub__($B.long_int.$factory(self),
                $B.long_int.$factory(other))
        }
    }
    if(_b_.isinstance(other, _b_.float)){
        return new Number(self - other)
    }
    if(_b_.isinstance(other, _b_.complex)){
        return $B.make_complex(self - other.$real, -other.$imag)
    }
    if(_b_.isinstance(other, _b_.bool)){
         var bool_value = 0;
         if(other.valueOf()){bool_value = 1}
         return self - bool_value
    }
    if(_b_.isinstance(other, _b_.complex)){
        return $B.make_complex(self.valueOf() - other.$real, other.$imag)
    }
    var rsub = $B.$getattr(other, "__rsub__", _b_.None)
    if(rsub !== _b_.None){return rsub(self)}
    throw $err("-", other)
}

function ( self , other ) { if ( _b_ . isinstance ( other , int ) ) { other = int_value ( other ) if ( typeof other == "number" ) { var res = self . valueOf ( ) - other . valueOf ( ) if ( res > $B . min_int && res < $B . max_int ) { return res } else { return $B . long_int . __sub__ ( $B . long_int . $factory ( self ) , $B . long_int . $factory ( other ) ) } } else if ( typeof other == "boolean" ) { return other ? self - 1 : self } else { return $B . long_int . __sub__ ( $B . long_int . $factory ( self ) , $B . long_int . $factory ( other ) ) } } if ( _b_ . isinstance ( other , _b_ . float ) ) { return new Number ( self - other ) } if ( _b_ . isinstance ( other , _b_ . complex ) ) { return $B . make_complex ( self - other . $real , - other . $imag ) } if ( _b_ . isinstance ( other , _b_ . bool ) ) { var bool_value = 0 ; if ( other . valueOf ( ) ) { bool_value = 1 } return self - bool_value } if ( _b_ . isinstance ( other , _b_ . complex ) ) { return $B . make_complex ( self . valueOf ( ) - other . $real , other . $imag ) } var rsub = $B . $getattr ( other , "__rsub__" , _b_ . None ) if ( rsub !== _b_ . None ) { return rsub ( self ) } throw $err ( "-" , other ) }


function inlineResourcesFromString(content, urlResolver) {
  // Curry through the inlining functions.
  return [
    inlineTemplate,
    inlineStyle,
    removeModuleId
  ].reduce((content, fn) => fn(content, urlResolver), content);
}

function inlineResourcesFromString ( content , urlResolver ) { return [ inlineTemplate , inlineStyle , removeModuleId ] . reduce ( ( content , fn ) => fn ( content , urlResolver ) , content ) ; }

Inline resources from a string content.
@param content {string} The source file's content.
@param urlResolver {Function} A resolver that takes a URL and return a path.
@returns {string} The content with resources inlined.

Inline resources from a string content .


function buildSass(content, sourceFile) {
  try {
    const result = sass.renderSync({
      data: content,
      file: sourceFile,
      importer: tildeImporter
    });
    return result.css.toString()
  } catch (e) {
    console.error('\x1b[41m');
    console.error('at ' + sourceFile + ':' + e.line + ":" + e.column);
    console.error(e.formatted);
    console.error('\x1b[0m');
    return "";
  }
}

function
buildSass
(
content
,
sourceFile
)
{
try
{
const
result
=
sass
.
renderSync
(
{
data
:
content
,
file
:
sourceFile
,
importer
:
tildeImporter
}
)
;
return
result
.
css
.
toString
(
)
}
catch
(
e
)
{
console
.
error
(
'\x1b[41m'
)
;
\x1b
console
.
error
(
'at '
+
sourceFile
+
':'
+
e
.
line
+
":"
+
e
.
column
)
;
console
.
error
(
e
.
formatted
)
;
console
.
error
(
'\x1b[0m'
)
;
}
}

build sass content to css
@param content {string} the css content
@param sourceFile {string} the scss file sourceFile
@return {string} the generated css, empty string if error occured


function FormioResourceRoutes(config) {
    config = config || {};
    return [
        {
            path: '',
            component: config.index || index_component_1.FormioResourceIndexComponent
        },
        {
            path: 'new',
            component: config.create || create_component_1.FormioResourceCreateComponent
        },
        {
            path: ':id',
            component: config.resource || resource_component_1.FormioResourceComponent,
            children: [
                {
                    path: '',
                    redirectTo: 'view',
                    pathMatch: 'full'
                },
                {
                    path: 'view',
                    component: config.view || view_component_1.FormioResourceViewComponent
                },
                {
                    path: 'edit',
                    component: config.edit || edit_component_1.FormioResourceEditComponent
                },
                {
                    path: 'delete',
                    component: config.delete || delete_component_1.FormioResourceDeleteComponent
                }
            ]
        }
    ];
}

function FormioResourceRoutes ( config ) { config = config || { } ; return [ { path : '' , component : config . index || index_component_1 . FormioResourceIndexComponent } , { path : 'new' , component : config . create || create_component_1 . FormioResourceCreateComponent } , { path : ':id' , component : config . resource || resource_component_1 . FormioResourceComponent , children : [ { path : '' , redirectTo : 'view' , pathMatch : 'full' } , { path : 'view' , component : config . view || view_component_1 . FormioResourceViewComponent } , { path : 'edit' , component : config . edit || edit_component_1 . FormioResourceEditComponent } , { path : 'delete' , component : config . delete || delete_component_1 . FormioResourceDeleteComponent } ] } ] ; }


function BaseProducer (client, options, defaultPartitionerType, customPartitioner) {
  EventEmitter.call(this);
  options = options || {};

  this.ready = false;
  this.client = client;

  this.requireAcks = options.requireAcks === undefined ? DEFAULTS.requireAcks : options.requireAcks;
  this.ackTimeoutMs = options.ackTimeoutMs === undefined ? DEFAULTS.ackTimeoutMs : options.ackTimeoutMs;

  if (customPartitioner !== undefined && options.partitionerType !== PARTITIONER_TYPES.custom) {
    throw new Error('Partitioner Type must be custom if providing a customPartitioner.');
  } else if (customPartitioner === undefined && options.partitionerType === PARTITIONER_TYPES.custom) {
    throw new Error('No customer partitioner defined');
  }

  var partitionerType = PARTITIONER_MAP[options.partitionerType] || PARTITIONER_MAP[defaultPartitionerType];

  // eslint-disable-next-line
  this.partitioner = new partitionerType(customPartitioner);

  this.connect();
}

Provides common functionality for a kafka producer

@param {Client} client A kafka client object to use for the producer
@param {Object} [options] An object containing configuration options
@param {Number} [options.requireAcks=1] Configuration for when to consider a message as acknowledged.

0 = No ack required

1 = Leader ack required

-1 = All in sync replicas ack required

@param {Number} [options.ackTimeoutMs=100] The amount of time in milliseconds to wait for all acks before considered
the message as errored
@param {Number} [defaultPartitionType] The default partitioner type
@param {Object} [customPartitioner] a custom partitinoer to use of the form: function (partitions, key)
@constructor


function Context (options) {
  if (!options) options = { body: '', hostname: '' };

  const body = options.body;
  const href = 'http://' + options.hostname + '/';
  const cache = Object.create(null);
  const keys = [];

  this.atob = function (str) {
    return Buffer.from(str, 'base64').toString('binary');
  };

  // Used for eval during onRedirectChallenge
  this.location = { reload: function () {} };

  this.document = {
    createElement: function () {
      return { firstChild: { href: href } };
    },
    getElementById: function (id) {
      if (keys.indexOf(id) === -1) {
        const re = new RegExp(' id=[\'"]?' + id + '[^>]*>([^<]*)');
        const match = body.match(re);

        keys.push(id);
        cache[id] = match === null ? match : { innerHTML: match[1] };
      }

      return cache[id];
    }
  };
}

function
Context
(
options
)
{
if
(
!
options
)
options
=
{
body
:
''
,
hostname
:
''
}
;
const
body
=
options
.
body
;
const
href
=
'http://'
+
options
.
hostname
+
'/'
;
const
cache
=
Object
.
create
(
)
;
const
keys
=
[
]
;
this
.
atob
=
function
(
str
)
{
return
Buffer
.
from
(
str
,
'base64'
)
.
toString
(
'binary'
)
;
}
;
this
.
location
=
{
reload
:
function
(
)
{
}
}
;
this
.
document
=
{
createElement
:
function
(
)
{
return
{
firstChild
:
{
href
:
href
}
}
;
}
,
getElementById
:
function
(
id
)
{
if
(
keys
.
indexOf
(
id
)
===
1
)
{
const
re
=
new
RegExp
(
' id=[\'"]?'
+
\'
+
id
)
;
'[^>]*>([^<]*)'
const
match
=
body
.
match
(
re
)
;
keys
.
push
(
id
)
;
}
cache
[
id
]
=
match
===
match
:
{
innerHTML
:
match
[
1
]
}
;
}
}
;
}

Global context used to evaluate standard IUAM JS challenge


function alternative (options, { captcha: { url, siteKey } }) {
  // Here you do some magic with the siteKey provided by cloudscraper
  console.error('The url is "' + url + '"');
  console.error('The site key is "' + siteKey + '"');
  return Promise.reject(new Error('This is a dummy function'));
}

function
alternative
(
options
,
{
captcha
:
{
url
,
siteKey
}
}
)
{
console
.
error
(
'The url is "'
+
url
+
'"'
)
;
console
.
error
(
'The site key is "'
+
siteKey
+
'"'
)
;
return
Promise
.
reject
(
new
Error
(
'This is a dummy function'
)
)
;
}

An example handler with destructuring arguments


function performRequest (options, isFirstRequest) {
  // This should be the default export of either request or request-promise.
  const requester = options.requester;

  // Note that request is always an instanceof ReadableStream, EventEmitter
  // If the requester is request-promise, it is also thenable.
  const request = requester(options);

  // We must define the host header ourselves to preserve case and order.
  if (request.getHeader('host') === HOST) {
    request.setHeader('host', request.uri.host);
  }

  // If the requester is not request-promise, ensure we get a callback.
  if (typeof request.callback !== 'function') {
    throw new TypeError('Expected a callback function, got ' +
        typeof (request.callback) + ' instead.');
  }

  // We only need the callback from the first request.
  // The other callbacks can be safely ignored.
  if (isFirstRequest) {
    // This should be a user supplied callback or request-promise's callback.
    // The callback is always wrapped/bound to the request instance.
    options.callback = request.callback;
  }

  request.removeAllListeners('error')
    .once('error', function (error) {
      onRequestResponse(options, error);
    });

  request.removeAllListeners('complete')
    .once('complete', function (response, body) {
      onRequestResponse(options, null, response, body);
    });

  // Indicate that this is a cloudscraper request
  request.cloudscraper = true;
  return request;
}

function
performRequest
(
options
,
isFirstRequest
)
{
const
requester
=
options
.
requester
;
const
request
=
requester
(
options
)
;
if
(
request
.
getHeader
(
'host'
)
===
HOST
)
{
request
.
setHeader
(
'host'
,
request
.
uri
.
host
)
;
}
if
(
typeof
request
.
callback
!==
'function'
)
{
throw
new
TypeError
(
'Expected a callback function, got '
+
typeof
(
request
.
callback
)
+
' instead.'
)
;
}
if
(
isFirstRequest
)
{
options
.
callback
=
request
.
callback
;
}
request
.
removeAllListeners
(
'error'
)
.
once
(
'error'
,
function
(
error
)
{
onRequestResponse
(
options
,
error
)
;
}
)
;
request
.
removeAllListeners
(
'complete'
)
.
once
(
'complete'
,
function
(
response
,
body
)
{
onRequestResponse
(
options
,
,
response
,
body
)
;
}
)
;
request
.
cloudscraper
=
true
;
return
request
;
}

This function is wrapped to ensure that we get new options on first call. The options object is reused in subsequent calls when calling it directly.

This function is wrapped to ensure that we get new options on first call . The options object is reused in subsequent calls when calling it directly .


function onRequestResponse (options, error, response, body) {
  const callback = options.callback;

  // Encoding is null so body should be a buffer object
  if (error || !body || !body.toString) {
    // Pure request error (bad connection, wrong url, etc)
    return callback(new RequestError(error, options, response));
  }

  response.responseStartTime = Date.now();
  response.isCloudflare = /^cloudflare/i.test('' + response.caseless.get('server'));
  response.isHTML = /text\/html/i.test('' + response.caseless.get('content-type'));

  // If body isn't a buffer, this is a custom response body.
  if (!Buffer.isBuffer(body)) {
    return callback(null, response, body);
  }

  // Decompress brotli compressed responses
  if (/\bbr\b/i.test('' + response.caseless.get('content-encoding'))) {
    if (!brotli.isAvailable) {
      const cause = 'Received a Brotli compressed response. Please install brotli';
      return callback(new RequestError(cause, options, response));
    }

    response.body = body = brotli.decompress(body);
  }

  if (response.isCloudflare && response.isHTML) {
    onCloudflareResponse(options, response, body);
  } else {
    onRequestComplete(options, response, body);
  }
}

The argument convention is options first where possible, options always before response, and body always after response.

The argument convention is options first where possible options always before response and body always after response .


function onCaptcha (options, response, body) {
  const callback = options.callback;
  // UDF that has the responsibility of returning control back to cloudscraper
  const handler = options.onCaptcha;
  // The form data to send back to Cloudflare
  const payload = { /* s, g-re-captcha-response */ };

  let cause;
  let match;

  match = body.match(/<form(?: [^<>]*)? id=["']?challenge-form['"]?(?: [^<>]*)?>([\S\s]*?)<\/form>/);
  if (!match) {
    cause = 'Challenge form extraction failed';
    return callback(new ParserError(cause, options, response));
  }

  // Defining response.challengeForm for debugging purposes
  const form = response.challengeForm = match[1];

  match = form.match(/\/recaptcha\/api\/fallback\?k=([^\s"'<>]*)/);
  if (!match) {
    // The site key wasn't inside the form so search the entire document
    match = body.match(/data-sitekey=["']?([^\s"'<>]*)/);
    if (!match) {
      cause = 'Unable to find the reCAPTCHA site key';
      return callback(new ParserError(cause, options, response));
    }
  }

  // Everything that is needed to solve the reCAPTCHA
  response.captcha = {
    url: response.request.uri.href,
    siteKey: match[1],
    form: payload
  };

  // Adding formData
  match = form.match(/<input(?: [^<>]*)? name=[^<>]+>/g);
  if (!match) {
    cause = 'Challenge form is missing inputs';
    return callback(new ParserError(cause, options, response));
  }

  const inputs = match;
  // Only adding inputs that have both a name and value defined
  for (let name, value, i = 0; i < inputs.length; i++) {
    name = inputs[i].match(/name=["']?([^\s"'<>]*)/);
    if (name) {
      value = inputs[i].match(/value=["']?([^\s"'<>]*)/);
      if (value) {
        payload[name[1]] = value[1];
      }
    }
  }

  // Sanity check
  if (!payload['s']) {
    cause = 'Challenge form is missing secret input';
    return callback(new ParserError(cause, options, response));
  }

  // The callback used to green light form submission
  const submit = function (error) {
    if (error) {
      // Pass an user defined error back to the original request call
      return callback(new CaptchaError(error, options, response));
    }

    onSubmitCaptcha(options, response, body);
  };

  // This seems like an okay-ish API (fewer arguments to the handler)
  response.captcha.submit = submit;

  // We're handing control over to the user now.
  const thenable = handler(options, response, body);
  // Handle the case where the user returns a promise
  if (thenable && typeof thenable.then === 'function') {
    // eslint-disable-next-line promise/catch-or-return
    thenable.then(submit, function (error) {
      if (!error) {
        // The user broke their promise with a falsy error
        submit(new Error('Falsy error'));
      } else {
        submit(error);
      }
    });
  }
}

Parses the reCAPTCHA form and hands control over to the user


function (error) {
    if (error) {
      // Pass an user defined error back to the original request call
      return callback(new CaptchaError(error, options, response));
    }

    onSubmitCaptcha(options, response, body);
  }

function ( error ) { if ( error ) { return callback ( new CaptchaError ( error , options , response ) ) ; } onSubmitCaptcha ( options , response , body ) ; }

The callback used to green light form submission


function assets(userOptions = {}) {
  const options = {
    ...defaults,
    ...userOptions,
  };

  return (files, metalsmith, cb) => {
    const src = metalsmith.path(options.source);
    const dest = options.destination;

    // copied almost line for line from https://github.com/segmentio/metalsmith/blob/master/lib/index.js
    readdir(src, (readDirError, arr) => {
      if (readDirError) {
        cb(readDirError);
        return;
      }

      each(arr, read, err => cb(err, files));
    });

    function read(file, done) {
      const name = path.join(dest, path.relative(src, file));
      fs.stat(file, (statError, stats) => {
        if (statError) {
          done(statError);
          return;
        }

        fs.readFile(file, (err, buffer) => {
          if (err) {
            done(err);
            return;
          }

          const newFile = {};

          newFile.contents = buffer;
          newFile.stats = stats;

          newFile.mode = mode(stats).toOctal();
          files[name] = newFile;
          done();
        });
      });
    }
  };
}

function assets ( userOptions = { } ) { const options = { ... defaults , ... userOptions , } ; return ( files , metalsmith , cb ) => { const src = metalsmith . path ( options . source ) ; const dest = options . destination ; readdir ( src , ( readDirError , arr ) => { if ( readDirError ) { cb ( readDirError ) ; return ; } each ( arr , read , err => cb ( err , files ) ) ; } ) ; function read ( file , done ) { const name = path . join ( dest , path . relative ( src , file ) ) ; fs . stat ( file , ( statError , stats ) => { if ( statError ) { done ( statError ) ; return ; } fs . readFile ( file , ( err , buffer ) => { if ( err ) { done ( err ) ; return ; } const newFile = { } ; newFile . contents = buffer ; newFile . stats = stats ; newFile . mode = mode ( stats ) . toOctal ( ) ; files [ name ] = newFile ; done ( ) ; } ) ; } ) ; } } ; }

Metalsmith plugin to include static assets.

@param {Object} userOptions (optional)
@property {String} source Path to copy static assets from (relative to working directory). Defaults to './public'
@property {String} destination Path to copy static assets to (relative to destination directory). Defaults to '.'
@return {Function} a Metalsmith plugin

Metalsmith plugin to include static assets .


function getStartStopBoundaries(parent, sidebar, topOffset) {
  const bbox = parent.getBoundingClientRect();
  const sidebarBbox = sidebar.getBoundingClientRect();
  const bodyBbox = document.body.getBoundingClientRect();

  const containerAbsoluteTop = bbox.top - bodyBbox.top;
  const sidebarAbsoluteTop = sidebarBbox.top - bodyBbox.top;
  const marginTop = sidebarAbsoluteTop - containerAbsoluteTop;
  const start = containerAbsoluteTop - topOffset;
  const stop = bbox.height + containerAbsoluteTop - sidebarBbox.height - marginTop - topOffset;

  return {
    start,
    stop,
  };
}

function getStartStopBoundaries ( parent , sidebar , topOffset ) { const bbox = parent . getBoundingClientRect ( ) ; const sidebarBbox = sidebar . getBoundingClientRect ( ) ; const bodyBbox = document . body . getBoundingClientRect ( ) ; const containerAbsoluteTop = bbox . top - bodyBbox . top ; const sidebarAbsoluteTop = sidebarBbox . top - bodyBbox . top ; const marginTop = sidebarAbsoluteTop - containerAbsoluteTop ; const start = containerAbsoluteTop - topOffset ; const stop = bbox . height + containerAbsoluteTop - sidebarBbox . height - marginTop - topOffset ; return { start , stop , } ; }

Defines the limits where to start or stop the stickiness
@param {HTMLElement} parent the outer container of the sidebar
@param {HTMLElement} sidebar the sidebar
@param {number} topOffset an optional top offset for sticky menu


function around (obj, method, fn) {
  var old = obj[method]

  obj[method] = function () {
    var args = new Array(arguments.length)
    for (var i = 0; i < args.length; i++) args[i] = arguments[i]
    return fn.call(this, old, args)
  }
}

function around ( obj , method , fn ) { var old = obj [ method ] obj [ method ] = function ( ) { var args = new Array ( arguments . length ) for ( var i = 0 ; i < args . length ; i ++ ) args [ i ] = arguments [ i ] return fn . call ( this , old , args ) } }


function before (obj, method, fn) {
  var old = obj[method]

  obj[method] = function () {
    fn.call(this)
    old.apply(this, arguments)
  }
}

function before ( obj , method , fn ) { var old = obj [ method ] obj [ method ] = function ( ) { fn . call ( this ) old . apply ( this , arguments ) } }


function copyTemplate (from, to) {
  write(to, fs.readFileSync(path.join(TEMPLATE_DIR, from), 'utf-8'))
}

function copyTemplate ( from , to ) { write ( to , fs . readFileSync ( path . join ( TEMPLATE_DIR , from ) , 'utf-8' ) ) }


function copyTemplateMulti (fromDir, toDir, nameGlob) {
  fs.readdirSync(path.join(TEMPLATE_DIR, fromDir))
    .filter(minimatch.filter(nameGlob, { matchBase: true }))
    .forEach(function (name) {
      copyTemplate(path.join(fromDir, name), path.join(toDir, name))
    })
}

function copyTemplateMulti ( fromDir , toDir , nameGlob ) { fs . readdirSync ( path . join ( TEMPLATE_DIR , fromDir ) ) . filter ( minimatch . filter ( nameGlob , { matchBase : true } ) ) . forEach ( function ( name ) { copyTemplate ( path . join ( fromDir , name ) , path . join ( toDir , name ) ) } ) }

Copy multiple files from template directory.

Copy multiple files from template directory .


function createAppName (pathName) {
  return path.basename(pathName)
    .replace(/[^A-Za-z0-9.-]+/g, '-')
    .replace(/^[-_.]+|-+$/g, '')
    .toLowerCase()
}

function createAppName ( pathName ) { return path . basename ( pathName ) . replace ( / [^A-Za-z0-9.-]+ / g , '-' ) . replace ( / ^[-_.]+|-+$ / g , '' ) . toLowerCase ( ) }

Create an app name from a directory path, fitting npm naming requirements.

@param {String} pathName

Create an app name from a directory path fitting npm naming requirements .


function emptyDirectory (dir, fn) {
  fs.readdir(dir, function (err, files) {
    if (err && err.code !== 'ENOENT') throw err
    fn(!files || !files.length)
  })
}

function emptyDirectory ( dir , fn ) { fs . readdir ( dir , function ( err , files ) { if ( err && err . code !== 'ENOENT' ) throw err fn ( ! files || ! files . length ) } ) }

Check if the given directory `dir` is empty.

@param {String} dir
@param {Function} fn

Check if the given directory dir is empty .


function exit (code) {
  // flush output for Node.js Windows pipe bug
  // https://github.com/joyent/node/issues/6247 is just one bug example
  // https://github.com/visionmedia/mocha/issues/333 has a good discussion
  function done () {
    if (!(draining--)) _exit(code)
  }

  var draining = 0
  var streams = [process.stdout, process.stderr]

  exit.exited = true

  streams.forEach(function (stream) {
    // submit empty write request and wait for completion
    draining += 1
    stream.write('', done)
  })

  done()
}

function exit ( code ) { function done ( ) { if ( ! ( draining -- ) ) _exit ( code ) } var draining = 0 var streams = [ process . stdout , process . stderr ] exit . exited = true streams . forEach ( function ( stream ) { draining += 1 stream . write ( '' , done ) } ) done ( ) }


function loadTemplate (name) {
  var contents = fs.readFileSync(path.join(__dirname, '..', 'templates', (name + '.ejs')), 'utf-8')
  var locals = Object.create(null)

  function render () {
    return ejs.render(contents, locals, {
      escape: util.inspect
    })
  }

  return {
    locals: locals,
    render: render
  }
}

function loadTemplate ( name ) { var contents = fs . readFileSync ( path . join ( __dirname , '..' , 'templates' , ( name + '.ejs' ) ) , 'utf-8' ) var locals = Object . create ( null ) function render ( ) { return ejs . render ( contents , locals , { escape : util . inspect } ) } return { locals : locals , render : render } }


function main () {
  // Path
  var destinationPath = program.args.shift() || '.'

  // App name
  var appName = createAppName(path.resolve(destinationPath)) || 'hello-world'

  // View engine
  if (program.view === true) {
    if (program.ejs) program.view = 'ejs'
    if (program.hbs) program.view = 'hbs'
    if (program.hogan) program.view = 'hjs'
    if (program.pug) program.view = 'pug'
  }

  // Default view engine
  if (program.view === true) {
    warning('the default view engine will not be jade in future releases\n' +
      "use `--view=jade' or `--help' for additional options")
    program.view = 'jade'
  }

  // Generate application
  emptyDirectory(destinationPath, function (empty) {
    if (empty || program.force) {
      createApplication(appName, destinationPath)
    } else {
      confirm('destination is not empty, continue? [y/N] ', function (ok) {
        if (ok) {
          process.stdin.destroy()
          createApplication(appName, destinationPath)
        } else {
          console.error('aborting')
          exit(1)
        }
      })
    }
  })
}


function mkdir (base, dir) {
  var loc = path.join(base, dir)

  console.log('   \x1b[36mcreate\x1b[0m : ' + loc + path.sep)
  mkdirp.sync(loc, MODE_0755)
}

function
mkdir
(
base
,
dir
)
{
var
loc
=
path
.
join
(
base
,
dir
)
console
.
log
(
'   \x1b[36mcreate\x1b[0m : '
+
\x1b
+
\x1b
)
loc
}

Make the given dir relative to base.

@param {string} base
@param {string} dir


function renamedOption (originalName, newName) {
  return function (val) {
    warning(util.format("option `%s' has been renamed to `%s'", originalName, newName))
    return val
  }
}

function
renamedOption
(
originalName
,
newName
)
{
return
function
(
val
)
{
warning
(
util
.
format
(
"option `%s' has been renamed to `%s'"
,
originalName
,
newName
)
)
return
val
}
}

Generate a callback function for commander to warn about renamed option.

@param {String} originalName
@param {String} newName

Generate a callback function for commander to warn about renamed option .


function warning (message) {
  console.error()
  message.split('\n').forEach(function (line) {
    console.error('  warning: %s', line)
  })
  console.error()
}

function
warning
(
message
)
{
console
.
error
(
)
message
.
split
(
'\n'
)
.
\n
forEach
(
function
(
line
)
{
console
.
error
(
'  warning: %s'
,
line
)
}
)
}

Display a warning similar to how errors are displayed by commander.

@param {String} message

Display a warning similar to how errors are displayed by commander .


function write (file, str, mode) {
  fs.writeFileSync(file, str, { mode: mode || MODE_0666 })
  console.log('   \x1b[36mcreate\x1b[0m : ' + file)
}

function
write
(
file
,
str
,
mode
)
{
fs
.
writeFileSync
(
file
,
str
,
{
mode
:
mode
||
MODE_0666
}
)
console
.
log
(
'   \x1b[36mcreate\x1b[0m : '
+
\x1b
)
}

echo str > file.

@param {String} file
@param {String} str


function bind_d3(f, context) {
    return function() {
        var args = [this].concat([].slice.call(arguments)) // convert argument to array
        f.apply(context, args)
    }
}

function bind_d3 ( f , context ) { return function ( ) { var args = [ this ] . concat ( [ ] . slice . call ( arguments ) ) f . apply ( context , args ) } }

similar to _.bind, except it puts this as first argument to f, followed be other arguments, and make context f's this

similar to _ . bind except it puts this as first argument to f followed be other arguments and make context f s this


function adjustOptions(options) {
  const directory = process.cwd();
  const configPath = getWebpackConfigPath(directory, options.config);
  const haulOptions = getHaulConfig(configPath, logger);

  if (haulOptions.platforms) {
    const platformOption =
      command.options && command.options.find(_ => _.name === 'platform');
    if (platformOption) {
      platformOption.choices = [];
      for (const platformName in haulOptions.platforms) {
        if (
          Object.prototype.hasOwnProperty.call(
            haulOptions.platforms,
            platformName
          )
        ) {
          if (platformOption.choices) {
            platformOption.choices.push({
              value: platformName,
              description: `Builds ${haulOptions.platforms[
                platformName
              ]} bundle`,
            });
          }
        }
      }
    }
  }
}

function adjustOptions ( options ) { const directory = process . cwd ( ) ; const configPath = getWebpackConfigPath ( directory , options . config ) ; const haulOptions = getHaulConfig ( configPath , logger ) ; if ( haulOptions . platforms ) { const platformOption = command . options && command . options . find ( _ => _ . name === 'platform' ) ; if ( platformOption ) { platformOption . choices = [ ] ; for ( const platformName in haulOptions . platforms ) { if ( Object . prototype . hasOwnProperty . call ( haulOptions . platforms , platformName ) ) { if ( platformOption . choices ) { platformOption . choices . push ( { value : platformName , description : ` ${ haulOptions . platforms [ platformName ] } ` , } ) ; } } } } } }

Allow config file to override the list of availiable platforms


function devToolsMiddleware(debuggerProxy) {
  return (req, res, next) => {
    switch (req.cleanPath) {
      /**
       * Request for the debugger frontend
       */
      case '/debugger-ui/':
      case '/debugger-ui': {
        const readStream = fs.createReadStream(
          path.join(__dirname, '../assets/debugger.html')
        );
        res.writeHead(200, { 'Content-Type': 'text/html' });
        readStream.pipe(res);
        break;
      }

      /**
       * Request for the debugger worker
       */
      case '/debugger-ui/debuggerWorker.js':
      case '/debuggerWorker.js': {
        const readStream = fs.createReadStream(
          path.join(__dirname, '../assets/debuggerWorker.js')
        );
        res.writeHead(200, { 'Content-Type': 'application/javascript' });
        readStream.pipe(res);
        break;
      }

      /**
       * Request for (maybe) launching devtools
       */
      case '/launch-js-devtools': {
        if (!debuggerProxy.isDebuggerConnected()) {
          launchBrowser(`http://localhost:${req.socket.localPort}/debugger-ui`);
        }
        res.end('OK');
        break;
      }

      default:
        next();
    }
  };
}

function devToolsMiddleware ( debuggerProxy ) { return ( req , res , next ) => { switch ( req . cleanPath ) { case '/debugger-ui/' : case '/debugger-ui' : { const readStream = fs . createReadStream ( path . join ( __dirname , '../assets/debugger.html' ) ) ; res . writeHead ( 200 , { 'Content-Type' : 'text/html' } ) ; readStream . pipe ( res ) ; break ; } case '/debugger-ui/debuggerWorker.js' : case '/debuggerWorker.js' : { const readStream = fs . createReadStream ( path . join ( __dirname , '../assets/debuggerWorker.js' ) ) ; res . writeHead ( 200 , { 'Content-Type' : 'application/javascript' } ) ; readStream . pipe ( res ) ; break ; } case '/launch-js-devtools' : { if ( ! debuggerProxy . isDebuggerConnected ( ) ) { launchBrowser ( ` ${ req . socket . localPort } ` ) ; } res . end ( 'OK' ) ; break ; } default : next ( ) ; } } ; }

Devtools middleware compatible with default React Native implementation


function onLoad(event) {

	// Prepare the render pass.
	event.demo.renderPass.camera = event.demo.camera;

	document.getElementById("viewport").children[0].style.display = "none";

}

function onLoad ( event ) { event . demo . renderPass . camera = event . demo . camera ; document . getElementById ( "viewport" ) . children [ 0 ] . style . display = "none" ; }

Handles demo load events.

@private
@param {Event} event - An event.


function prefixSubstrings(prefix, substrings, strings) {

	let prefixed, regExp;

	for(const substring of substrings) {

		prefixed = "$1" + prefix + substring.charAt(0).toUpperCase() + substring.slice(1);
		regExp = new RegExp("([^\\.])(\\b" + substring + "\\b)", "g");

		for(const entry of strings.entries()) {

			if(entry[1] !== null) {

				strings.set(entry[0], entry[1].replace(regExp, prefixed));

			}

		}

	}

}

function prefixSubstrings ( prefix , substrings , strings ) { let prefixed , regExp ; for ( const substring of substrings ) { prefixed = "$1" + prefix + substring . charAt ( 0 ) . toUpperCase ( ) + substring . slice ( 1 ) ; regExp = new RegExp ( "([^\\.])(\\b" + \\ + \\ , substring ) ; "\\b)" } }

Prefixes substrings within the given strings.

@private
@param {String} prefix - A prefix.
@param {String[]} substrings - The substrings.
@param {Map<String, String>} strings - A collection of named strings.

Prefixes substrings within the given strings .


function createCanvas(width, height, data, channels) {

	const canvas = document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
	const context = canvas.getContext("2d");

	const imageData = context.createImageData(width, height);
	const target = imageData.data;

	let x, y;
	let i, j;

	for(y = 0; y < height; ++y) {

		for(x = 0; x < width; ++x) {

			i = (y * width + x) * 4;
			j = (y * width + x) * channels;

			target[i] = (channels > 0) ? data[j] : 0;
			target[i + 1] = (channels > 1) ? data[j + 1] : 0;
			target[i + 2] = (channels > 2) ? data[j + 2] : 0;
			target[i + 3] = (channels > 3) ? data[j + 3] : 255;

		}

	}

	canvas.width = width;
	canvas.height = height;

	context.putImageData(imageData, 0, 0);

	return canvas;

}

function createCanvas ( width , height , data , channels ) { const canvas = document . createElementNS ( "http://www.w3.org/1999/xhtml" , "canvas" ) ; const context = canvas . getContext ( "2d" ) ; const imageData = context . createImageData ( width , height ) ; const target = imageData . data ; let x , y ; let i , j ; for ( y = 0 ; y < height ; ++ y ) { for ( x = 0 ; x < width ; ++ x ) { i = ( y * width + x ) * 4 ; j = ( y * width + x ) * channels ; target [ i ] = ( channels > 0 ) ? data [ j ] : 0 ; target [ i + 1 ] = ( channels > 1 ) ? data [ j + 1 ] : 0 ; target [ i + 2 ] = ( channels > 2 ) ? data [ j + 2 ] : 0 ; target [ i + 3 ] = ( channels > 3 ) ? data [ j + 3 ] : 255 ; } } canvas . width = width ; canvas . height = height ; context . putImageData ( imageData , 0 , 0 ) ; return canvas ; }

Creates a new canvas from raw image data.

@private
@param {Number} width - The image width.
@param {Number} height - The image height.
@param {Uint8ClampedArray} data - The image data.
@param {Number} channels - The color channels used for a single pixel.
@return {Canvas} The canvas.

Creates a new canvas from raw image data .


function smoothArea(d, b) {

	const a1 = b.min;
	const a2 = b.max;

	const b1X = Math.sqrt(a1.x * 2.0) * 0.5;
	const b1Y = Math.sqrt(a1.y * 2.0) * 0.5;
	const b2X = Math.sqrt(a2.x * 2.0) * 0.5;
	const b2Y = Math.sqrt(a2.y * 2.0) * 0.5;

	const p = saturate(d / SMOOTH_MAX_DISTANCE);

	a1.set(lerp(b1X, a1.x, p), lerp(b1Y, a1.y, p));
	a2.set(lerp(b2X, a2.x, p), lerp(b2Y, a2.y, p));

	return b;

}

function smoothArea ( d , b ) { const a1 = b . min ; const a2 = b . max ; const b1X = Math . sqrt ( a1 . x * 2.0 ) * 0.5 ; const b1Y = Math . sqrt ( a1 . y * 2.0 ) * 0.5 ; const b2X = Math . sqrt ( a2 . x * 2.0 ) * 0.5 ; const b2Y = Math . sqrt ( a2 . y * 2.0 ) * 0.5 ; const p = saturate ( d / SMOOTH_MAX_DISTANCE ) ; a1 . set ( lerp ( b1X , a1 . x , p ) , lerp ( b1Y , a1 . y , p ) ) ; a2 . set ( lerp ( b2X , a2 . x , p ) , lerp ( b2Y , a2 . y , p ) ) ; return b ; }

A smoothing function for small U-patterns.

@private
@param {Number} d - A smoothing factor.
@param {Box2} b - The area that should be smoothed.
@return {Box2} The smoothed area.

A smoothing function for small U - patterns .


function calculateDiagonalAreaForPixel(p1, p2, pX, pY) {

	let a;
	let x, y;
	let offsetX, offsetY;

	for(a = 0, y = 0; y < DIAGONAL_SAMPLES; ++y) {

		for(x = 0; x < DIAGONAL_SAMPLES; ++x) {

			offsetX = x / (DIAGONAL_SAMPLES - 1.0);
			offsetY = y / (DIAGONAL_SAMPLES - 1.0);

			if(isInsideArea(p1, p2, pX + offsetX, pY + offsetY)) {

				++a;

			}

		}

	}

	return a / (DIAGONAL_SAMPLES * DIAGONAL_SAMPLES);

}

function calculateDiagonalAreaForPixel ( p1 , p2 , pX , pY ) { let a ; let x , y ; let offsetX , offsetY ; for ( a = 0 , y = 0 ; y < DIAGONAL_SAMPLES ; ++ y ) { for ( x = 0 ; x < DIAGONAL_SAMPLES ; ++ x ) { offsetX = x / ( DIAGONAL_SAMPLES - 1.0 ) ; offsetY = y / ( DIAGONAL_SAMPLES - 1.0 ) ; if ( isInsideArea ( p1 , p2 , pX + offsetX , pY + offsetY ) ) { ++ a ; } } } return a / ( DIAGONAL_SAMPLES * DIAGONAL_SAMPLES ) ; }

Calculates the area under the line p1 -> p2 for the pixel p using brute force
sampling.

@private
@param {Vector2} p1 - The lower bounds of the area.
@param {Vector2} p2 - The upper bounds of the area.
@param {Number} pX - The X-coordinates.
@param {Number} pY - The Y-coordinates.
@return {Number} The amount of pixels inside the area relative to the total amount of sampled pixels.

Calculates the area under the line p1 - > p2 for the pixel p using brute force sampling .


function calculateDiagonalArea(pattern, p1, p2, left, offset, result) {

	const e = diagonalEdges[pattern];
	const e1 = e[0];
	const e2 = e[1];

	if(e1 > 0) {

		p1.x += offset[0];
		p1.y += offset[1];

	}

	if(e2 > 0) {

		p2.x += offset[0];
		p2.y += offset[1];

	}

	return result.set(
		1.0 - calculateDiagonalAreaForPixel(p1, p2, 1.0 + left, 0.0 + left),
		calculateDiagonalAreaForPixel(p1, p2, 1.0 + left, 1.0 + left)
	);

}

function calculateDiagonalArea ( pattern , p1 , p2 , left , offset , result ) { const e = diagonalEdges [ pattern ] ; const e1 = e [ 0 ] ; const e2 = e [ 1 ] ; if ( e1 > 0 ) { p1 . x += offset [ 0 ] ; p1 . y += offset [ 1 ] ; } if ( e2 > 0 ) { p2 . x += offset [ 0 ] ; p2 . y += offset [ 1 ] ; } return result . set ( 1.0 - calculateDiagonalAreaForPixel ( p1 , p2 , 1.0 + left , 0.0 + left ) , calculateDiagonalAreaForPixel ( p1 , p2 , 1.0 + left , 1.0 + left ) ) ; }

Calculates the area under the line p1 -> p2. This includes the pixel and its
opposite.

@private
@param {Number} pattern - A pattern index.
@param {Vector2} p1 - The lower bounds of the area.
@param {Vector2} p2 - The upper bounds of the area.
@param {Number} left - The left distance.
@param {Float32Array} offset - An offset.
@param {Vector2} result - A target vector to store the area in.
@return {Vector2} The area.

Calculates the area under the line p1 - > p2 . This includes the pixel and its opposite .


function generatePatterns(patterns, offset, orthogonal) {

	const result = new Vector2();

	let i, l;
	let x, y;
	let c;

	let pattern;
	let data, size;

	for(i = 0, l = patterns.length; i < l; ++i) {

		pattern = patterns[i];

		data = pattern.data;
		size = pattern.width;

		for(y = 0; y < size; ++y) {

			for(x = 0; x < size; ++x) {

				if(orthogonal) {

					calculateOrthogonalAreaForPattern(i, x, y, offset, result);

				} else {

					calculateDiagonalAreaForPattern(i, x, y, offset, result);

				}

				c = (y * size + x) * 2;

				data[c] = result.x * 255;
				data[c + 1] = result.y * 255;

			}

		}

	}

}

function generatePatterns ( patterns , offset , orthogonal ) { const result = new Vector2 ( ) ; let i , l ; let x , y ; let c ; let pattern ; let data , size ; for ( i = 0 , l = patterns . length ; i < l ; ++ i ) { pattern = patterns [ i ] ; data = pattern . data ; size = pattern . width ; for ( y = 0 ; y < size ; ++ y ) { for ( x = 0 ; x < size ; ++ x ) { if ( orthogonal ) { calculateOrthogonalAreaForPattern ( i , x , y , offset , result ) ; } else { calculateDiagonalAreaForPattern ( i , x , y , offset , result ) ; } c = ( y * size + x ) * 2 ; data [ c ] = result . x * 255 ; data [ c + 1 ] = result . y * 255 ; } } } }

Calculates orthogonal or diagonal patterns for a given offset.

@param {RawImageData[]} patterns - The patterns to assemble.
@param {Number|Float32Array} offset - A pattern offset. Diagonal offsets are pairs.
@param {Boolean} orthogonal - Whether the patterns are orthogonal or diagonal.

Calculates orthogonal or diagonal patterns for a given offset .


function assemble(base, patterns, edges, size, orthogonal, target) {

	const p = new Vector2();

	const dstData = target.data;
	const dstWidth = target.width;

	let i, l;
	let x, y;
	let c, d;

	let edge;
	let pattern;
	let srcData, srcWidth;

	for(i = 0, l = patterns.length; i < l; ++i) {

		edge = edges[i];
		pattern = patterns[i];

		srcData = pattern.data;
		srcWidth = pattern.width;

		for(y = 0; y < size; ++y) {

			for(x = 0; x < size; ++x) {

				p.fromArray(edge).multiplyScalar(size);
				p.add(base);
				p.x += x;
				p.y += y;

				c = (p.y * dstWidth + p.x) * 2;

				/* The texture coordinates of orthogonal patterns are compressed
				quadratically to reach longer distances for a given texture size. */
				d = orthogonal ? ((y * y * srcWidth + x * x) * 2) :
					((y * srcWidth + x) * 2);

				dstData[c] = srcData[d];
				dstData[c + 1] = srcData[d + 1];

			}

		}

	}

}

function assemble ( base , patterns , edges , size , orthogonal , target ) { const p = new Vector2 ( ) ; const dstData = target . data ; const dstWidth = target . width ; let i , l ; let x , y ; let c , d ; let edge ; let pattern ; let srcData , srcWidth ; for ( i = 0 , l = patterns . length ; i < l ; ++ i ) { edge = edges [ i ] ; pattern = patterns [ i ] ; srcData = pattern . data ; srcWidth = pattern . width ; for ( y = 0 ; y < size ; ++ y ) { for ( x = 0 ; x < size ; ++ x ) { p . fromArray ( edge ) . multiplyScalar ( size ) ; p . add ( base ) ; p . x += x ; p . y += y ; c = ( p . y * dstWidth + p . x ) * 2 ; d = orthogonal ? ( ( y * y * srcWidth + x * x ) * 2 ) : ( ( y * srcWidth + x ) * 2 ) ; dstData [ c ] = srcData [ d ] ; dstData [ c + 1 ] = srcData [ d + 1 ] ; } } } }

Assembles orthogonal or diagonal patterns into the final area image.

@param {Vector2} base - A base position.
@param {RawImageData[]} patterns - The patterns to assemble.
@param {Uint8Array[]} edges - Edge coordinate pairs, used for positioning.
@param {Number} size - The pattern size.
@param {Boolean} orthogonal - Whether the patterns are orthogonal or diagonal.
@param {RawImageData} target - The target image data.

Assembles orthogonal or diagonal patterns into the final area image .


function deltaRight(left, top) {

	let d = 0;

	// If there is an edge, and no crossing edges, continue.
	if(top[3] === 1 && left[1] !== 1 && left[3] !== 1) {

		d += 1;

	}

	/* If an edge was previously found, there is another edge and there are no
	crossing edges, continue. */
	if(d === 1 && top[2] === 1 && left[0] !== 1 && left[2] !== 1) {

		d += 1;

	}

	return d;

}

Computes the delta distance to add in the last step of searches to the right.

@private
@param {Number[]} left - The left edge combination.
@param {Number[]} top - The top edge combination.
@return {Number} The right delta distance.

Computes the delta distance to add in the last step of searches to the right .


Calculates the bilinear fetch for a certain edge combination.

e[0]       e[1]

x <-------- Sample Position: (-0.25, -0.125)
e[2]       e[3] <--- Current Pixel [3]: (0.0, 0.0)

@private
@param {Number[]} e - The edge combination.
@return {Number} The interpolated value.

Calculates the bilinear fetch for a certain edge combination .


function checkForm(that) {
    var newValue = $(that).val()
    var matches = newValue != '' ? newValue.match(timeRegEx) : ''
    var error = $(that)
      .closest('.time-spinner')
      .find('.error_container')
    var $closerTimeSpinner = $(that)
      .closest('.time-spinner')
      .find('.spinner-control')

    if (matches) {
      $(error).html('')
      //$closerTimeSpinner.find('.spinner-hour input').val(timeRegEx.split(':')[0]);
      //$closerTimeSpinner.find('.spinner-min input').val(timeRegEx.split(':')[1]);
      return true
    } else {
      var errMsg = 'Formato data non valido'
      $(error).html(errMsg)
      //$(that).val('Formato data non valido')
      return false
    }
  }

function
checkForm
(
that
)
{
var
newValue
=
$
(
that
)
.
val
(
)
var
matches
=
newValue
!=
''
newValue
.
match
(
timeRegEx
)
:
''
var
error
=
$
(
that
)
.
closest
(
'.time-spinner'
)
.
find
(
'.error_container'
)
var
$closerTimeSpinner
=
$
(
that
)
.
closest
(
'.time-spinner'
)
.
find
(
'.spinner-control'
)
if
(
matches
)
{
$
(
error
)
.
html
(
''
)
return
true
}
else
{
var
errMsg
=
'Formato data non valido'
$
(
error
)
.
html
(
errMsg
)
return
false
}
}


function resetToMove(contextControl) {
    var left = contextControl.find('.source .transfer-group')
    var right = contextControl.find('.target .transfer-group')
    var textLeft = contextControl.find('.source .transfer-header span.num')
    var textRight = contextControl.find('.target .transfer-header span.num')
    var header = contextControl.find('.transfer-header input')

    $(left).html(elemLeft)
    $(right).html(elemRight)

    $(textLeft).text(elemLeftNum)
    $(textRight).text(elemRightNum)

    $(header).prop('disabled', false)
  }

function
resetToMove
(
contextControl
)
{
var
left
=
contextControl
.
find
(
'.source .transfer-group'
)
var
right
=
contextControl
.
find
(
'.target .transfer-group'
)
var
textLeft
=
contextControl
.
find
(
'.source .transfer-header span.num'
)
var
textRight
=
contextControl
.
find
(
'.target .transfer-header span.num'
)
var
header
=
contextControl
.
find
(
'.transfer-header input'
)
$
(
left
)
.
html
(
elemLeft
)
$
(
right
)
.
html
(
elemRight
)
$
(
textLeft
)
.
text
(
elemLeftNum
)
$
(
textRight
)
.
text
(
elemRightNum
)
$
(
header
)
.
prop
(
'disabled'
,
false
)
}


function checkIfActive(
    targetControl,
    targetHeaderControl,
    containerTypeControl,
    addButtonControl
  ) {
    $(targetControl).each(function(el) {
      if ($(this).prop('checked')) {
        if (!$(targetHeaderControl).hasClass('semi-checked')) {
          $(targetHeaderControl).addClass('semi-checked')
          $(targetHeaderControl).prop('checked', false)
          if (containerTypeControl.hasClass('source')) {
            $(addButtonControl).addClass('active')
          }
          if (containerTypeControl.hasClass('target')) {
            $(inverseButton).addClass('active')
          }
        }
        return false
      } else {
        $(targetHeaderControl).removeClass('semi-checked')
        if (containerTypeControl.hasClass('source')) {
          $(addButtonControl).removeClass('active')
        }
        if (containerTypeControl.hasClass('target')) {
          $(inverseButton).removeClass('active')
        }
      }
    })
  }

function checkIfActive ( targetControl , targetHeaderControl , containerTypeControl , addButtonControl ) { $ ( targetControl ) . each ( function ( el ) { if ( $ ( this ) . prop ( 'checked' ) ) { if ( ! $ ( targetHeaderControl ) . hasClass ( 'semi-checked' ) ) { $ ( targetHeaderControl ) . addClass ( 'semi-checked' ) $ ( targetHeaderControl ) . prop ( 'checked' , false ) if ( containerTypeControl . hasClass ( 'source' ) ) { $ ( addButtonControl ) . addClass ( 'active' ) } if ( containerTypeControl . hasClass ( 'target' ) ) { $ ( inverseButton ) . addClass ( 'active' ) } } return false } else { $ ( targetHeaderControl ) . removeClass ( 'semi-checked' ) if ( containerTypeControl . hasClass ( 'source' ) ) { $ ( addButtonControl ) . removeClass ( 'active' ) } if ( containerTypeControl . hasClass ( 'target' ) ) { $ ( inverseButton ) . removeClass ( 'active' ) } } } ) }


function sourceControl(contextControl) {
    var tocheck = contextControl.find('.transfer-scroll').find('input')
    var checknum = tocheck.length
    var targetText = contextControl
      .find('.transfer-header')
      .find('label span.num')
    var header = contextControl.find('.transfer-header input')

    $(header)
      .prop('checked', false)
      .removeClass('semi-checked')

    if (checknum < 1) {
      $(header).prop('disabled', true)
    } else {
      $(header).prop('disabled', false)
    }

    $(targetText).text(checknum)
  }

function
sourceControl
(
contextControl
)
{
var
tocheck
=
contextControl
.
find
(
'.transfer-scroll'
)
.
find
(
'input'
)
var
checknum
=
tocheck
.
length
var
targetText
=
contextControl
.
find
(
'.transfer-header'
)
.
find
(
'label span.num'
)
var
header
=
contextControl
.
find
(
'.transfer-header input'
)
$
(
header
)
.
prop
(
'checked'
,
false
)
.
removeClass
(
'semi-checked'
)
if
(
checknum
<
1
)
{
$
(
header
)
.
prop
(
'disabled'
,
true
)
}
else
{
$
(
header
)
.
prop
(
'disabled'
,
false
)
}
$
(
targetText
)
.
text
(
checknum
)
}


function targetControl(targetControl) {
    var tocheck = targetControl.find('input')
    var checknum = tocheck.length
    var targetText = tocheck
      .closest('.it-transfer-wrapper')
      .find('.transfer-header')
      .find('label span.num')
    var header = $(targetControl).find('.transfer-header input')

    if (checknum < 1) {
      $(header).prop('disabled', true)
    } else {
      $(header).prop('disabled', false)
    }

    $(targetText).text(checknum)
  }

function
targetControl
(
targetControl
)
{
var
tocheck
=
targetControl
.
find
(
'input'
)
var
checknum
=
tocheck
.
length
var
targetText
=
tocheck
.
closest
(
'.it-transfer-wrapper'
)
.
find
(
'.transfer-header'
)
.
find
(
'label span.num'
)
var
header
=
$
(
targetControl
)
.
find
(
'.transfer-header input'
)
if
(
checknum
<
1
)
{
$
(
header
)
.
prop
(
'disabled'
,
true
)
}
else
{
$
(
header
)
.
prop
(
'disabled'
,
false
)
}
$
(
targetText
)
.
text
(
checknum
)
}


function checkToMove(contextControl, targetControl) {
    var elements = contextControl.find('.transfer-group').find('input:checked')
    var sourceTag = $(elements).closest('.form-check')

    $(elements).each(function() {
      $(this).prop('checked', false)
      $(sourceTag)
        .detach()
        .appendTo(targetControl)
        .addClass('added')
    })
  }

function checkToMove ( contextControl , targetControl ) { var elements = contextControl . find ( '.transfer-group' ) . find ( 'input:checked' ) var sourceTag = $ ( elements ) . closest ( '.form-check' ) $ ( elements ) . each ( function ( ) { $ ( this ) . prop ( 'checked' , false ) $ ( sourceTag ) . detach ( ) . appendTo ( targetControl ) . addClass ( 'added' ) } ) }


function updateScrollPos() {
    if (!stickies.length) {
      return
    }

    lastKnownScrollTop =
      document.documentElement.scrollTop || document.body.scrollTop

    // Only trigger a layout change if we’re not already waiting for one
    if (!isAnimationRequested) {
      isAnimationRequested = true

      // Don’t update until next animation frame if we can, otherwise use a
      // timeout - either will help avoid too many repaints
      if (requestAnimationFrame) {
        requestAnimationFrame(setPositions)
      } else {
        if (timeout) {
          clearTimeout(timeout)
        }

        timeout = setTimeout(setPositions, 15)
      }
    }
  }

function updateScrollPos ( ) { if ( ! stickies . length ) { return } lastKnownScrollTop = document . documentElement . scrollTop || document . body . scrollTop if ( ! isAnimationRequested ) { isAnimationRequested = true if ( requestAnimationFrame ) { requestAnimationFrame ( setPositions ) } else { if ( timeout ) { clearTimeout ( timeout ) } timeout = setTimeout ( setPositions , 15 ) } } }


function scoreText(score) {
      if (score === -1) {
        return options.shortPass
      }

      score = score < 0 ? 0 : score

      if (score < 26) {
        return options.shortPass
      }
      if (score < 51) {
        return options.badPass
      }
      if (score < 76) {
        return options.goodPass
      }

      return options.strongPass
    }

function scoreText ( score ) { if ( score === - 1 ) { return options . shortPass } score = score < 0 ? 0 : score if ( score < 26 ) { return options . shortPass } if ( score < 51 ) { return options . badPass } if ( score < 76 ) { return options . goodPass } return options . strongPass }

Returns strings based on the score given.

@param int score Score base.
@return string

Returns strings based on the score given .


function calculateScore(password) {
      var score = 0

      // password < options.minimumLength
      if (password.length < options.minimumLength) {
        return -1
      }

      // password length
      score += password.length * 4
      score += checkRepetition(1, password).length - password.length
      score += checkRepetition(2, password).length - password.length
      score += checkRepetition(3, password).length - password.length
      score += checkRepetition(4, password).length - password.length

      // password has 3 numbers
      if (password.match(/(.*[0-9].*[0-9].*[0-9])/)) {
        score += 5
      }

      // password has at least 2 sybols
      var symbols = '.*[!,@,#,$,%,^,&,*,?,_,~]'
      symbols = new RegExp('(' + symbols + symbols + ')')
      if (password.match(symbols)) {
        score += 5
      }

      // password has Upper and Lower chars
      if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {
        score += 10
      }

      // password has number and chars
      if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) {
        score += 15
      }

      // password has number and symbol
      if (
        password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) &&
        password.match(/([0-9])/)
      ) {
        score += 15
      }

      // password has char and symbol
      if (
        password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) &&
        password.match(/([a-zA-Z])/)
      ) {
        score += 15
      }

      // password is just numbers or chars
      if (password.match(/^\w+$/) || password.match(/^\d+$/)) {
        score -= 10
      }

      if (score > 100) {
        score = 100
      }

      if (score < 0) {
        score = 0
      }

      return score
    }

function calculateScore ( password ) { var score = 0 if ( password . length < options . minimumLength ) { return - 1 } score += password . length * 4 score += checkRepetition ( 1 , password ) . length - password . length score += checkRepetition ( 2 , password ) . length - password . length score += checkRepetition ( 3 , password ) . length - password . length score += checkRepetition ( 4 , password ) . length - password . length if ( password . match ( / (.*[0-9].*[0-9].*[0-9]) / ) ) { score += 5 } var symbols = '.*[!,@,#,$,%,^,&,*,?,_,~]' symbols = new RegExp ( '(' + symbols + symbols + ')' ) if ( password . match ( symbols ) ) { score += 5 } if ( password . match ( / ([a-z].*[A-Z])|([A-Z].*[a-z]) / ) ) { score += 10 } if ( password . match ( / ([a-zA-Z]) / ) && password . match ( / ([0-9]) / ) ) { score += 15 } if ( password . match ( / ([!,@,#,$,%,^,&,*,?,_,~]) / ) && password . match ( / ([0-9]) / ) ) { score += 15 } if ( password . match ( / ([!,@,#,$,%,^,&,*,?,_,~]) / ) && password . match ( / ([a-zA-Z]) / ) ) { score += 15 } if ( password . match ( / ^\w+$ / ) || password . match ( / ^\d+$ / ) ) { score -= 10 } if ( score > 100 ) { score = 100 } if ( score < 0 ) { score = 0 } return score }

Returns a value between -1 and 100 to score
the user's password.

@param  string password The password to be checked.
@return int

Returns a value between - 1 and 100 to score the user s password .


function checkRepetition(rLen, str) {
      var res = '',
        repeated = false
      for (var i = 0; i < str.length; i++) {
        repeated = true
        for (var j = 0; j < rLen && j + i + rLen < str.length; j++) {
          repeated = repeated && str.charAt(j + i) === str.charAt(j + i + rLen)
        }
        if (j < rLen) {
          repeated = false
        }
        if (repeated) {
          i += rLen - 1
          repeated = false
        } else {
          res += str.charAt(i)
        }
      }
      return res
    }

function checkRepetition ( rLen , str ) { var res = '' , repeated = false for ( var i = 0 ; i < str . length ; i ++ ) { repeated = true for ( var j = 0 ; j < rLen && j + i + rLen < str . length ; j ++ ) { repeated = repeated && str . charAt ( j + i ) === str . charAt ( j + i + rLen ) } if ( j < rLen ) { repeated = false } if ( repeated ) { i += rLen - 1 repeated = false } else { res += str . charAt ( i ) } } return res }

Checks for repetition of characters in
a string

@param int rLen Repetition length.
@param string str The string to be checked.
@return string


function init() {
      var shown = true
      var $text = options.showText

      var $graybar = $('
').addClass(
        'password-meter progress rounded-0 position-absolute'
      )
      $graybar.append(`

`)
      var $colorbar = $('
').attr({
        class: 'progress-bar',
        role: 'progressbar',
        'aria-valuenow': '0',
        'aria-valuemin': '0',
        'aria-valuemax': '100',
      })
      var $insert = $('
').append($graybar.append($colorbar))

      if (options.showText) {
        $text = $('')
          .addClass('form-text text-muted')
          .html(options.enterPass)
        $insert.prepend($text)
      }

      $object.after($insert)

      $object.keyup(function() {
        var score = calculateScore($object.val())
        $object.trigger('password.score', [score])
        var perc = score < 0 ? 0 : score
        $colorbar.removeClass(function(index, className) {
          return (className.match(/(^|\s)bg-\S+/g) || []).join(' ')
        })
        $colorbar.addClass('bg-' + scoreColor(score))
        $colorbar.css({
          width: perc + '%',
        })
        $colorbar.attr('aria-valuenow', perc)

        if (options.showText) {
          var text = scoreText(score)
          if (!$object.val().length && score <= 0) {
            text = options.enterPass
          }

          if (
            $text.html() !==
            $('
')
              .html(text)
              .html()
          ) {
            $text.html(text)
            $text.removeClass(function(index, className) {
              return (className.match(/(^|\s)text-\S+/g) || []).join(' ')
            })
            $text.addClass('text-' + scoreColor(score))
            $object.trigger('password.text', [text, score])
          }
        }
      })

      return this
    }

Initializes the plugin creating and binding the
required layers and events.

@return void

Initializes the plugin creating and binding the required layers and events .


function LevelUpArrayAdapter(name, db, serializer) {
  this.db = Sublevel(db);
  this.db = this.db.sublevel(name);
  this.name = name;
  this.serializer = serializer || {
    encode: function(val, callback) {
      callback(null, val);
    },
    decode: function(val, callback) {
      callback(null, val);
    }
  };
}

function LevelUpArrayAdapter ( name , db , serializer ) { this . db = Sublevel ( db ) ; this . db = this . db . sublevel ( name ) ; this . name = name ; this . serializer = serializer || { encode : function ( val , callback ) { callback ( null , val ) ; } , decode : function ( val , callback ) { callback ( null , val ) ; } } ; }

Level up adapter that looks like an array. Doesn't support inserts.

Level up adapter that looks like an array . Doesn t support inserts .


function fixProps(tx, data) {
  // ethereumjs-tx doesn't allow for a `0` value in fields, but we want it to
  // in order to differentiate between a value that isn't set and a value
  // that is set to 0 in a fake transaction.
  // Once https://github.com/ethereumjs/ethereumjs-tx/issues/112 is figured
  // out we can probably remove this fix/hack.
  // We keep track of the original value and return that value when
  // referenced by its property name. This lets us properly encode a `0` as
  // an empty buffer while still being able to differentiate between a `0`
  // and `null`/`undefined`.
  tx._originals = [];
  const fieldNames = ["nonce", "gasPrice", "gasLimit", "value"];
  fieldNames.forEach((fieldName) => configZeroableField(tx, fieldName, 32));

  // Ethereumjs-tx doesn't set the _chainId value whenever the v value is set,
  // which causes transaction signing to fail on transactions that include a
  // chain id in the v value (like ethers.js does).
  // Whenever the v value changes we need to make sure the chainId is also set.
  const vDescriptors = Object.getOwnPropertyDescriptor(tx, "v");
  // eslint-disable-next-line accessor-pairs
  Object.defineProperty(tx, "v", {
    set: (v) => {
      vDescriptors.set.call(tx, v);
      // calculate chainId from signature
      const sigV = ethUtil.bufferToInt(tx.v);
      let chainId = Math.floor((sigV - 35) / 2);
      if (chainId < 0) {
        chainId = 0;
      }
      tx._chainId = chainId || 0;
    }
  });

  if (tx.isFake()) {
    /**
     * @prop {Buffer} from (read/write) Set from address to bypass transaction
     * signing on fake transactions.
     */
    Object.defineProperty(tx, "from", {
      enumerable: true,
      configurable: true,
      get: tx.getSenderAddress.bind(tx),
      set: (val) => {
        if (val) {
          tx._from = ethUtil.toBuffer(val);
        } else {
          tx._from = null;
        }
      }
    });

    if (data && data.from) {
      tx.from = data.from;
    }

    tx.hash = fakeHash;
  }
}

function fixProps ( tx , data ) { tx . _originals = [ ] ; const fieldNames = [ "nonce" , "gasPrice" , "gasLimit" , "value" ] ; fieldNames . forEach ( ( fieldName ) => configZeroableField ( tx , fieldName , 32 ) ) ; const vDescriptors = Object . getOwnPropertyDescriptor ( tx , "v" ) ; Object . defineProperty ( tx , "v" , { set : ( v ) => { vDescriptors . set . call ( tx , v ) ; const sigV = ethUtil . bufferToInt ( tx . v ) ; let chainId = Math . floor ( ( sigV - 35 ) / 2 ) ; if ( chainId < 0 ) { chainId = 0 ; } tx . _chainId = chainId || 0 ; } } ) ; if ( tx . isFake ( ) ) { Object . defineProperty ( tx , "from" , { enumerable : true , configurable : true , get : tx . getSenderAddress . bind ( tx ) , set : ( val ) => { if ( val ) { tx . _from = ethUtil . toBuffer ( val ) ; } else { tx . _from = null ; } } } ) ; if ( data && data . from ) { tx . from = data . from ; } tx . hash = fakeHash ; } }

etheruemjs-tx's Transactions don't behave quite like we need them to, so
we're monkey-patching them to do what we want here.
@param {Transaction} tx The Transaction to fix
@param {Object} [data] The data object

etheruemjs - tx s Transactions don t behave quite like we need them to so we re monkey - patching them to do what we want here .


function initData(tx, data) {
  if (data) {
    if (typeof data === "string") {
      data = to.buffer(data);
    }
    if (Buffer.isBuffer(data)) {
      data = rlp.decode(data);
    }
    const self = tx;
    if (Array.isArray(data)) {
      if (data.length > tx._fields.length) {
        throw new Error("wrong number of fields in data");
      }

      // make sure all the items are buffers
      data.forEach((d, i) => {
        self[self._fields[i]] = ethUtil.toBuffer(d);
      });
    } else if ((typeof data === "undefined" ? "undefined" : typeof data) === "object") {
      const keys = Object.keys(data);
      tx._fields.forEach(function(field) {
        if (keys.indexOf(field) !== -1) {
          self[field] = data[field];
        }
        if (field === "gasLimit") {
          if (keys.indexOf("gas") !== -1) {
            self["gas"] = data["gas"];
          }
        } else if (field === "data") {
          if (keys.indexOf("input") !== -1) {
            self["input"] = data["input"];
          }
        }
      });

      // Set chainId value from the data, if it's there and the data didn't
      // contain a `v` value with chainId in it already. If we do have a
      // data.chainId value let's set the interval v value to it.
      if (!tx._chainId && data && data.chainId != null) {
        tx.raw[self._fields.indexOf("v")] = tx._chainId = data.chainId || 0;
      }
    } else {
      throw new Error("invalid data");
    }
  }
}

function
initData
(
tx
,
data
)
{
if
(
data
)
{
if
(
typeof
data
===
"string"
)
{
data
=
to
.
buffer
(
data
)
;
}
if
(
Buffer
.
isBuffer
(
data
)
)
{
data
=
rlp
.
decode
(
data
)
;
}
const
self
=
tx
;
if
(
Array
.
isArray
(
data
)
)
{
if
(
data
.
length
>
tx
.
_fields
.
length
)
{
throw
new
Error
(
"wrong number of fields in data"
)
;
}
data
.
forEach
(
(
d
,
i
)
=>
{
self
[
self
.
_fields
[
i
]
]
=
ethUtil
.
toBuffer
(
d
)
;
}
)
;
}
else
if
(
(
typeof
data
===
"undefined"
"undefined"
:
typeof
data
)
===
"object"
)
{
const
keys
=
Object
.
keys
(
data
)
;
tx
.
_fields
.
forEach
(
function
(
field
)
{
if
(
keys
.
indexOf
(
field
)
!==
1
)
{
self
[
field
]
=
data
[
field
]
;
}
if
(
field
===
"gasLimit"
)
{
if
(
keys
.
indexOf
(
"gas"
)
!==
1
)
{
self
[
"gas"
]
=
data
[
"gas"
]
;
}
}
else
if
(
field
===
"data"
)
{
if
(
keys
.
indexOf
(
"input"
)
!==
1
)
{
self
[
"input"
]
=
data
[
"input"
]
;
}
}
}
)
;
if
(
!
tx
.
_chainId
&&
data
&&
data
.
chainId
!=
)
{
tx
.
raw
[
self
.
_fields
.
indexOf
(
"v"
)
]
=
tx
.
_chainId
=
data
.
chainId
||
0
;
}
}
else
{
throw
new
Error
(
"invalid data"
)
;
}
}
}

Parses the given data object and adds its properties to the given tx.
@param {Transaction} tx
@param {Object} [data]

Parses the given data object and adds its properties to the given tx .


function TXRejectedError(message) {
  // Why not just Error.apply(this, [message])? See
  // https://gist.github.com/justmoon/15511f92e5216fa2624b#anti-patterns
  Error.captureStackTrace(this, this.constructor);
  this.name = this.constructor.name;
  this.message = message;
}

function TXRejectedError ( message ) { Error . captureStackTrace ( this , this . constructor ) ; this . name = this . constructor . name ; this . message = message ; }

raised when the transaction is rejected prior to running it in the EVM.

raised when the transaction is rejected prior to running it in the EVM .


function RequestFunnel() {
  // We use an object here for O(1) lookups (speed).
  this.methods = {
    eth_call: true,
    eth_getStorageAt: true,
    eth_sendTransaction: true,
    eth_sendRawTransaction: true,

    // Ensure block filter and filter changes are process one at a time
    // as well so filter requests that come in after a transaction get
    // processed once that transaction has finished processing.
    eth_newBlockFilter: true,
    eth_getFilterChanges: true,
    eth_getFilterLogs: true
  };
  this.queue = [];
  this.isWorking = false;
}

function RequestFunnel ( ) { this . methods = { eth_call : true , eth_getStorageAt : true , eth_sendTransaction : true , eth_sendRawTransaction : true , eth_newBlockFilter : true , eth_getFilterChanges : true , eth_getFilterLogs : true } ; this . queue = [ ] ; this . isWorking = false ; }

See if any payloads for the specified methods are marked as external. If they are external, and match the method list, process them one at a time.

See if any payloads for the specified methods are marked as external . If they are external and match the method list process them one at a time .


function compileSass(_path, ext, data, callback) {
  const compiledCss = sass.renderSync({
    data: data,
    outputStyle: 'expanded',
    importer: function (url, prev, done) {
      if (url.startsWith('~')) {
        const newUrl = path.join(__dirname, 'node_modules', url.substr(1));
        return { file: newUrl };
      } else {
        return { file: url };
      }
    }
  });
  callback(null, compiledCss.css);
}

function compileSass ( _path , ext , data , callback ) { const compiledCss = sass . renderSync ( { data : data , outputStyle : 'expanded' , importer : function ( url , prev , done ) { if ( url . startsWith ( '~' ) ) { const newUrl = path . join ( __dirname , 'node_modules' , url . substr ( 1 ) ) ; return { file : newUrl } ; } else { return { file : url } ; } } } ) ; callback ( null , compiledCss . css ) ; }

Compile SASS to CSS.
@see https://github.com/ludohenin/gulp-inline-ng2-template
@see https://github.com/sass/node-sass


function requireBrocfile(brocfilePath) {
  let brocfile;

  if (brocfilePath.match(/\.ts$/)) {
    try {
      require.resolve('ts-node');
    } catch (e) {
      throw new Error(`Cannot find module 'ts-node', please install`);
    }

    try {
      require.resolve('typescript');
    } catch (e) {
      throw new Error(`Cannot find module 'typescript', please install`);
    }

    // Register ts-node typescript compiler
    require('ts-node').register(); // eslint-disable-line node/no-unpublished-require

    // Load brocfile via ts-node
    brocfile = require(brocfilePath);
  } else {
    // Load brocfile via esm shim
    brocfile = esmRequire(brocfilePath);
  }

  // ESM `export default X` is represented as module.exports = { default: X }
  if (brocfile !== null && typeof brocfile === 'object' && brocfile.hasOwnProperty('default')) {
    brocfile = brocfile.default;
  }

  return brocfile;
}

function requireBrocfile ( brocfilePath ) { let brocfile ; if ( brocfilePath . match ( / \.ts$ / ) ) { try { require . resolve ( 'ts-node' ) ; } catch ( e ) { throw new Error ( ` ` ) ; } try { require . resolve ( 'typescript' ) ; } catch ( e ) { throw new Error ( ` ` ) ; } require ( 'ts-node' ) . register ( ) ; brocfile = require ( brocfilePath ) ; } else { brocfile = esmRequire ( brocfilePath ) ; } if ( brocfile !== null && typeof brocfile === 'object' && brocfile . hasOwnProperty ( 'default' ) ) { brocfile = brocfile . default ; } return brocfile ; }

Require a brocfile via either ESM or TypeScript

@param {String} brocfilePath The path to the brocfile
@returns {*}