<commit_before>export { ChannelPartInfo };
export { ChannelPartInfoPool };
export { FiltersBiasesPartInfo };
export { FiltersBiasesPartInfoPool };

import * as Pool from "../../util/Pool.js";

/**
 * Half channels information. Describe channel index range of lower half or higher half.
 *
 *
 * @member {number} inputChannelCount
 *   This ChannelPart includes how many input channels.
 *
 * @member {number} effectFilterY_passThrough, effectFilterX_passThrough
 *   For pass-through filters, there is only one position (inside the effect depthwise filter) with non-zero value. All other
 * positions of the filters should be zero.
 *   - Note: Unfortunately, the pass-through feature may not work for ( dilation > 1 ) because the non-zero-filter-value might
 *       be just at the dilation position which does not exist in a filter. So, only ( dilation == 1 ) is supported.
 *   - Negative value means this part is not for pass-through.
 *
 * @member {boolean} bPassThrough
 *   If true, this is the half channels for pass-through input to output.
 */
class ChannelPartInfo {

  /**
   */
  constructor( inputChannelCount, effectFilterY_passThrough = -1, effectFilterX_passThrough = -1 ) {
    ChannelPartInfo.setAsConstructor.call( this, inputChannelCount, effectFilterY_passThrough, effectFilterX_passThrough );
  }

  /**
   * @param {ChannelPartInfo} this
   *   The object to be initialized.
   *
   * @return {ChannelPartInfo}
   *   Return the this object.
   */
  static setAsConstructor( inputChannelCount, effectFilterY_passThrough = -1, effectFilterX_passThrough = -1 ) {
    this.inputChannelCount = inputChannelCount;
    this.effectFilterY_passThrough = effectFilterY_passThrough;
    this.effectFilterX_passThrough = effectFilterX_passThrough;

    this.bPassThrough = ( ( this.effectFilterY_passThrough >= 0 ) && ( this.effectFilterX_passThrough >= 0 ) );
    return this;
  }

  /**
   * Sub-class should override this method (and call super.disposeResources() before return).
   */
  disposeResources() {
    this.bPassThrough = undefined;
    this.effectFilterX_passThrough = undefined;
    this.effectFilterY_passThrough = undefined;
    this.inputChannelCount = undefined;
    //super.disposeResources();
  }

  /**
   * After calling this method, this object should be viewed as disposed and should not be operated again.
   */
  disposeResources_and_recycleToPool() {
    this.disposeResources();
    ChannelPartInfoPool.Singleton.recycle( this );
  }

  /**
   * @return {boolean} Return true, if the specified position should be non-zero for pass-through input to output.
   */
  isPassThrough_FilterPosition_NonZero( effectFilterY, effectFilterX ) {
    if ( ( effectFilterY == this.effectFilterY_passThrough ) && ( effectFilterX == this.effectFilterX_passThrough ) )
      return true;
    return false;
  }
}

/**
 * Providing ChannelPartInfo.
 *
 */
class ChannelPartInfoPool extends Pool.Root {

  constructor() {
    super( "Depthwise.ChannelPartInfoPool", ChannelPartInfo, ChannelPartInfo.setAsConstructor );
  }

}

/**
 * Used as default Depthwise.ChannelPartInfo provider.
 */
ChannelPartInfoPool.Singleton = new ChannelPartInfoPool();

/**
 * Describe a range for a (depthwise) filters and a biases.
 *
 *
 * @member {ChannelPartInfo[]} aChannelPartInfoArray
 *   Every input-output relationship of this parts.
 *
 */
class FiltersBiasesPartInfo {

  /**
   *
   */
  constructor( aChannelPartInfoArray ) {
    this.aChannelPartInfoArray = aChannelPartInfoArray;
  }

  /**
   *
   * @param {FiltersBiasesPartInfo} this
   *   The object to be initialized.
   *
   * @return {FiltersBiasesPartInfo}
   *   Return the this object.
   */
  static setAsConstructor( aChannelPartInfoArray ) {
    this.aChannelPartInfoArray = aChannelPartInfoArray;
    return this;
  }

  /**
   * Sub-class should override this method (and call super.disposeResources() before return).
   */
  disposeResources() {
    this.aChannelPartInfoArray = null; // Because the array is not created by this FiltersBiasesPartInfo, do not recyclye it here.
    //super.disposeResources();
  }

  /**
   * After calling this method, this object should be viewed as disposed and should not be operated again.
   */
  disposeResources_and_recycleToPool() {
    this.disposeResources();
    FiltersBiasesPartInfoPool.Singleton.recycle( this );
  }

}

/**
 * Providing FiltersBiasesPartInfo.
 *
 */
class FiltersBiasesPartInfoPool extends Pool.Root {

  constructor() {
    super( "Depthwise.FiltersBiasesPartInfoPool", FiltersBiasesPartInfo, FiltersBiasesPartInfo.setAsConstructor );
  }

}

/**
 * Used as default Depthwise.FiltersBiasesPartInfo provider.
 */
FiltersBiasesPartInfoPool.Singleton = new FiltersBiasesPartInfoPool();

<commit_msg>Update Depthwise_ChannelPartInfo.js<commit_after>export { ChannelPartInfo };
export { FiltersBiasesPartInfo };

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../util/Recyclable.js";

/**
 * Half channels information. Describe channel index range of lower half or higher half.
 *
 *
 * @member {number} inputChannelCount
 *   This ChannelPart includes how many input channels.
 *
 * @member {number} effectFilterY_passThrough, effectFilterX_passThrough
 *   For pass-through filters, there is only one position (inside the effect depthwise filter) with non-zero value. All other
 * positions of the filters should be zero.
 *   - Note: Unfortunately, the pass-through feature may not work for ( dilation > 1 ) because the non-zero-filter-value might
 *       be just at the dilation position which does not exist in a filter. So, only ( dilation == 1 ) is supported.
 *   - Negative value means this part is not for pass-through.
 *
 * @member {boolean} bPassThrough
 *   If true, this is the half channels for pass-through input to output.
 */
class ChannelPartInfo extends Recyclable.Root {

  /**
   * Used as default Depthwise.ChannelPartInfo provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Depthwise.ChannelPartInfoPool", ChannelPartInfo, ChannelPartInfo.setAsConstructor );

  /**
   */
  constructor( inputChannelCount, effectFilterY_passThrough = -1, effectFilterX_passThrough = -1 ) {
    super();
    ChannelPartInfo.setAsConstructor_self.call( this, inputChannelCount, effectFilterY_passThrough, effectFilterX_passThrough );
  }

  /** @override */
  static setAsConstructor( inputChannelCount, effectFilterY_passThrough = -1, effectFilterX_passThrough = -1 ) {
    super.setAsConstructor();
    ChannelPartInfo.setAsConstructor_self.call( this, inputChannelCount, effectFilterY_passThrough, effectFilterX_passThrough );
    return this;
  }

  /** @override */
  static setAsConstructor_self( inputChannelCount, effectFilterY_passThrough = -1, effectFilterX_passThrough = -1 ) {
    this.inputChannelCount = inputChannelCount;
    this.effectFilterY_passThrough = effectFilterY_passThrough;
    this.effectFilterX_passThrough = effectFilterX_passThrough;

    this.bPassThrough = ( ( this.effectFilterY_passThrough >= 0 ) && ( this.effectFilterX_passThrough >= 0 ) );
  }

  /** @override */
  disposeResources() {
    this.bPassThrough = undefined;
    this.effectFilterX_passThrough = undefined;
    this.effectFilterY_passThrough = undefined;
    this.inputChannelCount = undefined;
    super.disposeResources();
  }

  /**
   * @return {boolean} Return true, if the specified position should be non-zero for pass-through input to output.
   */
  isPassThrough_FilterPosition_NonZero( effectFilterY, effectFilterX ) {
    if ( ( effectFilterY == this.effectFilterY_passThrough ) && ( effectFilterX == this.effectFilterX_passThrough ) )
      return true;
    return false;
  }
}

/**
 * Describe a range for a (depthwise) filters and a biases.
 *
 *
 * @member {ChannelPartInfo[]} aChannelPartInfoArray
 *   Every input-output relationship of this parts.
 *
 */
class FiltersBiasesPartInfo {

  /**
   * Used as default Depthwise.FiltersBiasesPartInfo provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Depthwise.FiltersBiasesPartInfoPool", FiltersBiasesPartInfo, FiltersBiasesPartInfo.setAsConstructor );

  /**
   *
   */
  constructor( aChannelPartInfoArray ) {
    super();
    FiltersBiasesPartInfo.setAsConstructor_self.call( this );
  }

  /** @override */
  static setAsConstructor( aChannelPartInfoArray ) {
    super.setAsConstructor();
    FiltersBiasesPartInfo.setAsConstructor_self.call( this );
    return this;
  }

  /** @override */
  static setAsConstructor( aChannelPartInfoArray ) {
    this.aChannelPartInfoArray = aChannelPartInfoArray;
  }

  /** @override */
  disposeResources() {
    this.aChannelPartInfoArray = null; // Because the array is not created by this FiltersBiasesPartInfo, do not recyclye it here.
    super.disposeResources();
  }

}

<|endoftext|>


<commit_before>var Promise = require('bluebird')

module.exports = {
  changedCommunities: function (startTime, endTime) {
    return Promise.join(
      // new members
      User.createdInTimeRange(startTime, endTime)
      .fetchAll({withRelated: ['memberships']}),

      // new posts
      Post.createdInTimeRange(startTime, endTime)
      .query(qb => qb.where('post.type', '!=', 'welcome'))
      .fetchAll({withRelated: [
        {communities: qb => qb.column('community.id')}
      ]}),

      // new comments
      Comment.createdInTimeRange(startTime, endTime)
      .query(qb => {
        qb.join('post', function () {
          this.on('post.id', 'comment.post_id')
        })
        qb.where('post.type', '!=', 'welcome')
      })
      .fetchAll({withRelated: [
        {post: qb => qb.column('id')},
        {'post.communities': qb => qb.column('community.id')}
      ]})
    ).spread(function (users, posts, comments) {
      var communityIds = []

      users.each(u => {
        var ids = u.relations.memberships.where({active: true}).map(m => m.get('community_id'))
        communityIds.push(ids)
      })

      posts.each(p => {
        var ids = p.relations.communities.map('id')
        communityIds.push(ids)
      })

      comments.each(c => {
        var ids = c.relations.post.relations.communities.map('id')
        communityIds.push(ids)
      })

      return _.union.apply(_, communityIds).sort((a, b) => a > b)
    })
  }

}
<commit_msg>filter out projects from changes in communities<commit_after>var Promise = require('bluebird')

module.exports = {
  changedCommunities: function (startTime, endTime) {
    return Promise.join(
      // new members
      User.createdInTimeRange(startTime, endTime)
      .fetchAll({withRelated: ['memberships']}),

      // new posts
      Post.createdInTimeRange(startTime, endTime)
      .query(qb => qb.where('post.type', 'not in', ['welcome', 'project']))
      .fetchAll({withRelated: [
        {communities: qb => qb.column('community.id')}
      ]}),

      // new comments
      Comment.createdInTimeRange(startTime, endTime)
      .query(qb => {
        qb.join('post', function () {
          this.on('post.id', 'comment.post_id')
        })
        qb.where('post.type', '!=', 'welcome')
      })
      .fetchAll({withRelated: [
        {post: qb => qb.column('id')},
        {'post.communities': qb => qb.column('community.id')}
      ]})
    ).spread(function (users, posts, comments) {
      var communityIds = []

      users.each(u => {
        var ids = u.relations.memberships.where({active: true}).map(m => m.get('community_id'))
        communityIds.push(ids)
      })

      posts.each(p => {
        var ids = p.relations.communities.map('id')
        communityIds.push(ids)
      })

      comments.each(c => {
        var ids = c.relations.post.relations.communities.map('id')
        communityIds.push(ids)
      })

      return _.union.apply(_, communityIds).sort((a, b) => a > b)
    })
  }

}
<|endoftext|>


<commit_before>const FloodFill = require('./floodfill.js');

module.exports = function(mapSize, tileSize, innerTileSize, trailTileSize) {
	this.map = [];
	this.updateTiles = [];
	this.mapSize = mapSize;
	this.tileSize = tileSize;
	this.innerTileSize = innerTileSize;
	this.trailTileSize = trailTileSize;

	this.setCellData = function(x, y, id, color, type) {
		this.map[x][y] = {
			x: x,
			y: y,
			id: id,
			color: color,
			type: type
		};
		this.updateTiles.push(this.map[x][y]);
	};

	this.clearPlayerLand = function(id) {
		for (var i = 0; i < this.mapSize; i++) {
			for (var j = 0; j < this.mapSize; j++) {
				if (this.map[i][j].id == id) {
					this.setCellData(i, j, 0, "#3a4f56", "land");
				}
			}
		}
	};

	this.addPlayerLand = function(player) {
		for (var i = -1; i < 2; i++) {
			for (var j = -1; j < 2; j++) {
				this.setCellData(player.x + i, player.y + j, player.id, player.color, "land");
			}
		}
	};

	this.floodFill = function(player) {
		var tempArray = [];

		var tempMinX = this.getMinMaxPlayerCoords(player.id).minX;
		tempMinX -= 1;
		var tempMaxX = this.getMinMaxPlayerCoords(player.id).maxX;
		tempMaxX += 1;
		var tempMinY = this.getMinMaxPlayerCoords(player.id).minY;
		tempMinY -= 1;
		var tempMaxY = this.getMinMaxPlayerCoords(player.id).maxY;
		tempMaxY += 1;
		for (var k = tempMinX; k <= tempMaxX; k++) {
			for (var l = tempMinY; l <= tempMaxY; l++) {
				if (k > tempMinX && k < tempMaxX && l > tempMinY && l < tempMaxY) {
					tempArray.push(this.map[k][l]);
				} else {
					tempArray.push({ //add blank layer
						x: k,
						y: l,
						id: 0,
						color: "#3a4f56",
						type: "land"
					});
				}
			}
		}

		var tempFloodFill = new FloodFill(tempArray, tempMinX, tempMaxX, tempMinY, tempMaxY, player.id);

		for (var j = 0; j < tempFloodFill.length; j++) {
			if (tempFloodFill[j].id == player.id) {
				this.setCellData(tempFloodFill[j].x, tempFloodFill[j].y, tempFloodFill[j].id, player.color, "land");
			}
		}
	};

	this.getMinMaxPlayerCoords = function(id) {
		var tempMinX = this.mapSize;
		var tempMinY = this.mapSize;
		var tempMaxX = 0;
		var tempMaxY = 0;
		for (var i = 0; i < this.mapSize; i++) {
			for (var j = 0; j < this.mapSize; j++) {
				if (this.map[i][j].id == id) {
					if (this.map[i][j].x < tempMinX) {
						tempMinX = this.map[i][j].x;
					}
					if (this.map[i][j].y < tempMinY) {
						tempMinY = this.map[i][j].y;
					}
					if (this.map[i][j].x > tempMaxX) {
						tempMaxX = this.map[i][j].x;
					}
					if (this.map[i][j].y > tempMaxY) {
						tempMaxY = this.map[i][j].y;
					}
				}
			}
		}
		var output = {
			minX: tempMinX,
			minY: tempMinY,
			maxX: tempMaxX,
			maxY: tempMaxY
		};
		return output;
	};

	this.clearMap = function() {
		for (var i = 0; i < this.mapSize; i++) {
			this.map[i] = [];
			for (var j = 0; j < this.mapSize; j++) {
				this.map[i][j] = {
					x: i,
					y: j,
					id: 0,
					color: "#3a4f56",
					type: "land"
				};
			}
		}
	};
	this.clearMap();
};<commit_msg>Added debug code for new dev branch<commit_after>const FloodFill = require('./floodfill.js');

module.exports = function(mapSize, tileSize, innerTileSize, trailTileSize) {
	this.map = [];
	this.updateTiles = [];
	this.mapSize = mapSize;
	this.tileSize = tileSize;
	this.innerTileSize = innerTileSize;
	this.trailTileSize = trailTileSize;

	this.setCellData = function(x, y, id, color, type) {
		this.map[x][y] = {
			x: x,
			y: y,
			id: id,
			color: color,
			type: type
		};
		this.updateTiles.push(this.map[x][y]);
	};

	this.clearPlayerLand = function(id) {
		for (var i = 0; i < this.mapSize; i++) {
			for (var j = 0; j < this.mapSize; j++) {
				if (this.map[i][j].id == id) {
					this.setCellData(i, j, 0, "#3a4f56", "land");
				}
			}
		}
	};

	this.addPlayerLand = function(player) {
		for (var i = -1; i < 2; i++) {
			for (var j = -1; j < 2; j++) {
				this.setCellData(player.x + i, player.y + j, player.id, player.color, "land");
			}
		}
	};

	this.floodFill = function(player) {
		var tempArray = [];

		var tempMinX = this.getMinMaxPlayerCoords(player.id).minX;
		tempMinX -= 1;
		var tempMaxX = this.getMinMaxPlayerCoords(player.id).maxX;
		tempMaxX += 1;
		var tempMinY = this.getMinMaxPlayerCoords(player.id).minY;
		tempMinY -= 1;
		var tempMaxY = this.getMinMaxPlayerCoords(player.id).maxY;
		tempMaxY += 1;
		for (var k = tempMinX; k <= tempMaxX; k++) {
			for (var l = tempMinY; l <= tempMaxY; l++) {
				if (k > tempMinX && k < tempMaxX && l > tempMinY && l < tempMaxY) {
					tempArray.push(this.map[k][l]);
				} else {
					tempArray.push({ //add blank layer
						x: k,
						y: l,
						id: 0,
						color: "#3a4f56",
						type: "land"
					});
				}
			}
		}

		console.log("Sending array", tempArray);

		var tempFloodFill = new FloodFill(tempArray, tempMinX, tempMaxX, tempMinY, tempMaxY, player.id);

		for (var j = 0; j < tempFloodFill.length; j++) {
			if (tempFloodFill[j].id == player.id) {
				this.setCellData(tempFloodFill[j].x, tempFloodFill[j].y, tempFloodFill[j].id, player.color, "land");
			}
		}
	};

	this.getMinMaxPlayerCoords = function(id) {
		var tempMinX = this.mapSize;
		var tempMinY = this.mapSize;
		var tempMaxX = 0;
		var tempMaxY = 0;
		for (var i = 0; i < this.mapSize; i++) {
			for (var j = 0; j < this.mapSize; j++) {
				if (this.map[i][j].id == id) {
					if (this.map[i][j].x < tempMinX) {
						tempMinX = this.map[i][j].x;
					}
					if (this.map[i][j].y < tempMinY) {
						tempMinY = this.map[i][j].y;
					}
					if (this.map[i][j].x > tempMaxX) {
						tempMaxX = this.map[i][j].x;
					}
					if (this.map[i][j].y > tempMaxY) {
						tempMaxY = this.map[i][j].y;
					}
				}
			}
		}
		var output = {
			minX: tempMinX,
			minY: tempMinY,
			maxX: tempMaxX,
			maxY: tempMaxY
		};
		return output;
	};

	this.clearMap = function() {
		for (var i = 0; i < this.mapSize; i++) {
			this.map[i] = [];
			for (var j = 0; j < this.mapSize; j++) {
				this.map[i][j] = {
					x: i,
					y: j,
					id: 0,
					color: "#3a4f56",
					type: "land"
				};
			}
		}
	};
	this.clearMap();
};<|endoftext|>


<commit_before>const
    PodcastRSS = require('podcast'),
    uuid = require('uuid'),
    _ = require('lodash'),
    { convertSecToHHMMSS } = require('../../util.js');

let generatePlaylistRSSFeed = (playlist) => {

  // Some podcast players do not use the image set in the item.itunesImage,
  // so instead we are using a Podverse default logo.
  // let podcastImageURL = `${
  //   playlist.mediaRefs.length > 0 ?
  //   playlist.mediaRefs[0].podcastImageURL :
  //   'https://podverse.fm/static/images/podverse-logo-180.png'
  // }`;

  let title, description;
  if (playlist.isRecommendation) {
    playlist.ownerName = playlist.ownerName ? playlist.ownerName : 'anonymous';
    title = `Playlist: From ${playlist.ownerName}`;
    description = `Playlist of recommended episodes and clips for ${playlist.title} from ${playlist.ownerName}. <br><br>`+
                  `Created with podverse.fm`;
  } else {
    playlist.ownerName = playlist.ownerName ? playlist.ownerName : 'anonymous';
    title = `${playlist.title}`;
    description = `Playlist of recommended episodes and clips by ${playlist.ownerName}. <br><br>`+
                  `Created with podverse.fm`;
  }

  const feedOptions = {
    title: title,
    description: description,
    generator: 'podverse.fm',
    feed_url: `https://podverse.fm/playlists/${playlist.id}?rssFeed`,
    site_url: `https://podverse.fm/playlists/${playlist.id}`,
    image_url: 'https://podverse.fm/static/images/podverse-logo-180.png',
    docs: 'https://podverse.fm/about',
    author: playlist.ownerName,
    managingEditor: playlist.ownerName,
    webMaster: playlist.ownerName,
    copyright: 'AGPLv3',
    language: 'English',
    categories: ['playlists'],
    pubDate: playlist.lastUpdated,
    // TODO: do we want to set ttl?
    // ttl: '', // number of minutes feed can be cached before refreshing from source

    // we need to set itunesSummary to an empty string, or podcastRSS
    // will automatically fill it out
    itunesSummary: '', //,
    itunesImage: 'https://podverse.fm/static/images/podverse-logo-180.png'
    // other options
    // itunesAuthor: '', // playlist.ownerName,
    // itunesSubtitle: '', // 'Created with podverse.fm',
    // itunesOwner: '', // playlist.ownerName,
    // itunesExplicit: '',
    // itunesCategories: ''
  }

  const feed = new PodcastRSS(feedOptions);

  let groupedMediaRefs = _.groupBy(playlist.mediaRefs, 'episodeMediaURL');
  let formattedMediaRefs = [];

  Object.keys(groupedMediaRefs).forEach(key => {
    let mediaRefs = groupedMediaRefs[key];

    let fMediaRef = formattedMediaRef = {};
    fMediaRef.episodeTitle = mediaRefs[0].title;
    fMediaRef.episodeMediaURL = mediaRefs[0].episodeMediaURL;
    fMediaRef.podcastTitle = mediaRefs[0].podcastTitle;
    fMediaRef.episodePubDate = mediaRefs[0].episodePubDate;
    fMediaRef.episodeMediaURL = mediaRefs[0].episodeMediaURL;
    fMediaRef.episodeDuration = mediaRefs[0].episodeDuration;
    fMediaRef.episodeImageURL = mediaRefs[0].episodeImageURL;
    fMediaRef.podcastImageURL = mediaRefs[0].podcastImageURL;

    fMediaRef.description = '';

    mediaRefs = _.sortBy(mediaRefs, 'startTime');

    let desc = `<b>${mediaRefs.length > 1 ? 'Clips' : 'Clip'} shared with you:</b> <br><br>`;
    for (let mediaRef of mediaRefs) {
      let startTime = convertSecToHHMMSS(mediaRef.startTime);
      let endTime = convertSecToHHMMSS(mediaRef.endTime);
      let timeString = '';
      if (mediaRef.startTime < mediaRef.endTime) {
        timeString = `${startTime} – ${endTime}`;
      } else {
        timeString = `${startTime} start time`;
      }
      let title = mediaRef.title ? mediaRef.title : 'untitled clip';
      desc += `${timeString}: ${title}<br>`;
    }

    desc += '
';
    desc += mediaRefs[0].episodeSummary;

    fMediaRef.description = desc;

    formattedMediaRefs.push(formattedMediaRef)
  });

  for (let mediaRef of playlist.mediaRefs) {
    let itemOptions = {
      title: mediaRef.episodeTitle,
      description: mediaRef.description,
      url: `https://podverse.fm/episodes/alias?mediaURL=${mediaRef.episodeMediaURL}`,
      guid: uuid(),
      // categories: ,
      author: mediaRef.podcastTitle, // TODO: should be real author listed in feed
      date: mediaRef.episodePubDate,
      enclosure: {
        url: mediaRef.episodeMediaURL,
        // file: ,
        // size: ,
        // mime
      },
      // we need to set itunesSummary to an empty string, or podcastRSS
      // will automatically fill it out
      itunesSummary: ' ',
      itunesDuration: mediaRef.episodeDuration,
      itunesImage: mediaRef.episodeImageURL || mediaRef.podcastImageURL
      // other options
      // itunesAuthor: '',
      // itunesSubtitle: '',
      // itunesOwner: '',
      // itunesExplicit: '',
      // itunesKeywords: ''
    };
    feed.item(itemOptions)
  }

  let xml = feed.xml(' '); // ' ' sets format to 2-space tabs

  return xml;
}

module.exports = {generatePlaylistRSSFeed};
<commit_msg>Use formattedMediaRefs array<commit_after>const
    PodcastRSS = require('podcast'),
    uuid = require('uuid'),
    _ = require('lodash'),
    { convertSecToHHMMSS } = require('../../util.js');

let generatePlaylistRSSFeed = (playlist) => {

  // Some podcast players do not use the image set in the item.itunesImage,
  // so instead we are using a Podverse default logo.
  // let podcastImageURL = `${
  //   playlist.mediaRefs.length > 0 ?
  //   playlist.mediaRefs[0].podcastImageURL :
  //   'https://podverse.fm/static/images/podverse-logo-180.png'
  // }`;

  let title, description;
  if (playlist.isRecommendation) {
    playlist.ownerName = playlist.ownerName ? playlist.ownerName : 'anonymous';
    title = `Playlist: From ${playlist.ownerName}`;
    description = `Playlist of recommended episodes and clips for ${playlist.title} from ${playlist.ownerName}. <br><br>`+
                  `Created with podverse.fm`;
  } else {
    playlist.ownerName = playlist.ownerName ? playlist.ownerName : 'anonymous';
    title = `${playlist.title}`;
    description = `Playlist of recommended episodes and clips by ${playlist.ownerName}. <br><br>`+
                  `Created with podverse.fm`;
  }

  const feedOptions = {
    title: title,
    description: description,
    generator: 'podverse.fm',
    feed_url: `https://podverse.fm/playlists/${playlist.id}?rssFeed`,
    site_url: `https://podverse.fm/playlists/${playlist.id}`,
    image_url: 'https://podverse.fm/static/images/podverse-logo-180.png',
    docs: 'https://podverse.fm/about',
    author: playlist.ownerName,
    managingEditor: playlist.ownerName,
    webMaster: playlist.ownerName,
    copyright: 'AGPLv3',
    language: 'English',
    categories: ['playlists'],
    pubDate: playlist.lastUpdated,
    // TODO: do we want to set ttl?
    // ttl: '', // number of minutes feed can be cached before refreshing from source

    // we need to set itunesSummary to an empty string, or podcastRSS
    // will automatically fill it out
    itunesSummary: '', //,
    itunesImage: 'https://podverse.fm/static/images/podverse-logo-180.png'
    // other options
    // itunesAuthor: '', // playlist.ownerName,
    // itunesSubtitle: '', // 'Created with podverse.fm',
    // itunesOwner: '', // playlist.ownerName,
    // itunesExplicit: '',
    // itunesCategories: ''
  }

  const feed = new PodcastRSS(feedOptions);

  let groupedMediaRefs = _.groupBy(playlist.mediaRefs, 'episodeMediaURL');
  let formattedMediaRefs = [];

  Object.keys(groupedMediaRefs).forEach(key => {
    let mediaRefs = groupedMediaRefs[key];

    let fMediaRef = formattedMediaRef = {};
    fMediaRef.episodeTitle = mediaRefs[0].title;
    fMediaRef.episodeMediaURL = mediaRefs[0].episodeMediaURL;
    fMediaRef.podcastTitle = mediaRefs[0].podcastTitle;
    fMediaRef.episodePubDate = mediaRefs[0].episodePubDate;
    fMediaRef.episodeMediaURL = mediaRefs[0].episodeMediaURL;
    fMediaRef.episodeDuration = mediaRefs[0].episodeDuration;
    fMediaRef.episodeImageURL = mediaRefs[0].episodeImageURL;
    fMediaRef.podcastImageURL = mediaRefs[0].podcastImageURL;

    fMediaRef.description = '';

    mediaRefs = _.sortBy(mediaRefs, 'startTime');

    let desc = `<b>${mediaRefs.length > 1 ? 'Clips' : 'Clip'} shared with you:</b> <br><br>`;
    for (let mediaRef of mediaRefs) {
      let startTime = convertSecToHHMMSS(mediaRef.startTime);
      let endTime = convertSecToHHMMSS(mediaRef.endTime);
      let timeString = '';
      if (mediaRef.startTime < mediaRef.endTime) {
        timeString = `${startTime} – ${endTime}`;
      } else {
        timeString = `${startTime} start time`;
      }
      let title = mediaRef.title ? mediaRef.title : 'untitled clip';
      desc += `${timeString}: ${title}<br>`;
    }

    desc += '
';
    desc += mediaRefs[0].episodeSummary;

    fMediaRef.description = desc;

    formattedMediaRefs.push(formattedMediaRef)
  });

  for (let mediaRef of formattedMediaRefs) {
    let itemOptions = {
      title: mediaRef.episodeTitle,
      description: mediaRef.description,
      url: `https://podverse.fm/episodes/alias?mediaURL=${mediaRef.episodeMediaURL}`,
      guid: uuid(),
      // categories: ,
      author: mediaRef.podcastTitle, // TODO: should be real author listed in feed
      date: mediaRef.episodePubDate,
      enclosure: {
        url: mediaRef.episodeMediaURL,
        // file: ,
        // size: ,
        // mime
      },
      // we need to set itunesSummary to an empty string, or podcastRSS
      // will automatically fill it out
      itunesSummary: ' ',
      itunesDuration: mediaRef.episodeDuration,
      itunesImage: mediaRef.episodeImageURL || mediaRef.podcastImageURL
      // other options
      // itunesAuthor: '',
      // itunesSubtitle: '',
      // itunesOwner: '',
      // itunesExplicit: '',
      // itunesKeywords: ''
    };
    feed.item(itemOptions)
  }

  let xml = feed.xml(' '); // ' ' sets format to 2-space tabs

  return xml;
}

module.exports = {generatePlaylistRSSFeed};
<|endoftext|>


<commit_before>export { Base }; // Stage.BlockParamsCreator.Base

import * as ValueDesc from "../../../Unpacker/ValueDesc.js";
import * as Block from "../../Block.js";
import { Params } from "../Stage_Params.js";

/**
 * Base class for all Stage.BlockParamsCreator.Xxx classes.
 *
 *
 * @member {number} outChannels0
 *   The output0's channel count in current configuration.
 *
 * @member {number} outChannels1
 *   The output1's channel count in current configuration.
 *
 */
class Base {

  /**
   * @param {Params} stageParams
   *   The Stage.Params object which provides basic parameters.
   */
  constructor( stageParams ) {
    this.stageParams = stageParams;

    this.inputHeight0 = this.inputWidth0 =
    this.channelCount0_pointwise1Before = this.channelCount1_pointwise1Before =
    this.pointwise1ChannelCount = this.bPointwise1Bias = this.pointwise1ActivationId =
    this.depthwise_AvgMax_Or_ChannelMultiplier = this.depthwiseFilterHeight = this.depthwiseFilterWidth =
    this.depthwiseStridesPad = this.bDepthwiseBias = this.depthwiseActivationId =
    this.pointwise20ChannelCount = this.bPointwise20Bias = this.pointwise20ActivationId =
    this.bOutput1Requested = this.bKeepInputTensor = undefined;

    this.blockCount = // How many block should be in the stage.
    this.depthwiseFilterHeight_Default = this.depthwiseFilterWidth_Default = // The default depthwise filter size.
    this.depthwiseFilterHeight_Last = this.depthwiseFilterWidth_Last =       // The last block's depthwise filter size.
    this.outChannels0 = this.outChannels1 = -1;

    this.channelShuffler = undefined;
  }

  /** Called to determine blockCount, depthwiseFilterHeight_Default, depthwiseFilterWidth_Default, depthwiseFilterHeight_Last,
    * depthwiseFilterWidth_Last.
    *
    * Sub-class could override this method to adjust data members.
    */
  determine_blockCount_depthwiseFilterHeightWidth_Default_Last() {
    let stageParams = this.stageParams;
    this.blockCount = stageParams.blockCountRequested; // By default, the block count is just the original block count.

    // By default, all blocks uses the original depthwise filter size.
    this.depthwiseFilterHeight_Default = this.depthwiseFilterHeight_Last = stageParams.depthwiseFilterHeight;
    this.depthwiseFilterWidth_Default = this.depthwiseFilterWidth_Last = stageParams.depthwiseFilterWidth;
  }

  /**
   * Called before block0 is about to be created. Sub-class should override this method to adjust data members.
   *
   * Block 0.
   *
   * The special points of a stage's block 0 are:
   *   - halve the height x width. (Both ShuffleNetV2 and MobileNetV2) (by depthwise convolution with strides = 2)
   *   - Double channels. (Please see explanation of class Stage.Base)
   */
  configTo_beforeBlock0() {
    let stageParams = this.stageParams;

    this.inputHeight0 = stageParams.sourceHeight; // block0 inputs the source image size.
    this.inputWidth0 = stageParams.sourceWidth;

    this.bias_activation_setup_forBlock0(); // bias, activation of pointwise1, depthwise1, pointwise2

    this.depthwiseFilterHeight = this.depthwiseFilterHeight_Default;
    this.depthwiseFilterWidth = this.depthwiseFilterWidth_Default;

    // block0 uses depthwise ( strides = 2, pad = "same" ) to halve ( height, width ).
    this.depthwiseStridesPad = ValueDesc.StridesPad.Singleton.Ids.STRIDES_2_PAD_SAME;

    this.bKeepInputTensor = stageParams.bKeepInputTensor; // block0 may or may not keep input tensor according to caller's necessary.
  }

  /**
   * Called after block0 is created (i.e. before block1, 2, 3, ...). Sub-class should override this method to adjust data members.
   */
  configTo_afterBlock0() {
    this.inputHeight0 = this.stageParams.outputHeight; // all blocks (except block0) inputs half the source image size.
    this.inputWidth0 = this.stageParams.outputWidth;

    // All blocks (except block0 in NoPointwise1) will not double the channel count by depthwise, because block0 has already double
    // output channel count.
    //
    this.depthwise_AvgMax_Or_ChannelMultiplier = 1;

    // All blocks (except block0) uses depthwise ( strides = 1, pad = "same" ) to keep ( height, width ).
    this.depthwiseStridesPad = ValueDesc.StridesPad.Singleton.Ids.STRIDES_1_PAD_SAME;

    this.bKeepInputTensor = false; // No matter bKeepInputTensor, all blocks (except block0) should not keep input tensor.
  }

  /**
   * Called before blockLast is about to be created. Sub-class could override this method to adjust data members.
   */
  configTo_beforeBlockLast() {

    // Besides, the blockLast may use a different depthwise filter size. This is especially true for NotShuffleNet_NotMobileNet.
    this.depthwiseFilterHeight = this.depthwiseFilterHeight_Last;
    this.depthwiseFilterWidth = this.depthwiseFilterWidth_Last;

    this.bias_activation_setup_forBlockLast(); // bias, activation of pointwise1, depthwise1, pointwise2
  }

  /**
   * Config the bias and activation of pointwise1, depthwise1, pointwise2 for block0.
   */
  bias_activation_setup_forBlock0() {
    let stageParams = this.stageParams;

    // pointwise1
    {
      this.bPointwise1Bias = true;
      this.pointwise1ActivationId = stageParams.nActivationId;
    }

    // depthwise
    {
      // MobileNetV2_Xxx's depthwise have bias and activation (to remedy its pointwise2's no activation).
      //
      if ( ValueDesc.ConvStageType.isMobileNetV2( stageParams.nConvStageType ) ) {
        this.bDepthwiseBias = true;
        this.depthwiseActivationId = stageParams.nActivationId;

      // non-MobileNetV2_Xxx's depthwise have no bias and no activation. (since they will be done at (squeeze-and-excitation
      // and) pointwise2.)
      //
      } else {
        this.bDepthwiseBias = false;
        this.depthwiseActivationId = ValueDesc.ActivationFunction.Singleton.Ids.NONE;

//!!! ...unfinished... (2022/05/31)
// In this case, if depthwise input ( height, width ) is ( 1, 1 ), the depthwise may be discarded (since no bias and no activation)
// to improve performance.

      }
    }

    // pointwise2
    {
      this.bPointwise20Bias = true; // All blocks' outputs needs bias (even if MobileNetV2_Xxx).

      // MobileNetV2_Xxx's pointwise2 always does not have activation function.
      //
      // The reason is that MobileNetV2_Xxx's pointwise2 has add-input-to-output so its block's output is not affine transformation
      // (even if no activation function). It and the next block's pointwise1 is not continuous multiple affine transformation
      // and will not become just one affine transformation.
      //
      if ( ValueDesc.ConvStageType.isMobileNetV2( stageParams.nConvStageType ) ) {
        this.pointwise20ActivationId = ValueDesc.ActivationFunction.Singleton.Ids.NONE;

      // For all other ConvStageType, all non-blockLast's pointwise2 must have activation function (to become non-affine transformation).
      // The reason is to avoid the previous block's pointwise2 and the next block's pointwis1 become just one affine transformation.
      } else {
        this.pointwise20ActivationId = stageParams.nActivationId;
      }
    }
  }

  /**
   * Config the bias and activation of pointwise1, depthwise1, pointwise2 for blockLast.
   */
  bias_activation_setup_forBlockLast() {
    let stageParams = this.stageParams;

    // pointwise2
    {
      // MobileNetV2_Xxx's pointwise2 always does not have activation function.
      //
      // The reason is that MobileNetV2_Xxx's pointwise2 has add-input-to-output so its block's output is not affine transformation
      // (even if no activation function). It and the next block's pointwise1 is not continuous multiple affine transformation
      // and will not become just one affine transformation.
      //
      if ( ValueDesc.ConvStageType.isMobileNetV2( stageParams.nConvStageType ) ) {
        this.pointwise20ActivationId = ValueDesc.ActivationFunction.Singleton.Ids.NONE;

      // For all other ConvStageType, whether blockLast's pointwise2 has activation function is according to the specified flag.
      } else {
        if ( stageParams.bPointwise2ActivatedAtStageEnd == false ) {
          this.pointwise20ActivationId = ValueDesc.ActivationFunction.Singleton.Ids.NONE;
        } else {
          this.pointwise20ActivationId = stageParams.nActivationId;
        }
      }
    }
  }

  /**
   *
   * @param {Float32Array} inputFloat32Array
   *   A Float32Array whose values will be interpreted as weights.
   *
   * @param {number} byteOffsetBegin
   *   The position to start to decode from the inputFloat32Array. This is relative to the inputFloat32Array.buffer
   * (not to the inputFloat32Array.byteOffset).
   *
   * @return {Block.Params}
   *   Create and return a Block.Params according to this object's current state.
   */
  create_BlockParams( inputFloat32Array, byteOffsetBegin ) {
    let params = new Block.Params(
      inputFloat32Array, byteOffsetBegin,
      this.inputHeight0, this.inputWidth0,
      this.channelCount0_pointwise1Before,
      this.channelCount1_pointwise1Before,
      this.pointwise1ChannelCount, this.bPointwise1Bias, this.pointwise1ActivationId,
      this.depthwise_AvgMax_Or_ChannelMultiplier, this.depthwiseFilterHeight, this.depthwiseFilterWidth,
      this.depthwiseStridesPad, this.bDepthwiseBias, this.depthwiseActivationId,
      this.pointwise20ChannelCount, this.bPointwise20Bias, this.pointwise20ActivationId,
      this.bOutput1Requested,
      this.bKeepInputTensor
    );
    return params;
  }

}
<commit_msg>Update Base.js<commit_after>export { Base }; // Stage.BlockParamsCreator.Base

import * as ValueDesc from "../../../Unpacker/ValueDesc.js";
import * as Block from "../../Block.js";
import { Params } from "../Stage_Params.js";

/**
 * Base class for all Stage.BlockParamsCreator.Xxx classes.
 *
 *
 * @member {number} outChannels0
 *   The output0's channel count in current configuration.
 *
 * @member {number} outChannels1
 *   The output1's channel count in current configuration.
 *
 */
class Base {

  /**
   * @param {Params} stageParams
   *   The Stage.Params object which provides basic parameters.
   */
  constructor( stageParams ) {
    this.stageParams = stageParams;

    this.inputHeight0 = this.inputWidth0 =
    this.channelCount0_pointwise1Before = this.channelCount1_pointwise1Before =
    this.pointwise1ChannelCount = this.bPointwise1Bias = this.pointwise1ActivationId =
    this.depthwise_AvgMax_Or_ChannelMultiplier = this.depthwiseFilterHeight = this.depthwiseFilterWidth =
    this.depthwiseStridesPad = this.bDepthwiseBias = this.depthwiseActivationId =
    this.pointwise20ChannelCount = this.bPointwise20Bias = this.pointwise20ActivationId =
    this.bOutput1Requested = this.bKeepInputTensor = undefined;

    this.blockCount = // How many block should be in the stage.
    this.depthwiseFilterHeight_Default = this.depthwiseFilterWidth_Default = // The default depthwise filter size.
    this.depthwiseFilterHeight_Last = this.depthwiseFilterWidth_Last =       // The last block's depthwise filter size.
    this.outChannels0 = this.outChannels1 = -1;

    this.channelShuffler = undefined;
  }

  /** Called to determine blockCount, depthwiseFilterHeight_Default, depthwiseFilterWidth_Default, depthwiseFilterHeight_Last,
    * depthwiseFilterWidth_Last.
    *
    * Sub-class could override this method to adjust data members.
    */
  determine_blockCount_depthwiseFilterHeightWidth_Default_Last() {
    let stageParams = this.stageParams;
    this.blockCount = stageParams.blockCountRequested; // By default, the block count is just the original block count.

    // By default, all blocks uses the original depthwise filter size.
    this.depthwiseFilterHeight_Default = this.depthwiseFilterHeight_Last = stageParams.depthwiseFilterHeight;
    this.depthwiseFilterWidth_Default = this.depthwiseFilterWidth_Last = stageParams.depthwiseFilterWidth;
  }

  /**
   * Called before block0 is about to be created. Sub-class should override this method to adjust data members.
   *
   * Block 0.
   *
   * The special points of a stage's block 0 are:
   *   - halve the height x width. (Both ShuffleNetV2 and MobileNetV2) (by depthwise convolution with strides = 2)
   *   - Double channels. (Please see explanation of class Stage.Base)
   */
  configTo_beforeBlock0() {
    let stageParams = this.stageParams;

    this.inputHeight0 = stageParams.sourceHeight; // block0 inputs the source image size.
    this.inputWidth0 = stageParams.sourceWidth;

    this.bias_activation_setup_forBlock0(); // bias, activation of pointwise1, depthwise1, pointwise2

    this.depthwiseFilterHeight = this.depthwiseFilterHeight_Default;
    this.depthwiseFilterWidth = this.depthwiseFilterWidth_Default;

    // block0 uses depthwise ( strides = 2, pad = "same" ) to halve ( height, width ).
    this.depthwiseStridesPad = ValueDesc.StridesPad.Singleton.Ids.STRIDES_2_PAD_SAME;

    this.bKeepInputTensor = stageParams.bKeepInputTensor; // block0 may or may not keep input tensor according to caller's necessary.

//!!! ...unfinished... (2022/06/08)
// If (
//        ( ( inputHeight == 1 ) && ( inputWidth == 1 ) )
//     && ( this.depthwise_AvgMax_Or_ChannelMultiplier <= 1 ) // i.e. avg or max or none or ( channelMultiplier == 1 ).
//     && ( depthwiseActivationId == ValueDesc.ActivationFunction.Singleton.Ids.NONE ) // i.e. depthwise is linear.
//     && (   ( nSqueezeExcitationChannelCountDivisor == ValueDesc.SqueezeExcitationChannelCountDivisor.Singleton.Ids.NONE ) // (-2), no squeeze-and-excitation (i.e. depthwise is linear)
//         || ( bSqueezeExcitationPrefix == false ) ) // or, has squeeze-and-excitation, but after pointwise2. (i.e. depthwise is still linear)
//        )
//    )
//
// Then, the depthwise should be discarded to improve performance.
// Perhaps, this automatical optimization could be done in Block.Base (i.e. not in Stage).
//

  }

  /**
   * Called after block0 is created (i.e. before block1, 2, 3, ...). Sub-class should override this method to adjust data members.
   */
  configTo_afterBlock0() {
    this.inputHeight0 = this.stageParams.outputHeight; // all blocks (except block0) inputs half the source image size.
    this.inputWidth0 = this.stageParams.outputWidth;

    // All blocks (except block0 in NoPointwise1) will not double the channel count by depthwise, because block0 has already double
    // output channel count.
    //
    this.depthwise_AvgMax_Or_ChannelMultiplier = 1;

    // All blocks (except block0) uses depthwise ( strides = 1, pad = "same" ) to keep ( height, width ).
    this.depthwiseStridesPad = ValueDesc.StridesPad.Singleton.Ids.STRIDES_1_PAD_SAME;

    this.bKeepInputTensor = false; // No matter bKeepInputTensor, all blocks (except block0) should not keep input tensor.
  }

  /**
   * Called before blockLast is about to be created. Sub-class could override this method to adjust data members.
   */
  configTo_beforeBlockLast() {

    // Besides, the blockLast may use a different depthwise filter size. This is especially true for NotShuffleNet_NotMobileNet.
    this.depthwiseFilterHeight = this.depthwiseFilterHeight_Last;
    this.depthwiseFilterWidth = this.depthwiseFilterWidth_Last;

    this.bias_activation_setup_forBlockLast(); // bias, activation of pointwise1, depthwise1, pointwise2
  }

  /**
   * Config the bias and activation of pointwise1, depthwise1, pointwise2 for block0.
   */
  bias_activation_setup_forBlock0() {
    let stageParams = this.stageParams;

    // pointwise1
    {
      this.bPointwise1Bias = true;
      this.pointwise1ActivationId = stageParams.nActivationId;
    }

    // depthwise
    {
      // MobileNetV2_Xxx's depthwise have bias and activation (to remedy its pointwise2's no activation).
      //
      if ( ValueDesc.ConvStageType.isMobileNetV2( stageParams.nConvStageType ) ) {
        this.bDepthwiseBias = true;
        this.depthwiseActivationId = stageParams.nActivationId;

      // non-MobileNetV2_Xxx's depthwise have no bias and no activation. (since they will be done at (squeeze-and-excitation
      // and) pointwise2.)
      //
      } else {
        this.bDepthwiseBias = false;
        this.depthwiseActivationId = ValueDesc.ActivationFunction.Singleton.Ids.NONE;

//!!! ...unfinished... (2022/05/31)
// In this case, if depthwise input ( height, width ) is ( 1, 1 ), the depthwise may be discarded (since no bias and no activation)
// to improve performance.

      }
    }

    // pointwise2
    {
      this.bPointwise20Bias = true; // All blocks' outputs needs bias (even if MobileNetV2_Xxx).

      // MobileNetV2_Xxx's pointwise2 always does not have activation function.
      //
      // The reason is that MobileNetV2_Xxx's pointwise2 has add-input-to-output so its block's output is not affine transformation
      // (even if no activation function). It and the next block's pointwise1 is not continuous multiple affine transformation
      // and will not become just one affine transformation.
      //
      if ( ValueDesc.ConvStageType.isMobileNetV2( stageParams.nConvStageType ) ) {
        this.pointwise20ActivationId = ValueDesc.ActivationFunction.Singleton.Ids.NONE;

      // For all other ConvStageType, all non-blockLast's pointwise2 must have activation function (to become non-affine transformation).
      // The reason is to avoid the previous block's pointwise2 and the next block's pointwis1 become just one affine transformation.
      } else {
        this.pointwise20ActivationId = stageParams.nActivationId;
      }
    }
  }

  /**
   * Config the bias and activation of pointwise1, depthwise1, pointwise2 for blockLast.
   */
  bias_activation_setup_forBlockLast() {
    let stageParams = this.stageParams;

    // pointwise2
    {
      // MobileNetV2_Xxx's pointwise2 always does not have activation function.
      //
      // The reason is that MobileNetV2_Xxx's pointwise2 has add-input-to-output so its block's output is not affine transformation
      // (even if no activation function). It and the next block's pointwise1 is not continuous multiple affine transformation
      // and will not become just one affine transformation.
      //
      if ( ValueDesc.ConvStageType.isMobileNetV2( stageParams.nConvStageType ) ) {
        this.pointwise20ActivationId = ValueDesc.ActivationFunction.Singleton.Ids.NONE;

      // For all other ConvStageType, whether blockLast's pointwise2 has activation function is according to the specified flag.
      } else {
        if ( stageParams.bPointwise2ActivatedAtStageEnd == false ) {
          this.pointwise20ActivationId = ValueDesc.ActivationFunction.Singleton.Ids.NONE;
        } else {
          this.pointwise20ActivationId = stageParams.nActivationId;
        }
      }
    }
  }

  /**
   *
   * @param {Float32Array} inputFloat32Array
   *   A Float32Array whose values will be interpreted as weights.
   *
   * @param {number} byteOffsetBegin
   *   The position to start to decode from the inputFloat32Array. This is relative to the inputFloat32Array.buffer
   * (not to the inputFloat32Array.byteOffset).
   *
   * @return {Block.Params}
   *   Create and return a Block.Params according to this object's current state.
   */
  create_BlockParams( inputFloat32Array, byteOffsetBegin ) {
    let params = new Block.Params(
      inputFloat32Array, byteOffsetBegin,
      this.inputHeight0, this.inputWidth0,
      this.channelCount0_pointwise1Before,
      this.channelCount1_pointwise1Before,
      this.pointwise1ChannelCount, this.bPointwise1Bias, this.pointwise1ActivationId,
      this.depthwise_AvgMax_Or_ChannelMultiplier, this.depthwiseFilterHeight, this.depthwiseFilterWidth,
      this.depthwiseStridesPad, this.bDepthwiseBias, this.depthwiseActivationId,
      this.pointwise20ChannelCount, this.bPointwise20Bias, this.pointwise20ActivationId,
      this.bOutput1Requested,
      this.bKeepInputTensor
    );
    return params;
  }

}
<|endoftext|>


<commit_before>const { BadRequest } = require('@feathersjs/errors');
const { isValidObjectId } = require('mongoose');

const validateParams = async (context) => {
	const { _ids } = context.params.query;

	if (!context.id && !_ids) {
		throw new BadRequest('The request requires either an id or ids to be present.');
	}

	if (context.id && !(isValidObjectId(context.id) || typeof context.id === 'string')) {
		throw new BadRequest('The type for id is incorrect.');
	}

	if (_ids && !(Array.isArray(_ids) || typeof _ids === 'object')) {
		throw new BadRequest('The type for ids is incorrect.');
	}

	if (
		(Array.isArray(_ids) && _ids.some((id) => !isValidObjectId(id))) ||
		(typeof _ids === 'object' && Object.values(_ids).some((id) => !isValidObjectId(id)))
	) {
		throw new BadRequest('The type for either one or several ids is incorrect.');
	}
	return context;
};

module.exports = {
	validateParams,
};
<commit_msg>disable eslint rule<commit_after>/* eslint-disable no-underscore-dangle */
const { BadRequest } = require('@feathersjs/errors');
const { isValidObjectId } = require('mongoose');

const validateParams = async (context) => {
	const { _ids } = context.params.query;

	if (!context.id && !_ids) {
		throw new BadRequest('The request requires either an id or ids to be present.');
	}

	if (context.id && !(isValidObjectId(context.id) || typeof context.id === 'string')) {
		throw new BadRequest('The type for id is incorrect.');
	}

	if (_ids && !(Array.isArray(_ids) || typeof _ids === 'object')) {
		throw new BadRequest('The type for ids is incorrect.');
	}

	if (
		(Array.isArray(_ids) && _ids.some((id) => !isValidObjectId(id))) ||
		(typeof _ids === 'object' && Object.values(_ids).some((id) => !isValidObjectId(id)))
	) {
		throw new BadRequest('The type for either one or several ids is incorrect.');
	}
	return context;
};

module.exports = {
	validateParams,
};
<|endoftext|>


<commit_before>'use strict';

// Load requirements
const path = require('path'),
      fs = require('fs');

// Helper method to check for a file
function isFile(file) {
  return fs.lstatSync(file).isFile();
}

module.exports = function(directory, seasons) {
  return new Promise((resolve, reject) => {

    // Variables
    let tasks = [],
        files = [];

    // Normalize the search directory
    directory = path.normalize(directory);

    // Single file
    if ( isFile(directory) ) {

      // Still ensure it matches a format we want
      if ( this.format.match(directory) ) {
        tasks.push({season: false, files: [directory]});
      }

      return resolve(tasks);
    }

    // Directory listing
    fs.readdir(directory, (err, result) => {

      // Was there a problem
      if ( err !== null ) {
        return reject(err);
      }

      // Loop the available files
      result.forEach((file) => {

        // Update file to include directory
        file = path.join(directory, file);

        // Check it's actually a file and in the format we want
        if ( isFile(file) && this.format.match(file) ) {
          files.push(file);
        }
      });

      // Push files into array and resolve
      tasks.push({season: false , files: files});
      return resolve(tasks);
    });
  });
};
<commit_msg>Add nested season handling and promise changing to queue<commit_after>'use strict';

// Load requirements
const path = require('path'),
      fs = require('fs');

// Helper method to check for a file
function isFile(file) {
  return fs.lstatSync(file).isFile();
}

module.exports = function(directory, seasons) {
  return new Promise((resolve, reject) => {

    // Variables
    let tasks = [],
        files = [],
        promises = [];

    // Normalize the search directory
    directory = path.normalize(directory);

    // Single file
    if ( isFile(directory) ) {

      // Still ensure it matches a format we want
      if ( this.format.match(directory) ) {
        tasks.push({season: false, files: [directory]});
      }

      return resolve(tasks);
    }

    // Handle seasons
    if ( seasons !== undefined && Array.isArray(seasons) ) {

      // Loop through the supplied seasons
      seasons.forEach((season) => {

        // Clean up season
        season = season.toString().trim();

        // Format the season directory path
        let seasonSub = ( parseInt(season) > 0 ? 'Season ' + season : season ),
            seasonDir = path.normalize(path.join(directory + '/' + seasonSub));

        // Push into promise queue
        promises.push(this.listing(seasonDir, season));
      });

      // Handle the promise resolution
      return Promise.all(promises).then((data) => {
        return resolve(data.map((season) => { return season[0]; }));
      }).catch((err) => {
        return reject(err.message || err);
      });
    }

    // Directory listing
    fs.readdir(directory, (err, result) => {

      // Was there a problem
      if ( err !== null ) {
        return reject(err.message);
      }

      // Loop the available files
      result.forEach((file) => {

        // Update file to include directory
        file = path.join(directory, file);

        // Check it's actually a file and in the format we want
        if ( isFile(file) && this.format.match(file) ) {
          files.push(file);
        }
      });

      // Push files into array and resolve
      tasks.push({season: seasons || false, files: files});
      return resolve(tasks);
    });
  });
};
<|endoftext|>


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

/*jslint node: true*/
/*global angular*/
/*jslint browser: true*/
/*jslint nomen: true */
/*global $, _*/

(function () {
    'use strict';

    /**
    * @name DashboardCtrl
    * @desc Main dashboard Controller
    */
    function DashboardCtrl($document, $rootScope, $log, $route, $routeParams, widgetDefinitions, widgets, DashboardService) {
        var vm = this;
        var path = $route.current.$$route.originalPath;

        /**
        * @name visibilityChanged
        * @desc Pauses/resumes interval updates if window/tab is out of focus.
        */
        function visibilityChanged() {
            if ($document[0].hidden || $document[0].webkitHidden ||
                $document[0].mozHidden || $document[0].msHidden) {
                DashboardService.cancelInterval();
            } else {
                DashboardService.updateInterval();
            }
        }

        /**
        * @name activate
        * @desc Initiliazes DashboardController
        */
        function activate() {
            DashboardService.initializeProperties();

            if ($routeParams.host) {
                $rootScope.properties.host = $routeParams.host;
                $log.info('Host: ' + $routeParams.host);
                if ($routeParams.hostspec) {
                    $rootScope.properties.hostspec = $routeParams.hostspec;
                    $log.info('Hostspec: ' + $routeParams.hostspec);
                }
                DashboardService.updateHost();
            }

            // hack to deal with window/tab out of focus
            $document[0]
                .addEventListener('visibilitychange', visibilityChanged, false);
            $document[0]
                .addEventListener('webkitvisibilitychange', visibilityChanged, false);
            $document[0]
                .addEventListener('msvisibilitychange', visibilityChanged, false);
            $document[0]
                .addEventListener('mozvisibilitychange', visibilityChanged, false);

            $log.info('Dashboard controller initialized with ' + path + ' view.');
        }

         vm.dashboardOptions = {
            hideToolbar: true,
            widgetButtons: false,
            hideWidgetName: true,
            hideWidgetSettings: true,
            widgetDefinitions: widgetDefinitions,
            defaultWidgets: widgets
        };

        // Export controller public functions
        vm.updateInterval = DashboardService.updateInterval;
        vm.updateHost = DashboardService.updateHost;
        vm.updateWindow = DashboardService.updateWindow;
        vm.isHostnameExpanded = false;
        activate();
    }

    DashboardCtrl.$inject = [
        '$document',
        '$rootScope',
        '$log',
        '$route',
        '$routeParams',
        'widgetDefinitions',
        'widgets',
        'DashboardService'
    ];

    angular
        .module('app.controllers', [])
        .controller('DashboardController', DashboardCtrl);
})();
<commit_msg>Removing unused global eslint.<commit_after>/**!
 *
 *  Copyright 2015 Netflix, Inc.
 *
 *     Licensed under the Apache License, Version 2.0 (the "License");
 *     you may not use this file except in compliance with the License.
 *     You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 *
 */

/*jslint node: true*/
/*global angular*/
/*jslint browser: true*/
/*jslint nomen: true */

(function () {
    'use strict';

    /**
    * @name DashboardCtrl
    * @desc Main dashboard Controller
    */
    function DashboardCtrl($document, $rootScope, $log, $route, $routeParams, widgetDefinitions, widgets, DashboardService) {
        var vm = this;
        var path = $route.current.$$route.originalPath;

        /**
        * @name visibilityChanged
        * @desc Pauses/resumes interval updates if window/tab is out of focus.
        */
        function visibilityChanged() {
            if ($document[0].hidden || $document[0].webkitHidden ||
                $document[0].mozHidden || $document[0].msHidden) {
                DashboardService.cancelInterval();
            } else {
                DashboardService.updateInterval();
            }
        }

        /**
        * @name activate
        * @desc Initiliazes DashboardController
        */
        function activate() {
            DashboardService.initializeProperties();

            if ($routeParams.host) {
                $rootScope.properties.host = $routeParams.host;
                $log.info('Host: ' + $routeParams.host);
                if ($routeParams.hostspec) {
                    $rootScope.properties.hostspec = $routeParams.hostspec;
                    $log.info('Hostspec: ' + $routeParams.hostspec);
                }
                DashboardService.updateHost();
            }

            // hack to deal with window/tab out of focus
            $document[0]
                .addEventListener('visibilitychange', visibilityChanged, false);
            $document[0]
                .addEventListener('webkitvisibilitychange', visibilityChanged, false);
            $document[0]
                .addEventListener('msvisibilitychange', visibilityChanged, false);
            $document[0]
                .addEventListener('mozvisibilitychange', visibilityChanged, false);

            $log.info('Dashboard controller initialized with ' + path + ' view.');
        }

         vm.dashboardOptions = {
            hideToolbar: true,
            widgetButtons: false,
            hideWidgetName: true,
            hideWidgetSettings: true,
            widgetDefinitions: widgetDefinitions,
            defaultWidgets: widgets
        };

        // Export controller public functions
        vm.updateInterval = DashboardService.updateInterval;
        vm.updateHost = DashboardService.updateHost;
        vm.updateWindow = DashboardService.updateWindow;
        vm.isHostnameExpanded = false;
        activate();
    }

    DashboardCtrl.$inject = [
        '$document',
        '$rootScope',
        '$log',
        '$route',
        '$routeParams',
        'widgetDefinitions',
        'widgets',
        'DashboardService'
    ];

    angular
        .module('app.controllers', [])
        .controller('DashboardController', DashboardCtrl);
})();
<|endoftext|>


<commit_before>'use strict';

const {autoUpdater} = require('electron-updater');
const log = require('electron-log');
const {dialog} = require('electron');
const messages = require('./messages');

autoUpdater.logger = log;

let updateVersion;
let initialized = false;

const setUp = async (mainWindow) => {

    if (initialized) return;

    autoUpdater.on('update-available', async updateInfo => {
        updateVersion = updateInfo.version;

        const result = await dialog.showMessageBox({
            type: 'info',
            title: messages.get('autoUpdate.available.title'),
            message: messages.get('autoUpdate.available.message.1')
                + updateInfo.version
                + messages.get('autoUpdate.available.message.2'),
            buttons: [messages.get('autoUpdate.available.yes'), messages.get('autoUpdate.available.no')],
            noLink: true
        });

        if (result.response === 0) {
            mainWindow.webContents.send('downloadProgress', {
                progressPercent: 0,
                version: updateVersion
            });
            await autoUpdater.downloadUpdate();
        }
    });

    autoUpdater.on('download-progress', progress => {
        mainWindow.webContents.send('downloadProgress', {
            progressPercent: progress.percent,
            version: updateVersion
        });
    });

    autoUpdater.on('update-downloaded', async updateInfo => {
        mainWindow.webContents.send('updateDownloaded', updateInfo);

        await dialog.showMessageBox({
            title: messages.get('autoUpdate.downloaded.title'),
            message: messages.get('autoUpdate.downloaded.message.1')
                + updateInfo.version
                + messages.get('autoUpdate.downloaded.message.2'),
            noLink: true
        });
    });

    process.on('uncaughtException', () => {
       mainWindow.webContents.send('downloadInterrupted');
    });

    await autoUpdater.checkForUpdates();
    initialized = true;
};

autoUpdater.autoDownload = false;

module.exports = {
    setUp: setUp
};
<commit_msg>Remove await<commit_after>'use strict';

const {autoUpdater} = require('electron-updater');
const log = require('electron-log');
const {dialog} = require('electron');
const messages = require('./messages');

autoUpdater.logger = log;

let updateVersion;
let initialized = false;

const setUp = async (mainWindow) => {

    if (initialized) return;

    autoUpdater.on('update-available', async updateInfo => {
        updateVersion = updateInfo.version;

        const result = await dialog.showMessageBox({
            type: 'info',
            title: messages.get('autoUpdate.available.title'),
            message: messages.get('autoUpdate.available.message.1')
                + updateInfo.version
                + messages.get('autoUpdate.available.message.2'),
            buttons: [messages.get('autoUpdate.available.yes'), messages.get('autoUpdate.available.no')],
            noLink: true
        });

        if (result.response === 0) {
            mainWindow.webContents.send('downloadProgress', {
                progressPercent: 0,
                version: updateVersion
            });
            autoUpdater.downloadUpdate();
        }
    });

    autoUpdater.on('download-progress', progress => {
        mainWindow.webContents.send('downloadProgress', {
            progressPercent: progress.percent,
            version: updateVersion
        });
    });

    autoUpdater.on('update-downloaded', async updateInfo => {
        mainWindow.webContents.send('updateDownloaded', updateInfo);

        await dialog.showMessageBox({
            title: messages.get('autoUpdate.downloaded.title'),
            message: messages.get('autoUpdate.downloaded.message.1')
                + updateInfo.version
                + messages.get('autoUpdate.downloaded.message.2'),
            noLink: true
        });
    });

    process.on('uncaughtException', () => {
       mainWindow.webContents.send('downloadInterrupted');
    });

    await autoUpdater.checkForUpdates();
    initialized = true;
};

autoUpdater.autoDownload = false;

module.exports = {
    setUp: setUp
};
<|endoftext|>


<commit_before>/*jshint browser:true*/
/*globals define, _, requirejs, WebGMEGlobal*/

define ([
        'js/util',
        'js/Constants'
    ],
    function (util, CONSTANTS) {

    'use strict';

    var parseInitialThingsToDoFromUrl,
        serializeStateToUrl,
        loadStateFromParsedUrl;

    parseInitialThingsToDoFromUrl = function () {
        return {
            layoutToLoad: util.getURLParameterByName('layout') || 'DefaultLayout',
            commitToLoad: util.getURLParameterByName('commit').toLowerCase(),
            projectToLoad:  util.getURLParameterByName('project'),
            objectToLoad: util.getURLParameterByName('node').toLowerCase() || CONSTANTS.PROJECT_ROOT_ID,
            createNewProject: util.getURLParameterByName('create') === 'true',
            branchToLoad: util.getURLParameterByName('branch'),
            visualizerToLoad: util.getURLParameterByName('visualizer') || 'ModelEditor',
            aspectToLoad: util.getURLParameterByName('aspect') || 'All',
            activeSelectionToLoad: util.getURLParameterByName('selection') ?
                util.getURLParameterByName('selection').split(',') : []
        };
        //var queryObj = util.getObjectFromUrlQuery(location.search);
        // TODO: use this instead and add tests (only parses the string once).
        //return {
        //    layoutToLoad: queryObj.layout || 'DefaultLayout',
        //    commitToLoad: queryObj.commit ? queryObj.commit.toLowerCase() : '',
        //    projectToLoad:  queryObj.project || '',
        //    objectToLoad: queryObj.activeObject ? queryObj.activeObject.toLowerCase() : '',
        //    createNewProject: queryObj.create === 'true',
        //    branchToLoad: queryObj.branch || ''
        //};
    };

    serializeStateToUrl = function () {
        var searchQuery = ''; // default if project is not open

        if (WebGMEGlobal.State.getActiveProjectName()) {
            searchQuery = 'project=' + WebGMEGlobal.State.getActiveProjectName();

            if (WebGMEGlobal.State.getActiveBranch()) {
                searchQuery += '&branch=' + WebGMEGlobal.State.getActiveBranch();
            } else if (WebGMEGlobal.State.getActiveCommit()) {
                searchQuery += '&commit=' + WebGMEGlobal.State.getActiveCommit();
            }

            if (WebGMEGlobal.State.getActiveObject()) {
                searchQuery += '&node=' + WebGMEGlobal.State.getActiveObject();
            } else if (WebGMEGlobal.State.getActiveObject() === CONSTANTS.PROJECT_ROOT_ID) {
                searchQuery += '&node=root';
            }

            if (WebGMEGlobal.State.getActiveVisualizer()) {
                searchQuery += '&visualizer=' + WebGMEGlobal.State.getActiveVisualizer();
            }

            if (WebGMEGlobal.State.getActiveAspect()) {
                searchQuery += '&aspect=' + WebGMEGlobal.State.getActiveAspect();
            }

            // leave this last, url may exceeds the max url limit
            if (WebGMEGlobal.State.getActiveSelection()) {
                searchQuery += '&selection=' + WebGMEGlobal.State.getActiveSelection().join(',');
            }
        }

        return searchQuery;
    };

    loadStateFromParsedUrl = function (parsedUrl) {
        var state = {};

        state[CONSTANTS.STATE_ACTIVE_ASPECT] = parsedUrl.aspectToLoad;

        if (parsedUrl.branchToLoad) {
            state[CONSTANTS.STATE_ACTIVE_BRANCH_NAME] = parsedUrl.branchToLoad;
        } else if (parsedUrl.commitToLoad) {
            state[CONSTANTS.STATE_ACTIVE_COMMIT] = parsedUrl.commitToLoad;
        }

        //state[CONSTANTS.STATE_ACTIVE_CROSSCUT] = parsedUrl.crosscutToLoad;

        state[CONSTANTS.STATE_ACTIVE_OBJECT] = parsedUrl.objectToLoad === 'root' ?
            CONSTANTS.PROJECT_ROOT_ID : parsedUrl.objectToLoad;

        state[CONSTANTS.STATE_ACTIVE_PROJECT_NAME] = parsedUrl.projectToLoad;
        state[CONSTANTS.STATE_ACTIVE_SELECTION] = parsedUrl.activeSelectionToLoad;
        state[CONSTANTS.STATE_ACTIVE_VISUALIZER] = parsedUrl.visualizerToLoad;

        setTimeout(function () {
            WebGMEGlobal.State.set(state);
        }, 1000);
    };

    return {
        parseInitialThingsToDoFromUrl: parseInitialThingsToDoFromUrl,
        serializeStateToUrl: serializeStateToUrl,
        loadStateFromParsedUrl: loadStateFromParsedUrl
    };

});<commit_msg>#304 remove previously introduced timeout.<commit_after>/*jshint browser:true*/
/*globals define, _, requirejs, WebGMEGlobal*/

define ([
        'js/util',
        'js/Constants'
    ],
    function (util, CONSTANTS) {

    'use strict';

    var parseInitialThingsToDoFromUrl,
        serializeStateToUrl,
        loadStateFromParsedUrl;

    parseInitialThingsToDoFromUrl = function () {
        return {
            layoutToLoad: util.getURLParameterByName('layout') || 'DefaultLayout',
            commitToLoad: util.getURLParameterByName('commit').toLowerCase(),
            projectToLoad:  util.getURLParameterByName('project'),
            objectToLoad: util.getURLParameterByName('node').toLowerCase() || CONSTANTS.PROJECT_ROOT_ID,
            createNewProject: util.getURLParameterByName('create') === 'true',
            branchToLoad: util.getURLParameterByName('branch'),
            visualizerToLoad: util.getURLParameterByName('visualizer') || 'ModelEditor',
            aspectToLoad: util.getURLParameterByName('aspect') || 'All',
            activeSelectionToLoad: util.getURLParameterByName('selection') ?
                util.getURLParameterByName('selection').split(',') : []
        };
        //var queryObj = util.getObjectFromUrlQuery(location.search);
        // TODO: use this instead and add tests (only parses the string once).
        //return {
        //    layoutToLoad: queryObj.layout || 'DefaultLayout',
        //    commitToLoad: queryObj.commit ? queryObj.commit.toLowerCase() : '',
        //    projectToLoad:  queryObj.project || '',
        //    objectToLoad: queryObj.activeObject ? queryObj.activeObject.toLowerCase() : '',
        //    createNewProject: queryObj.create === 'true',
        //    branchToLoad: queryObj.branch || ''
        //};
    };

    serializeStateToUrl = function () {
        var searchQuery = ''; // default if project is not open

        if (WebGMEGlobal.State.getActiveProjectName()) {
            searchQuery = 'project=' + WebGMEGlobal.State.getActiveProjectName();

            if (WebGMEGlobal.State.getActiveBranch()) {
                searchQuery += '&branch=' + WebGMEGlobal.State.getActiveBranch();
            } else if (WebGMEGlobal.State.getActiveCommit()) {
                searchQuery += '&commit=' + WebGMEGlobal.State.getActiveCommit();
            }

            if (WebGMEGlobal.State.getActiveObject()) {
                searchQuery += '&node=' + WebGMEGlobal.State.getActiveObject();
            } else if (WebGMEGlobal.State.getActiveObject() === CONSTANTS.PROJECT_ROOT_ID) {
                searchQuery += '&node=root';
            }

            if (WebGMEGlobal.State.getActiveVisualizer()) {
                searchQuery += '&visualizer=' + WebGMEGlobal.State.getActiveVisualizer();
            }

            if (WebGMEGlobal.State.getActiveAspect()) {
                searchQuery += '&aspect=' + WebGMEGlobal.State.getActiveAspect();
            }

            // leave this last, url may exceeds the max url limit
            if (WebGMEGlobal.State.getActiveSelection()) {
                searchQuery += '&selection=' + WebGMEGlobal.State.getActiveSelection().join(',');
            }
        }

        return searchQuery;
    };

    loadStateFromParsedUrl = function (parsedUrl) {
        var state = {};

        state[CONSTANTS.STATE_ACTIVE_ASPECT] = parsedUrl.aspectToLoad;

        if (parsedUrl.branchToLoad) {
            state[CONSTANTS.STATE_ACTIVE_BRANCH_NAME] = parsedUrl.branchToLoad;
        } else if (parsedUrl.commitToLoad) {
            state[CONSTANTS.STATE_ACTIVE_COMMIT] = parsedUrl.commitToLoad;
        }

        //state[CONSTANTS.STATE_ACTIVE_CROSSCUT] = parsedUrl.crosscutToLoad;

        state[CONSTANTS.STATE_ACTIVE_OBJECT] = parsedUrl.objectToLoad === 'root' ?
            CONSTANTS.PROJECT_ROOT_ID : parsedUrl.objectToLoad;

        state[CONSTANTS.STATE_ACTIVE_PROJECT_NAME] = parsedUrl.projectToLoad;
        state[CONSTANTS.STATE_ACTIVE_SELECTION] = parsedUrl.activeSelectionToLoad;
        state[CONSTANTS.STATE_ACTIVE_VISUALIZER] = parsedUrl.visualizerToLoad;

        //setTimeout(function () {
        WebGMEGlobal.State.set(state);
        //}, 1000);
    };

    return {
        parseInitialThingsToDoFromUrl: parseInitialThingsToDoFromUrl,
        serializeStateToUrl: serializeStateToUrl,
        loadStateFromParsedUrl: loadStateFromParsedUrl
    };

});<|endoftext|>


<commit_before>import RecordValues from './record-values';
import pgformat from 'pg-format';

export default class PostgresRecordValues extends RecordValues {
  static setupSearch(values, feature) {
    const searchableValue = feature.searchableValue;

    values.record_index_text = searchableValue;
    values.record_index = {raw: `to_tsvector(${ pgformat('%L', searchableValue) })`};

    return values;
  }

  static setupPoint(values, latitude, longitude) {
    const wkt = pgformat('POINT(%s %s)', longitude, latitude);

    return {raw: `ST_Force2D(ST_SetSRID(ST_GeomFromText('${ wkt }'), 4326))`};
  }
}
<commit_msg>specify 'simple' as text search configuration for the function to_tsvector<commit_after>import RecordValues from './record-values';
import pgformat from 'pg-format';

export default class PostgresRecordValues extends RecordValues {
  static setupSearch(values, feature) {
    const searchableValue = feature.searchableValue;

    values.record_index_text = searchableValue;
    values.record_index = {raw: `to_tsvector('simple', ${ pgformat('%L', searchableValue) })`};

    return values;
  }

  static setupPoint(values, latitude, longitude) {
    const wkt = pgformat('POINT(%s %s)', longitude, latitude);

    return {raw: `ST_Force2D(ST_SetSRID(ST_GeomFromText('${ wkt }'), 4326))`};
  }
}
<|endoftext|>


<commit_before>import m from 'mithril';
import Velocity from 'velocity-animate';
import {removeSong} from '../../socket/RestRequests';
import {Head, Spotify, SongPreview} from '../../components';
import funimations from '../endAnimations';

const vm = {
  init: () => {
    vm.flipped = m.prop([false, false, false]);
    vm.added = m.prop([false, false, false]);
    vm.playing = m.prop(false);
    vm.isPlaying = false;
  },
};

// View Helpers
const mid = (year, length) =>

Released

{year}

Length

{length}

;

const removeButton = (songToRemove,id) =>

     REMOVE
  ;

const foot = (uri, id, addSong) =>

    {removeButton(uri,id)}
  ;

const img = (url, id, preview, uri) =>

;

const songTitle = (name, album) =>

{name}

{album}

;

const front = (song, id, addSong, preview) =>
  <div id={`front-${id}`} className="card card-width smallCard">
    {img(song.img, id, preview, song.uri)}

      {songTitle(song.name, song.album)}

    {foot(song.uri, id, addSong)}

;

const view = (_, { song, ID, addSong, preview }) =>

    <div id={`flip-box-${ID}`}
      className="flipper card-width">

        {front(song, ID, addSong, preview)}

;

const controller = () => vm.init();

export default {
  vm,
  view,
  controller,
};
<commit_msg>asdfas<commit_after>import m from 'mithril';
import Velocity from 'velocity-animate';
import {removeSong} from '../../socket/RestRequests';
import {Head, Spotify, SongPreview} from '../../components';
import funimations from '../endAnimations';

const vm = {
  init: () => {
    vm.flipped = m.prop([false, false, false]);
    vm.added = m.prop([false, false, false]);
    vm.playing = m.prop(false);
    vm.isPlaying = false;
  },
};

// View Helpers
const mid = (year, length) =>

Released

{year}

Length

{length}

;

const removeButton = (songToRemove,id) =>

     REMOVE
  ;

const foot = (uri, id, addSong) =>

    {removeButton(uri,id)}
  ;

const img = (url, id, preview, uri) =>

;

const songTitle = (name, album) =>

{name}

{album}

;

const front = (song, id, addSong, preview) =>
  <div id={`front-${id}`} className="card card-width smallCard">
    {img(song.img, id, preview, song.uri)}

      {songTitle(song.name, song.album)}

    {foot(song.uri, id, addSong)}

;

const view = (_, { song, ID, addSong, preview }) =>

    <div id={`flip-box-${ID}`}
      className="flipper card-width">

        {front(song, ID, addSong, preview)}

;

const controller = () => vm.init();

export default {
  vm,
  view,
  controller,
};
<|endoftext|>


<commit_before>// @flow
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import LoadingOverlay from '../../components/LoadingOverlay';
import Operation from '../components/Operation';
import ApplicationHome from '../components/ApplicationHome';
import * as utils from '../../utils';
import Model from './Model';

import type { Service } from '../../generated/version/ServiceType';

import styles from './application.css';

import { actions as serviceActions } from '../../generated/version';

const allActions = Object.assign({}, serviceActions);

type Params = {
  model?: string,
  resource?: string,
  method: string,
  path: string,
  applicationKey: string,
  organizationKey: string,
}

type Props = {
  actions: Object, // FIXME
  params: Params, // FIXME
  loaded: boolean,
  service: Service,
  importedServices: Service[],
}

export class Application extends Component {
  props: Props;

  componentDidMount() {
    const orgKey = this.props.params.organizationKey;
    const applicationKey = this.props.params.applicationKey;
    this.props.actions.getByOrgkeyAndApplicationkeyAndVersion_get(
      { orgKey, applicationKey, version: 'latest' },
    );
  }

  render() {
    const { service, importedServices } = this.props;

    if (!service) {
      return <LoadingOverlay isLoaded={this.props.loaded} />;
    }
    if (this.props.params.resource) {
      // Load Operation
      const {
        method,
        path,
        resource: resourceType,
        applicationKey,
        organizationKey,
      } = this.props.params;

      const operation = utils.getOperation(resourceType, method, path, service);
      const resource = utils.getResource(resourceType, service);

      return (
        <LoadingOverlay isLoaded={this.props.loaded}>
          <Operation
            service={service}
            importedServices={importedServices}
            operation={operation}
            applicationKey={applicationKey}
            organizationKey={organizationKey}
            resource={resource}
            method={method}
            path={path}
          />
        </LoadingOverlay>
      );
    } else if (this.props.params.model) {
      // Load Model
      const modelName = this.props.params.model;
      if (utils.isEnum(modelName, service, importedServices)) {
        // FIXME - not sure if this is enum or model? Need a test case
        const enumModel = utils.getEnum(modelName, service, importedServices);
        /* if (enumModel) {
         *   enumModel.fields = enumModel.values.map(value => (
         *     { name: value.name, description: value.description, type: 'string', required: false }
         *   ));
         * }*/
        return (
          <LoadingOverlay isLoaded={this.props.loaded}>
            <Model model={enumModel} service={service} importedServices={importedServices} showJsonDoc={false} />;
          </LoadingOverlay>
        );
      } else {
        const model = utils.getModel(modelName, service, importedServices);
        return (
          <LoadingOverlay isLoaded={this.props.loaded}>
            <Model model={model} service={service} importedServices={importedServices} showJsonDoc={true} />;
          </LoadingOverlay>
        );
      }
    } else {
      // Load Application Home
      const {
        applicationKey,
        organizationKey,
      } = this.props.params;

      return (
        <LoadingOverlay isLoaded={this.props.loaded}>
          <ApplicationHome
            service={service}
            applicationKey={applicationKey}
            organizationKey={organizationKey}
          />
        </LoadingOverlay>
      );
    }
  }
}

const mapStateToProps = state => (
  {
    loaded: state.application.loaded,
    service: state.application.service,
    importedServices: state.application.importedServices,
  }
);

const mapDispatchToProps = dispatch => (
  { actions: bindActionCreators(allActions, dispatch) }
);

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(Application);

export {
  styles,
};
<commit_msg>Uncomment enum transform code<commit_after>// @flow
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import LoadingOverlay from '../../components/LoadingOverlay';
import Operation from '../components/Operation';
import ApplicationHome from '../components/ApplicationHome';
import * as utils from '../../utils';
import Model from './Model';

import type { Service } from '../../generated/version/ServiceType';

import styles from './application.css';

import { actions as serviceActions } from '../../generated/version';

const allActions = Object.assign({}, serviceActions);

type Params = {
  model?: string,
  resource?: string,
  method: string,
  path: string,
  applicationKey: string,
  organizationKey: string,
}

type Props = {
  actions: Object, // FIXME
  params: Params, // FIXME
  loaded: boolean,
  service: Service,
  importedServices: Service[],
}

export class Application extends Component {
  props: Props;

  componentDidMount() {
    const orgKey = this.props.params.organizationKey;
    const applicationKey = this.props.params.applicationKey;
    this.props.actions.getByOrgkeyAndApplicationkeyAndVersion_get(
      { orgKey, applicationKey, version: 'latest' },
    );
  }

  render() {
    const { service, importedServices } = this.props;

    if (!service) {
      return <LoadingOverlay isLoaded={this.props.loaded} />;
    }
    if (this.props.params.resource) {
      // Load Operation
      const {
        method,
        path,
        resource: resourceType,
        applicationKey,
        organizationKey,
      } = this.props.params;

      const operation = utils.getOperation(resourceType, method, path, service);
      const resource = utils.getResource(resourceType, service);

      return (
        <LoadingOverlay isLoaded={this.props.loaded}>
          <Operation
            service={service}
            importedServices={importedServices}
            operation={operation}
            applicationKey={applicationKey}
            organizationKey={organizationKey}
            resource={resource}
            method={method}
            path={path}
          />
        </LoadingOverlay>
      );
    } else if (this.props.params.model) {
      // Load Model
      const modelName = this.props.params.model;
      if (utils.isEnum(modelName, service, importedServices)) {
        // FIXME - not sure if this is enum or model? Need a test case
        const enumModel = utils.getEnum(modelName, service, importedServices);
        if (enumModel) {
          enumModel.fields = enumModel.values.map(value => (
            { name: value.name, description: value.description, type: 'string', required: false }
          ));
        }
        return (
          <LoadingOverlay isLoaded={this.props.loaded}>
            <Model model={enumModel} service={service} importedServices={importedServices} showJsonDoc={false} />
          </LoadingOverlay>
        );
      } else {
        const model = utils.getModel(modelName, service, importedServices);
        return (
          <LoadingOverlay isLoaded={this.props.loaded}>
            <Model model={model} service={service} importedServices={importedServices} showJsonDoc={true} />
          </LoadingOverlay>
        );
      }
    } else {
      // Load Application Home
      const {
        applicationKey,
        organizationKey,
      } = this.props.params;

      return (
        <LoadingOverlay isLoaded={this.props.loaded}>
          <ApplicationHome
            service={service}
            applicationKey={applicationKey}
            organizationKey={organizationKey}
          />
        </LoadingOverlay>
      );
    }
  }
}

const mapStateToProps = state => (
  {
    loaded: state.application.loaded,
    service: state.application.service,
    importedServices: state.application.importedServices,
  }
);

const mapDispatchToProps = dispatch => (
  { actions: bindActionCreators(allActions, dispatch) }
);

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(Application);

export {
  styles,
};
<|endoftext|>


<commit_before>jQuery(document).ready(function($){
  $('#equalize').equalHeights();
  $(document).pngFix();
  $("select[name=news_item_type]").change(refreshSortOrder);
  renderUserHeader();

  if (jQuery("#category_select option:selected").val() == 'Sub-network') {
    id = jQuery("#network_select option:selected").val();
    load_categories(id);
  }
});

jQuery("a").click(function($){
  $(".navigation a.selected").removeClass("selected");
  $(this).addClass("selected");
  return false;
});

function toggle_divs(div1, div2) {
  jQuery(div1).toggle();
  jQuery(div2).toggle();
}

$(function() {
  if ($.browser.msie && parseInt($.browser.version)< 7) {
    $("#reporters_toolbar li").hover(
      function() { $(this).addClass("sf"); },
      function() { $(this).removeClass("sf"); }
    );
  }
});

function renderUserHeader() {
  if (jQuery.cookie('current_user_full_name')) {
    // we are logged in
    jQuery('#logged_in span').html(decodeURI(jQuery.cookie('current_user_full_name').replace(/\+/g," ")));
    if (jQuery.cookie('balance_text')) {
      jQuery('#current_balance_line').html(decodeURI(jQuery.cookie('balance_text').replace(/\+/g," ")));
    }
    jQuery('#logged_in').show();
  } else {
    jQuery('#not_logged_in').show();
  }
}

function refreshSortOrder(){
  var select = jQuery('select[name=sort_by]');
  var type   = jQuery('select[name=news_item_type]')

  jQuery.get('/news_items/sort_options', {
    sort_by: select.val(),
    news_item_type: type.val()
  }, function(html, status){
    select.html(html);
  });
};

jQuery("#network_select").live("change", function() {
    id = jQuery("#network_select option:selected").val();
    load_categories(id);
});

function load_categories(id) {
    jQuery("#category_select").empty();
    jQuery.getJSON("/networks/" + id + "/categories", function(data){
      jQuery("<option>Sub-network...</option>").attr("value", "").appendTo("#category_select");
      jQuery.each(data, function(i, category) {
        jQuery("<option>" + category.name + "</option>").attr("value", category.id).appendTo("#category_select");
      });
    });
}
<commit_msg>Add facebox to all rel=facebox links<commit_after>jQuery(document).ready(function($){
  $('#equalize').equalHeights();
  $(document).pngFix();
  $("select[name=news_item_type]").change(refreshSortOrder);
  renderUserHeader();

  if (jQuery("#category_select option:selected").val() == 'Sub-network') {
    id = jQuery("#network_select option:selected").val();
    load_categories(id);
  }
});

jQuery("a").click(function($){
  $(".navigation a.selected").removeClass("selected");
  $(this).addClass("selected");
  return false;
});

function toggle_divs(div1, div2) {
  jQuery(div1).toggle();
  jQuery(div2).toggle();
}

$(function() {
  if ($.browser.msie && parseInt($.browser.version)< 7) {
    $("#reporters_toolbar li").hover(
      function() { $(this).addClass("sf"); },
      function() { $(this).removeClass("sf"); }
    );
  }
});

function renderUserHeader() {
  if (jQuery.cookie('current_user_full_name')) {
    // we are logged in
    jQuery('#logged_in span').html(decodeURI(jQuery.cookie('current_user_full_name').replace(/\+/g," ")));
    if (jQuery.cookie('balance_text')) {
      jQuery('#current_balance_line').html(decodeURI(jQuery.cookie('balance_text').replace(/\+/g," ")));
    }
    jQuery('#logged_in').show();
  } else {
    jQuery('#not_logged_in').show();
  }
}

function refreshSortOrder(){
  var select = jQuery('select[name=sort_by]');
  var type   = jQuery('select[name=news_item_type]')

  jQuery.get('/news_items/sort_options', {
    sort_by: select.val(),
    news_item_type: type.val()
  }, function(html, status){
    select.html(html);
  });
};

jQuery("#network_select").live("change", function() {
    id = jQuery("#network_select option:selected").val();
    load_categories(id);
});

function load_categories(id) {
    jQuery("#category_select").empty();
    jQuery.getJSON("/networks/" + id + "/categories", function(data){
      jQuery("<option>Sub-network...</option>").attr("value", "").appendTo("#category_select");
      jQuery.each(data, function(i, category) {
        jQuery("<option>" + category.name + "</option>").attr("value", category.id).appendTo("#category_select");
      });
    });
}

jQuery(document).ready(function($) {
  $('a[rel*=facebox]').facebox()
});
<|endoftext|>


<commit_before>import {ServiceBase} from './service-base';
import {CrudService} from './crud-service';
import {GuestService} from './guest-service';
import {HostService} from './host-service';
import {MetricsService} from './metrics-service';
import {RealmService} from './realm-service';
import {TemplateService} from './template-service';
import {UserService} from './user-service';
import {BrokerService} from './broker-service';
import {ExchangeService} from './exchange-service';
import {QueueService} from './queue-service';

export function configure(aurelia) {}
export {
  ServiceBase,
  CrudService,
  GuestService,
  HostService,
  MetricsService,
  RealmService,
  TemplateService,
  UserService,
  BrokerService,
  ExchangeService,
  QueueService
};
<commit_msg>feat(pool-service): add PoolService for guest pool access<commit_after>import {ServiceBase} from './service-base';
import {CrudService} from './crud-service';
import {GuestService} from './guest-service';
import {HostService} from './host-service';
import {MetricsService} from './metrics-service';
import {RealmService} from './realm-service';
import {TemplateService} from './template-service';
import {UserService} from './user-service';
import {BrokerService} from './broker-service';
import {ExchangeService} from './exchange-service';
import {QueueService} from './queue-service';
import {PoolService} from './pool-service';

export function configure(aurelia) {}
export {
  ServiceBase,
  CrudService,
  GuestService,
  HostService,
  MetricsService,
  RealmService,
  TemplateService,
  UserService,
  BrokerService,
  ExchangeService,
  QueueService,
  PoolService
};
<|endoftext|>