<commit_before>var config = require('config');
var log = require('./client/log')('geocode');
var get = require('./client/request').get;

var southWest = [-123.099060058594, 36.745486924699];
var northEast = [-121.192932128906, 38.182068998322];

/**********tismart **********************/
var dev_amigo_token = "A:m8SOB7KwYWuuWAeYEHHjBf7U9VIZFrMuH2LLjS";

/**
 * Geocode
 */

module.exports = geocode;
module.exports.reverse = reverse;
module.exports.suggest = suggest;
module.exports.suggestAmigo = suggestAmigo;

/**
 * Geocode
 */

function geocode(address, callback) {
  log('--> geocoding %s', address);
  get('/geocode/' + address, function(err, res) {
    if (err) {
      log('<-- geocoding error %s', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Reverse geocode
 */

function reverse(ll, callback) {
  log('--> reverse geocoding %s', ll);
  get('/geocode/reverse/' + ll[0] + ',' + ll[1], function(err, res) {
    if (err) {
      log('<-- geocoding error %e', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Suggestions!
 */

function suggestAmigo(text, callback) {

    var lista_direcciones;

    get('https://www.amigocloud.com/api/v1/me/geocoder/autocomplete?text=' + text +'&token=' + dev_amigo_token,

        function(err, res) {

            if(err) {
                console.log("Error amigo cloud");
                log("Amigo Cloud Response Error ->", err);

            }else{
                if(res.body.features) {

                    var lista_direcciones = res.body.features;
                    if (lista_direcciones.length > 0) {
                         callback(
                            null,
                            lista_direcciones
                        );
                    }else {
                        callback(true, res);
                    }

                }
            }
    });
}

function suggest(text, callback) {
  var bingSuggestions, nominatimSuggestions, totalSuggestions;
  log('--> getting suggestion for %s', text);

  get('/geocode/suggest/'+ text, function(err, res){

    if (err) {
      log('<-- suggestion error %s', err);
      callback(err, res);
    } else {
      log('<-- got %s suggestions', res.body.length);

	bingSuggestions = res.body;

    console.log("------------API GEOCODE---------------");
    console.log("res ->", res.body);
    console.log("res.body ->", res);

//      callback(null, res.body);
	get('http://nominatim.openstreetmap.org/search' +
	    '?format=json&addressdetails=1&' +
	    'viewbox=' + southWest[0] + ',' +
	    northEast[1] + ',' + northEast[0] + ',' + southWest[1] +
	    '&bounded=1' +
	    'countrycodes=us&q=' + text, function (err, nRes) {
		var inside = false;
	    nominatimSuggestions = [];
            for (var i = 0; i < nRes.body.length; i++) {
//		inside = inside && (nRes.body[i].lng > southWest[0]);
//		inside = inside && (nRes.body[i].lng < northEast[0]);
//		inside = inside && (nRes.body[i].lat > southWest[1]);
//		inside = inside && (nRes.body[i].lat < northEast[1]);
//		if (inside) {
                    nominatimSuggestions.push(nRes.body[i]);
//		}
            }

            console.log('======data enviada===============');
            console.log(nominatimSuggestions.slice(0,2).concat(bingSuggestions.slice(0,3)));
            callback(
		null,
		nominatimSuggestions.slice(0,2).concat(bingSuggestions.slice(0,3))
	    );
	});
    }
  });

}

<commit_msg>adding new search<commit_after>var config = require('config');
var log = require('./client/log')('geocode');
var get = require('./client/request').get;

var southWest = [-123.099060058594, 36.745486924699];
var northEast = [-121.192932128906, 38.182068998322];

/**********tismart **********************/
var dev_amigo_token = "A:m8SOB7KwYWuuWAeYEHHjBf7U9VIZFrMuH2LLjS";

/**
 * Geocode
 */

module.exports = geocode;
module.exports.reverse = reverse;
module.exports.suggest = suggest;
module.exports.suggestAmigo = suggestAmigo;

/**
 * Geocode
 */

function geocode(address, callback) {
  log('--> geocoding %s', address);
  get('/geocode/' + address, function(err, res) {
    if (err) {
      log('<-- geocoding error %s', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Reverse geocode
 */

function reverse(ll, callback) {

  console.log("reserve ll", ll);
  console.log("reserve callback", callback);
  log('--> reverse geocoding %s', ll);
  get('/geocode/reverse/' + ll[0] + ',' + ll[1], function(err, res) {
    if (err) {
      log('<-- geocoding error %e', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Suggestions!
 */

function suggestAmigo(text, callback) {

    var lista_direcciones;

    //get('https://www.amigocloud.com/api/v1/me/geocoder/autocomplete?text=' + text +'&token=' + dev_amigo_token,
    get('https://www.amigocloud.com/api/v1/me/geocoder/search?token=R:DNiePlGOMsw93cEgde88woWAQxm1xzWt7lvVXe&boundary.rect.min_lat=36.155617833819&boundary.rect.min_lon=-123.607177734375&boundary.rect.max_lat=38.826870521381&boundary.rect.max_lon=-120.701293945312&sources=osm,oa&text=' + text,

        function(err, res) {

            if(err) {
                console.log("Error amigo cloud");
                log("Amigo Cloud Response Error ->", err);

            }else{
                if(res.body.features) {

                    var lista_direcciones = res.body.features;
                    if (lista_direcciones.length > 0) {
                         callback(
                            null,
                            lista_direcciones
                        );
                    }else {
                        callback(true, res);
                    }

                }
            }
    });
}

function suggest(text, callback) {
  var bingSuggestions, nominatimSuggestions, totalSuggestions;
  log('--> getting suggestion for %s', text);

  get('/geocode/suggest/'+ text, function(err, res){

    if (err) {
      log('<-- suggestion error %s', err);
      callback(err, res);
    } else {
      log('<-- got %s suggestions', res.body.length);

	bingSuggestions = res.body;

    console.log("------------API GEOCODE---------------");
    console.log("res ->", res.body);
    console.log("res.body ->", res);

//      callback(null, res.body);
	get('http://nominatim.openstreetmap.org/search' +
	    '?format=json&addressdetails=1&' +
	    'viewbox=' + southWest[0] + ',' +
	    northEast[1] + ',' + northEast[0] + ',' + southWest[1] +
	    '&bounded=1' +
	    'countrycodes=us&q=' + text, function (err, nRes) {
		var inside = false;
	    nominatimSuggestions = [];
            for (var i = 0; i < nRes.body.length; i++) {
//		inside = inside && (nRes.body[i].lng > southWest[0]);
//		inside = inside && (nRes.body[i].lng < northEast[0]);
//		inside = inside && (nRes.body[i].lat > southWest[1]);
//		inside = inside && (nRes.body[i].lat < northEast[1]);
//		if (inside) {
                    nominatimSuggestions.push(nRes.body[i]);
//		}
            }

            console.log('======data enviada===============');
            console.log(nominatimSuggestions.slice(0,2).concat(bingSuggestions.slice(0,3)));
            callback(
		null,
		nominatimSuggestions.slice(0,2).concat(bingSuggestions.slice(0,3))
	    );
	});
    }
  });

}

<|endoftext|>


<commit_before>'use strict'

export default function (db, opts, callback) {
  callback()
}
<commit_msg>work on all docs<commit_after>'use strict'

import { collectConflicts } from 'pouchdb-merge'

const getDocs = (db, {filterKey, startkey, endkey, skip, limit, inclusiveEnd, includeDeleted}, callback) => {
  db.getKeys((error, keys) => {
    if (error) return callback(error)

    const filterKeys = keys.filter(key => {
      if (startkey && startkey > key) return false
      if (endkey) return inclusiveEnd ? endkey >= key : endkey > key
      if (filterKey) return filterKey === key

      return true
    })

    db.multiGet(filterKeys, (error, docs) => {
      if (error) return callback(error)

      let result = includeDeleted
        ? docs
        : docs.filter(doc => !doc.deleted)

      if (skip > 0) result = result.slice(skip)
      if (limit > 0 && result.length > limit) result = result.slice(0, limit)

      callback(null, result)
    })
  })
}

export default function (db, opts, callback) {
  const startkey = 'startkey' in opts ? opts.startkey : false
  const endkey = 'endkey' in opts ? opts.endkey : false
  const filterKey = 'key' in opts ? opts.key : false
  const skip = opts.skip || 0
  const limit = typeof opts.limit === 'number' ? opts.limit : -1
  const inclusiveEnd = opts.inclusive_end !== false
  const includeDeleted = 'deleted' in opts ? opts.deleted === 'ok' : false
  const includeDoc = 'include_docs' in opts ? opts.include_docs : true
  // const descending = 'descending' in opts && opts.descending ? true : false

  getDocs(db, {filterKey, startkey, endkey, skip, limit, inclusiveEnd, includeDeleted},
    (error, docs) => {
      if (error) return callback(error)

      let rows = docs.map(doc => {
        if (includeDoc) {
          return {
            id: doc.id,
            key: doc.id,
            value: {
              rev: doc.rev
            },
            doc: {
              ...doc.data,
              _id: doc.id,
              _rev: doc.id,
              _conflicts: opts.conflicts ? collectConflicts(doc) : null
            }
          }
        }

        return {
          id: doc.id,
          key: doc.id,
          value: {
            rev: doc.rev
          }
        }
      })

      callback(null, {
        total_rows: db.meta.doc_count,
        offset: opts.skip,
        rows
      })
    }
  )
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule writeRelayGeneratedFile
 * @flow
 * @format
 */

'use strict';

const SignedSource = require('signedsource');

const crypto = require('crypto');
const invariant = require('invariant');
const prettyStringify = require('prettyStringify');

import type CodegenDirectory from 'CodegenDirectory';
import type {GeneratedNode} from 'RelayConcreteNode';

async function writeRelayGeneratedFile(
  codegenDir: CodegenDirectory,
  generatedNode: GeneratedNode,
  buildCommand: string,
  flowText: ?string,
  persistQuery: ?(text: string) => Promise<string>,
  platform: ?string,
  relayRuntimeModule: string,
): Promise<?GeneratedNode> {
  const moduleName = generatedNode.name + '.graphql';
  const platformName = platform ? moduleName + '.' + platform : moduleName;
  const filename = platformName + '.js';
  const flowTypeName = generatedNode.kind === 'Batch'
    ? 'ConcreteBatch'
    : 'ConcreteFragment';

  let text = null;
  let hash = null;
  if (generatedNode.kind === 'Batch') {
    text = generatedNode.text;
    invariant(
      text,
      'codegen-runner: Expected query to have text before persisting.',
    );
    const oldContent = codegenDir.read(filename);
    // Hash the concrete node including the query text.
    hash = md5(
      JSON.stringify(generatedNode) +
        (persistQuery ? 'persisted' : '') +
        buildCommand +
        'cache-breaker-3',
    );
    if (hash === extractHash(oldContent)) {
      codegenDir.markUnchanged(filename);
      return null;
    }
    if (codegenDir.onlyValidate) {
      codegenDir.markUpdated(filename);
      return null;
    }
    if (persistQuery) {
      generatedNode = {
        ...generatedNode,
        text: null,
        id: await persistQuery(text),
      };
    }
  }

  const moduleText = generateModule({
    buildCommand,
    moduleName,
    documentType: flowTypeName,
    docText: text,
    flowText,
    hash,
    concreteText: prettyStringify(generatedNode),
    relayRuntimeModule,
  });

  codegenDir.writeFile(filename, moduleText);
  return generatedNode;
}

function extractHash(text: ?string): ?string {
  if (!text) {
    return null;
  }
  if (/<<<<<|>>>>>/.test(text)) {
    // looks like a merge conflict
    return null;
  }
  const match = text.match(/^ \* @relayHash (\w{32})$/m);
  return match && match[1];
}

/**
 * Generate a module for the given document name/text.
 */
function generateModule({
  buildCommand,
  moduleName,
  documentType,
  docText,
  concreteText,
  flowText,
  hash,
  relayRuntimeModule,
}: {
  buildCommand: string,
  moduleName: string,
  documentType: 'ConcreteBatch' | 'ConcreteFragment',
  docText: ?string,
  concreteText: string,
  flowText: ?string,
  hash: ?string,
  relayRuntimeModule: string,
}): string {
  const objectName = documentType === 'ConcreteBatch' ? 'batch' : 'fragment';
  const docTextComment = docText ? '\n/*\n' + docText.trim() + '\n*/\n' : '';
  const hashText = hash ? '\n * @relayHash ' + hash : '';
  const source = `/**
 * This file was generated by:
 *   ${buildCommand}
 *
 * ${'@'}providesModule ${moduleName}
 * ${SignedSource.getSigningToken()}${hashText}
 * ${'@'}flow
 * ${'@'}nogrep
 */

'use strict';

/*::
import type {${documentType}} from '${relayRuntimeModule}';
${flowText || ''}
*/

/* eslint-disable comma-dangle, quotes */
${docTextComment}
const ${objectName} /*: ${documentType}*/ = ${concreteText};

module.exports = ${objectName};
`;
  return SignedSource.signFile(source);
}

function md5(text: string): string {
  return crypto.createHash('md5').update(text).digest('hex');
}

module.exports = writeRelayGeneratedFile;
<commit_msg>Disable entirely eslint for files genareted by the compiler<commit_after>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule writeRelayGeneratedFile
 * @flow
 * @format
 */

'use strict';

const SignedSource = require('signedsource');

const crypto = require('crypto');
const invariant = require('invariant');
const prettyStringify = require('prettyStringify');

import type CodegenDirectory from 'CodegenDirectory';
import type {GeneratedNode} from 'RelayConcreteNode';

async function writeRelayGeneratedFile(
  codegenDir: CodegenDirectory,
  generatedNode: GeneratedNode,
  buildCommand: string,
  flowText: ?string,
  persistQuery: ?(text: string) => Promise<string>,
  platform: ?string,
  relayRuntimeModule: string,
): Promise<?GeneratedNode> {
  const moduleName = generatedNode.name + '.graphql';
  const platformName = platform ? moduleName + '.' + platform : moduleName;
  const filename = platformName + '.js';
  const flowTypeName = generatedNode.kind === 'Batch'
    ? 'ConcreteBatch'
    : 'ConcreteFragment';

  let text = null;
  let hash = null;
  if (generatedNode.kind === 'Batch') {
    text = generatedNode.text;
    invariant(
      text,
      'codegen-runner: Expected query to have text before persisting.',
    );
    const oldContent = codegenDir.read(filename);
    // Hash the concrete node including the query text.
    hash = md5(
      JSON.stringify(generatedNode) +
        (persistQuery ? 'persisted' : '') +
        buildCommand +
        'cache-breaker-3',
    );
    if (hash === extractHash(oldContent)) {
      codegenDir.markUnchanged(filename);
      return null;
    }
    if (codegenDir.onlyValidate) {
      codegenDir.markUpdated(filename);
      return null;
    }
    if (persistQuery) {
      generatedNode = {
        ...generatedNode,
        text: null,
        id: await persistQuery(text),
      };
    }
  }

  const moduleText = generateModule({
    buildCommand,
    moduleName,
    documentType: flowTypeName,
    docText: text,
    flowText,
    hash,
    concreteText: prettyStringify(generatedNode),
    relayRuntimeModule,
  });

  codegenDir.writeFile(filename, moduleText);
  return generatedNode;
}

function extractHash(text: ?string): ?string {
  if (!text) {
    return null;
  }
  if (/<<<<<|>>>>>/.test(text)) {
    // looks like a merge conflict
    return null;
  }
  const match = text.match(/^ \* @relayHash (\w{32})$/m);
  return match && match[1];
}

/**
 * Generate a module for the given document name/text.
 */
function generateModule({
  buildCommand,
  moduleName,
  documentType,
  docText,
  concreteText,
  flowText,
  hash,
  relayRuntimeModule,
}: {
  buildCommand: string,
  moduleName: string,
  documentType: 'ConcreteBatch' | 'ConcreteFragment',
  docText: ?string,
  concreteText: string,
  flowText: ?string,
  hash: ?string,
  relayRuntimeModule: string,
}): string {
  const objectName = documentType === 'ConcreteBatch' ? 'batch' : 'fragment';
  const docTextComment = docText ? '\n/*\n' + docText.trim() + '\n*/\n' : '';
  const hashText = hash ? '\n * @relayHash ' + hash : '';
  const source = `/**
 * This file was generated by:
 *   ${buildCommand}
 *
 * ${'@'}providesModule ${moduleName}
 * ${SignedSource.getSigningToken()}${hashText}
 * ${'@'}flow
 * ${'@'}nogrep
 */

/* eslint-disable */

'use strict';

/*::
import type {${documentType}} from '${relayRuntimeModule}';
${flowText || ''}
*/

${docTextComment}
const ${objectName} /*: ${documentType}*/ = ${concreteText};

module.exports = ${objectName};
`;
  return SignedSource.signFile(source);
}

function md5(text: string): string {
  return crypto.createHash('md5').update(text).digest('hex');
}

module.exports = writeRelayGeneratedFile;
<|endoftext|>


<commit_before>var mongoose = require('mongoose'),
    User = mongoose.model('User'),
    Account = mongoose.model('Account'),
    Assignment = mongoose.model('Assignment')

exports.try = function(req, res) {
  Assignment
      .find({
      })
      .exec(function(err, assignmentResult) {
        if(err) return next(err);

        var ID = [];
        var Numbers = {};

        var both, one, neither;
        both = one = neither = 0;

        for(assignment in assignmentResult) {
          if(assignmentResult[assignment].assignmentNumber == "" && assignmentResult[assignment].subAssignment == "")
            both++;
          else if(assignmentResult[assignment].assignmentNumber == "" || assignmentResult[assignment].subAssignment == "") {
            one++;
          } else
            neither++;

          ID.push(assignmentResult[assignment].assignmentID)

          if(Numbers.hasOwnProperty(assignmentResult[assignment].assignmentNumber)) {
            Numbers[assignmentResult[assignment].assignmentNumber] += 1;
          } else {
            Numbers[assignmentResult[assignment].assignmentNumber] = 0;
          }
        }

        console.log("Unique IDs " + ID.length)
        // for(i in ID) {
        //   console.log(ID[i])
        // }

        console.log("Groups of Assignment IDS ")
        for(var i in Numbers) {
          console.log(i, Numbers[i]);
        }

        console.log("--");
        console.log("With both: ", both)
        console.log("With one: ", one)
        console.log("With neither: ", neither)

      })
}

exports.test = function(req, res) {

  return next("Reaching test area");

  Assignment
      .find({
      })
      .exec(function(err, assignmentResult) {
        if(err) return next(err);

        for(assignment in assignmentResult) {
          if(assignmentResult[assignment].assignmentNumber == "" || assignmentResult[assignment].subAssignment == "") {
            var assignmentID = assignmentResult[assignment].assignmentID;
            var assignmentRaw = assignmentID.split(".");
            var assignmentNumber = assignmentRaw[0];
            var subAssignment = assignmentRaw[1];

              // Update assignments, deleting any with erroneous assignmentID

              if(subAssignment.length > 2) {
                 //remove all assignments with ridiculous decimal subAssignment
                Assignment
                  .remove({
                    assignmentID: assignmentID
                  })
                  .exec(function(err, result){
                      if(err) console.log(err)
                      console.log("deleted ", result, " assignments with ID ", assignmentID)
                  })
                } else {

                // Update assignments to all use assignmentNumber and subAssignment number! (Won't delete anything)

                Assignment
                  .update(
                      {
                        assignmentID: assignmentID
                      },
                      {
                        $set: {assignmentNumber: assignmentNumber, subAssignment: subAssignment}
                      }
                    ).exec(function(err, result) {
                      if(err) console.log(err)
                      console.log("updated assignment ", assignmentID)

                    })

                }

          }
        }
      });

}
<commit_msg>testing updates<commit_after>var mongoose = require('mongoose'),
    User = mongoose.model('User'),
    Account = mongoose.model('Account'),
    Assignment = mongoose.model('Assignment')

exports.try = function(req, res) {
  Assignment
      .find({
      })
      .exec(function(err, assignmentResult) {
        if(err) return next(err);

        var ID = [];
        var Numbers = {};

        var both, one, neither;
        both = one = neither = 0;

        for(assignment in assignmentResult) {
          if(assignmentResult[assignment].assignmentNumber == "" && assignmentResult[assignment].subAssignment == "")
            both++;
          else if(assignmentResult[assignment].assignmentNumber == "" || assignmentResult[assignment].subAssignment == "") {
            one++;
          } else
            neither++;

          ID.push(assignmentResult[assignment].assignmentID)

          if(Numbers.hasOwnProperty(assignmentResult[assignment].assignmentNumber)) {
            Numbers[assignmentResult[assignment].assignmentNumber] += 1;
          } else {
            Numbers[assignmentResult[assignment].assignmentNumber] = 0;
          }
        }

        console.log("Unique IDs " + ID.length)
        // for(i in ID) {
        //   console.log(ID[i])
        // }

        console.log("Groups of Assignment IDS ")
        for(var i in Numbers) {
          console.log(i, Numbers[i]);
        }

        console.log("--");
        console.log("With both: ", both)
        console.log("With one: ", one)
        console.log("With neither: ", neither)

      })
}

exports.test = function(req, res) {

  return next({"err":"Testing"});

  Assignment
      .find({
      })
      .exec(function(err, assignmentResult) {
        if(err) return next(err);

        for(assignment in assignmentResult) {
          if(assignmentResult[assignment].assignmentNumber == "" || assignmentResult[assignment].subAssignment == "") {
            var assignmentID = assignmentResult[assignment].assignmentID;
            var assignmentRaw = assignmentID.split(".");
            var assignmentNumber = assignmentRaw[0];
            var subAssignment = assignmentRaw[1];

              // Update assignments, deleting any with erroneous assignmentID

              if(subAssignment.length > 2) {
                 //remove all assignments with ridiculous decimal subAssignment
                Assignment
                  .remove({
                    assignmentID: assignmentID
                  })
                  .exec(function(err, result){
                      if(err) console.log(err)
                      console.log("deleted ", result, " assignments with ID ", assignmentID)
                  })
                } else {

                // Update assignments to all use assignmentNumber and subAssignment number! (Won't delete anything)

                Assignment
                  .update(
                      {
                        assignmentID: assignmentID
                      },
                      {
                        $set: {assignmentNumber: assignmentNumber, subAssignment: subAssignment}
                      }
                    ).exec(function(err, result) {
                      if(err) console.log(err)
                      console.log("updated assignment ", assignmentID)

                    })

                }

          }
        }
      });

}
<|endoftext|>


<commit_before>function AppCtrl ($scope) {
    'use strict';
    $scope.title = 'The Movie Database';
}

function WelcomeCtrl ($scope, moviesResponse) {
    'use strict';
    $scope.movies = moviesResponse.data;
    $scope.nav = 'home';
}

function MoviesListCtrl ($scope, $location, moviesResponse) {
    'use strict';
    $scope.nav = 'movies';
    $scope.movies = moviesResponse.data;
    $scope.add = function () {
        $location.path('/movies/new');
    };
}

MoviesListCtrl.resolve = {
    moviesResponse: function ($http) {
        'use strict';
        return $http.get('/movies');
    }
};

function MoviesAddCtrl ($scope, $http, $location) {
    'use strict';
    $scope.movie = {};
    $scope.save = function (movie) {
        $http.post('/movies', movie)
        .success(function(res) {
            $location.path('/movies/' + res.id);
        });
    };
}

function MovieDetailCtrl ($scope, $http, $location, moviesResponse) {
    'use strict';
    $scope.movie = moviesResponse.data;

    $scope['delete'] = function () {
        $http['delete']('/movies/' + $scope.movie.id).success(function (res) {
            $location.path('/movies');
        });
    };
}

function movieDetailResolver ($http, $route) {
    'use strict';
    var id = $route.current.params.id;
    return $http.get('/movies/' + id);
}

MovieDetailCtrl.resolve = {
    moviesResponse: movieDetailResolver
};

function MovieEditCtrl ($scope, $http, $location, moviesResponse) {
    'use strict';
    $scope.movie = moviesResponse.data;

    $scope.save = function () {
        $http.put('/movies/' + $scope.movie.id, $scope.movie)
        .success(function (res) {
            $location.path('/movies/' + $scope.movie.id);
        });
    };
}

MovieEditCtrl.resolve = {
    moviesResponse: movieDetailResolver
};

function NotFoundCtrl ($scope, $location) {
    'use strict';
    $scope.culprit = $location.search().culprit || 'unknown beast';
}

var ErrorCtrl = NotFoundCtrl;

function HeaderController($scope, $route) {
    $scope.active = function(name) {
        return ($route.current && ($route.current.activeTab === name)) ? 'active' : '';
    };
}
<commit_msg>fehlendes use strict<commit_after>function AppCtrl ($scope) {
    'use strict';
    $scope.title = 'The Movie Database';
}

function WelcomeCtrl ($scope, moviesResponse) {
    'use strict';
    $scope.movies = moviesResponse.data;
    $scope.nav = 'home';
}

function MoviesListCtrl ($scope, $location, moviesResponse) {
    'use strict';
    $scope.nav = 'movies';
    $scope.movies = moviesResponse.data;
    $scope.add = function () {
        $location.path('/movies/new');
    };
}

MoviesListCtrl.resolve = {
    moviesResponse: function ($http) {
        'use strict';
        return $http.get('/movies');
    }
};

function MoviesAddCtrl ($scope, $http, $location) {
    'use strict';
    $scope.movie = {};
    $scope.save = function (movie) {
        $http.post('/movies', movie)
        .success(function(res) {
            $location.path('/movies/' + res.id);
        });
    };
}

function MovieDetailCtrl ($scope, $http, $location, moviesResponse) {
    'use strict';
    $scope.movie = moviesResponse.data;

    $scope['delete'] = function () {
        $http['delete']('/movies/' + $scope.movie.id).success(function (res) {
            $location.path('/movies');
        });
    };
}

function movieDetailResolver ($http, $route) {
    'use strict';
    var id = $route.current.params.id;
    return $http.get('/movies/' + id);
}

MovieDetailCtrl.resolve = {
    moviesResponse: movieDetailResolver
};

function MovieEditCtrl ($scope, $http, $location, moviesResponse) {
    'use strict';
    $scope.movie = moviesResponse.data;

    $scope.save = function () {
        $http.put('/movies/' + $scope.movie.id, $scope.movie)
        .success(function (res) {
            $location.path('/movies/' + $scope.movie.id);
        });
    };
}

MovieEditCtrl.resolve = {
    moviesResponse: movieDetailResolver
};

function NotFoundCtrl ($scope, $location) {
    'use strict';
    $scope.culprit = $location.search().culprit || 'unknown beast';
}

var ErrorCtrl = NotFoundCtrl;

function HeaderController($scope, $route) {
    'use strict';
    $scope.active = function(name) {
        return ($route.current && ($route.current.activeTab === name)) ? 'active' : '';
    };
}
<|endoftext|>


<commit_before>var mongoose = require('mongoose'),
    User = mongoose.model('User'),
    Account = mongoose.model('Account'),
    Assignment = mongoose.model('Assignment')

exports.try = function(req, res) {
  Assignment
      .find({
      })
      .exec(function(err, assignmentResult) {
        if(err) return next(err);

        var ID = [];
        var Numbers = {};

        var both, one, neither;
        both = one = neither = 0;

        for(assignment in assignmentResult) {
          if(assignmentResult[assignment].assignmentNumber == "" && assignmentResult[assignment].subAssignment == "")
            both++;
          else if(assignmentResult[assignment].assignmentNumber == "" || assignmentResult[assignment].subAssignment == "") {
            one++;
          } else
            neither++;

          ID.push(assignmentResult[assignment].assignmentID)

          if(Numbers.hasOwnProperty(assignmentResult[assignment].assignmentNumber)) {
            Numbers[assignmentResult[assignment].assignmentNumber] += 1;
          } else {
            Numbers[assignmentResult[assignment].assignmentNumber] = 0;
          }
        }

        console.log("Unique IDs " + ID.length)
        // for(i in ID) {
        //   console.log(ID[i])
        // }

        console.log("Groups of Assignment IDS ")
        for(var i in Numbers) {
          console.log(i, Numbers[i]);
        }

        console.log("--");
        console.log("With both: ", both)
        console.log("With one: ", one)
        console.log("With neither: ", neither)

      })
}

exports.testing = function(req, res, next) {

  Assignment
      .find({
        "assignmentNumber": {$exists: false},
        "subAssignment": {$exists: false},
        "email": "dburlins@uncc.edu"
      })
      .limit(100)
      .exec(function(err, assignmentResult) {
        if(err) return next(err);

        //return next(assignmentResult.length);

        var numUpdated = 0;
        var numDeleted = 0;
        var numTotal = assignmentResult.length;
        var numToModify = 0;
        var numShouldDelete = 0;
        var numShouldUpdate = 0;
        var numSkipped = 0;

        for(assignment in assignmentResult) {
          if(assignmentResult[assignment].assignmentNumber == "" || assignmentResult[assignment].subAssignment == "") {
            numToModify++;
            var assignmentID = assignmentResult[assignment].assignmentID;
            var assignmentRaw = assignmentID.split(".");

            if(assignmentRaw.length < 2) {
              numSkipped++;
              continue;
            }

            var assignmentNumber = assignmentRaw[0];
            var subAssignment = assignmentRaw[1];

            return next("(num skipped:) " + numSkipped +" "+ assignmentResult[assignment] +" "+ assignmentID +" "+ assignmentNumber +" "+ subAssignment)

              // Update assignments, deleting any with erroneous assignmentID

              if(subAssignment.length > 2) {
                numShouldDelete++;
                 //remove all assignments with ridiculous decimal subAssignment
                Assignment
                  .remove({
                    "assignmentID": assignmentID
                  })
                  .exec(function(err, result){
                      if(err) return next(err)
                      numDeleted++;
                  })
                } else {

                numShouldUpdate++;
                //Update assignments to all use assignmentNumber and subAssignment number! (Won't delete anything)
                Assignment
                  .update(
                      {
                        assignmentID: assignmentID
                      },
                      {
                        $set:
                        {
                          assignmentNumber: assignmentNumber,
                          subAssignment: subAssignment
                        }
                      }
                    )
                    .exec(function(err, result) {
                      if(err) return next(err)
                      //console.log("updated assignment ", assignmentID)
                      numUpdated++;

                    })

                }
              }
        }

        return next("Num skipped: " + numSkipped + ", Num to modify: " + numToModify + ", Num should delete: " + numShouldDelete + ", Num deleted " + numDeleted + ", Number should Update: " + numShouldUpdate + ", Number updated " + numUpdated)
      });

}

exports.frustrated = function(req, res, next) {

  Assignment
      .find({
        "assignmentNumber": {$exists: false},
        "subAssignment": {$exists: false},
        "email": "dburlins@uncc.edu"
      })
      //.limit(100)
      .exec(function(err, assignmentResult) {
        if(err) return next(err);

        var numUpdated = 0;
        var numDeleted = 0;
        var numTotal = assignmentResult.length;
        var numToModify = 0;
        var numShouldDelete = 0;
        var numShouldUpdate = 0;
        var numSkipped = 0;
var county = 0;
var county1 = 0;
        var ids = "";
        var id = [];

        for(assignment in assignmentResult) {
          //if(assignmentResult[assignment].assignmentNumber == "" || assignmentResult[assignment].subAssignment == "") {
            numToModify++;
            var assignmentID = assignmentResult[assignment].assignmentID;
            var assignmentRaw = assignmentID.split(".");

            if(assignmentRaw.length < 2) {
              numSkipped++;
              continue;
            }

            var assignmentNumber = assignmentRaw[0];
            var subAssignment = assignmentRaw[1];

            if(subAssignment == "0") subAssignment = "00";

            ids += assignmentID + " ";
            id.push(assignmentID);
        //  }
        }

        // for(x in id) {
        //   county1++;
        //   var assignmentRaw = id[x];
        //   var num = assignmentRaw[0];
        //   var sub = assignmentRaw[1];
        //
        //   Assignment
        //     .update(
        //         {
        //           assignmentID: assignmentRaw
        //         },
        //         {
        //           $set:
        //           {
        //             assignmentNumber: num,
        //             subAssignment: sub
        //           }
        //         }
        //       )
        //       .exec(function(err, result) {
        //         if(err) return next(err)
        //         county++;
        //       })
        // }

        //return next(county + "/" + county1 +" updated");
        return next("to modify: (", id.length, ") ", ids);

      });

}

exports.trial = function(req, res, next) {

  Assignment
      .find({
        "email": "dburlins@uncc.edu",
        "assignmentNumber": {$exists: false},
        "subAssignment": {$exists: false}
      })
      .limit(100)
      .exec(function(err, result){

        for(a in result) {
          var tmp = result[a];
          var assignmentID = tmp.assignmentID;
          var assignmentRaw = assignmentID.split(".");

          // skips
          if(assignmentRaw.length < 2) {
            numSkipped++;
            continue;
          }

          var assignmentNumber = assignmentRaw[0];
          var subAssignment = assignmentRaw[1];

          ids += assignmentID + " ";
          id.push(assignmentID);
          }
          }

          for(x in id) {
          county1++;
          var assignmentRaw = id[x];
          var num = assignmentRaw[0];
          var sub = assignmentRaw[1];

          Assignment
          .update(
              {
                assignmentID: assignmentRaw
              },
              {
                $set:
                {
                  assignmentNumber: num,
                  subAssignment: sub
                }
              }
            )
            .exec(function(err, result) {
              if(err) return next(err)
              county++;
            })
          }
    }
<commit_msg>Testing assignments<commit_after>var mongoose = require('mongoose'),
    User = mongoose.model('User'),
    Account = mongoose.model('Account'),
    Assignment = mongoose.model('Assignment')

exports.try = function(req, res) {
  Assignment
      .find({
      })
      .exec(function(err, assignmentResult) {
        if(err) return next(err);

        var ID = [];
        var Numbers = {};

        var both, one, neither;
        both = one = neither = 0;

        for(assignment in assignmentResult) {
          if(assignmentResult[assignment].assignmentNumber == "" && assignmentResult[assignment].subAssignment == "")
            both++;
          else if(assignmentResult[assignment].assignmentNumber == "" || assignmentResult[assignment].subAssignment == "") {
            one++;
          } else
            neither++;

          ID.push(assignmentResult[assignment].assignmentID)

          if(Numbers.hasOwnProperty(assignmentResult[assignment].assignmentNumber)) {
            Numbers[assignmentResult[assignment].assignmentNumber] += 1;
          } else {
            Numbers[assignmentResult[assignment].assignmentNumber] = 0;
          }
        }

        console.log("Unique IDs " + ID.length)
        // for(i in ID) {
        //   console.log(ID[i])
        // }

        console.log("Groups of Assignment IDS ")
        for(var i in Numbers) {
          console.log(i, Numbers[i]);
        }

        console.log("--");
        console.log("With both: ", both)
        console.log("With one: ", one)
        console.log("With neither: ", neither)

      })
}

exports.testing = function(req, res, next) {

  Assignment
      .find({
        "assignmentNumber": {$exists: false},
        "subAssignment": {$exists: false},
        "email": "dburlins@uncc.edu"
      })
      .limit(100)
      .exec(function(err, assignmentResult) {
        if(err) return next(err);

        //return next(assignmentResult.length);

        var numUpdated = 0;
        var numDeleted = 0;
        var numTotal = assignmentResult.length;
        var numToModify = 0;
        var numShouldDelete = 0;
        var numShouldUpdate = 0;
        var numSkipped = 0;

        for(assignment in assignmentResult) {
          if(assignmentResult[assignment].assignmentNumber == "" || assignmentResult[assignment].subAssignment == "") {
            numToModify++;
            var assignmentID = assignmentResult[assignment].assignmentID;
            var assignmentRaw = assignmentID.split(".");

            if(assignmentRaw.length < 2) {
              numSkipped++;
              continue;
            }

            var assignmentNumber = assignmentRaw[0];
            var subAssignment = assignmentRaw[1];

            return next("(num skipped:) " + numSkipped +" "+ assignmentResult[assignment] +" "+ assignmentID +" "+ assignmentNumber +" "+ subAssignment)

              // Update assignments, deleting any with erroneous assignmentID

              if(subAssignment.length > 2) {
                numShouldDelete++;
                 //remove all assignments with ridiculous decimal subAssignment
                Assignment
                  .remove({
                    "assignmentID": assignmentID
                  })
                  .exec(function(err, result){
                      if(err) return next(err)
                      numDeleted++;
                  })
                } else {

                numShouldUpdate++;
                //Update assignments to all use assignmentNumber and subAssignment number! (Won't delete anything)
                Assignment
                  .update(
                      {
                        assignmentID: assignmentID
                      },
                      {
                        $set:
                        {
                          assignmentNumber: assignmentNumber,
                          subAssignment: subAssignment
                        }
                      }
                    )
                    .exec(function(err, result) {
                      if(err) return next(err)
                      //console.log("updated assignment ", assignmentID)
                      numUpdated++;

                    })

                }
              }
        }

        return next("Num skipped: " + numSkipped + ", Num to modify: " + numToModify + ", Num should delete: " + numShouldDelete + ", Num deleted " + numDeleted + ", Number should Update: " + numShouldUpdate + ", Number updated " + numUpdated)
      });

}

exports.frustrated = function(req, res, next) {

  Assignment
      .find({
        "assignmentNumber": {$exists: false},
        "subAssignment": {$exists: false},
        "email": "dburlins@uncc.edu"
      })
      //.limit(100)
      .exec(function(err, assignmentResult) {
        if(err) return next(err);

        var numUpdated = 0;
        var numDeleted = 0;
        var numTotal = assignmentResult.length;
        var numToModify = 0;
        var numShouldDelete = 0;
        var numShouldUpdate = 0;
        var numSkipped = 0;
var county = 0;
var county1 = 0;
        var ids = "";
        var id = [];

        for(assignment in assignmentResult) {
          //if(assignmentResult[assignment].assignmentNumber == "" || assignmentResult[assignment].subAssignment == "") {
            numToModify++;
            var assignmentID = assignmentResult[assignment].assignmentID;
            var assignmentRaw = assignmentID.split(".");

            if(assignmentRaw.length < 2) {
              numSkipped++;
              continue;
            }

            var assignmentNumber = assignmentRaw[0];
            var subAssignment = assignmentRaw[1];

            if(subAssignment == "0") subAssignment = "00";

            ids += assignmentID + " ";
            id.push(assignmentID);
        //  }
        }

        // for(x in id) {
        //   county1++;
        //   var assignmentRaw = id[x];
        //   var num = assignmentRaw[0];
        //   var sub = assignmentRaw[1];
        //
        //   Assignment
        //     .update(
        //         {
        //           assignmentID: assignmentRaw
        //         },
        //         {
        //           $set:
        //           {
        //             assignmentNumber: num,
        //             subAssignment: sub
        //           }
        //         }
        //       )
        //       .exec(function(err, result) {
        //         if(err) return next(err)
        //         county++;
        //       })
        // }

        //return next(county + "/" + county1 +" updated");
        return next("to modify: (", id.length, ") ", ids);

      });

}

// exports.trial = function(req, res, next) {
//
//   Assignment
//       .find({
//         "email": "dburlins@uncc.edu",
//         "assignmentNumber": {$exists: false},
//         "subAssignment": {$exists: false}
//       })
//       .limit(100)
//       .exec(function(err, result){
//
//         for(a in result) {
//           var tmp = result[a];
//           var assignmentID = tmp.assignmentID;
//           var assignmentRaw = assignmentID.split(".");
//
//           // skips
//           if(assignmentRaw.length < 2) {
//             numSkipped++;
//             continue;
//           }
//
//           var assignmentNumber = assignmentRaw[0];
//           var subAssignment = assignmentRaw[1];
//
//           ids += assignmentID + " ";
//           id.push(assignmentID);
//           }
//           }
//
//           for(x in id) {
//           county1++;
//           var assignmentRaw = id[x];
//           var num = assignmentRaw[0];
//           var sub = assignmentRaw[1];
//
//           Assignment
//           .update(
//               {
//                 assignmentID: assignmentRaw
//               },
//               {
//                 $set:
//                 {
//                   assignmentNumber: num,
//                   subAssignment: sub
//                 }
//               }
//             )
//             .exec(function(err, result) {
//               if(err) return next(err)
//               county++;
//             })
//           }
//     }
<|endoftext|>


<commit_before>'use strict';

/**
 * Constants definition.
 *
 * author: Michael Liao
 */

module.exports = {
    // user role:
    role: {
        ADMIN:       0,
        EDITOR:      10,
        CONTRIBUTOR: 100,
        SUBSCRIBER:  10000,
        GUEST:       100000000
    },

    signin: {
        LOCAL: 'local'
    },

    // cache keys:
    cache: {
        NAVIGATIONS: '__navigations__',
        CATEGORIES: '__categories__',
        WEBSITE: '__website__',
        SNIPPETS: '__snippet__'
    },

    // queue name:
    queue: {
        MAIL: 'queueMail',
        SNS: 'queueSNS'
    }
};
<commit_msg>add new cache key<commit_after>'use strict';

/**
 * Constants definition.
 *
 * author: Michael Liao
 */

module.exports = {
    // user role:
    role: {
        ADMIN:       0,
        EDITOR:      10,
        CONTRIBUTOR: 100,
        SUBSCRIBER:  10000,
        GUEST:       100000000
    },

    signin: {
        LOCAL: 'local'
    },

    // cache keys:
    cache: {
        NAVIGATIONS: '__navigations__',
        CATEGORIES: '__categories__',
        ARTICLE_FEED: '__articlefeed__',
        WEBSITE: '__website__',
        SNIPPETS: '__snippet__'
    },

    // queue name:
    queue: {
        MAIL: 'queueMail',
        SNS: 'queueSNS'
    }
};
<|endoftext|>


<commit_before>/*
    Agora Forum Software
    Copyright (C) 2016 Gregory Sartucci
    License: AGPL-3.0, Check file LICENSE
*/

/**
 * The main view consists of the following basic modules:
 *
 *    * Main Module (main.js)
 *          This file; the primary entry-point and handler for the other four modules.
 *          Callbacks are mostly set up and destroyed in this module.
 *
 *    * Layout (layout.js)
 *          Chooses positions for posts.
 *
 *    * Camera (camera.js)
 *          Stores client view state (position, zoom, screen boundaries).
 *          Also handles camera input.
 *
 *    * Partitioner (partitioner.js)
 *          An optimization module. Exposes a number of efficient spatial queries.
 *          Depends on the camera.
 *
 *    * Renderer (renderer.js)
 *          Handles the WebGL context and performs canvas rendering.
 *          Depends on the camera.
 *
 *    * Detailed Posts (detailed/detailed.js)
 *          Handles the creation of template-based HTML posts.
 *          These detailed posts appear when the camera is sufficiently zoomed.
 *          Depends on the camera and partitioner.
 *
 *    * Reply (reply/reply.js)
 *          Handles the reply box and related code.
 *
 *    * Report (report/report.js)
 *          Handles the report box and related code.
 *
 */

Template.mainView.onCreated(function() {
    let instance = this;

    //Declare modules
    this.layout = new MainViewLayout();
    this.camera = new MainViewCamera();
    this.partitioner = new MainViewPartitioner(this.camera);
    this.renderer = new MainViewRenderer(this.camera, this.layout);
    this.detailedPosts = new MainViewDetailedPosts(this.camera, this.partitioner);
    let modules = [this.camera, this.partitioner, this.renderer, this.detailedPosts];

    Template.body.camera = this.camera;

    //Set up async notifiers.
    this.onRendered = new Notifier();
    let onSubReady = new Notifier();

    this.subscribe(this.data.subscription, {onReady: onSubReady.fulfill});
    this.targetPost = new ReactiveVar();
    this.targetMode = new ReactiveVar();
    this.reportTarget = new ReactiveVar();
    this.isSizeDirty = true;

    this.isReplyBoxOpen = function() {
        return instance.targetPost.get() !== undefined;
    };

    this.removePost = function(post) {

        //First, remove a post from the layout.
        let results = instance.layout.removePost(post);

        //Then, for each of the other modules:
        for (let module of modules) {

            //Adjust all the posts displaced by this.
            for (let updatedPost of results.changedPosts) {
                module.updatePost(updatedPost._id, updatedPost);
            }

            //and remove the post.
            module.removePost(results.post);
        }

        //Finally, re-do the partitioner.
        instance.partitioner.init(instance.layout.getPosts());
    }

    this.addPost = function(post) {

        if (!post) return;

        //First, check to make sure the post is not already present
        if (instance.layout.getPost(post._id)) return;

        //Then add it to the layout.
        let results = instance.layout.addPost(post);

        //Then, for each of the other modules:
        for (let module of modules) {

            //Adjust all the posts displaced by this.
            for (let updatedPost of results.changedPosts) {
                module.updatePost(updatedPost._id, updatedPost);
            }
            //and add the new post.
            module.addPost(results.post);
        }

        //Finally, re-do the partitioner.
        instance.partitioner.init(instance.layout.getPosts());
    }

    this.addPostByID = function(id) {
        this.addPost(Posts.findOne({_id: id}));
    }

    Notifier.all(onSubReady, this.onRendered).onFulfilled(function() {
        //Perform initial setup.
        let postCursor = Posts.find({});

        let initPostArray = instance.layout.init(postCursor.fetch());

        for (let module of modules) {
            module.init(initPostArray);
        }

        //Callback for removed posts.
        instance.postObserver = postCursor.observe({
            removed: function(post) {
                instance.removePost(post);
            }
        });

        //Callback for changed post positions.
        instance.changeObserver = postCursor.observeChanges({
            changed: function(id, fields) {
                instance.layout.updatePost(id, fields);
                for (let module of modules) {
                    module.updatePost(id, fields);
                }
            }
        });

        //Change whether or not a post has been seen.
        instance.userObserver = Meteor.users.find({_id: Meteor.userId()}).observeChanges({
            changed: function(id, fields) {
                if (!fields.seenPosts) return;
                for (let postID of fields.seenPosts)
                    instance.renderer.seePost(postID);
            }
        });

        let t0 = performance.now();

        //Begin rendering.
        let render = function() {
            if (instance.isDestroyed) {
                return;
            }

            let t1 = performance.now();
            let dt = (t1 - t0)/1000.0;

            instance.canvas[0].width = instance.canvas.width();
            instance.canvas[0].height = instance.canvas.height();

            instance.camera.step(dt);
            instance.renderer.render();
            instance.detailedPosts.update();
            window.requestAnimationFrame(render);
            t0 = t1;
        };

        window.requestAnimationFrame(render);

        instance.autorun(
            function() {
                let post = instance.layout.getPost(Iron.controller().state.get('postID'));
                if (post) {
                    instance.camera.goToPos(post.position);
                }
                return;
            }
        );
    });
});

Template.mainView.onRendered(function() {
    let instance = this;

    //Initialize everything that depends on the canvas existing.
    let canvas = $('#main-viewport');

    this.canvas = canvas;
    this.camera.construct(canvas);
    this.renderer.construct(canvas);
    this.onRendered.fulfill();

    this.getMousePos = function(event) {
        return {x:event.pageX, y:event.pageY - canvas.offset().top};
    };

    this.getTouchPos = function(event) {
        let ret = [];
        for (touch of event.touches) {
            ret.push({x: touch.pageX, y: touch.pageY - canvas.offset().top})
        }
        return ret;
    }
});

Template.mainView.helpers({
    detailedPosts: function() {
        return Template.instance().detailedPosts.find();
    },
    showFullPosts: function() {
        return Template.instance().detailedPosts.showFullPosts.get();
    },
    targetPost: function() {
        return Template.instance().targetPost.get();
    },
    reportTarget: function() {
        return Template.instance().reportTarget.get();
    }
});

Template.mainView.events({
    'mousedown': function(event, instance) {
        if (instance.camera) {
            instance.camera.mouseDown(instance.getMousePos(event), event.button);
        }
    },
    'touchstart': function(event, instance) {
        event.preventDefault();
        var touches = instance.getTouchPos(event.originalEvent);
        if (instance.camera) {
            instance.camera.touchStart(touches);
        }
    },
    'mousemove': function(event, instance) {
        if (instance.camera) {
            instance.camera.mouseMove(instance.getMousePos(event));
        }
    },
    'touchmove': function(event, instance) {
        event.preventDefault();
        var touches = instance.getTouchPos(event.originalEvent);
        if (instance.camera) {
            instance.camera.touchMove(touches);
        }
    },
    'mouseup': function(event, instance) {
        if (instance.camera) {
            instance.camera.mouseUp(instance.getMousePos(event), event.button);
        }
    },
    'touchend': function(event, instance) {
        event.preventDefault();
        var touches = instance.getTouchPos(event.originalEvent);
        if (instance.camera) {
            instance.camera.touchEnd(touches);
        }
    },
    'mouseleave': function(event, instance) {
        //Stop dragging if we leave the canvas area. We can't see mouseup events if they are outside of the window.
        if (instance.camera && $('#main-container').is(event.target)) {
            instance.camera.mouseUp(instance.getMousePos(event), 0);
        }
    },
    'touchleave': function(event, instance) {
        event.preventDefault();
        var touches = instance.getTouchPos(event.originalEvent);
        if (instance.camera && $('#main-container').is(event.target)) {
            instance.camera.touchEnd(touches);
        }
    },
    'wheel': function(event, instance) {
        if (instance.camera) {
            //Normalize across browsers.
            //Will not respond properly to very fast scrolling, but whatever.
            instance.camera.mouseWheel(event.originalEvent.deltaY > 0 ? 1.0 : -1.0);
        }
    }
});

Template.mainView.onDestroyed(function() {
    if (this.postObserver) this.postObserver.stop();
    if(this.changeObserver) this.changeObserver.stop();
    this.isDestroyed = true;
});

Template.mainZoomControl.getParents();

Template.mainZoomControl.onRendered(function() {
    this.slider = $('#main-zoom-control-slider');
    let instance = this;
    this.parent.camera.onZoom(function(camera) {
        instance.slider.val(camera.getZoomFraction()*100.0);
    });
});

Template.mainZoomControl.events({
    'mousedown, touchstart, mousemove, touchmove, mouseup, touchend, wheel': function(event, instance) {
        if (instance.parent.camera.isDragging()) {
            //Prevents interaction while dragging.
            event.preventDefault();
        }
        else {
            //Prevent events from passing through posts into the WebGL canvas.
            event.stopImmediatePropagation();
        }
    },
    'input': function() {
        let instance = Template.instance();
        instance.parent.camera.setZoomFraction(instance.slider.val()/100.0);
    },
    "click #main-zoom-plus-button": function() {
        let instance = Template.instance();
        instance.parent.camera.setZoomFraction(instance.parent.camera.getZoomFraction() + 0.01);
    },
    "click #main-zoom-minus-button": function() {
        let instance = Template.instance();
        instance.parent.camera.setZoomFraction(instance.parent.camera.getZoomFraction() - 0.01);
    },
    "click #main-zoom-up-button": function() {
        let instance = Template.instance();
        instance.parent.camera.buttonPressed("ButtonUp");
    },
    "click #main-zoom-down-button": function() {
        let instance = Template.instance();
        instance.parent.camera.buttonPressed("ButtonDown");
    },
    "click #main-zoom-left-button": function() {
        let instance = Template.instance();
        instance.parent.camera.buttonPressed("ButtonLeft");
    },
    "click #main-zoom-right-button": function() {
        let instance = Template.instance();
        instance.parent.camera.buttonPressed("ButtonRight");
    },
    "keydown #main-zoom-control-slider": function(e, data, tpl) {
        // e -> jquery event
        // data -> Blaze data context of the DOM element triggering the event handler
        // tpl -> the parent template instance for the target element

        if (e.key.startsWith("Arrow")) {
            e.stopImmediatePropagation();
        } else if (e.key == "-") {
            let instance = Template.instance();
            instance.parent.camera.setZoomFraction(instance.parent.camera.getZoomFraction() - 0.01);
        } else if (e.key == "+") {
            let instance = Template.instance();
            instance.parent.camera.setZoomFraction(instance.parent.camera.getZoomFraction() + 0.01);
        }
    },
    "keyup #main-zoom-control-slider": function(e, data, tpl) {
        // e -> jquery event
        // data -> Blaze data context of the DOM element triggering the event handler
        // tpl -> the parent template instance for the target element

        if (e.key.startsWith("Arrow")) {
            e.stopImmediatePropagation();
        } else if (e.key == "-" || e.key == "+") {
            Template.body.camera.keyReleased(e.key);
        }
    }
});

//code for catching key events globally.
Template.body.events({
    "keydown": function(e, data, tpl) {
        // e -> jquery event
        // data -> Blaze data context of the DOM element triggering the event handler
        // tpl -> the parent template instance for the target element

        if (e.key.startsWith("Arrow") || e.key == "-" || e.key == "+") {
            Template.body.camera.keyPressed(e.key);
        }
    },
    "keyup": function(e, data, tpl) {
        // e -> jquery event
        // data -> Blaze data context of the DOM element triggering the event handler
        // tpl -> the parent template instance for the target element

        if (e.key.startsWith("Arrow") || e.key == "-" || e.key == "+") {
            Template.body.camera.keyReleased(e.key);
        }
    }
})
<commit_msg>expand main forum view to work with different subscirptions<commit_after>/*
    Agora Forum Software
    Copyright (C) 2016 Gregory Sartucci
    License: AGPL-3.0, Check file LICENSE
*/

/**
 * The main view consists of the following basic modules:
 *
 *    * Main Module (main.js)
 *          This file; the primary entry-point and handler for the other four modules.
 *          Callbacks are mostly set up and destroyed in this module.
 *
 *    * Layout (layout.js)
 *          Chooses positions for posts.
 *
 *    * Camera (camera.js)
 *          Stores client view state (position, zoom, screen boundaries).
 *          Also handles camera input.
 *
 *    * Partitioner (partitioner.js)
 *          An optimization module. Exposes a number of efficient spatial queries.
 *          Depends on the camera.
 *
 *    * Renderer (renderer.js)
 *          Handles the WebGL context and performs canvas rendering.
 *          Depends on the camera.
 *
 *    * Detailed Posts (detailed/detailed.js)
 *          Handles the creation of template-based HTML posts.
 *          These detailed posts appear when the camera is sufficiently zoomed.
 *          Depends on the camera and partitioner.
 *
 *    * Reply (reply/reply.js)
 *          Handles the reply box and related code.
 *
 *    * Report (report/report.js)
 *          Handles the report box and related code.
 *
 */

Template.mainView.onCreated(function() {
    let instance = this;

    //Declare modules
    this.layout = new MainViewLayout();
    this.camera = new MainViewCamera();
    this.partitioner = new MainViewPartitioner(this.camera);
    this.renderer = new MainViewRenderer(this.camera, this.layout);
    this.detailedPosts = new MainViewDetailedPosts(this.camera, this.partitioner);
    let modules = [this.camera, this.partitioner, this.renderer, this.detailedPosts];

    Template.body.camera = this.camera;

    //Set up async notifiers.
    this.onRendered = new Notifier();
    let onSubReady = new Notifier();

    if (this.data.subscription) {
        if (this.data.arg) {
            console.log(this.data.arg);
            this.subscribe(this.data.subscription, this.data.arg, {onReady: onSubReady.fulfill});
        } else this.subscribe(this.data.subscription, {onReady: onSubReady.fulfill});
    }
    this.targetPost = new ReactiveVar();
    this.targetMode = new ReactiveVar();
    this.reportTarget = new ReactiveVar();
    this.isSizeDirty = true;

    this.isReplyBoxOpen = function() {
        return instance.targetPost.get() !== undefined;
    };

    this.removePost = function(post) {

        //First, remove a post from the layout.
        let results = instance.layout.removePost(post);

        //Then, for each of the other modules:
        for (let module of modules) {

            //Adjust all the posts displaced by this.
            for (let updatedPost of results.changedPosts) {
                module.updatePost(updatedPost._id, updatedPost);
            }

            //and remove the post.
            module.removePost(results.post);
        }

        //Finally, re-do the partitioner.
        instance.partitioner.init(instance.layout.getPosts());
    }

    this.addPost = function(post) {

        if (!post) return;

        //First, check to make sure the post is not already present
        if (instance.layout.getPost(post._id)) return;

        //Then add it to the layout.
        let results = instance.layout.addPost(post);

        //Then, for each of the other modules:
        for (let module of modules) {

            //Adjust all the posts displaced by this.
            for (let updatedPost of results.changedPosts) {
                module.updatePost(updatedPost._id, updatedPost);
            }
            //and add the new post.
            module.addPost(results.post);
        }

        //Finally, re-do the partitioner.
        instance.partitioner.init(instance.layout.getPosts());
    }

    this.addPostByID = function(id) {
        this.addPost(Posts.findOne({_id: id}));
    }

    Notifier.all(onSubReady, this.onRendered).onFulfilled(function() {
        //Perform initial setup.
        let postCursor = Posts.find({});

        let initPostArray = instance.layout.init(postCursor.fetch());

        for (let module of modules) {
            module.init(initPostArray);
        }

        //Callback for removed posts.
        instance.postObserver = postCursor.observe({
            removed: function(post) {
                instance.removePost(post);
            }
        });

        //Callback for changed post positions.
        instance.changeObserver = postCursor.observeChanges({
            changed: function(id, fields) {
                instance.layout.updatePost(id, fields);
                for (let module of modules) {
                    module.updatePost(id, fields);
                }
            }
        });

        //Change whether or not a post has been seen.
        instance.userObserver = Meteor.users.find({_id: Meteor.userId()}).observeChanges({
            changed: function(id, fields) {
                if (!fields.seenPosts) return;
                for (let postID of fields.seenPosts)
                    instance.renderer.seePost(postID);
            }
        });

        let t0 = performance.now();

        //Begin rendering.
        let render = function() {
            if (instance.isDestroyed) {
                return;
            }

            let t1 = performance.now();
            let dt = (t1 - t0)/1000.0;

            instance.canvas[0].width = instance.canvas.width();
            instance.canvas[0].height = instance.canvas.height();

            instance.camera.step(dt);
            instance.renderer.render();
            instance.detailedPosts.update();
            window.requestAnimationFrame(render);
            t0 = t1;
        };

        window.requestAnimationFrame(render);

        instance.autorun(
            function() {
                let post = instance.layout.getPost(Iron.controller().state.get('postID'));
                if (post) {
                    instance.camera.goToPos(post.position);
                }
                return;
            }
        );
    });
});

Template.mainView.onRendered(function() {
    let instance = this;

    //Initialize everything that depends on the canvas existing.
    let canvas = $('#main-viewport');

    this.canvas = canvas;
    this.camera.construct(canvas);
    this.renderer.construct(canvas);
    this.onRendered.fulfill();

    this.getMousePos = function(event) {
        return {x:event.pageX, y:event.pageY - canvas.offset().top};
    };

    this.getTouchPos = function(event) {
        let ret = [];
        for (touch of event.touches) {
            ret.push({x: touch.pageX, y: touch.pageY - canvas.offset().top})
        }
        return ret;
    }
});

Template.mainView.helpers({
    detailedPosts: function() {
        return Template.instance().detailedPosts.find();
    },
    showFullPosts: function() {
        return Template.instance().detailedPosts.showFullPosts.get();
    },
    targetPost: function() {
        return Template.instance().targetPost.get();
    },
    reportTarget: function() {
        return Template.instance().reportTarget.get();
    }
});

Template.mainView.events({
    'mousedown': function(event, instance) {
        if (instance.camera) {
            instance.camera.mouseDown(instance.getMousePos(event), event.button);
        }
    },
    'touchstart': function(event, instance) {
        event.preventDefault();
        var touches = instance.getTouchPos(event.originalEvent);
        if (instance.camera) {
            instance.camera.touchStart(touches);
        }
    },
    'mousemove': function(event, instance) {
        if (instance.camera) {
            instance.camera.mouseMove(instance.getMousePos(event));
        }
    },
    'touchmove': function(event, instance) {
        event.preventDefault();
        var touches = instance.getTouchPos(event.originalEvent);
        if (instance.camera) {
            instance.camera.touchMove(touches);
        }
    },
    'mouseup': function(event, instance) {
        if (instance.camera) {
            instance.camera.mouseUp(instance.getMousePos(event), event.button);
        }
    },
    'touchend': function(event, instance) {
        event.preventDefault();
        var touches = instance.getTouchPos(event.originalEvent);
        if (instance.camera) {
            instance.camera.touchEnd(touches);
        }
    },
    'mouseleave': function(event, instance) {
        //Stop dragging if we leave the canvas area. We can't see mouseup events if they are outside of the window.
        if (instance.camera && $('#main-container').is(event.target)) {
            instance.camera.mouseUp(instance.getMousePos(event), 0);
        }
    },
    'touchleave': function(event, instance) {
        event.preventDefault();
        var touches = instance.getTouchPos(event.originalEvent);
        if (instance.camera && $('#main-container').is(event.target)) {
            instance.camera.touchEnd(touches);
        }
    },
    'wheel': function(event, instance) {
        if (instance.camera) {
            //Normalize across browsers.
            //Will not respond properly to very fast scrolling, but whatever.
            instance.camera.mouseWheel(event.originalEvent.deltaY > 0 ? 1.0 : -1.0);
        }
    }
});

Template.mainView.onDestroyed(function() {
    if (this.postObserver) this.postObserver.stop();
    if(this.changeObserver) this.changeObserver.stop();
    this.isDestroyed = true;
});

Template.mainZoomControl.getParents();

Template.mainZoomControl.onRendered(function() {
    this.slider = $('#main-zoom-control-slider');
    let instance = this;
    this.parent.camera.onZoom(function(camera) {
        instance.slider.val(camera.getZoomFraction()*100.0);
    });
});

Template.mainZoomControl.events({
    'mousedown, touchstart, mousemove, touchmove, mouseup, touchend, wheel': function(event, instance) {
        if (instance.parent.camera.isDragging()) {
            //Prevents interaction while dragging.
            event.preventDefault();
        }
        else {
            //Prevent events from passing through posts into the WebGL canvas.
            event.stopImmediatePropagation();
        }
    },
    'input': function() {
        let instance = Template.instance();
        instance.parent.camera.setZoomFraction(instance.slider.val()/100.0);
    },
    "click #main-zoom-plus-button": function() {
        let instance = Template.instance();
        instance.parent.camera.setZoomFraction(instance.parent.camera.getZoomFraction() + 0.01);
    },
    "click #main-zoom-minus-button": function() {
        let instance = Template.instance();
        instance.parent.camera.setZoomFraction(instance.parent.camera.getZoomFraction() - 0.01);
    },
    "click #main-zoom-up-button": function() {
        let instance = Template.instance();
        instance.parent.camera.buttonPressed("ButtonUp");
    },
    "click #main-zoom-down-button": function() {
        let instance = Template.instance();
        instance.parent.camera.buttonPressed("ButtonDown");
    },
    "click #main-zoom-left-button": function() {
        let instance = Template.instance();
        instance.parent.camera.buttonPressed("ButtonLeft");
    },
    "click #main-zoom-right-button": function() {
        let instance = Template.instance();
        instance.parent.camera.buttonPressed("ButtonRight");
    },
    "keydown #main-zoom-control-slider": function(e, data, tpl) {
        // e -> jquery event
        // data -> Blaze data context of the DOM element triggering the event handler
        // tpl -> the parent template instance for the target element

        if (e.key.startsWith("Arrow")) {
            e.stopImmediatePropagation();
        } else if (e.key == "-") {
            let instance = Template.instance();
            instance.parent.camera.setZoomFraction(instance.parent.camera.getZoomFraction() - 0.01);
        } else if (e.key == "+") {
            let instance = Template.instance();
            instance.parent.camera.setZoomFraction(instance.parent.camera.getZoomFraction() + 0.01);
        }
    },
    "keyup #main-zoom-control-slider": function(e, data, tpl) {
        // e -> jquery event
        // data -> Blaze data context of the DOM element triggering the event handler
        // tpl -> the parent template instance for the target element

        if (e.key.startsWith("Arrow")) {
            e.stopImmediatePropagation();
        } else if (e.key == "-" || e.key == "+") {
            Template.body.camera.keyReleased(e.key);
        }
    }
});

//code for catching key events globally.
Template.body.events({
    "keydown": function(e, data, tpl) {
        // e -> jquery event
        // data -> Blaze data context of the DOM element triggering the event handler
        // tpl -> the parent template instance for the target element

        if (e.key.startsWith("Arrow") || e.key == "-" || e.key == "+") {
            Template.body.camera.keyPressed(e.key);
        }
    },
    "keyup": function(e, data, tpl) {
        // e -> jquery event
        // data -> Blaze data context of the DOM element triggering the event handler
        // tpl -> the parent template instance for the target element

        if (e.key.startsWith("Arrow") || e.key == "-" || e.key == "+") {
            Template.body.camera.keyReleased(e.key);
        }
    }
})
<|endoftext|>


<commit_before>// @flow

/**
 * inlined version of
 * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js
 */

const uppercasePattern = /([A-Z])/g;
const msPattern = /^ms-/;

/**
 * Hyphenates a camelcased CSS property name, for example:
 *
 *   > hyphenateStyleName('backgroundColor')
 *   < "background-color"
 *   > hyphenateStyleName('MozTransition')
 *   < "-moz-transition"
 *   > hyphenateStyleName('msTransition')
 *   < "-ms-transition"
 *
 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
 * is converted to `-ms-`.
 *
 * @param {string} string
 * @return {string}
 */
export default function hyphenateStyleName(string: string): string {
  return string
    .replace(uppercasePattern, '-$1')
    .toLowerCase()
    .replace(msPattern, '-ms-');
}
<commit_msg>speed up hyphenating style names (#3251)<commit_after>// @flow

/**
 * inlined version of
 * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js
 */

const uppercaseCheck = /([A-Z])/;
const uppercasePattern = new RegExp(uppercaseCheck, 'g');
const msPattern = /^ms-/;
const prefixAndLowerCase = (char: string): string => `-${char.toLowerCase()}`;

/**
 * Hyphenates a camelcased CSS property name, for example:
 *
 *   > hyphenateStyleName('backgroundColor')
 *   < "background-color"
 *   > hyphenateStyleName('MozTransition')
 *   < "-moz-transition"
 *   > hyphenateStyleName('msTransition')
 *   < "-ms-transition"
 *
 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
 * is converted to `-ms-`.
 *
 * @param {string} string
 * @return {string}
 */
export default function hyphenateStyleName(string: string): string {
  return uppercaseCheck.test(string)
  ? string
    .replace(uppercasePattern, prefixAndLowerCase)
    .replace(msPattern, '-ms-')
  : string;
}
<|endoftext|>


<commit_before>/* jshint undef: true */

//import {Syncher} from 'service-framework/dist/Syncher';
import {divideURL} from '../utils/utils';
import hello from './hello';

/**
* Hyperty Connector;
* @author Paulo Chainho [paulo-g-chainho@telecom.pt]
* @version 0.1.0
*/
class HelloWorldReporter {

  /**
  * Create a new HelloWorldReporter
  * @param  {Syncher} syncher - Syncher provided from the runtime core
  */
  constructor(hypertyURL, bus, configuration, factory) {

    if (!hypertyURL) throw new Error('The hypertyURL is a needed parameter');
    if (!bus) throw new Error('The MiniBus is a needed parameter');
    if (!configuration) throw new Error('The configuration is a needed parameter');
    if (!factory) throw new Error('The factory is a needed parameter');

    let _this = this;

    let domain = divideURL(hypertyURL).domain;
    _this._domain = domain;
    _this._objectDescURL = 'hyperty-catalogue://catalogue.' + domain + '/.well-known/dataschema/HelloWorldDataSchema';
    _this._factory = factory;
    debugger;

    let syncher = _this._factory.createSyncher(hypertyURL, bus, configuration);

    _this._syncher = syncher;

    /*_this._syncher.resumeReporters({}).then((resumeReporters) => {

      if (!resumeReporters) return;

      // lets now observe any changes done in Hello World Object
      console.log('[hyperty syncher resume] - dataObject', resumeReporters);

      Object.values(resumeReporters).forEach((helloObjtReporter) => {
        _this.helloObjtReporter = helloObjtReporter;

        this.prepareDataObjectReporter(helloObjtReporter);

        helloObjtReporter.data.hello = 'REPORTER RESUMED';

        console.log(this._onReporterResume);
        if (this._onReporterResume) this._onReporterResume(helloObjtReporter);
      })

    });*/

  }

  /**
  * Create HelloWorld Data Object
  * @param  {HypertyURL} HypertyURL - Invited
  */

  hello(hypertyURL) {
    let _this = this;
    let syncher = _this._syncher;

    return new Promise(function(resolve, reject) {

      let input = Object.assign({resources: ['hello']}, {});

      syncher.create(_this._objectDescURL, [hypertyURL], hello, false, false, 'hello', {}, input).then(function(helloObjtReporter) {
        console.info('1. Return Created Hello World Data Object Reporter', helloObjtReporter);

        _this.helloObjtReporter = helloObjtReporter;

        _this.prepareDataObjectReporter(helloObjtReporter);

        resolve(helloObjtReporter);

      })
      .catch(function(reason) {
        console.error(reason);
        reject(reason);
      });

    });
  }

  prepareDataObjectReporter(helloObjtReporter) {

    helloObjtReporter.onSubscription(function(event) {
      console.info('-------- Hello World Reporter received subscription request --------- \n');

      // All subscription requested are accepted

      event.accept();
    });

    helloObjtReporter.onRead((event) => {
      event.accept();
    });

  }

  /**
  * Update HelloWorld Data Object
  *
  */

  bye(byeMsg) {
    let _this = this;

    console.log('bye:', _this.helloObjtReporter );

    if (byeMsg)
      _this.helloObjtReporter.data.hello = byeMsg;
    else {
      _this.helloObjtReporter.data.hello = "bye, bye";
      }
  }

  onReporterResume(callback) {
    this._onReporterResume = callback;
  }

}

export default function activate(hypertyURL, bus, configuration, factory) {

  return {
    name: 'HelloWorldReporter',
    instance: new HelloWorldReporter(hypertyURL, bus, configuration, factory)
  };

}
<commit_msg>fixed activate with new factory parameter. seems to work with fake and browser worker sandbox<commit_after>/* jshint undef: true */

//import {Syncher} from 'service-framework/dist/Syncher';
import {divideURL} from '../utils/utils';
import hello from './hello';

/**
* Hyperty Connector;
* @author Paulo Chainho [paulo-g-chainho@telecom.pt]
* @version 0.1.0
*/
class HelloWorldReporter {

  /**
  * Create a new HelloWorldReporter
  * @param  {Syncher} syncher - Syncher provided from the runtime core
  */
  constructor(hypertyURL, bus, configuration, factory) {

    if (!hypertyURL) throw new Error('The hypertyURL is a needed parameter');
    if (!bus) throw new Error('The MiniBus is a needed parameter');
    if (!configuration) throw new Error('The configuration is a needed parameter');
    if (!factory) throw new Error('The factory is a needed parameter');

    let _this = this;

    let domain = divideURL(hypertyURL).domain;
    _this._domain = domain;
    _this._objectDescURL = 'hyperty-catalogue://catalogue.' + domain + '/.well-known/dataschema/HelloWorldDataSchema';
    _this._factory = factory;
    debugger;

    let syncher = _this._factory.createSyncher(hypertyURL, bus, configuration);

    _this._syncher = syncher;

    /*_this._syncher.resumeReporters({}).then((resumeReporters) => {

      if (!resumeReporters) return;

      // lets now observe any changes done in Hello World Object
      console.log('[hyperty syncher resume] - dataObject', resumeReporters);

      Object.values(resumeReporters).forEach((helloObjtReporter) => {
        _this.helloObjtReporter = helloObjtReporter;

        this.prepareDataObjectReporter(helloObjtReporter);

        helloObjtReporter.data.hello = 'REPORTER RESUMED';

        console.log(this._onReporterResume);
        if (this._onReporterResume) this._onReporterResume(helloObjtReporter);
      })

    });*/

  }

  /**
  * Create HelloWorld Data Object
  * @param  {HypertyURL} HypertyURL - Invited
  */

  hello(hypertyURL) {
    let _this = this;
    let syncher = _this._syncher;

    return new Promise(function(resolve, reject) {

      let input = Object.assign({resources: ['hello']}, {});

      syncher.create(_this._objectDescURL, [hypertyURL], hello, false, false, 'hello', {}, input).then(function(helloObjtReporter) {
        console.info('1. Return Created Hello World Data Object Reporter', helloObjtReporter);

        _this.helloObjtReporter = helloObjtReporter;

        _this.prepareDataObjectReporter(helloObjtReporter);

        resolve(helloObjtReporter);

      })
      .catch(function(reason) {
        console.error(reason);
        reject(reason);
      });

    });
  }

  prepareDataObjectReporter(helloObjtReporter) {

    helloObjtReporter.onSubscription(function(event) {
      console.info('-------- Hello World Reporter received subscription request --------- \n');

      // All subscription requested are accepted

      event.accept();
    });

    helloObjtReporter.onRead((event) => {
      event.accept();
    });

  }

  /**
  * Update HelloWorld Data Object
  *
  */

  bye(byeMsg) {
    let _this = this;

    console.log('bye:', _this.helloObjtReporter );

    if (byeMsg)
      _this.helloObjtReporter.data.hello = byeMsg;
    else {
      _this.helloObjtReporter.data.hello = "bye, bye";
      }
  }

  onReporterResume(callback) {
    this._onReporterResume = callback;
  }

}

export default function activate(hypertyURL, bus, configuration, factory) {

 // console.log('Hello World Activate', factory);
//  debugger;

  return {
    name: 'HelloWorldReporter',
    instance: new HelloWorldReporter(hypertyURL, bus, configuration, factory)
  };

}
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import Page from 'components/Page'
import {Grid, Row, Col} from 'react-bootstrap'

import SecurityBanner from 'components/SecurityBanner'
import Header from 'components/Header'
import Nav from 'components/Nav'
import NoPositionBanner from 'components/NoPositionBanner'
import History from 'components/History'
import dict from 'dictionary'

import API from 'api'
import {Person, Organization} from 'models'

import dictionary from 'resources/dictionary.json'

export default class App extends Page {
	static PagePropTypes = {
		useNavigation: PropTypes.bool,
		fluidContainer: PropTypes.bool,
	}

	static propTypes = {
		children: PropTypes.element.isRequired,
	}

	static childContextTypes = {
		app: PropTypes.object,
		currentUser: PropTypes.instanceOf(Person),
//		dictionary: PropTypes.object,
	}

	getChildContext() {
		return {
			app: this,
			currentUser: this.state.currentUser,
//			dictionary: this.state.dictionary,
		}
	}

	constructor(props) {
		super(props)

		this.state = {
			currentUser: new Person(),
			settings: {},
			organizations: [],
//			dictionary: {}
		}

		this.state = this.processData(window.ANET_DATA)
	}

	componentWillReceiveProps() {
		// this is just to prevent App from refetching app settings on every
		// single page load. in the future we may wish to do something more
		// intelligent to refetch page settings
	}

	fetchData() {
		API.query(/* GraphQL */`
			person(f:me) {
				id, name, role, emailAddress, rank, status
				position {
					id, name, type, isApprover
					organization { id, shortName , allDescendantOrgs { id }}
				}
			}

			adminSettings(f:getAll) {
				key, value
			}

			organizationList(f:getTopLevelOrgs, type: ADVISOR_ORG) {
				list { id, shortName }
			}
		`).then(data => {
			data.person._loaded = true
			this.setState(this.processData(data), () => {
				// if this is a new user, redirect to the create profile page
				if (this.state.currentUser.isNewUser()) {
					History.replace('/onboarding')
				}
			})
		})

		//Fetch the dictionary.
		// @vassil dictionary.json temporarily moved to resouces. Difficulties to load from /dictionary.json when deployed as the files is moved under PUBLIC_URL
//		API.fetch('/dictonary.json').then(dictionary =>
			dict.setDictionary(dictionary)
//		)
	}

	processData(data) {
		let currentUser = new Person(data.person)
		let organizations = (data.organizationList && data.organizationList.list) || []
		organizations = Organization.fromArray(organizations)
		organizations.sort((a, b) => a.shortName.localeCompare(b.shortName))

		let settings = this.state.settings
		data.adminSettings.forEach(setting => settings[setting.key] = setting.value)
		let dictionary = this.state.dictionary

		return {currentUser, settings, organizations, dictionary}
	}

	render() {
		let pageProps = this.props.children.type.pageProps || {}
		let currentUser = this.state.currentUser

		return (

				<SecurityBanner location={this.props.location} />

				{currentUser && currentUser.position && currentUser.position.id === 0 && !currentUser.isNewUser() && <NoPositionBanner />}

				<Grid componentClass="section" bsClass={pageProps.fluidContainer ? 'container-fluid' : 'container'}>
					{pageProps.useNavigation === false
						? <Row><Col xs={12}>{this.props.children}</Col></Row>
						: <Row>
							<Col sm={3} className="hide-for-print">

							</Col>
							<Col sm={9} className="primary-content">
								{this.props.children}
							</Col>
						</Row>
					}
				</Grid>

		)
	}
}
<commit_msg>Render General Banner Component in the app<commit_after>import React, {PropTypes} from 'react'
import Page from 'components/Page'
import {Grid, Row, Col} from 'react-bootstrap'

import SecurityBanner from 'components/SecurityBanner'
import GeneralBanner from 'components/GeneralBanner'
import Header from 'components/Header'
import Nav from 'components/Nav'
import NoPositionBanner from 'components/NoPositionBanner'
import History from 'components/History'
import dict from 'dictionary'

import API from 'api'
import {Person, Organization} from 'models'

import dictionary from 'resources/dictionary.json'

const GENERAL_BANNER_TEXT = 'GENERAL_BANNER_TEXT'

export default class App extends Page {
	static PagePropTypes = {
		useNavigation: PropTypes.bool,
		fluidContainer: PropTypes.bool,
	}

	static propTypes = {
		children: PropTypes.element.isRequired,
	}

	static childContextTypes = {
		app: PropTypes.object,
		currentUser: PropTypes.instanceOf(Person),
//		dictionary: PropTypes.object,
	}

	getChildContext() {
		return {
			app: this,
			currentUser: this.state.currentUser,
//			dictionary: this.state.dictionary,
		}
	}

	constructor(props) {
		super(props)

		this.state = {
			currentUser: new Person(),
			settings: {},
			organizations: [],
//			dictionary: {}
		}

		this.state = this.processData(window.ANET_DATA)
	}

	componentWillReceiveProps() {
		// this is just to prevent App from refetching app settings on every
		// single page load. in the future we may wish to do something more
		// intelligent to refetch page settings
	}

	fetchData() {
		API.query(/* GraphQL */`
			person(f:me) {
				id, name, role, emailAddress, rank, status
				position {
					id, name, type, isApprover
					organization { id, shortName , allDescendantOrgs { id }}
				}
			}

			adminSettings(f:getAll) {
				key, value
			}

			organizationList(f:getTopLevelOrgs, type: ADVISOR_ORG) {
				list { id, shortName }
			}
		`).then(data => {
			data.person._loaded = true
			this.setState(this.processData(data), () => {
				// if this is a new user, redirect to the create profile page
				if (this.state.currentUser.isNewUser()) {
					History.replace('/onboarding')
				}
			})
		})

		//Fetch the dictionary.
		// @vassil dictionary.json temporarily moved to resouces. Difficulties to load from /dictionary.json when deployed as the files is moved under PUBLIC_URL
//		API.fetch('/dictonary.json').then(dictionary =>
			dict.setDictionary(dictionary)
//		)
	}

	processData(data) {
		let currentUser = new Person(data.person)
		let organizations = (data.organizationList && data.organizationList.list) || []
		organizations = Organization.fromArray(organizations)
		organizations.sort((a, b) => a.shortName.localeCompare(b.shortName))

		let settings = this.state.settings
		data.adminSettings.forEach(setting => settings[setting.key] = setting.value)
		let dictionary = this.state.dictionary

		return {currentUser, settings, organizations, dictionary}
	}

	render() {
		let pageProps = this.props.children.type.pageProps || {}
		let currentUser = this.state.currentUser
		let banner = {
			message: this.state.settings[GENERAL_BANNER_TEXT],
			statusColor: 'alert-info'
		}

		return (

				<SecurityBanner location={this.props.location} />

				{currentUser && currentUser.position && currentUser.position.id === 0 && !currentUser.isNewUser() && <NoPositionBanner />}

				<Grid componentClass="section" bsClass={pageProps.fluidContainer ? 'container-fluid' : 'container'}>
					<Row><Col xs={12}><GeneralBanner banner={banner} /></Col></Row>
					{pageProps.useNavigation === false
						? <Row><Col xs={12}>{this.props.children}</Col></Row>
						: <Row>
							<Col sm={3} className="hide-for-print">

							</Col>
							<Col sm={9} className="primary-content">
								{this.props.children}
							</Col>
						</Row>
					}
				</Grid>

		)
	}
}
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor'
import { neuron_catalog_version } from '../lib/version'
import { Notifications } from './globals-client'
import $ from 'jquery'

// check for a new release of neuron catalog

let on_version_received = function (data, status, xhr) {
  if (status !== 'success') {
    return
  }
  let is_up_to_date = compareVersions(neuron_catalog_version, data.version)
  if (!is_up_to_date) {
    return Notifications.info('A new version of neuron-catalog is available',
      data.description_html)
  }
}

let check_version = () => $.ajax({
  url: 'https://s3-eu-west-1.amazonaws.com/strawlab.org/neuron-catalog/latest-release.json',
  dataType: 'json',
  success: on_version_received
}
)

let initial_check_version = function () {
  check_version()
  return Meteor.setInterval(check_version, 12 * 1000 * 60 * 60) // every 12 hours check version
}

Meteor.startup(() => Meteor.setTimeout(initial_check_version, 30 * 1000))

// From http://stackoverflow.com/a/6832670/1633026
// return true if 'installed' (considered as a JRE version string) is
// greater than or equal to 'required' (again, a JRE version string).
function compareVersions (installed, required) {
  let a = installed.split('.')
  let b = required.split('.')
  let i = 0
  while (i < a.length) {
    a[i] = Number(a[i])
    ++i
  }
  i = 0
  while (i < b.length) {
    b[i] = Number(b[i])
    ++i
  }
  if (a.length === 2) {
    a[2] = 0
  }
  if (a[0] > b[0]) {
    return true
  }
  if (a[0] < b[0]) {
    return false
  }
  if (a[1] > b[1]) {
    return true
  }
  if (a[1] < b[1]) {
    return false
  }
  if (a[2] > b[2]) {
    return true
  }
  if (a[2] < b[2]) {
    return false
  }
  return true
}
<commit_msg>directly use strawlab.org URL as location of version info<commit_after>import { Meteor } from 'meteor/meteor'
import { neuron_catalog_version } from '../lib/version'
import { Notifications } from './globals-client'
import $ from 'jquery'

// check for a new release of neuron catalog

let on_version_received = function (data, status, xhr) {
  if (status !== 'success') {
    return
  }
  let is_up_to_date = compareVersions(neuron_catalog_version, data.version)
  if (!is_up_to_date) {
    return Notifications.info('A new version of neuron-catalog is available',
      data.description_html)
  }
}

let check_version = () => $.ajax({
  url: 'https://strawlab.org/neuron-catalog/latest-release.json',
  dataType: 'json',
  success: on_version_received
}
)

let initial_check_version = function () {
  check_version()
  return Meteor.setInterval(check_version, 12 * 1000 * 60 * 60) // every 12 hours check version
}

Meteor.startup(() => Meteor.setTimeout(initial_check_version, 30 * 1000))

// From http://stackoverflow.com/a/6832670/1633026
// return true if 'installed' (considered as a JRE version string) is
// greater than or equal to 'required' (again, a JRE version string).
function compareVersions (installed, required) {
  let a = installed.split('.')
  let b = required.split('.')
  let i = 0
  while (i < a.length) {
    a[i] = Number(a[i])
    ++i
  }
  i = 0
  while (i < b.length) {
    b[i] = Number(b[i])
    ++i
  }
  if (a.length === 2) {
    a[2] = 0
  }
  if (a[0] > b[0]) {
    return true
  }
  if (a[0] < b[0]) {
    return false
  }
  if (a[1] > b[1]) {
    return true
  }
  if (a[1] < b[1]) {
    return false
  }
  if (a[2] > b[2]) {
    return true
  }
  if (a[2] < b[2]) {
    return false
  }
  return true
}
<|endoftext|>


<commit_before>import d3 from "d3";
import Baobab from "baobab";

import Jupyter from "base/js/namespace";

import {Presenter} from "./presenter";
import {Sorter} from "./sorter";

let {toolbar} = Jupyter;

class NBPresent {
  constructor() {
    this.tree = new Baobab();
    this.presenter = new Presenter(this.tree);
    this.sorter = new Sorter(this.tree);

    this.initToolbar();
  }

  present() {
    this.presenter.present();
  }

  initToolbar() {
    toolbar.add_buttons_group([{
      label: 'nbpresent',
      icon: 'fa-gift',
      callback: this.present,
      id: 'start_nbpresent'
    }]);
  }
}

var nbpresent = () => {
  let nbp = new NBPresent();
}

export {nbpresent};
<commit_msg>present context<commit_after>import d3 from "d3";
import Baobab from "baobab";

import Jupyter from "base/js/namespace";

import {Presenter} from "./presenter";
import {Sorter} from "./sorter";

class NBPresent {
  constructor() {
    this.tree = new Baobab();
    this.presenter = new Presenter(this.tree);
    this.sorter = new Sorter(this.tree);

    this.initToolbar();
  }

  present() {
    this.presenter.present();
  }

  initToolbar() {
    Jupyter.toolbar.add_buttons_group([{
      label: 'nbpresent',
      icon: 'fa-gift',
      callback: () => this.present(),
      id: 'start_nbpresent'
    }]);
  }
}

var nbpresent = () => {
  let nbp = new NBPresent();
}

export {nbpresent};
<|endoftext|>