<commit_before>import React, { Component } from 'react'

import BetJson from '../build/contracts/Bet.json'
import getWeb3 from '../utils/getWeb3'

class Bet extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bet_state: '',
      is_featured: false,
      title: '',
      category: '',
      team_0: '',
      team_1: '',
      team_0_bet_sum: 0,
      team_1_bet_sum: 0,
      bets_to_team_0: {},
      bets_to_team_1: {},
      timestamp_match_begin: 0,
      timestamp_match_end: 0,
      timestamp_hard_deadline: 0,
      timestamp_terminate_deadline: 0,
      url_oraclize: '',
      web3: null, // TODO: REMOVE WEB3, DO STATIC
    }
  }

  componentWillMount() {
    // Get network provider and web3 instance.
    // See utils/getWeb3 for more info.

    getWeb3
    .then(results => {
      this.setState({
        web3: results.web3
      })

      // Instantiate contract once web3 provided.
      this.instantiateContract();
    })
    .catch((err) => {
      console.log('Error finding web3', err);
    })
  }

  instantiateContract() {
    var self = this;
    function setAttribute(attributeNames, contractInstance) {
      Object.keys(attributeNames).map(async (attr) => {
        if (attr !== 'web3' // FIXME: REMOVE ONCE WEB3 IS NOT HERE
            && attr !== 'bets_to_team_0' // Cannot get mapping keys, no prob: get from events
            && attr !== 'bets_to_team_1') { // idem
          var obj = {};
          obj[attr] = await betContractInstance[attr]();
          if (typeof obj[attr] === 'object') // Handle Big Number
            obj[attr] = obj[attr].toNumber();
          else
            obj[attr] = obj[attr].toString();
          self.setState(obj);
        }
      });
    }

    const contract = require('truffle-contract');
    const betContract = contract(BetJson);
    betContract.setProvider(this.state.web3.currentProvider);

    // Declaring this for later so we can chain functions on SimpleStorage.
    var betContractInstance = betContract.at(this.props.address);
    setAttribute(this.state, betContractInstance);

    betContractInstance.title(title => {console.log('TITLE', title);})

    var betEvents = betContractInstance.new_bet({fromBlock: 0, toBlock: 'latest'});
    console.log(betEvents);
    betEvents.watch((error, response) => {
      console.log('Bet:', response.args);
      if (response.args.for_team === false)
        this.setState({ team_0_bet_sum : this.state.team_0_bet_sum + response.args.amount.toNumber() });
      else
        this.setState({ team_1_bet_sum : this.state.team_1_bet_sum + response.args.amount.toNumber() });
    });
  }

  render() {
    return (

Title: {this.state.title}

        Addr: {this.props.address}

        State: {this.state.bet_state}

        Featured: {this.state.is_featured}

        Team0 {this.state.team_0}: ${this.state.team_0_bet_sum}

        Team1 {this.state.team_1}: ${this.state.team_1_bet_sum}

        Category: {this.state.category}

        Begins: {this.state.timestamp_match_begin}

        Ends: {this.state.timestamp_match_end}

        Hard Deadline: {this.state.timestamp_hard_deadline}

        Terminate Deadline: {this.state.timestamp_terminate_deadline}

        Oracle: {this.state.url_oraclize}

    );
  }
}

export default Bet;<commit_msg>Bet render just once<commit_after>import React, { Component } from 'react'

import BetJson from '../build/contracts/Bet.json'
import getWeb3 from '../utils/getWeb3'

class Bet extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bet_state: '',
      is_featured: false,
      title: '',
      category: '',
      team_0: '',
      team_1: '',
      team_0_bet_sum: 0,
      team_1_bet_sum: 0,
      bets_to_team_0: {},
      bets_to_team_1: {},
      timestamp_match_begin: 0,
      timestamp_match_end: 0,
      timestamp_hard_deadline: 0,
      timestamp_terminate_deadline: 0,
      url_oraclize: '',
      web3: null, // TODO: REMOVE WEB3, DO STATIC
    }
  }

  componentWillMount() {
    // Get network provider and web3 instance.
    // See utils/getWeb3 for more info.

    getWeb3
    .then(results => {
      this.setState({
        web3: results.web3
      })

      // Instantiate contract once web3 provided.
      this.instantiateContract();
    })
    .catch((err) => {
      console.log('Error finding web3', err);
    })
  }

  instantiateContract() {
    var self = this;
    var objs = {};
    function setAttributes(attributeNames, contractInstance) {
      var promises = Object.keys(attributeNames).map(async (attr) => {
        if (attr !== 'web3' // FIXME: REMOVE ONCE WEB3 IS NOT HERE
            && attr !== 'bets_to_team_0' // Cannot get mapping keys, no prob: get from events
            && attr !== 'bets_to_team_1') { // idem

          var res = await betContractInstance[attr]();
          if (typeof res === 'object') // Handle BigNumber
            res = res.toNumber();
          else
            res = res.toString();
          objs[attr] = res;
          // self.setState(obj);
        }
      });
      Promise.all(promises).then(res => {
        self.setState(objs);
      })
    }

    const contract = require('truffle-contract');
    const betContract = contract(BetJson);
    betContract.setProvider(this.state.web3.currentProvider);

    // Declaring this for later so we can chain functions on SimpleStorage.
    var betContractInstance = betContract.at(this.props.address);
    setAttributes(this.state, betContractInstance);

    var betEvents = betContractInstance.new_bet({fromBlock: 0, toBlock: 'latest'});
    console.log(betEvents);
    betEvents.watch((error, response) => {
      console.log('Bet:', response.args);
      if (response.args.for_team === false)
        this.setState({ team_0_bet_sum : this.state.team_0_bet_sum + response.args.amount.toNumber() });
      else
        this.setState({ team_1_bet_sum : this.state.team_1_bet_sum + response.args.amount.toNumber() });
    });
  }

  render() {
    var teams = this.state.title.split('x');
    console.log(teams);
    return (

{teams[0]}

{teams[1]}

        Addr: {this.props.address}

        State: {this.state.bet_state}

        Featured: {this.state.is_featured}

        Team0 {this.state.team_0}: ${this.state.team_0_bet_sum}

        Team1 {this.state.team_1}: ${this.state.team_1_bet_sum}

        Category: {this.state.category}

        Begins: {this.state.timestamp_match_begin}

        Ends: {this.state.timestamp_match_end}

        Hard Deadline: {this.state.timestamp_hard_deadline}

        Terminate Deadline: {this.state.timestamp_terminate_deadline}

        Oracle: {this.state.url_oraclize}

    );
  }
}

export default Bet;<|endoftext|>


<commit_before>/* eslint jasmine/prefer-toHaveBeenCalledWith:0 */
const fs = require('fs');
const {resolve} = require('canonical-path');
const {generateDocs} = require('./index.js');
const { DOCS_OUTPUT_PATH } = require('../config');

describe('authors-package (integration tests)', () => {
  let originalJasmineTimeout;
  let files;

  beforeAll(() => {
    originalJasmineTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
  });
  afterAll(() => jasmine.DEFAULT_TIMEOUT_INTERVAL = originalJasmineTimeout);

  beforeEach(() => {
    files = [];
    spyOn(fs, 'writeFile').and.callFake((file, content, callback) => {
      files.push(file);
      callback();
    });
  });

  it('should generate marketing docs if the "fileChanged" is a marketing doc', (done) => {
    generateDocs('aio/content/marketing/about.html', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'about.json'));
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, '../navigation.json'));
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, '../contributors.json'));
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, '../resources.json'));
      done();
    });
  });

  it('should generate tutorial docs if the "fileChanged" is a tutorial doc', (done) => {
    generateDocs('aio/content/tutorial/toh-pt5.md', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'tutorial/toh-pt5.json'));
      done();
    });
  });

  it('should generate tutorial docs if the "fileChanged" is the tutorial index', (done) => {
    generateDocs('aio/content/tutorial/index.md', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'tutorial.json'));
      done();
    });
  });

  it('should generate tutorial docs if the "fileChanged" is a tutorial example', (done) => {
    generateDocs('aio/content/examples/toh-pt3/app/app.component.1.html', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'tutorial/toh-pt3.json'));
      done();
    });
  });

  it('should generate guide doc if the "fileChanged" is a guide doc', (done) => {
    generateDocs('aio/content/guide/architecture.md', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'guide/architecture.json'));
      done();
    });
  });

  it('should generate guide doc if the "fileChanged" is a guide example', (done) => {
    generateDocs('aio/content/examples/architecture/src/app/app.module.ts', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'guide/architecture.json'));
      done();
    });
  });

  it('should generate API doc if the "fileChanged" is an API doc', (done) => {
    generateDocs('packages/forms/src/form_builder.ts', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'api/forms/FormBuilder.json'));
      done();
    });
  }, 16000);

  it('should generate API doc if the "fileChanged" is an API example', (done) => {
    generateDocs('packages/examples/forms/ts/formBuilder/form_builder_example.ts', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'api/forms/FormBuilder.json'));
      done();
    });
  }, 16000);
});
<commit_msg>style(aio): add newline between test blocks (#22401)<commit_after>/* eslint jasmine/prefer-toHaveBeenCalledWith:0 */
const fs = require('fs');
const {resolve} = require('canonical-path');
const {generateDocs} = require('./index.js');
const { DOCS_OUTPUT_PATH } = require('../config');

describe('authors-package (integration tests)', () => {
  let originalJasmineTimeout;
  let files;

  beforeAll(() => {
    originalJasmineTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
  });

  afterAll(() => jasmine.DEFAULT_TIMEOUT_INTERVAL = originalJasmineTimeout);

  beforeEach(() => {
    files = [];
    spyOn(fs, 'writeFile').and.callFake((file, content, callback) => {
      files.push(file);
      callback();
    });
  });

  it('should generate marketing docs if the "fileChanged" is a marketing doc', (done) => {
    generateDocs('aio/content/marketing/about.html', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'about.json'));
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, '../navigation.json'));
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, '../contributors.json'));
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, '../resources.json'));
      done();
    });
  });

  it('should generate tutorial docs if the "fileChanged" is a tutorial doc', (done) => {
    generateDocs('aio/content/tutorial/toh-pt5.md', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'tutorial/toh-pt5.json'));
      done();
    });
  });

  it('should generate tutorial docs if the "fileChanged" is the tutorial index', (done) => {
    generateDocs('aio/content/tutorial/index.md', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'tutorial.json'));
      done();
    });
  });

  it('should generate tutorial docs if the "fileChanged" is a tutorial example', (done) => {
    generateDocs('aio/content/examples/toh-pt3/app/app.component.1.html', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'tutorial/toh-pt3.json'));
      done();
    });
  });

  it('should generate guide doc if the "fileChanged" is a guide doc', (done) => {
    generateDocs('aio/content/guide/architecture.md', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'guide/architecture.json'));
      done();
    });
  });

  it('should generate guide doc if the "fileChanged" is a guide example', (done) => {
    generateDocs('aio/content/examples/architecture/src/app/app.module.ts', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'guide/architecture.json'));
      done();
    });
  });

  it('should generate API doc if the "fileChanged" is an API doc', (done) => {
    generateDocs('packages/forms/src/form_builder.ts', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'api/forms/FormBuilder.json'));
      done();
    });
  }, 16000);

  it('should generate API doc if the "fileChanged" is an API example', (done) => {
    generateDocs('packages/examples/forms/ts/formBuilder/form_builder_example.ts', { silent: true }).then(() => {
      expect(fs.writeFile).toHaveBeenCalled();
      expect(files).toContain(resolve(DOCS_OUTPUT_PATH, 'api/forms/FormBuilder.json'));
      done();
    });
  }, 16000);
});
<|endoftext|>


<commit_before>// import { padded } from 'pristine-app';

// forms
import Button from './components/Button';
import FieldGroup from './components/FieldGroup';
import Label from './components/Label';
import Form from './components/Form';
import FormBox from './components/FormBox';
import TextInput from './components/TextInput';
import Toggle from './components/Toggle';
import RadioGroup from './components/RadioGroup';
import Select from './components/Select';

// layout
import Accordion from './components/Accordion';
import AccordionGroup from './components/AccordionGroup';
import Card from './components/Card';
import FluidGridList from './components/FluidGridList';
import ScrollBox from './components/ScrollBox';
import SidebarLayout from './components/SidebarLayout';

// navigation
import TabGroup from './components/TabGroup';
import Link from './components/Link';
import TopNav from './components/TopNav';

// misc
import Code from './components/Code';
import ErrorScreen from './components/ErrorScreen';

// themes
import defaultTheme from './themes/default';
import smallTheme from './themes/small';
import secondaryTheme from './themes/secondary';
import errorTheme from './themes/error';

export const components = {
  forms: [
    Form,
    FormBox,
    Button,
    TextInput,
    RadioGroup,
    Select,
    Toggle,
    Label,
    FieldGroup,
  ],

  layout: [
    Accordion,
    AccordionGroup,
    Card,
    FluidGridList,
    ScrollBox,
    SidebarLayout,
  ],

  navigation: [
    TabGroup,
    Link,
    TopNav,
  ],

  misc: [
    Code,
    ErrorScreen,
  ],
};

// add any styled-components themes you want to use here
export const themes = [
  defaultTheme,
  smallTheme,
  secondaryTheme,
  errorTheme,
];

// you can specify a custom header by exporting one. can be a string, or a React node
export const header = 'Bandwidth Shared Components';
<commit_msg>add lists to pristineg<commit_after>// import { padded } from 'pristine-app';

// forms
import Button from './components/Button';
import FieldGroup from './components/FieldGroup';
import Label from './components/Label';
import Form from './components/Form';
import FormBox from './components/FormBox';
import TextInput from './components/TextInput';
import Toggle from './components/Toggle';
import RadioGroup from './components/RadioGroup';
import Select from './components/Select';

// layout
import Accordion from './components/Accordion';
import AccordionGroup from './components/AccordionGroup';
import Card from './components/Card';
import FluidGridList from './components/FluidGridList';
import ScrollBox from './components/ScrollBox';
import SidebarLayout from './components/SidebarLayout';
import List from './components/List';
import ListItem from './components/ListItem';

// navigation
import TabGroup from './components/TabGroup';
import Link from './components/Link';
import TopNav from './components/TopNav';

// misc
import Code from './components/Code';
import ErrorScreen from './components/ErrorScreen';

// themes
import defaultTheme from './themes/default';
import smallTheme from './themes/small';
import secondaryTheme from './themes/secondary';
import errorTheme from './themes/error';

export const components = {
  forms: [
    Form,
    FormBox,
    Button,
    TextInput,
    RadioGroup,
    Select,
    Toggle,
    Label,
    FieldGroup,
  ],

  layout: [
    Accordion,
    AccordionGroup,
    Card,
    FluidGridList,
    ScrollBox,
    SidebarLayout,
    List,
    ListItem,
  ],

  navigation: [
    TabGroup,
    Link,
    TopNav,
  ],

  misc: [
    Code,
    ErrorScreen,
  ],
};

// add any styled-components themes you want to use here
export const themes = [
  defaultTheme,
  smallTheme,
  secondaryTheme,
  errorTheme,
];

// you can specify a custom header by exporting one. can be a string, or a React node
export const header = 'Bandwidth Shared Components';
<|endoftext|>


<commit_before>/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    // Add options here
    emberHighCharts: {
      includeHighCharts: true,
      includeModules: ['exporting']
      /* available modules:
      boost, broken-axis, canvas-tools, data, drilldown, exporting, funnel,
      heatmap, map, no-data-to-display, offline-exporting, solid-gauge, treemap
      */
    }
  });

  // Use `app.import` to add additional libraries to the generated
  // output files.
  //
  // If you need to use different assets in different
  // environments, specify an object as the first parameter. That
  // object's keys should be the environment name and the values
  // should be the asset to use in that environment.
  //
  // If the library that you are including contains AMD or ES6
  // modules that you would like to import into your application
  // please specify an object with the list of modules as keys
  // along with the exports of each module as its value.

  return app.toTree();
};
<commit_msg>inlude polyfill and (hopefully) fix IE bug: Login screen doesn't load<commit_after>/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    // Add options here
    babel: {
      includePolyfill: true
    },
    emberHighCharts: {
      includeHighCharts: true,
      includeModules: ['exporting']
      /* available modules:
      boost, broken-axis, canvas-tools, data, drilldown, exporting, funnel,
      heatmap, map, no-data-to-display, offline-exporting, solid-gauge, treemap
      */
    }
  });

  // Use `app.import` to add additional libraries to the generated
  // output files.
  //
  // If you need to use different assets in different
  // environments, specify an object as the first parameter. That
  // object's keys should be the environment name and the values
  // should be the asset to use in that environment.
  //
  // If the library that you are including contains AMD or ES6
  // modules that you would like to import into your application
  // please specify an object with the list of modules as keys
  // along with the exports of each module as its value.

  return app.toTree();
};
<|endoftext|>


<commit_before>/**
 * Returns an object {name, index} having a generated name and an index
 * for a Creep with memory.role 'role' which is to be spawned by Spawn 'spawn'
 */
function getNameByRole(spawn, role)
{
    var creepIndex = 0;
    var creeps = Game.creeps;

    while (creeps [spawn.room.name + ' ' + role + ' ' + creepIndex])
    {
        creepIndex++;
    }

    var answer =
    {
        name : spawn.room.name + ' ' + role + ' ' + creepIndex,
        index : creepIndex
    };
    return answer;
}

/**
 * Makes a Spawn 'spawn' create a Creep with memory.role 'role' and bodyparts 'parts'
 */
function createByRole (spawn, role, parts)
{
    var creepInfo = getNameByRole(spawn, role);

    var spawnOutput = spawn.createCreep(parts, creepInfo.name, { role: role, index: creepInfo.index })

    // If spawning process started succesfully
    if (spawnOutput == creepInfo.name)
    {
        console.log("Spawning " + role + ": " + creepInfo.name);
        return true;
    }

    console.log ("Couldn't spawn a creep, error: " + spawnOutput);
    return false;
}

/**
 * Adds 'creepSpecs' ([role, parts]) to Spawn 'spawn's production queue
 */
function pushToQueue (spawn, creepSpecs)
{
    if (!spawn.memory.queue)
    {
        spawn.memory.queue = [];
    }

    console.log ("Creep pushed to production queue:");
    console.log ('  role: ' + creepSpecs [0]);
    console.log ('  body: ' + creepSpecs [1]);

    spawn.memory.queue.push (creepSpecs);
}

/**
 * Returns how many (integer) creeps with memory.role 'role'
 * are already in Spawn "spawn"'s creation queue
 */
function countInQueue(spawn, role)
{
    var inQueue = 0;
    for (var i in spawn.memory.queue)
    {
        var creepSpec = spawn.memory.queue[i];
        if (creepSpec[0] == role)
        {
            inQueue++;
        }
    }
    return inQueue;
}

/** Checks if there are more or equal Creeps with memory.role 'role' in the same room
 * as Spawn 'spawn'. If not, schedules the appropriate amount of such Creeps to be produced
 * by Spawn 'spawn' with bodies specified by 'parts'. 'creeps' contains already existing creeps
 * of any role. 'creeps' is of type <string, Creep array>
 */
function checkCreepSupply(spawn, role, creeps, desiredAmount, parts)
{

    if (spawn.spawning)
    {
        return;
    }

    if (!spawn.memory.queue)
    {
        spawn.memory.queue = [];
    }

    // num of creeps in the room
    var inRoom = creeps[role] ? creeps[role].length : 0;
    // num of creeps scheduled for creation
    var inQueue = countInQueue(spawn, role);
    // adds creeps to the queue until the total of in room
    // and in queue reaches the desired amount of creeps
    while (inRoom + inQueue < desiredAmount)
    {
        pushToQueue (spawn, [role, parts]);
        inQueue++;
    }

}

var LIFETIME = 1500;
/**
 * If called every tick, makes Spawn 'spawn' produce a Creep with memory.role 'role'
 * and body specified by 'parts' every 'interval' amount of ticks with stagger 'stagger'
 */
function spawnCreepEvery(spawn, role, interval, stagger, parts)
{
    if ((Game.time - stagger) % interval == 0 && countInQueue(spawn, role) == 0)
    {
        pushToQueue (spawn, [role, parts]);
    }
}

/**
 * Makes Spawn 'spawn' create Creeps according to its creation queue
 */
function spawnFromQueue(spawn)
{
    // Spawn's busy
    if (spawn.spawning)
        return;
    // Nothing to create, queue's empty
    if (!spawn.memory.queue || !spawn.memory.queue.length)
        return;
    // Creation process started successfully
    if (createByRole(spawn, spawn.memory.queue[0][0], spawn.memory.queue[0][1]))
    {
        spawn.memory.queue.shift();
    }
}

var COST            = {};
COST[MOVE]          = 50;
COST[WORK]          = 100;
COST[CARRY]         = 50;
COST[ATTACK]        = 80;
COST[RANGED_ATTACK] = 150;
COST[HEAL]          = 250;
COST[TOUGH]         = 10;

/**
 * Calculates the energy cost of a Creep with bodyparts 'parts'
 */
function calculateCost (parts)
{
    var cost = 0;
    for (var i in parts)
    {
        var part = parts[i];
        if (COST[part])
        {
            cost += COST[part];
        }
    }
    return cost;
}

var MAX_PARTS = 30;

function generateBody (baseParts, maxEnergy)
{
    var baseBody = [];
    baseBody = baseBody.concat (baseParts);

    // Add enough MOVE parts to let it move at half the max speed
    for (var i = 0; i < baseParts.length / 2; i++)
    {
        baseBody.push (MOVE);
    }

    // How many baseBodys we can produce with maxEnergy
    var times = Math.floor (maxEnergy / calculateCost(baseBody));

    // If there are more parts than maximum, lower the 'times' accordingly
    if (times * baseBody.length > MAX_PARTS)
    {
        times = Math.floor (MAX_PARTS / baseBody.length);
    }
    else if (times == 0)
    {
        return [];
    }

    // Construct a finalBody out of 'times' baseBodys, which is the biggest body affordable for the maxEnergy
    var finalBody = [];
    for (var i = 0; i < times; i++)
    {
        finalBody = finalBody.concat (baseBody);
    }

    //console.log ('---------------');
    //console.log ('baseBody cost: '  + calculateCost(baseBody));
    //console.log ('maximum energy: ' + maxEnergy);
    //console.log ('finalBody: '      + finalBody);
    //console.log ('---------------');
    return finalBody;
}

/**
 * Makes Spawn 'spawn' perform spawner behaviour
 */
module.exports = function (spawn)
{
    var allCreeps = spawn.room.find(FIND_MY_CREEPS);

    // Make a dictionary 'roleCreeps' <string, Creep Array>
    // with roles as hash codes
    var roleCreeps = {};
    for (var i in allCreeps)
    {
        var thisCreep = allCreeps[i];

        if (!roleCreeps[thisCreep.memory.role])
        {
            roleCreeps[thisCreep.memory.role] = [];
        }

        roleCreeps[thisCreep.memory.role].push(thisCreep);
    }

    // Get total energy usable in Creep creation
    var totalEnergy = spawn.energy;

    // Find all extensions
    var extensions = spawn.room.find(FIND_MY_STRUCTURES, {
        filter: function (s)
        {
            return s.structureType == STRUCTURE_EXTENSION;
        }
    });

    for (var i in extensions)
    {
        totalEnergy += extensions[i].energy;
    }

    var baseBodies = require ('baseBodies');

    // Max energy a single creep may cost
    var spawningEnergy = totalEnergy;

    var harvesterBody = generateBody (baseBodies['harvester'], spawningEnergy);
    var guardBody =     generateBody (baseBodies['guard'],     spawningEnergy);

    spawnCreepEvery  (spawn, 'harvester', Math.round(LIFETIME / 6), 0, harvesterBody);
    checkCreepSupply (spawn, 'harvester', roleCreeps,               3, harvesterBody);

    spawnCreepEvery (spawn, 'upgrader', LIFETIME / 2, 100, generateBody (baseBodies['upgrader'], spawningEnergy));
    spawnCreepEvery (spawn, 'builder',  LIFETIME / 2, 200, generateBody (baseBodies['builder'],  spawningEnergy));

    // Find all storages in the room
    var storages = spawn.room.find(FIND_MY_STRUCTURES, {
        filter: function (s)
        {
            return s.structureType == STRUCTURE_STORAGE;
        }
    });

    // If there are storages in the room, schedule creation of tankers
    if (storages.length >= 1)
    {
        var tankerBody = generateBody (baseBodies['tanker'], spawningEnergy);
        checkCreepSupply (spawn, 'tanker', roleCreeps,   1,   tankerBody);
        spawnCreepEvery  (spawn, 'tanker', LIFETIME / 2, 400, tankerBody);
    }

    // Make number of guards and number of enemies in the room match
    var targets = spawn.room.find (FIND_HOSTILE_CREEPS);
    var min = targets.length < 1 ? 1 : targets.length;
    checkCreepSupply (spawn, 'guard', roleCreeps, min, guardBody);

    spawnFromQueue (spawn);
}<commit_msg>Add checks that given body isn't empty<commit_after>/**
 * Returns an object {name, index} having a generated name and an index
 * for a Creep with memory.role 'role' which is to be spawned by Spawn 'spawn'
 */
function getNameByRole(spawn, role)
{
    var creepIndex = 0;
    var creeps = Game.creeps;

    while (creeps [spawn.room.name + ' ' + role + ' ' + creepIndex])
    {
        creepIndex++;
    }

    var answer =
    {
        name : spawn.room.name + ' ' + role + ' ' + creepIndex,
        index : creepIndex
    };
    return answer;
}

/**
 * Makes a Spawn 'spawn' create a Creep with memory.role 'role' and bodyparts 'parts'
 */
function createByRole (spawn, role, parts)
{
    var creepInfo = getNameByRole(spawn, role);

    var spawnOutput = spawn.createCreep(parts, creepInfo.name, { role: role, index: creepInfo.index })

    // If spawning process started succesfully
    if (spawnOutput == creepInfo.name)
    {
        console.log("Spawning " + role + ": " + creepInfo.name);
        return true;
    }

    console.log ("Couldn't spawn a creep, error: " + spawnOutput);
    return false;
}

/**
 * Adds 'creepSpecs' ([role, parts]) to Spawn 'spawn's production queue
 */
function pushToQueue (spawn, creepSpecs)
{
    if (!spawn.memory.queue)
    {
        spawn.memory.queue = [];
    }

    console.log ("Creep pushed to production queue:");
    console.log ('  role: ' + creepSpecs [0]);
    console.log ('  body: ' + creepSpecs [1]);

    spawn.memory.queue.push (creepSpecs);
}

/**
 * Returns how many (integer) creeps with memory.role 'role'
 * are already in Spawn "spawn"'s creation queue
 */
function countInQueue(spawn, role)
{
    var inQueue = 0;
    for (var i in spawn.memory.queue)
    {
        var creepSpec = spawn.memory.queue[i];
        if (creepSpec[0] == role)
        {
            inQueue++;
        }
    }
    return inQueue;
}

/** Checks if there are more or equal Creeps with memory.role 'role' in the same room
 * as Spawn 'spawn'. If not, schedules the appropriate amount of such Creeps to be produced
 * by Spawn 'spawn' with bodies specified by 'parts'. 'creeps' contains already existing creeps
 * of any role. 'creeps' is of type <string, Creep array>
 */
function checkCreepSupply(spawn, role, creeps, desiredAmount, parts)
{

    if (spawn.spawning)
    {
        return;
    }

    if (!spawn.memory.queue)
    {
        spawn.memory.queue = [];
    }

    // num of creeps in the room
    var inRoom = creeps[role] ? creeps[role].length : 0;
    // num of creeps scheduled for creation
    var inQueue = countInQueue(spawn, role);
    // adds creeps to the queue until the total of in room
    // and in queue reaches the desired amount of creeps
    while (inRoom + inQueue < desiredAmount)
    {
        pushToQueue (spawn, [role, parts]);
        inQueue++;
    }

}

var LIFETIME = 1500;
/**
 * If called every tick, makes Spawn 'spawn' produce a Creep with memory.role 'role'
 * and body specified by 'parts' every 'interval' amount of ticks with stagger 'stagger'
 */
function spawnCreepEvery(spawn, role, interval, stagger, parts)
{
    if ((Game.time - stagger) % interval == 0 && countInQueue(spawn, role) == 0)
    {
        pushToQueue (spawn, [role, parts]);
    }
}

/**
 * Makes Spawn 'spawn' create Creeps according to its creation queue
 */
function spawnFromQueue(spawn)
{
    // Spawn's busy
    if (spawn.spawning)
        return;
    // Nothing to create, queue's empty
    if (!spawn.memory.queue || !spawn.memory.queue.length)
        return;
    // Creation process started successfully
    if (createByRole(spawn, spawn.memory.queue[0][0], spawn.memory.queue[0][1]))
    {
        spawn.memory.queue.shift();
    }
}

var COST            = {};
COST[MOVE]          = 50;
COST[WORK]          = 100;
COST[CARRY]         = 50;
COST[ATTACK]        = 80;
COST[RANGED_ATTACK] = 150;
COST[HEAL]          = 250;
COST[TOUGH]         = 10;

/**
 * Calculates the energy cost of a Creep with bodyparts 'parts'
 */
function calculateCost (parts)
{
    var cost = 0;
    for (var i in parts)
    {
        var part = parts[i];
        if (COST[part])
        {
            cost += COST[part];
        }
    }
    return cost;
}

var MAX_PARTS = 30;

function generateBody (baseParts, maxEnergy)
{
    var baseBody = [];
    baseBody = baseBody.concat (baseParts);

    // Add enough MOVE parts to let it move at half the max speed
    for (var i = 0; i < baseParts.length / 2; i++)
    {
        baseBody.push (MOVE);
    }

    // How many baseBodys we can produce with maxEnergy
    var times = Math.floor (maxEnergy / calculateCost(baseBody));

    // If there are more parts than maximum, lower the 'times' accordingly
    if (times * baseBody.length > MAX_PARTS)
    {
        times = Math.floor (MAX_PARTS / baseBody.length);
    }
    else if (times == 0)
    {
        return [];
    }

    // Construct a finalBody out of 'times' baseBodys, which is the biggest body affordable for the maxEnergy
    var finalBody = [];
    for (var i = 0; i < times; i++)
    {
        finalBody = finalBody.concat (baseBody);
    }

    //console.log ('---------------');
    //console.log ('baseBody cost: '  + calculateCost(baseBody));
    //console.log ('maximum energy: ' + maxEnergy);
    //console.log ('finalBody: '      + finalBody);
    //console.log ('---------------');
    return finalBody;
}

/**
 * Makes Spawn 'spawn' perform spawner behaviour
 */
module.exports = function (spawn)
{
    var allCreeps = spawn.room.find(FIND_MY_CREEPS);

    // Make a dictionary 'roleCreeps' <string, Creep Array>
    // with roles as hash codes
    var roleCreeps = {};
    for (var i in allCreeps)
    {
        var thisCreep = allCreeps[i];

        if (!roleCreeps[thisCreep.memory.role])
        {
            roleCreeps[thisCreep.memory.role] = [];
        }

        roleCreeps[thisCreep.memory.role].push(thisCreep);
    }

    // Get total energy usable in Creep creation
    var totalEnergy = spawn.energy;

    // Find all extensions
    var extensions = spawn.room.find(FIND_MY_STRUCTURES, {
        filter: function (s)
        {
            return s.structureType == STRUCTURE_EXTENSION;
        }
    });

    for (var i in extensions)
    {
        totalEnergy += extensions[i].energy;
    }

    var baseBodies = require ('baseBodies');

    // Max energy a single creep may cost
    var spawningEnergy = totalEnergy;

    var harvesterBody = generateBody (baseBodies['harvester'], spawningEnergy);

    spawnCreepEvery  (spawn, 'harvester', Math.round(LIFETIME / 6), 0, harvesterBody);
    checkCreepSupply (spawn, 'harvester', roleCreeps,               3, harvesterBody);

    var upraderBody = generateBody (baseBodies['upgrader'], spawningEnergy);
    if (upgraderBody.length)
    {
        spawnCreepEvery (spawn, 'upgrader', LIFETIME / 2, 100, upraderBody);
    }

    var builderBody = generateBody (baseBodies['builder'], spawningEnergy);
    if (builderBody.length)
    {
        spawnCreepEvery (spawn, 'builder',  LIFETIME / 2, 200, builderBody);
    }

    // Find all storages in the room
    var storages = spawn.room.find(FIND_MY_STRUCTURES, {
        filter: function (s)
        {
            return s.structureType == STRUCTURE_STORAGE;
        }
    });

    // If there are storages in the room, schedule creation of tankers
    if (storages.length >= 1)
    {
        var tankerBody = generateBody (baseBodies['tanker'], spawningEnergy);
        if (tankerBody.length)
        {
            checkCreepSupply (spawn, 'tanker', roleCreeps,   1,   tankerBody);
            spawnCreepEvery  (spawn, 'tanker', LIFETIME / 2, 400, tankerBody);
        }
    }

    var guardBody = generateBody (baseBodies['guard'], spawningEnergy);
    if (guardBody.length)
    {
        // Make number of guards and number of enemies in the room match
        var targets = spawn.room.find (FIND_HOSTILE_CREEPS);
        var min = targets.length < 1 ? 1 : targets.length;
        checkCreepSupply (spawn, 'guard', roleCreeps, min, guardBody);
    }

    spawnFromQueue (spawn);
}<|endoftext|>


<commit_before>/**
 * Created by maddoxw on 9/25/16.
 *
 * Step 1: Replace "DONTEVERPUTKEYSINSOURCECONTROL" with a valid bing key.
 * Step 2: Rename this file to bingkey.js
 * Step 3: Verify app/main/bingkey.js is in the .gitignore at the root of this project.
 *
 */

define([], function () {
  const bingKey = 'DONTEVERPUTKEYSINSOURCECONTROL'
  return bingKey
})
<commit_msg>commonjs sugar<commit_after>/**
 * Created by maddoxw on 9/25/16.
 *
 * Step 1: Replace "DONTEVERPUTKEYSINSOURCECONTROL" with a valid bing key.
 * Step 2: Rename this file to bingkey.js
 * Step 3: Verify app/main/bingkey.js is in the .gitignore at the root of this project.
 *
 */

const bingKey = 'DONTEVERPUTKEYSINSOURCECONTROL'
module.exports = bingKey
<|endoftext|>


<commit_before>regionConstructors['polygon'] = function(map, name, region)
{
	if(!region.min || !region.max)
		return;
	if(region.max.y > 64)
		region.max.y = 64;
	if(regionCfg.use3dregions)
	{
		regionPolygons[name+'_bottom'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
			paths: [
			map.getProjection().fromWorldToLatLng(region.min.x,region.min.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.min.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.min.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.min.y,region.max.z)
			],
			map: map
			}));
		regionPolygons[name+'_top'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
			paths: [
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.max.z)
			],
			map: map
			}));
		regionPolygons[name+'_east'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
			paths: [
			map.getProjection().fromWorldToLatLng(region.min.x,region.min.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.min.y,region.min.z)
			],
			map: map
			}));
		regionPolygons[name+'_south'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
			paths: [
			map.getProjection().fromWorldToLatLng(region.max.x,region.min.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.min.y,region.max.z)
			],
			map: map
			}));
		regionPolygons[name+'_west'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
			paths: [
			map.getProjection().fromWorldToLatLng(region.min.x,region.min.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.min.y,region.max.z)
			],
			map: map
			}));
		regionPolygons[name+'_north'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
			paths: [
			map.getProjection().fromWorldToLatLng(region.min.x,region.min.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.min.y,region.max.z)
			],
			map: map
			}));
		google.maps.event.addListener(regionPolygons[name+'_bottom'] , 'click', function(event) {
			regionInfo(event, name, region);
		});
		google.maps.event.addListener(regionPolygons[name+'_top'] , 'click', function(event) {
			regionInfo(event, name, region);
		});
		google.maps.event.addListener(regionPolygons[name+'_east'] , 'click', function(event) {
			regionInfo(event, name, region);
		});
		google.maps.event.addListener(regionPolygons[name+'_south'] , 'click', function(event) {
			regionInfo(event, name, region);
		});
		google.maps.event.addListener(regionPolygons[name+'_west'] , 'click', function(event) {
			regionInfo(event, name, region);
		});
		google.maps.event.addListener(regionPolygons[name+'_north'] , 'click', function(event) {
			regionInfo(event, name, region);
		});
	}
	else
	{
		regionPolygons[name+'_bottom'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
			paths: [
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.max.z)
			],
			map: map
			}));

		google.maps.event.addListener(regionPolygons[name+'_bottom'] , 'click', function(event) {
			regionInfo(event, name, region);
		});
	}
}
regionConstructors['info'] = function(event, name, region)
{
	var owners = {'players':'', 'groups':''};
	$.each(region.owners, function(type, names)
	{
		$.each(names, function(index, name)
		{
			if(type == 'players')
				owners['players'] += name+' ';
			else if(type == 'groups')
				owners['groups'] += name+' ';
		});
	});
	var members = {'players':'', 'groups':''};
	$.each(region.members, function(type, names)
	{
		$.each(names, function(index, name)
		{
			if(type == 'players')
				members['players'] += name+' ';
			else if(type == 'groups')
				members['groups'] += name+' ';
		});
	});
	var flags = '';
	$.each(region.flags, function(name, value)
	{
		flags += name+': '+value+'
';
	});

	name = ''+name+'';
	owners['players'] = ''+owners['players']+'';
	owners['groups'] = ''+owners['groups']+'';
	members['players'] = ''+members['players']+'';
	members['groups'] = ''+members['groups']+'';
	var region_parent = (region.parent) ? ''+region.parent+'' : '';
	flags = ''+flags+'';
	var region_priority = ''+region.priority+'';

	var replace = ['%regionname%','%playerowners%','%groupowners%','%playermembers%','%groupmembers%','%parent%','%flags%','%priority%'];
	var by = [name,owners['players'],owners['groups'],members['players'], members['groups'],region_parent,flags,region_priority];

	var contentString = arrayReplace(replace, by, regionCfg.infowindow)

	regionInfoWindow.setContent(contentString);
	regionInfoWindow.setPosition(event.latLng);

	regionInfoWindow.open(dynmap.map);
}

regionConstructors['update'] = function(map)
{
	if(regionInfoWindow)
		regionInfoWindow.close();
	$.each(regionPolygons, function(index, region)
	{
		region.setMap(null);
	});
	regionPolygons = {};

	regionFile = regionCfg.filename.substr(0, regionCfg.filename.lastIndexOf('.'));
	regionFile += '_'+map+'.json';

	$.getJSON('standalone/'+regionFile, function(data)
	{
		var regionnames = '';
		var count = 0;
		$.each(data, function(name, residence)
		{
			count += 1;
			regionnames += ", "+name;
			makeRegionPolygonCube(dynmap.map, name, residence);
		});
	});
}<commit_msg>Fix WorldGuard regions support to include WG5 polygon support<commit_after>regionConstructors['polygon'] = function(map, name, region)
{
    if(region.points) {
    	var i;
		if(regionCfg.use3dregions) {
			var toppts = [];
			var botpts = [];
    		for(i = 0; i < region.points.length; i++) {
    			toppts.push(map.getProjection().fromWorldToLatLng(region.points[i].x,
    				region['max-y'], region.points[i].z));
    			botpts.push(map.getProjection().fromWorldToLatLng(region.points[i].x,
    				region['min-y'], region.points[i].z));
    		}
    		for(i = 0; i < region.points.length; i++) {
				regionPolygons[name+'_side'+i] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
					paths: [
						toppts[i], botpts[i], botpts[(i+1)%region.points.length], toppts[(i+1)%region.points.length]
					], map: map }));
				google.maps.event.addListener(regionPolygons[name+'_side'+i] , 'click', function(event) {
					regionInfo(event, name, region);
				});
			}
			regionPolygons[name+'_bottom'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
				paths: botpts, map: map }));
			google.maps.event.addListener(regionPolygons[name+'_bottom'] , 'click', function(event) {
				regionInfo(event, name, region);
			});
			regionPolygons[name+'_top'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
				paths: toppts, map: map }));
			google.maps.event.addListener(regionPolygons[name+'_top'] , 'click', function(event) {
				regionInfo(event, name, region);
			});
    	}
    	else {
 	   		var pts = [];
    		var yy = (region['min-y']+region['max-y'])/2;
    		for(i = 0; i < region.points.length; i++) {
    			pts.push(map.getProjection().fromWorldToLatLng(region.points[i].x,
    				yy, region.points[i].z));
    		}
			regionPolygons[name+'_bottom'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
				paths: pts, map: map }));
			google.maps.event.addListener(regionPolygons[name+'_bottom'] , 'click', function(event) {
				regionInfo(event, name, region);
			});
		}
		return;
    }
	if(!region.min || !region.max)
		return;
    if(region.max.y <= region.min.y)
        region.min.y = region.max.y - 1;
	if(regionCfg.use3dregions)
	{
		regionPolygons[name+'_bottom'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
			paths: [
			map.getProjection().fromWorldToLatLng(region.min.x,region.min.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.min.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.min.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.min.y,region.max.z)
			],
			map: map
			}));
		regionPolygons[name+'_top'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
			paths: [
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.max.z)
			],
			map: map
			}));
		regionPolygons[name+'_east'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
			paths: [
			map.getProjection().fromWorldToLatLng(region.min.x,region.min.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.min.y,region.min.z)
			],
			map: map
			}));
		regionPolygons[name+'_south'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
			paths: [
			map.getProjection().fromWorldToLatLng(region.max.x,region.min.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.min.y,region.max.z)
			],
			map: map
			}));
		regionPolygons[name+'_west'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
			paths: [
			map.getProjection().fromWorldToLatLng(region.min.x,region.min.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.min.y,region.max.z)
			],
			map: map
			}));
		regionPolygons[name+'_north'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
			paths: [
			map.getProjection().fromWorldToLatLng(region.min.x,region.min.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.min.y,region.max.z)
			],
			map: map
			}));
		google.maps.event.addListener(regionPolygons[name+'_bottom'] , 'click', function(event) {
			regionInfo(event, name, region);
		});
		google.maps.event.addListener(regionPolygons[name+'_top'] , 'click', function(event) {
			regionInfo(event, name, region);
		});
		google.maps.event.addListener(regionPolygons[name+'_east'] , 'click', function(event) {
			regionInfo(event, name, region);
		});
		google.maps.event.addListener(regionPolygons[name+'_south'] , 'click', function(event) {
			regionInfo(event, name, region);
		});
		google.maps.event.addListener(regionPolygons[name+'_west'] , 'click', function(event) {
			regionInfo(event, name, region);
		});
		google.maps.event.addListener(regionPolygons[name+'_north'] , 'click', function(event) {
			regionInfo(event, name, region);
		});
	}
	else
	{
		regionPolygons[name+'_bottom'] = new google.maps.Polygon($.extend(regionCfg.regionstyle, {
			paths: [
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.min.z),
			map.getProjection().fromWorldToLatLng(region.max.x,region.max.y,region.max.z),
			map.getProjection().fromWorldToLatLng(region.min.x,region.max.y,region.max.z)
			],
			map: map
			}));

		google.maps.event.addListener(regionPolygons[name+'_bottom'] , 'click', function(event) {
			regionInfo(event, name, region);
		});
	}
}
regionConstructors['info'] = function(event, name, region)
{
	var owners = {'players':'', 'groups':''};
	$.each(region.owners, function(type, names)
	{
		$.each(names, function(index, name)
		{
			if(type == 'players')
				owners['players'] += name+' ';
			else if(type == 'groups')
				owners['groups'] += name+' ';
		});
	});
	var members = {'players':'', 'groups':''};
	$.each(region.members, function(type, names)
	{
		$.each(names, function(index, name)
		{
			if(type == 'players')
				members['players'] += name+' ';
			else if(type == 'groups')
				members['groups'] += name+' ';
		});
	});
	var flags = '';
	$.each(region.flags, function(name, value)
	{
		flags += name+': '+value+'
';
	});

	name = ''+name+'';
	owners['players'] = ''+owners['players']+'';
	owners['groups'] = ''+owners['groups']+'';
	members['players'] = ''+members['players']+'';
	members['groups'] = ''+members['groups']+'';
	var region_parent = (region.parent) ? ''+region.parent+'' : '';
	flags = ''+flags+'';
	var region_priority = ''+region.priority+'';

	var replace = ['%regionname%','%playerowners%','%groupowners%','%playermembers%','%groupmembers%','%parent%','%flags%','%priority%'];
	var by = [name,owners['players'],owners['groups'],members['players'], members['groups'],region_parent,flags,region_priority];

	var contentString = arrayReplace(replace, by, regionCfg.infowindow)

	regionInfoWindow.setContent(contentString);
	regionInfoWindow.setPosition(event.latLng);

	regionInfoWindow.open(dynmap.map);
}

regionConstructors['update'] = function(map)
{
	if(regionInfoWindow)
		regionInfoWindow.close();
	$.each(regionPolygons, function(index, region)
	{
		region.setMap(null);
	});
	regionPolygons = {};

	regionFile = regionCfg.filename.substr(0, regionCfg.filename.lastIndexOf('.'));
	regionFile += '_'+map+'.json';

	$.getJSON('standalone/'+regionFile, function(data)
	{
		var regionnames = '';
		var count = 0;
		$.each(data, function(name, residence)
		{
			count += 1;
			regionnames += ", "+name;
			makeRegionPolygonCube(dynmap.map, name, residence);
		});
	});
}<|endoftext|>


<commit_before>import React from 'react'
import {
  ScrollView,
  TouchableOpacity,
  View,
  Image,
  Text,
  Linking,
  Animated,
  PanResponder,
  LayoutAnimation
} from 'react-native'
import PurpleGradient from '../Components/PurpleGradient'

import VenueMap from '../Components/VenueMap'
import Gallery from '../Components/Gallery'
import { Images, Metrics } from '../Themes'
import { connect } from 'react-redux'
import Secrets from 'react-native-config'
import styles from './Styles/LocationScreenStyle'

const VENUE_LATITUDE = 45.524166
const VENUE_LONGITUDE = -122.681645
const { UBER_CLIENT_ID } = Secrets
const MAP_TAP_THRESHOLD = 100

class LocationScreen extends React.Component {
  constructor (props) {
    super(props)

    this.state = {
      showRideOptions: false,
      scrollY: new Animated.Value(0),
      mapTouchStart: '',
      mapViewMode: false
    }
  }

  static navigationOptions = {
    tabBarLabel: 'Location',
    tabBarIcon: ({ focused }) => (
      <Image source={focused ? Images.activeLocationIcon : Images.inactiveLocationIcon} />
    )
  }

  componentWillMount () {
    // Get the map tap check
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderGrant: (e) => this.setState({mapTouchStart: e.nativeEvent.timestamp}),
      onPanResponderRelease: this.cehckMapTap
    })
  }
  cehckMapTap = (e) => {
    if (e.nativeEvent.timestamp - this.state.mapTouchStart < MAP_TAP_THRESHOLD) {
      LayoutAnimation.configureNext({...LayoutAnimation.Presets.linear, duration: 500})
      this.refs.scrolly.scrollTo({y: Metrics.screenHeight / 4.25, animated: true})
      this.setState({mapViewMode: true})
    }
    this.setState({mapTouchStart: ''})
  }

  openMaps (daddr = '128+NW+Eleventh+Ave+Portland,+OR+97209') {
    const googleMaps = `comgooglemaps://?daddr=${daddr}`
    const appleMaps = `http://maps.apple.com?daddr=${daddr}`

    Linking.canOpenURL(googleMaps).then((supported) => {
      if (supported) {
        Linking.openURL(googleMaps)
      } else {
        Linking.canOpenURL(appleMaps).then((supported) =>
          supported
          ? Linking.openURL(appleMaps)
          : window.alert('Unable to find maps application.')
        )
      }
    })
  }

  openLyft () {
    const lat = `destination[latitude]=${VENUE_LATITUDE}`
    const lng = `destination[longitude]=${VENUE_LONGITUDE}`
    const lyft = `lyft://ridetype?${lat}&${lng}`

    Linking.canOpenURL(lyft).then((supported) => {
      if (supported) {
        Linking.openURL(lyft)
      } else {
        window.alert('Unable to open Lyft.')
      }
    })
  }

  openUber () {
    const pickup = 'action=setPickup&pickup=my_location'
    const client = `client_id=${UBER_CLIENT_ID}`
    const lat = `dropoff[latitude]=${VENUE_LATITUDE}`
    const lng = `dropoff[longitude]=${VENUE_LONGITUDE}`
    const nick = `dropoff[nickname]=The%20Armory`
    const daddr = `dropoff[formatted_address]=128%20NW%20Eleventh%20Ave%2C%20Portland%2C%20OR%2097209`
    const uber = `uber://?${pickup}&${client}&${lat}&${lng}&${nick}&${daddr}`

    Linking.canOpenURL(uber).then((supported) => {
      if (supported) {
        Linking.openURL(uber)
      } else {
        window.alert('Unable to open Uber.')
      }
    })
  }

  toggleRides = () => {
    const { showRideOptions, scrollY } = this.state
    if (!showRideOptions && scrollY._value < 200) {
      this.refs.scrolly.scrollTo({x: 0, y: 200, animated: true})
    }
    this.setState({showRideOptions: !this.state.showRideOptions})
  }

  renderBackground = () => {
    const height = Metrics.locationBackgroundHeight
    const { scrollY } = this.state
    return (
      <Animated.Image
        style={[styles.venue, {position: 'absolute'}, {
          width: '100%',
          height: height,
          transform: [{
            translateY: scrollY.interpolate({
              inputRange: [-height, 0, height],
              outputRange: [height, 0, 0]
            })
          }, {
            scale: scrollY.interpolate({
              inputRange: [-height, 0, height],
              outputRange: [0.9, 1, 1.5]
            })
          }]
        }]}
        source={Images.theArmory}
        resizeMode='cover'
      />
    )
  }

  renderHeader = () => {
    const height = Metrics.locationBackgroundHeight - 24
    const { scrollY } = this.state
    return (
      <Animated.View style={{
        position: 'relative',
        height: height,
        padding: 0,
        opacity: scrollY.interpolate({
          inputRange: [-height, 0, height * 0.4, height * 0.9],
          outputRange: [1, 1, 1, 0]
        }),
        transform: [{
          translateY: scrollY.interpolate({
            inputRange: [-height, 0, height * 0.45, height],
            outputRange: [0, 0, height * 0.45, height * 0.4]
          })
        }]
      }}>
        <View style={styles.headingContainer}>
          <Text style={styles.mainHeading}>The Armory</Text>
          <Text style={styles.address}>
            128 NW Eleventh Ave{'\n'}
            Portland, OR 97209
          </Text>
        </View>
      </Animated.View>
    )
  }

  onCloseMap = () => {
    LayoutAnimation.configureNext({...LayoutAnimation.Presets.linear, duration: 400})
    this.setState({mapViewMode: false})
  }

  render () {
    const { showRideOptions, mapViewMode } = this.state
    const { nearbyData } = this.props
    const { event } = Animated

    return (
      <PurpleGradient style={[styles.linearGradient, {flex: 1}]}>
        <ScrollView
          ref='scrolly'
          onScroll={event([{nativeEvent: {contentOffset: {y: this.state.scrollY}}}])}
          scrollEventThrottle={10}
          scrollEnabled={!this.state.mapViewMode}>
          <View style={styles.container}>
            {this.renderBackground()}
            {this.renderHeader()}
            <View ref='mapContainer' {...this._panResponder.panHandlers}>
              <VenueMap mapViewMode={mapViewMode} onCloseMap={this.onCloseMap} scrollEnabled={mapViewMode} style={[styles.map, mapViewMode && {height: Metrics.screenHeight / 2}]} />
            </View>
            <View style={styles.mapActions}>
              <TouchableOpacity onPress={() => this.openMaps()}>
                <View style={styles.getDirections}>
                  <View style={styles.addressContainer}>
                    <Text style={styles.venueName}>
                      The Armory
                    </Text>
                    <Text style={styles.venueAddress}>
                      128 NW Eleventh Ave.{'\n'}Portland, OR 97209
                    </Text>
                  </View>
                  <View style={styles.directionsIcon}>
                    <Image source={Images.directionsIcon} />
                    <Text style={styles.directionsLabel}>Directions</Text>
                  </View>
                </View>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => this.toggleRides()}>
                <View style={styles.getRide}>
                  <Text style={styles.getRideLabel}>
                    Taking an Uber or Lyft?
                  </Text>
                  <Image
                    style={[styles.getRideIcon, showRideOptions && styles.flip]}
                    source={Images.chevronIcon}
                  />
                </View>
              </TouchableOpacity>
            </View>
            <View style={[styles.rideOptions, showRideOptions && {height: 170}]}>
              <TouchableOpacity onPress={() => this.openLyft()}>
                <Image style={styles.rideButton} source={Images.lyftButton} />
              </TouchableOpacity>
              <TouchableOpacity onPress={() => this.openUber()}>
                <Image style={styles.rideButton} source={Images.uberButton} />
              </TouchableOpacity>
            </View>
            <View style={styles.nearby}>
              <Text style={styles.mainHeading}>
                Nearby
              </Text>
            </View>
            <Gallery
              data={nearbyData}
              onItemPress={(daddr) => this.openMaps(daddr)}
            />
          </View>
        </ScrollView>
      </PurpleGradient>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    nearbyData: state.location.nearby
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(LocationScreen)
<commit_msg>map grows to fit screen<commit_after>import React from 'react'
import {
  ScrollView,
  TouchableOpacity,
  View,
  Image,
  Text,
  Linking,
  Animated,
  PanResponder,
  LayoutAnimation
} from 'react-native'
import PurpleGradient from '../Components/PurpleGradient'

import VenueMap from '../Components/VenueMap'
import Gallery from '../Components/Gallery'
import { Images, Metrics } from '../Themes'
import { connect } from 'react-redux'
import Secrets from 'react-native-config'
import styles from './Styles/LocationScreenStyle'

const VENUE_LATITUDE = 45.524166
const VENUE_LONGITUDE = -122.681645
const { UBER_CLIENT_ID } = Secrets
const MAP_TAP_THRESHOLD = 100

class LocationScreen extends React.Component {
  constructor (props) {
    super(props)

    this.state = {
      showRideOptions: false,
      scrollY: new Animated.Value(0),
      mapTouchStart: '',
      mapViewMode: false
    }

    this.scrollSpot = Metrics.screenHeight / 4.25
    this.activeMapHeight = Metrics.screenHeight - this.scrollSpot
  }

  static navigationOptions = {
    tabBarLabel: 'Location',
    tabBarIcon: ({ focused }) => (
      <Image source={focused ? Images.activeLocationIcon : Images.inactiveLocationIcon} />
    )
  }

  componentWillMount () {
    // Get the map tap check
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderGrant: (e) => this.setState({mapTouchStart: e.nativeEvent.timestamp}),
      onPanResponderRelease: this.checkMapTap
    })
  }
  checkMapTap = (e) => {
    if (e.nativeEvent.timestamp - this.state.mapTouchStart < MAP_TAP_THRESHOLD) {
      LayoutAnimation.configureNext({...LayoutAnimation.Presets.linear, duration: 500})
      this.refs.scrolly.scrollTo({y: this.scrollSpot, animated: true})
      this.setState({mapViewMode: true})
    }
    this.setState({mapTouchStart: ''})
  }

  openMaps (daddr = '128+NW+Eleventh+Ave+Portland,+OR+97209') {
    const googleMaps = `comgooglemaps://?daddr=${daddr}`
    const appleMaps = `http://maps.apple.com?daddr=${daddr}`

    Linking.canOpenURL(googleMaps).then((supported) => {
      if (supported) {
        Linking.openURL(googleMaps)
      } else {
        Linking.canOpenURL(appleMaps).then((supported) =>
          supported
          ? Linking.openURL(appleMaps)
          : window.alert('Unable to find maps application.')
        )
      }
    })
  }

  openLyft () {
    const lat = `destination[latitude]=${VENUE_LATITUDE}`
    const lng = `destination[longitude]=${VENUE_LONGITUDE}`
    const lyft = `lyft://ridetype?${lat}&${lng}`

    Linking.canOpenURL(lyft).then((supported) => {
      if (supported) {
        Linking.openURL(lyft)
      } else {
        window.alert('Unable to open Lyft.')
      }
    })
  }

  openUber () {
    const pickup = 'action=setPickup&pickup=my_location'
    const client = `client_id=${UBER_CLIENT_ID}`
    const lat = `dropoff[latitude]=${VENUE_LATITUDE}`
    const lng = `dropoff[longitude]=${VENUE_LONGITUDE}`
    const nick = `dropoff[nickname]=The%20Armory`
    const daddr = `dropoff[formatted_address]=128%20NW%20Eleventh%20Ave%2C%20Portland%2C%20OR%2097209`
    const uber = `uber://?${pickup}&${client}&${lat}&${lng}&${nick}&${daddr}`

    Linking.canOpenURL(uber).then((supported) => {
      if (supported) {
        Linking.openURL(uber)
      } else {
        window.alert('Unable to open Uber.')
      }
    })
  }

  toggleRides = () => {
    const { showRideOptions, scrollY } = this.state
    if (!showRideOptions && scrollY._value < 200) {
      this.refs.scrolly.scrollTo({x: 0, y: 200, animated: true})
    }
    this.setState({showRideOptions: !this.state.showRideOptions})
  }

  renderBackground = () => {
    const height = Metrics.locationBackgroundHeight
    const { scrollY } = this.state
    return (
      <Animated.Image
        style={[styles.venue, {position: 'absolute'}, {
          width: '100%',
          height: height,
          transform: [{
            translateY: scrollY.interpolate({
              inputRange: [-height, 0, height],
              outputRange: [height, 0, 0]
            })
          }, {
            scale: scrollY.interpolate({
              inputRange: [-height, 0, height],
              outputRange: [0.9, 1, 1.5]
            })
          }]
        }]}
        source={Images.theArmory}
        resizeMode='cover'
      />
    )
  }

  renderHeader = () => {
    const height = Metrics.locationBackgroundHeight - 24
    const { scrollY } = this.state
    return (
      <Animated.View style={{
        position: 'relative',
        height: height,
        padding: 0,
        opacity: scrollY.interpolate({
          inputRange: [-height, 0, height * 0.4, height * 0.9],
          outputRange: [1, 1, 1, 0]
        }),
        transform: [{
          translateY: scrollY.interpolate({
            inputRange: [-height, 0, height * 0.45, height],
            outputRange: [0, 0, height * 0.45, height * 0.4]
          })
        }]
      }}>
        <View style={styles.headingContainer}>
          <Text style={styles.mainHeading}>The Armory</Text>
          <Text style={styles.address}>
            128 NW Eleventh Ave{'\n'}
            Portland, OR 97209
          </Text>
        </View>
      </Animated.View>
    )
  }

  onCloseMap = () => {
    LayoutAnimation.configureNext({...LayoutAnimation.Presets.linear, duration: 400})
    this.setState({mapViewMode: false})
  }

  render () {
    const { showRideOptions, mapViewMode } = this.state
    const { nearbyData } = this.props
    const { event } = Animated

    return (
      <PurpleGradient style={[styles.linearGradient, {flex: 1}]}>
        <ScrollView
          ref='scrolly'
          onScroll={event([{nativeEvent: {contentOffset: {y: this.state.scrollY}}}])}
          scrollEventThrottle={10}
          scrollEnabled={!this.state.mapViewMode}>
          <View style={styles.container}>
            {this.renderBackground()}
            {this.renderHeader()}
            <View ref='mapContainer' {...this._panResponder.panHandlers}>
              <VenueMap mapViewMode={mapViewMode} onCloseMap={this.onCloseMap} scrollEnabled={mapViewMode} style={[styles.map, mapViewMode && {height: this.activeMapHeight}]} />
            </View>
            <View style={styles.mapActions}>
              <TouchableOpacity onPress={() => this.openMaps()}>
                <View style={styles.getDirections}>
                  <View style={styles.addressContainer}>
                    <Text style={styles.venueName}>
                      The Armory
                    </Text>
                    <Text style={styles.venueAddress}>
                      128 NW Eleventh Ave.{'\n'}Portland, OR 97209
                    </Text>
                  </View>
                  <View style={styles.directionsIcon}>
                    <Image source={Images.directionsIcon} />
                    <Text style={styles.directionsLabel}>Directions</Text>
                  </View>
                </View>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => this.toggleRides()}>
                <View style={styles.getRide}>
                  <Text style={styles.getRideLabel}>
                    Taking an Uber or Lyft?
                  </Text>
                  <Image
                    style={[styles.getRideIcon, showRideOptions && styles.flip]}
                    source={Images.chevronIcon}
                  />
                </View>
              </TouchableOpacity>
            </View>
            <View style={[styles.rideOptions, showRideOptions && {height: 170}]}>
              <TouchableOpacity onPress={() => this.openLyft()}>
                <Image style={styles.rideButton} source={Images.lyftButton} />
              </TouchableOpacity>
              <TouchableOpacity onPress={() => this.openUber()}>
                <Image style={styles.rideButton} source={Images.uberButton} />
              </TouchableOpacity>
            </View>
            <View style={styles.nearby}>
              <Text style={styles.mainHeading}>
                Nearby
              </Text>
            </View>
            <Gallery
              data={nearbyData}
              onItemPress={(daddr) => this.openMaps(daddr)}
            />
          </View>
        </ScrollView>
      </PurpleGradient>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    nearbyData: state.location.nearby
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(LocationScreen)
<|endoftext|>