<commit_before>'use strict';

var space = ' ';
var inQuote = ' \"';
var outQuote = '\" ';
var outQuote2 = '\"';
var apostrophe = '\'';
var position = 0;
var totalQuestions = 7;
var correct = 0;
var quizStatus = correct + ' correct out of ' + totalQuestions;

//welcome the user and ask them if they're ready to take the quiz.
var confirmed = confirm('Welcome! Before you go any further, I\'d like to find out how well you know me. Are you ready for a quiz?');
//determine whether or not they're ready and respond.
if(confirmed === true){
  console.log('The user is ready!');
  //let the user know we heard them.
  alert('Great! I\'ll call the Quiz Master over.');
} else {
  //let the user know we can't stop it now.
  console.log('The user said they were not ready... but we\'re gonna start anyway.');
  alert('Ah nuts. I already sen\'t for the Quiz Master. He\'ll be here any minute. Be a pal and do it anyway, will ya?');
}

//ask the user for their name and store it.
var name = prompt('Oh! I almost forgot. What should I call you?');
//write the quiz status to the page.
document.querySelector('.score').innerHTML = '
' + name + ', ' + 'you got ' + quizStatus + '.' + '
';

//introduce the quiz maaster who will be asking the questions.
alert('Quiz Master: You called? Who needs quizzing?');
//razz the user a little for fun.
alert('Quiz Master: Oh... it\'s this one. (sigh) alright then, ' + name + '. Let\'s get it over with.');

//an array to store each of the first 5 questions and all of the associated brikabrak
var questions = [
  [],
//Question text:[i][0]    Incorrect feedback:[i][1]    Correct feedback:[i][2]    Correct Answer(yes || no):[i][3]    The user's response:[i][4]
['Has Jed ever eaten a live squid?', 'Wrong! No need to get into it here, but he did.', 'Good guess. He did indeed. Do not try it yourself if you can avoid it.', 'yes', 'user answer'],
['Has Jed ever been to Paris?', 'Whoops. Not yet, but he plans to go soon!', 'Correct. He plans to go soon, though.', 'no', 'user answer'],
['If Jed were an animal, would he be a Polar Bear?', 'WRONG! There is no better animal. Period.', 'HECK YES HE WOULD!', 'yes', 'user answer'],
['When Jed shares his profession, do people usually look at him quizically?', 'Unfortunately, most people have no idea what an Instructional Designer is.', 'That\'s right. Nobody knows.', 'yes', 'user answer'],
['Do you like Polar Bears, too?', 'What is wrong with you?', 'HECK YES YOU DO!', 'yes', 'user answer']
];

//iterate through the questions array, asking each question, recording the answer and providing feedback
// noprotect
for (var i = 1; i <= questions.length - 1; i++) {
  //adjust the user's position in the quiz.
  position++;
  //ask the question and place the user's response into the appropriate place in the questions array
  questions[i].splice(4,1,prompt(questions[i][0]));
  //adjust the user's answer to account for edge cases
  if(questions[i][4].toLowerCase() == 'y' || questions[i][4].toLowerCase() == 'yes'){
    questions[i].splice(4,1,'yes');
  } else if (questions[i][4].toLowerCase() == 'n' || questions[i][4].toLowerCase() == 'no') {
    questions[i].splice(4,1,'no');
  } else if (questions[i][4] === '') {
    questions[i].splice(4,1,'a silent, steely-eyed stare');
  } else {
    questions[i].splice(4,1,'something nonsensical');
  }
  //log the user's answer to check if fixes were applied to edge cases.
  console.log(questions[i][4]);
  console.log('i is currently ' + i);
  //check the user's answer against the answer in the array. If it matches do something. If not, do something else.
  if(questions[i][4] == questions[i][3]) {
    //add a point to the correct variable
    correct++;
    //write the user's answer to the page and let them know if it was right or wrong.
    document.querySelector('.answer' + i).innerHTML = '
The Quiz Master asked, ' + inQuote + questions[i][0] + outQuote + 'You responded with' + inQuote + questions[i][4] + outQuote2 + '. ' + questions[i][2] + '
';
  } else if (questions[i][4] == 'a silent, steely-eyed stare') {
    document.querySelector('.answer' + i).innerHTML = '
The Quiz Master asked, ' + inQuote + questions[i][0] + outQuote + 'You responded with' + space + questions[i][4] + '. ' + questions[i][1] + '
';
  } else {
    document.querySelector('.answer' + i).innerHTML = '
The Quiz Master asked, ' + inQuote + questions[i][0] + outQuote + 'You responded with' + inQuote + questions[i][4] + outQuote2 + '. ' + questions[i][1] + '
';
  }
}
//log the current position to the console
console.log(position);

//Grab a random number between 1 and 30
var randNum = Math.floor(Math.random() * 30) + 1;
//Log the random number for debugging/cheating purposes
console.log(randNum);

//give the user four chances to guess the random number
alert('Alright, smarty-pants. If you know Jed so well, let\'s see if you can guess what number he\'s thinking of.');
var q6 = prompt('I\'ll even give you a hint. It\s between 1 and 30');
var q6Result = false;
//loop will give the user 4 chances to get the question correct before moving on.
for (var j = 3; j > 0; j--) {
  //shot or shots? Grammar is important. Let's find out!
  if (j === 1) {
    var shot = 'shot';
  } else {
    var shot = 'shots';
  }
  //Now we'll see if they guessed correctly.
  if (q6 != randNum) {
    if (q6 < randNum) {
      q6 = prompt('Not quite. Guess higher. You\'ve got ' + j + ' ' + shot + ' left.');
    } else if (q6 > randNum ) {
      q6 = prompt('Not quite. Guess lower. You\'ve got ' + j + ' ' + shot + ' left.');
    } else if (isNaN(q6) === true) {
      q6 = prompt('That\'s not a number, fool. Try again.');
    }
  }
  else {
    console.log('Bingo! You got it ' + name + '! Time for question #7.' );
    q6Result = true;
    position++;
    correct++;
  }
  console.log('j = ' + j);
}
if (q6Result == true){
  document.querySelector('.answer6').innerHTML = '
The Quiz Master asked you to guess a number between 1 and 30 . You nailed it.
';
}else{
  document.querySelector('.answer6').innerHTML = '
The Quiz Master asked you to guess a number between 1 and 30 . You didn\'t manage to guess the number ' + randNum + '.' + '
';
}
<commit_msg>q7 started<commit_after>'use strict';

var space = ' ';
var inQuote = ' \"';
var outQuote = '\" ';
var outQuote2 = '\"';
var apostrophe = '\'';
var position = 0;
var totalQuestions = 7;
var correct = 0;
var quizStatus = correct + ' correct out of ' + totalQuestions;

//welcome the user and ask them if they're ready to take the quiz.
var confirmed = confirm('Welcome! Before you go any further, I\'d like to find out how well you know me. Are you ready for a quiz?');
//determine whether or not they're ready and respond.
if(confirmed === true){
  console.log('The user is ready!');
  //let the user know we heard them.
  alert('Great! I\'ll call the Quiz Master over.');
} else {
  //let the user know we can't stop it now.
  console.log('The user said they were not ready... but we\'re gonna start anyway.');
  alert('Ah nuts. I already sen\'t for the Quiz Master. He\'ll be here any minute. Be a pal and do it anyway, will ya?');
}

//ask the user for their name and store it.
var name = prompt('Oh! I almost forgot. What should I call you?');
//write the quiz status to the page.
document.querySelector('.score').innerHTML = '
' + name + ', ' + 'you got ' + quizStatus + '.' + '
';

//introduce the quiz maaster who will be asking the questions.
alert('Quiz Master: You called? Who needs quizzing?');
//razz the user a little for fun.
alert('Quiz Master: Oh... it\'s this one. (sigh) alright then, ' + name + '. Let\'s get it over with.');

//an array to store each of the first 5 questions and all of the associated brikabrak
var questions = [
  [],
//Question text:[i][0]    Incorrect feedback:[i][1]    Correct feedback:[i][2]    Correct Answer(yes || no):[i][3]    The user's response:[i][4]
['Has Jed ever eaten a live squid?', 'Wrong! No need to get into it here, but he did.', 'Good guess. He did indeed. Do not try it yourself if you can avoid it.', 'yes', 'user answer'],
['Has Jed ever been to Paris?', 'Whoops. Not yet, but he plans to go soon!', 'Correct. He plans to go soon, though.', 'no', 'user answer'],
['If Jed were an animal, would he be a Polar Bear?', 'WRONG! There is no better animal. Period.', 'HECK YES HE WOULD!', 'yes', 'user answer'],
['When Jed shares his profession, do people usually look at him quizically?', 'Unfortunately, most people have no idea what an Instructional Designer is.', 'That\'s right. Nobody knows.', 'yes', 'user answer'],
['Do you like Polar Bears, too?', 'What is wrong with you?', 'HECK YES YOU DO!', 'yes', 'user answer']
];

//iterate through the questions array, asking each question, recording the answer and providing feedback
// noprotect
for (var i = 1; i <= questions.length - 1; i++) {
  //adjust the user's position in the quiz.
  position++;
  //ask the question and place the user's response into the appropriate place in the questions array
  questions[i].splice(4,1,prompt(questions[i][0]));
  //adjust the user's answer to account for edge cases
  if(questions[i][4].toLowerCase() == 'y' || questions[i][4].toLowerCase() == 'yes'){
    questions[i].splice(4,1,'yes');
  } else if (questions[i][4].toLowerCase() == 'n' || questions[i][4].toLowerCase() == 'no') {
    questions[i].splice(4,1,'no');
  } else if (questions[i][4] === '') {
    questions[i].splice(4,1,'a silent, steely-eyed stare');
  } else {
    questions[i].splice(4,1,'something nonsensical');
  }
  //log the user's answer to check if fixes were applied to edge cases.
  console.log(questions[i][4]);
  console.log('i is currently ' + i);
  //check the user's answer against the answer in the array. If it matches do something. If not, do something else.
  if(questions[i][4] == questions[i][3]) {
    //add a point to the correct variable
    correct++;
    //write the user's answer to the page and let them know if it was right or wrong.
    document.querySelector('.answer' + i).innerHTML = '
The Quiz Master asked, ' + inQuote + questions[i][0] + outQuote + 'You responded with' + inQuote + questions[i][4] + outQuote2 + '. ' + questions[i][2] + '
';
  } else if (questions[i][4] == 'a silent, steely-eyed stare') {
    document.querySelector('.answer' + i).innerHTML = '
The Quiz Master asked, ' + inQuote + questions[i][0] + outQuote + 'You responded with' + space + questions[i][4] + '. ' + questions[i][1] + '
';
  } else {
    document.querySelector('.answer' + i).innerHTML = '
The Quiz Master asked, ' + inQuote + questions[i][0] + outQuote + 'You responded with' + inQuote + questions[i][4] + outQuote2 + '. ' + questions[i][1] + '
';
  }
}
//log the current position to the console
console.log('current position is ' + position);

//Grab a random number between 1 and 30
var randNum = Math.floor(Math.random() * 30) + 1;
//Log the random number for debugging/cheating purposes
console.log('The chosen number is' + randNum);

//give the user four chances to guess the random number
alert('Alright, smarty-pants. If you know Jed so well, let\'s see if you can guess what number he\'s thinking of.');
var q6 = prompt('I\'ll even give you a hint. It\s between 1 and 30');
var q6Result = false;
//loop will give the user 4 chances to get the question correct before moving on.
for (var j = 3; j > 0; j--) {
  //shot or shots? Grammar is important. Let's find out!
  if (j === 1) {
    var shot = 'shot';
  } else {
    var shot = 'shots';
  }
  //Now we'll see if they guessed correctly.
  if (q6 != randNum) {
    if (q6 < randNum) {
      q6 = prompt('Not quite. Guess higher. You\'ve got ' + j + ' ' + shot + ' left.');
    } else if (q6 > randNum ) {
      q6 = prompt('Not quite. Guess lower. You\'ve got ' + j + ' ' + shot + ' left.');
    } else if (isNaN(q6) === true) {
      q6 = prompt('That\'s not a number, fool. Try again.');
    }
  }
  else {
    console.log('Bingo! You got it ' + name + '! Time for question #7.' );
    q6Result = true;
    position++;
    correct++;
  }
  console.log('j = ' + j);
}
if (q6Result == true){
  document.querySelector('.answer6').innerHTML = '
The Quiz Master asked you to guess a number between 1 and 30 . You nailed it.
';
}else{
  document.querySelector('.answer6').innerHTML = '
The Quiz Master asked you to guess a number between 1 and 30 . You didn\'t manage to guess the number ' + randNum + '.' + '
';
}

//start q7
var q7array = [ 'Can you guess a state that I\'ve lived in besides Washington?', ['ARIZONA','ILLINOIS','NEVADA'], 'user answer'];
console.log(q7array[2]);
q7array.splice(2,1,prompt(q7array[0]));
//check for some edge cases and fix
if (q7array[2].toUpperCase() == 'AZ' || q7array[2].toUpperCase() == 'IL' || q7array[2].toUpperCase() == 'NV'){
  if (q7array[2].toUpperCase() == 'AZ') {
    q7array[2] = 'ARIZONA';
  } else if (q7array[2].toUpperCase() == 'IL') {
    q7array[2] = 'ILLINOIS';
  } else {
    q7array[2] = 'NEVADA';
  }
}
else {
  //do nothing
}
//now see if they're right or not
console.log(q7array[2]);
for (var k = 6; k > 0; k--) {
  console.log(q7array[2]);
  //adjust the user's answer to account for edge cases
  if (q7array[2].toUpperCase() == q7array[1][0] || q7array[2].toUpperCase() == q7array[1][1] || q7array[2].toUpperCase() == q7array[1][2]) {
    console.log('right!');
    break;
  } else {
    console.log('wrong');
    q7array[2] = prompt('Try again!');
  }
}
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');

let adWhitelist = (Config.adWhitelist ? Config.adWhitelist : []);
let bannedMessages = (Config.bannedMessages ? Config.bannedMessages : []);
let adRegex = new RegExp("(play.pokemonshowdown.com\\/~~)(?!(" + adWhitelist.join('|') + "))", "g");

Config.chatfilter = function (message, user, room, connection) {
	user.lastActive = Date.now();

	for (let x in bannedMessages) {
		if (message.toLowerCase().indexOf(bannedMessages[x]) > -1 && bannedMessages[x] !== '' && message.substr(0, 1) !== '/') {
			if (user.locked) return false;
			Punishments.lock(user, Date.now() + 7 * 24 * 60 * 60 * 1000, "Said a banned word: " + bannedMessages[x]);
			user.popup('You have been automatically locked for sending a message containing a banned word.');
			Rooms('staff').add('[PornMonitor] ' + (room ? '(' + room + ') ' : '') + Tools.escapeHTML(user.name) +
			' was automatically locked for trying to say "' + message + '"').update();
			fs.appendFile('logs/modlog/modlog_staff.txt', '[' + (new Date().toJSON()) + '] (staff) ' + user.name + ' was locked from talking by the Server (' +
			bannedMessages[x] + ') (' + connection.ip + ')\n');
			Misc.staffPM(user.name + ' has been automatically locked for sending a message containing a banned word' +
			(room ? ". **Room:**" + room.id : " in a private message.") + ' **Message:** ' + message, '~Server');
			return false;
		}
};
<commit_msg>Update chatfilter.js<commit_after>'use strict';

const fs = require('fs');

let adWhitelist = (Config.adWhitelist ? Config.adWhitelist : []);
let bannedMessages = (Config.bannedMessages ? Config.bannedMessages : []);
let adRegex = new RegExp("(play.pokemonshowdown.com\\/~~)(?!(" + adWhitelist.join('|') + "))", "g");

Config.chatfilter = function (message, user, room, connection) {
	user.lastActive = Date.now();

	for (let x in bannedMessages) {
		if (message.toLowerCase().indexOf(bannedMessages[x]) > -1 && bannedMessages[x] !== '' && message.substr(0, 1) !== '/') {
			if (user.locked) return false;
			Punishments.lock(user, Date.now() + 7 * 24 * 60 * 60 * 1000, "Said a banned word: " + bannedMessages[x]);
			user.popup('You have been automatically locked for sending a message containing a banned word.');
			Rooms('staff').add('[PornMonitor] ' + (room ? '(' + room + ') ' : '') + Tools.escapeHTML(user.name) +
			' was automatically locked for trying to say "' + message + '"').update();
			fs.appendFile('logs/modlog/modlog_staff.txt', '[' + (new Date().toJSON()) + '] (staff) ' + user.name + ' was locked from talking by the Server (' +
			bannedMessages[x] + ') (' + connection.ip + ')\n');
			Misc.staffPM(user.name + ' has been automatically locked for sending a message containing a banned word' +
			(room ? ". **Room:**" + room.id : " in a private message.") + ' **Message:** ' + message, '~Server');
			return false;
		}
	}
};
<|endoftext|>


<commit_before>var cheerio = require('cheerio');
    request = require('request');
    url = 'http://www.fzw.de/programm/'

request(url, function (error, response, body) {
	if (!error) {
  	var $ = cheerio.load(body);
    bigBox = $('.bigBox').html();
    $ = cheerio.load(bigBox);
  	$('div[style="position: relative; background: url(img/blank.gif);"]').each(function() {

      eventBlob = $(this).html();
      $ = cheerio.load(eventBlob);
      console.log($('table > tr > td > h3').text().trim());
      console.log($('table > tr > td[style="width: 85px; vertical-align: top;"] > h2').text().trim());
      console.log($('table > tr > td > span').text().trim());
      console.log($('.programEventInfo > table > tr > td:last-child').text().trim());
      console.log("---")
    });
  } else {
		console.log("HTTP Request fehlgeschlagen: " + error);
	}
});
<commit_msg>Change output from YAML to JSON<commit_after>var cheerio = require('cheerio');
    request = require('request');
    url = 'http://www.fzw.de/programm/'

request(url, function (error, response, body) {
	if (!error) {
  	var $ = cheerio.load(body);
  	$('div[style="position: relative; background: url(img/blank.gif);"] > a').each(function(i, element) {
      eventUrl = "http://www.fzw.de/"+ $(this).attr('href');
      request(eventUrl, function (error, response, body) {
      	if (!error) {
          var $ = cheerio.load(body);
          var eventDate = $('.bigBox > h2:first-of-type').text();
          eventDate = eventDate.substring(4);
          var eventDetails = $('.bigBox > h2:nth-of-type(3)').text();
          var eventDetailsRegEx = /Beginn: (\d\d.\d\d)/;
          var eventDetailsResult = eventDetails.match(eventDetailsRegEx);
          if (eventDetailsResult !== null) var eventStartTime = eventDetailsResult[1];
          var eventName = $('.bigBox > h3:first-of-type').text().trim();
          $('.bigBox > div:nth-of-type(2) > *').each(function() {
            var content = $(this).text();
            $(this).replaceWith(content);
          });
          var eventDescription = ($('.bigBox > div:nth-of-type(2)').text().trim());
          var eventJSON = {
            "@context": "http://schema.org",
            "@type": "Event",
            "name": eventName,
            "description": eventDescription,
            "location": {
              "@type": "Place",
              "address": {
                "@type": "PostalAddress",
                "streetAddress" : "Ritterstr. 20",
                "addressLocality" : "Dortmund",
                "postalCode" : "44137"
                }
              },
            "startDate": eventDate + eventStartTime,
            "url": eventUrl
          }

          console.log(JSON.stringify(eventJSON));
        } else {
      		console.log("Event HTTP Request fehlgeschlagen: " + error);
      	}
      });
    });
  } else {
		console.log("Übersicht HTTP Request fehlgeschlagen: " + error);
	}

});
<|endoftext|>


<commit_before>const WIDTH = 800;
const HEIGHT = 600;

var setup = function() {
  createCanvas(WIDTH, HEIGHT);
  background(0);
  fill(255);

  angleMode(DEGREES);

  stroke(255);
  strokeWeight(1);
  strokeCap(SQUARE);
}

var draw = function() {
  push();
  translate(200, 200);
  rotate(45);
  rect(-50, -25, 100, 50);
  pop();

  push();
  translate(100, 300);
  rotate(45);
  rect(-50, -25, 100, 50);
  pop();

  push();
  translate(300, 100);
  rotate(45);
  rect(-50, -25, 100, 50);
  pop();
}
<commit_msg>extract drawRectangle function<commit_after>const WIDTH = 800;
const HEIGHT = 600;

const RECT_SIZE_X = 100;
const RECT_SIZE_Y = 50;

var setup = function() {
  createCanvas(WIDTH, HEIGHT);
  background(0);
  fill(255);

  angleMode(DEGREES);

  stroke(255);
  strokeWeight(1);
  strokeCap(SQUARE);
}

var drawRectangle = (posX, posY) => {
  push();
  translate(posX, posY);
  rotate(45);
  rect(-(RECT_SIZE_X/2), -(RECT_SIZE_Y/2), RECT_SIZE_X, RECT_SIZE_Y);
  pop();
}

var draw = function() {
  drawRectangle(200, 200);
  drawRectangle(100, 300);
  drawRectangle(300, 100);
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief test the collection interface
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var jsunity = require("jsunity");

var arangodb = require("org/arangodb");
var internal = require("internal");

var ArangoCollection = arangodb.ArangoCollection;
var db = arangodb.db;
var ERRORS = arangodb.errors;
var testHelper = require("org/arangodb/test-helper").Helper;

// -----------------------------------------------------------------------------
// --SECTION--                                                    figure methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: FiguresSuite
////////////////////////////////////////////////////////////////////////////////

function FiguresSuite () {
  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief figures
////////////////////////////////////////////////////////////////////////////////

    testFigures : function () {
      var collection = "example";

      db._drop(collection);
      var c1 = db._create(collection);

      c1.load();

      var f = c1.figures();
      assertEqual(0, f.datafiles.count);
      assertEqual(0, f.compactors.count);
      assertEqual(0, f.shapefiles.count);
      assertEqual(0, f.shapefiles.fileSize);
      assertEqual(0, f.alive.count);
      assertEqual(0, f.alive.size);
      assertEqual(0, f.dead.count);
      assertEqual(0, f.dead.size);
      assertEqual(0, f.dead.deletion);

      var d1 = c1.save({ hello : 1 });

      internal.wal.flush(true, true);
      f = c1.figures();

      assertEqual(0, f.datafiles.count);
      assertEqual(0, f.datafiles.fileSize);
      assertEqual(1, f.journals.count);
      assertTrue(f.journals.fileSize > 0);
      assertEqual(0, f.compactors.count);
      assertEqual(0, f.shapefiles.count);
      assertEqual(0, f.shapefiles.fileSize);
      assertEqual(1, f.alive.count);
      assertNotEqual(0, f.alive.size);
      assertEqual(0, f.dead.count);
      assertEqual(0, f.dead.size);
      assertEqual(0, f.dead.deletion);

      var d2 = c1.save({ hello : 2 });

      internal.wal.flush(true, true);
      f = c1.figures();

      assertEqual(0, f.datafiles.count);
      assertEqual(0, f.datafiles.fileSize);

      assertEqual(1, f.journals.count);
      assertTrue(f.journals.fileSize > 0);
      assertEqual(2, f.alive.count);
      assertNotEqual(0, f.alive.size);
      assertEqual(0, f.dead.count);
      assertEqual(0, f.dead.size);
      assertEqual(0, f.dead.deletion);

      c1.remove(d1);

      internal.wal.flush(true, true);
      f = c1.figures();

      assertEqual(0, f.datafiles.count);
      assertEqual(0, f.datafiles.fileSize);
      assertEqual(1, f.journals.count);
      assertTrue(f.journals.fileSize > 0);
      assertEqual(1, f.alive.count);
      assertNotEqual(0, f.alive.size);
      assertEqual(1, f.dead.count);
      assertNotEqual(0, f.dead.size);
      assertEqual(1, f.dead.deletion);

      c1.remove(d2);

      internal.wal.flush(true, true);
      f = c1.figures();

      assertEqual(0, f.datafiles.count);
      assertEqual(0, f.datafiles.fileSize);
      assertEqual(1, f.journals.count);
      assertTrue(f.journals.fileSize > 0);
      assertEqual(0, f.alive.count);
      assertEqual(0, f.alive.size);
      assertEqual(2, f.dead.count);
      assertNotEqual(0, f.dead.size);
      assertEqual(2, f.dead.deletion);

      var attributes = f.attributes.count;
      var shapes = f.shapes.count;

      c1.save({ b0rk : "abc" });

      internal.wal.flush(true, true);
      f = c1.figures();

      assertEqual(attributes + 1, f.attributes.count);
      assertEqual(shapes + 1, f.shapes.count);

      db._drop(collection);
    },
////////////////////////////////////////////////////////////////////////////////
/// @brief check figures
////////////////////////////////////////////////////////////////////////////////

    testFiguresAfterOperations : function () {
      var cnName = "example";

      db._drop(collection);
      var collection = db._create(cnName);

      collection.load();
      var figures;

      collection.save({ _key : "a1" });
      collection.save({ _key : "a2" });
      collection.save({ _key : "a3" });

      internal.wal.flush(true, true);
      figures = collection.figures();

      assertEqual(3, figures.alive.count);
      assertEqual(0, figures.dead.count);

      // insert a few duplicates
      try {
        collection.save({ _key : "a1" });
        fail();
      }
      catch (e1) {
      }

      try {
        collection.save({ _key : "a2" });
        fail();
      }
      catch (e2) {
      }

      // we should see the same figures
      internal.wal.flush(true, true);
      figures = collection.figures();

      assertEqual(3, figures.alive.count);
      assertEqual(0, figures.dead.count);

      // now remove some documents
      collection.remove("a2");
      collection.remove("a3");

      // we should see two live docs less
      internal.wal.flush(true, true);
      figures = collection.figures();

      assertEqual(1, figures.alive.count);
      assertEqual(2, figures.dead.count);

      // replacing one document does not change alive, but increases dead!
      collection.replace("a1", { });

      internal.wal.flush(true, true);
      figures = collection.figures();

      assertEqual(1, figures.alive.count);
      assertEqual(3, figures.dead.count);

      // this doc does not exist. should not change the figures
      try {
        collection.replace("a2", { });
        fail();
      }
      catch (e3) {
      }

      internal.wal.flush(true, true);
      figures = collection.figures();

      assertEqual(1, figures.alive.count);
      assertEqual(3, figures.dead.count);
    }
  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

jsunity.run(FiguresSuite);

return jsunity.done();

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:

<commit_msg>test fix attempt<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief test the collection interface
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var jsunity = require("jsunity");

var arangodb = require("org/arangodb");
var internal = require("internal");

var ArangoCollection = arangodb.ArangoCollection;
var db = arangodb.db;
var ERRORS = arangodb.errors;
var testHelper = require("org/arangodb/test-helper").Helper;

// -----------------------------------------------------------------------------
// --SECTION--                                                    figure methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: FiguresSuite
////////////////////////////////////////////////////////////////////////////////

function FiguresSuite () {
  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief figures
////////////////////////////////////////////////////////////////////////////////

    testFigures : function () {
      var collection = "example";

      db._drop(collection);
      var c1 = db._create(collection);

      c1.load();

      var f = c1.figures();
      assertEqual(0, f.datafiles.count);
      assertEqual(0, f.compactors.count);
      assertEqual(0, f.shapefiles.count);
      assertEqual(0, f.shapefiles.fileSize);
      assertEqual(0, f.alive.count);
      assertEqual(0, f.alive.size);
      assertEqual(0, f.dead.count);
      assertEqual(0, f.dead.size);
      assertEqual(0, f.dead.deletion);

      var d1 = c1.save({ hello : 1 });

      internal.wal.flush(true, true);

      var tries = 0;
      while (++tries < 20) {
        f = c1.figures();
        if (f.alive.count === 1) {
          break;
        }
        internal.wait(1, false);
      }

      assertEqual(0, f.datafiles.count);
      assertEqual(0, f.datafiles.fileSize);
      assertEqual(1, f.journals.count);
      assertTrue(f.journals.fileSize > 0);
      assertEqual(0, f.compactors.count);
      assertEqual(0, f.shapefiles.count);
      assertEqual(0, f.shapefiles.fileSize);
      assertEqual(1, f.alive.count);
      assertNotEqual(0, f.alive.size);
      assertEqual(0, f.dead.count);
      assertEqual(0, f.dead.size);
      assertEqual(0, f.dead.deletion);

      var d2 = c1.save({ hello : 2 });

      internal.wal.flush(true, true);
      f = c1.figures();

      assertEqual(0, f.datafiles.count);
      assertEqual(0, f.datafiles.fileSize);

      assertEqual(1, f.journals.count);
      assertTrue(f.journals.fileSize > 0);
      assertEqual(2, f.alive.count);
      assertNotEqual(0, f.alive.size);
      assertEqual(0, f.dead.count);
      assertEqual(0, f.dead.size);
      assertEqual(0, f.dead.deletion);

      c1.remove(d1);

      internal.wal.flush(true, true);
      f = c1.figures();

      assertEqual(0, f.datafiles.count);
      assertEqual(0, f.datafiles.fileSize);
      assertEqual(1, f.journals.count);
      assertTrue(f.journals.fileSize > 0);
      assertEqual(1, f.alive.count);
      assertNotEqual(0, f.alive.size);
      assertEqual(1, f.dead.count);
      assertNotEqual(0, f.dead.size);
      assertEqual(1, f.dead.deletion);

      c1.remove(d2);

      internal.wal.flush(true, true);
      f = c1.figures();

      assertEqual(0, f.datafiles.count);
      assertEqual(0, f.datafiles.fileSize);
      assertEqual(1, f.journals.count);
      assertTrue(f.journals.fileSize > 0);
      assertEqual(0, f.alive.count);
      assertEqual(0, f.alive.size);
      assertEqual(2, f.dead.count);
      assertNotEqual(0, f.dead.size);
      assertEqual(2, f.dead.deletion);

      var attributes = f.attributes.count;
      var shapes = f.shapes.count;

      c1.save({ b0rk : "abc" });

      internal.wal.flush(true, true);
      f = c1.figures();

      assertEqual(attributes + 1, f.attributes.count);
      assertEqual(shapes + 1, f.shapes.count);

      db._drop(collection);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief check figures
////////////////////////////////////////////////////////////////////////////////

    testFiguresAfterOperations : function () {
      var cnName = "example";

      db._drop(cnName);
      var collection = db._create(cnName);

      collection.load();
      var figures;

      collection.save({ _key : "a1" });
      collection.save({ _key : "a2" });
      collection.save({ _key : "a3" });

      internal.wal.flush(true, true);
      figures = collection.figures();

      assertEqual(3, figures.alive.count);
      assertEqual(0, figures.dead.count);

      // insert a few duplicates
      try {
        collection.save({ _key : "a1" });
        fail();
      }
      catch (e1) {
      }

      try {
        collection.save({ _key : "a2" });
        fail();
      }
      catch (e2) {
      }

      // we should see the same figures
      internal.wal.flush(true, true);
      figures = collection.figures();

      assertEqual(3, figures.alive.count);
      assertEqual(0, figures.dead.count);

      // now remove some documents
      collection.remove("a2");
      collection.remove("a3");

      // we should see two live docs less
      internal.wal.flush(true, true);
      figures = collection.figures();

      assertEqual(1, figures.alive.count);
      assertEqual(2, figures.dead.count);

      // replacing one document does not change alive, but increases dead!
      collection.replace("a1", { });

      internal.wal.flush(true, true);
      figures = collection.figures();

      assertEqual(1, figures.alive.count);
      assertEqual(3, figures.dead.count);

      // this doc does not exist. should not change the figures
      try {
        collection.replace("a2", { });
        fail();
      }
      catch (e3) {
      }

      internal.wal.flush(true, true);
      figures = collection.figures();

      assertEqual(1, figures.alive.count);
      assertEqual(3, figures.dead.count);
    }
  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

jsunity.run(FiguresSuite);

return jsunity.done();

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:

<|endoftext|>


<commit_before>'use strict';

var InstitutionModel = require('../../../models').Institutions;

module.exports = function(router) {
    router.get('/', function(req, res) {
        InstitutionModel.find(function(err, data) {
            res.send(err ? {
                'error': 'API Error',
                'message': 'Error occurred'
            } : data);
        });
    });
};
<commit_msg>:mailbox_with_mail: POST method for institutions<commit_after>'use strict';

var InstitutionModel = require('../../../models').Institutions,
    shortid = require('shortid');

module.exports = function(router) {
    router.get('/', function(req, res) {
        InstitutionModel.find(function(err, data) {
            res.json(err ? {
                'error': 'API Error',
                'message': 'Error occurred'
            } : data);
        });
    });

    router.post('/', function(req, res) {
        var response = {};
        if (typeof req.body.name === 'undefined' || req.body.name === '') {
            response = {
                'error': 'Incorrect params',
                'message': 'Name cannot be empty'
            };
        }
        if (typeof req.body.address === 'undefined' || req.body.address === '') {
            response = {
                'error': 'Incorrect params',
                'message': 'Address cannot be empty'
            };
        }
        if (typeof req.body.capacity === 'undefined' || req.body.capacity === '') {
            response = {
                'error': 'Incorrect params',
                'message': 'Capacity cannot be empty'
            };
        }
        if (typeof req.body.category === 'undefined' || req.body.category === '') {
            response = {
                'error': 'Incorrect params',
                'message': 'Category cannot be empty'
            };
        }
        if (!Object.keys(response).length) {
            var model = {
                id: shortid.generate(),
                name: req.body.name,
                address: req.body.address,
                category: req.body.category.split(','),
                capacity: req.body.capacity
            };

            InstitutionModel(model).save(function(err, data) {
                res.json(err ? {
                    'error': 'API Error',
                    'message': 'Could not add institution'
                } : data);
            });
        } else {
            res.json(response);
        }
    });
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow strict
 */

'use strict';

export type AccessibilityTrait =
  | 'none'
  | 'button'
  | 'link'
  | 'header'
  | 'search'
  | 'image'
  | 'selected'
  | 'plays'
  | 'key'
  | 'text'
  | 'summary'
  | 'disabled'
  | 'frequentUpdates'
  | 'startsMedia'
  | 'adjustable'
  | 'allowsDirectInteraction'
  | 'pageTurn';

export type AccessibilityTraits =
  | AccessibilityTrait
  | $ReadOnlyArray<AccessibilityTrait>;

export type AccessibilityComponentType =
  | 'none'
  | 'button'
  | 'radiobutton_checked'
  | 'radiobutton_unchecked';

export type AccessibilityRole =
  | 'none'
  | 'button'
  | 'link'
  | 'search'
  | 'image'
  | 'keyboardkey'
  | 'text'
  | 'adjustable'
  | 'imagebutton';

export type CurrentViewState = 'selected' | 'disabled';

export type CurrentViewStates =
  | CurrentViewState
  | $ReadOnlyArray<CurrentViewState>;

module.exports = {
  AccessibilityTraits: [
    'none',
    'button',
    'link',
    'header',
    'search',
    'image',
    'selected',
    'plays',
    'key',
    'text',
    'summary',
    'disabled',
    'frequentUpdates',
    'startsMedia',
    'adjustable',
    'allowsDirectInteraction',
    'pageTurn',
  ],
  AccessibilityComponentTypes: [
    'none',
    'button',
    'radiobutton_checked',
    'radiobutton_unchecked',
  ],
  AccessibilityRoles: [
    'none',
    'button',
    'link',
    'search',
    'image',
    'keyboardkey',
    'text',
    'adjustable',
    'imagebutton',
  ],
  CurrentViewStates: ['selected', 'disabled'],
};
<commit_msg>added header and summary options for roles<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow strict
 */

'use strict';

export type AccessibilityTrait =
  | 'none'
  | 'button'
  | 'link'
  | 'header'
  | 'search'
  | 'image'
  | 'selected'
  | 'plays'
  | 'key'
  | 'text'
  | 'summary'
  | 'disabled'
  | 'frequentUpdates'
  | 'startsMedia'
  | 'adjustable'
  | 'allowsDirectInteraction'
  | 'pageTurn';

export type AccessibilityTraits =
  | AccessibilityTrait
  | $ReadOnlyArray<AccessibilityTrait>;

export type AccessibilityComponentType =
  | 'none'
  | 'button'
  | 'radiobutton_checked'
  | 'radiobutton_unchecked';

export type AccessibilityRole =
  | 'none'
  | 'button'
  | 'link'
  | 'search'
  | 'image'
  | 'keyboardkey'
  | 'text'
  | 'adjustable'
  | 'imagebutton'
  | 'header'
  | 'summary';

export type CurrentViewState = 'selected' | 'disabled';

export type CurrentViewStates =
  | CurrentViewState
  | $ReadOnlyArray<CurrentViewState>;

module.exports = {
  AccessibilityTraits: [
    'none',
    'button',
    'link',
    'header',
    'search',
    'image',
    'selected',
    'plays',
    'key',
    'text',
    'summary',
    'disabled',
    'frequentUpdates',
    'startsMedia',
    'adjustable',
    'allowsDirectInteraction',
    'pageTurn',
  ],
  AccessibilityComponentTypes: [
    'none',
    'button',
    'radiobutton_checked',
    'radiobutton_unchecked',
  ],
  AccessibilityRoles: [
    'none',
    'button',
    'link',
    'search',
    'image',
    'keyboardkey',
    'text',
    'adjustable',
    'imagebutton',
    'header',
    'summary',
  ],
  CurrentViewStates: ['selected', 'disabled'],
};
<|endoftext|>


<commit_before>import babel from 'rollup-plugin-babel';

module.exports = {
  entry: './src/index.js',
  format: 'iife',
  globals: {
    webcharts: 'webCharts',
    d3: 'd3',
    spikeHistogram: 'spikeHistogram'
  },
  moduleName: 'webcodebook',
   plugins: [
    babel(
      {
        "presets": [
          [
            "es2015",
            {
              "modules": false
            }
          ]
        ],
        "plugins": [
          "external-helpers"
        ],
        "exclude": "node_modules/**"
      })
  ]
};

<commit_msg>remove spike-hist dependency<commit_after>import babel from 'rollup-plugin-babel';

module.exports = {
  entry: './src/index.js',
  format: 'iife',
  globals: {
    webcharts: 'webCharts',
    d3: 'd3'
  },
  moduleName: 'webcodebook',
   plugins: [
    babel(
      {
        "presets": [
          [
            "es2015",
            {
              "modules": false
            }
          ]
        ],
        "plugins": [
          "external-helpers"
        ],
        "exclude": "node_modules/**"
      })
  ]
};
<|endoftext|>


<commit_before>'use strict';

const mongoose = require('mongoose');
const Residence = require('./residence.js');

const incidentSchema = mongoose.Schema({
  userId: { type: mongoose.Schema.Types.ObjectId, ref: 'user', required: true },
  timeStamp: { type: Date, default: Date.now() },
  type: { type: String, required: true },
  description: { type: String, required: true },
  residenceId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'residence',
    required: true
  },
  comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'comments', }]
});

incidentSchema.pre('save', function(next) {
  Residence.findById(this.residence)
    .then(() => next())
    .catch(() =>
      next(
        new Error(
          'Validation failed - failed to create Incident, residence does not exist'
        )
      )
    );
});

incidentSchema.post('save', function(doc, next) {
  Residence.findById(doc.residenceId)
    .then(residence => {
      let incidentIDSet = new Set(residence.incidents);
      incidentIDSet.add(this._id.toString());
      residence.incidents = Array.from(incidentIDSet);
      return residence.save();
    })
    .then(() => next())
    .catch(next);
});

incidentSchema.post('remove', function(doc, next) {
  Residence.findById(doc.residence)
    .then(residence => {
      residence.incidents = residence.incidents.filter(
        incident => incident._id !== doc._id
      );
      return residence.save();
    })
    .then(() => next)
    .catch(next);
});

module.exports = mongoose.model('incidents', incidentSchema);
<commit_msg>change incidents model to incident<commit_after>'use strict';

const mongoose = require('mongoose');
const Residence = require('./residence.js');

const incidentSchema = mongoose.Schema({
  userId: { type: mongoose.Schema.Types.ObjectId, ref: 'user', required: true },
  timeStamp: { type: Date, default: Date.now() },
  type: { type: String, required: true },
  description: { type: String, required: true },
  residenceId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'residence',
    required: true
  },
  comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'comments', }]
});

incidentSchema.pre('save', function(next) {
  Residence.findById(this.residence)
    .then(() => next())
    .catch(() =>
      next(
        new Error(
          'Validation failed - failed to create Incident, residence does not exist'
        )
      )
    );
});

incidentSchema.post('save', function(doc, next) {
  Residence.findById(doc.residenceId)
    .then(residence => {
      let incidentIDSet = new Set(residence.incidents);
      incidentIDSet.add(this._id.toString());
      residence.incidents = Array.from(incidentIDSet);
      return residence.save();
    })
    .then(() => next())
    .catch(next);
});

incidentSchema.post('remove', function(doc, next) {
  Residence.findById(doc.residence)
    .then(residence => {
      residence.incidents = residence.incidents.filter(
        incident => incident._id !== doc._id
      );
      return residence.save();
    })
    .then(() => next)
    .catch(next);
});

module.exports = mongoose.model('incident', incidentSchema);
<|endoftext|>


<commit_before>import React from 'react';
import { beforeEach, it, describe } from 'mocha';
import { expect } from 'chai';
import { Interactor } from '@bigtest/interactor';

import { mount } from '../../../tests/helpers';

import DropdownMenu from '../DropdownMenu';

const dropdownMenuId = 'dropdownMenu';
const mountDropdownMenu = ({ open }) => (
  mount(
    <DropdownMenu
      open={open}
      id="dropdownMenu"
    >

Select All

    </DropdownMenu>
  )
);

describe('DropdownMenu', () => {
  const dropdownMenu = new Interactor(`#${dropdownMenuId}`);

  describe('When opened', () => {
    beforeEach(async () => {
      await mountDropdownMenu({ open: true });
    });

    it('Than should be visible', () => {
      expect(dropdownMenu.isVisible).to.be.true;
    });
  });

  describe('When closed', () => {
    beforeEach(async () => {
      await mountDropdownMenu({ open: false });
    });

    it('Than should not be visible', () => {
      expect(dropdownMenu.isVisible).to.be.false;
    });
  });
});
<commit_msg>Upgrade Dropdownmenu tests/interactors. (#1850)<commit_after>import React from 'react';
import { beforeEach, it, describe } from 'mocha';
import { Bigtest } from '@folio/stripes-testing';
import { mount } from '../../../tests/helpers';

import DropdownMenu from '../DropdownMenu';

const HTML = Bigtest.HTML;

const dropdownMenuId = 'dropdownMenu';
const mountDropdownMenu = ({ open }) => (
  mount(
    <DropdownMenu
      open={open}
      id="dropdownMenu"
    >

Select All

    </DropdownMenu>
  )
);

describe('DropdownMenu', () => {
  const dropdownMenu = HTML({ id: `${dropdownMenuId}` });

  describe('When opened', () => {
    beforeEach(async () => {
      await mountDropdownMenu({ open: true });
    });

    it('Than should be visible', () => dropdownMenu.exists());
  });

  describe('When closed', () => {
    beforeEach(async () => {
      await mountDropdownMenu({ open: false });
    });

    it('Than should not be visible', () => dropdownMenu.absent());
  });
});
<|endoftext|>


<commit_before>import Kinds from '../kube-kinds'
import { putResource, removeResource } from '../state/actions/workloads'
import { addError } from '../state/actions/errors'
import { keyForResource } from '../utils/resource-utils'

const throttles = {
  'Endpoints/MODIFIED': 10000,
}
const throttlePurgeInterval = 2 * 60 * 1000
const aggregationInterval = 1000

export default class ResourceKindWatcher {

  constructor(props) {

    this.props = props
    this.tries = 0
    if (!!props.kind && !!props.dispatch && !!props.resourceGroup) {
      this.initialize()
    }
  }

  initialize = () => {
    let { props } = this
    let dispatch = this.dispatch = props.dispatch
    let kind = this.kind = Kinds[props.resourceGroup][props.kind]
    let resourceVersion = props.resourceVersion || 0
    let loc = window.location
    let scheme = (loc.protocol === 'https:' ? 'wss' : 'ws')

    let url = `${scheme}://${loc.host}/proxy`
    url += `/${kind.base}/watch/${this.kind.plural}`
    url += `?watch=true&resourceVersion=${resourceVersion}`

    this.socket = new WebSocket(url)
    this.socket.onerror = function (e) {
      console.error(`ResourceKindWatcher(${kind.plural})`, e)
      if (this.tries < 3) {
        ++this.tries
        window.setTimeout(this.reset.bind(this), 2000)
      } else {
        dispatch(addError(e,'error',`WebSocket error occurred while creating watch for ${kind.plural}`,
          'Try Again', () => { this.initialize() }))
      }
    }
    this.socket.onmessage = this.onEvent.bind(this)
    console.log(`ResourceKindWatcher<${this.kind.plural}> created`)
    this.throttled = {}
    this.lastPurge = Date.now()
    this.events = {}
    this.interval = window.setInterval(this.processEvents.bind(this), props.interval || aggregationInterval)
  }

  processEvents = () => {
    if (Object.keys(this.events).length) {
      for (let key in this.events) {
        let data = this.events[key]
        switch(data.type) {
          case 'ADDED':
            this.dispatch(putResource(data.object, true))
            break
          case 'MODIFIED':
            this.dispatch(putResource(data.object, false))
            break
          case 'DELETED':
            this.dispatch(removeResource(data.object))
            break
          default:
            return
        }
      }
      this.events = {}
    }
  }

  closed = () => {
    return !this.socket || this.socket.readyState === 3 || this.socket.readyState === 2
  }

  onEvent = (event) => {
    let data = this.applyThrottles(JSON.parse(event.data))
    if (!!data) {
      let key = keyForResource(data.object)
      this.events[key] = data
    }
  }

  destroy = () => {
    this.interval && window.clearInterval(this.interval)
    this.socket && this.socket.close()
  }

  reset = () => {
    this.destroy()
    this.initialize()
  }

  /**
   *
   */
  applyThrottles = (data) => {
    let resource = data.object
    let throttle = throttles[`${resource.kind}/${data.type}`]
    if (!!throttle) {
      let key = `${resource.metadata.namespace}/${resource.kind}/${resource.metadata.name}/${data.type}`
      let lastSeen = this.throttled[key] || 0
      let now = Date.now()
      this.purgeThrottles(now)
      if ((now - lastSeen) > throttle) {
        this.throttled[key] = now
        return data
      }
      return null
    }
    return data
  }

  purgeThrottles = (now) => {
    if ((now - this.lastPurge) > throttlePurgeInterval) {
      for (let t in this.throttled) {
        let throttle = throttles[t]
        let lastSeen = this.throttled[t]
        if (now - lastSeen > throttle) {
          delete this.throttled[t]
        }
      }
      this.lastPurge = now
    }
  }

}
<commit_msg>bind resource kind watcher for retries<commit_after>import Kinds from '../kube-kinds'
import { putResource, removeResource } from '../state/actions/workloads'
import { addError } from '../state/actions/errors'
import { keyForResource } from '../utils/resource-utils'

const throttles = {
  'Endpoints/MODIFIED': 10000,
}
const throttlePurgeInterval = 2 * 60 * 1000
const aggregationInterval = 1000

export default class ResourceKindWatcher {

  constructor(props) {

    this.props = props
    this.tries = 0
    this.initialize = this.initialize.bind(this)
    if (!!props.kind && !!props.dispatch && !!props.resourceGroup) {
      this.initialize()
    }
  }

  initialize = () => {
    let { props } = this
    let dispatch = this.dispatch = props.dispatch
    let kind = this.kind = Kinds[props.resourceGroup][props.kind]
    let resourceVersion = props.resourceVersion || 0
    let loc = window.location
    let scheme = (loc.protocol === 'https:' ? 'wss' : 'ws')

    let url = `${scheme}://${loc.host}/proxy`
    url += `/${kind.base}/watch/${this.kind.plural}`
    url += `?watch=true&resourceVersion=${resourceVersion}`

    this.socket = new WebSocket(url)
    this.socket.onerror = function (e) {
      console.error(`ResourceKindWatcher(${kind.plural})`, e)
      if (this.tries < 3) {
        ++this.tries
        window.setTimeout(this.reset.bind(this), 2000)
      } else {
        dispatch(addError(e,'error',`WebSocket error occurred while creating watch for ${kind.plural}`,
          'Try Again', () => { this.initialize() }))
      }
    }
    this.socket.onmessage = this.onEvent.bind(this)
    console.log(`ResourceKindWatcher<${this.kind.plural}> created`)
    this.throttled = {}
    this.lastPurge = Date.now()
    this.events = {}
    this.interval = window.setInterval(this.processEvents.bind(this), props.interval || aggregationInterval)
  }

  processEvents = () => {
    if (Object.keys(this.events).length) {
      for (let key in this.events) {
        let data = this.events[key]
        switch(data.type) {
          case 'ADDED':
            this.dispatch(putResource(data.object, true))
            break
          case 'MODIFIED':
            this.dispatch(putResource(data.object, false))
            break
          case 'DELETED':
            this.dispatch(removeResource(data.object))
            break
          default:
            return
        }
      }
      this.events = {}
    }
  }

  closed = () => {
    return !this.socket || this.socket.readyState === 3 || this.socket.readyState === 2
  }

  onEvent = (event) => {
    let data = this.applyThrottles(JSON.parse(event.data))
    if (!!data) {
      let key = keyForResource(data.object)
      this.events[key] = data
    }
  }

  destroy = () => {
    this.interval && window.clearInterval(this.interval)
    this.socket && this.socket.close()
  }

  reset = () => {
    this.destroy()
    this.initialize()
  }

  /**
   *
   */
  applyThrottles = (data) => {
    let resource = data.object
    let throttle = throttles[`${resource.kind}/${data.type}`]
    if (!!throttle) {
      let key = `${resource.metadata.namespace}/${resource.kind}/${resource.metadata.name}/${data.type}`
      let lastSeen = this.throttled[key] || 0
      let now = Date.now()
      this.purgeThrottles(now)
      if ((now - lastSeen) > throttle) {
        this.throttled[key] = now
        return data
      }
      return null
    }
    return data
  }

  purgeThrottles = (now) => {
    if ((now - this.lastPurge) > throttlePurgeInterval) {
      for (let t in this.throttled) {
        let throttle = throttles[t]
        let lastSeen = this.throttled[t]
        if (now - lastSeen > throttle) {
          delete this.throttled[t]
        }
      }
      this.lastPurge = now
    }
  }

}
<|endoftext|>


<commit_before>var ids = {
  google: {
    clientID: 'get_your_own',
    clientSecret: 'get_your_own',
    callbackURL: 'http://localhost:3000/auth/google/callback'
  }

};

module.exports = ids;<commit_msg>removed test file oauth.js<commit_after><|endoftext|>


<commit_before>//Kanye Quest

// MAKE BRANCH FOR:
//(PROM EDITION) - 3 keys, once collected go to boss door
//                 Fight enemy to save princess, defeat
//                 enemy,
//(SPACE THEMED) - Explore the universe and go to prom with me (or something like that I guess)

var GRAVITY = .4; //Constant
var JUMP = -10; //constant
var GROUND, BG, PLAYER, BOSS_CASTLE, ENEMIES, FIRE, STRUCTURES, CLOUDS; //Sprites
var GroundImg, BgImg, PlayerImg, EnemyImg, FireImg; //Images

var FireCounter = 100;
var FireStatus;
var PlayerHealth = 100;
function preload() {

    // GroundImg = loadImage('http://i.imgur.com/p6L1baG.png');
    // FireImg = loadImage('http://i.imgur.com/0NUZboL.png');
    // PlayerImg = loadImage('http://i.imgur.com/AljRUIL.png');

}

function setup() {
  createCanvas(700,600);
  //Length of game strip: 4,000 pixels
  //start @ x = 0
  //end @ x = 4000

  //Sizing is tmp for mechanics:      width height
  GROUND = createSprite(width/2, 550, 1400, 100);
  // GROUND.addImage(GroundImg);

  //BG = createSprite();

  PLAYER = createSprite(width/2, 475, 50, 50);
  // PLAYER.addImage(PlayerImg);
  PLAYER.setCollider("circle", 0,0,50);

  BOSS_CASTLE = createSprite(3500, 475, 400, 400);
  BOSS_CASTLE.setCollider();

  FireStatus = createSprite(125, 50, 200, 50);
  PlayerHealth = createSprite(125, 110, 200, 50);

  ENEMIES = new Group();
  FIRE = new Group();
  STRUCTURES = new Group();
  CLOUDS = new Group();

}

function draw() {
  background(100, 150, 200);
  textAlign(CENTER);
  PLAYER.velocity.y += GRAVITY;

  //Player GUI movement
  FireStatus.position.x = camera.position.x + (FireCounter - 100) - width/2 + 125;
  PlayerHealth.position.x = camera.position.x - width/2 + 125;
  FireStatus.width = FireCounter * 2;

  FireStatus.depth = 3;
  PlayerHealth.depth = 3;
  //PLAYER and CAMERA bounds
    //  Says that CAMERA will always follow PLAYER except out of bounds
  if(PLAYER.position.x >= 3850){
    camera.position.x = 3850;
  } else if(PLAYER.position.x <= 350){
    camera.position.x = 350;
  } else {
    camera.position.x = PLAYER.position.x;
  }

    //  bounding for PLAYER
  if(PLAYER.position.x < 50) {
    PLAYER.position.x = 50;
  } else if(PLAYER.position.x > 3850) {
    PLAYER.position.x = 3850;
  }

  if(PLAYER.position.y < 250) {
     PLAYER.position.y = 250;
  }

  /*

  End of PLAYER | CAMERA | GUI bounding

  */

  //Wrap ground

    //  My better-than-alex's attempt to get the ground to wrap with movement
  if(camera.position.x > GROUND.position.x + width / 4) {
    GROUND.position.x += GROUND.width / 6;
  } else if(camera.position.x < GROUND.position.x - width / 4) {
    GROUND.position.x -= GROUND.width / 6;
  }
  /*

  End of ground wrapping.

  */

  //Abilities

    //  Left | Right
  if(keyDown(65)) {
    PLAYER.position.x -= playerStep;
    PLAYER.mirrorX(1);
  } else if(keyDown(68)) {
    PLAYER.position.x += playerStep;
    PLAYER.mirrorX(-1);
  }

    //  Jump
  if(keyWentDown(87)) {
    PLAYER.velocity.y = JUMP;
  }

    //  Sprinting
  if(keyDown(16)) { //SHIFT keycode = 16
    playerStep = 9;
  } else {
    playerStep = 4;
  }

  if(FireCounter < 100) {
    FireCounter += .1;
  }

  //  Player spits fire
  if(keyWentDown(32) && FireCounter >= 10) {
      var fire = createSprite(PLAYER.position.x - 20 * PLAYER.mirrorX(), PLAYER.position.y);
      //fire.addImage(FireImg);
      fire.life = 40;
      fire.setSpeed(-(11 + playerStep) * PLAYER.mirrorX(), 0);
      fire.mirrorX(-1 * PLAYER.mirrorX());
      FIRE.add(fire);

      FireCounter -= 10;
  }

  //Prevents player from falling through ground (?)
  if(PLAYER.collide(GROUND)) {
    PLAYER.velocity.y = 0;
  }

  /*

  End of PLAYER code.

  */

  //Check values here
  console.log("FireStatus.position.x: " + FireStatus.position.x);

  //Environment sprites

    //  Create Enemies
  for(var i = ENEMIES.length; i < 2; i++) {
    var posX = random(PLAYER.position.x - (width/2), PLAYER.position.x + (width/2));
    var posY = 475;
    createEnemy(posX, posY);

    // if(ENEMIES.get(i).overlap(STRUCTURES)) {
    //   if(ENEMIES.get(i).getDirection == 180) {
    //     ENEMIES.get(i).setSpeed(1, 0);
    //   } else {
    //     ENEMIES.get(i).setSpeed(-1, 0)
    //   }
    // }
  }

    //  Remove Enemies
  for (var i = 0; i < ENEMIES.length; i++) {
    if(ENEMIES[i].position.x + (ENEMIES[i].width / 2) < PLAYER.position.x - (width / 2) || ENEMIES[i].position.x - (ENEMIES[i].width / 2) > PLAYER.position.x + (width / 2)) {
      ENEMIES[i].remove();
    }
  }

    //  Structures
  if(frameCount % 60 == 0) {

  }

  var min = camera.position.x - width / 2 - 75;
  var max = camera.position.x + width / 2 + 75;

  //Clouds

    //  Create Clouds
  for(var i = CLOUDS.length; i < 21; i++) {

    var posY = random(height / 3, 0);

    if(i <= 10) {
      // generates an x position that is onscreen
      var posX = random(min, max);

    } else {
      // generates an x position to the next screen over, depending on which way the player is facing
      var posX = random(min - width * PLAYER.mirrorX(), max - width * PLAYER.mirrorX());
    }
    createCloud(posX, posY);
  }

    //  Remove Clouds
  for(var i = 0; i < CLOUDS.length; i++) {
    if(CLOUDS[i].position.x + (CLOUDS[i].width / 2) < min - width - (width * PLAYER.mirrorX()) || CLOUDS[i].position.x - (CLOUDS[i].width / 2) > max + width - (width * PLAYER.mirrorX())) {
      CLOUDS[i].remove();
    }
  }

  //Debug
  GROUND.debug = true;
  PLAYER.debug = true;
  BOSS_CASTLE.debug = true;

  drawSprites();
}

//Creates an enemy
function createEnemy(x, y) {
  var enemy = createSprite(x, y, 50, 50);
  //add img for enemy here (?)

  enemy.setSpeed(-1, 0);
  enemy.debug = true;
  enemy.setCollider("circle", 0,0,50);
  ENEMIES.add(enemy);

  return enemy;
}

//Creates a cloud
function createCloud(x, y) {
  var newCloud = createSprite(x ,y, random(50, 75), random(16, 32));
      newCloud.depth = y / 100;
  // newCloud.setCollider("rectangle");
  CLOUDS.add(newCloud);

  return newCloud;
}
<commit_msg>0.31 beta<commit_after>//Kanye Quest

// MAKE BRANCH FOR:
//(PROM EDITION) - 3 keys, once collected go to boss door
//                 Fight enemy to save princess, defeat
//                 enemy,
//(SPACE THEMED) - Explore the universe and go to prom with me (or something like that I guess)

var GRAVITY = .4; //Constant
var JUMP = -10; //constant
var GROUND, BG, PLAYER, BOSS_CASTLE, ENEMIES, FIRE, STRUCTURES, CLOUDS; //Sprites
var GroundImg, BgImg, PlayerImg, EnemyImg, FireImg; //Images

var FireCounter = 100;
var FireStatus;
    FireStatus.depth = 10;
var PlayerHealth = 100;
    PlayerHealth.depth = 10;
function preload() {

    // GroundImg = loadImage('http://i.imgur.com/p6L1baG.png');
    // FireImg = loadImage('http://i.imgur.com/0NUZboL.png');
    // PlayerImg = loadImage('http://i.imgur.com/AljRUIL.png');

}

function setup() {
  createCanvas(700,600);
  //Length of game strip: 4,000 pixels
  //start @ x = 0
  //end @ x = 4000

  //Sizing is tmp for mechanics:      width height
  GROUND = createSprite(width/2, 550, 1400, 100);
  // GROUND.addImage(GroundImg);

  //BG = createSprite();

  PLAYER = createSprite(width/2, 475, 50, 50);
  // PLAYER.addImage(PlayerImg);
  PLAYER.setCollider("circle", 0,0,50);

  BOSS_CASTLE = createSprite(3500, 475, 400, 400);
  BOSS_CASTLE.setCollider();

  FireStatus = createSprite(125, 50, 200, 50);
  PlayerHealth = createSprite(125, 110, 200, 50);

  ENEMIES = new Group();
  FIRE = new Group();
  STRUCTURES = new Group();
  CLOUDS = new Group();

}

function draw() {
  background(100, 150, 200);
  textAlign(CENTER);
  PLAYER.velocity.y += GRAVITY;

  //Player GUI movement
  FireStatus.position.x = camera.position.x + (FireCounter - 100) - width/2 + 125;
  PlayerHealth.position.x = camera.position.x - width/2 + 125;
  FireStatus.width = FireCounter * 2;

  //PLAYER and CAMERA bounds
    //  Says that CAMERA will always follow PLAYER except out of bounds
  if(PLAYER.position.x >= 3850){
    camera.position.x = 3850;
  } else if(PLAYER.position.x <= 350){
    camera.position.x = 350;
  } else {
    camera.position.x = PLAYER.position.x;
  }

    //  bounding for PLAYER
  if(PLAYER.position.x < 50) {
    PLAYER.position.x = 50;
  } else if(PLAYER.position.x > 3850) {
    PLAYER.position.x = 3850;
  }

  if(PLAYER.position.y < 250) {
     PLAYER.position.y = 250;
  }

  /*

  End of PLAYER | CAMERA | GUI bounding

  */

  //Wrap ground

    //  My better-than-alex's attempt to get the ground to wrap with movement
  if(camera.position.x > GROUND.position.x + width / 4) {
    GROUND.position.x += GROUND.width / 6;
  } else if(camera.position.x < GROUND.position.x - width / 4) {
    GROUND.position.x -= GROUND.width / 6;
  }
  /*

  End of ground wrapping.

  */

  //Abilities

    //  Left | Right
  if(keyDown(65)) {
    PLAYER.position.x -= playerStep;
    PLAYER.mirrorX(1);
  } else if(keyDown(68)) {
    PLAYER.position.x += playerStep;
    PLAYER.mirrorX(-1);
  }

    //  Jump
  if(keyWentDown(87)) {
    PLAYER.velocity.y = JUMP;
  }

    //  Sprinting
  if(keyDown(16)) { //SHIFT keycode = 16
    playerStep = 9;
  } else {
    playerStep = 4;
  }

  if(FireCounter < 100) {
    FireCounter += .1;
  }

  //  Player spits fire
  if(keyWentDown(32) && FireCounter >= 10) {
      var fire = createSprite(PLAYER.position.x - 20 * PLAYER.mirrorX(), PLAYER.position.y);
      //fire.addImage(FireImg);
      fire.life = 40;
      fire.setSpeed(-(11 + playerStep) * PLAYER.mirrorX(), 0);
      fire.mirrorX(-1 * PLAYER.mirrorX());
      FIRE.add(fire);

      FireCounter -= 10;
  }

  //Prevents player from falling through ground (?)
  if(PLAYER.collide(GROUND)) {
    PLAYER.velocity.y = 0;
  }

  /*

  End of PLAYER code.

  */

  //Check values here
  console.log("FireStatus.position.x: " + FireStatus.position.x);

  //Environment sprites

    //  Create Enemies
  for(var i = ENEMIES.length; i < 2; i++) {
    var posX = random(PLAYER.position.x - (width/2), PLAYER.position.x + (width/2));
    var posY = 475;
    createEnemy(posX, posY);

    // if(ENEMIES.get(i).overlap(STRUCTURES)) {
    //   if(ENEMIES.get(i).getDirection == 180) {
    //     ENEMIES.get(i).setSpeed(1, 0);
    //   } else {
    //     ENEMIES.get(i).setSpeed(-1, 0)
    //   }
    // }
  }

    //  Remove Enemies
  for (var i = 0; i < ENEMIES.length; i++) {
    if(ENEMIES[i].position.x + (ENEMIES[i].width / 2) < PLAYER.position.x - (width / 2) || ENEMIES[i].position.x - (ENEMIES[i].width / 2) > PLAYER.position.x + (width / 2)) {
      ENEMIES[i].remove();
    }
  }

    //  Structures
  if(frameCount % 60 == 0) {

  }

  var min = camera.position.x - width / 2 - 75;
  var max = camera.position.x + width / 2 + 75;

  //Clouds

    //  Create Clouds
  for(var i = CLOUDS.length; i < 21; i++) {

    var posY = random(height / 3, 0);

    if(i <= 10) {
      // generates an x position that is onscreen
      var posX = random(min, max);
    } else {
      // generates an x position to the next screen over, depending on which way the player is facing
      var posX = random(min - width * PLAYER.mirrorX(), max - width * PLAYER.mirrorX());
    }
    createCloud(posX, posY);
  }
    //  Remove Clouds
  for(var i = 0; i < CLOUDS.length; i++) {
    if(CLOUDS[i].position.x + (CLOUDS[i].width / 2) < min - width - (width * PLAYER.mirrorX()) || CLOUDS[i].position.x - (CLOUDS[i].width / 2) > max + width - (width * PLAYER.mirrorX())) {
      CLOUDS[i].remove();
    }
  }

  //Debug
  GROUND.debug = true;
  PLAYER.debug = true;
  BOSS_CASTLE.debug = true;

  drawSprites();
}

//Creates an enemy
function createEnemy(x, y) {
  var enemy = createSprite(x, y, 50, 50);
  //add img for enemy here (?)

  enemy.setSpeed(-1, 0);
  enemy.debug = true;
  enemy.setCollider("circle", 0,0,50);
  ENEMIES.add(enemy);

  return enemy;
}

//Creates a cloud
function createCloud(x, y) {
  var newCloud = createSprite(x ,y, random(50, 75), random(16, 32));
      newCloud.depth = y / 100;
  // newCloud.setCollider("rectangle");
  CLOUDS.add(newCloud);

  return newCloud;
}
<|endoftext|>


<commit_before>module.exports = function Hashcash (difficulty) {

  function isValid (input) {
    var parts = input.split(':');

    if (parts[1] < difficulty) {
      return false;
    }

    return true;
  }

  return function HashcashMiddleware (req, res, next) {
    var cash = req.headers['X-Hashcash'];
    if (!cash) return res.error('Not enough hashcash.  Please try again.');

    var valid = isValid(cash);
    if (!valid) return res.error('Insufficient difficulty.  Please try again.');

    return next();

  };
}<commit_msg>Check bits in middleware<commit_after>var crypto = require('sha3');

module.exports = function Hashcash (difficulty) {

  function isValid (input) {
    var parts = input.split(':');
    var claim = parts[1];

    if (claim < difficulty) {
      return false;
    }

    var hash = new crypto.SHA3Hash();
    hash.update(input);
    var digest = hash.digest('hex');
    var match = digest.match(/^(0+)/);
    var bits = (match) ? match[0].length : 0;

    if (bits < difficult) {
      return false;
    }

    return true;
  }

  return function HashcashMiddleware (req, res, next) {
    var cash = req.headers['X-Hashcash'];
    if (!cash) return res.error('Not enough hashcash.  Please try again.');

    var valid = isValid(cash);
    if (!valid) return res.error('Insufficient difficulty.  Please try again.');

    return next();

  };
}<|endoftext|>


<commit_before>define([
    'jquery',
    '/bower_components/chainpad-listmap/chainpad-listmap.js',
    '/bower_components/chainpad-crypto/crypto.js',
    '/common/common-util.js',
    '/common/outer/network-config.js',
    '/customize/credential.js',
    '/bower_components/chainpad/chainpad.dist.js',
    '/common/common-realtime.js',
    '/common/common-constants.js',
    '/common/common-interface.js',
    '/common/common-feedback.js',
    '/common/outer/local-store.js',
    '/customize/messages.js',

    '/bower_components/tweetnacl/nacl-fast.min.js',
    '/bower_components/scrypt-async/scrypt-async.min.js', // better load speed
], function ($, Listmap, Crypto, Util, NetConfig, Cred, ChainPad, Realtime, Constants, UI,
            Feedback, LocalStore, Messages) {
    var Exports = {
        Cred: Cred,
    };

    var Nacl = window.nacl;
    var allocateBytes = function (bytes) {
        var dispense = Cred.dispenser(bytes);

        var opt = {};

        // dispense 18 bytes of entropy for your encryption key
        var encryptionSeed = dispense(18);
        // 16 bytes for a deterministic channel key
        var channelSeed = dispense(16);
        // 32 bytes for a curve key
        var curveSeed = dispense(32);

        var curvePair = Nacl.box.keyPair.fromSecretKey(new Uint8Array(curveSeed));
        opt.curvePrivate = Nacl.util.encodeBase64(curvePair.secretKey);
        opt.curvePublic = Nacl.util.encodeBase64(curvePair.publicKey);

        // 32 more for a signing key
        var edSeed = opt.edSeed = dispense(32);

        // derive a private key from the ed seed
        var signingKeypair = Nacl.sign.keyPair.fromSeed(new Uint8Array(edSeed));

        opt.edPrivate = Nacl.util.encodeBase64(signingKeypair.secretKey);
        opt.edPublic = Nacl.util.encodeBase64(signingKeypair.publicKey);

        var keys = opt.keys = Crypto.createEditCryptor(null, encryptionSeed);

        // 24 bytes of base64
        keys.editKeyStr = keys.editKeyStr.replace(/\//g, '-');

        // 32 bytes of hex
        var channelHex = opt.channelHex = Util.uint8ArrayToHex(channelSeed);

        // should never happen
        if (channelHex.length !== 32) { throw new Error('invalid channel id'); }

        opt.channel64 = Util.hexToBase64(channelHex);

        opt.userHash = '/1/edit/' + [opt.channel64, opt.keys.editKeyStr].join('/');

        return opt;
    };

    var loadUserObject = function (opt, cb) {
        var config = {
            websocketURL: NetConfig.getWebsocketURL(),
            channel: opt.channelHex,
            data: {},
            validateKey: opt.keys.validateKey, // derived validation key
            crypto: Crypto.createEncryptor(opt.keys),
            logLevel: 1,
            classic: true,
            ChainPad: ChainPad,
            owners: [opt.edPublic]
        };

        var rt = opt.rt = Listmap.create(config);
        rt.proxy
        .on('ready', function () {
            setTimeout(function () { cb(void 0, rt); });
        })
        .on('disconnect', function (info) {
            cb('E_DISCONNECT', info);
        });
    };

    var isProxyEmpty = function (proxy) {
        return Object.keys(proxy).length === 0;
    };

    Exports.loginOrRegister = function (uname, passwd, isRegister, shouldImport, cb) {
        if (typeof(cb) !== 'function') { return; }

        // Usernames are all lowercase. No going back on this one
        uname = uname.toLowerCase();

        // validate inputs
        if (!Cred.isValidUsername(uname)) { return void cb('INVAL_USER'); }
        if (!Cred.isValidPassword(passwd)) { return void cb('INVAL_PASS'); }
        if (isRegister && !Cred.isLongEnoughPassword(passwd)) {
            return void cb('PASS_TOO_SHORT');
        }

        Cred.deriveFromPassphrase(uname, passwd, 192, function (bytes) {
            // results...
            var res = {
                register: isRegister,
            };

            // run scrypt to derive the user's keys
            var opt = res.opt = allocateBytes(bytes);

            // use the derived key to generate an object
            loadUserObject(opt, function (err, rt) {
                if (err) { return void cb(err); }

                res.proxy = rt.proxy;
                res.realtime = rt.realtime;
                res.network = rt.network;

                // they're registering...
                res.userHash = opt.userHash;
                res.userName = uname;

                // export their signing key
                res.edPrivate = opt.edPrivate;
                res.edPublic = opt.edPublic;

                res.curvePrivate = opt.curvePrivate;
                res.curvePublic = opt.curvePublic;

                // they tried to just log in but there's no such user
                if (!isRegister && isProxyEmpty(rt.proxy)) {
                    rt.network.disconnect(); // clean up after yourself
                    return void cb('NO_SUCH_USER', res);
                }

                // they tried to register, but those exact credentials exist
                if (isRegister && !isProxyEmpty(rt.proxy)) {
                    rt.network.disconnect();
                    return void cb('ALREADY_REGISTERED', res);
                }

                if (isRegister) {
                    var proxy = rt.proxy;
                    proxy.edPublic = res.edPublic;
                    proxy.edPrivate = res.edPrivate;
                    proxy.curvePublic = res.curvePublic;
                    proxy.curvePrivate = res.curvePrivate;
                    proxy.login_name = uname;
                    proxy[Constants.displayNameKey] = uname;
                    sessionStorage.createReadme = 1;
                    if (!shouldImport) { proxy.version = 6; }
                    Feedback.send('REGISTRATION', true);
                } else {
                    Feedback.send('LOGIN', true);
                }

                if (shouldImport) {
                    sessionStorage.migrateAnonDrive = 1;
                }

                // We have to call whenRealtimeSyncs asynchronously here because in the current
                // version of listmap, onLocal calls `chainpad.contentUpdate(newValue)`
                // asynchronously.
                // The following setTimeout is here to make sure whenRealtimeSyncs is called after
                // `contentUpdate` so that we have an update userDoc in chainpad.
                setTimeout(function () {
                    Realtime.whenRealtimeSyncs(rt.realtime, function () {
                        LocalStore.login(res.userHash, res.userName, function () {
                            setTimeout(function () { cb(void 0, res); });
                        });
                    });
                });
            });
        });
    };
    Exports.redirect = function () {
        if (sessionStorage.redirectTo) {
            var h = sessionStorage.redirectTo;
            var parser = document.createElement('a');
            parser.href = h;
            if (parser.origin === window.location.origin) {
                delete sessionStorage.redirectTo;
                window.location.href = h;
                return;
            }
        }
        window.location.href = '/drive/';
    };

    var hashing;
    Exports.loginOrRegisterUI = function (uname, passwd, isRegister, shouldImport, testing, test) {
        if (hashing) { return void console.log("hashing is already in progress"); }
        hashing = true;

        var proceed = function (result) {
            hashing = false;
            if (test && typeof test === "function" && test()) { return; }
            Realtime.whenRealtimeSyncs(result.realtime, function () {
                Exports.redirect();
            });
        };

        // setTimeout 100ms to remove the keyboard on mobile devices before the loading screen
        // pops up
        window.setTimeout(function () {
            UI.addLoadingScreen({
                loadingText: Messages.login_hashing,
                hideTips: true,
            });

            // We need a setTimeout(cb, 0) otherwise the loading screen is only displayed
            // after hashing the password
            window.setTimeout(function () {
                Exports.loginOrRegister(uname, passwd, isRegister, shouldImport, function (err, result) {
                    var proxy;
                    if (result) { proxy = result.proxy; }

                    if (err) {
                        switch (err) {
                            case 'NO_SUCH_USER':
                                UI.removeLoadingScreen(function () {
                                    UI.alert(Messages.login_noSuchUser, function () {
                                        hashing = false;
                                    });
                                });
                                break;
                            case 'INVAL_USER':
                                UI.removeLoadingScreen(function () {
                                    UI.alert(Messages.login_invalUser, function () {
                                        hashing = false;
                                    });
                                });
                                break;
                            case 'INVAL_PASS':
                                UI.removeLoadingScreen(function () {
                                    UI.alert(Messages.login_invalPass, function () {
                                        hashing = false;
                                    });
                                });
                                break;
                            case 'PASS_TOO_SHORT':
                                UI.removeLoadingScreen(function () {
                                    var warning = Messages._getKey('register_passwordTooShort', [
                                        Cred.MINIMUM_PASSWORD_LENGTH
                                    ]);
                                    UI.alert(warning, function () {
                                        hashing = false;
                                    });
                                });
                                break;
                            case 'ALREADY_REGISTERED':
                                // logMeIn should reset registering = false
                                UI.removeLoadingScreen(function () {
                                    UI.confirm(Messages.register_alreadyRegistered, function (yes) {
                                        if (!yes) {
                                            hashing = false;
                                            return;
                                        }
                                        proxy.login_name = uname;

                                        if (!proxy[Constants.displayNameKey]) {
                                            proxy[Constants.displayNameKey] = uname;
                                        }
                                        LocalStore.eraseTempSessionValues();
                                        proceed(result);
                                    });
                                });
                                break;
                            default: // UNHANDLED ERROR
                                hashing = false;
                                UI.errorLoadingScreen(Messages.login_unhandledError);
                        }
                        return;
                    }

                    if (testing) { return void proceed(result); }

                    proceed(result);
                });
            }, 500);
        }, 200);
    };

    return Exports;
});
<commit_msg>use nthen to sequence async events<commit_after>define([
    'jquery',
    '/bower_components/chainpad-listmap/chainpad-listmap.js',
    '/bower_components/chainpad-crypto/crypto.js',
    '/common/common-util.js',
    '/common/outer/network-config.js',
    '/customize/credential.js',
    '/bower_components/chainpad/chainpad.dist.js',
    '/common/common-realtime.js',
    '/common/common-constants.js',
    '/common/common-interface.js',
    '/common/common-feedback.js',
    '/common/outer/local-store.js',
    '/customize/messages.js',
    '/bower_components/nthen/index.js',

    '/bower_components/tweetnacl/nacl-fast.min.js',
    '/bower_components/scrypt-async/scrypt-async.min.js', // better load speed
], function ($, Listmap, Crypto, Util, NetConfig, Cred, ChainPad, Realtime, Constants, UI,
            Feedback, LocalStore, Messages, nThen) {
    var Exports = {
        Cred: Cred,
    };

    var Nacl = window.nacl;
    var allocateBytes = function (bytes) {
        var dispense = Cred.dispenser(bytes);

        var opt = {};

        // dispense 18 bytes of entropy for your encryption key
        var encryptionSeed = dispense(18);
        // 16 bytes for a deterministic channel key
        var channelSeed = dispense(16);
        // 32 bytes for a curve key
        var curveSeed = dispense(32);

        var curvePair = Nacl.box.keyPair.fromSecretKey(new Uint8Array(curveSeed));
        opt.curvePrivate = Nacl.util.encodeBase64(curvePair.secretKey);
        opt.curvePublic = Nacl.util.encodeBase64(curvePair.publicKey);

        // 32 more for a signing key
        var edSeed = opt.edSeed = dispense(32);

        // derive a private key from the ed seed
        var signingKeypair = Nacl.sign.keyPair.fromSeed(new Uint8Array(edSeed));

        opt.edPrivate = Nacl.util.encodeBase64(signingKeypair.secretKey);
        opt.edPublic = Nacl.util.encodeBase64(signingKeypair.publicKey);

        var keys = opt.keys = Crypto.createEditCryptor(null, encryptionSeed);

        // 24 bytes of base64
        keys.editKeyStr = keys.editKeyStr.replace(/\//g, '-');

        // 32 bytes of hex
        var channelHex = opt.channelHex = Util.uint8ArrayToHex(channelSeed);

        // should never happen
        if (channelHex.length !== 32) { throw new Error('invalid channel id'); }

        opt.channel64 = Util.hexToBase64(channelHex);

        opt.userHash = '/1/edit/' + [opt.channel64, opt.keys.editKeyStr].join('/');

        return opt;
    };

    var loadUserObject = function (opt, cb) {
        var config = {
            websocketURL: NetConfig.getWebsocketURL(),
            channel: opt.channelHex,
            data: {},
            validateKey: opt.keys.validateKey, // derived validation key
            crypto: Crypto.createEncryptor(opt.keys),
            logLevel: 1,
            classic: true,
            ChainPad: ChainPad,
            owners: [opt.edPublic]
        };

        var rt = opt.rt = Listmap.create(config);
        rt.proxy
        .on('ready', function () {
            setTimeout(function () { cb(void 0, rt); });
        })
        .on('disconnect', function (info) {
            cb('E_DISCONNECT', info);
        });
    };

    var isProxyEmpty = function (proxy) {
        return Object.keys(proxy).length === 0;
    };

    Exports.loginOrRegister = function (uname, passwd, isRegister, shouldImport, cb) {
        if (typeof(cb) !== 'function') { return; }

        // Usernames are all lowercase. No going back on this one
        uname = uname.toLowerCase();

        // validate inputs
        if (!Cred.isValidUsername(uname)) { return void cb('INVAL_USER'); }
        if (!Cred.isValidPassword(passwd)) { return void cb('INVAL_PASS'); }
        if (isRegister && !Cred.isLongEnoughPassword(passwd)) {
            return void cb('PASS_TOO_SHORT');
        }

        // results...
        var res = {
            register: isRegister,
        };

        var RT;

        nThen(function (waitFor) {
            Cred.deriveFromPassphrase(uname, passwd, 192, waitFor(function (bytes) {
                // run scrypt to derive the user's keys
                res.opt = allocateBytes(bytes);
            }));
        }).nThen(function (waitFor) {
            var opt = res.opt;
            // use the derived key to generate an object
            loadUserObject(opt, waitFor(function (err, rt) {
                if (err) { return void cb(err); }
                RT = rt;

                res.proxy = rt.proxy;
                res.realtime = rt.realtime;
                res.network = rt.network;

                // they're registering...
                res.userHash = opt.userHash;
                res.userName = uname;

                // export their signing key
                res.edPrivate = opt.edPrivate;
                res.edPublic = opt.edPublic;

                res.curvePrivate = opt.curvePrivate;
                res.curvePublic = opt.curvePublic;

                // they tried to just log in but there's no such user
                if (!isRegister && isProxyEmpty(rt.proxy)) {
                    rt.network.disconnect(); // clean up after yourself
                    waitFor.abort();
                    return void cb('NO_SUCH_USER', res);
                }

                // they tried to register, but those exact credentials exist
                if (isRegister && !isProxyEmpty(rt.proxy)) {
                    rt.network.disconnect();
                    waitFor.abort();
                    return void cb('ALREADY_REGISTERED', res);
                }

                if (isRegister) {
                    var proxy = rt.proxy;
                    proxy.edPublic = res.edPublic;
                    proxy.edPrivate = res.edPrivate;
                    proxy.curvePublic = res.curvePublic;
                    proxy.curvePrivate = res.curvePrivate;
                    proxy.login_name = uname;
                    proxy[Constants.displayNameKey] = uname;
                    sessionStorage.createReadme = 1;
                    if (!shouldImport) { proxy.version = 6; }
                    Feedback.send('REGISTRATION', true);
                } else {
                    Feedback.send('LOGIN', true);
                }

                if (shouldImport) {
                    sessionStorage.migrateAnonDrive = 1;
                }
            }));
        }).nThen(function () {
            // We have to call whenRealtimeSyncs asynchronously here because in the current
            // version of listmap, onLocal calls `chainpad.contentUpdate(newValue)`
            // asynchronously.
            // The following setTimeout is here to make sure whenRealtimeSyncs is called after
            // `contentUpdate` so that we have an update userDoc in chainpad.
            setTimeout(function () {
                Realtime.whenRealtimeSyncs(RT.realtime, function () {
                    LocalStore.login(res.userHash, res.userName, function () {
                        setTimeout(function () { cb(void 0, res); });
                    });
                });
            });
        });
    };
    Exports.redirect = function () {
        if (sessionStorage.redirectTo) {
            var h = sessionStorage.redirectTo;
            var parser = document.createElement('a');
            parser.href = h;
            if (parser.origin === window.location.origin) {
                delete sessionStorage.redirectTo;
                window.location.href = h;
                return;
            }
        }
        window.location.href = '/drive/';
    };

    var hashing;
    Exports.loginOrRegisterUI = function (uname, passwd, isRegister, shouldImport, testing, test) {
        if (hashing) { return void console.log("hashing is already in progress"); }
        hashing = true;

        var proceed = function (result) {
            hashing = false;
            if (test && typeof test === "function" && test()) { return; }
            Realtime.whenRealtimeSyncs(result.realtime, function () {
                Exports.redirect();
            });
        };

        // setTimeout 100ms to remove the keyboard on mobile devices before the loading screen
        // pops up
        window.setTimeout(function () {
            UI.addLoadingScreen({
                loadingText: Messages.login_hashing,
                hideTips: true,
            });

            // We need a setTimeout(cb, 0) otherwise the loading screen is only displayed
            // after hashing the password
            window.setTimeout(function () {
                Exports.loginOrRegister(uname, passwd, isRegister, shouldImport, function (err, result) {
                    var proxy;
                    if (result) { proxy = result.proxy; }

                    if (err) {
                        switch (err) {
                            case 'NO_SUCH_USER':
                                UI.removeLoadingScreen(function () {
                                    UI.alert(Messages.login_noSuchUser, function () {
                                        hashing = false;
                                    });
                                });
                                break;
                            case 'INVAL_USER':
                                UI.removeLoadingScreen(function () {
                                    UI.alert(Messages.login_invalUser, function () {
                                        hashing = false;
                                    });
                                });
                                break;
                            case 'INVAL_PASS':
                                UI.removeLoadingScreen(function () {
                                    UI.alert(Messages.login_invalPass, function () {
                                        hashing = false;
                                    });
                                });
                                break;
                            case 'PASS_TOO_SHORT':
                                UI.removeLoadingScreen(function () {
                                    var warning = Messages._getKey('register_passwordTooShort', [
                                        Cred.MINIMUM_PASSWORD_LENGTH
                                    ]);
                                    UI.alert(warning, function () {
                                        hashing = false;
                                    });
                                });
                                break;
                            case 'ALREADY_REGISTERED':
                                // logMeIn should reset registering = false
                                UI.removeLoadingScreen(function () {
                                    UI.confirm(Messages.register_alreadyRegistered, function (yes) {
                                        if (!yes) {
                                            hashing = false;
                                            return;
                                        }
                                        proxy.login_name = uname;

                                        if (!proxy[Constants.displayNameKey]) {
                                            proxy[Constants.displayNameKey] = uname;
                                        }
                                        LocalStore.eraseTempSessionValues();
                                        proceed(result);
                                    });
                                });
                                break;
                            default: // UNHANDLED ERROR
                                hashing = false;
                                UI.errorLoadingScreen(Messages.login_unhandledError);
                        }
                        return;
                    }

                    if (testing) { return void proceed(result); }

                    proceed(result);
                });
            }, 500);
        }, 200);
    };

    return Exports;
});
<|endoftext|>


<commit_before>import React from 'react';
import {
  StyleSheet,
  View,
  TextInput,
  Item,
  Text,
  Switch,
  Picker } from 'react-native';

const styles = StyleSheet.create({
  containerSolve: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingTop: 7,
  },
  textInput: {
    height: 45,
    marginTop: 10,
  },
  picker: {
    flex: 1,
    justifyContent: 'flex-start',
  },
});

const MissionModalInput = React.createClass({

  getInitialState() {
    return {
      unableToSolve: this.props.unableToSolve,
      txtUnableToSolve: 'Unable to solve',
      inputType: this.props.inputType,
      selected: 'key0',
      answer: ' ',
    };
  },

  /*
  * Picker
  */
  onValueChange(key, value) {
    const newState = {};
    newState[key] = value;
    this.setState(newState);
  },

  render() {
    let inputField;

    if (this.state.unableToSolve) {
      inputField = (
        <View>
        </View>
      );
    } else {
      switch (this.state.inputType) {
        case 'select':
          inputField = (
            <Picker
              style = { styles.picker }
              selectedValue = { this.state.selected }
              onValueChange = { this.onValueChange.bind(this, 'selected') }
            >
              <Item label = 'hello' value = 'key0' />
              <Item label = 'world' value = 'key1' />
            </Picker>
          );
          break;
        case 'input':
          inputField = (
            <TextInput
              style = { styles.textInput }
              autoCapitalize = 'words'
              placeholder = 'Mission type'
              onChangeText = { (answer) => this.setState({ answer }) }
              value = { this.state.answer }
            />
          );
          break;
        default:
          inputField = (
            <View>
            </View>
          );
          return;
      }
    }

    return (
      <View>
        <View style = { styles.containerSolve }>
          <Text style = { styles.text }>{ this.state.txtUnableToSolve }</Text>
          <Switch
            onValueChange = { (value) => this.setState({ unableToSolve: value }) }
            value = { this.state.unableToSolve }
          />
        </View>
        <View>
          { inputField }
        </View>
      </View>
    );
  }
});

module.exports = MissionModalInput;
<commit_msg>fixed switch-case default case<commit_after>import React from 'react';
import {
  StyleSheet,
  View,
  TextInput,
  Item,
  Text,
  Switch,
  Picker } from 'react-native';

const styles = StyleSheet.create({
  containerSolve: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingTop: 7,
  },
  textInput: {
    height: 45,
    marginTop: 10,
  },
  picker: {
    flex: 1,
    justifyContent: 'flex-start',
  },
});

const MissionModalInput = React.createClass({

  getInitialState() {
    return {
      unableToSolve: this.props.unableToSolve,
      txtUnableToSolve: 'Unable to solve',
      inputType: this.props.inputType,
      selected: 'key0',
      answer: ' ',
    };
  },

  /*
  * Picker
  */
  onValueChange(key, value) {
    const newState = {};
    newState[key] = value;
    this.setState(newState);
  },

  render() {
    let inputField;

    if (this.state.unableToSolve) {
      inputField = (
        <View>
        </View>
      );
    } else {
      switch (this.state.inputType) {
        case 'select':
          inputField = (
            <Picker
              style = { styles.picker }
              selectedValue = { this.state.selected }
              onValueChange = { this.onValueChange.bind(this, 'selected') }
            >
              <Item label = 'hello' value = 'key0' />
              <Item label = 'world' value = 'key1' />
            </Picker>
          );
          break;
        case 'input':
          inputField = (
            <TextInput
              style = { styles.textInput }
              autoCapitalize = 'words'
              placeholder = 'Mission type'
              onChangeText = { (answer) => this.setState({ answer }) }
              value = { this.state.answer }
            />
          );
          break;
        default:
          inputField = (
            <View>
            </View>
          );
          break;
      }
    }

    return (
      <View>
        <View style = { styles.containerSolve }>
          <Text style = { styles.text }>{ this.state.txtUnableToSolve }</Text>
          <Switch
            onValueChange = { (value) => this.setState({ unableToSolve: value }) }
            value = { this.state.unableToSolve }
          />
        </View>
        <View>
          { inputField }
        </View>
      </View>
    );
  }
});

module.exports = MissionModalInput;
<|endoftext|>