<commit_before>import _ from 'lodash';
import * as twitter from '../apis/twitter';

import {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLID,
  GraphQLString,
  GraphQLNonNull,
  GraphQLInt,
  GraphQLList,
} from 'graphql';

let UserType = new GraphQLObjectType({

  name: 'TwitterUser',
  description: 'Twitter user, or as we like to say in France: a \'tweetos\'',
  fields: () => ({
    created_at: { type: GraphQLString },
    description: { type: GraphQLString },
    id: { type: GraphQLID }, // GraphQLInt would return null
    screen_name: { type: GraphQLString },
    name: { type: GraphQLString },
    profile_image_url: { type: GraphQLString },
    url: { type: GraphQLString },
    tweets_count: {
      type: GraphQLInt,
      resolve: ({ statuses_count }) => statuses_count
    },
    followers_count: { type: GraphQLInt },
    tweets: {
      type: new GraphQLList(TweetType),
      description: 'Get a list of tweets for current user',
      args: {
        limit: { type: GraphQLInt }
      },
      //             user            args
      resolve: ({ id: user_id }, { limit = 10 }) => twitter.getTweets(user_id, limit)
    }
  })

});

let TweetType = new GraphQLObjectType({

  name: 'Tweet',
  description: 'A tweet object',
  fields: () => ({
    id: { type: GraphQLID },
    created_at: { type: GraphQLString },
    text: { type: GraphQLString },
    retweet_count: { type: GraphQLInt },
    user: {
      type: UserType
    },
    retweets: {
      type: new GraphQLList(RetweetType),
      description: 'Get a list of retweets',
      args: {
        limit: { type: GraphQLInt }
      },
      //        passing integer 'id' here doesn't work surprisingly, had to use 'id_str'
      resolve: ({ id_str: tweetId }, { limit = 5 }) => twitter.getRetweets(tweetId, limit)
    }
  })
});

let RetweetType = new GraphQLObjectType({

  name: 'Retweet',
  description: 'Retweet of a tweet',
  fields: () => ({
    id: { type: GraphQLID },
    created_at: { type: GraphQLString },
    in_reply_to_tweet_id: {
      type: GraphQLString,
      resolve: ({ in_reply_to_status_id }) => in_reply_to_status_id
    },
    in_reply_to_user_id: { type: GraphQLInt },
    in_reply_to_screen_name: { type: GraphQLString },
    retweeted_status: {
      type: TweetType
    },
    user: {
      type: UserType
    }
  })
});

let twitterType = new GraphQLObjectType({

  name: 'TwitterAPI',
  description: 'The Twitter API',
  fields: {
    user: {
      type: UserType,
      args: {
        user_id: {
          description: 'ID of user account',
          type: GraphQLInt
        },
        screen_name: {
          description: 'Screenname of the user',
          type: GraphQLString
        }
      },
      resolve: (_, { user_id, screen_name }) => {

        const { getUser } = twitter;

        if (!user_id && !screen_name) {
          return getUser('user_id', 9533042);
        }
        else {

          if (_.isNumber(user_id)) {
            return getUser('user_id', user_id);
          }
          else {
            return getUser('screen_name', screen_name);
          }
        }
      }
    },
    tweet: {
      type: TweetType,
      args: {
        id: {
          type: new GraphQLNonNull(GraphQLString),
          description: 'Unique ID of tweet'
        }
      },
      resolve: (_, { id: tweetId }) => twitter.getTweet(tweetId)
    },
    search: {
      type: new GraphQLList(TweetType),
      description: "Returns a collection of relevant Tweets matching a specified query.",
      args: {
        q: {
          type: new GraphQLNonNull(GraphQLString),
          description: "A UTF-8, URL-encoded search query of 500 characters maximum, including operators. Queries may additionally be limited by complexity."
        },
        count: {
          type: GraphQLInt,
          description: "The number of tweets to return per page, up to a maximum of 100. Defaults to 15. This was formerly the “rpp” parameter in the old Search API."
        },
        result_type: {
          type: GraphQLString,
          description: `Specifies what type of search results you would prefer to receive. The current default is “mixed.” Valid values include:
          * mixed: Include both popular and real time results in the response.
          * recent: return only the most recent results in the response
          * popular: return only the most popular results in the response.`
        }
      },
      resolve: (_, searchArgs) => twitter.searchFor(searchArgs)
    }
  }
});

export const Schema = {
  query: {
    type: twitterType,
    resolve() {
      return {};
    }
  }
};
<commit_msg>space/alignement for consecutive key/value<commit_after>import _ from 'lodash';
import * as twitter from '../apis/twitter';

import {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLID,
  GraphQLString,
  GraphQLNonNull,
  GraphQLInt,
  GraphQLList,
} from 'graphql';

let UserType = new GraphQLObjectType({

  name        : 'TwitterUser',
  description : 'Twitter user, or as we like to say in France: a \'tweetos\'',
  fields      : () => ({
    created_at        : { type: GraphQLString },
    description       : { type: GraphQLString },
    id                : { type: GraphQLID }, // GraphQLInt would return null
    screen_name       : { type: GraphQLString },
    name              : { type: GraphQLString },
    profile_image_url : { type: GraphQLString },
    url               : { type: GraphQLString },
    tweets_count      : {
      type    : GraphQLInt,
      resolve : ({ statuses_count }) => statuses_count
    },
    followers_count : { type: GraphQLInt },
    tweets          : {
      type        : new GraphQLList(TweetType),
      description : 'Get a list of tweets for current user',
      args        : {
        limit: { type: GraphQLInt }
      },
      //             user            args
      resolve: ({ id: user_id }, { limit = 10 }) => twitter.getTweets(user_id, limit)
    }
  })

});

let TweetType = new GraphQLObjectType({

  name        : 'Tweet',
  description : 'A tweet object',
  fields      : () => ({
    id            : { type: GraphQLID },
    created_at    : { type: GraphQLString },
    text          : { type: GraphQLString },
    retweet_count : { type: GraphQLInt },
    user          : { type: UserType },
    retweets      : {
      type        : new GraphQLList(RetweetType),
      description : 'Get a list of retweets',
      args        : {
        limit: { type: GraphQLInt }
      },
      //        passing integer 'id' here doesn't work surprisingly, had to use 'id_str'
      resolve: ({ id_str: tweetId }, { limit = 5 }) => twitter.getRetweets(tweetId, limit)
    }
  })
});

let RetweetType = new GraphQLObjectType({

  name        : 'Retweet',
  description : 'Retweet of a tweet',
  fields      : () => ({
    id                   : { type: GraphQLID },
    created_at           : { type: GraphQLString },
    in_reply_to_tweet_id : {
      type    : GraphQLString,
      resolve : ({ in_reply_to_status_id }) => in_reply_to_status_id
    },
    in_reply_to_user_id     : { type: GraphQLInt },
    in_reply_to_screen_name : { type: GraphQLString },
    retweeted_status        : { type: TweetType },
    user                    : { type: UserType }
  })
});

let twitterType = new GraphQLObjectType({

  name        : 'TwitterAPI',
  description : 'The Twitter API',
  fields : {
    user : {
      type : UserType,
      args : {
        user_id: {
          description : 'ID of user account',
          type        : GraphQLInt
        },
        screen_name: {
          description : 'Screenname of the user',
          type        : GraphQLString
        }
      },
      resolve: (_, { user_id, screen_name }) => {

        const { getUser } = twitter;

        if (!user_id && !screen_name) {
          return getUser('user_id', 9533042);
        }
        else {

          if (_.isNumber(user_id)) {
            return getUser('user_id', user_id);
          }
          else {
            return getUser('screen_name', screen_name);
          }
        }
      }
    },
    tweet: {
      type : TweetType,
      args : {
        id : {
          type        : new GraphQLNonNull(GraphQLString),
          description : 'Unique ID of tweet'
        }
      },
      resolve: (_, { id: tweetId }) => twitter.getTweet(tweetId)
    },
    search: {
      type        : new GraphQLList(TweetType),
      description : "Returns a collection of relevant Tweets matching a specified query.",
      args: {
        q: {
          type        : new GraphQLNonNull(GraphQLString),
          description : "A UTF-8, URL-encoded search query of 500 characters maximum, including operators. Queries may additionally be limited by complexity."
        },
        count: {
          type        : GraphQLInt,
          description : "The number of tweets to return per page, up to a maximum of 100. Defaults to 15. This was formerly the “rpp” parameter in the old Search API."
        },
        result_type: {
          type: GraphQLString,
          description: `Specifies what type of search results you would prefer to receive. The current default is “mixed.” Valid values include:
          * mixed: Include both popular and real time results in the response.
          * recent: return only the most recent results in the response
          * popular: return only the most popular results in the response.`
        }
      },
      resolve: (_, searchArgs) => twitter.searchFor(searchArgs)
    }
  }
});

export const Schema = {
  query: {
    type: twitterType,
    resolve() {
      return {};
    }
  }
};
<|endoftext|>


<commit_before>'use strict';
const fs = require('fs');
const http = require('http');
const https = require('https');
const basicAuth = require('basic-auth');
const app = require('express')();
const bodyParser = require('body-parser');
const multer = require('multer'); // v1.0.5
const upload = multer(); // for parsing multipart/form-data
// const coBusboy = require('co-busboy');
// var Busboy = require('busboy');
const busboy = require('connect-busboy');

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({
  extended: true
})); // for parsing application/x-www-form-urlencoded
app.use(busboy());
app.use(function(req, res, next) {
  if (!req.is('multipart/*') || !req.busboy) {
    next();
    return;
  }
  req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding +
    ', mimetype: ' + mimetype);
    file.on('data', function(data) {
      console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
    });
    file.on('end', function() {
      console.log('File [' + fieldname + '] Finished');
    });
  });
  req.busboy.on('field', function(fieldname, val
  /*, fieldnameTruncated, valTruncated, encoding, mimetype*/) {
    console.log('Field [' + fieldname + ']: value: ' + val);
  });
  req.busboy.on('finish', function() {
    next();
  });
  req.pipe(req.busboy);
});
// app.use(function* (next) {
//   console.log('Next function called');
//   if (!this.request.is('multipart/*')) {
//     return yield next;
//   }
//   console.log('Processing multipart request');
//   var parts = coBusboy(this);
//   var part
//   while (part = yield parts) {
//     if (part.length) {
//       // arrays are busboy fields
//       console.log('key: ' + part[0]);
//       console.log('value: ' + part[1]);
//     } else {
//       // otherwise, it's a stream
//       console.log('It\'s a stream');
//       //part.pipe(fs.createWriteStream('some file.txt'))
//     }
//   }
//   console.log('and we are done parsing the form!');
// });

class TestServer {
  constructor() {
    this.credentials = {
      key: fs.readFileSync('./tests/certs/server1.key', 'utf8'),
      cert: fs.readFileSync('./tests/certs/server1.crt', 'utf8')
    };
    this.post = 8081;
    app.disable('x-powered-by');
    // app.disable('etag');
    this.setHandlers();
    this.createServer();
  }

  basicAuth(req, res, next) {
    var user = basicAuth(req);
    if (!user || !user.name || !user.pass) {
      return this.unauthorized(res);
    }
    if (user.name === 'test' && user.pass === 'test') {
      return next();
    } else {
      return this.unauthorized(res);
    }
  }

  /**
   * To be called when the user is not basic authenticated.
   */
  unauthorized(res) {
    res.set('WWW-Authenticate', 'Basic realm=Authorization Required (test:test)');
    return res.sendStatus(401);
  }

  createServer() {
    var httpServer = http.createServer(app);
    var httpsServer = https.createServer(this.credentials, app);
    // httpServer.listen(80, () => {
    //   console.log('HTTP started (80).');
    // });
    httpServer.listen(this.post, () => {
      console.log('HTTP started (' + this.post + ').');
    });
    // httpsServer.listen(443, () => {
    //   console.log('HTTPS started (443).');
    // });
    httpsServer.listen(3000, () => {
      console.log('HTTPS started (3000).');
    });
  }

  setHandlers() {
    this._setMain();
    this._setBasicAuth();
    this._setMeta();
    this._setJson();
    this._setXML();
    this._setCookie();
    this._setPost();
    this._setPut();
    this._setDelete();
    this._setMultipard();
    this._setRedirect();
    this._setErrors();
  }

  _setMain() {
    app.get('/', (req, res) => {
      // res.removeHeader('Date');
      // res.removeHeader('Connection');
      // res.removeHeader('Content-Length');
      // res.removeHeader('Transfer-Encoding');
      // res.end();
      res.set('Content-Type', 'text/html');
      if (req.secure) {
        res.send('
SSL connection made
');
      } else {
        res.send('
Non SSL connection made
');
      }
    });

    app.delete('/', (req, res) => {
      res.sendStatus(204);
    });
  }

  _setBasicAuth() {
    app.get('/auth', this.basicAuth.bind(this), (req, res) => {
      res.set('Content-Type', 'text/html');
      res.send('
You are authenticated
');
    });
  }

  _setMeta() {
    app.get('/meta', (req, res) => {
      // res.status(200).send('OK');
      res.set('Content-Type', 'text/html');
      res.set('Link', '</.meta>; rel=meta');
      res.send('
You should see  </.meta>; rel=meta in the Link header
');
    });
  }

  _setJson() {
    app.get('/json', (req, res) => {
      var json = fs.readFileSync('./tasks/test-data/json1.json', 'utf8');
      // res.status(200).send('OK');
      res.set('Content-Type', 'application/json');
      res.send(json);
    });
    app.get('/json2', (req, res) => {
      var json = fs.readFileSync('./tasks/test-data/json2.json', 'utf8');
      // res.status(200).send('OK');
      res.set('Content-Type', 'application/json');
      res.send(json);
    });
  }

  _setXML() {
    app.get('/xml', (req, res) => {
      var json = fs.readFileSync('./tasks/test-data/xml1.xml', 'utf8');
      // res.status(200).send('OK');
      res.set('Content-Type', 'application/xml');
      res.send(json);
    });
    app.get('/xml2', (req, res) => {
      var json = fs.readFileSync('./tasks/test-data/xml2.xml', 'utf8');
      // res.status(200).send('OK');
      res.set('Content-Type', 'application/xml');
      res.send(json);
    });
    app.get('/xml3', (req, res) => {
      var json = fs.readFileSync('./tasks/test-data/xml3.xml', 'utf8');
      // res.status(200).send('OK');
      res.set('Content-Type', 'application/xml');
      res.send(json);
    });
  }

  _setCookie() {
    app.get('/cookie', (req, res) => {
      var Chance = require('chance');
      var chance = new Chance();
      for (var i = 0; i < 10; i++) {
        var value = chance.string({
          length: chance.integer({
            min: 10,
            max: 100
          })
        });
        var opts = {};
        if (chance.bool()) {
          opts.expires = 0;
        }
        if (chance.bool()) {
          opts.httpOnly = true;
        }
        if (chance.bool()) {
          opts.domain = chance.domain();
        }
        res.cookie(chance.word(), value, opts);
      }
      res.cookie('rememberme', '1', {
        maxAge: 900000,
        httpOnly: true,
        domain: 'localhost',
        path: '/cookie',
        secure: true
      });
      res.set('Content-Type', 'text/html');
      res.send('
Cookies are set
');
    });
  }

  _setPost() {
    app.post('/', upload.array(), (req, res) => {
      var response = Object.assign({}, {
        'body': req.body,
        'query': req.query
      });
      // console.log(req.body, req.query);
      // console.log(req.headers);
      // console.log(req);
      res.set('Content-Type', 'application/json');
      res.send(response);
    });
  }

  _setMultipard() {
    app.post('/post', (req, res) => {
      console.log('Calling /post');
      console.log(req.body, req.query);
      res.set('Connection', 'close');
      res.set('Content-Type', 'text/html');
      res.send('Post with success');
      // var busboy = new Busboy({
      //   headers: req.headers
      // });
      // busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
      //   console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' +
      //   encoding + ', mimetype: ' + mimetype);
      //   file.on('data', function(data) {
      //     console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
      //   });
      //   file.on('end', function() {
      //     console.log('File [' + fieldname + '] Finished');
      //   });
      // });
      // busboy.on('field', function(fieldname, val, fieldnameTruncated,
      //  valTruncated, encoding, mimetype) {
      //   console.log('Field [' + fieldname + ']: value: ' + inspect(val));
      // });
      // busboy.on('finish', function() {
      //   console.log('Done parsing form!');
      //   res.writeHead(303, {
      //     Connection: 'close',
      //     Location: '/'
      //   });
      //   res.end();
      // });
      // req.pipe(busboy);

      // console.log(req.headers);
      // console.log(req);
      // res.set('Content-Type', 'application/json');
      // res.send(response);
    });
  }

  _setPut() {
    app.put('/', (req, res) => {
      res.send('PUT request to homepage');
    });
  }

  _setDelete() {
    app.delete('/', (req, res) => {
      res.send('DELETE request to homepage');
    });
  }

  _setRedirect() {
    app.get('/redirect', (req, res) => {
      res.redirect('/redirect/dest');
    });
    app.get('/redirect2', (req, res) => {
      res.redirect('http://localhost:' + this.post + '/redirect/dest');
    });
    app.get('/redirect/dest', (req, res) => {
      res.set('Content-Type', 'text/html');
      res.send('
You have been redirected
');
    });
  }

  _setErrors() {
    app.get('/not-found', (req, res) => {
      res.status(404).end();
    });
    app.get('/status-error', (req, res) => {
      res.status(604).end();
    });
  }
}

module.exports = {
  create: () => {
    new TestServer();
  }
};
<commit_msg>Changed redirection test to better test relative redirection<commit_after>'use strict';
const fs = require('fs');
const http = require('http');
const https = require('https');
const basicAuth = require('basic-auth');
const app = require('express')();
const bodyParser = require('body-parser');
const multer = require('multer'); // v1.0.5
const upload = multer(); // for parsing multipart/form-data
// const coBusboy = require('co-busboy');
// var Busboy = require('busboy');
const busboy = require('connect-busboy');

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({
  extended: true
})); // for parsing application/x-www-form-urlencoded
app.use(busboy());
app.use(function(req, res, next) {
  if (!req.is('multipart/*') || !req.busboy) {
    next();
    return;
  }
  req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding +
    ', mimetype: ' + mimetype);
    file.on('data', function(data) {
      console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
    });
    file.on('end', function() {
      console.log('File [' + fieldname + '] Finished');
    });
  });
  req.busboy.on('field', function(fieldname, val
  /*, fieldnameTruncated, valTruncated, encoding, mimetype*/) {
    console.log('Field [' + fieldname + ']: value: ' + val);
  });
  req.busboy.on('finish', function() {
    next();
  });
  req.pipe(req.busboy);
});
// app.use(function* (next) {
//   console.log('Next function called');
//   if (!this.request.is('multipart/*')) {
//     return yield next;
//   }
//   console.log('Processing multipart request');
//   var parts = coBusboy(this);
//   var part
//   while (part = yield parts) {
//     if (part.length) {
//       // arrays are busboy fields
//       console.log('key: ' + part[0]);
//       console.log('value: ' + part[1]);
//     } else {
//       // otherwise, it's a stream
//       console.log('It\'s a stream');
//       //part.pipe(fs.createWriteStream('some file.txt'))
//     }
//   }
//   console.log('and we are done parsing the form!');
// });

class TestServer {
  constructor() {
    this.credentials = {
      key: fs.readFileSync('./tests/certs/server1.key', 'utf8'),
      cert: fs.readFileSync('./tests/certs/server1.crt', 'utf8')
    };
    this.post = 8081;
    app.disable('x-powered-by');
    // app.disable('etag');
    this.setHandlers();
    this.createServer();
  }

  basicAuth(req, res, next) {
    var user = basicAuth(req);
    if (!user || !user.name || !user.pass) {
      return this.unauthorized(res);
    }
    if (user.name === 'test' && user.pass === 'test') {
      return next();
    } else {
      return this.unauthorized(res);
    }
  }

  /**
   * To be called when the user is not basic authenticated.
   */
  unauthorized(res) {
    res.set('WWW-Authenticate', 'Basic realm=Authorization Required (test:test)');
    return res.sendStatus(401);
  }

  createServer() {
    var httpServer = http.createServer(app);
    var httpsServer = https.createServer(this.credentials, app);
    // httpServer.listen(80, () => {
    //   console.log('HTTP started (80).');
    // });
    httpServer.listen(this.post, () => {
      console.log('HTTP started (' + this.post + ').');
    });
    // httpsServer.listen(443, () => {
    //   console.log('HTTPS started (443).');
    // });
    httpsServer.listen(3000, () => {
      console.log('HTTPS started (3000).');
    });
  }

  setHandlers() {
    this._setMain();
    this._setBasicAuth();
    this._setMeta();
    this._setJson();
    this._setXML();
    this._setCookie();
    this._setPost();
    this._setPut();
    this._setDelete();
    this._setMultipard();
    this._setRedirect();
    this._setErrors();
  }

  _setMain() {
    app.get('/', (req, res) => {
      // res.removeHeader('Date');
      // res.removeHeader('Connection');
      // res.removeHeader('Content-Length');
      // res.removeHeader('Transfer-Encoding');
      // res.end();
      res.set('Content-Type', 'text/html');
      if (req.secure) {
        res.send('
SSL connection made
');
      } else {
        res.send('
Non SSL connection made
');
      }
    });

    app.delete('/', (req, res) => {
      res.sendStatus(204);
    });
  }

  _setBasicAuth() {
    app.get('/auth', this.basicAuth.bind(this), (req, res) => {
      res.set('Content-Type', 'text/html');
      res.send('
You are authenticated
');
    });
  }

  _setMeta() {
    app.get('/meta', (req, res) => {
      // res.status(200).send('OK');
      res.set('Content-Type', 'text/html');
      res.set('Link', '</.meta>; rel=meta');
      res.send('
You should see  </.meta>; rel=meta in the Link header
');
    });
  }

  _setJson() {
    app.get('/json', (req, res) => {
      var json = fs.readFileSync('./tasks/test-data/json1.json', 'utf8');
      // res.status(200).send('OK');
      res.set('Content-Type', 'application/json');
      res.send(json);
    });
    app.get('/json2', (req, res) => {
      var json = fs.readFileSync('./tasks/test-data/json2.json', 'utf8');
      // res.status(200).send('OK');
      res.set('Content-Type', 'application/json');
      res.send(json);
    });
  }

  _setXML() {
    app.get('/xml', (req, res) => {
      var json = fs.readFileSync('./tasks/test-data/xml1.xml', 'utf8');
      // res.status(200).send('OK');
      res.set('Content-Type', 'application/xml');
      res.send(json);
    });
    app.get('/xml2', (req, res) => {
      var json = fs.readFileSync('./tasks/test-data/xml2.xml', 'utf8');
      // res.status(200).send('OK');
      res.set('Content-Type', 'application/xml');
      res.send(json);
    });
    app.get('/xml3', (req, res) => {
      var json = fs.readFileSync('./tasks/test-data/xml3.xml', 'utf8');
      // res.status(200).send('OK');
      res.set('Content-Type', 'application/xml');
      res.send(json);
    });
  }

  _setCookie() {
    app.get('/cookie', (req, res) => {
      var Chance = require('chance');
      var chance = new Chance();
      for (var i = 0; i < 10; i++) {
        var value = chance.string({
          length: chance.integer({
            min: 10,
            max: 100
          })
        });
        var opts = {};
        if (chance.bool()) {
          opts.expires = 0;
        }
        if (chance.bool()) {
          opts.httpOnly = true;
        }
        if (chance.bool()) {
          opts.domain = chance.domain();
        }
        res.cookie(chance.word(), value, opts);
      }
      res.cookie('rememberme', '1', {
        maxAge: 900000,
        httpOnly: true,
        domain: 'localhost',
        path: '/cookie',
        secure: true
      });
      res.set('Content-Type', 'text/html');
      res.send('
Cookies are set
');
    });
  }

  _setPost() {
    app.post('/', upload.array(), (req, res) => {
      var response = Object.assign({}, {
        'body': req.body,
        'query': req.query
      });
      // console.log(req.body, req.query);
      // console.log(req.headers);
      // console.log(req);
      res.set('Content-Type', 'application/json');
      res.send(response);
    });
  }

  _setMultipard() {
    app.post('/post', (req, res) => {
      console.log('Calling /post');
      console.log(req.body, req.query);
      res.set('Connection', 'close');
      res.set('Content-Type', 'text/html');
      res.send('Post with success');
      // var busboy = new Busboy({
      //   headers: req.headers
      // });
      // busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
      //   console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' +
      //   encoding + ', mimetype: ' + mimetype);
      //   file.on('data', function(data) {
      //     console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
      //   });
      //   file.on('end', function() {
      //     console.log('File [' + fieldname + '] Finished');
      //   });
      // });
      // busboy.on('field', function(fieldname, val, fieldnameTruncated,
      //  valTruncated, encoding, mimetype) {
      //   console.log('Field [' + fieldname + ']: value: ' + inspect(val));
      // });
      // busboy.on('finish', function() {
      //   console.log('Done parsing form!');
      //   res.writeHead(303, {
      //     Connection: 'close',
      //     Location: '/'
      //   });
      //   res.end();
      // });
      // req.pipe(busboy);

      // console.log(req.headers);
      // console.log(req);
      // res.set('Content-Type', 'application/json');
      // res.send(response);
    });
  }

  _setPut() {
    app.put('/', (req, res) => {
      res.send('PUT request to homepage');
    });
  }

  _setDelete() {
    app.delete('/', (req, res) => {
      res.send('DELETE request to homepage');
    });
  }

  _setRedirect() {
    app.get('/relative-redirect', (req, res) => {
      res.redirect('/relative-redirect/step-1');
    });
    app.get('/relative-redirect/step-1', (req, res) => {
      res.redirect('/relative-redirect/step-2');
    });
    app.get('/relative-redirect/step-2', (req, res) => {
      res.redirect('/redirect/dest');
    });
    app.get('/redirect', (req, res) => {
      res.redirect('http://localhost:' + this.post + '/redirect/dest');
    });
    app.get('/redirect/dest', (req, res) => {
      res.set('Content-Type', 'text/html');
      res.send('
You have been redirected
');
    });
  }

  _setErrors() {
    app.get('/not-found', (req, res) => {
      res.status(404).end();
    });
    app.get('/status-error', (req, res) => {
      res.status(604).end();
    });
  }
}

module.exports = {
  create: () => {
    new TestServer();
  }
};
<|endoftext|>


<commit_before>const https = require('https')
class TBA {
	constructor(auth_key) {
		this.header = '?X-TBA-Auth-Key=' + auth_key;
		this.base = 'https://www.thebluealliance.com/api/v3/';
	}

	callAPI(uri) {
		return new Promise((resolve, reject) => {
			let content = '';
			https.get(this.base + uri + this.header, res => {
				if (res.statusCode != 200) {
					reject(res.statusCode + ': ' + res.statusMessage);
				}

				res.on('data', data => {
					content += data;
				});

				res.on('end', data => {
					if (res.statusCode == 200) resolve(JSON.parse(content));
				});
			});
		});
	}

	getStatus() {
		return this.callAPI('status/');
	}

	//Teams

	getTeamList(pageNum) {
		return this.callAPI('teams/' + pageNum);
	}

	getTeamListSimple(pageNum) {
		return this.callAPI('teams/' + pageNum + '/simple');
	}

	getTeamList(pageNum, year) {
		return this.callAPI('teams' + (year === undefined ? '' : '/' + year) + '/' + pageNum);
	}

	getTeamListSimple(pageNum, year) {
		console.log(year);
		return this.callAPI('teams' + (year === undefined ? '' : '/' + year) + '/' + pageNum + '/simple');
	}

	getTeam(teamNum) {
		return this.callAPI('team/frc' + teamNum);
	}

	getTeamSimple(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/simple');
	}

	getYearsParticipated(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/years_participated');
	}

	getTeamDistricts(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/districts');
	}

	getTeamRobots(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/robots');
	}

	getTeamEventList(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/events');
	}

	getTeamEventList(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/events' + (year === undefined ? '' : '/' + year));
	}

	getTeamEventListSimple(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/events/simple');
	}

	getTeamEventListSimple(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/events' + (year === undefined ? '' : '/' + year) + '/simple');
	}

	getTeamEventListKeys(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/events/keys');
	}

	getTeamEventListKeys(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/events' + (year === undefined ? '' : '/' + year) + '/keys');
	}

	getTeamEventMatchList(teamNum, eventKey) {
		return this.callAPI('team/frc' + teamNum + '/event/' + eventKey + "/matches");
	}

	getTeamEventMatchListSimple(teamNum, eventKey) {
		return this.callAPI('team/frc' + teamNum + '/event/' + eventKey + "/matches/simple");
	}

	getTeamEventMatchListKeys(teamNum, eventKey) {
		return this.callAPI('team/frc' + teamNum + '/event/' + eventKey + "/matches/simple");
	}

	getTeamEventAwards(teamNum, eventKey) {
		return this.callAPI('team/frc' + teamNum + '/event/' + eventKey + '/awards');
	}

	getTeamEventStatus(teamNum, eventKey) {
		return this.callAPI('team/frc' + teamNum + '/event/' + eventKey + '/awards');
	}

	getTeamAwards(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/awards/' + year);
	}

	getTeamMatchList(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/matches/' + year);
	}

	getTeamMatchListSimple(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/matches/' + year + '/simple');
	}

	getTeamMatchListKeys(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/matches/' + year + '/keys');
	}

	getTeamMedia(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/media/' + year);
	}

	getTeamSocialMedia(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/social_media');
	}

	//Events - work on this

	getEventList(year) {
		return this.callAPI('events/' + year);
	}

	getEventListSimple(year) {
		return this.callAPI('events/' + year + '/simple');
	}

	getEventListKeys(year) {
		return this.callAPI('events/' + year + '/keys');
	}

	getEvent(eventKey) {
		return this.callAPI('event/' + eventKey);
	}

	getEventSimple(eventKey) {
		return this.callAPI('event/' + eventKey + '/simple');
	}

	getEventAlliances(eventKey) {
		return this.callAPI('event/' + eventKey + '/alliances');
	}

	getEventInsights(eventKey) {
		return this.callAPI('event/' + eventKey + '/insights');
	}

	getEventOprs(eventKey) {
		return this.callAPI('event/' + eventKey + '/oprs');
	}

	getEventPredictions(eventKey) {
		return this.callAPI('event/' + eventKey + '/predictions');
	}

	getEventTeams(eventKey) {
		return this.callAPI('event/' + eventKey + '/teams');
	}

	getEventTeamsSimple(eventKey) {
		return this.callAPI('event/' + eventKey + '/teams/simple');
	}

	getEventTeamsKeys(eventKey) {
		return this.callAPI('event/' + eventKey + '/teams/keys');
	}

	getEventMatches(eventKey) {
		return this.callAPI('event/' + eventKey + '/matches');
	}

	getEventMatchesSimple(eventKey) {
		return this.callAPI('event/' + eventKey + '/matches/simple');
	}

	getEventMatchesKeys(eventKey) {
		return this.callAPI('event/' + eventKey + '/matches/keys');
	}

	getEventRankings(eventKey) {
		return this.callAPI('event/' + eventKey + '/rankings');
	}

	getEventAwards(eventKey) {
		return this.callAPI('event/' + eventKey + '/awards');
	}

	getEventDistrictPoints(eventKey) {
		return this.callAPI('event/' + eventKey + '/district_points');
	}

	//Matches

	getMatch(matchKey) {
		return this.callAPI('match/' + matchKey);
	}

	getMatchSimple(matchKey) {
		return this.callAPI('match/' + matchKey + '/simple');
	}

	//Districts

	getDistrictList(year) {
		return this.callAPI('districts/' + year);
	}

	getDistrictEvents(districtShort) {
		return this.callAPI('district/' + districtShort + '/events');
	}

	getDistrictEventsSimple(districtShort) {
		return this.callAPI('district/' + districtShort + '/events/simple');
	}

	getDistrictEventsKeys(districtShort) {
		return this.callAPI('district/' + districtShort + '/events/keys');
	}

	getDistrictRankings(districtShort, year) {
		return this.callAPI('district/' + districtShort + '/' + year + '/rankings');
	}

	getDistrictTeams(districtShort, year) {
		return this.callAPI('district/' + districtShort + '/teams');
	}

	getDistrictTeamsSimple(districtShort, year) {
		return this.callAPI('district/' + districtShort + '/teams/simple');
	}

	getDistrictTeamsKeys(districtShort, year) {
		return this.callAPI('district/' + districtShort + '/teams/keys');
	}
}
module.exports = TBA;
<commit_msg>Add strict mode<commit_after>'use strict';
const https = require('https')
class TBA {
	constructor(auth_key) {
		this.header = '?X-TBA-Auth-Key=' + auth_key;
		this.base = 'https://www.thebluealliance.com/api/v3/';
	}

	callAPI(uri) {
		return new Promise((resolve, reject) => {
			let content = '';
			https.get(this.base + uri + this.header, res => {
				if (res.statusCode != 200) {
					reject(res.statusCode + ': ' + res.statusMessage);
				}

				res.on('data', data => {
					content += data;
				});

				res.on('end', data => {
					if (res.statusCode == 200) resolve(JSON.parse(content));
				});
			});
		});
	}

	getStatus() {
		return this.callAPI('status/');
	}

	//Teams

	getTeamList(pageNum) {
		return this.callAPI('teams/' + pageNum);
	}

	getTeamListSimple(pageNum) {
		return this.callAPI('teams/' + pageNum + '/simple');
	}

	getTeamList(pageNum, year) {
		return this.callAPI('teams' + (year === undefined ? '' : '/' + year) + '/' + pageNum);
	}

	getTeamListSimple(pageNum, year) {
		console.log(year);
		return this.callAPI('teams' + (year === undefined ? '' : '/' + year) + '/' + pageNum + '/simple');
	}

	getTeam(teamNum) {
		return this.callAPI('team/frc' + teamNum);
	}

	getTeamSimple(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/simple');
	}

	getYearsParticipated(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/years_participated');
	}

	getTeamDistricts(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/districts');
	}

	getTeamRobots(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/robots');
	}

	getTeamEventList(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/events');
	}

	getTeamEventList(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/events' + (year === undefined ? '' : '/' + year));
	}

	getTeamEventListSimple(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/events/simple');
	}

	getTeamEventListSimple(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/events' + (year === undefined ? '' : '/' + year) + '/simple');
	}

	getTeamEventListKeys(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/events/keys');
	}

	getTeamEventListKeys(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/events' + (year === undefined ? '' : '/' + year) + '/keys');
	}

	getTeamEventMatchList(teamNum, eventKey) {
		return this.callAPI('team/frc' + teamNum + '/event/' + eventKey + "/matches");
	}

	getTeamEventMatchListSimple(teamNum, eventKey) {
		return this.callAPI('team/frc' + teamNum + '/event/' + eventKey + "/matches/simple");
	}

	getTeamEventMatchListKeys(teamNum, eventKey) {
		return this.callAPI('team/frc' + teamNum + '/event/' + eventKey + "/matches/simple");
	}

	getTeamEventAwards(teamNum, eventKey) {
		return this.callAPI('team/frc' + teamNum + '/event/' + eventKey + '/awards');
	}

	getTeamEventStatus(teamNum, eventKey) {
		return this.callAPI('team/frc' + teamNum + '/event/' + eventKey + '/awards');
	}

	getTeamAwards(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/awards/' + year);
	}

	getTeamMatchList(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/matches/' + year);
	}

	getTeamMatchListSimple(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/matches/' + year + '/simple');
	}

	getTeamMatchListKeys(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/matches/' + year + '/keys');
	}

	getTeamMedia(teamNum, year) {
		return this.callAPI('team/frc' + teamNum + '/media/' + year);
	}

	getTeamSocialMedia(teamNum) {
		return this.callAPI('team/frc' + teamNum + '/social_media');
	}

	//Events - work on this

	getEventList(year) {
		return this.callAPI('events/' + year);
	}

	getEventListSimple(year) {
		return this.callAPI('events/' + year + '/simple');
	}

	getEventListKeys(year) {
		return this.callAPI('events/' + year + '/keys');
	}

	getEvent(eventKey) {
		return this.callAPI('event/' + eventKey);
	}

	getEventSimple(eventKey) {
		return this.callAPI('event/' + eventKey + '/simple');
	}

	getEventAlliances(eventKey) {
		return this.callAPI('event/' + eventKey + '/alliances');
	}

	getEventInsights(eventKey) {
		return this.callAPI('event/' + eventKey + '/insights');
	}

	getEventOprs(eventKey) {
		return this.callAPI('event/' + eventKey + '/oprs');
	}

	getEventPredictions(eventKey) {
		return this.callAPI('event/' + eventKey + '/predictions');
	}

	getEventTeams(eventKey) {
		return this.callAPI('event/' + eventKey + '/teams');
	}

	getEventTeamsSimple(eventKey) {
		return this.callAPI('event/' + eventKey + '/teams/simple');
	}

	getEventTeamsKeys(eventKey) {
		return this.callAPI('event/' + eventKey + '/teams/keys');
	}

	getEventMatches(eventKey) {
		return this.callAPI('event/' + eventKey + '/matches');
	}

	getEventMatchesSimple(eventKey) {
		return this.callAPI('event/' + eventKey + '/matches/simple');
	}

	getEventMatchesKeys(eventKey) {
		return this.callAPI('event/' + eventKey + '/matches/keys');
	}

	getEventRankings(eventKey) {
		return this.callAPI('event/' + eventKey + '/rankings');
	}

	getEventAwards(eventKey) {
		return this.callAPI('event/' + eventKey + '/awards');
	}

	getEventDistrictPoints(eventKey) {
		return this.callAPI('event/' + eventKey + '/district_points');
	}

	//Matches

	getMatch(matchKey) {
		return this.callAPI('match/' + matchKey);
	}

	getMatchSimple(matchKey) {
		return this.callAPI('match/' + matchKey + '/simple');
	}

	//Districts

	getDistrictList(year) {
		return this.callAPI('districts/' + year);
	}

	getDistrictEvents(districtShort) {
		return this.callAPI('district/' + districtShort + '/events');
	}

	getDistrictEventsSimple(districtShort) {
		return this.callAPI('district/' + districtShort + '/events/simple');
	}

	getDistrictEventsKeys(districtShort) {
		return this.callAPI('district/' + districtShort + '/events/keys');
	}

	getDistrictRankings(districtShort, year) {
		return this.callAPI('district/' + districtShort + '/' + year + '/rankings');
	}

	getDistrictTeams(districtShort, year) {
		return this.callAPI('district/' + districtShort + '/teams');
	}

	getDistrictTeamsSimple(districtShort, year) {
		return this.callAPI('district/' + districtShort + '/teams/simple');
	}

	getDistrictTeamsKeys(districtShort, year) {
		return this.callAPI('district/' + districtShort + '/teams/keys');
	}
}
module.exports = TBA;
<|endoftext|>


<commit_before>define(['jquery', 'underscore', 'oro/select2-component'], function($, _, Select2Component) {
    'use strict';

    var contexts = {};
    var organizations = {};
    var currentOrganization = null;

    function processData(data) {
        if (typeof data === 'undefined') {
            return;
        }

        var parsedItem = JSON.parse(data);
        if (parsedItem.contextText) {
            contexts[parsedItem.key] = {};
            contexts[parsedItem.key] = {
                id: JSON.stringify(parsedItem.contextValue),
                text: parsedItem.contextText,
            };
            if (parsedItem.organization) {
                organizations[parsedItem.key] = parsedItem.organization;
            }
        }
    }

    var Select2EmailRecipientsComponent = Select2Component.extend({
        $el: null,
        $contextEl: null,

        initialize: function(options) {
            this.$el = options._sourceElement;
            this.$contextEl = $('[data-ftid=oro_email_email_contexts]');
            this._initEditation();
            Select2EmailRecipientsComponent.__super__.initialize.apply(this, arguments);
        },

        preConfig: function() {
            var config = Select2EmailRecipientsComponent.__super__.preConfig.apply(this, arguments);

            var self = this;
            config.ajax.results = function(data) {
                var results = _.map(data.results, function(section) {
                    if (typeof section.children === 'undefined') {
                        processData(section.data);
                        self._onRecipientAdd.call(self, section.id);

                        return {
                            id: section.id,
                            text: section.text
                        };
                    }

                    return {
                        text: section.text,
                        children: _.map(section.children, function(item) {
                            processData(item.data);

                            return {
                                id: item.id,
                                text: item.text
                            };
                        })
                    };
                });

                self.$el.on('change', function(e) {
                    var data = self.$contextEl.select2('data');

                    if (e.added) {
                        self._onRecipientAdd.call(self, e.added.id);
                    }

                    if (e.removed) {
                        if (typeof contexts[e.removed.id] !== 'undefined') {
                            var newData = _.reject(data, function(item) {
                                return item.id === contexts[e.removed.id].id;
                            });
                            self.$contextEl.select2('data', newData);
                        }

                        if (_.isEmpty(self.$el.select2('val'))) {
                            currentOrganization = null;
                        }
                    }
                });

                return {results: results};
            };

            var originalData = config.ajax.data;
            config.ajax.data = function() {
                var params = originalData.apply(this, arguments);

                if (currentOrganization) {
                    params.organization = currentOrganization;
                }

                return params;
            };

            return config;
        },

        _onRecipientAdd: function(id) {
            if (typeof contexts[id] === 'undefined') {
                return;
            }

            var data = this.$contextEl.select2('data');
            currentOrganization = _.result(organizations, id, null);
            data.push(contexts[id]);
            this.$contextEl.select2('data', data);
        },

        _initEditation: function() {
            var $el = this.$el;
            this.$el.parent('.controls').on('click', '.select2-search-choice', function(e) {
                var $choice = $(this);
                var $searchField = $(this).parent('.select2-choices').find('input');

                var originalData = $el.select2('data');
                var selectedIndex = $choice.index();
                var removedItem = originalData[selectedIndex];
                var newData = _.reject(originalData, function(item, index) {
                    return index === selectedIndex;
                });

                $el.select2('data', newData);
                $searchField.click().val(removedItem.text).trigger('paste');
            });
        }
    });

    return Select2EmailRecipientsComponent;
});
<commit_msg>CRM-3884: New email could be trimmed<commit_after>define(['jquery', 'underscore', 'oro/select2-component'], function($, _, Select2Component) {
    'use strict';

    var contexts = {};
    var organizations = {};
    var currentOrganization = null;

    function processData(data) {
        if (typeof data === 'undefined') {
            return;
        }

        var parsedItem = JSON.parse(data);
        if (parsedItem.contextText) {
            contexts[parsedItem.key] = {};
            contexts[parsedItem.key] = {
                id: JSON.stringify(parsedItem.contextValue),
                text: parsedItem.contextText,
            };
            if (parsedItem.organization) {
                organizations[parsedItem.key] = parsedItem.organization;
            }
        }
    }

    var Select2EmailRecipientsComponent = Select2Component.extend({
        $el: null,
        $contextEl: null,

        initialize: function(options) {
            this.$el = options._sourceElement;
            this.$contextEl = $('[data-ftid=oro_email_email_contexts]');
            this._initEditation();
            Select2EmailRecipientsComponent.__super__.initialize.apply(this, arguments);
        },

        preConfig: function() {
            var config = Select2EmailRecipientsComponent.__super__.preConfig.apply(this, arguments);
            var emptyData = {id: '', text: ''};
            var searchChoice = {data: emptyData};

            var self = this;
            config.ajax.results = function(data) {
                var results = _.map(data.results, function(section) {
                    if (typeof section.children === 'undefined') {
                        processData(section.data);
                        self._onRecipientAdd.call(self, section.id);

                        return {
                            id: section.id,
                            text: section.text
                        };
                    }

                    return {
                        text: section.text,
                        children: _.map(section.children, function(item) {
                            processData(item.data);

                            return {
                                id: item.id,
                                text: item.text
                            };
                        })
                    };
                });

                self.$el.one('change', function(e) {
                    searchChoice.data = _.clone(emptyData);
                    var data = self.$contextEl.select2('data');

                    if (e.added) {
                        self._onRecipientAdd.call(self, e.added.id);
                    }

                    if (e.removed) {
                        if (typeof contexts[e.removed.id] !== 'undefined') {
                            var newData = _.reject(data, function(item) {
                                return item.id === contexts[e.removed.id].id;
                            });
                            self.$contextEl.select2('data', newData);
                        }

                        if (_.isEmpty(self.$el.select2('val'))) {
                            currentOrganization = null;
                        }
                    }
                });

                return {results: results};
            };

            var originalData = config.ajax.data;
            config.ajax.data = function() {
                var params = originalData.apply(this, arguments);

                if (currentOrganization) {
                    params.organization = currentOrganization;
                }

                return params;
            };

            config.createSearchChoice = function(term, data) {
                if (!dataHasText(data, term)) {
                    searchChoice.data = _.clone(emptyData);
                    searchChoice.data.id = term;
                    searchChoice.data.text = term;

                    return searchChoice.data;
                }
            };

            this.$el.on('select2-init', function() {
                var select2 = $(this).data('select2');

                select2.search.on('keyup', function() {
                    var val = $(this).val();
                    if (!val) {
                        return;
                    }

                    searchChoice.data.text = val;
                    searchChoice.data.id = val;
                });

                var originalSelectHighlighted = select2.selectHighlighted;
                select2.selectHighlighted = function() {
                    if (!this.results.find('.select2-highlighted').length) {
                        var val = this.search.val();
                        this.onSelect({
                            id: val,
                            text: val
                        });
                    }

                    originalSelectHighlighted.apply(this, arguments);
                };
            });

            return config;
        },

        _onRecipientAdd: function(id) {
            if (typeof contexts[id] === 'undefined') {
                return;
            }

            var data = this.$contextEl.select2('data');
            currentOrganization = _.result(organizations, id, null);
            data.push(contexts[id]);
            this.$contextEl.select2('data', data);
        },

        _initEditation: function() {
            var $el = this.$el;
            this.$el.parent('.controls').on('click', '.select2-search-choice', function(e) {
                var $choice = $(this);
                var $searchField = $(this).parent('.select2-choices').find('input');

                var originalData = $el.select2('data');
                var selectedIndex = $choice.index();
                var removedItem = originalData[selectedIndex];
                var newData = _.reject(originalData, function(item, index) {
                    return index === selectedIndex;
                });

                $el.select2('data', newData);
                $searchField.click().val(removedItem.text).trigger('paste');
            });
        }
    });

    function dataHasText(data, text) {
        return _.some(data, function(row) {
            if (!row.hasOwnProperty('children')) {
                return row.text.localeCompare(text) === 0;
            }

            return dataHasText(row.children, text);
        });
    }

    return Select2EmailRecipientsComponent;
});
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import Well from 'react-bootstrap/lib/Well';
import Helmet from 'react-helmet';
import superagent from 'superagent';
import cookie from 'react-cookie';

export default class Activation extends Component {
  state = {
    responseStatus: 0,
    responseMsg: ''
  }

  componentWillMount() {
    superagent
    .post('/activation')
    .set('Accept', 'application/json')
    .end((error, res) => {
      if (res.body.status === 1) {
        this.setState({responseStatus: 1});
        this.setState({responseMsg: 'Dein Account wurde erfolgreich bestätigt! Herzlich willkommen bei der Swiss React Community! '});
        cookie.save('ck_status', true, { expires: new Date(new Date().getTime() + (3600*3600*3600)) });
      } else {
        this.setState({responseStatus: 2});
        this.setState({responseMsg: 'Es liegt ein Fehler mit der Bestätigung deines Accounts vor, bitte versuche es später nochmals! '});
        cookie.save('ck_status', false, { expires: new Date(new Date().getTime() + (3600*3600*3600)) });
      }
    });
  }

  render() {
    const {responseMsg, responseStatus} = this.state;
    return (

        <Helmet title="Aktivierung"/>
          {responseStatus === 0 ?

Fehler: Seite existiert nicht

            : null
          }
          {responseStatus === 1 ?
            <Well>

Erfolgreich Account bestätigt

            </Well>
            : null
          }
          {responseStatus === 2 ?
            <Well>

Fehler bei der Bestätigung deines Accounts

            </Well>
            : null
          }

    )
  }
}
<commit_msg>preload images FIX 3 DEFss<commit_after>import React, {Component} from 'react';
import Well from 'react-bootstrap/lib/Well';
import Helmet from 'react-helmet';
import superagent from 'superagent';
import cookie from 'react-cookie';

export default class Activation extends Component {
  state = {
    responseStatus: 0,
    responseMsg: ''
  }

  componentWillMount() {
    superagent
    .get('/activation')
    .set('Accept', 'application/json')
    .end((error, res) => {
      if (res.body.status === 1) {
        this.setState({responseStatus: 1});
        this.setState({responseMsg: 'Dein Account wurde erfolgreich bestätigt! Herzlich willkommen bei der Swiss React Community! '});
        cookie.save('ck_status', true, { expires: new Date(new Date().getTime() + (3600*3600*3600)) });
      } else {
        this.setState({responseStatus: 2});
        this.setState({responseMsg: 'Es liegt ein Fehler mit der Bestätigung deines Accounts vor, bitte versuche es später nochmals! '});
        cookie.save('ck_status', false, { expires: new Date(new Date().getTime() + (3600*3600*3600)) });
      }
    });
  }

  render() {
    const {responseMsg, responseStatus} = this.state;
    return (

        <Helmet title="Aktivierung"/>
          {responseStatus === 0 ?

Fehler: Seite existiert nicht

            : null
          }
          {responseStatus === 1 ?
            <Well>

Erfolgreich Account bestätigt

            </Well>
            : null
          }
          {responseStatus === 2 ?
            <Well>

Fehler bei der Bestätigung deines Accounts

            </Well>
            : null
          }

    )
  }
}
<|endoftext|>


<commit_before>/*
Copyright 2015 OpenMarket Ltd

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

'use strict';

var React = require("react");
var MatrixClientPeg = require("../../MatrixClientPeg");
var PresetValues = require('../atoms/create_room/Presets').Presets;
var q = require('q');
var encryption = require("../../encryption");

module.exports = {
    propTypes: {
        onRoomCreated: React.PropTypes.func,
    },

    phases: {
        CONFIG: "CONFIG",  // We're waiting for user to configure and hit create.
        CREATING: "CREATING",  // We're sending the request.
        CREATED: "CREATED",  // We successfully created the room.
        ERROR: "ERROR",  // There was an error while trying to create room.
    },

    getDefaultProps: function() {
        return {
            onRoomCreated: function() {},
        };
    },

    getInitialState: function() {
        return {
            phase: this.phases.CONFIG,
            error_string: "",
            is_private: true,
            share_history: false,
            default_preset: PresetValues.PrivateChat,
            topic: '',
            room_name: '',
            invited_users: [],
        };
    },

    onCreateRoom: function() {
        var options = {};

        if (this.state.room_name) {
            options.name = this.state.room_name;
        }

        if (this.state.topic) {
            options.topic = this.state.topic;
        }

        if (this.state.preset) {
            if (this.state.preset != PresetValues.Custom) {
                options.preset = this.state.preset;
            } else {
                options.initial_state = [
                    {
                        type: "m.room.join_rules",
                        content: {
                            "join_rules": this.state.is_private ? "invite" : "public"
                        }
                    },
                    {
                        type: "m.room.history_visibility",
                        content: {
                            "history_visibility": this.state.share_history ? "shared" : "invited"
                        }
                    },
                ];
            }
        }

        options.invite = this.state.invited_users;

        var alias = this.getAliasLocalpart();
        if (alias) {
            options.room_alias_name = alias;
        }

        var cli = MatrixClientPeg.get();
        if (!cli) {
            // TODO: Error.
            console.error("Cannot create room: No matrix client.");
            return;
        }

        var deferred = cli.createRoom(options);

        var response;

        if (this.state.encrypt) {
            deferred = deferred.then(function(res) {
                response = res;
                return encryption.enableEncryption(
                    cli, response.roomId, options.invite
                );
            }).then(function() {
                return q(response) }
            );
        }

        this.setState({
            phase: this.phases.CREATING,
        });

        var self = this;

        deferred.then(function (resp) {
            self.setState({
                phase: self.phases.CREATED,
            });
            self.props.onRoomCreated(resp.room_id);
        }, function(err) {
            self.setState({
                phase: self.phases.ERROR,
                error_string: err.toString(),
            });
        });
    }
};
<commit_msg>Fix bugs from typos from hackathon<commit_after>/*
Copyright 2015 OpenMarket Ltd

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

'use strict';

var React = require("react");
var MatrixClientPeg = require("../../MatrixClientPeg");
var PresetValues = require('../atoms/create_room/Presets').Presets;
var q = require('q');
var encryption = require("../../encryption");

module.exports = {
    propTypes: {
        onRoomCreated: React.PropTypes.func,
    },

    phases: {
        CONFIG: "CONFIG",  // We're waiting for user to configure and hit create.
        CREATING: "CREATING",  // We're sending the request.
        CREATED: "CREATED",  // We successfully created the room.
        ERROR: "ERROR",  // There was an error while trying to create room.
    },

    getDefaultProps: function() {
        return {
            onRoomCreated: function() {},
        };
    },

    getInitialState: function() {
        return {
            phase: this.phases.CONFIG,
            error_string: "",
            is_private: true,
            share_history: false,
            default_preset: PresetValues.PrivateChat,
            topic: '',
            room_name: '',
            invited_users: [],
        };
    },

    onCreateRoom: function() {
        var options = {};

        if (this.state.room_name) {
            options.name = this.state.room_name;
        }

        if (this.state.topic) {
            options.topic = this.state.topic;
        }

        if (this.state.preset) {
            if (this.state.preset != PresetValues.Custom) {
                options.preset = this.state.preset;
            } else {
                options.initial_state = [
                    {
                        type: "m.room.join_rules",
                        content: {
                            "join_rule": this.state.is_private ? "invite" : "public"
                        }
                    },
                    {
                        type: "m.room.history_visibility",
                        content: {
                            "history_visibility": this.state.share_history ? "shared" : "invited"
                        }
                    },
                ];
            }
        }

        options.invite = this.state.invited_users;

        var alias = this.getAliasLocalpart();
        if (alias) {
            options.room_alias_name = alias;
        }

        var cli = MatrixClientPeg.get();
        if (!cli) {
            // TODO: Error.
            console.error("Cannot create room: No matrix client.");
            return;
        }

        var deferred = cli.createRoom(options);

        var response;

        if (this.state.encrypt) {
            deferred = deferred.then(function(res) {
                response = res;
                return encryption.enableEncryption(
                    cli, response.room_id, options.invite
                );
            }).then(function() {
                return q(response) }
            );
        }

        this.setState({
            phase: this.phases.CREATING,
        });

        var self = this;

        deferred.then(function (resp) {
            self.setState({
                phase: self.phases.CREATED,
            });
            self.props.onRoomCreated(resp.room_id);
        }, function(err) {
            self.setState({
                phase: self.phases.ERROR,
                error_string: err.toString(),
            });
        });
    }
};
<|endoftext|>


<commit_before>var playoff = {

    settings: {
        'winner_h_offset': 5,
        'loser_h_offset': 20,
        'place_winner_h_offset': 10,
        'place_loser_h_offset': 15,
        'finish_winner_h_offset': 5,
        'finish_loser_h_offset': 20,
        'winner_v_offset': -10,
        'loser_v_offset': 10,
        'place_winner_v_offset': 2,
        'place_loser_v_offset': 9,
        'finish_winner_v_offset': -4,
        'finish_loser_v_offset': 4,
        'loser_colour': '#ff0000',
        'winner_colour': '#00ff00',
        'place_loser_colour': '#dddd00',
        'place_winner_colour': '#00dddd',
        'finish_loser_colour': '#ff0000',
        'finish_winner_colour': '#00ff00'
    },

    drawLine: function(ctx, line) {
        ctx.beginPath();
        ctx.moveTo(line[0], line[1]);
        ctx.lineTo(line[2], line[3]);
        ctx.stroke();
    },

    loadSettings: function(canvas, defaults) {
        for (var setting in defaults) {
            var attr = 'data-' + setting.replace(/_/g, '-');
            var attr_value = canvas.getAttribute(attr);
            if (attr_value) {
                defaults[setting] = attr_value;
            }
        }
        return defaults;
    },

    run: function() {
        var boxes = document.getElementsByClassName('playoff_matchbox');
        var lines = {
            'winner': {},
            'loser': {},
            'place-winner': {},
            'place-loser': {},
            'finish-winner': {},
            'finish-loser': {}
        };
        var boxes_idx = {};
        for (var b = 0; b < boxes.length; b++) {
            var id = boxes[b].getAttribute('data-id');
            boxes_idx[id] = boxes[b];
            for (var attr in lines) {
                var value = boxes[b].getAttribute('data-' + attr);
                if (value) {
                    if (!lines[attr][value]) {
                        lines[attr][value] = [];
                    }
                    lines[attr][value].push(id);
                }
            }
        }
        var canvas = document.getElementById('playoff_canvas');
        this.settings = this.loadSettings(canvas, this.settings);
        var lineMethods = {
            'place-winner': 'to',
            'place-loser': 'to',
            'finish-winner': 'midpoint',
            'finish-loser': 'midpoint',
            'winner': 'midpoint',
            'loser': 'midpoint'
        };
        var lineCalculator = {
            correctLines: function(hLines, vLine, comparator) {
                for (var l1 in hLines) {
                    for (var l2 in hLines) {
                        hLines[l1][2] = comparator(hLines[l1][2], hLines[l2][2]);
                        hLines[l2][2] = hLines[l1][2];
                    }
                }
                for (var l1 in hLines) {
                    vLine[0] = vLine[2] = comparator(hLines[l1][2], vLine[2]);
                    vLine[1] = Math.min(vLine[1], hLines[l1][3]);
                    vLine[3] = Math.max(vLine[3], hLines[l1][3]);
                }
            },
            template: function() {
                return {
                    hFrom: [],
                    vFrom: [0, canvas.height, 0, 0],
                    hTo: [],
                    vTo: [canvas.width, canvas.height, canvas.width, 0],
                    midpoints: []
                }
            },
            from: function(from, to, hOffset, vOffset) {
                var lines = this.template();
                for (var f = 0; f < from.length; f++) {
                    var box = boxes_idx[from[f]];
                    var line = [
                        Math.floor(parseInt(box.offsetLeft) + parseInt(box.clientWidth)),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset),
                        Math.floor(parseInt(box.offsetLeft) + parseInt(box.clientWidth) + hOffset),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset)
                    ];
                    lines.hFrom.push(line);
                }
                this.correctLines(lines.hFrom, lines.vFrom, Math.max);
                for (var t = 0; t < to.length; t++) {
                    var box = boxes_idx[to[t]];
                    var line = [
                        Math.floor(parseInt(box.offsetLeft)),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset),
                        lines.vFrom[0],
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset)
                    ];
                    lines.hTo.push(line);
                }
                this.correctLines(lines.hTo, lines.vTo, Math.min);
                lines.midpoints = [
                    [lines.vFrom[0], lines.vFrom[1]],
                    [lines.vTo[0], lines.vTo[1]]
                ];
                return lines;
            },
            to: function(from, to, hOffset, vOffset) {
                var lines = this.template();
                for (var t = 0; t < to.length; t++) {
                    var box = boxes_idx[to[t]];
                    var line = [
                        parseInt(box.offsetLeft),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset),
                        Math.floor(parseInt(box.offsetLeft) - hOffset),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset)
                    ];
                    lines.hTo.push(line);
                }
                this.correctLines(lines.hTo, lines.vTo, Math.min);
                for (var f = 0; f < from.length; f++) {
                    var box = boxes_idx[from[f]];
                    var line = [
                        Math.floor(parseInt(box.offsetLeft) + parseInt(box.clientWidth)),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset),
                        lines.vTo[0],
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset)
                    ];
                    lines.hFrom.push(line);
                }
                this.correctLines(lines.hFrom, lines.vFrom, Math.max);
                lines.midpoints = [
                    [lines.vFrom[0], lines.vFrom[1]],
                    [lines.vTo[0], lines.vTo[1]]
                ];
                return lines;
            },
            midpoint: function(from, to, hOffset, vOffset) {
                var lines = this.template();
                for (var f = 0; f < from.length; f++) {
                    var box = boxes_idx[from[f]];
                    var line = [
                        Math.floor(parseInt(box.offsetLeft) + parseInt(box.clientWidth)),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset),
                        Math.floor(parseInt(box.offsetLeft) + parseInt(box.clientWidth) + hOffset),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset)
                    ];
                    lines.hFrom.push(line);
                }
                this.correctLines(lines.hFrom, lines.vFrom, Math.max);
                for (var t = 0; t < to.length; t++) {
                    var box = boxes_idx[to[t]];
                    var line = [
                        parseInt(box.offsetLeft),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset),
                        Math.floor(parseInt(box.offsetLeft) - hOffset),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset)
                    ];
                    lines.hTo.push(line);
                }
                this.correctLines(lines.hTo, lines.vTo, Math.min);
                lines.midpoints = [
                    [
                        (lines.vFrom[0] + lines.vFrom[2]) / 2,
                        (lines.vFrom[1] + lines.vFrom[3]) / 2
                    ],
                    [
                        hOffset / 2 + (lines.vFrom[0] + lines.vFrom[2] + lines.vTo[0] + lines.vTo[2]) / 4,
                        (lines.vFrom[1] + lines.vFrom[3]) / 2
                    ],
                    [
                        hOffset / 2 + (lines.vFrom[0] + lines.vFrom[2] + lines.vTo[0] + lines.vTo[2]) / 4,
                        (lines.vTo[1] + lines.vTo[3]) / 2
                    ],
                    [
                        (lines.vTo[0] + lines.vTo[2]) / 2,
                        (lines.vTo[1] + lines.vTo[3]) / 2
                    ]
                ]
                return lines;
            }
        };
        var ctx = canvas.getContext('2d');
        for (var type in lines) {
            styleType = type.replace('-', '_');
            ctx.strokeStyle = this.settings[styleType + '_colour'];
            for (var from in lines[type]) {
                var to = lines[type][from];
                from = from.split(' ');
                var linesToDraw = lineCalculator[lineMethods[type]](
                    from, to,
                    this.settings[styleType + '_h_offset'], this.settings[styleType + '_v_offset']);
                for (var l in linesToDraw.hFrom) {
                    this.drawLine(ctx, linesToDraw.hFrom[l]);
                }
                this.drawLine(ctx, linesToDraw.vFrom);
                for (var l in linesToDraw.hTo) {
                    this.drawLine(ctx, linesToDraw.hTo[l]);
                }
                this.drawLine(ctx, linesToDraw.vTo);
                for (var m = 0; m < linesToDraw.midpoints.length-1; m++) {
                    this.drawLine(ctx, [
                        linesToDraw.midpoints[m][0], linesToDraw.midpoints[m][1],
                        linesToDraw.midpoints[m+1][0], linesToDraw.midpoints[m+1][1]
                    ]);
                }
            }
        }
    }

}

playoff.run();
<commit_msg>Fix for overlapping lines if match boxes are wider than expected<commit_after>var playoff = {

    settings: {
        'winner_h_offset': 5,
        'loser_h_offset': 20,
        'place_winner_h_offset': 10,
        'place_loser_h_offset': 15,
        'finish_winner_h_offset': 5,
        'finish_loser_h_offset': 20,
        'winner_v_offset': -10,
        'loser_v_offset': 10,
        'place_winner_v_offset': 2,
        'place_loser_v_offset': 9,
        'finish_winner_v_offset': -4,
        'finish_loser_v_offset': 4,
        'loser_colour': '#ff0000',
        'winner_colour': '#00ff00',
        'place_loser_colour': '#dddd00',
        'place_winner_colour': '#00dddd',
        'finish_loser_colour': '#ff0000',
        'finish_winner_colour': '#00ff00'
    },

    drawLine: function(ctx, line) {
        ctx.beginPath();
        ctx.moveTo(line[0], line[1]);
        ctx.lineTo(line[2], line[3]);
        ctx.stroke();
    },

    loadSettings: function(canvas, defaults) {
        for (var setting in defaults) {
            var attr = 'data-' + setting.replace(/_/g, '-');
            var attr_value = canvas.getAttribute(attr);
            if (attr_value) {
                defaults[setting] = attr_value;
            }
        }
        return defaults;
    },

    run: function() {
        var boxes = document.getElementsByClassName('playoff_matchbox');
        var lines = {
            'winner': {},
            'loser': {},
            'place-winner': {},
            'place-loser': {},
            'finish-winner': {},
            'finish-loser': {}
        };
        var boxes_idx = {};
        for (var b = 0; b < boxes.length; b++) {
            var id = boxes[b].getAttribute('data-id');
            boxes_idx[id] = boxes[b];
            for (var attr in lines) {
                var value = boxes[b].getAttribute('data-' + attr);
                if (value) {
                    if (!lines[attr][value]) {
                        lines[attr][value] = [];
                    }
                    lines[attr][value].push(id);
                }
            }
        }
        var canvas = document.getElementById('playoff_canvas');
        this.settings = this.loadSettings(canvas, this.settings);
        var lineMethods = {
            'place-winner': 'to',
            'place-loser': 'to',
            'finish-winner': 'midpoint',
            'finish-loser': 'midpoint',
            'winner': 'midpoint',
            'loser': 'midpoint'
        };
        var lineCalculator = {
            correctLines: function(hLines, vLine, comparator) {
                for (var l1 in hLines) {
                    for (var l2 in hLines) {
                        hLines[l1][2] = comparator(hLines[l1][2], hLines[l2][2]);
                        hLines[l2][2] = hLines[l1][2];
                    }
                }
                for (var l1 in hLines) {
                    vLine[0] = vLine[2] = comparator(hLines[l1][2], vLine[2]);
                    vLine[1] = Math.min(vLine[1], hLines[l1][3]);
                    vLine[3] = Math.max(vLine[3], hLines[l1][3]);
                }
            },
            template: function() {
                return {
                    hFrom: [],
                    vFrom: [0, canvas.height, 0, 0],
                    hTo: [],
                    vTo: [canvas.width, canvas.height, canvas.width, 0],
                    midpoints: []
                }
            },
            from: function(from, to, hOffset, vOffset) {
                var lines = this.template();
                for (var f = 0; f < from.length; f++) {
                    var box = boxes_idx[from[f]];
                    var line = [
                        Math.floor(parseInt(box.offsetLeft) + parseInt(box.clientWidth)),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset),
                        Math.floor(parseInt(box.offsetLeft) + parseInt(box.clientWidth) + hOffset),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset)
                    ];
                    lines.hFrom.push(line);
                }
                this.correctLines(lines.hFrom, lines.vFrom, Math.max);
                for (var t = 0; t < to.length; t++) {
                    var box = boxes_idx[to[t]];
                    var line = [
                        Math.floor(parseInt(box.offsetLeft)),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset),
                        lines.vFrom[0],
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset)
                    ];
                    lines.hTo.push(line);
                }
                this.correctLines(lines.hTo, lines.vTo, Math.min);
                lines.midpoints = [
                    [lines.vFrom[0], lines.vFrom[1]],
                    [lines.vTo[0], lines.vTo[1]]
                ];
                return lines;
            },
            to: function(from, to, hOffset, vOffset) {
                var lines = this.template();
                for (var t = 0; t < to.length; t++) {
                    var box = boxes_idx[to[t]];
                    var line = [
                        parseInt(box.offsetLeft),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset),
                        Math.floor(parseInt(box.offsetLeft) - hOffset),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset)
                    ];
                    lines.hTo.push(line);
                }
                this.correctLines(lines.hTo, lines.vTo, Math.min);
                for (var f = 0; f < from.length; f++) {
                    var box = boxes_idx[from[f]];
                    var line = [
                        Math.floor(parseInt(box.offsetLeft) + parseInt(box.clientWidth)),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset),
                        lines.vTo[0],
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset)
                    ];
                    lines.hFrom.push(line);
                }
                this.correctLines(lines.hFrom, lines.vFrom, Math.max);
                lines.midpoints = [
                    [lines.vFrom[0], lines.vFrom[1]],
                    [lines.vTo[0], lines.vTo[1]]
                ];
                return lines;
            },
            midpoint: function(from, to, hOffset, vOffset) {
                var lines = this.template();
                for (var f = 0; f < from.length; f++) {
                    var box = boxes_idx[from[f]];
                    var line = [
                        Math.floor(parseInt(box.offsetLeft) + parseInt(box.clientWidth)),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset),
                        Math.floor(parseInt(box.offsetLeft) + parseInt(box.clientWidth) + hOffset),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset)
                    ];
                    lines.hFrom.push(line);
                }
                this.correctLines(lines.hFrom, lines.vFrom, Math.max);
                for (var t = 0; t < to.length; t++) {
                    var box = boxes_idx[to[t]];
                    var line = [
                        parseInt(box.offsetLeft),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset),
                        Math.floor(parseInt(box.offsetLeft) - hOffset),
                        Math.floor(parseInt(box.offsetTop) + 0.5 * parseInt(box.clientHeight) + vOffset)
                    ];
                    lines.hTo.push(line);
                }
                this.correctLines(lines.hTo, lines.vTo, Math.min);
                lines.midpoints = [
                    [
                        (lines.vFrom[0] + lines.vFrom[2]) / 2,
                        (lines.vFrom[1] + lines.vFrom[3]) / 2
                    ],
                    [
                        hOffset / 2 + (lines.vFrom[0] + lines.vFrom[2] + lines.vTo[0] + lines.vTo[2]) / 4,
                        (lines.vFrom[1] + lines.vFrom[3]) / 2
                    ],
                    [
                        hOffset / 2 + (lines.vFrom[0] + lines.vFrom[2] + lines.vTo[0] + lines.vTo[2]) / 4,
                        (lines.vTo[1] + lines.vTo[3]) / 2
                    ],
                    [
                        (lines.vTo[0] + lines.vTo[2]) / 2,
                        (lines.vTo[1] + lines.vTo[3]) / 2
                    ]
                ]
                for (var h in lines.hTo) {
                    lines.hTo[h][2] = Math.max(
                        lines.hTo[h][2],
                        lines.midpoints[2][0]
                    );
                }
                for (var h in lines.hFrom) {
                    lines.hFrom[h][2] = Math.min(
                        lines.hFrom[h][2],
                        lines.midpoints[0][0]
                    );
                }
                return lines;
            }
        };
        var ctx = canvas.getContext('2d');
        for (var type in lines) {
            styleType = type.replace('-', '_');
            ctx.strokeStyle = this.settings[styleType + '_colour'];
            for (var from in lines[type]) {
                var to = lines[type][from];
                from = from.split(' ');
                var linesToDraw = lineCalculator[lineMethods[type]](
                    from, to,
                    this.settings[styleType + '_h_offset'], this.settings[styleType + '_v_offset']);
                for (var l in linesToDraw.hFrom) {
                    this.drawLine(ctx, linesToDraw.hFrom[l]);
                }
                this.drawLine(ctx, linesToDraw.vFrom);
                for (var l in linesToDraw.hTo) {
                    this.drawLine(ctx, linesToDraw.hTo[l]);
                }
                this.drawLine(ctx, linesToDraw.vTo);
                for (var m = 0; m < linesToDraw.midpoints.length-1; m++) {
                    if (linesToDraw.midpoints[m][0] <= linesToDraw.midpoints[m+1][0]) {
                        this.drawLine(ctx, [
                            linesToDraw.midpoints[m][0], linesToDraw.midpoints[m][1],
                            linesToDraw.midpoints[m+1][0], linesToDraw.midpoints[m+1][1]
                        ]);
                    }
                }
            }
        }
    }

}

playoff.run();
<|endoftext|>


<commit_before>/* global Promise */

var express = require("express");
var bodyParser = require("body-parser");
var fs = require("fs");
var spawn = require("child_process").spawn;

var app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get("/is_crawling", function isCrawling(req, res) {
  fs.stat("crawling.lock", function statResult(err) {
    if (err) {
      res.json({
        crawling: false
      });
    } else {
      res.json({
        crawling: true
      });
    }
  });
});

/**
 * withCrawlingLockAsync
 *
 * Execute the function @crawl with a lock, to ensure that @crawl cannot
 * be executed more than one simultaneously. This functions checks for a
 * crawling.lock file, then creates it and continues.
 *
 * Obviously, this isn't race condition proof, but should be good enough for
 * now.
 *
 * @param crawl {function} - The function to call to start crawling
 * @param error {function} - An error handler function
 * @param done {function} - The function to call when we're done with the lock
 * @returns {undefined}
 */
function withCrawlingLockAsync(crawl, error, done) {
  fs.stat("crawling.lock", function statResult(errStat) {
    /* We want this */
    if (errStat) {
      fs.writeFile("crawling.lock", function onErrorWrite(errWrite) {
        if (errWrite) {
          error(errWrite);
          return;
        }

        crawl(function onDoneCrawling() {
          fs.unlink("crawling.lock", function onErrorUnlink(errUnlink) {
            if (errUnlink) {
              error(errUnlink);
              return;
            }

            done.apply(arguments);
          });
        });
      });
    } else {
      error("Lock file already exists! Cannot crawl");
    }
  });
}

app.post("/start_crawling", function startCrawling(req, res) {
  withCrawlingLockAsync(function onAcquiredLock(done) {
    res.status(200);
    res.json({
      status: "started"
    });

    new Promise(function downloadDocuments(resolve, reject) {
      // Create child python process
      var loadProc = spawn("./python-virtualenv/bin/python", ["./python-virtualenv/bin/download-pubmed-articles"], {
        stdio: ["pipe", "inherit", "inherit"]
      });
      loadProc.on("exit", function onExit(code, signal) {
        if (code !== 0 || signal) {
          reject("Crawling process failed with " + code + " " + signal);
        } else {
          resolve();
        }
      });
    }).then(function parseDocuments() {
      return new Promise(function parseXML(resolve, reject) {
        // Create child python process
        var loadProc = spawn("./python-virtualenv/bin/python", ["./python-virtualenv/bin/parse-pubmed-files", "Retractions"], {
          stdio: ["pipe", "pipe", "pipe"]
        });
        var stdout = [];
        loadProc.on("exit", function onExit(code, signal) {
          if (code !== 0 || signal) {
            reject("Crawling process failed with " + code + " " + signal);
          } else {
            console.log(stdout.join(""));  // eslint-disable-line no-console
            resolve(JSON.parse(stdout.join("")));
          }
        });
        loadProc.stdout.on("data", function onData(data) {
          stdout.push(String(data));
        });
      });
    }).then(function loadDatabase(json) {
      return new Promise(function loadDB(resolve, reject) {
        // Create child python process
        var loadProc = spawn("./python-virtualenv/bin/python", ["./python-virtualenv/bin/load-pubmed-files"], {
          stdio: ["pipe", "inherit", "inherit"]
        });
        // Crawling is completed now, resolve or reject promise
        loadProc.on("exit", function onExit(code, signal) {
          if (code !== 0 || signal) {
            reject("Crawling process failed with " + code + " " + signal);
          } else {
            resolve();
          }
        });
        loadProc.stdin.write(JSON.stringify(json));
        loadProc.stdin.end();
      });
    }).then(function onDone() {
      done();
    })
    .catch(function onError(error) {
      // eslint-disable-next-line no-console
      console.error("Crawing process failed with " + error + " " + error.stack);
      done();
    });
  }, function onErrorAcquiringLock(error) {
    res.send(500);
    res.json({
      status: "failure",
      message: String(error)
    });
  }, function onDoneWithLock() {
  });

  res.json({
    status: "started"
  });
});

app.set("port", 6001);

app.listen(app.get("port"), function onPort() {
  // eslint-disable-next-line no-console
  console.log("Scraper service server listening on port " + server.address().port);
});
<commit_msg>scraper: Just hardcode the port<commit_after>/* global Promise */

var express = require("express");
var bodyParser = require("body-parser");
var fs = require("fs");
var spawn = require("child_process").spawn;

var app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get("/is_crawling", function isCrawling(req, res) {
  fs.stat("crawling.lock", function statResult(err) {
    if (err) {
      res.json({
        crawling: false
      });
    } else {
      res.json({
        crawling: true
      });
    }
  });
});

/**
 * withCrawlingLockAsync
 *
 * Execute the function @crawl with a lock, to ensure that @crawl cannot
 * be executed more than one simultaneously. This functions checks for a
 * crawling.lock file, then creates it and continues.
 *
 * Obviously, this isn't race condition proof, but should be good enough for
 * now.
 *
 * @param crawl {function} - The function to call to start crawling
 * @param error {function} - An error handler function
 * @param done {function} - The function to call when we're done with the lock
 * @returns {undefined}
 */
function withCrawlingLockAsync(crawl, error, done) {
  fs.stat("crawling.lock", function statResult(errStat) {
    /* We want this */
    if (errStat) {
      fs.writeFile("crawling.lock", function onErrorWrite(errWrite) {
        if (errWrite) {
          error(errWrite);
          return;
        }

        crawl(function onDoneCrawling() {
          fs.unlink("crawling.lock", function onErrorUnlink(errUnlink) {
            if (errUnlink) {
              error(errUnlink);
              return;
            }

            done.apply(arguments);
          });
        });
      });
    } else {
      error("Lock file already exists! Cannot crawl");
    }
  });
}

app.post("/start_crawling", function startCrawling(req, res) {
  withCrawlingLockAsync(function onAcquiredLock(done) {
    res.status(200);
    res.json({
      status: "started"
    });

    new Promise(function downloadDocuments(resolve, reject) {
      // Create child python process
      var loadProc = spawn("./python-virtualenv/bin/python", ["./python-virtualenv/bin/download-pubmed-articles"], {
        stdio: ["pipe", "inherit", "inherit"]
      });
      loadProc.on("exit", function onExit(code, signal) {
        if (code !== 0 || signal) {
          reject("Crawling process failed with " + code + " " + signal);
        } else {
          resolve();
        }
      });
    }).then(function parseDocuments() {
      return new Promise(function parseXML(resolve, reject) {
        // Create child python process
        var loadProc = spawn("./python-virtualenv/bin/python", ["./python-virtualenv/bin/parse-pubmed-files", "Retractions"], {
          stdio: ["pipe", "pipe", "pipe"]
        });
        var stdout = [];
        loadProc.on("exit", function onExit(code, signal) {
          if (code !== 0 || signal) {
            reject("Crawling process failed with " + code + " " + signal);
          } else {
            console.log(stdout.join(""));  // eslint-disable-line no-console
            resolve(JSON.parse(stdout.join("")));
          }
        });
        loadProc.stdout.on("data", function onData(data) {
          stdout.push(String(data));
        });
      });
    }).then(function loadDatabase(json) {
      return new Promise(function loadDB(resolve, reject) {
        // Create child python process
        var loadProc = spawn("./python-virtualenv/bin/python", ["./python-virtualenv/bin/load-pubmed-files"], {
          stdio: ["pipe", "inherit", "inherit"]
        });
        // Crawling is completed now, resolve or reject promise
        loadProc.on("exit", function onExit(code, signal) {
          if (code !== 0 || signal) {
            reject("Crawling process failed with " + code + " " + signal);
          } else {
            resolve();
          }
        });
        loadProc.stdin.write(JSON.stringify(json));
        loadProc.stdin.end();
      });
    }).then(function onDone() {
      done();
    })
    .catch(function onError(error) {
      // eslint-disable-next-line no-console
      console.error("Crawing process failed with " + error + " " + error.stack);
      done();
    });
  }, function onErrorAcquiringLock(error) {
    res.send(500);
    res.json({
      status: "failure",
      message: String(error)
    });
  }, function onDoneWithLock() {
  });

  res.json({
    status: "started"
  });
});

app.set("port", 6001);

app.listen(app.get("port"), function onPort() {
  // eslint-disable-next-line no-console
  console.log("Scraper service server listening on port 6001");
});
<|endoftext|>


<commit_before>/*
 * #%L
 * BroadleafCommerce Open Admin Platform
 * %%
 * Copyright (C) 2009 - 2013 Broadleaf Commerce
 * %%
 * 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.
 * #L%
 */
$(document).ready(function() {

	$('body').on('click', '.modal-footer button.btn-primary', function() {
		$(this).closest('div.modal').find('form').submit();
	});

	$('body').on('shown', '.modal', function () {
		$("html").css({ overflow: 'hidden' });
	});

	$('body').on('hide', '.modal', function () {
		$("html").css({ overflow: 'inherit' });
	});

	$('body').on('click', 'a.modal-view', function() {
    	BLCAdmin.showLinkAsModal($(this).attr('href'));
		return false;
	});

});<commit_msg>#890 - Scroll gets disabled when hiding a modal in the admin<commit_after>/*
 * #%L
 * BroadleafCommerce Open Admin Platform
 * %%
 * Copyright (C) 2009 - 2013 Broadleaf Commerce
 * %%
 * 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.
 * #L%
 */
$(document).ready(function() {

	$('body').on('click', '.modal-footer button.btn-primary', function() {
		$(this).closest('div.modal').find('form').submit();
	});

	$('body').on('shown', '.modal', function () {
		$("html").css({ overflow: 'hidden' });
	});

	$('body').on('hide', '.modal', function () {
		$("html").css({ overflow: 'auto' });
	});

	$('body').on('click', 'a.modal-view', function() {
    	BLCAdmin.showLinkAsModal($(this).attr('href'));
		return false;
	});

});<|endoftext|>