<commit_before>import {NativeEventEmitter, NativeModules} from "react-native";

const { RNAppsFlyer }        = NativeModules;
const appsFlyer              = {};
const eventsMap              = {};
const appsFlyerEventEmitter  = new NativeEventEmitter(RNAppsFlyer);

function initSdkCallback(options, successC, errorC) {
  return RNAppsFlyer.initSdk(options, successC, errorC);
}

function initSdkPromise(options): Promise<string> {
  return RNAppsFlyer.initSdkWithPromise(options);
}

function initSdk(options, success, error): Promise<string> {
  options.onInstallConversionDataListener = eventsMap["onInstallConversionData"]
      ? true
      : false;

  if (success && error) {
    //initSdk is a callback function
    initSdkCallback(options, success, error);
  } else if (!success) {
    //initSdk is a promise function
    return initSdkPromise(options);
  }
}
appsFlyer.initSdk = initSdk;

function logEventCallback(eventName, eventValues, successC, errorC) {
  return RNAppsFlyer.logEvent(eventName, eventValues, successC, errorC);
}

function logEventPromise(eventName, eventValues): Promise<string> {
  return RNAppsFlyer.logEventWithPromise(eventName, eventValues);
}

function logEvent(eventName, eventValues, success, error): Promise<string> {
  if (success && error) {
    //logEvent is a callback function
    logEventCallback(eventName, eventValues, success, error);
  } else if (!success) {
    //logEvent is a promise function
    return logEventPromise(eventName, eventValues);
  }
}

appsFlyer.logEvent = logEvent;

/**
 * Manually record the location of the user
 *
 * @param longitude latitude as double.
 * @param latitude latitude as double.
 * @param callback success callback function
 */
appsFlyer.logLocation = (longitude, latitude, callback) => {
  return RNAppsFlyer.logLocation(longitude, latitude, callback);
};

/**
 * Set the user emails and encrypt them.
 *
 * @param options latitude as double.
 * @param successC success callback function.
 * @param errorC error callback function.
 */
appsFlyer.setUserEmails = (options, successC, errorC) => {
  return RNAppsFlyer.setUserEmails(options, successC, errorC);
};

/**
 * Set additional data to be sent to AppsFlyer.
 *
 * @param additionalData additional data Dictionary.
 * @param successC success callback function.
 */
appsFlyer.setAdditionalData = (additionalData, successC) => {
  return RNAppsFlyer.setAdditionalData(additionalData, successC);
};

/**
 * Get AppsFlyer's unique device ID is created for every new install of an app.
 *
 * @callback callback function that returns (error,uid)
 */
appsFlyer.getAppsFlyerUID = callback => {
  return RNAppsFlyer.getAppsFlyerUID(callback);
};

appsFlyer.sendDeepLinkData = callback => {
  return RNAppsFlyer.sendDeepLinkData(callback);
};

/**
 * @deprecated
 */
appsFlyer.setGCMProjectNumber = (gcmProjectNumber, successC, errorC) => {
  return RNAppsFlyer.setGCMProjectNumber(gcmProjectNumber, successC, errorC);
};

/**
 * Manually pass the Firebase / GCM Device Token for Uninstall measurement.
 *
 * @param token Firebase Device Token.
 * @param successC success callback function.
 */
appsFlyer.updateServerUninstallToken = (token, successC) => {
  return RNAppsFlyer.updateServerUninstallToken(token, successC);
};

/**
 * Setting your own customer ID enables you to cross-reference your own unique ID with AppsFlyer’s unique ID and the other devices’ IDs.
 * This ID is available in AppsFlyer CSV reports along with Postback APIs for cross-referencing with your internal IDs.
 *
 * @param {string} userId Customer ID for client.
 * @param successC callback function.
 */
appsFlyer.setCustomerUserId = (userId, successC) => {
  return RNAppsFlyer.setCustomerUserId(userId, successC);
};

/**
 * Once this API is invoked, our SDK no longer communicates with our servers and stops functioning.
 * In some extreme cases you might want to shut down all SDK activity due to legal and privacy compliance.
 * This can be achieved with the stop API.
 *
 * @param {boolean} isStopped boolean should SDK be stopped.
 * @param successC callback function.
 */
appsFlyer.stop = (isStopped, successC) => {
  return RNAppsFlyer.stop(isStopped, successC);
};

/**
 * Opt-out of collection of IMEI.
 * If the app does NOT contain Google Play Services, device IMEI is collected by the SDK.
 * However, apps with Google play services should avoid IMEI collection as this is in violation of the Google Play policy.
 *
 * @param {boolean} isCollect boolean, false to opt out.
 * @param successC callback function.
 * @platform android
 */
appsFlyer.setCollectIMEI = (isCollect, successC) => {
  return RNAppsFlyer.setCollectIMEI(isCollect, successC);
};

/**
 * Opt-out of collection of Android ID.
 * If the app does NOT contain Google Play Services, Android ID is collected by the SDK.
 * However, apps with Google play services should avoid Android ID collection as this is in violation of the Google Play policy.
 *
 * @param {boolean} isCollect boolean, false to opt out.
 * @param successC callback function.
 * @platform android
 */
appsFlyer.setCollectAndroidID = (isCollect, successC) => {
  return RNAppsFlyer.setCollectAndroidID(isCollect, successC);
};

/**
 * Set the OneLink ID that should be used for User-Invite-API.
 * The link that is generated for the user invite will use this OneLink as the base link.
 *
 * @param {string} oneLinkID OneLink ID obtained from the AppsFlyer Dashboard.
 * @param successC callback function.
 */
appsFlyer.setAppInviteOneLinkID = (oneLinkID, successC) => {
  return RNAppsFlyer.setAppInviteOneLinkID(oneLinkID, successC);
};

/**
 * The LinkGenerator class builds the invite URL according to various setter methods which allow passing on additional information on the click.
 * @see https://support.appsflyer.com/hc/en-us/articles/115004480866-User-invite-attribution-
 *
 * @param parameters Dictionary.
 * @param success success callback function..
 * @param error error callback function.
 */
appsFlyer.generateInviteLink = (parameters, success, error) => {
  return RNAppsFlyer.generateInviteLink(parameters, success, error);
};

/**
 * To attribute an impression use the following API call.
 * Make sure to use the promoted App ID as it appears within the AppsFlyer dashboard.
 *
 * @param appId promoted App ID.
 * @param campaign cross promotion campaign.
 * @param parameters additional params to be added to the attribution link
 */
appsFlyer.logCrossPromotionImpression = (appId, campaign, parameters) => {
  return RNAppsFlyer.logCrossPromotionImpression(appId, campaign, parameters);
};

/**
 * Use the following API to attribute the click and launch the app store's app page.
 *
 * @param appId promoted App ID.
 * @param campaign cross promotion campaign.
 * @param params additional user params.
 */
appsFlyer.logAndOpenStore = (appId, campaign, params) => {
  return RNAppsFlyer.logAndOpenStore(appId, campaign, params);
};

/**
 * Setting user local currency code for in-app purchases.
 * The currency code should be a 3 character ISO 4217 code. (default is USD).
 * You can set the currency code for all events by calling the following method.
 * @param currencyCode
 * @param successC success callback function.
 */
appsFlyer.setCurrencyCode = (currencyCode, successC) => {
  return RNAppsFlyer.setCurrencyCode(currencyCode, successC);
};

/**
 * Accessing AppsFlyer Attribution / Conversion Data from the SDK (Deferred Deeplinking)
 * @param callback: contains fields:
 *    status: success/failure
 *    type:
 *          onAppOpenAttribution
 *          onInstallConversionDataLoaded
 *          onAttributionFailure
 *          onInstallConversionFailure
 *    data: metadata,
 * @example {"status":"success","type":"onInstallConversionDataLoaded","data":{"af_status":"Organic","af_message":"organic install"}}
 *
 * @returns {remove: function - unregister listener}
 */
appsFlyer.onInstallConversionData = callback => {

  const listener = appsFlyerEventEmitter.addListener(
      "onInstallConversionDataLoaded",
      _data => {
        if (callback && typeof callback === typeof Function) {
          try {
            let data = JSON.parse(_data);
            callback(data);
          } catch (_error) {
            //throw new AFParseJSONException("...");
            //TODO: for today we return an error in callback
            callback(new AFParseJSONException("Invalid data structure", _data));
          }
        }
      }
  );

  eventsMap["onInstallConversionData"] = listener;

  // unregister listener (suppose should be called from componentWillUnmount() )
  return function remove() {
    listener.remove();
  };
};

appsFlyer.onInstallConversionFailure = callback => {

  const listener = appsFlyerEventEmitter.addListener(
      "onInstallConversionFailure",
      _data => {
        if (callback && typeof callback === typeof Function) {
          try {
            let data = JSON.parse(_data);
            callback(data);
          } catch (_error) {
            //throw new AFParseJSONException("...");
            //TODO: for today we return an error in callback
            callback(new AFParseJSONException("Invalid data structure", _data));
          }
        }
      }
  );

  eventsMap["onInstallConversionFailure"] = listener;

  // unregister listener (suppose should be called from componentWillUnmount() )
  return function remove() {
    listener.remove();
  };
};

appsFlyer.onAppOpenAttribution = callback => {

  //console.log("onAppOpenAttribution is called" );

  const listener = appsFlyerEventEmitter.addListener(
      "onAppOpenAttribution",
      _data => {
        if (callback && typeof callback === typeof Function) {
          try {
            let data = JSON.parse(_data);
            callback(data);
          } catch (_error) {
            callback(new AFParseJSONException("Invalid data structure", _data));
          }
        }
      }
  );

  eventsMap["onAppOpenAttribution"] = listener;

  // unregister listener (suppose should be called from componentWillUnmount() )
  return function remove() {
    listener.remove();
  };
};

/**
 * Anonymize user Data.
 * Use this API during the SDK Initialization to explicitly anonymize a user's installs, events and sessions.
 * Default is false
 * @param isDeviceLoggingDisabled boolean
 * @param successC success callback function.
 */
appsFlyer.setDeviceLoggingDisabled = (isDeviceLoggingDisabled, successC) => {
  return RNAppsFlyer.setDeviceLoggingDisabled(isDeviceLoggingDisabled, successC);
};

/**
 * Set Onelink custom/branded domains
 * Use this API during the SDK Initialization to indicate branded domains.
 * For more information please refer to https://support.appsflyer.com/hc/en-us/articles/360002329137-Implementing-Branded-Links
 * @param domains array of strings
 * @param successC success callback function.
 * @param errorC error callback function.
 */
appsFlyer.setOneLinkCustomDomains = (domains, successC, errorC) => {
  return RNAppsFlyer.setOneLinkCustomDomains(domains, successC, errorC);
};

/**
 * Set domains used by ESP when wrapping your deeplinks.
 * Use this API during the SDK Initialization to indicate that links from certain domains should be resolved
 * in order to get original deeplink
 * For more information please refer to https://support.appsflyer.com/hc/en-us/articles/360001409618-Email-service-provider-challenges-with-iOS-Universal-links
 * @param urls array of strings
 * @param successC success callback function.
 * @param errorC error callback function.
 */
appsFlyer.setResolveDeepLinkURLs = (urls, successC, errorC) => {
  return RNAppsFlyer.setResolveDeepLinkURLs(urls, successC, errorC);
};

appsFlyer.performOnAppAttribution = (urlString, callback) => {
  return RNAppsFlyer.performOnAppAttribution(urlString, callback);
}

appsFlyer.setSharingFilterForAllPartners = () => {
  return RNAppsFlyer.setSharingFilterForAllPartners();
}

appsFlyer.setSharingFilter = (partners, successC, errorC) => {
  return RNAppsFlyer.setSharingFilter(partners, successC, errorC);
}

/**
 * iOS only
 */
appsFlyer.waitForAdvertisingIdentifierWithTimeoutInterval = (timeoutInterval, successC, errorC) => {
  return RNAppsFlyer.waitForAdvertisingIdentifierWithTimeoutInterval(timeoutInterval * 1000, successC, errorC);
}

function AFParseJSONException(_message, _data) {
  this.message = _message;
  this.data = _data;
  this.name = "AFParseJSONException";
}

export default appsFlyer;
<commit_msg>refactoring<commit_after>import {NativeEventEmitter, NativeModules} from "react-native";

const { RNAppsFlyer }        = NativeModules;
const appsFlyer              = {};
const eventsMap              = {};
const appsFlyerEventEmitter  = new NativeEventEmitter(RNAppsFlyer);

function initSdkCallback(options, successC, errorC) {
  return RNAppsFlyer.initSdk(options, successC, errorC);
}

function initSdkPromise(options): Promise<string> {
  return RNAppsFlyer.initSdkWithPromise(options);
}

function initSdk(options, success, error): Promise<string> {
  options.onInstallConversionDataListener = eventsMap["onInstallConversionData"]
      ? true
      : false;

  if (success && error) {
    //initSdk is a callback function
    initSdkCallback(options, success, error);
  } else if (!success) {
    //initSdk is a promise function
    return initSdkPromise(options);
  }
}
appsFlyer.initSdk = initSdk;

function logEventCallback(eventName, eventValues, successC, errorC) {
  return RNAppsFlyer.logEvent(eventName, eventValues, successC, errorC);
}

function logEventPromise(eventName, eventValues): Promise<string> {
  return RNAppsFlyer.logEventWithPromise(eventName, eventValues);
}

function logEvent(eventName, eventValues, success, error): Promise<string> {
  if (success && error) {
    //logEvent is a callback function
    logEventCallback(eventName, eventValues, success, error);
  } else if (!success) {
    //logEvent is a promise function
    return logEventPromise(eventName, eventValues);
  }
}

appsFlyer.logEvent = logEvent;

/**
 * Manually record the location of the user
 *
 * @param longitude latitude as double.
 * @param latitude latitude as double.
 * @param callback success callback function
 */
appsFlyer.logLocation = (longitude, latitude, callback) => {
  return RNAppsFlyer.logLocation(longitude, latitude, callback);
};

/**
 * Set the user emails and encrypt them.
 *
 * @param options latitude as double.
 * @param successC success callback function.
 * @param errorC error callback function.
 */
appsFlyer.setUserEmails = (options, successC, errorC) => {
  return RNAppsFlyer.setUserEmails(options, successC, errorC);
};

/**
 * Set additional data to be sent to AppsFlyer.
 *
 * @param additionalData additional data Dictionary.
 * @param successC success callback function.
 */
appsFlyer.setAdditionalData = (additionalData, successC) => {
  return RNAppsFlyer.setAdditionalData(additionalData, successC);
};

/**
 * Get AppsFlyer's unique device ID is created for every new install of an app.
 *
 * @callback callback function that returns (error,uid)
 */
appsFlyer.getAppsFlyerUID = callback => {
  return RNAppsFlyer.getAppsFlyerUID(callback);
};

appsFlyer.sendDeepLinkData = callback => {
  return RNAppsFlyer.sendDeepLinkData(callback);
};

/**
 * @deprecated
 */
appsFlyer.setGCMProjectNumber = (gcmProjectNumber, successC, errorC) => {
  return RNAppsFlyer.setGCMProjectNumber(gcmProjectNumber, successC, errorC);
};

/**
 * Manually pass the Firebase / GCM Device Token for Uninstall measurement.
 *
 * @param token Firebase Device Token.
 * @param successC success callback function.
 */
appsFlyer.updateServerUninstallToken = (token, successC) => {
  return RNAppsFlyer.updateServerUninstallToken(token, successC);
};

/**
 * Setting your own customer ID enables you to cross-reference your own unique ID with AppsFlyer’s unique ID and the other devices’ IDs.
 * This ID is available in AppsFlyer CSV reports along with Postback APIs for cross-referencing with your internal IDs.
 *
 * @param {string} userId Customer ID for client.
 * @param successC callback function.
 */
appsFlyer.setCustomerUserId = (userId, successC) => {
  return RNAppsFlyer.setCustomerUserId(userId, successC);
};

/**
 * Once this API is invoked, our SDK no longer communicates with our servers and stops functioning.
 * In some extreme cases you might want to shut down all SDK activity due to legal and privacy compliance.
 * This can be achieved with the stop API.
 *
 * @param {boolean} isStopped boolean should SDK be stopped.
 * @param successC callback function.
 */
appsFlyer.stop = (isStopped, successC) => {
  return RNAppsFlyer.stop(isStopped, successC);
};

/**
 * Opt-out of collection of IMEI.
 * If the app does NOT contain Google Play Services, device IMEI is collected by the SDK.
 * However, apps with Google play services should avoid IMEI collection as this is in violation of the Google Play policy.
 *
 * @param {boolean} isCollect boolean, false to opt out.
 * @param successC callback function.
 * @platform android
 */
appsFlyer.setCollectIMEI = (isCollect, successC) => {
  return RNAppsFlyer.setCollectIMEI(isCollect, successC);
};

/**
 * Opt-out of collection of Android ID.
 * If the app does NOT contain Google Play Services, Android ID is collected by the SDK.
 * However, apps with Google play services should avoid Android ID collection as this is in violation of the Google Play policy.
 *
 * @param {boolean} isCollect boolean, false to opt out.
 * @param successC callback function.
 * @platform android
 */
appsFlyer.setCollectAndroidID = (isCollect, successC) => {
  return RNAppsFlyer.setCollectAndroidID(isCollect, successC);
};

/**
 * Set the OneLink ID that should be used for User-Invite-API.
 * The link that is generated for the user invite will use this OneLink as the base link.
 *
 * @param {string} oneLinkID OneLink ID obtained from the AppsFlyer Dashboard.
 * @param successC callback function.
 */
appsFlyer.setAppInviteOneLinkID = (oneLinkID, successC) => {
  return RNAppsFlyer.setAppInviteOneLinkID(oneLinkID, successC);
};

/**
 * The LinkGenerator class builds the invite URL according to various setter methods which allow passing on additional information on the click.
 * @see https://support.appsflyer.com/hc/en-us/articles/115004480866-User-invite-attribution-
 *
 * @param parameters Dictionary.
 * @param success success callback function..
 * @param error error callback function.
 */
appsFlyer.generateInviteLink = (parameters, success, error) => {
  return RNAppsFlyer.generateInviteLink(parameters, success, error);
};

/**
 * To attribute an impression use the following API call.
 * Make sure to use the promoted App ID as it appears within the AppsFlyer dashboard.
 *
 * @param appId promoted App ID.
 * @param campaign cross promotion campaign.
 * @param parameters additional params to be added to the attribution link
 */
appsFlyer.logCrossPromotionImpression = (appId, campaign, parameters) => {
  return RNAppsFlyer.logCrossPromotionImpression(appId, campaign, parameters);
};

/**
 * Use the following API to attribute the click and launch the app store's app page.
 *
 * @param appId promoted App ID.
 * @param campaign cross promotion campaign.
 * @param params additional user params.
 */
appsFlyer.logAndOpenStore = (appId, campaign, params) => {
  return RNAppsFlyer.logAndOpenStore(appId, campaign, params);
};

/**
 * Setting user local currency code for in-app purchases.
 * The currency code should be a 3 character ISO 4217 code. (default is USD).
 * You can set the currency code for all events by calling the following method.
 * @param currencyCode
 * @param successC success callback function.
 */
appsFlyer.setCurrencyCode = (currencyCode, successC) => {
  return RNAppsFlyer.setCurrencyCode(currencyCode, successC);
};

/**
 * Accessing AppsFlyer Attribution / Conversion Data from the SDK (Deferred Deeplinking)
 * @param callback: contains fields:
 *    status: success/failure
 *    type:
 *          onAppOpenAttribution
 *          onInstallConversionDataLoaded
 *          onAttributionFailure
 *          onInstallConversionFailure
 *    data: metadata,
 * @example {"status":"success","type":"onInstallConversionDataLoaded","data":{"af_status":"Organic","af_message":"organic install"}}
 *
 * @returns {remove: function - unregister listener}
 */
appsFlyer.onInstallConversionData = callback => {

  const listener = appsFlyerEventEmitter.addListener(
      "onInstallConversionDataLoaded",
      _data => {
        if (callback && typeof callback === typeof Function) {
          try {
            let data = JSON.parse(_data);
            callback(data);
          } catch (_error) {
            //throw new AFParseJSONException("...");
            //TODO: for today we return an error in callback
            callback(new AFParseJSONException("Invalid data structure", _data));
          }
        }
      }
  );

  eventsMap["onInstallConversionData"] = listener;

  // unregister listener (suppose should be called from componentWillUnmount() )
  return function remove() {
    listener.remove();
  };
};

appsFlyer.onInstallConversionFailure = callback => {

  const listener = appsFlyerEventEmitter.addListener(
      "onInstallConversionFailure",
      _data => {
        if (callback && typeof callback === typeof Function) {
          try {
            let data = JSON.parse(_data);
            callback(data);
          } catch (_error) {
            //throw new AFParseJSONException("...");
            //TODO: for today we return an error in callback
            callback(new AFParseJSONException("Invalid data structure", _data));
          }
        }
      }
  );

  eventsMap["onInstallConversionFailure"] = listener;

  // unregister listener (suppose should be called from componentWillUnmount() )
  return function remove() {
    listener.remove();
  };
};

appsFlyer.onAppOpenAttribution = callback => {

  //console.log("onAppOpenAttribution is called" );

  const listener = appsFlyerEventEmitter.addListener(
      "onAppOpenAttribution",
      _data => {
        if (callback && typeof callback === typeof Function) {
          try {
            let data = JSON.parse(_data);
            callback(data);
          } catch (_error) {
            callback(new AFParseJSONException("Invalid data structure", _data));
          }
        }
      }
  );

  eventsMap["onAppOpenAttribution"] = listener;

  // unregister listener (suppose should be called from componentWillUnmount() )
  return function remove() {
    listener.remove();
  };
};

/**
 * Anonymize user Data.
 * Use this API during the SDK Initialization to explicitly anonymize a user's installs, events and sessions.
 * Default is false
 * @param isDeviceLoggingDisabled boolean
 * @param successC success callback function.
 */
appsFlyer.setDeviceLoggingDisabled = (isDeviceLoggingDisabled, successC) => {
  return RNAppsFlyer.setDeviceLoggingDisabled(isDeviceLoggingDisabled, successC);
};

/**
 * Set Onelink custom/branded domains
 * Use this API during the SDK Initialization to indicate branded domains.
 * For more information please refer to https://support.appsflyer.com/hc/en-us/articles/360002329137-Implementing-Branded-Links
 * @param domains array of strings
 * @param successC success callback function.
 * @param errorC error callback function.
 */
appsFlyer.setOneLinkCustomDomains = (domains, successC, errorC) => {
  return RNAppsFlyer.setOneLinkCustomDomains(domains, successC, errorC);
};

/**
 * Set domains used by ESP when wrapping your deeplinks.
 * Use this API during the SDK Initialization to indicate that links from certain domains should be resolved
 * in order to get original deeplink
 * For more information please refer to https://support.appsflyer.com/hc/en-us/articles/360001409618-Email-service-provider-challenges-with-iOS-Universal-links
 * @param urls array of strings
 * @param successC success callback function.
 * @param errorC error callback function.
 */
appsFlyer.setResolveDeepLinkURLs = (urls, successC, errorC) => {
  return RNAppsFlyer.setResolveDeepLinkURLs(urls, successC, errorC);
};

appsFlyer.performOnAppAttribution = (urlString, callback) => {
  return RNAppsFlyer.performOnAppAttribution(urlString, callback);
}

appsFlyer.setSharingFilterForAllPartners = () => {
  return RNAppsFlyer.setSharingFilterForAllPartners();
}

appsFlyer.setSharingFilter = (partners, successC, errorC) => {
  return RNAppsFlyer.setSharingFilter(partners, successC, errorC);
}

/**
 * iOS only
 */
appsFlyer.waitForAdvertisingIdentifierWithTimeoutInterval = (timeoutInterval, successC, errorC) => {
  return RNAppsFlyer.waitForAdvertisingIdentifierWithTimeoutInterval(timeoutInterval * 1000, successC, errorC);
}

function AFParseJSONException(_message, _data) {
  this.message = _message;
  this.data = _data;
  this.name = "AFParseJSONException";
}

export default appsFlyer;
<|endoftext|>


<commit_before>/* global app:true, io:false */

var socket;
var myname;
var block_id;
var blockData;
var ledData;
var ledTime;
var imageData;
var imageTime;
var timeline;

(function() {
  'use strict';

  //var blockdata = [];
  //var qs = new Querystring();
  //var block_id = qs.get("myBlock");

  socket = io.connect();
  socket.on('connect', function(){
  	socket.emit('/replay/#join');
  });

  socket.on('/replay/#postdata', function(data){
  	blockData = [];
	ledData = [];
	ledTime = [];
	blockData.push(data[0]); // time
	blockData.push(data[1]); // owner
	blockData.push(data[2]); // experiment id
	blockData.push(data[3]); // pattern id

	// image dir = 171.65.102.132:3001/blockid/

	for (var i=0;i<data[4].length/2;i++)
	{
	  ledData.push(data[4][i*2]);
	  ledTime.push(Math.round(parseInt(data[4][i*2+1])/100)*100);
	}

	console.log(blockData);
	console.log(ledData);
	console.log(ledData.length);
	console.log(ledTime);
	console.log(ledTime.length);
  });

  socket.on('/replay/#postimglist', function(data){
	imageData = [];
	imageTime = [];
	timeline = [];
	data.forEach(function(filename){
	    var res = filename.split(".");
	    var convertDate = new Date(res[0]);
	    imageTime.push(convertDate.getTime()+convertDate.getMilliseconds());
	    imageData.push(filename);
	});

	console.log(imageData);
	console.log(imageData.length);
	console.log(imageTime);
	console.log(imageTime.length);
  });

  socket.on('/replay/#newUser', function(user) {
      myname = user;
      console.log('>>> DB connected' + block_id);
  });

  socket.on('message', function (message) {
  	console.log(message);
  });

  socket.on('disconnect', function() {
	console.log('>>> DB disconnected');
  });

  app = app || {};

  app.Reset = Backbone.Model.extend({
    defaults: {
      success: false,
      errors: [],
      errfor: {},
      blockid: undefined,
      confitm: ''
    },
    url: function(){
      return '/account/replay/' + this.get('block_id') +'/';
    }
  });

  /*app.BlocksView = Backbone.View.extend({
    el: '#blocks_nav',
    template: _.template( $('#tmpl-blocks_nav').html() ),
    events: {
      'click .btn-prev': 'reqPrev',
      'click .btn-now': 'reqNow',
      'click .btn-next': 'reqNext'
    },
    initialize: function() {
      this.model = new app.Blocks();
      this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes));
    },
    reqPrev: function() {
      currenttime.setHours(currenttime.getHours() - 1);
      callBlocks(currenttime);
    },
    reqNow: function() {
      currenttime = new Date();
      callBlocks(currenttime);
    },
    reqNext: function() {
      currenttime.setHours(currenttime.getHours() + 1);
      callBlocks(currenttime);
    }
  });*/

  app.Router = Backbone.Router.extend({
    routes: {
      'account/replay/': 'default',
      'account/replay/load/:block/': 'load'
    },
    default: function(){
      console.log(" >>default view, nothing loaded");
    },
    load: function(block) {
      console.log(">> loading block "+block);
      block_id = block;
      socket.emit('/replay/#callblock', { targetBlock: block});
    }
  });

  $(document).ready(function() {
    //app.blocksView = new app.BlocksView();
    app.router = new app.Router();
    Backbone.history.start({ pushState: true });
  });

}());
<commit_msg>image name<commit_after>/* global app:true, io:false */

var socket;
var myname;
var block_id;
var blockData;
var ledData;
var ledTime;
var imageData;
var imageTime;
var timeline;

(function() {
  'use strict';

  //var blockdata = [];
  //var qs = new Querystring();
  //var block_id = qs.get("myBlock");

  socket = io.connect();
  socket.on('connect', function(){
  	socket.emit('/replay/#join');
  });

  socket.on('/replay/#postdata', function(data){
  	blockData = [];
	ledData = [];
	ledTime = [];
	blockData.push(data[0]); // time
	blockData.push(data[1]); // owner
	blockData.push(data[2]); // experiment id
	blockData.push(data[3]); // pattern id

	// image dir = 171.65.102.132:3001/blockid/

	for (var i=0;i<data[4].length/2;i++)
	{
	  ledData.push(data[4][i*2]);
	  ledTime.push(Math.round(parseInt(data[4][i*2+1])/100)*100);
	}

	console.log(blockData);
	console.log(ledData);
	console.log(ledData.length);
	console.log(ledTime);
	console.log(ledTime.length);
  });

  socket.on('/replay/#postimglist', function(data){
	imageData = [];
	imageTime = [];
	timeline = [];
	data.forEach(function(filename){
	    var res = filename.split(".");
	    imageTime.push(parseInt(res[0]));
	    imageData.push(filename);
	});

	console.log(imageData);
	console.log(imageData.length);
	console.log(imageTime);
	console.log(imageTime.length);
  });

  socket.on('/replay/#newUser', function(user) {
      myname = user;
      console.log('>>> DB connected' + block_id);
  });

  socket.on('message', function (message) {
  	console.log(message);
  });

  socket.on('disconnect', function() {
	console.log('>>> DB disconnected');
  });

  app = app || {};

  app.Reset = Backbone.Model.extend({
    defaults: {
      success: false,
      errors: [],
      errfor: {},
      blockid: undefined,
      confitm: ''
    },
    url: function(){
      return '/account/replay/' + this.get('block_id') +'/';
    }
  });

  /*app.BlocksView = Backbone.View.extend({
    el: '#blocks_nav',
    template: _.template( $('#tmpl-blocks_nav').html() ),
    events: {
      'click .btn-prev': 'reqPrev',
      'click .btn-now': 'reqNow',
      'click .btn-next': 'reqNext'
    },
    initialize: function() {
      this.model = new app.Blocks();
      this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes));
    },
    reqPrev: function() {
      currenttime.setHours(currenttime.getHours() - 1);
      callBlocks(currenttime);
    },
    reqNow: function() {
      currenttime = new Date();
      callBlocks(currenttime);
    },
    reqNext: function() {
      currenttime.setHours(currenttime.getHours() + 1);
      callBlocks(currenttime);
    }
  });*/

  app.Router = Backbone.Router.extend({
    routes: {
      'account/replay/': 'default',
      'account/replay/load/:block/': 'load'
    },
    default: function(){
      console.log(" >>default view, nothing loaded");
    },
    load: function(block) {
      console.log(">> loading block "+block);
      block_id = block;
      socket.emit('/replay/#callblock', { targetBlock: block});
    }
  });

  $(document).ready(function() {
    //app.blocksView = new app.BlocksView();
    app.router = new app.Router();
    Backbone.history.start({ pushState: true });
  });

}());
<|endoftext|>


<commit_before>var chai      = require('chai')
  , expect    = chai.expect
  , Support   = require(__dirname + '/../support')
  , dialect   = Support.getTestDialect()
  , DataTypes = require(__dirname + "/../../lib/data-types")
  , _         = require('lodash')

chai.config.includeStack = true

if (dialect.match(/^postgres/)) {
  describe('[POSTGRES Specific] DAO', function() {
    beforeEach(function(done) {
      this.sequelize.options.quoteIdentifiers = true
      this.User = this.sequelize.define('User', {
        username: DataTypes.STRING,
        email: {type: DataTypes.ARRAY(DataTypes.TEXT)},
        settings: DataTypes.HSTORE,
        document: {type: DataTypes.HSTORE, defaultValue: '"default"=>"value"'}
      })
      this.User.sync({ force: true }).success(function() {
        done()
      })
    })

    afterEach(function(done) {
      this.sequelize.options.quoteIdentifiers = true
      done()
    })

    it('should be able to search within an array', function(done) {
      this.User.all({where: {email: ['hello', 'world']}}).on('sql', function(sql) {
        expect(sql).to.equal('SELECT * FROM "Users" AS "User" WHERE "User"."email" && ARRAY[\'hello\',\'world\']::TEXT[];')
        done()
      })
    })

    it('should be able to find a record while searching in an array', function(done) {
      var self = this
      this.User.bulkCreate([
        {username: 'bob', email: ['myemail@email.com']},
        {username: 'tony', email: ['wrongemail@email.com']}
      ]).success(function() {
        self.User.all({where: {email: ['myemail@email.com']}}).success(function(user) {
          expect(user).to.be.instanceof(Array)
          expect(user).to.have.length(1)
          expect(user[0].username).to.equal('bob')
          done()
        })
      })
    })

    describe('hstore', function() {
      it('should tell me that a column is hstore and not USER-DEFINED', function(done) {
        this.sequelize.queryInterface.describeTable('Users').success(function(table) {
          expect(table.settings.type).to.equal('HSTORE')
          expect(table.document.type).to.equal('HSTORE')
          done()
        })
      })

      it('should stringify hstore with insert', function(done) {
        this.User.create({
          username: 'bob',
          email: ['myemail@email.com'],
          settings: {mailing: false, push: 'facebook', frequency: 3}
        }).on('sql', function(sql) {
          var expected = 'INSERT INTO "Users" ("id","username","email","settings","document","createdAt","updatedAt") VALUES (DEFAULT,\'bob\',ARRAY[\'myemail@email.com\']::TEXT[],\'"mailing"=>false,"push"=>"facebook","frequency"=>3\',\'"default"=>"value"\''
          expect(sql.indexOf(expected)).to.equal(0)
          done()
        })
      })
    })

    describe('enums', function() {
      it('should be able to ignore enum types that already exist', function(done) {
        var User = this.sequelize.define('UserEnums', {
          mood: DataTypes.ENUM('happy', 'sad', 'meh')
        })

        User.sync({ force: true }).success(function() {
          User.sync().success(function() {
            done()
          })
        })
      })

      it('should be able to create/drop enums multiple times', function(done) {
        var User = this.sequelize.define('UserEnums', {
          mood: DataTypes.ENUM('happy', 'sad', 'meh')
        })

        User.sync({ force: true }).success(function() {
          User.sync({ force: true }).success(function() {
            done()
          })
        })
      })

      it("should be able to create/drop multiple enums multiple times", function(done) {
        var DummyModel = this.sequelize.define('Dummy-pg', {
          username: DataTypes.STRING,
          theEnumOne: {
            type: DataTypes.ENUM,
            values:[
              'one',
              'two',
              'three',
            ]
          },
          theEnumTwo: {
            type: DataTypes.ENUM,
            values:[
              'four',
              'five',
              'six',
            ],
          }
        })

        DummyModel.sync({ force: true }).done(function(err) {
          expect(err).not.to.be.ok
          // now sync one more time:
          DummyModel.sync({force: true}).done(function(err) {
            expect(err).not.to.be.ok
            // sync without dropping
            DummyModel.sync().done(function(err) {
              expect(err).not.to.be.ok
              done();
            })
          })
        })
      })

      it('should be able to add enum types', function(done) {
        var self = this
          , User = this.sequelize.define('UserEnums', {
          mood: DataTypes.ENUM('happy', 'sad', 'meh')
        })

        var _done = _.after(4, function() {
          done()
        })

        User.sync({ force: true }).success(function() {
          User = self.sequelize.define('UserEnums', {
            mood: DataTypes.ENUM('neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful')
          })

          User.sync().success(function() {
            expect(User.rawAttributes.mood.values).to.deep.equal(['neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful'])
            _done()
          }).on('sql', function(sql) {
            if (sql.indexOf('neutral') > -1) {
              expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'neutral' BEFORE 'happy'")
              _done()
            }
            else if (sql.indexOf('ecstatic') > -1) {
              expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'ecstatic' BEFORE 'meh'")
              _done()
            }
            else if (sql.indexOf('joyful') > -1) {
              expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'joyful' AFTER 'meh'")
              _done()
            }
          })
        })
      })
    })

    describe('integers', function() {
      describe('integer', function() {
        beforeEach(function(done) {
          this.User = this.sequelize.define('User', {
            aNumber: DataTypes.INTEGER
          })

          this.User.sync({ force: true }).success(function() {
            done()
          })
        })

        it('positive', function(done) {
          var User = this.User

          User.create({aNumber: 2147483647}).success(function(user) {
            expect(user.aNumber).to.equal(2147483647)
            User.find({where: {aNumber: 2147483647}}).success(function(_user) {
              expect(_user.aNumber).to.equal(2147483647)
              done()
            })
          })
        })

        it('negative', function(done) {
          var User = this.User

          User.create({aNumber: -2147483647}).success(function(user) {
            expect(user.aNumber).to.equal(-2147483647)
            User.find({where: {aNumber: -2147483647}}).success(function(_user) {
              expect(_user.aNumber).to.equal(-2147483647)
              done()
            })
          })
        })
      })

      describe('bigint', function() {
        beforeEach(function(done) {
          this.User = this.sequelize.define('User', {
            aNumber: DataTypes.BIGINT
          })

          this.User.sync({ force: true }).success(function() {
            done()
          })
        })

        it('positive', function(done) {
          var User = this.User

          User.create({aNumber: '9223372036854775807'}).success(function(user) {
            expect(user.aNumber).to.equal('9223372036854775807')
            User.find({where: {aNumber: '9223372036854775807'}}).success(function(_user) {
              expect(_user.aNumber).to.equal('9223372036854775807')
              done()
            })
          })
        })

        it('negative', function(done) {
          var User = this.User

          User.create({aNumber: '-9223372036854775807'}).success(function(user) {
            expect(user.aNumber).to.equal('-9223372036854775807')
            User.find({where: {aNumber: '-9223372036854775807'}}).success(function(_user) {
              expect(_user.aNumber).to.equal('-9223372036854775807')
              done()
            })
          })
        })
      })
    })

    describe('model', function() {
      it("create handles array correctly", function(done) {
        this.User
          .create({ username: 'user', email: ['foo@bar.com', 'bar@baz.com'] })
          .success(function(oldUser) {
            expect(oldUser.email).to.contain.members(['foo@bar.com', 'bar@baz.com'])
            done()
          })
          .error(function(err) {
            console.log(err)
          })
      })

      it("should save hstore correctly", function(done) {
        var self = this

        this.User
          .create({ username: 'user', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}})
          .success(function(newUser) {
            // Check to see if the default value for an hstore field works
            expect(newUser.document).to.deep.equal({default: 'value'})
            expect(newUser.settings).to.deep.equal({ created: { test: '"value"' }})

            // Check to see if updating an hstore field works
            newUser.updateAttributes({settings: {should: 'update', to: 'this', first: 'place'}}).success(function(oldUser){
              // Postgres always returns keys in alphabetical order (ascending)
              expect(oldUser.settings).to.deep.equal({first: 'place', should: 'update', to: 'this'})
              done()
            })
          })
          .error(console.log)
      })

      it("should read hstore correctly", function(done) {
        var self = this
        var data = { username: 'user', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}}

        this.User
          .create(data)
          .success(function() {
            // Check that the hstore fields are the same when retrieving the user
            self.User.find({ where: { username: 'user' }})
              .success(function(user) {
                expect(user.settings).to.deep.equal(data.settings)

                done()
              })
          })
          .error(console.log)
      })
    })

    describe('[POSTGRES] Unquoted identifiers', function() {
      it("can insert and select", function(done) {
        var self = this
        this.sequelize.options.quoteIdentifiers = false
        this.sequelize.getQueryInterface().QueryGenerator.options.quoteIdentifiers = false

        this.User = this.sequelize.define('Userxs', {
          username: DataTypes.STRING,
          fullName: DataTypes.STRING // Note mixed case
        }, {
          quoteIdentifiers: false
        })

        this.User.sync({ force: true }).success(function() {
          self.User
            .create({ username: 'user', fullName: "John Smith" })
            .success(function(user) {
              // We can insert into a table with non-quoted identifiers
              expect(user.id).to.exist
              expect(user.id).not.to.be.null
              expect(user.username).to.equal('user')
              expect(user.fullName).to.equal('John Smith')

              // We can query by non-quoted identifiers
              self.User.find({
                where: {fullName: "John Smith"}
              })
              .success(function(user2) {
                self.sequelize.options.quoteIndentifiers = true
                self.sequelize.getQueryInterface().QueryGenerator.options.quoteIdentifiers = true
                self.sequelize.options.logging = false
                // We can map values back to non-quoted identifiers
                expect(user2.id).to.equal(user.id)
                expect(user2.username).to.equal('user')
                expect(user2.fullName).to.equal('John Smith')
                done()
              })
            })
        })
      })
    })
  })
}
<commit_msg>Remove unused variable<commit_after>var chai      = require('chai')
  , expect    = chai.expect
  , Support   = require(__dirname + '/../support')
  , dialect   = Support.getTestDialect()
  , DataTypes = require(__dirname + "/../../lib/data-types")
  , _         = require('lodash')

chai.config.includeStack = true

if (dialect.match(/^postgres/)) {
  describe('[POSTGRES Specific] DAO', function() {
    beforeEach(function(done) {
      this.sequelize.options.quoteIdentifiers = true
      this.User = this.sequelize.define('User', {
        username: DataTypes.STRING,
        email: {type: DataTypes.ARRAY(DataTypes.TEXT)},
        settings: DataTypes.HSTORE,
        document: {type: DataTypes.HSTORE, defaultValue: '"default"=>"value"'}
      })
      this.User.sync({ force: true }).success(function() {
        done()
      })
    })

    afterEach(function(done) {
      this.sequelize.options.quoteIdentifiers = true
      done()
    })

    it('should be able to search within an array', function(done) {
      this.User.all({where: {email: ['hello', 'world']}}).on('sql', function(sql) {
        expect(sql).to.equal('SELECT * FROM "Users" AS "User" WHERE "User"."email" && ARRAY[\'hello\',\'world\']::TEXT[];')
        done()
      })
    })

    it('should be able to find a record while searching in an array', function(done) {
      var self = this
      this.User.bulkCreate([
        {username: 'bob', email: ['myemail@email.com']},
        {username: 'tony', email: ['wrongemail@email.com']}
      ]).success(function() {
        self.User.all({where: {email: ['myemail@email.com']}}).success(function(user) {
          expect(user).to.be.instanceof(Array)
          expect(user).to.have.length(1)
          expect(user[0].username).to.equal('bob')
          done()
        })
      })
    })

    describe('hstore', function() {
      it('should tell me that a column is hstore and not USER-DEFINED', function(done) {
        this.sequelize.queryInterface.describeTable('Users').success(function(table) {
          expect(table.settings.type).to.equal('HSTORE')
          expect(table.document.type).to.equal('HSTORE')
          done()
        })
      })

      it('should stringify hstore with insert', function(done) {
        this.User.create({
          username: 'bob',
          email: ['myemail@email.com'],
          settings: {mailing: false, push: 'facebook', frequency: 3}
        }).on('sql', function(sql) {
          var expected = 'INSERT INTO "Users" ("id","username","email","settings","document","createdAt","updatedAt") VALUES (DEFAULT,\'bob\',ARRAY[\'myemail@email.com\']::TEXT[],\'"mailing"=>false,"push"=>"facebook","frequency"=>3\',\'"default"=>"value"\''
          expect(sql.indexOf(expected)).to.equal(0)
          done()
        })
      })
    })

    describe('enums', function() {
      it('should be able to ignore enum types that already exist', function(done) {
        var User = this.sequelize.define('UserEnums', {
          mood: DataTypes.ENUM('happy', 'sad', 'meh')
        })

        User.sync({ force: true }).success(function() {
          User.sync().success(function() {
            done()
          })
        })
      })

      it('should be able to create/drop enums multiple times', function(done) {
        var User = this.sequelize.define('UserEnums', {
          mood: DataTypes.ENUM('happy', 'sad', 'meh')
        })

        User.sync({ force: true }).success(function() {
          User.sync({ force: true }).success(function() {
            done()
          })
        })
      })

      it("should be able to create/drop multiple enums multiple times", function(done) {
        var DummyModel = this.sequelize.define('Dummy-pg', {
          username: DataTypes.STRING,
          theEnumOne: {
            type: DataTypes.ENUM,
            values:[
              'one',
              'two',
              'three',
            ]
          },
          theEnumTwo: {
            type: DataTypes.ENUM,
            values:[
              'four',
              'five',
              'six',
            ],
          }
        })

        DummyModel.sync({ force: true }).done(function(err) {
          expect(err).not.to.be.ok
          // now sync one more time:
          DummyModel.sync({force: true}).done(function(err) {
            expect(err).not.to.be.ok
            // sync without dropping
            DummyModel.sync().done(function(err) {
              expect(err).not.to.be.ok
              done();
            })
          })
        })
      })

      it('should be able to add enum types', function(done) {
        var self = this
          , User = this.sequelize.define('UserEnums', {
          mood: DataTypes.ENUM('happy', 'sad', 'meh')
        })

        var _done = _.after(4, function() {
          done()
        })

        User.sync({ force: true }).success(function() {
          User = self.sequelize.define('UserEnums', {
            mood: DataTypes.ENUM('neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful')
          })

          User.sync().success(function() {
            expect(User.rawAttributes.mood.values).to.deep.equal(['neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful'])
            _done()
          }).on('sql', function(sql) {
            if (sql.indexOf('neutral') > -1) {
              expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'neutral' BEFORE 'happy'")
              _done()
            }
            else if (sql.indexOf('ecstatic') > -1) {
              expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'ecstatic' BEFORE 'meh'")
              _done()
            }
            else if (sql.indexOf('joyful') > -1) {
              expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'joyful' AFTER 'meh'")
              _done()
            }
          })
        })
      })
    })

    describe('integers', function() {
      describe('integer', function() {
        beforeEach(function(done) {
          this.User = this.sequelize.define('User', {
            aNumber: DataTypes.INTEGER
          })

          this.User.sync({ force: true }).success(function() {
            done()
          })
        })

        it('positive', function(done) {
          var User = this.User

          User.create({aNumber: 2147483647}).success(function(user) {
            expect(user.aNumber).to.equal(2147483647)
            User.find({where: {aNumber: 2147483647}}).success(function(_user) {
              expect(_user.aNumber).to.equal(2147483647)
              done()
            })
          })
        })

        it('negative', function(done) {
          var User = this.User

          User.create({aNumber: -2147483647}).success(function(user) {
            expect(user.aNumber).to.equal(-2147483647)
            User.find({where: {aNumber: -2147483647}}).success(function(_user) {
              expect(_user.aNumber).to.equal(-2147483647)
              done()
            })
          })
        })
      })

      describe('bigint', function() {
        beforeEach(function(done) {
          this.User = this.sequelize.define('User', {
            aNumber: DataTypes.BIGINT
          })

          this.User.sync({ force: true }).success(function() {
            done()
          })
        })

        it('positive', function(done) {
          var User = this.User

          User.create({aNumber: '9223372036854775807'}).success(function(user) {
            expect(user.aNumber).to.equal('9223372036854775807')
            User.find({where: {aNumber: '9223372036854775807'}}).success(function(_user) {
              expect(_user.aNumber).to.equal('9223372036854775807')
              done()
            })
          })
        })

        it('negative', function(done) {
          var User = this.User

          User.create({aNumber: '-9223372036854775807'}).success(function(user) {
            expect(user.aNumber).to.equal('-9223372036854775807')
            User.find({where: {aNumber: '-9223372036854775807'}}).success(function(_user) {
              expect(_user.aNumber).to.equal('-9223372036854775807')
              done()
            })
          })
        })
      })
    })

    describe('model', function() {
      it("create handles array correctly", function(done) {
        this.User
          .create({ username: 'user', email: ['foo@bar.com', 'bar@baz.com'] })
          .success(function(oldUser) {
            expect(oldUser.email).to.contain.members(['foo@bar.com', 'bar@baz.com'])
            done()
          })
          .error(function(err) {
            console.log(err)
          })
      })

      it("should save hstore correctly", function(done) {
        this.User
          .create({ username: 'user', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}})
          .success(function(newUser) {
            // Check to see if the default value for an hstore field works
            expect(newUser.document).to.deep.equal({default: 'value'})
            expect(newUser.settings).to.deep.equal({ created: { test: '"value"' }})

            // Check to see if updating an hstore field works
            newUser.updateAttributes({settings: {should: 'update', to: 'this', first: 'place'}}).success(function(oldUser){
              // Postgres always returns keys in alphabetical order (ascending)
              expect(oldUser.settings).to.deep.equal({first: 'place', should: 'update', to: 'this'})
              done()
            })
          })
          .error(console.log)
      })

      it("should read hstore correctly", function(done) {
        var self = this
        var data = { username: 'user', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}}

        this.User
          .create(data)
          .success(function() {
            // Check that the hstore fields are the same when retrieving the user
            self.User.find({ where: { username: 'user' }})
              .success(function(user) {
                expect(user.settings).to.deep.equal(data.settings)

                done()
              })
          })
          .error(console.log)
      })
    })

    describe('[POSTGRES] Unquoted identifiers', function() {
      it("can insert and select", function(done) {
        var self = this
        this.sequelize.options.quoteIdentifiers = false
        this.sequelize.getQueryInterface().QueryGenerator.options.quoteIdentifiers = false

        this.User = this.sequelize.define('Userxs', {
          username: DataTypes.STRING,
          fullName: DataTypes.STRING // Note mixed case
        }, {
          quoteIdentifiers: false
        })

        this.User.sync({ force: true }).success(function() {
          self.User
            .create({ username: 'user', fullName: "John Smith" })
            .success(function(user) {
              // We can insert into a table with non-quoted identifiers
              expect(user.id).to.exist
              expect(user.id).not.to.be.null
              expect(user.username).to.equal('user')
              expect(user.fullName).to.equal('John Smith')

              // We can query by non-quoted identifiers
              self.User.find({
                where: {fullName: "John Smith"}
              })
              .success(function(user2) {
                self.sequelize.options.quoteIndentifiers = true
                self.sequelize.getQueryInterface().QueryGenerator.options.quoteIdentifiers = true
                self.sequelize.options.logging = false
                // We can map values back to non-quoted identifiers
                expect(user2.id).to.equal(user.id)
                expect(user2.username).to.equal('user')
                expect(user2.fullName).to.equal('John Smith')
                done()
              })
            })
        })
      })
    })
  })
}
<|endoftext|>


<commit_before>var BUDGET = 'budget-';
var LS_KEY_PRODUCT_LIST = 'products';

// setup
function setupStorage(){
    // localStorage.clear();

    // init products
    if(localStorage.getItem(LS_KEY_PRODUCT_LIST)){
        console.log('existing setup');
    }
    else{
        console.log('setting up products...');

        var arrProducts = new Array(1);
        var index = -1;

        index++;
        var objProduct = new Object();
        objProduct.id = index;
        objProduct.name = 'Haha';
        objProduct.price = 10;
        objProduct.remarks = 'test product ' + index;
        arrProducts[index] = objProduct;

        index++;
        objProduct = new Object();
        objProduct.id = index;
        objProduct.name = 'Haha';
        objProduct.price = 10;
        objProduct.remarks = 'test product ' + index;
        arrProducts[index] = objProduct;

        console.log('clearing localstorage...');
        localStorage.clear();

        console.log('loading data into localstorage...');
        console.log('storing: ' + JSON.stringify(arrProducts));
        localStorage.setItem(LS_KEY_PRODUCT_LIST, JSON.stringify(arrProducts));
    }
}

function storage_getProducts(){
    return JSON.parse(localStorage.getItem(LS_KEY_PRODUCT_LIST));
}

function storage_addProduct(sName, sPrice, sRemarks){
    var objProduct = new Object();
    var nPrice = parseFloat(sPrice);

    // generate index (length + 1)
    var arrProducts = storage_getProducts();
    objProduct.id = arrProducts.length;
    objProduct.name = sName;
    objProduct.price = nPrice;
    objProduct.remarks = sRemarks;

    arrProducts[objProduct.id] = objProduct;
    localStorage.setItem(LS_KEY_PRODUCT_LIST, JSON.stringify(arrProducts));
}

function storage_removeAllProducts(){
    var arrProducts = storage_getProducts();
    arrProducts.splice(0, arrProducts.length);

    console.log('after cleaing... ' + JSON.stringify(arrProducts));
    localStorage.setItem(LS_KEY_PRODUCT_LIST, JSON.stringify(arrProducts));
}

function storage_RefreshList_UL(element_id){
    console.log('element_id: ' + element_id);
    $('#' + element_id).empty();

    var arrProducts = storage_getProducts();
    console.log('storage_RefreshList_UL() ' + arrProducts.length);
    if(arrProducts.length > 0){
        var sItemList = "
";
        for(var i = 0; i < arrProducts.length; i++){
            sItemList = sItemList + '
' + arrProducts[i].name + '
';
        }
        sItemList = sItemList + '
';
        console.log('sItemList: ' + sItemList);

        console.log('div-html-before: ' + $('#' + element_id).html());
        $('#' + element_id).html(sItemList);
        $('#' + element_id).page();
        console.log('div-html-after: ' + $('#' + element_id).html());
    }
    else{
        $('#' + element_id).html('
(no item)
');
    }
}

// Budget
function storage_budget_saveBudget(sYYYYMM, sAmount){
    var boolStatus = false;
    try{
        var nAmount = parseFloat(sAmount);
        localStorage.setItem(BUDGET + sYYYYMM, nAmount);
        boolStatus = true;
    }
    catch(err){
        console.error('storage_budget_saveBudget() - ' + err.description);
        e_alert('Error: ' + err.description);
    }

    return boolStatus;
}

function storage_budget_retrieveBudget(sYYYYMM){
    return parseFloat(localStorage.getItem(BUDGET + sYYYYMM));
}

<commit_msg>Update storage.api.js<commit_after>var BUDGET = 'budget-';
var LS_KEY_PRODUCT_LIST = 'products';

// setup
function setupStorage(){
    // localStorage.clear();

    // init products
    if(localStorage.getItem(LS_KEY_PRODUCT_LIST)){
        console.log('existing setup');
    }
    else{
        console.log('setting up products...');

        var arrProducts = new Array(1);
        var index = -1;

        index++;
        var objProduct = new Object();
        objProduct.id = index;
        objProduct.name = 'Haha';
        objProduct.price = 10;
        objProduct.remarks = 'test product ' + index;
        arrProducts[index] = objProduct;

        index++;
        objProduct = new Object();
        objProduct.id = index;
        objProduct.name = 'Haha';
        objProduct.price = 10;
        objProduct.remarks = 'test product ' + index;
        arrProducts[index] = objProduct;

        console.log('clearing localstorage...');
        localStorage.clear();

        console.log('loading data into localstorage...');
        console.log('storing: ' + JSON.stringify(arrProducts));
        localStorage.setItem(LS_KEY_PRODUCT_LIST, JSON.stringify(arrProducts));
    }
}

function storage_getProducts(){
    return JSON.parse(localStorage.getItem(LS_KEY_PRODUCT_LIST));
}

function storage_addProduct(sName, sPrice, sRemarks){
    var objProduct = new Object();
    var nPrice = parseFloat(sPrice);

    // generate index (length + 1)
    var arrProducts = storage_getProducts();
    objProduct.id = arrProducts.length;
    objProduct.name = sName;
    objProduct.price = nPrice;
    objProduct.remarks = sRemarks;

    arrProducts[objProduct.id] = objProduct;
    localStorage.setItem(LS_KEY_PRODUCT_LIST, JSON.stringify(arrProducts));
}

function storage_removeAllProducts(){
    var arrProducts = storage_getProducts();
    arrProducts.splice(0, arrProducts.length);

    console.log('after cleaing... ' + JSON.stringify(arrProducts));
    localStorage.setItem(LS_KEY_PRODUCT_LIST, JSON.stringify(arrProducts));
}

function storage_RefreshList_UL(element_id){
    console.log('element_id: ' + element_id);
    $('#' + element_id).empty();

    var arrProducts = storage_getProducts();
    console.log('storage_RefreshList_UL() ' + arrProducts.length);
    if(arrProducts.length > 0){
        var sItemList = "
";
        for(var i = 0; i < arrProducts.length; i++){
            sItemList = sItemList + '
' + arrProducts[i].name + '
';
        }
        sItemList = sItemList + '
';
        console.log('sItemList: ' + sItemList);

        console.log('div-html-before: ' + $('#' + element_id).html());
        // $('#' + element_id).html(sItemList);
        // $('#' + element_id).page();
        $('#' + element_id).append(sItemList);
        $('#ul_item_list').listview('refresh');

        console.log('div-html-after: ' + $('#' + element_id).html());
    }
    else{
        $('#' + element_id).html('
(no item)
');
    }
}

// Budget
function storage_budget_saveBudget(sYYYYMM, sAmount){
    var boolStatus = false;
    try{
        var nAmount = parseFloat(sAmount);
        localStorage.setItem(BUDGET + sYYYYMM, nAmount);
        boolStatus = true;
    }
    catch(err){
        console.error('storage_budget_saveBudget() - ' + err.description);
        e_alert('Error: ' + err.description);
    }

    return boolStatus;
}

function storage_budget_retrieveBudget(sYYYYMM){
    return parseFloat(localStorage.getItem(BUDGET + sYYYYMM));
}

<|endoftext|>


<commit_before>angular.module(PKG.name + '.services')
  .factory('myFileUploader', function($q, $window, $alert, cfpLoadingBar, myAuth) {
    function upload(fileObj){
      var deferred = $q.defer();
      if (!myAuth.currentUser) {
        deferred.reject(400);
        $alert({
          title: 'Must specify user: ',
          content: 'Could not find user.',
          type: 'danger'
        });
      } else {
        var xhr = new $window.XMLHttpRequest();
        xhr.upload.addEventListener('progress', function (e) {
          if (e.type === 'progress') {
            console.info('App Upload in progress!');
          }
        });
        var path = fileObj.path;
        xhr.open('POST', path, true);
        xhr.setRequestHeader('Content-type', 'application/octet-stream');
        xhr.setRequestHeader('X-Archive-Name', fileObj.file.name);
        xhr.setRequestHeader('X-ApiKey', '');
        xhr.setRequestHeader('Authorization', 'Bearer ' + myAuth.currentUser.token);
        xhr.send(fileObj.file);
        cfpLoadingBar.start();
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status > 399){
              deferred.reject(xhr.response);
            } else {
              deferred.resolve();
            }
            cfpLoadingBar.complete();
          }
        };
      }
      return deferred.promise;
    }
    return {
      upload: upload
    };
  });
<commit_msg>removing apikey<commit_after>angular.module(PKG.name + '.services')
  .factory('myFileUploader', function($q, $window, $alert, cfpLoadingBar, myAuth) {
    function upload(fileObj){
      var deferred = $q.defer();
      if (!myAuth.currentUser) {
        deferred.reject(400);
        $alert({
          title: 'Must specify user: ',
          content: 'Could not find user.',
          type: 'danger'
        });
      } else {
        var xhr = new $window.XMLHttpRequest();
        xhr.upload.addEventListener('progress', function (e) {
          if (e.type === 'progress') {
            console.info('App Upload in progress!');
          }
        });
        var path = fileObj.path;
        xhr.open('POST', path, true);
        xhr.setRequestHeader('Content-type', 'application/octet-stream');
        xhr.setRequestHeader('X-Archive-Name', fileObj.file.name);
        xhr.setRequestHeader('Authorization', 'Bearer ' + myAuth.currentUser.token);
        xhr.send(fileObj.file);
        cfpLoadingBar.start();
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status > 399){
              deferred.reject(xhr.response);
            } else {
              deferred.resolve();
            }
            cfpLoadingBar.complete();
          }
        };
      }
      return deferred.promise;
    }
    return {
      upload: upload
    };
  });
<|endoftext|>


<commit_before>var path = require('path'),
  util = require('util');
require('colors');
// @see http://nodejs.org/api/all.html#all_require_extensions

// first value of `extensions` property should be an extension the require registers
// aliases & extensions can also be used when calling require('better-require')(formats)
var supportedFormats = {
  'json': {
    require: 'require-json'
  }
  , 'yaml': {
    require: 'require-yaml'
    , extensions: ['yaml', 'yml']
  }
  , 'csv': {
    require: 'require-csv'
  }
  , 'xml': {
    require: 'require-xml'
  }
  , 'ini': {
    require: 'require-ini'
  }
  , 'coffeescript': {
    require: 'coffee-script'
    , extensions: ['coffee']
    , aliases: ['coffee-script']
  }
  , 'livescript': {
    require: 'LiveScript'
    , extensions: ['ls']
    }
  , 'six': {
    require: 'six'
  }
  , 'clojurescript': {
    require: 'clojure-script'
    , aliases: 'clojure-script'
    , extensions: 'cljs'
    , bundled: false
    , url: 'https://github.com/michaelsbradleyjr/node-clojurescript'
  }
  , 'dart': {
    require: 'Frog'
    , extensions: 'dart'
    , bundled: false
    , install: 'You will also need to install the Dart SDK http://www.dartlang.org/docs/getting-started/sdk/#download.'
    , url: 'https://github.com/kaisellgren/Frog/'
  }
  , 'typescript': {
    require: 'require-typescript'
    , extensions: ['ts']
  }
};

module.exports = function (formats) {
  formats = formats || Object.keys(supportedFormats);

  if (!(formats instanceof Array)) {
    formats = formats.split(/ +/);
  }

  // # Format supportedFormats
  for (var key in supportedFormats) {
    console.log('key in ?: line68: ', key);
    var supportedFormat = supportedFormats[key];
    supportedFormat.name = supportedFormat.name || key;
    // ## Populate .extensions
    supportedFormat.extensions = supportedFormat.extensions || [];
    // string -> [string]
    if (typeof supportedFormat.extensions === 'string')
      supportedFormat.extensions = [supportedFormat.extensions];
    // add key to extensions
    if (supportedFormat.extensions.indexOf(key) === -1)
      supportedFormat.extensions.push(key);
    // ## Populate .aliases
    supportedFormat.aliases = supportedFormat.aliases || [];
    // string -> [string]
    if (typeof supportedFormat.aliases === 'string')
      supportedFormat.aliases = [supportedFormat.aliases];
    // add extensions to aliases
    supportedFormat.aliases = supportedFormat.aliases.concat(supportedFormat.extensions);
    // ## Populate install
    var install = supportedFormat.install || '';

    supportedFormat.install = function (filename) {
      var filename = path.basename(filename);
      return supportedFormat.name
      + ' depends on a heavy package and better-require does not install it by default. '
      + 'You need to install it by yourself before you can require ' + filename.grey + ':'
      + '\n\n'
      + ('npm install ' + supportedFormat.require  + '').blue
      + '\n\n'
      + (install ? install + ' ' : '')
      + (supportedFormat.url ? 'More install information at ' + supportedFormat.url : '')
      + '\n\n';
    }
  }

  for (var key in supportedFormats) {
    var supportedFormat = supportedFormats[key];
    formats.forEach(function (format) {
      if (supportedFormat.aliases.indexOf(format) !== -1) {
        requireFormat(supportedFormat);
      }
    });
  };
}

function requireFormat (format) {
  try {
    require(format.require);
  }
  catch (e) {
    format.extensions.forEach(function (extension) {
      require.extensions['.' + extension] = function(module, filename) {
        var err = new Error(format.install(filename));
        throw err;
      };
    });
  }
}
<commit_msg>updated to include 'LiveScript'<commit_after>var path = require('path'),
  util = require('util');
require('colors');
// @see http://nodejs.org/api/all.html#all_require_extensions

// first value of `extensions` property should be an extension the require registers
// aliases & extensions can also be used when calling require('better-require')(formats)
var supportedFormats = {
  'json': {
    require: 'require-json'
  }
  , 'yaml': {
    require: 'require-yaml'
    , extensions: ['yaml', 'yml']
  }
  , 'csv': {
    require: 'require-csv'
  }
  , 'xml': {
    require: 'require-xml'
  }
  , 'ini': {
    require: 'require-ini'
  }
  , 'coffeescript': {
    require: 'coffee-script'
    , extensions: ['coffee']
    , aliases: ['coffee-script']
  }
  , 'livescript': {
    require: 'LiveScript'
    , extensions: ['ls']
    , aliases: ['LiveScript']
    }
  , 'six': {
    require: 'six'
  }
  , 'clojurescript': {
    require: 'clojure-script'
    , aliases: 'clojure-script'
    , extensions: 'cljs'
    , bundled: false
    , url: 'https://github.com/michaelsbradleyjr/node-clojurescript'
  }
  , 'dart': {
    require: 'Frog'
    , extensions: 'dart'
    , bundled: false
    , install: 'You will also need to install the Dart SDK http://www.dartlang.org/docs/getting-started/sdk/#download.'
    , url: 'https://github.com/kaisellgren/Frog/'
  }
  , 'typescript': {
    require: 'require-typescript'
    , extensions: ['ts']
  }
};

module.exports = function (formats) {
  formats = formats || Object.keys(supportedFormats);

  if (!(formats instanceof Array)) {
    formats = formats.split(/ +/);
  }

  // # Format supportedFormats
  for (var key in supportedFormats) {
    var supportedFormat = supportedFormats[key];
    supportedFormat.name = supportedFormat.name || key;
    // ## Populate .extensions
    supportedFormat.extensions = supportedFormat.extensions || [];
    // string -> [string]
    if (typeof supportedFormat.extensions === 'string')
      supportedFormat.extensions = [supportedFormat.extensions];
    // add key to extensions
    if (supportedFormat.extensions.indexOf(key) === -1)
      supportedFormat.extensions.push(key);
    // ## Populate .aliases
    supportedFormat.aliases = supportedFormat.aliases || [];
    // string -> [string]
    if (typeof supportedFormat.aliases === 'string')
      supportedFormat.aliases = [supportedFormat.aliases];
    // add extensions to aliases
    supportedFormat.aliases = supportedFormat.aliases.concat(supportedFormat.extensions);
    // ## Populate install
    var install = supportedFormat.install || '';

    supportedFormat.install = function (filename) {
      var filename = path.basename(filename);
      return supportedFormat.name
      + ' depends on a heavy package and better-require does not install it by default. '
      + 'You need to install it by yourself before you can require ' + filename.grey + ':'
      + '\n\n'
      + ('npm install ' + supportedFormat.require  + '').blue
      + '\n\n'
      + (install ? install + ' ' : '')
      + (supportedFormat.url ? 'More install information at ' + supportedFormat.url : '')
      + '\n\n';
    }
  }

  for (var key in supportedFormats) {
    var supportedFormat = supportedFormats[key];
    formats.forEach(function (format) {
      if (supportedFormat.aliases.indexOf(format) !== -1) {
        requireFormat(supportedFormat);
      }
    });
  };
}

function requireFormat (format) {
  try {
    require(format.require);
  }
  catch (e) {
    format.extensions.forEach(function (extension) {
      require.extensions['.' + extension] = function(module, filename) {
        var err = new Error(format.install(filename));
        throw err;
      };
    });
  }
}
<|endoftext|>


<commit_before>/* Copyright (c) 2018 e-soa Jacques Desodt, MIT License */
'use strict'

/* Default plugin options */
const role = 'entity-crud-test'

/* Prerequisites */
const Seneca = require('seneca') // eslint-disable-line no-unused-vars
const testFunctions = require('./functions')

/* Test prerequisites */
const Code = require('code')
const Lab = require('lab', {timeout: testFunctions.timeout})
var lab = (exports.lab = Lab.script())
var describe = lab.describe
var it = lab.it
var expect = Code.expect

describe('query + appends', function () {
  it('no select in the query, one append', function (fin) {
    /* Initializes */
    var authorRole = 'author'
    var appends = [
      {
        action: {role: authorRole, cmd: 'query'},
        resultname: 'append_author',
        select: {idname: 'author', valuename: 'author'}
      }
    ]
    /* Gets the Seneca instance */
    var seneca = testFunctions.setSeneca(Seneca, role, fin) // Add 'print' for debug
    /* Creates the posts */
    testFunctions.createPosts(seneca, role, function (createPostsResults) {
      /* Creates the authors */
      testFunctions.createAuthors(seneca, authorRole, function (createAuthorsResults) {
        /* Fires the test */
        seneca.act({role: role, cmd: 'query', appends: appends}, function (ignore, result) {
          /* Checks the result */
          expect(result.success).to.equal(true)
          expect(result.list.length).to.equal(testFunctions.getPosts().length)
          expect(result.count).to.equal(testFunctions.getPosts().length)
          result.list.forEach(function (item) {
            if (item.author) {
              expect(item.append_author.list[0].author).to.equal(item.author)
            } else {
              expect(item.append_author).to.not.exist()
            }
          })
          fin()
        })
      })
    })
  })
  it('select in the query and append', function (fin) {
    /* Initializes */
    var authorRole = 'author'
    var appends = [
      {
        action: {role: authorRole, cmd: 'query'},
        resultname: 'append_author',
        select: {idname: 'author', valuename: 'author'}
      }
    ]
    var select = { title: 'Tuesday'}
    /* Gets the Seneca instance */
    var seneca = testFunctions.setSeneca(Seneca, role, fin) // Add 'print' for debug
    /* Creates the posts */
    testFunctions.createPosts(seneca, role, function (createPostsResults) {
      /* Creates the authors */
      testFunctions.createAuthors(seneca, authorRole, function (createAuthorsResults) {
        /* Fires the test */
        seneca.act({role: role, cmd: 'query', select: select, appends: appends}, function (ignore, result) {
          /* Checks the result */
          expect(result.success).to.equal(true)
          expect(result.list.length).to.equal(2)
          expect(result.count).to.equal(2)
          result.list.forEach(function (item) {
            if (item.author) {
              expect(item.append_author.list[0].author).to.equal(item.author)
            } else {
              expect(item.append_author).to.not.exist()
            }
          })
          fin()
        })
      })
    })
  })
  it('select in the query and append with no result', function (fin) {
    /* Initializes */
    var authorRole = 'author'
    var appends = [
      {
        action: {role: authorRole, cmd: 'query'},
        resultname: 'append_author',
        select: {idname: 'author', valuename: 'author'}
      }
    ]
    var select = { title: 'Monday'}
    /* Gets the Seneca instance */
    var seneca = testFunctions.setSeneca(Seneca, role, fin) // Add 'print' for debug
    /* Creates the posts */
    testFunctions.createPosts(seneca, role, function (createPostsResults) {
      /* Creates the authors */
      testFunctions.createAuthors(seneca, authorRole, function (createAuthorsResults) {
        /* Fires the test */
        seneca.act({role: role, cmd: 'query', select: select, appends: appends}, function (ignore, result) {
          /* Checks the result */
          expect(result.success).to.equal(true)
          expect(result.list.length).to.equal(1)
          expect(result.count).to.equal(1)
          result.list.forEach(function (item) {
            if (item.author) {
              expect(item.append_author.list[0].author).to.equal(item.author)
            } else {
              expect(item.append_author).to.not.exist()
            }
          })
          fin()
        })
      })
    })
  })
})
<commit_msg>This project has been moved to GitLab<commit_after><|endoftext|>


<commit_before>
drawStackedChart(10);

$(document).on('click', '.dropdown-menu li a', function () {
    $(document.get)
    updateStackedChart(parseFloat($(this).text()), 1955, 1965);
});

$(function(){
    $("#top_num li a").click(function(){
      $(".btn:first-child").text("# of top words: " + $(this).text());
      $(".btn:first-child").val($(this).text());
   });
});

var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 860 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var tooltip = d3.select("div#chart")
    .append("div")
    .attr("class", "remove")
    .style("position", "absolute")
    .style("z-index", "20")
    .style("visibility", "hidden")
    .style("top", "30px")
    .style("left", "225px");

var datearray = [];

var x = d3.scale.linear()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

var color = d3.scale.category20();

var xAxis = d3.svg.axis()
    .scale(x)
    .tickFormat(d3.format('d'))
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var stack = d3.layout.stack()
  .offset('zero')
  .values(function(d){ return d.values; })
  .x(function(d){ return d.yearCol; })
  .y(function(d){ return d.countCol; });

var area = d3.svg.area()
    .interpolate('basis')
    .x(function(d) { return x(d.yearCol); })
    .y0(function(d) { return y(d.y0); })
    .y1(function(d) { return y(d.y0 + d.y); });

var svg = d3.select("div#chart").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

function drawStackedChart(word_num){

  d3.csv('Words_allyears_26oct.csv', function(error, data){

    data.forEach(function(d){
      d.countCol = +d.countCol;
      d.yearCol = +d.yearCol;
    });

    var summed_data = d3.nest()
                        .key(function(d){ return d.wordCol; })
                        .rollup(function(leaves){
                            return {"total": d3.sum(
                              leaves, function(d){ return d.countCol; })}})
                        .entries(data);
    summed_data.sort(function(a,b){ return b.values.total - a.values.total; });

    var list = [];
    for (i=0; i<word_num; i++){
      list.push(summed_data[i].key);
    }

    var data = $.map(data, function(element){
      return ($.inArray(element.wordCol,list)>-1?element:null)
    });

    complete(data, list, data);

    data.sort(function(a,b){ return a.yearCol - b.yearCol; });

    var nest = d3.nest()
      .key(function(d){ return d.wordCol; })
      .entries(data);

    var layers = stack(nest);

    x.domain(d3.extent(data, function(d){ return d.yearCol; }));
    y.domain([0, d3.max(data, function(d){ return d.y0 + d.y; })]);

    var chartLayers = svg.selectAll(".layer")
        .data(layers);

    chartLayers
      .enter().append("path")
        .attr("class", "layer")
        .attr("d", function(d) { return area(d.values); })
        .style("fill", function(d, i) { return color(i); });

    chartLayers
        .transition()
        .duration(550)
        .attr("class", "layer")
        .attr("d", function(d) { return area(d.values); })
        .style("fill", function(d, i) { return color(i); });

    chartLayers
        .exit()
        .transition()
        .duration(550)
        .remove();

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);

    svg.selectAll(".layer")
      .attr("opacity", 1)
      .on("mouseover", function(d, i) {
        svg.selectAll(".layer").transition()
        .duration(550)
        .attr("opacity", function(d, j) {
          return j != i ? 1 : 1;
      })})
      .on("mousemove", function(d, i) {
        mousex = d3.mouse(this);
        mousex = mousex[0];
        var invertedx = x.invert(mousex);
        //invertedx = invertedx.getMonth() + invertedx.getDate();
        var selected = (d.values);
        for (var k = 0; k < selected.length; k++) {
          datearray[k] = selected[k].yearCol;
        }

        mousedate = datearray.indexOf(Math.round(invertedx));
        pro = d.values[mousedate].countCol;
        tip_year = d.values[mousedate].yearCol;

        d3.select(this)
        .classed("hover", true)
        .attr("stroke", color[0])
        .attr("stroke-width", "0.5px"),
        tooltip.html( "
" + d.key + " | " + tip_year + ": " + pro + "
" ).style("visibility", "visible");

      })
      .on("mouseout", function(d, i) {
       svg.selectAll(".layer")
        .transition()
        .duration(250)
        .attr("opacity", "1");
        d3.select(this)
        .classed("hover", false)
        .attr("stroke-width", "0px"), tooltip.html( "
" + d.key + "
" + pro + "
" ).style("visibility", "hidden");
    });

  });
}

function updateStackedChart(word_num, start, end){
  d3.csv('Words_allyears_26oct.csv', function(error, data){

    data.forEach(function(d){
      d.countCol = +d.countCol;
      d.yearCol = +d.yearCol;
    });

    var summed_data = d3.nest()
                        .key(function(d){ return d.wordCol; })
                        .rollup(function(leaves){
                            return {"total": d3.sum(
                              leaves, function(d){ return d.countCol; })}})
                        .entries(data);
    summed_data.sort(function(a,b){ return b.values.total - a.values.total; });

    var list = [];
    for (i=0; i<word_num; i++){
      list.push(summed_data[i].key);
    }

    var data = $.map(data, function(element){
      return ($.inArray(element.wordCol,list)>-1?element:null)
    });

    complete(data, list, data);

    var year_list = [];
    for (i=start; i<end+1; i++){
      year_list.push(i);
    };

    data = $.map(data, function(element){
      return ($.inArray(element.yearCol, year_list) > -1 ? element:null)
    });

    data.sort(function(a,b){ return a.yearCol - b.yearCol; });

    var nest = d3.nest()
      .key(function(d){ return d.wordCol; })
      .entries(data);

    var layers = stack(nest);

    x.domain(d3.extent(data, function(d){ return d.yearCol; }));
    y.domain([0, d3.max(data, function(d){ return d.y0 + d.y; })]);

    var chartLayers = svg.selectAll(".layer")
        .data(layers);

    chartLayers
      .enter().append("path")
        .attr("class", "layer")
        .attr("d", function(d) { return area(d.values); })
        .style("fill", function(d, i) { return color(i); });

    chartLayers
        .transition()
        .duration(550)
        .attr("class", "layer")
        .attr("d", function(d) { return area(d.values); })
        .style("fill", function(d, i) { return color(i); });

    chartLayers
        .exit()
        .transition()
        .duration(550)
        .remove();

    svg.selectAll('.x.axis')
        .transition()
        .duration(550)
        .call(xAxis);

    svg.selectAll('.y.axis')
        .transition()
        .duration(550)
        .call(yAxis);

    svg.selectAll(".layer")
      .attr("opacity", 1)
      /*
      .on("mouseover", function(d, i) {
        svg.selectAll(".layer").transition()
        .duration(250)
        .attr("opacity", function(d, j) {
          return j != i ? 0.6 : 1;
      })})
      */
      .on("mousemove", function(d, i) {
        mousex = d3.mouse(this);
        mousex = mousex[0];
        var invertedx = x.invert(mousex);
        //invertedx = invertedx.getMonth() + invertedx.getDate();
        var selected = (d.values);
        for (var k = 0; k < selected.length; k++) {
          datearray[k] = selected[k].yearCol;
        }

        mousedate = datearray.indexOf(Math.round(invertedx));
        pro = d.values[mousedate].countCol;
        tip_year = d.values[mousedate].yearCol;

        d3.select(this)
        .classed("hover", true)
        .attr("stroke", color[0])
        .attr("stroke-width", "0.5px"),
        tooltip.html( "
" + d.key + " | " + tip_year + ": " + pro + "
" ).style("visibility", "visible");

      })
      .on("mouseout", function(d, i) {
       svg.selectAll(".layer")
        .transition()
        .duration(550)
        .attr("opacity", "1");
        d3.select(this)
        .classed("hover", false)
        .attr("stroke-width", "0px"), tooltip.html( "
" + d.key + "
" + pro + "
" ).style("visibility", "hidden");
    });
  });
}

function complete(x, key, data){
  for (i=0; i<key.length; i++){
    tempdata = x.filter(function(d){ return d.wordCol == key[i]; });
    yearsPresent = []
    years = [];

    for (year=1955; year<2010; year++){
      years.push(year)
      for (row=0; row<tempdata.length; row++){
        if (tempdata[row].yearCol === year){
          yearsPresent.push(year);
        }
      }
    }

    for (year=0; year<years.length; year++){
      if (yearsPresent.indexOf(years[year]) < 0){
        dict = {}
        dict['countCol'] = 0;
        dict['wordCol'] = tempdata[0].wordCol;
        dict['yearCol'] = years[year];
        data.push(dict);
      }
    }
  }

};
  <commit_msg>update data<commit_after>
drawStackedChart(10);

$(document).on('click', '#top_num li a', function () {
    $(document.get)
    updateStackedChart(parseFloat($(this).text()), 1955, 1965);
});

$(function(){
    $("#top_num li a").click(function(){
      $(".btn:first-child").text("# of top words: " + $(this).text());
      $(".btn:first-child").val($(this).text());
   });
});

var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 860 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var tooltip = d3.select("div#chart")
    .append("div")
    .attr("class", "remove")
    .style("position", "absolute")
    .style("z-index", "20")
    .style("visibility", "hidden")
    .style("top", "30px")
    .style("left", "225px");

var datearray = [];

var x = d3.scale.linear()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

var color = d3.scale.category20();

var xAxis = d3.svg.axis()
    .scale(x)
    .tickFormat(d3.format('d'))
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var stack = d3.layout.stack()
  .offset('zero')
  .values(function(d){ return d.values; })
  .x(function(d){ return d.yearCol; })
  .y(function(d){ return d.countCol; });

var area = d3.svg.area()
    .interpolate('basis')
    .x(function(d) { return x(d.yearCol); })
    .y0(function(d) { return y(d.y0); })
    .y1(function(d) { return y(d.y0 + d.y); });

var svg = d3.select("div#chart").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

function drawStackedChart(word_num){

  d3.csv('Words_allyears_26oct.csv', function(error, data){

    data.forEach(function(d){
      d.countCol = +d.countCol;
      d.yearCol = +d.yearCol;
    });

    var summed_data = d3.nest()
                        .key(function(d){ return d.wordCol; })
                        .rollup(function(leaves){
                            return {"total": d3.sum(
                              leaves, function(d){ return d.countCol; })}})
                        .entries(data);
    summed_data.sort(function(a,b){ return b.values.total - a.values.total; });

    var list = [];
    for (i=0; i<word_num; i++){
      list.push(summed_data[i].key);
    }

    var data = $.map(data, function(element){
      return ($.inArray(element.wordCol,list)>-1?element:null)
    });

    complete(data, list, data);

    data.sort(function(a,b){ return a.yearCol - b.yearCol; });

    var nest = d3.nest()
      .key(function(d){ return d.wordCol; })
      .entries(data);

    var layers = stack(nest);

    x.domain(d3.extent(data, function(d){ return d.yearCol; }));
    y.domain([0, d3.max(data, function(d){ return d.y0 + d.y; })]);

    var chartLayers = svg.selectAll(".layer")
        .data(layers);

    chartLayers
      .enter().append("path")
        .attr("class", "layer")
        .attr("d", function(d) { return area(d.values); })
        .style("fill", function(d, i) { return color(i); });

    chartLayers
        .transition()
        .duration(550)
        .attr("class", "layer")
        .attr("d", function(d) { return area(d.values); })
        .style("fill", function(d, i) { return color(i); });

    chartLayers
        .exit()
        .transition()
        .duration(550)
        .remove();

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);

    svg.selectAll(".layer")
      .attr("opacity", 1)
      .on("mouseover", function(d, i) {
        svg.selectAll(".layer").transition()
        .duration(550)
        .attr("opacity", function(d, j) {
          return j != i ? 1 : 1;
      })})
      .on("mousemove", function(d, i) {
        mousex = d3.mouse(this);
        mousex = mousex[0];
        var invertedx = x.invert(mousex);
        //invertedx = invertedx.getMonth() + invertedx.getDate();
        var selected = (d.values);
        for (var k = 0; k < selected.length; k++) {
          datearray[k] = selected[k].yearCol;
        }

        mousedate = datearray.indexOf(Math.round(invertedx));
        pro = d.values[mousedate].countCol;
        tip_year = d.values[mousedate].yearCol;

        d3.select(this)
        .classed("hover", true)
        .attr("stroke", color[0])
        .attr("stroke-width", "0.5px"),
        tooltip.html( "
" + d.key + " | " + tip_year + ": " + pro + "
" ).style("visibility", "visible");

      })
      .on("mouseout", function(d, i) {
       svg.selectAll(".layer")
        .transition()
        .duration(250)
        .attr("opacity", "1");
        d3.select(this)
        .classed("hover", false)
        .attr("stroke-width", "0px"), tooltip.html( "
" + d.key + "
" + pro + "
" ).style("visibility", "hidden");
    });

  });
}

function updateStackedChart(word_num, start, end){
  d3.csv('Words_allyears_26oct.csv', function(error, data){

    data.forEach(function(d){
      d.countCol = +d.countCol;
      d.yearCol = +d.yearCol;
    });

    var summed_data = d3.nest()
                        .key(function(d){ return d.wordCol; })
                        .rollup(function(leaves){
                            return {"total": d3.sum(
                              leaves, function(d){ return d.countCol; })}})
                        .entries(data);
    summed_data.sort(function(a,b){ return b.values.total - a.values.total; });

    var list = [];
    for (i=0; i<word_num; i++){
      list.push(summed_data[i].key);
    }

    var data = $.map(data, function(element){
      return ($.inArray(element.wordCol,list)>-1?element:null)
    });

    complete(data, list, data);

    var year_list = [];
    for (i=start; i<end+1; i++){
      year_list.push(i);
    };

    data = $.map(data, function(element){
      return ($.inArray(element.yearCol, year_list) > -1 ? element:null)
    });

    data.sort(function(a,b){ return a.yearCol - b.yearCol; });

    var nest = d3.nest()
      .key(function(d){ return d.wordCol; })
      .entries(data);

    var layers = stack(nest);

    x.domain(d3.extent(data, function(d){ return d.yearCol; }));
    y.domain([0, d3.max(data, function(d){ return d.y0 + d.y; })]);

    var chartLayers = svg.selectAll(".layer")
        .data(layers);

    chartLayers
      .enter().append("path")
        .attr("class", "layer")
        .attr("d", function(d) { return area(d.values); })
        .style("fill", function(d, i) { return color(i); });

    chartLayers
        .transition()
        .duration(550)
        .attr("class", "layer")
        .attr("d", function(d) { return area(d.values); })
        .style("fill", function(d, i) { return color(i); });

    chartLayers
        .exit()
        .transition()
        .duration(550)
        .remove();

    svg.selectAll('.x.axis')
        .transition()
        .duration(550)
        .call(xAxis);

    svg.selectAll('.y.axis')
        .transition()
        .duration(550)
        .call(yAxis);

    svg.selectAll(".layer")
      .attr("opacity", 1)
      /*
      .on("mouseover", function(d, i) {
        svg.selectAll(".layer").transition()
        .duration(250)
        .attr("opacity", function(d, j) {
          return j != i ? 0.6 : 1;
      })})
      */
      .on("mousemove", function(d, i) {
        mousex = d3.mouse(this);
        mousex = mousex[0];
        var invertedx = x.invert(mousex);
        //invertedx = invertedx.getMonth() + invertedx.getDate();
        var selected = (d.values);
        for (var k = 0; k < selected.length; k++) {
          datearray[k] = selected[k].yearCol;
        }

        mousedate = datearray.indexOf(Math.round(invertedx));
        pro = d.values[mousedate].countCol;
        tip_year = d.values[mousedate].yearCol;

        d3.select(this)
        .classed("hover", true)
        .attr("stroke", color[0])
        .attr("stroke-width", "0.5px"),
        tooltip.html( "
" + d.key + " | " + tip_year + ": " + pro + "
" ).style("visibility", "visible");

      })
      .on("mouseout", function(d, i) {
       svg.selectAll(".layer")
        .transition()
        .duration(550)
        .attr("opacity", "1");
        d3.select(this)
        .classed("hover", false)
        .attr("stroke-width", "0px"), tooltip.html( "
" + d.key + "
" + pro + "
" ).style("visibility", "hidden");
    });
  });
}

function complete(x, key, data){
  for (i=0; i<key.length; i++){
    tempdata = x.filter(function(d){ return d.wordCol == key[i]; });
    yearsPresent = []
    years = [];

    for (year=1955; year<2010; year++){
      years.push(year)
      for (row=0; row<tempdata.length; row++){
        if (tempdata[row].yearCol === year){
          yearsPresent.push(year);
        }
      }
    }

    for (year=0; year<years.length; year++){
      if (yearsPresent.indexOf(years[year]) < 0){
        dict = {}
        dict['countCol'] = 0;
        dict['wordCol'] = tempdata[0].wordCol;
        dict['yearCol'] = years[year];
        data.push(dict);
      }
    }
  }

};
  <|endoftext|>