<commit_before>// 汎用タスク定義
require( 'require-dir' )( './gulp/tasks', { recurse: true } );

////////////////////////////////////////////////////////////////////////////////
//                           プロジェクト固有タスク
////////////////////////////////////////////////////////////////////////////////

var gulp = require( 'gulp' );

/**
 * リリース用イメージを削除します。
 *
 * @param {Function} cb コールバック関数。
 */
gulp.task( 'clean', function( cb ) {
    var del = require( 'del' );
    del( [ './bin/src', './bin/release' ], cb );
} );

/**
 * リリース用 CSS と、その参照を解決した HTML を生成します。
 *
 * @return {[type]} [description]
 */
gulp.task( 'css-release', [ 'clean', 'css', ], function() {
    var runSequence = require( 'run-sequence' );
    runSequence( 'useref' );
} );

/**
 * リリース用イメージに必要なファイルをコピーします。
 *
 * @return {Object} gulp ストリーム。
 */
gulp.task( 'copy', [ 'js-release', 'css-release' ], function() {
    return gulp.src(
            [ './src/fonts/**', './src/js/bundle.js', 'src/package.json' ],
            { base: './src' }
        )
        .pipe( gulp.dest( './bin/src' ) );
} );

/**
 * ブロジェクトのリリース用イメージを出力します。
 */
gulp.task( 'release', [ 'copy' ], function() {
    var runSequence = require( 'run-sequence' );
    runSequence( 'nw' );
} );

/**
 * 開発用リソースの変更を監視して、必要ならビルドを実行します。
 */
gulp.task( 'watch', [ 'css', 'iconfont', 'watchify' ], function () {
    gulp.watch( [ './src/stylus/*.styl', '!./src/css/*.css' ], [ 'css' ] );
    gulp.watch( [ './icons/*.svg' ], [ 'iconfont' ] );
} );

/**
 * gulp の既定タスクです。
 */
gulp.task( 'default', [ 'watch' ] );
<commit_msg>#3 リリース用ビルドでアイコン フォント生成が抜けていたため、追加<commit_after>// 汎用タスク定義
require( 'require-dir' )( './gulp/tasks', { recurse: true } );

////////////////////////////////////////////////////////////////////////////////
//                           プロジェクト固有タスク
////////////////////////////////////////////////////////////////////////////////

var gulp = require( 'gulp' );

/**
 * リリース用イメージを削除します。
 *
 * @param {Function} cb コールバック関数。
 */
gulp.task( 'clean', function( cb ) {
    var del = require( 'del' );
    del( [ './bin/src', './bin/release' ], cb );
} );

/**
 * リリース用 CSS と、その参照を解決した HTML を生成します。
 *
 * @return {[type]} [description]
 */
gulp.task( 'css-release', [ 'clean', 'css', ], function() {
    var runSequence = require( 'run-sequence' );
    runSequence( 'useref' );
} );

/**
 * リリース用イメージに必要なファイルをコピーします。
 *
 * @return {Object} gulp ストリーム。
 */
gulp.task( 'copy', [ 'js-release', 'css-release', 'iconfont' ], function() {
    return gulp.src(
            [ './src/fonts/**', './src/js/bundle.js', 'src/package.json' ],
            { base: './src' }
        )
        .pipe( gulp.dest( './bin/src' ) );
} );

/**
 * ブロジェクトのリリース用イメージを出力します。
 */
gulp.task( 'release', [ 'copy' ], function() {
    var runSequence = require( 'run-sequence' );
    runSequence( 'nw' );
} );

/**
 * 開発用リソースの変更を監視して、必要ならビルドを実行します。
 */
gulp.task( 'watch', [ 'css', 'iconfont', 'watchify' ], function () {
    gulp.watch( [ './src/stylus/*.styl', '!./src/css/*.css' ], [ 'css' ] );
    gulp.watch( [ './icons/*.svg' ], [ 'iconfont' ] );
} );

/**
 * gulp の既定タスクです。
 */
gulp.task( 'default', [ 'watch' ] );
<|endoftext|>


<commit_before>cronenberg.DashboardHolder = function(url_, element_) {
    this.url = url_;
    this.dashboard = null;
    this.element = element_;

    this.setRange = function(from, until) {
        var self = this;
        var url = URI(self.url);
        if (from) {
            url.setQuery('from', from);
        }
        if (until) {
            url.setQuery('until', until);
        }
        self.url = url.href();
    };
};

cronenberg.DashboardManager = function() {
    this.current = null,

    /**
     * Register an event handler for processing a dashboard once it's
     * loaded and ready.
     */
    this.onDashboardLoaded = function(handler) {
        var self = this;
        bean.on(self, cronenberg.events.DASHBOARD_LOADED, handler);
        return self;
    };

    this.load = function(url, element) {
        var self = this;
        self.current = new cronenberg.DashboardHolder(url, element);
        $.ajax({
            dataType: "json",
            url: url
        }).done(function(data) {
            var dashboard = data.entities[0];
            self.current.dashboard = dashboard;

            // Build a map from the presentation elements to their
            // model objects.
            dashboard.elementToItemMap = {};
            _.each(dashboard.grid.rows, function(row) {
                if (row.item_type == 'row') {
                    _.each(row.cells, function(cell) {
                        _.each(cell.presentation, function(presentation) {
                            if (typeof(presentation.element_id) != "undefined") {
                                dashboard.elementToItemMap[presentation.element_id] = presentation;
                            }
                        });
                    });
                }
            });

            // Set up the queries
            cronenberg.queries.clear();
            for (var query_name in dashboard.queries) {
                cronenberg.queries.add(query_name, dashboard.queries[query_name]);
            }

            // Render the dashboard
            var rendered = cronenberg.templates.render(dashboard);
            $(self.current.element).html(rendered);

            var currentURL = URI(self.current.url);

            bean.fire(self, cronenberg.events.RANGE_CHANGED, {
                from: currentURL.query('from'),
                until: currentURL.query('until')
            });

            // Load the queries
            cronenberg.queries.loadAll();

            bean.fire(self, cronenberg.events.DASHBOARD_LOADED, dashboard);
        });
        return self;
    };

    this.refresh = function() {
        var self = this;
        if (self.current) {
            self.load(self.current.url, self.current.element);
        }
    };

    this.set_time_range = function(from, until) {
        var self = this;
        var location = URI(window.location).setQuery('from', from).href();
        window.history.pushState({url: self.current.url, element:self.current.element}, '', location);

        self.current.setRange(from, until);
        bean.fire(self, cronenberg.events.RANGE_CHANGED, {
            from: from, until: until
        });
        self.refresh();
    };

    this.ranges = {
        // TODO - quick hack. Parse the range and generate on the fly
        // for maximum flexibiliy
        '-1h'  : 'Past Hour',
        '-2h'  : 'Past Two Hours',
        '-3h'  : 'Past Three Hours',
        '-4h'  : 'Past Four Hours',
        '-6h'  : 'Past Six Hours',
        '-12h' : 'Past Twelve Hours',
        '-1d'  : 'Past Day',
        '-7d'  : 'Past Week'
    };

    this.getRangeDescription = function(range) {
        var self = this;
        if (range in self.ranges) {
            return self.ranges[range];
        } else {
            return null;
        }
    };

    this.onRangeChanged = function(handler) {
        var self = this;
        bean.on(self, cronenberg.events.RANGE_CHANGED, handler);
    };

    this.autoRefreshInterval = null;
    this.intervalId = null;

    this.set_refresh_interval = function(value) {
        var self = this;
        var intervalSeconds = parseInt(value);
        self.autoRefreshInterval = intervalSeconds;
        if (self.intervalId) {
            window.clearInterval(self.intervalId);
        }
        if (intervalSeconds > 0) {
            self.intervalSeconds = intervalSeconds;
            self.intervalId = window.setInterval(self.refresh, intervalSeconds * 1000);
        }
    };
};

cronenberg.dashboards = new cronenberg.DashboardManager();
<commit_msg>Consistent range labels<commit_after>cronenberg.DashboardHolder = function(url_, element_) {
    this.url = url_;
    this.dashboard = null;
    this.element = element_;

    this.setRange = function(from, until) {
        var self = this;
        var url = URI(self.url);
        if (from) {
            url.setQuery('from', from);
        }
        if (until) {
            url.setQuery('until', until);
        }
        self.url = url.href();
    };
};

cronenberg.DashboardManager = function() {
    this.current = null,

    /**
     * Register an event handler for processing a dashboard once it's
     * loaded and ready.
     */
    this.onDashboardLoaded = function(handler) {
        var self = this;
        bean.on(self, cronenberg.events.DASHBOARD_LOADED, handler);
        return self;
    };

    this.load = function(url, element) {
        var self = this;
        self.current = new cronenberg.DashboardHolder(url, element);
        $.ajax({
            dataType: "json",
            url: url
        }).done(function(data) {
            var dashboard = data.entities[0];
            self.current.dashboard = dashboard;

            // Build a map from the presentation elements to their
            // model objects.
            dashboard.elementToItemMap = {};
            _.each(dashboard.grid.rows, function(row) {
                if (row.item_type == 'row') {
                    _.each(row.cells, function(cell) {
                        _.each(cell.presentation, function(presentation) {
                            if (typeof(presentation.element_id) != "undefined") {
                                dashboard.elementToItemMap[presentation.element_id] = presentation;
                            }
                        });
                    });
                }
            });

            // Set up the queries
            cronenberg.queries.clear();
            for (var query_name in dashboard.queries) {
                cronenberg.queries.add(query_name, dashboard.queries[query_name]);
            }

            // Render the dashboard
            var rendered = cronenberg.templates.render(dashboard);
            $(self.current.element).html(rendered);

            var currentURL = URI(self.current.url);

            bean.fire(self, cronenberg.events.RANGE_CHANGED, {
                from: currentURL.query('from'),
                until: currentURL.query('until')
            });

            // Load the queries
            cronenberg.queries.loadAll();

            bean.fire(self, cronenberg.events.DASHBOARD_LOADED, dashboard);
        });
        return self;
    };

    this.refresh = function() {
        var self = this;
        if (self.current) {
            self.load(self.current.url, self.current.element);
        }
    };

    this.set_time_range = function(from, until) {
        var self = this;
        var location = URI(window.location).setQuery('from', from).href();
        window.history.pushState({url: self.current.url, element:self.current.element}, '', location);

        self.current.setRange(from, until);
        bean.fire(self, cronenberg.events.RANGE_CHANGED, {
            from: from, until: until
        });
        self.refresh();
    };

    this.ranges = {
        // TODO - quick hack. Parse the range and generate on the fly
        // for maximum flexibiliy
        '-1h'  : 'Past Hour',
        '-2h'  : 'Past 2 Hours',
        '-3h'  : 'Past 3 Hours',
        '-4h'  : 'Past 4 Hours',
        '-6h'  : 'Past 6 Hours',
        '-12h' : 'Past 12 Hours',
        '-1d'  : 'Past Day',
        '-7d'  : 'Past Week'
    };

    this.getRangeDescription = function(range) {
        var self = this;
        if (range in self.ranges) {
            return self.ranges[range];
        } else {
            return null;
        }
    };

    this.onRangeChanged = function(handler) {
        var self = this;
        bean.on(self, cronenberg.events.RANGE_CHANGED, handler);
    };

    this.autoRefreshInterval = null;
    this.intervalId = null;

    this.set_refresh_interval = function(value) {
        var self = this;
        var intervalSeconds = parseInt(value);
        self.autoRefreshInterval = intervalSeconds;
        if (self.intervalId) {
            window.clearInterval(self.intervalId);
        }
        if (intervalSeconds > 0) {
            self.intervalSeconds = intervalSeconds;
            self.intervalId = window.setInterval(self.refresh, intervalSeconds * 1000);
        }
    };
};

cronenberg.dashboards = new cronenberg.DashboardManager();
<|endoftext|>


<commit_before>/**
 * @file guildMemberAdd event
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

module.exports = async member => {
  try {
    const greetMessages = xrequire('./assets/greetingMessages.json');

    let guildModel = await member.client.database.models.guild.findOne({
      attributes: [ 'greet', 'greetMessage', 'greetTimeout', 'greetPrivate', 'greetPrivateMessage', 'autoAssignableRoles', 'serverLog' ],
      where: {
        guildID: member.guild.id
      }
    });
    if (!guildModel) return;

    if (guildModel.dataValues.serverLog) {
      let logChannel = member.guild.channels.get(guildModel.dataValues.serverLog);
      if (logChannel) {
        logChannel.send({
          embed: {
            color: member.guild.client.colors.GREEN,
            title: member.guild.client.i18n.event(member.guild.language, 'guildMemberAdd'),
            fields: [
              {
                name: 'User',
                value: member.user.tag,
                inline: true
              },
              {
                name: 'User ID',
                value: member.id,
                inline: true
              }
            ],
            timestamp: new Date()
          }
        }).catch(e => {
          member.guild.client.log.error(e);
        });
      }
    }

    if (guildModel.dataValues.greet) {
      let greetMessage;
      if (guildModel.dataValues.greetMessage) {
        greetMessage = await member.client.utils.decompressString(guildModel.dataValues.greetMessage);
      }
      else {
        greetMessage = greetMessages[Math.floor(Math.random() * greetMessages.length)];
      }
      greetMessage = greetMessage.replace(/\$user/ig, `<@${member.id}>`);
      greetMessage = greetMessage.replace(/\$server/ig, member.guild.name);
      greetMessage = greetMessage.replace(/\$username/ig, member.displayName);
      greetMessage = greetMessage.replace(/\$prefix/ig, member.guild.prefix ? member.guild.prefix[0] : member.client.configurations.prefix[0]);

      let greetChannel = member.guild.channels.get(guildModel.dataValues.greet);
      if (greetChannel) {
        greetChannel.send({
          embed: {
            color: member.client.colors.BLUE,
            title: `Hello ${member.displayName}`,
            description: greetMessage
          }
        }).then(m => {
          if (guildModel.dataValues.greetTimeout > 0) {
            m.delete(1000 * parseInt(guildModel.dataValues.greetTimeout)).catch(e => {
              member.client.log.error(e);
            });
          }
        }).catch(e => {
          member.client.log.error(e);
        });
      }
    }

    if (guildModel.dataValues.greetPrivate) {
      let greetPrivateMessage;
      if (guildModel.dataValues.greetPrivateMessage) {
        greetPrivateMessage = await member.client.utils.decompressString(guildModel.dataValues.greetPrivateMessage);
      }
      else {
        greetPrivateMessage = greetMessages[Math.floor(Math.random() * greetMessages.length)];
      }
      greetPrivateMessage = greetPrivateMessage.replace(/\$user/ig, `<@${member.id}>`);
      greetPrivateMessage = greetPrivateMessage.replace(/\$server/ig, member.guild.name);
      greetPrivateMessage = greetPrivateMessage.replace(/\$username/ig, member.displayName);
      greetPrivateMessage = greetPrivateMessage.replace(/\$prefix/ig, member.guild.prefix ? member.guild.prefix[0] : member.client.configurations.prefix[0]);

      member.send({
        embed: {
          color: member.client.colors.BLUE,
          title: `Hello ${member.displayName}`,
          description: greetPrivateMessage
        }
      }).catch(e => {
        member.client.log.error(e);
      });
    }

    let autoAssignableRoles = [];
    if (guildModel.dataValues.autoAssignableRoles) {
      autoAssignableRoles = guildModel.dataValues.autoAssignableRoles;
    }
    autoAssignableRoles = autoAssignableRoles.filter(r => member.guild.roles.get(r));
    if (autoAssignableRoles.length) {
      member.addRoles(autoAssignableRoles).catch(() => {});
    }
  }
  catch (e) {
    member.client.log.error(e);
  }
};
<commit_msg>events(discord): implement new greeting messages in guildMemberAdd event<commit_after>/**
 * @file guildMemberAdd event
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

module.exports = async member => {
  try {
    const greetMessages = xrequire('./assets/greetingMessages.json');

    let guildModel = await member.client.database.models.guild.findOne({
      attributes: [ 'greet', 'greetMessage', 'greetTimeout', 'greetPrivate', 'greetPrivateMessage', 'autoAssignableRoles', 'serverLog' ],
      where: {
        guildID: member.guild.id
      }
    });
    if (!guildModel) return;

    if (guildModel.dataValues.serverLog) {
      let logChannel = member.guild.channels.get(guildModel.dataValues.serverLog);
      if (logChannel) {
        logChannel.send({
          embed: {
            color: member.guild.client.colors.GREEN,
            title: member.guild.client.i18n.event(member.guild.language, 'guildMemberAdd'),
            fields: [
              {
                name: 'User',
                value: member.user.tag,
                inline: true
              },
              {
                name: 'User ID',
                value: member.id,
                inline: true
              }
            ],
            timestamp: new Date()
          }
        }).catch(e => {
          member.guild.client.log.error(e);
        });
      }
    }

    if (guildModel.dataValues.greet) {
      let isEmbed = guildModel.dataValues.greetMessage && Object.keys(guildModel.dataValues.greetMessage).length;

      let greetMessage = isEmbed ? guildModel.dataValues.greetMessage : greetMessages.getRandom();

      if (isEmbed) {
        greetMessage = JSON.stringify(greetMessage);
      }

      greetMessage = greetMessage.replace(/\$user/ig, `<@${member.id}>`);
      greetMessage = greetMessage.replace(/\$server/ig, member.guild.name);
      greetMessage = greetMessage.replace(/\$username/ig, member.displayName);
      greetMessage = greetMessage.replace(/\$prefix/ig, member.guild.prefix ? member.guild.prefix[0] : member.client.configurations.prefix[0]);

      let text, embed;
      if (isEmbed) {
        greetMessage = JSON.parse(greetMessage);

        greetMessage.footer = {};
        greetMessage.footer.text = 'Greetings!';

        text = greetMessage.text ? greetMessage.text : null;
        delete greetMessage.text;
        embed = Object.keys(greetMessage).length ? greetMessage : null;
      }

      let greetChannel = member.guild.channels.get(guildModel.dataValues.greet);

      if (greetChannel) {
        let greetings;

        if (text && embed) {
          greetings = await greetChannel.send(text, { embed: embed }).catch(e => {
            member.client.log.error(e);
          });
        }
        else if (text) {
          greetings = await greetChannel.send({
            embed: {
              color: member.client.colors.BLUE,
              description: text,
              footer: {
                text: 'Greetings!'
              }
            }
          }).catch(e => {
            member.client.log.error(e);
          });
        }
        else if (embed) {
          greetings = await greetChannel.send({ embed: embed }).catch(e => {
            member.client.log.error(e);
          });
        }

        if (greetings && guildModel.dataValues.greetTimeout > 0) {
          await greetings.delete(1000 * parseInt(guildModel.dataValues.greetTimeout)).catch(e => {
            member.client.log.error(e);
          });
        }
      }
    }

    if (guildModel.dataValues.greetPrivate) {
      let isEmbed = guildModel.dataValues.greetPrivateMessage && Object.keys(guildModel.dataValues.greetPrivateMessage).length;

      let greetPrivateMessage = isEmbed ? guildModel.dataValues.greetPrivateMessage : greetMessages.getRandom();

      if (isEmbed) {
        greetPrivateMessage = JSON.stringify(greetPrivateMessage);
      }

      greetPrivateMessage = greetPrivateMessage.replace(/\$user/ig, `<@${member.id}>`);
      greetPrivateMessage = greetPrivateMessage.replace(/\$server/ig, member.guild.name);
      greetPrivateMessage = greetPrivateMessage.replace(/\$username/ig, member.displayName);
      greetPrivateMessage = greetPrivateMessage.replace(/\$prefix/ig, member.guild.prefix ? member.guild.prefix[0] : member.client.configurations.prefix[0]);

      let text, embed;
      if (isEmbed) {
        greetPrivateMessage = JSON.parse(greetPrivateMessage);

        greetPrivateMessage.footer = {};
        greetPrivateMessage.footer.text = 'Greetings!';

        text = greetPrivateMessage.text ? greetPrivateMessage.text : null;
        delete greetPrivateMessage.text;
        embed = Object.keys(greetPrivateMessage).length ? greetPrivateMessage : null;
      }

      if (text && embed) {
        await member.send(text, { embed: embed }).catch(e => {
          member.client.log.error(e);
        });
      }
      else if (text) {
        await member.send({
          embed: {
            color: member.client.colors.BLUE,
            description: text,
            footer: {
              text: 'Greetings!'
            }
          }
        }).catch(e => {
          member.client.log.error(e);
        });
      }
      else if (embed) {
        await member.send({ embed: embed }).catch(e => {
          member.client.log.error(e);
        });
      }
    }

    let autoAssignableRoles = [];
    if (guildModel.dataValues.autoAssignableRoles) {
      autoAssignableRoles = guildModel.dataValues.autoAssignableRoles;
    }
    autoAssignableRoles = autoAssignableRoles.filter(r => member.guild.roles.get(r));
    if (autoAssignableRoles.length) {
      member.addRoles(autoAssignableRoles).catch(() => {});
    }
  }
  catch (e) {
    member.client.log.error(e);
  }
};
<|endoftext|>


<commit_before>import React from 'react'

import BrowserProtocol from 'farce/lib/BrowserProtocol'

import createConnectedRouter from 'found/lib/createConnectedRouter'
import resolver from 'found/lib/resolver'
import { ScrollManager } from 'found-scroll'

import render from './render'

export function createRouterElement(renderArgs, getState) {
	const ConnectedRouter = createConnectedRouter({
		render: (renderArgs) => {
			const pageHasLoaded = !getState().preload.pending
			const nextLocation = renderArgs.location
			const previousLocation = getState().found.resolvedMatch.location
			const location = pageHasLoaded ? nextLocation : previousLocation
			const key = window.reactWebsiteRemountOnNavigate === false ? undefined : `${location.pathname}${location.search}`
			return (
				<ScrollManager renderArgs={renderArgs}>
					<Passthrough key={key}>
						{render(renderArgs)}
					</Passthrough>
				</ScrollManager>
			)
		}
	})
	return (
		<ConnectedRouter
			resolver={resolver}
			initialRenderArgs={renderArgs}/>
	)
}

export function createHistoryProtocol() {
	return new BrowserProtocol()
}

function Passthrough(props) {
	return props.children
}<commit_msg>Better re-mounting on navigation.<commit_after>import React from 'react'

import BrowserProtocol from 'farce/lib/BrowserProtocol'

import createConnectedRouter from 'found/lib/createConnectedRouter'
import resolver from 'found/lib/resolver'
import { ScrollManager } from 'found-scroll'

import render from './render'

export function createRouterElement(renderArgs, getState) {
	const ConnectedRouter = createConnectedRouter({
		render: (renderArgs) => {
			// Force re-mount the last `<Route/>` component on location path change.
			// https://github.com/4Catalyzer/found/issues/199#issuecomment-415616836
			const elements = renderArgs.elements
			if (elements && window.reactWebsiteRemountOnNavigate !== false) {
				elements[elements.length - 1] = React.cloneElement(elements[elements.length - 1], { key: renderArgs.location.pathname })
			}
			return (
				<ScrollManager renderArgs={renderArgs}>
					{render(renderArgs)}
				</ScrollManager>
			)
		}
	})
	return (
		<ConnectedRouter
			resolver={resolver}
			initialRenderArgs={renderArgs}/>
	)
}

export function createHistoryProtocol() {
	return new BrowserProtocol()
}<|endoftext|>


<commit_before>var hijackResponse = require('hijackresponse');

var HtmlParser = require('htmlparser2').Parser;

var RangeOmittingStream = require('./RangeOmittingStream');

module.exports = function (config) {
  config = config || {};

  var memoize = config.memoize;
  var previousResultByUrl = {};

  return function expressExtractHeaders(req, res, next) {
    var previousResult = previousResultByUrl[req.url];
    var isHead = req.method === 'HEAD';
    if (
      previousResult &&
      memoize &&
      (previousResult.omitRanges.length === 0 || isHead)
    ) {
      res.set(previousResult.headers);
      next();
    } else {
      if (isHead) {
        // Rewrite to GET so we can retrieve the response from the upstream middleware and
        // still get the correct previousHeaders:
        req.method = 'GET';
      }
      delete req.headers.range;
      delete req.headers['if-range'];

      hijackResponse(res, next).then(({ readable, writable }) => {
        if (
          previousResult &&
          previousResult.headers.etag &&
          previousResult.headers.etag === res.getHeader('ETag') &&
          (previousResult.omitRanges.length === 0 ||
            !/^W\//.test(previousResult.headers.etag))
        ) {
          res.set(previousResult.headers);
          if (previousResult.omitRanges.length > 0) {
            return readable
              .pipe(new RangeOmittingStream(previousResult.omitRanges))
              .pipe(writable);
          } else {
            return readable.pipe(writable);
          }
        }

        if (/^text\/html(?:;|\s|$)/i.test(res.getHeader('Content-Type'))) {
          var headers = {};
          var omitRanges = [];
          var stillParsing = true;
          var chunks = [];

          var stopParsingAndSendResponse = function () {
            if (stillParsing) {
              stillParsing = false;
              var contentLength = res.getHeader('Content-Length');
              if (typeof contentLength !== 'undefined') {
                var contentLengthAdjustment = 0;
                omitRanges.forEach(function (omitRange) {
                  contentLengthAdjustment += omitRange[1] - omitRange[0];
                });
                if (contentLengthAdjustment) {
                  headers['content-length'] = String(
                    parseInt(contentLength, 10) - contentLengthAdjustment
                  );
                }
              }
              res.set(headers);
              headers.etag = res.getHeader('ETag');
              previousResultByUrl[req.url] = {
                headers: headers,
                omitRanges: omitRanges,
              };
              if (omitRanges.length > 0) {
                var rangeOmittingStream = new RangeOmittingStream(omitRanges);
                rangeOmittingStream.pipe(writable);
                chunks.forEach(function (chunk) {
                  rangeOmittingStream.write(chunk);
                });
              } else {
                chunks.forEach(function (chunk) {
                  writable.write(chunk);
                });
              }
            }
          };

          var htmlParser = new HtmlParser({
            onopentag: function (name, attribs) {
              if (stillParsing) {
                if (name === 'meta') {
                  var httpEquiv = attribs['http-equiv'];
                  if (typeof httpEquiv === 'string') {
                    if (attribs.content) {
                      // Normalize whitespace, convert newlines to spaces so they'll work
                      // in an HTTP header:
                      headers[httpEquiv] = attribs.content
                        .replace(/\s/g, ' ')
                        .trim();
                    } else {
                      headers[httpEquiv] = '';
                    }
                    if (
                      /^(?:X-Frame-Options|Content-Security-Policy(?:-Report-Only)?)$/i.test(
                        httpEquiv
                      )
                    ) {
                      omitRanges.push([
                        htmlParser.startIndex,
                        htmlParser.endIndex + 1,
                      ]);
                    }
                  }
                } else if (name === 'link') {
                  var rel = attribs.rel;
                  var href = attribs.href;
                  var as = attribs.as;
                  var pr = attribs.pr;
                  var crossorigin = attribs.crossorigin;
                  if (
                    typeof href === 'string' &&
                    /^(?:preconnect|prefetch|prerender|preload|dns-prefetch)$/i.test(
                      rel
                    )
                  ) {
                    var linkHeaderValue = `<${href}>; rel=${rel}`;
                    if (as) {
                      linkHeaderValue += `; as=${as}`;
                    }
                    if (pr) {
                      linkHeaderValue += `; pr=${pr}`;
                    }
                    if (typeof crossorigin === 'string') {
                      linkHeaderValue += `; crossorigin${
                        crossorigin ? `=${crossorigin}` : ''
                      }`;
                    }
                    if (Array.isArray(headers.link)) {
                      headers.link.push(linkHeaderValue);
                    } else if (headers.link) {
                      headers.link = [headers.link, linkHeaderValue];
                    } else {
                      headers.link = linkHeaderValue;
                    }
                  }
                }
              }
            },
            onclosetag: function (name) {
              if (name === 'head') {
                stopParsingAndSendResponse();
              }
            },
          });

          readable
            .on('data', function (chunk) {
              if (stillParsing) {
                if (!isHead) {
                  chunks.push(chunk);
                }
                htmlParser.write(chunk);
              } else if (!isHead) {
                writable.write(chunk);
              }
            })
            .on('end', function () {
              stopParsingAndSendResponse();
              writable.end();
            });
        } else {
          readable.pipe(writable);
        }
      });
    }
  };
};
<commit_msg>Send strings rather than Buffer instances into htmlparser2<commit_after>var hijackResponse = require('hijackresponse');

var HtmlParser = require('htmlparser2').Parser;

var RangeOmittingStream = require('./RangeOmittingStream');

module.exports = function (config) {
  config = config || {};

  var memoize = config.memoize;
  var previousResultByUrl = {};

  return function expressExtractHeaders(req, res, next) {
    var previousResult = previousResultByUrl[req.url];
    var isHead = req.method === 'HEAD';
    if (
      previousResult &&
      memoize &&
      (previousResult.omitRanges.length === 0 || isHead)
    ) {
      res.set(previousResult.headers);
      next();
    } else {
      if (isHead) {
        // Rewrite to GET so we can retrieve the response from the upstream middleware and
        // still get the correct previousHeaders:
        req.method = 'GET';
      }
      delete req.headers.range;
      delete req.headers['if-range'];

      hijackResponse(res, next).then(({ readable, writable }) => {
        if (
          previousResult &&
          previousResult.headers.etag &&
          previousResult.headers.etag === res.getHeader('ETag') &&
          (previousResult.omitRanges.length === 0 ||
            !/^W\//.test(previousResult.headers.etag))
        ) {
          res.set(previousResult.headers);
          if (previousResult.omitRanges.length > 0) {
            return readable
              .pipe(new RangeOmittingStream(previousResult.omitRanges))
              .pipe(writable);
          } else {
            return readable.pipe(writable);
          }
        }

        if (/^text\/html(?:;|\s|$)/i.test(res.getHeader('Content-Type'))) {
          // https://github.com/fb55/htmlparser2/issues/991#issuecomment-950325704
          readable.setEncoding('utf-8');

          var headers = {};
          var omitRanges = [];
          var stillParsing = true;
          var chunks = [];

          var stopParsingAndSendResponse = function () {
            if (stillParsing) {
              stillParsing = false;
              var contentLength = res.getHeader('Content-Length');
              if (typeof contentLength !== 'undefined') {
                var contentLengthAdjustment = 0;
                omitRanges.forEach(function (omitRange) {
                  contentLengthAdjustment += omitRange[1] - omitRange[0];
                });
                if (contentLengthAdjustment) {
                  headers['content-length'] = String(
                    parseInt(contentLength, 10) - contentLengthAdjustment
                  );
                }
              }
              res.set(headers);
              headers.etag = res.getHeader('ETag');
              previousResultByUrl[req.url] = {
                headers: headers,
                omitRanges: omitRanges,
              };
              if (omitRanges.length > 0) {
                var rangeOmittingStream = new RangeOmittingStream(omitRanges);
                rangeOmittingStream.pipe(writable);
                chunks.forEach(function (chunk) {
                  rangeOmittingStream.write(chunk);
                });
              } else {
                chunks.forEach(function (chunk) {
                  writable.write(chunk);
                });
              }
            }
          };

          var htmlParser = new HtmlParser({
            onopentag: function (name, attribs) {
              if (stillParsing) {
                if (name === 'meta') {
                  var httpEquiv = attribs['http-equiv'];
                  if (typeof httpEquiv === 'string') {
                    if (attribs.content) {
                      // Normalize whitespace, convert newlines to spaces so they'll work
                      // in an HTTP header:
                      headers[httpEquiv] = attribs.content
                        .replace(/\s/g, ' ')
                        .trim();
                    } else {
                      headers[httpEquiv] = '';
                    }
                    if (
                      /^(?:X-Frame-Options|Content-Security-Policy(?:-Report-Only)?)$/i.test(
                        httpEquiv
                      )
                    ) {
                      omitRanges.push([
                        htmlParser.startIndex,
                        htmlParser.endIndex + 1,
                      ]);
                    }
                  }
                } else if (name === 'link') {
                  var rel = attribs.rel;
                  var href = attribs.href;
                  var as = attribs.as;
                  var pr = attribs.pr;
                  var crossorigin = attribs.crossorigin;
                  if (
                    typeof href === 'string' &&
                    /^(?:preconnect|prefetch|prerender|preload|dns-prefetch)$/i.test(
                      rel
                    )
                  ) {
                    var linkHeaderValue = `<${href}>; rel=${rel}`;
                    if (as) {
                      linkHeaderValue += `; as=${as}`;
                    }
                    if (pr) {
                      linkHeaderValue += `; pr=${pr}`;
                    }
                    if (typeof crossorigin === 'string') {
                      linkHeaderValue += `; crossorigin${
                        crossorigin ? `=${crossorigin}` : ''
                      }`;
                    }
                    if (Array.isArray(headers.link)) {
                      headers.link.push(linkHeaderValue);
                    } else if (headers.link) {
                      headers.link = [headers.link, linkHeaderValue];
                    } else {
                      headers.link = linkHeaderValue;
                    }
                  }
                }
              }
            },
            onclosetag: function (name) {
              if (name === 'head') {
                stopParsingAndSendResponse();
              }
            },
          });

          readable
            .on('data', function (chunk) {
              if (stillParsing) {
                if (!isHead) {
                  chunks.push(chunk);
                }
                htmlParser.write(chunk);
              } else if (!isHead) {
                writable.write(chunk);
              }
            })
            .on('end', function () {
              stopParsingAndSendResponse();
              writable.end();
            });
        } else {
          readable.pipe(writable);
        }
      });
    }
  };
};
<|endoftext|>


<commit_before>/*global process*/
var fs = require("fs");
var fromDir = process.argv[2];
var toDir = process.argv[3];

var linkMap = {
  "datepicker": "https://raw.githubusercontent.com/fengyuanchen/datepicker/master/dist/datepicker.min.js",
  "flyd": "https://unpkg.com/flyd@0.2.6/flyd.js",
  "immutable": "https://unpkg.com/immutable@3.8.2/dist/immutable.js",
  "jquery": "https://unpkg.com/jquery@3.3.1/dist/jquery.js",
  "lodash": "https://unpkg.com/lodash@4.17.5",
  "lodash-fp": "https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)",
  "meiosis": "https://unpkg.com/meiosis@1.4.1",
  "meiosis-tracer": "https://unpkg.com/meiosis-tracer@1.4.1",
  "mithril": "https://unpkg.com/mithril@1.1.6",
  "mithril-stream": "https://unpkg.com/mithril-stream@1.1.0",
  "patchinko": "https://unpkg.com/patchinko@3.2.1/overloaded.js",
  "ramda": "https://unpkg.com/ramda@0.25.0/dist/ramda.min.js",
  "react": "https://unpkg.com/react@16.3.1/umd/react.development.js",
  "react-dom": "https://unpkg.com/react-dom@16.3.1/umd/react-dom.development.js",
  "universal-router": "https://unpkg.com/universal-router@6.0.0/universal-router.min.js",
  "universal-router-generate-urls": "https://unpkg.com/universal-router@6.0.0/universal-router-generate-urls.min.js"
};

var filenames = fs.readdirSync(fromDir);

filenames.forEach(source => {
  var input = fs.readFileSync(fromDir + "/" + source, "ascii");
  var lines = input.split("\n");
  var flemNumber = 1;

  lines = lines.map(function(line) {
    if (line.startsWith("@flems")) {
      var parts = line.split(" ");

      var files = parts[1].split(",");
      var fileContents = files.map(longfilename => {
        var filename = null;
        var shortname = null;
        var asIndex = longfilename.indexOf("#as#");
        if (asIndex >= 0) {
          filename = longfilename.substring(0, asIndex);
          shortname = longfilename.substring(asIndex + 4);
        }
        else {
          filename = longfilename;
          shortname = longfilename.substring(longfilename.lastIndexOf("/") + 1);
        }
        var file = JSON.stringify(fs.readFileSync(filename, "ascii"));
        var compiler = "";
        if (shortname.endsWith("jsx")) {
          shortname = shortname.substring(0, shortname.length - 1);
        }
        if (shortname.endsWith("js")) {
          compiler = ", compiler: \"babel\"";
        }
        return `{name: "${shortname}", content: ${file}${compiler}}`;
      });
      var fileString = "[" + fileContents.join(",") + "]";

      var links = parts.length > 2 ? parts[2].split(",") : [];
      if (links.length === 1 && links[0] === "[]") {
        links = [];
      }
      var linkContents = links.map(link => {
        var url = linkMap[link];
        return `{name: "${link}", type: "js", url: "${url}"}`;
      });
      var linkString = "[" + linkContents.join(",") + "]";

      var style = "";
      if (parts.length > 3) {
        style = " style=\"height:" + parts[3] + "px\"";
      }
      var middle = "75";
      if (parts.length > 4) {
        middle = parts[4];
      }

      line = `

      `;

      flemNumber++;
    }
    return line;
  });

  var dest = toDir + "/" + source;
  fs.writeFileSync(dest, lines.join("\n"));
});
<commit_msg>Fix meiosis and tracer flems for Firefox.<commit_after>/*global process*/
var fs = require("fs");
var fromDir = process.argv[2];
var toDir = process.argv[3];

var linkMap = {
  "datepicker": "https://raw.githubusercontent.com/fengyuanchen/datepicker/master/dist/datepicker.min.js",
  "flyd": "https://unpkg.com/flyd@0.2.6/flyd.js",
  "immutable": "https://unpkg.com/immutable@3.8.2/dist/immutable.js",
  "jquery": "https://unpkg.com/jquery@3.3.1/dist/jquery.js",
  "lodash": "https://unpkg.com/lodash@4.17.5",
  "lodash-fp": "https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)",
  "meiosis": "https://unpkg.com/meiosis@1.4.1/dist/meiosis.js",
  "meiosis-tracer": "https://unpkg.com/meiosis-tracer@1.4.1/dist/meiosis-tracer.js",
  "mithril": "https://unpkg.com/mithril@1.1.6",
  "mithril-stream": "https://unpkg.com/mithril-stream@1.1.0",
  "patchinko": "https://unpkg.com/patchinko@3.2.1/overloaded.js",
  "ramda": "https://unpkg.com/ramda@0.25.0/dist/ramda.min.js",
  "react": "https://unpkg.com/react@16.3.1/umd/react.development.js",
  "react-dom": "https://unpkg.com/react-dom@16.3.1/umd/react-dom.development.js",
  "universal-router": "https://unpkg.com/universal-router@6.0.0/universal-router.min.js",
  "universal-router-generate-urls": "https://unpkg.com/universal-router@6.0.0/universal-router-generate-urls.min.js"
};

var filenames = fs.readdirSync(fromDir);

filenames.forEach(source => {
  var input = fs.readFileSync(fromDir + "/" + source, "ascii");
  var lines = input.split("\n");
  var flemNumber = 1;

  lines = lines.map(function(line) {
    if (line.startsWith("@flems")) {
      var parts = line.split(" ");

      var files = parts[1].split(",");
      var fileContents = files.map(longfilename => {
        var filename = null;
        var shortname = null;
        var asIndex = longfilename.indexOf("#as#");
        if (asIndex >= 0) {
          filename = longfilename.substring(0, asIndex);
          shortname = longfilename.substring(asIndex + 4);
        }
        else {
          filename = longfilename;
          shortname = longfilename.substring(longfilename.lastIndexOf("/") + 1);
        }
        var file = JSON.stringify(fs.readFileSync(filename, "ascii"));
        var compiler = "";
        if (shortname.endsWith("jsx")) {
          shortname = shortname.substring(0, shortname.length - 1);
        }
        if (shortname.endsWith("js")) {
          compiler = ", compiler: \"babel\"";
        }
        return `{name: "${shortname}", content: ${file}${compiler}}`;
      });
      var fileString = "[" + fileContents.join(",") + "]";

      var links = parts.length > 2 ? parts[2].split(",") : [];
      if (links.length === 1 && links[0] === "[]") {
        links = [];
      }
      var linkContents = links.map(link => {
        var url = linkMap[link];
        return `{name: "${link}", type: "js", url: "${url}"}`;
      });
      var linkString = "[" + linkContents.join(",") + "]";

      var style = "";
      if (parts.length > 3) {
        style = " style=\"height:" + parts[3] + "px\"";
      }
      var middle = "75";
      if (parts.length > 4) {
        middle = parts[4];
      }

      line = `

      `;

      flemNumber++;
    }
    return line;
  });

  var dest = toDir + "/" + source;
  fs.writeFileSync(dest, lines.join("\n"));
});
<|endoftext|>


<commit_before>function noop(){}
$(document).ready(function(){
  var scope = window.scope = angular.compile(document);
  scope.getJSON = function(url, callback) {
    var list = [];
    var self = this;
    self.set('status', 'fetching');
    $.getJSON(url, function(response){
      _(response).forEach(function(v,k){
        list[k] = v;
      });
      (callback||noop)(response);
      self.set('status', '');
      self.updateView();
    });
    return list;
  };

  function fetchTweets(username){
    return scope.getJSON(
        username ?
            "http://twitter.com/statuses/user_timeline/"+username+".json" :
            "http://twitter.com/statuses/home_timeline.json");
  }

  scope.set('fetchTweets', fetchTweets);
  scope.set('users', [
      {screen_name:'mhevery', name:'Mi\u0161ko Hevery', notes:'Author of <angular/>.',
        profile_image_url:'http://a3.twimg.com/profile_images/54360179/Me_-_Small_Banner_normal.jpg'},
      {screen_name:'abrons', name:'Adam Abrons', notes:'Author of <angular/> & Ruby guru.',
        profile_image_url:'http://a1.twimg.com/profile_images/533646480/PIC00024_normal.jpg'}
    ]);
  scope.watchUrl();
  scope.init();
});
<commit_msg>update image for adam<commit_after>function noop(){}
$(document).ready(function(){
  var scope = window.scope = angular.compile(document);
  scope.getJSON = function(url, callback) {
    var list = [];
    var self = this;
    self.set('status', 'fetching');
    $.getJSON(url, function(response){
      _(response).forEach(function(v,k){
        list[k] = v;
      });
      (callback||noop)(response);
      self.set('status', '');
      self.updateView();
    });
    return list;
  };

  function fetchTweets(username){
    return scope.getJSON(
        username ?
            "http://twitter.com/statuses/user_timeline/"+username+".json" :
            "http://twitter.com/statuses/home_timeline.json");
  }

  scope.set('fetchTweets', fetchTweets);
  scope.set('users', [
      {screen_name:'mhevery', name:'Mi\u0161ko Hevery', notes:'Author of <angular/>.',
        profile_image_url:'http://a3.twimg.com/profile_images/54360179/Me_-_Small_Banner_normal.jpg'},
      {screen_name:'abrons', name:'Adam Abrons', notes:'Author of <angular/> & Ruby guru.',
        profile_image_url:'http://media.linkedin.com/mpr/mpr/shrink_80_80/p/2/000/005/0a8/044278d.jpg'}
    ]);
  scope.watchUrl();
  scope.init();
});
<|endoftext|>


<commit_before>/* Msisp.js - by C. Desmarchelier - Nov.2017*/
mdefault = "index.md"   // variable à modifier pour préciser le fichier md affiché par défaut, chemin compris à partir du fichier index.html
basemd = "/" ;        // variable à modifier pour préciser le répertoire racine par défaut des fichiers md

titleinit = document.getElementsByTagName("TITLE")[0].innerText ;
baseinit = document.getElementsByTagName("BASE")[0].href ;
function ajax(meth,src,a,init) {
  var req = new XMLHttpRequest();
  req.open(meth, src, true);
  req.setRequestHeader("Content-type", "text/plain");
  req.onreadystatechange = function()
  {
    if (req.readyState == 4) {
      if (req.status == 200) {
        /*alert(marked(req.responseText));*/
        basemd = req.responseURL ;
		if (init != 1) {
		  window.history.replaceState( {} , '', "#!" + req.responseURL);
		}
		document.getElementById("main").innerHTML=marked(req.responseText);
		idx = -1;
		for (i = 0; i < 3; i++) {
          idx = req.responseURL.indexOf('/',idx+1);
        }
        file   = req.responseURL.substring(idx);
		folder = file.substring(0,file.lastIndexOf('/'));
		document.getElementById("folder").href = req.responseURL.substring(0,req.responseURL.lastIndexOf('/')) ;
		heads=document.getElementsByTagName("H1");
		if (heads.length == 0) heads=document.getElementsByTagName("H2");
		if (heads.length == 0) heads=document.getElementsByTagName("H3");
		if (heads.length == 0) heads=document.getElementsByTagName("H4");
		if (heads.length == 0) {
		  document.getElementsByTagName("TITLE")[0].innerText = document.getElementById("main").innerText.substring(0,30);
		} else {
		  document.getElementsByTagName("TITLE")[0].innerText = heads[0].innerText;
		}
		path = document.location.origin + document.location.pathname ;
		if (path.substring(0,path.lastIndexOf('/'))==req.responseURL.substring(0,req.responseURL.lastIndexOf('/'))) {
		    document.getElementById("dropdown").style.display = 'none';
        } else {
		    document.getElementById("dropdown").style.display = 'inline-block';
		}
      } else {
        alert("Erreur http "+req.status);
      }
    }
  }
  req.send(JSON.stringify(a));
}
function init() {
  doc=document.location.hash;
  if (doc.slice(-1)=="/") doc=doc+"index.md";
  if (doc.length < 3) {
    ajax("GET",mdefault,"",1);
  } else  if (doc.substring(0,2) == '#!') {
    document.getElementsByTagName("BASE")[0].href = basemd ;
    ajax("GET",doc.substring(2),"",0);
    document.getElementsByTagName("BASE")[0].href = baseinit ;
  }
}
<commit_msg>Update mdisp.js<commit_after>/* Msisp.js - by C. Desmarchelier - Nov.2017*/
mdefault = "index.md"   // variable à modifier pour préciser le fichier md affiché par défaut, chemin compris à partir du fichier index.html
basemd = "." ;        // variable à modifier pour préciser le répertoire racine par défaut des fichiers md

titleinit = document.getElementsByTagName("TITLE")[0].innerText ;
baseinit = document.getElementsByTagName("BASE")[0].href ;
function ajax(meth,src,a,init) {
  var req = new XMLHttpRequest();
  req.open(meth, src, true);
  req.setRequestHeader("Content-type", "text/plain");
  req.onreadystatechange = function()
  {
    if (req.readyState == 4) {
      if (req.status == 200) {
        /*alert(marked(req.responseText));*/
        basemd = req.responseURL ;
		if (init != 1) {
		  window.history.replaceState( {} , '', "#!" + req.responseURL);
		}
		document.getElementById("main").innerHTML=marked(req.responseText);
		idx = -1;
		for (i = 0; i < 3; i++) {
          idx = req.responseURL.indexOf('/',idx+1);
        }
        file   = req.responseURL.substring(idx);
		folder = file.substring(0,file.lastIndexOf('/'));
		document.getElementById("folder").href = req.responseURL.substring(0,req.responseURL.lastIndexOf('/')) ;
		heads=document.getElementsByTagName("H1");
		if (heads.length == 0) heads=document.getElementsByTagName("H2");
		if (heads.length == 0) heads=document.getElementsByTagName("H3");
		if (heads.length == 0) heads=document.getElementsByTagName("H4");
		if (heads.length == 0) {
		  document.getElementsByTagName("TITLE")[0].innerText = document.getElementById("main").innerText.substring(0,30);
		} else {
		  document.getElementsByTagName("TITLE")[0].innerText = heads[0].innerText;
		}
		path = document.location.origin + document.location.pathname ;
		if (path.substring(0,path.lastIndexOf('/'))==req.responseURL.substring(0,req.responseURL.lastIndexOf('/'))) {
		    document.getElementById("dropdown").style.display = 'none';
        } else {
		    document.getElementById("dropdown").style.display = 'inline-block';
		}
      } else {
        alert("Erreur http "+req.status);
      }
    }
  }
  req.send(JSON.stringify(a));
}
function init() {
  doc=document.location.hash;
  if (doc.slice(-1)=="/") doc=doc+"index.md";
  if (doc.length < 3) {
    ajax("GET",mdefault,"",1);
  } else  if (doc.substring(0,2) == '#!') {
    document.getElementsByTagName("BASE")[0].href = basemd ;
    ajax("GET",doc.substring(2),"",0);
    document.getElementsByTagName("BASE")[0].href = baseinit ;
  }
}
<|endoftext|>


<commit_before>given("there are no export jobs pending", () => {
  cy.server();

  //login
  cy.fixture('admin').as("user");
  cy.get('@user').then((userData) => {
    cy.getToken(userData.username, userData.password)
      .then((token) => {
        // get job list
        cy.request({
          'url': Cypress.env('apiUrl') + '/v2/export/jobs',
          'method': 'GET',
          'auth': {'bearer': token}
        }).then((queriesResponce) => {
          queriesResponce.body["exportJobs"].map(x => x["id"]).forEach(x => {
            cy.request({
              'url': Cypress.env('apiUrl') + '/v2/export/' + x,
              'method': 'DELETE',
              'auth': {'bearer': token}
            });
          })
        });

      })
  });
});

when('I select all data', () => {
  cy.get('.gb-nav').contains('Export').click();
  cy.get('.checkAllText').find(".ui-chkbox-box").click()
});

when('I export this data with the name {string}', (jobName) => {
  cy.get('#exportJobNameInput').type(jobName);
  cy.contains('Create export').click();
});

then('then the job {string} has status {string}', (jobName, status) => {
  cy.get('.ui-datatable-even').contains(jobName).parent().parent().find('td').eq(1).contains(status);
});
<commit_msg>Make export assertion more reliable<commit_after>given("there are no export jobs pending", () => {
  cy.server();

  //login
  cy.fixture('admin').as("user");
  cy.get('@user').then((userData) => {
    cy.getToken(userData.username, userData.password)
      .then((token) => {
        // get job list
        cy.request({
          'url': Cypress.env('apiUrl') + '/v2/export/jobs',
          'method': 'GET',
          'auth': {'bearer': token}
        }).then((queriesResponce) => {
          queriesResponce.body["exportJobs"].map(x => x["id"]).forEach(x => {
            cy.request({
              'url': Cypress.env('apiUrl') + '/v2/export/' + x,
              'method': 'DELETE',
              'auth': {'bearer': token}
            });
          })
        });

      })
  });
});

when('I select all data', () => {
  cy.get('.gb-nav').contains('Export').click();
  cy.get('.checkAllText').find(".ui-chkbox-box").click()
});

when('I export this data with the name {string}', (jobName) => {
  cy.get('#exportJobNameInput').type(jobName);
  cy.contains('Create export').click();
});

then('then the job {string} has status {string}', (jobName, status) => {
  cy.get('tr.ui-datatable-even').should('contain', jobName).and('contain', status);
});
<|endoftext|>


<commit_before>/**  veneer.js custom html tag definition
 {
	tagName: 'veneer-mustache',
	version: '1.0.0', tags: 'text template',
	purpose: 'Turns a mustache template (inside) to a fancy html view by calling render() with some data',
	attribs: {
		url: 'a jsonp URL calling the element.render method to update the template',
		src: 'the URL location of a standard JSON resource to update the templated data',
		object: 'the JS window path of an existing object to render the template with',
		target: 'renders the template content to another tag, chosen by this CSS selector',
		interval: '# of seconds after which to auto-re-render or reload external content',
		static: 'if present, tag will never update after first render, and wont respond to interval to save RAM/CPU'
	},
	externals: ['//js.zapjs.com/js/zap.plugin.mustache.js'],
	methods: ['render(objData) - updates the html by apply the tags mustache template to the data'],
	events:  [ 'insert', 'update' ]
 }
**/

//////////////////////////////////////////////
(function(){

// mostache, mo'mustache 8.2a (mustache 8.1 fork )
;(function(A,h){"object"==typeof exports&&exports?h(exports):"function"==typeof define&&define.amd?define(["exports"],h):h(A.Mustache={}),h.global=A})(this,function mostache(h){function D(a,c){return c.split(/[\.,]/).reduce(function(b,a){return b&&b[a]},a)}function v(a){return"function"==typeof a}function x(a){return a.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function E(a,c){function b(a){"string"==typeof a&&(a=a.split(F,2));if(!y(a)||2!==a.length)throw Error("Invalid tags: "+a);d=new RegExp(x(a[0])+"\\s*"),r=new RegExp("\\s*"+x(a[1])),B=new RegExp("\\s*"+x("}"+a[1]))}if(!a)return[];var f=[],e=[],w=[],m=!1,l=!1,d,r,B;b(c||h.tags);for(var g=new u(a),p,k,n,t;!g.eos();){p=g.pos;if(n=g.scanUntil(d)){t=0;for(var q=n.length;t<q;++t)if(k=n.charAt(t),G.call(H,k)?l=!0:w.push(e.length),e.push(["text",k,p,p+1]),p+=1,"\n"===k){if(m&&!l)for(;w.length;)delete e[w.pop()];else w=[];l=m=!1}}if(!g.scan(d))break;m=!0,k=g.scan(I)||"name",g.scan(J),"="===k?(n=g.scanUntil(C),g.scan(C),g.scanUntil(r)):"{"===k?(n=g.scanUntil(B),g.scan(K),g.scanUntil(r),k="&"):n=g.scanUntil(r);if(!g.scan(r))throw Error("Unclosed tag at "+g.pos);t=[k,n,p,g.pos],e.push(t);if("#"===k||"^"===k)f.push(t);else if("/"===k){k=f.pop();if(!k)throw Error('Unopened section "'+n+'" at '+p);if(k[1]!==n)throw Error('Unclosed section "'+k[1]+'" at '+p)}else"name"===k||"{"===k||"&"===k?l=!0:"="===k&&b(n)}if(k=f.pop())throw Error('Unclosed section "'+k[1]+'" at '+g.pos);return L(M(e))}function M(a){for(var c=[],b,f,e=0,h=a.length;e<h;++e)(b=a[e])&&("text"===b[0]&&f&&"text"===f[0]?(f[1]+=b[1],f[3]=b[3]):(c.push(b),f=b));return c}function L(a){for(var c=[],b=c,f=[],e,h=0,m=a.length;h<m;++h)switch(e=a[h],e[0]){case"#":case"^":b.push(e),f.push(e),b=e[4]=[];break;case"/":b=f.pop(),b[5]=e[2],b=0<f.length?f[f.length-1][4]:c;break;default:b.push(e)}return c}function u(a){this.tail=this.string=a,this.pos=0}function q(a,c){this.view=null==a?{}:a,this.cache={".":this.view},this.parent=c}function s(){this.cache={}}var N=Object.prototype.toString,y=Array.isArray||function(a){return"[object Array]"===N.call(a)},G=RegExp.prototype.test,H=/\S/,O={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"},J=/\s*/,F=/\s+/,C=/\s*=/,K=/\s*\}/,I=/#|\^|\/|>|\{|&|=|!/;u.prototype.eos=function(){return""===this.tail},u.prototype.scan=function(a){return a=this.tail.match(a),!a||0!==a.index?"":(a=a[0],this.tail=this.tail.substring(a.length),this.pos+=a.length,a)},u.prototype.scanUntil=function(a){a=this.tail.search(a);var c;switch(a){case-1:c=this.tail,this.tail="";break;case 0:c="";break;default:c=this.tail.substring(0,a),this.tail=this.tail.substring(a)}return this.pos+=c.length,c},q.prototype.push=function(a){return new q(a,this)},q.prototype.lookup=function(a){var c=this.cache,b,f,e=[],h;-1!==a.indexOf("|")&&(f=a.trim().split(/\s*\|\s*/).map(function(a,b){return"."===a.slice(0,1)&&(e[b-1]=!0,a=a.slice(1)),a}),a=f.shift());if(a in c)b=c[a];else{for(var m=this,l,d;m;){if(0<a.indexOf("."))for(b=m.view,l=a.split("."),d=0;null!=b&&d<l.length;)h=b,b=b[l[d++]];else b=m.view[a];if(null!=b)break;m=m.parent}c[a]=b}return f&&f.forEach(function(c,f){var g=c.split("(");c=g.shift(),g.length&&(g=g[0].trim().split(")")[0].trim().split(/\s*\,\s*/).map(function(a){try{return JSON.parse(a)}catch(b){return a}}));var d=D(e[f]?void 0===b?a:b:mostache.global,c);if("function"==typeof d){void 0===b&&(b=a);try{if(e[f])g.length?b=d.apply(b,g):b=d.call(b);else if(g.length)switch(g.length){case 1:return b=d(b,g[0]);case 2:return b=d(b,g[0],g[1]);case 3:return b=d(b,g[0],g[1],g[2]);default:return d.apply(this,[b].concat(g))}else b=d(b)}catch(h){}}}),v(b)&&(-1!==String(b).indexOf("[native code]")&&h?b=b.call(h):b=b.call(this.view)),b},s.prototype.clearCache=function(){this.cache={}},s.prototype.parse=function(a,c){var b=this.cache,f=b[a];return null==f&&(f=b[a]=E(a,c)),f},s.prototype.render=function(a,c,b){var f=this.parse(a);return c=c instanceof q?c:new q(c),this.renderTokens(f,c,b,a)},s.prototype.renderTokens=function(a,c,b,f,e){function q(a){return m.render(a,c,b)}e="";for(var m=this,l,d,r="$1",s=/\{SEP\}([\w\W]+?)\{\/SEP\}/g,g=0,p=a.length;g<p;++g)switch(l=a[g],l[0]){case"#":d=c.lookup(l[1]);if(!d)continue;if(y(d))for(var k=0,n=d.length;k<n;++k)r=n-1===k?"":"$1",e+=this.renderTokens(l[4],c.push(d[k]),b,f).replace(/\{INDEX\}/g,k+1).replace(s,r);else if("object"==typeof d||"string"==typeof d)e+=this.renderTokens(l[4],c.push(d),b,f).replace(s,r);else if(v(d)){if("string"!=typeof f)throw Error("Cannot use higher-order sections without the original template");d=d.call(c.view,f.slice(l[3],l[5]),q),null!=d&&(e+=d)}else e+=this.renderTokens(l[4],c,b,f);break;case"^":d=c.lookup(l[1]);if(!d||y(d)&&0===d.length)e+=this.renderTokens(l[4],c,b,f);break;case">":if(!b)continue;d=v(b)?b(l[1]):b[l[1]],null!=d&&(e+=this.renderTokens(this.parse(d),c,b,d));break;case"&":d=c.lookup(l[1]),null!=d&&(e+=d);break;case"name":d=c.lookup(l[1]),null!=d&&(e+=h.escape(d));break;case"text":e+=l[1]}return e},h.name="mustache.js",h.version="0.8.1mo",h.tags=["{{","}}"];var z=new s;h.clearCache=function(){return z.clearCache()},h.parse=function(a,c){return z.parse(a,c)},h.render=function(a,c,b){return z.render(a,c,b)},h.to_html=function(a,c,b,f){a=h.render(a,c,b);if(!v(f))return a;f(a)},h.escape=function(a){return String(a).replace(/[&<>"'\/]/g,function(a){return O[a]})},h.Scanner=u,h.Context=q,h.Writer=s});

 veneer("veneer-mustache", {
	events: {
	insert: function(e){
		var elm=e.target;

		if(elm.parentNode && elm.parentNode.tagName.match(/^BS\-/i)){ return; } //defer bs widget loading, it will be re-appending in a moment

		if(!elm._temp){
			var x;
			if((x=veneer.$("template, [type*='template']", elm))[0]){

				function getParents(elm){
				  var r=[elm];
				  while(elm=elm.parentNode) r.push(elm);
				  return r;
				}

				var x3=x.slice(0);

				x=x.filter(function(a){
				   var p=getParents(a),
				   ok=false;
					p.some(function(aa){
					   if(aa && aa.tagName && aa.tagName.toLowerCase()=="veneer-mustache"){
							if(aa===elm){ return ok=true;} // next up mustache tag is elm, use this template
							return true;// next up mustache tag is not elm, skip this template
						}
					});
				   return ok;
				});

				elm._temp=(x[0]||elm).innerHTML;
			}else{
				elm._temp=elm.innerHTML;
			}
		}

		elm.updateObject=function(){
			try{ elm._data=Function("return 0||"+elm.object)(); }catch(y){}
		};

		elm.render=function(data){
			if(!data){
				if(elm.object && !elm._data ){
					data=elm._data;
				}else{
					data=elm._data || {};
				}
			}
			elm._data=data;
			elm.change();
		};

		elm.append=function(data, blnPre){
			if(!data || !elm._temp){
				return false;
			}

			var t=veneer.elm("div", {}, Mustache.to_html(elm._temp.replace(/@src=/g,"src=").trim()+" ", data));
			var targ=elm.target && veneer.$(elm.target)[0] || elm;
			if(blnPre===true){
				veneer._(t.children).forEach(function(a){targ.insertBefore(a, targ.firstChild);});
			}else{
				veneer._(t.children).forEach(targ.appendChild.bind(targ));
			}
			elm.change();
		};

		elm.prepend=function(data){
			elm.append(data, true);
		};

		function doRender(){
			if(elm.url)veneer.include(elm.url);
			if(elm.src)veneer.ajax(elm.src, function(e){ elm.render(elm._data=JSON.parse(e)); });
			if(elm._data)elm.render(elm._data);
		}//end dorender

		if(elm.interval){ elm._timer=setInterval(doRender, elm.interval * 1000 ); }
		if(elm.object && !elm.data) elm.updateObject();
		doRender();
	},

	update: function upd(e){
		var elm=e.target;
		elm._data=elm._data||"";

		if(elm.object){
			elm.updateObject();
		}

		var targ=elm.target && veneer.$(elm.target)[0] || elm;

		if(elm._data){
			var b1=elm._last, b2=Mustache.to_html(elm._temp.replace(/@src=/g,"src="), elm._data);
			if(b1!=b2){elm._last=targ.innerHTML=b2;}
		}

		veneer.$("script", targ).forEach(function(script){
			if(script.src){
				veneer.include(script.src);
			}else{
				try{Function("e", script.textContent).call(window, e);}catch(y){}
			}
		});

		if(elm.onchange  )	elm.onchange(e);
		if(elm.oninput )	elm.oninput();

		if(elm.static){
			elm.interval=elm.object=elm.src=elm.url=elm._data=elm._temp=elm._last="";
			clearInterval(elm._timer);
		}

	}
	},
	props: {
		url: veneer.k,
		src: veneer.k,
		object: veneer.k,
		target: veneer.k,
		"static": veneer.bool,
		interval: Number
	},
	css: "veneer-mustache {  } "
  });

 }());<commit_msg>added doc, added tag attribs, fixed minor bugs on subscribed objects<commit_after>/**  veneer.js custom html tag definition
 {
	tagName: 'veneer-mustache',
	version: '1.0.6', tags: 'text template',
	purpose: 'Turns a mustache template (inside) to a fancy html view by calling render() with some data',
	attribs: {
		url: 'a jsonp URL calling the element.render method to update the template',
		src: 'the URL location of a standard JSON resource to update the templated data',
		object: 'the JS window path of an existing object to render the template with',
		target: 'renders the template content to another tag, chosen by this CSS selector',
		interval: '# of seconds after which to auto-re-render or reload external content',
		static: 'if present, tag will never update after first render, and wont respond to interval to save RAM/CPU',
		tag: 'the name of a temp tag to use when parsing mustache output, normally div, but alllows tbody for generating TR tags'
	},
	externals: ['//js.zapjs.com/js/zap.plugin.mustache.js'],
	methods: {
		render:'(objData) - updates the html by apply the tags mustache template to the data',
		prepend:'(opt_objData) - runs the template and prepends the result to the target',
		apppend:'(opt_objData) - runs the template and appends the result to the target'
		},
	events:  [ 'insert', 'update' ]
 }
**/

//////////////////////////////////////////////
(function(){

// mostache, mo'mustache 8.2a (mustache 8.1 fork )
;(function(A,h){"object"==typeof exports&&exports?h(exports):"function"==typeof define&&define.amd?define(["exports"],h):h(A.Mustache={}),h.global=A})(this,function mostache(h){function D(a,c){return c.split(/[\.,]/).reduce(function(b,a){return b&&b[a]},a)}function v(a){return"function"==typeof a}function x(a){return a.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function E(a,c){function b(a){"string"==typeof a&&(a=a.split(F,2));if(!y(a)||2!==a.length)throw Error("Invalid tags: "+a);d=new RegExp(x(a[0])+"\\s*"),r=new RegExp("\\s*"+x(a[1])),B=new RegExp("\\s*"+x("}"+a[1]))}if(!a)return[];var f=[],e=[],w=[],m=!1,l=!1,d,r,B;b(c||h.tags);for(var g=new u(a),p,k,n,t;!g.eos();){p=g.pos;if(n=g.scanUntil(d)){t=0;for(var q=n.length;t<q;++t)if(k=n.charAt(t),G.call(H,k)?l=!0:w.push(e.length),e.push(["text",k,p,p+1]),p+=1,"\n"===k){if(m&&!l)for(;w.length;)delete e[w.pop()];else w=[];l=m=!1}}if(!g.scan(d))break;m=!0,k=g.scan(I)||"name",g.scan(J),"="===k?(n=g.scanUntil(C),g.scan(C),g.scanUntil(r)):"{"===k?(n=g.scanUntil(B),g.scan(K),g.scanUntil(r),k="&"):n=g.scanUntil(r);if(!g.scan(r))throw Error("Unclosed tag at "+g.pos);t=[k,n,p,g.pos],e.push(t);if("#"===k||"^"===k)f.push(t);else if("/"===k){k=f.pop();if(!k)throw Error('Unopened section "'+n+'" at '+p);if(k[1]!==n)throw Error('Unclosed section "'+k[1]+'" at '+p)}else"name"===k||"{"===k||"&"===k?l=!0:"="===k&&b(n)}if(k=f.pop())throw Error('Unclosed section "'+k[1]+'" at '+g.pos);return L(M(e))}function M(a){for(var c=[],b,f,e=0,h=a.length;e<h;++e)(b=a[e])&&("text"===b[0]&&f&&"text"===f[0]?(f[1]+=b[1],f[3]=b[3]):(c.push(b),f=b));return c}function L(a){for(var c=[],b=c,f=[],e,h=0,m=a.length;h<m;++h)switch(e=a[h],e[0]){case"#":case"^":b.push(e),f.push(e),b=e[4]=[];break;case"/":b=f.pop(),b[5]=e[2],b=0<f.length?f[f.length-1][4]:c;break;default:b.push(e)}return c}function u(a){this.tail=this.string=a,this.pos=0}function q(a,c){this.view=null==a?{}:a,this.cache={".":this.view},this.parent=c}function s(){this.cache={}}var N=Object.prototype.toString,y=Array.isArray||function(a){return"[object Array]"===N.call(a)},G=RegExp.prototype.test,H=/\S/,O={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"},J=/\s*/,F=/\s+/,C=/\s*=/,K=/\s*\}/,I=/#|\^|\/|>|\{|&|=|!/;u.prototype.eos=function(){return""===this.tail},u.prototype.scan=function(a){return a=this.tail.match(a),!a||0!==a.index?"":(a=a[0],this.tail=this.tail.substring(a.length),this.pos+=a.length,a)},u.prototype.scanUntil=function(a){a=this.tail.search(a);var c;switch(a){case-1:c=this.tail,this.tail="";break;case 0:c="";break;default:c=this.tail.substring(0,a),this.tail=this.tail.substring(a)}return this.pos+=c.length,c},q.prototype.push=function(a){return new q(a,this)},q.prototype.lookup=function(a){var c=this.cache,b,f,e=[],h;-1!==a.indexOf("|")&&(f=a.trim().split(/\s*\|\s*/).map(function(a,b){return"."===a.slice(0,1)&&(e[b-1]=!0,a=a.slice(1)),a}),a=f.shift());if(a in c)b=c[a];else{for(var m=this,l,d;m;){if(0<a.indexOf("."))for(b=m.view,l=a.split("."),d=0;null!=b&&d<l.length;)h=b,b=b[l[d++]];else b=m.view[a];if(null!=b)break;m=m.parent}c[a]=b}return f&&f.forEach(function(c,f){var g=c.split("(");c=g.shift(),g.length&&(g=g[0].trim().split(")")[0].trim().split(/\s*\,\s*/).map(function(a){try{return JSON.parse(a)}catch(b){return a}}));var d=D(e[f]?void 0===b?a:b:mostache.global,c);if("function"==typeof d){void 0===b&&(b=a);try{if(e[f])g.length?b=d.apply(b,g):b=d.call(b);else if(g.length)switch(g.length){case 1:return b=d(b,g[0]);case 2:return b=d(b,g[0],g[1]);case 3:return b=d(b,g[0],g[1],g[2]);default:return d.apply(this,[b].concat(g))}else b=d(b)}catch(h){}}}),v(b)&&(-1!==String(b).indexOf("[native code]")&&h?b=b.call(h):b=b.call(this.view)),b},s.prototype.clearCache=function(){this.cache={}},s.prototype.parse=function(a,c){var b=this.cache,f=b[a];return null==f&&(f=b[a]=E(a,c)),f},s.prototype.render=function(a,c,b){var f=this.parse(a);return c=c instanceof q?c:new q(c),this.renderTokens(f,c,b,a)},s.prototype.renderTokens=function(a,c,b,f,e){function q(a){return m.render(a,c,b)}e="";for(var m=this,l,d,r="$1",s=/\{SEP\}([\w\W]+?)\{\/SEP\}/g,g=0,p=a.length;g<p;++g)switch(l=a[g],l[0]){case"#":d=c.lookup(l[1]);if(!d)continue;if(y(d))for(var k=0,n=d.length;k<n;++k)r=n-1===k?"":"$1",e+=this.renderTokens(l[4],c.push(d[k]),b,f).replace(/\{INDEX\}/g,k+1).replace(s,r);else if("object"==typeof d||"string"==typeof d)e+=this.renderTokens(l[4],c.push(d),b,f).replace(s,r);else if(v(d)){if("string"!=typeof f)throw Error("Cannot use higher-order sections without the original template");d=d.call(c.view,f.slice(l[3],l[5]),q),null!=d&&(e+=d)}else e+=this.renderTokens(l[4],c,b,f);break;case"^":d=c.lookup(l[1]);if(!d||y(d)&&0===d.length)e+=this.renderTokens(l[4],c,b,f);break;case">":if(!b)continue;d=v(b)?b(l[1]):b[l[1]],null!=d&&(e+=this.renderTokens(this.parse(d),c,b,d));break;case"&":d=c.lookup(l[1]),null!=d&&(e+=d);break;case"name":d=c.lookup(l[1]),null!=d&&(e+=h.escape(d));break;case"text":e+=l[1]}return e},h.name="mustache.js",h.version="0.8.1mo",h.tags=["{{","}}"];var z=new s;h.clearCache=function(){return z.clearCache()},h.parse=function(a,c){return z.parse(a,c)},h.render=function(a,c,b){return z.render(a,c,b)},h.to_html=function(a,c,b,f){a=h.render(a,c,b);if(!v(f))return a;f(a)},h.escape=function(a){return String(a).replace(/[&<>"'\/]/g,function(a){return O[a]})},h.Scanner=u,h.Context=q,h.Writer=s});

 veneer("veneer-mustache", {
	events: {
	insert: function(e){
		var elm=e.target;

		if(elm.parentNode && elm.parentNode.tagName.match(/^BS\-/i)){ return; } //defer bs widget loading, it will be re-appending in a moment

		elm.updateObject=function(){
			try{ elm._data=Function("return 0||"+elm.object)(); }catch(y){}
		};

		if(!elm._temp){
			var x;
			if((x=veneer.$("template, [type*='template']", elm))[0]){

				function getParents(elm){
				  var r=[elm];
				  while(elm=elm.parentNode) r.push(elm);
				  return r;
				}

				var x3=x.slice(0);

				x=x.filter(function(a){
				   var p=getParents(a),
				   ok=false;
					p.some(function(aa){
					   if(aa && aa.tagName && aa.tagName.toLowerCase()=="veneer-mustache"){
							if(aa===elm){ return ok=true;} // next up mustache tag is elm, use this template
							return true;// next up mustache tag is not elm, skip this template
						}
					});
				   return ok;
				});

				elm._temp=(x[0]||elm).innerHTML;
			}else{
				elm._temp=elm.innerHTML;
			}
		}

		elm.render=function(data){
			if(!data){
				if(elm.object && !elm._data ){
					data=elm._data;
				}else{
					data=elm._data || {};
				}
			}
			elm._data=data;
			elm.change();
		};

		elm.append=function(data, blnPre){

			if(!data){
				if(elm.object && elm.updateObject) elm.updateObject();
				if(elm._data) data=elm._data;
			}

			if(!data || !elm._temp){
				return false;
			}

			var t=veneer.elm(elm.tag||"div", {}, Mustache.to_html(elm._temp.replace(/@src=/g,"src=").trim()+" ", data));
			var targ=elm.target && veneer.$(elm.target)[0] || elm;
			if(blnPre===true){
				veneer._(t.children).forEach(function(a){targ.insertBefore(a, targ.firstChild);});
			}else{
				veneer._(t.children).forEach(targ.appendChild.bind(targ));
			}
			elm.change();
		};

		elm.prepend=function(data){
			elm.append(data, true);
		};

		function doRender(){
			if(elm.url)veneer.include(elm.url);
			if(elm.src)veneer.ajax(elm.src, function(e){ elm.render(elm._data=JSON.parse(e)); });
			if(elm._data)elm.render(elm._data);
		}//end dorender

		if(elm.interval){ elm._timer=setInterval(doRender, elm.interval * 1000 ); }
		if(elm.object && !elm.data) elm.updateObject();
		doRender();
	},

	update: function upd(e){
		var elm=e.target;
		elm._data=elm._data||"";

		if(elm.object && elm.updateObject){
			elm.updateObject();
		}

		var targ=elm.target && veneer.$(elm.target)[0] || elm;

		if(elm._data){
			var b1=elm._last, b2=Mustache.to_html(elm._temp.replace(/@src=/g,"src="), elm._data);
			if(b1!=b2){elm._last=targ.innerHTML=b2;}
		}

		veneer.$("script", targ).forEach(function(script){
			if(script.src){
				veneer.include(script.src);
			}else{
				try{Function("e", script.textContent).call(window, e);}catch(y){}
			}
		});

		if(elm.onchange  )	elm.onchange(e);
		if(elm.oninput )	elm.oninput();

		if(elm.static){
			elm.interval=elm.object=elm.src=elm.url=elm._data=elm._temp=elm._last="";
			clearInterval(elm._timer);
		}

	}
	},
	props: {
		url: veneer.k,
		src: veneer.k,
		object: veneer.k,
		target: veneer.k,
		"static": veneer.bool,
		interval: Number,
		tag: veneer.k
	},
	css: "veneer-mustache {  } "
  });

 }());<|endoftext|>


<commit_before>import * as _ from 'lodash';

import { Jar } from 'jvm';
import { Pipeline } from '../src/Pipeline';
import { ClassVisitor } from '../src/ClassVisitor';
import { Flags } from 'jvm/lib/core/jvm/AccessFlags';

let isVisibleToChildren = (member) => {
  return Flags.isPublic(member.accessFlags) || Flags.isProtected(member.accessFlags);
}

let parentHasVisibleField = (jar, cls, name, desc) => {
  if ( ! _.has(jar, cls.superName)) {
    return false;
  }

  let field = _.find(jar[cls.superName].fields, { name, desc });
  return !! field && isVisibleToChildren(field);
}

class FieldVisitor extends ClassVisitor {
  constructor(jar) {
    super();
    this.jar = jar;
    this.visited = new Set;
  }

  get count() {
    return this.visited.size;
  }

  recordField(cls, field) {
    this.visited.add([cls.name, field.name, field.desc].join(':'));
  }

  toArray() {
    return [...this.visited];
  }
}

class DeclaredFieldVisitor extends FieldVisitor {
  constructor(jar) {
    super(jar);
    this.on('visit-start', (cls) => this.visitInheritedFields(cls));
    this.on('visit-field', (cls, field) => this.recordField(cls, field));
  }

  visitInheritedFields(cls) {
    let parent = this.jar[cls.superName];
    while (parent) {
      parent.fields
        .filter(isVisibleToChildren)
        .forEach(field => this.recordField(parent, field));

      parent = this.jar[parent.superName];
    }
  }
}

class ReferencedFieldVisitor extends FieldVisitor {
  constructor(jar) {
    super(jar);
    this.on('visit-method', (cls, method) => this.visitMethodInstructions(method.instructions));
  }

  visitFieldInstruction(insn) {
    let cls = this.jar[insn.owner];
    let fieldStruct = { name: insn.name, desc: insn.desc };
    this.recordField(cls, fieldStruct);

    let parent = this.jar[cls.superName];
    while (parent) {
      let field = _.find(parent.fields, fieldStruct);
      if ( ! field || ! isVisibleToChildren(field)) {
        break;
      }

      this.recordField(parent, field);

      parent = this.jar[parent.superName];
    }
  }

  visitMethodInstructions(instructions) {
    instructions
      .filter(insn => insn.constructor.name === 'FieldInstruction' && insn.owner in this.jar)
      .forEach(insn => this.visitFieldInstruction(insn));
  }
}

let createFieldUsagePipeline = () => {
  let pipeline = new Pipeline;

  // analysis/transformation steps

  pipeline.addStep('identification', (jar) => {
    let declaredFields = new DeclaredFieldVisitor(jar);
    let referencedFields = new ReferencedFieldVisitor(jar);

    _.values(jar).forEach(cls => {
      declaredFields.accept(cls);
      referencedFields.accept(cls);
    });

    return {
      declared: declaredFields.count,
      referenced: referencedFields.count,
      unreferenced: _.difference(declaredFields.toArray(), referencedFields.toArray())
    };
  });

  pipeline.addStep('transformation', (jar) => {
    pipeline
      .stepResult('identification')
      .unreferenced
      .forEach(key => {
        let [clazz, name, desc] = key.split(':');
        let cls = jar[clazz];
        let field = _.find(cls.fields, { name, desc });
        _.remove(cls.fields, field);
      });
  });

  // output

  pipeline.afterStep('identification', (step, elapsed) => {
    console.log('Fields declared but not referenced: %s.', step.unreferenced.length);
    console.log('Fields referenced: %s/%s', step.referenced, step.declared);
  });

  pipeline.afterStep('transformation', (step, elapsed) => {
    console.log('Removed fields from classes in %ss', elapsed);
  });

  pipeline.after(elapsed => console.log('Unused Field Pipeline completed in %ss', elapsed));

  return pipeline;
}

Jar.unpack(process.argv[2])
  .then(jar => _.object([...jar]))
  .then(jar => {
    createFieldUsagePipeline()
      .execute(jar);
  })
  .catch(console.error.bind(console));
<commit_msg>removed method that is no longer needed in unused field transform<commit_after>import * as _ from 'lodash';

import { Jar } from 'jvm';
import { Pipeline } from '../src/Pipeline';
import { ClassVisitor } from '../src/ClassVisitor';
import { Flags } from 'jvm/lib/core/jvm/AccessFlags';

let isVisibleToChildren = (member) => {
  return Flags.isPublic(member.accessFlags) || Flags.isProtected(member.accessFlags);
}

class FieldVisitor extends ClassVisitor {
  constructor(jar) {
    super();
    this.jar = jar;
    this.visited = new Set;
  }

  get count() {
    return this.visited.size;
  }

  recordField(cls, field) {
    this.visited.add([cls.name, field.name, field.desc].join(':'));
  }

  toArray() {
    return [...this.visited];
  }
}

class DeclaredFieldVisitor extends FieldVisitor {
  constructor(jar) {
    super(jar);
    this.on('visit-start', (cls) => this.visitInheritedFields(cls));
    this.on('visit-field', (cls, field) => this.recordField(cls, field));
  }

  visitInheritedFields(cls) {
    let parent = this.jar[cls.superName];
    while (parent) {
      parent.fields
        .filter(isVisibleToChildren)
        .forEach(field => this.recordField(parent, field));

      parent = this.jar[parent.superName];
    }
  }
}

class ReferencedFieldVisitor extends FieldVisitor {
  constructor(jar) {
    super(jar);
    this.on('visit-method', (cls, method) => this.visitMethodInstructions(method.instructions));
  }

  visitFieldInstruction(insn) {
    let cls = this.jar[insn.owner];
    let fieldStruct = { name: insn.name, desc: insn.desc };
    this.recordField(cls, fieldStruct);

    let parent = this.jar[cls.superName];
    while (parent) {
      let field = _.find(parent.fields, fieldStruct);
      if ( ! field || ! isVisibleToChildren(field)) {
        break;
      }

      this.recordField(parent, field);

      parent = this.jar[parent.superName];
    }
  }

  visitMethodInstructions(instructions) {
    instructions
      .filter(insn => insn.constructor.name === 'FieldInstruction' && insn.owner in this.jar)
      .forEach(insn => this.visitFieldInstruction(insn));
  }
}

let createFieldUsagePipeline = () => {
  let pipeline = new Pipeline;

  // analysis/transformation steps

  pipeline.addStep('identification', (jar) => {
    let declaredFields = new DeclaredFieldVisitor(jar);
    let referencedFields = new ReferencedFieldVisitor(jar);

    _.values(jar).forEach(cls => {
      declaredFields.accept(cls);
      referencedFields.accept(cls);
    });

    return {
      declared: declaredFields.count,
      referenced: referencedFields.count,
      unreferenced: _.difference(declaredFields.toArray(), referencedFields.toArray())
    };
  });

  pipeline.addStep('transformation', (jar) => {
    pipeline
      .stepResult('identification')
      .unreferenced
      .forEach(key => {
        let [clazz, name, desc] = key.split(':');
        let cls = jar[clazz];
        let field = _.find(cls.fields, { name, desc });
        _.remove(cls.fields, field);
      });
  });

  // output

  pipeline.afterStep('identification', (step, elapsed) => {
    console.log('Fields declared but not referenced: %s.', step.unreferenced.length);
    console.log('Fields referenced: %s/%s', step.referenced, step.declared);
  });

  pipeline.afterStep('transformation', (step, elapsed) => {
    console.log('Removed fields from classes in %ss', elapsed);
  });

  pipeline.after(elapsed => console.log('Unused Field Pipeline completed in %ss', elapsed));

  return pipeline;
}

Jar.unpack(process.argv[2])
  .then(jar => _.object([...jar]))
  .then(jar => {
    createFieldUsagePipeline()
      .execute(jar);
  })
  .catch(console.error.bind(console));
<|endoftext|>


<commit_before>const Uppy = require('../../src/core/Core.js')
const Dashboard = require('../../src/plugins/Dashboard')
const GoogleDrive = require('../../src/plugins/GoogleDrive')
const Dropbox = require('../../src/plugins/Dropbox')
const Instagram = require('../../src/plugins/Instagram')
const Webcam = require('../../src/plugins/Webcam')
const Tus10 = require('../../src/plugins/Tus10')
// const Multipart = require('../../src/plugins/Multipart')
// const DragDrop = require('../../src/plugins/FileInput')
const FileInput = require('../../src/plugins/FileInput')
const MetaData = require('../../src/plugins/MetaData')
// const Informer = require('../../src/plugins/Informer')
// const StatusBar = require('../../src/plugins/StatusBar')
// const DragDrop = require('../../src/plugins/DragDrop')

const PROTOCOL = location.protocol === 'https:' ? 'https' : 'http'
const TUS_ENDPOINT = PROTOCOL + '://master.tus.io/files/'

// import ru_RU from '../../src/locales/ru_RU.js'
// import MagicLog from '../../src/plugins/MagicLog'
// import PersistentState from '../../src/plugins/PersistentState'

const uppy = Uppy({
  debug: true,
  autoProceed: true,
  meta: {
    username: 'John'
  }
})
  .use(Dashboard, {
    trigger: '#uppyModalOpener',
    // maxWidth: 350,
    // maxHeight: 400,
    inline: false,
    // disableStatusBar: true,
    // disableInformer: true,
    setMetaFromTargetForm: true,
    target: '.MyForm',
    locale: {
      strings: { browse: 'wow' }
    }
  })
  .use(GoogleDrive, {target: Dashboard, host: 'http://localhost:3020'})
  .use(Dropbox, {target: Dashboard, host: 'http://localhost:3020'})
  .use(GoogleDrive, {target: Dashboard, host: 'http://localhost:3020'})
  .use(Dropbox, {target: Dashboard, host: 'http://localhost:3020'})
  .use(Instagram, {target: Dashboard, host: 'http://localhost:3020'})
  // .use(FileInput, {target: '.Uppy', locale: {
  //   strings: {selectToUpload: 'Выберите файл для загрузки'}
  // }})
  // .use(DragDrop, {target: 'body', locale: {
  //   strings: {chooseFile: 'Выберите файл'}
  // }})
  // .use(ProgressBar, {target: 'body'})
  // .use(Webcam, {target: Dashboard})
  // .use(Multipart, {endpoint: '//api2.transloadit.com'})
  .use(Tus10, {endpoint: TUS_ENDPOINT, resume: true})
  // .use(Informer, {target: Dashboard})
  // .use(StatusBar, {target: Dashboard})
  .use(MetaData, {
    fields: [
      { id: 'resizeTo', name: 'Resize to', value: 1200, placeholder: 'specify future image size' },
      { id: 'description', name: 'Description', value: 'none', placeholder: 'describe what the file is for' }
    ]
  })
uppy.run()

uppy.on('core:success', (fileCount) => {
  console.log('UPLOAD SUCCESSFUL!!!')
  console.log(fileCount)
})

// uppy.emit('informer', 'Smile!', 'info', 2000)

var modalTrigger = document.querySelector('#uppyModalOpener')
if (modalTrigger) modalTrigger.click()
<commit_msg>fix main.js<commit_after>const Uppy = require('../../src/core/Core.js')
const Dashboard = require('../../src/plugins/Dashboard')
const GoogleDrive = require('../../src/plugins/GoogleDrive')
const Dropbox = require('../../src/plugins/Dropbox')
const Instagram = require('../../src/plugins/Instagram')
// const Webcam = require('../../src/plugins/Webcam')
const Tus10 = require('../../src/plugins/Tus10')
// const Multipart = require('../../src/plugins/Multipart')
// const DragDrop = require('../../src/plugins/FileInput')
// const FileInput = require('../../src/plugins/FileInput')
const MetaData = require('../../src/plugins/MetaData')
// const Informer = require('../../src/plugins/Informer')
// const StatusBar = require('../../src/plugins/StatusBar')
// const DragDrop = require('../../src/plugins/DragDrop')

const PROTOCOL = location.protocol === 'https:' ? 'https' : 'http'
const TUS_ENDPOINT = PROTOCOL + '://master.tus.io/files/'

// import ru_RU from '../../src/locales/ru_RU.js'
// import MagicLog from '../../src/plugins/MagicLog'
// import PersistentState from '../../src/plugins/PersistentState'

const uppy = Uppy({
  debug: true,
  autoProceed: false,
  meta: {
    username: 'John'
  }
})
  .use(Dashboard, {
    trigger: '#uppyModalOpener',
    // maxWidth: 350,
    // maxHeight: 400,
    inline: false,
    // disableStatusBar: true,
    // disableInformer: true,
    setMetaFromTargetForm: true,
    // replaceTargetContent: true,
    target: '.MyForm',
    locale: {
      strings: { browse: 'wow' }
    }
  })
  .use(GoogleDrive, {target: Dashboard, host: 'http://localhost:3020'})
  .use(Dropbox, {target: Dashboard, host: 'http://localhost:3020'})
  .use(Instagram, {target: Dashboard, host: 'http://localhost:3020'})
  // .use(FileInput, {target: '.Uppy', locale: {
  //   strings: {selectToUpload: 'Выберите файл для загрузки'}
  // }})
  // .use(DragDrop, {target: 'body', locale: {
  //   strings: {chooseFile: 'Выберите файл'}
  // }})
  // .use(ProgressBar, {target: 'body'})
  // .use(Webcam, {target: Dashboard})
  // .use(Multipart, {endpoint: '//api2.transloadit.com'})
  .use(Tus10, {endpoint: TUS_ENDPOINT, resume: true})
  // .use(Informer, {target: Dashboard})
  // .use(StatusBar, {target: Dashboard})
  .use(MetaData, {
    fields: [
      { id: 'resizeTo', name: 'Resize to', value: 1200, placeholder: 'specify future image size' },
      { id: 'description', name: 'Description', value: 'none', placeholder: 'describe what the file is for' }
    ]
  })
uppy.run()

uppy.on('core:success', (fileCount) => {
  console.log('UPLOAD SUCCESSFUL!!!')
  console.log(fileCount)
})

// uppy.emit('informer', 'Smile!', 'info', 2000)

var modalTrigger = document.querySelector('#uppyModalOpener')
if (modalTrigger) modalTrigger.click()
<|endoftext|>


<commit_before>ig.module(
  'game.entities.soldier'
).requires(
  'impact.entity'
).defines(function() {

EntitySoldier = ig.Entity.extend({
  size: {x: 128, y: 64}
  , animSheet: new ig.AnimationSheet('media/man_run.png', 64, 64)
  , accelWalk: 800
  , type: ig.Entity.TYPE.B
  , checkAgainst: ig.Entity.TYPE.A

  , init: function(x, y, settings) {
    this.parent(x, y, settings);

    this.addAnim('idle', .2, [0, 1, 0]);
	this.addAnim( 'walkleft', 0.4, [0,1,0] );
	this.addAnim( 'walkright', 0.4, [0,1,0] );
	this.humanMove = Math.floor(Math.random() * 20) +1;
	this.timer = new ig.Timer(1);
	this.movin = 0;
  }

	, update: function() {
	var accel = this.accelWalk
		, soldier = this.pos;

	if (soldier > playa && dist <= 300) {
		this.currentAnim = this.anims.walkleft;
		this.accel.x = -accel;
	}

	else if (soldier > playa && dist <= 300) {
		this.currentAnim = this.anims.walkright;
		this.accel.x = accel;
	} else {
		this.currentAnim = this.anims.idle;
	}

	this.parent();
  }

  , check: function(other) {
	other.addInventory('HUE-MAN'); console.log(ig.player.inventory);
	this.kill();
  }

	});
});
<commit_msg>soldierz yo<commit_after>ig.module(
  'game.entities.soldier'
).requires(
  'impact.entity'
).defines(function() {

EntitySoldier = ig.Entity.extend({
  size: {x: 128, y: 64}
  , animSheet: new ig.AnimationSheet('media/man_run.png', 64, 64)
  , accelWalk: 800
  , type: ig.Entity.TYPE.B
  , checkAgainst: ig.Entity.TYPE.A

  , init: function(x, y, settings) {
    this.parent(x, y, settings);

    this.addAnim('idle', .2, [0, 1, 0]);
	this.addAnim( 'walkleft', 0.4, [0,1,0] );
	this.addAnim( 'walkright', 0.4, [0,1,0] );
	this.humanMove = Math.floor(Math.random() * 20) +1;
	this.timer = new ig.Timer(1);
	this.movin = 0;
  }

	, update: function() {
	var accel = this.accelWalk
		, playa = ig.player.pos.x
		, dist = this.distanceTo(ig.player)
		, soldier = this.pos;

	if (soldier > playa && dist <= 300) {
		this.currentAnim = this.anims.walkleft;
		this.accel.x = -accel;
	}

	else if (soldier > playa && dist <= 300) {
		this.currentAnim = this.anims.walkright;
		this.accel.x = accel;
	} else {
		this.currentAnim = this.anims.idle;
	}

	this.parent();
  }

  , check: function(other) {
	other.addInventory('HUE-MAN'); console.log(ig.player.inventory);
	this.kill();
  }

	});
});
<|endoftext|>