<commit_before>export const patterns = [{
	name:"Date in format dd/mm/yyyy",
	regex:/^(0?[1-9]|[12][0-9]|3[01])([ /\-])(0?[1-9]|1[012])\2([0-9][0-9][0-9][0-9])$/,
	description:"Will match dates with dashes, slashes or with spaces dd-mm-yyyy dd/mm/yyyy dd mm yyyy",
	tags:"date,time"
},
{
	name: "Time in 24-hour format",
	regex: /([01]?[0-9]|2[0-3]):[0-5][0-9]/,
	description: "Match times in 24 hour format",
	tags: "date,time"
},
{
	name:"HTML tags",
	regex:/^<([a-z1-6]+)([^<]+)*(?:>(.*)<\/\1>| *\/>)$/,
	description:"Match opening and closing HTML tags with content between",
	tags:"markup,xml,html"
},
{
	name:"Username",
	regex:/^[a-zA-Z0-9_-]{3,16}$/,
	description:"A string between 3 and 16 characters, allowing alphanumeric characters and hyphens and underscores",
	tags:"username,validation"
},
{
	name:"Hex Color Value",
	regex:/^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/,
	description:"RGB hex colors",
	tags:"hex,color"
},
{
	name:"URL Slug",
	regex:/^[a-z0-9-]+$/,
	description:"Match valid URL slugs",
	tags:"URL"
},
{
	name:"Email",
	regex:/^.+@.+$/,
	description:"Verify that there is an @ symbol with something before it",
	tags:"email,validation"
},
{
	name:"SRC of image tag",
	regex:/^<\s*img[^>]+src\s*=\s*(["'])(.*?)\1[^>]*>$/,
	description:"Match the src attribute of an HTML image tag",
	tags:"html,tag,image"
},
{
	name:"URL",
	regex:/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/,
	description:"Match URL with optional protocal",
	tags:"url,address,http"
},
{
	name:"IPv4 Address",
	regex:/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
	description:"Match IP v4 addresses",
	tags:"tcpip,internet,address"
},
{
	name: "IPv6 Address",
	regex: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,
	description: "Match IP v6 addresses",
	tags: "tcpip,internet,address"
},
{
	name:"Positive Integer",
	regex:/^\d+$/,
	descriptions:"Match whole numbers above zero",
	tags:"number"
},
{
	name:"Negative Integer",
	regex:/^-\d+$/,
	description:"Match whole numbers below zero",
	tags:"number"
},
{
	name:"Integer",
	regex:/^-?\d+$/,
	description:"Match whole numbers, above or below zero",
	tags:"number"
},
{
	name:"Positive number",
	regex:/^\d*\.?\d+$/,
	description:"Match integers or floats that are positive",
	tags:"float"
},
{
	name:"Negative number",
	regex:/^-\d*\.?\d+$/,
	description:"Match integers or floats that are negative",
	tags:"float"
},
{
	name:"Positive or negative number",
	regex:/^-?\d*\.?\d+$/,
	description:"Match integers or floats that are positive or negative",
	tags:"float"
},
{
	name:"Phone number",
	regex:/^\+?[\d\s]{3,}$/,
	description:"Match phone numbers at least 3 digits long",
	tags:"validation"
},
{
	name:"New line",
	regex:/[\r\n]|$/,
	description:"Match new lines within text",
	tags:"text"
},
{
	name:"ID of Youtube video",
	regex:/https?:\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)v=)([\w-]{11}).*/gi,
	description:"Match the ID of a youtube video URL",
	tags:"video,youtube,url"
},
{
	name:"ID of Youtube Channel",
	regex: /https?:\/\/(www\.)?youtube.com\/channel\/UC([-_a-z0-9]{22})/i,
	description:"Match the ID of a youtube channel URL",
	tags:"channel,youtube,url"
},
{
	name:"CSS comment",
	regex:/\/\*[^*]*\*+([^/*][^*]*\*+)*\//,
	description:"Match standard CSS comments",
	tags:"css,comment,code"
},
{
	name:"Wordpress shortcodes",
	regex:/^\[([a-z-_0-9]+)([^\[]+)*(?:\](.*)\[\/\1\]|\s+\/\])$/,
	description:"Matches opening and closing shortcode tags with content in-between them.",
	tags:"wordpress,shortcodes,markup"
},
{
	name: "U.S./Canadian ZIP/Postal Code",
	regex: /(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)/,
	description:"Matches US ZIP, ZIP+4, and Canadian Postal Codes",
	tags:"address, postal, zip"
}
];
<commit_msg>Added morse code regex, consistency fixes.<commit_after>export const patterns = [{
	name:"Date in format dd/mm/yyyy",
	regex:/^(0?[1-9]|[12][0-9]|3[01])([ /\-])(0?[1-9]|1[012])\2([0-9][0-9][0-9][0-9])$/,
	description:"Will match dates with dashes, slashes or with spaces dd-mm-yyyy dd/mm/yyyy dd mm yyyy",
	tags:"date,time"
},
{
	name:"Time in 24-hour format",
	regex: /([01]?[0-9]|2[0-3]):[0-5][0-9]/,
	description: "Match times in 24 hour format",
	tags:"date,time"
},
{
	name:"HTML tags",
	regex:/^<([a-z1-6]+)([^<]+)*(?:>(.*)<\/\1>| *\/>)$/,
	description:"Match opening and closing HTML tags with content between",
	tags:"markup,xml,html"
},
{
	name:"Username",
	regex:/^[a-zA-Z0-9_-]{3,16}$/,
	description:"A string between 3 and 16 characters, allowing alphanumeric characters and hyphens and underscores",
	tags:"username,validation"
},
{
	name:"Hex Color Value",
	regex:/^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/,
	description:"RGB hex colors",
	tags:"hex,color"
},
{
	name:"URL Slug",
	regex:/^[a-z0-9-]+$/,
	description:"Match valid URL slugs",
	tags:"URL"
},
{
	name:"Email",
	regex:/^.+@.+$/,
	description:"Verify that there is an @ symbol with something before it",
	tags:"email,validation"
},
{
	name:"SRC of image tag",
	regex:/^<\s*img[^>]+src\s*=\s*(["'])(.*?)\1[^>]*>$/,
	description:"Match the src attribute of an HTML image tag",
	tags:"html,tag,image"
},
{
	name:"URL",
	regex:/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/,
	description:"Match URL with optional protocal",
	tags:"url,address,http"
},
{
	name:"IPv4 Address",
	regex:/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
	description:"Match IP v4 addresses",
	tags:"tcpip,internet,address"
},
{
	name:"IPv6 Address",
	regex:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,
	description: "Match IP v6 addresses",
	tags:"tcpip,internet,address"
},
{
	name:"Positive Integer",
	regex:/^\d+$/,
	descriptions:"Match whole numbers above zero",
	tags:"number"
},
{
	name:"Negative Integer",
	regex:/^-\d+$/,
	description:"Match whole numbers below zero",
	tags:"number"
},
{
	name:"Integer",
	regex:/^-?\d+$/,
	description:"Match whole numbers, above or below zero",
	tags:"number"
},
{
	name:"Positive number",
	regex:/^\d*\.?\d+$/,
	description:"Match integers or floats that are positive",
	tags:"float"
},
{
	name:"Negative number",
	regex:/^-\d*\.?\d+$/,
	description:"Match integers or floats that are negative",
	tags:"float"
},
{
	name:"Positive or negative number",
	regex:/^-?\d*\.?\d+$/,
	description:"Match integers or floats that are positive or negative",
	tags:"float"
},
{
	name:"Phone number",
	regex:/^\+?[\d\s]{3,}$/,
	description:"Match phone numbers at least 3 digits long",
	tags:"validation"
},
{
	name:"New line",
	regex:/[\r\n]|$/,
	description:"Match new lines within text",
	tags:"text"
},
{
	name:"ID of Youtube video",
	regex:/https?:\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)v=)([\w-]{11}).*/gi,
	description:"Match the ID of a youtube video URL",
	tags:"video,youtube,url"
},
{
	name:"ID of Youtube Channel",
	regex:/https?:\/\/(www\.)?youtube.com\/channel\/UC([-_a-z0-9]{22})/i,
	description:"Match the ID of a youtube channel URL",
	tags:"channel,youtube,url"
},
{
	name:"CSS comment",
	regex:/\/\*[^*]*\*+([^/*][^*]*\*+)*\//,
	description:"Match standard CSS comments",
	tags:"css,comment,code"
},
{
	name:"Wordpress shortcodes",
	regex:/^\[([a-z-_0-9]+)([^\[]+)*(?:\](.*)\[\/\1\]|\s+\/\])$/,
	description:"Matches opening and closing shortcode tags with content in-between them.",
	tags:"wordpress,shortcodes,markup"
},
{
	name:"U.S./Canadian ZIP/Postal Code",
	regex:/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)/,
	description:"Matches US ZIP, ZIP+4, and Canadian Postal Codes",
	tags:"address, postal, zip"
}
{
	name:"Valid Morse Code",
	regex:/^[.-]{1,5}(?> [.-]{1,5})*(?>(?!\S*(?:\s\S*){5})[.-]{1,5}(?> [.-]{1,5})*)*$/,
	description:"Matches valid Morse Code",
	tags:"morse, code"
}
];

<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const simpleGit = require('simple-git')(path.join(__dirname, '..'));

const configPath = path.join(__dirname, '..', 'package.json');
fs.readFile(configPath, function(err, data) {
  if (err) {
    console.error('error reading config', err);
  } else {
    const json = JSON.parse(data);
    const curVersion = json.version;
    const subVersions = curVersion.split('.').map(i => parseInt(i, 10));
    if (subVersions[2] < 9) {
      subVersions[2]++;
    } else if (subVersions[2] === 9 && subVersions[1] < 9) {
      subVersions[2] = 0;
      subVersions[1]++;
    } else if (subVersions[2] === 9 && subVersions[1] === 9) {
      subVersions[2] = 0;
      subVersions[1] = 0;
      subVersions[0]++;
    }
    const newVersion = subVersions.join('.');
    console.log(curVersion + ' -> ' + newVersion);
    json.version = newVersion;
    const newData = JSON.stringify(json, null, 2) + '\n';
    fs.writeFile(configPath, newData, (writeErr) => {
      if (err) {
        console.error('error updating config', err);
      } else {
        console.log('updated ' + configPath);
      }
    });
  }
});
<commit_msg>Flesh out bump-version script with git tagging<commit_after>const fs = require('fs');
const path = require('path');
const simpleGit = require('simple-git')(path.join(__dirname, '..'));

const configPath = path.join(__dirname, '..', 'package.json');

function makeGitTag(version) {
  simpleGit.add(configPath).
      commit('Bump version to ' + version).
      push('origin', 'master').
      addTag(version).
      pushTags('origin');
}

fs.readFile(configPath, function(err, data) {
  if (err) {
    console.error('error reading config', err);
  } else {
    const json = JSON.parse(data);
    const curVersion = json.version;
    const subVersions = curVersion.split('.').map(i => parseInt(i, 10));
    if (subVersions[2] < 9) {
      subVersions[2]++;
    } else if (subVersions[2] === 9 && subVersions[1] < 9) {
      subVersions[2] = 0;
      subVersions[1]++;
    } else if (subVersions[2] === 9 && subVersions[1] === 9) {
      subVersions[2] = 0;
      subVersions[1] = 0;
      subVersions[0]++;
    }
    const newVersion = subVersions.join('.');
    console.log(curVersion + ' -> ' + newVersion);
    json.version = newVersion;
    const newData = JSON.stringify(json, null, 2) + '\n';
    fs.writeFile(configPath, newData, (writeErr) => {
      if (err) {
        console.error('error updating config', err);
      } else {
        console.log('updated ' + configPath);
        makeGitTag(newVersion);
      }
    });
  }
});
<|endoftext|>


<commit_before>var pageIndex = 0;

$( document ).ready(function() {
  //loadPageIntoElement("JSONP", addPage());
  //loadPageIntoElement("Copenhagen", addPage());
  //addSearchPage();
  setUpSearch();
});

function addPage() {
	var pageId = "page" + pageIndex++;

	var tempContainer = document.createElement("div");
	tempContainer.innerHtml =
'
' +
'
'+
'
'+
'

'+
'
'+
'

'+
'
'+
'
';

	$(".wikibrowser-host").append(tempContainer.innerHtml);

	// Scroll to reveal the new pane
	var newPageOffset = $("#" + pageId).offset().left;
	$(".wikibrowser-host").animate({scrollLeft: newPageOffset}, 400);

	return pageId;
}

function addSearchPage() {
	var pageId = "page" + pageIndex++;

	var tempContainer = document.createElement("div");
	tempContainer.innerHtml =
'
' +
'
'+
'
'+
'

'+
'
'+
'
'+
'
Search
'+
'                        <input type="text" placeholder="Coming soon"></input>
'+
'
Other upcoming features:
'+
'
'+
'
Close and rearrange articles
'+
'
Set bookmarks and leave notes
'+
'
Save, restore and share your layout
'+
'
'+
'
'+
'
How do I use this?
'+
'                        Click on links in Wikipedia articles on the left. They will open new articles side by side!
'+
'
'+
'
'+
'
';

	$(".wikibrowser-host").append(tempContainer.innerHtml);

	return pageId;
}

function loadPageIntoElement(page, element) {
	console.log('load page ' + page);
	$.ajax({
	    url : "http://en.wikipedia.org/w/api.php?action=parse&format=json&callback=?&continue=&page=" + page,
	    data: {
	    	format: 'json'
	    },
	    dataType: 'jsonp',
	    cache: 'true' // defaults to false for jsonp.
	})
	.done(function(data) {
		$( "#" + element + " > .pre-content > h1" ).append( data.parse.displaytitle );
		$( "#" + element + " > .content" ).append( data.parse.text['*'] );
		$( "#" + element + " > .content a").each(fixHyperlink);
		$( "#" + element ).perfectScrollbar({
			wheelSpeed: 3
		});
	});
}

function fixHyperlink(index, element)
{
	var jElement = $(element);
	var address = jElement.attr('href');
	if (address.substring(0, 6) === '/wiki/')
	{
		jElement.attr('href', "http://en.wikipedia.org" + address);
		jElement.on('click', function() {
			loadPageIntoElement(address.substring(6), addPage());
			return false; // prevent going to href (wikipedia)
		})
	}
	if (address.substring(0, 1) !== '#')
	{
		jElement.attr('target', "_blank");
	}
}

function setUpSearch() {
	console.log("setUpSearch");
	var searchBox = $(".wikibrowser-search-content input");
	searchBox.keyup(function(event) {
		if (event.keyCode == 13) {
			console.log("enter");
			goToArticle(searchBox[0].value);
		}
	});
	var goButton = $(".wikibrowser-go-button");
	goButton.on('click', function() {
		goToArticle(searchBox[0].value);
	});
	var searchButton = $(".wikibrowser-search-button");
	searchButton.on('click', function() {
		searchArticle(searchBox[0].value);
	});
}

function goToArticle(query) {
	console.log("goToArticle " + query);
	results = getSearchResults(query, function(results) {
		if (typeof results.query.search === 'undefined' || results.query.searchinfo.totalhits === 0)
		{
			$('.wikibrowser-search-results-title').html('There are no search results for ' + query + '.');
			if (typeof results.query.searchinfo.suggestion !== 'undefined') {
				$('.wikibrowser-search-results-title').append('
Did you mean ' + results.query.searchinfo.suggestion + '?');
			}

		}
		console.log("Go to: ");
		var bestMatch = results.query.search[0];
		console.log(bestMatch);
		loadPageIntoElement(bestMatch.title, addPage());
	});
}

function searchArticle(query) {
	console.log("searchArticle " + query);
	var results = getSearchResults(query, function(results) {
		if (typeof results.query.search === 'undefined' || results.query.searchinfo.totalhits === 0)
		{
			$('.wikibrowser-search-results-title').html('There are no search results for ' + query + '.');
			if (typeof results.query.searchinfo.suggestion !== 'undefined') {
				$('.wikibrowser-search-results-title').append('
Did you mean ' + results.query.searchinfo.suggestion + '?');
			}
		}
		else
		{
			$('.wikibrowser-search-results-title').html('Search results for ' + query + ':');
		}
		/* Remove existing results */
		$('.wikibrowser-search-results').html("");
		console.log("Received search results:");
		console.log(results.query.search);
		for (var index in results.query.search) {
			var resultItem = document.createElement("li");
			var displayTitle = results.query.search[index].titlesnippet !== "" ? results.query.search[index].titlesnippet : results.query.search[index].title;
			console.log(displayTitle);
			$(resultItem).html(displayTitle);
			console.log(resultItem);
			$('.wikibrowser-search-results').append(resultItem);
		}
		/* If not visible, reveal the results */
		$('.wikibrowser-search-results-title').show();
		$('.wikibrowser-search-results').show();
	});
}

function getSearchResults(query, callback) {
	console.log("getSearchResults " + query);
	$.ajax({
	    url : "http://en.wikipedia.org/w/api.php?action=query&list=search&srprop=titlesnippet|redirecttitle&format=json&callback=?&continue=&srsearch=" + query,
	    data: {
	    	format: 'json'
	    },
	    dataType: 'jsonp',
	})
	.done(callback);
}<commit_msg>Adds comment with URL for reference<commit_after>var pageIndex = 0;

$( document ).ready(function() {
  //loadPageIntoElement("JSONP", addPage());
  //loadPageIntoElement("Copenhagen", addPage());
  //addSearchPage();
  setUpSearch();
});

function addPage() {
	var pageId = "page" + pageIndex++;

	var tempContainer = document.createElement("div");
	tempContainer.innerHtml =
'
' +
'
'+
'
'+
'

'+
'
'+
'

'+
'
'+
'
';

	$(".wikibrowser-host").append(tempContainer.innerHtml);

	// Scroll to reveal the new pane
	var newPageOffset = $("#" + pageId).offset().left;
	$(".wikibrowser-host").animate({scrollLeft: newPageOffset}, 400);

	return pageId;
}

function addSearchPage() {
	var pageId = "page" + pageIndex++;

	var tempContainer = document.createElement("div");
	tempContainer.innerHtml =
'
' +
'
'+
'
'+
'

'+
'
'+
'
'+
'
Search
'+
'                        <input type="text" placeholder="Coming soon"></input>
'+
'
Other upcoming features:
'+
'
'+
'
Close and rearrange articles
'+
'
Set bookmarks and leave notes
'+
'
Save, restore and share your layout
'+
'
'+
'
'+
'
How do I use this?
'+
'                        Click on links in Wikipedia articles on the left. They will open new articles side by side!
'+
'
'+
'
'+
'
';

	$(".wikibrowser-host").append(tempContainer.innerHtml);

	return pageId;
}

function loadPageIntoElement(page, element) {
	console.log('load page ' + page);
	$.ajax({
	    url : "http://en.wikipedia.org/w/api.php?action=parse&format=json&callback=?&continue=&page=" + page,
	    data: {
	    	format: 'json'
	    },
	    dataType: 'jsonp',
	    cache: 'true' // defaults to false for jsonp.
	})
	.done(function(data) {
		$( "#" + element + " > .pre-content > h1" ).append( data.parse.displaytitle );
		$( "#" + element + " > .content" ).append( data.parse.text['*'] );
		$( "#" + element + " > .content a").each(fixHyperlink);
		$( "#" + element ).perfectScrollbar({
			wheelSpeed: 3
		});
	});
}

function fixHyperlink(index, element)
{
	var jElement = $(element);
	var address = jElement.attr('href');
	if (address.substring(0, 6) === '/wiki/')
	{
		jElement.attr('href', "http://en.wikipedia.org" + address);
		jElement.on('click', function() {
			loadPageIntoElement(address.substring(6), addPage());
			return false; // prevent going to href (wikipedia)
		})
	}
	if (address.substring(0, 1) !== '#')
	{
		jElement.attr('target', "_blank");
	}
}

function setUpSearch() {
	console.log("setUpSearch");
	var searchBox = $(".wikibrowser-search-content input");
	searchBox.keyup(function(event) {
		if (event.keyCode == 13) {
			console.log("enter");
			goToArticle(searchBox[0].value);
		}
	});
	var goButton = $(".wikibrowser-go-button");
	goButton.on('click', function() {
		goToArticle(searchBox[0].value);
	});
	var searchButton = $(".wikibrowser-search-button");
	searchButton.on('click', function() {
		searchArticle(searchBox[0].value);
	});
}

function goToArticle(query) {
	console.log("goToArticle " + query);
	results = getSearchResults(query, function(results) {
		if (typeof results.query.search === 'undefined' || results.query.searchinfo.totalhits === 0)
		{
			$('.wikibrowser-search-results-title').html('There are no search results for ' + query + '.');
			if (typeof results.query.searchinfo.suggestion !== 'undefined') {
				$('.wikibrowser-search-results-title').append('
Did you mean ' + results.query.searchinfo.suggestion + '?');
			}

		}
		console.log("Go to: ");
		var bestMatch = results.query.search[0];
		console.log(bestMatch);
		loadPageIntoElement(bestMatch.title, addPage());
	});
}

function searchArticle(query) {
	console.log("searchArticle " + query);
	var results = getSearchResults(query, function(results) {
		if (typeof results.query.search === 'undefined' || results.query.searchinfo.totalhits === 0)
		{
			$('.wikibrowser-search-results-title').html('There are no search results for ' + query + '.');
			if (typeof results.query.searchinfo.suggestion !== 'undefined') {
				$('.wikibrowser-search-results-title').append('
Did you mean ' + results.query.searchinfo.suggestion + '?');
			}
		}
		else
		{
			$('.wikibrowser-search-results-title').html('Search results for ' + query + ':');
		}
		/* Remove existing results */
		$('.wikibrowser-search-results').html("");
		console.log("Received search results:");
		console.log(results.query.search);
		for (var index in results.query.search) {
			var resultItem = document.createElement("li");
			var displayTitle = results.query.search[index].titlesnippet !== "" ? results.query.search[index].titlesnippet : results.query.search[index].title;
			console.log(displayTitle);
			$(resultItem).html(displayTitle);
			console.log(resultItem);
			$('.wikibrowser-search-results').append(resultItem);
		}
		/* If not visible, reveal the results */
		$('.wikibrowser-search-results-title').show();
		$('.wikibrowser-search-results').show();
	});
}

function getSearchResults(query, callback) {
	// See: http://www.mediawiki.org/wiki/API:Search
	console.log("getSearchResults " + query);
	$.ajax({
	    url : "http://en.wikipedia.org/w/api.php?action=query&list=search&srprop=titlesnippet|redirecttitle&format=json&callback=?&continue=&srsearch=" + query,
	    data: {
	    	format: 'json'
	    },
	    dataType: 'jsonp',
	})
	.done(callback);
}<|endoftext|>


<commit_before>/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

(function (global) {
  const dateFormat = (() => {
    const token = /d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LlopSZWN]|"[^"]*"|'[^']*'/g;
    const timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g;
    const timezoneClip = /[^-+\dA-Z]/g;

    // Regexes and supporting functions are cached through closure
    return (date, mask, utc, gmt) => {
      // You can't provide utc if you skip other args (use the 'UTC:' mask prefix)
      if (
        arguments.length === 1 &&
        kindOf(date) === "string" &&
        !/\d/.test(date)
      ) {
        mask = date;
        date = undefined;
      }

      date = date || date === 0 ? date : new Date();

      if (!(date instanceof Date)) {
        date = new Date(date);
      }

      if (isNaN(date)) {
        throw TypeError("Invalid date");
      }

      mask = String(
        dateFormat.masks[mask] || mask || dateFormat.masks["default"]
      );

      // Allow setting the utc/gmt argument via the mask
      const maskSlice = mask.slice(0, 4);
      if (maskSlice === "UTC:" || maskSlice === "GMT:") {
        mask = mask.slice(4);
        utc = true;
        if (maskSlice === "GMT:") {
          gmt = true;
        }
      }

      const _ = () => (utc ? "getUTC" : "get");
      const d = () => date[_() + "Date"]();
      const D = () => date[_() + "Day"]();
      const m = () => date[_() + "Month"]();
      const y = () => date[_() + "FullYear"]();
      const H = () => date[_() + "Hours"]();
      const M = () => date[_() + "Minutes"]();
      const s = () => date[_() + "Seconds"]();
      const L = () => date[_() + "Milliseconds"]();
      const o = () => (utc ? 0 : date.getTimezoneOffset());
      const W = () => getWeek(date);
      const N = () => getDayOfWeek(date);

      const flags = {
        d: () => d(),
        dd: () => pad(d()),
        ddd: () => dateFormat.i18n.dayNames[D()],
        DDD: () => getDayName({
          y: y(),
          m: m(),
          D: D(),
          _: _(),
          dayName: dateFormat.i18n.dayNames[D()],
          short: true
        }),
        dddd: () => dateFormat.i18n.dayNames[D() + 7],
        DDDD: () => getDayName({
          y: y(),
          m: m(),
          D: D(),
          _: _(),
          dayName: dateFormat.i18n.dayNames[D() + 7]
        }),
        m: () => m() + 1,
        mm: () => pad(m() + 1),
        mmm: () => dateFormat.i18n.monthNames[m()],
        mmmm: () => dateFormat.i18n.monthNames[m() + 12],
        yy: () => String(y()).slice(2),
        yyyy: () => pad(y(), 4),
        h: () => H() % 12 || 12,
        hh: () => pad(H() % 12 || 12),
        H: () => H(),
        HH: () => pad(H()),
        M: () => M(),
        MM: () => pad(M()),
        s: () => s(),
        ss: () => pad(s()),
        l: () => pad(L(), 3),
        L: () => pad(Math.floor(L() / 10)),
        t: () =>
          H() < 12
            ? dateFormat.i18n.timeNames[0]
            : dateFormat.i18n.timeNames[1],
        tt: () =>
          H() < 12
            ? dateFormat.i18n.timeNames[2]
            : dateFormat.i18n.timeNames[3],
        T: () =>
          H() < 12
            ? dateFormat.i18n.timeNames[4]
            : dateFormat.i18n.timeNames[5],
        TT: () =>
          H() < 12
            ? dateFormat.i18n.timeNames[6]
            : dateFormat.i18n.timeNames[7],
        Z: () =>
          gmt
            ? "GMT"
            : utc
              ? "UTC"
              : (String(date).match(timezone) || [""])
                .pop()
                .replace(timezoneClip, "")
                .replace(/GMT\+0000/g, "UTC"),
        o: () =>
          (o() > 0 ? "-" : "+") +
          pad(Math.floor(Math.abs(o()) / 60) * 100 + (Math.abs(o()) % 60), 4),
        p: () =>
          (o() > 0 ? "-" : "+") +
          pad(Math.floor(Math.abs(o()) / 60), 2) +
          ":" +
          pad(Math.floor(Math.abs(o()) % 60), 2),
        S: () =>
          ["th", "st", "nd", "rd"][
            d() % 10 > 3 ? 0 : (((d() % 100) - (d() % 10) != 10) * d()) % 10
          ],
        W: () => W(),
        N: () => N(),
      };

      return mask.replace(token, (match) => {
        if (match in flags) {
          return flags[match]();
        }
        return match.slice(1, match.length - 1);
      });
    };
  })();

  dateFormat.masks = {
    default: "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    paddedShortDate: "mm/dd/yyyy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:sso",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",
    expiresHeaderFormat: "ddd, dd mmm yyyy HH:MM:ss Z",
  };

  // Internationalization strings
  dateFormat.i18n = {
    dayNames: [
      "Sun",
      "Mon",
      "Tue",
      "Wed",
      "Thu",
      "Fri",
      "Sat",
      "Sunday",
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday",
    ],
    monthNames: [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec",
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December",
    ],
    timeNames: ["a", "p", "am", "pm", "A", "P", "AM", "PM"],
  };

  const pad = (val, len) => {
    val = String(val);
    len = len || 2;
    while (val.length < len) {
      val = "0" + val;
    }
    return val;
  };

  /**
   * Get day name
   * Yesterday, Today, Tomorrow if the date lies within, else fallback to Monday - Sunday
   * @param  {Object}
   * @return {String}
   */
  const getDayName = ({ y, m, D, _, dayName, short = false }) => {
    const today = new Date();
    const yesterday = new Date();
    yesterday.setDate(yesterday[_ + 'Date']() - 1);
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow[_ + 'Date']() + 1);
    const today_D = () => today[_ + 'Day']();
    const today_m = () => today[_ + 'Month']();
    const today_y = () => today[_ + 'FullYear']();
    const yesterday_D = () => yesterday[_ + 'Day']();
    const yesterday_m = () => yesterday[_ + 'Month']();
    const yesterday_y = () => yesterday[_ + 'FullYear']();
    const tomorrow_D = () => tomorrow[_ + 'Day']();
    const tomorrow_m = () => tomorrow[_ + 'Month']();
    const tomorrow_y = () => tomorrow[_ + 'FullYear']();

    if (today_y() === y && today_m() === m && today_D() === D) {
      return short ? 'Tdy' : 'Today';
    }
    else if (yesterday_y() === y && yesterday_m() === m && yesterday_D() === D) {
      return short ? 'Ysd' : 'Yesterday';
    }
    else if (tomorrow_y() === y && tomorrow_m() === m && tomorrow_D() === D) {
      return short ? 'Tmw' : 'Tomorrow';
    }
    return dayName;
  };

  /**
   * Get the ISO 8601 week number
   * Based on comments from
   * http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html
   *
   * @param  {Object} `date`
   * @return {Number}
   */
  const getWeek = (date) => {
    // Remove time components of date
    const targetThursday = new Date(
      date.getFullYear(),
      date.getMonth(),
      date.getDate()
    );

    // Change date to Thursday same week
    targetThursday.setDate(
      targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3
    );

    // Take January 4th as it is always in week 1 (see ISO 8601)
    const firstThursday = new Date(targetThursday.getFullYear(), 0, 4);

    // Change date to Thursday same week
    firstThursday.setDate(
      firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3
    );

    // Check if daylight-saving-time-switch occurred and correct for it
    const ds =
      targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset();
    targetThursday.setHours(targetThursday.getHours() - ds);

    // Number of weeks between target Thursday and first Thursday
    const weekDiff = (targetThursday - firstThursday) / (86400000 * 7);
    return 1 + Math.floor(weekDiff);
  };

  /**
   * Get ISO-8601 numeric representation of the day of the week
   * 1 (for Monday) through 7 (for Sunday)
   *
   * @param  {Object} `date`
   * @return {Number}
   */
  const getDayOfWeek = (date) => {
    let dow = date.getDay();
    if (dow === 0) {
      dow = 7;
    }
    return dow;
  };

  /**
   * kind-of shortcut
   * @param  {*} val
   * @return {String}
   */
  const kindOf = (val) => {
    if (val === null) {
      return "null";
    }

    if (val === undefined) {
      return "undefined";
    }

    if (typeof val !== "object") {
      return typeof val;
    }

    if (Array.isArray(val)) {
      return "array";
    }

    return {}.toString.call(val).slice(8, -1).toLowerCase();
  };

  if (typeof define === "function" && define.amd) {
    define(() => {
      return dateFormat;
    });
  } else if (typeof exports === "object") {
    module.exports = dateFormat;
  } else {
    global.dateFormat = dateFormat;
  }
})(this);
<commit_msg>fix DDD and DDDD masks<commit_after>/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

(function (global) {
  const dateFormat = (() => {
    const token = /d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LlopSZWN]|"[^"]*"|'[^']*'/g;
    const timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g;
    const timezoneClip = /[^-+\dA-Z]/g;

    // Regexes and supporting functions are cached through closure
    return (date, mask, utc, gmt) => {
      // You can't provide utc if you skip other args (use the 'UTC:' mask prefix)
      if (
        arguments.length === 1 &&
        kindOf(date) === "string" &&
        !/\d/.test(date)
      ) {
        mask = date;
        date = undefined;
      }

      date = date || date === 0 ? date : new Date();

      if (!(date instanceof Date)) {
        date = new Date(date);
      }

      if (isNaN(date)) {
        throw TypeError("Invalid date");
      }

      mask = String(
        dateFormat.masks[mask] || mask || dateFormat.masks["default"]
      );

      // Allow setting the utc/gmt argument via the mask
      const maskSlice = mask.slice(0, 4);
      if (maskSlice === "UTC:" || maskSlice === "GMT:") {
        mask = mask.slice(4);
        utc = true;
        if (maskSlice === "GMT:") {
          gmt = true;
        }
      }

      const _ = () => (utc ? "getUTC" : "get");
      const d = () => date[_() + "Date"]();
      const D = () => date[_() + "Day"]();
      const m = () => date[_() + "Month"]();
      const y = () => date[_() + "FullYear"]();
      const H = () => date[_() + "Hours"]();
      const M = () => date[_() + "Minutes"]();
      const s = () => date[_() + "Seconds"]();
      const L = () => date[_() + "Milliseconds"]();
      const o = () => (utc ? 0 : date.getTimezoneOffset());
      const W = () => getWeek(date);
      const N = () => getDayOfWeek(date);

      const flags = {
        d: () => d(),
        dd: () => pad(d()),
        ddd: () => dateFormat.i18n.dayNames[D()],
        DDD: () => getDayName({
          y: y(),
          m: m(),
          d: d(),
          _: _(),
          dayName: dateFormat.i18n.dayNames[D()],
          short: true
        }),
        dddd: () => dateFormat.i18n.dayNames[D() + 7],
        DDDD: () => getDayName({
          y: y(),
          m: m(),
          d: d(),
          _: _(),
          dayName: dateFormat.i18n.dayNames[D() + 7]
        }),
        m: () => m() + 1,
        mm: () => pad(m() + 1),
        mmm: () => dateFormat.i18n.monthNames[m()],
        mmmm: () => dateFormat.i18n.monthNames[m() + 12],
        yy: () => String(y()).slice(2),
        yyyy: () => pad(y(), 4),
        h: () => H() % 12 || 12,
        hh: () => pad(H() % 12 || 12),
        H: () => H(),
        HH: () => pad(H()),
        M: () => M(),
        MM: () => pad(M()),
        s: () => s(),
        ss: () => pad(s()),
        l: () => pad(L(), 3),
        L: () => pad(Math.floor(L() / 10)),
        t: () =>
          H() < 12
            ? dateFormat.i18n.timeNames[0]
            : dateFormat.i18n.timeNames[1],
        tt: () =>
          H() < 12
            ? dateFormat.i18n.timeNames[2]
            : dateFormat.i18n.timeNames[3],
        T: () =>
          H() < 12
            ? dateFormat.i18n.timeNames[4]
            : dateFormat.i18n.timeNames[5],
        TT: () =>
          H() < 12
            ? dateFormat.i18n.timeNames[6]
            : dateFormat.i18n.timeNames[7],
        Z: () =>
          gmt
            ? "GMT"
            : utc
              ? "UTC"
              : (String(date).match(timezone) || [""])
                .pop()
                .replace(timezoneClip, "")
                .replace(/GMT\+0000/g, "UTC"),
        o: () =>
          (o() > 0 ? "-" : "+") +
          pad(Math.floor(Math.abs(o()) / 60) * 100 + (Math.abs(o()) % 60), 4),
        p: () =>
          (o() > 0 ? "-" : "+") +
          pad(Math.floor(Math.abs(o()) / 60), 2) +
          ":" +
          pad(Math.floor(Math.abs(o()) % 60), 2),
        S: () =>
          ["th", "st", "nd", "rd"][
            d() % 10 > 3 ? 0 : (((d() % 100) - (d() % 10) != 10) * d()) % 10
          ],
        W: () => W(),
        N: () => N(),
      };

      return mask.replace(token, (match) => {
        if (match in flags) {
          return flags[match]();
        }
        return match.slice(1, match.length - 1);
      });
    };
  })();

  dateFormat.masks = {
    default: "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    paddedShortDate: "mm/dd/yyyy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:sso",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",
    expiresHeaderFormat: "ddd, dd mmm yyyy HH:MM:ss Z",
  };

  // Internationalization strings
  dateFormat.i18n = {
    dayNames: [
      "Sun",
      "Mon",
      "Tue",
      "Wed",
      "Thu",
      "Fri",
      "Sat",
      "Sunday",
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday",
    ],
    monthNames: [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec",
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December",
    ],
    timeNames: ["a", "p", "am", "pm", "A", "P", "AM", "PM"],
  };

  const pad = (val, len) => {
    val = String(val);
    len = len || 2;
    while (val.length < len) {
      val = "0" + val;
    }
    return val;
  };

  /**
   * Get day name
   * Yesterday, Today, Tomorrow if the date lies within, else fallback to Monday - Sunday
   * @param  {Object}
   * @return {String}
   */
  const getDayName = ({ y, m, d, _, dayName, short = false }) => {
    const today = new Date();
    const yesterday = new Date();
    yesterday.setDate(yesterday[_ + 'Date']() - 1);
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow[_ + 'Date']() + 1);
    const today_d = () => today[_ + 'Date']();
    const today_m = () => today[_ + 'Month']();
    const today_y = () => today[_ + 'FullYear']();
    const yesterday_d = () => yesterday[_ + 'Date']();
    const yesterday_m = () => yesterday[_ + 'Month']();
    const yesterday_y = () => yesterday[_ + 'FullYear']();
    const tomorrow_d = () => tomorrow[_ + 'Date']();
    const tomorrow_m = () => tomorrow[_ + 'Month']();
    const tomorrow_y = () => tomorrow[_ + 'FullYear']();

    if (today_y() === y && today_m() === m && today_d() === d) {
      return short ? 'Tdy' : 'Today';
    }
    else if (yesterday_y() === y && yesterday_m() === m && yesterday_d() === d) {
      return short ? 'Ysd' : 'Yesterday';
    }
    else if (tomorrow_y() === y && tomorrow_m() === m && tomorrow_d() === d) {
      return short ? 'Tmw' : 'Tomorrow';
    }
    return dayName;
  };

  /**
   * Get the ISO 8601 week number
   * Based on comments from
   * http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html
   *
   * @param  {Object} `date`
   * @return {Number}
   */
  const getWeek = (date) => {
    // Remove time components of date
    const targetThursday = new Date(
      date.getFullYear(),
      date.getMonth(),
      date.getDate()
    );

    // Change date to Thursday same week
    targetThursday.setDate(
      targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3
    );

    // Take January 4th as it is always in week 1 (see ISO 8601)
    const firstThursday = new Date(targetThursday.getFullYear(), 0, 4);

    // Change date to Thursday same week
    firstThursday.setDate(
      firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3
    );

    // Check if daylight-saving-time-switch occurred and correct for it
    const ds =
      targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset();
    targetThursday.setHours(targetThursday.getHours() - ds);

    // Number of weeks between target Thursday and first Thursday
    const weekDiff = (targetThursday - firstThursday) / (86400000 * 7);
    return 1 + Math.floor(weekDiff);
  };

  /**
   * Get ISO-8601 numeric representation of the day of the week
   * 1 (for Monday) through 7 (for Sunday)
   *
   * @param  {Object} `date`
   * @return {Number}
   */
  const getDayOfWeek = (date) => {
    let dow = date.getDay();
    if (dow === 0) {
      dow = 7;
    }
    return dow;
  };

  /**
   * kind-of shortcut
   * @param  {*} val
   * @return {String}
   */
  const kindOf = (val) => {
    if (val === null) {
      return "null";
    }

    if (val === undefined) {
      return "undefined";
    }

    if (typeof val !== "object") {
      return typeof val;
    }

    if (Array.isArray(val)) {
      return "array";
    }

    return {}.toString.call(val).slice(8, -1).toLowerCase();
  };

  if (typeof define === "function" && define.amd) {
    define(() => {
      return dateFormat;
    });
  } else if (typeof exports === "object") {
    module.exports = dateFormat;
  } else {
    global.dateFormat = dateFormat;
  }
})(this);
<|endoftext|>


<commit_before>let arg = require('yargs').argv;
let fs = require('fs');
let Conference = artifacts.require("./Conference.sol");

if (!(arg.f && arg.t)) {
  throw('usage: truffle exec scripts/change_owner.js -f original_owner.txt -t address_to_change.txt');
}
module.exports = async function() {
  let conference = await Conference.deployed();
  let from = fs.readFileSync(arg.f, 'utf8').trim().split('\n')[0];
  let to = fs.readFileSync(arg.t, 'utf8').trim().split('\n')[0];
  let owner = await conference.owner.call();
  if (owner != from) {
    throw('current owner', owner, ' does not match with', from);
  }
  await conference.transferOwnership(to, {from:from})
  let new_owner = await conference.owner.call();
  console.log('Changing ownership from ', from, ' to ', to);
  if (new_owner != to) {
    throw('new owner', new_owner, ' does not match with', to);
  }
}
<commit_msg>Added more logging<commit_after>let arg = require('yargs').argv;
let fs = require('fs');
let Conference = artifacts.require("./Conference.sol");

if (!(arg.f && arg.t)) {
  throw('usage: truffle exec scripts/change_owner.js -f original_owner.txt -t address_to_change.txt');
}
module.exports = async function() {

  let from = fs.readFileSync(arg.f, 'utf8').trim().split('\n')[0];
  let to = fs.readFileSync(arg.t, 'utf8').trim().split('\n')[0];
  console.log('Changing ownership from ', from, ' to ', to);
  let conference = await Conference.deployed();
  let owner = await conference.owner.call();
  console.log('owner', owner, from, owner === from)
  if (owner != from) {
    throw('current owner', owner, ' does not match with', from);
  }
  var result = await conference.transferOwnership(to, {from:from})
  let new_owner = await conference.owner.call();
  if (new_owner != to) {
    throw('new owner', new_owner, ' does not match with', to);
  }
}
<|endoftext|>


<commit_before>// Extensions
(function( undefined ){
	wrap.fn.filter = function( sel ){
		var ret = [],
			sel = wrap( sel );
		this.each(function( i ){
			if( wrap.inArray( sel, this ) ){
				ret.push( this );
			}
		});
		return wrap( ret );
	};
})();<commit_msg>emboldened the filter method to work with unappended nodes. This helps with filtering content before it's inserted into the dom.<commit_after>// Extensions
(function( undefined ){
	wrap.fn.filter = function( sel ){
		var ret = [],
			wsel =  wrap( sel );

		this.each(function(){

			if( !this.parentNode ){
				var context = wrap( document.createDocumentFragment() );
				context[ 0 ].appendChild( this );
				wsel = wrap( sel, context );
			}

			if( wrap.inArray( wsel, this ) ){
				ret.push( this );
			}
		});

		return wrap( ret );
	};
})();<|endoftext|>


<commit_before>var simplebug = simplebug || {};

simplebug.BugInfo = Backbone.Model.extend({
  urlRoot: function() {
    var url = "https://api-dev.bugzilla.mozilla.org/latest/bug/";
    var limit = "?include_fields=comments,url,summary,whiteboard,id";
    return url + this.get('bugID') + limit;
  },
  defaults: {
    domain: "your site."
  },
  parse: function(response, options) {
    var defaultDomain = this.defaults.domain;
    function getDomain(url) {
      if (url) {
        var a = document.createElement('a');
        a.href = url;
        return a.hostname
      } else {
        return defaultDomain;
      }
    }
    // stash whiteboard and summary so BugComments model can peek at it
    simplebug.whiteboard = response.whiteboard || "";
    simplebug.summary = response.summary || "";

    this.set({
      bugID:  response.id,
      url:    response.url,
      domain: getDomain(response.url)
    });
  }
});

simplebug.BugComments = Backbone.Model.extend({
  urlRoot: function() {
    var url = "https://api-dev.bugzilla.mozilla.org/latest/bug/";
    var limit = "/comment";
    return url + this.get('bugID') + limit;
  },
  defaults: {
    suggestedfix: "The recommended way to detect Firefox and other mobile browsers is by searching for the string “Mobi”. This can be implemented through custom code or through a library/framework. If it is through a library/framework you can check that it is up to date or reach out to the vendor for more information. Mozilla Developer Network has detailed information on user agent detection."
  },
  description: function(type) {
      type = type || "server or client";
      var copy = "This website is using " + type + " side user agent detection to determine if a user is browsing using a desktop or mobile client. Unfortunately the site is not properly detecting the user agent string for mobile Firefox browsers. This is causing Firefox mobile browsers to be redirected to the desktop version of the website rather than mobile.";
      return copy;
  },
  parse: function(response, options) {
    this.sanitize(response.comments);
    this.set("firstComment", response.comments[0].raw_text.trim());
    this.getDescription(response);
    this.getSuggestedFix(response);
    this.set("summary", this.sanitize(simplebug.summary));
  },
  sanitize: function(commentsArray) {
    // clean up any codenames that make little sense to the outside world
    // Also escape text to be HTML safe.
    function replaceCodewords(string) {
      return _.escape(string.replace(/b2g/ig, 'Firefox OS')
                            .replace(/fxos/ig, 'Firefox OS')
                            .replace(/fennec/ig, 'Firefox for Android'));
    }

    if (!$.isArray(commentsArray) && typeof commentsArray == "string") {
        // it's the summary, so replace junk and return.
        return replaceCodewords(commentsArray);
    }

    $.each(commentsArray, function(index, item) {
      item.raw_text = replaceCodewords(item.raw_text);
    });
  },
  getTaggedComment: function(tag, comments) {
    var result = false;
    // loop from the bottom up. in case there are multiple results --
    // we only want the latest one.
    for (var i = comments.length - 1; i >= 0; i--) {
      if (comments[i].tags && comments[i].tags.indexOf(tag) != -1) {
        result = [tag, comments[i].raw_text];
        break;
      }
    }
    // result is either a useful array, or `false`.
    return result;
  },
  getDefaultDescription: function() {
    if (simplebug.whiteboard && /(server|client)/.exec(simplebug.whiteboard)) {
      return this.description(RegExp.$1);
    }
  },
  getDescription: function(response) {
    // if any comment is tagged "description", use it.
    var descriptionTag = this.getTaggedComment("description", response.comments);
    if (descriptionTag) {
      this.set(descriptionTag[0], descriptionTag[1]);
    } else {
      // if first comment is tagged "simplebug-ignore", use default.
      // OR if the first comment is empty, use default.
      var ignoreTag = this.getTaggedComment("simplebug-ignore", response.comments);
      if (ignoreTag || this.get("firstComment") === "") {
        this.set("description", this.getDefaultDescription());
      } else {
        // Use first comment (which is the description in the Bugzilla UI)
        this.set("description", this.get("firstComment"));
      }
    }
  },
  getSuggestedFix: function(response){
    var suggestedfixTag = this.getTaggedComment("suggestedfix", response.comments);
    if (suggestedfixTag) {
        this.set(suggestedfixTag[0], suggestedfixTag[1]);
    } // otherwise it will use defaults.suggestedfix
  }
});

simplebug.HeaderView = Backbone.View.extend({
  tagName: 'h1',
  template: _.template($('#header-tmpl').html()),
  render: function() {
    this.$el.html(this.template(this.model.attributes));
    return this;
  }
});

simplebug.URLView = Backbone.View.extend({
  tagName: 'p',
  template: _.template($('#url-tmpl').html()),
  render: function() {
    this.$el.html(this.template(this.model.attributes));
    return this;
  }
});

simplebug.Description = Backbone.View.extend({
  template: _.template($('#description-tmpl').html()),
  render: function() {
    this.$el.html(this.template(this.model.attributes));
    return this;
  }
});

simplebug.SuggestedFix = Backbone.View.extend({
  template: _.template($('#suggestedfix-tmpl').html()),
  render: function() {
    this.$el.html(this.template(this.model.attributes));
    return this;
  }
});

simplebug.MoreInfo = Backbone.View.extend({
  tagName: 'p',
  template: _.template($('#information-tmpl').html()),
  render: function() {
    this.$el.html(this.template(this.model.attributes));
    return this;
  }
});

simplebug.MainView = Backbone.View.extend({
  el: $('#buginfo'),
  initialize: function(opts) {
    $('#main-loader').show();
    $('#index').hide();
    // set up models
    this.bugInfo = new simplebug.BugInfo({bugID: opts.bugID});
    this.bugComments = new simplebug.BugComments({bugID: opts.bugID});
    this.initSubViews();
    this.fetchModels();
  },
  initSubViews: function() {
    this.url = new simplebug.URLView({model: this.bugInfo});
    this.header = new simplebug.HeaderView({model: this.bugInfo});
    this.moreInfo = new simplebug.MoreInfo({model: this.bugInfo});
    this.desc = new simplebug.Description({model: this.bugComments});
    this.suggestedFix = new simplebug.SuggestedFix({model: this.bugComments});
  },
  fetchModels: function() {
    var self = this;
    this.bugInfo.fetch().success(function(){
      self.url.setElement(self.$('#url')).render();
      self.header.setElement(self.$('.general')).render();
      self.moreInfo.setElement(self.$('#information')).render();
      self.bugComments.fetch().success(function(){
        self.desc.setElement(self.$('#description')).render();
        self.suggestedFix.setElement(self.$('#suggestedfix')).render();
        $('#main-loader, #error').fadeOut(300);
        // render() the MainView.
        // Note, we can move this up above this fetch() if we want to show
        // the explanation before we add in the description and suggestedfix
        // That makes the page feel faster, maybe.
        self.render();
      }).error(function(){console.log("TODO: actual error handling >_>");});
    }).error(function(){$('#error').show();});
  },
  render: function() {
    this.$el.fadeIn();
  }
});

simplebug.Router = Backbone.Router.extend({
    routes: {
        "mozilla/:id":  "showBug",
        "*catchall": "index",
    },
    initialize: function () {},
    index: function() {
      // backwards compatibility with early version of simplebug
      // that only used a single id get param.
      var oldParam;
      if (oldParam = location.href.match(/\?id=(\d+)/)) {
        if (history.replaceState) history.replaceState({}, "", "index.html");
        this.navigate("mozilla/" + oldParam[1], {trigger: true});
      }
      $('#main-loader').hide();
    },
    showBug: function(id) {
      //need to validate id.
      document.title = "Web Compatibility Error Report for " + id;
      this.mainView = new simplebug.MainView({bugID: id});
    }
});
/* Let's get this party started. */
jQuery.ajaxSetup({timeout: 7500});
new simplebug.Router();
Backbone.history.start();
<commit_msg>Fixes #39. Update Bugzilla API endpoint.<commit_after>var simplebug = simplebug || {};

simplebug.BugInfo = Backbone.Model.extend({
  urlRoot: function() {
    var url = "https://bugzilla.mozilla.org/rest/bug/";
    var limit = "?include_fields=comments,url,summary,whiteboard,id";
    return url + this.get('bugID') + limit;
  },
  defaults: {
    domain: "your site."
  },
  parse: function(response, options) {
    var response = response.bugs[0];
    var defaultDomain = this.defaults.domain;
    function getDomain(url) {
      if (url) {
        var a = document.createElement('a');
        a.href = url;
        return a.hostname
      } else {
        return defaultDomain;
      }
    }
    // stash whiteboard and summary so BugComments model can peek at it
    simplebug.whiteboard = response.whiteboard || "";
    simplebug.summary = response.summary || "";

    this.set({
      bugID:  response.id,
      url:    response.url,
      domain: getDomain(response.url)
    });
  }
});

simplebug.BugComments = Backbone.Model.extend({
  urlRoot: function() {
    var url = "https://bugzilla.mozilla.org/rest/bug/";
    var limit = "/comment";
    return url + this.get('bugID') + limit;
  },
  defaults: {
    suggestedfix: "The recommended way to detect Firefox and other mobile browsers is by searching for the string “Mobi”. This can be implemented through custom code or through a library/framework. If it is through a library/framework you can check that it is up to date or reach out to the vendor for more information. Mozilla Developer Network has detailed information on user agent detection."
  },
  description: function(type) {
      type = type || "server or client";
      var copy = "This website is using " + type + " side user agent detection to determine if a user is browsing using a desktop or mobile client. Unfortunately the site is not properly detecting the user agent string for mobile Firefox browsers. This is causing Firefox mobile browsers to be redirected to the desktop version of the website rather than mobile.";
      return copy;
  },
  initialize: function(options) {
    this.bugID = options.bugID;
  },
  parse: function(response, options) {
    var response = response.bugs[this.bugID];
    this.sanitize(response.comments);
    this.set("firstComment", response.comments[0].raw_text.trim());
    this.getDescription(response);
    this.getSuggestedFix(response);
    this.set("summary", this.sanitize(simplebug.summary));
  },
  sanitize: function(commentsArray) {
    // clean up any codenames that make little sense to the outside world
    // Also escape text to be HTML safe.
    function replaceCodewords(string) {
      return _.escape(string.replace(/b2g/ig, 'Firefox OS')
                            .replace(/fxos/ig, 'Firefox OS')
                            .replace(/fennec/ig, 'Firefox for Android'));
    }

    if (!$.isArray(commentsArray) && typeof commentsArray == "string") {
        // it's the summary, so replace junk and return.
        return replaceCodewords(commentsArray);
    }

    $.each(commentsArray, function(index, item) {
      item.raw_text = replaceCodewords(item.raw_text);
    });
  },
  getTaggedComment: function(tag, comments) {
    var result = false;
    // loop from the bottom up. in case there are multiple results --
    // we only want the latest one.
    for (var i = comments.length - 1; i >= 0; i--) {
      if (comments[i].tags && comments[i].tags.indexOf(tag) != -1) {
        result = [tag, comments[i].raw_text];
        break;
      }
    }
    // result is either a useful array, or `false`.
    return result;
  },
  getDefaultDescription: function() {
    if (simplebug.whiteboard && /(server|client)/.exec(simplebug.whiteboard)) {
      return this.description(RegExp.$1);
    }
  },
  getDescription: function(response) {
    // if any comment is tagged "description", use it.
    var descriptionTag = this.getTaggedComment("description", response.comments);
    if (descriptionTag) {
      this.set(descriptionTag[0], descriptionTag[1]);
    } else {
      // if first comment is tagged "simplebug-ignore", use default.
      // OR if the first comment is empty, use default.
      var ignoreTag = this.getTaggedComment("simplebug-ignore", response.comments);
      if (ignoreTag || this.get("firstComment") === "") {
        this.set("description", this.getDefaultDescription());
      } else {
        // Use first comment (which is the description in the Bugzilla UI)
        this.set("description", this.get("firstComment"));
      }
    }
  },
  getSuggestedFix: function(response){
    var suggestedfixTag = this.getTaggedComment("suggestedfix", response.comments);
    if (suggestedfixTag) {
        this.set(suggestedfixTag[0], suggestedfixTag[1]);
    } // otherwise it will use defaults.suggestedfix
  }
});

simplebug.HeaderView = Backbone.View.extend({
  tagName: 'h1',
  template: _.template($('#header-tmpl').html()),
  render: function() {
    this.$el.html(this.template(this.model.attributes));
    return this;
  }
});

simplebug.URLView = Backbone.View.extend({
  tagName: 'p',
  template: _.template($('#url-tmpl').html()),
  render: function() {
    this.$el.html(this.template(this.model.attributes));
    return this;
  }
});

simplebug.Description = Backbone.View.extend({
  template: _.template($('#description-tmpl').html()),
  render: function() {
    this.$el.html(this.template(this.model.attributes));
    return this;
  }
});

simplebug.SuggestedFix = Backbone.View.extend({
  template: _.template($('#suggestedfix-tmpl').html()),
  render: function() {
    this.$el.html(this.template(this.model.attributes));
    return this;
  }
});

simplebug.MoreInfo = Backbone.View.extend({
  tagName: 'p',
  template: _.template($('#information-tmpl').html()),
  render: function() {
    this.$el.html(this.template(this.model.attributes));
    return this;
  }
});

simplebug.MainView = Backbone.View.extend({
  el: $('#buginfo'),
  initialize: function(opts) {
    $('#main-loader').show();
    $('#index').hide();
    // set up models
    this.bugInfo = new simplebug.BugInfo({bugID: opts.bugID});
    this.bugComments = new simplebug.BugComments({bugID: opts.bugID});
    this.initSubViews();
    this.fetchModels();
  },
  initSubViews: function() {
    this.url = new simplebug.URLView({model: this.bugInfo});
    this.header = new simplebug.HeaderView({model: this.bugInfo});
    this.moreInfo = new simplebug.MoreInfo({model: this.bugInfo});
    this.desc = new simplebug.Description({model: this.bugComments});
    this.suggestedFix = new simplebug.SuggestedFix({model: this.bugComments});
  },
  fetchModels: function() {
    var self = this;
    this.bugInfo.fetch().success(function(){
      self.url.setElement(self.$('#url')).render();
      self.header.setElement(self.$('.general')).render();
      self.moreInfo.setElement(self.$('#information')).render();
      self.bugComments.fetch().success(function(){
        self.desc.setElement(self.$('#description')).render();
        self.suggestedFix.setElement(self.$('#suggestedfix')).render();
        $('#main-loader, #error').fadeOut(300);
        // render() the MainView.
        // Note, we can move this up above this fetch() if we want to show
        // the explanation before we add in the description and suggestedfix
        // That makes the page feel faster, maybe.
        self.render();
      }).error(function(){console.log("TODO: actual error handling >_>");});
    }).error(function(){$('#error').show();});
  },
  render: function() {
    this.$el.fadeIn();
  }
});

simplebug.Router = Backbone.Router.extend({
    routes: {
        "mozilla/:id":  "showBug",
        "*catchall": "index",
    },
    initialize: function () {},
    index: function() {
      // backwards compatibility with early version of simplebug
      // that only used a single id get param.
      var oldParam;
      if (oldParam = location.href.match(/\?id=(\d+)/)) {
        if (history.replaceState) history.replaceState({}, "", "index.html");
        this.navigate("mozilla/" + oldParam[1], {trigger: true});
      }
      $('#main-loader').hide();
    },
    showBug: function(id) {
      //need to validate id.
      document.title = "Web Compatibility Error Report for " + id;
      this.mainView = new simplebug.MainView({bugID: id});
    }
});
/* Let's get this party started. */
jQuery.ajaxSetup({timeout: 7500});
new simplebug.Router();
Backbone.history.start();
<|endoftext|>


<commit_before>udefine(['clamp'], function(clamp) {
  return function(min, max, amt) {
    var tmpAmt = clamp(amt, 0.0, 1.0);
    var diff = Math.abs(max - min);

    if (diff === 0) {
      return min;
    } else {
      return min + (diff * tmpAmt);
    }
  };
});
<commit_msg>Remove transition stub<commit_after><|endoftext|>


<commit_before>// @flow

import React, { Component, Children, cloneElement, type ReactElement } from 'react';
import { View, Animated, StyleSheet, ScrollView, Dimensions } from 'react-native';
import AnimatedOverlay from 'react-native-animated-overlay';

import Separator from './Separator';
import Animation from './Animation';

const { width: WIDTH, height: HEIGHT } = Dimensions.get('window');

// action sheet states
const ACTION_SHEET_OPENING: string = 'opening';
const ACTION_SHEET_OPENED: string = 'opened';
const ACTION_SHEET_CLOSING: string = 'closing';
const ACTION_SHEET_CLOSED: string = 'closed';

const DEFAULT_ANIMATION_DURATION: number = 250;

const INITIAL_TOP_POSITION: number = -180;
const INITIAL_BOTTOM_POSITION: number = HEIGHT * -1;

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 0,
    left: 0,
    backgroundColor: 'white',
  },
  contentContainer: {
    width: WIDTH,
    position: 'absolute',
    backgroundColor: 'white',
  },
  scrollView: {
  },
});

type Props = {
  onShow?: () => void;
  onHide?: () => void;
  show?: boolean;
  animationDuration?: number;
  overlayOpacity?: number;
  position?: 'top' | 'bottom';
  onChange?: () => void;
  multi?: boolean;
  showSparator?: boolean;
  children?: any;
};

const defaultProps = {
  onShow: () => {},
  onHide: () => {},
  show: false,
  animationDuration: DEFAULT_ANIMATION_DURATION,
  overlayOpacity: 0.3,
  position: 'top',
  onChange: () => {},
  multi: false,
  showSparator: true,
  children: null,
};

class ActionSheet extends Component {
  props: Props

  static defaultProps = defaultProps

  constructor(props: Props) {
    super(props);

    this.state = {
      show: props.show,
      selectedData: {},
      actionSheetState: ACTION_SHEET_CLOSED,
      actionSheetAnimation: new Animation(this.hideActionSheetPosition),
    };
  }

  componentDidMount() {
    if (this.props.show) {
      this.show();
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.show !== nextProps.show) {
      if (nextProps.show) {
        this.show();
      } else {
        this.hide();
      }
    }
  }

  get showActionSheetPosition(): string {
    const { position } = this.props;
    if (position === 'top') {
      return INITIAL_TOP_POSITION * -1;
    }
    return 0;
  }

  get hideActionSheetPosition(): string {
    const { position } = this.props;
    if (position === 'top') {
      return INITIAL_TOP_POSITION;
    }
    return INITIAL_BOTTOM_POSITION * -1;
  }

  onOverlayPress = (): void => {
    this.hide();
  }

  setActionSheetState(toValue: number, callback?: Function = () => {}): void {
    const { animationDuration } = this.props;
    const isClosed = (this.state.actionSheetState === ACTION_SHEET_CLOSED);

    let actionSheetState = isClosed ? ACTION_SHEET_OPENING : ACTION_SHEET_CLOSING;

    this.setState({ actionSheetState });

    this.state.actionSheetAnimation.toValue(toValue, animationDuration, () => {
      const isClosing = (this.state.actionSheetState === ACTION_SHEET_CLOSING);
      actionSheetState = isClosing ? ACTION_SHEET_CLOSED : ACTION_SHEET_OPENED;

      this.setState({ actionSheetState });
      callback();
    });
  }

  show = (callback?: Function = () => {}): void => {
    if ([ACTION_SHEET_OPENING, ACTION_SHEET_OPENED].includes(this.state.actionSheetState)) {
      return;
    }

    const { onShow } = this.props;

    this.setState({ show: true });
    this.setActionSheetState(this.showActionSheetPosition);
    onShow();
    callback();
  }

  hide = (callback?: Function = () => {}): void => {
    if ([ACTION_SHEET_CLOSING, ACTION_SHEET_CLOSED].includes(this.state.actionSheetState)) {
      return;
    }

    const { onHide } = this.props;

    this.setState({ show: false });
    this.setActionSheetState(this.hideActionSheetPosition);
    onHide();
    callback();
  }

  onItemPress(value, index): void {
    if (this.state.selectedData[index]) {
      this.unselectItem(value, index);
      return;
    }

    this.selectItem(value, index);
  }

  selectItem(value, index) {
    const { multi: isMultiSelect, onChange } = this.props;
    let selectedData;

    if (isMultiSelect) {
      selectedData = { ...this.state.selectedData };
    } else {
      selectedData = {};
    }

    selectedData[index] = value;
    this.setState({ selectedData });
    onChange(value, index);
  }

  unselectItem(value, index) {
    const { multi: isMultiSelect, onChange } = this.props;
    let selectedData;

    if (isMultiSelect) {
      selectedData = { ...this.state.selectedData };
      delete selectedData[index];
    } else {
      selectedData = {};
    }

    this.setState({ selectedData });
    onChange(value, index);
  }

  isItemSelected(index): boolean {
    return !!this.state.selectedData[index];
  }

  renderItems(): ReactElement {
    const { children, showSparator } = this.props;
    const separator = showSparator ? <Separator /> : null;

    return Children.map(children, (child, index) => {
      const item = cloneElement(child, {
        index,
        selected: this.isItemSelected(index),
        onPress: (value, index) => {
          child.props.onPress(value, index);
          this.onItemPress(value, index);
        },
      });

      return (
        <View style={{ flex: 1 }}>
          {item}
          {separator}
        </View>
      );
    });
  }

  render() {
    const { animationDuration, overlayOpacity, position } = this.props;
    const { actionSheetState, actionSheetAnimation: { animations } } = this.state;

    const overlayShow = [ACTION_SHEET_OPENED, ACTION_SHEET_OPENING].includes(actionSheetState);
    const pointerEvents = (actionSheetState === ACTION_SHEET_OPENED) ? 'auto' : 'none';

    const contentPosition = (position === 'top')
      ? { top: INITIAL_TOP_POSITION }
      : { bottom: INITIAL_BOTTOM_POSITION };

    const scrollView = (position === 'top')
      ? { paddingTop: 30 }
      : null;

    return (
      <View style={[styles.container]}>
        <AnimatedOverlay
          onPress={this.onOverlayPress}
          overlayShow={overlayShow}
          duration={animationDuration}
          opacity={overlayOpacity}
          pointerEvents={pointerEvents}
        />
        <Animated.View
          style={[styles.contentContainer, contentPosition, animations]}
        >
          <ScrollView style={[styles.scrollView, scrollView]}>
            {this.renderItems()}
          </ScrollView>
        </Animated.View>
      </View>
    );
  }
}

export default ActionSheet;
<commit_msg>add defautSelected and hideOnSelected prop<commit_after>// @flow

import React, { Component, Children, cloneElement, type ReactElement } from 'react';
import { View, Animated, StyleSheet, ScrollView, Dimensions } from 'react-native';
import AnimatedOverlay from 'react-native-animated-overlay';

import Separator from './Separator';
import Animation from './Animation';

const { width: WIDTH, height: HEIGHT } = Dimensions.get('window');

// action sheet states
const ACTION_SHEET_OPENING: string = 'opening';
const ACTION_SHEET_OPENED: string = 'opened';
const ACTION_SHEET_CLOSING: string = 'closing';
const ACTION_SHEET_CLOSED: string = 'closed';

const DEFAULT_ANIMATION_DURATION: number = 250;

const INITIAL_TOP_POSITION: number = -180;
const INITIAL_BOTTOM_POSITION: number = HEIGHT * -1;

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 0,
    left: 0,
    backgroundColor: 'white',
  },
  contentContainer: {
    width: WIDTH,
    position: 'absolute',
    backgroundColor: 'white',
  },
  scrollView: {
  },
  hidden: {
    top: -10000,
    left: 0,
    height: 0,
    width: 0,
  },
});

type Props = {
  onShow?: () => void;
  onHide?: () => void;
  show?: boolean;
  animationDuration?: number;
  overlayOpacity?: number;
  position?: 'top' | 'bottom';
  onChange?: () => void;
  multi?: boolean;
  showSparator?: boolean;
  defaultSelected: any;
  hideOnSelceted?: boolean;
  children?: any;
};

const defaultProps = {
  onShow: () => {},
  onHide: () => {},
  show: false,
  animationDuration: DEFAULT_ANIMATION_DURATION,
  overlayOpacity: 0.3,
  position: 'top',
  onChange: () => {},
  multi: false,
  showSparator: true,
  defaultSelected: null,
  hideOnSelceted: true,
  children: null,
};

class ActionSheet extends Component {
  props: Props

  static defaultProps = defaultProps

  constructor(props: Props) {
    super(props);

    // set default selected
    const { defaultSelected } = props;
    const selectedData = {};
    props.children.forEach((child, index) => {
      (Array.isArray(defaultSelected) ? defaultSelected : [defaultSelected]).forEach((selected) => {
        if (child.props.value === selected) {
          if (props.multi) {
            selectedData[index] = child.props.value;
          } else if (Object.keys(selectedData).length === 0) {
            selectedData[index] = child.props.value;
          }
        }
      });
    });

    this.state = {
      show: props.show,
      selectedData,
      actionSheetState: ACTION_SHEET_CLOSED,
      actionSheetAnimation: new Animation(this.hideActionSheetPosition),
    };
  }

  componentDidMount() {
    if (this.props.show) {
      this.show();
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.position !== nextProps.position) {
      this.setState({ actionSheetAnimation: new Animation(this.hideActionSheetPosition) });
    }

    if (this.props.show !== nextProps.show) {
      if (nextProps.show) {
        this.show();
      } else {
        this.hide();
      }
    }

    nextProps.children.forEach((child, index) => {
      if (child.props.selected && !this.state.selectedData[index]) {
        const selectedData = { ...this.state.selectedData };
        selectedData[index] = child.props.value;
        this.setState({ selectedData });
      }
    });
  }

  get showActionSheetPosition(): string {
    const { position } = this.props;
    if (position === 'top') {
      return INITIAL_TOP_POSITION * -1;
    }
    return 0;
  }

  get hideActionSheetPosition(): string {
    const { position } = this.props;
    if (position === 'top') {
      return INITIAL_TOP_POSITION;
    }
    return INITIAL_BOTTOM_POSITION * -1;
  }

  onOverlayPress = (): void => {
    this.hide();
  }

  setActionSheetState(toValue: number, callback?: Function = () => {}): void {
    const { animationDuration } = this.props;
    const isClosed = (this.state.actionSheetState === ACTION_SHEET_CLOSED);

    let actionSheetState = isClosed ? ACTION_SHEET_OPENING : ACTION_SHEET_CLOSING;

    this.setState({ actionSheetState });

    this.state.actionSheetAnimation.toValue(toValue, animationDuration, () => {
      const isClosing = (this.state.actionSheetState === ACTION_SHEET_CLOSING);
      actionSheetState = isClosing ? ACTION_SHEET_CLOSED : ACTION_SHEET_OPENED;

      this.setState({ actionSheetState });
      callback();
    });
  }

  show = (callback?: Function = () => {}): void => {
    if ([ACTION_SHEET_OPENING, ACTION_SHEET_OPENED].includes(this.state.actionSheetState)) {
      return;
    }

    const { onShow } = this.props;

    this.setState({ show: true });
    this.setActionSheetState(this.showActionSheetPosition);
    onShow();
    callback();
  }

  hide = (callback?: Function = () => {}): void => {
    if ([ACTION_SHEET_CLOSING, ACTION_SHEET_CLOSED].includes(this.state.actionSheetState)) {
      return;
    }

    const { onHide } = this.props;

    this.setState({ show: false });
    this.setActionSheetState(this.hideActionSheetPosition);
    onHide();
    callback();
  }

  onItemPress(value, index): void {
    const { hideOnSelceted } = this.props;
    if (hideOnSelceted) {
      this.hide();
    }

    if (this.state.selectedData[index]) {
      this.unselectItem(value, index);
      return;
    }

    this.selectItem(value, index);
  }

  selectItem(value, index) {
    const { multi: isMultiSelect, onChange } = this.props;
    let selectedData;

    if (isMultiSelect) {
      selectedData = { ...this.state.selectedData };
    } else {
      selectedData = {};
    }

    selectedData[index] = value;
    this.setState({ selectedData });
    onChange(value, index);
  }

  unselectItem(value, index) {
    const { multi: isMultiSelect, onChange } = this.props;
    let selectedData;

    if (isMultiSelect) {
      selectedData = { ...this.state.selectedData };
      delete selectedData[index];
    } else {
      selectedData = {};
    }

    this.setState({ selectedData });
    onChange(value, index);
  }

  isItemSelected(index): boolean {
    return !!this.state.selectedData[index];
  }

  renderItems(): ReactElement {
    const { children, showSparator } = this.props;
    const separator = showSparator ? <Separator /> : null;

    return Children.map(children, (child, index) => {
      const item = cloneElement(child, {
        index,
        selected: child.props.selected || this.isItemSelected(index),
        onPress: (value, selectedIndex) => {
          child.props.onPress(value, selectedIndex);
          this.onItemPress(value, selectedIndex);
        },
      });

      return (
        <View style={{ flex: 1 }}>
          {item}
          {separator}
        </View>
      );
    });
  }

  render() {
    const { animationDuration, overlayOpacity, position } = this.props;
    const { actionSheetState, actionSheetAnimation: { animations } } = this.state;

    const overlayShow = [ACTION_SHEET_OPENED, ACTION_SHEET_OPENING].includes(actionSheetState);
    const pointerEvents = (actionSheetState === ACTION_SHEET_OPENED) ? 'auto' : 'none';
    const hidden = actionSheetState === ACTION_SHEET_CLOSED && styles.hidden;

    const contentPosition = (position === 'top')
      ? { top: INITIAL_TOP_POSITION }
      : { bottom: INITIAL_BOTTOM_POSITION };

    const scrollView = (position === 'top')
      ? { paddingTop: 30 }
      : null;

    return (
      <View style={[styles.container, hidden]}>
        <AnimatedOverlay
          onPress={this.onOverlayPress}
          overlayShow={overlayShow}
          duration={animationDuration}
          opacity={overlayOpacity}
          pointerEvents={pointerEvents}
        />
        <Animated.View
          style={[styles.contentContainer, contentPosition, animations]}
        >
          <ScrollView style={[styles.scrollView, scrollView]}>
            {this.renderItems()}
          </ScrollView>
        </Animated.View>
      </View>
    );
  }
}

export default ActionSheet;
<|endoftext|>


<commit_before>// Limit scope pollution from any deprecated API
(function() {

var matched, browser;

// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
	ua = ua.toLowerCase();

	var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
		/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
		/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
		/(msie) ([\w.]+)/.exec( ua ) ||
		ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
		[];

	return {
		browser: match[ 1 ] || "",
		version: match[ 2 ] || "0"
	};
};

matched = jQuery.uaMatch( navigator.userAgent );
browser = {};

if ( matched.browser ) {
	browser[ matched.browser ] = true;
	browser.version = matched.version;
}

// Deprecated, use jQuery.browser.webkit instead
// Maintained for back-compat only
if ( browser.webkit ) {
	browser.safari = true;
}

jQuery.browser = browser;

jQuery.sub = function() {
	function jQuerySub( selector, context ) {
		return new jQuerySub.fn.init( selector, context );
	}
	jQuery.extend( true, jQuerySub, this );
	jQuerySub.superclass = this;
	jQuerySub.fn = jQuerySub.prototype = this();
	jQuerySub.fn.constructor = jQuerySub;
	jQuerySub.sub = this.sub;
	jQuerySub.fn.init = function init( selector, context ) {
		if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
			context = jQuerySub( context );
		}

		return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
	};
	jQuerySub.fn.init.prototype = jQuerySub.fn;
	var rootjQuerySub = jQuerySub(document);
	return jQuerySub;
};

})();
<commit_msg>Fix #12333. Chrome needs $.browser.webkit too.<commit_after>// Limit scope pollution from any deprecated API
(function() {

var matched, browser;

// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
	ua = ua.toLowerCase();

	var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
		/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
		/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
		/(msie) ([\w.]+)/.exec( ua ) ||
		ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
		[];

	return {
		browser: match[ 1 ] || "",
		version: match[ 2 ] || "0"
	};
};

matched = jQuery.uaMatch( navigator.userAgent );
browser = {};

if ( matched.browser ) {
	browser[ matched.browser ] = true;
	browser.version = matched.version;
}

// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
	browser.webkit = true;
} else if ( browser.webkit ) {
	browser.safari = true;
}

jQuery.browser = browser;

jQuery.sub = function() {
	function jQuerySub( selector, context ) {
		return new jQuerySub.fn.init( selector, context );
	}
	jQuery.extend( true, jQuerySub, this );
	jQuerySub.superclass = this;
	jQuerySub.fn = jQuerySub.prototype = this();
	jQuerySub.fn.constructor = jQuerySub;
	jQuerySub.sub = this.sub;
	jQuerySub.fn.init = function init( selector, context ) {
		if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
			context = jQuerySub( context );
		}

		return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
	};
	jQuerySub.fn.init.prototype = jQuerySub.fn;
	var rootjQuerySub = jQuerySub(document);
	return jQuerySub;
};

})();
<|endoftext|>


<commit_before>const debug = require('debug')('restinga-node:descriptor');
const {version} = require('../package.json');

export default class Descriptor {
	/**
	 * @param {Object} params
	 */
	constructor({service, headers, prefix, agent}) {
		debug(`Creating Descriptor ${service}`);

		this.service = service;
		this.headers = headers;
		this.prefix = prefix;
		this.agent = agent || `restinga-node/${version} (https://github.com/jay-ess/restinga-node)`;
	}
}

<commit_msg>Remove dead code<commit_after>const debug = require('debug')('restinga-node:descriptor');
const {version} = require('../package.json');

export default class Descriptor {
	/**
	 * @param {Object} params
	 */
	constructor({service, prefix, agent}) {
		debug(`Creating Descriptor ${service}`);

		this.service = service;
		this.prefix = prefix;
		this.agent = agent || `restinga-node/${version} (https://github.com/jay-ess/restinga-node)`;
	}
}

<|endoftext|>


<commit_before>'use strict';

const constants = require('../constants');
const filters = require('./filters');
const updates = require('./updates');
const validate_doc_update = require('./validateDocUpdate');
const views = require('./views');

module.exports = function getDesignDoc(custom) {
    custom = custom || {};
    return {
        _id: constants.DESIGN_DOC_ID,
        language: 'javascript',
        version: constants.DESIGN_DOC_VERSION,
        customVersion: custom.version,
        filters: Object.assign({}, custom.filters, filters),
        updates: Object.assign({}, custom.updates, updates),
        views: Object.assign({}, custom.views, views),
        validate_doc_update
    };
};
<commit_msg>Add lists<commit_after>'use strict';

const constants = require('../constants');
const filters = require('./filters');
const updates = require('./updates');
const validate_doc_update = require('./validateDocUpdate');
const views = require('./views');

module.exports = function getDesignDoc(custom) {
    custom = custom || {};
    return {
        _id: constants.DESIGN_DOC_ID,
        language: 'javascript',
        version: constants.DESIGN_DOC_VERSION,
        customVersion: custom.version,
        filters: Object.assign({}, custom.filters, filters),
        updates: Object.assign({}, custom.updates, updates),
        views: Object.assign({}, custom.views, views),
        validate_doc_update,
        lists: Object.assign({}, custom.lists)
    };
};
<|endoftext|>