<commit_before>import {
    Transformime,
    TextTransformer,
    ImageTransformer,
    HTMLTransformer
} from "transformime";

import {
    StreamTransformer,
    TracebackTransformer,
    MarkdownTransformer,
    LaTeXTransformer,
    PDFTransformer
} from "transformime-jupyter-transformers";

(function() {

// Shim & native-safe ownerDocument lookup
var owner = document.currentScript.ownerDocument;

/**
 * Jupyter display area.
 *
 * Used to display output from Jupyter kernels.
 */
class JupyterDisplayArea extends HTMLElement {

    /**
     * When element is created, browser calls this.
     */
    createdCallback() {
        let template = owner.querySelector('#tmpl-jupyter-display-area');
        let node = owner.importNode(template.content, true);

        this.shadow = this.createShadowRoot();
        this.shadow.appendChild(node);
        this.document = this.shadow.ownerDocument;

        this.el = this.shadow.getElementById('outputs');

        /**
         * Original display order
         *
        OutputArea.display_order = [
            'application/javascript',
            'text/html',
            'text/markdown',
            'text/latex',
            'image/svg+xml',
            'image/png',
            'image/jpeg',
            'application/pdf',
            'text/plain'
        ];
        */

        // Transformers are in reverse priority order
        // so that new ones can be `push`ed on with higher priority
        var transformers = [
            new TextTransformer(),
            new PDFTransformer(),
            new ImageTransformer('image/jpeg'),
            new ImageTransformer('image/gif'),
            new ImageTransformer('image/png'),
            // SVG would go here, IF I HAD ONE
            new StreamTransformer(),
            new TracebackTransformer(),
            new MarkdownTransformer(),
            new HTMLTransformer()
            // JavaScript would go here, IF I HAD ONE
        ];

        this.transformime = new Transformime(transformers);

        // 'Private'
        this._outputs = [];
        this._clear_queued = false;
    }

    /**
     * Deserialize, filling the output area.
     * @param  {object} outputs - See nbformat
     */
    fromJSON(outputs) {
        // TODO: Update for promises
        outputs.map(this.appendOutput.bind(this));
    }

    /**
     * Serialize the contents of the output area.
     * @return {object} See nbformat.
     */
    toJSON() {
        return this._outputs;
    }

    /**
     * Handle a Jupyter message.
     *
     * Only handles display related messages, including clear output.
     * @param  {object} msg - See Jupyter msgspec.
     * @return {Promise}     Happy promise
     */
    handle(msg) {
        if(! msg.header || !msg.header.msg_type) {
            return;
        }

        var json = {};
        var msg_type = json.output_type = msg.header.msg_type;
        var content = msg.content;
        switch (msg_type) {
            case 'clear_output':
                // msg spec v4 had stdout, stderr, display keys
                // v4.1 replaced these with just wait
                // The default behavior is the same (stdout=stderr=display=True, wait=False),
                // so v4 messages will still be properly handled,
                // except for the rarely used clearing less than all output.
                this.clearOutput(msg.content.wait || false);
                return;
            case 'stream':
                json.text = content.text;
                json.name = content.name;
                break;
            case 'display_data':
                json.data = content.data;
                json.metadata = content.metadata;
                break;
            case 'execute_result':
                json.data = content.data;
                json.metadata = content.metadata;
                json.execution_count = content.execution_count;
                break;
            case 'error':
                json.ename = content.ename;
                json.evalue = content.evalue;
                json.traceback = content.traceback;
                break;
            case 'status':
            case 'execute_input':
                // Explicit ignore of status changes and input
                return false;
            default:
                console.log('unhandled output message', msg);
                return false;
        }
        return this.appendOutput(json);
    }

    /**
     * Remove all elements from the display area.
     * @param  {boolean} wait - wait until the next display message before clearing.
     */
    clearOutput(wait) {
        if (wait) {

            // If a clear is queued, clear before adding another to the queue.
            if (this._clear_queued) {
                this.clearOutput(false);
            }

            this._clear_queued = true;
        } else {

            if (this._clear_queued) {
                this._clear_queued = false;
            }

            // Clear all
            let o = this.el;
            while(o.firstChild) { o.removeChild(o.firstChild); }

            this._outputs = [];
            return;
        }
    }

    /**
     * Append output to the output area.
     * @param  {object} json - output json.  See nbformat.
     * @return {bool}      whether or not output was appended
     */
    appendOutput(json) {
        let bundle, el;
        bundle = {};

        // Clear the output if clear is queued.
        if (this._clear_queued) {
            this.clearOutput(false);
        }

        switch(json.output_type) {
            case 'execute_result':
            case 'display_data':
                bundle = json.data;
                break;
            case 'stream':
                bundle = {'jupyter/stream': json};
                break;
            case 'error':
                bundle = {'jupyter/traceback': json};
                break;
            default:
                console.warn('Unrecognized output type: ' + json.output_type);
                bundle = {'text/plain': 'Unrecognized output type' + JSON.stringify(json)};
        }

        let elementPromise = this.transformime.transformRichest(bundle, this.document);

        elementPromise.then(elementBundle => {
            this.el.appendChild(elementBundle.el);
        });

        return elementPromise;
    }

}

// Register jupyter-display-area with the document
owner.registerElement('jupyter-display-area', JupyterDisplayArea);

})();
<commit_msg>Promises everywhere!<commit_after>import {
    Transformime,
    TextTransformer,
    ImageTransformer,
    HTMLTransformer
} from "transformime";

import {
    StreamTransformer,
    TracebackTransformer,
    MarkdownTransformer,
    LaTeXTransformer,
    PDFTransformer
} from "transformime-jupyter-transformers";

(function() {

// Shim & native-safe ownerDocument lookup
var owner = document.currentScript.ownerDocument;

/**
 * Jupyter display area.
 *
 * Used to display output from Jupyter kernels.
 */
class JupyterDisplayArea extends HTMLElement {

    /**
     * When element is created, browser calls this.
     */
    createdCallback() {
        let template = owner.querySelector('#tmpl-jupyter-display-area');
        let node = owner.importNode(template.content, true);

        this.shadow = this.createShadowRoot();
        this.shadow.appendChild(node);
        this.document = this.shadow.ownerDocument;

        this.el = this.shadow.getElementById('outputs');

        /**
         * Original display order
         *
        OutputArea.display_order = [
            'application/javascript',
            'text/html',
            'text/markdown',
            'text/latex',
            'image/svg+xml',
            'image/png',
            'image/jpeg',
            'application/pdf',
            'text/plain'
        ];
        */

        // Transformers are in reverse priority order
        // so that new ones can be `push`ed on with higher priority
        var transformers = [
            new TextTransformer(),
            new PDFTransformer(),
            new ImageTransformer('image/jpeg'),
            new ImageTransformer('image/gif'),
            new ImageTransformer('image/png'),
            // SVG would go here, IF I HAD ONE
            new StreamTransformer(),
            new TracebackTransformer(),
            new MarkdownTransformer(),
            new HTMLTransformer()
            // JavaScript would go here, IF I HAD ONE
        ];

        this.transformime = new Transformime(transformers);

        // 'Private'
        this._outputs = [];
        this._clear_queued = false;
    }

    /**
     * Deserialize, filling the output area.
     * @param  {object} outputs - See nbformat
     */
    fromJSON(outputs) {
        return Promise.all(outputs.map(this.appendOutput.bind(this)));
    }

    /**
     * Serialize the contents of the output area.
     * @return {object} See nbformat.
     */
    toJSON() {
        return this._outputs;
    }

    /**
     * Handle a Jupyter message.
     *
     * Only handles display related messages, including clear output.
     * @param  {object} msg - See Jupyter msgspec.
     * @return {Promise}     Happy promise
     */
    handle(msg) {
        if(!msg.header || !msg.header.msg_type) {
            return;
        }

        var json = {};
        var msg_type = json.output_type = msg.header.msg_type;
        var content = msg.content;
        switch (msg_type) {
            case 'clear_output':
                // msg spec v4 had stdout, stderr, display keys
                // v4.1 replaced these with just wait
                // The default behavior is the same (stdout=stderr=display=True, wait=False),
                // so v4 messages will still be properly handled,
                // except for the rarely used clearing less than all output.
                this.clearOutput(msg.content.wait || false);
                return Promise.resolve();
            case 'stream':
                json.text = content.text;
                json.name = content.name;
                break;
            case 'display_data':
                json.data = content.data;
                json.metadata = content.metadata;
                break;
            case 'execute_result':
                json.data = content.data;
                json.metadata = content.metadata;
                json.execution_count = content.execution_count;
                break;
            case 'error':
                json.ename = content.ename;
                json.evalue = content.evalue;
                json.traceback = content.traceback;
                break;
            case 'status':
            case 'execute_input':
                // Explicit ignore of status changes and input
                return Promise.reject("Jupyter Display Area doesn't handle status or execute_input");
            default:
                return Promise.reject("Unhandled output message " + JSON.stringify(msg));
        }
        return this.appendOutput(json);
    }

    /**
     * Remove all elements from the display area.
     * @param  {boolean} wait - wait until the next display message before clearing.
     */
    clearOutput(wait) {
        if (wait) {

            // If a clear is queued, clear before adding another to the queue.
            if (this._clear_queued) {
                this.clearOutput(false);
            }

            this._clear_queued = true;
        } else {

            if (this._clear_queued) {
                this._clear_queued = false;
            }

            // Clear all
            let o = this.el;
            while(o.firstChild) { o.removeChild(o.firstChild); }

            this._outputs = [];
            return;
        }
    }

    /**
     * Append output to the output area.
     * @param  {object} json - output json.  See nbformat.
     * @return {Promise}
     */
    appendOutput(json) {
        let bundle, el;
        bundle = {};

        // Clear the output if clear is queued.
        if (this._clear_queued) {
            this.clearOutput(false);
        }

        switch(json.output_type) {
            case 'execute_result':
            case 'display_data':
                bundle = json.data;
                break;
            case 'stream':
                bundle = {'jupyter/stream': json};
                break;
            case 'error':
                bundle = {'jupyter/traceback': json};
                break;
            default:
                console.warn('Unrecognized output type: ' + json.output_type);
                bundle = {'text/plain': 'Unrecognized output type' + JSON.stringify(json)};
        }

        let elementPromise = this.transformime.transformRichest(bundle, this.document);

        elementPromise.then(elementBundle => {
            this.el.appendChild(elementBundle.el);
        });

        return elementPromise;
    }

}

// Register jupyter-display-area with the document
owner.registerElement('jupyter-display-area', JupyterDisplayArea);

})();
<|endoftext|>


<commit_before>/*
Language: PowerShell
Author: David Mohundro <david@mohundro.com>
Contributors: Nicholas Blumhardt <nblumhardt@nblumhardt.com>, Victor Zhou <OiCMudkips@users.noreply.github.com>
*/

function(hljs) {
  var backtickEscape = {
    begin: '`[\\s\\S]',
    relevance: 0
  };
  var VAR = {
    className: 'variable',
    variants: [
      {begin: /\$[\w\d][\w\d_:]*/}
    ]
  };
  var LITERAL = {
    className: 'literal',
    begin: /\$(null|true|false)\b/
  };
  var QUOTE_STRING = {
    className: 'string',
    begin: /"/, end: /"/,
    contains: [
      backtickEscape,
      VAR,
      {
        className: 'variable',
        begin: /\$[A-z]/, end: /[^A-z]/
      }
    ]
  };
  var APOS_STRING = {
    className: 'string',
    begin: /'/, end: /'/
  };

  var MULTILINE_COMMENT = {
    className: 'comment',
    begin: /<#/, end: /#>/
  }

  return {
    aliases: ['ps'],
    lexemes: /-?[A-z\.\-]+/,
    case_insensitive: true,
    keywords: {
      keyword: 'if else foreach return function do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch',
      built_in: 'Add-Content Add-History Add-Member Add-PSSnapin Clear-Content Clear-Item Clear-Item Property Clear-Variable Compare-Object ConvertFrom-SecureString Convert-Path ConvertTo-Html ConvertTo-SecureString Copy-Item Copy-ItemProperty Export-Alias Export-Clixml Export-Console Export-Csv ForEach-Object Format-Custom Format-List Format-Table Format-Wide Get-Acl Get-Alias Get-AuthenticodeSignature Get-ChildItem Get-Command Get-Content Get-Credential Get-Culture Get-Date Get-EventLog Get-ExecutionPolicy Get-Help Get-History Get-Host Get-Item Get-ItemProperty Get-Location Get-Member Get-PfxCertificate Get-Process Get-PSDrive Get-PSProvider Get-PSSnapin Get-Service Get-TraceSource Get-UICulture Get-Unique Get-Variable Get-WmiObject Group-Object Import-Alias Import-Clixml Import-Csv Invoke-Expression Invoke-History Invoke-Item Join-Path Measure-Command Measure-Object Move-Item Move-ItemProperty New-Alias New-Item New-ItemProperty New-Object New-PSDrive New-Service New-TimeSpan New-Variable Out-Default Out-File Out-Host Out-Null Out-Printer Out-String Pop-Location Push-Location Read-Host Remove-Item Remove-ItemProperty Remove-PSDrive Remove-PSSnapin Remove-Variable Rename-Item Rename-ItemProperty Resolve-Path Restart-Service Resume-Service Select-Object Select-String Set-Acl Set-Alias Set-AuthenticodeSignature Set-Content Set-Date Set-ExecutionPolicy Set-Item Set-ItemProperty Set-Location Set-PSDebug Set-Service Set-TraceSource Set-Variable Sort-Object Split-Path Start-Service Start-Sleep Start-Transcript Stop-Process Stop-Service Stop-Transcript Suspend-Service Tee-Object Test-Path Trace-Command Update-FormatData Update-TypeData Where-Object Write-Debug Write-Error Write-Host Write-Output Write-Progress Write-Verbose Write-Warning',
      nomarkup: '-ne -eq -lt -gt -ge -le -not -like -notlike -match -notmatch -contains -notcontains -in -notin -replace'
    },
    contains: [
      hljs.HASH_COMMENT_MODE,
      hljs.NUMBER_MODE,
      QUOTE_STRING,
      APOS_STRING,
      LITERAL,
      VAR,
	  MULTILINE_COMMENT
    ]
  };
}
<commit_msg>fix whitespace<commit_after>/*
Language: PowerShell
Author: David Mohundro <david@mohundro.com>
Contributors: Nicholas Blumhardt <nblumhardt@nblumhardt.com>, Victor Zhou <OiCMudkips@users.noreply.github.com>
*/

function(hljs) {
  var backtickEscape = {
    begin: '`[\\s\\S]',
    relevance: 0
  };
  var VAR = {
    className: 'variable',
    variants: [
      {begin: /\$[\w\d][\w\d_:]*/}
    ]
  };
  var LITERAL = {
    className: 'literal',
    begin: /\$(null|true|false)\b/
  };
  var QUOTE_STRING = {
    className: 'string',
    begin: /"/, end: /"/,
    contains: [
      backtickEscape,
      VAR,
      {
        className: 'variable',
        begin: /\$[A-z]/, end: /[^A-z]/
      }
    ]
  };
  var APOS_STRING = {
    className: 'string',
    begin: /'/, end: /'/
  };

  var MULTILINE_COMMENT = {
    className: 'comment',
    begin: /<#/, end: /#>/
  }

  return {
    aliases: ['ps'],
    lexemes: /-?[A-z\.\-]+/,
    case_insensitive: true,
    keywords: {
      keyword: 'if else foreach return function do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch',
      built_in: 'Add-Content Add-History Add-Member Add-PSSnapin Clear-Content Clear-Item Clear-Item Property Clear-Variable Compare-Object ConvertFrom-SecureString Convert-Path ConvertTo-Html ConvertTo-SecureString Copy-Item Copy-ItemProperty Export-Alias Export-Clixml Export-Console Export-Csv ForEach-Object Format-Custom Format-List Format-Table Format-Wide Get-Acl Get-Alias Get-AuthenticodeSignature Get-ChildItem Get-Command Get-Content Get-Credential Get-Culture Get-Date Get-EventLog Get-ExecutionPolicy Get-Help Get-History Get-Host Get-Item Get-ItemProperty Get-Location Get-Member Get-PfxCertificate Get-Process Get-PSDrive Get-PSProvider Get-PSSnapin Get-Service Get-TraceSource Get-UICulture Get-Unique Get-Variable Get-WmiObject Group-Object Import-Alias Import-Clixml Import-Csv Invoke-Expression Invoke-History Invoke-Item Join-Path Measure-Command Measure-Object Move-Item Move-ItemProperty New-Alias New-Item New-ItemProperty New-Object New-PSDrive New-Service New-TimeSpan New-Variable Out-Default Out-File Out-Host Out-Null Out-Printer Out-String Pop-Location Push-Location Read-Host Remove-Item Remove-ItemProperty Remove-PSDrive Remove-PSSnapin Remove-Variable Rename-Item Rename-ItemProperty Resolve-Path Restart-Service Resume-Service Select-Object Select-String Set-Acl Set-Alias Set-AuthenticodeSignature Set-Content Set-Date Set-ExecutionPolicy Set-Item Set-ItemProperty Set-Location Set-PSDebug Set-Service Set-TraceSource Set-Variable Sort-Object Split-Path Start-Service Start-Sleep Start-Transcript Stop-Process Stop-Service Stop-Transcript Suspend-Service Tee-Object Test-Path Trace-Command Update-FormatData Update-TypeData Where-Object Write-Debug Write-Error Write-Host Write-Output Write-Progress Write-Verbose Write-Warning',
      nomarkup: '-ne -eq -lt -gt -ge -le -not -like -notlike -match -notmatch -contains -notcontains -in -notin -replace'
    },
    contains: [
      hljs.HASH_COMMENT_MODE,
      hljs.NUMBER_MODE,
      QUOTE_STRING,
      APOS_STRING,
      LITERAL,
      VAR,
      MULTILINE_COMMENT
    ]
  };
}
<|endoftext|>


<commit_before>'use strict';
const request         = require('../comum/tago_request.js');
const config          = require('../config.js');
const default_headers = require('../comum/default_headers.js');

/** Class for the Connector and data */
class Connector {
  /** Connector
     * @param  {String} Connector Token
     * @param  {Boolean} Show Details
     * @return {Object} Connector Object
     */
  constructor(token, details) {
    this.token   = token;
    this.default_options = {
      'json': true,
      'headers': default_headers(this)
    };

    if (details) {
      this.default_options.qs = {'details': true};
    }
  }

  /** Info
     * Get information about the current connector
     * @return {Promise}
     */
  info() {
    let url    = `${config.api_url}/info`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, {url, method});
    return request(options);
  }

  resolveToken(serie_number, authorization) {
    let url    = `${config.api_url}/info/${serie_number}`;
    let method = 'GET';

    if (authorization) url = `${url}/${authorization}`;

    let options = Object.assign({}, this.default_options, {url, method});
    return request(options);
  }
}

module.exports = Connector;
<commit_msg>fixed resolveToken connector route<commit_after>'use strict';
const request         = require('../comum/tago_request.js');
const config          = require('../config.js');
const default_headers = require('../comum/default_headers.js');

/** Class for the Connector and data */
class Connector {
  /** Connector
     * @param  {String} Connector Token
     * @param  {Boolean} Show Details
     * @return {Object} Connector Object
     */
  constructor(token, details) {
    this.token   = token;
    this.default_options = {
      'json': true,
      'headers': default_headers(this)
    };

    if (details) {
      this.default_options.qs = {'details': true};
    }
  }

  /** Info
     * Get information about the current connector
     * @return {Promise}
     */
  info() {
    let url    = `${config.api_url}/info`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, {url, method});
    return request(options);
  }

  resolveToken(serie_number, authorization) {
    let url    = `${config.api_url}/connector/resolve/${serie_number}`;
    let method = 'GET';

    if (authorization) url = `${url}/${authorization}`;

    let options = Object.assign({}, this.default_options, {url, method});
    return request(options);
  }
}

module.exports = Connector;
<|endoftext|>


<commit_before>const config = require('./server/init/configuration')
const queue = require('node-queue-adapter')(config.secure.azure.queueConnectionString)
const {addDescription} = require('message-type')
const handleMessage = require('./handleMessage')
<<<<<<< HEAD
require('colors')

=======
var MESSAGECOUNTER = 0
>>>>>>> 2be91919e12578a68c13130ac99f6a52f27ef2af
function readMessage () {
  MESSAGECOUNTER += 1
  process.stdout.write('\nChecking Azure queue... ' + MESSAGECOUNTER)

  let message
  return queue
    .readMessageFromQueue('ug-canvas')
    .then(msg => {
      message = msg
      if (!msg) {
        // Best way to abort a promise chain is by a custom error according to:
        // http://stackoverflow.com/questions/11302271/how-to-properly-abort-a-node-js-promise-chain-using-q
        throw new Error('abort_chain')
      }

      return msg
    })
    .then(msg => JSON.parse(msg.body))
    .then(msg =>{
        console.log(JSON.stringify(msg,null,4).blue);
        return msg
    })
    .then(addDescription)
    .then(handleMessage)
    .then(() => queue.deleteMessageFromQueue(message))
    .then(readMessage)
    .catch(e => {
      if (e.message !== 'abort_chain') {
        console.log("\nIn Error handling function testing to remove the message from queue.....")
        console.error(`Exception: `, e)
      }
      return readMessage()
    })
}
readMessage()
<commit_msg>logging messages<commit_after>const config = require('./server/init/configuration')
const queue = require('node-queue-adapter')(config.secure.azure.queueConnectionString)
const {addDescription} = require('message-type')
const handleMessage = require('./handleMessage')

require('colors')

var MESSAGECOUNTER = 0

function readMessage () {
  MESSAGECOUNTER += 1
  //process.stdout.write('\nChecking Azure queue... ' + MESSAGECOUNTER)

  let message
  return queue
    .readMessageFromQueue('ug-canvas')
    .then(msg => {
      message = msg
      if (!msg) {
        // Best way to abort a promise chain is by a custom error according to:
        // http://stackoverflow.com/questions/11302271/how-to-properly-abort-a-node-js-promise-chain-using-q
        throw new Error('abort_chain')
      }

      return msg
    })
    .then(msg => JSON.parse(msg.body))
    .then(msg =>{
        console.log(JSON.stringify(msg,null,4).blue);
        return msg
    })
    .then(addDescription)
    .then(handleMessage)
    .then(() => queue.deleteMessageFromQueue(message))
    .then(readMessage)
    .catch(e => {
      if (e.message !== 'abort_chain') {
        console.log("\nIn Error handling function testing to remove the message from queue.....")
        console.error(`Exception: `, e)
      }
      return readMessage()
    })
}
readMessage()
<|endoftext|>


<commit_before>function ContainElement(options) {
	var scaleFactor = 1;
	var element = document.getElementById(options.id);
	var elementWidth = options.width || element.offsetWidth;
	var elementHeight = options.height || element.offsetHeight;

	// Apply required attributes to the element and its parents
	element.style.position = 'absolute';
	element.parentElement.style.overflow = 'hidden';
	if (['relative', 'absolute', 'fixed'].indexOf(window.getComputedStyle(element.parentElement, null).getPropertyValue('position')) === -1)
		element.parentElement.style.position = 'relative';

	function updateContain() {
		var parentWidth = element.parentElement.offsetWidth;
		var parentHeight = element.parentElement.offsetHeight;

		// Run the scale/position functionality if able to determine the document width and height
		if ((parentWidth) && (parentHeight)) {
			// Calculate the scale factor
			if (parentWidth > ((parentHeight / (elementHeight * scaleFactor)) * (elementWidth * scaleFactor)))
				scaleFactor = (parentWidth / elementWidth);
			else
				scaleFactor = (parentHeight / elementHeight);

			// Scale the element using the scale factor
			element.style.width = (elementWidth * scaleFactor) + 'px';
			element.style.height = (elementHeight * scaleFactor) + 'px';

			// Anchor the element horizontally to the left/center/right
			if (parentWidth < (elementWidth * scaleFactor)) {
				switch(options.halign) {
					case 'left':
						// Anchor horizontally to the left of the parent element
						element.style.left = 0 + 'px';
						break;
					case 'right':
						// Anchor horizontally to the right of the parent element
						element.style.left = (0 - ((elementWidth * scaleFactor) - parentWidth)) + 'px';
						break;
					default:
						// Anchor horizontally to the center of the parent element
						element.style.left = (0 - (((elementWidth * scaleFactor) - parentWidth) / 2)) + 'px';
				}
			} else {
				element.style.left = 0 + 'px';
			}

			// Anchor the element vertically to the top/center/bottom
			if ((elementHeight * scaleFactor) > parentHeight) {
				switch(options.valign) {
					case 'top':
						// Anchor vertically to the top of the parent element
						element.style.top = 0 + 'px';
						break;
					case 'bottom':
						// Anchor veritcally to the bottom of the parent element
						element.style.top = (0 - ((elementHeight * scaleFactor) - parentHeight)) + 'px';
						break;
					default:
						// Anchor vertically to the center of the parent element
						element.style.top = (0 - (((elementHeight * scaleFactor) - parentHeight) / 2)) + 'px';
				}
			} else {
				element.style.top = 0 + 'px';
			}
		} else {
			// Try again in 30ms if the document didn't load enough to determine its width and height yet
			window.setTimeout(updateContain, 30);
		}
	}

	// Run the scale function and bind it to various window-size-changing events
	updateContain();

	// Add scale function to the library
	this.update = updateContain;
}

<commit_msg>Update comments to reflect changes made since writing them<commit_after>function ContainElement(options) {
	var scaleFactor = 1;
	var element = document.getElementById(options.id);
	var elementWidth = options.width || element.offsetWidth;
	var elementHeight = options.height || element.offsetHeight;

	// Apply required attributes to the element and its parents
	element.style.position = 'absolute';
	element.parentElement.style.overflow = 'hidden';
	if (['relative', 'absolute', 'fixed'].indexOf(window.getComputedStyle(element.parentElement, null).getPropertyValue('position')) === -1)
		element.parentElement.style.position = 'relative';

	function updateContain() {
		var parentWidth = element.parentElement.offsetWidth;
		var parentHeight = element.parentElement.offsetHeight;

		// Run the scale/position functionality if able to determine the document width and height
		if ((parentWidth) && (parentHeight)) {
			// Calculate the scale factor
			if (parentWidth > ((parentHeight / (elementHeight * scaleFactor)) * (elementWidth * scaleFactor)))
				scaleFactor = (parentWidth / elementWidth);
			else
				scaleFactor = (parentHeight / elementHeight);

			// Scale the element using the scale factor
			element.style.width = (elementWidth * scaleFactor) + 'px';
			element.style.height = (elementHeight * scaleFactor) + 'px';

			// Anchor the element horizontally to the left/center/right
			if (parentWidth < (elementWidth * scaleFactor)) {
				switch(options.halign) {
					case 'left':
						// Anchor horizontally to the left of the parent element
						element.style.left = 0 + 'px';
						break;
					case 'right':
						// Anchor horizontally to the right of the parent element
						element.style.left = (0 - ((elementWidth * scaleFactor) - parentWidth)) + 'px';
						break;
					default:
						// Anchor horizontally to the center of the parent element
						element.style.left = (0 - (((elementWidth * scaleFactor) - parentWidth) / 2)) + 'px';
				}
			} else {
				element.style.left = 0 + 'px';
			}

			// Anchor the element vertically to the top/center/bottom
			if ((elementHeight * scaleFactor) > parentHeight) {
				switch(options.valign) {
					case 'top':
						// Anchor vertically to the top of the parent element
						element.style.top = 0 + 'px';
						break;
					case 'bottom':
						// Anchor veritcally to the bottom of the parent element
						element.style.top = (0 - ((elementHeight * scaleFactor) - parentHeight)) + 'px';
						break;
					default:
						// Anchor vertically to the center of the parent element
						element.style.top = (0 - (((elementHeight * scaleFactor) - parentHeight) / 2)) + 'px';
				}
			} else {
				element.style.top = 0 + 'px';
			}
		} else {
			// Try again in 30ms if the document didn't load enough to determine its width and height yet
			window.setTimeout(updateContain, 30);
		}
	}

	// Run the function to scale and anchor the element
	updateContain();

	// Add an external scale and anchor update function
	this.update = updateContain;
}

<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { Autobind } from 'es-decorators';

// Redux
import withRedux from 'next-redux-wrapper';
import { initStore } from 'store';
import { setLimit } from 'redactions/widgetEditor';

class LimitContainer extends React.Component {

  @Autobind
  handleLimitChange(event) {
    let newValue = null;
    try {
      newValue = parseInt(event.target.value, 10);
      if (isNaN(newValue) || newValue > 1000) {
        newValue = 1000;
      }
    } catch (err) {
      newValue = 1000;
    }
    this.props.setLimit(newValue);
  }

  render() {
    const { widgetEditor } = this.props;
    const limit = widgetEditor.limit;

    return (

          Limit

        <input
          value={limit}
          onChange={this.handleLimitChange}
        />

    );
  }
}

LimitContainer.propTypes = {
  // Store
  widgetEditor: PropTypes.object.isRequired,
  setLimit: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  widgetEditor: state.widgetEditor
});

const mapDispatchToProps = dispatch => ({
  setLimit: (limit) => {
    dispatch(setLimit(limit));
  }
});

export default withRedux(initStore, mapStateToProps, mapDispatchToProps)(LimitContainer);
<commit_msg>Debounce the limit field of the widget editor<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { Autobind } from 'es-decorators';
import debounce from 'lodash/debounce';

// Redux
import withRedux from 'next-redux-wrapper';
import { initStore } from 'store';
import { setLimit } from 'redactions/widgetEditor';

class LimitContainer extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      limit: props.widgetEditor.limit || 1000
    };
  }

  @Autobind
  handleLimitChange(newLimit) {
    // We round the number to an integer
    let limit = Math.round(newLimit);

    // We also restrict it to [[1, 1000]]
    limit = Math.max(Math.min(limit, 1000), 1);

    this.setState({ limit });
    this.props.setLimit(limit);
  }

  render() {
    return (

          Limit

        <input
          type="number"
          step="1"
          min="1"
          max="1000"
          value={this.state.limit}
          onChange={e => this.handleLimitChange(e.target.value)}
        />

    );
  }
}

LimitContainer.propTypes = {
  // Store
  widgetEditor: PropTypes.object.isRequired,
  setLimit: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  widgetEditor: state.widgetEditor
});

const mapDispatchToProps = dispatch => ({
  setLimit: debounce((limit) => {
    dispatch(setLimit(limit));
  }, 500)
});

export default withRedux(initStore, mapStateToProps, mapDispatchToProps)(LimitContainer);
<|endoftext|>


<commit_before>'use strict';

const express = require('express').Router;
const pg = require('../lib/pg');
const app = express();

const HttpError = require('@starefossen/http-error');

app.get('/routing', (req, res, next) => {
  // Convert all coordinates to propper float values
  const source = (req.query.source || '')
    .split(',')
    .map(coordinate => parseFloat(coordinate, 10))
    .filter(coordinate => !isNaN(coordinate));

  const target = (req.query.target || '')
    .split(',')
    .map(coordinate => parseFloat(coordinate, 10))
    .filter(coordinate => !isNaN(coordinate));

  // Validate required source and target parameters
  if (source.length !== 2 || target.length !== 2) {
    return next(new HttpError('Missing or invalid coordinates', 400));
  }

  const pathBuffer = Math.min(parseInt(req.query.path_buffer || 2000, 10), 4000);
  const pointBuffer = Math.min(parseInt(req.query.point_buffer || 10, 10), 1000);

  const sql = pg.SQL`
    SELECT
      cost,
      ST_AsGeoJSON(ST_Transform(geom, 4326)) as geometry
    FROM path(
      ${source[0]}, ${source[1]},
      ${target[0]}, ${target[1]},
      path_buffer:=${pathBuffer},
      point_buffer:=${pointBuffer}
    )
    LIMIT 1;
  `;

  return pg.query(sql, (err, result) => {
    if (err) { return next(new HttpError('Database Query Failed', 500, err)); }

    const collection = {
      type: 'GeometryCollection',
      geometries: [],
    };

    if (!result.rows.length || !result.rows[0].geometry) {
      return res.json(collection);
    }

    result.rows.forEach((row) => {
      collection.geometries.push({
        type: 'Feature',
        geometry: JSON.parse(row.geometry),
        properties: { cost: row.cost },
      });
    });

    return res.json(collection);
  });
});

module.exports = app;
<commit_msg>feat(routing): type cast prepared statement input parameters<commit_after>'use strict';

const express = require('express').Router;
const pg = require('../lib/pg');
const app = express();

const HttpError = require('@starefossen/http-error');

app.get('/routing', (req, res, next) => {
  // Convert all coordinates to propper float values
  const source = (req.query.source || '')
    .split(',')
    .map(coordinate => parseFloat(coordinate, 10))
    .filter(coordinate => !isNaN(coordinate));

  const target = (req.query.target || '')
    .split(',')
    .map(coordinate => parseFloat(coordinate, 10))
    .filter(coordinate => !isNaN(coordinate));

  // Validate required source and target parameters
  if (source.length !== 2 || target.length !== 2) {
    return next(new HttpError('Missing or invalid coordinates', 400));
  }

  const pathBuffer = Math.min(parseInt(req.query.path_buffer || 2000, 10), 4000);
  const pointBuffer = Math.min(parseInt(req.query.point_buffer || 10, 10), 1000);

  const sql = pg.SQL`
    SELECT
      cost,
      ST_AsGeoJSON(ST_Transform(geom, 4326)) as geometry
    FROM path(
      ${source[0]}::double precision,
      ${source[1]}::double precision,
      ${target[0]}::double precision,
      ${target[1]}::double precision,
      path_buffer:=${pathBuffer}::integer,
      point_buffer:=${pointBuffer}::integer
    )
    LIMIT 1;
  `;

  return pg.query(sql, (err, result) => {
    if (err) { return next(new HttpError('Database Query Failed', 500, err)); }

    const collection = {
      type: 'GeometryCollection',
      geometries: [],
    };

    if (!result.rows.length || !result.rows[0].geometry) {
      return res.json(collection);
    }

    result.rows.forEach((row) => {
      collection.geometries.push({
        type: 'Feature',
        geometry: JSON.parse(row.geometry),
        properties: { cost: row.cost },
      });
    });

    return res.json(collection);
  });
});

module.exports = app;
<|endoftext|>


<commit_before>var topic_ctrl = require('./topic');

var config = require('../config').config;
var data2xml = require('data2xml');

exports.index = function (req,res,next) {
	if (!config.rss) {
		return res.send('Please set `rss` in config.js');
	}
	var opt = { limit: config.rss.max_rss_items, sort: [['create_at','desc']] };

	topic_ctrl.get_topics_by_query({}, opt, function (err, topics) {
		if(err) return next(err);

		var rss_obj = {
			_attr: { version: '2.0' },
			channel: {
				title: config.rss.title,
				link: config.rss.link,
				language: config.rss.language,
				description: config.rss.description,
				item: []
			},
		};

		topics.forEach(function (topic) {
			rss_obj.channel.item.push({
				title: topic.title,
				link: config.rss.link + '/topic/' + topic._id,
				guid: config.rss.link + '/topic/' + topic._id,
				description: topic.content,
				author: topic.author.name,
				pubDate: topic.create_at.toUTCString()
			});
		});

		var rss_content = data2xml('rss', rss_obj);

		res.contentType('application/xml');
		res.send(rss_content);
	});
};
<commit_msg>convert markdown to html for rss reader<commit_after>var topic_ctrl = require('./topic');

var config = require('../config').config;
var data2xml = require('data2xml');
var Markdown = require('node-markdown').Markdown;

exports.index = function (req,res,next) {
	if (!config.rss) {
		return res.send('Please set `rss` in config.js');
	}
	var opt = { limit: config.rss.max_rss_items, sort: [['create_at','desc']] };

	topic_ctrl.get_topics_by_query({}, opt, function (err, topics) {
		if(err) return next(err);

		var rss_obj = {
			_attr: { version: '2.0' },
			channel: {
				title: config.rss.title,
				link: config.rss.link,
				language: config.rss.language,
				description: config.rss.description,
				item: []
			},
		};

		topics.forEach(function (topic) {
			rss_obj.channel.item.push({
				title: topic.title,
				link: config.rss.link + '/topic/' + topic._id,
				guid: config.rss.link + '/topic/' + topic._id,
				description: Markdown(topic.content, true),
				author: topic.author.name,
				pubDate: topic.create_at.toUTCString()
			});
		});

		var rss_content = data2xml('rss', rss_obj);

		res.contentType('application/xml');
		res.send(rss_content);
	});
};
<|endoftext|>


<commit_before>

module.exports = (app, text) => {
  let slapp = app.slapp
  let helpText = text
  let kv = app.dataStore

  // response to the user typing "help"
  slapp.message('help', ['mention', 'direct_message'], (msg) => {
    msg.say(helpText)
}
<commit_msg>testing beepboop persist storage<commit_after>

module.exports = (app, text) => {
  let slapp = app.slapp
  let helpText = text
  let kv = app.dataStore

  // response to the user typing "help"
  slapp.message('help', ['mention', 'direct_message'], (msg) => {
    msg.say(helpText)
  })
}
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
} from 'react-native';
import SpotlightSearch from 'react-native-spotlight-search';
import banana from './banana.png'
import strawberry from './strawberry.png'
import kiwi from './kiwi.png'

const sampleFruits = [
  {
    name: 'Strawberry',
    details: 'A sweet and juicy fruit.',
    key: '1',
    image: strawberry,
    keywords: ['delicious', 'edible'],
  },
  {
    name: 'Banana',
    details: 'A bright yellow fruit.',
    key: '2',
    image: banana,
    keywords: ['plantain'],
  },
  {
    name: 'Kiwi',
    details: 'Not a type of bird.',
    key: '3',
    image: kiwi,
    keywords: ['new zeland'],
  },
];

SpotlightSearch.searchItemTapped((uniqueIdentifier) => {
  const selectedFruit = sampleFruits.filter((fruit) => fruit.key === uniqueIdentifier)[0];

  alert(`You tapped on ${selectedFruit.name}!`);
});

const indexSearchableItems = (() => {
  SpotlightSearch.indexItems(sampleFruits.map((fruit) => {
    return {
      title: fruit.name,
      contentDescription: fruit.details,
      uniqueIdentifier: fruit.key,
      thumbnailUri: fruit.image.path,
      keywords: fruit.keywords,
    };
  }));
})();

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  introText: {
    marginTop: 64,
  },
  row: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: 10,
    paddingRight: 10,
  },
  rowTextContainer: {
    flex: 1,
    justifyContent: 'center',
    padding: 4,
  },
  rowTitle: {
    fontSize: 20,
  },
  rowDescription: {
    color: '#333333',
  },
  rowImage: {
    width: 64,
    height: 64,
  }
});

const FruitRow = ({fruit}) => (
  <View style={styles.row}>
    <Image resizeMode={Image.resizeMode.contain}
      style={styles.rowImage}
      source={fruit.image}/>
    <View style={styles.rowTextContainer}>
      <Text style={styles.rowTitle}>{fruit.name}</Text>
      <Text style={styles.rowDescription}>{fruit.details}</Text>
    </View>
  </View>
);

const Example = () => (
  <View style={styles.container}>
    <Text style={styles.introText}>The items below have been added to the Spotlight search index on this device</Text>
    {sampleFruits.map((fruit) => (
      <FruitRow key={fruit.key}
        fruit={fruit}/>
    ))}
  </View>
);

export default Example;
<commit_msg>Style improvements.<commit_after>import React, {Component} from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
} from 'react-native';
import SpotlightSearch from 'react-native-spotlight-search';
import banana from './banana.png'
import strawberry from './strawberry.png'
import kiwi from './kiwi.png'

const sampleFruits = [
  {
    name: 'Strawberry',
    details: 'A sweet and juicy fruit.',
    key: '1',
    image: strawberry,
    keywords: ['delicious', 'edible'],
  },
  {
    name: 'Banana',
    details: 'A bright yellow fruit.',
    key: '2',
    image: banana,
    keywords: ['plantain'],
  },
  {
    name: 'Kiwi',
    details: 'Not a type of bird.',
    key: '3',
    image: kiwi,
    keywords: ['new zeland'],
  },
];

SpotlightSearch.searchItemTapped((uniqueIdentifier) => {
  const selectedFruit = sampleFruits.filter((fruit) => fruit.key === uniqueIdentifier)[0];

  alert(`You tapped on ${selectedFruit.name}!`);
});

const indexSearchableItems = (() => {
  SpotlightSearch.indexItems(sampleFruits.map((fruit) => {
    return {
      title: fruit.name,
      contentDescription: fruit.details,
      uniqueIdentifier: fruit.key,
      thumbnailUri: fruit.image.path,
      keywords: fruit.keywords,
    };
  }));
})();

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
    paddingLeft: 10,
    paddingRight: 10,
  },
  introText: {
    marginTop: 64,
  },
  row: {
    height: 120,
    flexDirection: 'row',
    alignItems: 'center',
  },
  rowTextContainer: {
    flex: 1,
    justifyContent: 'center',
    padding: 4,
  },
  rowTitle: {
    fontSize: 20,
  },
  rowDescription: {
    color: '#333333',
  },
  rowImage: {
    width: 64,
    height: 64,
  }
});

const FruitRow = ({fruit}) => (
  <View style={styles.row}>
    <Image resizeMode={Image.resizeMode.contain}
      style={styles.rowImage}
      source={fruit.image}/>
    <View style={styles.rowTextContainer}>
      <Text style={styles.rowTitle}>{fruit.name}</Text>
      <Text style={styles.rowDescription}>{fruit.details}</Text>
    </View>
  </View>
);

const Example = () => (
  <View style={styles.container}>
    <Text style={styles.introText}>The items below have been added to the Spotlight search index on this device</Text>
    {sampleFruits.map((fruit) => (
      <FruitRow key={fruit.key}
        fruit={fruit}/>
    ))}
  </View>
);

export default Example;
<|endoftext|>


<commit_before>function serialize_object(form_selector) {
    var formdata = $(form_selector).serializeArray();
    var data = {};
    _.each(formdata, function(element){
    // Return all of the values of the object's properties.
      var value = _.values(element);
    // name : value
      data[value[0]] = value[1];
    });
    return data;
}
function validate_item(json) {
    return _.every(_.values(json));
}

$(function() {
    var Item = Backbone.Model.extend({
        idAttribute: '_id',
        urlRoot: "",
        schema: {
            item_id: 'Text',
            buy_buyout: 'Text',
            buy_amount: 'Text',
            buy_additive: 'Text',

            sell_min_buyout: 'Text',
            sell_max_buyout: 'Text',
            sell_run_time: 'Text',
            sell_stack_size: 'Text',
            sell_ignore_stacks_below: 'Text',
            sell_amount: 'Text',
            sell_bid_percent: 'Text',
            sell_undercut_percent: 'Text'
        }
    });
    var Items = Backbone.Collection.extend({
        model: Item,
        url: ""
    });
    var ItemInfoView = Backbone.Marionette.ItemView.extend({
        initialize: function() {
            this.listenTo(this.model, 'destroy', this.remove);
        },
        template: "#item_info_template",
        tagName: "div",
        events: {
            'click button#btn_delete': 'delete_item',
        },
        delete_item: function(e) {
            this.model.destroy();
        }
    });
    var ItemsView = Backbone.Marionette.CompositeView.extend({
        tagName: "div",
        id: 'item_accordion',
        className: 'panel-group wat',
        attributes: {
            'role': 'tablist',
            'aria-multiselectable': 'true'
        },
        childView: ItemInfoView,
        template: "#item_data_template",
    });

    var ItemOutputView = Backbone.Marionette.ItemView.extend({
        initialize: function() {},
        template: "#item_output_template",
        tagName: "div",
        events: {}
    });

    var CreateItemView = Backbone.Marionette.ItemView.extend({
        initialize: function(starting_items) {
            this.currency_regex = /(\d+[Gg])?(\d{1,2}[Ss])?(\d{1,2}[Cc])?/;
            var validate_keys = _.keys(new Item().schema);
            // don't validate boolean field
            this.validate_keys = _.filter(validate_keys, function(k) {return k!=='buy_additive';});
        },
        template: "#item_add_template",
        tagName: "div",
        events: {
            'click button#add_item_submit': 'add_item'
        },
        field_is_not_blank: function(attributes, field) {
            return (attributes[field] && attributes[field].length > 0);
        },
        show_failed_validation: function(field_id) {
            $('div#'+field_id).addClass('has-error');
        },
        validate_item: function(item) {
            // for each field, check that the attributes value isn't blank
            //var greediest_match = item.attributes.buy_buyout.match(this.currency_regex);
            //console.log(greediest_match[0]);

            // clear prior validation
            _.each(this.validate_keys, function(key) {$('div#'+key).removeClass('has-error');});

            var not_blank = _.partial(this.field_is_not_blank, item.attributes, _);
            var failed_fields = _.reject(this.validate_keys, not_blank);
            _.each(failed_fields, this.show_failed_validation);

            return failed_fields.length === 0;
        },
        add_item: function(e) {
            var form_data = serialize_object('form#item_add_form');

            if(form_data.buy_additive === 'on') {
                form_data.buy_additive = "True";
            } else {
                form_data.buy_additive = "False";
            }

            var cur_item = new Item(form_data);
            if(this.validate_item(cur_item)) {
                items.push(cur_item);
            }
            e.preventDefault();
        }
    });

    var items = new Items([{
        item_id: 'item_id',
        buy_buyout: 'buy_buyout',
        buy_amount: 'buy_amount',
        buy_additive: 'True',

        sell_min_buyout: 'sell_min_buyout',
        sell_max_buyout: 'sell_max_buyout',
        sell_run_time: 'sell_run_time',
        sell_stack_size: 'sell_stack_size',
        sell_ignore_stacks_below: 'sell_ignore_stacks_below',
        sell_amount: 'sell_amount',
        sell_bid_percent: 'sell_bid_percent',
        sell_undercut_percent: 'sell_undercut_percent'
    }]);
    var MyApp = new Backbone.Marionette.Application();
    MyApp.addRegions({
      item_output: "#item_output_anchor",
      item_list: "#item_list_anchor",
      item_add_form: '#item_add_form_anchor'
    });

    MyApp.addInitializer(function(options){
      var itemsView = new ItemsView({
        collection: options.items
      });
      MyApp.item_list.show(itemsView);

      var createView = new CreateItemView();
      MyApp.item_add_form.show(createView);

      var outputView = new ItemOutputView();
      MyApp.item_output.show(outputView);
    });

    MyApp.start({items: items});
});

/*
var base_template_info;
    $.ajax({
        url: 'static/base_template.js',
        method: 'GET',
        contentType: 'text',
        mimeType: 'text/plain; charset=x-user-defined',
        success: function (data) {
            base_template_info = data;
        }
    });

//*/
<commit_msg>Removed unused class.<commit_after>function serialize_object(form_selector) {
    var formdata = $(form_selector).serializeArray();
    var data = {};
    _.each(formdata, function(element){
    // Return all of the values of the object's properties.
      var value = _.values(element);
    // name : value
      data[value[0]] = value[1];
    });
    return data;
}
function validate_item(json) {
    return _.every(_.values(json));
}

$(function() {
    var Item = Backbone.Model.extend({
        idAttribute: '_id',
        urlRoot: "",
        schema: {
            item_id: 'Text',
            buy_buyout: 'Text',
            buy_amount: 'Text',
            buy_additive: 'Text',

            sell_min_buyout: 'Text',
            sell_max_buyout: 'Text',
            sell_run_time: 'Text',
            sell_stack_size: 'Text',
            sell_ignore_stacks_below: 'Text',
            sell_amount: 'Text',
            sell_bid_percent: 'Text',
            sell_undercut_percent: 'Text'
        }
    });
    var Items = Backbone.Collection.extend({
        model: Item,
        url: ""
    });
    var ItemInfoView = Backbone.Marionette.ItemView.extend({
        initialize: function() {
            this.listenTo(this.model, 'destroy', this.remove);
        },
        template: "#item_info_template",
        tagName: "div",
        events: {
            'click button#btn_delete': 'delete_item',
        },
        delete_item: function(e) {
            this.model.destroy();
        }
    });
    var ItemsView = Backbone.Marionette.CompositeView.extend({
        tagName: "div",
        id: 'item_accordion',
        className: 'panel-group',
        attributes: {
            'role': 'tablist',
            'aria-multiselectable': 'true'
        },
        childView: ItemInfoView,
        template: "#item_data_template",
    });

    var ItemOutputView = Backbone.Marionette.ItemView.extend({
        initialize: function() {},
        template: "#item_output_template",
        tagName: "div",
        events: {}
    });

    var CreateItemView = Backbone.Marionette.ItemView.extend({
        initialize: function(starting_items) {
            this.currency_regex = /(\d+[Gg])?(\d{1,2}[Ss])?(\d{1,2}[Cc])?/;
            var validate_keys = _.keys(new Item().schema);
            // don't validate boolean field
            this.validate_keys = _.filter(validate_keys, function(k) {return k!=='buy_additive';});
        },
        template: "#item_add_template",
        tagName: "div",
        events: {
            'click button#add_item_submit': 'add_item'
        },
        field_is_not_blank: function(attributes, field) {
            return (attributes[field] && attributes[field].length > 0);
        },
        show_failed_validation: function(field_id) {
            $('div#'+field_id).addClass('has-error');
        },
        validate_item: function(item) {
            // for each field, check that the attributes value isn't blank
            //var greediest_match = item.attributes.buy_buyout.match(this.currency_regex);
            //console.log(greediest_match[0]);

            // clear prior validation
            _.each(this.validate_keys, function(key) {$('div#'+key).removeClass('has-error');});

            var not_blank = _.partial(this.field_is_not_blank, item.attributes, _);
            var failed_fields = _.reject(this.validate_keys, not_blank);
            _.each(failed_fields, this.show_failed_validation);

            return failed_fields.length === 0;
        },
        add_item: function(e) {
            var form_data = serialize_object('form#item_add_form');

            if(form_data.buy_additive === 'on') {
                form_data.buy_additive = "True";
            } else {
                form_data.buy_additive = "False";
            }

            var cur_item = new Item(form_data);
            if(this.validate_item(cur_item)) {
                items.push(cur_item);
            }
            e.preventDefault();
        }
    });

    var items = new Items([{
        item_id: 'item_id',
        buy_buyout: 'buy_buyout',
        buy_amount: 'buy_amount',
        buy_additive: 'True',

        sell_min_buyout: 'sell_min_buyout',
        sell_max_buyout: 'sell_max_buyout',
        sell_run_time: 'sell_run_time',
        sell_stack_size: 'sell_stack_size',
        sell_ignore_stacks_below: 'sell_ignore_stacks_below',
        sell_amount: 'sell_amount',
        sell_bid_percent: 'sell_bid_percent',
        sell_undercut_percent: 'sell_undercut_percent'
    }]);
    var MyApp = new Backbone.Marionette.Application();
    MyApp.addRegions({
      item_output: "#item_output_anchor",
      item_list: "#item_list_anchor",
      item_add_form: '#item_add_form_anchor'
    });

    MyApp.addInitializer(function(options){
      var itemsView = new ItemsView({
        collection: options.items
      });
      MyApp.item_list.show(itemsView);

      var createView = new CreateItemView();
      MyApp.item_add_form.show(createView);

      var outputView = new ItemOutputView();
      MyApp.item_output.show(outputView);
    });

    MyApp.start({items: items});
});

/*
var base_template_info;
    $.ajax({
        url: 'static/base_template.js',
        method: 'GET',
        contentType: 'text',
        mimeType: 'text/plain; charset=x-user-defined',
        success: function (data) {
            base_template_info = data;
        }
    });

//*/
<|endoftext|>


<commit_before>/**
 * Object with helper methods for jsonDom handling
 */

export const getComponentByKey = (key, json) => {
    if (!json) return
    const keyParts = key.split('.')

    // as the key always starts with 0 remove the first value
    keyParts.shift()

    if (json.constructor !== Array) {
        keyParts.shift()
    }
    let cur = json
    for (let i = 0; i < keyParts.length; i++) {
        if (i > 0 && keyParts[i - 1] === '$loop') {
            continue
        }
        const part = keyParts[i]
        if (cur.constructor === Object && cur.c) cur = cur.c
        if (cur.constructor === Object && !isNaN(part)) cur = [cur]

        if (!cur[part]) {
            console.warn('Something is wrong with the key: ' + key, part)
            return null
        }
        cur = cur[part]
    }
    return cur
}

export const addComponent = ({key, json, index, component}) => {
    const subJson = getComponentByKey(key, json)
    if (subJson) {
        let c = subJson['c']
        if (!c) {
            c = []
        } else if (c.constructor === Object) {
            c = [c]
        } else if (c.constructor === String) {
            c = [{c}]
        }
        if (!component) {
            component = {'c': 'new component'}
        }
        if (isNaN(index)) {
            index = c.length
        }

        c.splice(index, 0, component)
        subJson.c = c
    }
    return subJson
}

export const getParentKey = (key) => {
    return key.substring(0, key.lastIndexOf('.'))
}

export const removeComponent = (key, json) => {
    const parentKey = getParentKey(key)
    const parent = getComponentByKey(parentKey, json),
        child = getComponentByKey(key, json)
    if (parent && child) {
        let c = parent['c']
        if (!c) {
            return false
        } else if (c.constructor !== Array) {
            c = ''
        } else {
            c.splice(c.indexOf(child), 1)
        }

        if (c.constructor === Array && c.length === 0) {
            c = ''
        }

        parent.c = c
        return true
    }

    return false
}

export const isTargetAbove = (sourceKey, targetKey) => {
    let isTargetAbove = true
    const sourceKeyParts = sourceKey.split('.')
    const targetKeyParts = targetKey.split('.')
    for (let i = 0; i < sourceKeyParts.length; i++) {
        if (i > targetKeyParts.length) {
            break
        }
        if (sourceKeyParts[i] === targetKeyParts[i]) {
            continue
        }
        const posSource = parseInt(sourceKeyParts[i]),
            posTarget = parseInt(targetKeyParts[i])

        if (posTarget > posSource) {
            isTargetAbove = false
            break
        }
    }
    return isTargetAbove
}

export const classNameByPath = (path, extraClassName) => {
    let className = 'JsonDom'
    if (path) {

        const p = path.split('/')
        let classPath = ''
        for (let i = 0; i < p.length; i++) {
            if (classPath) classPath += '-'
            classPath += p[i]
            className += ' Cms-' + classPath
        }
    }
    if (extraClassName)
        className += ' ' + extraClassName
    return className
}
<commit_msg>Small improvements<commit_after>/**
 * Object with helper methods for jsonDom handling
 */

export const getComponentByKey = (key, json) => {
    if (!json) return
    const keyParts = key.split('.')

    // as the key always starts with 0 remove the first value
    keyParts.shift()

    if (json.constructor !== Array) {
        keyParts.shift()
    }
    let cur = json
    for (let i = 0; i < keyParts.length; i++) {
        if (i > 0 && keyParts[i - 1] === '$loop') {
            continue
        }
        const part = keyParts[i]
        if (cur.constructor === Object && cur.c) cur = cur.c
        if (cur.constructor === Object && !isNaN(part)) cur = [cur]

        if (!cur[part]) {
            console.warn('Something is wrong with the key: ' + key, part)
            return null
        }
        cur = cur[part]
    }
    return cur
}

export const addComponent = ({key, json, index, component}) => {
    const subJson = getComponentByKey(key, json)
    if (subJson) {
        let c = subJson['c']
        if (!c) {
            c = []
        } else if (c.constructor === Object) {
            c = [c]
        } else if (c.constructor === String) {
            c = [{c}]
        }
        if (!component) {
            component = {'c': 'new component'}
        }
        if (isNaN(index)) {
            index = c.length
        }

        c.splice(index, 0, component)
        subJson.c = c
    }
    return subJson
}

export const getParentKey = (key) => {
    return key.substring(0, key.lastIndexOf('.'))
}

export const removeComponent = (key, json) => {
    const parentKey = getParentKey(key)
    const parent = getComponentByKey(parentKey, json),
        child = getComponentByKey(key, json)
    if (parent && child) {
        let c = parent['c']
        if (!c) {
            return false
        } else if (c.constructor !== Array) {
            c = ''
        } else {
            c.splice(c.indexOf(child), 1)
        }

        if (c.constructor === Array && c.length === 0) {
            c = ''
        }

        parent.c = c
        return true
    }

    return false
}

export const isTargetAbove = (sourceKey, targetKey) => {
    let isTargetAbove = true
    const sourceKeyParts = sourceKey.split('.')
    const targetKeyParts = targetKey.split('.')
    for (let i = 0; i < sourceKeyParts.length; i++) {
        if (i > targetKeyParts.length) {
            break
        }
        if (sourceKeyParts[i] === targetKeyParts[i]) {
            continue
        }
        const posSource = parseInt(sourceKeyParts[i]),
            posTarget = parseInt(targetKeyParts[i])

        if (posTarget > posSource) {
            isTargetAbove = false
            break
        }
    }
    return isTargetAbove
}

export const classNameByPath = (path, extraClassName) => {
    let className = 'JsonDom'
    if (path != undefined) {

        const p = path.split('/')
        let classPath = ''
        for (let i = 0; i < p.length; i++) {
            if (classPath) classPath += '-'
            classPath += p[i]
            className += ' Cms-' + classPath
        }
    }
    if (extraClassName)
        className += ' ' + extraClassName
    return className
}
<|endoftext|>


<commit_before>import { makeStyles } from '@material-ui/core/styles';
import Box from '@material-ui/core/Box';
import cx from 'clsx';

const useHeaderStyles = makeStyles({
  section: {
    color: '#615870',
    display: 'flex',
    alignItems: 'center',
    fontSize: 13,
    gap: '18px',

    '&::before, &::after': {
      content: "''",
      borderTop: '1px solid rgba(97, 88, 112, 0.5)',
      flex: 1,
    },
  },
});

function Header({ className, ...props }) {
  const classes = useHeaderStyles();
  return
;
}

const useStyles = makeStyles({
  root: {
    maxWidth: 1168 + 32 * 2,
    padding: '0 32px',
    margin: '0 auto',
  },
});

function SectionSponsor() {
  const classes = useStyles();

  return (
    <>

        合作夥伴
        <Box display="flex">
          <Box flex={1} marginRight={['12px', '96px']}>
            贊助夥伴
          </Box>
          <Box flex={1}>
            天使捐助
          </Box>
        </Box>

    </>
  );
}

export default SectionSponsor;
<commit_msg>[ReportPage] apply ProgressionWrapper to SectionSponsor<commit_after>import { makeStyles } from '@material-ui/core/styles';
import Box from '@material-ui/core/Box';
import ProgressionWrapper from './ProgressionWrapper';
import cx from 'clsx';

const useHeaderStyles = makeStyles({
  root: {
    color: '#615870',
    display: 'flex',
    alignItems: 'center',
    fontSize: 13,
    gap: '18px',

    '&::before, &::after': {
      content: "''",
      borderTop: '1px solid rgba(97, 88, 112, 0.5)',
      flex: 1,
    },
  },
});

function Header({ className, ...props }) {
  const classes = useHeaderStyles();
  return
;
}

const useStyles = makeStyles(theme => ({
  section: {
    maxWidth: 1168 + 32 * 2,
    padding: '0 32px',
    margin: '0 auto',
  },

  wrapper: {
    zIndex: 1,
    position: 'relative', // for stacking context
    background: theme.palette.background.default,
  },
}));

function SectionSponsor() {
  const classes = useStyles();

  return (
    <ProgressionWrapper className={classes.wrapper}>

        合作夥伴
        <Box display="flex">
          <Box flex={1} marginRight={['12px', '96px']}>
            贊助夥伴
          </Box>
          <Box flex={1}>
            天使捐助
          </Box>
        </Box>

    </ProgressionWrapper>
  );
}

export default SectionSponsor;
<|endoftext|>


<commit_before>import React from 'react';
import { Router } from 'routes';
import { StickyContainer, Sticky } from 'react-sticky';
import PropTypes from 'prop-types';

// Utils
import { substitution } from 'utils/utils';

// Components
import Aside from 'components/ui/Aside';
import DatasetsForm from 'components/datasets/form/DatasetsForm';
import MetadataForm from 'components/admin/metadata/form/MetadataForm';
import TagsForm from 'components/admin/tags/TagsForm';
import VocabulariesAssociationForm from 'components/admin/vocabularies/association/VocabulariesAssociationForm';
import WidgetIndex from 'components/admin/widget/pages/index';
import LayersIndex from 'components/admin/layers/pages/index';

// Constants
const DATASET_SUBTABS = [{
  label: 'Edit dataset',
  value: 'edit',
  route: 'admin_data_detail',
  params: { tab: 'datasets', id: '{{id}}', subtab: 'edit' }
}, {
  label: 'Metadata',
  value: 'metadata',
  route: 'admin_data_detail',
  params: { tab: 'datasets', id: '{{id}}', subtab: 'metadata' }
}, {
  label: 'Tags',
  value: 'vocabularies',
  route: 'admin_data_detail',
  params: { tab: 'datasets', id: '{{id}}', subtab: 'vocabularies' }
}, {
  label: 'Widgets',
  value: 'widgets',
  route: 'admin_data_detail',
  params: { tab: 'datasets', id: '{{id}}', subtab: 'widgets' }
}, {
  label: 'Layers',
  value: 'layers',
  route: 'admin_data_detail',
  params: { tab: 'datasets', id: '{{id}}', subtab: 'layers' }
}];

class DatasetsShow extends React.Component {
  /**
   * HELPERS
   * - parseTabs
  */
  parseTabs(obj) {
    const { id } = this.props;
    return JSON.parse(substitution(JSON.stringify(obj), [{ key: 'id', value: id }]));
  }

  render() {
    const { id, user } = this.props;
    const subtab = this.props.subtab || 'edit';

    return (

        <StickyContainer>

              <Sticky>
                {
                  ({ style }) => (

                  )
                }
              </Sticky>

              {subtab === 'edit' &&
                <DatasetsForm
                  application={[process.env.APPLICATIONS]}
                  authorization={user.token}
                  dataset={id}
                  onSubmit={() => Router.pushRoute('admin_data', { tab: 'datasets' })}
                />
              }

              {subtab === 'metadata' &&
                <MetadataForm
                  application={process.env.APPLICATIONS}
                  authorization={user.token}
                  dataset={id}
                  onSubmit={() => Router.pushRoute('admin_data', { tab: 'datasets', id })}
                />
              }

              {subtab === 'vocabularies' &&

                  <VocabulariesAssociationForm
                    application={process.env.APPLICATIONS}
                    authorization={user.token}
                    dataset={id}
                    language="en"
                  />
                  <TagsForm
                    dataset={id}
                    user={user}
                  />

              }

              {subtab === 'widgets' &&
                <WidgetIndex user={user} dataset={id} embed />
              }

              {subtab === 'layers' &&
                <LayersIndex user={user} dataset={id} />
              }

        </StickyContainer>

    );
  }
}

DatasetsShow.propTypes = {
  id: PropTypes.string,
  subtab: PropTypes.string,

  // Store
  user: PropTypes.object.isRequired
};

export default DatasetsShow;
<commit_msg>remove VocabulariesAssociationFrom from tags view<commit_after>import React from 'react';
import { Router } from 'routes';
import { StickyContainer, Sticky } from 'react-sticky';
import PropTypes from 'prop-types';

// Utils
import { substitution } from 'utils/utils';

// Components
import Aside from 'components/ui/Aside';
import DatasetsForm from 'components/datasets/form/DatasetsForm';
import MetadataForm from 'components/admin/metadata/form/MetadataForm';
import TagsForm from 'components/admin/tags/TagsForm';
import WidgetIndex from 'components/admin/widget/pages/index';
import LayersIndex from 'components/admin/layers/pages/index';

// Constants
const DATASET_SUBTABS = [{
  label: 'Edit dataset',
  value: 'edit',
  route: 'admin_data_detail',
  params: { tab: 'datasets', id: '{{id}}', subtab: 'edit' }
}, {
  label: 'Metadata',
  value: 'metadata',
  route: 'admin_data_detail',
  params: { tab: 'datasets', id: '{{id}}', subtab: 'metadata' }
}, {
  label: 'Tags',
  value: 'vocabularies',
  route: 'admin_data_detail',
  params: { tab: 'datasets', id: '{{id}}', subtab: 'vocabularies' }
}, {
  label: 'Widgets',
  value: 'widgets',
  route: 'admin_data_detail',
  params: { tab: 'datasets', id: '{{id}}', subtab: 'widgets' }
}, {
  label: 'Layers',
  value: 'layers',
  route: 'admin_data_detail',
  params: { tab: 'datasets', id: '{{id}}', subtab: 'layers' }
}];

class DatasetsShow extends React.Component {
  /**
   * HELPERS
   * - parseTabs
  */
  parseTabs(obj) {
    const { id } = this.props;
    return JSON.parse(substitution(JSON.stringify(obj), [{ key: 'id', value: id }]));
  }

  render() {
    const { id, user } = this.props;
    const subtab = this.props.subtab || 'edit';

    return (

        <StickyContainer>

              <Sticky>
                {
                  ({ style }) => (

                  )
                }
              </Sticky>

              {subtab === 'edit' &&
                <DatasetsForm
                  application={[process.env.APPLICATIONS]}
                  authorization={user.token}
                  dataset={id}
                  onSubmit={() => Router.pushRoute('admin_data', { tab: 'datasets' })}
                />
              }

              {subtab === 'metadata' &&
                <MetadataForm
                  application={process.env.APPLICATIONS}
                  authorization={user.token}
                  dataset={id}
                  onSubmit={() => Router.pushRoute('admin_data', { tab: 'datasets', id })}
                />
              }

              {subtab === 'vocabularies' &&

                  <TagsForm
                    dataset={id}
                    user={user}
                  />

              }

              {subtab === 'widgets' &&
                <WidgetIndex user={user} dataset={id} embed />
              }

              {subtab === 'layers' &&
                <LayersIndex user={user} dataset={id} />
              }

        </StickyContainer>

    );
  }
}

DatasetsShow.propTypes = {
  id: PropTypes.string,
  subtab: PropTypes.string,

  // Store
  user: PropTypes.object.isRequired
};

export default DatasetsShow;
<|endoftext|>


<commit_before>
var ast = require('../parser/ast');

var counter = 0;

var constructorNames = [];

var escapeNonAscii = function (name) {
    var newName = '';
    for (var i = 0; i < name.length; ++i) {
        var char = name.charCodeAt(i);

        if ((char >= 65 && char <= 90) || (char >= 97 && char <= 122))  {
            newName += String.fromCharCode(char);
        } else {
            newName += '_' + char;
        }
    }
    return newName;
};

var translateConstructorVariables = function (variables) {
    return ast.join(ast.map(variables, translateExpression));
};

var translateMatch = function (match) {
    var cases = [];

    for (var i = 2; i < ast.size(match); i += 2) {
        var _constructor = ast.child(match, i);
        if (ast.isList(_constructor)) {
            cases.push(escapeNonAscii(ast.value(ast.child(_constructor, 0))) + ':function(' + translateConstructorVariables(ast.slice(_constructor, 1)) + '){return ' + translateExpression(ast.child(match, i + 1)) + ';}');
        } else {
            cases.push(escapeNonAscii(ast.value(_constructor)) + ':function(){return ' + translateExpression(ast.child(match, i + 1)) + ';}');
        }
    }

    return 'match(' + translateExpression(ast.child(match, 1)) + ',{' + cases.join(',') + '})';
};

var translateExpression = function (expression) {
    if (ast.isList(expression)) {
        if (ast.value(ast.child(expression, 0)) === 'match') {
            return translateMatch(expression);
        } else if (ast.value(ast.child(expression, 0)) === '+'
                || ast.value(ast.child(expression, 0)) === '-'
                || ast.value(ast.child(expression, 0)) === '*'
                || ast.value(ast.child(expression, 0)) === '/'
                || ast.value(ast.child(expression, 0)) === '%') {
            return '(' + translateExpression(ast.child(expression, 1)) + ast.value(ast.child(expression, 0)) + translateExpression(ast.child(expression, 2)) + '|0)';
        } else if (ast.value(ast.child(expression, 0)) === 'int32-compare') {
            return '(' + translateExpression(ast.child(expression, 1)) + '<' + translateExpression(ast.child(expression, 3)) + '?' + translateExpression(ast.child(expression, 2)) + ':' + translateExpression(ast.child(expression, 4)) + ')';
        } else {
            return translateExpression(ast.child(expression, 0)) + '(' + ast.join(ast.map(ast.slice(expression, 1), translateExpression), ',') + ')';
        }
    } else {
        var name = ast.value(expression);
        if (!isNaN(parseFloat(name)) && isFinite(name)) {
            return (parseInt(name, 10) | 0).toString();
        } else {
            return escapeNonAscii(name);
        }
    }
};

var translateDefinition = function (definition, exportStatement) {
    var name = ast.value(ast.child(definition, 1));

    var expression = translateExpression(ast.child(definition, 3));

    var parameters = ast.child(definition, 2);
    var parameterString = ast.join(ast.map(parameters, translateExpression), ',');

    var moduleExport = '';
    if (exportStatement) {
        moduleExport = 'module.exports.' + name + '=' + escapeNonAscii(name) + ';'
    }

    return 'function ' + escapeNonAscii(name) + '(' + parameterString + '){return ' + expression + ';}' + moduleExport;
};

var translateDataConstructor = function (expression) {
    if (ast.isList(expression)) {
        var name = escapeNonAscii(ast.value(ast.child(expression, 0)));
        return 'var ' + name + '=function(){return {type:"' + name + '",values:arguments}};';
    } else {
        var name = escapeNonAscii(ast.value(expression));
        return 'var ' + name + '={};' + name + '.type="' + name + '";';
    }
};

var translateData = function (definition) {
    return ast.join(ast.map(ast.slice(definition, 2), translateDataConstructor), '\n');
};

var translateModuleEntry = function (definition) {
    if (ast.isList(definition)) {
        if (ast.value(ast.child(definition, 0)) === 'def') {
            return translateDefinition(definition, false);
        } else if (ast.value(ast.child(definition, 0)) === 'export') {
            return translateDefinition(definition, true);
        } else {
            return translateData(definition);
        }
    } else {
        return '';
    }
};

var translateModule = function (definitions) {
    return ast.join(ast.map(definitions, translateModuleEntry), '\n');
};

var runtime = 'function match(expression, cases) {return cases[expression.type].apply(null,expression.values);}\n';

module.exports.translate = function (expression) {
    return [
        {filename: 'src/source.js', contents: runtime + translateModule(expression)}
    ];
};
<commit_msg>Do not escape numbers in javascript translator<commit_after>
var ast = require('../parser/ast');

var counter = 0;

var constructorNames = [];

var escapeNonAscii = function (name) {
    var newName = '';
    for (var i = 0; i < name.length; ++i) {
        var char = name.charCodeAt(i);

        if ((char >= 65 && char <= 90) || (char >= 97 && char <= 122) || (char >= 48 && char <= 57))  {
            newName += String.fromCharCode(char);
        } else {
            newName += '_' + char;
        }
    }
    return newName;
};

var translateConstructorVariables = function (variables) {
    return ast.join(ast.map(variables, translateExpression));
};

var translateMatch = function (match) {
    var cases = [];

    for (var i = 2; i < ast.size(match); i += 2) {
        var _constructor = ast.child(match, i);
        if (ast.isList(_constructor)) {
            cases.push(escapeNonAscii(ast.value(ast.child(_constructor, 0))) + ':function(' + translateConstructorVariables(ast.slice(_constructor, 1)) + '){return ' + translateExpression(ast.child(match, i + 1)) + ';}');
        } else {
            cases.push(escapeNonAscii(ast.value(_constructor)) + ':function(){return ' + translateExpression(ast.child(match, i + 1)) + ';}');
        }
    }

    return 'match(' + translateExpression(ast.child(match, 1)) + ',{' + cases.join(',') + '})';
};

var translateExpression = function (expression) {
    if (ast.isList(expression)) {
        if (ast.value(ast.child(expression, 0)) === 'match') {
            return translateMatch(expression);
        } else if (ast.value(ast.child(expression, 0)) === '+'
                || ast.value(ast.child(expression, 0)) === '-'
                || ast.value(ast.child(expression, 0)) === '*'
                || ast.value(ast.child(expression, 0)) === '/'
                || ast.value(ast.child(expression, 0)) === '%') {
            return '(' + translateExpression(ast.child(expression, 1)) + ast.value(ast.child(expression, 0)) + translateExpression(ast.child(expression, 2)) + '|0)';
        } else if (ast.value(ast.child(expression, 0)) === 'int32-compare') {
            return '(' + translateExpression(ast.child(expression, 1)) + '<' + translateExpression(ast.child(expression, 3)) + '?' + translateExpression(ast.child(expression, 2)) + ':' + translateExpression(ast.child(expression, 4)) + ')';
        } else {
            return translateExpression(ast.child(expression, 0)) + '(' + ast.join(ast.map(ast.slice(expression, 1), translateExpression), ',') + ')';
        }
    } else {
        var name = ast.value(expression);
        if (!isNaN(parseFloat(name)) && isFinite(name)) {
            return (parseInt(name, 10) | 0).toString();
        } else {
            return escapeNonAscii(name);
        }
    }
};

var translateDefinition = function (definition, exportStatement) {
    var name = ast.value(ast.child(definition, 1));

    var expression = translateExpression(ast.child(definition, 3));

    var parameters = ast.child(definition, 2);
    var parameterString = ast.join(ast.map(parameters, translateExpression), ',');

    var moduleExport = '';
    if (exportStatement) {
        moduleExport = 'module.exports.' + name + '=' + escapeNonAscii(name) + ';'
    }

    return 'function ' + escapeNonAscii(name) + '(' + parameterString + '){return ' + expression + ';}' + moduleExport;
};

var translateDataConstructor = function (expression) {
    if (ast.isList(expression)) {
        var name = escapeNonAscii(ast.value(ast.child(expression, 0)));
        return 'var ' + name + '=function(){return {type:"' + name + '",values:arguments}};';
    } else {
        var name = escapeNonAscii(ast.value(expression));
        return 'var ' + name + '={};' + name + '.type="' + name + '";';
    }
};

var translateData = function (definition) {
    return ast.join(ast.map(ast.slice(definition, 2), translateDataConstructor), '\n');
};

var translateModuleEntry = function (definition) {
    if (ast.isList(definition)) {
        if (ast.value(ast.child(definition, 0)) === 'def') {
            return translateDefinition(definition, false);
        } else if (ast.value(ast.child(definition, 0)) === 'export') {
            return translateDefinition(definition, true);
        } else {
            return translateData(definition);
        }
    } else {
        return '';
    }
};

var translateModule = function (definitions) {
    return ast.join(ast.map(definitions, translateModuleEntry), '\n');
};

var runtime = 'function match(expression, cases) {return cases[expression.type].apply(null,expression.values);}\n';

module.exports.translate = function (expression) {
    return [
        {filename: 'src/source.js', contents: runtime + translateModule(expression)}
    ];
};
<|endoftext|>


<commit_before>window.Boxoffice = window.Boxoffice || {};

window.Boxoffice.Order = {
  config: {
    baseURL: window.location.origin,
    order: {
      method: 'GET',
      urlFor: function() {
        return window.location.href;
      }
    },
    assign: {
      method: 'POST',
      urlFor: function(access_token) {
        return Boxoffice.Order.config.baseURL + '/participant/' + access_token + '/assign';
      }
    }
  },
  init: function() {
    $.ajax({
      url: Boxoffice.Order.config.order.urlFor(),
      type: Boxoffice.Order.config.order.method,
      timeout: 5000,
      retries: 5,
      dataType: 'json',
      retryInterval: 5000,
      success: function(data) {
        window.Boxoffice.Order.view(data);
      },
      error: function(response) {
        var ajaxLoad = this;
        ajaxLoad.retries -= 1;
        var errorMsg;
        if(response.readyState === 4) {
          //Add error message
        }
        else if(response.readyState === 0) {
          if(ajaxLoad.retries < 0) {
            errorMsg = "Unable to connect. Please write to us at support@hasgeek.com with your order number";

          } else {
            setTimeout(function() {
              $.ajax(ajaxLoad);
            }, ajaxLoad.retryInterval);
          }
        }
      }
    });
  },
  view: function(data) {
    var order = this;
    order.ractive = new Ractive({
        el: '#boxoffice-order',
        template: '#boxoffice-ticket-template',
        data: {
          order_id: data.order_id,
          access_token: data.access_token,
          eventName: data.item_collection_name,
          line_items: data.line_items,
          buyer_name: data.buyer_name,
          buyer_email: data.buyer_email,
          buyer_phone: data.buyer_phone
        },
        scrollTop: function(line_item_seq){
          //Scroll to the corresponding line_item.
          var domElem =  order.ractive.nodes[ 'item-' + line_item_seq ];
          $('html,body').animate({ scrollTop: $(domElem).offset().top }, '300');
        },
        viewTicket: function(event, line_item, line_item_seq) {
          event.original.preventDefault();
          order.ractive.set(line_item + '.toAssign', false);
          order.ractive.scrollTop(line_item_seq);
        },
        inputFieldEdit: function(event, line_item) {
          if(event.node.value) {
            event.node.classList.add('filled');
          }
          else {
            event.node.classList.remove('filled');
          }
        },
        assign: function(event, line_item) {
          event.original.preventDefault();

          var assignment = order.ractive.get(line_item +'.assignment');

          if(assignment === 'self') {
            order.ractive.set(line_item + '.assignee.fullname', order.ractive.get('buyer_name'));
            order.ractive.set(line_item + '.assignee.email', order.ractive.get('buyer_email'));
            order.ractive.set(line_item + '.assignee.phone', order.ractive.get('buyer_phone'));
          }
          order.ractive.set(line_item + '.toAssign', true);
        },
        addAttendeDetails: function(event, line_item, line_item_seq, line_item_id) {

          var validationConfig = [{
              name: 'name',
              rules: 'required'
            },
            {
              name: 'email',
              rules: 'required|valid_email'
            },
            {
              name: 'phone',
              rules: 'required|max_length[16]'
            }
          ];

          var attendeeForm = 'attendee-form-' + line_item_seq;

          var formValidator = new FormValidator(attendeeForm, validationConfig, function(errors, event) {
            event.preventDefault();
            if (errors.length > 0) {
              order.ractive.set(line_item + '.errorMsg', errors[0].message);
            } else {
              order.ractive.set(line_item + '.errorMsg', '');
              order.ractive.set(line_item + '.assigningTicket', true);
              order.ractive.sendAttendeDetails(line_item, line_item_seq, line_item_id);
            }
          });
        },
        sendAttendeDetails: function(line_item, line_item_seq, line_item_id) {
          var attendeeForm = 'attendee-details-' + line_item_seq
          var formElements = $('#'+ attendeeForm).serializeArray();
          var attendeeDetails ={};
          for (var formIndex=0; formIndex < formElements.length; formIndex++) {
            if(formElements[formIndex].value) {
              attendeeDetails[formElements[formIndex].name] = formElements[formIndex].value;
            }
          }
          attendeeDetails['email'] = order.ractive.get(line_item + '.assignee.email');
          attendeeDetails['fullname'] = order.ractive.get(line_item + '.assignee.fullname');
          $.ajax({
            url: Boxoffice.Order.config.assign.urlFor(order.ractive.get('access_token')),
            type: Boxoffice.Order.config.assign.method,
            contentType: 'application/json',
            data: JSON.stringify({
              attendee: attendeeDetails,
              line_item_id: line_item_id
            }),
            timeout: 5000,
            retries: 5,
            retryInterval: 5000,
            success: function(data) {
              order.ractive.set(line_item + '.assigningTicket', false);
              order.ractive.set(line_item + '.toAssign', false);
              order.ractive.set(line_item + '.isTicketAssigned', true);
              order.ractive.scrollTop(line_item_seq);
            },
            error: function(response) {
              var ajaxLoad = this;
              ajaxLoad.retries -= 1;
              if (response.readyState === 4) {
                order.ractive.set(line_item + '.errorMsg', 'Server error');
                order.ractive.set(line_item + '.assigningTicket', false);
              } else if (response.readyState === 0) {
                if(ajaxLoad.retries < 0) {
                  order.ractive.set(line_item + '.errorMsg', "Unable to connect. Please try again later.")
                  order.ractive.set(line_item + '.assigningTicket', false);
                } else {
                  setTimeout(function() {
                    $.ajax(ajaxLoad);
                  }, ajaxLoad.retryInterval);
                }
              }
            }
          });
        }
    });
  }
};

$(function() {
  Ractive.DEBUG = false;

  window.Boxoffice.Order.init();

});<commit_msg>Increase ajax timeout and retry interval in case of error.<commit_after>window.Boxoffice = window.Boxoffice || {};

window.Boxoffice.Order = {
  config: {
    baseURL: window.location.origin,
    order: {
      method: 'GET',
      urlFor: function() {
        return window.location.href;
      }
    },
    assign: {
      method: 'POST',
      urlFor: function(access_token) {
        return Boxoffice.Order.config.baseURL + '/participant/' + access_token + '/assign';
      }
    }
  },
  init: function() {
    $.ajax({
      url: Boxoffice.Order.config.order.urlFor(),
      type: Boxoffice.Order.config.order.method,
      timeout: 5000,
      retries: 5,
      dataType: 'json',
      retryInterval: 5000,
      success: function(data) {
        window.Boxoffice.Order.view(data);
      },
      error: function(response) {
        var ajaxLoad = this;
        ajaxLoad.retries -= 1;
        var errorMsg;
        if(response.readyState === 4) {
          //Add error message
        }
        else if(response.readyState === 0) {
          if(ajaxLoad.retries < 0) {
            errorMsg = "Unable to connect. Please write to us at support@hasgeek.com with your order number";

          } else {
            setTimeout(function() {
              $.ajax(ajaxLoad);
            }, ajaxLoad.retryInterval);
          }
        }
      }
    });
  },
  view: function(data) {
    var order = this;
    order.ractive = new Ractive({
        el: '#boxoffice-order',
        template: '#boxoffice-ticket-template',
        data: {
          order_id: data.order_id,
          access_token: data.access_token,
          eventName: data.item_collection_name,
          line_items: data.line_items,
          buyer_name: data.buyer_name,
          buyer_email: data.buyer_email,
          buyer_phone: data.buyer_phone
        },
        scrollTop: function(line_item_seq){
          //Scroll to the corresponding line_item.
          var domElem =  order.ractive.nodes[ 'item-' + line_item_seq ];
          $('html,body').animate({ scrollTop: $(domElem).offset().top }, '300');
        },
        viewTicket: function(event, line_item, line_item_seq) {
          event.original.preventDefault();
          order.ractive.set(line_item + '.toAssign', false);
          order.ractive.scrollTop(line_item_seq);
        },
        inputFieldEdit: function(event, line_item) {
          if(event.node.value) {
            event.node.classList.add('filled');
          }
          else {
            event.node.classList.remove('filled');
          }
        },
        assign: function(event, line_item) {
          event.original.preventDefault();

          var assignment = order.ractive.get(line_item +'.assignment');

          if(assignment === 'self') {
            order.ractive.set(line_item + '.assignee.fullname', order.ractive.get('buyer_name'));
            order.ractive.set(line_item + '.assignee.email', order.ractive.get('buyer_email'));
            order.ractive.set(line_item + '.assignee.phone', order.ractive.get('buyer_phone'));
          }
          order.ractive.set(line_item + '.toAssign', true);
        },
        addAttendeDetails: function(event, line_item, line_item_seq, line_item_id) {

          var validationConfig = [{
              name: 'name',
              rules: 'required'
            },
            {
              name: 'email',
              rules: 'required|valid_email'
            },
            {
              name: 'phone',
              rules: 'required|max_length[16]'
            }
          ];

          var attendeeForm = 'attendee-form-' + line_item_seq;

          var formValidator = new FormValidator(attendeeForm, validationConfig, function(errors, event) {
            event.preventDefault();
            if (errors.length > 0) {
              order.ractive.set(line_item + '.errorMsg', errors[0].message);
            } else {
              order.ractive.set(line_item + '.errorMsg', '');
              order.ractive.set(line_item + '.assigningTicket', true);
              order.ractive.sendAttendeDetails(line_item, line_item_seq, line_item_id);
            }
          });
        },
        sendAttendeDetails: function(line_item, line_item_seq, line_item_id) {
          var attendeeForm = 'attendee-details-' + line_item_seq
          var formElements = $('#'+ attendeeForm).serializeArray();
          var attendeeDetails ={};
          for (var formIndex=0; formIndex < formElements.length; formIndex++) {
            if(formElements[formIndex].value) {
              attendeeDetails[formElements[formIndex].name] = formElements[formIndex].value;
            }
          }
          attendeeDetails['email'] = order.ractive.get(line_item + '.assignee.email');
          attendeeDetails['fullname'] = order.ractive.get(line_item + '.assignee.fullname');
          $.ajax({
            url: Boxoffice.Order.config.assign.urlFor(order.ractive.get('access_token')),
            type: Boxoffice.Order.config.assign.method,
            contentType: 'application/json',
            data: JSON.stringify({
              attendee: attendeeDetails,
              line_item_id: line_item_id
            }),
            timeout: 30000,
            retries: 5,
            retryInterval: 30000,
            success: function(data) {
              order.ractive.set(line_item + '.assigningTicket', false);
              order.ractive.set(line_item + '.toAssign', false);
              order.ractive.set(line_item + '.isTicketAssigned', true);
              order.ractive.scrollTop(line_item_seq);
            },
            error: function(response) {
              var ajaxLoad = this;
              ajaxLoad.retries -= 1;
              if (response.readyState === 4) {
                order.ractive.set(line_item + '.errorMsg', 'Server error');
                order.ractive.set(line_item + '.assigningTicket', false);
              } else if (response.readyState === 0) {
                if(ajaxLoad.retries < 0) {
                  order.ractive.set(line_item + '.errorMsg', "Unable to connect. Please try again later.")
                  order.ractive.set(line_item + '.assigningTicket', false);
                } else {
                  setTimeout(function() {
                    $.ajax(ajaxLoad);
                  }, ajaxLoad.retryInterval);
                }
              }
            }
          });
        }
    });
  }
};

$(function() {
  Ractive.DEBUG = false;

  window.Boxoffice.Order.init();

});<|endoftext|>