code stringlengths 2 1.05M |
|---|
var MONTHS = ["Bogus", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var results = [];
var numberOfPlayers;
var numberOfEvents;
var timer;
var tacdOutput = "";
var tacdQuarter;
var tacdYear;
var officers = {};
var finishedOfficers = true;
var parkName;
var isNorthernEmpirePark = false;
var quarters = [];
var numberOfDays = 0;
var startDate = null;
var endDate = null;
var eventPark = null;
quarters['1'] = ['01', '02', '03'];
quarters['2'] = ['04', '05', '06'];
quarters['3'] = ['07', '08', '09'];
quarters['4'] = ['10', '11', '12'];
quarter = quarters[1];
var playedWithinOneYear = [];
function awardsFromPlayerData(pageContent) {
var $pageContent = $(pageContent);
var awards = ["Order of the Dragon", "Order of the Flame", "Order of the Garber", "Order of the Gryphon", "Order of the Hydra", "Order of the Jovious", "Order of the Lion", "Order of the Mask", "Order of the Owl", "Order of the Rose", "Order of the Smith", "Order of the Warrior", "Order of the Zodiac", "Master Archer", "Master Assassin", "Master Barbarian", "Master Monk", "Master Scout", "Master Warrior", "Master Bard", "Master Druid", "Master Healer", "Master Wizard", "Master Anti-Paladin", "Master Paladin"];
var arrayLength = awards.length;
var players = $pageContent.find("a[href*='Route=Player']");
numberOfPlayers = players.length;
players.each(function(index, player) {
var url = new URL(player.href);
url.protocol = 'https';
$.get(url.href, function( data ) {
var $playerHTML = $(data);
var persona = $playerHTML.find("span:contains('Persona:')").next().html();
var outputLine = persona + "\t";
for (var i = 0; i < arrayLength; i++) {
var award = awards[i];
var awardCount = $playerHTML.find("#Awards td:contains('" + award + "')").length;
if (award.startsWith("Master ")) {
if (awardCount > 0) {
outputLine = outputLine + "Yes";
}
} else {
outputLine = outputLine + awardCount;
}
if (i < arrayLength - 1)
outputLine = outputLine + "\t";
}
results = results.concat(outputLine + "\r\n");
});
});
timer = setInterval(waitForAwards, 1000);
}
function attendanceFromPlayerDataGV(pageContent, minAttendance, parkNumber) {
var $pageContent = $(pageContent);
var parkName = parkNameFrom($pageContent);
var players = $pageContent.find("a[href*='Route=Player']");
isNorthernEmpirePark = checkIfNorthernEmpirePark($pageContent);
moment.updateLocale('en', {
week: {
dow: 0,
},
});
numberOfPlayers = players.length;
players.each(function(index, player) {
var url = new URL(player.href);
// set up a date at midnight 6 months ago at the beginning of the Goldenvale week starting on Sunday
var sixMonthsAgo = setMomentToMidnight(moment());
sixMonthsAgo.set('month', sixMonthsAgo.get('month') - 6);
sixMonthsAgo.startOf('week');
var earliestAttendance;
url.protocol = 'https';
$.get(url.href, function( data ) {
var currentWeek = null;
var attendanceCount = 0;
var $playerHTML = $(data);
var $attendance = $($($playerHTML.find("#Attendance thead")[1]).parent().children()[1]).children();
var persona = $playerHTML.find("span:contains('Persona:')").next().html();
var duesPaid = $playerHTML.find("span:contains('Dues Paid:')").next().html();
if (duesPaid != "No") {
duesPaid = moment(duesPaid) <= moment() ? "No" : "Yes";
}
var parks = [];
$attendance.each(function() {
$attendanceTR = $(this);
$attendanceDateTD = $attendanceTR.children().first();
var newAttendanceInWeek = false;
var dateText = $attendanceDateTD.text();
console.log("<" + dateText + "> for " + persona);
attendanceDate = setMomentToMidnightPlusOne(moment(dateText));
earliestAttendance = attendanceDate;
var validParkOrEvent = false;
var wasEvent = false;
attendancePark = $($attendanceTR.children()[2]).text();
if (attendancePark.length == 0) {
attendancePark = $($attendanceTR.children()[3]).text();
wasEvent = true;
validParkOrEvent = true;
} else {
if (parkName === attendancePark) {
validParkOrEvent = true;
}
}
if (validParkOrEvent && attendanceDate > sixMonthsAgo) {
if (currentWeek) {
if (attendanceDate < currentWeek) {
newAttendanceInWeek = true;
}
} else {
newAttendanceInWeek = true;
}
if (newAttendanceInWeek) {
currentWeek = startOfWeekFor(attendanceDate);
attendanceCount = attendanceCount + 1;
if (wasEvent) {
parks.push(attendancePark);
} else {
if (!parks.includes(attendancePark)) {
parks.push(attendancePark);
}
}
}
}
});
meetsStartingAttendance = isNorthernEmpirePark ? earliestAttendance <= sixMonthsAgo : true;
results.push(persona + "\t" + (((attendanceCount > (minAttendance - 1)) && meetsStartingAttendance) ? 'yes' : 'no') + "\t" + attendanceCount + "\t" + duesPaid + "\t" + parks.join(", ") + "\r\n");
});
});
timer = setInterval(waitForAttendance, 1000);
}
function attendanceFromPlayerDataNB(pageContent, minAttendance) {
var $pageContent = $(pageContent);
var parkName = parkNameFrom($pageContent);
var players = $pageContent.find("a[href*='Route=Player']");
isNorthernEmpirePark = checkIfNorthernEmpirePark($pageContent);
numberOfPlayers = players.length;
moment.updateLocale('en', {
week: {
dow: 1,
},
});
players.each(function(index, player) {
var url = new URL(player.href);
// set up a date at midnight 6 months ago at the beginning of the Goldenvale week starting on Sunday
var sixMonthsAgo = setMomentToMidnight(moment());
sixMonthsAgo.set('month', sixMonthsAgo.get('month') - 6);
sixMonthsAgo.startOf('week');
var earliestAttendance;
url.protocol = 'https';
$.get(url.href, function( data ) {
var currentWeek = null;
var attendanceCount = 0;
var $playerHTML = $(data);
var $attendance = $($($playerHTML.find("#Attendance thead")[1]).parent().children()[1]).children();
var persona = $playerHTML.find("span:contains('Persona:')").next().html();
var duesPaid = $playerHTML.find("span:contains('Dues Paid:')").next().html();
if (duesPaid != "No") {
duesPaid = moment(duesPaid) <= moment() ? "No" : "Yes";
}
var parks = [];
$attendance.each(function() {
$attendanceTR = $(this);
$attendanceDateTD = $attendanceTR.children().first();
var newAttendanceInWeek = false;
var dateText = $attendanceDateTD.text();
console.log("<" + dateText + "> for " + persona);
attendanceDate = setMomentToMidnightPlusOne(moment(dateText));
earliestAttendance = attendanceDate;
attendancePark = $($attendanceTR.children()[2]).text();
if (attendancePark.length > 0 && attendancePark === parkName) {
if (attendanceDate > sixMonthsAgo) {
if (currentWeek) {
if (attendanceDate < currentWeek) {
newAttendanceInWeek = true;
}
} else {
newAttendanceInWeek = true;
}
if (newAttendanceInWeek) {
currentWeek = startOfWeekFor(attendanceDate);
attendanceCount = attendanceCount + 1;
if (!parks.includes(attendancePark)) {
parks.push(attendancePark);
}
}
}
}
});
meetsStartingAttendance = isNorthernEmpirePark ? earliestAttendance <= sixMonthsAgo : true;
results.push(persona + "\t" + (((attendanceCount > (minAttendance - 1)) && meetsStartingAttendance) ? 'yes' : 'no') + "\t" + attendanceCount + "\t" + duesPaid + "\t" + parks.join(", ") + "\r\n");
});
});
timer = setInterval(waitForAttendance, 1000);
}
function retirementCheckFromRetiredData(pageContent) {
var $pageContent = $(pageContent);
var players = $pageContent.find("a[href*='Route=Player']");
numberOfPlayers = players.length;
// set up a date at midnight eight months ago at the beginning of the Goldenvale week starting on Sunday
var eightMonthsAgo = setMomentToMidnight(moment());
eightMonthsAgo.set('month', eightMonthsAgo.get('month') - 8);
eightMonthsAgo.startOf('week');
var counter = 0;
players.each(function(index, player) {
counter = counter + 1;
var urlAttendance = new URL(player.href);
urlAttendance.protocol = 'https';
$.get(urlAttendance.href, function( data ) {
var $playerHTML = $(data);
var $attendance = $($($playerHTML.find("#Attendance thead")[1]).parent().children()[1]).children();
var personaAttendance = $playerHTML.find("span:contains('Persona:')").next().html();
var withinOneYear = false;
var foundButOlderThanOneYear = false;
$attendance.each(function() {
if (!withinOneYear && !foundButOlderThanOneYear) {
$attendanceTR = $(this);
$attendanceDateTD = $attendanceTR.children().first();
var newAttendanceInWeek = false;
var dateText = $attendanceDateTD.text();
// console.log("<" + dateText + "> for " + personaAttendance);
attendanceDate = setMomentToMidnightPlusOne(moment(dateText));
if (attendanceDate > eightMonthsAgo) {
withinOneYear = true;
}
if (attendanceDate < eightMonthsAgo) {
foundButOlderThanOneYear = true;
}
}
});
if (personaAttendance == "" || personaAttendance == "...") {
console.log("removing (" + personaAttendance + ")");
numberOfPlayers = numberOfPlayers - 1;
} else {
if (personaAttendance in playedWithinOneYear) {
numberOfPlayers = numberOfPlayers - 1;
} else {
if (withinOneYear) {
var playerNumber = this.url.split("/").pop();
playedWithinOneYear[personaAttendance] = "https://ork.amtgard.com/orkui/index.php?Route=Player/index/" + playerNumber;
} else {
numberOfPlayers = numberOfPlayers - 1;
}
}
}
});
});
timer = setInterval(waitForRetiredCheck, 1000);
}
function awardsFromParkURL(parkURL) {
var parkNumber = parkNumberFromURL(parkURL);
$.get("https://ork.amtgard.com/orkui/index.php?Route=Reports/roster/Park&id=" + parkNumber, function( data ) {
awardsFromPlayerData(data);
});
}
function attendance8in6FromParkURL(parkURL) {
var parkNumber = parkNumberFromURL(parkURL);
$.get("https://ork.amtgard.com/orkui/index.php?Route=Reports/roster/Park&id=" + parkNumber, function( data ) {
attendanceFromPlayerData(data, 8);
});
}
function attendanceKingdomFromParkURL(parkURL) {
var parkNumber = parkNumberFromURL(parkURL);
$.get("https://ork.amtgard.com/orkui/index.php?Route=Reports/roster/Park&id=" + parkNumber, function( data ) {
attendanceFromPlayerDataGV(data, 10, parkNumber);
});
}
function attendanceNorthernEmpireFromParkURL(parkURL) {
var parkNumber = parkNumberFromURL(parkURL);
$.get("https://ork.amtgard.com/orkui/index.php?Route=Reports/roster/Park&id=" + parkNumber, function( data ) {
attendanceFromPlayerDataNB(data, 6, parkNumber);
});
}
function retiredCheckFromParkURL(parkURL) {
var parkNumber = parkNumberFromURL(parkURL);
$.get("https://ork.amtgard.com/orkui/index.php?Route=Reports/inactive/Park&id=" + parkNumber, function( data ) {
retirementCheckFromRetiredData(data);
});
}
function tacdFromParkURL(parkURL, aQuarter, aYear) {
var parkNumber = parkNumberFromURL(parkURL);
tacdQuarter = aQuarter;
tacdYear = aYear;
var goldenvalePark;
quarter = quarters[tacdQuarter];
$.get(parkURL, function( data ) {
$parkData = $(data);
isNorthernEmpirePark = checkIfNorthernEmpirePark($parkData);
parkName = parkNameFrom($parkData);
numMonths = 14;
attendanceDates = new Array();
playerList = new HashMap();
console.log("============== " + parkName + " ==============");
getOfficers('https://ork.amtgard.com/orkui/index.php?Route=Admin/setparkofficers&ParkId=' + parkNumber);
aURL = 'https://ork.amtgard.com/orkui/index.php?Route=Reports/attendance/Park/' + parkNumber + '/Months/' + numMonths;
getAttendanceDates(aURL);
});
}
function eventAttendance(parkURL, theStartDate, theEndDate) {
startDate = theStartDate;
endDate = theEndDate;
movingStartDate = moment(theStartDate);
var parkNumber = parkNumberFromURL(parkURL);
uniquePlayerIDsForEvent = new Array();
numberOfDays = endDate.diff(startDate, "days") + 1;
$.get(parkURL, function( data ) {
$parkData = $(data);
eventPark = parkNameFrom($parkData);
timer = setInterval(waitForEventAttendance, 1000);
for (var m = movingStartDate; movingStartDate.isSameOrBefore(endDate); movingStartDate.add(1, 'days')) {
var dateURL = "https://ork.amtgard.com/orkui/index.php?Route=Attendance/park/" + parkNumber + "&AttendanceDate=" + m.format('YYYY-MM-DD');
uniquesForAttendanceFromUrl(dateURL, uniquePlayerIDsForEvent);
}
});
}
function uniquesForAttendanceFromUrl(dateURL, uniques) {
$.get(dateURL, function( data ) {
var $playersHTML = $(data);
$playersHTML.find('.information-table').children().last().children().each(function(index, player) {
$player = $(player);
var playerHref = $($player.children()[2])[0].children[0].href;
var lastSlash = playerHref.lastIndexOf("/");
var playerID = playerHref.substr(lastSlash + 1);
if (uniques.indexOf(playerID) == -1) {
uniques.push(playerID);
}
});
results.push('more');
});
}
function getOfficers(officersURL) {
var fields = ['user', 'player', 'role', 'position', 'hidden1', 'hidden2'];
$.get(officersURL, function( data ) {
$officerData = $(data);
$officerList = $officerData.find('.information-table').children().first().next().children();
$officerList.each(function() {
anOfficer = {};
var fieldPosition = 0;
var $officerRow = $(this).first().children()
$officerRow.each(function () {
$rowItem = $(this);
anOfficer[fields[fieldPosition]] = $rowItem.text();
fieldPosition++;
});
if (anOfficer['position']) {
officers[anOfficer['position']] = anOfficer;
}
});
finishedOfficers = true;
});
}
function waitForAwards() {
if (results.length == numberOfPlayers) {
clearInterval(timer);
results.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
results.unshift("Persona\tDragon\tFlame\tGarber\tGryphon\tHydra\tJovious\tLion\tMask\tOwl\tRose\tSmith\tWarrior\tZodiac\tMaster Archer\tMaster Assassin\tMaster Barbari`an\tMaster Monk\tMaster Scout\tMaster Warrior\tMaster Bard\tMaster Druid\tMaster Healer\tMaster Wizard\tMaster Anti-Paladin\tMaster Paladin\r\n");
$('#status').html("Done!<br>The results are in your clipboard<br>You should be able to paste<br>directly into a spreadsheet");
$('#loader').hide();
copyTextToClipboard(results.join(""));
} else {
$('#status').html(results.length + " of " + numberOfPlayers + " players")
}
}
function waitForAttendance() {
if (results.length == numberOfPlayers) {
clearInterval(timer);
results.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
results.unshift("Persona\tQualified\tTimes in last 6 Months\tDues Paid\tParks\r\n");
$('#status').html("Done!<br>The results are in your clipboard<br>You should be able to paste<br>directly into a spreadsheet");
$('#loader').hide();
copyTextToClipboard(results.join(""));
} else {
$('#status').html(results.length + " of " + numberOfPlayers + " players")
}
}
function waitForEventAttendance() {
if (results.length === numberOfDays) {
clearInterval(timer);
uniquePlayersForEvent = new Array();
timer = setInterval(waitForEventAttendanceNamesAndParks, 1000);
uniquePlayerIDsForEvent.forEach(function(id) {
personaURL = "https://ork.amtgard.com/orkui/index.php?Route=Player/index/" + id;
$.get(personaURL, function( data ) {
$personaData = $(data);
isNorthernEmpirePark = checkIfNorthernEmpirePark($personaData);
parkName = parkNameFrom($personaData);
persona = personaFrom($personaData);
kingdom = kingdomFrom($personaData);
uniquePlayersForEvent.push({ persona: persona, parkName: parkName, kingdom: kingdom, isNorthernEmpirePark: isNorthernEmpirePark } );
})
});
} else {
$('#status').html(results.length + " of " + numberOfDays + " days to go")
}
}
function waitForEventAttendanceNamesAndParks() {
if (uniquePlayersForEvent.length === uniquePlayerIDsForEvent.length) {
clearInterval(timer);
output = [];
var sortedPlayers = uniquePlayersForEvent.sort(function (a, b) {
if (a.kingdom === b.kingdom) {
if (a.parkName === b.parkName) {
return a.persona.toLowerCase().localeCompare(b.persona.toLowerCase());
}
return a.parkName.toLowerCase().localeCompare(b.parkName.toLowerCase());
}
return a.kingdom.toLowerCase().localeCompare(b.kingdom.toLowerCase());
});
output.push(sortedPlayers.length + " unique signatures for the " + eventPark + " event dates " + startDate.format('YYYY-MM-DD') + " to " + endDate.format('YYYY-MM-DD') + "\r\n");
sortedPlayers.forEach( function (player) {
output.push(player.persona + "\t" + player.parkName + "\t" + player.kingdom + "\r\n");
})
copyTextToClipboard(output.join(""));
$('#status').html("Done!<br>The unique attendance results are in your clipboard<br>You should be able to paste<br>directly into a spreadsheet or document");
$('#loader').hide();
} else {
$('#status').html("Finding parks for " + uniquePlayersForEvent.length + " of " + uniquePlayerIDsForEvent.length + " personas")
}
}
function waitForRetiredCheck() {
var currentCount = Object.keys(playedWithinOneYear).length;
if (currentCount == numberOfPlayers) {
clearInterval(timer);
results.unshift("Persona\tPlayer URL\r\n");
var sortedPersonas = Object.keys(playedWithinOneYear).sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
sortedPersonas.forEach( function (persona) {
results.push(persona + "\t" + playedWithinOneYear[persona] + "\r\n");
})
$('#status').html("Done!<br>The results are in your clipboard<br>You should be able to paste<br>directly into a spreadsheet");
$('#loader').hide();
copyTextToClipboard(results.join(""));
} else {
$('#status').html(currentCount + " of " + numberOfPlayers + " players")
}
}
function waitForTaCD() {
if (results.length == numberofEvents && finishedOfficers) {
clearInterval(timer);
output = [];
kingdom = isNorthernEmpirePark ? "Pricipality of the Nine Blades" : "Kingdom of Goldenvale";
output.push("== " + quarterAbbreviation(tacdQuarter) + " quarter, " + tacdYear + " TacD for " + parkName + " in the " + kingdom + " ==\r\n\r\n");
monarch = officers['Monarch'];
output.push("Monarch: " + monarch['player'] + " (ORK id: " + monarch['user'] + ") \r\n\r\n");
output.push("Email or Contact Info: ____________________________________\r\n\r\n");
primeminister = officers['Prime Minister'];
output.push("Prime Minister: " + primeminister['player'] + " (ORK id: " + primeminister['user'] + ") \r\n\r\n");
output.push("Email or Contact Info: ____________________________________\r\n\r\n");
regent = officers['Regent'];
output.push("Regent: " + regent['player'] + " (ORK id: " + regent['user'] + ") \r\n\r\n");
output.push("Email or Contact Info: ____________________________________\r\n\r\n");
champion = officers['Champion'];
output.push("Champion: " + champion['player'] + " (ORK id: " + champion['user'] + ") \r\n\r\n");
output.push("Email or Contact Info: ____________________________________\r\n\r\n");
output.push("Year\tMonth\t1-15th\t16th-on\ttotal unique attendance\r\n");
playerList.forEach(function(aMonthMap, aYear) {
if (aYear == tacdYear) {
aMonthMap.forEach(function(breakdown, aMonth) {
if (quarter.indexOf(aMonth) != -1) {
output.push(aYear + "\t" + aMonth + "\t" + breakdown.get('begin').length + "\t" + breakdown.get('end').length + "\t" + breakdown.get('month').length + "\r\n");
}
})
}
})
output.push("\r\n\r\n");
if (!isNorthernEmpirePark) {
quarter.forEach(function(aMonth) {
output.push("\r\nFor " + MONTHS[parseInt(aMonth)] + ", _________ terms of dues paid by ____________________________________");
output.push("\r\nexample 3 terms of dues paid (Ann x2 and Bob x1)\r\n");
});
output.push("\r\n_____ Total terms of dues paid, ____ ");
}
appendInstructions(output, isNorthernEmpirePark);
copyTextToClipboard(output.join(""));
$('#status').html("Done!<br>The TaCD results are in your clipboard<br>You should be able to paste<br>directly into an email");
$('#loader').hide();
$("#rerun-tacd").show();
} else {
$('#status').html("Looking at " + results.length + " of " + numberofEvents + " attendance dates")
}
}
function copyTextToClipboard(text) {
var copyFrom = $('<textarea/>');
copyFrom.css({
position: "absolute",
left: "-1000px",
top: "-1000px",
});
copyFrom.text(text);
$('body').append(copyFrom);
copyFrom.select();
document.execCommand('copy');
}
function parkNumberFromURL(parkURL) {
return parkURL.slice(parkURL.indexOf('index/') + 6);
}
function setMomentToMidnight(aMoment) {
aMoment.set('hour', 0);
aMoment.set('minue', 0);
aMoment.set('second', 0);
aMoment.set('millisecond', 0);
return aMoment;
}
function setMomentToMidnightPlusOne(aMoment) {
setMomentToMidnight(aMoment);
aMoment.set('second', 1);
return aMoment;
}
function startOfWeekFor(aMoment) {
var startOfWeek = aMoment.clone();
setMomentToMidnight(startOfWeek);
startOfWeek.startOf('week');
return startOfWeek;
}
function checkIfNorthernEmpirePark($pageContent) {
return $($($($pageContent.children()[1]).children()[0]).children()[2]).text() === "Principality of the Nine Blades";
}
function kingdomFrom($pageContent) {
return $($($($pageContent.children()[1]).children()[0]).children()[2]).text();
}
function parkNameFrom($pageContent) {
// return $($($pageContent.children()[1]).children()[3]).text()
return $($($($pageContent.children()[1]).children()[0]).children()[3]).text();
}
function personaFrom($pageContent) {
// return $($($pageContent.children()[1]).children()[3]).text()
return $($($($pageContent.children()[1]).children()[0]).children()[4]).text();
}
function getPlayersFromUrl(playersURL, aBeginEnd, aMonth) {
$.get(playersURL, function( data ) {
var $playersHTML = $(data);
$playersHTML.find('.information-table').children().last().children().each(function(index, player) {
$player = $(player);
playerName = $($player.children()[2]).text();
if (aBeginEnd.indexOf(playerName) == -1)
aBeginEnd.push(playerName);
// console.log(beginEnd);
if (aMonth.indexOf(playerName) == -1)
aMonth.push(playerName);
// console.log(aMonth);
});
results.push('more');
});
}
function getAttendanceDates(attendanceURL) {
$.get(attendanceURL, function( data ) {
var $attendanceURL = $(data);
var $attendanceDates = $attendanceURL.find('.information-table').children().first().next().children();
numberofEvents = $attendanceDates.length;
$attendanceDates.each(function(index, attendanceDate) {
$attendanceDate = $(attendanceDate);
aDateURL = "https:" + $attendanceDate.attr('onclick').substring($attendanceDate.attr('onclick').indexOf('//'));
aDateURL = aDateURL.substring(0, aDateURL.length - 1);
aDate = $attendanceDate.children().first().text();
aMonthList = monthListForDate(aDate);
beginEnd = null;
if (aDate.split('-')[2] < 16) {
beginEnd = aMonthList.get('begin');
} else {
beginEnd = aMonthList.get('end');
}
getPlayersFromUrl(aDateURL, beginEnd, aMonthList.get('month'));
});
timer = setInterval(waitForTaCD, 1000);
});
}
function monthListForDate(aDate) {
dateArray = aDate.split('-');
year = dateArray[0];
month = dateArray[1];
day = dateArray[2];
yearMap = null;
monthMap = null;
yearMap = playerList.get(year);
if (!yearMap) {
yearMap = new HashMap();
playerList.set(year, yearMap);
}
monthMap = yearMap.get(month);
if (!monthMap) {
monthMap = new HashMap();
monthMap.set("begin", new Array());
monthMap.set("end", new Array());
monthMap.set("month", new Array());
yearMap.set(month, monthMap);
}
return monthMap;
}
function quarterAbbreviation(quarter) {
switch(quarter) {
case 1:
return '1st';
case 2:
return '2nd';
case 3:
return '3rd';
case 4:
return '4th';
}
}
function appendInstructions(output, isNorthernEmpirePark) {
var instructions1 = "\r\n\r\nHERE IS WHAT YOU HAVE TO DO:\r\n\r\n\
If your Officers do not look right then the ORK is not right, I just grab it from there.\r\n\
Sadly, I cannot get the email addresses from the ORK. So that is a manual task on your side.\r\n\
Take everything above after you have modified it and email it to the Goldenvale Prime Minister. That email address can \
be found on the Facebook Goldenvale Officers page. If you do not have access ask Ken Walker.\r\n\r\n";
var gvInstructions = "Goldenvale CORE Parks you have to update your specific page with your \
officers contact information. If you have updated that you should be able to find that on your own ORK officers page. \
The other thing you have to do is enter in the \
terms paid per month, by whom and for how many terms they paid.\r\b\r\n";
var instructions2 = "Technically for the latest TaCD you do not need the mid month attendance but sometimes it may be useful so I am leaving it in there.\r\n\r\n\
Any issues, please PM me or comment on the GV Officers Page,\r\n\
Ken Walker, Lord Kismet of Felfrost, Mover of Bits (ok, I made that up)";
output.push(instructions1);
if (!isNorthernEmpirePark) {
output.push(gvInstructions);
}
output.push(instructions2);
}
|
const fs = require('fs')
function hasABBA(str){
return str.match(/(\S)((?!\1).)\2\1/);
}
function splitOutSections(str){
return str.split(/\[.*?\]/)
}
function getHypertext(str){
return str.match(/\[(.*?)\]/g)
}
function isValid(str){
return splitOutSections(str).some(hasABBA) &&
getHypertext(str).every((str) => !hasABBA(str));
}
lines = fs.readFileSync("../day7.txt", "utf8").split("\n");
console.log(lines.filter(isValid).length); |
var React = require('react');
var _ = require('lodash');
var { getJSON } = require('./backend');
const formatCode = code => _.chunk(code, 3).map(c => c.join('')).join('-');
const formatIndex = index => index > 9 ? index : ' ' + index;
const PrintPage = React.createClass({
getInitialState() {
return {
codes: []
};
},
componentWillMount() {
getJSON('/admin/print').then(({ codes }) => {
this.setState({
codes
});
});
},
renderBlock(codes) {
return _.zip(...codes).map((voteSessionCodes, index) => (
voteSessionCodes.map((code) => (
(formatIndex(index + 1)) + ' ' + formatCode(code)
)).join('\t')
)).join('\n');
},
render() {
const { codes } = this.state;
return (
<pre className="code-wrapper">
{
_.chunk(
_.chunk(codes, 4).map(this.renderBlock),
3
).map(
triple => triple.join('\n'.repeat(3))
)
.join('\n'.repeat(3))
}
</pre>
);
}
});
module.exports = PrintPage;
|
import jsdom from 'jsdom';
describe('bundle', function() {
it('should corectly wire-up all the dependencies via their UMD-exposed globals', function(done) {
jsdom.env({
html: '<html></html>',
virtualConsole: jsdom.createVirtualConsole().sendTo(console),
scripts: [
// transitive dependencies
'./node_modules/d3-array/build/d3-array.js',
'./node_modules/d3-collection/build/d3-collection.js',
'./node_modules/d3-color/build/d3-color.js',
'./node_modules/d3-format/build/d3-format.js',
'./node_modules/d3-interpolate/build/d3-interpolate.js',
'./node_modules/d3-time-format/build/d3-time-format.js',
// direct dependencies
'./node_modules/d3-scale/build/d3-scale.js',
'./node_modules/d3-time/build/d3-time.js',
'./node_modules/d3fc-rebind/build/d3fc-rebind.js',
'./build/d3fc-discontinuous-scale.js'
],
done: (_, win) => {
const scale = win.fc.scaleDiscontinuous();
const scaled = scale(23);
expect(scaled).not.toBeUndefined();
done();
}
});
});
});
|
/**
* @file guildMemberRemove event
* @author Sankarsan Kampa (a.k.a k3rn31p4nic)
* @license GPL-3.0
*/
module.exports = async member => {
try {
let guildModel = await member.client.database.models.guild.findOne({
attributes: [ 'farewell', 'farewellMessage', 'farewellTimeout', 'serverLog' ],
where: {
guildID: member.guild.id
}
});
if (!guildModel) return;
if (guildModel.dataValues.farewell) {
let farewellMessage = guildModel.dataValues.farewellMessage && Object.keys(guildModel.dataValues.farewellMessage).length ? guildModel.dataValues.farewellMessage : { text: 'May we meet again.' };
farewellMessage = JSON.stringify(farewellMessage);
farewellMessage = member.client.methods.replaceMemberVariables(farewellMessage, member);
let text, embed;
farewellMessage = JSON.parse(farewellMessage);
text = farewellMessage.text ? farewellMessage.text : null;
delete farewellMessage.text;
embed = Object.keys(farewellMessage).length ? farewellMessage : null;
if (embed) {
embed.footer = {};
embed.footer.text = 'Farewell!';
}
let farewellChannel = member.guild.channels.get(guildModel.dataValues.farewell);
if (farewellChannel) {
let farewell;
if (text && embed) {
farewell = await farewellChannel.send(text, { embed: embed }).catch(e => {
member.client.log.error(e);
});
}
else if (text) {
farewell = await farewellChannel.send({
embed: {
color: member.client.colors.RED,
description: text,
footer: {
text: 'Farewell!'
}
}
}).catch(e => {
member.client.log.error(e);
});
}
else if (embed) {
farewell = await farewellChannel.send({ embed: embed }).catch(e => {
member.client.log.error(e);
});
}
if (farewell && guildModel.dataValues.farewellTimeout > 0) {
await farewell.delete(1000 * parseInt(guildModel.dataValues.farewellTimeout)).catch(e => {
member.client.log.error(e);
});
}
}
}
if (guildModel.dataValues.serverLog) {
if (member.guild.me && member.guild.me.hasPermission('BAN_MEMBERS')) {
let bannedUsers = await member.guild.fetchBans();
if (bannedUsers.has(member.id)) return;
}
let logChannel = member.guild.channels.get(guildModel.dataValues.serverLog);
if (logChannel) {
logChannel.send({
embed: {
color: member.guild.client.colors.RED,
title: member.guild.client.i18n.event(member.guild.language, 'guildMemberRemove'),
fields: [
{
name: 'User',
value: member.user.tag,
inline: true
},
{
name: 'User ID',
value: member.id,
inline: true
}
],
timestamp: new Date()
}
}).catch(e => {
member.guild.client.log.error(e);
});
}
}
}
catch (e) {
member.client.log.error(e);
}
};
|
//<![CDATA[
// Emoticon bar before comment-form
function rpl4rt()
{
window.open("http://ferdhika31.github.io/emot/","_blank"," width=700, height=400");
}
$(function() {
$(putEmoAbove)
.before('<div style="text-align:center" class="emoWrap"> :o :calangap B-) :gaya :P :wle :D :grin (y) :ye :/ :hah <br/><br/><a onclick="rpl4rt()" class="button">Lainnya</a> <br/></div>');
var emo = function(emo, imgRep, emoKey) {
$(emoRange)
.each(function() {
$(this)
.html($(this)
.html()
.replace(/<br>:/g, "<br> :")
.replace(/<br>;/g, "<br> ;")
.replace(/<br>=/g, "<br> =")
.replace(/<br>\^/g, "<br> ^")
.replace(emo, " <img style='max-height:24px' src='" + imgRep + "' class='emo delayLoad' alt='" + emoKey + "' />"));
});
};
emo(/\s:o/ig, "http://4.bp.blogspot.com/-NrgNszQXsK4/UvtxFVwRENI/AAAAAAAACgg/a5Fi5cjyxd0/s1600/1.gif", ":o");
emo(/\s:calangap/ig, "http://3.bp.blogspot.com/-BlTC_3BeDqQ/UvuFJxMjfTI/AAAAAAAACjI/UVStKr-Oli0/s1600/1.png", ":calangap");
emo(/\sB-\)+/g, "http://3.bp.blogspot.com/-BSmiqmChkF0/UvtxNgG_dII/AAAAAAAACiI/AkNTJoYMFlY/s1600/3.gif", "B-)");
emo(/\s:gaya/ig, "http://1.bp.blogspot.com/-4xHfnoJkiwI/UvuHfb_novI/AAAAAAAACjY/ocuyCMQIEME/s1600/2.png", ":gaya");
emo(/\s:P/ig, "http://2.bp.blogspot.com/-Yv41tVfYDug/UvtxPSYDDjI/AAAAAAAACiY/V3_3k9lbHTY/s1600/5.gif", ":P");
emo(/\s:wle/ig, "http://3.bp.blogspot.com/-W8GvX9X4BP0/UvuHfVlEPPI/AAAAAAAACjU/2LiTkbxFuE8/s1600/3.png", ":wle");
emo(/\s:D/ig, "http://3.bp.blogspot.com/-MrxS0RD-GS4/UvtxP2uxbsI/AAAAAAAACio/NLfLmEIenrM/s1600/7.gif", ":D");
emo(/\s:grin/ig, "http://1.bp.blogspot.com/-3ftXP96pexw/UvuHf-ktU5I/AAAAAAAACjo/liCBh7ta424/s1600/4.png", ":grin");
emo(/\s\(y\)+/ig, "http://4.bp.blogspot.com/-XTyJblQXK9I/UvtxRP4W1uI/AAAAAAAACi0/s1FBJVV0J3Y/s1600/9.gif", "(y)");
emo(/\s:ye/ig, "http://2.bp.blogspot.com/-b6nnkpFfULs/UvuHgc5Q1jI/AAAAAAAACjk/8Mj-OuFA4wk/s1600/5.png", ":ye");
emo(/\s:\/+/g, "http://4.bp.blogspot.com/-Fs39wfzsczs/UvtxF5ZF4sI/AAAAAAAACgs/bDsGubktGOM/s1600/11.gif", "(:/");
emo(/\s:hah/ig, "http://2.bp.blogspot.com/-04urjy8Tty8/UvuHhfl4KzI/AAAAAAAACj0/X_wV46fHOl8/s1600/6.png", ":hah");
emo(/\s:caped/ig, "http://4.bp.blogspot.com/-LjJRqUzMcfg/UvtxH_1eghI/AAAAAAAAChA/15IG4AX2ia4/s1600/13.gif", ":caped");
emo(/\s:s/ig, "http://2.bp.blogspot.com/-0GaXpHyU-XM/UvtxJQ2Wj0I/AAAAAAAAChQ/7ABkfjcAxdo/s1600/15.gif", ":s");
emo(/\s---/ig, "http://2.bp.blogspot.com/-vqqIgz8Wsb4/UvtxKlKwzMI/AAAAAAAAChg/frWF0KMc6PI/s1600/17.gif", "---");
emo(/\s-_-/ig, "http://1.bp.blogspot.com/-eJfqPHjni7s/UvtxL2aPjoI/AAAAAAAAChs/vD3ZayVoy1A/s1600/19.gif", "-_-");
emo(/\sO.o/ig, "http://4.bp.blogspot.com/-vwZsF-YSEyc/UvtxMdGpyFI/AAAAAAAACh4/-M0Q8NIxEP0/s1600/2.gif", "O.o"); //
emo(/\sT_T/ig, "http://3.bp.blogspot.com/-1f2X2oDRvBY/UvtxN9op_lI/AAAAAAAACiM/p2ChY_fLIC4/s1600/4.gif", "T_T");
emo(/\s:\*/g, "http://3.bp.blogspot.com/-OGTD5iqkigY/UvtxPekauOI/AAAAAAAACic/mmTG2M5c70Q/s1600/6.gif", ":*");
emo(/\s:\)+/g, "http://2.bp.blogspot.com/-8XgFW2MLfvQ/UvtxQ761aMI/AAAAAAAACiw/kqK95iwWPxc/s1600/8.gif", ":)");
emo(/\s\(n\)+/ig, "http://3.bp.blogspot.com/-cdPjg5A_pWE/UvtxFrbyxdI/AAAAAAAACgk/xoubQYIiBAs/s1600/10.gif", "(n)");
emo(/\s\[~\|\~\]/g, "http://3.bp.blogspot.com/-eFZj6fbpe-E/UvtxG6JZc5I/AAAAAAAACg4/cssiGQSx00E/s1600/12.gif", "[~|~]");
emo(/\s:maho/ig, "http://1.bp.blogspot.com/-gwT79SOFX-M/UvtxIqXAgxI/AAAAAAAAChI/drlSqipldn8/s1600/14.gif", ":maho");
emo(/\s:berak/ig, "http://3.bp.blogspot.com/-MAZF3PuC-gc/UvtxKMuTsII/AAAAAAAAChY/2KQ3PcJYQ2o/s1600/16.gif", ":berak");
emo(/\s:v/ig, "http://2.bp.blogspot.com/-rFMMnvknAp0/UvtxLeVLfbI/AAAAAAAACho/4SldvJ_tnbw/s1600/18.gif", ":v");
emo(/\s:hamer/ig, "http://4.bp.blogspot.com/-LNqQRMnQb0c/UvtxNQILQqI/AAAAAAAACiA/wguFrobsKbI/s1600/20.gif", ":hamer");
// Show alert one times!
$('div.emoWrap')
.one("click", function() {
if (emoMessage) {
alert(emoMessage);
}
});
// Click to show the code!
$('.emo')
.css('cursor', 'pointer')
.live("click", function(e) {
$('.emoKey')
.remove();
$(this)
.after('<input class="emoKey" type="text" size="' + this.alt.length + '" value=" ' + this.alt + '" />');
$('.emoKey')
.trigger("select");
e.stopPropagation();
});
$('.emoKey')
.live("click", function() {
$(this)
.focus()
.select();
});
});
//]]>
|
'use strict';
var di = require('di');
var PrismManager = require('./prism-manager');
var PrismUtils = require('./services/prism-utils');
var UrlRewrite = require('./services/url-rewrite');
function HttpEvents(prismManager, urlRewrite, prismUtils) {
this.handleRequest = function(req, res) {
var prism = prismManager.get(req.url);
if (prism) {
// rewrite request if applicable
if (prism.config.rules.length) {
prism.config.rules.forEach(urlRewrite.rewriteRequest(req));
}
// Add headers present in the config object
if (prism.config.headers != null) {
for(var key in prism.config.headers) {
req.headers[key] = prism.config.headers[key];
}
}
prism.config.requestHandler(req, res, prism);
return true;
}
return false;
};
this.handleResponse = function(proxyRes, req, res) {
var prism = prismManager.get(req.originalUrl);
if (prism) {
prism.config.responseHandler(req, proxyRes, prism);
}
};
}
di.annotate(HttpEvents, new di.Inject(PrismManager, UrlRewrite, PrismUtils));
module.exports = HttpEvents;
|
var serverRoutes = require("./serverRoutes");
module.exports = function(app, config){
new serverRoutes.ServerRoutes(app, config);
}; |
'use strict';
var mongoose = require('bluebird').promisifyAll(require('mongoose'));
var GameRoundSchema = new mongoose.Schema({
userId: {type: String, index: true},
bet: Number,
game: {type: String, index: true},
action: {type: String, index: true},
outcome: {},
win: Number,
isOver: Boolean
}, {timestamps: true});
GameRoundSchema.index({updatedAt: -1})
export default mongoose.model('GameRound', GameRoundSchema);
|
var store = require('fh-wfm-mongoose-store');
/**
*
* Connecting to the mongoose store.
*
* @param connectionString
* @returns {*}
*/
function connect(connectionString) {
return store.connect(connectionString, {});
}
/**
* Disconnecting from the mongoose store. Ensures the mongo connections are closed.
*/
function disconnect() {
return store.disconnect();
}
/**
*
* @param dataSetId
* @returns {*}
*/
function getCollectionStore(dataSetId) {
return store.getDAL(dataSetId);
}
module.exports = {
connect: connect,
disconnect: disconnect,
getCollectionStore: getCollectionStore
}; |
function BSP(values, options) {
this.getter = options.getter;
this.root = Node.partition(values, this.getter);
}
BSP.prototype.inRange = function inRange(min, max) {
var ranged = [];
this.root.visitInRange(min, max, function(v) {
ranged.push(v);
});
return ranged;
};
BSP.prototype.intersects = function intersects(value) {
var intersects = [];
this.root.findIntersection(value, function(v) {
intersects.push(v);
});
return intersects;
};
function Node(obj, value, min, max) {
this.obj = obj;
this.value = value;
this.min = min;
this.max = max;
}
Node.partition = function partition(values, getter, start, end) {
if (start === undefined && end === undefined) {
start = 0;
end = values.length - 1;
}
var middle = Math.floor((start + end) / 2);
var node = new Node(values[middle],
getter(values[middle]),
getter(values[start]),
getter(values[end]));
if (start < middle) {
node.left = this.partition(values, getter, start, middle - 1);
}
if (middle < end) {
node.right = this.partition(values, getter, middle + 1, end);
}
return node;
};
Node.prototype.inOrder = function walk(visitor) {
if (this.value) {
this.inOrder.call(this.left, visitor);
visitor(this.obj);
this.inOrder.call(this.right, visitor);
}
};
Node.prototype.visitInRange = function(min, max, visitor) {
this.left && this.visitInRange.call(this.left, min, max, visitor);
if (this.value[1] >= min && this.value[0] <= max) {
visitor(this.obj);
}
this.right && this.visitInRange.call(this.right, min, max, visitor);
};
Node.prototype.findIntersection = function(value, visitor) {
this.left && this.findIntersection.call(this.left, value, visitor);
if (this.value[0] <= value && this.value[1] >= value) {
visitor(this.obj);
}
this.right && this.findIntersection.call(this.right, value, visitor);
};
|
/*! GeoFire-Titanium is a JavaScript library that allows you to store and query
* a set of keys based on their geographic location. GeoFire uses Firebase for
* data storage, allowing query results to be updated in realtime as they change.
*
* This library is ported from the official GeoFire JavaScript library for use
* with the Firebase-Titanium module in the Appcelerator Titanium environment.
*
* GeoFire-Titanium v1.1
* https://github.com/LeftLaneLab/geofire-titanium
* License: MIT
*
* Ported From:
*
* GeoFire 3.0.2
* https://github.com/firebase/geofire/
* License: MIT
*
*/
// Load the [RSVP] library
if (typeof RSVP === 'undefined')
{
var RSVP = require('rsvp');
}
var GeoFire = (function() {
"use strict";
/**
* Creates a GeoCallbackRegistration instance.
*
* @constructor
* @this {GeoCallbackRegistration}
* @param {function} cancelCallback Callback to run when this callback registration is cancelled.
*/
var GeoCallbackRegistration = function(cancelCallback) {
/********************/
/* PUBLIC METHODS */
/********************/
/**
* Cancels this callback registration so that it no longer fires its callback. This
* has no effect on any other callback registrations you may have created.
*/
this.cancel = function() {
if (typeof _cancelCallback !== "undefined") {
_cancelCallback();
_cancelCallback = undefined;
}
};
/*****************/
/* CONSTRUCTOR */
/*****************/
if (typeof cancelCallback !== "function") {
throw new Error("callback must be a function");
}
var _cancelCallback = cancelCallback;
};
/**
* Creates a GeoFire instance.
*
* @constructor
* @this {GeoFire}
* @param {Firebase} firebaseRef A Firebase reference where the GeoFire data will be stored.
*/
var GeoFire = function(firebaseRef) {
/********************/
/* PUBLIC METHODS */
/********************/
/**
* Returns the Firebase instance used to create this GeoFire instance.
*
* @return {Firebase} The Firebase instance used to create this GeoFire instance.
*/
this.ref = function() {
return _firebaseRef;
};
/**
* Adds the provided key - location pair to Firebase. Returns an empty promise which is fulfilled when the write is complete.
*
* If the provided key already exists in this GeoFire, it will be overwritten with the new location value.
*
* @param {string} key The key representing the location to add.
* @param {array} location The [latitude, longitude] pair to add.
* @return {RSVP.Promise} A promise that is fulfilled when the write is complete.
*/
this.set = function(key, location) {
validateKey(key);
if (location !== null) {
// Setting location to null is valid since it will remove the key
validateLocation(location);
}
return new RSVP.Promise(function(resolve, reject) {
function onComplete(error) {
if (error) {
reject("Error: Firebase synchronization failed: " + error);
}
else {
resolve();
}
}
if (location === null) {
_firebaseRef.child(key).remove(onComplete);
} else {
var geohash = encodeGeohash(location);
_firebaseRef.child(key).setWithPriority(encodeGeoFireObject(location, geohash), geohash, onComplete);
}
});
};
/**
* Returns a promise fulfilled with the location corresponding to the provided key.
*
* If the provided key does not exist, the returned promise is fulfilled with null.
*
* @param {string} key The key of the location to retrieve.
* @return {RSVP.Promise} A promise that is fulfilled with the location of the given key.
*/
this.get = function(key) {
validateKey(key);
return new RSVP.Promise(function(resolve, reject) {
_firebaseRef.child(key).once("value", function(dataSnapshot) {
if (dataSnapshot.val() === null) {
resolve(null);
} else {
resolve(decodeGeoFireObject(dataSnapshot.val()));
}
}, function (error) {
reject("Error: Firebase synchronization failed: " + error);
});
});
};
/**
* Removes the provided key from this GeoFire. Returns an empty promise fulfilled when the key has been removed.
*
* If the provided key is not in this GeoFire, the promise will still successfully resolve.
*
* @param {string} key The key of the location to remove.
* @return {RSVP.Promise} A promise that is fulfilled after the inputted key is removed.
*/
this.remove = function(key) {
return this.set(key, null);
};
/**
* Returns a new GeoQuery instance with the provided queryCriteria.
*
* @param {object} queryCriteria The criteria which specifies the GeoQuery's center and radius.
* @return {GeoQuery} A new GeoQuery object.
*/
this.query = function(queryCriteria) {
return new GeoQuery(_firebaseRef, queryCriteria);
};
/*****************/
/* CONSTRUCTOR */
/*****************/
if (Object.prototype.toString.call(firebaseRef) !== "[object Object]") {
throw new Error("firebaseRef must be an instance of Firebase");
}
var _firebaseRef = firebaseRef;
};
/**
* Static method which calculates the distance, in kilometers, between two locations,
* via the Haversine formula. Note that this is approximate due to the fact that the
* Earth's radius varies between 6356.752 km and 6378.137 km.
*
* @param {array} location1 The [latitude, longitude] pair of the first location.
* @param {array} location2 The [latitude, longitude] pair of the second location.
* @return {number} The distance, in kilometers, between the inputted locations.
*/
GeoFire.distance = function(location1, location2) {
validateLocation(location1);
validateLocation(location2);
var radius = 6371; // Earth's radius in kilometers
var latDelta = degreesToRadians(location2[0] - location1[0]);
var lonDelta = degreesToRadians(location2[1] - location1[1]);
var a = (Math.sin(latDelta / 2) * Math.sin(latDelta / 2)) +
(Math.cos(degreesToRadians(location1[0])) * Math.cos(degreesToRadians(location2[0])) *
Math.sin(lonDelta / 2) * Math.sin(lonDelta / 2));
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return radius * c;
};
// Default geohash length
var g_GEOHASH_PRECISION = 10;
// Characters used in location geohashes
var g_BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz";
// The meridional circumference of the earth in meters
var g_EARTH_MERI_CIRCUMFERENCE = 40007860;
// Length of a degree latitude at the equator
var g_METERS_PER_DEGREE_LATITUDE = 110574;
// Number of bits per geohash character
var g_BITS_PER_CHAR = 5;
// Maximum length of a geohash in bits
var g_MAXIMUM_BITS_PRECISION = 22*g_BITS_PER_CHAR;
// Equatorial radius of the earth in meters
var g_EARTH_EQ_RADIUS = 6378137.0;
// The following value assumes a polar radius of
// var g_EARTH_POL_RADIUS = 6356752.3;
// The formulate to calculate g_E2 is
// g_E2 == (g_EARTH_EQ_RADIUS^2-g_EARTH_POL_RADIUS^2)/(g_EARTH_EQ_RADIUS^2)
// The exact value is used here to avoid rounding errors
var g_E2 = 0.00669447819799;
// Cutoff for rounding errors on double calculations
var g_EPSILON = 1e-12;
Math.log2 = Math.log2 || function(x) {
return Math.log(x)/Math.log(2);
};
/**
* Validates the inputted key and throws an error if it is invalid.
*
* @param {string} key The key to be verified.
*/
var validateKey = function(key) {
var error;
if (typeof key !== "string") {
error = "key must be a string";
}
else if (key.length === 0) {
error = "key cannot be the empty string";
}
else if (1 + g_GEOHASH_PRECISION + key.length > 755) {
// Firebase can only stored child paths up to 768 characters
// The child path for this key is at the least: "i/<geohash>key"
error = "key is too long to be stored in Firebase";
}
else if (/[\[\].#$\/\u0000-\u001F\u007F]/.test(key)) {
// Firebase does not allow node keys to contain the following characters
error = "key cannot contain any of the following characters: . # $ ] [ /";
}
if (typeof error !== "undefined") {
throw new Error("Invalid GeoFire key '" + key + "': " + error);
}
};
/**
* Validates the inputted location and throws an error if it is invalid.
*
* @param {array} location The [latitude, longitude] pair to be verified.
*/
var validateLocation = function(location) {
var error;
if (Object.prototype.toString.call(location) !== "[object Array]") {
error = "location must be an array";
}
else if (location.length !== 2) {
error = "expected array of length 2, got length " + location.length;
}
else {
var latitude = location[0];
var longitude = location[1];
if (typeof latitude !== "number" || isNaN(latitude)) {
error = "latitude must be a number";
}
else if (latitude < -90 || latitude > 90) {
error = "latitude must be within the range [-90, 90]";
}
else if (typeof longitude !== "number" || isNaN(longitude)) {
error = "longitude must be a number";
}
else if (longitude < -180 || longitude > 180) {
error = "longitude must be within the range [-180, 180]";
}
}
if (typeof error !== "undefined") {
throw new Error("Invalid GeoFire location '" + location + "': " + error);
}
};
/**
* Validates the inputted geohash and throws an error if it is invalid.
*
* @param {string} geohash The geohash to be validated.
*/
var validateGeohash = function(geohash) {
var error;
if (typeof geohash !== "string") {
error = "geohash must be a string";
}
else if (geohash.length === 0) {
error = "geohash cannot be the empty string";
}
else {
for (var i = 0, length = geohash.length; i < length; ++i) {
if (g_BASE32.indexOf(geohash[i]) === -1) {
error = "geohash cannot contain \"" + geohash[i] + "\"";
}
}
}
if (typeof error !== "undefined") {
throw new Error("Invalid GeoFire geohash '" + geohash + "': " + error);
}
};
/**
* Validates the inputted query criteria and throws an error if it is invalid.
*
* @param {object} newQueryCriteria The criteria which specifies the query's center and/or radius.
*/
var validateCriteria = function(newQueryCriteria, requireCenterAndRadius) {
if (typeof newQueryCriteria !== "object") {
throw new Error("query criteria must be an object");
}
else if (typeof newQueryCriteria.center === "undefined" && typeof newQueryCriteria.radius === "undefined") {
throw new Error("radius and/or center must be specified");
}
else if (requireCenterAndRadius && (typeof newQueryCriteria.center === "undefined" || typeof newQueryCriteria.radius === "undefined")) {
throw new Error("query criteria for a new query must contain both a center and a radius");
}
// Throw an error if there are any extraneous attributes
for (var key in newQueryCriteria) {
if (newQueryCriteria.hasOwnProperty(key)) {
if (key !== "center" && key !== "radius") {
throw new Error("Unexpected attribute '" + key + "'' found in query criteria");
}
}
}
// Validate the "center" attribute
if (typeof newQueryCriteria.center !== "undefined") {
validateLocation(newQueryCriteria.center);
}
// Validate the "radius" attribute
if (typeof newQueryCriteria.radius !== "undefined") {
if (typeof newQueryCriteria.radius !== "number" || isNaN(newQueryCriteria.radius)) {
throw new Error("radius must be a number");
}
else if (newQueryCriteria.radius < 0) {
throw new Error("radius must be greater than or equal to 0");
}
}
};
/**
* Converts degrees to radians.
*
* @param {number} degrees The number of degrees to be converted to radians.
* @return {number} The number of radians equal to the inputted number of degrees.
*/
var degreesToRadians = function(degrees) {
if (typeof degrees !== "number" || isNaN(degrees)) {
throw new Error("Error: degrees must be a number");
}
return (degrees * Math.PI / 180);
};
/**
* Generates a geohash of the specified precision/string length
* from the [latitude, longitude] pair, specified as an array.
*
* @param {array} location The [latitude, longitude] pair to encode into
* a geohash.
* @param {number} precision The length of the geohash to create. If no
* precision is specified, the global default is used.
* @return {string} The geohash of the inputted location.
*/
var encodeGeohash = function(location, precision) {
validateLocation(location);
if (typeof precision !== "undefined") {
if (typeof precision !== "number" || isNaN(precision)) {
throw new Error("precision must be a number");
}
else if (precision <= 0) {
throw new Error("precision must be greater than 0");
}
else if (precision > 22) {
throw new Error("precision cannot be greater than 22");
}
else if (Math.round(precision) !== precision) {
throw new Error("precision must be an integer");
}
}
// Use the global precision default if no precision is specified
precision = precision || g_GEOHASH_PRECISION;
var latitudeRange = {
min: -90,
max: 90
};
var longitudeRange = {
min: -180,
max: 180
};
var hash = "";
var hashVal = 0;
var bits = 0;
var even = 1;
while (hash.length < precision) {
var val = even ? location[1] : location[0];
var range = even ? longitudeRange : latitudeRange;
var mid = (range.min + range.max) / 2;
/* jshint -W016 */
if (val > mid) {
hashVal = (hashVal << 1) + 1;
range.min = mid;
}
else {
hashVal = (hashVal << 1) + 0;
range.max = mid;
}
/* jshint +W016 */
even = !even;
if (bits < 4) {
bits++;
}
else {
bits = 0;
hash += g_BASE32[hashVal];
hashVal = 0;
}
}
return hash;
};
/**
* Calculates the number of degrees a given distance is at a given latitude
* @param {number} distance
* @param {number} latitude
* @return {number} The number of degrees the distance corresponds to
*/
var metersToLongitudeDegrees = function(distance, latitude) {
var radians = degreesToRadians(latitude);
var num = Math.cos(radians)*g_EARTH_EQ_RADIUS*Math.PI/180;
var denom = 1/Math.sqrt(1-g_E2*Math.sin(radians)*Math.sin(radians));
var deltaDeg = num*denom;
if (deltaDeg < g_EPSILON) {
return distance > 0 ? 360 : 0;
}
else {
return Math.min(360, distance/deltaDeg);
}
};
/**
* Calculates the bits necessary to reach a given resolution in meters for
* the longitude at a given latitude
* @param {number} resolution
* @param {number} latitude
* @return {number}
*/
var longitudeBitsForResolution = function(resolution, latitude) {
var degs = metersToLongitudeDegrees(resolution, latitude);
return (Math.abs(degs) > 0.000001) ? Math.max(1, Math.log2(360/degs)) : 1;
};
/**
* Calculates the bits necessary to reach a given resolution in meters for
* the latitude
* @param {number} resolution
*/
var latitudeBitsForResolution = function(resolution) {
return Math.min(Math.log2(g_EARTH_MERI_CIRCUMFERENCE/2/resolution), g_MAXIMUM_BITS_PRECISION);
};
/**
* Wraps the longitude to [-180,180]
* @param {number} longitude
* @return {number} longitude
*/
var wrapLongitude = function(longitude) {
if (longitude <= 180 && longitude >= -180) {
return longitude;
}
var adjusted = longitude + 180;
if (adjusted > 0) {
return (adjusted % 360) - 180;
}
else {
return 180 - (-adjusted % 360);
}
};
/**
* Calculates the maximum number of bits of a geohash to get
* a bounding box that is larger than a given size at the given
* coordinate.
* @param {array} coordinate The coordinate as a [latitude, longitude] pair
* @param {number} size The size of the bounding box
* @return {number} The number of bits necessary for the geohash
*/
var boundingBoxBits = function(coordinate, size) {
var latDeltaDegrees = size/g_METERS_PER_DEGREE_LATITUDE;
var latitudeNorth = Math.min(90, coordinate[0] + latDeltaDegrees);
var latitudeSouth = Math.max(-90, coordinate[0] - latDeltaDegrees);
var bitsLat = Math.floor(latitudeBitsForResolution(size))*2;
var bitsLongNorth = Math.floor(longitudeBitsForResolution(size, latitudeNorth))*2-1;
var bitsLongSouth = Math.floor(longitudeBitsForResolution(size, latitudeSouth))*2-1;
return Math.min(bitsLat, bitsLongNorth, bitsLongSouth, g_MAXIMUM_BITS_PRECISION);
};
/**
* Calculates 8 points on the bounding box and the center of a given circle.
* At least one geohash of these 9 coordinates, truncated to a precision of
* at most radius, are guaranteed to be prefixes of any geohash that lies
* within the circle.
* @param {array} center The center given as [latitude, longitude]
* @param {number} radius The radius of the circle
* @return {number} The four bounding box points
*/
var boundingBoxCoordinates = function(center, radius) {
var latDegrees = radius/g_METERS_PER_DEGREE_LATITUDE;
var latitudeNorth = Math.min(90, center[0] + latDegrees);
var latitudeSouth = Math.max(-90, center[0] - latDegrees);
var longDegsNorth = metersToLongitudeDegrees(radius, latitudeNorth);
var longDegsSouth = metersToLongitudeDegrees(radius, latitudeSouth);
var longDegs = Math.max(longDegsNorth, longDegsSouth);
return [
[center[0], center[1]],
[center[0], wrapLongitude(center[1] - longDegs)],
[center[0], wrapLongitude(center[1] + longDegs)],
[latitudeNorth, center[1]],
[latitudeNorth, wrapLongitude(center[1] - longDegs)],
[latitudeNorth, wrapLongitude(center[1] + longDegs)],
[latitudeSouth, center[1]],
[latitudeSouth, wrapLongitude(center[1] - longDegs)],
[latitudeSouth, wrapLongitude(center[1] + longDegs)]
];
};
/**
* Calculates the bounding box query for a geohash with x bits precision
* @param {string} geohash
* @param {number} bits
* @return {array} A [start,end] pair
*/
var geohashQuery = function(geohash, bits) {
validateGeohash(geohash);
var precision = Math.ceil(bits/g_BITS_PER_CHAR);
if (geohash.length < precision) {
return [geohash, geohash+"~"];
}
geohash = geohash.substring(0, precision);
var base = geohash.substring(0, geohash.length - 1);
var lastValue = g_BASE32.indexOf(geohash.charAt(geohash.length - 1));
var significantBits = bits - (base.length*g_BITS_PER_CHAR);
if (significantBits === 0) {
return [base, base+"~"];
}
var unusedBits = (g_BITS_PER_CHAR - significantBits);
/*jshint bitwise: false*/
// delete unused bits
var startValue = (lastValue >> unusedBits) << unusedBits;
var endValue = startValue + (1 << unusedBits);
/*jshint bitwise: true*/
if (endValue > 31) {
return [base+g_BASE32[startValue], base+"~"];
}
else {
return [base+g_BASE32[startValue], base+g_BASE32[endValue]];
}
};
/**
* Calculates a set of queries to fully contain a given circle
* A query is a [start,end] pair where any geohash is guaranteed to
* be lexiographically larger then start and smaller than end
* @param {array} center The center given as [latitude, longitude] pair
* @param {number} radius The radius of the circle
* @return {array} An array of geohashes containing a [start,end] pair
*/
var geohashQueries = function(center, radius) {
validateLocation(center);
var queryBits = Math.max(1, boundingBoxBits(center, radius));
var geohashPrecision = Math.ceil(queryBits/g_BITS_PER_CHAR);
var coordinates = boundingBoxCoordinates(center, radius);
var queries = coordinates.map(function(coordinate) {
return geohashQuery(encodeGeohash(coordinate, geohashPrecision), queryBits);
});
// remove duplicates
return queries.filter(function(query, index) {
return !queries.some(function(other, otherIndex) {
return index > otherIndex && query[0] === other[0] && query[1] === other[1];
});
});
};
/**
* Encodes a location and geohash as a GeoFire object
*
* @param {array} location The location as [latitude, longitude] pair.
* @param {string} geohash The geohash of the location
* @return {Object} The location encoded as GeoFire object
*/
function encodeGeoFireObject(location, geohash) {
validateLocation(location);
validateGeohash(geohash);
return {
"g": geohash,
"l": location
};
}
/**
* Decodes the location given as GeoFire object. Returns null if decoding fails
*
* @param {Object} geoFireObj The location encoded as GeoFire object
* @return {array} location The location as [latitude, longitude] pair or null if decoding fails
*/
function decodeGeoFireObject(geoFireObj) {
if (geoFireObj !== null && geoFireObj.hasOwnProperty("l") && Array.isArray(geoFireObj.l) && geoFireObj.l.length === 2) {
return geoFireObj.l;
} else {
throw new Error("Unexpected GeoFire location object encountered: " + JSON.stringify(geoFireObj));
}
}
/**
* Creates a GeoQuery instance.
*
* @constructor
* @this {GeoQuery}
* @param {Firebase} firebaseRef A Firebase reference.
* @param {object} queryCriteria The criteria which specifies the query's center and radius.
*/
var GeoQuery = function (firebaseRef, queryCriteria) {
/*********************/
/* PRIVATE METHODS */
/*********************/
/**
* Fires each callback for the provided eventType, passing it provided key's data.
*
* @param {string} eventType The event type whose callbacks to fire. One of "key_entered", "key_exited", or "key_moved".
* @param {string} key The key of the location for which to fire the callbacks.
* @param {array|null} location The location as latitude longitude pair
* @param {double|null} distanceFromCenter The distance from the center or null
*/
function _fireCallbacksForKey(eventType, key, location, distanceFromCenter) {
_callbacks[eventType].forEach(function(callback) {
if (typeof location === "undefined" || location === null) {
callback(key, null, null);
}
else {
callback(key, location, distanceFromCenter);
}
});
}
/**
* Fires each callback for the "ready" event.
*/
function _fireReadyEventCallbacks() {
_callbacks.ready.forEach(function(callback) {
callback();
});
}
/**
* Decodes a query string to a query
* @param {string} str The encoded query
* @return {array} The decoded query as a [start,end] pair
*/
function _stringToQuery(string) {
var decoded = string.split(":");
if (decoded.length !== 2) {
throw new Error("Invalid internal state! Not a valid geohash query: " + string);
}
return decoded;
}
/**
* Encodes a query as a string for easier indexing and equality
* @param {array} query The query to encode
* @param {string} The encoded query as string
*/
function _queryToString(query) {
if (query.length !== 2) {
throw new Error("Not a valid geohash query: " + query);
}
return query[0]+":"+query[1];
}
/**
* Turns off all callbacks for geo query
* @param {array} query The geohash query
* @param {object} queryState An object storing the current state of the query
*/
function _cancelGeohashQuery(query, queryState) {
var queryRef = _firebaseRef.startAt(query[0]).endAt(query[1]);
queryRef.off("child_added", queryState.childAddedCallback);
queryRef.off("child_removed", queryState.childRemovedCallback);
queryRef.off("child_changed", queryState.childChangedCallback);
queryRef.off("value", queryState.valueCallback);
}
/**
* Removes unnecessary Firebase queries which are currently being queried.
*/
function _cleanUpCurrentGeohashesQueried() {
for (var geohashQueryStr in _currentGeohashesQueried) {
if (_currentGeohashesQueried.hasOwnProperty(geohashQueryStr)) {
var queryState = _currentGeohashesQueried[geohashQueryStr];
if (queryState.active === false) {
var query = _stringToQuery(geohashQueryStr);
// Delete the geohash since it should no longer be queried
_cancelGeohashQuery(query, queryState);
delete _currentGeohashesQueried[geohashQueryStr];
}
}
}
// Delete each location which should no longer be queried
for (var key in _locationsTracked) {
if (_locationsTracked.hasOwnProperty(key)) {
if (!_geohashInSomeQuery(_locationsTracked[key].geohash)) {
if (_locationsTracked[key].isInQuery) {
throw new Error("Internal State error, trying to remove location that is still in query");
}
delete _locationsTracked[key];
}
}
}
// Specify that this is done cleaning up the current geohashes queried
_geohashCleanupScheduled = false;
// Cancel any outstanding scheduled cleanup
if (_cleanUpCurrentGeohashesQueriedTimeout !== null) {
clearTimeout(_cleanUpCurrentGeohashesQueriedTimeout);
_cleanUpCurrentGeohashesQueriedTimeout = null;
}
}
/**
* Callback for any updates to locations. Will update the information about a key and fire any necessary
* events every time the key's location changes
*
* When a key is removed from GeoFire or the query, this function will be called with null and performs
* any necessary cleanup.
*
* @param {string} key The key of the geofire location
* @param {array|null} location The location as [latitude, longitude] pair
*/
function _updateLocation(key, location) {
validateLocation(location);
// Get the key and location
var distanceFromCenter, isInQuery;
var wasInQuery = (_locationsTracked.hasOwnProperty(key)) ? _locationsTracked[key].isInQuery : false;
var oldLocation = (_locationsTracked.hasOwnProperty(key)) ? _locationsTracked[key].location : null;
// Determine if the location is within this query
distanceFromCenter = GeoFire.distance(location, _center);
isInQuery = (distanceFromCenter <= _radius);
// Add this location to the locations queried dictionary even if it is not within this query
_locationsTracked[key] = {
location: location,
distanceFromCenter: distanceFromCenter,
isInQuery: isInQuery,
geohash: encodeGeohash(location, g_GEOHASH_PRECISION)
};
// Fire the "key_entered" event if the provided key has entered this query
if (isInQuery && !wasInQuery) {
_fireCallbacksForKey("key_entered", key, location, distanceFromCenter);
} else if (isInQuery && oldLocation !== null && (location[0] !== oldLocation[0] || location[1] !== oldLocation[1])) {
_fireCallbacksForKey("key_moved", key, location, distanceFromCenter);
} else if (!isInQuery && wasInQuery) {
_fireCallbacksForKey("key_exited", key, location, distanceFromCenter);
}
}
/**
* Checks if this geohash is currently part of any of the geohash queries
*
* @param {string} geohash The geohash
* @param {boolean} Returns true if the geohash is part of any of the current geohash queries
*/
function _geohashInSomeQuery(geohash) {
for (var queryStr in _currentGeohashesQueried) {
if (_currentGeohashesQueried.hasOwnProperty(queryStr)) {
var query = _stringToQuery(queryStr);
if (geohash >= query[0] && geohash <= query[1]) {
return true;
}
}
}
return false;
}
/**
* Removes the location from the local state and fires any events if necessary
*
* @param {string} key The key to be removed
* @param {array} currentLocation The current location as [latitude, longitude] pair or null if removed
*/
function _removeLocation(key, currentLocation) {
var locationDict = _locationsTracked[key];
delete _locationsTracked[key];
if (typeof locationDict !== "undefined" && locationDict.isInQuery) {
var distanceFromCenter = (currentLocation) ? GeoFire.distance(currentLocation, _center) : null;
_fireCallbacksForKey("key_exited", key, currentLocation, distanceFromCenter);
}
}
/**
* Callback for child added events.
*
* @param {Firebase DataSnapshot} locationDataSnapshot A snapshot of the data stored for this location.
*/
function _childAddedCallback(locationDataSnapshot) {
_updateLocation(locationDataSnapshot.name(), decodeGeoFireObject(locationDataSnapshot.val()));
}
/**
* Callback for child changed events
*
* @param {Firebase DataSnapshot} locationDataSnapshot A snapshot of the data stored for this location.
*/
function _childChangedCallback(locationDataSnapshot) {
_updateLocation(locationDataSnapshot.name(), decodeGeoFireObject(locationDataSnapshot.val()));
}
/**
* Callback for child removed events
*
* @param {Firebase DataSnapshot} locationDataSnapshot A snapshot of the data stored for this location.
*/
function _childRemovedCallback(locationDataSnapshot) {
var key = locationDataSnapshot.name();
if (_locationsTracked.hasOwnProperty(key)) {
_firebaseRef.child(key).once("value", function(snapshot) {
var location = snapshot.val() === null ? null : decodeGeoFireObject(snapshot.val());
var geohash = (location !== null) ? encodeGeohash(location) : null;
// Only notify observers if key is not part of any other geohash query or this actually might not be
// a key exited event, but a key moved or entered event. These events will be triggered by updates
// to a different query
if (!_geohashInSomeQuery(geohash)) {
_removeLocation(key, location);
}
});
}
}
/**
* Called once all geohash queries have received all child added events and fires the ready
* event if necessary.
*/
function _geohashQueryReadyCallback(queryStr) {
var index = _outstandingGeohashReadyEvents.indexOf(queryStr);
if (index > -1) {
_outstandingGeohashReadyEvents.splice(index, 1);
}
_valueEventFired = (_outstandingGeohashReadyEvents.length === 0);
// If all queries have been processed, fire the ready event
if (_valueEventFired) {
_fireReadyEventCallbacks();
}
}
/**
* Attaches listeners to Firebase which track when new geohashes are added within this query's
* bounding box.
*/
function _listenForNewGeohashes() {
// Get the list of geohashes to query
var geohashesToQuery = geohashQueries(_center, _radius*1000).map(_queryToString);
// Filter out duplicate geohashes
geohashesToQuery = geohashesToQuery.filter(function(geohash, i){
return geohashesToQuery.indexOf(geohash) === i;
});
// For all of the geohashes that we are already currently querying, check if they are still
// supposed to be queried. If so, don't re-query them. Otherwise, mark them to be un-queried
// next time we clean up the current geohashes queried dictionary.
for (var geohashQueryStr in _currentGeohashesQueried) {
if (_currentGeohashesQueried.hasOwnProperty(geohashQueryStr)) {
var index = geohashesToQuery.indexOf(geohashQueryStr);
if (index === -1) {
_currentGeohashesQueried[geohashQueryStr].active = false;
}
else {
_currentGeohashesQueried[geohashQueryStr].active = true;
geohashesToQuery.splice(index, 1);
}
}
}
// If we are not already cleaning up the current geohashes queried and we have more than 25 of them,
// kick off a timeout to clean them up so we don't create an infinite number of unneeded queries.
if (_geohashCleanupScheduled === false && Object.keys(_currentGeohashesQueried).length > 25) {
_geohashCleanupScheduled = true;
_cleanUpCurrentGeohashesQueriedTimeout = setTimeout(_cleanUpCurrentGeohashesQueried, 10);
}
// Keep track of which geohashes have been processed so we know when to fire the "ready" event
_outstandingGeohashReadyEvents = geohashesToQuery.slice();
// Loop through each geohash to query for and listen for new geohashes which have the same prefix.
// For every match, attach a value callback which will fire the appropriate events.
// Once every geohash to query is processed, fire the "ready" event.
geohashesToQuery.forEach(function(toQueryStr) {
// decode the geohash query string
var query = _stringToQuery(toQueryStr);
// Create the Firebase query
var firebaseQuery = _firebaseRef.startAt(query[0]).endAt(query[1]);
// For every new matching geohash, determine if we should fire the "key_entered" event
var childAddedCallback = firebaseQuery.on("child_added", _childAddedCallback);
var childRemovedCallback = firebaseQuery.on("child_removed", _childRemovedCallback);
var childChangedCallback = firebaseQuery.on("child_changed", _childChangedCallback);
// Once the current geohash to query is processed, see if it is the last one to be processed
// and, if so, mark the value event as fired.
// Note that Firebase fires the "value" event after every "child_added" event fires.
var valueCallback = firebaseQuery.on("value", function() {
firebaseQuery.off("value", valueCallback);
_geohashQueryReadyCallback(toQueryStr);
});
// Add the geohash query to the current geohashes queried dictionary and save its state
_currentGeohashesQueried[toQueryStr] = {
active: true,
childAddedCallback: childAddedCallback,
childRemovedCallback: childRemovedCallback,
childChangedCallback: childChangedCallback,
valueCallback: valueCallback
};
});
// Based upon the algorithm to calculate geohashes, it's possible that no "new"
// geohashes were queried even if the client updates the radius of the query.
// This results in no "READY" event being fired after the .updateQuery() call.
// Check to see if this is the case, and trigger the "READY" event.
if(geohashesToQuery.length === 0) {
_geohashQueryReadyCallback();
}
}
/********************/
/* PUBLIC METHODS */
/********************/
/**
* Returns the location signifying the center of this query.
*
* @return {array} The [latitude, longitude] pair signifying the center of this query.
*/
this.center = function() {
return _center;
};
/**
* Returns the radius of this query, in kilometers.
*
* @return {integer} The radius of this query, in kilometers.
*/
this.radius = function() {
return _radius;
};
/**
* Updates the criteria for this query.
*
* @param {object} newQueryCriteria The criteria which specifies the query's center and radius.
*/
this.updateCriteria = function(newQueryCriteria) {
// Validate and save the new query criteria
validateCriteria(newQueryCriteria);
_center = newQueryCriteria.center || _center;
_radius = newQueryCriteria.radius || _radius;
// Loop through all of the locations in the query, update their distance from the center of the
// query, and fire any appropriate events
for (var key in _locationsTracked) {
if (_locationsTracked.hasOwnProperty(key)) {
// Get the cached information for this location
var locationDict = _locationsTracked[key];
// Save if the location was already in the query
var wasAlreadyInQuery = locationDict.isInQuery;
// Update the location's distance to the new query center
locationDict.distanceFromCenter = GeoFire.distance(locationDict.location, _center);
// Determine if the location is now in this query
locationDict.isInQuery = (locationDict.distanceFromCenter <= _radius);
// If the location just left the query, fire the "key_exited" callbacks
if (wasAlreadyInQuery && !locationDict.isInQuery) {
_fireCallbacksForKey("key_exited", key, locationDict.location, locationDict.distanceFromCenter);
}
// If the location just entered the query, fire the "key_entered" callbacks
else if (!wasAlreadyInQuery && locationDict.isInQuery) {
_fireCallbacksForKey("key_entered", key, locationDict.location, locationDict.distanceFromCenter);
}
}
}
// Reset the variables which control when the "ready" event fires
_valueEventFired = false;
// Listen for new geohashes being added to GeoFire and fire the appropriate events
_listenForNewGeohashes();
};
/**
* Attaches a callback to this query which will be run when the provided eventType fires. Valid eventType
* values are "ready", "key_entered", "key_exited", and "key_moved". The ready event callback is passed no
* parameters. All other callbacks will be passed three parameters: (1) the location's key, (2) the location's
* [latitude, longitude] pair, and (3) the distance, in kilometers, from the location to this query's center
*
* "ready" is used to signify that this query has loaded its initial state and is up-to-date with its corresponding
* GeoFire instance. "ready" fires when this query has loaded all of the initial data from GeoFire and fired all
* other events for that data. It also fires every time updateQuery() is called, after all other events have
* fired for the updated query.
*
* "key_entered" fires when a key enters this query. This can happen when a key moves from a location outside of
* this query to one inside of it or when a key is written to GeoFire for the first time and it falls within
* this query.
*
* "key_exited" fires when a key moves from a location inside of this query to one outside of it. If the key was
* entirely removed from GeoFire, both the location and distance passed to the callback will be null.
*
* "key_moved" fires when a key which is already in this query moves to another location inside of it.
*
* Returns a GeoCallbackRegistration which can be used to cancel the callback. You can add as many callbacks
* as you would like for the same eventType by repeatedly calling on(). Each one will get called when its
* corresponding eventType fires. Each callback must be cancelled individually.
*
* @param {string} eventType The event type for which to attach the callback. One of "ready", "key_entered",
* "key_exited", or "key_moved".
* @param {function} callback Callback function to be called when an event of type eventType fires.
* @return {GeoCallbackRegistration} A callback registration which can be used to cancel the provided callback.
*/
this.on = function(eventType, callback) {
// Validate the inputs
if (["ready", "key_entered", "key_exited", "key_moved"].indexOf(eventType) === -1) {
throw new Error("event type must be \"ready\", \"key_entered\", \"key_exited\", or \"key_moved\"");
}
if (typeof callback !== "function") {
throw new Error("callback must be a function");
}
// Add the callback to this query's callbacks list
_callbacks[eventType].push(callback);
// If this is a "key_entered" callback, fire it for every location already within this query
if (eventType === "key_entered") {
for (var key in _locationsTracked) {
if (_locationsTracked.hasOwnProperty(key)) {
var locationDict = _locationsTracked[key];
if (locationDict.isInQuery) {
callback(key, locationDict.location, locationDict.distanceFromCenter);
}
}
}
}
// If this is a "ready" callback, fire it if this query is already ready
if (eventType === "ready") {
if (_valueEventFired) {
callback();
}
}
// Return an event registration which can be used to cancel the callback
return new GeoCallbackRegistration(function() {
_callbacks[eventType].splice(_callbacks[eventType].indexOf(callback), 1);
});
};
/**
* Terminates this query so that it no longer sends location updates. All callbacks attached to this
* query via on() will be cancelled. This query can no longer be used in the future.
*/
this.cancel = function () {
// Cancel all callbacks in this query's callback list
_callbacks = {
ready: [],
key_entered: [],
key_exited: [],
key_moved: []
};
// Turn off all Firebase listeners for the current geohashes being queried
for (var geohashQueryStr in _currentGeohashesQueried) {
if (_currentGeohashesQueried.hasOwnProperty(geohashQueryStr)) {
var query = _stringToQuery(geohashQueryStr);
_cancelGeohashQuery(query, _currentGeohashesQueried[geohashQueryStr]);
delete _currentGeohashesQueried[geohashQueryStr];
}
}
// Delete any stored locations
_locationsTracked = {};
// Turn off the current geohashes queried clean up interval
clearInterval(_cleanUpCurrentGeohashesQueriedInterval);
};
/*****************/
/* CONSTRUCTOR */
/*****************/
// Firebase reference of the GeoFire which created this query
if (Object.prototype.toString.call(firebaseRef) !== "[object Object]") {
throw new Error("firebaseRef must be an instance of Firebase");
}
var _firebaseRef = firebaseRef;
// Event callbacks
var _callbacks = {
ready: [],
key_entered: [],
key_exited: [],
key_moved: []
};
// Variables used to keep track of when to fire the "ready" event
var _valueEventFired = false;
var _outstandingGeohashReadyEvents;
// A dictionary of locations that a currently active in the queries
// Note that not all of these are currently within this query
var _locationsTracked = {};
// A dictionary of geohash queries which currently have an active callbacks
var _currentGeohashesQueried = {};
// Every ten seconds, clean up the geohashes we are currently querying for. We keep these around
// for a little while since it's likely that they will need to be re-queried shortly after they
// move outside of the query's bounding box.
var _geohashCleanupScheduled = false;
var _cleanUpCurrentGeohashesQueriedTimeout = null;
var _cleanUpCurrentGeohashesQueriedInterval = setInterval(function() {
if (_geohashCleanupScheduled === false) {
_cleanUpCurrentGeohashesQueried();
}
}, 10000);
// Validate and save the query criteria
validateCriteria(queryCriteria, /* requireCenterAndRadius */ true);
var _center = queryCriteria.center;
var _radius = queryCriteria.radius;
// Listen for new geohashes being added around this query and fire the appropriate events
_listenForNewGeohashes();
};
return GeoFire;
})();
module.exports = GeoFire; |
'use strict'
var uuid = require('uuid');
var md5 = require('md5');
var jwt = require('jsonwebtoken');
var LoginModel = require('../models/login');
exports.login = function (req, res, next) {
var secret = req._config && req._config.token ? req._config.token.secret : undefined;
if (!secret) return req._error.NO_TOKEN_SECRET();
if (!req.body.login || !req.body.password) return req._error.USER_NOT_FOUND();
req.body.password = md5(req.body.password);
LoginModel.search(req, req.body, function (err, doc) {
// if(err) return req._error.show(err);
if (!doc) return req._error.USER_NOT_FOUND();
var refreshToken = uuid.v4();
var data = {
_id: doc._id,
_refreshToken: refreshToken,
login: doc.login,
group: doc.group,
name: doc.name,
};
var token = jwt.sign(data, secret, { expiresIn: req._config.token.expire || 60 });
LoginModel.update(req, { _id: doc._id }, { _refreshToken: refreshToken });
res.json({
token: token,
login: doc.login,
group: doc.group,
name: doc.name,
_links: {
self: { href: '/token' },
},
});
});
};
exports.update = function (req, res, next) {
var secret = req._config && req._config.token ? req._config.token.secret : undefined;
if (!secret) return req._error.NO_TOKEN_SECRET();
var token = req.headers['x-access-token'] || req.body.token || req.query.token;
if (!token) return req._error.NO_TOKEN();
var decoded = jwt.decode(token, secret);
LoginModel.search(req, { refreshToken: decoded._refreshToken }, function (err, doc) {
// if(err) return req._error.show(err);
if (!doc) return req._error.USER_NOT_FOUND();
var refreshToken = uuid.v4();
var data = {
_id: doc._id,
_refreshToken: refreshToken,
login: doc.login,
group: doc.group,
name: doc.name,
};
var token = jwt.sign(data, secret, { expiresIn: req._config.token.expire || 60 });
LoginModel.update(req, { _id: doc._id }, { _refreshToken: refreshToken });
res.json({
token: token,
login: doc.login,
group: doc.group,
name: doc.name,
_links: {
self: { href: '/token' },
},
});
});
};
exports.info = function (req, res, next) {
var token = req.headers['x-access-token'] || req.body.token || req.query.token;
if (!token) return req._error.NO_TOKEN();
var decoded = jwt.decode(token, req._config.token.secret);
res.json(decoded);
};
|
'use strict';
/**
* `default.js`
*
* The default function to be used if no function is specified in the interface
* an no priority is specified.
*/
module.exports = function NOOP() {
var glui = this;
this.log[this.conf.interface.missingFunctionLogLevel]
('Function not defined in interface!');
};
|
import { helper } from '@ember/component/helper';
import { isEqual as emberIsEqual } from '@ember/utils';
export function isEqual([a, b]) {
return emberIsEqual(a, b);
}
export default helper(isEqual);
|
import unfold from '../../src/utils/unfold.js';
import { expect } from 'chai';
describe('unfold', () => {
it('should get some tests written', () => {
expect(unfold).to.be.a('function');
});
});
|
/**
* Sequelize model for French Departments.
* @param sequelize The Sequelize instance.
* @param DataTypes The data types.
* @returns {Object} The Sequelize model.
*/
module.exports = function (sequelize, DataTypes) {
var Department = sequelize.define('Department', {
code: DataTypes.STRING,
name: DataTypes.STRING,
region: DataTypes.STRING
}, {
tableName: 'departments',
classMethods: {
associate: function (models) {
Department.hasMany(models.Address)
}
}
});
return Department
}; |
/*global define*/
define(function (require) {
'use strict';
/**
* Edition field for a date - a text input with a datepicker.
*
* @example <ma-date-field field="field" value="value"></ma-date-field>
*/
function maDateField() {
return {
scope: {
'field': '&',
'value': '='
},
restrict: 'E',
link: function(scope, element) {
var field = scope.field();
scope.name = field.name();
scope.rawValue = scope.value;
scope.$watch('rawValue', function(rawValue) {
scope.value = field.parse()(rawValue);
});
scope.format = field.format();
scope.v = field.validation();
scope.isOpen = false;
var input = element.find('input').eq(0);
var attributes = field.attributes();
for (var name in attributes) {
input.attr(name, attributes[name]);
}
scope.toggleDatePicker = function ($event) {
$event.preventDefault();
$event.stopPropagation();
scope.isOpen = !scope.isOpen;
};
},
template:
'<div class="input-group datepicker">' +
'<input type="text" ng-model="rawValue" id="{{ name }}" name="{{ name }}" class="form-control" ' +
'datepicker-popup="{{ format }}" is-open="isOpen" close-text="Close" ' +
'ng-required="v.required" />' +
'<span class="input-group-btn">' +
'<button type="button" class="btn btn-default" ng-click="toggleDatePicker($event)"><i class="glyphicon glyphicon-calendar"></i></button>' +
'</span>' +
'</div>'
};
}
maDateField.$inject = [];
return maDateField;
});
|
/*
* sf-collection - v0.1.6
* jQuery plugin to handle symfony2 collection in a proper way
*
*
* Copyright (C) 2015 Giorgio Premi
* Licensed under MIT License
* See LICENSE file for the full copyright notice.
*/
;(function ( $, window, document, undefined ) {
"use strict";
var pluginName = "sfcollection";
var defaults = {
collectionName: null,
prototype: null,
prototypeName: "__name__",
allowAdd: true,
allowRemove: true,
// hooks
initAddButton: defaultInitAddButton,
initRemoveButton: defaultInitRemoveButton,
entrySelector: '> div',
entryNameGenerator: defaultEntryNameGenerator,
// Events
create: null,
add: null,
remove: null,
};
function SfCollection(element, options) {
this.element = $(element);
this.options = $.extend({}, defaults, this.element.data(), options);
this._defaults = defaults;
this._name = pluginName;
this.widgetEventPrefix = pluginName;
this.entries = $();
this.entryNames = [];
this.onRemoveAll = false;
this.lastEntry = null;
this.init();
}
$.extend(SfCollection.prototype, {
init: function () {
var self = this;
var options = this.options;
options.collectionName = options.collectionName || '';
if (!this.options.collectionName.length) {
console.error("jquery.sf-collection.js: collectionName is required to correctly ");
return;
}
this.element.addClass('sf-collection');
this.element.find(this.options.entrySelector).each(function(i, entry) {
entry = $(entry);
var entryName = findEntryName(entry, options.collectionName);
if (!entryName) {
return;
}
self._initEntryNode.call(self, entry, entryName);
self.lastEntry = entry;
});
if (options.allowAdd) {
var $add = options.initAddButton(this.element);
if ($add !== false) {
if (!isNonEmptyObject($add)) {
console.error("jquery.sf-collection.js: initAddButton must return a non-empty jQuery object or false");
return false;
}
$add.addClass('sf-collection-action sf-collection-add');
}
}
if (options.allowRemove) {
var $remove = options.initRemoveButton(this.element);
if (false !== $remove) {
if (!isNonEmptyObject($remove)) {
console.error("jquery.sf-collection.js: initRemoveButton must return a non-empty jQuery object or false");
return false;
}
$remove.addClass('sf-collection-action sf-collection-remove');
}
}
this.element.on('click', '.sf-collection-action', function(event) { self._dispatchClickEvent.call(self, event); });
this._trigger("create", null, {
collection: this.element,
entries: this.entries,
entryNames: this.entryNames,
});
},
_initEntryNode: function (entry, entryName) {
var options = this.options;
if (this.entryNames.indexOf(entryName) >= 0) {
console.warn("jquery.sf-collection.js: duplicated entry name");
}
this.entries = this.entries.add(entry);
this.entryNames.push(entryName);
entry.addClass('sf-collection-entry').data('entry-name', entryName);
if (options.allowAdd) {
var $add = options.initAddButton(this.element, entry);
if (false !== $add) {
if (!isNonEmptyObject($add)) {
console.error("jquery.sf-collection.js: initAddButton must return a non-empty jQuery object or false");
return false;
}
$add.addClass('sf-collection-action sf-collection-add');
}
}
if (options.allowRemove) {
var $remove = options.initRemoveButton(this.element, entry);
if (false !== $remove) {
if (!isNonEmptyObject($remove)) {
console.error("jquery.sf-collection.js: initRemoveButton must return a non-empty jQuery object or false");
return false;
}
$remove.addClass('sf-collection-action sf-collection-remove');
}
}
},
_dispatchClickEvent: function (event) {
var action = $(event.currentTarget);
var entry = $(event.target).closest('.sf-collection, .sf-collection-entry');
if (entry.is('.sf-collection')) {
entry = null;
}
if (action.is('.sf-collection-add')) {
this._addEntryNode(entry, event);
} else if (action.is('.sf-collection-remove')) {
if (null !== entry) {
this._removeEntryNode(entry, event);
} else {
this._removeAll(event);
}
} else {
return;
}
event.stopPropagation();
event.preventDefault();
},
_addEntryNode: function (afterEntry, originalEvent) {
var entryName = this.options.entryNameGenerator(this.element, this.entryNames);
afterEntry = afterEntry || this.lastEntry;
var regExp = new RegExp(escapeRegExp(this.options.prototypeName), 'g');
var prototype = this.options.prototype.replace(regExp, entryName);
var entry = $($.trim(prototype));
this._initEntryNode(entry, entryName);
if (afterEntry) {
entry.insertAfter(afterEntry);
} else {
entry.prependTo(this.element);
}
var newLast = this.lastEntry ?
this.lastEntry.nextAll('.sf-collection-entry').last()
: this.element.children('.sf-collection-entry').last();
if (newLast.length) {
this.lastEntry = newLast;
}
this._trigger("add", originalEvent, {
collection: this.element,
entries: this.entries,
entry: entry,
entryName: entryName,
});
},
_removeAll: function (originalEvent) {
var self = this;
this.onRemoveAll = true;
while (this.entries.length) {
self._removeEntryNode.call(self, this.entries.eq(0), originalEvent);
}
this.onRemoveAll = false;
},
_removeEntryNode: function (entry, originalEvent) {
var entryName = entry.data('entry-name');
if (this.lastEntry.is(entry)) {
this.lastEntry = this.lastEntry.prev('.sf-collection-entry');
if (!this.lastEntry.length) {
this.lastEntry = null;
}
}
var index = this.entryNames.indexOf(entryName);
if (index !== -1) {
this.entryNames.splice(index, 1);
}
this.entries = this.entries.not(entry);
entry.remove();
this._trigger("remove", originalEvent, {
collection: this.element,
entries: this.entries,
entryNames: this.entryNames,
entry: entry,
entryName: entryName,
removeAll: this.onRemoveAll
});
},
// copy-pasted from jQueryUI widget
_trigger: function( type, event, data ) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
});
/*
* Plugin wrapper
*/
$.fn[pluginName] = function (options) {
return this.each(function() {
var plugin = $.data(this, "plugin-" + pluginName);
if (!plugin) {
plugin = $.data(this, "plugin-" + pluginName, new SfCollection(this, options));
}
});
};
/*
* private functions
*/
function escapeRegExp(string) {
return string.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
}
function isNonEmptyObject($object) {
return typeof $object === "object" && null !== $object && $object.length > 0;
}
function findEntryName(entry, collectionName) {
var anInput = entry.find(':input[name^="' + collectionName + '["]').eq(0);
var fullName = '' + anInput.attr('name');
var regExp = new RegExp('^' + escapeRegExp(collectionName) + '\\[([a-z0-9]+)\\].*$');
var matches = fullName.match(regExp);
if (!matches) {
return null;
}
return matches[1];
}
function defaultInitRemoveButton(collection, entry) {
if (!entry) {
return false;
}
var prototype = collection.data('prototype-remove') || '<a href="#remove">[-]</a>';
var $remove = $($.trim(prototype));
if ($remove.length > 1) {
console.warn("jquery.sf-collection.js: button should be a single DOM node. Wrapping everything in a div...");
$remove = $('<div>').append($remove);
}
return $remove.appendTo(entry);
}
function defaultInitAddButton(collection, entry) {
if (entry) {
return false;
}
var prototype = collection.data('prototype-add') || '<a href="#add">[+]</a>';
var $add = $($.trim(prototype));
if ($add.length > 1) {
console.warn("jquery.sf-collection.js: button should be a single DOM node. Wrapping everything in a div...");
$add = $('<div>').append($add);
}
return $add.appendTo(entry ? entry : collection);
}
function defaultEntryNameGenerator(collection, entryNames) {
var max = collection.data('sf-collection-max-entry') || Math.max.apply(null, entryNames.concat(0));
if (isNaN(max) || !isFinite(max)) {
console.error("jquery.sf-collection.js: cannot calculate a maximum. Define a custom entry name generator.");
return null;
}
collection.data('sf-collection-max-entry', ++ max);
return max;
}
})( jQuery, window, document );
|
var MockMan_MockRegistry = require('./mockregistry'),
_ = require('underscore');
module.exports = function(type) {
// Current method defining the calls on
var current_method,
// Current call count expectation
current_call_count = 0,
// Current return value
current_return = null,
// Name of the mocked method
mock_name = '',
// Callback information
callback_info = {
enabled: false,
argument_number: 0,
func_params: null
};
// Expectations object
var expectations = {};
if(!type || !_.contains(['literal', 'constructor'], type)) {
type = 'literal';
}
var saveExpectation = function() {
var expects = {
returns: current_return,
expected: {
'calls': current_call_count
},
actual: {
'calls': 0
},
callback: {
enabled: callback_info.enabled,
arg: callback_info.argument_number,
func_params: callback_info.func_params
}
};
expectations[current_method] = expects;
};
var refreshExpectation = function() {
current_method = undefined;
current_call_count = 0;
current_return = 0;
};
var addDynamicMethod = function(method, return_value) {
returnObject[method] = function() {
expectations[method].actual.calls += 1;
return return_value;
}
};
var incrementCallCount = function(method) {
if(expectations[method]) {
expectations[method].actual.calls += 1;
}
}
var returnObject = {
mname: '',
setName: function(name) {
this.mname = name;
},
shouldReceive: function(name) {
refreshExpectation();
current_method = name;
saveExpectation();
return this.times('any');
},
once: function() {
return this.times(1);
},
twice: function() {
return this.times(2);
},
any: function() {
return this.times(-1);
},
never: function() {
return this.times(0);
},
times: function(number) {
current_call_count = number;
saveExpectation();
return this;
},
willReturn: function(value) {
current_return = value;
saveExpectation();
return this;
},
willExecuteCallback: function(arg_number, values) {
callback_info.enabled = true;
callback_info.argument_number = arg_number;
callback_info.func_params = values;
saveExpectation();
return this;
},
getExpectations: function() {
return expectations;
},
getMock: function() {
// Start to build the mock object
var obj = {
__calls: {},
__getMethods: function() {
return _.keys(this.__calls);
},
__getActualCallCount: function(name) {
if(!this.__calls[name]) return 0;
return this.__calls[name].actual || 0;
},
__getExpectedCallCount: function(name) {
if(!this.__calls[name]) return 0;
return this.__calls[name].expected || 0;
},
__createMethod: function(name, expected_calls, returns, callback) {
this.__calls[name] = {};
this.__calls[name].expected = expected_calls;
this.__calls[name].actual = 0;
this.__calls[name].callback = callback;
this[name] = function() {
this.__calls[name].actual++;
if(this.__calls[name].callback.enabled) {
if(typeof arguments[this.__calls[name].callback.arg] == "function") {
arguments[this.__calls[name].callback.arg].apply(undefined, this.__calls[name].callback.func_params);
} else {
throw new Error('Callback is not a function');
}
}
return returns;
}
}
};
for(var method in expectations) {
var method_exp = expectations[method];
obj.__createMethod(method, method_exp.expected.calls, method_exp.returns, method_exp.callback);
}
MockMan_MockRegistry.addMock(this.mname, obj);
return function() { return obj; };
}
};
return returnObject;
}; |
const ALERT = 2,
COMPLEXITY = 10,
IGNORE = 0,
MAX_NESTED_BLOCKS = 4,
MAX_NESTED_CALLBACKS = 10,
MAX_PARAMS = 3,
MAX_PATH_LENGTH = 3,
MAX_STATEMENT_LENGTH = 80,
MAX_STATEMENTS = 10,
MIN_DEPTH = 3,
TAB_SPACE = 2,
WARN = 1;
module.exports = {
parser: 'babel-eslint',
env: {
es6: true,
browser: true,
node: true,
mongo: true,
meteor: true,
jquery: true,
jasmine: true
},
plugins: [
'html',
'json',
'react',
'meteor',
'mongodb',
'lodash3',
'jasmine'
],
ecmaFeatures: {
arrowFunctions: true,
binaryLiterals: true,
blockBindings: true,
classes: true,
defaultParams: true,
destructuring: true,
forOf: true,
generators: true,
modules: true,
objectLiteralComputedProperties: true,
objectLiteralDuplicateProperties: false,
objectLiteralShorthandMethods: true,
objectLiteralShorthandProperties: true,
octalLiterals: true,
regexUFlag: true,
regexYFlag: true,
restParams: true,
spread: true,
superInFunctions: true,
templateStrings: true,
unicodeCodePointEscapes: true,
globalReturn: false,
jsx: true,
experimentalObjectRestSpread: true
},
rules: {
/* Possible Errors */
// disallow trailing commas in object literals
'comma-dangle': [ALERT, 'never'],
// disallow assignment in conditional expressions
'no-cond-assign': [ALERT, 'always'],
// disallow use of console
'no-console': WARN,
// disallow use of constant expressions in conditions
'no-constant-condition': ALERT,
// disallow control characters in regular expressions
'no-control-regex': ALERT,
// disallow use of debugger
'no-debugger': WARN,
// disallow duplicate arguments in functions
'no-dupe-args': ALERT,
// disallow duplicate keys when creating object literals
'no-dupe-keys': ALERT,
// disallow a duplicate case label.
'no-duplicate-case': ALERT,
// disallow the use of empty character classes in regular expressions
'no-empty-character-class': ALERT,
// disallow empty statements
'no-empty': ALERT,
// disallow assigning to the exception in a catch block
'no-ex-assign': ALERT,
// disallow double-negation boolean casts in a boolean context
'no-extra-boolean-cast': ALERT,
// disallow unnecessary parentheses
'no-extra-parens': ALERT,
// disallow unnecessary semicolons
'no-extra-semi': ALERT,
// disallow overwriting functions written as function declarations
'no-func-assign': IGNORE,
// disallow function or variable declarations in nested blocks
'no-inner-declarations': ALERT,
// disallow invalid regular expression strings in the RegExp constructor
'no-invalid-regexp': ALERT,
// disallow irregular whitespace outside of strings and comments
'no-irregular-whitespace': ALERT,
// disallow negation of the left operand of an in expression
'no-negated-in-lhs': ALERT,
// disallow the use of object properties of the global object (Math and JSON) as functions
'no-obj-calls': ALERT,
// disallow multiple spaces in a regular expression literal
'no-regex-spaces': ALERT,
// disallow sparse arrays
'no-sparse-arrays': ALERT,
// Avoid code that looks like two expressions but is actually one
'no-unexpected-multiline': ALERT,
// disallow unreachable statements after a return, throw, continue, or break statement
'no-unreachable': ALERT,
// disallow comparisons with the value NaN
'use-isnan': ALERT,
// ensure JSDoc comments are valid
'valid-jsdoc': ALERT,
// ensure that the results of typeof are compared against a valid string
'valid-typeof': ALERT,
/* Strict Mode */
// babel/meteor inserts `use strict;` for us
strict: [ALERT, 'never'],
/* Best Practices */
// Enforces getter/setter pairs in objects
'accessor-pairs': ALERT,
// treat var statements as if they were block scoped
'block-scoped-var': ALERT,
// specify the maximum cyclomatic complexity allowed in a program
complexity: [WARN, COMPLEXITY],
// require return statements to either always or never specify values
'consistent-return': ALERT,
// specify curly brace conventions for all control statements
curly: ALERT,
// require default case in switch statements
'default-case': ALERT,
// encourages use of dot notation whenever possible
'dot-location': [ALERT, 'property'],
// enforces consistent newlines before or after dots
'dot-notation': [ALERT, { allowKeywords: true }],
// require the use of === and !==
eqeqeq: ALERT,
// make sure for-in loops have an if statement
'guard-for-in': ALERT,
// disallow the use of alert, confirm, and prompt
'no-alert': WARN,
// disallow use of arguments.caller or arguments.callee
'no-caller': ALERT,
// disallow lexical declarations in case clauses
'no-case-declarations': ALERT,
// disallow division operators explicitly at beginning of regular expression
'no-div-regex': ALERT,
// disallow else after a return in an if
'no-else-return': ALERT,
// disallow use of labels for anything other then loops and switches
'no-empty-label': ALERT,
// disallow use of empty destructuring patterns
'no-empty-pattern': ALERT,
// disallow comparisons to null without a type-checking operator
'no-eq-null': ALERT,
// disallow use of eval()
'no-eval': ALERT,
// disallow adding to native types
'no-extend-native': ALERT,
// disallow unnecessary function binding
'no-extra-bind': ALERT,
// disallow fallthrough of case statements
'no-fallthrough': ALERT,
// disallow the use of leading or trailing decimal points in numeric literals
'no-floating-decimal': ALERT,
// disallow the type conversions with shorter notations
'no-implicit-coercion': ALERT,
// disallow use of eval()-like methods
'no-implied-eval': ALERT,
// disallow this keywords outside of classes or class-like objects
'no-invalid-this': ALERT,
// disallow usage of __iterator__ property
'no-iterator': ALERT,
// disallow use of labeled statements
'no-labels': ALERT,
// disallow unnecessary nested blocks
'no-lone-blocks': ALERT,
// disallow creation of functions within loops
'no-loop-func': ALERT,
// disallow the use of magic numbers
'no-magic-numbers': ALERT,
// disallow use of multiple spaces
'no-multi-spaces': ALERT,
// disallow use of multiline strings
'no-multi-str': ALERT,
// disallow reassignments of native objects
'no-native-reassign': ALERT,
// disallow use of new operator for Function object
'no-new-func': ALERT,
// disallows creating new instances of String,Number, and Boolean
'no-new-wrappers': ALERT,
// disallow use of the new operator when not part of an assignment or comparison
'no-new': ALERT,
// disallow use of octal escape sequences in string literals, such as var foo = "Copyright \251";
'no-octal-escape': ALERT,
// disallow use of octal literals
'no-octal': ALERT,
// disallow reassignment of function parameters
'no-param-reassign': [ALERT, { props: false }],
// disallow use of process.env
'no-process-env': WARN,
// disallow usage of __proto__ property
'no-proto': ALERT,
// disallow declaring the same variable more than once
'no-redeclare': [ALERT, { builtinGlobals: true }],
// disallow use of assignment in return statement
'no-return-assign': ALERT,
// disallow use of javascript: urls.
'no-script-url': ALERT,
// disallow comparisons where both sides are exactly the same
'no-self-compare': ALERT,
// disallow use of the comma operator
'no-sequences': ALERT,
// restrict what can be thrown as an exception
'no-throw-literal': ALERT,
// disallow usage of expressions in statement position
'no-unused-expressions': ALERT,
// disallow unnecessary .call() and .apply()
'no-useless-call': ALERT,
// disallow unnecessary concatenation of literals or template literals
'no-useless-concat': ALERT,
// disallow use of the void operator
'no-void': ALERT,
// disallow usage of configurable warning terms in comments - e.g. todo or fixme
'no-warning-comments': [WARN, {
terms: ['todo', 'fixme', 'xxx'],
location: 'start'
}],
// disallow use of the with statement
'no-with': ALERT,
// require use of the second argument for parseInt()
radix: ALERT,
// require declaration of all vars at the top of their containing scope
'vars-on-top': ALERT,
// require immediate function invocation to be wrapped in parentheses
'wrap-iife': [ALERT, 'any'],
// require or disallow Yoda conditions
yoda: ALERT,
/* Variables */
// enforce or disallow variable initializations at definition
'init-declarations': [WARN, 'always'],
// disallow the catch clause parameter name being the same as a variable in the outer scope
'no-catch-shadow': ALERT,
// disallow deletion of variables
'no-delete-var': ALERT,
// disallow labels that share a name with a variable
'no-label-var': ALERT,
// disallow shadowing of names such as arguments
'no-shadow-restricted-names': ALERT,
// disallow declaration of variables already declared in the outer scope
'no-shadow': ALERT,
// disallow use of undefined when initializing variables
'no-undef-init': ALERT,
// disallow use of undeclared variables unless mentioned in a /*global */ block
'no-undef': ALERT,
// disallow use of undefined variable
'no-undefined': IGNORE,
// disallow declaration of variables that are not used in the code
'no-unused-vars': ALERT,
// disallow use of variables before they are defined
'no-use-before-define': ALERT,
/* Node.js and CommonJS */
// enforce return after a callback
'callback-return': ALERT,
// enforce require() on top-level module scope
'global-require': ALERT,
// enforce error handling in callbacks
'handle-callback-err': ALERT,
// disallow mixing regular variable and require declarations
'no-mixed-requires': ALERT,
// disallow use of new operator with the require function
'no-new-require': ALERT,
// disallow string concatenation with __dirname and __filename
'no-path-concat': ALERT,
// disallow process.exit()
'no-process-exit': ALERT,
// restrict usage of specified node modules
'no-restricted-modules': IGNORE,
// disallow use of synchronous methods
'no-sync': ALERT,
/* Stylistic Issues */
// enforce spacing inside array brackets
'array-bracket-spacing': [ALERT, 'never'],
// disallow or enforce spaces inside of single line blocks
'block-spacing': [ALERT, 'always'],
// enforce one true brace style
'brace-style': [ALERT, 'stroustrup', { allowSingleLine: true }],
// require camel case names
camelcase: [ALERT, { properties: 'always' }],
// enforce spacing before and after comma
'comma-spacing': [ALERT, { before: false, after: true }],
// enforce one true comma style
'comma-style': [ALERT, 'last'],
// require or disallow padding inside computed properties
'computed-property-spacing': [ALERT, 'never'],
// enforce consistent naming when capturing the current execution context
'consistent-this': [ALERT, 'self'],
// enforce newline at the end of file, with no multiple empty lines
'eol-last': ALERT,
// require function expressions to have a name
'func-names': WARN,
// enforce use of function declarations or expressions
'func-style': IGNORE,
// this option enforces minimum and maximum identifier lengths (variable names, property names etc.)
'id-length': IGNORE,
// require identifiers to match the provided regular expression
'id-match': IGNORE,
// specify tab or space width for your code
indent: [ALERT, 2],
// specify whether double or single quotes should be used in JSX attributes
'jsx-quotes': [ALERT, 'prefer-single'],
// enforce spacing between keys and values in object literal properties
'key-spacing': [ALERT, { beforeColon: false, afterColon: true }],
// disallow mixed LF and CRLF as linebreaks
'linebreak-style': [ALERT, 'unix'],
// enforce empty lines around comments
'lines-around-comment': [ALERT, {
beforeBlockComment: true,
allowBlockStart: true,
allowObjectStart: true,
allowArrayStart: true
}],
// specify the maximum depth that blocks can be nested
'max-depth': [WARN, MAX_NESTED_BLOCKS],
// specify the maximum length of a line in your program
'max-len': [WARN, MAX_STATEMENT_LENGTH, TAB_SPACE, {
ignoreComments: true,
ignoreUrls: true
}],
// specify the maximum depth callbacks can be nested
'max-nested-callbacks': [WARN, MAX_NESTED_CALLBACKS],
// limits the number of parameters that can be used in the function declaration.
'max-params': [WARN, MAX_PARAMS],
// specify the maximum number of statement allowed in a function
'max-statements': [IGNORE, MAX_STATEMENTS],
// require a capital letter for constructors
'new-cap': [ALERT, { newIsCap: true, capIsNew: false }],
// disallow the omission of parentheses when invoking a constructor with no arguments
'new-parens': ALERT,
// require or disallow an empty newline after variable declarations
'newline-after-var': ALERT,
// disallow use of the Array constructor
'no-array-constructor': ALERT,
// disallow use of bitwise operators
'no-bitwise': ALERT,
// disallow use of the continue statement
'no-continue': ALERT,
// disallow comments inline after code
'no-inline-comments': ALERT,
// disallow if as the only statement in an else block
'no-lonely-if': ALERT,
// disallow mixed spaces and tabs for indentation
'no-mixed-spaces-and-tabs': [ALERT, 'smart-tabs'],
// disallow multiple empty lines
'no-multiple-empty-lines': [ALERT, { max: 2, maxEOF: 1 }],
// disallow negated conditions
'no-negated-condition': ALERT,
// disallow nested ternary expressions
'no-nested-ternary': ALERT,
// disallow the use of the Object constructor
'no-new-object': ALERT,
// disallow use of unary operators, ++ and --
'no-plusplus': [ALERT, { allowForLoopAfterthoughts: true }],
// disallow use of certain syntax in code
'no-restricted-syntax': [ALERT, 'ClassDeclaration'],
// disallow space between function identifier and application
'no-spaced-func': ALERT,
// disallow the use of ternary operators
'no-ternary': IGNORE,
// disallow trailing whitespace at the end of lines
'no-trailing-spaces': ALERT,
// disallow dangling underscores in identifiers
'no-underscore-dangle': IGNORE,
// disallow the use of ternary operators when a simpler alternative exists
'no-unneeded-ternary': ALERT,
// require or disallow padding inside curly braces
'object-curly-spacing': [ALERT, 'always'],
// require or disallow one variable declaration per function
'one-var': [WARN, 'always'],
// require assignment operator shorthand where possible or prohibit it entirely
'operator-assignment': [ALERT, 'always'],
// enforce operators to be placed before or after line breaks
'operator-linebreak': [ALERT, 'before'],
// enforce padding within blocks
'padded-blocks': [ALERT, 'never'],
// require quotes around object literal property names
'quote-props': [ALERT, 'as-needed', { keywords: true }],
// specify whether backticks, double or single quotes should be used
quotes: [ALERT, 'single', 'avoid-escape'],
// Require JSDoc comment
'require-jsdoc': [WARN, {
require: {
FunctionDeclaration: true,
MethodDefinition: true,
ClassDeclaration: true
}
}],
// enforce spacing before and after semicolons
'semi-spacing': [ALERT, { before: false, after: true }],
// require or disallow use of semicolons instead of ASI
semi: [ALERT, 'always'],
// sort variables within the same declaration block
'sort-vars': [IGNORE, { ignoreCase: true }],
// require a space after certain keywords
'space-after-keywords': [ALERT, 'always'],
// require or disallow a space before blocks
'space-before-blocks': [ALERT, 'always'],
// require or disallow a space before function opening parenthesis
'space-before-function-paren': [ALERT, 'never'],
// require a space before certain keywords
'space-before-keywords': [ALERT, 'always'],
// require or disallow spaces inside parentheses
'space-in-parens': [ALERT, 'never'],
// require spaces around operators
'space-infix-ops': ALERT,
// require a space after return, throw, and case
'space-return-throw-case': ALERT,
// require or disallow spaces before/after unary operators
'space-unary-ops': [ALERT, { words: true, nonwords: false }],
// require or disallow a space immediately following the // or /* in a comment
'spaced-comment': [ALERT, 'always'],
// require regex literals to be wrapped in parentheses
'wrap-regex': IGNORE,
/* ECMAScript 6 */
// require braces in arrow function body
'arrow-body-style': [ALERT, 'as-needed'],
// require parens in arrow function arguments
'arrow-parens': [ALERT, 'as-needed'],
// require space before/after arrow functions arrow
'arrow-spacing': [ALERT, { before: true, after: true }],
// verify calls of super() in constructors
'constructor-super': ALERT,
// enforce spacing around the * in generator functions
'generator-star-spacing': [ALERT, { before: false, after: true }],
// disallow arrow functions where a condition is expected
'no-arrow-condition': ALERT,
// disallow modifying variables of class declarations
'no-class-assign': ALERT,
// disallow modifying variables that are declared using const
'no-const-assign': ALERT,
// disallow duplicate name in class members
'no-dupe-class-members': ALERT,
// disallow use of this/super before calling super() in constructors.
'no-this-before-super': ALERT,
// require let or const instead of var
'no-var': ALERT,
// require method and property shorthand syntax for object literals
'object-shorthand': ALERT,
// suggest using arrow functions as callbacks
'prefer-arrow-callback': IGNORE,
// suggest using const declaration for variables that are never modified after declared
'prefer-const': WARN,
// suggest using Reflect methods where applicable
'prefer-reflect': IGNORE,
// suggest using the spread operator instead of .apply().
'prefer-spread': ALERT,
// suggest using template literals instead of strings concatenation
'prefer-template': ALERT,
// disallow generator functions that do not have yield
'require-yield': ALERT,
/* Plugins */
/* - Meteor */
// Definitions for global Meteor variables based on environment
'meteor/globals': ALERT,
// Meteor Core API
'meteor/core': ALERT,
// Prevent misusage of Publish and Subscribe
'meteor/pubsub': ALERT,
// Prevent misusage of methods
'meteor/methods': ALERT,
// Core API for check and Match
'meteor/check': ALERT,
// Core API for connections
'meteor/connections': ALERT,
// Core API for collections
'meteor/collections': ALERT,
// Core API for Session
'meteor/session': ALERT,
// Enforce check on all arguments passed to methods and publish functions
'meteor/audit-argument-checks': IGNORE,
// Prevent usage of Session
'meteor/no-session': ALERT,
// Prevent deprecated template lifecycle callback assignments
'meteor/no-blaze-lifecycle-assignment': ALERT,
// Prevent usage of Meteor.setTimeout with zero delay
'meteor/no-zero-timeout': ALERT,
// Force consistent event handler parameters in event maps
'meteor/blaze-consistent-eventmap-params': ALERT,
/* - React */
// Prevent missing displayName in a React component definition
'react/display-name': WARN,
// Forbid certain propTypes
'react/forbid-prop-types': WARN,
// Enforce boolean attributes notation in JSX
'react/jsx-boolean-value': WARN,
// Validate closing bracket location in JSX
'react/jsx-closing-bracket-location': WARN,
// Enforce or disallow spaces inside of curly braces in JSX attributes
'react/jsx-curly-spacing': WARN,
// Enforce event handler naming conventions in JSX
'react/jsx-handler-names': WARN,
// Validate props indentation in JSX
'react/jsx-indent-props': WARN,
// Validate JSX has key prop when in array or iterator
'react/jsx-key': WARN,
// Limit maximum of props on a single line in JSX
'react/jsx-max-props-per-line': WARN,
// Prevent usage of .bind() and arrow functions in JSX props
'react/jsx-no-bind': WARN,
// Prevent duplicate props in JSX
'react/jsx-no-duplicate-props': WARN,
// Prevent usage of unwrapped JSX strings
'react/jsx-no-literals': WARN,
// Disallow undeclared variables in JSX
'react/jsx-no-undef': WARN,
// Enforce PascalCase for user-defined JSX components
'react/jsx-pascal-case': WARN,
// Enforce quote style for JSX attributes
// 'react/jsx-quotes': WARN, // DEPRECIED
// Enforce propTypes declarations alphabetical sorting
'react/jsx-sort-prop-types': WARN,
// Enforce props alphabetical sorting
'react/jsx-sort-props': WARN,
// Prevent React to be incorrectly marked as unused
'react/jsx-uses-react': WARN,
// Prevent variables used in JSX to be incorrectly marked as unused
'react/jsx-uses-vars': WARN,
// Prevent usage of dangerous JSX properties
'react/no-danger': WARN,
// Prevent usage of setState in componentDidMount
'react/no-did-mount-set-state': WARN,
// Prevent usage of setState in componentDidUpdate
'react/no-did-update-set-state': WARN,
// Prevent direct mutation of this.state
'react/no-direct-mutation-state': WARN,
// Prevent multiple component definition per file
'react/no-multi-comp': WARN,
// Prevent usage of setState
'react/no-set-state': WARN,
// Prevent usage of unknown DOM property
'react/no-unknown-property': WARN,
// Prefer es6 class instead of createClass for React Components
'react/prefer-es6-class': WARN,
// Prevent missing props validation in a React component definition
'react/prop-types': WARN,
// Prevent missing React when using JSX
'react/react-in-jsx-scope': WARN,
// Restrict file extensions that may be required
'react/require-extension': WARN,
// Prevent extra closing tags for components without children
'react/self-closing-comp': WARN,
// Enforce component methods order
'react/sort-comp': WARN,
// Prevent missing parentheses around multilines JSX
'react/wrap-multilines': WARN,
/* - Jasmine */
// Disallow use of focused tests
'jasmine/no-focused-tests': ALERT,
// Disallow use of disabled tests
'jasmine/no-disabled-tests': WARN,
// Disallow the use of duplicate spec names
'jasmine/no-spec-dupes': [WARN, 'branch'],
// Disallow the use of duplicate suite names
'jasmine/no-suite-dupes': [WARN, 'branch'],
// Enforce that a suitess callback does not contain any arguments
'jasmine/no-suite-callback-args': ALERT,
// Enforce expectation
'jasmine/missing-expect': [WARN, 'expect()'],
// Enforce valid expect() usage
'jasmine/valid-expect': WARN,
/* - Lodash */
// Prefer property shorthand syntax
'lodash3/prop-shorthand': WARN,
// Prefer matches property shorthand syntax
'lodash3/matches-shorthand': [WARN, MAX_PATH_LENGTH],
// Prefer matches shorthand syntax
'lodash3/matches-prop-shorthand': WARN,
// Preferred aliases
'lodash3/prefer-chain': WARN,
// Prefer chain over nested lodash calls
'lodash3/preferred-alias': WARN,
// Prevent chaining syntax for single method, e.g. _(x).map().value()
'lodash3/no-single-chain': WARN,
// Prefer _.reject over filter with !(expression) or x.prop1 !== value
'lodash3/prefer-reject': [WARN, MAX_PATH_LENGTH],
// Prefer _.filter over _.forEach with an if statement inside.
'lodash3/prefer-filter': [WARN, MAX_PATH_LENGTH],
// Prefer passing thisArg over binding.
'lodash3/no-unnecessary-bind': WARN,
// Prevent chaining without evaluation via value() or non-chainable methods like max().
'lodash3/unwrap': WARN,
// Prefer _.compact over _.filter for only truthy values.
'lodash3/prefer-compact': WARN,
// Do not use .value() on chains that have already ended (e.g. with max() or reduce())
'lodash3/no-double-unwrap': WARN,
// Prefer _.map over _.forEach with a push inside.
'lodash3/prefer-map': WARN,
// Prefer using array and string methods in the chain and not the initial value, e.g. _(str).split( )...
'lodash3/prefer-wrapper-method': WARN,
// Prefer using _.invoke over _.map with a method call inside.
'lodash3/prefer-invoke': WARN,
// Prefer using _.prototype.thru in the chain and not call functions in the initial value, e.g. _(x).thru(f).map(g)...
'lodash3/prefer-thru': WARN,
// Prefer using Lodash chains (e.g. _.map) over native and mixed chains.
'lodash3/prefer-lodash-chain': WARN,
// Prefer using Lodash collection methods (e.g. _.map) over native array methods.
'lodash3/prefer-lodash-method': WARN,
// Prefer using _.is* methods over typeof and instanceof checks when applicable.
'lodash3/prefer-lodash-typecheck': WARN,
// Do not use .commit() on chains that should end with .value()
'lodash3/no-commit': WARN,
// Prefer using _.get or _.has over expression chains like a && a.b && a.b.c.
'lodash3/prefer-get': [WARN, MIN_DEPTH],
// Always return a value in iteratees of lodash collection methods that arent forEach.
'lodash3/collection-return': WARN,
// Prefer _.matches over conditions like a.foo === 1 && a.bar === 2 && a.baz === 3.
'lodash3/prefer-matches': WARN,
// Prefer _.times over _.map without using the iteratees arguments.
'lodash3/prefer-times': WARN,
/* - MongoDB */
// Check insertOne/insertMany calls to ensure their arguments are well formed.
'mongodb/check-insert-calls': ALERT,
// Check find/findOne calls to ensure their arguments are well formed
'mongodb/check-query-calls': ALERT,
// Check update calls to ensure their arguments are well formed.
'mongodb/check-update-calls': ALERT,
// Check remove calls to ensure their arguments are well formed.
'mongodb/check-remove-calls': ALERT,
// Check collection calls and warn in case of deprecated methods usage.
'mongodb/check-deprecated-calls': ALERT,
// Check update queries to ensure no raw replace is done
'mongodb/no-replace': WARN,
// Check $rename update operator usage.
'mongodb/check-rename-updates': ALERT,
// Check $unset update operator usage.
'mongodb/check-unset-updates': ALERT,
// Check $currentDate update operator usage.
'mongodb/check-current-date-updates': ALERT,
// Check update queries to ensure numeric operators like $mul and $inc contain numeric values.
'mongodb/check-numeric-updates': ALERT,
// Check $min and $max update operators usage.
'mongodb/check-minmax-updates': ALERT,
// Check $set and $setOnInsert update operators usage.
'mongodb/check-set-updates': ALERT,
// Check $push update operator usage and its modifiers.
'mongodb/check-push-updates': ALERT,
// Check $pull update operator usage.
'mongodb/check-pull-updates': ALERT,
// Check $pop update operator usage.
'mongodb/check-pop-updates': ALERT,
// Check $addToSet update operator usage and common misuses.
'mongodb/check-addtoset-updates': ALERT,
// Check deprecated update operator usage.
'mongodb/check-deprecated-updates': ALERT
},
settings: {
mongodb: {
callPatterns: {
query: [
'(\\.|^)db\\.collection\\([^\\)]+\\)\\.(find|findOne|)$'
],
update: [
'(\\.|^)db\\.collection\\([^\\)]+\\)\\.(findOneAndUpdate'
+ '|updateOne|updateMany)$'
],
insert: [
'(\\.|^)db\\.collection\\([^\\)]+\\)\\.(insertOne|insertMany)$'
],
remove: [
'(\\.|^)db\\.collection\\([^\\)]+\\)\\.(findOneAndDelete'
+ '|deleteOne|deleteMany)$'
],
deprecated: [
'(\\.|^)db\\.collection\\([^\\)]+\\)\\.(remove|update|'
+ 'findAndModify|ensureIndex|findAndRemove|insert|dropAllIndexes)$'
]
}
},
meteor: {
// all universal collections
collections: []
}
},
globals: {
// main package
K: true,
Patterns: true,
errorPrefix: true,
buildCheckError: true,
primitiveMap: true,
// tests
beautifyPattern: true,
beautifyValue: true,
matches: true,
fails: true,
primitiveValues: true,
integrateArray: true,
integrateCustomFunctions: true,
integrateExactValues: true,
integrateMatchAny: true,
integrateMatchInteger: true,
integrateMatchOneOf: true,
integrateMatchWhere: true,
integrateObject: true,
integratePrimitiveTypes: true,
matchAny: true,
matchInteger: true
}
};
|
// Select DOM elements to work with
const welcomeDiv = document.getElementById("WelcomeMessage");
const signInButton = document.getElementById("SignIn");
const cardDiv = document.getElementById("card-div");
const mailButton = document.getElementById("readMail");
const profileButton = document.getElementById("seeProfile");
const profileDiv = document.getElementById("profile-div");
const popTokenAcquired = document.getElementById("PopTokenAcquired");
function showWelcomeMessage(account) {
// Reconfiguring DOM elements
cardDiv.style.display = 'initial';
welcomeDiv.innerHTML = `Welcome ${username}`;
signInButton.nextElementSibling.style.display = 'none';
signInButton.setAttribute("onclick", "signOut();");
signInButton.setAttribute('class', "btn btn-success")
signInButton.innerHTML = "Sign Out";
}
function showPopTokenAcquired() {
const popTokenAcquired = document.createElement('p');
popTokenAcquired.setAttribute("id", "PopTokenAcquired");
popTokenAcquired.innerHTML = "Successfully acquired PoP Token";
profileDiv.appendChild(popTokenAcquired);
}
function updateUI(data, endpoint) {
console.log('Graph API responded at: ' + new Date().toString());
if (endpoint === graphConfig.graphMeEndpoint) {
const title = document.createElement('p');
title.innerHTML = "<strong>Title: </strong>" + data.jobTitle;
const email = document.createElement('p');
email.innerHTML = "<strong>Mail: </strong>" + data.mail;
const phone = document.createElement('p');
phone.innerHTML = "<strong>Phone: </strong>" + data.businessPhones[0];
const address = document.createElement('p');
address.innerHTML = "<strong>Location: </strong>" + data.officeLocation;
profileDiv.appendChild(title);
profileDiv.appendChild(email);
profileDiv.appendChild(phone);
profileDiv.appendChild(address);
} else if (endpoint === graphConfig.graphMailEndpoint) {
if (data.value.length < 1) {
alert("Your mailbox is empty!")
} else {
const tabList = document.getElementById("list-tab");
const tabContent = document.getElementById("nav-tabContent");
data.value.map((d, i) => {
// Keeping it simple
if (i < 10) {
const listItem = document.createElement("a");
listItem.setAttribute("class", "list-group-item list-group-item-action")
listItem.setAttribute("id", "list" + i + "list")
listItem.setAttribute("data-toggle", "list")
listItem.setAttribute("href", "#list" + i)
listItem.setAttribute("role", "tab")
listItem.setAttribute("aria-controls", i)
listItem.innerHTML = d.subject;
tabList.appendChild(listItem)
const contentItem = document.createElement("div");
contentItem.setAttribute("class", "tab-pane fade")
contentItem.setAttribute("id", "list" + i)
contentItem.setAttribute("role", "tabpanel")
contentItem.setAttribute("aria-labelledby", "list" + i + "list")
contentItem.innerHTML = "<strong> from: " + d.from.emailAddress.address + "</strong><br><br>" + d.bodyPreview + "...";
tabContent.appendChild(contentItem);
}
});
}
}
}
|
var gulp = require('gulp'),
sass = require('gulp-sass'),
autoprefixer = require('gulp-autoprefixer'),
rename = require('gulp-rename'),
browserSync = require('browser-sync').create(),
cssnano = require('gulp-cssnano');
gulp.task('css', function () {
return gulp.src('scss/main.scss')
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer('last 4 version'))
.pipe(gulp.dest('css'))
.pipe(cssnano())
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('css'))
.pipe(browserSync.stream())
});
// Static Server + watching scss/html files
gulp.task('serve', ['css'], function() {
browserSync.init({
server: "./"
});
gulp.watch("scss/**/*.scss", ['css']);
gulp.watch("*.html").on('change', browserSync.reload);
});
gulp.task('default', ['serve']);
|
VISITOR.pushDeclVar = function(_name, _index)
{
if(_index == undefined)
{
var currentScope = VISITOR.CURRENT_Function + 1;
COMPILER.VAR_STATE[currentScope].push(_name);
}
else COMPILER.VAR_STATE[_index].push(_name);
}
VISITOR.getDeclVar = function(_name, _index)
{
var _state;
if(_index == undefined)
{
var currentScope = VISITOR.CURRENT_Function + 1;
_state = COMPILER.VAR_STATE[currentScope].push(_name);
}
else _state =COMPILER.VAR_STATE[_index].push(_name);
console.log(_state);
}
VISITOR.checkUndefVar = function(_name)
{
var currentScope = VISITOR.CURRENT_Function + 1;
var _exists = false;
for(var i = currentScope; i > -1; i--)
{
if(COMPILER.VAR_STATE[i].indexOf(_name) > -1)
{
_exists = true;
break;
}
else if(COMPILER.GLOBAL.indexOf(_name) > -1)
{
_exists = true;
break;
}
}
if(!_exists)
{
COMPILER.VAR_STATE[currentScope].push(_name);
COMPILER.DECL.push( "var " + _name + ";");
}
}
VISITOR.addFunctionVarInit = function(_name)
{
if(VISITOR.CURRENT_Function > -1)
{
if(COMPILER.INFO.SCOPE[VISITOR.Function_STATE[VISITOR.CURRENT_Function]].init.indexOf(_name) < 0)
COMPILER.INFO.SCOPE[VISITOR.Function_STATE[VISITOR.CURRENT_Function]].init.push(_name);
}
}
VISITOR.addFunctionVarUse = function(_value)
{
if(VISITOR.CURRENT_Function > -1)
{
if(COMPILER.INFO.SCOPE[VISITOR.Function_STATE[VISITOR.CURRENT_Function]].use.indexOf(_value) < 0 && VISITOR.IGNORE.indexOf(_value) < 0)
COMPILER.INFO.SCOPE[VISITOR.Function_STATE[VISITOR.CURRENT_Function]].use.push(_value);
}
}
VISITOR.addFunctionVarCall = function(_id, _type)
{
if(COMPILER.INFO.SCOPE[_id] && COMPILER.INFO.SCOPE[_id].call.indexOf(_type) < 0)
COMPILER.INFO.SCOPE[_id].call.push(_type);
}
VISITOR.addFunctionVarParam = function(_id, _number)
{
if(COMPILER.INFO.SCOPE[_id] && COMPILER.INFO.SCOPE[_id].param.indexOf(_number) < 0)
COMPILER.INFO.SCOPE[_id].param.push(_number);
}
VISITOR.disableFastFunction = function()
{
if(COMPILER.INFO.SCOPE[VISITOR.Function_STATE[VISITOR.CURRENT_Function]])
{
//COMPILER.INFO.SCOPE[VISITOR.Function_STATE[VISITOR.CURRENT_Function]].fast = false;
}
}
VISITOR.readOnlyVar = function(_name)
{
VISITOR.addFunctionVarInit(_name);
if(COMPILER.READ_ONLY.indexOf(_name) > -1)
{
console.log("[!] Fatal error: " + _name + " is a read only variable");
process.exit(1);
}
}
VISITOR.objectExpression = require("./objectExpression.js");
VISITOR.memberExpression = require("./memberExpression.js");
VISITOR.callExpression = require("./callExpression.js");
VISITOR.arrayExpression = require("./arrayExpression.js");
|
'use strict';
require('should');
const Mapper = require('../../src/mapper');
const testData = require('./data/mapperCustom');
const { checkResult } = require('../helpers/integration/resultChecker');
function resultToPromise(result, isPromisify) {
if (isPromisify) {
return Promise.resolve(result);
} else {
return result;
}
}
function generateMapperCustomTests(isAsync) {
const { methodName } = testData;
const fullMethodName = isAsync ? `${methodName}Async` : methodName;
const testsPrefix = isAsync ? '- async' : '';
it(`should use array new map with custom behaviour (Simple Type to Simple Type) ${testsPrefix}`, () => {
const { SourceSimpleType, DestSimpleType, sourceSimpleObject, expectedDestSimpleToSimpleObject } = testData;
const mapper = new Mapper();
mapper.register(mapper.SNAKE_CASE_CONVENTION, fullMethodName, SourceSimpleType, DestSimpleType, (map) => {
map.ignoreField('field_3')
.mapField('field_2', obj => resultToPromise(obj.field2.toUpperCase(), isAsync))
.mapFieldByPath('field_1', 'field1');
});
return checkResult(testData, mapper[fullMethodName]([sourceSimpleObject]), [expectedDestSimpleToSimpleObject], false, isAsync);
});
it(`should use new map with custom behaviour (Simple Type to Simple Type) ${testsPrefix}`, () => {
const { SourceSimpleType, DestSimpleType, sourceSimpleObject, expectedDestSimpleToSimpleObject } = testData;
const mapper = new Mapper();
mapper.register(mapper.SNAKE_CASE_CONVENTION, fullMethodName, SourceSimpleType, DestSimpleType, (map) => {
map.ignoreField('field_3')
.mapField('field_2', obj => resultToPromise(obj.field2.toUpperCase(), isAsync))
.mapFieldByPath('field_1', 'field1');
});
return checkResult(testData, mapper[fullMethodName](sourceSimpleObject), expectedDestSimpleToSimpleObject, false, isAsync);
});
it(`should use new map with default behaviour (Simple Type to Custom Type) ${testsPrefix}`, () => {
const { SourceSimpleType, DestCustomType, sourceSimpleObject, expectedDestSimpleToCustomObject } = testData;
const mapper = new Mapper();
mapper.register(mapper.SNAKE_CASE_CONVENTION, fullMethodName, SourceSimpleType, DestCustomType, (map) => {
map.mapField('field_2', obj => resultToPromise(obj.field2.substring(0, 1), isAsync))
.mapField('field_test', 'fieldTest')
.mapFieldByPath('field_test2', 'fieldTest2');
});
return checkResult(testData, mapper[fullMethodName](sourceSimpleObject), expectedDestSimpleToCustomObject, true, isAsync);
});
it(`should use new map with default behaviour (Custom Type to Simple Type) ${testsPrefix}`, () => {
const { SourceCustomType, DestSimpleType, sourceCustomObject, expectedDestCustomToSimpleObject } = testData;
const mapper = new Mapper();
mapper.register(mapper.SNAKE_CASE_CONVENTION, fullMethodName, SourceCustomType, DestSimpleType, (map) => {
map.mapField('test', 'test');
});
return checkResult(testData, mapper[fullMethodName](sourceCustomObject), expectedDestCustomToSimpleObject, false, isAsync);
});
it(`should use new map with default behaviour (Custom Type to Custom Type) ${testsPrefix}`, () => {
const { SourceCustomType, DestCustomType, sourceCustomObject, expectedDestCustomToCustomObject } = testData;
const mapper = new Mapper();
mapper.register(mapper.SNAKE_CASE_CONVENTION, fullMethodName, SourceCustomType, DestCustomType, (map) => {
map.mapField('field_2', obj => resultToPromise(obj.field2.toUpperCase(), isAsync));
});
return checkResult(testData, mapper[fullMethodName](sourceCustomObject), expectedDestCustomToCustomObject, true, isAsync);
});
}
describe('Mapper with custom map', () => {
generateMapperCustomTests(false);
generateMapperCustomTests(true);
}); |
if (!_.isUndefined(Dagaz.Controller.addSound)) {
Dagaz.Controller.addSound(0, "../sounds/slide.ogg", true);
}
ZRF = {
JUMP: 0,
IF: 1,
FORK: 2,
FUNCTION: 3,
IN_ZONE: 4,
FLAG: 5,
SET_FLAG: 6,
POS_FLAG: 7,
SET_POS_FLAG: 8,
ATTR: 9,
SET_ATTR: 10,
PROMOTE: 11,
MODE: 12,
ON_BOARD_DIR: 13,
ON_BOARD_POS: 14,
PARAM: 15,
LITERAL: 16,
VERIFY: 20
};
Dagaz.Model.BuildDesign = function(design) {
design.checkVersion("z2j", "2");
design.checkVersion("smart-moves", "false");
design.checkVersion("progressive-levels", "true");
design.addDirection("se");
design.addDirection("s");
design.addDirection("sw");
design.addDirection("e");
design.addDirection("w");
design.addDirection("ne");
design.addDirection("nw");
design.addDirection("n");
design.addPlayer("You", [6, 7, 5, 4, 3, 2, 0, 1]);
design.addPosition("c1", [4, 3, 0, 1, 0, 0, 0, 0]);
design.addPosition("b1", [4, 3, 2, 1, -1, 0, 0, 0]);
design.addPosition("a1", [0, 3, 2, 0, -1, 0, 0, 0]);
design.addPosition("c2", [4, 3, 0, 1, 0, -2, 0, -3]);
design.addPosition("b2", [4, 3, 2, 1, -1, -2, -4, -3]);
design.addPosition("a2", [0, 3, 2, 0, -1, 0, -4, -3]);
design.addPosition("c3", [0, 0, 0, 1, 0, -2, 0, -3]);
design.addPosition("b3", [0, 0, 0, 1, -1, -2, -4, -3]);
design.addPosition("a3", [0, 0, 0, 0, -1, 0, -4, -3]);
design.addCommand(0, ZRF.FUNCTION, 24); // from
design.addCommand(0, ZRF.PARAM, 0); // $1
design.addCommand(0, ZRF.FUNCTION, 22); // navigate
design.addCommand(0, ZRF.FUNCTION, 1); // empty?
design.addCommand(0, ZRF.FUNCTION, 20); // verify
design.addCommand(0, ZRF.FUNCTION, 25); // to
design.addCommand(0, ZRF.FUNCTION, 28); // end
design.addCommand(1, ZRF.FUNCTION, 24); // from
design.addCommand(1, ZRF.PARAM, 0); // $1
design.addCommand(1, ZRF.FUNCTION, 22); // navigate
design.addCommand(1, ZRF.PARAM, 1); // $2
design.addCommand(1, ZRF.FUNCTION, 22); // navigate
design.addCommand(1, ZRF.FUNCTION, 1); // empty?
design.addCommand(1, ZRF.FUNCTION, 20); // verify
design.addCommand(1, ZRF.FUNCTION, 25); // to
design.addCommand(1, ZRF.FUNCTION, 28); // end
design.addCommand(2, ZRF.FUNCTION, 24); // from
design.addCommand(2, ZRF.PARAM, 0); // $1
design.addCommand(2, ZRF.FUNCTION, 22); // navigate
design.addCommand(2, ZRF.FUNCTION, 1); // empty?
design.addCommand(2, ZRF.FUNCTION, 0); // not
design.addCommand(2, ZRF.IF, 7);
design.addCommand(2, ZRF.FORK, 3);
design.addCommand(2, ZRF.FUNCTION, 25); // to
design.addCommand(2, ZRF.FUNCTION, 28); // end
design.addCommand(2, ZRF.PARAM, 1); // $2
design.addCommand(2, ZRF.FUNCTION, 22); // navigate
design.addCommand(2, ZRF.JUMP, -8);
design.addCommand(2, ZRF.FUNCTION, 28); // end
design.addPiece("Pawn", 0);
design.addMove(0, 0, [7], 0);
design.addPiece("Knight", 1);
design.addMove(1, 1, [7, 6], 0);
design.addMove(1, 1, [7, 5], 0);
design.addPiece("Lance", 2);
design.addMove(2, 2, [7, 7], 0);
design.addPiece("Rook", 3);
design.addMove(3, 2, [7, 7], 0);
design.addMove(3, 2, [3, 3], 0);
design.addMove(3, 2, [4, 4], 0);
design.addMove(3, 2, [1, 1], 0);
design.addPiece("Bishop", 4);
design.addMove(4, 2, [6, 6], 0);
design.addMove(4, 2, [5, 5], 0);
design.addMove(4, 2, [2, 2], 0);
design.addMove(4, 2, [0, 0], 0);
design.addPiece("Silver", 5);
design.addMove(5, 0, [7], 0);
design.addMove(5, 0, [6], 0);
design.addMove(5, 0, [5], 0);
design.addMove(5, 0, [2], 0);
design.addMove(5, 0, [0], 0);
design.setup("You", "Rook", 2);
design.setup("You", "Knight", 4);
design.setup("You", "Knight", 5);
design.setup("You", "Silver", 1);
design.setup("You", "Silver", 7);
design.goal(0, "You", "Rook", [8]);
}
Dagaz.View.configure = function(view) {
view.defBoard("Board");
view.defPiece("YouPawn", "You Pawn");
view.defPiece("YouKnight", "You Knight");
view.defPiece("YouLance", "You Lance");
view.defPiece("YouRook", "You Rook");
view.defPiece("YouBishop", "You Bishop");
view.defPiece("YouSilver", "You Silver");
view.defPosition("c1", 4, 4, 64, 65);
view.defPosition("b1", 76, 4, 64, 65);
view.defPosition("a1", 148, 4, 64, 65);
view.defPosition("c2", 4, 76, 64, 65);
view.defPosition("b2", 76, 76, 64, 65);
view.defPosition("a2", 148, 76, 64, 65);
view.defPosition("c3", 4, 148, 64, 65);
view.defPosition("b3", 76, 148, 64, 65);
view.defPosition("a3", 148, 148, 64, 65);
}
|
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.config.debug = true;
Vue.config.devTools = true;
// import components
import app from './components/App.vue';
// import map
import routes from './router/routes.js';
import VueResource from 'vue-resource'
/**
VUE ROUTER CONFIGURATION
*/
// Make new VueRouter Instance
Vue.use(VueRouter)
Vue.use(VueResource)
let router = new VueRouter({ routes })
/**
MOUNT THE VUE
*/
new Vue( Vue.util.extend({ router }, app)).$mount('app')
|
const Facade = require.main.require('./core/Common/Facades/Facade');
class SearchFacade extends Facade {
static getFacadeAccessor() { return 'SearchService' }
}
module.exports = SearchFacade; |
/*jshint browser:true */
/*global angular:true */
'use strict';
/*
Angular.js service wrapping the elastic.js API. This module can simply
be injected into your angular controllers.
*/
angular.module('elasticjs.service', [])
.factory('ejsResource', ['$http', function ($http) {
return function (config) {
var
// use existing ejs object if it exists
ejs = window.ejs || {},
/* results are returned as a promise */
promiseThen = function (httpPromise, successcb, errorcb) {
return httpPromise.then(function (response) {
(successcb || angular.noop)(response.data);
return response.data;
}, function (response) {
(errorcb || angular.noop)(response.data);
return response.data;
});
};
// check if we have a config object
// if not, we have the server url so
// we convert it to a config object
if (config !== Object(config)) {
config = {server: config};
}
// set url to empty string if it was not specified
if (config.server == null) {
config.server = '';
}
/* implement the elastic.js client interface for angular */
ejs.client = {
server: function (s) {
if (s == null) {
return config.server;
}
config.server = s;
return this;
},
post: function (path, data, successcb, errorcb) {
path = config.server + path;
var reqConfig = {url: path, data: data, method: 'POST'};
return promiseThen($http(angular.extend(reqConfig, config)), successcb, errorcb);
},
get: function (path, data, successcb, errorcb) {
path = config.server + path;
// no body on get request, data will be request params
var reqConfig = {url: path, params: data, method: 'GET'};
return promiseThen($http(angular.extend(reqConfig, config)), successcb, errorcb);
},
put: function (path, data, successcb, errorcb) {
path = config.server + path;
var reqConfig = {url: path, data: data, method: 'PUT'};
return promiseThen($http(angular.extend(reqConfig, config)), successcb, errorcb);
},
del: function (path, data, successcb, errorcb) {
path = config.server + path;
var reqConfig = {url: path, data: data, method: 'DELETE'};
return promiseThen($http(angular.extend(reqConfig, config)), successcb, errorcb);
},
head: function (path, data, successcb, errorcb) {
path = config.server + path;
// no body on HEAD request, data will be request params
var reqConfig = {url: path, params: data, method: 'HEAD'};
return $http(angular.extend(reqConfig, config))
.then(function (response) {
(successcb || angular.noop)(response.headers());
return response.headers();
}, function (response) {
(errorcb || angular.noop)(undefined);
return undefined;
});
}
};
return ejs;
};
}]);
|
var debug = require( 'debug' ),
verbose = debug( 'twtstats-verbose' ),
log = debug( 'twtstats:main' ),
path = require( 'path' ),
readline = require('readline'),
request = require( 'request' ),
Stream = require('stream'),
fs = require( 'fs' ),
Tweet = require( './entities/tweet' ),
Matrix = require( './entities/matrix' ),
stats = require( './libs/stats' ),
tweets = [],
tweetsLength = 0,
inStream, outStream;
var DAYS = 7,
HOUR_RANGE = 4,
URL_CSV = process.env.URL_CSV || null;
outStream = new Stream();
outStream.readable = true;
outStream.writable = true;
inStream = URL_CSV ? request.get( URL_CSV )
: fs.createReadStream( path.join( __dirname, 'db', 'blackfriday2013.csv' ) );
readline.createInterface( { input: inStream, output: outStream, terminal: false} )
.on( 'line', function( line ){
var twt = line.split( /,/ ),
favs = parseInt( twt[4], 10 ),
retwts = parseInt( twt[3], 10 ),
date = twt[5];
if( !isNaN(favs) && !isNaN(retwts) && date )
{
verbose( "[%s]favs(%s) retweets(%s) date(%s)", twt[0], twt[4], twt[3], twt[5] );
tweets[tweetsLength++] = new Tweet( retwts, favs, date );
} else {
verbose( 'Invalid tweet %j', twt );
}
} )
.on( 'close', function(){
var buckets = [],
matrixIndexRetwts, matrixIndexFavs, matrixIndexWeight, matrixTwetsPerDayAndHour,
bestScoreInWeekForRetwts, bestScoreInWeekForFavs, bestScoreInWeekForWeigth, bestScoreInWeekForTwetsPerDayHour,
bestScoreNextDayForRetwts, bestScoreNextDayForFavs, bestScoreNextDayForWeigth, bestScoreNextDayForTwetsPerDayHour;
log( 'Sample %d tweets', tweets.length );
verbose( "Tweets: %j", tweets );
buckets = stats.distribution( tweets, Array.apply(null, /*7 Days X 4 Hours_Rage*/ Array( DAYS * HOUR_RANGE ) ).map( function(){ return []; } ) );
// To create the matrix first I get the median using a specific key. After that, percentages are calculated using the max. value in the array.
matrixIndexRetwts = new Matrix( stats.scale( stats.median( buckets, 'retwts' ) ), HOUR_RANGE, DAYS, 'Index Retwts' );
matrixIndexFavs = new Matrix( stats.scale( stats.median( buckets, 'favs' ) ), HOUR_RANGE, DAYS, 'Index Favs' );
matrixIndexWeight = new Matrix( stats.scale( stats.median( buckets, 'weight' ) ), HOUR_RANGE, DAYS, 'Index Weight' );
bestScoreInWeekForRetwts = matrixIndexRetwts.bestScore();
bestScoreInWeekForFavs = matrixIndexFavs.bestScore();
bestScoreInWeekForWeigth = matrixIndexWeight.bestScore();
bestScoreNextDayForRetwts = matrixIndexRetwts.bestScore( ( new Date().getDay() + 1 ) % DAYS );
bestScoreNextDayForFavs = matrixIndexRetwts.bestScore( ( new Date().getDay() + 1 ) % DAYS );
bestScoreNextDayForWeigth = matrixIndexRetwts.bestScore( ( new Date().getDay() + 1 ) % DAYS );
//BONUS: When the people is more active in twitter
matrixTwetsPerDayAndHour = new Matrix( buckets.map( function( bucket ){ return bucket.length } ), HOUR_RANGE, DAYS, 'Tweets Per Day/Hour (Bonus)' );
bestScoreInWeekForTwetsPerDayHour = matrixTwetsPerDayAndHour.bestScore();
bestScoreNextDayForTwetsPerDayHour = matrixTwetsPerDayAndHour.bestScore( ( new Date().getDay() + 1 ) % DAYS );
log( "\n%s\n", matrixIndexRetwts.print() );
log( "On %s. at %s is the optimal combination to get retwts", bestScoreInWeekForRetwts.day, bestScoreInWeekForRetwts.range );
log( "Tomorrow %s. at %s is the optimal combination to get retwts", bestScoreNextDayForRetwts.day, bestScoreNextDayForRetwts.range );
log( "\n%s\n", matrixIndexFavs.print() );
log( "On %s. at %s is the optimal combination to get favs", bestScoreInWeekForFavs.day, bestScoreInWeekForFavs.range );
log( "Tomorrow %s. at %s is the optimal combination to get favs", bestScoreNextDayForFavs.day, bestScoreNextDayForFavs.range );
log( "\n%s\n", matrixIndexWeight.print() );
log( "On %s. at %s is the optimal combination to get the best tweets", bestScoreInWeekForWeigth.day, bestScoreInWeekForWeigth.range );
log( "Tomorrow %s. at %s is the optimal combination to get the best tweets", bestScoreNextDayForWeigth.day, bestScoreNextDayForWeigth.range );
log( "\n%s\n", matrixTwetsPerDayAndHour.print() );
log( "On %s. at %s the people is more active in twitter", bestScoreInWeekForTwetsPerDayHour.day, bestScoreInWeekForTwetsPerDayHour.range );
log( "Tomorrow %s. at %s the people is more active in twitter", bestScoreNextDayForTwetsPerDayHour.day, bestScoreNextDayForTwetsPerDayHour.range );
} );
|
angular.module('crm', ['ui.state', 'ui.select2', 'ui.date', 'core.security', 'crm.templates'])
.config(['$routeProvider', '$locationProvider', '$stateProvider', '$urlRouterProvider', 'securityAuthorizationProvider',
function($routeProvider, $locationProvider, $stateProvider, $urlRouterProvider, securityAuthorizationProvider) {
$urlRouterProvider.otherwise('/contracts');
var contractList = {
name: 'page2C.contractList',
url: '/contracts',
views: {
'sidebar': {
templateUrl: '/ng-app/modules/crm/contracts/list/contractListFilter.tpl.html'
},
'content': {
templateUrl: '/ng-app/modules/crm/contracts/list/contractListGrid.tpl.html'
}
},
resolve: {
//authUser: securityAuthorizationProvider.requireAuthenticatedUser()
projectMember: securityAuthorizationProvider.requireGroups(['admins', 'managers', 'executors'])
}
},
contractCommonTab = {
name: 'tabPage1C.contractCommonTab',
url: '/contracts/:contractid/common',
views: {
'tabbar': {
template: '<div ng-controller="contractTabsCtrl" tabbar="0"></div>'
},
'content': {
templateUrl: '/ng-app/modules/crm/contracts/commonTab/contractCommonTab.tpl.html'
}
}
},
contractTasksTab = {
name: 'tabPage2C.contractTasksTab',
url: '/contracts/:contractid/tasks',
views: {
'tabbar': {
template: '<div ng-controller="contractTabsCtrl" tabbar="1"></div>'
},
'sidebar': {
templateUrl: '/ng-app/modules/crm/contracts/tasksTab/contractTasksTabFilter.tpl.html'
},
'content': {
templateUrl: '/ng-app/modules/crm/contracts/tasksTab/contractTasksTabGrid.tpl.html'
}
}
};
$stateProvider
.state(contractList)
.state(contractCommonTab)
.state(contractTasksTab);
}
])
.service("contractService", ['$q','$http',
function($q, $http) {
this.getContracts = function(filter) {
var deferred = $q.defer();
$http.post("/api/v1", {
action: "get",
model: "project.contracts",
project: window.app.project,
filter: filter
}).success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
// TODO
});
return deferred.promise;
};
this.getContractTasks = function(filter, contract) {
var deferred = $q.defer();
$http.post("/api/v1", {
action: "get",
model: "project.contracts.tasks",
project: window.app.project,
contract: parseInt(contract),
filter: filter
}).success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
// TODO
});
return deferred.promise;
};
}
])
.controller('contractListGridCtrl', ['$scope', 'contractService', 'pageConfig',
function($scope, $contractService, $pageConfig) {
$pageConfig.setConfig({
breadcrumbs: [{
name: "Projects",
url: '/projects'
},{
name: window.app.project,
url: '#!/contracts'
},{
name: 'Contracts',
url: '#!/contracts'
}]
});
$scope.contracts=[];
$contractService.getContracts({}).then(function (res) {
$scope.contracts = res.contracts;
});
}
])
.controller('contractTabsCtrl', ['$scope', '$stateParams',
function($scope, $stateParams) {
$scope.tabs = [{
name: 'Common',
url: '#!/contracts/' + $stateParams.contractid + '/common'
}, {
name: 'Tasks',
url: '#!/contracts/' + $stateParams.contractid + '/tasks'
}];
}
])
.controller('contractCommonTabCtrl', ['$scope', '$stateParams', 'pageConfig',
function($scope, $stateParams, $pageConfig) {
var contractid = $stateParams.contractid;
$pageConfig.setConfig({
breadcrumbs: [{
name: "Projects",
url: '/projects'
},{
name: window.app.project,
url: '#!/contracts'
},{
name: 'contracts',
url: '#!/contracts'
}, {
name: contractid,
url: '#!/contracts/' + contractid + '/common'
}
]
});
$scope.contractid = contractid;
}
])
.controller('contractTasksTabCtrl', ['$scope', '$stateParams', 'pageConfig', 'contractService',
function($scope, $stateParams, $pageConfig, $contractService) {
var contractid = $stateParams.contractid;
$pageConfig.setConfig({
breadcrumbs: [{
name: "Projects",
url: '/projects'
},{
name: window.app.project,
url: '#!/contracts'
},{
name: 'contracts',
url: '#!/contracts'
}, {
name: contractid,
url: '#!/contracts/' + contractid + '/common'
}
]
});
$scope.contractid = contractid;
$contractService.getContractTasks({}, contractid).then(function (res) {
$scope.tasks = res.tasks;
});
}
])
// Edit
.controller('contractItemCtrl', ['$scope', '$q', '$timeout',
function($scope, $q, $timeout) {
var categories = [{
id: 1,
text: 'cat'
}, {
id: 2,
text: 'dog'
}, {
id: 3,
text: 'pet'
}, {
id: 4,
text: 'rat'
}, {
id: 5,
text: 'fat'
}, {
id: 6,
text: 'zet'
}];
var contract = {
name: 'contract-123',
signedAt: new Date(2010, 01, 01),
category: [{
id: 1,
text: 'cat'
}]
};
$scope.categoryOptions = {
multiple: true,
query: function(query) {
$timeout(function() {
var data = {
results: categories
};
query.callback(data);
}, 400);
}
};
$scope.contract = angular.copy(contract);
$scope.cancel = function() {
//WTF?? where this method?? contractForm.$setPristine();
//$scope.contractForm.$pristine = true;
$scope.contract = angular.copy(contract);
};
$scope.update = function() {
if (contractForm) {
contract = angular.copy($scope.contract);
}
};
$scope.isChanged = function() {
return !angular.equals($scope.contract, contract);
};
}
])
.directive('requiredMultiple', function() {
function isEmpty(value) {
return angular.isUndefined(value) || (angular.isArray(value) && value.length === 0) || value === '' || value === null || value !== value;
}
return {
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) {
return;
}
attr.required = true; // force truthy in case we are on non input element
var validator = function(value) {
if (attr.required && (isEmpty(value) || value === false)) {
ctrl.$setValidity('required', false);
return;
} else {
ctrl.$setValidity('required', true);
return value;
}
};
ctrl.$formatters.push(validator);
ctrl.$parsers.unshift(validator);
attr.$observe('required', function() {
validator(ctrl.$viewValue);
});
}
};
})
.directive('fakeServerValidation', ['$timeout',
function($timeout) {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
var validator = function(viewValue) {
//fake call to server validation method
$timeout(function() {
if (viewValue && viewValue.indexOf('-') > 0) {
// it is valid
ctrl.$setValidity('fsv', true);
//return viewValue;
} else {
// it is invalid, return undefined (no model update)
ctrl.$setValidity('fsv', false);
//return viewValue;
}
}, 500);
return viewValue; //return must be synchronous because piped validators needs viewValue
};
ctrl.$formatters.push(validator);
ctrl.$parsers.unshift(validator);
}
};
}
]); |
var queue = require('queue-async');
var config = require('./config');
var codemotion = require('./../build/Release/codemotion');
var q = queue(config.NUM_TASKS * 2);
for (var i = 0; i < config.NUM_TASKS; i++) {
q.defer(function(done) {
done(null, codemotion.simpleTask(config.SECONDS));
});
}
q.awaitAll(function(err, results) {
console.dir(results);
});
console.log('Am I blocked?');
|
var canadian_cities = ["100 Mile House, British Columbia",
"108 Mile House, British Columbia",
"108 Mile Ranch, British Columbia",
"150 Mile House, British Columbia",
"Abbey, Saskatchewan",
"Abbotsford, British Columbia",
"Aberarder, Ontario",
"Abercorn, Quebec",
"Aberdeen, Saskatchewan",
"Abernethy, Saskatchewan",
"Abitibi Canyon, Ontario",
"Acadia Valley, Alberta",
"Acme, Alberta",
"Acton, Ontario",
"Acton Vale, Quebec",
"Adamsville, Quebec",
"Adolphustown, Ontario",
"Advocate Harbour, Nova Scotia",
"Agassiz, British Columbia",
"Agassiz Provincial Forest, Manitoba",
"Aguanish, Quebec",
"Ahousat, British Columbia",
"Ailsa Craig, Ontario",
"Airdrie, Alberta",
"Ajax, Ontario",
"Aklavik, Northwest Territories",
"Alameda, Saskatchewan",
"Alban, Ontario",
"Albanel, Quebec",
"Albert, New Brunswick",
"Albert Mines, New Brunswick",
"Alberta Beach, Alberta",
"Alberton, Prince Edward Island",
"Alder Flats, Alberta",
"Aldergrove, British Columbia",
"Alderville First Nation, Ontario",
"Alert Bay, British Columbia",
"Alexander, Manitoba",
"Alexandria, Ontario",
"Alexis Creek, British Columbia",
"Alfred, Ontario",
"Algoma Mills, Ontario",
"Alida, Saskatchewan",
"Alix, Alberta",
"Alkali Lake, British Columbia",
"Allan, Saskatchewan",
"Allardville, New Brunswick",
"Alliance, Alberta",
"Alliston, Ontario",
"Alma, New Brunswick",
"Alma, Quebec",
"Almonte, Ontario",
"Alonsa, Manitoba",
"Alouette, Quebec",
"Alsask, Saskatchewan",
"Altario, Alberta",
"Altona, Manitoba",
"Alvena, Saskatchewan",
"Alvinston, Ontario",
"Amherst, Nova Scotia",
"Amherstburg, Ontario",
"Amos, Quebec",
"Amqui, Quebec",
"Ancaster, Ontario",
"Andrew, Alberta",
"Aneroid, Saskatchewan",
"Angliers, Quebec",
"Angus, Ontario",
"Anjou, Quebec",
"Annapolis Royal, Nova Scotia",
"Anse-Saint-Jean, Quebec",
"Antigonish, Nova Scotia",
"Anzac, Alberta",
"Appleton, Newfoundland",
"Apsley, Ontario",
"Arborfield, Saskatchewan",
"Arborg, Manitoba",
"Archerwill, Saskatchewan",
"Arcola, Saskatchewan",
"Arden, Ontario",
"Ardrossan, Alberta",
"Argentia, Newfoundland",
"Argyle, Nova Scotia",
"Arichat, Nova Scotia",
"Arkell, Ontario",
"Arkona, Ontario",
"Armagh, Quebec",
"Armstrong, British Columbia",
"Armstrong, Ontario",
"Arnold`s Cove, Newfoundland",
"Arnprior, Ontario",
"Arrowwood, Alberta",
"Arthur, Ontario",
"Arundel, Quebec",
"Arviat, Nunavut",
"Asbestos, Quebec",
"Ascot, Quebec",
"Ascot Corner, Quebec",
"Ashcroft, British Columbia",
"Ashern, Manitoba",
"Ashmont, Alberta",
"Ashuapmushuan, Quebec",
"Asquith, Saskatchewan",
"Assiniboia, Saskatchewan",
"Assumption, Alberta",
"Aston-Jonction, Quebec",
"Athabasca, Alberta",
"Athens, Ontario",
"Atikokan, Ontario",
"Atlin, British Columbia",
"Attawapiskat, Ontario",
"Atwood, Ontario",
"Auburn, Ontario",
"Aurora, Ontario",
"Austin, Manitoba",
"Avola, British Columbia",
"Avondale, Newfoundland",
"Avonlea, Saskatchewan",
"Avonmore, Ontario",
"Ayer`s Cliff, Quebec",
"Aylesford, Nova Scotia",
"Aylmer, Ontario",
"Aylmer, Quebec",
"Ayr, Ontario",
"Ayton, Ontario",
"Azilda, Ontario",
"Baddeck, Nova Scotia",
"Baden, Ontario",
"Badger, Newfoundland",
"Bagotville, Quebec",
"Baie Verte, Newfoundland",
"Baie-Comeau, Quebec",
"Baie-de-Shawinigan, Quebec",
"Baie-des-Sables, Quebec",
"Baie-du-Febvre, Quebec",
"Baie-d`Urfe, Quebec",
"Baie-Johan-Beetz, Quebec",
"Baie-Sainte-Catherine, Quebec",
"Baie-St-Paul, Quebec",
"Baie-Ste-Anne, New Brunswick",
"Baie-Trinite, Quebec",
"Bailieboro, Ontario",
"Baker Brook, New Brunswick",
"Baker Lake, Nunavut",
"Bala, Ontario",
"Balcarres, Saskatchewan",
"Baldur, Manitoba",
"Balfour, British Columbia",
"Balgonie, Saskatchewan",
"Balmertown, Ontario",
"Balmoral, New Brunswick",
"Baltimore, Ontario",
"Bamfield, British Columbia",
"Bancroft, Ontario",
"Banff, Alberta",
"Barachois, Quebec",
"Barkmere, Quebec",
"Barons, Alberta",
"Barraute, Quebec",
"Barrhead, Alberta",
"Barrie, Ontario",
"Barriere, British Columbia",
"Barry`s Bay, Ontario",
"Barwick, Ontario",
"Bashaw, Alberta",
"Bass River, Nova Scotia",
"Bassano, Alberta",
"Basswood, Manitoba",
"Batawa, Ontario",
"Batchawana Bay, Ontario",
"Bath, New Brunswick",
"Bath, Ontario",
"Bathurst, New Brunswick",
"Batiscan, Quebec",
"Batteau, Newfoundland",
"Battle Harbour, Newfoundland",
"Battleford, Saskatchewan",
"Bauline, Newfoundland",
"Bawlf, Alberta",
"Bay Bulls, Newfoundland",
"Bay de Verde, Newfoundland",
"Bay L`Argent, Newfoundland",
"Bay Roberts, Newfoundland",
"Bayfield, Ontario",
"Baysville, Ontario",
"Beach Grove, British Columbia",
"Beachburg, Ontario",
"Beachville, Ontario",
"Beaconsfield, Quebec",
"Beamsville, Ontario",
"Bear Canyon, Alberta",
"Bear Lake, British Columbia",
"Bear River, Nova Scotia",
"Beardmore, Ontario",
"Bearskin Lake, Ontario",
"Bearskin Lake First Nation, Ontario",
"Bear`s Passage, Ontario",
"Beaucanton, Quebec",
"Beauceville, Quebec",
"Beauharnois, Quebec",
"Beaulac-Garthby, Quebec",
"Beaumont, Alberta",
"Beaumont, Newfoundland",
"Beaumont, Quebec",
"Beauport, Quebec",
"Beaupre, Quebec",
"Beausejour, Manitoba",
"Beauval, Saskatchewan",
"Beaver Cove, British Columbia",
"Beaver Creek, Yukon",
"Beaverdell, British Columbia",
"Beaverlodge, Alberta",
"Beaverton, Ontario",
"Becancour, Quebec",
"Bedeque, Prince Edward Island",
"Bedford, Quebec",
"Beechy, Saskatchewan",
"Beeton, Ontario",
"Beiseker, Alberta",
"Bell Island, Newfoundland",
"Bella Bella, British Columbia",
"Bella Coola, British Columbia",
"Belle Neige, Quebec",
"Belle River, Ontario",
"Belledune, New Brunswick",
"Bellefeuille, Quebec",
"Belleoram, Newfoundland",
"Belleterre, Quebec",
"Belleville, Ontario",
"Bellevue, Newfoundland",
"Belmont, Manitoba",
"Belmont, Ontario",
"Beloeil, Quebec",
"Bengough, Saskatchewan",
"Benito, Manitoba",
"Benoit`s Cove, Newfoundland",
"Bentley, Alberta",
"Berens River, Manitoba",
"Beresford, New Brunswick",
"Bergeronnes, Quebec",
"Berthierville, Quebec",
"Berwick, Nova Scotia",
"Berwyn, Alberta",
"Bethany, Ontario",
"Bethesda, Ontario",
"Bethune, Saskatchewan",
"Betsiamites, Quebec",
"Beulah, Manitoba",
"Biencourt, Quebec",
"Bienfait, Saskatchewan",
"Big River, Saskatchewan",
"Big Trout Lake, Ontario",
"Big Valley, Alberta",
"Biggar, Saskatchewan",
"Binbrook, Ontario",
"Bindloss, Alberta",
"Binscarth, Manitoba",
"Birch Hills, Saskatchewan",
"Birch Island, Ontario",
"Birchy Bay, Newfoundland",
"Birsay, Saskatchewan",
"Birtle, Manitoba",
"Biscotasing, Ontario",
"Bishopton, Quebec",
"Bishop`s Falls, Newfoundland",
"Bissett, Manitoba",
"Black Creek, British Columbia",
"Black Diamond, Alberta",
"Black Duck Cove, Newfoundland",
"Black Lake, Quebec",
"Black Point, British Columbia",
"Black Tickle, Newfoundland",
"Blackfalds, Alberta",
"Blackie, Alberta",
"Blacks Harbour, New Brunswick",
"Blackstock, Ontario",
"Blackville, New Brunswick",
"Blaine Lake, Saskatchewan",
"Blainville, Quebec",
"Blanc-Sablon, Quebec",
"Blandford, Nova Scotia",
"Blenheim, Ontario",
"Blezard Valley, Ontario",
"Blind River, Ontario",
"Bloomfield, Ontario",
"Blue Ridge, Alberta",
"Blue River, British Columbia",
"Blyth, Ontario",
"Bob Quinn Lake, British Columbia",
"Bobcaygeon, Ontario",
"Boiestown, New Brunswick",
"Bois-des-Filion, Quebec",
"Boisbriand, Quebec",
"Boischatel, Quebec",
"Boisdale, Nova Scotia",
"Boissevain, Manitoba",
"Bolton, Ontario",
"Bon Accord, Alberta",
"Bonanza, Alberta",
"Bonaventure, Quebec",
"Bonavista, Newfoundland",
"Bonfield, Ontario",
"Bonne-Esperance, Quebec",
"Bonnyville, Alberta",
"Borden, Ontario",
"Borden, Prince Edward Island",
"Borden, Saskatchewan",
"Boston Bar, British Columbia",
"Boswell, British Columbia",
"Bothwell, Ontario",
"Botwood, Newfoundland",
"Boucherville, Quebec",
"Bouchette, Quebec",
"Bouctouche, New Brunswick",
"Boularderie, Nova Scotia",
"Bourget, Ontario",
"Bow Island, Alberta",
"Bowden, Alberta",
"Bowen Island, British Columbia",
"Bowmanville, Ontario",
"Bowser, British Columbia",
"Boyd`s Cove, Newfoundland",
"Boyle, Alberta",
"Bracebridge, Ontario",
"Bradford, Ontario",
"Bradford West Gwillimbury, Ontario",
"Braeside, Ontario",
"Bragg Creek, Alberta",
"Brampton, Ontario",
"Branch, Newfoundland",
"Brandon, Manitoba",
"Brantford, Ontario",
"Breakeyville, Quebec",
"Brechin, Ontario",
"Bredenbury, Saskatchewan",
"Brent`s Cove, Newfoundland",
"Breslau, Ontario",
"Breton, Alberta",
"Bridge Lake, British Columbia",
"Bridgenorth, Ontario",
"Bridgetown, Nova Scotia",
"Bridgewater, Nova Scotia",
"Briercrest, Saskatchewan",
"Brigden, Ontario",
"Brigham, Quebec",
"Bright, Ontario",
"Brighton, Ontario",
"Brights Grove, Ontario",
"Brigus, Newfoundland",
"Britannia Beach, British Columbia",
"Britt, Ontario",
"Broadview, Saskatchewan",
"Brochet, Manitoba",
"Brock, Saskatchewan",
"Brocket, Alberta",
"Brockville, Ontario",
"Brome, Quebec",
"Bromont, Quebec",
"Bromptonville, Quebec",
"Brookdale, Manitoba",
"Brookfield, Nova Scotia",
"Brooklin, Ontario",
"Brooks, Alberta",
"Brossard, Quebec",
"Browns Flat, New Brunswick",
"Brownsburg, Quebec",
"Brownsville, Ontario",
"Brownvale, Alberta",
"Bruce Mines, Ontario",
"Bruderheim, Alberta",
"Bruno, Saskatchewan",
"Brussels, Ontario",
"Bryson, Quebec",
"Buchanan, Saskatchewan",
"Buchans, Newfoundland",
"Buckhorn, Ontario",
"Buckingham, Quebec",
"Buffalo Narrows, Saskatchewan",
"Burdett, Alberta",
"Burford, Ontario",
"Burgeo, Newfoundland",
"Burgessville, Ontario",
"Burin, Newfoundland",
"Burk`s Falls, Ontario",
"Burleigh Falls, Ontario",
"Burlington, Newfoundland",
"Burlington, Ontario",
"Burnaby, British Columbia",
"Burns Lake, British Columbia",
"Burnt Islands, Newfoundland",
"Burstall, Saskatchewan",
"Burwash Landing, Yukon",
"Bury, Quebec",
"Byemoor, Alberta",
"Cabano, Quebec",
"Cabri, Saskatchewan",
"Cache Bay, Ontario",
"Cache Creek, British Columbia",
"Cacouna, Quebec",
"Cadillac, Quebec",
"Cadillac, Saskatchewan",
"Cadomin, Alberta",
"Calabogie, Ontario",
"Calder, Saskatchewan",
"Caledon, Ontario",
"Caledon East, Ontario",
"Caledonia, Ontario",
"Calgary, Alberta",
"Callander, Ontario",
"Calling Lake, Alberta",
"Calmar, Alberta",
"Calstock, Ontario",
"Calumet, Quebec",
"Cambray, Ontario",
"Cambridge, Ontario",
"Cambridge Bay, Nunavut",
"Cameron, Ontario",
"Camlachie, Ontario",
"Campbell River, British Columbia",
"Campbellford, Ontario",
"Campbellton, New Brunswick",
"Campbellton, Newfoundland",
"Campbellville, Ontario",
"Campbell`s Bay, Quebec",
"Camperville, Manitoba",
"Campobello Island, New Brunswick",
"Camrose, Alberta",
"Canal Flats, British Columbia",
"Candiac, Quebec",
"Canmore, Alberta",
"Canning, Nova Scotia",
"Cannington, Ontario",
"Canoe Narrows, Saskatchewan",
"Canora, Saskatchewan",
"Canso, Nova Scotia",
"Canterbury, New Brunswick",
"Cantley, Quebec",
"Canwood, Saskatchewan",
"Cap-a-l`Aigle, Quebec",
"Cap-aux-Meules, Quebec",
"Cap-Chat, Quebec",
"Cap-de-la-Madeleine, Quebec",
"Cap-des-Rosiers, Quebec",
"Cap-Pele, New Brunswick",
"Cap-Rouge, Quebec",
"Cap-Saint-Ignace, Quebec",
"Cape Broyle, Newfoundland",
"Cape Dorset, Nunavut",
"Caplan, Quebec",
"Capreol, Ontario",
"Caradoc First Nation, Ontario",
"Caramat, Ontario",
"Caraquet, New Brunswick",
"Carberry, Manitoba",
"Carbon, Alberta",
"Carbonear, Newfoundland",
"Carcross, Yukon",
"Cardiff, Ontario",
"Cardigan, Prince Edward Island",
"Cardinal, Ontario",
"Cardston, Alberta",
"Cargill, Ontario",
"Caribou, Nova Scotia",
"Carievale, Saskatchewan",
"Carignan, Quebec",
"Carillon, Quebec",
"Carleton, Nova Scotia",
"Carleton, Quebec",
"Carleton Place, Ontario",
"Carlyle, Saskatchewan",
"Carmacks, Yukon",
"Carman, Manitoba",
"Carmangay, Alberta",
"Carmanville, Newfoundland",
"Carnarvon, Ontario",
"Carnduff, Saskatchewan",
"Caroline, Alberta",
"Caron, Saskatchewan",
"Carp, Ontario",
"Carrot River, Saskatchewan",
"Carseland, Alberta",
"Carstairs, Alberta",
"Cartier, Ontario",
"Cartwright, Manitoba",
"Cartwright, Newfoundland",
"Casselman, Ontario",
"Cassiar, British Columbia",
"Castlegar, British Columbia",
"Castlemore, Ontario",
"Castleton, Ontario",
"Castor, Alberta",
"Cat Lake, Ontario",
"Catalina, Newfoundland",
"Causapscal, Quebec",
"Cavan, Ontario",
"Cayley, Alberta",
"Cayuga, Ontario",
"Celista, British Columbia",
"Central Butte, Saskatchewan",
"Centralia, Ontario",
"Centreville, New Brunswick",
"Centreville-Wareham-Trinity, Newfoundland",
"Cereal, Alberta",
"Cessford, Alberta",
"Ceylon, Saskatchewan",
"Chalk River, Ontario",
"Chambly, Quebec",
"Chambord, Quebec",
"Champion, Alberta",
"Champlain, Quebec",
"Chance Cove, Newfoundland",
"Chandler, Quebec",
"Change islands, Newfoundland",
"Chapais, Quebec",
"Chapeau, Quebec",
"Chapel Arm, Newfoundland",
"Chapleau, Ontario",
"Chaplin, Saskatchewan",
"Charette, Quebec",
"Charlemagne, Quebec",
"Charlesbourg, Quebec",
"Charlevoix, Quebec",
"Charlottetown, Newfoundland",
"Charlottetown, Prince Edward Island",
"Charlton, Ontario",
"Charny, Quebec",
"Chartierville, Quebec",
"Chase, British Columbia",
"Chateau-Richer, Quebec",
"Chateauguay, Quebec",
"Chatham, New Brunswick",
"Chatham, Ontario",
"Chatsworth, Ontario",
"Chauvin, Alberta",
"Chelmsford, Ontario",
"Chelsea, Nova Scotia",
"Chelsea, Quebec",
"Chemainus, British Columbia",
"Cheneville, Quebec",
"Chesley, Ontario",
"Chester, Nova Scotia",
"Chesterfield Inlet, Nunavut",
"Chestermere, Alberta",
"Chesterville, Ontario",
"Chesterville, Quebec",
"Cheticamp, Nova Scotia",
"Chetwynd, British Columbia",
"Cheverie, Nova Scotia",
"Chevery, Quebec",
"Chibougamau, Quebec",
"Chicoutimi, Quebec",
"Chiefs Point First Nation, Ontario",
"Chilliwack, British Columbia",
"Chipewyan Lake, Alberta",
"Chipman, Alberta",
"Chipman, New Brunswick",
"Chippewas of Kettle/Stony Poin, Ontario",
"Chippewas Of Sarnia First Nati, Ontario",
"Chisasibi, Quebec",
"Choiceland, Saskatchewan",
"Chomedey, Quebec",
"Christian Island, Ontario",
"Christina Lake, British Columbia",
"Christopher Lake, Saskatchewan",
"Churchbridge, Saskatchewan",
"Churchill, Manitoba",
"Churchill Falls, Newfoundland",
"Chute-aux-Outardes, Quebec",
"Chute-des-Passes, Quebec",
"Clair, New Brunswick",
"Clairmont, Alberta",
"Claremont, Ontario",
"Clarence Creek, Ontario",
"Clarence-Rockland, Ontario",
"Clarenville, Newfoundland",
"Clarenville-Shoal Harbour, Newfoundland",
"Claresholm, Alberta",
"Clarington, Ontario",
"Clarke`s Beach, Newfoundland",
"Clarks Corners, New Brunswick",
"Clarkson, Ontario",
"Clarksville, Nova Scotia",
"Clark`s Harbour, Nova Scotia",
"Clavet, Saskatchewan",
"Clearwater, British Columbia",
"Clearwater Bay, Ontario",
"Clericy, Quebec",
"Clermont, Quebec",
"Clifford, Ontario",
"Climax, Saskatchewan",
"Clinton, British Columbia",
"Clinton, Ontario",
"Clive, Alberta",
"Cloridorme, Quebec",
"Cloud Bay, Ontario",
"Clova, Quebec",
"Clyde, Alberta",
"Coaldale, Alberta",
"Coalhurst, Alberta",
"Coaticook, Quebec",
"Cobalt, Ontario",
"Cobble Hill, British Columbia",
"Cobden, Ontario",
"Coboconk, Ontario",
"Cobourg, Ontario",
"Cocagne, New Brunswick",
"Cochenour, Ontario",
"Cochin, Saskatchewan",
"Cochrane, Alberta",
"Cochrane, Ontario",
"Coderre, Saskatchewan",
"Codroy, Newfoundland",
"Coe Hill, Ontario",
"Colborne, Ontario",
"Colchester, Ontario",
"Cold Lake, Alberta",
"Cold Springs, Ontario",
"Coldwater, Ontario",
"Coleville, Saskatchewan",
"Colliers, Newfoundland",
"Collingwood, Ontario",
"Collingwood Corner, Nova Scotia",
"Colombier, Quebec",
"Colonsay, Saskatchewan",
"Colwood, British Columbia",
"Comber, Ontario",
"Come By Chance, Newfoundland",
"Comfort Cove-Newstead, Newfoundland",
"Comox, British Columbia",
"Compton, Quebec",
"Conception Bay South, Newfoundland",
"Conception Harbour, Newfoundland",
"Conche, Newfoundland",
"Concord, Ontario",
"Coniston, Ontario",
"Conklin, Alberta",
"Connaught, Ontario",
"Conne River, Newfoundland",
"Conquest, Saskatchewan",
"Consort, Alberta",
"Constance Bay, Ontario",
"Constance Lake First Nation, Ontario",
"Consul, Saskatchewan",
"Contrecoeur, Quebec",
"Cookshire, Quebec",
"Cookstown, Ontario",
"Cooksville, Ontario",
"Cook`s Harbour, Newfoundland",
"Coquitlam, British Columbia",
"Coral Harbour, Nunavut",
"Cormorant, Manitoba",
"Corner Brook, Newfoundland",
"Cornwall, Ontario",
"Cornwall, Prince Edward Island",
"Coronach, Saskatchewan",
"Coronation, Alberta",
"Corunna, Ontario",
"Cote-St-Luc, Quebec",
"Coteau-du-Lac, Quebec",
"Cottam, Ontario",
"Cottlesville, Newfoundland",
"Courcelette, Quebec",
"Courcelles, Quebec",
"Courtenay, British Columbia",
"Courtice, Ontario",
"Courtright, Ontario",
"Coutts, Alberta",
"Covehead, Prince Edward Island",
"Cow Head, Newfoundland",
"Cowan, Manitoba",
"Cowansville, Quebec",
"Cowichan Bay, British Columbia",
"Cowley, Alberta",
"Crabtree, Quebec",
"Craigmyle, Alberta",
"Craik, Saskatchewan",
"Cranberry Portage, Manitoba",
"Cranbrook, British Columbia",
"Crandall, Manitoba",
"Crapaud, Prince Edward Island",
"Crawford Bay, British Columbia",
"Crediton, Ontario",
"Creelman, Saskatchewan",
"Creemore, Ontario",
"Creighton, Saskatchewan",
"Cremona, Alberta",
"Crescent Beach, British Columbia",
"Creston, British Columbia",
"Cross Lake, Manitoba",
"Crossfield, Alberta",
"Crowsnest Pass, Alberta",
"Crysler, Ontario",
"Crystal Beach, Ontario",
"Crystal City, Manitoba",
"Cudworth, Saskatchewan",
"Cumberland, British Columbia",
"Cumberland, Ontario",
"Cumberland House, Saskatchewan",
"Cupar, Saskatchewan",
"Cupids, Newfoundland",
"Cut Knife, Saskatchewan",
"Cypress River, Manitoba",
"Czar, Alberta",
"Dalhousie, New Brunswick",
"Dalmeny, Saskatchewan",
"Daniel`s Harbour, Newfoundland",
"Danville, Quebec",
"Darlingford, Manitoba",
"Dartmouth, Nova Scotia",
"Dashwood, Ontario",
"Dauphin, Manitoba",
"Daveluyville, Quebec",
"Davidson, Saskatchewan",
"Davis Inlet, Newfoundland",
"Dawson, Yukon",
"Dawson Creek, British Columbia",
"Daysland, Alberta",
"Dease Lake, British Columbia",
"Deauville, Quebec",
"Debden, Saskatchewan",
"Debec, New Brunswick",
"Debert, Nova Scotia",
"DeBolt, Alberta",
"Deep River, Ontario",
"Deer Lake, Newfoundland",
"Deer Lake, Ontario",
"Deerbrook, Ontario",
"Degelis, Quebec",
"Delaware of the Thames(Moravia, Ontario",
"Delburne, Alberta",
"Delhi, Ontario",
"Delia, Alberta",
"Delisle, Quebec",
"Delisle, Saskatchewan",
"Deloraine, Manitoba",
"Delson, Quebec",
"Delta, British Columbia",
"Delta, Ontario",
"Denbigh, Ontario",
"Denzil, Saskatchewan",
"Derwent, Alberta",
"Desbarats, Ontario",
"Desbiens, Quebec",
"Deschaillons-sur-Saint-Laurent, Quebec",
"Deseronto, Ontario",
"Destruction Bay, Yukon",
"Deux-Montagnes, Quebec",
"Deux-Rivieres, Ontario",
"Devlin, Ontario",
"Devon, Alberta",
"Dewberry, Alberta",
"Didsbury, Alberta",
"Dieppe, New Brunswick",
"Digby, Nova Scotia",
"Dillon, Saskatchewan",
"Dingwall, Nova Scotia",
"Dinsmore, Saskatchewan",
"Disraeli, Quebec",
"Dixonville, Alberta",
"Doaktown, New Brunswick",
"Dodsland, Saskatchewan",
"Dokis, Ontario",
"Dokis First Nation, Ontario",
"Dolbeau-Mistassini, Quebec",
"Dollard-des-Ormeaux, Quebec",
"Dominion City, Manitoba",
"Domremy, Saskatchewan",
"Donald, British Columbia",
"Donalda, Alberta",
"Donnacona, Quebec",
"Donnelly, Alberta",
"Dorchester, New Brunswick",
"Dorchester, Ontario",
"Dorion, Ontario",
"Dorset, Ontario",
"Dorval, Quebec",
"Douglas, Ontario",
"Douglas Lake, British Columbia",
"Douglastown, Ontario",
"Dover, Newfoundland",
"Drake, Saskatchewan",
"Drayton, Ontario",
"Drayton Valley, Alberta",
"Dresden, Ontario",
"Drumbo, Ontario",
"Drumheller, Alberta",
"Drummondville, Quebec",
"Dryden, Ontario",
"Dublin, Ontario",
"Dubreuilville, Ontario",
"Dubuc, Saskatchewan",
"Dubuisson, Quebec",
"Duchess, Alberta",
"Duck Lake, Saskatchewan",
"Dugald, Manitoba",
"Duncan, British Columbia",
"Dunchurch, Ontario",
"Dundalk, Ontario",
"Dundas, Ontario",
"Dundee, Nova Scotia",
"Dundurn, Saskatchewan",
"Dungannon, Ontario",
"Dunham, Quebec",
"Dunnville, Ontario",
"Dunsford, Ontario",
"Dunster, British Columbia",
"Duparquet, Quebec",
"Dupuy, Quebec",
"Durham, Ontario",
"Dutton, Ontario",
"Duvernay, Quebec",
"Dwight, Ontario",
"Dyer`s Bay, Ontario",
"Dysart, Saskatchewan",
"D`Arcy, British Columbia",
"Eagle Lake First Nation, Ontario",
"Eagle River, Ontario",
"Eaglesham, Alberta",
"Ear Falls, Ontario",
"Earl Grey, Saskatchewan",
"Earlton, Ontario",
"East Angus, Quebec",
"East Bay, Nova Scotia",
"East Broughton, Quebec",
"East Coulee, Alberta",
"East Farnham, Quebec",
"East Gwillimbury, Ontario",
"East Hereford, Quebec",
"East Pine, British Columbia",
"East Point, Prince Edward Island",
"East York, Ontario",
"Eastend, Saskatchewan",
"Easterville, Manitoba",
"Eastmain, Quebec",
"Eastman, Quebec",
"Eastport, Newfoundland",
"Eastwood, Ontario",
"Eatonia, Saskatchewan",
"Echo Bay, Ontario",
"Eckville, Alberta",
"Ecum Secum, Nova Scotia",
"Edam, Saskatchewan",
"Eddystone, Manitoba",
"Edgerton, Alberta",
"Edmonton, Alberta",
"Edmundston, New Brunswick",
"Edson, Alberta",
"Edwin, Manitoba",
"Edzo, Northwest Territories",
"Eganville, Ontario",
"Elbow, Saskatchewan",
"Eldon, Prince Edward Island",
"Elfros, Saskatchewan",
"Elgin, Manitoba",
"Elgin, Ontario",
"Elie, Manitoba",
"Elizabethtown, Ontario",
"Elk Lake, Ontario",
"Elk Point, Alberta",
"Elkford, British Columbia",
"Elkhorn, Manitoba",
"Elko, British Columbia",
"Elkwater, Alberta",
"Elliot Lake, Ontario",
"Elliston, Newfoundland",
"Elm Creek, Manitoba",
"Elmira, Ontario",
"Elmsdale, Nova Scotia",
"Elmvale, Ontario",
"Elnora, Alberta",
"Elora, Ontario",
"Elrose, Saskatchewan",
"Embree, Newfoundland",
"Embro, Ontario",
"Embrun, Ontario",
"Emerson, Manitoba",
"Emeryville, Ontario",
"Emo, Ontario",
"Empress, Alberta",
"Emsdale, Ontario",
"Enchant, Alberta",
"Enderby, British Columbia",
"Englee, Newfoundland",
"Englehart, Ontario",
"English Harbour East, Newfoundland",
"Enterprise, Northwest Territories",
"Enterprise, Ontario",
"Entrelacs, Quebec",
"Erickson, Manitoba",
"Eriksdale, Manitoba",
"Erin, Ontario",
"Eskasoni, Nova Scotia",
"Espanola, Ontario",
"Essex, Ontario",
"Estaire, Ontario",
"Esterel, Quebec",
"Esterhazy, Saskatchewan",
"Estevan, Saskatchewan",
"Estevan Point, British Columbia",
"Eston, Saskatchewan",
"Ethelbert, Manitoba",
"Etobicoke, Ontario",
"Etzikom, Alberta",
"Eugenia, Ontario",
"Evain, Quebec",
"Evansburg, Alberta",
"Exeter, Ontario",
"Exshaw, Alberta",
"Eyebrow, Saskatchewan",
"Fabre, Quebec",
"Fabreville, Quebec",
"Fair Haven, Newfoundland",
"Fairmont Hot Springs, British Columbia",
"Fairview, Alberta",
"Falardeau, Quebec",
"Falcon Lake, Manitoba",
"Falher, Alberta",
"Falkland, British Columbia",
"Farnham, Quebec",
"Faro, Yukon",
"Fassett, Quebec",
"Fauquier, British Columbia",
"Fauquier, Ontario",
"Faust, Alberta",
"Fenelon Falls, Ontario",
"Fenwick, Ontario",
"Fergus, Ontario",
"Ferintosh, Alberta",
"Ferland, Quebec",
"Ferme-Neuve, Quebec",
"Fermeuse, Newfoundland",
"Fermont, Quebec",
"Fernie, British Columbia",
"Feversham, Ontario",
"Field, British Columbia",
"Field, Ontario",
"Fillmore, Saskatchewan",
"Finch, Ontario",
"Fingal, Ontario",
"Fisher Branch, Manitoba",
"Fisher River, Manitoba",
"Fisherville, Ontario",
"Flamborough, Ontario",
"Flanders, Ontario",
"Flatbush, Alberta",
"Flatrock, British Columbia",
"Flatrock, Newfoundland",
"Fleming, Saskatchewan",
"Flesherton, Ontario",
"Fleur de Lys, Newfoundland",
"Fleurimont, Quebec",
"Flin Flon, Manitoba",
"Florenceville, New Brunswick",
"Flower`s Cove, Newfoundland",
"Foam Lake, Saskatchewan",
"Fogo, Newfoundland",
"Foley, Ontario",
"Foleyet, Ontario",
"Fond-du-Lac, Saskatchewan",
"Fords Mills, New Brunswick",
"Foremost, Alberta",
"Forest, Ontario",
"Forest Grove, British Columbia",
"Forestburg, Alberta",
"Forestville, Quebec",
"Fork River, Manitoba",
"Fort Albany, Ontario",
"Fort Assiniboine, Alberta",
"Fort Chipewyan, Alberta",
"Fort Erie, Ontario",
"Fort Frances, Ontario",
"Fort Fraser, British Columbia",
"Fort Good Hope, Northwest Territories",
"Fort Hope, Ontario",
"Fort Liard, Northwest Territories",
"Fort MacKay, Alberta",
"Fort Macleod, Alberta",
"Fort McMurray, Alberta",
"Fort McPherson, Northwest Territories",
"Fort Nelson, British Columbia",
"Fort Providence, Northwest Territories",
"Fort Qu`Appelle, Saskatchewan",
"Fort Saskatchewan, Alberta",
"Fort Severn, Ontario",
"Fort Severn First Nation, Ontario",
"Fort Simpson, Northwest Territories",
"Fort Smith, Northwest Territories",
"Fort St. James, British Columbia",
"Fort St. John, British Columbia",
"Fort Vermilion, Alberta",
"Fort William First Nation, Ontario",
"Fort-Coulonge, Quebec",
"Forteau, Newfoundland",
"Fortierville, Quebec",
"Fortune, Newfoundland",
"Fossambault-sur-le-Lac, Quebec",
"Fox Cove-Mortier, Newfoundland",
"Fox Creek, Alberta",
"Fox Lake, Alberta",
"Fox Valley, Saskatchewan",
"Foxboro, Ontario",
"Foxwarren, Manitoba",
"Foymount, Ontario",
"Frampton, Quebec",
"Francis, Saskatchewan",
"Frankford, Ontario",
"Franklin Centre, Quebec",
"Fraser Lake, British Columbia",
"Fredericton, New Brunswick",
"Fredericton Junction, New Brunswick",
"Freelton, Ontario",
"Freeport, Nova Scotia",
"Frelighsburg, Quebec",
"French River First Nation, Ontario",
"French Village, Nova Scotia",
"Frenchmans Island, Newfoundland",
"Freshwater, Newfoundland",
"Frobisher, Saskatchewan",
"Frontier, Saskatchewan",
"Fruitvale, British Columbia",
"Fugereville, Quebec",
"Gabarus, Nova Scotia",
"Gabriola, British Columbia",
"Gadsby, Alberta",
"Gagetown, New Brunswick",
"Gainsborough, Saskatchewan",
"Galahad, Alberta",
"Galiano Island, British Columbia",
"Galt, Ontario",
"Gambo, Newfoundland",
"Gananoque, Ontario",
"Gander, Newfoundland",
"Ganges, British Columbia",
"Garden Hill, Ontario",
"Garden River First Nation, Ontario",
"Garnish, Newfoundland",
"Garson, Ontario",
"Gaspe, Quebec",
"Gatineau, Quebec",
"Gaultois, Newfoundland",
"Gentilly, Quebec",
"Georgetown, Ontario",
"Georgetown, Prince Edward Island",
"Georgina, Ontario",
"Geraldton, Ontario",
"Gibbons, Alberta",
"Gibsons, British Columbia",
"Gift Lake, Alberta",
"Gilbert Plains, Manitoba",
"Gillam, Manitoba",
"Gilmour, Ontario",
"Gimli, Manitoba",
"Girardville, Quebec",
"Girouxville, Alberta",
"Giscome, British Columbia",
"Gjoa Haven, Nunavut",
"Glace Bay, Nova Scotia",
"Gladstone, Manitoba",
"Glaslyn, Saskatchewan",
"Glassville, New Brunswick",
"Gleichen, Alberta",
"Glen Ewen, Saskatchewan",
"Glen Robertson, Ontario",
"Glen Water, Ontario",
"Glen Williams, Ontario",
"Glenavon, Saskatchewan",
"Glenboro, Manitoba",
"Glencoe, Ontario",
"Glendon, Alberta",
"Glenella, Manitoba",
"Glenwood, Alberta",
"Glenwood, Newfoundland",
"Gloucester, Ontario",
"Glovertown, Newfoundland",
"Godbout, Quebec",
"Goderich, Ontario",
"Gods Lake Narrows, Manitoba",
"Gogama, Ontario",
"Gold Bridge, British Columbia",
"Gold River, British Columbia",
"Goldboro, Nova Scotia",
"Golden, British Columbia",
"Golden Lake, Ontario",
"Good Hope Lake, British Columbia",
"Gooderham, Ontario",
"Goodeve, Saskatchewan",
"Goodsoil, Saskatchewan",
"Goose Bay, Newfoundland",
"Gore Bay, Ontario",
"Gormley, Ontario",
"Gorrie, Ontario",
"Goshen, Nova Scotia",
"Goulais River, Ontario",
"Govan, Saskatchewan",
"Gowganda, Ontario",
"Gracefield, Quebec",
"Grafton, Ontario",
"Granby, Quebec",
"Grand Bank, Newfoundland",
"Grand Bay, New Brunswick",
"Grand Beach, Manitoba",
"Grand Bend, Ontario",
"Grand Centre, Alberta",
"Grand Etang, Nova Scotia",
"Grand Falls, New Brunswick",
"Grand Falls, Newfoundland",
"Grand Falls-Windsor, Newfoundland",
"Grand Forks, British Columbia",
"Grand Lake, Nova Scotia",
"Grand Manan, New Brunswick",
"Grand Narrows, Nova Scotia",
"Grand Rapids, Manitoba",
"Grand Valley, Ontario",
"Grand-Mere, Quebec",
"Grand-Remous, Quebec",
"Grand-Sault, New Brunswick",
"Grande Cache, Alberta",
"Grande Prairie, Alberta",
"Grande-Anse, New Brunswick",
"Grande-Entree, Quebec",
"Grande-Riviere, Quebec",
"Grande-Vallee, Quebec",
"Grandes-Bergeronnes, Quebec",
"Grandes-Piles, Quebec",
"Grandview, Manitoba",
"Granisle, British Columbia",
"Granton, Ontario",
"Granum, Alberta",
"Grasmere, British Columbia",
"Grassland, Alberta",
"Grassy Lake, Alberta",
"Grassy Narrows, Ontario",
"Grassy Narrows First Nation, Ontario",
"Grassy Plains, British Columbia",
"Gravelbourg, Saskatchewan",
"Gravenhurst, Ontario",
"Grayson, Saskatchewan",
"Great Harbour Deep, Newfoundland",
"Great Village, Nova Scotia",
"Green Island Cove, Newfoundland",
"Green Lake, Saskatchewan",
"Greenfield Park, Quebec",
"Greenspond, Newfoundland",
"Greensville, Ontario",
"Greenville, British Columbia",
"Greenwood, British Columbia",
"Greenwood, Nova Scotia",
"Grenfell, Saskatchewan",
"Grenville, Quebec",
"Gretna, Manitoba",
"Grimsby, Ontario",
"Grimshaw, Alberta",
"Grouard, Alberta",
"Guelph, Ontario",
"Guigues, Quebec",
"Gull Bay, Ontario",
"Gull Bay First Nation, Ontario",
"Gull Lake, Saskatchewan",
"Guysborough, Nova Scotia",
"Gypsumville, Manitoba",
"Hadashville, Manitoba",
"Hafford, Saskatchewan",
"Hagersville, Ontario",
"Hague, Saskatchewan",
"Haileybury, Ontario",
"Haines Junction, Yukon",
"Hairy Hill, Alberta",
"Haldimand, Ontario",
"Haliburton, Ontario",
"Halifax, Nova Scotia",
"Halkirk, Alberta",
"Halton Hills, Ontario",
"Ham-Nord, Quebec",
"Hamilton, Ontario",
"Hamiota, Manitoba",
"Hammond, Quebec",
"Hampden, Newfoundland",
"Hampstead, New Brunswick",
"Hampstead, Quebec",
"Hampton, New Brunswick",
"Hampton, Ontario",
"Hanley, Saskatchewan",
"Hanmer, Ontario",
"Hanna, Alberta",
"Hanover, Ontario",
"Hantsport, Nova Scotia",
"Hant`s Harbour, Newfoundland",
"Happy Valley-Goose Bay, Newfoundland",
"Harbour Breton, Newfoundland",
"Harbour Grace, Newfoundland",
"Harbour Main-Chapel Cove-Lakev, Newfoundland",
"Hardisty, Alberta",
"Hare Bay, Newfoundland",
"Harewood, New Brunswick",
"Harrietsville, Ontario",
"Harrington Harbour, Quebec",
"Harris, Saskatchewan",
"Harriston, Ontario",
"Harrow, Ontario",
"Harrowsmith, Ontario",
"Hartland, New Brunswick",
"Hartley Bay, British Columbia",
"Hartney, Manitoba",
"Hastings, Ontario",
"Havelock, New Brunswick",
"Havelock, Ontario",
"Havre-Aubert, Quebec",
"Havre-aux-Maisons, Quebec",
"Havre-St-Pierre, Quebec",
"Hawarden, Saskatchewan",
"Hawk Junction, Ontario",
"Hawkesbury, Ontario",
"Hawke`s Bay, Newfoundland",
"Hay Lakes, Alberta",
"Hay River, Northwest Territories",
"Hays, Alberta",
"Hazelton, British Columbia",
"Hazlet, Saskatchewan",
"Hearst, Ontario",
"Heart`s Content, Newfoundland",
"Heart`s Delight-Islington, Newfoundland",
"Heart`s Desire, Newfoundland",
"Heatherton, Nova Scotia",
"Hebertville, Quebec",
"Hebertville-Station, Quebec",
"Hecla, Manitoba",
"Hedley, British Columbia",
"Heinsburg, Alberta",
"Heisler, Alberta",
"Hemlo, Ontario",
"Hemlock Valley, British Columbia",
"Hemmingford, Quebec",
"Hendrix Lake, British Columbia",
"Henryville, Quebec",
"Hensall, Ontario",
"Henvey Inlet First Nation, Ontario",
"Hepburn, Saskatchewan",
"Hepworth, Ontario",
"Herbert, Saskatchewan",
"Herschel, Saskatchewan",
"Hespeler, Ontario",
"Hickman`s Harbour, Newfoundland",
"Hickson, Ontario",
"High Level, Alberta",
"High Prairie, Alberta",
"High River, Alberta",
"Highgate, Ontario",
"Hilda, Alberta",
"Hillgrade, Newfoundland",
"Hillsborough, New Brunswick",
"Hillsburgh, Ontario",
"Hillview, Newfoundland",
"Hines Creek, Alberta",
"Hinton, Alberta",
"Hixon, British Columbia",
"Hobbema, Alberta",
"Hodgeville, Saskatchewan",
"Holberg, British Columbia",
"Holden, Alberta",
"Holdfast, Saskatchewan",
"Holland, Manitoba",
"Holland Landing, Ontario",
"Holstein, Ontario",
"Holyrood, Newfoundland",
"Honey Harbour, Ontario",
"Hope, British Columbia",
"Hopedale, Newfoundland",
"Hopewell, Nova Scotia",
"Hornepayne, Ontario",
"Horsefly, British Columbia",
"Houston, British Columbia",
"Howick, Quebec",
"Howley, Newfoundland",
"Hoyt, New Brunswick",
"Hubbards, Nova Scotia",
"Hudson, Ontario",
"Hudson, Quebec",
"Hudson Bay, Saskatchewan",
"Hudson`s Hope, British Columbia",
"Hughenden, Alberta",
"Hull, Quebec",
"Humber Arm South, Newfoundland",
"Humboldt, Saskatchewan",
"Humphrey, Ontario",
"Hunter River, Prince Edward Island",
"Huntingdon, Quebec",
"Huntsville, Ontario",
"Hussar, Alberta",
"Hythe, Alberta",
"Iberville, Quebec",
"Ignace, Ontario",
"Ilderton, Ontario",
"Ile-a-la-Crosse, Saskatchewan",
"Ile-aux-Coudres, Quebec",
"Iles-de-la-Madeleine, Quebec",
"Ilford, Manitoba",
"Imperial, Saskatchewan",
"Indian Head, Saskatchewan",
"Indian Tickle, Newfoundland",
"Ingersoll, Ontario",
"Ingleside, Ontario",
"Ingonish, Nova Scotia",
"Innerkip, Ontario",
"Innisfail, Alberta",
"Innisfil, Ontario",
"Innisfree, Alberta",
"Inukjuak, Quebec",
"Inuvik, Northwest Territories",
"Inverary, Ontario",
"Invermay, Saskatchewan",
"Invermere, British Columbia",
"Inverness, Nova Scotia",
"Inverness, Quebec",
"Inwood, Manitoba",
"Inwood, Ontario",
"Iqaluit, Nunavut",
"Irma, Alberta",
"Iron Bridge, Ontario",
"Iron Springs, Alberta",
"Iroquois, Ontario",
"Iroquois Falls, Ontario",
"Irricana, Alberta",
"Irvine, Alberta",
"Iskut, British Columbia",
"Island Harbour, Newfoundland",
"Island Lake, Manitoba",
"Islay, Alberta",
"Isle aux Morts, Newfoundland",
"Ituna, Saskatchewan",
"Jackson`s Arm, Newfoundland",
"Jacquet River, New Brunswick",
"Jaffray, British Columbia",
"Jaffray Melick, Ontario",
"Jamestown, Newfoundland",
"Jansen, Saskatchewan",
"Jarvie, Alberta",
"Jarvis, Ontario",
"Jasper, Alberta",
"Jasper, Ontario",
"Jean Marie River, Northwest Territories",
"Jellicoe, Ontario",
"Jenner, Alberta",
"Jockvale, Ontario",
"Joe Batt`s Arm-Barr`d Islands-, Newfoundland",
"Johnstown, Ontario",
"Joliette, Quebec",
"Jonquiere, Quebec",
"Jordan, Ontario",
"Joussard, Alberta",
"Joutel, Quebec",
"Kakisa, Northwest Territories",
"Kaministiquia, Ontario",
"Kamiskotia, Ontario",
"Kamloops, British Columbia",
"Kamsack, Saskatchewan",
"Kananaskis, Alberta",
"Kanata, Ontario",
"Kangiqsualujjuaq, Quebec",
"Kangirsuk, Quebec",
"Kapuskasing, Ontario",
"Kasabonika First Nation, Ontario",
"Kashechewan First Nation, Ontario",
"Kaslo, British Columbia",
"Kateville, Quebec",
"Kazabazua, Quebec",
"Kearney, Ontario",
"Kedgwick, New Brunswick",
"Keene, Ontario",
"Keephills, Alberta",
"Keewatin, Ontario",
"Keg River, Alberta",
"Kelliher, Saskatchewan",
"Kelowna, British Columbia",
"Kelvington, Saskatchewan",
"Kelwood, Manitoba",
"Kemano, British Columbia",
"Kemptville, Ontario",
"Kenaston, Saskatchewan",
"Kennedy, Saskatchewan",
"Kennetcook, Nova Scotia",
"Kenora, Ontario",
"Kenosee, Saskatchewan",
"Kensington, Prince Edward Island",
"Kent Centre, Ontario",
"Kenton, Manitoba",
"Kentville, Nova Scotia",
"Kenzieville, Nova Scotia",
"Keremeos, British Columbia",
"Kerrobert, Saskatchewan",
"Kerwood, Ontario",
"Keswick, New Brunswick",
"Keswick, Ontario",
"Ketch Harbour, Nova Scotia",
"Key Lake, Saskatchewan",
"Killaloe, Ontario",
"Killam, Alberta",
"Killarney, Manitoba",
"Killarney, Ontario",
"Kimberley, British Columbia",
"Kincaid, Saskatchewan",
"Kincardine, Ontario",
"Kincolith, British Columbia",
"Kindersley, Saskatchewan",
"King City, Ontario",
"Kingfisher Lake, Ontario",
"Kingfisher Lake First Nation, Ontario",
"Kingsbury, Quebec",
"Kingsey Falls, Quebec",
"Kingston, Nova Scotia",
"Kingston, Ontario",
"Kingsville, Ontario",
"King`s Cove, Newfoundland",
"King`s Point, Newfoundland",
"Kinistino, Saskatchewan",
"Kinmount, Ontario",
"Kintore, Ontario",
"Kinuso, Alberta",
"Kipling, Saskatchewan",
"Kippens, Newfoundland",
"Kirkfield, Ontario",
"Kirkland, Quebec",
"Kirkland Lake, Ontario",
"Kirkton, Ontario",
"Kisbey, Saskatchewan",
"Kitchener, Ontario",
"Kitimat, British Columbia",
"Kitkatla, British Columbia",
"Kitsault, British Columbia",
"Kitscoty, Alberta",
"Kitwanga, British Columbia",
"Kleinburg, Ontario",
"Klemtu, British Columbia",
"Knowlton, Quebec",
"Kugluktuk, Northwest Territories",
"Kuujjuaq, Quebec",
"Kyle, Saskatchewan",
"Kyuquot, British Columbia",
"La Baie, Quebec",
"La Broquerie, Manitoba",
"La Corne, Quebec",
"La Crete, Alberta",
"La Dore, Quebec",
"La Grande, Quebec",
"La Guadeloupe, Quebec",
"La Loche, Saskatchewan",
"La Malbaie, Quebec",
"La Martre, Quebec",
"La Minerve, Quebec",
"La Patrie, Quebec",
"La Plaine, Quebec",
"La Pocatiere, Quebec",
"La Prairie, Quebec",
"La Reine, Quebec",
"La Romaine, Quebec",
"La Ronge, Saskatchewan",
"La Sarre, Quebec",
"La Scie, Newfoundland",
"La Tuque, Quebec",
"Labelle, Quebec",
"Labrador City, Newfoundland",
"Lac Brochet, Manitoba",
"Lac du Bonnet, Manitoba",
"Lac Kenogami, Quebec",
"Lac La Biche, Alberta",
"Lac la Croix, Ontario",
"Lac la Hache, British Columbia",
"Lac Seul First Nation, Ontario",
"Lac-au-Saumon, Quebec",
"Lac-aux-Sables, Quebec",
"Lac-Bouchette, Quebec",
"Lac-Brome, Quebec",
"Lac-Delage, Quebec",
"Lac-des-Ecorces, Quebec",
"Lac-Drolet, Quebec",
"Lac-du-Cerf, Quebec",
"Lac-Edouard, Quebec",
"Lac-Etchemin, Quebec",
"Lac-Frontiere, Quebec",
"Lac-Poulin, Quebec",
"Lac-Saguay, Quebec",
"Lac-Sergent, Quebec",
"Lac-St-Joseph, Quebec",
"Lachenaie, Quebec",
"Lachine, Quebec",
"Lachute, Quebec",
"Lacolle, Quebec",
"Lacombe, Alberta",
"Ladle Cove, Newfoundland",
"Ladysmith, British Columbia",
"Lafleche, Saskatchewan",
"Lafontaine, Ontario",
"Lafontaine, Quebec",
"Lagoon City, Ontario",
"LaHave, Nova Scotia",
"Laird, Saskatchewan",
"Lake Alma, Saskatchewan",
"Lake Charlotte, Nova Scotia",
"Lake Cowichan, British Columbia",
"Lake Lenore, Saskatchewan",
"Lake Louise, Alberta",
"Lake Megantic, Quebec",
"Lakefield, Ontario",
"Lamaline, Newfoundland",
"Lambeth, Ontario",
"Lambton, Quebec",
"Lameque, New Brunswick",
"Lamont, Alberta",
"Lampman, Saskatchewan",
"Lanark, Ontario",
"Lancaster, Ontario",
"Landis, Saskatchewan",
"Lang, Saskatchewan",
"Langara, British Columbia",
"Langdon, Alberta",
"Langenburg, Saskatchewan",
"Langham, Saskatchewan",
"Langley, British Columbia",
"Langruth, Manitoba",
"Langton, Ontario",
"Lanigan, Saskatchewan",
"Lanoraie, Quebec",
"Lansdowne, Ontario",
"Lansdowne House, Ontario",
"Lantzville, British Columbia",
"Larder Lake, Ontario",
"Lark Harbour, Newfoundland",
"Larrys River, Nova Scotia",
"LaSalle, Ontario",
"LaSalle, Quebec",
"Lashburn, Saskatchewan",
"Latchford, Ontario",
"Laterriere, Quebec",
"Latulipe, Quebec",
"Laurentides, Quebec",
"Laurier-Station, Quebec",
"Laurierville, Quebec",
"Laval, Quebec",
"Laval des Rapides, Quebec",
"Laval Ouest, Quebec",
"Lavaltrie, Quebec",
"Laverlochere, Quebec",
"Lavoy, Alberta",
"Lawn, Newfoundland",
"Lawrencetown, Nova Scotia",
"Lawrenceville, Quebec",
"Le Bic, Quebec",
"Le Gardeur, Quebec",
"Leader, Saskatchewan",
"Leaf Rapids, Manitoba",
"Leamington, Ontario",
"Leask, Saskatchewan",
"Lebel-sur-Quevillon, Quebec",
"Leclercville, Quebec",
"Leduc, Alberta",
"Lefroy, Ontario",
"Legal, Alberta",
"Lemberg, Saskatchewan",
"LeMoyne, Quebec",
"Lennoxville, Quebec",
"Leoville, Saskatchewan",
"Leroy, Saskatchewan",
"Lery, Quebec",
"Les Boules, Quebec",
"Les Cedres, Quebec",
"Les Coteaux, Quebec",
"Les Eboulements, Quebec",
"Les Escoumins, Quebec",
"Les Mechins, Quebec",
"Leslieville, Alberta",
"Lestock, Saskatchewan",
"Lethbridge, Alberta",
"Levack, Ontario",
"Levis, Quebec",
"Lewisporte, Newfoundland",
"Libau, Manitoba",
"Liberty, Saskatchewan",
"Likely, British Columbia",
"Lillooet, British Columbia",
"Limerick, Saskatchewan",
"Lincoln, Ontario",
"Lindsay, Ontario",
"Lintlaw, Saskatchewan",
"Linwood, Ontario",
"Lion`s Head, Ontario",
"Lipton, Saskatchewan",
"Listowel, Ontario",
"Little Bay, Newfoundland",
"Little Bay Islands, Newfoundland",
"Little Britain, Ontario",
"Little Burnt Bay, Newfoundland",
"Little Catalina, Newfoundland",
"Little Current, Ontario",
"Little Fort, British Columbia",
"Little Grand Rapids, Manitoba",
"Little Heart`s Ease, Newfoundland",
"Lively, Ontario",
"Liverpool, Nova Scotia",
"Lloydminster, Alberta",
"Lloydminster, Saskatchewan",
"Lockeport, Nova Scotia",
"Lockport, Manitoba",
"Lodgepole, Alberta",
"Logan Lake, British Columbia",
"Logy Bay-Middle Cove-Outer Cov, Newfoundland",
"Lombardy, Ontario",
"Lomond, Alberta",
"London, Ontario",
"Long Harbour-Mount Arlington H, Newfoundland",
"Long Lac, Ontario",
"Long Lake First Nation, Ontario",
"Long Point, Ontario",
"Long Pond, Newfoundland",
"Long Sault, Ontario",
"Longlac, Ontario",
"Longueuil, Quebec",
"Longview, Alberta",
"Loon Lake, Saskatchewan",
"Loos, British Columbia",
"Loreburn, Saskatchewan",
"Loretteville, Quebec",
"Lorne, Ontario",
"Lorraine, Quebec",
"Lorrainville, Quebec",
"Lougheed, Alberta",
"Louisbourg, Nova Scotia",
"Louisdale, Nova Scotia",
"Louiseville, Quebec",
"Lourdes, Newfoundland",
"Lourdes de Blanc Sablon, Quebec",
"Louvicourt, Quebec",
"Low, Quebec",
"Lower Island Cove, Newfoundland",
"Lower Post, British Columbia",
"Lucan, Ontario",
"Luceville, Quebec",
"Lucknow, Ontario",
"Lucky Lake, Saskatchewan",
"Lumby, British Columbia",
"Lumsden, Newfoundland",
"Lumsden, Saskatchewan",
"Lundar, Manitoba",
"Lunenburg, Nova Scotia",
"Luseland, Saskatchewan",
"Luskville, Quebec",
"Lyn, Ontario",
"Lynden, Ontario",
"Lynn Lake, Manitoba",
"Lyster, Quebec",
"Lytton, British Columbia",
"L`Acadie, Quebec",
"L`Ancienne-Lorette, Quebec",
"L`Ange-Gardien, Quebec",
"L`Annonciation, Quebec",
"L`Anse-au-Loup, Newfoundland",
"L`Ardoise, Nova Scotia",
"L`Assomption, Quebec",
"L`Avenir, Quebec",
"L`Epiphanie, Quebec",
"L`Ile-Aux-Noix, Quebec",
"L`Ile-Bizard, Quebec",
"L`Ile-Cadieux, Quebec",
"L`Ile-Dorval, Quebec",
"L`Ile-d`Entree, Quebec",
"L`Ile-Perrot, Quebec",
"L`Île-Verte, Quebec",
"L`Islet, Quebec",
"L`Orignal, Ontario",
"Ma-Me-O Beach, Alberta",
"Maberly, Ontario",
"Mabou, Nova Scotia",
"Macamic, Quebec",
"Maccan, Nova Scotia",
"Macdiarmid, Ontario",
"Maces Bay, New Brunswick",
"MacGregor, Manitoba",
"Mackenzie, British Columbia",
"Macklin, Saskatchewan",
"Macrorie, Saskatchewan",
"MacTier, Ontario",
"Madoc, Ontario",
"Madsen, Ontario",
"Mafeking, Manitoba",
"Magnetawan, Ontario",
"Magnetawan First Nation, Ontario",
"Magog, Quebec",
"Magrath, Alberta",
"Mahone Bay, Nova Scotia",
"Maidstone, Ontario",
"Maidstone, Saskatchewan",
"Main Brook, Newfoundland",
"Maitland, Nova Scotia",
"Maitland, Ontario",
"Makkovik, Newfoundland",
"Malartic, Quebec",
"Mallorytown, Ontario",
"Malton, Ontario",
"Manic-Cinq, Quebec",
"Manigotagan, Manitoba",
"Manitou, Manitoba",
"Manitouwadge, Ontario",
"Manitowaning, Ontario",
"Maniwaki, Quebec",
"Mankota, Saskatchewan",
"Manning, Alberta",
"Mannville, Alberta",
"Manor, Saskatchewan",
"Manotick, Ontario",
"Manouane, Quebec",
"Manseau, Quebec",
"Mansonville, Quebec",
"Manyberries, Alberta",
"Maple, Ontario",
"Maple Creek, Saskatchewan",
"Maple Grove, Quebec",
"Maple Ridge, British Columbia",
"Marathon, Ontario",
"Marcelin, Saskatchewan",
"Margaree Forks, Nova Scotia",
"Margo, Saskatchewan",
"Maria, Quebec",
"Marieville, Quebec",
"Marion Bridge, Nova Scotia",
"Markdale, Ontario",
"Markham, Ontario",
"Markstay, Ontario",
"Marlboro, Alberta",
"Marmora, Ontario",
"Marquis, Saskatchewan",
"Marsden, Saskatchewan",
"Marsh Lake, Yukon",
"Marshall, Saskatchewan",
"Marsoui, Quebec",
"Marten Falls First Nation, Ontario",
"Marten River, Ontario",
"Martensville, Saskatchewan",
"Martintown, Ontario",
"Marwayne, Alberta",
"Maryfield, Saskatchewan",
"Marystown, Newfoundland",
"Mary`s Harbour, Newfoundland",
"Mascouche, Quebec",
"Maskinonge, Quebec",
"Masset, British Columbia",
"Massey, Ontario",
"Massey Drive, Newfoundland",
"Masson-Angers, Quebec",
"Massueville, Quebec",
"Mastigouche, Quebec",
"Matachewan, Ontario",
"Matagami, Quebec",
"Matane, Quebec",
"Matapedia, Quebec",
"Matheson, Ontario",
"Mattawa, Ontario",
"Mattice, Ontario",
"Maxville, Ontario",
"Mayerthorpe, Alberta",
"Maymont, Saskatchewan",
"Maynooth, Ontario",
"Mayo, Yukon",
"McAdam, New Brunswick",
"McAuley, Manitoba",
"McBride, British Columbia",
"McCreary, Manitoba",
"McDonalds Corners, Ontario",
"McGregor, Ontario",
"McIver`s, Newfoundland",
"McKellar, Ontario",
"McLeese Lake, British Columbia",
"McLennan, Alberta",
"McLeod Lake, British Columbia",
"Mcmasterville, Quebec",
"Meacham, Saskatchewan",
"Meadow Lake, Saskatchewan",
"Meaford, Ontario",
"Meander River, Alberta",
"Meath Park, Saskatchewan",
"Medicine Hat, Alberta",
"Meductic, New Brunswick",
"Melbourne, Ontario",
"Melbourne, Quebec",
"Melfort, Saskatchewan",
"Melita, Manitoba",
"Mellin, Quebec",
"Melocheville, Quebec",
"Melrose, Nova Scotia",
"Melville, Saskatchewan",
"Memramcook, New Brunswick",
"Meota, Saskatchewan",
"Mercier, Quebec",
"Merigomish, Nova Scotia",
"Merlin, Ontario",
"Merrickville, Ontario",
"Merritt, British Columbia",
"Metabetchouan, Quebec",
"Metcalfe, Ontario",
"Meteghan, Nova Scotia",
"Metis-sur-Mer, Quebec",
"Miami, Manitoba",
"Mica Creek, British Columbia",
"Midale, Saskatchewan",
"Middle Lake, Saskatchewan",
"Middleton, Nova Scotia",
"Midland, Ontario",
"Midway, British Columbia",
"Milden, Saskatchewan",
"Mildmay, Ontario",
"Milestone, Saskatchewan",
"Milford Bay, Ontario",
"Milk River, Alberta",
"Millbrook, Ontario",
"Millertown, Newfoundland",
"Millet, Alberta",
"Millhaven, Ontario",
"Milltown-Head of Bay D`Espoir, Newfoundland",
"Millville, New Brunswick",
"Milo, Alberta",
"Milton, Ontario",
"Milverton, Ontario",
"Minaki, Ontario",
"Minburn, Alberta",
"Mindemoya, Ontario",
"Minden, Ontario",
"Mine Centre, Ontario",
"Ming`s Bight, Newfoundland",
"Miniota, Manitoba",
"Minnedosa, Manitoba",
"Minto, Manitoba",
"Minto, New Brunswick",
"Minton, Saskatchewan",
"Mirabel, Quebec",
"Miramichi, New Brunswick",
"Mirror, Alberta",
"Miscou Island, New Brunswick",
"Missanabie, Ontario",
"Mission, British Columbia",
"Mississauga, Ontario",
"Mistassini, Quebec",
"Mistatim, Saskatchewan",
"Mitchell, Ontario",
"Mohawks Of The Bay of Quinte F, Ontario",
"Moisie, Quebec",
"Molanosa, Saskatchewan",
"Monastery, Nova Scotia",
"Moncton, New Brunswick",
"Monkstown, Newfoundland",
"Monkton, Ontario",
"Mont Bechervaise, Quebec",
"Mont St Grégoire, Quebec",
"Mont-Joli, Quebec",
"Mont-Laurier, Quebec",
"Mont-Louis, Quebec",
"Mont-Rolland, Quebec",
"Mont-Royal, Quebec",
"Mont-St-Hilaire, Quebec",
"Mont-St-Pierre, Quebec",
"Mont-Tremblant, Quebec",
"Montague, Prince Edward Island",
"Montebello, Quebec",
"Montmagny, Quebec",
"Montmartre, Saskatchewan",
"Montney, British Columbia",
"Montreal, Quebec",
"Montreal - Est, Quebec",
"Montréal - Nord, Quebec",
"Montréal - Ouest, Quebec",
"Moonbeam, Ontario",
"Moonstone, Ontario",
"Mooretown, Ontario",
"Moose Creek, Ontario",
"Moose Factory, Ontario",
"Moose Jaw, Saskatchewan",
"Moose Lake, Manitoba",
"Moosomin, Saskatchewan",
"Moosonee, Ontario",
"Morden, Manitoba",
"Morell, Prince Edward Island",
"Morin-Heights, Quebec",
"Morinville, Alberta",
"Morley, Alberta",
"Morrin, Alberta",
"Morris, Manitoba",
"Morrisburg, Ontario",
"Morse, Saskatchewan",
"Morson, Ontario",
"Mortlach, Saskatchewan",
"Mossbank, Saskatchewan",
"Mount Albert, Ontario",
"Mount Brydges, Ontario",
"Mount Carmel-Mitchells Brook-S, Newfoundland",
"Mount Forest, Ontario",
"Mount Hope, Ontario",
"Mount Moriah, Newfoundland",
"Mount Pearl, Newfoundland",
"Mount Pleasant, Ontario",
"Mount Stewart, Prince Edward Island",
"Mount Uniacke, Nova Scotia",
"Moyie, British Columbia",
"Mulgrave, Nova Scotia",
"Mulhurst, Alberta",
"Muncho Lake, British Columbia",
"Mundare, Alberta",
"Murdochville, Quebec",
"Murray River, Prince Edward Island",
"Musgrave Harbour, Newfoundland",
"Musgravetown, Newfoundland",
"Muskoka, Ontario",
"Muskoka Falls, Ontario",
"Muskrat Dam, Ontario",
"Muskrat Dam First Nation, Ontario",
"Musquodoboit Harbour, Nova Scotia",
"Mutton Bay, Quebec",
"Myrnam, Alberta",
"M`Chigeeng, Ontario",
"Nackawic, New Brunswick",
"Nahanni Butte, Northwest Territories",
"Naicam, Saskatchewan",
"Nain, Newfoundland",
"Nairn, Ontario",
"Naiscoutaing First Nation, Ontario",
"Nakina, Ontario",
"Nakusp, British Columbia",
"Namao, Alberta",
"Nampa, Alberta",
"Nanaimo, British Columbia",
"Nantes, Quebec",
"Nanticoke, Ontario",
"Nanton, Alberta",
"Napanee, Ontario",
"Napierville, Quebec",
"Naramata, British Columbia",
"Natashquan, Quebec",
"Navan, Ontario",
"Nedelec, Quebec",
"Neepawa, Manitoba",
"Neguac, New Brunswick",
"Neidpath, Saskatchewan",
"Neilburg, Saskatchewan",
"Nelson, British Columbia",
"Nelson House, Manitoba",
"Nepean, Ontario",
"Nephton, Ontario",
"Nestor Falls, Ontario",
"Neudorf, Saskatchewan",
"Neustadt, Ontario",
"Neuville, Quebec",
"Neville, Saskatchewan",
"New Aiyansh, British Columbia",
"New Carlisle, Quebec",
"New Dayton, Alberta",
"New Denmark, New Brunswick",
"New Denver, British Columbia",
"New Dundee, Ontario",
"New Germany, Nova Scotia",
"New Glasgow, Nova Scotia",
"New Glasgow, Quebec",
"New Hamburg, Ontario",
"New Harbour, Newfoundland",
"New Haven, Prince Edward Island",
"New Liskeard, Ontario",
"New London, Prince Edward Island",
"New Norway, Alberta",
"New Perlican, Newfoundland",
"New Richmond, Quebec",
"New Ross, Nova Scotia",
"New Sarepta, Alberta",
"New Tecumseth, Ontario",
"New Waterford, Nova Scotia",
"New Westminster, British Columbia",
"New-Wes-Valley, Newfoundland",
"Newbrook, Alberta",
"Newburgh, Ontario",
"Newcastle, Ontario",
"Newdale, Manitoba",
"Newmarket, Ontario",
"Newport, Quebec",
"Newtonville, Ontario",
"Niagara Falls, Ontario",
"Niagara-on-the-Lake, Ontario",
"Nickel Centre, Ontario",
"Nicolet, Quebec",
"Nimpo Lake, British Columbia",
"Nipawin, Saskatchewan",
"Nipigon, Ontario",
"Nipissing First Nation, Ontario",
"Nippers Harbour, Newfoundland",
"Nisku, Alberta",
"Niton Junction, Alberta",
"Niverville, Manitoba",
"Nobel, Ontario",
"Nobleford, Alberta",
"Nobleton, Ontario",
"Noel, Nova Scotia",
"Noelville, Ontario",
"Nokomis, Saskatchewan",
"Norbertville, Quebec",
"Nordegg, Alberta",
"Norman Wells, Northwest Territories",
"Normandin, Quebec",
"Norman`s Cove-Long Cove, Newfoundland",
"Normetal, Quebec",
"Norquay, Saskatchewan",
"Norris Arm, Newfoundland",
"North Augusta, Ontario",
"North Battleford, Saskatchewan",
"North Bay, Ontario",
"North Gower, Ontario",
"North Hatley, Quebec",
"North Portal, Saskatchewan",
"North Saanich, British Columbia",
"North Spirit Lake, Ontario",
"North Sydney, Nova Scotia",
"North Vancouver, British Columbia",
"North West River, Newfoundland",
"North York, Ontario",
"Northbrook, Ontario",
"Northern Arm, Newfoundland",
"Norton, New Brunswick",
"Norval, Ontario",
"Norway House, Manitoba",
"Norwich, Ontario",
"Norwood, Ontario",
"Notre Dame de Bonsecours, Quebec",
"Notre Dame de Lourdes, Manitoba",
"Notre Dame de Lourdes, Quebec",
"Notre Dame De L`Ile Perrot, Quebec",
"Notre Dame des Laurentides, Quebec",
"Notre Dame Des Prairies, Quebec",
"Notre Dame Du Portage, Quebec",
"Notre-Dame-de-la-Paix, Quebec",
"Notre-Dame-de-la-Salette, Quebec",
"Notre-Dame-de-Stanbridge, Quebec",
"Notre-Dame-du-Bon-Conseil, Quebec",
"Notre-Dame-du-Lac, Quebec",
"Notre-Dame-du-Laus, Quebec",
"Notre-Dame-du-Nord, Quebec",
"Nouvelle, Quebec",
"Oak Lake, Manitoba",
"Oak Ridges, Ontario",
"Oak River, Manitoba",
"Oakville, Manitoba",
"Oakville, Ontario",
"Oakwood, Ontario",
"Oba, Ontario",
"Ocean Falls, British Columbia",
"Ocean Park, British Columbia",
"Ochre River, Manitoba",
"Odessa, Ontario",
"Odessa, Saskatchewan",
"Ogema, Saskatchewan",
"Ogoki, Ontario",
"Ohsweken, Ontario",
"Oil Springs, Ontario",
"Ojibways of Hiawatha First Nat, Ontario",
"Ojibways of Walpole Island Fir, Ontario",
"Oka, Quebec",
"Okanagan Falls, British Columbia",
"Okotoks, Alberta",
"Old Crow, Yukon",
"Old Perlican, Newfoundland",
"Olds, Alberta",
"Oliver, British Columbia",
"Omemee, Ontario",
"Omerville, Quebec",
"Onaping Falls, Ontario",
"Oneida First Nation, Ontario",
"Onoway, Alberta",
"Opasatika, Ontario",
"Ophir, Ontario",
"Orangeville, Ontario",
"Orford, Quebec",
"Orillia, Ontario",
"Orleans, Ontario",
"Ormiston, Saskatchewan",
"Ormstown, Quebec",
"Oro, Ontario",
"Oromocto, New Brunswick",
"Orono, Ontario",
"Orrville, Ontario",
"Osgoode, Ontario",
"Oshawa, Ontario",
"Osler, Saskatchewan",
"Osoyoos, British Columbia",
"Ottawa, Ontario",
"Otterburn Park, Quebec",
"Otterville, Ontario",
"Outlook, Saskatchewan",
"Outremont, Quebec",
"Owen Sound, Ontario",
"Oxbow, Saskatchewan",
"Oxdrift, Ontario",
"Oxford, Nova Scotia",
"Oxford House, Manitoba",
"Oxford Mills, Ontario",
"Oyama, British Columbia",
"Oyen, Alberta",
"O`Leary, Prince Edward Island",
"Packs Harbour, Newfoundland",
"Pacquet, Newfoundland",
"Paddockwood, Saskatchewan",
"Paisley, Ontario",
"Pakenham, Ontario",
"Palgrave, Ontario",
"Palmarolle, Quebec",
"Palmer Rapids, Ontario",
"Palmerston, Ontario",
"Pangman, Saskatchewan",
"Papineauville, Quebec",
"Paquette Corner, Ontario",
"Paquetville, New Brunswick",
"Paradise, Newfoundland",
"Paradise Hill, Saskatchewan",
"Paradise River, Newfoundland",
"Paradise Valley, Alberta",
"Parent, Quebec",
"Parham, Ontario",
"Paris, Ontario",
"Parkhill, Ontario",
"Parksville, British Columbia",
"Parrsboro, Nova Scotia",
"Parry Sound, Ontario",
"Parson, British Columbia",
"Pasadena, Newfoundland",
"Pass Lake, Ontario",
"Patuanak, Saskatchewan",
"Paynton, Saskatchewan",
"Peace River, Alberta",
"Peachland, British Columbia",
"Peawanuck, Ontario",
"Peerless Lake, Alberta",
"Peers, Alberta",
"Pefferlaw, Ontario",
"Peggy`s Cove, Nova Scotia",
"Peguis, Manitoba",
"Pelee Island, Ontario",
"Pelham, Ontario",
"Pelican Narrows, Saskatchewan",
"Pelican Rapids, Manitoba",
"Pelly, Saskatchewan",
"Pelly Crossing, Yukon",
"Pemberton, British Columbia",
"Pembroke, Ontario",
"Penetanguishene, Ontario",
"Penhold, Alberta",
"Pennant, Saskatchewan",
"Pense, Saskatchewan",
"Penticton, British Columbia",
"Perce, Quebec",
"Perdue, Saskatchewan",
"Peribonka, Quebec",
"Perkins, Quebec",
"Perrault Falls, Ontario",
"Perth, Ontario",
"Perth-Andover, New Brunswick",
"Petawawa, Ontario",
"Peterborough, Ontario",
"Peterview, Newfoundland",
"Petit Rocher, New Brunswick",
"Petitcodiac, New Brunswick",
"Petite-Riviere-St-Francois, Quebec",
"Petrolia, Ontario",
"Petty Harbour-Maddox Cove, Newfoundland",
"Philipsburg, Quebec",
"Piapot, Saskatchewan",
"Pickering, Ontario",
"Pickle Lake, Ontario",
"Picton, Ontario",
"Pictou, Nova Scotia",
"Picture Butte, Alberta",
"Pierceland, Saskatchewan",
"Pierrefonds, Quebec",
"Pierreville, Quebec",
"Pikangikum First Nation, Ontario",
"Pikwitonei, Manitoba",
"Pilot Butte, Saskatchewan",
"Pilot Mound, Manitoba",
"Pinawa, Manitoba",
"Pincher Creek, Alberta",
"Pincourt, Quebec",
"Pine Dock, Manitoba",
"Pine Falls, Manitoba",
"Pine River, Manitoba",
"Pineal Lake, Ontario",
"Pinehouse, Saskatchewan",
"Piney, Manitoba",
"Pintendre, Quebec",
"Pitt Meadows, British Columbia",
"Placentia, Newfoundland",
"Plaisance, Quebec",
"Plamondon, Alberta",
"Plantagenet, Ontario",
"Plaster Rock, New Brunswick",
"Plate Cove East, Newfoundland",
"Plato, Saskatchewan",
"Plattsville, Ontario",
"Pleasant Park, Ontario",
"Plenty, Saskatchewan",
"Plessisville, Quebec",
"Plevna, Ontario",
"Plum Coulee, Manitoba",
"Plumas, Manitoba",
"Pohenegamook, Quebec",
"Point Grondine First Nation, Ontario",
"Point Leamington, Newfoundland",
"Point Pelee, Ontario",
"Pointe au Baril, Ontario",
"Pointe Aux Trembles, Quebec",
"Pointe du Bois, Manitoba",
"Pointe-a-la-Croix, Quebec",
"Pointe-au-Pere, Quebec",
"Pointe-aux-Outardes, Quebec",
"Pointe-Calumet, Quebec",
"Pointe-Claire, Quebec",
"Pointe-des-Cascades, Quebec",
"Pointe-des-Monts, Quebec",
"Pointe-Fortune, Quebec",
"Pointe-Lebel, Quebec",
"Ponoka, Alberta",
"Pont-Rouge, Quebec",
"Pont-Viau, Quebec",
"Ponteix, Saskatchewan",
"Pontiac, Quebec",
"Pool`s Cove, Newfoundland",
"Poplar River, Manitoba",
"Poplarfield, Manitoba",
"Porcupine Plain, Saskatchewan",
"Port Alberni, British Columbia",
"Port Alice, British Columbia",
"Port au Choix, Newfoundland",
"Port au Port West-Aguathuna-Fe, Newfoundland",
"Port Aux Basques, Newfoundland",
"Port Bickerton, Nova Scotia",
"Port Blandford, Newfoundland",
"Port Burwell, Ontario",
"Port Carling, Ontario",
"Port Clements, British Columbia",
"Port Colborne, Ontario",
"Port Coquitlam, British Columbia",
"Port Credit, Ontario",
"Port Cunnington, Ontario",
"Port Dover, Ontario",
"Port Dufferin, Nova Scotia",
"Port Edward, British Columbia",
"Port Elgin, New Brunswick",
"Port Elgin, Ontario",
"Port Franks, Ontario",
"Port Greville, Nova Scotia",
"Port Hardy, British Columbia",
"Port Hawkesbury, Nova Scotia",
"Port Hood, Nova Scotia",
"Port Hope, Ontario",
"Port Hope Simpson, Newfoundland",
"Port La Tour, Nova Scotia",
"Port Lambton, Ontario",
"Port Loring, Ontario",
"Port Maitland, Nova Scotia",
"Port McNeill, British Columbia",
"Port McNicoll, Ontario",
"Port Mellon, British Columbia",
"Port Moody, British Columbia",
"Port Morien, Nova Scotia",
"Port Mouton, Nova Scotia",
"Port Perry, Ontario",
"Port Renfrew, British Columbia",
"Port Rexton, Newfoundland",
"Port Robinson, Ontario",
"Port Rowan, Ontario",
"Port Saunders, Newfoundland",
"Port Stanley, Ontario",
"Port Sydney, Ontario",
"Port Union, Newfoundland",
"Port-Cartier, Quebec",
"Port-Daniel, Quebec",
"Port-Menier, Quebec",
"Portage la Prairie, Manitoba",
"Portage-du-Fort, Quebec",
"Portland, Ontario",
"Portneuf, Quebec",
"Portugal Cove-St. Philip`s, Newfoundland",
"Poste-de-la-Baleine, Quebec",
"Postville, Newfoundland",
"Pouce Coupe, British Columbia",
"Pouch Cove, Newfoundland",
"Powassan, Ontario",
"Powell River, British Columbia",
"Preeceville, Saskatchewan",
"Prelate, Saskatchewan",
"Prescott, Ontario",
"Prespatou, British Columbia",
"Preston, Ontario",
"Prevost, Quebec",
"Price, Quebec",
"Prince Albert, Saskatchewan",
"Prince George, British Columbia",
"Prince Rupert, British Columbia",
"Princeton, British Columbia",
"Princeton, Newfoundland",
"Princeton, Ontario",
"Princeville, Quebec",
"Prophet River, British Columbia",
"Provost, Alberta",
"Prud`homme, Saskatchewan",
"Pubnico, Nova Scotia",
"Puce, Ontario",
"Pugwash, Nova Scotia",
"Punnichy, Saskatchewan",
"Puvirnituq, Quebec",
"Quadra Island, British Columbia",
"Qualicum Beach, British Columbia",
"Quebec, Quebec",
"Queen Charlotte, British Columbia",
"Queensport, Nova Scotia",
"Queenston, Ontario",
"Queensville, Ontario",
"Quesnel, British Columbia",
"Quill Lake, Saskatchewan",
"Quispamsis, New Brunswick",
"Quyon, Quebec",
"Qu`Appelle, Saskatchewan",
"Rabbit Lake, Saskatchewan",
"Radisson, Quebec",
"Radisson, Saskatchewan",
"Radium Hot Springs, British Columbia",
"Radville, Saskatchewan",
"Radway, Alberta",
"Rae, Northwest Territories",
"Rae Lakes, Northwest Territories",
"Rainbow Lake, Alberta",
"Rainy Lake First Nation, Ontario",
"Rainy River, Ontario",
"Raith, Ontario",
"Raleigh, Newfoundland",
"Ralston, Alberta",
"Ramea, Newfoundland",
"Ramore, Ontario",
"Rankin Inlet, Nunavut",
"Rapid City, Manitoba",
"Rathwell, Manitoba",
"Rawdon, Quebec",
"Raymond, Alberta",
"Raymore, Saskatchewan",
"Rayside-Balfour, Ontario",
"Red Bank, New Brunswick",
"Red Bay, Newfoundland",
"Red Deer, Alberta",
"Red Lake, Ontario",
"Red Rock, British Columbia",
"Red Rock, Ontario",
"Red Sucker Lake, Manitoba",
"Redbridge, Ontario",
"Redcliff, Alberta",
"Redditt, Ontario",
"Redvers, Saskatchewan",
"Redwater, Alberta",
"Reefs Harbour, Newfoundland",
"Regina, Saskatchewan",
"Regina Beach, Saskatchewan",
"Remigny, Quebec",
"Rencontre East, Newfoundland",
"Renfrew, Ontario",
"Rennie, Manitoba",
"Repentigny, Quebec",
"Réserve faunique de Rimouski, Quebec",
"Réserve faunique la Vérendrye, Quebec",
"Réserves fauniques de Matane e, Quebec",
"Resolute, Nunavut",
"Reston, Manitoba",
"Restoule, Ontario",
"Revelstoke, British Columbia",
"Rhein, Saskatchewan",
"Riceton, Saskatchewan",
"Richelieu, Quebec",
"Richibucto, New Brunswick",
"Richmond, British Columbia",
"Richmond, Ontario",
"Richmond, Quebec",
"Richmond Hill, Ontario",
"Richmound, Saskatchewan",
"Ridgedale, Saskatchewan",
"Ridgetown, Ontario",
"Ridgeway, Ontario",
"Rigaud, Quebec",
"Rigolet, Newfoundland",
"Rimbey, Alberta",
"Rimouski, Quebec",
"Rimouski-Est, Quebec",
"Riondel, British Columbia",
"Ripley, Ontario",
"Ripon, Quebec",
"Riske Creek, British Columbia",
"River Hebert, Nova Scotia",
"River John, Nova Scotia",
"River of Ponds, Newfoundland",
"Riverhurst, Saskatchewan",
"Riverport, Nova Scotia",
"Rivers, Manitoba",
"Riverton, Manitoba",
"Riverview, New Brunswick",
"Riviere-a-Pierre, Quebec",
"Riviere-au-Renard, Quebec",
"Riviere-au-Tonnerre, Quebec",
"Riviere-Beaudette, Quebec",
"Riviere-Bleue, Quebec",
"Riviere-du-Loup, Quebec",
"Riviere-Heva, Quebec",
"Riviere-St-Jean, Quebec",
"Robb, Alberta",
"Robertsonville, Quebec",
"Robert`s Arm, Newfoundland",
"Roberval, Quebec",
"Roblin, Manitoba",
"Rocanville, Saskatchewan",
"Rochebaucourt, Quebec",
"Rochester, Alberta",
"Rock Creek, British Columbia",
"Rock Forest, Quebec",
"Rockglen, Saskatchewan",
"Rockland, Ontario",
"Rockwood, Ontario",
"Rocky Harbour, Newfoundland",
"Rocky Mountain House, Alberta",
"Rockyford, Alberta",
"Roddickton, Newfoundland",
"Rodney, Ontario",
"Rogersville, New Brunswick",
"Roland, Manitoba",
"Rolla, British Columbia",
"Rollet, Quebec",
"Rolling Hills, Alberta",
"Rolphton, Ontario",
"Rondeau, Ontario",
"Rorketon, Manitoba",
"Rosalind, Alberta",
"Rose Blanche-Harbour Le Cou, Newfoundland",
"Rose Valley, Saskatchewan",
"Rosebud, Alberta",
"Rosemere, Quebec",
"Roseneath, Ontario",
"Rosetown, Saskatchewan",
"Ross River, Yukon",
"Rossburn, Manitoba",
"Rosseau, Ontario",
"Rossland, British Columbia",
"Rosthern, Saskatchewan",
"Rothesay, New Brunswick",
"Rougemont, Quebec",
"Rouleau, Saskatchewan",
"Rouyn-Noranda, Quebec",
"Roxboro, Quebec",
"Roxton Falls, Quebec",
"Roxton Pond, Quebec",
"Rumsey, Alberta",
"Rushoon, Newfoundland",
"Russell, Manitoba",
"Russell, Ontario",
"Rusticoville, Prince Edward Island",
"Ruthven, Ontario",
"Rycroft, Alberta",
"Ryley, Alberta",
"Saanich, British Columbia",
"Sabrevois, Quebec",
"Sachigo First Nation Reserve 1, Ontario",
"Sackville, New Brunswick",
"Sacre Coeur, Quebec",
"Saint Alexandre D`Iberville, Quebec",
"Saint Alphonse de Granby, Quebec",
"Saint Amable, Quebec",
"Saint Andrews, New Brunswick",
"Saint Antoine Des Laurentides, Quebec",
"Saint Antoine Sur Richelieu, Quebec",
"Saint Antonin, Quebec",
"Saint Athanase, Quebec",
"Saint Calixte, Quebec",
"Saint Charles Borromee, Quebec",
"Saint Charles Sur Richelieu, Quebec",
"Saint Christophe D`Arthabaska, Quebec",
"Saint Clair Beach, Ontario",
"Saint Colomban, Quebec",
"Saint Denis De Brompton, Quebec",
"Saint Denis Sur Richelieu, Quebec",
"Saint Esprit, Quebec",
"Saint Etienne de Beauharnois, Quebec",
"Saint Etienne de Lauzon, Quebec",
"Saint Gerard Majella, Quebec",
"Saint Isidore de la Prairie, Quebec",
"Saint Jean Baptiste, Quebec",
"Saint Jean D`Orleans, Quebec",
"Saint Joachim, Quebec",
"Saint John, New Brunswick",
"Saint Joseph De La Pointe De L, Quebec",
"Saint Laurent D`Orleans, Quebec",
"Saint Lazare De Vaudreuil, Quebec",
"Saint Lin Laurentides, Quebec",
"Saint Marc Sur Richelieu, Quebec",
"Saint Mathias Sur Richelieu, Quebec",
"Saint Mathieu de Beloeil, Quebec",
"Saint Mathieu de la Prairie, Quebec",
"Saint Maurice, Quebec",
"Saint Norbert D`Arthabaska, Quebec",
"Saint Paul D`Industrie, Quebec",
"Saint Philippe, Quebec",
"Saint Pierre D`Orleans, Quebec",
"Saint Robert, Quebec",
"Saint Roch De L`Achigan, Quebec",
"Saint Roch De Richelieu, Quebec",
"Saint Sulpice, Quebec",
"Saint Thomas, Quebec",
"Saint Urbain Premier, Quebec",
"Saint Valere, Quebec",
"Saint Victoire de Sorel, Quebec",
"Saint-Alexis-de-Montcalm, Quebec",
"Saint-Côme, Quebec",
"Saint-Donat, Quebec",
"Saint-Élie, Quebec",
"Saint-Élie-d`Orford, Quebec",
"Saint-Ferdinand, Quebec",
"Saint-Ferréol-les-neiges, Quebec",
"Saint-Hubert, Quebec",
"Saint-Hyacinthe, Quebec",
"Saint-Michel-des-Saints, Quebec",
"Sainte Angele De Monnoir, Quebec",
"Sainte Ann De Sorel, Quebec",
"Sainte Brigide D`Iberville, Quebec",
"Sainte Cecile De Milton, Quebec",
"Sainte Dorotheé, Quebec",
"Sainte Famille, Quebec",
"Sainte Marie Salome, Quebec",
"Sainte Marthe Du Cap, Quebec",
"Sainte Sophie, Quebec",
"Sainte Therese De Blainville, Quebec",
"Salaberry-de-Valleyfield, Quebec",
"Salem, Ontario",
"Salisbury, New Brunswick",
"Salluit, Quebec",
"Salmo, British Columbia",
"Salmon Arm, British Columbia",
"Salmon Cove, Newfoundland",
"Salmon Valley, British Columbia",
"Salt Springs, Nova Scotia",
"Saltcoats, Saskatchewan",
"Salvage, Newfoundland",
"Sandspit, British Columbia",
"Sandwich, Ontario",
"Sandy Bay, Saskatchewan",
"Sandy Cove Acres, Ontario",
"Sandy Lake, Manitoba",
"Sandy Lake, Ontario",
"Sandy Lake First Nation, Ontario",
"Sanford, Manitoba",
"Sangudo, Alberta",
"Sanmaur, Quebec",
"Sapawe, Ontario",
"Sarnia, Ontario",
"Saskatchewan River Crossing, Alberta",
"Saskatoon, Saskatchewan",
"Sauble Beach, Ontario",
"Saugeen First Nation, Ontario",
"Saulnierville, Nova Scotia",
"Sault Ste. Marie, Ontario",
"Sault-au-Mouton, Quebec",
"Savant Lake, Ontario",
"Savona, British Columbia",
"Sawyerville, Quebec",
"Sayabec, Quebec",
"Sayward, British Columbia",
"Scarborough, Ontario",
"Sceptre, Saskatchewan",
"Schefferville, Quebec",
"Schomberg, Ontario",
"Schreiber, Ontario",
"Schuler, Alberta",
"Scotland, Ontario",
"Scotstown, Quebec",
"Scott, Saskatchewan",
"Seaforth, Ontario",
"Seal Cove, Newfoundland",
"Searchmont, Ontario",
"Seba Beach, Alberta",
"Sebright, Ontario",
"Sebringville, Ontario",
"Sechelt, British Columbia",
"Sedgewick, Alberta",
"Sedley, Saskatchewan",
"Seeleys Bay, Ontario",
"Selby, Ontario",
"Seldom-Little Seldom, Newfoundland",
"Selkirk, Manitoba",
"Selkirk, Ontario",
"Semans, Saskatchewan",
"Senneterre, Quebec",
"Senneville, Quebec",
"Sept-Iles, Quebec",
"Serpent River First Nation, Ontario",
"Seven Persons, Alberta",
"Severn Bridge, Ontario",
"Sexsmith, Alberta",
"Shakespeare, Ontario",
"Shalalth, British Columbia",
"Shamattawa, Manitoba",
"Shannonville, Ontario",
"Sharbot Lake, Ontario",
"Shaunavon, Saskatchewan",
"Shawanaga First Nation, Ontario",
"Shawbridge, Quebec",
"Shawinigan, Quebec",
"Shawinigan-Sud, Quebec",
"Shawville, Quebec",
"Shebandowan, Ontario",
"Shedden, Ontario",
"Shediac, New Brunswick",
"Shefford, Quebec",
"Sheho, Saskatchewan",
"Shelburne, Nova Scotia",
"Shelburne, Ontario",
"Shell Lake, Saskatchewan",
"Shellbrook, Saskatchewan",
"Sherbrooke, Nova Scotia",
"Sherbrooke, Quebec",
"Sherwood Park, Alberta",
"Shigawake, Quebec",
"Shilo, Manitoba",
"Shippagan, New Brunswick",
"Shipshaw, Quebec",
"Shoal Lake, Manitoba",
"Shubenacadie, Nova Scotia",
"Sibbald, Alberta",
"Sicamous, British Columbia",
"Sidney, British Columbia",
"Sidney, Manitoba",
"Sifton, Manitoba",
"Sillery, Quebec",
"Silver Valley, Alberta",
"Silver Water, Ontario",
"Simcoe, Ontario",
"Simpson, Saskatchewan",
"Sintaluta, Saskatchewan",
"Sioux Lookout, Ontario",
"Sioux Narrows, Ontario",
"Six Nations of the Grand River, Ontario",
"Skookumchuck, British Columbia",
"Slave Lake, Alberta",
"Slocan, British Columbia",
"Small Point-Broad Cove-Blackhe, Newfoundland",
"Smeaton, Saskatchewan",
"Smiley, Saskatchewan",
"Smith, Alberta",
"Smithers, British Columbia",
"Smiths Falls, Ontario",
"Smithville, Ontario",
"Smoky Lake, Alberta",
"Smooth Rock Falls, Ontario",
"Snelgrove, Ontario",
"Snow Lake, Manitoba",
"Snowflake, Manitoba",
"Sointula, British Columbia",
"Sombra, Ontario",
"Somerset, Manitoba",
"Sooke, British Columbia",
"Sorel-Tracy, Quebec",
"Sorrento, British Columbia",
"Souris, Manitoba",
"Souris, Prince Edward Island",
"South Brook, Newfoundland",
"South Indian Lake, Manitoba",
"South Lake, Prince Edward Island",
"South Mountain, Ontario",
"South River, Newfoundland",
"South River, Ontario",
"South Slocan, British Columbia",
"Southampton, Nova Scotia",
"Southampton, Ontario",
"Southend, Saskatchewan",
"Southern Harbour, Newfoundland",
"Southey, Saskatchewan",
"Spalding, Saskatchewan",
"Spaniard`s Bay, Newfoundland",
"Spanish, Ontario",
"Sparta, Ontario",
"Sparwood, British Columbia",
"Speers, Saskatchewan",
"Spencerville, Ontario",
"Spences Bridge, British Columbia",
"Sperling, Manitoba",
"Spillimacheen, British Columbia",
"Spirit River, Alberta",
"Spiritwood, Saskatchewan",
"Split Lake, Manitoba",
"Spotted Island, Newfoundland",
"Sprague, Manitoba",
"Springdale, Newfoundland",
"Springfield, New Brunswick",
"Springfield, Nova Scotia",
"Springhill, Nova Scotia",
"Springside, Saskatchewan",
"Spruce Grove, Alberta",
"Spruce View, Alberta",
"Sprucedale, Ontario",
"Spy Hill, Saskatchewan",
"Squamish, British Columbia",
"Squatec, Quebec",
"St-Adelphe, Quebec",
"St-Adolphe-de-Dudswell, Quebec",
"St-Adolphe-d`Howard, Quebec",
"St-Agapit, Quebec",
"St-Aime, Quebec",
"St-Albert, Quebec",
"St-Alexandre-de-Kamouraska, Quebec",
"St-Alexis-de-Matapedia, Quebec",
"St-Alexis-des-Monts, Quebec",
"St-Alphonse-Rodriguez, Quebec",
"St-Andre, Quebec",
"St-Andre-Avellin, Quebec",
"St-Andre-du-Lac-St-Jean, Quebec",
"St-Andre-Est, Quebec",
"St-Anselme, Quebec",
"St-Antoine, New Brunswick",
"St-Antoine, Quebec",
"St-Antoine-de-Tilly, Quebec",
"St-Apollinaire, Quebec",
"St-Augustin-de-Desmaures, Quebec",
"St-Barnabe, Quebec",
"St-Barthelemy, Quebec",
"St-Basile, New Brunswick",
"St-Basile-le-Grand, Quebec",
"St-Basile-Sud, Quebec",
"St-Blaise-sur-Richelieu, Quebec",
"St-Boniface-de-Shawinigan, Quebec",
"St-Bruno, Quebec",
"St-Bruno-de-Montarville, Quebec",
"St-Calixte-de-Kilkenny, Quebec",
"St-Casimir, Quebec",
"St-Celestin, Quebec",
"St-Cesaire, Quebec",
"St-Charles-de-Bellechasse, Quebec",
"St-Chrysostome, Quebec",
"St-Clet, Quebec",
"St-Constant, Quebec",
"St-Cyrille-de-Wendover, Quebec",
"St-Damase, Quebec",
"St-Damien-de-Buckland, Quebec",
"St-Denis, Quebec",
"St-Edouard-de-Lotbiniere, Quebec",
"St-Eleuthere, Quebec",
"St-Emile, Quebec",
"St-Emile-de-Suffolk, Quebec",
"St-Ephrem-de-Beauce, Quebec",
"St-Ephrem-de-Tring, Quebec",
"St-Eugene, Ontario",
"St-Eugene-de-Guigues, Quebec",
"St-Eustache, Quebec",
"St-Fabien-de-Panet, Quebec",
"St-Felicien, Quebec",
"St-Felix-de-Kingsey, Quebec",
"St-Felix-de-Valois, Quebec",
"St-Fidele-de-Mont-Murray, Quebec",
"St-Flavien, Quebec",
"St-Francois-du-Lac, Quebec",
"St-Fulgence, Quebec",
"St-Gabriel, Quebec",
"St-Gabriel-de-Brandon, Quebec",
"St-Gedeon, Quebec",
"St-Georges, Quebec",
"St-Georges-de-Beauce, Quebec",
"St-Georges-de-Cacouna, Quebec",
"St-Gerard, Quebec",
"St-Germain-de-Grantham, Quebec",
"St-Gregoire-de-Greenlay, Quebec",
"St-Guillaume, Quebec",
"St-Hilarion, Quebec",
"St-Hippolyte, Quebec",
"St-Honore-de-Beauce, Quebec",
"St-Honore-de-Chicoutimi, Quebec",
"St-Hugues, Quebec",
"St-Irenee, Quebec",
"St-Isidore, New Brunswick",
"St-Jacques, Quebec",
"St-Jean-Chrysostome, Quebec",
"St-Jean-de-Dieu, Quebec",
"St-Jean-de-Matha, Quebec",
"St-Jean-Port-Joli, Quebec",
"St-Jean-sur-Richelieu, Quebec",
"St-Jerome, Quebec",
"St-Joseph-de-Beauce, Quebec",
"St-Joseph-de-la-Rive, Quebec",
"St-Joseph-de-Sorel, Quebec",
"St-Jovite, Quebec",
"St-Jude, Quebec",
"St-Just-de-Bretenieres, Quebec",
"St-Lambert, Quebec",
"St-Lambert-de-Lauzon, Quebec",
"St-Laurent, Quebec",
"St-Leon-le-Grand, Quebec",
"St-Leonard, Quebec",
"St-Leonard-d`Aston, Quebec",
"St-Liboire, Quebec",
"St-Lin, Quebec",
"St-Louis de Kent, New Brunswick",
"St-Louis-de-France, Quebec",
"St-Luc, Quebec",
"St-Ludger, Quebec",
"St-Magloire, Quebec",
"St-Malachie, Quebec",
"St-Malo, Quebec",
"St-Marc-des-Carrieres, Quebec",
"St-Methode-de-Frontenac, Quebec",
"St-Michel-de-Bellechasse, Quebec",
"St-Moose, Quebec",
"St-Nazaire-d`Acton, Quebec",
"St-Nicolas, Quebec",
"St-Noel, Quebec",
"St-Odilon-de-Cranbourne, Quebec",
"St-Ours, Quebec",
"St-Pacome, Quebec",
"St-Pamphile, Quebec",
"St-Pascal, Quebec",
"St-Patrice-de-Beaurivage, Quebec",
"St-Paul-de-Montminy, Quebec",
"St-Paul-d`Abbotsford, Quebec",
"St-Paulin, Quebec",
"St-Philippe-de-Neri, Quebec",
"St-Pie, Quebec",
"St-Pie-de-Guire, Quebec",
"St-Pierre, Quebec",
"St-Pierre-de-Wakefield, Quebec",
"St-Pierre-Jolys, Manitoba",
"St-Pierre-les-Becquets, Quebec",
"St-Polycarpe, Quebec",
"St-Prime, Quebec",
"St-Prosper-de-Dorchester, Quebec",
"St-Quentin, New Brunswick",
"St-Raymond, Quebec",
"St-Redempteur, Quebec",
"St-Remi, Quebec",
"St-Rene-de-Matane, Quebec",
"St-Roch-de-Mekinac, Quebec",
"St-Roch-des-Aulnaies, Quebec",
"St-Romuald, Quebec",
"St-Sauveur, Quebec",
"St-Sauveur-des-Monts, Quebec",
"St-Simeon, Quebec",
"St-Simon-de-Bagot, Quebec",
"St-Simon-de-Rimouski, Quebec",
"St-Sylvere, Quebec",
"St-Sylvestre, Quebec",
"St-Theophile, Quebec",
"St-Thomas-d`Aquin, Quebec",
"St-Timothee, Quebec",
"St-Tite, Quebec",
"St-Tite-des-Caps, Quebec",
"St-Ubalde, Quebec",
"St-Ulric, Quebec",
"St-Urbain, Quebec",
"St-Victor, Quebec",
"St-Wenceslas, Quebec",
"St-Zacharie, Quebec",
"St-Zenon, Quebec",
"St-Zephirin, Quebec",
"St-Zotique, Quebec",
"St. Alban`s, Newfoundland",
"St. Albert, Alberta",
"St. Ambroise de Chicoutimi, Quebec",
"St. Anthony, Newfoundland",
"St. Basile de Portneuf, Quebec",
"St. Benedict, Saskatchewan",
"St. Bernard de Dorchester, Quebec",
"St. Bernard`s-Jacques Fontaine, Newfoundland",
"St. Brendan`s, Newfoundland",
"St. Bride`s, Newfoundland",
"St. Brieux, Saskatchewan",
"St. Catharines, Ontario",
"St. Charles, Ontario",
"St. Claude, Manitoba",
"St. Clements, Ontario",
"St. Come de Kennebec, Quebec",
"St. Davids, Ontario",
"St. Edouard de Frampton, Quebec",
"St. Fabien de Rimouski, Quebec",
"St. Ferdinand d`Halifax, Quebec",
"St. Fidele, Quebec",
"St. Francois Xavier, Manitoba",
"St. Gabriel de Rimouski, Quebec",
"St. Gedeon de Beauce, Quebec",
"St. George, New Brunswick",
"St. George, Ontario",
"St. George`s, Newfoundland",
"St. Gregoire de Nicolet, Quebec",
"St. Gregor, Saskatchewan",
"St. Henri de Levis, Quebec",
"St. Honore, Quebec",
"St. Isidore de Prescott, Ontario",
"St. Jacobs, Ontario",
"St. Jacques-Coomb`s Cove, Newfoundland",
"St. Jean Baptiste, Manitoba",
"St. John`s, Newfoundland",
"St. Laurent, Manitoba",
"St. Lawrence, Newfoundland",
"St. Lazare, Manitoba",
"St. Leon De Chic., Quebec",
"St. Leonard, New Brunswick",
"St. Lewis, Newfoundland",
"St. Louis, Saskatchewan",
"St. Lunaire-Griquet, Newfoundland",
"St. Margaret Village, Nova Scotia",
"St. Martin de Beauce, Quebec",
"St. Martins, New Brunswick",
"St. Marys, Ontario",
"St. Mary`s, Newfoundland",
"St. Michael, Alberta",
"St. Moise, Quebec",
"St. Paul, Alberta",
"St. Peters, Prince Edward Island",
"St. Peter`s, Nova Scotia",
"St. Raphael de Bellechasse, Quebec",
"St. Regis, Ontario",
"St. Sebastien, Quebec",
"St. Stanislas de Champlain, Quebec",
"St. Stephen, New Brunswick",
"St. Theodore de Chertsey, Quebec",
"St. Thomas, Ontario",
"St. Victor de Beauce, Quebec",
"St. Vincent de Paul, Quebec",
"St. Vincent`s-St. Stephen`s-Pe, Newfoundland",
"St. Walburg, Saskatchewan",
"Stand Off, Alberta",
"Standard, Alberta",
"Stanley, New Brunswick",
"Stanley Mission, Saskatchewan",
"Stanstead, Quebec",
"Star City, Saskatchewan",
"Starbuck, Manitoba",
"Stavely, Alberta",
"Stayner, Ontario",
"Ste-Adele, Quebec",
"Ste-Agathe, Quebec",
"Ste-Agathe-des-Monts, Quebec",
"Ste-Agathe-Sud, Quebec",
"Ste-Anne-de-Beaupre, Quebec",
"Ste-Anne-de-Bellevue, Quebec",
"Ste-Anne-de-la-Perade, Quebec",
"Ste-Anne-de-Madawaska, New Brunswick",
"Ste-Anne-de-Portneuf, Quebec",
"Ste-Anne-des-Monts, Quebec",
"Ste-Anne-des-Plaines, Quebec",
"Ste-Anne-du-Lac, Quebec",
"Ste-Blandine, Quebec",
"Ste-Brigitte-de-Laval, Quebec",
"Ste-Catherine, Quebec",
"Ste-Clotilde-de-Horton, Quebec",
"Ste-Eulalie, Quebec",
"Ste-Felicite, Quebec",
"Ste-Foy, Quebec",
"Ste-Genevieve, Quebec",
"Ste-Helene-de-Bagot, Quebec",
"Ste-Henedine, Quebec",
"Ste-Jeanne-d`Arc, Quebec",
"Ste-Julie, Quebec",
"Ste-Julie-de-Vercheres, Quebec",
"Ste-Julienne, Quebec",
"Ste-Justine, Quebec",
"Ste-Lucie-de-Beauregard, Quebec",
"Ste-Madeleine, Quebec",
"Ste-Marguerite, Quebec",
"Ste-Marie-de-Beauce, Quebec",
"Ste-Marie-de-Blandford, Quebec",
"Ste-Marthe, Quebec",
"Ste-Marthe-sur-le-Lac, Quebec",
"Ste-Perpetue, Quebec",
"Ste-Petronille, Quebec",
"Ste-Rosalie, Quebec",
"Ste-Rose, Quebec",
"Ste-Rose-de-Watford, Quebec",
"Ste-Rose-du-Nord, Quebec",
"Ste-Sophie-de-Levrard, Quebec",
"Ste-Thecle, Quebec",
"Ste-Therese, Quebec",
"Ste-Veronique, Quebec",
"Ste-Victoire, Quebec",
"Ste. Agathe, Manitoba",
"Ste. Agathe de Lotbiniere, Quebec",
"Ste. Angele de Laval, Quebec",
"Ste. Cecile Masham, Quebec",
"Ste. Claire de Dorchester, Quebec",
"Ste. Croix de Lotbiniere, Quebec",
"Ste. Gertrude, Quebec",
"Ste. Justine de Newton, Quebec",
"Ste. Martine, Quebec",
"Ste. Methode de Frontenac, Quebec",
"Ste. Monique de Nicolet, Quebec",
"Ste. Rose du Lac, Manitoba",
"Steady Brook, Newfoundland",
"Steep Rock, Manitoba",
"Steinbach, Manitoba",
"Stellarton, Nova Scotia",
"Stephenville, Newfoundland",
"Stephenville Crossing, Newfoundland",
"Stettler, Alberta",
"Stevensville, Ontario",
"Stewart, British Columbia",
"Stewarttown, Ontario",
"Stewiacke, Nova Scotia",
"Stirling, Alberta",
"Stirling, Ontario",
"Stockholm, Saskatchewan",
"Stoke, Quebec",
"Stoke`s Bay, Ontario",
"Stoneham, Quebec",
"Stonewall, Manitoba",
"Stoney Creek, Ontario",
"Stoney Point, Ontario",
"Stony Plain, Alberta",
"Stony Rapids, Saskatchewan",
"Storthoaks, Saskatchewan",
"Stouffville, Ontario",
"Stoughton, Saskatchewan",
"Straffordville, Ontario",
"Strasbourg, Saskatchewan",
"Stratford, Ontario",
"Stratford, Prince Edward Island",
"Stratford, Quebec",
"Strathclair, Manitoba",
"Strathmore, Alberta",
"Strathroy, Ontario",
"Stratton, Ontario",
"Streetsville, Ontario",
"Strome, Alberta",
"Strongfield, Saskatchewan",
"Stroud, Ontario",
"Stukely-Sud, Quebec",
"Sturgeon Falls, Ontario",
"Sturgis, Saskatchewan",
"Sudbury, Ontario",
"Sultan, Ontario",
"Summer Beaver, Ontario",
"Summerford, Newfoundland",
"Summerland, British Columbia",
"Summerside, Newfoundland",
"Summerside, Prince Edward Island",
"Summerville, New Brunswick",
"Summit Lake, British Columbia",
"Sunderland, Ontario",
"Sundre, Alberta",
"Sundridge, Ontario",
"Sunnyside, Newfoundland",
"Surrey, British Columbia",
"Sussex, New Brunswick",
"Sutton, Ontario",
"Sutton, Quebec",
"Swan Hills, Alberta",
"Swan Lake, Manitoba",
"Swan River, Manitoba",
"Swastika, Ontario",
"Swift Current, Saskatchewan",
"Swift River, Yukon",
"Sydenham, Ontario",
"Sydney, Nova Scotia",
"Sylvan Lake, Alberta",
"Taber, Alberta",
"Tabusintac, New Brunswick",
"Tachie, British Columbia",
"Tadoule Lake, Manitoba",
"Tadoussac, Quebec",
"Tagish, Yukon",
"Tahsis, British Columbia",
"Tamworth, Ontario",
"Tangier, Nova Scotia",
"Tantallon, Saskatchewan",
"Tara, Ontario",
"Taschereau, Quebec",
"Tasiujaq, Quebec",
"Tatamagouche, Nova Scotia",
"Tatla Lake, British Columbia",
"Tavistock, Ontario",
"Taylor, British Columbia",
"Taylor Corners, Ontario",
"Tecumseh, Ontario",
"Teeswater, Ontario",
"Telegraph Creek, British Columbia",
"Telkwa, British Columbia",
"Temagami, Ontario",
"Temiscaming, Quebec",
"Terra Nova, Newfoundland",
"Terrace, British Columbia",
"Terrace Bay, Ontario",
"Terrasse Vaudreuil, Quebec",
"Terrebonne, Quebec",
"Terrenceville, Newfoundland",
"Teslin, Yukon",
"Tete-a-la-Baleine, Quebec",
"Teulon, Manitoba",
"Thamesford, Ontario",
"Thamesville, Ontario",
"The Eabametoong (Fort Hope) Fi, Ontario",
"The Pas, Manitoba",
"Thedford, Ontario",
"Theodore, Saskatchewan",
"Thessalon, Ontario",
"Thessalon First Nation, Ontario",
"Thetford Mines, Quebec",
"Thicket Portage, Manitoba",
"Thompson, Manitoba",
"Thorburn, Nova Scotia",
"Thorhild, Alberta",
"Thornbury, Ontario",
"Thorndale, Ontario",
"Thorne, Ontario",
"Thornhill, Ontario",
"Thorold, Ontario",
"Thorsby, Alberta",
"Three Hills, Alberta",
"Thrums, British Columbia",
"Thunder Bay, Ontario",
"Thurlow, Ontario",
"Thurso, Quebec",
"Tignish, Prince Edward Island",
"Tilbury, Ontario",
"Tilley, Alberta",
"Tillsonburg, Ontario",
"Timmins, Ontario",
"Tingwick, Quebec",
"Tisdale, Saskatchewan",
"Tiverton, Ontario",
"Toad River, British Columbia",
"Tobermory, Ontario",
"Tobique First Nation, New Brunswick",
"Tofield, Alberta",
"Tofino, British Columbia",
"Togo, Saskatchewan",
"Toledo, Ontario",
"Tomahawk, Alberta",
"Tompkins, Saskatchewan",
"Topley, British Columbia",
"Torbay, Newfoundland",
"Toronto, Ontario",
"Toronto Island, Ontario",
"Torquay, Saskatchewan",
"Torrington, Alberta",
"Tottenham, Ontario",
"Tracadie-Sheila, New Brunswick",
"Trail, British Columbia",
"Tramping Lake, Saskatchewan",
"Treherne, Manitoba",
"Tremblay, Quebec",
"Trenton, Nova Scotia",
"Trenton, Ontario",
"Trepassey, Newfoundland",
"Tribune, Saskatchewan",
"Tring-Jonction, Quebec",
"Triton, Newfoundland",
"Trochu, Alberta",
"Trois-Pistoles, Quebec",
"Trois-Rivieres, Quebec",
"Trout Creek, Ontario",
"Trout Lake, Alberta",
"Trout Lake, British Columbia",
"Trout Lake, Northwest Territories",
"Trout River, Newfoundland",
"Trowbridge, Ontario",
"Truro, Nova Scotia",
"Tsay Keh Dene, British Columbia",
"Tsiigehtchic, Northwest Territories",
"Tuktoyaktuk, Northwest Territories",
"Tumbler Ridge, British Columbia",
"Turner Valley, Alberta",
"Turnor Lake, Saskatchewan",
"Turtleford, Saskatchewan",
"Tusket, Nova Scotia",
"Tweed, Ontario",
"Twillingate, Newfoundland",
"Two Hills, Alberta",
"Tyne Valley, Prince Edward Island",
"Ucluelet, British Columbia",
"Udora, Ontario",
"Umiujaq, Quebec",
"Uniondale, Ontario",
"Unionville, Ontario",
"Unity, Saskatchewan",
"Upper Island Cove, Newfoundland",
"Upper Musquodoboit, Nova Scotia",
"Upper Stewiacke, Nova Scotia",
"Upsala, Ontario",
"Upton, Quebec",
"Uranium City, Saskatchewan",
"Utterson, Ontario",
"Uxbridge, Ontario",
"Val Marie, Saskatchewan",
"Val-Alain, Quebec",
"Val-Barrette, Quebec",
"Val-Belair, Quebec",
"Val-Brillant, Quebec",
"Val-David, Quebec",
"Val-des-Bois, Quebec",
"Val-d`Or, Quebec",
"Valcartier, Quebec",
"Valcourt, Quebec",
"Valemount, British Columbia",
"Vallee-Jonction, Quebec",
"Valley East, Ontario",
"Valleyview, Alberta",
"Vallican, British Columbia",
"Van Anda, British Columbia",
"Vancouver, British Columbia",
"Vanderhoof, British Columbia",
"Vanguard, Saskatchewan",
"Vanier, Ontario",
"Vanier, Quebec",
"Vankleek Hill, Ontario",
"Vanscoy, Saskatchewan",
"Varennes, Quebec",
"Vaudreuil, Quebec",
"Vaudreuil Dorion, Quebec",
"Vaudreuil-sur-le-Lac, Quebec",
"Vaughan, Ontario",
"Vauxhall, Alberta",
"Vavenby, British Columbia",
"Vegreville, Alberta",
"Venise-en-Quebec, Quebec",
"Vercheres, Quebec",
"Verdun, Quebec",
"Vermilion, Alberta",
"Vermilion Bay, Ontario",
"Verner, Ontario",
"Vernon, British Columbia",
"Vernon River, Prince Edward Island",
"Verona, Ontario",
"Veteran, Alberta",
"Vibank, Saskatchewan",
"Victoria, British Columbia",
"Victoria, Newfoundland",
"Victoria, Ontario",
"Victoriaville, Quebec",
"View Royal, British Columbia",
"Viking, Alberta",
"Ville-Marie, Quebec",
"Vilna, Alberta",
"Vimont, Quebec",
"Vineland, Ontario",
"Virden, Manitoba",
"Virginiatown, Ontario",
"Viscount, Saskatchewan",
"Vita, Manitoba",
"Vonda, Saskatchewan",
"Vulcan, Alberta",
"Waasagomach, Manitoba",
"Wabamun, Alberta",
"Wabana, Newfoundland",
"Wabigoon, Ontario",
"Wabowden, Manitoba",
"Wabush, Newfoundland",
"Wadena, Saskatchewan",
"Wainfleet, Ontario",
"Wainwright, Alberta",
"Wakaw, Saskatchewan",
"Wakefield, Quebec",
"Walden, Ontario",
"Waldheim, Saskatchewan",
"Walkerton, Ontario",
"Wallace, Nova Scotia",
"Wallaceburg, Ontario",
"Walsh, Alberta",
"Walton, Nova Scotia",
"Wandering River, Alberta",
"Wanham, Alberta",
"Wanless, Manitoba",
"Wapekeka First Nation, Ontario",
"Wapella, Saskatchewan",
"Warburg, Alberta",
"Warden, Quebec",
"Wardsville, Ontario",
"Warkworth, Ontario",
"Warman, Saskatchewan",
"Warner, Alberta",
"Warren, Ontario",
"Warspite, Alberta",
"Warwick, Quebec",
"Wasaga Beach, Ontario",
"Wasagaming, Manitoba",
"Waskaganish, Quebec",
"Waskatenau, Alberta",
"Waskesiu Lake, Saskatchewan",
"Waswanipi, Quebec",
"Waterdown, Ontario",
"Waterford, Ontario",
"Waterhen, Manitoba",
"Waterloo, Ontario",
"Waterloo, Quebec",
"Waterville, Quebec",
"Watford, Ontario",
"Watrous, Saskatchewan",
"Watson, Saskatchewan",
"Watson Lake, Yukon",
"Waubaushene, Ontario",
"Waverley, Nova Scotia",
"Wawa, Ontario",
"Wawanesa, Manitoba",
"Wawota, Saskatchewan",
"Webb, Saskatchewan",
"Webbwood, Ontario",
"Webequie, Ontario",
"Wedgeport, Nova Scotia",
"Weedon, Quebec",
"Weedon Centre, Quebec",
"Welcome, Ontario",
"Welland, Ontario",
"Wellandport, Ontario",
"Wellesley, Ontario",
"Wellington, Ontario",
"Wellington, Prince Edward Island",
"Wells, British Columbia",
"Welsford, New Brunswick",
"Welwyn, Saskatchewan",
"Wembley, Alberta",
"Wemindji, Quebec",
"Wendover, Quebec",
"Wesleyville, Newfoundland",
"West Brome, Quebec",
"West Guilford, Ontario",
"West Lincoln, Ontario",
"West Lorne, Ontario",
"West Vancouver, British Columbia",
"Westbank, British Columbia",
"Westbury, Quebec",
"Western Bay, Newfoundland",
"Westfield, New Brunswick",
"Westlock, Alberta",
"Westmeath, Ontario",
"Westmount, Quebec",
"Westport, Newfoundland",
"Westport, Ontario",
"Westree, Ontario",
"Westville, Nova Scotia",
"Westwold, British Columbia",
"Wetaskiwin, Alberta",
"Weyburn, Saskatchewan",
"Weymouth, Nova Scotia",
"Whale Cove, Nunavut",
"Wheatley, Ontario",
"Whistler, British Columbia",
"Whitbourne, Newfoundland",
"Whitby, Ontario",
"Whitchurch-Stouffville, Ontario",
"White Fox, Saskatchewan",
"White River, Ontario",
"White Rock, British Columbia",
"Whitecourt, Alberta",
"Whitefish, Ontario",
"Whitefish Falls, Ontario",
"Whitefish River First Nation, Ontario",
"Whitehorse, Yukon",
"Whitelaw, Alberta",
"Whitemouth, Manitoba",
"Whitewood, Saskatchewan",
"Whitney, Ontario",
"Whycocomagh, Nova Scotia",
"Wiarton, Ontario",
"Wickham, Quebec",
"Widewater, Alberta",
"Wikwemikong, Ontario",
"Wilberforce, Ontario",
"Wilcox, Saskatchewan",
"Wildwood, Alberta",
"Wilkie, Saskatchewan",
"Williams Lake, British Columbia",
"Williamsburg, Ontario",
"Willingdon, Alberta",
"Willow Bunch, Saskatchewan",
"Willowbrook, British Columbia",
"Winchester, Ontario",
"Windermere, Ontario",
"Windsor, Nova Scotia",
"Windsor, Ontario",
"Windsor, Quebec",
"Windthorst, Saskatchewan",
"Winfield, Alberta",
"Winfield, British Columbia",
"Wingham, Ontario",
"Winkler, Manitoba",
"Winnipeg, Manitoba",
"Winnipeg Beach, Manitoba",
"Winnipegosis, Manitoba",
"Winona, Ontario",
"Winter Harbour, British Columbia",
"Winterton, Newfoundland",
"Wiseton, Saskatchewan",
"Wishart, Saskatchewan",
"Witless Bay, Newfoundland",
"Woburn, Quebec",
"Woking, Alberta",
"Wolfville, Nova Scotia",
"Wollaston Lake, Saskatchewan",
"Wolseley, Saskatchewan",
"Wonowon, British Columbia",
"Wood Mountain, Saskatchewan",
"Woodbridge, Ontario",
"Woodridge, Manitoba",
"Woodstock, New Brunswick",
"Woodstock, Ontario",
"Woodville, Ontario",
"Woody Point, Newfoundland",
"Wooler, Ontario",
"Worsley, Alberta",
"Wotton, Quebec",
"Wrentham, Alberta",
"Wrigley, Northwest Territories",
"Wunnummin Lake, Ontario",
"Wynndel, British Columbia",
"Wynyard, Saskatchewan",
"Wyoming, Ontario",
"Yahk, British Columbia",
"Yale, British Columbia",
"Yamachiche, Quebec",
"Yamaska, Quebec",
"Yamaska-Est, Quebec",
"Yarker, Ontario",
"Yarmouth, Nova Scotia",
"Yellow Creek, Saskatchewan",
"Yellow Grass, Saskatchewan",
"Yellowknife, Northwest Territories",
"York, Ontario",
"Yorkton, Saskatchewan",
"Youbou, British Columbia",
"Young, Saskatchewan",
"Youngstown, Alberta",
"Young`s Cove Road, New Brunswick",
"Zealandia, Saskatchewan",
"Zeballos, British Columbia",
"Zenon Park, Saskatchewan",
"Zurich, Ontario"]; |
version https://git-lfs.github.com/spec/v1
oid sha256:fcf05751346aaefcf8efe832927ea394201b2971a014ab12ec1d9fa1b6d3c02d
size 3847
|
import React from 'react'
import './label-hint-item.style.scss'
const LabelHint = ({ name }) => <li className="label-hint-item">{name}</li>
export default LabelHint
|
import React from 'react';
import MG from 'metrics-graphics';
const MG_ALLOWED_OPTIONS = [
'aggregate_rollover',
'animate_on_load',
'area',
'axes_not_compact',
'bar_height',
'bar_margin',
'bar_orientation',
'baseline_accessor',
'baselines',
'binned',
'bins',
'bottom',
'buffer',
'center_title_full_width',
'chart_type',
'color_accessor',
'color_range',
'color_type',
'custom_line_color_map',
'data',
'decimals',
'description',
'dodge_accessor',
'error',
'european_clock',
'format',
'full_height',
'full_width',
'height',
'inflator',
'interpolate',
'interpolate_tension',
'left',
'legend',
'legend_target',
'linked',
'linked_format',
'list',
'lowess',
'ls',
'markers',
'max_data_size',
'max_x',
'max_y',
'min_x',
'min_y',
'min_y_from_data',
'missing_is_hidden',
'missing_is_hidden_accessor',
'missing_is_zero',
'missing_text',
'mousemove',
'mouseout',
'mouseover',
'outer_padding_percentage',
'padding_percentage',
'point_size',
'point_size',
'predictor_accessor',
'right',
'rollover_callback',
'rotate_x_labels',
'rotate_y_labels',
'show_confidence_band',
'show_missing_background',
'show_rollover_text',
'show_secondary_x_label',
'show_tooltips',
'show_year_markers',
'show_years',
'size_accessor',
'size_range',
'small_height_threshold',
'small_text',
'small_width_threshold',
'target',
'title',
'top',
'transition_on_update',
'truncate_x_labels',
'truncate_y_labels',
'utc_time',
'width',
'x_accessor',
'x_axis',
'x_extended_ticks',
'x_label',
'x_rollover_format',
'x_rug',
'x_scale_type',
'x_sort',
'xax_count',
'xax_format',
'xax_start_at_min',
'xax_tick_length',
'xax_units',
'y_accessor',
'y_axis',
'y_extended_ticks',
'y_label',
'y_rollover_format',
'y_rug',
'y_scale_type',
'yax_count',
'yax_format',
'yax_tick_length',
'yax_units',
'yax_units_append',
];
function getMGOptions(props){
var mgOptions={},x,p;
for(x=MG_ALLOWED_OPTIONS.length-1;x>=0;x--){
p=MG_ALLOWED_OPTIONS[x];
if(props.hasOwnProperty(p)){
mgOptions[p]=props[p];
}
}
return mgOptions;
}
export default class MetricsGraphics extends React.Component {
constructor(props){
super(props);
this.mgData={};
}
componentDidMount(){
this.mgData=Object.assign(this.mgData,getMGOptions(this.props));
if(this.mgData.target){
if(!this.props.xax_format){
delete this.mgData.xax_format;
}
MG.data_graphic(this.mgData);
}
}
componentWillReceiveProps(nextProps){
this.mgData=Object.assign(this.mgData,getMGOptions(nextProps));
if(this.mgData.target&&!nextProps.xax_format){
delete this.mgData.xax_format;
}
}
componentDidUpdate(){
if(this.mgData.target){
MG.data_graphic(this.mgData);
}
}
render(){
const _this=this;
return(
<div className="metricsGraphicsCon" ref={ (c) =>{ if(c!=null) _this.mgData.target=c; } }></div>
);
}
}
MetricsGraphics.propTypes = MG_ALLOWED_OPTIONS.reduce(
function(obj, propertyName) {
obj[propertyName] = React.PropTypes.any;
return obj;
}, {});
|
// Module for adding messages to the message board
app.addMessage = {
init: function() {
// EVENTS
// Clicking the Send button
$( "div.send-button" ).bind( "click", this.addMessage);
// Handling the Enter keypress
$( "input.message-field" ).keypress(function( event ) {
if ( event.which == 13 ) {
event.preventDefault();
// Adding a message
app.addMessage.addMessage();
}
});
},
// Value for defining on which side shoul we display a new message
side: 0,
// Counter for tracking the number of messages
messagesNumber: 7,
// Adding an inormational box, if there are now messages
addInfoBox: function() {
if (this.messagesNumber == 0) {
// HTML that should be appended
messageHTML = "<div class='no-messages'>" + app.config.noMessagesText + "</div>";
// Appending with animation
$('<div></div>').appendTo("div.message-board").hide().append(messageHTML).fadeIn();
}
},
// Adding a message to the message board
addMessage: function() {
// Declaring the vars
var message, sideClass, messageHTML;
// Checking if the message input field isn't empty
if ($("input.message-field").val() != "") {
// Reseting the message board before adding the first message
if (app.addMessage.messagesNumber == 0) {
$("div.message-board").empty();
}
// Getting the message field value
message = $("input.message-field").val();
// Reseting the input field value
$("input.message-field").val("");
// Defining on which side should we display the message
if (app.addMessage.side) {
sideClass = "left"
} else {
sideClass = "right"
}
// Reversing the counter value
app.addMessage.side = !app.addMessage.side;
// HTML that should be appended
messageHTML = "<div class='message " + sideClass +"-side'><p>" + message + "</p><div class='tail'></div></div>";
// Appending with animation
$('<div></div>').appendTo("div.message-board").hide().append(messageHTML).fadeIn();
// Tracking the message
app.addMessage.messagesNumber++;
}
}
} |
const pizzaGuy = require('../dist/pizza-guy');
const images = require('./large-data').images;
pizzaGuy
.deliver(images)
.onAddress('./demo/downloaded-images')
.onSuccess((info) => {
console.log(`Downloaded: ${info.fileName}`);
})
.onError((info) => {
console.log(`Failed: ${info.fileName}`);
})
.start();
|
require('node-define');
require('node-amd-require');
var assert = require('chai').assert;
var basePath = '../../../';
var srcPath = 'main/js/';
var SrlSketch = require(basePath + srcPath + 'sketchLibrary/SrlSketch');
describe('Sketch Tests', function() {
describe('initializations', function() {
it('should be able to create an instance of the sketch class', function() {
console.log(SrlSketch);
var sketch = new SrlSketch();
});
});
});
|
/*
* Globalize Culture pa
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator
*/
(function (window, undefined) {
var Globalize;
if (typeof require !== "undefined" &&
typeof exports !== "undefined" &&
typeof module !== "undefined") {
// Assume CommonJS
Globalize = require("globalize");
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo("pa", "default", {
name: "pa",
englishName: "Punjabi",
nativeName: "ਪੰਜਾਬੀ",
language: "pa",
numberFormat: {
groupSizes: [3, 2],
percent: {
groupSizes: [3, 2]
},
currency: {
pattern: ["$ -n", "$ n"],
groupSizes: [3, 2],
symbol: "ਰੁ"
}
},
calendars: {
standard: {
"/": "-",
firstDay: 1,
days: {
names: ["ਐਤਵਾਰ", "ਸੋਮਵਾਰ", "ਮੰਗਲਵਾਰ", "ਬੁੱਧਵਾਰ", "ਵੀਰਵਾਰ", "ਸ਼ੁੱਕਰਵਾਰ", "ਸ਼ਨਿੱਚਰਵਾਰ"],
namesAbbr: ["ਐਤ.", "ਸੋਮ.", "ਮੰਗਲ.", "ਬੁੱਧ.", "ਵੀਰ.", "ਸ਼ੁਕਰ.", "ਸ਼ਨਿੱਚਰ."],
namesShort: ["ਐ", "ਸ", "ਮ", "ਬ", "ਵ", "ਸ਼", "ਸ਼"]
},
months: {
names: ["ਜਨਵਰੀ", "ਫ਼ਰਵਰੀ", "ਮਾਰਚ", "ਅਪ੍ਰੈਲ", "ਮਈ", "ਜੂਨ", "ਜੁਲਾਈ", "ਅਗਸਤ", "ਸਤੰਬਰ", "ਅਕਤੂਬਰ", "ਨਵੰਬਰ", "ਦਸੰਬਰ", ""],
namesAbbr: ["ਜਨਵਰੀ", "ਫ਼ਰਵਰੀ", "ਮਾਰਚ", "ਅਪ੍ਰੈਲ", "ਮਈ", "ਜੂਨ", "ਜੁਲਾਈ", "ਅਗਸਤ", "ਸਤੰਬਰ", "ਅਕਤੂਬਰ", "ਨਵੰਬਰ", "ਦਸੰਬਰ", ""]
},
AM: ["ਸਵੇਰ", "ਸਵੇਰ", "ਸਵੇਰ"],
PM: ["ਸ਼ਾਮ", "ਸ਼ਾਮ", "ਸ਼ਾਮ"],
patterns: {
d: "dd-MM-yy",
D: "dd MMMM yyyy dddd",
t: "tt hh:mm",
T: "tt hh:mm:ss",
f: "dd MMMM yyyy dddd tt hh:mm",
F: "dd MMMM yyyy dddd tt hh:mm:ss",
M: "dd MMMM"
}
}
}
});
}(this));
|
(function() {
'use strict';
/**
* @name config
* @description config block
*/
function config($stateProvider) {
$stateProvider
.state('root.infoMovie', {
// url: '/info/:id',
url: '/info',
views: {
'@': {
template: '<info-movie></info-movie>',
}
}
});
}
angular.module('info-movie', ['infoMovieDirective'])
.config(config);
})(); |
const botToken = ''; //--REQUIRED--
const ownerID = ''; //--REQUIRED--
const basedirext = '/files/', //default: '/files/'
basedirsplit = basedirext.split('/').filter(c => c.length),
basedir = __dirname+basedirext;
const http = require('http');
const fs = require('fs');
const discordie = require('discordie');
const hostname = '127.0.0.1';
const port = 8000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('It\'s Hammer Time');
});
if (!botToken)
throw 'No Bot Token, please define in "'+__dirname+'/bot.js"';
else if (!ownerID)
throw 'No Owner ID, please define in "'+__dirname+'/bot.js"';
else
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
var createFolderFunction = (i) => {
if (basedirsplit.length > i) {
var dir = __dirname+'/';
for (var j = 0; i >= j; j++)
dir+=basedirsplit[j];
if (!fs.existsSync(dir))
fs.mkdirSync(dir);
createFolderFunction(++i);
}
};
createFolderFunction(0);
var usernamelist = {},
bans = {},
settings = {},
blacklisted = {},
globSettings = {},
loadedGuilds = {};
fs.readFile(basedir+'blacklisted.json', 'utf8', function (err, data) {
if (err && err.code === 'ENOENT')
fs.writeFile(basedir+'blacklisted.json', '{}', function(err) {
if (err) throw err;
});else if (err)
throw err;
else
blacklisted = JSON.parse(data);
});
fs.readFile(basedir+'settings.json', 'utf8', function (err, data) {
if (err && err.code === 'ENOENT')
fs.writeFile(basedir+'settings.json', '{}', function(err) {
if (err) throw err;
});
else if (err)
throw err;
else
globSettings = JSON.parse(data);
});
function ban(member, match, guild) {
var info = {
username: member.username,
discriminator: member.discriminator,
id: member.id,
matches: match
};
guild.ban(info.id, 0).then(function() {
if (!settings['_'+guild.id].silentban)
guild.generalChannel.sendMessage(settings['_'+guild.id].banmsg+'\n`'+info.username+'#'+info.discriminator+'` ('+info.id+')');
console.log('banned '+info.username+'#'+info.discriminator+' ('+info.id+')');
bans['_'+guild.id].push(info);
fs.writeFile(basedir+'bans/'+guild.id+'.json', JSON.stringify(bans['_'+guild.id]), function(err) {
if (err) throw err;
bans.length++;
fs.writeFile(basedir+'banslength.txt', bans.length.toString(), function(err) {
if (err) throw err;
client.User.setGame('🔨x'+bans.length);
});
});
}, function(err) {
guild.generalChannel.sendMessage('error banning `'+info.username+'#'+info.discriminator+'` ('+info.id+')```'+err+'```');
console.log('ERROR '+info.username+'#'+info.discriminator+' ('+info.id+')');
});
}
function usernameCheck(member, guild) {
var name = member.username,
matches = [];
for (var i = 0; usernamelist['_'+guild.id].length > i; i++)
if (name.match(new RegExp(usernamelist['_'+guild.id][i], 'i')))
matches.push(usernamelist['_'+guild.id][i]);
return matches;
}
var client = new discordie({autoReconnect: true});
client.connect({
token: botToken
});
function eachGuild(guild, num) {
if (typeof loadedGuilds[guild.id] !== 'string') {
fs.readFile(basedir+'bans/'+guild.id+'.json', 'utf8', function (err, data) {
if (err && err.code === 'ENOENT') {
bans['_'+guild.id] = [];
fs.writeFile(basedir+'bans/'+guild.id+'.json', '[]', function(err) {
if (err) throw err;
});
} else if (err)
throw err;
else
bans['_'+guild.id] = JSON.parse(data);
});
fs.readFile(basedir+'settings/'+guild.id+'.json', 'utf8', function (err, data) {
if (err && err.code === 'ENOENT') {
settings['_'+guild.id] = {
banmsg: 'goodbye :hammer:'
};
fs.writeFile(basedir+'settings/'+guild.id+'.json', JSON.stringify(settings['_'+guild.id]), function(err) {
if (err) throw err;
});
} else if (err)
throw err;
else
settings['_'+guild.id] = JSON.parse(data);
});
fs.readFile(basedir+'usernamelist/'+guild.id+'.json', 'utf8', function (err, data) {
if (err && err.code === 'ENOENT') {
usernamelist['_'+guild.id] = [];
fs.writeFile(basedir+'usernamelist/'+guild.id+'.json', '[]', function(err) {
if (err) throw err;
});
} else if (err)
throw err;
else
usernamelist['_'+guild.id] = JSON.parse(data);
});
if (usernamelist['_'+guild.id] && usernamelist['_'+guild.id].length)
for (var i = 0; guild.members.length > i; i++)
if (usernameCheck(guild.members[i], guild).length)
ban(guild.members[i], matches, guild);
if (num)
console.log('finished: '+guild.name+' ('+num+'/'+client.Guilds.length+')');
}
loadedGuilds[guild.id] = guild.name;
}
client.Dispatcher.on('GATEWAY_READY', e => {
console.log('Connected as: '+client.User.username+'\n');
fs.readFile(basedir+'banslength.txt', 'utf8', function (err, data) {
if (err && err.code === 'ENOENT') {
bans.length = 0;
fs.writeFile(basedir+'banslength.txt', '0', function(err) {
if (err) throw err;
});
} else if (err)
throw err;
else
bans.length = parseFloat(data);
client.User.setGame('🔨x'+bans.length);
});
var guildcount = 1;
client.Guilds.forEach(function(guild) {
if (typeof blacklisted['_'+guild.id] === 'string') {
guild.generalChannel.sendMessage('this server has been blacklisted for the following reason```'+(blacklisted['_'+guild.id] ? blacklisted['_'+guild.id] : '(no reason given)')+'```').then(function() {
guild.leave();
}, function() {
guild.leave();
});
console.log('blacklisted: '+guild.name+' ('+guildcount+'/'+client.Guilds.length+') - '+blacklisted['_'+guild.id])
} else {
eachGuild(guild, guildcount);
}
guildcount++;
});
client.User.setGame('🔨x'+bans.length);
});
/*client.Dispatcher.on('GUILD_MEMBER_REMOVE', e => {
});*/
client.Dispatcher.on('GUILD_MEMBER_ADD', e => {
var matches = usernameCheck(e.member, e.guild);
if (matches.length)
ban(e.member, matches, e.guild);
});
client.Dispatcher.on('GUILD_DELETE', e => {
if (!globSettings.noLeaveNotify)
client.Users.get(ownerID).openDM().then(function(dm) {
dm.sendMessage('left server `'+loadedGuilds[e.guildId]+'` ('+e.guildId+')');
delete loadedGuilds[e.guildId];
}, function() {
console.log('unable to open dm')
delete loadedGuilds[e.guildId];
});
});
client.Dispatcher.on('GUILD_CREATE', e => {
console.log('joined: '+e.guild.name+' ('+e.guild.id+')');
if (!globSettings.noJoinNotify)
client.Users.get(ownerID).openDM().then(function(dm) {
dm.sendMessage('joined server `'+e.guild.name+'` ('+e.guild.id+')');
}, function() {
console.log('unable to open dm')
});
if (typeof blacklisted['_'+e.guild.id] === 'string') {
e.guild.generalChannel.sendMessage('this server has been blacklisted for the following reason```'+(blacklisted['_'+e.guild.id] ? blacklisted['_'+e.guild.id] : '(no reason given)')+'```').then(function() {
e.guild.leave();
}, function() {
e.guild.leave();
});
console.log('left server, blacklisted ('+blacklisted['_'+e.guild.id]+')')
} else {
eachGuild(e.guild, null);
e.guild.generalChannel.sendMessage('I am **'+client.User.username+'**\nType `@'+client.User.username+'#'+client.User.discriminator+' help` for help');
}
});
client.Dispatcher.on('MESSAGE_CREATE', e => {
if (!e.message.isPrivate)
loadedGuilds[e.message.guild.id] = e.message.guild.name;
if (!e.message.author.bot) {
var priorityCommands = ['invite', 'invitelink', 'link', 'git', 'github', 'source'];
if ((e.message.isPrivate || e.message.content.match(new RegExp('^<@.{0,1}'+client.User.id+'> *'))) && priorityCommands.indexOf(e.message.content.replace(new RegExp('<@.{0,1}'+client.User.id+'> *'), '').toLowerCase())) {
switch(e.message.content.replace(new RegExp('<@.{0,1}'+client.User.id+'> *'), '').toLowerCase()) {
case 'invite':
case 'invitelink':
case 'link':
e.message.channel.sendMessage('https://discordapp.com/oauth2/authorize?client_id='+client.User.id+'&scope=bot&permissions=4');
break;
/*Start - Do Not Remove*/
//if removed, make sure this link (https://github.com/jaketr00/hammer-time) is somewhere that can be accessed easily by the user
case 'git':
case 'github':
case 'source':
e.message.channel.sendMessage('https://github.com/jaketr00/hammer-time');
break;
/*End - Do Not Remove*/
}
} else if (!e.message.isPrivate && e.message.author.permissionsFor(e.message.channel)['General']['BAN_MEMBERS'] && e.message.content.match(new RegExp('^<@.{0,1}'+client.User.id+'> '))) {
var msg = e.message.content.replace(new RegExp('<@.{0,1}'+client.User.id+'> '), '').toLowerCase(),
command = msg.split(' ')[0],
args = msg.replace(new RegExp('^'+command+' *'), '');
switch(command) {
case 'list':
e.message.author.openDM().then(function(dmc) {
if (usernamelist['_'+e.message.guild.id].length) {
var start = 'Blocked Names for **'+e.message.guild.name+'**',
MdS = '```',
MdE = '```',
first = true;
var textCount = 0,
textLength = 0;
textCount+= (start+MdS).length;
var maxLength = 2000-MdE.length;
var text = [];
text[0] = start+MdS;
for (var i = 0; usernamelist['_'+e.message.guild.id].length > i; i++) {
var humannum = i+1,
textnum = humannum < 10 ? '00'+humannum.toString() : (humannum < 100 ? '0'+humannum.toString() : humannum.toString());
var toAdd = '#'+textnum+' | '+usernamelist['_'+e.message.guild.id][i];
if (!first)
toAdd = '\n'+toAdd;
if (textCount+toAdd.length > maxLength) {
text[textLength]+= MdE;
textLength++;
textCount = MdS.length;
text[textLength] = MdS+toAdd;
first = true;
} else {
textCount+= toAdd.length;
text[textLength]+= toAdd;
first = false;
}
}
text[textLength]+= MdE;
for (var i = 0; text.length > i; i++) {
dmc.sendMessage(text[i]);
}
} else
dmc.sendMessage('No blocked names for **'+e.message.guild.name+'**');
}, function() {
e.message.channel.sendMessage('unable to open a dm');
});
break;
case 'add':
if (args) {
args = args.replace(/[.?!$^\\\/\-*+]/, function(c) {
return '\\'+c;
});
if (usernamelist['_'+e.message.guild.id].indexOf(args)+1)
e.message.channel.sendMessage('**'+args+'** has already been added');
else {
usernamelist['_'+e.message.guild.id].push(args);
fs.writeFile(basedir+'usernamelist/'+e.message.guild.id+'.json', JSON.stringify(usernamelist), function(err) {
if (err) throw err;
e.message.channel.sendMessage('added **'+args+'** to blocked names');
});
}
}
break;
case 'addraw':
if (args) {
if (usernamelist['_'+e.message.guild.id].indexOf(args)+1)
e.message.channel.sendMessage('**'+args+'** has already been added');
else {
usernamelist['_'+e.message.guild.id].push(args);
fs.writeFile(basedir+'usernamelist/'+e.message.guild.id+'.json', JSON.stringify(usernamelist), function(err) {
if (err) throw err;
e.message.channel.sendMessage('added **'+args+'** to blocked names');
});
}
}
break;
case 'remove':
if (args && args.match(/^[0-9]*$/)) {
args = parseInt(args)-1;
if (usernamelist['_'+e.message.guild.id][args]) {
var name = usernamelist['_'+e.message.guild.id][args];
usernamelist['_'+e.message.guild.id].splice(args, 1);
fs.writeFile(basedir+'usernamelist/'+e.message.guild.id+'.json', JSON.stringify(usernamelist['_'+e.message.guild.id]), function(err) {
if (err) throw err;
e.message.channel.sendMessage('removed **'+name+'** from blocked names');
});
} else
e.message.channel.sendMessage('**'+(args+1)+'** is not a valid number to be removed');
}
break;
case 'bans':
e.message.author.openDM().then(function(dmc) {
if (bans['_'+e.message.guild.id].length) {
var start = 'Bans for **'+e.message.guild.name+'**',
MdS = '```diff\n',
MdE = '```',
first = true;
var textCount = 0,
textLength = 0;
textCount+= (start+MdS).length;
var maxLength = 2000-MdE.length;
var text = [];
text[0] = start+MdS;
for (var i = 0; bans['_'+e.message.guild.id].length > i; i++) {
var humannum = i+1,
textnum = humannum < 10 ? '00'+humannum.toString() : (humannum < 100 ? '0'+humannum.toString() : humannum.toString());
var toAdd = '- '+bans['_'+e.message.guild.id][i].username+'#'+bans['_'+e.message.guild.id][i].discriminator+' ('+bans['_'+e.message.guild.id][i].id+') / '+bans['_'+e.message.guild.id][i].matches.join(',');
if (!first)
toAdd = '\n'+toAdd;
if (textCount+toAdd.length > maxLength) {
text[textLength]+= MdE;
textLength++;
textCount = MdS.length;
text[textLength] = MdS+toAdd;
first = true;
} else {
textCount+= toAdd.length;
text[textLength]+= toAdd;
first = false;
}
}
text[textLength]+= MdE;
for (var i = 0; text.length > i; i++) {
dmc.sendMessage(text[i]);
}
} else
dmc.sendMessage('No bans from **'+e.message.guild.name+'**');
}, function() {
e.message.channel.sendMessage('unable to open a dm');
});
break;
case 'banmsg':
if (args) {
settings['_'+e.message.guild.id].banmsg = args;
fs.writeFile(basedir+'settings/'+e.message.guild.id+'.json', JSON.stringify(settings['_'+e.message.guild.id]), function(err) {
if (err) throw err;
e.message.channel.sendMessage('ban message set to **'+args+'**');
});
}
break;
case 'silentban':
var setTo;
switch(args) {
case 'on':
case 'true':
case '1':
case 'yes':
setTo = true;
break;
case 'off':
case 'false':
case '0':
case 'no':
setTo = false;
break;
default:
setTo = !settings['_'+e.message.guild.id].silentban;
break;
}
if (setTo !== settings['_'+e.message.guild.id].silentban) {
settings['_'+e.message.guild.id].silentban = setTo;
fs.writeFile(basedir+'settings/'+e.message.guild.id+'.json', JSON.stringify(settings['_'+e.message.guild.id]), function(err) {
if (err) throw err;
e.message.channel.sendMessage('silent ban has been **'+(setTo ? 'enabled' : 'disabled')+'**');
});
} else
e.message.channel.sendMessage('silent ban is already **'+(setTo ? 'enabled' : 'disabled')+'**');
break;
case 'help':
e.message.author.openDM().then(function(dmc) {
var help = [
'list: sends you a dm of blocked usernames',
'add <name>: adds a blocked username',
'addraw <regex>: adds a blocked username Regular Exponent (remember to escape things meant to be escaped and be to careful with this command)',
'remove <number>: removes a blocked username (use "list" command to get the number)',
'banmsg <text>: what the bot says when it bans',
'bans: send you a dm of the list of bans',
'silentban [yes|no]: enables or disables the "goodbye" message on each ban (no arguments will toggle the state)',
'help: if you really need help with this command, then you need help with a number of other things too'
];
dmc.sendMessage('help```md\n# '+help.join('\n# ')+'\n```');
}, function() {
e.message.channel.sendMessage('unable to open a dm');
});
break;
}
} else if (e.message.isPrivate && e.message.author.id === ownerID) {
var command = e.message.content.split(' ')[0].toLowerCase(),
args = e.message.content.replace(new RegExp('^'+command+' *'), '').toLowerCase();
switch(command) {
case 'servers':
if (client.Guilds.length) {
var start = 'Servers',
MdS = '```md\n',
MdE = '```',
first = true;
var textCount = 0,
textLength = 0;
textCount+= (start+MdS).length;
var maxLength = 2000-MdE.length;
var text = [];
text[0] = start+MdS;
var i = 0;
client.Guilds.forEach(function(guild) {
var humannum = i+1,
textnum = humannum < 10 ? '00'+humannum.toString() : (humannum < 100 ? '0'+humannum.toString() : humannum.toString());
var toAdd = '#'+textnum+' '+guild.name+' ('+guild.id+')';
if (!first)
toAdd = '\n'+toAdd;
if (textCount+toAdd.length > maxLength) {
text[textLength]+= MdE;
textLength++;
textCount = MdS.length;
text[textLength] = MdS+toAdd;
first = true;
} else {
textCount+= toAdd.length;
text[textLength]+= toAdd;
first = false;
}
i++;
});
text[textLength]+= MdE;
for (var i = 0; text.length > i; i++) {
e.message.channel.sendMessage(text[i]);
}
} else
e.message.channel.sendMessage('no servers');
break;
case 'leave':
if (args && args.match(/^[0-9]*$/)) {
args = parseInt(args)-1;
var guilds = client.Guilds.toArray();
if (guilds[args]) {
var id = guilds[args].id;
console.log('leaving: '+guilds[args].name+' ('+guilds[args].id+')');
e.message.channel.sendMessage('leaving **'+guilds[args].name+'** ('+guilds[args].id+')');
guilds[args].leave().then(function() {
if (!globSettings.noLeaveNotify)
e.message.channel.sendMessage('left');
}, function() {
e.message.channel.sendMessage('error leaving');
});
} else
e.message.channel.sendMessage('**'+(args+1)+'** is not a valid server number to leave');
}
break;
case 'blacklisted':
if (client.Guilds.length) {
var start = 'Blacklisted Servers',
MdS = '```diff\n',
MdE = '```',
first = true;
var textCount = 0,
textLength = 0;
textCount+= (start+MdS).length;
var maxLength = 2000-MdE.length;
var text = [];
text[0] = start+MdS;
for (var key in blacklisted) {
var toAdd = '- '+key.replace(/^_/, '')+' ('+(blacklisted[key] ? blacklisted[key] : 'no reason given')+')';
if (!first)
toAdd = '\n'+toAdd;
if (textCount+toAdd.length > maxLength) {
text[textLength]+= MdE;
textLength++;
textCount = MdS.length;
text[textLength] = MdS+toAdd;
first = true;
} else {
textCount+= toAdd.length;
text[textLength]+= toAdd;
first = false;
}
}
text[textLength]+= MdE;
for (var i = 0; text.length > i; i++) {
e.message.channel.sendMessage(text[i]);
}
} else
e.message.channel.sendMessage('no blacklisted servers');
break;
case 'blacklist':
if (args && args.match(/^[0-9]{18}/)) {
var id = args.split(' ')[0],
reason = args.replace(new RegExp('^'+id+' *'), '');
blacklisted['_'+id] = reason;
fs.writeFile(basedir+'blacklisted.json', JSON.stringify(blacklisted), function(err) {
if (err) throw err;
e.message.channel.sendMessage('server `'+args+'` is now blacklisted for '+(reason ? 'the reason```'+reason+'```' : '**no reason**'));
});
if (client.Guilds.get(id))
client.Guilds.get(id).generalChannel.sendMessage('this server has been blacklisted for the following reason```'+(blacklisted['_'+client.Guilds.get(id).id] ? blacklisted['_'+client.Guilds.get(id).id] : '(no reason given)')+'```').then(function() {
client.Guilds.get(id).leave();
}, function() {
client.Guilds.get(id).leave();
});
}
break;
case 'unblacklist':
if (args && args.match(/^[0-9]{18}$/)) {
if (typeof blacklisted['_'+args] === 'string') {
delete blacklisted['_'+args];
fs.writeFile(basedir+'blacklisted.json', JSON.stringify(blacklisted), function(err) {
if (err) throw err;
e.message.channel.sendMessage('server `'+args+'` is no longer blacklisted');
});
} else
e.message.channel.sendMessage('server `'+args+'` was not blacklisted');
}
break;
case 'joinnotify':
var setTo;
switch(args) {
case 'on':
case 'true':
case '1':
case 'yes':
setTo = false;
break;
case 'off':
case 'false':
case '0':
case 'no':
setTo = true;
break;
default:
setTo = !globSettings.noJoinNotify;
break;
}
if (setTo !== globSettings.noJoinNotify) {
globSettings.noJoinNotify = setTo;
fs.writeFile(basedir+'settings.json', JSON.stringify(globSettings), function(err) {
if (err) throw err;
e.message.channel.sendMessage('guild join notifications has been **'+(setTo ? 'disabled' : 'enabled')+'**');
});
} else
e.message.channel.sendMessage('guild join notifications is already **'+(setTo ? 'disabled' : 'enabled')+'**');
break;
case 'leavenotify':
var setTo;
switch(args) {
case 'on':
case 'true':
case '1':
case 'yes':
setTo = false;
break;
case 'off':
case 'false':
case '0':
case 'no':
setTo = true;
break;
default:
setTo = !globSettings.noLeaveNotify;
break;
}
if (setTo !== globSettings.noLeaveNotify) {
globSettings.noLeaveNotify = setTo;
fs.writeFile(basedir+'settings.json', JSON.stringify(globSettings), function(err) {
if (err) throw err;
e.message.channel.sendMessage('guild leave notifications has been **'+(setTo ? 'disabled' : 'enabled')+'**');
});
} else
e.message.channel.sendMessage('guild leave notifications is already **'+(setTo ? 'disabled' : 'enabled')+'**');
break;
case 'help':
var help = [
'servers: sends you a dm of all connected servers',
'leave <number>: leaves a connected server (use "servers" command to get the number)',
'blacklisted: lists all blacklisted servers',
'blacklist <id>: blacklists a server',
'unblacklist <number>: removes a server from the blacklist (use "blacklisted" command to get the number)',
'joinnotify [yes|no]: enables or disables dming when joining a server (no arguments will toggle the state)',
'leavenotify [yes|no]: enables or disables dming when leaving a server (no arguments will toggle the state)',
'help: if you really need help with this command, then you need help with a number of other things too'
];
e.message.channel.sendMessage('bot owner help```md\n# '+help.join('\n# ')+'\n```');
break;
}
}
}
});
}); |
const path = require('path')
const userinfo = require('common-userinfo')
const util = require('util')
const username = userinfo.username
module.exports = name => {
return {
app: {
local: util.format('/Applications/%s.app', name),
system: util.format('/Applications/%s.app', name),
user: util.format('/Users/%s/Applications/%s.app', username, name)
},
bin: {
local: '/opt/local/bin',
system: '/bin',
user: '/usr/bin'
},
config: {
local: util.format('/etc/%s', name),
system: util.format('/etc/%s', name),
user: util.format('/Users/%s/%s', username, name)
},
home: util.format('/Users/%s', username),
lib: {
local: '/usr/lib',
system: '/lib',
user: '/usr/lib'
},
log: {
local: util.format('/var/local/%s/log', name),
system: util.format('/var/%s/log', name),
user: util.format('/var/opt/%s/log', name)
},
temp: path.join(require('os').tmpdir(), name)
}
}
|
require('../../spec/helpers');
const chai = require('chai');
const expect = chai.expect;
const SimpleModel = require('../../spec/models/simpleModel.model');
const update = require('.');
const utilities = require('../utilities');
describe('curdy.update.render', () => {
beforeEach(() => {
return SimpleModel.create({
string: 'string',
number: 42,
date: Date.now(),
boolean: true
})
.then((simpleModel) => {
this.simpleModel = simpleModel;
this.res = {
status: () => {return this.res;},
json: utilities.when
};
});
});
describe('simple models', () => {
beforeEach(() => {
this.update = update.render.method(
SimpleModel,
'curdy.simpleModel',
{
string: 'string',
number: 'number',
boolean: 'boolean'
}
);
});
it('must render', () => {
const req = {
curdy: {
simpleModel: this.simpleModel
}
};
return this.update(req, this.res)
.then((json) => {
expect(json.simpleModel.string).to.equal(this.simpleModel.string);
expect(json.simpleModel.number).to.equal(this.simpleModel.number);
expect(json.simpleModel.boolean).to.equal(this.simpleModel.boolean);
});
});
it('must render allow functions to access the req', () => {
const req = {
curdy: {
simpleModel: this.simpleModel
},
reqValue: 42
};
this.update = update.render.method(
SimpleModel,
'curdy.simpleModel',
{
_id: ({ object }) => {return object._id;},
reqValue: ({ templateOpts }) => {return templateOpts.req.reqValue;}
}
);
return this.update(req, this.res)
.then((json) => {
expect(json.simpleModel._id).to.equal(this.simpleModel._id);
expect(json.simpleModel.reqValue).to.equal(req.reqValue);
});
});
});
}); |
var _ = require('lodash')
var levels = require('hexaworld-levels')
var set = _.values(levels)
require('./app.js')('container', set) |
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = swaggerMiddleware;
var _swaggerClient = require('swagger-client');
var _swaggerClient2 = _interopRequireDefault(_swaggerClient);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function swaggerMiddleware(opts) {
var _this = this;
return function (_ref) {
var dispatch = _ref.dispatch,
getState = _ref.getState;
return function (next) {
return function (action) {
if (typeof action === 'function') {
return action(dispatch, getState);
}
if (!action.swagger) {
return next(action);
}
return new _swaggerClient2['default'](_extends({}, opts, {
requestInterceptor: function requestInterceptor(req) {
return !!opts.requestInterceptor ? opts.requestInterceptor(req, action, dispatch, getState) : req;
},
responseInterceptor: function responseInterceptor(resp) {
return !!opts.responseInterceptor ? opts.responseInterceptor(resp, action, dispatch, getState) : resp;
}
})).then(function (result) {
var swagger = action.swagger,
types = action.types,
actions = action.actions,
rest = _objectWithoutProperties(action, ['swagger', 'types', 'actions']);
var _ref2 = actions || types,
REQUEST = _ref2[0],
SUCCESS = _ref2[1],
FAILURE = _ref2[2];
var callApi = function () {
var _ref3 = _asyncToGenerator(regeneratorRuntime.mark(function _callee(apis, sw) {
var error, resp;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(typeof sw !== 'function')) {
_context.next = 4;
break;
}
error = new Error('Swagger api call is not a function');
opts.error && opts.error(error);
throw error;
case 4:
if (typeof REQUEST === 'function') next(REQUEST(rest));else if (REQUEST) next(_extends({}, rest, { type: REQUEST }));
_context.t0 = !!opts.preRequest;
if (!_context.t0) {
_context.next = 9;
break;
}
_context.next = 9;
return opts.preRequest(action);
case 9:
_context.prev = 9;
_context.next = 12;
return sw(apis, action);
case 12:
resp = _context.sent;
if (!(typeof SUCCESS === 'function')) {
_context.next = 17;
break;
}
return _context.abrupt('return', next(SUCCESS(_extends({}, rest, { result: resp }))));
case 17:
if (!(SUCCESS !== undefined)) {
_context.next = 19;
break;
}
return _context.abrupt('return', next(_extends({}, rest, { result: resp, type: SUCCESS })));
case 19:
_context.next = 29;
break;
case 21:
_context.prev = 21;
_context.t1 = _context['catch'](9);
if (!(typeof FAILURE === 'function')) {
_context.next = 27;
break;
}
return _context.abrupt('return', next(FAILURE(_extends({}, rest, { error: _context.t1 }))));
case 27:
if (!(FAILURE !== undefined)) {
_context.next = 29;
break;
}
return _context.abrupt('return', next(_extends({}, rest, { error: _context.t1, type: FAILURE })));
case 29:
case 'end':
return _context.stop();
}
}
}, _callee, _this, [[9, 21]]);
}));
return function callApi(_x, _x2) {
return _ref3.apply(this, arguments);
};
}();
return callApi(result.apis, swagger);
}, function (err) {
return opts.error && opts.error(err);
})['catch'](function (err) {
return opts.error && opts.error(err);
});
};
};
};
} |
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, '../test/client/index.js'),
output: {
path: path.resolve(__dirname, '../test/client'),
filename: 'test-bundle.js'
},
devtool: 'source-map',
module: {
loaders: [
{
test: /.+.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'es2016', 'es2017', 'stage-0', 'react']
}
}
]
}
};
|
$(document).ready(function(){
ants = JSON.parse(localStorage.getItem('ants'));
if(ants) {
var $aptsList = $('#apts');
$.each(ants, function(index, value) {
$aptsList.append('<li>' +
'<a href="/smartdiary/web/app_dev.php/pensieri-alternativi-funzionali/nuovo/'+index+'"' +
'id="apt-'+ index +'" class="ui-btn ui-btn-icon-right ui-icon-carat-r"' +
'data-ajax="false">' +
'<h3>Pensiero negativo:</h3><p>'+ value['ant'] +'</p>' +
'<h3>Pensiero alternativo:</h3><p>'+ value['apt'] +'</p>' +
'</a></li>');
});
}
}); |
/*
* Author: Paolo Cifariello <paolocifa@gmail.com>
*
*/
(function($){
/* Inizializzazione */
var ES = {
/* Elements handled */
_elements: []
};
/**
* event tracker for dom nodes
*
* @node DOM node
*/
function ElementEvent(node) {
this.node = node;
this.event = {};
this.spaces = {};
}
/**
* Space of events
*
* @name is the identifier
*/
function Space(name) {
this.name = name;
this.active = false;
this.Activate = function() {
this.active = true;
}
this.Deactivate = function() {
this.active = false;
}
}
/*********** Util functions ***********/
/* Add new event listener */
function _addListener(elementEvent, event, spaces, handler) {
var callbacksForEvent = elementEvent.event[event] =
elementEvent.event[event] ? elementEvent.event[event] : [];
jQuery.each(spaces, function(index, spaceName) {
callbacksForEvent.push({
space: spaceName,
callback: handler
});
});
}
/* Try to find event track object for specific node */
function _getElementEvent(node) {
var filterElement = $(ES._elements).filter(function(index, elementEvent) {
return elementEvent.node === node;
});
return filterElement[0];
}
/* Create new space of events */
function _createSpace(elementEvent, spaceName) {
var newSpace = new Space(spaceName);
elementEvent.spaces[spaceName] = newSpace;
return newSpace;
}
/* Delete space of events */
function _deleteSpace(elementEvent, spaceName) {
delete elementEvent.spaces[spaceName];
}
/* Get space of events with that name */
function _getSpace(elementEvent, spaceName) {
return elementEvent.spaces[spaceName];
}
/* Just look if a space is active */
function _isActive(elementEvent, spaceName) {
var sp = _getSpace(elementEvent, spaceName);
if (sp === undefined)
return false;
return sp.active;
}
/* Activate space of events with that name */
function _set(node, spaces, keep) {
var elementEvent = _getElementEvent(node);
jQuery.each(spaces, function(index, spaceName) {
var space = _getSpace(elementEvent, spaceName);
if (typeof space === 'undefined') {
space = _createSpace(elementEvent, spaceName)
}
space.Activate();
});
}
/* Deactivate space of events with that name */
function _unset(node, spaces) {
var elementEvent = _getElementEvent(node);
jQuery.each(spaces, function(index, spaceName) {
var space = _getSpace(elementEvent, spaceName);
if (typeof space !== 'undefined') {
space.Deactivate();
}
});
}
function _son(event, spaces, handler, bubbling) {
var elementEvent = _getElementEvent(this);
if (typeof elementEvent === 'undefined') {
elementEvent = new ElementEvent(this);
ES._elements.push(elementEvent);
$(this).on(event, _handler, bubbling);
}
jQuery.each(spaces, function(index, spaceName) {
if (_getSpace(elementEvent, spaceName) === undefined) {
_createSpace(elementEvent, spaceName);
}
});
_addListener(elementEvent, event, spaces, handler);
};
function _sun(event, spaces, handler) {
var elementEvent = _getElementEvent(this);
if (typeof elementEvent === 'undefined')
return
/* In case spaces are not speceified, then all callbacks for that event are removed */
if (typeof spaces === 'undefined') {
elementEvent.event[event] = [];
return;
}
jQuery.each(spaces, function(index, spaceName) {
elementEvent.event[event] =
jQuery.grep(elementEvent.event[event], function(callbackObject){
if (callbackObject.space === spaceName) {
return typeof handler === 'undefined' ? false : handler !== callbackObject.callback;
}
return true;
});
});
}
/* Handler function */
function _handler() {
var ee = _getElementEvent(this),
event = (event) ? event : arguments[0];
if (!ee)
return;
var cb = ee.event[event.type];
for (var i = 0; i < cb.length; i++)
if (_isActive(ee, cb[i].space)) {
cb[i].callback.call(this, arguments[0]);
return;
}
}
/*********** Public functions ***********/
/*
* Activate an event space
*
* Usage:
* ES.set('intro') -> set intro state and deactivate other spaces
* ES.set(['intro', 'post intro', 'tech']) -> set 3 state active
* ES.set() -> unset all states
*/
$.fn.set = function(spaceName, keep) {
/* In case of set() we call _set(this, [], undefined) so it will unset al active spaces */
if (typeof spaceName === 'undefined')
spaceName = [];
if (spaceName.constructor !== String && spaceName.constructor !== Array)
return;
if (spaceName.constructor === String)
spaceName = [spaceName];
jQuery.each(this, function(index, node) {
_set(node, spaceName, keep);
});
};
/*
* Deactivate an event space
*
* Usage:
* ES.unset('intro') -> set intro state
* ES.unset(['intro', 'post intro', 'tech']) -> unset 3 state active
*/
$.fn.unset = function(spaceName) {
if (spaceName.constructor !== String && spaceName.constructor !== Array)
return;
if (spaceName.constructor === String)
spaceName = [spaceName];
jQuery.each(this, function(index, node) {
_unset(node, spaceName);
});
};
/*
* Add new event handler for an existing event space
*
* Usage:
* $(selector).son('click', ['init', 'post'],
* function(){
* alert('click!');
* },
* false
* );
*/
$.fn.son = function(event, spaces, handler, bubbling) {
if (typeof event !== 'string' ||
typeof handler !== 'function' ||
(spaces.constructor !== String && spaces.constructor !== Array))
return;
if (spaces.constructor === String)
spaces = [spaces];
jQuery.each(this, function(index, node){
_son.call(node, event, spaces, handler, bubbling)
});
};
/*
* Add new event handler for an existing event space
*
* Usage:
* $(selector).sun('click', ['init', 'post'], onClickHandler);
* to remove onClickHandler from those spaces
*
* or
*
* $(selector).sun('click', ['init', 'post']);
* to remove all handlers for click in those spaces
*
* or
*
* $(selector).sun('click');
* to remove all handlers for click in all spaces
*/
$.fn.sun = function(event, spaces, handler) {
if (typeof event !== 'string' ||
(typeof spaces !== 'undefined' && spaces.constructor !== Array && spaces.constructor !== String))
return;
if (spaces.constructor === String)
spaces = [spaces];
jQuery.each(this, function(index, node){
_sun.call(node, event, spaces, handler)
});
};
})($); |
/* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* The routing is enclosed within an anonymous function so that you can
* always reference jQuery with $, even when in .noConflict() mode.
*
* Google CDN, Latest jQuery
* To use the default WordPress version of jQuery, go to lib/config.php and
* remove or comment out: add_theme_support('jquery-cdn');
* ======================================================================== */
(function($) {
// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Roots = {
// All pages
common: {
init: function() {
// JavaScript to be fired on all pages
// steller header
$('.page').stellar();
// Side mene drower
$.slidebars();
// cart form validation
$('.cart')
.bootstrapValidator({
message: 'This value is not valid',
container: 'tooltip',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
'drop-adress1': {
validators: {
notEmpty: {
message: 'The adress is required'
}
}
},
'drop-adress2': {
validators: {
notEmpty: {
enabled: false
}
}
},
'drop-name': {
validators: {
notEmpty: {
message: 'The name is required'
}
}
},
'drop-phone': {
validators: {
notEmpty: {
enabled: false
}
}
}
}
});
//login check and open modal
if (typeof($needLogIn) === "undefined") {
} else {
if($needLogIn){
$('#loginModal').modal('show');
}
}
}
},
// Home page
home: {
init: function() {
// JavaScript to be fired on the home page
$('.home').stellar();
// //jQuery to collapse the navbar on scroll
// $(".navbar-fixed-top").removeClass("top-nav-collapse");
// $(window).scroll(function() {
// if ($(".navbar").offset().top > 50) {
// $(".navbar-fixed-top").addClass("top-nav-collapse");
// } else {
// $(".navbar-fixed-top").removeClass("top-nav-collapse");
// }
// });
}
},
// About us page, note the change from about-us to about_us.
single_product: {
init: function() {
// init
var initProductForm = function(){
showProduct();
// makeProductCarousel();
};
var makeProductCarousel = function(){
var owlProduct = $(".product-carousel");
owlProduct.owlCarousel({
items:1,
// loop:false,
animateIn:false,
animateOut:false,
mouseDrag:true,
touchDrag:false,
autoHeight : false,
center:false,
margin:0,
URLhashListener:true,
startPosition: 'URLHash',
dots:false
});
owlProduct.on('translated.owl.carousel', function(event) {
if(event.item.index === 0){
showProduct();
} else if(event.item.index === 1){
showDrop();
}
$('body,html').animate({ scrollTop: 0 }, 100);
return false;
});
};
var showProduct = function(){
// alert("aaaaaa");
$('#progress-title-product').show();
$('#progress-title-drop').hide();
$(location).attr('href', '#product-price');
};
var showDrop = function(){
// alert("bbbbbbb");
$('#progress-title-product').hide();
$('#progress-title-drop').show();
};
var selectProduct = function(){
$(location).attr('href', '#drop');
};
$('#product-next').click(selectProduct);
initProductForm();
}
},
moncompte: {
init: function() {
// Show only in mordal
$('#login-close-botton').hide();
// $('#login-close-botton-home').show();
}
},
// type speed area select
commander: {
init: function() {
// init
var initOrderForm = function(){
$(location).attr('href', '#type');
var sType;
var sSpeed;
var sArea;
showType();
makeOrderCarousel();
adjustHeight();
};
// Adjust Select Botton
var adjustHeight = function(){
$('.btn-order').matchHeight();
};
// Carousel
var makeOrderCarousel = function(){
var owlOrder = $(".owl-carousel");
owlOrder.owlCarousel({
items:1,
// loop:false,
animateIn:false,
animateOut:false,
mouseDrag:false,
touchDrag:false,
autoHeight : false,
center:false,
margin:0,
URLhashListener:true,
startPosition: 'URLHash',
dots:false
});
owlOrder.on('translated.owl.carousel', function(event) {
if(event.item.index === 0){
showType();
} else if(event.item.index === 1){
showArea();
} else if(event.item.index === 2){
showSpeed();
}
$('body,html').animate({ scrollTop: 0 }, 100);
return false;
});
};
var changeTitleOrder = function(tName){
// alert(cLang);
if( cLang === "en"){
if( tName === "type"){
$('#progress-title').html("SELECT YOUR BAGGAGE TYPE");
} else if ( tName === "area" ){
$('#progress-title').html("SELECT DELIVERY AREA");
} else if ( tName === "speed" ){
$('#progress-title').html("SELECT DELIVERY SPEED");
}
} else if( cLang === "fr"){
if( tName === "type"){
$('#progress-title').html("SELECTIONNEZ VOTRE TYPE DE BAGAGES");
} else if ( tName === "area" ){
$('#progress-title').html("SELECTIONNEZ DELIVERY AREA");
} else if ( tName === "speed" ){
$('#progress-title').html("SELECTIONNEZ DELIVERY SPEED");
}
} else if( cLang === "ja"){
if( tName === "type"){
$('#progress-title').html("お荷物のタイプを選択してください");
} else if ( tName === "area" ){
$('#progress-title').html("配達エリアを選択してください");
} else if ( tName === "speed" ){
$('#progress-title').html("配達スピードを選択してください");
}
}
};
var showType = function(){
resetSelect("#type-select");
// changeTitleOrder('type');
// $('#progressType').addClass('active');
// $('#progressArea').removeClass('active');
// $('#progressSpeed').removeClass('active');
refreshOwl();
};
var showArea = function(){
resetSelect("#area-select");
// changeTitleOrder('area');
// $('#progressType').removeClass('active');
// $('#progressArea').addClass('active');
// $('#progressSpeed').removeClass('active');
refreshOwl();
};
var showSpeed = function(){
resetSelect("#speed-select");
// changeTitleOrder('speed');
// $('#progressType').removeClass('active');
// $('#progressArea').removeClass('active');
// $('#progressSpeed').addClass('active');
refreshOwl();
};
// Type section
var selectType = function(){
sType = $(this).val();
$(location).attr('href', '#area');
};
// Area section
var selectArea = function(){
sArea = $(this).val();
$(location).attr('href', '#speed');
};
// Speed section
var selectSpeed = function(){
sSpeed = $(this).val();
selectProduct();
};
var resetSelect = function(objName){
var dName = objName + " button";
for(var i = 0 ; i < $(dName).length ; i++){
if($(dName).eq(i).hasClass('active')){
$(dName).eq(i).removeClass('active');
}
}
};
refreshOwl = function(owlOrder){
// alert("tetsetset");
$("html,body").animate({scrollTop:0},'fast');
return false;
};
var selectProduct = function(){
var langD ;
// if(cLang === 'fr'){
// langD = '/';
// } else if (cLang === 'en'){
// langD = '/en/';
// } else if (cLang === 'ja'){
// langD = '/ja/';
// }
if(cLang === 'en'){
langD = '/';
} else if (cLang === 'fr'){
langD = '/fr/';
} else if (cLang === 'ja'){
langD = '/ja/';
}
$(location).attr('href', langD + 'shop/' + sType + '-' + sArea + '-' + sSpeed + '/');
};
initOrderForm();
$('#type-select .btn-type').click(selectType);
$('#speed-select .btn-speed').click(selectSpeed);
$('#area-select .btn-area').click(selectArea);
}
},
commande: {
},
checkout: {
init: function() {
$('.checkout').stellar();
toggleLogin = function(){
$('#login-checkout').toggle();
};
//
var smoothScroll = function(){
$('a[href^=#]').click(function() {
var speed = 400;
var href= $(this).attr("href");
var target = $(href === "#" || href === "" ? 'html' : href);
var offset = $(".navbar").height();
var position = target.offset().top - offset;
$('body,html').animate({scrollTop:position}, speed, 'swing');
return false;
});
};
// Carousel
var makeCheckoutCarousel = function(){
$owl = $(".checkout-carousel").owlCarousel({
items:1,
mouseDrag:true,
touchDrag:true,
autoHeight : true,
center:false,
margin:0,
URLhashListener:true,
startPosition: 'URLHash',
dots:false
});
$owl.on('translated.owl.carousel', function(event) {
refreshOwl($owl);
});
};
var backCheckoutCarousel = function(){
$(".checkout-carousel").trigger('prev.owl.carousel');
};
// cart form validation
var initCheckoutValidation = function(){
$('#checkout').bootstrapValidator({
message:'This value is not valid',
container:'tooltip',
feedbackIcons:{
valid:'glyphicon glyphicon-ok',
invalid:'glyphicon glyphicon-remove',
validating:'glyphicon glyphicon-refresh'
},
fields:{
'billing_first_name':{validators:{notEmpty:{message:'The First name is required'}}},
'billing_last_name':{validators:{notEmpty:{message:'The Last name is required'}}},
'billing_company':{validators:{notEmpty:{enabled:false}}},
'billing_address_1':{validators:{notEmpty:{message:'The adress is required'}}},
'billing_address_2':{validators:{notEmpty:{enabled:false}}},
'billing_email':{validators:{notEmpty:{message:'The e-mail is required'},emailAddress:{message:'The value is not a valid email address'}}},
'billing_phone':{validators:{notEmpty:{enabled:false}}},
'account_password':{validators:{notEmpty:{message:'The password is required'}}},
'shipping_company':{validators:{notEmpty:{enabled:false}}},
'shipping_first_name':{validators:{notEmpty:{message: 'The First name is required'}}},
'shipping_last_name':{validators:{notEmpty:{enabled:false}}},
'shipping_address_1': {validators:{notEmpty:{message:'The adress is required'}}},
'shipping_address_2':{validators:{notEmpty:{enabled:false}}}
}
});
};
var resetSelect = function(bbb){
var aaa = bbb + " button";
for(var i = 0 ; i < $(aaa).length ; i++){
if($(aaa).eq(i).hasClass('active')){
$(aaa).eq(i).removeClass('active');
}
}
};
var checkoutGotoBilling = function(){
$(location).attr('href', '#checkout-billing');
refreshOwl();
};
var checkoutGotoPickup = function(){
$(location).attr('href', '#checkout-pickup');
refreshOwl();
};
var checkoutGotoShipping = function(){
$(location).attr('href', '#checkout-shipping');
refreshOwl();
};
var checkoutGotoPayment = function(){
// alert("hello");
$(location).attr('href', '#checkout-payment');
refreshOwl();
};
var checkoutGotoShippingNoCheck = function(){
$('#pickup-from-different-address-checkbox').prop('checked', false);
$(location).attr('href', '#checkout-shipping');
refreshOwl();
};
var checkoutGotoPaymentNoCheck = function(){
$('#ship-to-different-address-checkbox').prop('checked', false);
$(location).attr('href', '#checkout-payment');
refreshOwl();
};
var checkoutGotoMemo = function(){
alert(this);
// $(location).attr('href', '#checkout-memo');
refreshOwl();
};
var toggleDifferentPickupAddress = function(){
if($('#pickup-from-different-address-checkbox').prop('checked')){
$('#pickup-from-different-address-checkbox').prop('checked', false);
} else {
$('#pickup-from-different-address-checkbox').prop('checked', true);
}
// alert($('#pickup-to-different-address-checkbox').prop('checked'));
togglePickupAddressForm();
pickupValid();
clearPickupForm();
};
var toggleDifferentShippingAddress = function(){
if($('#ship-to-different-address-checkbox').prop('checked')){
$('#ship-to-different-address-checkbox').prop('checked', false);
} else {
$('#ship-to-different-address-checkbox').prop('checked', true);
}
// alert($('#ship-to-different-address-checkbox').prop('checked'));
toggleShippingAddressForm();
// shippingValid();
clearShippingForm();
};
var togglePickupAddressForm = function(){
$( '.pickup_select' ).hide();
$( '.pickup_address' ).show();
$owl.trigger('next.owl.carousel', [1]);
$owl.trigger('prev.owl.carousel', [1]);
$( '#pickup-from-same-address-link' ).removeClass('hide');
$('.woocommerce').hide().show(1);
refreshOwl();
};
var toggleShippingAddressForm = function(){
$( '.shipping_select' ).hide();
$( '.shipping_address' ).show();
$( '#shipping-to-same-address-link' ).removeClass('hide');
$owl.trigger('next.owl.carousel', [1]);
$owl.trigger('prev.owl.carousel', [1]);
$('.woocommerce').hide().show(1);
refreshOwl();
};
var clearPickupForm = function(){
$( '#pickup_company' ).val("");
$( '#pickup_first_name' ).val("");
$( '#pickup_last_name' ).val("");
$( '#pickup_address_1' ).val("");
$( '#pickup_address_2' ).val("");
};
var clearShippingForm = function(){
$( '#shipping_company' ).val("");
$( '#shipping_first_name' ).val("");
$( '#shipping_last_name' ).val("");
$( '#shipping_address_1' ).val("");
$( '#shipping_address_2' ).val("");
};
var selectPaymentCod = function(){
$( '#payment_method_cod' ).prop('checked', true);
};
var selectPaymentCheque = function(){
$( '#payment_method_cheque' ).prop('checked', true);
};
var selectPaymentBacs = function(){
$( '#payment_method_bacs' ).prop('checked', true);
};
var selectPaymentPaypal = function(){
$( '#payment_method_paypal' ).prop('checked', true);
};
var billingValid = function(){
if( $('#billing-next-btn').attr('disabled') === 'disabled' && $('#billing_first_name_field').hasClass('has-success') &&$('#billing_last_name_field').hasClass('has-success') && $('#billing_address_1_field').hasClass('has-success') && $('#billing_email_field').hasClass('has-success') && $('#account_password_field').hasClass('has-success') ){
$('#billing-next-btn').removeAttr('disabled');
}
};
var pickupValid = function(){
if( $('#pickup-next-btn').attr('disabled') === 'disabled' && $('#shipping_pickup_first_name_field').hasClass('has-success') && $('#shipping_pickup_address_1_field').hasClass('has-success') ){
$('#pickup-next-btn').removeAttr('disabled');
}
};
var shippingValid = function(){
if( $('#shipping-next-btn').attr('disabled') === 'disabled' && $('#shipping_first_name_field').hasClass('has-success') && $('#shipping_address_1_field').hasClass('has-success') ){
$('#shipping-next-btn').removeAttr('disabled');
}
};
// Add class to input text
var addInputClass = function(){
$(".dropform .input-text").addClass("form-control input-drop");
};
refreshOwl = function(owl){
$("html,body").animate({scrollTop:0},'fast');
return false;
};
var initCheckoutForm = function(){
$(location).attr('href', '#checkout-billing');
// alert('$loggedIn');
// var loggedIn = printf('<?php echo is_user_logged_in(); ?>');
// addInputClass();
makeCheckoutCarousel();
initCheckoutValidation();
smoothScroll();
};
initCheckoutForm();
//test
$('#test-btn').click(checkoutGotoMemo);
$('.btn-back').click(backCheckoutCarousel);
// facture
$('#billing-next-btn').click(checkoutGotoPickup);
$('.woocommerce-billing-fields input').keyup(billingValid);
// pickup
$('#pickup-next-btn').click(checkoutGotoShipping);
$('#pickup-from-different-address-button').click(toggleDifferentPickupAddress);
$('#pickup-from-same-address-button').click(checkoutGotoShipping);
$('#pickup-from-same-address-link').click(checkoutGotoShippingNoCheck);
$('#pickup-back-btn').click(checkoutGotoBilling);
$('.woocommerce-pickup-fields input').keyup(pickupValid);
// Shipping
$('#shipping-next-btn').click(checkoutGotoPayment);
$('#ship-to-different-address-button').click(toggleDifferentShippingAddress);
$('#ship-to-same-address-button').click(checkoutGotoPayment);
$('#shipping-to-same-address-link').click(checkoutGotoPaymentNoCheck);
$('#shipping-back-btn').click(checkoutGotoPickup);
$('.woocommerce-shipping-fields input').keyup(shippingValid);
//payment
$('#payment-btn-cod').click(selectPaymentCod);
$('#payment-btn-cheque').click(selectPaymentCheque);
$('#payment-btn-bacs').click(selectPaymentBacs);
$('#payment-btn-paypal').click(selectPaymentPaypal);
// $('#payment-block .btn-checkout').click(checkoutGotoMemo);
// $('.payment-next-btn').click(checkoutGotoMemo);
$('#payment-back-btn').click(checkoutGotoPickup);
// memo
$('#memo-back-btn').click(checkoutGotoPayment);
}
}
};
Roots.commande = Roots.checkout ;
Roots.my_account = Roots.moncompte ;
// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
fire: function(func, funcname, args) {
var namespace = Roots;
funcname = (funcname === undefined) ? 'init' : funcname;
if (func !== '' && namespace[func] && typeof namespace[func][funcname] === 'function') {
namespace[func][funcname](args);
}
},
loadEvents: function() {
UTIL.fire('common');
$.each(document.body.className.replace(/-/g, '_').split(/\s+/),function(i,classnm) {
UTIL.fire(classnm);
});
}
};
$(document).ready(UTIL.loadEvents);
})(jQuery); // Fully reference jQuery after this point.
|
import { MOCK_EVENT as DATA, createEvent } from './red.data'
import CONTEXT from './red.context'
const EXPECTED_RESULT = {
type: 'UpdateAction',
contact: {
identifier: [ '_contactKey', { name: 'BrokerOffice', value: '_originatingSystemContactKey' } ],
honorificPrefix: '_namePrefix',
givenName: '_firstName',
additionalName: [ '_middleName', '_nickname' ],
familyName: '_lastName',
honorificSuffix: '_nameSuffix',
name: '_fullName',
jobTitle: '_jobTitle',
worksFor: '_company',
preferredContactMethod: '_preferredContactMethod',
preferredPhoneType: '_preferredPhoneType',
preferredTime: '_preferredTime',
address: [ {
type: 'PostalAddress',
identifier: '_addressKey',
name: '_addressType',
streetAddress: [ '_address1', '_address2' ],
addressLocality: '_city',
addressRegion: '_stateOrProvince',
postalCode: '_postalCode',
addressCountry: '_country',
dateCreated: '2017-05-24T20:16:12.8419099-05:00',
dateModified: '2017-05-24T20:16:12.8419099-05:00',
} ],
contactPoint: [
{
type: 'ContactPoint',
identifier: '_emailAddressKey',
email: '_emailAddress',
name: '_emailType',
usedForApm: true,
dateCreated: '2017-05-21T14:03:57.8640648-05:00',
dateModified: '2017-05-21T14:03:57.957819-05:00',
},
{
type: 'ContactPoint',
identifier: '_phoneNumberKey',
name: '_phoneNumberType',
telephone: '_phoneNumber',
dateCreated: '2017-05-21T14:03:57.8640648-05:00',
dateModified: '2017-05-21T14:03:57.957819-05:00',
},
],
comment: [ {
type: 'Comment',
identifier: '_noteKey',
author: '_addedByMember',
value: '_note',
dateCreated: '2017-05-24T12:09:45',
} ],
},
recipient: [ {
type: [ 'Organization', 'RealEstateAgent' ],
identifier: '_ownerKey',
autoAccept: false,
assignmentType: '_assignmentType',
dateCreated: '2017-05-21T14:03:57.8796905-05:00',
},
{
type: [ 'Person', 'RealEstateAgent' ],
identifier: '_ownerKey',
autoAccept: false,
assignmentType: '_assignmentType',
dateCreated: '2017-05-21T14:03:57.8796905-05:00',
} ],
instrument: [ {
leadSource: '_leadSource',
subLeadSource: '_subLeadSource',
originalReferrerUrl: '_originalReferrerUrl',
isLead: true,
dateCreated: '2017-05-21T14:03:57.8796905-05:00',
} ],
mentions: [ {
listingKey: '7117c767-fbaa-4ed5-8fa7-d1febcf5a50d',
listingId: '21705506',
listAor: 'parayac-v',
mlsStatus: 'Active',
listingContractDate: '2017-05-16T00:00:00',
daysOnMarket: 5,
listPrice: 169900,
streetNumber: '20',
streetNumberNumeric: 20,
streetDirPrefix: null,
streetName: 'Asbury Ct',
streetSuffix: null,
unitNumber: null,
addressLocality: 'Mount Wolf',
addressRegion: 'PA',
postalCode: '17347',
addressCountry: 'USA',
countyOrParish: 'York',
subdivisionName: 'Riverview',
directions: null,
listAgentFirstName: 'Jim',
listAgentLastName: 'Powers',
listAgentFullName: 'Jim Powers',
listAgentEmail: 'jpowers@homesale.com',
listAgentMlsId: '3478',
listOfficeMlsId: 'PRUYOST',
listingTypeName: 'Residential',
propertyType: 'Single Family',
propertySubType: '2 Story',
lotSizeArea: 0.2945,
lotSizeDimensions: '1/4 - 1/2 Acre',
poolFeatures: 'Data Unavailable',
bathroomsTotal: null,
bedroomsTotal: '3',
garageSpaces: null,
stories: 2,
yearBuilt: 2002,
heating: 'Gas Heat',
cooling: 'Window Air Conditioning',
interiorFeatures: null,
exteriorFeatures: 'Shed',
roof: 'Asphalt Shingle',
contactNote: 'Situated on a quiet cul-de-sacdlesac in Asbury Pointe, this 3 bedoom, 2 bath home has been freshly painted and new laminate flooring recently installed. Open layout with vaulted ceiling in living room, spacious eat in kitchen with dining area that has sliding glass doors for deck access. Partially finished lower level w/rough-in plumbing that could be used as family room/extended living space. Newer roof, Shed & 2 car garage.',
listBrokerName: 'BERKSHIRE HATHAWAY HOMESALE',
listBrokerPhone: '(800) 383-3535',
propertyUrl: 'http://www.berkshirehathawayhs.com/homesale-realty-pa305/21705506',
dateCreated: '2017-05-21T14:03:57.8796905-05:00',
dateModified: '2017-05-21T14:03:57.8796905-05:00',
} ],
acceptedByMember: true,
dateCreated: '2017-05-21T14:03:57.8796905-05:00',
dateModified: '2017-05-21T14:03:57.8796905-05:00',
}
describe(`Action Types`, () => {
const context = CONTEXT
const transform = context.map
test(`Accepted -> AcceptAction`, () => {
let action = transform(createEvent('Accepted'));
expect(action).toHaveProperty('type', 'AcceptAction')
});
test(`ExternalCreate -> AddAction`, () => {
let action = transform(createEvent('ExternalCreate'));
expect(action).toHaveProperty('type', 'AddAction')
});
test(`Created -> AddAction`, () => {
let action = transform(createEvent('Created'));
expect(action).toHaveProperty('type', 'AddAction')
});
test(`Assigned -> AssignAction`, () => {
let action = transform(createEvent('Assigned'));
expect(action).toHaveProperty('type', 'AssignAction')
});
test(`Associated -> AssignAction`, () => {
let action = transform(createEvent('Associated'));
expect(action).toHaveProperty('type', 'AssignAction')
});
test(`AutoAccepted -> AssignAction`, () => {
let action = transform(createEvent('AutoAccepted'));
expect(action).toHaveProperty('type', 'AssignAction')
});
test(`AssignedToSelf -> AssignAction`, () => {
let action = transform(createEvent('AssignedToSelf'));
expect(action).toHaveProperty('type', 'AssignAction')
});
test(`Deleted -> RemoveAction`, () => {
let action = transform(createEvent('Deleted'));
expect(action).toHaveProperty('type', 'RemoveAction')
});
test(`Registered -> RegisterAction`, () => {
let action = transform(createEvent('Registered'));
expect(action).toHaveProperty('type', 'RegisterAction')
});
test(`Declined -> RejectAction`, () => {
let action = transform(createEvent('Declined'));
expect(action).toHaveProperty('type', 'RejectAction')
});
test(`LeadActivity -> UpdateAction`, () => {
let action = transform(createEvent('LeadActivity'));
expect(action).toHaveProperty('type', 'UpdateAction')
});
test(`DuplicateCreated -> UpdateAction`, () => {
let action = transform(createEvent('DuplicateCreated'));
expect(action).toHaveProperty('type', 'UpdateAction')
});
test(`AdminUpdate -> UpdateAction`, () => {
let action = transform(createEvent('AdminUpdate'));
expect(action).toHaveProperty('type', 'UpdateAction')
});
test(`CRMSync -> UpdateAction`, () => {
let action = transform(createEvent('CRMSync'));
expect(action).toHaveProperty('type', 'UpdateAction')
});
test(`NoteAdded -> UpdateAction`, () => {
let action = transform(createEvent('NoteAdded'));
expect(action).toHaveProperty('type', 'UpdateAction')
});
test(`Updated -> UpdateAction`, () => {
let action = transform(createEvent('Updated'));
expect(action).toHaveProperty('type', 'UpdateAction')
});
test(`Retracted -> UnAssignAction`, () => {
let action = transform(createEvent('Retracted'));
expect(action).toHaveProperty('type', 'UnAssignAction')
});
test(`Unassigned -> UnAssignAction`, () => {
let action = transform(createEvent('Unassigned'));
expect(action).toHaveProperty('type', 'UnAssignAction')
});
})
describe('Context Transformation', () => {
const context = CONTEXT
const result = context.map(DATA)
const expected = EXPECTED_RESULT
test(`eventType => Action`, () => {
expect(result.type).toEqual('UpdateAction')
})
test(`contactPoints`, () => {
expect(result.contact.contactPoint).toEqual(expected.contact.contactPoint)
});
test(`addresses => address`, () => {
expect(result.contact.address).toEqual(expected.contact.address)
});
test(`contact`, () => {
expect(result.contact).toEqual(expected.contact);
})
test(`notes => contact.comment`, () => {
expect(result.contact.comment).toEqual(expected.contact.comment)
})
test(`assignments => recipient`, () => {
expect(result.recipient).toEqual(expected.recipient)
});
test(`recipient`, () => {
expect(result.recipient).toEqual(expected.recipient)
});
test(`leadSource => instrument`, () => {
expect(result.instrument).toEqual(expected.instrument)
});
})
|
import {connect} from 'react-redux';
import Home from '../components/content/home';
export default connect(state => {
return {
base: state.base,
readme: selectReadme(state)
};
})(Home);
function selectReadme(state) {
const url = state.routing.locationBeforeTransitions.pathname;
return `
# Nothing found
> Pretty sure these aren't the hypertext documents you are looking for.
We looked everywhere and could not find a single thing at \`${url}\`.
You might want to navigate back to [Home](/) or use the search.
---
Help us to make this message more helpful on [GitHub](https://github.com/sinnerschrader/patternplate)
`;
}
|
import { fork, take, put, call } from 'redux-saga'
import api from '../blockcypher'
import { actions } from './reducers'
import { utxoSetDiffer } from './logic'
import { wait } from '../app/util'
export default function* watchForSwitch (getState) {
while (true) {
const switchOver = yield take('SWITCH')
yield fork([
put(blockchain.startFetch()),
])
}
}
|
import chalk from 'chalk';
import RSVP from 'rsvp';
import { getIssues as getRepoIssues } from './github';
import { getIssues as getSheetIssues } from './google-spreadsheet';
RSVP.hash({
sheetIssues: getSheetIssues(process.env.SHEET_KEY),
repoIssues: getRepoIssues('emberjs/ember.js')
}).then(({sheetIssues, repoIssues}) => {
sheetIssues.byNumber = sheetIssues.reduce((hash, issue) => {
hash[issue.number] = issue;
return hash;
}, {});
let passCount = 0;
repoIssues.forEach((repoIssue) => {
const number = repoIssue.number;
const stack = [];
let failed = false;
stack.push(chalk.white(`issue #${number}`));
const actual = sheetIssues.byNumber[number];
if (!actual) {
stack.push(fail(`is not present`));
failed = true;
}
if (!failed) {
Object.keys(repoIssue).forEach((prop) => {
if (actual[prop] !== repoIssue[prop]) {
stack.push(fail(`doesn't have matching ${prop}`));
stack.push(info(` expected: ${repoIssue[prop]}`));
stack.push(info(` actual: ${actual[prop]}`));
failed = true;
}
});
}
if (failed) {
console.log(stack.join('\n'));
console.log();
} else {
passCount++;
}
});
console.log(`${repoIssues.length} open issues (${passCount} matching in spreadsheet)`);
}).catch(console.error);
function pass(msg) {
return chalk.green(' ✔') + chalk.gray(` ${msg}`);
}
function fail(msg) {
return chalk.red(' ✘') + chalk.gray(` ${msg}`);
}
function info(msg) {
return chalk.gray(` ${msg}`);
}
|
(function () {
/* Imports */
var Meteor = Package.meteor.Meteor;
var Tracker = Package.tracker.Tracker;
var Deps = Package.tracker.Deps;
var _ = Package.underscore._;
var EJSON = Package.ejson.EJSON;
/* Package-scope variables */
var SubsManager;
(function () {
//////////////////////////////////////////////////////////////////////////////////////////////
// //
// packages/meteorhacks:subs-manager/lib/sub_manager.js //
// //
//////////////////////////////////////////////////////////////////////////////////////////////
//
SubsManager = function (options) { // 1
var self = this; // 2
self.options = options || {}; // 3
// maxiumum number of subscriptions are cached // 4
self.options.cacheLimit = self.options.cacheLimit || 10; // 5
// maximum time, subscription stay in the cache // 6
self.options.expireIn = self.options.expireIn || 5; // 7
// 8
self._cacheMap = {}; // 9
self._cacheList = []; // 10
self.ready = false; // 11
self.dep = new Deps.Dependency(); // 12
// 13
self.computation = self._registerComputation(); // 14
}; // 15
// 16
SubsManager.prototype.subscribe = function() { // 17
var self = this; // 18
if(Meteor.isClient) { // 19
this._addSub(arguments); // 20
// 21
return { // 22
ready: function() { // 23
self.dep.depend(); // 24
return self.ready; // 25
} // 26
}; // 27
} else { // 28
// to support fast-render // 29
if(Meteor.subscribe) { // 30
return Meteor.subscribe.apply(Meteor, arguments); // 31
} // 32
} // 33
}; // 34
// 35
SubsManager.prototype._addSub = function(args) { // 36
var self = this; // 37
var hash = EJSON.stringify(args); // 38
args = _.toArray(args); // 39
if(!self._cacheMap[hash]) { // 40
var sub = { // 41
args: args, // 42
hash: hash // 43
}; // 44
// 45
this._handleError(sub); // 46
// 47
self._cacheMap[hash] = sub; // 48
self._cacheList.push(sub); // 49
// 50
self.ready = false; // 51
// no need to interfere with the current computation // 52
self._reRunSubs(); // 53
} // 54
// 55
// add the current sub to the top of the list // 56
var sub = self._cacheMap[hash]; // 57
sub.updated = (new Date).getTime(); // 58
// 59
var index = self._cacheList.indexOf(sub); // 60
self._cacheList.splice(index, 1); // 61
self._cacheList.push(sub); // 62
}; // 63
// 64
SubsManager.prototype._reRunSubs = function() { // 65
var self = this; // 66
// 67
if(Deps.currentComputation) { // 68
Deps.afterFlush(function() { // 69
self.computation.invalidate(); // 70
}); // 71
} else { // 72
self.computation.invalidate(); // 73
} // 74
}; // 75
// 76
SubsManager.prototype._applyCacheLimit = function () { // 77
var self = this; // 78
var overflow = self._cacheList.length - self.options.cacheLimit; // 79
if(overflow > 0) { // 80
var removedSubs = self._cacheList.splice(0, overflow); // 81
_.each(removedSubs, function(sub) { // 82
delete self._cacheMap[sub.hash]; // 83
}); // 84
} // 85
}; // 86
// 87
SubsManager.prototype._applyExpirations = function() { // 88
var self = this; // 89
var newCacheList = []; // 90
// 91
var expirationTime = (new Date).getTime() - self.options.expireIn * 60 * 1000; // 92
_.each(self._cacheList, function(sub) { // 93
if(sub.updated >= expirationTime) { // 94
newCacheList.push(sub); // 95
} else { // 96
delete self._cacheMap[sub.hash]; // 97
} // 98
}); // 99
// 100
self._cacheList = newCacheList; // 101
}; // 102
// 103
SubsManager.prototype._registerComputation = function() { // 104
var self = this; // 105
var computation = Deps.autorun(function() { // 106
self._applyExpirations(); // 107
self._applyCacheLimit(); // 108
// 109
var ready = true; // 110
_.each(self._cacheList, function(sub) { // 111
sub.ready = Meteor.subscribe.apply(Meteor, sub.args).ready(); // 112
ready = ready && sub.ready; // 113
}); // 114
// 115
if(ready) { // 116
self.ready = true; // 117
self.dep.changed(); // 118
} // 119
}); // 120
// 121
return computation; // 122
}; // 123
// 124
SubsManager.prototype._createIdentifier = function(args) { // 125
var tmpArgs = _.map(args, function(value) { // 126
if(typeof value == "string") { // 127
return '"' + value + '"'; // 128
} else { // 129
return value; // 130
} // 131
}); // 132
// 133
return tmpArgs.join(', '); // 134
}; // 135
// 136
SubsManager.prototype._handleError = function(sub) { // 137
var args = sub.args; // 138
var lastElement = _.last(args); // 139
sub.identifier = this._createIdentifier(args); // 140
// 141
if(!lastElement) { // 142
args.push({onError: errorHandlingLogic}); // 143
} else if(typeof lastElement == "function") { // 144
args.pop(); // 145
args.push({onReady: lastElement, onError: errorHandlingLogic}); // 146
} else if(typeof lastElement.onError == "function") { // 147
var originalOnError = lastElement.onError; // 148
lastElement.onError = function(err) { // 149
errorHandlingLogic(err); // 150
originalOnError(err); // 151
}; // 152
} else if(typeof lastElement.onReady == "function") { // 153
lastElement.onError = errorHandlingLogic; // 154
} else { // 155
args.push({onError: errorHandlingLogic}); // 156
} // 157
// 158
function errorHandlingLogic (err) { // 159
console.log("Error invoking SubsManager.subscribe(%s): ", sub.identifier , err.reason); // 160
// expire this sub right away. // 161
// Then expiration machanism will take care of the sub removal // 162
sub.updated = new Date(1); // 163
} // 164
}; // 165
// 166
SubsManager.prototype.reset = function() { // 167
var self = this; // 168
var oldComputation = self.computation; // 169
self.computation = self._registerComputation(); // 170
// 171
// invalidate the new compuation and it will fire new subscriptions // 172
self.computation.invalidate(); // 173
// 174
// after above invalidation completed, fire stop the old computation // 175
// which then send unsub messages // 176
// mergeBox will correct send changed data and there'll be no flicker // 177
Deps.afterFlush(function() { // 178
oldComputation.stop(); // 179
}); // 180
}; // 181
// 182
SubsManager.prototype.clear = function() { // 183
this._cacheList = []; // 184
this._cacheMap = []; // 185
this._reRunSubs(); // 186
}; // 187
//////////////////////////////////////////////////////////////////////////////////////////////
}).call(this);
/* Exports */
if (typeof Package === 'undefined') Package = {};
Package['meteorhacks:subs-manager'] = {
SubsManager: SubsManager
};
})();
//# sourceMappingURL=meteorhacks_subs-manager.js.map
|
/*
* Socks .Element.TextFragment.Em
*
* Copyright (c) 2009 Peter Jihoon Kim
*
* Licensed under the MIT License (MIT-LICENSE.txt)
*
* http://wiki.github.com/petejkim/socks
*
*/
(function(Socks){
Socks.Element.TextFragment.Em = function(parent, style, array) {
this._socks_type = 'Socks.Element.TextFragment.Em';
this._elementId = window.Socks._nextElementId++;
this._parent = parent;
// create style object
this._style = new Socks.Style();
if(array !== undefined) {
this._contents = array;
} else {
this._contents = [];
}
// create element in the memory
this._createElement('em',{fontStyle:'italic'});
//set styles
this.setStyle(style);
};
Socks.Element.TextFragment.Em.prototype = new Socks.Element.TextFragment();
})(window.SOCKS);
|
/**
* List Movie Cinemas Test
* @copyright 2013 Jeremy Worboys
*/
var chai = require('chai');
var request = require('supertest');
var expect = chai.expect;
var app = require('../app');
describe('List Movie Cinemas', function() {
describe('/movie/:id/cinemas', function() {
beforeEach(function() {
// Disable request signing while running tests
app.disable('signed_requests');
});
it('should return json', function(done) {
request(app)
.get('/movie/4/cinemas')
.expect('content-type', /json/)
.expect(200)
.end(function(err) {
// This global is defined in sql-query@0.1.15
// I have submitted a pull request to the developer which
// can be found at: https://github.com/dresende/node-sql-query/pull/27
delete global.ii;
done(err);
});
});
it('should follow jsend spec', function(done) {
request(app)
.get('/movie/4/cinemas')
.end(function(err, res) {
delete global.ii;
expect(res.body.status).to.equal('success');
expect(res.body.data).to.exist;
expect(res.body.data).to.be.a('object');
expect(res.body.data.cinemas).to.exist;
expect(res.body.data.cinemas).to.be.a('array');
done(err);
});
});
it('should return the list of movies retrieved from the db', function(done) {
request(app)
.get('/movie/4/cinemas')
.end(function(err, res) {
delete global.ii;
expect(res.body.data.cinemas).to.have.length(5);
expect(res.body.data.cinemas[0].id).to.equal(4);
expect(res.body.data.cinemas[1].id).to.equal(15);
expect(res.body.data.cinemas[2].id).to.equal(38);
expect(res.body.data.cinemas[3].id).to.equal(56);
expect(res.body.data.cinemas[4].id).to.equal(59);
done(err);
});
});
});
});
|
var zeros = require("zeros")
var ndarray = require("ndarray")
var fill = require("ndarray-fill")
var conv = require("../index.js")
require("tape")(function(t) {
function checkFunc(shape, f) {
var x = zeros(shape)
fill(x, f)
var vol = conv.array2rle([0,0,0], x)
var y = conv.rle2array(vol, [[0,0,0], shape]).phase
for(var i=0; i<shape[0]; ++i) {
for(var j=0; j<shape[1]; ++j) {
for(var k=0; k<shape[2]; ++k) {
t.equals(x.get(i,j,k), y.get(i,j,k))
}
}
}
}
checkFunc([2,2,2], function(x,y,z) {
return x===0 && y==0 && z==0
})
checkFunc([3, 4, 5], function(x, y, z) {
x -= 2
y -= 2
z -= 2
return x*x+y*y+z*z<3 ? 1 : 0
})
t.end()
})
|
import { createElement as h } from 'react'
import * as events from '../../../../constants/events'
import Input from '../Input'
import Select from '../Select'
import Label from '../Label'
import Spinner from '../Spinner'
import Spacer from '../Spacer'
import Tooltip from '../Tooltip'
import useCreateEvent from '../../api/hooks/events/useCreateEvent'
import useInputs from '../../hooks/useInputs'
import commonModalProps from '../../utils/commonModalProps'
import shortId from '../../utils/shortId'
const ModalEventAdd = (props) => {
const createEvent = useCreateEvent()
const loading = createEvent.loading === true
const [ inputs, onInputChange ] = useInputs({
title: '',
type: events.EVENTS_TYPE_TOTAL_CHART,
})
const onSubmit = async (e) => {
e.preventDefault()
await createEvent.mutate({
variables: {
input: inputs,
},
})
props.closeModal()
}
const titleId = shortId()
const typeId = shortId()
return (
h('form', { className: 'card', onSubmit },
h('div', { className: 'card__inner' },
h(Spacer, { size: 0.5 }),
h(Label, { htmlFor: titleId }, 'Event title'),
h(Input, {
type: 'text',
id: titleId,
required: true,
disabled: loading === true,
focused: true,
placeholder: 'Event title',
value: inputs.title,
onChange: onInputChange('title'),
}),
h('div', { className: 'card__group' },
h(Label, { spacing: false, htmlFor: typeId }, 'Event type'),
h(Tooltip, {}, 'Specifies how the aggregated data will be displayed in the UI. Can be changed at any time.'),
),
h(Select, {
id: typeId,
required: true,
disabled: loading === true,
value: inputs.type,
items: [
{
value: events.EVENTS_TYPE_TOTAL_CHART,
label: 'Chart with total sums',
},
{
value: events.EVENTS_TYPE_AVERAGE_CHART,
label: 'Chart with average values',
},
{
value: events.EVENTS_TYPE_TOTAL_LIST,
label: 'List with total sums',
},
{
value: events.EVENTS_TYPE_AVERAGE_LIST,
label: 'List with average values',
},
],
onChange: onInputChange('type'),
}),
),
h('div', { className: 'card__footer' },
h('button', {
type: 'button',
className: 'card__button link',
onClick: props.closeModal,
}, 'Close'),
h('div', {
className: 'card__separator',
}),
h('button', {
className: 'card__button card__button--primary link color-white',
disabled: loading === true,
}, loading === true ? h(Spinner) : 'Add'),
),
)
)
}
ModalEventAdd.propTypes = {
...commonModalProps,
}
export default ModalEventAdd |
version https://git-lfs.github.com/spec/v1
oid sha256:0b7080a8d786392697188409066d6105ac04a42c2f63c0d8e26651ce3238f23e
size 19701
|
//~ name b130
alert(b130);
//~ component b131.js
|
function syncSearch () {
$("#query2").keyup(function(){
$("#query3").val($("#query2").val());
});
$("#query3").keyup(function(){
$("#query2").val($("#query3").val());
});
} |
var wechat_pay = require('weixin-pay');
var wechat_pay = wechat_pay({
appid: 'wx8c0b9d8b32234d7a',
mch_id: '1296148301',
partner_key: '0C041A15FD88DFBE55844778EFD86918',
pfx: require('fs').readFileSync(__dirname + '/../asset/cert/apiclient_cert.p12'),
});
function getClientIp(req) {
return req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
}
exports.createOrder = function (req, order, callback) {
wechat_pay.getBrandWCPayRequestParams({
openid: req.user.openid,
body: order.service.name,
detail: order.service.name,
out_trade_no: '20161010' + Math.random().toString().substr(2, 10),
total_fee: order.price * 100,
spbill_create_ip: getClientIp(req),
notify_url: 'http://www.meikes.cn/account/pay/notify'
}, callback);
}; |
// # URL helper
// Usage: `{{url}}`, `{{url absolute="true"}}`
//
// Returns the URL for the current object scope i.e. If inside a post scope will return post permalink
// `absolute` flag outputs absolute URL, else URL is relative
var getMetaDataUrl = require('../data/meta/url');
function url(options) {
var absolute = options && options.hash.absolute;
var lang = options.data.root.lang || 'en';
return getMetaDataUrl(this, absolute, lang);
}
module.exports = url;
|
/*
* LeetCode-javascript
* https://github.com/oneRice/LeetCode-javascript
*
* Copyright (c) 2016 oneRice
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
var name_array = require('./problem_resource.js').solution_name;
var findName = require('./problem_resource.js').findPara;
// Auto export the solution function.
grunt.registerTask('autoExport', 'auto export the solution function', function(num) {
if (arguments.length !== 1) {
grunt.warn('Please enter the number of problem.');
return false;
}
var solution_path = 'tmp/solution.js';
if (!grunt.file.exists(solution_path)) {
grunt.log.warn('Source file "' + solution_path + '" not found.');
return false;
}
var src = grunt.file.read(solution_path);
// Add the export statement.
var solution = findName(name_array, num);
if (solution === 'unfound') {
grunt.log.warn('the solution name is unfound.');
return false;
}
src += '\nexports.solution = ' + solution + ';';
// Write the file.
grunt.file.write(solution_path, src);
// Print a success message.
grunt.log.writeln('File "' + solution_path + '" processed.');
});
};
|
angular.module('app').component('slct',{
templateUrl: 'app/template/componentTypes/slct/slct.html',
controller: function(modalCodeFactory){
var ctrl = this;
ctrl.selectOptions = [{
id: 0,
name: 'Option 1'
},{
id: 1,
name: 'Option 2'
},{
id: 2,
name: 'Option 3'
}]
ctrl.selectedOption = 1;
ctrl.onChange = function(){
console.log('selection changed!', ctrl.selectedOption);
}
ctrl.showCode = function(){
modalCodeFactory.showCode('slct');
}
}
}) |
'use strict'
const twilio = require('twilio')
const async = require('async')
/* client for Twilio TaskRouter */
const taskrouterClient = new twilio.TaskRouterClient(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_AUTH_TOKEN,
process.env.TWILIO_WORKSPACE_SID)
/* client for Twilio IP Chat */
const chatClient = new twilio.IpMessagingClient(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_AUTH_TOKEN)
module.exports.createCallback = function (req, res) {
taskrouterClient.workspace.tasks.create({
WorkflowSid: req.configuration.twilio.workflowSid,
attributes: JSON.stringify(req.body),
timeout: 3600
}, function (err) {
if (err) {
res.status(500).json(err)
} else {
res.status(200).end()
}
})
}
module.exports.createChat = function (req, res) {
/* create a chat room */
async.waterfall([
function (callback) {
/* create token */
var grant = new twilio.AccessToken.IpMessagingGrant({
serviceSid: process.env.TWILIO_IPM_SERVICE_SID,
endpointId: req.body.endpoint
})
var accessToken = new twilio.AccessToken(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_API_KEY,
process.env.TWILIO_API_SECRET,
{ ttl: 3600 })
accessToken.addGrant(grant)
accessToken.identity = req.body.identity
var payload = {
identity: req.body.identity,
token: accessToken.toJwt()
}
callback(null, payload)
}, function (payload, callback) {
/* retrieve ip chat service */
var service = chatClient.services(process.env.TWILIO_IPM_SERVICE_SID)
var uid = Math.random().toString(36).substring(7)
service.channels.create({
friendlyName: 'Support Chat with ' + req.body.identity,
uniqueName: 'support_channel_' + uid
}, function (err, channel) {
if (err) {
callback(err)
} else {
payload.channelSid = channel.sid
callback(null, payload)
}
})
}, function (payload, callback) {
taskrouterClient.workspace.tasks.create({
workflowSid: req.configuration.twilio.workflowSid,
attributes: JSON.stringify({
title: 'Chat request',
text: 'Customer entered chat via support page',
channel: 'chat',
endpoint: 'web',
team: 'support',
name: payload.identity,
channelSid: payload.channelSid
}), timeout: 3600
}, function (err, task) {
if (err) {
callback(err)
} else {
payload.task = task.sid
callback(null, payload)
}
})
}
], function (err, payload) {
if (err) {
console.log(err)
res.status(500).json(err)
return
}
res.status(200).send(payload)
})
} |
/*
* Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
define(function (require, exports) {
"use strict";
var Promise = require("bluebird"),
_ = require("lodash");
var adapter = require("adapter"),
ps = require("adapter").ps,
ui = require("adapter").ps.ui,
descriptor = require("adapter").ps.descriptor;
var events = require("js/events"),
locks = require("js/locks"),
system = require("js/util/system"),
objUtil = require("js/util/object"),
nls = require("js/util/nls"),
log = require("js/util/log"),
headlights = require("js/util/headlights"),
policyActions = require("./policy");
var macMenuJSON = require("static/menu-mac.json"),
winMenuJSON = require("static/menu-win.json"),
rawShortcuts = require("js/util/shortcuts"),
rawMenuActions = require("static/menu-actions.json"),
rawTemplates = require("static/templates.json"),
rawMenuObj = system.isMac ? macMenuJSON : winMenuJSON,
rawMenuShortcuts = rawShortcuts.MENU;
// On debug builds, we always enable cut/copy/paste so they work in dev tools
if (__PG_DEBUG__) {
rawMenuActions.EDIT.CUT["$enable-rule"] = "always";
rawMenuActions.EDIT.COPY["$enable-rule"] = "always";
rawMenuActions.EDIT.PASTE["$enable-rule"] = "always";
}
/**
* List of place command menu IDs.
*
* @private
* @type {number}
*/
var _PLACE_LINKED_MENU_ID = 3090,
_PLACE_EMBEDDED_MENU_ID = 1032;
/**
* Execute a native Photoshop menu command.
*
* @param {{commandID: number, waitForCompletion: boolean=}} payload
* @return {Promise}
*/
var native = function (payload) {
if (!payload.hasOwnProperty("commandID")) {
var error = new Error("Missing native menu command ID");
return Promise.reject(error);
}
var isPlaceCommand = payload.commandID === _PLACE_LINKED_MENU_ID ||
payload.commandID === _PLACE_EMBEDDED_MENU_ID;
return Promise.bind(this)
.then(function () {
// This is a hack for the place linked/embedded menu commands which do not
// seem to promptly emit a toolModalStateChanged:enter event
if (isPlaceCommand) {
this.dispatch(events.menus.PLACE_COMMAND, { executing: true });
if (!this.flux.store("policy").areAllSuspended()) {
return this.transfer(policyActions.suspendAllPolicies);
}
}
})
.then(function () {
// Photoshop expects commandId with a lower case d, so convert here
payload.commandId = payload.commandID;
return ps.performMenuCommand(payload);
})
.then(function (success) {
if (__PG_DEBUG__ && !success) {
log.error("Menu command not available: " + payload.commandID);
}
// Return the menu command result for outer promise chain.
return success;
})
.catch(function (error) {
if (isPlaceCommand) {
// Call the handler for any exceptions to make sure
// the policies are restored and relevent event is dispatched.
return this.transfer(handleExecutedPlaceCommand);
}
// Re-throw the error
throw error;
});
};
native.action = {
reads: locks.ALL_NATIVE_LOCKS,
writes: locks.ALL_NATIVE_LOCKS,
transfers: [policyActions.suspendAllPolicies, "menu.handleExecutedPlaceCommand"]
};
/**
* Execute a native Photoshop menu command modally.
*
* @param {{commandID: number, waitForCompletion: boolean?}} payload
* @return {Promise}
*/
var nativeModal = function (payload) {
return native.call(this, payload);
};
nativeModal.action = {
reads: locks.ALL_NATIVE_LOCKS,
writes: locks.ALL_NATIVE_LOCKS,
modal: true
};
/**
* Open a URL in the user's default browser.
*
* @param {{url: string, category: string, subcategory: string, eventName: string}} payload
* @return {Promise}
*/
var openURL = function (payload) {
if (!payload.hasOwnProperty("url")) {
var error = new Error("Missing URL");
return Promise.reject(error);
}
if (payload.category !== null && payload.subcategory !== null && payload.eventName !== null) {
headlights.logEvent(payload.category, payload.subcategory, payload.eventName);
}
var url = payload.url;
if (payload.localize) {
url = nls.localize(url);
}
return adapter.openURLInDefaultBrowser(url);
};
openURL.action = {
reads: [],
writes: [],
modal: true
};
/**
* Resolve an action path into a callable action function
*
* @private
* @param {string} actionPath
* @return {function()}
*/
var _resolveAction = function (actionPath) {
var actionNameParts = actionPath.split("."),
actionModuleName = actionNameParts[0],
actionName = actionNameParts[1],
actionNameThrottled = actionName + "Throttled",
actionThrottled = objUtil.getPath(this.flux.actions, actionModuleName)[actionNameThrottled];
return actionThrottled;
};
/**
* Call action for menu command
*
* @param {string} commandID
*/
var _playMenuCommand = function (commandID) {
var menuStore = this.flux.store("menu"),
descriptor = menuStore.getApplicationMenu().getMenuAction(commandID);
if (!descriptor) {
log.error("Unknown menu command:", commandID);
return;
}
descriptor = descriptor.toObject();
var action = _resolveAction.call(this, descriptor.$action),
$payload = descriptor.$payload,
$dontLog = descriptor.$dontLog || false,
menuKeys = commandID.split("."),
subcategory = menuKeys.shift(),
event = menuKeys.pop();
if (!$payload || !$payload.preserveFocus) {
window.document.activeElement.blur();
}
if (!$dontLog) {
headlights.logEvent("menu", subcategory, _.kebabCase(event));
}
action($payload);
};
/**
* This handler will be triggered when the user confirm or cancel the new layer
* created from the place-linked or place-embedded menu item.
*
* @return {Promise}
*/
var handleExecutedPlaceCommand = function () {
return this.dispatchAsync(events.menus.PLACE_COMMAND, { executing: false })
.bind(this)
.then(function () {
if (this.flux.store("policy").areAllSuspended()) {
return this.transfer(policyActions.restoreAllPolicies);
}
});
};
handleExecutedPlaceCommand.action = {
reads: [],
writes: [locks.JS_MENU, locks.PS_MENU],
transfers: [policyActions.restoreAllPolicies]
};
/**
* Event handlers initialized in beforeStartup.
*
* @private
* @type {function()}
*/
var _menuChangeHandler,
_adapterMenuHandler,
_toolModalStateChangedHandler;
/**
* Loads menu descriptors, installs menu handlers and a menu store listener
* to reload menus
*
* @return {Promise}
*/
var beforeStartup = function () {
// We listen to menu store directly from this action
// and reload menus, menu store emits change events
// only when the menus actually have changed
_menuChangeHandler = function () {
var menuStore = this.flux.store("menu"),
appMenu = menuStore.getApplicationMenu();
if (appMenu !== null) {
var menuDescriptor = appMenu.getMenuDescriptor();
ui.installMenu(menuDescriptor)
.catch(function (err) {
log.warn("Failed to install menu: ", err, menuDescriptor);
});
}
}.bind(this);
this.flux.store("menu").on("change", _menuChangeHandler);
if (!__PG_DEBUG__) {
_.remove(rawMenuObj.menu, function (menu) {
return menu.id === "DEBUG";
});
}
// Menu store waits for this event to parse descriptors
this.dispatch(events.menus.INIT_MENUS, {
menus: rawMenuObj,
shortcuts: rawMenuShortcuts,
templates: rawTemplates,
actions: rawMenuActions
});
// Menu item clicks come to us from Photoshop through this event
var controller = this.controller;
_adapterMenuHandler = function (payload) {
if (!controller.active) {
return;
}
_playMenuCommand.call(this, payload.command);
}.bind(this);
ui.on("menu", _adapterMenuHandler);
_toolModalStateChangedHandler = function (event) {
var isExecutingPlaceCommand = this.flux.store("menu").getState().isExecutingPlaceCommand,
modalStateEnded = event.state && event.state._value === "exit";
if (isExecutingPlaceCommand && modalStateEnded) {
this.flux.actions.menu.handleExecutedPlaceCommand();
}
}.bind(this);
descriptor.addListener("toolModalStateChanged", _toolModalStateChangedHandler);
return Promise.resolve();
};
beforeStartup.action = {
reads: [],
writes: [locks.JS_MENU, locks.PS_MENU]
};
/**
* Send info about menu commands to search store
*
* @return {Promise}
*/
var afterStartup = function () {
return this.transfer("search.commands.registerMenuCommandSearch");
};
afterStartup.action = {
reads: [],
writes: [],
transfers: ["search.commands.registerMenuCommandSearch"]
};
/**
* Remove event handlers.
*
* @private
* @return {Promise}
*/
var onReset = function () {
ui.removeListener("menu", _adapterMenuHandler);
this.flux.store("menu").removeListener("change", _menuChangeHandler);
descriptor.removeListener("toolModalStateChanged", _toolModalStateChangedHandler);
return Promise.resolve();
};
onReset.action = {
reads: [],
writes: []
};
exports.native = native;
exports.nativeModal = nativeModal;
exports.openURL = openURL;
exports.handleExecutedPlaceCommand = handleExecutedPlaceCommand;
exports._playMenuCommand = _playMenuCommand;
exports.beforeStartup = beforeStartup;
exports.afterStartup = afterStartup;
exports.onReset = onReset;
});
|
import defaultComparator from './alphabetical';
export default function(property, comparator) {
comparator = comparator || defaultComparator;
return function(a, b) {
return comparator(a[property], b[property]);
};
};
|
function noFit () {
device.style.transform = '';
device.style.transformOrigin = '';
}
function toggleFit () {
if (!device.style.transform) {
device.style.transform = 'scale(' + window.innerHeight/device.offsetHeight + ')';
device.style.transformOrigin = '50% 0px';
} else {
device.style.transform = '';
device.style.transformOrigin = '';
}
}
function needFit () {
if (window.innerHeight < device.offsetHeight) {
fit.classList.remove('hidden');
} else {
fit.classList.add('hidden');
}
}
fit.onclick = function () {
toggleFit();
};
|
class ncprov_ncprovider_1 {
constructor() {
}
// System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateObjRef() {
}
// bool Equals(System.Object obj)
Equals() {
}
// int GetHashCode()
GetHashCode() {
}
// System.Object GetLifetimeService()
GetLifetimeService() {
}
// type GetType()
GetType() {
}
// System.Object InitializeLifetimeService()
InitializeLifetimeService() {
}
// string ToString()
ToString() {
}
}
module.exports = ncprov_ncprovider_1;
|
// init time
export function initTimeDate() {
const date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
return date;
}
// zero fill
export function fixString(str) {
str = "" + str;
return str.length <= 1? "0" + str : str;
}
const maps = {
'yyyy': date => date.getFullYear(),
'MM': date => fixString(date.getMonth() + 1),
'dd': date => fixString(date.getDate()),
'HH': date => fixString(date.getHours()),
'mm': date => fixString(date.getMinutes()),
'ss': date => fixString(date.getSeconds())
};
// datetime format
export function handleFormat(value, format = "yyyy-MM-dd HH:mm:ss") {
const trunk = new RegExp(Object.keys(maps).join('|'),'g');
value = new Date(value);
return format.replace(trunk, (capture) => {
return maps[capture]? maps[capture](value): "";
});
}
const SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
const MOZ_HACK_REGEXP = /^moz([A-Z])/;
function camelCase(name) {
return name.replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).replace(MOZ_HACK_REGEXP, 'Moz$1');
}
// getStyle
export function getStyle (element, styleName) {
if (!element || !styleName) return null;
styleName = camelCase(styleName);
if (styleName === 'float') {
styleName = 'cssFloat';
}
try {
const computed = document.defaultView.getComputedStyle(element, '');
return element.style[styleName] || computed ? computed[styleName] : null;
} catch(e) {
return element.style[styleName];
}
}
// judge type
export function typeOf(obj) {
const toString = Object.prototype.toString;
const map = {
'[object Boolean]' : 'boolean',
'[object Number]' : 'number',
'[object String]' : 'string',
'[object Function]' : 'function',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object RegExp]' : 'regExp',
'[object Undefined]': 'undefined',
'[object Null]' : 'null',
'[object Object]' : 'object'
};
return map[toString.call(obj)];
}
// deepCopy
export function deepCopy(data) {
const t = typeOf(data);
let o;
if (t === 'array') {
o = [];
} else if ( t === 'object') {
o = {};
} else {
return data;
}
if (t === 'array') {
for (let i = 0; i < data.length; i++) {
o.push(deepCopy(data[i]));
}
} else if ( t === 'object') {
for (let i in data) {
o[i] = deepCopy(data[i]);
}
}
return o;
}
//debounce
export function debounce(fn) {
let waiting;
return function() {
if (waiting) return;
waiting = true;
const context = this,
args = arguments;
const later = function() {
waiting = false;
fn.apply(context, args);
};
this.$nextTick(later);
};
}
// Find components upward
export function findComponentUpward (context, componentName, componentNames) {
if (typeof componentName === 'string') {
componentNames = [componentName];
} else {
componentNames = componentName;
}
let parent = context.$parent;
let name = parent.$options.name;
while (parent && (!name || componentNames.indexOf(name) < 0)) {
parent = parent.$parent;
if (parent) name = parent.$options.name;
}
return parent;
}
// Find component downward
export function findComponentDownward (context, componentName) {
const childrens = context.$children;
let children = null;
if (childrens.length) {
for (const child of childrens) {
const name = child.$options.name;
if (name === componentName) {
children = child;
break;
} else {
children = findComponentDownward(child, componentName);
if (children) break;
}
}
}
return children;
}
// Find components downward
export function findComponentsDownward (context, componentName) {
return context.$children.reduce((components, child) => {
if (child.$options.name === componentName) components.push(child);
const foundChilds = findComponentsDownward(child, componentName);
return components.concat(foundChilds);
}, []);
}
// scrollTop animation
export function scrollTop(el, from = 0, to, duration = 500) {
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
return window.setTimeout(callback, 1000/60);
}
);
}
const difference = Math.abs(from - to);
const step = Math.ceil(difference / duration * 50);
function scroll(start, end, step) {
if (start === end) return;
let d = (start + step > end) ? end : start + step;
if (start > end) {
d = (start - step < end) ? end : start - step;
}
if (el === window) {
window.scrollTo(d, d);
} else {
el.scrollTop = d;
}
window.requestAnimationFrame(() => scroll(d, end, step));
}
scroll(from, to, step);
}
|
var classhryky_1_1uri_1_1query_1_1_entity =
[
[ "heap_type", "classhryky_1_1uri_1_1query_1_1_entity.html#a6a87c9ead5b29c94ff56dc2c97f9d89d", null ],
[ "octets_type", "classhryky_1_1uri_1_1query_1_1_entity.html#afaaea8b9a51297cfc0aee68afacdd91a", null ],
[ "this_type", "classhryky_1_1uri_1_1query_1_1_entity.html#a169f59d5b5b0d125a9128047e916f802", null ],
[ "Entity", "classhryky_1_1uri_1_1query_1_1_entity.html#a065c41d80b72bba5eb28d364fd143886", null ],
[ "Entity", "classhryky_1_1uri_1_1query_1_1_entity.html#a71d821dc298c409421f0c9a3a3904a37", null ],
[ "Entity", "classhryky_1_1uri_1_1query_1_1_entity.html#abc2d9b2d91a67dff58b7e0b9754f1d91", null ],
[ "Entity", "classhryky_1_1uri_1_1query_1_1_entity.html#a6b90e5da838efee6e939091ffd5e58fd", null ],
[ "Entity", "classhryky_1_1uri_1_1query_1_1_entity.html#a250b93519f4d1b9973a3208acc3eae8b", null ],
[ "~Entity", "classhryky_1_1uri_1_1query_1_1_entity.html#ae8f69fb92a256a0779c519875a458a09", null ],
[ "append", "classhryky_1_1uri_1_1query_1_1_entity.html#ac77ae66d43c86f31e6e02c300ec215a4", null ],
[ "clear", "classhryky_1_1uri_1_1query_1_1_entity.html#a40c836cd4253d074ca72cfa9b8bb513f", null ],
[ "reduce", "classhryky_1_1uri_1_1query_1_1_entity.html#a91a3e23305fa6240b2a19d29f9fe9610", null ],
[ "swap", "classhryky_1_1uri_1_1query_1_1_entity.html#a078a7930cef140ee4a0f01eebb4a2926", null ],
[ "hryky_assign_op", "classhryky_1_1uri_1_1query_1_1_entity.html#a2ae62e94497faafbb1e1aa8ffe2daceb", null ]
]; |
(function() {
"use strict";
var inNodeJS = false;
if (typeof process !== 'undefined' && !process.browser) {
inNodeJS = true;
var request = require('request'.trim()); //prevents browserify from bundling the module
}
var supportsCORS = false;
var inLegacyIE = false;
try {
var testXHR = new XMLHttpRequest();
if (typeof testXHR.withCredentials !== 'undefined') {
supportsCORS = true;
} else {
if ("XDomainRequest" in window) {
supportsCORS = true;
inLegacyIE = true;
}
}
} catch (e) { }
// Create a simple indexOf function for support
// of older browsers. Uses native indexOf if
// available. Code similar to underscores.
// By making a separate function, instead of adding
// to the prototype, we will not break bad for loops
// in older browsers
var indexOfProto = Array.prototype.indexOf;
var ttIndexOf = function(array, item) {
var i = 0, l = array.length;
if (indexOfProto && array.indexOf === indexOfProto) return array.indexOf(item);
for (; i < l; i++) if (array[i] === item) return i;
return -1;
};
/*
Initialize with Tabletop.init( { key: '0AjAPaAU9MeLFdHUxTlJiVVRYNGRJQnRmSnQwTlpoUXc' } )
OR!
Initialize with Tabletop.init( { key: 'https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AjAPaAU9MeLFdHUxTlJiVVRYNGRJQnRmSnQwTlpoUXc&output=html&widget=true' } )
OR!
Initialize with Tabletop.init('0AjAPaAU9MeLFdHUxTlJiVVRYNGRJQnRmSnQwTlpoUXc')
*/
var Tabletop = function(options) {
// Make sure Tabletop is being used as a constructor no matter what.
if(!this || !(this instanceof Tabletop)) {
return new Tabletop(options);
}
if(typeof(options) === 'string') {
options = { key : options };
}
this.callback = options.callback;
this.wanted = options.wanted || [];
this.key = options.key;
this.simpleSheet = !!options.simpleSheet;
this.parseNumbers = !!options.parseNumbers;
this.wait = !!options.wait;
this.reverse = !!options.reverse;
this.postProcess = options.postProcess;
this.debug = !!options.debug;
this.query = options.query || '';
this.orderby = options.orderby;
this.endpoint = options.endpoint || "https://spreadsheets.google.com";
this.singleton = !!options.singleton;
this.simple_url = !!options.simple_url;
this.callbackContext = options.callbackContext;
// Default to on, unless there's a proxy, in which case it's default off
this.prettyColumnNames = typeof(options.prettyColumnNames) == 'undefined' ? !options.proxy : options.prettyColumnNames
if(typeof(options.proxy) !== 'undefined') {
// Remove trailing slash, it will break the app
this.endpoint = options.proxy.replace(/\/$/,'');
this.simple_url = true;
this.singleton = true;
// Let's only use CORS (straight JSON request) when
// fetching straight from Google
supportsCORS = false;
}
this.parameterize = options.parameterize || false;
if(this.singleton) {
if(typeof(Tabletop.singleton) !== 'undefined') {
this.log("WARNING! Tabletop singleton already defined");
}
Tabletop.singleton = this;
}
/* Be friendly about what you accept */
if(/key=/.test(this.key)) {
this.log("You passed an old Google Docs url as the key! Attempting to parse.");
this.key = this.key.match("key=(.*?)(&|#|$)")[1];
}
if(/pubhtml/.test(this.key)) {
this.log("You passed a new Google Spreadsheets url as the key! Attempting to parse.");
this.key = this.key.match("d\\/(.*?)\\/pubhtml")[1];
}
if(/spreadsheets\/d/.test(this.key)) {
this.log("You passed a new Google Spreadsheets url as the key! Attempting to parse.");
this.key = this.key.match("d\\/(.*?)\/")[1];
}
if(!this.key) {
this.log("You need to pass Tabletop a key!");
return;
}
this.log("Initializing with key " + this.key);
this.models = {};
this.model_names = [];
this.base_json_path = "/feeds/worksheets/" + this.key + "/public/basic?alt=";
if (inNodeJS || supportsCORS) {
this.base_json_path += 'json';
} else {
this.base_json_path += 'json-in-script';
}
if(!this.wait) {
this.fetch();
}
};
// A global storage for callbacks.
Tabletop.callbacks = {};
// Backwards compatibility.
Tabletop.init = function(options) {
return new Tabletop(options);
};
Tabletop.sheets = function() {
this.log("Times have changed! You'll want to use var tabletop = Tabletop.init(...); tabletop.sheets(...); instead of Tabletop.sheets(...)");
};
Tabletop.prototype = {
fetch: function(callback) {
if(typeof(callback) !== "undefined") {
this.callback = callback;
}
this.requestData(this.base_json_path, this.loadSheets);
},
/*
This will call the environment appropriate request method.
In browser it will use JSON-P, in node it will use request()
*/
requestData: function(path, callback) {
if (inNodeJS) {
this.serverSideFetch(path, callback);
} else {
//CORS only works in IE8/9 across the same protocol
//You must have your server on HTTPS to talk to Google, or it'll fall back on injection
var protocol = this.endpoint.split("//").shift() || "http";
if (supportsCORS && (!inLegacyIE || protocol === location.protocol)) {
this.xhrFetch(path, callback);
} else {
this.injectScript(path, callback);
}
}
},
/*
Use Cross-Origin XMLHttpRequest to get the data in browsers that support it.
*/
xhrFetch: function(path, callback) {
//support IE8's separate cross-domain object
var xhr = inLegacyIE ? new XDomainRequest() : new XMLHttpRequest();
xhr.open("GET", this.endpoint + path);
var self = this;
xhr.onload = function() {
try {
var json = JSON.parse(xhr.responseText);
} catch (e) {
console.error(e);
}
callback.call(self, json);
};
xhr.send();
},
/*
Insert the URL into the page as a script tag. Once it's loaded the spreadsheet data
it triggers the callback. This helps you avoid cross-domain errors
http://code.google.com/apis/gdata/samples/spreadsheet_sample.html
Let's be plain-Jane and not use jQuery or anything.
*/
injectScript: function(path, callback) {
var script = document.createElement('script');
var callbackName;
if(this.singleton) {
if(callback === this.loadSheets) {
callbackName = 'Tabletop.singleton.loadSheets';
} else if (callback === this.loadSheet) {
callbackName = 'Tabletop.singleton.loadSheet';
}
} else {
var self = this;
callbackName = 'tt' + (+new Date()) + (Math.floor(Math.random()*100000));
// Create a temp callback which will get removed once it has executed,
// this allows multiple instances of Tabletop to coexist.
Tabletop.callbacks[ callbackName ] = function () {
var args = Array.prototype.slice.call( arguments, 0 );
callback.apply(self, args);
script.parentNode.removeChild(script);
delete Tabletop.callbacks[callbackName];
};
callbackName = 'Tabletop.callbacks.' + callbackName;
}
var url = path + "&callback=" + callbackName;
if(this.simple_url) {
// We've gone down a rabbit hole of passing injectScript the path, so let's
// just pull the sheet_id out of the path like the least efficient worker bees
if(path.indexOf("/list/") !== -1) {
script.src = this.endpoint + "/" + this.key + "-" + path.split("/")[4];
} else {
script.src = this.endpoint + "/" + this.key;
}
} else {
script.src = this.endpoint + url;
}
if (this.parameterize) {
script.src = this.parameterize + encodeURIComponent(script.src);
}
document.getElementsByTagName('script')[0].parentNode.appendChild(script);
},
/*
This will only run if tabletop is being run in node.js
*/
serverSideFetch: function(path, callback) {
var self = this
request({url: this.endpoint + path, json: true}, function(err, resp, body) {
if (err) {
return console.error(err);
}
callback.call(self, body);
});
},
/*
Is this a sheet you want to pull?
If { wanted: ["Sheet1"] } has been specified, only Sheet1 is imported
Pulls all sheets if none are specified
*/
isWanted: function(sheetName) {
if(this.wanted.length === 0) {
return true;
} else {
return (ttIndexOf(this.wanted, sheetName) !== -1);
}
},
/*
What gets send to the callback
if simpleSheet === true, then don't return an array of Tabletop.this.models,
only return the first one's elements
*/
data: function() {
// If the instance is being queried before the data's been fetched
// then return undefined.
if(this.model_names.length === 0) {
return undefined;
}
if(this.simpleSheet) {
if(this.model_names.length > 1 && this.debug) {
this.log("WARNING You have more than one sheet but are using simple sheet mode! Don't blame me when something goes wrong.");
}
return this.models[ this.model_names[0] ].all();
} else {
return this.models;
}
},
/*
Add another sheet to the wanted list
*/
addWanted: function(sheet) {
if(ttIndexOf(this.wanted, sheet) === -1) {
this.wanted.push(sheet);
}
},
/*
Load all worksheets of the spreadsheet, turning each into a Tabletop Model.
Need to use injectScript because the worksheet view that you're working from
doesn't actually include the data. The list-based feed (/feeds/list/key..) does, though.
Calls back to loadSheet in order to get the real work done.
Used as a callback for the worksheet-based JSON
*/
loadSheets: function(data) {
var i, ilen;
var toLoad = [];
if (!data) {
alert('Google spreadsheet could not be loaded');
return;
}
this.googleSheetName = data.feed.title.$t;
this.foundSheetNames = [];
for(i = 0, ilen = data.feed.entry.length; i < ilen ; i++) {
this.foundSheetNames.push(data.feed.entry[i].title.$t);
// Only pull in desired sheets to reduce loading
if( this.isWanted(data.feed.entry[i].content.$t) ) {
var linkIdx = data.feed.entry[i].link.length-1;
var sheet_id = data.feed.entry[i].link[linkIdx].href.split('/').pop();
var json_path = "/feeds/list/" + this.key + "/" + sheet_id + "/public/values?alt="
if (inNodeJS || supportsCORS) {
json_path += 'json';
} else {
json_path += 'json-in-script';
}
if(this.query) {
json_path += "&sq=" + this.query;
}
if(this.orderby) {
json_path += "&orderby=column:" + this.orderby.toLowerCase();
}
if(this.reverse) {
json_path += "&reverse=true";
}
toLoad.push(json_path);
}
}
this.sheetsToLoad = toLoad.length;
for(i = 0, ilen = toLoad.length; i < ilen; i++) {
this.requestData(toLoad[i], this.loadSheet);
}
},
/*
Access layer for the this.models
.sheets() gets you all of the sheets
.sheets('Sheet1') gets you the sheet named Sheet1
*/
sheets: function(sheetName) {
if(typeof sheetName === "undefined") {
return this.models;
} else {
if(typeof(this.models[ sheetName ]) === "undefined") {
// alert( "Can't find " + sheetName );
return;
} else {
return this.models[ sheetName ];
}
}
},
sheetReady: function(model) {
this.models[ model.name ] = model;
if(ttIndexOf(this.model_names, model.name) === -1) {
this.model_names.push(model.name);
}
this.sheetsToLoad--;
if(this.sheetsToLoad === 0)
this.doCallback();
},
/*
Parse a single list-based worksheet, turning it into a Tabletop Model
Used as a callback for the list-based JSON
*/
loadSheet: function(data) {
var that = this;
var model = new Tabletop.Model( { data: data,
parseNumbers: this.parseNumbers,
postProcess: this.postProcess,
tabletop: this,
prettyColumnNames: this.prettyColumnNames,
onReady: function() {
that.sheetReady(this);
} } );
},
/*
Execute the callback upon loading! Rely on this.data() because you might
only request certain pieces of data (i.e. simpleSheet mode)
Tests this.sheetsToLoad just in case a race condition happens to show up
*/
doCallback: function() {
if(this.sheetsToLoad === 0) {
this.callback.apply(this.callbackContext || this, [this.data(), this]);
}
},
log: function(msg) {
if(this.debug) {
if(typeof console !== "undefined" && typeof console.log !== "undefined") {
Function.prototype.apply.apply(console.log, [console, arguments]);
}
}
}
};
/*
Tabletop.Model stores the attribute names and parses the worksheet data
to turn it into something worthwhile
Options should be in the format { data: XXX }, with XXX being the list-based worksheet
*/
Tabletop.Model = function(options) {
var i, j, ilen, jlen;
this.column_names = [];
this.name = options.data.feed.title.$t;
this.tabletop = options.tabletop;
this.elements = [];
this.onReady = options.onReady;
this.raw = options.data; // A copy of the sheet's raw data, for accessing minutiae
if(typeof(options.data.feed.entry) === 'undefined') {
options.tabletop.log("Missing data for " + this.name + ", make sure you didn't forget column headers");
this.original_columns = [];
this.elements = [];
this.onReady.call(this);
return;
}
for(var key in options.data.feed.entry[0]){
if(/^gsx/.test(key))
this.column_names.push( key.replace("gsx$","") );
}
this.original_columns = this.column_names;
for(i = 0, ilen = options.data.feed.entry.length ; i < ilen; i++) {
var source = options.data.feed.entry[i];
var element = {};
for(var j = 0, jlen = this.column_names.length; j < jlen ; j++) {
var cell = source[ "gsx$" + this.column_names[j] ];
if (typeof(cell) !== 'undefined') {
if(options.parseNumbers && cell.$t !== '' && !isNaN(cell.$t))
element[ this.column_names[j] ] = +cell.$t;
else
element[ this.column_names[j] ] = cell.$t;
} else {
element[ this.column_names[j] ] = '';
}
}
if(element.rowNumber === undefined)
element.rowNumber = i + 1;
if( options.postProcess )
options.postProcess(element);
this.elements.push(element);
}
if(options.prettyColumnNames)
this.fetchPrettyColumns();
else
this.onReady.call(this);
};
Tabletop.Model.prototype = {
/*
Returns all of the elements (rows) of the worksheet as objects
*/
all: function() {
return this.elements;
},
fetchPrettyColumns: function() {
if(!this.raw.feed.link[3])
return this.ready();
var cellurl = this.raw.feed.link[3].href.replace('/feeds/list/', '/feeds/cells/').replace('https://spreadsheets.google.com', '');
var that = this;
this.tabletop.requestData(cellurl, function(data) {
that.loadPrettyColumns(data)
});
},
ready: function() {
this.onReady.call(this);
},
/*
* Store column names as an object
* with keys of Google-formatted "columnName"
* and values of human-readable "Column name"
*/
loadPrettyColumns: function(data) {
var pretty_columns = {};
var column_names = this.column_names;
var i = 0;
var l = column_names.length;
for (; i < l; i++) {
if (typeof data.feed.entry[i].content.$t !== 'undefined') {
pretty_columns[column_names[i]] = data.feed.entry[i].content.$t;
} else {
pretty_columns[column_names[i]] = column_names[i];
}
}
this.pretty_columns = pretty_columns;
this.prettifyElements();
this.ready();
},
/*
* Go through each row, substitutiting
* Google-formatted "columnName"
* with human-readable "Column name"
*/
prettifyElements: function() {
var pretty_elements = [],
ordered_pretty_names = [],
i, j, ilen, jlen;
var ordered_pretty_names;
for(j = 0, jlen = this.column_names.length; j < jlen ; j++) {
ordered_pretty_names.push(this.pretty_columns[this.column_names[j]]);
}
for(i = 0, ilen = this.elements.length; i < ilen; i++) {
var new_element = {};
for(j = 0, jlen = this.column_names.length; j < jlen ; j++) {
var new_column_name = this.pretty_columns[this.column_names[j]];
new_element[new_column_name] = this.elements[i][this.column_names[j]];
}
pretty_elements.push(new_element);
}
this.elements = pretty_elements;
this.column_names = ordered_pretty_names;
},
/*
Return the elements as an array of arrays, instead of an array of objects
*/
toArray: function() {
var array = [],
i, j, ilen, jlen;
for(i = 0, ilen = this.elements.length; i < ilen; i++) {
var row = [];
for(j = 0, jlen = this.column_names.length; j < jlen ; j++) {
row.push( this.elements[i][ this.column_names[j] ] );
}
array.push(row);
}
return array;
}
};
if(typeof module !== "undefined" && module.exports) { //don't just use inNodeJS, we may be in Browserify
module.exports = Tabletop;
} else if (typeof define === 'function' && define.amd) {
define(function () {
return Tabletop;
});
} else {
window.Tabletop = Tabletop;
}
})();
|
export const ic_laptop_twotone = {"viewBox":"0 0 24 24","children":[{"name":"g","attribs":{},"children":[{"name":"rect","attribs":{"fill":"none","height":"24","width":"24","x":"0"},"children":[{"name":"rect","attribs":{"fill":"none","height":"24","width":"24","x":"0"},"children":[]}]}]},{"name":"g","attribs":{},"children":[{"name":"g","attribs":{},"children":[{"name":"g","attribs":{},"children":[{"name":"path","attribs":{"d":"M4,6h16v10H4V6z","enable-background":"new","opacity":".3"},"children":[{"name":"path","attribs":{"d":"M4,6h16v10H4V6z","enable-background":"new","opacity":".3"},"children":[]}]},{"name":"path","attribs":{"d":"M20,18c1.1,0,2-0.9,2-2V6c0-1.1-0.9-2-2-2H4C2.9,4,2,4.9,2,6v10c0,1.1,0.9,2,2,2H0v2h24v-2H20z M4,6h16v10H4V6z"},"children":[{"name":"path","attribs":{"d":"M20,18c1.1,0,2-0.9,2-2V6c0-1.1-0.9-2-2-2H4C2.9,4,2,4.9,2,6v10c0,1.1,0.9,2,2,2H0v2h24v-2H20z M4,6h16v10H4V6z"},"children":[]}]}]}]}]}]}; |
'use strict';
var express = require('express'),
router = express.Router(),
request = require('request'),
imagesize = require('imagesize');
module.exports = function(){
return router
.post('/',function(req,res,next){
var stream = request
.get(req.body.image.src)
.on('error',function(err){
console.log(err);
res.status(422).json({ error: err });
});
imagesize(stream, function (err, result) {
if(err){ return next(err); }
res.json({ meta: result }); // {type, width, height}
});
});
};
|
var mongoose = require('mongoose')
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/crawlerStage5')
exports.SpiderDate = mongoose.model('SpiderDate', require('./spiderDate')) |
Package()
.use('tupai.Application')
.use('Config')
.run(function(cp){
console.log('run');
var app = new cp.Application({
window: {
routes: cp.Config['routes']
},
cacheManager: cp.Config['cache_manager'],
apiManagers: cp.Config['api_managers'],
apiManager: cp.Config['api_manager'],
});
app.show('/root/list');
});
|
/* eslint key-spacing:0 spaced-comment:0 */
import _debug from 'debug'
import path from 'path'
import { argv } from 'yargs'
const debug = _debug('app:config:_base')
const config = {
env : process.env.NODE_ENV,
// ----------------------------------
// Project Structure
// ----------------------------------
path_base : path.resolve(__dirname, '../'),
dir_client : 'src',
dir_dist : 'dist',
dir_server : 'server',
dir_test : 'tests',
// ----------------------------------
// Server Configuration
// ----------------------------------
server_host : 'localhost',
server_port : process.env.PORT || 3000,
// ----------------------------------
// Compiler Configuration
// ----------------------------------
compiler_css_modules : false,
compiler_enable_hmr : false,
compiler_source_maps : true,
compiler_hash_type : 'hash',
compiler_fail_on_warning : false,
compiler_quiet : false,
compiler_public_path : './',
compiler_stats : {
chunks : false,
chunkModules : false,
colors : true
},
compiler_vendor : [
'history',
'react',
'react-redux',
'react-router',
'redux',
'redux-actions',
'redux-simple-router'
],
// ----------------------------------
// Test Configuration
// ----------------------------------
coverage_enabled : !argv.watch,
coverage_reporters : [
{ type : 'text-summary' },
{ type : 'html', dir : 'coverage' }
]
}
/************************************************
-------------------------------------------------
All Internal Configuration Below
Edit at Your Own Risk
-------------------------------------------------
************************************************/
// ------------------------------------
// Environment
// ------------------------------------
config.globals = {
'process.env' : {
'NODE_ENV' : JSON.stringify(config.env)
},
'NODE_ENV' : config.env,
'__DEV__' : config.env === 'development',
'__PROD__' : config.env === 'production',
'__DEBUG__' : config.env === 'development' && !argv.no_debug,
'__DEBUG_NEW_WINDOW__' : !!argv.nw
}
// ------------------------------------
// Validate Vendor Dependencies
// ------------------------------------
const pkg = require('../package.json')
config.compiler_vendor = config.compiler_vendor
.filter(dep => {
if (pkg.dependencies[dep]) return true
debug(
`Package "${dep}" was not found as an npm dependency in package.json; ` +
`it won't be included in the webpack vendor bundle.\n` +
`Consider removing it from vendor_dependencies in ~/config/index.js`
)
})
// ------------------------------------
// Utilities
// ------------------------------------
config.utils_paths = (() => {
const resolve = path.resolve
const base = (...args) =>
resolve.apply(resolve, [config.path_base, ...args])
return {
base : base,
client : base.bind(null, config.dir_client),
dist : base.bind(null, config.dir_dist)
}
})()
export default config
|
var gulp = require('gulp');
var appDev = 'assets/app/';
var appProd = 'public/js/app/';
/* JS & TS */
var jsuglify = require('gulp-uglify');
var typescript = require('gulp-typescript');
var sourcemaps = require('gulp-sourcemaps');
// Other
var concat = require('gulp-concat');
var tsProject = typescript.createProject('tsconfig.json');
gulp.task('build-ts', function () {
return gulp.src(appDev + '**/*.ts')
.pipe(sourcemaps.init())
.pipe(typescript(tsProject))
.pipe(sourcemaps.write())
// .pipe(jsuglify())
.pipe(concat('bundle.js'))
.pipe(gulp.dest(appProd));
});
gulp.task('watch', function () {
gulp.watch(appDev + '**/*.ts', ['build-ts']);
});
gulp.task('default', ['watch', 'build-ts']); |
/**
* freeCodeCamp Front End Algorithm Challenges
* @author Heather K.
*/
// Return Largest Numbers from an Array's Subarrays
function largestOfFour(arr) {
// Inputs an array of subarrays (1 level), outputs an array of the largest values from each subarray
var maxVal;
var maxArr = [];
for (var i = 0; i < arr.length; i++) {
maxVal = 0;
for (var j = 0; j < arr[i].length; j++) {
if (arr[i][j] > maxVal) {
maxVal = arr[i][j];
}
}
maxArr.push(maxVal);
}
//console.log(maxArr);
return maxArr;
}
function largestOfFourTest() {
// Test suite for titleCase
var item1 = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
var test1 = largestOfFour(item1);
var result1 = true;
if (Array.isArray(test1) == result1) {
console.log("PASS", item1, "returned an array");
} else {
console.log("FAIL", item1, "should return an array");
}
var item2 = [[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]];
var test2 = largestOfFour(item2);
var result2 = [27,5,39,1001];
if (JSON.stringify(test2) == JSON.stringify(result2)) {
console.log("PASS", item2, "returned", result2);
} else {
console.log("FAIL", item2, "should return", result2);
}
var item3 = [[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]];
var test3 = largestOfFour(item3);
var result3 = [9, 35, 97, 1000000];
if (JSON.stringify(test3) == JSON.stringify(result3)) {
console.log("PASS", item3, "returned", result3);
} else {
console.log("FAIL", item3, "should return", result3);
}
}
largestOfFourTest();
|
var gulp = require('gulp');
var compiler = require('gulp-hogan-compile');
gulp.task('templates', function () {
return gulp.src('src/templates/*.html')
.pipe(compiler('templates.js', {
wrapper: 'commonjs',
hoganModule: 'hogan.js/lib/template.js'
}))
.pipe(gulp.dest('./build'));
});
|
/*!
Copyright (C) 2015 by WebReflection
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*! a zero hassle wrapper for sqlite by Andrea Giammarchi !*/
var
isArray = Array.isArray,
// used to generate unique "end of the query" identifiers
crypto = require('crypto'),
// relative, absolute, and db paths are normalized anyway
path = require('path'),
// each dblite(fileName) instance is an EventEmitter
EventEmitter = require('events').EventEmitter,
// used to perform some fallback
WIN32 = process.platform === 'win32',
// what kind of Path Separator we have here ?
PATH_SEP = path.sep || (
WIN32 ? '\\' : '/'
),
// each dblite instance spawns a process once
// and interact with that shell for the whole session
// one spawn per database and no more (on avg 1 db is it)
spawn = require('child_process').spawn,
// use to re-generate Date objects
DECIMAL = /^[1-9][0-9]*$/,
// verify if it's a select or not
SELECT = /^\s*(?:select|SELECT|pragma|PRAGMA|with|WITH) /,
// for simple query replacements: WHERE field = ?
REPLACE_QUESTIONMARKS = /\?/g,
// for named replacements: WHERE field = :data
REPLACE_PARAMS = /(?:\:|\@|\$)([a-zA-Z0-9_$]+)/g,
// the way CSV threats double quotes
DOUBLE_DOUBLE_QUOTES = /""/g,
// to escape strings
SINGLE_QUOTES = /'/g,
// to use same escaping logic for double quotes
// except it makes escaping easier for JSON data
// which usually is full of "
SINGLE_QUOTES_DOUBLED = "''",
// to verify there are named fields/parametes
HAS_PARAMS = /(?:\?|(?:(?:\:|\@|\$)[a-zA-Z0-9_$]+))/,
// shortcut used as deafault notifier
log = console.log.bind(console),
// the default binary as array of paths
bin = ['sqlite3'],
// private shared variables
// avoid creation of N functions
// keeps memory low and improves performance
paramsIndex, // which index is the current
paramsArray, // which value when Array
paramsObject, // which value when Object (named parameters)
IS_NODE_06 = false, // dirty things to do there ...
// defned later on
EOL, EOL_LENGTH,
SANITIZER, SANITIZER_REPLACER,
waitForEOLToBeDefined = [],
createProgram = function () {
for (var args = [], i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
return spawn(
// executable only, folder needs to be specified a part
bin.length === 1 ? bin[0] : ('.' + PATH_SEP + bin[bin.length - 1]),
// normalize file path if not :memory:
normalizeFirstArgument(
// it is possible to eventually send extra sqlite3 args
// so all arguments are passed
args
).concat('-csv') // but the output MUST be csv
.reverse(), // see https://github.com/WebReflection/dblite/pull/12
// be sure the dir is the right one
{
// the right folder is important or sqlite3 won't work
cwd: bin.slice(0, -1).join(PATH_SEP) || process.cwd(),
env: process.env, // same env is OK
encoding: 'utf8', // utf8 is OK
stdio: ['pipe', 'pipe', 'pipe'] // handled here
}
);
},
defineCSVEOL = function (fn) {
if (waitForEOLToBeDefined.push(fn) === 1) {
var
program = createProgram(':memory:', '-noheader'),
ondata = function (data) {
setUpAndGo(data.toString().slice(1));
},
// save the Mac, SAVE THE MAC!!!
// error could occur due \r\n
// so clearly that won't be the right EOL
onerror = function () {
setUpAndGo('\n');
},
setUpAndGo = function (eol) {
// habemus EOL \o/
EOL = eol;
// what's EOL length? Used to properly parse data
EOL_LENGTH = EOL.length;
// makes EOL safe for strings passed to the shell
SANITIZER = new RegExp("[;" + EOL.split('').map(function(c) {
return '\\x' + ('0' + c.charCodeAt(0).toString(16)).slice(-2);
}).join('') + "]+$");
// used to mark the end of each line passed to the shell
SANITIZER_REPLACER = ';' + EOL;
// once closed, reassign this helper
// and trigger all queued functions
program.on('close', function () {
defineCSVEOL = function (fn) { fn(); };
waitForEOLToBeDefined
.splice(0, waitForEOLToBeDefined.length)
.forEach(defineCSVEOL);
});
program.kill();
}
;
program.stdout.on('data', ondata);
program.stdin.on('error', onerror);
program.stdout.on('error', onerror);
program.stderr.on('error', onerror);
program.stdin.write('SELECT 1;\r\n');
}
}
;
/**
* var db = dblite('filename.sqlite'):EventEmitter;
*
* db.query( thismethod has **many** overloads where almost everything is optional
*
* SQL:string, only necessary field. Accepts a query or a command such `.databases`
*
* params:Array|Object, optional, if specified replaces SQL parts with this object
* db.query('INSERT INTO table VALUES(?, ?)', [null, 'content']);
* db.query('INSERT INTO table VALUES(:id, :value)', {id:null, value:'content'});
*
* fields:Array|Object, optional, if specified is used to normalize the query result with named fields.
* db.query('SELECT table.a, table.other FROM table', ['a', 'b']);
* [{a:'first value', b:'second'},{a:'row2 value', b:'row2'}]
*
*
* db.query('SELECT table.a, table.other FROM table', ['a', 'b']);
* [{a:'first value', b:'second'},{a:'row2 value', b:'row2'}]
* callback:Function
* );
*/
function dblite() {
var
args = arguments,
// the current dblite "instance"
self = new EventEmitter(),
// the incrementally concatenated buffer
// cleaned up as soon as the current command has been completed
selectResult = '',
// sqlite3 shell can produce one output per time
// every operation performed through this wrapper
// should not bother the program until next
// available slot. This queue helps keeping
// requests ordered without stressing the system
// once things will be ready, callbacks will be notified
// accordingly. As simple as that ^_^
queue = [],
// set as true only once db.close() has been called
notWorking = false,
// marks the shell busy or not
// initially we need to wait for the EOL
// so it's busy by default
busy = true,
// tells if current output needs to be processed
wasSelect = false,
wasNotSelect = false,
wasError = false,
// forces the output not to be processed
// might be handy in some case where it's passed around
// as string instread of needing to serialize/unserialize
// the list of already arrays or objects
dontParseCSV = false,
// one callback per time will be notified
$callback,
// recycled variable for fields operation
$fields,
// this will be the delimiter of each sqlite3 shell command
SUPER_SECRET,
SUPER_SECRET_SELECT,
SUPER_SECRET_LENGTH,
// the spawned program
program
;
defineCSVEOL(function () {
// this is the delimiter of each sqlite3 shell command
SUPER_SECRET = '---' +
crypto.randomBytes(64).toString('base64') +
'---';
// ... I wish .print was introduced before SQLite 3.7.10 ...
// this is a weird way to get rid of the header, if enabled
SUPER_SECRET_SELECT = '"' + SUPER_SECRET + '" AS "' + SUPER_SECRET + '";' + EOL;
// used to check the end of a buffer
SUPER_SECRET_LENGTH = -(SUPER_SECRET.length + EOL_LENGTH);
// add the EOL to the secret
SUPER_SECRET += EOL;
// define the spawn program
program = createProgram.apply(null, args);
// and all its IO handled here
program.stderr.on('data', onerror);
program.stdin.on('error', onerror);
program.stdout.on('error', onerror);
program.stderr.on('error', onerror);
// invoked each time the sqlite3 shell produces an output
program.stdout.on('data', function (data) {
/*jshint eqnull: true*/
// big output might require more than a call
var str, result, callback, fields, headers, wasSelectLocal, rows, dpcsv;
if (wasError) {
selectResult = '';
wasError = false;
if (self.ignoreErrors) {
busy = false;
next();
}
return;
}
// the whole output is converted into a string here
selectResult += data;
// if the end of the output is the serapator
if (selectResult.slice(SUPER_SECRET_LENGTH) === SUPER_SECRET) {
// time to move forward since sqlite3 has done
str = selectResult.slice(0, SUPER_SECRET_LENGTH);
// drop the secret header if present
headers = str.slice(SUPER_SECRET_LENGTH) === SUPER_SECRET;
if (headers) str = str.slice(0, SUPER_SECRET_LENGTH);
// clean up the outer variabls
selectResult = '';
// makes the spawned program not busy anymore
busy = false;
// if it was a select
if (wasSelect || wasNotSelect) {
wasSelectLocal = wasSelect;
dpcsv = dontParseCSV;
// set as false all conditions
// only here dontParseCSV could have been true
// set to false that too
wasSelect = wasNotSelect = dontParseCSV = busy;
// which callback should be invoked?
// last expected one for this round
callback = $callback;
// same as fields
fields = $fields;
// parse only if it was a select/pragma
if (wasSelectLocal) {
// unless specified, process the string
// converting the CSV into an Array of rows
result = dpcsv ? str : parseCSV(str);
// if there were headers/fields and we have a result ...
if (headers && isArray(result) && result.length) {
// ... and fields is not defined
if (fields == null) {
// fields is the row 0
fields = result[0];
} else if(!isArray(fields)) {
// per each non present key, enrich the fields object
// it is then possible to have automatic headers
// with some known field validated/parsed
// e.g. {id:Number} will be {id:Number, value:String}
// if the query was SELECT id, value FROM table
// and the fields object was just {id:Number}
// but headers were active
result[0].forEach(enrichFields, fields);
}
// drop the first row with headers
result.shift();
}
}
// but next query, should not have
// previously set callbacks or fields
$callback = $fields = null;
// the spawned program can start a new job without current callback
// being able to push another job as soon as executed. This makes
// the queue fair for everyone without granting priority to anyone.
next();
// if there was actually a callback to call
if (callback) {
rows = fields ? (
// and if there was a need to parse each row
isArray(fields) ?
// as object with properties
result.map(row2object, fields) :
// or object with validated properties
result.map(row2parsed, parseFields(fields))
) :
// go for it ... otherwise returns the result as it is:
// an Array of Arrays
result
;
// if there was an error signature
if (1 < callback.length) {
callback.call(self, null, rows);
} else {
// invoke it with the db object as context
callback.call(self, rows);
}
}
} else {
// not a select, just a special command
// such .databases or .tables
next();
// if there is something to notify
if (str.length) {
// and if there was an 'info' listener
if (self.listeners('info').length) {
// notify
self.emit('info', EOL + str);
} else {
// otherwise log
log(EOL + str);
}
}
}
}
});
// detach the program from this one
// node 0.6 has not unref
if (program.unref) {
program.on('close', close);
} else {
IS_NODE_06 = true;
program.stdout.on('close', close);
}
// let's begin
busy = false;
next();
});
// when program is killed or closed for some reason
// the dblite object needs to be notified too
function close(code) {
if (self.listeners('close').length) {
self.emit('close', code);
if (program.unref)
program.unref();
} else {
log('bye bye');
}
}
// as long as there's something else to do ...
function next() {
if (queue.length) {
// ... do that and wait for next check
self.query.apply(self, queue.shift());
}
}
// common error helper
function onerror(data) {
if($callback && 1 < $callback.length) {
// there is a callback waiting
// and there is more than an argument in there
// the callback is waiting for errors too
var callback = $callback;
wasSelect = wasNotSelect = dontParseCSV = false;
$callback = $fields = null;
wasError = true;
// should the next be called ? next();
callback.call(self, new Error(data.toString()), null);
} else if(self.listeners('error').length) {
// notify listeners
self.emit('error', '' + data);
} else {
// log the output avoiding exit 1
// if no listener was added
console.error('' + data);
}
}
// WARNING: this can be very unsafe !!!
// if there is an error and this
// property is explicitly set to false
// it keeps running queries no matter what
self.ignoreErrors = false;
// - - - - - - - - - - - - - - - - - - - -
// safely closes the process
// will emit 'close' once done
self.close = function() {
// close can happen only once
if (!notWorking) {
// this should gently terminate the program
// only once everything scheduled has been completed
self.query('.exit');
notWorking = true;
// the hardly killed version was like this:
// program.stdin.end();
// program.kill();
}
};
// SELECT last_insert_rowid() FROM table might not work as expected
// This method makes the operation atomic and reliable
self.lastRowID = function(table, callback) {
self.query(
'SELECT ROWID FROM `' + table + '` ORDER BY ROWID DESC LIMIT 1',
function(result){
var row = result[0], k;
// if headers are switched on
if (!(row instanceof Array)) {
for (k in row) {
if (row.hasOwnProperty(k)) {
row = [row[k]];
break;
}
}
}
(callback || log).call(self, row[0]);
}
);
return self;
};
// Handy if for some reason data has to be passed around
// as string instead of being serialized and deserialized
// as Array of Arrays. Don't use if not needed.
self.plain = function() {
dontParseCSV = true;
return self.query.apply(self, arguments);
};
// main logic/method/entry point
self.query = function(string, params, fields, callback) {
// recognizes sql-template-strings objects
if (typeof string === 'object' && 'sql' in string && 'values' in string) {
switch (arguments.length) {
case 3: return self.query(string.sql, string.values, params, fields);
case 2: return self.query(string.sql, string.values, params);
}
return self.query(string.sql, string.values);
}
if (
// notWorking is set once .close() has been called
// it does not make sense to execute anything after
// the program is being closed
notWorking &&
// however, since at that time the program could also be busy
// let's be sure than this is either the exit call
// or that the last call is still the exit one
!(string === '.exit' || queue[queue.length - 1][0] === '.exit')
) return onerror('closing'), self;
// if something is still going on in the sqlite3 shell
// the progcess is flagged as busy. Just queue other operations
if (busy) return queue.push(arguments), self;
// if a SELECT or a PRAGMA ...
wasSelect = SELECT.test(string);
if (wasSelect) {
// SELECT and PRAGMA makes `dblite` busy
busy = true;
switch(arguments.length) {
// all arguments passed, nothing to do
case 4:
$callback = callback;
$fields = fields;
string = replaceString(string, params);
break;
// 3 arguments passed ...
case 3:
// is the last one the callback ?
if (typeof fields == 'function') {
// assign it
$callback = fields;
// has string parameters to repalce
// such ? or :id and others ?
if (HAS_PARAMS.test(string)) {
// no objectification and/or validation needed
$fields = null;
// string replaced wit parameters
string = replaceString(string, params);
} else {
// no replacement in the SQL needed
// objectification with validation
// if specified, will manage the result
$fields = params;
}
} else {
// no callback specified at all, probably in "dev mode"
$callback = log; // just log the result
$fields = fields; // use objectification
string = replaceString(string, params); // replace parameters
}
break;
// in this case ...
case 2:
// simple query with a callback
if (typeof params == 'function') {
// no objectification
$fields = null;
// callback is params argument
$callback = params;
} else {
// "dev mode", just log
$callback = log;
// if there's something to replace
if (HAS_PARAMS.test(string)) {
// no objectification
$fields = null;
string = replaceString(string, params);
} else {
// nothing to replace
// objectification with eventual validation
$fields = params;
}
}
break;
default:
// 1 argument, the SQL string and nothing else
// "dev mode" log will do
$callback = log;
$fields = null;
break;
}
// ask the sqlite3 shell ...
program.stdin.write(
// trick to always know when the console is not busy anymore
// specially for those cases where no result is shown
sanitize(string) + 'SELECT ' + SUPER_SECRET_SELECT
);
} else {
// if db.plain() was used but this is not a SELECT or PRAGMA
// something is wrong with the logic since no result
// was expected anyhow
if (dontParseCSV) {
dontParseCSV = false;
throw new Error('not a select');
} else if (string[0] === '.') {
// .commands are special queries .. so
// .commands make `dblite` busy
busy = true;
// same trick with the secret to emit('info', resultAsString)
// once everything is done
program.stdin.write(string + EOL + 'SELECT ' + SUPER_SECRET_SELECT);
} else {
switch(arguments.length) {
case 1:
/* falls through */
case 2:
if (typeof params !== 'function') {
// no need to make the shell busy
// since no output is shown at all (errors ... eventually)
// sqlite3 shell will take care of the order
// same as writing in a linux shell while something else is going on
// who cares, will show when possible, after current job ^_^
program.stdin.write(sanitize(HAS_PARAMS.test(string) ?
replaceString(string, params) :
string
));
// keep checking for possible following operations
process.nextTick(next);
break;
}
fields = params;
// not necessary but guards possible wrong replaceString
params = null;
/* falls through */
case 3:
// execute a non SELECT/PRAGMA statement
// and be notified once it's done.
// set state as busy
busy = wasNotSelect = true;
$callback = fields;
program.stdin.write(
(sanitize(
HAS_PARAMS.test(string) ?
replaceString(string, params) :
string
)) +
EOL + 'SELECT ' + SUPER_SECRET_SELECT
);
}
}
}
// chainability just useful here for multiple queries at once
return self;
};
return self;
}
// enrich possible fields object with extra headers
function enrichFields(key) {
var had = this.hasOwnProperty(key),
callback = had && this[key];
delete this[key];
this[key] = had ? callback : String;
}
// if not a memory database
// the file path should be resolved as absolute
function normalizeFirstArgument(args) {
var file = args[0];
if (file !== ':memory:') {
args[0] = path.resolve(args[0]);
}
return args.indexOf('-header') < 0 ? args.concat('-noheader') : args;
}
// assuming generated CSV is always like
// 1,what,everEOL
// with double quotes when necessary
// 2,"what's up",everEOL
// this parser works like a charm
function parseCSV(output) {
/*jshint eqnull: true*/
if (EOL == null) throw new Error(
'SQLite EOL not found. Please connect to a database first'
);
for(var
fields = [],
rows = [],
index = 0,
rindex = 0,
length = output.length,
i = 0,
j, loop,
current,
endLine,
iNext,
str;
i < length; i++
) {
switch(output[i]) {
case '"':
loop = true;
j = i;
do {
iNext = output.indexOf('"', current = j + 1);
switch(output[j = iNext + 1]) {
case EOL[0]:
if (EOL_LENGTH === 2 && output[j + 1] !== EOL[1]) {
break;
}
/* falls through */
case ',':
loop = false;
}
} while(loop);
str = output.slice(i + 1, iNext++).replace(DOUBLE_DOUBLE_QUOTES, '"');
break;
default:
iNext = output.indexOf(',', i);
endLine = output.indexOf(EOL, i);
if (iNext < 0) iNext = length - EOL_LENGTH;
str = output.slice(i, endLine < iNext ? (iNext = endLine) : iNext);
break;
}
fields[index++] = str;
if (output[i = iNext] === EOL[0] && (
EOL_LENGTH === 1 || (
output[i + 1] === EOL[1] && ++i
)
)
) {
rows[rindex++] = fields;
fields = [];
index = 0;
}
}
return rows;
}
// create an object with right validation
// and right fields to simplify the parsing
// NOTE: this is based on ordered key
// which is not specified by old ES specs
// but it works like this in V8
function parseFields($fields) {
for (var
current,
fields = Object.keys($fields),
parsers = [],
length = fields.length,
i = 0; i < length; i++
) {
current = $fields[fields[i]];
parsers[i] = current === Boolean ?
$Boolean : (
current === Date ?
$Date :
current || String
)
;
}
return {f: fields, p: parsers};
}
// transform SQL strings using parameters
function replaceString(string, params) {
// if params is an array
if (isArray(params)) {
// replace all ? occurence ? with right
// incremental params[index++]
paramsIndex = 0;
paramsArray = params;
string = string.replace(REPLACE_QUESTIONMARKS, replaceQuestions);
} else {
// replace :all @fields with the right
// object.all or object.fields occurrences
paramsObject = params;
string = string.replace(REPLACE_PARAMS, replaceParams);
}
paramsArray = paramsObject = null;
return string;
}
// escape the property found in the SQL
function replaceParams(match, key) {
return escape(paramsObject[key]);
}
// escape the value found for that ? in the SQL
function replaceQuestions() {
return escape(paramsArray[paramsIndex++]);
}
// objectification: makes an Array an object
// assuming the context is an array of ordered fields
function row2object(row) {
for (var
out = {},
length = this.length,
i = 0; i < length; i++
) {
out[this[i]] = row[i];
}
return out;
}
// objectification with validation:
// makes an Array a validated object
// assuming the context is an object
// produced via parseFields() function
function row2parsed(row) {
for (var
out = {},
fields = this.f,
parsers = this.p,
length = fields.length,
i = 0; i < length; i++
) {
out[fields[i]] = parsers[i](row[i]);
}
return out;
}
// escape in a smart way generic values
// making them compatible with SQLite types
// or useful for JavaScript once retrieved back
function escape(what) {
/*jshint eqnull: true*/
if (EOL == null) throw new Error(
'SQLite EOL not found. Please connect to a database first'
);
switch (typeof what) {
case 'string':
return "'" + what.replace(
SINGLE_QUOTES, SINGLE_QUOTES_DOUBLED
) + "'";
case 'undefined':
what = null;
/* falls through */
case 'object':
return what == null ?
'null' :
("'" + JSON.stringify(what).replace(
SINGLE_QUOTES, SINGLE_QUOTES_DOUBLED
) + "'")
;
// SQLite has no Boolean type
case 'boolean':
return what ? '1' : '0'; // 1 => true, 0 => false
case 'number':
// only finite numbers can be stored
if (isFinite(what)) return '' + what;
}
// all other cases
throw new Error('unsupported data');
}
// makes an SQL statement OK for dblite <=> sqlite communications
function sanitize(string) {
return string.replace(SANITIZER, '') + SANITIZER_REPLACER;
}
// no Boolean type in SQLite
// this will replace the possible Boolean validator
// returning the right expected value
function $Boolean(field) {
switch(field.toLowerCase()) {
case '0':
case 'false':
case 'null':
case '':
return false;
}
return true;
}
// no Date in SQLite, this will
// take care of validating/creating Dates
// when the field is retrieved with a Date validator
function $Date(field) {
return new Date(
DECIMAL.test(field) ? parseInt(field, 10) : field
);
}
// which sqlite3 executable ?
// it is possible to specify a different
// sqlite3 executable even in relative paths
// be sure the file exists and is usable as executable
Object.defineProperty(
dblite,
'bin',
{
get: function () {
// normalized string if was a path
return bin.join(PATH_SEP);
},
set: function (value) {
var isPath = -1 < value.indexOf(PATH_SEP);
if (isPath) {
// resolve the path
value = path.resolve(value);
// verify it exists
if (!require(IS_NODE_06 ? 'path' : 'fs').existsSync(value)) {
throw 'invalid executable: ' + value;
}
}
// assign as Array in any case
bin = value.split(PATH_SEP);
}
}
);
// starting from v0.6.0 sqlite version shuold be specified
// specially if SQLite version is 3.8.6 or greater
// var dblite = require('dblite').withSQLite('3.8.6')
dblite.withSQLite = function (sqliteVersion) {
dblite.sqliteVersion = sqliteVersion;
return dblite;
};
// to manually parse CSV data if necessary
// mainly to be able to use db.plain(SQL)
// without parsing it right away and pass the string
// around instead of serializing and de-serializing it
// all the time. Ideally this is a scenario for clusters
// no need to usually do manually anything otherwise.
dblite.parseCSV = parseCSV;
// how to manually escape data
// might be handy to write directly SQL strings
// instead of using handy paramters Array/Object
// usually you don't want to do this
dblite.escape = escape;
// helps writing queries
dblite.SQL = (function () {
'use strict';
const lsp = str => (/^[\s\n\r]/.test(str) ? str : ' ' + str);
const push = (str, val, statement, spaced) => {
const {strings, values} = statement;
str[str.length - 1] += spaced ? lsp(strings[0]) : strings[0];
str.push(...strings.slice(1));
val.push(...values);
};
class SQLStatement {
constructor(strings, values) {
this.strings = strings;
this.values = values;
}
append(statement) {
const {strings, values} = this;
if (statement instanceof SQLStatement)
push(strings, values, statement, true);
else
strings[strings.length - 1] += lsp(statement);
return this;
}
named() {
return this;
}
get sql() {
return this.strings.join('?');
}
}
const SQL = (tpl, ...val) => {
const strings = [tpl[0]];
const values = [];
for (let {length} = tpl, prev = tpl[0], j = 0, i = 1; i < length; i++) {
const current = tpl[i];
const value = val[i - 1];
if (/^('|")/.test(current) && RegExp.$1 === prev.slice(-1)) {
strings[j] = [
strings[j].slice(0, -1),
value,
current.slice(1)
].join('`');
} else {
if (value instanceof SQLStatement) {
push(strings, values, value, false);
j = strings.length - 1;
strings[j] += current;
} else {
values.push(value);
j = strings.push(current) - 1;
}
prev = strings[j];
}
}
return new SQLStatement(strings, values);
};
return SQL;
}());
// that's it!
module.exports = dblite;
/** some simple example
var db =
require('./build/dblite.node.js')('./test/dblite.test.sqlite').
on('info', console.log.bind(console)).
on('error', console.error.bind(console)).
on('close', console.log.bind(console));
// CORE FUNCTIONS: http://www.sqlite.org/lang_corefunc.html
// PRAGMA: http://www.sqlite.org/pragma.html
db.query('PRAGMA table_info(kvp)');
// to test memory database
var db = require('./build/dblite.node.js')(':memory:');
db.query('CREATE TABLE test (key INTEGER PRIMARY KEY, value TEXT)') && undefined;
db.query('INSERT INTO test VALUES(null, "asd")') && undefined;
db.query('SELECT * FROM test') && undefined;
// db.close();
*/
|
/**
* Проверка на макс. кол-во ответов
* @param {object} obj объекты ответов
* @param {int} id ID опроса
* @param {int} max_votes макс. кол-во голосов
* @param {bool} shrt в блоке?
* @returns {null}
*/
function check_max_selected(obj, id, max_votes, shrt) {
var $chkboxes = jQuery('.answer_'+id+(shrt?"_short":"")+':checked');
if ($chkboxes.length > max_votes) {
jQuery(obj).attr('checked', false);
alert(polls_you_re_select_max_vote);
}
}
/**
* Отображение результатов голосования
* @param {int} poll_id ID опроса
* @param {bool} voting из голосования?
* @param {bool} shrt в блоке?
* @returns {null}
*/
function change_voting_type(poll_id, voting, shrt) {
var type = -1;
if (!voting)
type = 1;
var si = "poll"+poll_id+(shrt?"_short":"")+"_status_icon";
status_icon(si, 'loading_white');
jQuery.get('index.php', {
'module':'polls_manage',
'nno':'1',
'from_ajax':'1',
'id':poll_id,
'votes':type,
'short':shrt
}, function (data) {
status_icon(si, 'success');
jQuery('#question_id'+poll_id+(shrt?"_short":"")).replaceWith(data);
if (type==1)
init_votes(poll_id, shrt);
});
}
/**
* Голосование в опросе
* @param {int} poll_id ID опроса
* @param {bool} shrt в блоке?
* @returns {null}
*/
function poll_vote(poll_id, shrt) {
var answers = jQuery('#question_id'+poll_id+(shrt?"_short":"")+' form').serialize();
var si = "poll"+poll_id+(shrt?"_short":"")+"_status_icon";
status_icon(si, 'loading_white');
jQuery.post('index.php?module=polls_manage&from_ajax=1&act=vote&id='+poll_id, answers, function (data) {
if (is_ok(data)) {
status_icon(si, 'success');
change_voting_type(poll_id, 0, shrt);
} else {
alert(error_text+': '+data);
status_icon(si, 'error');
}
});
}
/**
* Инициализация голосов в опросе
* @param {int} poll_id ID опроса
* @param {bool} shrt в блоке?
* @returns {null}
*/
function init_votes(poll_id, shrt) {
jQuery('#question_id'+poll_id+(shrt?"_short":"")+' div.votes').each(function () {
var $this = jQuery(this);
var $width = parseFloat($this.children('span').text());
if ($width) {
$width = ($width!="0"?$width+"%":'1px');
if ($width!='1px')
$this.animate({
'width': $width
}, 1000, 'swing');
}
});
}
/**
* Редактирование опроса
* @param {int} poll_id ID опроса
* @param {bool} shrt в блоке?
* @returns {null}
*/
function edit_polls(poll_id, shrt) {
var si = "poll"+poll_id+(shrt?"_short":"")+"_status_icon";
status_icon(si, 'loading_white');
jQuery.get('index.php', {
'module':'polls_manage',
'act':'edit',
'from_ajax':'1',
'id':poll_id,
'nno':1
}, function (data) {
status_icon(si, 'success');
jQuery('#question_id'+poll_id+(shrt?"_short":"")).empty();
jQuery('#question_id'+poll_id+(shrt?"_short":"")).append(data);
});
}
/**
* Удаление опроса
* @param {int} poll_id ID опроса
* @param {bool} shrt в блоке?
* @returns {null}
*/
function delete_polls(poll_id, shrt) {
if (!confirm(polls_you_re_sure_to_delete))
return;
var si = "poll"+poll_id+(shrt?"_short":"")+"_status_icon";
status_icon(si, 'loading_white');
jQuery.post('index.php'+fk_ajax+'module=polls_manage&act=delete&from_ajax=1&id='+poll_id, function (data) {
if (is_ok(data)) {
//alert(success_text);
var obj = jQuery('#question_id'+poll_id+(shrt?"_short":""));
obj.fadeOut(1000, function () {
status_icon(si, 'success');
if (jQuery(this).is('.single_poll'))
window.location = polls_link;
jQuery(this).remove();
});
} else {
alert(error_text);
status_icon(si, 'error');
}
});
} |
module.exports = {
'google-openid': {
css: 'google',
title: 'Google OpenId',
social: true
},
'google-apps': {
css: 'google',
title: 'Google Apps',
social: false
},
'google-oauth2': {
css: 'googleplus',
title: 'Google',
social: true
},
'facebook': {
css: 'facebook',
title: 'Facebook',
social: true
},
'windowslive': {
css: 'windows',
title: 'Microsoft Account',
social: true
},
'linkedin': {
css: 'linkedin',
title: 'LinkedIn',
social: true
},
'github': {
css: 'github',
title: 'GitHub',
social: true
},
'paypal': {
css: 'paypal',
title: 'PayPal',
social: true
},
'twitter': {
css: 'twitter',
title: 'Twitter',
social: true
},
'amazon': {
css: 'amazon',
title: 'Amazon',
social: true
},
'vkontakte': {
css: 'vk',
title: 'vKontakte',
social: true
},
'yandex': {
css: 'yandex',
title: 'Yandex',
social: true
},
'office365': {
css: 'office365',
title: 'Office365',
social: false
},
'waad': {
css: 'waad',
title: 'Windows Azure AD',
social: false
},
'adfs': {
css: 'windows',
title: 'ADFS',
social: false
},
'samlp': {
css: 'guest',
title: 'SAML',
social: false
},
'pingfederate': {
css: 'guest',
title: 'Ping Federate',
social: false
},
'ip': {
css: 'guest',
title: 'IP Address',
social: false
},
'mscrm': {
css: 'guest',
title: 'Dynamics CRM',
social: false
},
'ad': {
css: 'windows',
title: 'AD / LDAP',
social: false,
userAndPass: true
},
'custom': {
css: 'guest',
title: 'Custom Auth',
social: false
},
'auth0': {
css: 'guest',
title: 'Auth0',
social: false,
userAndPass: true
},
'auth0-adldap': {
css: 'guest',
title: 'AD/LDAP',
social: false,
userAndPass: true
},
'thirtysevensignals': {
css: 'thirtysevensignals',
title: '37 Signals',
social: true
},
'box': {
css: 'box',
title: 'Box',
social: true,
imageicon: true
},
'salesforce-community': {
css: 'salesforce',
title: 'Salesforce Community',
social: true
},
'salesforce': {
css: 'salesforce',
title: 'Salesforce',
social: true
},
'salesforce-sandbox': {
css: 'salesforce',
title: 'Salesforce (sandbox)',
social: true
},
'fitbit': {
css: 'fitbit',
title: 'Fitbit',
social: true
},
'baidu': {
css: 'baidu',
title: '百度',
social: true
},
'renren': {
css: 'renren',
title: '人人',
social: true
},
'yahoo': {
css: 'yahoo',
title: 'Yahoo!',
social: true
},
'aol': {
css: 'aol',
title: 'Aol',
social: true
},
'yammer': {
css: 'yammer',
title: 'Yammer',
social: true
},
'wordpress': {
css: 'wordpress',
title: 'Wordpress',
social: true
},
'dwolla': {
css: 'dwolla',
title: 'Dwolla',
social: true
},
'shopify': {
css: 'shopify',
title: 'Shopify',
social: true
},
'miicard': {
css: 'miicard',
title: 'miiCard',
social: true
},
'soundcloud': {
css: 'soundcloud',
title: 'Soundcloud',
social: true
},
'ebay': {
css: 'ebay',
title: 'ebay',
social: true
},
'evernote': {
css: 'evernote',
title: 'Evernote',
social: true
},
'evernote-sandbox': {
css: 'evernote',
title: 'Evernote (sandbox)',
social: true
},
'sharepoint': {
css: 'sharepoint',
title: 'SharePoint Apps',
social: false
},
'weibo': {
css: 'weibo',
title: '新浪微博',
social: true
},
'instagram': {
css: 'instagram',
title: 'Instagram',
social: true
},
'thecity': {
css: 'thecity',
title: 'The City',
social: true
},
'thecity-sandbox': {
css: 'thecity',
title: 'The City (sandbox)',
social: true
},
'planningcenter': {
css: 'planningcenter',
title: 'Planning Center',
social: true
},
'exact': {
css: 'exact',
title: 'Exact',
social: true
},
'bitbucket': {
css: 'bitbucket',
title: 'Bitbucket',
social: true
},
'dropbox': {
css: 'dropbox',
title: 'Dropbox',
social: true
}
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const serializable_1 = require("../serializable");
const encoding_1 = require("../lib/encoding");
const Address = require("../address");
class Transaction extends serializable_1.SerializableWithHash {
constructor() {
super();
this.m_publicKey = encoding_1.Encoding.ZERO_KEY;
this.m_signature = encoding_1.Encoding.ZERO_SIG64;
this.m_method = '';
this.m_nonce = -1;
}
get address() {
return Address.addressFromPublicKey(this.m_publicKey);
}
get method() {
return this.m_method;
}
set method(s) {
this.m_method = s;
}
get nonce() {
return this.m_nonce;
}
set nonce(n) {
this.m_nonce = n;
}
get input() {
const input = this.m_input;
return input;
}
set input(i) {
this.m_input = i;
}
/**
* virtual验证交易的签名段
*/
verifySignature() {
if (!this.m_publicKey) {
return false;
}
return Address.verify(this.m_hash, this.m_signature, this.m_publicKey);
}
sign(privateKey) {
let pubkey = Address.publicKeyFromSecretKey(privateKey);
this.m_publicKey = pubkey;
this.updateHash();
this.m_signature = Address.sign(this.m_hash, privateKey);
}
_encodeHashContent(writer) {
try {
writer.writeVarString(this.m_method);
writer.writeU32(this.m_nonce);
writer.writeBytes(this.m_publicKey);
this._encodeInput(writer);
}
catch (e) {
return serializable_1.ErrorCode.RESULT_INVALID_FORMAT;
}
return serializable_1.ErrorCode.RESULT_OK;
}
encode(writer) {
let err = super.encode(writer);
if (err) {
return err;
}
try {
writer.writeBytes(this.m_signature);
}
catch (e) {
return serializable_1.ErrorCode.RESULT_INVALID_FORMAT;
}
return serializable_1.ErrorCode.RESULT_OK;
}
_decodeHashContent(reader) {
try {
this.m_method = reader.readVarString();
this.m_nonce = reader.readU32();
this.m_publicKey = reader.readBytes(33, false);
this._decodeInput(reader);
}
catch (e) {
return serializable_1.ErrorCode.RESULT_INVALID_FORMAT;
}
return serializable_1.ErrorCode.RESULT_OK;
}
decode(reader) {
let err = super.decode(reader);
if (err) {
return err;
}
try {
this.m_signature = reader.readBytes(64, false);
}
catch (e) {
return serializable_1.ErrorCode.RESULT_INVALID_FORMAT;
}
return serializable_1.ErrorCode.RESULT_OK;
}
_encodeInput(writer) {
let input;
if (this.m_input) {
input = JSON.stringify(serializable_1.toStringifiable(this.m_input, true));
}
else {
input = JSON.stringify({});
}
writer.writeVarString(input);
return writer;
}
_decodeInput(reader) {
this.m_input = serializable_1.fromStringifiable(JSON.parse(reader.readVarString()));
return serializable_1.ErrorCode.RESULT_OK;
}
stringify() {
let obj = super.stringify();
obj.method = this.method;
obj.input = this.input;
obj.nonce = this.nonce;
obj.caller = this.address;
return obj;
}
}
exports.Transaction = Transaction;
class EventLog {
constructor() {
this.m_event = '';
}
set name(n) {
this.m_event = n;
}
get name() {
return this.m_event;
}
set param(p) {
this.m_params = p;
}
get param() {
const param = this.m_params;
return param;
}
encode(writer) {
let input;
try {
if (this.m_params) {
input = JSON.stringify(serializable_1.toStringifiable(this.m_params, true));
}
else {
input = JSON.stringify({});
}
writer.writeVarString(input);
}
catch (e) {
return serializable_1.ErrorCode.RESULT_INVALID_FORMAT;
}
return serializable_1.ErrorCode.RESULT_OK;
}
decode(reader) {
try {
this.m_params = serializable_1.fromStringifiable(JSON.parse(reader.readVarString()));
}
catch (e) {
return serializable_1.ErrorCode.RESULT_INVALID_FORMAT;
}
return serializable_1.ErrorCode.RESULT_OK;
}
stringify() {
let obj = Object.create(null);
obj.name = this.name;
obj.param = this.param;
return obj;
}
}
exports.EventLog = EventLog;
class Receipt {
constructor() {
this.m_transactionHash = '';
this.m_returnCode = 0;
this.m_eventLogs = new Array();
}
set transactionHash(s) {
this.m_transactionHash = s;
}
get transactionHash() {
return this.m_transactionHash;
}
set returnCode(n) {
this.m_returnCode = n;
}
get returnCode() {
return this.m_returnCode;
}
set eventLogs(logs) {
this.m_eventLogs = logs;
}
get eventLogs() {
const l = this.m_eventLogs;
return l;
}
encode(writer) {
try {
writer.writeVarString(this.m_transactionHash);
writer.writeI32(this.m_returnCode);
writer.writeU16(this.m_eventLogs.length);
}
catch (e) {
return serializable_1.ErrorCode.RESULT_INVALID_FORMAT;
}
for (let log of this.m_eventLogs) {
let err = log.encode(writer);
if (err) {
return err;
}
}
return serializable_1.ErrorCode.RESULT_OK;
}
decode(reader) {
this.m_transactionHash = reader.readVarString();
this.m_returnCode = reader.readI32();
let nCount = reader.readU16();
for (let i = 0; i < nCount; i++) {
let log = new EventLog();
let err = log.decode(reader);
if (err) {
return err;
}
this.m_eventLogs.push(log);
}
return serializable_1.ErrorCode.RESULT_OK;
}
stringify() {
let obj = Object.create(null);
obj.transactionHash = this.m_transactionHash;
obj.returnCode = this.m_returnCode;
obj.logs = [];
for (let l of this.eventLogs) {
obj.logs.push(l.stringify());
}
return obj;
}
}
exports.Receipt = Receipt;
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.2.3.13-2-20
description: >
Object.isExtensible returns true for all built-in objects
(RegExp.prototype)
includes: [runTestCase.js]
---*/
function testcase() {
var e = Object.isExtensible(RegExp.prototype);
if (e === true) {
return true;
}
}
runTestCase(testcase);
|
/*=============================================================
Authour URI: www.binarytheme.com
License: Commons Attribution 3.0
http://creativecommons.org/licenses/by/3.0/
100% Free To use For Personal And Commercial Use.
IN EXCHANGE JUST GIVE US CREDITS AND TELL YOUR FRIENDS ABOUT US
======================================================== */
(function ($) {
"use strict";
var mainApp = {
reviews_fun:function()
{
($)(function () {
$('#carousel-example').carousel({
interval: 3000 //TIME IN MILLI SECONDS
});
});
},
custom_fun:function()
{
/*====================================
WRITE YOUR SCRIPTS BELOW
======================================*/
},
}
$(document).ready(function () {
mainApp.reviews_fun();
mainApp.custom_fun();
});
}(jQuery));
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-expand-multiline',
included: function(app, parentAddon) {
var target = (parentAddon || app);
// necessary for nested usage
// parent addon should call `this._super.included.apply(this, arguments);`
if (target.app) {
target = target.app;
}
this.app = target;
// Use configuration to decide which theme css files
// to import, thus not populating the user's app
this.importThemes(target);
this._super.included.apply(this, arguments);
},
importThemes: function(app) {
app.import('vendor/ember-expand-multiline/base.css');
}
}; |
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users');
var codehubblogs = require('../../app/controllers/codehubblogs');
// Codehubblogs Routes
app.route('/codehubblogs')
.get(codehubblogs.list)
.post(users.requiresLogin, codehubblogs.create);
app.route('/codehubblogs/:codehubblogId')
.get(codehubblogs.read)
.put(users.requiresLogin, codehubblogs.hasAuthorization, codehubblogs.update)
.delete(users.requiresLogin, codehubblogs.hasAuthorization, codehubblogs.delete);
// Finish by binding the Codehubblog middleware
app.param('codehubblogId', codehubblogs.codehubblogByID);
}; |
(function () {
'use strict';
var deadlines = {
'el': document.getElementById('deadlines')
};
deadlines.controller = function () {
var ctrl = this;
ctrl.data = {};
deadlines.el.addEventListener('deadlines', function (event) {
var body = event.detail;
if (body.events.length === 0) {
return;
}
body.events.forEach(function (e) {
e.date = moment(e.date).lang('nb');
});
var eventDate = body.events[0].date,
now = moment();
if (eventDate.isBefore(now) || eventDate.isSame(now, 'day')) {
body.today = body.events.shift() || null;
} else {
body.today = null;
}
var lines = Math.floor(((deadlines.el.parentNode.getAttribute("data-sizey")-2)*155) / 20)
body.events = body.events.slice(0, 4+lines);
ctrl.data = body;
m.render(deadlines.el, deadlines.view(ctrl));
});
};
deadlines.view = function (c) {
if (Object.keys(c.data).length === 0) {
return m('p', 'Waiting for data');
}
var rows = c.data.events.map(function (event) {
return m('tr', [
m('td', {'class': 'fade summary'}, jrvs.truncate(event.summary, 19)),
m('td.start', event.date.format('DD. MM HH:mm'))
]);
});
return [
m('p.fade', 'Deadlines:'),
m('h1', c.data.today ? c.data.today.date.format('HH:mm') : '--:--'),
m('h2', c.data.today ?
jrvs.truncate(c.data.today.summary, 20) : 'Kommende deadlines!'),
m('table', rows),
m('p', {'class': 'fade updated-at'}, 'Sist oppdatert: ' +
c.data.updatedAt)
];
};
if (deadlines.el !== null) {
m.module(deadlines.el, deadlines);
}
})();
|
'use strict';
var restify = require('restify'),
expect = require('chai').expect;
describe("Hackers", function() {
var client, newHacker;
before(function() {
client = restify.createJsonClient('http://localhost:3000');
});
it("should create Hacker", function(done) {
var hacker = {
fullName: 'John Doe',
github: 'johndoe',
twitter: 'johndoe',
registered: new Date().toISOString(),
skills: 'java,c,nodejs,ruby,css',
email: 'johndoe@gmail.com'
};
client.post('/hackers', hacker, function(err, req, res, obj) {
expect(err).to.be.null;
expect(res.statusCode).to.eql(201);
newHacker = obj;
expect(newHacker).not.to.be.null;
expect(newHacker._id).not.to.be.null;
done();
});
});
it("should retrieve created Hacker", function(done) {
client.get('/hackers/' + newHacker._id, function(err, req, res, obj) {
expect(err).to.be.null;
expect(res.statusCode).to.eql(200);
expect(obj.fullName).to.equal(newHacker.fullName);
expect(obj.github).to.equal(newHacker.github);
expect(obj.twitter).to.equal(newHacker.twitter);
expect(obj.skills).to.eql(newHacker.skills);
done();
});
});
it("should retrieve all Hackers", function(done) {
client.get('/hackers', function(err, req, res, obj) {
expect(err).to.be.null;
expect(res.statusCode).to.eql(200);
expect(obj.results).to.be.a('array');
expect(obj.__total).to.equal(3);
done();
});
});
it("should use old email when updating Hacker with no email", function(done) {
client.put('/hackers/' + newHacker._id, {
email: ''
}, function(err, req, res, obj) {
expect(err).to.be.null;
expect(res.statusCode).to.eql(204);
client.get('/hackers/' + newHacker._id, function(err, req, res, obj) {
expect(err).to.be.null;
expect(res.statusCode).to.eql(200);
expect(obj.email).to.equal(newHacker.email);
done();
});
});
});
it("should delete Hacker", function(done) {
client.del('/hackers/' + newHacker._id, function(err, req, res, obj) {
expect(err).to.be.null;
expect(res.statusCode).to.eql(204);
client.get('/hackers/' + newHacker._id, function(err, req, res, obj) {
expect(err).not.to.be.null;
expect(res.statusCode).to.eql(404);
done();
});
});
});
});
|
import Flags from './modules.js';
import './server/publications.js';
export default Flags; |
/**
* @license @product.name@ JS v@product.version@ (@product.date@)
*
* (c) 2014 Highsoft AS
* Authors: Jon Arild Nygard / Oystein Moseng
*
* License: www.highcharts.com/license
*/
(function (H) {
var seriesTypes = H.seriesTypes,
merge = H.merge,
extendClass = H.extendClass,
defaultOptions = H.getOptions(),
plotOptions = defaultOptions.plotOptions,
noop = function () { return; },
each = H.each;
//defaultOptions.legend = false;
function Area(x, y, w, h) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.val = 0;
}
// Define default options
plotOptions.treemap = merge(plotOptions.scatter, {
legend: false,
marker: false,
borderColor: '#FFFFFF',
borderWidth: 1,
borderRadius: 0,
radius: 0,
dataLabels: {
verticalAlign: 'middle',
formatter: function () { // #2945
return this.point.id;
}
},
tooltip: {
headerFormat: '',
pointFormat: 'id: <b>{point.id}</b><br/>parent: <b>{point.parent}</b><br/>value: <b>{point.value}</b><br/>'
},
layoutAlgorithm: 'sliceAndDice'
});
// Stolen from heatmap
var colorSeriesMixin = {
// mapping between SVG attributes and the corresponding options
pointAttrToOptions: {
stroke: 'borderColor',
'stroke-width': 'borderWidth',
fill: 'color',
dashstyle: 'borderDashStyle',
r: 'borderRadius'
},
pointArrayMap: ['value'],
axisTypes: ['xAxis', 'yAxis', 'colorAxis'],
optionalAxis: 'colorAxis',
getSymbol: noop,
parallelArrays: ['x', 'y', 'value'],
colorKey: 'colorValue', // Point color option key
translateColors: seriesTypes.heatmap.prototype.translateColors
};
// The Treemap series type
seriesTypes.treemap = extendClass(seriesTypes.scatter, merge(colorSeriesMixin, {
type: 'treemap',
isCartesian: false,
trackerGroups: ['group', 'dataLabelsGroup'],
handleLayout: function () {
var tree = this.buildTree(),
seriesArea = this.getSeriesArea(tree.val);
this.calculateArea(tree, seriesArea);
this.setColorRecursive(tree, undefined);
},
buildTree: function () {
var tree,
i = 0,
parentList = [],
allIds = [],
key,
insertItem = function (key) {
each(parentList[key], function (item) {
parentList[""].push(item);
});
},
getNodeTree = function (id, i, level, list, points) {
var children = [],
sortedChildren = [],
val = 0,
nodeTree,
node,
insertNode;
insertNode = function () {
var i = 0,
inserted = false;
if (sortedChildren.length !== 0) {
each(sortedChildren, function (child) {
if (node.val > child.val && !inserted) {
sortedChildren.splice(i, 0, node);
inserted = true;
}
i = i + 1;
});
}
if (!inserted) {
sortedChildren.push(node);
}
};
// Actions
if (list[id] !== undefined) {
each(list[id], function (i) {
node = getNodeTree(points[i].id, i, (level + 1), list, points);
val += node.val;
insertNode();
children.push(node);
});
} else {
val = points[i].value;
}
nodeTree = {
id: id,
i: i,
children: sortedChildren,
val: val,
level: level
};
return nodeTree;
};
// Actions
// Map children to index
each(this.points, function (point) {
var parent = "";
allIds.push(point.id);
if (point.parent !== undefined) {
parent = point.parent;
}
if (parentList[parent] === undefined) {
parentList[parent] = [];
}
parentList[parent].push(i);
i = i + 1;
});
/*
* Quality check:
* - If parent does not exist, then set parent to tree root
* - Add node id to parents children list
*/
for (key in parentList) {
if (parentList.hasOwnProperty(key)) {
if (key !== "") {
if (allIds.indexOf(key) === -1) {
insertItem(key);
delete parentList[key];
}
}
}
}
tree = getNodeTree("", -1, 0, parentList, this.points);
return tree;
},
calculateArea: function (node, area) {
var childrenValues = [],
childValues,
series = this,
i = 0,
setPointValues = function (node, values) {
var point;
if (node.val > 0) {
point = series.points[node.i];
// Set point values
point.shapeType = 'rect';
point.shapeArgs = {
x: values.x,
y: values.y,
width: values.width,
height: values.height
};
point.plotX = point.shapeArgs.x + (point.shapeArgs.width / 2);
point.plotY = point.shapeArgs.y + (point.shapeArgs.height / 2);
}
};
childrenValues = series[series.options.layoutAlgorithm](area, node.children);
each(node.children, function (child) {
childValues = childrenValues[i];
childValues.val = child.val;
// If node has children, then call method recursively
if (child.children.length) {
series.calculateArea(child, childValues);
} else {
setPointValues(child, childValues);
}
i = i + 1;
});
},
getSeriesArea: function (val) {
var w = this.chart.plotWidth,
x = w * this._i,
y = 0,
h = this.chart.plotHeight,
seriesArea = new Area(x, y, w, h);
seriesArea.val = val;
return seriesArea;
},
setColorRecursive: function (node, color) {
var series = this,
point = series.points[node.i];
if (node.i !== -1) {
if (point.color === undefined) {
if (color !== undefined) {
point.color = color;
point.options.color = color;
}
} else {
color = point.color;
}
}
if (node.children.length) {
each(node.children, function (child) {
series.setColorRecursive(child, color);
});
}
},
strip: function (parent, children) {
var childrenArea = [],
pTot,
x = parent.x,
y = parent.y,
height = parent.height,
i = 0,
end = children.length - 1,
group = {
total: 0,
nW: 0,
lW: 0,
elArr: [],
lP: {
total: 0,
lH: 0,
nH: 0,
nR: 0,
lR: 0,
aspectRatio: function (w, h) {
return Math.max((w / h), (h / w));
}
},
addElement: function (el) {
this.lW = this.nW;
// Calculate last point old aspect ratio
this.lP.total = this.elArr[this.elArr.length - 1];
this.lP.lH = this.lP.total / this.nW;
this.lP.lR = this.lP.aspectRatio(this.lW, this.lP.lH);
// New total
this.total = this.total + el;
this.nW = this.total / height;
// Calculate last point new aspect ratio
this.lP.nH = this.lP.total / this.nW;
this.lP.nR = this.lP.aspectRatio(this.nW, this.lP.nH);
this.elArr.push(el);
},
reset: function () {
this.nW = 0;
this.lW = 0;
this.elArr = [];
this.total = 0;
}
},
calculateGroupPoints = function (last) {
var pX,
pY,
pW,
pH,
gW = group.lW,
keep,
i = 0,
end = group.elArr.length - 1;
if (last) {
gW = group.nW;
} else {
keep = group.elArr[group.elArr.length - 1];
}
each(group.elArr, function (p) {
if (last || (i < end)) {
pX = x;
pY = y;
pW = gW;
pH = p / pW;
childrenArea.push(new Area(pX, pY, pW, pH));
y = y + pH;
}
i = i + 1;
});
// Reset variables
group.reset();
y = parent.y;
x = x + gW;
// If not last, then add uncalculated element
if (!last) {
group.addElement(keep);
}
};
// Loop through and calculate all areas
each(children, function (child) {
pTot = (parent.width * parent.height) * (child.val / parent.val);
group.addElement(pTot);
if (group.lP.nR > group.lP.lR) {
calculateGroupPoints(false);
}
// If last child, then calculate all remaining areas
if (i === end) {
calculateGroupPoints(true);
}
i = i + 1;
});
return childrenArea;
},
squarified: function (parent, children) {
var childrenArea = [],
pTot,
x = parent.x,
y = parent.y,
height = parent.height,
width = parent.width,
i = 0,
direction = 0,
end = children.length - 1,
group = {
total: 0,
nW: 0,
lW: 0,
nH: 0,
lH: 0,
elArr: [],
lP: {
total: 0,
lH: 0,
nH: 0,
lW: 0,
nW: 0,
nR: 0,
lR: 0,
aspectRatio: function (w, h) {
return Math.max((w / h), (h / w));
}
},
addElement: function (el) {
this.lP.total = this.elArr[this.elArr.length - 1];
this.total = this.total + el;
if (direction === 0) {
// Calculate last point old aspect ratio
this.lW = this.nW;
this.lP.lH = this.lP.total / this.lW;
this.lP.lR = this.lP.aspectRatio(this.lW, this.lP.lH);
// Calculate last point new aspect ratio
this.nW = this.total / height;
this.lP.nH = this.lP.total / this.nW;
this.lP.nR = this.lP.aspectRatio(this.nW, this.lP.nH);
} else {
// Calculate last point old aspect ratio
this.lH = this.nH;
this.lP.lW = this.lP.total / this.lH;
this.lP.lR = this.lP.aspectRatio(this.lP.lW, this.lH);
// Calculate last point new aspect ratio
this.nH = this.total / width;
this.lP.nW = this.lP.total / this.nH;
this.lP.nR = this.lP.aspectRatio(this.lP.nW, this.nH);
}
this.elArr.push(el);
},
reset: function () {
this.nW = 0;
this.lW = 0;
this.elArr = [];
this.total = 0;
}
},
calculateGroupPoints = function (last) {
var pX,
pY,
pW,
pH,
gW = group.lW,
gH = group.lH,
keep,
i = 0,
end = group.elArr.length - 1;
if (last) {
gW = group.nW;
gH = group.nH;
} else {
keep = group.elArr[group.elArr.length - 1];
}
each(group.elArr, function (p) {
if (last || (i < end)) {
if (direction === 0) {
pX = x;
pY = y;
pW = gW;
pH = p / pW;
} else {
pX = x;
pY = y;
pH = gH;
pW = p / pH;
}
childrenArea.push(new Area(pX, pY, pW, pH));
if (direction === 0) {
y = y + pH;
} else {
x = x + pW;
}
}
i = i + 1;
});
// Reset variables
group.reset();
if (direction === 0) {
width = width - gW;
} else {
height = height - gH;
}
y = parent.y + (parent.height - height);
x = parent.x + (parent.width - width);
direction = 1 - direction;
// If not last, then add uncalculated element
if (!last) {
group.addElement(keep);
}
};
// Loop through and calculate all areas
each(children, function (child) {
pTot = (parent.width * parent.height) * (child.val / parent.val);
group.addElement(pTot);
if (group.lP.nR > group.lP.lR) {
calculateGroupPoints(false);
}
// If last child, then calculate all remaining areas
if (i === end) {
calculateGroupPoints(true);
}
i = i + 1;
});
return childrenArea;
},
sliceAndDice: function (parent, children) {
var childrenArea = [],
pTot,
direction = 0,
x = parent.x,
y = parent.y,
width = parent.width,
height = parent.height,
pX,
pY,
pW,
pH;
each(children, function (child) {
pTot = (parent.width * parent.height) * (child.val / parent.val);
pX = x;
pY = y;
if (direction === 0) {
pH = height;
pW = pTot / pH;
width = width - pW;
x = x + pW;
} else {
pW = width;
pH = pTot / pW;
height = height - pH;
y = y + pH;
}
childrenArea.push(new Area(pX, pY, pW, pH));
direction = 1 - direction;
});
return childrenArea;
},
stripes: function (parent, children) {
var childrenArea = [],
pTot,
x = parent.x,
y = parent.y,
width = parent.width,
pX,
pY,
pW,
pH;
each(children, function (child) {
pTot = (parent.width * parent.height) * (child.val / parent.val);
pX = x;
pY = y;
pH = parent.height;
pW = pTot / pH;
width = width - pW;
x = x + pW;
childrenArea.push(new Area(pX, pY, pW, pH));
});
return childrenArea;
},
translate: function () {
H.Series.prototype.translate.call(this);
this.handleLayout();
this.translateColors();
// Make sure colors are updated on colorAxis update (#2893)
if (this.chart.hasRendered) {
each(this.points, function (point) {
point.shapeArgs.fill = point.color;
});
}
},
drawPoints: seriesTypes.column.prototype.drawPoints,
drawLegendSymbol: H.LegendSymbolMixin.drawRectangle
}));
}(Highcharts));
|
require('ts-node/register')
global.Observable = require('rxjs').Observable
|
import DS from 'ember-data';
/**
* Define the endpoint object model
*
* @author Eric Fehr (ricofehr@nextdeploy.io, github: ricofehr)
* @class Endpoint
* @namespace model
* @module nextdeploy
* @augments DS/Model
*/
export default DS.Model.extend({
/**
* @attribute prefix
* @type {String}
*/
prefix: DS.attr('string'),
/**
* @attribute path
* @type {String}
*/
path: DS.attr('string'),
/**
* @attribute envvars
* @type {String}
*/
envvars: DS.attr('string'),
/**
* @attribute aliases
* @type {String}
*/
aliases: DS.attr('string'),
/**
* @attribute is_install
* @type {Boolean}
*/
is_install: DS.attr('boolean'),
/**
* @attribute ipfilter
* @type {String}
*/
ipfilter: DS.attr('string'),
/**
* @attribute port
* @type {String}
*/
port: DS.attr('string'),
/**
* @attribute customvhost
* @type {String}
*/
customvhost: DS.attr('string'),
/**
* @attribute is_sh
* @type {Boolean}
*/
is_sh: DS.attr('boolean'),
/**
* @attribute is_import
* @type {Boolean}
*/
is_import: DS.attr('boolean'),
/**
* @attribute is_main
* @type {Boolean}
*/
is_main: DS.attr('boolean'),
/**
* @attribute is_ssl
* @type {Boolean}
*/
is_ssl: DS.attr('boolean'),
/**
* @attribute project
* @type {Project}
*/
project: DS.belongsTo('project'),
/**
* @attribute framework
* @type {Framework}
*/
framework: DS.belongsTo('framework')
});
|
/**
* @classdesc
* Fog is an {@linkcode Effect} added to the Camera that applies a fog effect to the scene.
*
* @property {number} density The "thickness" of the fog. Keep it tiny.
* @property {Color} tint The color of the fog.
* @property {number} heightFallOff The fall-off based on the height. This is to simulate a thinning atmosphere.
* @property {number} startDistance The distance from the camera at which the effect should start to be applied.
*
* @constructor
* @param {Number} [density] The "thickness" of the fog. Keep it tiny.
* @param {Color} [tint] The color of the fog.
* @param {Number} [heightFallOff] The fall-off based on the height. This is to simulate a thinning atmosphere.
* @param {Number} [startDistance] The distance from the camera at which the effect should start to be applied.
*
* @extends Effect
*
* @author derschmale <http://www.derschmale.com>
*/
import {EffectPass} from "./EffectPass";
import {ShaderLibrary} from "../shader/ShaderLibrary";
import {Effect} from "./Effect";
import {GL} from "../core/GL";
import {Color} from "../core/Color";
import {META} from "../Helix";
function Fog(density, tint, heightFallOff, startDistance)
{
Effect.call(this);
this._fogPass = new EffectPass(ShaderLibrary.get("fog_vertex.glsl"), ShaderLibrary.get("fog_fragment.glsl"));
this.needsNormalDepth = true;
this.density = density === undefined? .001 : density;
this._tint = new Color(1, 1, 1, 1);
if (tint !== undefined)
this.tint = tint;
this.startDistance = startDistance === undefined? 0 : startDistance;
this.heightFallOff = heightFallOff === undefined? 0.01 : heightFallOff;
}
Fog.prototype = Object.create(Effect.prototype,
{
density: {
get: function()
{
return this._density;
},
set: function(value)
{
this._density = value;
this._fogPass.setUniform("density", value);
}
},
tint: {
get: function ()
{
return this._tint;
},
set: function (value)
{
this._tint.copyFrom(value);
if (META.OPTIONS.useGammaCorrection)
this._tint.gammaToLinear();
this._fogPass.setUniform("tint", {x: value.r, y: value.g, z: value.b});
}
},
startDistance: {
get: function()
{
return this._startDistance;
},
set: function(value)
{
this._startDistance = value;
this._fogPass.setUniform("startDistance", value);
}
},
heightFallOff: {
get: function()
{
return this._heightFallOff;
},
set: function(value)
{
this._heightFallOff = value;
this._fogPass.setUniform("heightFallOff", value);
}
}
}
);
/**
* @ignore
*/
Fog.prototype.draw = function(renderer, dt)
{
GL.setRenderTarget(this.hdrTarget);
GL.clear();
this._fogPass.draw(renderer);
};
export { Fog }; |
/**
* Collapsable object
* Given a node element, it will allow it to open and close
*
* @constructor
* @public
*
* @param {Element} el
*/
function Collapsable(el) {
this.el = el;
this.isOpen = false;
this.bindEvents();
}
Collapsable.prototype = {
/**
* @see Collapsable
* @type {Function}
*/
constructor: Collapsable,
/**
* open
* Opens the node
*
* @method
* @public
* @chainable
*/
open: function () {
if (!this.isOpen) {
this.addClass();
this.isOpen = true;
this.triggerEvent('opened');
}
return this;
},
/**
* close
* closes the node
*
* @method
* @public
* @chainable
*/
close: function () {
if (this.isOpen) {
this.removeClass();
this.isOpen = false;
this.triggerEvent('closed');
}
return this;
},
/**
* toggle
* Opens the element if it's closed.
* Closes if it's open
*
* @method
* @public
* @chainable
*/
toggle: function (evt) {
if (evt) { evt.stopPropagation(); }
return (this.isOpen) ?
this.close() :
this.open();
},
/**
* addClass
* adds the 'open' class to the element
*
* @method
* @public
* @chainable
*/
addClass: function () {
if (!this.hasClass('opened')) {
var className = this.el.getAttribute('class');
this.el.setAttribute('class', className + ' opened');
}
return this;
},
/**
* removeClass
* removes the 'open' class to the element
*
* @method
* @public
* @chainable
*/
removeClass: function () {
var className = this.el.getAttribute('class');
this.el.setAttribute('class', className.replace(/\sopened/g, ''));
return this;
},
hasClass: function (className) {
return (this.el.getAttribute('class') &&
this.el.getAttribute('class').indexOf(className) !== -1);
},
/**
* bindEvents
* Attach the necessary events
*
* @method
* @protected
* @return {undefined}
*/
bindEvents: function () {
this.el.addEventListener('click', _.bind(this.toggle, this));
},
/**
* bindEvents
* dettach the necessary events
*
* @method
* @protected
* @return {undefined}
*/
unbindEvents: function () {
this.el.removeEventListener('click', _.bind(this.toggle, this));
},
triggerEvent: function (name) {
var event = document.createEvent('MouseEvents');
event.initMouseEvent(name, true, true);
this.el.dispatchEvent(event);
},
/**
* dealloc
* Removes binded events, destroys the element
*
* @method
* @public
* @return {undefined}
*/
dealloc: function () {
this.unbindEvents();
this.el.parentNode.removeChild(this.el);
delete this.el;
delete this.isOpen;
}
};
|
var Login = artifacts.require("./Login.sol");
module.exports = function(deployer) {
deployer.deploy(Login);
};
|
/*
* hellop5js
* 2014.09.12
*
*/
// -----------------------------------------------------------------------------
// Properties
// -----------------------------------------------------------------------------
var particles = [];
// -----------------------------------------------------------------------------
// Methods
// -----------------------------------------------------------------------------
function runPSystem (){
for (var i = 0; i < particles.length;i++) {
particles[i].run();
}
};
function particle (x, y, w, h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.rotation = 0;
this.display = function(){
stroke(0);// black stroke in HEX
push();// set the matrix so it is always centered
translate(this.x, this.y);// push it to our position
rectMode(CENTER);// we want the rect to be centered
rotate(radians(this.rotation));// rotate it takes radians as arg
rect(0, 0, this.w, this.h);// draw the particle
pop();// push the matrix back
};
this.turn = function(){
this.rotation++;
};
this.move = function(){
var _x = this.x;// get the current value x
var _y = this.y;// get the current value y
_x += random(-1, 1);// change it
_y += random(-1, 1);// change it
this.x = constrain(_x, 0, displayWidth);// constrain it to the screen
this.y = constrain(_y, 0, displayHeight);// constrain it to the screen
};
this.update = function(){
this.turn();
this.move();
};
this.run = function(){
this.display();
this.update();
};
}
function cls() {
rectMode(CORNER);
noStroke();
rect(0, 0, width, height);
}
//
// Setup
//
function setup() {
createCanvas(displayWidth, displayHeight);
}
//
// Draw
//
function draw() {
cls();
runPSystem();
}
// -----------------------------------------------------------------------------
// Events
// -----------------------------------------------------------------------------
//
// Keyboard
//
// function keyPressed() {
// }
// //
// // Mouse
// //
function mousePressed() {
particles.push(new particle(mouseX,mouseY,10,10));
}
// function mouseDragged() {
// };
// function mouseReleased() {
// };
// //
// // Touch
// //
// function touchStarted() {
// };
// function touchMoved() {
// };
// function touchEnded() {
// };
// //
// // Drag & Drop
// //
// function onDrop(event) {
// };
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.