<commit_before>// Copyright 2017 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// The source code of the storage is at https://github.com/hajimehoshi/snippets
const snippets = 'https://natto-umeboshi-20170912.appspot.com/'
const defaultProg = `package main

import (
    "fmt"
    "github.com/gopherjs/gopherjs/js"
)

func main() {
    fmt.Println("Hai")
    doc := js.Global.Get("document")
    doc.Call("addEventListener","DOMContentLoaded",func() {
        fmt.Println("Loaded")
        doc.Get("body").Set("innerHTML","HAI")
    })
}
`;
const iframeDocument = `<!DOCTYPE html>
<html>
<head>
<script>
if (top.goPrintToConsole) {
    window.goPrintToConsole = top.goPrintToConsole;
}
</script>
</head>
<body>
</body>
</html>
`;

function setButtonsDisabled(value) {
    let buttons = document.querySelectorAll('.btn');
    for (let button of buttons) {
        button.disabled = value;
    }
}

function init() {
    Go.RedirectConsole(function (l) {
        let e = document.getElementById('console');
        e.innerHTML = e.innerHTML + l;
    })
    let el = document.getElementById('pg-editor')
    let editor = ace.edit(el);
    editor.$blockScrolling = Infinity;
    editor.setTheme('ace/theme/sqlserver');
    editor.getSession().setMode('ace/mode/golang');

    setButtonsDisabled(true);
    if (window.location.hash) {
        let hash = window.location.hash.substring(1);
        if (hash[0] === '/') {
            hash = hash.substring(1);
        }
        fetch(`${snippets}${hash}`).then(response => {
            if (200 <= response.status && response.status < 300)
                return response.text();
            return Promise.reject(response);
        }).then(text => {
            editor.setValue(text, -1);
            Go.Compile(text).then(() => {
                setButtonsDisabled(false);
            })
        }).catch(_ => {
            location.href = location.href.split('#')[0];
        });
    } else {
        editor.setValue(defaultProg, -1);
        Go.Compile(defaultProg).then(() => {
            setButtonsDisabled(false);
        });
    }

    let fontSize = parseInt(getCookie('fontsize'), 10);
    if (fontSize === 0) {
        fontSize = 16;
    }
    document.getElementById('pg-fontsize').value = fontSize;
    editor.setFontSize(fontSize);

    document.getElementById('pg-fontsize').addEventListener('change', (e) => {
        e.preventDefault()
        let size = +(document.getElementById('pg-fontsize').value);
        editor.setFontSize(size);
        setCookie('fontsize',size,365);
    });

    document.getElementById('pg-format').addEventListener('click', (e) => {
        e.preventDefault();
        setButtonsDisabled(true);
        let src = editor.getValue();
        Go.Format(src, document.getElementById('pg-imports').checked)
            .then(s => editor.setValue(s,-1))
            .then(() => {setButtonsDisabled(false);})
            .catch(err => {
                document.getElementById('console').textContent = err;
                setButtonsDisabled(false);
            })
    });

    document.getElementById('pg-share').addEventListener('click', (e) => {
        e.preventDefault()
        let share = document.getElementById('pg-share');
        share.disabled = true;
        fetch(`${snippets}`, {
            method: 'POST',
            body:   editor.getValue(),
        }).then(response => {
            return response.text();
        }).then(text => {
            location.hash = `#/${text}`;
            share.disabled = false;
        }).catch(err => {
            document.getElementById('console').textContent = err;
        });
    });

    document.getElementById('pg-run').addEventListener('click', (e) => {
        e.preventDefault();
        setButtonsDisabled(true);
        Go.Compile(editor.getValue())
            .then((src) => {
                document.getElementById('console').textContent = '';
                let output = document.getElementById('output')
                while (output.firstChild) {
                    output.removeChild(output.firstChild);
                }
                let div = document.createElement('div');
                div.classList.add('embed-responsive');
                div.classList.add('embed-responsive-4by3');
                // allowfullscreen
                let iframe = document.createElement('iframe');
                iframe.className = 'embed-responsive-item';
                iframe.sandbox = 'allow-forms allow-scripts allow-same-origin allow-modals allow-popups';
                div.appendChild(iframe);
                output.appendChild(div)
                let doc = iframe.contentWindow.document;
                doc.open();
                doc.write(iframeDocument)
                let script = doc.createElement('script');
                script.textContent = src;
                doc.body.appendChild(script);
                doc.close()
                setButtonsDisabled(false);
            })
            .catch((err) => {
                document.getElementById('console').textContent = err;
                setButtonsDisabled(false);
            });
    });
}

window.addEventListener('load', init);

function setCookie(cname, cvalue, exdays) {
    let d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    let expires = 'expires='+ d.toUTCString();
    document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';
}

function getCookie(cname) {
    let name = cname + '=';
    let decodedCookie = decodeURIComponent(document.cookie);
    let ca = decodedCookie.split(';');
    for(let i = 0; i <ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length);
        }
    }
    return '';
}
<commit_msg>Bug fix: Ignore compile errors for the loaded script<commit_after>// Copyright 2017 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// The source code of the storage is at https://github.com/hajimehoshi/snippets
const snippets = 'https://natto-umeboshi-20170912.appspot.com/'
const defaultProg = `package main

import (
    "fmt"
    "github.com/gopherjs/gopherjs/js"
)

func main() {
    fmt.Println("Hai")
    doc := js.Global.Get("document")
    doc.Call("addEventListener","DOMContentLoaded",func() {
        fmt.Println("Loaded")
        doc.Get("body").Set("innerHTML","HAI")
    })
}
`;
const iframeDocument = `<!DOCTYPE html>
<html>
<head>
<script>
if (top.goPrintToConsole) {
    window.goPrintToConsole = top.goPrintToConsole;
}
</script>
</head>
<body>
</body>
</html>
`;

function setButtonsDisabled(value) {
    let buttons = document.querySelectorAll('.btn');
    for (let button of buttons) {
        button.disabled = value;
    }
}

function init() {
    Go.RedirectConsole(function (l) {
        let e = document.getElementById('console');
        e.innerHTML = e.innerHTML + l;
    })
    let el = document.getElementById('pg-editor')
    let editor = ace.edit(el);
    editor.$blockScrolling = Infinity;
    editor.setTheme('ace/theme/sqlserver');
    editor.getSession().setMode('ace/mode/golang');

    setButtonsDisabled(true);
    if (window.location.hash) {
        let hash = window.location.hash.substring(1);
        if (hash[0] === '/') {
            hash = hash.substring(1);
        }
        fetch(`${snippets}${hash}`).then(response => {
            if (200 <= response.status && response.status < 300)
                return response.text();
            return Promise.reject(response);
        }).then(text => {
            editor.setValue(text, -1);
            Go.Compile(text).then(() => {
                setButtonsDisabled(false);
            }).catch(_ => {
                setButtonsDisabled(false);
            })
        }).catch(_ => {
            location.href = location.href.split('#')[0];
        });
    } else {
        editor.setValue(defaultProg, -1);
        Go.Compile(defaultProg).then(() => {
            setButtonsDisabled(false);
        });
    }

    let fontSize = parseInt(getCookie('fontsize'), 10);
    if (fontSize === 0) {
        fontSize = 16;
    }
    document.getElementById('pg-fontsize').value = fontSize;
    editor.setFontSize(fontSize);

    document.getElementById('pg-fontsize').addEventListener('change', (e) => {
        e.preventDefault()
        let size = +(document.getElementById('pg-fontsize').value);
        editor.setFontSize(size);
        setCookie('fontsize',size,365);
    });

    document.getElementById('pg-format').addEventListener('click', (e) => {
        e.preventDefault();
        setButtonsDisabled(true);
        let src = editor.getValue();
        Go.Format(src, document.getElementById('pg-imports').checked)
            .then(s => editor.setValue(s,-1))
            .then(() => {setButtonsDisabled(false);})
            .catch(err => {
                document.getElementById('console').textContent = err;
                setButtonsDisabled(false);
            })
    });

    document.getElementById('pg-share').addEventListener('click', (e) => {
        e.preventDefault()
        let share = document.getElementById('pg-share');
        share.disabled = true;
        fetch(`${snippets}`, {
            method: 'POST',
            body:   editor.getValue(),
        }).then(response => {
            return response.text();
        }).then(text => {
            location.hash = `#/${text}`;
            share.disabled = false;
        }).catch(err => {
            document.getElementById('console').textContent = err;
        });
    });

    document.getElementById('pg-run').addEventListener('click', (e) => {
        e.preventDefault();
        setButtonsDisabled(true);
        Go.Compile(editor.getValue())
            .then((src) => {
                document.getElementById('console').textContent = '';
                let output = document.getElementById('output')
                while (output.firstChild) {
                    output.removeChild(output.firstChild);
                }
                let div = document.createElement('div');
                div.classList.add('embed-responsive');
                div.classList.add('embed-responsive-4by3');
                // allowfullscreen
                let iframe = document.createElement('iframe');
                iframe.className = 'embed-responsive-item';
                iframe.sandbox = 'allow-forms allow-scripts allow-same-origin allow-modals allow-popups';
                div.appendChild(iframe);
                output.appendChild(div)
                let doc = iframe.contentWindow.document;
                doc.open();
                doc.write(iframeDocument)
                let script = doc.createElement('script');
                script.textContent = src;
                doc.body.appendChild(script);
                doc.close()
                setButtonsDisabled(false);
            })
            .catch((err) => {
                document.getElementById('console').textContent = err;
                setButtonsDisabled(false);
            });
    });
}

window.addEventListener('load', init);

function setCookie(cname, cvalue, exdays) {
    let d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    let expires = 'expires='+ d.toUTCString();
    document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';
}

function getCookie(cname) {
    let name = cname + '=';
    let decodedCookie = decodeURIComponent(document.cookie);
    let ca = decodedCookie.split(';');
    for(let i = 0; i <ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length);
        }
    }
    return '';
}
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Kyle E. Mitchell
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
*/

var round = require('round')

var BILLING_INCREMENT = 15
var MINUTES_PER_HOUR = 60
var MILLISECONDS_PER_MINUTE = MINUTES_PER_HOUR * 1000

// Define LISP-style math functions.
function add(x, y) { return x + y }
function subtract(x, y) { return x - y }
function multiply(x, y) { return x * y }
function divide(x, y) { return x / y }

function dateMatches(year, month, date) {
  return (
    date.getFullYear() === year &&
    // getMonth() is zero-indexed.
    // The month argument is one-indexed.
    add(date.getMonth(), 1) === month) }

function spanAmount(year, month, span) {
  var start = new Date(span.start)
  var end = new Date(span.end)

  // Span is within the relevant month.
  if (dateMatches(year, month, start) &&
      dateMatches(year, month, end)) {
    return round(
      divide(subtract(end, start), MILLISECONDS_PER_MINUTE)) }

  // Span is outside the relevant month.
  else { return 0 } }

function entryAmount(year, month, entry) {

  // Entry gives number of billable hours.
  if ('time' in entry) {
    if (dateMatches(year, month, new Date(entry.date))) {
      return round.down(multiply(entry.time, entry.rate), 1) }
    else { return 0 } }

  // Entry lists spans of billable time.
  else {
    return (
      round.down(
        multiply(
          entry.rate,
          divide(
            // Round billable minutes.
            round(
              entry.spans.reduce(
                function(total, span) {
                  return add(total, spanAmount(year, month, span)) },
                0),
              BILLING_INCREMENT),
            MINUTES_PER_HOUR)),
        1)) } }

module.exports = function(year, month, project) {

  // Bill per a a flat estimate.
  if (project.method === 'estimate') {
    var complete = new Date(project.completed)
    // Was the project completed in the relevant month?
    if (complete && dateMatches(year, month, complete)) {
      return project.estimate }
    else { return 0 } }

  // Bill time on the project.
  else {
    return project.service.reduce(
      function(entryTotal, entry) {
        return add(entryTotal, entryAmount(year, month, entry)) },
      0) } }
<commit_msg>Comment and format<commit_after>/*
 * Copyright 2015 Kyle E. Mitchell
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
*/

var round = require('round')

var BILLING_INCREMENT = 15
var MINUTES_PER_HOUR = 60
var MILLISECONDS_PER_MINUTE = MINUTES_PER_HOUR * 1000

// Define LISP-style math functions.
function add(x, y) { return x + y }
function subtract(x, y) { return x - y }
function multiply(x, y) { return x * y }
function divide(x, y) { return x / y }

function dateMatches(year, month, date) {
  return (
    date.getFullYear() === year &&
    // getMonth() is zero-indexed.
    // The month argument is one-indexed.
    add(date.getMonth(), 1) === month) }

function spanAmount(year, month, span) {
  var start = new Date(span.start)
  var end = new Date(span.end)

  // Span is within the relevant month.
  if (dateMatches(year, month, start) &&
      dateMatches(year, month, end)) {
    return round(
      divide(subtract(end, start), MILLISECONDS_PER_MINUTE)) }

  else { return 0 } }

function entryAmount(year, month, entry) {

  // Entry gives number of billable hours.
  if ('time' in entry) {

    // Entry is within the relevant month.
    if (dateMatches(year, month, new Date(entry.date))) {
      return round.down(multiply(entry.time, entry.rate), 1) }

    else { return 0 } }

  // Entry lists spans of billable time.
  else {
    return (
      round.down(
        multiply(
          entry.rate,
          divide(
            // Round billable minutes.
            round(
              // Sum time spans.
              entry.spans.reduce(
                function(total, span) {
                  return add(total, spanAmount(year, month, span)) },
                0),
              BILLING_INCREMENT),
            MINUTES_PER_HOUR)),
        1)) } }

module.exports = function(year, month, project) {

  // Bill per a a flat estimate.
  if (project.method === 'estimate') {
    var complete = new Date(project.completed)

    // Was the project completed in the relevant month?
    if (complete && dateMatches(year, month, complete)) {
      return project.estimate }

    else { return 0 } }

  // Bill time on the project.
  else {
    return project.service.reduce(
      function(entryTotal, entry) {
        return add(entryTotal, entryAmount(year, month, entry)) },
      0) } }
<|endoftext|>


<commit_before>'use strict';

/**
 * Discord chatbot
 */

const credentials = require('./setup/custom/credentials');
const Brain = require('/utils/Brain');
const ChatBot = require('/utils/ChatBot');

// Build the initial runtime object
let runtime = require('./utils/Runtime');
runtime.debug = process.argv[2] === 'debug' || false;
runtime.coreCommands = null;
runtime.pluginCommands = null;
runtime.websocketCommands = null;
runtime.startUpTime = new Date().getTime();
runtime.credentials = credentials;
runtime.brain = Brain;

// Verify credentials exist
if ( !runtime.credentials.email || !runtime.credentials.password || !runtime.credentials.token ) {
    console.error('ERROR: Credentials file is missing required attributes. Please check your credentials.js');
    console.log('[bot] Quitting startup process.');
    return;
}

runtime.brain.start( __dirname + "/brain" );
ChatBot.start();<commit_msg>Trying to fix paths in index.js<commit_after>'use strict';

/**
 * Discord chatbot
 */

const credentials = require('./setup/custom/credentials');
const Brain = require('./utils/Brain');
const ChatBot = require('./utils/ChatBot');

// Build the initial runtime object
let runtime = require('./utils/Runtime');
runtime.debug = process.argv[2] === 'debug' || false;
runtime.coreCommands = null;
runtime.pluginCommands = null;
runtime.websocketCommands = null;
runtime.startUpTime = new Date().getTime();
runtime.credentials = credentials;
runtime.brain = Brain;

// Verify credentials exist
if ( !runtime.credentials.email || !runtime.credentials.password || !runtime.credentials.token ) {
    console.error('ERROR: Credentials file is missing required attributes. Please check your credentials.js');
    console.log('[bot] Quitting startup process.');
    return;
}

runtime.brain.start( __dirname + "/brain" );
ChatBot.start();<|endoftext|>


<commit_before>class DataIterator {
	constructor(list) {
		this._list = list
		this._current = list.head
	}

	next() {
		let current = this._current

		if (!current) {
			return { done: true }
		}

		this._current = current.next

		return { done: false, value: current.data }
	}
}

class Node {
	constructor(data) {
		this.data = data
	}
}

class LinkedList {
	constructor() {
		this.head = undefined
		this.tail = undefined
		this.length = 0
		this.foreach = this.forEach
	}

	push(item) {
		let node = new Node(item)

		if (this.length > 0) {
			this.tail.next = node
			node.prev = this.tail
			this.tail = node
		} else {
			this.head = node
			this.tail = node
		}

		this.length++;

		return node
	}

	pushAll(arr) {
		for (let i = 0; i < arr.length; i++) {
			this.push(arr[i])
		}
	}

	unshift(item) {
		let node = new Node(item)

		if (this.length > 0) {
			this.head.prev = node
			node.next = this.head
			this.head = node
		} else {
			this.head = node
			this.tail = node
		}

		this.length++;

		return node
	}

	unshiftAll(arr) {
		for (let i = 0; i < arr.length; i++) {
			this.unshift(arr[i])
		}
	}

	forEach(fn) {
		let current = this.head
		while (current) {
			let next = current.next
			let stop = fn(current)
			if (stop) break
			current = next
		}
	}

	nodeIterator() {
		return () => {
			if (this.head) {
				let t = this.head
				this.head = this.head.next
				return t
			}
		}
	}

	iterator() {
		return () => {
			if (this.head) {
				let data = this.head.data
				this.head = this.head.next
				return data
			}
		}
	}

	[Symbol.iterator]() {
		return new DataIterator(this)
	}

	findFirst(data) {
		let current = this.head

		while (current !== undefined) {
			if (current.data === data) {
				return current
			}

			current = current.next
		}
	}

	findAll(data) {
		let current = this.head
		let results = []

		while (current !== undefined) {
			if (current.data === data) {
				results.push(current)
			}

			current = current.next
		}

		return results
	}

	findFirstBy(predicate) {
		let current = this.head

		while (current !== undefined) {
			if (predicate(current.data)) {
				return current
			}

			current = current.next
		}
	}

	findAllBy(predicate) {
		let current = this.head
		let results = []

		while (current !== undefined) {
			if (predicate(current.data)) {
				results.push(current)
			}

			current = current.next
		}

		return results
	}

	remove(node) {

		if (!(node instanceof Node)) {
			throw new TypeError('remove() can only be used with node objects return from various methods of the list')
		}

		if (this.length === 0) {
			return
		}

		if (this.head === node) {
			// its the head
			this.head = this.head.next
			if (this.head) {
				this.head.prev = undefined

				if (!this.head.next) {
					this.tail = this.head // only 1 item remains
				}

			} else {
				this.tail = undefined // was the last, now its empty - so clean tail reference too
			}

			this.length--

		} else if (this.tail === node) {
			this.tail = this.tail.prev
			this.tail.next = undefined
			this.length--
		} else if (node.prev && node.next) {
			let prev = node.prev
			let next = node.next
			prev.next = next
			next.prev = prev
			this.length--
		}

		node.prev = undefined
		node.next = undefined

		return node.data
	}

	shift() {
		if (this.head) {
			return this.remove(this.head)
		}
	}

	pop() {
		if (this.tail) {
			return this.remove(this.tail)
		}
	}
}

module.exports = LinkedList<commit_msg>make ES6 iterator expose both data and node<commit_after>class DataIterator {
	constructor(list) {
		this._list = list
		this._current = list.head
	}

	next() {
		let current = this._current

		if (!current) {
			return { done: true }
		}

		this._current = current.next

		return {
			done: false,
			value: {
				data: current.data,
				node: current
			}
		}
	}
}

class Node {
	constructor(data) {
		this.data = data
	}
}

class LinkedList {
	constructor() {
		this.head = undefined
		this.tail = undefined
		this.length = 0
		this.foreach = this.forEach
	}

	/**
	 *    push an item to the tail of this list
	 *
	 *    @param  {variant} item
	 *    @return {Node}
	 */
	push(item) {
		let node = new Node(item)

		if (this.length > 0) {
			this.tail.next = node
			node.prev = this.tail
			this.tail = node
		} else {
			this.head = node
			this.tail = node
		}

		this.length++;

		return node
	}

	pushAll(arr) {
		for (let i = 0; i < arr.length; i++) {
			this.push(arr[i])
		}
	}

	unshift(item) {
		let node = new Node(item)

		if (this.length > 0) {
			this.head.prev = node
			node.next = this.head
			this.head = node
		} else {
			this.head = node
			this.tail = node
		}

		this.length++;

		return node
	}

	unshiftAll(arr) {
		for (let i = 0; i < arr.length; i++) {
			this.unshift(arr[i])
		}
	}

	forEach(fn) {
		let current = this.head
		while (current) {
			let next = current.next
			let stop = fn(current)
			if (stop) break
			current = next
		}
	}

	nodeIterator() {
		return () => {
			if (this.head) {
				let t = this.head
				this.head = this.head.next
				return t
			}
		}
	}

	iterator() {
		return () => {
			if (this.head) {
				let data = this.head.data
				this.head = this.head.next
				return data
			}
		}
	}

	[Symbol.iterator]() {
		return new DataIterator(this)
	}

	findFirst(data) {
		let current = this.head

		while (current !== undefined) {
			if (current.data === data) {
				return current
			}

			current = current.next
		}
	}

	findAll(data) {
		let current = this.head
		let results = []

		while (current !== undefined) {
			if (current.data === data) {
				results.push(current)
			}

			current = current.next
		}

		return results
	}

	findFirstBy(predicate) {
		let current = this.head

		while (current !== undefined) {
			if (predicate(current.data)) {
				return current
			}

			current = current.next
		}
	}

	findAllBy(predicate) {
		let current = this.head
		let results = []

		while (current !== undefined) {
			if (predicate(current.data)) {
				results.push(current)
			}

			current = current.next
		}

		return results
	}

	remove(node) {

		if (!(node instanceof Node)) {
			throw new TypeError('remove() can only be used with node objects return from various methods of the list')
		}

		if (this.length === 0) {
			return
		}

		if (this.head === node) {
			// its the head
			this.head = this.head.next
			if (this.head) {
				this.head.prev = undefined

				if (!this.head.next) {
					this.tail = this.head // only 1 item remains
				}

			} else {
				this.tail = undefined // was the last, now its empty - so clean tail reference too
			}

			this.length--

		} else if (this.tail === node) {
			this.tail = this.tail.prev
			this.tail.next = undefined
			this.length--
		} else if (node.prev && node.next) {
			let prev = node.prev
			let next = node.next
			prev.next = next
			next.prev = prev
			this.length--
		}

		node.prev = undefined
		node.next = undefined

		return node.data
	}

	shift() {
		if (this.head) {
			return this.remove(this.head)
		}
	}

	pop() {
		if (this.tail) {
			return this.remove(this.tail)
		}
	}
}

module.exports = LinkedList<|endoftext|>


<commit_before>'use strict'

const m = require('mithril/render/hyperscript')
const cssauron = require('cssauron')
const code = require('yields-keycode')

const PD = '//'

function copyObj(data) {
  return Object.assign(Object.create(Object.getPrototypeOf(data)), data)
}

function identity(thing) {
  return thing
}

function isBoolean(thing) {
  return typeof thing === 'boolean'
}

function isString(thing) {
  return Object.prototype.toString.call(thing) === '[object String]'
}

function isNumber(thing) {
  return typeof thing === 'number'
}

function isStringOrNumber(thing) {
  return isString(thing) || isNumber(thing)
}

function getContent(thing) {
  if (!thing) {
    return ''
  }
  if (isString(thing)) {
    return thing
  }
  if (isNumber(thing)) {
    return '' + thing
  }
  if (thing.tag === '#') {
    return getContent(thing.children)
  }
  if (isArray(thing)) {
    return thing.map(getContent).join('')
  }
  return ''
}

function isArray(thing) {
  return Object.prototype.toString.call(thing) === '[object Array]'
}

function isComponent(thing) {
  return (
    (thing && (typeof thing === 'object' && thing.view)) ||
    isFunction(thing) ||
    isClass(thing)
  )
}

function isFunction(thing) {
  return typeof thing === 'function' && !isClass(thing)
}

function isClass(thing) {
  return typeof thing === 'function' && /^\s*class\s+/.test(thing.toString())
}

function call(thing) {
  return thing()
}

function consoleLogFn(a) {
  const util = require('util')
  // eslint-disable-next-line no-console
  console.log(
    util.inspect(a, {
      colors: true,
      depth: null,
    })
  )
}

const language = cssauron({
  tag: 'tag',
  contents(node) {
    const content = node.text == null ? '' : '' + node.text
    if (isStringOrNumber(node.children) || isBoolean(node.children)) {
      return '' + content + node.children
    }
    return '' + content + getContent(node.renderedChildren)
  },
  id(node) {
    if (node.attrs) {
      return node.attrs.id || ''
    }
    return ''
  },
  class(node) {
    if (node.attrs) {
      return node.attrs.className
    }
    return ''
  },
  parent: 'parent',
  children(node) {
    return isArray(node.renderedChildren)
      ? node.renderedChildren.filter(identity)
      : []
  },
  attr(node, attr) {
    if (node.attrs) {
      return node.attrs[attr]
    }
  },
})

function join(arrays) {
  return arrays.reduce(function(result, array) {
    return result.concat(array)
  }, [])
}

function renderComponents(states, onremovers) {
  function renderComponent(component, treePath) {
    if (isFunction(component.tag)) {
      component.instance = component.tag(component)
    } else if (isClass(component.tag)) {
      const Component = component.tag
      component.instance = new Component(component)
    } else {
      component.instance = copyObj(component.tag)
    }

    if (!states[treePath]) {
      component.state = component.instance
      if (component.instance.oninit) {
        component.instance.oninit(component)
        states[treePath] = component.state
      }
      if (component.instance.onremove) {
        onremovers.push(function() {
          component.instance.onremove(component)
        })
      }
      if (component.instance._captureVnode) {
        component.instance._captureVnode(component)
      }
    } else {
      component.state = states[treePath]
      if (component.instance.onupdate) {
        component.instance.onupdate(component)
      }
    }
    const node = component.instance.view(component)

    return node
  }

  return function renderNode(parent, node, treePath) {
    if (!node) {
      return ''
    }
    if (isArray(node)) {
      return node.map(function(subnode, index) {
        return renderNode(parent, subnode, treePath + PD + index)
      })
    }
    if (isComponent(node.tag)) {
      const componentTreePath = treePath + PD + (node.key || '')
      return renderNode(
        parent,
        renderComponent(node, componentTreePath),
        componentTreePath
      )
    }

    if (node.children) {
      node.renderedChildren = renderNode(
        node,
        node.children,
        treePath + PD + (node.key || '')
      )
    }

    if (isString(node.tag)) {
      node.parent = parent;
    }

    return node
  }
}

function scan(render) {
  const states = {}
  const onremovers = []
  const renderNode = renderComponents(states, onremovers)
  const api = {
    onremovers,
    redraw() {
      api.rootNode = renderNode(undefined, render(api), 'ROOT')
    },
  }
  api.redraw()

  function find(selectorString, node) {
    return select(language(selectorString))(node)
  }

  function select(matchesSelector) {
    return function matches(node) {
      if (!node) {
        return []
      }
      if (isArray(node)) {
        return join(
          node.filter(identity).map(function(childNode) {
            return matches(childNode)
          })
        )
      }
      const foundNodes = []
      if (matchesSelector(node)) {
        foundNodes.push(node)
      }
      if (
        isBoolean(node.children) ||
        isStringOrNumber(node.children) ||
        !node.children
      ) {
        return foundNodes
      }
      node.renderedChildren.filter(identity).map(function(child) {
        if (typeof child === 'string' || typeof child === 'number') {
          return
        }
        child.parent = node
        child.inspect = function() {
          return {
            tag: child.tag,
            children: child.children,
            text: child.text,
            attrs: child.attrs,
          }
        }
      })
      return foundNodes.concat(matches(node.renderedChildren))
    }
  }

  function first(selector) {
    const node = find(selector, api.rootNode)[0]
    if (!node) {
      throw new Error('No element matches ' + selector)
    }
    return node
  }

  function has(selector) {
    return find(selector, api.rootNode).length > 0
  }

  function contains(value, node) {
    return !!find(':contains(' + value + ')', node).length
  }

  function shouldHaveAtLeast(minCount, selector) {
    const actualCount = find(selector, api.rootNode).length
    if (actualCount < minCount) {
      throw new Error(
        'Wrong count of elements that matches "' +
          selector +
          '"\n  expected: >=' +
          minCount +
          '\n  actual: ' +
          actualCount
      )
    }
    return true
  }

  function shouldHave(expectedCount, selector) {
    if (!selector) {
      return isArray(expectedCount)
        ? shouldHaveCollection(expectedCount)
        : shouldHaveAtLeast(1, expectedCount)
    }

    const actualCount = find(selector, api.rootNode).length
    if (actualCount !== expectedCount) {
      throw new Error(
        'Wrong count of elements that matches "' +
          selector +
          '"\n  expected: ' +
          expectedCount +
          '\n  actual: ' +
          actualCount
      )
    }
    return true
  }

  function shouldHaveCollection(selectors) {
    selectors.forEach(function(selector) {
      shouldHaveAtLeast(1, selector)
    })
    return true
  }

  function shouldNotHave(selector) {
    shouldHave(0, selector)
    return true
  }

  function shouldContain(string) {
    if (!contains(string, api.rootNode)) {
      throw new Error('Expected "' + string + '" not found!')
    }
    return true
  }

  function shouldNotContain(string) {
    if (contains(string, api.rootNode)) {
      throw new Error('Unexpected "' + string + '" found!')
    }
    return true
  }

  function setValue(selector, string, silent) {
    const attrs = first(selector).attrs
    const event = {
      currentTarget: { value: string },
      target: { value: string },
    }
    attrs.oninput && attrs.oninput(event)
    attrs.onchange && attrs.onchange(event)
    attrs.onkeyup && attrs.onkeyup(event)
    silent || api.redraw()
  }

  function trigger(eventName) {
    return function(selector, event, silent) {
      const attrs = first(selector).attrs
      attrs[eventName](event)
      silent = silent || (event && event.redraw === false)
      silent || api.redraw()
    }
  }

  function triggerKey(eventName) {
    const fire = trigger('on' + eventName)
    return function handleEvent(selector, key, event, silent) {
      const keyCode = isString(key) ? code(key) : key
      const defaultEvent = {
        altKey: false,
        shiftKey: false,
        ctrlKey: false,
        type: eventName,
        keyCode,
        which: keyCode,
      }
      fire(
        selector,
        Object.assign({}, defaultEvent, event || {}),
        !!silent
      )
    }
  }

  shouldHave.at = {
    least: shouldHaveAtLeast,
  }

  api.first = first
  api.has = has
  api.contains = function(value) {
    return contains(value, api.rootNode)
  }
  api.find = function(selector) {
    return find(selector, api.rootNode)
  }
  api.setValue = setValue
  ;[
    'focus',
    'click',
    'blur',
    'mousedown',
    'mouseup',
    'mouseover',
    'mouseout',
    'mouseenter',
    'mouseleave',
  ].map(function(eventName) {
    api[eventName] = trigger('on' + eventName)
  })
  api.contextMenu = trigger('contextmenu')
  api.keydown = triggerKey('keydown')
  api.keypress = triggerKey('keypress')
  api.keyup = triggerKey('keyup')
  api.trigger = function(selector, eventName, event, silent) {
    trigger(eventName)(selector, event, silent)
  }
  api.should = {
    not: {
      have: shouldNotHave,
      contain: shouldNotContain,
    },
    have: shouldHave,
    contain: shouldContain,
  }
  api.log = function(selector, logFn = consoleLogFn) {
    logFn(api.find(selector))
    return api
  }
  return api
}

function init(viewOrComponentOrRootNode, nodeOrAttrs) {
  let api = {}
  if (isComponent(viewOrComponentOrRootNode)) {
    api = scan(function(api) {
      viewOrComponentOrRootNode._captureVnode = function(vnode) {
        api.vnode = vnode
      }
      return m(viewOrComponentOrRootNode, nodeOrAttrs)
    })
  } else {
    // assume that first argument is rendered view
    api = scan(function() {
      return viewOrComponentOrRootNode
    })
  }
  api.onremove = function() {
    api.onremovers.filter(isFunction).map(call)
  }
  return api
}

module.exports = init
<commit_msg>children function for cssauron can be missing node<commit_after>'use strict'

const m = require('mithril/render/hyperscript')
const cssauron = require('cssauron')
const code = require('yields-keycode')

const PD = '//'

function copyObj(data) {
  return Object.assign(Object.create(Object.getPrototypeOf(data)), data)
}

function identity(thing) {
  return thing
}

function isBoolean(thing) {
  return typeof thing === 'boolean'
}

function isString(thing) {
  return Object.prototype.toString.call(thing) === '[object String]'
}

function isNumber(thing) {
  return typeof thing === 'number'
}

function isStringOrNumber(thing) {
  return isString(thing) || isNumber(thing)
}

function getContent(thing) {
  if (!thing) {
    return ''
  }
  if (isString(thing)) {
    return thing
  }
  if (isNumber(thing)) {
    return '' + thing
  }
  if (thing.tag === '#') {
    return getContent(thing.children)
  }
  if (isArray(thing)) {
    return thing.map(getContent).join('')
  }
  return ''
}

function isArray(thing) {
  return Object.prototype.toString.call(thing) === '[object Array]'
}

function isComponent(thing) {
  return (
    (thing && (typeof thing === 'object' && thing.view)) ||
    isFunction(thing) ||
    isClass(thing)
  )
}

function isFunction(thing) {
  return typeof thing === 'function' && !isClass(thing)
}

function isClass(thing) {
  return typeof thing === 'function' && /^\s*class\s+/.test(thing.toString())
}

function call(thing) {
  return thing()
}

function consoleLogFn(a) {
  const util = require('util')
  // eslint-disable-next-line no-console
  console.log(
    util.inspect(a, {
      colors: true,
      depth: null,
    })
  )
}

const language = cssauron({
  tag: 'tag',
  contents(node) {
    const content = node.text == null ? '' : '' + node.text
    if (isStringOrNumber(node.children) || isBoolean(node.children)) {
      return '' + content + node.children
    }
    return '' + content + getContent(node.renderedChildren)
  },
  id(node) {
    if (node.attrs) {
      return node.attrs.id || ''
    }
    return ''
  },
  class(node) {
    if (node.attrs) {
      return node.attrs.className
    }
    return ''
  },
  parent: 'parent',
  children(node) {
    return node && isArray(node.renderedChildren)
      ? node.renderedChildren.filter(identity)
      : []
  },
  attr(node, attr) {
    if (node.attrs) {
      return node.attrs[attr]
    }
  },
})

function join(arrays) {
  return arrays.reduce(function(result, array) {
    return result.concat(array)
  }, [])
}

function renderComponents(states, onremovers) {
  function renderComponent(component, treePath) {
    if (isFunction(component.tag)) {
      component.instance = component.tag(component)
    } else if (isClass(component.tag)) {
      const Component = component.tag
      component.instance = new Component(component)
    } else {
      component.instance = copyObj(component.tag)
    }

    if (!states[treePath]) {
      component.state = component.instance
      if (component.instance.oninit) {
        component.instance.oninit(component)
        states[treePath] = component.state
      }
      if (component.instance.onremove) {
        onremovers.push(function() {
          component.instance.onremove(component)
        })
      }
      if (component.instance._captureVnode) {
        component.instance._captureVnode(component)
      }
    } else {
      component.state = states[treePath]
      if (component.instance.onupdate) {
        component.instance.onupdate(component)
      }
    }
    return component.instance.view(component)
  }

  return function renderNode(parent, node, treePath) {
    if (!node) {
      return ''
    }
    if (isArray(node)) {
      return node.map(function(subnode, index) {
        return renderNode(parent, subnode, treePath + PD + index)
      })
    }
    if (isComponent(node.tag)) {
      const componentTreePath = treePath + PD + (node.key || '')
      return renderNode(
        parent,
        renderComponent(node, componentTreePath),
        componentTreePath
      )
    }

    if (node.children) {
      node.renderedChildren = renderNode(
        node,
        node.children,
        treePath + PD + (node.key || '')
      )
    }

    if (isString(node.tag)) {
      node.parent = parent;
    }

    return node
  }
}

function scan(render) {
  const states = {}
  const onremovers = []
  const renderNode = renderComponents(states, onremovers)
  const api = {
    onremovers,
    redraw() {
      api.rootNode = renderNode(undefined, render(api), 'ROOT')
    },
  }
  api.redraw()

  function find(selectorString, node) {
    return select(language(selectorString))(node)
  }

  function select(matchesSelector) {
    return function matches(node) {
      if (!node) {
        return []
      }
      if (isArray(node)) {
        return join(
          node.filter(identity).map(function(childNode) {
            return matches(childNode)
          })
        )
      }
      const foundNodes = []
      if (matchesSelector(node)) {
        foundNodes.push(node)
      }
      if (
        isBoolean(node.children) ||
        isStringOrNumber(node.children) ||
        !node.children
      ) {
        return foundNodes
      }
      node.renderedChildren.filter(identity).map(function(child) {
        if (typeof child === 'string' || typeof child === 'number') {
          return
        }
        child.parent = node
        child.inspect = function() {
          return {
            tag: child.tag,
            children: child.children,
            text: child.text,
            attrs: child.attrs,
          }
        }
      })
      return foundNodes.concat(matches(node.renderedChildren))
    }
  }

  function first(selector) {
    const node = find(selector, api.rootNode)[0]
    if (!node) {
      throw new Error('No element matches ' + selector)
    }
    return node
  }

  function has(selector) {
    return find(selector, api.rootNode).length > 0
  }

  function contains(value, node) {
    return !!find(':contains(' + value + ')', node).length
  }

  function shouldHaveAtLeast(minCount, selector) {
    const actualCount = find(selector, api.rootNode).length
    if (actualCount < minCount) {
      throw new Error(
        'Wrong count of elements that matches "' +
          selector +
          '"\n  expected: >=' +
          minCount +
          '\n  actual: ' +
          actualCount
      )
    }
    return true
  }

  function shouldHave(expectedCount, selector) {
    if (!selector) {
      return isArray(expectedCount)
        ? shouldHaveCollection(expectedCount)
        : shouldHaveAtLeast(1, expectedCount)
    }

    const actualCount = find(selector, api.rootNode).length
    if (actualCount !== expectedCount) {
      throw new Error(
        'Wrong count of elements that matches "' +
          selector +
          '"\n  expected: ' +
          expectedCount +
          '\n  actual: ' +
          actualCount
      )
    }
    return true
  }

  function shouldHaveCollection(selectors) {
    selectors.forEach(function(selector) {
      shouldHaveAtLeast(1, selector)
    })
    return true
  }

  function shouldNotHave(selector) {
    shouldHave(0, selector)
    return true
  }

  function shouldContain(string) {
    if (!contains(string, api.rootNode)) {
      throw new Error('Expected "' + string + '" not found!')
    }
    return true
  }

  function shouldNotContain(string) {
    if (contains(string, api.rootNode)) {
      throw new Error('Unexpected "' + string + '" found!')
    }
    return true
  }

  function setValue(selector, string, silent) {
    const attrs = first(selector).attrs
    const event = {
      currentTarget: { value: string },
      target: { value: string },
    }
    attrs.oninput && attrs.oninput(event)
    attrs.onchange && attrs.onchange(event)
    attrs.onkeyup && attrs.onkeyup(event)
    silent || api.redraw()
  }

  function trigger(eventName) {
    return function(selector, event, silent) {
      const attrs = first(selector).attrs
      attrs[eventName](event)
      silent = silent || (event && event.redraw === false)
      silent || api.redraw()
    }
  }

  function triggerKey(eventName) {
    const fire = trigger('on' + eventName)
    return function handleEvent(selector, key, event, silent) {
      const keyCode = isString(key) ? code(key) : key
      const defaultEvent = {
        altKey: false,
        shiftKey: false,
        ctrlKey: false,
        type: eventName,
        keyCode,
        which: keyCode,
      }
      fire(
        selector,
        Object.assign({}, defaultEvent, event || {}),
        !!silent
      )
    }
  }

  shouldHave.at = {
    least: shouldHaveAtLeast,
  }

  api.first = first
  api.has = has
  api.contains = function(value) {
    return contains(value, api.rootNode)
  }
  api.find = function(selector) {
    return find(selector, api.rootNode)
  }
  api.setValue = setValue
  ;[
    'focus',
    'click',
    'blur',
    'mousedown',
    'mouseup',
    'mouseover',
    'mouseout',
    'mouseenter',
    'mouseleave',
  ].map(function(eventName) {
    api[eventName] = trigger('on' + eventName)
  })
  api.contextMenu = trigger('contextmenu')
  api.keydown = triggerKey('keydown')
  api.keypress = triggerKey('keypress')
  api.keyup = triggerKey('keyup')
  api.trigger = function(selector, eventName, event, silent) {
    trigger(eventName)(selector, event, silent)
  }
  api.should = {
    not: {
      have: shouldNotHave,
      contain: shouldNotContain,
    },
    have: shouldHave,
    contain: shouldContain,
  }
  api.log = function(selector, logFn = consoleLogFn) {
    logFn(api.find(selector))
    return api
  }
  return api
}

function init(viewOrComponentOrRootNode, nodeOrAttrs) {
  let api = {}
  if (isComponent(viewOrComponentOrRootNode)) {
    api = scan(function(api) {
      viewOrComponentOrRootNode._captureVnode = function(vnode) {
        api.vnode = vnode
      }
      return m(viewOrComponentOrRootNode, nodeOrAttrs)
    })
  } else {
    // assume that first argument is rendered view
    api = scan(function() {
      return viewOrComponentOrRootNode
    })
  }
  api.onremove = function() {
    api.onremovers.filter(isFunction).map(call)
  }
  return api
}

module.exports = init
<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var mktemp = require('mktemp')
var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var walk = require('walk')
var glob = require('glob')
var hapi = require('hapi')
var async = require('async')
var synchronized = require('synchronized')
var Gaze = require('gaze').Gaze
var ES6Transpiler = require('es6-module-transpiler').Compiler
var jsStringEscape = require('js-string-escape')

var helpers = require('./lib/helpers')

var Generator
exports.Generator = Generator = function (src) {
  this.src = src
  this.preprocessors = {}
  this.compilers = []
}

Generator.prototype.regenerate = function () {
  var self = this
  synchronized(this, function (done) {
    self.cleanup(function() { /* do not wait for cleanup to finish */ })
    self.createDest() // create pristine directory with new name

    self.preprocess(function () {
      self.compile(function () {
        console.log('Regenerated')
        done()
      })
    })
  })
}

Generator.prototype.registerPreprocessor = function (preprocessor) {
  for (var i = 0; i < preprocessor.extensions.length; i++) {
    if (this.preprocessors[preprocessor.extensions[i]]) {
      console.warn('Warning: Extension ' + preprocessor.extensions[i] + ' already registered; overwriting existing handler.')
    }
    this.preprocessors[preprocessor.extensions[i]] = preprocessor
  }
}

Generator.prototype.registerCompiler = function (compilerFunction) {
  this.compilers.push(compilerFunction)
}

Generator.prototype.preprocess = function (callback) {
  var self = this

  if (this.preprocessTarget != null) throw new Error('self.preprocessTarget is not null/undefined')
  this.preprocessTarget = mktemp.createDirSync(this.dest + '/preprocess_target-XXXXXX.tmp')

  var srcRoot = this.src
  var walker = walk.walk(srcRoot, {})

  // Be deterministic
  walker.on('names', function (fileRoot, nodeNamesArray) { nodeNamesArray.sort() })

  walker.on('directory', function (dirRoot, dirStats, next) {
    var relativePath = dirRoot.slice(srcRoot.length + 1)
    if (relativePath.length > 0) relativePath = relativePath + '/'
    fs.mkdirSync(self.preprocessTarget + '/' + relativePath + dirStats.name)
    next()
  })

  function processFile (fileRoot, fileStats, next) {
    var fileInfo = helpers.getFileInfo(srcRoot, fileRoot, fileStats)
    var extensions = []
    for (var e in self.preprocessors) {
      if (self.preprocessors.hasOwnProperty(e)) {
        extensions.push(e)
      }
    }
    extensions.sort()
    extensions.push(null) // copy if no preprocessor found
    for (var i = 0; i < extensions.length; i++) {
      var extension = extensions[i]
      if (extension === null) {
        // No preprocessor; copy
        var depth = (self.preprocessTarget + '/' + fileInfo.relativePath).split('/').length - 1
        var parentDirs = new Array(depth + 1).join('../')
        fs.symlinkSync(parentDirs + fileInfo.fullPath, self.preprocessTarget + '/' + fileInfo.relativePath)
        next()
        break
      } else if (fileInfo.extension === extension) {
        var preprocessor = self.preprocessors[extension]
        var targetPath = self.preprocessTarget + '/' + fileInfo.moduleName + '.' + (preprocessor.targetExtension || extension)
        preprocessor.run(fileInfo, targetPath, next)
        break
      }
    }
  }

  walker.on('file', processFile)
  walker.on('symbolicLink', processFile) // TODO: check if target is a file

  walker.on('errors', function (fileRoot, nodeStatsArray, next) {
    // ERR
    console.error('Warning: unhandled error(s)', nodeStatsArray)
    next()
  })

  walker.on('end', function () {
    callback()
  })
}

Generator.prototype.compile = function (callback) {
  var self = this
  if (this.compileTarget != null) throw new Error('self.compileTarget is not null/undefined')
  this.compileTarget = mktemp.createDirSync(this.dest + '/compile_target-XXXXXX.tmp')
  async.eachSeries(self.compilers, function (compiler, callback) {
    compiler.run(self.preprocessTarget, self.compileTarget, callback)
  }, function (err) {
    callback()
  })
}

Generator.prototype.createDest = function () {
  if (this.dest != null) throw new Error('Expected generator.dest to be null/undefined; did something go out of sync?')
  this.dest = mktemp.createDirSync('broccoli-XXXXXX.tmp')
}

Generator.prototype.cleanup = function (callback) {
  if (this.dest != null) {
    rimraf(this.dest, callback)
  }
  this.dest = null
  this.preprocessTarget = null
  this.compileTarget = null
}

Generator.prototype.serve = function () {
  var self = this

  this.regenerate()

  var gaze = new Gaze([this.src + '/**/*', __dirname + '/vendor/**/*'])
  gaze.on('all', function (event, filepath) {
    console.error(event, filepath)
    // We should debounce this, e.g. when you do `touch *`
    self.regenerate()
  })

  console.log('Serving on http://localhost:8000/')
  var server = hapi.createServer('localhost', 8000)

  server.route({
    method: 'GET',
    path: '/{path*}',
    handler: {
      directory: {
        path: function (request) {
          return self.compileTarget
        }
      }
    }
  })

  server.ext('onRequest', function (request, next) {
    // `synchronized` delays serving until we've finished regenerating
    synchronized(self, function (done) {
      done() // release lock immediately
      next()
    })
  })

  server.start()
}

var ES6TemplatePreprocessor = function (options) {
  for (var key in options) {
    if (options.hasOwnProperty(key)) {
      this[key] = options[key]
    }
  }
}

ES6TemplatePreprocessor.prototype.run = function (fileInfo, targetPath, callback) {
  var fileContents = fs.readFileSync(fileInfo.fullPath).toString()
  var moduleContents = 'export default ' + this.compileFunction +
    '("' + jsStringEscape(fileContents) + '");\n'
  fs.writeFileSync(targetPath, moduleContents)
  callback()
}

ES6TemplatePreprocessor.prototype.compileFunction = ''
ES6TemplatePreprocessor.prototype.extensions = [] // set when instantiating
ES6TemplatePreprocessor.prototype.targetExtension = 'js'

var ES6Compiler = function () {}

ES6Compiler.prototype.run = function (src, dest, callback) {
  var appJs = fs.createWriteStream(dest + '/app.js')

  // Write vendor files (this needs to go away)
  var files = fs.readdirSync(__dirname + '/vendor')
  for (var i = 0; i < files.length; i++) {
    var contents = fs.readFileSync(__dirname + '/vendor/' + files[i])
    appJs.write(contents)
  }

  // Make me configurable, or remove me?
  var modulePrefix = 'appkit/'

  // Write app files
  function compileJavascripts(callback) {
    helpers.walkFiles(src, 'js', function (fileInfo, fileStats, next) {
      var fileContents = fs.readFileSync(fileInfo.fullPath).toString()
      var compiler = new ES6Transpiler(fileContents, modulePrefix + fileInfo.moduleName)
      var output = compiler.toAMD() // ERR: handle exceptions
      appJs.write(output + '\n')
      next()
    }, function () {
      callback()
    })
  }

  compileJavascripts(function () {
    appJs.end()
    callback()
  })
}

var StaticFileCompiler = function (options) {
  this.files = []
  for (var key in options) {
    if (options.hasOwnProperty(key)) {
      this[key] = options[key]
    }
  }
  for (var i = 0; i < this.files.length; i++) {
    if (this.files[i].length > 0 && this.files[i][0] === '/') {
      throw new Error('Patterns must not be absolute: ' + this.files[i])
    }
  }
}

StaticFileCompiler.prototype.run = function (src, dest, callback) {
  var globPatterns = this.files.map(function (pattern) {
    return src + '/' + pattern
  })
  // Constructing globs like `{**/*.html,**/*.png}` should work reliably. If
  // not, we may need to switch to some multi-glob module.
  var combinedPattern = globPatterns.join(',')
  if (globPatterns.length > 1) {
    combinedPattern = '{' + combinedPattern + '}'
  }
  var paths = glob.sync(combinedPattern)
  for (var i = 0; i < paths.length; i++) {
    var relativePath = path.relative(src, paths[i])
    var destPath = dest + '/' + relativePath
    var contents = fs.readFileSync(paths[i])
    mkdirp.sync(path.dirname(destPath))
    fs.writeFileSync(destPath, contents)
  }
  callback()
}

var generator = new Generator('app')
generator.registerPreprocessor(new ES6TemplatePreprocessor({
  extensions: ['hbs', 'handlebars'],
  compileFunction: 'Ember.Handlebars.compile'
}))
generator.registerCompiler(new ES6Compiler)
generator.registerCompiler(new StaticFileCompiler({
  files: ['**/*.html']
}))
process.on('SIGINT', function () {
  synchronized(generator, function () {
    generator.cleanup(function () {
      process.exit()
    })
  })
  setTimeout(function () {
    console.error('Error: Something is slow or jammed, and we could not clean up in time.')
    console.error('This should *never* happen. Please file a bug report.')
    process.exit()
  }, 300)
})
generator.serve()
<commit_msg>Simplify preprocessor signature<commit_after>var fs = require('fs')
var path = require('path')
var mktemp = require('mktemp')
var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var walk = require('walk')
var glob = require('glob')
var hapi = require('hapi')
var async = require('async')
var synchronized = require('synchronized')
var Gaze = require('gaze').Gaze
var ES6Transpiler = require('es6-module-transpiler').Compiler
var jsStringEscape = require('js-string-escape')

var helpers = require('./lib/helpers')

var Generator
exports.Generator = Generator = function (src) {
  this.src = src
  this.preprocessors = {}
  this.compilers = []
}

Generator.prototype.regenerate = function () {
  var self = this
  synchronized(this, function (done) {
    self.cleanup(function() { /* do not wait for cleanup to finish */ })
    self.createDest() // create pristine directory with new name

    self.preprocess(function () {
      self.compile(function () {
        console.log('Regenerated')
        done()
      })
    })
  })
}

Generator.prototype.registerPreprocessor = function (preprocessor) {
  for (var i = 0; i < preprocessor.extensions.length; i++) {
    if (this.preprocessors[preprocessor.extensions[i]]) {
      console.warn('Warning: Extension ' + preprocessor.extensions[i] + ' already registered; overwriting existing handler.')
    }
    this.preprocessors[preprocessor.extensions[i]] = preprocessor
  }
}

Generator.prototype.registerCompiler = function (compilerFunction) {
  this.compilers.push(compilerFunction)
}

Generator.prototype.preprocess = function (callback) {
  var self = this

  if (this.preprocessTarget != null) throw new Error('self.preprocessTarget is not null/undefined')
  this.preprocessTarget = mktemp.createDirSync(this.dest + '/preprocess_target-XXXXXX.tmp')

  var srcRoot = this.src
  var walker = walk.walk(srcRoot, {})

  // Be deterministic
  walker.on('names', function (fileRoot, nodeNamesArray) { nodeNamesArray.sort() })

  walker.on('directory', function (dirRoot, dirStats, next) {
    var relativePath = dirRoot.slice(srcRoot.length + 1)
    if (relativePath.length > 0) relativePath = relativePath + '/'
    fs.mkdirSync(self.preprocessTarget + '/' + relativePath + dirStats.name)
    next()
  })

  function processFile (fileRoot, fileStats, next) {
    var fileInfo = helpers.getFileInfo(srcRoot, fileRoot, fileStats)
    var extensions = []
    for (var e in self.preprocessors) {
      if (self.preprocessors.hasOwnProperty(e)) {
        extensions.push(e)
      }
    }
    extensions.sort()
    extensions.push(null) // copy if no preprocessor found
    for (var i = 0; i < extensions.length; i++) {
      var extension = extensions[i]
      if (extension === null) {
        // No preprocessor; copy
        var depth = (self.preprocessTarget + '/' + fileInfo.relativePath).split('/').length - 1
        var parentDirs = new Array(depth + 1).join('../')
        fs.symlinkSync(parentDirs + fileInfo.fullPath, self.preprocessTarget + '/' + fileInfo.relativePath)
        next()
        break
      } else if (fileInfo.extension === extension) {
        var preprocessor = self.preprocessors[extension]
        var destFilePath = self.preprocessTarget + '/' + fileInfo.moduleName + '.' + (preprocessor.targetExtension || extension)
        preprocessor.run(fileInfo.fullPath, destFilePath, next)
        break
      }
    }
  }

  walker.on('file', processFile)
  walker.on('symbolicLink', processFile) // TODO: check if target is a file

  walker.on('errors', function (fileRoot, nodeStatsArray, next) {
    // ERR
    console.error('Warning: unhandled error(s)', nodeStatsArray)
    next()
  })

  walker.on('end', function () {
    callback()
  })
}

Generator.prototype.compile = function (callback) {
  var self = this
  if (this.compileTarget != null) throw new Error('self.compileTarget is not null/undefined')
  this.compileTarget = mktemp.createDirSync(this.dest + '/compile_target-XXXXXX.tmp')
  async.eachSeries(self.compilers, function (compiler, callback) {
    compiler.run(self.preprocessTarget, self.compileTarget, callback)
  }, function (err) {
    callback()
  })
}

Generator.prototype.createDest = function () {
  if (this.dest != null) throw new Error('Expected generator.dest to be null/undefined; did something go out of sync?')
  this.dest = mktemp.createDirSync('broccoli-XXXXXX.tmp')
}

Generator.prototype.cleanup = function (callback) {
  if (this.dest != null) {
    rimraf(this.dest, callback)
  }
  this.dest = null
  this.preprocessTarget = null
  this.compileTarget = null
}

Generator.prototype.serve = function () {
  var self = this

  this.regenerate()

  var gaze = new Gaze([this.src + '/**/*', __dirname + '/vendor/**/*'])
  gaze.on('all', function (event, filepath) {
    console.error(event, filepath)
    // We should debounce this, e.g. when you do `touch *`
    self.regenerate()
  })

  console.log('Serving on http://localhost:8000/')
  var server = hapi.createServer('localhost', 8000)

  server.route({
    method: 'GET',
    path: '/{path*}',
    handler: {
      directory: {
        path: function (request) {
          return self.compileTarget
        }
      }
    }
  })

  server.ext('onRequest', function (request, next) {
    // `synchronized` delays serving until we've finished regenerating
    synchronized(self, function (done) {
      done() // release lock immediately
      next()
    })
  })

  server.start()
}

var ES6TemplatePreprocessor = function (options) {
  for (var key in options) {
    if (options.hasOwnProperty(key)) {
      this[key] = options[key]
    }
  }
}

ES6TemplatePreprocessor.prototype.run = function (srcFilePath, destFilePath, callback) {
  var fileContents = fs.readFileSync(srcFilePath).toString()
  var moduleContents = 'export default ' + this.compileFunction +
    '("' + jsStringEscape(fileContents) + '");\n'
  fs.writeFileSync(destFilePath, moduleContents)
  callback()
}

ES6TemplatePreprocessor.prototype.compileFunction = ''
ES6TemplatePreprocessor.prototype.extensions = [] // set when instantiating
ES6TemplatePreprocessor.prototype.targetExtension = 'js'

var ES6Compiler = function () {}

ES6Compiler.prototype.run = function (src, dest, callback) {
  var appJs = fs.createWriteStream(dest + '/app.js')

  // Write vendor files (this needs to go away)
  var files = fs.readdirSync(__dirname + '/vendor')
  for (var i = 0; i < files.length; i++) {
    var contents = fs.readFileSync(__dirname + '/vendor/' + files[i])
    appJs.write(contents)
  }

  // Make me configurable, or remove me?
  var modulePrefix = 'appkit/'

  // Write app files
  function compileJavascripts(callback) {
    helpers.walkFiles(src, 'js', function (fileInfo, fileStats, next) {
      var fileContents = fs.readFileSync(fileInfo.fullPath).toString()
      var compiler = new ES6Transpiler(fileContents, modulePrefix + fileInfo.moduleName)
      var output = compiler.toAMD() // ERR: handle exceptions
      appJs.write(output + '\n')
      next()
    }, function () {
      callback()
    })
  }

  compileJavascripts(function () {
    appJs.end()
    callback()
  })
}

var StaticFileCompiler = function (options) {
  this.files = []
  for (var key in options) {
    if (options.hasOwnProperty(key)) {
      this[key] = options[key]
    }
  }
  for (var i = 0; i < this.files.length; i++) {
    if (this.files[i].length > 0 && this.files[i][0] === '/') {
      throw new Error('Patterns must not be absolute: ' + this.files[i])
    }
  }
}

StaticFileCompiler.prototype.run = function (src, dest, callback) {
  var globPatterns = this.files.map(function (pattern) {
    return src + '/' + pattern
  })
  // Constructing globs like `{**/*.html,**/*.png}` should work reliably. If
  // not, we may need to switch to some multi-glob module.
  var combinedPattern = globPatterns.join(',')
  if (globPatterns.length > 1) {
    combinedPattern = '{' + combinedPattern + '}'
  }
  var paths = glob.sync(combinedPattern)
  for (var i = 0; i < paths.length; i++) {
    var relativePath = path.relative(src, paths[i])
    var destPath = dest + '/' + relativePath
    var contents = fs.readFileSync(paths[i])
    mkdirp.sync(path.dirname(destPath))
    fs.writeFileSync(destPath, contents)
  }
  callback()
}

var generator = new Generator('app')
generator.registerPreprocessor(new ES6TemplatePreprocessor({
  extensions: ['hbs', 'handlebars'],
  compileFunction: 'Ember.Handlebars.compile'
}))
generator.registerCompiler(new ES6Compiler)
generator.registerCompiler(new StaticFileCompiler({
  files: ['**/*.html']
}))
process.on('SIGINT', function () {
  synchronized(generator, function () {
    generator.cleanup(function () {
      process.exit()
    })
  })
  setTimeout(function () {
    console.error('Error: Something is slow or jammed, and we could not clean up in time.')
    console.error('This should *never* happen. Please file a bug report.')
    process.exit()
  }, 300)
})
generator.serve()
<|endoftext|>


<commit_before>/*!
 * expand-brackets <https://github.com/jonschlinkert/expand-brackets>
 *
 * Copyright (c) 2015 Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

/**
 * POSIX character classes
 */

var POSIX = {
  alnum: 'a-zA-Z0-9',
  alpha: 'a-zA-Z',
  blank: ' \\t',
  cntrl: '\\x00-\\x1F\\x7F',
  digit: '0-9',
  graph: '\\x21-\\x7E',
  lower: 'a-z',
  print: '\\x20-\\x7E',
  punct: '!"#$%&\'()\\*+,-./:;<=>?@[\\]^_`{|}~',
  space: ' \\t\\r\\n\\v\\f',
  upper: 'A-Z',
  word:  'A-Za-z0-9_',
  xdigit: 'A-Fa-f0-9',
};

/**
 * Expose `brackets`
 */

module.exports = brackets;

function brackets(str) {
  var negated = false;

  if (str.indexOf('[^') !== -1) {
    negated = true;
    str = str.split('[^').join('[');
  }
  if (str.indexOf('[!') !== -1) {
    negated = true;
    str = str.split('[!').join('[');
  }

  var a = str.split('[');
  var b = str.split(']');
  var imbalanced = a.length !== b.length;

  var parts = str.split(/(?::\]\[:|\[?\[:|:\]\]?)/);
  var len = parts.length, i = 0;
  var end = '', beg = '';
  var res = [];

  while (len--) {
    var inner = parts[i++];
    if (inner === '^[!' || inner === '[!') {
      inner = '';
      negated = true;
    }

    var prefix = negated ? '^' : '';
    var ch = POSIX[inner];

    if (ch) {
      res.push('[' + prefix + ch + ']');
    } else if (inner) {
      if (/^\[?\w-\w\]?$/.test(inner)) {
        if (i === parts.length) {
          res.push('[' + prefix + inner);
        } else if (i === 1) {
          res.push(prefix + inner + ']');
        } else {
          res.push(prefix + inner);
        }
      } else {
        if (i === 1) {
          beg += inner;
        } else if (i === parts.length) {
          end += inner;
        } else {
          res.push('[' + prefix + inner + ']');
        }
      }
    }
  }

  var result = res.join('|');
  var len = res.length || 1;
  if (len > 1) {
    result = '(?:' + result + ')';
    len = 1;
  }
  if (beg) {
    len++;
    if (beg.charAt(0) === '[') {
      if (imbalanced) {
        beg = '\\[' + beg.slice(1);
      } else {
        beg += ']';
      }
    }
    result = beg + result;
  }
  if (end) {
    len++;
    if (end.slice(-1) === ']') {
      if (imbalanced) {
        end = end.slice(0, end.length - 1) + '\\]';
      } else {
        end = '[' + end;
      }
    }
    result += end;
  }

  if (len > 1) {
    result = result.split('][').join(']|[');
    if (result.indexOf('|') !== -1 && !/\(\?/.test(result)) {
      result = '(?:' + result + ')';
    }
  }

  result = result.replace(/\[+=|=\]+/g, '\\b');
  return result;
}

brackets.makeRe = function (pattern) {
  try {
    return new RegExp(brackets(pattern));
  } catch (err) {}
};

brackets.isMatch = function (str, pattern) {
  try {
    return brackets.makeRe(pattern).test(str);
  } catch (err) {
    return false;
  }
};

brackets.match = function (arr, pattern) {
  var len = arr.length, i = 0;
  var res = arr.slice();

  var re = brackets.makeRe(pattern);
  while (i < len) {
    var ele = arr[i++];
    if (!re.test(ele)) {
      continue;
    }
    res.splice(i, 1);
  }
  return res;
};
<commit_msg>check for character classes before trying to expand<commit_after>/*!
 * expand-brackets <https://github.com/jonschlinkert/expand-brackets>
 *
 * Copyright (c) 2015 Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

var isPosixBracket = require('is-posix-bracket');

/**
 * POSIX character classes
 */

var POSIX = {
  alnum: 'a-zA-Z0-9',
  alpha: 'a-zA-Z',
  blank: ' \\t',
  cntrl: '\\x00-\\x1F\\x7F',
  digit: '0-9',
  graph: '\\x21-\\x7E',
  lower: 'a-z',
  print: '\\x20-\\x7E',
  punct: '!"#$%&\'()\\*+,-./:;<=>?@[\\]^_`{|}~',
  space: ' \\t\\r\\n\\v\\f',
  upper: 'A-Z',
  word:  'A-Za-z0-9_',
  xdigit: 'A-Fa-f0-9',
};

/**
 * Expose `brackets`
 */

module.exports = brackets;

function brackets(str) {
  if (!isPosixBracket(str)) {
    return str;
  }

  var negated = false;
  if (str.indexOf('[^') !== -1) {
    negated = true;
    str = str.split('[^').join('[');
  }
  if (str.indexOf('[!') !== -1) {
    negated = true;
    str = str.split('[!').join('[');
  }

  var a = str.split('[');
  var b = str.split(']');
  var imbalanced = a.length !== b.length;

  var parts = str.split(/(?::\]\[:|\[?\[:|:\]\]?)/);
  var len = parts.length, i = 0;
  var end = '', beg = '';
  var res = [];

  // start at the end (innermost) first
  while (len--) {
    var inner = parts[i++];
    if (inner === '^[!' || inner === '[!') {
      inner = '';
      negated = true;
    }

    var prefix = negated ? '^' : '';
    var ch = POSIX[inner];

    if (ch) {
      res.push('[' + prefix + ch + ']');
    } else if (inner) {
      if (/^\[?\w-\w\]?$/.test(inner)) {
        if (i === parts.length) {
          res.push('[' + prefix + inner);
        } else if (i === 1) {
          res.push(prefix + inner + ']');
        } else {
          res.push(prefix + inner);
        }
      } else {
        if (i === 1) {
          beg += inner;
        } else if (i === parts.length) {
          end += inner;
        } else {
          res.push('[' + prefix + inner + ']');
        }
      }
    }
  }

  var result = res.join('|');
  var rlen = res.length || 1;
  if (rlen > 1) {
    result = '(?:' + result + ')';
    rlen = 1;
  }
  if (beg) {
    rlen++;
    if (beg.charAt(0) === '[') {
      if (imbalanced) {
        beg = '\\[' + beg.slice(1);
      } else {
        beg += ']';
      }
    }
    result = beg + result;
  }
  if (end) {
    rlen++;
    if (end.slice(-1) === ']') {
      if (imbalanced) {
        end = end.slice(0, end.length - 1) + '\\]';
      } else {
        end = '[' + end;
      }
    }
    result += end;
  }

  if (rlen > 1) {
    result = result.split('][').join(']|[');
    if (result.indexOf('|') !== -1 && !/\(\?/.test(result)) {
      result = '(?:' + result + ')';
    }
  }

  result = result.replace(/\[+=|=\]+/g, '\\b');
  return result;
}

brackets.makeRe = function (pattern) {
  try {
    return new RegExp(brackets(pattern));
  } catch (err) {}
};

brackets.isMatch = function (str, pattern) {
  try {
    return brackets.makeRe(pattern).test(str);
  } catch (err) {
    return false;
  }
};

brackets.match = function (arr, pattern) {
  var len = arr.length, i = 0;
  var res = arr.slice();

  var re = brackets.makeRe(pattern);
  while (i < len) {
    var ele = arr[i++];
    if (!re.test(ele)) {
      continue;
    }
    res.splice(i, 1);
  }
  return res;
};
<|endoftext|>


<commit_before>/**
 * Created by developer on 5/18/15.
 */
/**
 * Module dependencies
 */

var path = require('path');
var util = require('util');
var Writable = require('stream').Writable;
var _ = require('lodash');
var concat = require('concat-stream');
var async = require('async');

/**
 * skipper-orientdb
 *
 * @param  {Object} globalOpts
 * @return {Object}
 */

module.exports = function OrientDBStore(globalOpts) {
    globalOpts = globalOpts || {};

    _.defaults(globalOpts, {
        maxChunkSize: 4096, //1MB
        filesCollection: 'files',
        filesChunksCollection: 'files_chunks'
    });

    //var getConnection = _connectionBuilder(globalOpts);

    var files = function () {
            return globalOpts.filesCollection;
        },
        filesChunks = function () {
            return globalOpts.filesChunksCollection;
        };

    var adapter = {
        ls: function (dirname, cb) {

            files().find({where: {'metadata.dirname': dirname}}).then(function (err, files) {
                if (err) return cb(err);
                return cb(null, files);
            });

        },

        read: function (fd, cb) {
            console.log("Not implemented yet!!!");
            return;
            GridStore.exist(db, fd, globalOpts.bucket, function (err, exists) {
                if (err) {
                    db.close();
                    return cb(err);
                }
                if (!exists) {
                    err = new Error('ENOENT');
                    err.name = 'Error (ENOENT)';
                    err.code = 'ENOENT';
                    err.status = 404;
                    err.message = util.format('No file exists in this mongo gridfs bucket with that file descriptor (%s)', fd);
                    db.close();
                    return cb(err);
                }

                var gridStore = new GridStore(db, fd, 'r', {root: globalOpts.bucket});
                gridStore.open(function (err, gridStore) {
                    if (err) {
                        db.close();
                        return cb(err);
                    }
                    var stream = gridStore.stream();
                    stream.pipe(concat(function (data) {
                        db.close();
                        return cb(null, data);
                    }));

                    stream.on('error', function (err) {
                        db.close();
                        return cb(err);
                    });

                    stream.on('close', function () {
                        db.close();
                    });
                });
            });

        },

        readLastVersion: function (fd, cb) {
            console.log("Not implemented yet!!!");
            return;
            this.readVersion(fd, -1, cb);

        },

        readVersion: function (fd, version, cb) {
            console.log("Not implemented yet!!!");
            return;
            MongoClient.connect(globalOpts.uri, {native_parser: true}, function (err, db) {
                if (err) {
                    return cb(err);
                }
                var gfs = Grid(db, mongo);
                gfs.collection(globalOpts.bucket).ensureIndex({filename: 1, uploadDate: -1}, function (err, indexName) {
                    if (err) {
                        db.close();
                        return cb(err);
                    }

                    var cursor = gfs.collection(globalOpts.bucket).find({filename: fd});
                    if (version < 0) {
                        var skip = Math.abs(version) - 1;
                        cursor.limit(-1).skip(skip).sort({uploadDate: -1}); //'desc
                    } else {
                        cursor.limit(-1).skip(version).sort({uploadDate: 1}); //'asc'
                    }

                    cursor.next(function (err, file) {

                        if (err) {
                            console.log(err);
                            db.close();
                            return cb(err);
                        }
                        if (!file) {
                            err = new Error('ENOENT');
                            err.name = 'Error (ENOENT)';
                            err.code = 'ENOENT';
                            err.status = 404;
                            err.message = util.format('No file exists in this mongo gridfs bucket with that file descriptor (%s)', fd);
                            db.close();
                            return cb(err);
                        }

                        var gridStore = new GridStore(db, file._id, 'r', {root: globalOpts.bucket});
                        gridStore.open(function (err, gridStore) {
                            if (err) {
                                db.close();
                                return cb(err);
                            }

                            var stream = gridStore.stream();
                            stream.pipe(concat(function (data) {
                                db.close();
                                return cb(null, data);
                            }));

                            stream.on('error', function (err) {
                                db.close();
                                return cb(err);
                            });

                            stream.on('close', function () {
                                db.close();
                            });
                        });
                    });
                });
            });
        },

        rm: function (fd, cb) {
            console.log("Not implemented yet!!!");
        },

        /**
         * A simple receiver for Skipper that writes Upstreams to
         * gridfs
         *
         *
         * @param  {Object} options
         * @return {Stream.Writable}
         */
        receive: function GridFSReceiver(options) {
            options = options || {};
            options = _.defaults(options, globalOpts);

            var receiver__ = Writable({
                objectMode: true
            });

            // This `_write` method is invoked each time a new file is received
            // from the Readable stream (Upstream) which is pumping filestreams
            // into this receiver.  (filename === `__newFile.filename`).
            receiver__._write = function onFile(__newFile, encoding, done) {
                // console.log('write fd:',__newFile.fd);
                var fd = __newFile.fd;

                receiver__.once('error', function (err, db) {
                    // console.log('ERROR ON RECEIVER__ ::',err);
                    //db.close();
                    done(err);
                });

                var bytesCount = parseInt(__newFile.byteCount);
                files().create({
                    filename: fd,
                    contentType: 'binary/octet-stream',
                    length: bytesCount,
                    chunkSize: options.maxChunkSize,
                    metadata: {
                        fd: fd,
                        dirname: __newFile.dirname || path.dirname(fd)
                    }
                }).exec(function (err, file) {
                    if (err) {
                        receiver__.emit('error', err);
                        return;
                    }
                    var totalBytesRead = 0;
                    var chunks = bytesCount / options.maxChunkSize;

                    var index = 0, chunkRegistry = [];
                    while (index < chunks) {
                        chunkRegistry.push({starts: (index * options.maxChunkSize), index: index});
                        index++;
                    }
                    async.eachSeries(chunkRegistry, function (current, next) {
                        var chunkData = __newFile.read(options.maxChunkSize);

                        filesChunks().getDB().record.create({
                            '@class': options.filesChunksCollection,
                            files_id: file.id,
                            data: chunkData,
                            n: current.index
                        }).exec(function (err1, fileChunk) {
                            next(err1);
                        });

                    }, function (err) {
                        done(err);
                    });
                });

            };
            return receiver__;
        }
    };

    return adapter;

    // Helper methods:
    ////////////////////////////////////////////////////////////////////////////////

};<commit_msg>removed java and reverted back to javascript<commit_after>/**
 * Created by developer on 5/18/15.
 */
/**
 * Module dependencies
 */

var path = require('path');
var util = require('util');
var Writable = require('stream').Writable;
var _ = require('lodash');
var concat = require('concat-stream');
var async = require('async');

/**
 * skipper-orientdb
 *
 * @param  {Object} globalOpts
 * @return {Object}
 */

module.exports = function OrientDBStore(globalOpts) {
    globalOpts = globalOpts || {};

    _.defaults(globalOpts, {
        maxChunkSize: 4096, //1MB
        filesCollection: 'files',
        filesChunksCollection: 'fileschunks',
        filesChunksClusterName: 'fileschunks'
    });

    //var getConnection = _connectionBuilder(globalOpts);

    var files = function () {
            return globalOpts.filesCollection;
        },
        filesChunks = function () {
            return globalOpts.filesChunksCollection;
        };

    var adapter = {
        ls: function (dirname, cb) {

            files().find({where: {'metadata.dirname': dirname}}).then(function (err, files) {
                if (err) return cb(err);
                return cb(null, files);
            });

        },

        read: function (fd, cb) {
            console.log("Not implemented yet!!!");
            return;
            GridStore.exist(db, fd, globalOpts.bucket, function (err, exists) {
                if (err) {
                    db.close();
                    return cb(err);
                }
                if (!exists) {
                    err = new Error('ENOENT');
                    err.name = 'Error (ENOENT)';
                    err.code = 'ENOENT';
                    err.status = 404;
                    err.message = util.format('No file exists in this mongo gridfs bucket with that file descriptor (%s)', fd);
                    db.close();
                    return cb(err);
                }

                var gridStore = new GridStore(db, fd, 'r', {root: globalOpts.bucket});
                gridStore.open(function (err, gridStore) {
                    if (err) {
                        db.close();
                        return cb(err);
                    }
                    var stream = gridStore.stream();
                    stream.pipe(concat(function (data) {
                        db.close();
                        return cb(null, data);
                    }));

                    stream.on('error', function (err) {
                        db.close();
                        return cb(err);
                    });

                    stream.on('close', function () {
                        db.close();
                    });
                });
            });

        },

        readLastVersion: function (fd, cb) {
            console.log("Not implemented yet!!!");
            return;
            this.readVersion(fd, -1, cb);

        },

        readVersion: function (fd, version, cb) {
            console.log("Not implemented yet!!!");
            return;
            MongoClient.connect(globalOpts.uri, {native_parser: true}, function (err, db) {
                if (err) {
                    return cb(err);
                }
                var gfs = Grid(db, mongo);
                gfs.collection(globalOpts.bucket).ensureIndex({filename: 1, uploadDate: -1}, function (err, indexName) {
                    if (err) {
                        db.close();
                        return cb(err);
                    }

                    var cursor = gfs.collection(globalOpts.bucket).find({filename: fd});
                    if (version < 0) {
                        var skip = Math.abs(version) - 1;
                        cursor.limit(-1).skip(skip).sort({uploadDate: -1}); //'desc
                    } else {
                        cursor.limit(-1).skip(version).sort({uploadDate: 1}); //'asc'
                    }

                    cursor.next(function (err, file) {

                        if (err) {
                            console.log(err);
                            db.close();
                            return cb(err);
                        }
                        if (!file) {
                            err = new Error('ENOENT');
                            err.name = 'Error (ENOENT)';
                            err.code = 'ENOENT';
                            err.status = 404;
                            err.message = util.format('No file exists in this mongo gridfs bucket with that file descriptor (%s)', fd);
                            db.close();
                            return cb(err);
                        }

                        var gridStore = new GridStore(db, file._id, 'r', {root: globalOpts.bucket});
                        gridStore.open(function (err, gridStore) {
                            if (err) {
                                db.close();
                                return cb(err);
                            }

                            var stream = gridStore.stream();
                            stream.pipe(concat(function (data) {
                                db.close();
                                return cb(null, data);
                            }));

                            stream.on('error', function (err) {
                                db.close();
                                return cb(err);
                            });

                            stream.on('close', function () {
                                db.close();
                            });
                        });
                    });
                });
            });
        },

        rm: function (fd, cb) {
            console.log("Not implemented yet!!!");
        },

        /**
         * A simple receiver for Skipper that writes Upstreams to
         * gridfs
         *
         *
         * @param  {Object} options
         * @return {Stream.Writable}
         */
        receive: function GridFSReceiver(options) {
            options = options || {};
            options = _.defaults(options, globalOpts);

            var receiver__ = Writable({
                objectMode: true
            });

            // This `_write` method is invoked each time a new file is received
            // from the Readable stream (Upstream) which is pumping filestreams
            // into this receiver.  (filename === `__newFile.filename`).
            receiver__._write = function onFile(__newFile, encoding, done) {
                // console.log('write fd:',__newFile.fd);
                var fd = __newFile.fd;

                receiver__.once('error', function (err, db) {
                    // console.log('ERROR ON RECEIVER__ ::',err);
                    //db.close();
                    done(err);
                });

                var bytesCount = parseInt(__newFile.byteCount);
                files().create({
                    filename: fd,
                    contentType: 'binary/octet-stream',
                    length: bytesCount,
                    chunkSize: options.maxChunkSize,
                    metadata: {
                        fd: fd,
                        dirname: __newFile.dirname || path.dirname(fd)
                    }
                }).exec(function (err, file) {
                    if (err) {
                        receiver__.emit('error', err);
                        return;
                    }
                    var totalBytesRead = 0;
                    var chunks = bytesCount / options.maxChunkSize;

                    var index = 0, chunkRegistry = [];
                    while (index < chunks) {
                        chunkRegistry.push({starts: (index * options.maxChunkSize), index: index});
                        index++;
                    }
                    async.eachSeries(chunkRegistry, function (current, next) {
                        var chunkData = __newFile.read(options.maxChunkSize);

                        files().getDB().record.create({
                            '@class': options.filesChunksClusterName,
                            files_id: file.id,
                            data: chunkData,
                            n: current.index
                        }).exec(function (err1, fileChunk) {
                            next(err1);
                        });

                    }, function (err) {
                        done(err);
                    });
                });

            };
            return receiver__;
        }
    };

    return adapter;

    // Helper methods:
    ////////////////////////////////////////////////////////////////////////////////

};<|endoftext|>


<commit_before>var request = require('request')

module.exports = function (refreshToken, clientID, clientSecret, next) {
  var opts = {
    uri: 'https://accounts.spotify.com/api/token',
    json: {
      grant_type: 'refresh_token',
      refresh_token: refreshToken
      client_id: clientID,
      client_secret: clientSecret
    }
  }
  return request(opts, next)
}
<commit_msg>dunno how to javascript<commit_after>var request = require('request')

module.exports = function (refreshToken, clientID, clientSecret, next) {
  var opts = {
    uri: 'https://accounts.spotify.com/api/token',
    json: {
      'grant_type': 'refresh_token',
      'refresh_token': refreshToken
      'client_id': clientID,
      'client_secret': clientSecret
    }
  }
  return request(opts, next)
}
<|endoftext|>


<commit_before>'use strict';

var istanbul = require('istanbul');

module.exports = function(source) {
    var instrumenter = new istanbul.Instrumenter({
        embedSource: true,
        noAutoWrap: true
    });

    if (this.cacheable) {
        this.cacheable();
    }

    return instrumenter.instrumentSync(source, this.request);
};
<commit_msg>Replace the `request` property with `resourcePath`<commit_after>'use strict';

var istanbul = require('istanbul');

module.exports = function(source) {
    var instrumenter = new istanbul.Instrumenter({
        embedSource: true,
        noAutoWrap: true
    });

    if (this.cacheable) {
        this.cacheable();
    }

    return instrumenter.instrumentSync(source, this.resourcePath);
};
<|endoftext|>


<commit_before>glob = require('glob')
path = require('path')

module.exports = function(url, prev, done) {
  if(!glob.hasMagic(url)) {
    // normal url, resolve to an import of the file
    if(url.indexOf('|prev=') === 0) {
      // if there is a |prev keyword, resolve file relative to that file.. so if
      // you do @import |prev=~|foo.sass, it will resolve to ~/foo.sass
      var prev_dir = null
      var prev_re = /^\|prev=([^\|]*?)\|/
      var matches = url.match(prev_re)

      if(matches.length) {
        prev_dir = path.dirname(matches[1])
        url = url.replace(prev_re, '')
        url = path.resolve(prev_dir, url)
        done({file: url})
        return void 0;
      }
    } else {
      done({file: url})
      return void 0;
    }
  }

  // search for scss | sass files if no extension provided

  // url is a glob, like foo/*.sass, resolve to importing all matching files, so
  // if there is foo/1.sass and foo/2.sass, it will import both of those files
  var cwd = path.dirname(prev)
  glob(url, {cwd: cwd}, function (err, files) {
    var ret = {
      contents: "\n"
    }

    // import all the matched files, passing through the current file. this is
    // because if you didn't, the path will resolve relative to foo/*.sass,
    // which will fail since that is not an actual path.
    files.forEach(function(file) {
      var ext = path.extname(file)
      var abspath = path.resolve(cwd, file)

      if(/^\.s[ac]ss$/.test(ext) && prev !== abspath) {
        // don't import self
        var prev_kwd = '|prev=' + prev + '|'
        ret.contents += '@import "' + prev_kwd + file + "\";\n"
      }
    })

    done(ret)
    return void 0;
  })
};
<commit_msg>Added synchronous glob search support and changed the API to accept a parameter options<commit_after>var glob = require('glob'),
    path = require('path');

function extend (origin, add) {
  if (add === null || typeof add !== 'object') {
    return origin
  }

  var keys = Object.keys(add)
  var i = keys.length
  while (i--) {
    origin[keys[i]] = add[keys[i]]
  }
  return origin
}

module.exports = function(opts) {

  opts = extend(opts, {
    sync: false,
  });

  return function(url, prev, done) {
    if(!glob.hasMagic(url)) {
      // normal url, resolve to an import of the file
      if(url.indexOf('|prev=') === 0) {
        // if there is a |prev keyword, resolve file relative to that file.. so if
        // you do @import |prev=~|foo.sass, it will resolve to ~/foo.sass
        var prev_dir = null
        var prev_re = /^\|prev=([^\|]*?)\|/
        var matches = url.match(prev_re)

        if(matches.length) {
          prev_dir = path.dirname(matches[1])
          url = url.replace(prev_re, '')
          url = path.resolve(prev_dir, url)
          done({file: url})
          return void 0;
        }
      } else {
        done({file: url})
        return void 0;
      }
    }

    // search for scss | sass files if no extension provided

    // url is a glob, like foo/*.sass, resolve to importing all matching files, so
    // if there is foo/1.sass and foo/2.sass, it will import both of those files
    var cwd = path.dirname(prev)

    var handler = function (err, files) {
      var ret = {
        contents: "\n"
      }

      // import all the matched files, passing through the current file. this is
      // because if you didn't, the path will resolve relative to foo/*.sass,
      // which will fail since that is not an actual path.
      files.forEach(function(file) {
        var ext = path.extname(file)
        var abspath = path.resolve(cwd, file)

        if(/^\.s[ac]ss$/.test(ext) && prev !== abspath) {
          // don't import self
          var prev_kwd = '|prev=' + prev + '|'
          ret.contents += '@import "' + prev_kwd + file + "\";\n"
        }
      })

      done(ret)
      return void 0;
    };

    if (!opts.sync) {
      glob(url, {cwd: cwd}, handler);

    } else {

      var files = glob.sync(url, {cwd: cwd});
      handler(null, files);
    }

  };

};<|endoftext|>


<commit_before>var JSONStream = require('JSONStream');
var duplexer = require('duplexer');
var through = require('through');
var uglify = require('uglify-js');

var fs = require('fs');
var path = require('path');

var combineSourceMap = require('combine-source-map');

var prelude = (function () {
    var src = fs.readFileSync(path.join(__dirname, 'prelude.js'), 'utf8');
    return uglify(src) + '({';
})();

function newlinesIn(src) {
  if (!src) return 0;
  var newlines = src.match(/\n/g);

  return newlines ? newlines.length : 0;
}

module.exports = function (opts) {
    if (!opts) opts = {};
    var parser = opts.raw ? through() : JSONStream.parse([ true ]);
    var output = through(write, end);
    parser.pipe(output);

    var first = true;
    var entries = [];
    var order = [];

    var lineno = 1 + newlinesIn(prelude);
    var sourcemap;

    return duplexer(parser, output);

    function write (row) {
        if (first) this.queue(prelude);

        if (row.sourceFile) {
            sourcemap = sourcemap || combineSourceMap.create();
            sourcemap.addFile(
                { sourceFile: row.sourceFile, source: row.source },
                { line: lineno }
            );
        }

        var wrappedSource = [
            (first ? '' : ','),
            JSON.stringify(row.id),
            ':[',
            'function(require,module,exports){\n',
            combineSourceMap.removeComments(row.source),
            '\n},',
            JSON.stringify(row.deps || {}),
            ']'
        ].join('');

        this.queue(wrappedSource);
        lineno += newlinesIn(wrappedSource);

        first = false;
        if (row.entry && row.order !== undefined) {
            entries[row.order] = row.id;
        }
        else if (row.entry) entries.push(row.id);
    }

    function end () {
        if (first) this.queue(prelude);
        entries = entries.filter(function (x) { return x !== undefined });

        this.queue('},{},' + JSON.stringify(entries) + ')');
        if (sourcemap) this.queue('\n' + sourcemap.comment());

        this.queue(null);
    }
};
<commit_msg>allow an injectable prelude<commit_after>var JSONStream = require('JSONStream');
var duplexer = require('duplexer');
var through = require('through');
var uglify = require('uglify-js');

var fs = require('fs');
var path = require('path');

var combineSourceMap = require('combine-source-map');

var prelude = (function () {
    var src = fs.readFileSync(path.join(__dirname, 'prelude.js'), 'utf8');
    return uglify(src);
})();

function newlinesIn(src) {
  if (!src) return 0;
  var newlines = src.match(/\n/g);

  return newlines ? newlines.length : 0;
}

module.exports = function (opts) {
    if (!opts) opts = {};
    var parser = opts.raw ? through() : JSONStream.parse([ true ]);
    var output = through(write, end);
    parser.pipe(output);

    var first = true;
    var entries = [];
    var order = [];

    var lineno = 1 + newlinesIn(prelude);
    var sourcemap;

    return duplexer(parser, output);

    function write (row) {
        if (first) this.queue((opts.prelude || prelude) + '({');

        if (row.sourceFile) {
            sourcemap = sourcemap || combineSourceMap.create();
            sourcemap.addFile(
                { sourceFile: row.sourceFile, source: row.source },
                { line: lineno }
            );
        }

        var wrappedSource = [
            (first ? '' : ','),
            JSON.stringify(row.id),
            ':[',
            'function(require,module,exports){\n',
            combineSourceMap.removeComments(row.source),
            '\n},',
            JSON.stringify(row.deps || {}),
            ']'
        ].join('');

        this.queue(wrappedSource);
        lineno += newlinesIn(wrappedSource);

        first = false;
        if (row.entry && row.order !== undefined) {
            entries[row.order] = row.id;
        }
        else if (row.entry) entries.push(row.id);
    }

    function end () {
        if (first) this.queue(prelude);
        entries = entries.filter(function (x) { return x !== undefined });

        this.queue('},{},' + JSON.stringify(entries) + ')');
        if (sourcemap) this.queue('\n' + sourcemap.comment());

        this.queue(null);
    }
};
<|endoftext|>