<commit_before>import React from 'react';
import {
  StyleSheet,
  Text,
  View,
  TextInput,
  AlertIOS,
  AsyncStorage,
  TouchableHighlight,
  Image
} from 'react-native';

var STORAGE_KEY = 'id_token';

export default class Memories extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      image: {},
      imageList: [
        {
          _id: '',
          uri: 'http://r.ddmcdn.com/s_f/o_1/cx_633/cy_0/cw_1725/ch_1725/w_720/APL/uploads/2014/11/too-cute-doggone-it-video-playlist.jpg'
        },
        {
          id: '',
          uri: 'http://www.nextavenue.org/wp-content/uploads/2015/08/The-People-You-Meet-While-Traveling-466243609.jpg'
        },
        {
          id: '',
          uri: 'http://www.simplyrecipes.com/wp-content/uploads/2016/10/2016-10-04-PumpkinIceCream-9.jpg'
        }
      ]
    };
  }

  _navigate(image) {
    console.log('changing scenes!');
    this.props.navigator.push({
      name: 'Memory',
      passProps: {
        'image': {uri: image.uri},
        'id': image._id,
        'prevScene': 'Memories'
      }
    });
  }

  fetchImages() {
    fetch('https://invalid-memories-greenfield.herokuapp.com/api/memories/all', {
      method: 'GET'
    })
    .then(function(images) {
      //NOTE: Expecting response to be an array of objects with properties uri and _id
      this.setState({imageList: images});
    });
  }

  componentDidMount() {
    // TODO: fetchImages();
  }

  render() {
    return (
      <View style={styles.container}>
        {this.state.imageList.map(image =>
          <TouchableHighlight onPress={this._navigate.bind(this, image)}>
            <Image style={{width:150, height:150}} source={{uri: image.uri}}/>
          </TouchableHighlight>)}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'space-around',
  }
});
<commit_msg>(test) Try with s3 public url<commit_after>import React from 'react';
import {
  StyleSheet,
  Text,
  View,
  TextInput,
  AlertIOS,
  AsyncStorage,
  TouchableHighlight,
  Image
} from 'react-native';

var STORAGE_KEY = 'id_token';

export default class Memories extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      image: {},
      imageList: [
        {
          _id: '',
          uri: 'https://s3-us-west-1.amazonaws.com/invalidmemories/images/9961254d-064c-48ea-9ed5-060772f0199b-large.jpg'
        },
        {
          id: '',
          uri: 'http://www.nextavenue.org/wp-content/uploads/2015/08/The-People-You-Meet-While-Traveling-466243609.jpg'
        },
        {
          id: '',
          uri: 'http://www.simplyrecipes.com/wp-content/uploads/2016/10/2016-10-04-PumpkinIceCream-9.jpg'
        }
      ]
    };
  }

  _navigate(image) {
    console.log('changing scenes!');
    this.props.navigator.push({
      name: 'Memory',
      passProps: {
        'image': {uri: image.uri},
        'id': image._id,
        'prevScene': 'Memories'
      }
    });
  }

  fetchImages() {
    fetch('https://invalid-memories-greenfield.herokuapp.com/api/memories/all', {
      method: 'GET'
    })
    .then(function(images) {
      //NOTE: Expecting response to be an array of objects with properties uri and _id
      this.setState({imageList: images});
    });
  }

  componentDidMount() {
    // TODO: fetchImages();
  }

  render() {
    return (
      <View style={styles.container}>
        {this.state.imageList.map(image =>
          <TouchableHighlight onPress={this._navigate.bind(this, image)}>
            <Image style={{width:150, height:150}} source={{uri: image.uri}}/>
          </TouchableHighlight>)}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'space-around',
  }
});
<|endoftext|>


<commit_before>import _ from 'lodash'

import { PubSub as pubSub } from '../models'

export function addModel(dbAdapter) {
  /**
   * @constructor
   */
  var Timeline = function(params) {
    this.id = params.id
    this.intId = params.intId
    this.name = params.name
    this.userId = params.userId
    if (parseInt(params.createdAt, 10))
      this.createdAt = params.createdAt
    if (parseInt(params.updatedAt, 10))
      this.updatedAt = params.updatedAt
    this.offset = parseInt(params.offset, 10) || 0
    this.limit = parseInt(params.limit, 10) || 30
    this.currentUser = params.currentUser
  }

  Timeline.className = Timeline
  Timeline.namespace = "timeline"

  Object.defineProperty(Timeline.prototype, 'name', {
    get: function() { return this.name_ },
    set: function(newValue) {
      newValue ? this.name_ = newValue.trim() : this.name_ = ''
    }
  })

  /**
   * Adds the specified post to all timelines where it needs to appear
   * (the timelines of the feeds to which it is posted, the River of News
   * timeline of the posting user and the River of News timelines of all
   * subscribers of the feeds to which it is posted).
   */

  Timeline.publishPost = async function(post) {
    const currentTime = new Date().getTime()

    // We can use post.timelineIds here instead of post.getPostedToIds
    // because we are about to create that post and have just received
    // a request from user, so postedToIds == timelineIds here
    const timelines = await dbAdapter.getTimelinesByIds(post.timelineIds)

    let promises = timelines.map(async (timeline) => {
      const feed = await timeline.getUser()
      await feed.updateLastActivityAt()

      return timeline.getSubscribersRiversOfNewsIntIds()
    })

    const allSubscribedTimelineIds = _.flatten(await Promise.all(promises))
    const allTimelines = _.uniq(_.union(post.feedIntIds, allSubscribedTimelineIds))
    await dbAdapter.setPostUpdatedAt(post.id, currentTime)
    await dbAdapter.insertPostIntoFeeds(allTimelines, post.id)
    await pubSub.newPost(post.id)
  }

  Timeline.getObjectsByIds = async function (objectIds){
    return dbAdapter.getTimelinesByIds(objectIds)
  }

  Timeline.prototype.validate = async function() {
    const valid = this.name
      && this.name.length > 0
      && this.userId
      && this.userId.length > 0

    if (!valid)
      throw new Error('Invalid')
  }

  Timeline.prototype.create = async function() {
    return this._createTimeline()
  }

  Timeline.prototype._createTimeline = async function() {
    const currentTime = new Date().getTime()

    await this.validate()

    const payload = {
      'name':      this.name,
      'userId':    this.userId,
      'createdAt': currentTime.toString(),
      'updatedAt': currentTime.toString()
    }

    this.id = await dbAdapter.createTimeline(payload)

    this.createdAt = currentTime
    this.updatedAt = currentTime

    return this
  }

  Timeline.prototype.getPostIds = async function(offset, limit) {
    if (_.isUndefined(offset))
      offset = this.offset
    else if (offset < 0)
      offset = 0

    // -1 = special magic number, meaning “do not use limit defaults,
    // do not use passed in value, use 0 instead". this is at the very least
    // used in Timeline.mergeTo()
    if (_.isUndefined(limit))
      limit = this.limit
    else if (limit < 0)
      limit = 0

    let valid = await this.canShow(this.currentUser)

    if (!valid)
      return []

    this.postIds = await dbAdapter.getTimelinePostsRange(this.intId, offset, limit)
    return this.postIds
  }

  Timeline.prototype.getFeedPosts = async function(offset, limit, params, customFeedIds) {
    if (_.isUndefined(offset))
      offset = this.offset
    else if (offset < 0)
      offset = 0

    // -1 = special magic number, meaning “do not use limit defaults,
    // do not use passed in value, use 0 instead". this is at the very least
    // used in Timeline.mergeTo()
    if (_.isUndefined(limit))
      limit = this.limit
    else if (limit < 0)
      limit = 0

    let valid = await this.canShow(this.currentUser)

    if (!valid)
      return []

    let feedIds = [this.intId]
    if (customFeedIds){
      feedIds = customFeedIds
    }

    return dbAdapter.getFeedsPostsRange(feedIds, offset, limit, params)
  }

  Timeline.prototype.getPosts = async function(offset, limit) {
    let reader = this.currentUser ? (await dbAdapter.getUserById(this.currentUser)) : null
    let banIds = reader ? (await reader.getBanIds()) : []
    let readerOwnFeeds = reader ? (await reader.getPublicTimelinesIntIds()) : []
    let feedOwner = await this.getUser()

    let posts
    if (this.name != 'MyDiscussions') {
      posts = await this.getFeedPosts(offset, limit, {currentUser: this.currentUser})
    } else {
      const myDiscussionsFeedSourcesIds = await Promise.all([feedOwner.getCommentsTimelineIntId(), feedOwner.getLikesTimelineIntId()])
      posts = await this.getFeedPosts(offset, limit, {currentUser: this.currentUser}, myDiscussionsFeedSourcesIds)
    }
    let postIds = posts.map((p)=>{
      return p.id
    })

    if (reader) {
      let oldestPostTime
      if (posts[posts.length - 1]) {
        oldestPostTime = posts[posts.length - 1].updatedAt
      }

      let localBumps = await dbAdapter.getUserLocalBumps(reader.id, oldestPostTime)
      let localBumpedPostIds = localBumps.map((bump) => { return bump.postId })

      let absentPostIds = _.difference(localBumpedPostIds, postIds)
      if (absentPostIds.length > 0){
        let localBumpedPosts = await dbAdapter.getPostsByIds(absentPostIds, {currentUser: this.currentUser})
        localBumpedPosts = _.sortBy(localBumpedPosts, (post)=>{
          return _.indexOf(absentPostIds, post.id)
        })
        posts = localBumpedPosts.concat(posts)
      }

      for (let p of posts){
        if(_.includes(localBumpedPostIds, p.id)){
          let bump = _.find(localBumps, (b)=>{ return b.postId === p.id })
          p.bumpedAt = bump.bumpedAt
        }
      }
    }

    posts.sort((p1, p2)=>{
      let t1 = p1.updatedAt
      let t2 = p2.updatedAt
      if (p1.bumpedAt){
        t1 = p1.bumpedAt
      }
      if (p2.bumpedAt){
        t2 = p2.bumpedAt
      }
      return t2 - t1
    })

    let uids = _.uniq(posts.map(post => post.userId))
    let users = (await dbAdapter.getUsersByIds(uids)).filter(Boolean)
    let bans = await dbAdapter.getBannedUserIds(uids)

    let usersCache = {}

    for (let i = 0; i < users.length; i++) {
      let user = users[i];
      usersCache[user.id] = [user, bans[i] || []];
    }

    async function userById(id) {
      if (!(id in usersCache)) {
        let user = await dbAdapter.getUserById(id)

        if (!user) {
          throw new Error(`no user for id=${id}`)
        }

        let bans = await user.getBanIds()

        usersCache[id] = [user, bans]
      }

      return usersCache[id]
    }

    posts = await Promise.all(posts.map(async (post) => {
      if (post.userId === this.currentUser) {
        // shortcut for the author
        return post
      }

      let author, reverseBanIds

      try {
        [author, reverseBanIds] = await userById(post.userId)
      } catch (e) {
        throw new Error(`did not find user-object of author of post with id=${post.id}\nPREVIOUS: ${e.message}`)
      }

      let readerBannedAuthor = (banIds.indexOf(post.userId) >= 0)
      let authorBannedReader = (reverseBanIds.indexOf(this.currentUser) >= 0)

      if (readerBannedAuthor || authorBannedReader)
        return null

      if (author.isPrivate) {
        if (feedOwner.isPrivate !== '1' && (this.isPosts()) || this.isDirects()) {
          return post
        }

        if (_.intersection(post.destinationFeedIds, readerOwnFeeds).length > 0) {
          return post
        }

        if (reader && _.intersection(post.destinationFeedIds, reader.subscribedFeedIds).length > 0) {
          return post
        }

        let postTimelines = await post.getTimelines()
        let promises = postTimelines.map(async (timeline) => {
          if (!timeline.isPosts() && !timeline.isDirects()) {
            return false
          }

          return timeline.canShow(this.currentUser)
        })

        let wasPostedToReadableFeed = _.any(await Promise.all(promises))

        if (!wasPostedToReadableFeed) {
          return null
        }
      }

      return post
    }))

    this.posts = posts.filter(Boolean)

    return this.posts
  }

  /**
   * Merges contents of this timeline into timeline specified by id
   * @param timelineId
   */
  Timeline.prototype.mergeTo = async function(timelineId) {
    await dbAdapter.createMergedPostsTimeline(timelineId, timelineId, this.intId)

    let timeline = await dbAdapter.getTimelineByIntId(timelineId)
    let postIds = await timeline.getPostIds(0, -1)

    await dbAdapter.createPostsUsagesInTimeline(postIds, [timelineId])
  }

  Timeline.prototype.unmerge = async function(feedIntId) {
    let postIds = await dbAdapter.getTimelinesIntersectionPostIds(this.intId, feedIntId)

    await Promise.all(_.flatten(postIds.map((postId) =>
      dbAdapter.withdrawPostFromFeeds([feedIntId], postId)
    )))

    return
  }

  Timeline.prototype.getUser = function() {
    return dbAdapter.getFeedOwnerById(this.userId)
  }

  /**
   * Returns the IDs of users subscribed to this timeline, as a promise.
   */
  Timeline.prototype.getSubscriberIds = async function(includeSelf) {
    let userIds = await dbAdapter.getTimelineSubscribersIds(this.id)

    // A user is always subscribed to their own posts timeline.
    if (includeSelf && (this.isPosts() || this.isDirects())) {
      userIds = _.uniq(userIds.concat([this.userId]))
    }

    this.subscriberIds = userIds

    return userIds
  }

  Timeline.prototype.getSubscribers = async function(includeSelf) {
    let users = await dbAdapter.getTimelineSubscribers(this.intId)

    if (includeSelf && (this.isPosts() || this.isDirects())) {
      let currentUser = await dbAdapter.getUserById(this.userId)
      users = users.concat(currentUser)
    }

    this.subscribers = users

    return this.subscribers
  }

  /**
   * Returns the list of the 'River of News' timelines of all subscribers to this
   * timeline.
   */
  Timeline.prototype.getSubscribedTimelineIds = async function() {
    var subscribers = await this.getSubscribers(true);
    return await Promise.all(subscribers.map((subscriber) => subscriber.getRiverOfNewsTimelineId()))
  }

  Timeline.prototype.getSubscribersRiversOfNewsIntIds = async function() {
    var subscribers = await this.getSubscribers(true);
    return await Promise.all(subscribers.map((subscriber) => subscriber.getRiverOfNewsTimelineIntId()))
  }

  Timeline.prototype.isRiverOfNews = function() {
    return this.name === "RiverOfNews"
  }

  Timeline.prototype.isPosts = function() {
    return this.name === "Posts"
  }

  Timeline.prototype.isLikes = function() {
    return this.name === "Likes"
  }

  Timeline.prototype.isComments = function() {
    return this.name === "Comments"
  }

  Timeline.prototype.isDirects = function() {
    return this.name === "Directs"
  }

  Timeline.prototype.isHides = function() {
    return this.name === "Hides"
  }

  Timeline.prototype.updatePost = async function(postId, action) {
    if (action === "like") {
      let postInTimeline = await dbAdapter.isPostPresentInTimeline(this.intId, postId)

      if (postInTimeline) {
        // For the time being, like does not bump post if it is already present in timeline
        return
      }
    }

    var currentTime = new Date().getTime()

    if (action === "like") {
      await dbAdapter.insertPostIntoFeeds([this.intId], postId)
      if(this.isRiverOfNews()) {
        await dbAdapter.createLocalBump(postId, this.userId)
      }
    } else {
      await Promise.all([
        dbAdapter.insertPostIntoFeeds([this.intId], postId),
        dbAdapter.setPostUpdatedAt(postId, currentTime)
      ])
    }

    // does not update lastActivity on like
    if (action === 'like') {
      return
    }

    const feed = await this.getUser()
    await feed.updateLastActivityAt()
  }

  Timeline.prototype.canShow = async function(userId) {
    // owner can read her posts
    if (this.userId === userId)
      return true

    // if post is already in user's feed then she can read it
    if (this.isDirects())
      return this.userId === userId

    // this is a public feed, anyone can read public posts, this is
    // a free country
    var user = await this.getUser()
    if (user && user.isPrivate !== '1')
      return true

    // otherwise user can view post if and only if she is subscriber
    var userIds = await this.getSubscriberIds()
    return userIds.indexOf(userId) >= 0
  }

  return Timeline
}
<commit_msg>Fix incorrect posts bubbling.<commit_after>import _ from 'lodash'

import { PubSub as pubSub } from '../models'

export function addModel(dbAdapter) {
  /**
   * @constructor
   */
  var Timeline = function(params) {
    this.id = params.id
    this.intId = params.intId
    this.name = params.name
    this.userId = params.userId
    if (parseInt(params.createdAt, 10))
      this.createdAt = params.createdAt
    if (parseInt(params.updatedAt, 10))
      this.updatedAt = params.updatedAt
    this.offset = parseInt(params.offset, 10) || 0
    this.limit = parseInt(params.limit, 10) || 30
    this.currentUser = params.currentUser
  }

  Timeline.className = Timeline
  Timeline.namespace = "timeline"

  Object.defineProperty(Timeline.prototype, 'name', {
    get: function() { return this.name_ },
    set: function(newValue) {
      newValue ? this.name_ = newValue.trim() : this.name_ = ''
    }
  })

  /**
   * Adds the specified post to all timelines where it needs to appear
   * (the timelines of the feeds to which it is posted, the River of News
   * timeline of the posting user and the River of News timelines of all
   * subscribers of the feeds to which it is posted).
   */

  Timeline.publishPost = async function(post) {
    const currentTime = new Date().getTime()

    // We can use post.timelineIds here instead of post.getPostedToIds
    // because we are about to create that post and have just received
    // a request from user, so postedToIds == timelineIds here
    const timelines = await dbAdapter.getTimelinesByIds(post.timelineIds)

    let promises = timelines.map(async (timeline) => {
      const feed = await timeline.getUser()
      await feed.updateLastActivityAt()

      return timeline.getSubscribersRiversOfNewsIntIds()
    })

    const allSubscribedTimelineIds = _.flatten(await Promise.all(promises))
    const allTimelines = _.uniq(_.union(post.feedIntIds, allSubscribedTimelineIds))
    await dbAdapter.setPostUpdatedAt(post.id, currentTime)
    await dbAdapter.insertPostIntoFeeds(allTimelines, post.id)
    await pubSub.newPost(post.id)
  }

  Timeline.getObjectsByIds = async function (objectIds){
    return dbAdapter.getTimelinesByIds(objectIds)
  }

  Timeline.prototype.validate = async function() {
    const valid = this.name
      && this.name.length > 0
      && this.userId
      && this.userId.length > 0

    if (!valid)
      throw new Error('Invalid')
  }

  Timeline.prototype.create = async function() {
    return this._createTimeline()
  }

  Timeline.prototype._createTimeline = async function() {
    const currentTime = new Date().getTime()

    await this.validate()

    const payload = {
      'name':      this.name,
      'userId':    this.userId,
      'createdAt': currentTime.toString(),
      'updatedAt': currentTime.toString()
    }

    this.id = await dbAdapter.createTimeline(payload)

    this.createdAt = currentTime
    this.updatedAt = currentTime

    return this
  }

  Timeline.prototype.getPostIds = async function(offset, limit) {
    if (_.isUndefined(offset))
      offset = this.offset
    else if (offset < 0)
      offset = 0

    // -1 = special magic number, meaning “do not use limit defaults,
    // do not use passed in value, use 0 instead". this is at the very least
    // used in Timeline.mergeTo()
    if (_.isUndefined(limit))
      limit = this.limit
    else if (limit < 0)
      limit = 0

    let valid = await this.canShow(this.currentUser)

    if (!valid)
      return []

    this.postIds = await dbAdapter.getTimelinePostsRange(this.intId, offset, limit)
    return this.postIds
  }

  Timeline.prototype.getFeedPosts = async function(offset, limit, params, customFeedIds) {
    if (_.isUndefined(offset))
      offset = this.offset
    else if (offset < 0)
      offset = 0

    // -1 = special magic number, meaning “do not use limit defaults,
    // do not use passed in value, use 0 instead". this is at the very least
    // used in Timeline.mergeTo()
    if (_.isUndefined(limit))
      limit = this.limit
    else if (limit < 0)
      limit = 0

    let valid = await this.canShow(this.currentUser)

    if (!valid)
      return []

    let feedIds = [this.intId]
    if (customFeedIds){
      feedIds = customFeedIds
    }

    return dbAdapter.getFeedsPostsRange(feedIds, offset, limit, params)
  }

  Timeline.prototype.getPosts = async function(offset, limit) {
    let reader = this.currentUser ? (await dbAdapter.getUserById(this.currentUser)) : null
    let banIds = reader ? (await reader.getBanIds()) : []
    let readerOwnFeeds = reader ? (await reader.getPublicTimelinesIntIds()) : []
    let feedOwner = await this.getUser()

    let posts
    if (this.name != 'MyDiscussions') {
      posts = await this.getFeedPosts(offset, limit, {currentUser: this.currentUser})
    } else {
      const myDiscussionsFeedSourcesIds = await Promise.all([feedOwner.getCommentsTimelineIntId(), feedOwner.getLikesTimelineIntId()])
      posts = await this.getFeedPosts(offset, limit, {currentUser: this.currentUser}, myDiscussionsFeedSourcesIds)
    }
    let postIds = posts.map((p)=>{
      return p.id
    })

    if (reader && this.name == 'RiverOfNews') {
      let oldestPostTime
      if (posts[posts.length - 1]) {
        oldestPostTime = posts[posts.length - 1].updatedAt
      }

      let localBumps = await dbAdapter.getUserLocalBumps(reader.id, oldestPostTime)
      let localBumpedPostIds = localBumps.map((bump) => { return bump.postId })

      let absentPostIds = _.difference(localBumpedPostIds, postIds)
      if (absentPostIds.length > 0){
        let localBumpedPosts = await dbAdapter.getPostsByIds(absentPostIds, {currentUser: this.currentUser})
        localBumpedPosts = _.sortBy(localBumpedPosts, (post)=>{
          return _.indexOf(absentPostIds, post.id)
        })
        posts = localBumpedPosts.concat(posts)
      }

      for (let p of posts){
        if(_.includes(localBumpedPostIds, p.id)){
          let bump = _.find(localBumps, (b)=>{ return b.postId === p.id })
          p.bumpedAt = bump.bumpedAt
        }
      }
    }

    posts.sort((p1, p2)=>{
      let t1 = p1.updatedAt
      let t2 = p2.updatedAt
      if (p1.bumpedAt){
        t1 = p1.bumpedAt
      }
      if (p2.bumpedAt){
        t2 = p2.bumpedAt
      }
      return t2 - t1
    })

    let uids = _.uniq(posts.map(post => post.userId))
    let users = (await dbAdapter.getUsersByIds(uids)).filter(Boolean)
    let bans = await dbAdapter.getBannedUserIds(uids)

    let usersCache = {}

    for (let i = 0; i < users.length; i++) {
      let user = users[i];
      usersCache[user.id] = [user, bans[i] || []];
    }

    async function userById(id) {
      if (!(id in usersCache)) {
        let user = await dbAdapter.getUserById(id)

        if (!user) {
          throw new Error(`no user for id=${id}`)
        }

        let bans = await user.getBanIds()

        usersCache[id] = [user, bans]
      }

      return usersCache[id]
    }

    posts = await Promise.all(posts.map(async (post) => {
      if (post.userId === this.currentUser) {
        // shortcut for the author
        return post
      }

      let author, reverseBanIds

      try {
        [author, reverseBanIds] = await userById(post.userId)
      } catch (e) {
        throw new Error(`did not find user-object of author of post with id=${post.id}\nPREVIOUS: ${e.message}`)
      }

      let readerBannedAuthor = (banIds.indexOf(post.userId) >= 0)
      let authorBannedReader = (reverseBanIds.indexOf(this.currentUser) >= 0)

      if (readerBannedAuthor || authorBannedReader)
        return null

      if (author.isPrivate) {
        if (feedOwner.isPrivate !== '1' && (this.isPosts()) || this.isDirects()) {
          return post
        }

        if (_.intersection(post.destinationFeedIds, readerOwnFeeds).length > 0) {
          return post
        }

        if (reader && _.intersection(post.destinationFeedIds, reader.subscribedFeedIds).length > 0) {
          return post
        }

        let postTimelines = await post.getTimelines()
        let promises = postTimelines.map(async (timeline) => {
          if (!timeline.isPosts() && !timeline.isDirects()) {
            return false
          }

          return timeline.canShow(this.currentUser)
        })

        let wasPostedToReadableFeed = _.any(await Promise.all(promises))

        if (!wasPostedToReadableFeed) {
          return null
        }
      }

      return post
    }))

    this.posts = posts.filter(Boolean)

    return this.posts
  }

  /**
   * Merges contents of this timeline into timeline specified by id
   * @param timelineId
   */
  Timeline.prototype.mergeTo = async function(timelineId) {
    await dbAdapter.createMergedPostsTimeline(timelineId, timelineId, this.intId)

    let timeline = await dbAdapter.getTimelineByIntId(timelineId)
    let postIds = await timeline.getPostIds(0, -1)

    await dbAdapter.createPostsUsagesInTimeline(postIds, [timelineId])
  }

  Timeline.prototype.unmerge = async function(feedIntId) {
    let postIds = await dbAdapter.getTimelinesIntersectionPostIds(this.intId, feedIntId)

    await Promise.all(_.flatten(postIds.map((postId) =>
      dbAdapter.withdrawPostFromFeeds([feedIntId], postId)
    )))

    return
  }

  Timeline.prototype.getUser = function() {
    return dbAdapter.getFeedOwnerById(this.userId)
  }

  /**
   * Returns the IDs of users subscribed to this timeline, as a promise.
   */
  Timeline.prototype.getSubscriberIds = async function(includeSelf) {
    let userIds = await dbAdapter.getTimelineSubscribersIds(this.id)

    // A user is always subscribed to their own posts timeline.
    if (includeSelf && (this.isPosts() || this.isDirects())) {
      userIds = _.uniq(userIds.concat([this.userId]))
    }

    this.subscriberIds = userIds

    return userIds
  }

  Timeline.prototype.getSubscribers = async function(includeSelf) {
    let users = await dbAdapter.getTimelineSubscribers(this.intId)

    if (includeSelf && (this.isPosts() || this.isDirects())) {
      let currentUser = await dbAdapter.getUserById(this.userId)
      users = users.concat(currentUser)
    }

    this.subscribers = users

    return this.subscribers
  }

  /**
   * Returns the list of the 'River of News' timelines of all subscribers to this
   * timeline.
   */
  Timeline.prototype.getSubscribedTimelineIds = async function() {
    var subscribers = await this.getSubscribers(true);
    return await Promise.all(subscribers.map((subscriber) => subscriber.getRiverOfNewsTimelineId()))
  }

  Timeline.prototype.getSubscribersRiversOfNewsIntIds = async function() {
    var subscribers = await this.getSubscribers(true);
    return await Promise.all(subscribers.map((subscriber) => subscriber.getRiverOfNewsTimelineIntId()))
  }

  Timeline.prototype.isRiverOfNews = function() {
    return this.name === "RiverOfNews"
  }

  Timeline.prototype.isPosts = function() {
    return this.name === "Posts"
  }

  Timeline.prototype.isLikes = function() {
    return this.name === "Likes"
  }

  Timeline.prototype.isComments = function() {
    return this.name === "Comments"
  }

  Timeline.prototype.isDirects = function() {
    return this.name === "Directs"
  }

  Timeline.prototype.isHides = function() {
    return this.name === "Hides"
  }

  Timeline.prototype.updatePost = async function(postId, action) {
    if (action === "like") {
      let postInTimeline = await dbAdapter.isPostPresentInTimeline(this.intId, postId)

      if (postInTimeline) {
        // For the time being, like does not bump post if it is already present in timeline
        return
      }
    }

    var currentTime = new Date().getTime()

    if (action === "like") {
      await dbAdapter.insertPostIntoFeeds([this.intId], postId)
      if(this.isRiverOfNews()) {
        await dbAdapter.createLocalBump(postId, this.userId)
      }
    } else {
      await Promise.all([
        dbAdapter.insertPostIntoFeeds([this.intId], postId),
        dbAdapter.setPostUpdatedAt(postId, currentTime)
      ])
    }

    // does not update lastActivity on like
    if (action === 'like') {
      return
    }

    const feed = await this.getUser()
    await feed.updateLastActivityAt()
  }

  Timeline.prototype.canShow = async function(userId) {
    // owner can read her posts
    if (this.userId === userId)
      return true

    // if post is already in user's feed then she can read it
    if (this.isDirects())
      return this.userId === userId

    // this is a public feed, anyone can read public posts, this is
    // a free country
    var user = await this.getUser()
    if (user && user.isPrivate !== '1')
      return true

    // otherwise user can view post if and only if she is subscriber
    var userIds = await this.getSubscriberIds()
    return userIds.indexOf(userId) >= 0
  }

  return Timeline
}
<|endoftext|>


<commit_before>import { Class } from '../../core/Core';

import UndoManager from './UndoManager';

const StoreUndoManager = Class({

    Extends: UndoManager,

    // eslint-disable-next-line object-shorthand
    init: function (/* ...mixins */) {
        StoreUndoManager.parent.constructor.apply( this, arguments );
        this.get( 'store' )
            .on( 'willCommit', this, 'saveUndoCheckpoint' )
            .on( 'record:user:create', this, 'dataDidChange' )
            .on( 'record:user:update', this, 'dataDidChange' )
            .on( 'record:user:destroy', this, 'dataDidChange' );
    },

    destroy () {
        this.get( 'store' )
            .off( 'willCommit', this, 'saveUndoCheckpoint' )
            .off( 'record:user:create', this, 'dataDidChange' )
            .off( 'record:user:update', this, 'dataDidChange' )
            .off( 'record:user:destroy', this, 'dataDidChange' );
        StoreUndoManager.parent.destroy.call( this );
    },

    dataDidChange () {
        const noChanges =
            !this.get( 'store' ).checkForChanges().get( 'hasChanges' );
        this._isInUndoState = noChanges;
        return this
            .set( 'canRedo', noChanges && !!this._redoStack.length )
            .set( 'canUndo', noChanges && !!this._undoStack.length )
            .fire( 'input' );
    },

    getUndoData () {
        const store = this.get( 'store' );
        return store.checkForChanges().get( 'hasChanges' ) ?
            store.getInverseChanges() : null;
    },

    applyChange ( data ) {
        const store = this.get( 'store' );
        store.applyChanges( data );
        const inverse = store.getInverseChanges();
        store.commitChanges();
        return inverse;
    },
});

export default StoreUndoManager;
<commit_msg>Fix StoreUndoManager saves wrong data<commit_after>import { Class } from '../../core/Core';

import UndoManager from './UndoManager';

const StoreUndoManager = Class({

    Extends: UndoManager,

    // eslint-disable-next-line object-shorthand
    init: function (/* ...mixins */) {
        StoreUndoManager.parent.constructor.apply( this, arguments );
        this.get( 'store' )
            .on( 'willCommit', this, '_saveUndoCheckpoint' )
            .on( 'record:user:create', this, 'dataDidChange' )
            .on( 'record:user:update', this, 'dataDidChange' )
            .on( 'record:user:destroy', this, 'dataDidChange' );
    },

    destroy () {
        this.get( 'store' )
            .off( 'willCommit', this, '_saveUndoCheckpoint' )
            .off( 'record:user:create', this, 'dataDidChange' )
            .off( 'record:user:update', this, 'dataDidChange' )
            .off( 'record:user:destroy', this, 'dataDidChange' );
        StoreUndoManager.parent.destroy.call( this );
    },

    // Avoid passing event argument to saveUndoCheckpoint method
    _saveUndoCheckpoint () {
        this.saveUndoCheckpoint();
    },

    dataDidChange () {
        const noChanges =
            !this.get( 'store' ).checkForChanges().get( 'hasChanges' );
        this._isInUndoState = noChanges;
        return this
            .set( 'canRedo', noChanges && !!this._redoStack.length )
            .set( 'canUndo', noChanges && !!this._undoStack.length )
            .fire( 'input' );
    },

    getUndoData () {
        const store = this.get( 'store' );
        return store.checkForChanges().get( 'hasChanges' ) ?
            store.getInverseChanges() : null;
    },

    applyChange ( data ) {
        const store = this.get( 'store' );
        store.applyChanges( data );
        const inverse = store.getInverseChanges();
        store.commitChanges();
        return inverse;
    },
});

export default StoreUndoManager;
<|endoftext|>


<commit_before>/*
Copyright (c) 2013 dissimulate at Codepen

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

document.getElementById('close').onmousedown = function(e) {
  e.preventDefault();
  document.getElementById('info').style.display = 'none';
  return false;
};

// settings

var physics_accuracy  = 3,
    mouse_influence   = 20,
    mouse_cut         = 5,
    gravity           = 1000,
    cloth_height      = 70,
    cloth_width       = 160,
    start_y           = 20,
    spacing           = 7,
    tear_distance     = 60;

window.requestAnimFrame =
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function (callback) {
        window.setTimeout(callback, 1000 / 60);
};

var canvas,
    ctx,
    cloth,
    boundsx,
    boundsy,
    mouse = {
        down: false,
        button: 1,
        x: 0,
        y: 0,
        px: 0,
        py: 0
    };

var Point = function (x, y) {

    this.x      = x;
    this.y      = y;
    this.px     = x;
    this.py     = y;
    this.vx     = 0;
    this.vy     = 0;
    this.pin_x  = null;
    this.pin_y  = null;

    this.constraints = [];
};

Point.prototype.update = function (delta) {

    if (mouse.down) {

        var diff_x = this.x - mouse.x,
            diff_y = this.y - mouse.y,
            dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y);

        if (mouse.button == 1) {

            if (dist < mouse_influence) {
                this.px = this.x - (mouse.x - mouse.px) * 1.8;
                this.py = this.y - (mouse.y - mouse.py) * 1.8;
            }

        } else if (dist < mouse_cut) this.constraints = [];
    }

    this.add_force(0, gravity);

    delta *= delta;
    nx = this.x + ((this.x - this.px) * .99) + ((this.vx / 2) * delta);
    ny = this.y + ((this.y - this.py) * .99) + ((this.vy / 2) * delta);

    this.px = this.x;
    this.py = this.y;

    this.x = nx;
    this.y = ny;

    this.vy = this.vx = 0
};

Point.prototype.draw = function () {

    if (!this.constraints.length) return;

    var i = this.constraints.length;
    while (i--) this.constraints[i].draw();
};

Point.prototype.resolve_constraints = function () {

    if (this.pin_x != null && this.pin_y != null) {

        this.x = this.pin_x;
        this.y = this.pin_y;
        return;
    }

    var i = this.constraints.length;
    while (i--) this.constraints[i].resolve();

    this.x > boundsx ? this.x = 2 * boundsx - this.x : 1 > this.x && (this.x = 2 - this.x);
    this.y < 1 ? this.y = 2 - this.y : this.y > boundsy && (this.y = 2 * boundsy - this.y);
};

Point.prototype.attach = function (point) {

    this.constraints.push(
        new Constraint(this, point)
    );
};

Point.prototype.remove_constraint = function (constraint) {

    this.constraints.splice(this.constraints.indexOf(constraint), 1);
};

Point.prototype.add_force = function (x, y) {

    this.vx += x;
    this.vy += y;
};

Point.prototype.pin = function (pinx, piny) {
    this.pin_x = pinx;
    this.pin_y = piny;
};

var Constraint = function (p1, p2) {

    this.p1     = p1;
    this.p2     = p2;
    this.length = spacing;
};

Constraint.prototype.resolve = function () {

    var diff_x  = this.p1.x - this.p2.x,
        diff_y  = this.p1.y - this.p2.y,
        dist    = Math.sqrt(diff_x * diff_x + diff_y * diff_y),
        diff    = (this.length - dist) / dist;

    if (dist > tear_distance) this.p1.remove_constraint(this);

    var px = diff_x * diff * 0.5;
    var py = diff_y * diff * 0.5;

    this.p1.x += px;
    this.p1.y += py;
    this.p2.x -= px;
    this.p2.y -= py;
};

Constraint.prototype.draw = function () {

    ctx.moveTo(this.p1.x, this.p1.y);
    ctx.lineTo(this.p2.x, this.p2.y);
};

var Cloth = function () {

    this.points = [];

    var start_x = canvas.width / 2 - cloth_width * spacing / 2;

    for (var y = 0; y <= cloth_height; y++) {

        for (var x = 0; x <= cloth_width; x++) {

            var p = new Point(start_x + x * spacing, start_y + y * spacing);

            x != 0 && p.attach(this.points[this.points.length - 1]);
            y == 0 && p.pin(p.x, p.y);
            y != 0 && p.attach(this.points[x + (y - 1) * (cloth_width + 1)])

            this.points.push(p);
        }
    }
};

Cloth.prototype.update = function () {

    var i = physics_accuracy;

    while (i--) {
        var p = this.points.length;
        while (p--) this.points[p].resolve_constraints();
    }

    i = this.points.length;
    while (i--) this.points[i].update(.016);
};

Cloth.prototype.draw = function () {

    ctx.beginPath();

    var i = cloth.points.length;
    while (i--) cloth.points[i].draw();

    ctx.stroke();
};

function update() {

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    cloth.update();
    cloth.draw();

    requestAnimFrame(update);
}

function start() {

    canvas.onmousedown = function (e) {
        mouse.button  = e.which;
        mouse.px      = mouse.x;
        mouse.py      = mouse.y;
        var rect      = canvas.getBoundingClientRect();
        mouse.x       = e.clientX - rect.left,
        mouse.y       = e.clientY - rect.top,
        mouse.down    = true;
        e.preventDefault();
    };

    canvas.onmouseup = function (e) {
        mouse.down = false;
        e.preventDefault();
    };

    canvas.onmousemove = function (e) {
        mouse.px  = mouse.x;
        mouse.py  = mouse.y;
        var rect  = canvas.getBoundingClientRect();
        mouse.x   = e.clientX - rect.left,
        mouse.y   = e.clientY - rect.top,
        e.preventDefault();
    };

    canvas.oncontextmenu = function (e) {
        e.preventDefault();
    };

    boundsx = canvas.width - 1;
    boundsy = canvas.height - 1;

    ctx.strokeStyle = '#888';

    cloth = new Cloth();

    update();
}

window.onload = function () {

    canvas  = document.getElementById('c');
    ctx     = canvas.getContext('2d');

    canvas.width  = 1360;
    canvas.height = 560;
    start();
};
<commit_msg>Update index.js<commit_after>/*
Copyright (c) 2013 dissimulate at Codepen

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

document.getElementById('close').onmousedown = function(e) {
  e.preventDefault();
  document.getElementById('info').style.display = 'none';
  return false;
};

// settings

var physics_accuracy  = 3,
    mouse_influence   = 20,
    mouse_cut         = 5,
    gravity           = 1000,
    cloth_height      = 70,
    cloth_width       = 140,
    start_y           = 20,
    spacing           = 7,
    tear_distance     = 60;

window.requestAnimFrame =
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function (callback) {
        window.setTimeout(callback, 1000 / 60);
};

var canvas,
    ctx,
    cloth,
    boundsx,
    boundsy,
    mouse = {
        down: false,
        button: 1,
        x: 0,
        y: 0,
        px: 0,
        py: 0
    };

var Point = function (x, y) {

    this.x      = x;
    this.y      = y;
    this.px     = x;
    this.py     = y;
    this.vx     = 0;
    this.vy     = 0;
    this.pin_x  = null;
    this.pin_y  = null;

    this.constraints = [];
};

Point.prototype.update = function (delta) {

    if (mouse.down) {

        var diff_x = this.x - mouse.x,
            diff_y = this.y - mouse.y,
            dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y);

        if (mouse.button == 1) {

            if (dist < mouse_influence) {
                this.px = this.x - (mouse.x - mouse.px) * 1.8;
                this.py = this.y - (mouse.y - mouse.py) * 1.8;
            }

        } else if (dist < mouse_cut) this.constraints = [];
    }

    this.add_force(0, gravity);

    delta *= delta;
    nx = this.x + ((this.x - this.px) * .99) + ((this.vx / 2) * delta);
    ny = this.y + ((this.y - this.py) * .99) + ((this.vy / 2) * delta);

    this.px = this.x;
    this.py = this.y;

    this.x = nx;
    this.y = ny;

    this.vy = this.vx = 0
};

Point.prototype.draw = function () {

    if (!this.constraints.length) return;

    var i = this.constraints.length;
    while (i--) this.constraints[i].draw();
};

Point.prototype.resolve_constraints = function () {

    if (this.pin_x != null && this.pin_y != null) {

        this.x = this.pin_x;
        this.y = this.pin_y;
        return;
    }

    var i = this.constraints.length;
    while (i--) this.constraints[i].resolve();

    this.x > boundsx ? this.x = 2 * boundsx - this.x : 1 > this.x && (this.x = 2 - this.x);
    this.y < 1 ? this.y = 2 - this.y : this.y > boundsy && (this.y = 2 * boundsy - this.y);
};

Point.prototype.attach = function (point) {

    this.constraints.push(
        new Constraint(this, point)
    );
};

Point.prototype.remove_constraint = function (constraint) {

    this.constraints.splice(this.constraints.indexOf(constraint), 1);
};

Point.prototype.add_force = function (x, y) {

    this.vx += x;
    this.vy += y;
};

Point.prototype.pin = function (pinx, piny) {
    this.pin_x = pinx;
    this.pin_y = piny;
};

var Constraint = function (p1, p2) {

    this.p1     = p1;
    this.p2     = p2;
    this.length = spacing;
};

Constraint.prototype.resolve = function () {

    var diff_x  = this.p1.x - this.p2.x,
        diff_y  = this.p1.y - this.p2.y,
        dist    = Math.sqrt(diff_x * diff_x + diff_y * diff_y),
        diff    = (this.length - dist) / dist;

    if (dist > tear_distance) this.p1.remove_constraint(this);

    var px = diff_x * diff * 0.5;
    var py = diff_y * diff * 0.5;

    this.p1.x += px;
    this.p1.y += py;
    this.p2.x -= px;
    this.p2.y -= py;
};

Constraint.prototype.draw = function () {

    ctx.moveTo(this.p1.x, this.p1.y);
    ctx.lineTo(this.p2.x, this.p2.y);
};

var Cloth = function () {

    this.points = [];

    var start_x = canvas.width / 2 - cloth_width * spacing / 2;

    for (var y = 0; y <= cloth_height; y++) {

        for (var x = 0; x <= cloth_width; x++) {

            var p = new Point(start_x + x * spacing, start_y + y * spacing);

            x != 0 && p.attach(this.points[this.points.length - 1]);
            y == 0 && p.pin(p.x, p.y);
            y != 0 && p.attach(this.points[x + (y - 1) * (cloth_width + 1)])

            this.points.push(p);
        }
    }
};

Cloth.prototype.update = function () {

    var i = physics_accuracy;

    while (i--) {
        var p = this.points.length;
        while (p--) this.points[p].resolve_constraints();
    }

    i = this.points.length;
    while (i--) this.points[i].update(.016);
};

Cloth.prototype.draw = function () {

    ctx.beginPath();

    var i = cloth.points.length;
    while (i--) cloth.points[i].draw();

    ctx.stroke();
};

function update() {

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    cloth.update();
    cloth.draw();

    requestAnimFrame(update);
}

function start() {

    canvas.onmousedown = function (e) {
        mouse.button  = e.which;
        mouse.px      = mouse.x;
        mouse.py      = mouse.y;
        var rect      = canvas.getBoundingClientRect();
        mouse.x       = e.clientX - rect.left,
        mouse.y       = e.clientY - rect.top,
        mouse.down    = true;
        e.preventDefault();
    };

    canvas.onmouseup = function (e) {
        mouse.down = false;
        e.preventDefault();
    };

    canvas.onmousemove = function (e) {
        mouse.px  = mouse.x;
        mouse.py  = mouse.y;
        var rect  = canvas.getBoundingClientRect();
        mouse.x   = e.clientX - rect.left,
        mouse.y   = e.clientY - rect.top,
        e.preventDefault();
    };

    canvas.oncontextmenu = function (e) {
        e.preventDefault();
    };

    boundsx = canvas.width - 1;
    boundsy = canvas.height - 1;

    ctx.strokeStyle = '#888';

    cloth = new Cloth();

    update();
}

window.onload = function () {

    canvas  = document.getElementById('c');
    ctx     = canvas.getContext('2d');

    canvas.width  = 1360;
    canvas.height = 530;
    start();
};
<|endoftext|>


<commit_before>function keyify(text_str){
  text_str = text_str.toLowerCase()
  text_str = text_str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "_");
  return text_str;
};

var unitArray = {
  'm': {
    'm2spa_kg': 1.95e-10
   }
};

$(document).ready(function(){
  $("#btn1").click(function() {
    var val = +$("#value").val();
    var i_unit = +$("#inp_unit").val();
    var o_unit = +$("#out_unit").val();
    var ikey = keyify(i_unit);
    var okey = keyify(o_unit);
    var res = val * unitArray[okey][ikey]
    $("#result").val(res);
    $("#res_unit").val(o_unit);
  });
});

/* No work..
function funcCalc(jQuery, val, i_unit, o_unit)
{
  var value = document.getElementById('value').value;
  var  inp_unit = document.getElementById('inp_unit').value;
  var out_unit = document.getElementById('out_unit').value;
  var unitArray = {};
  unitArray.m.m2sPa_kg = 1.95e-10
  i_unit = i_unit.replace("/", "_");
  o_unit = o_unit.replace("/", "_");
  return unitArray[o_unit][i_unit] *
}

$(document).ready(function(){
    $(".calc_button").click(
    function(){
          var val = +$(".value").val();
          var i_unit = +$(".inp_unit").val();
          var o_unit = +$(".out_unit").val();
          var res = funcCalc(val, i_unit, o_unit);
          Alert(res);
          $("#result").val(res);
   });
});
*/

// test writing with Firefox Web IDE (ctrl+s saves!)<commit_msg>Trouble all the way with unitconverter.js<commit_after>

$(document).ready(function(){$("#btn1").click(function() {
  function keyify(text_str){
    text_str = String(text_str).toLowerCase()
    text_str = text_str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "_");
    return text_str;
  };

  var unitArray = {
    'm': {
      'm2spa_kg': 1.95e-10
    }
  };

  var val = +$("#value").val();
  console.log(val);
  var i_unit = +$("#inp_unit").val();
  console.log(val);
  var o_unit = +$("#out_unit").val();
  console.log(val);
  var ikey = keyify(i_unit);
  console.log(val);
  var okey = keyify(o_unit);
  console.log(val);
  // var res = val * unitArray[okey][ikey]
  $("#result").val(111);
  $("#res_unit").val(o_unit);
});});

<|endoftext|>


<commit_before>
app.controller("CourseSelectorController", ["$scope", "$window", "$state", '$stateParams', 'Course',
    function ($scope, $window, $state, $stateParams, Course) {
      Course.get(function(response) {
        $scope.courses = response.results
      });
      if ($window.user.indexOf("berkeley.edu") == -1) {
        $window.swal({
            title: "Is this the right login?",
            text: "Logging you in with your \"" + $window.user + "\" account...",
            type: "info",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes - that's correct!",
            cancelButtonText: "No - log me out",
            closeOnConfirm: true,
            closeOnCancel: true
        }, function(isConfirm) {
            if (isConfirm) {
              // Do nothing, because the user might want to select a course.
            } else {
                $window.location.href = $window.reloginLink;
            }
        });
      } else {
         $window.location.hash = "";
      }
    }
]);

// Assignment Controllers
app.controller("AssignmentOverviewController", ['$scope', 'Assignment', 'User', '$timeout',
  function($scope, Assignment, User, $timeout) {
    Assignment.query({
      fields: {
        id: true,
        display_name: true,
        id: true,
        due_date: true,
        points: true,
        created: true,
      }}, function(response) {
      $scope.assignments = response.results;
    })}
]);

// Assignment Controllers
app.controller("GroupOverviewController", ['$scope', 'Assignment', 'User', '$timeout',
  function($scope, Assignment, User, $timeout) {
    Group.query(function(response) {
      $scope.assignments = response.results;
    })}
]);

app.controller("SubmissionDetailCtrl", ['$scope', '$window', '$location', '$stateParams',  '$timeout', '$anchorScroll', 'Submission',
  function($scope, $window, $location, $stateParams, $timeout, $anchorScroll, Submission) {
     Submission.get({id: $stateParams.submissionId}, function (response) {
        $scope.submission = response;
        $scope.courseId = $stateParams.courseId;
        if ($scope.submission.messages && $scope.submission.messages.file_contents['submit']) {
          $scope.isSubmit = true;
          delete $scope.submission.messages.file_contents['submit'];
        }
        $timeout(function() {
          $('code').each(function(i, block) {
            hljs.highlightBlock(block);

            code = $scope.submission.messages.file_contents;
            for (var key in code) {
                if (code.hasOwnProperty(key)) {
                    lines = code[key].match(/"\n"/) || [];
                    numbers = '';
                    for (i=0;i<lines.length;i++) {
                      numbers += '
'+i+'
';
                    }
                    $(this).parent().find('.num-cont ul').html(numbers);
                }
            }
          });
        }, 100);
      }, function (error) {
        $window.swal("Uhoh", "There was an error!", "error");
      });
  }]);

// Main dashboard controller. Should be modularized later.
app.controller("AssignmentDashController", ['$scope', '$window', '$state',  '$stateParams', 'Assignment', 'User', 'Group', 'Submission', '$timeout',
  function($scope, $window, $state,  $stateParams, Assignment, User, Group, Submission, $timeout) {
      $scope.courseId = $stateParams.courseId

      $scope.toggleAssign = function (assign) {
        if ($scope.currAssign == assign) {
          $scope.currAssign = null
        } else {
          $scope.currAssign = assign;
        }
      }

      $scope.findAndToggle = function (assignId) {
        for (var i = 0; i < $scope.assignments.length; i++) {
          if ($scope.assignments[i].id == assignId) {
            $scope.toggleAssign($scope.assignments[i])
          }
        }
      }

      $scope.reloadAssignments = function () {
        $scope.showLoader()
          User.get({
            course: $stateParams.courseId,
          }, function (response) {
            $scope.assignments = response.assignments
            $scope.hideLoader()
          }, function (error) {
            $scope.hideLoader()
            $window.swal('Unknown Course', 'Whoops.', 'error');
            $state.transitionTo('courseLanding', null, { reload: true, inherit: true, notify: true })
          })
      }

      $scope.reloadView = function () {
        // oldToggle = $scope.currAssign.id
        $state.transitionTo($state.current, angular.copy($stateParams), { reload: true, inherit: true, notify: true });
      };

      $scope.showLoader = function showLoader() {
        $('.loader').removeClass('hide');
      }

      $scope.hideLoader = function hideLoader() {
        $('.loader').addClass('done hide');
        setTimeout(function() {
          $('.loader').removeClass('done')
        },800)
      }

      $scope.reloadAssignments()

      $scope.removeMember = function(currGroup, member) {
            Group.removeMember({
              id: currGroup.id,
              email: member.email[0]
            }, function (err) {
              $scope.hideGroup();
              if (member.email[0] != $window.user) {
                  $scope.reloadView()
              } else {
                $scope.currGroup = null;
                $scope.currAssign.group = null

              }
            });
      };

      $scope.winRate = function (assign, backupId) {
        assign.winrate = {'progress': 1, 'message': "Loading"}
        Submission.winRate({
          id: backupId
        }, function (response){
          if (response.error.type) {
            assign.winrate = {'progress': 0, 'error': true, 'message': response.error.type+" Error"}
            $window.swal(response.error.type + " Error",'There was a ' + response.error.type + ' error in your code.','error')
          } else {
            $scope.winrate = response
            assign.winrate = {
              'progress': (response.winrate / .56) * 100,
              'percent': response.winrate * 100,
              'message': response.message
            }
          }
          // $window.swal(response.winrate*100 +"%",'Final Win Rate','info')
        }, function (err) {
          assign.winrate = {
            'message': response.message,
            'error': true
          }

          $window.swal("Uhoh",'There was an error','error')
        });
      }

      $scope.rejectInvite = function(currGroup) {
          Group.rejectInvitation({
            id: currGroup.id,
          }, function (err) {
            currGroup = null
            $scope.currAssign.group = null
          });
      };

      $scope.acceptInvite = function(currGroup) {
          Group.acceptInvitation({
              id: currGroup.id,
          }, function (err) {
            $scope.reloadView()
          });
      };

      $scope.getSubmissions = function (assignId) {
            User.getSubmissions({
              assignment: assignId
            }, function (response) {
              $scope.currAssign.submissions = response;
              $scope.showSubms();
            });
      }

      $scope.getBackups = function (assignId) {
            User.getBackups({
              assignment: assignId
            }, function (response) {
              $scope.currAssign.backups = response;
              $scope.showBackups();
            });
      }

      $scope.addMember = function(assign, member) {
        if (member && member != '') {
          assignId = assign.assignment.id
          Assignment.invite({
            id: assignId,
            email: member
          }, function (response) {
              $scope.reloadView()
              $window.swal({
                  title: "Invitation Sent!",
                  text: "They will need to login to okpy.org and accept the invite.",
                  timer: 3500,
                  type: "success"
                });

          }, function (err) {
            $window.swal("Oops...", "Can't add that user to your group.    Is that the right email? They might already be in a group or may not be in the course.", "error");
         });
        }
      };

      $scope.showGroup = function showGroup(group) {
          $('.popups').addClass('active');
          $('.popup').removeClass('active');
          $('.popup.group').addClass('active').removeClass('hide');
          $scope.currGroup = group
      }

      $scope.hideGroup = function hideGroup() {
          $('.popups').removeClass('active');
          $('.popup').removeClass('active');
          $('.popup.group').addClass('active').addClass('hide');
      }

      $scope.showBackups = function showGroup(id) {
          $('.popups').addClass('active');
          $('.popup').removeClass('active');
          $('.popup.backups').addClass('active').removeClass('hide');
      }

      $scope.showSubms = function showGroup(id) {
          $('.popups').addClass('active');
          $('.popup').removeClass('active');
          $('.popup.submissions').addClass('active').removeClass('hide');
      }

      $scope.hidePopups =  function hidePopups() {
          $('.assign').removeClass('s');
          $('.popups').removeClass('active');
          $('.popup').removeClass('active');
          setTimeout(function() {
            $('.popup').addClass('hide');
          },400);
        }

      }
]);

<commit_msg>line numbers successfully added<commit_after>
app.controller("CourseSelectorController", ["$scope", "$window", "$state", '$stateParams', 'Course',
    function ($scope, $window, $state, $stateParams, Course) {
      Course.get(function(response) {
        $scope.courses = response.results
      });
      if ($window.user.indexOf("berkeley.edu") == -1) {
        $window.swal({
            title: "Is this the right login?",
            text: "Logging you in with your \"" + $window.user + "\" account...",
            type: "info",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes - that's correct!",
            cancelButtonText: "No - log me out",
            closeOnConfirm: true,
            closeOnCancel: true
        }, function(isConfirm) {
            if (isConfirm) {
              // Do nothing, because the user might want to select a course.
            } else {
                $window.location.href = $window.reloginLink;
            }
        });
      } else {
         $window.location.hash = "";
      }
    }
]);

// Assignment Controllers
app.controller("AssignmentOverviewController", ['$scope', 'Assignment', 'User', '$timeout',
  function($scope, Assignment, User, $timeout) {
    Assignment.query({
      fields: {
        id: true,
        display_name: true,
        id: true,
        due_date: true,
        points: true,
        created: true,
      }}, function(response) {
      $scope.assignments = response.results;
    })}
]);

// Assignment Controllers
app.controller("GroupOverviewController", ['$scope', 'Assignment', 'User', '$timeout',
  function($scope, Assignment, User, $timeout) {
    Group.query(function(response) {
      $scope.assignments = response.results;
    })}
]);

app.controller("SubmissionDetailCtrl", ['$scope', '$window', '$location', '$stateParams',  '$timeout', '$anchorScroll', 'Submission',
  function($scope, $window, $location, $stateParams, $timeout, $anchorScroll, Submission) {
     Submission.get({id: $stateParams.submissionId}, function (response) {
        $scope.submission = response;
        $scope.courseId = $stateParams.courseId;
        if ($scope.submission.messages && $scope.submission.messages.file_contents['submit']) {
          $scope.isSubmit = true;
          delete $scope.submission.messages.file_contents['submit'];
        }
        $timeout(function() {
          $('code').each(function(i, block) {
            hljs.highlightBlock(block);

            code = $scope.submission.messages.file_contents;
            for (var key in code) {
                if (code.hasOwnProperty(key)) {
                    count = code[key].match(/[^\n]*\n[^\n]*/gi).length;
                    console.log(count);
                    numbers = '';
                    for (i=0;i<count;i++) {
                      numbers += '
'+(i+1)+'
';
                    }
                    $(this).parent().find('.num-cont ul').html(numbers);
                }
            }
          });
        }, 100);
      }, function (error) {
        $window.swal("Uhoh", "There was an error!", "error");
      });
  }]);

// Main dashboard controller. Should be modularized later.
app.controller("AssignmentDashController", ['$scope', '$window', '$state',  '$stateParams', 'Assignment', 'User', 'Group', 'Submission', '$timeout',
  function($scope, $window, $state,  $stateParams, Assignment, User, Group, Submission, $timeout) {
      $scope.courseId = $stateParams.courseId

      $scope.toggleAssign = function (assign) {
        if ($scope.currAssign == assign) {
          $scope.currAssign = null
        } else {
          $scope.currAssign = assign;
        }
      }

      $scope.findAndToggle = function (assignId) {
        for (var i = 0; i < $scope.assignments.length; i++) {
          if ($scope.assignments[i].id == assignId) {
            $scope.toggleAssign($scope.assignments[i])
          }
        }
      }

      $scope.reloadAssignments = function () {
        $scope.showLoader()
          User.get({
            course: $stateParams.courseId,
          }, function (response) {
            $scope.assignments = response.assignments
            $scope.hideLoader()
          }, function (error) {
            $scope.hideLoader()
            $window.swal('Unknown Course', 'Whoops.', 'error');
            $state.transitionTo('courseLanding', null, { reload: true, inherit: true, notify: true })
          })
      }

      $scope.reloadView = function () {
        // oldToggle = $scope.currAssign.id
        $state.transitionTo($state.current, angular.copy($stateParams), { reload: true, inherit: true, notify: true });
      };

      $scope.showLoader = function showLoader() {
        $('.loader').removeClass('hide');
      }

      $scope.hideLoader = function hideLoader() {
        $('.loader').addClass('done hide');
        setTimeout(function() {
          $('.loader').removeClass('done')
        },800)
      }

      $scope.reloadAssignments()

      $scope.removeMember = function(currGroup, member) {
            Group.removeMember({
              id: currGroup.id,
              email: member.email[0]
            }, function (err) {
              $scope.hideGroup();
              if (member.email[0] != $window.user) {
                  $scope.reloadView()
              } else {
                $scope.currGroup = null;
                $scope.currAssign.group = null

              }
            });
      };

      $scope.winRate = function (assign, backupId) {
        assign.winrate = {'progress': 1, 'message': "Loading"}
        Submission.winRate({
          id: backupId
        }, function (response){
          if (response.error.type) {
            assign.winrate = {'progress': 0, 'error': true, 'message': response.error.type+" Error"}
            $window.swal(response.error.type + " Error",'There was a ' + response.error.type + ' error in your code.','error')
          } else {
            $scope.winrate = response
            assign.winrate = {
              'progress': (response.winrate / .56) * 100,
              'percent': response.winrate * 100,
              'message': response.message
            }
          }
          // $window.swal(response.winrate*100 +"%",'Final Win Rate','info')
        }, function (err) {
          assign.winrate = {
            'message': response.message,
            'error': true
          }

          $window.swal("Uhoh",'There was an error','error')
        });
      }

      $scope.rejectInvite = function(currGroup) {
          Group.rejectInvitation({
            id: currGroup.id,
          }, function (err) {
            currGroup = null
            $scope.currAssign.group = null
          });
      };

      $scope.acceptInvite = function(currGroup) {
          Group.acceptInvitation({
              id: currGroup.id,
          }, function (err) {
            $scope.reloadView()
          });
      };

      $scope.getSubmissions = function (assignId) {
            User.getSubmissions({
              assignment: assignId
            }, function (response) {
              $scope.currAssign.submissions = response;
              $scope.showSubms();
            });
      }

      $scope.getBackups = function (assignId) {
            User.getBackups({
              assignment: assignId
            }, function (response) {
              $scope.currAssign.backups = response;
              $scope.showBackups();
            });
      }

      $scope.addMember = function(assign, member) {
        if (member && member != '') {
          assignId = assign.assignment.id
          Assignment.invite({
            id: assignId,
            email: member
          }, function (response) {
              $scope.reloadView()
              $window.swal({
                  title: "Invitation Sent!",
                  text: "They will need to login to okpy.org and accept the invite.",
                  timer: 3500,
                  type: "success"
                });

          }, function (err) {
            $window.swal("Oops...", "Can't add that user to your group.    Is that the right email? They might already be in a group or may not be in the course.", "error");
         });
        }
      };

      $scope.showGroup = function showGroup(group) {
          $('.popups').addClass('active');
          $('.popup').removeClass('active');
          $('.popup.group').addClass('active').removeClass('hide');
          $scope.currGroup = group
      }

      $scope.hideGroup = function hideGroup() {
          $('.popups').removeClass('active');
          $('.popup').removeClass('active');
          $('.popup.group').addClass('active').addClass('hide');
      }

      $scope.showBackups = function showGroup(id) {
          $('.popups').addClass('active');
          $('.popup').removeClass('active');
          $('.popup.backups').addClass('active').removeClass('hide');
      }

      $scope.showSubms = function showGroup(id) {
          $('.popups').addClass('active');
          $('.popup').removeClass('active');
          $('.popup.submissions').addClass('active').removeClass('hide');
      }

      $scope.hidePopups =  function hidePopups() {
          $('.assign').removeClass('s');
          $('.popups').removeClass('active');
          $('.popup').removeClass('active');
          setTimeout(function() {
            $('.popup').addClass('hide');
          },400);
        }

      }
]);

<|endoftext|>


<commit_before>const winston = require('winston');

const SPLAT = Symbol.for('splat');

let logLevel;

switch (process.env.NODE_ENV) {
	case 'development':
		logLevel = 'debug';
		break;
	case 'test':
		logLevel = 'emerg';
		break;
	case 'production':
	default:
		logLevel = 'info';
}

function formatObject(param) {
	if (typeof param === 'object') {
		return JSON.stringify(param);
	}
	return param;
}

// workaround to call log functions with multiple message parameter.
// example: logger.info('first', 'secound', 'some other string')
const all = winston.format((info) => {
	const isSplatTypeMessage = typeof info.message === 'string'
		&& (info.message.includes('%s') || info.message.includes('%d') || info.message.includes('%j'));
	if (isSplatTypeMessage) {
		return info;
	}

	const splat = info[SPLAT] || [];
	const message = formatObject(info.message);
	const rest = splat
		.map(formatObject)
		.join(' ');
	info.message = `${message} ${rest}`;
	return info;
});

const logger = winston.createLogger({
	levels: winston.config.syslog.levels,
	format: winston.format.combine(
		all(),
		winston.format.timestamp(), // adds current timestamp
		winston.format.ms(),	// adds time since last log
		winston.format.prettyPrint(), // output as prettyfied Json. Use 'winston.format.simple()' for output string
	),
	transports: [
		new winston.transports.Console({
			level: logLevel,
			handleExceptions: true,
		}),
	],
	exitOnError: false,
});

module.exports = logger;
<commit_msg>retrieve changes<commit_after>const winston = require('winston');

//const SPLAT = Symbol.for('splat');

let logLevel;

switch (process.env.NODE_ENV) {
	case 'development':
		logLevel = 'debug';
		break;
	case 'test':
		logLevel = 'emerg';
		break;
	case 'production':
	default:
		logLevel = 'info';
}
/*
function formatObject(param) {
	if (typeof param === 'object') {
		return JSON.stringify(param);
	}
	return param;
}

// workaround to call log functions with multiple message parameter.
// example: logger.info('first', 'secound', 'some other string')
const all = winston.format((info) => {
	const isSplatTypeMessage = typeof info.message === 'string'
		&& (info.message.includes('%s') || info.message.includes('%d') || info.message.includes('%j'));
	if (isSplatTypeMessage) {
		return info;
	}

	const splat = info[SPLAT] || [];
	const message = formatObject(info.message);
	const rest = splat
		.map(formatObject)
		.join(' ');
	info.message = `${message} ${rest}`;
	return info;
});
*/
const logger = winston.createLogger({
	levels: winston.config.syslog.levels,
	format: winston.format.combine(
		//all(),
		winston.format.timestamp(), // adds current timestamp
		winston.format.ms(),	// adds time since last log
		winston.format.simple(), // output as prettyfied Json. Use 'winston.format.simple()' for output string
	),
	transports: [
		new winston.transports.Console({
			level: logLevel,
			handleExceptions: true,
		}),
	],
	exitOnError: false,
});

module.exports = logger;
<|endoftext|>


<commit_before>/**
 * XML.as
 */

var XML;
var XMLList;

function XMLClass(runtime, scope, instance, baseClass) {
  var FLAG_IGNORE_COMMENTS                = 0x01;
  var FLAG_IGNORE_PROCESSING_INSTRUCTIONS = 0x02;
  var FLAG_IGNORE_WHITESPACE              = 0x04;
  var FLAG_PRETTY_PRINTING                = 0x08;

  XML = function (value) {
    if (!value) {
      toXML.call(this, "");
    } else if (value instanceof XML || value instanceof XMLList) {
      constructFromXML.call(this, xml);
    } else {
      toXML.call(this, value);
    }
  };

  // E4X 10.3
  function toXML(value) {
    if (value === null) {
      throw new TypeError(formatErrorMessage(Errors.ConvertNullToObjectError));
    } else if (value === undefined) {
      throw new TypeError(formatErrorMessage(Errors.ConvertUndefinedToObjectError));
    } else if (value instanceof XML) {
      return value;
    } else if (value instanceof XMLList) {
      // TODO: Return first XML element in the list.
      throw new TypeError(formatErrorMessage(Errors.XMLMarkupMustBeWellFormed));
    } else {
      return constructFromString.call(this, toString(value));
    }
  }

  function constructFromString(string) {
    warning("TODO: Parse: " + string);
  }

  function constructFromXML(xml) {
    warning("TODO: Clone: " + xml);
  }

  var c = new runtime.domain.system.Class("XML", XML, Domain.passthroughCallable(XML));

  c._flags = FLAG_IGNORE_COMMENTS | FLAG_IGNORE_PROCESSING_INSTRUCTIONS | FLAG_IGNORE_WHITESPACE | FLAG_PRETTY_PRINTING;
  c._prettyIndent = 2;

  c.extend(baseClass);
  c.native = {
    static: {
      ignoreComments: {
        get: function ignoreComments() {
          return getBitFlags(c._flags, FLAG_IGNORE_COMMENTS);
        },
        set: function ignoreComments(newIgnore) {
          c._flags = setBitFlags(c._flags, FLAG_IGNORE_COMMENTS, newIgnore);
        }
      },
      ignoreProcessingInstructions: {
        get: function ignoreProcessingInstructions() {
          return getBitFlags(c._flags, FLAG_IGNORE_PROCESSING_INSTRUCTIONS);
        },
        set: function ignoreProcessingInstructions(newIgnore) {
          c._flags = setBitFlags(c._flags, FLAG_IGNORE_PROCESSING_INSTRUCTIONS, newIgnore);
        }
      },
      ignoreWhitespace: {
        get: function ignoreWhitespace() {
          return getBitFlags(c._flags, FLAG_IGNORE_WHITESPACE);
        },
        set: function ignoreWhitespace(newIgnore) {
          c._flags = setBitFlags(c._flags, FLAG_IGNORE_WHITESPACE, newIgnore);
        }
      },
      prettyPrinting: {
        get: function prettyPrinting() {
          return getBitFlags(c._flags, FLAG_PRETTY_PRINTING);
        },
        set: function prettyPrinting(newPretty) {
          c._flags = setBitFlags(c._flags, FLAG_PRETTY_PRINTING, newPretty);
        }
      },
      prettyIndent: {
        get: function prettyIndent() {
          return c._prettyIndent;
        },
        set: function prettyIndent(newIndent) {
          c._prettyIndent = newIndent;
        }
      }
    },
    instance: {
      toString: function toString() { // (void) -> String
        return this._value;
      },
      hasOwnProperty: function hasOwnProperty(P) { // (P) -> Boolean
        notImplemented("XML.hasOwnProperty");
      },
      propertyIsEnumerable: function propertyIsEnumerable(P) { // (P) -> Boolean
        notImplemented("XML.propertyIsEnumerable");
      },
      addNamespace: function addNamespace(ns) { // (ns) -> XML
        notImplemented("XML.addNamespace");
      },
      appendChild: function appendChild(child) { // (child) -> XML
        notImplemented("XML.appendChild");
      },
      attribute: function attribute(arg) { // (arg) -> XMLList
        notImplemented("XML.attribute");
      },
      attributes: function attributes() { // (void) -> XMLList
        notImplemented("XML.attributes");
      },
      child: function child(propertyName) { // (propertyName) -> XMLList
        notImplemented("XML.child");
      },
      childIndex: function childIndex() { // (void) -> int
        notImplemented("XML.childIndex");
      },
      children: function children() { // (void) -> XMLList
        notImplemented("XML.children");
      },
      comments: function comments() { // (void) -> XMLList
        notImplemented("XML.comments");
      },
      contains: function contains(value) { // (value) -> Boolean
        notImplemented("XML.contains");
      },
      copy: function copy() { // (void) -> XML
        notImplemented("XML.copy");
      },
      descendants: function descendants(name) { // (name = "*") -> XMLList
        notImplemented("XML.descendants");
      },
      elements: function elements(name) { // (name = "*") -> XMLList
        notImplemented("XML.elements");
      },
      hasComplexContent: function hasComplexContent() { // (void) -> Boolean
        notImplemented("XML.hasComplexContent");
      },
      hasSimpleContent: function hasSimpleContent() { // (void) -> Boolean
        notImplemented("XML.hasSimpleContent");
      },
      inScopeNamespaces: function inScopeNamespaces() { // (void) -> Array
        notImplemented("XML.inScopeNamespaces");
      },
      insertChildAfter: function insertChildAfter(child1, child2) { // (child1, child2) -> any
        notImplemented("XML.insertChildAfter");
      },
      insertChildBefore: function insertChildBefore(child1, child2) { // (child1, child2) -> any
        notImplemented("XML.insertChildBefore");
      },
      localName: function localName() { // (void) -> Object
        notImplemented("XML.localName");
      },
      name: function name() { // (void) -> Object
        notImplemented("XML.name");
      },
      _namespace: function _namespace(prefix, argc) { // (prefix, argc:int) -> any
        notImplemented("XML._namespace");
      },
      namespaceDeclarations: function namespaceDeclarations() { // (void) -> Array
        notImplemented("XML.namespaceDeclarations");
      },
      nodeKind: function nodeKind() { // (void) -> String
        notImplemented("XML.nodeKind");
      },
      normalize: function normalize() { // (void) -> XML
        notImplemented("XML.normalize");
      },
      parent: function parent() { // (void) -> any
        notImplemented("XML.parent");
      },
      processingInstructions: function processingInstructions(name) { // (name = "*") -> XMLList
        notImplemented("XML.processingInstructions");
      },
      prependChild: function prependChild(value) { // (value) -> XML
        notImplemented("XML.prependChild");
      },
      removeNamespace: function removeNamespace(ns) { // (ns) -> XML
        notImplemented("XML.removeNamespace");
      },
      replace: function replace(propertyName, value) { // (propertyName, value) -> XML
        notImplemented("XML.replace");
      },
      setChildren: function setChildren(value) { // (value) -> XML
        notImplemented("XML.setChildren");
      },
      setLocalName: function setLocalName(name) { // (name) -> void
        notImplemented("XML.setLocalName");
      },
      setName: function setName(name) { // (name) -> void
        notImplemented("XML.setName");
      },
      setNamespace: function setNamespace(ns) { // (ns) -> void
        notImplemented("XML.setNamespace");
      },
      text: function text() { // (void) -> XMLList
        notImplemented("XML.text");
      },
      toXMLString: function toXMLString() { // (void) -> String
        notImplemented("XML.toXMLString");
      },
      notification: function notification() { // (void) -> Function
        notImplemented("XML.notification");
      },
      setNotification: function setNotification(f) { // (f:Function) -> any
        notImplemented("XML.setNotification");
      }
    }
  };
  return c;
}

function XMLListClass(runtime, scope, instance, baseClass) {
  XMLList = function () {}
  var c = new runtime.domain.system.Class("XMLList", XMLList, Domain.passthroughCallable(XMLList));
  c.extend(baseClass);
  c.native = {
    static: {
    },
    instance: {
      toString: function toString() { // (void) -> String
        notImplemented("XMLList.toString");
      },
      hasOwnProperty: function hasOwnProperty(P) { // (P) -> Boolean
        notImplemented("XMLList.hasOwnProperty");
      },
      propertyIsEnumerable: function propertyIsEnumerable(P) { // (P) -> Boolean
        notImplemented("XMLList.propertyIsEnumerable");
      },
      attribute: function attribute(arg) { // (arg) -> XMLList
        notImplemented("XMLList.attribute");
      },
      attributes: function attributes() { // (void) -> XMLList
        notImplemented("XMLList.attributes");
      },
      child: function child(propertyName) { // (propertyName) -> XMLList
        notImplemented("XMLList.child");
      },
      children: function children() { // (void) -> XMLList
        notImplemented("XMLList.children");
      },
      comments: function comments() { // (void) -> XMLList
        notImplemented("XMLList.comments");
      },
      contains: function contains(value) { // (value) -> Boolean
        notImplemented("XMLList.contains");
      },
      copy: function copy() { // (void) -> XMLList
        notImplemented("XMLList.copy");
      },
      descendants: function descendants(name) { // (name = "*") -> XMLList
        notImplemented("XMLList.descendants");
      },
      elements: function elements(name) { // (name = "*") -> XMLList
        notImplemented("XMLList.elements");
      },
      hasComplexContent: function hasComplexContent() { // (void) -> Boolean
        notImplemented("XMLList.hasComplexContent");
      },
      hasSimpleContent: function hasSimpleContent() { // (void) -> Boolean
        notImplemented("XMLList.hasSimpleContent");
      },
      length: function length() { // (void) -> int
        notImplemented("XMLList.length");
      },
      name: function name() { // (void) -> Object
        notImplemented("XMLList.name");
      },
      normalize: function normalize() { // (void) -> XMLList
        notImplemented("XMLList.normalize");
      },
      parent: function parent() { // (void) -> any
        notImplemented("XMLList.parent");
      },
      processingInstructions: function processingInstructions(name) { // (name = "*") -> XMLList
        notImplemented("XMLList.processingInstructions");
      },
      text: function text() { // (void) -> XMLList
        notImplemented("XMLList.text");
      },
      toXMLString: function toXMLString() { // (void) -> String
        notImplemented("XMLList.toXMLString");
      },
      addNamespace: function addNamespace(ns) { // (ns) -> XML
        notImplemented("XMLList.addNamespace");
      },
      appendChild: function appendChild(child) { // (child) -> XML
        notImplemented("XMLList.appendChild");
      },
      childIndex: function childIndex() { // (void) -> int
        notImplemented("XMLList.childIndex");
      },
      inScopeNamespaces: function inScopeNamespaces() { // (void) -> Array
        notImplemented("XMLList.inScopeNamespaces");
      },
      insertChildAfter: function insertChildAfter(child1, child2) { // (child1, child2) -> any
        notImplemented("XMLList.insertChildAfter");
      },
      insertChildBefore: function insertChildBefore(child1, child2) { // (child1, child2) -> any
        notImplemented("XMLList.insertChildBefore");
      },
      nodeKind: function nodeKind() { // (void) -> String
        notImplemented("XMLList.nodeKind");
      },
      _namespace: function _namespace(prefix, argc) { // (prefix, argc:int) -> any
        notImplemented("XMLList._namespace");
      },
      localName: function localName() { // (void) -> Object
        notImplemented("XMLList.localName");
      },
      namespaceDeclarations: function namespaceDeclarations() { // (void) -> Array
        notImplemented("XMLList.namespaceDeclarations");
      },
      prependChild: function prependChild(value) { // (value) -> XML
        notImplemented("XMLList.prependChild");
      },
      removeNamespace: function removeNamespace(ns) { // (ns) -> XML
        notImplemented("XMLList.removeNamespace");
      },
      replace: function replace(propertyName, value) { // (propertyName, value) -> XML
        notImplemented("XMLList.replace");
      },
      setChildren: function setChildren(value) { // (value) -> XML
        notImplemented("XMLList.setChildren");
      },
      setLocalName: function setLocalName(name) { // (name) -> void
        notImplemented("XMLList.setLocalName");
      },
      setName: function setName(name) { // (name) -> void
        notImplemented("XMLList.setName");
      },
      setNamespace: function setNamespace(ns) { // (ns) -> void
        notImplemented("XMLList.setNamespace");
      }
    }
  };
  return c;
}

function QNameClass(runtime, scope, instance, baseClass) {
  function QName() {}
  var c = new runtime.domain.system.Class("QName", QName, Domain.passthroughCallable(QName));
  c.extend(baseClass);
  c.native = {
    static: {
    },
    instance: {
      localName: {
        get: function localName() { // (void) -> String
          notImplemented("QName.localName");
          return this._localName;
        }
      },
      uri: {
        get: function uri() { // (void) -> any
          notImplemented("QName.uri");
          return this._uri;
        }
      }
    }
  };
  return c;
};

<commit_msg>revert trival ws change<commit_after>/**
 * XML.as
 */

var XML;
var XMLList;

function XMLClass(runtime, scope, instance, baseClass) {
  var FLAG_IGNORE_COMMENTS                = 0x01;
  var FLAG_IGNORE_PROCESSING_INSTRUCTIONS = 0x02;
  var FLAG_IGNORE_WHITESPACE              = 0x04;
  var FLAG_PRETTY_PRINTING                = 0x08;

  XML = function (value) {
    if (!value) {
      toXML.call(this, "");
    } else if (value instanceof XML || value instanceof XMLList) {
      constructFromXML.call(this, xml);
    } else {
      toXML.call(this, value);
    }
  };

  // E4X 10.3
  function toXML(value) {
    if (value === null) {
      throw new TypeError(formatErrorMessage(Errors.ConvertNullToObjectError));
    } else if (value === undefined) {
      throw new TypeError(formatErrorMessage(Errors.ConvertUndefinedToObjectError));
    } else if (value instanceof XML) {
      return value;
    } else if (value instanceof XMLList) {
      // TODO: Return first XML element in the list.
      throw new TypeError(formatErrorMessage(Errors.XMLMarkupMustBeWellFormed));
    } else {
      return constructFromString.call(this, toString(value));
    }
  }

  function constructFromString(string) {
    warning("TODO: Parse: " + string);
  }

  function constructFromXML(xml) {
    warning("TODO: Clone: " + xml);
  }

  var c = new runtime.domain.system.Class("XML", XML, Domain.passthroughCallable(XML));

  c._flags = FLAG_IGNORE_COMMENTS | FLAG_IGNORE_PROCESSING_INSTRUCTIONS | FLAG_IGNORE_WHITESPACE | FLAG_PRETTY_PRINTING;
  c._prettyIndent = 2;

  c.extend(baseClass);
  c.native = {
    static: {
      ignoreComments: {
        get: function ignoreComments() {
          return getBitFlags(c._flags, FLAG_IGNORE_COMMENTS);
        },
        set: function ignoreComments(newIgnore) {
          c._flags = setBitFlags(c._flags, FLAG_IGNORE_COMMENTS, newIgnore);
        }
      },
      ignoreProcessingInstructions: {
        get: function ignoreProcessingInstructions() {
          return getBitFlags(c._flags, FLAG_IGNORE_PROCESSING_INSTRUCTIONS);
        },
        set: function ignoreProcessingInstructions(newIgnore) {
          c._flags = setBitFlags(c._flags, FLAG_IGNORE_PROCESSING_INSTRUCTIONS, newIgnore);
        }
      },
      ignoreWhitespace: {
        get: function ignoreWhitespace() {
          return getBitFlags(c._flags, FLAG_IGNORE_WHITESPACE);
        },
        set: function ignoreWhitespace(newIgnore) {
          c._flags = setBitFlags(c._flags, FLAG_IGNORE_WHITESPACE, newIgnore);
        }
      },
      prettyPrinting: {
        get: function prettyPrinting() {
          return getBitFlags(c._flags, FLAG_PRETTY_PRINTING);
        },
        set: function prettyPrinting(newPretty) {
          c._flags = setBitFlags(c._flags, FLAG_PRETTY_PRINTING, newPretty);
        }
      },
      prettyIndent: {
        get: function prettyIndent() {
          return c._prettyIndent;
        },
        set: function prettyIndent(newIndent) {
          c._prettyIndent = newIndent;
        }
      }
    },
    instance: {
      toString: function toString() { // (void) -> String
        return this._value;
      },
      hasOwnProperty: function hasOwnProperty(P) { // (P) -> Boolean
        notImplemented("XML.hasOwnProperty");
      },
      propertyIsEnumerable: function propertyIsEnumerable(P) { // (P) -> Boolean
        notImplemented("XML.propertyIsEnumerable");
      },
      addNamespace: function addNamespace(ns) { // (ns) -> XML
        notImplemented("XML.addNamespace");
      },
      appendChild: function appendChild(child) { // (child) -> XML
        notImplemented("XML.appendChild");
      },
      attribute: function attribute(arg) { // (arg) -> XMLList
        notImplemented("XML.attribute");
      },
      attributes: function attributes() { // (void) -> XMLList
        notImplemented("XML.attributes");
      },
      child: function child(propertyName) { // (propertyName) -> XMLList
        notImplemented("XML.child");
      },
      childIndex: function childIndex() { // (void) -> int
        notImplemented("XML.childIndex");
      },
      children: function children() { // (void) -> XMLList
        notImplemented("XML.children");
      },
      comments: function comments() { // (void) -> XMLList
        notImplemented("XML.comments");
      },
      contains: function contains(value) { // (value) -> Boolean
        notImplemented("XML.contains");
      },
      copy: function copy() { // (void) -> XML
        notImplemented("XML.copy");
      },
      descendants: function descendants(name) { // (name = "*") -> XMLList
        notImplemented("XML.descendants");
      },
      elements: function elements(name) { // (name = "*") -> XMLList
        notImplemented("XML.elements");
      },
      hasComplexContent: function hasComplexContent() { // (void) -> Boolean
        notImplemented("XML.hasComplexContent");
      },
      hasSimpleContent: function hasSimpleContent() { // (void) -> Boolean
        notImplemented("XML.hasSimpleContent");
      },
      inScopeNamespaces: function inScopeNamespaces() { // (void) -> Array
        notImplemented("XML.inScopeNamespaces");
      },
      insertChildAfter: function insertChildAfter(child1, child2) { // (child1, child2) -> any
        notImplemented("XML.insertChildAfter");
      },
      insertChildBefore: function insertChildBefore(child1, child2) { // (child1, child2) -> any
        notImplemented("XML.insertChildBefore");
      },
      localName: function localName() { // (void) -> Object
        notImplemented("XML.localName");
      },
      name: function name() { // (void) -> Object
        notImplemented("XML.name");
      },
      _namespace: function _namespace(prefix, argc) { // (prefix, argc:int) -> any
        notImplemented("XML._namespace");
      },
      namespaceDeclarations: function namespaceDeclarations() { // (void) -> Array
        notImplemented("XML.namespaceDeclarations");
      },
      nodeKind: function nodeKind() { // (void) -> String
        notImplemented("XML.nodeKind");
      },
      normalize: function normalize() { // (void) -> XML
        notImplemented("XML.normalize");
      },
      parent: function parent() { // (void) -> any
        notImplemented("XML.parent");
      },
      processingInstructions: function processingInstructions(name) { // (name = "*") -> XMLList
        notImplemented("XML.processingInstructions");
      },
      prependChild: function prependChild(value) { // (value) -> XML
        notImplemented("XML.prependChild");
      },
      removeNamespace: function removeNamespace(ns) { // (ns) -> XML
        notImplemented("XML.removeNamespace");
      },
      replace: function replace(propertyName, value) { // (propertyName, value) -> XML
        notImplemented("XML.replace");
      },
      setChildren: function setChildren(value) { // (value) -> XML
        notImplemented("XML.setChildren");
      },
      setLocalName: function setLocalName(name) { // (name) -> void
        notImplemented("XML.setLocalName");
      },
      setName: function setName(name) { // (name) -> void
        notImplemented("XML.setName");
      },
      setNamespace: function setNamespace(ns) { // (ns) -> void
        notImplemented("XML.setNamespace");
      },
      text: function text() { // (void) -> XMLList
        notImplemented("XML.text");
      },
      toXMLString: function toXMLString() { // (void) -> String
        notImplemented("XML.toXMLString");
      },
      notification: function notification() { // (void) -> Function
        notImplemented("XML.notification");
      },
      setNotification: function setNotification(f) { // (f:Function) -> any
        notImplemented("XML.setNotification");
      }
    }
  };
  return c;
}

function XMLListClass(runtime, scope, instance, baseClass) {
  XMLList = function () {}
  var c = new runtime.domain.system.Class("XMLList", XMLList, Domain.passthroughCallable(XMLList));
  c.extend(baseClass);
  c.native = {
    static: {
    },
    instance: {
      toString: function toString() { // (void) -> String
        notImplemented("XMLList.toString");
      },
      hasOwnProperty: function hasOwnProperty(P) { // (P) -> Boolean
        notImplemented("XMLList.hasOwnProperty");
      },
      propertyIsEnumerable: function propertyIsEnumerable(P) { // (P) -> Boolean
        notImplemented("XMLList.propertyIsEnumerable");
      },
      attribute: function attribute(arg) { // (arg) -> XMLList
        notImplemented("XMLList.attribute");
      },
      attributes: function attributes() { // (void) -> XMLList
        notImplemented("XMLList.attributes");
      },
      child: function child(propertyName) { // (propertyName) -> XMLList
        notImplemented("XMLList.child");
      },
      children: function children() { // (void) -> XMLList
        notImplemented("XMLList.children");
      },
      comments: function comments() { // (void) -> XMLList
        notImplemented("XMLList.comments");
      },
      contains: function contains(value) { // (value) -> Boolean
        notImplemented("XMLList.contains");
      },
      copy: function copy() { // (void) -> XMLList
        notImplemented("XMLList.copy");
      },
      descendants: function descendants(name) { // (name = "*") -> XMLList
        notImplemented("XMLList.descendants");
      },
      elements: function elements(name) { // (name = "*") -> XMLList
        notImplemented("XMLList.elements");
      },
      hasComplexContent: function hasComplexContent() { // (void) -> Boolean
        notImplemented("XMLList.hasComplexContent");
      },
      hasSimpleContent: function hasSimpleContent() { // (void) -> Boolean
        notImplemented("XMLList.hasSimpleContent");
      },
      length: function length() { // (void) -> int
        notImplemented("XMLList.length");
      },
      name: function name() { // (void) -> Object
        notImplemented("XMLList.name");
      },
      normalize: function normalize() { // (void) -> XMLList
        notImplemented("XMLList.normalize");
      },
      parent: function parent() { // (void) -> any
        notImplemented("XMLList.parent");
      },
      processingInstructions: function processingInstructions(name) { // (name = "*") -> XMLList
        notImplemented("XMLList.processingInstructions");
      },
      text: function text() { // (void) -> XMLList
        notImplemented("XMLList.text");
      },
      toXMLString: function toXMLString() { // (void) -> String
        notImplemented("XMLList.toXMLString");
      },
      addNamespace: function addNamespace(ns) { // (ns) -> XML
        notImplemented("XMLList.addNamespace");
      },
      appendChild: function appendChild(child) { // (child) -> XML
        notImplemented("XMLList.appendChild");
      },
      childIndex: function childIndex() { // (void) -> int
        notImplemented("XMLList.childIndex");
      },
      inScopeNamespaces: function inScopeNamespaces() { // (void) -> Array
        notImplemented("XMLList.inScopeNamespaces");
      },
      insertChildAfter: function insertChildAfter(child1, child2) { // (child1, child2) -> any
        notImplemented("XMLList.insertChildAfter");
      },
      insertChildBefore: function insertChildBefore(child1, child2) { // (child1, child2) -> any
        notImplemented("XMLList.insertChildBefore");
      },
      nodeKind: function nodeKind() { // (void) -> String
        notImplemented("XMLList.nodeKind");
      },
      _namespace: function _namespace(prefix, argc) { // (prefix, argc:int) -> any
        notImplemented("XMLList._namespace");
      },
      localName: function localName() { // (void) -> Object
        notImplemented("XMLList.localName");
      },
      namespaceDeclarations: function namespaceDeclarations() { // (void) -> Array
        notImplemented("XMLList.namespaceDeclarations");
      },
      prependChild: function prependChild(value) { // (value) -> XML
        notImplemented("XMLList.prependChild");
      },
      removeNamespace: function removeNamespace(ns) { // (ns) -> XML
        notImplemented("XMLList.removeNamespace");
      },
      replace: function replace(propertyName, value) { // (propertyName, value) -> XML
        notImplemented("XMLList.replace");
      },
      setChildren: function setChildren(value) { // (value) -> XML
        notImplemented("XMLList.setChildren");
      },
      setLocalName: function setLocalName(name) { // (name) -> void
        notImplemented("XMLList.setLocalName");
      },
      setName: function setName(name) { // (name) -> void
        notImplemented("XMLList.setName");
      },
      setNamespace: function setNamespace(ns) { // (ns) -> void
        notImplemented("XMLList.setNamespace");
      }
    }
  };
  return c;
}

function QNameClass(runtime, scope, instance, baseClass) {
  function QName() {}
  var c = new runtime.domain.system.Class("QName", QName, Domain.passthroughCallable(QName));
  c.extend(baseClass);
  c.native = {
    static: {
    },
    instance: {
      localName: {
        get: function localName() { // (void) -> String
          notImplemented("QName.localName");
          return this._localName;
        }
      },
      uri: {
        get: function uri() { // (void) -> any
          notImplemented("QName.uri");
          return this._uri;
        }
      }
    }
  };
  return c;
};
<|endoftext|>