public String inputHandler(Interaction interaction, Object data) throws ContextDataRequired, GeneralInteractionError, AbortInteraction { // first, check for pagination... PaginationAssistant paginator = interaction.getContextData( PaginationAssistant.class, interaction, getTranslationKey(interaction) + "_paginator"); if (paginator != null) { boolean paginationCommand = paginator.processPageCommand(data.toString()); if (paginationCommand) { interaction.pageWaitingForInput = true; return null; } else { // it wasn't a pagination command, so we kill the paginator // so we don't end up with a cache of old data if the player // comes back to this interaction page interaction.context.remove(getTranslationKey(interaction) + "_paginator"); } } // if we don't have pagination (or it wasn't a pagination command..) // see if we are using a choice model, or straight to direct input if (hasChoices) { Choices choices = Choices.getChoices(this, interaction); return choices.takeAction(this, interaction, data); } else return acceptValidatedInput(interaction, data); }
/** * create a 1-d String array from a network, for easy transmission to R. triples (source, * edgeType, target) are filled in to an array of length 3 * # of interactions * * @param network a gaggle network * @return the edge attributes of the network as a string array */ protected String[] networkEdgeAttributesToStringArray(Network network) { Interaction[] interactions = network.getInteractions(); String source, target, type; String[] attributeNames = network.getEdgeAttributeNames(); ArrayList<String> list = new ArrayList<String>(); for (Interaction interaction : interactions) { source = interaction.getSource(); type = interaction.getType(); target = interaction.getTarget(); String edgeName = source + " (" + type + ") " + target; String terseEdgeName = source + "::" + target + "::" + type; for (String name : attributeNames) { HashMap hash = network.getEdgeAttributes(name); if (hash.containsKey(edgeName)) { Object value = hash.get(edgeName); StringBuffer sb = new StringBuffer(); sb.append(terseEdgeName); sb.append("::"); sb.append(name); sb.append("::"); sb.append(value.toString()); list.add(sb.toString()); } else { System.out.println("no " + name + " attribute for " + edgeName); } } // for a } // for r return list.toArray(new String[0]); } // networkEdgeAttributesToStringArray
public String getDisplayText(Interaction interaction) throws ContextDataRequired, GeneralInteractionError, AbortInteraction { // TOOD: Pagination support... // see if we have an active paginator PaginationAssistant paginator = interaction.getContextData( PaginationAssistant.class, interaction, getTranslationKey(interaction) + "_paginator"); if (paginator != null) { return paginator.getDisplayText(); } else { // generate page content, and if there's too much, then activate a paginator.. if (hasChoices) { Choices choices = Choices.getChoices(this, interaction); if (choices == null) choices = generateChoices(interaction); String text = generateDisplayBody(interaction) + "\n"; String choiceText = interaction.parseMessage(StringUtils.join(choices.generateChoiceList(), "")); if (text.split("\n").length + choiceText.split("\n").length + 1 > maxLines) { // we'll need a paginator paginator = new PaginationAssistant(choiceText, maxLines, text); interaction.context.put(getTranslationKey(interaction) + "_paginator", paginator); return paginator.getDisplayText(); } else return text + "\n" + choiceText; } else { String text = generateDisplayBody(interaction); if (text.split("\n").length > maxLines) { paginator = new PaginationAssistant(text, maxLines, ""); interaction.context.put(getTranslationKey(interaction) + "_paginator", paginator); return paginator.getDisplayText(); } else return text; } } }
private void createEdge(final Interaction itr, final CySubNetwork subNetwork) { CyNode sourceNode = nMap.get(itr.getSource()); if (sourceNode == null) { sourceNode = subNetwork.addNode(); subNetwork.getRow(sourceNode).set(CyNetwork.NAME, itr.getSource()); nMap.put(itr.getSource(), subNetwork.getRootNetwork().getNode(sourceNode.getSUID())); } for (final String target : itr.getTargets()) { CyNode targetNode = nMap.get(target); if (targetNode == null) { targetNode = subNetwork.addNode(); subNetwork.getRow(targetNode).set(CyNetwork.NAME, target); nMap.put(target, subNetwork.getRootNetwork().getNode(targetNode.getSUID())); } // Add the sourceNode and targetNode to subNetwork if (!subNetwork.containsNode(sourceNode)) { subNetwork.addNode(sourceNode); } if (!subNetwork.containsNode(targetNode)) { subNetwork.addNode(targetNode); } final CyEdge edge = subNetwork.addEdge(sourceNode, targetNode, true); subNetwork.getRow(edge).set(CyNetwork.NAME, getEdgeName(itr, target)); subNetwork.getRow(edge).set(CyEdge.INTERACTION, itr.getType()); } }
@Override protected void runChild(Interaction interaction, RunNotifier notifier) { final Description description = describeChild(interaction); notifier.fireTestStarted(description); if (interaction.providerState().isDefined()) { final Optional<FrameworkMethod> initializationMethod = findProvderStateInitializationMethod(interaction.providerState().get()); if (initializationMethod.isPresent()) { try { invokeMethod(initializationMethod.get()); testPact(interaction); notifier.fireTestFinished(description); return; } catch (Exception ex) { notifier.fireTestFailure(new Failure(description, ex)); return; } } else { notifier.fireTestIgnored(description); return; } } notifier.fireTestIgnored(description); }
private String getEdgeName(Interaction itr, String target) { edgeNameBuilder.delete(0, edgeNameBuilder.length()); edgeNameBuilder.append(itr.getSource()); edgeNameBuilder.append(" ("); edgeNameBuilder.append(itr.getType()); edgeNameBuilder.append(") "); edgeNameBuilder.append(target); return edgeNameBuilder.toString(); }
/* * THIS METHOD IS FOR USE WITH THE INTERACTION CLASS. * USE ITEM FROM THE PLAYER'S INVENTORY ON ENVIRONMENT. */ public void use(String itemName) { Item item = new Item(itemName); if (!p.inv.contains(item.name)) console.print("You don't have a " + itemName + "."); else { Interaction in = Interaction.getInteraction(item, getCurrentTile().entities); if (in == null) console.print("Nothing to use the " + item.name + " with."); else { Interaction.interact(in, getCurrentTile(), p.inv); console.print(in.msg); p.decFood(1); p.decWater(1); } } }
@Override protected void onFinishInflate() { super.onFinishInflate(); mZenButtons = (SegmentedButtons) findViewById(R.id.zen_buttons); mZenButtons.addButton( R.string.interruption_level_none, R.drawable.ic_zen_none, Global.ZEN_MODE_NO_INTERRUPTIONS); mZenButtons.addButton( R.string.interruption_level_priority, R.drawable.ic_zen_important, Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS); mZenButtons.addButton( R.string.interruption_level_all, R.drawable.ic_zen_all, Global.ZEN_MODE_OFF); mZenButtons.setCallback(mZenButtonsCallback); final ViewGroup zenButtonsContainer = (ViewGroup) findViewById(R.id.zen_buttons_container); zenButtonsContainer.setLayoutTransition(newLayoutTransition(null)); mZenSubhead = findViewById(R.id.zen_subhead); mZenSubheadCollapsed = (TextView) findViewById(R.id.zen_subhead_collapsed); mZenSubheadCollapsed.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { setExpanded(true); } }); Interaction.register(mZenSubheadCollapsed, mInteractionCallback); mZenSubheadExpanded = (TextView) findViewById(R.id.zen_subhead_expanded); Interaction.register(mZenSubheadExpanded, mInteractionCallback); mMoreSettings = findViewById(R.id.zen_more_settings); mMoreSettings.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { fireMoreSettings(); } }); Interaction.register(mMoreSettings, mInteractionCallback); mZenConditions = (LinearLayout) findViewById(R.id.zen_conditions); for (int i = 0; i < mMaxConditions; i++) { mZenConditions.addView(mInflater.inflate(R.layout.zen_mode_condition, this, false)); } setLayoutTransition(newLayoutTransition(mTransitionHelper)); }
/** * Checks if the controlled Interaction contains a controller as a participant. This constraint * filters out such cases. * * @param match current pattern match * @param ind mapped indices * @return true if participants of teh controlled Interactions not also a controller of the * Control. */ @Override public boolean satisfies(Match match, int... ind) { Control ctrl = (Control) match.get(ind[0]); for (Process process : ctrl.getControlled()) { if (process instanceof Interaction) { Interaction inter = (Interaction) process; Set<Entity> participant = inter.getParticipant(); for (Controller controller : ctrl.getController()) { if (participant.contains(controller)) return false; } } } return true; }
public boolean addInteraction(Interaction i) { boolean addSuccess = interactions.add(i); if (addSuccess) i.check(); return addSuccess; }
/** * Calculate scores for each entry in the EntrySet. The scores are added to the EntrySet directly * and the scoring report will be returned. * * @param entrySet the entry set where the scores will be added to * @return scoring report * @throws PsiscoreException */ public List<String> calculateScores(EntrySet entrySet) throws PsiscoreException { if (entrySet.getEntries() == null) { throw new PsiscoreException("EntrySet does not contain any entries", new PsiscoreFault()); } List<String> report = new ArrayList<String>(); int scored = 0; int unscored = 0; int totalConfidences = 0; // go over all entries Iterator<Entry> it = entrySet.getEntries().iterator(); scoringParameters.setScoresAdded(false); while (it.hasNext()) { Entry entry = it.next(); // and go over all interactions in that entry Collection<Interaction> interactions = entry.getInteractions(); for (Iterator<Interaction> interactionIt = interactions.iterator(); interactionIt.hasNext(); ) { Interaction interaction = interactionIt.next(); Collection<Confidence> confidences = null; // and request the scores for that interaction try { confidences = getInteractionScores(interaction); } catch (ScoringException e) { report.add(e.getMessage()); } // confidences = null; if (confidences == null || confidences.size() == 0) { unscored++; } else if (confidences.size() > 0) { scoringParameters.setScoresAdded(true); scored++; totalConfidences += confidences.size(); interaction.getConfidences().addAll(confidences); } } } report.add( totalConfidences + " confidences scores added for " + scored + " interactions, nothing added for " + unscored + " interactions"); return report; }
public static void main(String[] args) { final int MIN = 1; final int MAX = 100; int guess; int randomInt; Random random = new Random(MIN, MAX); randomInt = random.getValue(); Interaction.summarizeProgram(); do { Interaction.requestInput(); guess = Interaction.getInput(); } while (!Interaction.giveHintIfWrong(guess, randomInt)); }
/** * Gets the layer interaction property relevant to the supplied key (or toolCategoryId). * * @param layerInteraction * @return interaction */ public static Interaction getInteraction(String layerInteraction) { // check for deprecated ProjectBlackboardConstants if (layerInteraction.equals(ProjectBlackboardConstants.LAYER__EDIT_APPLICABILITY) || layerInteraction.equals(ProjectBlackboardConstants.LAYER__FEATURES_ADD_APPLICABILITY) || layerInteraction.equals( ProjectBlackboardConstants.LAYER__FEATURES_MODIFY_APPLICABILITY) || layerInteraction.equals( ProjectBlackboardConstants.LAYER__FEATURES_REMOVE_APPLICABILITY)) { return Interaction.EDIT; } for (Interaction interaction : Interaction.values()) { if (layerInteraction.equals(interaction.getKey())) { return interaction; } } return null; }
/** * @param operator "+" for filter in keeping positive values. "0" filter for keeping 0 values. "-" * for keeping negative values * @return */ public TreeSet<Interaction> getAllInteractions(String operator) { HashSet<Interaction> unsorted = new HashSet<>(); TreeSet<Interaction> out = new TreeSet<>(new ValueComparator()); Iterator<Interaction> iter = dsm.iterator(); while (iter.hasNext()) { Interaction interaction = iter.next(); double val = interaction.getValue(); if ((val == 0.0 && operator.equalsIgnoreCase("0")) || (val > 0.0 && operator.equalsIgnoreCase("+")) || (val < 0.0 && operator.equalsIgnoreCase("-"))) { unsorted.add(interaction); } } out.addAll(unsorted); return out; }
/** * Handle incoming data. * * @param StreamConsumer consumer The consumer object. * @param Interaction interaction The interaction data. * @throws EInvalidData */ public void onInteraction(StreamConsumer c, Interaction i) { try { try { _fw.append(i.getStringVal("interaction.id")); } catch (EInvalidData e) { // Ignored } _fw.append(",\""); try { _fw.append(i.getStringVal("interaction.created_at").replace("\"", "\\\"")); } catch (EInvalidData e) { // Ignored } _fw.append("\",\""); try { _fw.append(i.getStringVal("interaction.author.username").replace("\"", "\\\"")); } catch (EInvalidData e) { // Ignored } _fw.append("\",\""); try { _fw.append(i.getStringVal("interaction.content").replace("\"", "\\\"").replace('\n', ' ')); } catch (EInvalidData e) { // Ignored } _fw.append("\"\n"); _fw.flush(); _counter += 1; if (_counter % 1000 == 0) { System.err.print("\r" + String.valueOf(_counter++)); } } catch (IOException e) { System.err.println("ERR: Failed to write interaction to the CSV file: " + e.getMessage()); } }
private static void testPact(Interaction interaction) { try { final ExecutionContextExecutor executionContextExecutor = ExecutionContext$.MODULE$.fromExecutor(Executors.newCachedThreadPool()); final Request request = new Request( interaction.request().method(), "http://localhost:8080" + interaction.request().path(), interaction.request().query(), interaction.request().headers(), interaction.request().body(), interaction.request().matchingRules()); Future<Response> actualResponseFuture = HttpClient.run(request, executionContextExecutor); Response actualResponse = Await.result(actualResponseFuture, Duration.create(1000, TimeUnit.SECONDS)); assertEquals( FullResponseMatch$.MODULE$, ResponseMatching$.MODULE$.matchRules(interaction.response(), actualResponse)); } catch (Exception e) { throw new RuntimeException(e); } }
/** * create a 1-d String array from a network, for easy transmission to R. each element in the array * is a string, with format sourceNode::targetNode::edgeType * * @param network the network to convert to a string * @return an array of strings representing a network */ protected String[] networkToStringArray(Network network) { Interaction[] interactions = network.getInteractions(); ArrayList<String> list = new ArrayList<String>(); // System.out.println ("networkToStringArray, interaction ount: " + interactions.length); for (Interaction interaction : interactions) { String source = interaction.getSource(); String target = interaction.getTarget(); String type = interaction.getType(); String combined = source + "::" + target + "::" + type; // System.out.println (" interaction: " + combined); list.add(combined); } // for i String[] orphanNodes = network.getOrphanNodes(); // System.out.println ("networkToStringArray, orphanCount: " + orphanNodes.length); for (String orphanNode : orphanNodes) { // System.out.println (" orphan: " + orphanNodes [i]); list.add(orphanNode); } return list.toArray(new String[0]); } // networkToStringArray
protected void processRequest(final HttpServletRequest req, final HttpServletResponse resp) { LanternUtils.addCSPHeader(resp); final String uri = req.getRequestURI(); log.debug("Received URI: {}", uri); final String interactionStr = StringUtils.substringAfterLast(uri, "/"); if (StringUtils.isBlank(interactionStr)) { log.debug("blank interaction"); HttpUtils.sendClientError(resp, "blank interaction"); return; } log.debug("Headers: " + HttpUtils.getRequestHeaders(req)); if (!"XMLHttpRequest".equals(req.getHeader("X-Requested-With"))) { log.debug("invalid X-Requested-With"); HttpUtils.sendClientError(resp, "invalid X-Requested-With"); return; } if (!SecurityUtils.constantTimeEquals(model.getXsrfToken(), req.getHeader("X-XSRF-TOKEN"))) { log.debug( "X-XSRF-TOKEN wrong: got {} expected {}", req.getHeader("X-XSRF-TOKEN"), model.getXsrfToken()); HttpUtils.sendClientError(resp, "invalid X-XSRF-TOKEN"); return; } final int cl = req.getContentLength(); String json = ""; if (cl > 0) { try { json = IOUtils.toString(req.getInputStream()); } catch (final IOException e) { log.error("Could not parse json?"); } } log.debug("Body: '" + json + "'"); final Interaction inter = Interaction.valueOf(interactionStr.toUpperCase()); if (inter == Interaction.CLOSE) { if (handleClose(json)) { return; } } if (inter == Interaction.URL) { final String url = JsonUtils.getValueFromJson("url", json); if (!StringUtils.startsWith(url, "http://") && !StringUtils.startsWith(url, "https://")) { log.error("http(s) url expected, got {}", url); HttpUtils.sendClientError(resp, "http(s) urls only"); return; } try { new URL(url); } catch (MalformedURLException e) { log.error("invalid url: {}", url); HttpUtils.sendClientError(resp, "invalid url"); return; } final String cmd; if (SystemUtils.IS_OS_MAC_OSX) { cmd = "open"; } else if (SystemUtils.IS_OS_LINUX) { cmd = "gnome-open"; } else if (SystemUtils.IS_OS_WINDOWS) { cmd = "start"; } else { log.error("unsupported OS"); HttpUtils.sendClientError(resp, "unsupported OS"); return; } try { if (SystemUtils.IS_OS_WINDOWS) { // On Windows, we have to quote the url to allow for // e.g. ? and & characters in query string params. // To quote the url, we supply a dummy first argument, // since otherwise start treats the first argument as a // title for the new console window when it's quoted. LanternUtils.runCommand(cmd, "\"\"", "\"" + url + "\""); } else { // on OS X and Linux, special characters in the url make // it through this call without our having to quote them. LanternUtils.runCommand(cmd, url); } } catch (IOException e) { log.error("open url failed"); HttpUtils.sendClientError(resp, "open url failed"); return; } return; } final Modal modal = this.model.getModal(); log.debug( "processRequest: modal = {}, inter = {}, mode = {}", modal, inter, this.model.getSettings().getMode()); if (handleExceptionalInteractions(modal, inter, json)) { return; } Modal switchTo = null; try { // XXX a map would make this more robust switchTo = Modal.valueOf(interactionStr); } catch (IllegalArgumentException e) { } if (switchTo != null && switchModals.contains(switchTo)) { if (!switchTo.equals(modal)) { if (!switchModals.contains(modal)) { this.internalState.setLastModal(modal); } Events.syncModal(model, switchTo); } return; } switch (modal) { case welcome: this.model.getSettings().setMode(Mode.unknown); switch (inter) { case GET: log.debug("Setting get mode"); handleSetModeWelcome(Mode.get); break; case GIVE: log.debug("Setting give mode"); handleSetModeWelcome(Mode.give); break; } break; case authorize: log.debug("Processing authorize modal..."); this.internalState.setModalCompleted(Modal.authorize); this.internalState.advanceModal(null); break; case finished: this.internalState.setCompletedTo(Modal.finished); switch (inter) { case CONTINUE: log.debug("Processing continue"); this.model.setShowVis(true); Events.sync(SyncPath.SHOWVIS, true); this.internalState.setModalCompleted(Modal.finished); this.internalState.advanceModal(null); break; case SET: log.debug("Processing set in finished modal...applying JSON\n{}", json); applyJson(json); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError( resp, "Interaction not handled for modal: " + modal + " and interaction: " + inter); break; } break; case firstInviteReceived: log.error("Processing invite received..."); break; case lanternFriends: this.internalState.setCompletedTo(Modal.lanternFriends); switch (inter) { case FRIEND: this.friender.addFriend(email(json)); break; case REJECT: this.friender.removeFriend(email(json)); break; case CONTINUE: // This dialog always passes continue as of this writing and // not close. case CLOSE: log.debug("Processing continue/close for friends dialog"); if (this.model.isSetupComplete()) { Events.syncModal(model, Modal.none); } else { this.internalState.setModalCompleted(Modal.lanternFriends); this.internalState.advanceModal(null); } break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError( resp, "Interaction not handled for modal: " + modal + " and interaction: " + inter); break; } break; case none: break; case notInvited: switch (inter) { case RETRY: Events.syncModal(model, Modal.authorize); break; // not currently implemented: // case REQUESTINVITE: // Events.syncModal(model, Modal.requestInvite); // break; default: log.error("Unexpected interaction: " + inter); break; } break; case proxiedSites: this.internalState.setCompletedTo(Modal.proxiedSites); switch (inter) { case CONTINUE: if (this.model.isSetupComplete()) { Events.syncModal(model, Modal.none); } else { this.internalState.setModalCompleted(Modal.proxiedSites); this.internalState.advanceModal(null); } break; case LANTERNFRIENDS: log.debug("Processing lanternFriends from proxiedSites"); Events.syncModal(model, Modal.lanternFriends); break; case SET: if (!model.getSettings().isSystemProxy()) { String msg = "Because you are using manual proxy " + "configuration, you may have to restart your " + "browser for your updated proxied sites list " + "to take effect."; model.addNotification(msg, MessageType.info, 30); Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications()); } applyJson(json); break; case SETTINGS: log.debug("Processing settings from proxiedSites"); Events.syncModal(model, Modal.settings); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "unexpected interaction for proxied sites"); break; } break; case requestInvite: log.info("Processing request invite"); switch (inter) { case CANCEL: this.internalState.setModalCompleted(Modal.requestInvite); this.internalState.advanceModal(Modal.notInvited); break; case CONTINUE: applyJson(json); this.internalState.setModalCompleted(Modal.proxiedSites); // TODO: need to do something here this.internalState.advanceModal(null); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "unexpected interaction for request invite"); break; } break; case requestSent: log.debug("Process request sent"); break; case settings: switch (inter) { case GET: log.debug("Setting get mode"); // Only deal with a mode change if the mode has changed! if (modelService.getMode() == Mode.give) { // Break this out because it's set in the subsequent // setMode call final boolean everGet = model.isEverGetMode(); this.modelService.setMode(Mode.get); if (!everGet) { // need to do more setup to switch to get mode from // give mode model.setSetupComplete(false); model.setModal(Modal.proxiedSites); Events.syncModel(model); } else { // This primarily just triggers a setup complete event, // which triggers connecting to proxies, setting up // the local system proxy, etc. model.setSetupComplete(true); } } break; case GIVE: log.debug("Setting give mode"); this.modelService.setMode(Mode.give); break; case CLOSE: log.debug("Processing settings close"); Events.syncModal(model, Modal.none); break; case SET: log.debug("Processing set in setting...applying JSON\n{}", json); applyJson(json); break; case RESET: log.debug("Processing reset"); Events.syncModal(model, Modal.confirmReset); break; case PROXIEDSITES: log.debug("Processing proxied sites in settings"); Events.syncModal(model, Modal.proxiedSites); break; case LANTERNFRIENDS: log.debug("Processing friends in settings"); Events.syncModal(model, Modal.lanternFriends); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError( resp, "Interaction not handled for modal: " + modal + " and interaction: " + inter); break; } break; case settingsLoadFailure: switch (inter) { case RETRY: modelIo.reload(); Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications()); Events.syncModal(model, model.getModal()); break; case RESET: backupSettings(); Events.syncModal(model, Modal.welcome); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); break; } break; case systemProxy: this.internalState.setCompletedTo(Modal.systemProxy); switch (inter) { case CONTINUE: log.debug("Processing continue in systemProxy", json); applyJson(json); Events.sync(SyncPath.SYSTEMPROXY, model.getSettings().isSystemProxy()); this.internalState.setModalCompleted(Modal.systemProxy); this.internalState.advanceModal(null); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "error setting system proxy pref"); break; } break; case updateAvailable: switch (inter) { case CLOSE: this.internalState.setModalCompleted(Modal.updateAvailable); this.internalState.advanceModal(null); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); break; } break; case authorizeLater: log.error("Did not handle interaction {} for modal {}", inter, modal); break; case confirmReset: log.debug("Handling confirm reset interaction"); switch (inter) { case CANCEL: log.debug("Processing cancel"); Events.syncModal(model, Modal.settings); break; case RESET: handleReset(); Events.syncModel(this.model); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError( resp, "Interaction not handled for modal: " + modal + " and interaction: " + inter); } break; case about: // fall through on purpose case sponsor: switch (inter) { case CLOSE: Events.syncModal(model, this.internalState.getLastModal()); break; default: HttpUtils.sendClientError(resp, "invalid interaction " + inter); } break; case contact: switch (inter) { case CONTINUE: String msg; MessageType messageType; try { lanternFeedback.submit(json, this.model.getProfile().getEmail()); msg = "Thank you for contacting Lantern."; messageType = MessageType.info; } catch (Exception e) { log.error("Error submitting contact form: {}", e); msg = "Error sending message. Please check your " + "connection and try again."; messageType = MessageType.error; } model.addNotification(msg, messageType, 30); Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications()); // fall through because this should be done in both cases: case CANCEL: Events.syncModal(model, this.internalState.getLastModal()); break; default: HttpUtils.sendClientError(resp, "invalid interaction " + inter); } break; case giveModeForbidden: if (inter == Interaction.CONTINUE) { // need to do more setup to switch to get mode from give mode model.getSettings().setMode(Mode.get); model.setSetupComplete(false); this.internalState.advanceModal(null); Events.syncModal(model, Modal.proxiedSites); Events.sync(SyncPath.SETUPCOMPLETE, false); } break; default: log.error("No matching modal for {}", modal); } this.modelIo.write(); }
public String generateDisplayBody(Interaction interaction) { String text = null; if (translatableBody) text = VariableTool.variable(getTranslationKey(interaction) + ".text"); else text = getText(); return interaction.parseMessage(text); }
@Override protected Description describeChild(Interaction interaction) { return Description.createTestDescription( pactToVerify.consumer().name(), interaction.description()); }
@Override public boolean matches(Object arg0) { if (!(arg0 instanceof Interaction)) return false; Interaction turn = (Interaction) arg0; return turn.getName().equals(mName); }
private void frameAnalysis(ArrayList<SimInfo> sia) { if (!(timeStamp > startTime && timeStamp <= endTime)) return; frameNum++; int size = sia.size(); speedLost += history.size() - size; thetaLost += history.size() - size; if (size == 0) return; while (size > history.size()) { history.add(new ArrayList<SimInfo>()); speedLost += frameNum - 1; thetaLost += frameNum - 1; } SimInfo si = null; SimInfo si2 = null; double xOff, yOff, thetaOff; double speed; ArrayList<MutableDouble2D> pa = new ArrayList<MutableDouble2D>(); MutableDouble2D loc = null; for (int i = 0; i < size; i++) { loc = new MutableDouble2D(sia.get(i).getPX(), sia.get(i).getPY()); pa.add(loc); si = sia.get(i); si2 = getRecorded(sia_recorder, si); if (si2 != null && si != null) { // in the sia_recorder xOff = si.getPX() - si2.getPX(); yOff = si.getPY() - si2.getPY(); speed = Math.sqrt(xOff * xOff + yOff * yOff) / (si.getTimeStamp() - si2.getTimeStamp()); if (speed < minSpeed) minSpeed = speed; if (speed > maxSpeed) maxSpeed = speed; thetaOff = Math.atan2(si.getDY(), si.getDX()) - Math.atan2(si2.getDY(), si2.getDX()); if (thetaOff > Math.PI) thetaOff -= 2 * Math.PI; if (thetaOff < -Math.PI) thetaOff += 2 * Math.PI; if (Math.abs(thetaOff) > maxThetaOff) maxThetaOff = thetaOff; if (Math.abs(thetaOff) < minThetaOff) minThetaOff = Math.abs(thetaOff); int speedIndex = (int) (speed / speedWidth); int thetaIndex = (int) (Math.abs(thetaOff) / 0.01); if (speed == 0) speedZero++; if (speedIndex >= (int) (guessedMaxSpeed / speedWidth)) speedOutBound++; if (speedIndex < (int) (guessedMaxSpeed / speedWidth) && speed > 0) speedHistogram[speedIndex]++; if (thetaOff == 0) thetaZero++; if (thetaIndex >= (int) (Math.PI / thetaWidth)) thetaOutBound++; if (thetaIndex < (int) (Math.PI / thetaWidth) && Math.abs(thetaOff) > 0) thetaHistogram[thetaIndex]++; if (speed > 0.12) { System.out.println("ts1: " + si2.getTimeStamp() + " id: " + si2.getId()); System.out.println("ts2: " + si.getTimeStamp() + " id: " + si.getId()); } } else { speedLost++; thetaLost++; } } double tmp; ArrayList<Integer> ia = new ArrayList<Integer>(); // store the id of the // interacting agent ArrayList<Integer> ib = new ArrayList<Integer>(); // store the agentType // of the // interacting agent Interaction interaction = null; ArrayList<Interaction> interactionList = new ArrayList<Interaction>(); for (int i = 0; i < size; i++) { si = sia.get(i); ia.clear(); ib.clear(); interactionList.clear(); boolean in_touch = false; for (int j = 0; j < size; j++) { if (j != i) { tmp = Math.pow(pa.get(i).getX() - pa.get(j).getX(), 2); tmp += Math.pow(pa.get(i).getY() - pa.get(j).getY(), 2); tmp = Math.sqrt(tmp); if (tmp <= interacting_distance) { // interacting in_touch = true; ia.add(sia.get(j).getId()); ib.add(sia.get(j).getAgentType()); } } } int interacting_index = find_id(interacting, si.getId()); if (in_touch) { if (interacting_index != -1) { if ((Math.abs(interacting.get(interacting_index).getPX() - si.getPX()) < 0.0000002) && (Math.abs(interacting.get(interacting_index).getPY() - si.getPY()) < 0.0000002)) { if (si.getTimeStamp() - interacting.get(interacting_index).getTimeStamp() >= interacting_time_length) { interacting.get(interacting_index).setTimeStamp(si.getTimeStamp()); interacting.get(interacting_index).setPX(si.getPX()); interacting.get(interacting_index).setPY(si.getPY()); interacting_count++; } } else { interacting.get(interacting_index).setTimeStamp(si.getTimeStamp()); interacting.get(interacting_index).setPX(si.getPX()); interacting.get(interacting_index).setPY(si.getPY()); } } else { interacting.add(si); } } else { if (interacting_index != -1) { interacting.get(interacting_index).setTimeStamp(si.getTimeStamp()); interacting.get(interacting_index).setPX(si.getPX()); interacting.get(interacting_index).setPY(si.getPY()); } else { interacting.add(si); } } try { writer.write( " <row> 1:" + si.getTimeStamp() + " 2:" + si.getAgentType() + " 3:" + si.getId() + " 4:" + si.getPX() + " 5:" + si.getPY() + " 6:" + si.getPZ() + " 7:" + si.getDX() + " 8:" + si.getDY() + " 9:" + si.getDZ() + " 10:["); for (int k = 0; k < ia.size(); k++) { int type = getInteractionType(sia, ib.get(k), ia.get(k), si.getAgentType(), si.getId()); Double2D toLoc = getToLocation(sia, ib.get(k), ia.get(k), si.getAgentType(), si.getId()); if (type != -1) { interaction = new Interaction(type, toLoc.getX(), toLoc.getY()); interactionList.add(interaction); writer.write( "(" + interaction.getType() + ":" + ia.get(k) + "{" + interaction.getToX() + "+" + interaction.getToY() + "})"); } } writer.write("] </row>\n"); writer.flush(); si.setInteractionList(interactionList); while (history.size() <= si.getId()) { history.add(new ArrayList<SimInfo>()); speedLost += frameNum - 1; thetaLost += frameNum - 1; } history.get(si.getId()).add(si); } catch (IOException e) { System.err.println(e); System.exit(1); } } sia_recorder.clear(); for (int i = 0; i < sia.size(); i++) { sia_recorder.add(sia.get(i)); } }
private void bind(final Condition condition, final View row) { if (condition == null) throw new IllegalArgumentException("condition must not be null"); final boolean enabled = condition.state == Condition.STATE_TRUE; final ConditionTag tag = row.getTag() != null ? (ConditionTag) row.getTag() : new ConditionTag(); row.setTag(tag); final boolean first = tag.rb == null; if (tag.rb == null) { tag.rb = (RadioButton) row.findViewById(android.R.id.checkbox); } tag.condition = condition; final Uri conditionId = getConditionId(tag.condition); if (DEBUG) Log.d( mTag, "bind i=" + mZenConditions.indexOfChild(row) + " first=" + first + " condition=" + conditionId); tag.rb.setEnabled(enabled); final boolean checked = (mSessionExitCondition != null || mAttachedZen != Global.ZEN_MODE_OFF) && (sameConditionId(mSessionExitCondition, tag.condition) || isCountdown(mSessionExitCondition) && isCountdown(tag.condition)); if (checked != tag.rb.isChecked()) { if (DEBUG) Log.d(mTag, "bind checked=" + checked + " condition=" + conditionId); tag.rb.setChecked(checked); } tag.rb.setOnCheckedChangeListener( new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (mExpanded && isChecked) { if (DEBUG) Log.d(mTag, "onCheckedChanged " + conditionId); final int N = getVisibleConditions(); for (int i = 0; i < N; i++) { final ConditionTag childTag = getConditionTagAt(i); if (childTag == null || childTag == tag) continue; childTag.rb.setChecked(false); } select(tag.condition); announceConditionSelection(tag); } } }); if (tag.lines == null) { tag.lines = row.findViewById(android.R.id.content); } if (tag.line1 == null) { tag.line1 = (TextView) row.findViewById(android.R.id.text1); } if (tag.line2 == null) { tag.line2 = (TextView) row.findViewById(android.R.id.text2); } final String line1 = !TextUtils.isEmpty(condition.line1) ? condition.line1 : condition.summary; final String line2 = condition.line2; tag.line1.setText(line1); if (TextUtils.isEmpty(line2)) { tag.line2.setVisibility(GONE); } else { tag.line2.setVisibility(VISIBLE); tag.line2.setText(line2); } tag.lines.setEnabled(enabled); tag.lines.setAlpha(enabled ? 1 : .4f); final ImageView button1 = (ImageView) row.findViewById(android.R.id.button1); button1.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { onClickTimeButton(row, tag, false /*down*/); } }); final ImageView button2 = (ImageView) row.findViewById(android.R.id.button2); button2.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { onClickTimeButton(row, tag, true /*up*/); } }); tag.lines.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { tag.rb.setChecked(true); } }); final long time = ZenModeConfig.tryParseCountdownConditionId(conditionId); if (time > 0) { button1.setVisibility(VISIBLE); button2.setVisibility(VISIBLE); if (mBucketIndex > -1) { button1.setEnabled(mBucketIndex > 0); button2.setEnabled(mBucketIndex < MINUTE_BUCKETS.length - 1); } else { final long span = time - System.currentTimeMillis(); button1.setEnabled(span > MIN_BUCKET_MINUTES * MINUTES_MS); final Condition maxCondition = ZenModeConfig.toTimeCondition( mContext, MAX_BUCKET_MINUTES, ActivityManager.getCurrentUser()); button2.setEnabled(!Objects.equals(condition.summary, maxCondition.summary)); } button1.setAlpha(button1.isEnabled() ? 1f : .5f); button2.setAlpha(button2.isEnabled() ? 1f : .5f); } else { button1.setVisibility(GONE); button2.setVisibility(GONE); } // wire up interaction callbacks for newly-added condition rows if (first) { Interaction.register(tag.rb, mInteractionCallback); Interaction.register(tag.lines, mInteractionCallback); Interaction.register(button1, mInteractionCallback); Interaction.register(button2, mInteractionCallback); } row.setVisibility(VISIBLE); }
@EventHandler public void onChatEvent(PlayerChatEvent event) { Interaction.chatEvent(event); }
@Override public int compare(Interaction o1, Interaction o2) { return (int) (o1.getValue() - o2.getValue()); }