auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void resolveVars(Map<String, String> variables, Map<String, String> env) { for (Map.Entry<String, String> entry : variables.entrySet()) { String value = Util.replaceMacro(entry.getValue(), env); entry.setValue(value); } boolean stopToResolveVars = false; int nbUnresolvedVar = 0; while (!stopToResolveVars) { int previousNbUnresolvedVar = nbUnresolvedVar; nbUnresolvedVar = 0; for (Map.Entry<String, String> entry : variables.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); Map<String, String> resolveVariables = new HashMap<String, String>(variables); resolveVariables.remove(key); String newValue = Util.replaceMacro(value, resolveVariables); entry.setValue(newValue); boolean variableChanged = !newValue.equals(value); if (variableChanged && isUnresolvedVar(newValue)) { nbUnresolvedVar++; } } if (previousNbUnresolvedVar == nbUnresolvedVar) { stopToResolveVars = true; } } }

Target:
public void resolveVars(Map<String, String> variables, Map<String, String> env) { for (Map.Entry<String, String> entry : variables.entrySet()) { String value = Util.replaceMacro(entry.getValue(), env); entry.setValue(value); } boolean stopToResolveVars = false; int nbUnresolvedVar = 0; while (!stopToResolveVars) { int previousNbUnresolvedVar = nbUnresolvedVar; nbUnresolvedVar = 0; for (Map.Entry<String, String> entry : variables.entrySet()) { Map<String, String> resolveVariables = new HashMap<String, String>(variables); resolveVariables.remove(entry.getKey()); String value = Util.replaceMacro(entry.getValue(), resolveVariables); entry.setValue(value); if (isUnresolvedVar(value)) { nbUnresolvedVar++; } } if (previousNbUnresolvedVar == nbUnresolvedVar) { stopToResolveVars = true; } } }
Source:
public String getDeviceManufacturer() { return String.valueOf(Build.MANUFACTURER); }

Target:
public String getDeviceManufacturer() { return Build.MANUFACTURER; }
Source:
public void addLogger() throws Exception { AddLogCategory addLogCategory = new AddLogCategory.Builder(TEST_LOGGER_NAME) .level(Level.OFF) .filter("match(\"filter\")") .setUseParentHandler(true) .build(); client.apply(addLogCategory); assertTrue("logger wasn't created", ops.exists(TEST_LOGGER_ADDRESS)); RemoveLogCategory removeLogger = new RemoveLogCategory(TEST_LOGGER_NAME); client.apply(removeLogger); assertFalse("logger wasn't deleted", ops.exists(TEST_LOGGER_ADDRESS)); }

Target:
public void addLogger() throws Exception { LogCategoryCommand addLogCategory = LogCategoryCommand.add(TEST_LOGGER_NAME) .level(Level.OFF) .filter("match(\"filter\")") .setUseParentHandler(true) .build(); client.apply(addLogCategory); assertTrue("logger should be created", ops.exists(TEST_LOGGER_ADDRESS)); LogCategoryCommand removeLogger = LogCategoryCommand.remove(TEST_LOGGER_NAME); client.apply(removeLogger); assertFalse("logger should be deleted", ops.exists(TEST_LOGGER_ADDRESS)); }
Source:
public SortedMap<String, List<String>> parseTopAndSecondLevelCategories(final String journalKey) throws IOException { String cacheKey = "topAndSecondLevelCategories:" + CacheParams.createKeyHash(journalKey); SortedMap<String, List<String>> categories = cache.get(cacheKey); if (categories == null) { categories = parseTopAndSecondLevelCategoriesWithoutCache(journalKey); cache.put(cacheKey, (Serializable) categories); } return categories; }

Target:
public SortedMap<String, List<String>> parseTopAndSecondLevelCategories(final String journalKey) throws IOException { String cacheKey = "topAndSecondLevelCategories:" + CacheParams.createKeyHash(journalKey); return CacheUtil.getOrCompute(cache, cacheKey, () -> parseTopAndSecondLevelCategoriesWithoutCache(journalKey)); }
Source:
private void executeToolForImmutableTables(ConnectionQueryServices queryServices, ArrayList<String> immutableList) { boolean atLeastOneHasIndexes=false; for (String dataTableFullName : immutableList) { HashSet<String> indexes = tablesAndIndexes.get(dataTableFullName); if (!(indexes.isEmpty() || atLeastOneHasIndexes)) { atLeastOneHasIndexes = true; } try (Admin admin = queryServices.getAdmin()) { LOGGER.info("Executing " + operation + " of " + dataTableFullName + " (immutable)"); disableTable(admin, dataTableFullName, indexes); modifyTable(admin, dataTableFullName, indexes); } catch (IOException | SQLException e) { LOGGER.severe("Something went wrong while disabling or modifying immutable " + "table " + dataTableFullName+ " " + e); } } if (!(test || dryRun) && atLeastOneHasIndexes) { LOGGER.info("The input list has at least one immutable table with indexes, " + "waiting for " + (GLOBAL_INDEX_CHECKER_ENABLED_MAP_EXPIRATION_MIN + 1) + " minutes for client cache to expire"); try { Thread.sleep((GLOBAL_INDEX_CHECKER_ENABLED_MAP_EXPIRATION_MIN + 1) * 60 * 1000); } catch (InterruptedException e) { LOGGER.warning("Sleep before starting index rebuild is interrupted. " + e.getMessage()); } } for (String dataTableFullName : immutableList) { try (Admin admin = queryServices.getAdmin()) { HashSet<String> indexes = tablesAndIndexes.get(dataTableFullName); enableTable(admin, dataTableFullName, indexes); } catch (IOException | SQLException e) { LOGGER.severe("Something went wrong while enabling immutable table " + dataTableFullName + " " + e); } LOGGER.info("Completed " + operation + " of " + dataTableFullName + " (immutable)"); } }

Target:
private long executeToolForImmutableTables(ConnectionQueryServices queryServices, ArrayList<String> immutableList) { LOGGER.info("Started " + operation + " for immutable tables"); for (String dataTableFullName : immutableList) { try (Admin admin = queryServices.getAdmin()) { HashSet<String> indexes = tablesAndIndexes.get(dataTableFullName); LOGGER.info("Executing " + operation + " of " + dataTableFullName + " (immutable)"); disableTable(admin, dataTableFullName, indexes); modifyTable(admin, dataTableFullName, indexes); } catch (IOException | SQLException e) { LOGGER.severe("Something went wrong while disabling " + "or modifying immutable table " + e); handleFailure(queryServices, dataTableFullName, immutableList); } } long startWaitTime = EnvironmentEdgeManager.currentTimeMillis(); return startWaitTime; }
Source:
public void shouldNotFireAssignmentEventOnAssigneeChangesInDeleteListener() { BpmnModelInstance model = createModelWithTaskEventsRecorderOnAssignedUserTask(TRACKED_EVENTS, null, TaskListener.EVENTNAME_DELETE, CandidateUserAssignment.class); testRule.deploy(model); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("process"); runtimeService.deleteProcessInstance(processInstance.getId(), "Canceled!"); LinkedList<String> orderedEvents = RecorderTaskListener.getOrderedEvents(); assertThat(orderedEvents.size()).isEqualTo(2); assertThat(orderedEvents.getFirst()).isEqualToIgnoringCase(TaskListener.EVENTNAME_CREATE); assertThat(orderedEvents.getLast()).isEqualToIgnoringCase(TaskListener.EVENTNAME_DELETE); }

Target:
public void shouldNotFireAssignmentEventOnAssigneeChangesInDeleteListener() { BpmnModelInstance model = createModelWithTaskEventsRecorderOnAssignedUserTask(TRACKED_EVENTS, null, TaskListener.EVENTNAME_DELETE, AssigneeAssignment.class); testRule.deploy(model); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("process"); runtimeService.deleteProcessInstance(processInstance.getId(), "Canceled!"); LinkedList<String> orderedEvents = RecorderTaskListener.getOrderedEvents(); assertThat(orderedEvents.size()).isEqualTo(2); assertThat(orderedEvents.getFirst()).isEqualToIgnoringCase(TaskListener.EVENTNAME_CREATE); assertThat(orderedEvents.getLast()).isEqualToIgnoringCase(TaskListener.EVENTNAME_DELETE); }
Source:
public void scmSourceShouldContainCorrectData() { given().when().get(VERSION_RESOURCE).then().statusCode(HttpStatus.SC_OK).body(is(new Matcher<Object>() { String error = null; @Override public boolean matches(final Object item) { try { final Map info = mapper.readValue( new ByteArrayInputStream(item.toString().getBytes()), Map.class); if (null == info) { error = "Failed to read data from version " + item; return false; } else { final Map scmSource = (Map) info.get("scm_source"); if (null == scmSource) { error = "Scm source is not specified in " + item; return false; } for (final String key : new String[]{"revision", "url", "author"}) { final String value = (String) scmSource.get(key); if (StringUtils.isEmpty(value)) { error = "field scm_source." + key + " is " + value + ", but content expected"; return false; } } if (scmSource.get("status") == null) { error = "scm_source.status field in null"; return false; } return true; } } catch (final IOException e) { error = "Failed to read versionInfo from json: " + e.getMessage(); return false; } } @Override public void describeMismatch(Object item, Description mismatchDescription) { mismatchDescription.appendText("Error: " + error + " for " + item); } @Override public void _dont_implement_Matcher___instead_extend_BaseMatcher_() { } @Override public void describeTo(Description description) { description.appendText(error); } })); }

Target:
public void scmSourceShouldContainCorrectData() { given().when().get(VERSION_RESOURCE).then() .assertThat().statusCode(HttpStatus.SC_OK) .and().assertThat().body("scm_source.revision", allOf(notNullValue(), not(""))) .and().assertThat().body("scm_source.url", allOf(notNullValue(), not(""))) .and().assertThat().body("scm_source.author", allOf(notNullValue(), not(""))) .and().assertThat().body("scm_source.status", notNullValue()); }
Source:
public void refresh() { nativeRefresh(nativePtr); invokeListenerIfSchemaChanged(); }

Target:
public void refresh() { nativeRefresh(nativePtr); invokeSchemaChangeListenerIfSchemaChanged(); }
Source:
private IAction createHierarchicalAction() { IAction action = new Action(Messages.ControlFlowView_hierarchicalViewLabel, IAction.AS_RADIO_BUTTON) { @Override public void run() { ITmfTrace parentTrace = getTrace(); synchronized (fFlatTraces) { fFlatTraces.remove(parentTrace); for (ITmfTrace trace : TmfTraceManager.getTraceSet(parentTrace)) { final ITmfStateSystem ss = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID); for (TimeGraphEntry traceEntry : getEntryList(ss)) { List<ControlFlowEntry> currentRootList = traceEntry.getChildren().stream() .filter(e -> e instanceof ControlFlowEntry) .map(e -> (ControlFlowEntry) e) .collect(Collectors.toList()); addEntriesToHierarchicalTree(currentRootList, traceEntry); } } } refresh(); } }; action.setChecked(true); action.setToolTipText(Messages.ControlFlowView_hierarchicalViewToolTip); return action; }

Target:
private IAction createHierarchicalAction() { IAction action = new Action(Messages.ControlFlowView_hierarchicalViewLabel, IAction.AS_RADIO_BUTTON) { @Override public void run() { ITmfTrace parentTrace = getTrace(); synchronized (fFlatTraces) { fFlatTraces.remove(parentTrace); List<@NonNull TimeGraphEntry> entryList = getEntryList(parentTrace); if (entryList != null) { for (TimeGraphEntry traceEntry : entryList) { addEntriesToHierarchicalTree(Iterables.filter(traceEntry.getChildren(), ControlFlowEntry.class), traceEntry); } } } refresh(); } }; action.setChecked(true); action.setToolTipText(Messages.ControlFlowView_hierarchicalViewToolTip); return action; }
Source:
public void spec307_afterSubscriptionIsCancelledAdditionalCancelationsMustBeNops_shouldFailBy_unexpectedErrorInCancelling() throws Throwable { requireTestFailure(new ThrowingRunnable() { @Override public void run() throws Throwable { customPublisherVerification(new Publisher<Integer>() { @Override public void subscribe(final Subscriber<? super Integer> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { } @Override public void cancel() { s.onError(new RuntimeException("Invalid, don't do this!")); } }); } }).spec307_afterSubscriptionIsCancelledAdditionalCancelationsMustBeNops(); } }, "Async error during test execution: Invalid, don't do this!"); }

Target:
public void spec307_afterSubscriptionIsCancelledAdditionalCancelationsMustBeNops_shouldFailBy_unexpectedErrorInCancelling() throws Throwable { requireTestFailure(new ThrowingRunnable() { @Override public void run() throws Throwable { customPublisherVerification(new Publisher<Integer>() { @Override public void subscribe(final Subscriber<? super Integer> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { } @Override public void cancel() { s.onError(new TestException()); } }); } }).spec307_afterSubscriptionIsCancelledAdditionalCancelationsMustBeNops(); } }, "Async error during test execution: Test Exception: Boom!"); }
Source:
public MetadataSchema getSchema(@PathParam("schema_prefix") String schemaPrefix, @QueryParam("expand") @DefaultValue("fields") String expand, @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, @QueryParam("xforwarderfor") String xforwarderfor, @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException { log.info("Reading metadata schemas."); org.dspace.core.Context context = null; MetadataSchema metadataSchema = null; try { context = createContext(getUser(headers)); org.dspace.content.MetadataSchema schema = metadataSchemaService.find(context, schemaPrefix); metadataSchema = new MetadataSchema(schema, expand, context); if (schema == null) { log.error(String.format("Schema not found for index %s", schemaPrefix)); throw new WebApplicationException(Response.Status.NOT_FOUND); } context.complete(); } catch (SQLException e) { processException("Could not read metadata schema, SQLException. Message:" + e, context); log.error(e.getMessage()); throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } catch (ContextException e) { processException("Could not read metadata schema, ContextException. Message:" + e.getMessage(), context); } finally { processFinally(context); } log.trace("Metadata schemas successfully read."); return metadataSchema; }

Target:
public MetadataSchema getSchema(@PathParam("schema_prefix") String schemaPrefix, @QueryParam("expand") @DefaultValue("fields") String expand, @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, @QueryParam("xforwarderfor") String xforwarderfor, @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException { log.info("Reading metadata schemas."); org.dspace.core.Context context = null; MetadataSchema metadataSchema = null; try { context = createContext(getUser(headers)); org.dspace.content.MetadataSchema schema = metadataSchemaService.find(context, schemaPrefix); metadataSchema = new MetadataSchema(schema, expand, context); if (schema == null) { processException(String.format("Schema not found for index %s", schemaPrefix), context); } context.complete(); } catch (SQLException e) { processException("Could not read metadata schema, SQLException. Message:" + e, context); } catch (ContextException e) { processException("Could not read metadata schema, ContextException. Message:" + e.getMessage(), context); } finally { processFinally(context); } log.trace("Metadata schemas successfully read."); return metadataSchema; }
Source:
public final List<JSONObject> handle(R photonRequest) { TagFilterQueryBuilder queryBuilder = buildQuery(photonRequest); Integer limit = photonRequest.getLimit(); SearchResponse results = elasticsearchSearcher.search(queryBuilder.buildQuery(), limit); if (results.getHits().getTotalHits() == 0) { results = elasticsearchSearcher.search(queryBuilder.withStrictMatch().buildQuery(), limit); } List<JSONObject> resultJsonObjects = new ConvertToJson(photonRequest.getLanguage()).convert(results); StreetDupesRemover streetDupesRemover = new StreetDupesRemover(photonRequest.getLanguage()); resultJsonObjects = streetDupesRemover.execute(resultJsonObjects); if (resultJsonObjects.size() > limit) { resultJsonObjects = resultJsonObjects.subList(0, limit); } return resultJsonObjects; }

Target:
public final List<JSONObject> handle(R photonRequest) { TagFilterQueryBuilder queryBuilder = buildQuery(photonRequest); Integer limit = photonRequest.getLimit(); SearchResponse results = elasticsearchSearcher.search(queryBuilder.buildQuery(), limit); if (results.getHits().getTotalHits() == 0) { results = elasticsearchSearcher.search(queryBuilder.withLenientMatch().buildQuery(), limit); } List<JSONObject> resultJsonObjects = new ConvertToJson(photonRequest.getLanguage()).convert(results); StreetDupesRemover streetDupesRemover = new StreetDupesRemover(photonRequest.getLanguage()); resultJsonObjects = streetDupesRemover.execute(resultJsonObjects); if (resultJsonObjects.size() > limit) { resultJsonObjects = resultJsonObjects.subList(0, limit); } return resultJsonObjects; }
Source:
public void testPopulatesInitialSeeds() throws Exception { cluster = app.createAndManageChild(EntitySpec.create(CassandraDatacenter.class) .configure(CassandraDatacenter.INITIAL_SIZE, 2) .configure(CassandraDatacenter.TOKEN_SHIFT, BigInteger.ZERO) .configure(CassandraDatacenter.DELAY_BEFORE_ADVERTISING_CLUSTER, Duration.ZERO) .configure(CassandraDatacenter.MEMBER_SPEC, EntitySpec.create(EmptySoftwareProcess.class))); app.start(ImmutableList.of(loc)); Thread.sleep(Duration.seconds(1).toMilliseconds()); EmptySoftwareProcess e1 = (EmptySoftwareProcess) Iterables.get(cluster.getMembers(), 0); EmptySoftwareProcess e2 = (EmptySoftwareProcess) Iterables.get(cluster.getMembers(), 1); EntityTestUtils.assertAttributeEqualsEventually(cluster, CassandraDatacenter.CURRENT_SEEDS, ImmutableSet.<Entity>of(e1, e2)); }

Target:
public void testPopulatesInitialSeeds() throws Exception { cluster = app.createAndManageChild(EntitySpec.create(CassandraDatacenter.class) .configure(CassandraDatacenter.INITIAL_SIZE, 2) .configure(CassandraDatacenter.TOKEN_SHIFT, BigInteger.ZERO) .configure(CassandraDatacenter.DELAY_BEFORE_ADVERTISING_CLUSTER, Duration.ZERO) .configure(CassandraDatacenter.MEMBER_SPEC, EntitySpec.create(EmptySoftwareProcess.class))); app.start(ImmutableList.of(loc)); EmptySoftwareProcess e1 = (EmptySoftwareProcess) Iterables.get(cluster.getMembers(), 0); EmptySoftwareProcess e2 = (EmptySoftwareProcess) Iterables.get(cluster.getMembers(), 1); EntityTestUtils.assertAttributeEqualsEventually(cluster, CassandraDatacenter.CURRENT_SEEDS, ImmutableSet.<Entity>of(e1, e2)); }
Source:
public AsyncDocumentClient getAsyncDocumentClient() { return asyncDocumentClient; }

Target:
AsyncDocumentClient getAsyncDocumentClient() { return asyncDocumentClient; }
Source:
public void start(Future<Void> startFuture) { PfxOptions pfxOptions = new PfxOptions().setValue(Buffer.buffer("boom")); HttpServerOptions httpServerOptions = new HttpServerOptions(); httpServerOptions .setSsl(true) .setPfxTrustOptions(pfxOptions); vertx.createHttpServer(httpServerOptions).requestHandler(req -> { req.response().end("Hello World!"); }).listen(8443, ar -> { if (ar.succeeded()) { startFuture.complete(); } else { startFuture.fail(ar.cause()); } }); }

Target:
public void start(Future<Void> startFuture) { HttpServerOptions invalidOptions = new HttpServerOptions() .setSsl(true) .setPfxTrustOptions(new PfxOptions().setValue(Buffer.buffer("boom"))); vertx.createHttpServer(invalidOptions).requestHandler(req -> { req.response().end("Hello World!"); }).listen(8443, ar -> { if (ar.succeeded()) { startFuture.complete(); } else { startFuture.fail(ar.cause()); } }); }
Source:
public void publish(String jsonMessage) { LOG.debug("Received request {}", jsonMessage); try { JsonNode messageAsNode = jsonReader.read(jsonMessage); if (messageAsNode.has("topics")) { String topicsTo = messageAsNode.get("topics").get("to").asText(); pushRequestMessage(topicsTo, jsonMessage); } } catch (IOException e) { LOG.error("Received message can not be parsed"); } }

Target:
public void publish(String jsonMessage) { LOG.debug("Received request {}", jsonMessage); try { JsonNode messageAsNode = jsonReader.read(jsonMessage); if (!messageAsNode.has("topics")) { throw new JsonSchemaValidationException(String.format("missing topics in message %s", jsonMessage)); } JsonNode topicsAsNode = messageAsNode.get("topics"); if (!topicsAsNode.has("to")) { throw new JsonSchemaValidationException(String.format("missing topics.to in message %s", jsonMessage)); } String topicsTo = topicsAsNode.get("to").asText(); pushRequestMessage(topicsTo, jsonMessage); } catch (IOException e) { LOG.error("Received message can not be parsed"); } }
Source:
private static InputStream nodeToInputStream(Node node) throws Exception { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(node), new StreamResult(outputStream)); return new ByteArrayInputStream(outputStream.toByteArray()); }

Target:
private static InputStream nodeToInputStream(Node node) throws Exception { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { TransformerFactory.newInstance().newTransformer().transform(new DOMSource(node), new StreamResult(outputStream)); return new ByteArrayInputStream(outputStream.toByteArray()); } }
Source:
public void expand(IProgressMonitor monitor) { item.setExpanded(true); refreshContent(); }

Target:
public void expand(IProgressMonitor monitor) { item.setExpanded(true); refreshContent(false, monitor); }
Source:
protected boolean hasPermission(String nxuser) { NuxeoPrincipal principal = ((NuxeoPrincipal) getContext().getCoreSession().getPrincipal()); return principal.isAdministrator() || (nxuser == null ? false : principal.getName().equals(nxuser)); }

Target:
protected boolean hasPermission(String nxuser) { NuxeoPrincipal principal = ((NuxeoPrincipal) getContext().getCoreSession().getPrincipal()); return principal.isAdministrator() || (nxuser == null ? false : nxuser.equals(principal.getName())); }
Source:
private static OptionalDouble mergeAverage(OptionalDouble first, OptionalLong firstRowCount, OptionalDouble second, OptionalLong secondRowCount) { if (first.isPresent() && second.isPresent()) { if (!(firstRowCount.isPresent() && secondRowCount.isPresent())) { return OptionalDouble.empty(); } long totalRowCount = firstRowCount.getAsLong() + secondRowCount.getAsLong(); if (totalRowCount == 0) { return OptionalDouble.empty(); } double sumFirst = first.getAsDouble() * firstRowCount.getAsLong(); double sumSecond = second.getAsDouble() * secondRowCount.getAsLong(); return OptionalDouble.of((sumFirst + sumSecond) / totalRowCount); } return first.isPresent() ? first : second; }

Target:
private static OptionalDouble mergeAverage(OptionalDouble first, OptionalLong firstRowCount, OptionalDouble second, OptionalLong secondRowCount) { if (first.isPresent() && second.isPresent()) { if (!firstRowCount.isPresent() || !secondRowCount.isPresent()) { return OptionalDouble.empty(); } long totalRowCount = firstRowCount.getAsLong() + secondRowCount.getAsLong(); if (totalRowCount == 0) { return OptionalDouble.empty(); } double sumFirst = first.getAsDouble() * firstRowCount.getAsLong(); double sumSecond = second.getAsDouble() * secondRowCount.getAsLong(); return OptionalDouble.of((sumFirst + sumSecond) / totalRowCount); } return first.isPresent() ? first : second; }
Source:
public void init(final DeleteProjectPopUpScreen presenter) { domUtil = new Elemental2DomUtil(); this.presenter = presenter; modalSetup(); }

Target:
public void init(final DeleteProjectPopUpScreen presenter) { this.presenter = presenter; modalSetup(); }
Source:
public synchronized void send(Message<?> message) throws Exception { if (this.socketOutputStream == null) { int writeBufferSize = this.socket.getSendBufferSize(); this.socketOutputStream = new BufferedOutputStream(this.socket.getOutputStream(), writeBufferSize > 0 ? writeBufferSize : 8192); } Object object = getMapper().fromMessage(message); Assert.state(object != null, "Mapper mapped the message to 'null."); this.lastSend = System.currentTimeMillis(); try { ((Serializer<Object>) getSerializer()).serialize(object, this.socketOutputStream); this.socketOutputStream.flush(); } catch (Exception e) { this.publishConnectionExceptionEvent(new MessagingException(message, "Failed TCP serialization", e)); this.closeConnection(true); throw e; } if (logger.isDebugEnabled()) { logger.debug(getConnectionId() + " Message sent " + message); } }

Target:
public synchronized void send(Message<?> message) throws Exception { if (this.socketOutputStream == null) { int writeBufferSize = this.socket.getSendBufferSize(); this.socketOutputStream = new BufferedOutputStream(this.socket.getOutputStream(), writeBufferSize > 0 ? writeBufferSize : 8192); } Object object = getMapper().fromMessage(message); Assert.state(object != null, "Mapper mapped the message to 'null'."); this.lastSend = System.currentTimeMillis(); try { ((Serializer<Object>) getSerializer()).serialize(object, this.socketOutputStream); this.socketOutputStream.flush(); } catch (Exception e) { this.publishConnectionExceptionEvent(new MessagingException(message, "Failed TCP serialization", e)); this.closeConnection(true); throw e; } if (logger.isDebugEnabled()) { logger.debug(getConnectionId() + " Message sent " + message); } }
Source:
public boolean isClusterUp() { String llapAppID = variablesFacade.getVariableValue(Settings.VARIABLE_LLAP_APP_ID); if (llapAppID == null || llapAppID.isEmpty()) { return false; } ApplicationId appId = ApplicationId.fromString(llapAppID); YarnClient yClient = yarnClientService.getYarnClientSuper(settings.getConfiguration()).getYarnClient(); ApplicationReport applicationReport = null; try { applicationReport = yClient.getApplicationReport(appId); } catch (IOException | YarnException e) { logger.log(Level.SEVERE, "Could not retrieve application state for llap cluster with appId: " + appId.toString(), e); return false; } YarnApplicationState appState = applicationReport.getYarnApplicationState(); return appState == YarnApplicationState.RUNNING || appState == YarnApplicationState.SUBMITTED || appState == YarnApplicationState.ACCEPTED || appState == YarnApplicationState.NEW || appState == YarnApplicationState.NEW_SAVING; }

Target:
public boolean isClusterUp() { String llapAppID = variablesFacade.getVariableValue(Settings.VARIABLE_LLAP_APP_ID); if (llapAppID == null || llapAppID.isEmpty()) { return false; } ApplicationId appId = ApplicationId.fromString(llapAppID); YarnClient yarnClient = yarnClientService.getYarnClientSuper(settings.getConfiguration()).getYarnClient(); ApplicationReport applicationReport = null; try { applicationReport = yarnClient.getApplicationReport(appId); } catch (IOException | YarnException e) { logger.log(Level.SEVERE, "Could not retrieve application state for llap cluster with appId: " + appId.toString(), e); return false; } finally { try { yarnClient.close(); } catch (IOException ex) } YarnApplicationState appState = applicationReport.getYarnApplicationState(); return appState == YarnApplicationState.RUNNING || appState == YarnApplicationState.SUBMITTED || appState == YarnApplicationState.ACCEPTED || appState == YarnApplicationState.NEW || appState == YarnApplicationState.NEW_SAVING; }
Source:
public void copyObject( String bucketName, String objectName, Map<String, String> headerMap, ServerSideEncryption sse, String srcBucketName, String srcObjectName, ServerSideEncryption srcSse, CopyConditions copyConditions) throws ErrorResponseException, IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidKeyException, InvalidResponseException, IOException, NoSuchAlgorithmException, XmlParserException { checkBucketName(bucketName); checkObjectName(objectName); checkWriteRequestSse(sse); try { checkBucketName(srcBucketName); } catch (InvalidBucketNameException e) { throw new IllegalArgumentException("invalid source bucket name"); } if (srcObjectName == null) { srcObjectName = objectName; } checkReadRequestSse(srcSse); if (headerMap == null) { headerMap = new HashMap<>(); } headerMap.put("x-amz-copy-source", S3Escaper.encodePath(srcBucketName + "/" + srcObjectName)); if (sse != null) { headerMap.putAll(sse.headers()); } if (srcSse != null) { headerMap.putAll(srcSse.copySourceHeaders()); } if (copyConditions != null) { headerMap.putAll(copyConditions.getConditions()); } Response response = executePut(bucketName, objectName, headerMap, null, "", 0); try (ResponseBody body = response.body()) { Xml.unmarshal(CopyObjectResult.class, body.charStream()); } }

Target:
public void copyObject( String bucketName, String objectName, Map<String, String> headerMap, ServerSideEncryption sse, String srcBucketName, String srcObjectName, ServerSideEncryption srcSse, CopyConditions copyConditions) throws ErrorResponseException, IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidKeyException, InvalidResponseException, IOException, NoSuchAlgorithmException, XmlParserException { if ((bucketName == null) || (bucketName.isEmpty())) { throw new IllegalArgumentException("bucket name cannot be empty"); } checkObjectName(objectName); checkWriteRequestSse(sse); if ((srcBucketName == null) || (srcBucketName.isEmpty())) { throw new IllegalArgumentException("Source bucket name cannot be empty"); } if (srcObjectName == null) { srcObjectName = objectName; } checkReadRequestSse(srcSse); if (headerMap == null) { headerMap = new HashMap<>(); } headerMap.put("x-amz-copy-source", S3Escaper.encodePath(srcBucketName + "/" + srcObjectName)); if (sse != null) { headerMap.putAll(sse.headers()); } if (srcSse != null) { headerMap.putAll(srcSse.copySourceHeaders()); } if (copyConditions != null) { headerMap.putAll(copyConditions.getConditions()); } Response response = executePut(bucketName, objectName, headerMap, null, "", 0); try (ResponseBody body = response.body()) { Xml.unmarshal(CopyObjectResult.class, body.charStream()); } }
Source:
public static ExtensionInfo noExtInfoSeen() { return new ExtensionInfo(Collections.emptySet()); }

Target:
public static ExtensionInfo noExtInfoSeen() { return new ExtensionInfo(Collections.<String>emptySet()); }
Source:
public ProcessingDirective process(final Item<AvroRecordBuffer> item) { final long time = System.currentTimeMillis(); try { final TrackedFile trackedFile = currentTrackedFile.get(); trackedFile.divolteFile.append(item.payload); trackedFile.recordsSinceLastSync += 1; possiblySyncAndOrRoll(time); return CONTINUE; } catch(final IOException ioe) { markFileSystemUnavailable(time); logger.error("File system connection error. Marking file system as unavailable. Attempting reconnect after " + reconnectDelay + " ms.", ioe); return PAUSE; } }

Target:
public ProcessingDirective process(final Item<AvroRecordBuffer> item) { final long nanoTime = System.nanoTime(); try { final TrackedFile trackedFile = currentTrackedFile.orElseThrow(IllegalStateException::new); trackedFile.divolteFile.append(item.payload); trackedFile.recordsSinceLastSync += 1; possiblySyncAndOrRoll(nanoTime); return CONTINUE; } catch(final IOException ioe) { markFileSystemUnavailable(nanoTime); logger.error("File system connection error. Marking file system as unavailable. Attempting reconnect after " + reconnectDelayNanos + " ns.", ioe); return PAUSE; } }
Source:
public static boolean[] validate(String[] files) throws IOException { if (files == null || files.length == 0) { throw new IllegalArgumentException("No files to validate"); } boolean[] results = new boolean[files.length]; for (int i = 0; i < files.length; i++) { String file = files[i]; if (file == null || file.trim().length() == 0) { results[i] = false; } else{ String f = file.toLowerCase(); boolean b; if (f.endsWith("tif") || f.endsWith("tiff")) { String comment = ""; try(RandomAccessInputStream stream = new RandomAccessInputStream(file)) { comment = new TiffParser(stream).getComment(); } b = validate(f, new BufferedReader(new StringReader(comment))); } else { b = validate(f, new BufferedReader(new InputStreamReader( new FileInputStream(f), Constants.ENCODING))); } results[i] = b; } } return results; }

Target:
public static boolean[] validate(String[] files) throws IOException { if (files == null || files.length == 0) { throw new IllegalArgumentException("No files to validate"); } boolean[] results = new boolean[files.length]; List<String> extensions = Arrays.asList(TiffReader.TIFF_SUFFIXES); for (int i = 0; i < files.length; i++) { String file = files[i]; if (file == null || file.trim().length() == 0) { results[i] = false; } else{ String f = file.toLowerCase(); boolean b; String extension = f.substring(f.lastIndexOf(".")+1); if (extensions.contains(extension)) { String comment = ""; try (RandomAccessInputStream stream = new RandomAccessInputStream(file)) { comment = new TiffParser(stream).getComment(); } b = validate(new BufferedReader(new StringReader(comment)), f); } else { b = validate(new BufferedReader(new InputStreamReader( new FileInputStream(f), Constants.ENCODING)), f); } results[i] = b; } } return results; }
Source:
public static OS guess() { final String osName = System.getProperty("os.name"); if (osName==null) return OS.Windows; return osName.contains("Windows") ? OS.Windows : osName.contains("Mac") ? OS.Mac : osName.contains("SunOS") ? OS.SunOS : OS.Linux; }

Target:
public static Architecture guess(){ return System.getProperty("os.arch").contains("64") ? x64 : x86; }
Source:
protected void executeQueryCommand() { Guid tryingImage = Guid.Empty; DiskImage activeDisk = findImageForDrive(SnapshotType.ACTIVE); DiskImage inactiveDisk = findImageForDrive(SnapshotType.PREVIEW);; if (getDiskImageDao().getAllForVm(getParameters().getId(), getUserID(), getParameters().isFiltered()).isEmpty() || activeDisk == null || imageBeforePreviewIsMissing(activeDisk, inactiveDisk)) { log.warnFormat("Vm {0} images data incorrect", getParameters().getId()); getQueryReturnValue().setReturnValue(new ArrayList<DiskImage>()); return; } if (inactiveDisk != null) { tryingImage = activeDisk.getParentId(); } Guid topmostImageGuid = inactiveDisk == null ? activeDisk.getId() : inactiveDisk.getId(); getQueryReturnValue().setReturnValue( ImagesHandler.getAllImageSnapshots(topmostImageGuid, activeDisk.getit_guid())); getQueryReturnValue().setTryingImage(tryingImage); }

Target:
protected void executeQueryCommand() { Guid tryingImage = Guid.Empty; DiskImage activeDisk = findImageForDrive(SnapshotType.ACTIVE); DiskImage inactiveDisk = findImageForDrive(SnapshotType.PREVIEW); if (getDiskImageDao().getAllForVm(getParameters().getId(), getUserID(), getParameters().isFiltered()).isEmpty() || activeDisk == null || imageBeforePreviewIsMissing(activeDisk, inactiveDisk)) { log.warnFormat("Vm {0} images data incorrect", getParameters().getId()); getQueryReturnValue().setReturnValue(new ArrayList<DiskImage>()); return; } if (inactiveDisk != null) { tryingImage = activeDisk.getParentId(); } Guid topmostImageGuid = inactiveDisk == null ? activeDisk.getId() : inactiveDisk.getId(); getQueryReturnValue().setReturnValue( ImagesHandler.getAllImageSnapshots(topmostImageGuid, activeDisk.getit_guid())); getQueryReturnValue().setTryingImage(tryingImage); }
Source:
protected ActionResult execute() { new GateKeeper().verifyAdminPrivileges(account); AdminEmailComposePageData data = new AdminEmailComposePageData(account); String emailContent = getRequestParamValue(Const.ParamsNames.ADMIN_EMAIL_CONTENT); String subject = getRequestParamValue(Const.ParamsNames.ADMIN_EMAIL_SUBJECT); String addressReceiverListString = getRequestParamValue(Const.ParamsNames.ADMIN_EMAIL_ADDRESS_RECEVIERS); String groupReceiverListFileKey = getRequestParamValue(Const.ParamsNames.ADMIN_EMAIL_GROUP_RECEIVER_LIST_FILE_KEY); String emailId = getRequestParamValue(Const.ParamsNames.ADMIN_EMAIL_ID); addressReceiver.add(addressReceiverListString); if(groupReceiverListFileKey != null && !groupReceiverListFileKey.isEmpty()){ groupReceiver.add(groupReceiverListFileKey); } boolean isNewDraft = emailId == null; if(isNewDraft){ createAndSaveNewDraft(subject, addressReceiver, groupReceiver, emailContent); } else { AdminEmailAttributes previousDraft = logic.getAdminEmailById(emailId); if(previousDraft == null){ createAndSaveNewDraft(subject, addressReceiver, groupReceiver, emailContent); } else { updatePreviousEmailDraft(previousDraft.getEmailId(), subject, addressReceiver, groupReceiver, emailContent); } statusToAdmin = "Email draft has been saved: <br>" + "Subject: " + subject; statusToUser.add("Email draft has been saved"); } return this.createShowPageResult(Const.ViewURIs.ADMIN_EMAIL, data); }

Target:
protected ActionResult execute() { new GateKeeper().verifyAdminPrivileges(account); AdminEmailComposePageData data = new AdminEmailComposePageData(account); String emailContent = getRequestParamValue(Const.ParamsNames.ADMIN_EMAIL_CONTENT); String subject = getRequestParamValue(Const.ParamsNames.ADMIN_EMAIL_SUBJECT); String addressReceiverListString = getRequestParamValue(Const.ParamsNames.ADMIN_EMAIL_ADDRESS_RECEVIERS); String groupReceiverListFileKey = getRequestParamValue(Const.ParamsNames.ADMIN_EMAIL_GROUP_RECEIVER_LIST_FILE_KEY); String emailId = getRequestParamValue(Const.ParamsNames.ADMIN_EMAIL_ID); addressReceiver.add(addressReceiverListString); if(groupReceiverListFileKey != null && !groupReceiverListFileKey.isEmpty()){ groupReceiver.add(groupReceiverListFileKey); } boolean isNewDraft = (emailId == null); if(isNewDraft){ createAndSaveNewDraft(subject, addressReceiver, groupReceiver, emailContent); } else { AdminEmailAttributes previousDraft = logic.getAdminEmailById(emailId); if(previousDraft == null){ createAndSaveNewDraft(subject, addressReceiver, groupReceiver, emailContent); } else { updatePreviousEmailDraft(previousDraft.getEmailId(), subject, addressReceiver, groupReceiver, emailContent); } } if(isError){ data.emailToEdit = new AdminEmailAttributes(subject, addressReceiver, groupReceiver, new Text(emailContent), null); data.emailToEdit.emailId = emailId; } else { statusToAdmin = "Email draft has been saved: <br>" + "Subject: " + subject; statusToUser.add("Email draft has been saved"); } return createShowPageResult(Const.ViewURIs.ADMIN_EMAIL, data); }
Source:
public PartIdsFromHttpResponseFull(DateService dateParser) { this.dateParser = dateParser; }

Target:
PartIdsFromHttpResponseFull(DateService dateParser) { this.dateParser = dateParser; }
Source:
public Builder(String context, Configuration conf) { if (isValid(context)) { sb.append(context); } fieldSeparator = conf.get(HADOOP_CALLER_CONTEXT_SEPARATOR_KEY, HADOOP_CALLER_CONTEXT_SEPARATOR_DEFAULT); }

Target:
public Builder(String context, Configuration conf) { if (isValid(context)) { sb.append(context); } fieldSeparator = conf.get(HADOOP_CALLER_CONTEXT_SEPARATOR_KEY, HADOOP_CALLER_CONTEXT_SEPARATOR_DEFAULT); checkFieldSeparator(fieldSeparator); }
Source:
public Iterable<String> getEdgeIds(final Direction direction, final String[] labels, final Authorizations authorizations) { getFetchHints().validateHasEdgeFetchHints(direction); return getEdgeIdsWithOtherVertexId(null, direction, labels, authorizations); }

Target:
public Iterable<String> getEdgeIds(final Direction direction, final String[] labels, final Authorizations authorizations) { getFetchHints().validateHasEdgeFetchHints(direction, labels); return getEdgeIdsWithOtherVertexId(null, direction, labels, authorizations); }
Source:
private boolean descriptionMatch(Item subject, Item candidate) { Set<String> candidateList = descriptionToProcessedList(candidate.getDescription()); Set<String> subjectList = descriptionToProcessedList(subject.getDescription()); Set<String> allCapitalisedWordsList = Sets.newHashSet(candidateList); allCapitalisedWordsList.addAll( subjectList.stream() .filter(word -> !candidateList.contains(word)) .collect(Collectors.toSet()) ); Set<String> capitalisedWordsFoundInBoth = Sets.newHashSet(subjectList); capitalisedWordsFoundInBoth.retainAll(candidateList); return (new Double(capitalisedWordsFoundInBoth.size()) / new Double(allCapitalisedWordsList.size())) > PROPORTION_CROSSOVER; }

Target:
private boolean descriptionMatch(Item subject, Item candidate) { Set<String> candidateList = descriptionToProcessedList(candidate.getDescription()); Set<String> subjectList = descriptionToProcessedList(subject.getDescription()); Set<String> allWords = Sets.union(candidateList, subjectList); Set<String> commonWords = Sets.intersection(subjectList, candidateList); double proportionOfCommonWords = (commonWords.size() + 0.0) / allWords.size(); return proportionOfCommonWords > COMMON_WORDS_PROPORTION_THRESHOLD; }
Source:
public FileInfo(FileSystem srcFs, Path sourcePath, String subDir) { this.srcFs = srcFs; this.sourcePath = sourcePath; this.cmPath = null; this.checkSum = null; this.useSourcePath = true; this.subDir = subDir; }

Target:
public FileInfo(FileSystem srcFs, Path sourcePath, String subDir) { this(srcFs, sourcePath, null, null, true, subDir); }
Source:
public void updateDevices() { mUSBMonitor.dumpDevices(); final List<DeviceFilter> filter = DeviceFilter.getDeviceFilters(getActivity(), R.xml.uvc_device_filter); mDeviceListAdapter = new DeviceListAdapter(getActivity(), mUSBMonitor.getDeviceList(filter.get(0))); mSpinner.setAdapter(mDeviceListAdapter); }

Target:
public void updateDevices() { if (getActivity() != null && mUSBMonitor != null){ final List<DeviceFilter> filter = DeviceFilter.getDeviceFilters(getActivity(), R.xml.uvc_device_filter); if (!filter.isEmpty()){ mDeviceListAdapter = new DeviceListAdapter(getActivity(), mUSBMonitor.getDeviceList(filter.get(0))); mSpinner.setAdapter(mDeviceListAdapter); } } }
Source:
boolean supportsTarget(ILaunchDescriptor descriptor, IRemoteConnection target) throws CoreException { String descriptorTypeId = getDescriptorTypeId(descriptor.getType()); for (LaunchConfigProviderInfo provider : configProviders.get(descriptorTypeId)) { try { Ternary supports = provider.getProvider().supports(descriptor, target); if (supports == Ternary.TRUE) { return true; } if (supports == Ternary.FALSE) { return false; } } catch (Throwable e) { Activator.log(e); } } return false; }

Target:
boolean supportsTarget(ILaunchDescriptor descriptor, IRemoteConnection target) throws CoreException { String descriptorTypeId = getDescriptorTypeId(descriptor.getType()); for (LaunchConfigProviderInfo provider : configProviders.get(descriptorTypeId)) { try { if (provider.getProvider().supports(descriptor, target)) { return true; } } catch (Throwable e) { Activator.log(e); } } return false; }
Source:
public View getView(Context context) { super.getView(context); ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter .createFromResource(context, R.array.ev3_stop_motor_chooser, android.R.layout.simple_spinner_item); spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner spinner = view.findViewById(R.id.stop_motor_spinner); spinner.setAdapter(spinnerAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) { motor = Motor.values()[position].name(); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); spinner.setSelection(Motor.valueOf(motor).ordinal()); return view; }

Target:
public View getView(Context context) { super.getView(context); ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter .createFromResource(context, R.array.nxt_stop_motor_chooser, android.R.layout.simple_spinner_item); spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner spinner = view.findViewById(R.id.stop_motor_spinner); spinner.setAdapter(spinnerAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) { motor = Motor.values()[position].name(); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); spinner.setSelection(Motor.valueOf(motor).ordinal()); return view; }
Source:
private void hotSetMemory(int newAmountOfMemory) { int currentMemory = getVm().getMemSizeMb(); if (getVm().getStatus() == VMStatus.Down) { newVmStatic.setMemSizeMb(newAmountOfMemory); return; } if (getVm().getStatus() == VMStatus.Up && currentMemory != newAmountOfMemory) { HotSetAmountOfMemoryParameters params = new HotSetAmountOfMemoryParameters( newVmStatic, currentMemory < newAmountOfMemory ? PlugAction.PLUG : PlugAction.UNPLUG, 0); VdcReturnValueBase setAmountOfMemoryResult = runInternalAction( VdcActionType.HotSetAmountOfMemory, params, cloneContextAndDetachFromParent()); newVmStatic.setMemSizeMb(setAmountOfMemoryResult.getSucceeded() ? newAmountOfMemory : currentMemory); hotSetMemlog(params, setAmountOfMemoryResult); return; } newVmStatic.setMemSizeMb(currentMemory); }

Target:
private void hotSetMemory(int newAmountOfMemory) { int currentMemory = getVm().getMemSizeMb(); HotSetAmountOfMemoryParameters params = new HotSetAmountOfMemoryParameters( newVmStatic, currentMemory < newAmountOfMemory ? PlugAction.PLUG : PlugAction.UNPLUG, 0); VdcReturnValueBase setAmountOfMemoryResult = runInternalAction( VdcActionType.HotSetAmountOfMemory, params, cloneContextAndDetachFromParent()); newVmStatic.setMemSizeMb(setAmountOfMemoryResult.getSucceeded() ? newAmountOfMemory : currentMemory); hotSetMemlog(params, setAmountOfMemoryResult); }
Source:
default public D build(Stream<UpstreamEntry<K, V>> upstreamData, long upstreamDataSize, C ctx) { return build(upstreamData.iterator(), upstreamDataSize, ctx); }

Target:
public default D build(Stream<UpstreamEntry<K, V>> upstreamData, long upstreamDataSize, C ctx) { return build(upstreamData.iterator(), upstreamDataSize, ctx); }
Source:
public HandlerResult handle(ProcessState state, ProcessInstance process) { Instance instance = (Instance) state.getResource(); if (instance == null) { return null; } ServiceExposeMap smap = objectManager.findAny(ServiceExposeMap.class, SERVICE_EXPOSE_MAP.INSTANCE_ID, instance.getId(), SERVICE_EXPOSE_MAP.REMOVED, null); if (smap == null) { return null; } Service service = getObjectManager().loadResource(Service.class, smap.getServiceId()); if (service == null) { return null; } List<Service> activeLbServices = lookupAllActiveLBServices(service); List<? extends Instance> lbInstances = getLBServiceInstances(activeLbServices); for (Instance lbInstance : lbInstances) { for (InstanceHostMap ihm : mapDao.findNonPurged(InstanceHostMap.class, Instance.class, lbInstance.getId())) { Object agentResource = getObjectByRelationship("host", ihm); if (ObjectUtils.getRemoved(agentResource) != null) continue; RemoteAgent agent = agentLocator.lookupAgent(agentResource); if (agent == null) continue; handleEvent(state, process, ihm, ihm, agentResource, agent); } } return null; }

Target:
public HandlerResult handle(ProcessState state, ProcessInstance process) { Instance instance = (Instance) state.getResource(); if (instance == null) { return null; } ServiceExposeMap smap = objectManager.findAny(ServiceExposeMap.class, SERVICE_EXPOSE_MAP.INSTANCE_ID, instance.getId(), SERVICE_EXPOSE_MAP.REMOVED, null); if (smap == null) { return null; } Service service = getObjectManager().loadResource(Service.class, smap.getServiceId()); if (service == null) { return null; } List<Service> activeLbServices = lookupAllActiveLBServices(service); List<? extends Instance> lbInstances = getLBServiceInstances(activeLbServices); for (Instance lbInstance : lbInstances) { RemoteAgent agent = agentLocator.lookupAgent(lbInstance); if (agent == null) continue; handleEvent(state, process, instance, instance, lbInstance, agent); } return null; }
Source:
public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { if(gadgetsLoaded) { return new ItemStack(TinkerGadgets.throwball, 1, ItemThrowball.ThrowballType.GLOW.ordinal()); } return null; }

Target:
public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { if(TinkerGadgets.throwball != null) { return new ItemStack(TinkerGadgets.throwball, 1, ItemThrowball.ThrowballType.GLOW.ordinal()); } return null; }