auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String exec(String cmd) throws IOException { LOG.debug("Shell cmd: {}", cmd); Process process = new ProcessBuilder(new String[]{ "/bin/bash", "-c", cmd }).start(); try { process.waitFor(); <START> String output = IOUtils.toString(process.getInputStream(), Charsets.UTF_8); <END> String errorOutput = IOUtils.toString(process.getErrorStream(), Charsets.UTF_8); LOG.debug("Shell Output: {}", output); if (errorOutput.length() != 0) { LOG.error("Shell Error Output: {}", errorOutput); throw new IOException(errorOutput); } return output; } catch (InterruptedException | ClosedByInterruptException ie) { throw new IOException(ie); } }</code><technical_language>this break if system's standard charset UTF-8</technical_language>

Target:
public static String exec(String cmd) throws IOException { LOG.debug("Shell cmd: {}", cmd); Process process = new ProcessBuilder(new String[]{ "/bin/bash", "-c", cmd }).start(); try { process.waitFor(); String output = IOUtils.toString(process.getInputStream()); String errorOutput = IOUtils.toString(process.getErrorStream()); LOG.debug("Shell Output: {}", output); if (errorOutput.length() != 0) { LOG.error("Shell Error Output: {}", errorOutput); throw new IOException(errorOutput); } return output; } catch (InterruptedException | ClosedByInterruptException ie) { throw new IOException(ie); } }
Source:
<code>private String getLatestConceptMapVersion(TranslationRequest theTranslationRequest) { Pageable page = PageRequest.of(0, 1); List<TermConceptMap> theConceptMapList = myConceptMapDao.findTermConceptMapByUrl(page, theTranslationRequest.getUrl().asStringValue()); if (!theConceptMapList.isEmpty()) { return theConceptMapList.get(0).getVersion(); } <START> return null; <END> }</code><technical_language>need a JUnit test for case translate is requested a URL version, requested ConceptMap is versioned in repository</technical_language>

Target:
private String getLatestConceptMapVersion(TranslationRequest theTranslationRequest) { Pageable page = PageRequest.of(0, 1); List<TermConceptMap> theConceptMapList = myConceptMapDao.getTermConceptMapEntitiesByUrlOrderByVersion(page, theTranslationRequest.getUrl().asStringValue()); if (!theConceptMapList.isEmpty()) { return theConceptMapList.get(0).getVersion(); } return null; }
Source:
<code>public boolean onHttpRequestSend(HttpMessage msg) { try { String url = msg.getRequestHeader().getURI().toString(); String path = msg.getRequestHeader().getURI().getPath(); <START> LOGGER.debug("Callback received for URL : " + url + " path : " <END> + path); if (path.startsWith("/" + TEST_PREFIX)) { String str = Constant.messages.getString("callback.test.msg", url, msg.getRequestHeader().getSenderAddress().toString()); if (View.isInitialised()) { View.getSingleton().getOutputPanel() .appendAsync(str + "\n"); } else { LOGGER.info(str); } return true; } else if (path.startsWith("/favicon.ico")) { return true; } for (Entry<String, CallbackImplementor> callback : callbacks .entrySet()) { if (path.startsWith(callback.getKey())) { callback.getValue().handleCallBack(msg.cloneAll()); return true; } } LOGGER.error("No callback handler for URL : " + url); } catch (URIException e) { LOGGER.error(e.getMessage(), e); } return true; }</code><technical_language>Worth including sender address</technical_language>

Target:
public boolean onHttpRequestSend(HttpMessage msg) { try { String url = msg.getRequestHeader().getURI().toString(); String path = msg.getRequestHeader().getURI().getPath(); LOGGER.debug("Callback received for URL : " + url + " path : " + path + " from " + msg.getRequestHeader().getSenderAddress()); if (path.startsWith("/" + TEST_PREFIX)) { String str = Constant.messages.getString( "callback.test.msg", url, msg.getRequestHeader() .getSenderAddress().toString()); if (View.isInitialised()) { View.getSingleton().getOutputPanel() .appendAsync(str + "\n"); } LOGGER.info(str); return true; } else if (path.startsWith("/favicon.ico")) { return true; } for (Entry<String, CallbackImplementor> callback : callbacks .entrySet()) { if (path.startsWith(callback.getKey())) { callback.getValue().handleCallBack(msg.cloneAll()); return true; } } LOGGER.error("No callback handler for URL : " + url + " from " + msg.getRequestHeader().getSenderAddress()); } catch (URIException e) { LOGGER.error(e.getMessage(), e); } return true; }
Source:
<code>public Builder keyStore(File file) { if (file == null) { <START> return this; <END> } if (!file.exists()) { throw new IllegalArgumentException("Keystore file does not exist: " + file); } this.keyStoreSource = Files.asByteSource(file); return this; }</code><technical_language>This sounds error, too</technical_language>

Target:
public Builder keyStore(File file) { if (file == null || !file.exists()) { throw new IllegalArgumentException("A file with the keystore must be provided."); } this.keyStoreSource = Files.asByteSource(file); return this; }
Source:
<code>private void logRunningAsyncTasks(List<AsyncTask> asyncTasks) { String runningTasks = asyncTasks .stream() .map(AsyncTask::toString) <START> .collect(Collectors.joining(", ")); <END> log.warn("There are running tasks: '{}'", runningTasks); }</code><technical_language>AsyncTask's toString is a tad large. joining this list a newline log easier read</technical_language>

Target:
private void logRunningAsyncTasks(List<AsyncTask> asyncTasks) { String runningTasks = asyncTasks .stream() .map(AsyncTask::toString) .collect(Collectors.joining("\n")); log.warn("There are running tasks: '{}'", runningTasks); }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HostMetricTagsPair that = (HostMetricTagsPair) o; if (!metric.equals(that.metric)) return false; <START> if (!metric.equals(that.metric)) return false; <END> return tags != null ? tags.equals(that.tags) : that.tags == null; }</code><technical_language>of host</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HostMetricTagsPair that = (HostMetricTagsPair) o; if (!metric.equals(that.metric) || !host.equals(that.host)) return false; return tags != null ? tags.equals(that.tags) : that.tags == null; }
Source:
<code>public void testAllBatchesReturned() throws DbException { final Schema schema = new Schema(ImmutableList.of(Type.STRING_TYPE), ImmutableList.of("joined_ints")); final TupleBatchBuffer input = new TupleBatchBuffer(schema); final long expectedResults = 2 * TupleBatch.BATCH_SIZE + 1; final int intsInRow = 10; <START> for (long i = 0; i < (expectedResults / intsInRow) + 1; ++i) { <END> final int remainder = (int) (expectedResults % intsInRow); final int intsToConcatSize; if ((expectedResults - (i * intsInRow)) == remainder) { intsToConcatSize = remainder; } else { intsToConcatSize = intsInRow; } final long[] intsToConcat = new long[intsToConcatSize]; for (int j = 0; j < intsToConcatSize; ++j) { intsToConcat[j] = (i * intsInRow) + j; } input.putString(0, Longs.join(",", intsToConcat)); } Split splitOp = new Split(new TupleSource(input), 0, ","); splitOp.open(TestEnvVars.get()); TupleBatch result; long rowIdx = 0; while (!splitOp.eos()) { result = splitOp.nextReady(); if (result != null) { assertEquals(schema.numColumns(), result.getSchema().numColumns()); assertEquals(Type.STRING_TYPE, result.getSchema().getColumnType(0)); for (int batchIdx = 0; batchIdx < result.numTuples(); ++batchIdx, ++rowIdx) { assertEquals(rowIdx, Long.parseLong(result.getString(0, batchIdx))); } } } assertEquals(expectedResults, rowIdx); splitOp.close(); }</code><technical_language>here? This complicated. Is a reason a StringBuilder concatenate ints 0..expectedResults-1? java StringBuilder sb = new StringBuilder(); for (int i = 0; i < expectedResults; ++i) { sb.append(i).append(','); } input.putString(0, sb.toString()); [or that; need convert int string.]</technical_language>

Target:
public void testAllBatchesReturned() throws DbException { final Schema schema = Schema.ofFields("joined_ints", Type.STRING_TYPE); final Schema expectedResultSchema = Schema.appendColumn(schema, Type.STRING_TYPE, "joined_ints_splits"); final TupleBatchBuffer input = new TupleBatchBuffer(schema); final long expectedResults = 2 * TupleBatch.BATCH_SIZE + 1; StringBuilder sb = new StringBuilder(); for (int i = 0; i < expectedResults; ++i) { sb.append(i); if (i < expectedResults - 1) { sb.append(","); } } input.putString(0, sb.toString()); Split splitOp = new Split(new TupleSource(input), 0, ","); splitOp.open(TestEnvVars.get()); long rowIdx = 0; while (!splitOp.eos()) { TupleBatch result = splitOp.nextReady(); if (result != null) { assertEquals(expectedResultSchema, result.getSchema()); for (int batchIdx = 0; batchIdx < result.numTuples(); ++batchIdx, ++rowIdx) { assertEquals(rowIdx, Integer.parseInt(result.getString(1, batchIdx))); } } } assertEquals(expectedResults, rowIdx); splitOp.close(); }
Source:
<code>private void markOperationStart() { logger.trace("{} started for {}", operationType, blobId); <START> operationStartTime = System.currentTimeMillis(); <END> }</code><technical_language>rate metrics</technical_language>

Target:
void markOperationStart() { logger.trace("{} started for {}", operationType, blobId); operationStartTime = System.currentTimeMillis(); }
Source:
<code>public Map<String, String> getMeta() { <START> Map<String, String> meta = new HashMap<>(); <END> meta.put(InfrastructureManager.ELASTIC, "false"); return meta; }</code><technical_language>Souldn't hashmap configured object allocation instead of recreating time getMeta() is invoked</technical_language>

Target:
public Map<String, String> getMeta() { return meta; }
Source:
<code>protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__ADD); <START> addCanDoActionMessage(VdcBllMessages.VAR__TYPE__NETWORK_QOS); <END> }</code><technical_language>this line pulled setActionMessageParameters() method in NetworkQoSCommandBase class repeats in of NetworkQoS commands</technical_language>

Target:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__TYPE__NETWORK_QOS); }
Source:
<code>public void parse(File reportFile) throws IOException { try { for (SuiteResult suiteResult : SuiteResult.parse(reportFile, keepLongStdio)) add(suiteResult); } catch (InterruptedException e) { throw new IOException("Failed to read "+reportFile,e); } catch (RuntimeException e) { throw new IOException("Failed to read "+reportFile,e); } catch (DocumentException e) { String reportFileContent = null; try { reportFileContent = Files.toString(reportFile, UTF_8); } catch (Exception ee) { } if (!reportFile.getPath().endsWith(".xml")) { throw new IOException("Failed to parse "+reportFile+"\n"+ <START> "Is this really a JUnit report file? Your configuration may be matching too many files? The file contains:\n\n" + reportFileContent + "\n\n",e); <END> } else { SuiteResult sr = new SuiteResult(reportFile.getName(), "", ""); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); String error = "Failed to parse test report file "+reportFile.getAbsolutePath()+"\n The file contains:\n\n" + reportFileContent + "\n\n"+writer.toString(); sr.addCase(new CaseResult(sr,"[failed-to-read]",error)); add(sr); } } }</code><technical_language>reject file name end .xml, I do read it</technical_language>

Target:
public void parse(File reportFile) throws IOException { parse(reportFile, null); }
Source:
<code>protected Position handlePosition(Position position) { <START> String attributesString = Context.getDeviceManager().lookupAttributeString(position.getDeviceId(), <END> "processing.copyAttributes", null, false); Position last = getLastPosition(position.getDeviceId()); if (attributesString != null && last != null) { for (String attribute : attributesString.split(" ")) { if (last.getAttributes().containsKey(attribute) && !position.getAttributes().containsKey(attribute)) { position.getAttributes().put(attribute, last.getAttributes().get(attribute)); } } } return position; }</code><technical_language>I more readable if fit line, move parameters next one</technical_language>

Target:
protected Position handlePosition(Position position) { String attributesString = Context.getDeviceManager().lookupAttributeString( position.getDeviceId(), "processing.copyAttributes", null, true); Position last = getLastPosition(position.getDeviceId()); if (attributesString != null && last != null) { for (String attribute : attributesString.split(" ")) { if (last.getAttributes().containsKey(attribute) && !position.getAttributes().containsKey(attribute)) { position.getAttributes().put(attribute, last.getAttributes().get(attribute)); } } } return position; }
Source:
<code>protected final SClass getEnclosingClass(final SObjectWithClass rcvr) { <START> SClass lexicalClass = rcvr.getSOMClass().getClassCorrespondingTo(mixinId); <END> if (lexicalClass == null) { lexicalClass = rcvr.getSOMClass().getClassWithMixinCorrespondingTo(mixinId); } assert lexicalClass != null; return lexicalClass; }</code><technical_language>This is silly nitpicking, but, I issues reading this code, so, a rcvrClass local variable? avoid .getSOMClass(). matter performance-wise, I of indirection less</technical_language>

Target:
protected final SClass getEnclosingClass(final SObjectWithClass rcvr) { SClass rcvrClass = rcvr.getSOMClass(); SClass lexicalClass = rcvrClass.lookupClass(mixinId); if (lexicalClass == null) { lexicalClass = rcvrClass.lookupClassWithMixinApplied(mixinId); } assert lexicalClass != null; return lexicalClass; }
Source:
<code>public Boolean call() { try { LOG.info("Moving region: from to {}", region.getEncodedName(), sourceServer, targetServer); admin.move(region.getEncodedNameAsBytes(), targetServer); <START> LOG.info("Moved from to {}", region.getEncodedName(), sourceServer, targetServer); <END> } catch (Exception e) { LOG.error("Error Moving Region: {}", region.getEncodedName(), e); } finally { movedRegions.add(region); } return true; }</code><technical_language>s/Moved/Requested Move expressly checking if worked</technical_language>

Target:
public Boolean call() { try { LOG.info("Moving region: from to {}", region.getEncodedName(), sourceServer, targetServer); admin.move(region.getEncodedNameAsBytes(), targetServer); LOG.info("Requested move from to {}", region.getEncodedName(), sourceServer, targetServer); } catch (Exception e) { LOG.error("Error Moving Region: {}", region.getEncodedName(), e); } finally { movedRegions.add(region); } return true; }
Source:
<code>public void open(String inPortName, int rate, int dataBits, int stopBits, int parity) throws IOException { info("connect to port %s %d|%d|%d|%d", inPortName, rate, dataBits, stopBits, parity); this.rate = rate; this.dataBits = dataBits; this.stopBits = stopBits; this.parity = parity; lastPortName = portName; if (this.portName != null) { info("#1 already connected"); Port port = ports.get(portName); if (port.isOpen() && port.isListening() && !portName.equals(inPortName)) { info("already connected to %s - disconnect first to reconnect", portName); return; } } if (ports.containsKey(inPortName)) { info("#2 connect to a pre-existing port"); connectPort(ports.get(inPortName), null); lastPortName = portName; return; } if (inPortName != null && inPortName.toLowerCase().startsWith("tcp://")) { try { info("connecting tcp"); connectTcp(inPortName); return; } catch (Exception e) { <START> error("connect ctp threw"); <END> throw new IOException(e); } } if (Platform.isVirtual()) { connectVirtualUart(inPortName); connect(inPortName); return; } info("#3 we don't have an pre-existing port - so we'll try a hardware port"); Port port = createHardwarePort(inPortName, rate, dataBits, stopBits, parity); if (port == null) { return; } connectPort(port, null); }</code><technical_language>a typo in this error / log message "ctp" "tcp"</technical_language>

Target:
public void open(String inPortName, int rate, int dataBits, int stopBits, int parity) throws IOException { info("connect to port %s %d|%d|%d|%d", inPortName, rate, dataBits, stopBits, parity); this.rate = rate; this.dataBits = dataBits; this.stopBits = stopBits; this.parity = parity; lastPortName = portName; if (this.portName != null) { info("#1 already connected"); Port port = ports.get(portName); if (port.isOpen() && port.isListening() && !portName.equals(inPortName)) { info("already connected to %s - disconnect first to reconnect", portName); return; } } if (ports.containsKey(inPortName)) { info("#2 connect to a pre-existing port"); connectPort(ports.get(inPortName), null); lastPortName = portName; return; } if (inPortName != null && inPortName.toLowerCase().startsWith("tcp://")) { try { info("connecting tcp"); connectTcp(inPortName); return; } catch (Exception e) { error("connect tcp threw"); throw new IOException(e); } } if (Platform.isVirtual()) { connectVirtualUart(inPortName); connect(inPortName); return; } info("#3 we don't have an pre-existing port - so we'll try a hardware port"); Port port = createHardwarePort(inPortName, rate, dataBits, stopBits, parity); if (port == null) { return; } connectPort(port, null); }
Source:
<code>public ILaunchDescriptor getDescriptor(Object element) { if (element instanceof ILaunchConfiguration) { ILaunchConfiguration config = (ILaunchConfiguration) element; try { if( config.getType().isPublic()) { DefaultLaunchDescriptor descriptor = descriptors.get(config); if (descriptor == null) { descriptor = new DefaultLaunchDescriptor(this, config); descriptors.put(config, descriptor); } return descriptor; } } catch(CoreException ce) { <START> ce.printStackTrace(); <END> } catch(NullPointerException npe) { npe.printStackTrace(); } } return null; }</code><technical_language>No, please log these. Activator a static log() method easy</technical_language>

Target:
public ILaunchDescriptor getDescriptor(Object element) { if (element instanceof ILaunchConfiguration) { ILaunchConfiguration config = (ILaunchConfiguration) element; try { if( config.getType().isPublic() && !(config.getAttribute(ILaunchManager.ATTR_PRIVATE, false))) { DefaultLaunchDescriptor descriptor = descriptors.get(config); if (descriptor == null) { descriptor = new DefaultLaunchDescriptor(this, config); descriptors.put(config, descriptor); } return descriptor; } } catch(CoreException ce) { Activator.log(ce.getStatus()); } catch(NullPointerException npe) { npe.printStackTrace(); } } return null; }
Source:
<code>static private Class<?> getReturnType(Method method) { if (isSuspend(method)) { <START> return getSuspendReturnType(method).resolve(); <END> } else { return method.getReturnType(); } }</code><technical_language>resolve() return null Class<?> getReturnType(Method method) is expected return null values. resolve(Class<?> fallback) variant assert returned class is null returning if case here</technical_language>

Target:
static private Class<?> getReturnType(Method method) { if (isSuspend(method)) { final Class<?> returnType = getSuspendReturnType(method).resolve(); Assert.notNull(returnType, "returnType cannot be null"); return returnType; } else { return method.getReturnType(); } }
Source:
<code>private String createHeader(Detail shortDetail) { EvaluationContext context = mSession.getEvaluationContext(); DetailField[] fields = shortDetail.getFields(); StringBuilder row = new StringBuilder(); int i = 0; for(DetailField field : fields) { <START> Object o = field.getHeader().evaluate(context); <END> String s; if(!(o instanceof String)) { s = ""; } else { s = (String)o; } int widthHint = SCREEN_WIDTH / fields.length; try { widthHint = Integer.parseInt(field.getHeaderWidthHint()); } catch(Exception e) { } addPaddedStringToBuilder(row, s, widthHint); i++; if(i != fields.length) { row.append(" | "); } } return row.toString(); }</code><technical_language>This returns a String, down-casting Object</technical_language>

Target:
private String createHeader(Detail shortDetail) { EvaluationContext context = mSession.getEvaluationContext(); DetailField[] fields = shortDetail.getFields(); StringBuilder row = new StringBuilder(); int i = 0; for (DetailField field : fields) { String s = field.getHeader().evaluate(context); int widthHint = SCREEN_WIDTH / fields.length; try { widthHint = Integer.parseInt(field.getHeaderWidthHint()); } catch (Exception e) { } addPaddedStringToBuilder(row, s, widthHint); i++; if (i != fields.length) { row.append(" | "); } } return row.toString(); }
Source:
<code>public MyFacesInjectionProvider() { <START> if (StartupContext.getInjectionContainer() != null) { <END> this.injectionContainer = StartupContext.getInjectionContainer(); } }</code><technical_language>need check of StartupContext.getInjectionContainer() assigning this.injectionContainer</technical_language>

Target:
public MyFacesInjectionProvider() { this.injectionContainer = StartupContext.getInjectionContainer(); }
Source:
<code>public void register(final InstanceInfo info) throws Exception { long expiryTime = System.currentTimeMillis() + info.getLeaseInfo().getRenewalIntervalInSecs() * 1000; batchingDispatcher.process( <START> "register#" + info.getId(), <END> new InstanceReplicationTask(targetHost, Action.Register, info, null, true) { public HttpResponse<Void> execute() { return replicationClient.register(info); } }, expiryTime ); }</code><technical_language>ids a concat of appName + instanceId combination uniquely identifies</technical_language>

Target:
public void register(final InstanceInfo info) throws Exception { long expiryTime = System.currentTimeMillis() + info.getLeaseInfo().getRenewalIntervalInSecs() * 1000; batchingDispatcher.process( taskId("register", info), new InstanceReplicationTask(targetHost, Action.Register, info, null, true) { public HttpResponse<Void> execute() { return replicationClient.register(info); } }, expiryTime ); }
Source:
<code>public void submit(Statement statement, QueryExecution queryExecution, SelectionContext<C> selectionContext, Executor executor) { checkState(configurationManager.get() != null, "configurationManager not set"); int activeWorkerCount = getActiveWorkerCount(); <START> if (!acceptQueries.get() && !shouldQueueQueriesWithInsufficientWorkers) { <END> if (nanosSince(initialNanos).compareTo(initializationTimeout) < 0 && activeWorkerCount < initializationRequiredWorkers) { queryExecution.fail(new PrestoException(SERVER_STARTING_UP, String.format("Cluster is still initializing, there are insufficient active worker nodes (%s) to run query. Waiting for (%s) active worker nodes.", activeWorkerCount, initializationRequiredWorkers))); } acceptQueries.set(true); } createGroupIfNecessary(selectionContext, executor); groups.get(selectionContext.getResourceGroupId()).run(queryExecution, shouldQueueQueries()); }</code><technical_language>- Pending queries infinitely hiding another issue in cluster</technical_language>

Target:
public void submit(Statement statement, QueryExecution queryExecution, SelectionContext<C> selectionContext, Executor executor) { checkState(configurationManager.get() != null, "configurationManager not set"); int activeWorkerCount = getActiveWorkerCount(); if (!acceptQueries.get() && !shouldPendQueriesUntilScaleout()) { if (nanosSince(initialNanos).compareTo(initializationTimeout) < 0 && activeWorkerCount < initializationRequiredWorkers) { queryExecution.fail(new PrestoException(SERVER_STARTING_UP, String.format("Cluster is still initializing, there are insufficient active worker nodes (%s) to run query. Waiting for (%s) active worker nodes.", activeWorkerCount, initializationRequiredWorkers))); } acceptQueries.set(true); } createGroupIfNecessary(selectionContext, executor); groups.get(selectionContext.getResourceGroupId()).run(queryExecution, shouldPendQueriesUntilScaleout()); }
Source:
<code>public static @Nullable PercentType toColorTemperaturePercentType(State lightState) { ColorMode colorMode = lightState.getColorMode(); if (colorMode != null && !colorMode.equals(ColorMode.CT)) { <START> return null; <END> } int percent = (int) Math .round(((lightState.getColorTemperature() - MIN_COLOR_TEMPERATURE) * 100.0) / COLOR_TEMPERATURE_RANGE); return new PercentType(restrictToBounds(percent)); }</code><technical_language>Returning Java null work - do is send a channel state update UnDefType.NULL. Imho place do colorMode check [here](<LINK_0> - simply do update PercentType colorMode!=CT do updateState(CHANNEL_COLORTEMPERATURE, UnDefType.NULL);. sense</technical_language>

Target:
public static PercentType toColorTemperaturePercentType(State lightState) { int percent = (int) Math .round(((lightState.getColorTemperature() - MIN_COLOR_TEMPERATURE) * 100.0) / COLOR_TEMPERATURE_RANGE); return new PercentType(restrictToBounds(percent)); }
Source:
<code><START> default Collation asc() { <END> return Collation.of(Matchers.extract(this).path(), Ordering.Direction.ASCENDING); }</code><technical_language>Is return type of asc() is (ie Collation) ? While add functionality hides methods user IDE auto-complete (that point of empty interface)</technical_language>

Target:
default Ordering asc() { return Collation.of(Matchers.extract(this).path(), Ordering.Direction.ASCENDING); }
Source:
<code>public FormValidation doReloadTypes(@QueryParameter String credential, @AncestorInPath AbstractProject project) { if (project == null) { if (!project.hasPermission(Jenkins.ADMINISTER)) { return FormValidation.ok(); } } else if (!project.hasPermission(Item.EXTENDED_READ) && !project.hasPermission(CredentialsProvider.USE_ITEM)) { return FormValidation.ok(); } <START> project.checkPermission(AbstractProject.CONFIGURE); <END> Credential overridingcredential = RepositoryUtils.retrieveOverridingCredentialFromProject(project); try { DeployitServer deployitServer = RepositoryUtils.getDeployitServer(credential, overridingcredential, project); if (null == deployitServer) return error("Server not found for credential."); deployitServer.reload(); return ok("Types reloaded from XL Deploy version " + deployitServer.getServerInfo().getVersion() + " at " + deployitServer.getBooterConfig().getUrl()); } catch (DeployitPluginException ex) { return error(String.format("Unable to reload types. Cause: %s.", ex.getMessage())); } }</code><technical_language>above, this wrong</technical_language>

Target:
public FormValidation doReloadTypes(@QueryParameter String credential, @AncestorInPath AbstractProject project) { project.checkPermission(Jenkins.ADMINISTER); Credential overridingcredential = RepositoryUtils.retrieveOverridingCredentialFromProject(project); try { DeployitServer deployitServer = RepositoryUtils.getDeployitServer(credential, overridingcredential, project); if (null == deployitServer) return error("Server not found for credential."); deployitServer.reload(); return ok("Types reloaded from XL Deploy version " + deployitServer.getServerInfo().getVersion() + " at " + deployitServer.getBooterConfig().getUrl()); } catch (DeployitPluginException ex) { return error(String.format("Unable to reload types. Cause: %s.", ex.getMessage())); } }
Source:
<code>public void apply(EntitySpec<?> entitySpec, String nodeId, ToscaApplication toscaApplication) { final Iterable<String> artifacts = getToscaFacade().getArtifacts(nodeId, toscaApplication); if (Iterables.isEmpty(artifacts)) { return; } final Map<String, String> filesToCopy = MutableMap.of(); for (String artifactId : artifacts) { Optional<Path> optionalResourcesRootPath = getToscaFacade().getArtifactPath(nodeId, toscaApplication, artifactId); if(!optionalResourcesRootPath.isPresent()) { continue; } BrooklynDslDeferredSupplier deferredRunDir = BrooklynDslCommon.attributeWhenReady("run.dir"); entitySpec.configure(SoftwareProcess.SHELL_ENVIRONMENT.subKey(artifactId), deferredRunDir); try { Files.walkFileTree(optionalResourcesRootPath.get(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { <START> filesToCopy.put(file.toAbsolutePath().toString(), file.getFileName().toString()); <END> return FileVisitResult.CONTINUE; } }); } catch (IOException e) { LOG.warn("Cannot parse CSAR resources", e); } } entitySpec.configure(SoftwareProcess.RUNTIME_FILES, filesToCopy); }</code><technical_language>this risk overwriting files? e.g. if a project resources config/foo config2/foo. If approach copy files directory structure intact</technical_language>

Target:
public void apply(EntitySpec<?> entitySpec, String nodeId, ToscaApplication toscaApplication) { final Iterable<String> artifacts = getToscaFacade().getArtifacts(nodeId, toscaApplication); if (Iterables.isEmpty(artifacts)) { return; } final Map<String, String> filesToCopy = MutableMap.of(); for (final String artifactId : artifacts) { Optional<Path> optionalResourcesRootPath = getToscaFacade().getArtifactPath(nodeId, toscaApplication, artifactId); if(!optionalResourcesRootPath.isPresent()) { continue; } BrooklynDslDeferredSupplier deferredRunDir = (BrooklynDslDeferredSupplier) BrooklynDslCommon.formatString("%s/%s", BrooklynDslCommon.attributeWhenReady("run.dir"), artifactId); entitySpec.configure(SoftwareProcess.SHELL_ENVIRONMENT.subKey(artifactId), deferredRunDir); try { Files.walkFileTree(optionalResourcesRootPath.get(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { filesToCopy.put(file.toAbsolutePath().toString(), artifactId + "/" + file.getFileName().toString()); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { LOG.warn("Cannot parse CSAR resources", e); } } entitySpec.configure(SoftwareProcess.RUNTIME_FILES, filesToCopy); }
Source:
<code>public Object next() { Object obj = null; <START> if (hasNext) { <END> hasNext = false; obj = "THE_ROW"; } return obj; }</code><technical_language>iterator contract is throw NoSuchElementException if is next</technical_language>

Target:
public Object next() { if (!hasNext) { throw new NoSuchElementException("no more rows"); } hasNext = false; return "THE_ROW"; }
Source:
<code>private void window() { state.startWindow(); Runnable windowWorker = new Runnable() { @Override public void run() { try { containerMetrics.windows().inc(); ReadableCoordinator coordinator = new ReadableCoordinator(task.taskName()); long startTime = clock.nanoTime(); task.window(coordinator); containerMetrics.windowNs().update(clock.nanoTime() - startTime); <START> double lowerBoundForWindowTriggerTimeInMs = <END> containerMetrics.windowNs().getSnapshot().getAverage() / 1e6; if (windowMs <= lowerBoundForWindowTriggerTimeInMs) { log.warn( "Window might potentially starve process method." + " Consider increasing the window interval to something greater than ms", (long) lowerBoundForWindowTriggerTimeInMs); } coordinatorRequests.update(coordinator); state.doneWindow(); } catch (Throwable t) { log.error("Task window failed", task.taskName(), t); abort(t); } finally { log.trace("Task window completed", task.taskName()); resume(); } } }; if (threadPool != null) { log.trace("Task window on the thread pool", task.taskName()); threadPool.submit(windowWorker); } else { log.trace("Task window on the run loop thread", task.taskName()); windowWorker.run(); } }</code><technical_language>large window skew avg process invoked it, this logic catch contiguous long window spikiness. Please requirement</technical_language>

Target:
private void window() { state.startWindow(); Runnable windowWorker = new Runnable() { @Override public void run() { try { containerMetrics.windows().inc(); ReadableCoordinator coordinator = new ReadableCoordinator(task.taskName()); long startTime = clock.nanoTime(); task.window(coordinator); containerMetrics.windowNs().update(clock.nanoTime() - startTime); long lowerBoundForWindowTriggerTimeInMs = TimeUnit.NANOSECONDS .toMillis((long) containerMetrics.windowNs().getSnapshot().getAverage()); if (windowMs <= lowerBoundForWindowTriggerTimeInMs) { log.warn( "window() call might potentially starve process calls." + " Consider setting task.window.ms > ms", lowerBoundForWindowTriggerTimeInMs); } coordinatorRequests.update(coordinator); state.doneWindow(); } catch (Throwable t) { log.error("Task window failed", task.taskName(), t); abort(t); } finally { log.trace("Task window completed", task.taskName()); resume(); } } }; if (threadPool != null) { log.trace("Task window on the thread pool", task.taskName()); threadPool.submit(windowWorker); } else { log.trace("Task window on the run loop thread", task.taskName()); windowWorker.run(); } }
Source:
<code>public void sendEvents() { log.debug("Committing ActiveMQ transaction"); try { ClientSession session = this.getClientSession(); session.commit(); <START> session.close(); <END> } catch (Exception e) { log.error("Error committing ActiveMQ transaction", e); } }</code><technical_language>Put close() a finally block attempt is close session, commit failure. If closing session fails, do -- log move on</technical_language>

Target:
public void sendEvents() { log.debug("Committing ActiveMQ transaction"); try (ClientSession session = this.getClientSession()) { session.commit(); } catch (Exception e) { log.error("Error committing ActiveMQ transaction", e); } }
Source:
<code>public static void main(String[] args) { List<Trade> trades = ImmutableList.of(createTrade()); List<Column> columns = ImmutableList.of( Column.of(Measure.PRESENT_VALUE)); MarketDataBuilder marketDataBuilder = MarketDataBuilder.ofResource(MARKET_DATA_RESOURCE_ROOT); CalculationRules rules = CalculationRules.builder() .pricingRules(OpenGammaPricingRules.standard()) .marketDataRules(marketDataBuilder.rules()) <START> .reportingRules(ReportingRules.empty()) <END> .build(); Map<LocalDate, Map<RateCurveId, Curve>> historicalCurves = marketDataBuilder.loadAllRatesCurves(); List<LocalDate> scenarioDates = new ArrayList<LocalDate>(historicalCurves.keySet()); scenarioDates.sort(null); ScenarioDefinition historicalScenarios = buildHistoricalScenarios(historicalCurves, scenarioDates); LocalDate valuationDate = LocalDate.of(2015, 4, 23); BaseMarketData snapshot = marketDataBuilder.buildSnapshot(valuationDate); CalculationEngine engine = ExampleEngine.create(); Results results = engine.calculate(trades, columns, rules, snapshot, historicalScenarios); ScenarioResult<?> scenarioValuations = (ScenarioResult<?>) results.get(0, 0).getValue(); outputPnl(scenarioDates, scenarioValuations); }</code><technical_language>Empty reporting rules default this line is redundant</technical_language>

Target:
public static void main(String[] args) { List<Trade> trades = ImmutableList.of(createTrade()); List<Column> columns = ImmutableList.of( Column.of(Measure.PRESENT_VALUE)); MarketDataBuilder marketDataBuilder = MarketDataBuilder.ofResource(MARKET_DATA_RESOURCE_ROOT); CalculationRules rules = CalculationRules.builder() .pricingRules(OpenGammaPricingRules.standard()) .marketDataRules(marketDataBuilder.rules()) .build(); SortedMap<LocalDate, Map<RateCurveId, Curve>> historicalCurves = marketDataBuilder.loadAllRatesCurves(); List<LocalDate> scenarioDates = new ArrayList<LocalDate>(historicalCurves.keySet()); ScenarioDefinition historicalScenarios = buildHistoricalScenarios(historicalCurves, scenarioDates); LocalDate valuationDate = LocalDate.of(2015, 4, 23); BaseMarketData snapshot = marketDataBuilder.buildSnapshot(valuationDate); CalculationEngine engine = ExampleEngine.create(); Results results = engine.calculate(trades, columns, rules, snapshot, historicalScenarios); ScenarioResult<?> scenarioValuations = (ScenarioResult<?>) results.get(0, 0).getValue(); outputPnl(scenarioDates, scenarioValuations); }
Source:
<code>public byte[] get(NamedKey key) { byte[] result = null; try (ResourceHolder<ShardedJedis> clientHolder = supplier.get()) { final ShardedJedis jedis = clientHolder.get(); final byte[] itemKey = CacheImplUtils.computeKeyHash(prefix, key).getBytes(); final byte[] serialized = jedis.get(itemKey); if (serialized != null) { result = deserialize(key, serialized); hitCount.incrementAndGet(); } else { missCount.incrementAndGet(); } } catch (IOException ex) { <START> throw Throwables.propagate(ex); <END> } catch (JedisConnectionException ex) { if (isTimeout(ex)) { timeoutCount.incrementAndGet(); } throw Throwables.propagate(ex); } catch (JedisException | LZ4Exception ex) { errorCount.incrementAndGet(); log.warn(ex, "Error getting cache item"); return null; } return result; }</code><technical_language>increase errorCount, log a warning return null instead of propagating error query complete if cache is problems</technical_language>

Target:
public byte[] get(NamedKey key) { byte[] result = null; try (ResourceHolder<ShardedJedis> clientHolder = supplier.get()) { final ShardedJedis jedis = clientHolder.get(); final byte[] itemKey = CacheImplUtils.computeKeyHash(prefix, key).getBytes(); final byte[] serialized = jedis.get(itemKey); if (serialized != null) { result = deserialize(key, serialized); hitCount.incrementAndGet(); } else { missCount.incrementAndGet(); } } catch (IOException | JedisException | LZ4Exception ex) { this.countException(ex); log.warn(ex, "Error getting cache item"); } return result; }
Source:
<code>public void init_module_relative_import() { String code = String.join(System.getProperty("line.separator"), "from .. import fn", "fn()", "class A: pass"); FileInput fileInput = new PythonTreeMaker().fileInput(PythonParser.create().parse(code)); PythonFile pythonFile = Mockito.mock(PythonFile.class, "__init__.py"); when(pythonFile.fileName()).thenReturn("__init__.py"); PythonVisitorContext context = new PythonVisitorContext(fileInput, pythonFile, null, "foo.bar"); fileInput = context.rootTree(); CallExpression callExpression = (CallExpression) getAllDescendant(fileInput, tree -> tree.is(Tree.Kind.CALL_EXPR)).get(0); <START> assertThat(callExpression.calleeSymbol().fullyQualifiedName()).isEqualTo("fn"); <END> ClassDef classDef = (ClassDef) getAllDescendant(fileInput, tree -> tree.is(Tree.Kind.CLASSDEF)).get(0); assertThat(classDef.name().symbol().fullyQualifiedName()).isEqualTo("foo.bar.A"); }</code><technical_language>I understand, do FQN fn</technical_language>

Target:
public void init_module_relative_import() { String code = String.join(System.getProperty("line.separator"), "from .. import fn", "fn()", "class A: pass"); FileInput fileInput = new PythonTreeMaker().fileInput(PythonParser.create().parse(code)); PythonFile pythonFile = Mockito.mock(PythonFile.class, "__init__.py"); when(pythonFile.fileName()).thenReturn("__init__.py"); PythonVisitorContext context = new PythonVisitorContext(fileInput, pythonFile, null, "foo.bar"); fileInput = context.rootTree(); CallExpression callExpression = (CallExpression) getAllDescendant(fileInput, tree -> tree.is(Tree.Kind.CALL_EXPR)).get(0); assertThat(callExpression.calleeSymbol().fullyQualifiedName()).isEqualTo("foo.fn"); ClassDef classDef = (ClassDef) getAllDescendant(fileInput, tree -> tree.is(Tree.Kind.CLASSDEF)).get(0); assertThat(classDef.name().symbol().fullyQualifiedName()).isEqualTo("foo.bar.A"); }
Source:
<code>int limit(Long limit) { if (limit != null) { <START> parallelism = Math.min(parallelism, limit.intValue() / 1000); <END> } return Math.max(1, parallelism); }</code><technical_language>change limit.intValue() / 1000 (int) (limit / 1000)</technical_language>

Target:
int limit(Long limit) { if (limit != null) { parallelism = Math.min(parallelism, (int) (limit / 1000)); } return Math.max(1, parallelism); }
Source:
<code>private Mono<Document> tryUpdateDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { BridgeInternal.setProperty(document, "regionId", index); BridgeInternal.setProperty(document, "regionEndpoint", client.getReadEndpoint()); RequestOptions options = new RequestOptions(); <START> options.setIfMatchEtag(document.getETag()); <END> return client.replaceDocument(document.getSelfLink(), document, null).onErrorResume(e -> { if (hasDocumentClientException(e, 412)) { return Mono.empty(); } return Mono.error(e); }).map(ResourceResponse::getResource); }</code><technical_language>This is called ETag (see CosmosAsyncItemResponse.java: public String getETag()). Etag. consistent this</technical_language>

Target:
private Mono<Document> tryUpdateDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { BridgeInternal.setProperty(document, "regionId", index); BridgeInternal.setProperty(document, "regionEndpoint", client.getReadEndpoint()); RequestOptions options = new RequestOptions(); options.setIfMatchETag(document.getETag()); return client.replaceDocument(document.getSelfLink(), document, null).onErrorResume(e -> { if (hasDocumentClientException(e, 412)) { return Mono.empty(); } return Mono.error(e); }).map(ResourceResponse::getResource); }
Source:
<code>public void tag(final TagParams params) throws ImageNotFoundException, IOException { String sourceImage = params.getImage(); String targetImage = params.getRepository(); String tag = params.getTag(); <START> if (sourceImage.contains(":")) { <END> tag = sourceImage.split(":")[1]; sourceImage = sourceImage.split(":")[0]; } else if (isNullOrEmpty(tag)) { tag = "latest"; } String sourceImageWithTag; try { String sourceImageTagName = KubernetesStringUtils.getTagNameFromRepoString(sourceImage); ImageStreamTag existingTag = getImageStreamTagFromRepo(sourceImageTagName); sourceImageWithTag = existingTag.getTag().getFrom().getName(); } catch (IOException e) { sourceImageWithTag = String.format("%s:%s", sourceImage, tag); } String imageStreamTagName = KubernetesStringUtils.getImageStreamTagName(sourceImageWithTag, targetImage); createImageStreamTag(sourceImageWithTag, imageStreamTagName); }</code><technical_language>split images string tag image name multiple times in code. avoid duplication extract logic in a new method</technical_language>

Target:
public void tag(final TagParams params) throws ImageNotFoundException, IOException { String paramsSourceImage = params.getImage(); String targetImage = params.getRepository(); String paramsTag = params.getTag(); String sourceImage = KubernetesStringUtils.stripTagFromPullSpec(paramsSourceImage); String tag = KubernetesStringUtils.getTagNameFromPullSpec(paramsSourceImage); if (isNullOrEmpty(tag)) { tag = !isNullOrEmpty(paramsTag) ? paramsTag : "latest"; } String sourceImageWithTag; try { String sourceImageTagName = KubernetesStringUtils.convertPullSpecToTagName(sourceImage); ImageStreamTag existingTag = getImageStreamTagFromRepo(sourceImageTagName); sourceImageWithTag = existingTag.getTag().getFrom().getName(); } catch (IOException e) { sourceImageWithTag = String.format("%s:%s", sourceImage, tag); } String imageStreamTagName = KubernetesStringUtils.createImageStreamTagName(sourceImageWithTag, targetImage); createImageStreamTag(sourceImageWithTag, imageStreamTagName); }
Source:
<code>public String toString() { if (rate == (long) rate) { <START> return pair + " " + Long.toString((long) rate); <END> } return pair + " " + Double.toString(rate); }</code><technical_language>isMathematicalInteger "pair +" commonality</technical_language>

Target:
public String toString() { return pair + " " + (DoubleMath.isMathematicalInteger(rate) ? Long.toString((long) rate) : Double.toString(rate)); }
Source:
<code>NatsConnectionWriter(NatsConnection connection) { this.connection = connection; this.running = new AtomicBoolean(false); this.reconnectMode = new AtomicBoolean(false); this.startStopLock = new ReentrantLock(); this.stopped = new CompletableFuture<>(); ((CompletableFuture<Boolean>)this.stopped).complete(Boolean.TRUE); int bufSize = connection.getOptions().getBufferSize(); this.sendBuffer = new byte[bufSize]; <START> this.maxAccumulate = 1000; <END> outgoing = new MessageQueue(true, (int) (5 * maxAccumulate)); reconnectOutgoing = new MessageQueue(true, 0); }</code><technical_language>this based total pending size in bytes msgs</technical_language>

Target:
NatsConnectionWriter(NatsConnection connection) { this.connection = connection; this.running = new AtomicBoolean(false); this.reconnectMode = new AtomicBoolean(false); this.startStopLock = new ReentrantLock(); this.stopped = new CompletableFuture<>(); ((CompletableFuture<Boolean>)this.stopped).complete(Boolean.TRUE); int bufSize = connection.getOptions().getBufferSize(); this.sendBuffer = new byte[bufSize]; outgoing = new MessageQueue(true, Options.MAX_MESSAGES_IN_OUTGOING_QUEUE); reconnectOutgoing = new MessageQueue(true, 0); }
Source:
<code><START> PRED_change_owner_1(Term a1, Operation n) { <END> arg1 = a1; cont = n; }</code><technical_language>public</technical_language>

Target:
public PRED_change_owner_1(Term a1, Operation n) { arg1 = a1; cont = n; }
Source:
<code>public ILocationConfiguratorPlugin newInstance(String locationType) { if (BrooklynOrchestratorFactory.BROOKLYN.equals(locationType)) { return applicationContext.getBean(BrooklynLocationConfigurer.class); } return new ILocationConfiguratorPlugin() { @Override public List<PluginArchive> pluginArchives() { return new ArrayList<>(); } @Override public List<String> getResourcesTypes() { return new ArrayList<>(); } @Override public Map<String, MatchingConfiguration> getMatchingConfigurations() { <START> return new HashMap<>(); <END> } @Override public List<LocationResourceTemplate> instances(ILocationResourceAccessor resourceAccessor) { return null; } }; }</code><technical_language>Collections.emptyList .emptyMap here</technical_language>

Target:
public ILocationConfiguratorPlugin newInstance(String locationType) { if (BrooklynOrchestratorFactory.BROOKLYN.equals(locationType)) { return applicationContext.getBean(BrooklynLocationConfigurer.class); } return new ILocationConfiguratorPlugin() { @Override public List<PluginArchive> pluginArchives() { return Collections.emptyList(); } @Override public List<String> getResourcesTypes() { return Collections.emptyList(); } @Override public Map<String, MatchingConfiguration> getMatchingConfigurations() { return Collections.emptyMap(); } @Override public List<LocationResourceTemplate> instances(ILocationResourceAccessor resourceAccessor) { return Collections.emptyList(); } }; }
Source:
<code>private boolean checkServiceDeployed(String response, int numTasks, boolean useMarathonServices) { JSONObject deployment = new JSONObject(response); JSONArray tasks = (JSONArray) deployment.get("tasks"); int numTasksRunning = 0; for (int i = 0; i < tasks.length(); i++) { if (useMarathonServices) { numTasksRunning = tasks.getJSONObject(i).get("status").equals("RUNNING") ? (numTasksRunning + 1) : numTasksRunning; } else if (!useMarathonServices) { numTasksRunning = tasks.getJSONObject(i).get("state").equals("TASK_RUNNING") ? (numTasksRunning + 1) : numTasksRunning; } } <START> return numTasksRunning == numTasks ? true : false; <END> }</code><technical_language>Dejaria directamente el return asi: _return numTasksRunning == numTasks;_ (poner lo otro al final es redundante)</technical_language>

Target:
private boolean checkServiceDeployed(String response, int numTasks, boolean useMarathonServices) { JSONObject deployment = new JSONObject(response); JSONArray tasks = (JSONArray) deployment.get("tasks"); int numTasksRunning = 0; for (int i = 0; i < tasks.length(); i++) { if (useMarathonServices) { numTasksRunning = tasks.getJSONObject(i).get("status").equals("RUNNING") ? (numTasksRunning + 1) : numTasksRunning; } else { numTasksRunning = tasks.getJSONObject(i).get("state").equals("TASK_RUNNING") ? (numTasksRunning + 1) : numTasksRunning; } } return numTasksRunning == numTasks; }
Source:
<code>private int skipIndefiniteLengthContents() throws BerDataValueFormatException { boolean prevZeroByte = false; int bytesRead = 0; while (true) { if (!mBuf.hasRemaining()) { throw new BerDataValueFormatException( "Truncated indefinite-length contents: " + bytesRead + " bytes read"); } int b = mBuf.get(); bytesRead++; if (bytesRead < 0) { throw new BerDataValueFormatException("Indefinite-length contents too long"); } if (b == 0) { if (prevZeroByte) { return bytesRead - 2; } prevZeroByte = true; <START> continue; <END> } else { prevZeroByte = false; } } }</code><technical_language>Unneeded</technical_language>

Target:
private int skipIndefiniteLengthContents() throws BerDataValueFormatException { boolean prevZeroByte = false; int bytesRead = 0; while (true) { if (!mBuf.hasRemaining()) { throw new BerDataValueFormatException( "Truncated indefinite-length contents: " + bytesRead + " bytes read"); } int b = mBuf.get(); bytesRead++; if (bytesRead < 0) { throw new BerDataValueFormatException("Indefinite-length contents too long"); } if (b == 0) { if (prevZeroByte) { return bytesRead - 2; } prevZeroByte = true; } else { prevZeroByte = false; } } }