Example usage for org.apache.commons.lang3.tuple Pair getValue

List of usage examples for org.apache.commons.lang3.tuple Pair getValue

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getValue.

Prototype

@Override
public R getValue() 

Source Link

Document

Gets the value from this pair.

This method implements the Map.Entry interface returning the right element as the value.

Usage

From source file:com.quancheng.saluki.registry.consul.ConsulRegistry.java

@Override
protected synchronized void doSubscribe(GrpcURL url, NotifyListener.NotifyServiceListener listener) {
    Pair<GrpcURL, Set<NotifyListener.NotifyServiceListener>> listenersPair = notifyServiceListeners
            .get(url.getServiceKey());//from w  w w  .ja v a2  s  .  c  o  m
    if (listenersPair == null) {
        Set<NotifyListener.NotifyServiceListener> listeners = Sets.newConcurrentHashSet();
        listeners.add(listener);
        listenersPair = new ImmutablePair<GrpcURL, Set<NotifyListener.NotifyServiceListener>>(url, listeners);
    } else {
        listenersPair.getValue().add(listener);
    }
    notifyServiceListeners.putIfAbsent(url.getServiceKey(), listenersPair);
    if (!serviceGroupLookUped.contains(url.getGroup())) {
        serviceGroupLookUped.add(url.getGroup());
        ServiceLookUper serviceLookUper = new ServiceLookUper(url.getGroup());
        serviceLookUper.setDaemon(true);
        serviceLookUper.start();
        ConsulEphemralNode ephemralNode = this.buildEphemralNode(url, ThrallRoleType.CONSUMER);
        client.registerEphemralNode(ephemralNode);
    } else {
        notifyListener(url, listener);
    }
}

From source file:com.act.lcms.db.analysis.FeedingAnalysis.java

private static void performFeedingAnalysis(DB db, String lcmsDir, String searchIon, String searchMassStr,
        String plateBarcode, String strainOrConstruct, String extract, String feedingCondition,
        String outPrefix, String fmt) throws SQLException, Exception {
    Plate p = Plate.getPlateByBarcode(db, plateBarcode);
    if (p == null) {
        throw new RuntimeException(String.format("Unable to find plate with barcode %s", plateBarcode));
    }/* w  ww.  j  a  v  a 2s .c o m*/
    if (p.getContentType() != Plate.CONTENT_TYPE.FEEDING_LCMS) {
        throw new RuntimeException(String.format("Plate with barcode %s is not a feeding plate (%s)",
                plateBarcode, p.getContentType()));
    }
    List<FeedingLCMSWell> allPlateWells = FeedingLCMSWell.getInstance().getFeedingLCMSWellByPlateId(db,
            p.getId());
    if (allPlateWells == null || allPlateWells.size() == 0) {
        throw new RuntimeException(
                String.format("No feeding LCMS wells available for plate %s", p.getBarcode()));
    }

    List<FeedingLCMSWell> relevantWells = new ArrayList<>();
    for (FeedingLCMSWell well : allPlateWells) {
        if (!well.getMsid().equals(strainOrConstruct) && !well.getComposition().equals(strainOrConstruct)) {
            // Ignore wells that don't have the right strain/construct (though we assume the whole plate shares one).
            continue;
        }

        if (!well.getExtract().equals(extract)) {
            // Filter by extract.
            continue;
        }

        if (!well.getChemical().equals(feedingCondition)) {
            // Filter by fed chemical.
            continue;
        }

        relevantWells.add(well);
    }

    Collections.sort(relevantWells, new Comparator<FeedingLCMSWell>() {
        @Override
        public int compare(FeedingLCMSWell o1, FeedingLCMSWell o2) {
            // Assume concentration is never null.
            return o1.getConcentration().compareTo(o2.getConcentration());
        }
    });

    Map<FeedingLCMSWell, ScanFile> wellsToScanFiles = new HashMap<>();
    Set<String> constructs = new HashSet<>(1);
    for (FeedingLCMSWell well : relevantWells) {
        List<ScanFile> scanFiles = ScanFile.getScanFileByPlateIDRowAndColumn(db, well.getPlateId(),
                well.getPlateRow(), well.getPlateColumn());
        if (scanFiles == null || scanFiles.size() == 0) {
            System.err.format("WARNING: no scan files for well at %s %s\n", p.getBarcode(),
                    well.getCoordinatesString());
            continue;
        }
        if (scanFiles.size() > 1) {
            System.err.format("WARNING: found multiple scan files for %s %s, using first\n", p.getBarcode(),
                    well.getCoordinatesString());
        }
        while (scanFiles.size() > 0 && scanFiles.get(0).getFileType() != ScanFile.SCAN_FILE_TYPE.NC) {
            scanFiles.remove(0);
        }
        if (scanFiles.size() == 0) {
            System.err.format("WARNING: no scan files with valid format for %s %s\n", p.getBarcode(),
                    well.getCoordinatesString());
            continue;
        }
        // All of the extracted wells should be unique, so there should be no collisions here.
        wellsToScanFiles.put(well, scanFiles.get(0));
        constructs.add(well.getComposition());
    }

    Pair<String, Double> searchMass = null;
    if (searchMassStr != null) {
        searchMass = Utils.extractMassFromString(db, searchMassStr);
    }
    if (searchMass == null) {
        if (constructs.size() != 1) {
            throw new RuntimeException(String.format(
                    "Found multiple growth targets for feeding analysis when no mass specified: %s",
                    StringUtils.join(constructs, ", ")));
        }
        String constructName = constructs.iterator().next();
        CuratedChemical cc = Utils.extractTargetForConstruct(db, constructName);
        if (cc == null) {
            throw new RuntimeException(
                    String.format("Unable to find curated chemical for construct %s", constructName));
        }
        System.out.format("Using target %s of construct %s as search mass (%f)\n", cc.getName(), constructName,
                cc.getMass());
        searchMass = Pair.of(cc.getName(), cc.getMass());
    }

    MS1 c = new MS1();
    // TODO: use configurable or scan-file derived ion mode. Do it the way its done in:
    // https://github.com/20n/act/blob/d997e84f0f44a5c88a94ef935829cb47e0ca8d1a/reachables/src/main/java/com/act/lcms/db/analysis/AnalysisHelper.java#L79
    MS1.IonMode mode = MS1.IonMode.valueOf("POS");
    Map<String, Double> metlinMasses = c.getIonMasses(searchMass.getValue(), mode);

    if (searchIon == null || searchIon.isEmpty()) {
        System.err.format("No search ion defined, defaulting to M+H\n");
        searchIon = DEFAULT_ION;
    }

    List<Pair<Double, MS1ScanForWellAndMassCharge>> rampUp = new ArrayList<>();
    for (FeedingLCMSWell well : relevantWells) {
        ScanFile scanFile = wellsToScanFiles.get(well);
        if (scanFile == null) {
            System.err.format("WARNING: no scan file available for %s %s", p.getBarcode(),
                    well.getCoordinatesString());
            continue;
        }
        File localScanFile = new File(lcmsDir, scanFile.getFilename());
        if (!localScanFile.exists() && localScanFile.isFile()) {
            System.err.format("WARNING: could not find regular file at expected path: %s\n",
                    localScanFile.getAbsolutePath());
            continue;
        }
        System.out.format("Processing scan data at %s\n", localScanFile.getAbsolutePath());

        MS1ScanForWellAndMassCharge ms1ScanCache = new MS1ScanForWellAndMassCharge();
        MS1ScanForWellAndMassCharge ms1ScanResults = ms1ScanCache
                .getByPlateIdPlateRowPlateColUseSnrScanFileChemical(db, p, well, true, scanFile,
                        searchMass.getKey(), metlinMasses, localScanFile);

        Double concentration = well.getConcentration();
        rampUp.add(Pair.of(concentration, ms1ScanResults));
    }

    WriteAndPlotMS1Results plotFeedingsResults = new WriteAndPlotMS1Results();
    plotFeedingsResults.plotFeedings(rampUp, searchIon, outPrefix, fmt, outPrefix + ".gnuplot");
}

From source file:com.trenako.web.tags.BreadcrumbTags.java

private void addElement(List<HtmlTag> items, String contextPath, Criteria criterion) {
    Pair<String, String> crit = getCriteria().get(criterion);
    if (crit == null)
        return;// w  ww  .j  a  va 2  s  .c  om

    String criteriaName = criterion.criterionName();

    String path = new StringBuilder().append("/rs/").append(criteriaName).append("/").append(crit.getKey())
            .toString();

    String label = messageSource.getMessage("breadcrumb." + criteriaName + ".label", null, criteriaName, null);
    String title = messageSource.getMessage("breadcrumb." + criteriaName + ".title.label", null, criteriaName,
            null);

    items.add(snippet(li(plain(label + " "), span("/").cssClass("divider")).cssClass("active"),

            li(a(crit.getValue()).href(contextPath, path).title(title), plain(" "),
                    span("/").cssClass("divider"))));
}

From source file:com.nextdoor.bender.operation.substitution.formatted.FormattedSubstitution.java

@Override
protected void doSubstitution(InternalEvent ievent, DeserializedEvent devent, Map<String, Object> nested) {
    Object[] values = new Object[this.variables.size()];
    List<String> keyToRemove = new ArrayList<String>();

    for (int i = 0; i < this.variables.size(); i++) {
        Variable<?> variable = this.variables.get(i);

        /*//from  ww w  .j  a  va  2 s.c  o  m
         * Get values
         */
        if (variable instanceof Variable.FieldVariable) {
            Pair<String, Object> kv = null;
            try {
                kv = getFieldAndSource(devent, ((Variable.FieldVariable) variable).getSrcFields(), true);

                if (((Variable.FieldVariable) variable).getRemoveSrcField()) {
                    keyToRemove.add(kv.getKey());
                }
            } catch (FieldNotFoundException e) {
                if (((Variable.FieldVariable) variable).getFailSrcNotFound()) {
                    throw new OperationException(e);
                }
            }

            if (kv != null) {
                values[i] = kv.getValue();
            } else {
                /*
                 * This handles the case of when fail src not found is false
                 */
                values[i] = null;
            }
        } else if (variable instanceof Variable.StaticVariable) {
            values[i] = ((Variable.StaticVariable) variable).getValue();
        }
    }

    /*
     * Format string with values
     */
    String formatted = format.format(values);

    /*
     * Perform substitution
     */
    if (nested != null) {
        nested.put(this.key, formatted);
        keyToRemove.forEach(fieldName -> {
            if (fieldName.equals(this.key)) {
                return;
            }
            try {
                devent.removeField(fieldName);
            } catch (FieldNotFoundException e) {
            }
        });
        return;
    }

    try {
        devent.setField(this.key, formatted);
    } catch (FieldNotFoundException e) {
        if (this.failDstNotFound) {
            throw new OperationException(e);
        }
    }

    /*
     * Remove source fields
     */
    keyToRemove.forEach(fieldName -> {
        if (fieldName.equals(this.key)) {
            return;
        }
        try {
            devent.removeField(fieldName);
        } catch (FieldNotFoundException e) {
        }
    });
}

From source file:com.nttec.everychan.chans.sich.SichModule.java

@Override
public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception {
    UrlPageModel urlModel = new UrlPageModel();
    urlModel.chanName = CHAN_NAME;//from  ww  w  . j ava  2s.c o m
    urlModel.boardName = model.boardName;
    if (model.threadNumber == null) {
        urlModel.type = UrlPageModel.TYPE_BOARDPAGE;
        urlModel.boardPage = UrlPageModel.DEFAULT_FIRST_PAGE;
    } else {
        urlModel.type = UrlPageModel.TYPE_THREADPAGE;
        urlModel.threadNumber = model.threadNumber;
    }
    String referer = buildUrl(urlModel);
    List<Pair<String, String>> fields = VichanAntiBot.getFormValues(referer, task, httpClient);

    if (task != null && task.isCancelled())
        throw new Exception("interrupted");

    ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create()
            .setCharset(Charset.forName("UTF-8")).setDelegates(listener, task);
    for (Pair<String, String> pair : fields) {
        if (pair.getKey().equals("spoiler"))
            continue;
        String val;
        switch (pair.getKey()) {
        case "subject":
            val = model.subject;
            break;
        case "body":
            val = model.comment;
            break;
        case "password":
            val = model.password;
            break;
        default:
            val = pair.getValue();
        }
        int i = 1;
        String fileNo;
        switch (pair.getKey()) {
        case "file":
        case "file2":
        case "file3":
        case "file4":
            fileNo = pair.getKey().replaceAll("[\\D]", "");
            if (fileNo != "") {
                i = Integer.parseInt(fileNo);
            }
            if (model.attachments == null || model.attachments.length < i) {
                postEntityBuilder.addPart(pair.getKey(), new ByteArrayBody(new byte[0], ""));
            } else {
                postEntityBuilder.addFile(pair.getKey(), model.attachments[i - 1], model.randomHash);
            }
            break;
        default:
            postEntityBuilder.addString(pair.getKey(), val);
        }
    }

    String url = getUsingUrl() + "post.php";
    Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, referer) };
    HttpRequestModel request = HttpRequestModel.builder().setPOST(postEntityBuilder.build())
            .setCustomHeaders(customHeaders).setNoRedirect(true).build();
    HttpResponseModel response = null;
    try {
        response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, listener, task);
        if (response.statusCode == 200 || response.statusCode == 400) {
            ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
            IOUtils.copyStream(response.stream, output);
            String htmlResponse = output.toString("UTF-8");
            Matcher errorMatcher = ERROR_PATTERN.matcher(htmlResponse);
            if (errorMatcher.find())
                throw new Exception(errorMatcher.group(1));
        } else if (response.statusCode == 303) {
            for (Header header : response.headers) {
                if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) {
                    return fixRelativeUrl(header.getValue());
                }
            }
        }
        throw new Exception(response.statusCode + " - " + response.statusReason);
    } finally {
        if (response != null)
            response.release();
    }
}

From source file:forge.screens.match.CMatchUI.java

public void updateZones(List<Pair<PlayerView, ZoneType>> zonesToUpdate) {
    //System.out.println("updateZones " + zonesToUpdate);
    for (Pair<PlayerView, ZoneType> kv : zonesToUpdate) {
        PlayerView owner = kv.getKey();//  w  w  w. j  a v a2 s  .  co m
        ZoneType zt = kv.getValue();

        switch (zt) {
        case Battlefield:
            getFieldViewFor(owner).getTabletop().setupPlayZone();
            break;
        case Hand:
            VHand vHand = getHandFor(owner);
            if (vHand != null) {
                vHand.getLayoutControl().updateHand();
            }
            getFieldViewFor(owner).getDetailsPanel().updateZones();
            FloatingCardArea.refresh(owner, zt);
            break;
        case Command:
            getCommandFor(owner).getTabletop().setupPlayZone();
            break;
        case Ante:
            CAntes.SINGLETON_INSTANCE.update();
            break;
        default:
            final VField vf = getFieldViewFor(owner);
            if (vf != null) {
                vf.getDetailsPanel().updateZones();
            }
            FloatingCardArea.refresh(owner, zt);
            break;
        }
    }
}

From source file:com.galenframework.speclang2.pagespec.PageSectionProcessor.java

private Pair<PageRule, Map<String, String>> findAndProcessRule(String ruleText, StructNode ruleNode) {
    ListIterator<Pair<Rule, PageRule>> iterator = pageSpecHandler.getPageRules()
            .listIterator(pageSpecHandler.getPageRules().size());
    /*//  w  w  w  .  j a v  a2  s  . co  m
    It is important to make a reversed iteration over all rules so that
    it is possible for the end user to override previously defined rules
     */

    while (iterator.hasPrevious()) {
        Pair<Rule, PageRule> rulePair = iterator.previous();
        Matcher matcher = rulePair.getKey().getPattern().matcher(ruleText);
        if (matcher.matches()) {
            int index = 1;

            Map<String, String> parameters = new HashMap<>();

            for (String parameterName : rulePair.getKey().getParameters()) {
                String value = matcher.group(index);
                pageSpecHandler.setGlobalVariable(parameterName, value, ruleNode);

                parameters.put(parameterName, value);
                index += 1;
            }

            return new ImmutablePair<>(rulePair.getValue(), parameters);
        }
    }
    throw new SyntaxException(ruleNode, "Couldn't find rule matching: " + ruleText);
}

From source file:lineage2.gameserver.network.clientpackets.EnterWorld.java

/**
 * Method runImpl.//from   w w  w  .  java  2  s. c  om
 */
@Override
protected void runImpl() {
    GameClient client = getClient();
    Player activeChar = client.getActiveChar();
    if (activeChar == null) {
        client.closeNow(false);
        return;
    }
    int MyObjectId = activeChar.getObjectId();
    Long MyStoreId = activeChar.getStoredId();
    for (Castle castle : ResidenceHolder.getInstance().getResidenceList(Castle.class)) {
        activeChar.sendPacket(new ExCastleState(castle));
    }
    synchronized (_lock) {

        for (Player cha : GameObjectsStorage.getAllPlayersForIterate()) {
            if (MyStoreId.equals(cha.getStoredId())) {
                continue;
            }
            try {
                if (cha.getObjectId() == MyObjectId) {
                    _log.warn("Double EnterWorld for char: " + activeChar.getName());
                    cha.kick();
                }
            } catch (Exception e) {
                _log.error("", e);
            }
        }
    }
    GameStats.incrementPlayerEnterGame();
    boolean first = activeChar.entering;
    if (first) {
        activeChar.setOnlineStatus(true);
        if (activeChar.getPlayerAccess().GodMode && !Config.SHOW_GM_LOGIN) {
            activeChar.setInvisibleType(InvisibleType.NORMAL);
        }
        activeChar.setNonAggroTime(Long.MAX_VALUE);
        activeChar.spawnMe();
        if (activeChar.isInStoreMode()) {
            if (!TradeHelper.checksIfCanOpenStore(activeChar, activeChar.getPrivateStoreType())) {
                activeChar.setPrivateStoreType(Player.STORE_PRIVATE_NONE);
                activeChar.standUp();
                activeChar.broadcastCharInfo();
            }
        }
        activeChar.setRunning();
        activeChar.standUp();
        activeChar.startTimers();
    }
    activeChar.sendPacket(new ExBR_PremiumState(activeChar, activeChar.hasBonus()));

    activeChar.getMacroses().sendUpdate(0x01, 0, true);
    activeChar.sendPacket(new SSQInfo(), new HennaInfo(activeChar));
    activeChar.sendItemList(false);
    activeChar.sendPacket(new ShortCutInit(activeChar));
    activeChar.sendPacket(new ShortCutInit(activeChar), new SkillList(activeChar),
            new SkillCoolTime(activeChar));
    activeChar.sendPacket(new SkillCoolTime(activeChar));
    //activeChar.sendPacket(new ExCastleState(_castle));
    activeChar.sendPacket(new ExVitalityEffectInfo(activeChar));
    for (Castle castle : ResidenceHolder.getInstance().getResidenceList(Castle.class)) {
        activeChar.sendPacket(new ExCastleState(castle));
    }
    activeChar.sendPacket(SystemMsg.WELCOME_TO_THE_WORLD_OF_LINEAGE_II);
    Announcements.getInstance().showAnnouncements(activeChar);
    if (first) {
        activeChar.getListeners().onEnter();
    }
    if (first && (activeChar.getCreateTime() > 0)) {
        Calendar create = Calendar.getInstance();
        create.setTimeInMillis(activeChar.getCreateTime());
        Calendar now = Calendar.getInstance();
        int day = create.get(Calendar.DAY_OF_MONTH);
        if ((create.get(Calendar.MONTH) == Calendar.FEBRUARY) && (day == 29)) {
            day = 28;
        }
        int myBirthdayReceiveYear = activeChar.getVarInt(Player.MY_BIRTHDAY_RECEIVE_YEAR, 0);
        if ((create.get(Calendar.MONTH) == now.get(Calendar.MONTH))
                && (create.get(Calendar.DAY_OF_MONTH) == day)) {
            if (((myBirthdayReceiveYear == 0) && (create.get(Calendar.YEAR) != now.get(Calendar.YEAR)))
                    || ((myBirthdayReceiveYear > 0) && (myBirthdayReceiveYear != now.get(Calendar.YEAR)))) {
                Mail mail = new Mail();
                mail.setSenderId(1);
                mail.setSenderName(StringHolder.getInstance().getNotNull(activeChar, "birthday.npc"));
                mail.setReceiverId(activeChar.getObjectId());
                mail.setReceiverName(activeChar.getName());
                mail.setTopic(StringHolder.getInstance().getNotNull(activeChar, "birthday.title"));
                mail.setBody(StringHolder.getInstance().getNotNull(activeChar, "birthday.text"));
                ItemInstance item = ItemFunctions.createItem(21169);
                item.setLocation(ItemInstance.ItemLocation.MAIL);
                item.setCount(1L);
                item.save();
                mail.addAttachment(item);
                mail.setUnread(true);
                mail.setType(Mail.SenderType.BIRTHDAY);
                mail.setExpireTime((720 * 3600) + (int) (System.currentTimeMillis() / 1000L));
                mail.save();
                activeChar.setVar(Player.MY_BIRTHDAY_RECEIVE_YEAR, String.valueOf(now.get(Calendar.YEAR)), -1);
            }
        }
    }
    if (activeChar.getClan() != null) {
        notifyClanMembers(activeChar);
        activeChar.sendPacket(activeChar.getClan().listAll());
        activeChar.sendPacket(new PledgeShowInfoUpdate(activeChar.getClan()),
                new PledgeSkillList(activeChar.getClan()));
    }
    if (first && Config.ALLOW_WEDDING) {
        CoupleManager.getInstance().engage(activeChar);
        CoupleManager.getInstance().notifyPartner(activeChar);
    }
    if (first) {
        activeChar.getFriendList().notifyFriends(true);
        loadTutorial(activeChar);
        activeChar.restoreDisableSkills();
        activeChar.mentoringLoginConditions();
    }
    sendPacket(new L2FriendList(activeChar), new ExStorageMaxCount(activeChar), new QuestList(activeChar),
            new ExBasicActionList(activeChar), new EtcStatusUpdate(activeChar));
    activeChar.checkHpMessages(activeChar.getMaxHp(), activeChar.getCurrentHp());
    activeChar.checkDayNightMessages();
    if (Config.PETITIONING_ALLOWED) {
        PetitionManager.getInstance().checkPetitionMessages(activeChar);
    }
    if (!first) {
        if (activeChar.isCastingNow()) {
            Creature castingTarget = activeChar.getCastingTarget();
            Skill castingSkill = activeChar.getCastingSkill();
            long animationEndTime = activeChar.getAnimationEndTime();
            if ((castingSkill != null) && (castingTarget != null) && castingTarget.isCreature()
                    && (activeChar.getAnimationEndTime() > 0)) {
                sendPacket(new MagicSkillUse(activeChar, castingTarget, castingSkill.getId(),
                        castingSkill.getLevel(), (int) (animationEndTime - System.currentTimeMillis()), 0));
            }
        }
        if (activeChar.isInBoat()) {
            activeChar.sendPacket(activeChar.getBoat().getOnPacket(activeChar, activeChar.getInBoatPosition()));
        }
        if (activeChar.isMoving || activeChar.isFollow) {
            sendPacket(activeChar.movePacket());
        }
        if (activeChar.getMountNpcId() != 0) {
            sendPacket(new Ride(activeChar));
        }
        if (activeChar.isFishing()) {
            activeChar.stopFishing();
        }
    }
    activeChar.entering = false;
    activeChar.sendUserInfo();
    if (activeChar.isSitting()) {
        activeChar.sendPacket(new ChangeWaitType(activeChar, ChangeWaitType.WT_SITTING));
    }
    if (activeChar.getPrivateStoreType() != Player.STORE_PRIVATE_NONE) {
        if (activeChar.getPrivateStoreType() == Player.STORE_PRIVATE_BUY) {
            sendPacket(new PrivateStoreMsgBuy(activeChar));
        } else if ((activeChar.getPrivateStoreType() == Player.STORE_PRIVATE_SELL)
                || (activeChar.getPrivateStoreType() == Player.STORE_PRIVATE_SELL_PACKAGE)) {
            sendPacket(new PrivateStoreMsgSell(activeChar));
        } else if (activeChar.getPrivateStoreType() == Player.STORE_PRIVATE_MANUFACTURE) {
            sendPacket(new RecipeShopMsg(activeChar));
        }
    }
    if (activeChar.isDead()) {
        sendPacket(new Die(activeChar));
    }
    activeChar.unsetVar("offline");
    activeChar.sendActionFailed();
    if (first && activeChar.isGM() && Config.SAVE_GM_EFFECTS && activeChar.getPlayerAccess().CanUseGMCommand) {
        if (activeChar.getVarB("gm_silence")) {
            activeChar.setMessageRefusal(true);
            activeChar.sendPacket(SystemMsg.MESSAGE_REFUSAL_MODE);
        }
        if (activeChar.getVarB("gm_invul")) {
            activeChar.setIsInvul(true);
            activeChar.startAbnormalEffect(AbnormalEffect.S_INVINCIBLE);
            activeChar.sendMessage(activeChar.getName() + " is now immortal.");
        }
        try {
            int var_gmspeed = Integer.parseInt(activeChar.getVar("gm_gmspeed"));
            if ((var_gmspeed >= 1) && (var_gmspeed <= 4)) {
                activeChar.doCast(SkillTable.getInstance().getInfo(7029, var_gmspeed), activeChar, true);
            }
        } catch (Exception E) {
        }
    }
    PlayerMessageStack.getInstance().CheckMessages(activeChar);
    sendPacket(ClientSetTime.STATIC, new ExSetCompassZoneCode(activeChar));
    Pair<Integer, OnAnswerListener> entry = activeChar.getAskListener(false);
    if ((entry != null) && (entry.getValue() instanceof ReviveAnswerListener)) {
        sendPacket(new ConfirmDlg(
                SystemMsg.C1_IS_MAKING_AN_ATTEMPT_TO_RESURRECT_YOU_IF_YOU_CHOOSE_THIS_PATH_S2_EXPERIENCE_WILL_BE_RETURNED_FOR_YOU,
                0).addString("Other player").addString("some"));
    }
    if (activeChar.isCursedWeaponEquipped()) {
        CursedWeaponsManager.getInstance().showUsageTime(activeChar, activeChar.getCursedWeaponEquippedId());
    }
    if (!first) {
        if (activeChar.isInObserverMode()) {
            if (activeChar.getObserverMode() == Player.OBSERVER_LEAVING) {
                activeChar.returnFromObserverMode();
            } else if (activeChar.getOlympiadObserveGame() != null) {
                activeChar.leaveOlympiadObserverMode(true);
            } else {
                activeChar.leaveObserverMode();
            }
        } else if (activeChar.isVisible()) {
            World.showObjectsToPlayer(activeChar);
        }
        for (Summon summon : activeChar.getSummonList()) {
            sendPacket(new PetInfo(summon));
        }
        if (activeChar.isInParty()) {
            sendPacket(new PartySmallWindowAll(activeChar.getParty(), activeChar));
            for (Player member : activeChar.getParty().getPartyMembers()) {
                if (member != activeChar) {
                    sendPacket(new PartySpelled(member, true));
                    for (Summon memberPet : member.getSummonList()) {
                        sendPacket(new PartySpelled(memberPet, true));
                    }
                    sendPacket(RelationChanged.update(activeChar, member, activeChar));
                }
            }
            if (activeChar.getParty().isInCommandChannel()) {
                sendPacket(ExMPCCOpen.STATIC);
            }
        }
        for (int shotId : activeChar.getAutoSoulShot()) {
            sendPacket(new ExAutoSoulShot(shotId, true));
        }
        for (Effect e : activeChar.getEffectList().getAllFirstEffects()) {
            if (e.getSkill().isToggle()) {
                sendPacket(new MagicSkillLaunched(activeChar.getObjectId(), e.getSkill().getId(),
                        e.getSkill().getLevel(), activeChar));
            }
        }
        activeChar.broadcastCharInfo();
    } else {
        activeChar.sendUserInfo();
    }
    activeChar.updateEffectIcons();
    activeChar.setCurrentHpMp(activeChar.getActiveSubClass().getlogOnHp(),
            activeChar.getActiveSubClass().getlogOnMp());
    activeChar.setCurrentCp(activeChar.getActiveSubClass().getlogOnCp());
    activeChar.updateStats();
    if (Config.ALT_PCBANG_POINTS_ENABLED) {
        activeChar.sendPacket(new ExPCCafePointInfo(activeChar, 0, 1, 2, 12));
    }
    if (!activeChar.getPremiumItemList().isEmpty()) {
        activeChar.sendPacket(Config.GOODS_INVENTORY_ENABLED ? ExGoodsInventoryChangedNotify.STATIC
                : ExNotifyPremiumItem.STATIC);
    }
    if (activeChar.getVarB("HeroPeriod") && Config.SERVICES_HERO_SELL_ENABLED) {
        activeChar.setHero(activeChar);
    }
    activeChar.sendVoteSystemInfo();
    activeChar.sendPacket(new ExReceiveShowPostFriend(activeChar));
    activeChar.sendPacket(new ExSubjobInfo(activeChar.getPlayer(), false));
    activeChar.sendPacket(new ExVitalityEffectInfo(activeChar));
    activeChar.sendPacket(new ExTutorialList());
    activeChar.sendPacket(new ExWaitWaitingSubStituteInfo(true));
    for (Effect effect : activeChar.getEffectList().getAllEffects()) {
        if (effect.isInUse()) {
            if (effect.getSkill().getId() == 10022) {
                activeChar.setIsIgnoringDeath(true);
            }
        }
    }
    if (Config.ALT_GAME_REMOVE_PREVIOUS_CERTIFICATES) {
        Skill[] allSkill = activeChar.getAllSkillsArray();
        int totalCertificates = 0;
        for (Skill skl : allSkill) {
            if (skl.getId() >= 1573 && skl.getId() <= 1581) {
                totalCertificates += skl.getLevel();
                activeChar.removeSkill(skl, true);
            }
        }
        if (totalCertificates > 0) {
            activeChar.getInventory().addItem(10280, totalCertificates);
            _log.info("EnterWorld: Player - " + activeChar.getName() + " - Has received " + totalCertificates
                    + " by previous skill certificate deletion.");
            for (SubClass sc : activeChar.getSubClassList().values()) {
                sc.setCertification(0);
                activeChar.store(true);
            }
        }
    }
    activeChar.sendPacket(new ExAcquirableSkillListByClass(activeChar));
    activeChar.setPartySearchStatus(true);
    activeChar.sendPacket(new ExWaitWaitingSubStituteInfo(true));
    checkNewMail(activeChar);
    activeChar.sendPacket(new ExChangeMPCost(1, -3));
    activeChar.sendPacket(new ExChangeMPCost(1, -5));
    activeChar.sendPacket(new ExChangeMPCost(0, 20));
    activeChar.sendPacket(new ExChangeMPCost(1, -10));
    activeChar.sendPacket(new ExChangeMPCost(3, -20));
    activeChar.sendPacket(new ExChangeMPCost(22, -20));
    if (activeChar.getVar("startMovie") == null) {
        activeChar.setVar("startMovie", "1", -1);
        activeChar.sendPacket(new ExShowUsmVideo(ExShowUsmVideo.GD1_INTRO));
    }
    if ((activeChar.getLevel() > 84) && !activeChar.isAwaking()) {
        AwakingManager.getInstance().SendReqToStartQuest(activeChar);
    }
    if (activeChar.isAwaking()) //If the characters returns to Main, or dual Subclass and Delete Skills prof are active, do check of Correct skills
    {
        if (Config.ALT_CHECK_SKILLS_AWAKENING) {
            AwakingManager.getInstance().checkAwakenPlayerSkills(activeChar);
        }
    }
}

From source file:forge.limited.BoosterDraftAI.java

/**
 * <p>/*w ww  .j a v a 2s.  c o m*/
 * Choose a CardPrinted from the list given.
 * </p>
 *
 * @param chooseFrom
 *            List of CardPrinted
 * @param player
 *            a int.
 * @return a {@link forge.item.PaperCard} object.
 */
public PaperCard choose(final List<PaperCard> chooseFrom, final int player) {
    if (ForgePreferences.DEV_MODE) {
        System.out.println("Player[" + player + "] pack: " + chooseFrom.toString());
    }

    final DeckColors deckCols = this.playerColors.get(player);
    final ColorSet currentChoice = deckCols.getChosenColors();
    final boolean canAddMoreColors = deckCols.canChoseMoreColors();

    final List<Pair<PaperCard, Double>> rankedCards = rankCards(chooseFrom);

    for (final Pair<PaperCard, Double> p : rankedCards) {
        double valueBoost = 0;

        // If a card is not ai playable, somewhat decrease its rating
        if (p.getKey().getRules().getAiHints().getRemAIDecks()) {
            valueBoost = TAKE_BEST_THRESHOLD;
        }

        // if I cannot choose more colors, and the card cannot be played with chosen colors, decrease its rating.
        if (!canAddMoreColors
                && !p.getKey().getRules().getManaCost().canBePaidWithAvaliable(currentChoice.getColor())) {
            valueBoost = TAKE_BEST_THRESHOLD * 3;
        }

        if (valueBoost > 0) {
            p.setValue(p.getValue() + valueBoost);
            //System.out.println(p.getKey() + " is now " + p.getValue());
        }
    }

    double bestRanking = Double.MAX_VALUE;
    PaperCard bestPick = null;
    final List<PaperCard> possiblePick = new ArrayList<PaperCard>();
    for (final Pair<PaperCard, Double> p : rankedCards) {
        final double rating = p.getValue();
        if (rating <= bestRanking + .01) {
            if (rating < bestRanking) {
                // found a better card start a new list
                possiblePick.clear();
                bestRanking = rating;
            }
            possiblePick.add(p.getKey());
        }
    }

    bestPick = Aggregates.random(possiblePick);

    if (canAddMoreColors) {
        deckCols.addColorsOf(bestPick);
    }

    System.out.println("Player[" + player + "] picked: " + bestPick + " ranking of " + bestRanking);
    this.deck.get(player).add(bestPick);

    return bestPick;
}

From source file:com.galenframework.speclang2.reader.pagespec.PageSectionProcessor.java

private Pair<PageRule, Map<String, String>> findAndProcessRule(String ruleText, StructNode ruleNode) {
    for (Pair<Rule, PageRule> rulePair : pageSpecHandler.getPageRules()) {
        Matcher matcher = rulePair.getKey().getPattern().matcher(ruleText);
        if (matcher.matches()) {
            int index = 1;

            Map<String, String> parameters = new HashMap<String, String>();

            for (String parameterName : rulePair.getKey().getParameters()) {
                String value = matcher.group(index);
                pageSpecHandler.setGlobalVariable(parameterName, value, ruleNode);

                parameters.put(parameterName, value);
                index += 1;/*from   w  w w .java  2  s. c  o  m*/
            }

            return new ImmutablePair<PageRule, Map<String, String>>(rulePair.getValue(), parameters);
        }
    }
    throw new SyntaxException(ruleNode, "Could find rule matching: " + ruleText);
}