auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void handleSchemes(Collection<IScheme> toAdd, Collection<IScheme> toRemove) throws Exception { List<ISchemeInformation> schemesInformation = getSchemesInformation(toAdd); <START> for (ISchemeInformation schemeInformation : schemesInformation) { <END> String handlerInstanceLocation = schemeInformation.getHandlerInstanceLocation(); processExecutor.execute(LSREGISTER, UNREGISTER, handlerInstanceLocation); } String pathToEclipseApp = getPathToEclipseApp(); changePlistFile(toAdd, toRemove, pathToEclipseApp); registerAppWithLsregister(pathToEclipseApp); }</code><technical_language>intention attempt modify info.plist of another app. remove registration in other app manually. platform pref page provides a hint for user</technical_language>

Target:
public void handleSchemes(Collection<IScheme> toAdd, Collection<IScheme> toRemove) throws Exception { String pathToEclipseApp = getPathToEclipseApp(); changePlistFile(toAdd, toRemove, pathToEclipseApp); registerAppWithLsregister(pathToEclipseApp); }
Source:
<code>public GetQuotaByQuotaIdQueryParameters(Guid quotaId) { <START> this(); <END> this.quotaId = quotaId; }</code><technical_language>Remove call this();</technical_language>

Target:
public GetQuotaByQuotaIdQueryParameters(Guid quotaId) { this.quotaId = quotaId; }
Source:
<code>public void doPatchsetCreatedHook(final Change change, final PatchSet patchSet) { final PatchSetCreatedEvent event = new PatchSetCreatedEvent(); event.change = getChangeAttribute(change); event.patchSet = getPatchSetAttribute(patchSet); fireEvent(change, event); final List<String> args = new ArrayList<String>(); args.add(patchsetCreatedHook.getAbsolutePath()); args.add("--change"); args.add(event.change.id); <START> args.add("--change-number"); <END> args.add(event.change.number); args.add("--project"); args.add(event.change.project); args.add("--branch"); args.add(event.change.branch); args.add("--commit"); args.add(event.patchSet.revision); args.add("--patchset"); args.add(event.patchSet.number); runHook(getRepo(change), args); }</code><technical_language>not. I hope kill in future. If need a URL change, instead use: $BASE_URL/r/$change $BASE_URL is URL access server in browser $change is event.change_id is passed in --change flag. Or.. server generate URL pass a --change-url flag</technical_language>

Target:
public void doPatchsetCreatedHook(final Change change, final PatchSet patchSet) { final PatchSetCreatedEvent event = new PatchSetCreatedEvent(); event.change = getChangeAttribute(change); event.patchSet = getPatchSetAttribute(patchSet); fireEvent(change, event); final List<String> args = new ArrayList<String>(); args.add(patchsetCreatedHook.getAbsolutePath()); args.add("--change"); args.add(event.change.id); args.add("--change-url"); args.add(event.change.url); args.add("--project"); args.add(event.change.project); args.add("--branch"); args.add(event.change.branch); args.add("--commit"); args.add(event.patchSet.revision); args.add("--patchset"); args.add(event.patchSet.number); runHook(getRepo(change), args); }
Source:
<code>private NSArray selectionsFromBindings() { if (canGetValueForBinding(Keys.Selections)) { NSArray result = (NSArray)valueForBinding(Keys.Selections); <START> if (hasBinding(Keys.SortKey)) { <END> String sortKey = stringValueForBinding(Keys.SortKey); result = ERXArrayUtilities.sortedArraySortedWithKey(result, sortKey); } if(result != null) { return result; } } return NSArray.EmptyArray; }</code><technical_language>moved if(result != null) { block sorting a non-existing result sense throw exception in ERXArrayUtilities</technical_language>

Target:
private NSArray selectionsFromBindings() { if (canGetValueForBinding(Keys.Selections)) { NSArray result = (NSArray)valueForBinding(Keys.Selections); if(result != null) { if (hasBinding(Keys.SortKey)) { String sortKey = stringValueForBinding(Keys.SortKey); result = ERXArrayUtilities.sortedArraySortedWithKey(result, sortKey); } return result; } } return NSArray.EmptyArray; }
Source:
<code>public LocalStreamProcessorListener(String processorId) { <START> if (processorId == null) { <END> throw new NullPointerException("processorId cannot be null in LocalStreamProcessorListener!!"); } this.processorId = processorId; }</code><technical_language>Minor: StringUtils.isEmpty</technical_language>

Target:
public LocalStreamProcessorListener(String processorId) { if (StringUtils.isEmpty(processorId)) { throw new NullPointerException("processorId has to be defined in LocalStreamProcessorListener."); } this.processorId = processorId; }
Source:
<code>public void testSocketSourceGenerator() throws Exception { final ExecutorService serverExecutor = Executors.newSingleThreadExecutor(); final List<String> inputStream = Arrays.asList( "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "In in leo nec erat fringilla mattis eu non massa.", "Cras quis diam suscipit, commodo enim id, pulvinar nunc."); final List<String> result = new LinkedList<>(); final ServerSocket serverSoc = serverSocket; serverExecutor.submit(() -> { try { <START> final Socket sc = serverSoc.accept(); <END> System.out.println("Socket is connected to " + sc); final PrintWriter out = new PrintWriter(sc.getOutputStream(), true); inputStream.stream().forEach(out::println); out.close(); sc.close(); } catch (final IOException e) { e.printStackTrace(); throw new RuntimeException(e); } }); final JavaConfigurationBuilder jcb = Tang.Factory.getTang().newConfigurationBuilder(); jcb.bindNamedParameter(SocketServerIp.class, "127.0.0.1"); jcb.bindNamedParameter(SocketServerPort.class, "8030"); jcb.bindImplementation(SourceGenerator.class, TextSocketStreamGenerator.class); final Injector injector = Tang.Factory.getTang().newInjector(jcb.build()); final SourceGenerator<String> sourceGenerator = injector.getInstance(SourceGenerator.class); sourceGenerator.setOutputEmitter(result::add); sourceGenerator.start(); Thread.sleep(3000); sourceGenerator.close(); Assert.assertEquals("SourceGenerator should generate " + inputStream, inputStream, result); }</code><technical_language>Variable naming. consistent entire codebase. sc? sock socket</technical_language>

Target:
public void testSocketSourceGenerator() throws Exception { final List<String> inputStream = Arrays.asList( "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "In in leo nec erat fringilla mattis eu non massa.", "Cras quis diam suscipit, commodo enim id, pulvinar nunc."); final CountDownLatch countDownLatch = new CountDownLatch(inputStream.size()); final ExecutorService serverExecutor = Executors.newSingleThreadExecutor(); final List<String> result = new LinkedList<>(); serverExecutor.submit(() -> { try { final Socket socket = serverSocket.accept(); LOG.info("Socket is connected to " + socket); final PrintWriter out = new PrintWriter(socket.getOutputStream(), true); inputStream.stream().forEach(out::println); out.close(); socket.close(); } catch (final IOException e) { e.printStackTrace(); throw new RuntimeException(e); } }); final JavaConfigurationBuilder jcb = Tang.Factory.getTang().newConfigurationBuilder(); jcb.bindNamedParameter(SocketServerIp.class, serverIpAddress); jcb.bindNamedParameter(SocketServerPort.class, Integer.toString(port)); jcb.bindImplementation(SourceGenerator.class, TextSocketStreamGenerator.class); final Injector injector = Tang.Factory.getTang().newInjector(jcb.build()); try (final SourceGenerator<String> sourceGenerator = injector.getInstance(SourceGenerator.class)) { sourceGenerator.setOutputEmitter((data) -> { result.add(data); countDownLatch.countDown(); }); sourceGenerator.start(); countDownLatch.await(); } finally { Assert.assertEquals("SourceGenerator should generate " + inputStream, inputStream, result); } }
Source:
<code>public void testInterceptResolve() throws IOException { String pathAfterResolution = "/user-hadoop"; Path remainingPath = new Path("/ad-data"); String srcRegex = "hadoop"; String replaceString = "hdfs"; RegexMountPointResolvedDstPathReplaceInterceptor interceptor = new RegexMountPointResolvedDstPathReplaceInterceptor(srcRegex, replaceString); interceptor.initialize(); <START> Assert.assertTrue( <END> interceptor.interceptResolvedDestPathStr(pathAfterResolution) .equals("/user-hdfs")); }</code><technical_language>want assertEquals instead</technical_language>

Target:
public void testInterceptResolve() throws IOException { String pathAfterResolution = "/user-hadoop"; String srcRegex = "hadoop"; String replaceString = "hdfs"; RegexMountPointResolvedDstPathReplaceInterceptor interceptor = new RegexMountPointResolvedDstPathReplaceInterceptor(srcRegex, replaceString); interceptor.initialize(); Assert.assertEquals("/user-hdfs", interceptor.interceptResolvedDestPathStr(pathAfterResolution)); }
Source:
<code>public void testAdaptForTable(){ GCRule gcRule = GCRULES.maxVersions(1); ColumnFamily columnFamily = ColumnFamily.newBuilder() .setGcRule(gcRule.toProto()).build(); <START> Table table = Table.fromProto(com.google.bigtable.admin.v2.Table.newBuilder() <END> .setName(TABLE_NAME) .putColumnFamilies(COLUMN_FAMILY, columnFamily).build()); HTableDescriptor actualTableDesc = tableAdapter.adapt(table); HTableDescriptor expected = new HTableDescriptor(TableName.valueOf(TABLE_ID)); expected.addFamily(new HColumnDescriptor(COLUMN_FAMILY)); Assert.assertEquals(expected, actualTableDesc); }</code><technical_language>This wrong</technical_language>

Target:
public void testAdaptForTable(){ GCRule gcRule = GCRULES.maxVersions(1); ColumnFamily columnFamily = ColumnFamily.newBuilder() .setGcRule(gcRule.toProto()).build(); Table table = Table.newBuilder() .setName(TABLE_NAME) .putColumnFamilies(COLUMN_FAMILY, columnFamily).build(); HTableDescriptor actualTableDesc = tableAdapter.adapt( com.google.cloud.bigtable.admin.v2.models.Table.fromProto(table)); HTableDescriptor expected = new HTableDescriptor(TableName.valueOf(TABLE_ID)); expected.addFamily(new HColumnDescriptor(COLUMN_FAMILY)); Assert.assertEquals(expected, actualTableDesc); }
Source:
<code>public void deployContrib(String name, String contrib) throws Exception { RuntimeContext context = runtime.getContext(name); if (context == null) { context = runtime.getContext(); BundleFile file = lookupBundle(name); <START> URL location = file.getEntry(contrib); <END> if (location == null) { throw new AssertionError("Cannot locate " + contrib + " in " + name); } context.deploy(location); return; } context.deploy(contrib); }</code><technical_language>add INFO log bundle install</technical_language>

Target:
public void deployContrib(String name, String contrib) throws Exception { RuntimeContext context = runtime.getContext(name); if (context == null) { context = runtime.getContext(); BundleFile file = lookupBundle(name); URL location = file.getEntry(contrib); if (location == null) { throw new AssertionError("Cannot locate " + contrib + " in " + name); } context.deploy(location); } else { context.deploy(contrib); } }
Source:
<code>private synchronized void populateFromDbHelper(Map<Long, ResourceGroupSpecBuilder> recordMap, Set<Long> rootGroupIds, Map<Long, ResourceGroupIdTemplate> resourceGroupIdTemplateMap, Map<Long, Set<Long>> subGroupIdsToBuild) { List<ResourceGroupSpecBuilder> records = dao.getResourceGroups(nodeInfo.getEnvironment()); <START> records.stream() <END> .forEach(record -> { recordMap.put(record.getId(), record); if (!record.getParentId().isPresent()) { rootGroupIds.add(record.getId()); resourceGroupIdTemplateMap.put(record.getId(), new ResourceGroupIdTemplate(record.getNameTemplate().toString())); } else { subGroupIdsToBuild.computeIfAbsent(record.getParentId().get(), k -> new HashSet<>()).add(record.getId()); } }); }</code><technical_language>revert put this refactoring a commit</technical_language>

Target:
private synchronized void populateFromDbHelper(Map<Long, ResourceGroupSpecBuilder> recordMap, Set<Long> rootGroupIds, Map<Long, ResourceGroupIdTemplate> resourceGroupIdTemplateMap, Map<Long, Set<Long>> subGroupIdsToBuild) { List<ResourceGroupSpecBuilder> records = dao.getResourceGroups(nodeInfo.getEnvironment()); for (ResourceGroupSpecBuilder record : records) { recordMap.put(record.getId(), record); if (!record.getParentId().isPresent()) { rootGroupIds.add(record.getId()); resourceGroupIdTemplateMap.put(record.getId(), new ResourceGroupIdTemplate(record.getNameTemplate().toString())); } else { subGroupIdsToBuild.computeIfAbsent(record.getParentId().get(), k -> new HashSet<>()).add(record.getId()); } } }
Source:
<code>protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("url", url) .append("username", username) .append("originType", originType) <START> .append("vmsNames", <END> vmsNames); }</code><technical_language>vmNames</technical_language>

Target:
protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("url", url) .append("username", username) .append("originType", originType) .append("namesOfVms", namesOfVms); }
Source:
<code>public void prohibitedCustomHeaderFails() throws Exception { CouchConfig customCouchConfig = getCouchConfig(); Map<String, String> customHeaders = new HashMap<String, String>(); <START> customHeaders.put("WWW-Authenticate", "test"); <END> customCouchConfig.setCustomHeaders(customHeaders); HttpRequests client = new CouchClient(customCouchConfig, TEST_DB).getHttpClient(); URI allDbUri = this.uriHelper.allDbsUri(); InputStream is = client.get(allDbUri); Assert.assertNotNull(is); String s = IOUtils.toString(is); Assert.assertTrue(s.contains(TEST_DB)); }</code><technical_language>This a loop prohibited ones</technical_language>

Target:
public void prohibitedCustomHeaderFails() throws Exception { String[] prohibitedHeaders = {"WWW-Authenticate", "Host", "Connection", "Content-Type", "Accept", "Content-Length"}; for (String h : prohibitedHeaders) { try { CouchConfig customCouchConfig = getCouchConfig(); Map<String, String> customHeaders = new HashMap<String, String>(); customHeaders.put(h, "test"); customCouchConfig.setCustomHeaders(customHeaders); HttpRequests client = new CouchClient(customCouchConfig, TEST_DB).getHttpClient(); URI allDbUri = this.uriHelper.allDbsUri(); client.get(allDbUri); Assert.fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException iae) { ; } } }
Source:
<code>private boolean isArgValueIdentifierTerminator(char ch, boolean quoteOpen) { <START> return (ch == '|' && !quoteOpen) || (ch == ';' && !quoteOpen) || ch == '\0' || (ch == ' ' && !quoteOpen) <END> || (ch == '\t' && !quoteOpen) || (ch == '>' && !quoteOpen) || ch == '\r' || ch == '\n'; }</code><technical_language>do need add a (ch == '&' && !quoteOpen)</technical_language>

Target:
private boolean isArgValueIdentifierTerminator(char ch, boolean quoteOpen) { return (ch == '&' && !quoteOpen) || (ch == '|' && !quoteOpen) || (ch == ';' && !quoteOpen) || ch == '\0' || (ch == ' ' && !quoteOpen) || (ch == '\t' && !quoteOpen) || (ch == '>' && !quoteOpen) || ch == '\r' || ch == '\n'; }
Source:
<code>private static StringBuilder fakeBody(final Request... parts) throws IOException { final StringBuilder builder = new StringBuilder(); for (final Request part : parts) { builder.append( String.format("--%s", FakeMultipartRequest.BOUNDARY) ) .append(RqMultipart.CRLF) <START> .append("Content-Disposition: ") <END> .append( new RqHeaders.Smart( new RqHeaders.Base(part) ).single("Content-Disposition") ).append(RqMultipart.CRLF); final String body = new RqPrint(part).printBody(); if (!(RqMultipart.CRLF.equals(body) || body.isEmpty())) { builder.append(RqMultipart.CRLF) .append(body) .append(RqMultipart.CRLF); } } builder.append("Content-Transfer-Encoding: utf-8") .append(RqMultipart.CRLF) .append( String.format("--%s--", FakeMultipartRequest.BOUNDARY) ); return builder; }</code><technical_language>@2686747 string constant Content-Disposition: in class I need this supression</technical_language>

Target:
private static StringBuilder fakeBody(final Request... parts) throws IOException { final StringBuilder builder = new StringBuilder(100); for (final Request part : parts) { builder.append( String.format("--%s", FakeMultipartRequest.BOUNDARY) ) .append(RqMultipart.CRLF) .append(RqMultipart.DISPOSITION) .append(": ") .append( new RqHeaders.Smart( new RqHeaders.Base(part) ).single(RqMultipart.DISPOSITION) ).append(RqMultipart.CRLF); final String body = new RqPrint(part).printBody(); if (!(RqMultipart.CRLF.equals(body) || body.isEmpty())) { builder.append(RqMultipart.CRLF) .append(body) .append(RqMultipart.CRLF); } } builder.append("Content-Transfer-Encoding: utf-8") .append(RqMultipart.CRLF) .append( String.format("--%s--", FakeMultipartRequest.BOUNDARY) ); return builder; }
Source:
<code>public Integer call() throws Exception { try { Iterator<RemoteStore> storeIterator = stores.iterator(); if (storeIterator.hasNext()) { RemoteStore store = storeIterator.next(); RemoteCache<Object, Object> storeCache = store.getRemoteCache(); RemoteStoreConfiguration storeConfig = store.getConfiguration(); if (!storeConfig.hotRodWrapping()) { throw log.remoteStoreNoHotRodWrapping(cache.getName()); } AtomicInteger counter = new AtomicInteger(0); migrateEntriesWithMetadata(storeCache,counter); <START> gracefulShutdown(executorService); <END> return counter.intValue(); } return null; } finally { cache.removeListener(listener); } }</code><technical_language>Put in finally block</technical_language>

Target:
public Integer call() throws Exception { try { Iterator<RemoteStore> storeIterator = stores.iterator(); if (storeIterator.hasNext()) { RemoteStore store = storeIterator.next(); RemoteCache<Object, Object> storeCache = store.getRemoteCache(); RemoteStoreConfiguration storeConfig = store.getConfiguration(); if (!storeConfig.hotRodWrapping()) { throw log.remoteStoreNoHotRodWrapping(cache.getName()); } AtomicInteger counter = new AtomicInteger(0); migrateEntriesWithMetadata(storeCache, counter); awaitTermination(executorService); return counter.intValue(); } return null; } finally { cache.removeListener(listener); if (executorService != null) { executorService.shutdownNow(); } } }
Source:
<code>public void testAddFileWithOutOfRangeKey(){ <START> List<S3ObjectSummary> list = Arrays.asList(badKeyFile); <END> manger.addS3Objects(list.iterator(), mockCallback); verify(mockCallback).progressMade(null); verify(mockFileMetadataDao, never()).getFileState(badKeyFile.getBucketName(), badKeyFile.getKey()); verify(mockFolderMetadataDao, never()).createOrUpdateFolderState((FolderState) any()); }</code><technical_language>outOfRangeKeyFile</technical_language>

Target:
public void testAddFileWithOutOfRangeKey(){ List<S3ObjectSummary> list = Arrays.asList(outOfRangeKeyFile); manger.addS3Objects(list.iterator(), mockCallback); verify(mockCallback).progressMade(null); verify(mockFileMetadataDao, never()).getFileState(outOfRangeKeyFile.getBucketName(), outOfRangeKeyFile.getKey()); verify(mockFolderMetadataDao, never()).createOrUpdateFolderState((FolderState) any()); }
Source:
<code>public String toString() { String prefix = DISCONTINUE == getAction() ? "DC " : ""; return prefix + "DrugOrder(" + getDose() + getDoseUnits() + " of " <START> + (getDrugNonCoded() != null ? getDrugNonCoded() : (getDrug() != null ? getDrug().getName() : "[no drug]")) + " from " + getDateActivated() + " to " <END> + (isDiscontinuedRightNow() ? getDateStopped() : getAutoExpireDate()) + ")"; }</code><technical_language>Delegate isNonCodedDrug() making check</technical_language>

Target:
public String toString() { String prefix = DISCONTINUE == getAction() ? "DC " : ""; return prefix + "DrugOrder(" + getDose() + getDoseUnits() + " of " + (isNonCodedDrug() ? getDrugNonCoded() : (getDrug() != null ? getDrug().getName() : "[no drug]")) + " from " + getDateActivated() + " to " + (isDiscontinuedRightNow() ? getDateStopped() : getAutoExpireDate()) + ")"; }
Source:
<code>private void setUpAccessBaseAgingExpectations() { ReferenceQueue<Integer> queue = mock(ReferenceQueue.class); map = new ReapedMap<String, Integer>(1000, true, queue); <START> when(queue.poll()).thenReturn(null); <END> }</code><technical_language>is this necessary? This is default behaviour for mocked Object returning methods</technical_language>

Target:
private void setUpAccessBaseAgingExpectations() { ReferenceQueue<Integer> queue = mock(ReferenceQueue.class); map = new ReapedMap<String, Integer>(1000, true, queue); }
Source:
<code>public Vote[] getPredictionVotes() { double trueValue = this.lastSeenInstance.classValue(); return new Vote[] { new Vote("instance number", this.instanceIdentifier), <START> new Vote("true value", trueValue, 10), <END> new Vote("predicted value", this.lastPredictedValue, 10) }; }</code><technical_language>define a constant understandable name for 10</technical_language>

Target:
public Vote[] getPredictionVotes() { double trueValue = this.lastSeenInstance.classValue(); return new Vote[] { new Vote("instance number", this.instanceIdentifier), new Vote("true value", trueValue, this.DECIMAL_PLACES), new Vote("predicted value", this.lastPredictedValue, this.DECIMAL_PLACES) }; }
Source:
<code>protected DispatchRequest doExecute() { super.doExecute(); try { RequestBuilder requestBuilder = buildRequest(); return new GwtHttpDispatchRequest(requestBuilder.send()); <START> } catch (RequestException | ActionException e) { <END> onExecuteFailure(e); } return new CompletedDispatchRequest(); }</code><technical_language>Java 7 rocks for :D</technical_language>

Target:
protected DispatchRequest doExecute() { try { RequestBuilder requestBuilder = buildRequest(); return new GwtHttpDispatchRequest(requestBuilder.send()); } catch (RequestException | ActionException e) { onExecuteFailure(e); } return new CompletedDispatchRequest(); }
Source:
<code>public void emptyRegexValidationFails(){ <START> SpamRuleDto spamRuleDto = randomSpamRuleDto().setRegex(""); <END> Set<ConstraintViolation<SpamRuleDto>> constraintViolations = validator.validate(spamRuleDto); Assert.assertEquals(constraintViolations.size(), 1); }</code><technical_language>nullOrBlank() function test for - null, empty space strings</technical_language>

Target:
public void emptyRegexValidationFails(){ SpamRuleDto spamRuleDto = randomSpamRuleDto().setRegex(nullOrEmpty()); Set<ConstraintViolation<SpamRuleDto>> constraintViolations = validator.validate(spamRuleDto); assertEquals(constraintViolations.size(), 1); }
Source:
<code>protected IgniteAwareApplication() { Runtime.getRuntime().addShutdownHook(hook = new Thread(() -> { log.info("SIGTERM recorded."); if (!finished && !broken) terminate(); else log.info("Application already done [finished=" + finished + ", broken=" + broken + "]"); <START> log.info("Waiting for graceful termination..."); while (!finished && !broken) { if (log.isTraceEnabled()) log.trace("Waiting for graceful termination cycle..."); <END> try { U.sleep(100); } catch (IgniteInterruptedCheckedException e) { e.printStackTrace(); } } log.info("Graceful termination done."); })); log.info("ShutdownHook registered."); }</code><technical_language>do need this additional logging</technical_language>

Target:
protected IgniteAwareApplication() { Runtime.getRuntime().addShutdownHook(hook = new Thread(() -> { log.info("SIGTERM recorded."); if (!finished && !broken) terminate(); else log.info("Application already done [finished=" + finished + ", broken=" + broken + "]"); if (log.isDebugEnabled()) log.debug("Waiting for graceful termination..."); while (!finished && !broken) { log.info("Waiting for graceful termination cycle..."); try { U.sleep(100); } catch (IgniteInterruptedCheckedException e) { e.printStackTrace(); } } if (log.isDebugEnabled()) log.debug("Graceful termination done."); })); log.info("ShutdownHook registered."); }
Source:
<code>private Vector createOrcVector(TajoDataTypes.DataType type) { switch (type.getType()) { case INT1: case INT2: case INT4: case INT8: <START> case UINT1: case UINT2: case UINT4: case UINT8: <END> case INET4: case TIMESTAMP: case DATE: return new LongVector(); case FLOAT4: case FLOAT8: return new DoubleVector(); case BOOLEAN: case NULL_TYPE: return new BooleanVector(); case BLOB: case TEXT: case CHAR: case PROTOBUF: return new SliceVector(); default: throw new UnsupportedException("This data type is not supported currently: "+type.toString()); } }</code><technical_language>Unsigned types in current implementation. So, omit them</technical_language>

Target:
private Vector createOrcVector(TajoDataTypes.DataType type) { switch (type.getType()) { case INT1: case INT2: case INT4: case INT8: case INET4: case TIMESTAMP: case DATE: return new LongVector(); case FLOAT4: case FLOAT8: return new DoubleVector(); case BOOLEAN: case NULL_TYPE: return new BooleanVector(); case BLOB: case TEXT: case CHAR: case PROTOBUF: return new SliceVector(); default: LOG.error("Not supported type for "+type.toString()); throw new UnimplementedException("ORC type: "+type.toString()); } }
Source:
<code>public void execute(final AsyncResponse asyncResponse, final String id, final String details, final String command, String kwargs, final int timeout) { final InstrumentAgent thisAgent = discovery.getAgent(id); if (thisAgent != null) { if (kwargs == null) kwargs = "{}"; final String myKwargs = kwargs; executor.execute(new Runnable() { @Override public void run() { <START> try { ClusterTask ct = ClusterLockUtils.lookupLock(id, details); if (ct != null) { ClusterTaskPK id = ct.getId(); log.handle(Priority.INFO, "ID name = " + id.getName() + " Details = " + id.getDetails() + " locked = " + ct.isRunning()); if (!ct.isRunning()) { String reply = thisAgent.execute(command, myKwargs, timeout); asyncResponse.resume(Response.ok(reply).type(MediaType.APPLICATION_JSON).build()); } else { asyncResponse.resume(Response.ok("Can't execute " + command + ". ID = " + id.getName() + " is locked", MediaType.APPLICATION_JSON).build()); } } else { log.handle(Priority.INFO, "LockUtils lookupLock returns null for Cluster Task"); asyncResponse.resume(Response.ok("LockUtils lookupLock returns null Cluster Task", MediaType.APPLICATION_JSON).build()); } } catch (Exception e) { log.error("ClusterLockUtils.lookupLock exception", e); asyncResponse.resume(Response.ok("ClusterLockUtils.lookupLock exception", MediaType.APPLICATION_JSON).build()); } <END> } }); } else { asyncResponse.resume(agentNotFound()); } }</code><technical_language>please match existing indentation scheme</technical_language>

Target:
public void execute(final AsyncResponse asyncResponse, final String id, final String details, final String command, String kwargs, final int timeout) { final InstrumentAgent thisAgent = discovery.getAgent(id); if (thisAgent != null) { if (kwargs == null) kwargs = "{}"; final String myKwargs = kwargs; executor.execute(new Runnable() { @Override public void run() { try { ClusterTask ct = ClusterLockUtils.lookupLock(id, details); if (ct != null) { ClusterTaskPK id = ct.getId(); log.handle(Priority.INFO, "ID name = " + id.getName() + " Details = " + id.getDetails() + " locked = " + ct.isRunning()); if (!ct.isRunning()) { String reply = thisAgent.execute(command, myKwargs, timeout); asyncResponse.resume(Response.ok(reply).type(MediaType.APPLICATION_JSON).build()); } else { asyncResponse.resume(Response.ok("Can't execute " + command + ". ID = " + id.getName() + " is locked", MediaType.APPLICATION_JSON).build()); } } else { log.handle(Priority.INFO, "Error processing lock lookup for cluster task [" + id + "/" + details + "]"); asyncResponse.resume(Response.ok("Error processing lock lookup for cluster task [" + id + "/" + details + "]", MediaType.APPLICATION_JSON).build()); } } catch (Exception e) { log.error("Error Processing lock lookup for cluster task [" + id + "/" + details + "]", e); asyncResponse.resume(Response.ok("Error Processing lock lookup for cluster task [" + id + "/" + details + "]", MediaType.APPLICATION_JSON).build()); } } }); } else { asyncResponse.resume(agentNotFound()); } }
Source:
<code>public String toString() { <START> StringBuilder builder = new StringBuilder(); <END> builder.append("Record["); builder.append("id=").append(id); builder.append(", ").append("name=").append(name); builder.append(", ").append("type=").append(type); if (ttl != null) builder.append(", ").append("ttl=").append(ttl); if (data != null) builder.append(", ").append("data=").append(data); if (priority != null) builder.append(", ").append("priority=").append(priority); builder.append("]"); return builder.toString(); }</code><technical_language>lots of loc :) this method present for toString ordering</technical_language>

Target:
public String toString() { return new StringBuilder(name).append(type).append(ttl).append(data).append(priority).toString(); }
Source:
<code>void testNewTargetGroupsWithEmptyUnitsAndEnemyUnits() { final List<TargetGroup> result = TargetGroup.newTargetGroups(List.of(), List.of()); <START> assertEquals(0, result.size()); <END> }</code><technical_language>nit: <LINK_0> assertEquals(0, results.size()) -> assertThat(results, is(emptyCollection())</technical_language>

Target:
void testNewTargetGroupsWithEmptyUnitsAndEnemyUnits() { final List<TargetGroup> result = TargetGroup.newTargetGroups(List.of(), List.of()); assertThat(result, empty()); }
Source:
<code>public String listSenders(final Model model) { HashMap<Sender, Boolean> optInRequiredSenders = new HashMap<>(); Sender.all().stream() .filter(Sender_Base::getOptInRequired) .filter(sender -> sender.getRecipients().stream().anyMatch(group -> group.isMember(Authenticate.getUser()))) .forEach(sender -> optInRequiredSenders.put(sender, sender.getOptedInUsers().contains(Authenticate.getUser()))); <START> final boolean isOptOutAvailable = MessagingSystem.getInstance().getOptOutAvailable().isMember(Authenticate.getUser()); <END> model.addAttribute("isOptOutAvailable", isOptOutAvailable); if (isOptOutAvailable) { model.addAttribute("isOptedOut", MessagingSystem.getInstance().getOptedOutGroup().isMember(Authenticate.getUser())); } model.addAttribute("optInRequiredSenders", optInRequiredSenders); return "/messaging/listOptIns"; }</code><technical_language>I this is enough. Imagine scenario: 1. user is able opt-out it. 2. undetermined period, is longer member of optOutAvailable group 3. wants remove opt-out option can't. user able remove opt-out if is member of optedOutGroup</technical_language>

Target:
public String listSenders(final Model model) { HashMap<Sender, Boolean> optInRequiredSenders = new HashMap<>(); Sender.all().stream() .filter(Sender_Base::getOptInRequired) .filter(sender -> sender.getRecipients().stream().anyMatch(group -> group.isMember(Authenticate.getUser()))) .forEach(sender -> optInRequiredSenders.put(sender, sender.getOptedInUsers().contains(Authenticate.getUser()))); final boolean canConfigOptOut = MessagingSystem.getInstance().getOptOutAvailable().isMember(Authenticate.getUser()) || MessagingSystem.getInstance().getOptedOutGroup().isMember(Authenticate.getUser()); model.addAttribute("canConfigOptOut", canConfigOptOut); if (canConfigOptOut) { model.addAttribute("isOptedOut", MessagingSystem.getInstance().getOptedOutGroup().isMember(Authenticate.getUser())); } model.addAttribute("optInRequiredSenders", optInRequiredSenders); return "/messaging/listOptIns"; }
Source:
<code>private Set<OmniEclipseProject> fetchEclipseProjects(GradleBuild build, SubMonitor progress) { progress.setTaskName("Loading Gradle project models"); <START> Collection<EclipseProject> models = build.fetchCompositeModel(EclipseProject.class, getToken(), progress); <END> ImmutableSet.Builder<OmniEclipseProject> projects = ImmutableSet.builder(); for (EclipseProject model : models) { projects.addAll(DefaultOmniEclipseProject.from(model).getAll()); } return projects.build(); }</code><technical_language>This code in model provider</technical_language>

Target:
private Set<OmniEclipseProject> fetchEclipseProjects(GradleBuild build, SubMonitor progress) { progress.setTaskName("Loading Gradle project models"); ModelProvider modelProvider = build.getModelProvider(); return modelProvider.fetchEclipseGradleProjects(FetchStrategy.FORCE_RELOAD, getToken(), progress); }
Source:
<code>private void cancel(Job[] jobs) { <START> for (Job job : jobs) { <END> job.cancel(); } }</code><technical_language>"brackets for single statements" cleanup in this file done in a separate commit, mix unrelated changes</technical_language>

Target:
private void cancel(Job[] jobs) { for (Job job : jobs) job.cancel(); }
Source:
<code>public boolean onCreateOptionsMenu(Menu menu) { menu.clear(); getSupportMenuInflater().inflate(R.menu.main_menu, menu); statsModeMenuItem = menu.findItem(R.id.itemMainmenuStatsMode); if (isRefreshing()) { <START> if (swipeRefresh != null && !swipeRefresh.isRefreshing()) <END> swipeRefresh.setRefreshing(true); } updateStatsMode(); return true; }</code><technical_language>tabs</technical_language>

Target:
public boolean onCreateOptionsMenu(Menu menu) { menu.clear(); getSupportMenuInflater().inflate(R.menu.main_menu, menu); statsModeMenuItem = menu.findItem(R.id.itemMainmenuStatsMode); if (isRefreshing()) menu.findItem(R.id.itemMainmenuRefresh).setActionView( R.layout.action_bar_indeterminate_progress); updateStatsMode(); return true; }
Source:
<code>default AnnotatedTypeConfigurator<T> configure() { <START> return null; <END> }</code><technical_language>I this is good. In fact, returning null in default impl nasty. I understand meant provide a default method, this class is implemented end user CDI impl itself, *not having* default harm IMO</technical_language>

Target:
public default AnnotatedTypeConfigurator<T> configure() { throw new UnsupportedOperationException("Configuration not supported here"); }
Source:
<code>public List<Aggregator> generateInternalAggs(final Schema inputSchema) throws DbException { Objects.requireNonNull(inputSchema, "inputSchema"); Preconditions.checkArgument( initializers.size() == updaters.size(), "must have the same number of aggregate state initializers (%s) and updaters (%s)", initializers.size(), updaters.size()); for (int i = 0; i < initializers.size(); i++) { Preconditions.checkArgument( Objects.equals(initializers.get(i).getOutputName(), updaters.get(i).getOutputName()), "initializers[i] and updaters[i] have different names (%s) != (%s)", initializers.get(i).getOutputName(), updaters.get(i).getOutputName()); } Schema stateSchema = generateStateSchema(inputSchema); initEvaluator = getEvalScript(initializers, new ExpressionOperatorParameter(inputSchema)); updateEvaluator = getEvalScript(updaters, new ExpressionOperatorParameter(inputSchema, stateSchema)); ExpressionOperatorParameter emitParams = new ExpressionOperatorParameter(null, stateSchema); ImmutableList.Builder<Type> types = ImmutableList.builder(); ImmutableList.Builder<String> names = ImmutableList.builder(); for (Expression e : emitters) { types.add(e.getOutputType(emitParams)); names.add(e.getOutputName()); } resultSchema = new Schema(types, names); return ImmutableList.of( <START> new UserDefinedAggregator(initEvaluator, updateEvaluator, resultSchema, stateSchema)); <END> }</code><technical_language>OK, emitEvaluators computed emitters in Aggregate operator</technical_language>

Target:
public List<Aggregator> generateInternalAggs(final Schema inputSchema) throws DbException { for (int i = 0; i < initializers.size(); ++i) { initEvaluators.add( getEvaluator(initializers.get(i), new ExpressionOperatorParameter(inputSchema), i)); } Schema stateSchema = generateStateSchema(inputSchema); ExpressionOperatorParameter param = new ExpressionOperatorParameter(inputSchema, stateSchema, pyFuncReg); for (int i = 0; i < updaters.size(); ++i) { if (updaters.get(i).isRegisteredPythonUDF()) { updateEvaluators.add(new PythonUDFEvaluator(updaters.get(i), param)); } else { updateEvaluators.add(getEvaluator(updaters.get(i), param, i)); } } ExpressionOperatorParameter emitParams = new ExpressionOperatorParameter(null, stateSchema); ImmutableList.Builder<Type> types = ImmutableList.builder(); ImmutableList.Builder<String> names = ImmutableList.builder(); for (Expression e : emitters) { types.add(e.getOutputType(emitParams)); names.add(e.getOutputName()); } resultSchema = new Schema(types, names); return ImmutableList.of( new UserDefinedAggregator(initEvaluators, updateEvaluators, resultSchema, stateSchema)); }
Source:
<code>public void visitMethodInvocation(MethodInvocationTree mit) { super.visitMethodInvocation(mit); if (LOGGING_METHODS.anyMatch(mit)) { <START> Iterator<UsageStatus> iterator = usageStatusStack.iterator(); <END> while (iterator.hasNext()) { iterator.next().addLoggingMethodInvocation(mit); } } }</code><technical_language>usageStatusStack.forEach(</technical_language>

Target:
public void visitMethodInvocation(MethodInvocationTree mit) { super.visitMethodInvocation(mit); if (LOGGING_METHODS.anyMatch(mit)) { usageStatusStack.forEach(usageStatus -> usageStatus.addLoggingMethodInvocation(mit)); } }
Source:
<code>public ExternalBeanDefinition(String beanInfo) throws Exception { if (beanInfo == null || beanInfo.isEmpty()) { <START> throw new Exception("External type name missing"); <END> } int lastPos = beanInfo.lastIndexOf("."); if (lastPos >= 0) { this.beanPackageName = beanInfo.substring(0, lastPos); this.beanName = beanInfo.substring(lastPos + 1); } else { this.beanPackageName = DEFAULT_BEAN_PKG; this.beanName = beanInfo; } }</code><technical_language>Please general Exception type for throwing exceptions. This handling of exceptions hard, type of exception is hidden. For this, IllegalArgumentException - exception specific - Illegal for beanInfo argument provided. Minor edit: please reformat throw line, is right 4 spaces</technical_language>

Target:
public ExternalBeanDefinition(String beanInfo) throws IllegalArgumentException { if (beanInfo == null || beanInfo.isEmpty()) { throw new IllegalArgumentException("External type name missing"); } int lastPos = beanInfo.lastIndexOf("."); if (lastPos >= 0) { this.beanPackageName = beanInfo.substring(0, lastPos); this.beanName = beanInfo.substring(lastPos + 1); } else { this.beanPackageName = DEFAULT_BEAN_PKG; this.beanName = beanInfo; } }
Source:
<code>public static InputStream getInputStreamFromName(String name) { int prefixEnd = name.indexOf(":"); String prefix = null; String path = name; if (prefixEnd != -1) { prefix = name.substring(0, prefixEnd); path = name.substring(prefixEnd + 1); } <START> if (prefix == null) { <END> throw new TechnicalException("prefix is not defined"); } switch (prefix) { case RESOURCE_PREFIX: if (!path.startsWith("/")) { path = "/" + path; } return CommonHelper.class.getResourceAsStream(path); case CLASSPATH_PREFIX: return Thread.currentThread().getContextClassLoader().getResourceAsStream(path); case HTTP_PREFIX: logger.warn("IdP metadata is retrieved from an insecure http endpoint [{}]", path); return getInputStreamViaHttp(name); case HTTPS_PREFIX: return getInputStreamViaHttp(name); default: try { return new FileInputStream(path); } catch (FileNotFoundException e) { throw new TechnicalException(e); } } }</code><technical_language>compatible, support case prefix</technical_language>

Target:
public static InputStream getInputStreamFromName(String name) { int prefixEnd = name.indexOf(":"); String prefix = null; String path = name; if (prefixEnd != -1) { prefix = name.substring(0, prefixEnd); path = name.substring(prefixEnd + 1); } if (prefix == null || prefix.isEmpty()) { try { return new FileInputStream(path); } catch (FileNotFoundException e) { throw new TechnicalException(e); } } switch (prefix) { case RESOURCE_PREFIX: if (!path.startsWith("/")) { path = "/" + path; } return CommonHelper.class.getResourceAsStream(path); case CLASSPATH_PREFIX: return Thread.currentThread().getContextClassLoader().getResourceAsStream(path); case HttpConstants.SCHEME_HTTP: logger.warn("file is retrieved from an insecure http endpoint [{}]", path); return getInputStreamViaHttp(name); case HttpConstants.SCHEME_HTTPS: return getInputStreamViaHttp(name); default: throw new TechnicalException("prefix is not handled:" + prefix); } }
Source:
<code>public Map<String, String> query(Serializer serializer) { if (serializer == null) { serializer = Serializer.defaultSerializer(); } Map<String, String> map = new HashMap<>(); DateTimeFormatter formatter = serializer.dateTimeFormatter(); if (offset != null) { map.put("offset", offset.toString()); } if (limit != null) { map.put("limit", limit.toString()); } if (from != null) { <START> map.put("from", from.atZone(ZoneId.of("Z")).format(formatter)); <END> } if (to != null) { map.put("to", to.atZone(ZoneId.of("Z")).format(formatter)); } if (order != null) { map.put("order", serializer.serializeToQueryParams(order)); } return Collections.unmodifiableMap(map); }</code><technical_language>do need convert Instant ZonedDateTime formatting here</technical_language>

Target:
public Map<String, String> query(Serializer serializer) { if (serializer == null) { serializer = Serializer.defaultSerializer(); } Map<String, String> map = new HashMap<>(); DateTimeFormatter formatter = serializer.dateTimeFormatter(); if (offset != null) { map.put("offset", offset.toString()); } if (limit != null) { map.put("limit", limit.toString()); } if (from != null) { map.put("from", formatter.format(from)); } if (to != null) { map.put("to", formatter.format(to)); } if (order != null) { map.put("order", serializer.serializeToQueryParams(order)); } return Collections.unmodifiableMap(map); }
Source:
<code>public static <E> GenericData getDataModelForType(Class<E> type) { if (SpecificRecord.class.isAssignableFrom(type)) { return new SpecificData(type.getClassLoader()); } else if (GenericRecord.class.isAssignableFrom(type)) { return GenericData.get(); <START> } else if (IndexedRecord.class.isAssignableFrom(type)) { <END> return GenericData.get(); } else { return ReflectData.get(); } }</code><technical_language>GenericRecord extends IndexedRecord, this code path hit</technical_language>

Target:
public static <E> GenericData getDataModelForType(Class<E> type) { if (SpecificRecord.class.isAssignableFrom(type)) { return new SpecificData(type.getClassLoader()); } else if (IndexedRecord.class.isAssignableFrom(type)) { return GenericData.get(); } else { return ReflectData.AllowNull.get(); } }
Source:
<code>public void run() { try { DataInputStream in = new DataInputStream(s.getInputStream()); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8")), true); byte[] head = new byte[10]; in.readFully(head); String header = new String(head, Charsets.US_ASCII); if (header.startsWith("GET ")) { respondHello(header,s); return; } String s = new DataInputStream(new SequenceInputStream(new ByteArrayInputStream(head),in)).readUTF(); if(s.startsWith("Protocol:")) { String protocol = s.substring(9); AgentProtocol p = AgentProtocol.of(protocol); if (p!=null) { if (Jenkins.getInstance().getAgentProtocols().contains(protocol)) { <START> LOGGER.log(Level.INFO, "Accepted {0} connection #{1} from {2}", new Object[] {protocol, id, this.s.getRemoteSocketAddress()}); <END> p.handle(this.s); } else { error(out, "Disabled protocol:" + s); } } else error(out, "Unknown protocol:" + s); } else { error(out, "Unrecognized protocol: "+s); } } catch (InterruptedException e) { LOGGER.log(Level.WARNING,"Connection #"+id+" aborted",e); try { s.close(); } catch (IOException _) { } } catch (IOException e) { LOGGER.log(Level.WARNING,"Connection #"+id+" failed",e); try { s.close(); } catch (IOException _) { } } }</code><technical_language>sort of is protocol</technical_language>

Target:
public void run() { try { LOGGER.log(Level.FINE, "Accepted connection #{0} from {1}", new Object[] {id, s.getRemoteSocketAddress()}); DataInputStream in = new DataInputStream(s.getInputStream()); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8")), true); byte[] head = new byte[10]; in.readFully(head); String header = new String(head, Charsets.US_ASCII); if (header.startsWith("GET ")) { respondHello(header,s); return; } String s = new DataInputStream(new SequenceInputStream(new ByteArrayInputStream(head),in)).readUTF(); if(s.startsWith("Protocol:")) { String protocol = s.substring(9); AgentProtocol p = AgentProtocol.of(protocol); if (p!=null) { if (Jenkins.getInstance().getAgentProtocols().contains(protocol)) { LOGGER.log(Level.INFO, "Accepted {0} connection #{1} from {2}", new Object[] {protocol, id, this.s.getRemoteSocketAddress()}); p.handle(this.s); } else { error(out, "Disabled protocol:" + s); } } else error(out, "Unknown protocol:" + s); } else { error(out, "Unrecognized protocol: "+s); } } catch (InterruptedException e) { LOGGER.log(Level.WARNING,"Connection #"+id+" aborted",e); try { s.close(); } catch (IOException _) { } } catch (IOException e) { LOGGER.log(Level.WARNING,"Connection #"+id+" failed",e); try { s.close(); } catch (IOException _) { } } }
Source:
<code>public List<Block> execute(RssMacroParameters parameters, String content, MacroTransformationContext context) throws MacroExecutionException { List<Block> result; SyndFeed feed = this.romeFeedFactory.createFeed(parameters); <START> this.setFeed(feed); <END> if (parameters.isDecoration()) { result = super.execute(parameters, content == null ? StringUtils.EMPTY : content, context); } else { result = Arrays.<Block>asList(new GroupBlock(Collections.singletonMap(CLASS_ATTRIBUTE, FEED_CLASS_VALUE))); } generateEntries(result.get(0), feed, parameters); return result; }</code><technical_language>nice explain a bit obvious</technical_language>

Target:
public List<Block> execute(RssMacroParameters parameters, String content, MacroTransformationContext context) throws MacroExecutionException { List<Block> result; SyndFeed feed = this.romeFeedFactory.createFeed(parameters); this.setFeed(feed); if (parameters.isDecoration()) { result = super.execute(parameters, content == null ? StringUtils.EMPTY : content, context); } else { result = Arrays.<Block>asList(new GroupBlock(Collections.singletonMap(CLASS_ATTRIBUTE, FEED_CLASS_VALUE))); } generateEntries(result.get(0), feed, parameters); this.removeContextFeed(); return result; }