Example #1
0
var projectReducer = function(state, action) {
	if(typeof state === 'undefined') {
		return {
            id: 0,
            people: [],
            pairingBoards: []
		};
	}

    switch (action.type) {
        case "LOAD_PROJECT":
            return action.project;
        case "MOVE_PERSON":
            var stateClone = _.cloneDeep(state);

            var fromPairingBoard = action.fromPairingBoardIndex >=0 ? stateClone.pairingBoards[action.fromPairingBoardIndex] : stateClone;
            var toPairingBoard = action.toPairingBoardIndex >=0 ? stateClone.pairingBoards[action.toPairingBoardIndex] : stateClone;

            toPairingBoard.people.push(_.pullAt(fromPairingBoard.people, action.personIndex)[0]);

            return stateClone;
        case "CREATE_PERSON":
            var stateClone = _.cloneDeep(state);

            stateClone.people.push({name: action.name});

            return stateClone;
        case "CREATE_PAIRING_BOARD":
            var stateClone = _.cloneDeep(state);

            stateClone.pairingBoards.push({name: action.name, people: []});

            return stateClone;
        case "DELETE_PERSON":
            var stateClone = _.cloneDeep(state);

            var pairingBoard = action.pairingBoardIndex >=0 ? stateClone.pairingBoards[action.pairingBoardIndex] : stateClone;
            _.pullAt(pairingBoard.people, action.personIndex);

            return stateClone;
        case "DELETE_PAIRING_BOARD":
            var stateClone = _.cloneDeep(state);

            stateClone.people = stateClone.people.concat(stateClone.pairingBoards[action.pairingBoardIndex].people);
            _.pullAt(stateClone.pairingBoards, action.pairingBoardIndex);

            return stateClone;
        case "RENAME_PAIRING_BOARD":
            var stateClone = _.cloneDeep(state);

            stateClone.pairingBoards[action.pairingBoardIndex].name = action.name;

            return stateClone;
        default:
            return state;
    }
};
Example #2
0
function compactObj(obj) {
	var length = _.keys(obj).length;
	var keys = _.keys(obj);
	var values = _.values(obj);
	var index = [];
	for (var i = 0; i < length; i++) {
		values[i] += '';
		if (values[i].length == 0) {
			index.push(i);
		}
	}
	_.pullAt(keys, index);
	_.pullAt(values, index);
	return _.zipObject(keys, values);
}
  deletePhoto: function() {
    	var self = this;

    	if (self.model.get('photos').length < 2)
        	return false;

    self.hasDeleted = true;

    var photoIndex = self.swiper.activeIndex;
    var photo = self.model.get('photos')[photoIndex];

    var fsFail = function(error) {
      console.log(error);
    };

    _.pullAt(self.model.get('photos'), photoIndex);
    self.model.save()
                .done(function() {
                  self.render();
                  if (window.cordova) {
                    	/* jshint ignore:start */
                    window.resolveLocalFileSystemURL(photo.url, function(fs) {
                      //1- Delete file mobile
                      fs.remove(function() {
                        //Dialog ?
                      }, fsFail);
                    }, fsFail);
                    /* jshint ignore:end */
                  }
                })
                .fail(function(error) {
                  console.log(error);
                });
  },
Example #4
0
KinesisStream.prototype._retryValidRecords = function(requestContent, err) {
  const self = this;

  // By default asumes that all records filed
  var failedRecords = requestContent.Records;

  // try to find within the error, whih records have fail.
  var failedRecordIndexes = getRecordIndexesFromError(err);

  if (failedRecordIndexes.length > 0) {

    // failed records found, extract them from collection of records
    failedRecords = _.pullAt(requestContent.Records, failedRecordIndexes);

    // now, try one more time with records that didn't fail.
    self._putRecords({
      StreamName: requestContent.StreamName,
      Records: requestContent.Records
    });
  }

  // send error with failed records
  err.streamName = requestContent.StreamName;
  err.records = failedRecords;
  self.emit('error', err);
};
Example #5
0
File: game.js Project: wmzy/tactic
  /**
   * 选择武将
   * @returns {Promise.<void>}
   */
  async choiceWarrior() {
    this.restWarriors = _.shuffle(Warrior.getNormalWarriors());
    // 主公开始选将
    // 主公可选武将包含两个普通武将
    const normalWarriorsForMonarch = cutArray(this.restWarriors, 2);
    this.candidateWarriorsForMonarch = Warrior.getMonarchWarriors().concat(normalWarriorsForMonarch);
    const index = await this.request(
      new Request('game.monarchChoiceWarrior')
        .to(this.players[0], {warriors: this.candidateWarriorsForMonarch})
    );
    this.players[0].warrior = this.candidateWarriorsForMonarch[index];
    _.pullAt(this.candidateWarriorsForMonarch, index);
    this.restWarriors = _.shuffle(this.restWarriors.concat(this.candidateWarriorsForMonarch));

    const req = new Request('game.choiceWarrior');
    this.players.slice(1).forEach(player =>
      req.to(player, {warriors: cutArray(this.restWarriors, player.role === 'traitor' ? 6 : 3)})
    );
    const indexes = await this.waitAllResponse(req);
    _.forEach(req.toPlayers, (to, i) => {
      to.player[0].warrior = to.payload.warriors[indexes[i]];
      _.pullAt(to.payload.warriors, indexes[i]);
      this.restWarriors = this.restWarriors.concat(to.payload.warriors);
    });
  }
                        _.each(_.sortBy(currentTable.divisions, function(division) {return division.rank}), function(division) {
                            var scores = [],
                                usersDemoted = 0,
                                currentRank = division.rank;

                            index++;
                            _.each(division.users, function(user) {
                                if (user.state !== "ACTIVE") {
                                    usersDemoted++;
                                } else {
                                    var score = _this.calculateUserScore(user, division.scores);
                                    scores.push({score: score, user: user});
                                }
                            });

                            scores = _.sortBy(scores, function(score) {return score.score}).reverse();

                            //Promotion
                            if (currentRank != 0) {
                                var usersToBePromoted =  DIVISION_SIZE - rankToUser[currentRank - 1].length;
                                for (var i = 0; i < usersToBePromoted; i++) {
                                    _this.addRankToScore(rankToUser, currentRank - 1, scores[0].user);
                                    _.pullAt(scores, 0);
                                }


                            }

                            //Demotion
                            if (usersDemoted <= 2 && index != currentTable.divisions.length) {
                                if (usersDemoted <= 1) {
                                    _this.addRankToScore(rankToUser, currentRank + 1, scores[scores.length - 1].user);
                                    _.pullAt(scores, scores.length - 1);
                                }
                                if (usersDemoted == 0) {
                                    _this.addRankToScore(rankToUser, currentRank + 1, scores[scores.length - 1].user);
                                    _.pullAt(scores, scores.length - 1);
                                }
                            }

                            //Remain
                            _.each(scores, function(score) {
                                _this.addRankToScore(rankToUser, currentRank, score.user);
                            });

                        });
 function (cb) {
   let index                 = _.random(0, props.length - 1);
   let p                     = _.pullAt(props, [index]);
   p[0].pricelist.priceRange = priceRange % 6;
   priceRange++;
   generated++;
   properties.updateProperty(gameId, p[0], cb);
 },
Example #8
0
app.delete('/lions/:id', function (req, res){
  var del = _.findIndex(lions, {id:req.params.id});
  if (!lions[del]){
    res.send();
  }
  else {
    res.send(_.pullAt(lions, del)[0]);
  }
});
Example #9
0
app.delete('/lions/:id', function(req, res) {
  var lion = _.findIndex(lions, {id: req.params.id});
  if (!lions[lion]) {
    res.send();
  } else {
    var deletedLion = _.pullAt(lions, lion)[0];
    res.send(deletedLion);
  }
});
Example #10
0
 queue.remove = function (qid) {
   var f = _.findIndex(queue.q, ['qid', qid]);
   if (f > -1) {
     _.pullAt(queue.q, f);
     _domainManager.emitEvent("eqFTP", "event", {
       action: 'queue:update',
       data: eqftp.queue.get()
     });
   }
 };
Example #11
0
 }, function(err, data) {
   if (data) {
     if (data.state === 1000) {
       _.pullAt(todoContent.list, [tag]);
       reloadData();
     } else {
       // alert fail
       toastr['warning']('删除失败');
     }
   }
 });
Example #12
0
 }).then(json=> {
     log("json", json)
     if (json.status.toLowerCase() == "ok") {
         _this.context.showMessage("Question set deleted.", 1000);
         _.pullAt(originalData, [deletingSetId]);
         _this.createTable(originalData);
     }
     else {
         _this.context.showMessage("Question set deleting fail!", 1000);
     }
 }).catch(err=> {
Example #13
0
function deleteActionOperationInvocationDetails(swagger, operationId) {
  console.log('deleteActionOperationInvocationDetails: deleting case entry for ' + operationId);
  var caseArr = _.get(swagger, 'x-ibm-configuration.assembly.execute[0].operation-switch.case') || [];
  if (caseArr.length > 0) {
    var caseIdx = getCaseOperationIdx(caseArr, operationId);
    _.pullAt(caseArr, caseIdx);
    _.set(swagger, 'x-ibm-configuration.assembly.execute[0].operation-switch.case', caseArr);
  } else {
    console.log('deleteActionOperationInvocationDetails: empty case[] array; case operation '+operationId+' does not exist');
  }
}
Example #14
0
function shuffleArray(data,deleteIndexs){

	if (_.isArray(data) && _.isArray(deleteIndexs)) {
		var countData = data.length;
		var countFilter = deleteIndexs.length;
		if (countData >= countFilter && countData > _.max(deleteIndexs)) {
			_.pullAt(data,deleteIndexs);
			return data;
		}
	}
	return false;
}
Example #15
0
// filter array values
//eg: filter:[1,2,4] will get (data[1],data[2],data[4])
function filterArray(data, filters) {

	if (_.isArray(data) && _.isArray(filters)) {
		var countData = data.length;
		var countFilter = filters.length;
		if (countData >= countFilter && countData > _.max(filters)) {
			filters.sort();
			return _.pullAt(data,filters);
		}
	}
	return false;
}
Example #16
0
  Round.prototype.setTable = function(value,player){
    var encontrado = false;
      if(player == 'player1'){
        var card = new Card (this.returnNumber(value),this.returnSuit(value));
        var aux = undefined;
        var i = 0;
        while (i < _.size(this.game.player1.cards)){
          if(this.game.player1.cards[i].number == card.number && this.game.player1.cards[i].suit == card.suit){
            aux = i;
            encontrado = true;
            this.tablep1.push(card);        
          }
          i++;
        }
        console.log("posicion de la carta " + aux);

        if(aux!=undefined){ 
          _.pullAt(this.game.player1.cards, [aux]);
        }
      }
      if(player == 'player2'){
        var card = new Card (this.returnNumber(value),this.returnSuit(value));
        var aux = undefined;
        var i = 0;
        while (i < _.size(this.game.player2.cards)){
          if(this.game.player2.cards[i].number == card.number && this.game.player2.cards[i].suit == card.suit){
            aux = i;
            encontrado=true;
            this.tablep2.push(card);            
          }
          i++;
        }

        console.log("posicion de la carta " + aux);
        if(aux!=undefined){
          _.pullAt(this.game.player2.cards, [aux]);
        }
      }
      
  }  
Example #17
0
	this.delJob = function(idx) {
		if (this.jobs[idx].job instanceof schedule.Job) {
			if (this.jobs[idx].job.cancel()) {
				log.info('Delete job at ' + idx + ' successfully');
			} else {
				log.error('Error deleting job at ' + idx);
			}
		} else {
			log.warn('Removed a job that wasn\'t a Job');
		}
		_.pullAt(this.jobs, idx);
		this.store.put('jobs', this.jobs);
	}
Example #18
0
        }, function (err, people) {
          if (err) {
            return res.status(500).send("Unable to get friends' games");
          }
          people.push(me); // add self to friends array

          // convert list of people into list of games
          var games = _.flatten(_.map(people, function (person) {
            person.games = _.map(person.games, function (game) {
              var gameObject = {
                //TODO: this doesn't work for some reason
                //title: '<a href="http://store.steampowered.com/app/' + game.appid + '/" target="_blank">' + game.name + '</a>',
                title: game.name,
                personaName: person.personaname
              };
              gameObject.Me = 0;
              for (var i = 0; i < friendList.length; i++) {
                gameObject[friendList[i].personaname] = 0
              }
              gameObject[person.personaname] = Math.round(game.playtime_2weeks / 0.6) / 100;
              return gameObject;
            });
            return person.games;
          }));

          // sort by title
          games.sort(function (a, b) {
            return (a.title > b.title) ? 1 : ((b.title > a.title) ? -1 : 0);
          });

          // remove duplicates
          for (var i = 0; i < games.length - 1; i++) {
            while (games[i].title === games[i + 1].title) {
              var newName = games[i + 1].personaName;
              games[i][newName] = games[i + 1][newName];
              _.pullAt(games, i + 1);
            }
            games[i] = _.omit(games[i], 'personaName');
            games[i+1] = _.omit(games[i+1], 'personaName');
          }

          // create a first row with all people
          var firstRow = {};
          firstRow.Me = 0;
          for (var j = 0; j < friendList.length; j++) {
            firstRow[friendList[j].personaname] = 0
          }
          games.unshift(firstRow);
          res.json(games)

        })
Example #19
0
 }, function(err, data) {
   if (data) {
     if (data.state === 1000) {
       if (filterIndex === '1' || filterIndex === '2') {
         _.pullAt(todoContent.list, [tag]);
       } else {
         todoContent.list[tag].completed = completed;
       }
       reloadData();
     } else {
       toastr['warning']('标记任务完成失败');
     }
   }
 });
Example #20
0
const unset = (object, path) => {
  const pathArray = _.toPath(path);
  const leavePath = pathArray.pop();

  // remove from array
  if (pathArray.length) {
    const parent = _.get(object, pathArray);
    if (_.isArray(parent)) {
      return _.pullAt(parent, leavePath);
    }
  }

  return _.unset(object, path);
};
Example #21
0
// Reducer for users in the chat room
function users(state = defaultUsersState, action) {
  let newData, idx;
  switch (action.type) {
    case ActionTypes.JOIN_ROOM.LOADING:
      return {
        ...state,
        isLoading: true
      };
      
    case ActionTypes.JOIN_ROOM.SUCCESS:
      newData = sortBy(uniqBy([ ...state.data, ...action.payload.users ], 'userId'), [ 'firstName', 'lastName' ]);
      return {
        ...state,
        isLoading: false,
        data: newData
      };
    
    case ActionTypes.LEAVE_ROOM:  
    case ActionTypes.JOIN_ROOM.FAILURE:
      return defaultUsersState;
    
    case ActionTypes.USER_JOINED.SUCCESS:
      idx = findIndex(state.data, { userId: action.payload.userId });
      if (idx === -1) {
        newData = sortBy([ ...state.data, action.payload ], [ 'firstName', 'lastName' ]);
        return {
          ...state,
          data: newData
        };
      }
      
      
    case ActionTypes.USER_LEFT.SUCCESS:
      idx = findIndex(state.data, { userId: action.payload.userId });
      if (idx !== -1) {
        newData = [ ...state.data ];
        pullAt(newData, idx);
        return {
          ...state,
          data: newData
        };
      }
  }
  
  return state;
}
Example #22
0
 ajaxHandler.request("POST", "/items/deleteComplete", null, function(err, data) {
   if (data) {
     if (data.state === 1000) {
       var deleteIndexs = [];
       for (var i = 0; i < todoContent.list.length; i++) {
         var completed = todoContent.list[i].completed;
         if (completed === true) {
           deleteIndexs.push(i);
         }
       }
       _.pullAt(todoContent.list, deleteIndexs);
       reloadData();
     } else {
       toastr['warning']('删除已完成全部任务 失败');
     }
   }
 });
Example #23
0
    _processAwaitingSuites: function(browser) {
        var suites = this.awaiting[browser],
            complete = [];

        if (!suites) {
            return;
        }

        _.forEachRight(suites, function(suite, i) {
            if (_.every(suite.children, this._isCompletedInBrowser.bind(this, browser))) {
                this._markAsCompleted(suite, browser);
                this.emit(RunnerEvents.END_SUITE, {suite: suite, browserId: browser});
                complete.push(i);
            }
        }.bind(this));

        _.pullAt(suites, complete);
    },
Example #24
0
/**
 *
 * @param {Number} A
 * @param {Number} B
 * @param {Number} sim
 * @returns {Array}
 */
function scoreUpdate(A, B, sim) {
  const update = [];
  if (!sim) return update;

  for (let [a, b] of [[A, B], [B, A]]) {
    let index = _.findIndex(items[a].r, {0: b});
    index > -1 && _.pullAt(items[a].r, index);

    if (sim >= MIN_SIMILARITY) {
      index = _.sortedIndexBy(items[a].r, [b, sim], 1);
      items[a].r.splice(index, 0, [b, sim]);
      update.push(['ZADD', `r:${a}`, sim, b]);
    } else {
      update.push(['ZREM', `r:${a}`, b]);
    }
  }
  return update;
}
Example #25
0
var clearNamespaces = function() {
  var namespacesKey = PREFIX + SEP + SEP + 'namespaces';
  var namespaces = JSON.parse(localStorage.getItem(namespacesKey));
  if (!_.isArray(namespaces)) namespaces = [];
  for (var i = 0; i < namespaces.length; i++) {
    var namespace = namespaces[i];
    var prefix = PREFIX + SEP + namespace + SEP;
    var key = prefix + SEP + 'ts';
    var timestamp = Number(localStorage.getItem(key));
    if (timestamp + NAMESPACE_TIMEOUT < Date.now()) {
      var storage = new NamespacedStorage(namespace);
      storage.clear();
      _.pullAt(namespaces, i);
      i--;
      localStorage.setItem(namespacesKey, JSON.stringify(namespaces));
    }
  };
};
Example #26
0
  renderInput = (props, key) => {
    const Input = this.inputs[props.type];
    const inputValue = this.props.values[props.target];
    // retrieve options for the select input
    const selectOptions = props.type === 'enum' || props.type === 'select' ? props.items : [];

    // custom check for dynamic keys used for databases
    const dynamicTarget = join(pullAt(split(props.target, '.'),['0', '1', '3', '4']), '.');

    // check if the input has a nested form so it is displayed on the entire line
    const customBootstrapClass = this.state.hasNestedInput ?
      // bootstrap class to make the input displayed on the entire line
      'col-md-6 offset-md-6 mr-md-5' :
      // if the input hasn't a nested form but the config requires him to be displayed differently
      config[props.target] || config[dynamicTarget] || '';

    // custom handleChange props for nested input form
    const handleChange = this.state.hasNestedInput ? this.handleChange :  this.props.onChange;
    let hiddenLabel = includes(props.name, 'enabled');

    if (includes(config.showInputLabel, props.name)) hiddenLabel = false;

    const errorIndex = findIndex(this.props.formErrors, ['target', props.target]);
    const errors = errorIndex !== -1 ? this.props.formErrors[errorIndex].errors : [];

    return (
      <Input
        customBootstrapClass={customBootstrapClass}
        key={key}
        handleChange={handleChange}
        name={props.name}
        target={props.target}
        isChecked={inputValue}
        selectOptions={selectOptions}
        validations={props.validations}
        value={inputValue}
        addRequiredInputDesign={this.props.addRequiredInputDesign}
        hiddenLabel={hiddenLabel}
        inputDescription={props.description}
        errors={errors}
      />
    );
  }
GraphManager.prototype.RemoveNode = function(node) {
    // This look convoluted, but all it is is removing edges in place rather than creating a new array
    var index = _.findIndex(this.edges, function(edge) {
        return edge.start === node || edge.end === node;
    });

    while(index >= 0) {
        _.pullAt(this.edges, index);

        index = _.findIndex(this.edges, function(edge) {
            return edge.start === node || edge.end === node;
        });
    }

    _.pull(this.nodes, node);

    fv.Renderer.Update();

    fv.emit('node-removed', node);
    return node;
};
Example #28
0
 var finisher = function (err, data) {
   debug('firing finisher');
   var i = _.findIndex(queue.q, {qid: queuer.qid});
   if (i > -1) {
     queuer = (_.pullAt(queue.q, i))[0];
     _.set(eqftp.cache, ['queue', id], queue.q);
     if (err) {
       queuer.queue = 'f';
       queuer.err = err;
       queue.add(queuer, true);
     }
   }
   queue.isBusy = false;
   if (!err) {
     _domainManager.emitEvent("eqFTP", "event", {
       action: 'queue:update',
       data: eqftp.queue.get()
     });
   }
   queue.next();
   callback(err, data);
 };
/**
 * @param {string} term
 * @param {Array} packages
 * @param {object} [specificPackage]
 * @returns {Array}
 */
function sortSearchResultsWithTerm(term, packages, specificPackage) {
  const pulled = [],
    exactTerm = [],
    includesTerm = [],
    recommended = [];

  _.each(packages, (packageInfo, index) => {
    const name = packageInfo.name;

    if (name === term) {
      pulled.push(index);

      if (!specificPackage) {
        exactTerm.push(packageInfo);
      }
    } else if (_.includes(recommendedPackages, name)) {
      pulled.push(index);
      recommended.push(_.assign({recommended: true}, packageInfo));
    } else if (_.includes(name, term)) {
      pulled.push(index);
      includesTerm.push(packageInfo);
    }
  });

  _.pullAt(packages, pulled);

  if (specificPackage) {
    exactTerm.push(specificPackage);
  }

  if (exactTerm.length && _.includes(recommendedPackages, exactTerm[0].name)) {
    _.assign(exactTerm[0], {recommended: true});
  }

  return exactTerm.concat(recommended, includesTerm, packages);
}
Example #30
0
 $scope.removeCell = function (index) {
   _.pullAt($scope.state.sheet, index);
   $scope.safeSearch();
 };