<commit_before>var fs = require("fs"),
	uuid = require("uuid"),
	request = require("sync-request");

const directory = process.argv[3];

var urls = [],
	snippets = {},
	resources = {},
	files = [];

var logSnippet = function(filename, logContent, content) {
	snippets[filename] = logContent;
	fs.writeFileSync(directory + filename, content);
	fs.writeFileSync(directory + "snippets.json", JSON.stringify(snippets, null, "\t"));
};

module.exports = {
	getUUID: uuid.v4,
	kill: function(message) {
		console.trace(message)
		process.exit(0)
	},
	fetchUrl: function(method, url, headers = {}, body) {
		if (process.argv.indexOf("--download") == -1) {
			console.log(`Faking a ${method} request to ${url}`);
			console.log("Use the flag --download to actually download the file (eg. for encoded payloads).");
			return `(Content of ${url})`;
		}

		console.log(`Emulating a ${method} request to ${url}`);
		headers["User-Agent"] = "Mozilla/4.0 (Windows; MSIE 6.0; Windows NT 6.0)";
		let options = {
			headers,
			maxRedirects: 20,
			timeout: 5000
		};
		if (body)
			options.body = body;
		var file = request(method, url, options);
		Buffer.prototype.charCodeAt = function(index) { return this[index]; }
		console.log("Length: " + file.body.length + " bytes.");
		return file.body;
	},
	writeFile: function(filename, contents) {
		files[filename] = contents;
	},
	readFile: function(filename) {
		return files[filename];
	},
	logUrl: function(method, url) {
		if (urls.indexOf(url) == -1) urls.push(url);
		fs.writeFileSync(directory + "urls.json", JSON.stringify(urls, null, "\t"))
	},
	logResource: function(resourceName, logContent, content) {
		resources[resourceName] = logContent;
		fs.writeFileSync(directory + resourceName, content);
		fs.writeFileSync(directory + "resources.json", JSON.stringify(resources, null, "\t"))
	},
	logSnippet,
	logJS: function(code) {
		const filename = uuid.v4() + ".js";
		console.log("Code saved to", filename)
		logSnippet(filename, {as: "eval'd JS"}, code)
		return code; // Helps with tail call optimization
	}
}<commit_msg>Print resource filetype when saving<commit_after>var fs = require("fs"),
	uuid = require("uuid"),
	request = require("sync-request");

const directory = process.argv[3];

var urls = [],
	snippets = {},
	resources = {},
	files = [];

var logSnippet = function(filename, logContent, content) {
	snippets[filename] = logContent;
	fs.writeFileSync(directory + filename, content);
	fs.writeFileSync(directory + "snippets.json", JSON.stringify(snippets, null, "\t"));
};

module.exports = {
	getUUID: uuid.v4,
	kill: function(message) {
		console.trace(message)
		process.exit(0)
	},
	fetchUrl: function(method, url, headers = {}, body) {
		if (process.argv.indexOf("--download") == -1) {
			console.log(`Faking a ${method} request to ${url}`);
			console.log("Use the flag --download to actually download the file (eg. for encoded payloads).");
			return `(Content of ${url})`;
		}

		console.log(`Emulating a ${method} request to ${url}`);
		headers["User-Agent"] = "Mozilla/4.0 (Windows; MSIE 6.0; Windows NT 6.0)";
		let options = {
			headers,
			maxRedirects: 20,
			timeout: 5000
		};
		if (body)
			options.body = body;
		var file = request(method, url, options);
		Buffer.prototype.charCodeAt = function(index) { return this[index]; }
		console.log(`Downloaded ${file.body.length} bytes.`);
		return file.body;
	},
	writeFile: function(filename, contents) {
		files[filename] = contents;
	},
	readFile: function(filename) {
		return files[filename];
	},
	logUrl: function(method, url) {
		if (urls.indexOf(url) == -1) urls.push(url);
		fs.writeFileSync(directory + "urls.json", JSON.stringify(urls, null, "\t"))
	},
	logResource: function(resourceName, logContent, content, print = false) {
		resources[resourceName] = logContent;
		fs.writeFileSync(directory + resourceName, content);
		fs.writeFileSync(directory + "resources.json", JSON.stringify(resources, null, "\t"))
		if (!print) return;
		let filetype = require("child_process").execSync("file " + JSON.stringify(directory + resourceName)).toString("utf8");
		filetype = filetype.replace(`${directory + resourceName}: `, "").replace("\n", "");
		console.log(`Saved ${directory + resourceName} (${content.length})`);
		console.log(`${directory + resourceName} has been detected as ${filetype}.`);
	},
	logSnippet,
	logJS: function(code) {
		const filename = uuid.v4() + ".js";
		console.log("Code saved to", filename)
		logSnippet(filename, {as: "eval'd JS"}, code)
		return code; // Helps with tail call optimization
	}
}<|endoftext|>


<commit_before>qx.Class.define("unify.ui.widget.styling.Theme", {
  extend: qx.core.Object,

  /**
   * new unify.ui.styling.Theme({
   *   "label" : {
   *     "borderLeft" : "1px solid red",
   *     "children" : {
   *       "mouseover" : {
   *         "borderLeft" : "3px solid green"
   *       }
   *     }
   *   }
   * });
   */
  construct : function(style) {
    this.__style = style;
  },

  members: {
    __style : null,

    getStyles : function(key) {
      var args = key.split(".");

      var styles = this.__style;
      var widgetStyle = {};

      for (var i=0,ii=args.length; styles && (i<ii); i++) {
        var arg = args[i];
        styles = styles[arg];
        if (!styles) {
          break;
        }

        qx.lang.Object.merge(widgetStyle, styles, true);
        styles = styles.children;
      }

      delete widgetStyle.children;

      return widgetStyle;
    }
  },

  destruct : function() {
    this.__style = null;
  }
});
<commit_msg>Inheritance is wrong so rewrite to a simpler theme management<commit_after>qx.Class.define("unify.ui.widget.styling.Theme", {
  extend: qx.core.Object,

  /**
   * new unify.ui.styling.Theme({
   *   "label" : {
   *     "borderLeft" : "1px solid red",
   *     "children" : {
   *       "mouseover" : {
   *         "borderLeft" : "3px solid green"
   *       }
   *     }
   *   }
   * });
   */
  construct : function(style) {
    this.__style = style;
  },

  members: {
    __style : null,

    getStyles : function(key) {
      var styles = this.__style;
      var widgetStyle = styles[key];

      return widgetStyle;
    }
  },

  destruct : function() {
    this.__style = null;
  }
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/** @const {string} */
const ROOT = 'mdc-checkbox';

/** @enum {string} */
const cssClasses = {
  UPGRADED: 'mdc-checkbox--upgraded',
  CHECKED: 'mdc-checkbox--checked',
  INDETERMINATE: 'mdc-checkbox--indeterminate',
  DISABLED: 'mdc-checkbox--disabled',
  ANIM_UNCHECKED_CHECKED: 'mdc-checkbox--anim-unchecked-checked',
  ANIM_UNCHECKED_INDETERMINATE: 'mdc-checkbox--anim-unchecked-indeterminate',
  ANIM_CHECKED_UNCHECKED: 'mdc-checkbox--anim-checked-unchecked',
  ANIM_CHECKED_INDETERMINATE: 'mdc-checkbox--anim-checked-indeterminate',
  ANIM_INDETERMINATE_CHECKED: 'mdc-checkbox--anim-indeterminate-checked',
  ANIM_INDETERMINATE_UNCHECKED: 'mdc-checkbox--anim-indeterminate-unchecked',
};

/** @enum {string} */
const strings = {
  NATIVE_CONTROL_SELECTOR: `.${ROOT}__native-control`,
  TRANSITION_STATE_INIT: 'init',
  TRANSITION_STATE_CHECKED: 'checked',
  TRANSITION_STATE_UNCHECKED: 'unchecked',
  TRANSITION_STATE_INDETERMINATE: 'indeterminate',
};

/** @enum {number} */
const numbers = {
  ANIM_END_LATCH_MS: 100,
};

export {cssClasses, strings, numbers};
<commit_msg>fix(checkbox): Fix background fading too fast (#2122)<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/** @const {string} */
const ROOT = 'mdc-checkbox';

/** @enum {string} */
const cssClasses = {
  UPGRADED: 'mdc-checkbox--upgraded',
  CHECKED: 'mdc-checkbox--checked',
  INDETERMINATE: 'mdc-checkbox--indeterminate',
  DISABLED: 'mdc-checkbox--disabled',
  ANIM_UNCHECKED_CHECKED: 'mdc-checkbox--anim-unchecked-checked',
  ANIM_UNCHECKED_INDETERMINATE: 'mdc-checkbox--anim-unchecked-indeterminate',
  ANIM_CHECKED_UNCHECKED: 'mdc-checkbox--anim-checked-unchecked',
  ANIM_CHECKED_INDETERMINATE: 'mdc-checkbox--anim-checked-indeterminate',
  ANIM_INDETERMINATE_CHECKED: 'mdc-checkbox--anim-indeterminate-checked',
  ANIM_INDETERMINATE_UNCHECKED: 'mdc-checkbox--anim-indeterminate-unchecked',
};

/** @enum {string} */
const strings = {
  NATIVE_CONTROL_SELECTOR: `.${ROOT}__native-control`,
  TRANSITION_STATE_INIT: 'init',
  TRANSITION_STATE_CHECKED: 'checked',
  TRANSITION_STATE_UNCHECKED: 'unchecked',
  TRANSITION_STATE_INDETERMINATE: 'indeterminate',
};

/** @enum {number} */
const numbers = {
  ANIM_END_LATCH_MS: 250,
};

export {cssClasses, strings, numbers};
<|endoftext|>


<commit_before>import axios from "axios";
import { Alert, notification, Progress, Tooltip } from "antd";
import { IconStop } from "../../components/icons/Icons";
import React from "react";

/**
 * Upload a list of files to the server.
 *
 * @param {array} files - List of files to upload
 * @param {string} url - Url to upload to
 * @param {function} onProgressUpdate - allows caller to tap into the upload progress.
 * @returns {Promise<AxiosResponse<any>>}
 */
export function uploadFiles({ files, url, onProgressUpdate = () => {} }) {
  const names = files.map(f => f.name);
  const formData = new FormData();
  files.forEach((f, i) => formData.append(`files[${i}]`, f));

  const CancelToken = axios.CancelToken;
  const source = CancelToken.source();
  const key = Date.now();

  const showProgressNotification = ({
    progress,
    duration = 0,
    cancelled = false
  }) =>
    notification.info({
      key,
      closeIcon: ,
      message: i18n("FileUploader.progress.title"),
      description: (
        <>
          {i18n("FileUploader.progress.desc")}
          {

              {names.map(name => (

{name}

              ))}

          }
          {cancelled ? (
            <Alert
              message={i18n("FileUploader.progress.cancelled")}
              type="info"
            />
          ) : (
            <>

                <Progress
                  style={{ flexGrow: 1 }}
                  percent={progress}
                  size="small"
                />
                <Tooltip
                  title={i18n("FileUploader.progress.tooltip")}
                  placement="topRight"
                >
                  <IconStop onClick={cancelUpload} />
                </Tooltip>

              <Alert
                message={`Don't refresh your page or the download will be cancelled.`}
                type="warning"
              />
            </>
          )}
        </>
      ),
      placement: "bottomRight",
      duration
    });

  const cancelUpload = () => {
    showProgressNotification({ progress: 0, duration: 4, cancelled: true });
    source.cancel();
  };

  const listener = event => {
    // Cancel the event as stated by the standard.
    event.preventDefault();
    // Chrome requires returnValue to be set.
    event.returnValue = window.confirm(i18n("FileUploader.listener-warning"));
  };

  window.addEventListener("beforeunload", listener);

  return axios
    .post(url, formData, {
      headers: {
        "Content-Type": "multipart/form-data"
      },
      cancelToken: source.token,
      onUploadProgress: function(progressEvent) {
        const totalLength = progressEvent.lengthComputable
          ? progressEvent.total
          : progressEvent.target.getResponseHeader("content-length") ||
            progressEvent.target.getResponseHeader(
              "x-decompressed-content-length"
            );
        if (totalLength !== null) {
          const progress = Math.round(
            (progressEvent.loaded * 100) / totalLength
          );
          showProgressNotification({ progress });
        }
      }
    })
    .then(({ data }) => data)
    .catch(({ data }) => data)
    .finally(() => {
      console.log("REMOVING LISENER");
      window.removeEventListener("beforeunload", listener);
    });
}
<commit_msg>Comments and removed logging statement<commit_after>import axios from "axios";
import { Alert, notification, Progress, Tooltip } from "antd";
import { IconStop } from "../../components/icons/Icons";
import React from "react";

/**
 * Upload a list of files to the server.
 *
 * @param {array} files - List of files to upload
 * @param {string} url - Url to upload to
 * @param {function} onProgressUpdate - allows caller to tap into the upload progress.
 * @returns {Promise<AxiosResponse<any>>}
 */
export function uploadFiles({ files, url, onProgressUpdate = () => {} }) {
  const names = files.map(f => f.name);
  const formData = new FormData();
  files.forEach((f, i) => formData.append(`files[${i}]`, f));

  const CancelToken = axios.CancelToken;
  const source = CancelToken.source();
  const key = Date.now();

  const showProgressNotification = ({
    progress,
    duration = 0,
    cancelled = false
  }) =>
    notification.info({
      key,
      closeIcon: ,
      message: i18n("FileUploader.progress.title"),
      description: (
        <>
          {i18n("FileUploader.progress.desc")}
          {

              {names.map(name => (

{name}

              ))}

          }
          {cancelled ? (
            <Alert
              message={i18n("FileUploader.progress.cancelled")}
              type="info"
            />
          ) : (
            <>

                <Progress
                  style={{ flexGrow: 1 }}
                  percent={progress}
                  size="small"
                />
                <Tooltip
                  title={i18n("FileUploader.progress.tooltip")}
                  placement="topRight"
                >
                  <IconStop onClick={cancelUpload} />
                </Tooltip>

              <Alert
                message={`Don't refresh your page or the download will be cancelled.`}
                type="warning"
              />
            </>
          )}
        </>
      ),
      placement: "bottomRight",
      duration
    });

  const cancelUpload = () => {
    showProgressNotification({ progress: 0, duration: 4, cancelled: true });
    source.cancel();
  };

  /**
   * Function called when window onbeforeunload is called when a file is
   * uploading, since leaving the page would cause the upload to cancel.
   * This prompts the user if they want to continue leaving the site.
   * @param event
   */
  const listener = event => {
    // Cancel the event as stated by the standard.
    event.preventDefault();
    // Chrome requires returnValue to be set.
    event.returnValue = window.confirm(i18n("FileUploader.listener-warning"));
  };

  window.addEventListener("beforeunload", listener);

  return axios
    .post(url, formData, {
      headers: {
        "Content-Type": "multipart/form-data"
      },
      cancelToken: source.token,
      onUploadProgress: function(progressEvent) {
        const totalLength = progressEvent.lengthComputable
          ? progressEvent.total
          : progressEvent.target.getResponseHeader("content-length") ||
            progressEvent.target.getResponseHeader(
              "x-decompressed-content-length"
            );
        if (totalLength !== null) {
          const progress = Math.round(
            (progressEvent.loaded * 100) / totalLength
          );
          showProgressNotification({ progress });
        }
      }
    })
    .then(({ data }) => data)
    .catch(({ data }) => data)
    .finally(() => {
      window.removeEventListener("beforeunload", listener);
    });
}
<|endoftext|>


<commit_before>var GitHubApi = require("github").GitHubApi
  , request = require('request')
  , github = new GitHubApi()
  , async = require('async')
  , nfs = require('node-fs')
  , fs = require('fs')
  , lockerUrl
  , auth
  , viewers = []
  ;

exports.sync = function(processInfo, cb) {
    auth = processInfo.auth;
    auth.headers = {"Authorization":"token "+auth.accessToken, "Connection":"keep-alive"};
    lockerUrl = processInfo.lockerUrl;
    github.getUserApi().show(auth.username, function(err, profile) {
        if (err) console.error(err);
        exports.syncRepos(function(err, repos) {
            if (err) console.error(err);
            var responseObj = {data : {}, config: {}};
            responseObj.data.profile = [{obj: profile}];
            responseObj.data.repo = repos;
            responseObj.data.view = viewers;
            console.error(viewers);
            cb(err, responseObj);
        });
    });
};

exports.syncRepos = function(callback) {
    github.getRepoApi().getUserRepos(auth.username, function(err, repos) {
        if(err || !repos || !repos.length) return callback(err, []);
        // process each one to get richer data
        async.forEachSeries(repos, function(repo, cb){
            repo.id = getIDFromUrl(repo.url);
            // get the watchers, is nice
            console.error("checking "+repo.id);
            github.getRepoApi().getRepoWatchers(auth.username, repo.id.substring(repo.id.indexOf('/') + 1), function(err, watchers){
                repo.watchers = watchers;
                // get a snapshot of the full repo, is nice too
                request.get({uri:"https://api.github.com/repos/" + repo.id + "/git/trees/HEAD?recursive=1", headers:auth.headers, json:true}, function(err, resp, tree) {
                    if(err || !tree || !tree.tree) return cb(err);
                    repo.tree = tree.tree;
                    // see if there's any viewers!
                    var viewer = false;
                    for(var i=0; i < repo.tree.length; i++) if(/^\w+\.app$/.test(repo.tree[i].path)) viewer = repo.tree[i].path;
                    if(!viewer) return cb();
                    console.error("found a viewer! "+repo.id);
                    syncRepo(repo, function(err) {
                        // mangle the manifest so it's a unique handle
                        var manifest = repo.id+"/"+viewer;
                        var js;
                        try {
                            js = JSON.parse(fs.readFileSync(manifest));
                            if(!js || js.static != "true") throw new Error("invalid manifest");
                            js.handle = repo.id.replace("/", "-");
                            js.author = auth.username;
                            fs.writeFileSync(manifest, JSON.stringify(js));
                        } catch (err) {
                            // bail, no viewer for you
                            console.error("failed: "+err);
                            return cb();
                        }
                        viewers.push({id:repo.id, manifest:manifest, at:repo.pushed_at, viewer:js.viewer});
                        request.get({url:lockerUrl+'/map/upsert?manifest=Me/github/'+manifest}, function(err, resp) {
                            cb();
                        });
                    });
                });
            });
        }, function(err){
            callback(err, repos);
        });
    });
}

function getIDFromUrl(url) {
    if(typeof url !== 'string')
        return url;
    return url.substring(url.lastIndexOf('/', url.lastIndexOf('/') - 1) + 1);
}

function syncRepo(repo, callback)
{
    var existing = {};
    try {
        var js = JSON.parse(fs.readFileSync(repo.id+".json"));
        for(var i=0; i < js.tree.length; i++)
        {
            existing[js.tree[i].path] = js.tree[i].sha;
        }
    } catch(e){};
    async.forEach(repo.tree, function(t, cb){
        if(t.type != "tree") return cb();
        if(existing[t.path] == t.sha) return cb(); // no changes
        nfs.mkdir(repo.id + "/" + t.path, 0777, true, cb);
    }, function(){
        // then the blobs
        async.forEachSeries(repo.tree, function(t, cb){
            if(t.type != "blob") return cb();
            if(existing[t.path] == t.sha) return cb(); // no changes
            setTimeout(function(){
                request.get({uri:'https://raw.github.com/'+repo.id+'/HEAD/'+t.path, encoding: 'binary', headers:auth.headers}, function(err, resp, body) {
                    console.error(resp.statusCode + " for "+ t.path);
                    if(err || !resp || resp.statusCode != 200) {t.sha = ""; return cb(); } // don't save the sha so it gets retried again
                    fs.writeFile(repo.id + "/" + t.path, body, 'binary', cb);
                });
            },500);
        }, function(){
            fs.writeFile(repo.id+".json", JSON.stringify(repo));
            callback();
        });
    });
}<commit_msg>cache repo status to hit api less and sync tons faster<commit_after>var GitHubApi = require("github").GitHubApi
  , request = require('request')
  , github = new GitHubApi()
  , async = require('async')
  , nfs = require('node-fs')
  , fs = require('fs')
  , lockerUrl
  , auth
  , viewers = []
  ;

exports.sync = function(processInfo, cb) {
    auth = processInfo.auth;
    auth.headers = {"Authorization":"token "+auth.accessToken, "Connection":"keep-alive"};
    var cached = {};
    if (processInfo.config && processInfo.config.cached) {
        cached = processInfo.config.cached;
    }
    lockerUrl = processInfo.lockerUrl;
    github.getUserApi().show(auth.username, function(err, profile) {
        if (err) console.error(err);
        exports.syncRepos(cached, function(err, repos) {
            if (err) console.error(err);
            var responseObj = {data : {}, config: { cached: cached }};
            responseObj.data.profile = [{obj: profile}];
            responseObj.data.repo = repos;
            responseObj.data.view = viewers;
            console.error(viewers);
            cb(err, responseObj);
        });
    });
};

exports.syncRepos = function(cached, callback) {
    github.getRepoApi().getUserRepos(auth.username, function(err, repos) {
        if(err || !repos || !repos.length) return callback(err, []);
        // process each one to get richer data
        async.forEach(repos, function(repo, cb){
            repo.id = getIDFromUrl(repo.url);
            // nothing changed
            var ckey = repo.pushed_at + repo.watchers;
            if(cached[repo.id] == ckey) return cb();
            cached[repo.id] = ckey;
            // get the watchers, is nice
            console.error("checking "+repo.id);
            github.getRepoApi().getRepoWatchers(auth.username, repo.id.substring(repo.id.indexOf('/') + 1), function(err, watchers){
                repo.watchers = watchers;
                // get a snapshot of the full repo, is nice too
                request.get({uri:"https://api.github.com/repos/" + repo.id + "/git/trees/HEAD?recursive=1", headers:auth.headers, json:true}, function(err, resp, tree) {
                    if(err || !tree || !tree.tree) return cb(err);
                    repo.tree = tree.tree;
                    // see if there's any viewers!
                    var viewer = false;
                    for(var i=0; i < repo.tree.length; i++) if(/^\w+\.app$/.test(repo.tree[i].path)) viewer = repo.tree[i].path;
                    if(!viewer) return cb();
                    console.error("found a viewer! "+repo.id);
                    syncRepo(repo, function(err) {
                        // mangle the manifest so it's a unique handle
                        var manifest = repo.id+"/"+viewer;
                        var js;
                        try {
                            js = JSON.parse(fs.readFileSync(manifest));
                            if(!js || js.static != "true") throw new Error("invalid manifest");
                            js.handle = repo.id.replace("/", "-");
                            js.author = auth.username;
                            fs.writeFileSync(manifest, JSON.stringify(js));
                        } catch (err) {
                            // bail, no viewer for you
                            console.error("failed: "+err);
                            return cb();
                        }
                        viewers.push({id:repo.id, manifest:manifest, at:repo.pushed_at, viewer:js.viewer});
                        request.get({url:lockerUrl+'/map/upsert?manifest=Me/github/'+manifest}, function(err, resp) {
                            cb();
                        });
                    });
                });
            });
        }, function(err){
            callback(err, repos);
        });
    });
}

function getIDFromUrl(url) {
    if(typeof url !== 'string')
        return url;
    return url.substring(url.lastIndexOf('/', url.lastIndexOf('/') - 1) + 1);
}

function syncRepo(repo, callback)
{
    var existing = {};
    try {
        var js = JSON.parse(fs.readFileSync(repo.id+".json"));
        for(var i=0; i < js.tree.length; i++)
        {
            existing[js.tree[i].path] = js.tree[i].sha;
        }
    } catch(e){};
    async.forEach(repo.tree, function(t, cb){
        if(t.type != "tree") return cb();
        if(existing[t.path] == t.sha) return cb(); // no changes
        nfs.mkdir(repo.id + "/" + t.path, 0777, true, cb);
    }, function(){
        // then the blobs
        async.forEachSeries(repo.tree, function(t, cb){
            if(t.type != "blob") return cb();
            if(existing[t.path] == t.sha) return cb(); // no changes
            setTimeout(function(){
                request.get({uri:'https://raw.github.com/'+repo.id+'/HEAD/'+t.path, encoding: 'binary', headers:auth.headers}, function(err, resp, body) {
                    console.error(resp.statusCode + " for "+ t.path);
                    if(err || !resp || resp.statusCode != 200) {t.sha = ""; return cb(); } // don't save the sha so it gets retried again
                    fs.writeFile(repo.id + "/" + t.path, body, 'binary', cb);
                });
            },500);
        }, function(){
            fs.writeFile(repo.id+".json", JSON.stringify(repo));
            callback();
        });
    });
}<|endoftext|>


<commit_before>import Component from '@glimmer/component';
import {action} from '@ember/object';
import {inject as service} from '@ember/service';
import {task} from 'ember-concurrency-decorators';
import {tracked} from '@glimmer/tracking';

export default class GhMembersSegmentSelect extends Component {
    @service store;

    @tracked _options = [];

    get renderInPlace() {
        return this.args.renderInPlace === undefined ? false : this.args.renderInPlace;
    }

    constructor() {
        super(...arguments);
        this.fetchOptionsTask.perform();
    }

    get options() {
        if (this.args.hideOptionsWhenAllSelected) {
            const selectedSegments = this.selectedOptions.mapBy('segment');
            if (selectedSegments.includes('status:free') && selectedSegments.includes('status:-free')) {
                return this._options.filter(option => !option.groupName);
            }
        }

        return this._options;
    }

    get flatOptions() {
        const options = [];

        function getOptions(option) {
            if (option.options) {
                return option.options.forEach(getOptions);
            }

            options.push(option);
        }

        this._options.forEach(getOptions);

        return options;
    }

    get selectedOptions() {
        const segments = (this.args.segment || '').split(',');
        return this.flatOptions.filter(option => segments.includes(option.segment));
    }

    @action
    setSegment(options) {
        const segment = options.mapBy('segment').join(',') || null;
        this.args.onChange?.(segment);
    }

    @task
    *fetchOptionsTask() {
        const options = yield [{
            name: 'Free members',
            segment: 'status:free',
            class: 'segment-status-free'
        }, {
            name: 'Paid members',
            segment: 'status:-free', // paid & comped
            class: 'segment-status-paid'
        }];

        // fetch all labels w̶i̶t̶h̶ c̶o̶u̶n̶t̶s̶
        // TODO: add `include: 'count.members` to query once API is fixed
        const labels = yield this.store.query('label', {limit: 'all'});

        if (labels.length > 0) {
            const labelsGroup = {
                groupName: 'Labels',
                options: []
            };

            labels.forEach((label) => {
                labelsGroup.options.push({
                    name: label.name,
                    segment: `label:${label.slug}`,
                    count: label.count?.members,
                    class: 'segment-label'
                });
            });

            options.push(labelsGroup);
        }

        this._options = options;
    }
}
<commit_msg>Added product options to members segment select<commit_after>import Component from '@glimmer/component';
import {action} from '@ember/object';
import {inject as service} from '@ember/service';
import {task} from 'ember-concurrency-decorators';
import {tracked} from '@glimmer/tracking';

export default class GhMembersSegmentSelect extends Component {
    @service store;

    @tracked _options = [];

    get renderInPlace() {
        return this.args.renderInPlace === undefined ? false : this.args.renderInPlace;
    }

    constructor() {
        super(...arguments);
        this.fetchOptionsTask.perform();
    }

    get options() {
        if (this.args.hideOptionsWhenAllSelected) {
            const selectedSegments = this.selectedOptions.mapBy('segment');
            if (selectedSegments.includes('status:free') && selectedSegments.includes('status:-free')) {
                return this._options.filter(option => !option.groupName);
            }
        }

        return this._options;
    }

    get flatOptions() {
        const options = [];

        function getOptions(option) {
            if (option.options) {
                return option.options.forEach(getOptions);
            }

            options.push(option);
        }

        this._options.forEach(getOptions);

        return options;
    }

    get selectedOptions() {
        const segments = (this.args.segment || '').split(',');
        return this.flatOptions.filter(option => segments.includes(option.segment));
    }

    @action
    setSegment(options) {
        const segment = options.mapBy('segment').join(',') || null;
        this.args.onChange?.(segment);
    }

    @task
    *fetchOptionsTask() {
        const options = yield [{
            name: 'Free members',
            segment: 'status:free',
            class: 'segment-status-free'
        }, {
            name: 'Paid members',
            segment: 'status:-free', // paid & comped
            class: 'segment-status-paid'
        }];

        // fetch all labels w̶i̶t̶h̶ c̶o̶u̶n̶t̶s̶
        // TODO: add `include: 'count.members` to query once API is fixed
        const labels = yield this.store.query('label', {limit: 'all'});

        if (labels.length > 0) {
            const labelsGroup = {
                groupName: 'Labels',
                options: []
            };

            labels.forEach((label) => {
                labelsGroup.options.push({
                    name: label.name,
                    segment: `label:${label.slug}`,
                    count: label.count?.members,
                    class: 'segment-label'
                });
            });

            options.push(labelsGroup);
        }

        // fetch all products w̶i̶t̶h̶ c̶o̶u̶n̶t̶s̶
        // TODO: add `include: 'count.members` to query once API supports
        const products = yield this.store.query('product', {limit: 'all'});

        if (products.length > 0) {
            const productsGroup = {
                groupName: 'Products',
                options: []
            };

            products.forEach((product) => {
                productsGroup.options.push({
                    name: product.name,
                    segment: `product:${product.slug}`,
                    count: product.count?.members,
                    class: 'segment-product'
                });
            });

            options.push(productsGroup);
        }

        this._options = options;
    }
}
<|endoftext|>


<commit_before>/**
 * Admin
 *
 * for admin pages
 */
var Admin = typeof Admin == 'undefined' ? {} : Admin;

/**
 * Forms
 *
 * @return void
 */
Admin.form = function() {
	// Tooltips activation
	$('[rel=tooltip],*[data-title]:not([data-content]),input[title],textarea[title]').tooltip();
	if (typeof $.prototype.tipsy == 'function') {
		$('a.tooltip').tipsy({gravity: 's', html: false}); // Legacy tooltip
	}

	var ajaxToggle = function(e) {
		var $this = $(this);
		$this.addClass('icon-spinner icon-spin').find('i').attr('class', 'icon-none');
		var url = $this.data('url');
		$.post(url, function(data) {
			$this.parent().html(data);
		});
	}

	// Autocomplete
	if (typeof $.fn.typeahead_autocomplete === 'function') {
		$('input.typeahead-autocomplete').typeahead_autocomplete();
	}

	// Row Actions
	$('body')
		.on('click', 'a[data-row-action]', Admin.processLink)
		.on('click', 'a.ajax-toggle', ajaxToggle)
	;
}

/**
 * Protect forms for accidental page refresh
 */
Admin.protectForms = function() {
	var forms  = document.getElementsByClassName('protected-form');
	if (forms.length > 0) {
		var watchElements = ['input', 'select', 'textarea'];
		var ignored = ['button', '[type=submit]', '.cancel'];
		for (var i = 0; i < forms.length; i++) {
			var $form = $(forms[i]);
			var customIgnore = $form.data('ignore-elements');
			var whitelist = ignored.join(',');
			if (customIgnore) {
				whitelist += ',' + customIgnore;
			}
			$form
				.on('change', watchElements.join(','), function(e) {
					$form.data('dirty', true);
				})
				.on('click', whitelist, function(e) {
					$form.data('dirty', false);
					Croogo.Wysiwyg.resetDirty();
				});
		}

		window.onbeforeunload = function(e) {
			var dirty = false;
			for (var i = 0; i < forms.length; i++) {
				if ($(forms[i]).data('dirty') === true) {
					dirty = true;
					break;
				}
			}
			if (!dirty && !Croogo.Wysiwyg.checkDirty()) {
				return;
			}

			var confirmationMessage = 'Please save your changes';
			(e || window.event).returnValue = confirmationMessage;
			return confirmationMessage;
		};
	}
}

/**
 * Helper to process row action links
 */
Admin.processLink = function(event) {
	var $el = $(event.currentTarget);
	var checkbox = $(event.currentTarget.attributes["href"].value);
	var form = checkbox.get(0).form;
	var action = $el.data('row-action');
	var confirmMessage = $el.data('confirm-message');
	if (confirmMessage && !confirm(confirmMessage)) {
		return false;
	}
	$('input[type=checkbox]', form).prop('checked', false);
	checkbox.prop("checked", true);
	$('#bulk-action select', form).val(action);
	form.submit();
	return false;
}

/**
 * Extra stuff
 *
 * rounded corners, striped table rows, etc
 *
 * @return void
 */
Admin.extra = function() {
	// Activates the first tab in #content
	$('#content .nav-tabs > li:first-child a').tab('show');

	// Box toggle
	$('body').on('click', '.box-title', function() {
		$(this).next().slideToggle();
	});

	if (typeof $.prototype.tabs == 'function') {
		$('.tabs').tabs(); // legacy tabs from jquery-ui
	}
	if (typeof $.prototype.elastic == 'function') {
		$('textarea').not('.content').elastic();
	}
	$("div.message").addClass("notice");
	$('#loading p').addClass('ui-corner-bl ui-corner-br');
}

/**
 * Helper callback for toggling record selection
 */
Admin.toggleRowSelection = function(selector, checkboxSelector) {
	var $selector = $(selector);
	if (typeof checkboxSelector == 'undefined') {
		checkboxSelector = "input.row-select[type='checkbox']";
	}
	$selector.on('click', function(e) {
		$(checkboxSelector).attr('checked', $selector.is(':checked'));
	});
}

/**
 * Document ready
 *
 * @return void
 */
$(document).ready(function() {
	Admin.form();
	Admin.protectForms();
	Admin.extra();
});
<commit_msg>Fix: Use $.prop() instead of $.attr()<commit_after>/**
 * Admin
 *
 * for admin pages
 */
var Admin = typeof Admin == 'undefined' ? {} : Admin;

/**
 * Forms
 *
 * @return void
 */
Admin.form = function() {
	// Tooltips activation
	$('[rel=tooltip],*[data-title]:not([data-content]),input[title],textarea[title]').tooltip();
	if (typeof $.prototype.tipsy == 'function') {
		$('a.tooltip').tipsy({gravity: 's', html: false}); // Legacy tooltip
	}

	var ajaxToggle = function(e) {
		var $this = $(this);
		$this.addClass('icon-spinner icon-spin').find('i').attr('class', 'icon-none');
		var url = $this.data('url');
		$.post(url, function(data) {
			$this.parent().html(data);
		});
	}

	// Autocomplete
	if (typeof $.fn.typeahead_autocomplete === 'function') {
		$('input.typeahead-autocomplete').typeahead_autocomplete();
	}

	// Row Actions
	$('body')
		.on('click', 'a[data-row-action]', Admin.processLink)
		.on('click', 'a.ajax-toggle', ajaxToggle)
	;
}

/**
 * Protect forms for accidental page refresh
 */
Admin.protectForms = function() {
	var forms  = document.getElementsByClassName('protected-form');
	if (forms.length > 0) {
		var watchElements = ['input', 'select', 'textarea'];
		var ignored = ['button', '[type=submit]', '.cancel'];
		for (var i = 0; i < forms.length; i++) {
			var $form = $(forms[i]);
			var customIgnore = $form.data('ignore-elements');
			var whitelist = ignored.join(',');
			if (customIgnore) {
				whitelist += ',' + customIgnore;
			}
			$form
				.on('change', watchElements.join(','), function(e) {
					$form.data('dirty', true);
				})
				.on('click', whitelist, function(e) {
					$form.data('dirty', false);
					Croogo.Wysiwyg.resetDirty();
				});
		}

		window.onbeforeunload = function(e) {
			var dirty = false;
			for (var i = 0; i < forms.length; i++) {
				if ($(forms[i]).data('dirty') === true) {
					dirty = true;
					break;
				}
			}
			if (!dirty && !Croogo.Wysiwyg.checkDirty()) {
				return;
			}

			var confirmationMessage = 'Please save your changes';
			(e || window.event).returnValue = confirmationMessage;
			return confirmationMessage;
		};
	}
}

/**
 * Helper to process row action links
 */
Admin.processLink = function(event) {
	var $el = $(event.currentTarget);
	var checkbox = $(event.currentTarget.attributes["href"].value);
	var form = checkbox.get(0).form;
	var action = $el.data('row-action');
	var confirmMessage = $el.data('confirm-message');
	if (confirmMessage && !confirm(confirmMessage)) {
		return false;
	}
	$('input[type=checkbox]', form).prop('checked', false);
	checkbox.prop("checked", true);
	$('#bulk-action select', form).val(action);
	form.submit();
	return false;
}

/**
 * Extra stuff
 *
 * rounded corners, striped table rows, etc
 *
 * @return void
 */
Admin.extra = function() {
	// Activates the first tab in #content
	$('#content .nav-tabs > li:first-child a').tab('show');

	// Box toggle
	$('body').on('click', '.box-title', function() {
		$(this).next().slideToggle();
	});

	if (typeof $.prototype.tabs == 'function') {
		$('.tabs').tabs(); // legacy tabs from jquery-ui
	}
	if (typeof $.prototype.elastic == 'function') {
		$('textarea').not('.content').elastic();
	}
	$("div.message").addClass("notice");
	$('#loading p').addClass('ui-corner-bl ui-corner-br');
}

/**
 * Helper callback for toggling record selection
 */
Admin.toggleRowSelection = function(selector, checkboxSelector) {
	var $selector = $(selector);
	if (typeof checkboxSelector == 'undefined') {
		checkboxSelector = "input.row-select[type='checkbox']";
	}
	$selector.on('click', function(e) {
		$(checkboxSelector).prop('checked', $selector.is(':checked'));
	});
}

/**
 * Document ready
 *
 * @return void
 */
$(document).ready(function() {
	Admin.form();
	Admin.protectForms();
	Admin.extra();
});
<|endoftext|>


<commit_before><commit_msg>fix groove bug<commit_after><|endoftext|>


<commit_before>var request = require('request'),
	url = require('url');

module.exports.getSize = function getSize(file, next) {
	var compressed = 0,
		decompressed = 0;

	request.get({
			url: url.parse(file)
		}, function(err, res, body) {
			if (res.statusCode == 200) {
				if (res.headers && res.headers['content-length']) {
					compressed = parseInt(res.headers['content-length'], 10);
				} else {
					compressed = body.length;
				}
			}
		})
		/*.on('response', function (res) {
			console.log('response', arguments.length);
			if (res.statusCode == 200) {
				if (res.headers && res.headers['content-length']) {
					compressed = parseInt(res.headers['content-length'], 10);
					console.log('yes header content-length: ', compressed);
				} else {
					console.log('no header content-length; calculating compressed data...');
					res.on('data', function (data) {
						compressed += data.length;
					});
				}
			}
		})*/
		.on('data', function(data) {
			decompressed += Buffer.byteLength(data.toString(), 'utf8');
		})
		.on('complete', function(err) {
			next(null, {
				compressed: compressed,
				decompressed: decompressed
			});
		}).on('error', function(err) {
			next(err);
		});
};
<commit_msg>:bug: Fixed bug when response is undefined when getting file size<commit_after>var request = require('request'),
	url = require('url');

module.exports.getSize = function getSize(file, next) {
	var compressed = 0,
		decompressed = 0;

	request.get({
			url: url.parse(file)
		}, function(err, res, body) {
			if (!err && res.statusCode === 200) {
				if (res.headers && res.headers['content-length']) {
					compressed = parseInt(res.headers['content-length'], 10);
				} else {
					compressed = body.length;
				}
			}
		})
		/*.on('response', function (res) {
			console.log('response', arguments.length);
			if (res.statusCode == 200) {
				if (res.headers && res.headers['content-length']) {
					compressed = parseInt(res.headers['content-length'], 10);
					console.log('yes header content-length: ', compressed);
				} else {
					console.log('no header content-length; calculating compressed data...');
					res.on('data', function (data) {
						compressed += data.length;
					});
				}
			}
		})*/
		.on('data', function(data) {
			decompressed += Buffer.byteLength(data.toString(), 'utf8');
		})
		.on('complete', function(err) {
			next(null, {
				compressed: compressed,
				decompressed: decompressed
			});
		}).on('error', function(err) {
			next(err);
		});
};
<|endoftext|>


<commit_before>var moment = require('moment');
var bcrypt = require('bcryptjs');

exports = module.exports = function(urls){
	return function authenticator(req, res, next){

		/// Basic cookie based authentication
		var cookie = req.signedCookies.authentication;
		if((!cookie)||(cookie == '')){ // :O No cookie!
			res.redirect(urls.login);
		} else {
			console.log(cookie);
			req.database.models.sessions.findOne({ _id: JSON.parse(cookie).sessionID }).exec(function(error, session) {
				if(error) req.authenticated = false;
				// Do some useful session time/access/ip comparisons here
				else req.authenticated = { username: session.username };
			});
		}
		///

		req.signIn = function(req, res, callback){
			var opened = moment();
			var expires = opened.add(7, 'days');

			req.database.models.users.findOne({ username: req.param('username') }).exec(function(error, user) {
				bcrypt.compare(req.param('password'), user.hash, function(error, result) {
					if(error) return callback(error);
					if(result){
						// Create a new session token
						req.database.models.sessions.create({
							username: username,
							access: 'approved',
							ipAddress: req.ip,
							stamp: { opened: opened, expires: expires }
						}, function(error, session){
							if(error) return callback(error);

							res.cookie('authentication', { sessionID: session._id, opened: opened }, { signed: true });
							callback(undefined, session);
						});
					}
				});
			})
		},

		req.signOut = function(req, res, callback){
			res.clearCookie('authentication');
		}

		next();
	}
}<commit_msg>Login bug fix<commit_after>var moment = require('moment');
var bcrypt = require('bcryptjs');

exports = module.exports = function(urls){
	return function authenticator(req, res, next){

		/// Basic cookie based authentication
		var cookie = req.signedCookies.authentication;
		if((!cookie)||(cookie == '')){ // :O No cookie!
			return res.redirect(urls.login);
		} else {
			console.log(cookie);
			req.database.models.sessions.findOne({ _id: JSON.parse(cookie).sessionID }).exec(function(error, session) {
				if(error) req.authenticated = false;
				// Do some useful session time/access/ip comparisons here
				else req.authenticated = { username: session.username };
			});
		}
		///

		req.signIn = function(req, res, callback){
			var opened = moment();
			var expires = opened.add(7, 'days');

			req.database.models.users.findOne({ username: req.param('username') }).exec(function(error, user) {
				bcrypt.compare(req.param('password'), user.hash, function(error, result) {
					if(error) return callback(error);
					if(result){
						// Create a new session token
						req.database.models.sessions.create({
							username: username,
							access: 'approved',
							ipAddress: req.ip,
							stamp: { opened: opened, expires: expires }
						}, function(error, session){
							if(error) return callback(error);

							res.cookie('authentication', { sessionID: session._id, opened: opened }, { signed: true });
							callback(undefined, session);
						});
					}
				});
			})
		},

		req.signOut = function(req, res, callback){
			res.clearCookie('authentication');
		}

		next();
	}
}<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([
    "firebug/lib/events",
    "firebug/lib/trace"
],
function factoryOptions(Events, FBTrace) {

// ********************************************************************************************* //
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;

const nsIPrefBranch = Ci.nsIPrefBranch;
const nsIPrefBranch2 = Ci.nsIPrefBranch2;
const PrefService = Cc["@mozilla.org/preferences-service;1"];

const nsIPrefService = Ci.nsIPrefService;
const prefService = PrefService.getService(nsIPrefService);
const prefs = PrefService.getService(nsIPrefBranch2);

const prefNames =  // XXXjjb TODO distribute to modules
[
    // Global
    "defaultPanelName", "throttleMessages", "textSize", "showInfoTips",
    "commandEditor", "textWrapWidth", "framePosition", "showErrorCount",
    "activateSameOrigin", "allPagesActivation", "hiddenPanels",
    "panelTabMinWidth", "sourceLinkLabelWidth", "currentVersion",
    "useDefaultLocale", "toolbarCustomizationDone", "addonBarOpened",
    "showBreakNotification", "showStatusIcon", "stringCropLength",
    "showFirstRunPage",

    // Search
    "searchCaseSensitive", "searchGlobal", "searchUseRegularExpression",
    "netSearchHeaders", "netSearchParameters", "netSearchResponseBody",

    // Console
    "showJSErrors", "showJSWarnings", "showCSSErrors", "showXMLErrors",
    "showChromeErrors", "showChromeMessages", "showExternalErrors",
    "showXMLHttpRequests", "showNetworkErrors", "tabularLogMaxHeight",
    "consoleFilterTypes", "alwaysShowCommandLine",

    // HTML
    "showFullTextNodes", "showCommentNodes",
    "showTextNodesWithWhitespace", "showTextNodesWithEntities",
    "highlightMutations", "expandMutations", "scrollToMutations", "shadeBoxModel",
    "showQuickInfoBox", "displayedAttributeValueLimit", "multiHighlightLimit",

    // CSS
    "onlyShowAppliedStyles",
    "showUserAgentCSS",
    "expandShorthandProps",
    "computedStylesDisplay",
    "showMozillaSpecificStyles",
    "cssEditMode",

    // Script
    "decompileEvals", "replaceTabs", "maxScriptLineLength",

    // DOM
    "showUserProps", "showUserFuncs", "showDOMProps", "showDOMFuncs", "showDOMConstants",
    "ObjectShortIteratorMax", "showEnumerableProperties", "showOwnProperties",
    "showInlineEventHandlers",

    // Layout
    "showRulers",

    // Net
    "netFilterCategory", "netDisplayedResponseLimit",
    "netDisplayedPostBodyLimit", "netPhaseInterval", "sizePrecision",
    "netParamNameLimit", "netShowPaintEvents", "netShowBFCacheResponses",
    "netHtmlPreviewHeight",

    // JSON Preview
    "sortJsonPreview",

    // Stack
    "omitObjectPathStack",

    "showStackTrace", // Console
    "filterSystemURLs", // Stack
    "showAllSourceFiles", "breakOnErrors",  "trackThrowCatch" // Script
];

var optionUpdateMap = {};

// ********************************************************************************************* //

/**
 * Interface to preference storage.
 * Panels send commands to request option change.
 * Backend responds with events when the change is accepted.
 */
var Options =
/** @lends Options */
{
    getPrefDomain: function()
    {
        return this.prefDomain;
    },

    initialize: function(prefDomain)
    {
        this.prefDomain = prefDomain;

        if (FBTrace.DBG_INITIALIZE)
            FBTrace.sysout("options.initialize with prefDomain " + this.prefDomain);

        this.initializePrefs();
    },

    shutdown: function()
    {
        prefs.removeObserver(this.prefDomain, this, false);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Custom Listeners

    listeners: [],

    addListener: function(listener)
    {
        this.listeners.push(listener);
    },

    removeListener: function(listener)
    {
        for (var i=0; i<this.listeners.length; ++i)
            if (this.listeners[i] == listener)
                return this.listeners.splice(i, 1);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // nsIPrefObserver

    observe: function(subject, topic, data)
    {
        if (data.indexOf(Options.prefDomain) === -1)
            return;

        var name = data.substr(Options.prefDomain.length+1);  // +1 for .
        var value = this.get(name);

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.observe name = value: "+name+"= "+value+"\n");

        this.updatePref(name, value);
    },

    updatePref: function(name, value)
    {
        // Prevent infinite recursion due to pref observer
        if (optionUpdateMap.hasOwnProperty(name))
            return;

        try
        {
            optionUpdateMap[name] = 1;
            Firebug[name] = value;

            Events.dispatch(this.listeners, "updateOption", [name, value]);
        }
        catch (err)
        {
            if (FBTrace.DBG_OPTIONS || FBTrace.DBG_ERRORS)
                FBTrace.sysout("options.updatePref EXCEPTION:" + err, err);
        }
        finally
        {
            delete optionUpdateMap[name];
        }

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.updatePref EXIT: "+name+"="+value+"\n");
    },

    register: function(name, value)
    {
        var currentValue = this.getPref(this.prefDomain, name);

        if (FBTrace.DBG_INITIALIZE)
            FBTrace.sysout("registerPreference "+name+" -> "+value+" type "+typeof(value)+
                " with currentValue "+currentValue);

        if (currentValue === undefined)
        {
            // https://developer.mozilla.org/en/Code_snippets/Preferences
            // This is the reason why you should usually pass strings ending with a dot to
            // getBranch(), like prefs.getBranch("accessibility.").
            var defaultBranch = prefService.getDefaultBranch(this.prefDomain+"."); //

            var type = this.getPreferenceTypeByExample(typeof(value));
            if (this.setPreference(name, value, type, defaultBranch))
                return true;
        }

        return false;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Options
    // TODO support per context options eg break on error

    initializePrefs: function()
    {
        for (var i = 0; i < prefNames.length; ++i)
            Firebug[prefNames[i]] = this.getPref(this.prefDomain, prefNames[i]);

        prefs.addObserver(this.prefDomain, this, false);

        var basePrefNames = prefNames.length;

        for (var i = basePrefNames; i < prefNames.length; ++i)
            Firebug[prefNames[i]] = this.getPref(this.prefDomain, prefNames[i]);

        if (FBTrace.DBG_OPTIONS)
        {
             for (var i = 0; i < prefNames.length; ++i)
             {
                FBTrace.sysout("options.initialize option "+this.prefDomain+"."+prefNames[i]+"="+
                    Firebug[prefNames[i]]+"\n");
             }
        }
    },

    togglePref: function(name)
    {
        this.setPref(Options.prefDomain, name, !Firebug[name]);
    },

    get: function(name)
    {
        return Options.getPref(this.prefDomain, name);
    },

    getPref: function(prefDomain, name)
    {
        var prefName = prefDomain + "." + name;

        var type = prefs.getPrefType(prefName);

        var value;
        if (type == nsIPrefBranch.PREF_STRING)
            value = prefs.getCharPref(prefName);
        else if (type == nsIPrefBranch.PREF_INT)
            value = prefs.getIntPref(prefName);
        else if (type == nsIPrefBranch.PREF_BOOL)
            value = prefs.getBoolPref(prefName);

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.getPref "+prefName+" has type "+
                this.getPreferenceTypeName(type)+" and value "+value);

        return value;
    },

    set: function(name, value)
    {
        Options.setPref(Options.prefDomain, name, value);
    },

    /**
     * Set a preference value.
     *
     * @param prefDomain, e.g. "extensions.firebug"
     * @param name Name of the preference (the part after prfDomain without dot)
     * @param value New value for the preference.
     * @param prefType optional pref type useful when adding a new preference.
     */
    setPref: function(prefDomain, name, value, prefType)
    {
        var prefName = prefDomain + "." + name;

        var type = this.getPreferenceTypeByExample((prefType ? prefType : typeof(value)));
        if (!this.setPreference(prefName, value, type, prefs))
            return;

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.setPref type="+type+" name="+prefName+" value="+value);
    },

    setPreference: function(prefName, value, type, prefBranch)
    {
        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("setPreference "+prefName, {prefName: prefName, value: value});

        if (type == nsIPrefBranch.PREF_STRING)
            prefBranch.setCharPref(prefName, value);
        else if (type == nsIPrefBranch.PREF_INT)
            prefBranch.setIntPref(prefName, value);
        else if (type == nsIPrefBranch.PREF_BOOL)
            prefBranch.setBoolPref(prefName, value);
        else if (type == nsIPrefBranch.PREF_INVALID)
        {
            FBTrace.sysout("options.setPref FAILS: Invalid preference "+prefName+" with type "+
                type+", check that it is listed in defaults/prefs.js");

            return false;
        }

        return true;
    },

    getPreferenceTypeByExample: function(prefType)
    {
        if (prefType)
        {
            if (prefType === typeof("s"))
                var type = nsIPrefBranch.PREF_STRING;
            else if (prefType === typeof(1))
                var type = nsIPrefBranch.PREF_INT;
            else if (prefType === typeof (true))
                var type = nsIPrefBranch.PREF_BOOL;
            else
                var type = nsIPrefBranch.PREF_INVALID;
        }
        else
        {
            var type = prefs.getPrefType(prefName);
        }

        return type;
    },

    getPreferenceTypeName: function(prefType)
    {
        if (prefType == Ci.nsIPrefBranch.PREF_STRING)
            return "string";
        else if (prefType == Ci.nsIPrefBranch.PREF_INT)
            return "int";
        else if (prefType == Ci.nsIPrefBranch.PREF_BOOL)
            return "boolean";
    },

    clearPref: function(prefDomain, name)
    {
        var prefName = prefDomain + "." + name;
        if (prefs.prefHasUserValue(prefName))
            prefs.clearUserPref(prefName);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Firebug UI text zoom

    changeTextSize: function(amt)
    {
        var textSize = Options.get("textSize");
        var newTextSize = textSize + amt;
        if ((newTextSize < 0 && Math.abs(newTextSize) < this.negativeZoomFactors.length) ||
            (newTextSize >= 0 && textSize+amt < this.positiveZoomFactors.length))
        {
            this.setTextSize(textSize+amt);
        }
    },

    setTextSize: function(value)
    {
        var setValue = value;
        if (value >= this.positiveZoomFactors.length)
            setValue = this.positiveZoomFactors[this.positiveZoomFactors.length-1];
        else if (value < 0 && Math.abs(value) >= this.negativeZoomFactors.length)
            setValue = this.negativeZoomFactors[this.negativeZoomFactors.length-1];
        this.set("textSize", setValue);
    },

    positiveZoomFactors: [1, 1.1, 1.2, 1.3, 1.5, 2, 3],
    negativeZoomFactors: [1, 0.95, 0.8, 0.7, 0.5],

    getZoomByTextSize: function(value)
    {
        var zoom = value >= 0 ? this.positiveZoomFactors[value] :
            this.negativeZoomFactors[Math.abs(value)];

        return zoom;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

    /**
     * Resets all Firebug options to default state. Note that every option
     * starting with "extensions.firebug" is considered as a Firebug option.
     */
    resetAllOptions: function()
    {
        var preferences = prefs.getChildList("extensions.firebug", {});
        for (var i = 0; i < preferences.length; i++)
        {
            if (preferences[i].indexOf("DBG_") == -1 &&
                preferences[i].indexOf("filterSystemURLs") == -1)
            {
                if (FBTrace.DBG_OPTIONS)
                    FBTrace.sysout("Clearing option: "+i+") "+preferences[i]);
                if (prefs.prefHasUserValue(preferences[i]))  // avoid exception
                    prefs.clearUserPref(preferences[i]);
            }
            else
            {
                if (FBTrace.DBG_OPTIONS)
                    FBTrace.sysout("Skipped clearing option: "+i+") "+preferences[i]);
            }
        }
    },
};

// ********************************************************************************************* //
// Registration

return Options;

// ********************************************************************************************* //
});
<commit_msg>[1.9] Do not ignore extensions.firebug.filterSystemURLs pref when "Reset All Firebug Option" is executed.<commit_after>/* See license.txt for terms of usage */

define([
    "firebug/lib/events",
    "firebug/lib/trace"
],
function factoryOptions(Events, FBTrace) {

// ********************************************************************************************* //
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;

const nsIPrefBranch = Ci.nsIPrefBranch;
const nsIPrefBranch2 = Ci.nsIPrefBranch2;
const PrefService = Cc["@mozilla.org/preferences-service;1"];

const nsIPrefService = Ci.nsIPrefService;
const prefService = PrefService.getService(nsIPrefService);
const prefs = PrefService.getService(nsIPrefBranch2);

const prefNames =  // XXXjjb TODO distribute to modules
[
    // Global
    "defaultPanelName", "throttleMessages", "textSize", "showInfoTips",
    "commandEditor", "textWrapWidth", "framePosition", "showErrorCount",
    "activateSameOrigin", "allPagesActivation", "hiddenPanels",
    "panelTabMinWidth", "sourceLinkLabelWidth", "currentVersion",
    "useDefaultLocale", "toolbarCustomizationDone", "addonBarOpened",
    "showBreakNotification", "showStatusIcon", "stringCropLength",
    "showFirstRunPage",

    // Search
    "searchCaseSensitive", "searchGlobal", "searchUseRegularExpression",
    "netSearchHeaders", "netSearchParameters", "netSearchResponseBody",

    // Console
    "showJSErrors", "showJSWarnings", "showCSSErrors", "showXMLErrors",
    "showChromeErrors", "showChromeMessages", "showExternalErrors",
    "showXMLHttpRequests", "showNetworkErrors", "tabularLogMaxHeight",
    "consoleFilterTypes", "alwaysShowCommandLine",

    // HTML
    "showFullTextNodes", "showCommentNodes",
    "showTextNodesWithWhitespace", "showTextNodesWithEntities",
    "highlightMutations", "expandMutations", "scrollToMutations", "shadeBoxModel",
    "showQuickInfoBox", "displayedAttributeValueLimit", "multiHighlightLimit",

    // CSS
    "onlyShowAppliedStyles",
    "showUserAgentCSS",
    "expandShorthandProps",
    "computedStylesDisplay",
    "showMozillaSpecificStyles",
    "cssEditMode",

    // Script
    "decompileEvals", "replaceTabs", "maxScriptLineLength",

    // DOM
    "showUserProps", "showUserFuncs", "showDOMProps", "showDOMFuncs", "showDOMConstants",
    "ObjectShortIteratorMax", "showEnumerableProperties", "showOwnProperties",
    "showInlineEventHandlers",

    // Layout
    "showRulers",

    // Net
    "netFilterCategory", "netDisplayedResponseLimit",
    "netDisplayedPostBodyLimit", "netPhaseInterval", "sizePrecision",
    "netParamNameLimit", "netShowPaintEvents", "netShowBFCacheResponses",
    "netHtmlPreviewHeight",

    // JSON Preview
    "sortJsonPreview",

    // Stack
    "omitObjectPathStack",

    "showStackTrace", // Console
    "filterSystemURLs", // Stack
    "showAllSourceFiles", "breakOnErrors",  "trackThrowCatch" // Script
];

var optionUpdateMap = {};

// ********************************************************************************************* //

/**
 * Interface to preference storage.
 * Panels send commands to request option change.
 * Backend responds with events when the change is accepted.
 */
var Options =
/** @lends Options */
{
    getPrefDomain: function()
    {
        return this.prefDomain;
    },

    initialize: function(prefDomain)
    {
        this.prefDomain = prefDomain;

        if (FBTrace.DBG_INITIALIZE)
            FBTrace.sysout("options.initialize with prefDomain " + this.prefDomain);

        this.initializePrefs();
    },

    shutdown: function()
    {
        prefs.removeObserver(this.prefDomain, this, false);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Custom Listeners

    listeners: [],

    addListener: function(listener)
    {
        this.listeners.push(listener);
    },

    removeListener: function(listener)
    {
        for (var i=0; i<this.listeners.length; ++i)
            if (this.listeners[i] == listener)
                return this.listeners.splice(i, 1);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // nsIPrefObserver

    observe: function(subject, topic, data)
    {
        if (data.indexOf(Options.prefDomain) === -1)
            return;

        var name = data.substr(Options.prefDomain.length+1);  // +1 for .
        var value = this.get(name);

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.observe name = value: "+name+"= "+value+"\n");

        this.updatePref(name, value);
    },

    updatePref: function(name, value)
    {
        // Prevent infinite recursion due to pref observer
        if (optionUpdateMap.hasOwnProperty(name))
            return;

        try
        {
            optionUpdateMap[name] = 1;
            Firebug[name] = value;

            Events.dispatch(this.listeners, "updateOption", [name, value]);
        }
        catch (err)
        {
            if (FBTrace.DBG_OPTIONS || FBTrace.DBG_ERRORS)
                FBTrace.sysout("options.updatePref EXCEPTION:" + err, err);
        }
        finally
        {
            delete optionUpdateMap[name];
        }

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.updatePref EXIT: "+name+"="+value+"\n");
    },

    register: function(name, value)
    {
        var currentValue = this.getPref(this.prefDomain, name);

        if (FBTrace.DBG_INITIALIZE)
            FBTrace.sysout("registerPreference "+name+" -> "+value+" type "+typeof(value)+
                " with currentValue "+currentValue);

        if (currentValue === undefined)
        {
            // https://developer.mozilla.org/en/Code_snippets/Preferences
            // This is the reason why you should usually pass strings ending with a dot to
            // getBranch(), like prefs.getBranch("accessibility.").
            var defaultBranch = prefService.getDefaultBranch(this.prefDomain+"."); //

            var type = this.getPreferenceTypeByExample(typeof(value));
            if (this.setPreference(name, value, type, defaultBranch))
                return true;
        }

        return false;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Options
    // TODO support per context options eg break on error

    initializePrefs: function()
    {
        for (var i = 0; i < prefNames.length; ++i)
            Firebug[prefNames[i]] = this.getPref(this.prefDomain, prefNames[i]);

        prefs.addObserver(this.prefDomain, this, false);

        var basePrefNames = prefNames.length;

        for (var i = basePrefNames; i < prefNames.length; ++i)
            Firebug[prefNames[i]] = this.getPref(this.prefDomain, prefNames[i]);

        if (FBTrace.DBG_OPTIONS)
        {
             for (var i = 0; i < prefNames.length; ++i)
             {
                FBTrace.sysout("options.initialize option "+this.prefDomain+"."+prefNames[i]+"="+
                    Firebug[prefNames[i]]+"\n");
             }
        }
    },

    togglePref: function(name)
    {
        this.setPref(Options.prefDomain, name, !Firebug[name]);
    },

    get: function(name)
    {
        return Options.getPref(this.prefDomain, name);
    },

    getPref: function(prefDomain, name)
    {
        var prefName = prefDomain + "." + name;

        var type = prefs.getPrefType(prefName);

        var value;
        if (type == nsIPrefBranch.PREF_STRING)
            value = prefs.getCharPref(prefName);
        else if (type == nsIPrefBranch.PREF_INT)
            value = prefs.getIntPref(prefName);
        else if (type == nsIPrefBranch.PREF_BOOL)
            value = prefs.getBoolPref(prefName);

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.getPref "+prefName+" has type "+
                this.getPreferenceTypeName(type)+" and value "+value);

        return value;
    },

    set: function(name, value)
    {
        Options.setPref(Options.prefDomain, name, value);
    },

    /**
     * Set a preference value.
     *
     * @param prefDomain, e.g. "extensions.firebug"
     * @param name Name of the preference (the part after prfDomain without dot)
     * @param value New value for the preference.
     * @param prefType optional pref type useful when adding a new preference.
     */
    setPref: function(prefDomain, name, value, prefType)
    {
        var prefName = prefDomain + "." + name;

        var type = this.getPreferenceTypeByExample((prefType ? prefType : typeof(value)));
        if (!this.setPreference(prefName, value, type, prefs))
            return;

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.setPref type="+type+" name="+prefName+" value="+value);
    },

    setPreference: function(prefName, value, type, prefBranch)
    {
        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("setPreference "+prefName, {prefName: prefName, value: value});

        if (type == nsIPrefBranch.PREF_STRING)
            prefBranch.setCharPref(prefName, value);
        else if (type == nsIPrefBranch.PREF_INT)
            prefBranch.setIntPref(prefName, value);
        else if (type == nsIPrefBranch.PREF_BOOL)
            prefBranch.setBoolPref(prefName, value);
        else if (type == nsIPrefBranch.PREF_INVALID)
        {
            FBTrace.sysout("options.setPref FAILS: Invalid preference "+prefName+" with type "+
                type+", check that it is listed in defaults/prefs.js");

            return false;
        }

        return true;
    },

    getPreferenceTypeByExample: function(prefType)
    {
        if (prefType)
        {
            if (prefType === typeof("s"))
                var type = nsIPrefBranch.PREF_STRING;
            else if (prefType === typeof(1))
                var type = nsIPrefBranch.PREF_INT;
            else if (prefType === typeof (true))
                var type = nsIPrefBranch.PREF_BOOL;
            else
                var type = nsIPrefBranch.PREF_INVALID;
        }
        else
        {
            var type = prefs.getPrefType(prefName);
        }

        return type;
    },

    getPreferenceTypeName: function(prefType)
    {
        if (prefType == Ci.nsIPrefBranch.PREF_STRING)
            return "string";
        else if (prefType == Ci.nsIPrefBranch.PREF_INT)
            return "int";
        else if (prefType == Ci.nsIPrefBranch.PREF_BOOL)
            return "boolean";
    },

    clearPref: function(prefDomain, name)
    {
        var prefName = prefDomain + "." + name;
        if (prefs.prefHasUserValue(prefName))
            prefs.clearUserPref(prefName);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Firebug UI text zoom

    changeTextSize: function(amt)
    {
        var textSize = Options.get("textSize");
        var newTextSize = textSize + amt;
        if ((newTextSize < 0 && Math.abs(newTextSize) < this.negativeZoomFactors.length) ||
            (newTextSize >= 0 && textSize+amt < this.positiveZoomFactors.length))
        {
            this.setTextSize(textSize+amt);
        }
    },

    setTextSize: function(value)
    {
        var setValue = value;
        if (value >= this.positiveZoomFactors.length)
            setValue = this.positiveZoomFactors[this.positiveZoomFactors.length-1];
        else if (value < 0 && Math.abs(value) >= this.negativeZoomFactors.length)
            setValue = this.negativeZoomFactors[this.negativeZoomFactors.length-1];
        this.set("textSize", setValue);
    },

    positiveZoomFactors: [1, 1.1, 1.2, 1.3, 1.5, 2, 3],
    negativeZoomFactors: [1, 0.95, 0.8, 0.7, 0.5],

    getZoomByTextSize: function(value)
    {
        var zoom = value >= 0 ? this.positiveZoomFactors[value] :
            this.negativeZoomFactors[Math.abs(value)];

        return zoom;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

    /**
     * Resets all Firebug options to default state. Note that every option
     * starting with "extensions.firebug" is considered as a Firebug option.
     *
     * Options starting with DBG_ are intended for Firebug Tracing Console (FBTrace)
     * and ignored (their state is not changed).
     */
    resetAllOptions: function()
    {
        var preferences = prefs.getChildList("extensions.firebug", {});
        for (var i = 0; i < preferences.length; i++)
        {
            if (preferences[i].indexOf("DBG_") == -1)
            {
                if (FBTrace.DBG_OPTIONS)
                    FBTrace.sysout("Clearing option: " + i + ") " + preferences[i]);

                if (prefs.prefHasUserValue(preferences[i]))  // avoid exception
                    prefs.clearUserPref(preferences[i]);
            }
            else
            {
                if (FBTrace.DBG_OPTIONS)
                    FBTrace.sysout("Skipped clearing option: " + i + ") " + preferences[i]);
            }
        }
    },
};

// ********************************************************************************************* //
// Registration

return Options;

// ********************************************************************************************* //
});
<|endoftext|>


<commit_before>/**
 * Screencode™
 *
 * @author Nick Kaye <nick.c.kaye@gmail.com>
 * @laboratory Outright Mental Inc.
 * @code https://github.com/outrightmental/screencode
 *
 * Copyright (c) 2014 Outright Mental Inc.
 * Licensed under the MIT license.
 */

var cli = require('cli');
require('colors');

module.exports = {

  /**
   * Show UI
   */
  show: {

    /**
     * Title Banner
     */
    banner: function () {
      cli.output('\n' + 'Screencode'.bold + ' by Outright Mental Inc.'.blue + '\n\n');
    },

    /**
     * Loading Progress
     * @param total seconds
     * @param done
     */
    loading: function(total, done) {
      var i = 0, interval = setInterval(function () {
        cli.progress(++i / 100);
        if (i >= 100) {
          clearInterval(interval);
          done();
        }
      }, total * 10);
    },

    /**
     * All done!
     */
    done: function() {
      cli.output('\n' + 'Screencode'.bold + ' ' + 'OK'.green.bold + '.' + '\n\n');
    }

  }

};<commit_msg>Fun banner.<commit_after>/**
 * Screencode™
 *
 * @author Nick Kaye <nick.c.kaye@gmail.com>
 * @laboratory Outright Mental Inc.
 * @code https://github.com/outrightmental/screencode
 *
 * Copyright (c) 2014 Outright Mental Inc.
 * Licensed under the MIT license.
 */

var cli = require('cli');
require('colors');

module.exports = {

  /**
   * Show UI
   */
  show: {

    /**
     * Title Banner
     */
    banner: function () {
      cli.output('\n');
      cli.output('                                     _       \n'.red.bold);
      cli.output('   ___ ___ ___ ___ ___ ___ ___ ___ _| |___   \n'.yellow.bold);
      cli.output('  |_ -|  _|  _| -_| -_|   |  _| . | . | -_|  \n'.green.bold);
      cli.output('  |___|___|_| |___|___|_|_|___|___|___|___|  \n'.cyan.bold);
      cli.output('\n');
      cli.output('          by Outright Mental Inc.'.blue + '\n\n');
    },

    /**
     * Loading Progress
     * @param total seconds
     * @param done
     */
    loading: function(total, done) {
      var i = 0, interval = setInterval(function () {
        cli.progress(++i / 100);
        if (i >= 100) {
          clearInterval(interval);
          done();
        }
      }, total * 10);
    },

    /**
     * All done!
     */
    done: function() {
      cli.output('\n' + 'Screencode'.bold + ' ' + 'OK'.green.bold + '.' + '\n\n');
    }

  }

};<|endoftext|>


<commit_before>'use strict';

var storeDependencies = require('./lib/storeDependencies'),
  getModule = require('./lib/getModule'),
  start = require('./lib/start'),
  storeNgAppAndView = require('./lib/storeNgAppAndView'),
  storeUsedModules = require('./lib/storeUsedModules'),
  hasNameSpace = require('./lib/hasNameSpace'),
  modData = require('./lib/moduleData');

var doc = Array.prototype.slice.call(document.getElementsByTagName('*')),
  originalAngularModule = angular.module,
  modules = {};

storeNgAppAndView(doc);

angular.module = function(name, requiresOriginal) {
  var module = originalAngularModule.apply(this, arguments),
      name = module.name;

  module.requiresOriginal = requiresOriginal;
  modules[name] = module;
  hasNameSpace(name);
  var modToCheck = getModule(name, true);

  if(modToCheck && modToCheck.requiresOriginal !== module.requiresOriginal) {
    if(!modData.createdMulti[name]) {
      modData.createdMulti[name] = [getModule(name,true)];
    }
    modData.createdMulti[name].push(module);
  }
  modData.createdModules[name] = module;
  return module;
};

angular.module('ngHintModules', []).config(function() {
  var ngAppMod = modules[modData.ngAppMod];
  storeUsedModules(ngAppMod, modules);
  start();
});
<commit_msg>style(hintModules): fix whitespace<commit_after>'use strict';

var storeDependencies = require('./lib/storeDependencies'),
    getModule = require('./lib/getModule'),
    start = require('./lib/start'),
    storeNgAppAndView = require('./lib/storeNgAppAndView'),
    storeUsedModules = require('./lib/storeUsedModules'),
    hasNameSpace = require('./lib/hasNameSpace'),
    modData = require('./lib/moduleData');

var doc = Array.prototype.slice.call(document.getElementsByTagName('*')),
  originalAngularModule = angular.module,
  modules = {};

storeNgAppAndView(doc);

angular.module = function(name, requiresOriginal) {
  var module = originalAngularModule.apply(this, arguments),
      name = module.name;

  module.requiresOriginal = requiresOriginal;
  modules[name] = module;
  hasNameSpace(name);
  var modToCheck = getModule(name, true);

  if(modToCheck && modToCheck.requiresOriginal !== module.requiresOriginal) {
    if(!modData.createdMulti[name]) {
      modData.createdMulti[name] = [getModule(name,true)];
    }
    modData.createdMulti[name].push(module);
  }
  modData.createdModules[name] = module;
  return module;
};

angular.module('ngHintModules', []).config(function() {
  var ngAppMod = modules[modData.ngAppMod];
  storeUsedModules(ngAppMod, modules);
  start();
});
<|endoftext|>


<commit_before>'use strict';
var Transaction;
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var _ = require('underscore');
var async = require('async');

var constants = require('../constants');
var WalletAddress = mongoose.model('WalletAddress');

var Input = new Schema({
  utxo: String,
  vout: Number,
  address: String,
  amount: Number,
  wallets: {type: [Schema.Types.ObjectId]}
});

var Output = new Schema({
  address: String,
  amount: Number,
  vout: Number,
  wallets: {type: [Schema.Types.ObjectId]},
  spent: Boolean
});

var TransactionSchema = new Schema({
  txid: String,
  mainChain: Boolean,
  chain: String,
  blockHeight: Number,
  blockHash: String,
  blockTime: Date,
  blockTimeNormalized: Date,
  inputs: [Input],
  outputs: [Output],
  coinbase: Boolean,
  fee: Number,
  inputsProcessed: Boolean,
  wallets: {type: [Schema.Types.ObjectId]}
});

TransactionSchema.index({txid: 1}, {unique: true});
TransactionSchema.index({blockHeight: 1, wallets: 1});
TransactionSchema.index({blockHash: 1});
TransactionSchema.index({blockTime: 1});
TransactionSchema.index({blockTimeNormalized: 1, wallets: 1});

TransactionSchema.index({'outputs.address': 1});
TransactionSchema.index({'inputs.address': 1});
TransactionSchema.index({'wallets': 1}, {sparse: true});
TransactionSchema.index({'inputs.wallets': 1}, {sparse: true});
TransactionSchema.index({'outputs.wallets': 1}, {sparse: true});

TransactionSchema.statics.syncTransactionAndOutputs = function(data, callback) {
  var transaction = data.transaction;
  Transaction.findOne({txid: transaction.rhash()}).lean().exec(function(err, hasTx) {
    if(err) {
      return callback(err);
    }
    if(hasTx) {
      if (!hasTx.mainChain){
        return Transaction.update({txid: transaction.rhash()},
        {$set: {
          mainChain: true,
          blockHash: data.blockHash,
          blockHeight: data.blockHeight,
          blockTime: new Date(data.blockTime),
          blockTimeNormalized: new Date(data.blockTimeNormalized)
        }}, callback);
      }
      return callback();
    }

    var newTx = new Transaction();
    newTx.blockHeight = data.blockHeight;
    newTx.blockHash = data.blockHash;
    newTx.blockTime = new Date(data.blockTime);
    newTx.blockTimeNormalized = new Date(data.blockTimeNormalized);
    newTx.txid = transaction.rhash();

    async.eachOfLimit(transaction.outputs, constants.maxPoolSize, function(output, index, outputCb) {
      var address = output.getAddress();
      if(address){
        address = address.toString('main');
      }
      mongoose.model('WalletAddress').find({address: address}).lean().exec(function(err, wallets) {
        if(err) {
          return outputCb(err);
        }

        _.each(wallets, function(wallet) {
          newTx.wallets.addToSet(wallet.wallet);
        });

        newTx.outputs.push({
          vout: index,
          amount: parseFloat((output.value * 1e-8).toFixed(8)),
          address: address,
          wallets: _.pluck(wallets, 'wallet'),
          spent: false
        });
        outputCb();
      });
    }, function(err) {
      if(err) {
        return callback(err);
      }
      // Coinbase
      if(transaction.isCoinbase()) {
        newTx.coinbase = true;
        newTx.inputs.push({
          amount: _.reduce(newTx.outputs, function(total, output) {return total + output.amount;}, 0)
        });
        newTx.inputsProcessed = true;
      } else {
        transaction.inputs.forEach(function(input) {
          var prevTxId = input.prevout.rhash();
          newTx.inputs.push({
            utxo: prevTxId,
            vout: input.prevout.index
          });
        });
        newTx.inputsProcessed = false;
      }
      newTx.save({ordered: false}, callback);
    });
  });
};

TransactionSchema.statics.syncTransactionInputs = function(txid, callback) {
  Transaction.findOne({txid: txid}, function(err, transaction) {
    if(err) {
      return callback(err);
    }
    if(transaction.inputsProcessed) {
      return callback();
    }
    async.eachLimit(transaction.inputs, constants.maxPoolSize, function(input, inputCb) {
      Transaction.findOne({txid: input.utxo}).select('outputs').lean().exec(function(err, utxo) {
        if(err) {
          return inputCb(err);
        }
        if(!utxo) {
          return callback(new Error('Couldnt find utxo'));
        }
        utxo = _.findWhere(utxo.outputs, {vout: input.vout});
        input.address = utxo.address;
        input.amount = parseFloat(utxo.amount.toFixed(8));
        // TODO the find and update need to be consolidated here, while still being lean
        Transaction.update({txid: input.utxo, 'outputs.vout': input.vout},{
          $set: {'outputs.$.spent': true}
        }, function(err){
          if(err){
            return callback(err);
          }
          if(!input.address) {
            return inputCb();
          }
          WalletAddress.find({address: input.address}).lean().exec(function(err, wallets) {
            if(err) {
              return inputCb(err);
            }
            _.each(wallets, function(wallet) {
              transaction.wallets.addToSet(wallet.wallet);
            });
            input.wallets = _.pluck(wallets, 'wallet');
            inputCb();
          });
        });
      });
    }, function(err) {
      if(err) {
        return callback(err);
      }
      var totalInputs = _.reduce(transaction.inputs, function(total, input) {return total + input.amount;}, 0);
      var totalOutputs = _.reduce(transaction.outputs, function(total, output) {return total + output.amount;}, 0);
      transaction.fee = parseFloat((totalInputs - totalOutputs).toFixed(8));
      if(transaction.fee < 0) {
        return callback('Fee is negative, something is really wrong');
      }
      transaction.inputsProcessed = true;
      transaction.save({ordered: false}, callback);
    });
  });
};

var Transaction = module.exports = mongoose.model('Transaction', TransactionSchema);<commit_msg>consolidate findOne and update for spent<commit_after>'use strict';
var Transaction;
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var _ = require('underscore');
var async = require('async');

var constants = require('../constants');
var WalletAddress = mongoose.model('WalletAddress');

var Input = new Schema({
  utxo: String,
  vout: Number,
  address: String,
  amount: Number,
  wallets: {type: [Schema.Types.ObjectId]}
});

var Output = new Schema({
  address: String,
  amount: Number,
  vout: Number,
  wallets: {type: [Schema.Types.ObjectId]},
  spent: Boolean
});

var TransactionSchema = new Schema({
  txid: String,
  mainChain: Boolean,
  chain: String,
  blockHeight: Number,
  blockHash: String,
  blockTime: Date,
  blockTimeNormalized: Date,
  inputs: [Input],
  outputs: [Output],
  coinbase: Boolean,
  fee: Number,
  inputsProcessed: Boolean,
  wallets: {type: [Schema.Types.ObjectId]}
});

TransactionSchema.index({txid: 1}, {unique: true});
TransactionSchema.index({blockHeight: 1, wallets: 1});
TransactionSchema.index({blockHash: 1});
TransactionSchema.index({blockTime: 1});
TransactionSchema.index({blockTimeNormalized: 1, wallets: 1});

TransactionSchema.index({'outputs.address': 1});
TransactionSchema.index({'inputs.address': 1});
TransactionSchema.index({'wallets': 1}, {sparse: true});
TransactionSchema.index({'inputs.wallets': 1}, {sparse: true});
TransactionSchema.index({'outputs.wallets': 1}, {sparse: true});

TransactionSchema.statics.syncTransactionAndOutputs = function(data, callback) {
  var transaction = data.transaction;
  Transaction.findOne({txid: transaction.rhash()}).lean().exec(function(err, hasTx) {
    if(err) {
      return callback(err);
    }
    if(hasTx) {
      if (!hasTx.mainChain){
        return Transaction.update({txid: transaction.rhash()},
        {$set: {
          mainChain: true,
          blockHash: data.blockHash,
          blockHeight: data.blockHeight,
          blockTime: new Date(data.blockTime),
          blockTimeNormalized: new Date(data.blockTimeNormalized)
        }}, callback);
      }
      return callback();
    }

    var newTx = new Transaction();
    newTx.blockHeight = data.blockHeight;
    newTx.blockHash = data.blockHash;
    newTx.blockTime = new Date(data.blockTime);
    newTx.blockTimeNormalized = new Date(data.blockTimeNormalized);
    newTx.txid = transaction.rhash();

    async.eachOfLimit(transaction.outputs, constants.maxPoolSize, function(output, index, outputCb) {
      var address = output.getAddress();
      if(address){
        address = address.toString('main');
      }
      mongoose.model('WalletAddress').find({address: address}).lean().exec(function(err, wallets) {
        if(err) {
          return outputCb(err);
        }

        _.each(wallets, function(wallet) {
          newTx.wallets.addToSet(wallet.wallet);
        });

        newTx.outputs.push({
          vout: index,
          amount: parseFloat((output.value * 1e-8).toFixed(8)),
          address: address,
          wallets: _.pluck(wallets, 'wallet'),
          spent: false
        });
        outputCb();
      });
    }, function(err) {
      if(err) {
        return callback(err);
      }
      // Coinbase
      if(transaction.isCoinbase()) {
        newTx.coinbase = true;
        newTx.inputs.push({
          amount: _.reduce(newTx.outputs, function(total, output) {return total + output.amount;}, 0)
        });
        newTx.inputsProcessed = true;
      } else {
        transaction.inputs.forEach(function(input) {
          var prevTxId = input.prevout.rhash();
          newTx.inputs.push({
            utxo: prevTxId,
            vout: input.prevout.index
          });
        });
        newTx.inputsProcessed = false;
      }
      newTx.save({ordered: false}, callback);
    });
  });
};

TransactionSchema.statics.syncTransactionInputs = function(txid, callback) {
  Transaction.findOne({txid: txid}, function(err, transaction) {
    if(err) {
      return callback(err);
    }
    if(transaction.inputsProcessed) {
      return callback();
    }
    async.eachLimit(transaction.inputs, constants.maxPoolSize, function(input, inputCb) {
      Transaction.findOneAndUpdate({txid: input.utxo, 'outputs.vout': input.vout},
        {$set: {'outputs.$.spent': true}},
        {new: true}
      ).select('outputs').lean().exec(function(err, utxo) {
        if(err) {
          return inputCb(err);
        }
        if(!utxo) {
          return callback(new Error('Couldnt find utxo'));
        }
        utxo = _.findWhere(utxo.outputs, {vout: input.vout});
        input.address = utxo.address;
        input.amount = parseFloat(utxo.amount.toFixed(8));
        if(!input.address) {
          return inputCb();
        }
        WalletAddress.find({address: input.address}).lean().exec(function(err, wallets) {
          if(err) {
            return inputCb(err);
          }
          _.each(wallets, function(wallet) {
            transaction.wallets.addToSet(wallet.wallet);
          });
          input.wallets = _.pluck(wallets, 'wallet');
          inputCb();
        });
      });
    }, function(err) {
      if(err) {
        return callback(err);
      }
      var totalInputs = _.reduce(transaction.inputs, function(total, input) {return total + input.amount;}, 0);
      var totalOutputs = _.reduce(transaction.outputs, function(total, output) {return total + output.amount;}, 0);
      transaction.fee = parseFloat((totalInputs - totalOutputs).toFixed(8));
      if(transaction.fee < 0) {
        return callback('Fee is negative, something is really wrong');
      }
      transaction.inputsProcessed = true;
      transaction.save({ordered: false}, callback);
    });
  });
};

var Transaction = module.exports = mongoose.model('Transaction', TransactionSchema);<|endoftext|>


<commit_before>d3binding.binding = function() {

    var that = d3binding.expandable(function(selection) {});
    that.isTransition = false;

    that.transition = function() {
        if (!that.isTransition) {
            var newThat = d3binding.expandable(that);
            for (key in that) {
                if (that.hasOwnProperty(key)) {
                    newThat[key] = that[key];
                }
            }
            newThat.isTransition = true;
            return newThat;
        }

        return that;
    };

    var common = function(that, name, value, funcname) {
        that.expand(function(selection) {
            selection[funcname](name, function(d) {
                var s = d3.select(this);
                var v = value;
                if (typeof v === "function") {
                    v = v(d);
                    if (v.prototype === sb.Observable) {
                        var o = v;
                        sb.binding(o, function() {
                            if (that.isTransition) {
                                if (name !== null) {
                                    (s.transition())[funcname](name, o());
                                } else {
                                    (s.transition())[funcname](o());
                                }
                            } else {
                                if (name !== null) {
                                    s[funcname](name, o());
                                } else {
                                    s[funcname](o());
                                }
                            }
                        }).bind();
                        v = o();
                    }
                }

                return v;
            });
        });

        return that;
    }

    that.attr = function(name, value) {
        return common(this, name, value, "attr");
    };

    that.style = function(name, value) {
        return common(this, name, value, "style");
    };

    that.classed = function(name, value) {
        return common(this, name, value, "classed");
    };

    that.text = function(value) {
        return common(this, null, value, "text");
    };

    that.html = function(value) {
        return common(this, null, value, "classed");
    };

    return that;
};
<commit_msg>hogeにしたー<commit_after>d3binding.binding = function() {

    var that = d3binding.expandable(function(selection) {});
    that.isTransition = false;

    that.transition = function() {
        if (!that.isTransition) {
            var newThat = d3binding.expandable(that);
            for (key in that) {
                if (that.hasOwnProperty(key)) {
                    newThat[key] = that[key];
                }
            }
            newThat.isTransition = true;
            return newThat;
        }

        return that;
    };

    var common = function(hoge, name, value, funcname) {
        hoge.expand(function(selection) {
            selection[funcname](name, function(d) {
                var s = d3.select(this);
                var v = value;
                if (typeof v === "function") {
                    v = v(d);
                    if (v.prototype === sb.Observable) {
                        var o = v;
                        sb.binding(o, function() {
                            if (hoge.isTransition) {
                                if (name !== null) {
                                    (s.transition())[funcname](name, o());
                                } else {
                                    (s.transition())[funcname](o());
                                }
                            } else {
                                if (name !== null) {
                                    s[funcname](name, o());
                                } else {
                                    s[funcname](o());
                                }
                            }
                        }).bind();
                        v = o();
                    }
                }

                return v;
            });
        });

        return that;
    }

    that.attr = function(name, value) {
        return common(this, name, value, "attr");
    };

    that.style = function(name, value) {
        return common(this, name, value, "style");
    };

    that.classed = function(name, value) {
        return common(this, name, value, "classed");
    };

    that.text = function(value) {
        return common(this, null, value, "text");
    };

    that.html = function(value) {
        return common(this, null, value, "classed");
    };

    return that;
};
<|endoftext|>


<commit_before>(function () {
  "use strict";

  function normalizePackageDependencies(pkg) {
    var deps = (pkg.ender && pkg.ender.dependencies) || pkg.enderDependencies || pkg.browserDependencies || pkg.dependencies || {}
      , depsArr = deps
      ;

    function depsArrayToMap(dep) {
      var depParts = dep.split('@')
        ;

      deps[depParts[0]] = depParts[1] || '>= 0.0.0';
    }

    if (Array.isArray(depsArr)) {
      deps = {};
      deps.forEach(depsArrayToMap);
    }

    depsArr = [];
    Object.keys(deps).forEach(function (key) {
      depsArr.push(key + '@' + deps[key]);
    });

    //return depsArr;
    return deps;
  }

  module.exports.normalizePackageDependencies = normalizePackageDependencies;
}());
<commit_msg>[ISSUE#2] fixed typo deps.forEach -> depsArr.forEach<commit_after>(function () {
  "use strict";

  function normalizePackageDependencies(pkg) {
    var deps = (pkg.ender && pkg.ender.dependencies) || pkg.enderDependencies || pkg.browserDependencies || pkg.dependencies || {}
      , depsArr = deps
      ;

    function depsArrayToMap(dep) {
      var depParts = dep.split('@')
        ;

      deps[depParts[0]] = depParts[1] || '>= 0.0.0';
    }

    if (Array.isArray(depsArr)) {
      deps = {};
      depsArr.forEach(depsArrayToMap);
    }

    depsArr = [];
    Object.keys(deps).forEach(function (key) {
      depsArr.push(key + '@' + deps[key]);
    });

    //return depsArr;
    return deps;
  }

  module.exports.normalizePackageDependencies = normalizePackageDependencies;
}());
<|endoftext|>