var loggerTransport = new winston.transports.Console({ "level" : (process.env.LOG_LEVEL || 'info'), "dumpExceptions" : true, "showStack" : true, "colorize" : true }); var logger = new winston.Logger({"transports" : [ loggerTransport ]}); commander.version('0.0.1') .option('-p, --path [path]', 'Request test serve on given path') .option('-c, --concurrency [concurrency]', 'Run c concurrent requests') .parse(process.argv); Async.parallel( _.map(_.range(commander.concurrency), function(i) { return function(callback) { Async.waterfall([ function createGetRequest(cb) { var requestOpts = { "host" : "127.0.0.1", "port" : process.env.PORT || 8000, "path" : path.join(commander.path, i.toString()), "method" : "get" }; var get = http.request(requestOpts, function(response) { cb(null, response); }); logger.debug("%d) sending request", i); get.end(); }, function extractResponseBody(response, cb) {
ctrl.changePlayerSetting = (n, entity) => { let playerActors = ctrl.playerActors(); playerActors[n] = entity; ctrl.playerActors(playerActors); }; }, view (ctrl) { return m('.NewGameSetting', m('.col', [ m('h4', 'Genral Settings'), m('.row', [ 'players: ', m('select', { key: 'players', value: ctrl.players(), onchange: m.withAttr('value', ctrl.changePlayerCount.bind(ctrl)), },_.range(1,5).map(n => { return m('option', { value: n }, n); })), ]), _.range(1, parseInt(ctrl.players()) + 1).map(n => { return m('.row', { key: `actor${n}.row` }, [ m('.PlayerSetting', `player ${n}:`), m('select', { value: ctrl.playerActors()[n-1], onchange: m.withAttr('value', ctrl.changePlayerSetting.bind(ctrl, n-1)), }, ctrl.actors.map(player => { return m('option', {
finder.find= function (query) { if (query.opts.hints) console.log(('SCAN on '+query.table.name+' for '+JSON.stringify(query.cond,null,2)).red); var p= dyn.promise(['results','count','end'],null,'consumed'), avgItemSize= Math.ceil(query.table._dynamo.TableSizeBytes/query.table._dynamo.ItemCount), perWorker= (M/avgItemSize)*80/100, workers= Math.ceil(query.table._dynamo.ItemCount/perWorker); if (!workers) workers= 1; else if (workers>query.table._dynamo.ProvisionedThroughput.ReadCapacityUnits) workers= query.table._dynamo.ProvisionedThroughput.ReadCapacityUnits; // FIXME: implement opts.maxworkers ? better divide & conquer algorithm var filter= {}; Object.keys(query.$filter).forEach(function (fieldName) { var field= query.$filter[fieldName]; if (field.op!='REGEXP') { filter[fieldName]= field; delete query.$filter[fieldName]; query.$filtered.push(fieldName); } }); query.counted= query.canCount()&&query.count; if (query.counted) { var count= 0, progress= [], _progress= function (segment, pcount) { progress[segment]= pcount; process.stdout.write(('\r'+_.reduce(progress,function (memo,num) { return memo+num; },0)).yellow); }; async.forEach(_.range(workers), function (segment,done) { var sp= dyn.table(query.table.name) .scan(function (wcount) { count+=wcount; done(); }, { filter: filter, attrs: query.finderProjection(), limit: query.window, count: query.count, segment: { no: segment, of: workers } }) .consumed(p.trigger.consumed) .error(done); if (dyn.iscli()) sp.progress(function (pcount) { _progress(segment,pcount); }) }, function (err) { if (err) p.trigger.error(err); else p.trigger.count(count); }); } else { async.forEach(_.range(workers), function (segment,done) { dyn.table(query.table.name) .scan(p.trigger.results, { filter: filter, attrs: query.finderProjection(), segment: { no: segment, of: workers }, limit: query.window }) .consumed(p.trigger.consumed) .end(done) .error(done); }, function (err) { if (err) p.trigger.error(err); else p.trigger.end(); }); } return p; };
selftest.define('galaxy self-signed cert', ['galaxy'], function () { galaxyUtils.sanityCheck(); var s = new Sandbox; // Login with a valid Galaxy account galaxyUtils.loginToGalaxy(s); // Deploy an app. Check that it is running. var appName = galaxyUtils.createAndDeployApp(s); checkAppIsRunning(appName, { text: "Hello" }); // Force SSL. var run = s.run("add", "force-ssl"); run.waitSecs(5); run.expectExit(0); run = s.run("deploy", appName); run.waitSecs(30); run.expectExit(0); galaxyUtils.waitForContainers(); // Create a signed certificate for the app. // createSelfSignedCertificateForApp: function (appId, options) { var appRecord = galaxyUtils.getAppRecordByName(appName); var conn = galaxyUtils.loggedInGalaxyAPIConnection(); var certIds = _.map(_.range(0, 15), function () { return galaxyUtils.callGalaxyAPI( conn, "createSelfSignedCertificateForApp", appRecord._id); }); // Activate a certificate in the middle -- not the first or the last. galaxyUtils.callGalaxyAPI( conn, "activateCertificateForApp", certIds[3], appRecord._id); // Check that we are getting a re-direct. galaxyUtils.waitForContainers(); appRecord = galaxyUtils.getAppRecordByName(appName); selftest.expectEqual(appRecord.containerCount, 1); var activeCert = appRecord["activeCertificateId"]; selftest.expectEqual(activeCert, certIds[3]); if (! galaxyUtils.ignoreHttpChecks()) { run = galaxyUtils.curlToGalaxy(appName); run.waitSecs(5); run.matchErr("SSL"); run.expectExit(60); } // Remove the un-activated certificates _.each(_.range(0, 15), function (i) { if (i !== 3) { galaxyUtils.callGalaxyAPI( conn, "removeCertificateFromApp", certIds[i], appRecord._id); } }); // Check that we are still getting a re-direct and GalaxyAPI thinks that we // are using the same cert. appRecord = galaxyUtils.getAppRecordByName(appName); selftest.expectEqual(appRecord["activeCertificateId"], activeCert); if (! galaxyUtils.ignoreHttpChecks()) { run = galaxyUtils.curlToGalaxy(appName); run.waitSecs(5); run.matchErr("SSL"); run.expectExit(60); } // Clean up. galaxyUtils.cleanUpApp(s, appName); testUtils.logout(s); galaxyUtils.closeGalaxyConnection(conn); });
out.push(fn(i)); } return out; }; var loopeven = function(n,fn){ var out = []; for (var i = 0; i < n; i++){ if (i%2 === 0){ out.push(fn(i)); } else { out.push(i); } } return out; }; log(loop(n,sq)); //square fn log(loop(n,cub)); //cubic fn log(loopeven(n,sq)); //square on even indices and return idx otherwise log(loopeven(n,cub)); //Same as above for cubed //Implementation 3: using underscorejs.org var uu = require('underscore'); //range: generate an array of numbers from 0 to n //map: apply a function to the specified array range(incl 0 ,excl n) log( uu.map(uu.range(0,n),sq) ); log( uu.map(uu.range(0,n),cub) );
var position = obj[this.props.sortId]; var change = position; var inRange = this.inRange(oldPosition, newPosition, position); if ( inRange ) change += positiveChange ? -1 : 1; this._updateItemPosition(obj.id, obj.id == id ? newPosition : change) }); }, inRange(oldPosition, newPosition, position) { var positiveChange = newPosition > oldPosition; var start = positiveChange ? oldPosition : newPosition; var end = positiveChange ? newPosition : oldPosition; var range = _.range(start, end + 1); return _.contains(range, position); }, childrenWithData() { var Component = React.Children.only(this.props.children); if (this.state.items && this.state.items.length) { return this.state.items.map((object, idx) => { var obj = _.clone(object); if (!obj.key) { obj.key = obj.id; } obj.index = idx + 1; return (React.cloneElement(Component, _.extend(obj, this._buildProps()))); });
return self.driver.getServerStatus().then(function(status) { logger.debug("Obtained status: ", status); /* remove everything but the current clip */ var ret = Q.resolve() ; // .then(function() { logger.debug("Cleaning playlist"); // return ret = ret.then(function() { return self.driver.cleanPlaylist().then(function(){ logger.debug("Playlist cleaned");}); }); // }); var expected = self.getExpectedMedia(); var addClip = function(media) { //return ret.then(function() { logger.info("Adding media: " + media.get('file')); return self.driver.appendClip(media.toJSON()); //}); }; if( ! expected.media ) { logger.warn("If we fixed blanks, we NEVER should enter here", self.pluck('file')); //TODO: After fixing blanks, we NEVER should enter here... Throw error?? self.forEach(function(c, i) { // ret = ret.then(function() { c.set("actual_order", i) logger.debug("Queuing Append for clip: " + c.get('file')); // return ret = ret.then(function() { return addClip(c); }); // }); }); logger.debug("Leaving read semaphore"); return ret.then(self.leave); } logger.debug("Expected media: ", {"media": expected.media.get('file'), "frame": expected.frame}); var ids = self.pluck('id'); // I need to add from expected clip var cur_i = ids.indexOf(expected.media.id); self.remove(ids.slice(0, cur_i)); var add_current = false; if(status.currentClip && ( expected.media.id.toString() === status.currentClip.id.toString() )) { logger.debug("Current playing clip is expected"); } else { // append expected clip logger.debug("Queuing Append for expected clip: " + self.at(0).get('file')); // ret = ret = ret.then(function() { return addClip(self.at(0)).then(function() { logger.debug("Appended first clip"); });}); // I'll need to add the current clip to myself to make sure I keep reflecting melted status add_current = status.currentClip; } // append next clip just in case if(self.length > 1) { logger.debug("Queuing Append for next clip: " + self.at(1).get("file")); ret = ret.then(function() { return addClip(self.at(1)).then(function() { logger.debug("Appended second clip"); });}); } // generate a new promise that will release the read semaphore inmediatly after appending the next clip ret = ret.then(function() { var start = 0; if (add_current) start = 1; // we do this here in order to have actual order synched before leaving semaphore logger.debug("Rearranging actual order"); self.forEach(function(c, i) { c.set('actual_order', i + start); }); logger.debug("Leaving read semaphore"); self.leave(); }); /* and then put everything after into melted */ logger.debug("Queuing Append for rest of the clips"); _.range(2, self.length).forEach(function(i) { ret = ret.then(function() { return addClip(self.at(i)).then(function(){ logger.debug("Appended %d-th clip", i); });}); }); if( add_current ) { logger.debug("Adding current (wrong) clip so we can reflect melted status"); /* I leave the current clip at the top of the melted playlist, it won't do any harm */ status.currentClip.actual_order = 0; self.add(status.currentClip, { at: 0, set_melted: false, fix_blanks: false }); } return ret; }).fail(function(err) {
click_handler: function (args) { var data = args.data; var num_cols = this.model.colors[0].length; var index = args.row_num * num_cols + args.column_num; var row = args.row_num; var column = args.column_num; var that = this; var idx = this.model.get("selected") ? utils.deepCopy(this.model.get("selected")) : []; var selected = utils.deepCopy(this._cell_nums_from_indices(idx)); var elem_index = selected.indexOf(index); var accelKey = d3.event.ctrlKey || d3.event.metaKey; //TODO: This is a shim for when accelKey is supported by chrome. // index of slice i. Checking if it is already present in the // list if(elem_index > -1 && accelKey) { // if the index is already selected and if ctrl key is // pressed, remove the element from the list idx.splice(elem_index, 1); } else { if(!accelKey) { selected = []; idx = []; } idx.push([row, column]); selected.push(that._cell_nums_from_indices([[row, column]])[0]); if(d3.event.shiftKey) { //If shift is pressed and the element is already //selected, do not do anything if(elem_index > -1) { return; } //Add elements before or after the index of the current //slice which has been clicked var row_index = (selected.length !== 0) ? that.anchor_cell_index[0] : row; var col_index = (selected.length !== 0) ? that.anchor_cell_index[1] : column; _.range(Math.min(row, row_index), Math.max(row, row_index)+1).forEach(function(i) { _.range(Math.min(column, col_index), Math.max(column, col_index)+1).forEach(function(j) { var cell_num = that._cell_nums_from_indices([[i, j]])[0]; if (selected.indexOf(cell_num) === -1) { selected.push(cell_num); idx.push([i, j]); } }) }); } else { // updating the array containing the slice indexes selected // and updating the style this.anchor_cell_index = [row, column]; } } this.model.set("selected", ((idx.length === 0) ? null : idx), {updated_view: this}); this.touch(); if(!d3.event) { d3.event = window.event; } var e = d3.event; if(e.cancelBubble !== undefined) { // IE e.cancelBubble = true; } if(e.stopPropagation) { e.stopPropagation(); } e.preventDefault(); this.selected_indices = idx; this.apply_styles(); },
draw: function() { this.set_ranges(); var that = this; var num_rows = this.model.colors.length; var num_cols = this.model.colors[0].length; var row_scale = this.scales.row; var column_scale = this.scales.column; var row_start_aligned = this.model.get("row_align") === "start"; var col_start_aligned = this.model.get("column_align") === "start"; var new_domain; if(this.model.modes.row !== "middle" && this.model.modes.row !== "boundaries") { new_domain = this.expand_scale_domain(row_scale, this.model.rows, this.model.modes.row, (row_start_aligned)); if(d3.min(new_domain) < d3.min(row_scale.model.domain) || d3.max(new_domain) > d3.max(row_scale.model.domain)) { // Update domain if domain has changed row_scale.model.compute_and_set_domain(new_domain, row_scale.model.model_id); } } if(this.model.modes.column !== "middle" && this.model.modes.column !== "boundaries") { new_domain = this.expand_scale_domain(column_scale, this.model.columns, this.model.modes.column, col_start_aligned); if(d3.min(new_domain) < d3.min(column_scale.model.domain) || d3.max(new_domain) > d3.max(column_scale.model.domain)) { // Update domain if domain has changed column_scale.model.compute_and_set_domain(new_domain, column_scale.model.model_id); } } var row_plot_data = this.get_tile_plotting_data(row_scale, this.model.rows, this.model.modes.row, row_start_aligned); var column_plot_data = this.get_tile_plotting_data(column_scale, this.model.columns, this.model.modes.column, col_start_aligned); this.row_pixels = row_plot_data.start.map(function(d, i) { return [d, d + row_plot_data.widths[i]]; }) this.column_pixels = column_plot_data.start.map(function(d, i) { return [d, d + column_plot_data.widths[i]]; }) this.display_rows = this.d3el.selectAll(".heatmaprow") .data(_.range(num_rows)); this.display_rows.enter().append("g") .attr("class", "heatmaprow"); this.display_rows .attr("transform", function(d) { return "translate(0, " + row_plot_data.start[d] + ")"; }); var col_nums = _.range(num_cols); var row_nums = _.range(num_rows); var data_array = row_nums.map(function(row) { return col_nums.map(function(col) { return that.model.mark_data[row * num_cols + col]; }); }); this.display_cells = this.display_rows.selectAll(".heatmapcell").data(function(d, i) { return data_array[i]; }); this.display_cells.enter() .append("rect") .attr("class", "heatmapcell") .on("click", _.bind(function() { this.event_dispatcher("element_clicked"); }, this)); var stroke = this.model.get("stroke"); var opacity = this.model.get("opacity"); this.display_cells .attr({ "x": function(d, i) { return column_plot_data.start[i]; }, "y": 0 }) .attr("width", function(d, i) { return column_plot_data.widths[i]; }) .attr("height",function(d) { return row_plot_data.widths[d.row_num]; }) .style("fill", function(d) { return that.get_element_fill(d); }) .style({ "stroke": stroke, "opacity": opacity }); this.display_cells.on("click", function(d, i) { return that.event_dispatcher("element_clicked", { data: d.color, index: i, row_num: d.row_num, column_num: d.column_num }); }); },
}, function (cb) { console.log('generating SMGs'); async.forEach(_.range(1, smgCount + 1), function (smgId, cb) { async.series([ function (cb) { db.models.smg.create({ id: smgId, name: "name", description: DESC }, cb); }, function (cb) { async.forEach(testData.characteristic, function (characteristic, cb) { var values = { smg_id: smgId, characteristic_id: characteristic.id, valuetype_id: null, value: null, description: DESC }; if (characteristic.type_id === 1) { //checkbox values.value = randomCheckbox(); } if (characteristic.type_id === 2) { //number values.value = _.random(1, 1000) * 1000; } if (characteristic.type_id === 3 || characteristic.type_id === 4) { //piclist, radio values.valuetype_id = _.chain(testData.characteristicTypeValue) .filter(function (item) { return item.characteristic_id === characteristic.id; }) .sample() .value() .id; } if (characteristic.type_id === 5) { //text values.value = moniker.choose(); } if (characteristic.type_id === 6) { //textarea values.value = randomText(); } if (characteristic.type_id === 7) { //image values.value = 1; } db.models.smgCharacteristic.create(values, cb); }, cb); }, function (cb) { async.forEach(_.range(1, examplesPerSmg + 1), function (nr, cb) { db.models.example.create({ smg_id: smgId, name: moniker.choose(), type: _.sample(["type1", "type2", "type3", "type4"]), description: randomHtml() }, cb); }, cb); } ], cb); }, cb); }, function (cb) {
/* 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? */ var _ = require('underscore'); var gcd = function(m, n) { return n ? gcd(n ,m % n) : m; }; var lcm = function(m, n) { return m * n / gcd(m, n); }; console.log(_.range(1, 21).reduce(lcm));
async.eachSeries(_.range(settings.numberOfUsers), function(userNumber, callbackB){ async.eachSeries(_.range(settings.numberOfTestGroups), function(number, callbackC){ groupModel.assignUserToGroup(userIds[userNumber], groupIds[number], callbackC); }, callbackB); }, callback);
function castTestVotes(userId, postIds, vote, callback){ async.eachSeries(_.range(settings.numberOfTestVotes), function(number, callback){ userModel.castVote(userId, postIds[number], vote, callback); }, callback); }
Goban.prototype.range = function () { return _.range(0, this.get('size')); };
.map(function (x) { var indent = _(_.range(x.rank - lowestRank)) .reduce(function (acc, x) { return acc + '\t'; }, ''); return indent + '- ' + x.anchor; })
desc : 'description valeur 1', val : '+10', unit : '%', criteria: 0 }, { desc : 'description valeur 1', val : '+10', unit : '%', criteria: 1 } ] }; var pictos=['ion-leaf','ion-lightbulb','ion-bug','ion-film-marker','ion-trophy','ion-waterdrop','ion-bonfire','ion-earth','ion-umbrella']; var cl = ['engie-blueLight', 'engie-blue', 'engie-green', 'engie-yellow', 'engie-red', 'engie-purple', 'engie-pink']; var GardenItems = _.map( _.range(1, 10), function(num, key){ return _.extend(_.clone(GardenItem), { id : key, odr : key, name : 'Item' + key, price: 100 * key, picto: pictos[key], cl : cl[key % cl.length] }); }); var GardenIndicator = { id : 0, name_canonical: 'indicator', name : 'Indicator', picto : 'picto-1',
var table = require('./table.json'); var dynamodb = require('dynamodb-test')('dynamodb-migrator', table); var kinesis = require('kinesis-test')('dynamodb-migrator', 1); var _ = require('underscore'); var fs = require('fs'); var migration = require('..'); var fixtures = _.range(100).map(function(i) { return { id: i.toString(), data: 'base64:' + (new Buffer(i.toString())).toString('base64'), decoded: new Buffer(i.toString()) }; }); dynamodb.test('[index] live scan', fixtures, function(assert) { var active = 0; var gotLogger = false; function migrate(item, dyno, logger, callback) { active++; if (active > 10) assert.fail('surpassed concurrency'); assert.ok(dyno, 'received dyno'); assert.ok(item.id, 'one item'); assert.ok(Buffer.isBuffer(item.data), 'decoded base64 data'); logger.info(item.id); setTimeout(function() { active--; callback(); }, 300);
db.open(function(err, db) { if(!err) { log.info("Successful connect to mongodb"); log.info("Starting BrowserQuest game server..."); var storagedb = new StorageDB(db); server.onConnect(function(connection) { var world, // the one in which the player will be spawned connect = function() { if(world) { var player = new Player(connection, world, storagedb); world.connect_callback(player); } }; if(metrics) { metrics.getOpenWorldCount(function(open_world_count) { // choose the least populated world among open worlds world = _.min(_.first(worlds, open_world_count), function(w) { return w.playerCount; }); connect(); }); } else { // simply fill each world sequentially until they are full world = _.detect(worlds, function(world) { return world.playerCount < config.nb_players_per_world; }); world.updatePopulation(); connect(); } }); server.onError(function() { log.error(Array.prototype.join.call(arguments, ", ")); }); var onPopulationChange = function() { metrics.updatePlayerCounters(worlds, function(totalPlayers) { _.each(worlds, function(world) { world.updatePopulation(totalPlayers); }); }); metrics.updateWorldDistribution(getWorldDistribution(worlds)); }; _.each(_.range(config.nb_worlds), function(i) { var world = new WorldServer('world'+ (i+1), config.nb_players_per_world, server, storagedb); world.run(config.map_filepath); worlds.push(world); if(metrics) { world.onPlayerAdded(onPopulationChange); world.onPlayerRemoved(onPopulationChange); } }); server.onRequestStatus(function() { return JSON.stringify(getWorldDistribution(worlds)); }); if(config.metrics_enabled) { metrics.ready(function() { onPopulationChange(); // initialize all counters to 0 when the server starts }); } process.on('uncaughtException', function (e) { log.error('uncaughtException: ' + e); }); } else { log.error("cannot connect to mongodb", err); return; } });
var BACKGROUND_COLOR = '#FFFFFF'; //white var canvas = document.createElement('canvas'); canvas.setAttribute('height', HEIGHT); canvas.setAttribute('width', WIDTH); var context = canvas.getContext('2d'); context.fillStyle = BACKGROUND_COLOR; context.fillRect(0, 0, WIDTH, HEIGHT); var manager = new Manager(canvas); var opponent = new Opponent(canvas); var conn = new Connection(); //add ten circles _.each(_.range(10), function createCircles() { manager.addCircle(new Circle(canvas)); }); //add palyer manager.addPlayer(new Player(canvas, 100)); //attach tcp to opponent and manager conn.attachToOpponent(opponent); conn.attachToLocal(manager); //simulation loop var loop = raf(function tick(){ if (manager.ended) { return; }
describe('VertCatCol', function () { var vcc; var y = 0.2; var inc = 0.1; var row = { contents_fudge: _.map(_.range(0, 20, 1), function (p) { return new THREE.Vector2(p / 40, p / 40); }) }; // console.log('rows: %s', util.inspect(row)); before(function () { vcc = new c.VertCatCol(y, inc, row, {}); // console.log('vcc: %s', util.inspect(vcc)); }); it('should have min_y', function(){ vcc.min_y.should.eql(y); }); it('should have max_y', function(){ vcc.max_y.should.eql(y + inc ) }); it('should have min_y', function(){ vcc.min_y_fudge.should.eql(y - inc); }); it('should have max_y', function(){ vcc.max_y_fudge.should.eql(y + 2 *inc ) }); it('#contains', function () { vcc.contents.should.eql( [ { x: 0.2, y: 0.2 }, { x: 0.225, y: 0.225 }, { x: 0.25, y: 0.25 }, { x: 0.275, y: 0.275 }, { x: 0.3, y: 0.3 } ] ); vcc.contents_fudge.should.eql( [ { x: 0.1, y: 0.1 }, { x: 0.125, y: 0.125 }, { x: 0.15, y: 0.15 }, { x: 0.175, y: 0.175 }, { x: 0.2, y: 0.2 }, { x: 0.225, y: 0.225 }, { x: 0.25, y: 0.25 }, { x: 0.275, y: 0.275 }, { x: 0.3, y: 0.3 }, { x: 0.325, y: 0.325 }, { x: 0.35, y: 0.35 }, { x: 0.375, y: 0.375 } ] ); }); it('#closest', function(){ var test_point = new THREE.Vector2(0.225, 0.225); var closest = vcc.closest(test_point); closest.should.eql(test_point); var test_point2 = new THREE.Vector2(0.2255, 0.225); var closest2 = vcc.closest(test_point2); closest2.should.eql(closest); }); });
getValuesObject: function() { return _.isArray(this.values) ? _(_.range(1, this.values.length + 1)).object(this.values) : this.values; }
/** * @Function _.object * @des 数组转换成object 有意思 */ //两个一维数组 按顺序合并 length保证统一 var data_2x = _.object(['moe', 'larry', 'curly'], [30, 40, 50]); //data_2x => {moe: 30, larry: 40, curly: 50} //三个以为数组,每个length为2 形成object key - value对应 var data_3x = _.object([['moe', 30], ['larry', 40], ['curly', 50]]); //data_3x => {moe: 30, larry: 40, curly: 50} /** * @Function _.indexOf / _.lastIndexOf * @des 没啥说的 返回位置 */ /** * @Function _.sortedIndex(arr, value) * @des 二分查找法 返回value所处位置 */ /** * @Function _.range(min, max, sq) * @des 形成数组 sq为区间差距值 注意不包含max 但包含min */ var range = _.range(15, 25, 5); //range => [15, 20] console.log('_.range:' + range);
return _.map(_.range(cardinality), function(i) { return _.map(_.range(length), function(j) { return String.fromCharCode(Math.floor(i + 2 + j + 1)+65); }).join(''); });
/** * Created by megic on 2015-04-20. */ //var xlsx = require('node-xlsx'); //var obj = xlsx.parse(__dirname + '/data/mjf.xlsx'); // parses a file //console.log(obj[1]['data'].length); var _=require('underscore'); //穷举法 function getPermutation(arr) { if (arr.length == 1) { return [arr]; } var permutation = []; for (var i=0; i<arr.length; i++) { var firstEle = arr[i]; var arrClone = arr.slice(0); arrClone.splice(i, 1); var childPermutation = getPermutation(arrClone); for (var j=0; j<childPermutation.length; j++) { childPermutation[j].unshift(firstEle); } permutation = permutation.concat(childPermutation); } return permutation; } //穷举1-8个任务组合 var taskArr = getPermutation(_.range(8)); console.log(taskArr);
const betweenAiTeams = async () => { if (!g.aiTrades) { return; } const aiTids = _.range(g.numTeams).filter((i) => { return !g.userTids.includes(i); }); if (aiTids.length === 0) { return; } const tid = random.choice(aiTids); const otherTids = _.range(g.numTeams).filter((i) => { return i !== tid && !g.userTids.includes(i); }); if (otherTids.length === 0) { return; } const otherTid = random.choice(otherTids); const players = (await idb.getCopies.players({tid})).filter((p) => !isUntradable(p)); const draftPicks = await idb.cache.draftPicks.indexGetAll('draftPicksByTid', tid); if (players.length === 0 && draftPicks.length === 0) { return; } const r = Math.random(); const pids = []; const dpids = []; if (r < 0.33 || draftPicks.length === 0) { pids.push(random.choice(players).pid); } else if (r < 0.67 || players.length === 0) { dpids.push(random.choice(draftPicks).dpid); } else { pids.push(random.choice(players).pid); dpids.push(random.choice(draftPicks).dpid); } const teams0 = [{ tid, pids, dpids, }, { tid: otherTid, pids: [], dpids: [], }]; const teams = await makeItWork(teams0, false); if (teams === undefined) { return; } // Don't do trades of just picks, it's weird usually if (teams[0].pids.length === 0 && teams[1].pids.length === 0) { return; } // Don't do trades for nothing, it's weird usually if (teams[1].pids.length === 0 && teams[1].dpids.length === 0) { return; } const tradeSummary = await summary(teams); if (!tradeSummary.warning) { // Make sure this isn't a really shitty trade const dv2 = await team.valueChange(teams[0].tid, teams[1].pids, teams[0].pids, teams[1].dpids, teams[0].dpids); if (dv2 < -15) { return; } const finalTids = [teams[0].tid, teams[1].tid]; const finalPids = [teams[0].pids, teams[1].pids]; const finalDpids = [teams[0].dpids, teams[1].dpids]; await processTrade(tradeSummary, finalTids, finalPids, finalDpids); } };
*/ _.isEqual('a', 'b'); _.isEqual({x: 1}, {y: 2}); // Flow considers these compatible with isEqual(a: any, b: any). // Reasonable people disagree about whether these should be considered legal calls. // See https://github.com/splodingsocks/FlowTyped/pull/1#issuecomment-149345275 // and https://github.com/facebook/flow/issues/956 _.isEqual(1); _.isEqual(1, 2, 3); /** * _.range */ _.range(0, 10)[4] == 4 // $ExpectError string. This type is incompatible with number _.range(0, 'a'); // $ExpectError string cannot be compared to number _.range(0, 10)[4] == 'a'; /** * _.extend */ _.extend({a: 1}, {b: 2}).a _.extend({a: 1}, {b: 2}).b // $ExpectError property `c`. Property not found in object literal _.extend({a: 1}, {b: 2}).c
App.on('start', function () { var AppView = require('./common/views/AppView'); new Marionette.AppRouter({ routes: { '*default': function () { Backbone.history.navigate('timetable', {trigger: true, replace: true}); } } }); // navigation menu modules require('./timetable'); require('./modules'); require('./venues'); // require('./friends'); require('./nuswhispers'); require('./barenus'); require('./preferences'); require('./apps'); require('./blog'); require('./reddit'); // require('ivle'); // footer modules require('./about'); require('./contribute'); require('./help'); require('./support'); Promise.all(_.map(_.range(1, 5), function(semester) { var semTimetableFragment = config.semTimetableFragment(semester); return localforage.getItem(semTimetableFragment + ':queryString') .then(function (savedQueryString) { if ('/' + semTimetableFragment === window.location.pathname) { var queryString = window.location.search.slice(1); if (queryString) { if (savedQueryString !== queryString) { // If initial query string does not match saved query string, // timetable is shared. App.request('selectedModules', semester).shared = true; } // If there is a query string for timetable, return so that it will // be used instead of saved query string. return; } } var selectedModules = TimetableModuleCollection.fromQueryStringToJSON(savedQueryString); return Promise.all(_.map(selectedModules, function (module) { return App.request('addModule', semester, module.ModuleCode, module); })); }); }).concat([NUSMods.generateModuleCodes()])).then(function () { new AppView(); Backbone.history.start({pushState: true}); }); localforage.getItem(bookmarkedModulesNamespace, function (modules) { if (!modules) { localforage.setItem(bookmarkedModulesNamespace, []); } }); });
var _ = require('underscore'); var nox = require('../'); var zombieSpec = { hp: nox.rnd({min:10,max:20}), xp: nox.method({method: (o)=>{return(o.hp*1.5);}}) }; var zombieTemplate = nox.createTemplate("Zombie",zombieSpec); var zombies = _.map(_.range(10),(i) => { return nox.constructTemplate("Zombie"); }); _.each(zombies,(zombie)=>{ console.log(nox.deNox(zombie)); }); // For testing module.exports = { zombieSpec: zombieSpec, zombieTemplate: zombieTemplate, zombies: zombies, };
it('引数が1つめのinvoker関数に適応するとき1つ目の関数を実行する',function() { expect(str(_.range(10))).to.eql("0,1,2,3,4,5,6,7,8,9"); });
if (this.world.paused) return; var scale_factor = 1 / Math.pow(Math.E, (this.z / 5)); if (this.world) { this.move(-scale_factor, 0); } if (this.rect.x <= -100) { this.kill(); } } }); var AnimScrollable = Entity.extend({ animSpec: { normal: {frames: _.range(30), rate: 20, loop: true} }, initialize: function(options) { options = (options || {}); this.z = options.z || 0; this.world = options.world || null; if (options.spriteSheet){ this.spriteSheet = options.spriteSheet; this.anim = new animate.Animation(this.spriteSheet, "normal", this.animSpec); this.image = this.anim.update(0); this.anim.setFrame(0); } var scale_factor = 1 / Math.pow(Math.E, (this.z / 5));