<commit_before>/* eslint no-console: [2, { allow: ["warn", "error"] }] */
import {
  REQUEST_USER,
  RECEIVE_USER,
  SELECT_WATCH_QUILT,
  REQUEST_FRIENDS,
  RECEIVE_FRIENDS,
  REQUEST_NOTIFS,
  RECEIVE_NOTIFS,
  RECEIVE_QUILTS,
  REQUEST_QUILTS,
  RECEIVE_POST_QUILT,
  REQUEST_POST_QUILT,
  REQUEST_ADD_QUILT,
  RESPONSE_ADD_QUILT,
  CREATE_QUILT,
  REVIEW_QUILT,
  ADD_TO_QUILT,
  WATCH_QUILT,
  LOGIN_OR_SIGNUP,
  RECEIVE_USER_ERROR,
  INVITE_FRIENDS,
  RECEIVE_USERNAME_EXIST_ERROR,
  RECEIVE_USERNAME_NOT_EXIST,
  REQUEST_CONTACTS,
  RECEIVE_CONTACTS,
} from '../constants/ActionTypes';

import ip from '../config';
import Keychain from 'react-native-keychain';
import Contacts from 'react-native-contacts';

export const selectLoginOrSignup = (selection) => ({
  type: LOGIN_OR_SIGNUP,
  payload: selection,
});

export const createQuilt = (data) => ({
  type: CREATE_QUILT,
  payload: data,
});

export const addToQuilt = (data) => ({
  type: ADD_TO_QUILT,
  payload: data,
});

export const watchQuilt = (data) => ({
  type: WATCH_QUILT,
  payload: data,
});

// dispatched at login to set the current user of the app
const requestUser = () => ({
  type: REQUEST_USER,
});

const receiveUser = (user) => ({
  type: RECEIVE_USER,
  payload: user,
});

const receiveUserError = () => ({
  type: RECEIVE_USER_ERROR,
});

const receiveUsernameExistError = () => ({
  type: RECEIVE_USERNAME_EXIST_ERROR,
});

const receiveUsernameNotExist = () => ({
  type: RECEIVE_USERNAME_NOT_EXIST,
});

export function signupUser(email, password) {
  return (dispatch) => {
    dispatch(requestUser());
    return fetch(`http://${ip}:8000/api/auth?email=${email}&password=${password}`, {
      method: 'POST',
    })
    .then(response => response.json())
    .then(user => dispatch(receiveUser(user)))
    .catch(error => console.error('error', error));
  };
}

export function loginUser(usernameOrEmail, password) {
  return (dispatch) => {
    dispatch(requestUser());
    return fetch(`http://${ip}:8000/api/auth?usernameOrEmail=${usernameOrEmail}&password=${password}`, {
      method: 'GET',
    })
    .then(response => response.json())
    .then(user => dispatch(receiveUser(user)))
    .catch(error => dispatch(receiveUserError()));
  };
}

export function isLoggedIn() {
  return (dispatch) => {
    dispatch(requestUser());
    return Keychain.getInternetCredentials(`${ip}`)
      .then(credentials => dispatch(receiveUser(JSON.parse(credentials.username))))
      .catch(err => dispatch(receiveUser()));
  }
}

export function updateUser(id, data) {
  const query = Object.assign({}, data);
  delete query.token;
  return (dispatch) => {
    dispatch(requestUser());
    return fetch(`http://${ip}:8000/api/auth?userId=${id}&token=${data.token}`, {
      method: 'PUT',
      body: JSON.stringify(query),
    })
    .then(user => {
      if (user._bodyInit) {
        console.log('user exist');
        return dispatch(receiveUsernameExistError());
      }
      return dispatch(receiveUser(data));
    })
    .catch(error => {
      console.error('error updating user:', error);
      return dispatch(receiveUserError());
    });
  };
}

export function checkUsername(id, data) {
  const query = Object.assign({}, data);
  delete query.token;
  return (dispatch) => {
    dispatch(requestUser());
    return fetch(`http://${ip}:8000/api/user/${query.username}`)
    .then(response => response.json())
    .then(user => {
      if(user.username){
        return dispatch(receiveUsernameExistError());
      }
      return dispatch(receiveUsernameNotExist());
    })
    .catch(error => {
      console.error('error retreiving user:', error);
      return dispatch(receiveUserError());
    });
  };
}

export const reviewQuilt = (file) => ({
  type: REVIEW_QUILT,
  payload: file,
});

// begin post request to send quilt to server
const requestPostQuilt = () => ({
  type: REQUEST_POST_QUILT,
});

// receive response from the server relating to post request
// todo: format response data so that status code passed
const responsePostQuilt = (data) => ({
  type: RECEIVE_POST_QUILT,
  payload: data,
});

export function postQuilt(data) {
  return (dispatch) => {
    dispatch(requestPostQuilt());
    return fetch(`http://${ip}:8000/api/quilt?token=${data.token}`, {
      method: 'POST',
      body: data.video,
      headers: {
        'Content-Type': 'application/json',
        'Meta-Data': JSON.stringify({
          title: data.title,
          theme: data.theme,
          users: data.users,
          creator: data.creator,
        }),
      },
    })
    .then(response => dispatch(responsePostQuilt(response.status)))
    .catch(err => console.error('post quilt error', err));
  };
}

export const contributeToQuilt = (id) => ({
  type: REQUEST_ADD_QUILT,
  payload: id,
});

// begin post request to send quilt to server
const requestAddQuilt = () => ({
  type: REQUEST_ADD_QUILT,
});

// receive response from the server relating to post request
// todo: format response data so that status code passed
const responseAddQuilt = () => ({
  type: RESPONSE_ADD_QUILT,
});

export function postToExistingQuilt(data) {
  return (dispatch) => {
    dispatch(requestAddQuilt());
    return fetch(`http://${ip}:8000/api/quilt/${data.quiltId}?token=${data.token}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Meta-Data': JSON.stringify({
          creator: data.creator,
        }),
      },
      body: data.video,
    })
    .then(response => dispatch(responseAddQuilt(response.status)))
    .catch(err => console.error('post quilt error', err));
  };
}

// get all users from server
const requestFriends = () => ({
  type: REQUEST_FRIENDS,
});

// uncommnet when not testing
const receiveFriends = (friends) => ({
  type: RECEIVE_FRIENDS,
  payload: friends,
});

export function fetchFriends(options) {
  return (dispatch) => {
    dispatch(requestFriends());
    // todo: catch errors

    return fetch(`http://${ip}:8000/api/friends/${options.id}?token=${options.token}`, {
      method: 'GET',
    })
    .then(response => response.json())
    .then(json => dispatch(receiveFriends(json)));
  };
}

const requestContacts = () => {
  return {
    type: REQUEST_CONTACTS,
  }
}

const receiveContacts = (data) => {
  return {
    type: RECEIVE_CONTACTS,
    payload: data,
  }
}

// TODO: clean up
export function getUserContacts(token, userId) {
  return (dispatch) => {
    dispatch(requestContacts());
    return Contacts.getAll((err, contacts) => {
      if (err) {
        console.log('error', err);
      } else {
        const cleanContacts = contacts.reduce((acc, nxt) => {
          acc.push({
            fullName: `${nxt.givenName || ''} ${nxt.familyName || ''}`,
            emails: nxt.emailAddresses.map(obj => obj.email),
            phoneNumbers: nxt.phoneNumbers.map(obj => obj.number),
          });
          return acc;
        }, []);

        return fetch(`http://${ip}:8000/api/cross?userId=${userId}&token=${token}`, {
          method: 'POST',
          body: JSON.stringify(cleanContacts),
        })
        .then(response => dispatch(receiveContacts(JSON.parse(response._bodyInit))));      }
    });
  }
}

// add authentication, dispatches
export function postFriends(userId, token, ...friendsId) {
  return (dispatch) => fetch(`http://${ip}:8000/api/friends/${userId}?token=${token}`, {
    method: 'POST',
    body: JSON.stringify({ friends: friendsId }),
  });
}

const requestQuilts = () => ({
  type: REQUEST_QUILTS,
});

const receiveQuilts = (quilts) => ({
  type: RECEIVE_QUILTS,
  payload: quilts,
});

export function fetchQuilts(options) {
  return (dispatch) => {
    dispatch(requestQuilts());
    return fetch(`http://${ip}:8000/api/quilt?username=${options.username}&token=${options.token}`)
      .then(response => response.json())
      .then(data => dispatch(receiveQuilts(data)))
      .catch(error => console.error('Error in getting user\'s quilts', error));
  };
}

const requestNotifs = () => ({
  type: REQUEST_NOTIFS,
});

const receiveNotifs = (notifs) => ({
  type: RECEIVE_NOTIFS,
  payload: notifs,
});

export function fetchNotifs(userId) {
  return (dispatch) => {
    dispatch(requestNotifs());
    return fetch(`http://${ip}:8000/api/notifications/${userId}`)
      .then((response) => response.json())
      .then((data) => dispatch(receiveNotifs(data)))
      .catch((error) => console.error('Error in getting user\'s notifications', error));
  };
}

export function selectWatchQuilt(data) {
  return {
    type: SELECT_WATCH_QUILT,
    payload: data,
  };
}

export function inviteFriends(data) {
  return {
    type: INVITE_FRIENDS,
    payload: data,
  };
}
<commit_msg>enqure contacts are unique users<commit_after>/* eslint no-console: [2, { allow: ["warn", "error"] }] */
import {
  REQUEST_USER,
  RECEIVE_USER,
  SELECT_WATCH_QUILT,
  REQUEST_FRIENDS,
  RECEIVE_FRIENDS,
  REQUEST_NOTIFS,
  RECEIVE_NOTIFS,
  RECEIVE_QUILTS,
  REQUEST_QUILTS,
  RECEIVE_POST_QUILT,
  REQUEST_POST_QUILT,
  REQUEST_ADD_QUILT,
  RESPONSE_ADD_QUILT,
  CREATE_QUILT,
  REVIEW_QUILT,
  ADD_TO_QUILT,
  WATCH_QUILT,
  LOGIN_OR_SIGNUP,
  RECEIVE_USER_ERROR,
  INVITE_FRIENDS,
  RECEIVE_USERNAME_EXIST_ERROR,
  RECEIVE_USERNAME_NOT_EXIST,
  REQUEST_CONTACTS,
  RECEIVE_CONTACTS,
} from '../constants/ActionTypes';

import ip from '../config';
import Keychain from 'react-native-keychain';
import Contacts from 'react-native-contacts';
import _ from 'lodash';

export const selectLoginOrSignup = (selection) => ({
  type: LOGIN_OR_SIGNUP,
  payload: selection,
});

export const createQuilt = (data) => ({
  type: CREATE_QUILT,
  payload: data,
});

export const addToQuilt = (data) => ({
  type: ADD_TO_QUILT,
  payload: data,
});

export const watchQuilt = (data) => ({
  type: WATCH_QUILT,
  payload: data,
});

// dispatched at login to set the current user of the app
const requestUser = () => ({
  type: REQUEST_USER,
});

const receiveUser = (user) => ({
  type: RECEIVE_USER,
  payload: user,
});

const receiveUserError = () => ({
  type: RECEIVE_USER_ERROR,
});

const receiveUsernameExistError = () => ({
  type: RECEIVE_USERNAME_EXIST_ERROR,
});

const receiveUsernameNotExist = () => ({
  type: RECEIVE_USERNAME_NOT_EXIST,
});

export function signupUser(email, password) {
  return (dispatch) => {
    dispatch(requestUser());
    return fetch(`http://${ip}:8000/api/auth?email=${email}&password=${password}`, {
      method: 'POST',
    })
    .then(response => response.json())
    .then(user => dispatch(receiveUser(user)))
    .catch(error => console.error('error', error));
  };
}

export function loginUser(usernameOrEmail, password) {
  return (dispatch) => {
    dispatch(requestUser());
    return fetch(`http://${ip}:8000/api/auth?usernameOrEmail=${usernameOrEmail}&password=${password}`, {
      method: 'GET',
    })
    .then(response => response.json())
    .then(user => dispatch(receiveUser(user)))
    .catch(error => dispatch(receiveUserError()));
  };
}

export function isLoggedIn() {
  return (dispatch) => {
    dispatch(requestUser());
    return Keychain.getInternetCredentials(`${ip}`)
      .then(credentials => dispatch(receiveUser(JSON.parse(credentials.username))))
      .catch(err => dispatch(receiveUser()));
  }
}

export function updateUser(id, data) {
  const query = Object.assign({}, data);
  delete query.token;
  return (dispatch) => {
    dispatch(requestUser());
    return fetch(`http://${ip}:8000/api/auth?userId=${id}&token=${data.token}`, {
      method: 'PUT',
      body: JSON.stringify(query),
    })
    .then(user => {
      if (user._bodyInit) {
        console.log('user exist');
        return dispatch(receiveUsernameExistError());
      }
      return dispatch(receiveUser(data));
    })
    .catch(error => {
      console.error('error updating user:', error);
      return dispatch(receiveUserError());
    });
  };
}

export function checkUsername(id, data) {
  const query = Object.assign({}, data);
  delete query.token;
  return (dispatch) => {
    dispatch(requestUser());
    return fetch(`http://${ip}:8000/api/user/${query.username}`)
    .then(response => response.json())
    .then(user => {
      if(user.username){
        return dispatch(receiveUsernameExistError());
      }
      return dispatch(receiveUsernameNotExist());
    })
    .catch(error => {
      console.error('error retreiving user:', error);
      return dispatch(receiveUserError());
    });
  };
}

export const reviewQuilt = (file) => ({
  type: REVIEW_QUILT,
  payload: file,
});

// begin post request to send quilt to server
const requestPostQuilt = () => ({
  type: REQUEST_POST_QUILT,
});

// receive response from the server relating to post request
// todo: format response data so that status code passed
const responsePostQuilt = (data) => ({
  type: RECEIVE_POST_QUILT,
  payload: data,
});

export function postQuilt(data) {
  return (dispatch) => {
    dispatch(requestPostQuilt());
    return fetch(`http://${ip}:8000/api/quilt?token=${data.token}`, {
      method: 'POST',
      body: data.video,
      headers: {
        'Content-Type': 'application/json',
        'Meta-Data': JSON.stringify({
          title: data.title,
          theme: data.theme,
          users: data.users,
          creator: data.creator,
        }),
      },
    })
    .then(response => dispatch(responsePostQuilt(response.status)))
    .catch(err => console.error('post quilt error', err));
  };
}

export const contributeToQuilt = (id) => ({
  type: REQUEST_ADD_QUILT,
  payload: id,
});

// begin post request to send quilt to server
const requestAddQuilt = () => ({
  type: REQUEST_ADD_QUILT,
});

// receive response from the server relating to post request
// todo: format response data so that status code passed
const responseAddQuilt = () => ({
  type: RESPONSE_ADD_QUILT,
});

export function postToExistingQuilt(data) {
  return (dispatch) => {
    dispatch(requestAddQuilt());
    return fetch(`http://${ip}:8000/api/quilt/${data.quiltId}?token=${data.token}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Meta-Data': JSON.stringify({
          creator: data.creator,
        }),
      },
      body: data.video,
    })
    .then(response => dispatch(responseAddQuilt(response.status)))
    .catch(err => console.error('post quilt error', err));
  };
}

// get all users from server
const requestFriends = () => ({
  type: REQUEST_FRIENDS,
});

// uncommnet when not testing
const receiveFriends = (friends) => ({
  type: RECEIVE_FRIENDS,
  payload: friends,
});

export function fetchFriends(options) {
  return (dispatch) => {
    dispatch(requestFriends());
    // todo: catch errors

    return fetch(`http://${ip}:8000/api/friends/${options.id}?token=${options.token}`, {
      method: 'GET',
    })
    .then(response => response.json())
    .then(json => dispatch(receiveFriends(json)));
  };
}

const requestContacts = () => {
  return {
    type: REQUEST_CONTACTS,
  }
}

const receiveContacts = (data) => {
  return {
    type: RECEIVE_CONTACTS,
    payload: data,
  }
}

// TODO: clean up
export function getUserContacts(token, userId) {
  return (dispatch) => {
    dispatch(requestContacts());
    return Contacts.getAll((err, contacts) => {
      if (err) {
        console.log('error', err);
      } else {
        const cleanContacts = contacts.reduce((acc, nxt) => {
          acc.push({
            fullName: `${nxt.givenName || ''} ${nxt.familyName || ''}`,
            emails: nxt.emailAddresses.map(obj => obj.email),
            phoneNumbers: nxt.phoneNumbers.map(obj => obj.number),
          });
          return acc;
        }, []);

        return fetch(`http://${ip}:8000/api/cross?userId=${userId}&token=${token}`, {
          method: 'POST',
          body: JSON.stringify(cleanContacts),
        })
        .then(response => {
          const usersInContacts = _.uniq(JSON.parse(response._bodyInit), 'username');
          dispatch(receiveContacts(usersInContacts))
        });
      }
    });
  }
}

// add authentication, dispatches
export function postFriends(userId, token, ...friendsId) {
  return (dispatch) => fetch(`http://${ip}:8000/api/friends/${userId}?token=${token}`, {
    method: 'POST',
    body: JSON.stringify({ friends: friendsId }),
  });
}

const requestQuilts = () => ({
  type: REQUEST_QUILTS,
});

const receiveQuilts = (quilts) => ({
  type: RECEIVE_QUILTS,
  payload: quilts,
});

export function fetchQuilts(options) {
  return (dispatch) => {
    dispatch(requestQuilts());
    return fetch(`http://${ip}:8000/api/quilt?username=${options.username}&token=${options.token}`)
      .then(response => response.json())
      .then(data => dispatch(receiveQuilts(data)))
      .catch(error => console.error('Error in getting user\'s quilts', error));
  };
}

const requestNotifs = () => ({
  type: REQUEST_NOTIFS,
});

const receiveNotifs = (notifs) => ({
  type: RECEIVE_NOTIFS,
  payload: notifs,
});

export function fetchNotifs(userId) {
  return (dispatch) => {
    dispatch(requestNotifs());
    return fetch(`http://${ip}:8000/api/notifications/${userId}`)
      .then((response) => response.json())
      .then((data) => dispatch(receiveNotifs(data)))
      .catch((error) => console.error('Error in getting user\'s notifications', error));
  };
}

export function selectWatchQuilt(data) {
  return {
    type: SELECT_WATCH_QUILT,
    payload: data,
  };
}

export function inviteFriends(data) {
  return {
    type: INVITE_FRIENDS,
    payload: data,
  };
}
<|endoftext|>


<commit_before>'use strict'

const path = require('path')

const articles = require('./articles.js')
const database = require('./database.js')
const paths = require('./paths.js')

const addCommonData = data => {
  const commonData = {
    currentYear: new Date().getFullYear()
  }

  return Object.assign({}, commonData, data)
}

function index (req, res) {
  database.getAtricles().then(databaseArticles => {
    const data = addCommonData({
      articles: databaseArticles
    })

    res.render(path.join(paths.templates, 'index.html'), data)
  }).catch(e => console.log(e))
}

function article (req, res) {
  database.getAtricle(req.params.article).then(article => {
    if (article) {
      const data = addCommonData({
        title: article.title,
        date: article.publication_date,
        article: article.content
      })

      res.render(path.join(paths.templates, 'article.html'), data)
    } else {
      // TODO: function for displaying 404
      res.render(path.join(paths.templates, '404.html'))
    }
  }).catch(e => console.log(e))
}

function debug (req, res) {
  // get all metadata from article.md files
  let metadata = articles.getArticlesMetadata(paths.articles, 'article.md')

  // sort articles by publication_date descendant
  articles.sortObjectBy(metadata, 'publication_date')

  const data = addCommonData({
    articles: metadata,
    debugUrlPrefix: 'debug/'
  })

  res.render(path.join(paths.templates, 'index.html'), data)
}

function debugArticle (req, res) {
  let articleName = req.params.article

  let articlePath = articles.findPathToArticle(paths.articles, articleName, 2)
  if (!articlePath) {
    res.render(path.join(paths.templates, '404.html'))
  } else {
    const fsArticle = articles.parseArticle(path.join(articlePath, 'article.md'))
    const data = addCommonData({
      title: fsArticle.metadata.title,
      date: fsArticle.metadata.publication_date,
      article: fsArticle.html
    })

    res.render(path.join(paths.templates, 'article.html'), data)
  }
}

const rss = (req, res) => {
  database.getRSS().then(databaseArticles => {
    const data = {articles: databaseArticles}
    for (let i = 0; i < data.articles.length; i++) {
      data.articles[i].pubData = new Date(data.articles.publication_date).toGMTString()
    }

    res.type('text/xml')
    res.render('other/rss.xml', data)
  }).catch(e => console.log(e))
}

module.exports = {
  index,
  article,
  debug,
  debugArticle,
  rss
}
<commit_msg>routes: use template names instead of full path<commit_after>'use strict'

const path = require('path')

const articles = require('./articles.js')
const database = require('./database.js')
const paths = require('./paths.js')

const addCommonData = data => {
  const commonData = {
    currentYear: new Date().getFullYear()
  }

  return Object.assign({}, commonData, data)
}

function index (req, res) {
  database.getAtricles().then(databaseArticles => {
    const data = addCommonData({
      articles: databaseArticles
    })

    res.render('index.html', data)
  }).catch(e => console.log(e))
}

function article (req, res) {
  database.getAtricle(req.params.article).then(article => {
    if (article) {
      const data = addCommonData({
        title: article.title,
        date: article.publication_date,
        article: article.content
      })

      res.render('article.html', data)
    } else {
      // TODO: function for displaying 404
      res.render('404.html')
    }
  }).catch(e => console.log(e))
}

function debug (req, res) {
  // get all metadata from article.md files
  let metadata = articles.getArticlesMetadata(paths.articles, 'article.md')

  // sort articles by publication_date descendant
  articles.sortObjectBy(metadata, 'publication_date')

  const data = addCommonData({
    articles: metadata,
    debugUrlPrefix: 'debug/'
  })

  res.render('index.html', data)
}

function debugArticle (req, res) {
  let articleName = req.params.article

  let articlePath = articles.findPathToArticle(paths.articles, articleName, 2)
  if (!articlePath) {
    res.render('404.html')
    return
  }

  const fsArticle = articles.parseArticle(path.join(articlePath, 'article.md'))
  const data = addCommonData({
    title: fsArticle.metadata.title,
    date: fsArticle.metadata.publication_date,
    article: fsArticle.html
  })

  res.render('article.html', data)
}

const rss = (req, res) => {
  database.getRSS().then(databaseArticles => {
    const data = {articles: databaseArticles}
    for (let i = 0; i < data.articles.length; i++) {
      data.articles[i].pubData = new Date(data.articles.publication_date).toGMTString()
    }

    res.type('text/xml')
    res.render('other/rss.xml', data)
  }).catch(e => console.log(e))
}

module.exports = {
  index,
  article,
  debug,
  debugArticle,
  rss
}
<|endoftext|>


<commit_before>'use strict';

var format = function(str, data) {
    var re = /{([^{}]+)}/g;

    return str.replace(/{([^{}]+)}/g, function(match, val) {
        var prop = data;
        val.split('.').forEach(function(key) {
            prop = prop[key];
        });

        return prop;
    });
};

String.prototype.format = function(data) {
    return format(this, data);
};

var nomesMeses = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
var nomesDias = ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'];

Date.prototype.nomeMes = function() {
    return nomesMeses[this.getMonth()];
};

Date.prototype.nomeDia = function() {
    return nomesDias[this.getDay()];
};

Date.prototype.idadeNascidoEm = function(nascimento) {
    nascimento = [nascimento.splice(0, 2), nascimento.splice(2, 2), nascimento.splice(4, 4)];
    var dataNascimento = new Date(parseInt(nascimento.splice(4, 4)), parseInt(nascimento.splice(2, 2)) - 1, parseInt(nascimento.splice(0, 2)));
    var idade = (this - dataNascimento) / (1000 * 60 * 60 * 24 * 365.4);
    return nomesDias[this.getDay()];
};

//var urlBackEnd = 'https://concept2-staging.herokuapp.com';
var urlBackEnd = 'http://localhost:5000';

angular.module(
    'concept2',
    [
        'ngRoute',
        'ngResource',
        'ngCookies',
        'uiGmapgoogle-maps',
        'ui.mask',
        'concept2.services',
        'concept2.login',
        'concept2.home',
        'concept2.produtos',
        'concept2.noticias',
        'concept2.comunidade',
        'concept2.eventos',
        'concept2.suporte',
        'concept2.contato'
    ])
    .factory('atualizaToken', ['Autentic', function(Autentic) {
        return {
            response: function(response) {
                var headers = response.headers();
                if (headers['xsrf-token']) {
                   Autentic.atualizaValores(headers['xsrf-token'], headers['user-id'])
                }
                return response;
            },
            request: function(config) {
                config.headers['XSRF-TOKEN'] = Autentic.token;
                return config;
            }
        };
    }])
    .config(['$sceDelegateProvider', '$httpProvider', function($sceDelegateProvider, $httpProvider) {
        $sceDelegateProvider.resourceUrlWhitelist([
            'self',
            '{0}/**'.format([urlBackEnd])
        ]);
        $httpProvider.defaults.withCredentials = true;
        $httpProvider.interceptors.push('atualizaToken');
    }])
    .run(['$rootScope', 'Autentic', function($rootScope, Autentic) {
        $rootScope.pagina = "";
        $rootScope.titulo = "";
        $rootScope.$on('$locationChangeSuccess', function(evt, absNewUrl, absOldUrl) {
            $rootScope.referrer = absOldUrl;
        });
        Autentic.atualizaValores();
        $rootScope.atletaLogado = Autentic.estaLogado();
    }]);
<commit_msg>Corrigindo a url do backend<commit_after>'use strict';

var format = function(str, data) {
    var re = /{([^{}]+)}/g;

    return str.replace(/{([^{}]+)}/g, function(match, val) {
        var prop = data;
        val.split('.').forEach(function(key) {
            prop = prop[key];
        });

        return prop;
    });
};

String.prototype.format = function(data) {
    return format(this, data);
};

var nomesMeses = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
var nomesDias = ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'];

Date.prototype.nomeMes = function() {
    return nomesMeses[this.getMonth()];
};

Date.prototype.nomeDia = function() {
    return nomesDias[this.getDay()];
};

Date.prototype.idadeNascidoEm = function(nascimento) {
    nascimento = [nascimento.splice(0, 2), nascimento.splice(2, 2), nascimento.splice(4, 4)];
    var dataNascimento = new Date(parseInt(nascimento.splice(4, 4)), parseInt(nascimento.splice(2, 2)) - 1, parseInt(nascimento.splice(0, 2)));
    var idade = (this - dataNascimento) / (1000 * 60 * 60 * 24 * 365.4);
    return nomesDias[this.getDay()];
};

var urlBackEnd = 'https://concept2-staging.herokuapp.com';
//var urlBackEnd = 'http://localhost:5000';

angular.module(
    'concept2',
    [
        'ngRoute',
        'ngResource',
        'ngCookies',
        'uiGmapgoogle-maps',
        'ui.mask',
        'concept2.services',
        'concept2.login',
        'concept2.home',
        'concept2.produtos',
        'concept2.noticias',
        'concept2.comunidade',
        'concept2.eventos',
        'concept2.suporte',
        'concept2.contato'
    ])
    .factory('atualizaToken', ['Autentic', function(Autentic) {
        return {
            response: function(response) {
                var headers = response.headers();
                if (headers['xsrf-token']) {
                   Autentic.atualizaValores(headers['xsrf-token'], headers['user-id'])
                }
                return response;
            },
            request: function(config) {
                config.headers['XSRF-TOKEN'] = Autentic.token;
                return config;
            }
        };
    }])
    .config(['$sceDelegateProvider', '$httpProvider', function($sceDelegateProvider, $httpProvider) {
        $sceDelegateProvider.resourceUrlWhitelist([
            'self',
            '{0}/**'.format([urlBackEnd])
        ]);
        $httpProvider.defaults.withCredentials = true;
        $httpProvider.interceptors.push('atualizaToken');
    }])
    .run(['$rootScope', 'Autentic', function($rootScope, Autentic) {
        $rootScope.pagina = "";
        $rootScope.titulo = "";
        $rootScope.$on('$locationChangeSuccess', function(evt, absNewUrl, absOldUrl) {
            $rootScope.referrer = absOldUrl;
        });
        Autentic.atualizaValores();
        $rootScope.atletaLogado = Autentic.estaLogado();
    }]);
<|endoftext|>


<commit_before>import Reflux from 'reflux';

import Firebase from 'firebase';
import Actions from '../actions/Actions';
import { firebaseUrl } from '../utils/constants';

let baseRef = new Firebase(firebaseUrl);
let usersRef = baseRef.child('users');

let data = {
    users: []
};

var UsersStore = Reflux.createStore({

  listenables: Actions,

  init() {
  },

  watchUsers: function() {
    usersRef
    .orderByKey()
    .limitToLast(10)
    .on('value', this.updateUsers);
  },

  updateUsers(userDataObj){
    let endAt = 10;

    // add users to new array
    let newUsers = [];

    userDataObj.forEach(userData => {
      let user = userData.val();
      user.id = userData.key();
      newUsers.unshift(user);

      // increment id for next addition
      this.autoIncrementId(user.id);
    });

    // slice off extra user
    data.users = newUsers.slice(0, endAt);

    this.trigger(data);
  },

  stopWatchingUsers() {
    usersRef.off();
  },

  onRemoveUser(id){
    data.users.map(function(user, index){
      if(user.id === id){
        delete data.users[index];
      }
    });
    this.trigger(data);
  },

  onAddUser(user){
    user.id = this.getAutoIncrementedId();
    data.users.unshift(user);
    this.trigger(data);

    // auto increment user id
    this.autoIncrementId(user.id);
  },

  autoIncrementId(id){
    this.id_auto_inc += (id >= this.id_auto_inc) ? 1 : 0;
    return this.id_auto_inc;
  },

  getAutoIncrementedId(){
    return this.id_auto_inc;
  },

  getDefaultData() {
    return data;
  }
});

// static id auto incremented
UsersStore.id_auto_inc = 1;

export default UsersStore;
<commit_msg>remove slice, manage pagination later<commit_after>import Reflux from 'reflux';

import Firebase from 'firebase';
import Actions from '../actions/Actions';
import { firebaseUrl } from '../utils/constants';

let baseRef = new Firebase(firebaseUrl);
let usersRef = baseRef.child('users');

let data = {
    users: []
};

var UsersStore = Reflux.createStore({

  listenables: Actions,

  watchUsers: function() {
    usersRef
    .orderByKey()
    .on('value', this.updateUsers);
  },

  updateUsers(userDataObj){
    // add users to new array
    let newUsers = [];

    userDataObj.forEach(userData => {
      let user = userData.val();
      user.id = userData.key();
      newUsers.unshift(user);

      // increment id for next addition
      this.autoIncrementId(user.id);
    });

    data.users = newUsers

    this.trigger(data);
  },

  stopWatchingUsers() {
    usersRef.off();
  },

  onRemoveUser(id){
    data.users.map(function(user, index){
      if(user.id === id){
        delete data.users[index];
      }
    });
    this.trigger(data);
  },

  onAddUser(user){
    user.id = this.getAutoIncrementedId();
    data.users.unshift(user);
    this.trigger(data);

    // auto increment user id
    this.autoIncrementId(user.id);
  },

  autoIncrementId(id){
    this.id_auto_inc += (id >= this.id_auto_inc) ? 1 : 0;
    return this.id_auto_inc;
  },

  getAutoIncrementedId(){
    return this.id_auto_inc;
  },

  getDefaultData() {
    return data;
  }
});

// static auto incremented id
UsersStore.id_auto_inc = 1;

export default UsersStore;
<|endoftext|>


<commit_before>/* global self */
(function (global) {
  const toolbox = global.toolbox;

  /**
   * Cache first
   */

  // cloudflare cdn
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'cloudflare-cdn',
    },
    origin: /cdnjs\.cloudflare\.com$/
  });

  // gstatic cdn
  // - firebase scripts
  // - google fonts
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'gstatic-cdn',
    },
    origin: /\.gstatic\.com$/
  });

  // googleapis fonts cdn
  // - google fonts css
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'fonts-googleapis-cdn'
    },
    origin: /fonts\.googleapis\.com/
  });

  /**
   * Fastest
   */

  // worldofwarcraft character render
  toolbox.router.get(/character\/(.*?)\.jpg/, toolbox.fastest, {
    cache: {
      name: 'worldofwarcraft-render',
      maxEntries: 50,
      maxAgeSeconds: 86400
    },
    origin: /render-(?:tw|eu|us|kr)\.worldofwarcraft\.com/
  });

  // firebase storage character index
  toolbox.router.get(/index\.json/, toolbox.fastest, {
    origin: /firebasestorage\.googleapis\.com/
  });
}(self));
<commit_msg>update buttons.github.io sw config<commit_after>/* global self */
(function (global) {
  const toolbox = global.toolbox;

  /**
   * Cache first
   */

  // cloudflare cdn
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'cloudflare-cdn',
    },
    origin: /cdnjs\.cloudflare\.com$/
  });

  // gstatic cdn
  // - firebase scripts
  // - google fonts
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'gstatic-cdn',
    },
    origin: /\.gstatic\.com$/
  });

  // googleapis fonts cdn
  // - google fonts css
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'fonts-googleapis-cdn'
    },
    origin: /fonts\.googleapis\.com/
  });

  // github buttons cdn
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'github-buttons-cdn-600',
      maxAgeSeconds: 600
    },
    origin: /buttons\.github\.io/
  });

  /**
   * Fastest
   */

  // worldofwarcraft character render
  toolbox.router.get(/character\/(.*?)\.jpg/, toolbox.fastest, {
    cache: {
      name: 'worldofwarcraft-render',
      maxEntries: 50,
      maxAgeSeconds: 86400
    },
    origin: /render-(?:tw|eu|us|kr)\.worldofwarcraft\.com/
  });

  // firebase storage character index
  toolbox.router.get(/index\.json/, toolbox.fastest, {
    origin: /firebasestorage\.googleapis\.com/
  });
}(self));
<|endoftext|>


<commit_before>/*******************************************************************************
 * @license
 * Copyright (c) 2012 VMware, Inc. All Rights Reserved.
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Contributors:
 *     Kris De Volder - initial API and implementation
 ******************************************************************************/

/*global require exports __dirname console */

//To run this test do this on the commandline:

//1) install nodeunit:
// 'cd ~'
// 'npm install nodeunit'
//2) run the tests
// 'cd <this-directory>'
// 'nodeunit <this-filename>'

// Good read about unit testing in node.js:
//
// http://caolanmcmahon.com/posts/unit_testing_in_node_js

// A way to run in debug mode (not tried yet)?
// node --debug `which nodeunit` test/run.js

var toCompareString = require('../../server/jsdepend/utils').toCompareString;
var configuration = require('../../server/jsdepend/filesystem');

function makeApi(relativeBaseDir) {
	var baseDir = __dirname+'/test-resources/'+relativeBaseDir;
	var conf = configuration.withBaseDir(baseDir);
	var api = require('../../server/jsdepend/file-indexer').configure(conf);
	return api;
}

exports.scriptedFileAtRoot = function(test) {
	var api = makeApi('with-a-scripted-file');
	api.getIndexer('subdir/subsubdir/dummy.js', function (indexer) {
		test.equals(indexer.getRootDir(), '.');
		test.done();
	});
};

exports.scriptedFileInSubproject = function(test) {
	var api = makeApi('with-a-scripted-file');
	api.getIndexer('subproject/subdir/subsubdir/dummy.js', function (indexer) {
		test.equals(indexer.getRootDir(), 'subproject');
		test.done();
	});
};

exports.projectFileAtRoot = function(test) {
	var api = makeApi('with-a-project-file');
	api.getIndexer('subdir/subsubdir/dummy.js', function (indexer) {
		test.equals(indexer.getRootDir(), '.');
		test.done();
	});
};

exports.projectFileInSubproject = function(test) {
	var api = makeApi('with-a-project-file');
	api.getIndexer('subproject/subdir/subsubdir/dummy.js', function (indexer) {
		test.equals(indexer.getRootDir(), 'subproject');
		test.done();
	});
};

exports.noRootMarkerFile = function(test) {
	//The behavior for this case has changed a few times.
	//current expected behavior is that we use directory of the file itself as the root.
	var api = makeApi('no-root-marker-file');
	api.getIndexer('subdir/subsubdir/dummy.js',
		function (indexer) {
			test.equals(indexer.getRootDir(), 'subdir/subsubdir');
			test.done();
		},
		function (error) {
			throw 'should not be called';
		}
	);
};

exports.searchForNameContainsDum = function(test) {
	var api = makeApi('with-a-scripted-file');
	api.getIndexer('subdir/subsubdir/dummy.js', function (indexer) {
		indexer.findFileNamesContaining('dum', function (files) {
			//console.log(files);
			test.equals(files.length, 2);
			test.done();
		});
	});
};

exports.canFindScriptedFiles = function(test) {
	var api = makeApi('with-a-scripted-file');
	api.getIndexer('subdir/subsubdir/dummy.js', function (indexer) {
		indexer.findFileNamesContaining('.scripted', function (files) {
			//console.log(files);
			test.equals(files.length, 2);
			test.done();
		});
	});
};

exports.findFilesWithName = function (test) {
	var api = makeApi('with-a-scripted-file');
	api.getIndexer('subdir/subsubdir/dummy.js', function (indexer) {
		indexer.findFilesWithName('exact.js', function (files) {
			//console.log(files);
			test.equals(files.length, 2);
			test.done();
		});
	});
};
<commit_msg>Cleanup: trailing white space.<commit_after>/*******************************************************************************
 * @license
 * Copyright (c) 2012 VMware, Inc. All Rights Reserved.
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Contributors:
 *     Kris De Volder - initial API and implementation
 ******************************************************************************/

/*global require exports __dirname console */

//To run this test do this on the commandline:

//1) install nodeunit:
// 'cd ~'
// 'npm install nodeunit'
//2) run the tests
// 'cd <this-directory>'
// 'nodeunit <this-filename>'

// Good read about unit testing in node.js:
//
// http://caolanmcmahon.com/posts/unit_testing_in_node_js

// A way to run in debug mode (not tried yet)?
// node --debug `which nodeunit` test/run.js

var toCompareString = require('../../server/jsdepend/utils').toCompareString;
var configuration = require('../../server/jsdepend/filesystem');

function makeApi(relativeBaseDir) {
	var baseDir = __dirname+'/test-resources/'+relativeBaseDir;
	var conf = configuration.withBaseDir(baseDir);
	var api = require('../../server/jsdepend/file-indexer').configure(conf);
	return api;
}

exports.scriptedFileAtRoot = function(test) {
	var api = makeApi('with-a-scripted-file');
	api.getIndexer('subdir/subsubdir/dummy.js', function (indexer) {
		test.equals(indexer.getRootDir(), '.');
		test.done();
	});
};

exports.scriptedFileInSubproject = function(test) {
	var api = makeApi('with-a-scripted-file');
	api.getIndexer('subproject/subdir/subsubdir/dummy.js', function (indexer) {
		test.equals(indexer.getRootDir(), 'subproject');
		test.done();
	});
};

exports.projectFileAtRoot = function(test) {
	var api = makeApi('with-a-project-file');
	api.getIndexer('subdir/subsubdir/dummy.js', function (indexer) {
		test.equals(indexer.getRootDir(), '.');
		test.done();
	});
};

exports.projectFileInSubproject = function(test) {
	var api = makeApi('with-a-project-file');
	api.getIndexer('subproject/subdir/subsubdir/dummy.js', function (indexer) {
		test.equals(indexer.getRootDir(), 'subproject');
		test.done();
	});
};

exports.noRootMarkerFile = function(test) {
	//The behavior for this case has changed a few times.
	//current expected behavior is that we use directory of the file itself as the root.
	var api = makeApi('no-root-marker-file');
	api.getIndexer('subdir/subsubdir/dummy.js',
		function (indexer) {
			test.equals(indexer.getRootDir(), 'subdir/subsubdir');
			test.done();
		},
		function (error) {
			throw 'should not be called';
		}
	);
};

exports.searchForNameContainsDum = function(test) {
	var api = makeApi('with-a-scripted-file');
	api.getIndexer('subdir/subsubdir/dummy.js', function (indexer) {
		indexer.findFileNamesContaining('dum', function (files) {
			//console.log(files);
			test.equals(files.length, 2);
			test.done();
		});
	});
};

exports.canFindScriptedFiles = function(test) {
	var api = makeApi('with-a-scripted-file');
	api.getIndexer('subdir/subsubdir/dummy.js', function (indexer) {
		indexer.findFileNamesContaining('.scripted', function (files) {
			//console.log(files);
			test.equals(files.length, 2);
			test.done();
		});
	});
};

exports.findFilesWithName = function (test) {
	var api = makeApi('with-a-scripted-file');
	api.getIndexer('subdir/subsubdir/dummy.js', function (indexer) {
		indexer.findFilesWithName('exact.js', function (files) {
			//console.log(files);
			test.equals(files.length, 2);
			test.done();
		});
	});
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

Error.stackTraceLimit = 30;

exports.root = __dirname;

// Executed once all application were loaded.
// Used to "attach" hooks for models etc.
/* exports.init = function (N) {}; */

// disable orc at runtime to avoid segfaults,
// see https://github.com/lovell/sharp/issues/172#issuecomment-162800414
process.env.VIPS_NOVECTOR = 1;

if (!module.parent) {
  require('nodeca.core/lib/system/runner').bootstrap(exports);
}
<commit_msg>removed libvips kludge (not needed with sharp 0.12.1)<commit_after>#!/usr/bin/env node

'use strict';

Error.stackTraceLimit = 30;

exports.root = __dirname;

// Executed once all application were loaded.
// Used to "attach" hooks for models etc.
/* exports.init = function (N) {}; */

if (!module.parent) {
  require('nodeca.core/lib/system/runner').bootstrap(exports);
}
<|endoftext|>


<commit_before>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2012 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*  define a state transition  */
$cs.transition = function () {
    /*  special case  */
    if (arguments.length === 1 && arguments[0] === null) {
        /*  remove all user-defined transistions  */
        _cs.states_clear();
        return;
    }

    /*  determine parameters  */
    var params = $cs.params("transition", arguments, {
        target: { pos: 0,     def: null,  req: true },
        enter:  { pos: 1,     def: null,  req: true },
        leave:  { pos: 2,     def: null,  req: true },
        source: { pos: 3,     def: null             }
    });

    /*  add new state  */
    _cs.states_add(
        params.target,
        params.enter,
        params.leave,
        params.source
    );
};

/*  initialize state transition set with a reasonable default  */
$cs.transition("created",      "create",  "destroy"); /* created and attached to component tree */
$cs.transition("prepared",     "prepare", "cleanup"); /* prepared and ready for rendering */
$cs.transition("materialized", "render",  "release"); /* rendered onto the DOM tree */
$cs.transition("visible",      "show",    "hide"   ); /* visible to the user */
$cs.transition("enabled",      "enable",  "disable"); /* enabled and the user can operate on it */

<commit_msg>fix typo<commit_after>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2012 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*  define a state transition  */
$cs.transition = function () {
    /*  special case  */
    if (arguments.length === 1 && arguments[0] === null) {
        /*  remove all user-defined transitions  */
        _cs.states_clear();
        return;
    }

    /*  determine parameters  */
    var params = $cs.params("transition", arguments, {
        target: { pos: 0,     def: null,  req: true },
        enter:  { pos: 1,     def: null,  req: true },
        leave:  { pos: 2,     def: null,  req: true },
        source: { pos: 3,     def: null             }
    });

    /*  add new state  */
    _cs.states_add(
        params.target,
        params.enter,
        params.leave,
        params.source
    );
};

/*  initialize state transition set with a reasonable default  */
$cs.transition("created",      "create",  "destroy"); /* created and attached to component tree */
$cs.transition("prepared",     "prepare", "cleanup"); /* prepared and ready for rendering */
$cs.transition("materialized", "render",  "release"); /* rendered onto the DOM tree */
$cs.transition("visible",      "show",    "hide"   ); /* visible to the user */
$cs.transition("enabled",      "enable",  "disable"); /* enabled and the user can operate on it */

<|endoftext|>


<commit_before>/* eslint-disable react/no-danger */
import React, { PropTypes } from 'react';
import styled from 'styled-components';
import Vimeo from 'react-vimeo';

import { media } from '../../style/utils';

import Img from '../Img';

const Container = styled.article`
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100vh;
  padding: 2rem 0;
  background-color: #d8c0c0;

  &:nth-child(odd) { background-color: #dcddde; }

  ${media.large`
    flex-flow: row wrap;
  `}
`;

const GridItem = styled.div`
  width: 100%;
  padding: 1rem 2rem;
  font-family: Gill Sans, Lato, sans-serif;

  ${media.large`
    width: 50%;
    padding: 3rem;
    padding-left: 4rem;
    padding-right: 1.5rem;

    &:last-child {
      padding-left: 1.5rem;
      padding-right: 4rem;
    }
  `}
`;

const Title = styled.h1`
  margin-bottom: 0.5em;
  font-size: 2.2rem;
  letter-spacing: 0.03em;
  font-weight: 600;
`;

const Content = styled.div`
  font-size: 1rem;

  & p {
    margin-bottom: 1em;
  }

  & a {
    color: currentColor;
    text-decoration: none;
  }

  & a:hover {
    text-decoration: underline;
  }
`;

const ImgContainer = styled.div`
  padding: 0 2rem;
  text-align: center;

  ${media.large`
    padding: 0;
  `}

  & .vimeo {
    margin-left: -2rem;
  }

  & iframe {
    width: 300px;
    height: 300px;
  }
`;

export default function BlogPost({ item }) {
  return (
    <Container bg={item.background}>
      <GridItem>
        <ImgContainer>
          {item.video ?
            <Vimeo videoId={item.video} autoplay /> :

          }
        </ImgContainer>
      </GridItem>
      <GridItem>
        <Title>{item.title}</Title>
        <Content dangerouslySetInnerHTML={{ __html: item.html }} />
      </GridItem>
    </Container>
  );
}

BlogPost.propTypes = {
  item: PropTypes.shape({
    img: PropTypes.string,
    title: PropTypes.string.isRequired,
    html: PropTypes.string.isRequired,
    background: PropTypes.string,
  }).isRequired,
};
<commit_msg>Fix styling issue<commit_after>/* eslint-disable react/no-danger */
import React, { PropTypes } from 'react';
import styled from 'styled-components';
import Vimeo from 'react-vimeo';

import { media } from '../../style/utils';

import Img from '../Img';

const Container = styled.article`
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100vh;
  padding: 2rem 0;
  background-color: #d8c0c0;

  &:nth-child(odd) { background-color: #dcddde; }

  ${media.large`
    flex-flow: row wrap;
  `}
`;

const GridItem = styled.div`
  width: 100%;
  padding: 1rem 2rem;
  font-family: Gill Sans, Lato, sans-serif;

  ${media.large`
    width: 50%;
    padding: 3rem;
    padding-left: 4rem;
    padding-right: 1.5rem;

    &:last-child {
      padding-left: 1.5rem;
      padding-right: 4rem;
    }
  `}
`;

const Title = styled.h1`
  margin-bottom: 0.5em;
  font-size: 2.2rem;
  letter-spacing: 0.03em;
  font-weight: 600;
`;

const Content = styled.div`
  font-size: 1rem;

  & p {
    margin-bottom: 1em;
  }

  & a {
    color: currentColor;
    text-decoration: none;
  }

  & a:hover {
    text-decoration: underline;
  }
`;

const ImgContainer = styled.div`
  padding: 0 2rem;
  text-align: center;

  ${media.large`
    padding: 0;
  `}

  & .vimeo {
    margin-left: -2rem;
  }

  & iframe {
    width: 270px;
    height: 270px;
  }

  ${media.medium`
    & iframe {
      width: 450px;
      height: 450px;
    }
  `}
`;

export default function BlogPost({ item }) {
  return (
    <Container bg={item.background}>
      <GridItem>
        <ImgContainer>
          {item.video ?
            <Vimeo videoId={item.video} autoplay /> :

          }
        </ImgContainer>
      </GridItem>
      <GridItem>
        <Title>{item.title}</Title>
        <Content dangerouslySetInnerHTML={{ __html: item.html }} />
      </GridItem>
    </Container>
  );
}

BlogPost.propTypes = {
  item: PropTypes.shape({
    img: PropTypes.string,
    title: PropTypes.string.isRequired,
    html: PropTypes.string.isRequired,
    background: PropTypes.string,
  }).isRequired,
};
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import {connectToStores} from 'fluxible-addons-react';
import { Container, Divider,Header,Segment,Form,Label,Dropdown,Input,TextArea} from 'semantic-ui-react';
import UserProfileStore from '../../stores/UserProfileStore';
import ReCAPTCHA from 'react-google-recaptcha';
import {publicRecaptchaKey} from '../../configs/general';
import fetchUser from '../../actions/user/userprofile/fetchUser';
import {FormattedMessage, defineMessages} from 'react-intl';
import sendContactForm from '../../actions/home/sendContactForm';

class ContactUs extends React.Component {
    constructor(props){
        super(props);
        this.state ={
            type : '',
            firstName:this.props.UserProfileStore.user.fname,
            lastName:this.props.UserProfileStore.user.lname,
            email: this.props.UserProfileStore.user.email

        };
        this.messages = defineMessages({
            swal_title:{
                id: 'contactUs.swal_title',
                defaultMessage:'Contact Us'
            },
            checkType_text:{
                id: 'contactUs.checkType_text',
                defaultMessage:'Please, please select the type of feedback'
            },
            swal_button:{
                id: 'contactUs.swal_button',
                defaultMessage:'Ok'
            },
            checkEmail_text:{
                id: 'contactUs.checkEmail_text',
                defaultMessage:'Please, use a valid email address'
            },
            checkSummary_text:{
                id: 'contactUs.checkSummary_text',
                defaultMessage:'Please, provide us a summary of your issue'
            },
            checkCaptcha_text:{
                id: 'contactUs.checkCaptcha_text',
                defaultMessage:'Please, confirm you are not a bot',
            },
            typeOption_suggestion:{
                id: 'contactUs.typeOption_suggestion',
                defaultMessage: 'Suggestion'
            },
            typeOption_support:{
                id: 'contactUs.typeOption_support',
                defaultMessage: 'Support Issue'
            },
            typeOption_account:{
                id: 'contactUs.typeOption_account',
                defaultMessage: 'Account Issue'
            },
            typeOption_other:{
                id: 'contactUs.typeOption_other',
                defaultMessage: 'Other'
            },
            form_explanation:{
                id: 'contactUs.form_explanation',
                defaultMessage:'If you wish to contact us, please complete the form below. If you wish to report an issue with a particular deck, please use the Reporting button on the deck.'
            },
            form_subheader:{
                id: 'contactUs.form_subheader',
                defaultMessage:'Feedback'
            },
            form_type_label:{
                id: 'contactUs.form_type_label',
                defaultMessage:'Type of report*:'
            },
            form_type_placeholder:{
                id: 'contactUs.form_type_placeholder',
                defaultMessage:'Select type of report'
            },
            form_firstName_label:{
                id: 'contactUs.form_firstName_label',
                defaultMessage:'First Name:'
            },
            form_firstName_placeholder:{
                id: 'contactUs.form_firstName_placeholder',
                defaultMessage:'First name'
            },
            form_lastName_label:{
                id: 'contactUs.form_lastName_label',
                defaultMessage:'Last Name:'
            },
            form_lastName_placeholder:{
                id: 'contactUs.form_lastName_placeholder',
                defaultMessage:'Last name'
            },
            form_email_label:{
                id: 'contactUs.form_email_label',
                defaultMessage:'Email*:'
            },
            form_email_placeholder:{
                id: 'contactUs.form_email_placeholder',
                defaultMessage:'user@server.com'
            },
            form_summary_label:{
                id: 'contactUs.form_summary_label',
                defaultMessage:'Summary*:'
            },
            form_summary_placeholder:{
                id: 'contactUs.form_summary_placeholder',
                defaultMessage:'Please, write us a one-sentence summary'
            },
            form_description_label:{
                id: 'contactUs.form_description_label',
                defaultMessage:'Description:'
            },
            form_description_placeholder:{
                id: 'contactUs.form_description_placeholder',
                defaultMessage:'Please, give us more information about.'
            },
            form_button:{
                id: 'contactUs.form_button',
                defaultMessage:'Send Feedback'
            },
            send_swal_text:{
                id: 'contactUs.send_swal_text',
                defaultMessage:'Feedback sent. Thank you!'
            },
            send_swal_button:{
                id: 'contactUs.send_swal_button',
                defaultMessage:'Close'
            },
            send_swal_error_text: {
                id: 'contactUs.send_swal_error_text',
                defaultMessage:'An error occoured while contacting us. Please try again later.'
            },
            send_swal_error_button:{
                id: 'contactUs.send_swal_error_button',
                defaultMessage:'Close'
            }
        });
    }
    componentDidMount(){
      //Load user info, if user is conected.
        if(this.props.UserProfileStore.username.length > 0)
            this.context.executeAction(fetchUser,{ params: {username: this.props.UserProfileStore.username, id:this.props.UserProfileStore.userid}});
    }
    componentWillReceiveProps(nextProps){
        this.setState({
            firstName :nextProps.UserProfileStore.user.fname,
            lastName:nextProps.UserProfileStore.user.lname,
            email: nextProps.UserProfileStore.user.email
        });

    }

    onRecaptchaChange(response) {
        this.setState({
            'grecaptcharesponse': response
        });
    }
    /*Using react-semantic-ui Inputs, when we assign them an initial value,
    the only way they can become editable is handling the onChange method.
    If the user is not logged, they don't receive an initial value,
    but the problem is the same, so we need to change by hand the value.
    Now, only not logged users can edit name, surname and email. If we want to
    allow all users to edit, we need to remove the if condition in each change method*/
    onFirstNameChange(event,data){
        if(this.props.UserProfileStore.username.length === 0){
          //Not logged user, he can edit
            this.setState({
                firstName: data.value
            });
        }
    }
    onLastNameChange(event,data){
        if(this.props.UserProfileStore.username.length === 0){
          //Not logged user, he can edit
            this.setState({
                lastName: data.value
            });
        }
    }
    onEmailChange(event,data){
        if(this.props.UserProfileStore.username.length === 0){
          //Not logged user, he can edit
            this.setState({
                email: data.value
            });
        }
    }
    checkType(){
        let noTypeError = true;

        if (this.typeContact.state.value === '' ){
            noTypeError = false;
            swal({
                title: this.context.intl.formatMessage(this.messages.swal_title),
                text: this.context.intl.formatMessage(this.messages.checkType_text),
                type: 'error',
                confirmButtonText: this.context.intl.formatMessage(this.messages.swal_button),
                confirmButtonClass: 'ui olive button',
                allowEscapeKey: false,
                allowOutsideClick: false,
                buttonsStyling: false
            }).then((accepted) => {

                ReactDOM.findDOMNode(this.typeContact).focus();
            });
        }
        return noTypeError;

    }
    checkEmail(){
        let noEmailError = true;
        let regExp = /\S+@\S+\.\S+/;
        if (this.state.email === '' || !regExp.test(this.state.email)){
            noEmailError = false;
            swal({
                title: this.context.intl.formatMessage(this.messages.swal_title),
                text: this.context.intl.formatMessage(this.messages.checkEmail_text),
                type: 'error',
                confirmButtonText: this.context.intl.formatMessage(this.messages.swal_button),
                confirmButtonClass: 'ui olive button',
                allowEscapeKey: false,
                allowOutsideClick: false,
                buttonsStyling: false
            }).then((accepted) => {

                this.emailContact.focus();
            });
        }
        return noEmailError;

    }
    checkSummary(){
        let noSummaryError = true;

        if (this.summaryContact.inputRef.value === ''){
            noSummaryError = false;
            swal({
                title: this.context.intl.formatMessage(this.messages.swal_title),
                text: this.context.intl.formatMessage(this.messages.checkSummary_text),
                type: 'error',
                confirmButtonText: this.context.intl.formatMessage(this.messages.swal_button),
                confirmButtonClass: 'ui olive button',
                allowEscapeKey: false,
                allowOutsideClick: false,
                buttonsStyling: false
            }).then((accepted) => {

                this.summaryContact.focus();
            });
        }
        return noSummaryError;
    }
    checkCaptcha(){
    // REturns true if everything is ok
        let noCaptchaError = true;
        if(this.state.grecaptcharesponse === undefined){
            noCaptchaError = false;
            swal({
                title:this.context.intl.formatMessage(this.messages.swal_title),
                text: this.context.intl.formatMessage(this.messages.checkCaptcha_text),
                type: 'error',
                confirmButtonText: this.context.intl.formatMessage(this.messages.swal_button),
                confirmButtonClass: 'ui olive button',
                allowEscapeKey: false,
                allowOutsideClick: false,
                buttonsStyling: false
            }).then((accepted) => {
                //recaptcha-checkbox-checkmark
                ReactDOM.findDOMNode(this.recaptcha).focus();
                //$('#recaptchaGoogleContact').focus();
            });
        }
        return noCaptchaError;
    }
    checkForm(){
    //Checks if requiered fields are ok.
    // Returns true if all are ok
        if(this.checkType())
            if(this.checkEmail())
                if(this.checkSummary())
                    if(this.checkCaptcha())
                        return true;
        return false;
    }

    getSwalMessages(){
      //Get the messages which will show in the swal showed  when the form is sent
        return {
            title: this.context.intl.formatMessage(this.messages.swal_title),
            text: this.context.intl.formatMessage(this.messages.send_swal_text),
            confirmButtonText: this.context.intl.formatMessage(this.messages.send_swal_button),
            error_text: this.context.intl.formatMessage(this.messages.send_swal_error_text),
            error_confirmButtonText: this.context.intl.formatMessage(this.messages.send_swal_error_button)
        };
    }

    onSubmitHandler(event){
        //email, first name and last name are stored in the state
        event.preventDefault();
        if(this.checkForm()){
          //all data is ok. Send info
            let payload = {
                subject : this.summaryContact.inputRef.value,
                text : 'First Name: '+this.state.firstName +'\n'+
                       'Last Name: '+this.state.lastName +'\n'+
                       'email: '+this.state.email+'\n'+
                       'Feedback type: '+this.typeContact.state.value+'\n'+
                       'Summary: '+this.summaryContact.inputRef.value+'\n'+
                       'Description: '+this.descriptionContact.ref.value,
                swal_messages : this.getSwalMessages()
            };
            console.log(payload);
            this.context.executeAction(sendContactForm,payload);
        }
    }

    render() {
        const typeOptions = [
          {value:'Suggestion' , text:this.context.intl.formatMessage(this.messages.typeOption_suggestion)},
          {value:'Support' , text:this.context.intl.formatMessage(this.messages.typeOption_support)},
          {value:'Account' , text:this.context.intl.formatMessage(this.messages.typeOption_account)},
          {value:'Other' , text:this.context.intl.formatMessage(this.messages.typeOption_other)},

        ];
        const labelStyle = {
            width:20+'px'
        };

        const recaptchaStyle = {display: 'inline-block'};

        //Short way. It creates symple labels. If they don't like ribbons, we can change to this:
        //     <Form.Input id='NameContact' label='Name:' placeholder='Your name' />

        return (
            <Container text>
                <Divider hidden />

                {this.context.intl.formatMessage(this.messages.swal_title)}

{this.context.intl.formatMessage(this.messages.form_explanation)}

                  <Divider hidden />
                  <Segment attached="bottom" textAlign="left" >
                    {this.context.intl.formatMessage(this.messages.form_subheader)}
                    <Form onSubmit={this.onSubmitHandler.bind(this)}>
                      <Form.Field>

                       {this.context.intl.formatMessage(this.messages.form_type_label)}

                      <Dropdown selection openOnFocus id='typeContact' name='typeContact'
                       ref={(type) => {this.typeContact = type;}}
                       placeholder={this.context.intl.formatMessage(this.messages.form_type_placeholder)} options={typeOptions}
                       tabIndex="0" aria-required="true" />
                      </Form.Field>

                      <Form.Input type='text' id='firstNameContact' name="firstNameContact" ref={(input) => {this.firstNameContact = input;}}
                         label={this.context.intl.formatMessage(this.messages.form_firstName_label)}
                         placeholder= {this.context.intl.formatMessage(this.messages.form_firstName_placeholder)}
                         value={this.state.firstName}
                         onChange ={this.onFirstNameChange.bind(this)}
                      />

                      <Form.Input type='text' id='lastNameContact' name="lastNameContact" ref={(input) => {this.lastNameContact = input;}}
                         label={this.context.intl.formatMessage(this.messages.form_lastName_label)}
                         placeholder={this.context.intl.formatMessage(this.messages.form_lastName_placeholder)}
                         value={this.state.lastName}
                         onChange ={this.onLastNameChange.bind(this)}/>

                      <Form.Input type='email' id='emailContact' name="emailContact" ref={(input) => {this.emailContact = input;}}
                         label={this.context.intl.formatMessage(this.messages.form_email_label)}
                         placeholder={this.context.intl.formatMessage(this.messages.form_email_placeholder)}
                         aria-required="true" value={this.state.email}
                         onChange ={this.onEmailChange.bind(this)}/>

                      <Form.Input type='text' id='summaryContact' name="summaryContact" ref={(input) => {this.summaryContact = input;}}
                        label={this.context.intl.formatMessage(this.messages.form_summary_label)}
                        placeholder={this.context.intl.formatMessage(this.messages.form_summary_placeholder)}
                        aria-required="true"  />

                      <Form.Field>

                         {this.context.intl.formatMessage(this.messages.form_description_label)}

                         <TextArea id='descriptionContact' name="descriptionContact" ref={(input) => {this.descriptionContact = input;}}
                          autoHeight
                          placeholder= {this.context.intl.formatMessage(this.messages.form_description_placeholder)} />
                      </Form.Field>
                      <Form.Field>
                        <input type="hidden" id="recaptchaContact" name="recaptchaContact"></input>
                        <ReCAPTCHA id="recaptchaGoogleContact" ref= {(recap) => {this.recaptcha = recap;}}
                         style={recaptchaStyle} sitekey={publicRecaptchaKey}
                         onChange={this.onRecaptchaChange.bind(this)}
                         aria-required="true" tabIndex="0"/>
                      </Form.Field>
                      <Form.Button color='blue'>
                        {this.context.intl.formatMessage(this.messages.form_button)}
                      </Form.Button>
                   </Form>
                   </Segment>

            </Container>

        );
    }
}

ContactUs.contextTypes = {
    executeAction: React.PropTypes.func.isRequired,
    intl: React.PropTypes.object.isRequired
};

ContactUs = connectToStores(ContactUs,[UserProfileStore],(context,props) => {
    return {
        UserProfileStore: context.getStore(UserProfileStore).getState()
    };
});

export default ContactUs;
<commit_msg>SWIK-1542 alternative to the dropdown<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import {connectToStores} from 'fluxible-addons-react';
import { Container, Divider,Header,Segment,Form,Label,Dropdown,Input,TextArea} from 'semantic-ui-react';
import UserProfileStore from '../../stores/UserProfileStore';
import ReCAPTCHA from 'react-google-recaptcha';
import {publicRecaptchaKey} from '../../configs/general';
import fetchUser from '../../actions/user/userprofile/fetchUser';
import {FormattedMessage, defineMessages} from 'react-intl';
import sendContactForm from '../../actions/home/sendContactForm';

class ContactUs extends React.Component {
    constructor(props){
        super(props);
        this.state ={
            type : '',
            firstName:this.props.UserProfileStore.user.fname,
            lastName:this.props.UserProfileStore.user.lname,
            email: this.props.UserProfileStore.user.email

        };
        this.messages = defineMessages({
            swal_title:{
                id: 'contactUs.swal_title',
                defaultMessage:'Contact Us'
            },
            checkType_text:{
                id: 'contactUs.checkType_text',
                defaultMessage:'Please, please select the type of feedback'
            },
            swal_button:{
                id: 'contactUs.swal_button',
                defaultMessage:'Ok'
            },
            checkEmail_text:{
                id: 'contactUs.checkEmail_text',
                defaultMessage:'Please, use a valid email address'
            },
            checkSummary_text:{
                id: 'contactUs.checkSummary_text',
                defaultMessage:'Please, provide us a summary of your issue'
            },
            checkCaptcha_text:{
                id: 'contactUs.checkCaptcha_text',
                defaultMessage:'Please, confirm you are not a bot',
            },
            typeOption_suggestion:{
                id: 'contactUs.typeOption_suggestion',
                defaultMessage: 'Suggestion'
            },
            typeOption_support:{
                id: 'contactUs.typeOption_support',
                defaultMessage: 'Support Issue'
            },
            typeOption_account:{
                id: 'contactUs.typeOption_account',
                defaultMessage: 'Account Issue'
            },
            typeOption_other:{
                id: 'contactUs.typeOption_other',
                defaultMessage: 'Other'
            },
            form_explanation:{
                id: 'contactUs.form_explanation',
                defaultMessage:'If you wish to contact us, please complete the form below. If you wish to report an issue with a particular deck, please use the Reporting button on the deck.'
            },
            form_subheader:{
                id: 'contactUs.form_subheader',
                defaultMessage:'Feedback'
            },
            form_type_label:{
                id: 'contactUs.form_type_label',
                defaultMessage:'Type of report*:'
            },
            form_type_placeholder:{
                id: 'contactUs.form_type_placeholder',
                defaultMessage:'Select type of report'
            },
            form_firstName_label:{
                id: 'contactUs.form_firstName_label',
                defaultMessage:'First Name:'
            },
            form_firstName_placeholder:{
                id: 'contactUs.form_firstName_placeholder',
                defaultMessage:'First name'
            },
            form_lastName_label:{
                id: 'contactUs.form_lastName_label',
                defaultMessage:'Last Name:'
            },
            form_lastName_placeholder:{
                id: 'contactUs.form_lastName_placeholder',
                defaultMessage:'Last name'
            },
            form_email_label:{
                id: 'contactUs.form_email_label',
                defaultMessage:'Email*:'
            },
            form_email_placeholder:{
                id: 'contactUs.form_email_placeholder',
                defaultMessage:'user@server.com'
            },
            form_summary_label:{
                id: 'contactUs.form_summary_label',
                defaultMessage:'Summary*:'
            },
            form_summary_placeholder:{
                id: 'contactUs.form_summary_placeholder',
                defaultMessage:'Please, write us a one-sentence summary'
            },
            form_description_label:{
                id: 'contactUs.form_description_label',
                defaultMessage:'Description:'
            },
            form_description_placeholder:{
                id: 'contactUs.form_description_placeholder',
                defaultMessage:'Please, give us more information about.'
            },
            form_button:{
                id: 'contactUs.form_button',
                defaultMessage:'Send Feedback'
            },
            send_swal_text:{
                id: 'contactUs.send_swal_text',
                defaultMessage:'Feedback sent. Thank you!'
            },
            send_swal_button:{
                id: 'contactUs.send_swal_button',
                defaultMessage:'Close'
            },
            send_swal_error_text: {
                id: 'contactUs.send_swal_error_text',
                defaultMessage:'An error occoured while contacting us. Please try again later.'
            },
            send_swal_error_button:{
                id: 'contactUs.send_swal_error_button',
                defaultMessage:'Close'
            }
        });
    }
    componentDidMount(){
      //Load user info, if user is conected.
        if(this.props.UserProfileStore.username.length > 0)
            this.context.executeAction(fetchUser,{ params: {username: this.props.UserProfileStore.username, id:this.props.UserProfileStore.userid}});
    }
    componentWillReceiveProps(nextProps){
        this.setState({
            firstName :nextProps.UserProfileStore.user.fname,
            lastName:nextProps.UserProfileStore.user.lname,
            email: nextProps.UserProfileStore.user.email
        });

    }

    onRecaptchaChange(response) {
        this.setState({
            'grecaptcharesponse': response
        });
    }
    /*Using react-semantic-ui Inputs, when we assign them an initial value,
    the only way they can become editable is handling the onChange method.
    If the user is not logged, they don't receive an initial value,
    but the problem is the same, so we need to change by hand the value.
    Now, only not logged users can edit name, surname and email. If we want to
    allow all users to edit, we need to remove the if condition in each change method*/
    onFirstNameChange(event,data){
        if(this.props.UserProfileStore.username.length === 0){
          //Not logged user, he can edit
            this.setState({
                firstName: data.value
            });
        }
    }
    onLastNameChange(event,data){
        if(this.props.UserProfileStore.username.length === 0){
          //Not logged user, he can edit
            this.setState({
                lastName: data.value
            });
        }
    }
    onEmailChange(event,data){
        if(this.props.UserProfileStore.username.length === 0){
          //Not logged user, he can edit
            this.setState({
                email: data.value
            });
        }
    }
    checkType(){
        let noTypeError = true;

        if (this.typeContact.state.value === '' ){
            noTypeError = false;
            swal({
                title: this.context.intl.formatMessage(this.messages.swal_title),
                text: this.context.intl.formatMessage(this.messages.checkType_text),
                type: 'error',
                confirmButtonText: this.context.intl.formatMessage(this.messages.swal_button),
                confirmButtonClass: 'ui olive button',
                allowEscapeKey: false,
                allowOutsideClick: false,
                buttonsStyling: false
            }).then((accepted) => {

                ReactDOM.findDOMNode(this.typeContact).focus();
            });
        }
        return noTypeError;

    }
    checkEmail(){
        let noEmailError = true;
        let regExp = /\S+@\S+\.\S+/;
        if (this.state.email === '' || !regExp.test(this.state.email)){
            noEmailError = false;
            swal({
                title: this.context.intl.formatMessage(this.messages.swal_title),
                text: this.context.intl.formatMessage(this.messages.checkEmail_text),
                type: 'error',
                confirmButtonText: this.context.intl.formatMessage(this.messages.swal_button),
                confirmButtonClass: 'ui olive button',
                allowEscapeKey: false,
                allowOutsideClick: false,
                buttonsStyling: false
            }).then((accepted) => {

                this.emailContact.focus();
            });
        }
        return noEmailError;

    }
    checkSummary(){
        let noSummaryError = true;

        if (this.summaryContact.inputRef.value === ''){
            noSummaryError = false;
            swal({
                title: this.context.intl.formatMessage(this.messages.swal_title),
                text: this.context.intl.formatMessage(this.messages.checkSummary_text),
                type: 'error',
                confirmButtonText: this.context.intl.formatMessage(this.messages.swal_button),
                confirmButtonClass: 'ui olive button',
                allowEscapeKey: false,
                allowOutsideClick: false,
                buttonsStyling: false
            }).then((accepted) => {

                this.summaryContact.focus();
            });
        }
        return noSummaryError;
    }
    checkCaptcha(){
    // REturns true if everything is ok
        let noCaptchaError = true;
        if(this.state.grecaptcharesponse === undefined){
            noCaptchaError = false;
            swal({
                title:this.context.intl.formatMessage(this.messages.swal_title),
                text: this.context.intl.formatMessage(this.messages.checkCaptcha_text),
                type: 'error',
                confirmButtonText: this.context.intl.formatMessage(this.messages.swal_button),
                confirmButtonClass: 'ui olive button',
                allowEscapeKey: false,
                allowOutsideClick: false,
                buttonsStyling: false
            }).then((accepted) => {
                //recaptcha-checkbox-checkmark
                ReactDOM.findDOMNode(this.recaptcha).focus();
                //$('#recaptchaGoogleContact').focus();
            });
        }
        return noCaptchaError;
    }
    checkForm(){
    //Checks if requiered fields are ok.
    // Returns true if all are ok
        if(this.checkType())
            if(this.checkEmail())
                if(this.checkSummary())
                    if(this.checkCaptcha())
                        return true;
        return false;
    }

    getSwalMessages(){
      //Get the messages which will show in the swal showed  when the form is sent
        return {
            title: this.context.intl.formatMessage(this.messages.swal_title),
            text: this.context.intl.formatMessage(this.messages.send_swal_text),
            confirmButtonText: this.context.intl.formatMessage(this.messages.send_swal_button),
            error_text: this.context.intl.formatMessage(this.messages.send_swal_error_text),
            error_confirmButtonText: this.context.intl.formatMessage(this.messages.send_swal_error_button)
        };
    }

    onSubmitHandler(event){
        //email, first name and last name are stored in the state
        event.preventDefault();
        if(this.checkForm()){
          //all data is ok. Send info
            let payload = {
                subject : this.summaryContact.inputRef.value,
                text : 'First Name: '+this.state.firstName +'\n'+
                       'Last Name: '+this.state.lastName +'\n'+
                       'email: '+this.state.email+'\n'+
                       'Feedback type: '+this.typeContact.state.value+'\n'+
                       'Summary: '+this.summaryContact.inputRef.value+'\n'+
                       'Description: '+this.descriptionContact.ref.value,
                swal_messages : this.getSwalMessages()
            };
            console.log(payload);
            this.context.executeAction(sendContactForm,payload);
        }
    }

    render() {
        const typeOptions = [
          {value:'Suggestion' , text:this.context.intl.formatMessage(this.messages.typeOption_suggestion)},
          {value:'Support' , text:this.context.intl.formatMessage(this.messages.typeOption_support)},
          {value:'Account' , text:this.context.intl.formatMessage(this.messages.typeOption_account)},
          {value:'Other' , text:this.context.intl.formatMessage(this.messages.typeOption_other)},

        ];
        const labelStyle = {
            width:20+'px'
        };

        const recaptchaStyle = {display: 'inline-block'};

        //Short way. It creates symple labels. If they don't like ribbons, we can change to this:
        //     <Form.Input id='NameContact' label='Name:' placeholder='Your name' />
        /*
        <Form.Input list='typeOptions' id='typeContact2'
          label= {this.context.intl.formatMessage(this.messages.form_type_label)}
          placeholder={this.context.intl.formatMessage(this.messages.form_type_placeholder)} />
          <datalist id='typeOptions'>
            <option value={this.context.intl.formatMessage(this.messages.typeOption_suggestion)} />
            <option value={this.context.intl.formatMessage(this.messages.typeOption_support)} />
            <option value={this.context.intl.formatMessage(this.messages.typeOption_account)} />
            <option value={this.context.intl.formatMessage(this.messages.typeOption_other)} />
          </datalist>
          */

        return (
            <Container text>
                <Divider hidden />

                {this.context.intl.formatMessage(this.messages.swal_title)}

{this.context.intl.formatMessage(this.messages.form_explanation)}

                  <Divider hidden />
                  <Segment attached="bottom" textAlign="left" >
                    {this.context.intl.formatMessage(this.messages.form_subheader)}
                    <Form onSubmit={this.onSubmitHandler.bind(this)}>
                      <Form.Field>

                       {this.context.intl.formatMessage(this.messages.form_type_label)}

                      <Dropdown selection openOnFocus id='typeContact' name='typeContact'
                       ref={(type) => {this.typeContact = type;}}
                       placeholder={this.context.intl.formatMessage(this.messages.form_type_placeholder)} options={typeOptions}
                       tabIndex="0" aria-required="true" />
                      </Form.Field>

                      <Form.Field>

                        {this.context.intl.formatMessage(this.messages.form_type_label)}

                        <Input list='typeOptions' id='typeContact2'
                          placeholder={this.context.intl.formatMessage(this.messages.form_type_placeholder)} />
                          <datalist id='typeOptions'>
                            <option value={this.context.intl.formatMessage(this.messages.typeOption_suggestion)} />
                            <option value={this.context.intl.formatMessage(this.messages.typeOption_support)} />
                            <option value={this.context.intl.formatMessage(this.messages.typeOption_account)} />
                            <option value={this.context.intl.formatMessage(this.messages.typeOption_other)} />
                          </datalist>
                      </Form.Field>

                      <Form.Input type='text' id='firstNameContact' name="firstNameContact" ref={(input) => {this.firstNameContact = input;}}
                         label={this.context.intl.formatMessage(this.messages.form_firstName_label)}
                         placeholder= {this.context.intl.formatMessage(this.messages.form_firstName_placeholder)}
                         value={this.state.firstName}
                         onChange ={this.onFirstNameChange.bind(this)}
                      />

                      <Form.Input type='text' id='lastNameContact' name="lastNameContact" ref={(input) => {this.lastNameContact = input;}}
                         label={this.context.intl.formatMessage(this.messages.form_lastName_label)}
                         placeholder={this.context.intl.formatMessage(this.messages.form_lastName_placeholder)}
                         value={this.state.lastName}
                         onChange ={this.onLastNameChange.bind(this)}/>

                      <Form.Input type='email' id='emailContact' name="emailContact" ref={(input) => {this.emailContact = input;}}
                         label={this.context.intl.formatMessage(this.messages.form_email_label)}
                         placeholder={this.context.intl.formatMessage(this.messages.form_email_placeholder)}
                         aria-required="true" value={this.state.email}
                         onChange ={this.onEmailChange.bind(this)}/>

                      <Form.Input type='text' id='summaryContact' name="summaryContact" ref={(input) => {this.summaryContact = input;}}
                        label={this.context.intl.formatMessage(this.messages.form_summary_label)}
                        placeholder={this.context.intl.formatMessage(this.messages.form_summary_placeholder)}
                        aria-required="true"  />

                      <Form.Field>

                         {this.context.intl.formatMessage(this.messages.form_description_label)}

                         <TextArea id='descriptionContact' name="descriptionContact" ref={(input) => {this.descriptionContact = input;}}
                          autoHeight
                          placeholder= {this.context.intl.formatMessage(this.messages.form_description_placeholder)} />
                      </Form.Field>
                      <Form.Field>
                        <input type="hidden" id="recaptchaContact" name="recaptchaContact"></input>
                        <ReCAPTCHA id="recaptchaGoogleContact" ref= {(recap) => {this.recaptcha = recap;}}
                         style={recaptchaStyle} sitekey={publicRecaptchaKey}
                         onChange={this.onRecaptchaChange.bind(this)}
                         aria-required="true" tabIndex="0"/>
                      </Form.Field>
                      <Form.Button color='blue'>
                        {this.context.intl.formatMessage(this.messages.form_button)}
                      </Form.Button>
                   </Form>
                   </Segment>

            </Container>

        );
    }
}

ContactUs.contextTypes = {
    executeAction: React.PropTypes.func.isRequired,
    intl: React.PropTypes.object.isRequired
};

ContactUs = connectToStores(ContactUs,[UserProfileStore],(context,props) => {
    return {
        UserProfileStore: context.getStore(UserProfileStore).getState()
    };
});

export default ContactUs;
<|endoftext|>


<commit_before>import React from 'react'

import SectionLayout from '../SectionLayout'
import { InlineLink } from '../Link'
import CodeBlock from '../CodeBlock'
import Code from '../Code'

const theme = (`
// theme.ts
export default interface ThemeInterface {
  primaryColor: string;
  primaryColorInverted: string;
}
`).trim()

const styledComponents = (`
// styled-components.ts
import * as styledComponents from 'styled-components';
import { ThemedStyledComponentsModule } from 'styled-components';

import ThemeInterface from './theme';

const {
    default: styled,
    css,
    injectGlobal,
    keyframes,
    ThemeProvider
} = styledComponents as ThemedStyledComponentsModule<ThemeInterface>;

export { css, injectGlobal, keyframes, ThemeProvider };
export default styled;
`).trim()

const propsClassName = (`
interface LogoProps {
  /* This prop is optional, since TypeScript won't know that it's passed by the wrapper */
  className?: string;
}

class Logo extends React.Component<LogoProps, {}> {
  render() {
    return (

        Logo

    );
  }
}

const LogoStyled = styled(Logo)\`
  font-family: 'Helvetica';
  font-weight: bold;
  font-size: 1.8rem;
\`;
`).trim()

const statelessComponent = (`
interface BoxProps {
  theme?: ThemeInterface;
  borders?: boolean;
  className?: string;
}

const Box: React.StatelessComponent<BoxProps> = props => (

    {props.children}

);

const StyledBox = styled(Box)\`
  padding: \${props => props.theme.lateralPadding};
\`;
`).trim()

const TypeScript = () => (
  <SectionLayout title="TypeScript">

      Styled Components has TypeScript definitions to allow the library to be used in any TypeScript project.

      {'A basic example can be found '}
      <InlineLink href="https://github.com/patrick91/Styled-Components-Typescript-Example">
        here
      </InlineLink>
      .

    <SectionLayout sub title="Define a theme interface">

        By default every styled component will have the theme prop set to any.
        When building complex apps it would be better to have autocomplete and error checks everywhere.

        To have autocomplete and checks around the theme prop we should first define the theme
        interface we would like to use throught our app:

      <CodeBlock code={theme} />

        Then we can re-export the styled function with our custom theme interface:

      <CodeBlock code={styledComponents} />

        Finally, instead of importing the styled functions from the styled-components module,
        we import it from our above, custom module.

    </SectionLayout>

    <SectionLayout sub title={[ 'Caveat with ', className ]}>

        When defining a component you will need to mark className as optional
        in your Props interface:

      <CodeBlock code={propsClassName} />
    </SectionLayout>

    <SectionLayout sub title="Caveat with Stateless Components">

        To use stateless components and have typechecking for the props you'll need to define
        the component alongside with its type, like this:

      <CodeBlock code={statelessComponent} />
    </SectionLayout>
  </SectionLayout>
)

export default TypeScript
<commit_msg>s/throught/throughout<commit_after>import React from 'react'
import SectionLayout from '../SectionLayout'
import { InlineLink } from '../Link'
import CodeBlock from '../CodeBlock'
import Code from '../Code'

const theme = (`
// theme.ts
export default interface ThemeInterface {
  primaryColor: string;
  primaryColorInverted: string;
}
`).trim()

const styledComponents = (`
// styled-components.ts
import * as styledComponents from 'styled-components';
import { ThemedStyledComponentsModule } from 'styled-components';

import ThemeInterface from './theme';

const {
    default: styled,
    css,
    injectGlobal,
    keyframes,
    ThemeProvider
} = styledComponents as ThemedStyledComponentsModule<ThemeInterface>;

export { css, injectGlobal, keyframes, ThemeProvider };
export default styled;
`).trim()

const propsClassName = (`
interface LogoProps {
  /* This prop is optional, since TypeScript won't know that it's passed by the wrapper */
  className?: string;
}

class Logo extends React.Component<LogoProps, {}> {
  render() {
    return (

        Logo

    );
  }
}

const LogoStyled = styled(Logo)\`
  font-family: 'Helvetica';
  font-weight: bold;
  font-size: 1.8rem;
\`;
`).trim()

const statelessComponent = (`
interface BoxProps {
  theme?: ThemeInterface;
  borders?: boolean;
  className?: string;
}

const Box: React.StatelessComponent<BoxProps> = props => (

    {props.children}

);

const StyledBox = styled(Box)\`
  padding: \${props => props.theme.lateralPadding};
\`;
`).trim()

const TypeScript = () => (
  <SectionLayout title="TypeScript">

      Styled Components has TypeScript definitions to allow the library to be used in any TypeScript project.

      {'A basic example can be found '}
      <InlineLink href="https://github.com/patrick91/Styled-Components-Typescript-Example">
        here
      </InlineLink>
      .

    <SectionLayout sub title="Define a theme interface">

        By default every styled component will have the theme prop set to any.
        When building complex apps it would be better to have autocomplete and error checks everywhere.

        To have autocomplete and checks around the theme prop we should first define the theme
        interface we would like to use throughout our app:

      <CodeBlock code={theme} />

        Then we can re-export the styled function with our custom theme interface:

      <CodeBlock code={styledComponents} />

        Finally, instead of importing the styled functions from the styled-components module,
        we import it from our above, custom module.

    </SectionLayout>

    <SectionLayout sub title={[ 'Caveat with ', className ]}>

        When defining a component you will need to mark className as optional
        in your Props interface:

      <CodeBlock code={propsClassName} />
    </SectionLayout>

    <SectionLayout sub title="Caveat with Stateless Components">

        To use stateless components and have typechecking for the props you'll need to define
        the component alongside with its type, like this:

      <CodeBlock code={statelessComponent} />
    </SectionLayout>
  </SectionLayout>
)

export default TypeScript
<|endoftext|>


<commit_before>const _ = require('lodash');

const ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]

function findMe(gameState) {
    return _.find(gameState.players, player => player.name == 'Texas Nodem');
}

function isPair(cards) {
    return cards[0].rank == cards[1].rank;
}

function sameColor(cards) {
    return cards[0].suit == cards[1].suit;
}

function isNeighbors(cards) {
    const index0 = ranks.indexOf(cards[0].rank);
    const index1 = ranks.indexOf(cards[1].rank);
    return Math.abs(index0 - index1);
}

function isAcePair(cards) {
    return isPair(cards) && cards[0].rank == "A";
}

function onlyFigures(cards) {
    return _.every(cards, card => ranks.indexOf(card.rank) > 7);
}

function allCards(gameState) {
    const myCards = findMe(gameState).hole_cards;
    return gameState.community_cards.concat(myCards);
}

function isFlush(cards) {
    let hash = {};
    cards.forEach(card => {
        if (hash[card.suit]) hash[card.suit]++;
        else hash[card.suit] = 1;
    });
    for (let suit in hash) {
        if (hash[suit] >= 5) return true;
    }
    return false;
}

function makeBet(gameState, bet) {
    const me = findMe(gameState);
    console.log("ME", me);

    const cards = me.hole_cards;
    const playerCount = gameState.players.length;

    console.log("--- VARIABLES ---");

    if (onlyFigures(cards)) console.log("round ", gameState.round, " : ", "onlyFigures");
    if (isPair(cards)) console.log("round ", gameState.round, " : ", "isPair");
    if (sameColor(cards)) console.log("round ", gameState.round, " : ", "sameColor");
    if (isNeighbors(cards)) console.log("round ", gameState.round, " : ", "isNeighbors");
    if (isAcePair(cards)) console.log("round ", gameState.round, " : ", "isAcePair");
    console.log("round ", gameState.round, " : ", "playerCount", playerCount);

    console.log("--- DECIDE ---");

    const danger = true;

    if (danger && gameState.minimum_raise > 20 && gameState.minimum_raise < 250) {
        console.log("round ", gameState.round, " : ", "ALL in due to minimum_raise", gameState.minimum_raise);
        return bet(5000);
    }

    if ((sameColor(cards) && onlyFigures(cards)) || isPair(cards)) {
        console.log("round ", gameState.round, " : ", "ALL in");
        return bet(5000);
    }

    if (sameColor(cards) && isNeighbors(cards)) {
        if (playerCount <= 3 || isAcePair(cards)) {
            console.log("round ", gameState.round, " : ", "ALL in");
            return bet(5000);
        }
    }

    if (gameState.minimum_raise <= 20) {
        console.log("round ", gameState.round, " : ", "20 to minimum_raise", gameState.minimum_raise);
        return bet(gameState.current_buy_in);
    }

    console.log("round ", gameState.round, " : ", "NOT good");
    return bet(0);
}

module.exports = {
    makeBet,
    isFlush,
    allCards,
    onlyFigures,
    isAcePair,
    isNeighbors,
    sameColor,
    isPair,
    findMe
};<commit_msg>Danger<commit_after>const _ = require('lodash');

const ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]

function findMe(gameState) {
    return _.find(gameState.players, player => player.name == 'Texas Nodem');
}

function isPair(cards) {
    return cards[0].rank == cards[1].rank;
}

function sameColor(cards) {
    return cards[0].suit == cards[1].suit;
}

function isNeighbors(cards) {
    const index0 = ranks.indexOf(cards[0].rank);
    const index1 = ranks.indexOf(cards[1].rank);
    return Math.abs(index0 - index1);
}

function isAcePair(cards) {
    return isPair(cards) && cards[0].rank == "A";
}

function onlyFigures(cards) {
    return _.every(cards, card => ranks.indexOf(card.rank) > 7);
}

function allCards(gameState) {
    const myCards = findMe(gameState).hole_cards;
    return gameState.community_cards.concat(myCards);
}

function isFlush(cards) {
    let hash = {};
    cards.forEach(card => {
        if (hash[card.suit]) hash[card.suit]++;
        else hash[card.suit] = 1;
    });
    for (let suit in hash) {
        if (hash[suit] >= 5) return true;
    }
    return false;
}

function makeBet(gameState, bet) {
    const me = findMe(gameState);
    console.log("ME", me);

    const cards = me.hole_cards;
    const playerCount = gameState.players.length;

    console.log("--- VARIABLES ---");

    if (onlyFigures(cards)) console.log("round ", gameState.round, " : ", "onlyFigures");
    if (isPair(cards)) console.log("round ", gameState.round, " : ", "isPair");
    if (sameColor(cards)) console.log("round ", gameState.round, " : ", "sameColor");
    if (isNeighbors(cards)) console.log("round ", gameState.round, " : ", "isNeighbors");
    if (isAcePair(cards)) console.log("round ", gameState.round, " : ", "isAcePair");
    console.log("round ", gameState.round, " : ", "playerCount", playerCount);

    console.log("--- DECIDE ---");

    const danger = false;

    if (danger && gameState.minimum_raise > 20 && gameState.minimum_raise < 250) {
        console.log("round ", gameState.round, " : ", "ALL in due to minimum_raise", gameState.minimum_raise);
        return bet(5000);
    }

    if ((sameColor(cards) && onlyFigures(cards)) || isPair(cards)) {
        console.log("round ", gameState.round, " : ", "ALL in");
        return bet(5000);
    }

    if (sameColor(cards) && isNeighbors(cards)) {
        if (playerCount <= 3 || isAcePair(cards)) {
            console.log("round ", gameState.round, " : ", "ALL in");
            return bet(5000);
        }
    }

    if (gameState.minimum_raise <= 20) {
        console.log("round ", gameState.round, " : ", "20 to minimum_raise", gameState.minimum_raise);
        return bet(gameState.current_buy_in);
    }

    console.log("round ", gameState.round, " : ", "NOT good");
    return bet(0);
}

module.exports = {
    makeBet,
    isFlush,
    allCards,
    onlyFigures,
    isAcePair,
    isNeighbors,
    sameColor,
    isPair,
    findMe
};<|endoftext|>