<commit_before>(function Communicator(_win, _chrome) {
	var SocketEvent = function SocketEvent(_code) {
		this.code = _code;
	};

	var AcceptEvent = function AcceptEvent(_id, _data) {
		this.id = _id;
		this.data = _data;
		this.output = null;
	};

	var ReceivedEvent = function(_data) {
		this.data = _data;
	};

	var Socket = function Socket(_myIP, _type, _port, _onready, _onerror) {
		// implements the "Socket Interface"
		this.inheritFrom = EventDispatcher;
		this.inheritFrom();
		delete this.inheritFrom;

		var __self__ = this;
		var _socketId = -1;
		var _acceptId = -1;

		var __constructor__ = function() {
	  		_chrome.socket.create(_type, null, onCreate);
		};

		var onCreate = function(info) {
			_socketId = info.socketId;

			if (_type == Socket.TCP) {
				_chrome.socket.listen(
					info.socketId,
					_myIP,
					_port,
					onBind
				);
			} else if (_type == Socket.UDP) {
				_chrome.socket.bind(
					info.socketId,
					_myIP,
					_port,
					onBind
				);
			} else if (_onerror)
				_onerror(new SocketEvent(-1));
		};

		var onBind = function(code) {
			if (code === 0) {
				setupReceive();
				_onready(new SocketEvent(code));
			} else if (_onerror)
				_onerror(new SocketEvent(code));
		};

		var setupReceive = function() {
			if (_type == Socket.TCP)
				_chrome.socket.accept(_socketId, onAccept);
			else if (_type == Socket.UDP) {
				_chrome.socket.recvFrom(_socketId, onReceive);
		};

		var onAccept = function(info) {
			_acceptId = info.socketId;
			_chrome.socket.read(info.socketId, onRead);
		};

		var onReceive = function(info) {
			__self__.dispatchEvent(Socket.RECEIVED, new ReceivedEvent(info.data));
			_chrome.socket.recvFrom(_socketId, onReceive);
		};

		var onRead = function(result) {
			var e = new AcceptEvent(_acceptId, result.data);
			__self__.dispatchEvent(Socket.RECEIVED, e);
			_chrome.socket.write(_acceptId, e.output, onWrite);
		};

		var onWrite = function(e) {
			_chrome.socket.destroy(_acceptId);
			_chrome.socket.accept(_socketId, onAccept);
		};

		var onSend = function(info) {
			// do anything??
		};

		this.send = function(ip, data) {
			if (_type == Socket.UDP)
				_chrome.socket.sendTo(_socketId, data, ip, _port, onSend);
		};

		this.destroy = function() {
			_chrome.socket.destroy(_socketId);
			// ??
		};

		__constructor__();
	};
	Socket.UDP = 'udp';
	Socket.TCP = 'tcp';
	// EVENTS
	Socket.SENT = 0;
	Socket.RECEIVED = 1;

	var ChromeCommunicator = _win.ChromeCommunicator =
	function ChromeCommunicator(_onready, _onerror) {
		// implements the "Communicator Interface"
		var __self__ = this;
		var _ip = null;

		var onNetworkList = function(data) {
			if (!data[0]) {
				if (_onerror)
					_onerror();
				return;
			}
			_ip = data[0].address;
			_onready(_ip);
		};

		this.getIp = function() {
			return _ip;
		};

		this.createSocket = function(type, port) {
			return new Socket(_ip, type, port);
		};

		chrome.getNetworkList(onNetworkList);
	};
})(window, chrome);<commit_msg>ughhh<commit_after><|endoftext|>


<commit_before>//@flow
import * as ActionTypes from './constants';

type State = {
  request: boolean,
  error: string,
  posts: Array<Asset>
};

const initialState = {
  request: false,
  error: '',
  posts: []
};

function assets(state: Object = initialState, action: Object): State {
  switch(action.type) {
    case ActionTypes.ASSETS_REQUEST:
      return Object.assign({}, state, {
        request: true,
        posts: []
      });
    case ActionTypes.ASSETS_SUCCESS:
      return Object.assign({}, state, {
        request: false,
        error: '',
        posts: action.posts
      });
    case ActionTypes.ASSETS_ERROR:
      return Object.assign({}, state, {
        request: false,
        error: action.error
      });
    case ActionTypes.ASSETS_DELETE_SUCCESS:
      return Object.assign({}, state, {
        request: false,
        error: ''
      });
    default:
      return state;
  }
}

export default assets;
<commit_msg>Simplify Assets reducer.<commit_after>//@flow
import * as ActionTypes from './constants';

type State = {
  request: boolean,
  error: string,
  posts: Array<Asset>
};

const initialState = {
  request: false,
  error: '',
  posts: []
};

function assets(state: Object = initialState, action: Object): State {
  switch(action.type) {
    case ActionTypes.ASSETS_REQUEST:
      return {
        ...state,
        request: true,
        posts: []
      };
    case ActionTypes.ASSETS_SUCCESS:
      return {
        ...state,
        request: false,
        error: '',
        posts: action.posts
      };
    case ActionTypes.ASSETS_ERROR:
      return {
        ...state,
        request: false,
        error: action.error
      };
    case ActionTypes.ASSETS_DELETE_SUCCESS:
      return {
        ...state,
        request: false,
        error: ''
      };
    default:
      return state;
  }
}

export default assets;
<|endoftext|>


<commit_before>const stripHtml = require('string-strip-html');

let production;
let linksArray;

function fetchContent() {
	let finalHtml = '';
	$('.sc-blog .spinner').show();
	$('.sc-blog .placeholder').hide();

	const changePage = () => {
		$('.sc-blog .loading').remove();
		finalHtml = finalHtml
			.replace(/x<[/]td>/g, '	');
		$('.sc-blog .content').html(stripHtml(finalHtml,
			{ onlyStripTags: ['script', 'style'] }));
		$('.sc-blog .content').css('opacity', '1');
	};

	const promiseFunc = new Promise((resolve) => {
		$.ajax({
			url: 'ghost/landing-page/',
			type: 'GET',
			dataType: 'json',
			contentType: 'application/json',
			timeout: 8000,
		})
			.then((result) => {
				const regexHash = /\#{1}[a-zA-Z--]+/g;
				const regexAsterisk = /\~{1}[a-zA-Z--]+/g;
				if (production) {
					linksArray = result.pages[0].html.match(regexHash);
				} else {
					linksArray = result.pages[0].html.match(regexAsterisk);
				}
				resolve();
			})
			.fail(() => {
				$('.sc-blog .spinner').hide();
				$('.sc-blog .placeholder').show();
			});
	});

	promiseFunc
		.then(() => {
			linksArray.forEach((url, index) => {
				url = url.substr(1);
				$.ajax({
					url: `/ghost/${url}/`,
					type: 'GET',
					dataType: 'json',
					contentType: 'application/json',
					timeout: 8000,
					async: false,
				})
					.then((result) => {
						finalHtml += result.pages[0].html;
						if (index === linksArray.length - 1) {
							changePage();
						}
					})
					.fail(() => {
						$('.sc-blog .spinner').hide();
						$('.sc-blog .placeholder').show();
					});
			});
		});
}

$(document).ready(() => {
	production = window.production === 'true';
	fetchContent();
	$('.sc-blog .placeholder button').on('click', fetchContent);
});
<commit_msg>codacy error fix<commit_after>const stripHtml = require('string-strip-html');

let production;
let linksArray;

function fetchContent() {
	let finalHtml = '';
	$('.sc-blog .spinner').show();
	$('.sc-blog .placeholder').hide();

	const changePage = () => {
		$('.sc-blog .loading').remove();
		finalHtml = finalHtml
			.replace(/x<[/]td>/g, '	');
		$('.sc-blog .content').html(stripHtml(finalHtml,
			{ onlyStripTags: ['script', 'style'] }));
		$('.sc-blog .content').css('opacity', '1');
	};

	const promiseFunc = new Promise((resolve) => {
		$.ajax({
			url: 'ghost/landing-page/',
			type: 'GET',
			dataType: 'json',
			contentType: 'application/json',
			timeout: 8000,
		})
			.then((result) => {
				const regexHash = /\#{1}[a-zA-Z--]+/g;
				const regexAsterisk = /\~{1}[a-zA-Z--]+/g;
				if (production) {
					linksArray = result.pages[0].html.match(regexHash);
				} else {
					linksArray = result.pages[0].html.match(regexAsterisk);
				}
				resolve();
			})
			.fail(() => {
				$('.sc-blog .spinner').hide();
				$('.sc-blog .placeholder').show();
			});
	});

	promiseFunc
		.then(() => {
			linksArray.forEach((url, index) => {
				urlCut = url.substr(1);
				$.ajax({
					url: `/ghost/${urlCut}/`,
					type: 'GET',
					dataType: 'json',
					contentType: 'application/json',
					timeout: 8000,
					async: false,
				})
					.then((result) => {
						finalHtml += result.pages[0].html;
						if (index === linksArray.length - 1) {
							changePage();
						}
					})
					.fail(() => {
						$('.sc-blog .spinner').hide();
						$('.sc-blog .placeholder').show();
					});
			});
		});
}

$(document).ready(() => {
	production = window.production === 'true';
	fetchContent();
	$('.sc-blog .placeholder button').on('click', fetchContent);
});
<|endoftext|>


<commit_before>$(function() {
	$.getJSON( "data.json", function( ajaxdata ) {
    	var items = [];
 		var config = {
 			type: 'line',
 			data: {
 				labels: ["-95", "-90", "-85", "-80", "-75", "-70", "-65", "-60", "-55", "-50", "-45", "-40", "-35", "-30", "-25", "-20", "-15", "-10", "-5", "0"],
 				datasets: [{
 					label: "Temperature (" + String.fromCharCode(176) + "C)",
 					backgroundColor: window.chartColors.red,
 					borderColor: window.chartColors.red,
 					data: ajaxdata.ambientTemperature,
 					fill: false,
 				}]
 			},
 			options: {
 				responsive: true,
 				tooltips: {
 					mode: 'index',
 					intersect: false,
 				},
 				hover: {
 				mode: 'nearest',
 					intersect: true
 				},
 				scales: {
 				xAxes: [{
 						display: true,
 						scaleLabel: {
 							display: true,
 							labelString: 'Time (Mins ago)',
 							fontFamily: "sans-serif"
 						}
 					}],
 					yAxes: [{
 						display: true,
 						scaleLabel: {
 						display: true,
 							labelString: 'Temperature'
 						}
 					}]
 				}
 		}
 		};

			var ctx2 = document.getElementById("ambient").getContext("2d");
 			window.myLine = new Chart(ctx2, config);
		});
	window.setInterval(function () {
		document.getElementById("measurementTime").innerText = parseInt(document.getElementById("measurementTime").innerText) + 1;
	}, 1000);
  });
$(function() {
	$.getJSON( "data.json", function( ajaxdata ) {
    	var items = [];
 		var config = {
 			type: 'line',
 			data: {
 				labels: ["-95", "-90", "-85", "-80", "-75", "-70", "--65", "-60", "-55", "-50", "-45", "-40", "-35", "-30", "-25", "-20", "-15", "-10", "-5", "0"],
 				datasets: [{
 					label: "Humidity (%)",
 					backgroundColor: window.chartColors.red,
 					borderColor: window.chartColors.red,
 					data: ajaxdata.humidity,
 					fill: false,
 				}]
 			},
 			options: {
 				responsive: true,
 				tooltips: {
 					mode: 'index',
 					intersect: false,
 				},
 				hover: {
 				mode: 'nearest',
 					intersect: true
 				},
 				scales: {
 				xAxes: [{
 						display: true,
 						scaleLabel: {
 							display: true,
 							labelString: 'Time (Mins ago)',
 							fontFamily: "sans-serif"
 						}
 					}],
 					yAxes: [{
 						display: true,
						min: 10,
						max: 95,
 						scaleLabel: {
 						display: true,
 							labelString: 'Humidity (%)'
 						}
 					}]
 				}
 		}
 		};

			var ctx2 = document.getElementById("humidity").getContext("2d");
 			window.myLine = new Chart(ctx2, config);
		});
  });
$(function() {
	$.getJSON( "data.json", function( ajaxdata ) {
    	var items = [];
 		var config = {
 			type: 'line',
 			data: {
 				labels: ["-95", "-90", "-85", "-80", "-75", "-70", "--65", "-60", "-55", "-50", "-45", "-40", "-35", "-30", "-25", "-20", "-15", "-10", "-5", "0"],
 				datasets: [{
 					label: "Pressure (hPa)",
 					backgroundColor: window.chartColors.red,
 					borderColor: window.chartColors.red,
 					data: ajaxdata.pressure,
 					fill: false,
 				}]
 			},
 			options: {
 				responsive: true,
 				tooltips: {
 					mode: 'index',
 					intersect: false,
 				},
 				hover: {
 				mode: 'nearest',
 					intersect: true
 				},
 				scales: {
 				xAxes: [{
 						display: true,
 						scaleLabel: {
 							display: true,
 							labelString: 'Time (Mins ago)',
 							fontFamily: "sans-serif"
 						}
 					}],
 					yAxes: [{
 						display: true,
 						scaleLabel: {
 						display: true,
 							labelString: 'Humidity (%)'
 						}
 					}]
 				}
 		}
 		};

			var ctx2 = document.getElementById("pressure").getContext("2d");
 			window.myLine = new Chart(ctx2, config);
		});
  });
<commit_msg>fix scale<commit_after>$(function() {
	$.getJSON( "data.json", function( ajaxdata ) {
    	var items = [];
 		var config = {
 			type: 'line',
 			data: {
 				labels: ["-95", "-90", "-85", "-80", "-75", "-70", "-65", "-60", "-55", "-50", "-45", "-40", "-35", "-30", "-25", "-20", "-15", "-10", "-5", "0"],
 				datasets: [{
 					label: "Temperature (" + String.fromCharCode(176) + "C)",
 					backgroundColor: window.chartColors.red,
 					borderColor: window.chartColors.red,
 					data: ajaxdata.ambientTemperature,
 					fill: false,
 				}]
 			},
 			options: {
 				responsive: true,
 				tooltips: {
 					mode: 'index',
 					intersect: false,
 				},
 				hover: {
 				mode: 'nearest',
 					intersect: true
 				},
 				scales: {
 				xAxes: [{
 						display: true,
 						scaleLabel: {
 							display: true,
 							labelString: 'Time (Mins ago)',
 							fontFamily: "sans-serif"
 						}
 					}],
 					yAxes: [{
 						display: true,
 						scaleLabel: {
 						display: true,
 							labelString: 'Temperature'
 						}
 					}]
 				}
 		}
 		};

			var ctx2 = document.getElementById("ambient").getContext("2d");
 			window.myLine = new Chart(ctx2, config);
		});
	window.setInterval(function () {
		document.getElementById("measurementTime").innerText = parseInt(document.getElementById("measurementTime").innerText) + 1;
	}, 1000);
  });
$(function() {
	$.getJSON( "data.json", function( ajaxdata ) {
    	var items = [];
 		var config = {
 			type: 'line',
 			data: {
 				labels: ["-95", "-90", "-85", "-80", "-75", "-70", "--65", "-60", "-55", "-50", "-45", "-40", "-35", "-30", "-25", "-20", "-15", "-10", "-5", "0"],
 				datasets: [{
 					label: "Humidity (%)",
 					backgroundColor: window.chartColors.red,
 					borderColor: window.chartColors.red,
 					data: ajaxdata.humidity,
 					fill: false,
 				}]
 			},
 			options: {
 				responsive: true,
 				tooltips: {
 					mode: 'index',
 					intersect: false,
 				},
 				hover: {
 				mode: 'nearest',
 					intersect: true
 				},
 				scales: {
 				xAxes: [{
 						display: true,
 						scaleLabel: {
 							display: true,
 							labelString: 'Time (Mins ago)',
 							fontFamily: "sans-serif"
 						}
 					}],
 					yAxes: [{
 						display: true,
						ticks: {
							min: 10,
							max: 95,
						},
 						scaleLabel: {
 						display: true,
 							labelString: 'Humidity (%)'
 						}
 					}]
 				}
 		}
 		};

			var ctx2 = document.getElementById("humidity").getContext("2d");
 			window.myLine = new Chart(ctx2, config);
		});
  });
$(function() {
	$.getJSON( "data.json", function( ajaxdata ) {
    	var items = [];
 		var config = {
 			type: 'line',
 			data: {
 				labels: ["-95", "-90", "-85", "-80", "-75", "-70", "--65", "-60", "-55", "-50", "-45", "-40", "-35", "-30", "-25", "-20", "-15", "-10", "-5", "0"],
 				datasets: [{
 					label: "Pressure (hPa)",
 					backgroundColor: window.chartColors.red,
 					borderColor: window.chartColors.red,
 					data: ajaxdata.pressure,
 					fill: false,
 				}]
 			},
 			options: {
 				responsive: true,
 				tooltips: {
 					mode: 'index',
 					intersect: false,
 				},
 				hover: {
 				mode: 'nearest',
 					intersect: true
 				},
 				scales: {
 				xAxes: [{
 						display: true,
 						scaleLabel: {
 							display: true,
 							labelString: 'Time (Mins ago)',
 							fontFamily: "sans-serif"
 						}
 					}],
 					yAxes: [{
 						display: true,
 						scaleLabel: {
 						display: true,
 							labelString: 'Humidity (%)'
 						}
 					}]
 				}
 		}
 		};

			var ctx2 = document.getElementById("pressure").getContext("2d");
 			window.myLine = new Chart(ctx2, config);
		});
  });
<|endoftext|>


<commit_before>this.mmooc = this.mmooc || {};

this.mmooc.discussionTopics = function () {
    return {
        setDiscussionTopicPubDate: function(discussionTopic) {
            if(discussionTopic) {
              var formattedDate = mmooc.util.formattedDate(discussionTopic.posted_at);
              var pubDate = $("
" + formattedDate + "
");
              $(pubDate).prependTo('#discussion_topic .discussion-header-right');
            }
        },

        alterDiscussionReadStateLook: function() {
            var self = this;
            $('body').on('click', '.read-unread-button', function (){
               $(this).toggleClass('read');
               $(this).closest(".entry-content").siblings(".discussion-read-state-btn").click();
               self.toggleReadUnreadButton($(this));
           });

            var checkExist = setInterval(function() {
                if ($('.discussion-read-state-btn').length) {
                  clearInterval(checkExist);
                  var readUnreadButton = $("
Marker som lest
");
                  readUnreadButton.appendTo('.discussion_entry:not(.deleted-discussion-entry) .entry-header');
                  self.toggleReadUnreadButton($(this).closest(".discussion_entry").find("read-unread-button"));
                }
            }, 100);
        },

        toggleReadUnreadButton: function(button) {
            $(".discussion-read-state-btn").each(function(index) {
                    var button = $(this).siblings(".entry-content").find(".read-unread-button");
                    if($(this).parent().hasClass("unread")) {
                        button.text('Marker som lest');
                        button.addClass('read');
                    }
                    else {
                        button.text('Marker som ulest');
                        button.removeClass('read');
                    }
                });
        },
        setDiscussionsListUnreadClass: function() {
          var checkExist = setInterval(function() {
            if ($("#open-discussions .ig-list .discussion").length) {
              clearInterval(checkExist);
              $("#open-discussions .ig-list .discussion").each(function() {
                var unread = $(this).find('.new-items').text();
                if(unread.indexOf('0') == -1) {
                  $(this).addClass('unread');
                }
              });
            }
          }, 100);
        },
        insertSearchButton: function() {
          $('.index_view_filter_form').append('<button class="btn btn-discussion-search">');
        },
        printDiscussionUnreadCount: function(modules, context) {
            var discussionItems = mmooc.discussionTopics.getDiscussionItems(modules);
            var courseId = mmooc.api.getCurrentCourseId();
            var totalUnread = 0;
            var asyncsDone = 0;
            var groupDiscussionTopics = [];
            for (var i = 0; i < discussionItems.length; i++) {
                var contentId = discussionItems[i].content_id;
                mmooc.api.getDiscussionTopic(courseId, contentId, function(discussionTopic) {
                    if (discussionTopic) {
                        if (discussionTopic.group_category_id) {
                            groupDiscussionTopics.push(discussionTopic);
                        }
                        else {
                            if (discussionTopic.unread_count > 0) {
                                if (context == "coursepage") {
                                    mmooc.discussionTopics.printUnreadCountOnIcon(discussionTopic.unread_count, discussionTopic.id);
                                }
                                totalUnread = totalUnread + discussionTopic.unread_count;
                            }
                        }
                    }
                    asyncsDone++;
                    if (asyncsDone == discussionItems.length) {
                        if (totalUnread > 0 && groupDiscussionTopics.length == 0) {
                            mmooc.discussionTopics.printUnreadCountInTab(totalUnread);
                            if (context == "discussionslist") {
                                return;
                            }
                        }
                        else if (groupDiscussionTopics.length > 0) {
                            mmooc.discussionTopics.printGroupDiscussionUnreadCount(courseId, groupDiscussionTopics, totalUnread, context);
                        }
                        else {
                            return;
                        }
                    }
                });
            }
        },
        printGroupDiscussionUnreadCount: function(courseId, groupDiscussionTopics, totalUnread, context) {
            // if teacher or admin
            if (mmooc.util.isTeacherOrAdmin()) {
                var params = { user_id: "self" };
                var asyncsDone = 0;
                var sectionNames = [];
                // get enrollments and sections for current user
                mmooc.api.getEnrollmentsForCourse(courseId, params, function(enrollments) {
                    for (var i = 0; i < enrollments.length; i++) {
                        var sectionId = enrollments[i].course_section_id;
                        mmooc.api.getSingleSection(sectionId, function(section) {
                            sectionNames.push(section.name);
                            asyncsDone++;
                            if (asyncsDone == enrollments.length) {
                                mmooc.api.getGroupsInCourse(courseId, function(groups) {
                                    var totalAsyncs = 0;
                                    var allUnreadCounts = [];
                                    asyncsDone = 0;
                                    for (var j = 0; j < groups.length; j++) {
                                        for (var k = 0; k < sectionNames.length; k++) {
                                            // check if group name equals section name then get discussion topics
                                            if (groups[j].name == sectionNames[k]) {
                                                var groupId = groups[j].id;
                                                totalAsyncs++;
                                                mmooc.api.getGroupDiscussionTopics(groupId, function(discussions) {
                                                    for (var l = 0; l < discussions.length; l++) {
                                                        for (var m = 0; m < groupDiscussionTopics.length; m++) {
                                                            // check if group discussion is exists current course
                                                            if (discussions[l].root_topic_id == groupDiscussionTopics[m].id) {
                                                                if (discussions[l].unread_count > 0) {
                                                                    var rootTopicUnreadCountsObj = {
                                                                        rootTopicId: discussions[l].root_topic_id,
                                                                        unreadCount: discussions[l].unread_count
                                                                    }
                                                                    allUnreadCounts.push(rootTopicUnreadCountsObj);
                                                                    totalUnread = totalUnread + discussions[l].unread_count;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    asyncsDone++;
                                                    if (asyncsDone == totalAsyncs) {
                                                        mmooc.discussionTopics.printUnreadCountInTab(totalUnread);
                                                        if (context == "coursepage" || context == "discussionslist") {
                                                            var unreadCountForRootTopic = 0;
                                                            var totalRootTopicUnreadCounts = [];
                                                            // add together unread counts with same root topic id
                                                            for (var n = 0; n < allUnreadCounts.length; n++) {
                                                                for (var o = 0; o < allUnreadCounts.length; o++) {
                                                                    if (allUnreadCounts[n].rootTopicId == allUnreadCounts[o].rootTopicId) {
                                                                        unreadCountForRootTopic = unreadCountForRootTopic + allUnreadCounts[o].unreadCount;
                                                                    }
                                                                }
                                                                var totalRootTopicUnreadCountsObj = {
                                                                    rootTopicId: allUnreadCounts[n].rootTopicId,
                                                                    unreadCount: unreadCountForRootTopic
                                                                }
                                                                totalRootTopicUnreadCounts.push(totalRootTopicUnreadCountsObj);
                                                                unreadCountForRootTopic = 0;
                                                            }
                                                            // only print unread count for unique topic ids
                                                            var uniqueTotalRootTopicUnreadCounts = [];
                                                            var used = [];
                                                            for (var p = 0; p < totalRootTopicUnreadCounts.length; p++) {
                                                                if (used.indexOf(totalRootTopicUnreadCounts[p].rootTopicId) == -1) {
                                                                    var totalRootTopicUnreadCountsObj = {
                                                                        rootTopicId: totalRootTopicUnreadCounts[p].rootTopicId,
                                                                        unreadCount: totalRootTopicUnreadCounts[p].unreadCount
                                                                    }
                                                                    uniqueTotalRootTopicUnreadCounts.push(totalRootTopicUnreadCountsObj);
                                                                    used.push(totalRootTopicUnreadCounts[p].rootTopicId);
                                                                }
                                                            }// end for totalRootTopicUnreadCounts.length
                                                            if (context == "coursepage") {
                                                                for (var q = 0; q < uniqueTotalRootTopicUnreadCounts.length; q++) {
                                                                    mmooc.discussionTopics.printUnreadCountOnIcon(uniqueTotalRootTopicUnreadCounts[q].unreadCount, uniqueTotalRootTopicUnreadCounts[q].rootTopicId);
                                                                }
                                                            }
                                                            if (context == "discussionslist") {
                                                                mmooc.discussionTopics.printUnreadCountInDiscussionsList(uniqueTotalRootTopicUnreadCounts);
                                                            }// end if discussions list
                                                        }// end if coursepage or discussions list
                                                    }// end if asyncsDone
                                                });// end group discussion topics async call
                                            }// end if group name equals section name
                                        }// end for sectionNames.length
                                    }// end for groups.length
                                });// end for groups in course async call
                            }// end if asyncsDone
                        });// end section async call
                    }// end for enrollments.length
                });// end enrollments async call
            }// end if teacher or admin
            // if student
            else {
                mmooc.api.getUserGroups(function(groups) {
                    if (groups.length == 0 && totalUnread > 0) {
                        mmooc.discussionTopics.printUnreadCountInTab(totalUnread);
                    }
                    for (var i = 0; i < groups.length; i++) {
                        for (var j = 0; j < groupDiscussionTopics.length; j++) {
                            if (groups[i].course_id == courseId && groups[i].group_category_id == groupDiscussionTopics[j].group_category_id) {
                                groupId = groups[i].id;
                                mmooc.api.getGroupDiscussionTopics(groupId, function(discussions) {
                                    var totalRootTopicUnreadCounts = [];
                                    for (var k = 0; k < discussions.length; k++) {
                                        if (discussions[k].unread_count > 0) {
                                            if (context == "coursepage") {
                                                mmooc.discussionTopics.printUnreadCountOnIcon(discussions[k].unread_count, discussions[k].root_topic_id);
                                            }
                                            if (context == "discussionslist") {
                                                var totalRootTopicUnreadCountsObj = {
                                                    rootTopicId: discussions[k].root_topic_id,
                                                    unreadCount: discussions[k].unread_count
                                                }
                                                totalRootTopicUnreadCounts.push(totalRootTopicUnreadCountsObj);
                                            }
                                            totalUnread += discussions[k].unread_count;
                                        }
                                    }
                                    if (totalUnread > 0) {
                                        mmooc.discussionTopics.printUnreadCountInTab(totalUnread);
                                    }
                                    if (context == "discussionslist") {
                                        mmooc.discussionTopics.printUnreadCountInDiscussionsList(totalRootTopicUnreadCounts);
                                    }
                                }); // end group discussions async call
                            }
                            break;
                        } // end for groupDiscussionTopics.length
                        break;
                    } // end for groupDiscussionTopics.length
                }); // end user groups async call
            }
        },
        getDiscussionItems: function(modules) {
            var discussionItems = [];
            for (var i = 0; i < modules.length; i++) {
                for (var j = 0; j < modules[i].items.length; j++) {
                    if (modules[i].items[j].type == 'Discussion') {
                        discussionItems.push(modules[i].items[j]);
                    }
                }
            }
            return discussionItems;
        },
        printUnreadCountOnIcon: function(unread, discussionId) {
            $(".discussion-unread-tag.discussion-id-" + discussionId).html("
" + unread + "
");
        },
        printUnreadCountInTab: function(totalUnread) {
            $(".mmooc-course-tab a").each(function() {
                if ($(this).text() == "Diskusjoner") {
                    $(this).parent().append("" + totalUnread + "")
                }
            });
        },
        printUnreadCountInDiscussionsList: function(groupDiscussionsUnreadCount) {
            var checkExist = setInterval(function() {
                if ($("#open-discussions .ig-list .discussion").length) {
                    clearInterval(checkExist);
                    $("#open-discussions .ig-list .discussion").each(function() {
                        for (var i = 0; i < groupDiscussionsUnreadCount.length; i++) {
                            if($(this).attr("data-id") == groupDiscussionsUnreadCount[i].rootTopicId) {
                                $(this).find('.new-items').text(groupDiscussionsUnreadCount[i].unreadCount);
                                $(this).addClass("unread");
                            }
                        }
                    });
                    mmooc.discussionTopics.showUnreadCountInDiscussionList();
                }
            }, 100);
        },
        hideUnreadCountInDiscussionList: function() {
            var checkExist = setInterval(function() {
                if ($("#open-discussions .ig-list .discussion").length) {
                    clearInterval(checkExist);
                    $("#open-discussions .ig-list .discussion").each(function() {
                        $(this).find('.new-items').hide();
                        $(this).find('.new-items').parent().prepend("");
                    });
                }
            }, 100);
        },
        showUnreadCountInDiscussionList: function() {
            $("#open-discussions .ig-list .discussion .loading-gif").remove();
            $("#open-discussions .ig-list .discussion").each(function() {
                $(this).find('.new-items').show();
            });
        }
    };
}();

<commit_msg>MAT-260: Fixed for-loop break-bug<commit_after>this.mmooc = this.mmooc || {};

this.mmooc.discussionTopics = function () {
    return {
        setDiscussionTopicPubDate: function(discussionTopic) {
            if(discussionTopic) {
              var formattedDate = mmooc.util.formattedDate(discussionTopic.posted_at);
              var pubDate = $("
" + formattedDate + "
");
              $(pubDate).prependTo('#discussion_topic .discussion-header-right');
            }
        },

        alterDiscussionReadStateLook: function() {
            var self = this;
            $('body').on('click', '.read-unread-button', function (){
               $(this).toggleClass('read');
               $(this).closest(".entry-content").siblings(".discussion-read-state-btn").click();
               self.toggleReadUnreadButton($(this));
           });

            var checkExist = setInterval(function() {
                if ($('.discussion-read-state-btn').length) {
                  clearInterval(checkExist);
                  var readUnreadButton = $("
Marker som lest
");
                  readUnreadButton.appendTo('.discussion_entry:not(.deleted-discussion-entry) .entry-header');
                  self.toggleReadUnreadButton($(this).closest(".discussion_entry").find("read-unread-button"));
                }
            }, 100);
        },

        toggleReadUnreadButton: function(button) {
            $(".discussion-read-state-btn").each(function(index) {
                    var button = $(this).siblings(".entry-content").find(".read-unread-button");
                    if($(this).parent().hasClass("unread")) {
                        button.text('Marker som lest');
                        button.addClass('read');
                    }
                    else {
                        button.text('Marker som ulest');
                        button.removeClass('read');
                    }
                });
        },
        setDiscussionsListUnreadClass: function() {
          var checkExist = setInterval(function() {
            if ($("#open-discussions .ig-list .discussion").length) {
              clearInterval(checkExist);
              $("#open-discussions .ig-list .discussion").each(function() {
                var unread = $(this).find('.new-items').text();
                if(unread.indexOf('0') == -1) {
                  $(this).addClass('unread');
                }
              });
            }
          }, 100);
        },
        insertSearchButton: function() {
          $('.index_view_filter_form').append('<button class="btn btn-discussion-search">');
        },
        printDiscussionUnreadCount: function(modules, context) {
            var discussionItems = mmooc.discussionTopics.getDiscussionItems(modules);
            var courseId = mmooc.api.getCurrentCourseId();
            var totalUnread = 0;
            var asyncsDone = 0;
            var groupDiscussionTopics = [];
            for (var i = 0; i < discussionItems.length; i++) {
                var contentId = discussionItems[i].content_id;
                mmooc.api.getDiscussionTopic(courseId, contentId, function(discussionTopic) {
                    if (discussionTopic) {
                        if (discussionTopic.group_category_id) {
                            groupDiscussionTopics.push(discussionTopic);
                        }
                        else {
                            if (discussionTopic.unread_count > 0) {
                                if (context == "coursepage") {
                                    mmooc.discussionTopics.printUnreadCountOnIcon(discussionTopic.unread_count, discussionTopic.id);
                                }
                                totalUnread = totalUnread + discussionTopic.unread_count;
                            }
                        }
                    }
                    asyncsDone++;
                    if (asyncsDone == discussionItems.length) {
                        if (totalUnread > 0 && groupDiscussionTopics.length == 0) {
                            mmooc.discussionTopics.printUnreadCountInTab(totalUnread);
                            if (context == "discussionslist") {
                                return;
                            }
                        }
                        else if (groupDiscussionTopics.length > 0) {
                            mmooc.discussionTopics.printGroupDiscussionUnreadCount(courseId, groupDiscussionTopics, totalUnread, context);
                        }
                        else {
                            return;
                        }
                    }
                });
            }
        },
        printGroupDiscussionUnreadCount: function(courseId, groupDiscussionTopics, totalUnread, context) {
            // if teacher or admin
            if (mmooc.util.isTeacherOrAdmin()) {
                var params = { user_id: "self" };
                var asyncsDone = 0;
                var sectionNames = [];
                // get enrollments and sections for current user
                mmooc.api.getEnrollmentsForCourse(courseId, params, function(enrollments) {
                    for (var i = 0; i < enrollments.length; i++) {
                        var sectionId = enrollments[i].course_section_id;
                        mmooc.api.getSingleSection(sectionId, function(section) {
                            sectionNames.push(section.name);
                            asyncsDone++;
                            if (asyncsDone == enrollments.length) {
                                mmooc.api.getGroupsInCourse(courseId, function(groups) {
                                    var totalAsyncs = 0;
                                    var allUnreadCounts = [];
                                    asyncsDone = 0;
                                    for (var j = 0; j < groups.length; j++) {
                                        for (var k = 0; k < sectionNames.length; k++) {
                                            // check if group name equals section name then get discussion topics
                                            if (groups[j].name == sectionNames[k]) {
                                                var groupId = groups[j].id;
                                                totalAsyncs++;
                                                mmooc.api.getGroupDiscussionTopics(groupId, function(discussions) {
                                                    for (var l = 0; l < discussions.length; l++) {
                                                        for (var m = 0; m < groupDiscussionTopics.length; m++) {
                                                            // check if group discussion is exists current course
                                                            if (discussions[l].root_topic_id == groupDiscussionTopics[m].id) {
                                                                if (discussions[l].unread_count > 0) {
                                                                    var rootTopicUnreadCountsObj = {
                                                                        rootTopicId: discussions[l].root_topic_id,
                                                                        unreadCount: discussions[l].unread_count
                                                                    }
                                                                    allUnreadCounts.push(rootTopicUnreadCountsObj);
                                                                    totalUnread = totalUnread + discussions[l].unread_count;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    asyncsDone++;
                                                    if (asyncsDone == totalAsyncs) {
                                                        mmooc.discussionTopics.printUnreadCountInTab(totalUnread);
                                                        if (context == "coursepage" || context == "discussionslist") {
                                                            var unreadCountForRootTopic = 0;
                                                            var totalRootTopicUnreadCounts = [];
                                                            // add together unread counts with same root topic id
                                                            for (var n = 0; n < allUnreadCounts.length; n++) {
                                                                for (var o = 0; o < allUnreadCounts.length; o++) {
                                                                    if (allUnreadCounts[n].rootTopicId == allUnreadCounts[o].rootTopicId) {
                                                                        unreadCountForRootTopic = unreadCountForRootTopic + allUnreadCounts[o].unreadCount;
                                                                    }
                                                                }
                                                                var totalRootTopicUnreadCountsObj = {
                                                                    rootTopicId: allUnreadCounts[n].rootTopicId,
                                                                    unreadCount: unreadCountForRootTopic
                                                                }
                                                                totalRootTopicUnreadCounts.push(totalRootTopicUnreadCountsObj);
                                                                unreadCountForRootTopic = 0;
                                                            }
                                                            // only print unread count for unique topic ids
                                                            var uniqueTotalRootTopicUnreadCounts = [];
                                                            var used = [];
                                                            for (var p = 0; p < totalRootTopicUnreadCounts.length; p++) {
                                                                if (used.indexOf(totalRootTopicUnreadCounts[p].rootTopicId) == -1) {
                                                                    var totalRootTopicUnreadCountsObj = {
                                                                        rootTopicId: totalRootTopicUnreadCounts[p].rootTopicId,
                                                                        unreadCount: totalRootTopicUnreadCounts[p].unreadCount
                                                                    }
                                                                    uniqueTotalRootTopicUnreadCounts.push(totalRootTopicUnreadCountsObj);
                                                                    used.push(totalRootTopicUnreadCounts[p].rootTopicId);
                                                                }
                                                            }// end for totalRootTopicUnreadCounts.length
                                                            if (context == "coursepage") {
                                                                for (var q = 0; q < uniqueTotalRootTopicUnreadCounts.length; q++) {
                                                                    mmooc.discussionTopics.printUnreadCountOnIcon(uniqueTotalRootTopicUnreadCounts[q].unreadCount, uniqueTotalRootTopicUnreadCounts[q].rootTopicId);
                                                                }
                                                            }
                                                            if (context == "discussionslist") {
                                                                mmooc.discussionTopics.printUnreadCountInDiscussionsList(uniqueTotalRootTopicUnreadCounts);
                                                            }// end if discussions list
                                                        }// end if coursepage or discussions list
                                                    }// end if asyncsDone
                                                });// end group discussion topics async call
                                            }// end if group name equals section name
                                        }// end for sectionNames.length
                                    }// end for groups.length
                                });// end for groups in course async call
                            }// end if asyncsDone
                        });// end section async call
                    }// end for enrollments.length
                });// end enrollments async call
            }// end if teacher or admin
            // if student
            else {
                mmooc.api.getUserGroups(function(groups) {
                    if (groups.length == 0 && totalUnread > 0) {
                        mmooc.discussionTopics.printUnreadCountInTab(totalUnread);
                    }
                    for (var i = 0; i < groups.length; i++) {
                        for (var j = 0; j < groupDiscussionTopics.length; j++) {
                            if (groups[i].course_id == courseId && groups[i].group_category_id == groupDiscussionTopics[j].group_category_id) {
                                groupId = groups[i].id;
                                mmooc.api.getGroupDiscussionTopics(groupId, function(discussions) {
                                    var totalRootTopicUnreadCounts = [];
                                    for (var k = 0; k < discussions.length; k++) {
                                        if (discussions[k].unread_count > 0) {
                                            if (context == "coursepage") {
                                                mmooc.discussionTopics.printUnreadCountOnIcon(discussions[k].unread_count, discussions[k].root_topic_id);
                                            }
                                            if (context == "discussionslist") {
                                                var totalRootTopicUnreadCountsObj = {
                                                    rootTopicId: discussions[k].root_topic_id,
                                                    unreadCount: discussions[k].unread_count
                                                }
                                                totalRootTopicUnreadCounts.push(totalRootTopicUnreadCountsObj);
                                            }
                                            totalUnread += discussions[k].unread_count;
                                        }
                                    }
                                    if (totalUnread > 0) {
                                        mmooc.discussionTopics.printUnreadCountInTab(totalUnread);
                                    }
                                    if (context == "discussionslist") {
                                        mmooc.discussionTopics.printUnreadCountInDiscussionsList(totalRootTopicUnreadCounts);
                                    }
                                }); // end group discussions async call
                                break;
                            }
                        } // end for groupDiscussionTopics.length
                    } // end for groupDiscussionTopics.length
                }); // end user groups async call
            }
        },
        getDiscussionItems: function(modules) {
            var discussionItems = [];
            for (var i = 0; i < modules.length; i++) {
                for (var j = 0; j < modules[i].items.length; j++) {
                    if (modules[i].items[j].type == 'Discussion') {
                        discussionItems.push(modules[i].items[j]);
                    }
                }
            }
            return discussionItems;
        },
        printUnreadCountOnIcon: function(unread, discussionId) {
            $(".discussion-unread-tag.discussion-id-" + discussionId).html("
" + unread + "
");
        },
        printUnreadCountInTab: function(totalUnread) {
            $(".mmooc-course-tab a").each(function() {
                if ($(this).text() == "Diskusjoner") {
                    $(this).parent().append("" + totalUnread + "")
                }
            });
        },
        printUnreadCountInDiscussionsList: function(groupDiscussionsUnreadCount) {
            var checkExist = setInterval(function() {
                if ($("#open-discussions .ig-list .discussion").length) {
                    clearInterval(checkExist);
                    $("#open-discussions .ig-list .discussion").each(function() {
                        for (var i = 0; i < groupDiscussionsUnreadCount.length; i++) {
                            if($(this).attr("data-id") == groupDiscussionsUnreadCount[i].rootTopicId) {
                                $(this).find('.new-items').text(groupDiscussionsUnreadCount[i].unreadCount);
                                $(this).addClass("unread");
                            }
                        }
                    });
                    mmooc.discussionTopics.showUnreadCountInDiscussionList();
                }
            }, 100);
        },
        hideUnreadCountInDiscussionList: function() {
            var checkExist = setInterval(function() {
                if ($("#open-discussions .ig-list .discussion").length) {
                    clearInterval(checkExist);
                    $("#open-discussions .ig-list .discussion").each(function() {
                        $(this).find('.new-items').hide();
                        $(this).find('.new-items').parent().prepend("");
                    });
                }
            }, 100);
        },
        showUnreadCountInDiscussionList: function() {
            $("#open-discussions .ig-list .discussion .loading-gif").remove();
            $("#open-discussions .ig-list .discussion").each(function() {
                $(this).find('.new-items').show();
            });
        }
    };
}();

<|endoftext|>


<commit_before>sjcl.ecc.ecdsa.secretKey.prototype = {
  sign: function(hash, paranoia) {
    var R = this._curve.r,
        l = R.bitLength(),
        k = sjcl.bn.random(R.sub(1), paranoia).add(1),
        r = this._curve.G.mult(k).x.mod(R),
        s = sjcl.bn.fromBits(hash).add(r.mul(this._exponent)).mul(k.inverseMod(R)).mod(R);

    return sjcl.bitArray.concat(r.toBits(l), s.toBits(l));
  }
};

sjcl.ecc.ecdsa.publicKey.prototype = {
  verify: function(hash, rs) {
    var w = sjcl.bitArray,
        R = this._curve.r,
        l = R.bitLength(),
        r = sjcl.bn.fromBits(w.bitSlice(rs,0,l)),
        s = sjcl.bn.fromBits(w.bitSlice(rs,l,2*l)),
        sInv = s.inverseMod(R),
        hG = sjcl.bn.fromBits(hash).mul(sInv).mod(R),
        hA = r.mul(sInv).mod(R),
        r2 = this._curve.G.mult2(hG, hA, this._point).x;

    if (r.equals(0) || s.equals(0) || r.greaterEquals(R) || s.greaterEquals(R) || !r2.equals(r)) {
      throw (new sjcl.exception.corrupt("signature didn't check out"));
    }
    return true;
  }
};
<commit_msg>[CHORE] Modified functions not to overwrite entire prototype<commit_after>sjcl.ecc.ecdsa.secretKey.prototype.sign = function(hash, paranoia) {
  var R = this._curve.r,
      l = R.bitLength(),
      k = sjcl.bn.random(R.sub(1), paranoia).add(1),
      r = this._curve.G.mult(k).x.mod(R),
      s = sjcl.bn.fromBits(hash).add(r.mul(this._exponent)).mul(k.inverseMod(R)).mod(R);

  return sjcl.bitArray.concat(r.toBits(l), s.toBits(l));
};

sjcl.ecc.ecdsa.publicKey.prototype.verify = function(hash, rs) {
  var w = sjcl.bitArray,
      R = this._curve.r,
      l = R.bitLength(),
      r = sjcl.bn.fromBits(w.bitSlice(rs,0,l)),
      s = sjcl.bn.fromBits(w.bitSlice(rs,l,2*l)),
      sInv = s.inverseMod(R),
      hG = sjcl.bn.fromBits(hash).mul(sInv).mod(R),
      hA = r.mul(sInv).mod(R),
      r2 = this._curve.G.mult2(hG, hA, this._point).x;

  if (r.equals(0) || s.equals(0) || r.greaterEquals(R) || s.greaterEquals(R) || !r2.equals(r)) {
    throw (new sjcl.exception.corrupt("signature didn't check out"));
  }
  return true;
};
<|endoftext|>


<commit_before>import Router from 'mini-routerjs';
import JSONStore from 'jsonstore-js';
import React, {Component, PropTypes} from 'react';
import {
  View,
  StyleSheet,
  Dimensions,
  Keyboard
} from 'react-native';
import Page from './Page';

const emptyFunc = () => {};
const SCREEN_HEIGHT = Dimensions.get('window').height;

class EasyReactNative extends Component {
  constructor(props) {
    super(props);
    this.history = [];
    this._routes = props.routes;
    this._currentPath = props.initialPath;
    this._prevPath = '';
    this._currentPattern = '';
    this._prevPattern = '';
    this._pageRefs = [];
    this._pageStates = {};
    this._renderedPages = {};
    this._store = props.initialStore;
    this._router = new Router({
      strict: props.strict !== false
    });
    this._routes.forEach(route => {
      let selector = typeof route.selector === "function" ? route.selector : emptyFunc;
      // Register all routes
      this._router.create(route.pattern, request => {
        this._pageStates[route.pattern] = selector(request, viewStore(this._store));
        if(request.pattern !== this._currentPattern){
          this._prevPattern = this._currentPattern;
        }
        this._currentPattern = request.pattern;

        this._prevPath = this._currentPath;
        this._currentPath = request.url.url;

        route.url = request.url.url;
      });
    });

    this._router.match(this._currentPath);

    this.state = Object.assign({}, this._pageStates);
  }

  getChildContext() {
    return {
      update: this.update.bind(this),
      updateStore: this.updateStore.bind(this),
      getData: this.getData.bind(this),
      historyPush: this.historyPush.bind(this),
      historyPop: this.historyPop.bind(this)
    };
  }

  historyPush(url){
    if(url === true){
      this.history = [];
    }
    this.history.push(url);
  }

  historyPop(){
    let history;
    while ((history = this.history.pop()) === this._currentPath){}
    if(history){
      this.update(history)
    }
  }

  update(pushHistory, path, action, a, b, c, d, e, f) {
    if(typeof pushHistory !== 'boolean'){
      pushHistory = true;
      path = pushHistory;
      action = path;
      a = action;
      b = a;
      c = b;
      d = c;
      e = d;
      f = e;
    }
    if(pushHistory === true && typeof path === 'string'){
      this.historyPush(path);
    }
    let actionReturn;
    if (typeof path === "function") {
      actionReturn = this._store.do(path, action, a, b, c, d, f);
    } else {
      if (typeof action === "function") {
        actionReturn = this._store.do(action, a, b, c, d, e);
      }
    }
    actionReturn = actionReturn && Object.prototype.hasOwnProperty.call(actionReturn, 'then') && typeof actionReturn.then === 'function' ? actionReturn : Promise.resolve();
    actionReturn.then(() => {
      this._router.match(typeof path === "string" && path.length ? path : this._currentPath);
      let state = {};
      state[this._currentPattern] = this._pageStates[this._currentPattern];
      this.setState(state);
    });
  }

  updateStore(name, action, a, b, c, d, e) {
    return this._store.do(name, action, a, b, c, d, e);
  }

  getData(path, copy) {
    return this._store.get(path, copy);
  }

  _renderPage(route, props) {
    props = props || {};
    let disabledPageStyle = null,
      disabledPagePointerEvents = 'auto',
      pattern = route.pattern;
    if (pattern !== this._currentPattern) {
      disabledPageStyle = styles.disabledPage;
      disabledPagePointerEvents = 'none';
    }
    if(this._currentPath !== this._prevPath){
      if(this._currentPath === route.url){
        props = Object.assign({ _pageShow: true }, props);
      }else{
        Keyboard.dismiss();
        props = Object.assign({ _pageHide: true }, props);
      }
    }
    return props._pageHide && route.cache === false ? null : (
      <Page
        _pageShow={props._pageShow}
        _pageHide={props._pageHide}
        collapsable={false}
        key={`page_${route.pattern}_${route.url || ''}`}
        ref={(page) => {
          this._pageRefs[pattern] = page;
        }}
        pointerEvents={disabledPagePointerEvents}
        style={[styles.basePage, disabledPageStyle]}>
        {React.createElement(route.component, props)}
      </Page>
    );
  }

  render() {
    let pages = this._routes.map(route => {
      if (route.pattern === this._currentPattern || (route.pattern === this._prevPattern && this._prevPath !== this._currentPath)) {
        let renderedPage = this._renderPage(route, this.state[route.pattern]);
        this._renderedPages[route.pattern] = renderedPage;
        return renderedPage;
      } else {
        return this._renderedPages[route.pattern];
      }
    });
    return (
      <View style={[styles.container]}>
        {pages}
      </View>
    );
  }
}

EasyReactNative.Store = JSONStore;

module.exports = EasyReactNative;

EasyReactNative.defaultProps = {
  initialPath: '/',
  dismissKeyboard: true
};

EasyReactNative.propTypes = {
  routes: PropTypes.array.isRequired,
  initialPath: PropTypes.string,
  dismissKeyboard: PropTypes.bool
};

EasyReactNative.childContextTypes = {
  update: PropTypes.func.isRequired,
  updateStore: PropTypes.func.isRequired,
  getData: PropTypes.func.isRequired,
  historyPush: PropTypes.func.isRequired,
  historyPop: PropTypes.func.isRequired
};

/**
 * Wrapping the store to make sure that only accessing data copy is allowed when rendering view
 * */
function viewStore(store) {
  return {
    get: function (path) {
      return store.get(path, true);
    }
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    overflow: 'hidden',
  },
  basePage: {
    position: 'absolute',
    overflow: 'hidden',
    left: 0,
    right: 0,
    bottom: 0,
    top: 0,
  },
  disabledPage: {
    top: SCREEN_HEIGHT,
    bottom: -SCREEN_HEIGHT,
  }
});
<commit_msg>Fix history errors<commit_after>import Router from 'mini-routerjs';
import JSONStore from 'jsonstore-js';
import React, {Component, PropTypes} from 'react';
import {
  View,
  StyleSheet,
  Dimensions,
  Keyboard
} from 'react-native';
import Page from './Page';

const emptyFunc = () => {};
const SCREEN_HEIGHT = Dimensions.get('window').height;

class EasyReactNative extends Component {
  constructor(props) {
    super(props);
    this.history = [this.props.initialPath];
    this._routes = props.routes;
    this._currentPath = props.initialPath;
    this._prevPath = '';
    this._currentPattern = '';
    this._prevPattern = '';
    this._pageRefs = [];
    this._pageStates = {};
    this._renderedPages = {};
    this._store = props.initialStore;
    this._rootHistoryDic = this._getRootHistoryDict();
    this._router = new Router({
      strict: props.strict !== false
    });
    this._routes.forEach(route => {
      let selector = typeof route.selector === "function" ? route.selector : emptyFunc;
      // Register all routes
      this._router.create(route.pattern, request => {
        this._pageStates[route.pattern] = selector(request, viewStore(this._store));
        if(request.pattern !== this._currentPattern){
          this._prevPattern = this._currentPattern;
        }
        this._currentPattern = request.pattern;

        this._prevPath = this._currentPath;
        this._currentPath = request.url.url;

        route.url = request.url.url;
      });
    });

    this._router.match(this._currentPath);

    this.state = Object.assign({}, this._pageStates);
  }

  _getRootHistoryDict(){
    let dict = {};
    this.props.rootHistorys.forEach(history => {
      dict[history] = true;
    });
    return dict;
  }

  getChildContext() {
    return {
      update: this.update.bind(this),
      updateStore: this.updateStore.bind(this),
      getData: this.getData.bind(this),
      historyPush: this.historyPush.bind(this),
      historyPop: this.historyPop.bind(this),
      historyRemove: this.historyRemove.bind(this)
    };
  }

  historyRemove(index, count){
    index = parseInt(index) || -1;
    count = parseInt(count) || 1;
    return this.history.splice(index, count);
  }

  historyPush(url, isRoot){
    let historyLength = this.history.length;
    if(isRoot === true || this._rootHistoryDic[url]){
      this.history = [url];
    }else if(!historyLength || this.history[historyLength - 1] !== url){
      this.history.push(url);
    }
  }

  historyPop(){
    let history;
    while ((history = this.history.pop()) === this._currentPath){}
    if(history){
      this.update(false, history);
      if(this.history.length === 0){
        this.history.push(history);
        return true;
      }

    }
    return false;
  }

  update(pushHistory, path, action, a, b, c, d, e, f) {
    if(typeof pushHistory !== 'boolean'){
      f = e;
      e = d;
      d = c;
      c = b;
      b = a;
      a = action;
      action = path;
      path = pushHistory;
      pushHistory = true;
    }
    if(pushHistory === true && typeof path === 'string'){
      this.historyPush(path);
    }
    let actionReturn;
    if (typeof path === "function") {
      actionReturn = this._store.do(path, action, a, b, c, d, f);
    } else {
      if (typeof action === "function") {
        actionReturn = this._store.do(action, a, b, c, d, e);
      }
    }
    actionReturn = actionReturn && Object.prototype.hasOwnProperty.call(actionReturn, 'then') && typeof actionReturn.then === 'function' ? actionReturn : Promise.resolve();
    actionReturn.then(() => {
      this._router.match(typeof path === "string" && path.length ? path : this._currentPath);
      let state = {};
      state[this._currentPattern] = this._pageStates[this._currentPattern];
      this.setState(state);
    });
  }

  updateStore(name, action, a, b, c, d, e) {
    return this._store.do(name, action, a, b, c, d, e);
  }

  getData(path, copy) {
    return this._store.get(path, copy);
  }

  _renderPage(route, props) {
    props = props || {};
    let disabledPageStyle = null,
      disabledPagePointerEvents = 'auto',
      pattern = route.pattern;
    if (pattern !== this._currentPattern) {
      disabledPageStyle = styles.disabledPage;
      disabledPagePointerEvents = 'none';
    }
    if(this._currentPath !== this._prevPath){
      if(this._currentPath === route.url){
        props = Object.assign({ _pageShow: true }, props);
      }else{
        Keyboard.dismiss();
        props = Object.assign({ _pageHide: true }, props);
      }
    }
    return props._pageHide && route.cache === false ? null : (
      <Page
        _pageShow={props._pageShow}
        _pageHide={props._pageHide}
        collapsable={false}
        key={`page_${route.pattern}_${route.url || ''}`}
        ref={(page) => {
          this._pageRefs[pattern] = page;
        }}
        pointerEvents={disabledPagePointerEvents}
        style={[styles.basePage, disabledPageStyle]}>
        {React.createElement(route.component, props)}
      </Page>
    );
  }

  render() {
    let pages = this._routes.map(route => {
      if (route.pattern === this._currentPattern || (route.pattern === this._prevPattern && this._prevPath !== this._currentPath)) {
        let renderedPage = this._renderPage(route, this.state[route.pattern]);
        this._renderedPages[route.pattern] = renderedPage;
        return renderedPage;
      } else {
        return this._renderedPages[route.pattern];
      }
    });
    return (
      <View style={[styles.container]}>
        {pages}
      </View>
    );
  }
}

EasyReactNative.Store = JSONStore;

module.exports = EasyReactNative;

EasyReactNative.defaultProps = {
  initialPath: '/',
  dismissKeyboard: true,
  rootHistorys: []
};

EasyReactNative.propTypes = {
  routes: PropTypes.array.isRequired,
  initialPath: PropTypes.string,
  dismissKeyboard: PropTypes.bool,
  rootHistorys: PropTypes.array
};

EasyReactNative.childContextTypes = {
  update: PropTypes.func.isRequired,
  updateStore: PropTypes.func.isRequired,
  getData: PropTypes.func.isRequired,
  historyPush: PropTypes.func.isRequired,
  historyPop: PropTypes.func.isRequired,
  historyRemove: PropTypes.func.isRequired
};

/**
 * Wrapping the store to make sure that only accessing data copy is allowed when rendering view
 * */
function viewStore(store) {
  return {
    get: function (path) {
      return store.get(path, true);
    }
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    overflow: 'hidden',
  },
  basePage: {
    position: 'absolute',
    overflow: 'hidden',
    left: 0,
    right: 0,
    bottom: 0,
    top: 0,
  },
  disabledPage: {
    top: SCREEN_HEIGHT,
    bottom: -SCREEN_HEIGHT,
  }
});
<|endoftext|>


<commit_before>import {defineOption} from "../edit"
import {eventMixin} from "../util/event"
import {AssertionError} from "../util/error"

import {rebaseSteps} from "./rebase"
export {rebaseSteps}

defineOption("collab", false, (pm, value) => {
  if (pm.mod.collab) {
    pm.mod.collab.detach()
    pm.mod.collab = null
  }

  if (value) {
    pm.mod.collab = new Collab(pm, value)
  }
})

class Collab {
  constructor(pm, options) {
    this.pm = pm
    this.options = options

    this.version = options.version || 0
    this.versionDoc = pm.doc

    this.unconfirmedSteps = []
    this.unconfirmedMaps = []

    pm.on("transform", this.onTransform = transform => {
      for (let i = 0; i < transform.steps.length; i++) {
        this.unconfirmedSteps.push(transform.steps[i])
        this.unconfirmedMaps.push(transform.maps[i])
      }
      this.signal("mustSend")
    })
    pm.on("beforeSetDoc", this.onSetDoc = () => {
      AssertionError.raise("setDoc is not supported on a collaborative editor")
    })
    pm.history.allowCollapsing = false
  }

  detach() {
    this.pm.off("transform", this.onTransform)
    this.pm.off("beforeSetDoc", this.onSetDoc)
    this.pm.history.allowCollapsing = true
  }

  hasSendableSteps() {
    return this.unconfirmedSteps.length > 0
  }

  sendableSteps() {
    return {
      version: this.version,
      doc: this.pm.doc,
      steps: this.unconfirmedSteps.slice()
    }
  }

  confirmSteps(sendable) {
    this.unconfirmedSteps.splice(0, sendable.steps.length)
    this.unconfirmedMaps.splice(0, sendable.steps.length)
    this.version += sendable.steps.length
    this.versionDoc = sendable.doc
  }

  receive(steps) {
    let doc = this.versionDoc
    let maps = steps.map(step => {
      let result = step.apply(doc)
      doc = result.doc
      return result.map
    })
    this.version += steps.length
    this.versionDoc = doc

    let rebased = rebaseSteps(doc, maps, this.unconfirmedSteps, this.unconfirmedMaps)
    this.unconfirmedSteps = rebased.transform.steps.slice()
    this.unconfirmedMaps = rebased.transform.maps.slice()

    this.pm.updateDoc(rebased.doc, rebased.mapping)
    this.pm.history.rebased(maps, rebased.transform, rebased.positions)
    return maps
  }
}

eventMixin(Collab)
<commit_msg>docs(collab): Add doc comments to the collab module<commit_after>import {defineOption} from "../edit"
import {eventMixin} from "../util/event"
import {AssertionError} from "../util/error"

import {rebaseSteps} from "./rebase"
export {rebaseSteps}

// :: ?Object #path=collab #kind=option
//
// When given, enables the collaborative editing framework for the
// editor. Will register itself of the `Collab` class as
// `.mod.collab`.
//
// If the object given has a `version` property, that will determine
// the starting version number of the collaborative editing.

defineOption("collab", false, (pm, value) => {
  if (pm.mod.collab) {
    pm.mod.collab.detach()
    pm.mod.collab = null
  }

  if (value) {
    pm.mod.collab = new Collab(pm, value)
  }
})

// ;; This class accumulates changes that have to be sent to the
// central authority in the collaborating group, signals an event when
// it has something to send, and makes it possible to integrate
// changes made by peers into our local document. It is created and
// attached to the editor (under `.mod.collab`) by setting the
// `collab` option.
//
// Includes the [event mixin](#EventMixin).
class Collab {
  constructor(pm, options) {
    this.pm = pm
    this.options = options

    // :: number
    // The version number of the last update received from the central
    // authority. Starts at 0 or the value of the `version` property
    // in the option object, for the editor's value when the option
    // was enabled.
    this.version = options.version || 0
    this.versionDoc = pm.doc

    this.unconfirmedSteps = []
    this.unconfirmedMaps = []

    pm.on("transform", this.onTransform = transform => {
      for (let i = 0; i < transform.steps.length; i++) {
        this.unconfirmedSteps.push(transform.steps[i])
        this.unconfirmedMaps.push(transform.maps[i])
      }
      // :: () #path=Collab#events#mustSend
      // Fired when there are new steps to send to the central
      // authority. Consumers should respond by calling
      // `sendableSteps` and pushing those to the authority.
      this.signal("mustSend")
    })
    pm.on("beforeSetDoc", this.onSetDoc = () => {
      AssertionError.raise("setDoc is not supported on a collaborative editor")
    })
    pm.history.allowCollapsing = false
  }

  detach() {
    this.pm.off("transform", this.onTransform)
    this.pm.off("beforeSetDoc", this.onSetDoc)
    this.pm.history.allowCollapsing = true
  }

  // :: () -> bool
  // Reports whether the editor has any unsent steps.
  hasSendableSteps() {
    return this.unconfirmedSteps.length > 0
  }

  // :: () → {version: number, doc: Node, steps: [Step]}
  // Provides the data describing the editor's unconfirmed steps. This
  // is the thing you'd send to the central authority.
  sendableSteps() {
    return {
      version: this.version,
      doc: this.pm.doc,
      steps: this.unconfirmedSteps.slice()
    }
  }

  // :: ({version: number, doc: Node, steps: [Step]})
  // Tells the module that a set of unconfirmed steps have been
  // accepted by the central authority, and can now be considered
  // confirmed.
  confirmSteps(sendable) {
    this.unconfirmedSteps.splice(0, sendable.steps.length)
    this.unconfirmedMaps.splice(0, sendable.steps.length)
    this.version += sendable.steps.length
    this.versionDoc = sendable.doc
  }

  // :: ([Step]) → [PosMap]
  // Pushes a set of steps (made by peers and received from the
  // central authority) into the editor. This will rebase any
  // unconfirmed steps over these steps.
  //
  // Returns the [position maps](#PosMap) produced by applying the
  // steps.
  receive(steps) {
    let doc = this.versionDoc
    let maps = steps.map(step => {
      let result = step.apply(doc)
      doc = result.doc
      return result.map
    })
    this.version += steps.length
    this.versionDoc = doc

    let rebased = rebaseSteps(doc, maps, this.unconfirmedSteps, this.unconfirmedMaps)
    this.unconfirmedSteps = rebased.transform.steps.slice()
    this.unconfirmedMaps = rebased.transform.maps.slice()

    this.pm.updateDoc(rebased.doc, rebased.mapping)
    this.pm.history.rebased(maps, rebased.transform, rebased.positions)
    return maps
  }
}

eventMixin(Collab)
<|endoftext|>


<commit_before>import compareReportsCommand from './compareReports';
import generateDevSha from '../generateDevSha';
import uploadReport from '../uploadReport';

export default async function devCommand(config, { only }) {
  const {
    apiKey,
    apiSecret,
    endpoint,
    hooks: {
      run,
    },
  } = config;
  let previousSha;
  run(config, {
    only,
    onReady: async (snaps) => {
      const sha = generateDevSha();
      console.log(`Preparing report (${sha})...`);
      const { url } = await uploadReport({
        snaps,
        sha,
        endpoint,
        apiKey,
        apiSecret,
      });
      console.log(`View results at ${url}`);

      if (previousSha) {
        console.log('Comparing with previous run...')
        const result = await compareReportsCommand(
          previousSha,
          sha,
          { apiKey, apiSecret, endpoint },
          {}
        );
        console.log(result.summary);
      }
      previousSha = sha;
    },
    onBuilding: () => {
      console.log('Building...');
    }
  });
}
<commit_msg>Compare with baseline report during `happo dev`<commit_after>import compareReportsCommand from './compareReports';
import generateDevSha from '../generateDevSha';
import uploadReport from '../uploadReport';

export default async function devCommand(config, { only }) {
  const {
    apiKey,
    apiSecret,
    endpoint,
    hooks: {
      run,
    },
  } = config;
  let baselineSha;
  run(config, {
    only,
    onReady: async (snaps) => {
      const sha = generateDevSha();
      console.log(`Preparing report (${sha})...`);
      const { url } = await uploadReport({
        snaps,
        sha,
        endpoint,
        apiKey,
        apiSecret,
      });
      console.log(`View results at ${url}`);

      if (baselineSha) {
        console.log('Comparing with baseline report...')
        const result = await compareReportsCommand(
          baselineSha,
          sha,
          { apiKey, apiSecret, endpoint },
          {}
        );
        console.log(result.summary);
      } else {
        baselineSha = sha;
      }
    },
    onBuilding: () => {
      console.log('Building...');
    }
  });
}
<|endoftext|>


<commit_before>angular.module('angular-number-incrementor').directive('numberIncrementor', [ function() {

    return {
        restrict: 'EA',
        replace: true,
        transclude: true,
        scope: {
            output : '='
        },
        templateUrl: function(element, attributes) {
          return attributes.template || "numberincrementor.html";
        },
        link: function($scope, $element, $attrs) {

            $scope.output = $scope.spinnerValue;

            $scope.spinnerValue = 0;

            $scope.increase = function(){
                $scope.spinnerValue++;
                $scope.output = $scope.spinnerValue;
            };

            $scope.decrease = function(){
                $scope.spinnerValue--;
                $scope.output = $scope.spinnerValue;
            };

        }
    };
}]);
<commit_msg>added min and max count attributes<commit_after>angular.module('angular-number-incrementor').directive('numberIncrementor', [ function() {

    return {
        restrict: 'EA',
        replace: true,
        transclude: true,
        scope: {
            output : '=',
            mincount : '=',
            maxcount : '='
        },
        templateUrl: function(element, attributes) {
          return attributes.template || "numberincrementor.html";
        },
        link: function($scope, $element, $attrs) {

            $scope.output = $scope.spinnerValue;

            $scope.spinnerValue = 0;

            $scope.increase = function(){
                if($scope.maxcount && (typeof $scope.maxcount === 'number') && ($scope.spinnerValue < $scope.maxcount)){
                    $scope.spinnerValue++;
                    $scope.output = $scope.spinnerValue;
                } else if(!$scope.maxcount){
                    $scope.spinnerValue++;
                    $scope.output = $scope.spinnerValue;
                }

            };

            $scope.decrease = function(){
                if($scope.mincount && (typeof $scope.mincount === 'number') && ($scope.spinnerValue > $scope.mincount)){
                    $scope.spinnerValue--;
                    $scope.output = $scope.spinnerValue;
                } else if(!$scope.mincount){
                    $scope.spinnerValue--;
                    $scope.output = $scope.spinnerValue;
                }
            };

        }
    };
}]);
<|endoftext|>


<commit_before>'use strict';

var _     = require('lodash');
var memoizee = require('memoizee');

////////////////////////////////////////////////////////////////////////////////

module.exports = function (N) {

  // Helper to fetch usergroups by IDs
  //
  function fetchForumSettings(id, callback) {
    N.models.forum.Section.findOne({ _id: String(id) })
      .select('settings.forum_usergroup')
      .setOptions({ lean: true })
      .exec(callback);
  }

  // Memoized version of fetchUserGroups helper
  //
  var fetchForumSettingsCached = memoizee(fetchForumSettings, {
    // memoizee options. revalidate cache after 30 sec
    async:      true,
    maxAge:     30000,
    primitive:  true
  });

  ////////////////////////////////////////////////////////////////////////////////

  // ##### Params
  //
  // - usergroup_ids (Array)
  // - forum_id (String|ObjectId)
  //
  var ForumGroupStore = N.settings.createStore({
    get: function (keys, params, options, callback) {
      var func = options.skipCache ? fetchForumSettings : fetchForumSettingsCached;

      if (!params.forum_id) {
        callback("forum_id param is required for getting settings from forum_usergroup store");
        return;
      }

      if (!_.isArray(params.usergroup_ids) || !params.usergroup_ids.length) {
        callback("usergroup_ids param required to be non-empty array for getting settings from forum_usergroup store");
        return;
      }

      func(params.forum_id, function (err, forum) {
        var settings, results = {};

        if (err) {
          callback(err);
          return;
        }

        settings = forum.settings || {};
        settings = settings.forum_usergroup  || {};

        keys.forEach(function (k) {
          var values = [];

          params.usergroup_ids.forEach(function (id) {
            if (settings[id]) {
              values.push(settings[id]);
            } else {
              values.push(null);
            }
          });

          results[k] = ForumGroupStore.mergeValues(values);
        });

        callback(null, results);
      });
    },

    set: function (settings, params, callback) {
      if (!params.forum_id) {
        callback("forum_id param is required for saving settings into forum_usergroup store");
        return;
      }

      if (!params.usergroup_id) {
        callback("usergroup_id param is required for saving settings into forum_usergroup store");
        return;
      }

      N.models.forum.Section.findOne({
        _id: params.forum_id
      }).exec(function (err, forum) {
        var grp_id = params.usergroup_id;

        if (err) {
          callback(err);
          return;
        }

        // make sure we have settings storages
        forum.settings = forum.settings || {};
        forum.settings.forum_usergroup = forum.settings.forum_usergroup || {};
        forum.settings.forum_usergroup[grp_id] = forum.settings.forum_usergroup[grp_id] || {};

        _.each(settings, function (opts, key) {
          if (null === opts) {
            delete forum.settings.forum_usergroup[grp_id][key];
          } else {
            forum.settings.forum_usergroup[grp_id][key] = opts;
          }
        });

        forum.markModified('settings');
        forum.save(callback);
      });
    }
  });

  return ForumGroupStore;
};<commit_msg>Fix mergeValue method<commit_after>'use strict';

var _     = require('lodash');
var memoizee = require('memoizee');

////////////////////////////////////////////////////////////////////////////////

module.exports = function (N) {

  // Helper to fetch usergroups by IDs
  //
  function fetchForumSettings(id, callback) {
    N.models.forum.Section.findOne({ _id: String(id) })
      .select('settings.forum_usergroup')
      .setOptions({ lean: true })
      .exec(callback);
  }

  // Memoized version of fetchUserGroups helper
  //
  var fetchForumSettingsCached = memoizee(fetchForumSettings, {
    // memoizee options. revalidate cache after 30 sec
    async:      true,
    maxAge:     30000,
    primitive:  true
  });

  ////////////////////////////////////////////////////////////////////////////////

  // ##### Params
  //
  // - usergroup_ids (Array)
  // - forum_id (String|ObjectId)
  //
  var ForumGroupStore = N.settings.createStore({
    get: function (keys, params, options, callback) {
      var func = options.skipCache ? fetchForumSettings : fetchForumSettingsCached;

      if (!params.forum_id) {
        callback("forum_id param is required for getting settings from forum_usergroup store");
        return;
      }

      if (!_.isArray(params.usergroup_ids) || !params.usergroup_ids.length) {
        callback("usergroup_ids param required to be non-empty array for getting settings from forum_usergroup store");
        return;
      }

      func(params.forum_id, function (err, forum) {
        var settings, results = {};

        if (err) {
          callback(err);
          return;
        }

        settings = forum.settings || {};
        settings = settings.forum_usergroup  || {};

        keys.forEach(function (k) {
          var values = [];

          params.usergroup_ids.forEach(function (id) {
            if (settings[id]) {
              values.push(settings[id]);
            } else {
              values.push(null);
            }
          });

          results[k] = N.settings.mergeValues(values);
        });

        callback(null, results);
      });
    },

    set: function (settings, params, callback) {
      if (!params.forum_id) {
        callback("forum_id param is required for saving settings into forum_usergroup store");
        return;
      }

      if (!params.usergroup_id) {
        callback("usergroup_id param is required for saving settings into forum_usergroup store");
        return;
      }

      N.models.forum.Section.findOne({
        _id: params.forum_id
      }).exec(function (err, forum) {
        var grp_id = params.usergroup_id;

        if (err) {
          callback(err);
          return;
        }

        // make sure we have settings storages
        forum.settings = forum.settings || {};
        forum.settings.forum_usergroup = forum.settings.forum_usergroup || {};
        forum.settings.forum_usergroup[grp_id] = forum.settings.forum_usergroup[grp_id] || {};

        _.each(settings, function (opts, key) {
          if (null === opts) {
            delete forum.settings.forum_usergroup[grp_id][key];
          } else {
            forum.settings.forum_usergroup[grp_id][key] = opts;
          }
        });

        forum.markModified('settings');
        forum.save(callback);
      });
    }
  });

  return ForumGroupStore;
};
<|endoftext|>


<commit_before>/* eslint max-len: 0 */
/* eslint no-nested-ternary: 0 */
import React, { Component } from 'react';
import classSet from 'classnames';

class ExpandComponent extends Component {

  render() {
    const { selectRow, isSelected, className, row } = this.props;
    const selectRowClass = typeof selectRow.className === 'function' ?
        selectRow.className(row, isSelected) : ( isSelected ? selectRow.className : null);
    const trCss = {
      style: {
        backgroundColor: this.props.bgColor
      },
      className: classSet(selectRowClass, className)
    };
    return (

          { this.props.children }

    );
  }
}

export default ExpandComponent;
<commit_msg>fix #1327, expandrow broken<commit_after>/* eslint max-len: 0 */
/* eslint no-nested-ternary: 0 */
import React, { Component } from 'react';
import classSet from 'classnames';

class ExpandComponent extends Component {

  render() {
    const { className } = this.props;
    const trCss = {
      style: {
        backgroundColor: this.props.bgColor
      },
      className: classSet(className)
    };
    return (

          { this.props.children }

    );
  }
}

export default ExpandComponent;
<|endoftext|>


<commit_before>// External
const mem = require('mem');

// Ours
const { merge } = require('../utils/structures');
const { getProjectConfig } = require('./project');

const PROJECT_TYPES_CONFIG = {
  preact: {
    plugins: [
      [
        require.resolve('@babel/plugin-transform-react-jsx'),
        {
          pragma: 'h'
        }
      ]
    ]
  },
  react: {
    presets: [require.resolve('@babel/preset-react')]
  }
};

module.exports.getBabelConfig = mem(({ isModernJS } = {}) => {
  const { babel: projectBabelConfig, type } = getProjectConfig();

  return merge(
    {
      presets: [
        [
          require.resolve('@babel/preset-env'),
          {
            targets: {
              browsers: isModernJS
                ? ['Chrome >= 60', 'Safari >= 10.1', 'iOS >= 10.3', 'Firefox >= 54', 'Edge >= 15']
                : ['> 1% in au', '> 5%', 'Firefox ESR']
            },
            useBuiltIns: 'entry',
            modules: process.env.NODE_ENV === 'test' ? 'commonjs' : false
          }
        ]
      ],
      plugins: [
        require.resolve('@babel/plugin-proposal-object-rest-spread'),
        require.resolve('@babel/plugin-syntax-dynamic-import'),
        require.resolve('@babel/plugin-proposal-class-properties')
      ]
    },
    PROJECT_TYPES_CONFIG[type],
    projectBabelConfig
  );
});
<commit_msg>Babel config now respects package.json's browserslist in non-modern builds.<commit_after>// External
const mem = require('mem');

// Ours
const { merge } = require('../utils/structures');
const { getProjectConfig } = require('./project');

const PROJECT_TYPES_CONFIG = {
  preact: {
    plugins: [
      [
        require.resolve('@babel/plugin-transform-react-jsx'),
        {
          pragma: 'h'
        }
      ]
    ]
  },
  react: {
    presets: [require.resolve('@babel/preset-react')]
  }
};

module.exports.getBabelConfig = mem(({ isModernJS } = {}) => {
  const { babel: projectBabelConfig, pkg, type } = getProjectConfig();

  return merge(
    {
      presets: [
        [
          require.resolve('@babel/preset-env'),
          {
            targets: {
              browsers: isModernJS
                ? ['Chrome >= 60', 'Safari >= 10.1', 'iOS >= 10.3', 'Firefox >= 54', 'Edge >= 15']
                : pkg.browserslist || ['> 1% in au', '> 5%', 'Firefox ESR']
            },
            useBuiltIns: 'entry',
            modules: process.env.NODE_ENV === 'test' ? 'commonjs' : false
          }
        ]
      ],
      plugins: [
        require.resolve('@babel/plugin-proposal-object-rest-spread'),
        require.resolve('@babel/plugin-syntax-dynamic-import'),
        require.resolve('@babel/plugin-proposal-class-properties')
      ]
    },
    PROJECT_TYPES_CONFIG[type],
    projectBabelConfig
  );
});
<|endoftext|>


<commit_before>const fs = require('fs')
const ncp = require('ncp').ncp
const path = require('path')

function writeFile (path, content) {
  fs.writeFile(path, content, 'utf8', error => {
    if (error) {
      throw error
    }
  })
}

function writeFiles (parentDirectory, files) {
  if (!files) {
    return
  }
  if (files.constructor === Array) {
    files.forEach(file => writeFile(path.resolve(parentDirectory, file), ''))
  } else if (files.constructor === Object) {
    Object.keys(files).forEach(name => {
      writeFile(name, files[name])
    })
  }
}

function writeDirectory (parentDirectory, directoryObject) {
  writeFiles(parentDirectory, directoryObject.files)
  if (!directoryObject.directories) return
  Object.keys(directoryObject.directories).forEach(directory => {
    const newParentDirectory = parentDirectory + '/' + directory
    fs.mkdirSync(newParentDirectory)
    writeDirectory(newParentDirectory, directoryObject.directories[directory])
  })
}

function writeFolderConfig (config, callback) {
  const loadFromPath = config.path
  const folderFiles = fs.readdirSync(loadFromPath)
  let countdown = folderFiles.length
  const beforeCallback = _ => {
    if (--countdown === 0) {
      if (callback) {
        callback()
      }
    }
  }
  folderFiles.forEach(file => {
    ncp(path.resolve(loadFromPath, file), process.cwd(), error => {
      if (error) {
        throw error
      }
      beforeCallback()
    })
  })
}

function writeRegularConfig (config) {
  return writeDirectory(process.cwd(), config)
}

function write (config, callback) {
  if (config.isDirectory) {
    writeFolderConfig(config, callback)
  } else {
    writeRegularConfig(config)
  }
}

module.exports = {
  write: write
}
<commit_msg>Fixed a bug where ncp wouldn't store sub-folders correctly<commit_after>const fs = require('fs')
const ncp = require('ncp').ncp
const path = require('path')
const cwd = process.cwd()

function writeFile (path, content) {
  fs.writeFile(path, content, 'utf8', error => {
    if (error) {
      throw error
    }
  })
}

function writeFiles (parentDirectory, files) {
  if (!files) {
    return
  }
  if (files.constructor === Array) {
    files.forEach(file => writeFile(path.resolve(parentDirectory, file), ''))
  } else if (files.constructor === Object) {
    Object.keys(files).forEach(name => {
      writeFile(name, files[name])
    })
  }
}

function writeDirectory (parentDirectory, directoryObject) {
  writeFiles(parentDirectory, directoryObject.files)
  if (!directoryObject.directories) return
  Object.keys(directoryObject.directories).forEach(directory => {
    const newParentDirectory = parentDirectory + '/' + directory
    fs.mkdirSync(newParentDirectory)
    writeDirectory(newParentDirectory, directoryObject.directories[directory])
  })
}

function writeFolderConfig (config, callback) {
  const loadFromPath = config.path
  const folderFiles = fs.readdirSync(loadFromPath)
  let countdown = folderFiles.length
  const beforeCallback = _ => {
    if (--countdown === 0) {
      if (callback) {
        callback()
      }
    }
  }
  folderFiles.forEach(file => {
    ncp(path.resolve(loadFromPath, file), path.resolve(cwd, file), error => {
      if (error) {
        throw error
      }
      beforeCallback()
    })
  })
}

function writeRegularConfig (config) {
  return writeDirectory(cwd, config)
}

function write (config, callback) {
  if (config.isDirectory) {
    writeFolderConfig(config, callback)
  } else {
    writeRegularConfig(config)
  }
}

module.exports = {
  write: write
}
<|endoftext|>