<commit_before>
var fs = require('fs'),
    path = require('path'),
    should = require('should');
var purest = require('../../lib/provider'),
    providers = require('../../config/providers');
var image = path.resolve(__dirname, '../fixtures/cat.png'),
    audio = path.resolve(__dirname, '../fixtures/beep.mp3'),
    pdf = path.resolve(__dirname, '../fixtures/coffee.pdf');

describe('upload', function () {
    require('../utils/credentials');
    var cred = {
        app:require('../../config/app'),
        user:require('../../config/user')
    };
    var p = {};
    before(function () {
        for (var name in providers) {
            var provider = providers[name];
            p[name] = new purest(provider.__provider.oauth
                ? {provider:name, key:cred.app[name].key, secret:cred.app[name].secret}
                : {provider:name});
        }
    });

    describe('asana', function () {
        it('upload', function (done) {
            var id = '16202185639027';
            p.asana.post('tasks/'+id+'/attachments', {
                auth: {bearer:cred.user.asana.token},
                headers:{'content-type':'multipart/form-data'},
                formData:{
                    file:fs.createReadStream(image)
                }
            },
            function (err, res, body) {
                debugger;
                if (err) return error(err, done);
                body.data.name.should.equal('cat.png');
                done();
            });
        });
    });
    describe('box content', function () {
        var file = {};
        it('upload', function (done) {
            p.box.post('files/content', {
                api:'upload',
                auth:{bearer:cred.user.box.token},
                qs:{parent_id:0},
                headers:{'content-type':'multipart/form-data'},
                formData:{filename:fs.createReadStream(image)}
            }, function (err, res, body) {
                debugger;
                if (err) return error(err, done);
                body.entries[0].name.should.equal('cat.png');
                file = body.entries[0];
                done();
            });
        });
        it('download', function (done) {
            p.box.get('files/'+file.id+'/content', {
                auth:{bearer:cred.user.box.token}
            }, function (err, res, body) {
                debugger;
                if (err) return error(err, done);
                fs.writeFileSync('cat.png', body, 'binary');
                fs.statSync('cat.png').size.should.equal(22025);
                done();
            });
        });
        after(function (done) {
            p.box.del('files/'+file.id, {
                auth:{bearer:cred.user.box.token}
            }, function (err, res, body) {
                debugger;
                if (err) return error(err, done);
                fs.unlinkSync('cat.png');
                done();
            });
        });
    });
    describe('box view', function () {
        it.skip('upload', function (done) {
            // works - need to figure out a testing scheme
            p.box.post('documents', {
                api:'view-upload',
                headers: {
                    'Authorization':'Token '+cred.user.box.viewapikey,
                    'content-type':'multipart/form-data'
                },
                formData:{
                    name:'coffee.pdf',
                    file:fs.readFileSync(pdf)
                }
            }, function (err, res, body) {
                debugger;
                if (err) return error(err, done);
                body.type.should.equal('document');
                body.status.should.equal('queued');
                done();
            });
        });
    });
    it('facebook', function (done) {
        p.facebook.post('me/photos', {
            qs:{
                access_token:cred.user.facebook.token,
                message:'Sent on '+new Date()
            },
            headers:{'content-type':'multipart/form-data'},
            formData:{
                source:fs.createReadStream(image)
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.id.should.match(/\d+/);
            body.post_id.should.match(/\d+_\d+/);
            done();
        });
    });
    describe('flickr', function () {
        it('upload', function (done) {
            p.flickr.post('', {
                oauth:{token:cred.user.flickr.token, secret:cred.user.flickr.secret},
                api:'upload',
                upload:'cat.png',
                form: {
                    title:'Sent on '+new Date(),
                    description:'...',
                    is_public:0, is_friend:1, is_family:1, hidden:2,
                    photo:fs.readFileSync(image)
                }
            },
            function (err, res, body) {
                debugger;
                if (err) return error(err, done);
                res.statusCode.should.equal(200);
                done();
            });
        });
        it('replace', function (done) {
            p.flickr.post('', {
                oauth:{token:cred.user.flickr.token, secret:cred.user.flickr.secret},
                api:'replace',
                upload:'cat.png',
                form: {
                    photo_id:'14887285783',
                    photo:fs.readFileSync(image)
                }
            },
            function (err, res, body) {
                debugger;
                if (err) return error(err, done);
                res.statusCode.should.equal(200);
                done();
            });
        });
    });
    it('foursquare', function (done) {
        p.foursquare.post('users/self/update', {
            qs:{
                oauth_token:cred.user.foursquare.token,
                v:'20140503'
            },
            headers:{'content-type':'multipart/form-data'},
            formData:{
                photo:fs.createReadStream(image)
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.meta.code.should.equal(200);
            done();
        });
    });
    describe('google', function () {
        it('drive', function (done) {
            p.google.post('files', {
                api:'upload-drive',
                qs:{
                    access_token:cred.user.google.token,
                    uploadType:'multipart'
                },
                multipart: [
                    {
                        'Content-Type':'application/json',
                        body: JSON.stringify({
                            title:'Test.png'
                        })
                    },
                    {
                        'Content-Type':'image/png',
                        // streaming is not implemented
                        body: fs.readFileSync(image)
                    }
                ],
                json:false
            },
            function (err, res, body) {
                // console.log(body);
                debugger;
                if (err) return error(err, done);
                done();
            });
        });
    });
    it('mailgun', function (done) {
        p.mailgun.post(cred.user.mailgun.domain+'/messages', {
            auth:{user:'api',pass:cred.user.mailgun.apikey},
            headers:{'content-type':'multipart/form-data'},
            formData:{
                from:'purest@mailinator.com',
                to:'purest@mailinator.com,purest2@mailinator.com',
                subject:'Purest is awesome! (mailgun+attachments)',
                html:'
Purest is awesome!
',
                text:'True idd!',
                attachment:[fs.createReadStream(image), fs.createReadStream(audio)]
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.message.should.be.type('string');
            body.id.should.be.type('string');
            done();
        });
    });
    it('sendgrid', function (done) {
        p.sendgrid.post('mail.send', {
            headers:{'content-type':'multipart/form-data'},
            formData:{
                api_user:cred.user.sendgrid.user,
                api_key:cred.user.sendgrid.pass,
                from:'purest@gmail.com',
                to:['purest@mailinator.com','purest2@mailinator.com'],
                subject:'Purest is awesome! (sendgrid+attachments)',
                html:'
Purest is awesome!
',
                text:'True idd!',
                'files[cat.png]':fs.createReadStream(image),
                'files[beep.mp3]':fs.createReadStream(audio)
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.message.should.equal('success');
            done();
        });
    });
    it('slack', function (done) {
        p.slack.post('files.upload', {
            qs:{
                token:cred.user.slack.token,
                filename:'cat',
                title:'Sent on '+new Date()
            },
            headers:{'content-type':'multipart/form-data'},
            formData:{
                file:fs.createReadStream(image)
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.ok.should.equal(true);
            body.file.name.should.equal('cat');
            done();
        });
    });
    it('soundcloud', function (done) {
        p.soundcloud.post('tracks', {
            qs:{
                oauth_token:cred.user.soundcloud.token
            },
            headers:{'content-type':'multipart/form-data'},
            formData:{
                'track[title]':'Sent on '+new Date(),
                'track[asset_data]':fs.createReadStream(audio)
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.kind.should.equal('track');
            done();
        });
    });
    it('stocktwits', function (done) {
        p.stocktwits.post('messages/create', {
            qs:{
                access_token:cred.user.stocktwits.token
            },
            headers:{'content-type':'multipart/form-data'},
            formData:{
                body:'Sent on '+new Date(),
                chart:fs.createReadStream(image)
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.response.status.should.equal(200);
            body.message.entities.chart.should.be.an.instanceOf(Object);
            done();
        });
    });
    it('twitter', function (done) {
        p.twitter.post('statuses/update_with_media', {
            oauth:{token:cred.user.twitter.token, secret:cred.user.twitter.secret},
            headers:{'content-type':'multipart/form-data'},
            formData:{
                status:'Sent on '+new Date(),
                'media[]':fs.createReadStream(image)
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.entities.media[0].should.be.an.instanceOf(Object);
            done();
        });
    });
});

function error (err, done) {
    return (err instanceof Error)
        ? done(err)
        : (console.log(err) || done(new Error('Network error!')));
}
<commit_msg>Remove headers in multipart tests<commit_after>
var fs = require('fs'),
    path = require('path'),
    should = require('should');
var purest = require('../../lib/provider'),
    providers = require('../../config/providers');
var image = path.resolve(__dirname, '../fixtures/cat.png'),
    audio = path.resolve(__dirname, '../fixtures/beep.mp3'),
    pdf = path.resolve(__dirname, '../fixtures/coffee.pdf');

describe('upload', function () {
    require('../utils/credentials');
    var cred = {
        app:require('../../config/app'),
        user:require('../../config/user')
    };
    var p = {};
    before(function () {
        for (var name in providers) {
            var provider = providers[name];
            p[name] = new purest(provider.__provider.oauth
                ? {provider:name, key:cred.app[name].key, secret:cred.app[name].secret}
                : {provider:name});
        }
    });

    describe('asana', function () {
        it('upload', function (done) {
            var id = '16202185639027';
            p.asana.post('tasks/'+id+'/attachments', {
                auth: {bearer:cred.user.asana.token},
                formData:{
                    file:fs.createReadStream(image)
                }
            },
            function (err, res, body) {
                debugger;
                if (err) return error(err, done);
                body.data.name.should.equal('cat.png');
                done();
            });
        });
    });
    describe('box content', function () {
        var file = {};
        it('upload', function (done) {
            p.box.post('files/content', {
                api:'upload',
                auth:{bearer:cred.user.box.token},
                qs:{parent_id:0},
                formData:{filename:fs.createReadStream(image)}
            }, function (err, res, body) {
                debugger;
                if (err) return error(err, done);
                body.entries[0].name.should.equal('cat.png');
                file = body.entries[0];
                done();
            });
        });
        it('download', function (done) {
            p.box.get('files/'+file.id+'/content', {
                auth:{bearer:cred.user.box.token}
            }, function (err, res, body) {
                debugger;
                if (err) return error(err, done);
                fs.writeFileSync('cat.png', body, 'binary');
                fs.statSync('cat.png').size.should.equal(22025);
                done();
            });
        });
        after(function (done) {
            p.box.del('files/'+file.id, {
                auth:{bearer:cred.user.box.token}
            }, function (err, res, body) {
                debugger;
                if (err) return error(err, done);
                fs.unlinkSync('cat.png');
                done();
            });
        });
    });
    describe('box view', function () {
        it.skip('upload', function (done) {
            // works - need to figure out a testing scheme
            p.box.post('documents', {
                api:'view-upload',
                headers: {
                    'Authorization':'Token '+cred.user.box.viewapikey,
                    'content-type':'multipart/form-data'
                },
                formData:{
                    name:'coffee.pdf',
                    file:fs.readFileSync(pdf)
                }
            }, function (err, res, body) {
                debugger;
                if (err) return error(err, done);
                body.type.should.equal('document');
                body.status.should.equal('queued');
                done();
            });
        });
    });
    it('facebook', function (done) {
        p.facebook.post('me/photos', {
            qs:{
                access_token:cred.user.facebook.token,
                message:'Sent on '+new Date()
            },
            formData:{
                source:fs.createReadStream(image)
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.id.should.match(/\d+/);
            body.post_id.should.match(/\d+_\d+/);
            done();
        });
    });
    describe('flickr', function () {
        it('upload', function (done) {
            p.flickr.post('', {
                oauth:{token:cred.user.flickr.token, secret:cred.user.flickr.secret},
                api:'upload',
                upload:'cat.png',
                form: {
                    title:'Sent on '+new Date(),
                    description:'...',
                    is_public:0, is_friend:1, is_family:1, hidden:2,
                    photo:fs.readFileSync(image)
                }
            },
            function (err, res, body) {
                debugger;
                if (err) return error(err, done);
                res.statusCode.should.equal(200);
                done();
            });
        });
        it('replace', function (done) {
            p.flickr.post('', {
                oauth:{token:cred.user.flickr.token, secret:cred.user.flickr.secret},
                api:'replace',
                upload:'cat.png',
                form: {
                    photo_id:'14887285783',
                    photo:fs.readFileSync(image)
                }
            },
            function (err, res, body) {
                debugger;
                if (err) return error(err, done);
                res.statusCode.should.equal(200);
                done();
            });
        });
    });
    it('foursquare', function (done) {
        p.foursquare.post('users/self/update', {
            qs:{
                oauth_token:cred.user.foursquare.token,
                v:'20140503'
            },
            formData:{
                photo:fs.createReadStream(image)
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.meta.code.should.equal(200);
            done();
        });
    });
    describe('google', function () {
        it('drive', function (done) {
            p.google.post('files', {
                api:'upload-drive',
                qs:{
                    access_token:cred.user.google.token,
                    uploadType:'multipart'
                },
                multipart: [
                    {
                        'Content-Type':'application/json',
                        body: JSON.stringify({
                            title:'Test.png'
                        })
                    },
                    {
                        'Content-Type':'image/png',
                        body: fs.readFileSync(image)
                        // streaming is implemented in the next release
                        // body: fs.createReadStream(image)
                    }
                ],
                json:false
            },
            function (err, res, body) {
                // console.log(body);
                debugger;
                if (err) return error(err, done);
                done();
            });
        });
    });
    it('mailgun', function (done) {
        p.mailgun.post(cred.user.mailgun.domain+'/messages', {
            auth:{user:'api',pass:cred.user.mailgun.apikey},
            formData:{
                from:'purest@mailinator.com',
                to:'purest@mailinator.com,purest2@mailinator.com',
                subject:'Purest is awesome! (mailgun+attachments)',
                html:'
Purest is awesome!
',
                text:'True idd!',
                attachment:[fs.createReadStream(image), fs.createReadStream(audio)]
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.message.should.be.type('string');
            body.id.should.be.type('string');
            done();
        });
    });
    it('sendgrid', function (done) {
        p.sendgrid.post('mail.send', {
            formData:{
                api_user:cred.user.sendgrid.user,
                api_key:cred.user.sendgrid.pass,
                from:'purest@mailinator.com',
                to:['purest@mailinator.com','purest2@mailinator.com'],
                subject:'Purest is awesome! (sendgrid+attachments)',
                html:'
Purest is awesome!
',
                text:'True idd!',
                'files[cat.png]':fs.createReadStream(image),
                'files[beep.mp3]':fs.createReadStream(audio)
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.message.should.equal('success');
            done();
        });
    });
    it('slack', function (done) {
        p.slack.post('files.upload', {
            qs:{
                token:cred.user.slack.token,
                filename:'cat',
                title:'Sent on '+new Date()
            },
            formData:{
                file:fs.createReadStream(image)
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.ok.should.equal(true);
            body.file.name.should.equal('cat');
            done();
        });
    });
    it('soundcloud', function (done) {
        p.soundcloud.post('tracks', {
            qs:{
                oauth_token:cred.user.soundcloud.token
            },
            formData:{
                'track[title]':'Sent on '+new Date(),
                'track[asset_data]':fs.createReadStream(audio)
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.kind.should.equal('track');
            done();
        });
    });
    it('stocktwits', function (done) {
        p.stocktwits.post('messages/create', {
            qs:{
                access_token:cred.user.stocktwits.token
            },
            formData:{
                body:'Sent on '+new Date(),
                chart:fs.createReadStream(image)
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.response.status.should.equal(200);
            body.message.entities.chart.should.be.an.instanceOf(Object);
            done();
        });
    });
    it('twitter', function (done) {
        p.twitter.post('statuses/update_with_media', {
            oauth:{token:cred.user.twitter.token, secret:cred.user.twitter.secret},
            formData:{
                status:'Sent on '+new Date(),
                'media[]':fs.createReadStream(image)
            }
        },
        function (err, res, body) {
            debugger;
            if (err) return error(err, done);
            body.entities.media[0].should.be.an.instanceOf(Object);
            done();
        });
    });
});

function error (err, done) {
    return (err instanceof Error)
        ? done(err)
        : (console.log(err) || done(new Error('Network error!')));
}
<|endoftext|>


<commit_before>'use strict';

var mcf = require('minecraft-protocol-forge');
var mc = require('minecraft-protocol');
var ping = mc.ping;
var assert = require('assert');

function createClientAuto(options, cb) {
  assert.ok(options, 'options is required');

  console.log('pinging',options.host);
  // TODO: refactor with DNS SRV lookup in NMP
  // TODO: detect ping timeout, https://github.com/PrismarineJS/node-minecraft-protocol/issues/329
  ping(options, function(err, response) {
    var client;

    if (err) return cb(err, null);
    console.log('ping response',response);
    // TODO: could also use ping pre-connect to save description, type, negotiate protocol etc.
    //  ^ see https://github.com/PrismarineJS/node-minecraft-protocol/issues/327

    if (response.modinfo && response.modinfo.type === 'FML') {
      // Use the list of Forge mods from the server ping, so client will match server
      var forgeMods = response.modinfo.modList;
      console.log('Using forgeMods:',forgeMods);
      client = mcf.createClient(options); // we know we can use Forge
      client.forgeMods = forgeMods; // for fmlHandshakeStep TODO: refactor, constructor?
    } else {
        client = mc.createClient(options); // vanilla
    }
    cb(null, client);
  });
}

module.exports = {
  createClientAsync: createClientAuto
};
<commit_msg>Set version based on server ping version name<commit_after>'use strict';

var mcf = require('minecraft-protocol-forge');
var mc = require('minecraft-protocol');
var ping = mc.ping;
var assert = require('assert');

function createClientAuto(options, cb) {
  assert.ok(options, 'options is required');

  console.log('pinging',options.host);
  // TODO: refactor with DNS SRV lookup in NMP
  // TODO: detect ping timeout, https://github.com/PrismarineJS/node-minecraft-protocol/issues/329
  ping(options, function(err, response) {
    var client;

    if (err) return cb(err, null);
    console.log('ping response',response);
    // TODO: could also use ping pre-connect to save description, type, negotiate protocol etc.
    //  ^ see https://github.com/PrismarineJS/node-minecraft-protocol/issues/327
    var motd = response.description;
    console.log('Server description:',motd); // TODO: save

    // Pass server-reported version to protocol handler
    // The version string is interpereted by https://github.com/PrismarineJS/node-minecraft-data
    var versionName = response.version.name;        // 1.8.9, 1.7.10
    var versionProtocol = response.version.protocol;//    47,      5

    console.log(`Server version: ${versionName}, protocol: ${versionProtocol}`);
    // TODO: test or report unsupported versions?
    // TODO: fix non-vanilla/FML server support! Spigot 1.8.8, Glowstone++ 1.8.9 is 'versionName'; should use versionProtocol
    //

    options.version = versionName;

    if (response.modinfo && response.modinfo.type === 'FML') {
      // Use the list of Forge mods from the server ping, so client will match server
      var forgeMods = response.modinfo.modList;
      console.log('Using forgeMods:',forgeMods);
      client = mcf.createClient(options); // we know we can use Forge
      client.forgeMods = forgeMods; // for fmlHandshakeStep TODO: refactor, constructor?
    } else {
        client = mc.createClient(options); // vanilla
    }
    cb(null, client);
  });
}

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


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [time in seconds]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

process.on('exit', function () {
  var args = ['push']
  child_process.execFileSync('/usr/bin/git', args)
})

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-m<commit_msg>You feeling lucky punk?<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [time in seconds]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

process.on('exit', function () {
  var args = ['push']
  child_process.execFileSync('/usr/bin/git', args)
})

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-mi<|endoftext|>


<commit_before>app.controller("summaryCtrl", function ($scope, $rootScope, centsa) {
    $scope.getBudget = () => centsa.settings.set("strict.mode", $scope.strictMode).then(() => {
        centsa.general.budget($scope.strictMode).then(resp => $scope.budget = resp.data);
    });

    $scope.filterDate = $event => {
        const date = $($event.currentTarget.innerHTML).find('.amcharts-balloon-div-categoryAxis').text();
        if(new Date(date).getTime()){
            $rootScope.setFilter({
                fromDate : date,
                sort : "date ASC, id ASC"
            });
        }

    };

    centsa.settings.get("strict.mode").then(setting => {
        $scope.strictMode = setting == "1";
        $scope.getBudget();
    });

    centsa.transactions.getCumulativeSums().then(resp => {
        const sums = resp.data.map(x => ({
            date: new Date(x.date).formatDate("yyyy/MM/dd"),
            sum: x.sum / 100
        }));
        const valueAxes = [{
            id: "v1",
            axisAlpha: 0,
            position: "left",
            ignoreAxisWidth: true
        }];
        const graphs = [{
            id: "g1",
            balloon: {
                drop: true,
                adjustBorderColor: false,
                color: "#ffffff"
            },
            lineThickness: 2,
            useLineColorForBulletBorder: true,
            valueField: "sum",
            balloonText: "[[value]]"
        }];
        const chartOpts = {
            type: "serial",
            theme: "light",
            marginRight: 60,
            marginLeft: 60,
            dataDateFormat: "YYYY/MM/DD",
            valueAxes: valueAxes,
            balloon: {
                borderThickness: 1,
                shadowAlpha: 0
            },
            graphs: graphs,
            chartCursor: {
                pan: true,
                valueLineEnabled: true,
                valueLineBalloonEnabled: true,
                cursorAlpha: 1,
                cursorColor: "#258cbb",
                limitToGraph: "g1",
                valueLineAlpha: 0.2,
                valueZoomable: true
            },
            categoryField: "date",
            categoryAxis: {
                parseDates: false,
                dashLength: 1,
            },
            chartScrollbar: {
                graph: "g1",
                oppositeAxis: false,
                offset: 30,
                scrollbarHeight: 80,
                backgroundAlpha: 0,
                selectedBackgroundAlpha: 0.1,
                selectedBackgroundColor: "#888888",
                graphFillAlpha: 0,
                graphLineAlpha: 0.5,
                selectedGraphFillAlpha: 0,
                selectedGraphLineAlpha: 1,
                color: "#AAAAAA"
            },
            dataProvider: sums,
            mouseWheelZoomEnabled: true
        };
        AmCharts.makeChart("trans-chart", chartOpts);
    });
});
<commit_msg>#112 Fixed scroll issue<commit_after>app.controller("summaryCtrl", function ($scope, $rootScope, centsa) {
    let transChart;

    $scope.getBudget = () => centsa.settings.set("strict.mode", $scope.strictMode).then(() => {
        centsa.general.budget($scope.strictMode).then(resp => $scope.budget = resp.data);
    });

    $scope.filterDate = $event => {
        const date = $($event.currentTarget.innerHTML).find('.amcharts-balloon-div-categoryAxis').text();
        transChart.handleMouseOut();
        if(new Date(date).getTime()){
            $rootScope.setFilter({
                fromDate : date,
                sort : "date ASC, id ASC"
            });
        }

    };

    centsa.settings.get("strict.mode").then(setting => {
        $scope.strictMode = setting == "1";
        $scope.getBudget();
    });

    centsa.transactions.getCumulativeSums().then(resp => {
        const sums = resp.data.map(x => ({
            date: new Date(x.date).formatDate("yyyy/MM/dd"),
            sum: x.sum / 100
        }));
        const valueAxes = [{
            id: "v1",
            axisAlpha: 0,
            position: "left",
            ignoreAxisWidth: true
        }];
        const graphs = [{
            id: "g1",
            balloon: {
                drop: true,
                adjustBorderColor: false,
                color: "#ffffff"
            },
            lineThickness: 2,
            useLineColorForBulletBorder: true,
            valueField: "sum",
            balloonText: "[[value]]"
        }];
        const chartOpts = {
            type: "serial",
            theme: "light",
            marginRight: 60,
            marginLeft: 60,
            dataDateFormat: "YYYY/MM/DD",
            valueAxes: valueAxes,
            balloon: {
                borderThickness: 1,
                shadowAlpha: 0
            },
            graphs: graphs,
            chartCursor: {
                pan: true,
                valueLineEnabled: true,
                valueLineBalloonEnabled: true,
                cursorAlpha: 1,
                cursorColor: "#258cbb",
                limitToGraph: "g1",
                valueLineAlpha: 0.2,
                valueZoomable: true
            },
            categoryField: "date",
            categoryAxis: {
                parseDates: false,
                dashLength: 1,
            },
            chartScrollbar: {
                graph: "g1",
                oppositeAxis: false,
                offset: 30,
                scrollbarHeight: 80,
                backgroundAlpha: 0,
                selectedBackgroundAlpha: 0.1,
                selectedBackgroundColor: "#888888",
                graphFillAlpha: 0,
                graphLineAlpha: 0.5,
                selectedGraphFillAlpha: 0,
                selectedGraphLineAlpha: 1,
                color: "#AAAAAA"
            },
            dataProvider: sums,
            mouseWheelZoomEnabled: true
        };
        transChart = AmCharts.makeChart("trans-chart", chartOpts);
    });
});
<|endoftext|>


<commit_before>'use strict';

const Log   = require('ipfs-log');
const Cache = require('./Cache');

class OperationsLog {
  constructor(ipfs, dbname, opts) {
    this.dbname = dbname;
    this.options = opts || { cacheFile: null };
    this._lastWrite = null;
    this._ipfs = ipfs;
    this._log = null;
  }

  get ops() {
    return this._log.items;
  }

  addOperation(operation, key, value) {
    const entry = {
      op: operation,
      key: key,
      value: value,
      meta: {
        ts: new Date().getTime()
      }
    };

    let node, logHash;
    return this._log.add(entry)
      .then((op) => node = op)
      .then(() => Object.assign(node.payload, { hash: node.hash }))
      .then(() => Log.getIpfsHash(this._ipfs, this._log))
      .then((hash) => logHash = hash)
      .then(() => this._lastWrite = logHash)
      .then(() => Cache.set(this.dbname, logHash))
      .then(() => {
        return { operation: node.payload, log: logHash };
      })
  }

  load(id) {
    return Log.create(this._ipfs, id)
      .then((log) => this._log = log)
      .then(() => Cache.loadCache(this.options.cacheFile))
      .then(() => this.merge(Cache.get(this.dbname)))
  }

  merge(hash) {
    if(!hash || hash === this._lastWrite || !this._log)
      return Promise.resolve([]);

    const oldCount = this._log.items.length;
    let newItems = [];
    return Log.fromIpfsHash(this._ipfs, hash)
      .then((other) => this._log.join(other))
      .then((merged) => newItems = merged)
      .then(() => Cache.set(this.dbname, hash))
      .then(() => newItems.forEach((f) => Object.assign(f.payload, { hash: f.hash })))
      .then(() => newItems.map((f) => f.payload))
  }

  delete() {
    this._log.clear();
  }

  _padOperation(node) {
    Object.assign(node.payload, { hash: node.hash });
    return node;
  }
}

module.exports = OperationsLog;
<commit_msg>Remove _padOperation from OperationsLog<commit_after>'use strict';

const Log   = require('ipfs-log');
const Cache = require('./Cache');

class OperationsLog {
  constructor(ipfs, dbname, opts) {
    this.dbname = dbname;
    this.options = opts || { cacheFile: null };
    this._lastWrite = null;
    this._ipfs = ipfs;
    this._log = null;
  }

  get ops() {
    return this._log.items;
  }

  addOperation(operation, key, value) {
    const entry = {
      op: operation,
      key: key,
      value: value,
      meta: {
        ts: new Date().getTime()
      }
    };

    let node, logHash;
    return this._log.add(entry)
      .then((op) => node = op)
      .then(() => Object.assign(node.payload, { hash: node.hash }))
      .then(() => Log.getIpfsHash(this._ipfs, this._log))
      .then((hash) => logHash = hash)
      .then(() => this._lastWrite = logHash)
      .then(() => Cache.set(this.dbname, logHash))
      .then(() => {
        return { operation: node.payload, log: logHash };
      })
  }

  load(id) {
    return Log.create(this._ipfs, id)
      .then((log) => this._log = log)
      .then(() => Cache.loadCache(this.options.cacheFile))
      .then(() => this.merge(Cache.get(this.dbname)))
  }

  merge(hash) {
    if(!hash || hash === this._lastWrite || !this._log)
      return Promise.resolve([]);

    const oldCount = this._log.items.length;
    let newItems = [];
    return Log.fromIpfsHash(this._ipfs, hash)
      .then((other) => this._log.join(other))
      .then((merged) => newItems = merged)
      .then(() => Cache.set(this.dbname, hash))
      .then(() => newItems.forEach((f) => Object.assign(f.payload, { hash: f.hash })))
      .then(() => newItems.map((f) => f.payload))
  }

  delete() {
    this._log.clear();
  }
}

module.exports = OperationsLog;
<|endoftext|>


<commit_before>var childProcess = require('child_process');
var path = require('path');

var clean = require('gulp-clean');
var cleanCss = require('gulp-clean-css');
var concat = require('gulp-concat');
var copy = require('gulp-copy');
var gulp = require('gulp');
var jade = require('gulp-jade');
var jshint = require('gulp-jshint');
var less = require('gulp-less');
var lesshint = require('gulp-lesshint');
var merge = require('merge-stream');
var plumber = require('gulp-plumber');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');

var bowerInstall = require('./lib/bower_install.js');
var logger = require('./lib/logger.js');
var settings = require('./lib/settings.js');
var version = require('./lib/version.js');
var frontEndDependencies = require('./lib/front_end_deps.js');

var jadeLocals = {
  settings: settings,
  version: version,
  deps: frontEndDependencies,
};

var paths = {};
paths.lessMain = 'less/theme.less';
paths.lessAll = 'less/**/*.less';
paths.css = 'public/css/';
paths.jade = 'jade/**/*.jade';
paths.html = 'public/';
paths.serverJs = ['server.js', 'lib/**/*.js'];
paths.publicJs = ['public/js/**/*.js', '!public/js/lib/**/*.js'];
paths.server = concatenateItems(paths.serverJs, '*.json', '!package.json', '!bower.json');
paths.js = concatenateItems('gulpfile.js', paths.serverJs, paths.publicJs);
paths.misc = ['node_modules/**/*'];
paths.assets = ['public/imgs/**/*', 'public/fonts/**/*', 'public/**/*.html'];
paths.public = 'public/';
paths.build = 'dist/';
paths.buildJsHead = 'dist/public/js/bundle_head.js';
paths.buildJsFinal = 'dist/public/js/bundle_final.js';
paths.buildCss = 'dist/public/css/bundle.css';

function concatenateItems() {
  var itemList = [];
  for (var i = 0; i < arguments.length; i++) {
    itemList = itemList.concat(arguments[i]);
  }
  return itemList;
}

var server = null;
var restarting = false;
function startServer() {
  if (server !== null) {
    throw new Error('Server is already started');
  }

  server = childProcess.spawn('node', ['server.js']);

  server.stdout.on('data', function(data) {
    process.stdout.write(data);
  });

  server.stderr.on('data', function(data) {
    process.stdout.write(data);
  });
}

function restartServer(callback) {
  if (restarting) {
    return;
  }

  restarting = true;

  if (server === null) {
    startServer();
    callback(null);
    restarting = false;
    return;
  }

  server.on('exit', function() {
    server = null;
    startServer();
    callback(null);
    restarting = false;
  });

  server.kill('SIGTERM');
}

gulp.task('bower', function(callback) {
  bowerInstall(callback);
});

gulp.task('server', function(callback) {
  startServer();
});

gulp.task('less', function() {
  return gulp.src(paths.lessMain)
    .pipe(less())
    .pipe(gulp.dest(paths.css));
});

gulp.task('jade', function() {
  return gulp.src(paths.jade)
    .pipe(jade({
      locals: jadeLocals,
    }))
    .pipe(gulp.dest(paths.html));
});

gulp.task('watch_less', ['less'], function() {
  // Watch is done like this so that if any Less file changes, the entire
  // monolithic less file is rebuilt (which depends on everything).
  return watch(paths.lessAll, function() {
    gulp.src(paths.lessMain)
      .pipe(less())
      .pipe(gulp.dest(paths.css));
  });
});

gulp.task('watch_jade', function() {
  return gulp.src(paths.jade)
    .pipe(watch(paths.jade))
    .pipe(plumber())
    .pipe(jade({
      locals: jadeLocals,
    }))
    .pipe(gulp.dest(paths.html));
});

gulp.task('watch_server', function() {
  startServer();
  return watch(paths.server, function() {
    logger.log('File changed. Restarting server...');
    restartServer(function() {});
  });
});

gulp.task('watch', ['watch_less', 'watch_jade', 'watch_server']);

gulp.task('lint_js', function() {
  return gulp.src(paths.js)
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});

gulp.task('lint_less', function() {
  return gulp.src(paths.lessAll)
    .pipe(lesshint())
    .pipe(lesshint.reporter());
});

gulp.task('lint', ['lint_js', 'lint_less']);

gulp.task('build_server', function() {
  return gulp.src(paths.server)
    .pipe(copy(paths.build));
});

gulp.task('build_misc', function() {
  return gulp.src(paths.misc)
    .pipe(copy(paths.build));
});

gulp.task('build_assets', ['jade'], function() {
  return gulp.src(paths.assets)
    .pipe(copy(paths.build));
});

gulp.task('build_js', function() {
  var headFiles = frontEndDependencies.headJs.map(function(fileName) {
    return paths.public + fileName;
  });
  var finalFiles = frontEndDependencies.finalJs.map(function(fileName) {
    return paths.public + fileName;
  });

  var head = gulp.src(headFiles)
    .pipe(concat(paths.buildJsHead))
    .pipe(uglify())
    .pipe(gulp.dest('.'));
  var final = gulp.src(finalFiles)
    .pipe(concat(paths.buildJsFinal))
    .pipe(uglify())
    .pipe(gulp.dest('.'));
  return merge(head, final);
});

gulp.task('build_css', ['less'], function() {
  var files = frontEndDependencies.css.map(function(fileName) {
    return paths.public + fileName;
  });

  return gulp.src(files)
    .pipe(concat(paths.buildCss))
    .pipe(cleanCss({
      keepSpecialComments: 0,
    }))
    .pipe(gulp.dest('.'));
});

gulp.task('build', ['build_server', 'build_misc', 'build_assets', 'build_js', 'build_css']);

gulp.task('clean', function() {
  return gulp.src(paths.build, { read: false })
    .pipe(clean());
});

gulp.task('default', ['watch']);
<commit_msg>Make package.json get copied when building<commit_after>var childProcess = require('child_process');
var path = require('path');

var clean = require('gulp-clean');
var cleanCss = require('gulp-clean-css');
var concat = require('gulp-concat');
var copy = require('gulp-copy');
var gulp = require('gulp');
var jade = require('gulp-jade');
var jshint = require('gulp-jshint');
var less = require('gulp-less');
var lesshint = require('gulp-lesshint');
var merge = require('merge-stream');
var plumber = require('gulp-plumber');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');

var bowerInstall = require('./lib/bower_install.js');
var logger = require('./lib/logger.js');
var settings = require('./lib/settings.js');
var version = require('./lib/version.js');
var frontEndDependencies = require('./lib/front_end_deps.js');

var jadeLocals = {
  settings: settings,
  version: version,
  deps: frontEndDependencies,
};

var paths = {};
paths.lessMain = 'less/theme.less';
paths.lessAll = 'less/**/*.less';
paths.css = 'public/css/';
paths.jade = 'jade/**/*.jade';
paths.html = 'public/';
paths.serverJs = ['server.js', 'lib/**/*.js'];
paths.publicJs = ['public/js/**/*.js', '!public/js/lib/**/*.js'];
paths.server = concatenateItems(paths.serverJs, '*.json', '!bower.json');
paths.js = concatenateItems('gulpfile.js', paths.serverJs, paths.publicJs);
paths.misc = ['node_modules/**/*'];
paths.assets = ['public/imgs/**/*', 'public/fonts/**/*', 'public/**/*.html'];
paths.public = 'public/';
paths.build = 'dist/';
paths.buildJsHead = 'dist/public/js/bundle_head.js';
paths.buildJsFinal = 'dist/public/js/bundle_final.js';
paths.buildCss = 'dist/public/css/bundle.css';

function concatenateItems() {
  var itemList = [];
  for (var i = 0; i < arguments.length; i++) {
    itemList = itemList.concat(arguments[i]);
  }
  return itemList;
}

var server = null;
var restarting = false;
function startServer() {
  if (server !== null) {
    throw new Error('Server is already started');
  }

  server = childProcess.spawn('node', ['server.js']);

  server.stdout.on('data', function(data) {
    process.stdout.write(data);
  });

  server.stderr.on('data', function(data) {
    process.stdout.write(data);
  });
}

function restartServer(callback) {
  if (restarting) {
    return;
  }

  restarting = true;

  if (server === null) {
    startServer();
    callback(null);
    restarting = false;
    return;
  }

  server.on('exit', function() {
    server = null;
    startServer();
    callback(null);
    restarting = false;
  });

  server.kill('SIGTERM');
}

gulp.task('bower', function(callback) {
  bowerInstall(callback);
});

gulp.task('server', function(callback) {
  startServer();
});

gulp.task('less', function() {
  return gulp.src(paths.lessMain)
    .pipe(less())
    .pipe(gulp.dest(paths.css));
});

gulp.task('jade', function() {
  return gulp.src(paths.jade)
    .pipe(jade({
      locals: jadeLocals,
    }))
    .pipe(gulp.dest(paths.html));
});

gulp.task('watch_less', ['less'], function() {
  // Watch is done like this so that if any Less file changes, the entire
  // monolithic less file is rebuilt (which depends on everything).
  return watch(paths.lessAll, function() {
    gulp.src(paths.lessMain)
      .pipe(less())
      .pipe(gulp.dest(paths.css));
  });
});

gulp.task('watch_jade', function() {
  return gulp.src(paths.jade)
    .pipe(watch(paths.jade))
    .pipe(plumber())
    .pipe(jade({
      locals: jadeLocals,
    }))
    .pipe(gulp.dest(paths.html));
});

gulp.task('watch_server', function() {
  startServer();
  return watch(paths.server, function() {
    logger.log('File changed. Restarting server...');
    restartServer(function() {});
  });
});

gulp.task('watch', ['watch_less', 'watch_jade', 'watch_server']);

gulp.task('lint_js', function() {
  return gulp.src(paths.js)
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});

gulp.task('lint_less', function() {
  return gulp.src(paths.lessAll)
    .pipe(lesshint())
    .pipe(lesshint.reporter());
});

gulp.task('lint', ['lint_js', 'lint_less']);

gulp.task('build_server', function() {
  return gulp.src(paths.server)
    .pipe(copy(paths.build));
});

gulp.task('build_misc', function() {
  return gulp.src(paths.misc)
    .pipe(copy(paths.build));
});

gulp.task('build_assets', ['jade'], function() {
  return gulp.src(paths.assets)
    .pipe(copy(paths.build));
});

gulp.task('build_js', function() {
  var headFiles = frontEndDependencies.headJs.map(function(fileName) {
    return paths.public + fileName;
  });
  var finalFiles = frontEndDependencies.finalJs.map(function(fileName) {
    return paths.public + fileName;
  });

  var head = gulp.src(headFiles)
    .pipe(concat(paths.buildJsHead))
    .pipe(uglify())
    .pipe(gulp.dest('.'));
  var final = gulp.src(finalFiles)
    .pipe(concat(paths.buildJsFinal))
    .pipe(uglify())
    .pipe(gulp.dest('.'));
  return merge(head, final);
});

gulp.task('build_css', ['less'], function() {
  var files = frontEndDependencies.css.map(function(fileName) {
    return paths.public + fileName;
  });

  return gulp.src(files)
    .pipe(concat(paths.buildCss))
    .pipe(cleanCss({
      keepSpecialComments: 0,
    }))
    .pipe(gulp.dest('.'));
});

gulp.task('build', ['build_server', 'build_misc', 'build_assets', 'build_js', 'build_css']);

gulp.task('clean', function() {
  return gulp.src(paths.build, { read: false })
    .pipe(clean());
});

gulp.task('default', ['watch']);
<|endoftext|>


<commit_before>/*
 author：徐超，冯士兵，杨迪升
 */

$(function(){
    console.log('欢迎');
    var net = require('net');
    var HOST = '192.168.1.200';
    var PORT = 4196;

    //创建socket连接
    var client = new net.Socket();
    client.connect(PORT, HOST, function() {
        console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    });

    //添加socket连接的监听事件，有数据来就显示到界面上
    client.on('data', function(data) {
        //解析读取到的内容
        console.log('DATA: ' + data);
        //console.log( data.length)

        var datas = new Array();
        datas = data.toString().split("\t");
        if(data.length==35) {
            console.log('env info');
            var Hex = datas[2]
            var envorinment_temperature = datas[6]
            var body_temperature = datas[7]
            var heart_rate = datas[8]
            var place_x = datas[9]
            var place_y = datas[10]
            var place_z = datas[11]

            //将收集到的数据显示到界面上
            $('#bodyTemperature1').text(body_temperature);
            $('#heartBeat1').text(heart_rate);
            $('#temperature1').text(envorinment_temperature);
        }
        else if(data.length==25) {
            var jump_step = datas[5]
            var network_address = datas[8]
        }
        else if(data.length==21) {
            var remain_node_num = datas[6]
            var relate_node_num = datas[7]
        }
    });
});

function draw(id) {
    var canvas = document.getElementById(id);
    if (canvas == null)
        return false;
    var context = canvas.getContext("2d");
    context.fillStyle = "#EEEEFF";
    context.fillRect(0, 0, 400, 600);
    var n = 0;
    var dx = 150;
    var dy = 150;
    var s = 100;
    context.beginPath();
    context.fillStyle = 'rgb(100,255,100)';
    context.strokeStyle = 'rgb(0,0,100)';
    var x = Math.sin(0);
    var y = Math.cos(0);
    var dig = Math.PI / 15 * 11;
    for (var i = 0; i < 30; i++) {
        var x = Math.sin(i * dig);
        var y = Math.cos(i * dig);
        context.lineTo(dx + x * s, dy + y * s);
    }
    context.closePath();
    context.fill();
    context.stroke();
}
function drawLine(id,rgb,startx,starty,endx,endy,nodeArray) {
    var canvas = document.getElementById(id);
    if (canvas == null)
        return false;
    var context = canvas.getContext("2d");
    //context.beginPath();
    context.strokeStyle = rgb;
    context.fillStyle = rgb;
    context.lineWidth=3;
    context.moveTo(startx, starty);
    //之后的lineTo会以上次lineTo的节点为开始
    var lineLength = Math.floor(Math.sqrt((endx-startx)*(endx-startx)+(endy-starty)*(endy-starty)));
    var fractionLength = Math.floor(lineLength / (nodeArray.length*2 + 1));
    var xFractionLength = Math.floor((endx-startx) / (nodeArray.length*2 + 1));
    var yFractionLength = Math.floor((endy-starty) / (nodeArray.length*2 + 1));
    context.lineTo(startx+xFractionLength, starty+yFractionLength);
    for (var i = 0; i < nodeArray.length; i++)
    {
        //context.rotate(45*Math.PI/180);
        context.strokeStyle = "rgb(0,255,255)";
        context.lineWidth=1;
        if(id === "line2" || id === "line3")
            context.strokeText(nodeArray[i], Number(startx+xFractionLength*(i*2+1.6)), Number(starty+yFractionLength*(i*2+1.6)));
        else if(id === "line1" || id === "line4")
            context.strokeText(nodeArray[i], Number(startx+xFractionLength*(i*2+1.4)), Number(starty+yFractionLength*(i*2+1.6)));
        context.strokeStyle = rgb;
        context.lineWidth=3;
        context.strokeRect(Number(startx+xFractionLength*(i*2+1)),Number(starty+yFractionLength*(i*2+1)),xFractionLength,yFractionLength);
        //context.beginPath();
        //context.rotate(-45*Math.PI/180);
        context.moveTo(Number(startx+xFractionLength*(i*2+2)), Number(starty+yFractionLength*(i*2+2)));
        context.lineTo(Number(startx+xFractionLength*(i*2+3)), Number(starty+yFractionLength*(i*2+3)));
    }
    context.lineTo(endx, endy);
    context.stroke();
    //context.fill();
    $('#surplusElectricity1').val(30);
    $('#surplusElectricity2').val(50);
    $('#surplusElectricity3').val(70);
    $('#surplusElectricity4').val(90);
}

drawLine("line1","rgb(255,0,0)",10,10,150,150,[1,2,3,4]);
drawLine("line2","rgb(0,255,0)",150,10,10,150,[5,6,7]);
drawLine("line3","rgb(0,0,255)",150,10,10,150,[8,9]);
drawLine("line4","rgb(255,255,0)",10,10,150,150,[10]);
<commit_msg>更改draw<commit_after>/*
 author：徐超，冯士兵，杨迪升
 */

$(function(){
    console.log('欢迎');
    var net = require('net');
    var HOST = '192.168.1.200';
    var PORT = 4196;

    //创建socket连接
    var client = new net.Socket();
    client.connect(PORT, HOST, function() {
        console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    });

    //添加socket连接的监听事件，有数据来就显示到界面上
    client.on('data', function(data) {
        //解析读取到的内容
        console.log('DATA: ' + data);
        //console.log( data.length)

        var datas = new Array();
        datas = data.toString().split("\t");
        if(data.length==35) {
            console.log('env info');
            var Hex = datas[2]
            var envorinment_temperature = datas[6]
            var body_temperature = datas[7]
            var heart_rate = datas[8]
            var place_x = datas[9]
            var place_y = datas[10]
            var place_z = datas[11]

            //将收集到的数据显示到界面上
            $('#bodyTemperature1').text(body_temperature);
            $('#heartBeat1').text(heart_rate);
            $('#temperature1').text(envorinment_temperature);
        }
        else if(data.length==25) {
            var jump_step = datas[5]
            var network_address = datas[8]
        }
        else if(data.length==21) {
            var remain_node_num = datas[6]
            var relate_node_num = datas[7]
        }
    });
});

function draw(id,electricity,nodeArray) {
    switch (id) {
        case "line1": drawLine("line1","rgb(255,0,0)",10,10,150,150,nodeArray);
            $('#surplusElectricity1').val(electricity);
            break;
        case "line2": drawLine("line2","rgb(0,255,0)",150,10,10,150,nodeArray);
            $('#surplusElectricity2').val(electricity);
            break;
        case "line3": drawLine("line3","rgb(0,0,255)",150,10,10,150,nodeArray);
            $('#surplusElectricity3').val(electricity);
            break;
        case "line4": drawLine("line4","rgb(255,255,0)",10,10,150,150,nodeArray);
            $('#surplusElectricity4').val(electricity);
            break;
    }
}
function drawLine(id,rgb,startx,starty,endx,endy,nodeArray) {
    var canvas = document.getElementById(id);
    if (canvas == null)
        return false;
    var context = canvas.getContext("2d");
    //context.beginPath();
    context.strokeStyle = rgb;
    context.fillStyle = rgb;
    context.lineWidth=3;
    context.moveTo(startx, starty);
    //之后的lineTo会以上次lineTo的节点为开始
    var lineLength = Math.floor(Math.sqrt((endx-startx)*(endx-startx)+(endy-starty)*(endy-starty)));
    var fractionLength = Math.floor(lineLength / (nodeArray.length*2 + 1));
    var xFractionLength = Math.floor((endx-startx) / (nodeArray.length*2 + 1));
    var yFractionLength = Math.floor((endy-starty) / (nodeArray.length*2 + 1));
    context.lineTo(startx+xFractionLength, starty+yFractionLength);
    for (var i = 0; i < nodeArray.length; i++)
    {
        //context.rotate(45*Math.PI/180);
        context.strokeStyle = "rgb(0,255,255)";
        context.lineWidth=1;
        if(id === "line2" || id === "line3")
            context.strokeText(nodeArray[i], Number(startx+xFractionLength*(i*2+1.6)), Number(starty+yFractionLength*(i*2+1.6)));
        else if(id === "line1" || id === "line4")
            context.strokeText(nodeArray[i], Number(startx+xFractionLength*(i*2+1.4)), Number(starty+yFractionLength*(i*2+1.6)));
        context.strokeStyle = rgb;
        context.lineWidth=3;
        context.strokeRect(Number(startx+xFractionLength*(i*2+1)),Number(starty+yFractionLength*(i*2+1)),xFractionLength,yFractionLength);
        //context.beginPath();
        //context.rotate(-45*Math.PI/180);
        context.moveTo(Number(startx+xFractionLength*(i*2+2)), Number(starty+yFractionLength*(i*2+2)));
        context.lineTo(Number(startx+xFractionLength*(i*2+3)), Number(starty+yFractionLength*(i*2+3)));
    }
    context.lineTo(endx, endy);
    context.stroke();
    //context.fill();
}<|endoftext|>


<commit_before>/*!

   MPEG-DASH engine plugin for Flowplayer HTML5 version 5.x

   requires:
   - Flowplayer HTML5 version 5.x
   - dash.js https://github.com/Dash-Industry-Forum/dash.js

*/

(function ($) {
  flowplayer.engine.dash = function(player, root) {
    var mediaPlayer,
    videoTag,
    context = new Dash.di.DashContext();

    return {
      pick: function(sources) {
        if (typeof window.MediaSource == "function" &&
            window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.640029, mp4a.40.5"')) {
          var sources = $.grep(sources, function(src) {
            return src.type === 'application/dash+xml';
          });
          if (!sources.length) return;
          return sources[0];
        }
      },
      load: function(video) {
        root.find('video').remove();
        videoTag = document.createElement('video');
        videoTag.addEventListener('play', function() {
          root.trigger('resume', [player]);
        });
        videoTag.addEventListener('pause', function() {
          root.trigger('pause', [player]);
        });
        videoTag.addEventListener('timeupdate', function() {
          root.trigger('progress', [player, videoTag.currentTime]);
        });
        videoTag.addEventListener('loadedmetadata', function() {
          video.duration = video.seekable = videoTag.duration;
          root.trigger('ready', [player, video]);
        });
        videoTag.addEventListener('seeked', function() {
          root.trigger('seek', [player, videoTag.currentTime]);
        });
        videoTag.addEventListener('progress', function() {
          try {
            var buffered = videoTag.buffered,
                buffer = buffered.end(0), // first loaded buffer
                ct = videoTag.currentTime,
                buffend = 0,
                i;

            // buffered.end(null) will not always return the current buffer
            // so we cycle through the time ranges to obtain it
            if (ct) {
              for (i = 1; i < buffered.length; i++) {
                buffend = buffered.end(i);

                if (buffend >= ct && buffered.start(i) <= ct) {
                  buffer = buffend;
                }
              }
            }
            video.buffer = buffer;
          } catch (ignored) {}
          root.trigger('buffer', [player]);
        });
        videoTag.addEventListener('ended', function() {
          root.trigger('finish', [player]);
        });
        videoTag.addEventListener('volumechange', function() {
          root.trigger('volume', [player, videoTag.volume]);
        });

        videoTag.className = 'fp-engine dash-engine';
        root.prepend(videoTag);

        mediaPlayer = new MediaPlayer(context);
        mediaPlayer.setScheduleWhilePaused(true);
        mediaPlayer.setAutoPlay(player.conf.autoplay || player.conf.splash);
        mediaPlayer.startup();
        mediaPlayer.attachView(videoTag);
        mediaPlayer.attachSource(video.src);
      },
      resume: function() {
        if (player.finished) {
          videoTag.currentTime = 0;
        }
        videoTag.play();
      },
      pause: function() {
        videoTag.pause();
      },
      seek: function(time) {
        if (videoTag.paused) {
          $(videoTag).one("seeked.dashpaused", function () {
            setTimeout(function () {
              videoTag.pause()
            }, 10);
          });
        }
        videoTag.currentTime = time;
      },
      volume: function(level) {
        if (videoTag !== undefined) {
          videoTag.volume = level;
        }
      },
      speed: function(val) {
        videoTag.playbackRate = val;
        root.trigger('speed', [player, val]);
      },
      unload: function() {
        if (mediaPlayer) {
          mediaPlayer.reset();
        }
        $(videoTag).remove();
        root.trigger("unload", [player]);
      }

    };
  };
}(jQuery));
<commit_msg>Update v5 with latest and a hack approximating proper engine selection<commit_after>/*!

   MPEG-DASH engine plugin for Flowplayer HTML5 version 5.x

   requires:
   - Flowplayer HTML5 version 5.x
   - dash.js https://github.com/Dash-Industry-Forum/dash.js

*/

(function ($) {
  if (!flowplayer.support.video ||
      typeof window.MediaSource != "function" ||
      !window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.640029, mp4a.40.5"')) {
    return;
  }

  flowplayer.engine.mpegdash = function(player, root) {
    var mediaPlayer,
    videoTag,
    dashstop = false,
    context = new Dash.di.DashContext();

    // see seek implementation below
    player.bind("stop", function (e) {
      if (!dashstop) {
        e.preventDefault();
      }
      dashstop = !dashstop;
    });

    return {
      pick: function(sources) {
        var i;

        for (i = 0; i < sources.length; i++) {
          if (sources[i].type === "application/dash+xml") {
            return sources[i];
          }
        }
      },
      load: function(video) {
        root.find('video').remove();
        videoTag = $("<video/>")[0],
        $(videoTag).on('play', function() {
          root.trigger('resume', [player]);
        });
        $(videoTag).on('pause', function() {
          root.trigger('pause', [player]);
        });
        $(videoTag).on('timeupdate', function() {
          root.trigger('progress', [player, videoTag.currentTime]);
        });
        $(videoTag).on('loadeddata', function() {
          video.duration = video.seekable = videoTag.duration;
          root.trigger('ready', [player, video]);
        });
        $(videoTag).on('seeked', function() {
          root.trigger('seek', [player, videoTag.currentTime]);
        });
        $(videoTag).on('progress', function(e) {
          try {
            var buffered = videoTag.buffered,
                buffer = buffered.end(0), // first loaded buffer
                ct = videoTag.currentTime,
                buffend = 0,
                i;

            // buffered.end(null) will not always return the current buffer
            // so we cycle through the time ranges to obtain it
            if (ct) {
              for (i = 1; i < buffered.length; i++) {
                buffend = buffered.end(i);

                if (buffend >= ct && buffered.start(i) <= ct) {
                  buffer = buffend;
                }
              }
            }
            video.buffer = buffer;
          } catch (ignored) {}
          root.trigger('buffer', [player, e]);
        });
        $(videoTag).on('ended', function() {
          root.trigger('finish', [player]);
        });
        $(videoTag).on('volumechange', function() {
          root.trigger('volume', [player, videoTag.volume]);
        });

        videoTag.className = 'fp-engine dash-engine';
        root.prepend(videoTag);

        mediaPlayer = new MediaPlayer(context);
        mediaPlayer.setScheduleWhilePaused(true);
        mediaPlayer.setAutoPlay(player.conf.autoplay || player.conf.splash);
        mediaPlayer.startup();
        mediaPlayer.attachView(videoTag);
        mediaPlayer.attachSource(video.src);
      },
      resume: function() {
        if (player.finished) {
          videoTag.currentTime = 0;
        }
        videoTag.play();
      },
      pause: function() {
        videoTag.pause();
      },
      seek: function(time) {
        if (videoTag.paused) {
          // dash.js always resumes playback after seek
          $(videoTag).one("seeked.dashpaused", function () {
            setTimeout(function () {
              videoTag.pause()
              // stop seeks to 0 causing dash.js to resume
              // see stop handle above
              if (dashstop) {
                player.trigger('stop', [player]);
              }
            }, 0);
          });
        }
        videoTag.currentTime = time;
      },
      volume: function(level) {
        if (videoTag) {
          videoTag.volume = level;
        }
      },
      speed: function(val) {
        videoTag.playbackRate = val;
        root.trigger('speed', [player, val]);
      },
      unload: function() {
        if (mediaPlayer) {
          mediaPlayer.reset();
        }
        $(videoTag).remove();
        root.trigger("unload", [player]);
      }

    };

  };

  $(function () {
    // hack: globally force dash engine, but allow other global config
    flowplayer.conf.engine = "mpegdash";
  });

}(jQuery));
<|endoftext|>


<commit_before>import http from 'http';
import urlParser from 'url';
import debug from 'debug';

const log = debug('w3c-webdriver');

function findError({ status, value }) {
  if (!status && (!value || !value.error)) {
    return null;
  }

  const { message, error } = value;

  return new Error(`WebDriverError(${error || status}): ${message}`);
}

function sendRequest(method, url, body) {
  const jsonBody = JSON.stringify(body);
  const urlParts = urlParser.parse(url);
  const options = {
    hostname: urlParts.hostname,
    port: urlParts.port,
    path: urlParts.path,
    method,
    headers: {}
  };

  if (body) {
    options.headers['Content-Length'] = Buffer.byteLength(jsonBody);
    options.headers['Content-Type'] = 'application/json';
  }

  return new Promise((resolve, reject) => {
    const request = http.request(options, (response) => {
      const chunks = [];
      response.setEncoding('utf8');
      response.on('data', (chunk) => {
        chunks.push(chunk);
      });
      response.on('end', () => {
        let responseBody;

        try {
          responseBody = JSON.parse(chunks.join(''));
        } catch (err) {
          reject(err);
        }

        log(`WebDriver response: ${chunks.join('')}`);

        const error = findError(responseBody);

        if (error) {
          reject(error);
          return;
        }

        resolve(responseBody);
      });
    });

    request.on('error', error => reject(error));

    if (body) {
      request.write(jsonBody);
    }
    request.end();
  });
}

export const GET = url => sendRequest('GET', url);
export const POST = (url, body) => sendRequest('POST', url, body);
export const DELETE = (url, body) => sendRequest('DELETE', url, body);
<commit_msg>Improve logging<commit_after>import http from 'http';
import urlParser from 'url';
import debug from 'debug';

const log = debug('w3c-webdriver');

function findError({ status, value }) {
  if (!status && (!value || !value.error)) {
    return null;
  }

  const { message, error } = value;

  return new Error(`WebDriverError(${error || status}): ${message}`);
}

function sendRequest(method, url, body) {
  const jsonBody = JSON.stringify(body);
  const urlParts = urlParser.parse(url);
  const options = {
    hostname: urlParts.hostname,
    port: urlParts.port,
    path: urlParts.path,
    method,
    headers: {}
  };

  if (body) {
    options.headers['Content-Length'] = Buffer.byteLength(jsonBody);
    options.headers['Content-Type'] = 'application/json';
  }

  return new Promise((resolve, reject) => {
    log(`WebDriver request: ${options.url} ${options.body}`);
    const request = http.request(options, (response) => {
      const chunks = [];
      response.setEncoding('utf8');
      response.on('data', (chunk) => {
        chunks.push(chunk);
      });
      response.on('end', () => {
        let responseBody;

        try {
          responseBody = JSON.parse(chunks.join(''));
        } catch (err) {
          reject(err);
        }

        log(`WebDriver response: ${chunks.join('')}`);

        const error = findError(responseBody);

        if (error) {
          reject(error);
          return;
        }

        resolve(responseBody);
      });
    });

    request.on('error', error => reject(error));

    if (body) {
      request.write(jsonBody);
    }
    request.end();
  });
}

export const GET = url => sendRequest('GET', url);
export const POST = (url, body) => sendRequest('POST', url, body);
export const DELETE = (url, body) => sendRequest('DELETE', url, body);
<|endoftext|>


<commit_before>var path = require('path'); //http://nodejs.org/api/path.html
var fs = require('node-fs'); // Recursive directory creation. https://github.com/bpedro/node-fs
var winston = require('winston'); // Logging. https://github.com/flatiron/winston

process.chdir(path.dirname(process.mainModule.filename));

global.configPath = './config.json';

// args will be ['node', 'server.js', 'config.json']
if (process.argv.length > 2) {
    global.configPath = process.argv[2];
}

global.app = null;
global.comm = {};
global.loggers = {};
global.config = JSON.parse(fs.readFileSync(global.configPath));

winston.info('Server starting up.');
var ServerState = require('./model/serverState.js').ServerState;
global.serverState = new ServerState(config.server);
serverState.start();
winston.info('Server started.');

/*
Content Updater
    There is an "unzipping app" message even if the app isn't new
    Backup current app/content to .old folders before beginning
    "Rollback" button to bring back .old
    Multiple remotes -- live and test data.

Logging
    Offline Google Analytics -- save events when offline, send when online

Demo App
    share state

Console
    Localhost console shows local client, master console shows all clients
        List of clients in config file, or use auto-discovery?
    Output
        Number of clients
        CPU temperature? http://ipmiutil.sourceforge.net/
        Display arbitrary amount of state per client (like ICE)
    Input
        Kill running client
        Kill all running clients
        Start dead client
        Start all clients
        Restart client
        Restart all clients
        Update content on all clients: kill process, update content, update client, restart client
        Config editor
        Push config to all clients

State manager
    Runs on master only
    App sends state to master over OSC on interval
    Server sends state to apps over OSC on interval
    State is just a JS object
    Server sends config to clients over socket on interval - or socket?
        On config, write to file and restart app with new config

Run as service? https://npmjs.org/package/node-windows
*/<commit_msg>todos<commit_after>var path = require('path'); //http://nodejs.org/api/path.html
var fs = require('node-fs'); // Recursive directory creation. https://github.com/bpedro/node-fs
var winston = require('winston'); // Logging. https://github.com/flatiron/winston

process.chdir(path.dirname(process.mainModule.filename));

global.configPath = './config.json';

// args will be ['node', 'server.js', 'config.json']
if (process.argv.length > 2) {
    global.configPath = process.argv[2];
}

global.app = null;
global.comm = {};
global.loggers = {};
global.config = JSON.parse(fs.readFileSync(global.configPath));

winston.info('Server starting up.');
var ServerState = require('./model/serverState.js').ServerState;
global.serverState = new ServerState(config.server);
serverState.start();
winston.info('Server started.');

/*
Misc
    There is an "unzipping app" message even if the app isn't new
    Change restartAppAfter to seconds
    Make startup schedule do restarts
    Provide a way to turn off logs -- current solution doesn't actually work
    Offline Google Analytics -- save events when offline, send when online
    Add a tag property for loggly config to differentiate installs.

Content Updater
    Backup current app/content to .old folders before beginning
    "Rollback" button to bring back .old
    Multiple remotes -- live and test data.

Demo App
    share state

Console
    Localhost console shows local client, master console shows all clients
        List of clients in config file, or use auto-discovery?
    Output
        Number of clients
        CPU temperature? http://ipmiutil.sourceforge.net/
        Display arbitrary amount of state per client (like ICE)
    Input
        Kill running client
        Kill all running clients
        Start dead client
        Start all clients
        Restart client
        Restart all clients
        Update content on all clients: kill process, update content, update client, restart client
        Config editor
        Push config to all clients

State manager
    Runs on master only
    App sends state to master over OSC on interval
    Server sends state to apps over OSC on interval
    State is just a JS object
    Server sends config to clients over socket on interval - or socket?
        On config, write to file and restart app with new config

Run as service? https://npmjs.org/package/node-windows
*/<|endoftext|>


<commit_before>;
(function() {

  var oAuthImplicitGRant = function(){
  	function getParameterByName(name) {
		  var match = RegExp('[#&]' + name + '=([^&]*)').exec(window.location.hash);
		  return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
		}

		function getAccessToken() {
		  return getParameterByName('access_token');
		  console.log("access_token!", access_token); //the new item is returned with an ID
		}

		function getIdToken() {
		  return getParameterByName('id_token');
		}

		$(function () {
		  var access_token = getAccessToken();

		  // Optional: an id_token will be returned by Auth0
		  // if your response_type argument contained id_token
		  var id_token = getIdToken();

		  // Use the access token to make API calls
			$('#get-appointments').click(function(e) {
			  e.preventDefault();

			  // $.ajax({
			  //   cache: false,
			  //   url: "https://danvitoriano.auth0.com/userinfo",
			  //   headers: { "Authorization": "Bearer " + access_token }
			  // });

			  $.ajax({
	        type: 'GET',
	        cache: false,
	        url: 'https://danvitoriano.auth0.com/userinfo',
	        headers: { "Authorization": "Bearer " + access_token },
	        success: function(data) {
	          console.log("access_token!", access_token); //the new item is returned with an ID

	          $("#res-10").html("
" + data.email + "
");
	        },
	        error: function() {
	          console.log("Content not added!", access_token); //the new item is returned with an ID
	          $("#res-10").html("
Error " + access_token + "
");
	        }
	      });

			});
		});
  }();

})();
<commit_msg>add implicit grant test<commit_after>;
(function() {

  var oAuthImplicitGRant = function(){
  	function getParameterByName(name) {
		  var match = RegExp('[#&]' + name + '=([^&]*)').exec(window.location.hash);
		  return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
		}

		function getAccessToken() {
		  return getParameterByName('access_token');
		  console.log("access_token!", access_token); //the new item is returned with an ID
		}

		function getIdToken() {
		  return getParameterByName('id_token');
		}

		$(function () {
		  var access_token = getAccessToken();

		  // Optional: an id_token will be returned by Auth0
		  // if your response_type argument contained id_token
		  var id_token = getIdToken();

		  // Use the access token to make API calls
			$('#get-appointments').click(function(e) {
			  e.preventDefault();

			  // $.ajax({
			  //   cache: false,
			  //   url: "https://danvitoriano.auth0.com/userinfo",
			  //   headers: { "Authorization": "Bearer " + access_token }
			  // });

			  $.ajax({
	        type: 'GET',
	        cache: false,
	        url: 'https://danvitoriano.auth0.com/userinfo',
	        headers: { "Authorization": "Bearer " + access_token },
	        success: function(data) {
	          console.log("access_token!", access_token); //the new item is returned with an ID

	          $("#res-10").html("
" + data.email + ", " + data.name + ", " + data.family_name + "
");
	        },
	        error: function() {
	          console.log("Content not added!", access_token); //the new item is returned with an ID
	          $("#res-10").html("
Error " + access_token + "
");
	        }
	      });

			});
		});
  }();

})();
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 <commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]<|endoftext|>


<commit_before>function AfficherClassement() {

	var liste = [[1,"MULOT Cyrille",3],[2,"AMIOT Antoine",2],[3,"BRUNET Xavier",36],[4,"FONTENAY Karine",1],[5,"PRIVAT Nicolas",61],[6,"KAMINSKI Stephan",98],[7,"GARDENT Thierry",51],[8,"HENNENFENT Roland",17],[9,"BENOIT Philippe",39],[10,"LANGEVIN Samuel",58],[11,"REVILLER Thierry",86],[12,"SAVART Jerome",65],[13,"MOULIN Franck",68],[14,"ALENDOURO Victor",66],[15,"PECOT Stève",95],[16,"VASTESAEGER Sven",75],[17,"GARNIER Dominique",23],[18,"FLOURET Michel",46],[19,"MINARD Anne laure",76],[20,"PASQUET Frederic",79],[21,"DEVILLERT Christophe",28],[22,"LAPIERRE Michael",85],[23,"ROUX Thierry",82],[24,"ROULET David",59],[25,"DORDAIN Tony",93],[26,"MENDER Miloud",96],[27,"FONTAINE Julien",29],[28,"FOUQUET Arnaud",48],[29,"GICQUEL Fabrice",97],[30,"ARAR Didier",84],[31,"BRAJON Bertrand",57],[32,"SCIACCA Aurélia",50],[33,"LOPES LELO Maria",5],[34,"FORESTIER David",33],[35,"HUET Jérôme",53],[36,"MARSURA Philippe",42],[37,"LINVAL Philippe",69],[38,"HERNOT Laurent",89],[39,"LAKAS Patrice",67],[40,"MARCHAND Eric",40],[41,"BOURNAT Thierry",38],[42,"CAMBONI Mario",25],[43,"BARICHARD Jérôme",47],[44,"SANSELME Philippe",87],[45,"ANDRE Serge",71],[46,"CARTON Noël",24],[47,"PETITJEAN Rémy",64],[48,"TEISSEDRE Christian",37],[49,"AMY Jérôme",99],[50,"MOYNAULT Christophe",35],[51,"VéNIANT Romu",92],[52,"LEBIGUE Tristan",88],[53,"JUGE Fabrice",26],[54,"VINCENT Jérémy",90],[55,"IVART Yann",30],[56,"DESJOUR Patrick",70],[57,"GALLON Fabrice",77],[58,"GUYOT Jean-joseph",27],[59,"CHATARD Benoit",80],[60,"ROUX Claude",9],[61,"KOWALSKI Dany",63],[62,"PERRETTE Christophe",34],[63,"DUBOURDIEU Stephane",81],[64,"LAMBERT Guillaume",54],[65,"FAMBRINI Cyril",52],[66,"MOUNIER Christian",72],[67,"BROSSARD Remy",13],[68,"FOUQUET Arnaud",94],[69,"ARNAUD Christian",44]];

	var liste2 = [[70,"MOSNIER Bernard",55],[71,"BERGERET Lise",8],[72,"BERGERET Christophe",7],[73,"LEFEBVRE Michel",91],[74,"FLEURY Stephanie",15],[75,"AUBARD Nicolas",74],[76,"VALLEE Nelly",45],[77,"BERNABEU Julien",73],[78,"DUPRé Alain",78],[79,"SALIGNAT Jean-claude",4],[80,"VOLAT Marc",21],[81,"BENIGAUD Sylviane",18],[82,"LEPAIN Laurent",22]];

	for (i=0; i!=liste.length; i++) {
		document.getElementById('liste').innerHTML += '
'+liste[i][2]+'	'+liste[i][1]+'	'+liste[i][0]+'
';
	}

	for (y=0; y!=liste2.length; y++) {
		document.getElementById('liste').innerHTML += '
'+liste2[y][2]+'	'+liste2[y][1]+'	'+liste2[y][0]+'
';
	}
}<commit_msg>Fix error + add global list var<commit_after>	var liste = [[1,"MULOT Cyrille",3],[2,"AMIOT Antoine",2],[3,"BRUNET Xavier",36],[4,"FONTENAY Karine",1],[5,"PRIVAT Nicolas",61],[6,"KAMINSKI Stephan",98],[7,"GARDENT Thierry",51],[8,"HENNENFENT Roland",17],[9,"BENOIT Philippe",39],[10,"LANGEVIN Samuel",58],[11,"REVILLER Thierry",86],[12,"SAVART Jerome",65],[13,"MOULIN Franck",68],[14,"ALENDOURO Victor",66],[15,"PECOT Stève",95],[16,"VASTESAEGER Sven",75],[17,"GARNIER Dominique",23],[18,"FLOURET Michel",46],[19,"MINARD Anne laure",76],[20,"PASQUET Frederic",79],[21,"DEVILLERT Christophe",28],[22,"LAPIERRE Michael",85],[23,"ROUX Thierry",82],[24,"ROULET David",59],[25,"DORDAIN Tony",93],[26,"MENDER Miloud",96],[27,"FONTAINE Julien",29],[28,"FOUQUET Arnaud",48],[29,"GICQUEL Fabrice",97],[30,"ARAR Didier",84],[31,"BRAJON Bertrand",57],[32,"SCIACCA Aurélia",50],[33,"LOPES LELO Maria",5],[34,"FORESTIER David",33],[35,"HUET Jérôme",53],[36,"MARSURA Philippe",42],[37,"LINVAL Philippe",69],[38,"HERNOT Laurent",89],[39,"LAKAS Patrice",67],[40,"MARCHAND Eric",40],[41,"BOURNAT Thierry",38],[42,"CAMBONI Mario",25],[43,"BARICHARD Jérôme",47],[44,"SANSELME Philippe",87],[45,"ANDRE Serge",71],[46,"CARTON Noël",24],[47,"PETITJEAN Rémy",64],[48,"TEISSEDRE Christian",37],[49,"AMY Jérôme",99],[50,"MOYNAULT Christophe",35],[51,"VéNIANT Romu",92],[52,"LEBIGUE Tristan",88],[53,"JUGE Fabrice",26],[54,"VINCENT Jérémy",90],[55,"IVART Yann",30],[56,"DESJOUR Patrick",70],[57,"GALLON Fabrice",77],[58,"GUYOT Jean-joseph",27],[59,"CHATARD Benoit",80],[60,"ROUX Claude",9],[61,"KOWALSKI Dany",63],[62,"PERRETTE Christophe",34],[63,"DUBOURDIEU Stephane",81],[64,"LAMBERT Guillaume",54],[65,"FAMBRINI Cyril",52],[66,"MOUNIER Christian",72],[67,"BROSSARD Remy",13],[68,"FOUQUET Arnaud",94],[69,"ARNAUD Christian",44]];

	var liste2 = [[70,"MOSNIER Bernard",55],[71,"BERGERET Lise",8],[72,"BERGERET Christophe",7],[73,"LEFEBVRE Michel",91],[74,"FLEURY Stephanie",15],[75,"AUBARD Nicolas",74],[76,"VALLEE Nelly",45],[77,"BERNABEU Julien",73],[78,"DUPRé Alain",78],[79,"SALIGNAT Jean-claude",4],[80,"VOLAT Marc",21],[81,"BENIGAUD Sylviane",18],[82,"LEPAIN Laurent",22]];

	var listeglobal = liste.concat(liste2);

function AfficherClassement() {
	for (i=0; i<listeglobal.length; i++) {
		document.getElementById('liste').innerHTML += '
'+listeglobal[i][0]+'	'+listeglobal[i][1]+'	'+listeglobal[i][2]+'
';
	}
}<|endoftext|>


<commit_before>var gulp = require('gulp'),
    bower = require('gulp-bower'),
    exec = require('child_process').exec;

gulp.task('default', function(){
  bower()
    .pipe(gulp.dest('public/js/lib/'));
});

gulp.task('cordova-bower', function (cb) {
  // couldn't figure out how to get bower to run in a different directory
  exec('cd opentok-meet-cordova;bower install');

  // Compile common-js-helpers
  exec('cd opentok-meet-cordova/www/js/lib/common-js-helpers;npm install;grunt', function (err, stdout) {
    console.log(stdout);
    cb(err);
  });
});

gulp.task('cordova', ['cordova-bower'], function (cb) {
  // Copy over the single-sourced JS
  gulp.src('./public/js/*.js')
    .pipe(gulp.dest('opentok-meet-cordova/www/js'));

  // Copy over the single-source CSS
  gulp.src('./public/css/*.css')
    .pipe(gulp.dest('opentok-meet-cordova/www/css'));

  // Copy over the images
  gulp.src('./public/images/*.*')
    .pipe(gulp.dest('opentok-meet-cordova/www/images'));

  var prepare = function () {
    // Add the ios platform
    exec('cd opentok-meet-cordova;cordova platform add ios', function (err) {
      // Prepare for ios
      if (!err) {
        // If there's no error then you haven't already installed the platform
        console.log('If you want to hide the status bar you may need to add the following to OpenTokMeet-Info.plist');
        console.log('<key>UIStatusBarHidden</key>\n' +
                  '<true/>\n' +
                  '<key>UIViewControllerBasedStatusBarAppearance</key>\n' +
                  '<false/>\n'
        );
      }
      exec('cd opentok-meet-cordova;cordova prepare ios', function (err) {
        if (err) cb(err);
        else {
          // Copy over icons
          gulp.src('./opentok-meet-cordova/src/icons/ios7/*.png')
            .pipe(gulp.dest('opentok-meet-cordova/platforms/ios/OpenTokMeet/Resources/icons'));
          // Copy over splash screens
          gulp.src('./opentok-meet-cordova/src/splash/*.png')
            .pipe(gulp.dest('opentok-meet-cordova/platforms/ios/OpenTokMeet/Resources/splash'));
          exec('open opentok-meet-cordova/platforms/ios/OpenTokMeet.xcodeproj');
          cb();
        }
      });
    });
  };

  var cordovaPlugins = {
    'com.tokbox.cordova.opentok': 'https://github.com/phonegap-build/StatusBarPlugin.git',
    'com.phonegap.plugin.statusbar': 'https://github.com/phonegap-build/StatusBarPlugin.git'
  };
  // Install the cordova plugins if they're not already there
  var output = exec('cd opentok-meet-cordova;cordova plugin list', function (err, stdout, stderr) {
    if (err) {
      cb(err);
      return;
    }
    var plugins = Object.keys(cordovaPlugins);
    var getNextPlugin = function() {
      var key = plugins.pop();
      if (!key) {
        prepare();
        return;
      }
      if (stdout.indexOf(key) < 0) {
        console.log('Installing cordova plugin from: ' + cordovaPlugins[key]);
        exec('cd opentok-meet-cordova;cordova plugin add ' + cordovaPlugins[key], function (err, stdout, stderr) {
          console.log(stdout);
          if (err) cb(err);
          else {
            getNextPlugin();
          }
        });
      } else {
        getNextPlugin();
      }
    };
    getNextPlugin();
  });
});

gulp.task('serve-ios', ['cordova'], function (cb) {
  exec('cd opentok-meet-cordova;cordova serve ios');
});<commit_msg>Adding logging of the URLTypes properties to gulp. Should really get this into cordova though. See #9<commit_after>var gulp = require('gulp'),
    bower = require('gulp-bower'),
    exec = require('child_process').exec;

gulp.task('default', function(){
  bower()
    .pipe(gulp.dest('public/js/lib/'));
});

gulp.task('cordova-bower', function (cb) {
  // couldn't figure out how to get bower to run in a different directory
  exec('cd opentok-meet-cordova;bower install');

  // Compile common-js-helpers
  exec('cd opentok-meet-cordova/www/js/lib/common-js-helpers;npm install;grunt', function (err, stdout) {
    console.log(stdout);
    cb(err);
  });
});

gulp.task('cordova', ['cordova-bower'], function (cb) {
  // Copy over the single-sourced JS
  gulp.src('./public/js/*.js')
    .pipe(gulp.dest('opentok-meet-cordova/www/js'));

  // Copy over the single-source CSS
  gulp.src('./public/css/*.css')
    .pipe(gulp.dest('opentok-meet-cordova/www/css'));

  // Copy over the images
  gulp.src('./public/images/*.*')
    .pipe(gulp.dest('opentok-meet-cordova/www/images'));

  var prepare = function () {
    // Add the ios platform
    exec('cd opentok-meet-cordova;cordova platform add ios', function (err) {
      // Prepare for ios
      if (!err) {
        // If there's no error then you haven't already installed the platform
        console.warn('If you want to hide the status bar you may need to add the following to OpenTokMeet-Info.plist');
        console.warn('<key>UIStatusBarHidden</key>\n' +
                  '<true/>\n' +
                  '<key>UIViewControllerBasedStatusBarAppearance</key>\n' +
                  '<false/>\n' +
                    '<key>CFBundleURLTypes</key>\n' +
                    '<array>\n' +
                    '<dict>\n' +
                    '<key>CFBundleTypeRole</key>\n' +
                    '<string>Viewer</string>\n' +
                    '<key>CFBundleURLIconFile</key>\n' +
                    '<string>Icon-72</string>\n' +
                    '<key>CFBundleURLName</key>\n' +
                    '<string>com.tokbox.meet</string>\n' +
                    '<key>CFBundleURLSchemes</key>\n' +
                    '<array>\n' +
                    '<string>otmeet</string>\n' +
                    '</array>\n' +
                    '</dict>\n' +
                    '</array>\n'
        );
      }
      exec('cd opentok-meet-cordova;cordova prepare ios', function (err) {
        if (err) cb(err);
        else {
          // Copy over icons
          gulp.src('./opentok-meet-cordova/src/icons/ios7/*.png')
            .pipe(gulp.dest('opentok-meet-cordova/platforms/ios/OpenTokMeet/Resources/icons'));
          // Copy over splash screens
          gulp.src('./opentok-meet-cordova/src/splash/*.png')
            .pipe(gulp.dest('opentok-meet-cordova/platforms/ios/OpenTokMeet/Resources/splash'));
          exec('open opentok-meet-cordova/platforms/ios/OpenTokMeet.xcodeproj');
          cb();
        }
      });
    });
  };

  var cordovaPlugins = {
    'com.tokbox.cordova.opentok': 'https://github.com/phonegap-build/StatusBarPlugin.git',
    'com.phonegap.plugin.statusbar': 'https://github.com/phonegap-build/StatusBarPlugin.git'
  };
  // Install the cordova plugins if they're not already there
  var output = exec('cd opentok-meet-cordova;cordova plugin list', function (err, stdout, stderr) {
    if (err) {
      cb(err);
      return;
    }
    var plugins = Object.keys(cordovaPlugins);
    var getNextPlugin = function() {
      var key = plugins.pop();
      if (!key) {
        prepare();
        return;
      }
      if (stdout.indexOf(key) < 0) {
        console.log('Installing cordova plugin from: ' + cordovaPlugins[key]);
        exec('cd opentok-meet-cordova;cordova plugin add ' + cordovaPlugins[key], function (err, stdout, stderr) {
          console.log(stdout);
          if (err) cb(err);
          else {
            getNextPlugin();
          }
        });
      } else {
        getNextPlugin();
      }
    };
    getNextPlugin();
  });
});

gulp.task('serve-ios', ['cordova'], function (cb) {
  exec('cd opentok-meet-cordova;cordova serve ios');
});<|endoftext|>