auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void create() { log.infoFormat("InitResourceManager: {0}", new Date()); ResourceManager.getInstance().init(); AsyncTaskManager.getInstance().InitAsyncTaskManager(); log.infoFormat("AsyncTaskManager: {0}", new Date()); if (Config.<Boolean> GetValue(ConfigValues.EnableVdsLoadBalancing)) { VdsLoadBalancer.EnableLoadBalancer(); } log.infoFormat("VdsLoadBalancer: {0}", new Date()); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { log.infoFormat("MacPoolManager started: {0}", new Date()); MacPoolManager.getInstance().initialize(); log.infoFormat("MacPoolManager finished: {0}", new Date()); } }); StoragePoolStatusHandler.Init(); GlusterManager.getInstance().init(); <START> log.infoFormat("GlusterManager: {0}", new Date()); <END> }</code><technical_language>This log scope GlusterManager. I line 50, 52, 37, 40 present behavior - I fixed (i.e - log of init a part of init method)</technical_language>

Target:
public void create() { log.infoFormat("InitResourceManager: {0}", new Date()); ResourceManager.getInstance().init(); AsyncTaskManager.getInstance().InitAsyncTaskManager(); log.infoFormat("AsyncTaskManager: {0}", new Date()); if (Config.<Boolean> GetValue(ConfigValues.EnableVdsLoadBalancing)) { VdsLoadBalancer.EnableLoadBalancer(); } log.infoFormat("VdsLoadBalancer: {0}", new Date()); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { log.infoFormat("MacPoolManager started: {0}", new Date()); MacPoolManager.getInstance().initialize(); log.infoFormat("MacPoolManager finished: {0}", new Date()); } }); StoragePoolStatusHandler.Init(); GlusterManager.getInstance().init(); }
Source:
<code>private <START> List<ProjectInfo> list(final <END> ListRequest request) throws RestApiException { ListProjects lp = listProvider.get(); lp.setShowDescription(request.getDescription()); lp.setLimit(request.getLimit()); lp.setStart(request.getStart()); lp.setMatchPrefix(request.getPrefix()); Map<String, ProjectInfo> result = lp.apply(); return ImmutableList.copyOf(result.values()); }</code><technical_language>I List is fine</technical_language>

Target:
private List<ProjectInfo> list(final ListRequest request) throws RestApiException { ListProjects lp = listProvider.get(); lp.setShowDescription(request.getDescription()); lp.setLimit(request.getLimit()); lp.setStart(request.getStart()); lp.setMatchPrefix(request.getPrefix()); return ImmutableList.copyOf(lp.apply().values()); }
Source:
<code>protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SSOConfig config = (SSOConfig) request.getServletContext().getAttribute(SSOUtils.SSO_CONFIG); Credentials credentials = null; if (config.isAcceptBasicAuthHeaders()) { credentials = SSOUtils.getUserCredentialsFromHeader(request); <START> } <END> if (doAuth(request, response)) { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE4_URI); } else if (credentials != null) { request.getSession(true).setAttribute(SSOUtils.USER_CREDENTIALS, credentials); response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE3_URI); } else if (config.isEnforceNego()) { enforceNego(response); } else { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE2_URI); } }</code><technical_language>I credentials I</technical_language>

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SSOConfig config = (SSOConfig) request.getServletContext().getAttribute(SSOUtils.SSO_CONFIG); Credentials credentials; if (doAuth(request, response)) { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE4_URI); } else if (config.isAcceptBasicAuthHeaders() && (credentials = SSOUtils.getUserCredentialsFromHeader(request)) != null) { request.getSession(true).setAttribute(SSOUtils.USER_CREDENTIALS, credentials); response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE3_URI); } else if (config.isEnforceNego()) { enforceNego(response); } else { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE2_URI); } }
Source:
<code><START> public InternalFunctions getFunctions(RealmUser user, CodecRegistry codecRegistry) { <END> return new InternalFunctions(user, codecRegistry); }</code><technical_language>suggestion public Functions getFunctions(RealmUser user, CodecRegistry codecRegistry) {</technical_language>

Target:
public Functions getFunctions(RealmUser user, CodecRegistry codecRegistry) { return new FunctionsImpl(user, codecRegistry); }
Source:
<code>private StorageLocation fakeLocation(long total, long free, long max, Double percent) throws IOException { Configuration config = Configuration.builder(PathType.unix()) .setRoots("/") .setWorkingDirectory("/") .setAttributeViews("basic") .setMaxSize(total) .setBlockSize(1000) .build(); Path path = Jimfs.newFileSystem(config).getPath("/"); <START> Files.write(path.resolve("junk"), new byte[(int) (total - free)]); END> Assert.assertEquals(free, Files.getFileStore(path).getUsableSpace()); return new StorageLocation(path, max, percent); }</code><technical_language>So, write a file here, benefit of jimfs? do local file system writing in memory if jimfs</technical_language>

Target:
private StorageLocation fakeLocation(long total, long free, long max, Double percent) { File file = EasyMock.mock(File.class); EasyMock.expect(file.getTotalSpace()).andReturn(total).anyTimes(); EasyMock.expect(file.getFreeSpace()).andReturn(free).anyTimes(); EasyMock.replay(file); return new StorageLocation(file, max, percent); }
Source:
<code>public void testBasics() throws Exception { final Path tmpPath = Files.createTempFile("testfile", ".txt"); tmpPath.toFile().deleteOnExit(); <START> try (final PathEntity httpentity = new PathEntity(tmpPath, ContentType.TEXT_PLAIN)) { <END> Assert.assertEquals(Files.size(tmpPath), httpentity.getContentLength()); try (final InputStream content = httpentity.getContent()) { Assert.assertNotNull(content); } Assert.assertTrue(httpentity.isRepeatable()); Assert.assertFalse(httpentity.isStreaming()); if (!Files.deleteIfExists(tmpPath)) { Assert.fail("Failed to delete: " + tmpPath); } } }</code><technical_language>Typo httpEntity</technical_language>

Target:
public void testBasics() throws Exception { final Path tmpPath = Files.createTempFile("testfile", ".txt"); tmpPath.toFile().deleteOnExit(); try (final PathEntity httpEntity = new PathEntity(tmpPath, ContentType.TEXT_PLAIN)) { Assert.assertEquals(Files.size(tmpPath), httpEntity.getContentLength()); try (final InputStream content = httpEntity.getContent()) { Assert.assertNotNull(content); } Assert.assertTrue(httpEntity.isRepeatable()); Assert.assertFalse(httpEntity.isStreaming()); if (!Files.deleteIfExists(tmpPath)) { Assert.fail("Failed to delete: " + tmpPath); } } }
Source:
<code>public static void touch(Path f) throws IOException { try (FileChannel fc = FileChannel.open(f, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.SYNC)) { Files.setLastModifiedTime(f, <START> FileTime.from(Instant.now())); <END> } }</code><technical_language>Andrey's question clock sync NFS machine this Java code runs relevant</technical_language>

Target:
public static void touch(Path f) throws IOException { try (FileChannel fc = FileChannel.open(f, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.SYNC)) { } Files.setLastModifiedTime(f, FileTime.from(Instant.now())); }
Source:
<code>AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { if (more == null) { more = new String[0]; } this.parentFileSystem = parentFileSystem; Flux<String> elementFlux = <START> Flux.fromArray(first.split(this.parentFileSystem.getSeparator())) .concatWith(Flux.fromArray(more) .flatMap(str -> Flux.fromArray(str.split(this.parentFileSystem.getSeparator())))) .filter(str -> !str.isEmpty()); <END> this.pathString = String.join(this.parentFileSystem.getSeparator(), elementFlux.toIterable()); elementFlux.skip(1) .flatMap(str -> str.contains(ROOT_DIR_SUFFIX) ? Mono.error(Utility.logError(logger, new InvalidPathException(this.pathString, ROOT_DIR_SUFFIX + " is an invalid character except to identify the root element of this path if there is one."))) : Mono.just(str)).blockLast(); elementFlux.take(1) .flatMap(str -> str.contains(ROOT_DIR_SUFFIX) && str.indexOf(ROOT_DIR_SUFFIX) < str.length() - 1 ? Mono.error(Utility.logError(logger, new InvalidPathException(this.pathString, ROOT_DIR_SUFFIX + " may" + " only be used as the last character in the root component of a path"))) : Mono.just(str)).blockLast(); }</code><technical_language>this simplified iterative approach following? java List<String> elements = Arrays.asList(first.split(parentFileSystem.getSeparator())); for (String next : more) { elements.addAll(Arrays.asList(more.split(parentFileSystem.getSeparator()))); } Stream elementStream = elements.stream().filter(CoreUtils::isNullOrEmpty);</technical_language>

Target:
AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.parentFileSystem = parentFileSystem; List<String> elements = new ArrayList<>(Arrays.asList(first.split(parentFileSystem.getSeparator()))); if (more != null) { for (String next : more) { elements.addAll(Arrays.asList(next.split(parentFileSystem.getSeparator()))); } } elements.removeIf(String::isEmpty); this.pathString = String.join(this.parentFileSystem.getSeparator(), elements); for (int i = 0; i < elements.size(); i++) { String element = elements.get(i); if (i == 0) { if (element.contains(ROOT_DIR_SUFFIX) && element.indexOf(ROOT_DIR_SUFFIX) < element.length() - 1) { throw Utility.logError(logger, new InvalidPathException(this.pathString, ROOT_DIR_SUFFIX + " may" + " only be used as the last character in the root component of a path")); } } else if (element.contains(ROOT_DIR_SUFFIX)) { throw Utility.logError(logger, new InvalidPathException(this.pathString, ROOT_DIR_SUFFIX + " is an " + "invalid character except to identify the root element of this path if there is one.")); } } }
Source:
<code><START> private static MultitenantBlackBoxContext multiTenant(String name, EventEnricher enricher) { <END> return new MultitenantBlackBoxContext(name, enricher); }</code><technical_language>I assume rest of similar factory methods private get removed in part 2</technical_language>

Target:
public static MultitenantBlackBoxContext multiTenant(String name, EventEnricher enricher) { return new MultitenantBlackBoxContext(name, enricher); }
Source:
<code>private void shiftBaseTemplateToSuccessor() { try { final Guid newBaseTemplateId = findIdOfOldestTemplate(templateSubVersions); updateBaseTemplateId(newBaseTemplateId, templateSubVersions); } finally { freeSubTemplatesLock(); } <START> } <END></code><technical_language>I prefer stored-procedure it, shorter easier. In update query poll 'oldest sub-version' update templates about-to-be-deleted template is base template sub-versions of poll result</technical_language>

Target:
private void shiftBaseTemplateToSuccessor() { try { getVmTemplateDao().shiftBaseTemplate(getVmTemplateId()); } finally { freeSubTemplatesLock(); } }
Source:
<code><START> public String getCookie(URL url){ <END> try { URL sessionURL = new URL(String.format("%s://%s:%d/_session", url.getProtocol(), url.getHost(), url.getPort())); HttpConnection conn = Http.POST(sessionURL, "application/x-www-form-urlencoded"); conn.setRequestBody(sessionRequestBody); HttpURLConnection connection = conn.execute().getConnection(); String cookieHeader = connection.getHeaderField("Set-Cookie"); int responseCode = connection.getResponseCode(); if(responseCode / 100 == 2){ if(sessionHasStarted(connection.getInputStream())) { return cookieHeader.substring(0, cookieHeader.indexOf(";")); } else { return null; } } else if(responseCode == 401){ shouldAttemptCookieRequest = false; logger.severe("Credentials are incorrect, cookie authentication will not be" + " attempted again by this interceptor object"); } else if (responseCode / 100 == 5){ logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, cookie auth", responseCode); } else { logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, " + "cookie authentication will not be attempted again", responseCode); shouldAttemptCookieRequest = false; } } catch (MalformedURLException e) { logger.log(Level.SEVERE,"Failed to create URL for _session endpoint",e); } catch (UnsupportedEncodingException e) { logger.log(Level.SEVERE, "Failed to encode cookieRequest body", e); } catch (IOException e) { logger.log(Level.SEVERE, "Failed to read cookie response header", e); } return null; }</code><technical_language>sync-android this is private. public? interceptor designed care of cookie remote server, in requests renewing etc</technical_language>

Target:
private String getCookie(URL url){ try { URL sessionURL = new URL(String.format("%s://%s:%d/_session", url.getProtocol(), url.getHost(), url.getPort())); HttpConnection conn = Http.POST(sessionURL, "application/x-www-form-urlencoded"); conn.setRequestBody(sessionRequestBody); HttpURLConnection connection = conn.execute().getConnection(); String cookieHeader = connection.getHeaderField("Set-Cookie"); int responseCode = connection.getResponseCode(); if(responseCode / 100 == 2){ if(sessionHasStarted(connection.getInputStream())) { return cookieHeader.substring(0, cookieHeader.indexOf(";")); } else { return null; } } else if(responseCode == 401){ shouldAttemptCookieRequest = false; logger.severe("Credentials are incorrect, cookie authentication will not be" + " attempted again by this interceptor object"); } else if (responseCode / 100 == 5){ logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, cookie auth", responseCode); } else { logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, " + "cookie authentication will not be attempted again", responseCode); shouldAttemptCookieRequest = false; } } catch (MalformedURLException e) { logger.log(Level.SEVERE,"Failed to create URL for _session endpoint",e); } catch (UnsupportedEncodingException e) { logger.log(Level.SEVERE, "Failed to encode cookieRequest body", e); } catch (IOException e) { logger.log(Level.SEVERE, "Failed to read cookie response header", e); } return null; }
Source:
<code>protected void init() { if (getEntity() == null) { return; } allowDuplicates.setEntity(getEntity().isAllowDuplicateMacAddresses()); if (getEntity().getId() != null) { Frontend.getInstance() .runAction(ActionType.GetAvailableMacsForMacPool, new IdParameters(getEntity().getId()), result -> { initRanges(); Map<Pair<String, String>, Integer> availableMacsPerRange = result.getReturnValue().getActionReturnValue(); macRanges.getItems().forEach(macRangeModel -> { <START> MacRange macRange = macRangeModel.getMacRange(); Integer availableMacs = availableMacsPerRange.get(new Pair<>(macRange.getMacFrom(), macRange.getMacTo())); if (availableMacs != null) { macRangeModel.setAvailableMacs(availableMacs); } macRangeModel.recalculateMacsCount(); }); <END> }); } else { initRanges(); } }</code><technical_language>setting MACs recalculating belongs in MacRangeModel preserve good OO encapsulation: macRangeModel.recalc..Count(availableMacsPerRange.get(new Pair..))</technical_language>

Target:
protected void init() { if (getEntity() == null) { return; } allowDuplicates.setEntity(getEntity().isAllowDuplicateMacAddresses()); if (getEntity().getId() != null) { Frontend.getInstance() .runAction(ActionType.GetAvailableMacsForMacPool, new IdParameters(getEntity().getId()), result -> { initRanges(); Map<MacRange, Integer> availableMacsPerRange = result.getReturnValue().getActionReturnValue(); macRanges.getItems().forEach(macRangeModel -> { Integer availableMacs = availableMacsPerRange.get(macRangeModel.getMacRange()); if (availableMacs != null) { macRangeModel.setAvailableMacsCount(availableMacs); } }); }); } else { initRanges(); } }
Source:
<code>public InputStream executeToInputStream(HttpConnection connection) throws CouchDbException { if (proxyUrl != null) { connection.setProxy(proxyUrl); } connection.requestProperties.put("Accept", "application/json"); connection.responseInterceptors.addAll(this.responseInterceptors); connection.requestInterceptors.addAll(this.requestInterceptors); InputStream is = null; InputStream es = null; String response = null; int code = -1; Throwable cause = null; try { is = connection.execute().responseAsInputStream(); } catch (IOException ioe) { cause = ioe; } try { code = connection.getConnection().getResponseCode(); response = connection.getConnection().getResponseMessage(); if (code / 100 == 2) { return is; } else if (code == 404) { throw new NoDocumentException(response, cause); } else if(code == 412) { throw new PreconditionFailedException(response, cause); } else { CouchDbException ex = null; try { es = connection.getConnection().getErrorStream(); ex = getGson().fromJson(new InputStreamReader(es), CouchDbException.class); } catch(Exception e) { ex = new CouchDbException(response, code); } finally { <START> if (ex == null) { <END> ex = new CouchDbException(response, code); } ex.setStatusCode(code); throw ex; } } } catch (IOException ioe) { throw new CouchDbException("Error retrieving server response", ioe, code); } finally { if (es != null) { try { es.close(); } catch (IOException ioe) { ; } } } }</code><technical_language>I this block is needed set for ex in catch block</technical_language>

Target:
public InputStream executeToInputStream(HttpConnection connection) throws CouchDbException { if (proxyUrl != null) { connection.setProxy(proxyUrl); } connection.requestProperties.put("Accept", "application/json"); connection.responseInterceptors.addAll(this.responseInterceptors); connection.requestInterceptors.addAll(this.requestInterceptors); InputStream is = null; InputStream es = null; String response = null; int code = -1; Throwable cause = null; try { is = connection.execute().responseAsInputStream(); } catch (IOException ioe) { cause = ioe; } try { code = connection.getConnection().getResponseCode(); response = connection.getConnection().getResponseMessage(); if (code / 100 == 2) { return is; } else if (code == 404) { throw new NoDocumentException(response, cause); } else if (code == 412) { throw new PreconditionFailedException(response, cause); } else { CouchDbException ex = new CouchDbException(response, code); es = connection.getConnection().getErrorStream(); if (es != null) { try { ex = getGson().fromJson(new InputStreamReader(es), CouchDbException.class); ex.setStatusCode(code); } catch (JsonParseException e) { } } throw ex; } } catch (IOException ioe) { throw new CouchDbException("Error retrieving server response", ioe, code); } finally { close(es); } }
Source:
<code>public void testSomeUser3() { List<Integer> lightData = Lists.newArrayList(); final URL userCSVFile = Resources.getResource("insights/bedlightduration/lightDataUser3.csv"); try { final String csvString = Resources.toString(userCSVFile, Charsets.UTF_8); final String[] lightDataStringList = csvString.replaceAll("\\s+","").split(","); for (String lightDataString : lightDataStringList) { lightData.add(Integer.parseInt(lightDataString)); } <START> } catch (IOException ioexception) { <END> ioexception.printStackTrace(); } List<Long> timeStamps = Lists.newArrayList(); final URL timeStampCSVFile = Resources.getResource("insights/bedlightduration/timeStampUser3.csv"); try { final String csvString = Resources.toString(timeStampCSVFile, Charsets.UTF_8); final String[] timeStampStringList = csvString.replaceAll("\\s+","").replaceAll("L","").split(","); for (String timeStampString : timeStampStringList) { timeStamps.add(Long.parseLong(timeStampString)); } } catch (IOException ioexception) { ioexception.printStackTrace(); } final List<DeviceData> deviceData = Lists.newArrayList(); for (int i = 0; i < lightData.size(); i++) { final int myHour = new DateTime(timeStamps.get(i), DateTimeZone.forOffsetMillis(-25200000)).getHourOfDay(); if (myHour > 21 || myHour < 4) { deviceData.add(createNewDeviceData(lightData.get(i), new DateTime(timeStamps.get(i)))); } } final int avgLightOn = BedLightDuration.getInsightsHelper(deviceData); assertThat(avgLightOn, is(176)); }</code><technical_language>this copy/pasted a dozen time, a hint write a convenience method</technical_language>

Target:
public void testSomeUser3() throws IOException{ final List<Integer> lightData = readLightData("insights/bedlightduration/lightDataUser3.csv"); final List<Long> timeStamps = readTimeStamps("insights/bedlightduration/timeStampUser3.csv"); final List<DeviceData> deviceData = Lists.newArrayList(); for (int i = 0; i < lightData.size(); i++) { final int myHour = new DateTime(timeStamps.get(i), DateTimeZone.forOffsetMillis(-25200000)).getHourOfDay(); if (myHour > 21 || myHour < 4) { deviceData.add(createNewDeviceData(lightData.get(i), new DateTime(timeStamps.get(i)))); } } final int avgLightOn = BedLightDuration.getInsightsHelper(deviceData); assertThat(avgLightOn, is(176)); }
Source:
<code><START> public void close() { lastUsed.set(System.currentTimeMillis()); useCnt.decrementAndGet(); } <END></code><technical_language>A Repository opened RepositoryCache in a standalone way. change close method close affect standalone case. repository closed evict called in standalone. I 2 options here: Repository opened repository cache wrapped in a class holding usage counters (useCnt lastUsed) overwrite close method do logic done in evict method. problem approach is wrapping repository in repository is added cache register method. For this solution work, need remove register method (and break compatibility). Another option is repository opened RepositoryCache, leak usage counter(as originally implemented) useCnt=1 repo is in cache. In therminator thread do: Runnable terminator = new Runnable() { @Override public void run() { try { for (Reference<Repository> ref : cacheMap.values()) { Repository repository = ref.get(); if (repository.useCnt.get() == 1 && (System.currentTimeMillis() - repository.lastUsed.get() > 20000)) { RepositoryCache.unregister(repository); repository.close(); } } } catch (Throwable e) { LOG.error(e.getMessage(), e); } } };</technical_language>

Target:
public void close() { lastUsed.set(System.currentTimeMillis()); useCnt.decrementAndGet(); if (RepositoryCache.isCached(this)) { evict(0); } }
Source:
<code>public void shouldComplainAboutInvalidNumber() { try { converter.convert("---", BigInteger.class); <START> fail("Should throws an exception"); <END> } catch (ConversionException e) { assertThat(e.getValidationMessage(), hasMessage("--- is not a valid integer.")); } }</code><technical_language>"should throw exception" Expected exception</technical_language>

Target:
public void shouldComplainAboutInvalidNumber() { try { converter.convert("---", BigInteger.class); fail("should throw an exception"); } catch (ConversionException e) { assertThat(e.getValidationMessage(), hasMessage("--- is not a valid integer.")); } }
Source:
<code>private AttributesNode getCurrentAttributesNode(OperationType opType, WorkingTreeIterator workingTreeIterator, DirCacheIterator dirCacheIterator) throws IOException { AttributesNode attributesNode = null; switch (opType) { case CHECKIN_OP: if (workingTreeIterator != null) { attributesNode = workingTreeIterator.getEntryAttributesNode(); } if (attributesNode == null && dirCacheIterator != null) { attributesNode = dirCacheIterator .getEntryAttributesNode(getObjectReader()); } break; case CHECKOUT_OP: if (dirCacheIterator != null) { attributesNode = dirCacheIterator .getEntryAttributesNode(getObjectReader()); } if (attributesNode == null && workingTreeIterator != null) { attributesNode = workingTreeIterator.getEntryAttributesNode(); } break; default: throw new IllegalStateException( <START> "The only operation type handled are:" <END> + OperationType.CHECKIN_OP + "," + OperationType.CHECKOUT_OP); } return attributesNode; }</code><technical_language>supported operation types are:</technical_language>

Target:
private AttributesNode getCurrentAttributesNode(OperationType opType, WorkingTreeIterator workingTreeIterator, DirCacheIterator dirCacheIterator) throws IOException { AttributesNode attributesNode = null; switch (opType) { case CHECKIN_OP: if (workingTreeIterator != null) { attributesNode = workingTreeIterator.getEntryAttributesNode(); } if (attributesNode == null && dirCacheIterator != null) { attributesNode = dirCacheIterator .getEntryAttributesNode(getObjectReader()); } break; case CHECKOUT_OP: if (dirCacheIterator != null) { attributesNode = dirCacheIterator .getEntryAttributesNode(getObjectReader()); } if (attributesNode == null && workingTreeIterator != null) { attributesNode = workingTreeIterator.getEntryAttributesNode(); } break; default: throw new IllegalStateException( "The only supported operation types are:" + OperationType.CHECKIN_OP + "," + OperationType.CHECKOUT_OP); } return attributesNode; }
Source:
<code>public void processWorkerMetrics(Map<String, Object> conf, WorkerMetrics metrics) throws MetricException { try (NimbusClient client = NimbusClient.getConfiguredClient(conf)) { client.getClient().processWorkerMetrics(metrics); <START> } catch (Exception e) { <END> throw new MetricException("Failed to process metrics", e); } }</code><technical_language>instead of handling exceptions, more specific capturing NimbusLeaderNotFoundException ? catch (TException | NimbusLeaderNotFoundException e)</technical_language>

Target:
public void processWorkerMetrics(Map<String, Object> conf, WorkerMetrics metrics) throws MetricException { try (NimbusClient client = NimbusClient.getConfiguredClient(conf)) { client.getClient().processWorkerMetrics(metrics); } catch (TException | NimbusLeaderNotFoundException e) { throw new MetricException("Failed to process metrics", e); } }
Source:
<code>public void generateStreetTransfers(TransportNetwork transportNetwork, ProfileRequest request) { Map<Integer, List<Transfer>> transfersWithSameStart = transferToOption.keySet().stream() .collect(Collectors.groupingBy(Transfer::getAlightStop)); boolean prevReverseSearch = request.reverseSearch; request.reverseSearch = false; for (Map.Entry<Integer, List<Transfer>> entry: transfersWithSameStart.entrySet()) { StreetRouter streetRouter = new StreetRouter(transportNetwork.streetLayer); streetRouter.streetMode = StreetMode.WALK; streetRouter.profileRequest = request; <START> streetRouter.distanceLimitMeters = TransitLayer.TRANSFER_DISTANCE_LIMIT_METERS; <END> int stopIndex = transportNetwork.transitLayer.streetVertexForStop.get(entry.getKey()); streetRouter.setOrigin(stopIndex); streetRouter.route(); for (Transfer transfer: entry.getValue()) { int endIndex = transportNetwork.transitLayer.streetVertexForStop.get(transfer.boardStop); StreetRouter.State lastState = streetRouter.getStateAtVertex(endIndex); if (lastState != null) { StreetPath streetPath = new StreetPath(lastState, transportNetwork, false); StreetSegment streetSegment = new StreetSegment(streetPath, LegMode.WALK, transportNetwork.streetLayer); for (ProfileOption profileOption: transferToOption.get(transfer)) { profileOption.addMiddle(streetSegment, transfer); } } else { LOG.warn("Street transfer: not found in streetlayer", transfer); } } } request.reverseSearch = prevReverseSearch; }</code><technical_language>import constant need qualify class name</technical_language>

Target:
public void generateStreetTransfers(TransportNetwork transportNetwork, ProfileRequest request) { Map<Integer, List<Transfer>> transfersWithSameStart = transferToOption.keySet().stream() .collect(Collectors.groupingBy(Transfer::getAlightStop)); boolean prevReverseSearch = request.reverseSearch; request.reverseSearch = false; for (Map.Entry<Integer, List<Transfer>> entry: transfersWithSameStart.entrySet()) { StreetRouter streetRouter = new StreetRouter(transportNetwork.streetLayer); streetRouter.streetMode = StreetMode.WALK; streetRouter.profileRequest = request; streetRouter.distanceLimitMeters = TRANSFER_DISTANCE_LIMIT_METERS; int stopIndex = transportNetwork.transitLayer.streetVertexForStop.get(entry.getKey()); streetRouter.setOrigin(stopIndex); streetRouter.route(); for (Transfer transfer: entry.getValue()) { int endIndex = transportNetwork.transitLayer.streetVertexForStop.get(transfer.boardStop); StreetRouter.State lastState = streetRouter.getStateAtVertex(endIndex); if (lastState != null) { StreetPath streetPath = new StreetPath(lastState, transportNetwork, false); StreetSegment streetSegment = new StreetSegment(streetPath, LegMode.WALK, transportNetwork.streetLayer); for (ProfileOption profileOption: transferToOption.get(transfer)) { profileOption.addMiddle(streetSegment, transfer); } } else { LOG.warn("Street transfer: not found in streetlayer", transfer); } } } request.reverseSearch = prevReverseSearch; }
Source:
<code>public void testScanByArrayValue() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); createTableWithArray(BaseConnectedQueryTest.getUrl(), getDefaultSplits(tenantId), null, ts - 2); initTablesWithArrays(tenantId, null, ts); String query = "SELECT a_double_array, b_string, a_float FROM table_with_array WHERE ?=organization_id and ?=a_float"; Properties props = new Properties(TEST_PROPERTIES); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); try { PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, tenantId); statement.setFloat(2, 0.01f); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); Double[] doubleArr = new Double[2]; doubleArr[0] = 25.343; doubleArr[1] = 36.763; <START> PhoenixArray array = (PhoenixArray) conn.createArrayOf("DOUBLE", <END> doubleArr); PhoenixArray resultArray = (PhoenixArray) rs.getArray(1); assertEquals(resultArray, array); assertEquals(rs.getString("B_string"), B_VALUE); assertTrue(Floats.compare(rs.getFloat(3), 0.01f) == 0); assertFalse(rs.next()); } finally { conn.close(); } }</code><technical_language>JDBC interface Array instead of Phoenix implementation class</technical_language>

Target:
public void testScanByArrayValue() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); createTableWithArray(BaseConnectedQueryTest.getUrl(), getDefaultSplits(tenantId), null, ts - 2); initTablesWithArrays(tenantId, null, ts); String query = "SELECT a_double_array, b_string, a_float FROM table_with_array WHERE ?=organization_id and ?=a_float"; Properties props = new Properties(TEST_PROPERTIES); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); try { PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, tenantId); statement.setFloat(2, 0.01f); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); Double[] doubleArr = new Double[4]; doubleArr[0] = 25.343; doubleArr[1] = 36.763; doubleArr[2] = 37.56; doubleArr[3] = 386.63; Array array = conn.createArrayOf("DOUBLE", doubleArr); PhoenixArray resultArray = (PhoenixArray) rs.getArray(1); assertEquals(resultArray, array); assertEquals(rs.getString("B_string"), B_VALUE); assertTrue(Floats.compare(rs.getFloat(3), 0.01f) == 0); assertFalse(rs.next()); } finally { conn.close(); } }
Source:
<code><START> public Optional<SystemDescriptor> getSystemDescriptor() { <END> return this.systemDescriptorOptional; }</code><technical_language>feasible fully hide system descriptor? Some properties stream system descriptors, get confusing get necessary values</technical_language>

Target:
public SystemDescriptor getSystemDescriptor() { return this.systemDescriptor; }
Source:
<code>private void applyModuleConfiguration(@NotNull IProject wrappedModule) { Module module = wrappedModule.adaptTo(IntelliJProjectImpl.class).getModule(); ModuleConfiguration moduleConfiguration = queuedModuleOptions.remove(module); if (moduleConfiguration == null) { log.debug("Skipped module root model adjustment as not options were found - " + module); return; } if (!moduleConfiguration.isExistingModule()) { ModuleRootModificationUtil.updateModel( module, modifiableRootModel -> applyModuleConfiguration(modifiableRootModel, moduleConfiguration)); <START> } else { <END> ContentEntry[] contentEntries = ModuleRootManager.getInstance(module).getContentEntries(); if (contentEntries.length != 1) { log.error("Encountered shared module with multiple content roots - " + module); return; } ContentEntry contentEntry = contentEntries[0]; if (configurationDiffers(contentEntry, moduleConfiguration.getRootPaths())) { Runnable changeModuleConfiguration = () -> ModuleRootModificationUtil.updateModel( module, modifiableRootModel -> { resetModuleConfiguration(modifiableRootModel); applyModuleConfiguration(modifiableRootModel, moduleConfiguration); }); SafeDialogUtils.showYesNoDialog( module.getProject(), Messages.ModuleConfigurationInitializer_override_module_config_message, Messages.ModuleConfigurationInitializer_override_module_config_title, changeModuleConfiguration); } } }</code><technical_language>return</technical_language>

Target:
private void applyModuleConfiguration(@NotNull IProject wrappedModule) { Module module = wrappedModule.adaptTo(IntelliJProjectImpl.class).getModule(); ModuleConfiguration moduleConfiguration = queuedModuleOptions.remove(module); if (moduleConfiguration == null) { log.debug("Skipped module root model adjustment as not options were found - " + module); return; } if (!moduleConfiguration.isExistingModule()) { ModuleRootModificationUtil.updateModel( module, modifiableRootModel -> applyModuleConfiguration(modifiableRootModel, moduleConfiguration)); return; } ContentEntry[] contentEntries = ModuleRootManager.getInstance(module).getContentEntries(); if (contentEntries.length != 1) { log.error("Encountered shared module with multiple content roots - " + module); return; } ContentEntry contentEntry = contentEntries[0]; if (!configurationDiffers(contentEntry, moduleConfiguration.getRootPaths())) { return; } Runnable changeModuleConfiguration = () -> ModuleRootModificationUtil.updateModel( module, modifiableRootModel -> { resetModuleConfiguration(modifiableRootModel); applyModuleConfiguration(modifiableRootModel, moduleConfiguration); }); SafeDialogUtils.showYesNoDialog( module.getProject(), Messages.ModuleConfigurationInitializer_override_module_config_message, Messages.ModuleConfigurationInitializer_override_module_config_title, changeModuleConfiguration); }
Source:
<code>protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { final long start = System.currentTimeMillis(); try { filterChain.doFilter(request, response); } finally { final long time = System.currentTimeMillis(); final Long timing = time - start; final String userAgent = Optional.ofNullable(request.getHeader("User-Agent")).orElse("-"); final String user = Optional.ofNullable(request.getUserPrincipal()).map(Principal::getName).orElse("-"); final String method = request.getMethod(); final String path = request.getRequestURI(); final String query = Optional.ofNullable(request.getQueryString()).map(q -> "?" + q).orElse(""); final String contentEncoding = Optional.ofNullable(request.getHeader(HttpHeaders.CONTENT_ENCODING)) .orElse("-"); final String acceptEncoding = Optional.ofNullable(request.getHeader(HttpHeaders.ACCEPT_ENCODING)) .orElse("-"); LOG.info("[ACCESS_LOG] \"{}{}\" \"{}\" \"{}\" statusCode: ms \"{}\" \"{}\"", method, path, query, userAgent, user, response.getStatus(), timing, contentEncoding, acceptEncoding); <START> publisher.publish(method,path, query,user, response.getStatus(), timing); <END> } }</code><technical_language>method,path space</technical_language>

Target:
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { final long start = System.currentTimeMillis(); try { filterChain.doFilter(request, response); } finally { final long time = System.currentTimeMillis(); final Long timing = time - start; final String userAgent = Optional.ofNullable(request.getHeader("User-Agent")).orElse("-"); final String user = Optional.ofNullable(request.getUserPrincipal()).map(Principal::getName).orElse("-"); final String method = request.getMethod(); final String path = request.getRequestURI(); final String query = Optional.ofNullable(request.getQueryString()).map(q -> "?" + q).orElse(""); final String contentEncoding = Optional.ofNullable(request.getHeader(HttpHeaders.CONTENT_ENCODING)) .orElse("-"); final String acceptEncoding = Optional.ofNullable(request.getHeader(HttpHeaders.ACCEPT_ENCODING)) .orElse("-"); LOG.info("[ACCESS_LOG] \"{}{}\" \"{}\" \"{}\" statusCode: ms \"{}\" \"{}\"", method, path, query, userAgent, user, response.getStatus(), timing, contentEncoding, acceptEncoding); nakadiKpiPublisher.publish(accessLogEventType, () -> new JSONObject() .put("method", method) .put("path", path) .put("query", query) .put("app", user) .put("app_hashed", Hex.encodeHexString(sha256MessageDigest.digest(user.getBytes(Charsets.UTF_8)))) .put("status_code", response.getStatus()) .put("response_time_ms", timing)); } }
Source:
<code>public List<String> missingClusterCpuFlags(String clusterCpuFlagsString, String serverFlagsString) { List<String> missingFlags = null; List<String> clusterFlags = StringUtils.isEmpty(clusterCpuFlagsString) ? <START> new ArrayList<>() <END> : Arrays.asList(clusterCpuFlagsString.split("[,]", -1)); Set<String> serverFlags = StringUtils.isEmpty(serverFlagsString) ? new HashSet<>() : new HashSet<>(Arrays.asList(serverFlagsString.split("[,]", -1))); for (String flag : clusterFlags) { if (!serverFlags.contains(flag)) { if (missingFlags == null) { missingFlags = new ArrayList<>(); } missingFlags.add(flag); } } return missingFlags; }</code><technical_language>replacing this Collections.emptyList</technical_language>

Target:
public List<String> missingClusterCpuFlags(String clusterCpuFlagsString, String serverFlagsString) { List<String> clusterFlags = StringUtils.isEmpty(clusterCpuFlagsString) ? Collections.emptyList() : Arrays.asList(clusterCpuFlagsString.split("[,]", -1)); Set<String> serverFlags = StringUtils.isEmpty(serverFlagsString) ? Collections.emptySet() : new HashSet<>(Arrays.asList(serverFlagsString.split("[,]", -1))); return clusterFlags.stream().filter(flag -> !serverFlags.contains(flag)).collect(Collectors.toList()); }
Source:
<code>public void reload(Page page) { <START> m_transactionTemplate.execute(new TransactionCallbackWithoutResult() { <END> @Override protected void doInTransactionWithoutResult(TransactionStatus status) { reset(); List<T> beans = getItemsForCache(m_datasource, page); if (beans == null) return; int rowNumber = page.getStart(); for (T eachBean : beans) { addItem(rowNumber, getId(eachBean), eachBean); doItemAddedCallBack(rowNumber, getId(eachBean), eachBean); rowNumber++; } } }); }</code><technical_language>moving this OnmsDaoContainerDatasource remove doItemAddedCallback method alltogether, I logic live in OnmsDaoContainerDatasource too</technical_language>

Target:
public void reload(Page page) { reset(); List<T> beans = getItemsForCache(m_datasource, page); if (beans == null) return; int rowNumber = page.getStart(); for (T eachBean : beans) { addItem(rowNumber, getId(eachBean), eachBean); rowNumber++; } if (beans.size() != rowMap.size()) { throw new IllegalStateException("The cache is supposed to carry " + beans.size() + " but only contains " + rowMap.size() + " items."); } }
Source:
<code>public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { MDC.put(REQUEST_ID, idGenerator.generate()); <START> String loginName = appTokenParser.getLoginName(request); <END> if (StringUtils.isNotEmpty(loginName)) { MDC.put(USER_ID, loginName); } return true; }</code><technical_language>LoginUserInfo.getLoginName() anonymous</technical_language>

Target:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { MDC.put(REQUEST_ID, UUIDGenerator.generate()); String loginName = StringUtils.isNotEmpty(LoginUserInfo.getLoginName()) ? LoginUserInfo.getLoginName() : ANONYMOUS; MDC.put(USER_ID, loginName); return true; }
Source:
<code>public void testNoSubText() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); Notification notification = mpPushSpy.createNotification(intent); <START> verify(builderSpy, never()).setSubText("MESSAGE"); <END> }</code><technical_language>This test pass if setSubText is called other "Message". This verifying called thing</technical_language>

Target:
public void testNoSubText() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); Notification notification = mpPushSpy.createNotification(intent); verify(builderSpy, never()).setSubText(any(String.class)); }
Source:
<code>void init() { if (mDbHelper == null || mDbHelper.getAppId() != ProviderUtils.getSeatedOrInstallingAppId()) { String dbName = ProviderUtils.getProviderDbName( ProviderUtils.ProviderType.INSTANCES, ProviderUtils.getSeatedOrInstallingAppId()); <START> mDbHelper = new DatabaseHelper(CommCareApplication._(), dbName); <END> } }</code><technical_language>a bit confused. pass this DB name + app_id seat that, reading app ID DB name</technical_language>

Target:
void init() { String appId = ProviderUtils.getSandboxedAppId(); if (mDbHelper == null || mDbHelper.getAppId() != appId) { String dbName = ProviderUtils.getProviderDbName(ProviderUtils.ProviderType.INSTANCES, appId); mDbHelper = new DatabaseHelper(CommCareApplication._(), dbName, appId); } }
Source:
<code>public ContentLengthNotMatchException(final String fileName, final long contentLenght, final long totalBytes) { <START> super(String.format("The Content length for %s (%d) not match the number of byte read (%d)", fileName, contentLenght, totalBytes)); <END> }</code><technical_language>need stored in exception recovering a partial get, bytes sent/received</technical_language>

Target:
public ContentLengthNotMatchException(final String fileName, final long contentLenght, final long totalBytes) { super(String.format("The Content length for %s (%d) not match the number of byte read (%d)", fileName, contentLenght, totalBytes)); this.fileName = fileName; this.contentLenght = contentLenght; this.totalBytes = totalBytes; }
Source:
<code>@Override public boolean next(List<Cell> result) throws IOException { try { <START> boolean hasMore; <END> do { hasMore = scanner.next(result); if (result.isEmpty()) { break; } numRowsScanned++; if (maskIfExpired && checkRowNotExpired(result)) { break; } if (deleteIfExpired && deleteRowIfExpired(result)) { numRowsDeleted++; break; } if (maskIfExpired) { numRowsExpired++; } result.clear(); } while (hasMore); return hasMore; } catch (Throwable t) { ServerUtil.throwIOException(region.getRegionInfo().getRegionNameAsString(), t); return false; } }</code><technical_language>Extract this a method nextRaw() exact</technical_language>

Target:
@Override public boolean next(List<Cell> result) throws IOException { return doNext(result, false); }
Source:
<code>private Environment decrypt(Environment environment, TextEncryptorLocator encryptor) { Environment result = new Environment(environment); for (PropertySource source : environment.getPropertySources()) { Map<Object, Object> map = new LinkedHashMap<Object, Object>( source.getSource()); for (Map.Entry<Object, Object> entry : new LinkedHashSet<>(map.entrySet())) { Object key = entry.getKey(); String name = key.toString(); <START> String value = null; <END> if(entry.getValue() != null){ value = entry.getValue().toString(); } if (value != null && value.startsWith("{cipher}")) { map.remove(key); try { value = value.substring("{cipher}".length()); value = encryptor.locate( this.helper.getEncryptorKeys(name, StringUtils .arrayToCommaDelimitedString(environment .getProfiles()), value)).decrypt(this.helper.stripPrefix(value)); } catch (Exception e) { value = "<n/a>"; name = "invalid." + name; String message = "Cannot decrypt key: " + key + " (" + e.getClass() + ": " + e.getMessage() + ")"; if (logger.isDebugEnabled()) { logger.debug(message, e); } else if (logger.isWarnEnabled()) { logger.warn(message); } } map.put(name, value); } } result.add(new PropertySource(source.getName(), map)); } return result; }</code><technical_language>This need if, else</technical_language>

Target:
private Environment decrypt(Environment environment, TextEncryptorLocator encryptor) { Environment result = new Environment(environment); for (PropertySource source : environment.getPropertySources()) { Map<Object, Object> map = new LinkedHashMap<Object, Object>( source.getSource()); for (Map.Entry<Object, Object> entry : new LinkedHashSet<>(map.entrySet())) { Object key = entry.getKey(); String name = key.toString(); if(entry.getValue() != null && entry.getValue().toString().startsWith("{cipher}")){ String value = entry.getValue().toString(); map.remove(key); try { value = value.substring("{cipher}".length()); value = encryptor.locate( this.helper.getEncryptorKeys(name, StringUtils .arrayToCommaDelimitedString(environment .getProfiles()), value)).decrypt(this.helper.stripPrefix(value)); } catch (Exception e) { value = "<n/a>"; name = "invalid." + name; String message = "Cannot decrypt key: " + key + " (" + e.getClass() + ": " + e.getMessage() + ")"; if (logger.isDebugEnabled()) { logger.debug(message, e); } else if (logger.isWarnEnabled()) { logger.warn(message); } } map.put(name, value); } } result.add(new PropertySource(source.getName(), map)); } return result; }
Source:
<code>private VirtualFileGroupInterface setVirtualFileGroup(ProjectFileGroup projectFileGroup, VariableReplacer variableReplacer) { <START> VirtualFileGroupInterface virtualFileGroupInterface = UghImplementation.INSTANCE.createVirtualFileGroup(); <END> virtualFileGroupInterface.setName(projectFileGroup.getName()); virtualFileGroupInterface.setPathToFiles(variableReplacer.replace(projectFileGroup.getPath())); virtualFileGroupInterface.setMimetype(projectFileGroup.getMimeType()); virtualFileGroupInterface.setFileSuffix(projectFileGroup.getSuffix()); virtualFileGroupInterface.setOrdinary(!projectFileGroup.isPreviewImage()); return virtualFileGroupInterface; }</code><technical_language>Interface appended variable name</technical_language>

Target:
private VirtualFileGroupInterface setVirtualFileGroup(ProjectFileGroup projectFileGroup, VariableReplacer variableReplacer) { VirtualFileGroupInterface virtualFileGroup = UghImplementation.INSTANCE.createVirtualFileGroup(); virtualFileGroup.setName(projectFileGroup.getName()); virtualFileGroup.setPathToFiles(variableReplacer.replace(projectFileGroup.getPath())); virtualFileGroup.setMimetype(projectFileGroup.getMimeType()); virtualFileGroup.setFileSuffix(projectFileGroup.getSuffix()); virtualFileGroup.setOrdinary(!projectFileGroup.isPreviewImage()); return virtualFileGroup; }