<commit_before>'use strict';

let	gutil= require('gulp-util'),
	express = require('express'),
  	http = require('http'),
  	bodyParser= require('body-parser'),
  	path= require('path'),
  	utils= require('./utils');

// Set the gulp object in the constructor
// Then call the registerTasks methods to register these tasks on gulp
// Allow to register server tasks
class ServerHelper{

	constructor(gulp){
		this.gulp= gulp;
	}

	// Define the server object which searches for files into
	// node_modules and trainingapp
	run(){

		var appServer= express()
		    .get('/', function(req, res){
		    	res.sendFile('index.html', {root: utils.appFolder});
		    })
		    .use(bodyParser.json())
		    .use(express.static(utils.baseProject + '/' + utils.appFolder))
		    .use(express.static(utils.baseProject + '/node_modules'));

		return http.createServer(appServer);

	}

	registerTasks(){

		let gulp= this.gulp;
		let server= this.run();

		// Define the express task which runs the express http server
		gulp.task('express', function(cb){
		  let port= 8080;
		  server.listen(port, function(){
		    gutil.log(`server listening on ${port}`);
		    cb();
		  });
		});

	}

};

module.exports= ServerHelper;<commit_msg>Change Port Number<commit_after>'use strict';

let	gutil= require('gulp-util'),
	express = require('express'),
  	http = require('http'),
  	bodyParser= require('body-parser'),
  	path= require('path'),
  	utils= require('./utils');

// Set the gulp object in the constructor
// Then call the registerTasks methods to register these tasks on gulp
// Allow to register server tasks
class ServerHelper{

	constructor(gulp){
		this.gulp= gulp;
	}

	// Define the server object which searches for files into
	// node_modules and trainingapp
	run(){

		var appServer= express()
		    .get('/', function(req, res){
		    	res.sendFile('index.html', {root: utils.appFolder});
		    })
		    .use(bodyParser.json())
		    .use(express.static(utils.baseProject + '/' + utils.appFolder))
		    .use(express.static(utils.baseProject + '/node_modules'));

		return http.createServer(appServer);

	}

	registerTasks(){

		let gulp= this.gulp;
		let server= this.run();

		// Define the express task which runs the express http server
		gulp.task('express', function(cb){
		  let port= 8081;
		  server.listen(port, function(){
		    gutil.log(`server listening on ${port}`);
		    cb();
		  });
		});

	}

};

module.exports= ServerHelper;<|endoftext|>


<commit_before>/* global BookReader, BookReaderJSIAinit */
import { extraVolOptions, custvolumesManifest } from './ia-multiple-volumes-manifest.js';

/**
 * This is how Internet Archive loads bookreader
 */
const urlParams = new URLSearchParams(window.location.search);

const ocaid = urlParams.get('ocaid');
const openFullImmersionTheater = urlParams.get('view') === 'theater';
const ui = urlParams.get('ui');
const autoflip = urlParams.get('autoflip');
const searchTerm = urlParams.get('q');

const iaBookReader = document.querySelector('ia-bookreader');

const downloadListWithLCP = [
  [
    "lcpPDF",
    "link to lcp pdf"
  ],
  [
    "lcpEPUB",
    "link to lcp epub"
  ]
];

if (openFullImmersionTheater) {
  $(document.body).addClass('BRfullscreenActive');
  iaBookReader.fullscreen = openFullImmersionTheater;
}

const modal = document.querySelector('modal-manager');
iaBookReader.modal = modal;

// Override options coming from IA
BookReader.optionOverrides.imagesBaseURL = '/BookReader/images/';

const initializeBookReader = (brManifest) => {
  console.log('initializeBookReader', brManifest);
  const br = new BookReader();

  const customAutoflipParams = {
    autoflip: !!autoflip,
    flipSpeed: urlParams.flipSpeed || 2000,
    flipDelay: urlParams.flipDelay || 5000
  };

  const options = {
    el: '#BookReader',
    /* Url plugin - IA uses History mode for URL */
    // commenting these out as demo uses hash mode
    // keeping them here for reference
    // urlHistoryBasePath: `/details/{$ocaid}/`,
    // resumeCookiePath: `/details/{$ocaid}/`,
    // urlMode: 'history',
    // Only reflect these params onto the URL
    // urlTrackedParams: ['page', 'search', 'mode'],
    /* End url plugin */
    enableBookTitleLink: false,
    bookUrlText: null,
    startFullscreen: openFullImmersionTheater,
    initialSearchTerm: searchTerm ? searchTerm : '',
    // leaving this option commented out bc we change given user agent on archive.org
    // onePage: { autofit: <?=json_encode($this->ios ? 'width' : 'auto')?> },
    showToolbar: false,
    /* Multiple volumes */
    // To show multiple volumes:
    enableMultipleBooks: false, // turn this on
    multipleBooksList: [], // populate this  // TODO: get sample blob and tie into demo
    /* End multiple volumes */
    enableBookmarks: true, // turn this on
    enableFSLogoShortcut: true,
  };

  // we want to show item as embedded when ?ui=embed is in URI
  if (ui === 'embed') {
    options.mode = 1;
    options.ui = 'embed';
  }

  // we expect this at the global level
  BookReaderJSIAinit(brManifest.data, options);

  if (customAutoflipParams.autoflip) {
    br.autoToggle(customAutoflipParams);
  }
};

window.initializeBookReader = initializeBookReader;

const showLCP = document.querySelector('#show-lcp');
showLCP.addEventListener('click', async () => {
  const iaBr = document.querySelector('ia-bookreader');
  const bookNav = iaBr.shadowRoot.querySelector('book-navigator');

  bookNav.downloadableTypes = downloadListWithLCP;

  bookNav.updateMenuContents();
  await bookNav.updateComplete;
});

const multiVolume = document.querySelector('#multi-volume');
multiVolume.addEventListener('click', () => {
  // remove everything
  $('#BookReader').empty();
  delete window.br;
  // and re-mount with a new book
  BookReaderJSIAinit(custvolumesManifest, extraVolOptions);
});

const fetchBookManifestAndInitializeBookreader = async (iaMetadata) => {
  document.querySelector('input[name="itemMD"]').checked = true;
  iaBookReader.item = iaMetadata;

  const {
    metadata: {
      identifier
    },
  } = iaMetadata;

  const locator = `https://archive.org/bookreader/BookReaderJSLocate.php?format=json&subPrefix=&id=${identifier}`;
  // Todo: move from `locator` to create `iaManifestUrl` url from `iaMetadata`
  // so we can support multiple volumes
  // const iaManifestUrl = `https://${server}/BookReader/BookReaderJSIA.php?format=jsonp&itemPath=${dir}&id=${identifier}`;

  const manifest = await fetch(locator)
    .then(response => response.json());
  document.querySelector('input[name="bookManifest"]').checked = true;

  initializeBookReader(manifest);
};

// Temp; Circumvent bug in BookReaderJSIA code
window.Sentry = null;
window.logError = function(e) {
  console.error(e);
};
fetch(`https://archive.org/metadata/${ocaid}`)
  .then(response => response.json())
  .then(iaMetadata => fetchBookManifestAndInitializeBookreader(iaMetadata));
<commit_msg>Replace BRJSLocate with direct BookReaderJSIA.php call<commit_after>/* global BookReader, BookReaderJSIAinit */
import { extraVolOptions, custvolumesManifest } from './ia-multiple-volumes-manifest.js';

/**
 * This is how Internet Archive loads bookreader
 */
const urlParams = new URLSearchParams(window.location.search);

const ocaid = urlParams.get('ocaid');
const openFullImmersionTheater = urlParams.get('view') === 'theater';
const ui = urlParams.get('ui');
const autoflip = urlParams.get('autoflip');
const searchTerm = urlParams.get('q');

const iaBookReader = document.querySelector('ia-bookreader');

const downloadListWithLCP = [
  [
    "lcpPDF",
    "link to lcp pdf"
  ],
  [
    "lcpEPUB",
    "link to lcp epub"
  ]
];

if (openFullImmersionTheater) {
  $(document.body).addClass('BRfullscreenActive');
  iaBookReader.fullscreen = openFullImmersionTheater;
}

const modal = document.querySelector('modal-manager');
iaBookReader.modal = modal;

// Override options coming from IA
BookReader.optionOverrides.imagesBaseURL = '/BookReader/images/';

const initializeBookReader = (brManifest) => {
  console.log('initializeBookReader', brManifest);
  const br = new BookReader();

  const customAutoflipParams = {
    autoflip: !!autoflip,
    flipSpeed: urlParams.flipSpeed || 2000,
    flipDelay: urlParams.flipDelay || 5000
  };

  const options = {
    el: '#BookReader',
    /* Url plugin - IA uses History mode for URL */
    // commenting these out as demo uses hash mode
    // keeping them here for reference
    // urlHistoryBasePath: `/details/{$ocaid}/`,
    // resumeCookiePath: `/details/{$ocaid}/`,
    // urlMode: 'history',
    // Only reflect these params onto the URL
    // urlTrackedParams: ['page', 'search', 'mode'],
    /* End url plugin */
    enableBookTitleLink: false,
    bookUrlText: null,
    startFullscreen: openFullImmersionTheater,
    initialSearchTerm: searchTerm ? searchTerm : '',
    // leaving this option commented out bc we change given user agent on archive.org
    // onePage: { autofit: <?=json_encode($this->ios ? 'width' : 'auto')?> },
    showToolbar: false,
    /* Multiple volumes */
    // To show multiple volumes:
    enableMultipleBooks: false, // turn this on
    multipleBooksList: [], // populate this  // TODO: get sample blob and tie into demo
    /* End multiple volumes */
    enableBookmarks: true, // turn this on
    enableFSLogoShortcut: true,
  };

  // we want to show item as embedded when ?ui=embed is in URI
  if (ui === 'embed') {
    options.mode = 1;
    options.ui = 'embed';
  }

  // we expect this at the global level
  BookReaderJSIAinit(brManifest.data, options);

  if (customAutoflipParams.autoflip) {
    br.autoToggle(customAutoflipParams);
  }
};

window.initializeBookReader = initializeBookReader;

const showLCP = document.querySelector('#show-lcp');
showLCP.addEventListener('click', async () => {
  const iaBr = document.querySelector('ia-bookreader');
  const bookNav = iaBr.shadowRoot.querySelector('book-navigator');

  bookNav.downloadableTypes = downloadListWithLCP;

  bookNav.updateMenuContents();
  await bookNav.updateComplete;
});

const multiVolume = document.querySelector('#multi-volume');
multiVolume.addEventListener('click', () => {
  // remove everything
  $('#BookReader').empty();
  delete window.br;
  // and re-mount with a new book
  BookReaderJSIAinit(custvolumesManifest, extraVolOptions);
});

const fetchBookManifestAndInitializeBookreader = async (iaMetadata) => {
  document.querySelector('input[name="itemMD"]').checked = true;
  iaBookReader.item = iaMetadata;

  const jsiaParams = {
    format: 'jsonp',
    itemPath: iaMetadata.dir,
    id: iaMetadata.metadata.identifier,
    server: iaMetadata.server,
  };

  const jp2File = iaMetadata.files.find(f => f.name.endsWith('_jp2.zip'))
  if (jp2File) {
    jsiaParams.subPrefix = jp2File.name.replace('_jp2.zip', '');
  }

  const iaManifestUrl = `https://${iaMetadata.server}/BookReader/BookReaderJSIA.php?${
    new URLSearchParams(jsiaParams)
  }`;

  const manifest = await fetch(iaManifestUrl).then(response => response.json());
  document.querySelector('input[name="bookManifest"]').checked = true;

  initializeBookReader(manifest);
};

// Temp; Circumvent bug in BookReaderJSIA code
window.Sentry = null;
window.logError = function(e) {
  console.error(e);
};
fetch(`https://archive.org/metadata/${ocaid}`)
  .then(response => response.json())
  .then(iaMetadata => fetchBookManifestAndInitializeBookreader(iaMetadata));
<|endoftext|>


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

const path = require("path")

const PATHS = {
  app: path.join(__dirname, 'src/index.jsx'),
}

module.exports = {
  entry: {
    app: PATHS.app,
  },
  output: {
    path: __dirname + '/dist',
    filename: 'bundle.js',
  },
  mode: 'production',
  module: {
    rules: [
      {
        test: /\.(js|jsx|ts|tsx)$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        include: /src/
      }
    ],
  },
  resolve: {
    extensions: [".tsx", ".ts", ".jsx", ".js"]
  },
}<commit_msg>adding css to prod build<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2020 Looker Data Sciences, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

const path = require("path");

const PATHS = {
  app: path.join(__dirname, "src/index.jsx"),
};

module.exports = {
  entry: {
    app: PATHS.app,
  },
  output: {
    path: __dirname + "/dist",
    filename: "bundle.js",
  },
  mode: "production",
  module: {
    rules: [
      {
        test: /\.(js|jsx|ts|tsx)$/,
        loader: "babel-loader",
        exclude: /node_modules/,
        include: /src/,
      },
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
  resolve: {
    extensions: [".tsx", ".ts", ".jsx", ".js"],
  },
};
<|endoftext|>


<commit_before>'use strict';

var chai = require('chai');
var expect = chai.expect;

var MockWritableStream = require('../../lib/mockWritableStream');
var mockWritableStream;

describe('mockWritableStream', function() {

  before(function() {
    mockWritableStream = new MockWritableStream();
  });

  it('should be a function', function() {
    expect(MockWritableStream).to.be.a('function');
  });

  it('should be an object factory', function() {
    expect(mockWritableStream).to.be.a('object');
    expect(mockWritableStream).to.be.an.instanceof(MockWritableStream);
  });

  it('should expose "MockWritableStream" prototype', function() {
    expect(mockWritableStream).to.have.property('writable');
    expect(mockWritableStream.writable).to.be.a('function');

    expect(mockWritableStream).to.have.property('end');
    expect(mockWritableStream.end).to.be.a('function');

    expect(mockWritableStream).to.have.property('destroy');
    expect(mockWritableStream.destroy).to.be.a('function');

    expect(mockWritableStream).to.have.property('destroySoon');
    expect(mockWritableStream.destroySoon).to.be.a('function');
  });

  it('should return undefined when methods called', function() {
    expect(mockWritableStream.writable()).to.be.undefined;
    expect(mockWritableStream.end()).to.be.undefined;
    expect(mockWritableStream.destroy()).to.be.undefined;
    expect(mockWritableStream.destroySoon()).to.be.undefined;
  });

});
<commit_msg>updated; unit test to reflect updates in WritableStream<commit_after>'use strict';

var chai = require('chai');
var expect = chai.expect;

var MockWritableStream = require('../../lib/mockWritableStream');
var mockWritableStream;

describe('mockWritableStream', function() {

  before(function() {
    mockWritableStream = new MockWritableStream();
  });

  it('should be a function', function() {
    expect(MockWritableStream).to.be.a('function');
  });

  it('should be an object factory', function() {
    expect(mockWritableStream).to.be.a('object');
    expect(mockWritableStream).to.be.an.instanceof(MockWritableStream);
  });

  it('should expose "MockWritableStream" prototype', function() {
    expect(mockWritableStream).to.have.property('end');
    expect(mockWritableStream.end).to.be.a('function');

    expect(mockWritableStream).to.have.property('destroy');
    expect(mockWritableStream.destroy).to.be.a('function');

    expect(mockWritableStream).to.have.property('destroySoon');
    expect(mockWritableStream.destroySoon).to.be.a('function');
  });

  it('should return undefined when methods called', function() {
    expect(mockWritableStream.end()).to.be.undefined;
    expect(mockWritableStream.destroy()).to.be.undefined;
    expect(mockWritableStream.destroySoon()).to.be.undefined;
  });

});
<|endoftext|>


<commit_before>//:: ((a, b) -> c) -> a -> b -> c
export const curry = (fn, ...args) => {
  const c = (fnArgs) => {
    if (fnArgs.length >= fn.length) {
      return fn.apply(this, fnArgs);
    }
    return (...cArgs) => c([...fnArgs, ...cArgs]);
  };
  return c(args);
};

//:: ([a] -> b?, [a]) -> b?
export const apply = curry((fn, args) => fn.apply(null, args));

//:: (a -> b -> c) -> b -> a -> c
export const flip = curry((fn, x, y) => fn(y, x));

//:: Function -> Function
export const fix = (f) =>
  ((g) => (...args) => f(g(g)).apply(null, args))(
    (g) => (...args) => f(g(g)).apply(null, args)
  );

//:: (a -> b) -> a -> b
export const memoize = (fn) => {
  let memo = {};
  return (...args) => {
    const key = args.map((arg) => arg + typeof arg).join('');
    return memo[key] || (memo[key] = fn.apply(null, args));
  };
};

// (a -> b) -> !(a -> b)
export const negate = (fn) => (...args) => !fn.apply(null, args);

//:: ([a -> b?]) -> a -> b?
export const compose = (...fns) =>
  (...args) =>
    fns.reduceRight((memo, fn) => [fn.apply(this, memo)], args)[0];

// aliases

export const memoise = memoize;
<commit_msg>optimize Func.memoize<commit_after>//:: ((a, b) -> c) -> a -> b -> c
export const curry = (fn, ...args) => {
  const c = (fnArgs) => {
    if (fnArgs.length >= fn.length) {
      return fn.apply(this, fnArgs);
    }
    return (...cArgs) => c([...fnArgs, ...cArgs]);
  };
  return c(args);
};

//:: ([a] -> b?, [a]) -> b?
export const apply = curry((fn, args) => fn.apply(null, args));

//:: (a -> b -> c) -> b -> a -> c
export const flip = curry((fn, x, y) => fn(y, x));

//:: Function -> Function
export const fix = (f) =>
  ((g) => (...args) => f(g(g)).apply(null, args))(
    (g) => (...args) => f(g(g)).apply(null, args)
  );

//:: (a -> b) -> a -> b
export const memoize = (fn) => {
  let memo = {};
  return (...args) => {
    const key = args.map((arg) => arg + typeof arg).join('');
    return (key in memo) ? memo[key] : (memo[key] = fn.apply(null, args));
  };
};

// (a -> b) -> !(a -> b)
export const negate = (fn) => (...args) => !fn.apply(null, args);

//:: ([a -> b?]) -> a -> b?
export const compose = (...fns) =>
  (...args) =>
    fns.reduceRight((memo, fn) => [fn.apply(this, memo)], args)[0];

// aliases

export const memoise = memoize;
<|endoftext|>


<commit_before>$(function(){
    map = new GMaps({
        div: '#map',
        lat: -12.043333,
        lng: -77.028333,
        mapType: google.maps.MapTypeId.HYBRID,
        mapTypeControlOptions: {
            mapTypeIds : ["hybrid", "roadmap", "satellite", "terrain", "osm"]
        },
        rightclick: function(e) {
            lastRightClickedPoint = e.latLng;
        }
    });

    map.addMapType("osm", {
        getTileUrl: function(coord, zoom) {
            return "http://otile1.mqcdn.com/tiles/1.0.0/map/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
        },
        tileSize: new google.maps.Size(256, 256),
        name: "OpenStreetMap",
        maxZoom: 18
    });

    map.setContextMenu({
        control: 'map',
        options: [
            {
                title: 'Crear centro de votación aquí',
                name: 'agregar_lugar',
                action: function(e) {
                    var tr = $('tr.establecimiento.active');
                    var p_d = $('select#distrito option:selected').val().split('-');
                    var c = $('td', tr).map(function(d,e) { return e.innerHTML; });
                    if( $('tr.establecimiento.active + tr.matches td table tbody').length ) {
                      $('tr.establecimiento.active + tr.matches td table tbody').prepend(new_estab_tmpl({contents: c}));
                    }
                    else {
                      $('tr.establecimiento.active + tr.matches td table').prepend(new_estab_tmpl({contents: c}));
                    }
                    var place_data = {
                        nombre: c[0],
                        direccion: c[1],
                        localidad: c[2],
                        wkb_geometry_4326: 'SRID=4326;POINT(' + lastRightClickedPoint.lng() + ' ' + lastRightClickedPoint.lat() + ')',
                        distrito: p_d[0],
                        seccion: p_d[1]
                    };
                    $.post('/create',
                           place_data,
                           function(d) {
                               place_data['ogc_fid'] = d['ogc_fid'];
                               var new_tr = $('tr.establecimiento.active + tr.matches td table tr:first-child');
                               new_tr.data('place', place_data);
                               $('input[type=checkbox]', new_tr)
                                   .prop('checked', true)
                                   .trigger('change');
                           });
                }
            },
        ]
    });

    var table_tmpl = _.template($('#establecimientos-template').html());
    var matches_tmpl = _.template($('#matches-template').html());
    var infowindow_tmpl = _.template($('#infowindow-template').html());
    var completion_tmpl = _.template($('#completion-template').html());
    var new_estab_tmpl = _.template($('#new-establecimiento-template').html());

    var polygon = null;
    var markers = [];

    var maxZoomService = new google.maps.MaxZoomService();

    var currentBounds = null;
    var currentMarker = null;
    var currentPlace  = null;
    var currentSeccion = null;
    var currentDistrito = null;
    var lastRightClickedPoint = null;

    var updateCompletion = function() {
        $.get('/completion', function(provincias) {
            $('#provincia-ranking').html(completion_tmpl({provincias:provincias}));
        })
    };

    completionRankingInterval = window.setInterval(updateCompletion, 10000);
    updateCompletion();

    var addGeocomplete = function(selector) {
        $(selector)
            .geocomplete({ bounds: polygon.getBounds() })
            .bind("geocode:result", function(event, result) {
                if (!polygon.getBounds().contains(result.geometry.location))
                    // no salir de los bounds actuales si el geocoder
                    // retorna algo afuera de esos bounds
                    return;
                maxZoomService.getMaxZoomAtLatLng(result.geometry.location, function(r) {
                    if (r.status == google.maps.MaxZoomStatus.OK)
                        map.setZoom(r.zoom);
                    map.map.panTo(result.geometry.location);
                });

            });
    };

    $('select#distrito').on('change', function() {
        var p_d = $(this).val().split('-');
        var provincia = $(this).parent('optgroup').attr('label')
        history.pushState({foo: null}, "", "/" + p_d[0] + "/" + p_d[1]);
        $.get('/establecimientos/' + p_d.join('/'),
              function(data) {
                  $('table#establecimientos')
                      .html(table_tmpl({establecimientos: data, provincia: p_d[0] }));
              });

        map.removeMarkers(markers);
        markers = [];

        currentSeccion = p_d[1];
        currentDistrito = p_d[0];

        $.get('/seccion/' + p_d.join('/'), function(data) {
            currentBounds = data.bounds.coordinates[0].map(function(p) {
                return new google.maps.LatLng(p[1], p[0]);
            });
            map.fitLatLngBounds(currentBounds);

            if (polygon != null) map.removePolygon(polygon);

            polygon = map.drawPolygon({
                paths: data.geojson.coordinates,
                useGeoJSON: true,
                strokeOpacity: 0.2,
                strokeWeight: 1,
                strokeColor: '#ff0000',
                fillColor: '#BBD8E9',
                fillOpacity: 0.4,
                clickable: false
            });

            $('a#shapefile').attr('href', '/shape/' + p_d[0] + '/' + p_d[1]);

        });
    });

    var showMarker = function(e) {
        //console.log(e);
    };

    $(document).on({
      'click': function(e){
        e.preventDefault();
        var loc = $('input#latlng').val();
        var l_l = loc.split(',');
        var g = new google.maps.LatLng(l_l[0], l_l[1]);
        if (polygon.getBounds().contains(g)) {
          var tr = $('tr.establecimiento.active');
          var p_d = $('select#distrito option:selected').val().split('-');
          var c = $('td', tr).map(function(d,e) { return e.innerHTML; });
          if( $('tr.establecimiento.active + tr.matches td table tbody').length ) {
            $('tr.establecimiento.active + tr.matches td table tbody').prepend(new_estab_tmpl({contents: c}));
          }
          else {
            $('tr.establecimiento.active + tr.matches td table').prepend(new_estab_tmpl({contents: c}));
          }
          var place_data = {
            nombre: c[0],
            direccion: c[1],
            localidad: c[2],
            wkb_geometry_4326: 'SRID=4326;POINT(' + l_l[1].trim() + ' ' + l_l[0].trim() + ')',
            distrito: p_d[0],
            seccion: p_d[1]
          };
          $.post('/create',place_data,
               function(d) {
                   place_data['ogc_fid'] = d['ogc_fid'];
                   var new_tr = $('tr.establecimiento.active + tr.matches td table tr:first-child');
                   new_tr.data('place', place_data);
                   $('input[type=checkbox]', new_tr)
                       .prop('checked', true)
                       .trigger('change');
          });
          $('input#latlng').val("");
        }
        else {
          $('span#error').css('visibility', 'visible');
          $('input#latlng').val("");
          setTimeout(function(){$("span#error").css('visibility', 'hidden');}, 2000);
        }
        return false;
      }
    }, 'button#latlngBut')

    $(document).on({
        'click': function() {
            if (currentMarker) {
                currentMarker.infoWindow.close();
            }
            var d = $(this).data('place');
            currentPlace = d;
            currentMarker = _.find(map.markers, function(m) {
                return m.details == d;
            });
            // Simulate a click on the actual marker
            google.maps.event.trigger(currentMarker, 'click');
        },
        'dblclick': function() {
            maxZoomService.getMaxZoomAtLatLng(currentMarker.getPosition(), function(r) {
                if (r.status == google.maps.MaxZoomStatus.OK)
                    map.setZoom(r.zoom);
                map.map.panTo(currentMarker.getPosition());
            });
        }
    }, 'tr.matches tr')

    $(document).on({
        'change': function() { // checkbox to choose a match
            var chk = $(this);

            var establecimiento_tr = chk
                .parents('.matches')
                .prev();

            var establecimiento = establecimiento_tr
                .data('establecimiento-id');

            currentPlace = chk
                .parents('tr:not(.matches)')
                .data('place');

            var url = '/matches/' + establecimiento + '/' + currentPlace.ogc_fid;

            if (chk.is(':checked')) {
                //establecimiento_tr.removeClass('guessed');
                //establecimiento_tr.removeClass('wrong');
                establecimiento_tr.addClass('matched');
                $.post(url);
            }
            else { //delete
                establecimiento_tr.removeClass('matched');
                var url = '/matches/' + establecimiento;
                $.post(url, { _method: 'delete'});
            }
        },
    }, 'tr.matches tr input[type=checkbox]')

    $(document).on({
        'click': function(e) {
            var a = $(this);
            var t = a.data('searchType');
            var tr = a.parents('tr.matches');
            var prev = tr.prev();
            var eid = prev.data('establecimiento-id');
            var enombre = $('td:nth-child(1)', prev).html();
            var edireccion = $('td:nth-child(2)', prev).html();
            var elocalidad = $('td:nth-child(3)', prev).html();
            var elat = prev.data('lat');
            var elng = prev.data('lng');
            $.get('/places/' + currentDistrito + '/' + currentSeccion,
                  { // Add nombre and localidad to the mixture for the similarity
                    nombre: $('td:nth-child(1)', prev).html(),
                    direccion: $('td:nth-child(2)', prev).html(),
                    localidad: $('td:nth-child(3)', prev).html(),
                    search_type: t},
                  function(data) {
                      tr.remove();
                      prev.after(matches_tmpl({
                          matches: data,
                          seccion: '',
                          distrito: ''
                      }));
                      $('tr', prev.next()).each(function(i, t) {
                          $(this).data('place', data[i]);
                      });
                      map.removeMarkers(markers);
                      markers = []
                      if (elat != "") {
                        // Add current geoposition
                        var m = {
                          nombre: enombre,
                          direccion: edireccion,
                          desc_distrito: elocalidad
                        };
                        var emarker = map.addMarker({
                              lat: elat,
                              lng: elng,
                              details: m,
                              infoWindow: {
                                  content: infowindow_tmpl({place: m})
                              },
                              icon: '/static/polling.png'
                        });
                        markers.push(emarker);
                      }
                      data.forEach(function(m) {
                        if (m.score > 0.2) {
                            var marker = map.addMarker({
                                lat: m.geojson.coordinates[1],
                                lng: m.geojson.coordinates[0],
                                details: m,
                                infoWindow: {
                                    content: infowindow_tmpl({place: m})
                                },
                                click: showMarker,
                            });
                            markers.push(marker);
                        }
                        else {
                          //console.log(m.score)
                        }
                      });
                      if (markers.length > 0) map.fitZoom();
                      addGeocomplete($('input#geocomplete', $($(prev).next())));
                  });
            e.preventDefault();
            return false;
        }
    }, 'a.view-all-places')

    $(document).on(
        {
            // click en establecimiento, abre los matches
            'click': function() {
                $('tr', $(this).parent()).removeClass('active');
                $('tr.matches').remove();
                var tr = $(this);
                tr.addClass('active');
                var eid = tr.data('establecimiento-id');
                var enombre = $('td:nth-child(1)', tr).html();
                var edireccion = $('td:nth-child(2)', tr).html();
                var elocalidad = $('td:nth-child(3)', tr).html();
                var elat = tr.data('lat');
                var elng = tr.data('lng');
                $.get('/matches/' + eid,
                      function(data) {
                          // todo este quilombo es para sacar los duplicados que vienen del join
                          data =
                              _.sortBy(
                                  _.map(
                                      _.pairs(
                                          _.groupBy(data,
                                                    function(d) {
                                                        return d.ogc_fid;
                                                    }, data)
                                      ), function(p) {
                                          return _.max(p[1],
                                                       function(d) {
                                                           return d.score;
                                                       });
                                      }),
                                  function(d) {
                                      return -d.score;
                                  });

                          tr.after(matches_tmpl({
                              matches: data,
                              seccion: $('select#distrito option:selected').html(),
                              distrito: $('select#distrito option:selected').parent().attr('label')
                          }));
                          $('tr', tr.next()).each(function(i, t) {
                              $(this).data('place', data[i]);
                          });

                          if (_.some(data, function(d) { return d.score == 1}))
                              tr.addClass('matched');

                          map.removeMarkers(markers);
                          markers = [];
                          if (elat != "") {
                            // Add current geoposition
                            var m = {
                              nombre: enombre,
                              direccion: edireccion,
                              desc_distrito: elocalidad
                            };
                            var emarker = map.addMarker({
                                  lat: elat,
                                  lng: elng,
                                  details: m,
                                  infoWindow: {
                                      content: infowindow_tmpl({place: m})
                                  },
                                  icon: '/static/polling.png'
                            });
                            markers.push(emarker);
                          }
                          data.forEach(function(m) {
                              var marker = map.addMarker({
                                  lat: m.geojson.coordinates[1],
                                  lng: m.geojson.coordinates[0],
                                  details: m,
                                  infoWindow: {
                                      content: infowindow_tmpl({place: m})
                                  },
                                  click: showMarker,
                              });
                              markers.push(marker);
                          });
                          if (markers.length > 0) map.fitZoom();

                          addGeocomplete($('input#geocomplete', tr.next()));
                      });
            }
        }, 'table#establecimientos tr.establecimiento');

    $(document).on("ajaxSend", function(e, xhr, settings, exception)  {
        if (settings.url == '/completion') return;
        $('#loading').css('visibility', 'visible');
    });

    $(document).on("ajaxComplete", function(e, xhr, settings, exception)  {
        $('#loading').css('visibility', 'hidden');
    });

    $('select#distrito').trigger('change');

});
<commit_msg>remove clickable from polling marker<commit_after>$(function(){
    map = new GMaps({
        div: '#map',
        lat: -12.043333,
        lng: -77.028333,
        mapType: google.maps.MapTypeId.HYBRID,
        mapTypeControlOptions: {
            mapTypeIds : ["hybrid", "roadmap", "satellite", "terrain", "osm"]
        },
        rightclick: function(e) {
            lastRightClickedPoint = e.latLng;
        }
    });

    map.addMapType("osm", {
        getTileUrl: function(coord, zoom) {
            return "http://otile1.mqcdn.com/tiles/1.0.0/map/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
        },
        tileSize: new google.maps.Size(256, 256),
        name: "OpenStreetMap",
        maxZoom: 18
    });

    map.setContextMenu({
        control: 'map',
        options: [
            {
                title: 'Crear centro de votación aquí',
                name: 'agregar_lugar',
                action: function(e) {
                    var tr = $('tr.establecimiento.active');
                    var p_d = $('select#distrito option:selected').val().split('-');
                    var c = $('td', tr).map(function(d,e) { return e.innerHTML; });
                    if( $('tr.establecimiento.active + tr.matches td table tbody').length ) {
                      $('tr.establecimiento.active + tr.matches td table tbody').prepend(new_estab_tmpl({contents: c}));
                    }
                    else {
                      $('tr.establecimiento.active + tr.matches td table').prepend(new_estab_tmpl({contents: c}));
                    }
                    var place_data = {
                        nombre: c[0],
                        direccion: c[1],
                        localidad: c[2],
                        wkb_geometry_4326: 'SRID=4326;POINT(' + lastRightClickedPoint.lng() + ' ' + lastRightClickedPoint.lat() + ')',
                        distrito: p_d[0],
                        seccion: p_d[1]
                    };
                    $.post('/create',
                           place_data,
                           function(d) {
                               place_data['ogc_fid'] = d['ogc_fid'];
                               var new_tr = $('tr.establecimiento.active + tr.matches td table tr:first-child');
                               new_tr.data('place', place_data);
                               $('input[type=checkbox]', new_tr)
                                   .prop('checked', true)
                                   .trigger('change');
                           });
                }
            },
        ]
    });

    var table_tmpl = _.template($('#establecimientos-template').html());
    var matches_tmpl = _.template($('#matches-template').html());
    var infowindow_tmpl = _.template($('#infowindow-template').html());
    var completion_tmpl = _.template($('#completion-template').html());
    var new_estab_tmpl = _.template($('#new-establecimiento-template').html());

    var polygon = null;
    var markers = [];

    var maxZoomService = new google.maps.MaxZoomService();

    var currentBounds = null;
    var currentMarker = null;
    var currentPlace  = null;
    var currentSeccion = null;
    var currentDistrito = null;
    var lastRightClickedPoint = null;

    var updateCompletion = function() {
        $.get('/completion', function(provincias) {
            $('#provincia-ranking').html(completion_tmpl({provincias:provincias}));
        })
    };

    completionRankingInterval = window.setInterval(updateCompletion, 10000);
    updateCompletion();

    var addGeocomplete = function(selector) {
        $(selector)
            .geocomplete({ bounds: polygon.getBounds() })
            .bind("geocode:result", function(event, result) {
                if (!polygon.getBounds().contains(result.geometry.location))
                    // no salir de los bounds actuales si el geocoder
                    // retorna algo afuera de esos bounds
                    return;
                maxZoomService.getMaxZoomAtLatLng(result.geometry.location, function(r) {
                    if (r.status == google.maps.MaxZoomStatus.OK)
                        map.setZoom(r.zoom);
                    map.map.panTo(result.geometry.location);
                });

            });
    };

    $('select#distrito').on('change', function() {
        var p_d = $(this).val().split('-');
        var provincia = $(this).parent('optgroup').attr('label')
        history.pushState({foo: null}, "", "/" + p_d[0] + "/" + p_d[1]);
        $.get('/establecimientos/' + p_d.join('/'),
              function(data) {
                  $('table#establecimientos')
                      .html(table_tmpl({establecimientos: data, provincia: p_d[0] }));
              });

        map.removeMarkers(markers);
        markers = [];

        currentSeccion = p_d[1];
        currentDistrito = p_d[0];

        $.get('/seccion/' + p_d.join('/'), function(data) {
            currentBounds = data.bounds.coordinates[0].map(function(p) {
                return new google.maps.LatLng(p[1], p[0]);
            });
            map.fitLatLngBounds(currentBounds);

            if (polygon != null) map.removePolygon(polygon);

            polygon = map.drawPolygon({
                paths: data.geojson.coordinates,
                useGeoJSON: true,
                strokeOpacity: 0.2,
                strokeWeight: 1,
                strokeColor: '#ff0000',
                fillColor: '#BBD8E9',
                fillOpacity: 0.4,
                clickable: false
            });

            $('a#shapefile').attr('href', '/shape/' + p_d[0] + '/' + p_d[1]);

        });
    });

    var showMarker = function(e) {
        //console.log(e);
    };

    $(document).on({
      'click': function(e){
        e.preventDefault();
        var loc = $('input#latlng').val();
        var l_l = loc.split(',');
        var g = new google.maps.LatLng(l_l[0], l_l[1]);
        if (polygon.getBounds().contains(g)) {
          var tr = $('tr.establecimiento.active');
          var p_d = $('select#distrito option:selected').val().split('-');
          var c = $('td', tr).map(function(d,e) { return e.innerHTML; });
          if( $('tr.establecimiento.active + tr.matches td table tbody').length ) {
            $('tr.establecimiento.active + tr.matches td table tbody').prepend(new_estab_tmpl({contents: c}));
          }
          else {
            $('tr.establecimiento.active + tr.matches td table').prepend(new_estab_tmpl({contents: c}));
          }
          var place_data = {
            nombre: c[0],
            direccion: c[1],
            localidad: c[2],
            wkb_geometry_4326: 'SRID=4326;POINT(' + l_l[1].trim() + ' ' + l_l[0].trim() + ')',
            distrito: p_d[0],
            seccion: p_d[1]
          };
          $.post('/create',place_data,
               function(d) {
                   place_data['ogc_fid'] = d['ogc_fid'];
                   var new_tr = $('tr.establecimiento.active + tr.matches td table tr:first-child');
                   new_tr.data('place', place_data);
                   $('input[type=checkbox]', new_tr)
                       .prop('checked', true)
                       .trigger('change');
          });
          $('input#latlng').val("");
        }
        else {
          $('span#error').css('visibility', 'visible');
          $('input#latlng').val("");
          setTimeout(function(){$("span#error").css('visibility', 'hidden');}, 2000);
        }
        return false;
      }
    }, 'button#latlngBut')

    $(document).on({
        'click': function() {
            if (currentMarker) {
                currentMarker.infoWindow.close();
            }
            var d = $(this).data('place');
            currentPlace = d;
            currentMarker = _.find(map.markers, function(m) {
                return m.details == d;
            });
            // Simulate a click on the actual marker
            google.maps.event.trigger(currentMarker, 'click');
        },
        'dblclick': function() {
            maxZoomService.getMaxZoomAtLatLng(currentMarker.getPosition(), function(r) {
                if (r.status == google.maps.MaxZoomStatus.OK)
                    map.setZoom(r.zoom);
                map.map.panTo(currentMarker.getPosition());
            });
        }
    }, 'tr.matches tr')

    $(document).on({
        'change': function() { // checkbox to choose a match
            var chk = $(this);

            var establecimiento_tr = chk
                .parents('.matches')
                .prev();

            var establecimiento = establecimiento_tr
                .data('establecimiento-id');

            currentPlace = chk
                .parents('tr:not(.matches)')
                .data('place');

            var url = '/matches/' + establecimiento + '/' + currentPlace.ogc_fid;

            if (chk.is(':checked')) {
                //establecimiento_tr.removeClass('guessed');
                //establecimiento_tr.removeClass('wrong');
                establecimiento_tr.addClass('matched');
                $.post(url);
            }
            else { //delete
                establecimiento_tr.removeClass('matched');
                var url = '/matches/' + establecimiento;
                $.post(url, { _method: 'delete'});
            }
        },
    }, 'tr.matches tr input[type=checkbox]')

    $(document).on({
        'click': function(e) {
            var a = $(this);
            var t = a.data('searchType');
            var tr = a.parents('tr.matches');
            var prev = tr.prev();
            var eid = prev.data('establecimiento-id');
            var enombre = $('td:nth-child(1)', prev).html();
            var edireccion = $('td:nth-child(2)', prev).html();
            var elocalidad = $('td:nth-child(3)', prev).html();
            var elat = prev.data('lat');
            var elng = prev.data('lng');
            $.get('/places/' + currentDistrito + '/' + currentSeccion,
                  { // Add nombre and localidad to the mixture for the similarity
                    nombre: $('td:nth-child(1)', prev).html(),
                    direccion: $('td:nth-child(2)', prev).html(),
                    localidad: $('td:nth-child(3)', prev).html(),
                    search_type: t},
                  function(data) {
                      tr.remove();
                      prev.after(matches_tmpl({
                          matches: data,
                          seccion: '',
                          distrito: ''
                      }));
                      $('tr', prev.next()).each(function(i, t) {
                          $(this).data('place', data[i]);
                      });
                      map.removeMarkers(markers);
                      markers = []
                      if (elat != "") {
                        // Add current geoposition
                        var m = {
                          nombre: enombre,
                          direccion: edireccion,
                          desc_distrito: elocalidad
                        };
                        var emarker = map.addMarker({
                              clickable: false,
                              lat: elat,
                              lng: elng,
                              details: m,
                              infoWindow: {
                                  content: infowindow_tmpl({place: m})
                              },
                              icon: '/static/polling.png'
                        });
                        markers.push(emarker);
                      }
                      data.forEach(function(m) {
                        if (m.score > 0.2) {
                            var marker = map.addMarker({
                                lat: m.geojson.coordinates[1],
                                lng: m.geojson.coordinates[0],
                                details: m,
                                infoWindow: {
                                    content: infowindow_tmpl({place: m})
                                },
                                click: showMarker,
                            });
                            markers.push(marker);
                        }
                        else {
                          //console.log(m.score)
                        }
                      });
                      if (markers.length > 0) map.fitZoom();
                      addGeocomplete($('input#geocomplete', $($(prev).next())));
                  });
            e.preventDefault();
            return false;
        }
    }, 'a.view-all-places')

    $(document).on(
        {
            // click en establecimiento, abre los matches
            'click': function() {
                $('tr', $(this).parent()).removeClass('active');
                $('tr.matches').remove();
                var tr = $(this);
                tr.addClass('active');
                var eid = tr.data('establecimiento-id');
                var enombre = $('td:nth-child(1)', tr).html();
                var edireccion = $('td:nth-child(2)', tr).html();
                var elocalidad = $('td:nth-child(3)', tr).html();
                var elat = tr.data('lat');
                var elng = tr.data('lng');
                $.get('/matches/' + eid,
                      function(data) {
                          // todo este quilombo es para sacar los duplicados que vienen del join
                          data =
                              _.sortBy(
                                  _.map(
                                      _.pairs(
                                          _.groupBy(data,
                                                    function(d) {
                                                        return d.ogc_fid;
                                                    }, data)
                                      ), function(p) {
                                          return _.max(p[1],
                                                       function(d) {
                                                           return d.score;
                                                       });
                                      }),
                                  function(d) {
                                      return -d.score;
                                  });

                          tr.after(matches_tmpl({
                              matches: data,
                              seccion: $('select#distrito option:selected').html(),
                              distrito: $('select#distrito option:selected').parent().attr('label')
                          }));
                          $('tr', tr.next()).each(function(i, t) {
                              $(this).data('place', data[i]);
                          });

                          if (_.some(data, function(d) { return d.score == 1}))
                              tr.addClass('matched');

                          map.removeMarkers(markers);
                          markers = [];
                          if (elat != "") {
                            // Add current geoposition
                            var m = {
                              nombre: enombre,
                              direccion: edireccion,
                              desc_distrito: elocalidad
                            };
                            var emarker = map.addMarker({
                                  clickable: false,
                                  lat: elat,
                                  lng: elng,
                                  details: m,
                                  infoWindow: {
                                      content: infowindow_tmpl({place: m})
                                  },
                                  icon: '/static/polling.png'
                            });
                            markers.push(emarker);
                          }
                          data.forEach(function(m) {
                              var marker = map.addMarker({
                                  lat: m.geojson.coordinates[1],
                                  lng: m.geojson.coordinates[0],
                                  details: m,
                                  infoWindow: {
                                      content: infowindow_tmpl({place: m})
                                  },
                                  click: showMarker,
                              });
                              markers.push(marker);
                          });
                          if (markers.length > 0) map.fitZoom();

                          addGeocomplete($('input#geocomplete', tr.next()));
                      });
            }
        }, 'table#establecimientos tr.establecimiento');

    $(document).on("ajaxSend", function(e, xhr, settings, exception)  {
        if (settings.url == '/completion') return;
        $('#loading').css('visibility', 'visible');
    });

    $(document).on("ajaxComplete", function(e, xhr, settings, exception)  {
        $('#loading').css('visibility', 'hidden');
    });

    $('select#distrito').trigger('change');

});
<|endoftext|>


<commit_before>/*
This is a game by:
Markus "TiByte" Becker   - Lead Developer
Lucas "LFalch"           - Programmer
Aileen                   - Graphic Designer
Kilian "Malloth Rha"     - Musician
Micha                    - Junior Programmer
Using Libraries: Pixi.js and Howler.js
date: 16.04.2016 for LD35
theme: Shapeshift
*/

/*
STRING OF EVENTS:
1. Intro Comic (3 Pictures)
    - socks come to life when unattended
2. Under the bed
    2.1. game
        - avoid hands
    2.2. more story
        - grey sock tells hero to fight sewer monster
3. Sewerfall
    3.1. game
        - falling in the sewer
        - avoid dirt
    3.2. reward (grow arms)
        - if not too dirty
4. Snake game
    4.1. game
        - eat fluff
    4.2. reward (grow bigger)
        - if player ate more than 20 fluff in 30 sec.
5. Plumbing game
    5.1. game
        - turn tiles to connect pipes
    5.2. reward (grow hair)
        - did it in 15 seconds
### Optional ###
0. Platforming game
    0.1. game
    0.2. reward (grow wings)
################
6. Doodle Jump
    6.1. game
        - collect something to gain height
    6.2. more story
        - if won grabbed by sock-hand
        - else falling = losing health
7. Boss fight
    - attack in turns
*/

/*
000 - Intro
001 - Under the bed game
002 - Story (washing machine)
003 - Sewerfall game
004 - Story (Sockbert)
005 - Snake game
006 - Story (Explanation)
007 - Plumbing game
008 - Story (Break out)
009 - Sewer Jump
010 - Story (Getting grabbed)
011 - Boss fight
012 - Thanks for playing
*/

// Cheat Sheet: https://github.com/mtib/ludum34/blob/master/game.js

// Canvas Size
const WIDTH = 1280;
const HEIGHT = 720;

// Current version
const version = "0.01d"

// Initialize Renderer
var renderer = PIXI.autoDetectRenderer(WIDTH, HEIGHT, {antialiasing: true, transparent: false, resolution: 1});
renderer.backgroundColor = 0x6ec2cb;
document.getElementById("gamediv").appendChild(renderer.view);

// Master Containter
var stage = new PIXI.Container();

// Layers
var cBack = new PIXI.Container();
var cMiddle = new PIXI.Container();
var cFront = new PIXI.Container();
var cGui = new PIXI.Container();

// Config goes here:
const fontConfig = {font: "30px 'Arial'", fill: "#000000", align: "left"};
const debugConfig = {font: "20px 'Fira Code',monospace,sans-serif", fill: "#FF0000", align: "left"};
const pointsConfig = {font: "20px monospace", fill: "#FF00FF", align: "right"};
const infoConfig = {font: "60px Arial", fill: "#FFFFFF", align: "center", dropShadow: true, dropShadowColor: "#000000"};

const relcenter = {x:0.5,y:0.5};
const enterKey = keyboard(13);

const leftArrow = keyboard(37);
const upArrow = keyboard(38);
const rightArrow = keyboard(39);
const downArrow = keyboard(40);

const aKey = keyboard(65);
const wKey = keyboard(87);
const dKey = keyboard(68);
const sKey = keyboard(83);

const s000bed1 = "./scenes/000/bed.pic1.jpg";
const s000bed2 = "./scenes/000/bed.pic2.jpg";
const s000bed3 = "./scenes/000/bed.pic3.jpg";
const s001bg = "./scenes/001/background.jpg"; // background for game #1
const ssock = "./scenes/001/sock.png"; // normal sock, for use in all? scenes
const s001armo = "./scenes/001/arm.open.png"; // o = open
const s001armg = "./scenes/001/arm.sock.png"; // g = grabbed

const sceneMusic = [ // for the cool kids!
    new Howl({
        src: ['scenes/000/SockventureIntro.ogg'],
        loop: true,
        volume: 0.4,
    }),
    new Howl({
        src: ['scenes/001/SockventureHand.ogg'],
        loop: true,
        volume: 0.4,
    })
];

function Game1Sock() {
    self = this;
    size = 128 // Pixel
    speed = 3 // Pixel / Frame
    this.sprite = new PIXI.Sprite.fromImage(ssock);
    this.sprite.anchor = relcenter;
    this.sprite.width = size;
    this.sprite.height = size;
    this.sprite.position = {x: WIDTH*0.5, y: HEIGHT*0.5};
    this.die = function() {
        cMiddle.removeChild(this.sprite);
    }
    this.move = function() {
        delta = {x:0, y:0};
        if ((rightArrow.isDown || dKey.isDown) && this.sprite.position.x < WIDTH - 100) {
            delta.x += speed;
        }
        if ((leftArrow.isDown || aKey.isDown) && this.sprite.position.x > 100) {
            delta.x -= speed;
        }
        if ((upArrow.isDown || wKey.isDown) && this.sprite.position.y > 230) {
            delta.y -= speed;
        }
        if ((downArrow.isDown || sKey.isDown) && this.sprite.position.y < HEIGHT - 100) {
            delta.y += speed;
        }
        magsqr = Math.sqrt(Math.abs(delta.x) + Math.abs(delta.y))
        if (magsqr == 0) {
            return;
        }
        if (delta.x > 0 && this.sprite.scale.x > 0) {
            this.sprite.scale.x *= -1;
        } else if (delta.x < 0 && this.sprite.scale.x < 0) {
            this.sprite.scale.x *= -1;
        }
        delta.x /= magsqr;
        delta.y /= magsqr;
        this.sprite.position.x += delta.x;
        this.sprite.position.y += delta.y;
    }
    cMiddle.addChild(this.sprite);
}

function Game1Hand(position) {
    this.sopen = new PIXI.Sprite.fromImage(s001armo);
    this.sgrab = new PIXI.Sprite.fromImage(s001armg);

    this.sopen.position = position;
    this.sopen.rotation = Math.atan((this.sopen.position.y - gamestate.playerpos().y)/(this.sopen.position.x - gamestate.playerpos().x) );

    this.grab = function() {
        this.sgrab.position = this.sopen.position;
        this.sgrab.anchor = this.sopen.anchor;
        this.sgrab.size = this.sopen.size;
        this.sgrab.rotation = this.sopen.rotation;
        cFront.removeChild(this.sopen);
        cFront.addChild(this.sgrab);
    }
    this.release = function() {
        // shouldnt be needed...
    }
    this.logic = function() {
        // TODO move
    }
    cFront.addChild(this.sopen);
}

function State() {
    self = this;
    this.debugText = new PIXI.Text("Version: "+version+"\n<Debug Information>\nState: ",debugConfig);
    this.debugText.position = {x:5,y:5};
    this.score = new PIXI.Text("0", pointsConfig);
    this.score.position = {x: WIDTH - 5, y: 5};
    this.score.anchor = {x: 1, y:0};
    this.debugStateText = new PIXI.Text("0", debugConfig);
    this.debugStateText.position = {x:89,y:45};

    this.infotext = new PIXI.Text("", infoConfig); // eg. "press xxx to skip"
    this.infotext.position = {x: WIDTH/2, y: HEIGHT/2};
    this.infotext.anchor = relcenter;

    this.doc = {}; // DestroyOnChange
    this.number = 0;

    this.playerpos = function() {
        switch (this.number) {
            case 1:
                return this.doc["gamesock"].sprite.position;
        }
        return {x: -31415, y:-1337};
    }

    cGui.addChild(this.infotext);
    cGui.addChild(this.debugText);
    cGui.addChild(this.debugStateText);

    sceneMusic[0].play();
    this.run = function(){
        console.log("default state");
    }

    this.nextState = function(){
        for (var sprite in this.doc) {
            if (this.doc.hasOwnProperty(sprite)) {
                if (this.doc[sprite].die) {
                    this.doc[sprite].die();
                } else {
                    cGui.removeChild(this.doc[sprite])
                    cMiddle.removeChild(this.doc[sprite])
                    cFront.removeChild(this.doc[sprite])
                    cBack.removeChild(this.doc[sprite]);
                }
            }
            delete this.doc[sprite];
        }
        enterKey.press = undefined;

        sceneMusic[this.number++].stop();
        sceneMusic[this.number].play();

        this.switched = true;
        this.debugStateText.text = this.number;
        this.run = this.funcarray[this.number];
    }
    diasStateGenerator = function(backgrounds) {
        return function(){
            if (this.switched){
                this.infotext.text = "Press <Enter> to skip"
                this.doc["dias"] = 0;
                for (var bg in backgrounds){
                    this.doc[bg] = PIXI.Sprite.fromImage(backgrounds[bg]);
                    this.doc[bg].width  = WIDTH;
                    this.doc[bg].height = HEIGHT;
                }

                cBack.addChild(this.doc[0]);

                enterKey.press = function(){
                    if (self.doc["dias"] == backgrounds.length - 1){
                        self.nextState();
                        enterKey.press = undefined;
                    }else{
                        cBack.removeChild(self.doc[self.doc["dias"]++]);
                        cBack.addChild(self.doc[self.doc["dias"]]);
                    }
                }

                this.switched = false;
            }
        }
    }
    this.introfunc = diasStateGenerator([s000bed1, s000bed2, s000bed3]);
    this.switched = true;
    this.underTheBed = function(){
        if (this.switched) {
            this.infotext.text = "[WASD] to move";
            this.starttime = Date.now();
            this.doc["points"] = this.score;
            this.doc["s001bg"] = PIXI.Sprite.fromImage(s001bg);
            this.doc["s001armo"] = PIXI.Sprite.fromImage(s001armo);
            this.doc["s001armg"] = PIXI.Sprite.fromImage(s001armg);

            this.doc["s001bg"].width = WIDTH;
            this.doc["s001bg"].height = HEIGHT;
            cBack.addChild(this.doc["s001bg"]);
            cGui.addChild(this.doc["points"]);
            this.doc["gamesock"] = new Game1Sock();

            hidetext = function(that){
                window.setTimeout(function(){that.infotext.text = ""}, 4000);
            }(this);

            this.spawnHands = window.setInterval(function () {
                orientation = Math.floor(Math.random() * 4.0);
                rx = WIDTH * Math.random();
                ry = HEIGHT * Math.random();
                pos = {};
                switch (orientation) {
                    case 0: // top
                        pos = {x: rx, y: 0};
                        break;
                    case 1: // right
                        pos = {x: 0, y: ry};
                        break;
                    case 2: // bottom
                        pos = {x: rx, y: HEIGHT};
                        break;
                    case 3: // left
                        pos = {x: 0, y: ry};
                        break;
                }
                this.doc["hand"+Date.now()] = new Game1Hand(pos);
            }, 800);

            this.switched = false;
        }
        this.doc["gamesock"].move();
        this.doc["points"].text = Math.floor((Date.now() - this.starttime) / 1000.0);
    }
    this.funcarray = [this.introfunc, this.underTheBed];

    this.run = this.funcarray[this.number];
}

var gamestate = new State();

/*
    stage
      |
      +-- cBack
      +-- cMiddle
      +-- cFront
      +-- cGui
Drawn from top to bottom
*/
stage.addChild(cBack);
stage.addChild(cMiddle);
stage.addChild(cFront);
stage.addChild(cGui);

PIXI.loader
    .add(s001bg)
    .add(s001armg)
    .add(s001armo)
    .add(ssock)
    .load(setup);

function setup(){
    // Do setup here
    // Easteregg: eyes!¬
    renderStage();
}

// Request Animation Frame
function renderStage(){
    requestAnimationFrame(renderStage);
    gameLoop();
    renderer.render(stage);
}

// Called before rendering
function gameLoop(){
    // after doing logic:
    gamestate.run()
}

// start game
setup();
<commit_msg>hands<commit_after>/*
This is a game by:
Markus "TiByte" Becker   - Lead Developer
Lucas "LFalch"           - Programmer
Aileen                   - Graphic Designer
Kilian "Malloth Rha"     - Musician
Micha                    - Junior Programmer
Using Libraries: Pixi.js and Howler.js
date: 16.04.2016 for LD35
theme: Shapeshift
*/

/*
STRING OF EVENTS:
1. Intro Comic (3 Pictures)
    - socks come to life when unattended
2. Under the bed
    2.1. game
        - avoid hands
    2.2. more story
        - grey sock tells hero to fight sewer monster
3. Sewerfall
    3.1. game
        - falling in the sewer
        - avoid dirt
    3.2. reward (grow arms)
        - if not too dirty
4. Snake game
    4.1. game
        - eat fluff
    4.2. reward (grow bigger)
        - if player ate more than 20 fluff in 30 sec.
5. Plumbing game
    5.1. game
        - turn tiles to connect pipes
    5.2. reward (grow hair)
        - did it in 15 seconds
### Optional ###
0. Platforming game
    0.1. game
    0.2. reward (grow wings)
################
6. Doodle Jump
    6.1. game
        - collect something to gain height
    6.2. more story
        - if won grabbed by sock-hand
        - else falling = losing health
7. Boss fight
    - attack in turns
*/

/*
000 - Intro
001 - Under the bed game
002 - Story (washing machine)
003 - Sewerfall game
004 - Story (Sockbert)
005 - Snake game
006 - Story (Explanation)
007 - Plumbing game
008 - Story (Break out)
009 - Sewer Jump
010 - Story (Getting grabbed)
011 - Boss fight
012 - Thanks for playing
*/

// Cheat Sheet: https://github.com/mtib/ludum34/blob/master/game.js

// Canvas Size
const WIDTH = 1280;
const HEIGHT = 720;

// Current version
const version = "0.01d"

// Initialize Renderer
var renderer = PIXI.autoDetectRenderer(WIDTH, HEIGHT, {antialiasing: true, transparent: false, resolution: 1});
renderer.backgroundColor = 0x6ec2cb;
document.getElementById("gamediv").appendChild(renderer.view);

// Master Containter
var stage = new PIXI.Container();

// Layers
var cBack = new PIXI.Container();
var cMiddle = new PIXI.Container();
var cFront = new PIXI.Container();
var cGui = new PIXI.Container();

// Config goes here:
const fontConfig = {font: "30px 'Arial'", fill: "#000000", align: "left"};
const debugConfig = {font: "20px 'Fira Code',monospace,sans-serif", fill: "#FF0000", align: "left"};
const pointsConfig = {font: "20px monospace", fill: "#FF00FF", align: "right"};
const infoConfig = {font: "60px Arial", fill: "#FFFFFF", align: "center", dropShadow: true, dropShadowColor: "#000000"};

const relcenter = {x:0.5,y:0.5};
const enterKey = keyboard(13);

const leftArrow = keyboard(37);
const upArrow = keyboard(38);
const rightArrow = keyboard(39);
const downArrow = keyboard(40);

const aKey = keyboard(65);
const wKey = keyboard(87);
const dKey = keyboard(68);
const sKey = keyboard(83);

const s000bed1 = "./scenes/000/bed.pic1.jpg";
const s000bed2 = "./scenes/000/bed.pic2.jpg";
const s000bed3 = "./scenes/000/bed.pic3.jpg";
const s001bg = "./scenes/001/background.jpg"; // background for game #1
const ssock = "./scenes/001/sock.png"; // normal sock, for use in all? scenes
const s001armo = "./scenes/001/arm.open.png"; // o = open
const s001armg = "./scenes/001/arm.sock.png"; // g = grabbed

const sceneMusic = [ // for the cool kids!
    new Howl({
        src: ['scenes/000/SockventureIntro.ogg'],
        loop: true,
        volume: 0.4,
    }),
    new Howl({
        src: ['scenes/001/SockventureHand.ogg'],
        loop: true,
        volume: 0.4,
    })
];

function Game1Sock() {
    self = this;
    size = 128 // Pixel
    speed = 3 // Pixel / Frame
    this.sprite = new PIXI.Sprite.fromImage(ssock);
    this.sprite.anchor = relcenter;
    this.sprite.width = size;
    this.sprite.height = size;
    this.sprite.position = {x: WIDTH*0.5, y: HEIGHT*0.5};
    this.die = function() {
        cMiddle.removeChild(this.sprite);
    }
    this.move = function() {
        delta = {x:0, y:0};
        if ((rightArrow.isDown || dKey.isDown) && this.sprite.position.x < WIDTH - 100) {
            delta.x += speed;
        }
        if ((leftArrow.isDown || aKey.isDown) && this.sprite.position.x > 100) {
            delta.x -= speed;
        }
        if ((upArrow.isDown || wKey.isDown) && this.sprite.position.y > 230) {
            delta.y -= speed;
        }
        if ((downArrow.isDown || sKey.isDown) && this.sprite.position.y < HEIGHT - 100) {
            delta.y += speed;
        }
        magsqr = Math.sqrt(Math.abs(delta.x) + Math.abs(delta.y))
        if (magsqr == 0) {
            return;
        }
        if (delta.x > 0 && this.sprite.scale.x > 0) {
            this.sprite.scale.x *= -1;
        } else if (delta.x < 0 && this.sprite.scale.x < 0) {
            this.sprite.scale.x *= -1;
        }
        delta.x /= magsqr;
        delta.y /= magsqr;
        this.sprite.position.x += delta.x;
        this.sprite.position.y += delta.y;
    }
    cMiddle.addChild(this.sprite);
}

function Game1Hand(position) {
    this.sopen = new PIXI.Sprite.fromImage(s001armo);
    this.sgrab = new PIXI.Sprite.fromImage(s001armg);

    this.sopen.position = position;
    this.sopen.rotation = Math.atan((this.sopen.position.y - gamestate.playerpos().y)/(this.sopen.position.x - gamestate.playerpos().x) );

    this.grab = function() {
        this.sgrab.position = this.sopen.position;
        this.sgrab.anchor = this.sopen.anchor;
        this.sgrab.size = this.sopen.size;
        this.sgrab.rotation = this.sopen.rotation;
        cFront.removeChild(this.sopen);
        cFront.addChild(this.sgrab);
    }
    this.release = function() {
        // shouldnt be needed...
    }
    this.logic = function() {
        // TODO move
    }
    this.die = function() {
        cFront.removeChild(this.sopen);
        cFront.removeChild(this.sgrab);
        delete this;
    }
    cFront.addChild(this.sopen);
}

function State() {
    self = this;
    this.debugText = new PIXI.Text("Version: "+version+"\n<Debug Information>\nState: ",debugConfig);
    this.debugText.position = {x:5,y:5};
    this.score = new PIXI.Text("0", pointsConfig);
    this.score.position = {x: WIDTH - 5, y: 5};
    this.score.anchor = {x: 1, y:0};
    this.debugStateText = new PIXI.Text("0", debugConfig);
    this.debugStateText.position = {x:89,y:45};

    this.infotext = new PIXI.Text("", infoConfig); // eg. "press xxx to skip"
    this.infotext.position = {x: WIDTH/2, y: HEIGHT/2};
    this.infotext.anchor = relcenter;

    this.doc = {}; // DestroyOnChange
    this.number = 0;

    this.playerpos = function() {
        switch (this.number) {
            case 1:
                return this.doc["gamesock"].sprite.position;
        }
        return {x: -31415, y:-1337};
    }

    cGui.addChild(this.infotext);
    cGui.addChild(this.debugText);
    cGui.addChild(this.debugStateText);

    sceneMusic[0].play();
    this.run = function(){
        console.log("default state");
    }

    this.nextState = function(){
        for (var sprite in this.doc) {
            if (this.doc.hasOwnProperty(sprite)) {
                if (this.doc[sprite].die) {
                    this.doc[sprite].die();
                } else {
                    cGui.removeChild(this.doc[sprite])
                    cMiddle.removeChild(this.doc[sprite])
                    cFront.removeChild(this.doc[sprite])
                    cBack.removeChild(this.doc[sprite]);
                }
            }
            delete this.doc[sprite];
        }
        enterKey.press = undefined;

        sceneMusic[this.number++].stop();
        sceneMusic[this.number].play();

        this.switched = true;
        this.debugStateText.text = this.number;
        this.run = this.funcarray[this.number];
    }
    diasStateGenerator = function(backgrounds) {
        return function(){
            if (this.switched){
                this.infotext.text = "Press <Enter> to proceed"
                this.doc["dias"] = 0;
                for (var bg in backgrounds){
                    this.doc[bg] = PIXI.Sprite.fromImage(backgrounds[bg]);
                    this.doc[bg].width  = WIDTH;
                    this.doc[bg].height = HEIGHT;
                }

                cBack.addChild(this.doc[0]);

                enterKey.press = function(){
                    if (self.doc["dias"] == backgrounds.length - 1){
                        self.nextState();
                        enterKey.press = undefined;
                    }else{
                        cBack.removeChild(self.doc[self.doc["dias"]++]);
                        cBack.addChild(self.doc[self.doc["dias"]]);
                    }
                }

                this.switched = false;
            }
        }
    }
    this.introfunc = diasStateGenerator([s000bed1, s000bed2, s000bed3]);
    this.switched = true;
    this.underTheBed = function(){
        if (this.switched) {
            this.infotext.text = "[WASD] to move";
            this.starttime = Date.now();
            this.doc["points"] = this.score;
            this.doc["s001bg"] = PIXI.Sprite.fromImage(s001bg);
            this.doc["s001armo"] = PIXI.Sprite.fromImage(s001armo);
            this.doc["s001armg"] = PIXI.Sprite.fromImage(s001armg);

            this.doc["s001bg"].width = WIDTH;
            this.doc["s001bg"].height = HEIGHT;
            cBack.addChild(this.doc["s001bg"]);
            cGui.addChild(this.doc["points"]);
            this.doc["gamesock"] = new Game1Sock();

            hidetext = function(that){
                window.setTimeout(function(){that.infotext.text = ""}, 4000);
            }(this);

            this.spawnHands = function(self) {
                window.setTimeout(function () {
                    orientation = Math.floor(Math.random() * 4.0);
                    rx = WIDTH * Math.random();
                    ry = HEIGHT * Math.random();
                    pos = {};
                    switch (orientation) {
                        case 0: // top
                            pos = {x: rx, y: 0};
                            break;
                        case 1: // right
                            pos = {x: 0, y: ry};
                            break;
                        case 2: // bottom
                            pos = {x: rx, y: HEIGHT};
                            break;
                        case 3: // left
                            pos = {x: 0, y: ry};
                            break;
                    }
                    self.doc[Date.now()] = new Game1Hand(pos);
                }, 1200);
            }(this);

            this.switched = false;
        }
        this.doc["gamesock"].move();
        this.doc["points"].text = Math.floor((Date.now() - this.starttime) / 1000.0);
    }
    this.funcarray = [this.introfunc, this.underTheBed];

    this.run = this.funcarray[this.number];
}

var gamestate = new State();

/*
    stage
      |
      +-- cBack
      +-- cMiddle
      +-- cFront
      +-- cGui
Drawn from top to bottom
*/
stage.addChild(cBack);
stage.addChild(cMiddle);
stage.addChild(cFront);
stage.addChild(cGui);

PIXI.loader
    .add(s001bg)
    .add(s001armg)
    .add(s001armo)
    .add(ssock)
    .load(setup);

function setup(){
    // Do setup here
    // Easteregg: eyes!¬
    renderStage();
}

// Request Animation Frame
function renderStage(){
    requestAnimationFrame(renderStage);
    gameLoop();
    renderer.render(stage);
}

// Called before rendering
function gameLoop(){
    // after doing logic:
    gamestate.run()
}

// start game
setup();
<|endoftext|>


<commit_before>(function($) {
  'use strict';

  var DEFAULT_FONT_SIZE = 14;

  var $btn = $('#btn-create'),
      $thumb = $('#thumb'),
      $fontSize = $('#fs'),
      $fontSizeOut = $('#fs-out');

  $(function() {

    $fontSize.val(DEFAULT_FONT_SIZE);
    $fontSize.on('input', function() {
      var fs = $(this).val();
      $fontSizeOut.text(fs);
    });

    $btn.on('click', function() {
      $thumb.hide();
      var $img = $('<img>');
      var imgURI = '/lorem?w=' + $('#w').val() + '&h=' + $('#h').val() + '&fs=' + $fontSize.val();
      var text = $('#s').val();
      if (text.length > 0) {
      imgURI += '&s=' + text.replace(/\s/g, '+')
                            .replace(/&/g, '＆')
                            .replace(/=/g, '＝')
                            .replace(/;/g, '；')
                            .replace(/%/g, '％');
      }
      var hasProp = $('#p').prop('checked');
      if (hasProp) {
        imgURI += '&p=1';
      }
      var imgType = $('input[name="t"]:checked').val();
      if (imgType) {
        imgURI += '&t=' + imgType;
      }
      $img.attr('src', imgURI);
      $thumb
        .empty()
        .append($img)
        .fadeIn();
    });
  });
})(jQuery);
<commit_msg>Make fields variable<commit_after>(function($) {
  'use strict';

  var DEFAULT_FONT_SIZE = 14;

  var $btn = $('#btn-create'),
      $thumb = $('#thumb'),
      $fontSize = $('#fs'),
      $fontSizeOut = $('#fs-out'),
      $width = $('#w'),
      $height = $('#h'),
      $text = $('#s'),
      $hasProp = $('#p');

  $(function() {

    $fontSize.val(DEFAULT_FONT_SIZE);
    $fontSize.on('input', function() {
      var fs = $(this).val();
      $fontSizeOut.text(fs);
    });

    $btn.on('click', function() {
      $thumb.hide();
      var $img = $('<img>');
      var imgURI = '/lorem?w=' + $width.val() + '&h=' + $height.val() + '&fs=' + $fontSize.val();
      var text = $text.val();
      if (text.length > 0) {
      imgURI += '&s=' + text.replace(/\s/g, '+')
                            .replace(/&/g, '＆')
                            .replace(/=/g, '＝')
                            .replace(/;/g, '；')
                            .replace(/%/g, '％');
      }
      var hasProp = $hasProp.prop('checked');
      if (hasProp) {
        imgURI += '&p=1';
      }
      var imgType = $('input[name="t"]:checked').val();
      if (imgType) {
        imgURI += '&t=' + imgType;
      }
      $img.attr('src', imgURI);
      $thumb
        .empty()
        .append($img)
        .fadeIn();
    });
  });
})(jQuery);
<|endoftext|>


<commit_before>/*
 *  DenonAVR.js
 *
 *  David Janes
 *  IOTDB
 *  2014-12-06
 */

var iotdb = require("iotdb");
var _ = iotdb._;

exports.Model = iotdb.make_model('DenonAVR')
    .name("Denon AVR")
    .description("Denon Audio/Visual Receivers")
    .io("on", iotdb.boolean.on)
    .io("volume", iotdb.number.unit.volume)
    .io("band", iotdb.string.band)
    .io("band",
        iotdb
        .make_string(":band")
        .enumeration(_.ld.expand([
            "iot-attribute:band.aux",
            "iot-attribute:band.bluray",
            "iot-attribute:band.cable",
            "iot-attribute:band.cd",
            "iot-attribute:band.dvd",
            "iot-attribute:band.dvr",
            "iot-attribute:band.game",
            "iot-attribute:band.game#1",
            "iot-attribute:band.game#2",
            "iot-attribute:band.phono",
            "iot-attribute:band.radio.hd",
            "iot-attribute:band.radio.internet",
            "iot-attribute:band.radio.tuner",
            "iot-attribute:band.satellite",
            "iot-attribute:band.streaming.flickr",
            "iot-attribute:band.streaming.lastfm",
            "iot-attribute:band.streaming.napster",
            "iot-attribute:band.streaming.pandora",
            "iot-attribute:band.streaming.rhapsody",
            "iot-attribute:band.tv",
            "iot-attribute:band.usb",
            "iot-attribute:band.vendor.dock",
            "iot-attribute:band.vendor.favorites",
            "iot-attribute:band.vendor.ipod",
            "iot-attribute:band.vendor.media-player",
        ]))
    )
    .make();

exports.binding = {
    bridge: require('../DenonAVRBridge').Bridge,
    model: exports.Model,
    mapping: {
        band: {
            "iot-attribute:band.phono": "PHONO",
            "iot-attribute:band.cd": "CD",
            "iot-attribute:band.dvd": "DVD",
            "iot-attribute:band.bluray": "BD",
            "iot-attribute:band.tv": "TV",
            "iot-attribute:band.satellite": "SAT/CBL",
            "iot-attribute:band.cable": "SAT/CBL",
            "iot-attribute:band.dvr": "DVR",
            "iot-attribute:band.game": "GAME",
            "iot-attribute:band.game#1": "GAME",
            "iot-attribute:band.game#2": "GAME2",
            "iot-attribute:band.aux": "V.AUX",
            "iot-attribute:band.vendor.dock": "DOCK",
            "iot-attribute:band.vendor.ipod": "IPOD",
            "iot-attribute:band.vendor.favorites": "FAVORITES",
            "iot-attribute:band.radio.tuner": "TUNER",
            "iot-attribute:band.radio.hd": "radio.hd",
            "iot-attribute:band.vendor.media-player": "MPLAY",
            "iot-attribute:band.streaming.rhapsody": "RHAPSODY",
            "iot-attribute:band.streaming.napster": "NAPSTER",
            "iot-attribute:band.streaming.pandora": "PANDORA",
            "iot-attribute:band.streaming.lastfm": "LASTFM",
            "iot-attribute:band.streaming.flickr": "FLICKR",
            "iot-attribute:band.radio.internet": "IRADIO",
            "iot-attribute:band.usb": "USB",
        }
    }
};
<commit_msg>cleanup for permissions<commit_after>/*
 *  DenonAVR.js
 *
 *  David Janes
 *  IOTDB
 *  2014-12-06
 */

var iotdb = require("iotdb");
var _ = iotdb._;

exports.Model = iotdb.make_model('DenonAVR')
    .name("Denon AVR")
    .description("Denon Audio/Visual Receivers")
    .io("on", iotdb.boolean.on)
    .io("volume", iotdb.number.unit.volume)
    .io("band", iotdb.string.band)
    .io("band",
        iotdb
        .make_string(":band")
        .enumeration(_.ld.expand([
            "iot-attribute:band.aux",
            "iot-attribute:band.bluray",
            "iot-attribute:band.cable",
            "iot-attribute:band.cd",
            "iot-attribute:band.dvd",
            "iot-attribute:band.dvr",
            "iot-attribute:band.game",
            "iot-attribute:band.game#1",
            "iot-attribute:band.game#2",
            "iot-attribute:band.phono",
            "iot-attribute:band.radio.hd",
            "iot-attribute:band.radio.internet",
            "iot-attribute:band.radio.tuner",
            "iot-attribute:band.satellite",
            "iot-attribute:band.service.flickr",
            "iot-attribute:band.service.lastfm",
            "iot-attribute:band.service.napster",
            "iot-attribute:band.service.pandora",
            "iot-attribute:band.service.rhapsody",
            "iot-attribute:band.tv",
            "iot-attribute:band.usb",
            "iot-attribute:band.vendor.dock",
            "iot-attribute:band.vendor.favorites",
            "iot-attribute:band.vendor.ipod",
            "iot-attribute:band.vendor.media-player",
        ]))
    )
    .make();

exports.binding = {
    bridge: require('../DenonAVRBridge').Bridge,
    model: exports.Model,
    mapping: {
        band: {
            "iot-attribute:band.phono": "PHONO",
            "iot-attribute:band.cd": "CD",
            "iot-attribute:band.dvd": "DVD",
            "iot-attribute:band.bluray": "BD",
            "iot-attribute:band.tv": "TV",
            "iot-attribute:band.satellite": "SAT/CBL",
            "iot-attribute:band.cable": "SAT/CBL",
            "iot-attribute:band.dvr": "DVR",
            "iot-attribute:band.game": "GAME",
            "iot-attribute:band.game#1": "GAME",
            "iot-attribute:band.game#2": "GAME2",
            "iot-attribute:band.aux": "V.AUX",
            "iot-attribute:band.vendor.dock": "DOCK",
            "iot-attribute:band.vendor.ipod": "IPOD",
            "iot-attribute:band.vendor.favorites": "FAVORITES",
            "iot-attribute:band.radio.tuner": "TUNER",
            "iot-attribute:band.radio.hd": "radio.hd",
            "iot-attribute:band.vendor.media-player": "MPLAY",
            "iot-attribute:band.service.rhapsody": "RHAPSODY",
            "iot-attribute:band.service.napster": "NAPSTER",
            "iot-attribute:band.service.pandora": "PANDORA",
            "iot-attribute:band.service.lastfm": "LASTFM",
            "iot-attribute:band.service.flickr": "FLICKR",
            "iot-attribute:band.radio.internet": "IRADIO",
            "iot-attribute:band.usb": "USB",
        }
    }
};
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var cluster = require('../');

require('./common');
var assert = require('assert');

cluster = cluster()
  .set('workers', 2)
  .set('restart threshold', 0)
  .use(cluster.debug())
  .start();

if (!cluster.isMaster) {
  return;
}

var parentId = process.env.CLUSTER_PARENT_PID;

cluster.on('listening', function() {
  if (parentId) {
    cluster.close();
    return;
  }

  cluster.restart();
  setTimeout(function() {
    throw new Error('Initial master process has turned into a zombie!');
  }, 3000);
});
<commit_msg>refactor standalone test slightly<commit_after>
/**
 * Module dependencies.
 */

var cluster = require('../');

require('./common');
var assert = require('assert');

cluster = cluster()
  .set('workers', 2)
  .set('restart threshold', 0)
  .use(cluster.debug())
  .start();

if (!cluster.isMaster) return;
var ppid = process.env.CLUSTER_PARENT_PID;

cluster.on('listening', function(){
  if (ppid) return cluster.close();
  cluster.restart();
  setTimeout(function() {
    throw new Error('Initial master process has turned into a zombie!');
  }, 3000);
});
<|endoftext|>