<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
const { console } = Cu.import("resource://gre/modules/Console.jsm", {});
const { NetUtil } = Cu.import("resource://gre/modules/NetUtil.jsm", {});
const { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
const ChromeRegistry = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(Ci.nsIXULChromeRegistry);

this.EXPORTED_SYMBOLS = ["Runtime"];

this.Runtime = {
  start(appFile) {
    registerChromePrefix(appFile.parent.path);

    const systemPrincipal = Cc["@mozilla.org/systemprincipal;1"].
                            createInstance(Ci.nsIPrincipal);

    const sandbox = new Cu.Sandbox(systemPrincipal, {
      wantComponents: true,
    });

    Services.scriptloader.loadSubScript(`chrome://app/content/${appFile.leafName}`, sandbox, 'UTF-8');
  },
};

function readFile(file) {
  let stream = NetUtil.newChannel({
    uri: file,
    loadUsingSystemPrincipal: true,
  }).open2();
  let count = stream.available();
  let data = NetUtil.readInputStreamToString(stream, count);
  stream.close();
  return data;
}

function registerChromePrefix(path) {
  let manifestText = `content app ${path}/`;

  const tempFile = Services.dirsvc.get("TmpD", Ci.nsIFile);
  tempFile.append("temp.manifest");
  tempFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);

  let fileStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
  fileStream.init(tempFile, 0x02 | 0x08 | 0x20, 0o664, 0); // write, create, truncate
  fileStream.write(manifestText, manifestText.length);
  fileStream.close();

  Components.manager.QueryInterface(Ci.nsIComponentRegistrar).autoRegister(tempFile);
  ChromeRegistry.checkForNewChrome();

  tempFile.remove(false);
}
<commit_msg>fix formatting; reduce file permissions<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
const { console } = Cu.import("resource://gre/modules/Console.jsm", {});
const { NetUtil } = Cu.import("resource://gre/modules/NetUtil.jsm", {});
const { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
const ChromeRegistry = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(Ci.nsIXULChromeRegistry);

this.EXPORTED_SYMBOLS = ["Runtime"];

this.Runtime = {
  start(appFile) {
    registerChromePrefix(appFile.parent.path);

    const systemPrincipal = Cc["@mozilla.org/systemprincipal;1"].createInstance(Ci.nsIPrincipal);

    const sandbox = new Cu.Sandbox(systemPrincipal, {
      wantComponents: true,
    });

    Services.scriptloader.loadSubScript(`chrome://app/content/${appFile.leafName}`, sandbox, 'UTF-8');
  },
};

function readFile(file) {
  let stream = NetUtil.newChannel({
    uri: file,
    loadUsingSystemPrincipal: true,
  }).open2();
  let count = stream.available();
  let data = NetUtil.readInputStreamToString(stream, count);
  stream.close();
  return data;
}

function registerChromePrefix(path) {
  let manifestText = `content app ${path}/`;

  const tempFile = Services.dirsvc.get("TmpD", Ci.nsIFile);
  tempFile.append("temp.manifest");
  tempFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);

  let fileStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
  fileStream.init(tempFile, 0x02 | 0x08 | 0x20, 0o600, 0); // write, create, truncate
  fileStream.write(manifestText, manifestText.length);
  fileStream.close();

  Components.manager.QueryInterface(Ci.nsIComponentRegistrar).autoRegister(tempFile);
  ChromeRegistry.checkForNewChrome();

  tempFile.remove(false);
}
<|endoftext|>


<commit_before>"use strict";

/**
 * Tries to load the given model from cache and updates the attributes.
 * Creates a new instance if there is no cache or if the cache has not this instance yet.
 * After that the instance is stored in the cache (if present).
 *
 * If the cached model has unaccepted changes the new data is discarded.
 *
 * @param {Object} ids
 * @param {Object|Model} modelData
 * @param ModelClass
 * @returns {Model}
 */
function createSingle(ids, modelData, ModelClass) {
    var cache = ModelClass.cache,
        setNewData = true,
        resourceUrl,
        model;

    if (modelData instanceof ModelClass) {
        // it's already an instance, so we do nothing
        return modelData;
    }

    if (cache) {
        resourceUrl = ModelClass.getResourceUrl(ids);
        model = cache.get(resourceUrl);
    }

    if (model) {
        // TODO What happens if data has changed? Emit a conflict or something similar?
        setNewData = model.hasChanged() === false;
    } else {
        model = new ModelClass(modelData.id);
    }

    if (setNewData) {
        model.setIds(ids);
        model.set(modelData);
        model.accept();
    }

    if (cache) {
        cache.set(resourceUrl, model);
    }

    return model;
}

/**
 * Calls createSingle for every modelData-object in the array. modelInstances in the
 * modelDataArray are just skipped.
 *
 * @param {Object} ids
 * @param {Array<Object|Model>} modelDataArray
 * @param {Class} ModelClass
 * @returns {Array<Model>}
 */
function createMultiple(ids, modelDataArray, ModelClass) {
    var instances = [],
        url = ModelClass.prototype.url,
        arrayElem,
        modelData,
        model;

    for (arrayElem in modelDataArray) {
        if (modelDataArray.hasOwnProperty(arrayElem)) {
            modelData = modelDataArray[arrayElem];

            if (modelData instanceof ModelClass) {
                // it's already an instance, so we do nothing
                instances.push(modelData);
                continue;
            }

            if (modelData.id === undefined) {
                throw new Error("(alamid) Cannot create new model: The new model data has no id.");
            }

            // we can re-use the ids-object since model.setIds() clones the object
            ids[url] = modelData.id;

            instances.push(createSingle(ids, modelData, ModelClass));
        }
    }

    return instances;
}

exports.multiple = createMultiple;
exports.single = createSingle;<commit_msg>Fixed wrong for-loop<commit_after>"use strict";

/**
 * Tries to load the given model from cache and updates the attributes.
 * Creates a new instance if there is no cache or if the cache has not this instance yet.
 * After that the instance is stored in the cache (if present).
 *
 * If the cached model has unaccepted changes the new data is discarded.
 *
 * @param {Object} ids
 * @param {Object|Model} modelData
 * @param ModelClass
 * @returns {Model}
 */
function createSingle(ids, modelData, ModelClass) {
    var cache = ModelClass.cache,
        setNewData = true,
        resourceUrl,
        model;

    if (modelData instanceof ModelClass) {
        // it's already an instance, so we do nothing
        return modelData;
    }

    if (cache) {
        resourceUrl = ModelClass.getResourceUrl(ids);
        model = cache.get(resourceUrl);
    }

    if (model) {
        // TODO What happens if data has changed? Emit a conflict or something similar?
        setNewData = model.hasChanged() === false;
    } else {
        model = new ModelClass(modelData.id);
    }

    if (setNewData) {
        model.setIds(ids);
        model.set(modelData);
        model.accept();
    }

    if (cache) {
        cache.set(resourceUrl, model);
    }

    return model;
}

/**
 * Calls createSingle for every raw model object in the array. The array can be mixed with instances of ModelClass,
 * which will just be ignored.
 *
 * @param {Object} ids parent ids of the model
 * @param {Array<Object|Model>} models an array containing raw model data or instances of the ModelClass
 * @param {Class} ModelClass
 * @returns {Array<Model>}
 */
function createMultiple(ids, models, ModelClass) {
    var instances = [],
        url = ModelClass.prototype.url,
        i,
        model;

    for (i = 0; i < models.length; i++) {
        model = models[i];

        if (model instanceof ModelClass) {
            // it's already an instance, so we do nothing
            instances.push(model);
            continue;
        }

        if (model.id === undefined) {
            throw new Error("(alamid) Cannot create new model: The new model data has no id.");
        }

        // we can re-use the ids-object since model.setIds() clones the object
        ids[url] = model.id;

        instances.push(createSingle(ids, model, ModelClass));
    }

    return instances;
}

exports.multiple = createMultiple;
exports.single = createSingle;<|endoftext|>


<commit_before>import classnames from 'classnames'
import reportError from '../lib/reportError'
import { niceAttrs } from './constants'

function addClassName(props, name) {
  return props.className ? `${props.className} ${name}` : name
}

function niceProps(props) {
  Object.keys(props).forEach(key => {
    if (niceAttrs[key]) {
      props[niceAttrs[key]] = props[key]
      delete props[key]
    }
  })
  return props
}

export default function elementProps(Motion, { name, whitelisted, key, index }, view, props) {
  const viewName = view.__motion ? view.__motion.name : view.name

  if (props) {
    props = niceProps(props)
  }

  if (props && props.className) {
    props.className = classnames(props.className)
  }

  props = props || {}

  if (!props.key && !props.nokey) {
    props.key = name + key
    if (index) props.key += index
  }

  if (props.onEnter) {
    let originalKeyDown = props.onKeyDown

    props.onKeyDown = function(e) {
      if (e.keyCode === 13) props.onEnter(e.target.value)
      originalKeyDown && originalKeyDown(e)
    }
  }

  if (props.yield) {
    props = Object.assign(
      props,
      view.props,
      // take parent style
      props.style && { style: props.style },
      // merge parent classname
      props.className && { className: classnames(props.className, view.props.className) }
    )
  }

  if (props.onClick) {
    const originalOnClick = props.onClick

    props.onClick = function(...args) {
      if (_Motion.isInspecting) return false
      return originalOnClick.call(this, ...args)
    }
  }

  // sync
  if (props.__motionOnChange) {
    let userOnChange = props.onChange
    let type = props.type
    let attr = (
      ((!type && name == 'input') || type == 'input' || type == 'text' || name == 'textarea'  || type == 'search')
        ? 'value'
        : type == 'checkbox' || type == 'radio'
          ? 'checked'
          : false
    )

    if (!attr) {
      reportError({ message: 'sync attribute not supported on this input type yet', fileName: `${viewName}, <${name}>` })
    }

    props.onChange = function(e) {
      if (userOnChange) userOnChange.call(this, e)
      props.__motionOnChange(e.target[attr])
    }

    if (typeof props.__motionValue != 'undefined') {
      props[attr] = props.__motionValue
    }
  }

  // if not external component
  if (typeof component != 'function') {
    props.__motion = {
      parentStyles: view.styles,
      parentStylesStatic: Motion.styleObjects[viewName],
      parentName: viewName,
      key,
      index,
      tagName: name
    }

    // only for tags
    if (name[0] == name[0].toLowerCase()) {
      props.className = addClassName(props, viewName.replace('.', '-'))
    }
  }

  // ensure styles for whitelisted
  if (whitelisted) {
    props.className = addClassName(props, name)
  }

  if (name == 'svg') {
    // for react 0.15
    props.class = props.className
    delete props.className
  }

  return props
}
<commit_msg>unnamed fallback for viewname<commit_after>import classnames from 'classnames'
import reportError from '../lib/reportError'
import { niceAttrs } from './constants'

function addClassName(props, name) {
  return props.className ? `${props.className} ${name}` : name
}

function niceProps(props) {
  Object.keys(props).forEach(key => {
    if (niceAttrs[key]) {
      props[niceAttrs[key]] = props[key]
      delete props[key]
    }
  })
  return props
}

export default function elementProps(Motion, { name, whitelisted, key, index }, view, props) {
  const viewName = view.__motion ? view.__motion.name : view.name || 'unnamed'

  if (props) {
    props = niceProps(props)
  }

  if (props && props.className) {
    props.className = classnames(props.className)
  }

  props = props || {}

  if (!props.key && !props.nokey) {
    props.key = name + key
    if (index) props.key += index
  }

  if (props.onEnter) {
    let originalKeyDown = props.onKeyDown

    props.onKeyDown = function(e) {
      if (e.keyCode === 13) props.onEnter(e.target.value)
      originalKeyDown && originalKeyDown(e)
    }
  }

  if (props.yield) {
    props = Object.assign(
      props,
      view.props,
      // take parent style
      props.style && { style: props.style },
      // merge parent classname
      props.className && { className: classnames(props.className, view.props.className) }
    )
  }

  if (props.onClick) {
    const originalOnClick = props.onClick

    props.onClick = function(...args) {
      if (_Motion.isInspecting) return false
      return originalOnClick.call(this, ...args)
    }
  }

  // sync
  if (props.__motionOnChange) {
    let userOnChange = props.onChange
    let type = props.type
    let attr = (
      ((!type && name == 'input') || type == 'input' || type == 'text' || name == 'textarea'  || type == 'search')
        ? 'value'
        : type == 'checkbox' || type == 'radio'
          ? 'checked'
          : false
    )

    if (!attr) {
      reportError({ message: 'sync attribute not supported on this input type yet', fileName: `${viewName}, <${name}>` })
    }

    props.onChange = function(e) {
      if (userOnChange) userOnChange.call(this, e)
      props.__motionOnChange(e.target[attr])
    }

    if (typeof props.__motionValue != 'undefined') {
      props[attr] = props.__motionValue
    }
  }

  // if not external component
  if (typeof component != 'function') {
    props.__motion = {
      parentStyles: view.styles,
      parentStylesStatic: Motion.styleObjects[viewName],
      parentName: viewName,
      key,
      index,
      tagName: name
    }

    // only for tags
    if (name[0] == name[0].toLowerCase()) {
      props.className = addClassName(props, viewName.replace('.', '-'))
    }
  }

  // ensure styles for whitelisted
  if (whitelisted) {
    props.className = addClassName(props, name)
  }

  if (name == 'svg') {
    // for react 0.15
    props.class = props.className
    delete props.className
  }

  return props
}
<|endoftext|>


<commit_before>global.fetch = () => Promise.resolve({})

global.localStorage = {
	_storage: {},
	getItem(key) {
		if (!this.hasItem(key)) {
			return null
		}
		return this._storage[key]
	},
	setItem(key, val) {
		this._storage[key] = String(val)
	},
	removeItem(key) {
		delete this._storage[key]
	},
	hasItem(key) {
		return key in this._storage
	},
	clear() {
		this._storage = {}
	},
}
<commit_msg>configure enzyme v3<commit_after>import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

Enzyme.configure({ adapter: new Adapter() })

global.fetch = () => Promise.resolve({})

global.localStorage = {
	_storage: {},
	getItem(key) {
		if (!this.hasItem(key)) {
			return null
		}
		return this._storage[key]
	},
	setItem(key, val) {
		this._storage[key] = String(val)
	},
	removeItem(key) {
		delete this._storage[key]
	},
	hasItem(key) {
		return key in this._storage
	},
	clear() {
		this._storage = {}
	},
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

const { program } = require("commander");
const chalk = require("chalk");
const prompts = require("prompts");
const path = require("path");
const { install, initGit } = require("./helpers/install");
const package = require("./package.json");
const copy = require("./helpers/copy");
const Listr = require("listr");

// Output path to create new portal app
let projectPath = "";

// Commander parameters to specify CLI behavior
program
  .name(package.name)
  .version(package.version)
  /**
   * TODO
   * Add Options
   * Add Example Options
   * Add templates
   */
  .arguments("[dir]")
  .usage(`${chalk.yellow("[dir]")}`)
  .description({
    dir: "Directory to be used on install Portal.js",
  })
  .action((name) => (projectPath = name))
  .allowUnknownOption()
  .parse(process.argv);

/**
 * Method to ask a custon name if was not passed as parameter
 * returns the value passed from terminal input
 */
async function promptPath() {
  return prompts({
    type: "text",
    name: "path",
    message: "Choose a name to your project",
    initial: "",
    validate: (name) => {
      //TODO Method to validate valid path name
      return true;
    },
  });
}

/**
 * Main method to start CLI and validate inputs
 */
async function run() {
  if (typeof projectPath === "string") {
    projectPath = projectPath.trim();
  }
  if (!projectPath) {
    const response = await promptPath();
    if (typeof response.path === "string") {
      projectPath = response.path.trim();
    }
  }
  if (!projectPath) {
    //TODO separate log methods
    console.log();
    console.log("Please choose a name to your project:");
    console.log();
    console.log("Example:");
    console.log(
      `${chalk.cyan(program.name())} ${chalk.yellow("ny-portal-app")}`
    );
    console.log();

    process.exit(1);
  }

  const root = path.join(__dirname + "/../portal");

  const parsedPath = path.resolve(projectPath);
  const project = path.basename(parsedPath);

  console.log();
  console.log(
    `Begin Instalation of new portal.js on ${chalk.cyan(projectPath)} folder`
  );
  console.log();
  //TODO Move this method to another one to keep more functional and split responsabilites
  const tasks = new Listr([
    {
      title: "Fetching Content",
      task: () => copy(root, project),
    },
    {
      title: "Updating Content",
      task: () => "",
    },
    {
      title: "Installing Dependencies",
      task: () => install(project, true),
    },
    {
      title: "Git Init",
      task: () => initGit(projectPath),
    },
  ]);
}

//Main CLI execution workflow
run()
  .then(`${chalk.greenBright("Project Installed Sucess")}`)
  .catch((error) => {
    if (error.command) {
      console.log(`${chalk.cyan("Error on Create App")}`);
    } else {
      console.log(
        `${chalk.red("Unexpected Erro. Please report it as a bug")}`
      );
      console.log(error);
    }
    console.log();
    process.exit(1);
  });
<commit_msg>[feat] [s]: run main install tasks<commit_after>#!/usr/bin/env node

const { program } = require("commander");
const chalk = require("chalk");
const prompts = require("prompts");
const path = require("path");
const { install, initGit } = require("./helpers/install");
const package = require("./package.json");
const copy = require("./helpers/copy");
const Listr = require("listr");

// Output path to create new portal app
let projectPath = "";

// Commander parameters to specify CLI behavior
program
  .name(package.name)
  .version(package.version)
  /**
   * TODO
   * Add Options
   * Add Example Options
   * Add templates
   */
  .arguments("[dir]")
  .usage(`${chalk.yellow("[dir]")}`)
  .description({
    dir: "Directory to be used on install Portal.js",
  })
  .action((name) => (projectPath = name))
  .allowUnknownOption()
  .parse(process.argv);

/**
 * Method to ask a custon name if was not passed as parameter
 * returns the value passed from terminal input
 */
async function promptPath() {
  return prompts({
    type: "text",
    name: "path",
    message: "Choose a name to your project",
    initial: "",
    validate: (name) => {
      //TODO Method to validate valid path name
      return true;
    },
  });
}

/**
 * Main method to start CLI and validate inputs
 */
async function run() {
  if (typeof projectPath === "string") {
    projectPath = projectPath.trim();
  }
  if (!projectPath) {
    const response = await promptPath();
    if (typeof response.path === "string") {
      projectPath = response.path.trim();
    }
  }
  if (!projectPath) {
    //TODO separate log methods
    console.log();
    console.log("Please choose a name to your project:");
    console.log();
    console.log("Example:");
    console.log(
      `${chalk.cyan(program.name())} ${chalk.yellow("ny-portal-app")}`
    );
    console.log();

    process.exit(1);
  }

  const root = path.join(__dirname + "/../portal");

  const parsedPath = path.resolve(projectPath);
  const project = path.basename(parsedPath);

  console.log();
  console.log(
    `Begin Instalation of new portal.js on ${chalk.cyan(projectPath)} folder`
  );
  console.log();
  //TODO Move this method to another one to keep more functional and split responsabilites
  const tasks = new Listr([
    {
      title: "Fetching Content",
      task: () => copy(root, project),
    },
    {
      title: "Updating Content",
      task: () => "",
    },
    {
      title: "Installing Dependencies",
      task: () => install(project, true),
    },
    {
      title: "Git Init",
      task: () => initGit(projectPath),
    },
  ]);

  tasks
    .run()
    .then(()=> {
      console.log()
      console.log(`${chalk.greenBright('Instalation Completed!')}`)
      console.log()
      console.log(`Run ${chalk.cyan('cd '+ projectPath)} and ${chalk.green('yarn dev')} or ${chalk.yellow('npm run dev')}`)
      console.log()
      console.log('Enjoy =)')
    })
}

//Main CLI execution workflow
run()
  .then(`${chalk.greenBright("Project Installed Sucess")}`)
  .catch((error) => {
    if (error.command) {
      console.log(`${chalk.cyan("Error on Create App")}`);
    } else {
      console.log(
        `${chalk.red("Unexpected Erro. Please report it as a bug")}`
      );
      console.log(error);
    }
    console.log();
    process.exit(1);
  });
<|endoftext|>


<commit_before>/**
  [Glimmer](https://github.com/tildeio/glimmer) is a templating engine used by Ember.js that is compatible with a subset of the [Handlebars](http://handlebarsjs.com/) syntax.

  ### Showing a property

  Templates manage the flow of an application's UI, and display state (through
  the DOM) to a user. For example, given a component with the property "name",
  that component's template can use the name in several ways:

  ```app/components/person.js
    export default Ember.Component.extend({
      name: 'Jill'
    });
  ```

  ```app/components/person.hbs
  {{name}}
  <div>{{name}}</div>
  <span data-name={{name}}></span>
  ```

  Any time the "name" property on the component changes, the DOM will be
  updated.

  Properties can be chained as well:

  ```handlebars
  {{aUserModel.name}}
  <div>{{listOfUsers.firstObject.name}}</div>
  ```

  ### Using Ember helpers

  When content is passed in mustaches `{{}}`, Ember will first try to find a helper
  or component with that name. For example, the `if` helper:

  ```handlebars
  {{if name "I have a name" "I have no name"}}
  <span data-has-name={{if name true}}></span>
  ```

  The returned value is placed where the `{{}}` is called. The above style is
  called "inline". A second style of helper usage is called "block". For example:

  ```handlebars
  {{#if name}}
  I have a name
  {{else}}
  I have no name
  {{/if}}
  ```

  The block form of helpers allows you to control how the UI is created based
  on the values of properties.
  A third form of helper is called "nested". For example here the concat
  helper will add " Doe" to a displayed name if the person has no last name:

  ```handlebars
  <span data-name={{concat firstName (
  if lastName (concat " " lastName) "Doe"
  )}}></span>
  ```

  Ember's built-in helpers are described under the [Ember.Templates.helpers](/api/classes/Ember.Templates.helpers.html)
  namespace. Documentation on creating custom helpers can be found under
  [Ember.Helper](/api/classes/Ember.Helper.html).

  ### Invoking a Component

  Ember components represent state to the UI of an application. Further
  reading on components can be found under [Ember.Component](/api/classes/Ember.Component.html).

  @module ember
  @submodule ember-glimmer
  @main ember-glimmer
  @public
 */

/**
  Use the `{{with}}` helper when you want to alias a property to a new name. This is helpful
  for semantic clarity as it allows you to retain default scope or to reference a property from another
  `{{with}}` block.

  If the aliased property is "falsey", for example: `false`, `undefined` `null`, `""`, `0`, `NaN` or
  an empty array, the block will not be rendered.

  ```handlebars
  {{! Will only render if user.posts contains items}}
  {{#with user.posts as |blogPosts|}}
    <div class="notice">
      There are {{blogPosts.length}} blog posts written by {{user.name}}.
    </div>
    {{#each blogPosts as |post|}}
      <li>{{post.title}}</li>
    {{/each}}
  {{/with}}
  ```

  Without the `as` operator, it would be impossible to reference `user.name` in the example above.

  NOTE: The alias should not reuse a name from the bound property path.

  For example: `{{#with foo.bar as |foo|}}` is not supported because it attempts to alias using
  the first part of the property path, `foo`. Instead, use `{{#with foo.bar as |baz|}}`.

  @method with
  @for Ember.Templates.helpers
  @param {Object} options
  @return {String} HTML string
  @public
 */

/**
  `{{yield}}` denotes an area of a template that will be rendered inside
  of another template.

  ### Use with Ember.Component

  When designing components `{{yield}}` is used to denote where, inside the component's
  template, an optional block passed to the component should render:

  ```application.hbs
  {{#labeled-textfield value=someProperty}}
    First name:
  {{/labeled-textfield}}
  ```

  ```components/labeled-textfield.hbs
  <label>
    {{yield}} {{input value=value}}
  </label>
  ```

  Result:

  ```html
  <label>
    First name: <input type="text" />
  </label>
  ```

  Additionally you can `yield` properties into the context for use by the consumer:

  ```application.hbs
  {{#labeled-textfield value=someProperty validator=(action 'firstNameValidator') as |validationError|}}
    {{#if validationError}}
      <p class="error">{{ValidationError}}</p>
    {{/if}}
    First name:
  {{/labeled-textfield}}
  ```

  ```components/labeled-textfield.hbs
  <label>
    {{yield validationError}} {{input value=value}}
  </label>
  ```

  Result:

  ```html
  <label>
    <p class="error">First Name must be at least 3 characters long.</p>
    First name: <input type="text" />
  </label>
  ```
  @method yield
  @for Ember.Templates.helpers
  @param {Hash} options
  @return {String} HTML string
  @public
 */

/**
  Execute the `debugger` statement in the current template's context.

  ```handlebars
  {{debugger}}
  ```

  When using the debugger helper you will have access to a `get` function. This
  function retrieves values available in the context of the template.
  For example, if you're wondering why a value `{{foo}}` isn't rendering as
  expected within a template, you could place a `{{debugger}}` statement and,
  when the `debugger;` breakpoint is hit, you can attempt to retrieve this value:

  ```
  > get('foo')
  ```

  `get` is also aware of keywords. So in this situation

  ```handlebars
  {{#each items as |item|}}
    {{debugger}}
  {{/each}}
  ```

  You'll be able to get values from the current item:

  ```
  > get('item.name')
  ```

  You can also access the context of the view to make sure it is the object that
  you expect:

  ```
  > context
  ```

  @method debugger
  @for Ember.Templates.helpers
  @public
 */

/**
  The `partial` helper renders another template without
  changing the template context:

  ```handlebars
  {{foo}}
  {{partial "nav"}}
  ```

  The above example template will render a template named
  "-nav", which has the same context as the parent template
  it's rendered into, so if the "-nav" template also referenced
  `{{foo}}`, it would print the same thing as the `{{foo}}`
  in the above example.

  If a "-nav" template isn't found, the `partial` helper will
  fall back to a template named "nav".

  ### Bound template names

  The parameter supplied to `partial` can also be a path
  to a property containing a template name, e.g.:

  ```handlebars
  {{partial someTemplateName}}
  ```

  The above example will look up the value of `someTemplateName`
  on the template context (e.g. a controller) and use that
  value as the name of the template to render. If the resolved
  value is falsy, nothing will be rendered. If `someTemplateName`
  changes, the partial will be re-rendered using the new template
  name.

  @method partial
  @for Ember.Templates.helpers
  @param {String} partialName The name of the template to render minus the leading underscore.
  @public
*/

export { INVOKE } from './helpers/action';
export { default as RootTemplate } from './templates/root';
export { default as template } from './template';
export { default as Checkbox } from './components/checkbox';
export { default as TextField } from './components/text_field';
export { default as TextArea } from './components/text_area';
export { default as LinkComponent } from './components/link-to';
export { default as Component } from './component';
export { default as Helper, helper } from './helper';
export { default as Environment } from './environment';
export {
  SafeString,
  escapeExpression,
  htmlSafe,
  isHTMLSafe,
  getSafeString as _getSafeString
} from './utils/string';
export {
  Renderer,
  InertRenderer,
  InteractiveRenderer,
  _resetRenderers
} from './renderer';
export {
  getTemplate,
  setTemplate,
  hasTemplate,
  getTemplates,
  setTemplates
} from './template_registry';
export { setupEngineRegistry, setupApplicationRegistry } from './setup-registry';
export { DOMChanges, NodeDOMTreeConstruction, DOMTreeConstruction } from './dom';
export { registerMacros as _registerMacros, experimentalMacros as _experimentalMacros } from './syntax';
export { default as AbstractComponentManager } from './component-managers/abstract';
<commit_msg>Remove outdated {{with}} documentation<commit_after>/**
  [Glimmer](https://github.com/tildeio/glimmer) is a templating engine used by Ember.js that is compatible with a subset of the [Handlebars](http://handlebarsjs.com/) syntax.

  ### Showing a property

  Templates manage the flow of an application's UI, and display state (through
  the DOM) to a user. For example, given a component with the property "name",
  that component's template can use the name in several ways:

  ```app/components/person.js
    export default Ember.Component.extend({
      name: 'Jill'
    });
  ```

  ```app/components/person.hbs
  {{name}}
  <div>{{name}}</div>
  <span data-name={{name}}></span>
  ```

  Any time the "name" property on the component changes, the DOM will be
  updated.

  Properties can be chained as well:

  ```handlebars
  {{aUserModel.name}}
  <div>{{listOfUsers.firstObject.name}}</div>
  ```

  ### Using Ember helpers

  When content is passed in mustaches `{{}}`, Ember will first try to find a helper
  or component with that name. For example, the `if` helper:

  ```handlebars
  {{if name "I have a name" "I have no name"}}
  <span data-has-name={{if name true}}></span>
  ```

  The returned value is placed where the `{{}}` is called. The above style is
  called "inline". A second style of helper usage is called "block". For example:

  ```handlebars
  {{#if name}}
  I have a name
  {{else}}
  I have no name
  {{/if}}
  ```

  The block form of helpers allows you to control how the UI is created based
  on the values of properties.
  A third form of helper is called "nested". For example here the concat
  helper will add " Doe" to a displayed name if the person has no last name:

  ```handlebars
  <span data-name={{concat firstName (
  if lastName (concat " " lastName) "Doe"
  )}}></span>
  ```

  Ember's built-in helpers are described under the [Ember.Templates.helpers](/api/classes/Ember.Templates.helpers.html)
  namespace. Documentation on creating custom helpers can be found under
  [Ember.Helper](/api/classes/Ember.Helper.html).

  ### Invoking a Component

  Ember components represent state to the UI of an application. Further
  reading on components can be found under [Ember.Component](/api/classes/Ember.Component.html).

  @module ember
  @submodule ember-glimmer
  @main ember-glimmer
  @public
 */

/**
  Use the `{{with}}` helper when you want to alias a property to a new name. This is helpful
  for semantic clarity as it allows you to retain default scope or to reference a property from another
  `{{with}}` block.

  If the aliased property is "falsey", for example: `false`, `undefined` `null`, `""`, `0`, `NaN` or
  an empty array, the block will not be rendered.

  ```handlebars
  {{! Will only render if user.posts contains items}}
  {{#with user.posts as |blogPosts|}}
    <div class="notice">
      There are {{blogPosts.length}} blog posts written by {{user.name}}.
    </div>
    {{#each blogPosts as |post|}}
      <li>{{post.title}}</li>
    {{/each}}
  {{/with}}
  ```

  NOTE: The alias should not reuse a name from the bound property path.

  For example: `{{#with foo.bar as |foo|}}` is not supported because it attempts to alias using
  the first part of the property path, `foo`. Instead, use `{{#with foo.bar as |baz|}}`.

  @method with
  @for Ember.Templates.helpers
  @param {Object} options
  @return {String} HTML string
  @public
 */

/**
  `{{yield}}` denotes an area of a template that will be rendered inside
  of another template.

  ### Use with Ember.Component

  When designing components `{{yield}}` is used to denote where, inside the component's
  template, an optional block passed to the component should render:

  ```application.hbs
  {{#labeled-textfield value=someProperty}}
    First name:
  {{/labeled-textfield}}
  ```

  ```components/labeled-textfield.hbs
  <label>
    {{yield}} {{input value=value}}
  </label>
  ```

  Result:

  ```html
  <label>
    First name: <input type="text" />
  </label>
  ```

  Additionally you can `yield` properties into the context for use by the consumer:

  ```application.hbs
  {{#labeled-textfield value=someProperty validator=(action 'firstNameValidator') as |validationError|}}
    {{#if validationError}}
      <p class="error">{{ValidationError}}</p>
    {{/if}}
    First name:
  {{/labeled-textfield}}
  ```

  ```components/labeled-textfield.hbs
  <label>
    {{yield validationError}} {{input value=value}}
  </label>
  ```

  Result:

  ```html
  <label>
    <p class="error">First Name must be at least 3 characters long.</p>
    First name: <input type="text" />
  </label>
  ```
  @method yield
  @for Ember.Templates.helpers
  @param {Hash} options
  @return {String} HTML string
  @public
 */

/**
  Execute the `debugger` statement in the current template's context.

  ```handlebars
  {{debugger}}
  ```

  When using the debugger helper you will have access to a `get` function. This
  function retrieves values available in the context of the template.
  For example, if you're wondering why a value `{{foo}}` isn't rendering as
  expected within a template, you could place a `{{debugger}}` statement and,
  when the `debugger;` breakpoint is hit, you can attempt to retrieve this value:

  ```
  > get('foo')
  ```

  `get` is also aware of keywords. So in this situation

  ```handlebars
  {{#each items as |item|}}
    {{debugger}}
  {{/each}}
  ```

  You'll be able to get values from the current item:

  ```
  > get('item.name')
  ```

  You can also access the context of the view to make sure it is the object that
  you expect:

  ```
  > context
  ```

  @method debugger
  @for Ember.Templates.helpers
  @public
 */

/**
  The `partial` helper renders another template without
  changing the template context:

  ```handlebars
  {{foo}}
  {{partial "nav"}}
  ```

  The above example template will render a template named
  "-nav", which has the same context as the parent template
  it's rendered into, so if the "-nav" template also referenced
  `{{foo}}`, it would print the same thing as the `{{foo}}`
  in the above example.

  If a "-nav" template isn't found, the `partial` helper will
  fall back to a template named "nav".

  ### Bound template names

  The parameter supplied to `partial` can also be a path
  to a property containing a template name, e.g.:

  ```handlebars
  {{partial someTemplateName}}
  ```

  The above example will look up the value of `someTemplateName`
  on the template context (e.g. a controller) and use that
  value as the name of the template to render. If the resolved
  value is falsy, nothing will be rendered. If `someTemplateName`
  changes, the partial will be re-rendered using the new template
  name.

  @method partial
  @for Ember.Templates.helpers
  @param {String} partialName The name of the template to render minus the leading underscore.
  @public
*/

export { INVOKE } from './helpers/action';
export { default as RootTemplate } from './templates/root';
export { default as template } from './template';
export { default as Checkbox } from './components/checkbox';
export { default as TextField } from './components/text_field';
export { default as TextArea } from './components/text_area';
export { default as LinkComponent } from './components/link-to';
export { default as Component } from './component';
export { default as Helper, helper } from './helper';
export { default as Environment } from './environment';
export {
  SafeString,
  escapeExpression,
  htmlSafe,
  isHTMLSafe,
  getSafeString as _getSafeString
} from './utils/string';
export {
  Renderer,
  InertRenderer,
  InteractiveRenderer,
  _resetRenderers
} from './renderer';
export {
  getTemplate,
  setTemplate,
  hasTemplate,
  getTemplates,
  setTemplates
} from './template_registry';
export { setupEngineRegistry, setupApplicationRegistry } from './setup-registry';
export { DOMChanges, NodeDOMTreeConstruction, DOMTreeConstruction } from './dom';
export { registerMacros as _registerMacros, experimentalMacros as _experimentalMacros } from './syntax';
export { default as AbstractComponentManager } from './component-managers/abstract';
<|endoftext|>


<commit_before>const isLoggedIn = require('./middlewares/isLoggedIn')
const Twitter = require('twitter')
const twitter = require('twitter')
const auth = require('../config/auth')
const then = require('express-then')
const promise = require('songbird')
const flash = require('connect-flash')
const request = require('request')
const networks = {
  twitter: {
    network: {
      icon: 'facebook',
      name: 'Facebook',
      class: 'btn-primary'
    }
  }
}

module.exports = (app) => {
  const twitterConfig = app.config.auth.twitter
  const passport = app.passport

  function getTwitterClient(req) {
    let twitterClient = new Twitter({
      consumer_key: twitterConfig.consumerKey,
      consumer_secret: twitterConfig.consumerSecret,
      access_token_key: req.user.twitter.token,
      access_token_secret: req.user.twitter.tokenSecret
    })
    return twitterClient
  }

  app.get('/', (req, res) => {
    res.render('index.ejs')
  })

  app.get('/logout', (req, res) => {
    req.logout()
    res.redirect('/')
  })

  app.get('/profile', isLoggedIn, (req, res) => {
    res.render('profile.ejs', {
      user: req.user,
      message: req.flash('error')
    })
  })

  app.get('/timeline', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    let tweets = await twitterClient.promise.get('statuses/home_timeline', { count: 20 })
    tweets = tweets.map(tweet => {
      return {
        id: tweet.id_str,
        image: tweet.user.profile_image_url,
        text: tweet.text,
        name: tweet.user.name,
        username: '@' + tweet.user.screen_name,
        liked: tweet.favorited,
        network: "Twitter",
        created_at: tweet.created_at,
        in_reply_to_status_id: tweet.in_reply_to_status_id
      }
    })
    res.render('timeline.ejs', {
      posts: tweets
    })
  }))

  app.get('/compose', isLoggedIn, (req, res) => {
    res.render('compose.ejs', {
      message: req.flash('error')
    })
  })

  app.post('/compose', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    const status = req.body.reply
    if (status && status.length > 140) {
      req.flash('error', 'Status is over 140 characters')
      res.redirect('/compose')
    }
    else if (!status) {
      req.flash('error', 'Status cannot be empty')
      res.redirect('/compose')
    } else {
      await twitterClient.promise.post('statuses/update', { status }, (err, data) => {
        if (err)
          console.log(err)
        res.redirect('/timeline')
      })
    }
  }))

  app.post('/like/:id', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    const id = req.params.id
    await twitterClient.promise.post('favorites/create', { id }, (err, data) => {
      if (err)
        console.log(err)
      res.end()
    })
  }))

  app.post('/unlike/:id', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    const id = req.params.id
    await twitterClient.promise.post('favorites/destroy', { id }, () => {
      res.end()
    })
  }))

  app.get('/share/:id', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    const id = req.params.id
    const post = await twitterClient.promise.get('statuses/show', { id })
    res.render('share.ejs', {
      post: post
    })
  }))

  app.post('/share/:id', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    const id = req.params.id
    await twitterClient.promise.post('statuses/retweet', { id })
    res.redirect('/timeline')
  }))

  app.get('/reply/:id', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    const id = req.params.id
    const post = await twitterClient.promise.get('statuses/show', { id })
    const replies = await twitterClient.promise.get('search/tweets', { in_reply_to_status_id: id }, (err) => {
      if (err)
        console.log(err.message)
    })
    res.render('reply.ejs', {
      post: post,
      replies: replies
    })
  }))

  app.post('/reply/:id', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    let status = req.body.reply
    const in_reply_to_status_id = req.params.id
    if (status && status.length > 140) {
      req.flash('error', 'Reply is over 140 characters')
      res.redirect('back')
    } else if (!status) {
      req.flash('error', 'Reply cannot be empty')
      res.redirect('back')
    } else {
      status = status + " " + req.body.url
      await twitterClient.promise.post('statuses/update', { status: status, in_reply_to_status_id: in_reply_to_status_id }, (err, data) => {
        if (err)
          console.log(err)
        res.redirect('/timeline')
      })
    }
  }))

  app.get('/auth/twitter', passport.authenticate('twitter'))

  app.get('/auth/twitter/callback',
    passport.authenticate('twitter', {
      failureRedirect: '/',
      successRedirect: '/timeline'
    })
  )
}<commit_msg>fix error in reply<commit_after>const isLoggedIn = require('./middlewares/isLoggedIn')
const Twitter = require('twitter')
const twitter = require('twitter')
const auth = require('../config/auth')
const then = require('express-then')
const promise = require('songbird')
const flash = require('connect-flash')
const request = require('request')
const networks = {
  twitter: {
    network: {
      icon: 'facebook',
      name: 'Facebook',
      class: 'btn-primary'
    }
  }
}

module.exports = (app) => {
  const twitterConfig = app.config.auth.twitter
  const passport = app.passport

  function getTwitterClient(req) {
    let twitterClient = new Twitter({
      consumer_key: twitterConfig.consumerKey,
      consumer_secret: twitterConfig.consumerSecret,
      access_token_key: req.user.twitter.token,
      access_token_secret: req.user.twitter.tokenSecret
    })
    return twitterClient
  }

  app.get('/', (req, res) => {
    res.render('index.ejs')
  })

  app.get('/logout', (req, res) => {
    req.logout()
    res.redirect('/')
  })

  app.get('/profile', isLoggedIn, (req, res) => {
    res.render('profile.ejs', {
      user: req.user,
      message: req.flash('error')
    })
  })

  app.get('/timeline', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    let tweets = await twitterClient.promise.get('statuses/home_timeline', { count: 20 })
    tweets = tweets.map(tweet => {
      return {
        id: tweet.id_str,
        image: tweet.user.profile_image_url,
        text: tweet.text,
        name: tweet.user.name,
        username: '@' + tweet.user.screen_name,
        liked: tweet.favorited,
        network: "Twitter",
        created_at: tweet.created_at,
        in_reply_to_status_id: tweet.in_reply_to_status_id
      }
    })
    res.render('timeline.ejs', {
      posts: tweets
    })
  }))

  app.get('/compose', isLoggedIn, (req, res) => {
    res.render('compose.ejs', {
      message: req.flash('error')
    })
  })

  app.post('/compose', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    const status = req.body.reply
    if (status && status.length > 140) {
      req.flash('error', 'Status is over 140 characters')
      res.redirect('/compose')
    }
    else if (!status) {
      req.flash('error', 'Status cannot be empty')
      res.redirect('/compose')
    } else {
      await twitterClient.promise.post('statuses/update', { status }, (err, data) => {
        if (err)
          console.log(err)
        res.redirect('/timeline')
      })
    }
  }))

  app.post('/like/:id', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    const id = req.params.id
    await twitterClient.promise.post('favorites/create', { id }, (err, data) => {
      if (err)
        console.log(err)
      res.end()
    })
  }))

  app.post('/unlike/:id', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    const id = req.params.id
    await twitterClient.promise.post('favorites/destroy', { id }, () => {
      res.end()
    })
  }))

  app.get('/share/:id', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    const id = req.params.id
    const post = await twitterClient.promise.get('statuses/show', { id })
    res.render('share.ejs', {
      post: post
    })
  }))

  app.post('/share/:id', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    const id = req.params.id
    await twitterClient.promise.post('statuses/retweet', { id })
    res.redirect('/timeline')
  }))

  app.get('/reply/:id', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    const id = req.params.id
    const post = await twitterClient.promise.get('statuses/show', { id })
    const replies = twitterClient.promise.get('search/tweets', { in_reply_to_status_id: id }, (err) => {
      if (err)
        console.log(err)
    })
    res.render('reply.ejs', {
      post: post,
      replies: replies
    })
  }))

  app.post('/reply/:id', isLoggedIn, then(async (req, res) => {
    const twitterClient = getTwitterClient(req)
    let status = req.body.reply
    const in_reply_to_status_id = req.params.id
    if (status && status.length > 140) {
      req.flash('error', 'Reply is over 140 characters')
      res.redirect('back')
    } else if (!status) {
      req.flash('error', 'Reply cannot be empty')
      res.redirect('back')
    } else {
      status = status + " " + req.body.url
      await twitterClient.promise.post('statuses/update', { status: status, in_reply_to_status_id: in_reply_to_status_id }, (err, data) => {
        if (err)
          console.log(err)
        res.redirect('/timeline')
      })
    }
  }))

  app.get('/auth/twitter', passport.authenticate('twitter'))

  app.get('/auth/twitter/callback',
    passport.authenticate('twitter', {
      failureRedirect: '/',
      successRedirect: '/timeline'
    })
  )
}<|endoftext|>


<commit_before>/*jslint node: true, nomen: true, white: true, todo: true*/
/*!
 * Sitegear3
 * Copyright(c) 2014 Ben New, Sitegear.org
 * MIT Licensed
 */

(function (_, path, fs, mkdirp) {
	"use strict";

	module.exports = function (options) {
		var convertKey = function (key) {
				return key.replace(/^\//, '').replace(/\//g, '_') + options.extension;
			};

		// TODO Put these defaults into an external file and load them
		options = _.merge({ extension: '.json', encoding: 'utf8' }, options);
		return {
			set: function (type, key, value, callback) {
				var parentPath = path.join(options.root, type),
					filePath = path.join(parentPath, convertKey(key));
				mkdirp(parentPath, function (mkdirError) {
					if (mkdirError) {
						callback(mkdirError);
					} else {
						if (!_.isString(value)) {
							value = JSON.stringify(value, null, '\t');
						}
						fs.writeFile(filePath, value, { encoding: options.encoding }, function (writeFileError) {
							callback(writeFileError);
						});
					}
				});
			},

			get: function (type, key, callback) {
				var filePath = path.join(options.root, type, convertKey(key));
				console.log(filePath);
				fs.readFile(filePath, { encoding: options.encoding }, function (error, value) {
					if (_.isString(value)) {
						// TODO Make this correctly handle malformed JSON
						value = JSON.parse(value);
					}
					callback(error, value);
				});
			},

			remove: function (type, key, callback) {
				var filePath = path.join(options.root, type, convertKey(key));
				fs.unlink(filePath, function (error) {
					callback(error);
				});
			}
		};
	};
}(require('lodash'), require('path'), require('fs'), require('mkdirp')));
<commit_msg>Correctly handle malformed JSON.<commit_after>/*jslint node: true, nomen: true, white: true, todo: true*/
/*!
 * Sitegear3
 * Copyright(c) 2014 Ben New, Sitegear.org
 * MIT Licensed
 */

(function (_, path, fs, mkdirp) {
	"use strict";

	module.exports = function (options) {
		var convertKey = function (key) {
				return key.replace(/^\//, '').replace(/\//g, '_') + options.extension;
			};

		// TODO Put these defaults into an external file and load them
		options = _.merge({ extension: '.json', encoding: 'utf8' }, options);
		return {
			set: function (type, key, value, callback) {
				var parentPath = path.join(options.root, type),
					filePath = path.join(parentPath, convertKey(key));
				mkdirp(parentPath, function (mkdirError) {
					if (mkdirError) {
						callback(mkdirError);
					} else {
						if (!_.isString(value)) {
							value = JSON.stringify(value, null, '\t');
						}
						fs.writeFile(filePath, value, { encoding: options.encoding }, function (writeFileError) {
							callback(writeFileError);
						});
					}
				});
			},

			get: function (type, key, callback) {
				var filePath = path.join(options.root, type, convertKey(key));
				fs.readFile(filePath, { encoding: options.encoding }, function (error, value) {
					if (_.isString(value)) {
						try {
							value = JSON.parse(value);
						} catch (parseError) {
							callback(parseError);
						}
					}
					callback(error, value);
				});
			},

			remove: function (type, key, callback) {
				var filePath = path.join(options.root, type, convertKey(key));
				fs.unlink(filePath, function (error) {
					callback(error);
				});
			}
		};
	};
}(require('lodash'), require('path'), require('fs'), require('mkdirp')));
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.View.extend({
  tagName: 'g'
});<commit_msg>remove unused app/views/nf-plot.js<commit_after><|endoftext|>


<commit_before>// require sequelize
const Sequelize = require('sequelize')

// connect to database spotifyjukebox
let db = new Sequelize('spotifyjukebox', process.env.POSTGRES_USER, process.env.POSTGRES_PASSWORD, {
	host: 'localhost',
	dialect: 'postgres'
})

// create model for users
let User = db.define('user', {
	// say name has to be unique in this table for login purposes
	spotify_id: {
		type: Sequelize.STRING,
		allowNull: false
	},
	access_token: {
		type: Sequelize.STRING,
		allowNull: false
	},
	refresh_token: {
		type: Sequelize.STRING,
		allowNull: false
	}
})

db.sync()

// by requiring database.js the code runs one time, by sending User in an object you can access and create a user in routes
// for example: db.User.create
module.exports = {User:User}<commit_msg>set db sync to force true so it's emptied every time the server restarts, can be turned off when i delete users with logout/expired session<commit_after>// require sequelize
const Sequelize = require('sequelize')

// connect to database spotifyjukebox
let db = new Sequelize('spotifyjukebox', process.env.POSTGRES_USER, process.env.POSTGRES_PASSWORD, {
	host: 'localhost',
	dialect: 'postgres'
})

// create model for users
let User = db.define('user', {
	// say name has to be unique in this table for login purposes
	spotify_id: {
		type: Sequelize.STRING,
		allowNull: false
	},
	access_token: {
		type: Sequelize.STRING,
		allowNull: false
	},
	refresh_token: {
		type: Sequelize.STRING,
		allowNull: false
	}
})

// for when I'm not deleting users yet, can be set to sync when log out and expired session delete user
db.sync({force:true})

//db.sync()

// by requiring database.js the code runs one time, by sending User in an object you can access and create a user in routes
// for example: db.User.create
module.exports = {User:User}<|endoftext|>


<commit_before>'use babel';

import {CompositeDisposable, Emitter} from 'atom';
const electron = require('electron')

const GENERIC_DEVICE = 'GenericDevice'

export default class ToolBarTheraView {

  constructor (options) {

    this.element = document.createElement('select')
    this.element.classList.add('form-control-tools')
    this.element.id = options.id

    option1 = document.createElement('option')
    option1.setAttribute("value", GENERIC_DEVICE)
    option1.text = 'no device connected'
    option1.type = GENERIC_DEVICE
    this.element.add(option1);

    this.element.addEventListener("change", function () {
      alert(this.options[this.selectedIndex].innerHTML)
      selectedOption = this.options[this.selectedIndex]
      target = selectedOption.tag;
      atom.commands.dispatch(atom.views.getView(atom.workspace), "thera-debugger:debugger:main-device", target);
    });

    // init symbols-tree-view and weex-run
    atom.commands.dispatch(atom.views.getView(atom.workspace), 'atom-live-server:get-sims')
    atom.commands.dispatch(atom.views.getView(atom.workspace), 'symbols-tree-view:activate')

    this.subscriptions = new CompositeDisposable()

    this.subscriptions.add(
      atom.commands.add('atom-workspace', 'console.targets', (allDevices) => {
        this.flashDeviceList(allDevices.detail)
      })
    );
  }

  flashDeviceList(options){

    this.element.innerHTML = "";

    let optionDefault = document.createElement('option')
    // optionDefault.setAttribute('value', GENERIC_DEVICE)
    // optionDefault.text = 'Generic Device'
    // this.element.add(optionDefault)

    for (var i=0;i<options.length;i++){
      optiontemp = document.createElement('option');
      optiontemp.value = options[i].deviceId;
      optiontemp.tag = options[i];
      optiontemp.text = options[i].model + " - " + (options[i].deviceId.split('|')[1]) + " - " + options[i].weexVersion;

      this.element.add(optiontemp);
    }

    if(this.element.options.length == 0){
      option1 = document.createElement('option')
      option1.setAttribute("value", GENERIC_DEVICE)
      option1.text = 'no device connected'
      option1.type = GENERIC_DEVICE
      this.element.add(option1);
    } else {
      this.element.options[0].selected = true
      alert(this.element.options[this.element.selectedIndex].innerHTML)
      atom.commands.dispatch(atom.views.getView(atom.workspace), "thera-debugger:debugger:main-device", options[0]);
    }
  }

  destroy () {
    this.subscriptions.dispose();
    if (this.element.parentNode) {
      this.element.parentNode.removeChild(this.element);
    }
    this.element = null;
  }
}
<commit_msg>delete alert<commit_after>'use babel';

import {CompositeDisposable, Emitter} from 'atom';
const electron = require('electron')

const GENERIC_DEVICE = 'GenericDevice'

export default class ToolBarTheraView {

  constructor (options) {

    this.element = document.createElement('select')
    this.element.classList.add('form-control-tools')
    this.element.id = options.id

    option1 = document.createElement('option')
    option1.setAttribute("value", GENERIC_DEVICE)
    option1.text = 'no device connected'
    option1.type = GENERIC_DEVICE
    this.element.add(option1);

    this.element.addEventListener("change", function () {
      selectedOption = this.options[this.selectedIndex]
      target = selectedOption.tag;
      atom.commands.dispatch(atom.views.getView(atom.workspace), "thera-debugger:debugger:main-device", target);
    });

    // init symbols-tree-view and weex-run
    atom.commands.dispatch(atom.views.getView(atom.workspace), 'atom-live-server:get-sims')
    atom.commands.dispatch(atom.views.getView(atom.workspace), 'symbols-tree-view:activate')

    this.subscriptions = new CompositeDisposable()

    this.subscriptions.add(
      atom.commands.add('atom-workspace', 'console.targets', (allDevices) => {
        this.flashDeviceList(allDevices.detail)
      })
    );
  }

  flashDeviceList(options){

    this.element.innerHTML = "";

    let optionDefault = document.createElement('option')
    // optionDefault.setAttribute('value', GENERIC_DEVICE)
    // optionDefault.text = 'Generic Device'
    // this.element.add(optionDefault)

    for (var i=0;i<options.length;i++){
      optiontemp = document.createElement('option');
      optiontemp.value = options[i].deviceId;
      optiontemp.tag = options[i];
      optiontemp.text = options[i].model + " - " + (options[i].deviceId.split('|')[1]) + " - " + options[i].weexVersion;

      this.element.add(optiontemp);
    }

    if(this.element.options.length == 0){
      option1 = document.createElement('option')
      option1.setAttribute("value", GENERIC_DEVICE)
      option1.text = 'no device connected'
      option1.type = GENERIC_DEVICE
      this.element.add(option1);
    } else {
      this.element.options[0].selected = true
      atom.commands.dispatch(atom.views.getView(atom.workspace), "thera-debugger:debugger:main-device", options[0]);
    }
  }

  destroy () {
    this.subscriptions.dispose();
    if (this.element.parentNode) {
      this.element.parentNode.removeChild(this.element);
    }
    this.element = null;
  }
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var inherits = require('inherits');
var Input = require('./input');
var Output = require('../output');
var $ = require('../../util/preconditions');

var Script = require('../../script');
var Signature = require('../../crypto/signature');
var Sighash = require('../sighash');
var PublicKey = require('../../publickey');
var BufferUtil = require('../../util/buffer');
var TransactionSignature = require('../signature');

/**
 * @constructor
 */
function MultiSigInput(input, pubkeys, threshold, signatures) {
  Input.apply(this, arguments);
  var self = this;
  pubkeys = pubkeys || input.publicKeys;
  threshold = threshold || input.threshold;
  signatures = signatures || input.signatures;
  this.publicKeys = _.sortBy(pubkeys, function(publicKey) { return publicKey.toString('hex'); });
  $.checkState(Script.buildMultisigOut(this.publicKeys, threshold).equals(this.output.script),
    'Provided public keys don\'t match to the provided output script');
  this.publicKeyIndex = {};
  _.each(this.publicKeys, function(publicKey, index) {
    self.publicKeyIndex[publicKey.toString()] = index;
  });
  this.threshold = threshold;
  // Empty array of signatures
  this.signatures = signatures ? this._deserializeSignatures(signatures) : new Array(this.publicKeys.length);
}
inherits(MultiSigInput, Input);

MultiSigInput.prototype.toObject = function() {
  var obj = Input.prototype.toObject.apply(this, arguments);
  obj.threshold = this.threshold;
  obj.publicKeys = _.map(this.publicKeys, function(publicKey) { return publicKey.toString(); });
  obj.signatures = this._serializeSignatures();
  return obj;
};

MultiSigInput.prototype._deserializeSignatures = function(signatures) {
  return _.map(signatures, function(signature) {
    if (!signature) {
      return undefined;
    }
    return new TransactionSignature(signature);
  });
};

MultiSigInput.prototype._serializeSignatures = function() {
  return _.map(this.signatures, function(signature) {
    if (!signature) {
      return undefined;
    }
    return signature.toObject();
  });
};

MultiSigInput.prototype.getSignatures = function(transaction, privateKey, index, sigtype) {
  $.checkState(this.output instanceof Output);
  sigtype = sigtype || Signature.SIGHASH_ALL;

  var self = this;
  var results = [];
  _.each(this.publicKeys, function(publicKey) {
    if (publicKey.toString() === privateKey.publicKey.toString()) {
      results.push(new TransactionSignature({
        publicKey: privateKey.publicKey,
        prevTxId: self.prevTxId,
        outputIndex: self.outputIndex,
        inputIndex: index,
        signature: Sighash.sign(transaction, privateKey, sigtype, index, self.output.script),
        sigtype: sigtype
      }));
    }
  });

  return results;
};

MultiSigInput.prototype.addSignature = function(transaction, signature) {
  $.checkState(!this.isFullySigned(), 'All needed signatures have already been added');
  $.checkArgument(!_.isUndefined(this.publicKeyIndex[signature.publicKey.toString()]),
    'Signature has no matching public key');
  $.checkState(this.isValidSignature(transaction, signature));
  this.signatures[this.publicKeyIndex[signature.publicKey.toString()]] = signature;
  this._updateScript();
  return this;
};

MultiSigInput.prototype._updateScript = function() {
  this.setScript(Script.buildMultisigIn(
    this.publicKeys,
    this.threshold,
    this._createSignatures()
  ));
  return this;
};

MultiSigInput.prototype._createSignatures = function() {
  return _.map(
    _.filter(this.signatures, function(signature) { return !_.isUndefined(signature); }),
    function(signature) {
      return BufferUtil.concat([
        signature.signature.toDER(),
        BufferUtil.integerAsSingleByteBuffer(signature.sigtype)
      ]);
    }
  );
};

MultiSigInput.prototype.clearSignatures = function() {
  this.signatures = new Array(this.publicKeys.length);
  this._updateScript();
};

MultiSigInput.prototype.isFullySigned = function() {
  return this.countSignatures() === this.threshold;
};

MultiSigInput.prototype.countMissingSignatures = function() {
  return this.threshold - this.countSignatures();
};

MultiSigInput.prototype.countSignatures = function() {
  return _.reduce(this.signatures, function(sum, signature) {
    return sum + (!!signature);
  }, 0);
};

MultiSigInput.prototype.publicKeysWithoutSignature = function() {
  var self = this;
  return _.filter(this.publicKeys, function(publicKey) {
    return !(self.signatures[self.publicKeyIndex[publicKey.toString()]]);
  });
};

MultiSigInput.prototype.isValidSignature = function(transaction, signature) {
  // FIXME: Refactor signature so this is not necessary
  signature.signature.nhashtype = signature.sigtype;
  return Sighash.verify(
    transaction,
    signature.signature,
    signature.publicKey,
    signature.inputIndex,
    this.output.script
  );
};

MultiSigInput.OPCODES_SIZE = 7; // serialized size (<=3) + 0 .. N .. M OP_CHECKMULTISIG
MultiSigInput.SIGNATURE_SIZE = 74; // size (1) + DER (<=72) + sighash (1)
MultiSigInput.PUBKEY_SIZE = 34; // size (1) + DER (<=33)

MultiSigInput.prototype._estimateSize = function() {
  return MultiSigInput.OPCODES_SIZE +
    this.threshold * MultiSigInput.SIGNATURE_SIZE +
    this.publicKeys.length * MultiSigInput.PUBKEY_SIZE;
};

module.exports = MultiSigInput;
<commit_msg>add function to parse list of signatures buffers into proper list of TransactionSignature objects<commit_after>'use strict';

var _ = require('lodash');
var inherits = require('inherits');
var Transaction = require('../transaction');
var Input = require('./input');
var Output = require('../output');
var $ = require('../../util/preconditions');

var Script = require('../../script');
var Signature = require('../../crypto/signature');
var Sighash = require('../sighash');
var PublicKey = require('../../publickey');
var BufferUtil = require('../../util/buffer');
var TransactionSignature = require('../signature');

/**
 * @constructor
 */
function MultiSigInput(input, pubkeys, threshold, signatures) {
  Input.apply(this, arguments);
  var self = this;
  pubkeys = pubkeys || input.publicKeys;
  threshold = threshold || input.threshold;
  signatures = signatures || input.signatures;
  this.publicKeys = _.sortBy(pubkeys, function(publicKey) { return publicKey.toString('hex'); });
  $.checkState(Script.buildMultisigOut(this.publicKeys, threshold).equals(this.output.script),
    'Provided public keys don\'t match to the provided output script');
  this.publicKeyIndex = {};
  _.each(this.publicKeys, function(publicKey, index) {
    self.publicKeyIndex[publicKey.toString()] = index;
  });
  this.threshold = threshold;
  // Empty array of signatures
  this.signatures = signatures ? this._deserializeSignatures(signatures) : new Array(this.publicKeys.length);
}
inherits(MultiSigInput, Input);

MultiSigInput.prototype.toObject = function() {
  var obj = Input.prototype.toObject.apply(this, arguments);
  obj.threshold = this.threshold;
  obj.publicKeys = _.map(this.publicKeys, function(publicKey) { return publicKey.toString(); });
  obj.signatures = this._serializeSignatures();
  return obj;
};

MultiSigInput.prototype._deserializeSignatures = function(signatures) {
  return _.map(signatures, function(signature) {
    if (!signature) {
      return undefined;
    }
    return new TransactionSignature(signature);
  });
};

MultiSigInput.prototype._serializeSignatures = function() {
  return _.map(this.signatures, function(signature) {
    if (!signature) {
      return undefined;
    }
    return signature.toObject();
  });
};

MultiSigInput.prototype.getSignatures = function(transaction, privateKey, index, sigtype) {
  $.checkState(this.output instanceof Output);
  sigtype = sigtype || Signature.SIGHASH_ALL;

  var self = this;
  var results = [];
  _.each(this.publicKeys, function(publicKey) {
    if (publicKey.toString() === privateKey.publicKey.toString()) {
      results.push(new TransactionSignature({
        publicKey: privateKey.publicKey,
        prevTxId: self.prevTxId,
        outputIndex: self.outputIndex,
        inputIndex: index,
        signature: Sighash.sign(transaction, privateKey, sigtype, index, self.output.script),
        sigtype: sigtype
      }));
    }
  });

  return results;
};

MultiSigInput.prototype.addSignature = function(transaction, signature) {
  $.checkState(!this.isFullySigned(), 'All needed signatures have already been added');
  $.checkArgument(!_.isUndefined(this.publicKeyIndex[signature.publicKey.toString()]),
    'Signature has no matching public key');
  $.checkState(this.isValidSignature(transaction, signature));
  this.signatures[this.publicKeyIndex[signature.publicKey.toString()]] = signature;
  this._updateScript();
  return this;
};

MultiSigInput.prototype._updateScript = function() {
  this.setScript(Script.buildMultisigIn(
    this.publicKeys,
    this.threshold,
    this._createSignatures()
  ));
  return this;
};

MultiSigInput.prototype._createSignatures = function() {
  return _.map(
    _.filter(this.signatures, function(signature) { return !_.isUndefined(signature); }),
    function(signature) {
      return BufferUtil.concat([
        signature.signature.toDER(),
        BufferUtil.integerAsSingleByteBuffer(signature.sigtype)
      ]);
    }
  );
};

MultiSigInput.prototype.clearSignatures = function() {
  this.signatures = new Array(this.publicKeys.length);
  this._updateScript();
};

MultiSigInput.prototype.isFullySigned = function() {
  return this.countSignatures() === this.threshold;
};

MultiSigInput.prototype.countMissingSignatures = function() {
  return this.threshold - this.countSignatures();
};

MultiSigInput.prototype.countSignatures = function() {
  return _.reduce(this.signatures, function(sum, signature) {
    return sum + (!!signature);
  }, 0);
};

MultiSigInput.prototype.publicKeysWithoutSignature = function() {
  var self = this;
  return _.filter(this.publicKeys, function(publicKey) {
    return !(self.signatures[self.publicKeyIndex[publicKey.toString()]]);
  });
};

MultiSigInput.prototype.isValidSignature = function(transaction, signature) {
  // FIXME: Refactor signature so this is not necessary
  signature.signature.nhashtype = signature.sigtype;
  return Sighash.verify(
    transaction,
    signature.signature,
    signature.publicKey,
    signature.inputIndex,
    this.output.script
  );
};

/**
 *
 * @param {Buffer[]} signatures
 * @param {PublicKey[]} publicKeys
 * @param {Transaction} transaction
 * @param {Integer} inputIndex
 * @param {Input} input
 * @returns {TransactionSignature[]}
 */
MultiSigInput.normalizeSignatures = function(transaction, input, inputIndex, signatures, publicKeys) {
  return publicKeys.map(function (pubKey) {
    var signatureMatch = null;
    signatures = signatures.filter(function (signatureBuffer) {
      if (signatureMatch) {
        return true;
      }

      var signature = new TransactionSignature({
        signature: Signature.fromTxFormat(signatureBuffer),
        publicKey: pubKey,
        prevTxId: input.prevTxId,
        outputIndex: input.outputIndex,
        inputIndex: inputIndex,
        sigtype: Signature.SIGHASH_ALL
      });

      signature.signature.nhashtype = signature.sigtype;
      var isMatch = Sighash.verify(
          transaction,
          signature.signature,
          signature.publicKey,
          signature.inputIndex,
          input.output.script
      );

      if (isMatch) {
        signatureMatch = signature;
        return false;
      }

      return true;
    });

    return signatureMatch ? signatureMatch : null;
  });
};

MultiSigInput.OPCODES_SIZE = 7; // serialized size (<=3) + 0 .. N .. M OP_CHECKMULTISIG
MultiSigInput.SIGNATURE_SIZE = 74; // size (1) + DER (<=72) + sighash (1)
MultiSigInput.PUBKEY_SIZE = 34; // size (1) + DER (<=33)

MultiSigInput.prototype._estimateSize = function() {
  return MultiSigInput.OPCODES_SIZE +
    this.threshold * MultiSigInput.SIGNATURE_SIZE +
    this.publicKeys.length * MultiSigInput.PUBKEY_SIZE;
};

module.exports = MultiSigInput;
<|endoftext|>