<commit_before>'use strict';

if (!/^(1|true)$/i.test(process.env.TEST_SQLITE || '1')) { return; }

var _ = require('lodash');
var expect = require('chai').expect;
var Database = require('../../../lib/db/database');
var BluebirdPromise = require('bluebird');

var shared = require('./shared_behaviors');
var returning = require('../../../lib/db/adapters/mixins/returning');
var PseudoReturn = returning.PseudoReturn;

var db, connection = {
  adapter: 'sqlite3',
  filename: ''
};

var resetSequence = BluebirdPromise.method(function(/*table*/) {
  // no need to reset
});

describe('SQLite3', function() {
  before(function() { db = this.db = Database.create(connection); });
  before(function() { this.resetSequence = resetSequence; });
  after(function(done) { db.disconnect().then(done, done); });

  it('executes raw sql', function(done) {
    var returnId = PseudoReturn.create('id');
    var queries = [
      ['CREATE TABLE azul_raw_sql_test ' +
       '(id integer primary key autoincrement, name varchar(255))'],
      ['INSERT INTO azul_raw_sql_test (name) VALUES (\'Azul\')', [returnId]],
      ['SELECT * FROM azul_raw_sql_test'],
      ['DROP TABLE azul_raw_sql_test']
    ];
    BluebirdPromise.reduce(queries, function(array, info) {
      var query = info[0], args = info[1] || [];
      return db._adapter.execute(query, args).then(function(result) {
        return array.concat([result]);
      });
    }, [])
    .spread(function(result1, result2, result3, result4) {
      expect(result1).to.eql({ rows: [], fields: [] });
      expect(result2).to.eql({
        rows: [{ id: 1 }], fields: ['id'] });
      expect(result3).to.eql({
        rows: [{ id: 1, name: 'Azul' }],
        fields: ['id', 'name'] });
      expect(result4).to.eql({ rows: [], fields: [] });
    })
    .done(done, done);
  });

  it('receives rows from raw sql', function(done) {
    var query = 'SELECT CAST(? AS INTEGER) AS number';
    var args = ['1'];
    db._adapter.execute(query, args)
    .then(function(result) {
      expect(result.rows).to.eql([{ number: 1 }]);
    })
    .done(done, done);
  });

  // run all shared examples
  _.each(shared, function(fn, name) {
    if (fn.length !== 0) {
      throw new Error('Cannot execute shared example: ' + name);
    }
    fn();
  });
});
<commit_msg>Added error reporting test.<commit_after>'use strict';

if (!/^(1|true)$/i.test(process.env.TEST_SQLITE || '1')) { return; }

var _ = require('lodash');
var expect = require('chai').expect;
var Database = require('../../../lib/db/database');
var BluebirdPromise = require('bluebird');

var shared = require('./shared_behaviors');
var returning = require('../../../lib/db/adapters/mixins/returning');
var PseudoReturn = returning.PseudoReturn;

var db, connection = {
  adapter: 'sqlite3',
  filename: ''
};

var resetSequence = BluebirdPromise.method(function(/*table*/) {
  // no need to reset
});

describe('SQLite3', function() {
  before(function() { db = this.db = Database.create(connection); });
  before(function() { this.resetSequence = resetSequence; });
  after(function(done) { db.disconnect().then(done, done); });

  it('executes raw sql', function(done) {
    var returnId = PseudoReturn.create('id');
    var queries = [
      ['CREATE TABLE azul_raw_sql_test ' +
       '(id integer primary key autoincrement, name varchar(255))'],
      ['INSERT INTO azul_raw_sql_test (name) VALUES (\'Azul\')', [returnId]],
      ['SELECT * FROM azul_raw_sql_test'],
      ['DROP TABLE azul_raw_sql_test']
    ];
    BluebirdPromise.reduce(queries, function(array, info) {
      var query = info[0], args = info[1] || [];
      return db._adapter.execute(query, args).then(function(result) {
        return array.concat([result]);
      });
    }, [])
    .spread(function(result1, result2, result3, result4) {
      expect(result1).to.eql({ rows: [], fields: [] });
      expect(result2).to.eql({
        rows: [{ id: 1 }], fields: ['id'] });
      expect(result3).to.eql({
        rows: [{ id: 1, name: 'Azul' }],
        fields: ['id', 'name'] });
      expect(result4).to.eql({ rows: [], fields: [] });
    })
    .done(done, done);
  });

  it('receives rows from raw sql', function(done) {
    var query = 'SELECT CAST(? AS INTEGER) AS number';
    var args = ['1'];
    db._adapter.execute(query, args)
    .then(function(result) {
      expect(result.rows).to.eql([{ number: 1 }]);
    })
    .done(done, done);
  });

  it('reports errors', function(done) {
    var query = 'SELECT & FROM ^';
    var args = [];
    db._adapter.execute(query, args)
    .throw(new Error('Expected query to fail.'))
    .catch(function(e) {
      expect(e.message).to.match(/SQLITE_ERROR.*syntax/i);
    })
    .done(done, done);
  });

  // run all shared examples
  _.each(shared, function(fn, name) {
    if (fn.length !== 0) {
      throw new Error('Cannot execute shared example: ' + name);
    }
    fn();
  });
});
<|endoftext|>


<commit_before><commit_msg>test(ngAnimate): test calling callbacks for various constellations<commit_after><|endoftext|>


<commit_before>/*global Raven*/
import {
  // User actions
  subscribe, unsubscribe,
  sendSubscriptionRequest,
  ban, unban,

  // Post actions
  showMoreComments, showMoreLikes,
  addAttachmentResponse, removeAttachment,
  likePost, unlikePost,
  hidePost, unhidePost,
  toggleModeratingComments,
  disableComments, enableComments,
  toggleEditingPost, cancelEditingPost, saveEditingPost,
  deletePost,

  // Comment actions
  toggleCommenting, updateCommentingText, addComment,
  toggleEditingComment, saveEditingComment,
  highlightComment, clearHighlightComment,
  deleteComment
} from '../redux/action-creators';

const MAX_LIKES = 4;

export const ommitBubblesThreshold = 600 * 1000; // 10 min

const allFalse = () => false;

const commentHighlighter = ({commentsHighlights, user, postsViewState}, commentsPostId, commentList) => {
  const {postId, author, arrows, baseCommentId} = commentsHighlights;
  const {comments} = user.frontendPreferences;
  const {omittedComments} = postsViewState[commentsPostId];
  if (!comments.highlightComments) {
    return allFalse;
  }

  if (commentsPostId !== postId) {
    return allFalse;
  }

  const baseIndex = commentList.indexOf(baseCommentId);
  const highlightIndex = (baseIndex + omittedComments) - arrows;
  const highlightCommentId = commentList[highlightIndex < baseIndex ? highlightIndex : -1];

  return (commentId, commentAuthor) => author === commentAuthor.username || highlightCommentId === commentId;
};

export const joinPostData = state => postId => {
  const post = state.posts[postId];
  if (!post) {
    return;
  }
  const user = state.user;

  const attachments = (post.attachments || []).map(attachmentId => state.attachments[attachmentId]);
  const postViewState = state.postsViewState[post.id];
  const omitRepeatedBubbles = state.user.frontendPreferences.comments.omitRepeatedBubbles;
  const highlightComment = commentHighlighter(state, postId, post.comments);
  let comments = (post.comments || []).reduce((_comments, commentId, index) => {
    const comment = state.comments[commentId];
    if (!comment) {
      return _comments;
    }
    const commentViewState = state.commentViewState[commentId];
    const placeholderUser = {id: comment.createdBy};
    const author = state.users[comment.createdBy] || placeholderUser;
    if (author === placeholderUser) {
      if (typeof Raven !== 'undefined') {
        Raven.captureMessage(`We've got comment with unknown author with id`, { extra: { uid: placeholderUser.id }});
      }
    }
    const previousPost = _comments[index-1] || {createdBy: null, createdAt: "0"};
    const omitBubble = omitRepeatedBubbles
      && postViewState.omittedComments === 0
      && !comment.hideType
      && !previousPost.hideType
      && comment.createdBy === previousPost.createdBy
      && comment.createdAt - previousPost.createdAt < ommitBubblesThreshold;
    const isEditable = (user.id === comment.createdBy);
    const isDeletable = (user.id === post.createdBy);
    const highlighted = highlightComment(commentId, author);
    return _comments.concat([{ ...comment, ...commentViewState, user: author, isEditable, isDeletable, omitBubble, highlighted }]);
  }, []);

  if (postViewState.omittedComments !== 0 && comments.length > 2) {
    comments = [ comments[0], comments[comments.length - 1] ];
  }

  let usersLikedPost = (post.likes || []).map(userId => state.users[userId]);

  if (postViewState.omittedLikes !== 0) {
    usersLikedPost = usersLikedPost.slice(0, MAX_LIKES);
  }

  const placeholderUser = {id: post.createdBy};

  const createdBy = state.users[post.createdBy] || placeholderUser;

  if (createdBy === placeholderUser) {
    if (typeof Raven !== 'undefined') {
      Raven.captureMessage(`We've got post with unknown author with id`, { extra: { uid: placeholderUser.id }});
    }
  }

  const isEditable = (post.createdBy === user.id);

  // Check if the post is a direct message
  const directRecipients = post.postedTo
    .filter((subscriptionId) => {
      const subscriptionType = (state.subscriptions[subscriptionId]||{}).name;
      return (subscriptionType === 'Directs');
    });
  const isDirect = !!directRecipients.length;

  // Get the list of post's recipients
  const recipients = post.postedTo
    .map(subscriptionId => {
      const userId = (state.subscriptions[subscriptionId]||{}).user;
      const subscriptionType = (state.subscriptions[subscriptionId]||{}).name;
      const isDirectToSelf = userId === post.createdBy && subscriptionType === 'Directs';
      return !isDirectToSelf ? userId : false;
    })
    .map(userId => state.subscribers[userId])
    .filter(user => user);

  const allowLinksPreview = state.user.frontendPreferences.allowLinksPreview;
  const readMoreStyle = state.user.frontendPreferences.readMoreStyle;

  return {...post,
    createdBy,
    isDirect,
    recipients,
    attachments,
    usersLikedPost,
    comments,
    ...postViewState,
    isEditable,
    allowLinksPreview,
    readMoreStyle,
  };
};

export function joinCreatePostData(state) {
  const createPostForm = state.createPostForm;
  return {...createPostForm,
    attachments: (createPostForm.attachments || []).map(attachmentId => state.attachments[attachmentId])
  };
}

export function postActions(dispatch) {
  return {
    showMoreComments: (postId) => dispatch(showMoreComments(postId)),
    showMoreLikes: (postId) => dispatch(showMoreLikes(postId)),
    toggleEditingPost: (postId, newValue) => dispatch(toggleEditingPost(postId, newValue)),
    cancelEditingPost: (postId, newValue) => dispatch(cancelEditingPost(postId, newValue)),
    saveEditingPost: (postId, newPost) => dispatch(saveEditingPost(postId, newPost)),
    deletePost: (postId) => dispatch(deletePost(postId)),
    toggleCommenting: (postId) => dispatch(toggleCommenting(postId)),
    updateCommentingText: (postId, commentText) => dispatch(updateCommentingText(postId, commentText)),
    addComment:(postId, commentText) => dispatch(addComment(postId, commentText)),
    likePost: (postId, userId) => dispatch(likePost(postId, userId)),
    unlikePost: (postId, userId) => dispatch(unlikePost(postId, userId)),
    hidePost: (postId) => dispatch(hidePost(postId)),
    unhidePost: (postId) => dispatch(unhidePost(postId)),
    toggleModeratingComments: (postId) => dispatch(toggleModeratingComments(postId)),
    disableComments: (postId) => dispatch(disableComments(postId)),
    enableComments: (postId) => dispatch(enableComments(postId)),
    addAttachmentResponse: (postId, attachments) => dispatch(addAttachmentResponse(postId, attachments)),
    removeAttachment: (postId, attachmentId) => dispatch(removeAttachment(postId, attachmentId)),
    commentEdit: {
      toggleEditingComment: (commentId) => dispatch(toggleEditingComment(commentId)),
      saveEditingComment: (commentId, newValue) => dispatch(saveEditingComment(commentId, newValue)),
      deleteComment: (commentId) => dispatch(deleteComment(commentId)),
      highlightComment: (postId, author, arrows, baseCommentId) => dispatch(highlightComment(postId, author, arrows,  baseCommentId)),
      clearHighlightComment: () => dispatch(clearHighlightComment()),
    },
  };
}

export function userActions(dispatch) {
  return {
    ban: username => dispatch(ban(username)),
    unban: username => dispatch(unban(username)),
    subscribe: username => dispatch(subscribe(username)),
    unsubscribe: username => dispatch(unsubscribe(username)),
    sendSubscriptionRequest: username => dispatch(sendSubscriptionRequest(username))
  };
}
<commit_msg>Fix ^-highlighting of hidden comments<commit_after>/*global Raven*/
import {
  // User actions
  subscribe, unsubscribe,
  sendSubscriptionRequest,
  ban, unban,

  // Post actions
  showMoreComments, showMoreLikes,
  addAttachmentResponse, removeAttachment,
  likePost, unlikePost,
  hidePost, unhidePost,
  toggleModeratingComments,
  disableComments, enableComments,
  toggleEditingPost, cancelEditingPost, saveEditingPost,
  deletePost,

  // Comment actions
  toggleCommenting, updateCommentingText, addComment,
  toggleEditingComment, saveEditingComment,
  highlightComment, clearHighlightComment,
  deleteComment
} from '../redux/action-creators';

const MAX_LIKES = 4;

export const ommitBubblesThreshold = 600 * 1000; // 10 min

const allFalse = () => false;

const commentHighlighter = ({commentsHighlights, user, postsViewState}, commentsPostId, commentList) => {
  const {postId, author, arrows, baseCommentId} = commentsHighlights;
  const {comments} = user.frontendPreferences;
  const {omittedComments} = postsViewState[commentsPostId];
  if (!comments.highlightComments) {
    return allFalse;
  }

  if (commentsPostId !== postId) {
    return allFalse;
  }

  const baseIndex = commentList.indexOf(baseCommentId);
  const highlightIndex = (baseIndex + omittedComments) - arrows;
  const highlightCommentId = commentList[highlightIndex < baseIndex ? highlightIndex : -1];

  return (commentId, commentAuthor) => author && author === commentAuthor.username || highlightCommentId === commentId;
};

export const joinPostData = state => postId => {
  const post = state.posts[postId];
  if (!post) {
    return;
  }
  const user = state.user;

  const attachments = (post.attachments || []).map(attachmentId => state.attachments[attachmentId]);
  const postViewState = state.postsViewState[post.id];
  const omitRepeatedBubbles = state.user.frontendPreferences.comments.omitRepeatedBubbles;
  const highlightComment = commentHighlighter(state, postId, post.comments);
  let comments = (post.comments || []).reduce((_comments, commentId, index) => {
    const comment = state.comments[commentId];
    if (!comment) {
      return _comments;
    }
    const commentViewState = state.commentViewState[commentId];
    const placeholderUser = {id: comment.createdBy};
    const author = state.users[comment.createdBy] || placeholderUser;
    if (author === placeholderUser) {
      if (typeof Raven !== 'undefined') {
        Raven.captureMessage(`We've got comment with unknown author with id`, { extra: { uid: placeholderUser.id }});
      }
    }
    const previousPost = _comments[index-1] || {createdBy: null, createdAt: "0"};
    const omitBubble = omitRepeatedBubbles
      && postViewState.omittedComments === 0
      && !comment.hideType
      && !previousPost.hideType
      && comment.createdBy === previousPost.createdBy
      && comment.createdAt - previousPost.createdAt < ommitBubblesThreshold;
    const isEditable = (user.id === comment.createdBy);
    const isDeletable = (user.id === post.createdBy);
    const highlighted = highlightComment(commentId, author);
    return _comments.concat([{ ...comment, ...commentViewState, user: author, isEditable, isDeletable, omitBubble, highlighted }]);
  }, []);

  if (postViewState.omittedComments !== 0 && comments.length > 2) {
    comments = [ comments[0], comments[comments.length - 1] ];
  }

  let usersLikedPost = (post.likes || []).map(userId => state.users[userId]);

  if (postViewState.omittedLikes !== 0) {
    usersLikedPost = usersLikedPost.slice(0, MAX_LIKES);
  }

  const placeholderUser = {id: post.createdBy};

  const createdBy = state.users[post.createdBy] || placeholderUser;

  if (createdBy === placeholderUser) {
    if (typeof Raven !== 'undefined') {
      Raven.captureMessage(`We've got post with unknown author with id`, { extra: { uid: placeholderUser.id }});
    }
  }

  const isEditable = (post.createdBy === user.id);

  // Check if the post is a direct message
  const directRecipients = post.postedTo
    .filter((subscriptionId) => {
      const subscriptionType = (state.subscriptions[subscriptionId]||{}).name;
      return (subscriptionType === 'Directs');
    });
  const isDirect = !!directRecipients.length;

  // Get the list of post's recipients
  const recipients = post.postedTo
    .map(subscriptionId => {
      const userId = (state.subscriptions[subscriptionId]||{}).user;
      const subscriptionType = (state.subscriptions[subscriptionId]||{}).name;
      const isDirectToSelf = userId === post.createdBy && subscriptionType === 'Directs';
      return !isDirectToSelf ? userId : false;
    })
    .map(userId => state.subscribers[userId])
    .filter(user => user);

  const allowLinksPreview = state.user.frontendPreferences.allowLinksPreview;
  const readMoreStyle = state.user.frontendPreferences.readMoreStyle;

  return {...post,
    createdBy,
    isDirect,
    recipients,
    attachments,
    usersLikedPost,
    comments,
    ...postViewState,
    isEditable,
    allowLinksPreview,
    readMoreStyle,
  };
};

export function joinCreatePostData(state) {
  const createPostForm = state.createPostForm;
  return {...createPostForm,
    attachments: (createPostForm.attachments || []).map(attachmentId => state.attachments[attachmentId])
  };
}

export function postActions(dispatch) {
  return {
    showMoreComments: (postId) => dispatch(showMoreComments(postId)),
    showMoreLikes: (postId) => dispatch(showMoreLikes(postId)),
    toggleEditingPost: (postId, newValue) => dispatch(toggleEditingPost(postId, newValue)),
    cancelEditingPost: (postId, newValue) => dispatch(cancelEditingPost(postId, newValue)),
    saveEditingPost: (postId, newPost) => dispatch(saveEditingPost(postId, newPost)),
    deletePost: (postId) => dispatch(deletePost(postId)),
    toggleCommenting: (postId) => dispatch(toggleCommenting(postId)),
    updateCommentingText: (postId, commentText) => dispatch(updateCommentingText(postId, commentText)),
    addComment:(postId, commentText) => dispatch(addComment(postId, commentText)),
    likePost: (postId, userId) => dispatch(likePost(postId, userId)),
    unlikePost: (postId, userId) => dispatch(unlikePost(postId, userId)),
    hidePost: (postId) => dispatch(hidePost(postId)),
    unhidePost: (postId) => dispatch(unhidePost(postId)),
    toggleModeratingComments: (postId) => dispatch(toggleModeratingComments(postId)),
    disableComments: (postId) => dispatch(disableComments(postId)),
    enableComments: (postId) => dispatch(enableComments(postId)),
    addAttachmentResponse: (postId, attachments) => dispatch(addAttachmentResponse(postId, attachments)),
    removeAttachment: (postId, attachmentId) => dispatch(removeAttachment(postId, attachmentId)),
    commentEdit: {
      toggleEditingComment: (commentId) => dispatch(toggleEditingComment(commentId)),
      saveEditingComment: (commentId, newValue) => dispatch(saveEditingComment(commentId, newValue)),
      deleteComment: (commentId) => dispatch(deleteComment(commentId)),
      highlightComment: (postId, author, arrows, baseCommentId) => dispatch(highlightComment(postId, author, arrows,  baseCommentId)),
      clearHighlightComment: () => dispatch(clearHighlightComment()),
    },
  };
}

export function userActions(dispatch) {
  return {
    ban: username => dispatch(ban(username)),
    unban: username => dispatch(unban(username)),
    subscribe: username => dispatch(subscribe(username)),
    unsubscribe: username => dispatch(unsubscribe(username)),
    sendSubscriptionRequest: username => dispatch(sendSubscriptionRequest(username))
  };
}
<|endoftext|>


<commit_before>
/*accountInformation
[credentials]
credentials:{key: validation}
*/

/*
queue
[{endpoint1: string, endpoint2: string, speed: number}]
*/

import { LOGIN, LOGOUT, PROMOTE, ENDPOINT_PROGRESS, ENDPOINT_UPDATE, UPDATE_HASH } from './actions';
import { transferOptimizations } from "./actions";

// import {cookie} from "react-cookies";
export const cookies = require("js-cookie");
export const beforeLogin = 0;
export const duringLogin = 1;
export const afterLogin = 2;
const initialState = {
	login: cookies.get('email') ? true : false,
	admin: false,
	email: cookies.get('email') || "noemail" ,
  publicKey: cookies.get('publicKey') || null ,
	hash: cookies.get('hash') || null,

	endpoint1: cookies.get('endpoint1') ? JSON.parse(cookies.get('endpoint1')) : {
		login: false,
		credential: {},
		uri: "",
        side: "left"
	},

	endpoint2: cookies.get('endpoint2') ? JSON.parse(cookies.get('endpoint2')) : {
    login: false,
		credential: {},
		uri: "",
        side: "right"
	},

	queue: [],
	transferOptions : {
		useTransferOptimization : transferOptimizations.None,
		overwriteExistingFiles : true,
		verifyFileInterity : false,
		encryptDataChannel : false,
		compressDataChannel : false
	}
}

export function onedatashareModel(state = initialState, action) {
  // For now, don't handle any actions
  // and just return the state given to us.
  switch (action.type) {
    case LOGIN:
    	console.log('logging in')
   		const {email, hash, publicKey} = action.credential;
      console.log(email);
    	cookies.set('email', email, );
		  cookies.set('hash', hash, );
      cookies.set('publicKey', publicKey, );
    	return Object.assign({}, state, {
    		login: true,
    		email: email,
    		hash: hash,
            publicKey: publicKey
    	});
    case LOGOUT:
      console.log("logging out");
      cookies.remove('email');
      cookies.remove('hash');
      cookies.remove('admin');
      cookies.remove('endpoint1');
      cookies.remove('endpoint2');
      cookies.remove("publicKey");
      window.location.replace('/');

      return Object.assign({}, state, {
        login: false,
        admin: false,
        hash: "",
        email: "noemail"
      });
    case PROMOTE:
      return Object.assign({}, state, {
        admin: true,
      });
    case ENDPOINT_PROGRESS:
      if(action.side === "left")
        return Object.assign({}, state, {
          endpoint1: {...state.endpoint1, loginProgress: action.progress},
        });
      else
        return Object.assign({}, state, {
          endpoint2: {...state.endpoint2, loginProgress: action.progress},
        });
    case ENDPOINT_UPDATE:
      if(action.side === "left"){
        console.log(JSON.stringify({...state.endpoint1, ...action.endpoint}));
        cookies.set('endpoint1', JSON.stringify({...state.endpoint1, ...action.endpoint}), );
          return Object.assign({}, state, {
            endpoint1: {...state.endpoint1, ...action.endpoint},
          });
        }
      else{
        cookies.set('endpoint2', JSON.stringify({...state.endpoint2, ...action.endpoint}), );
        return Object.assign({}, state, {
          endpoint2: {...state.endpoint2, ...action.endpoint},
        });
      }
    case UPDATE_HASH:
        cookies.remove('hash');
     cookies.set('hash',  action.hash, );
         return Object.assign({}, state, {
                  hash: action.hash
                });

    default:
      return state
  }
}<commit_msg>Update reducers.js<commit_after>
/*accountInformation
[credentials]
credentials:{key: validation}
*/

/*
queue
[{endpoint1: string, endpoint2: string, speed: number}]
*/

import { LOGIN, LOGOUT, PROMOTE, ENDPOINT_PROGRESS, ENDPOINT_UPDATE, UPDATE_HASH } from './actions';
import { transferOptimizations } from "./actions";

export const cookies = require("js-cookie");
export const beforeLogin = 0;
export const duringLogin = 1;
export const afterLogin = 2;
const initialState = {
	login: cookies.get('email') ? true : false,
	admin: false,
	email: cookies.get('email') || "noemail" ,
  publicKey: cookies.get('publicKey') || null ,
	hash: cookies.get('hash') || null,

	endpoint1: cookies.get('endpoint1') ? JSON.parse(cookies.get('endpoint1')) : {
		login: false,
		credential: {},
		uri: "",
        side: "left"
	},

	endpoint2: cookies.get('endpoint2') ? JSON.parse(cookies.get('endpoint2')) : {
    login: false,
		credential: {},
		uri: "",
        side: "right"
	},

	queue: [],
	transferOptions : {
		useTransferOptimization : transferOptimizations.None,
		overwriteExistingFiles : true,
		verifyFileInterity : false,
		encryptDataChannel : false,
		compressDataChannel : false
	}
}

export function onedatashareModel(state = initialState, action) {
  // For now, don't handle any actions
  // and just return the state given to us.
  switch (action.type) {
    case LOGIN:
    	console.log('logging in')
   		const {email, hash, publicKey} = action.credential;
      console.log(email);
    	cookies.set('email', email, );
		  cookies.set('hash', hash, );
      cookies.set('publicKey', publicKey, );
    	return Object.assign({}, state, {
    		login: true,
    		email: email,
    		hash: hash,
            publicKey: publicKey
    	});
    case LOGOUT:
      console.log("logging out");
      cookies.remove('email');
      cookies.remove('hash');
      cookies.remove('admin');
      cookies.remove('endpoint1');
      cookies.remove('endpoint2');
      cookies.remove("publicKey");
      window.location.replace('/');

      return Object.assign({}, state, {
        login: false,
        admin: false,
        hash: "",
        email: "noemail"
      });
    case PROMOTE:
      return Object.assign({}, state, {
        admin: true,
      });
    case ENDPOINT_PROGRESS:
      if(action.side === "left")
        return Object.assign({}, state, {
          endpoint1: {...state.endpoint1, loginProgress: action.progress},
        });
      else
        return Object.assign({}, state, {
          endpoint2: {...state.endpoint2, loginProgress: action.progress},
        });
    case ENDPOINT_UPDATE:
      if(action.side === "left"){
        console.log(JSON.stringify({...state.endpoint1, ...action.endpoint}));
        cookies.set('endpoint1', JSON.stringify({...state.endpoint1, ...action.endpoint}), );
          return Object.assign({}, state, {
            endpoint1: {...state.endpoint1, ...action.endpoint},
          });
        }
      else{
        cookies.set('endpoint2', JSON.stringify({...state.endpoint2, ...action.endpoint}), );
        return Object.assign({}, state, {
          endpoint2: {...state.endpoint2, ...action.endpoint},
        });
      }
    case UPDATE_HASH:
        cookies.remove('hash');
     cookies.set('hash',  action.hash, );
         return Object.assign({}, state, {
                  hash: action.hash
                });

    default:
      return state
  }
}
<|endoftext|>


<commit_before><commit_msg>replace boundaries for windows in tests<commit_after><|endoftext|>


<commit_before>import {showMoreComments, showMoreLikes, toggleEditingPost, cancelEditingPost,
        saveEditingPost, deletePost, addAttachmentResponse, removeAttachment,
        likePost, unlikePost, disableComments, enableComments, toggleCommenting, addComment,
        toggleEditingComment, cancelEditingComment, saveEditingComment, deleteComment,
        ban, unban, subscribe, unsubscribe, } from '../redux/action-creators'

const MAX_LIKES = 4

export const joinPostData = state => postId => {
  const post = state.posts[postId]
  if (!post){
    return
  }
  const user = state.user

  const attachments = (post.attachments || []).map(attachmentId => state.attachments[attachmentId])
  let comments = (post.comments || []).map(commentId => {
    const comment = state.comments[commentId]
    const commentViewState = state.commentViewState[commentId]
    const author = state.users[comment.createdBy]
    const isEditable = (user.id === comment.createdBy)
    return { ...comment, ...commentViewState, user: author, isEditable }
  })

  const postViewState = state.postsViewState[post.id]

  if (postViewState.omittedComments !== 0) {
    comments = [ comments[0], comments[comments.length - 1] ]
  }

  let usersLikedPost = _.map(post.likes, userId => state.users[userId])

  if (postViewState.omittedLikes !== 0) {
    usersLikedPost = usersLikedPost.slice(0, MAX_LIKES)
  }

  const createdBy = state.users[post.createdBy]
  const isEditable = (post.createdBy === user.id)
  const directFeeds = post.postedTo.map(feedId => state.timelines[feedId]).filter(feed => feed && feed.name === 'Directs')
  const isDirect = directFeeds.length

  // Get the list of post's recipients
  let recipients = post.postedTo
    .map(function(subscriptionId) {
      let userId = (state.subscriptions[subscriptionId]||{}).user
      let subscriptionType = (state.subscriptions[subscriptionId]||{}).name
      if (userId === post.createdBy && subscriptionType === 'Directs') {
        // Remove "directs to yourself" from the list
        return false
      } else {
        return userId
      }
    })
    .map(userId => state.subscribers[userId])
    .filter(user => user)

  return {...post,
    createdBy, isDirect, recipients,
    attachments, usersLikedPost, comments,
    ...postViewState, isEditable
  }
}

export function joinCreatePostData(state) {
  const createPostForm = state.createPostForm
  return {...createPostForm,
    attachments: (createPostForm.attachments || []).map(attachmentId => state.attachments[attachmentId])
  }
}

export function postActions(dispatch) {
  return {
    showMoreComments: (postId) => dispatch(showMoreComments(postId)),
    showMoreLikes: (postId) => dispatch(showMoreLikes(postId)),
    toggleEditingPost: (postId, newValue) => dispatch(toggleEditingPost(postId, newValue)),
    cancelEditingPost: (postId, newValue) => dispatch(cancelEditingPost(postId, newValue)),
    saveEditingPost: (postId, newPost) => dispatch(saveEditingPost(postId, newPost)),
    deletePost: (postId) => dispatch(deletePost(postId)),
    toggleCommenting: (postId) => dispatch(toggleCommenting(postId)),
    addComment:(postId, commentText) => dispatch(addComment(postId, commentText)),
    likePost: (postId, userId) => dispatch(likePost(postId, userId)),
    unlikePost: (postId, userId) => dispatch(unlikePost(postId, userId)),
    disableComments: (postId) => dispatch(disableComments(postId)),
    enableComments: (postId) => dispatch(enableComments(postId)),
    addAttachmentResponse:(postId, attachments) => dispatch(addAttachmentResponse(postId, attachments)),
    removeAttachment:(postId, attachmentId) => dispatch(removeAttachment(postId, attachmentId)),
    commentEdit: {
      toggleEditingComment: (commentId) => dispatch(toggleEditingComment(commentId)),
      saveEditingComment: (commentId, newValue) => dispatch(saveEditingComment(commentId, newValue)),
      deleteComment: (commentId) => dispatch(deleteComment(commentId)),
    },
  }
}

export function userActions(dispatch) {
  return {
    ban: username => dispatch(ban(username)),
    unban: username => dispatch(unban(username)),
    subscribe: username => dispatch(subscribe(username)),
    unsubscribe: username => dispatch(unsubscribe(username)),
  }
}
<commit_msg>Refactor: group the imports of action-creators<commit_after>import {
  // User actions
  subscribe, unsubscribe,
  ban, unban,

  // Post actions
  showMoreComments, showMoreLikes,
  addAttachmentResponse, removeAttachment,
  likePost, unlikePost,
  disableComments, enableComments,
  toggleEditingPost, cancelEditingPost, saveEditingPost,
  deletePost,

  // Comment actions
  toggleCommenting, addComment,
  toggleEditingComment, cancelEditingComment, saveEditingComment,
  deleteComment
} from '../redux/action-creators'

const MAX_LIKES = 4

export const joinPostData = state => postId => {
  const post = state.posts[postId]
  if (!post){
    return
  }
  const user = state.user

  const attachments = (post.attachments || []).map(attachmentId => state.attachments[attachmentId])
  let comments = (post.comments || []).map(commentId => {
    const comment = state.comments[commentId]
    const commentViewState = state.commentViewState[commentId]
    const author = state.users[comment.createdBy]
    const isEditable = (user.id === comment.createdBy)
    return { ...comment, ...commentViewState, user: author, isEditable }
  })

  const postViewState = state.postsViewState[post.id]

  if (postViewState.omittedComments !== 0) {
    comments = [ comments[0], comments[comments.length - 1] ]
  }

  let usersLikedPost = _.map(post.likes, userId => state.users[userId])

  if (postViewState.omittedLikes !== 0) {
    usersLikedPost = usersLikedPost.slice(0, MAX_LIKES)
  }

  const createdBy = state.users[post.createdBy]
  const isEditable = (post.createdBy === user.id)
  const directFeeds = post.postedTo.map(feedId => state.timelines[feedId]).filter(feed => feed && feed.name === 'Directs')
  const isDirect = directFeeds.length

  // Get the list of post's recipients
  let recipients = post.postedTo
    .map(function(subscriptionId) {
      let userId = (state.subscriptions[subscriptionId]||{}).user
      let subscriptionType = (state.subscriptions[subscriptionId]||{}).name
      if (userId === post.createdBy && subscriptionType === 'Directs') {
        // Remove "directs to yourself" from the list
        return false
      } else {
        return userId
      }
    })
    .map(userId => state.subscribers[userId])
    .filter(user => user)

  return {...post,
    createdBy, isDirect, recipients,
    attachments, usersLikedPost, comments,
    ...postViewState, isEditable
  }
}

export function joinCreatePostData(state) {
  const createPostForm = state.createPostForm
  return {...createPostForm,
    attachments: (createPostForm.attachments || []).map(attachmentId => state.attachments[attachmentId])
  }
}

export function postActions(dispatch) {
  return {
    showMoreComments: (postId) => dispatch(showMoreComments(postId)),
    showMoreLikes: (postId) => dispatch(showMoreLikes(postId)),
    toggleEditingPost: (postId, newValue) => dispatch(toggleEditingPost(postId, newValue)),
    cancelEditingPost: (postId, newValue) => dispatch(cancelEditingPost(postId, newValue)),
    saveEditingPost: (postId, newPost) => dispatch(saveEditingPost(postId, newPost)),
    deletePost: (postId) => dispatch(deletePost(postId)),
    toggleCommenting: (postId) => dispatch(toggleCommenting(postId)),
    addComment:(postId, commentText) => dispatch(addComment(postId, commentText)),
    likePost: (postId, userId) => dispatch(likePost(postId, userId)),
    unlikePost: (postId, userId) => dispatch(unlikePost(postId, userId)),
    disableComments: (postId) => dispatch(disableComments(postId)),
    enableComments: (postId) => dispatch(enableComments(postId)),
    addAttachmentResponse:(postId, attachments) => dispatch(addAttachmentResponse(postId, attachments)),
    removeAttachment:(postId, attachmentId) => dispatch(removeAttachment(postId, attachmentId)),
    commentEdit: {
      toggleEditingComment: (commentId) => dispatch(toggleEditingComment(commentId)),
      saveEditingComment: (commentId, newValue) => dispatch(saveEditingComment(commentId, newValue)),
      deleteComment: (commentId) => dispatch(deleteComment(commentId)),
    },
  }
}

export function userActions(dispatch) {
  return {
    ban: username => dispatch(ban(username)),
    unban: username => dispatch(unban(username)),
    subscribe: username => dispatch(subscribe(username)),
    unsubscribe: username => dispatch(unsubscribe(username)),
  }
}
<|endoftext|>


<commit_before>// mailer-test.js
//
// Test the mailer tool
//
// Copyright 2013, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require("assert"),
    vows = require("vows"),
    _ = require("underscore"),
    Logger = require("bunyan"),
    simplesmtp = require("simplesmtp"),
    emailutil = require("./lib/email"),
    Step = require("step"),
    oneEmail = emailutil.oneEmail;

var suite = vows.describe("mailer module interface").addBatch({
    "When we set up a dummy server": {
        topic: function() {
            var callback = this.callback,
                smtp = simplesmtp.createServer({disableDNSValidation: true});

            smtp.listen(1623, function(err) {
                if (err) {
                    callback(err, null);
                } else {
                    callback(null, smtp);
                }
            });
        },
        "it works": function(err, smtp) {
            assert.ifError(err);
            assert.isObject(smtp);
        },
        "teardown": function(smtp) {
            if (smtp) {
                smtp.end(function(err) {});
            }
        },
        "and we require the mailer module": {
            topic: function() {
                return require("../lib/mailer");
            },
            "it works": function(Mailer) {
                assert.isObject(Mailer);
            },
            "it has a setup() method": function(Mailer) {
                assert.isFunction(Mailer.setup);
            },
            "it has a sendEmail() method": function(Mailer) {
                assert.isFunction(Mailer.sendEmail);
            },
            "and we setup the Mailer module to use the dummy": {
                topic: function(Mailer) {
                    var log = new Logger({name: "mailer-test",
                                          streams: [{path: "/dev/null"}]}),
                        config = {
                            smtpuser: null,
                            smtppass: null,
                            smtpserver: "localhost",
                            smtpport: 1623,
                            smtpusessl: false,
                            smtpusetls: true,
                            hostname: "pump.localhost"
                        },
                        callback = this.callback;

                    try {
                        Mailer.setup(config, log);
                        callback(null);
                    } catch (err) {
                        callback(err);
                    }
                },
                "it works": function(err) {
                    assert.ifError(err);
                },
                "and we send an email message": {
                    topic: function(Mailer, smtp) {
                        var callback = this.callback,
                            message = {
                                to: "123@fakestreet.example",
                                subject: "Please report for arrest",
                                text: "We are coming to your house to arrest you"
                            };

                        Step(
                            function() {
                                oneEmail(smtp, message.to, this.parallel());
                                Mailer.sendEmail(message, this.parallel());
                            },
                            callback
                        );
                    },
                    "it works": function(err, received, sent) {
                        assert.ifError(err);
                        assert.isObject(received);
                        assert.isObject(sent);
                    }
                }
            }
        }
    }
});

suite["export"](module);
<commit_msg>Check doing multiple messages<commit_after>// mailer-test.js
//
// Test the mailer tool
//
// Copyright 2013, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require("assert"),
    vows = require("vows"),
    _ = require("underscore"),
    Logger = require("bunyan"),
    simplesmtp = require("simplesmtp"),
    emailutil = require("./lib/email"),
    Step = require("step"),
    oneEmail = emailutil.oneEmail;

var suite = vows.describe("mailer module interface").addBatch({
    "When we set up a dummy server": {
        topic: function() {
            var callback = this.callback,
                smtp = simplesmtp.createServer({disableDNSValidation: true});

            smtp.listen(1623, function(err) {
                if (err) {
                    callback(err, null);
                } else {
                    callback(null, smtp);
                }
            });
        },
        "it works": function(err, smtp) {
            assert.ifError(err);
            assert.isObject(smtp);
        },
        "teardown": function(smtp) {
            if (smtp) {
                smtp.end(function(err) {});
            }
        },
        "and we require the mailer module": {
            topic: function() {
                return require("../lib/mailer");
            },
            "it works": function(Mailer) {
                assert.isObject(Mailer);
            },
            "it has a setup() method": function(Mailer) {
                assert.isFunction(Mailer.setup);
            },
            "it has a sendEmail() method": function(Mailer) {
                assert.isFunction(Mailer.sendEmail);
            },
            "and we setup the Mailer module to use the dummy": {
                topic: function(Mailer) {
                    var log = new Logger({name: "mailer-test",
                                          streams: [{path: "/dev/null"}]}),
                        config = {
                            smtpuser: null,
                            smtppass: null,
                            smtpserver: "localhost",
                            smtpport: 1623,
                            smtpusessl: false,
                            smtpusetls: true,
                            hostname: "pump.localhost"
                        },
                        callback = this.callback;

                    try {
                        Mailer.setup(config, log);
                        callback(null);
                    } catch (err) {
                        callback(err);
                    }
                },
                "it works": function(err) {
                    assert.ifError(err);
                },
                "and we send an email message": {
                    topic: function(Mailer, smtp) {
                        var callback = this.callback,
                            message = {
                                to: "123@fakestreet.example",
                                subject: "Please report for arrest",
                                text: "We are coming to your house to arrest you"
                            };

                        Step(
                            function() {
                                oneEmail(smtp, message.to, this.parallel());
                                Mailer.sendEmail(message, this.parallel());
                            },
                            callback
                        );
                    },
                    "it works": function(err, received, sent) {
                        assert.ifError(err);
                        assert.isObject(received);
                        assert.isObject(sent);
                    },
                    "and we send a bunch of email messages": {
                        topic: function(received, sent, Mailer, smtp) {
                            var callback = this.callback,
                                message = {
                                    to: "456@fakestreet.example",
                                    subject: "Have you seen the perp?",
                                    text: "We sent an email and the perp ran."
                                };

                            Step(
                                function() {
                                    oneEmail(smtp, message.to, this.parallel());
                                    Mailer.sendEmail(message, this.parallel());
                                },
                                callback
                            );
                        },
                        "it works": function(err, received, sent) {
                            assert.ifError(err);
                            assert.isObject(received);
                            assert.isObject(sent);
                        }
                    }
                }
            }
        }
    }
});

suite["export"](module);
<|endoftext|>


<commit_before>var Producao = function(estado, prod, isInicial){
	this.estado = estado;
	this.prod = prod;
	this.isInicial = isInicial;
}

function testeInuteis(){
	var prod0 = new Producao('S', 'aA', true);
	var prod1 = new Producao('A', 'a', false);
	var prod2 = new Producao('E', 'aED', false);
	var prod3 = new Producao('D', 'dda', false);
	var prod4 = new Producao('D', 'aA', false);
	var prod5 = new Producao('H', 'aH', false);

	var terminais = ['a', 'b', 'd'];
	var nTerminais = ['S', 'A', 'E', 'D', 'H'];
	var producoes = [prod0, prod1, prod2, prod3, prod4, prod5];
	removerEstadosInuteis(terminais, nTerminais, producoes);
}

function removerEstadosInuteis(terminais, nTerminais, producoes){
	var estadoInicial;

	// Mostra no console as produções antes de eliminar inúteis
	console.log('Procuções antes de eliminar os inúteis: ');
	imprime(producoes);

	// Procura pelo estado inicial
	for (var i = 0; i < producoes.length; i++){
		if (producoes[i].isInicial){
			estadoInicial = producoes[i].estado;
			break;
		}
	}

	var geramTerminais = [];
	// Armazenar todos os Estados que geram terminais diretamente
	for(var i = 0; i < producoes.length; i++){
		var gera = true;

		externo: for (var j = 0; j < producoes[i].prod.length; j++){
			for (var k = 0; k < nTerminais.length; k++){
				if (producoes[i].prod[j] === nTerminais[k]){
					gera = false;
					break externo;
				}
			}
		}

		if (gera){
			geramTerminais.push(producoes[i].estado);
		}
	}

	// Limpa o array de estados que geram terminais diretamente para não possuir estados repetidos
	for (var i = 0; i < geramTerminais.length; i++){
		for (var j = i + 1; j < geramTerminais.length; j++){
			if (geramTerminais[i] === geramTerminais[j]){
				geramTerminais.splice(j, 1);
			}
		}
	}

	console.log('termeinais diretamente');
	for (var i = 0; i < geramTerminais.length; i++){
		console.log(geramTerminais[i]);
	}

	// Armazenar todos os Estados que acessam terminais indiretamente
	for(var i = 0; i < producoes.length; i++){
		// Somente vai validar os estados que não geram diretamente
		var geraDir = false;
		for (var j = 0; j < geramTerminais.length; j++){
			if (producoes[i].estado === geramTerminais[j]){
				geraDir = true;
				break;
			}
		}

		if(!geraDir){
			if (verificaGeraIndiretamente(criaArrayComProducoesDoEstadoX(producoes[i].estado, producoes), producoes, nTerminais, geramTerminais)){
			geramTerminais.push(producoes[i].estado);
			}
		}
	}

	console.log('termeinais diretamente + indiretamente');
	for (var i = 0; i < geramTerminais.length; i++){
		console.log(geramTerminais[i]);
	}

	// Elimina os estados que não geram terminais direta ou indiretamente
	for(var i = 0; i < producoes.length; i++){
		var remove = true;
		for (var j = 0; j < geramTerminais.length; j++){
			if (producoes[i].estado == geramTerminais[j]){
				remove = false;
				break;
			}
		}

		if(remove){
			producoes.splice(i, 1);
		}
	}

//	// Armazena o numero de produções do Simbolo Inicial
//	var producoesIniciais = 0;
//    for(var i = 0; i < producoes.length;i++){
//    	if(producoes[i].estado === estadoInicial){
//        	producoesIniciais++;
//        }
//    }
//
//	var estadosfinais = estadoInicial;
//	//Usar os simbolos restantes e ver quais deles são gerados a partir do simbolo inicial
//    for(var i = 0; i < ProduçõesIniciais; i++){
//		for(j= 0; j < geramTerminais.length;j++){
//			if (producoes[i].prod.indexOf(geramTerminais[j]) >= 0){
//				if(producoes[i].estado !=== geramTerminais[j-1]{
//					estadosfinal[j] = producoes[i].estado;
//				}
		//
//			}
//		}
//	}

	// Mostra no console as produções depois de eliminar inúteis
	console.log('Procuções depois de eliminar os inúteis: ');
	imprime(producoes);
}

function verificaGeraIndiretamente(prodEstado, producoes, nTerminais, geramTerminais){
	for (var i = 0; i < prodEstado.length; i++) {
		for(var j = 0; j < prodEstado[i].prod.length; j++){
			for (var k = 0; k < nTerminais.length; k++){
				if(prodEstado[i].prod[j] === nTerminais[k]){
					// Se entrou no IF achou um terminal na produção
					if (prodEstado[i].estado === nTerminais[k]){
						break;
					} else {
						for (var l = 0; l < geramTerminais.length; l++){
							if (nTerminais[k] === geramTerminais[l]){
								return true;
							}
						}
						return verificaGeraIndiretamente(criaArrayComProducoesDoEstadoX(nTerminais[k], producoes), producoes, nTerminais, geramTerminais);
					}
				}
			}
		}
	}
	return false;
}

function criaArrayComProducoesDoEstadoX(estado, producoes){
	var array = [];
	for (var i = 0; i < producoes.length;i++){
		if(producoes[i].estado === estado){
			array.push(producoes[i]);
		}
	}
	return array;
}

function imprime(producoes){
	for (var i = 0; i < producoes.length; i++){
		console.log(producoes[i].estado + ' ' + producoes[i].prod + ' ' + producoes[i].isInicial);
	}
}
<commit_msg>Concluído função para remover inúteis<commit_after>var Producao = function(estado, prod, isInicial){
	this.estado = estado;
	this.prod = prod;
	this.isInicial = isInicial;
}

function testeInuteis(){
	var prod0 = new Producao('S', 'aAB', true);
	var prod1 = new Producao('A', 'a', false);
	var prod2 = new Producao('E', 'aED', false);
	var prod3 = new Producao('D', 'dda', false);
	var prod4 = new Producao('D', 'aDA', false);
	var prod5 = new Producao('H', 'aH', false);
	var prod6 = new Producao('I', 'aAaA', false);
	var prod7 = new Producao('B', 'bD', false);
	var prod8 = new Producao('B', 'b', false);

	var terminais = ['a', 'b', 'd'];
	var nTerminais = ['S', 'A', 'B', 'E', 'D', 'H', 'I'];
	var producoes = [prod0, prod1, prod2, prod3, prod4, prod5, prod6, prod7, prod8];
	removerEstadosInuteis(terminais, nTerminais, producoes);
}

function removerEstadosInuteis(terminais, nTerminais, producoes){
	var estadoInicial;

	// Mostra no console as produções antes de eliminar inúteis
	console.log('Procuções antes de eliminar os inúteis: ');
	imprime(producoes);

	// Procura pelo estado inicial
	for (var i = 0; i < producoes.length; i++){
		if (producoes[i].isInicial){
			estadoInicial = producoes[i].estado;
			break;
		}
	}

	var geramTerminais = [];
	// Armazenar todos os Estados que geram terminais diretamente
	for(var i = 0; i < producoes.length; i++){
		var gera = true;

		externo: for (var j = 0; j < producoes[i].prod.length; j++){
			for (var k = 0; k < nTerminais.length; k++){
				if (producoes[i].prod[j] === nTerminais[k]){
					gera = false;
					break externo;
				}
			}
		}

		if (gera){
			geramTerminais.push(producoes[i].estado);
		}
	}

	// Limpa o array de estados que geram terminais diretamente para não possuir estados repetidos
	for (var i = 0; i < geramTerminais.length; i++){
		for (var j = i + 1; j < geramTerminais.length; j++){
			if (geramTerminais[i] === geramTerminais[j]){
				geramTerminais.splice(j, 1);
			}
		}
	}

	console.log('termeinais diretamente');
	for (var i = 0; i < geramTerminais.length; i++){
		console.log(geramTerminais[i]);
	}

	// Armazenar todos os Estados que acessam terminais indiretamente
	for(var i = 0; i < producoes.length; i++){
		// Somente vai validar os estados que não geram diretamente
		var geraDir = false;
		for (var j = 0; j < geramTerminais.length; j++){
			if (producoes[i].estado === geramTerminais[j]){
				geraDir = true;
				break;
			}
		}

		if(!geraDir){
			if (verificaGeraIndiretamente(criaArrayComProducoesDoEstadoX(producoes[i].estado, producoes), producoes, nTerminais, geramTerminais)){
			geramTerminais.push(producoes[i].estado);
			}
		}
	}

	console.log('termeinais diretamente + indiretamente');
	for (var i = 0; i < geramTerminais.length; i++){
		console.log(geramTerminais[i]);
	}

	// Elimina os estados que não geram terminais direta ou indiretamente
	for(var i = 0; i < producoes.length; i++){
		var remove = true;
		for (var j = 0; j < geramTerminais.length; j++){
			if (producoes[i].estado == geramTerminais[j]){
				remove = false;
				break;
			}
		}

		if(remove){
			var estadoEliminado = producoes[i].estado;
			// Remove a produção
			producoes.splice(i, 1);

			// Elimina as produções que contém os terminais eliminados
			for(var i = 0; i < producoes.length; i++){
				for(var j = 0; j < producoes[i].prod.length; j++){
					if(producoes[i].prod[j] === estadoEliminado){
						producoes.splice(i, 1);
					}
				}
			}

		}
	}

	var estadosAcessiveis = [];
	// Estados acessíveis a partir do estado inicial
	verificaAcessiveis(criaArrayComProducoesDoEstadoX(estadoInicial, producoes), producoes, nTerminais, estadosAcessiveis);

	// Remove repetiçõs no array de estados acessíveis
	for (var i = 0; i < estadosAcessiveis.length; i++){
		for (var j = i + 1; j < estadosAcessiveis.length; j++){
			if (estadosAcessiveis[i] === estadosAcessiveis[j]){
				estadosAcessiveis.splice(j, 1);
			}
		}
	}

	// Remove os estados que não são acessíveis a partir do simbolo inicial
	for(var i = 0; i < producoes.length; i++){
		var remove = true;
		for (var j = 0; j < estadosAcessiveis.length; j++){
			if (producoes[i].estado == estadosAcessiveis[j]){
				remove = false;
				break;
			}
		}

		if(remove){
			producoes.splice(i, 1);
		}
	}

	console.log("Estados acessíveis a partir do inicial: ");
	for (var i = 0; i < estadosAcessiveis.length; i++){
		console.log(estadosAcessiveis[i]);
	}

	// Mostra no console as produções depois de eliminar inúteis
	console.log('Procuções depois de eliminar os inúteis: ');
	imprime(producoes);
}

function verificaAcessiveis(prodEstado, producoes, nTerminais, estadosAcessiveis){
	for(var i = 0; i < prodEstado.length; i++){
		for(var j = 0; j < prodEstado[i].prod.length; j++){
			for(var k = 0; k < nTerminais.length; k++){
				if (prodEstado[i].prod[j] === nTerminais[k]){
					if (prodEstado[i].estado === nTerminais[k]){
						break;
					} else {
						estadosAcessiveis.push(nTerminais[k]);
						verificaAcessiveis(criaArrayComProducoesDoEstadoX(nTerminais[k], producoes), producoes, nTerminais, estadosAcessiveis);
						break;
					}
				}
			}
		}
	}
}

function verificaGeraIndiretamente(prodEstado, producoes, nTerminais, geramTerminais){
	for (var i = 0; i < prodEstado.length; i++) {
		for(var j = 0; j < prodEstado[i].prod.length; j++){
			for (var k = 0; k < nTerminais.length; k++){
				if(prodEstado[i].prod[j] === nTerminais[k]){
					// Se entrou no IF achou um terminal na produção
					if (prodEstado[i].estado === nTerminais[k]){
						break;
					} else {
						for (var l = 0; l < geramTerminais.length; l++){
							if (nTerminais[k] === geramTerminais[l]){
								return true;
							}
						}
						return verificaGeraIndiretamente(criaArrayComProducoesDoEstadoX(nTerminais[k], producoes), producoes, nTerminais, geramTerminais);
					}
				}
			}
		}
	}
	return false;
}

function criaArrayComProducoesDoEstadoX(estado, producoes){
	var array = [];
	for (var i = 0; i < producoes.length;i++){
		if(producoes[i].estado === estado){
			array.push(producoes[i]);
		}
	}
	return array;
}

function imprime(producoes){
	for (var i = 0; i < producoes.length; i++){
		console.log(producoes[i].estado + ' ' + producoes[i].prod + ' ' + producoes[i].isInicial);
	}
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import AutoSuggest from 'react-autosuggest';

export default class Input extends Component {

  constructor(props) {
    super(props);
  }

  onChange(text) {
    console.log('onChange event fired', text);
    if (text) this.props.onChange(text);
  }

  clearQuery() {
    this.props.onClear();
  }

  getSuggestions(input, cb) {
    cb(null, this.props.results.reduce((memo, d) => {
      memo.push(d.place_name);
      return memo;
    }, []));
  }

  setResult(v) {
    var result = this.props.results.filter((d) => {
      return v === d.place_name;
    })[0];

    console.log('Selected result', result);
  }

  render() {
    const { options } = this.props;

    const inputAttributes = {
      placeholder: options.placeholder,
      onChange: this.onChange.bind(this)
    };

    return (
      <div className={`mapbox-directions-${options.mode}`}>

          <span className={`directions-icon directions-icon-${options.icon}`}>

        <AutoSuggest
          ref='autosuggest'
          inputAttributes={inputAttributes}
          value={null}
          suggestions={this.getSuggestions.bind(this)}
          onSuggestionSelected={this.setResult.bind(this)}
        />

        {options.value && <button
          onClick={this.clearQuery.bind(this)}
          className='directions-icon directions-icon-close directions-close'
          title='Clear value'>
        </button>}

    );
  }
}

Input.propTypes = {
  text: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  onClear: PropTypes.func.isRequired,
  results: PropTypes.array.isRequired,
  options: PropTypes.object.isRequired
};
<commit_msg>Remove attribute used in testing<commit_after>import React, { Component, PropTypes } from 'react';
import AutoSuggest from 'react-autosuggest';

export default class Input extends Component {

  constructor(props) {
    super(props);
  }

  onChange(text) {
    console.log('onChange event fired', text);
    if (text) this.props.onChange(text);
  }

  clearQuery() {
    this.props.onClear();
  }

  getSuggestions(input, cb) {
    cb(null, this.props.results.reduce((memo, d) => {
      memo.push(d.place_name);
      return memo;
    }, []));
  }

  setResult(v) {
    var result = this.props.results.filter((d) => {
      return v === d.place_name;
    })[0];

    console.log('Selected result', result);
  }

  render() {
    const { options } = this.props;

    const inputAttributes = {
      placeholder: options.placeholder,
      onChange: this.onChange.bind(this)
    };

    return (
      <div className={`mapbox-directions-${options.mode}`}>

          <span className={`directions-icon directions-icon-${options.icon}`}>

        <AutoSuggest
          ref='autosuggest'
          inputAttributes={inputAttributes}
          suggestions={this.getSuggestions.bind(this)}
          onSuggestionSelected={this.setResult.bind(this)}
        />

        {options.value && <button
          onClick={this.clearQuery.bind(this)}
          className='directions-icon directions-icon-close directions-close'
          title='Clear value'>
        </button>}

    );
  }
}

Input.propTypes = {
  text: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  onClear: PropTypes.func.isRequired,
  results: PropTypes.array.isRequired,
  options: PropTypes.object.isRequired
};
<|endoftext|>


<commit_before>import React from 'react';

export default class Menu extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            visible: true
        };
    }

    show() {
        this.state.visible = true;
        document.addEventListener("click", this.hide.bind(this));
    }

    hide() {
        document.removeEventListener("click", this.hide.bind(this));
        this.state.visible = false;
    }

    render() {
        return (

 this.props.updatePage(0)} >
                        Status

 this.props.updatePage(0)} >
                        Second Page

        )
    }
}<commit_msg>Remove useless files<commit_after><|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import classNames from 'classnames';

const getImage = (assetID, color, fileIndex, assets) => {
  if ( ! assets.data) return;
  const fileName = assets.data[assetID].colors[color].files[fileIndex];
  return fileName ? `svg/${assetID}/${color}/${fileName}` : null;
};

const getNextIndex = (profile, assets, index) => {
  if ( ! assets.data) return;
  const length = assets.data[assets.current].colors[assets.currentColor].files.length;
  return (profile[assets.current].fileIndex + 1 + index) % length;
};

const getPrevIndex = (profile, assets, index) => {
  if ( ! assets.data) return;
  const length = assets.data[assets.current].colors[assets.currentColor].files.length;
  return (length + profile[assets.current].fileIndex - 1 - (1 - index) % 2) % length;
};

const getImg = (profile, assets, type, index) => {
  if ( ! assets.data) return;
  const fileIndex = type !== 'left' ? getNextIndex(profile, assets, index) : getPrevIndex(profile, assets, index);
  return ;
};

const Wheel = (
  ({ dispatch, assets, profile, type }) => {

    const classes = classNames('wheel',
      { left:  type === 'left' },
      { right: type === 'right'}
    );

    return  (

          {getImg(profile, assets, type, 0)}

          {getImg(profile, assets, type, 1)}

    )
  }
);

const mapStateToProps = state => ({
  assets: state.assets,
  profile: state.profile
});

export default connect(mapStateToProps)(Wheel);
<commit_msg>Remove unused argument<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import classNames from 'classnames';

const getImage = (assetID, color, fileIndex, assets) => {
  if ( ! assets.data) return;
  const fileName = assets.data[assetID].colors[color].files[fileIndex];
  return fileName ? `svg/${assetID}/${color}/${fileName}` : null;
};

const getNextIndex = (profile, assets, index) => {
  if ( ! assets.data) return;
  const length = assets.data[assets.current].colors[assets.currentColor].files.length;
  return (profile[assets.current].fileIndex + 1 + index) % length;
};

const getPrevIndex = (profile, assets, index) => {
  if ( ! assets.data) return;
  const length = assets.data[assets.current].colors[assets.currentColor].files.length;
  return (length + profile[assets.current].fileIndex - 1 - (1 - index) % 2) % length;
};

const getImg = (profile, assets, type, index) => {
  if ( ! assets.data) return;
  const fileIndex = type !== 'left' ? getNextIndex(profile, assets, index) : getPrevIndex(profile, assets, index);
  return ;
};

const Wheel = (
  ({ assets, profile, type }) => {

    const classes = classNames('wheel',
      { left:  type === 'left' },
      { right: type === 'right'}
    );

    return  (

          {getImg(profile, assets, type, 0)}

          {getImg(profile, assets, type, 1)}

    )
  }
);

const mapStateToProps = state => ({
  assets: state.assets,
  profile: state.profile
});

export default connect(mapStateToProps)(Wheel);
<|endoftext|>


<commit_before>import React from "react";
import { connect } from "react-redux";
import TitleBar from "../framework/title-bar";
import SingleDataset from "./single";

@connect((state) => {
  return {
    availableDatasets: state.datasets.availableDatasets,
    s3bucket: state.datasets.s3bucket
  };
})
class Status extends React.Component {
  getAllQueries() {
    console.warn("SHOULD ONLY EVER RUN ONCE");
    const queries = [];
    const exploreLevel = (pathSoFar, data) => {
      const keys = Object.keys(data).filter((v) => v !== "default");
      for (let key of keys) { // eslint-disable-line
        const path = [...pathSoFar, key];
        if (typeof data[key] === "string") { // i.e. zika = ""
          queries.push(path);
        } else {
          const nextLevelKey = Object.keys(data[key])[0];
          exploreLevel(path, data[key][nextLevelKey]);
        }
      }
    };
    exploreLevel([], this.props.availableDatasets.pathogen);
    return queries;
  }

  render() {
    if (!this.props.availableDatasets) {
      return null;
    }
    const queries = this.getAllQueries();
    return (

        <TitleBar dataNameHidden/>
        {queries.map((q) => (
          <SingleDataset key={q} path={q.join("_")} bucket={this.props.s3bucket}/>
        ))}

    );
  }
}

export default Status;
<commit_msg>header & allow staging server<commit_after>import React from "react";
import { connect } from "react-redux";
import TitleBar from "../framework/title-bar";
import SingleDataset from "./single";

@connect((state) => {
  return {
    availableDatasets: state.datasets.availableDatasets
  };
})
class Status extends React.Component {
  getAllQueries() {
    console.warn("SHOULD ONLY EVER RUN ONCE");
    const queries = [];
    const exploreLevel = (pathSoFar, data) => {
      const keys = Object.keys(data).filter((v) => v !== "default");
      for (let key of keys) { // eslint-disable-line
        const path = [...pathSoFar, key];
        if (typeof data[key] === "string") { // i.e. zika = ""
          queries.push(path);
        } else {
          const nextLevelKey = Object.keys(data[key])[0];
          exploreLevel(path, data[key][nextLevelKey]);
        }
      }
    };
    exploreLevel([], this.props.availableDatasets.pathogen);
    return queries;
  }
  render() {
    if (!this.props.availableDatasets) {
      return null;
    }
    const s3bucket = window.location.pathname.includes("staging") ? "staging" : "live";
    const queries = this.getAllQueries();
    return (

        <TitleBar dataNameHidden/>

          {`Status page (s3 bucket: ${s3bucket})`}

        {queries.map((q) => (
          <SingleDataset key={q} path={q.join("_")} bucket={s3bucket}/>
        ))}

    );
  }
}

export default Status;
<|endoftext|>


<commit_before>import {expect, assert} from 'chai'
import exec from 'crater-util/lib/exec'
import {childPrinted} from 'async-child-process'
import kill from 'crater-util/lib/kill'
import spawnAsync from 'crater-util/lib/spawnAsync'
import execAsync from 'crater-util/lib/execAsync'
import path from 'path'
import fs from 'fs'
import rimraf from 'rimraf'
import promisify from 'es6-promisify'
import {Collector} from 'istanbul'
import webpackConfig from '../../webpack/webpack.config.dev'
import debug from 'debug'

const browserLogsDebug = debug('crater:logs:browser')

const root = path.resolve(__dirname, '..', '..')
const src = path.join(root, 'src')
const build = path.join(root, 'build')
const webpack = path.join(root, 'webpack')

/* global browser: false */

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

function sharedTests() {
  it('serves page with correct title', async function () {
    expect(await browser.getTitle()).to.equal('Crater')
  })
  it('serves page with correct header', async function () {
    expect(await browser.getText('h1')).to.equal('Welcome to Crater!')
  })
  it('serves up client css', async function () {
    const color = await browser.getCssProperty('h1', 'color')
    expect(color.parsed.hex).to.equal('#333333')
  })
  it('updates the counter', async function () {
    const getCounter = async () => {
      const text = await browser.getText('.counter')
      const match = /(\d+)/.exec(text)
      return match && parseInt(match[1])
    }

    const initCounter = await getCounter()
    await delay(2000)
    expect(await getCounter()).to.be.above(initCounter)
  })
  it('sends Meteor.settings.public to the client', async function () {
    expect(await browser.getText('.settings-test')).to.equal('success')
  })
}

function unlinkIfExists(path, callback) {
  return fs.unlink(path, (err, result) => {
    if (err && /ENOENT/.test(err.message)) err = null
    return callback(err, result)
  })
}

// istanbul ignore next
async function mergeClientCoverage() {
  if (process.env.BABEL_ENV === 'coverage') {
    const collector = new Collector()

    collector.add(global.__coverage__)
    /* eslint-disable no-undef */
    collector.add((await browser.execute(() => window.__coverage__)).value)
    /* eslint-enable no-undef */
    global.__coverage__ = collector.getFinalCoverage()
  }
}

async function navigateTo(url) {
  if (process.env.DUMP_HTTP) {
    const popsicle = require('popsicle')
    const res = await popsicle.get(url)
    /* eslint-disable no-console */
    console.log(`GET ${url} ${res.status}`)
    console.log(res.headers)
    console.log(res.body)
    /* eslint-enable no-console */
  }
  await browser.url(url)
}

async function logBrowserMessages() {
  const logs = (await browser.log('browser')).value
  if (!logs) return
  logs.forEach(({level, message, timestamp}) => {
    const time = new Date(timestamp).toLocaleTimeString()
    browserLogsDebug(`${time} ${level} ${message}`)
  })
}

describe('prod mode', function () {
  let server
  const appFile = path.join(src, 'universal', 'components', 'App.js')
  const serverFile = path.join(src, 'server', 'index.js')
  let appCode, serverCode

  before(async function () {
    this.timeout(600000)
    appCode = await promisify(fs.readFile)(appFile, 'utf8')
    serverCode = await promisify(fs.readFile)(serverFile, 'utf8')
    server = exec('npm run prod', {cwd: root})
    await childPrinted(server, /App is listening on http/i)
    await browser.reload()
    await navigateTo(process.env.ROOT_URL)
  })

  after(async function () {
    this.timeout(600000)
    if (server) await kill(server, 'SIGINT')
    // restore code in App.js, which (may) have been changed by hot reloading test
    if (appCode) await promisify(fs.writeFile)(appFile, appCode, 'utf8')
    if (serverCode) await promisify(fs.writeFile)(serverFile, serverCode, 'utf8')
    if (process.env.BABEL_ENV === 'coverage') await mergeClientCoverage()
    await logBrowserMessages()
  })

  sharedTests()

  if (process.env.BABEL_ENV !== 'coverage') {
    describe('hot reloading', function () {
      it('server restarts when code is changed', async function () {
        this.timeout(60000)
        const serverModified = serverCode.replace(/express\(\)/, 'express()\napp.get("/test", (req, res) => res.send("hello world"))')
        await promisify(fs.writeFile)(serverFile, serverModified, 'utf8')
        await childPrinted(server, /App is listening on http/i)

        const newHeader = 'Welcome to Crater! with hot reloading'
        const appModified = appCode.replace(/Welcome to Crater!/, newHeader)
        await promisify(fs.writeFile)(appFile, appModified, 'utf8')
        await childPrinted(server, /App is listening on http/i)
      })
    })
  }
})

describe('prod mode with DISABLE_FULL_SSR=1', function () {
  let server

  before(async function () {
    this.timeout(240000)
    server = exec('npm run prod', {
      env: {
        ...process.env,
        DISABLE_FULL_SSR: '1',
      },
    })
    await childPrinted(server, /App is listening on http/i)
    await browser.reload()
    await navigateTo(process.env.ROOT_URL)
  })

  it('has hidden element to indicate that full SSR is disabled', async () => {
    assert(
      await browser.isExisting('#full-ssr-disabled'),
      "full SSR doesn't actually seem to be disabled"
    )
  })

  sharedTests()

  after(async function () {
    this.timeout(30000)
    if (server) await kill(server, 'SIGINT')
    if (process.env.BABEL_ENV === 'coverage') await mergeClientCoverage()
    await logBrowserMessages()
  })
})

describe('docker build', function () {
  let server

  before(async function () {
    this.timeout(15 * 60000)
    // run this first, even though it's not necessary, to increase coverage of scripts/build.js
    await spawnAsync('npm', ['run', 'build'], {cwd: root})
    await spawnAsync('npm', ['run', 'build:docker'], {cwd: root})
    server = exec('npm run docker', {
      cwd: root,
      env: {
        ...process.env,
        METEOR_SETTINGS: JSON.stringify({
          public: {
            test: 'success'
          }
        })
      }
    })
    await childPrinted(server, /App is listening on http/i)
    let host
    if (process.env.CI) host = (await execAsync('docker-compose port crater 80', {cwd: root})).stdout.trim()
    else {
      await execAsync('which docker-machine')
        .then(() => host = `192.168.99.100:${process.env.PORT}`)
        .catch(() => host = `localhost:${process.env.PORT}`)
    }
    await browser.reload()
    await navigateTo(`http://${host}`)
  })

  after(async function () {
    this.timeout(20000)
    if (process.env.BABEL_ENV === 'coverage') await mergeClientCoverage()
    await spawnAsync('docker-compose', ['down'], {cwd: root})
    await logBrowserMessages()
  })

  sharedTests()
})

describe('dev mode', function () {
  let server

  const appFile = path.join(src, 'universal', 'components', 'App.js')
  const serverFile = path.join(src, 'server', 'index.js')
  let appCode, serverCode

  before(async function () {
    this.timeout(15 * 60000)
    appCode = await promisify(fs.readFile)(appFile, 'utf8')
    serverCode = await promisify(fs.readFile)(serverFile, 'utf8')
    server = exec('npm start', {cwd: root})
    await Promise.all([
      childPrinted(server, /webpack built [a-z0-9]+ in \d+ms/i),
      childPrinted(server, /App is listening on http/i),
    ])
    await navigateTo(`http://localhost:${webpackConfig.devServer.port}`)
  })

  after(async function () {
    this.timeout(15 * 60000)
    if (server) await kill(server, 'SIGINT')
    // restore code in App.js, which (may) have been changed by hot reloading test
    if (appCode) await promisify(fs.writeFile)(appFile, appCode, 'utf8')
    if (serverCode) await promisify(fs.writeFile)(serverFile, serverCode, 'utf8')
    if (process.env.BABEL_ENV === 'coverage') await mergeClientCoverage()
    await logBrowserMessages()
  })

  sharedTests()

  if (process.env.BABEL_ENV !== 'coverage') {
    describe('hot reloading', function () {
      it('works on the client', async function () {
        this.timeout(40000)
        const newHeader = 'Welcome to Crater! with hot reloading'
        const modified = appCode.replace(/Welcome to Crater!/, newHeader)
        await promisify(fs.writeFile)(appFile, modified, 'utf8')
        await browser.waitUntil(
          () => browser.getText('h1') === newHeader,
          30000,
          'expected header text to hot update within 30s'
        )
      })

      it('server restarts when code is changed', async function () {
        this.timeout(60000)
        const modified = serverCode.replace(/express\(\)/, 'express()\napp.get("/test", (req, res) => res.send("hello world"))')
        await promisify(fs.writeFile)(serverFile, modified, 'utf8')
        await childPrinted(server, /App is listening on http/i)
      })
    })
  }
})

describe('build scripts', function () {
  describe('build:meteor', function () {
    it('only rebuilds when necessary', async function () {
      this.timeout(480000)

      await promisify(rimraf)(path.join(build, 'meteor'))
      expect(/building meteor packages/i.test((await execAsync('npm run build:meteor', {cwd: root})).stdout)).to.be.true
      expect(/build\/meteor is up to date/i.test((await execAsync('npm run build:meteor', {cwd: root})).stdout)).to.be.true

      await delay(1000)
      await promisify(fs.utimes)(path.resolve(root, 'meteor', '.meteor', 'packages'), NaN, NaN)
      expect(/building meteor packages/i.test((await execAsync('npm run build:meteor', {cwd: root})).stdout)).to.be.true
      expect(/build\/meteor is up to date/i.test((await execAsync('npm run build:meteor', {cwd: root})).stdout)).to.be.true
    })
  })
  describe('build:client', function () {
    it('only rebuilds when necessary', async function () {
      this.timeout(480000)

      await spawnAsync('npm', ['run', 'build:meteor'], {stdio: 'inherit', cwd: root})

      await promisify(unlinkIfExists)(path.join(build, 'assets.json'))
      expect(/building client bundle/.test((await execAsync('npm run build:client', {cwd: root})).stdout)).to.be.true
      expect(/client assets are up to date/.test((await execAsync('npm run build:client', {cwd: root})).stdout)).to.be.true

      await delay(1000)
      await promisify(fs.utimes)(path.resolve(webpack, 'webpack.config.prod.js'), NaN, NaN)
      expect(/building client bundle/.test((await execAsync('npm run build:client', {cwd: root})).stdout)).to.be.true
      expect(/client assets are up to date/.test((await execAsync('npm run build:client', {cwd: root})).stdout)).to.be.true
    })
  })
  describe('build:server', function () {
    it('only rebuilds when necessary', async function () {
      this.timeout(480000)

      await spawnAsync('npm', ['run', 'build:meteor'], {stdio: 'inherit', cwd: root})

      await promisify(unlinkIfExists)(path.join(build, 'prerender.js'))
      expect(/building server bundle/.test((await execAsync('npm run build:server', {cwd: root})).stdout)).to.be.true
      expect(/server assets are up to date/.test((await execAsync('npm run build:server', {cwd: root})).stdout)).to.be.true

      await delay(1000)
      await promisify(fs.utimes)(path.resolve(webpack, 'webpack.config.server.js'), NaN, NaN)
      expect(/building server bundle/.test((await execAsync('npm run build:server', {cwd: root})).stdout)).to.be.true
      expect(/server assets are up to date/.test((await execAsync('npm run build:server', {cwd: root})).stdout)).to.be.true
    })
  })
})
<commit_msg>test(coverage): try to fix code coverage drop<commit_after>import {expect, assert} from 'chai'
import exec from 'crater-util/lib/exec'
import {childPrinted} from 'async-child-process'
import kill from 'crater-util/lib/kill'
import spawnAsync from 'crater-util/lib/spawnAsync'
import execAsync from 'crater-util/lib/execAsync'
import path from 'path'
import fs from 'fs'
import rimraf from 'rimraf'
import promisify from 'es6-promisify'
import {Collector} from 'istanbul'
import webpackConfig from '../../webpack/webpack.config.dev'
import debug from 'debug'

const browserLogsDebug = debug('crater:logs:browser')

const root = path.resolve(__dirname, '..', '..')
const src = path.join(root, 'src')
const build = path.join(root, 'build')
const webpack = path.join(root, 'webpack')

/* global browser: false */

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

function sharedTests() {
  it('serves page with correct title', async function () {
    expect(await browser.getTitle()).to.equal('Crater')
  })
  it('serves page with correct header', async function () {
    expect(await browser.getText('h1')).to.equal('Welcome to Crater!')
  })
  it('serves up client css', async function () {
    const color = await browser.getCssProperty('h1', 'color')
    expect(color.parsed.hex).to.equal('#333333')
  })
  it('updates the counter', async function () {
    const getCounter = async () => {
      const text = await browser.getText('.counter')
      const match = /(\d+)/.exec(text)
      return match && parseInt(match[1])
    }

    const initCounter = await getCounter()
    await delay(2000)
    expect(await getCounter()).to.be.above(initCounter)
  })
  it('sends Meteor.settings.public to the client', async function () {
    expect(await browser.getText('.settings-test')).to.equal('success')
  })
}

function unlinkIfExists(path, callback) {
  return fs.unlink(path, (err, result) => {
    if (err && /ENOENT/.test(err.message)) err = null
    return callback(err, result)
  })
}

// istanbul ignore next
async function mergeClientCoverage() {
  if (process.env.BABEL_ENV === 'coverage') {
    const collector = new Collector()

    collector.add(global.__coverage__)
    /* eslint-disable no-undef */
    collector.add((await browser.execute(() => window.__coverage__)).value)
    /* eslint-enable no-undef */
    global.__coverage__ = collector.getFinalCoverage()
  }
}

async function navigateTo(url) {
  if (process.env.DUMP_HTTP) {
    const popsicle = require('popsicle')
    const res = await popsicle.get(url)
    /* eslint-disable no-console */
    console.log(`GET ${url} ${res.status}`)
    console.log(res.headers)
    console.log(res.body)
    /* eslint-enable no-console */
  }
  await browser.url(url)
}

async function logBrowserMessages() {
  const logs = (await browser.log('browser')).value
  if (!logs) return
  logs.forEach(({level, message, timestamp}) => {
    const time = new Date(timestamp).toLocaleTimeString()
    browserLogsDebug(`${time} ${level} ${message}`)
  })
}

describe('prod mode', function () {
  let server
  const appFile = path.join(src, 'universal', 'components', 'App.js')
  const serverFile = path.join(src, 'server', 'index.js')
  let appCode, serverCode

  before(async function () {
    this.timeout(600000)
    appCode = await promisify(fs.readFile)(appFile, 'utf8')
    serverCode = await promisify(fs.readFile)(serverFile, 'utf8')
    server = exec('npm run prod', {cwd: root})
    await childPrinted(server, /App is listening on http/i)
    await browser.reload()
    await navigateTo(process.env.ROOT_URL)
  })

  after(async function () {
    this.timeout(600000)
    if (process.env.BABEL_ENV === 'coverage') await mergeClientCoverage()
    if (server) await kill(server, 'SIGINT')
    // restore code in App.js, which (may) have been changed by hot reloading test
    if (appCode) await promisify(fs.writeFile)(appFile, appCode, 'utf8')
    if (serverCode) await promisify(fs.writeFile)(serverFile, serverCode, 'utf8')
    await logBrowserMessages()
  })

  sharedTests()

  if (process.env.BABEL_ENV !== 'coverage') {
    describe('hot reloading', function () {
      it('server restarts when code is changed', async function () {
        this.timeout(60000)
        const serverModified = serverCode.replace(/express\(\)/, 'express()\napp.get("/test", (req, res) => res.send("hello world"))')
        await promisify(fs.writeFile)(serverFile, serverModified, 'utf8')
        await childPrinted(server, /App is listening on http/i)

        const newHeader = 'Welcome to Crater! with hot reloading'
        const appModified = appCode.replace(/Welcome to Crater!/, newHeader)
        await promisify(fs.writeFile)(appFile, appModified, 'utf8')
        await childPrinted(server, /App is listening on http/i)
      })
    })
  }
})

describe('prod mode with DISABLE_FULL_SSR=1', function () {
  let server

  before(async function () {
    this.timeout(240000)
    server = exec('npm run prod', {
      env: {
        ...process.env,
        DISABLE_FULL_SSR: '1',
      },
    })
    await childPrinted(server, /App is listening on http/i)
    await browser.reload()
    await navigateTo(process.env.ROOT_URL)
  })

  it('has hidden element to indicate that full SSR is disabled', async () => {
    assert(
      await browser.isExisting('#full-ssr-disabled'),
      "full SSR doesn't actually seem to be disabled"
    )
  })

  sharedTests()

  after(async function () {
    this.timeout(30000)
    if (process.env.BABEL_ENV === 'coverage') await mergeClientCoverage()
    if (server) await kill(server, 'SIGINT')
    await logBrowserMessages()
  })
})

describe('docker build', function () {
  let server

  before(async function () {
    this.timeout(15 * 60000)
    // run this first, even though it's not necessary, to increase coverage of scripts/build.js
    await spawnAsync('npm', ['run', 'build'], {cwd: root})
    await spawnAsync('npm', ['run', 'build:docker'], {cwd: root})
    server = exec('npm run docker', {
      cwd: root,
      env: {
        ...process.env,
        METEOR_SETTINGS: JSON.stringify({
          public: {
            test: 'success'
          }
        })
      }
    })
    await childPrinted(server, /App is listening on http/i)
    let host
    if (process.env.CI) host = (await execAsync('docker-compose port crater 80', {cwd: root})).stdout.trim()
    else {
      await execAsync('which docker-machine')
        .then(() => host = `192.168.99.100:${process.env.PORT}`)
        .catch(() => host = `localhost:${process.env.PORT}`)
    }
    await browser.reload()
    await navigateTo(`http://${host}`)
  })

  after(async function () {
    this.timeout(20000)
    if (process.env.BABEL_ENV === 'coverage') await mergeClientCoverage()
    await spawnAsync('docker-compose', ['down'], {cwd: root})
    await logBrowserMessages()
  })

  sharedTests()
})

describe('dev mode', function () {
  let server

  const appFile = path.join(src, 'universal', 'components', 'App.js')
  const serverFile = path.join(src, 'server', 'index.js')
  let appCode, serverCode

  before(async function () {
    this.timeout(15 * 60000)
    appCode = await promisify(fs.readFile)(appFile, 'utf8')
    serverCode = await promisify(fs.readFile)(serverFile, 'utf8')
    server = exec('npm start', {cwd: root})
    await Promise.all([
      childPrinted(server, /webpack built [a-z0-9]+ in \d+ms/i),
      childPrinted(server, /App is listening on http/i),
    ])
    await navigateTo(`http://localhost:${webpackConfig.devServer.port}`)
  })

  after(async function () {
    this.timeout(15 * 60000)
    if (process.env.BABEL_ENV === 'coverage') await mergeClientCoverage()
    if (server) await kill(server, 'SIGINT')
    // restore code in App.js, which (may) have been changed by hot reloading test
    if (appCode) await promisify(fs.writeFile)(appFile, appCode, 'utf8')
    if (serverCode) await promisify(fs.writeFile)(serverFile, serverCode, 'utf8')
    await logBrowserMessages()
  })

  sharedTests()

  if (process.env.BABEL_ENV !== 'coverage') {
    describe('hot reloading', function () {
      it('works on the client', async function () {
        this.timeout(40000)
        const newHeader = 'Welcome to Crater! with hot reloading'
        const modified = appCode.replace(/Welcome to Crater!/, newHeader)
        await promisify(fs.writeFile)(appFile, modified, 'utf8')
        await browser.waitUntil(
          () => browser.getText('h1') === newHeader,
          30000,
          'expected header text to hot update within 30s'
        )
      })

      it('server restarts when code is changed', async function () {
        this.timeout(60000)
        const modified = serverCode.replace(/express\(\)/, 'express()\napp.get("/test", (req, res) => res.send("hello world"))')
        await promisify(fs.writeFile)(serverFile, modified, 'utf8')
        await childPrinted(server, /App is listening on http/i)
      })
    })
  }
})

describe('build scripts', function () {
  describe('build:meteor', function () {
    it('only rebuilds when necessary', async function () {
      this.timeout(480000)

      await promisify(rimraf)(path.join(build, 'meteor'))
      expect(/building meteor packages/i.test((await execAsync('npm run build:meteor', {cwd: root})).stdout)).to.be.true
      expect(/build\/meteor is up to date/i.test((await execAsync('npm run build:meteor', {cwd: root})).stdout)).to.be.true

      await delay(1000)
      await promisify(fs.utimes)(path.resolve(root, 'meteor', '.meteor', 'packages'), NaN, NaN)
      expect(/building meteor packages/i.test((await execAsync('npm run build:meteor', {cwd: root})).stdout)).to.be.true
      expect(/build\/meteor is up to date/i.test((await execAsync('npm run build:meteor', {cwd: root})).stdout)).to.be.true
    })
  })
  describe('build:client', function () {
    it('only rebuilds when necessary', async function () {
      this.timeout(480000)

      await spawnAsync('npm', ['run', 'build:meteor'], {stdio: 'inherit', cwd: root})

      await promisify(unlinkIfExists)(path.join(build, 'assets.json'))
      expect(/building client bundle/.test((await execAsync('npm run build:client', {cwd: root})).stdout)).to.be.true
      expect(/client assets are up to date/.test((await execAsync('npm run build:client', {cwd: root})).stdout)).to.be.true

      await delay(1000)
      await promisify(fs.utimes)(path.resolve(webpack, 'webpack.config.prod.js'), NaN, NaN)
      expect(/building client bundle/.test((await execAsync('npm run build:client', {cwd: root})).stdout)).to.be.true
      expect(/client assets are up to date/.test((await execAsync('npm run build:client', {cwd: root})).stdout)).to.be.true
    })
  })
  describe('build:server', function () {
    it('only rebuilds when necessary', async function () {
      this.timeout(480000)

      await spawnAsync('npm', ['run', 'build:meteor'], {stdio: 'inherit', cwd: root})

      await promisify(unlinkIfExists)(path.join(build, 'prerender.js'))
      expect(/building server bundle/.test((await execAsync('npm run build:server', {cwd: root})).stdout)).to.be.true
      expect(/server assets are up to date/.test((await execAsync('npm run build:server', {cwd: root})).stdout)).to.be.true

      await delay(1000)
      await promisify(fs.utimes)(path.resolve(webpack, 'webpack.config.server.js'), NaN, NaN)
      expect(/building server bundle/.test((await execAsync('npm run build:server', {cwd: root})).stdout)).to.be.true
      expect(/server assets are up to date/.test((await execAsync('npm run build:server', {cwd: root})).stdout)).to.be.true
    })
  })
})
<|endoftext|>