<commit_before>    var customIcons = {
        building: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/building_icon.png'
        },
        student_centre: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/student_centre_icon.png'
        },
        lecture_theatre: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/lecture_theatre_icon.png'
        },
        computer_lab: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/computer_lab_icon.png'
        },
        library: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/library_icon.png'
        },
        cycle_hire: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/cycle_hire_icon.png'
        },
        cycle_parking: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/cycle_parking_icon.png'
        },
        atm: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/atm_icon.png'
        }
    };

    var markerGroups = {
        "building": [],
        "student_centre": [],
        "lecture_theatre": [],
        "computer_lab": [],
        "library": [],
        "cycle_hire": [],
        "cycle_parking": [],
        "atm": []
    };

    function loadMap() {
    var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(51.527287, -0.103842),
        zoom: 15,
        mapTypeId: 'roadmap'
    });

    downloadUrl("../../includes/university-map/source/overview_source.php", function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
        var name = markers[i].getAttribute("name");
        var notes = markers[i].getAttribute("notes");
        var category = markers[i].getAttribute("category");
        var point = new google.maps.LatLng(
            parseFloat(markers[i].getAttribute("lat")),
            parseFloat(markers[i].getAttribute("lng")));
        var marker = createMarker(point, name, notes, category, map);
    }
    });
    }

    var infoWindow = new google.maps.InfoWindow({
        maxWidth: 400
    });

    function createMarker(point, name, notes, category, map) {
        var icon = customIcons[category] || {};
        var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon,
            type: category
        });
        if (!markerGroups[category]) markerGroups[category] = [];
        markerGroups[category].push(marker);
        var html = "" + name + "
" + notes;
        bindInfoWindow(marker, map, infoWindow, html);
        return marker;
    }

    function toggleGroup(category) {
        for (var i = 0; i < markerGroups[category].length; i++) {
            var marker = markerGroups[category][i];
            if (!marker.getVisible()) {
                marker.setVisible(true);
            } else {
                marker.setVisible(false);
            }
        }
    }

    function clearMarkers() {
        marker.setVisible(false);
    }

    function bindInfoWindow(marker, map, infoWindow, html) {
        google.maps.event.addListener(marker, 'click', function() {
            infoWindow.setContent(html);
            infoWindow.open(map, marker);

        });
    }

    function downloadUrl(url, callback) {
        var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();

        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                request.onreadystatechange = doNothing;
                callback(request, request.status);
            }
        };

        request.open('GET', url, true);
        request.send(null);
    }

    function doNothing() {}
<commit_msg>Changed structure<commit_after>    var customIcons = {
        building: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/building_icon.png'
        },
        student_centre: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/student_centre_icon.png'
        },
        lecture_theatre: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/lecture_theatre_icon.png'
        },
        computer_lab: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/computer_lab_icon.png'
        },
        library: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/library_icon.png'
        },
        cycle_hire: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/cycle_hire_icon.png'
        },
        cycle_parking: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/cycle_parking_icon.png'
        },
        atm: {
            icon: 'https://student-portal.co.uk/assets/img/university-map/atm_icon.png'
        }
    };

    var markerGroups = {
        "building": [],
        "student_centre": [],
        "lecture_theatre": [],
        "computer_lab": [],
        "library": [],
        "cycle_hire": [],
        "cycle_parking": [],
        "atm": []
    };

    function loadMap() {
    var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(51.527287, -0.103842),
        zoom: 15,
        mapTypeId: 'roadmap'
    });

    downloadUrl("../../includes/university-map/source/overview_source.php", function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
        var name = markers[i].getAttribute("name");
        var notes = markers[i].getAttribute("notes");
        var category = markers[i].getAttribute("category");
        var point = new google.maps.LatLng(
            parseFloat(markers[i].getAttribute("lat")),
            parseFloat(markers[i].getAttribute("lng")));
        var marker = createMarker(point, name, notes, category, map);
    }
    });
    }

    var infoWindow = new google.maps.InfoWindow({
        maxWidth: 400
    });

    function createMarker(point, name, notes, category, map) {
        var icon = customIcons[category] || {};
        var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon,
            type: category
        });
        if (!markerGroups[category]) markerGroups[category] = [];
        markerGroups[category].push(marker);
        var html = "" + name + "
" + notes;
        bindInfoWindow(marker, map, infoWindow, html);
        return marker;
    }

    function toggleGroup(category) {
        for (var i = 0; i < markerGroups[category].length; i++) {
            var marker = markerGroups[category][i];
            if (!marker.getVisible()) {
                marker.setVisible(true);
            } else {
                marker.setVisible(false);
            }
        }
    }

    function bindInfoWindow(marker, map, infoWindow, html) {
        google.maps.event.addListener(marker, 'click', function() {
            infoWindow.setContent(html);
            infoWindow.open(map, marker);

        });
    }

    function downloadUrl(url, callback) {
        var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();

        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                request.onreadystatechange = doNothing;
                callback(request, request.status);
            }
        };

        request.open('GET', url, true);
        request.send(null);
    }

    function doNothing() {}
<|endoftext|>


<commit_before>import { msg } from '../app/messages'
import { URL_NO_USER, RESERVED_URLS, URL_RESERVED_PREFIX } from '../app/routing'
import {
  createBuildings,
  updateBuildingPosition
} from '../segments/buildings'
import { DEFAULT_SEGMENTS } from '../segments/default'
import { getSegmentInfo } from '../segments/info'
import { normalizeAllSegmentWidths } from '../segments/resizing'
import { getVariantString, getVariantArray } from '../segments/variant_utils'
import {
  segmentsChanged,
  repositionSegments,
  createSegmentDom
} from '../segments/view'
import { getSignInData, isSignedIn } from '../users/authentication'
import { getUnits, getLeftHandTraffic, propagateUnits } from '../users/localization'
import { normalizeSlug } from '../util/helpers'
import { generateRandSeed } from '../util/random'
import { updateStreetName } from './name'
import {
  createNewUndoIfNecessary,
  unifyUndoStack
} from './undo_stack'
import {
  DEFAULT_STREET_WIDTH,
  normalizeStreetWidth,
  resizeStreetWidth
} from './width'
import { updateLastStreetInfo, scheduleSavingStreetToServer } from './xhr'
import {
  setBuildingVariant,
  setBuildingFloorValue,
  addLocation,
  updateSchemaVersion,
  clearSegments,
  saveCreatorId,
  updateEditCount,
  updateStreetWidth,
  saveStreetName,
  setUnits,
  setUpdateTime,
  updateSegments
} from '../store/actions/street'
import { resetUndoStack } from '../store/actions/undo'
import store from '../store'

const DEFAULT_BUILDING_HEIGHT_LEFT = 4
const DEFAULT_BUILDING_HEIGHT_RIGHT = 3
const DEFAULT_BUILDING_VARIANT_LEFT = 'narrow'
const DEFAULT_BUILDING_VARIANT_RIGHT = 'wide'
const DEFAULT_BUILDING_HEIGHT_EMPTY = 1
const DEFAULT_BUILDING_VARIANT_EMPTY = 'grass'

let _lastStreet

export function getLastStreet () {
  return _lastStreet
}

export function setLastStreet (value) {
  _lastStreet = value
}

const LATEST_SCHEMA_VERSION = 18
// 1: starting point
// 2: adding leftBuildingHeight and rightBuildingHeight
// 3: adding leftBuildingVariant and rightBuildingVariant
// 4: adding transit shelter elevation
// 5: adding another lamp type (traditional)
// 6: colored streetcar lanes
// 7: colored bus and light rail lanes
// 8: colored bike lane
// 9: second car type: truck
// 10: sidewalk density
// 11: unify median and planting strip into divider
// 12: getting rid of small tree
// 13: bike rack elevation
// 14: wayfinding has three types
// 15: sidewalks have rand seed
// 16: stop saving undo stack
// 17: alternative colors for bike lanes
// 18: change lat/lng format from array to object

export const DEFAULT_NAME = msg('DEFAULT_STREET_NAME')

function incrementSchemaVersion (street) {
  let segment, variant, schemaVersion

  if (!street.schemaVersion) {
    schemaVersion = 1
  }

  switch (street.schemaVersion) {
    case 1:
      store.dispatch(setBuildingFloorValue('left', DEFAULT_BUILDING_HEIGHT_LEFT))
      store.dispatch(setBuildingFloorValue('right', DEFAULT_BUILDING_HEIGHT_RIGHT))
      break
    case 2:
      store.dispatch(setBuildingVariant('left', DEFAULT_BUILDING_VARIANT_LEFT))
      store.dispatch(setBuildingVariant('right', DEFAULT_BUILDING_VARIANT_RIGHT))
      break
    case 3: // CHECK IF THIS NEEDS TO UPDATE STORE
      for (var i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'transit-shelter') {
          variant = getVariantArray(segment.type, segment.variantString)
          variant['transit-shelter-elevation'] = 'street-level'
          segment.variantString = getVariantString(variant)
        }
      }
      break
    case 4:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'sidewalk-lamp') {
          variant = getVariantArray(segment.type, segment.variantString)
          variant['lamp-type'] = 'modern'
          segment.variantString = getVariantString(variant)
        }
      }
      break
    case 5:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'streetcar') {
          variant = getVariantArray(segment.type, segment.variantString)
          variant['public-transit-asphalt'] = 'regular'
          segment.variantString = getVariantString(variant)
        }
      }
      break
    case 6:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'bus-lane') {
          variant = getVariantArray(segment.type, segment.variantString)
          variant['bus-asphalt'] = 'regular'
          segment.variantString = getVariantString(variant)
        } else if (segment.type === 'light-rail') {
          variant = getVariantArray(segment.type, segment.variantString)
          variant['public-transit-asphalt'] = 'regular'
          segment.variantString = getVariantString(variant)
        }
      }
      break
    case 7:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'bike-lane') {
          variant = getVariantArray(segment.type, segment.variantString)
          variant['bike-asphalt'] = 'regular'
          segment.variantString = getVariantString(variant)
        }
      }
      break
    case 8:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'drive-lane') {
          variant = getVariantArray(segment.type, segment.variantString)
          variant['car-type'] = 'car'
          segment.variantString = getVariantString(variant)
        }
      }
      break
    case 9:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'sidewalk') {
          variant = getVariantArray(segment.type, segment.variantString)
          variant['sidewalk-density'] = 'normal'
          segment.variantString = getVariantString(variant)
        }
      }
      break
    case 10:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'planting-strip') {
          segment.type = 'divider'

          if (segment.variantString === '') {
            segment.variantString = 'planting-strip'
          }
        } else if (segment.type === 'small-median') {
          segment.type = 'divider'
          segment.variantString = 'median'
        }
      }
      break
    case 11:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'divider') {
          if (segment.variantString === 'small-tree') {
            segment.variantString = 'big-tree'
          }
        } else if (segment.type === 'sidewalk-tree') {
          if (segment.variantString === 'small') {
            segment.variantString = 'big'
          }
        }
      }
      break
    case 12:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'sidewalk-bike-rack') {
          variant = getVariantArray(segment.type, segment.variantString)
          variant['bike-rack-elevation'] = 'sidewalk'
          segment.variantString = getVariantString(variant)
        }
      }
      break
    case 13:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'sidewalk-wayfinding') {
          variant = getVariantArray(segment.type, segment.variantString)
          variant['wayfinding-type'] = 'large'
          segment.variantString = getVariantString(variant)
        }
      }
      break
    case 14:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'sidewalk') {
          segment.randSeed = 35
        }
      }
      break
    case 15:
      store.dispatch(resetUndoStack())
      break
    case 16:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'bike-lane') {
          variant = getVariantArray(segment.type, segment.variantString)
          if (variant['bike-asphalt'] === 'colored') {
            variant['bike-asphalt'] = 'green'
          }
          segment.variantString = getVariantString(variant)
        }
      }
      break
    case 17:
      if (street.location && street.location.latlng) {
        const location = {
          ...street.location,
          latlng: {
            lat: street.location.latlng[0],
            lng: street.location.latlng[1]
          }
        }
        store.dispatch(addLocation(location))
      }
  }

  schemaVersion++
  store.dispatch(updateSchemaVersion(schemaVersion))
}

export function updateToLatestSchemaVersion (street) {
  var updated = false
  while (!street.schemaVersion || (street.schemaVersion < LATEST_SCHEMA_VERSION)) {
    incrementSchemaVersion(street)
    updated = true
  }

  return updated
}

export function createDomFromData () {
  document.querySelector('#street-section-editable').innerHTML = ''
  const street = store.getState().street

  for (var i in street.segments) {
    var segment = street.segments[i]

    // Add some additional data structures
    // TODO: populate data structure elsewhere
    segment.variant = getVariantArray(segment.type, segment.variantString)
    segment.warnings = []

    var el = createSegmentDom(segment)
    document.querySelector('#street-section-editable').appendChild(el)

    segment.el = el
    segment.el.dataNo = i
  }

  repositionSegments()
  updateBuildingPosition()
  createBuildings()
}

export function setStreetCreatorId (newId) {
  store.dispatch(saveCreatorId(newId))

  unifyUndoStack()
  updateLastStreetInfo()
}

export function setUpdateTimeToNow () {
  store.dispatch(setUpdateTime(new Date().getTime()))
  unifyUndoStack()
}

let ignoreStreetChanges = false

export function setIgnoreStreetChanges (value) {
  ignoreStreetChanges = value
}

export function saveStreetToServerIfNecessary () {
  if (ignoreStreetChanges || store.getState().errors.abortEverything) {
    return
  }

  const street = store.getState().street
  var currentData = trimStreetData(street)

  if (JSON.stringify(currentData) !== JSON.stringify(_lastStreet)) {
    if (street.editCount !== null) {
      street.editCount++
    }
    setUpdateTimeToNow()

    // Some parts of the UI need to know this happened to respond to it
    // TODO: figure out appropriate event name
    window.dispatchEvent(new window.CustomEvent('stmx:save_street'))

    createNewUndoIfNecessary(_lastStreet, currentData)

    scheduleSavingStreetToServer()

    _lastStreet = currentData
  }
}

// Copies only the data necessary for save/undo.
export function trimStreetData (street) {
  var newData = {}

  newData.schemaVersion = street.schemaVersion

  newData.width = street.width
  newData.name = street.name

  newData.id = street.id
  newData.namespacedId = street.namespacedId
  newData.creatorId = street.creatorId
  newData.originalStreetId = street.originalStreetId
  newData.units = street.units

  newData.location = street.location
  newData.userUpdated = street.userUpdated

  if (street.editCount !== null) {
    // console.log('saving editCount', street.editCount)
    newData.editCount = street.editCount
  } else {
    // console.log('not saving editCount')
  }

  newData.leftBuildingHeight = street.leftBuildingHeight
  newData.rightBuildingHeight = street.rightBuildingHeight
  newData.leftBuildingVariant = street.leftBuildingVariant
  newData.rightBuildingVariant = street.rightBuildingVariant

  newData.segments = []

  for (var i in street.segments) {
    var segment = {}
    segment.type = street.segments[i].type
    segment.variantString = street.segments[i].variantString
    segment.width = street.segments[i].width
    if (street.segments[i].randSeed) {
      segment.randSeed = street.segments[i].randSeed
    }

    newData.segments.push(segment)
  }

  return newData
}

// TODO this function should not exist; all the data should be in street.
// object to begin with
export function createDataFromDom () {
  var els = document.querySelectorAll('#street-section-editable > .segment')
  const segments = []

  for (var i = 0, el; el = els[i]; i++) { // eslint-disable-line no-cond-assign
    var segment = {}
    segment.type = el.getAttribute('type')
    if (el.getAttribute('rand-seed')) {
      segment.randSeed = parseInt(el.getAttribute('rand-seed'))
    }
    segment.variantString = el.getAttribute('variant-string')
    segment.variant = getVariantArray(segment.type, segment.variantString)
    segment.width = parseFloat(el.getAttribute('data-width'))
    segment.el = el
    segment.warnings = []
    segments.push(segment)
  }
  store.dispatch(updateSegments(segments))
}

function fillDefaultSegments () {
  const segments = []
  let leftHandTraffic = getLeftHandTraffic()

  for (var i in DEFAULT_SEGMENTS[leftHandTraffic]) {
    var segment = DEFAULT_SEGMENTS[leftHandTraffic][i]
    segment.warnings = []
    segment.variantString = getVariantString(segment.variant)

    if (getSegmentInfo(segment.type).needRandSeed) {
      segment.randSeed = generateRandSeed()
    }

    segments.push(segment)
  }
  store.dispatch(updateSegments(segments))
  normalizeAllSegmentWidths()
}

export function getStreetUrl (street) {
  var url = '/'
  if (street.creatorId) {
    if (RESERVED_URLS.indexOf(street.creatorId) !== -1) {
      url += URL_RESERVED_PREFIX
    }

    url += street.creatorId
  } else {
    url += URL_NO_USER
  }

  url += '/'

  url += street.namespacedId

  if (street.creatorId) {
    var slug = normalizeSlug(street.name)
    url += '/' + encodeURIComponent(slug)
  }

  return url
}

export function prepareDefaultStreet () {
  store.dispatch(setUnits(getUnits()))
  propagateUnits()

  store.dispatch(saveStreetName(DEFAULT_NAME, false))
  store.dispatch(updateStreetWidth(normalizeStreetWidth(DEFAULT_STREET_WIDTH)))
  store.dispatch(setBuildingFloorValue('left', DEFAULT_BUILDING_HEIGHT_LEFT))
  store.dispatch(setBuildingFloorValue('right', DEFAULT_BUILDING_HEIGHT_RIGHT))
  store.dispatch(setBuildingVariant('left', DEFAULT_BUILDING_VARIANT_LEFT))
  store.dispatch(setBuildingVariant('right', DEFAULT_BUILDING_VARIANT_RIGHT))
  store.dispatch(updateEditCount(0))

  // console.log('editCount = 0 on default street')
  if (isSignedIn()) {
    setStreetCreatorId(getSignInData().userId)
  }
  fillDefaultSegments()
  setUpdateTimeToNow()
}

export function prepareEmptyStreet () {
  store.dispatch(setUnits(getUnits()))
  propagateUnits()

  store.dispatch(saveStreetName(DEFAULT_NAME, false))
  store.dispatch(updateStreetWidth(normalizeStreetWidth(DEFAULT_STREET_WIDTH)))
  store.dispatch(setBuildingFloorValue('left', DEFAULT_BUILDING_HEIGHT_EMPTY))
  store.dispatch(setBuildingFloorValue('right', DEFAULT_BUILDING_HEIGHT_EMPTY))
  store.dispatch(setBuildingVariant('left', DEFAULT_BUILDING_VARIANT_EMPTY))
  store.dispatch(setBuildingVariant('right', DEFAULT_BUILDING_VARIANT_EMPTY))
  store.dispatch(updateEditCount(0))
  store.dispatch(clearSegments())

  // console.log('editCount = 0 on empty street!')
  if (isSignedIn()) {
    setStreetCreatorId(getSignInData().userId)
  }
  setUpdateTimeToNow()
}

/**
 * @todo: documentation
 *
 * @param {Boolean} dontScroll - document this
 * @param {Boolean} save - if set to `false`, calling this function will not
 *          cause a re-save of street to the server. (e.g. in the case of
 *          live update feature.) Default is `true`.
 */
export function updateEverything (dontScroll, save = true) {
  setIgnoreStreetChanges(true)
  propagateUnits()
  // TODO Verify that we don't need to dispatch an update width event here
  createDomFromData()
  segmentsChanged()
  resizeStreetWidth(dontScroll)
  updateStreetName()
  setIgnoreStreetChanges(false)
  _lastStreet = trimStreetData(store.getState().street)

  if (save === true) {
    scheduleSavingStreetToServer()
  }
}
<commit_msg>use changeSegmentVariant when updating schema; unsure if this is the correct way to do it<commit_after>import { msg } from '../app/messages'
import { URL_NO_USER, RESERVED_URLS, URL_RESERVED_PREFIX } from '../app/routing'
import {
  createBuildings,
  updateBuildingPosition
} from '../segments/buildings'
import { DEFAULT_SEGMENTS } from '../segments/default'
import { getSegmentInfo } from '../segments/info'
import { normalizeAllSegmentWidths } from '../segments/resizing'
import { getVariantString, getVariantArray } from '../segments/variant_utils'
import {
  segmentsChanged,
  repositionSegments,
  createSegmentDom
} from '../segments/view'
import { getSignInData, isSignedIn } from '../users/authentication'
import { getUnits, getLeftHandTraffic, propagateUnits } from '../users/localization'
import { normalizeSlug } from '../util/helpers'
import { generateRandSeed } from '../util/random'
import { updateStreetName } from './name'
import {
  createNewUndoIfNecessary,
  unifyUndoStack
} from './undo_stack'
import {
  DEFAULT_STREET_WIDTH,
  normalizeStreetWidth,
  resizeStreetWidth
} from './width'
import { updateLastStreetInfo, scheduleSavingStreetToServer } from './xhr'
import {
  setBuildingVariant,
  setBuildingFloorValue,
  addLocation,
  updateSchemaVersion,
  clearSegments,
  saveCreatorId,
  updateEditCount,
  updateStreetWidth,
  saveStreetName,
  setUnits,
  setUpdateTime,
  updateSegments,
  changeSegmentVariant
} from '../store/actions/street'
import { resetUndoStack } from '../store/actions/undo'
import store from '../store'

const DEFAULT_BUILDING_HEIGHT_LEFT = 4
const DEFAULT_BUILDING_HEIGHT_RIGHT = 3
const DEFAULT_BUILDING_VARIANT_LEFT = 'narrow'
const DEFAULT_BUILDING_VARIANT_RIGHT = 'wide'
const DEFAULT_BUILDING_HEIGHT_EMPTY = 1
const DEFAULT_BUILDING_VARIANT_EMPTY = 'grass'

let _lastStreet

export function getLastStreet () {
  return _lastStreet
}

export function setLastStreet (value) {
  _lastStreet = value
}

const LATEST_SCHEMA_VERSION = 18
// 1: starting point
// 2: adding leftBuildingHeight and rightBuildingHeight
// 3: adding leftBuildingVariant and rightBuildingVariant
// 4: adding transit shelter elevation
// 5: adding another lamp type (traditional)
// 6: colored streetcar lanes
// 7: colored bus and light rail lanes
// 8: colored bike lane
// 9: second car type: truck
// 10: sidewalk density
// 11: unify median and planting strip into divider
// 12: getting rid of small tree
// 13: bike rack elevation
// 14: wayfinding has three types
// 15: sidewalks have rand seed
// 16: stop saving undo stack
// 17: alternative colors for bike lanes
// 18: change lat/lng format from array to object

export const DEFAULT_NAME = msg('DEFAULT_STREET_NAME')

function incrementSchemaVersion (street) {
  let segment, variant, schemaVersion

  if (!street.schemaVersion) {
    schemaVersion = 1
  }

  switch (street.schemaVersion) {
    case 1:
      store.dispatch(setBuildingFloorValue('left', DEFAULT_BUILDING_HEIGHT_LEFT))
      store.dispatch(setBuildingFloorValue('right', DEFAULT_BUILDING_HEIGHT_RIGHT))
      break
    case 2:
      store.dispatch(setBuildingVariant('left', DEFAULT_BUILDING_VARIANT_LEFT))
      store.dispatch(setBuildingVariant('right', DEFAULT_BUILDING_VARIANT_RIGHT))
      break
    case 3:
      for (var i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'transit-shelter') {
          store.dispatch(changeSegmentVariant(i, 'transit-shelter-elevation', 'street-level'))
        }
      }
      break
    case 4:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'sidewalk-lamp') {
          store.dispatch(changeSegmentVariant(i, 'lamp-type', 'modern'))
        }
      }
      break
    case 5:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'streetcar') {
          store.dispatch(changeSegmentVariant(i, 'public-transit-asphalt', 'regular'))
        }
      }
      break
    case 6:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'bus-lane') {
          store.dispatch(changeSegmentVariant(i, 'bus-asphalt', 'regular'))
        } else if (segment.type === 'light-rail') {
          store.dispatch(changeSegmentVariant(i, 'public-transit-asphalt', 'regular'))
        }
      }
      break
    case 7:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'bike-lane') {
          store.dispatch(changeSegmentVariant(i, 'bike-asphalt', 'regular'))
        }
      }
      break
    case 8:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'drive-lane') {
          store.dispatch(changeSegmentVariant(i, 'car-type', 'car'))
        }
      }
      break
    case 9:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'sidewalk') {
          store.dispatch(changeSegmentVariant(i, 'sidewalk-density', 'normal'))
        }
      }
      break
    case 10:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'planting-strip') {
          segment.type = 'divider'

          if (segment.variantString === '') {
            segment.variantString = 'planting-strip'
          }
        } else if (segment.type === 'small-median') {
          segment.type = 'divider'
          segment.variantString = 'median'
        }
      }
      break
    case 11:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'divider') {
          if (segment.variantString === 'small-tree') {
            segment.variantString = 'big-tree'
          }
        } else if (segment.type === 'sidewalk-tree') {
          if (segment.variantString === 'small') {
            segment.variantString = 'big'
          }
        }
      }
      break
    case 12:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'sidewalk-bike-rack') {
          store.dispatch(changeSegmentVariant(i, 'bike-rack-elevation', 'sidewalk'))
        }
      }
      break
    case 13:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'sidewalk-wayfinding') {
          store.dispatch(changeSegmentVariant(i, 'wayfinding-type', 'large'))
        }
      }
      break
    case 14:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'sidewalk') {
          segment.randSeed = 35
        }
      }
      break
    case 15:
      store.dispatch(resetUndoStack())
      break
    case 16:
      for (let i in street.segments) {
        segment = street.segments[i]
        if (segment.type === 'bike-lane') {
          variant = getVariantArray(segment.type, segment.variantString)
          if (variant['bike-asphalt'] === 'colored') {
            variant['bike-asphalt'] = 'green'
          }
          segment.variantString = getVariantString(variant)
        }
      }
      break
    case 17:
      if (street.location && street.location.latlng) {
        const location = {
          ...street.location,
          latlng: {
            lat: street.location.latlng[0],
            lng: street.location.latlng[1]
          }
        }
        store.dispatch(addLocation(location))
      }
  }

  schemaVersion++
  store.dispatch(updateSchemaVersion(schemaVersion))
}

export function updateToLatestSchemaVersion (street) {
  var updated = false
  while (!street.schemaVersion || (street.schemaVersion < LATEST_SCHEMA_VERSION)) {
    incrementSchemaVersion(street)
    updated = true
  }

  return updated
}

export function createDomFromData () {
  document.querySelector('#street-section-editable').innerHTML = ''
  const street = store.getState().street

  for (var i in street.segments) {
    var segment = street.segments[i]

    // Add some additional data structures
    // TODO: populate data structure elsewhere
    segment.variant = getVariantArray(segment.type, segment.variantString)
    segment.warnings = []

    var el = createSegmentDom(segment)
    document.querySelector('#street-section-editable').appendChild(el)

    segment.el = el
    segment.el.dataNo = i
  }

  repositionSegments()
  updateBuildingPosition()
  createBuildings()
}

export function setStreetCreatorId (newId) {
  store.dispatch(saveCreatorId(newId))

  unifyUndoStack()
  updateLastStreetInfo()
}

export function setUpdateTimeToNow () {
  store.dispatch(setUpdateTime(new Date().getTime()))
  unifyUndoStack()
}

let ignoreStreetChanges = false

export function setIgnoreStreetChanges (value) {
  ignoreStreetChanges = value
}

export function saveStreetToServerIfNecessary () {
  if (ignoreStreetChanges || store.getState().errors.abortEverything) {
    return
  }

  const street = store.getState().street
  var currentData = trimStreetData(street)

  if (JSON.stringify(currentData) !== JSON.stringify(_lastStreet)) {
    if (street.editCount !== null) {
      street.editCount++
    }
    setUpdateTimeToNow()

    // Some parts of the UI need to know this happened to respond to it
    // TODO: figure out appropriate event name
    window.dispatchEvent(new window.CustomEvent('stmx:save_street'))

    createNewUndoIfNecessary(_lastStreet, currentData)

    scheduleSavingStreetToServer()

    _lastStreet = currentData
  }
}

// Copies only the data necessary for save/undo.
export function trimStreetData (street) {
  var newData = {}

  newData.schemaVersion = street.schemaVersion

  newData.width = street.width
  newData.name = street.name

  newData.id = street.id
  newData.namespacedId = street.namespacedId
  newData.creatorId = street.creatorId
  newData.originalStreetId = street.originalStreetId
  newData.units = street.units

  newData.location = street.location
  newData.userUpdated = street.userUpdated

  if (street.editCount !== null) {
    // console.log('saving editCount', street.editCount)
    newData.editCount = street.editCount
  } else {
    // console.log('not saving editCount')
  }

  newData.leftBuildingHeight = street.leftBuildingHeight
  newData.rightBuildingHeight = street.rightBuildingHeight
  newData.leftBuildingVariant = street.leftBuildingVariant
  newData.rightBuildingVariant = street.rightBuildingVariant

  newData.segments = []

  for (var i in street.segments) {
    var segment = {}
    segment.type = street.segments[i].type
    segment.variantString = street.segments[i].variantString
    segment.width = street.segments[i].width
    if (street.segments[i].randSeed) {
      segment.randSeed = street.segments[i].randSeed
    }

    newData.segments.push(segment)
  }

  return newData
}

// TODO this function should not exist; all the data should be in street.
// object to begin with
export function createDataFromDom () {
  var els = document.querySelectorAll('#street-section-editable > .segment')
  const segments = []

  for (var i = 0, el; el = els[i]; i++) { // eslint-disable-line no-cond-assign
    var segment = {}
    segment.type = el.getAttribute('type')
    if (el.getAttribute('rand-seed')) {
      segment.randSeed = parseInt(el.getAttribute('rand-seed'))
    }
    segment.variantString = el.getAttribute('variant-string')
    segment.variant = getVariantArray(segment.type, segment.variantString)
    segment.width = parseFloat(el.getAttribute('data-width'))
    segment.el = el
    segment.warnings = []
    segments.push(segment)
  }
  store.dispatch(updateSegments(segments))
}

function fillDefaultSegments () {
  const segments = []
  let leftHandTraffic = getLeftHandTraffic()

  for (var i in DEFAULT_SEGMENTS[leftHandTraffic]) {
    var segment = DEFAULT_SEGMENTS[leftHandTraffic][i]
    segment.warnings = []
    segment.variantString = getVariantString(segment.variant)

    if (getSegmentInfo(segment.type).needRandSeed) {
      segment.randSeed = generateRandSeed()
    }

    segments.push(segment)
  }
  store.dispatch(updateSegments(segments))
  normalizeAllSegmentWidths()
}

export function getStreetUrl (street) {
  var url = '/'
  if (street.creatorId) {
    if (RESERVED_URLS.indexOf(street.creatorId) !== -1) {
      url += URL_RESERVED_PREFIX
    }

    url += street.creatorId
  } else {
    url += URL_NO_USER
  }

  url += '/'

  url += street.namespacedId

  if (street.creatorId) {
    var slug = normalizeSlug(street.name)
    url += '/' + encodeURIComponent(slug)
  }

  return url
}

export function prepareDefaultStreet () {
  store.dispatch(setUnits(getUnits()))
  propagateUnits()

  store.dispatch(saveStreetName(DEFAULT_NAME, false))
  store.dispatch(updateStreetWidth(normalizeStreetWidth(DEFAULT_STREET_WIDTH)))
  store.dispatch(setBuildingFloorValue('left', DEFAULT_BUILDING_HEIGHT_LEFT))
  store.dispatch(setBuildingFloorValue('right', DEFAULT_BUILDING_HEIGHT_RIGHT))
  store.dispatch(setBuildingVariant('left', DEFAULT_BUILDING_VARIANT_LEFT))
  store.dispatch(setBuildingVariant('right', DEFAULT_BUILDING_VARIANT_RIGHT))
  store.dispatch(updateEditCount(0))

  // console.log('editCount = 0 on default street')
  if (isSignedIn()) {
    setStreetCreatorId(getSignInData().userId)
  }
  fillDefaultSegments()
  setUpdateTimeToNow()
}

export function prepareEmptyStreet () {
  store.dispatch(setUnits(getUnits()))
  propagateUnits()

  store.dispatch(saveStreetName(DEFAULT_NAME, false))
  store.dispatch(updateStreetWidth(normalizeStreetWidth(DEFAULT_STREET_WIDTH)))
  store.dispatch(setBuildingFloorValue('left', DEFAULT_BUILDING_HEIGHT_EMPTY))
  store.dispatch(setBuildingFloorValue('right', DEFAULT_BUILDING_HEIGHT_EMPTY))
  store.dispatch(setBuildingVariant('left', DEFAULT_BUILDING_VARIANT_EMPTY))
  store.dispatch(setBuildingVariant('right', DEFAULT_BUILDING_VARIANT_EMPTY))
  store.dispatch(updateEditCount(0))
  store.dispatch(clearSegments())

  // console.log('editCount = 0 on empty street!')
  if (isSignedIn()) {
    setStreetCreatorId(getSignInData().userId)
  }
  setUpdateTimeToNow()
}

/**
 * @todo: documentation
 *
 * @param {Boolean} dontScroll - document this
 * @param {Boolean} save - if set to `false`, calling this function will not
 *          cause a re-save of street to the server. (e.g. in the case of
 *          live update feature.) Default is `true`.
 */
export function updateEverything (dontScroll, save = true) {
  setIgnoreStreetChanges(true)
  propagateUnits()
  // TODO Verify that we don't need to dispatch an update width event here
  createDomFromData()
  segmentsChanged()
  resizeStreetWidth(dontScroll)
  updateStreetName()
  setIgnoreStreetChanges(false)
  _lastStreet = trimStreetData(store.getState().street)

  if (save === true) {
    scheduleSavingStreetToServer()
  }
}
<|endoftext|>


<commit_before>
/*import MaterialDateTimePicker from 'material-datetime-picker';*/
{

    let dp_soon = moment().add(2, 'h').minute(0);
    $('.c-datepicker-input').val( dp_soon.format('HH:mm YYYY/MM/DD') );

    const picker = new MaterialDatetimePicker({defualt: dp_soon, min: moment()}).on('submit', value => {
        if(value.toDate() < Date.now()) value = moment().add(2, 'h').minute(0);
        $('.c-datepicker-input').val( value.format('HH:mm YYYY/MM/DD') );
    });

    $('.c-datepicker-input').focus( e => {
        e.preventDefault();
        picker.open();
    });

    $('.req-ing-table input[name="req-want"], .req-ing-table input[name="req-have"]').change(function(e){

        if($(this).attr('name') === 'req-want'){ //set the other to false
            $('input[name="req-have"][value="'+$(this).attr('value')+'"]').prop('checked', false);
        } else {
            $('input[name="req-want"][value="'+$(this).attr('value')+'"]').prop('checked', false);
        }

        setTimeout(()=>{
            $('.req-have-table tbody tr, .req-want-table tbody tr').remove();
            $('.req-ing-table input[name="req-want"]:checked .name').each(function(){
                $('.req-want-table tbody').append('
'+$(this).text()+'
');
            });
            $('.req-ing-table input[name="req-have"]:checked .name').each(function(){
                $('.req-have-table tbody').append('
'+$(this).text()+'
');
            });
        }, 50);
    });

    $('input#req-ing-search').keyup(function(){
        $('.req-ing-table tbody tr').hide();
        $('.req-ing-table tbody tr[data-text*="'+$(this).val()+'"]').show();
    });

}

var initMap = function(){

    // setup objects //
    let geocoder = new google.maps.Geocoder();
    let autocomplete = new google.maps.places.Autocomplete(document.getElementById('req-loc'), {componentRestrictions: {country: 'au'}});

    let getLoc = new google.maps.LatLng( -26.0906899, 128.1506632);

    let map = new google.maps.Map(document.getElementById('req_getLocMap'), {
      center: getLoc,
      zoom: 5
    });

    let marker = new google.maps.Marker({
        map,
        position: getLoc
    });

    let circle = new google.maps.Circle({
        map,
        center: getLoc,
        radius: (Number($('input#req-dist').val()) || 2) * 1000,
        fillColor: "#004445",
        fillOpacity: 0.5,
        strokeWeight: 0,
        clickable: false
    });

    // setup helper functions //

    let updatePos = (e, dontName)=>{
        if(dontName){
            getLoc = e.latLng;
            marker.setPosition(getLoc);
            circle.setCenter(getLoc);
            map.setCenter(getLoc);
            $('input#req-lat').val(getLoc.lat());
            $('input#req-long').val(getLoc.lng());
        } else {
            geocoder.geocode( { location: e.latLng}, (results, status) => {
                if (status == 'OK') {
                    updatePos({latLng: results[0].geometry.location}, true);
                    $('input#req-loc').val(results[0].formatted_address);
                } else {
                    console.log(status);
                    updatePos({latLng: e.latLng});
                }
                map.setZoom(14);
            });
        }
    };

    let geoErr = (hasGeo) => { alert("Could not get your location. " + hasGeo) };

    // handle events //

    map.addListener('click', updatePos);

    $('button.getloc').click( e => {
        e.preventDefault();
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(position => {
                let geoloc = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                updatePos({latLng: geoloc});
            }, ()=> {
                geoErr(true);
            });
        } else geoErr(false);
    });

    $('input#req-dist').change( () => {
        circle.setRadius((Number($('input#req-dist').val()) || 2) * 1000);
    });

    $('input#req-loc').change( e => {
        setTimeout( ()=>{
            geocoder.geocode( { address: $('input#req-loc').val(), region: 'au'}, (results, status) => {
                if (status == 'OK') {
                    updatePos({latLng: results[0].geometry.location}, true);
                    console.log(results);
                    //$('input#req-loc').val(results[0].formatted_address);
                } else {
                    alert('Adress lookup failed. ' + status);
                }
                map.setZoom(14);
            });
        }, 100);
    });
};<commit_msg>moar twerks<commit_after>
/*import MaterialDateTimePicker from 'material-datetime-picker';*/
{

    let dp_soon = moment().add(2, 'h').minute(0);
    $('.c-datepicker-input').val( dp_soon.format('HH:mm YYYY/MM/DD') );

    const picker = new MaterialDatetimePicker({defualt: dp_soon, min: moment()}).on('submit', value => {
        if(value.toDate() < Date.now()) value = moment().add(2, 'h').minute(0);
        $('.c-datepicker-input').val( value.format('HH:mm YYYY/MM/DD') );
    });

    $('.c-datepicker-input').focus( e => {
        e.preventDefault();
        picker.open();
    });

    $('.req-ing-table input[name="req-want"], .req-ing-table input[name="req-have"]').change(function(e){

        if($(this).attr('name') === 'req-want'){ //set the other to false
            $('input[name="req-have"][value="'+$(this).attr('value')+'"]').prop('checked', false);
        } else {
            $('input[name="req-want"][value="'+$(this).attr('value')+'"]').prop('checked', false);
        }

        setTimeout(()=>{
            $('.req-have-table tbody tr, .req-want-table tbody tr').remove();
            $('.req-ing-table input[name="req-want"]:checked').each(function(){
                $('.req-want-table tbody').append('
'+$(this).attr('value')+'
');
            });
            $('.req-ing-table input[name="req-have"]:checked').each(function(){
                $('.req-have-table tbody').append('
'+$(this).attr('value')+'
');
            });
        }, 50);
    });

    $('input#req-ing-search').keyup(function(){
        if($(this).val().trim() !== ''){
            $('.req-ing-table tbody tr').hide();
            $('.req-ing-table tbody tr[data-text*="'+$(this).val()+'"]').show();
        } else {
            $('.req-ing-table tbody tr').show();
        }
    });

}

var initMap = function(){

    // setup objects //
    let geocoder = new google.maps.Geocoder();
    let autocomplete = new google.maps.places.Autocomplete(document.getElementById('req-loc'), {componentRestrictions: {country: 'au'}});

    let getLoc = new google.maps.LatLng( -26.0906899, 128.1506632);

    let map = new google.maps.Map(document.getElementById('req_getLocMap'), {
      center: getLoc,
      zoom: 5
    });

    let marker = new google.maps.Marker({
        map,
        position: getLoc
    });

    let circle = new google.maps.Circle({
        map,
        center: getLoc,
        radius: (Number($('input#req-dist').val()) || 2) * 1000,
        fillColor: "#004445",
        fillOpacity: 0.5,
        strokeWeight: 0,
        clickable: false
    });

    // setup helper functions //

    let updatePos = (e, dontName)=>{
        if(dontName){
            getLoc = e.latLng;
            marker.setPosition(getLoc);
            circle.setCenter(getLoc);
            map.setCenter(getLoc);
            $('input#req-lat').val(getLoc.lat());
            $('input#req-long').val(getLoc.lng());
        } else {
            geocoder.geocode( { location: e.latLng}, (results, status) => {
                if (status == 'OK') {
                    updatePos({latLng: results[0].geometry.location}, true);
                    $('input#req-loc').val(results[0].formatted_address);
                } else {
                    console.log(status);
                    updatePos({latLng: e.latLng});
                }
                map.setZoom(14);
            });
        }
    };

    let geoErr = (hasGeo) => { alert("Could not get your location. " + hasGeo) };

    // handle events //

    map.addListener('click', updatePos);

    $('button.getloc').click( e => {
        e.preventDefault();
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(position => {
                let geoloc = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                updatePos({latLng: geoloc});
            }, ()=> {
                geoErr(true);
            });
        } else geoErr(false);
    });

    $('input#req-dist').change( () => {
        circle.setRadius((Number($('input#req-dist').val()) || 2) * 1000);
    });

    $('input#req-loc').change( e => {
        setTimeout( ()=>{
            geocoder.geocode( { address: $('input#req-loc').val(), region: 'au'}, (results, status) => {
                if (status == 'OK') {
                    updatePos({latLng: results[0].geometry.location}, true);
                    console.log(results);
                    //$('input#req-loc').val(results[0].formatted_address);
                } else {
                    alert('Adress lookup failed. ' + status);
                }
                map.setZoom(14);
            });
        }, 100);
    });
};<|endoftext|>


<commit_before>db.trial_files.aggregate({$match: {court_id: ObjectId("53fba7656c6f6338e3010000")}}, {$limit: 200},{$group: { _id: "$number"}});<commit_msg>small changes to query<commit_after>db.trial_files.aggregate([{$limit: 200}, {$match: {court_id: ObjectId("53fba7656c6f6338e3010000")}}, {$group: { _id: "$number", }}, {$project : {date: 1, court_id: 1, _id: 1, number: 1}}]);<|endoftext|>


<commit_before>'use strict';

exports.BattleScripts = {
	moveHit: function (target, pokemon, move, moveData, isSecondary, isSelf) {
		let damage;
		move = this.getMoveCopy(move);

		if (!moveData) moveData = move;
		if (!moveData.flags) moveData.flags = {};
		let hitResult = true;

		// TryHit events:
		//   STEP 1: we see if the move will succeed at all:
		//   - TryHit, TryHitSide, or TryHitField are run on the move,
		//     depending on move target (these events happen in useMove
		//     or tryMoveHit, not below)
		//   == primary hit line ==
		//   Everything after this only happens on the primary hit (not on
		//   secondary or self-hits)
		//   STEP 2: we see if anything blocks the move from hitting:
		//   - TryFieldHit is run on the target
		//   STEP 3: we see if anything blocks the move from hitting the target:
		//   - If the move's target is a pokemon, TryHit is run on that pokemon

		// Note:
		//   If the move target is `foeSide`:
		//     event target = pokemon 0 on the target side
		//   If the move target is `allySide` or `all`:
		//     event target = the move user
		//
		//   This is because events can't accept actual sides or fields as
		//   targets. Choosing these event targets ensures that the correct
		//   side or field is hit.
		//
		//   It is the `TryHitField` event handler's responsibility to never
		//   use `target`.
		//   It is the `TryFieldHit` event handler's responsibility to read
		//   move.target and react accordingly.
		//   An exception is `TryHitSide` as a single event (but not as a normal
		//   event), which is passed the target side.

		if (move.target === 'all' && !isSelf) {
			hitResult = this.singleEvent('TryHitField', moveData, {}, target, pokemon, move);
		} else if ((move.target === 'foeSide' || move.target === 'allySide') && !isSelf) {
			hitResult = this.singleEvent('TryHitSide', moveData, {}, target.side, pokemon, move);
		} else if (target) {
			hitResult = this.singleEvent('TryHit', moveData, {}, target, pokemon, move);
		}
		if (!hitResult) {
			if (hitResult === false) this.add('-fail', target);
			return false;
		}

		if (target && !isSecondary && !isSelf) {
			if (move.target !== 'all' && move.target !== 'allySide' && move.target !== 'foeSide') {
				hitResult = this.runEvent('TryPrimaryHit', target, pokemon, moveData);
				if (hitResult === 0) {
					// special Substitute flag
					hitResult = true;
					target = null;
				}
			}
		}
		if (target && isSecondary && !moveData.self) {
			hitResult = true;
		}
		if (!hitResult) {
			return false;
		}

		if (target) {
			let didSomething = false;

			damage = this.getDamage(pokemon, target, moveData);

			// getDamage has several possible return values:
			//
			//   a number:
			//     means that much damage is dealt (0 damage still counts as dealing
			//     damage for the purposes of things like Static)
			//   false:
			//     gives error message: "But it failed!" and move ends
			//   null:
			//     the move ends, with no message (usually, a custom fail message
			//     was already output by an event handler)
			//   undefined:
			//     means no damage is dealt and the move continues
			//
			// basically, these values have the same meanings as they do for event
			// handlers.

			if ((damage || damage === 0) && !target.fainted) {
				if (move.noFaint && damage >= target.hp) {
					damage = target.hp - 1;
				}
				damage = this.damage(damage, target, pokemon, move);
				if (!(damage || damage === 0)) {
					this.debug('damage interrupted');
					return false;
				}
				didSomething = true;
			}
			if (damage === false || damage === null) {
				if (damage === false && !isSecondary && !isSelf) {
					this.add('-fail', target);
				}
				this.debug('damage calculation interrupted');
				return false;
			}

			if (moveData.boosts && !target.fainted) {
				hitResult = this.boost(moveData.boosts, target, pokemon, move, isSecondary, isSelf);
				didSomething = didSomething || hitResult;
			}
			if (moveData.heal && !target.fainted) {
				let d = target.heal((this.gen < 5 ? Math.floor : Math.round)(target.maxhp * moveData.heal[0] / moveData.heal[1]));
				if (!d && d !== 0) {
					this.add('-fail', target);
					this.debug('heal interrupted');
					return false;
				}
				this.add('-heal', target, target.getHealth);
				didSomething = true;
			}
			if (moveData.status) {
				hitResult = target.trySetStatus(moveData.status, pokemon, moveData.ability ? moveData.ability : move);
				if (!hitResult && move.status) return hitResult;
				didSomething = didSomething || hitResult;
			}
			if (moveData.forceStatus) {
				hitResult = target.setStatus(moveData.forceStatus, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.volatileStatus) {
				hitResult = target.addVolatile(moveData.volatileStatus, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.sideCondition) {
				hitResult = target.side.addSideCondition(moveData.sideCondition, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.weather) {
				hitResult = this.setWeather(moveData.weather, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.terrain) {
				hitResult = this.setTerrain(moveData.terrain, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.pseudoWeather) {
				hitResult = this.addPseudoWeather(moveData.pseudoWeather, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.forceSwitch) {
				if (this.canSwitch(target.side)) didSomething = true; // at least defer the fail message to later
			}
			if (moveData.selfSwitch) {
				if (this.canSwitch(pokemon.side)) didSomething = true; // at least defer the fail message to later
			}
			// Hit events
			//   These are like the TryHit events, except we don't need a FieldHit event.
			//   Scroll up for the TryHit event documentation, and just ignore the "Try" part. ;)
			hitResult = null;
			if (move.target === 'all' && !isSelf) {
				if (moveData.onHitField) hitResult = this.singleEvent('HitField', moveData, {}, target, pokemon, move);
			} else if ((move.target === 'foeSide' || move.target === 'allySide') && !isSelf) {
				if (moveData.onHitSide) hitResult = this.singleEvent('HitSide', moveData, {}, target.side, pokemon, move);
			} else {
				if (moveData.onHit) hitResult = this.singleEvent('Hit', moveData, {}, target, pokemon, move);
				if (!isSelf && !isSecondary) {
					this.runEvent('Hit', target, pokemon, move);
				}
				if (moveData.onAfterHit) hitResult = this.singleEvent('AfterHit', moveData, {}, target, pokemon, move);
			}

			if (!hitResult && !didSomething && !moveData.self && !moveData.selfdestruct) {
				if (!isSelf && !isSecondary) {
					if (hitResult === false || didSomething === false) this.add('-fail', target);
				}
				this.debug('move failed because it did nothing');
				return false;
			}
		}
		if (moveData.self) {
			let selfRoll;
			if (!isSecondary && moveData.self.boosts) selfRoll = this.random(100);
			// This is done solely to mimic in-game RNG behaviour. All self drops have a 100% chance of happening but still grab a random number.
			if (typeof moveData.self.chance === 'undefined' || selfRoll < moveData.self.chance) {
				this.moveHit(pokemon, pokemon, move, moveData.self, isSecondary, true);
			}
		}
		if (moveData.secondaries) {
			let secondaryRoll;
			let secondaries = this.runEvent('ModifySecondaries', target, pokemon, moveData, moveData.secondaries.slice());
			for (let i = 0; i < secondaries.length; i++) {
				secondaryRoll = this.random(100);
				if (typeof secondaries[i].chance === 'undefined' || secondaryRoll < secondaries[i].chance) {
					// mod for automagic start
					let flag = true;
					let subBlocks = !target || (target.volatiles['substitute'] && !move.infiltrates && !moveData.flags['authentic']);
					let canSetStatus = function (status, target, pokemon) {
						if (target.status) return false;
						let cantStatus = {
							brn: ['Fire', 'comatose', 'waterveil', 'waterbubble'],
							frz: ['Ice', 'comatose', 'magmaarmor'],
							par: ['Electric', 'comatose', 'limber'],
							psn: ['comatose', 'immunity'],
							slp: ['comatose', 'insomnia', 'vitalspirit'],
							tox: ['comatose', 'immunity'],
						};
						if (target.hasType(['Poison', 'Steel']) && (status === 'psn' || status === 'tox')) {
							if (pokemon.hasAbility('corrosion')) {
								return true;
							} else {
								return false;
							}
						}
						if (target.hasType(cantStatus[status][0])) return false;
						if (move.ignoreAbility) return true;
						if (target.hasAbility('leafguard') && this.isWeather(['sunnyday', 'desolateland'])) return false;
						if (target.hasAbility('shieldsdown') && target.template.speciesid === 'miniormeteor') return false;
						if (target.hasAbility(cantStatus[status])) return false;
						return true;
					};
					if (moveData.secondary.status) flag = !subBlocks && canSetStatus(moveData.secondary.status, target, pokemon);
					if (moveData.secondary.volatileStatus) flag = !subBlocks && !(moveData.secondary.volatileStatus in target.volatiles);
					if (moveData.secondary.volatileStatus === 'flinch') flag = flag && target.activeTurns && !target.moveThisTurn;
					this.moveHit(target, pokemon, move, secondaries[i], true, isSelf);
					if (moveData.secondary.self && moveData.secondary.self.boosts) {
						Object.keys(moveData.secondary.self.boosts).forEach(boost => {
							if (pokemon.boosts[boost] === 6) flag = false;
						});
					} else {
						flag = flag && target && !(target.hp === undefined || target.hp <= 0);
					}
					if (moveData.target !== 'self' && moveData.secondary.boosts && !subBlocks) {
						let cantLower = {
							'atk': ['clearbody', 'fullmetalbody', 'hypercutter', 'whitesmoke'],
							'def': ['bigpecks', 'clearbody', 'fullmetalbody', 'whitesmoke'],
							'spa': ['clearbody', 'fullmetalbody', 'whitesmoke'],
							'spd': ['clearbody', 'fullmetalbody', 'whitesmoke'],
							'spe': ['clearbody', 'fullmetalbody', 'whitesmoke'],
							'accuracy': ['clearbody', 'fullmetalbody', 'keeneye', 'whitesmoke'],
						};
						for (let k in moveData.secondary.boosts) {
							if (target.boosts[k] === -6) {
								flag = false;
								continue;
							}
							if (moveData.secondary.boosts[k] < 0 && target.hasAbility(cantLower[k]) && !move.ignoreAbility) {
								flag = false;
								break;
							}
						}
					}
					if (pokemon.hasAbility('sheerforce')) flag = false;
					if (target && target.hasAbility('shielddust') && !move.ignoreAbility && !move.secondary.self.boosts) {
						flag = false;
					}
					if (flag) this.runEvent('AfterSecondaryEffect', target, pokemon, moveData);
					// mod for automagic end
				}
			}
		}
		if (target && target.hp > 0 && pokemon.hp > 0 && moveData.forceSwitch && this.canSwitch(target.side)) {
			hitResult = this.runEvent('DragOut', target, pokemon, move);
			if (hitResult) {
				target.forceSwitchFlag = true;
			} else if (hitResult === false && move.category === 'Status') {
				this.add('-fail', target);
			}
		}
		if (move.selfSwitch && pokemon.hp) {
			pokemon.switchFlag = move.selfSwitch;
		}
		return damage;
	},
};
<commit_msg>Update scripts.js (#3353)<commit_after>'use strict';

exports.BattleScripts = {
	moveHit: function (target, pokemon, move, moveData, isSecondary, isSelf) {
		let damage;
		move = this.getMoveCopy(move);

		if (!moveData) moveData = move;
		if (!moveData.flags) moveData.flags = {};
		let hitResult = true;

		// TryHit events:
		//   STEP 1: we see if the move will succeed at all:
		//   - TryHit, TryHitSide, or TryHitField are run on the move,
		//     depending on move target (these events happen in useMove
		//     or tryMoveHit, not below)
		//   == primary hit line ==
		//   Everything after this only happens on the primary hit (not on
		//   secondary or self-hits)
		//   STEP 2: we see if anything blocks the move from hitting:
		//   - TryFieldHit is run on the target
		//   STEP 3: we see if anything blocks the move from hitting the target:
		//   - If the move's target is a pokemon, TryHit is run on that pokemon

		// Note:
		//   If the move target is `foeSide`:
		//     event target = pokemon 0 on the target side
		//   If the move target is `allySide` or `all`:
		//     event target = the move user
		//
		//   This is because events can't accept actual sides or fields as
		//   targets. Choosing these event targets ensures that the correct
		//   side or field is hit.
		//
		//   It is the `TryHitField` event handler's responsibility to never
		//   use `target`.
		//   It is the `TryFieldHit` event handler's responsibility to read
		//   move.target and react accordingly.
		//   An exception is `TryHitSide` as a single event (but not as a normal
		//   event), which is passed the target side.

		if (move.target === 'all' && !isSelf) {
			hitResult = this.singleEvent('TryHitField', moveData, {}, target, pokemon, move);
		} else if ((move.target === 'foeSide' || move.target === 'allySide') && !isSelf) {
			hitResult = this.singleEvent('TryHitSide', moveData, {}, target.side, pokemon, move);
		} else if (target) {
			hitResult = this.singleEvent('TryHit', moveData, {}, target, pokemon, move);
		}
		if (!hitResult) {
			if (hitResult === false) this.add('-fail', target);
			return false;
		}

		if (target && !isSecondary && !isSelf) {
			if (move.target !== 'all' && move.target !== 'allySide' && move.target !== 'foeSide') {
				hitResult = this.runEvent('TryPrimaryHit', target, pokemon, moveData);
				if (hitResult === 0) {
					// special Substitute flag
					hitResult = true;
					target = null;
				}
			}
		}
		if (target && isSecondary && !moveData.self) {
			hitResult = true;
		}
		if (!hitResult) {
			return false;
		}

		if (target) {
			let didSomething = false;

			damage = this.getDamage(pokemon, target, moveData);

			// getDamage has several possible return values:
			//
			//   a number:
			//     means that much damage is dealt (0 damage still counts as dealing
			//     damage for the purposes of things like Static)
			//   false:
			//     gives error message: "But it failed!" and move ends
			//   null:
			//     the move ends, with no message (usually, a custom fail message
			//     was already output by an event handler)
			//   undefined:
			//     means no damage is dealt and the move continues
			//
			// basically, these values have the same meanings as they do for event
			// handlers.

			if ((damage || damage === 0) && !target.fainted) {
				if (move.noFaint && damage >= target.hp) {
					damage = target.hp - 1;
				}
				damage = this.damage(damage, target, pokemon, move);
				if (!(damage || damage === 0)) {
					this.debug('damage interrupted');
					return false;
				}
				didSomething = true;
			}
			if (damage === false || damage === null) {
				if (damage === false && !isSecondary && !isSelf) {
					this.add('-fail', target);
				}
				this.debug('damage calculation interrupted');
				return false;
			}

			if (moveData.boosts && !target.fainted) {
				hitResult = this.boost(moveData.boosts, target, pokemon, move, isSecondary, isSelf);
				didSomething = didSomething || hitResult;
			}
			if (moveData.heal && !target.fainted) {
				let d = target.heal((this.gen < 5 ? Math.floor : Math.round)(target.maxhp * moveData.heal[0] / moveData.heal[1]));
				if (!d && d !== 0) {
					this.add('-fail', target);
					this.debug('heal interrupted');
					return false;
				}
				this.add('-heal', target, target.getHealth);
				didSomething = true;
			}
			if (moveData.status) {
				hitResult = target.trySetStatus(moveData.status, pokemon, moveData.ability ? moveData.ability : move);
				if (!hitResult && move.status) return hitResult;
				didSomething = didSomething || hitResult;
			}
			if (moveData.forceStatus) {
				hitResult = target.setStatus(moveData.forceStatus, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.volatileStatus) {
				hitResult = target.addVolatile(moveData.volatileStatus, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.sideCondition) {
				hitResult = target.side.addSideCondition(moveData.sideCondition, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.weather) {
				hitResult = this.setWeather(moveData.weather, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.terrain) {
				hitResult = this.setTerrain(moveData.terrain, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.pseudoWeather) {
				hitResult = this.addPseudoWeather(moveData.pseudoWeather, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.forceSwitch) {
				if (this.canSwitch(target.side)) didSomething = true; // at least defer the fail message to later
			}
			if (moveData.selfSwitch) {
				if (this.canSwitch(pokemon.side)) didSomething = true; // at least defer the fail message to later
			}
			// Hit events
			//   These are like the TryHit events, except we don't need a FieldHit event.
			//   Scroll up for the TryHit event documentation, and just ignore the "Try" part. ;)
			hitResult = null;
			if (move.target === 'all' && !isSelf) {
				if (moveData.onHitField) hitResult = this.singleEvent('HitField', moveData, {}, target, pokemon, move);
			} else if ((move.target === 'foeSide' || move.target === 'allySide') && !isSelf) {
				if (moveData.onHitSide) hitResult = this.singleEvent('HitSide', moveData, {}, target.side, pokemon, move);
			} else {
				if (moveData.onHit) hitResult = this.singleEvent('Hit', moveData, {}, target, pokemon, move);
				if (!isSelf && !isSecondary) {
					this.runEvent('Hit', target, pokemon, move);
				}
				if (moveData.onAfterHit) hitResult = this.singleEvent('AfterHit', moveData, {}, target, pokemon, move);
			}

			if (!hitResult && !didSomething && !moveData.self && !moveData.selfdestruct) {
				if (!isSelf && !isSecondary) {
					if (hitResult === false || didSomething === false) this.add('-fail', target);
				}
				this.debug('move failed because it did nothing');
				return false;
			}
		}
		if (moveData.self) {
			let selfRoll;
			if (!isSecondary && moveData.self.boosts) selfRoll = this.random(100);
			// This is done solely to mimic in-game RNG behaviour. All self drops have a 100% chance of happening but still grab a random number.
			if (typeof moveData.self.chance === 'undefined' || selfRoll < moveData.self.chance) {
				this.moveHit(pokemon, pokemon, move, moveData.self, isSecondary, true);
			}
		}
		if (moveData.secondaries) {
			let secondaryRoll;
			let secondaries = this.runEvent('ModifySecondaries', target, pokemon, moveData, moveData.secondaries.slice());
			for (let i = 0; i < secondaries.length; i++) {
				secondaryRoll = this.random(100);
				if (typeof secondaries[i].chance === 'undefined' || secondaryRoll < secondaries[i].chance) {
					// mod for automagic start
					let flag = true;
					let subBlocks = !target || (target.volatiles['substitute'] && !move.infiltrates && !moveData.flags['authentic']);
					let canSetStatus = function (status, target, pokemon) {
						if (target.status) return false;
						let cantStatus = {
							brn: ['Fire', 'comatose', 'waterveil', 'waterbubble'],
							frz: ['Ice', 'comatose', 'magmaarmor'],
							par: ['Electric', 'comatose', 'limber'],
							psn: ['comatose', 'immunity'],
							slp: ['comatose', 'insomnia', 'vitalspirit'],
							tox: ['comatose', 'immunity'],
						};
						if (target.hasType(['Poison', 'Steel']) && (status === 'psn' || status === 'tox')) {
							if (pokemon.hasAbility('corrosion')) {
								return true;
							} else {
								return false;
							}
						}
						if (target.hasType(cantStatus[status][0])) return false;
						if (move.ignoreAbility) return true;
						if (target.hasAbility('leafguard') && this.isWeather(['sunnyday', 'desolateland'])) return false;
						if (target.hasAbility('shieldsdown') && target.template.speciesid === 'miniormeteor') return false;
						if (target.hasAbility(cantStatus[status])) return false;
						return true;
					};
					if (secondaries[i].status) flag = !subBlocks && canSetStatus(secondaries[i].status, target, pokemon);
					if (secondaries[i].volatileStatus) flag = !subBlocks && !(secondaries[i].volatileStatus in target.volatiles);
					if (secondaries[i].volatileStatus === 'flinch') flag = flag && target.activeTurns && !target.moveThisTurn;
					this.moveHit(target, pokemon, move, secondaries[i], true, isSelf);
					if (secondaries[i].self && secondaries[i].self.boosts) {
						Object.keys(secondaries[i].self.boosts).forEach(boost => {
							if (pokemon.boosts[boost] === 6) flag = false;
						});
					} else {
						flag = flag && target && !(target.hp === undefined || target.hp <= 0);
					}
					if (moveData.target !== 'self' && secondaries[i].boosts && !subBlocks) {
						let cantLower = {
							'atk': ['clearbody', 'fullmetalbody', 'hypercutter', 'whitesmoke'],
							'def': ['bigpecks', 'clearbody', 'fullmetalbody', 'whitesmoke'],
							'spa': ['clearbody', 'fullmetalbody', 'whitesmoke'],
							'spd': ['clearbody', 'fullmetalbody', 'whitesmoke'],
							'spe': ['clearbody', 'fullmetalbody', 'whitesmoke'],
							'accuracy': ['clearbody', 'fullmetalbody', 'keeneye', 'whitesmoke'],
						};
						for (let k in secondaries[i].boosts) {
							if (target.boosts[k] === -6) {
								flag = false;
								continue;
							}
							if (secondaries[i].boosts[k] < 0 && target.hasAbility(cantLower[k]) && !move.ignoreAbility) {
								flag = false;
								break;
							}
						}
					}
					if (pokemon.hasAbility('sheerforce')) flag = false;
					if (target && target.hasAbility('shielddust') && !move.ignoreAbility && !secondaries[i].self.boosts) {
						flag = false;
					}
					if (flag) this.runEvent('AfterSecondaryEffect', target, pokemon, moveData);
					// mod for automagic end
				}
			}
		}
		if (target && target.hp > 0 && pokemon.hp > 0 && moveData.forceSwitch && this.canSwitch(target.side)) {
			hitResult = this.runEvent('DragOut', target, pokemon, move);
			if (hitResult) {
				target.forceSwitchFlag = true;
			} else if (hitResult === false && move.category === 'Status') {
				this.add('-fail', target);
			}
		}
		if (move.selfSwitch && pokemon.hp) {
			pokemon.switchFlag = move.selfSwitch;
		}
		return damage;
	},
};
<|endoftext|>


<commit_before>exports.BattleScripts = {
	init: function () {
		this.modData('Pokedex', 'archeops').abilities['1'] = 'Vital Spirit';
		this.modData('Pokedex', 'porygonz').types = ['Normal', 'Ghost'];
		this.modData('Pokedex', 'weezing').types = ['Poison', 'Steel'];
		this.modData('Pokedex', 'moltres').abilities['1'] = 'Magic Guard';
		this.modData('Pokedex', 'abomasnowmega').abilities['0'] = 'Technician';
		this.modData('Pokedex', 'cradily').abilities['1'] = 'Sand Stream';
		this.modData('Pokedex', 'froslass').abilities['1'] = 'Prankster';
		this.modData('Learnsets', 'absol').learnset.partingshot = ['6T'];
		this.modData('Pokedex', 'goodra').abilities['1'] = 'Protean';
		this.modData('Pokedex', 'entei').abilities['1'] = 'Defiant';
		this.modData('Pokedex', 'milotic').abilities['H'] = 'Multiscale';
		this.modData('Pokedex', 'empoleon').abilities['1'] = 'Lightning Rod';
		this.modData('Learnsets', 'reuniclus').learnset.voltswitch = ['6T'];
		this.modData('Pokedex', 'steelixmega').abilities['0'] = 'Arena Trap';
		this.modData('Pokedex', 'audinomega').abilities['0'] = 'Simple';
		this.modData('Learnsets', 'ampharos').learnset.wish = ['6T'];
		this.modData('Pokedex', 'absolmega').types = ['Dark', 'Fairy'];
		this.modData('Pokedex', 'weavile').abilities['1'] = 'Moxie';
		this.modData('Learnsets', 'pangoro').learnset.suckerpunch = ['6T'];
		this.modData('Pokedex', 'rotomfan').types = ['Electric', 'Steel'];
		this.modData('Learnsets', 'rotomfan').learnset.flashcannon = this.data.Learnsets.rotomfan.learnset.airslash;
		this.modData('Learnsets', 'rotomfan').learnset.airslash = null;
		this.modData('Learnsets', 'mantine').learnset.roost = ['6T'];
		this.modData('Learnsets', 'pidgeot').learnset.focusblast = ['6T'];
		this.modData('Pokedex', 'granbull').abilities['1'] = 'Fur Coat';
		this.modData('Pokedex', 'aggronmega').types = ['Steel', 'Dragon'];
		this.modData('Learnsets', 'floatzel').learnset.bellydrum = ['6T'];
		this.modData('Pokedex', 'forretress').abilities['1'] = 'Water Absorb';
		this.modData('Learnsets', 'bronzong').learnset.recover = ['6T'];
	}
};
<commit_msg>Add latest Theorymon winner<commit_after>exports.BattleScripts = {
	init: function () {
		this.modData('Pokedex', 'archeops').abilities['1'] = 'Vital Spirit';
		this.modData('Pokedex', 'porygonz').types = ['Normal', 'Ghost'];
		this.modData('Pokedex', 'weezing').types = ['Poison', 'Steel'];
		this.modData('Pokedex', 'moltres').abilities['1'] = 'Magic Guard';
		this.modData('Pokedex', 'abomasnowmega').abilities['0'] = 'Technician';
		this.modData('Pokedex', 'cradily').abilities['1'] = 'Sand Stream';
		this.modData('Pokedex', 'froslass').abilities['1'] = 'Prankster';
		this.modData('Learnsets', 'absol').learnset.partingshot = ['6T'];
		this.modData('Pokedex', 'goodra').abilities['1'] = 'Protean';
		this.modData('Pokedex', 'entei').abilities['1'] = 'Defiant';
		this.modData('Pokedex', 'milotic').abilities['H'] = 'Multiscale';
		this.modData('Pokedex', 'empoleon').abilities['1'] = 'Lightning Rod';
		this.modData('Learnsets', 'reuniclus').learnset.voltswitch = ['6T'];
		this.modData('Pokedex', 'steelixmega').abilities['0'] = 'Arena Trap';
		this.modData('Pokedex', 'audinomega').abilities['0'] = 'Simple';
		this.modData('Learnsets', 'ampharos').learnset.wish = ['6T'];
		this.modData('Pokedex', 'absolmega').types = ['Dark', 'Fairy'];
		this.modData('Pokedex', 'weavile').abilities['1'] = 'Moxie';
		this.modData('Learnsets', 'pangoro').learnset.suckerpunch = ['6T'];
		this.modData('Pokedex', 'rotomfan').types = ['Electric', 'Steel'];
		this.modData('Learnsets', 'rotomfan').learnset.flashcannon = this.data.Learnsets.rotomfan.learnset.airslash;
		this.modData('Learnsets', 'rotomfan').learnset.airslash = null;
		this.modData('Learnsets', 'mantine').learnset.roost = ['6T'];
		this.modData('Learnsets', 'pidgeot').learnset.focusblast = ['6T'];
		this.modData('Pokedex', 'granbull').abilities['1'] = 'Fur Coat';
		this.modData('Pokedex', 'aggronmega').types = ['Steel', 'Dragon'];
		this.modData('Learnsets', 'floatzel').learnset.bellydrum = ['6T'];
		this.modData('Pokedex', 'forretress').abilities['1'] = 'Water Absorb';
		this.modData('Learnsets', 'bronzong').learnset.recover = ['6T'];
		this.modData('Learnsets', 'sandslash').learnset.thousandarrows = ['6T'];
	}
};
<|endoftext|>


<commit_before>//Copyright (c) 2014 US Ignite
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software
//and/or hardware specification (the Work) to deal in the Work without restriction, including
//without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
//sell copies of the Work, and to permit persons to whom the Work 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 Work.
//
//THE WORK 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 WORK OR THE USE OR OTHER DEALINGS
//IN THE WORK.
module.exports = function (app, passport, Users, Slices, urls, url, script_dir) {
    var route_utils = require('./route_utils');
    require('./admin')(app, route_utils, Users, Slices, url, script_dir);
    require('./auth')(app, passport);
    require('./main')(app);
    require('./slice')(app, route_utils, urls, url, Users, Slices, script_dir);
    require('./user')(app, utils, Users, Slices, urls, script_dir);
}<commit_msg>fixed typo<commit_after>//Copyright (c) 2014 US Ignite
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software
//and/or hardware specification (the Work) to deal in the Work without restriction, including
//without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
//sell copies of the Work, and to permit persons to whom the Work 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 Work.
//
//THE WORK 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 WORK OR THE USE OR OTHER DEALINGS
//IN THE WORK.
module.exports = function (app, passport, Users, Slices, urls, url, script_dir) {
    var route_utils = require('./route_utils');
    require('./admin')(app, route_utils, Users, Slices, url, script_dir);
    require('./auth')(app, passport);
    require('./main')(app);
    require('./slice')(app, route_utils, urls, url, Users, Slices, script_dir);
    require('./user')(app, route_utils, Users, Slices, urls, script_dir);
}<|endoftext|>


<commit_before>(function(Storm, _, _window, _document, undefined) {

		/**
		 * Stores created apps
		 * @type {Array}
		 */
	var _apps = [],
		/** @type {Storm.Events} */
		_observable = Storm.Events.construct(),
		/**
		 * Track if the document is ready
		 * @type {Boolean}
		 */
		_isDocReady = false,
		/**
		 * Whether all apps are locked
		 * @type {Boolean}
		 */
		_isLocked = false;

	// When document.ready trigger all registered apps to start
	_document.ready(function() {
		_isDocReady = true;
		_observable.trigger('document:ready');
	});
	// On unload, trigger unload on the apps
	_window.on('beforeunload', function() {
		_observable.trigger('window:unload');
	});

	var _runChecks = function() {
		_.each(_apps, function(app) {
			app._check();
		});
	};

	/**
	 * Centralized start point for an application and
	 * allows multiple, separate apps to run side-by-side.
	 * Also reduces bindings to the DOM on window load/unload
	 * and document ready.
	 * @class App
	 */
	var App = Storm.Module.extend(function() {
		_apps.push(this);

		/**
		 * Holds the configuration for this app
		 * @type {Object}
		 */
		this.config = {};

		/**
		 * Holds the setup calls
		 * @type {Array[Function]}
		 */
		this.setupCalls = [];

		/**
		 * Holds the end call
		 * @type {Function}
		 */
		this.endCall = null; // Only one end call

		/**
		 * Holds the start call
		 * @type {Function}
		 */
		this.startCall = null;

		/**
		 * Track whether the app has been initialized.
		 * Need to know so that an unload call is not executed
		 * on an app that never loaded
		 * @type {Boolean}
		 */
		this._hasInitialized = false;

		/**
		 * @type {Boolean}
		 */
		this._isIgnited = false;

		this._initialize = _.once(_.bind(this._initialize, this)); // Initialize only once
		this._unload = _.once(_.bind(this._unload, this)); // Unload only once

		this._bindAutoStart();
		this._bindAutoEnd();

	}, {
		_check: function() {
			if (_isLocked) { return; }
			if (this._isIgnited || _isDocReady) { this._initialize(); }
		},

		/**
		 * By default, the app will startup on document.ready
		 * @type {Boolean}
		 */
		autoStart: true,

		/**
		 * Bind the autostart events
		 * @private
		 */
		_bindAutoStart: function() {
			if (!this.autoStart) { return; }

			if (_isDocReady) {
				return this._check();
			}

			_observable.on('document:ready', _.bind(this._check, this));
		},

		/**
		 * By default, the app will end on window beforeunload
		 * @type {Boolean}
		 */
		autoEnd: true,

		/**
		 * Bind the autoend events
		 * @private
		 */
		_bindAutoEnd: function() {
			if (!this.autoEnd) { return; }
			_observable.on('window:unload', _.bind(this._unload, this));
		},

		/**
		 * A configuration object or key, value pair
		 * that will extend this apps' configuration
		 * @param  {String || Object} key
		 * @param  {Value}  value
		 * @return {App}
		 */
		configure: function(key, value) {
			if (!_.isString(key)) {
				_.extend(this.config, key);
				return this;
			}

			this.config[key] = value;
			return this;
		},

		/**
		 * A setup function to run before the app starts.
		 * This function will still wait until document.ready
		 * to execute.
		 * @param  {Function} func
		 * @return {App}
		 */
		setup: function(func) {
			if (!_.isFunction(func)) { console.error('Setup must have a function.'); }
			this.setupCalls.push(func);
			return this;
		},

		/**
		 * Function that executes when the app starts
		 * @param  {Function} func
		 * @return {App}
		 */
		start: function(func) {
			if (!_.isFunction(func)) { console.error('Start must have a function.'); }
			this.startCall = func;
			return this;
		},

		/**
		 * Function that executes when the app ends
		 * @param  {Function} func
		 * @return {App}
		 */
		end: function(func) {
			if (!_.isFunction(func)) { console.error('End must have a function.'); }
			this.endCall = func;
			return this;
		},

		/**
		 * The app can be started manually without waiting
		 * for the document ready.
		 * @return {App}
		 */
		ignite: function() {
			this._isIgnited = true;
			this._check();
			return this;
		},

		/**
		 * The app can be unloaded manually without waiting
		 * for a window unload event.
		 * @return {App}
		 */
		smother: function(opts) {
			if (!this._hasInitialized) { return this; }

			opts = opts || {};
			if (!opts.isSilent) { this._unload(); }

			return this;
		},

		/**
		 * Initialize. If no startCall is present, create one
		 * so that the app can continue
		 * @private
		 */
		_initialize: function() {
			this.startCall = this.startCall || function() {};

			this._hasInitialized = true;

			this.trigger('setup:before', this.config);

			this._callSetup();

			this.trigger('setup:after', this.config);

			this.trigger('start:before', this.config);

			this._callStart();

			this.trigger('start:after', this.config);
		},

		/**
		 * Call all setup functions
		 * Clear the setup functions after their
		 * executed to keep them from being executed again
		 * @private
		 */
		_callSetup: function() {
			// Call the functions in the order
			// they were registered
			var idx = 0, length = this.setupCalls.length;
			for (; idx < length; idx++) {
				this.setupCalls[idx].call(null, this.config);
			}
			// After setup calls are made, clear the calls
			// so that they're not called again
			this.setupCalls.length = 0;
		},

		/**
		 * Call start and trigger events.
		 * Nullify the start call after it's executed
		 * to keep it from being executed again
		 * @private
		 */
		_callStart: function() {
			this.startCall.call(null, this.config);
			this.startCall = null;
		},

		/**
		 * Unload
		 * @private
		 */
		_unload: function() {
			// Never initialized, don't unload
			if (!this._hasInitialized) { return; }

			if (this.endCall) { this.endCall.call(null, this, this.config); }
			this.trigger('end');
		}
	});

	App.lock = function() {
		_isLocked = true;
	};

	App.unlock = function() {
		_isLocked = false;
		_runChecks();
	};

	Storm.mixin({
		apps: _apps,
		app: new App() // A base starting point for the application
		App: App
	});

}(Storm, _, $(window), $(document)));<commit_msg>Fixed syntax error - missing comma<commit_after>(function(Storm, _, _window, _document, undefined) {

		/**
		 * Stores created apps
		 * @type {Array}
		 */
	var _apps = [],
		/** @type {Storm.Events} */
		_observable = Storm.Events.construct(),
		/**
		 * Track if the document is ready
		 * @type {Boolean}
		 */
		_isDocReady = false,
		/**
		 * Whether all apps are locked
		 * @type {Boolean}
		 */
		_isLocked = false;

	// When document.ready trigger all registered apps to start
	_document.ready(function() {
		_isDocReady = true;
		_observable.trigger('document:ready');
	});
	// On unload, trigger unload on the apps
	_window.on('beforeunload', function() {
		_observable.trigger('window:unload');
	});

	var _runChecks = function() {
		_.each(_apps, function(app) {
			app._check();
		});
	};

	/**
	 * Centralized start point for an application and
	 * allows multiple, separate apps to run side-by-side.
	 * Also reduces bindings to the DOM on window load/unload
	 * and document ready.
	 * @class App
	 */
	var App = Storm.Module.extend(function() {
		_apps.push(this);

		/**
		 * Holds the configuration for this app
		 * @type {Object}
		 */
		this.config = {};

		/**
		 * Holds the setup calls
		 * @type {Array[Function]}
		 */
		this.setupCalls = [];

		/**
		 * Holds the end call
		 * @type {Function}
		 */
		this.endCall = null; // Only one end call

		/**
		 * Holds the start call
		 * @type {Function}
		 */
		this.startCall = null;

		/**
		 * Track whether the app has been initialized.
		 * Need to know so that an unload call is not executed
		 * on an app that never loaded
		 * @type {Boolean}
		 */
		this._hasInitialized = false;

		/**
		 * @type {Boolean}
		 */
		this._isIgnited = false;

		this._initialize = _.once(_.bind(this._initialize, this)); // Initialize only once
		this._unload = _.once(_.bind(this._unload, this)); // Unload only once

		this._bindAutoStart();
		this._bindAutoEnd();

	}, {
		_check: function() {
			if (_isLocked) { return; }
			if (this._isIgnited || _isDocReady) { this._initialize(); }
		},

		/**
		 * By default, the app will startup on document.ready
		 * @type {Boolean}
		 */
		autoStart: true,

		/**
		 * Bind the autostart events
		 * @private
		 */
		_bindAutoStart: function() {
			if (!this.autoStart) { return; }

			if (_isDocReady) {
				return this._check();
			}

			_observable.on('document:ready', _.bind(this._check, this));
		},

		/**
		 * By default, the app will end on window beforeunload
		 * @type {Boolean}
		 */
		autoEnd: true,

		/**
		 * Bind the autoend events
		 * @private
		 */
		_bindAutoEnd: function() {
			if (!this.autoEnd) { return; }
			_observable.on('window:unload', _.bind(this._unload, this));
		},

		/**
		 * A configuration object or key, value pair
		 * that will extend this apps' configuration
		 * @param  {String || Object} key
		 * @param  {Value}  value
		 * @return {App}
		 */
		configure: function(key, value) {
			if (!_.isString(key)) {
				_.extend(this.config, key);
				return this;
			}

			this.config[key] = value;
			return this;
		},

		/**
		 * A setup function to run before the app starts.
		 * This function will still wait until document.ready
		 * to execute.
		 * @param  {Function} func
		 * @return {App}
		 */
		setup: function(func) {
			if (!_.isFunction(func)) { console.error('Setup must have a function.'); }
			this.setupCalls.push(func);
			return this;
		},

		/**
		 * Function that executes when the app starts
		 * @param  {Function} func
		 * @return {App}
		 */
		start: function(func) {
			if (!_.isFunction(func)) { console.error('Start must have a function.'); }
			this.startCall = func;
			return this;
		},

		/**
		 * Function that executes when the app ends
		 * @param  {Function} func
		 * @return {App}
		 */
		end: function(func) {
			if (!_.isFunction(func)) { console.error('End must have a function.'); }
			this.endCall = func;
			return this;
		},

		/**
		 * The app can be started manually without waiting
		 * for the document ready.
		 * @return {App}
		 */
		ignite: function() {
			this._isIgnited = true;
			this._check();
			return this;
		},

		/**
		 * The app can be unloaded manually without waiting
		 * for a window unload event.
		 * @return {App}
		 */
		smother: function(opts) {
			if (!this._hasInitialized) { return this; }

			opts = opts || {};
			if (!opts.isSilent) { this._unload(); }

			return this;
		},

		/**
		 * Initialize. If no startCall is present, create one
		 * so that the app can continue
		 * @private
		 */
		_initialize: function() {
			this.startCall = this.startCall || function() {};

			this._hasInitialized = true;

			this.trigger('setup:before', this.config);

			this._callSetup();

			this.trigger('setup:after', this.config);

			this.trigger('start:before', this.config);

			this._callStart();

			this.trigger('start:after', this.config);
		},

		/**
		 * Call all setup functions
		 * Clear the setup functions after their
		 * executed to keep them from being executed again
		 * @private
		 */
		_callSetup: function() {
			// Call the functions in the order
			// they were registered
			var idx = 0, length = this.setupCalls.length;
			for (; idx < length; idx++) {
				this.setupCalls[idx].call(null, this.config);
			}
			// After setup calls are made, clear the calls
			// so that they're not called again
			this.setupCalls.length = 0;
		},

		/**
		 * Call start and trigger events.
		 * Nullify the start call after it's executed
		 * to keep it from being executed again
		 * @private
		 */
		_callStart: function() {
			this.startCall.call(null, this.config);
			this.startCall = null;
		},

		/**
		 * Unload
		 * @private
		 */
		_unload: function() {
			// Never initialized, don't unload
			if (!this._hasInitialized) { return; }

			if (this.endCall) { this.endCall.call(null, this, this.config); }
			this.trigger('end');
		}
	});

	App.lock = function() {
		_isLocked = true;
	};

	App.unlock = function() {
		_isLocked = false;
		_runChecks();
	};

	Storm.mixin({
		apps: _apps,
		app: new App(), // A base starting point for the application
		App: App
	});

}(Storm, _, $(window), $(document)));
<|endoftext|>


<commit_before>self.addEventListener('message', function(e) {
  self.postMessage({
    code: e.data,
    result: JSON.stringify(eval(e.data))
  });
});

function help() {
  var result = 'You can use these different fonctions : \n';
  result += 'age()\n';
  result += 'location()\n';

  return result;
}

function age() {
  var diff =  new Date() - new Date(1992, 3, 9);
  diff = diff / (1000 * 60 * 60 * 24 * 31 * 12); // number of milliseconds in a year

  return 'I am ' + Math.round(diff) + ' years old';
}

function location() {
  return 'I am living in London, UK';
}<commit_msg>Add different fonctions in the shell to play with it<commit_after>self.addEventListener('message', function(e) {
  self.postMessage(JSON.stringify(eval(e.data)));
});

function help() {
  self.postMessage('//You can use these different fonctions');
  self.postMessage('');
  self.postMessage(' profileHelp()  // Show functions around my profile');
  self.postMessage(' socialHelp()  // Show functions around my social activity');
  self.postMessage('');
}

function profileHelp() {
  self.postMessage('//You can use these different methods');
  self.postMessage('');
  self.postMessage(' profile.name()  // Show my name');
  self.postMessage(' profile.eyes()  // Show the color of my eyes');
  self.postMessage(' profile.age()  // Show my age');
  self.postMessage(' profile.sports()  // Show the sports I play');
  self.postMessage(' profile.location()  // Show my current location');
  self.postMessage(' profile.nationalities()  // Show my nationalities');
  self.postMessage(' profile.languages()  // Show the languages that I can speak');
  self.postMessage(' profile.countries()  // Show the countries that I visited');
  self.postMessage(' profile.series()  // Show the series that I watch(ed)');
  self.postMessage(' profile.kdramas()  // Show the Korean series that I watch(ed)');
  self.postMessage(' profile.jdramas()  // Show the Japanese series that I watch(ed)');
  self.postMessage(' profile.jdramas()  // Show the mangas that I watch(ed)/read');
  self.postMessage('');
}

var profile = {
  name: function name() {
    return 'Yacine Rezgui';
  },

  eyes: function languages() {
    return 'brown eyes';
  },

  age: function age() {
    var diff =  new Date() - new Date(1992, 3, 9);
    diff = diff / (1000 * 60 * 60 * 24 * 31 * 12); // number of milliseconds in a year

    return 'I am ' + Math.round(diff) + ' years old';
  },

  sports: function languages() {
    return ['football', 'biking', 'climbing', 'swimming'];
  },

  location: function location() {
    return 'I am living in London, UK';
  },

  nationalities: function nationalities() {
    return ['french', 'tunisian'];
  },

  languages: function languages() {
    return ['french', 'english', 'arabic'];
  },

  countries: function countries() {
    return ['France', 'United Kingdom', 'Tunisia', 'Morocco', 'Switzerland', 'Belgium', 'Italy'];
  },

  series: function series() {
    return ['24', 'Heroes', 'The Mentalist', 'Fringe', 'Game of Thrones', 'The Following', 'Continuum', 'The Big Bang Theory'];
  },

  kdramas: function kdramas() {
    return ['City Hunter', 'Secret Garden', 'Full House', 'Answer me 1997', 'You\'re All Surrounded', 'Love from another star', 'The Cyrano Agency', 'Cheongdam-dong Alice', 'Three days', 'I hear your voice', 'That Winter, the Wind Blows'];
  },

  jdramas: function jdramas() {
    return ['Unubore Deka', 'My boss, my Hero', 'GTO', 'Hana Yori Dango', 'Tiger & Dragon', 'Densha Otoko', 'Yama Onna Kabe Onna', 'Gokusen'];
  },

  mangas: function mangas() {
    return ['Dragon Ball Z', 'Captain Tsubasa', 'GTO', 'Naruto', 'Bleach', 'One Piece', 'School Rumble', 'Negima', 'Suzuka'];
  }
};

function socialHelp() {
  self.postMessage('//You can use these different methods');
  self.postMessage('');
  self.postMessage(' social.twitter()  // Show my twitter account');
  self.postMessage(' social.github()  // Show my Github account');
  self.postMessage(' social.googlePlus()  // Show my Google+ account');
  self.postMessage(' social.linkedin()  // Show my LinkedIn account');
  self.postMessage(' social.medium()  // Show my Medium account');
  self.postMessage(' social.oldBlog()  // Show my old blog (on Tumblr)');
  self.postMessage('');
}

var social = {
  twitter: function twitter() {
    return 'http://twitter.com/yrezgui';
  },

  github: function github() {
    return 'https://github.com/yrezgui';
  },

  googlePlus: function googlePlus() {
    return 'http://google.com/+YacineRezgui';
  },

  linkedin: function linkedin() {
    return 'http://www.linkedin.com/in/yrezgui/en';
  },

  medium: function medium() {
    return 'https://medium.com/@yrezgui';
  },

  oldBlog: function oldBlog() {
    return 'http://blog.yrezgui.com/';
  }
};<|endoftext|>


<commit_before>
/**
 * Structure class consists of general attributes of a structure:
 * name, size, foundingYear, structureType, and productionInput,
 * and the function that calculates the value for production efficiency
 * (production unit / time period).
 */
export default class Structure {
  /**
   * tile, name, size, and structureType are given to the constructor as parameters.
   * the initial value of productionInput is 0.
   * @param {ModelTile} param.tile
   * @param {string} param.name
   * @param {integer} param.size
   * @param {StructureType} param.structureType
   * @param {integer} foundingYear
   * @param {function} produceFn
   */
  constructor ({ tile, health, healthManager, ownerName, structureName, size, structureType, foundingYear, producer }) {
    this.tile = tile

    this.health = health
    this.healthManager = healthManager
    this.producer = producer

    this.ownerName = ownerName
    this.structureName = structureName
    this.size = size
    this.structureType = structureType
    this.foundingYear = foundingYear

    this.ownedTiles = []
    this.radiusForTileOwnership = structureType.radiusForTileOwnership
  }

  /**
   * Returns true if the structure produces throughout the year and false if
   * only during harvesting periods.
   */
  hasContinuousProduction () {
    return this.structureType.continuousProduction
  }

  /**
   * Returns the asset of the structure type
   */
  asset () {
    return this.structureType.asset
  }

  turnipProduction () {
    return this.lastProduce
  }

  /**
   * Returns the amount of turnips produced by this structure
   * @param {TimeEvent} timeEvent - Current ingame date
   * @return {number} - Turnips produced
   */
  produce (timeEvent) {
    this.lastProduce = this.producer === undefined ? 0 : this.producer.produce(timeEvent)
    return this.lastProduce
  }
}
<commit_msg>removed structure.js from root folder<commit_after><|endoftext|>