Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
// Part of this code up to END OF (c) is:
/*
Copyright 2011 Martin Hawksey
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var MINSIZE = 1; //minimum node size on autofill
var MAXSIZE = 10; //maximum node size on autofill
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [];
// When the user clicks on "addMenuExample" then "Menu Entry 1", the function function1 is executed.
menuEntries.push({name: "API Authentication", functionName: "configureAPI"});
menuEntries.push({name: "Test Collection", functionName: "testCollection"});
menuEntries.push({name: "Run Now!", functionName: "collectTweets"});
menuEntries.push(null); // line separator
ss.addMenu("TAGS", menuEntries);
var menuEntries = [];
menuEntries.push({name: "1. Get Friend Follower Relationships", functionName: "getCommunityGraph"});
menuEntries.push({name: "2. Replace User IDs with Names", functionName: "replaceIDsWithNames"});
menuEntries.push({name: "3. Fill Twitter User Information", functionName: "lookupTwitterID"});
menuEntries.push(null); // line separator
menuEntries.push({name: "Calculate Degree", functionName: "calcDegree"});
menuEntries.push(null); // line separator
menuEntries.push({name: "Fill Node Size (Degree)", functionName: "fillNodeUsingDegree"});
menuEntries.push({name: "Fill Node Size (In-Degree)", functionName: "fillNodeUsingInDegree"});
menuEntries.push({name: "Fill Node Size (Out-Degree)", functionName: "fillNodeUsingOutDegree"});
ss.addMenu("TAGS - Advanced", menuEntries);
}
function doPost(e){
// PART OF SCRIPT WHICH HANDLES DATA POSTED FROM R
// To use complete steps 1 -3 from TAGS - Advanced menu and File > Publish to the web..
// From this window select Share > Publish as service.. allowing anyone to invloke annonymously
// Download the R script from https://gist.github.com/1682306 and modify variables for the key, sheet, urls and common secret set below
// Run the R script and values will be entered into the spreadsheet
var secret ="FzWGlpUkt1Tmc"; //must match secret in R script
if (e.parameter.secret == secret){
var ss = SpreadsheetApp.openById(ScriptProperties.getProperty('active'));
var sheet = ss.getSheetByName("Vertices"); // read the existing data from Vertices sheet
var data = {}
var datagrid = Utilities.jsonParse(e.parameter.datagrid); // handling datagrid object made in R
var datagridlabels = Utilities.jsonParse(e.parameter.datagridlabels); // list of screen_names that match datagrid made in R
for (i in datagrid){
datagrid[i].screen_name = datagridlabels[i];
data[datagridlabels[i]]=datagrid[i]; // index objects with screennames
}
var toptens = Utilities.jsonParse(e.parameter.toptens); // collect toptens list made in R
var labels = Utilities.jsonParse(e.parameter.toptenslabels); //list of names of things calculated in R
var exdata = getRowsData(sheet); // read the existing data from Vertices sheet
for (i in exdata){ // add new data to existing data
if (data[exdata[i].screen_name] != undefined){
for (j in labels){
exdata[i][labels[j]] = data[exdata[i].screen_name][labels[j]];
}
}
}
setRowsData(sheet,exdata); // write individuals stats back to sheet
var sheet = ss.getSheetByName("SNA Metrics"); // add the top ten's to SNA Metrics sheet
var topsData = chunk(toptens,10);
// probably could have found better way of writting
sheet.getRange("A4:C13").setValues(topsData[0]);
sheet.getRange("A17:C26").setValues(topsData[1]);
sheet.getRange("A30:C39").setValues(topsData[2]);
sheet.getRange("A43:C52").setValues(topsData[3]);
sheet.getRange("A56:C65").setValues(topsData[4]);
sheet.getRange("A69:C78").setValues(topsData[5]);
}
}
function cron(){
collectTweets();
getStats();
}
function copyData(){
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sSheet = doc.getSheetByName("Copy of Archive");
var dSheet = doc.getSheetByName("Archive");
var col = 2;
dSheet.getRange(1,col,sSheet.getLastRow(),1).setValues(sSheet.getRange(1,col,sSheet.getLastRow(),1).getValues());
//setRowsData(dSheet);
}
function setup(){
ScriptProperties.setProperty('active', SpreadsheetApp.getActiveSpreadsheet().getId());
}
function authenticate(){
//ScriptProperties.setProperty('active', SpreadsheetApp.getActiveSpreadsheet().getId());
authorize();
}
function configureAPI() {
renderAPIConfigurationDialog();
}
function renderAPIConfigurationDialog() {
// modified from Twitter Approval Manager
// http://code.google.com/googleapps/appsscript/articles/twitter_tutorial.html
var doc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setTitle(
"Twitter API Authentication Configuration").setHeight(400).setWidth(420);
app.setStyleAttribute("padding", "10px");
//var dialog = app.loadComponent("GUIComponent");
var dialogPanel = app.createFlowPanel().setWidth("400px");
var label1 = app.createLabel("1. Register for an API key with Twitter at http://dev.twitter.com/apps/new (if you've already registered a Google Spreadsheet/Twitter mashup you can reuse your existing Consumer Key/Consumer Secret). In the form these are the important bits: ").setStyleAttribute("paddingBottom", "10px");
var label2 = app.createLabel(" - Application Website = anything you like").setStyleAttribute("textIndent", "30px");
var label3 = app.createLabel(" - Application Type = Browser").setStyleAttribute("textIndent", "30px");
var label4 = app.createLabel(" - Callback URL = https://spreadsheets.google.com/macros").setStyleAttribute("textIndent", "30px");
var label5 = app.createLabel(" - Default Access type = Read-only ").setStyleAttribute("textIndent", "30px").setStyleAttribute("paddingBottom", "10px");
var label6 = app.createLabel("2. Once finished filling in the form and accepting Twitter's terms and conditions you'll see a summary page which includes a Consumer Key and Consumer Secret which you need to enter below").setStyleAttribute("paddingBottom", "10px");
var label7 = app.createLabel("3. When your Key and Secret are saved you need to open Tools > Script Editor ... and run the 'authenticate' function").setStyleAttribute("paddingBottom", "10px");
//("<strong>hello</strong><ul><li>one</li></ul>");
dialogPanel.add(label1);
dialogPanel.add(label2);
dialogPanel.add(label3);
dialogPanel.add(label4);
dialogPanel.add(label5);
dialogPanel.add(label6);
dialogPanel.add(label7);
var consumerKeyLabel = app.createLabel(
"Twitter OAuth Consumer Key:");
var consumerKey = app.createTextBox();
consumerKey.setName("consumerKey");
consumerKey.setWidth("90%");
consumerKey.setText(getConsumerKey());
var consumerSecretLabel = app.createLabel(
"Twitter OAuth Consumer Secret:");
var consumerSecret = app.createTextBox();
consumerSecret.setName("consumerSecret");
consumerSecret.setWidth("90%");
consumerSecret.setText(getConsumerSecret());
var saveHandler = app.createServerClickHandler("saveConfiguration");
var saveButton = app.createButton("Save Configuration", saveHandler);
var listPanel = app.createGrid(2, 2);
listPanel.setStyleAttribute("margin-top", "10px")
listPanel.setWidth("100%");
listPanel.setWidget(0, 0, consumerKeyLabel);
listPanel.setWidget(0, 1, consumerKey);
listPanel.setWidget(1, 0, consumerSecretLabel);
listPanel.setWidget(1, 1, consumerSecret);
// Ensure that all form fields get sent along to the handler
saveHandler.addCallbackElement(listPanel);
//var dialogPanel = app.createFlowPanel();
//dialogPanel.add(helpLabel);
dialogPanel.add(listPanel);
dialogPanel.add(saveButton);
app.add(dialogPanel);
doc.show(app);
}
function collectTweets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sumSheet = ss.getSheetByName("Readme/Settings");
var SEARCH_TERM = sumSheet.getRange("B10").getValue();
var NUMBER_OF_TWEETS = sumSheet.getRange("B12").getValue();
var RESULT_TYPE = sumSheet.getRange("B13").getValue();
// if continuous sheetname = archive else make a name
if (RESULT_TYPE == "continuous"){
var sheetName = "Archive";
} else {
var sheetName = Utilities.formatDate(new Date(), "GMT", "dd-MMM-yy hh:mm"); //make a new sheet name based on todays date
}
// if sheetname doesn't exisit make it
if (!ss.getSheetByName(sheetName)){
var temp = ss.getSheetByName("TMP");
var sheet = ss.insertSheet(sheetName, {template:temp});
} else {
var sheet = ss.getSheetByName(sheetName);
}
var sinceid = false;
sinceid = alltrim(sumSheet.getRange("B14").getValue());
//if no since id grab search results
if (sinceid){
var data = getTweets(SEARCH_TERM, NUMBER_OF_TWEETS, sinceid); // get results from twitter sinceid
} else {
var data = getTweets(SEARCH_TERM, NUMBER_OF_TWEETS); // get results from twitter
}
// if some data insert rows
if (data.length>0){
sheet.insertRowsAfter(1, data.length);
setRowsData(sheet, data);
}
}
function testCollection(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sumSheet = ss.getSheetByName("Readme/Settings");
var SEARCH_TERM = sumSheet.getRange("B10").getValue();
var data = getTweets(SEARCH_TERM, 5); // get results from twitter
if (data.length>0){
Browser.msgBox("Found some tweets. Here's an example one from "+data[0]["from_user"]+" which says: "+data[0]["text"]);
} else {
Browser.msgBox("Twitter said: "+ScriptProperties.getProperty("errormsg"));
}
}
function getTweets(searchTerm, maxResults, sinceid, languageCode) {
//Based on Mikael Thuneberg getTweets - mod by mhawksey to convert to json
// if you include setRowsData this can be used to output chosen entries
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sumSheet = ss.getSheetByName("Readme/Settings");
if (isConfigured()){
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl(
"https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
} else {
var REFERER = sumSheet.getRange("B9").getValue();
var requestData = {"method":"GET", "headers": { "User-Agent": REFERER}}
}
try {
var pagenum = 1;
var data =[];
var idx = 0;
var sinceurl ="";
var period = 0;
var SEARCH_DURATION = sumSheet.getRange("B11").getValue();
// prepare search term
if (SEARCH_DURATION != "default"){
switch (SEARCH_DURATION){
case "yesterday":
period = 0;
break;
case "-2 days":
period = 1;
break;
case "-3 days":
period = 2;
break;
case "-4 days":
period = 3;
break;
case "-5 days":
period = 4;
break;
case "-6 days":
period = 5;
break;
case "-7 days":
period = 6;
break;
}
var until=new Date();
until.setDate(until.getDate()-period);
var since = new Date(until);
since.setDate(since.getDate()-1-period);
}
if (typeof maxResults == "undefined") {
maxResults = 100;
}
if (maxResults > 1500) {
maxResults = 1500;
}
if (maxResults > 100) {
resultsPerPage = 100;
maxPageNum = maxResults / 100;
} else {
resultsPerPage = maxResults;
maxPageNum = 1;
}
if (sinceid != null && sinceid.length > 0) {
sinceurl = "&since_id=" + sinceid;
}
//Logger.log(twDate(since)+" "+twDate(until));
searchTerm = encodeURIComponent(searchTerm);
var baseURL = "http://search.twitter.com/search.json";
for (pagenum = 1; pagenum <= maxPageNum; pagenum++) {
var URL = "";
if (typeof nextPage != "undefined"){
URL = nextPage+sinceurl;
} else if (pagenum == 1) {
URL = URL + "?q=" + searchTerm;
if (typeof since != "undefined") URL = URL + "&since=" + twDate(since);
if (typeof until != "undefined") URL = URL + "&until=" + twDate(until);
URL = URL + "&rpp=" + resultsPerPage;
URL = URL + "&page=" + pagenum;
URL = URL + "&result_type=recent";
URL = URL + "&include_entities=true";
URL = URL + "&with_twitter_user_id=true";
URL = URL + sinceurl;
/*
if (typeof languageCode != "undefined") {
if (languageCode.length > 0) {
URL = URL + "&lang=" + languageCode;
}
}
*/
}
if (URL != ""){
Logger.log(URL);
var response = UrlFetchApp.fetch(baseURL+URL, requestData);
var contentHeader = response.getHeaders();
if (response.getResponseCode() == 200) {
var responseData = Utilities.jsonParse(response.getContentText());
var nextPage = responseData.next_page;
var currentPage = responseData.page;
var objects = responseData.results;
for (i in objects){ // not pretty but I wanted to extract geo data
if (objects[i].geo != null){
objects[i]["geo_coordinates"] = "loc: "+objects[i].geo.coordinates[0]+","+objects[i].geo.coordinates[1];
}
objects[i]["status_url"] = "http://twitter.com/"+objects[i].from_user+"/statuses/"+objects[i].id_str;
objects[i].id_str = objects[i].id_str+" ";//used to force save to string
//objects[i].in_reply_to_status_id_str = objects[i].in_reply_to_status_id_str+" ";
objects[i]["time"] = (objects[i]["created_at"]).substring(5,25);
objects[i]["entities_str"] = Utilities.jsonStringify(objects[i]["entities"]);
var str = objects[i]["text"];
if (str.indexOf('? ')!=-1 || str.charAt(str.length-1)=="?"){
objects[i]["possible_question"]=true;
}
data[idx]=objects[i];
idx ++;
}
}
}
}
return data;
} catch (e) {
Logger.log("Line "+e.lineNumber+" "+e.message+e.name);
Browser.msgBox("Line "+e.lineNumber+" "+e.message+e.name);
ScriptProperties.setProperty("errormsg","Line "+e.lineNumber+" "+e.message+e.name);
return data;
}
}
function twDate(aDate){
var dateString = Utilities.formatDate(aDate, "GMT", "yyyy-MM-dd");
return dateString;
}
function testRate(){
var api_request = "account/rate_limit_status.json";
var data = tw_request("GET", api_request);
Logger.log(data.toString());
return data;
}
function tw_request(method, api_request){
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl(
"https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"method": method,
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
try {
var result = UrlFetchApp.fetch(
"https://api.twitter.com/1/"+api_request,
requestData);
var o = Utilities.jsonParse(result.getContentText());
Logger.log(o);
} catch (e) {
Logger.log(e);
}
return o;
}
function makeListOfTwitterIDUsernamesFromSearch(){
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sumSheet = doc.getSheetByName("Readme/Settings");
var SEARCH_TERM = sumSheet.getRange("B10").getValue();
var NUMBER_OF_TWEETS = sumSheet.getRange("B12").getValue();
doc.toast("Starting data collection");
var data = getTweets(SEARCH_TERM, NUMBER_OF_TWEETS);
var nodeList = [];
var nodes = [];
var nodeSheetName = "data";
if (!doc.getSheetByName(nodeSheetName)){
var sheetV = doc.insertSheet(nodeSheetName);
} else {
var sheetV = doc.getSheetByName(nodeSheetName);
sheetV.clearContents();
}
for (u in data){
if (!(data[u].from_user_id_str in oc(nodeList))){
nodeList.push(data[u].from_user_id_str);
nodes.push([data[u].from_user_id_str , data[u].from_user]);
}
}
sheetV.getRange(1,2).setValue(new Date());
sheetV.getRange(3,1,nodes.length,2).setValues(nodes);
getCommunityGraph("data")
replaceIDsWithNames();
doc.toast("All done! Refresh browser to see results");
}
function getCommunityGraph(optSource){
var source = optSource || "Summary";
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName(source);
var edgeSheetName = "Edges";
var verticesSheetName = "Vertices";
// get/make edges and Vertices sheet
if (!doc.getSheetByName(edgeSheetName)){
var sheetE = doc.insertSheet(edgeSheetName);
} else {
var sheetE = doc.getSheetByName(edgeSheetName);
if (sheetE.getLastRow()>0){
sheetE.getRange(1, 1, sheetE.getLastRow(), sheetE.getMaxColumns()).clear({contentsOnly:true});
}
}
if (!doc.getSheetByName(verticesSheetName)){
var temp = doc.getSheetByName("TMP_NODES");
var sheetV = doc.insertSheet(verticesSheetName, {template:temp});
} else {
var sheetV = doc.getSheetByName(verticesSheetName);
var test = sheetV.getLastRow();
if (sheetV.getLastRow()>1){
sheetV.getRange(2, 1, sheetV.getLastRow(), sheetV.getMaxColumns()).clear({contentsOnly:true});
}
}
// get the user_id_str from summary sheet
if (sheet.getLastRow()>253){
var maxRow = 250;
doc.toast("This function currently only collects friend/follower relationships for the top 250 twitter users appearing in this search archive","Important!");
} else {
var maxRow = sheet.getLastRow();
}
var user_ids = sheet.getRange(3,4,maxRow,2).getValues();
var users = {};
var links = [];
var nodes = [];
// get user friends
if (isConfigured()){
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl("https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl("https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"oAuthServiceName": "twitter",
"oAuthUseToken": "always",
"method": "GET"
};
} else {
var REFERER = doc.getSheetByName("Readme/Settings").sumSheet.getRange("B9").getValue();
var requestData = {"method":"GET", "headers": { "User-Agent": REFERER}};
Browser.msgBox("Warning: Results may be limited because you aren't using API Authenticated access");
}
for (var u = 0; u < user_ids.length; u++){
if (user_ids[u][0] != ""){
nodes.push(user_ids[u]);
try {
var next_cursor = -1; // only getting last 5000 friends
var url = "https://api.twitter.com/1/friends/ids.json?cursor="+next_cursor+"&stringify_ids=true&user_id="+user_ids[u][0];
var response = UrlFetchApp.fetch(url, requestData);
if (response.getResponseCode() == 200) {
var o = response.getContentText();
for (var t = 0; t < user_ids.length; t++){
if (user_ids[t][0] != ""){
var searchKey = new RegExp(user_ids[t][0],"gi");
if (o.search(searchKey) != -1){
links.push([user_ids[u][0],user_ids[t][0]]);
}
}
}
}
} catch(e) {
Logger.log(e);
//Browser.msgBox(e);
sheetE.getRange(1,1,links.length,2).setValues(links);
sheetV.getRange(2,1,nodes.length,2).setValues(nodes);
}
}
}
sheetE.getRange(1,1,links.length,2).setValues(links);
sheetV.getRange(2,1,nodes.length,2).setValues(nodes);
}
function replaceIDsWithNames(){
var doc = SpreadsheetApp.getActiveSpreadsheet();
var edgeSheetName = "Edges";
var verticesSheetName = "Vertices";
var sheetE = doc.getSheetByName(edgeSheetName);
var sheetV = doc.getSheetByName(verticesSheetName);
var user_ids = sheetV.getRange(2,1,sheetV.getLastRow(),2).getValues();
var edge_ids = sheetE.getRange(1,1,sheetE.getLastRow(),2).getValues();
for (var u=0; u<user_ids.length; u++){
for (var e=0; e<edge_ids.length; e++){
if (edge_ids[e][0] == user_ids[u][0]) edge_ids[e][0] = user_ids[u][1];
if (edge_ids[e][1] == user_ids[u][0]) edge_ids[e][1] = user_ids[u][1];
}
}
sheetE.getRange(1,1,sheetE.getLastRow(),2).setValues(edge_ids);
}
function lookupTwitterID(){
// lookup ids from twitter
var result = [];
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName("Vertices")
var users = sheet.getRange(2,1,sheet.getLastRow(),1).getValues();
var data = [];
if (isConfigured()){
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl(
"https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"method": "GET",
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
} else {
var REFERER = doc.getSheetByName("Readme/Settings").sumSheet.getRange("B9").getValue();
var requestData = {"method":"GET", "headers": { "User-Agent": REFERER}};
Browser.msgBox("Warning: Results may be limited because you aren't using API Authenticated access");
}
var chunks = chunk(users,100);
for (i in chunks){
var idurl ="http://api.twitter.com/1/users/lookup.json?user_id="+chunks[i].join();
try {
var response = UrlFetchApp.fetch(idurl, requestData);
if (response.getResponseCode() == 200) {
var objects = Utilities.jsonParse(response.getContentText());
for (j in objects){
data.push(objects[j]);
}
}
} catch(e) {
Browser.msgBox(e);
Logger.log(e);
}
}
if (data.length>0){
setRowsData(sheet, data);
}
}
function fillNodeUsingDegree(){
autofillSize(ScriptProperties.getProperty("Degree"),3,MINSIZE,MAXSIZE);
}
function fillNodeUsingInDegree(){
autofillSize(ScriptProperties.getProperty("In-Degree"),4,MINSIZE,MAXSIZE);
}
function fillNodeUsingOutDegree(){
autofillSize(ScriptProperties.getProperty("Out-Degree"),5,MINSIZE,MAXSIZE);
}
function fillNodeUsingBetweenness(){
autofillSize(ScriptProperties.getProperty("Betweenness"),6,MINSIZE,MAXSIZE);
}
function autofillSize(topLimit,col,min,max){
var doc = SpreadsheetApp.getActiveSpreadsheet();
var verticesSheetName = "Vertices";
var sheetV = doc.getSheetByName(verticesSheetName);
var user_ids = sheetV.getRange(2,col,sheetV.getLastRow()-1,1).getValues();
var output = [];
for (i=0;i<user_ids.length;i++){
var size = user_ids[i][0];
user_ids[i][0] = new Number(size*(max-min)/topLimit+min).toFixed(1);
}
sheetV.getRange(2,6,sheetV.getLastRow()-1,1).setValues(user_ids);
}
function calcDegree(){
var doc = SpreadsheetApp.getActiveSpreadsheet();
var edgeSheetName = "Edges";
var verticesSheetName = "Vertices";
var dMax = 0,
inDMax = 0,
outDMax = 0;
var sheetE = doc.getSheetByName(edgeSheetName);
var sheetV = doc.getSheetByName(verticesSheetName);
var user_ids = sheetV.getRange(2,2,sheetV.getLastRow()-1,1).getValues();
var edge_ids = sheetE.getRange(2,1,sheetE.getLastRow()-1,2).getValues();
var matrix = new Array(user_ids.length);
for (i=0; i <user_ids.length; i++) matrix[i]=replicate(3,0);
for (var i=0; i<user_ids.length; i++){
for (var k=0; k<edge_ids.length; k++){
if (user_ids[i][0]==edge_ids[k][0]){
matrix[i][0] = matrix[i][0] + 1;
matrix[i][2] = matrix[i][2] + 1;
if (matrix[i][0] > dMax) dMax = matrix[i][0];
if (matrix[i][2] > outDMax) outDMax = matrix[i][2];
}
if (user_ids[i][0]==edge_ids[k][1]){
matrix[i][0] = matrix[i][0] + 1;
matrix[i][1] = matrix[i][1] + 1;
if (matrix[i][0] > dMax) dMax = matrix[i][0];
if (matrix[i][1] > inDMax) inDMax = matrix[i][1];
}
}
}
ScriptProperties.setProperty("Degree",dMax);
ScriptProperties.setProperty("In-Degree",inDMax);
ScriptProperties.setProperty("Out-Degree",outDMax);
sheetV.getRange(2,3,matrix.length,3).setValues(matrix);
}
function calcBetweenness(){
var doc = SpreadsheetApp.getActiveSpreadsheet();
var edgeSheetName = "Edges";
var verticesSheetName = "Vertices";
var sheetE = doc.getSheetByName(edgeSheetName);
var sheetV = doc.getSheetByName(verticesSheetName);
var test = sheetV.getLastRow();
var user_ids = sheetV.getRange(2,2,sheetV.getLastRow()-1,1).getValues();
var edge_ids = sheetE.getRange(2,1,sheetE.getLastRow()-1,2).getValues();
Logger.log(new Date()+":make matrix ...");
var matrix = new Array(user_ids.length);
for (i=0; i <user_ids.length; i++) matrix[i]=replicate(user_ids.length,0);
for (var i=0; i<user_ids.length; i++){
Logger.log(new Date()+":user ..."+(i+1));
for (var j=0; j<user_ids.length; j++){
for (var k=0; k<edge_ids.length; k++){
if (user_ids[i][0]==edge_ids[k][0] && user_ids[j][0]==edge_ids[k][1]){
matrix[i][j] = 1;
break;
} else {
matrix[i][j] = 0;
}
}
}
}
Logger.log(new Date()+":... matrix made");
Logger.log(new Date()+":compute_betweenness");
var betweenness = compute_betweenness(matrix,user_ids.length);
var user_ids = sheetV.getRange(2,6,betweenness.length,1).setValues(betweenness);
}
// compute betweenness of each node in a network
// using the Brandes algorithm
// modified from NetVis Module 2.0
// by Jonathon N. Cummings
function compute_betweenness(matrix,ncols){
var betweenness = [];
var bMax = 0;
Logger.log(new Date()+":make betweenness matrix ...");
for(var i=0; i<ncols; i++){
betweenness[i]=0;
}
for(var s=0; s<ncols; s++){
var stack=[],
P=[],
sigma=[],
dist=[];
for(i=0;i<ncols;i++){
P[i]=[];
if(i==s){
sigma[i]=1;
dist[i]=0;
}else{
sigma[i]=0;
dist[i]=-1;
}
}
var queue=[];
queue.push(s);
while(queue.length > 0){
Logger.log(new Date()+":queue length: "+queue.length);
var v=queue.shift();
stack.push(v);
for(var w=0; w<ncols; w++){
if(matrix[v][w]==1){
if(dist[w] < 0){
//queue[]=w;
queue.push(w);
dist[w]=dist[v] + 1;
}
if(dist[w]==dist[v] + 1){
sigma[w]=sigma[w] +sigma[v];
//P[w][]=v;
P[w][P[w].length] = v;
}
}
}
}
var delta=[];
for(var i=0; i<ncols; i++){
delta[i]=0;
}
while(stack.length>0){
Logger.log(new Date()+":stack length: "+stack.length);
w=stack.pop();
for(var i=0; i<P[w].length; i++){
v=P[w][i];
delta[v] +=(sigma[v] /sigma[w]) * (1 +delta[w]);
}
if(w != s){
betweenness[w] +=delta[w];
}
}
}
for (var i=0; i<ncols; i++){
betweenness[i]=[(betweenness[i]/(2))];
if (betweenness[i] > bMax) bMax = betweenness[i][0];
}
ScriptProperties.setProperty("Betweenness",bMax);
return betweenness;
}
function alltrim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
// END OF (c)
function replicate (n, x) {
var xs = [];
for (var i = 0; i < n; ++i) {
xs.push(x);
}
return xs;
}
// http://jsfromhell.com/array/chunk
function chunk(a, s){
for(var x, i = 0, c = -1, l = a.length, n = []; i < l; i++)
(x = i % s) ? n[c][x] = a[i] : n[++c] = [a[i]];
return n;
}
// http://snook.ca/archives/javascript/testing_for_a_v
function oc(a)
{
var o = {};
for(var i=0;i<a.length;i++)
{
o[a[i]]='';
}
return o;
}
// Given a JavaScript 2d Array, this function returns the transposed table.
// Arguments:
// - data: JavaScript 2d Array
// Returns a JavaScript 2d Array
// Example: arrayTranspose([[1,2,3],[4,5,6]]) returns [[1,4],[2,5],[3,6]].
function arrayTranspose(data) {
if (data.length == 0 || data[0].length == 0) {
return null;
}
var ret = [];
for (var i = 0; i < data[0].length; ++i) {
ret.push([]);
}
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
ret[j][i] = data[i][j];
}
}
return ret;
}
// getColumnsData iterates column by column in the input range and returns an array of objects.
// Each object contains all the data for a given column, indexed by its normalized row name.
// [Modified by mhawksey]
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// This argument is optional and it defaults to all the cells except those in the first column
// or all the cells below rowHeadersIndex (if defined).
// - columnHeadersIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getColumnsData(sheet, range, columnHeadersIndex) {
var headersIndex = columnHeadersIndex || range ? range.getColumnIndex() - 1 : 1;
var dataRange = range ||
sheet.getRange(1, headersIndex + 1, sheet.getMaxRows(), sheet.getMaxColumns()- headersIndex);
var numRows = dataRange.getLastRow() - dataRange.getRow() + 1;
var headersRange = sheet.getRange(dataRange.getRow(),headersIndex,numRows,1);
var headers = arrayTranspose(headersRange.getValues())[0];
return getObjects(arrayTranspose(dataRange.getValues()), normalizeHeaders(headers));
}
// setRowsData fills in one row of data per object defined in the objects Array.
// For every Column, it checks if data objects define a value for it.
// Arguments:
// - sheet: the Sheet Object where the data will be written
// - objects: an Array of Objects, each of which contains data for a row
// - optHeadersRange: a Range of cells where the column headers are defined. This
// defaults to the entire first row in sheet.
// - optFirstDataRowIndex: index of the first row where data should be written. This
// defaults to the row immediately below the headers.
function setRowsData(sheet, objects, optHeadersRange, optFirstDataRowIndex) {
var headersRange = optHeadersRange || sheet.getRange(1, 1, 1, sheet.getMaxColumns());
var firstDataRowIndex = optFirstDataRowIndex || headersRange.getRowIndex() + 1;
var headers = normalizeHeaders(headersRange.getValues()[0]);
var data = [];
for (var i = 0; i < objects.length; ++i) {
var values = []
for (j = 0; j < headers.length; ++j) {
var header = headers[j];
values.push(header.length > 0 && objects[i][header] ? objects[i][header] : "");
}
data.push(values);
}
var destinationRange = sheet.getRange(firstDataRowIndex, headersRange.getColumnIndex(),
objects.length, headers.length);
destinationRange.setValues(data);
}
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// This argument is optional and it defaults to all the cells except those in the first row
// or all the cells below columnHeadersRowIndex (if defined).
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
var headersIndex = columnHeadersRowIndex || range ? range.getRowIndex() - 1 : 1;
var dataRange = range ||
sheet.getRange(headersIndex + 1, 1, sheet.getMaxRows() - headersIndex, sheet.getMaxColumns());
var numColumns = dataRange.getEndColumn() - dataRange.getColumn() + 1;
var headersRange = sheet.getRange(headersIndex, dataRange.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(dataRange.getValues(), normalizeHeaders(headers));
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Empty Strings are returned for all Strings that could not be successfully normalized.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
keys.push(normalizeHeader(headers[i]));
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
//if (!isAlnum(letter)) { // I removed this because result identifiers have '_' in name
// continue;
//}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
return char >= '0' && char <= '9';
}
// The first part of this code was developed by google and has a copyright statement.
// Everything after // Archive Twitter Status Updates is by mhawksey and released under CC
// Copyright 2010 Google Inc. All Rights Reserved.
/**
* @fileoverview Google Apps Script demo application to illustrate usage of:
* MailApp
* OAuthConfig
* ScriptProperties
* Twitter Integration
* UiApp
* UrlFetchApp
*
* @author vicfryzel@google.com (Vic Fryzel)
*/
/**
* Key of ScriptProperty for Twitter consumer key.
* @type {String}
* @const
*/
var CONSUMER_KEY_PROPERTY_NAME = "twitterConsumerKey";
/**
* Key of ScriptProperty for Twitter consumer secret.
* @type {String}
* @const
*/
var CONSUMER_SECRET_PROPERTY_NAME = "twitterConsumerSecret";
/**
* Key of ScriptProperty for tweets and all approvers.
* @type {String}
* @const
*/
var TWEETS_APPROVERS_PROPERTY_NAME = "twitterTweetsWithApprovers";
/**
* @param String Approver email address required to give approval
* prior to a tweet going live. Comma-delimited.
*/
function setApprovers(approvers) {
ScriptProperties.setProperty(APPROVERS_PROPERTY_NAME, approvers);
}
/**
* @return String OAuth consumer key to use when tweeting.
*/
function getConsumerKey() {
var key = ScriptProperties.getProperty(CONSUMER_KEY_PROPERTY_NAME);
if (key == null) {
key = "";
}
return key;
}
/**
* @param String OAuth consumer key to use when tweeting.
*/
function setConsumerKey(key) {
ScriptProperties.setProperty(CONSUMER_KEY_PROPERTY_NAME, key);
}
/**
* @return String OAuth consumer secret to use when tweeting.
*/
function getConsumerSecret() {
var secret = ScriptProperties.getProperty(CONSUMER_SECRET_PROPERTY_NAME);
if (secret == null) {
secret = "";
}
return secret;
}
/**
* @param String OAuth consumer secret to use when tweeting.
*/
function setConsumerSecret(secret) {
ScriptProperties.setProperty(CONSUMER_SECRET_PROPERTY_NAME, secret);
}
/**
* @return bool True if all of the configuration properties are set,
* false if otherwise.
*/
function isConfigured() {
return getConsumerKey() != "" && getConsumerSecret != "" ;
}
/** Retrieve config params from the UI and store them. */
function saveConfiguration(e) {
setConsumerKey(e.parameter.consumerKey);
setConsumerSecret(e.parameter.consumerSecret);
var app = UiApp.getActiveApplication();
app.close();
return app;
}
/**
* Authorize against Twitter. This method must be run prior to
* clicking any link in a script email. If you click a link in an
* email, you will get a message stating:
* "Authorization is required to perform that action."
*/
function authorize() {
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl(
"https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"method": "GET",
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
var result = UrlFetchApp.fetch(
"http://api.twitter.com/1/account/verify_credentials.json",
requestData);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.