<commit_before>import path from 'path';
import {CLIEngine, linter} from 'eslint';
import PackageJson from '../lib/package_json';

const project = PackageJson.load();
const baseConfig = linter.defaults();

const options = {
  ignorePath: path.resolve('.gitignore'),
  baseConfig: Object.assign({}, baseConfig, {
    parser: 'babel-eslint',
    plugins: [
      'babel'
    ],
    env: {
      es6: true,
      browser: true,
      worker: true,
      serviceworker: true,
      node: true,
      jasmine: project.dependsOn(/jasmine/)
    },
    rules: Object.assign({}, baseConfig.rules, {
      'babel/generator-star-spacing': [2, 'after'],
      'babel/new-cap': 2,
      'babel/object-curly-spacing': 2,
      'babel/object-shorthand': 2,

      // 'babel/arrow-parens': [2, 'as-needed'],

      'comma-dangle': 2,
      'no-cond-assign': 2,
      'no-console': 2,
      'no-constant-condition': 2,
      'no-control-regex': 2,
      'no-debugger': 2,
      'no-dupe-args': 2,
      'no-dupe-keys': 2,
      'no-duplicate-case': 2,
      'no-empty-character-class': 2,
      'no-empty': 2,
      'no-ex-assign': 2,
      'no-extra-boolean-cast': 2,
      'no-extra-parens': 2,
      'no-extra-semi': 2,
      'no-func-assign': 2,
      'no-inner-declarations': 2,
      'no-invalid-regexp': 2,
      'no-irregular-whitespace': 2,
      'no-negated-in-lhs': 2,
      'no-obj-calls': 2,
      'no-regex-spaces': 2,
      'no-sparse-arrays': 2,
      'no-unreachable': 2,
      'use-isnan': 2,
      'valid-jsdoc': 2,
      'valid-typeof': 2,
      'no-unexpected-multiline': 2,

      'accessor-pairs': 2,
      'block-scoped-var': 2,
      'complexity': [0, 11],
      'consistent-return': 2,
      'curly': 2,
      'default-case': 2,
      'dot-notation': 2,
      'dot-location': [2, 'property'],
      'eqeqeq': 2,
      'guard-for-in': 2,
      'no-alert': 2,
      'no-caller': 2,
      'no-div-regex': 0,
      'no-else-return': 2,
      'no-empty-label': 2,
      'no-eq-null': 2,
      'no-eval': 2,
      'no-extend-native': 2,
      'no-extra-bind': 2,
      'no-fallthrough': 2,
      'no-floating-decimal': 2,
      'no-implicit-coercion': 2,
      'no-implied-eval': 2,
      'no-invalid-this': 2,
      'no-iterator': 2,
      'no-labels': 2,
      'no-lone-blocks': 2,
      'no-loop-func': 2,
      'no-multi-spaces': [2, {exceptions: {Property: false}}],
      'no-multi-str': 2,
      'no-native-reassign': 2,
      'no-new-func': 2,
      'no-new-wrappers': 2,
      'no-new': 2,
      'no-octal-escape': 2,
      'no-octal': 2,
      'no-param-reassign': [2, {props: true}],
      'no-process-env': 2,
      'no-proto': 2,
      'no-redeclare': [2, {builtinGlobals: true}],
      'no-return-assign': 2,
      'no-script-url': 2,
      'no-self-compare': 2,
      'no-sequences': 2,
      'no-throw-literal': 2,
      'no-unused-expressions': 2,
      'no-useless-call': 2,
      'no-void': 2,
      'no-warning-comments': 2,
      'no-with': 2,
      'radix': 2,
      'vars-on-top': 2,
      'wrap-iife': 2,
      'yoda': 2,

      'strict': [2, 'never'],

      'init-declarations': 2,
      'no-catch-shadow': 0,
      'no-delete-var': 2,
      'no-label-var': 2,
      'no-shadow-restricted-names': 2,
      'no-shadow': 2,
      'no-undef-init': 2,
      'no-undef': 2,
      'no-undefined': 2,
      'no-unused-vars': 2,
      'no-use-before-define': 2,

      'callback-return': 2,
      'handle-callback-err': [2, '^(?:err|error)'],
      'no-mixed-requires': 2,
      'no-new-require': 2,
      'no-path-concat': 2,
      'no-process-exit': 2,
      'no-restricted-modules': 0,
      'no-sync': 2,

      'array-bracket-spacing': 2,
      'brace-style': 2,
      'camelcase': 2,
      'comma-spacing': 2,
      'comma-style': 2,
      'computed-property-spacing': 2,
      'consistent-this': [2, 'self'],
      'eol-last': 2,
      'func-names': 2,
      'func-style': [2, 'declaration'],
      'id-length': 2,
      'id-match': 0,
      'indent': [2, 2],
      'key-spacing': 2,
      'lines-around-comment': [2, {
        beforeBlockComment: true,
        beforeLineComment: true,
        allowBlockStart: true
      }],
      'linebreak-style': 2,
      'max-nested-callbacks': [2, 4],
      'new-cap': 0,
      'new-parens': 2,
      'newline-after-var': 2,
      'no-array-constructor': 2,
      'no-continue': 0,
      'no-inline-comments': 2,
      'no-lonely-if': 2,
      'no-mixed-spaces-and-tabs': 2,
      'no-multiple-empty-lines': [0, {max: 2}],
      'no-nested-ternary': 2,
      'no-new-object': 2,
      'no-spaced-func': 2,
      'no-ternary': 0,
      'no-trailing-spaces': 2,
      'no-underscore-dangle': 2,
      'no-unneeded-ternary': 2,
      'object-curly-spacing': 0,
      'one-var': 0,
      'operator-assignment': [2, 'always'],
      'operator-linebreak': 2,
      'padded-blocks': [2, 'never'],
      'quote-props': [2, 'consistent-as-needed'],
      'quotes': [2, 'single', 'avoid-escape'],
      'semi-spacing': 2,
      'semi': [2, 'always'],
      'sort-vars': 0,
      'space-after-keywords': 2,
      'space-before-blocks': 2,
      'space-before-function-paren': [2, 'never'],
      'space-in-parens': 2,
      'space-infix-ops': [2, {int32Hint: true}],
      'space-return-throw-case': 2,
      'space-unary-ops': 2,
      'spaced-comment': 2,
      'wrap-regex': 0,

      'arrow-parens': 0,
      'arrow-spacing': 2,
      'constructor-super': 2,
      'generator-star-spacing': 0,
      'no-class-assign': 2,
      'no-const-assign': 2,
      'no-this-before-super': 2,
      'no-var': 2,
      'object-shorthand': 0,
      'prefer-const': 2,
      'prefer-spread': 2,
      'prefer-reflect': 2,
      'require-yield': 2
    })
  })
};

const cli = new CLIEngine(options);
const formatter = cli.getFormatter();
const report = cli.executeOnFiles(['.']);

if (report.errorCount > 0) {
  process.stderr.write(formatter(report.results));

  /* eslint-disable no-process-exit, lines-around-comment */
  process.exit(1);
  /* eslint-enable no-process-exit, lines-around-comment */
}
<commit_msg>Cleaner way to disable eslint for a single line<commit_after>import path from 'path';
import {CLIEngine, linter} from 'eslint';
import PackageJson from '../lib/package_json';

const project = PackageJson.load();
const baseConfig = linter.defaults();

const options = {
  ignorePath: path.resolve('.gitignore'),
  baseConfig: Object.assign({}, baseConfig, {
    parser: 'babel-eslint',
    plugins: [
      'babel'
    ],
    env: {
      es6: true,
      browser: true,
      worker: true,
      serviceworker: true,
      node: true,
      jasmine: project.dependsOn(/jasmine/)
    },
    rules: Object.assign({}, baseConfig.rules, {
      'babel/generator-star-spacing': [2, 'after'],
      'babel/new-cap': 2,
      'babel/object-curly-spacing': 2,
      'babel/object-shorthand': 2,

      // 'babel/arrow-parens': [2, 'as-needed'],

      'comma-dangle': 2,
      'no-cond-assign': 2,
      'no-console': 2,
      'no-constant-condition': 2,
      'no-control-regex': 2,
      'no-debugger': 2,
      'no-dupe-args': 2,
      'no-dupe-keys': 2,
      'no-duplicate-case': 2,
      'no-empty-character-class': 2,
      'no-empty': 2,
      'no-ex-assign': 2,
      'no-extra-boolean-cast': 2,
      'no-extra-parens': 2,
      'no-extra-semi': 2,
      'no-func-assign': 2,
      'no-inner-declarations': 2,
      'no-invalid-regexp': 2,
      'no-irregular-whitespace': 2,
      'no-negated-in-lhs': 2,
      'no-obj-calls': 2,
      'no-regex-spaces': 2,
      'no-sparse-arrays': 2,
      'no-unreachable': 2,
      'use-isnan': 2,
      'valid-jsdoc': 2,
      'valid-typeof': 2,
      'no-unexpected-multiline': 2,

      'accessor-pairs': 2,
      'block-scoped-var': 2,
      'complexity': [0, 11],
      'consistent-return': 2,
      'curly': 2,
      'default-case': 2,
      'dot-notation': 2,
      'dot-location': [2, 'property'],
      'eqeqeq': 2,
      'guard-for-in': 2,
      'no-alert': 2,
      'no-caller': 2,
      'no-div-regex': 0,
      'no-else-return': 2,
      'no-empty-label': 2,
      'no-eq-null': 2,
      'no-eval': 2,
      'no-extend-native': 2,
      'no-extra-bind': 2,
      'no-fallthrough': 2,
      'no-floating-decimal': 2,
      'no-implicit-coercion': 2,
      'no-implied-eval': 2,
      'no-invalid-this': 2,
      'no-iterator': 2,
      'no-labels': 2,
      'no-lone-blocks': 2,
      'no-loop-func': 2,
      'no-multi-spaces': [2, {exceptions: {Property: false}}],
      'no-multi-str': 2,
      'no-native-reassign': 2,
      'no-new-func': 2,
      'no-new-wrappers': 2,
      'no-new': 2,
      'no-octal-escape': 2,
      'no-octal': 2,
      'no-param-reassign': [2, {props: true}],
      'no-process-env': 2,
      'no-proto': 2,
      'no-redeclare': [2, {builtinGlobals: true}],
      'no-return-assign': 2,
      'no-script-url': 2,
      'no-self-compare': 2,
      'no-sequences': 2,
      'no-throw-literal': 2,
      'no-unused-expressions': 2,
      'no-useless-call': 2,
      'no-void': 2,
      'no-warning-comments': 2,
      'no-with': 2,
      'radix': 2,
      'vars-on-top': 2,
      'wrap-iife': 2,
      'yoda': 2,

      'strict': [2, 'never'],

      'init-declarations': 2,
      'no-catch-shadow': 0,
      'no-delete-var': 2,
      'no-label-var': 2,
      'no-shadow-restricted-names': 2,
      'no-shadow': 2,
      'no-undef-init': 2,
      'no-undef': 2,
      'no-undefined': 2,
      'no-unused-vars': 2,
      'no-use-before-define': 2,

      'callback-return': 2,
      'handle-callback-err': [2, '^(?:err|error)'],
      'no-mixed-requires': 2,
      'no-new-require': 2,
      'no-path-concat': 2,
      'no-process-exit': 2,
      'no-restricted-modules': 0,
      'no-sync': 2,

      'array-bracket-spacing': 2,
      'brace-style': 2,
      'camelcase': 2,
      'comma-spacing': 2,
      'comma-style': 2,
      'computed-property-spacing': 2,
      'consistent-this': [2, 'self'],
      'eol-last': 2,
      'func-names': 2,
      'func-style': [2, 'declaration'],
      'id-length': 2,
      'id-match': 0,
      'indent': [2, 2],
      'key-spacing': 2,
      'lines-around-comment': [2, {
        beforeBlockComment: true,
        beforeLineComment: true,
        allowBlockStart: true
      }],
      'linebreak-style': 2,
      'max-nested-callbacks': [2, 4],
      'new-cap': 0,
      'new-parens': 2,
      'newline-after-var': 2,
      'no-array-constructor': 2,
      'no-continue': 0,
      'no-inline-comments': 2,
      'no-lonely-if': 2,
      'no-mixed-spaces-and-tabs': 2,
      'no-multiple-empty-lines': [0, {max: 2}],
      'no-nested-ternary': 2,
      'no-new-object': 2,
      'no-spaced-func': 2,
      'no-ternary': 0,
      'no-trailing-spaces': 2,
      'no-underscore-dangle': 2,
      'no-unneeded-ternary': 2,
      'object-curly-spacing': 0,
      'one-var': 0,
      'operator-assignment': [2, 'always'],
      'operator-linebreak': 2,
      'padded-blocks': [2, 'never'],
      'quote-props': [2, 'consistent-as-needed'],
      'quotes': [2, 'single', 'avoid-escape'],
      'semi-spacing': 2,
      'semi': [2, 'always'],
      'sort-vars': 0,
      'space-after-keywords': 2,
      'space-before-blocks': 2,
      'space-before-function-paren': [2, 'never'],
      'space-in-parens': 2,
      'space-infix-ops': [2, {int32Hint: true}],
      'space-return-throw-case': 2,
      'space-unary-ops': 2,
      'spaced-comment': 2,
      'wrap-regex': 0,

      'arrow-parens': 0,
      'arrow-spacing': 2,
      'constructor-super': 2,
      'generator-star-spacing': 0,
      'no-class-assign': 2,
      'no-const-assign': 2,
      'no-this-before-super': 2,
      'no-var': 2,
      'object-shorthand': 0,
      'prefer-const': 2,
      'prefer-spread': 2,
      'prefer-reflect': 2,
      'require-yield': 2
    })
  })
};

const cli = new CLIEngine(options);
const formatter = cli.getFormatter();
const report = cli.executeOnFiles(['.']);

if (report.errorCount > 0) {
  process.stderr.write(formatter(report.results));

  /* eslint-disable */
  process.exit(1);
  /* eslint-enable */
}
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')
const fsBlobStoreFactory = require('fs-blob-store')
const idGenerator = require('./id-generator')
const idValidator = require('./id-validator')
const Promise = require('bluebird')

// Internal Modules
const optionsParser = require('./options-parser')
const fsBlobItemList = require('./fs-blob-item-list')
const blobPathBuild = require('./blob-path-build')

exports.create = BlobStore

function BlobStore (opts) {
  if (!(this instanceof BlobStore)) {
    return new BlobStore(opts)
  }
  this.state = optionsParser(opts)
  this.state.newId = idGenerator(this.state.idType)
  this.state.validateId = idValidator(this.state.idType)
  this.currentBlobPath = false
  this.fsBlobStore = fsBlobStoreFactory(this.state.blobStoreRoot)
}

BlobStore.prototype.createWriteStream = function () {
  var self = this

  return Promise.resolve(this.currentBlobPath).then((blobPath) => {
    if (!blobPath) {
      return blobPathBuild(self.state)
    }
    return blobPath
  }).then((blobPath) => {
    var fullBlobPath = path.join(self.state.blobStoreRoot, blobPath)
    return fsBlobItemList(fullBlobPath, self.state.validateId, false).then(blobFileItems => {
      return blobFileItems.length
    }).then(blobFileCount => {
      if (blobFileCount >= self.state.dirWidth) {
        return blobPathBuild(self.state)
      }
      return blobPath
    })
  }).then((blobPath) => {
    self.currentBlobPath = blobPath
    var filePath = path.join(blobPath, self.state.newId())
    var writeStream = self.fsBlobStore.createWriteStream({
      key: filePath
    })
    var result = {
      blobPath: filePath,
      writeStream: writeStream
    }
    return result
  })
}

BlobStore.prototype.createReadStream = function (blobPath) {
  var self = this
  return new Promise((resolve, reject) => {
    try {
      var readStream = self.fsBlobStore.createReadStream({
        key: blobPath
      })
      resolve(readStream)
    } catch (err) {
      reject(err)
    }
  })
}

BlobStore.prototype.exists = function (blobPath) {
  var self = this
  return new Promise((resolve, reject) => {
    self.fsBlobStore.exists({
      key: blobPath
    }, (err) => {
      if (err) {
        reject(err)
      }
      resolve(true)
    })
  })
}

BlobStore.prototype.remove = function (blobPath) {
  var self = this
  return new Promise((resolve, reject) => {
    self.fsBlobStore.remove({
      key: blobPath
    }, (err) => {
      if (err) {
        reject(err)
      }
      resolve()
    })
  })
}

BlobStore.prototype.stat = function (blobPath) {
  var fullBlobPath = path.join(this.state.blobStoreRoot, blobPath)
  return new Promise((resolve, reject) => {
    fs.stat(fullBlobPath, (err, stat) => {
      if (err) {
        return reject(err)
      }
      resolve(stat)
    })
  })
}
<commit_msg>Fixed exists error<commit_after>const fs = require('fs')
const path = require('path')
const fsBlobStoreFactory = require('fs-blob-store')
const idGenerator = require('./id-generator')
const idValidator = require('./id-validator')
const Promise = require('bluebird')

// Internal Modules
const optionsParser = require('./options-parser')
const fsBlobItemList = require('./fs-blob-item-list')
const blobPathBuild = require('./blob-path-build')

exports.create = BlobStore

function BlobStore (opts) {
  if (!(this instanceof BlobStore)) {
    return new BlobStore(opts)
  }
  this.state = optionsParser(opts)
  this.state.newId = idGenerator(this.state.idType)
  this.state.validateId = idValidator(this.state.idType)
  this.currentBlobPath = false
  this.fsBlobStore = fsBlobStoreFactory(this.state.blobStoreRoot)
}

BlobStore.prototype.createWriteStream = function () {
  var self = this

  return Promise.resolve(this.currentBlobPath).then((blobPath) => {
    if (!blobPath) {
      return blobPathBuild(self.state)
    }
    return blobPath
  }).then((blobPath) => {
    var fullBlobPath = path.join(self.state.blobStoreRoot, blobPath)
    return fsBlobItemList(fullBlobPath, self.state.validateId, false).then(blobFileItems => {
      return blobFileItems.length
    }).then(blobFileCount => {
      if (blobFileCount >= self.state.dirWidth) {
        return blobPathBuild(self.state)
      }
      return blobPath
    })
  }).then((blobPath) => {
    self.currentBlobPath = blobPath
    var filePath = path.join(blobPath, self.state.newId())
    console.dir(filePath)
    var writeStream = self.fsBlobStore.createWriteStream({
      key: filePath
    })
    var result = {
      blobPath: filePath,
      writeStream: writeStream
    }
    return result
  })
}

BlobStore.prototype.createReadStream = function (blobPath) {
  var self = this
  return new Promise((resolve, reject) => {
    try {
      var readStream = self.fsBlobStore.createReadStream({
        key: blobPath
      })
      resolve(readStream)
    } catch (err) {
      reject(err)
    }
  })
}

BlobStore.prototype.exists = function (blobPath) {
  var self = this
  return new Promise((resolve, reject) => {
    self.fsBlobStore.exists({
      key: blobPath
    }, (err, exists) => {
      if (err) {
        reject(err)
      }
      resolve(exists)
    })
  })
}

BlobStore.prototype.remove = function (blobPath) {
  var self = this
  return new Promise((resolve, reject) => {
    self.fsBlobStore.remove({
      key: blobPath
    }, (err) => {
      if (err) {
        reject(err)
      }
      resolve()
    })
  })
}

BlobStore.prototype.stat = function (blobPath) {
  var fullBlobPath = path.join(this.state.blobStoreRoot, blobPath)
  return new Promise((resolve, reject) => {
    fs.stat(fullBlobPath, (err, stat) => {
      if (err) {
        return reject(err)
      }
      resolve(stat)
    })
  })
}
<|endoftext|>


<commit_before>import * as ActionTypes from './action-types';

export function serverError(error) {
  return {
    type: ActionTypes.SERVER_ERROR,
    error
  };
}

export function unauthenticated(payload) {
  return {
    type: ActionTypes.UNAUTHENTICATED,
    payload: {...payload, authToken: ''},
  };
}

export function staticPage(title) {
  return {
    type: ActionTypes.STATIC_PAGE,
    payload: {title}
  };
}

import * as Api from '../services/api';

export function whoAmI() {
  return {
    type: ActionTypes.WHO_AM_I,
    apiRequest: Api.getWhoAmI,
  };
}

export function home(offset = 0) {
  return {
    type: ActionTypes.HOME,
    apiRequest: Api.getHome,
    payload: {offset},
  };
}

export function discussions(offset = 0) {
  return {
    type: ActionTypes.DISCUSSIONS,
    apiRequest: Api.getDiscussions,
    payload: {offset},
  };
}

export function direct(offset = 0) {
  return {
    type: ActionTypes.DIRECT,
    apiRequest: Api.getDirect,
    payload: {offset},
  };
}

export function getUserFeed(username, offset = 0) {
  return {
    type: ActionTypes.GET_USER_FEED,
    apiRequest: Api.getUserFeed,
    nonAuthRequest: true,
    payload: {username, offset},
  };
}

export function showMoreComments(postId) {
  return {
    type: ActionTypes.SHOW_MORE_COMMENTS,
    apiRequest: Api.getPostWithAllComments,
    nonAuthRequest: true,
    payload: {postId},
  };
}

export function showMoreLikes(postId) {
  return {
    type: ActionTypes.SHOW_MORE_LIKES,
    payload: {postId},
  };
}

export function showMoreLikesAsync(postId) {
  return {
    type: ActionTypes.SHOW_MORE_LIKES_ASYNC,
    apiRequest: Api.getLikesOnly,
    nonAuthRequest: true,
    payload: {postId},
  };
}

export function showMoreLikesSync(postId) {
  return {
    type: ActionTypes.SHOW_MORE_LIKES_SYNC,
    payload: {postId},
  };
}

export function toggleEditingPost(postId) {
  return {
    type: ActionTypes.TOGGLE_EDITING_POST,
    payload: {postId}
  };
}

export function cancelEditingPost(postId) {
  return {
    type: ActionTypes.CANCEL_EDITING_POST,
    payload: {postId}
  };
}

export function saveEditingPost(postId, newPost) {
  return {
    type: ActionTypes.SAVE_EDITING_POST,
    apiRequest: Api.updatePost,
    payload: {postId, newPost},
  };
}

export function deletePost(postId) {
  return {
    type: ActionTypes.DELETE_POST,
    apiRequest: Api.deletePost,
    payload: {postId},
  };
}

export function toggleCommenting(postId) {
  return {
    type: ActionTypes.TOGGLE_COMMENTING,
    postId,
  };
}

export function addComment(postId, commentText) {
  return {
    type: ActionTypes.ADD_COMMENT,
    apiRequest: Api.addComment,
    payload: {
      postId,
      commentText,
    }
  };
}

export function likePost(postId, userId) {
  return {
    type: ActionTypes.LIKE_POST,
    apiRequest: Api.likePost,
    payload: {
      postId,
      userId
    }
  };
}

export function unlikePost(postId, userId) {
  return {
    type: ActionTypes.UNLIKE_POST,
    apiRequest: Api.unlikePost,
    payload: {
      postId,
      userId
    }
  };
}

export function hidePost(postId) {
  return {
    type: ActionTypes.HIDE_POST,
    apiRequest: Api.hidePost,
    payload: {
      postId
    }
  };
}

export function unhidePost(postId) {
  return {
    type: ActionTypes.UNHIDE_POST,
    apiRequest: Api.unhidePost,
    payload: {
      postId
    }
  };
}

export function toggleModeratingComments(postId) {
  return {
    type: ActionTypes.TOGGLE_MODERATING_COMMENTS,
    postId
  };
}

export function disableComments(postId) {
  return {
    type: ActionTypes.DISABLE_COMMENTS,
    apiRequest: Api.disableComments,
    payload: {
      postId
    }
  };
}

export function enableComments(postId) {
  return {
    type: ActionTypes.ENABLE_COMMENTS,
    apiRequest: Api.enableComments,
    payload: {
      postId
    }
  };
}

export function toggleEditingComment(commentId) {
  return {
    type: ActionTypes.TOGGLE_EDITING_COMMENT,
    commentId,
  };
}

export function saveEditingComment(commentId, newCommentBody) {
  return {
    type: ActionTypes.SAVE_EDITING_COMMENT,
    apiRequest: Api.updateComment,
    payload: {commentId, newCommentBody}
  };
}

export function deleteComment(commentId) {
  return {
    type: ActionTypes.DELETE_COMMENT,
    apiRequest: Api.deleteComment,
    payload: {commentId},
  };
}

export function createPost(feeds, postText, attachmentIds, more) {
  return {
    type: ActionTypes.CREATE_POST,
    apiRequest: Api.createPost,
    payload: {feeds, postText, attachmentIds, more},
  };
}

export function createBookmarkletPost(feeds, postText, imageUrls, commentText) {
  return {
    type: ActionTypes.CREATE_POST,
    apiRequest: Api.createBookmarkletPost,
    payload: {feeds, postText, imageUrls, commentText}
  };
}

export function addAttachmentResponse(postId, attachments) {
  return {
    type: ActionTypes.ADD_ATTACHMENT_RESPONSE,
    payload: {postId, attachments}
  };
}

export function removeAttachment(postId, attachmentId) {
  return {
    type: ActionTypes.REMOVE_ATTACHMENT,
    payload: {postId, attachmentId}
  };
}

export function signIn(username, password) {
  return {
    type: ActionTypes.SIGN_IN,
    apiRequest: Api.signIn,
    nonAuthRequest: true,
    payload: {
      username,
      password,
    },
  };
}

export function signUpChange(signUpData) {
  return {
    type: ActionTypes.SIGN_UP_CHANGE,
    ...signUpData,
  };
}

export function signUp(signUpData) {
  return {
    type: ActionTypes.SIGN_UP,
    apiRequest: Api.signUp,
    nonAuthRequest: true,
    payload: { ...signUpData },
  };
}

export function signUpEmpty(errorMessage) {
  return {
    type: ActionTypes.SIGN_UP_EMPTY,
    message: errorMessage
  };
}

export function updateUser(id, screenName, email, isPrivate, description) {
  return {
    type: ActionTypes.UPDATE_USER,
    apiRequest: Api.updateUser,
    payload: {id, screenName, email, isPrivate, description},
  };
}

export function userSettingsChange(payload) {
  return {
    type: ActionTypes.USER_SETTINGS_CHANGE,
    payload,
  };
}

export function updateFrontendPreferences(userId, prefs) {
  return {
    type: ActionTypes.UPDATE_FRONTEND_PREFERENCES,
    apiRequest: Api.updateFrontendPreferences,
    payload: {userId, prefs}
  };
}

export function updatePassword(payload) {
  return {
    type: ActionTypes.UPDATE_PASSWORD,
    apiRequest: Api.updatePassword,
    payload,
  };
}

export function updateUserPicture(picture) {
  return {
    type: ActionTypes.UPDATE_USER_PICTURE,
    apiRequest: Api.updateUserPicture,
    payload: {picture},
  };
}

export function getSinglePost(postId) {
  return {
    type: ActionTypes.GET_SINGLE_POST,
    apiRequest: Api.getPostWithAllComments,
    nonAuthRequest: true,
    payload: {postId},
  };
}

const userChangeAction = (type, apiRequest) => (payload) => {
  return {
    type,
    apiRequest,
    payload,
  };
};

export const ban = userChangeAction(ActionTypes.BAN, Api.ban);
export const unban = userChangeAction(ActionTypes.UNBAN, Api.unban);
export const subscribe = userChangeAction(ActionTypes.SUBSCRIBE, Api.subscribe);
export const unsubscribe = userChangeAction(ActionTypes.UNSUBSCRIBE, Api.unsubscribe);
export const sendSubscriptionRequest = userChangeAction(ActionTypes.SEND_SUBSCRIPTION_REQUEST, Api.sendSubscriptionRequest);

export function getUserComments(username, offset = 0) {
  return {
    type: ActionTypes.GET_USER_COMMENTS,
    apiRequest: Api.getUserComments,
    nonAuthRequest: true,
    payload: {username, offset},
  };
}

export function getUserLikes(username, offset = 0) {
  return {
    type: ActionTypes.GET_USER_LIKES,
    apiRequest: Api.getUserLikes,
    nonAuthRequest: true,
    payload: {username, offset},
  };
}

export function toggleHiddenPosts() {
  return {
    type: ActionTypes.TOGGLE_HIDDEN_POSTS
  };
}

export function subscribers(username) {
  return {
    type: ActionTypes.SUBSCRIBERS,
    apiRequest: Api.getSubscribers,
    payload: {username},
  };
}

export function subscriptions(username) {
  return {
    type: ActionTypes.SUBSCRIPTIONS,
    apiRequest: Api.getSubscriptions,
    payload: {username},
  };
}

export function getUserInfo(username) {
  return {
    type: ActionTypes.GET_USER_INFO,
    apiRequest: Api.getUserInfo,
    payload: {username},
  };
}

export function createGroup(groupSettings) {
  return {
    type: ActionTypes.CREATE_GROUP,
    payload: groupSettings,
    apiRequest: Api.createGroup
  };
}

export function updateGroup(id, groupSettings) {
  return {
    type: ActionTypes.UPDATE_GROUP,
    payload: {id, groupSettings},
    apiRequest: Api.updateGroup
  };
}

export function updateGroupPicture(groupName, file) {
  return {
    type: ActionTypes.UPDATE_GROUP_PICTURE,
    payload: {groupName, file},
    apiRequest: Api.updateGroupPicture
  };
}

export function managedGroups() {
  return {
    type: ActionTypes.MANAGED_GROUPS,
    apiRequest: Api.getManagedGroups
  };
}

export function acceptGroupRequest(groupName, userName) {
  return {
    type: ActionTypes.ACCEPT_GROUP_REQUEST,
    payload: {groupName, userName},
    apiRequest: Api.acceptGroupRequest
  };
}

export function rejectGroupRequest(groupName, userName) {
  return {
    type: ActionTypes.REJECT_GROUP_REQUEST,
    payload: {groupName, userName},
    apiRequest: Api.rejectGroupRequest
  };
}

export function acceptUserRequest(userName) {
  return {
    type: ActionTypes.ACCEPT_USER_REQUEST,
    payload: {userName},
    apiRequest: Api.acceptUserRequest
  };
}

export function rejectUserRequest(userName) {
  return {
    type: ActionTypes.REJECT_USER_REQUEST,
    payload: {userName},
    apiRequest: Api.rejectUserRequest
  };
}

export function resetPostCreateForm() {
  return {
    type: ActionTypes.RESET_POST_CREATE_FORM
  };
}

export function resetGroupCreateForm() {
  return {
    type: ActionTypes.RESET_GROUP_CREATE_FORM
  };
}

export function resetGroupUpdateForm() {
  return {
    type: ActionTypes.RESET_GROUP_UPDATE_FORM
  };
}

export function unsubscribeFromGroup(groupName, userName) {
  return {
    type: ActionTypes.UNSUBSCRIBE_FROM_GROUP,
    payload: {groupName, userName},
    apiRequest: Api.unsubscribeFromGroup
  };
}

export function promoteGroupAdmin(groupName, user) {
  return {
    type: ActionTypes.PROMOTE_GROUP_ADMIN,
    payload: {groupName, user},
    apiRequest: Api.promoteGroupAdmin
  };
}

export function demoteGroupAdmin(groupName, user, isItMe) {
  return {
    type: ActionTypes.DEMOTE_GROUP_ADMIN,
    payload: {groupName, user, isItMe},
    apiRequest: Api.demoteGroupAdmin
  };
}

export function revokeSentRequest(payload) {
  return {
    type: ActionTypes.REVOKE_USER_REQUEST,
    payload,
    apiRequest: Api.revokeSentRequest
  };
}

export function highlightComment(postId, author, arrows, baseCommentId) {
  return {
    type: ActionTypes.HIGHLIGHT_COMMENT,
    postId,
    author,
    arrows,
    baseCommentId
  };
}

export function clearHighlightComment() {
  return {
    type: ActionTypes.CLEAR_HIGHLIGHT_COMMENT,
  };
}

export function blockedByMe() {
  return {
    type: ActionTypes.BLOCKED_BY_ME,
    apiRequest: Api.getBlockedByMe
  };
}

export function toggleSidebar(val = null) {
  return {
    type: ActionTypes.TOGGLE_SIDEBAR,
    payload: {val}
  };
}

export function updateUserCard(payload) {
  return {
    type: ActionTypes.UPDATE_USER_CARD,
    payload
  };
}
<commit_msg>Enable /username/subscribers and /username/subscriptions for anons<commit_after>import * as ActionTypes from './action-types';

export function serverError(error) {
  return {
    type: ActionTypes.SERVER_ERROR,
    error
  };
}

export function unauthenticated(payload) {
  return {
    type: ActionTypes.UNAUTHENTICATED,
    payload: {...payload, authToken: ''},
  };
}

export function staticPage(title) {
  return {
    type: ActionTypes.STATIC_PAGE,
    payload: {title}
  };
}

import * as Api from '../services/api';

export function whoAmI() {
  return {
    type: ActionTypes.WHO_AM_I,
    apiRequest: Api.getWhoAmI,
  };
}

export function home(offset = 0) {
  return {
    type: ActionTypes.HOME,
    apiRequest: Api.getHome,
    payload: {offset},
  };
}

export function discussions(offset = 0) {
  return {
    type: ActionTypes.DISCUSSIONS,
    apiRequest: Api.getDiscussions,
    payload: {offset},
  };
}

export function direct(offset = 0) {
  return {
    type: ActionTypes.DIRECT,
    apiRequest: Api.getDirect,
    payload: {offset},
  };
}

export function getUserFeed(username, offset = 0) {
  return {
    type: ActionTypes.GET_USER_FEED,
    apiRequest: Api.getUserFeed,
    nonAuthRequest: true,
    payload: {username, offset},
  };
}

export function showMoreComments(postId) {
  return {
    type: ActionTypes.SHOW_MORE_COMMENTS,
    apiRequest: Api.getPostWithAllComments,
    nonAuthRequest: true,
    payload: {postId},
  };
}

export function showMoreLikes(postId) {
  return {
    type: ActionTypes.SHOW_MORE_LIKES,
    payload: {postId},
  };
}

export function showMoreLikesAsync(postId) {
  return {
    type: ActionTypes.SHOW_MORE_LIKES_ASYNC,
    apiRequest: Api.getLikesOnly,
    nonAuthRequest: true,
    payload: {postId},
  };
}

export function showMoreLikesSync(postId) {
  return {
    type: ActionTypes.SHOW_MORE_LIKES_SYNC,
    payload: {postId},
  };
}

export function toggleEditingPost(postId) {
  return {
    type: ActionTypes.TOGGLE_EDITING_POST,
    payload: {postId}
  };
}

export function cancelEditingPost(postId) {
  return {
    type: ActionTypes.CANCEL_EDITING_POST,
    payload: {postId}
  };
}

export function saveEditingPost(postId, newPost) {
  return {
    type: ActionTypes.SAVE_EDITING_POST,
    apiRequest: Api.updatePost,
    payload: {postId, newPost},
  };
}

export function deletePost(postId) {
  return {
    type: ActionTypes.DELETE_POST,
    apiRequest: Api.deletePost,
    payload: {postId},
  };
}

export function toggleCommenting(postId) {
  return {
    type: ActionTypes.TOGGLE_COMMENTING,
    postId,
  };
}

export function addComment(postId, commentText) {
  return {
    type: ActionTypes.ADD_COMMENT,
    apiRequest: Api.addComment,
    payload: {
      postId,
      commentText,
    }
  };
}

export function likePost(postId, userId) {
  return {
    type: ActionTypes.LIKE_POST,
    apiRequest: Api.likePost,
    payload: {
      postId,
      userId
    }
  };
}

export function unlikePost(postId, userId) {
  return {
    type: ActionTypes.UNLIKE_POST,
    apiRequest: Api.unlikePost,
    payload: {
      postId,
      userId
    }
  };
}

export function hidePost(postId) {
  return {
    type: ActionTypes.HIDE_POST,
    apiRequest: Api.hidePost,
    payload: {
      postId
    }
  };
}

export function unhidePost(postId) {
  return {
    type: ActionTypes.UNHIDE_POST,
    apiRequest: Api.unhidePost,
    payload: {
      postId
    }
  };
}

export function toggleModeratingComments(postId) {
  return {
    type: ActionTypes.TOGGLE_MODERATING_COMMENTS,
    postId
  };
}

export function disableComments(postId) {
  return {
    type: ActionTypes.DISABLE_COMMENTS,
    apiRequest: Api.disableComments,
    payload: {
      postId
    }
  };
}

export function enableComments(postId) {
  return {
    type: ActionTypes.ENABLE_COMMENTS,
    apiRequest: Api.enableComments,
    payload: {
      postId
    }
  };
}

export function toggleEditingComment(commentId) {
  return {
    type: ActionTypes.TOGGLE_EDITING_COMMENT,
    commentId,
  };
}

export function saveEditingComment(commentId, newCommentBody) {
  return {
    type: ActionTypes.SAVE_EDITING_COMMENT,
    apiRequest: Api.updateComment,
    payload: {commentId, newCommentBody}
  };
}

export function deleteComment(commentId) {
  return {
    type: ActionTypes.DELETE_COMMENT,
    apiRequest: Api.deleteComment,
    payload: {commentId},
  };
}

export function createPost(feeds, postText, attachmentIds, more) {
  return {
    type: ActionTypes.CREATE_POST,
    apiRequest: Api.createPost,
    payload: {feeds, postText, attachmentIds, more},
  };
}

export function createBookmarkletPost(feeds, postText, imageUrls, commentText) {
  return {
    type: ActionTypes.CREATE_POST,
    apiRequest: Api.createBookmarkletPost,
    payload: {feeds, postText, imageUrls, commentText}
  };
}

export function addAttachmentResponse(postId, attachments) {
  return {
    type: ActionTypes.ADD_ATTACHMENT_RESPONSE,
    payload: {postId, attachments}
  };
}

export function removeAttachment(postId, attachmentId) {
  return {
    type: ActionTypes.REMOVE_ATTACHMENT,
    payload: {postId, attachmentId}
  };
}

export function signIn(username, password) {
  return {
    type: ActionTypes.SIGN_IN,
    apiRequest: Api.signIn,
    nonAuthRequest: true,
    payload: {
      username,
      password,
    },
  };
}

export function signUpChange(signUpData) {
  return {
    type: ActionTypes.SIGN_UP_CHANGE,
    ...signUpData,
  };
}

export function signUp(signUpData) {
  return {
    type: ActionTypes.SIGN_UP,
    apiRequest: Api.signUp,
    nonAuthRequest: true,
    payload: { ...signUpData },
  };
}

export function signUpEmpty(errorMessage) {
  return {
    type: ActionTypes.SIGN_UP_EMPTY,
    message: errorMessage
  };
}

export function updateUser(id, screenName, email, isPrivate, description) {
  return {
    type: ActionTypes.UPDATE_USER,
    apiRequest: Api.updateUser,
    payload: {id, screenName, email, isPrivate, description},
  };
}

export function userSettingsChange(payload) {
  return {
    type: ActionTypes.USER_SETTINGS_CHANGE,
    payload,
  };
}

export function updateFrontendPreferences(userId, prefs) {
  return {
    type: ActionTypes.UPDATE_FRONTEND_PREFERENCES,
    apiRequest: Api.updateFrontendPreferences,
    payload: {userId, prefs}
  };
}

export function updatePassword(payload) {
  return {
    type: ActionTypes.UPDATE_PASSWORD,
    apiRequest: Api.updatePassword,
    payload,
  };
}

export function updateUserPicture(picture) {
  return {
    type: ActionTypes.UPDATE_USER_PICTURE,
    apiRequest: Api.updateUserPicture,
    payload: {picture},
  };
}

export function getSinglePost(postId) {
  return {
    type: ActionTypes.GET_SINGLE_POST,
    apiRequest: Api.getPostWithAllComments,
    nonAuthRequest: true,
    payload: {postId},
  };
}

const userChangeAction = (type, apiRequest) => (payload) => {
  return {
    type,
    apiRequest,
    payload,
  };
};

export const ban = userChangeAction(ActionTypes.BAN, Api.ban);
export const unban = userChangeAction(ActionTypes.UNBAN, Api.unban);
export const subscribe = userChangeAction(ActionTypes.SUBSCRIBE, Api.subscribe);
export const unsubscribe = userChangeAction(ActionTypes.UNSUBSCRIBE, Api.unsubscribe);
export const sendSubscriptionRequest = userChangeAction(ActionTypes.SEND_SUBSCRIPTION_REQUEST, Api.sendSubscriptionRequest);

export function getUserComments(username, offset = 0) {
  return {
    type: ActionTypes.GET_USER_COMMENTS,
    apiRequest: Api.getUserComments,
    nonAuthRequest: true,
    payload: {username, offset},
  };
}

export function getUserLikes(username, offset = 0) {
  return {
    type: ActionTypes.GET_USER_LIKES,
    apiRequest: Api.getUserLikes,
    nonAuthRequest: true,
    payload: {username, offset},
  };
}

export function toggleHiddenPosts() {
  return {
    type: ActionTypes.TOGGLE_HIDDEN_POSTS
  };
}

export function subscribers(username) {
  return {
    type: ActionTypes.SUBSCRIBERS,
    apiRequest: Api.getSubscribers,
    nonAuthRequest: true,
    payload: {username},
  };
}

export function subscriptions(username) {
  return {
    type: ActionTypes.SUBSCRIPTIONS,
    apiRequest: Api.getSubscriptions,
    nonAuthRequest: true,
    payload: {username},
  };
}

export function getUserInfo(username) {
  return {
    type: ActionTypes.GET_USER_INFO,
    apiRequest: Api.getUserInfo,
    payload: {username},
  };
}

export function createGroup(groupSettings) {
  return {
    type: ActionTypes.CREATE_GROUP,
    payload: groupSettings,
    apiRequest: Api.createGroup
  };
}

export function updateGroup(id, groupSettings) {
  return {
    type: ActionTypes.UPDATE_GROUP,
    payload: {id, groupSettings},
    apiRequest: Api.updateGroup
  };
}

export function updateGroupPicture(groupName, file) {
  return {
    type: ActionTypes.UPDATE_GROUP_PICTURE,
    payload: {groupName, file},
    apiRequest: Api.updateGroupPicture
  };
}

export function managedGroups() {
  return {
    type: ActionTypes.MANAGED_GROUPS,
    apiRequest: Api.getManagedGroups
  };
}

export function acceptGroupRequest(groupName, userName) {
  return {
    type: ActionTypes.ACCEPT_GROUP_REQUEST,
    payload: {groupName, userName},
    apiRequest: Api.acceptGroupRequest
  };
}

export function rejectGroupRequest(groupName, userName) {
  return {
    type: ActionTypes.REJECT_GROUP_REQUEST,
    payload: {groupName, userName},
    apiRequest: Api.rejectGroupRequest
  };
}

export function acceptUserRequest(userName) {
  return {
    type: ActionTypes.ACCEPT_USER_REQUEST,
    payload: {userName},
    apiRequest: Api.acceptUserRequest
  };
}

export function rejectUserRequest(userName) {
  return {
    type: ActionTypes.REJECT_USER_REQUEST,
    payload: {userName},
    apiRequest: Api.rejectUserRequest
  };
}

export function resetPostCreateForm() {
  return {
    type: ActionTypes.RESET_POST_CREATE_FORM
  };
}

export function resetGroupCreateForm() {
  return {
    type: ActionTypes.RESET_GROUP_CREATE_FORM
  };
}

export function resetGroupUpdateForm() {
  return {
    type: ActionTypes.RESET_GROUP_UPDATE_FORM
  };
}

export function unsubscribeFromGroup(groupName, userName) {
  return {
    type: ActionTypes.UNSUBSCRIBE_FROM_GROUP,
    payload: {groupName, userName},
    apiRequest: Api.unsubscribeFromGroup
  };
}

export function promoteGroupAdmin(groupName, user) {
  return {
    type: ActionTypes.PROMOTE_GROUP_ADMIN,
    payload: {groupName, user},
    apiRequest: Api.promoteGroupAdmin
  };
}

export function demoteGroupAdmin(groupName, user, isItMe) {
  return {
    type: ActionTypes.DEMOTE_GROUP_ADMIN,
    payload: {groupName, user, isItMe},
    apiRequest: Api.demoteGroupAdmin
  };
}

export function revokeSentRequest(payload) {
  return {
    type: ActionTypes.REVOKE_USER_REQUEST,
    payload,
    apiRequest: Api.revokeSentRequest
  };
}

export function highlightComment(postId, author, arrows, baseCommentId) {
  return {
    type: ActionTypes.HIGHLIGHT_COMMENT,
    postId,
    author,
    arrows,
    baseCommentId
  };
}

export function clearHighlightComment() {
  return {
    type: ActionTypes.CLEAR_HIGHLIGHT_COMMENT,
  };
}

export function blockedByMe() {
  return {
    type: ActionTypes.BLOCKED_BY_ME,
    apiRequest: Api.getBlockedByMe
  };
}

export function toggleSidebar(val = null) {
  return {
    type: ActionTypes.TOGGLE_SIDEBAR,
    payload: {val}
  };
}

export function updateUserCard(payload) {
  return {
    type: ActionTypes.UPDATE_USER_CARD,
    payload
  };
}
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import ApartmentUpdates from '../apartments/ApartmentUpdates';
import TenantUpdates from '../tenants/TenantUpdates';
import Apartment from '../apartments/Apartment';
import Tenant from '../tenants/Tenant';

const Home = () => (

    <MuiThemeProvider>
      <ApartmentUpdates />
    </MuiThemeProvider>
    <MuiThemeProvider>
      <TenantUpdates />
    </MuiThemeProvider>
    <Apartment />
    <Tenant />

)

export default Home;
<commit_msg>fix(): Fix bug on home page<commit_after>import React, {Component} from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import ApartmentUpdates from '../apartments/ApartmentUpdates';
import TenantUpdates from '../tenants/TenantUpdates';
import Apartment from '../apartments/Apartment';
import Tenant from '../tenants/Tenant';

const Home = () => (

    <MuiThemeProvider>
      <ApartmentUpdates />
    </MuiThemeProvider>
    <MuiThemeProvider>
      <TenantUpdates />
    </MuiThemeProvider>

)

export default Home;
<|endoftext|>


<commit_before>/**
 * In this file, we create a React component
 * which incorporates components providedby material-ui.
 */

import React from 'react';
import RaisedButton from 'material-ui/lib/raised-button';
import Dialog from 'material-ui/lib/dialog';
import {deepOrange500} from 'material-ui/lib/styles/colors';
import FlatButton from 'material-ui/lib/flat-button';
import getMuiTheme from 'material-ui/lib/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/lib/MuiThemeProvider';

const styles = {
  container: {
    textAlign: 'center',
    paddingTop: 200,
  },
};

const muiTheme = getMuiTheme({
  palette: {
    accent1Color: deepOrange500,
  },
});

class Main extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.handleRequestClose = this.handleRequestClose.bind(this);
    this.handleTouchTap = this.handleTouchTap.bind(this);

    this.state = {
      open: false,
    };
  }

  handleRequestClose() {
    this.setState({
      open: false,
    });
  }

  handleTouchTap() {
    this.setState({
      open: true,
    });
  }

  render() {
    const standardActions = (
      <FlatButton
        label="Ok"
        secondary={true}
        onTouchTap={this.handleRequestClose}
      />
    );

    return (
      <MuiThemeProvider muiTheme={muiTheme}>

          <Dialog
            open={this.state.open}
            title="Super Secret Password"
            actions={standardActions}
            onRequestClose={this.handleRequestClose}
          >
            1-2-3-4-5
          </Dialog>

material-ui

example project

          <RaisedButton
            label="Super Secret Password"
            primary={true}
            onTouchTap={this.handleTouchTap}
          />

      </MuiThemeProvider>
    );
  }
}

export default Main;
<commit_msg>[Examples] Update import statements<commit_after>/**
 * In this file, we create a React component
 * which incorporates components providedby material-ui.
 */

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import Dialog from 'material-ui/Dialog';
import {deepOrange500} from 'material-ui/styles/colors';
import FlatButton from 'material-ui/FlatButton';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

const styles = {
  container: {
    textAlign: 'center',
    paddingTop: 200,
  },
};

const muiTheme = getMuiTheme({
  palette: {
    accent1Color: deepOrange500,
  },
});

class Main extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.handleRequestClose = this.handleRequestClose.bind(this);
    this.handleTouchTap = this.handleTouchTap.bind(this);

    this.state = {
      open: false,
    };
  }

  handleRequestClose() {
    this.setState({
      open: false,
    });
  }

  handleTouchTap() {
    this.setState({
      open: true,
    });
  }

  render() {
    const standardActions = (
      <FlatButton
        label="Ok"
        secondary={true}
        onTouchTap={this.handleRequestClose}
      />
    );

    return (
      <MuiThemeProvider muiTheme={muiTheme}>

          <Dialog
            open={this.state.open}
            title="Super Secret Password"
            actions={standardActions}
            onRequestClose={this.handleRequestClose}
          >
            1-2-3-4-5
          </Dialog>

material-ui

example project

          <RaisedButton
            label="Super Secret Password"
            primary={true}
            onTouchTap={this.handleTouchTap}
          />

      </MuiThemeProvider>
    );
  }
}

export default Main;
<|endoftext|>


<commit_before>import request from 'superagent';
import React, { Component } from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import AppBar from 'material-ui/AppBar';
import { deepOrange500 } from 'material-ui/styles/colors';
import FlatButton from 'material-ui/FlatButton';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { GridList, GridTile } from 'material-ui/GridList';
import Subheader from 'material-ui/Subheader';
import IconButton from 'material-ui/IconButton';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';

import AppNavDrawer from './components/AppNavDrawer';

const styles = {
  container: {
    textAlign: 'center',
    paddingTop: 70
  },
  appBar: {
    position: 'fixed',
    top: 0
  },
  root: {
    display: 'flex',
    flexWrap: 'wrap',
    justifyContent: 'space-around',
    margin: '0px 4px 0px 4px'
  },
  gridList: {
    width: '100%',
    // height: 500,
    overflowY: 'auto',
    marginBottom: 24
  }
};

const tilesData = [
  {
    img: 'images/grid-list/00-52-29-429_640.jpg',
    title: 'Breakfast',
    author: 'jill111'
  },
  {
    img: 'images/grid-list/burger-827309_640.jpg',
    title: 'Tasty burger',
    author: 'pashminu'
  },
  {
    img: 'images/grid-list/camera-813814_640.jpg',
    title: 'Camera',
    author: 'Danson67'
  },
  {
    img: 'images/grid-list/morning-819362_640.jpg',
    title: 'Morning',
    author: 'fancycrave1'
  },
  {
    img: 'images/grid-list/hats-829509_640.jpg',
    title: 'Hats',
    author: 'Hans'
  },
  {
    img: 'images/grid-list/honey-823614_640.jpg',
    title: 'Honey',
    author: 'fancycravel'
  },
  {
    img: 'images/grid-list/vegetables-790022_640.jpg',
    title: 'Vegetables',
    author: 'jill111'
  },
  {
    img: 'images/grid-list/water-plant-821293_640.jpg',
    title: 'Water plant',
    author: 'BkrmadtyaKarki'
  }
];

const muiTheme = getMuiTheme({
  palette: {
    accent1Color: deepOrange500
  }
});

class Main extends Component {
  constructor(props, context) {
    super(props, context);

    this.handleTouchTapLeftIconButton = this.handleTouchTapLeftIconButton.bind(this);
    this.handleChangeRequestNavDrawer = this.handleChangeRequestNavDrawer.bind(this);
    this.handleRequestClose = this.handleRequestClose.bind(this);
    this.handleTouchTap = this.handleTouchTap.bind(this);

    this.state = {
      open: false,
      navDrawerOpen: false
    };
  }

  handleRequestClose() {
    this.setState({
      open: false
    });
  }

  handleTouchTap() {
    this.setState({
      open: true
    });
  }

  handleTouchTapLeftIconButton() {
    this.setState({
      navDrawerOpen: !this.state.navDrawerOpen
    });
  }

  handleChangeRequestNavDrawer(open) {
    this.setState({
      navDrawerOpen: open
    });
  }

  handleChangeFilter(filters) {
    const keys = Object.keys(filters);
    if (keys && keys.length > 0) {
      let tagsComponent;
      let url = 'http://localhost:3000/api/search?';
      keys.forEach((k, i) => {
        tagsComponent = 'tags='.concat(filters[k]);
        if (i < keys.length - 1) {
          tagsComponent += '&';
        }
        url += tagsComponent;
      });
      console.log(url);
      request
        .get(url)
        .send({ name: 'Manny', species: 'cat' })
        // .set('X-API-Key', 'foobar')
        .set('Accept', 'application/json')
        .end((err, res) => {
          if (!res.body.success) {
            alert('error communicating with the server');
          } else {
            console.log(res.body.result);
          }
        });
    }
  }

  render() {
    styles.navDrawer = {
      zIndex: styles.appBar.zIndex - 1
    };
    let docked = false;
    let navDrawerOpen = this.state.navDrawerOpen;
    const standardActions = (
      <FlatButton
        label='Ok'
        primary
        onTouchTap={this.handleRequestClose}
      />
    );

    return (
      <MuiThemeProvider muiTheme={muiTheme}>

          <AppBar
            title='KTS Client'
            iconClassNameRight='muidocs-icon-navigation-expand-more'
            onLeftIconButtonTouchTap={this.handleTouchTapLeftIconButton}
            style={styles.appBar}
          />
          <AppNavDrawer
            style={styles.navDrawer}
            location={location}
            docked={docked}
            onRequestChangeNavDrawer={this.handleChangeRequestNavDrawer}
            onHandleChangeFilter={this.handleChangeFilter}
            open={navDrawerOpen}
          />

            <GridList
              cellHeight={200}
              style={styles.gridList}
            >
              {tilesData.map((tile) => (
                <GridTile
                  key={tile.img}
                  title={tile.title}
                  subtitle={by {tile.author}}
                  actionIcon={<IconButton><StarBorder color='white' /></IconButton>}
                >

                </GridTile>
              ))}
            </GridList>

      </MuiThemeProvider>
    );
  }
}

export default Main;
<commit_msg>horrible way to build url, should be done elsewhere<commit_after>import request from 'superagent';
import React, { Component } from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import AppBar from 'material-ui/AppBar';
import { deepOrange500 } from 'material-ui/styles/colors';
import FlatButton from 'material-ui/FlatButton';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { GridList, GridTile } from 'material-ui/GridList';
import Subheader from 'material-ui/Subheader';
import IconButton from 'material-ui/IconButton';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';

import AppNavDrawer from './components/AppNavDrawer';

const styles = {
  container: {
    textAlign: 'center',
    paddingTop: 70
  },
  appBar: {
    position: 'fixed',
    top: 0
  },
  root: {
    display: 'flex',
    flexWrap: 'wrap',
    justifyContent: 'space-around',
    margin: '0px 4px 0px 4px'
  },
  gridList: {
    width: '100%',
    // height: 500,
    overflowY: 'auto',
    marginBottom: 24
  }
};

let tilesData = [
  {
    img: 'images/grid-list/00-52-29-429_640.jpg',
    title: 'Breakfast',
    author: 'jill111'
  },
  {
    img: 'images/grid-list/burger-827309_640.jpg',
    title: 'Tasty burger',
    author: 'pashminu'
  },
  {
    img: 'images/grid-list/camera-813814_640.jpg',
    title: 'Camera',
    author: 'Danson67'
  },
  {
    img: 'images/grid-list/morning-819362_640.jpg',
    title: 'Morning',
    author: 'fancycrave1'
  },
  {
    img: 'images/grid-list/hats-829509_640.jpg',
    title: 'Hats',
    author: 'Hans'
  },
  {
    img: 'images/grid-list/honey-823614_640.jpg',
    title: 'Honey',
    author: 'fancycravel'
  },
  {
    img: 'images/grid-list/vegetables-790022_640.jpg',
    title: 'Vegetables',
    author: 'jill111'
  },
  {
    img: 'images/grid-list/water-plant-821293_640.jpg',
    title: 'Water plant',
    author: 'BkrmadtyaKarki'
  }
];

const muiTheme = getMuiTheme({
  palette: {
    accent1Color: deepOrange500
  }
});

class Main extends Component {
  constructor(props, context) {
    super(props, context);

    this.handleTouchTapLeftIconButton = this.handleTouchTapLeftIconButton.bind(this);
    this.handleChangeRequestNavDrawer = this.handleChangeRequestNavDrawer.bind(this);
    this.handleRequestClose = this.handleRequestClose.bind(this);
    this.handleTouchTap = this.handleTouchTap.bind(this);

    this.state = {
      open: false,
      navDrawerOpen: false
    };
  }

  handleRequestClose() {
    this.setState({
      open: false
    });
  }

  handleTouchTap() {
    this.setState({
      open: true
    });
  }

  handleTouchTapLeftIconButton() {
    this.setState({
      navDrawerOpen: !this.state.navDrawerOpen
    });
  }

  handleChangeRequestNavDrawer(open) {
    this.setState({
      navDrawerOpen: open
    });
  }

  handleChangeFilter(filters) {
    const keys = Object.keys(filters);
    if (keys && keys.length > 0) {
      let tagsComponent;
      let url = 'http://localhost:3000/api/search?';
      keys.forEach((k, i) => {
        tagsComponent = 'tags='.concat(filters[k]);
        if (i < keys.length - 1) {
          tagsComponent += '&';
        }
        url += tagsComponent;
      });
      console.log(url);
      request
        .get(url)
        .send({ name: 'Manny', species: 'cat' })
        // .set('X-API-Key', 'foobar')
        .set('Accept', 'application/json')
        .end((err, res) => {
          const body = res.body;
          if (!body.success) {
            alert('error communicating with the server');
          } else {
            console.log(body.result);
            if (body.result && body.result.length > 0) {
              tilesData = body.result.map((p) => {
                const url = 'http://localhost:3000/static/'.concat(p.page.nameslug)
                  .concat('_img/')
                  .concat(p.filename);
                return {
                  img: url,
                  title: p.filename,
                  author: p._d
                };
              });
            }
          }
        });
    }
  }

  render() {
    styles.navDrawer = {
      zIndex: styles.appBar.zIndex - 1
    };
    let docked = false;
    let navDrawerOpen = this.state.navDrawerOpen;
    const standardActions = (
      <FlatButton
        label='Ok'
        primary
        onTouchTap={this.handleRequestClose}
      />
    );

    return (
      <MuiThemeProvider muiTheme={muiTheme}>

          <AppBar
            title='KTS Client'
            iconClassNameRight='muidocs-icon-navigation-expand-more'
            onLeftIconButtonTouchTap={this.handleTouchTapLeftIconButton}
            style={styles.appBar}
          />
          <AppNavDrawer
            style={styles.navDrawer}
            location={location}
            docked={docked}
            onRequestChangeNavDrawer={this.handleChangeRequestNavDrawer}
            onHandleChangeFilter={this.handleChangeFilter}
            open={navDrawerOpen}
          />

            <GridList
              cellHeight={200}
              style={styles.gridList}
            >
              {tilesData.map((tile) => (
                <GridTile
                  key={tile.img}
                  title={tile.title}
                  subtitle={by {tile.author}}
                  actionIcon={<IconButton><StarBorder color='white' /></IconButton>}
                >

                </GridTile>
              ))}
            </GridList>

      </MuiThemeProvider>
    );
  }
}

export default Main;
<|endoftext|>


<commit_before>function removeJavaScriptDisabledWarning() {
    // Not using jQuery here for speed and to support angient browsers.
    document.getElementById('javascript_disabled').style.display = 'none';
}

function addJavaScriptDisabledWarning() {
    document.getElementById('javascript_disabled').style.display = 'block';
}

function initLayout(suiteName, type) {
    parseTemplates();
    setTitle(suiteName, type);
    addHeader();
    addReportOrLogLink(type);
}

function parseTemplates() {
    $('script[type="text/x-jquery-tmpl"]').map(function (idx, elem) {
        $.template(elem.id, elem.text);
    });
}

function setTitle(suiteName, type) {
    var givenTitle = window.settings.title;
    document.title = givenTitle ? givenTitle : suiteName + " Test " + type;
}

function addHeader() {
    var generatedAgoMillis = window.testdata.generated().getTime();
    var template =
        '
' +
        'Generated
${generated}
' +
        '${generatedAgo} ago' +
        '
' +
        '

' +
        '
${title}
';
    $.tmpl(template, {
        title: document.title,
        generated: window.output.generatedTimestamp,
        generatedAgo: util.createGeneratedAgoString(generatedAgoMillis)
    }).appendTo($('#header_div'));
}

function addReportOrLogLink(myType) {
    var url;
    var text;
    if (myType == 'Report') {
        url = window.settings.logURL;
        text = 'LOG';
    } else {
        url = window.settings.reportURL;
        text = 'REPORT';
    }
    if (url) {
        $('#report_or_log_link a').attr('href', url);
        $('#report_or_log_link a').text(text);
    } else {
        $('#report_or_log_link').remove();
    }
}

function addStatistics() {
    var statHeaders =
        'Total	' +
        'Pass	' +
        'Fail	' +
        'Graph	';
    var statTable =
        '
Test Statistics
' +
        '
' +
        '
Total Statistics	' + statHeaders + '
' +
        '
' +
        '
' +
        '
Statistics by Tag	' + statHeaders + '
' +
        '
' +
        '
' +
        '
Statistics by Suite	' + statHeaders + '
' +
        '
';
    $(statTable).appendTo('#statistics_container');
    $.map(['total', 'tag', 'suite'], addStatTable);
}

function addStatTable(tableName) {
    var stats = window.testdata.statistics()[tableName];
    if (tableName == 'tag' && stats.length == 0) {
        renderNoTagStatTable();
    } else {
        var templateName = tableName + 'StatisticsRowTemplate';
        renderStatTable(tableName, templateName, stats);
    }
}

function renderNoTagStatTable() {
    $.tmpl('no_tags_row').appendTo($('#tag_stats'));
}

function renderStatTable(tableName, templateName, stats) {
    var tableId = "#" + tableName + "_stats";
    // Need explicit for loop because $.tmpl() does not handle very large lists
    for (var i = 0; stats !== undefined && i < stats.length; i++) {
        $.tmpl(templateName , stats[i]).appendTo($(tableId));
    }
}

$.template("stat_columns",
    '${total}	' +
    '${pass}	' +
    '${fail}	' +
    '' +
      '
' +
        '

' +
        '

' +
      '
' +
    '	'
);

$.template('no_tags_row',
    '
' +
    'No Tags	' +
    '	' +
    '	' +
    '	' +
    '' +
      '

' +
    '	' +
    '
'
);

$.template('suiteStatusMessageTemplate',
    '${critical} critical test, ' +
    '${criticalPassed} passed, ' +
    '${criticalFailed} failed
' +
    '${total} test total, ' +
    '${totalPassed} passed, ' +
    '${totalFailed} failed'
);
<commit_msg>Fixed statistics graph in log/report when combined tag matches no tag.<commit_after>function removeJavaScriptDisabledWarning() {
    // Not using jQuery here for speed and to support ancient browsers.
    document.getElementById('javascript_disabled').style.display = 'none';
}

function addJavaScriptDisabledWarning() {
    document.getElementById('javascript_disabled').style.display = 'block';
}

function initLayout(suiteName, type) {
    parseTemplates();
    setTitle(suiteName, type);
    addHeader();
    addReportOrLogLink(type);
}

function parseTemplates() {
    $('script[type="text/x-jquery-tmpl"]').map(function (idx, elem) {
        $.template(elem.id, elem.text);
    });
}

function setTitle(suiteName, type) {
    var givenTitle = window.settings.title;
    document.title = givenTitle ? givenTitle : suiteName + " Test " + type;
}

function addHeader() {
    var generatedAgoMillis = window.testdata.generated().getTime();
    var template =
        '
' +
        'Generated
${generated}
' +
        '${generatedAgo} ago' +
        '
' +
        '

' +
        '
${title}
';
    $.tmpl(template, {
        title: document.title,
        generated: window.output.generatedTimestamp,
        generatedAgo: util.createGeneratedAgoString(generatedAgoMillis)
    }).appendTo($('#header_div'));
}

function addReportOrLogLink(myType) {
    var url;
    var text;
    if (myType == 'Report') {
        url = window.settings.logURL;
        text = 'LOG';
    } else {
        url = window.settings.reportURL;
        text = 'REPORT';
    }
    if (url) {
        $('#report_or_log_link a').attr('href', url);
        $('#report_or_log_link a').text(text);
    } else {
        $('#report_or_log_link').remove();
    }
}

function addStatistics() {
    var statHeaders =
        'Total	' +
        'Pass	' +
        'Fail	' +
        'Graph	';
    var statTable =
        '
Test Statistics
' +
        '
' +
        '
Total Statistics	' + statHeaders + '
' +
        '
' +
        '
' +
        '
Statistics by Tag	' + statHeaders + '
' +
        '
' +
        '
' +
        '
Statistics by Suite	' + statHeaders + '
' +
        '
';
    $(statTable).appendTo('#statistics_container');
    $.map(['total', 'tag', 'suite'], addStatTable);
}

function addStatTable(tableName) {
    var stats = window.testdata.statistics()[tableName];
    if (tableName == 'tag' && stats.length == 0) {
        renderNoTagStatTable();
    } else {
        var templateName = tableName + 'StatisticsRowTemplate';
        renderStatTable(tableName, templateName, stats);
    }
}

function renderNoTagStatTable() {
    $.tmpl('no_tags_row').appendTo($('#tag_stats'));
}

function renderStatTable(tableName, templateName, stats) {
    var tableId = "#" + tableName + "_stats";
    // Need explicit for loop because $.tmpl() does not handle very large lists
    for (var i = 0; stats !== undefined && i < stats.length; i++) {
        $.tmpl(templateName , stats[i]).appendTo($(tableId));
    }
}

$.template("stat_columns",
    '${total}	' +
    '${pass}	' +
    '${fail}	' +
    '' +
      '{{if total}}' +
      '
' +
        '

' +
        '

' +
      '
' +
      '{{else}}' +
      '

' +
      '{{/if}}' +
    '	'
);

$.template('no_tags_row',
    '
' +
    'No Tags	' +
    '	' +
    '	' +
    '	' +
    '' +
      '

' +
    '	' +
    '
'
);

$.template('suiteStatusMessageTemplate',
    '${critical} critical test, ' +
    '${criticalPassed} passed, ' +
    '${criticalFailed} failed
' +
    '${total} test total, ' +
    '${totalPassed} passed, ' +
    '${totalFailed} failed'
);
<|endoftext|>


<commit_before>
// @flow
import DeviceInfo from 'react-native-device-info';

import config from '../config'

export const allSession: () => any =
  () =>
    fetch(`${config.urls.sleepingPill}/public/allSessions`)
      .then((res) => res.json())

export const sessionBySlug: (string) => any =
  (slug) => fetch(`${config.urls.sleepingPill}/public/allSessions/${slug}`)
    .then((res) => res.json())

const options = {
	"Content-Type": "application/json",
      headers: {
        'Content-Type': "application/json",
		    "Voter-ID": DeviceInfo? "javazone2017" : "javazone2017"
      }
}
export const feedback: (feedback) => any =
  (feedback) => {
    options.method = 'POST';
    let feedbackBody = Object.keys(feedback).filter((key) => {
      return key !== 'sessionId' && key !== 'eventId';
    })
    options.body = JSON.stringify(feedback);
    return fetch(`${config.urls.devnull}/events/${feedback.eventId}/sessions/${feedback.sessionId}/feedbacks`, options)
      .then(res => res.json())
      //.catch(err => {
      //  console.log('err in fetch call', err)
      //  throw err;
      //})
  }<commit_msg>post feedback<commit_after>
// @flow
import DeviceInfo from 'react-native-device-info';

import config from '../config'

export const allSession: () => any =
  () =>
    fetch(`${config.urls.sleepingPill}/public/allSessions`)
      .then((res) => res.json())

export const sessionBySlug: (string) => any =
  (slug) => fetch(`${config.urls.sleepingPill}/public/allSessions/${slug}`)
    .then((res) => res.json())

const options = {
	"Content-Type": "application/json",
      headers: {
        'Content-Type': "application/json",
		    "Voter-ID": DeviceInfo? "javazone2017" : "javazone2017"
      }
}
export const feedback: (feedback) => any =
  (feedback) => {
    options.method = 'POST';
    let feedbackBody = Object.keys(feedback).filter((key) => {
      return key !== 'sessionId' && key !== 'eventId';
    })
    options.body = JSON.stringify(feedback.feedback);
    return fetch(`${config.urls.devnull}/events/${feedback.eventId}/sessions/${feedback.sessionId}/feedbacks`, options)
      .then(res => res.json())
  }<|endoftext|>


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

	ng
	.module("angular-autowrap")
	.directive("autowrap", [
		"autowrapController",
		"autowrapLinker",
		function(autowrapController, autowrapLinker){

			return {
				restrict: "A",
				require: "^form",
				scope: {
					config: "=autowrapConfig",
					theme: "@autowrapTheme",
					templateFor: "@autowrapTemplateFor"
				},

				controller: function($scope, $element, $attrs, $transclude){
					autowrapController.init($scope);
				},

				link: function(scope, element, attrs, ctrl, transclude){
					autowrapLinker.init(scope, element, attrs, ctrl, transclude);
				}
			};
		}
	]);

})(angular);
<commit_msg>changed controller declaration to array syntax, fixes bug in minified version<commit_after>(function(ng){
	"use strict";

	ng
	.module("angular-autowrap")
	.directive("autowrap", [
		"autowrapController",
		"autowrapLinker",
		function(autowrapController, autowrapLinker){

			return {
				restrict: "A",
				require: "^form",
				scope: {
					config: "=autowrapConfig",
					theme: "@autowrapTheme",
					templateFor: "@autowrapTemplateFor"
				},

				controller: [
					"$scope",
					function($scope){
						autowrapController.init($scope);
					}
				],

				link: function(scope, element, attrs, ctrl, transclude){
					autowrapLinker.init(scope, element, attrs, ctrl, transclude);
				}
			};
		}
	]);

})(angular);
<|endoftext|>


<commit_before>/*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/

'use strict';

// Older UI
togglbutton.render('.details-pane-body:not(.toggl)', {observe: true}, function (elem) {

  var link, descFunc, projectFunc,
    container = $('.sticky-view-placeholder', elem),
    description = $('#details_property_sheet_title', elem),
    project = $('#details_pane_project_tokenizer .token_name', elem);

  descFunc = function () {
    return !!description ? description.value : "";
  };

  projectFunc = function () {
    return (project && project.textContent) || ($('.ancestor-projects', elem) && $('.ancestor-projects', elem).textContent) || "";
  };

  link = togglbutton.createTimerLink({
    className: 'asana',
    description: descFunc,
    projectName: projectFunc
  });

  container.parentNode.insertBefore(link, container.nextSibling);
});

// New UI
togglbutton.render('#right_pane__contents .SingleTaskPane:not(.toggl)', {observe: true}, function (elem) {

  var link, descFunc, projectFunc,
    container = $('.SingleTaskTitleRow', elem),
    description = $('.SingleTaskTitleRow .simpleTextarea', elem),
    project = $('.TaskProjectPill-projectName div', elem);

  descFunc = function () {
    return !!description ? description.value : "";
  };

  projectFunc = function () {
    return (project && project.textContent) || ($('.ancestor-projects', elem) && $('.ancestor-projects', elem).textContent) || "";
  };

  link = togglbutton.createTimerLink({
    className: 'asana-new',
    description: descFunc,
    projectName: projectFunc
  });

  container.after(link);
});

// Board view
togglbutton.render('.BoardCard.BoardColumnCardsContainer-item:not(.toggl)', {observe: true}, function (elem) {
  if (!!$('.toggl-button', elem)) {
    return;
  }
  var link,
    container = $('.BoardCardMetadata-left', elem),
    description = $('.BoardCard-name', elem).textContent,
    project = $('.SidebarItemRow.is-selected').textContent;

  link = togglbutton.createTimerLink({
    className: 'asana-board',
    description: description,
    projectName: project,
    buttonType: 'minimal'
  });

  container.appendChild(link);
});

// Board task detail view
togglbutton.render('.SingleTaskTitleRow:not(.toggl)', {observe: true}, function (elem) {
  if (!!$('.toggl-button', elem)) {
    return;
  }
  var link,
    container = $('.SingleTaskPaneToolbar', elem.parentNode),
    description = $('.SingleTaskTitleRow textarea', elem.parentNode).textContent,
    projectElement = $('.SingleTaskPane-projects .TaskProjectPill-projectName', elem.parentNode);

  link = togglbutton.createTimerLink({
    className: 'asana-board',
    description: description,
    projectName: projectElement ? projectElement.textContent : '',
    buttonType: 'minimal'
  });

  container.appendChild(link);
});

<commit_msg>Fix Asana project autoselect<commit_after>/*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/

'use strict';

// Older UI
togglbutton.render('.details-pane-body:not(.toggl)', {observe: true}, function (elem) {

  var link, descFunc, projectFunc,
    container = $('.sticky-view-placeholder', elem),
    description = $('#details_property_sheet_title', elem),
    project = $('#details_pane_project_tokenizer .token_name', elem);

  descFunc = function () {
    return !!description ? description.value : "";
  };

  projectFunc = function () {
    return (project && project.textContent) || ($('.ancestor-projects', elem) && $('.ancestor-projects', elem).textContent) || "";
  };

  link = togglbutton.createTimerLink({
    className: 'asana',
    description: descFunc,
    projectName: projectFunc
  });

  container.parentNode.insertBefore(link, container.nextSibling);
});

// New UI
togglbutton.render('#right_pane__contents .SingleTaskPane:not(.toggl)', {observe: true}, function (elem) {

  var link, descFunc, projectFunc,
    container = $('.SingleTaskTitleRow', elem),
    description = $('.SingleTaskTitleRow .simpleTextarea', elem),
    project = $('.TaskProjectPill-projectName div', elem);

  descFunc = function () {
    return !!description ? description.value : "";
  };

  projectFunc = function () {
    return (project && project.textContent) || ($('.TaskAncestry-ancestorProjects', elem) && $('.TaskAncestry-ancestorProjects', elem).textContent) || "";
  };

  link = togglbutton.createTimerLink({
    className: 'asana-new',
    description: descFunc,
    projectName: projectFunc
  });

  container.after(link);
});

// Board view
togglbutton.render('.BoardCard.BoardColumnCardsContainer-item:not(.toggl)', {observe: true}, function (elem) {
  if (!!$('.toggl-button', elem)) {
    return;
  }
  var link,
    container = $('.BoardCardMetadata-left', elem),
    description = $('.BoardCard-name', elem).textContent,
    project = $('.SidebarItemRow.is-selected').textContent;

  link = togglbutton.createTimerLink({
    className: 'asana-board',
    description: description,
    projectName: project,
    buttonType: 'minimal'
  });

  container.appendChild(link);
});

// Board task detail view
togglbutton.render('.SingleTaskTitleRow:not(.toggl)', {observe: true}, function (elem) {
  if (!!$('.toggl-button', elem)) {
    return;
  }
  var link,
    container = $('.SingleTaskPaneToolbar', elem.parentNode),
    description = $('.SingleTaskTitleRow textarea', elem.parentNode).textContent,
    projectElement = $('.SingleTaskPane-projects .TaskProjectPill-projectName', elem.parentNode);

  link = togglbutton.createTimerLink({
    className: 'asana-board',
    description: description,
    projectName: projectElement ? projectElement.textContent : '',
    buttonType: 'minimal'
  });

  container.appendChild(link);
});

<|endoftext|>


<commit_before>$(document).ready(function() {
  var PER_PAGE = 50;
  var IMAGES = $.get('http://localhost:5000/images');

  var size = 78;
  var gender = 'neutral';
  var count = PER_PAGE;

  var filteredImages = function() {
    return IMAGES.then(function(images) {
      return _.filter(images, function(image) {
        return gender === 'neutral' || image.gender === gender;
      });
    });
  };

  var resizeImages = function() {
    var images = document.getElementsByClassName('image');
    var i;
    var image;

    for (i = 0; i < images.length; i++) {
      image = images[i];
      image.height = size;
      image.width = size;
    }
  };

  var showImages = function(options) {
    var from = options.from === undefined ? count : options.from;
    var to = options.to === undefined ? (from + PER_PAGE) : options.to;
    var append = !!options.append;

    var _preserves = null;

    filteredImages().then(function(filtered) {
      _preserves = filtered.length;
      return filtered.slice(from, to);
    }).then(function(images) {
      return _.map(images, function(i) {
        return ([
          ''
        ].join(''));
      });
    }).then(function(imageNodes) {
      if (append) {
        $('#images').append(imageNodes.join(''));
      } else {
        $('#images').html(imageNodes.join(''));

        $('#download-selected').addClass('disabled');
      }

      count = to;

      if (count >= _preserves) {
        count = _preserves;
        $('#load-more-container').html('');
      } else if ($('#load-more-container').html().trim().length === 0) {
        $('#load-more-container').html('<button type="button" id="load-more" class="button">Load More</button>');
      }
    });
  };

  // start
  showImages({});

  $('#load-more-container').on('click', '#load-more', function() {
    showImages({append: true});
  });

  $('select').change(function() {
    gender = this.value;

    showImages({from: 0, to: count, append: false});
  });

  var $sliderLabel = $('78px');

  $('#size-slider').slider({
    range: 'min',
    value: size,
    min: 32,
    max: 180,
    step: 1,
    create: function() {
      $('.ui-slider-handle').append($sliderLabel);
    },
    slide: function(event, ui) {
      $sliderLabel.html(ui.value + 'px');
      size = ui.value;
      resizeImages();
    }
  });

  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');

  var getFolderName = function() {
    var now = new Date();
    var month = ('0' + (now.getMonth() + 1)).slice(-2);
    var date = ('0' + now.getDate()).slice(-2);
    return ['diverseui', month, date].join('-');
  };

  var downloadImages = function(images, button) {
    if (!images.length) {
      return;
    }

    var zip = new JSZip();
    var i;
    var imageData;
    var folder = getFolderName();
    var initialText = button.innerHTML;

    if (window.ga) {
      ga('send', {
        hitType: 'event',
        eventCategory: 'Button',
        eventAction: 'Download',
        eventLabel: initialText,
        eventValue: images.length
      });
    }

    // Show LOADING if downloading more than 10 images
    if (images.length > 10) {
      button.innerHTML = 'LOADING...';
    }

    canvas.width = size;
    canvas.height = size;

    for (i = 0; i < images.length; i++) {
      context.drawImage(images[i], 0, 0, size, size);
      imageData = canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/, '');
      zip.file(folder + '/image-' + (i + 1) + '.png', imageData, {base64: true});
    }

    zip.generateAsync({type: 'blob'}).then(function(blob) {
      button.innerHTML = initialText;
      saveAs(blob, folder + '.zip');
    }, function(err) {
      button.innerHTML = initialText;
      console.log(err);
    });
  }

  $('#images').on('click', '.image', function() {
    $(this).toggleClass('selected-image');

    $('#download-selected').toggleClass('disabled', !$('.selected-image').length);
  });

  $('#download-all').on('click', function() {
    var button = this;
    var images = document.getElementsByClassName('image');
    downloadImages(images, button);
  });

  $('#download-selected').on('click', function() {
    var button = this;
    var images = document.getElementsByClassName('selected-image');
    downloadImages(images, button);
  });
});
<commit_msg>Change url to prod<commit_after>$(document).ready(function() {
  var PER_PAGE = 50;
  var IMAGES = $.get('https://www.diverseui.com/images');

  var size = 78;
  var gender = 'neutral';
  var count = PER_PAGE;

  var filteredImages = function() {
    return IMAGES.then(function(images) {
      return _.filter(images, function(image) {
        return gender === 'neutral' || image.gender === gender;
      });
    });
  };

  var resizeImages = function() {
    var images = document.getElementsByClassName('image');
    var i;
    var image;

    for (i = 0; i < images.length; i++) {
      image = images[i];
      image.height = size;
      image.width = size;
    }
  };

  var showImages = function(options) {
    var from = options.from === undefined ? count : options.from;
    var to = options.to === undefined ? (from + PER_PAGE) : options.to;
    var append = !!options.append;

    var _preserves = null;

    filteredImages().then(function(filtered) {
      _preserves = filtered.length;
      return filtered.slice(from, to);
    }).then(function(images) {
      return _.map(images, function(i) {
        return ([
          ''
        ].join(''));
      });
    }).then(function(imageNodes) {
      if (append) {
        $('#images').append(imageNodes.join(''));
      } else {
        $('#images').html(imageNodes.join(''));

        $('#download-selected').addClass('disabled');
      }

      count = to;

      if (count >= _preserves) {
        count = _preserves;
        $('#load-more-container').html('');
      } else if ($('#load-more-container').html().trim().length === 0) {
        $('#load-more-container').html('<button type="button" id="load-more" class="button">Load More</button>');
      }
    });
  };

  // start
  showImages({});

  $('#load-more-container').on('click', '#load-more', function() {
    showImages({append: true});
  });

  $('select').change(function() {
    gender = this.value;

    showImages({from: 0, to: count, append: false});
  });

  var $sliderLabel = $('78px');

  $('#size-slider').slider({
    range: 'min',
    value: size,
    min: 32,
    max: 180,
    step: 1,
    create: function() {
      $('.ui-slider-handle').append($sliderLabel);
    },
    slide: function(event, ui) {
      $sliderLabel.html(ui.value + 'px');
      size = ui.value;
      resizeImages();
    }
  });

  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');

  var getFolderName = function() {
    var now = new Date();
    var month = ('0' + (now.getMonth() + 1)).slice(-2);
    var date = ('0' + now.getDate()).slice(-2);
    return ['diverseui', month, date].join('-');
  };

  var downloadImages = function(images, button) {
    if (!images.length) {
      return;
    }

    var zip = new JSZip();
    var i;
    var imageData;
    var folder = getFolderName();
    var initialText = button.innerHTML;

    if (window.ga) {
      ga('send', {
        hitType: 'event',
        eventCategory: 'Button',
        eventAction: 'Download',
        eventLabel: initialText,
        eventValue: images.length
      });
    }

    // Show LOADING if downloading more than 10 images
    if (images.length > 10) {
      button.innerHTML = 'LOADING...';
    }

    canvas.width = size;
    canvas.height = size;

    for (i = 0; i < images.length; i++) {
      context.drawImage(images[i], 0, 0, size, size);
      imageData = canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/, '');
      zip.file(folder + '/image-' + (i + 1) + '.png', imageData, {base64: true});
    }

    zip.generateAsync({type: 'blob'}).then(function(blob) {
      button.innerHTML = initialText;
      saveAs(blob, folder + '.zip');
    }, function(err) {
      button.innerHTML = initialText;
      console.log(err);
    });
  }

  $('#images').on('click', '.image', function() {
    $(this).toggleClass('selected-image');

    $('#download-selected').toggleClass('disabled', !$('.selected-image').length);
  });

  $('#download-all').on('click', function() {
    var button = this;
    var images = document.getElementsByClassName('image');
    downloadImages(images, button);
  });

  $('#download-selected').on('click', function() {
    var button = this;
    var images = document.getElementsByClassName('selected-image');
    downloadImages(images, button);
  });
});
<|endoftext|>


<commit_before>function BaseMap(){
}
BaseMap.prototype.distanceBetween = function(waypoint1, waypoint2) {
  var rm = 6371*1000; //radius in meters
  var rad_per_deg = Math.PI/180;
  var lat1 = waypoint1[0]*rad_per_deg;
  var lng1 = waypoint1[1]*rad_per_deg;
  var lat2 = waypoint2[0]*rad_per_deg;
  var lng2 = waypoint2[1]*rad_per_deg;
  var dlat = lat2 - lat1;
  var dlng = lng2 - lng1;
  var a = Math.pow((dlat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow((dlng/2), 2);
  var c = 2 * Math.asin(Math.sqrt(a));
  return rm * c; //Delta in meters
};

BaseMap.prototype.lineDistance = function(waypoints) {
  var distance = 0;
  for(var i = 0; i< waypoints.length - 1; i++){
    distance = distance +  this.distanceBetween(waypoints[i], waypoints[i + 1]);
  }
  return distance;
};

// Add a marker to the map.
// Options:
// {
//   lat: <latitude (required)>,
//   lng: <longitude (required)>,
//   infoWindow: <info window content>,
//   label: <label text>,
//   icon: {
//           image: <url path>,
//           size: [<width>, <height>],
//           sprite_position: [<width>, <height>],
//           anchor: [<width>, <height>],
//           popupanchor: [<width>, <height>]
//   },
//   click: {
//             active: <clickable>,
//             callback: <click function>
//   },
//   drag: {
//           active: <draggable>,
//           callback: <drag end function ( obj = { position: {lat: <float>, lng: <float> } } )>
//   }
// }
BaseMap.prototype.addMarker = function(options) {
  throw 'Method undefined';
};

// Remove a marker from the map.
// Marker: Map marker object
BaseMap.prototype.removeMarker = function(marker) {
  throw 'Method undefined';
};

// Remove all markers from the map.
BaseMap.prototype.removeMarkers = function() {
  throw 'Method undefined';
};

// Close all info windows
BaseMap.prototype.hideInfoWindows = function() {
  throw 'Method undefined';
};

// Close all info windows and open only the info window
// of the given marker
BaseMap.prototype.showInfoWindows = function(marker) {
  throw 'Method undefined';
};

// Add a circle to the map
// Options:
// {
//   lat: <latitude (required)>,
//   lng: <longitude (required)>,
//   radius: <circle radius (require)>,
//   strokeColor: <stroke color>,
//   strokeOpacity: <strike opacity>,
//   strokeWeight: <stroke line weight>,
//   fillColor: <fill color>,
//   fillOpacity: <fill opacity>
// }
BaseMap.prototype.addCircle= function(options) {
  throw 'Method undefined';
};

// Add a drawPolyline to the map
// Options:
//   {
//     path: <bounds (required)>,
//     strokeColor: <stroke color>,
//     strokeOpacity: <stroke opacity>,
//     strokeWeight:  <stroke weight>,
//     fillColor: <fill color>,
//     fillOpacity: <fill opacity>
//   }

BaseMap.prototype.drawPolyline= function(options) {
  throw 'Method undefined';
};

// Center map based on the markers given
BaseMap.prototype.fitBoundsWithMarkers = function(markers) {
  throw 'Method undefined';
};
<commit_msg>fix document<commit_after>function BaseMap(){
}
BaseMap.prototype.distanceBetween = function(waypoint1, waypoint2) {
  var rm = 6371*1000; //radius in meters
  var rad_per_deg = Math.PI/180;
  var lat1 = waypoint1[0]*rad_per_deg;
  var lng1 = waypoint1[1]*rad_per_deg;
  var lat2 = waypoint2[0]*rad_per_deg;
  var lng2 = waypoint2[1]*rad_per_deg;
  var dlat = lat2 - lat1;
  var dlng = lng2 - lng1;
  var a = Math.pow((dlat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow((dlng/2), 2);
  var c = 2 * Math.asin(Math.sqrt(a));
  return rm * c; //Delta in meters
};

BaseMap.prototype.lineDistance = function(waypoints) {
  var distance = 0;
  for(var i = 0; i< waypoints.length - 1; i++){
    distance = distance +  this.distanceBetween(waypoints[i], waypoints[i + 1]);
  }
  return distance;
};

// Add a marker to the map.
// Options:
// {
//   lat: <latitude (required)>,
//   lng: <longitude (required)>,
//   infoWindow: <info window content>,
//   label: <label text>,
//   icon: {
//           image: <url path>,
//           size: [<width>, <height>],
//           sprite_position: [<width>, <height>],
//           anchor: [<width>, <height>],
//           popup_anchor: [<width>, <height>]
//   },
//   click: {
//             active: <clickable>,
//             callback: <click function>
//   },
//   drag: {
//           active: <draggable>,
//           callback: <drag end function ( obj = { position: {lat: <float>, lng: <float> } } )>
//   }
// }
BaseMap.prototype.addMarker = function(options) {
  throw 'Method undefined';
};

// Remove a marker from the map.
// Marker: Map marker object
BaseMap.prototype.removeMarker = function(marker) {
  throw 'Method undefined';
};

// Remove all markers from the map.
BaseMap.prototype.removeMarkers = function() {
  throw 'Method undefined';
};

// Close all info windows
BaseMap.prototype.hideInfoWindows = function() {
  throw 'Method undefined';
};

// Close all info windows and open only the info window
// of the given marker
BaseMap.prototype.showInfoWindows = function(marker) {
  throw 'Method undefined';
};

// Add a circle to the map
// Options:
// {
//   lat: <latitude (required)>,
//   lng: <longitude (required)>,
//   radius: <circle radius (require)>,
//   strokeColor: <stroke color>,
//   strokeOpacity: <strike opacity>,
//   strokeWeight: <stroke line weight>,
//   fillColor: <fill color>,
//   fillOpacity: <fill opacity>
// }
BaseMap.prototype.addCircle= function(options) {
  throw 'Method undefined';
};

// Add a drawPolyline to the map
// Options:
//   {
//     path: <bounds (required)>,
//     strokeColor: <stroke color>,
//     strokeOpacity: <stroke opacity>,
//     strokeWeight:  <stroke weight>,
//     fillColor: <fill color>,
//     fillOpacity: <fill opacity>
//   }

BaseMap.prototype.drawPolyline= function(options) {
  throw 'Method undefined';
};

// Center map based on the markers given
BaseMap.prototype.fitBoundsWithMarkers = function(markers) {
  throw 'Method undefined';
};
<|endoftext|>


<commit_before>/**
 * Defines bout events.
 */
export default class BoutEvent {

  /**
   * Creates a new bout event.
   *
   * @param {String} name to use for the event.
   * @param {String} bout emitted in the event.
   */
  constructor(name, bout) {

    /**
     * @type {String} Stores the name.
     * @private
     */
    this._name = name;

    /**
     * @type {String} Stores the bout.
     * @private
     */
    this._bout = bout;
  }

  /**
   * @returns {String} name of the event.
   */
  get name() {
    return this._name;
  }

  /**
   * @returns {String} bout of the event.
   */
  get bout() {
    return this._bout;
  }

  /**
   * @returns {string} representation of this enum.
   */
  toString() {
    return `BoutEvent.${this.name}`;
  }
}

// Data events - bouts

BoutEvent.BOUT = new BoutEvent("BOUT", "bout");
BoutEvent.BOUT_STARTED = new BoutEvent("BOUT_STARTED", "boutStarted");
BoutEvent.BOUT_FINISHED = new BoutEvent("BOUT_FINISHED", "boutFinished");
BoutEvent.BOUT_DELETED = new BoutEvent("BOUT_DELETED", "boutDeleted");

// Do not allow changes
Object.freeze(BoutEvent);

<commit_msg>Bout threshold reached event<commit_after>/**
 * Defines bout events.
 */
export default class BoutEvent {

  /**
   * Creates a new bout event.
   *
   * @param {String} name to use for the event.
   * @param {String} bout emitted in the event.
   */
  constructor(name, bout) {

    /**
     * @type {String} Stores the name.
     * @private
     */
    this._name = name;

    /**
     * @type {String} Stores the bout.
     * @private
     */
    this._bout = bout;
  }

  /**
   * @returns {String} name of the event.
   */
  get name() {
    return this._name;
  }

  /**
   * @returns {String} bout of the event.
   */
  get bout() {
    return this._bout;
  }

  /**
   * @returns {string} representation of this enum.
   */
  toString() {
    return `BoutEvent.${this.name}`;
  }
}

// Data events - bouts

BoutEvent.BOUT = new BoutEvent("BOUT", "bout");
BoutEvent.BOUT_STARTED = new BoutEvent("BOUT_STARTED", "boutStarted");
BoutEvent.BOUT_FINISHED = new BoutEvent("BOUT_FINISHED", "boutFinished");
BoutEvent.BOUT_DELETED = new BoutEvent("BOUT_DELETED", "boutDeleted");
BoutEvent.BOUT_THRESHOLD_REACHED = new BoutEvent("BOUT_THRESHOLD_REACHED", "boutThresholdReached");

// Do not allow changes
Object.freeze(BoutEvent);

<|endoftext|>


<commit_before>// 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.

import {existsSync} from 'fs'
import {join} from 'path'
import {PACKAGE_DIR, BIN_DIR} from './paths'
import {pickNonFalsy} from './util'
import {spawnSync} from 'child_process'

export function assertBinaryExists(targetBinary:string) {
  if (!existsSync(getBinaryPath(targetBinary)))
    throw new Error(`Binary “${targetBinary}” not found.`)
}

export function getBinaryPath(targetBinary:string) {
  const BIN = join(BIN_DIR, targetBinary)
  return process.platform === 'win32' ? `${BIN}.cmd` : BIN
}

/**
 * Find the binary and run it with the parent IO attached to it.
 */
export function runBin(targetBinary:string, args:string[], env?:Object) {
  const FOUND_BINARY = getBinaryPath(targetBinary)
  return spawnSync(FOUND_BINARY, args, {
    cwd: PACKAGE_DIR,
    env: pickNonFalsy(env),
    stdio: 'inherit',
  })
}

/**
 * Find the binary and run it.
 */
export function runBinPiped(targetBinary:string, args:string[], env?:Object) {
  const FOUND_BINARY = getBinaryPath(targetBinary)
  return spawnSync(FOUND_BINARY, args, {
    cwd: PACKAGE_DIR,
    env: pickNonFalsy(env),
  })
}
<commit_msg>Put env inside ctrine var<commit_after>// 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.

import {existsSync} from 'fs'
import {join} from 'path'
import {PACKAGE_DIR, BIN_DIR} from './paths'
import {pickNonFalsy} from './util'
import {spawnSync} from 'child_process'

export function assertBinaryExists(targetBinary:string) {
  if (!existsSync(getBinaryPath(targetBinary)))
    throw new Error(`Binary “${targetBinary}” not found.`)
}

export function getBinaryPath(targetBinary:string) {
  const BIN = join(BIN_DIR, targetBinary)
  return process.platform === 'win32' ? `${BIN}.cmd` : BIN
}

/**
 * Find the binary and run it with the parent IO attached to it.
 */
export function runBin(targetBinary:string, args:string[], env?:Object) {
  const FOUND_BINARY = getBinaryPath(targetBinary)
  return spawnSync(FOUND_BINARY, args, {
    cwd: PACKAGE_DIR,
    env: {ctrine: JSON.stringify(pickNonFalsy(env))},
    stdio: 'inherit',
  })
}

/**
 * Find the binary and run it.
 */
export function runBinPiped(targetBinary:string, args:string[], env?:Object) {
  const FOUND_BINARY = getBinaryPath(targetBinary)
  return spawnSync(FOUND_BINARY, args, {
    cwd: PACKAGE_DIR,
    env: {ctrine: JSON.stringify(pickNonFalsy(env))},
  })
}
<|endoftext|>