<commit_before>import React, { PureComponent } from 'react';
import ReactDOM from 'react-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import injectTapEventPlugin from 'react-tap-event-plugin';
import Sensor from '../components/sensor';
import LabQuest2 from 'sensor-labquest-2-interface';
import bleSensor from '../components/ble-sensor.js';
import LogoMenu from '../components/logo-menu';
import Clock from '../components/clock';
import { getURLParam } from '../utils';
import { List, ListItem } from 'material-ui/List';
import { GridList, GridTile } from 'material-ui/GridList'
import Thermoscope from '../components/thermoscope';

const sensor = bleSensor;

import '../../css/app.less';

// Required by Material-UI library.
injectTapEventPlugin();

darkBaseTheme.palette.textColor = '#ccc';
darkBaseTheme.palette.primary1Color = '#ccc';

let ThermoscopeMode = { Menu: 0, OneThermoscope: 1, TwoThermoscope: 2, ThreeThermoscope: 3 };
let meterSegments = [
  {
    color: "#800000",
    start: 0,
    end: 45
  },
  {
    color: "#a0a000",
    start: 45,
    end: 145
  },
  {
    color: "#008000",
    start: 145,
    end: 180
  }
];

export default class ThermoscopeControl extends PureComponent {

  constructor(props) {
    super(props);
    let initialMode = ThermoscopeMode.Menu;
    if (getURLParam('A')) {
      if (getURLParam('B')) {
        initialMode = ThermoscopeMode.TwoThermoscope;
      } else {
        initialMode = ThermoscopeMode.OneThermoscope;
      }
    }
    this.state = {
      mode: initialMode
    };
    this.setThermoscopeRendering = this.setThermoscopeRendering.bind(this);
    this.renderThermoscope = this.renderThermoscope.bind(this);
    this.showMenu = this.showMenu.bind(this);
  }
  showMenu() {
    this.setState({ mode: ThermoscopeMode.Menu });
  }

  setThermoscopeRendering(params, quantity) {
    var pageUrl = params ? '?' + params : '';
    window.history.pushState('', '', pageUrl);
    this.setState({ mode: quantity })
  }

  renderThermoscope(material, probeIndex, label, hidden, materialIndex, showMeter, meterMinClamp, meterMaxClamp) {
    let meterMin = meterMinClamp ? meterMinClamp : 0;
    let meterMax = meterMaxClamp ? meterMaxClamp : 1;
    let showControls = getURLParam('controls');
    let thermoscope =

        <Thermoscope
          sensor={sensor}
          material={material}
          embeddableSrc='../lab/embeddable.html'
          label={label}
          probeIndex={probeIndex}
          materialIndex={materialIndex}
          showMeter={showMeter}
          meterSegments={meterSegments}
          minClamp={meterMin}
          maxClamp={meterMax}
          showMaterialControls={showControls}
          hidden={hidden}/>

;
    return thermoscope;
  }

  render() {
    const { mode } = this.state;
    const gridStyle = {
      display: 'flex',
      flexWrap: 'nowrap',
      overflowX: 'auto',
    }
    return (
      <MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>

        <Clock />
          <LogoMenu scale="logo-menu small" navPath="../index.html" />

home

          { mode === ThermoscopeMode.Menu &&

Thermoscope Examples

                <GridList style={gridStyle}>
                  <GridTile onClick={() => this.setThermoscopeRendering("A=solid&B=solid", 2)} key="1">

Wood and Stone

                  </GridTile>
                  <GridTile onClick={() => this.setThermoscopeRendering("A=liquid&B=liquid", 2)} key="2" >

Oil and Soap

                  </GridTile>
                  <GridTile onClick={() => this.setThermoscopeRendering("A=gas&B=gas", 2)} key="3" >

Air

                  </GridTile>
                </GridList>
                <GridList style={gridStyle}>
                  <GridTile onClick={() => this.setThermoscopeRendering("A=liquid&B=liquid&materialA=2&materialB=2", 2)} key="4" >

Water

                  </GridTile>
                  <GridTile onClick={() => this.setThermoscopeRendering("A=uniform", 1)} key="5" >

Experiments

                  </GridTile>
                </GridList>

Thermoscope Experiments

                <GridList style={gridStyle}>
                  <GridTile onClick={() => this.setThermoscopeRendering("controls=true", 1)} key="5">

Thermoscope (one)

                  </GridTile>
                  <GridTile onClick={() => this.setThermoscopeRendering("controls=true", 2)} key="6">

Thermoscope (two)

                  </GridTile>
                </GridList>

          }
          {mode === ThermoscopeMode.OneThermoscope &&

              {this.renderThermoscope(getURLParam('A'), 0, 'A', getURLParam('hideA'))}

          }
          { mode === ThermoscopeMode.TwoThermoscope &&

              {this.renderThermoscope(getURLParam('A'), 0, 'A', getURLParam('hideA'),  getURLParam('materialA'))}
              {this.renderThermoscope(getURLParam('B'), 1, 'B', getURLParam('hideB'),  getURLParam('materialB'))}

          }
          { mode === ThermoscopeMode.ThreeThermoscope &&

              {this.renderThermoscope(getURLParam('A'), 0, 'A', getURLParam('hideA'), getURLParam('materialA'), true)}
              {this.renderThermoscope(getURLParam('B'), 1, 'B', getURLParam('hideB'), getURLParam('materialB'), true)}
              {this.renderThermoscope(getURLParam('C'), 1, 'C', getURLParam('hideC'), getURLParam('materialC'), true)}

          }
          <Sensor sensor={sensor} showAddressBox={false} />

      </MuiThemeProvider>
    )
  }
}

ReactDOM.render(<ThermoscopeControl/>, document.getElementById('app'));
<commit_msg>Use state to handle thermoscope rendering state, with option to read in url parameters and to write to url parameters if required - we aren’t using this much / at all at the moment since the implementation is focussed almost entirely on iOS edition. To display current parameters in the url, add “params=true” option to the url when loading the Thermoscope main page.<commit_after>import React, { PureComponent } from 'react';
import ReactDOM from 'react-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import injectTapEventPlugin from 'react-tap-event-plugin';
import Sensor from '../components/sensor';
import LabQuest2 from 'sensor-labquest-2-interface';
import bleSensor from '../components/ble-sensor.js';
import LogoMenu from '../components/logo-menu';
import Clock from '../components/clock';
import { getURLParam } from '../utils';
import { List, ListItem } from 'material-ui/List';
import { GridList, GridTile } from 'material-ui/GridList'
import Thermoscope from '../components/thermoscope';

const sensor = bleSensor;
const enableUrlParam = getURLParam('params') || false;

import '../../css/app.less';

// Required by Material-UI library.
injectTapEventPlugin();

darkBaseTheme.palette.textColor = '#ccc';
darkBaseTheme.palette.primary1Color = '#ccc';

let ThermoscopeMode = { Menu: 0, OneThermoscope: 1, TwoThermoscope: 2, ThreeThermoscope: 3 };
let meterSegments = [
  {
    color: "#800000",
    start: 0,
    end: 45
  },
  {
    color: "#a0a000",
    start: 45,
    end: 145
  },
  {
    color: "#008000",
    start: 145,
    end: 180
  }
];

export default class ThermoscopeControl extends PureComponent {

  constructor(props) {
    super(props);
    let initialMode = ThermoscopeMode.Menu;
    if (enableUrlParam && getURLParam('A')) {
      if (enableUrlParam && getURLParam('B')) {
        initialMode = ThermoscopeMode.TwoThermoscope;
      } else {
        initialMode = ThermoscopeMode.OneThermoscope;
      }
    }
    this.state = {
      mode: initialMode
    };
    this.setThermoscopeRendering = this.setThermoscopeRendering.bind(this);
    this.renderThermoscope = this.renderThermoscope.bind(this);
    this.showMenu = this.showMenu.bind(this);
  }
  getParam(param) {
    if (enableUrlParam) {
      return getURLParam(param);
    } else {
      return this.state.params[param] || false;
    }
  }
  showMenu() {
    this.setState({ mode: ThermoscopeMode.Menu });
  }

  setThermoscopeRendering(params, quantity) {
    if (enableUrlParam) {
      let urlParams = Object.entries(params).map(e => e.join('=')).join('&');
      var pageUrl = params ? '?' + urlParams : '';
      window.history.pushState('', '', pageUrl);
    }
    this.setState({ params, mode: quantity })
  }

  renderThermoscope(material, probeIndex, label, hidden, materialIndex, showMeter, meterMinClamp, meterMaxClamp) {
    let meterMin = meterMinClamp ? meterMinClamp : 0;
    let meterMax = meterMaxClamp ? meterMaxClamp : 1;
    let showControls = this.getParam('controls');
    let thermoscope =

        <Thermoscope
          sensor={sensor}
          material={material}
          embeddableSrc='../lab/embeddable.html'
          label={label}
          probeIndex={probeIndex}
          materialIndex={materialIndex}
          showMeter={showMeter}
          meterSegments={meterSegments}
          minClamp={meterMin}
          maxClamp={meterMax}
          showMaterialControls={showControls}
          hidden={hidden}/>

;
    return thermoscope;
  }

  render() {
    const { mode } = this.state;
    const gridStyle = {
      display: 'flex',
      flexWrap: 'nowrap'
    }
    return (
      <MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>

        <Clock />
          <LogoMenu scale="logo-menu small" navPath="../index.html" />

home

          { mode === ThermoscopeMode.Menu &&

Thermoscope Examples

                <GridList style={gridStyle}>
                <GridTile onClick={() => this.setThermoscopeRendering({ A: 'solid', B: 'solid' }, 2)} key="1">

Wood and Stone

                  </GridTile>
                  <GridTile onClick={() => this.setThermoscopeRendering({ A: 'liquid', B: 'liquid' }, 2)} key="2" >

Oil and Soap

                  </GridTile>
                  <GridTile onClick={() => this.setThermoscopeRendering({ A: 'gas', B: 'gas' }, 2)} key="3" >

Air

                  </GridTile>
                </GridList>
                <GridList style={gridStyle}>
                <GridTile onClick={() => this.setThermoscopeRendering({ A: 'liquid', B: 'liquid', materialA: 2, materialB: 2 }, 2)} key="4" >

Water

                  </GridTile>
                <GridTile onClick={() => this.setThermoscopeRendering({ A: 'uniform' }, 1)} key="5" >

Experiments

                  </GridTile>
                </GridList>

Thermoscope Experiments

                <GridList style={gridStyle}>
                <GridTile onClick={() => this.setThermoscopeRendering({ controls:true }, 1)} key="5">

Thermoscope (one)

                  </GridTile>
                  <GridTile onClick={() => this.setThermoscopeRendering({ controls:true }, 2)} key="6">

Thermoscope (two)

                  </GridTile>
                </GridList>

          }
          {mode === ThermoscopeMode.OneThermoscope &&

              {this.renderThermoscope(this.getParam('A'), 0, 'A', this.getParam('hideA'))}

          }
          { mode === ThermoscopeMode.TwoThermoscope &&

              {this.renderThermoscope(this.getParam('A'), 0, 'A', this.getParam('hideA'),  this.getParam('materialA'))}
              {this.renderThermoscope(this.getParam('B'), 1, 'B', this.getParam('hideB'),  this.getParam('materialB'))}

          }
          { mode === ThermoscopeMode.ThreeThermoscope &&

              {this.renderThermoscope(this.getParam('A'), 0, 'A', this.getParam('hideA'), this.getParam('materialA'), true)}
              {this.renderThermoscope(this.getParam('B'), 1, 'B', this.getParam('hideB'), this.getParam('materialB'), true)}
              {this.renderThermoscope(this.getParam('C'), 1, 'C', this.getParam('hideC'), this.getParam('materialC'), true)}

          }
          <Sensor sensor={sensor} showAddressBox={false} />

      </MuiThemeProvider>
    )
  }
}

ReactDOM.render(<ThermoscopeControl/>, document.getElementById('app'));
<|endoftext|>


<commit_before>// Karma configuration
module.exports = function(config) {
    var customLaunchers = {
        'latest-chrome': {
            base: 'SauceLabs',
            browserName: 'chrome'
        },
        'latest-firefox': {
            base: 'SauceLabs',
            browserName: 'firefox'
        },
        'internet-explorer-9': {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            version: '9'
        },
        'ios-6': {
            base: 'SauceLabs',
            browserName: 'iphone',
            platform: "OS X 10.8",
            version: "6.0"
        },
        'android-4': {
            base: 'SauceLabs',
            device: 'motorola droid razr emulator',
            platform: "Linux",
            version: "4.0"
        }
    };

    config.set({
        frameworks: ['qunit'],
        files: [
            'bower_components/jquery/dist/jquery.min.js',
            'bower_components/modernizr/modernizr.js',
            'dist/circle-progress.js',
            'tests/test_utils.js',
            'tests/tests.js'
        ],
        sauceLabs: {
            testName: 'Unit Tests for jquery-circle-progress'
        },
        captureTimeout: 120000,
        customLaunchers: customLaunchers,
        browsers: Object.keys(customLaunchers),
        reporters: ['dots', 'saucelabs'],
        singleRun: true
    });
};
<commit_msg>SauceLabs VM for Android 4.0 added<commit_after>// Karma configuration
module.exports = function(config) {
    var customLaunchers = {
        'latest-chrome': {
            base: 'SauceLabs',
            browserName: 'chrome'
        },
        'latest-firefox': {
            base: 'SauceLabs',
            browserName: 'firefox'
        },
        'internet-explorer-9': {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            version: '9'
        },
        'ios-6': {
            base: 'SauceLabs',
            browserName: 'iphone',
            platform: "OS X 10.8",
            version: "6.0"
        },
        'android-4': {
            base: 'SauceLabs',
            browserName: 'android',
            device: 'Motorola Droid Razr Emulator',
            platform: "Linux",
            version: "4.0"
        }
    };

    config.set({
        frameworks: ['qunit'],
        files: [
            'bower_components/jquery/dist/jquery.min.js',
            'bower_components/modernizr/modernizr.js',
            'dist/circle-progress.js',
            'tests/test_utils.js',
            'tests/tests.js'
        ],
        sauceLabs: {
            testName: 'Unit Tests for jquery-circle-progress'
        },
        captureTimeout: 120000,
        customLaunchers: customLaunchers,
        browsers: Object.keys(customLaunchers),
        reporters: ['dots', 'saucelabs'],
        singleRun: true
    });
};
<|endoftext|>


<commit_before>var request = require('request');
var cheerio = require('cheerio');
var schedule = require('node-schedule');
var mongoose = require('mongoose');
var Comic = require('../models/Comic').Comic;
var moment = require('moment');
var titleHelper = require('../utils/titleHelper');

var baseDynamiteURL = 'http://www.dynamite.com';

var dynamiteScrape = schedule.scheduleJob({hour: 10, dayOfWeek: new schedule.Range(1, 5)}, function(){
    console.log("About to scrape Dynamite comics");
    var scrapeDynamiteComics = function scrapeDynamiteComics(month){
        var now = month || moment();
        var url = baseDynamiteURL + '/htmlfiles/previews.html?getMonth='+now.format("MMMM")+'&getYear='+now.format("YYYY");
        console.log("Scraping "+url);
        request(url, function(error, response, html){
            if(error) console.error(error);
            if(!error){
                console.log("Got a response");

                var $ = cheerio.load(html);

                var domComics = $('#indexPlacement tr[align=left]');
                if(domComics.length === 0){
                    console.log("Done for now");
                    return;
                }
                var i = 0;
                domComics.each(function(){
                    var fullTitle = $(this).find('strong').text().trim();
                    var link = baseDynamiteURL + $(this).find('a').first().attr('href');
                    var release_date = moment(html.match(/ON SALE DATE: ([\w]+ [\d+])/i)[i++] + now.format(" YYYY"));
                    var title = titleHelper.getTitle(fullTitle);
                    var issue = titleHelper.getIssue(fullTitle);

                    var newComic = {
                        title: title,
                        issue: issue,
                        release_date: release_date.format('YYYY-MM-DD'),
                        publisher: 'Dynamite',
                        link : link
                    };

                    Comic.update({ title : newComic.title, publisher: newComic.publisher}, {$set: newComic}, {upsert:true}, function(err, newComic){
                        if (err) return console.error(err);
                    });
                });
                now.add(1, 'months');
                scrapeDynamiteComics(now);
            }
        });
    };
    scrapeDynamiteComics();
});

console.log("✔ Dynamite scraper loaded");<commit_msg>Migrated Dynamite to the new ScraperBase<commit_after>var Scraper = require('./ScraperBase');
var request = require('request');
var cheerio = require('cheerio');
var moment = require('moment');
var titleHelper = require('../utils/titleHelper');
var extend = require('util')._extend;

var dynamite = Object.create(Scraper);
dynamite.options = {
    'publisher' : 'Dynamite',
    'URL' : 'http://www.dynamite.com/htmlfiles/previews.html?getMonth=$month&getYear=$year',
    'monthFormat' : 'MMMM',
    'yearFormat' : 'YYYY',
    'dayFormat'  : 'DD',
    'scrapeTime' : 5,
    'scrapeMinute' : 0,
    'scrapeFunction' : function(scrapeVars){
        var domComics = $('#indexPlacement tr[align=left]');
        if(domComics.length === 0){
            scrapeVars.completedCallback();
            return;
        }
        var i = 0;
        domComics.each(function(){
            try{
                var fullTitle = $(this).find('strong').text().trim();
                var link = baseDynamiteURL + $(this).find('a').first().attr('href');
                var release_date = moment(html.match(/ON SALE DATE: ([\w]+ [\d+])/i)[i++] + scrapeVars.now.format(" YYYY"));
                var title = titleHelper.getTitle(fullTitle);
                var issue = titleHelper.getIssue(fullTitle);

                var newComic = {
                    title: title,
                    issue: issue,
                    release_date: release_date.format('YYYY-MM-DD'),
                    publisher: 'Dynamite',
                    link : link
                };

                scrapeVars.addComic(newComic);
            }catch (e){
                scrapeVars.errorCallback(e.message);
            }
        });
        // Call the next callback that triggers scraping the next month
        scrapeVars.nextCallback();
    }
};

module.exports = dynamite;

// Call the scraper directly and avoid the scheduler
if(process.argv && process.argv[2] && process.argv[2] == 'start'){
    dynamite.startNow();
}<|endoftext|>


<commit_before>'use strict';
var
db					  = require('lowdb')('./dbs/seLoger.json'),
request 			= require('request'),
cheerio 			= require('cheerio'), //parse it like Jquery
iconv 				= require('iconv-lite');

exports.scrap = function(url){
  return new Promise(function(resolve, reject){
    var apparts = [];
    request({uri: url, encoding: null}, function(err, resp, body){
      if(err)
        reject(err);
      body = iconv.decode(body, 'utf8');
      var $ = cheerio.load(body);
      var list = $('.liste_resultat').find('article');
      list.each(function(){
        var infos = $(this).find('.listing_infos');
        var props = $(this).find('.property_list');

        var flat = {from: 'seLoger', labels:[], values:[], upload: false};
        flat.id = parseInt($(this).attr('data-listing-id'));
        flat.href = $($(infos).find('a')).attr('href');
        flat.price = $($(infos).find('.amount')).html();
        flat.title = $($(infos).find('a')).attr('title');
        $(props).find('li').each(function(){
          flat.labels.push(' ');
          flat.values.push($(this).html());
        });
        if(!db('seLoger').find({id: flat.id})){
          db('seLoger').push({id: flat.id});
          apparts.push(flat);
        }
      });
      resolve(apparts);
    });
  });
};
<commit_msg>more infos.<commit_after>'use strict';
var
db					  = require('lowdb')('./dbs/seLoger.json'),
request 			= require('request'),
cheerio 			= require('cheerio'), //parse it like Jquery
iconv 				= require('iconv-lite');

var suck_it = function(url, cb){
  request({uri: url, encoding: null}, function(err, resp, body){
    if(err) return cb([], []);
    var values = [];
    var labels = [];
    body = iconv.decode(body, 'utf8');
    var $ = cheerio.load(body);
    var props = $('.description-liste').find('li');
    props.each(function(){
      labels.push(' ');
      values.push($(this).html());
    });
    return cb(labels, values);
  });
};

exports.scrap = function(url){
  return new Promise(function(resolve, reject){
    var apparts = [];
    request({uri: url, encoding: null}, function(err, resp, body){
      if(err)
        reject(err);
      body = iconv.decode(body, 'utf8');
      var $ = cheerio.load(body);
      var list = $('.liste_resultat').find('article');
      var count = list.length;
      list.each(function(){
        var infos = $(this).find('.listing_infos');
        var flat = {from: 'seLoger', labels:[], values:[], upload: false};
        flat.id = parseInt($(this).attr('data-listing-id'));
        flat.href = $($(infos).find('a')).attr('href');
        flat.price = $($(infos).find('.amount')).html();
        flat.title = $($(infos).find('a')).attr('title');
          suck_it(flat.href, function(labels, values){
            count--;
            if(!db('seLoger').find({id: flat.id})){
              db('seLoger').push({id: flat.id});
              flat.labels = labels;
              flat.values = values;
              apparts.push(flat);
            }
            if(count === 0){
              resolve(apparts);
            }
          });
      });
    });
  });
};
<|endoftext|>


<commit_before>var fs = require('fs')
var os = require('os')
var path = require('path')
var tar = require('tar-fs')
var gunzip = require('gunzip-maybe')
var mkdir = require('mkdirp')
var nugget = require('nugget')
var cpr = require('cpr')
var through = require('through2')
var rimraf = require('rimraf')
var yaml = require('yamljs')
var toTitleCase = require('titlecase')

// settings!
// var settings = {
//   latest: boolean,
//   version: string,
//   finalDir: string
// }

module.exports = function fetchDocs (settings, callback) {

  if (settings.latest) updateLatestVersion(settings.version)

  var url = 'https://api.github.com/repos/atom/electron/tarball/' + settings.version
  settings.tmpDir = path.join(os.tmpDir(), 'electron-tmp-download')

  // Create temp directory to fetch tarball into
  mkdir(settings.tmpDir, function (error) {
    if (error) return callback(error)
    var filename = 'electron.tar.gz'
    var opts = {
      headers: {"user-agent": "Electron"},
      target: filename,
      dir: settings.tmpDir,
      resume: true,
      verbose: true
      }

    nugget(url, opts, function (error) {
      if (error) return callback(error)
      extractDocs(filename, settings, callback)
    })
  })
}

function updateLatestVersion (version) {
  var config = yaml.load('_config.yml')
  config.latest_version = version
  fs.writeFileSync('_config.yml', yaml.stringify(config))
}

// Extract just the 'docs' directory from within
// tarball, then prepend each markdown file with
// Jekyll front matter
function extractDocs (filename, settings, callback) {
  var tarball = path.join(settings.tmpDir, filename)

  var extract = tar.extract(settings.tmpDir, {
    ignore: function (name) {
      return name.indexOf('/docs/') === -1
    },
    mapStream: function (fileStream, header) {
      var frontmatter
      if (path.extname(header.name) === '.md') {
        var metadata = constructDocMetadata(header.name, settings.version)
        metadata.source_url = constructSourceUrl(header.name)
        if (path.basename(header.name, '.md') === 'README') {
          metadata.permalink = '/docs/' + settings.version + '/index.html'
          frontmatter = new Buffer('---\n' + yaml.stringify(metadata) + '---\n\n')
          return fileStream.pipe(frontMatterify(frontmatter)).pipe(removeMdUrls())
        }
        frontmatter = new Buffer('---\n' + yaml.stringify(metadata) + '---\n\n')
        return fileStream.pipe(frontMatterify(frontmatter))
      }
      return filestream
    }
  })

  extract.on('entry', function extracting (header, stream, next) {
    var extractedElectronDir = header.name.split('/')[0]
    settings.newDir = path.join(settings.tmpDir, extractedElectronDir)
  })

  extract.on('finish', function extracted () {
    settings.versionDir = path.join(settings.newDir, settings.version)
    settings.extractedDocsDir = path.join(settings.newDir, 'docs')
    settings.finalDir = path.join(process.cwd(), settings.finalDir, settings.version)
    moveDirectories(settings, callback)
  })

  fs.createReadStream(tarball).pipe(gunzip()).pipe(extract)
}

function frontMatterify (frontmatter) {
  var appended = false
  return through(function (obj, enc, next) {
    if (!appended) this.push(frontmatter)
    appended = true
    this.push(obj)
    next()
  })
}

function removeMdUrls () {
  return through(function (obj, enc, next) {
    var regex = /\.md\)/ig
    var edits = obj.toString().replace(regex, ')')
    this.push(edits)
    next()
  })
}

function constructSourceUrl (path) {
  var baseUrl = 'https://github.com/atom/electron/blob/master/'
  var source = path.split('/')
  source.splice(0, 1)
  return baseUrl + source.join('/')
}

function constructDocMetadata (path, version) {
  var metadata = {}
  metadata.version = version
  var pathArray = path.split('/')
  pathArray.splice(0, 2)
  if (pathArray.length === 1) {
    metadata.category = "Contents"
    metadata.title = formatDocTitle(pathArray[0])
  } else {
    if (pathArray[0] === 'api') metadata.category = 'API'
    else metadata.category = toTitleCase(pathArray[0])
    metadata.title = formatDocTitle(pathArray[1])
  }
  return metadata
}

function formatDocTitle (filename) {
  filename = filename.replace('.md', '')
  filename = filename.split('-').join(' ')
  return toTitleCase(filename)
}

// Take newly extracted 'docs' directory, name it according
// to appropriate Electron version, copy it to electron.atom.io
// '_docs' directory and delete temp directory
function moveDirectories (settings, callback) {
  fs.rename(settings.extractedDocsDir, settings.versionDir, function renamed (error) {
    if (error) return callback(error)
    cpr(settings.versionDir, settings.finalDir, function moved (error) {
      if (error) return callback(error)
      rimraf(settings.tmpDir, function deleted (error) {
        if (error) return callback(error)
        if (callback) callback(null, "Done! Docs are in " + settings.finalDir)
      })
    })
  })
}
<commit_msg>Collect all versions, not just latest<commit_after>var fs = require('fs')
var os = require('os')
var path = require('path')
var tar = require('tar-fs')
var gunzip = require('gunzip-maybe')
var mkdir = require('mkdirp')
var nugget = require('nugget')
var cpr = require('cpr')
var through = require('through2')
var rimraf = require('rimraf')
var yaml = require('yamljs')
var toTitleCase = require('titlecase')

// settings!
// var settings = {
//   latest: boolean,
//   version: string,
//   finalDir: string
// }

module.exports = function fetchDocs (settings, callback) {

  updateVersions(settings.version, settings.latest)

  var url = 'https://api.github.com/repos/atom/electron/tarball/' + settings.version
  settings.tmpDir = path.join(os.tmpDir(), 'electron-tmp-download')

  // Create temp directory to fetch tarball into
  mkdir(settings.tmpDir, function (error) {
    if (error) return callback(error)
    var filename = 'electron.tar.gz'
    var opts = {
      headers: {"user-agent": "Electron"},
      target: filename,
      dir: settings.tmpDir,
      resume: true,
      verbose: true
      }

    nugget(url, opts, function (error) {
      if (error) return callback(error)
      extractDocs(filename, settings, callback)
    })
  })
}

function updateVersions (version, latest) {
  var config = yaml.load('_config.yml')
  if (latest) config.latest_version = version
  if (config.available_versions.indexOf(version) != 1) {
    config.available_versions.push(version)
  }
  fs.writeFileSync('_config.yml', yaml.stringify(config))
}

// Extract just the 'docs' directory from within
// tarball, then prepend each markdown file with
// Jekyll front matter
function extractDocs (filename, settings, callback) {
  var tarball = path.join(settings.tmpDir, filename)

  var extract = tar.extract(settings.tmpDir, {
    ignore: function (name) {
      return name.indexOf('/docs/') === -1
    },
    mapStream: function (fileStream, header) {
      var frontmatter
      if (path.extname(header.name) === '.md') {
        var metadata = constructDocMetadata(header.name, settings.version)
        metadata.source_url = constructSourceUrl(header.name)
        if (path.basename(header.name, '.md') === 'README') {
          metadata.permalink = '/docs/' + settings.version + '/index.html'
          frontmatter = new Buffer('---\n' + yaml.stringify(metadata) + '---\n\n')
          return fileStream.pipe(frontMatterify(frontmatter)).pipe(removeMdUrls())
        }
        frontmatter = new Buffer('---\n' + yaml.stringify(metadata) + '---\n\n')
        return fileStream.pipe(frontMatterify(frontmatter))
      }
      return filestream
    }
  })

  extract.on('entry', function extracting (header, stream, next) {
    var extractedElectronDir = header.name.split('/')[0]
    settings.newDir = path.join(settings.tmpDir, extractedElectronDir)
  })

  extract.on('finish', function extracted () {
    settings.versionDir = path.join(settings.newDir, settings.version)
    settings.extractedDocsDir = path.join(settings.newDir, 'docs')
    settings.finalDir = path.join(process.cwd(), settings.finalDir, settings.version)
    moveDirectories(settings, callback)
  })

  fs.createReadStream(tarball).pipe(gunzip()).pipe(extract)
}

function frontMatterify (frontmatter) {
  var appended = false
  return through(function (obj, enc, next) {
    if (!appended) this.push(frontmatter)
    appended = true
    this.push(obj)
    next()
  })
}

function removeMdUrls () {
  return through(function (obj, enc, next) {
    var regex = /\.md\)/ig
    var edits = obj.toString().replace(regex, ')')
    this.push(edits)
    next()
  })
}

function constructSourceUrl (path) {
  var baseUrl = 'https://github.com/atom/electron/blob/master/'
  var source = path.split('/')
  source.splice(0, 1)
  return baseUrl + source.join('/')
}

function constructDocMetadata (path, version) {
  var metadata = {}
  metadata.version = version
  var pathArray = path.split('/')
  pathArray.splice(0, 2)
  if (pathArray.length === 1) {
    metadata.category = "Table of Contents"
    metadata.title = formatDocTitle(pathArray[0])
  } else {
    if (pathArray[0] === 'api') metadata.category = 'API'
    else metadata.category = toTitleCase(pathArray[0])
    metadata.title = formatDocTitle(pathArray[1])
  }
  return metadata
}

function formatDocTitle (filename) {
  filename = filename.replace('.md', '')
  filename = filename.split('-').join(' ')
  return toTitleCase(filename)
}

// Take newly extracted 'docs' directory, name it according
// to appropriate Electron version, copy it to electron.atom.io
// '_docs' directory and delete temp directory
function moveDirectories (settings, callback) {
  fs.rename(settings.extractedDocsDir, settings.versionDir, function renamed (error) {
    if (error) return callback(error)
    cpr(settings.versionDir, settings.finalDir, function moved (error) {
      if (error) return callback(error)
      rimraf(settings.tmpDir, function deleted (error) {
        if (error) return callback(error)
        if (callback) callback(null, "Done! Docs are in " + settings.finalDir)
      })
    })
  })
}
<|endoftext|>


<commit_before>console.log (5+4)
alert("U start nu de log")
nameAsk();
datumAsk();
modemAsk();
function nameAsk() {
	var naam = prompt("Geef de naam");
	if (naam.length === 0){
		alert("Geen naam gegeven");
		nameAsk();
	}
	else {
		document.write('');
		document.write(naam);
		document.write("");
		document.write("
");
	}
}

function datumAsk() {
	var datum = prompt("Geef de datum (dd-mm-jjjj)");
	if (datum.length <= 9) {
		alert("Geef een geldige datum op");
		datumAsk();
	}
	else{
		document.write(datum);
		document.write("
");
	}
}

function modemAsk() {
	var modem = prompt("Wat voor type modem gebruikt de klant?");
	if (modem.length === 0){
		alert("Geef een geldige modem op");
		modemAsk();
	}
	else{
		document.write(modem);
		document.write("
");
	}
}

function klachtAsk() {
	var klacht = prompt("Heeft de klant een klacht");
	if (klacht.length === 0){
		alert("Geef een geldige klacht op");
		klachtAsk();
	}
	else{
		document.write(klacht);
		document.write("
");
	}
}<commit_msg>added klacht<commit_after>console.log (5+4)
alert("U start nu de log")
nameAsk();
datumAsk();
modemAsk();
klachtAsk();
function nameAsk() {
	var naam = prompt("Geef de naam");
	if (naam.length === 0){
		alert("Geen naam gegeven");
		nameAsk();
	}
	else {
		document.write('');
		document.write(naam);
		document.write("");
		document.write("
");
	}
}

function datumAsk() {
	var datum = prompt("Geef de datum (dd-mm-jjjj)");
	if (datum.length <= 9) {
		alert("Geef een geldige datum op");
		datumAsk();
	}
	else{
		document.write(datum);
		document.write("
");
	}
}

function modemAsk() {
	var modem = prompt("Wat voor type modem gebruikt de klant?");
	if (modem.length === 0){
		alert("Geef een geldige modem op");
		modemAsk();
	}
	else{
		document.write(modem);
		document.write("
");
	}
}

function klachtAsk() {
	var klachtCheck = confirm("Heeft de klant een klacht?");
	if (klachtCheck = true){
		var klacht = prompt("Heeft de klant een klacht");
		if (klacht.length === 0){
			alert("Geef een geldige klacht op");
			klachtAsk();
		}
		else{
			document.write(klacht);
			document.write("
");
		}
	}
	else{
		document.write(naam + datum + modem + klachtCheck + klacht);
	}
}<|endoftext|>


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

/* eslint-disable global-require, no-octal-escape */
const childProcess = require('child_process');
const { lstatSync, readdirSync } = require('fs');
const { join } = require('path');

const logger = console;

let cooldown = 0;

try {
  require('inquirer');
  require('commander');
  require('chalk');
  require('npmlog');
} catch (e) {
  logger.log('🕘 running bootstrap on a clean repo, we have to install dependencies');
  childProcess.spawnSync('yarn', ['install', '--ignore-optional'], {
    stdio: ['inherit', 'inherit', 'inherit'],
  });
  process.stdout.write('\x07');
  process.stdout.write('\033c');

  // give the filesystem some time
  cooldown = 1000;
} finally {
  setTimeout(run, cooldown);
}

function run() {
  const inquirer = require('inquirer');
  const program = require('commander');
  const chalk = require('chalk');
  const log = require('npmlog');

  const isTgz = (source) => lstatSync(source).isFile() && source.match(/.tgz$/);
  const getDirectories = (source) =>
    readdirSync(source)
      .map((name) => join(source, name))
      .filter(isTgz);

  log.heading = 'storybook';
  const prefix = 'bootstrap';
  log.addLevel('aborted', 3001, { fg: 'red', bold: true });

  const spawn = (command, options = {}) => {
    const out = childProcess.spawnSync(`${command}`, {
      shell: true,
      stdio: 'inherit',
      ...options,
    });

    if (out.status !== 0) {
      process.exit(out.status);
    }
    return out;
  };

  const main = program
    .version('5.0.0')
    .option('--all', `Bootstrap everything ${chalk.gray('(all)')}`);

  const createTask = ({
    defaultValue,
    option,
    name,
    check = () => true,
    command,
    pre = [],
    order,
  }) => ({
    value: false,
    defaultValue: defaultValue || false,
    option: option || undefined,
    name: name || 'unnamed task',
    check: check || (() => true),
    order,
    command: () => {
      // run all pre tasks
      pre
        .map((key) => tasks[key])
        .forEach((task) => {
          if (task.check()) {
            task.command();
          }
        });

      log.info(prefix, name);
      command();
    },
  });

  const tasks = {
    core: createTask({
      name: `Core, Dll & Examples ${chalk.gray('(core)')}`,
      defaultValue: true,
      option: '--core',
      command: () => {
        log.info(prefix, 'yarn workspace');
      },
      pre: ['install', 'build', 'dll'],
      order: 1,
    }),
    reset: createTask({
      name: `Clean repository ${chalk.red('(reset)')}`,
      defaultValue: false,
      option: '--reset',
      command: () => {
        log.info(prefix, 'git clean');
        spawn('node -r esm ./scripts/reset.js');
      },
      order: 0,
    }),
    install: createTask({
      name: `Install dependencies ${chalk.gray('(install)')}`,
      defaultValue: false,
      option: '--install',
      command: () => {
        spawn('yarn install --ignore-optional --network-concurrency 8');
      },
      order: 1,
    }),
    build: createTask({
      name: `Build packages ${chalk.gray('(build)')}`,
      defaultValue: false,
      option: '--build',
      command: () => {
        log.info(prefix, 'prepare');
        spawn('lerna run prepare');
      },
      order: 2,
    }),
    dll: createTask({
      name: `Generate DLL ${chalk.gray('(dll)')}`,
      defaultValue: false,
      option: '--dll',
      command: () => {
        log.info(prefix, 'dll');
        setTimeout(() => {
          spawn('lerna run createDlls --scope "@storybook/ui" --scope "@storybook/addon-docs"');
        }, 5000);
      },
      order: 3,
    }),
    docs: createTask({
      name: `Documentation ${chalk.gray('(docs)')}`,
      defaultValue: false,
      option: '--docs',
      command: () => {
        spawn('yarn bootstrap:docs');
      },
      order: 6,
    }),
    packs: createTask({
      name: `Build tarballs of packages ${chalk.gray('(build-packs)')}`,
      defaultValue: false,
      option: '--packs',
      command: () => {
        spawn('yarn build-packs');
      },
      check: () => getDirectories(join(__dirname, '..', 'packs')).length === 0,
      order: 5,
    }),
    registry: createTask({
      name: `Run local registry ${chalk.gray('(reg)')}`,
      defaultValue: false,
      option: '--reg',
      command: () => {
        spawn('./scripts/run-registry.js');
      },
      order: 11,
    }),
    dev: createTask({
      name: `Run build in watch mode ${chalk.gray('(dev)')}`,
      defaultValue: false,
      option: '--dev',
      command: () => {
        spawn('yarn dev');
      },
      order: 9,
    }),
  };

  const groups = {
    main: ['core', 'docs'],
    buildtasks: ['install', 'build', 'dll', 'packs'],
    devtasks: ['dev', 'registry', 'reset'],
  };

  Object.keys(tasks)
    .reduce((acc, key) => acc.option(tasks[key].option, tasks[key].name), main)
    .parse(process.argv);

  Object.keys(tasks).forEach((key) => {
    tasks[key].value = program[tasks[key].option.replace('--', '')] || program.all;
  });

  const createSeperator = (input) => `- ${input}${' ---------'.substr(0, 12)}`;

  const choices = Object.values(groups)
    .map((l) =>
      l.map((key) => ({
        name: tasks[key].name,
        checked: tasks[key].defaultValue,
      }))
    )
    .reduce(
      (acc, i, k) =>
        acc.concat(new inquirer.Separator(createSeperator(Object.keys(groups)[k]))).concat(i),
      []
    );

  let selection;
  if (
    !Object.keys(tasks)
      .map((key) => tasks[key].value)
      .filter(Boolean).length
  ) {
    selection = inquirer
      .prompt([
        {
          type: 'checkbox',
          message: 'Select the bootstrap activities',
          name: 'todo',
          pageSize: Object.keys(tasks).length + Object.keys(groups).length,
          choices,
        },
      ])
      .then(({ todo }) =>
        todo.map((name) => tasks[Object.keys(tasks).find((i) => tasks[i].name === name)])
      )
      .then((list) => {
        if (list.find((i) => i === tasks.reset)) {
          return inquirer
            .prompt([
              {
                type: 'confirm',
                message: `${chalk.red(
                  'DESTRUCTIVE'
                )} deletes node_modules, files not present in git ${chalk.underline(
                  'will get trashed'
                )}, except for .idea and .vscode, ${chalk.cyan('Continue?')}`,
                name: 'sure',
              },
            ])
            .then(({ sure }) => {
              if (sure) {
                return list;
              }
              throw new Error('problem is between keyboard and chair');
            });
        }
        return list;
      });
  } else {
    selection = Promise.resolve(
      Object.keys(tasks)
        .map((key) => tasks[key])
        .filter((item) => item.value === true)
    );
  }

  selection
    .then((list) => {
      if (list.length === 0) {
        log.warn(prefix, 'Nothing to bootstrap');
      } else {
        list
          .sort((a, b) => a.order - b.order)
          .forEach((key) => {
            key.command();
          });
        process.stdout.write('\x07');
      }
    })
    .catch((e) => {
      log.aborted(prefix, chalk.red(e.message));
      log.silly(prefix, e);
      process.exit(1);
    });
}
<commit_msg>refactor(bootstrap): use common code from cli-utils<commit_after>#!/usr/bin/env node

/* eslint-disable global-require */
const { lstatSync, readdirSync } = require('fs');
const { join } = require('path');
const { checkDependenciesAndRun, spawn } = require('./cli-utils');

function run() {
  const inquirer = require('inquirer');
  const program = require('commander');
  const chalk = require('chalk');
  const log = require('npmlog');

  const isTgz = (source) => lstatSync(source).isFile() && source.match(/.tgz$/);
  const getDirectories = (source) =>
    readdirSync(source)
      .map((name) => join(source, name))
      .filter(isTgz);

  log.heading = 'storybook';
  const prefix = 'bootstrap';
  log.addLevel('aborted', 3001, { fg: 'red', bold: true });

  const main = program
    .version('5.0.0')
    .option('--all', `Bootstrap everything ${chalk.gray('(all)')}`);

  const createTask = ({
    defaultValue,
    option,
    name,
    check = () => true,
    command,
    pre = [],
    order,
  }) => ({
    value: false,
    defaultValue: defaultValue || false,
    option: option || undefined,
    name: name || 'unnamed task',
    check: check || (() => true),
    order,
    command: () => {
      // run all pre tasks
      pre
        .map((key) => tasks[key])
        .forEach((task) => {
          if (task.check()) {
            task.command();
          }
        });

      log.info(prefix, name);
      command();
    },
  });

  const tasks = {
    core: createTask({
      name: `Core, Dll & Examples ${chalk.gray('(core)')}`,
      defaultValue: true,
      option: '--core',
      command: () => {
        log.info(prefix, 'yarn workspace');
      },
      pre: ['install', 'build', 'dll'],
      order: 1,
    }),
    reset: createTask({
      name: `Clean repository ${chalk.red('(reset)')}`,
      defaultValue: false,
      option: '--reset',
      command: () => {
        log.info(prefix, 'git clean');
        spawn('node -r esm ./scripts/reset.js');
      },
      order: 0,
    }),
    install: createTask({
      name: `Install dependencies ${chalk.gray('(install)')}`,
      defaultValue: false,
      option: '--install',
      command: () => {
        spawn('yarn install --ignore-optional --network-concurrency 8');
      },
      order: 1,
    }),
    build: createTask({
      name: `Build packages ${chalk.gray('(build)')}`,
      defaultValue: false,
      option: '--build',
      command: () => {
        log.info(prefix, 'prepare');
        spawn('lerna run prepare');
      },
      order: 2,
    }),
    dll: createTask({
      name: `Generate DLL ${chalk.gray('(dll)')}`,
      defaultValue: false,
      option: '--dll',
      command: () => {
        log.info(prefix, 'dll');
        setTimeout(() => {
          spawn('lerna run createDlls --scope "@storybook/ui" --scope "@storybook/addon-docs"');
        }, 5000);
      },
      order: 3,
    }),
    docs: createTask({
      name: `Documentation ${chalk.gray('(docs)')}`,
      defaultValue: false,
      option: '--docs',
      command: () => {
        spawn('yarn bootstrap:docs');
      },
      order: 6,
    }),
    packs: createTask({
      name: `Build tarballs of packages ${chalk.gray('(build-packs)')}`,
      defaultValue: false,
      option: '--packs',
      command: () => {
        spawn('yarn build-packs');
      },
      check: () => getDirectories(join(__dirname, '..', 'packs')).length === 0,
      order: 5,
    }),
    registry: createTask({
      name: `Run local registry ${chalk.gray('(reg)')}`,
      defaultValue: false,
      option: '--reg',
      command: () => {
        spawn('./scripts/run-registry.js');
      },
      order: 11,
    }),
    dev: createTask({
      name: `Run build in watch mode ${chalk.gray('(dev)')}`,
      defaultValue: false,
      option: '--dev',
      command: () => {
        spawn('yarn dev');
      },
      order: 9,
    }),
  };

  const groups = {
    main: ['core', 'docs'],
    buildtasks: ['install', 'build', 'dll', 'packs'],
    devtasks: ['dev', 'registry', 'reset'],
  };

  Object.keys(tasks)
    .reduce((acc, key) => acc.option(tasks[key].option, tasks[key].name), main)
    .parse(process.argv);

  Object.keys(tasks).forEach((key) => {
    tasks[key].value = program[tasks[key].option.replace('--', '')] || program.all;
  });

  const createSeperator = (input) => `- ${input}${' ---------'.substr(0, 12)}`;

  const choices = Object.values(groups)
    .map((l) =>
      l.map((key) => ({
        name: tasks[key].name,
        checked: tasks[key].defaultValue,
      }))
    )
    .reduce(
      (acc, i, k) =>
        acc.concat(new inquirer.Separator(createSeperator(Object.keys(groups)[k]))).concat(i),
      []
    );

  let selection;
  if (
    !Object.keys(tasks)
      .map((key) => tasks[key].value)
      .filter(Boolean).length
  ) {
    selection = inquirer
      .prompt([
        {
          type: 'checkbox',
          message: 'Select the bootstrap activities',
          name: 'todo',
          pageSize: Object.keys(tasks).length + Object.keys(groups).length,
          choices,
        },
      ])
      .then(({ todo }) =>
        todo.map((name) => tasks[Object.keys(tasks).find((i) => tasks[i].name === name)])
      )
      .then((list) => {
        if (list.find((i) => i === tasks.reset)) {
          return inquirer
            .prompt([
              {
                type: 'confirm',
                message: `${chalk.red(
                  'DESTRUCTIVE'
                )} deletes node_modules, files not present in git ${chalk.underline(
                  'will get trashed'
                )}, except for .idea and .vscode, ${chalk.cyan('Continue?')}`,
                name: 'sure',
              },
            ])
            .then(({ sure }) => {
              if (sure) {
                return list;
              }
              throw new Error('problem is between keyboard and chair');
            });
        }
        return list;
      });
  } else {
    selection = Promise.resolve(
      Object.keys(tasks)
        .map((key) => tasks[key])
        .filter((item) => item.value === true)
    );
  }

  selection
    .then((list) => {
      if (list.length === 0) {
        log.warn(prefix, 'Nothing to bootstrap');
      } else {
        list
          .sort((a, b) => a.order - b.order)
          .forEach((key) => {
            key.command();
          });
        process.stdout.write('\x07');
      }
    })
    .catch((e) => {
      log.aborted(prefix, chalk.red(e.message));
      log.silly(prefix, e);
      process.exit(1);
    });
}

checkDependenciesAndRun(run);
<|endoftext|>


<commit_before>var _ = require('lodash');

module.exports = function(robot) {
    robot.hear(/\(tableflip\)/i, function(res) {
    	res.reply("Please Respect Tables   ┬─┬ノ(ಠ_ಠノ)");
    });

    robot.hear(/jose/i, function (res) {
        res.send("(trolljose)");
    });

    robot.respond(/jose bomb( (\d+))?/i, function (msg) {
        var count = msg.match[2] || 5;
        for(var i = 0; i < count - 1; i++) {
            msg.send("(trolljose)");
        }
    });

    // robot.respond(/you suck/i, function(res) {
    // 	res.reply("\n\n....................../´¯/)\n....................,/¯../\n.................../..../\n............./´¯¯¯/'...'/´¯¯¯/`\n........../'/.../..../....././¨¯\\\n........('(...´...´.... ¯~/'...')\n.........\\.................'...../\n..........\\.................../\n............\\..............(\n..............\\.............\\....");
    // });

    var meanArray = [
    	'http://cdn.meme.am/instances/500x/53668178.jpg',
    	'http://cdn.meme.am/instances/400x/55364004.jpg',
    	'http://www.quickmeme.com/img/ab/abeee7d0019009857f3f87789e1913bad8da23b29881d920c5c8fc7038a75e7b.jpg',
    	'http://cdn.meme.am/instances/500x/52615916.jpg',
    	'http://i.qkme.me/3qf8sl.jpg',
    	'http://cdn.meme.am/instances/400x/54388732.jpg'

    ];

    robot.hear(/(you suck|you son of a bitch|damnit cubot|I hate you|(you are|you're) (the worst|terrible))/i, function(res) {
    	res.send(res.random(meanArray));
    });

    robot.hear(/testing 123/i, function(msg) {
        msg.send('/code ' + JSON.stringify(msg.envelope));
    });
};<commit_msg>Testing again<commit_after>var _ = require('lodash');

module.exports = function(robot) {
    robot.hear(/\(tableflip\)/i, function(res) {
    	res.reply("Please Respect Tables   ┬─┬ノ(ಠ_ಠノ)");
    });

    robot.hear(/jose/i, function (res) {
        res.send("(trolljose)");
    });

    robot.respond(/jose bomb( (\d+))?/i, function (msg) {
        var count = msg.match[2] || 5;
        for(var i = 0; i < count - 1; i++) {
            msg.send("(trolljose)");
        }
    });

    // robot.respond(/you suck/i, function(res) {
    // 	res.reply("\n\n....................../´¯/)\n....................,/¯../\n.................../..../\n............./´¯¯¯/'...'/´¯¯¯/`\n........../'/.../..../....././¨¯\\\n........('(...´...´.... ¯~/'...')\n.........\\.................'...../\n..........\\.................../\n............\\..............(\n..............\\.............\\....");
    // });

    var meanArray = [
    	'http://cdn.meme.am/instances/500x/53668178.jpg',
    	'http://cdn.meme.am/instances/400x/55364004.jpg',
    	'http://www.quickmeme.com/img/ab/abeee7d0019009857f3f87789e1913bad8da23b29881d920c5c8fc7038a75e7b.jpg',
    	'http://cdn.meme.am/instances/500x/52615916.jpg',
    	'http://i.qkme.me/3qf8sl.jpg',
    	'http://cdn.meme.am/instances/400x/54388732.jpg'

    ];

    robot.hear(/(you suck|you son of a bitch|damnit cubot|I hate you|(you are|you're) (the worst|terrible))/i, function(res) {
    	res.send(res.random(meanArray));
    });

    robot.hear(/testing 123/i, function(msg) {
        var roomId = msg.envelope.user.reply_to.split('_')[0];
        msg.send('/code ' + roomId);
    });
};<|endoftext|>


<commit_before>// dependencies
// Interface for Google Deepdream
var _ = require('lodash')
var fs = require('fs')
var runDeepdream = require('../lib/deepdream')

// quick test scripts
module.exports = function(robot) {
  robot.catchAll(/.+/, function(res) {
    // only telegram for now
    if (robot.adapterName != 'telegram') { return };
    if (_.has(res.message, 'photo')) {
      console.log("receiving photo")
      res.reply('running DeepDream. This may take up to 5 minutes :)')
      runDeepdream(res.message)
      .then(function(outFilepath) {
        console.log('made it out', outFilepath)
        robot.emit('telegram:invoke', 'sendPhoto', { chat_id: res.message.from.id, photo: fs.createReadStream(outFilepath) }, function (error, response) {
          if (err) { console.log(err) };
        });
      })
      .catch(console.log)
    };
  })
}
<commit_msg>add lomath to scripts/deepdream<commit_after>// dependencies
// Interface for Google Deepdream
var _ = require('lomath')
var fs = require('fs')
var runDeepdream = require('../lib/deepdream')

// quick test scripts
module.exports = function(robot) {
  robot.catchAll(/.+/, function(res) {
    // only telegram for now
    if (robot.adapterName != 'telegram') { return };
    if (_.has(res.message, 'photo')) {
      console.log("receiving photo")
      res.reply('running DeepDream. This may take up to 5 minutes :)')
      runDeepdream(res.message)
      .then(function(outFilepath) {
        console.log('made it out', outFilepath)
        robot.emit('telegram:invoke', 'sendPhoto', { chat_id: res.message.from.id, photo: fs.createReadStream(outFilepath) }, function (error, response) {
          if (err) { console.log(err) };
        });
      })
      .catch(console.log)
    };
  })
}
<|endoftext|>


<commit_before>"use strict";
var LineMessaging = require('hubot-line-messaging-api');
var StickerMessage = require('hubot-line-messaging-api').StickerMessage;
var PostbackMessage = require('hubot-line-messaging-api').PostbackMessage;
var SendSticker = LineMessaging.SendSticker;
var SendLocation = LineMessaging.SendLocation;
var SendImage = LineMessaging.SendImage;
var SendVideo = LineMessaging.SendVideo;
var SendAudio = LineMessaging.SendAudio;
var SendText = LineMessaging.SendText;
var comic = require('../db/models/comic.js');

const BuildTemplateMessage = LineMessaging.BuildTemplateMessage;

const LINE_TOKEN = process.env.HUBOT_LINE_TOKEN;

module.exports = function(robot){
  var filterStickers = function(message){
    var result = false;
    var stickerMsg = message.message;
    if (stickerMsg && stickerMsg.type && stickerMsg.type === 'sticker'){
      result = true;
    }
    // Not implement listener, so should CatchAllMessage.message
    //console.log("message: ", message);
    var user = message.user;
    robot.brain.set('USER:' + user.id, user);
    return result;
  };

  var filterPostback = function(message){
    var result = false;
    var postbackMsg = message.message;
    if (postbackMsg && postbackMsg.type && postbackMsg.type === 'postback'){
      console.log(message.message);
      result = true;
      // TODO save to database
    }
    //console.log('filterPostback', result);
    return result;
  }

  robot.listen(filterPostback, function(res){
    //console.log('reply postback');
    // push API
    //console.log(res);
    //var text = new SendText('已訂閱完成，謝謝');
    //res.reply(text);
    console.log(res.message.message.postback);
  });

  robot.listen(filterStickers, function(res){
    var stickerMessage = res.message.message;
    // This line is necessary to prevent error
    res.envelope.message = stickerMessage;
    var sticker = new SendSticker(stickerMessage.stickerId, stickerMessage.packageId);
    res.reply(sticker);
  });

  robot.respond(/hello/i, function(res){
    res.reply('world');
  });

  robot.hear(/profile/i, function(res){
    console.log("HUBOT_LINE_TOKEN ", LINE_TOKEN);
    console.log("USERID " , res.message.user.id);
    robot.http("https://api.line.me/v2/bot/profile/" + res.message.user.id)
      .header('Authorization', "Bearer " + LINE_TOKEN)
      .get()(function(err, resp, body) {
        console.log('RESP ', resp);
        console.log('BODY ', body);
        var respBody = JSON.parse(body);
        res.reply('你好，' + respBody.displayName + "，使用者ID " + res.message.user.id);
      });
  });

  robot.hear(/help/i, function(res){
    var text1 = new SendText('輸入 [subscribe]，即可享受訂閱推播服務');
    var text2 = new SendText('輸入 [list]，即可顯示Top 3推薦漫畫');
    var text3 = new SendText('輸入 [profile]，顯示個人資訊');

    res.reply(text1, text2, text3);
  });

  robot.hear(/b/i, function(res){
    var msg = BuildTemplateMessage
      .init('this is a template msg')
      .buttons({
        thumbnailImageUrl: 'https://github.com/puresmash/chatting-robot/blob/develope/docs/template.jpg?raw=true',
        title: 'Template Message',
        text: 'Let me google for you'
      })
      .action('uri', {
        label: 'Open Google',
        uri: 'https://www.google.com.tw/'
      })
      .action('postback', {
        label: 'postback',
        data: 'test=a'
      })
      .build();
    res.reply(msg);
  });

  // robot.hear(/s/i, function(res){
  //   var msg = BuildTemplateMessage
  //   .init('this is a confirm msg')
  //   .confirm({
  //       text: 'confirm?'
  //   })
  //   .action('uri', {
  //       label: 'OK',
  //       uri: 'https://www.google.com.tw/search?q=ok'
  //   })
  //   .action('message', {
  //       label: 'Cancel',
  //       text: 'cancel request'
  //   })
  //   .build();
  //   res.reply(msg);
  // });

  /**
   * Image URL (Max: 1000 characters)
   * HTTPS
   * JPEG or PNG
   * Aspect ratio: 1:1.51
   * Max width: 1024px
   * Max: 1 MB
   *
   * 訂閱後收到 postback 這邊可以提供付費功能
   */
  robot.hear(/list/i, function(res){
    var msg = BuildTemplateMessage
    .init('this is a carousel msg')
    .carousel({
        thumbnailImageUrl: 'https://github.com/puresmash/chatting-robot/blob/develope/docs/template.jpg?raw=true',
        title: 'Carousel Message 1',
        text: 'text1'
    })
    .action('uri', {
        label: 'Open Google',
        uri: 'https://www.google.com.tw/'
    })
    .action('postback', {
        label: 'subscribe',
        data: 'test=a&p=b'
    })
    .carousel({
        thumbnailImageUrl: 'https://github.com/puresmash/chatting-robot/blob/develope/docs/carousel.jpg?raw=true',
        title: 'Carousel Message 2',
        text: 'text2'
    })
    .action('uri', {
        label: 'Adapter Link',
        uri: 'https://github.com/puresmash/hubot-line-messaging'
    })
    .action('postback', {
        label: 'subscribe',
        data: 'test=b&p=c'
    })
    .build();
    res.reply(msg);
    //var comicList = comic.readAll().then(function(result){
      // var msgObj = BuildTemplateMessage.init('Comic list');
      // var count = 0;
      // result.rows.forEach(function(data){
        // console.log('comic data', data);
      //   if (count == 0) {
      //     msgObj = BuildTemplateMessage.init('Comic list')
      //     .carousel({
      //       thumbnailImageUrl: data.thumbnail,
      //       title: data.comicname,
      //       text: data.lastvolnumber
      //     })
      //     .action('postback', {
      //       label: '線上觀看',
      //       data: 'viewOnline'
      //     })
      //     .action('postback', {
      //       label: '訂閱[' + data.comicname + ']',
      //       data: 'subscribe'
      //     });
      //   } else {
      //     msgObj
      //     .carousel({
      //       thumbnailImageUrl: data.thumbnail,
      //       title: data.comicname,
      //       text: data.lastvolnumber
      //     })
      //     .action('postback', {
      //       label: '線上觀看',
      //       data: 'viewOnline'
      //     })
      //     .action('postback', {
      //       label: '訂閱[' + data.comicname + ']',
      //       data: 'subscribe'
      //     });
      //   }
      //   count++;
      //   console.log('count: ' + count + ', msgObj: ', msgObj);
      // });
      // msgObj.build();
      // res.reply("yes");
    // });
  });

  robot.hear(/test/i, function(res){
    var comicList = comic.readAll().then(function(result){
      res.reply(buildCarousel("comic list", result));
    });
  });

  function buildCarousel(altText, result) {
    var columns = [];
    result.rows.forEach(function(data){
      var carousel = {
        "thumbnailImageUrl": data.thumbnail,
        "title": data.comicname,
        "text": data.lastvolnumber,
        "actions": [
          {
            "type": "url",
            "label": "線上觀看",
            "uri": "https://github.com/Ksetra/morphling"
          },
          {
            "type": "postback",
            "label": "訂閱[" + data.comicname + "]",
            "data": "action=subscrbe&comic=" + data.id
          }
        ]
      };
      columns.push(carousel);
    });
    var obj = {
      "type": "template",
      "altText": altText,
      "template": {
          "type": "carousel",
          "columns": columns
      }
    }
    console.log('obj', obj);
    return obj;
  }

  // function buildCarouselColumns(result) {
  //   var columns = [];
  //   result.rows.forEach(function(data){
  //     var carousel = {
  //       "thumbnailImageUrl": data.thumbnail,
  //       "title": data.comicname,
  //       "text": data.lastvolnumber,
  //       "actions": [
  //         {
  //           "type": "url",
  //           "label": "線上觀看",
  //           "uri": "https://github.com/Ksetra/morphling"
  //         },
  //         {
  //           "type": "postback",
  //           "label": "訂閱[" + data.comicname + "]",
  //           "data": "action=subscrbe&comic=" + data.id
  //         }
  //       ]
  //     };
  //     columns.push(carousel);
  //   });
  //   return columns;
  // }

  // function msgCarousel(msgObj, data){
  //   msgObj.carousel({
  //     thumbnailImageUrl: data.thumbnail,
  //     title: data.comicname,
  //     text: data.lastvolnumber
  //   })
  //   .action('postback', {
  //     label: '線上觀看',
  //     data: 'viewOnline'
  //   })
  //   .action('postback', {
  //     label: '訂閱[' + data.comicname + ']',
  //     data: 'subscribe'
  //   });
  //   console.log('msgObj: ', msgObj);
  //   return msgObj;
  // }

};
<commit_msg>update<commit_after>"use strict";
var LineMessaging = require('hubot-line-messaging-api');
var StickerMessage = require('hubot-line-messaging-api').StickerMessage;
var PostbackMessage = require('hubot-line-messaging-api').PostbackMessage;
var SendSticker = LineMessaging.SendSticker;
var SendLocation = LineMessaging.SendLocation;
var SendImage = LineMessaging.SendImage;
var SendVideo = LineMessaging.SendVideo;
var SendAudio = LineMessaging.SendAudio;
var SendText = LineMessaging.SendText;
var comic = require('../db/models/comic.js');

const BuildTemplateMessage = LineMessaging.BuildTemplateMessage;

const LINE_TOKEN = process.env.HUBOT_LINE_TOKEN;

module.exports = function(robot){
  var filterStickers = function(message){
    var result = false;
    var stickerMsg = message.message;
    if (stickerMsg && stickerMsg.type && stickerMsg.type === 'sticker'){
      result = true;
    }
    // Not implement listener, so should CatchAllMessage.message
    //console.log("message: ", message);
    var user = message.user;
    robot.brain.set('USER:' + user.id, user);
    return result;
  };

  var filterPostback = function(message){
    var result = false;
    var postbackMsg = message.message;
    if (postbackMsg && postbackMsg.type && postbackMsg.type === 'postback'){
      console.log(message.message);
      result = true;
      // TODO save to database
    }
    //console.log('filterPostback', result);
    return result;
  }

  robot.listen(filterPostback, function(res){
    //console.log('reply postback');
    // push API
    //console.log(res);
    //var text = new SendText('已訂閱完成，謝謝');
    //res.reply(text);
    console.log(res.message.message.postback);
  });

  robot.listen(filterStickers, function(res){
    var stickerMessage = res.message.message;
    // This line is necessary to prevent error
    res.envelope.message = stickerMessage;
    var sticker = new SendSticker(stickerMessage.stickerId, stickerMessage.packageId);
    res.reply(sticker);
  });

  robot.respond(/hello/i, function(res){
    res.reply('world');
  });

  robot.hear(/profile/i, function(res){
    console.log("HUBOT_LINE_TOKEN ", LINE_TOKEN);
    console.log("USERID " , res.message.user.id);
    robot.http("https://api.line.me/v2/bot/profile/" + res.message.user.id)
      .header('Authorization', "Bearer " + LINE_TOKEN)
      .get()(function(err, resp, body) {
        console.log('RESP ', resp);
        console.log('BODY ', body);
        var respBody = JSON.parse(body);
        res.reply('你好，' + respBody.displayName + "，使用者ID " + res.message.user.id);
      });
  });

  robot.hear(/help/i, function(res){
    var text1 = new SendText('輸入 [subscribe]，即可享受訂閱推播服務');
    var text2 = new SendText('輸入 [list]，即可顯示Top 3推薦漫畫');
    var text3 = new SendText('輸入 [profile]，顯示個人資訊');

    res.reply(text1, text2, text3);
  });

  robot.hear(/b/i, function(res){
    var msg = BuildTemplateMessage
      .init('this is a template msg')
      .buttons({
        thumbnailImageUrl: 'https://github.com/puresmash/chatting-robot/blob/develope/docs/template.jpg?raw=true',
        title: 'Template Message',
        text: 'Let me google for you'
      })
      .action('uri', {
        label: 'Open Google',
        uri: 'https://www.google.com.tw/'
      })
      .action('postback', {
        label: 'postback',
        data: 'test=a'
      })
      .build();
    res.reply(msg);
  });

  // robot.hear(/s/i, function(res){
  //   var msg = BuildTemplateMessage
  //   .init('this is a confirm msg')
  //   .confirm({
  //       text: 'confirm?'
  //   })
  //   .action('uri', {
  //       label: 'OK',
  //       uri: 'https://www.google.com.tw/search?q=ok'
  //   })
  //   .action('message', {
  //       label: 'Cancel',
  //       text: 'cancel request'
  //   })
  //   .build();
  //   res.reply(msg);
  // });

  /**
   * Image URL (Max: 1000 characters)
   * HTTPS
   * JPEG or PNG
   * Aspect ratio: 1:1.51
   * Max width: 1024px
   * Max: 1 MB
   *
   * 訂閱後收到 postback 這邊可以提供付費功能
   */
  robot.hear(/list/i, function(res){
    var msg = BuildTemplateMessage
    .init('this is a carousel msg')
    .carousel({
        thumbnailImageUrl: 'https://github.com/puresmash/chatting-robot/blob/develope/docs/template.jpg?raw=true',
        title: 'Carousel Message 1',
        text: 'text1'
    })
    .action('uri', {
        label: 'Open Google',
        uri: 'https://www.google.com.tw/'
    })
    .action('postback', {
        label: 'subscribe',
        data: 'test=a&p=b'
    })
    .carousel({
        thumbnailImageUrl: 'https://github.com/puresmash/chatting-robot/blob/develope/docs/carousel.jpg?raw=true',
        title: 'Carousel Message 2',
        text: 'text2'
    })
    .action('uri', {
        label: 'Adapter Link',
        uri: 'https://github.com/puresmash/hubot-line-messaging'
    })
    .action('postback', {
        label: 'subscribe',
        data: 'test=b&p=c'
    })
    .build();
    res.reply(msg);
    //var comicList = comic.readAll().then(function(result){
      // var msgObj = BuildTemplateMessage.init('Comic list');
      // var count = 0;
      // result.rows.forEach(function(data){
        // console.log('comic data', data);
      //   if (count == 0) {
      //     msgObj = BuildTemplateMessage.init('Comic list')
      //     .carousel({
      //       thumbnailImageUrl: data.thumbnail,
      //       title: data.comicname,
      //       text: data.lastvolnumber
      //     })
      //     .action('postback', {
      //       label: '線上觀看',
      //       data: 'viewOnline'
      //     })
      //     .action('postback', {
      //       label: '訂閱[' + data.comicname + ']',
      //       data: 'subscribe'
      //     });
      //   } else {
      //     msgObj
      //     .carousel({
      //       thumbnailImageUrl: data.thumbnail,
      //       title: data.comicname,
      //       text: data.lastvolnumber
      //     })
      //     .action('postback', {
      //       label: '線上觀看',
      //       data: 'viewOnline'
      //     })
      //     .action('postback', {
      //       label: '訂閱[' + data.comicname + ']',
      //       data: 'subscribe'
      //     });
      //   }
      //   count++;
      //   console.log('count: ' + count + ', msgObj: ', msgObj);
      // });
      // msgObj.build();
      // res.reply("yes");
    // });
  });

  robot.hear(/test/i, function(res){
    var comicList = comic.readAll().then(function(result){
      res.reply(buildCarousel("comic list", result));
    });
  });

  function buildCarousel(altText, result) {
    var columns = [];
    result.rows.forEach(function(data){
      var carousel = {
        "thumbnailImageUrl": data.thumbnail,
        "title": data.comicname,
        "text": data.lastvolnumber,
        "actions": [
          {
            "type": "url",
            "label": "線上觀看",
            "uri": "https://github.com/Ksetra/morphling"
          },
          {
            "type": "postback",
            "label": "訂閱[" + data.comicname + "]",
            "data": "action=subscribe&comic=" + data.id
          }
        ]
      };
      columns.push(carousel);
    });
    console.log(columns);
    var obj = {
      "type": "template",
      "altText": altText,
      "template": {
          "type": "carousel",
          "columns": columns
      }
    }
    console.log('obj', obj);
    return obj;
  }

  // function buildCarouselColumns(result) {
  //   var columns = [];
  //   result.rows.forEach(function(data){
  //     var carousel = {
  //       "thumbnailImageUrl": data.thumbnail,
  //       "title": data.comicname,
  //       "text": data.lastvolnumber,
  //       "actions": [
  //         {
  //           "type": "url",
  //           "label": "線上觀看",
  //           "uri": "https://github.com/Ksetra/morphling"
  //         },
  //         {
  //           "type": "postback",
  //           "label": "訂閱[" + data.comicname + "]",
  //           "data": "action=subscrbe&comic=" + data.id
  //         }
  //       ]
  //     };
  //     columns.push(carousel);
  //   });
  //   return columns;
  // }

  // function msgCarousel(msgObj, data){
  //   msgObj.carousel({
  //     thumbnailImageUrl: data.thumbnail,
  //     title: data.comicname,
  //     text: data.lastvolnumber
  //   })
  //   .action('postback', {
  //     label: '線上觀看',
  //     data: 'viewOnline'
  //   })
  //   .action('postback', {
  //     label: '訂閱[' + data.comicname + ']',
  //     data: 'subscribe'
  //   });
  //   console.log('msgObj: ', msgObj);
  //   return msgObj;
  // }

};
<|endoftext|>


<commit_before>"use strict";
var LineMessaging = require('hubot-line-messaging');
var StickerMessage = require('hubot-line-messaging').StickerMessage;
var SendSticker = LineMessaging.SendSticker;
var SendLocation = LineMessaging.SendLocation;
var SendImage = LineMessaging.SendImage;
var SendVideo = LineMessaging.SendVideo;
var SendAudio = LineMessaging.SendAudio;
var SendText = LineMessaging.SendText;

const BuildTemplateMessage = LineMessaging.BuildTemplateMessage;

const LINE_TOKEN = process.env.HUBOT_LINE_TOKEN;

module.exports = function(robot){
  var filterStickers = function(message){
    var result = false;
    var stickerMsg = message.message;
    if (stickerMsg && stickerMsg.type && stickerMsg.type === 'sticker'){
      result = true;
    }
    // Not implement listener, so should CatchAllMessage.message
    console.log("message: ", message);
    var user = message.user;
    robot.brain.set('USER:' + user.id, user);
    return result;
  };

  robot.listen(filterStickers, function(res){
    var stickerMessage = res.message.message;
    // This line is necessary to prevent error
    res.envelope.message = stickerMessage;
    var sticker = new SendSticker(stickerMessage.stickerId, stickerMessage.packageId);
    res.reply(sticker);
  });

  robot.respond(/hello/i, function(res){
    res.reply('world');
  });

  robot.hear(/profile/i, function(res){
    console.log("HUBOT_LINE_TOKEN ", LINE_TOKEN);
    console.log("USERID " , res.message.user.id);
    robot.http("https://api.line.me/v2/bot/profile/" + res.message.user.id)
      .header('Authorization', "Bearer " + LINE_TOKEN)
      .get()(function(err, resp, body) {
        console.log('RESP ', resp);
        console.log('BODY ', body);
        res.reply('你好，' + resp.displayName + "，使用者ID " + res.message.user.id);
      });
  });

  robot.hear(/help/i, function(res){
    var text1 = new SendText('輸入 [subscribe]，即可享受訂閱推播服務');
    var text2 = new SendText('輸入 [list]，即可顯示Top 3推薦漫畫');
    var text3 = new SendText('輸入 [profile]，顯示個人資訊');

    res.reply(text1, text2, text3);
  });

  robot.hear(/buttons/i, function(res){
    var msg = BuildTemplateMessage
      .init('this is a template msg')
      .buttons({
        thumbnailImageUrl: 'https://github.com/puresmash/chatting-robot/blob/develope/docs/template.jpg?raw=true',
        title: 'Template Message',
        text: 'Let me google for you'
      })
      .action('uri', {
        label: 'Open Google',
        uri: 'https://www.google.com.tw/'
      })
      .action('uri', {
        label: 'Adapter Link',
        uri: 'https://github.com/puresmash/hubot-line-messaging'
      })
      .build();
    res.reply(msg);
  });

  /**
   * Image URL (Max: 1000 characters)
   * HTTPS
   * JPEG or PNG
   * Aspect ratio: 1:1.51
   * Max width: 1024px
   * Max: 1 MB
   */
  robot.hear(/list/i, function(res){
    var msg = BuildTemplateMessage
      .init('this is a carousel msg')
      .carousel({
        thumbnailImageUrl: 'https://static.fzdm.com/manhua/img/2.jpg',
        title: '海賊王',
        text: '海賊王851話'
      })
      .action('uri', {
        label: '海賊王',
        uri: 'https://140.110.203.1/test_comicr/api/pageGet.php?title=%E6%B5%B7%E8%B3%8A%E7%8E%8B%E6%BC%AB%E7%95%AB&vol=2&comicLink=851'
      })
      .carousel({
        thumbnailImageUrl: 'https://static.fzdm.com/manhua/img/10.jpg',
        title: '獵人',
        text: '獵人360話'
      })
      .action('uri', {
        label: '獵人',
        uri: 'http://140.110.203.1/test_comicr/api/pageGet.php?title=%E7%8D%B5%E4%BA%BA%E6%BC%AB%E7%95%AB&vol=10&comicLink=360'
      })
      .carousel({
        thumbnailImageUrl: 'https://static.fzdm.com/manhua/img/1.jpg',
        title: '火影忍者',
        text: '火影忍者博人傳08話'
      })
      .action('uri', {
        label: '火影忍者',
        uri: 'http://140.110.203.1/test_comicr/api/pageGet.php?title=%E7%81%AB%E5%BD%B1%E5%BF%8D%E8%80%85%E6%BC%AB%E7%95%AB&vol=1&comicLink=brz08'
      })
      .build();
    res.reply(msg);
  });

  robot.hear(/subscribe/i, function(res){
    var msg = BuildTemplateMessage
      .init('訂閱漫畫')
      .confirm({
        text: '訂閱海賊王?'
      })
      .action('postback', {
        label: '訂閱',
        //data: 'subscribe=true&comic=02'
        text: '訂閱成功'
        //uri: 'https://www.google.com.tw/search?q=ok'
      })
      .action('message', {
        label: '取消',
        text: '太可惜了'
      })
      .build();
    res.reply(msg);
  });
};
<commit_msg>update<commit_after>"use strict";
var LineMessaging = require('hubot-line-messaging');
var StickerMessage = require('hubot-line-messaging').StickerMessage;
var SendSticker = LineMessaging.SendSticker;
var SendLocation = LineMessaging.SendLocation;
var SendImage = LineMessaging.SendImage;
var SendVideo = LineMessaging.SendVideo;
var SendAudio = LineMessaging.SendAudio;
var SendText = LineMessaging.SendText;

const BuildTemplateMessage = LineMessaging.BuildTemplateMessage;

const LINE_TOKEN = process.env.HUBOT_LINE_TOKEN;

module.exports = function(robot){
  var filterStickers = function(message){
    var result = false;
    var stickerMsg = message.message;
    if (stickerMsg && stickerMsg.type && stickerMsg.type === 'sticker'){
      result = true;
    }
    // Not implement listener, so should CatchAllMessage.message
    console.log("message: ", message);
    var user = message.user;
    robot.brain.set('USER:' + user.id, user);
    return result;
  };

  robot.listen(filterStickers, function(res){
    var stickerMessage = res.message.message;
    // This line is necessary to prevent error
    res.envelope.message = stickerMessage;
    var sticker = new SendSticker(stickerMessage.stickerId, stickerMessage.packageId);
    res.reply(sticker);
  });

  robot.respond(/hello/i, function(res){
    res.reply('world');
  });

  robot.hear(/profile/i, function(res){
    console.log("HUBOT_LINE_TOKEN ", LINE_TOKEN);
    console.log("USERID " , res.message.user.id);
    robot.http("https://api.line.me/v2/bot/profile/" + res.message.user.id)
      .header('Authorization', "Bearer " + LINE_TOKEN)
      .get()(function(err, resp, body) {
        console.log('RESP ', resp);
        console.log('BODY ', body);
        var respBody = JSON.parse(body);
        res.reply('你好，' + respBody.displayName + "，使用者ID " + res.message.user.id);
      });
  });

  robot.hear(/help/i, function(res){
    var text1 = new SendText('輸入 [subscribe]，即可享受訂閱推播服務');
    var text2 = new SendText('輸入 [list]，即可顯示Top 3推薦漫畫');
    var text3 = new SendText('輸入 [profile]，顯示個人資訊');

    res.reply(text1, text2, text3);
  });

  robot.hear(/buttons/i, function(res){
    var msg = BuildTemplateMessage
      .init('this is a template msg')
      .buttons({
        thumbnailImageUrl: 'https://github.com/puresmash/chatting-robot/blob/develope/docs/template.jpg?raw=true',
        title: 'Template Message',
        text: 'Let me google for you'
      })
      .action('uri', {
        label: 'Open Google',
        uri: 'https://www.google.com.tw/'
      })
      .action('uri', {
        label: 'Adapter Link',
        uri: 'https://github.com/puresmash/hubot-line-messaging'
      })
      .build();
    res.reply(msg);
  });

  /**
   * Image URL (Max: 1000 characters)
   * HTTPS
   * JPEG or PNG
   * Aspect ratio: 1:1.51
   * Max width: 1024px
   * Max: 1 MB
   */
  robot.hear(/list/i, function(res){
    var msg = BuildTemplateMessage
      .init('Comic list')
      .carousel({
        thumbnailImageUrl: 'https://static.fzdm.com/manhua/img/2.jpg',
        title: '海賊王',
        text: '海賊王851話'
      })
      .action('uri', {
        label: '線上觀看',
        uri: 'https://140.110.203.1/test_comicr/api/pageGet.php?title=%E6%B5%B7%E8%B3%8A%E7%8E%8B%E6%BC%AB%E7%95%AB&vol=2&comicLink=851'
      })
      .action('postback', {
        lable: '訂閱[海賊王]',
        data: 'subscribe=true&comic=2'
      })
      .carousel({
        thumbnailImageUrl: 'https://static.fzdm.com/manhua/img/10.jpg',
        title: '獵人',
        text: '獵人360話'
      })
      .action('uri', {
        label: '線上觀看',
        uri: 'http://140.110.203.1/test_comicr/api/pageGet.php?title=%E7%8D%B5%E4%BA%BA%E6%BC%AB%E7%95%AB&vol=10&comicLink=360'
      })
      .action('postback', {
        lable: '訂閱[獵人]',
        data: 'subscribe=true&comic=10'
      })
      .carousel({
        thumbnailImageUrl: 'https://static.fzdm.com/manhua/img/1.jpg',
        title: '火影忍者',
        text: '火影忍者博人傳08話'
      })
      .action('uri', {
        label: '線上觀看',
        uri: 'http://140.110.203.1/test_comicr/api/pageGet.php?title=%E7%81%AB%E5%BD%B1%E5%BF%8D%E8%80%85%E6%BC%AB%E7%95%AB&vol=1&comicLink=brz08'
      })
      .action('postback', {
        lable: '訂閱[火影忍者]',
        data: 'subscribe=true&comic=1'
      })
      .build();
    res.reply(msg);
  });

  robot.hear(/subscribe/i, function(res){
    var msg = BuildTemplateMessage
      .init('Subscribe')
      .confirm({
        text: '訂閱海賊王?'
      })
      .action('postback', {
        label: '訂閱',
        //data: 'subscribe=true&comic=02'
        text: '訂閱成功'
        //uri: 'https://www.google.com.tw/search?q=ok'
      })
      .action('message', {
        label: '取消',
        text: '太可惜了'
      })
      .build();
    res.reply(msg);
  });
};
<|endoftext|>


<commit_before>/**
 * © 2017 Liferay, Inc. <https://liferay.com>
 *
 * SPDX-License-Identifier: MIT
 */

/* eslint-env jest */

const {RuleTester} = require('eslint');

RuleTester.describe = describe;
RuleTester.it = it;
<commit_msg>feat: make Jest descriptions better looking<commit_after>/**
 * © 2017 Liferay, Inc. <https://liferay.com>
 *
 * SPDX-License-Identifier: MIT
 */

/* eslint-env jest */

const {RuleTester} = require('eslint');

RuleTester.describe = describe;

RuleTester.it = function(description, method) {
	const prettifiedDescription = description.replace(
		/\\u0009|\\u000a/g,
		match => {
			if (match === '\\u0009') {
				return '\\t';
			} else {
				return '\\n';
			}
		}
	);

	it(prettifiedDescription, method);
};
<|endoftext|>


<commit_before>/*
 *    Copyright 2013 APPNEXUS 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.
*/

(function() {

	// Set up some variables
	var mraid = window.mraid = {};
	mraid.util = {};
	var listeners = [];
	listeners['ready']=[];
	listeners['error']=[];
	listeners['stateChange']=[];
	listeners['viewableChange']=[];
	var state='loading'; //Can be loading, default, expanded, or hidden
	var placement_type='inline';
	var is_viewable=false;
	var expand_properties={width:-1, height:-1, useCustomClose:false, isModal:true};
	var orientation_properties={allowOrientationChange:true, forceOrientation:"none"};

	// ----- MRAID AD API FUNCTIONS -----

	// getVersion() returns string '2.0'
	mraid.getVersion=function(){ return '2.0'};

	/** Adds a listener to a specific event. For example, a function onReady might be defined, and then mraid.addEventListener('ready', onReady)
	  * is called. When the ready event is fired, onReady will be called.
	  * Events 'error', 'viewableChange', 'stateChange', have parameters.
         */
	mraid.addEventListener=function(event_name, method){
		if(listeners[event_name].indexOf(method) > -1) return; // Listener is already registered
		listeners[event_name].push(method);
	};

	// Removes a listener from the registry
	mraid.removeEventListener=function(event_name, method){
	    //If no method name is given, remove all listeners from event
	    if(method == null){
	        listeners[event_name].length=0;
	    }

		var method_index = listeners[event_name].indexOf(method);
		if(method_index > -1){ //Don't try to remove unregistered listeners
			listeners[event_name].splice(method_index,1);
		}else{
		    mraid.util.errorEvent("An unregistered listener was requested to be removed.", "mraid.removeEventListener()")
		}
	};

	//returns 'loading', 'default', 'expanded', or 'hidden'
	mraid.getState=function(){
		return state;
	};

	//returns 'inline' or 'interstitial'
	mraid.getPlacementType=function(){
		return placement_type;
	};

	//returns true or false
	mraid.isViewable=function(){
		return is_viewable;
	};

	// ----- MRAID JS TO NATIVE FUNCTIONS -----

	//Closes an expanded ad or hides an ad in default state
	mraid.close=function(){
		switch(mraid.getState()){
		case 'loading':
			mraid.util.errorEvent("mraid.close() called while state is 'loading'.", "mraid.close()");
			break;
		case 'default':
			window.open("mraid://close/");
			mraid.util.stateChangeEvent('hidden');
			break;
		case 'expanded':
			window.open("mraid://close/");
			mraid.util.stateChangeEvent('default');
			break;
		case 'hidden':
			mraid.util.errorEvent("mraid.close() called while ad was already hidden", "mraid.close()");
			break;
		}
	};

	// Expands a default state ad, or unhides a hidden ad. Optionally takes a URL to load in the expanded view
	mraid.expand=function(url){
		switch(mraid.getState()){
		case 'loading':
			mraid.util.errorEvent("mraid.expand() called while state is 'loading'.", "mraid.expand()");
			break;
		case 'default':
			window.open("mraid://expand/"+"?w="+mraid.getExpandProperties().width+"&h="+mraid.getExpandProperties().height+"&useCustomClose="+mraid.getExpandProperties().useCustomClose+(url!=null ? "&url="+url:""));
			mraid.util.stateChangeEvent('expanded');
			if(url!=null){
			    window.open(url);
			}
			break;
		case 'expanded':
			mraid.util.errorEvent("mraid.expand() called while state is 'expanded'.", "mraid.expand()");
			break;
		case 'hidden':
            mraid.util.errorEvent("mraid.expand() called while state is 'hidden'.", "mraid.expand()");
			break;
		}
	};

	// Takes an object... {width:300, height:250, useCustomClose:false, isModal:false};
	mraid.setExpandProperties=function(properties){
		properties.isModal=true; // Read only property.
		expand_properties=properties;
	};

	//returns a json object... {width:300, height:250, useCustomClose:false, isModal:false};
	mraid.getExpandProperties=function(){
		return expand_properties;
	};

    // Takes an object... {allowOrientationChange:true, forceOrientation:"none"};
	mraid.setOrientationProperties=function(properties){
	    // TODO: Update native-side properties
	    orientation_properties=properties;
	}

	//returns a json object... {allowOrientationChange:true, forceOrientation:"none"};
	mraid.getOrientationProperties=function(){
	    return orientation_properties;
	}

	// Takes a boolean
	mraid.useCustomClose=function(well_is_it){
		ep = mraid.getExpandProperties();
		ep.useCustomClose = well_is_it;
		mraid.setExpandProperties(ep);
	};

	// Loads a given URL
	mraid.open=function(url){
		window.open(url);
	};

    // MRAID 2.0 Stuff.

    // Creates a calendar event when passed a W3C-formatted json object
    mraid.createCalendarEvent=function(event){
        window.open("mraid://createCalendarEvent/?p="+encodeURIComponent(JSON.stringify(event)));
    }

    // Creates a calendar event when passed a W3C-formatted json object
    mraid.createCalendarEvent=function(uri){
        window.open("mraid://playVideo/?uri="+encodeURIComponent(uri));
    }

	// ----- MRAID UTILITY FUNCTIONS -----
	// These functions are called by the native SDK to drive events and update information

	mraid.util.setPlacementType=function(type){
		placement_type=type;
	};

	mraid.util.readyEvent=function(){
		for(var i=0;i<listeners['ready'].length;i++){
			listeners['ready'][i]();
		}
	};

	mraid.util.errorEvent=function(message, what_doing){
		for(var i=0;i<listeners['error'].length;i++){
			listeners['error'][i](message, what_doing);
		}
	};

	mraid.util.viewableChangeEvent=function(is_viewable_now){
		is_viewable = is_viewable_now;
		for(var i=0;i<listeners['viewableChange'].length;i++){
			listeners['viewableChange'][i](is_viewable_now);
		}
	};

	mraid.util.setIsViewable=function(is_it_viewable){
		if(is_viewable===is_it_viewable) return;
		is_viewable=is_it_viewable;
		mraid.util.viewableChangeEvent(is_viewable);
	};

	mraid.util.stateChangeEvent=function(new_state){
		if(state===new_state) return;
		state=new_state;
		if(new_state==='hidden'){
			mraid.util.setIsViewable(false);
		}
		for(var i=0;i<listeners['stateChange'].length;i++){
			listeners['stateChange'][i](new_state);
		}
	};

}());
<commit_msg>Store picture, start of resize, resize properties object<commit_after>/*
 *    Copyright 2013 APPNEXUS 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.
*/

(function() {

	// Set up some variables
	var mraid = window.mraid = {};
	mraid.util = {};
	var listeners = [];
	listeners['ready']=[];
	listeners['error']=[];
	listeners['stateChange']=[];
	listeners['viewableChange']=[];
	var state='loading'; //Can be loading, default, expanded, or hidden
	var placement_type='inline';
	var is_viewable=false;
	var expand_properties={width:-1, height:-1, useCustomClose:false, isModal:true};
	var orientation_properties={allowOrientationChange:true, forceOrientation:"none"};
	var resize_properties={width:-1, height:-1, offsetX: 0, offsetY: 0, customClosePosition: 'top-right', allowOffscreen: true};

	// ----- MRAID AD API FUNCTIONS -----

	// getVersion() returns string '2.0'
	mraid.getVersion=function(){ return '2.0'};

	/** Adds a listener to a specific event. For example, a function onReady might be defined, and then mraid.addEventListener('ready', onReady)
	  * is called. When the ready event is fired, onReady will be called.
	  * Events 'error', 'viewableChange', 'stateChange', have parameters.
         */
	mraid.addEventListener=function(event_name, method){
		if(listeners[event_name].indexOf(method) > -1) return; // Listener is already registered
		listeners[event_name].push(method);
	};

	// Removes a listener from the registry
	mraid.removeEventListener=function(event_name, method){
	    //If no method name is given, remove all listeners from event
	    if(method == null){
	        listeners[event_name].length=0;
	    }

		var method_index = listeners[event_name].indexOf(method);
		if(method_index > -1){ //Don't try to remove unregistered listeners
			listeners[event_name].splice(method_index,1);
		}else{
		    mraid.util.errorEvent("An unregistered listener was requested to be removed.", "mraid.removeEventListener()")
		}
	};

	//returns 'loading', 'default', 'expanded', or 'hidden'
	mraid.getState=function(){
		return state;
	};

	//returns 'inline' or 'interstitial'
	mraid.getPlacementType=function(){
		return placement_type;
	};

	//returns true or false
	mraid.isViewable=function(){
		return is_viewable;
	};

	// ----- MRAID JS TO NATIVE FUNCTIONS -----

	//Closes an expanded ad or hides an ad in default state
	mraid.close=function(){
		switch(mraid.getState()){
		case 'loading':
			mraid.util.errorEvent("mraid.close() called while state is 'loading'.", "mraid.close()");
			break;
		case 'default':
			window.open("mraid://close/");
			mraid.util.stateChangeEvent('hidden');
			break;
		case 'expanded':
			window.open("mraid://close/");
			mraid.util.stateChangeEvent('default');
			break;
		case 'hidden':
			mraid.util.errorEvent("mraid.close() called while ad was already hidden", "mraid.close()");
			break;
		}
	};

	// Expands a default state ad, or unhides a hidden ad. Optionally takes a URL to load in the expanded view
	mraid.expand=function(url){
		switch(mraid.getState()){
		case 'loading':
			mraid.util.errorEvent("mraid.expand() called while state is 'loading'.", "mraid.expand()");
			break;
		case 'default':
			window.open("mraid://expand/"+"?w="+mraid.getExpandProperties().width+"&h="+mraid.getExpandProperties().height+"&useCustomClose="+mraid.getExpandProperties().useCustomClose+(url!=null ? "&url="+url:""));
			mraid.util.stateChangeEvent('expanded');
			if(url!=null){
			    window.open(url);
			}
			break;
		case 'expanded':
			mraid.util.errorEvent("mraid.expand() called while state is 'expanded'.", "mraid.expand()");
			break;
		case 'hidden':
            mraid.util.errorEvent("mraid.expand() called while state is 'hidden'.", "mraid.expand()");
			break;
		}
	};

	// Takes an object... {width:300, height:250, useCustomClose:false, isModal:false};
	mraid.setExpandProperties=function(properties){
		properties.isModal=true; // Read only property.
		expand_properties=properties;
	};

	//returns a json object... {width:300, height:250, useCustomClose:false, isModal:false};
	mraid.getExpandProperties=function(){
		return expand_properties;
	};

    // Takes an object... {allowOrientationChange:true, forceOrientation:"none"};
	mraid.setOrientationProperties=function(properties){
	    // TODO: Update native-side properties
	    orientation_properties=properties;
	}

	//returns a json object... {allowOrientationChange:true, forceOrientation:"none"};
	mraid.getOrientationProperties=function(){
	    return orientation_properties;
	}

	// Takes a boolean
	mraid.useCustomClose=function(well_is_it){
		ep = mraid.getExpandProperties();
		ep.useCustomClose = well_is_it;
		mraid.setExpandProperties(ep);
	};

	// Loads a given URL
	mraid.open=function(url){
		window.open(url);
	};

    // MRAID 2.0 Stuff.
    mraid.resize=function(){
        if(resize_properties.height<0 || resize_properties.width<0){
            mraid.util.errorEvent("mraid.resize() called before mraid.setResizeProperties()", "mraid.resize()");
            return;
        }
        //TODO: Rest of this
    }

    // TODO: get/set resize properties

    // Creates a calendar event when passed a W3C-formatted json object
    mraid.createCalendarEvent=function(event){
        window.open("mraid://createCalendarEvent/?p="+encodeURIComponent(JSON.stringify(event)));
    }

    // Creates a calendar event when passed a W3C-formatted json object
    mraid.createCalendarEvent=function(uri){
        window.open("mraid://playVideo/?uri="+encodeURIComponent(uri));
    }

    // Stores a picture on the device
    mraid.storePicture=function(uri){
        window.open("mraid://storePicture/?uri="+encodeURIComponent(uri));
    }

	// ----- MRAID UTILITY FUNCTIONS -----
	// These functions are called by the native SDK to drive events and update information

	mraid.util.setPlacementType=function(type){
		placement_type=type;
	};

	mraid.util.readyEvent=function(){
		for(var i=0;i<listeners['ready'].length;i++){
			listeners['ready'][i]();
		}
	};

	mraid.util.errorEvent=function(message, what_doing){
		for(var i=0;i<listeners['error'].length;i++){
			listeners['error'][i](message, what_doing);
		}
	};

	mraid.util.viewableChangeEvent=function(is_viewable_now){
		is_viewable = is_viewable_now;
		for(var i=0;i<listeners['viewableChange'].length;i++){
			listeners['viewableChange'][i](is_viewable_now);
		}
	};

	mraid.util.setIsViewable=function(is_it_viewable){
		if(is_viewable===is_it_viewable) return;
		is_viewable=is_it_viewable;
		mraid.util.viewableChangeEvent(is_viewable);
	};

	mraid.util.stateChangeEvent=function(new_state){
		if(state===new_state) return;
		state=new_state;
		if(new_state==='hidden'){
			mraid.util.setIsViewable(false);
		}
		for(var i=0;i<listeners['stateChange'].length;i++){
			listeners['stateChange'][i](new_state);
		}
	};

}());
<|endoftext|>