auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Set<SourceDescriptor> getFederatedSourceDescriptors( Collection<FederatedSource> sources, boolean addCatalogProviderDescriptor) { SourceDescriptorImpl sourceDescriptor; Set<SourceDescriptor> sourceDescriptors = new TreeSet<>(new SourceDescriptorComparator()); if (sources != null) { for (Source source : sources) { if (source != null) { String sourceId = source.getId(); LOGGER.debug("adding sourceId: {}", sourceId); final Set<ContentType> cachedContentTypes; final Optional<Set<ContentType>> contentTypesOptional = contentTypesCache.getCachedValueForSource(source); if (contentTypesOptional.isPresent()) { cachedContentTypes = contentTypesOptional.get(); } else { LOGGER.debug("Unknown ContentTypes for source id={}", sourceId); cachedContentTypes = Collections.emptySet(); } sourceDescriptor = new SourceDescriptorImpl( sourceId, cachedContentTypes, sourceActionRegistry.list(source)); sourceDescriptor.setVersion(source.getVersion()); sourceDescriptor.setAvailable(isSourceAvailable(source)); sourceDescriptors.add(sourceDescriptor); } } } if (addCatalogProviderDescriptor) { addCatalogSourceDescriptor(sourceDescriptors); } return sourceDescriptors; }

Target:
private Set<SourceDescriptor> getFederatedSourceDescriptors( Collection<FederatedSource> sources, boolean addCatalogProviderDescriptor) { SourceDescriptorImpl sourceDescriptor; Set<SourceDescriptor> sourceDescriptors = new TreeSet<>(new SourceDescriptorComparator()); if (sources != null) { for (Source source : sources) { if (source != null) { String sourceId = source.getId(); LOGGER.debug("adding sourceId: {}", sourceId); sourceDescriptor = new SourceDescriptorImpl( sourceId, contentTypesCache .getCachedValueForSource(source) .orElseGet( () -> { LOGGER.debug("Unknown content types for source id={}", source.getId()); return Collections.emptySet(); }), sourceActionRegistry.list(source)); sourceDescriptor.setVersion(source.getVersion()); sourceDescriptor.setAvailable(isSourceAvailable(source)); sourceDescriptors.add(sourceDescriptor); } } } if (addCatalogProviderDescriptor) { addCatalogSourceDescriptor(sourceDescriptors); } return sourceDescriptors; }
Source:
public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("UniformChoice("); for (Object item : s) { buffer.append(item.toString() + ", "); } buffer.replace(buffer.length() - 2, buffer.length(), ""); buffer.append(")"); return buffer.toString(); }

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("UniformChoice("); for (Object item : s) { builder.append(item.toString() + ", "); } builder.replace(builder.length() - 2, builder.length(), ""); builder.append(")"); return builder.toString(); }
Source:
private DataStore findDataStore(VirtualMachineProfile profile, DeployDestination dest) { DataStore dataStore = null; if (VirtualMachineManager.VmConfigDriveOnPrimaryPool.value()) { final List<VolumeVO> volumes = _volumeDao.findByInstanceAndType(profile.getVirtualMachine().getId(), Volume.Type.ROOT); if (volumes != null && volumes.size() > 0) { dataStore = _dataStoreMgr.getDataStore(volumes.get(0).getPoolId(), DataStoreRole.Primary); } } else { dataStore = _dataStoreMgr.getImageStore(dest.getDataCenter().getId()); } return dataStore; }

Target:
private DataStore findDataStore(VirtualMachineProfile profile, DeployDestination dest) { DataStore dataStore = null; if (VirtualMachineManager.VmConfigDriveOnPrimaryPool.value()) { if(MapUtils.isNotEmpty(dest.getStorageForDisks())) { dataStore = getPlannedDataStore(dest, dataStore); } if (dataStore == null) { dataStore = pickExistingRootVolumeFromDataStore(profile, dataStore); } } else { dataStore = _dataStoreMgr.getImageStore(dest.getDataCenter().getId()); } return dataStore; }
Source:
private Map<String, CommentInfo[]> listDrafts(final PatchSet.Id id, IProgressMonitor monitor) throws GerritException { String uri = "/changes/" + id.getParentKey().get() + "/revisions/" + id.get() + "/drafts/"; TypeToken<Map<String, CommentInfo[]>> resultType = new TypeToken<Map<String, CommentInfo[]>>() { }; return request(HttpMethod.GET, uri, null, resultType.getType(), null, monitor); }

Target:
private Map<String, CommentInfo[]> listDrafts(final PatchSet.Id id, IProgressMonitor monitor) throws GerritException { String uri = "/changes/" + id.getParentKey().get() + "/revisions/" + id.get() + "/drafts/"; TypeToken<Map<String, CommentInfo[]>> resultType = new TypeToken<Map<String, CommentInfo[]>>() { }; return request(client.new GetRequest<Map<String, CommentInfo[]>>(uri, resultType.getType(), null), monitor); }
Source:
public void visitVariable(VariableTree tree) { if (isSlingQuery(tree)) { slingQueries.put(tree.simpleName().name(), slingQueryStates.NOTUSED); slingQueryName = tree.simpleName().name(); } super.visitVariable(tree); if (findWasUsedOnSlingQuery()) { context.reportIssue(this, tree, RULE_MESSAGE); slingQueries.put(slingQueryName, slingQueryStates.ISSUERETURNED); } }

Target:
public void visitVariable(VariableTree tree) { if (isSlingQuery(tree)) { slingQueries.put(tree.simpleName().name(), SlingQueryStates.NOT_USED); currentSlingQueryVariableName = tree.simpleName().name(); } super.visitVariable(tree); reportIssueIfStrategyNotUsed(tree, currentSlingQueryVariableName); }
Source:
protected <T> TransactionManager getTransactionManager(T resource) { if (resource instanceof HotRodOperations.HotRodCache) { return ((HotRodOperations.HotRodCache) resource).noReturn.getTransactionManager(); } else { throw new IllegalArgumentException("Invalid resource: " + String.valueOf(resource)); } }

Target:
protected <T> TransactionManager getTransactionManager(T resource) { return ((HotRodOperations.HotRodCache) resource).noReturn.getTransactionManager(); }
Source:
private void sendTcpPollingEvent() { if (isValidationRequired()) { sendMessageDelayed(EVENT_POLL_TCPINFO, getTcpPollingInterval()); } }

Target:
void sendTcpPollingEvent() { if (isValidationRequired()) { sendMessageDelayed(EVENT_POLL_TCPINFO, getTcpPollingInterval()); } }
Source:
ViewerColumn<E,I> getViewerColumn(final int columnIndex) { ViewerColumn<E,I> viewer; Widget columnOwner = getColumnViewerOwner(columnIndex); if (columnOwner == null || columnOwner.isDisposed()) { return null; } viewer = (ViewerColumn<E,I>) columnOwner .getData(ViewerColumn.COLUMN_VIEWER_KEY); if (viewer == null) { viewer = createViewerColumn(columnOwner, CellLabelProvider .createViewerLabelProvider(this, getLabelProvider())); setupEditingSupport(columnIndex, viewer); } if (viewer.getEditingSupport() == null && getCellModifier() != null) { setupEditingSupport(columnIndex, viewer); } return viewer; }

Target:
ViewerColumn<E,I> getViewerColumn(final int columnIndex) { Widget columnOwner = getColumnViewerOwner(columnIndex); if (columnOwner == null || columnOwner.isDisposed()) { return null; } @SuppressWarnings("unchecked") ViewerColumn<E, I> viewer = (ViewerColumn<E, I>) columnOwner .getData(ViewerColumn.COLUMN_VIEWER_KEY); if (viewer == null) { viewer = createViewerColumn(columnOwner, CellLabelProvider.createViewerLabelProvider(this, getLabelProvider())); setupEditingSupport(columnIndex, viewer); } if (viewer.getEditingSupport() == null && getCellModifier() != null) { setupEditingSupport(columnIndex, viewer); } return viewer; }
Source:
public void create() { Boolean embedded = Boolean.parseBoolean(env.get("solr.embedded", "false")); String solrCore = env.get("solr.core", "mamute"); String solrHome = env.get("solr.home", ""); String remoteUrl = env.get("solr.url", ""); if (embedded) { LOGGER.info("Starting embedded Solr"); String home = solrHome; if (isEmpty(home)) { String locale = env.get("locale", "en"); LOGGER.info("Using default home, with locale ["+locale+"]"); home = env.getResource("/solr/"+locale).getPath(); } CoreContainer coreContainer = new CoreContainer(home); coreContainer.load(); server = new EmbeddedSolrServer(coreContainer, solrCore); } else if (isNotEmpty(remoteUrl)) { LOGGER.info("Connecting to external Solr at [" + remoteUrl + "]"); server = new HttpSolrServer(remoteUrl); } else { LOGGER.warn("Solr config options not valid, not initting"); } }

Target:
public void create() { Boolean embedded = Boolean.parseBoolean(env.get("solr.embedded", "false")); String solrCore = env.get("solr.core", "mamute"); String solrHome = env.get("solr.home", ""); String remoteUrl = env.get("solr.url", ""); if (embedded) { LOGGER.info("Starting embedded Solr"); String home = solrHome; if (isEmpty(home)) { String locale = env.get("locale"); LOGGER.info("Using default home, with locale ["+locale+"]"); home = env.getResource("/solr/"+locale).getPath(); } CoreContainer coreContainer = new CoreContainer(home); coreContainer.load(); server = new EmbeddedSolrServer(coreContainer, solrCore); } else if (isNotEmpty(remoteUrl)) { LOGGER.info("Connecting to external Solr at [" + remoteUrl + "]"); server = new HttpSolrServer(remoteUrl); } else { LOGGER.warn("Solr config options not valid, not initting"); } }
Source:
private void updateUserInfoList() { UsersInfo usersInfo = this.config.getUsersInfo(); if(usersInfo.getDefaultAfterDate() == null && usersInfo.getDefaultBeforeDate() == null) { return; } DateTime defaultAfterDate = usersInfo.getDefaultAfterDate(); DateTime defaultBeforeDate = usersInfo.getDefaultBeforeDate(); for(UserId user : usersInfo.getUserIds()) { if(defaultAfterDate != null && user.getAfterDate() == null) { user.setAfterDate(defaultAfterDate); } if(defaultBeforeDate != null && user.getBeforeDate() == null) { user.setBeforeDate(defaultBeforeDate); } } }

Target:
private void updateUserInfoList() { UsersInfo usersInfo = this.config.getUsersInfo(); if(usersInfo.getDefaultAfterDate() == null && usersInfo.getDefaultBeforeDate() == null) { return; } DateTime defaultAfterDate = usersInfo.getDefaultAfterDate(); DateTime defaultBeforeDate = usersInfo.getDefaultBeforeDate(); for(User user : usersInfo.getUsers()) { if(defaultAfterDate != null && user.getAfterDate() == null) { user.setAfterDate(defaultAfterDate); } if(defaultBeforeDate != null && user.getBeforeDate() == null) { user.setBeforeDate(defaultBeforeDate); } } }
Source:
public void testAllowSettingHaOnNonHostedEngine() { prepareVmToPassCanDoAction(); group.setCompatibilityVersion(Version.v3_3); vm.setOrigin(OriginType.RHEV); vmStatic.setOrigin(OriginType.RHEV); command.getParameters().getVm().setAutoStartup(true); Map<Integer, Map<Version, List<Pair<GraphicsType, DisplayType>>>> displayTypeMap = new HashMap<>(); displayTypeMap.put(0, new HashMap<Version, List<Pair<GraphicsType, DisplayType>>>()); displayTypeMap.get(0).put(Version.v3_3, Arrays.asList(new Pair<>(GraphicsType.SPICE, DisplayType.qxl))); when(osRepository.getGraphicsAndDisplays()).thenReturn(displayTypeMap); doReturn(true).when(osRepository).isBalloonEnabled(vm.getVmOsId(), group.getCompatibilityVersion()); boolean validInput = command.canDoAction(); assertTrue(validInput); }

Target:
public void testAllowSettingHaOnNonHostedEngine() { prepareVmToPassCanDoAction(); vm.setOrigin(OriginType.RHEV); vmStatic.setOrigin(OriginType.RHEV); command.getParameters().getVm().setAutoStartup(true); boolean validInput = command.canDoAction(); assertTrue(validInput); }
Source:
public P create(I id) { P projection = super.create(id); lifecycleOf(id).onCreateEntity(PROJECTION); return projection; }

Target:
public P create(I id) { P projection = super.create(id); lifecycleOf(id).onEntityCreated(PROJECTION); return projection; }
Source:
public String toString() { return new StringJoiner(", ", getClass().getSimpleName() + '[', "]") .add("path = " + path) .add("children = " + children) .add("fileCount = " + fileCount) .toString(); }

Target:
public String toString() { return String.format("FileNodeViewModel{path=%s, children=%s, fileCount=%s}", this.path, this.children, this.fileCount); }
Source:
public static F.Promise<Result> update(final String queryCountString) { return getRandomWorlds(queryCount(queryCountString)).flatMap(new F.Function<List<World>, F.Promise<Result>>() { @Override public F.Promise<Result> apply(List<World> worlds) throws Throwable { return updateWorlds(worlds); } }); }

Target:
public static F.Promise<Result> update(final String queryCountString) { return getRandomWorlds(queryCount(queryCountString)).map(new F.Function<List<World>, Result>() { @Override public Result apply(List<World> worlds) throws Throwable { Random random = ThreadLocalRandom.current(); for (World world : worlds) { world.randomNumber = (long) (random.nextInt(10000) + 1); } List<World> updatedWorlds = World.save(worlds); return ok(Json.toJson(updatedWorlds)); } }, dbEc); }
Source:
private void auditVmOnRebooting() { AuditLogableBase logable = Injector.injectMembers(new AuditLogableBase(vdsManager.getVdsId(), getVmId())); logable.addCustomValue("Details", "Rebooting from the Guest OS"); auditLog(logable, AuditLogType.VM_REBOOT); }

Target:
private void auditVmOnRebooting() { AuditLogableBase logable = Injector.injectMembers(new AuditLogableBase(vdsManager.getVdsId(), getVmId())); logable.addCustomValue("UserName", String.format("%s", dbVm.getConsoleCurrentUserName())); auditLog(logable, AuditLogType.USER_REBOOT_VM); }
Source:
public T create(@Nullable final Environment sourceEnv) throws InfrastructureException, ValidationException { Map<String, InternalMachineConfig> machines = new HashMap<>(); List<Warning> warnings = new ArrayList<>(); InternalRecipe recipe = null; if (sourceEnv != null) { recipe = recipeRetriever.getRecipe(sourceEnv.getRecipe()); for (Map.Entry<String, ? extends MachineConfig> machineEntry : sourceEnv.getMachines().entrySet()) { MachineConfig machineConfig = machineEntry.getValue(); List<Installer> installers; try { installers = installerRegistry.getOrderedInstallers(machineConfig.getInstallers()); } catch (InstallerException e) { throw new InfrastructureException(e); } InternalMachineConfig internalMachineConfig = new InternalMachineConfig( installers, normalizeServers(machineConfig.getServers()), machineConfig.getEnv(), machineConfig.getAttributes(), machineConfig.getVolumes()); internalMachineConfig.getAttributes().put(CONTAINER_SOURCE_ATTRIBUTE, RECIPE); machines.put(machineEntry.getKey(), internalMachineConfig); } machinesValidator.validate(machines); } return doCreate(recipe, machines, warnings); }

Target:
public T create(@Nullable final Environment sourceEnv) throws InfrastructureException, ValidationException { Map<String, InternalMachineConfig> machines = new HashMap<>(); List<Warning> warnings = new ArrayList<>(); InternalRecipe recipe = null; if (sourceEnv != null) { recipe = recipeRetriever.getRecipe(sourceEnv.getRecipe()); for (Map.Entry<String, ? extends MachineConfig> machineEntry : sourceEnv.getMachines().entrySet()) { MachineConfig machineConfig = machineEntry.getValue(); List<Installer> installers; try { installers = installerRegistry.getOrderedInstallers(machineConfig.getInstallers()); } catch (InstallerException e) { throw new InfrastructureException(e); } machines.put( machineEntry.getKey(), new InternalMachineConfig( installers, normalizeServers(machineConfig.getServers()), machineConfig.getEnv(), machineConfig.getAttributes(), machineConfig.getVolumes())); } machinesValidator.validate(machines); } T internalEnv = doCreate(recipe, machines, warnings); internalEnv .getMachines() .values() .forEach(m -> m.getAttributes().put(CONTAINER_SOURCE_ATTRIBUTE, RECIPE_CONTAINER_SOURCE)); return internalEnv; }
Source:
public void testIsValid() { LocalTime future = LocalTime.now().plusHours( 1 ); LocalTime past = LocalTime.now().minusHours( 1 ); assertTrue( constraint.isValid( null, null ) ); assertTrue( constraint.isValid( past, null ) ); assertFalse( constraint.isValid( future, null ) ); }

Target:
public void testIsValid() { LocalTime now = LocalTime.now(); int currentHour = now.getHour(); int currentMinute = now.getMinute(); LocalTime future = now.plusMinutes( 1 ); LocalTime past = now.minusMinutes( 1 ); assertTrue( constraint.isValid( null, null ), "null fails validation." ); if (!(currentHour == 0 && currentMinute == 0)) { assertTrue( constraint.isValid( past, null ), "Past LocalTime '" + past + "' fails validation."); } if (!(currentHour == 23 && currentMinute == 59)) { assertFalse( constraint.isValid( future, null ), "Future LocalDateTime '" + future + "' validated as past."); } }
Source:
public String toString() { return Objects.toStringHelper(this.getClass()) .add("status", status) .add("host", host) .toString(); }

Target:
public String toString() { return Objects.toStringHelper(getClass()) .add("status", status) .add("host", host) .toString(); }
Source:
public String transform(StructuredRecord structuredRecord) throws IOException { StringBuilder builder = new StringBuilder(); List<Schema.Field> fields = structuredRecord.getSchema().getFields(); builder.append(getFieldAsString(structuredRecord.get(fields.get(0).getName()))); for (int index = 1; index < fields.size(); index++) { builder.append(delimiter); builder.append(getFieldAsString(structuredRecord.get(fields.get(index).getName()))); } return builder.toString(); }

Target:
public String transform(StructuredRecord structuredRecord) throws IOException { StringBuilder builder = new StringBuilder(); Iterator<Schema.Field> fieldIterator = structuredRecord.getSchema().getFields().iterator(); if (fieldIterator.hasNext()) { builder.append(getFieldAsString(structuredRecord.get(fieldIterator.next().getName()))); } while (fieldIterator.hasNext()) { builder.append(delimiter); builder.append(getFieldAsString(structuredRecord.get(fieldIterator.next().getName()))); } return builder.toString(); }
Source:
public static List<Concept> conceptListHelper(String descriptor) { List<Concept> ret = new ArrayList<>(); if (descriptor == null || descriptor.length() == 0) { return ret; } ConceptService cs = Context.getConceptService(); Set<Concept> conceptSet = new HashSet<>(); for (StringTokenizer st = new StringTokenizer(descriptor, "|"); st.hasMoreTokens();) { String s = st.nextToken().trim(); boolean isSet = s.startsWith("set:"); if (isSet) { s = s.substring(4).trim(); } Concept c = null; if (s.startsWith("name:")) { String name = s.substring(5).trim(); c = cs.getConceptByName(name); } else { try { c = cs.getConcept(Integer.valueOf(s.trim())); } catch (Exception ex) } if (c != null) { if (isSet) { List<Concept> inSet = cs.getConceptsByConceptSet(c); conceptSet.addAll(inSet); } else { conceptSet.add(c); } } } for( Concept c: conceptSet) { ret.add(c); } return ret; }

Target:
public static List<Concept> conceptListHelper(String descriptor) { List<Concept> ret = new ArrayList<>(); if (descriptor == null || descriptor.length() == 0) { return ret; } ConceptService cs = Context.getConceptService(); Set<Concept> conceptSet = new HashSet<>(); for (StringTokenizer st = new StringTokenizer(descriptor, "|"); st.hasMoreTokens();) { String s = st.nextToken().trim(); boolean isSet = s.startsWith("set:"); if (isSet) { s = s.substring(4).trim(); } Concept c = null; if (s.startsWith("name:")) { String name = s.substring(5).trim(); c = cs.getConceptByName(name); } else { try { c = cs.getConcept(Integer.valueOf(s.trim())); } catch (Exception ex) } if (c != null) { if (isSet) { List<Concept> inSet = cs.getConceptsByConceptSet(c); conceptSet.addAll(inSet); } else { conceptSet.add(c); } } } for( Concept concept: conceptSet) { ret.add(concept); } return ret; }
Source:
public String[] getSourceTranslations() { try { List<String> sources = new ArrayList<>(); JSONArray sourceTranslationsJson = manifest.getJSONArray(FIELD_SOURCE_TRANSLATIONS); for (int i = 0; i < sourceTranslationsJson.length(); i++) { JSONObject obj = sourceTranslationsJson.getJSONObject(i); String sourceLanguageSlug = obj.getString(LANGUAGE_ID); String resourceSlug = obj.getString(RESOURCE_ID); SourceTranslation sourceTranslation = SourceTranslation.simple(this.projectId,sourceLanguageSlug,resourceSlug); sources.add(sourceTranslation.getId()); } return sources.toArray(new String[sources.size()]); } catch(Exception e) { Logger.e(TAG, "Error reading sources", e); } return null; }

Target:
public String[] getSourceTranslations() { try { List<String> sources = new ArrayList<>(); JSONArray sourceTranslationsJson = manifest.getJSONArray(FIELD_SOURCE_TRANSLATIONS); for (int i = 0; i < sourceTranslationsJson.length(); i++) { JSONObject obj = sourceTranslationsJson.getJSONObject(i); String sourceLanguageSlug = obj.getString(LANGUAGE_ID); String resourceSlug = obj.getString(RESOURCE_ID); SourceTranslation sourceTranslation = SourceTranslation.simple(this.projectId,sourceLanguageSlug,resourceSlug); sources.add(sourceTranslation.getId()); } return sources.toArray(new String[sources.size()]); } catch(Exception e) { Logger.e(TAG, "Error reading sources", e); } return new String[0]; }
Source:
public static Map<String, IAnalysisModule> getAnalysisModules() { if (fAnalysisModules.isEmpty()) { TmfAnalysisType analysis = TmfAnalysisType.getInstance(); List<IAnalysisModule> modules = analysis.getAnalysisModules(); for (IAnalysisModule module : modules) { fAnalysisModules.add(module); } } return getExecutableModules(); }

Target:
public static Map<String, IAnalysisModule> getAnalysisModules() { synchronized (fAnalysisModules) { if (fAnalysisModules.isEmpty()) { TmfAnalysisType analysis = TmfAnalysisType.getInstance(); List<IAnalysisModule> modules = analysis.getAnalysisModules(); for (IAnalysisModule module : modules) { fAnalysisModules.add(module); } } } return getExecutableModules(); }
Source:
public String postForToken(@FormParam("grant_type") String grantType, @FormParam("username") String username, @FormParam("password") String password, @FormParam("client_id") String clientId) { if (!allowedGrantTypes.contains(grantType)) { Response response = Response.status(Status.METHOD_NOT_ALLOWED) .build(); throw new WebApplicationException(response); } Model model = new ModelImpl(emf); try { AgencyAttribute attributeValue = new AgencyAttribute(model.getKernel() .getLogin()); attributeValue.setTextValue(username); List<Agency> agencies = model.find(attributeValue); if (agencies.size() > 1) { log.error(String.format("Multiple agencys with username %s", username)); throw new WebApplicationException(Status.UNAUTHORIZED); } if (agencies.size() == 0) { log.warn(String.format("Attempt to login from non existent username %s", username)); throw new WebApplicationException(Status.UNAUTHORIZED); } CoreUser user = (CoreUser) model.wrap(CoreUser.class, agencies.get(0)); if (!user.authenticate(password)) { log.warn(String.format("Invalid attempt to login from username %s", username)); throw new WebApplicationException(Status.UNAUTHORIZED); } return generateToken(user, model).getId() .toString(); } finally { model.getEntityManager() .close(); } }

Target:
public String postForToken(@FormParam("grant_type") String grantType, @FormParam("username") String username, @FormParam("password") String password, @FormParam("client_id") String clientId) { if (!allowedGrantTypes.contains(grantType)) { Response response = Response.status(Status.METHOD_NOT_ALLOWED) .build(); throw new WebApplicationException(response); } Model model = new ModelImpl(emf); try { AgencyAttribute attributeValue = new AgencyAttribute(model.getKernel() .getLogin()); attributeValue.setTextValue(username); List<Agency> agencies = model.find(attributeValue); if (agencies.size() > 1) { log.error(String.format("Multiple agencies with username %s", username)); throw new WebApplicationException(Status.UNAUTHORIZED); } if (agencies.size() == 0) { log.warn(String.format("Attempt to login from non existent username %s", username)); throw new WebApplicationException(Status.UNAUTHORIZED); } CoreUser user = (CoreUser) model.wrap(CoreUser.class, agencies.get(0)); if (!user.authenticate(password)) { log.warn(String.format("Invalid attempt to login from username %s", username)); throw new WebApplicationException(Status.UNAUTHORIZED); } return generateToken(user, model).getId() .toString(); } finally { model.getEntityManager() .close(); } }
Source:
private String serializeDefinition(StoredWorkflowDefinition storedDefinition) { try { return nflowObjectMapper.writeValueAsString(storedDefinition); } catch (JsonProcessingException e) { throw new RuntimeException("Failed to serialize workflow definition " + storedDefinition.type); } }

Target:
private String serializeDefinition(StoredWorkflowDefinition storedDefinition) { try { return nflowObjectMapper.writeValueAsString(storedDefinition); } catch (JsonProcessingException e) { throw new RuntimeException("Failed to serialize workflow definition " + storedDefinition.type, e); } }
Source:
public String toString() { return "KinesisSupervisorTuningConfig{" + "maxRowsInMemory=" + getMaxRowsInMemory() + ", maxRowsPerSegment=" + getMaxRowsPerSegment() + ", intermediatePersistPeriod=" + getIntermediatePersistPeriod() + ", basePersistDirectory=" + getBasePersistDirectory() + ", maxPendingPersists=" + getMaxPendingPersists() + ", indexSpec=" + getIndexSpec() + ", buildV9Directly=" + true + ", reportParseExceptions=" + isReportParseExceptions() + ", handoffConditionTimeout=" + getHandoffConditionTimeout() + ", resetOffsetAutomatically=" + isResetOffsetAutomatically() + ", skipSequenceNumberAvailabilityCheck=" + isSkipSequenceNumberAvailabilityCheck() + ", workerThreads=" + workerThreads + ", chatThreads=" + chatThreads + ", chatRetries=" + chatRetries + ", httpTimeout=" + httpTimeout + ", shutdownTimeout=" + shutdownTimeout + ", recordBufferSize=" + getRecordBufferSize() + ", recordBufferOfferTimeout=" + getRecordBufferOfferTimeout() + ", recordBufferFullWait=" + getRecordBufferFullWait() + ", fetchSequenceNumberTimeout=" + getFetchSequenceNumberTimeout() + ", fetchThreads=" + getFetchThreads() + ", segmentWriteOutMediumFactory=" + getSegmentWriteOutMediumFactory() + '}'; }

Target:
public String toString() { return "KinesisSupervisorTuningConfig{" + "maxRowsInMemory=" + getMaxRowsInMemory() + ", maxBytesInMemory=" + getMaxBytesInMemory() + ", maxRowsPerSegment=" + getMaxRowsPerSegment() + ", maxTotalRows=" + getMaxTotalRows() + ", intermediatePersistPeriod=" + getIntermediatePersistPeriod() + ", basePersistDirectory=" + getBasePersistDirectory() + ", maxPendingPersists=" + getMaxPendingPersists() + ", indexSpec=" + getIndexSpec() + ", reportParseExceptions=" + isReportParseExceptions() + ", handoffConditionTimeout=" + getHandoffConditionTimeout() + ", resetOffsetAutomatically=" + isResetOffsetAutomatically() + ", skipSequenceNumberAvailabilityCheck=" + isSkipSequenceNumberAvailabilityCheck() + ", workerThreads=" + workerThreads + ", chatThreads=" + chatThreads + ", chatRetries=" + chatRetries + ", httpTimeout=" + httpTimeout + ", shutdownTimeout=" + shutdownTimeout + ", recordBufferSize=" + getRecordBufferSize() + ", recordBufferOfferTimeout=" + getRecordBufferOfferTimeout() + ", recordBufferFullWait=" + getRecordBufferFullWait() + ", fetchSequenceNumberTimeout=" + getFetchSequenceNumberTimeout() + ", fetchThreads=" + getFetchThreads() + ", segmentWriteOutMediumFactory=" + getSegmentWriteOutMediumFactory() + ", logParseExceptions=" + isLogParseExceptions() + ", maxParseExceptions=" + getMaxParseExceptions() + ", maxSavedParseExceptions=" + getMaxSavedParseExceptions() + ", maxRecordsPerPoll=" + getMaxRecordsPerPoll() + ", intermediateHandoffPeriod=" + getIntermediateHandoffPeriod() + '}'; }
Source:
public void initialize(HttpRequest request) throws IOException { request.setUnsuccessfulResponseHandler(this); if (!credentials.hasRequestMetadata()) { return; } final HttpExecuteInterceptor originalInterceptor = request.getInterceptor(); request.setInterceptor(new HttpExecuteInterceptor() { @Override public void intercept(HttpRequest request) throws IOException { if (originalInterceptor != null) { originalInterceptor.intercept(request); } HttpHeaders requestHeaders = request.getHeaders(); URI uri = null; if (request.getUrl() != null) { uri = request.getUrl().toURI(); } Map<String, List<String>> credentialHeaders = credentials.getRequestMetadata(uri); if (credentialHeaders == null) { return; } for (Map.Entry<String, List<String>> entry : credentialHeaders.entrySet()) { String headerName = entry.getKey(); List<String> requestValues = new ArrayList<>(); requestValues.addAll(entry.getValue()); requestHeaders.put(headerName, requestValues); } } }); }

Target:
public void initialize(HttpRequest request) throws IOException { request.setUnsuccessfulResponseHandler(this); if (!credentials.hasRequestMetadata()) { return; } final HttpExecuteInterceptor originalInterceptor = request.getInterceptor(); request.setInterceptor(new HttpExecuteInterceptor() { @Override public void intercept(HttpRequest request) throws IOException { if (originalInterceptor != null) { originalInterceptor.intercept(request); } HttpHeaders requestHeaders = request.getHeaders(); URI uri = null; if (request.getUrl() != null) { uri = request.getUrl().toURI(); } Map<String, List<String>> credentialHeaders = credentials.getRequestMetadata(uri); if (credentialHeaders == null) { return; } for (Map.Entry<String, List<String>> entry : credentialHeaders.entrySet()) { String headerName = entry.getKey(); requestHeaders.put(headerName, new ArrayList<>(entry.getValue())); } } }); }
Source:
public void init() { resetAllMocks(); Set<ApiEntity> mockApis = new HashSet<>(); doReturn(mockApis).when(apiService).findPublishedByUser(any()); CategoryEntity category1 = new CategoryEntity(); category1.setId("1"); category1.setHidden(false); category1.setOrder(2); CategoryEntity category2 = new CategoryEntity(); category2.setId("2"); category2.setHidden(false); category2.setOrder(3); CategoryEntity category3 = new CategoryEntity(); category3.setId("3"); category3.setHidden(true); category3.setOrder(1); doReturn(1L).when(categoryService).getTotalApisByCategory(any(), any()) ; existingCategories = Arrays.asList(category1, category2, category3); doReturn(existingCategories).when(categoryService).findAll(); Mockito.when(categoryMapper.convert(any(), any())).thenCallRealMethod(); }

Target:
public void init() { resetAllMocks(); Set<ApiEntity> mockApis = new HashSet<>(); doReturn(mockApis).when(apiService).findPublishedByUser(any()); CategoryEntity category1 = new CategoryEntity(); category1.setId("1"); category1.setHidden(false); category1.setOrder(2); doReturn(1L).when(categoryService).getTotalApisByCategory(mockApis, category1); CategoryEntity category2 = new CategoryEntity(); category2.setId("2"); category2.setHidden(false); category2.setOrder(3); doReturn(0L).when(categoryService).getTotalApisByCategory(mockApis, category2); CategoryEntity category3 = new CategoryEntity(); category3.setId("3"); category3.setHidden(true); category3.setOrder(1); doReturn(2L).when(categoryService).getTotalApisByCategory(mockApis, category3); existingCategories = Arrays.asList(category1, category2, category3); doReturn(existingCategories).when(categoryService).findAll(); Mockito.when(categoryMapper.convert(any(), any())).thenCallRealMethod(); }
Source:
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mSettings = getActivity().getSharedPreferences("prefs", 0); boolean firstRunDiets = mSettings.getBoolean("firstRunDiets", true); if (firstRunDiets) { new MaterialDialog.Builder(view.getContext()) .title(R.string.diets_dialog_warning_title) .content(R.string.warning_diets_data) .positiveText(R.string.ok_button) .show(); SharedPreferences.Editor editor = mSettings.edit(); editor.putBoolean("firstRunDiets", false); editor.apply(); } mRvDiet = (RecyclerView) view.findViewById(R.id.diets_recycler); DaoSession daoSession = OFFApplication.getInstance().getDaoSession(); DietDao dietDao = daoSession.getDietDao(); List dietList = dietDao.loadAll(); mRvDiet.setLayoutManager(new LinearLayoutManager(this.getContext())); mRvDiet.setAdapter(new DietsAdapter(dietList, new ClickListener() { @Override public void onPositionClicked(int position, View v) { Log.i("INFO", "Click sur " + v.getId() + " de l'enregistrement n°" + position + " ayant pour Tag : " + v.getTag()); Fragment fragment = new EditDietFragment(); if (v.getTag() != null) { Bundle args = new Bundle(); args.putString("dietName", v.getTag().toString()); fragment.setArguments(args); } FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.fragment_container, fragment ); transaction.addToBackStack(null); transaction.commit(); } })); }

Target:
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mEmptyMessageView = view.findViewById(R.id.emptyDietsView); mOneDietMessageView = view.findViewById(R.id.oneDietView); mRvDiet = (RecyclerView) view.findViewById(R.id.diets_recycler); DaoSession daoSession = OFFApplication.getInstance().getDaoSession(); DietDao dietDao = daoSession.getDietDao(); List<Diet> dietList = dietDao.loadAll(); if (dietList.isEmpty()) { mEmptyMessageView.setVisibility(view.VISIBLE); mOneDietMessageView.setVisibility(view.GONE); mRvDiet.setVisibility(view.GONE); } else { mEmptyMessageView.setVisibility(view.GONE); mRvDiet.setVisibility(view.VISIBLE); if (dietList.size() == 1) mOneDietMessageView.setVisibility(view.VISIBLE); else mOneDietMessageView.setVisibility(view.GONE); mRvDiet.setLayoutManager(new LinearLayoutManager(this.getContext())); mRvDiet.setAdapter(new DietsAdapter(dietList, new ClickListener() { @Override public void onPositionClicked(int position, View v) { Fragment fragment = new EditDietFragment(); if (v.getTag() != null) { Bundle args = new Bundle(); args.putString("dietName", v.getTag().toString()); fragment.setArguments(args); } FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.fragment_container, fragment ); transaction.addToBackStack(null); transaction.commit(); } })); } BottomNavigationListenerInstaller.install(bottomNavigationView,getActivity(),getContext()); }
Source:
public static String getLocalPackageName(@NotNull String importPath) { final String illegalChars = "[-!\"#$%&'()*,:;<=>?[\\]^{|}\uFFFD]"; StringBuilder name = new StringBuilder(PathUtil.getFileName(importPath)); for (int i = 0; i < name.length(); i++) { char ch = name.charAt(i); if (Character.isWhitespace(ch) || illegalChars.indexOf(ch) != -1) { name.setCharAt(i, '_'); } } return name.toString(); }

Target:
public static String getLocalPackageName(@NotNull String importPath) { StringBuilder name = null; for (int i = 0; i < importPath.length(); i++) { char c = importPath.charAt(i); if (!(Character.isLetter(c) || c == '_' || (i != 0 && Character.isDigit(c)))) { if (name == null) { name = new StringBuilder(importPath.length()); name.append(importPath, 0, i); } name.append('_'); } else if (name != null) { name.append(c); } } return name == null ? importPath : name.toString(); }
Source:
public void changePreviewSize(int width, int height, int idx) { PORTRAIT_WIDTH = width; PORTRAIT_HEIGHT = height; LANDSCAPE_WIDTH = height; LANDSCAPE_HEIGHT = width; idxPhoneSize = idx; setPhoneStyle(); if (landscape) resizePanel(LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT); else resizePanel(width, height); }

Target:
public void changePreviewSize(int width, int height, int idx) { PORTRAIT_WIDTH = width; PORTRAIT_HEIGHT = height; LANDSCAPE_WIDTH = height; LANDSCAPE_HEIGHT = width; idxPhoneSize = idx; setPhoneStyle(); if (landscape) { resizePanel(LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT); } else { resizePanel(width, height); } }
Source:
private void assertExtractValue(String input, String xpath, Matcher<? super String> matcher) { assertThat(invocationDesc(BuiltInMethod.EXTRACTVALUE.getMethodName(), input), XmlFunctions.extractValue(input, xpath), matcher); }

Target:
private void assertExtractValue(String input, String xpath, Matcher<? super String> matcher) { String extractMethodDesc = BuiltInMethod.EXTRACT_VALUE.getMethodName() + "(" + String.join(", ", input) + ")"; assertThat(extractMethodDesc, XmlFunctions.extractValue(input, xpath), matcher); }
Source:
public TopNParams makeInitParams(DimensionSelector dimSelector, Cursor cursor) { return new TopNParams( dimSelector, cursor, Integer.MAX_VALUE, Integer.MAX_VALUE ); }

Target:
public TopNParams makeInitParams(DimensionSelector dimSelector, Cursor cursor) { return new TopNParams( dimSelector, cursor, dimSelector.getValueCardinality(), Integer.MAX_VALUE ); }
Source:
protected void scheduleTask(String rqid, double requiredCpus, double requiredMemoryMb) { Resources rs = new Resources(requiredCpus, requiredMemoryMb, 0); SingularityRequest rq = new SingularityRequestBuilder(rqid, RequestType.WORKER) .setInstances(Optional.of(1)) .build(); SingularityDeploy dp = new SingularityDeployBuilder(rq.getId(), "deployId1") .setCommand(Optional.of("sleep 100")) .setResources(Optional.of(rs)) .build(); SingularityDeployMarker marker = new SingularityDeployMarker(dp.getRequestId(), dp.getId(), System.currentTimeMillis(), Optional.empty(), Optional.empty()); SingularityPendingRequest pending = new SingularityPendingRequest( rq.getId(), dp.getId(), System.currentTimeMillis(), Optional.empty(), SingularityPendingRequest.PendingType.UPDATED_REQUEST, Optional.empty(), Optional.empty() ); requestManager.activate(rq, SingularityRequestHistory.RequestHistoryType.CREATED, System.currentTimeMillis(), Optional.empty(), Optional.empty()); deployManager.saveDeploy(rq, marker, dp); deployManager.deletePendingDeploy(marker.getRequestId()); deployManager.saveDeployResult(marker, Optional.of(dp), new SingularityDeployResult(DeployState.SUCCEEDED)); deployManager.saveNewRequestDeployState(new SingularityRequestDeployState(marker.getRequestId(), Optional.of(marker), Optional.empty())); requestManager.addToPendingQueue(pending); scheduler.drainPendingQueue(); }

Target:
protected void scheduleTask(String rqid, double requiredCpus, double requiredMemoryMb) { scheduleTask(rqid, requiredCpus, requiredMemoryMb, 1); }
Source:
public void shouldNotAddCustomAttributesToUser_withIntercomFindUserException() { final String userId = randomId(); when(User.find(userId)).thenThrow(Exception.class); final Map<String, Object> customAttributes = mockCustomAttributes(); intercomMetricCollector.addCustomAttributesToUser(userId, customAttributes); verifyStatic(never()); User.update(any(User.class)); }

Target:
public void shouldNotAddCustomAttributesToUser_withIntercomFindUserException() { final String userId = randomId(); when(User.find(userId)).thenThrow(Exception.class); final Map<String, Object> customAttributes = mock(Map.class); intercomMetricCollector.addCustomAttributesToUser(userId, customAttributes); verifyStatic(never()); User.update(any(User.class)); }
Source:
public double logLikelihood(@Nonnull CoverageModelCopyRatioEmissionData emissionData, double copyRatio, @Nullable Target target) { Utils.nonNull(emissionData, "The emission data must be non-null"); ParamUtils.isPositiveOrZero(copyRatio, "Copy ratio must be non-negative"); final double logLikelihood; switch (emissionData.getCopyRatioCallingMetadata().getEmissionCalculationStrategy()) { case POISSON: logLikelihood = logLikelihoodPoisson(emissionData, copyRatio); break; case HYBRID_POISSON_GAUSSIAN: if (emissionData.getReadCount() >= readCountThresholdPoissonSwitch) { if (copyRatio > 0) { logLikelihood = logLikelihoodLaplaceApproximation(emissionData, copyRatio); } else { logLikelihood = Double.NEGATIVE_INFINITY; } } else { logLikelihood = logLikelihoodPoisson(emissionData, copyRatio); } break; default: throw new GATKException.ShouldNeverReachHereException("The emission calculation model is not" + " properly set"); } if (CHECK_FOR_NANS && Double.isNaN(logLikelihood)) { throw new RuntimeException("A NaN was produced while calculating the emission probability for" + " emission data: " + emissionData.toString() + ", target: " + target + ", copy ratio: " + copyRatio); } return logLikelihood; }

Target:
public double logLikelihood(@Nonnull CoverageModelCopyRatioEmissionData emissionData, double copyRatio, @Nullable Target target) { Utils.nonNull(emissionData, "The emission data must be non-null"); ParamUtils.isPositiveOrZero(copyRatio, "Copy ratio must be non-negative"); final EmissionCalculationStrategy strategy = emissionData.getCopyRatioCallingMetadata().getEmissionCalculationStrategy(); final boolean usePoisson = strategy.equals(EmissionCalculationStrategy.POISSON) || emissionData.getReadCount() < readCountThresholdPoissonSwitch || copyRatio == 0; final double logLikelihood = usePoisson ? logLikelihoodPoisson(emissionData, copyRatio) : logLikelihoodLaplaceApproximation(emissionData, copyRatio); if (CHECK_FOR_NANS && Double.isNaN(logLikelihood)) { throw new RuntimeException("A NaN was produced while calculating the emission probability for" + " emission data: " + emissionData.toString() + ", target: " + target + ", copy ratio: " + copyRatio); } return logLikelihood; }
Source:
private void checkImportedSymbol(Symbol symbol) { for (IdentifierTree usageIdentifier : symbol.usages()) { Tree parent = usageIdentifier.parent(); if (parent.is(Kind.MEMBER_SELECT) && ((MemberSelectExpressionTree) parent).expression().is(Kind.MEMBER_SELECT)) { reportIssue(parent, String.format(MESSAGE, symbol.name())); hasIssue.add(parent); } } }

Target:
private void checkImportedSymbol(Symbol symbol) { for (IdentifierTree usageIdentifier : symbol.usages()) { Tree parent = usageIdentifier.parent(); if (parent.is(Kind.MEMBER_SELECT) && ((MemberSelectExpressionTree) parent).expression().is(Kind.MEMBER_SELECT)) { reportIssue(parent, String.format(MESSAGE, symbol.name())); } } }
Source:
public PostAggregator decorate(Map<String, AggregatorFactory> aggregators) { return this; }

Target:
public ZtestPostAggregator decorate(Map<String, AggregatorFactory> aggregators) { return new ZtestPostAggregator( name, Iterables .getOnlyElement(Queries.decoratePostAggregators(Collections.singletonList(successCount1), aggregators)), Iterables.getOnlyElement(Queries.decoratePostAggregators(Collections.singletonList(sample1Size), aggregators)), Iterables .getOnlyElement(Queries.decoratePostAggregators(Collections.singletonList(successCount2), aggregators)), Iterables.getOnlyElement(Queries.decoratePostAggregators(Collections.singletonList(sample2Size), aggregators)) ); }
Source:
public AccountDeviceInstanceKey getAccountDeviceInstanceKey() { return accountDeviceInstanceKey; }

Target:
AccountDeviceInstanceKey getAccountDeviceInstanceKey() { return accountDeviceInstanceKey; }
Source:
public void sendString(String s) { if (_socket == null || _socket.sendString(s + "\n") == false) { switch(get_gameStartSound()){ case 0: break; case 1: soundChessPiecesFall(); vibration(DECREASE); break; case 2: soundChessPiecesFall(); break; case 3: vibration(DECREASE); break; default: Log.e(TAG, "get_gameStartSound error"); } new AlertDialog.Builder(ICSClient.this) .setTitle(R.string.title_error) .setMessage("Connection to server is broken.") .setPositiveButton(getString(R.string.alert_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); finish(); } }) .show(); } }

Target:
public void sendString(String s) { if (_socket == null || _socket.sendString(s + "\n") == false) { new AlertDialog.Builder(ICSClient.this) .setTitle(R.string.title_error) .setMessage("Connection to server is broken.") .setPositiveButton(getString(R.string.alert_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); finish(); } }) .show(); } }
Source:
public static FieldInfo getRelationalReader(ClassInfo classInfo, String relationshipType, Direction relationshipDirection) { final DirectedRelationship directedRelationship = new DirectedRelationship(relationshipType, relationshipDirection); final Map<DirectedRelationship, FieldInfo> relationshipFieldInfoMap = relationalReaderCache .computeIfAbsent(classInfo, key -> new ConcurrentHashMap<>()); if (relationshipFieldInfoMap.containsKey(directedRelationship)) { return relationshipFieldInfoMap.get(directedRelationship); } while (classInfo != null) { FieldInfo fieldInfo = classInfo.relationshipField(relationshipType, relationshipDirection, STRICT_MODE); if (fieldInfo != null && !fieldInfo.getAnnotations().isEmpty()) { relationshipFieldInfoMap.put(directedRelationship, fieldInfo); return fieldInfo; } if (!relationshipDirection.equals(Direction.INCOMING)) { fieldInfo = classInfo.relationshipField(relationshipType, relationshipDirection, INFERRED_MODE); if (fieldInfo != null && !fieldInfo.getAnnotations().isEmpty()) { relationshipFieldInfoMap.put(directedRelationship, fieldInfo); return fieldInfo; } if (fieldInfo != null) { relationshipFieldInfoMap.put(directedRelationship, fieldInfo); return fieldInfo; } } classInfo = classInfo.directSuperclass(); } return null; }

Target:
public static FieldInfo getRelationalReader(ClassInfo classInfo, String relationshipType, Direction relationshipDirection) { final DirectedRelationship directedRelationship = new DirectedRelationship(relationshipType, relationshipDirection); final Map<DirectedRelationship, FieldInfo> relationshipFieldInfoMap = relationalReaderCache .computeIfAbsent(classInfo, key -> new ConcurrentHashMap<>()); if (relationshipFieldInfoMap.containsKey(directedRelationship)) { return relationshipFieldInfoMap.get(directedRelationship); } while (classInfo != null) { FieldInfo fieldInfo = classInfo.relationshipField(relationshipType, relationshipDirection, STRICT_MODE); if (fieldInfo != null && !fieldInfo.getAnnotations().isEmpty()) { relationshipFieldInfoMap.put(directedRelationship, fieldInfo); return fieldInfo; } if (relationshipDirection != Direction.INCOMING) { fieldInfo = classInfo.relationshipField(relationshipType, relationshipDirection, INFERRED_MODE); if (fieldInfo != null && !fieldInfo.getAnnotations().isEmpty()) { relationshipFieldInfoMap.put(directedRelationship, fieldInfo); return fieldInfo; } if (fieldInfo != null) { relationshipFieldInfoMap.put(directedRelationship, fieldInfo); return fieldInfo; } } classInfo = classInfo.directSuperclass(); } return null; }
Source:
public double getHeight(double lat, double lon) { double deltaLat = Math.abs(lat - minLat); double deltaLon = Math.abs(lon - minLon); if (deltaLat > latHigherBound || deltaLat < lowerBound) throw new IllegalStateException("latitude not in boundary of this file:" + lat + "," + lon + ", this:" + this.toString()); if (deltaLon > lonHigherBound || deltaLon < lowerBound) throw new IllegalStateException("longitude not in boundary of this file:" + lat + "," + lon + ", this:" + this.toString()); double elevation; if (interpolate) { double x = (width - 1) * deltaLon / horizontalDegree; double y = (height - 1) * (1 - deltaLat / verticalDegree); int left = (int) x; int top = (int) y; int right = left + 1; int bottom = top + 1; double w00 = getHeightSample(left, top); double w01 = getHeightSample(left, bottom); double w10 = getHeightSample(right, top); double w11 = getHeightSample(right, bottom); double topEle = linearInterpolate(w00, w10, x - left); double bottomEle = linearInterpolate(w01, w11, x - left); elevation = linearInterpolate(topEle, bottomEle, y - top); } else { int x = (int) (width / horizontalDegree * deltaLon); if (x >= width) x = width - 1; int y = height - 1 - (int) (height / verticalDegree * deltaLat); if (y < 0) y = 0; elevation = getHeightSample(x, y); } return elevation < MIN_ELEVATION ? Double.NaN : elevation; }

Target:
public double getHeight(double lat, double lon) { double deltaLat = Math.abs(lat - minLat); double deltaLon = Math.abs(lon - minLon); if (deltaLat > latHigherBound || deltaLat < lowerBound) throw new IllegalStateException("latitude not in boundary of this file:" + lat + "," + lon + ", this:" + this.toString()); if (deltaLon > lonHigherBound || deltaLon < lowerBound) throw new IllegalStateException("longitude not in boundary of this file:" + lat + "," + lon + ", this:" + this.toString()); double elevation; if (interpolate) { double x = (width - 1) * deltaLon / horizontalDegree; double y = (height - 1) * (1 - deltaLat / verticalDegree); int left = (int) x; int top = (int) y; int right = left + 1; int bottom = top + 1; double w00 = getHeightSample(left, top); double w01 = getHeightSample(left, bottom); double w10 = getHeightSample(right, top); double w11 = getHeightSample(right, bottom); double topEle = linearInterpolate(w00, w10, x - left); double bottomEle = linearInterpolate(w01, w11, x - left); elevation = linearInterpolate(topEle, bottomEle, y - top); } else { int x = (int) (width / horizontalDegree * deltaLon); if (x >= width) x = width - 1; int y = height - 1 - (int) (height / verticalDegree * deltaLat); if (y < 0) y = 0; elevation = getHeightSample(x, y); } return isValidElevation(elevation) ? elevation : Double.NaN; }