<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * This is a third-party polyfill grabbed from:
 * https://github.com/github/fetch
 *
 * @providesModule fetch
 * @nolint
 */
/* eslint-disable */
'use strict';

var self = {};

/**
 * Copyright (c) 2014 GitHub, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @preserve-header
 */
(function() {
  'use strict';

  if (self.fetch) {
    return
  }

  function normalizeName(name) {
    if (typeof name !== 'string') {
      name = name.toString();
    }
    if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
      throw new TypeError('Invalid character in header field name')
    }
    return name.toLowerCase()
  }

  function normalizeValue(value) {
    if (typeof value !== 'string') {
      value = value.toString();
    }
    return value
  }

  function Headers(headers) {
    this.map = {}

    var self = this
    if (headers instanceof Headers) {
      headers.forEach(function(name, values) {
        values.forEach(function(value) {
          self.append(name, value)
        })
      })

    } else if (headers) {
      Object.getOwnPropertyNames(headers).forEach(function(name) {
        self.append(name, headers[name])
      })
    }
  }

  Headers.prototype.append = function(name, value) {
    name = normalizeName(name)
    value = normalizeValue(value)
    var list = this.map[name]
    if (!list) {
      list = []
      this.map[name] = list
    }
    list.push(value)
  }

  Headers.prototype['delete'] = function(name) {
    delete this.map[normalizeName(name)]
  }

  Headers.prototype.get = function(name) {
    var values = this.map[normalizeName(name)]
    return values ? values[0] : null
  }

  Headers.prototype.getAll = function(name) {
    return this.map[normalizeName(name)] || []
  }

  Headers.prototype.has = function(name) {
    return this.map.hasOwnProperty(normalizeName(name))
  }

  Headers.prototype.set = function(name, value) {
    this.map[normalizeName(name)] = [normalizeValue(value)]
  }

  // Instead of iterable for now.
  Headers.prototype.forEach = function(callback) {
    var self = this
    Object.getOwnPropertyNames(this.map).forEach(function(name) {
      callback(name, self.map[name])
    })
  }

  function consumed(body) {
    if (body.bodyUsed) {
      return Promise.reject(new TypeError('Already read'))
    }
    body.bodyUsed = true
  }

  function fileReaderReady(reader) {
    return new Promise(function(resolve, reject) {
      reader.onload = function() {
        resolve(reader.result)
      }
      reader.onerror = function() {
        reject(reader.error)
      }
    })
  }

  function readBlobAsArrayBuffer(blob) {
    var reader = new FileReader()
    reader.readAsArrayBuffer(blob)
    return fileReaderReady(reader)
  }

  function readBlobAsText(blob) {
    var reader = new FileReader()
    reader.readAsText(blob)
    return fileReaderReady(reader)
  }

  var support = {
    blob: 'FileReader' in self && 'Blob' in self && (function() {
      try {
        new Blob();
        return true
      } catch(e) {
        return false
      }
    })(),
    formData: 'FormData' in self
  }

  function Body() {
    this.bodyUsed = false

    this._initBody = function(body) {
      this._bodyInit = body
      if (typeof body === 'string') {
        this._bodyText = body
      } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
        this._bodyBlob = body
      } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
        this._bodyFormData = body
      } else if (!body) {
        this._bodyText = ''
      } else {
        throw new Error('unsupported BodyInit type')
      }
    }

    if (support.blob) {
      this.blob = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return Promise.resolve(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as blob')
        } else {
          return Promise.resolve(new Blob([this._bodyText]))
        }
      }

      this.arrayBuffer = function() {
        return this.blob().then(readBlobAsArrayBuffer)
      }

      this.text = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return readBlobAsText(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as text')
        } else {
          return Promise.resolve(this._bodyText)
        }
      }
    } else {
      this.text = function() {
        var rejected = consumed(this)
        return rejected ? rejected : Promise.resolve(this._bodyText)
      }
    }

    if (support.formData) {
      this.formData = function() {
        return this.text().then(decode)
      }
    }

    this.json = function() {
      return this.text().then(JSON.parse)
    }

    return this
  }

  // HTTP methods whose capitalization should be normalized
  var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

  function normalizeMethod(method) {
    var upcased = method.toUpperCase()
    return (methods.indexOf(upcased) > -1) ? upcased : method
  }

  function Request(url, options) {
    options = options || {}
    this.url = url

    this.credentials = options.credentials || 'omit'
    this.headers = new Headers(options.headers)
    this.method = normalizeMethod(options.method || 'GET')
    this.mode = options.mode || null
    this.referrer = null

    if ((this.method === 'GET' || this.method === 'HEAD') && options.body) {
      throw new TypeError('Body not allowed for GET or HEAD requests')
    }
    this._initBody(options.body)
  }

  function decode(body) {
    var form = new FormData()
    body.trim().split('&').forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
    return form
  }

  function headers(xhr) {
    var head = new Headers()
    var pairs = xhr.getAllResponseHeaders().trim().split('\n')
    pairs.forEach(function(header) {
      var split = header.trim().split(':')
      var key = split.shift().trim()
      var value = split.join(':').trim()
      head.append(key, value)
    })
    return head
  }

  Body.call(Request.prototype)

  function Response(bodyInit, options) {
    if (!options) {
      options = {}
    }

    this._initBody(bodyInit)
    this.type = 'default'
    this.url = null
    this.status = options.status
    this.ok = this.status >= 200 && this.status < 300
    this.statusText = options.statusText
    this.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers)
    this.url = options.url || ''
  }

  Body.call(Response.prototype)

  self.Headers = Headers;
  self.Request = Request;
  self.Response = Response;

  self.fetch = function(input, init) {
    // TODO: Request constructor should accept input, init
    var request
    if (Request.prototype.isPrototypeOf(input) && !init) {
      request = input
    } else {
      request = new Request(input, init)
    }

    return new Promise(function(resolve, reject) {
      var xhr = new XMLHttpRequest()
      if (request.credentials === 'cors') {
        xhr.withCredentials = true;
      }

      function responseURL() {
        if ('responseURL' in xhr) {
          return xhr.responseURL
        }

        // Avoid security warnings on getResponseHeader when not allowed by CORS
        if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
          return xhr.getResponseHeader('X-Request-URL')
        }

        return;
      }

      xhr.onload = function() {
        var status = (xhr.status === 1223) ? 204 : xhr.status
        if (status < 100 || status > 599) {
          reject(new TypeError('Network request failed'))
          return
        }
        var options = {
          status: status,
          statusText: xhr.statusText,
          headers: headers(xhr),
          url: responseURL()
        }
        var body = 'response' in xhr ? xhr.response : xhr.responseText;
        resolve(new Response(body, options))
      }

      xhr.onerror = function() {
        reject(new TypeError('Network request failed'))
      }

      xhr.open(request.method, request.url, true)

      if ('responseType' in xhr && support.blob) {
        xhr.responseType = 'blob'
      }

      request.headers.forEach(function(name, values) {
        values.forEach(function(value) {
          xhr.setRequestHeader(name, value)
        })
      })

      xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
    })
  }
  self.fetch.polyfill = true
})();

/** End of the third-party code */

module.exports = self;
<commit_msg>Better feature detection for FormData/FileReader/Blob<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * This is a third-party polyfill grabbed from:
 * https://github.com/github/fetch
 *
 * @providesModule fetch
 * @nolint
 */
/* eslint-disable */
'use strict';

var self = {};

/**
 * Copyright (c) 2014 GitHub, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @preserve-header
 */
(function() {
  'use strict';

  if (self.fetch) {
    return
  }

  function normalizeName(name) {
    if (typeof name !== 'string') {
      name = String(name)
    }
    if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
      throw new TypeError('Invalid character in header field name')
    }
    return name.toLowerCase()
  }

  function normalizeValue(value) {
    if (typeof value !== 'string') {
      value = String(value)
    }
    return value
  }

  function Headers(headers) {
    this.map = {}

    if (headers instanceof Headers) {
      headers.forEach(function(value, name) {
        this.append(name, value)
      }, this)

    } else if (headers) {
      Object.getOwnPropertyNames(headers).forEach(function(name) {
        this.append(name, headers[name])
      }, this)
    }
  }

  Headers.prototype.append = function(name, value) {
    name = normalizeName(name)
    value = normalizeValue(value)
    var list = this.map[name]
    if (!list) {
      list = []
      this.map[name] = list
    }
    list.push(value)
  }

  Headers.prototype['delete'] = function(name) {
    delete this.map[normalizeName(name)]
  }

  Headers.prototype.get = function(name) {
    var values = this.map[normalizeName(name)]
    return values ? values[0] : null
  }

  Headers.prototype.getAll = function(name) {
    return this.map[normalizeName(name)] || []
  }

  Headers.prototype.has = function(name) {
    return this.map.hasOwnProperty(normalizeName(name))
  }

  Headers.prototype.set = function(name, value) {
    this.map[normalizeName(name)] = [normalizeValue(value)]
  }

  Headers.prototype.forEach = function(callback, thisArg) {
    Object.getOwnPropertyNames(this.map).forEach(function(name) {
      this.map[name].forEach(function(value) {
        callback.call(thisArg, value, name, this)
      }, this)
    }, this)
  }

  function consumed(body) {
    if (body.bodyUsed) {
      return Promise.reject(new TypeError('Already read'))
    }
    body.bodyUsed = true
  }

  function fileReaderReady(reader) {
    return new Promise(function(resolve, reject) {
      reader.onload = function() {
        resolve(reader.result)
      }
      reader.onerror = function() {
        reject(reader.error)
      }
    })
  }

  function readBlobAsArrayBuffer(blob) {
    var reader = new FileReader()
    reader.readAsArrayBuffer(blob)
    return fileReaderReady(reader)
  }

  function readBlobAsText(blob) {
    var reader = new FileReader()
    reader.readAsText(blob)
    return fileReaderReady(reader)
  }

  var support = {
    blob: typeof FileReader === 'function' && typeof Blob === 'function' && (function() {
      try {
        new Blob();
        return true
      } catch(e) {
        return false
      }
    })(),
    formData: typeof FormData === 'function'
  }

  function Body() {
    this.bodyUsed = false

    this._initBody = function(body) {
      this._bodyInit = body
      if (typeof body === 'string') {
        this._bodyText = body
      } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
        this._bodyBlob = body
      } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
        this._bodyFormData = body
      } else if (!body) {
        this._bodyText = ''
      } else {
        throw new Error('unsupported BodyInit type')
      }
    }

    if (support.blob) {
      this.blob = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return Promise.resolve(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as blob')
        } else {
          return Promise.resolve(new Blob([this._bodyText]))
        }
      }

      this.arrayBuffer = function() {
        return this.blob().then(readBlobAsArrayBuffer)
      }

      this.text = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return readBlobAsText(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as text')
        } else {
          return Promise.resolve(this._bodyText)
        }
      }
    } else {
      this.text = function() {
        var rejected = consumed(this)
        return rejected ? rejected : Promise.resolve(this._bodyText)
      }
    }

    if (support.formData) {
      this.formData = function() {
        return this.text().then(decode)
      }
    }

    this.json = function() {
      return this.text().then(JSON.parse)
    }

    return this
  }

  // HTTP methods whose capitalization should be normalized
  var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

  function normalizeMethod(method) {
    var upcased = method.toUpperCase()
    return (methods.indexOf(upcased) > -1) ? upcased : method
  }

  function Request(input, options) {
    options = options || {}
    var body = options.body
    if (Request.prototype.isPrototypeOf(input)) {
      if (input.bodyUsed) {
        throw new TypeError('Already read')
      }
      this.url = input.url
      this.credentials = input.credentials
      if (!options.headers) {
        this.headers = new Headers(input.headers)
      }
      this.method = input.method
      this.mode = input.mode
      if (!body) {
        body = input._bodyInit
        input.bodyUsed = true
      }
    } else {
      this.url = input
    }

    this.credentials = options.credentials || this.credentials || 'omit'
    if (options.headers || !this.headers) {
      this.headers = new Headers(options.headers)
    }
    this.method = normalizeMethod(options.method || this.method || 'GET')
    this.mode = options.mode || this.mode || null
    this.referrer = null

    if ((this.method === 'GET' || this.method === 'HEAD') && body) {
      throw new TypeError('Body not allowed for GET or HEAD requests')
    }
    this._initBody(body)
  }

  function decode(body) {
    var form = new FormData()
    body.trim().split('&').forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
    return form
  }

  function headers(xhr) {
    var head = new Headers()
    var pairs = xhr.getAllResponseHeaders().trim().split('\n')
    pairs.forEach(function(header) {
      var split = header.trim().split(':')
      var key = split.shift().trim()
      var value = split.join(':').trim()
      head.append(key, value)
    })
    return head
  }

  Body.call(Request.prototype)

  function Response(bodyInit, options) {
    if (!options) {
      options = {}
    }

    this._initBody(bodyInit)
    this.type = 'default'
    this.url = null
    this.status = options.status
    this.ok = this.status >= 200 && this.status < 300
    this.statusText = options.statusText
    this.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers)
    this.url = options.url || ''
  }

  Body.call(Response.prototype)

  self.Headers = Headers;
  self.Request = Request;
  self.Response = Response;

  self.fetch = function(input, init) {
    var request
    if (Request.prototype.isPrototypeOf(input) && !init) {
      request = input
    } else {
      request = new Request(input, init)
    }

    return new Promise(function(resolve, reject) {
      var xhr = new XMLHttpRequest()

      function responseURL() {
        if ('responseURL' in xhr) {
          return xhr.responseURL
        }

        // Avoid security warnings on getResponseHeader when not allowed by CORS
        if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
          return xhr.getResponseHeader('X-Request-URL')
        }

        return;
      }

      xhr.onload = function() {
        var status = (xhr.status === 1223) ? 204 : xhr.status
        if (status < 100 || status > 599) {
          reject(new TypeError('Network request failed'))
          return
        }
        var options = {
          status: status,
          statusText: xhr.statusText,
          headers: headers(xhr),
          url: responseURL()
        }
        var body = 'response' in xhr ? xhr.response : xhr.responseText;
        resolve(new Response(body, options))
      }

      xhr.onerror = function() {
        reject(new TypeError('Network request failed'))
      }

      xhr.open(request.method, request.url, true)

      if (request.credentials === 'include') {
        xhr.withCredentials = true
      }

      if ('responseType' in xhr && support.blob) {
        xhr.responseType = 'blob'
      }

      request.headers.forEach(function(value, name) {
        xhr.setRequestHeader(name, value)
      })

      xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
    })
  }
  self.fetch.polyfill = true
})();

/** End of the third-party code */

module.exports = self;
<|endoftext|>


<commit_before>// Define libraries
require.config({
	baseUrl: 'js/',
	paths: {
		jquery: '../../../assets/jquery.min',
		// ember: 'http://cloud.github.com/downloads/emberjs/ember.js/ember-latest.min',
		ember: 'lib/ember-latest',
		text: 'lib/require/text',
		jasmine: '../../../assets/jasmine/jasmine',
		jasmine_html: '../../../assets/jasmine/jasmine-html'
	}
});

// Load our app
define( 'app', [
	'app/router',
	'app/models/store',
	'app/controllers/entries',
	'app/views/application',
	'jquery',
	'ember'
	], function( Router, Store, EntriesController, ApplicationView ) {
		var App = Ember.Application.create({
			VERSION: '0.2',
			rootElement: '#todoapp',
			// Load routes
			Router: Router,
			// Extend to inherit outlet support
			ApplicationController: Ember.Controller.extend(),
			ApplicationView: ApplicationView,
			entriesController: EntriesController.create(
				{ store: new Store( 'todos-emberjs' ) }
			)
		});

		App.initialize();
		// Expose the application globally
		return window.Todos = App;
	}
);
<commit_msg>Add handlebar.js to dependencies. Closes #217.<commit_after>// Define libraries
require.config({
	baseUrl: 'js/',
	paths: {
		jquery: '../../../assets/jquery.min',
		ember: 'lib/ember-latest',
		handlebars: '../../../assets/handlebars.min',
		text: 'lib/require/text',
		jasmine: '../../../assets/jasmine/jasmine',
		jasmine_html: '../../../assets/jasmine/jasmine-html'
	}
});

// Load our app
define( 'app', [
	'app/router',
	'app/models/store',
	'app/controllers/entries',
	'app/views/application',
	'jquery',
	'handlebars',
	'ember'
	], function( Router, Store, EntriesController, ApplicationView ) {
		var App = Ember.Application.create({
			VERSION: '0.2',
			rootElement: '#todoapp',
			// Load routes
			Router: Router,
			// Extend to inherit outlet support
			ApplicationController: Ember.Controller.extend(),
			ApplicationView: ApplicationView,
			entriesController: EntriesController.create(
				{ store: new Store( 'todos-emberjs' ) }
			)
		});

		App.initialize();
		// Expose the application globally
		return window.Todos = App;
	}
);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Layout, Menu, Icon, Table, Button } from 'antd';
import { Row, Col, Card, Badge } from 'antd';
const { SubMenu } = Menu;
const { Header, Sider, Content, Footer } = Layout;

import './App.css';

class App extends Component {

    serviceStatus(props) {
        return (
            <Row gutter={16}
                 className="status-cards"
                 type="flex"
                 justify="space-around">
                <Col span="8">
                    <Card className="status-card">
                        <Icon className="service-icon" type="play-circle"/>

Task Runner

                            <Badge status="success" text="Running" />

                    </Card>
                </Col>
                <Col span="8">
                    <Card className="status-card">
                        <Icon className="service-icon" type="cloud-download"/>

Web Server

                            <Badge status="success" text="Running" />

                    </Card>
                </Col>
                <Col span="8">
                    <Card className="status-card">
                        <Icon className="service-icon" type="code-o"/>

PHP Runtime

                            <Badge status="success" text="Running" />

                    </Card>
                </Col>
                <Col span="8">
                    <Card className="status-card">
                        <Icon className="service-icon" type="hdd"/>

MySQL Server

                            <Badge status="success" text="Running" />

                    </Card>
                </Col>
                <Col span="8">
                    <Card className="status-card">
                        <Icon className="service-icon" type="lock"/>

Local SSL

                            <Badge status="default" text="Not Configured" />

                    </Card>
                </Col>
                <Col span="8">
                    <Card className="status-card">
                        <Icon className="service-icon" type="mail"/>

Local Inbox

                            <Badge status="success" text="Listening" />

                    </Card>
                </Col>
            </Row>
        );
    }

    overviewTable(props) {

        const overviewTopics = [
            {
                key: '1',
                text: 'Project Name',
                disp: 'ServerChef Website',
            },
            {
                key: '2',
                text: 'Website Address',
                action: 'link',
                href: '//serverchef.dev',
                prompt: 'Open Website'
            },
            {
                key: '3',
                text: 'Admin Interface',
                action: 'link',
                href: '//serverchef.dev/admin',
                prompt: 'Open Admin'
            },
            {
                key: '4',
                text: 'Project Location',
                disp: '~/websites/serverchef'
            },
            {
                key: '5',
                text: 'Runtime Environment',
                action: 'link',
                href: '#',
                prompt: 'View Details'
            }
        ];

        const columns = [
            {
                title: 'Topic',
                dataIndex: 'text',
                key: 'text'
            },
            {
                title: 'Action',
                dataIndex: 'action',
                key: 'action',
                render: (_, record) => {
                    if ( record.action === 'link') {
                        return (

                                <Button> {record.prompt} </Button>

                        )
                    } else {
                        return
{record.disp}

                    }
                }
            }
        ]
        return (

        )
    }
    render() {
      return (
          <Layout>

                  <Menu
                      theme='light'
                      mode='horizontal'
                      defaultSelectedKeys={['serverchef']}
                      style={{ lineHeight: '64px', float: 'right' }} >
                      <SubMenu key='projects'
                               title={serverchef.io  <Icon type="down"/>}>
                          <Menu.Item key='serverchef'>serverchef.io</Menu.Item>
                          <Menu.Item key='aagat'>aagat.com</Menu.Item>
                      </SubMenu>
                      <SubMenu key='user'
                               title={<Icon type="poweroff"/>}>
                          <Menu.Item key='1'><Icon type="poweroff"/>Shutdown</Menu.Item>
                          <Menu.Item key='2'><Icon type="reload"/>Restart</Menu.Item>
                      </SubMenu>
                  </Menu>

              <Content style={{ padding: '0 50px' }}>
                  <Layout style={{ padding: '24px 0', background: '#fff', margin: '24px 0' }}>
                      <Sider width={200} style={{ background: '#fff' }}>
                          <Menu
                              mode='inline'
                              defaultSelectedKeys={['1']}
                              style={{ height: '100%' }} >
                              <Menu.Item key='1'>
                                  <Icon type="line-chart" />
                                  Overview
                              </Menu.Item>
                              <Menu.Item key='2'>
                                  <Icon type="code-o" />
                                  Runtime
                              </Menu.Item>
                              <Menu.Item key='3'>
                                  <Icon type="hdd" />
                                  Database
                              </Menu.Item>
                              <Menu.Item key='4'>
                                  <Icon type="select" />
                                  Utilities
                              </Menu.Item>
                              <Menu.Item key='5'>
                                  <Icon type="link" />
                                  Network
                              </Menu.Item>
                              <Menu.Item key='6'>
                                  <Icon type="setting" />
                                  Settings
                              </Menu.Item>
                          </Menu>
                      </Sider>
                      <Content style={{ padding: '0 24px', minHeight: 280 }}>

Overview

                          { this.serviceStatus() }
                          { this.overviewTable() }
                      </Content>
                  </Layout>
              </Content>

                © Serverchef

          </Layout>
    );
  }
}

export default App;
<commit_msg>add logs to side menu<commit_after>import React, { Component } from 'react';
import { Layout, Menu, Icon, Table, Button } from 'antd';
import { Row, Col, Card, Badge } from 'antd';
const { SubMenu } = Menu;
const { Header, Sider, Content, Footer } = Layout;

import './App.css';

class App extends Component {

    serviceStatus(props) {
        return (
            <Row gutter={16}
                 className="status-cards"
                 type="flex"
                 justify="space-around">
                <Col span="8">
                    <Card className="status-card">
                        <Icon className="service-icon" type="play-circle"/>

Task Runner

                            <Badge status="success" text="Running" />

                    </Card>
                </Col>
                <Col span="8">
                    <Card className="status-card">
                        <Icon className="service-icon" type="cloud-download"/>

Web Server

                            <Badge status="success" text="Running" />

                    </Card>
                </Col>
                <Col span="8">
                    <Card className="status-card">
                        <Icon className="service-icon" type="code-o"/>

PHP Runtime

                            <Badge status="success" text="Running" />

                    </Card>
                </Col>
                <Col span="8">
                    <Card className="status-card">
                        <Icon className="service-icon" type="hdd"/>

MySQL Server

                            <Badge status="success" text="Running" />

                    </Card>
                </Col>
                <Col span="8">
                    <Card className="status-card">
                        <Icon className="service-icon" type="lock"/>

Local SSL

                            <Badge status="default" text="Not Configured" />

                    </Card>
                </Col>
                <Col span="8">
                    <Card className="status-card">
                        <Icon className="service-icon" type="mail"/>

Local Inbox

                            <Badge status="success" text="Listening" />

                    </Card>
                </Col>
            </Row>
        );
    }

    overviewTable(props) {

        const overviewTopics = [
            {
                key: '1',
                text: 'Project Name',
                disp: 'ServerChef Website',
            },
            {
                key: '2',
                text: 'Website Address',
                action: 'link',
                href: '//serverchef.dev',
                prompt: 'Open Website'
            },
            {
                key: '3',
                text: 'Admin Interface',
                action: 'link',
                href: '//serverchef.dev/admin',
                prompt: 'Open Admin'
            },
            {
                key: '4',
                text: 'Project Location',
                disp: '~/websites/serverchef'
            },
            {
                key: '5',
                text: 'Runtime Environment',
                action: 'link',
                href: '#',
                prompt: 'View Details'
            }
        ];

        const columns = [
            {
                title: 'Topic',
                dataIndex: 'text',
                key: 'text'
            },
            {
                title: 'Action',
                dataIndex: 'action',
                key: 'action',
                render: (_, record) => {
                    if ( record.action === 'link') {
                        return (

                                <Button> {record.prompt} </Button>

                        )
                    } else {
                        return
{record.disp}

                    }
                }
            }
        ]
        return (

        )
    }
    render() {
      return (
          <Layout>

                  <Menu
                      theme='light'
                      mode='horizontal'
                      defaultSelectedKeys={['serverchef']}
                      style={{ lineHeight: '64px', float: 'right' }} >
                      <SubMenu key='projects'
                               title={serverchef.io  <Icon type="down"/>}>
                          <Menu.Item key='serverchef'>serverchef.io</Menu.Item>
                          <Menu.Item key='aagat'>aagat.com</Menu.Item>
                      </SubMenu>
                      <SubMenu key='user'
                               title={<Icon type="poweroff"/>}>
                          <Menu.Item key='1'><Icon type="poweroff"/>Shutdown</Menu.Item>
                          <Menu.Item key='2'><Icon type="reload"/>Restart</Menu.Item>
                      </SubMenu>
                  </Menu>

              <Content style={{ padding: '0 50px' }}>
                  <Layout style={{ padding: '24px 0', background: '#fff', margin: '24px 0' }}>
                      <Sider width={200} style={{ background: '#fff' }}>
                          <Menu
                              mode='inline'
                              defaultSelectedKeys={['1']}
                              style={{ height: '100%' }} >
                              <Menu.Item key='1'>
                                  <Icon type="line-chart" />
                                  Overview
                              </Menu.Item>
                              <Menu.Item key='2'>
                                  <Icon type="code-o" />
                                  Runtime
                              </Menu.Item>
                              <Menu.Item key='3'>
                                  <Icon type="hdd" />
                                  Database
                              </Menu.Item>
                              <Menu.Item key='4'>
                                  <Icon type="select" />
                                  Utilities
                              </Menu.Item>
                              <Menu.Item key='5'>
                                  <Icon type="link" />
                                  Network
                              </Menu.Item>
                              <Menu.Item key='7'>
                                  <Icon type="file-text" />
                                  Logs
                              </Menu.Item>
                              <Menu.Item key='8'>
                                  <Icon type="setting" />
                                  Settings
                              </Menu.Item>
                          </Menu>
                      </Sider>
                      <Content style={{ padding: '0 24px', minHeight: 280 }}>

Overview

                          { this.serviceStatus() }
                          { this.overviewTable() }
                      </Content>
                  </Layout>
              </Content>

                © Serverchef

          </Layout>
    );
  }
}

export default App;
<|endoftext|>


<commit_before>import _ from 'lodash'
import {validateValue} from './validator/index'
import {aggregateResults} from './validator/utils'
import {getPath} from './dereference'

export const CHANGE_VALUE = 'CHANGE_VALUE'
export const VALIDATION_RESOLVED = 'VALIDATION_RESOLVED'
export const CHANGE_MODEL = 'SET_MODEL'

export function changeValue (bunsenId, value) {
  return {
    type: CHANGE_VALUE,
    bunsenId,
    value
  }
}

export function changeModel (model) {
  return {
    type: CHANGE_MODEL,
    model
  }
}

export function updateValidationResults (validationResult) {
  const errorsByInput = _.groupBy(validationResult.errors, 'path')
  const errorsFilteredToMessagesOnly = _.mapValues(errorsByInput, (fieldErrors, bunsenId) => _.pluck(fieldErrors, 'message'))
  const errorsMappedToDotNotation = _.mapKeys(errorsFilteredToMessagesOnly, (value, key) => getPath(key))

  return {
    errors: errorsMappedToDotNotation,
    type: VALIDATION_RESOLVED,
    validationResult // FIXME: I can probably go bye bye
  }
}

function invalidPath (refPath) {
  console.warn(`${refPath} is not a valid path`)
  return {}
}

function schemaFromRef (definitions) {
  if (_.isUndefined(definitions)) {
    return function (refPath) {
      const schema = invalidPath(refPath)
      console.warn('"$ref" can not be used, "definitions" is not defined for this schema')
      return schema
    }
  }

  return function (refPath, resolveRef) {
    const pathStack = refPath.split('/').reverse()
    if (pathStack.pop() !== '#' || pathStack.pop() !== 'definitions') {
      return invalidPath(refPath)
    }
    const startingSchema = definitions[pathStack.pop()]
    if (pathStack.length <= 0) {
      return startingSchema
    }
    return getSchema(pathStack, startingSchema, resolveRef)
  }
}

function getSchema (pathStack, model, resolveRef) {
  if (model.$ref !== undefined) {
    return resolveRef(model.$ref, resolveRef)
  }

  if (pathStack.length <= 0) {
    return model
  }

  if (model.properties) {
    const current = pathStack.pop()
    return getSchema(pathStack, model.properties[current], resolveRef)
  }

  if (model.items) { // This model is an array
    pathStack.pop() // Remove index since it doesn't provide any more useful information
    return getSchema(pathStack, model.items, resolveRef)
  }

  return {}
}

function findDefaults (value, path, model, resolveRef) {
  let schema

  if (model.$ref !== undefined) {
    schema = getSchema(null, model, resolveRef)
  } else if (path === null) {
    schema = model
  } else {
    const pathStack = path && path.split('.').reverse() || []
    schema = getSchema(pathStack, model, resolveRef)
  }
  const schemaDefault = _.clone(schema.default)
  if (model.type === 'object' || model.properties) { // Recursing only makes sense for objects
    let subSchemaDefaults = {}
    let hasDefaults = false
    _.each(schema.properties, function (subSchema, propName) {
      const defaults = findDefaults(value && value[propName], null, subSchema, resolveRef)
      if (defaults !== undefined) {
        subSchemaDefaults[propName] = defaults
        hasDefaults = true
      }
    })
    if (hasDefaults) { // If we didn't find any defaults, we don't want to try to modify the return
      return _.defaults(schemaDefault || {}, subSchemaDefaults)
    }
  } else if (value !== undefined) {
    return value
  }
  return schemaDefault
}

export function validate (bunsenId, inputValue, renderModel, validators) {
  return function (dispatch, getState) {
    let formValue = getState().value

    const isInputValueEmpty = (
      [undefined, null].indexOf(inputValue) !== -1 ||
      (_.isObject(inputValue) && Object.keys(inputValue).length === 0) // Check if empty object
    )

    const previousValue = _.get(formValue, bunsenId)

    // If an empty value has been provided and there is no previous value then
    // make sure to apply defaults from the model
    if (isInputValueEmpty && previousValue === undefined) {
      const resolveRef = schemaFromRef(renderModel.definitions)
      inputValue = findDefaults(inputValue, bunsenId, renderModel, resolveRef)

      if (bunsenId === null && inputValue === undefined) {
        inputValue = {}
      }
    }

    dispatch(changeValue(bunsenId, inputValue))

    // We must lookup the formValue again in order for the validation results to
    // be run on the post-change value rather than the pre-change value
    formValue = getState().value

    const result = validateValue(formValue, renderModel)

    const promises = []
    validators.forEach((validator) => {
      promises.push(validator(formValue))
    })

    Promise.all(promises)
      .then((snapshots) => {
        const results = _.pluck(snapshots, 'value')
        results.push(result)

        const aggregatedResult = aggregateResults(results)
        // TODO: Dispatch an err action
        dispatch(updateValidationResults(aggregatedResult))
      })
  }
}
<commit_msg>Remove obsolete FIXME comment<commit_after>import _ from 'lodash'
import {validateValue} from './validator/index'
import {aggregateResults} from './validator/utils'
import {getPath} from './dereference'

export const CHANGE_VALUE = 'CHANGE_VALUE'
export const VALIDATION_RESOLVED = 'VALIDATION_RESOLVED'
export const CHANGE_MODEL = 'SET_MODEL'

export function changeValue (bunsenId, value) {
  return {
    type: CHANGE_VALUE,
    bunsenId,
    value
  }
}

export function changeModel (model) {
  return {
    type: CHANGE_MODEL,
    model
  }
}

export function updateValidationResults (validationResult) {
  const errorsByInput = _.groupBy(validationResult.errors, 'path')
  const errorsFilteredToMessagesOnly = _.mapValues(errorsByInput, (fieldErrors, bunsenId) => _.pluck(fieldErrors, 'message'))
  const errorsMappedToDotNotation = _.mapKeys(errorsFilteredToMessagesOnly, (value, key) => getPath(key))

  return {
    errors: errorsMappedToDotNotation,
    type: VALIDATION_RESOLVED,
    validationResult
  }
}

function invalidPath (refPath) {
  console.warn(`${refPath} is not a valid path`)
  return {}
}

function schemaFromRef (definitions) {
  if (_.isUndefined(definitions)) {
    return function (refPath) {
      const schema = invalidPath(refPath)
      console.warn('"$ref" can not be used, "definitions" is not defined for this schema')
      return schema
    }
  }

  return function (refPath, resolveRef) {
    const pathStack = refPath.split('/').reverse()
    if (pathStack.pop() !== '#' || pathStack.pop() !== 'definitions') {
      return invalidPath(refPath)
    }
    const startingSchema = definitions[pathStack.pop()]
    if (pathStack.length <= 0) {
      return startingSchema
    }
    return getSchema(pathStack, startingSchema, resolveRef)
  }
}

function getSchema (pathStack, model, resolveRef) {
  if (model.$ref !== undefined) {
    return resolveRef(model.$ref, resolveRef)
  }

  if (pathStack.length <= 0) {
    return model
  }

  if (model.properties) {
    const current = pathStack.pop()
    return getSchema(pathStack, model.properties[current], resolveRef)
  }

  if (model.items) { // This model is an array
    pathStack.pop() // Remove index since it doesn't provide any more useful information
    return getSchema(pathStack, model.items, resolveRef)
  }

  return {}
}

function findDefaults (value, path, model, resolveRef) {
  let schema

  if (model.$ref !== undefined) {
    schema = getSchema(null, model, resolveRef)
  } else if (path === null) {
    schema = model
  } else {
    const pathStack = path && path.split('.').reverse() || []
    schema = getSchema(pathStack, model, resolveRef)
  }
  const schemaDefault = _.clone(schema.default)
  if (model.type === 'object' || model.properties) { // Recursing only makes sense for objects
    let subSchemaDefaults = {}
    let hasDefaults = false
    _.each(schema.properties, function (subSchema, propName) {
      const defaults = findDefaults(value && value[propName], null, subSchema, resolveRef)
      if (defaults !== undefined) {
        subSchemaDefaults[propName] = defaults
        hasDefaults = true
      }
    })
    if (hasDefaults) { // If we didn't find any defaults, we don't want to try to modify the return
      return _.defaults(schemaDefault || {}, subSchemaDefaults)
    }
  } else if (value !== undefined) {
    return value
  }
  return schemaDefault
}

export function validate (bunsenId, inputValue, renderModel, validators) {
  return function (dispatch, getState) {
    let formValue = getState().value

    const isInputValueEmpty = (
      [undefined, null].indexOf(inputValue) !== -1 ||
      (_.isObject(inputValue) && Object.keys(inputValue).length === 0) // Check if empty object
    )

    const previousValue = _.get(formValue, bunsenId)

    // If an empty value has been provided and there is no previous value then
    // make sure to apply defaults from the model
    if (isInputValueEmpty && previousValue === undefined) {
      const resolveRef = schemaFromRef(renderModel.definitions)
      inputValue = findDefaults(inputValue, bunsenId, renderModel, resolveRef)

      if (bunsenId === null && inputValue === undefined) {
        inputValue = {}
      }
    }

    dispatch(changeValue(bunsenId, inputValue))

    // We must lookup the formValue again in order for the validation results to
    // be run on the post-change value rather than the pre-change value
    formValue = getState().value

    const result = validateValue(formValue, renderModel)

    const promises = []
    validators.forEach((validator) => {
      promises.push(validator(formValue))
    })

    Promise.all(promises)
      .then((snapshots) => {
        const results = _.pluck(snapshots, 'value')
        results.push(result)

        const aggregatedResult = aggregateResults(results)
        // TODO: Dispatch an err action
        dispatch(updateValidationResults(aggregatedResult))
      })
  }
}
<|endoftext|>


<commit_before>'use strict';

var css = require('css');
var url = require('url');
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var concat = require('concat-stream');

var isExternalURL = function(path) {
    return !! url.parse(path).protocol;
};

var isRelativePath = function(path) {
    return /^[^\/]/.test(path);
};

var isInNodeModuleDir = function () {
    return !!process.cwd().match(/node_modules/);
};

var isNodeModule = function (path) {
    return /^node_modules/.test(path);
};

var findNodeModuleDir = function (dirname, path) {
    var parts = path.split('/');
    var moduleName = '';
    if (parts[0] === 'node_modules') {
        moduleName = parts[1];
    }

    var startingDirectory = process.cwd();
    process.chdir(dirname + '/node_modules');

    // move up the chain until we are no longer in a node module
    while(isInNodeModuleDir()) {
        if (fs.existsSync(process.cwd() + '/' + moduleName)) {
            var finalPath = process.cwd() + '/' + moduleName;
            process.chdir(startingDirectory);
            return finalPath;
        }
        process.chdir('../');
    }
    process.chdir(startingDirectory);
};

var removeNodeModuleInPath = function (path) {
    var parts = path.split('/');
    parts.shift();
    parts.shift();
    return parts.join('/');
};

var cssTransform = function(options, filename, callback) {
    var that = this;
    var externalURLs = [];
    var cssStream = concat({ encoding: 'string' }, function(data) {
        var result = _.reduce(externalURLs, function(result, url) {
            return result + '@import url("' + url + '");\n';
        }, '');
        result = result + data;
        callback(result);
    });

    var rebaseUrls = options.rebaseUrls;
    var rootDir = options.rootDir || '';
    if (isRelativePath(rootDir)) {
        rootDir = path.join(process.cwd(), rootDir);
    }
    var processRelativeUrl = function(relativeUrl) {
        return relativeUrl;
    };
    if (_.isFunction(options.processRelativeUrl)) {
        processRelativeUrl = options.processRelativeUrl;
    }

    var parseCSSFile = function(filename) {

        var rebase = function(source) {
            var absUrlRegEx = /^(\/|data:)/;
            var protocolRegEx = /[^\:\/]*:\/\/([^\/])*/;
            var urlRegEx = /url\s*\((?!#)\s*(\s*"([^"]*)"|'([^']*)'|[^\)]*\s*)\s*\)/ig;
            var r;
            while ((r = urlRegEx.exec(source))) {
                var url = r[2] || // url("path/to/foo.css");
                          r[3] || // url('path/to/foo.css');
                          r[1] || // url(path/to/foo.css)
                          '';
                var quoteLen = ((r[2] || r[3]) && r[1]) ? 1 : 0;
                var newUrl = url;

                if ( ! url.match(absUrlRegEx) && ! url.match(protocolRegEx)) {
                    // if both r[2] and r[3] are undefined, but r[1] is a string, it will be the case of url(path/to/foo.css)
                    quoteLen = ((r[2] || r[3]) && r[1]) ? 1 : 0;

                    var dirname = path.dirname(filename);
                    var from = rootDir,
                        to = path.resolve(dirname, url);

                    newUrl = processRelativeUrl(path.relative(from, to));

                    source = source.substr(0, urlRegEx.lastIndex - url.length - quoteLen - 1) + newUrl + source.substr(urlRegEx.lastIndex - quoteLen - 1);
                }

                urlRegEx.lastIndex = urlRegEx.lastIndex + (newUrl.length - url.length);
            }

            return source;
        };

        var data = fs.readFileSync(filename, 'utf8');
        if ( ! data) {
            return;
        }

        var rules = css.parse(data).stylesheet.rules;

        _.each(rules, function(rule) {
            if (rule.type === 'import') {
                //
                // @import 'path/to/foo.css';
                // @import "path/to/foo.css" screen, projection
                // @import url(path/to/foo.css)
                // @import url('path/to/foo.css') screen and (orientation:landscape)
                // @import url("path/to/foo.css") print;
                // @import url("path/to/foo.css ") projection, tv;
                // @import url("chrome://communicator/skin/")
                //
                var importRegEx = /(url)?\s*(('([^']*)'|"([^"]*)")|\(('([^']*)'|"([^"]*)"|([^\)]*))\))\s*;?/;
                var result = importRegEx.exec(rule['import']);

                                       // rule.import             result array
                                       // =======================================
                var url = result[7] || // url('path/to/foo.css')  result[7] = path/to/foo.css
                          result[8] || // url("path/to/foo.css")  result[8] = path/to/foo.css
                          result[9] || // url(path/to/foo.css)    result[9] = path/to/foo.css
                          result[4] || // 'path/to/foo.css'       result[4] = path/to/foo.css
                          result[5];   // "path/to/foo.css"       result[5] = path/to/foo.css

                url = _.trim(url);

                if (isExternalURL(url)) {
                    externalURLs.push(url);
                    return;
                }

                var dirname = path.dirname(filename);
                var absFilename;

                // if the path starts with node_modules, search up the tree to find the module
                // in case it was deduped to a higher location in the tree
                if (isNodeModule(url)) {
                    absFilename = findNodeModuleDir(dirname, url) + '/' + removeNodeModuleInPath(url);
                } else if (isRelativePath(url)) { // relative path
                    absFilename = path.resolve(dirname, url);
                } else { // absolute path
                    absFilename = path.join(rootDir, url);
                }

                if (that && typeof that.emit === 'function') {
                    that.emit('file', absFilename);
                }

                parseCSSFile(absFilename);

            } else {
                if (rebaseUrls) {
                    _.each(rule.declarations, function(declaration) {
                        declaration.value = rebase(declaration.value);
                    });
                }

                var cssText = css.stringify({
                    stylesheet: {
                        rules: [ rule ]
                    }
                });
                cssStream.write(cssText + '\n');
            }
        });
    };

    parseCSSFile(filename);

    cssStream.end();
};

var defaults = {
};

module.exports = function(options, filename, callback) {
    if (typeof options === 'string') {
        callback = filename;
        filename = options;
        options = {};
    }

    if (typeof callback !== 'function') {
        callback = function noop() {};
    }

    options = _.defaults(options || {}, defaults);

    cssTransform.call(this, options, filename, callback);
};
<commit_msg>adding comments and fixing a bug where file is not included from modules root directory<commit_after>'use strict';

var css = require('css');
var url = require('url');
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var concat = require('concat-stream');

var isExternalURL = function(path) {
    return !! url.parse(path).protocol;
};

var isRelativePath = function(path) {
    return /^[^\/]/.test(path);
};

var isInNodeModuleDir = function () {
    return !!process.cwd().match(/node_modules/);
};

var isNodeModule = function (path) {
    return /^node_modules/.test(path);
};

var findNodeModuleDir = function (dirname, path) {

    // get target module name
    var parts = path.split('/');
    var moduleName = '';
    if (parts[0] === 'node_modules') {
        moduleName = parts[1];
    }

    // remember where we started
    var startingDirectory = process.cwd();

    //move up to the current modules root
    while (!fs.existsSync(dirname + '/node_modules')) {
        process.chdir('../');
    }
    process.chdir(dirname + '/node_modules');

    // move up the chain until we are no longer in a node module
    while(isInNodeModuleDir()) {
        if (fs.existsSync(process.cwd() + '/' + moduleName)) {
            var finalPath = process.cwd() + '/' + moduleName;
            process.chdir(startingDirectory);
            return finalPath;
        }
        process.chdir('../');
    }
    process.chdir(startingDirectory);
};

var removeNodeModuleInPath = function (path) {
    var parts = path.split('/');
    parts.shift();
    parts.shift();
    return parts.join('/');
};

var cssTransform = function(options, filename, callback) {
    var that = this;
    var externalURLs = [];
    var cssStream = concat({ encoding: 'string' }, function(data) {
        var result = _.reduce(externalURLs, function(result, url) {
            return result + '@import url("' + url + '");\n';
        }, '');
        result = result + data;
        callback(result);
    });

    var rebaseUrls = options.rebaseUrls;
    var rootDir = options.rootDir || '';
    if (isRelativePath(rootDir)) {
        rootDir = path.join(process.cwd(), rootDir);
    }
    var processRelativeUrl = function(relativeUrl) {
        return relativeUrl;
    };
    if (_.isFunction(options.processRelativeUrl)) {
        processRelativeUrl = options.processRelativeUrl;
    }

    var parseCSSFile = function(filename) {

        var rebase = function(source) {
            var absUrlRegEx = /^(\/|data:)/;
            var protocolRegEx = /[^\:\/]*:\/\/([^\/])*/;
            var urlRegEx = /url\s*\((?!#)\s*(\s*"([^"]*)"|'([^']*)'|[^\)]*\s*)\s*\)/ig;
            var r;
            while ((r = urlRegEx.exec(source))) {
                var url = r[2] || // url("path/to/foo.css");
                          r[3] || // url('path/to/foo.css');
                          r[1] || // url(path/to/foo.css)
                          '';
                var quoteLen = ((r[2] || r[3]) && r[1]) ? 1 : 0;
                var newUrl = url;

                if ( ! url.match(absUrlRegEx) && ! url.match(protocolRegEx)) {
                    // if both r[2] and r[3] are undefined, but r[1] is a string, it will be the case of url(path/to/foo.css)
                    quoteLen = ((r[2] || r[3]) && r[1]) ? 1 : 0;

                    var dirname = path.dirname(filename);
                    var from = rootDir,
                        to = path.resolve(dirname, url);

                    newUrl = processRelativeUrl(path.relative(from, to));

                    source = source.substr(0, urlRegEx.lastIndex - url.length - quoteLen - 1) + newUrl + source.substr(urlRegEx.lastIndex - quoteLen - 1);
                }

                urlRegEx.lastIndex = urlRegEx.lastIndex + (newUrl.length - url.length);
            }

            return source;
        };

        var data = fs.readFileSync(filename, 'utf8');
        if ( ! data) {
            return;
        }

        var rules = css.parse(data).stylesheet.rules;

        _.each(rules, function(rule) {
            if (rule.type === 'import') {
                //
                // @import 'path/to/foo.css';
                // @import "path/to/foo.css" screen, projection
                // @import url(path/to/foo.css)
                // @import url('path/to/foo.css') screen and (orientation:landscape)
                // @import url("path/to/foo.css") print;
                // @import url("path/to/foo.css ") projection, tv;
                // @import url("chrome://communicator/skin/")
                //
                var importRegEx = /(url)?\s*(('([^']*)'|"([^"]*)")|\(('([^']*)'|"([^"]*)"|([^\)]*))\))\s*;?/;
                var result = importRegEx.exec(rule['import']);

                                       // rule.import             result array
                                       // =======================================
                var url = result[7] || // url('path/to/foo.css')  result[7] = path/to/foo.css
                          result[8] || // url("path/to/foo.css")  result[8] = path/to/foo.css
                          result[9] || // url(path/to/foo.css)    result[9] = path/to/foo.css
                          result[4] || // 'path/to/foo.css'       result[4] = path/to/foo.css
                          result[5];   // "path/to/foo.css"       result[5] = path/to/foo.css

                url = _.trim(url);

                if (isExternalURL(url)) {
                    externalURLs.push(url);
                    return;
                }

                var dirname = path.dirname(filename);
                var absFilename;

                // if the path starts with node_modules, search up the tree to find the module
                // in case it was deduped to a higher location in the tree
                if (isNodeModule(url)) {
                    absFilename = findNodeModuleDir(dirname, url) + '/' + removeNodeModuleInPath(url);
                } else if (isRelativePath(url)) { // relative path
                    absFilename = path.resolve(dirname, url);
                } else { // absolute path
                    absFilename = path.join(rootDir, url);
                }

                if (that && typeof that.emit === 'function') {
                    that.emit('file', absFilename);
                }

                parseCSSFile(absFilename);

            } else {
                if (rebaseUrls) {
                    _.each(rule.declarations, function(declaration) {
                        declaration.value = rebase(declaration.value);
                    });
                }

                var cssText = css.stringify({
                    stylesheet: {
                        rules: [ rule ]
                    }
                });
                cssStream.write(cssText + '\n');
            }
        });
    };

    parseCSSFile(filename);

    cssStream.end();
};

var defaults = {
};

module.exports = function(options, filename, callback) {
    if (typeof options === 'string') {
        callback = filename;
        filename = options;
        options = {};
    }

    if (typeof callback !== 'function') {
        callback = function noop() {};
    }

    options = _.defaults(options || {}, defaults);

    cssTransform.call(this, options, filename, callback);
};
<|endoftext|>


<commit_before>var e = module.exports = {};
var path = require('path');
var util = require('util');
const Jimp = require('jimp');
const fs = require('fs');
const GIFEncoder = require('gifencoder');

e.init = () => {
    e.category = bu.CommandType.GENERAL;
};

e.requireCtx = require;

e.isCommand = false;
e.hidden = false;
e.usage = 'triggered [user]';
e.info = `Shows everyone how triggered you are.`;
e.longinfo = `<p>Shows everyone how triggered you are.</p>`;

e.execute = async function(msg, words) {
    let user = msg.author;
    if (words[1]) {
        user = await bu.getUser(msg, words.slice(1).join(' '));
    }
    bot.sendChannelTyping(msg.channel.id);
    try {
        let avatar = await Jimp.read(user.avatarURL);
        avatar.resize(640, 640)
            //  let avatarBuffer = await getImageBuffer(avatar)
            //  logger.debug('meow', avatarBuffer)
        let triggered = await Jimp.read(path.join(__dirname, '..', 'img', `triggered.png`))

        let buffers = [];
        let encoder = new GIFEncoder(512, 512);
        let stream = encoder.createReadStream();
        //   encoder.createReadStream().pipe(fs.createWriteStream(path.join('..', 'myanimated.gif')));
        stream.on('data', function(buffer) {
            buffers.push(buffer);
        });
        stream.on('end', function() {
            let buffer = Buffer.concat(buffers);
            bu.send(msg, undefined, {
                file: buffer,
                name: 'TRIGGERED.gif'
            });
        });

        encoder.start();
        encoder.setRepeat(0);
        encoder.setDelay(20);
        let base = new Jimp(512, 512);

        for (let i = 0; i < 4; i++) {
            let temp = base.clone();
            let x = -64 + (bu.getRandomInt(-32, 32));
            let y = -64 + (bu.getRandomInt(-32, 32));
            temp.composite(avatar, x, y);
            x = 56 + (bu.getRandomInt(-8, 8));
            y = 420 + (bu.getRandomInt(-8, 8));
            temp.composite(triggered, x, y);
     //       encoder.addFrame(temp.bitmap.data);
        }
        encoder.finish();
    } catch (err) {
        logger.error(err);
    }
};

function getImageBuffer(image) {
    return new Promise((fulfill, reject) => {
        image.getBuffer(Jimp.MIME_PNG, (err, buf) => {
            if (err) {
                reject(err);
                return;
            }
            fulfill(buf);
        })
    });
}
<commit_msg>please don't be too blockign<commit_after>var e = module.exports = {};
var path = require('path');
var util = require('util');
const Jimp = require('jimp');
const fs = require('fs');
const GIFEncoder = require('gifencoder');

e.init = () => {
    e.category = bu.CommandType.GENERAL;
};

e.requireCtx = require;

e.isCommand = true;
e.hidden = false;
e.usage = 'triggered [user]';
e.info = `Shows everyone how triggered you are.`;
e.longinfo = `<p>Shows everyone how triggered you are.</p>`;

e.execute = async function(msg, words) {
    let user = msg.author;
    if (words[1]) {
        user = await bu.getUser(msg, words.slice(1).join(' '));
    }
    bot.sendChannelTyping(msg.channel.id);
    try {
        let frameCount = 4;
        let frames = [];

        let avatar = await Jimp.read(user.avatarURL);
        avatar.resize(320, 320)
        let triggered = await Jimp.read(path.join(__dirname, '..', 'img', `triggered.png`))
        triggered.resize(200, 30);
        let buffers = [];
        let encoder = new GIFEncoder(256, 256);
        let stream = encoder.createReadStream();

        stream.on('data', function(buffer) {
            buffers.push(buffer);
        });
        stream.on('end', function() {
            let buffer = Buffer.concat(buffers);
            bu.send(msg, undefined, {
                file: buffer,
                name: 'TRIGGERED.gif'
            });
        });

        let base = new Jimp(256, 256);

        // for (let i = 0; i < frameCount; i++) {
        let temp = base.clone();
        let x = -32 + (bu.getRandomInt(-16, 16));
        let y = -32 + (bu.getRandomInt(-16, 16));
        temp.composite(avatar, x, y);
        x = 28 + (bu.getRandomInt(-4, 4));
        y = 210 + (bu.getRandomInt(-4, 4));
        temp.composite(triggered, x, y);
        frames.push(temp.bitmap.data);

        temp = base.clone();
        x = -32 + (bu.getRandomInt(-16, 16));
        y = -32 + (bu.getRandomInt(-16, 16));
        temp.composite(avatar, x, y);
        x = 28 + (bu.getRandomInt(-4, 4));
        y = 210 + (bu.getRandomInt(-4, 4));
        temp.composite(triggered, x, y);
        frames.push(temp.bitmap.data);

        temp = base.clone();
        x = -32 + (bu.getRandomInt(-16, 16));
        y = -32 + (bu.getRandomInt(-16, 16));
        temp.composite(avatar, x, y);
        x = 28 + (bu.getRandomInt(-4, 4));
        y = 210 + (bu.getRandomInt(-4, 4));
        temp.composite(triggered, x, y);
        frames.push(temp.bitmap.data);

        temp = base.clone();
        x = -32 + (bu.getRandomInt(-16, 16));
        y = -32 + (bu.getRandomInt(-16, 16));
        temp.composite(avatar, x, y);
        x = 28 + (bu.getRandomInt(-4, 4));
        y = 210 + (bu.getRandomInt(-4, 4));
        temp.composite(triggered, x, y);
        frames.push(temp.bitmap.data);

        setTimeout(function() {
            encoder.start();
            encoder.setRepeat(0);
            encoder.setDelay(20);
            for (let frame of frames) encoder.addFrame(frame);
            encoder.finish();
        }, 500);

        //}
        bu.send(msg, 'done')
    } catch (err) {
        logger.error(err);
    }
};<|endoftext|>


<commit_before>/*
Input Mask plugin extentions
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) 2010 Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
Version: 0.0.3b

Optional extentions on the jquery.inputmask base
*/
(function($) {
    //extra definitions
    $.extend($.inputmask.defaults.definitions, {
        'A': { //auto uppercasing
            validator: "[A-Za-z]",
            cardinality: 1,
            casing: "upper"
        }
    });
    //date & time aliases
    $.extend($.inputmask.defaults.definitions, {
        'h': { //hours
            validator: "[01][0-9]|2[0-3]",
            cardinality: 2,
            prevalidator: [{ validator: "[0-2]", cardinality: 1}]
        },
        's': { //seconds || minutes
            validator: "[0-5][0-9]",
            cardinality: 2,
            prevalidator: [{ validator: "[0-5]", cardinality: 1}]
        },
        'd': { //basic day
            validator: "0[1-9]|[12][0-9]|3[01]",
            cardinality: 2,
            prevalidator: [{ validator: "[0-3]", cardinality: 1}]
        },
        'm': { //basic month
            validator: "0[1-9]|1[012]",
            cardinality: 2,
            prevalidator: [{ validator: "[01]", cardinality: 1}]
        },
        'y': { //basic year
            validator: "(19|20)\\d\\d",
            cardinality: 4,
            prevalidator: [
                        { validator: "[12]", cardinality: 1 },
                        { validator: "(19|20)", cardinality: 2 },
                        { validator: "(19|20)\\d", cardinality: 3 }
                        ]
        }
    });
    $.extend($.inputmask.defaults.aliases, {
        'dd/mm/yyyy': {
            mask: "d/m/y",
            placeholder: "dd/mm/yyyy",
            regex: {
                monthpre: new RegExp("[01]"),
                month: new RegExp("((0[1-9]|[12][0-9])\/(0[1-9]|1[012]))|(30\/(0[13-9]|1[012]))|(31\/(0[13578]|1[02]))"),
                year: new RegExp("(19|20)\\d\\d"),
                daypre: new RegExp("[0-3]"),
                day: new RegExp("0[1-9]|[12][0-9]|3[01]")
            },
            definitions: {
                'd': { //day
                    validator: function(chrs, buffer, pos, strict, opts) {
                        var isValid = opts.regex.day.test(chrs);
                        if (!strict && !isValid) {
                            if (chrs.charAt(1) == '/') {
                                isValid = opts.regex.day.test("0" + chrs.charAt(0));
                                if (isValid) {
                                    buffer[pos - 1] = "0";
                                    buffer[pos] = chrs.charAt(0);
                                    pos++;
                                    return pos;
                                }
                            }
                        }
                        return isValid;
                    },
                    cardinality: 2,
                    prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                        var isValid = opts.regex.daypre.test(chrs);
                        if (!strict && !isValid) {
                            isValid = opts.regex.day.test("0" + chrs);
                            if (isValid) {
                                buffer[pos] = "0";
                                pos++;
                                return pos;
                            }
                        }
                        return isValid;
                    }, cardinality: 1}]
                    },
                    'm': { //month
                        validator: function(chrs, buffer, pos, strict, opts) {
                            var dayValue = buffer.join('').substr(0, 3);
                            var isValid = opts.regex.month.test(dayValue + chrs);
                            if (!strict && !isValid) {
                                if (chrs.charAt(1) == '/') {
                                    isValid = opts.regex.month.test(dayValue + "0" + chrs.charAt(0));
                                    if (isValid) {
                                        buffer[pos - 1] = "0";
                                        buffer[pos] = chrs.charAt(0);
                                        pos++;
                                        return pos;
                                    }
                                }
                            }
                            return isValid;
                        },
                        cardinality: 2,
                        prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                            var isValid = opts.regex.monthpre.test(chrs);
                            if (!strict && !isValid) {
                                var dayValue = buffer.join('').substr(0, 3);
                                isValid = opts.regex.month.test(dayValue + "0" + chrs);
                                if (isValid) {
                                    buffer[pos] = "0";
                                    pos++;
                                    return pos;
                                }
                            }
                            return isValid;
                        }, cardinality: 1}]
                        },
                        'y': { //year
                            validator: function(chrs, buffer, pos, strict, opts) {
                                if (opts.regex.year.test(chrs)) {
                                    var dayMonthValue = buffer.join('').substr(0, 6);
                                    if (dayMonthValue != "29/02/")
                                        return true;
                                    else {
                                        var year = parseInt(chrs);  //detect leap year
                                        if (year % 4 == 0)
                                            if (year % 100 == 0)
                                            if (year % 400 == 0)
                                            return true;
                                        else return false;
                                        else return true;
                                        else return false;
                                    }
                                } else return false;
                            },
                            cardinality: 4,
                            prevalidator: [
                        { validator: "[12]", cardinality: 1 },
                        { validator: "(19|20)", cardinality: 2 },
                        { validator: "(19|20)\\d", cardinality: 3 }
                        ]
                        }
                    },
                    insertMode: false,
                    autoUnmask: false
                },
                'mm/dd/yyyy': {
                    mask: "m/d/y",
                    placeholder: "mm/dd/yyyy",
                    regex: {
                        day: new RegExp("((0[1-9]|1[012])\/(0[1-9]|[12][0-9]))|((0[13-9]|1[012])\/30)|((0[13578]|1[02])\/31)"),
                        daypre: new RegExp("((0[13-9]|1[012])\/[0-3])|(02\/[0-2])"),
                        month: new RegExp("0[1-9]|1[012]"),
                        monthpre: new RegExp("[01]"),
                        year: new RegExp("(19|20)\\d\\d")
                    },
                    definitions: {
                        'd': { //day
                            validator: function(chrs, buffer, pos, strict, opts) {
                                var monthValue = buffer.join('').substr(0, 3);
                                var isValid = opts.regex.day.test(monthValue + chrs);
                                if (!strict && !isValid) {
                                    if (chrs.charAt(1) == '/') {
                                        isValid = opts.regex.day.test(monthValue + "0" + chrs.charAt(0));
                                        if (isValid) {
                                            buffer[pos - 1] = "0";
                                            buffer[pos] = chrs.charAt(0);
                                            pos++;
                                            return pos;
                                        }
                                    }
                                }
                                return isValid;
                            },
                            cardinality: 2,
                            prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                                var monthValue = buffer.join('').substr(0, 3);
                                var isValid = opts.regex.daypre.test(monthValue + chrs);
                                if (!strict && !isValid) {
                                    isValid = opts.regex.day.test(monthValue + "0" + chrs);
                                    if (isValid) {
                                        buffer[pos] = "0";
                                        pos++;
                                        return pos;
                                    }
                                }
                                return isValid;
                            },
                                cardinality: 1}]
                            },
                            'm': { //month
                                validator: function(chrs, buffer, pos, strict, opts) {
                                    var isValid = opts.regex.month.test(chrs);
                                    if (!strict && !isValid) {
                                        if (chrs.charAt(1) == '/') {
                                            isValid = opts.regex.month.test("0" + chrs.charAt(0));
                                            if (isValid) {
                                                buffer[pos - 1] = "0";
                                                buffer[pos] = chrs.charAt(0);
                                                pos++;
                                                return pos;
                                            }
                                        }
                                    }
                                    return isValid;
                                },
                                cardinality: 2,
                                prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                                    var isValid = opts.regex.monthpre.test(chrs);
                                    if (!strict && !isValid) {
                                        isValid = opts.regex.month.test("0" + chrs);
                                        if (isValid) {
                                            buffer[pos] = "0";
                                            pos++;
                                            return pos;
                                        }
                                    }
                                    return isValid;
                                }, cardinality: 1}]
                                },
                                'y': { //year
                                    validator: function(chrs, buffer, pos, strict, opts) {
                                        if (opts.regex.year.test(chrs)) {
                                            var monthDayValue = buffer.join('').substr(0, 6);
                                            if (monthDayValue != "02/29/")
                                                return true;
                                            else {
                                                var year = parseInt(chrs);  //detect leap year
                                                if (year % 4 == 0)
                                                    if (year % 100 == 0)
                                                    if (year % 400 == 0)
                                                    return true;
                                                else return false;
                                                else return true;
                                                else return false;
                                            }
                                        } else return false;
                                    },
                                    cardinality: 4,
                                    prevalidator: [
                        { validator: "[12]", cardinality: 1 },
                        { validator: "(19|20)", cardinality: 2 },
                        { validator: "(19|20)\\d", cardinality: 3 }
                        ]
                                }
                            },
                            insertMode: false,
                            autoUnmask: false
                        },
                        'hh:mm:ss': {
                            mask: "h:s:s",
                            autoUnmask: false
                        },
                        'hh:mm': {
                            mask: "h:s",
                            autoUnmask: false
                        },
                        'date': {
                            alias: "dd/mm/yyyy" // "mm/dd/yyyy"
                        },
                        'datetime': {
                            mask: "d/m/y h:s",
                            placeholder: "dd/mm/yyyy hh:mm",
                            alias: "date"
                        }
                    });
                    //number aliases by Dean (datimson)
                    $.extend($.inputmask.defaults, {
                        radixPoint: "\.", // | ","
                        digits: "*", //numer of digits
                        groupSeparator: ",", // | "\."
                        groupSize: 3
                    });
                    $.extend($.inputmask.defaults.aliases, {
                        'decimal': {
                            mask: "~",
                            placeholder: "",
                            repeat: 10,
                            greedy: false,
                            regex: {
                                number: function(radixPoint, digits) { return new RegExp("^([\+\-]?[0-9]*[" + radixPoint + "]?[0-9]" + digits + ")$"); }
                            },
                            definitions: {
                                '~': { //real number
                                    validator: function(chrs, buffer, pos, strict, opts) {
                                        function digitExpression() { return opts.digits; } //enhance me
                                        var bufferStr = buffer.slice().splice(pos, 0, chrs).join('');
                                        var isValid = opts.regex.number(opts.radixPoint, digitExpression()).test(bufferStr);
                                        if (!strict && !isValid) {
                                            //todo grouping, radixpoint handling
                                        }
                                        return isValid;
                                    },
                                    cardinality: 1,
                                    prevalidator: null
                                }
                            },
                            insertMode: true
                        },
                        'non-negative-decimal': {
                            regex: {
                                number: function(radixPoint, digits) { return new RegExp("^([0-9]+[" + radixPoint + "]?[0-9]" + digits + ")$"); }
                            },
                            alias: "decimal"
                        },
                        'integer': {
                            regex: {
                                number: function() { return new RegExp("^([\+\-]?[0-9]*)$"); }
                            },
                            alias: "decimal"
                        }
                    });
                })(jQuery);<commit_msg>fix for number aliases<commit_after>/*
Input Mask plugin extentions
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) 2010 Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
Version: 0.0.3c

Optional extentions on the jquery.inputmask base
*/
(function($) {
    //extra definitions
    $.extend($.inputmask.defaults.definitions, {
        'A': { //auto uppercasing
            validator: "[A-Za-z]",
            cardinality: 1,
            casing: "upper"
        }
    });
    //date & time aliases
    $.extend($.inputmask.defaults.definitions, {
        'h': { //hours
            validator: "[01][0-9]|2[0-3]",
            cardinality: 2,
            prevalidator: [{ validator: "[0-2]", cardinality: 1}]
        },
        's': { //seconds || minutes
            validator: "[0-5][0-9]",
            cardinality: 2,
            prevalidator: [{ validator: "[0-5]", cardinality: 1}]
        },
        'd': { //basic day
            validator: "0[1-9]|[12][0-9]|3[01]",
            cardinality: 2,
            prevalidator: [{ validator: "[0-3]", cardinality: 1}]
        },
        'm': { //basic month
            validator: "0[1-9]|1[012]",
            cardinality: 2,
            prevalidator: [{ validator: "[01]", cardinality: 1}]
        },
        'y': { //basic year
            validator: "(19|20)\\d\\d",
            cardinality: 4,
            prevalidator: [
                        { validator: "[12]", cardinality: 1 },
                        { validator: "(19|20)", cardinality: 2 },
                        { validator: "(19|20)\\d", cardinality: 3 }
                        ]
        }
    });
    $.extend($.inputmask.defaults.aliases, {
        'dd/mm/yyyy': {
            mask: "d/m/y",
            placeholder: "dd/mm/yyyy",
            regex: {
                monthpre: new RegExp("[01]"),
                month: new RegExp("((0[1-9]|[12][0-9])\/(0[1-9]|1[012]))|(30\/(0[13-9]|1[012]))|(31\/(0[13578]|1[02]))"),
                year: new RegExp("(19|20)\\d\\d"),
                daypre: new RegExp("[0-3]"),
                day: new RegExp("0[1-9]|[12][0-9]|3[01]")
            },
            definitions: {
                'd': { //day
                    validator: function(chrs, buffer, pos, strict, opts) {
                        var isValid = opts.regex.day.test(chrs);
                        if (!strict && !isValid) {
                            if (chrs.charAt(1) == '/') {
                                isValid = opts.regex.day.test("0" + chrs.charAt(0));
                                if (isValid) {
                                    buffer[pos - 1] = "0";
                                    buffer[pos] = chrs.charAt(0);
                                    pos++;
                                    return pos;
                                }
                            }
                        }
                        return isValid;
                    },
                    cardinality: 2,
                    prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                        var isValid = opts.regex.daypre.test(chrs);
                        if (!strict && !isValid) {
                            isValid = opts.regex.day.test("0" + chrs);
                            if (isValid) {
                                buffer[pos] = "0";
                                pos++;
                                return pos;
                            }
                        }
                        return isValid;
                    }, cardinality: 1}]
                    },
                    'm': { //month
                        validator: function(chrs, buffer, pos, strict, opts) {
                            var dayValue = buffer.join('').substr(0, 3);
                            var isValid = opts.regex.month.test(dayValue + chrs);
                            if (!strict && !isValid) {
                                if (chrs.charAt(1) == '/') {
                                    isValid = opts.regex.month.test(dayValue + "0" + chrs.charAt(0));
                                    if (isValid) {
                                        buffer[pos - 1] = "0";
                                        buffer[pos] = chrs.charAt(0);
                                        pos++;
                                        return pos;
                                    }
                                }
                            }
                            return isValid;
                        },
                        cardinality: 2,
                        prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                            var isValid = opts.regex.monthpre.test(chrs);
                            if (!strict && !isValid) {
                                var dayValue = buffer.join('').substr(0, 3);
                                isValid = opts.regex.month.test(dayValue + "0" + chrs);
                                if (isValid) {
                                    buffer[pos] = "0";
                                    pos++;
                                    return pos;
                                }
                            }
                            return isValid;
                        }, cardinality: 1}]
                        },
                        'y': { //year
                            validator: function(chrs, buffer, pos, strict, opts) {
                                if (opts.regex.year.test(chrs)) {
                                    var dayMonthValue = buffer.join('').substr(0, 6);
                                    if (dayMonthValue != "29/02/")
                                        return true;
                                    else {
                                        var year = parseInt(chrs);  //detect leap year
                                        if (year % 4 == 0)
                                            if (year % 100 == 0)
                                            if (year % 400 == 0)
                                            return true;
                                        else return false;
                                        else return true;
                                        else return false;
                                    }
                                } else return false;
                            },
                            cardinality: 4,
                            prevalidator: [
                        { validator: "[12]", cardinality: 1 },
                        { validator: "(19|20)", cardinality: 2 },
                        { validator: "(19|20)\\d", cardinality: 3 }
                        ]
                        }
                    },
                    insertMode: false,
                    autoUnmask: false
                },
                'mm/dd/yyyy': {
                    mask: "m/d/y",
                    placeholder: "mm/dd/yyyy",
                    regex: {
                        day: new RegExp("((0[1-9]|1[012])\/(0[1-9]|[12][0-9]))|((0[13-9]|1[012])\/30)|((0[13578]|1[02])\/31)"),
                        daypre: new RegExp("((0[13-9]|1[012])\/[0-3])|(02\/[0-2])"),
                        month: new RegExp("0[1-9]|1[012]"),
                        monthpre: new RegExp("[01]"),
                        year: new RegExp("(19|20)\\d\\d")
                    },
                    definitions: {
                        'd': { //day
                            validator: function(chrs, buffer, pos, strict, opts) {
                                var monthValue = buffer.join('').substr(0, 3);
                                var isValid = opts.regex.day.test(monthValue + chrs);
                                if (!strict && !isValid) {
                                    if (chrs.charAt(1) == '/') {
                                        isValid = opts.regex.day.test(monthValue + "0" + chrs.charAt(0));
                                        if (isValid) {
                                            buffer[pos - 1] = "0";
                                            buffer[pos] = chrs.charAt(0);
                                            pos++;
                                            return pos;
                                        }
                                    }
                                }
                                return isValid;
                            },
                            cardinality: 2,
                            prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                                var monthValue = buffer.join('').substr(0, 3);
                                var isValid = opts.regex.daypre.test(monthValue + chrs);
                                if (!strict && !isValid) {
                                    isValid = opts.regex.day.test(monthValue + "0" + chrs);
                                    if (isValid) {
                                        buffer[pos] = "0";
                                        pos++;
                                        return pos;
                                    }
                                }
                                return isValid;
                            },
                                cardinality: 1}]
                            },
                            'm': { //month
                                validator: function(chrs, buffer, pos, strict, opts) {
                                    var isValid = opts.regex.month.test(chrs);
                                    if (!strict && !isValid) {
                                        if (chrs.charAt(1) == '/') {
                                            isValid = opts.regex.month.test("0" + chrs.charAt(0));
                                            if (isValid) {
                                                buffer[pos - 1] = "0";
                                                buffer[pos] = chrs.charAt(0);
                                                pos++;
                                                return pos;
                                            }
                                        }
                                    }
                                    return isValid;
                                },
                                cardinality: 2,
                                prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                                    var isValid = opts.regex.monthpre.test(chrs);
                                    if (!strict && !isValid) {
                                        isValid = opts.regex.month.test("0" + chrs);
                                        if (isValid) {
                                            buffer[pos] = "0";
                                            pos++;
                                            return pos;
                                        }
                                    }
                                    return isValid;
                                }, cardinality: 1}]
                                },
                                'y': { //year
                                    validator: function(chrs, buffer, pos, strict, opts) {
                                        if (opts.regex.year.test(chrs)) {
                                            var monthDayValue = buffer.join('').substr(0, 6);
                                            if (monthDayValue != "02/29/")
                                                return true;
                                            else {
                                                var year = parseInt(chrs);  //detect leap year
                                                if (year % 4 == 0)
                                                    if (year % 100 == 0)
                                                    if (year % 400 == 0)
                                                    return true;
                                                else return false;
                                                else return true;
                                                else return false;
                                            }
                                        } else return false;
                                    },
                                    cardinality: 4,
                                    prevalidator: [
                        { validator: "[12]", cardinality: 1 },
                        { validator: "(19|20)", cardinality: 2 },
                        { validator: "(19|20)\\d", cardinality: 3 }
                        ]
                                }
                            },
                            insertMode: false,
                            autoUnmask: false
                        },
                        'hh:mm:ss': {
                            mask: "h:s:s",
                            autoUnmask: false
                        },
                        'hh:mm': {
                            mask: "h:s",
                            autoUnmask: false
                        },
                        'date': {
                            alias: "dd/mm/yyyy" // "mm/dd/yyyy"
                        },
                        'datetime': {
                            mask: "d/m/y h:s",
                            placeholder: "dd/mm/yyyy hh:mm",
                            alias: "date"
                        }
                    });
                    //number aliases by Dean (datimson)
                    $.extend($.inputmask.defaults, {
                        radixPoint: "\.", // | ","
                        digits: "*", //numer of digits
                        groupSeparator: ",", // | "\."
                        groupSize: 3
                    });
                    $.extend($.inputmask.defaults.aliases, {
                        'decimal': {
                            mask: "~",
                            placeholder: "",
                            repeat: 10,
                            greedy: false,
                            regex: {
                                number: function(radixPoint, digits) { return new RegExp("^([\+\-]?[0-9]*[" + radixPoint + "]?[0-9]" + digits + ")$"); }
                            },
                            definitions: {
                                '~': { //real number
                                    validator: function(chrs, buffer, pos, strict, opts) {
                                        function digitExpression() {
                                            return isNaN(opts.digits) ? opts.digits : '{0,' + opts.digits + '}';
                                        }
                                        var cbuf = buffer.slice(); cbuf[pos] = chrs;
                                        var bufferStr = cbuf.join('');
                                        var isValid = opts.regex.number(opts.radixPoint, digitExpression()).test(bufferStr);
                                        if (!strict && !isValid) {
                                            //todo grouping, radixpoint handling
                                        }
                                        return isValid;
                                    },
                                    cardinality: 1,
                                    prevalidator: null
                                }
                            },
                            insertMode: true
                        },
                        'non-negative-decimal': {
                            regex: {
                                number: function(radixPoint, digits) { return new RegExp("^([0-9]+[" + radixPoint + "]?[0-9]" + digits + ")$"); }
                            },
                            alias: "decimal"
                        },
                        'integer': {
                            regex: {
                                number: function() { return new RegExp("^([\+\-]?[0-9]*)$"); }
                            },
                            alias: "decimal"
                        }
                    });
                })(jQuery);<|endoftext|>