<commit_before>'use strict';

// ///***CLAIRE'S CODE***CLAIRE'S CODE***CLAIRE'S CODE***CLAIRE'S CODE***CLAIRE'S CODE
// function PlayerInfo(name) {
//   this.playerName = name;
//   this.gamesWon = 0;
//   this.gamesPlayed = 0;
//   this.percentWon = 0;
//   this.totalPoints = 0;
// };
// Top player stats to display: ranking, player name, total points, and show top 5 players in list in order of total points.
// function calculateTotalPoints() {
//   var total = (this.gamesWon * 5);
//   this.totalPoints = total;
// }
// function toHtml () {
//   this.calculatePercentWon();
//   var elMain = document.getElementById('player-stats');
//
//   var elSection = document.createElement('section');
//   elMain.appendChild(elSection);
//
//   var elH2 = document.createElement('h2');
//   elH2.textContent = this.playerName;
//   elSection.appendChild(elH2);
//
//   var elOl = document.createElement('ol');
//   elSection.appendChild(elOl);
//
//   var elLi = document.createElement('li');
//   elLi.textContent = this.percentWon;
//   elOl.appendChild(elLi);
//
//   elLi = document.createElement('li');
//   elLi.textContent = this.totalPoints;
//   elOl.appendChild(elLi);
// }
// var canvas = document.getElementById('stage'),
//   c = canvas.getContext('2d');
//
// function drawLine(context , from, to) {
//   context.beingPath();
//   context.moveTo(from[0], from[1]);
//   context.lineTo(to[0], to[1]);
//   context.stroke();
//   drawLine(c, [0,0], [100,50]);
// }
// //Draw the canvas function drawCanvas()
// var c = canvas.getContext('2d');
// //reset the canvas and set the basic styles
// canvas.width = canvas.width;
// c.lineWidth = 10;
// c.strokeStyle = 'green';
// c.font = 'bold 24px Optimer, Arial, Helvetica, sans-serif';
// c.fillStyle = 'red';
// //draw the ground
// drawLine(c, [20,190], [180,190]);
// //start building the gallows if there's been a bad guess
// //if (badGuesses > 0) {
//   //create the upright
//   c.strokeStyle = '#A52A2A';
//   drawLine(c, [30,185], [30,10]);
//   //if (badGuesses > 1) {
//     //create the arm gallows
//     c.lineTo(150,10);
//     c.stroke();
//   //}
//   //if (badGuesses > 2) {
//     c.strokeStyle = 'black';
//     c.lineWidth = 3;
//     //draw rope
//     drawLine(c, [145,15], [145,30]);
//     //draw head
//     c.beginPath();
//     c.moveTo(160, 45);
//     c.arc(145, 45, 15, 0, (Math.PI/180)*360);
//     c.stroke();
//     //}
//   //if (badGuesses > 3) {
//     //draw body
//     drawLine(c, [145,60], [145,130]);
//   //}
//   //if (badGuesses > 4) {
//     //draw left arm
//     drawLine(c, [145,80], [110,90]);
//   //}
//   //if (badGuesses > 5) {
//     //draw right arm
//     drawLine(c, [145,80], [180,90]);
//   //}
//   //if  (badGuesses > 6) {
//     //draw left leg
//     drawLine(c, [145,130], [130,170]);
//   //}
//   //if (badGuesses > 7) {
//     //draw right leg and end game
//     drawLine(c, [145,130], [160,170]);
// //I wrote the functions to calculate the percent won and the total points. I made an ordered list with an h2 header that states the player name. The first list item is the percent won and the second list item is the total points.
// var playerForm = document.getElementById('form');
// //var welcomeMessage = document.getElementById('welcome_message');
// //***CLAIRE'S CODE***CLAIRE'S CODE***CLAIRE'S CODE***CLAIRE'S CODE***CLAIRE'S CODE***CLAIRE'S CODE

// Global variables
var playerAnswerArr = []; // blank spaces puzzle
var incorrectGuesses = 0;
var maxEasyGuesses = 5; // will correspond with number of easy difficulty body parts
var easyWords = ['four', 'phone', 'mouse', 'bottle', 'notebook']; // subject to change
var gameWord; // word chosen from word array
var remainingLetters; // remaining letters left to guess in the gameWord
var wonGame = false; // used in checkForWin/Loss and updatePlayerStats
var letterButton = document.getElementById('letter_buttons');
letterButton.addEventListener('click', handleClick); // listens for a button click
var display = document.getElementById('display_player_array');
var playAgainButton = document.getElementById('play_again_btn');
playAgainButton.addEventListener('click', handlePlayAgain);
var endMessage = document.getElementById('end_of_game_msg');

// - generate a hanging man
// _______ADDRESS______________________

// FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS //
// handles the event of a button click
function handlePlayAgain(event) {
  // reloads the page and starts it at the top
  window.location.reload();
  window.onbeforeunload = function () {
    window.scrollTo(0, 0);
  };
}

function handleClick(event) {
  event.preventDefault(); // prevent page refresh

  // determine if the event.target.value is in the gameWord array
  if (gameWord.includes(event.target.value) === true) {
    // loop through the gameWord to match target value (letter) with any same letter in the gameword
    for (var i = 0; i < gameWord.length; i++) {
      if (event.target.value === gameWord[i]) {

        playerAnswerArr[i] = gameWord[i]; // replace the blank index with the matching letter

        displayPlayerArray(playerAnswerArr); // update the display for the player
        remainingLetters--;
        // disable the button to prevent the player from selecting it again
        event.target.disabled = true;
        checkForWin();
      }
    }
  } else if (gameWord.includes(event.target.value) === false) {
    // if user selects a invalid letter, nothing changes in the playerAnswerArr
    displayPlayerArray(playerAnswerArr);

    //       - one body part gets added to the hangman

    incorrectGuesses += 1; // incorrectGuesses increases by 1
    // disable the button to prevent the player from selecting it again
    event.target.disabled = true;
    checkForLoss();
  }
}

function checkForWin() {
  if (remainingLetters === 0) { // if the player has guessed all the letters
    wonGame = true;
    // disable the buttons, display the solved gameWord, inform the player that they won, and updatePlayerStats
    letterButton.removeEventListener('click', handleClick);
    displayPlayerArray(playerAnswerArr);
    endMessage.textContent = 'Congrats! You won and saved the hangman!';
    updatePlayerStats();
    //   - refresh page?
  }
}

function checkForLoss() {
  if (remainingLetters > 0 && incorrectGuesses === maxEasyGuesses) {
    wonGame = false;
    //   - hangman will have all parts
    //   - display correct letters in the puzzle as the answer

    // disable the buttons, inform the player that they lost, and updatePlayerStats
    letterButton.removeEventListener('click', handleClick);
    endMessage.textContent = 'You failed to guess \'' + gameWord + '.\' A man has been hanged today. You lose.';
    updatePlayerStats();
    //   - refresh page?
  }
}

function updatePlayerStats() {
  var localStorageNameArr;
  var localStorageObjArr;
  var parsedLclStrgNameArr;
  var parsedlclStrgObjArr;
  // get the name array from local storage and parse from JSON to js
  localStorageNameArr = localStorage.getItem('allPlayerNames');
  parsedLclStrgNameArr = JSON.parse(localStorageNameArr);
  // pop off the last element (the current logged in user) and store it on a variable
  var playerToCheck = parsedLclStrgNameArr.pop();
  // get the player object array from local storage and parse from JSON to js
  localStorageObjArr = localStorage.getItem('players');
  parsedlclStrgObjArr = JSON.parse(localStorageObjArr);
  // compare the playerToCheck to the player names in the object array
  for (var i = 0; i < parsedlclStrgObjArr.length; i++) {
    // if there's a name match, update other object properties
    if (playerToCheck === parsedlclStrgObjArr[i].playerName) {
      parsedlclStrgObjArr[i].gamesPlayed ++;
      if (wonGame === true) {
        parsedlclStrgObjArr[i].totalPoints += 23; ////////THIS WILL PROBABLY CHANGE///////////////
        parsedlclStrgObjArr[i].gamesWon ++;
      }
      var numberWon = Math.round((parsedlclStrgObjArr[i].gamesWon / parsedlclStrgObjArr[i].gamesPlayed) * 100);
      parsedlclStrgObjArr[i].percentWon = numberWon;
      parsedlclStrgObjArr[i].percentDisplay = numberWon + '%';
    }
  }
  // stringify the updated array and set it back to local storage
  var playersJSON = JSON.stringify(parsedlclStrgObjArr);
  localStorage.setItem('players', playersJSON);
}

// pass in a word array to select a random word from it to assign to gameWord
function pickWord (wordArr) {
  gameWord = wordArr[generateRandomNumber(wordArr)];
  return gameWord;

  function generateRandomNumber(arr) {
    return Math.floor(Math.random() * arr.length);
  }
}

// initiate the playerAnswerArr to '_' characters, the length of the gameWord
function generatePlayerAnswerArray (gameWord) {
  for (var i = 0; i < gameWord.length; i++) {
    playerAnswerArr.push('_');
  };
}

// display the playerAnswerArr in html
function displayPlayerArray(playerAnswerArr) {
  display.textContent = playerAnswerArr.join(' ');
}

function runGame(){
  playerAnswerArr = [];
  // letterButton.addEventListener('click', handleClick); // listens for a button click
  // letterButton.disabled = false;
  // assign the gameWord
  gameWord = pickWord(easyWords);
  // set the remainingLetters left to guess
  remainingLetters = gameWord.length;
  // generate a playerAnswerArr blank puzzle that is the length of the gameWord and display it
  generatePlayerAnswerArray(gameWord);
  displayPlayerArray(playerAnswerArr);
}

//*****EXECUTE CODE*******************EXECUTE CODE**********************
runGame();
<commit_msg>added comments<commit_after>'use strict';

// ///***CLAIRE'S CODE***CLAIRE'S CODE***CLAIRE'S CODE***CLAIRE'S CODE***CLAIRE'S CODE
// function PlayerInfo(name) {
//   this.playerName = name;
//   this.gamesWon = 0;
//   this.gamesPlayed = 0;
//   this.percentWon = 0;
//   this.totalPoints = 0;
// };
// Top player stats to display: ranking, player name, total points, and show top 5 players in list in order of total points.
// function calculateTotalPoints() {
//   var total = (this.gamesWon * 5);
//   this.totalPoints = total;
// }
// function toHtml () {
//   this.calculatePercentWon();
//   var elMain = document.getElementById('player-stats');
//
//   var elSection = document.createElement('section');
//   elMain.appendChild(elSection);
//
//   var elH2 = document.createElement('h2');
//   elH2.textContent = this.playerName;
//   elSection.appendChild(elH2);
//
//   var elOl = document.createElement('ol');
//   elSection.appendChild(elOl);
//
//   var elLi = document.createElement('li');
//   elLi.textContent = this.percentWon;
//   elOl.appendChild(elLi);
//
//   elLi = document.createElement('li');
//   elLi.textContent = this.totalPoints;
//   elOl.appendChild(elLi);
// }
// var canvas = document.getElementById('stage'),
//   c = canvas.getContext('2d');
//
// function drawLine(context , from, to) {
//   context.beingPath();
//   context.moveTo(from[0], from[1]);
//   context.lineTo(to[0], to[1]);
//   context.stroke();
//   drawLine(c, [0,0], [100,50]);
// }
// //Draw the canvas function drawCanvas()
// var c = canvas.getContext('2d');
// //reset the canvas and set the basic styles
// canvas.width = canvas.width;
// c.lineWidth = 10;
// c.strokeStyle = 'green';
// c.font = 'bold 24px Optimer, Arial, Helvetica, sans-serif';
// c.fillStyle = 'red';
// //draw the ground
// drawLine(c, [20,190], [180,190]);
// //start building the gallows if there's been a bad guess
// //if (badGuesses > 0) {
//   //create the upright
//   c.strokeStyle = '#A52A2A';
//   drawLine(c, [30,185], [30,10]);
//   //if (badGuesses > 1) {
//     //create the arm gallows
//     c.lineTo(150,10);
//     c.stroke();
//   //}
//   //if (badGuesses > 2) {
//     c.strokeStyle = 'black';
//     c.lineWidth = 3;
//     //draw rope
//     drawLine(c, [145,15], [145,30]);
//     //draw head
//     c.beginPath();
//     c.moveTo(160, 45);
//     c.arc(145, 45, 15, 0, (Math.PI/180)*360);
//     c.stroke();
//     //}
//   //if (badGuesses > 3) {
//     //draw body
//     drawLine(c, [145,60], [145,130]);
//   //}
//   //if (badGuesses > 4) {
//     //draw left arm
//     drawLine(c, [145,80], [110,90]);
//   //}
//   //if (badGuesses > 5) {
//     //draw right arm
//     drawLine(c, [145,80], [180,90]);
//   //}
//   //if  (badGuesses > 6) {
//     //draw left leg
//     drawLine(c, [145,130], [130,170]);
//   //}
//   //if (badGuesses > 7) {
//     //draw right leg and end game
//     drawLine(c, [145,130], [160,170]);
// //I wrote the functions to calculate the percent won and the total points. I made an ordered list with an h2 header that states the player name. The first list item is the percent won and the second list item is the total points.
// var playerForm = document.getElementById('form');
// //var welcomeMessage = document.getElementById('welcome_message');
// //***CLAIRE'S CODE***CLAIRE'S CODE***CLAIRE'S CODE***CLAIRE'S CODE***CLAIRE'S CODE***CLAIRE'S CODE

// Global variables
var playerAnswerArr = []; // blank spaces puzzle
var incorrectGuesses = 0;
var maxEasyGuesses = 5; // will correspond with number of easy difficulty body parts
var easyWords = ['four', 'phone', 'mouse', 'bottle', 'notebook']; // subject to change
var gameWord; // word chosen from word array
var remainingLetters; // remaining letters left to guess in the gameWord
var wonGame = false; // used in checkForWin/Loss and updatePlayerStats
var letterButton = document.getElementById('letter_buttons');
letterButton.addEventListener('click', handleClick); // listens for a button click
var display = document.getElementById('display_player_array');
var playAgainButton = document.getElementById('play_again_btn');
playAgainButton.addEventListener('click', handlePlayAgain);
var endMessage = document.getElementById('end_of_game_msg');

// - generate a hanging man
// _______ADDRESS______________________

// FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS //
// handles the event when 'play again' button is clicked
function handlePlayAgain(event) {
  // reloads the page and starts it at the top
  window.location.reload();
  window.onbeforeunload = function () {
    window.scrollTo(0, 0);
  };
}

// handles the event of a letter button click
function handleClick(event) {
  event.preventDefault(); // prevent page refresh

  // determine if the event.target.value is in the gameWord array
  if (gameWord.includes(event.target.value) === true) {
    // loop through the gameWord to match target value (letter) with any same letter in the gameword
    for (var i = 0; i < gameWord.length; i++) {
      if (event.target.value === gameWord[i]) {

        playerAnswerArr[i] = gameWord[i]; // replace the blank index with the matching letter

        displayPlayerArray(playerAnswerArr); // update the display for the player
        remainingLetters--;
        // disable the button to prevent the player from selecting it again
        event.target.disabled = true;
        checkForWin();
      }
    }
  } else if (gameWord.includes(event.target.value) === false) {
    // if user selects a invalid letter, nothing changes in the playerAnswerArr
    displayPlayerArray(playerAnswerArr);

    //       - one body part gets added to the hangman

    incorrectGuesses += 1; // incorrectGuesses increases by 1
    // disable the button to prevent the player from selecting it again
    event.target.disabled = true;
    checkForLoss();
  }
}

function checkForWin() {
  if (remainingLetters === 0) { // if the player has guessed all the letters
    wonGame = true;
    // disable the buttons, display the solved gameWord, inform the player that they won, and updatePlayerStats
    letterButton.removeEventListener('click', handleClick);
    displayPlayerArray(playerAnswerArr);
    endMessage.textContent = 'Congrats! You won and saved the hangman!';
    updatePlayerStats();
    //   - refresh page?
  }
}

function checkForLoss() {
  if (remainingLetters > 0 && incorrectGuesses === maxEasyGuesses) {
    wonGame = false;
    //   - hangman will have all parts
    //   - display correct letters in the puzzle as the answer

    // disable the buttons, inform the player that they lost, and updatePlayerStats
    letterButton.removeEventListener('click', handleClick);
    endMessage.textContent = 'You failed to guess \'' + gameWord + '.\' A man has been hanged today. You lose.';
    updatePlayerStats();
    //   - refresh page?
  }
}

function updatePlayerStats() {
  var localStorageNameArr;
  var localStorageObjArr;
  var parsedLclStrgNameArr;
  var parsedlclStrgObjArr;
  // get the name array from local storage and parse from JSON to js
  localStorageNameArr = localStorage.getItem('allPlayerNames');
  parsedLclStrgNameArr = JSON.parse(localStorageNameArr);
  // pop off the last element (the current logged in user) and store it on a variable
  var playerToCheck = parsedLclStrgNameArr.pop();
  // get the player object array from local storage and parse from JSON to js
  localStorageObjArr = localStorage.getItem('players');
  parsedlclStrgObjArr = JSON.parse(localStorageObjArr);
  // compare the playerToCheck to the player names in the object array
  for (var i = 0; i < parsedlclStrgObjArr.length; i++) {
    // if there's a name match, update other object properties
    if (playerToCheck === parsedlclStrgObjArr[i].playerName) {
      parsedlclStrgObjArr[i].gamesPlayed ++;
      if (wonGame === true) {
        parsedlclStrgObjArr[i].totalPoints += 23; ////////THIS WILL PROBABLY CHANGE///////////////
        parsedlclStrgObjArr[i].gamesWon ++;
      }
      var numberWon = Math.round((parsedlclStrgObjArr[i].gamesWon / parsedlclStrgObjArr[i].gamesPlayed) * 100);
      parsedlclStrgObjArr[i].percentWon = numberWon;
      parsedlclStrgObjArr[i].percentDisplay = numberWon + '%';
    }
  }
  // stringify the updated array and set it back to local storage
  var playersJSON = JSON.stringify(parsedlclStrgObjArr);
  localStorage.setItem('players', playersJSON);
}

// pass in a word array to select a random word from it to assign to gameWord
function pickWord (wordArr) {
  gameWord = wordArr[generateRandomNumber(wordArr)];
  return gameWord;

  function generateRandomNumber(arr) {
    return Math.floor(Math.random() * arr.length);
  }
}

// initiate the playerAnswerArr to '_' characters, the length of the gameWord
function generatePlayerAnswerArray (gameWord) {
  for (var i = 0; i < gameWord.length; i++) {
    playerAnswerArr.push('_');
  };
}

// display the playerAnswerArr in html
function displayPlayerArray(playerAnswerArr) {
  display.textContent = playerAnswerArr.join(' ');
}

function runGame(){
  playerAnswerArr = [];
  // letterButton.addEventListener('click', handleClick); // listens for a button click
  // letterButton.disabled = false;
  // assign the gameWord
  gameWord = pickWord(easyWords);
  // set the remainingLetters left to guess
  remainingLetters = gameWord.length;
  // generate a playerAnswerArr blank puzzle that is the length of the gameWord and display it
  generatePlayerAnswerArray(gameWord);
  displayPlayerArray(playerAnswerArr);
}

//*****EXECUTE CODE*******************EXECUTE CODE**********************
runGame();
<|endoftext|>


<commit_before>'use strict'
// require('dotenv').config();
var express = require('express'),
spdy = require('spdy'),
fs = require('fs'),
https = require('https'),
mongoose = require('mongoose'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
app = express(),
favicon = require('serve-favicon'),
config = require('./config'),
cors = require('cors'),
expressLogger = require('./utils/logger'),
expressValidator = require('express-validator'),
url = require('url'),
path = require('path'),
helmet = require('helmet');

app.use(cors());
app.use(helmet());

app.use(express.static('./app'));
//app.use(favicon('./favicon.ico'));

var uri = config.database;
var promise_options = { promiseLibrary: require('bluebird') };
var db = mongoose.createConnection(uri, promise_options);

mongoose.connect(config.database);

// app.use(logger('dev'));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(expressValidator());
app.use(cookieParser());

//logging middleware
app.use(expressLogger.requestLogger('request'));
app.use(expressLogger.errorLogger());

app.use('/api/issues', require('./routes/issues'));
app.use('/api/postcards', require('./routes/postcards'));
app.use('/api/payments', require('./routes/payments'));
app.use('/api/representatives', require('./routes/representatives'));
app.use('/api/users', require('./routes/users'));

app.get('/api/', function(req, res, next){
	res.send('Hello World!');
});

if (process.env.NODE_ENV !== 'dev') {
  app.use('/',
    express.static(path.resolve(process.cwd(), 'client/build'))
  );
  app.get('*', (req, res) => res.sendFile(path.resolve(outputPath, 'index.html')))
}

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.listen(process.env.PORT || 8080, function () {
  console.log('App listening on port 8080!');
});

module.exports = app;
<commit_msg>outputPath error<commit_after>'use strict'
// require('dotenv').config();
var express = require('express'),
spdy = require('spdy'),
fs = require('fs'),
https = require('https'),
mongoose = require('mongoose'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
app = express(),
favicon = require('serve-favicon'),
config = require('./config'),
cors = require('cors'),
expressLogger = require('./utils/logger'),
expressValidator = require('express-validator'),
url = require('url'),
path = require('path'),
helmet = require('helmet');

app.use(cors());
app.use(helmet());

app.use(express.static('./app'));
//app.use(favicon('./favicon.ico'));

var uri = config.database;
var promise_options = { promiseLibrary: require('bluebird') };
var db = mongoose.createConnection(uri, promise_options);

mongoose.connect(config.database);

// app.use(logger('dev'));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(expressValidator());
app.use(cookieParser());

//logging middleware
app.use(expressLogger.requestLogger('request'));
app.use(expressLogger.errorLogger());

app.use('/api/issues', require('./routes/issues'));
app.use('/api/postcards', require('./routes/postcards'));
app.use('/api/payments', require('./routes/payments'));
app.use('/api/representatives', require('./routes/representatives'));
app.use('/api/users', require('./routes/users'));

app.get('/api/', function(req, res, next){
	res.send('Hello World!');
});

if (process.env.NODE_ENV !== 'dev') {
  app.use('/',
    express.static(path.resolve(process.cwd(), 'client/build'))
  );
  app.get('*', (req, res) => res.sendFile(path.resolve(path.resolve(process.cwd(), 'client/build'), 'index.html')))
}

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.listen(process.env.PORT || 8080, function () {
  console.log('App listening on port 8080!');
});

module.exports = app;
<|endoftext|>


<commit_before>// @flow

import type { ChatMessageInfoItemWithHeight } from './message.react';

import * as React from 'react';
import { View, Text, StyleSheet } from 'react-native';

import { stringForUser } from 'lib/shared/user-utils';

import Timestamp from './timestamp.react';

type Props = {|
  item: ChatMessageInfoItemWithHeight,
  focused: bool,
  color: 'light' | 'dark',
|};
function MessageHeader(props: Props) {
  const { item, focused, color } = props;
  const { creator, time } = item.messageInfo;
  const { isViewer } = creator;

  let authorName = null;
  if (!isViewer && (item.startsCluster || focused)) {
    const style = color === 'light'
      ? [ styles.authorName, styles.light ]
      : [ styles.authorName, styles.dark ];
    authorName = (
      <Text style={style} numberOfLines={1}>
        {stringForUser(creator)}
      </Text>
    );
  }

  const timestamp = focused || item.startsConversation
    ? <Timestamp time={time} color={color} />
    : null;
  if (!timestamp && !authorName) {
    return null;
  }

  const style = !item.startsCluster
    ? styles.clusterMargin
    : null;
  return (
    <View style={style}>
      {timestamp}
      {authorName}
    </View>
  );
}

const styles = StyleSheet.create({
  clusterMargin: {
    marginTop: 7,
  },
  authorName: {
    color: '#777777',
    fontSize: 14,
    marginLeft: 12,
    marginRight: 7,
    paddingHorizontal: 12,
    paddingVertical: 4,
    height: 25,
  },
  dark: {
    color: '#777777',
  },
  light: {
    color: 'white',
  },
});

export default MessageHeader;
<commit_msg>[native] Don't show dark MessageHeader just because focused<commit_after>// @flow

import type { ChatMessageInfoItemWithHeight } from './message.react';

import * as React from 'react';
import { View, Text, StyleSheet } from 'react-native';

import { stringForUser } from 'lib/shared/user-utils';

import Timestamp from './timestamp.react';

type Props = {|
  item: ChatMessageInfoItemWithHeight,
  focused: bool,
  color: 'light' | 'dark',
|};
function MessageHeader(props: Props) {
  const { item, focused, color } = props;
  const { creator, time } = item.messageInfo;
  const { isViewer } = creator;

  let authorName = null;
  if (!isViewer && (item.startsCluster || focused)) {
    const style = color === 'light' || !item.startsCluster
      ? [ styles.authorName, styles.light ]
      : [ styles.authorName, styles.dark ];
    authorName = (
      <Text style={style} numberOfLines={1}>
        {stringForUser(creator)}
      </Text>
    );
  }

  const timestampColor = color === 'light' || !item.startsConversation
    ? 'light'
    : 'dark';
  const timestamp = focused || item.startsConversation
    ? <Timestamp time={time} color={timestampColor} />
    : null;
  if (!timestamp && !authorName) {
    return null;
  }

  const style = !item.startsCluster
    ? styles.clusterMargin
    : null;
  return (
    <View style={style}>
      {timestamp}
      {authorName}
    </View>
  );
}

const styles = StyleSheet.create({
  clusterMargin: {
    marginTop: 7,
  },
  authorName: {
    color: '#777777',
    fontSize: 14,
    marginLeft: 12,
    marginRight: 7,
    paddingHorizontal: 12,
    paddingVertical: 4,
    height: 25,
  },
  dark: {
    color: '#777777',
  },
  light: {
    color: 'white',
  },
});

export default MessageHeader;
<|endoftext|>


<commit_before>/* -*- javascript -*- */
"use strict";

/**
 * UIAttribute -- base class for Semantic UI attributes
 */

import {inject, bindable, LogManager} from 'aurelia-framework';

const UI_ATTRIBUTE_NAME = /UI(\w+)Attribute/;

@inject( Element )
export class UIAttribute {

	constructor( element ) {
		this.logger = LogManager.getLogger( this.constructor.name );
		this.element = element;
	}

	bind() {
		let nameMatch = UI_ATTRIBUTE_NAME.exec( this.constructor.name );

		if ( nameMatch ) {
			let attrName = nameMatch[ 1 ].toLowerCase();
			this.logger.debug( `Adding 'ui ${attrName}' to the classList.` );
			this.element.classList.add( 'ui', attrName );
		} else {
			this.logger.warn( "Attribute class doesn't match the naming convention; ",
				"assuming it's going to manage the classList itself." );
		}
	}

}

export function bindableEnum( ...validValues ) {
	console.debug( "Bindable enum decorator called with: ", validValues );
	return function( target, name, descriptor ) {
		let changedMethodName = `${name}Changed`;
		console.debug( "Setting up a ", changedMethodName, " method on ", target );
		target[ changedMethodName ] = function( newValue, oldValue ) {
			this.logger.debug( `Changing ${name} to ${newValue} from ${oldValue}` );
			this.element.classList.remove( oldValue );
			this.element.classList.add( newValue );
		};

		let originalBind = target.bind;
		target.bind = function( ...args ) {
			Reflect.apply( originalBind, this, args );
			if ( this[name] ) {
				this.element.classList.add( this[name] );
			}
		};

		return bindable( target, name, descriptor );
	};
}

export function bindableToggle( target, name, descriptor ) {
	console.debug( "Bindable toggle decorator called with args: ", target, name, descriptor );
	let changedMethodName = `${name}Changed`;
	console.debug( "Setting up a ", changedMethodName, " method on ", target );
	target[ changedMethodName ] = function( newValue ) {
		this.logger.debug( `Toggling ${name} to ${newValue ? 'on' : 'off'}.` );
		if ( newValue ) { this.element.classList.add(name); }
		else { this.element.classList.remove(name); }
	};

	let originalBind = target.bind;
	target.bind = function( ...args ) {
		Reflect.apply( originalBind, this, args );
		if ( this[name] ) {
			this.element.classList.add( name );
		}
	};

	return bindable( target, name, descriptor );
}

<commit_msg>Comment out a bunch of debugging in ui-attribute<commit_after>/* -*- javascript -*- */
"use strict";

/**
 * UIAttribute -- base class for Semantic UI attributes
 */

import {inject, bindable, LogManager} from 'aurelia-framework';

const UI_ATTRIBUTE_NAME = /UI(\w+)Attribute/;

@inject( Element )
export class UIAttribute {

	constructor( element ) {
		this.logger = LogManager.getLogger( this.constructor.name );
		this.element = element;
	}

	bind() {
		let nameMatch = UI_ATTRIBUTE_NAME.exec( this.constructor.name );

		if ( nameMatch ) {
			let attrName = nameMatch[ 1 ].toLowerCase();
			this.element.classList.add( 'ui', attrName );
		} else {
			this.logger.warn( "Attribute class doesn't match the naming convention; ",
				"assuming it's going to manage the classList itself." );
		}
	}

}

export function bindableEnum( ...validValues ) {
	// console.debug( "Bindable enum decorator called with: ", validValues );
	return function( target, name, descriptor ) {
		let changedMethodName = `${name}Changed`;
		// console.debug( "Setting up a ", changedMethodName, " method on ", target );
		target[ changedMethodName ] = function( newValue, oldValue ) {
			this.logger.debug( `Changing ${name} to ${newValue} from ${oldValue}` );
			this.element.classList.remove( oldValue );
			this.element.classList.add( newValue );
		};

		let originalBind = target.bind;
		target.bind = function( ...args ) {
			Reflect.apply( originalBind, this, args );
			if ( this[name] ) {
				this.element.classList.add( this[name] );
			}
		};

		return bindable( target, name, descriptor );
	};
}

export function bindableToggle( target, name, descriptor ) {
	// console.debug( "Bindable toggle decorator called with args: ", target, name, descriptor );
	let changedMethodName = `${name}Changed`;
	// console.debug( "Setting up a ", changedMethodName, " method on ", target );
	target[ changedMethodName ] = function( newValue ) {
		this.logger.debug( `Toggling ${name} to ${newValue ? 'on' : 'off'}.` );
		if ( newValue ) { this.element.classList.add(name); }
		else { this.element.classList.remove(name); }
	};

	let originalBind = target.bind;
	target.bind = function( ...args ) {
		Reflect.apply( originalBind, this, args );
		if ( this[name] ) {
			this.element.classList.add( name );
		}
	};

	return bindable( target, name, descriptor );
}

<|endoftext|>


<commit_before>var Loader = function ( editor ) {

	var scope = this;
	var signals = editor.signals;

	this.loadFile = function ( file ) {

		var filename = file.name;
		var extension = filename.split( '.' ).pop().toLowerCase();

		switch ( extension ) {

			case 'babylon':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;
					var json = JSON.parse( contents );

					var loader = new THREE.BabylonLoader();
					var scene = loader.parse( json );

					editor.setScene( scene );

				}, false );
				reader.readAsText( file );

				break;

			case 'ctm':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var data = new Uint8Array( event.target.result );

					var stream = new CTM.Stream( data );
					stream.offset = 0;

					var loader = new THREE.CTMLoader();
					loader.createModel( new CTM.File( stream ), function( geometry ) {

						geometry.sourceType = "ctm";
						geometry.sourceFile = file.name;

						var material = new THREE.MeshPhongMaterial();

						var mesh = new THREE.Mesh( geometry, material );
						mesh.name = filename;

						editor.addObject( mesh );
						editor.select( mesh );

					} );

				}, false );
				reader.readAsArrayBuffer( file );

				break;

			case 'dae':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					var parser = new DOMParser();
					var xml = parser.parseFromString( contents, 'text/xml' );

					var loader = new THREE.ColladaLoader();
					loader.parse( xml, function ( collada ) {

						collada.scene.name = filename;

						editor.addObject( collada.scene );
						editor.select( collada.scene );

					} );

				}, false );
				reader.readAsText( file );

				break;

			case 'js':
			case 'json':

			case '3geo':
			case '3mat':
			case '3obj':
			case '3scn':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					// 2.0

					if ( contents.indexOf( 'postMessage' ) !== -1 ) {

						var blob = new Blob( [ contents ], { type: 'text/javascript' } );
						var url = URL.createObjectURL( blob );

						var worker = new Worker( url );

						worker.onmessage = function ( event ) {

							event.data.metadata = { version: 2 };
							handleJSON( event.data, file, filename );

						};

						worker.postMessage( Date.now() );

						return;

					}

					// >= 3.0

					var data;

					try {

						data = JSON.parse( contents );

					} catch ( error ) {

						alert( error );
						return;

					}

					handleJSON( data, file, filename );

				}, false );
				reader.readAsText( file );

				break;

			case 'obj':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					var object = new THREE.OBJLoader().parse( contents );
					object.name = filename;

					editor.addObject( object );
					editor.select( object );

				}, false );
				reader.readAsText( file );

				break;

			case 'ply':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					console.log( contents );

					var geometry = new THREE.PLYLoader().parse( contents );
					geometry.sourceType = "ply";
					geometry.sourceFile = file.name;

					var material = new THREE.MeshPhongMaterial();

					var mesh = new THREE.Mesh( geometry, material );
					mesh.name = filename;

					editor.addObject( mesh );
					editor.select( mesh );

				}, false );
				reader.readAsText( file );

				break;

			case 'stl':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					var geometry = new THREE.STLLoader().parse( contents );
					geometry.sourceType = "stl";
					geometry.sourceFile = file.name;

					var material = new THREE.MeshPhongMaterial();

					var mesh = new THREE.Mesh( geometry, material );
					mesh.name = filename;

					editor.addObject( mesh );
					editor.select( mesh );

				}, false );

				if ( reader.readAsBinaryString !== undefined ) {

					reader.readAsBinaryString( file );

				} else {

					reader.readAsArrayBuffer( file );

				}

				break;

			/*
			case 'utf8':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					var geometry = new THREE.UTF8Loader().parse( contents );
					var material = new THREE.MeshLambertMaterial();

					var mesh = new THREE.Mesh( geometry, material );

					editor.addObject( mesh );
					editor.select( mesh );

				}, false );
				reader.readAsBinaryString( file );

				break;
			*/

			case 'vtk':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					var geometry = new THREE.VTKLoader().parse( contents );
					geometry.sourceType = "vtk";
					geometry.sourceFile = file.name;

					var material = new THREE.MeshPhongMaterial();

					var mesh = new THREE.Mesh( geometry, material );
					mesh.name = filename;

					editor.addObject( mesh );
					editor.select( mesh );

				}, false );
				reader.readAsText( file );

				break;

			case 'wrl':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					var result = new THREE.VRMLLoader().parse( contents );

					editor.setScene( result );

				}, false );
				reader.readAsText( file );

				break;

			default:

				alert( 'Unsupported file format.' );

				break;

		}

	}

	var handleJSON = function ( data, file, filename ) {

		if ( data.metadata === undefined ) { // 2.0

			data.metadata = { type: 'Geometry' };

		}

		if ( data.metadata.type === undefined ) { // 3.0

			data.metadata.type = 'Geometry';

		}

		if ( data.metadata.version === undefined ) {

			data.metadata.version = data.metadata.formatVersion;

		}

		if ( data.metadata.type.toLowerCase() === 'geometry' ) {

			var loader = new THREE.JSONLoader();
			var result = loader.parse( data );

			var geometry = result.geometry;
			var material;

			if ( result.materials !== undefined ) {

				if ( result.materials.length > 1 ) {

					material = new THREE.MeshFaceMaterial( result.materials );

				} else {

					material = result.materials[ 0 ];

				}

			} else {

				material = new THREE.MeshPhongMaterial();

			}

			geometry.sourceType = "ascii";
			geometry.sourceFile = file.name;

			var mesh;

			if ( geometry.animation && geometry.animation.hierarchy ) {

				mesh = new THREE.SkinnedMesh( geometry, material );

			} else {

				mesh = new THREE.Mesh( geometry, material );

			}

			mesh.name = filename;

			editor.addObject( mesh );
			editor.select( mesh );

		} else if ( data.metadata.type.toLowerCase() === 'object' ) {

			var loader = new THREE.ObjectLoader();
			var result = loader.parse( data );

			if ( result instanceof THREE.Scene ) {

				editor.setScene( result );

			} else {

				editor.addObject( result );
				editor.select( result );

			}

		} else if ( data.metadata.type.toLowerCase() === 'scene' ) {

			// DEPRECATED

			var loader = new THREE.SceneLoader();
			loader.parse( data, function ( result ) {

				editor.setScene( result.scene );

			}, '' );

		}

	};

}
<commit_msg>Editor: Added support for BufferGeometry .json.<commit_after>var Loader = function ( editor ) {

	var scope = this;
	var signals = editor.signals;

	this.loadFile = function ( file ) {

		var filename = file.name;
		var extension = filename.split( '.' ).pop().toLowerCase();

		switch ( extension ) {

			case 'babylon':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;
					var json = JSON.parse( contents );

					var loader = new THREE.BabylonLoader();
					var scene = loader.parse( json );

					editor.setScene( scene );

				}, false );
				reader.readAsText( file );

				break;

			case 'ctm':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var data = new Uint8Array( event.target.result );

					var stream = new CTM.Stream( data );
					stream.offset = 0;

					var loader = new THREE.CTMLoader();
					loader.createModel( new CTM.File( stream ), function( geometry ) {

						geometry.sourceType = "ctm";
						geometry.sourceFile = file.name;

						var material = new THREE.MeshPhongMaterial();

						var mesh = new THREE.Mesh( geometry, material );
						mesh.name = filename;

						editor.addObject( mesh );
						editor.select( mesh );

					} );

				}, false );
				reader.readAsArrayBuffer( file );

				break;

			case 'dae':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					var parser = new DOMParser();
					var xml = parser.parseFromString( contents, 'text/xml' );

					var loader = new THREE.ColladaLoader();
					loader.parse( xml, function ( collada ) {

						collada.scene.name = filename;

						editor.addObject( collada.scene );
						editor.select( collada.scene );

					} );

				}, false );
				reader.readAsText( file );

				break;

			case 'js':
			case 'json':

			case '3geo':
			case '3mat':
			case '3obj':
			case '3scn':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					// 2.0

					if ( contents.indexOf( 'postMessage' ) !== -1 ) {

						var blob = new Blob( [ contents ], { type: 'text/javascript' } );
						var url = URL.createObjectURL( blob );

						var worker = new Worker( url );

						worker.onmessage = function ( event ) {

							event.data.metadata = { version: 2 };
							handleJSON( event.data, file, filename );

						};

						worker.postMessage( Date.now() );

						return;

					}

					// >= 3.0

					var data;

					try {

						data = JSON.parse( contents );

					} catch ( error ) {

						alert( error );
						return;

					}

					handleJSON( data, file, filename );

				}, false );
				reader.readAsText( file );

				break;

			case 'obj':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					var object = new THREE.OBJLoader().parse( contents );
					object.name = filename;

					editor.addObject( object );
					editor.select( object );

				}, false );
				reader.readAsText( file );

				break;

			case 'ply':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					console.log( contents );

					var geometry = new THREE.PLYLoader().parse( contents );
					geometry.sourceType = "ply";
					geometry.sourceFile = file.name;

					var material = new THREE.MeshPhongMaterial();

					var mesh = new THREE.Mesh( geometry, material );
					mesh.name = filename;

					editor.addObject( mesh );
					editor.select( mesh );

				}, false );
				reader.readAsText( file );

				break;

			case 'stl':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					var geometry = new THREE.STLLoader().parse( contents );
					geometry.sourceType = "stl";
					geometry.sourceFile = file.name;

					var material = new THREE.MeshPhongMaterial();

					var mesh = new THREE.Mesh( geometry, material );
					mesh.name = filename;

					editor.addObject( mesh );
					editor.select( mesh );

				}, false );

				if ( reader.readAsBinaryString !== undefined ) {

					reader.readAsBinaryString( file );

				} else {

					reader.readAsArrayBuffer( file );

				}

				break;

			/*
			case 'utf8':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					var geometry = new THREE.UTF8Loader().parse( contents );
					var material = new THREE.MeshLambertMaterial();

					var mesh = new THREE.Mesh( geometry, material );

					editor.addObject( mesh );
					editor.select( mesh );

				}, false );
				reader.readAsBinaryString( file );

				break;
			*/

			case 'vtk':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					var geometry = new THREE.VTKLoader().parse( contents );
					geometry.sourceType = "vtk";
					geometry.sourceFile = file.name;

					var material = new THREE.MeshPhongMaterial();

					var mesh = new THREE.Mesh( geometry, material );
					mesh.name = filename;

					editor.addObject( mesh );
					editor.select( mesh );

				}, false );
				reader.readAsText( file );

				break;

			case 'wrl':

				var reader = new FileReader();
				reader.addEventListener( 'load', function ( event ) {

					var contents = event.target.result;

					var result = new THREE.VRMLLoader().parse( contents );

					editor.setScene( result );

				}, false );
				reader.readAsText( file );

				break;

			default:

				alert( 'Unsupported file format.' );

				break;

		}

	}

	var handleJSON = function ( data, file, filename ) {

		if ( data.metadata === undefined ) { // 2.0

			data.metadata = { type: 'Geometry' };

		}

		if ( data.metadata.type === undefined ) { // 3.0

			data.metadata.type = 'Geometry';

		}

		if ( data.metadata.version === undefined ) {

			data.metadata.version = data.metadata.formatVersion;

		}

		if ( data.metadata.type === 'BufferGeometry' ) {

			var loader = new THREE.BufferGeometryLoader();
			var result = loader.parse( data );

			var mesh = new THREE.Mesh( result );

			editor.addObject( mesh );
			editor.select( mesh );

		} else if ( data.metadata.type.toLowerCase() === 'geometry' ) {

			var loader = new THREE.JSONLoader();
			var result = loader.parse( data );

			var geometry = result.geometry;
			var material;

			if ( result.materials !== undefined ) {

				if ( result.materials.length > 1 ) {

					material = new THREE.MeshFaceMaterial( result.materials );

				} else {

					material = result.materials[ 0 ];

				}

			} else {

				material = new THREE.MeshPhongMaterial();

			}

			geometry.sourceType = "ascii";
			geometry.sourceFile = file.name;

			var mesh;

			if ( geometry.animation && geometry.animation.hierarchy ) {

				mesh = new THREE.SkinnedMesh( geometry, material );

			} else {

				mesh = new THREE.Mesh( geometry, material );

			}

			mesh.name = filename;

			editor.addObject( mesh );
			editor.select( mesh );

		} else if ( data.metadata.type.toLowerCase() === 'object' ) {

			var loader = new THREE.ObjectLoader();
			var result = loader.parse( data );

			if ( result instanceof THREE.Scene ) {

				editor.setScene( result );

			} else {

				editor.addObject( result );
				editor.select( result );

			}

		} else if ( data.metadata.type.toLowerCase() === 'scene' ) {

			// DEPRECATED

			var loader = new THREE.SceneLoader();
			loader.parse( data, function ( result ) {

				editor.setScene( result.scene );

			}, '' );

		}

	};

}
<|endoftext|>


<commit_before>import { makeStyles, ThemeProvider } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import SvgIcon from '@material-ui/core/SvgIcon';
import { lightTheme, darkTheme } from 'lib/theme';

import cx from 'clsx';

function Arrow() {
  return (
    <SvgIcon viewBox="0 0 14 27">
      <path
        d="M2 1L10.6746 10.8575C12.0041 12.3683 12.0041 14.6317 10.6746 16.1425L2 26"
        stroke="currentColor"
        strokeWidth="3"
        fill="none"
      />
    </SvgIcon>
  );
}

const useStyles = makeStyles(theme => ({
  button: {
    border: '3px solid currentColor',
    borderRadius: 41,
    padding: '20px 20px 20px 25px',
    fontSize: 24,
    fontWeight: 700,
    lineHeight: 1,

    [theme.breakpoints.down('sm')]: {
      padding: '8px 16px 8px 20px',
      fontSize: 18,
    },

    '& img': {
      marginLeft: 16,

      [theme.breakpoints.down('sm')]: {
        height: 17,
        marginLeft: 8,
      },
    },
  },
}));

/**
 * Action button with right arrow. Use CSS font color to control its color.
 *
 * @param {object} props
 * @param {'light' | 'dark'} props.theme - On dark or light background. Affects hover & ripple style.
 */
function ActionButton({ className, theme = 'light', children, ...props }) {
  const classes = useStyles();

  return (
    <ThemeProvider theme={theme === 'light' ? lightTheme : darkTheme}>
      <Button
        variant="outlined"
        className={cx(classes.button, className)}
        {...props}
      >
        {children}
        <Arrow />
      </Button>
    </ThemeProvider>
  );
}

export default ActionButton;
<commit_msg>Fix report page action button arrow margin<commit_after>import { makeStyles, ThemeProvider } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import SvgIcon from '@material-ui/core/SvgIcon';
import { lightTheme, darkTheme } from 'lib/theme';

import cx from 'clsx';

function Arrow() {
  return (
    <SvgIcon viewBox="0 0 14 27">
      <path
        d="M2 1L10.6746 10.8575C12.0041 12.3683 12.0041 14.6317 10.6746 16.1425L2 26"
        stroke="currentColor"
        strokeWidth="3"
        fill="none"
      />
    </SvgIcon>
  );
}

const useStyles = makeStyles(theme => ({
  button: {
    border: '3px solid currentColor',
    borderRadius: 41,
    padding: '20px 20px 20px 25px',
    fontSize: 24,
    fontWeight: 700,
    lineHeight: 1,

    [theme.breakpoints.down('sm')]: {
      padding: '8px 16px 8px 20px',
      fontSize: 18,
    },

    '& svg': {
      marginLeft: 16,

      [theme.breakpoints.down('sm')]: {
        height: 17,
        marginLeft: 8,
      },
    },
  },
}));

/**
 * Action button with right arrow. Use CSS font color to control its color.
 *
 * @param {object} props
 * @param {'light' | 'dark'} props.theme - On dark or light background. Affects hover & ripple style.
 */
function ActionButton({ className, theme = 'light', children, ...props }) {
  const classes = useStyles();

  return (
    <ThemeProvider theme={theme === 'light' ? lightTheme : darkTheme}>
      <Button
        variant="outlined"
        className={cx(classes.button, className)}
        {...props}
      >
        {children}
        <Arrow />
      </Button>
    </ThemeProvider>
  );
}

export default ActionButton;
<|endoftext|>


<commit_before>// app.js

// VARIABLE DECLARATION
// =============================================================================
// Call the packages
var express    = require('express');
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

// Connection mongoose-mongodb
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Beach = require('./models/beach');

// configure app to use bodyParser()
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        // set port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();

router.use(function(req, res, next) {
    console.log('CRUD method is running!');
    next();
});

router.get('/', function(req, res) {
    res.json({ message: 'Hello world!' });
});

// main routes

router.route('/beaches')

	// POST
	.post(function(req, res) {

		var beach = new Beach();
		beach.name = req.body.name;  // set the beachs name

		beach.save(function(err) {
			if (err)
				res.send(err);

			res.json({ message: 'beach created!' });
		});

	})

	// GET all
	.get(function(req, res) {
		Beach.find(function(err, beaches) {
			if (err)
				res.send(err);

			res.json(beaches);
		});
	});

router.route('/beaches/:beach_id')

	// get the beach with that id
    .get(function(req, res) {
		Beach.findById(req.params.beach_id, function(err, beach) {
			if (err)
				res.send(err);
			res.json(beach);
		});
	})

	// update the beach with this id
	.put(function(req, res) {
		Beach.findById(req.params.beach_id, function(err, beach) {

			if (err)
				res.send(err);

			beach.name = req.body.name;
			beach.save(function(err) {
				if (err)
					res.send(err);

				res.json({ message: 'beach updated!' });
			});

		});
	})

	// delete the beach with this id
	.delete(function(req, res) {
		Beach.remove({
			_id: req.params.beach_id
		}, function(err, beach) {
			if (err)
				res.send(err);

			res.json({ message: 'Successfully deleted' });
		});
	});

// REGISTER OUR ROUTES -------------------------------
// all of our routes (of 'router') will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Server running on port ' + port);
<commit_msg>database path updated<commit_after>// app.js

// VARIABLE DECLARATION
// =============================================================================
// Call the packages
var express    = require('express');
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

// Connection mongoose-mongodb
var mongoose = require('mongoose');
mongoose.connect('mongodb://<dbuser>:<dbpassword>@ds031203.mongolab.com:31203/heroku_c9lt3r0p');
var Beach = require('./models/beach');

// configure app to use bodyParser()
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        // set port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();

router.use(function(req, res, next) {
    console.log('CRUD method is running!');
    next();
});

router.get('/', function(req, res) {
    res.json({ message: 'Hello world!' });
});

// main routes

router.route('/beaches')

	// POST
	.post(function(req, res) {

		var beach = new Beach();
		beach.name = req.body.name;  // set the beachs name

		beach.save(function(err) {
			if (err)
				res.send(err);

			res.json({ message: 'beach created!' });
		});

	})

	// GET all
	.get(function(req, res) {
		Beach.find(function(err, beaches) {
			if (err)
				res.send(err);

			res.json(beaches);
		});
	});

router.route('/beaches/:beach_id')

	// get the beach with that id
    .get(function(req, res) {
		Beach.findById(req.params.beach_id, function(err, beach) {
			if (err)
				res.send(err);
			res.json(beach);
		});
	})

	// update the beach with this id
	.put(function(req, res) {
		Beach.findById(req.params.beach_id, function(err, beach) {

			if (err)
				res.send(err);

			beach.name = req.body.name;
			beach.save(function(err) {
				if (err)
					res.send(err);

				res.json({ message: 'beach updated!' });
			});

		});
	})

	// delete the beach with this id
	.delete(function(req, res) {
		Beach.remove({
			_id: req.params.beach_id
		}, function(err, beach) {
			if (err)
				res.send(err);

			res.json({ message: 'Successfully deleted' });
		});
	});

// REGISTER OUR ROUTES -------------------------------
// all of our routes (of 'router') will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Server running on port ' + port);
<|endoftext|>


<commit_before>/* global Danbooru */

import _ from "lodash";

import EX from "../ex.js";
import Posts from "./posts.js";
import PreviewPanel from "./preview_panel.js";

export default class ModeMenu {
  static initialize() {
    ModeMenu.uninitializeDanbooruModeMenu();
    ModeMenu.initializeModeMenu();
    ModeMenu.initializeTagScriptControls();
    ModeMenu.initializeThumbnails();
  }

  static uninitializeDanbooruModeMenu() {
    Danbooru.PostModeMenu.initialize = _.noop;
    Danbooru.PostModeMenu.show_notice = _.noop;
    $(".post-preview a").unbind("click", Danbooru.PostModeMenu.click);
    $(document).unbind("keydown", "1 2 3 4 5 6 7 8 9 0", Danbooru.PostModeMenu.change_tag_script);
    $("#sidebar #mode-box").hide();
  }

  static initializeModeMenu() {
    $('.ex-mode-menu select[name="mode"]').change(ModeMenu.switchMode);
    const mode = _.defaultTo(EX.config.modeMenuState[EX.config.pageKey()], "view");
    ModeMenu.setMode(mode);
  }

  static initializeTagScriptControls() {
    $('.ex-mode-menu input[name="tag-script"]').on(
      "input", _.debounce(ModeMenu.saveTagScript, 250)
    );

    $('.ex-mode-menu select[name="tag-script-number"]').change(ModeMenu.switchTagScript);
    ModeMenu.setTagScriptNumber(EX.config.tagScriptNumber);

    $('.ex-mode-menu button[name="apply"]').click(ModeMenu.applyTagScript);
    $('.ex-mode-menu button[name="select-all"]').click(ModeMenu.selectAll);
    $('.ex-mode-menu button[name="select-invert"]').click(ModeMenu.invertSelection);
  }

  static initializeThumbnails() {
    const selector = `
      .mod-queue-preview aside a,
      div.post-preview .preview a,
      article.post-preview a
    `;

    $(document).on("click", selector, ModeMenu.onThumbnailClick);

    // Hide cursor when clicking outside of thumbnails.
    $(document).on("click", () => $(".ex-cursor").removeClass("ex-cursor"));
  }

  static switchToTagScript(event) {
    const newN = Number(String.fromCharCode(event.which));
    const oldN = ModeMenu.getTagScriptNumber();

    if (ModeMenu.getMode() === "tag-script" && newN === oldN) {
      $('.ex-mode-menu input[name="tag-script"]').focus();
    } else {
      ModeMenu.setMode("tag-script");
      ModeMenu.setTagScriptNumber(newN);
    }

    event.preventDefault();
  }

  static switchMode() {
    const mode = ModeMenu.getMode();

    let state = EX.config.modeMenuState;
    state[EX.config.pageKey()] = mode;
    EX.config.modeMenuState = state;

    $("body").removeClass((i, klass) => (klass.match(/mode-.*/) || []).join(' '));
    $("body").addClass(`mode-${mode}`);

    if (mode === "tag-script") {
      $(".ex-mode-menu .ex-tag-script-controls").show();

      $("#page").selectable({
        filter: "article.post-preview, div.post-preview .preview, .mod-queue-preview aside",
        delay: 200,
      });
    } else {
      $(".ex-mode-menu .ex-tag-script-controls").hide();

      if ($("#page").selectable("instance")) {
        $("#page").selectable("destroy");
      }
    }
  }

  static switchTagScript(event) {
    const n = ModeMenu.getTagScriptNumber();
    EX.config.tagScriptNumber = n;

    const script = EX.config.tagScripts[n];
    $('.ex-mode-menu input[name="tag-script"]').val(script).change();
  }

  static onThumbnailClick(event) {
    // Only apply on left click, not middle click and not ctrl+left click.
    if (event.ctrlKey || event.which !== 1) {
      return true;
    }

    switch (ModeMenu.getMode()) {
      case "view":
        return true;

      case "tag-script":
        Selection.moveCursorTo($(event.target), { selectTarget: true, selectInterval: event.shiftKey });
        /* fallthrough */

      case "preview":
        return false;
    }
  }

  static applyTagScript(event) {
    const mode = ModeMenu.getMode();

    if (mode === "tag-script") {
      const tag_script = ModeMenu.getTagScript();
      $(".ui-selected").each((i, e) => {
        const post_id = $(e).closest(".post-preview").data("id");
        Danbooru.TagScript.run(post_id, tag_script);
      });
    }
  }

  static selectAll(event) {
    if ($(".ui-selected").length) {
      $(".ui-selected").removeClass("ui-selected");
    } else {
      $(".ui-selectee").addClass("ui-selected");
    }

    event.preventDefault();
  }

  static invertSelection(event) {
    let $unselected = $(".ui-selectee:not(.ui-selected)");
    let $selected = $(".ui-selectee.ui-selected");

    $unselected.addClass("ui-selected");
    $selected.removeClass("ui-selected");
  }

  static getMode() {
    return $(".ex-mode-menu select").val();
  }

  static setMode(mode) {
    $('.ex-mode-menu select[name="mode"]').val(mode).change();
  }

  static toggleMode(mode) {
    ModeMenu.setMode(ModeMenu.getMode() === mode ? "view" : mode);
  }

  static getTagScript() {
    return $('.ex-mode-menu input[name="tag-script"]').val().trim();
  }

  static saveTagScript() {
    const scripts = EX.config.tagScripts;
    scripts[ModeMenu.getTagScriptNumber()] = ModeMenu.getTagScript();
    EX.config.tagScripts = scripts;
  }

  static getTagScriptNumber() {
    return Number($('.ex-mode-menu select[name="tag-script-number"]').val());
  }

  static setTagScriptNumber(n) {
    $('.ex-mode-menu select[name="tag-script-number"]').val(n).change();
  }
}

export class Selection {
  static get post() {
    return "article.post-preview, div.post-preview .preview, .mod-queue-preview aside";
  }

  static get $cursor() { return $(".ex-cursor"); }
  static set $cursor($newCursor) {
    Selection.$cursor.removeClass("ex-cursor");
    return $newCursor.addClass("ex-cursor");
  }

  static between($from, $to) {
    if ($from.nextAll().is($to)) {
      return $from.nextUntil($to, Selection.post).add($to).andSelf();
    } else if ($from.prevAll().is($to)) {
      return $from.prevUntil($to, Selection.post).add($to).andSelf();
    } else {
      return $();
    }
  }

  static selectBetween($from, $to) {
    return Selection.between($from, $to).addClass("ui-selected");
  }

  static deselectBetween($from, $to) {
    return Selection.between($from, $to).removeClass("ui-selected");
  }

  static moveCursor(direction, { selectInterval = false } = {}) {
    const post = Selection.post;
    const $cursor = Selection.$cursor;
    const firstInColumn = $posts =>
      $posts.filter((i, e) => $(e).position().left === $cursor.position().left).first();

    const $target = direction === "left"  ? $cursor.prev(post)
                  : direction === "right" ? $cursor.next(post)
                  : direction === "up"    ? firstInColumn($cursor.prevAll(post))
                  : direction === "down"  ? firstInColumn($cursor.nextAll(post))
                  : $();

    // XXX cleanup
    if ($target.length) {
      if (selectInterval) {
        $cursor.closest(".ui-selectee").toggleClass("ui-selected");
      }

      Selection.moveCursorTo($target, { selectInterval });
    }
  }

  static moveCursorTo($target, { selectTarget = false, selectInterval = false } = {}) {
    const $newCursor = $target.closest(".ui-selectee");
    const $oldCursor = $(".ex-cursor").length
                     ? $(".ex-cursor")
                     : $newCursor;

    const $newMark = $newCursor;
    const $oldMark = $(".ex-mark").length
                   ? $(".ex-mark")
                   : $(Selection.post).first().addClass("ex-mark");

    Selection.swapCursor($oldCursor, $newCursor);

    if (selectTarget) {
        $newCursor.toggleClass("ui-selected");
    }

    if (selectInterval) {
        Selection.deselectBetween($oldMark, $oldCursor);
        Selection.selectBetween($oldMark, $newCursor);
    } else {
        $oldMark.removeClass("ex-mark");
        $newMark.addClass("ex-mark");
    }
  }

  static swapCursor($oldCursor, $newCursor) {
    $oldCursor.removeClass("ex-cursor");
    $newCursor.addClass("ex-cursor");

    const post = Posts.normalize($newCursor.closest(".post-preview").data());
    const html = Posts.preview(post, { size: "large", classes: ["ex-no-tooltip"] });

    $("#ex-preview-panel article").replaceWith(html);
    PreviewPanel.setHeight();
  }
}
<commit_msg>[feat] Scroll posts into view when moving cursor with arrow keys.<commit_after>/* global Danbooru */

import _ from "lodash";

import EX from "../ex.js";
import Posts from "./posts.js";
import PreviewPanel from "./preview_panel.js";

export default class ModeMenu {
  static initialize() {
    ModeMenu.uninitializeDanbooruModeMenu();
    ModeMenu.initializeModeMenu();
    ModeMenu.initializeTagScriptControls();
    ModeMenu.initializeThumbnails();
  }

  static uninitializeDanbooruModeMenu() {
    Danbooru.PostModeMenu.initialize = _.noop;
    Danbooru.PostModeMenu.show_notice = _.noop;
    $(".post-preview a").unbind("click", Danbooru.PostModeMenu.click);
    $(document).unbind("keydown", "1 2 3 4 5 6 7 8 9 0", Danbooru.PostModeMenu.change_tag_script);
    $("#sidebar #mode-box").hide();
  }

  static initializeModeMenu() {
    $('.ex-mode-menu select[name="mode"]').change(ModeMenu.switchMode);
    const mode = _.defaultTo(EX.config.modeMenuState[EX.config.pageKey()], "view");
    ModeMenu.setMode(mode);
  }

  static initializeTagScriptControls() {
    $('.ex-mode-menu input[name="tag-script"]').on(
      "input", _.debounce(ModeMenu.saveTagScript, 250)
    );

    $('.ex-mode-menu select[name="tag-script-number"]').change(ModeMenu.switchTagScript);
    ModeMenu.setTagScriptNumber(EX.config.tagScriptNumber);

    $('.ex-mode-menu button[name="apply"]').click(ModeMenu.applyTagScript);
    $('.ex-mode-menu button[name="select-all"]').click(ModeMenu.selectAll);
    $('.ex-mode-menu button[name="select-invert"]').click(ModeMenu.invertSelection);
  }

  static initializeThumbnails() {
    const selector = `
      .mod-queue-preview aside a,
      div.post-preview .preview a,
      article.post-preview a
    `;

    $(document).on("click", selector, ModeMenu.onThumbnailClick);

    // Hide cursor when clicking outside of thumbnails.
    $(document).on("click", () => $(".ex-cursor").removeClass("ex-cursor"));
  }

  static switchToTagScript(event) {
    const newN = Number(String.fromCharCode(event.which));
    const oldN = ModeMenu.getTagScriptNumber();

    if (ModeMenu.getMode() === "tag-script" && newN === oldN) {
      $('.ex-mode-menu input[name="tag-script"]').focus();
    } else {
      ModeMenu.setMode("tag-script");
      ModeMenu.setTagScriptNumber(newN);
    }

    event.preventDefault();
  }

  static switchMode() {
    const mode = ModeMenu.getMode();

    let state = EX.config.modeMenuState;
    state[EX.config.pageKey()] = mode;
    EX.config.modeMenuState = state;

    $("body").removeClass((i, klass) => (klass.match(/mode-.*/) || []).join(' '));
    $("body").addClass(`mode-${mode}`);

    if (mode === "tag-script") {
      $(".ex-mode-menu .ex-tag-script-controls").show();

      $("#page").selectable({
        filter: "article.post-preview, div.post-preview .preview, .mod-queue-preview aside",
        delay: 200,
      });
    } else {
      $(".ex-mode-menu .ex-tag-script-controls").hide();

      if ($("#page").selectable("instance")) {
        $("#page").selectable("destroy");
      }
    }
  }

  static switchTagScript(event) {
    const n = ModeMenu.getTagScriptNumber();
    EX.config.tagScriptNumber = n;

    const script = EX.config.tagScripts[n];
    $('.ex-mode-menu input[name="tag-script"]').val(script).change();
  }

  static onThumbnailClick(event) {
    // Only apply on left click, not middle click and not ctrl+left click.
    if (event.ctrlKey || event.which !== 1) {
      return true;
    }

    switch (ModeMenu.getMode()) {
      case "view":
        return true;

      case "tag-script":
        Selection.moveCursorTo($(event.target), { selectTarget: true, selectInterval: event.shiftKey });
        /* fallthrough */

      case "preview":
        return false;
    }
  }

  static applyTagScript(event) {
    const mode = ModeMenu.getMode();

    if (mode === "tag-script") {
      const tag_script = ModeMenu.getTagScript();
      $(".ui-selected").each((i, e) => {
        const post_id = $(e).closest(".post-preview").data("id");
        Danbooru.TagScript.run(post_id, tag_script);
      });
    }
  }

  static selectAll(event) {
    if ($(".ui-selected").length) {
      $(".ui-selected").removeClass("ui-selected");
    } else {
      $(".ui-selectee").addClass("ui-selected");
    }

    event.preventDefault();
  }

  static invertSelection(event) {
    let $unselected = $(".ui-selectee:not(.ui-selected)");
    let $selected = $(".ui-selectee.ui-selected");

    $unselected.addClass("ui-selected");
    $selected.removeClass("ui-selected");
  }

  static getMode() {
    return $(".ex-mode-menu select").val();
  }

  static setMode(mode) {
    $('.ex-mode-menu select[name="mode"]').val(mode).change();
  }

  static toggleMode(mode) {
    ModeMenu.setMode(ModeMenu.getMode() === mode ? "view" : mode);
  }

  static getTagScript() {
    return $('.ex-mode-menu input[name="tag-script"]').val().trim();
  }

  static saveTagScript() {
    const scripts = EX.config.tagScripts;
    scripts[ModeMenu.getTagScriptNumber()] = ModeMenu.getTagScript();
    EX.config.tagScripts = scripts;
  }

  static getTagScriptNumber() {
    return Number($('.ex-mode-menu select[name="tag-script-number"]').val());
  }

  static setTagScriptNumber(n) {
    $('.ex-mode-menu select[name="tag-script-number"]').val(n).change();
  }
}

export class Selection {
  static get post() {
    return "article.post-preview, div.post-preview .preview, .mod-queue-preview aside";
  }

  static get $cursor() {
    return $(".ex-cursor").length
         ? $(".ex-cursor")
         : $(Selection.post).first().addClass("ex-cursor");
  }

  static set $cursor($newCursor) {
    Selection.$cursor.removeClass("ex-cursor");
    return $newCursor.addClass("ex-cursor");
  }

  static between($from, $to) {
    if ($from.nextAll().is($to)) {
      return $from.nextUntil($to, Selection.post).add($to).andSelf();
    } else if ($from.prevAll().is($to)) {
      return $from.prevUntil($to, Selection.post).add($to).andSelf();
    } else {
      return $();
    }
  }

  static selectBetween($from, $to) {
    return Selection.between($from, $to).addClass("ui-selected");
  }

  static deselectBetween($from, $to) {
    return Selection.between($from, $to).removeClass("ui-selected");
  }

  static moveCursor(direction, { selectInterval = false } = {}) {
    const post = Selection.post;
    const $cursor = Selection.$cursor;
    const firstInColumn = $posts =>
      $posts.filter((i, e) => $(e).position().left === $cursor.position().left).first();

    const $target = direction === "left"  ? $cursor.prev(post)
                  : direction === "right" ? $cursor.next(post)
                  : direction === "up"    ? firstInColumn($cursor.prevAll(post))
                  : direction === "down"  ? firstInColumn($cursor.nextAll(post))
                  : $();

    // XXX cleanup
    if ($target.length) {
      if (selectInterval) {
        $cursor.closest(".ui-selectee").toggleClass("ui-selected");
      }

      Selection.moveCursorTo($target, { selectInterval });
    }
  }

  static moveCursorTo($target, { selectTarget = false, selectInterval = false } = {}) {
    const $newCursor = $target.closest(".ui-selectee");
    const $oldCursor = $(".ex-cursor").length
                     ? $(".ex-cursor")
                     : $newCursor;

    const $newMark = $newCursor;
    const $oldMark = $(".ex-mark").length
                   ? $(".ex-mark")
                   : $(Selection.post).first().addClass("ex-mark");

    Selection.swapCursor($oldCursor, $newCursor);

    if (selectTarget) {
        $newCursor.toggleClass("ui-selected");
    }

    if (selectInterval) {
        Selection.deselectBetween($oldMark, $oldCursor);
        Selection.selectBetween($oldMark, $newCursor);
    } else {
        $oldMark.removeClass("ex-mark");
        $newMark.addClass("ex-mark");
    }
  }

  static swapCursor($oldCursor, $newCursor) {
    $oldCursor.removeClass("ex-cursor");
    $newCursor.addClass("ex-cursor");
    Selection.scrollWindowTo($newCursor);

    const post = Posts.normalize($newCursor.closest(".post-preview").data());
    const html = Posts.preview(post, { size: "large", classes: ["ex-no-tooltip"] });

    $("#ex-preview-panel article").replaceWith(html);
    PreviewPanel.setHeight();
  }

  static scrollWindowTo($target) {
    const targetTop = $target.position().top;
    const targetHeight = $target.height();

    if (targetTop + targetHeight > window.scrollY + window.innerHeight) {
      window.scrollTo(0, targetTop + 2*targetHeight - window.innerHeight);
    } else if (targetTop < window.scrollY) {
      window.scrollTo(0, targetTop - targetHeight);
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var compress = require('compression');
var errorHandler = require('errorhandler');
var favicon = require('serve-favicon');
var http = require('http');
var moment = require('moment-timezone');
var request = require('request');
var cors = require('cors')
var ical = require('ical-generator');
var clc = require('cli-color');
var sm = require('sitemap');

var config = require('./config');
var events = require('./events');
var archives = require('./archives');
var countdown = require('./countdown');
var repos = require('./repos');
var passport = require('./events/setup-passport');

var app = express();
var podcastApiUrl = config.podcastApiUrl;
var cal = ical();

var sitemap = sm.createSitemap ({
  hostname: 'https://' + config.domain,
  cacheTime: 600000,
  urls: [
    {
      url: '/',
      changefreq: 'daily',
      priority: 0.3
    }
  ]
});

app.set('port', process.env.PORT || process.env.OPENSHIFT_IOJS_PORT || 3000);

app.use(compress());
app.use('/public', express.static(__dirname + '/public'));
app.use('/humans.txt', express.static(__dirname + '/public/humans.txt'));
app.use('/robots.txt', express.static(__dirname + '/public/robots.txt'));
app.use('/sitemap.xml', express.static(__dirname + '/public/sitemap.xml'));
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(errorHandler());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(passport.initialize());

app.locals.pretty = true;
app.locals.moment = require('moment-timezone');

app.get('/sitemap.xml', function(req, res) {
  sitemap.toXML( function (xml) {
    res.header('Content-Type', 'application/xml');
    res.send( xml );
  });
});

app.get('/', function(req, res) {
  countdown.calculateCountdown();
  res.render('index.jade', {
    formattedTime: countdown.formattedTime,
    days: countdown.days,
    hours: countdown.hours,
    minutes: countdown.minutes,
    seconds: countdown.seconds,
    repos: repos.feed.repos.slice(0, 10),
    events: events.feed.events.slice(0, 10)
  });
});

app.get('/api/v1/check/:checkdate', cors(), function(req, res) {
  var checkdate = moment(req.params.checkdate, 'YYYY-MM-DD');
  var clashedEvents = {
    'meta': {
      'generated_at': new Date().toISOString(),
      'location': config.city,
      'api_version': config.api_version
    },
    'events': []
  };

  clashedEvents.events = events.feed.events.filter(function(element) {
    if (moment(element.start_time).isSame(checkdate, 'day') ) {
      return true;
    }
  });

  clashedEvents.meta.total_events = clashedEvents.events.length;

  res.send(clashedEvents);

})

app.get('/api/v1/events', cors(), function(req, res) {
  res.send(events.feed);
});

app.get('/api/v1/repos', cors(), function(req, res) {
  res.send(repos.feed);
});

app.get('/api/v1/repos/:language', cors(), function(req, res) {
  var language = req.params.language.toLowerCase();
  var reposWIthLanguage = repos.feed.repos.filter(function(repo) {
    if (!repo.language) {
      return false;
    }
    return repo.language.toLowerCase() === language;
  });

  res.send({
    meta: {
      generated_at: new Date().toISOString(),
      location: config.city,
      total_repos: repos.length,
      api_version: config.api_version,
      max_repos: reposWIthLanguage.length
    },
    repos: reposWIthLanguage
  });
});

app.get('/admin', function(req, res) {
  res.render('facebook_login.jade', {
    auth0: require('./config').auth0,
    error: req.query.error ? true : false,
    user: req.query.user ? req.query.user : ''
  });
});

app.get('/cal', function(req, res) {
  cal.clear()
  cal.setDomain(config.domain).setName(config.calendarTitle);

  events.feed.events.filter(function(thisEvent) {
    if (!(thisEvent.start_time && thisEvent.end_time && thisEvent.name && thisEvent.description)) {
      console.log('Not enough information on this event', thisEvent.name, thisEvent.start_time, thisEvent.end_time, thisEvent.description);
    }
    return thisEvent.start_time && thisEvent.end_time && thisEvent.name && thisEvent.description
  }).forEach(function(thisEvent) {
      cal.addEvent({
        start: new Date(thisEvent.start_time),
        end: new Date(thisEvent.end_time),
        summary: thisEvent.name + ' by ' + thisEvent.group_name,
        description: thisEvent.description + ' \n\nEvent URL: ' + thisEvent.url || thisEvent.group_url,
        location: thisEvent.location || config.city,
        url: thisEvent.url || thisEvent.group_url
      });
  });

  // add next We Build LIVE show dat
  request(podcastApiUrl, function(err, msg, response) {
    if (err) {
     console.error(clc.red('Error: Fetching We Build Live podcast api'));
     return;
    }
    response = JSON.parse(response);
    cal.addEvent({
      start: new Date(response.meta.next_live_show.start_time),
      end: new Date(response.meta.next_live_show.end_time),
      summary: response.meta.next_live_show.summary,
      description: response.meta.next_live_show.description + ' \n\nEvent URL: ' + response.meta.next_live_show.url,
      location: config.city,
      url: response.meta.next_live_show.url
    });
    cal.serve(res);
  });

});

app.get('/check', function(req, res) {
  res.redirect('/#check');
})

app.get('/callback', passport.callback);

app.post('/api/v1/events/update', function(req, res) {
  if (req.params.secret !== process.env.WEBUILD_API_SECRET) {
    res.status(503).send('Incorrect secret key');
    return;
  }
  events.update();
  res.status(200).send('Events feed updating...');
})

app.post('/api/v1/repos/update', function(req, res) {
  if (req.params.secrem !== process.env.WEBUILD_API_SECRET) {
    res.status(503).send('Incorrect secret key');
    return;
  }
  repos.update().then(function() {
    console.log('GitHub feed generated');
  });
  res.status(200).send('Updating the repos feed; sit tight!');
});

app.post('/api/v1/archives/update', function(req, res) {
  if (req.params.secret !== process.env.WEBUILD_API_SECRET) {
    res.status(503).send('Incorrect secret key');
    return;
  }
  archives.update();
  res.status(200).send('Updating the archives; sit tight!');

})

app.use('/api/v1/podcasts', cors(), function(req, res) {
 var url = podcastApiUrl;
 res.setHeader('Cache-Control', 'public, max-age=86400'); // 1 day
 request(url, function(err, msg, response) {
  if (err) {
    res.status(503).send('We Build Live Error');
    return;
  }
  res.end(response);
 })
});

app.use(function(req, res) {
  res.redirect('/');
  return;
});

events.update();
repos.update();
countdown.update();

http.createServer(app).listen(app.get('port'), process.env.OPENSHIFT_IOJS_IP || '0.0.0.0', function() {
  console.log(clc.black('Express server started at http://localhost:' + app.get('port')));
});
<commit_msg>fix: using request body for update requests and refactored config.ip and config.port<commit_after>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var compress = require('compression');
var errorHandler = require('errorhandler');
var favicon = require('serve-favicon');
var http = require('http');
var moment = require('moment-timezone');
var request = require('request');
var cors = require('cors')
var ical = require('ical-generator');
var clc = require('cli-color');
var sm = require('sitemap');

var config = require('./config');
var events = require('./events');
var archives = require('./archives');
var countdown = require('./countdown');
var repos = require('./repos');
var passport = require('./events/setup-passport');

var app = express();
var podcastApiUrl = config.podcastApiUrl;
var cal = ical();

var sitemap = sm.createSitemap ({
  hostname: 'https://' + config.domain,
  cacheTime: 600000,
  urls: [
    {
      url: '/',
      changefreq: 'daily',
      priority: 0.3
    }
  ]
});

config.port = process.env.PORT || process.env.OPENSHIFT_IOJS_PORT || 3000;
config.ip = process.env.OPENSHIFT_IOJS_IP || '0.0.0.0';

app.set('port', config.port);

app.use(compress());
app.use('/public', express.static(__dirname + '/public'));
app.use('/humans.txt', express.static(__dirname + '/public/humans.txt'));
app.use('/robots.txt', express.static(__dirname + '/public/robots.txt'));
app.use('/sitemap.xml', express.static(__dirname + '/public/sitemap.xml'));
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(errorHandler());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(passport.initialize());

app.locals.pretty = true;
app.locals.moment = require('moment-timezone');

app.get('/sitemap.xml', function(req, res) {
  sitemap.toXML( function (xml) {
    res.header('Content-Type', 'application/xml');
    res.send( xml );
  });
});

app.get('/', function(req, res) {
  countdown.calculateCountdown();
  res.render('index.jade', {
    formattedTime: countdown.formattedTime,
    days: countdown.days,
    hours: countdown.hours,
    minutes: countdown.minutes,
    seconds: countdown.seconds,
    repos: repos.feed.repos.slice(0, 10),
    events: events.feed.events.slice(0, 10)
  });
});

app.get('/api/v1/check/:checkdate', cors(), function(req, res) {
  var checkdate = moment(req.params.checkdate, 'YYYY-MM-DD');
  var clashedEvents = {
    'meta': {
      'generated_at': new Date().toISOString(),
      'location': config.city,
      'api_version': config.api_version
    },
    'events': []
  };

  clashedEvents.events = events.feed.events.filter(function(element) {
    if (moment(element.start_time).isSame(checkdate, 'day') ) {
      return true;
    }
  });

  clashedEvents.meta.total_events = clashedEvents.events.length;

  res.send(clashedEvents);

})

app.get('/api/v1/events', cors(), function(req, res) {
  res.send(events.feed);
});

app.get('/api/v1/repos', cors(), function(req, res) {
  res.send(repos.feed);
});

app.get('/api/v1/repos/:language', cors(), function(req, res) {
  var language = req.params.language.toLowerCase();
  var reposWIthLanguage = repos.feed.repos.filter(function(repo) {
    if (!repo.language) {
      return false;
    }
    return repo.language.toLowerCase() === language;
  });

  res.send({
    meta: {
      generated_at: new Date().toISOString(),
      location: config.city,
      total_repos: repos.length,
      api_version: config.api_version,
      max_repos: reposWIthLanguage.length
    },
    repos: reposWIthLanguage
  });
});

app.get('/admin', function(req, res) {
  res.render('facebook_login.jade', {
    auth0: require('./config').auth0,
    error: req.query.error ? true : false,
    user: req.query.user ? req.query.user : ''
  });
});

app.get('/cal', function(req, res) {
  cal.clear()
  cal.setDomain(config.domain).setName(config.calendarTitle);

  events.feed.events.filter(function(thisEvent) {
    if (!(thisEvent.start_time && thisEvent.end_time && thisEvent.name && thisEvent.description)) {
      console.log('Not enough information on this event', thisEvent.name, thisEvent.start_time, thisEvent.end_time, thisEvent.description);
    }
    return thisEvent.start_time && thisEvent.end_time && thisEvent.name && thisEvent.description
  }).forEach(function(thisEvent) {
      cal.addEvent({
        start: new Date(thisEvent.start_time),
        end: new Date(thisEvent.end_time),
        summary: thisEvent.name + ' by ' + thisEvent.group_name,
        description: thisEvent.description + ' \n\nEvent URL: ' + thisEvent.url || thisEvent.group_url,
        location: thisEvent.location || config.city,
        url: thisEvent.url || thisEvent.group_url
      });
  });

  // add next We Build LIVE show dat
  request(podcastApiUrl, function(err, msg, response) {
    if (err) {
     console.error(clc.red('Error: Fetching We Build Live podcast api'));
     return;
    }
    response = JSON.parse(response);
    cal.addEvent({
      start: new Date(response.meta.next_live_show.start_time),
      end: new Date(response.meta.next_live_show.end_time),
      summary: response.meta.next_live_show.summary,
      description: response.meta.next_live_show.description + ' \n\nEvent URL: ' + response.meta.next_live_show.url,
      location: config.city,
      url: response.meta.next_live_show.url
    });
    cal.serve(res);
  });

});

app.get('/check', function(req, res) {
  res.redirect('/#check');
})

app.get('/callback', passport.callback);

app.post('/api/v1/events/update', function(req, res) {
  if (!req.body || req.body.secret !== process.env.WEBUILD_API_SECRET) {
    res.status(503).send('Incorrect secret key');
    return;
  }
  events.update();
  res.status(200).send('Events feed updating...');
});

app.post('/api/v1/repos/update', function(req, res) {
  if (!req.body || req.body.secret !== process.env.WEBUILD_API_SECRET) {
    res.status(503).send('Incorrect secret key');
    return;
  }
  repos.update().then(function() {
    console.log('GitHub feed generated');
  });
  res.status(200).send('Updating the repos feed; sit tight!');
});

app.post('/api/v1/archives/update', function(req, res) {
  if (!req.body || req.body.secret !== process.env.WEBUILD_API_SECRET) {
    res.status(503).send('Incorrect secret key');
    return;
  }
  archives.update();
  res.status(200).send('Updating the archives; sit tight!');

});

app.use('/api/v1/podcasts', cors(), function(req, res) {
 var url = podcastApiUrl;
 res.setHeader('Cache-Control', 'public, max-age=86400'); // 1 day
 request(url, function(err, msg, response) {
  if (err) {
    res.status(503).send('We Build Live Error');
    return;
  }
  res.end(response);
 })
});

app.use(function(req, res) {
  res.redirect('/');
  return;
});

events.update();
repos.update();
countdown.update();

http.createServer(app).listen(config.port, config.ip, function() {
  console.log(clc.black('Express server started at http://localhost:' + app.get('port')));
});
<|endoftext|>


<commit_before>geo.gui.svgWidget = function (arg) {
  'use strict';
  if (!(this instanceof geo.gui.svgWidget)) {
    return new geo.gui.svgWidget(arg);
  }

  geo.gui.domWidget.call(this, arg);

  var m_this = this,
      m_width = null,
      m_height = null,
      m_corners = null,
      m_features = {},
      m_scale = 1,
      m_dx = 0,
      m_dy = 0,
      m_id = 'd3-' + geo.d3.uniqueID();

  this._d3id = function () {
    return m_id;
  };

  this.scaleFactor = function () {
    return m_scale;
  };

  this.draw = function () {};

  function setAttrs(select, attrs) {
    var key;
    for (key in attrs) {
      if (attrs.hasOwnProperty(key)) {
        select.attr(key, attrs[key]);
      }
    }
  }

  function initCorners() {
    var layer = m_this.layer(),
        map = layer.map(),
        width = m_this.layer().width(),
        height = m_this.layer().height();

    m_width = width;
    m_height = height;
    if (!m_width || !m_height) {
      throw 'Map layer has size 0';
    }
    m_corners = {
      'upperLeft': map.displayToGcs({'x': 0, 'y': 0}),
      'lowerRight': map.displayToGcs({'x': width, 'y': height})
    };
  }

  function setTransform() {
    if (!m_corners) {
      initCorners();
    }

    if (!m_this.args.sticky) {
      return;
    }

    var layer = m_this.layer(),
        map = layer.map(),
        upperLeft = map.gcsToDisplay(m_corners.upperLeft),
        lowerRight = map.gcsToDisplay(m_corners.lowerRight),
        dx, dy, scale;

    // calculate the translation
    dx = upperLeft.x;
    dy = upperLeft.y;

    // calculate the scale
    scale = (lowerRight.y - upperLeft.y) / m_height;

    // set the group transform property
    //group.attr('transform', 'matrix(' + [scale, 0, 0, scale, dx, dy].join() + ')');

    // set internal variables
    m_scale = scale;
    m_dx = dx;
    m_dy = dy;
  }

  this._createCanvas = function () {
    if (!m_this.canvas()) {
      m_this.canvas(d3.select(m_this.parentCanvas()).append('svg')[0][0]);

      d3.select(m_this.canvas()).attr('class', m_this._d3id());

      // @todo do we want these defs to be defined for *every* svg widget?
      var m_defs = d3.select(m_this.canvas()).append('defs');

      var shadow = m_defs
            .append('filter')
            .attr('id', 'geo-highlight')
            .attr('x', '-100%')
            .attr('y', '-100%')
            .attr('width', '300%')
            .attr('height', '300%');
      shadow
        .append('feMorphology')
        .attr('operator', 'dilate')
        .attr('radius', 2)
        .attr('in', 'SourceAlpha')
        .attr('result', 'dilateOut');
      shadow
        .append('feGaussianBlur')
        .attr('stdDeviation', 5)
        .attr('in', 'dilateOut')
        .attr('result', 'blurOut');
      shadow
        .append('feColorMatrix')
        .attr('type', 'matrix')
        .attr('values', '-1 0 0 0 1  0 -1 0 0 1  0 0 -1 0 1  0 0 0 1 0')
        .attr('in', 'blurOut')
        .attr('result', 'invertOut');
      shadow
        .append('feBlend')
        .attr('in', 'SourceGraphic')
        .attr('in2', 'invertOut')
        .attr('mode', 'normal');

      shadow = m_defs.append('filter')
        .attr('id', 'geo-blur')
        .attr('x', '-100%')
        .attr('y', '-100%')
        .attr('width', '300%')
        .attr('height', '300%');

      shadow
        .append('feGaussianBlur')
        .attr('stdDeviation', 20)
        .attr('in', 'SourceGraphic');

      // sticky, class, width, height, grouping
    }
  };

  this._appendChild = function () {
    m_this.parentCanvas().appendChild(m_this.canvas());
  };

  this._resize = function (x, y, w, h) {
    if (!m_corners) {
      initCorners();
    }
    d3.select(m_this.canvas()).attr('width', w);
    d3.select(m_this.canvas()).attr('height', h);
    setTransform();
    m_this.layer().geoTrigger(geo.event.d3Rescale, { scale: m_scale }, true);
  };

  this._init = function () {
    arg = arg || {};
    m_this.args = arg;
    m_this.args.sticky = arg.sticky || false;
    m_this.args.positionType = arg.positionType || 'viewport';

    if (arg.hasOwnProperty('parent') && arg.parent instanceof geo.gui.widget) {
      arg.parent.addChild(m_this);
    }

    m_this._createCanvas();
    m_this._appendChild();

    m_this.canvas().addEventListener('mousedown', function (e) {
      e.stopPropagation();
    });

    this.reposition();
  };

  // @todo docs lost
  this._removeFeature = function (id) {
    m_this.select(id).remove();
    delete m_features[id];
    return m_this;
  };

  this._drawFeatures = function (arg) {
    m_features[arg.id] = {
      data: arg.data,
      index: arg.dataIndex,
      style: arg.style,
      attributes: arg.attributes,
      classes: arg.classes,
      append: arg.append
    };
    return m_this.__render(arg.id);
  };

  function setStyles(selection, style) {
    selection = style = null;
    console.log('setStyles not yet implemented from renderer');
  }

  this.__render = function (id) {
    var key;
    if (id === undefined) {
      for (key in m_features) {
        if (m_features.hasOwnProperty(key)) {
          m_this.__render(key);
        }
      }
      return m_this;
    }
    var data = m_features[id].data,
        index = m_features[id].index,
        style = m_features[id].style,
        attributes = m_features[id].attributes,
        classes = m_features[id].classes,
        append = m_features[id].append,
        selection = m_this.select(id).data(data, index);
    selection.enter().append(append);
    selection.exit().remove();
    setAttrs(selection, attributes);
    selection.attr('class', classes.concat([id]).join(' '));
    setStyles(selection, style);
    return m_this;
  };

  this.layer().geoOn(geo.event.pan, setTransform);

  this.layer().geoOn(geo.event.resize, function (event) {
    m_this._resize(event.x, event.y, event.width, event.height);
  });

  this.layer().geoOn(geo.event.zoom, function () {
    setTransform();
    m_this.__render();
    m_this.layer().geoTrigger(geo.event.d3Rescale, { scale: m_scale }, true);
  });

  return this;
};

inherit(geo.gui.svgWidget, geo.gui.domWidget);

geo.registerWidget('dom', 'svg', geo.gui.svgWidget);
<commit_msg>Utilize d3Renderer as a helper in the svgWidget<commit_after>geo.gui.svgWidget = function (arg) {
  'use strict';
  if (!(this instanceof geo.gui.svgWidget)) {
    return new geo.gui.svgWidget(arg);
  }

  geo.gui.domWidget.call(this, arg);

  var m_this = this,
      m_renderer = geo.d3.d3Renderer;

  this._createCanvas = function () {
    m_renderer.call(m_this);
  };

  this._appendChild = function () {
    m_this.parentCanvas().appendChild(m_this.canvas());
  };

  this._init = function () {
    arg = arg || {};
    m_this.args = arg;
    m_this.args.sticky = arg.sticky || false;
    m_this.args.positionType = arg.positionType || 'viewport';

    if (arg.hasOwnProperty('parent') && arg.parent instanceof geo.gui.widget) {
      arg.parent.addChild(m_this);
    }

    m_this._createCanvas();
    m_this._appendChild();

    m_this.canvas().addEventListener('mousedown', function (e) {
      e.stopPropagation();
    });

    this.reposition();
  };

  return this;
};

inherit(geo.gui.svgWidget, geo.gui.domWidget);

geo.registerWidget('dom', 'svg', geo.gui.svgWidget);
<|endoftext|>