<commit_before>const {app, shell, dialog, ipcMain} = require('electron')
const {BrowserWindow, Menu} = require('electron')
const setting = require('./modules/setting')
const updater = require('./modules/updater')

let windows = []
let openfile = null
let isReady = false

function newWindow(path) {
    let window = new BrowserWindow({
        icon: process.platform == 'linux' ? `${__dirname}/logo.png` : null,
        title: app.getName(),
        useContentSize: true,
        width: setting.get('window.width'),
        height: setting.get('window.height'),
        minWidth: setting.get('window.minwidth'),
        minHeight: setting.get('window.minheight'),
        backgroundColor: '#111111',
        show: false
    })

    windows.push(window)
    buildMenu()

    window.webContents.setAudioMuted(!setting.get('sound.enable'))
    window.webContents.on('did-finish-load', () => {
        if (path) window.webContents.send('load-file', path)
    }).on('new-window', evt => {
        evt.preventDefault()
    })

    window.on('focus', () => {
        window.webContents.send('window-focus')
    }).on('closed', () => {
        windows.splice(windows.indexOf(window), 1)
        window = null
    })

    window.loadURL(`file://${__dirname}/browser/index.html`)

    if (setting.get('debug.dev_tools')) {
        window.toggleDevTools()
    }

    return window
}

function buildMenu(disableAll = false) {
    let template = JSON.parse(JSON.stringify(require('./menu.json')))

    // Create app menu for OS X

    if (process.platform == 'darwin') {
        let appMenu = [{role: 'about'}]

        // Remove original 'Check for Updates' menu item

        let helpMenu = template.find(x => x.label.replace('&', '') == 'Help')
        let items = helpMenu.submenu.splice(0, 3)

        appMenu.push(...items.slice(0, 2))

        // Remove original 'Preferences' menu item

        let fileMenu = template.find(x => x.label.replace('&', '') == 'File')
        let preferenceItem = fileMenu.submenu.splice(fileMenu.submenu.length - 2, 2)[1]

        appMenu.push(
            {type: 'separator'},
            preferenceItem,
            {type: 'separator'},
            {submenu: [], role: 'services'},
            {
                label: 'Text',
                submenu: [
                    {role: 'undo'},
                    {role: 'redo'},
                    {type: 'separator'},
                    {role: 'cut'},
                    {role: 'copy'},
                    {role: 'paste'},
                    {role: 'selectall'}
                ],
            },
            {type: 'separator'},
            {role: 'hide'},
            {role: 'hideothers'},
            {type: 'separator'},
            {
                label: `Quit ${app.getName()}`,
                accelerator: `CmdOrCtrl+Q`,
                click: () => {
                    for (let win of windows) {
                        let n = windows.length
                        win.close()
                        if (windows.length == n) return
                    }

                    app.quit()
                }
            }
        )

        template.unshift({
            label: '{name}',
            submenu: appMenu
        })

        // Add 'Window' menu

        template.splice(template.length - 1, 0, {
            submenu: [
                {
                    label: 'New Window',
                    click: () => newWindow(),
                    enabled: true
                },
                {role: 'minimize'},
                {type: 'separator'},
                {role: 'front'}
            ],
            role: 'window'
        })
    }

    // Load engines

    let engineMenu = template.find(x => x.label && x.label.replace('&', '') == 'Engine')

    if (engineMenu) {
        let attachMenu = engineMenu.submenu[0].submenu

        attachMenu.length = 0

        setting.load()
        setting.getEngines().forEach(engine => {
            attachMenu.push({
                label: engine.name,
                click: () => {
                    let window = BrowserWindow.getFocusedWindow()
                    if (!window) return

                    window.webContents.send('attach-engine', engine.path, engine.args)
                }
            })
        })

        if (setting.getEngines().length != 0) {
            attachMenu.push({type: 'separator'})
        }

        attachMenu.push({
            label: '&Manage Engines…',
            action: 'manageengines'
        })
    }

    // Process menu items

    let processMenu = items => {
        items.forEach(item => {
            if ('label' in item) {
                item.label = item.label
                .replace('{name}', app.getName())
                .replace('{version}', app.getVersion())
            }

            if ('action' in item) {
                let action = item.action

                item.click = () => {
                    let window = BrowserWindow.getFocusedWindow()
                    if (!window) return

                    window.webContents.send('menu-click', action)
                }

                delete item.action
            }

            if ('checked' in item) {
                item.type = 'checkbox'
                item.checked = !!setting.get(item.checked)
            }

            if (disableAll && !item.enabled && !('submenu' in item || 'role' in item)) {
                item.enabled = false
            }

            if ('submenu' in item) {
                processMenu(item.submenu)
            }
        })
    }

    processMenu(template)

    // Build

    Menu.setApplicationMenu(Menu.buildFromTemplate(template))

    // Create dock menu

    if (process.platform == 'darwin') {
        app.dock.setMenu(Menu.buildFromTemplate([{
            label: 'New Window',
            click: () => newWindow()
        }]))
    }
}

function checkForUpdates(showNoUpdatesDialog) {
    let repo = `yishn/${app.getName()}`

    updater.check(repo, (err, hasUpdates, url) => {
        if (err) return

        if (hasUpdates) {
            dialog.showMessageBox({
                type: 'info',
                buttons: ['Download Update', 'Not Now'],
                title: app.getName(),
                message: 'There is a new version of ' + app.getName() + ' available.',
                noLink: true,
                cancelId: 1
            }, response => response == 0 ? shell.openExternal(url) : null)
        } else if (showNoUpdatesDialog) {
            dialog.showMessageBox({
                type: 'info',
                buttons: ['OK'],
                title: app.getName(),
                message: 'There are no updates available.'
            }, () => {})
        }
    })
}

ipcMain.on('new-window', (evt, ...args) => newWindow(...args))
ipcMain.on('build-menu', (evt, ...args) => buildMenu(...args))
ipcMain.on('check-for-updates', (evt, ...args) => checkForUpdates(...args))

app.on('window-all-closed', () => {
    if (process.platform != 'darwin') {
        app.quit()
    } else {
        buildMenu(true)
    }
})

app.on('ready', () => {
    isReady = true

    if (!openfile && process.argv.length >= 2)
        openfile = process.argv[1]

    newWindow(openfile)

    if (setting.get('app.startup_check_updates')) {
        setTimeout(checkForUpdates, setting.get('app.startup_check_updates_delay'))
    }
})

app.on('activate', (evt, hasVisibleWindows) => {
    if (!hasVisibleWindows) newWindow()
})

app.on('open-file', (evt, path) => {
    evt.preventDefault()

    if (!isReady) {
        openfile = path
    } else {
        newWindow(path)
    }
})

process.on('uncaughtException', err => {
    dialog.showErrorBox(`${app.getName()} v${app.getVersion()}`, [
        'Something weird happened. ',
        app.getName(),
        ' will shut itself down. ',
        'If possible, please report this on ',
        `${app.getName()}’s repository on GitHub.\n\n`,
        err.stack
    ].join(''))

    app.quit()
})
<commit_msg>Revert "Attempt to fix #157"<commit_after>const {app, shell, dialog, ipcMain} = require('electron')
const {BrowserWindow, Menu} = require('electron')
const setting = require('./modules/setting')
const updater = require('./modules/updater')

let windows = []
let openfile = null
let isReady = false

function newWindow(path) {
    let window = new BrowserWindow({
        icon: process.platform == 'linux' ? `${__dirname}/logo.png` : null,
        title: app.getName(),
        useContentSize: true,
        width: setting.get('window.width'),
        height: setting.get('window.height'),
        minWidth: setting.get('window.minwidth'),
        minHeight: setting.get('window.minheight'),
        backgroundColor: '#111111',
        show: false
    })

    windows.push(window)
    buildMenu()

    window.webContents.setAudioMuted(!setting.get('sound.enable'))
    window.webContents.on('did-finish-load', () => {
        if (path) window.webContents.send('load-file', path)
    }).on('new-window', evt => {
        evt.preventDefault()
    })

    window.on('focus', () => {
        window.webContents.send('window-focus')
    }).on('closed', () => {
        window = null
    })

    window.loadURL(`file://${__dirname}/browser/index.html`)

    if (setting.get('debug.dev_tools')) {
        window.toggleDevTools()
    }

    return window
}

function buildMenu(disableAll = false) {
    let template = JSON.parse(JSON.stringify(require('./menu.json')))

    // Create app menu for OS X

    if (process.platform == 'darwin') {
        let appMenu = [{role: 'about'}]

        // Remove original 'Check for Updates' menu item

        let helpMenu = template.find(x => x.label.replace('&', '') == 'Help')
        let items = helpMenu.submenu.splice(0, 3)

        appMenu.push(...items.slice(0, 2))

        // Remove original 'Preferences' menu item

        let fileMenu = template.find(x => x.label.replace('&', '') == 'File')
        let preferenceItem = fileMenu.submenu.splice(fileMenu.submenu.length - 2, 2)[1]

        appMenu.push(
            {type: 'separator'},
            preferenceItem,
            {type: 'separator'},
            {submenu: [], role: 'services'},
            {
                label: 'Text',
                submenu: [
                    {role: 'undo'},
                    {role: 'redo'},
                    {type: 'separator'},
                    {role: 'cut'},
                    {role: 'copy'},
                    {role: 'paste'},
                    {role: 'selectall'}
                ],
            },
            {type: 'separator'},
            {role: 'hide'},
            {role: 'hideothers'},
            {type: 'separator'},
            {role: 'quit'}
        )

        template.unshift({
            label: '{name}',
            submenu: appMenu
        })

        // Add 'Window' menu

        template.splice(template.length - 1, 0, {
            submenu: [
                {
                    label: 'New Window',
                    click: () => newWindow(),
                    enabled: true
                },
                {role: 'minimize'},
                {type: 'separator'},
                {role: 'front'}
            ],
            role: 'window'
        })
    }

    // Load engines

    let engineMenu = template.find(x => x.label && x.label.replace('&', '') == 'Engine')

    if (engineMenu) {
        let attachMenu = engineMenu.submenu[0].submenu

        attachMenu.length = 0

        setting.load()
        setting.getEngines().forEach(engine => {
            attachMenu.push({
                label: engine.name,
                click: () => {
                    let window = BrowserWindow.getFocusedWindow()
                    if (!window) return

                    window.webContents.send('attach-engine', engine.path, engine.args)
                }
            })
        })

        if (setting.getEngines().length != 0) {
            attachMenu.push({type: 'separator'})
        }

        attachMenu.push({
            label: '&Manage Engines…',
            action: 'manageengines'
        })
    }

    // Process menu items

    let processMenu = items => {
        items.forEach(item => {
            if ('label' in item) {
                item.label = item.label
                .replace('{name}', app.getName())
                .replace('{version}', app.getVersion())
            }

            if ('action' in item) {
                let action = item.action

                item.click = () => {
                    let window = BrowserWindow.getFocusedWindow()
                    if (!window) return

                    window.webContents.send('menu-click', action)
                }

                delete item.action
            }

            if ('checked' in item) {
                item.type = 'checkbox'
                item.checked = !!setting.get(item.checked)
            }

            if (disableAll && !item.enabled && !('submenu' in item || 'role' in item)) {
                item.enabled = false
            }

            if ('submenu' in item) {
                processMenu(item.submenu)
            }
        })
    }

    processMenu(template)

    // Build

    Menu.setApplicationMenu(Menu.buildFromTemplate(template))

    // Create dock menu

    if (process.platform == 'darwin') {
        app.dock.setMenu(Menu.buildFromTemplate([{
            label: 'New Window',
            click: () => newWindow()
        }]))
    }
}

function checkForUpdates(showNoUpdatesDialog) {
    let repo = `yishn/${app.getName()}`

    updater.check(repo, (err, hasUpdates, url) => {
        if (err) return

        if (hasUpdates) {
            dialog.showMessageBox({
                type: 'info',
                buttons: ['Download Update', 'Not Now'],
                title: app.getName(),
                message: 'There is a new version of ' + app.getName() + ' available.',
                noLink: true,
                cancelId: 1
            }, response => response == 0 ? shell.openExternal(url) : null)
        } else if (showNoUpdatesDialog) {
            dialog.showMessageBox({
                type: 'info',
                buttons: ['OK'],
                title: app.getName(),
                message: 'There are no updates available.'
            }, () => {})
        }
    })
}

ipcMain.on('new-window', (evt, ...args) => newWindow(...args))
ipcMain.on('build-menu', (evt, ...args) => buildMenu(...args))
ipcMain.on('check-for-updates', (evt, ...args) => checkForUpdates(...args))

app.on('window-all-closed', () => {
    if (process.platform != 'darwin') {
        app.quit()
    } else {
        buildMenu(true)
    }
})

app.on('ready', () => {
    isReady = true

    if (!openfile && process.argv.length >= 2)
        openfile = process.argv[1]

    newWindow(openfile)

    if (setting.get('app.startup_check_updates')) {
        setTimeout(checkForUpdates, setting.get('app.startup_check_updates_delay'))
    }
})

app.on('activate', (evt, hasVisibleWindows) => {
    if (!hasVisibleWindows) newWindow()
})

app.on('open-file', (evt, path) => {
    evt.preventDefault()

    if (!isReady) {
        openfile = path
    } else {
        newWindow(path)
    }
})

process.on('uncaughtException', err => {
    dialog.showErrorBox(`${app.getName()} v${app.getVersion()}`, [
        'Something weird happened. ',
        app.getName(),
        ' will shut itself down. ',
        'If possible, please report this on ',
        `${app.getName()}’s repository on GitHub.\n\n`,
        err.stack
    ].join(''))

    app.quit()
})
<|endoftext|>


<commit_before>import React from 'react';
import { GridList, GridTile } from 'material-ui/GridList';

const styles = {
	root: {
		position: 'relative',
		display: 'flex',
		flexWrap: 'wrap',
		justifyContent: 'space-around',
		top: 50,
	},
	gridList: {
		width: '60%',
		height: 800,
		overflowY: 'auto',
		marginBottom: 24,
		background: 'white',
		'border-radius': 10,
	},
};

const tilesData = [
	{
		img: 'images/grid-list/00-52-29-429_640.jpg',
		title: 'Let\'s Get Started',
		author: 'jill111',
		featured: true,
	},
	{
		img: 'images/grid-list/burger-827309_640.jpg',
		title: '',
		author: 'pashminu',
	},
	{
		img: 'images/grid-list/camera-813814_640.jpg',
		title: '',
		author: 'Danson67',
	},
	{
		img: 'images/grid-list/hats-829509_640.jpg',
		title: 'Colin Zarnegar',
		author: 'Hans',
	},
	{
		img: 'images/grid-list/honey-823614_640.jpg',
		title: 'Austin Sefton',
		author: 'fancycravel',
	},
	{
		img: 'images/grid-list/vegetables-790022_640.jpg',
		title: 'Nathan Schwab',
		author: 'jill111',
	},
	{
		img: 'images/grid-list/water-plant-821293_640.jpg',
		title: 'Andrew Yao',
		author: 'BkrmadtyaKarki',
	},
	{
		img: 'images/grid-list/morning-8343453_640.jpg',
		title: 'Technologies Used',
		author: 'fancycrave1',
		featured: true,
	},
];

const Landing = () => (

		<GridList
			cols={2}
			cellHeight={200}
			padding={1}
			style={styles.gridList}
		>
		{tilesData.map((tile) => (
			<GridTile
				key={tile.img}
				title={tile.title}
				titlePosition="top"
				titleBackground="linear-gradient(to bottom, rgba(0,0,0,0.5) 0%,rgba(0,0,0,0.2) 70%,rgba(0,0,0,0) 100%)"
				cols={tile.featured ? 2 : 1}
				rows={tile.featured ? 2 : 1}
			>

			</GridTile>
		))}
		</GridList>

);

export default Landing;

//

//

//

//

//

//
Landing Page

//

//

//

//

//

<commit_msg>[refactor] removes landing page view because it is not completely built out<commit_after>import React from 'react';
import { GridList, GridTile } from 'material-ui/GridList';

// const styles = {
// 	root: {
// 		position: 'relative',
// 		display: 'flex',
// 		flexWrap: 'wrap',
// 		justifyContent: 'space-around',
// 		top: 50,
// 	},
// 	gridList: {
// 		width: '60%',
// 		height: 800,
// 		overflowY: 'auto',
// 		marginBottom: 24,
// 		background: 'white',
// 		'border-radius': 10,
// 	},
// };

// const tilesData = [
// 	{
// 		img: 'images/grid-list/00-52-29-429_640.jpg',
// 		title: 'Let\'s Get Started',
// 		author: 'jill111',
// 		featured: true,
// 	},
// 	{
// 		img: 'images/grid-list/burger-827309_640.jpg',
// 		title: '',
// 		author: 'pashminu',
// 	},
// 	{
// 		img: 'images/grid-list/camera-813814_640.jpg',
// 		title: '',
// 		author: 'Danson67',
// 	},
// 	{
// 		img: 'images/grid-list/hats-829509_640.jpg',
// 		title: 'Colin Zarnegar',
// 		author: 'Hans',
// 	},
// 	{
// 		img: 'images/grid-list/honey-823614_640.jpg',
// 		title: 'Austin Sefton',
// 		author: 'fancycravel',
// 	},
// 	{
// 		img: 'images/grid-list/vegetables-790022_640.jpg',
// 		title: 'Nathan Schwab',
// 		author: 'jill111',
// 	},
// 	{
// 		img: 'images/grid-list/water-plant-821293_640.jpg',
// 		title: 'Andrew Yao',
// 		author: 'BkrmadtyaKarki',
// 	},
// 	{
// 		img: 'images/grid-list/morning-8343453_640.jpg',
// 		title: 'Technologies Used',
// 		author: 'fancycrave1',
// 		featured: true,
// 	},
// ];

const Landing = () => (

Landing Page

//

// 		<GridList
// 			cols={2}
// 			cellHeight={200}
// 			padding={1}
// 			style={styles.gridList}
// 		>
// 		{tilesData.map((tile) => (
// 			<GridTile
// 				key={tile.img}
// 				title={tile.title}
// 				titlePosition="top"
// 				titleBackground="linear-gradient(to bottom, rgba(0,0,0,0.5) 0%,rgba(0,0,0,0.2) 70%,rgba(0,0,0,0) 100%)"
// 				cols={tile.featured ? 2 : 1}
// 				rows={tile.featured ? 2 : 1}
// 			>
//
// 			</GridTile>
// 		))}
// 		</GridList>
//

);

export default Landing;

//

//

//

//

//

//
Landing Page

//

//

//

//

//

<|endoftext|>


<commit_before>import React from "react";
import Radium from "radium";
// import _ from "lodash";
// import Flex from "./framework/flex";
// import { connect } from "react-redux";
// import { FOO } from "../actions";

// @connect(state => {
//   return state.FOO;
// })
@Radium
class Map extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

    };
  }
  static propTypes = {
    /* react */
    // dispatch: React.PropTypes.func,
    params: React.PropTypes.object,
    routes: React.PropTypes.array,
    /* component api */
    style: React.PropTypes.object,
    // foo: React.PropTypes.string
  }
  static defaultProps = {
    // foo: "bar"
  }
  getStyles() {
    return {
      base: {
        height: 300
      }
    };
  }
  componentDidMount() {
    var map = L.map('map').setView([51.505, -0.09], 13);

    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    L.marker([51.5, -0.09]).addTo(map)
        .bindPopup('A pretty CSS3 popup.
 Easily customizable.')
        .openPopup();
  }
  render() {
    const styles = this.getStyles();
    return (

        {"Map"}

    );
  }
}

export default Map;
<commit_msg>log out nodes<commit_after>import React from "react";
import Radium from "radium";
// import _ from "lodash";
// import Flex from "./framework/flex";
import { connect } from "react-redux";
// import { FOO } from "../actions";

@connect(state => {
  return state.tree
})
@Radium
class Map extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

    };
  }
  static propTypes = {
    /* react */
    // dispatch: React.PropTypes.func,
    params: React.PropTypes.object,
    routes: React.PropTypes.array,
    /* component api */
    style: React.PropTypes.object,
    // foo: React.PropTypes.string
  }
  static defaultProps = {
    // foo: "bar"
  }
  getStyles() {
    return {
      base: {
        height: 300
      }
    };
  }
  componentDidMount() {
    var map = L.map('map').setView([51.505, -0.09], 13);

    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    L.marker([51.5, -0.09]).addTo(map)
        .bindPopup('A pretty CSS3 popup.
 Easily customizable.')
        .openPopup();
  }
  render() {
    this.props.nodes.map((n) => {console.log(n.attr.country)})

    const styles = this.getStyles();
    return (

        {"Map"}

    );
  }
}

export default Map;
<|endoftext|>


<commit_before>/**
 * Created by truthlighting on 9/14/2016.
 */
var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleTower = require('role.tower');
var roleHauler = require('role.hauler');

if (!Memory.hCreepID) {
    Memory.hCreepID = 1;
}
if (!Memory.bCreepID) {
    Memory.bCreepID = 1;
}
if (!Memory.uCreepID) {
    Memory.uCreepID = 1;
}
if (!Memory.cCreepID) {
    Memory.cCreepID = 1;
}

module.exports.loop = function () {

    for(var name in Memory.creeps) {
        if(!Game.creeps[name]) {
            delete Memory.creeps[name];
            console.log('Clearing non-existing creep memory:', name);
        }
    }

    var harvesters = _.filter(Game.creeps, (creep) => creep.memory.role == 'harvester');
//    console.log('Harvesters: ' + harvesters.length);
    var sources = Game.rooms['W2N48'].find(FIND_SOURCES);
    var harvesterSources = _.map(Game.creeps, 'memory.assignedSource.id');
    console.log("hs: " + harvesterSources + "s: " + sources);
    var source;
    for (var i=0, l=sources.length; i < l; i++) {
        if (harvesterSources.indexOf(sources[i]) == -1) { source = sources[i]; break; }
    }
    //console.log(result);
//WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE
    if(harvesters.length < 2 && Game.spawns['Harmony'].canCreateCreep([WORK,WORK,WORK,WORK,CARRY,MOVE], "H-" + Memory.hCreepID)==OK) {
        var newName = Game.spawns['Harmony'].createCreep([WORK,WORK,WORK,WORK,CARRY,MOVE], "H-" + Memory.hCreepID, {role: 'harvester', assignedSource: source});
        Memory.hCreepID++;
        console.log('Spawning new harvester: ' + newName);
    }

    var haulers = _.filter(Game.creeps, (creep) => creep.memory.role == 'hauler');

    if(haulers.length < 1 && Game.spawns['Harmony'].canCreateCreep([CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE], "C-" + Memory.cCreepID)==OK) {
        var newName = Game.spawns['Harmony'].createCreep([CARRY, CARRY, CARRY, CARRY, CARRY, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE], "C-" + Memory.cCreepID, {role: 'hauler'});
        Memory.cCreepID++;
        console.log('Spawning new hauler: ' + newName);
    }

    var upgraders = _.filter(Game.creeps, (creep) => creep.memory.role == 'upgrader');
//    console.log('Upgraders: ' + harvesters.length);

    if(upgraders.length < 4 && harvesters.length >= 2 && Game.spawns['Harmony'].canCreateCreep([WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE], "U-" + Memory.uCreepID)==OK) {
        var newName = Game.spawns['Harmony'].createCreep([WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE], "U-" + Memory.uCreepID, {role: 'upgrader' });
        Memory.uCreepID++;
        console.log('Spawning new upgrader: ' + newName);
    }

    var builders = _.filter(Game.creeps, (creep) => creep.memory.role == 'builder');
//    console.log('Upgraders: ' + harvesters.length);

    if(builders.length < 3 && harvesters.length >= 2 && Game.spawns['Harmony'].canCreateCreep([WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE], "B-" + Memory.bCreepID)==OK) {
        var newName = Game.spawns['Harmony'].createCreep([WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE], "B-" + Memory.bCreepID, {role: 'builder'});
        Memory.bCreepID++;
        console.log('Spawning new builder: ' + newName);
    }

    for(var name in Game.creeps) {
        var creep = Game.creeps[name];
        if(creep.memory.role == 'harvester') {
            roleHarvester.run(creep);
        }
        if(creep.memory.role == 'upgrader') {
            roleUpgrader.run(creep);
        }
        if(creep.memory.role == 'builder') {
            roleBuilder.run(creep);
        }
        if(creep.memory.role == 'hauler') {
            roleHauler.run(creep);
        }
    }

    roleTower.run();
};<commit_msg>debugging main<commit_after>/**
 * Created by truthlighting on 9/14/2016.
 */
var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleTower = require('role.tower');
var roleHauler = require('role.hauler');

if (!Memory.hCreepID) {
    Memory.hCreepID = 1;
}
if (!Memory.bCreepID) {
    Memory.bCreepID = 1;
}
if (!Memory.uCreepID) {
    Memory.uCreepID = 1;
}
if (!Memory.cCreepID) {
    Memory.cCreepID = 1;
}

module.exports.loop = function () {

    for(var name in Memory.creeps) {
        if(!Game.creeps[name]) {
            delete Memory.creeps[name];
            console.log('Clearing non-existing creep memory:', name);
        }
    }

    var harvesters = _.filter(Game.creeps, (creep) => creep.memory.role == 'harvester');
//    console.log('Harvesters: ' + harvesters.length);
    var sources = Game.rooms['W2N48'].find(FIND_SOURCES);
    var harvesterSources = _.map(Game.creeps, 'memory.assignedSource.id');
    console.log("hs: " + harvesterSources + "s: " + sources);
    var source;
    for (var i=0, l=sources.length; i < l; i++) {
        if (harvesterSources.indexOf(sources[i]) == -1) { source = sources[i]; break; }
    }
    console.log("source: " + source);
    //console.log(result);
//WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE
    if(harvesters.length < 2 && Game.spawns['Harmony'].canCreateCreep([WORK,WORK,WORK,WORK,CARRY,MOVE], "H-" + Memory.hCreepID)==OK) {
        var newName = Game.spawns['Harmony'].createCreep([WORK,WORK,WORK,WORK,CARRY,MOVE], "H-" + Memory.hCreepID, {role: 'harvester', assignedSource: source});
        Memory.hCreepID++;
        console.log('Spawning new harvester: ' + newName);
    }

    var haulers = _.filter(Game.creeps, (creep) => creep.memory.role == 'hauler');

    if(haulers.length < 1 && Game.spawns['Harmony'].canCreateCreep([CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE], "C-" + Memory.cCreepID)==OK) {
        var newName = Game.spawns['Harmony'].createCreep([CARRY, CARRY, CARRY, CARRY, CARRY, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE], "C-" + Memory.cCreepID, {role: 'hauler'});
        Memory.cCreepID++;
        console.log('Spawning new hauler: ' + newName);
    }

    var upgraders = _.filter(Game.creeps, (creep) => creep.memory.role == 'upgrader');
//    console.log('Upgraders: ' + harvesters.length);

    if(upgraders.length < 4 && harvesters.length >= 2 && Game.spawns['Harmony'].canCreateCreep([WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE], "U-" + Memory.uCreepID)==OK) {
        var newName = Game.spawns['Harmony'].createCreep([WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE], "U-" + Memory.uCreepID, {role: 'upgrader' });
        Memory.uCreepID++;
        console.log('Spawning new upgrader: ' + newName);
    }

    var builders = _.filter(Game.creeps, (creep) => creep.memory.role == 'builder');
//    console.log('Upgraders: ' + harvesters.length);

    if(builders.length < 3 && harvesters.length >= 2 && Game.spawns['Harmony'].canCreateCreep([WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE], "B-" + Memory.bCreepID)==OK) {
        var newName = Game.spawns['Harmony'].createCreep([WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE], "B-" + Memory.bCreepID, {role: 'builder'});
        Memory.bCreepID++;
        console.log('Spawning new builder: ' + newName);
    }

    for(var name in Game.creeps) {
        var creep = Game.creeps[name];
        if(creep.memory.role == 'harvester') {
            roleHarvester.run(creep);
        }
        if(creep.memory.role == 'upgrader') {
            roleUpgrader.run(creep);
        }
        if(creep.memory.role == 'builder') {
            roleBuilder.run(creep);
        }
        if(creep.memory.role == 'hauler') {
            roleHauler.run(creep);
        }
    }

    roleTower.run();
};<|endoftext|>


<commit_before>import {SwapStrategies} from './swap-strategies';
import {ViewLocator} from './view-locator';
import {ViewEngine} from './view-engine';
import {HtmlBehaviorResource} from './html-behavior';
import {BehaviorInstruction, ViewCompileInstruction} from './instructions';
import {CompositionTransaction} from './composition-transaction';
import {DOM} from 'aurelia-pal';
import {Container, inject} from 'aurelia-dependency-injection';
import {metadata} from 'aurelia-metadata';
/**
* Instructs the composition engine how to dynamically compose a component.
*/
interface CompositionContext {
  /**
  * The parent Container for the component creation.
  */
  container: Container;
  /**
  * The child Container for the component creation. One will be created from the parent if not provided.
  */
  childContainer?: Container;
  /**
  * The context in which the view model is executed in.
  */
  bindingContext: any;
  /**
  * A secondary binding context that can override the standard context.
  */
  overrideContext?: any;
  /**
  * The view model url or instance for the component.
  */
  viewModel?: any;
  /**
  * Data to be passed to the "activate" hook on the view model.
  */
  model?: any;
  /**
  * The HtmlBehaviorResource for the component.
  */
  viewModelResource?: HtmlBehaviorResource;
  /**
  * The view resources for the view in which the component should be created.
  */
  viewResources: ViewResources;
  /**
  * The view inside which this composition is happening.
  */
  owningView?: View;
  /**
  * The view url or view strategy to override the default view location convention.
  */
  view?: string | ViewStrategy;
  /**
  * The slot to push the dynamically composed component into.
  */
  viewSlot: ViewSlot;
  /**
  * Should the composition system skip calling the "activate" hook on the view model.
  */
  skipActivation?: boolean;
}

function tryActivateViewModel(context) {
  if (context.skipActivation || typeof context.viewModel.activate !== 'function') {
    return Promise.resolve();
  }

  return context.viewModel.activate(context.model) || Promise.resolve();
}

class SwapStrategies {
  // animate the next view in before removing the current view;
  before(viewSlot, previousView, callback) {
    let promise = Promise.resolve(callback());

    if (previousView !== undefined) {
      return promise.then(() => viewSlot.remove(previousView, true));
    }

    return promise;
  }

  // animate the next view at the same time the current view is removed
  with(viewSlot, previousView, callback) {
    let promise = Promise.resolve(callback());

    if (previousView !== undefined) {
      return Promise.all([viewSlot.remove(previousView, true), promise]);
    }

    return promise;
  }

  // animate the next view in after the current view has been removed
  after(viewSlot, previousView, callback) {
    return Promise.resolve(viewSlot.removeAll(true)).then(callback);
  }
}

const swapStrategies = new SwapStrategies();

/**
* Used to dynamically compose components.
*/
@inject(ViewEngine, ViewLocator)
export class CompositionEngine {
  /**
  * Creates an instance of the CompositionEngine.
  * @param viewEngine The ViewEngine used during composition.
  */
  constructor(viewEngine: ViewEngine, viewLocator: ViewLocator) {
    this.viewEngine = viewEngine;
    this.viewLocator = viewLocator;
  }

  _createControllerAndSwap(context) {
    function swap(controller) {
      let swapStrategy = SwapStrategies[context.swapOrder] || SwapStrategies.after;
      let previousViews = context.viewSlot.children.slice();

      return swapStrategy(context.viewSlot, previousViews, () => {
        return Promise.resolve(context.viewSlot.add(controller.view)).then(() => {
          if (context.currentController) {
            context.currentController.unbind();
          }
        });
      }).then(() => {
        if (context.compositionTransactionNotifier) {
          context.compositionTransactionNotifier.done();
        }

        return controller;
      });
    }

    return this.createController(context).then(controller => {
      controller.automate(context.overrideContext, context.owningView);

      if (context.compositionTransactionOwnershipToken) {
        return context.compositionTransactionOwnershipToken.waitForCompositionComplete().then(() => swap(controller));
      }

      return swap(controller);
    });
  }

  /**
  * Creates a controller instance for the component described in the context.
  * @param context The CompositionContext that describes the component.
  * @return A Promise for the Controller.
  */
  createController(context: CompositionContext): Promise<Controller> {
    let childContainer;
    let viewModel;
    let viewModelResource;
    let m;

    return this.ensureViewModel(context).then(tryActivateViewModel).then(() => {
      childContainer = context.childContainer;
      viewModel = context.viewModel;
      viewModelResource = context.viewModelResource;
      m = viewModelResource.metadata;

      let viewStrategy = this.viewLocator.getViewStrategy(context.view || viewModel);

      if (context.viewResources) {
        viewStrategy.makeRelativeTo(context.viewResources.viewUrl);
      }

      return m.load(childContainer, viewModelResource.value, null, viewStrategy, true);
    }).then(viewFactory => m.create(childContainer, BehaviorInstruction.dynamic(context.host, viewModel, viewFactory)));
  }

  /**
  * Ensures that the view model and its resource are loaded for this context.
  * @param context The CompositionContext to load the view model and its resource for.
  * @return A Promise for the context.
  */
  ensureViewModel(context: CompositionContext): Promise<CompositionContext> {
    let childContainer = context.childContainer = (context.childContainer || context.container.createChild());

    if (typeof context.viewModel === 'string') {
      context.viewModel = context.viewResources
          ? context.viewResources.relativeToView(context.viewModel)
          : context.viewModel;

      return this.viewEngine.importViewModelResource(context.viewModel).then(viewModelResource => {
        childContainer.autoRegister(viewModelResource.value);

        if (context.host) {
          childContainer.registerInstance(DOM.Element, context.host);
        }

        context.viewModel = childContainer.viewModel = childContainer.get(viewModelResource.value);
        context.viewModelResource = viewModelResource;
        return context;
      });
    }

    let m = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, context.viewModel.constructor);
    m.elementName = m.elementName || 'dynamic-element';
    m.initialize(context.container || childContainer, context.viewModel.constructor);
    context.viewModelResource = { metadata: m, value: context.viewModel.constructor };
    childContainer.viewModel = context.viewModel;
    return Promise.resolve(context);
  }

  /**
  * Dynamically composes a component.
  * @param context The CompositionContext providing information on how the composition should occur.
  * @return A Promise for the View or the Controller that results from the dynamic composition.
  */
  compose(context: CompositionContext): Promise<View | Controller> {
    context.childContainer = context.childContainer || context.container.createChild();
    context.view = this.viewLocator.getViewStrategy(context.view);

    let transaction = context.childContainer.get(CompositionTransaction);
    let compositionTransactionOwnershipToken = transaction.tryCapture();

    if (compositionTransactionOwnershipToken) {
      context.compositionTransactionOwnershipToken = compositionTransactionOwnershipToken;
    } else {
      context.compositionTransactionNotifier = transaction.enlist();
    }

    if (context.viewModel) {
      return this._createControllerAndSwap(context);
    } else if (context.view) {
      if (context.viewResources) {
        context.view.makeRelativeTo(context.viewResources.viewUrl);
      }

      return context.view.loadViewFactory(this.viewEngine, new ViewCompileInstruction()).then(viewFactory => {
        let result = viewFactory.create(context.childContainer);
        result.bind(context.bindingContext, context.overrideContext);

        let work = () => {
          let swapStrategy = SwapStrategies[context.swapOrder] || SwapStrategies.after;
          let previousViews = context.viewSlot.children.slice();

          return swapStrategy(context.viewSlot, previousViews, () => {
            return Promise.resolve(context.viewSlot.add(controller.result)).then(() => {
              if (context.currentController) {
                context.currentController.unbind();
              }
            });
          }).then(() => {
            if (context.compositionTransactionNotifier) {
              context.compositionTransactionNotifier.done();
            }

            return result;
          });
        };

        if (context.compositionTransactionOwnershipToken) {
          return context.compositionTransactionOwnershipToken.waitForCompositionComplete().then(work);
        }

        return work();
      });
    } else if (context.viewSlot) {
      context.viewSlot.removeAll();

      if (context.compositionTransactionNotifier) {
        context.compositionTransactionNotifier.done();
      }

      return Promise.resolve(null);
    }

    return Promise.resolve(null);
  }
}
<commit_msg>resolve merge conflicts<commit_after>import {SwapStrategies} from './swap-strategies';
import {ViewLocator} from './view-locator';
import {ViewEngine} from './view-engine';
import {HtmlBehaviorResource} from './html-behavior';
import {BehaviorInstruction, ViewCompileInstruction} from './instructions';
import {CompositionTransaction} from './composition-transaction';
import {DOM} from 'aurelia-pal';
import {Container, inject} from 'aurelia-dependency-injection';
import {metadata} from 'aurelia-metadata';
/**
* Instructs the composition engine how to dynamically compose a component.
*/
interface CompositionContext {
  /**
  * The parent Container for the component creation.
  */
  container: Container;
  /**
  * The child Container for the component creation. One will be created from the parent if not provided.
  */
  childContainer?: Container;
  /**
  * The context in which the view model is executed in.
  */
  bindingContext: any;
  /**
  * A secondary binding context that can override the standard context.
  */
  overrideContext?: any;
  /**
  * The view model url or instance for the component.
  */
  viewModel?: any;
  /**
  * Data to be passed to the "activate" hook on the view model.
  */
  model?: any;
  /**
  * The HtmlBehaviorResource for the component.
  */
  viewModelResource?: HtmlBehaviorResource;
  /**
  * The view resources for the view in which the component should be created.
  */
  viewResources: ViewResources;
  /**
  * The view inside which this composition is happening.
  */
  owningView?: View;
  /**
  * The view url or view strategy to override the default view location convention.
  */
  view?: string | ViewStrategy;
  /**
  * The slot to push the dynamically composed component into.
  */
  viewSlot: ViewSlot;
  /**
  * Should the composition system skip calling the "activate" hook on the view model.
  */
  skipActivation?: boolean;
}

function tryActivateViewModel(context) {
  if (context.skipActivation || typeof context.viewModel.activate !== 'function') {
    return Promise.resolve();
  }

  return context.viewModel.activate(context.model) || Promise.resolve();
}

/**
* Used to dynamically compose components.
*/
@inject(ViewEngine, ViewLocator)
export class CompositionEngine {
  /**
  * Creates an instance of the CompositionEngine.
  * @param viewEngine The ViewEngine used during composition.
  */
  constructor(viewEngine: ViewEngine, viewLocator: ViewLocator) {
    this.viewEngine = viewEngine;
    this.viewLocator = viewLocator;
  }

  _createControllerAndSwap(context) {
    function swap(controller) {
      let swapStrategy = SwapStrategies[context.swapOrder] || SwapStrategies.after;
      let previousViews = context.viewSlot.children.slice();

      return swapStrategy(context.viewSlot, previousViews, () => {
        return Promise.resolve(context.viewSlot.add(controller.view)).then(() => {
          if (context.currentController) {
            context.currentController.unbind();
          }
        });
      }).then(() => {
        if (context.compositionTransactionNotifier) {
          context.compositionTransactionNotifier.done();
        }

        return controller;
      });
    }

    return this.createController(context).then(controller => {
      controller.automate(context.overrideContext, context.owningView);

      if (context.compositionTransactionOwnershipToken) {
        return context.compositionTransactionOwnershipToken.waitForCompositionComplete().then(() => swap(controller));
      }

      return swap(controller);
    });
  }

  /**
  * Creates a controller instance for the component described in the context.
  * @param context The CompositionContext that describes the component.
  * @return A Promise for the Controller.
  */
  createController(context: CompositionContext): Promise<Controller> {
    let childContainer;
    let viewModel;
    let viewModelResource;
    let m;

    return this.ensureViewModel(context).then(tryActivateViewModel).then(() => {
      childContainer = context.childContainer;
      viewModel = context.viewModel;
      viewModelResource = context.viewModelResource;
      m = viewModelResource.metadata;

      let viewStrategy = this.viewLocator.getViewStrategy(context.view || viewModel);

      if (context.viewResources) {
        viewStrategy.makeRelativeTo(context.viewResources.viewUrl);
      }

      return m.load(childContainer, viewModelResource.value, null, viewStrategy, true);
    }).then(viewFactory => m.create(childContainer, BehaviorInstruction.dynamic(context.host, viewModel, viewFactory)));
  }

  /**
  * Ensures that the view model and its resource are loaded for this context.
  * @param context The CompositionContext to load the view model and its resource for.
  * @return A Promise for the context.
  */
  ensureViewModel(context: CompositionContext): Promise<CompositionContext> {
    let childContainer = context.childContainer = (context.childContainer || context.container.createChild());

    if (typeof context.viewModel === 'string') {
      context.viewModel = context.viewResources
          ? context.viewResources.relativeToView(context.viewModel)
          : context.viewModel;

      return this.viewEngine.importViewModelResource(context.viewModel).then(viewModelResource => {
        childContainer.autoRegister(viewModelResource.value);

        if (context.host) {
          childContainer.registerInstance(DOM.Element, context.host);
        }

        context.viewModel = childContainer.viewModel = childContainer.get(viewModelResource.value);
        context.viewModelResource = viewModelResource;
        return context;
      });
    }

    let m = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, context.viewModel.constructor);
    m.elementName = m.elementName || 'dynamic-element';
    m.initialize(context.container || childContainer, context.viewModel.constructor);
    context.viewModelResource = { metadata: m, value: context.viewModel.constructor };
    childContainer.viewModel = context.viewModel;
    return Promise.resolve(context);
  }

  /**
  * Dynamically composes a component.
  * @param context The CompositionContext providing information on how the composition should occur.
  * @return A Promise for the View or the Controller that results from the dynamic composition.
  */
  compose(context: CompositionContext): Promise<View | Controller> {
    context.childContainer = context.childContainer || context.container.createChild();
    context.view = this.viewLocator.getViewStrategy(context.view);

    let transaction = context.childContainer.get(CompositionTransaction);
    let compositionTransactionOwnershipToken = transaction.tryCapture();

    if (compositionTransactionOwnershipToken) {
      context.compositionTransactionOwnershipToken = compositionTransactionOwnershipToken;
    } else {
      context.compositionTransactionNotifier = transaction.enlist();
    }

    if (context.viewModel) {
      return this._createControllerAndSwap(context);
    } else if (context.view) {
      if (context.viewResources) {
        context.view.makeRelativeTo(context.viewResources.viewUrl);
      }

      return context.view.loadViewFactory(this.viewEngine, new ViewCompileInstruction()).then(viewFactory => {
        let result = viewFactory.create(context.childContainer);
        result.bind(context.bindingContext, context.overrideContext);

        let work = () => {
          let swapStrategy = SwapStrategies[context.swapOrder] || SwapStrategies.after;
          let previousViews = context.viewSlot.children.slice();

          return swapStrategy(context.viewSlot, previousViews, () => {
            return Promise.resolve(context.viewSlot.add(controller.result)).then(() => {
              if (context.currentController) {
                context.currentController.unbind();
              }
            });
          }).then(() => {
            if (context.compositionTransactionNotifier) {
              context.compositionTransactionNotifier.done();
            }

            return result;
          });
        };

        if (context.compositionTransactionOwnershipToken) {
          return context.compositionTransactionOwnershipToken.waitForCompositionComplete().then(work);
        }

        return work();
      });
    } else if (context.viewSlot) {
      context.viewSlot.removeAll();

      if (context.compositionTransactionNotifier) {
        context.compositionTransactionNotifier.done();
      }

      return Promise.resolve(null);
    }

    return Promise.resolve(null);
  }
}
<|endoftext|>


<commit_before>chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('index.html', {
    bounds: {
      width: 1200,
      height: 658
    }
  });
});<commit_msg>updated deprecated api's.<commit_after>chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('index.html', {
    innerBounds: {
      width: 1200,
      height: 658,
      minWidth: 1200,
      minHeight: 658
    }
  });

});<|endoftext|>


<commit_before>function Creature(network, world, x, y)
{
	this.network = network;
	this.world = world;
	this.energy = 10;
	this.foodEaten = 0;

	this.location = new Vector(x, y);
	this.velocity = new Vector(0, 0);

	this.nearestFood = this.location;
	this.nearestCreature = this.location;

	this.color = 'rgb(' +
		Math.floor(Math.random() * 255) + ',' +
		Math.floor(Math.random() * 255) + ',' +
		Math.floor(Math.random() * 255) + ')';
}

Creature.prototype = {

	radius:           5,
	scanRadius:       50,
	maxEnergy:        1,
	linearMaxSpeed:   4,
	angularMaxSpeed:  Math.PI / 6,

	tick: function()
	{
		if (!this.isAlive()) {
			return;
		}

		// assign all input values
		var inputs = [];
		inputs.push(this.energy);
		inputs.push(this.nearestFood.magnitude());
		inputs.push(this.nearestFood.angle());
		inputs.push(this.nearestCreature.magnitude());
		inputs.push(this.nearestCreature.angle());

		// feed the neural network forward
		var outputs = this.network.activate(inputs);
		this.processOutputs(outputs);

		// interact with the world and other creatures
		this.interact();
	},

	processOutputs: function(networkOutput)
	{
		// first two network outputs specify the multipliers for deltas in distance and rotation
		let ds = networkOutput[0] * this.linearMaxSpeed;
		let da = networkOutput[1] * this.angularMaxSpeed;
		this.velocity.setMagnitude(ds);
		this.velocity.rotate(da);
		this.location.add(this.velocity);

		this.energy -= Math.abs(.02 * (ds / this.linearMaxSpeed)) + Math.abs(.02 * (da / this.angularMaxSpeed));
	},

	interact: function()
	{
		this.nearestFood = new Vector(0, 0);
		var distanceToNearestFood = this.scanRadius + 1;

		this.nearestCreature = new Vector(0, 0);
		var distanceToNearestCreature = this.scanRadius + 1;

		// eat
		for (var i in this.world.food) {
			if (this.world.food[i].x !== null && this.world.food[i].y !== null) {
				let distanceToFood = this.location.distanceBetween(this.world.food[i]);
				if (distanceToFood <= this.radius) {
					this.eatFood(i);
				}
				else if (distanceToFood <= distanceToNearestFood) {
					this.nearestFood = this.world.food[i].copy().subtract(this.location);
					distanceToNearestFood = distanceToFood;
				}
			}
		}

		// fight
		for (var i in this.world.creatures) {
			if (this.world.creatures[i] !== this && this.world.creatures[i].isAlive()) {
				let distanceToCreature = this.location.distanceBetween(this.world.creatures[i].location);
				if (distanceToCreature <= this.radius + this.world.creatures[i].radius &&
					this.velocity.magnitude() > this.world.creatures[i].velocity.magnitude()) {
					this.attackCreature(i);
				}
				else if (distanceToCreature <= distanceToNearestCreature) {
					this.nearestCreature = this.world.creatures[i].location.copy().subtract(this.location);
					distanceToNearestCreature = distanceToCreature;
				}
			}
		}
	},

	eatFood: function(foodId) {
		this.world.food[foodId].x = null; // invalidate
		this.foodEaten++;
		this.energy = Math.min(this.maxEnergy, this.energy + .1);
	},

	attackCreature: function(creatureId) {
		this.energy = this.maxEnergy;
		this.world.creatures[creatureId].energy = 0; // kill it
	},

	clone: function()
	{
		var x = Math.random() * this.world.width;
		var y = Math.random() * this.world.height;
		var creature = new Creature(this.network.clone(), this.world, x, y);

		var neurons = creature.network.neurons();
		for (var i in neurons) {
			var neuron = neurons[i].neuron;
			for (var j in neuron.connections.projected) {
				var connection = neuron.connections.projected[j];
				if (Math.random() < .3) {
					connection.weight += (Math.random() * .2) - .1;
				}
			}
		}

		creature.velocity.random();
		creature.color = this.color;

		// bad
		this.reset();
		creature.reset();

		return creature;
	},

	draw: function()
	{
		if (!this.isAlive()) {
			return;
		}

		this.world.ctx.lineWidth = 1;
		this.world.ctx.beginPath();
		this.world.ctx.fillStyle = this.color;
		this.world.ctx.arc(this.location.x, this.location.y, this.radius, 0, 2 * Math.PI);
		this.world.ctx.fill();

		// draw pointer (to show what direction the creature is facing)
		this.world.ctx.lineWidth = 3;
		this.world.ctx.beginPath();
		this.world.ctx.strokeStyle = 'black';
		this.world.ctx.moveTo(this.location.x, this.location.y);
		var relativeTarget = this.velocity.copy().setMagnitude(this.radius + 3);
		var absolutePosition = this.location.copy().add(relativeTarget);
		this.world.ctx.lineTo(absolutePosition.x, absolutePosition.y);
		this.world.ctx.stroke();

		// draw line to nearest food
		if (this.nearestFood.magnitude() < this.scanRadius) {
			this.world.ctx.lineWidth = 1;
			this.world.ctx.beginPath();
			this.world.ctx.strokeStyle = 'rgba(150, 150, 150, .5)';
			this.world.ctx.moveTo(this.location.x, this.location.y);
			var absolutePosition = this.location.copy().add(this.nearestFood);
			this.world.ctx.lineTo(absolutePosition.x, absolutePosition.y);
			this.world.ctx.stroke();
		}

		// draw line to nearest creature
		if (this.nearestCreature.magnitude() < this.scanRadius) {
			this.world.ctx.lineWidth = 1;
			this.world.ctx.beginPath();
			this.world.ctx.strokeStyle = 'rgba(255, 0, 0, .25)';
			this.world.ctx.moveTo(this.location.x, this.location.y);
			var absolutePosition = this.location.copy().add(this.nearestCreature);
			this.world.ctx.lineTo(absolutePosition.x, absolutePosition.y);
			this.world.ctx.stroke();
		}
	},

	fitness: function()
	{
		return this.isAlive() ? this.foodEaten : 0;
	},

	isAlive: function()
	{
		return this.energy > 0;
	},

	reset: function()
	{
		this.foodEaten = 0;
		this.energy = this.maxEnergy;
	}
}
<commit_msg>Set starting energy to 1<commit_after>function Creature(network, world, x, y)
{
	this.network = network;
	this.world = world;
	this.energy = 1;
	this.foodEaten = 0;

	this.location = new Vector(x, y);
	this.velocity = new Vector(0, 0);

	this.nearestFood = this.location;
	this.nearestCreature = this.location;

	this.color = 'rgb(' +
		Math.floor(Math.random() * 255) + ',' +
		Math.floor(Math.random() * 255) + ',' +
		Math.floor(Math.random() * 255) + ')';
}

Creature.prototype = {

	radius:           5,
	scanRadius:       50,
	maxEnergy:        1,
	linearMaxSpeed:   4,
	angularMaxSpeed:  Math.PI / 6,

	tick: function()
	{
		if (!this.isAlive()) {
			return;
		}

		// assign all input values
		var inputs = [];
		inputs.push(this.energy);
		inputs.push(this.nearestFood.magnitude());
		inputs.push(this.nearestFood.angle());
		inputs.push(this.nearestCreature.magnitude());
		inputs.push(this.nearestCreature.angle());

		// feed the neural network forward
		var outputs = this.network.activate(inputs);
		this.processOutputs(outputs);

		// interact with the world and other creatures
		this.interact();
	},

	processOutputs: function(networkOutput)
	{
		// first two network outputs specify the multipliers for deltas in distance and rotation
		let ds = networkOutput[0] * this.linearMaxSpeed;
		let da = networkOutput[1] * this.angularMaxSpeed;
		this.velocity.setMagnitude(ds);
		this.velocity.rotate(da);
		this.location.add(this.velocity);

		this.energy -= Math.abs(.02 * (ds / this.linearMaxSpeed)) + Math.abs(.02 * (da / this.angularMaxSpeed));
	},

	interact: function()
	{
		this.nearestFood = new Vector(0, 0);
		var distanceToNearestFood = this.scanRadius + 1;

		this.nearestCreature = new Vector(0, 0);
		var distanceToNearestCreature = this.scanRadius + 1;

		// eat
		for (var i in this.world.food) {
			if (this.world.food[i].x !== null && this.world.food[i].y !== null) {
				let distanceToFood = this.location.distanceBetween(this.world.food[i]);
				if (distanceToFood <= this.radius) {
					this.eatFood(i);
				}
				else if (distanceToFood <= distanceToNearestFood) {
					this.nearestFood = this.world.food[i].copy().subtract(this.location);
					distanceToNearestFood = distanceToFood;
				}
			}
		}

		// fight
		for (var i in this.world.creatures) {
			if (this.world.creatures[i] !== this && this.world.creatures[i].isAlive()) {
				let distanceToCreature = this.location.distanceBetween(this.world.creatures[i].location);
				if (distanceToCreature <= this.radius + this.world.creatures[i].radius &&
					this.velocity.magnitude() > this.world.creatures[i].velocity.magnitude()) {
					this.attackCreature(i);
				}
				else if (distanceToCreature <= distanceToNearestCreature) {
					this.nearestCreature = this.world.creatures[i].location.copy().subtract(this.location);
					distanceToNearestCreature = distanceToCreature;
				}
			}
		}
	},

	eatFood: function(foodId) {
		this.world.food[foodId].x = null; // invalidate
		this.foodEaten++;
		this.energy = Math.min(this.maxEnergy, this.energy + .1);
	},

	attackCreature: function(creatureId) {
		this.energy = this.maxEnergy;
		this.world.creatures[creatureId].energy = 0; // kill it
	},

	clone: function()
	{
		var x = Math.random() * this.world.width;
		var y = Math.random() * this.world.height;
		var creature = new Creature(this.network.clone(), this.world, x, y);

		var neurons = creature.network.neurons();
		for (var i in neurons) {
			var neuron = neurons[i].neuron;
			for (var j in neuron.connections.projected) {
				var connection = neuron.connections.projected[j];
				if (Math.random() < .3) {
					connection.weight += (Math.random() * .2) - .1;
				}
			}
		}

		creature.velocity.random();
		creature.color = this.color;

		// bad
		this.reset();
		creature.reset();

		return creature;
	},

	draw: function()
	{
		if (!this.isAlive()) {
			return;
		}

		this.world.ctx.lineWidth = 1;
		this.world.ctx.beginPath();
		this.world.ctx.fillStyle = this.color;
		this.world.ctx.arc(this.location.x, this.location.y, this.radius, 0, 2 * Math.PI);
		this.world.ctx.fill();

		// draw pointer (to show what direction the creature is facing)
		this.world.ctx.lineWidth = 3;
		this.world.ctx.beginPath();
		this.world.ctx.strokeStyle = 'black';
		this.world.ctx.moveTo(this.location.x, this.location.y);
		var relativeTarget = this.velocity.copy().setMagnitude(this.radius + 3);
		var absolutePosition = this.location.copy().add(relativeTarget);
		this.world.ctx.lineTo(absolutePosition.x, absolutePosition.y);
		this.world.ctx.stroke();

		// draw line to nearest food
		if (this.nearestFood.magnitude() < this.scanRadius) {
			this.world.ctx.lineWidth = 1;
			this.world.ctx.beginPath();
			this.world.ctx.strokeStyle = 'rgba(150, 150, 150, .5)';
			this.world.ctx.moveTo(this.location.x, this.location.y);
			var absolutePosition = this.location.copy().add(this.nearestFood);
			this.world.ctx.lineTo(absolutePosition.x, absolutePosition.y);
			this.world.ctx.stroke();
		}

		// draw line to nearest creature
		if (this.nearestCreature.magnitude() < this.scanRadius) {
			this.world.ctx.lineWidth = 1;
			this.world.ctx.beginPath();
			this.world.ctx.strokeStyle = 'rgba(255, 0, 0, .25)';
			this.world.ctx.moveTo(this.location.x, this.location.y);
			var absolutePosition = this.location.copy().add(this.nearestCreature);
			this.world.ctx.lineTo(absolutePosition.x, absolutePosition.y);
			this.world.ctx.stroke();
		}
	},

	fitness: function()
	{
		return this.isAlive() ? this.foodEaten : 0;
	},

	isAlive: function()
	{
		return this.energy > 0;
	},

	reset: function()
	{
		this.foodEaten = 0;
		this.energy = this.maxEnergy;
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
/*jslint nomen:true, vars:true, regexp:true, plusplus: true*/
/*global window, console, define, brackets, $, Mustache*/

define(function (require, exports, module) {
    "use strict";

    var Compiler            = require("Compiler"),
        NestedStyleParser   = require("NestedStyleParser"),
        SASSAgent           = require("SASSAgent"),
        SourceMapManager    = require("SourceMapManager");

    var _                   = brackets.getModule("thirdparty/lodash"),
        AppInit             = brackets.getModule("utils/AppInit"),
        Async               = brackets.getModule("utils/Async"),
        CSSUtils            = brackets.getModule("language/CSSUtils"),
        CodeInspection      = brackets.getModule("language/CodeInspection"),
        DocumentManager     = brackets.getModule("document/DocumentManager"),
        FileUtils           = brackets.getModule("file/FileUtils"),
        FileSystem          = brackets.getModule("filesystem/FileSystem"),
        ProjectManager      = brackets.getModule("project/ProjectManager");

    // Distinguish input SASS files from partials
    var RE_INPUT_FILE = /^[^_].*\.(scss|sass)$/,
        RE_PARTIAL_FILE = /^_.*\.(scss|sass)$/;

    // Augment CSSUtils.findMatchingRules to support source maps
    var baseFindMatchingRules = CSSUtils.findMatchingRules;

    function _convertMatchingRuleResult(selectorCache, generatedResult) {
        // Check CSS text for a sourceMappingURL
        var oneResult = new $.Deferred(),
            cssFile = generatedResult.document.file,
            sourceMapPromise = SourceMapManager.getSourceMap(cssFile),
            match = !sourceMapPromise && SourceMapManager.getSourceMappingURL(generatedResult.document.getText());

        if (match) {
            sourceMapPromise = SourceMapManager.setSourceMapFile(cssFile, match);
        }

        if (sourceMapPromise) {
            sourceMapPromise.then(function (sourceMap) {
                // TODO core brackets change to add selectorInfo
                // generatedPos = { line: info.selectorStartLine + 1, column: info.selectorStartChar },
                var info = generatedResult.selectorInfo,
                    generatedPos = { line: generatedResult.lineStart + 1, column: 0 },
                    origPos = sourceMap.originalPositionFor(generatedPos),
                    newResult;

                SourceMapManager.getSourceDocument(cssFile, origPos.source).then(function (doc) {
                    var fullPath = doc.file.fullPath,
                        selectors = selectorCache[fullPath],
                        fileExt = FileUtils.getFileExtension(fullPath),
                        docText = doc.getText(),
                        selector,
                        origLine = origPos.line - 1,
                        i;

                    // HACK? Use CSSUtils to parse SCSS selectors
                    if (!selectors) {
                        if (fileExt === "scss") {
                            selectors = NestedStyleParser.extractAllSelectors(docText);
                        } else {
                            // TODO support SASS
                            // selectors = IndentedStyleParser.extractAllSelectors(docText);
                            selectors = [];
                        }

                        selectorCache[doc.file.fullPath] = selectors;
                    }

                    // Find the original SASS selector based on the sourceMap position
                    for (i = 0; i < selectors.length; i++) {
                        selector = selectors[i];

                        if ((origLine >= selector.ruleStartLine) && (origLine <= selector.selectorEndLine)) {
                            break;
                        } else if (origLine < selector.ruleStartLine) {
                            // HACK We may skip over the actual rule/mixin due to our limited SASS parsing
                            break;
                        }
                    }

                    if (selector) {
                        // CSSUtils can't handle single line '//' comments
                        var name = selector.selector.replace("//.*\n", "");

                        newResult = {
                            name: name,
                            document: doc,
                            lineStart: selector.ruleStartLine,
                            lineEnd: selector.declListEndLine,
                            selectorGroup: selector.selectorGroup
                        };
                    }

                    // Overwrite original result
                    if (newResult) {
                        oneResult.resolve(newResult);
                    } else {
                        oneResult.reject();
                    }
                }, oneResult.reject);
            }, function () {
                // Source map error, use the original result
                oneResult.reject();
            });
        } else {
            // No source map for this result
            oneResult.reject();
        }

        return oneResult.promise();
    }

    /**
     * Replace matched CSS rules with SASS rules
     */
    function findMatchingRules(selector, htmlDocument) {
        var basePromise = baseFindMatchingRules(selector, htmlDocument),
            deferred = new $.Deferred(),
            newResults = [],
            selectorCache = {};

        // Check CSS file results for an associated source map
        basePromise.then(function (resultSelectors) {
            var parallelPromise = Async.doInParallel(resultSelectors, function (resultSelector, index) {
                var onePromise = _convertMatchingRuleResult(selectorCache, resultSelector);

                onePromise.then(function (newResult) {
                    // Use new SASS results
                    newResults[index] = newResult;
                }, function () {
                    // Use original result
                    newResults[index] = resultSelector;
                });

                return onePromise;
            });

            parallelPromise.always(function () {
                deferred.resolve(newResults);
            });
        }, deferred.reject);

        return deferred.promise();
    }

    // TODO Reconcile this with new quick edit support for SCSS/LESS in Brackets 44
    //      Can still provide value for SASS indented syntax
    // CSSUtils.findMatchingRules = findMatchingRules;

    /**
     * @private
     * CodeInspection callback to provider SASS errors
     * @param {!string} text
     * @param {!path} path
     */
    function _scanFileAsync(text, path) {
        // FIXME How to avoid calling preview() followed by compile()?
        // CodeInspection runs first firing _scanFileAsync. For now,
        // we just won't show errors when switching to a file that is not dirty
        var fileToScan = FileSystem.getFileForPath(path),
            usages = SourceMapManager.getUsageForFile(fileToScan),
            docs,
            inputFile = fileToScan,
            deferred = new $.Deferred(),
            usagePromise;

        if (_.size(usages) > 0) {
            _.find(usages, function (usage) {
                // Compile input SASS file (i.e. not partials) with in-memory document content
                usagePromise = SourceMapManager.getSourceDocuments(usage.cssFile);
                usagePromise.then(function (sourceDocs) {
                    docs = sourceDocs;
                    inputFile = usage.sourceMap.sassFile;
                });

                // Compile first usage only
                // FIXME support multiple usage?
                return true;
            });
        } else {
            docs = [];
            usagePromise = new $.Deferred().resolve().promise();
        }

        usagePromise.always(function () {
            var errorPromise = Compiler.getErrors(path);

            // If the promise is resolved, errors were cached when the file was
            // compiled as a partial.
            if (errorPromise.state() === "pending") {
                docs = docs.unshift(DocumentManager.getOpenDocumentForPath(path));
                Compiler.preview(inputFile, docs);
            }

            errorPromise.done(function (result) {
                deferred.resolve(result);
            });
        });

        return deferred.promise();
    }

    function _scanForSourceMaps() {
        // Get all .css.map files
        var promise = ProjectManager.getAllFiles(function (file) {
            return file.name.match(/\.css\.map$/i) !== null;
        });

        // Convert .css.map paths to .css output paths
        promise = promise.then(function (sourceMapFiles) {
            return sourceMapFiles.map(function (sourceMapFile) {
                // Get associated CSS file by dropping ".map"
                return {
                    sourceMapFile: sourceMapFile,
                    cssFilePath: sourceMapFile.fullPath.replace(/\.map$/i, "")
                };
            });
        });

        // Resolve css file paths to Files
        var resolvedPairs = [];
        promise = promise.then(function (pairs) {
            return Async.doInParallel(pairs, function (pair) {
                var deferred = new $.Deferred();

                FileSystem.resolve(pair.cssFilePath, function (err, cssFile) {
                    if (err) {
                        deferred.reject();
                    } else {
                        pair.cssFile = cssFile;
                        resolvedPairs.push(pair);
                        deferred.resolve();
                    }
                });

                return deferred.promise();
            });
        });

        // Read .css file sourceMappingURL
        promise.always(function () {
            resolvedPairs.forEach(function (pair) {
                var sourceMapFile = pair.sourceMapFile,
                    cssFile = pair.cssFile;

                FileUtils.readAsText(cssFile).done(function (cssText) {
                    var sourceMapRelPath = SourceMapManager.getSourceMappingURL(cssText),
                        regExp = new RegExp(sourceMapRelPath + "$");

                    // Confirm CSS sourceMappingURL matches the source map path
                    if (!sourceMapRelPath || !regExp.exec(sourceMapFile.fullPath)) {
                        return;
                    }

                    SourceMapManager.setSourceMapFile(cssFile, sourceMapFile);
                });
            });
        });
    }

    function _isSassFile(entry, regexp) {
        var isFile = entry && entry.isFile && entry.name.match(regexp);

        return isFile && ProjectManager.isWithinProject(entry);
    }

    function _isSassFileInput(entry) {
        return _isSassFile(entry, RE_INPUT_FILE);
    }

    function _isSassFilePartial(entry) {
        return _isSassFile(entry, RE_PARTIAL_FILE);
    }

    // Check if this file is referenced in one or more source maps
    function _getUsageForFile(sassFile) {
        var usages = SourceMapManager.getUsageForFile(sassFile),
            inputFiles = [];

        _.each(usages, function (usage) {
            inputFiles.push(usage.sourceMap.sassFile);
        });

        return inputFiles;
    }

    function _appReady() {
        CodeInspection.register("scss", {
            name: "SCSS",
            scanFileAsync: _scanFileAsync
        });

        CodeInspection.register("sass", {
            name: "SASS",
            scanFileAsync: _scanFileAsync
        });
    }

    $(ProjectManager).on("projectOpen", function (event, root) {
        // TODO Reset SourceMapManager when project changes

        // Scan for source maps in the new project
        _scanForSourceMaps();
    });

    // Return pending promises until preview completes
    $(Compiler).on("sourceMapPreviewStart", function (event, sassFile, cssFile) {
        if (_isSassFileInput(sassFile)) {
            SourceMapManager.setSourceMapPending(cssFile);
        }
    });

    // Update source map when preview completes and resolve promise
    $(Compiler).on("sourceMapPreviewEnd", function (event, sassFile, data) {
        if (_isSassFileInput(sassFile)) {
            SourceMapManager.setSourceMap(data.css.file, data.sourceMap.file, data.sourceMap.contents);
        }
    });

    // Reject promise waiting for a source map
    $(Compiler).on("sourceMapPreviewError", function (event, sassFile, cssFile, errors) {
        if (_isSassFileInput(sassFile)) {
            SourceMapManager.setSourceMap(cssFile);
        }
    });

    // All SASS files get compiled when changed on disk
    // TODO preferences to compile on demand, filter for file paths, etc.?
    FileSystem.on("change", function (event, entry, added, removed) {
        var filesToCompile = [],
            findUsage = [];

        if (entry) {
            if (_isSassFileInput(entry)) {
                // Compile a changed input file
                filesToCompile.push(entry);
                findUsage.push(entry);
            } else if (_isSassFilePartial(entry)) {
                // Check for usage of a partial file
                findUsage.push(entry);
            }
        }

        if (removed) {
            removed.forEach(function (removedFile) {
                // Find usages of partial files
                if (_isSassFilePartial(removedFile)) {
                    findUsage.push(removedFile);
                }

                // Clear caches
                SourceMapManager.deleteFile(removedFile);
            });
        }

        // Compile new input files (but not partials)
        if (added) {
            added.forEach(function (addedFile) {
                if (_isSassFileInput(addedFile)) {
                    filesToCompile.push(addedFile);
                }
            });
        }

        // Add input files that reference deleted/changed files
        findUsage.forEach(function (sassFile) {
            filesToCompile = filesToCompile.concat(_getUsageForFile(sassFile));
        });

        // Re-compile
        _.each(_.uniq(filesToCompile), function (entry) {
            Compiler.compile(entry);
        });
    });

    // Delay initialization until `appReady` event is fired
    AppInit.appReady(_appReady);
});<commit_msg>include in-memory docs correctly when linting<commit_after>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
/*jslint nomen:true, vars:true, regexp:true, plusplus: true*/
/*global window, console, define, brackets, $, Mustache*/

define(function (require, exports, module) {
    "use strict";

    var Compiler            = require("Compiler"),
        NestedStyleParser   = require("NestedStyleParser"),
        SASSAgent           = require("SASSAgent"),
        SourceMapManager    = require("SourceMapManager");

    var _                   = brackets.getModule("thirdparty/lodash"),
        AppInit             = brackets.getModule("utils/AppInit"),
        Async               = brackets.getModule("utils/Async"),
        CSSUtils            = brackets.getModule("language/CSSUtils"),
        CodeInspection      = brackets.getModule("language/CodeInspection"),
        DocumentManager     = brackets.getModule("document/DocumentManager"),
        FileUtils           = brackets.getModule("file/FileUtils"),
        FileSystem          = brackets.getModule("filesystem/FileSystem"),
        ProjectManager      = brackets.getModule("project/ProjectManager");

    // Distinguish input SASS files from partials
    var RE_INPUT_FILE = /^[^_].*\.(scss|sass)$/,
        RE_PARTIAL_FILE = /^_.*\.(scss|sass)$/;

    // Augment CSSUtils.findMatchingRules to support source maps
    var baseFindMatchingRules = CSSUtils.findMatchingRules;

    function _convertMatchingRuleResult(selectorCache, generatedResult) {
        // Check CSS text for a sourceMappingURL
        var oneResult = new $.Deferred(),
            cssFile = generatedResult.document.file,
            sourceMapPromise = SourceMapManager.getSourceMap(cssFile),
            match = !sourceMapPromise && SourceMapManager.getSourceMappingURL(generatedResult.document.getText());

        if (match) {
            sourceMapPromise = SourceMapManager.setSourceMapFile(cssFile, match);
        }

        if (sourceMapPromise) {
            sourceMapPromise.then(function (sourceMap) {
                // TODO core brackets change to add selectorInfo
                // generatedPos = { line: info.selectorStartLine + 1, column: info.selectorStartChar },
                var info = generatedResult.selectorInfo,
                    generatedPos = { line: generatedResult.lineStart + 1, column: 0 },
                    origPos = sourceMap.originalPositionFor(generatedPos),
                    newResult;

                SourceMapManager.getSourceDocument(cssFile, origPos.source).then(function (doc) {
                    var fullPath = doc.file.fullPath,
                        selectors = selectorCache[fullPath],
                        fileExt = FileUtils.getFileExtension(fullPath),
                        docText = doc.getText(),
                        selector,
                        origLine = origPos.line - 1,
                        i;

                    // HACK? Use CSSUtils to parse SCSS selectors
                    if (!selectors) {
                        if (fileExt === "scss") {
                            selectors = NestedStyleParser.extractAllSelectors(docText);
                        } else {
                            // TODO support SASS
                            // selectors = IndentedStyleParser.extractAllSelectors(docText);
                            selectors = [];
                        }

                        selectorCache[doc.file.fullPath] = selectors;
                    }

                    // Find the original SASS selector based on the sourceMap position
                    for (i = 0; i < selectors.length; i++) {
                        selector = selectors[i];

                        if ((origLine >= selector.ruleStartLine) && (origLine <= selector.selectorEndLine)) {
                            break;
                        } else if (origLine < selector.ruleStartLine) {
                            // HACK We may skip over the actual rule/mixin due to our limited SASS parsing
                            break;
                        }
                    }

                    if (selector) {
                        // CSSUtils can't handle single line '//' comments
                        var name = selector.selector.replace("//.*\n", "");

                        newResult = {
                            name: name,
                            document: doc,
                            lineStart: selector.ruleStartLine,
                            lineEnd: selector.declListEndLine,
                            selectorGroup: selector.selectorGroup
                        };
                    }

                    // Overwrite original result
                    if (newResult) {
                        oneResult.resolve(newResult);
                    } else {
                        oneResult.reject();
                    }
                }, oneResult.reject);
            }, function () {
                // Source map error, use the original result
                oneResult.reject();
            });
        } else {
            // No source map for this result
            oneResult.reject();
        }

        return oneResult.promise();
    }

    /**
     * Replace matched CSS rules with SASS rules
     */
    function findMatchingRules(selector, htmlDocument) {
        var basePromise = baseFindMatchingRules(selector, htmlDocument),
            deferred = new $.Deferred(),
            newResults = [],
            selectorCache = {};

        // Check CSS file results for an associated source map
        basePromise.then(function (resultSelectors) {
            var parallelPromise = Async.doInParallel(resultSelectors, function (resultSelector, index) {
                var onePromise = _convertMatchingRuleResult(selectorCache, resultSelector);

                onePromise.then(function (newResult) {
                    // Use new SASS results
                    newResults[index] = newResult;
                }, function () {
                    // Use original result
                    newResults[index] = resultSelector;
                });

                return onePromise;
            });

            parallelPromise.always(function () {
                deferred.resolve(newResults);
            });
        }, deferred.reject);

        return deferred.promise();
    }

    // TODO Reconcile this with new quick edit support for SCSS/LESS in Brackets 44
    //      Can still provide value for SASS indented syntax
    // CSSUtils.findMatchingRules = findMatchingRules;

    /**
     * @private
     * CodeInspection callback to provider SASS errors
     * @param {!string} text
     * @param {!path} path
     */
    function _scanFileAsync(text, path) {
        // FIXME How to avoid calling preview() followed by compile()?
        // CodeInspection runs first firing _scanFileAsync. For now,
        // we just won't show errors when switching to a file that is not dirty
        var fileToScan = FileSystem.getFileForPath(path),
            usages = SourceMapManager.getUsageForFile(fileToScan),
            docs,
            inputFile = fileToScan,
            deferred = new $.Deferred(),
            usagePromise;

        if (_.size(usages) > 0) {
            _.find(usages, function (usage) {
                // Compile input SASS file (i.e. not partials) with in-memory document content
                usagePromise = SourceMapManager.getSourceDocuments(usage.cssFile);
                usagePromise.then(function (sourceDocs) {
                    docs = sourceDocs;
                    inputFile = usage.sourceMap.sassFile;
                });

                // Compile first usage only
                // FIXME support multiple usage?
                return true;
            });
        } else {
            docs = [];
            usagePromise = new $.Deferred().resolve().promise();
        }

        usagePromise.always(function () {
            var errorPromise = Compiler.getErrors(path);

            // If the promise is resolved, errors were cached when the file was
            // compiled as a partial.
            if (errorPromise.state() === "pending") {
                docs.unshift(DocumentManager.getOpenDocumentForPath(path));
                Compiler.preview(inputFile, docs);
            }

            errorPromise.done(function (result) {
                deferred.resolve(result);
            });
        });

        return deferred.promise();
    }

    function _scanForSourceMaps() {
        // Get all .css.map files
        var promise = ProjectManager.getAllFiles(function (file) {
            return file.name.match(/\.css\.map$/i) !== null;
        });

        // Convert .css.map paths to .css output paths
        promise = promise.then(function (sourceMapFiles) {
            return sourceMapFiles.map(function (sourceMapFile) {
                // Get associated CSS file by dropping ".map"
                return {
                    sourceMapFile: sourceMapFile,
                    cssFilePath: sourceMapFile.fullPath.replace(/\.map$/i, "")
                };
            });
        });

        // Resolve css file paths to Files
        var resolvedPairs = [];
        promise = promise.then(function (pairs) {
            return Async.doInParallel(pairs, function (pair) {
                var deferred = new $.Deferred();

                FileSystem.resolve(pair.cssFilePath, function (err, cssFile) {
                    if (err) {
                        deferred.reject();
                    } else {
                        pair.cssFile = cssFile;
                        resolvedPairs.push(pair);
                        deferred.resolve();
                    }
                });

                return deferred.promise();
            });
        });

        // Read .css file sourceMappingURL
        promise.always(function () {
            resolvedPairs.forEach(function (pair) {
                var sourceMapFile = pair.sourceMapFile,
                    cssFile = pair.cssFile;

                FileUtils.readAsText(cssFile).done(function (cssText) {
                    var sourceMapRelPath = SourceMapManager.getSourceMappingURL(cssText),
                        regExp = new RegExp(sourceMapRelPath + "$");

                    // Confirm CSS sourceMappingURL matches the source map path
                    if (!sourceMapRelPath || !regExp.exec(sourceMapFile.fullPath)) {
                        return;
                    }

                    SourceMapManager.setSourceMapFile(cssFile, sourceMapFile);
                });
            });
        });
    }

    function _isSassFile(entry, regexp) {
        var isFile = entry && entry.isFile && entry.name.match(regexp);

        return isFile && ProjectManager.isWithinProject(entry);
    }

    function _isSassFileInput(entry) {
        return _isSassFile(entry, RE_INPUT_FILE);
    }

    function _isSassFilePartial(entry) {
        return _isSassFile(entry, RE_PARTIAL_FILE);
    }

    // Check if this file is referenced in one or more source maps
    function _getUsageForFile(sassFile) {
        var usages = SourceMapManager.getUsageForFile(sassFile),
            inputFiles = [];

        _.each(usages, function (usage) {
            inputFiles.push(usage.sourceMap.sassFile);
        });

        return inputFiles;
    }

    function _appReady() {
        CodeInspection.register("scss", {
            name: "SCSS",
            scanFileAsync: _scanFileAsync
        });

        CodeInspection.register("sass", {
            name: "SASS",
            scanFileAsync: _scanFileAsync
        });
    }

    $(ProjectManager).on("projectOpen", function (event, root) {
        // TODO Reset SourceMapManager when project changes

        // Scan for source maps in the new project
        _scanForSourceMaps();
    });

    // Return pending promises until preview completes
    $(Compiler).on("sourceMapPreviewStart", function (event, sassFile, cssFile) {
        if (_isSassFileInput(sassFile)) {
            SourceMapManager.setSourceMapPending(cssFile);
        }
    });

    // Update source map when preview completes and resolve promise
    $(Compiler).on("sourceMapPreviewEnd", function (event, sassFile, data) {
        if (_isSassFileInput(sassFile)) {
            SourceMapManager.setSourceMap(data.css.file, data.sourceMap.file, data.sourceMap.contents);
        }
    });

    // Reject promise waiting for a source map
    $(Compiler).on("sourceMapPreviewError", function (event, sassFile, cssFile, errors) {
        if (_isSassFileInput(sassFile)) {
            SourceMapManager.setSourceMap(cssFile);
        }
    });

    // All SASS files get compiled when changed on disk
    // TODO preferences to compile on demand, filter for file paths, etc.?
    FileSystem.on("change", function (event, entry, added, removed) {
        var filesToCompile = [],
            findUsage = [];

        if (entry) {
            if (_isSassFileInput(entry)) {
                // Compile a changed input file
                filesToCompile.push(entry);
                findUsage.push(entry);
            } else if (_isSassFilePartial(entry)) {
                // Check for usage of a partial file
                findUsage.push(entry);
            }
        }

        if (removed) {
            removed.forEach(function (removedFile) {
                // Find usages of partial files
                if (_isSassFilePartial(removedFile)) {
                    findUsage.push(removedFile);
                }

                // Clear caches
                SourceMapManager.deleteFile(removedFile);
            });
        }

        // Compile new input files (but not partials)
        if (added) {
            added.forEach(function (addedFile) {
                if (_isSassFileInput(addedFile)) {
                    filesToCompile.push(addedFile);
                }
            });
        }

        // Add input files that reference deleted/changed files
        findUsage.forEach(function (sassFile) {
            filesToCompile = filesToCompile.concat(_getUsageForFile(sassFile));
        });

        // Re-compile
        _.each(_.uniq(filesToCompile), function (entry) {
            Compiler.compile(entry);
        });
    });

    // Delay initialization until `appReady` event is fired
    AppInit.appReady(_appReady);
});<|endoftext|>


<commit_before>// start up scheduled tasks
require('./cronjobs.js');

// load config
var config = require('config');
const { login } = require('libfb');

// load module definitions
var commandDescriptions = require('./modules.json');

var prefixLen = 1;

// return module that handles a command
var commands = commandDescriptions .map(function(cmd) {
  return require('./' + cmd['path']);
});

var superagent = require('superagent');

// parse messages for handling
(async() => {
  const api = await login('rob@kedarv.com', 'testingx1');
  api.on('message', message => {
    message_text = message.message;
    if(isCommand(message_text)) {
      var commandString = message_text.slice(prefixLen);
      var trigger = commandString.substring(0, endOfCmd(commandString));
      commands.forEach(function(cmd, index) {
        if(trigger == commandDescriptions[index]['trigger']) {
          const args = commandString.slice(trigger.length+1) || '';
          cmd.trigger(args, api, message);
        }
      });
    }
  });
})();

// determine the end of the command
function endOfCmd(cmd) {
  if(cmd.indexOf(' ') > 0) {
    return cmd.indexOf(' ');
  } else {
    return cmd.length;
  }
}

// determine if a received message is a command
function isCommand(message) {
  if (!(message)) {
    return false;
  } else if (config.get('usePrefix')) {
    prefixLen = config.get('botPrefix').length + 1;
    return message.startsWith(config.get('botPrefix'));
  } else {
    return message.startsWith('/');
  }
}
<commit_msg>read authentication details from config<commit_after>// start up scheduled tasks
require('./cronjobs.js');

// load config
var config = require('config');
const { login } = require('libfb');

// load module definitions
var commandDescriptions = require('./modules.json');

var prefixLen = 1;

// return module that handles a command
var commands = commandDescriptions .map(function(cmd) {
  return require('./' + cmd['path']);
});

var superagent = require('superagent');

// parse messages for handling
(async() => {
  const api = await login(config.get('botUsername'), config.get('botPassword'));
  api.on('message', message => {
    message_text = message.message;
    if(isCommand(message_text)) {
      var commandString = message_text.slice(prefixLen);
      var trigger = commandString.substring(0, endOfCmd(commandString));
      commands.forEach(function(cmd, index) {
        if(trigger == commandDescriptions[index]['trigger']) {
          const args = commandString.slice(trigger.length+1) || '';
          cmd.trigger(args, api, message);
        }
      });
    }
  });
})();

// determine the end of the command
function endOfCmd(cmd) {
  if(cmd.indexOf(' ') > 0) {
    return cmd.indexOf(' ');
  } else {
    return cmd.length;
  }
}

// determine if a received message is a command
function isCommand(message) {
  if (!(message)) {
    return false;
  } else if (config.get('usePrefix')) {
    prefixLen = config.get('botPrefix').length + 1;
    return message.startsWith(config.get('botPrefix'));
  } else {
    return message.startsWith('/');
  }
}
<|endoftext|>