auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private ByteArrayInputStream uploadPackV2(String... inputLines) throws Exception { ByteArrayOutputStream send = new ByteArrayOutputStream(); PacketLineOut pckOut = new PacketLineOut(send); for (String line : inputLines) { if (line == PacketLineIn.END) { pckOut.end(); } else if (line == PacketLineIn.DELIM) { pckOut.writeDelim(); } else { pckOut.writeString(line); } } UploadPack up = new UploadPack(server); up.setUseProtocolV2(true); ByteArrayOutputStream recv = new ByteArrayOutputStream(); up.upload(new ByteArrayInputStream(send.toByteArray()), recv, null); ByteArrayInputStream recvStream = new ByteArrayInputStream(recv.toByteArray()); PacketLineIn pckIn = new PacketLineIn(recvStream); assertThat(pckIn.readString(), <START> is("version 2")); <END> assertThat(pckIn.readString(), is("ls-refs")); assertThat(pckIn.readString(), is("fetch=shallow")); assertTrue(pckIn.readString() == PacketLineIn.END); return recvStream; }</code><technical_language>add a constant for "version 2"</technical_language>

Target:
private ByteArrayInputStream uploadPackV2(String... inputLines) throws Exception { ByteArrayOutputStream send = new ByteArrayOutputStream(); PacketLineOut pckOut = new PacketLineOut(send); for (String line : inputLines) { if (line == PacketLineIn.END) { pckOut.end(); } else if (line == PacketLineIn.DELIM) { pckOut.writeDelim(); } else { pckOut.writeString(line); } } UploadPack up = new UploadPack(server); up.setUseProtocolV2(true); ByteArrayOutputStream recv = new ByteArrayOutputStream(); up.upload(new ByteArrayInputStream(send.toByteArray()), recv, null); ByteArrayInputStream recvStream = new ByteArrayInputStream(recv.toByteArray()); PacketLineIn pckIn = new PacketLineIn(recvStream); assertThat(pckIn.readString(), is("version 2")); assertThat( Arrays.asList(pckIn.readString(), pckIn.readString()), hasItems("ls-refs", "fetch=shallow")); assertTrue(pckIn.readString() == PacketLineIn.END); return recvStream; }
Source:
<code>private void repaint() { if (graph != null) { System.out.println("repainting graph..."); Tile model = new Tile(graph); TileView view = new TileView(); TileController tc = new TileController(view, model); Group root = new Group(); <START> wrapper.hvalueProperty().addListener( <END> (ChangeListener<Number>) (ov, oldVal, newVal) -> { repaintPosition(tc, root, newVal.doubleValue()); }); Rectangle clip = new Rectangle(getMaxUnifiedEnd(graph) * VertexView.HORIZONTALSCALE, 0); root.getChildren().add(clip); repaintPosition(tc, root, wrapper.hvalueProperty().doubleValue()); } }</code><technical_language>Iffy formatting</technical_language>

Target:
private void repaint() { if (graph != null) { GraphContainer model = new GraphContainer(graph); TileView view = new TileView(); TileController tileController = new TileController(view, model); Group root = new Group(); repaintPosition(tileController, root, wrapper.hvalueProperty() .doubleValue()); wrapper.hvalueProperty().addListener( (observable, oldValue, newValue) -> { repaintPosition(tileController, root, newValue.doubleValue()); }); Rectangle clip = new Rectangle(getMaxUnifiedEnd(graph) * VertexView.HORIZONTALSCALE, 0); root.getChildren().add(clip); repaintPosition(tileController, root, wrapper.hvalueProperty() .doubleValue()); } }
Source:
<code>public Request iterate(final Request req, final Coordinates cords) { <START> return null; <END> }</code><technical_language>return NULL, throw UnsupportedOperatedException instead</technical_language>

Target:
public Request iterate(final Request req, final Coordinates cords) { throw new UnsupportedOperationException(); }
Source:
<code>public MamQueryIQ parse(XmlPullParser parser, int initialDepth) throws Exception { String queryId = null; String node = null; DataForm dataForm = null; <START> if (parser.getName().equals(MamQueryIQ.ELEMENT)) { <END> queryId = parser.getAttributeValue("", "queryid"); node = parser.getAttributeValue("", "node"); boolean done = false; while (!done) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { if (parser.getName().equals(DataForm.ELEMENT)) { dataForm = new DataFormProvider().parse(parser); } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getName().equals(MamQueryIQ.ELEMENT)) { done = true; } } } } return new MamQueryIQ(queryId, node, dataForm); }</code><technical_language>is unusual, parser START_TAG of element. do feel is necessary check for this condition</technical_language>

Target:
public MamQueryIQ parse(XmlPullParser parser, int initialDepth) throws Exception { DataForm dataForm = null; String queryId = parser.getAttributeValue("", "queryid"); String node = parser.getAttributeValue("", "node"); outerloop: while (true) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { if (parser.getName().equals(DataForm.ELEMENT)) { dataForm = new DataFormProvider().parse(parser); } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getDepth() == initialDepth) { break outerloop; } } } return new MamQueryIQ(queryId, node, dataForm); }
Source:
<code>public static <T> TypeToken<T> getTypeToken(TypeToken<T> token, Class<? super T> raw) { if (raw!=null) return TypeToken.of((Class<T>)raw); <START> if (token!=null) return token; <END> throw new IllegalStateException("Both indicators of type are null"); }</code><technical_language>this prefer token raw</technical_language>

Target:
public static <T> TypeToken<T> getTypeToken(TypeToken<T> token, Class<? super T> raw) { if (token!=null) return token; if (raw!=null) return TypeToken.of((Class<T>)raw); throw new IllegalStateException("Both indicators of type are null"); }
Source:
<code>private void initPlugins() throws Exception { <START> Collection<? extends InitStep> pluginsInitSteps = pluginLoader.getInitSteps(); <END> for (InitStep initStep : pluginsInitSteps) { initStep.run(); } }</code><technical_language>shorter inline this variable in scope. :-)</technical_language>

Target:
private void initPlugins() throws Exception { for (InitStep initStep : pluginLoader.getInitSteps()) { initStep.run(); } }
Source:
<code>public <T> T cast(FormField<?> formField) { if (getDefaultOrNull(formField)) { return null; } if (this == formField.getValueType()) { return (T) formField.getValue(); } else if (STRING == formField.getValueType()) { <START> return (T) formField.getValue().toString(); <END> } else { throw LOGGER.logExceptionAsError(new UnsupportedOperationException(String.format("Cannot cast from " + "field value of type %s to type %s", formField.getValueType(), PHONE_NUMBER))); } }</code><technical_language>Is toString() required? of STRING type</technical_language>

Target:
public <T> T cast(FormField<?> formField) { if (isFieldValueNull(formField)) { return null; } return (T) String.valueOf(formField.getValue()); }
Source:
<code>public LengthFieldBasedFrameDecoder( ByteOrder byteOrder, int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) { checkPositive(maxFrameLength, "maxFrameLength"); checkPositiveOrZero(lengthFieldOffset, "lengthFieldOffset"); checkPositiveOrZero(initialBytesToStrip, "initialBytesToStrip"); if (lengthFieldOffset > maxFrameLength - lengthFieldLength) { throw new IllegalArgumentException( "maxFrameLength (" + maxFrameLength + ") " + "must be equal to or greater than " + "lengthFieldOffset (" + lengthFieldOffset + ") + " + "lengthFieldLength (" + lengthFieldLength + ")."); } <START> this.byteOrder = checkNotNull(byteOrder, "byteOrder"); <END> this.maxFrameLength = maxFrameLength; this.lengthFieldOffset = lengthFieldOffset; this.lengthFieldLength = lengthFieldLength; this.lengthAdjustment = lengthAdjustment; lengthFieldEndOffset = lengthFieldOffset + lengthFieldLength; this.initialBytesToStrip = initialBytesToStrip; this.failFast = failFast; }</code><technical_language>move check assignment other checks ensure behaviour is changed</technical_language>

Target:
public LengthFieldBasedFrameDecoder( ByteOrder byteOrder, int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) { this.byteOrder = checkNotNull(byteOrder, "byteOrder"); checkPositive(maxFrameLength, "maxFrameLength"); checkPositiveOrZero(lengthFieldOffset, "lengthFieldOffset"); checkPositiveOrZero(initialBytesToStrip, "initialBytesToStrip"); if (lengthFieldOffset > maxFrameLength - lengthFieldLength) { throw new IllegalArgumentException( "maxFrameLength (" + maxFrameLength + ") " + "must be equal to or greater than " + "lengthFieldOffset (" + lengthFieldOffset + ") + " + "lengthFieldLength (" + lengthFieldLength + ")."); } this.maxFrameLength = maxFrameLength; this.lengthFieldOffset = lengthFieldOffset; this.lengthFieldLength = lengthFieldLength; this.lengthAdjustment = lengthAdjustment; this.lengthFieldEndOffset = lengthFieldOffset + lengthFieldLength; this.initialBytesToStrip = initialBytesToStrip; this.failFast = failFast; }
Source:
<code>public static Optional<TableRefAndRemainder> tryParseTableRef(LockDescriptor lockDescriptor) { byte[] rawBytes = lockDescriptor.getBytes(); int endOfTableName = Bytes.indexOf(rawBytes, (byte) 0); if (endOfTableName == -1) { return Optional.empty(); } String fullyQualifiedName = new String(rawBytes, 0, endOfTableName); TableReference tableRef = TableReference.createFromFullyQualifiedName(fullyQualifiedName); <START> ByteString remainingBytes = ByteString.of(rawBytes, endOfTableName + 1, rawBytes.length - 1 - endOfTableName); <END> return Optional.of(ImmutableTableRefAndRemainder.of(tableRef, remainingBytes)); }</code><technical_language>clearer if rawBytes.length - (endOfTableName + 1)? fussed</technical_language>

Target:
public static Optional<TableRefAndRemainder> tryParseTableRef(LockDescriptor lockDescriptor) { byte[] rawBytes = lockDescriptor.getBytes(); int endOfTableName = Bytes.indexOf(rawBytes, (byte) 0); if (endOfTableName == -1) { return Optional.empty(); } String fullyQualifiedName = new String(rawBytes, 0, endOfTableName); TableReference tableRef = TableReference.createFromFullyQualifiedName(fullyQualifiedName); ByteString remainingBytes = ByteString.of(rawBytes, endOfTableName + 1, rawBytes.length - (endOfTableName + 1)); return Optional.of(ImmutableTableRefAndRemainder.of(tableRef, remainingBytes)); }
Source:
<code>public void ThrottleForNormalizeTestWithinIdeal() throws Exception { List<RateLimit> scenarios = new ArrayList<>(); int limit = 5000; int buffer = ApiRateLimitChecker.calculateBuffer(limit); int approximateIdeal = 4000; scenarios.add(new RateLimit(limit, approximateIdeal + buffer - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 101, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 99, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 99, soon)); scenarios.add(new RateLimit(limit, limit, soon)); setupStubs(scenarios); ApiRateLimitChecker.ThrottleForNormalize.checkApiRateLimit(listener, github); assertEquals(1, countOfOutputLinesContaining("under budget")); assertFalse(handler.getView().stream().anyMatch(m -> m.getMessage().contains("Sleeping"))); ApiRateLimitChecker.ThrottleForNormalize.checkApiRateLimit(listener, github); assertEquals(2, countOfOutputLinesContaining("rechecking")); assertEquals(3, countOfOutputLinesContaining("Still sleeping")); assertEquals(2, countOfOutputLinesContaining("Sleeping for")); assertEquals(1, countOfOutputLinesContaining("under budget")); <START> assertEquals(10, handler.getView().size()); <END> }</code><technical_language>EDIT: this is identical Liam said. making - this bump 8 10 is allow for new log lines, right? ([75](<LINK_0>, [106](<LINK_1></technical_language>

Target:
public void ThrottleForNormalizeTestWithinIdeal() throws Exception { List<RateLimit> scenarios = new ArrayList<>(); int limit = 5000; int buffer = ApiRateLimitChecker.calculateBuffer(limit); int approximateIdeal = 4000; scenarios.add(new RateLimit(limit, approximateIdeal + buffer - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 101, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 99, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 99, soon)); scenarios.add(new RateLimit(limit, limit, soon)); setupStubs(scenarios); ApiRateLimitChecker.ThrottleForNormalize.checkApiRateLimit(listener, github); assertEquals(1, countOfOutputLinesContaining("under budget")); assertFalse(handler.getView().stream().anyMatch(m -> m.getMessage().contains("Sleeping"))); ApiRateLimitChecker.ThrottleForNormalize.checkApiRateLimit(listener, github); assertEquals(2, countOfOutputLinesContaining("rechecking")); assertEquals(3, countOfOutputLinesContaining("Still sleeping")); assertEquals(2, countOfOutputLinesContaining("Sleeping for")); assertEquals(1, countOfOutputLinesContaining("under budget")); assertEquals(2, countOfOutputLinesContaining("Jenkins is attempting to evenly distribute GitHub API requests")); assertEquals(10, handler.getView().size()); }
Source:
<code>public boolean cleanupNode(final String id) { RegionAndId regionAndId = RegionAndId.fromSlashEncoded(id); ResourceGroup resourceGroup = resourceGroupMap.getUnchecked(regionAndId.region()); <START> String group = resourceGroup.name(); <END> VirtualMachine virtualMachine = api.getVirtualMachineApi(group).get(regionAndId.id()); if (virtualMachine == null) { return true; } logger.debug(">> destroying %s ...", regionAndId.slashEncode()); boolean vmDeleted = deleteVirtualMachine(group, virtualMachine); cleanupVirtualMachineNICs(group, virtualMachine); cleanupVirtualMachineStorage(group, virtualMachine); return vmDeleted; }</code><technical_language>[minor] name resourceGroupName</technical_language>

Target:
public boolean cleanupNode(final String id) { RegionAndId regionAndId = RegionAndId.fromSlashEncoded(id); ResourceGroup resourceGroup = resourceGroupMap.getUnchecked(regionAndId.region()); String resourceGroupName = resourceGroup.name(); VirtualMachine virtualMachine = api.getVirtualMachineApi(resourceGroupName).get(regionAndId.id()); if (virtualMachine == null) { return true; } logger.debug(">> destroying %s ...", regionAndId.slashEncode()); boolean vmDeleted = deleteVirtualMachine(resourceGroupName, virtualMachine); cleanupVirtualMachineNICs(resourceGroupName, virtualMachine); cleanupVirtualMachineStorage(resourceGroupName, virtualMachine); return vmDeleted; }
Source:
<code>public Factory(long nowMillis, Request request, Response cacheResponse) { this.nowMillis = nowMillis; this.request = request; this.cacheResponse = cacheResponse; if (cacheResponse != null) { this.sentRequestMillis = cacheResponse.sentRequestAtMillis(); this.receivedResponseMillis = cacheResponse.receivedResponseAtMillis(); Headers headers = cacheResponse.headers(); for (int i = 0, size = headers.size(); i < size; i++) { String fieldName = headers.name(i); String value = headers.value(i); if ("Date".equalsIgnoreCase(fieldName)) { servedDate = HttpDate.parse(value); servedDateString = value; } else if ("Expires".equalsIgnoreCase(fieldName)) { expires = HttpDate.parse(value); } else if ("Last-Modified".equalsIgnoreCase(fieldName)) { lastModified = HttpDate.parse(value); lastModifiedString = value; } else if ("ETag".equalsIgnoreCase(fieldName)) { etag = value; } else if ("Age".equalsIgnoreCase(fieldName)) { <START> ageSeconds = UtilKtKt.toNonNegativeInt(value, -1); <END> } } } }</code><technical_language>UtilKtKt a great name</technical_language>

Target:
public Factory(long nowMillis, Request request, Response cacheResponse) { this.nowMillis = nowMillis; this.request = request; this.cacheResponse = cacheResponse; if (cacheResponse != null) { this.sentRequestMillis = cacheResponse.sentRequestAtMillis(); this.receivedResponseMillis = cacheResponse.receivedResponseAtMillis(); Headers headers = cacheResponse.headers(); for (int i = 0, size = headers.size(); i < size; i++) { String fieldName = headers.name(i); String value = headers.value(i); if ("Date".equalsIgnoreCase(fieldName)) { servedDate = HttpDate.parse(value); servedDateString = value; } else if ("Expires".equalsIgnoreCase(fieldName)) { expires = HttpDate.parse(value); } else if ("Last-Modified".equalsIgnoreCase(fieldName)) { lastModified = HttpDate.parse(value); lastModifiedString = value; } else if ("ETag".equalsIgnoreCase(fieldName)) { etag = value; } else if ("Age".equalsIgnoreCase(fieldName)) { ageSeconds = UtilKt.toNonNegativeInt(value, -1); } } } }
Source:
<code>protected void doResolveAll(String inetHost, DnsRecord[] additionals, Promise<List<InetAddress>> promise, DnsCache resolveCache) throws Exception { if (inetHost == null || inetHost.isEmpty()) { promise.setSuccess(Collections.singletonList(loopbackAddress())); return; } final byte[] bytes = NetUtil.createByteArrayFromIpAddressString(inetHost); if (bytes != null) { promise.setSuccess(Collections.singletonList(InetAddress.getByAddress(bytes))); return; } final String hostname = hostname(inetHost); InetAddress hostsFileEntry = resolveHostsFileEntry(hostname); if (hostsFileEntry != null) { promise.setSuccess(Collections.singletonList(hostsFileEntry)); return; } CacheResult res = doResolveAllCached(hostname, additionals, promise, resolveCache, resolvedInternetProtocolFamilies); if (res == CacheResult.CACHED) { return; } <START> if (res == CacheResult.CACHED_EXPIRED) { <END> promise = executor().newPromise(); } doResolveAllUncached(hostname, additionals, promise, promise, resolveCache, completeOncePreferredResolved); }</code><technical_language>consider a switch(res) {...}</technical_language>

Target:
protected void doResolveAll(String inetHost, DnsRecord[] additionals, Promise<List<InetAddress>> promise, DnsCache resolveCache) throws Exception { if (inetHost == null || inetHost.isEmpty()) { promise.setSuccess(Collections.singletonList(loopbackAddress())); return; } final byte[] bytes = NetUtil.createByteArrayFromIpAddressString(inetHost); if (bytes != null) { promise.setSuccess(Collections.singletonList(InetAddress.getByAddress(bytes))); return; } final String hostname = hostname(inetHost); InetAddress hostsFileEntry = resolveHostsFileEntry(hostname); if (hostsFileEntry != null) { promise.setSuccess(Collections.singletonList(hostsFileEntry)); return; } ResolvedAddresses result; result = doResolveAllCached(hostname, additionals, resolveCache, resolvedInternetProtocolFamilies); if (result != null) { if (result.cause() != null) { ResolvedAddresses secondaryResult = doResolveAllCached(hostname, additionals, resolveCacheFallback, resolvedInternetProtocolFamilies); if (secondaryResult != null && secondaryResult.cause() == null) { result = secondaryResult; } } result.complete(promise); return; } result = doResolveAllCached(hostname, additionals, resolveCacheFallback, resolvedInternetProtocolFamilies); if (result != null) { result.complete(promise); promise = executor().newPromise(); } doResolveAllUncached(hostname, additionals, promise, promise, resolveCache, resolveCacheFallback, completeOncePreferredResolved); }
Source:
<code>private List<Resource> filterNotAuthorizedResource(PerunSession sess, List<Resource> resources) throws InternalErrorException { Iterator<Resource> resIterator = resources.iterator(); while(resIterator.hasNext()) { Resource resource = resIterator.next(); if(!AuthzResolver.isAuthorized(sess, Role.RESOURCEADMIN, resource) && <START> !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) resIterator.remove(); <END> } return resources; }</code><technical_language>For PerunObserver return resources immediately</technical_language>

Target:
private List<Resource> filterNotAuthorizedResource(PerunSession sess, List<Resource> resources) throws InternalErrorException { Iterator<Resource> resIterator = resources.iterator(); if (AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) { return resources; } while(resIterator.hasNext()) { Resource resource = resIterator.next(); if(!AuthzResolver.isAuthorized(sess, Role.RESOURCEADMIN, resource)) resIterator.remove(); } return resources; }
Source:
<code>public void initTrackerServers(List<TrackerServer> serverList) { serverList.add(new TrackerServer(new ServerBootstrap(), this.getName()) { @Override protected void addSpecificHandlers(ChannelPipeline pipeline) { pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1024, 1, 2, -3, 0)); pipeline.addLast("objectDecoder", new AstraProtocolDecoder(AstraProtocol.this)); } }); serverList.add(new TrackerServer(new ConnectionlessBootstrap(), this.getName()) { @Override protected void addSpecificHandlers(ChannelPipeline pipeline) { <START> pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1024, 1, 2, -3, 0)); <END> pipeline.addLast("objectDecoder", new AstraProtocolDecoder(AstraProtocol.this)); } }); }</code><technical_language>UDP is a datagram protocol, require frame decoder</technical_language>

Target:
public void initTrackerServers(List<TrackerServer> serverList) { serverList.add(new TrackerServer(new ServerBootstrap(), this.getName()) { @Override protected void addSpecificHandlers(ChannelPipeline pipeline) { pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1024, 1, 2, -3, 0)); pipeline.addLast("objectDecoder", new AstraProtocolDecoder(AstraProtocol.this)); } }); serverList.add(new TrackerServer(new ConnectionlessBootstrap(), this.getName()) { @Override protected void addSpecificHandlers(ChannelPipeline pipeline) { pipeline.addLast("objectDecoder", new AstraProtocolDecoder(AstraProtocol.this)); } }); }
Source:
<code>protected Properties getIntegrationProperties() { if (this.beanFactory != null) { return IntegrationContextUtils.getIntegrationProperties(this.beanFactory); } else { <START> return null; <END> } }</code><technical_language>return empty Properties (perhaps a static constant empty props create a new for instance). save a null check it</technical_language>

Target:
protected Properties getIntegrationProperties() { return IntegrationContextUtils.getIntegrationProperties(this.beanFactory); }
Source:
<code>public void testShowStatsSelectNonStarFails() { assertQueryFails("SHOW STATS FOR (SELECT nationkey FROM nation_partitioned)", ".*Only SELECT \\* is supported in SHOW STATS SELECT clause"); <START> } <END></code><technical_language>this change</technical_language>

Target:
public void testShowStatsSelectNonStarFails() { assertQueryFails("SHOW STATS FOR (SELECT orderkey FROM orders)", ".*Only SELECT \\* is supported in SHOW STATS SELECT clause"); assertQueryFails("SHOW STATS FOR (SELECT orderkey, custkey FROM orders)", ".*Only SELECT \\* is supported in SHOW STATS SELECT clause"); assertQueryFails("SHOW STATS FOR (SELECT *, * FROM orders)", ".*Only SELECT \\* is supported in SHOW STATS SELECT clause"); }
Source:
<code>protected static ConnectionFactory getConnectionFactory( IDatabaseConnection databaseConnection, String url ) { ConnectionFactory factory = null; if ( url.startsWith( "jdbc:mysql:" ) || ( url.startsWith( "jdbc:mariadb:" ) ) ) { Properties props = new Properties(); props.put( "user", StringEscapeUtils.unescapeHtml( databaseConnection.getUsername() ) ); <START> props.put( "password", StringEscapeUtils.unescapeHtml( databaseConnection.getPassword() ) ); <END> props.put( "socketTimeout", "0" ); props.put( "connectTimeout", "5000" ); factory = new DriverManagerConnectionFactory( url, props ); } else { factory = new DriverManagerConnectionFactory( url, StringEscapeUtils.unescapeHtml( databaseConnection.getUsername() ), StringEscapeUtils.unescapeHtml( databaseConnection.getPassword() ) ); } return factory; }</code><technical_language>do this - this is a bad practice. Please write code resembles this either. need symmetric encoding/decoding done for databases, targeted MySQL/MariaDB</technical_language>

Target:
protected static ConnectionFactory getConnectionFactory( IDatabaseConnection databaseConnection, String url ) { Properties props = new Properties(); props.put( "user", StringEscapeUtils.unescapeHtml( databaseConnection.getUsername() ) ); props.put( "password", StringEscapeUtils.unescapeHtml( databaseConnection.getPassword() ) ); if ( url.startsWith( "jdbc:mysql:" ) || ( url.startsWith( "jdbc:mariadb:" ) ) ) { props.put( "connectTimeout", "5000" ); } return new DriverManagerConnectionFactory( url, props ); }
Source:
<code>public void testDisableIncrementalAnalysis() { executeTarget("testDisableIncrementalAnalysis"); <START> assertOutputContaining("Avoid really long methods"); <END> }</code><technical_language>check cache exist, suggestion cache is logged</technical_language>

Target:
public void testDisableIncrementalAnalysis() { executeTarget("testDisableIncrementalAnalysis"); assertOutputContaining("Avoid really long methods"); assertDoesntContain(buildRule.getLog(), "This analysis could be faster"); assertFalse(currentTempFile().exists()); }
Source:
<code>public void preInstall() { resolver = Entities.newDownloader(this); String subpath = entity.getConfig(BrooklynNode.SUBPATH_IN_ARCHIVE); if (subpath==null) { String uploadUrl = entity.getConfig(BrooklynNode.DISTRO_UPLOAD_URL); String origDownloadName = uploadUrl; if (origDownloadName==null) { String downloadUrlTemplate = entity.getAttribute(BrooklynNode.DOWNLOAD_URL); if (downloadUrlTemplate!=null) { origDownloadName = DownloadSubstituters.substitute(downloadUrlTemplate, DownloadSubstituters.getBasicEntitySubstitutions(this)); } } if (origDownloadName!=null) { <START> origDownloadName = Urls.getBasename(origDownloadName); <END> String downloadName = origDownloadName; downloadName = Strings.removeFromEnd(downloadName, ".tar.gz"); downloadName = Strings.removeFromEnd(downloadName, ".tgz"); downloadName = Strings.removeFromEnd(downloadName, ".zip"); if (!downloadName.equals(origDownloadName)) { downloadName = Strings.removeFromEnd(downloadName, "-dist"); subpath = downloadName; } } } if (subpath==null) subpath = format("brooklyn-%s", getVersion()); setExpandedInstallDir(Os.mergePaths(getInstallDir(), resolver.getUnpackedDirectoryName(subpath))); }</code><technical_language>unescape url path it. hit this in actual usage</technical_language>

Target:
public void preInstall() { resolver = Entities.newDownloader(this); String subpath = entity.getConfig(BrooklynNode.SUBPATH_IN_ARCHIVE); if (subpath==null) { String uploadUrl = entity.getConfig(BrooklynNode.DISTRO_UPLOAD_URL); String origDownloadName = uploadUrl; if (origDownloadName==null) origDownloadName = entity.getAttribute(BrooklynNode.DOWNLOAD_URL); if (origDownloadName!=null) { origDownloadName = DownloadSubstituters.substitute(origDownloadName, DownloadSubstituters.getBasicEntitySubstitutions(this)); origDownloadName = Urls.decode(origDownloadName); origDownloadName = Urls.getBasename(origDownloadName); String downloadName = origDownloadName; downloadName = Strings.removeFromEnd(downloadName, ".tar.gz"); downloadName = Strings.removeFromEnd(downloadName, ".tgz"); downloadName = Strings.removeFromEnd(downloadName, ".zip"); if (!downloadName.equals(origDownloadName)) { downloadName = Strings.removeFromEnd(downloadName, "-dist"); subpath = downloadName; } } } if (subpath==null) subpath = format("brooklyn-%s", getVersion()); setExpandedInstallDir(Os.mergePaths(getInstallDir(), resolver.getUnpackedDirectoryName(subpath))); }
Source:
<code><START> public boolean isLaunchedFromIntent() { <END> return invokeSource.equals(InvokeSource.WIDGET) || invokeSource.equals(InvokeSource.INTENT_SHARE) || invokeSource.equals(InvokeSource.INTENT_PROCESS_TEXT); }</code><technical_language>A future refactor place this method in enum directly</technical_language>

Target:
public boolean isLaunchedFromIntent() { return invokeSource.fromIntent(); }
Source:
<code>private void initializeAsyncCancelAndVerifyCancelled(AlwaysFailingInitializer initializer, Runnable cleanupTask) throws InterruptedException { initializer.initialize(true); initializer.cancelInitialization(cleanupTask); int numberOfAttemptsWhenCancelled = initializer.initializationAttempts; <START> initializer.deterministicScheduler.tick(ASYNC_INIT_DELAY * 5 + 1, TimeUnit.MILLISECONDS); <END> assertThat(initializer.initializationAttempts).isEqualTo(numberOfAttemptsWhenCancelled); }</code><technical_language>ASYNC_INIT_DELAY * 5 + 1 (well, other time, 5*AID+1 ). Is worth extracting a constant here, SEVERAL_INIT_DELAYS</technical_language>

Target:
private void initializeAsyncCancelAndVerifyCancelled(AlwaysFailingInitializer initializer, Runnable cleanupTask) throws InterruptedException { initializer.initialize(true); initializer.cancelInitialization(cleanupTask); int numberOfAttemptsWhenCancelled = initializer.initializationAttempts; tickSchedulerFiveTimes(initializer); assertThat(initializer.initializationAttempts).isEqualTo(numberOfAttemptsWhenCancelled); }
Source:
<code>public ExecutorService getExecutor(Properties p) { TypedProperties tp = TypedProperties.toTypedProperties(p); int maxThreads = tp.getIntProperty("maxThreads", 1); int queueSize = tp.getIntProperty("queueSize", 100000); long keepAliveTime = tp.getLongProperty("keepAlive", 10000); final int threadPrio = tp.getIntProperty("threadPriority", Thread.MIN_PRIORITY); final String threadNamePrefix = tp.getProperty("threadNamePrefix", tp.getProperty("componentName", "Thread")); final String threadNameSuffix = tp.getProperty("threadNameSuffix", ""); ThreadFactory tf = new ThreadFactory() { @Override public Thread newThread(Runnable r) { String threadName = threadNamePrefix + "-" + counter.getAndIncrement() + threadNameSuffix; Thread th = new Thread(r, threadName); th.setDaemon(true); th.setPriority(threadPrio); return th; } }; ThreadPoolExecutor tpe = new ThreadPoolExecutor(maxThreads, maxThreads, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(queueSize), tf, new ThreadPoolExecutor.CallerRunsPolicy()); <START> tpe.allowCoreThreadTimeOut(true); <END> return tpe; }</code><technical_language>I this helps, long number of threads is smaller number of core threads, executor create new threads for submitted task</technical_language>

Target:
public ExecutorService getExecutor(Properties p) { TypedProperties tp = TypedProperties.toTypedProperties(p); int maxThreads = tp.getIntProperty("maxThreads", 1); int queueSize = tp.getIntProperty("queueSize", 100000); int coreThreads = queueSize == 0 ? 1 : tp.getIntProperty("coreThreads", maxThreads); long keepAliveTime = tp.getLongProperty("keepAliveTime", 60000); final int threadPrio = tp.getIntProperty("threadPriority", Thread.MIN_PRIORITY); final String threadNamePrefix = tp.getProperty("threadNamePrefix", tp.getProperty("componentName", "Thread")); final String threadNameSuffix = tp.getProperty("threadNameSuffix", ""); BlockingQueue<Runnable> queue = queueSize == 0 ? new SynchronousQueue<Runnable>() : new LinkedBlockingQueue<Runnable>(queueSize); ThreadFactory tf = new ThreadFactory() { @Override public Thread newThread(Runnable r) { String threadName = threadNamePrefix + "-" + counter.getAndIncrement() + threadNameSuffix; Thread th = new Thread(r, threadName); th.setDaemon(true); th.setPriority(threadPrio); return th; } }; return new ThreadPoolExecutor(coreThreads, maxThreads, keepAliveTime, TimeUnit.MILLISECONDS, queue, tf, new ThreadPoolExecutor.CallerRunsPolicy()); }
Source:
<code>public GWCConfig getConfig() { <START> if (gsEnvironment != null && gsEnvironment.isStale()) { <END> syncEnvironment(); } return gwcConfigPersister.getConfig(); }</code><technical_language>This bloc of code is repeated times, centralized in a single method</technical_language>

Target:
public GWCConfig getConfig() { return gwcConfigPersister.getConfig(); }
Source:
<code>private void captureScreenshot(String comment, WebDriver driver, WebElement element, boolean errorMessage) { if (getMessage(errorMessage) != null) { comment = getMessage(errorMessage); } LOGGER.debug("DriverListener->captureScreenshot starting..."); try { if (errorMessage) { LOGGER.error(comment); Screenshot.captureFailure(driver, comment); } else { LOGGER.info(comment); if (MobileContextHelper.isInWebViewContext()) { MobileContextHelper.backUpContext(driver); Screenshot.capture(driver, comment); <START> MobileContextHelper.restoreContext(driver); <END> } else { Screenshot.capture(driver, comment); } } } catch (Exception e) { LOGGER.debug("Unrecognized failure detected in DriverListener->captureScreenshot: " + e.getMessage(), e); } finally { resetMessages(); } LOGGER.debug("DriverListener->captureScreenshot finished..."); }</code><technical_language>I sense this if (MobileContextHelper.isInWebViewContext())</technical_language>

Target:
private void captureScreenshot(String comment, WebDriver driver, WebElement element, boolean errorMessage) { if (getMessage(errorMessage) != null) { comment = getMessage(errorMessage); } LOGGER.debug("DriverListener->captureScreenshot starting..."); try { if (errorMessage) { LOGGER.error(comment); Screenshot.captureFailure(driver, comment); } else { LOGGER.info(comment); MobileContextHelper contextHelper = new MobileContextHelper(); if (contextHelper.isInWebViewContext(driver)) { String context = contextHelper.getContext(driver); contextHelper.changeToNativeAppContext(driver); Screenshot.capture(driver, comment); contextHelper.setContext(context, driver); } else { Screenshot.capture(driver, comment); } } } catch (Exception e) { LOGGER.debug("Unrecognized failure detected in DriverListener->captureScreenshot: " + e.getMessage(), e); } finally { resetMessages(); } LOGGER.debug("DriverListener->captureScreenshot finished..."); }
Source:
<code>public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.my_courses, menu); final Config config = environment.getConfig(); if (config.isTabsLayoutEnabled()) { menu.findItem(R.id.menu_item_search).setVisible(false); menu.findItem(R.id.menu_item_account).setVisible(true); menu.findItem(R.id.menu_item_account).setIcon( new IconDrawable(getContext(), FontAwesomeIcons.fa_gear) .colorRes(getContext(), R.color.white) .actionBarSize(getContext())); } else { menu.findItem(R.id.menu_item_account).setVisible(false); if (config.getCourseDiscoveryConfig().isCourseDiscoveryEnabled()) { menu.findItem(R.id.menu_item_search).setVisible(true); } else { <START> menu.findItem(R.id.menu_item_search).setVisible(false); <END> } } }</code><technical_language>This if-else block simplified to: menu.findItem(R.id.menu_item_search).setVisible(config.getCourseDiscoveryConfig().isCourseDiscoveryEnabled())</technical_language>

Target:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.my_courses, menu); final Config config = environment.getConfig(); if (config.isTabsLayoutEnabled()) { menu.findItem(R.id.menu_item_search).setVisible(false); menu.findItem(R.id.menu_item_account).setVisible(true); menu.findItem(R.id.menu_item_account).setIcon( new IconDrawable(getContext(), FontAwesomeIcons.fa_gear) .colorRes(getContext(), R.color.white) .actionBarSize(getContext())); } else { menu.findItem(R.id.menu_item_account).setVisible(false); menu.findItem(R.id.menu_item_search).setVisible(config.getCourseDiscoveryConfig().isCourseDiscoveryEnabled()); } }
Source:
<code>protected List<AttributeStatement> createSubjectRoleStatement(final CallbackProperties properties) throws SAMLAssertionBuilderException { final String userCode = properties.getUserCode(); final String userSystem = properties.getUserSystem(); final String userSystemName = properties.getUserSystemName(); final String userDisplay = properties.getUserDisplay(); if (Arrays.asList(userCode, userSystem, userSystemName, userDisplay).contains(null)) { LOG.error("No information provided to fill in user role attribute.."); throw new SAMLAssertionBuilderException("No information provided to fill in user role attribute."); } final List<AttributeStatement> statements = new ArrayList<>(); final List<Attribute> attributes = new ArrayList<>(); <START> attributes.add(componentBuilder.createUserRoleAttribute(userCode, userSystem, userSystemName, userDisplay)); <END> if (!attributes.isEmpty()) { statements.addAll(componentBuilder.createAttributeStatement(attributes)); } return statements; }</code><technical_language>this changed createSubjectRoleAttribute</technical_language>

Target:
protected List<AttributeStatement> createSubjectRoleStatement(final CallbackProperties properties) { final String userCode = properties.getUserCode(); final String userSystem = properties.getUserSystem(); final String userSystemName = properties.getUserSystemName(); final String userDisplay = properties.getUserDisplay(); if (Arrays.asList(userCode, userSystem, userSystemName, userDisplay).contains(null)) { LOG.error("No information provided to fill in subject role attribute.."); throw new SAMLAssertionBuilderException("No information provided to fill in subject role attribute."); } final List<AttributeStatement> statements = new ArrayList<>(); final List<Attribute> attributes = new ArrayList<>(); attributes.add(componentBuilder.createSubjectRoleAttribute(userCode, userSystem, userSystemName, userDisplay)); if (!attributes.isEmpty()) { statements.addAll(componentBuilder.createAttributeStatement(attributes)); } return statements; }
Source:
<code>public LineRanges within(final LineRanges ranges) { final LineRanges result = new LineRanges(); final Iterator<LineRange> iterator = ranges.iterate(); <START> while (iterator.hasNext()) { <END> final LineRange next = iterator.next(); for (final LineRange line : this.lines.collection()) { if (next.within(line)) { result.add(line); } } } return result; }</code><technical_language>@JimDeanSpivey a foreach? for (final LineRange range : ranges)</technical_language>

Target:
public LineRanges within(final LineRanges ranges) { final LineRanges result = new LineRanges(); final Iterator<LineRange> iterator = ranges.iterator(); while (iterator.hasNext()) { final LineRange next = iterator.next(); for (final LineRange line : this.lines.collection()) { if (next.within(line)) { result.add(line); } } } return result; }
Source:
<code>public GlusterServersListReturnForXmlRpc(Map<String, Object> innerMap) { <START> super(innerMap); <END> List<GlusterServerInfo> glusterServers = new ArrayList<GlusterServerInfo>(); Object[] serversArr = (Object[]) innerMap.get(GLUSTER_HOSTS); if (serversArr != null) { for (int i = 0; i < serversArr.length; i++) { glusterServers.add(prepareServerInfo((Map<String, Object>) serversArr[i])); } } setServer(glusterServers); }</code><technical_language>Do try parse sever list if command failed (mStatus.code != 0)</technical_language>

Target:
public GlusterServersListReturnForXmlRpc(Map<String, Object> innerMap) { super(innerMap); List<GlusterServerInfo> glusterServers = new ArrayList<GlusterServerInfo>(); if (mStatus.mCode != 0) { Object[] serversArr = (Object[]) innerMap.get(GLUSTER_HOSTS); if (serversArr != null) { for (int i = 0; i < serversArr.length; i++) { glusterServers.add(prepareServerInfo((Map<String, Object>) serversArr[i])); } } } this.servers = glusterServers; }
Source:
<code>private void buildTestedInstance() { <START> ; <END> this.tested = new ClientFullSessionImpl(factory, canvasCommandManager, sessionCommandManager, requestCommandManager, registryFactory); }</code><technical_language>Floating semicolon</technical_language>

Target:
private void buildTestedInstance() { this.tested = new ClientFullSessionImpl(factory, canvasCommandManager, sessionCommandManager, requestCommandManager, registryFactory); }
Source:
<code><START> public void parentIsNotCalledIfAccountStatusExceptionIsThrown() { <END> AuthenticationProvider iThrowAccountStatusException = createProviderWhichThrows(new AccountStatusException( "", new Throwable()) { }); AuthenticationManager parent = mock(AuthenticationManager.class); ProviderManager mgr = new ProviderManager( Collections.singletonList(iThrowAccountStatusException), parent); try { mgr.authenticate(mock(Authentication.class)); fail("Expected exception"); } catch (AccountStatusException expected) { } verifyZeroInteractions(parent); }</code><technical_language>Thanks for cleanup items, too. please put in a separate commit (same PR)? is, code changes related new constructor, separate commit. This simplifies maintenance</technical_language>

Target:
public void parentIsNotCalledIfAccountStatusExceptionIsThrown() { AuthenticationProvider iThrowAccountStatusException = createProviderWhichThrows(new AccountStatusException( "", new Throwable()) { }); AuthenticationManager parent = mock(AuthenticationManager.class); ProviderManager mgr = new ProviderManager( Collections.singletonList(iThrowAccountStatusException), parent); try { mgr.authenticate(mock(Authentication.class)); fail("Expected exception"); } catch (AccountStatusException expected) { } verifyNoInteractions(parent); }
Source:
<code>private void initScanner(Schema projected) throws IOException { this.projector = new Projector(inSchema, outSchema, plan.getTargets()); <START> System.out.println("=======================>" + plan.getTableDesc().getName()); <END> for (FragmentProto f: fragments) { FileFragment ff = (FileFragment)FragmentConvertor.convert(context.getConf(), plan.getTableDesc().getMeta().getStoreType(), f); System.out.println(">>>>>>>>>>>>>>>>>>>" + ff.getPath()); } if (fragments != null) { if (fragments.length > 1) { this.scanner = new MergeScanner(context.getConf(), plan.getPhysicalSchema(), plan.getTableDesc().getMeta(), FragmentConvertor.<FileFragment>convert(context.getConf(), plan.getTableDesc().getMeta().getStoreType(), fragments), projected ); } else { this.scanner = StorageManagerFactory.getStorageManager( context.getConf()).getScanner(plan.getTableDesc().getMeta(), plan.getPhysicalSchema(), fragments[0], projected); } scanner.init(); } }</code><technical_language>Please remove debug codes</technical_language>

Target:
private void initScanner(Schema projected) throws IOException { this.projector = new Projector(inSchema, outSchema, plan.getTargets()); if (fragments != null) { if (fragments.length > 1) { this.scanner = new MergeScanner(context.getConf(), plan.getPhysicalSchema(), plan.getTableDesc().getMeta(), FragmentConvertor.<FileFragment>convert(context.getConf(), plan.getTableDesc().getMeta().getStoreType(), fragments), projected ); } else { this.scanner = StorageManagerFactory.getStorageManager( context.getConf()).getScanner(plan.getTableDesc().getMeta(), plan.getPhysicalSchema(), fragments[0], projected); } scanner.init(); } }
Source:
<code>public boolean put(ConflictTxStream conflictStream) { <START> Long val = cacheConflictKeys.get(conflictStream); <END> if (val != null && val >= conflictStream.txVersion) { log.error("For key {}, the value is not smaller than the expected value or maxWildCard", conflictStream, cacheConflictKeys.get(conflictStream), conflictStream.txVersion, maxConflictWildcard); return false; } if (cacheConflictKeys.size() == cacheSize) { invalidateFirst(); } cacheEntries.add(conflictStream); cacheConflictKeys.put(conflictStream, conflictStream.txVersion); cacheEntriesBytes += conflictStream.size(); return true; }</code><technical_language>please long</technical_language>

Target:
public boolean put(ConflictTxStream conflictStream) { Long val = conflictKeys.getOrDefault(conflictStream, Address.NON_ADDRESS); if (val > conflictStream.txVersion) { log.error("For key the new entry address is smaller than the entry " + "address in cache. There is a sequencer regression.", conflictStream, conflictStream.txVersion, conflictKeys.get(conflictStream)); return false; } if (conflictKeys.size() == cacheSize) { invalidateSmallestTxVersion(); } cacheEntries.add(conflictStream); conflictKeys.put(conflictStream, conflictStream.txVersion); return true; }
Source:
<code>public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final Collection<BindingSet> bindingSets) throws QueryEvaluationException { <START> return null; <END> }</code><technical_language>Is a reason this implemented</technical_language>

Target:
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final Collection<BindingSet> bindingSets) throws QueryEvaluationException { requireNonNull(bindingSets); final List<BindingSet> list = new ArrayList<>(); bindingSets.forEach(bindingSet -> { try { list.addAll(findBindings(bindingSet)); } catch (final Exception e) { Log.error("Unable to evaluate bindingset.", e); } }); return new CollectionIteration<>(list); }
Source:
<code><START> public static <T> void handleBulkWriteError(List<BulkWriteError> errors,String op,GetCB cb) { <END> for (BulkWriteError e : errors) { cb.getCtx(e.getIndex()).addError(getError(e,op)); } }</code><technical_language>nit: unnecessary generic type declaration</technical_language>

Target:
public static void handleBulkWriteError(List<BulkWriteError> errors,String op,GetCB cb) { for (BulkWriteError e : errors) { cb.getCtx(e.getIndex()).addError(getError(e,op)); } }
Source:
<code>public Integer getPartition() { String changelogPartition = getMessageValue(CHANGELOG_VALUE_KEY); <START> return (changelogPartition != null) ? Integer.parseInt(changelogPartition) : null; <END> }</code><technical_language>safer replace null check StringUtils.isNotBlank(changelogPartition)</technical_language>

Target:
public Integer getPartition() { String changelogPartition = getMessageValue(CHANGELOG_VALUE_KEY); return StringUtils.isNotBlank(changelogPartition) ? Integer.parseInt(changelogPartition) : null; }
Source:
<code>public void testInitAggregator() throws Exception { <START> final List<BuiltinAggregator> aggregators = Arrays.asList(BuiltinAggregator.COUNT, <END> BuiltinAggregator.MAX, BuiltinAggregator.MIN, BuiltinAggregator.SUM); testedView.initBuiltinAggregators(aggregators); aggregators.stream().forEach(agg -> verify(lstBuiltinAggregator).addOption(agg.value())); }</code><technical_language>Out of interest do BuiltinAggregator.values()</technical_language>

Target:
public void testInitAggregator() throws Exception { final List<BuiltinAggregator> aggregators = Arrays.asList(BuiltinAggregator.values()); testedView.initBuiltinAggregators(aggregators); aggregators.stream().forEach(agg -> verify(lstBuiltinAggregator).addOption(agg.value())); }