auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testPrintXpathTwo() throws Exception { final String eol = System.lineSeparator(); final String fileContent = "class Test { public void method() {int a = 5; int b = 5;}}"; final Path file = Files.createTempFile("", ""); Files.write(file, fileContent.getBytes(StandardCharsets.UTF_8)); final String expected = "CLASS_DEF -> CLASS_DEF [1:0]" + eol + "`--OBJBLOCK -> OBJBLOCK [1:11]" + eol + " |--METHOD_DEF -> METHOD_DEF [1:13]" + eol + " | `--SLIST -> { [1:34]" + eol + " | |--VARIABLE_DEF -> VARIABLE_DEF [1:35]" + eol + " | | |--IDENT -> a [1:39]" + eol + "---------" + eol + "CLASS_DEF -> CLASS_DEF [1:0]" + eol + "`--OBJBLOCK -> OBJBLOCK [1:11]" + eol + " |--METHOD_DEF -> METHOD_DEF [1:13]" + eol + " | `--SLIST -> { [1:34]" + eol + " | |--VARIABLE_DEF -> VARIABLE_DEF [1:46]" + eol + " | | |--IDENT -> b [1:50]" + eol; assertEquals("Branch string is different", expected, XpathUtil.printXpathBranch( " file.toFile())); }

Target:
public void testPrintXpathTwo() throws Exception { final String fileContent = "class Test { public void method() {int a = 5; int b = 5;}}"; final File file = tempFolder.newFile(); Files.write(file.toPath(), fileContent.getBytes(StandardCharsets.UTF_8)); final String expected = addEndOfLine( "CLASS_DEF -> CLASS_DEF [1:0]", "`--OBJBLOCK -> OBJBLOCK [1:11]", " |--METHOD_DEF -> METHOD_DEF [1:13]", " | `--SLIST -> { [1:34]", " | |--VARIABLE_DEF -> VARIABLE_DEF [1:35]", " | | |--IDENT -> a [1:39]", "---------", "CLASS_DEF -> CLASS_DEF [1:0]", "`--OBJBLOCK -> OBJBLOCK [1:11]", " |--METHOD_DEF -> METHOD_DEF [1:13]", " | `--SLIST -> { [1:34]", " | |--VARIABLE_DEF -> VARIABLE_DEF [1:46]", " | | |--IDENT -> b [1:50]"); final String result = XpathUtil.printXpathBranch( " assertThat("Branch string is different", result, is(expected)); }
Source:
public AllelicCountReader(final File file) throws IOException { super(file); if (columns().containsAll(AllelicCountTableColumns.FULL_COLUMN_NAME_ARRAY)) { verbosity = AllelicCountTableColumns.AllelicCountTableVerbosity.FULL; } else if (columns().containsAll(AllelicCountTableColumns.INTERMEDIATE_COLUMN_NAME_ARRAY)) { verbosity = AllelicCountTableColumns.AllelicCountTableVerbosity.INTERMEDIATE; } else if (columns().containsAll(AllelicCountTableColumns.BASIC_COLUMN_NAME_ARRAY)) { verbosity = AllelicCountTableColumns.AllelicCountTableVerbosity.BASIC; } else { final Set<String> missingColumns = Sets.difference( new HashSet<>(AllelicCountTableColumns.BASIC_COLUMN_NAME_ARRAY), new HashSet<>(columns().names())); throw new UserException.BadInput("Bad header in AllelicCount file. Not all mandatory columns are present." + " Missing: " + StringUtils.join(missingColumns, ", ")); } }

Target:
public AllelicCountReader(final File file) throws IOException { super(file); if (columns().containsAll(AllelicCountTableColumns.FULL_COLUMN_NAME_ARRAY)) { verbosity = AllelicCountTableVerbosity.FULL; } else if (columns().containsAll(AllelicCountTableColumns.INTERMEDIATE_COLUMN_NAME_ARRAY)) { verbosity = AllelicCountTableVerbosity.INTERMEDIATE; } else if (columns().containsAll(AllelicCountTableColumns.BASIC_COLUMN_NAME_ARRAY)) { verbosity = AllelicCountTableVerbosity.BASIC; } else { final Set<String> missingColumns = Sets.difference( new HashSet<>(AllelicCountTableColumns.BASIC_COLUMN_NAME_ARRAY), new HashSet<>(columns().names())); throw new UserException.BadInput("Bad header in AllelicCount file. Not all mandatory columns are present." + " Missing: " + StringUtils.join(missingColumns, ", ")); } }
Source:
protected Optional<PlanNode> pushDownProjectOff(PlanNodeIdAllocator idAllocator, JoinNode joinNode, Set<Symbol> referencedOutputs) { Optional<PlanNode> newLeft = restrictOutputs(idAllocator, joinNode.getLeft(), referencedOutputs); Optional<PlanNode> newRight = restrictOutputs(idAllocator, joinNode.getRight(), referencedOutputs); if (!(newLeft.isPresent() || newRight.isPresent())) { return Optional.empty(); } ImmutableList.Builder<Symbol> outputSymbolBuilder = ImmutableList.builder(); outputSymbolBuilder.addAll(newLeft.orElse(joinNode.getLeft()).getOutputSymbols()); outputSymbolBuilder.addAll(newRight.orElse(joinNode.getRight()).getOutputSymbols()); return Optional.of(new JoinNode( idAllocator.getNextId(), joinNode.getType(), newLeft.orElse(joinNode.getLeft()), newRight.orElse(joinNode.getRight()), joinNode.getCriteria(), outputSymbolBuilder.build(), joinNode.getFilter(), joinNode.getLeftHashSymbol(), joinNode.getRightHashSymbol(), joinNode.getDistributionType())); }

Target:
protected Optional<PlanNode> pushDownProjectOff(PlanNodeIdAllocator idAllocator, JoinNode joinNode, Set<Symbol> referencedOutputs) { Optional<PlanNode> newLeft = restrictOutputs(idAllocator, joinNode.getLeft(), referencedOutputs); Optional<PlanNode> newRight = restrictOutputs(idAllocator, joinNode.getRight(), referencedOutputs); if (!newLeft.isPresent() && !newRight.isPresent()) { return Optional.empty(); } ImmutableList.Builder<Symbol> outputSymbolBuilder = ImmutableList.builder(); outputSymbolBuilder.addAll(newLeft.orElse(joinNode.getLeft()).getOutputSymbols()); outputSymbolBuilder.addAll(newRight.orElse(joinNode.getRight()).getOutputSymbols()); return Optional.of(new JoinNode( idAllocator.getNextId(), joinNode.getType(), newLeft.orElse(joinNode.getLeft()), newRight.orElse(joinNode.getRight()), joinNode.getCriteria(), outputSymbolBuilder.build(), joinNode.getFilter(), joinNode.getLeftHashSymbol(), joinNode.getRightHashSymbol(), joinNode.getDistributionType())); }
Source:
private void addVmToDb() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { AddVmStatic(); AddVmDynamic(); AddVmNetwork(); AddVmStatistics(); getCompensationContext().stateChanged(); return null; } }); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { AddVmImages(); MoveOrCopyAllImageGroups(); VmHandler.LockVm(getVm().getvm_guid()); return null; } }); }

Target:
private void addVmToDb() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { AddVmStatic(); AddVmDynamic(); AddVmNetwork(); AddVmStatistics(); getCompensationContext().stateChanged(); return null; } }); }
Source:
static Map<Partition, List<String>> obtainPartitionDescriptorMap(String stagingDirectory, String streamName) { if (StringUtils.isBlank(stagingDirectory)) { LOG.warn("Empty staging directory"); return null; } if (StringUtils.isBlank(streamName)) { throw new SamzaException("stream name is empty!"); } Path path = PartitionDescriptorUtil.getPartitionDescriptorPath(stagingDirectory, streamName); try (FileSystem fs = path.getFileSystem(new Configuration())) { if (!fs.exists(path)) { return null; } try (FSDataInputStream fis = fs.open(path)) { String json = IOUtils.toString(fis, StandardCharsets.UTF_8); return PartitionDescriptorUtil.getDescriptorMapFromJson(json); } } catch (IOException e) { throw new SamzaException("Failed to read partition description from: " + path); } }

Target:
static Map<Partition, List<String>> obtainPartitionDescriptorMap(String stagingDirectory, String streamName) { if (StringUtils.isBlank(stagingDirectory)) { LOG.info("Empty or null staging directory: {}", stagingDirectory); return Collections.emptyMap(); } if (StringUtils.isBlank(streamName)) { throw new SamzaException(String.format("stream name (%s) is null or empty!", streamName)); } Path path = PartitionDescriptorUtil.getPartitionDescriptorPath(stagingDirectory, streamName); try (FileSystem fs = path.getFileSystem(new Configuration())) { if (!fs.exists(path)) { return Collections.emptyMap(); } try (FSDataInputStream fis = fs.open(path)) { String json = IOUtils.toString(fis, StandardCharsets.UTF_8); return PartitionDescriptorUtil.getDescriptorMapFromJson(json); } } catch (IOException e) { throw new SamzaException("Failed to read partition description from: " + path); } }
Source:
public SimpleInterval(final String contig, final int start, final int end){ if(contig == null){ throw new IllegalArgumentException("contig cannot be null"); } if (start <= 0 ){ throw new IllegalArgumentException("SimpleInterval is 1 based, so start must be >= 1, start:%d" + start); } if (end < start){ throw new IllegalArgumentException( String.format("start must be <= end. start:%d end:%d", start, end)); } this.contig = contig; this.start = start; this.end = end; }

Target:
public SimpleInterval(final String contig, final int start, final int end){ if(contig == null){ throw new IllegalArgumentException("contig cannot be null"); } if (start <= 0 ){ throw new IllegalArgumentException("SimpleInterval is 1 based, so start must be >= 1, start:%d" + start); } if (end < start -1){ throw new IllegalArgumentException( String.format("end must be >= start -1 . start:%d end:%d", start, end)); } this.contig = contig; this.start = start; this.end = end; }
Source:
private void initActive() throws ExecutorManagerException { final Executor executor; try { final String host = requireNonNull(getHost()); final int port = props.getInt(ConfigurationKeys.EXECUTOR_PORT, -1); checkState(port != -1); executor = this.executionLoader.fetchExecutor(host, port); } catch (final ExecutorManagerException e) { logger.error("Error fetching executor entry from DB", e); throw e; } if (executor == null) { logger.info("This executor wasn't found in the DB. Setting active=false."); getFlowRunnerManager().setActiveInternal(false); } else { logger.info("This executor is already in the DB. Found active=" + executor.isActive()); getFlowRunnerManager().setActiveInternal(executor.isActive()); } }

Target:
private void initActive() throws ExecutorManagerException { final Executor executor; final int port = this.props.getInt(ConfigurationKeys.EXECUTOR_PORT, -1); if (port != -1) { final String host = requireNonNull(getHost()); try { executor = this.executionLoader.fetchExecutor(host, port); } catch (final ExecutorManagerException e) { logger.error("Error fetching executor entry from DB", e); throw e; } if (executor == null) { logger.info("This executor wasn't found in the DB. Setting active=false."); getFlowRunnerManager().setActiveInternal(false); } else { logger.info("This executor is already in the DB. Found active=" + executor.isActive()); getFlowRunnerManager().setActiveInternal(executor.isActive()); } } else { logger.info(ConfigurationKeys.EXECUTOR_PORT + " wasn't set - free port will be picked automatically. Executor " + "is started with active=false and must be activated separately."); } }
Source:
public static Version getCompatibilityVersion(VmBase vmBase) { return vmBase.getClusterId() != null ? getInstance().getClusterDao().get(vmBase.getClusterId()).getCompatibilityVersion() : Version.v3_6; }

Target:
public static Version getCompatibilityVersion(VmBase vmBase) { return vmBase.getClusterId() != null ? getInstance().getClusterDao().get(vmBase.getClusterId()).getCompatibilityVersion() : Version.v3_5; }
Source:
void updateBindings(List<Binding> bindings) throws SQLException { getConnection(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { preparedStatement = conn.prepareStatement(UPDATE_BINDING); for (Binding binding : bindings) { preparedStatement.setString(1, binding.getBindingDetails()); preparedStatement.setString(2, binding.getQueueName()); preparedStatement.addBatch(); } preparedStatement.executeBatch(); } catch (SQLException e) { e.printStackTrace(); } finally { close(conn, preparedStatement, resultSet); } }

Target:
void updateBindings(List<Binding> bindings) throws SQLException { try (Connection conn = getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(UPDATE_BINDING)) { for (Binding binding : bindings) { preparedStatement.setString(1, binding.getBindingDetails()); preparedStatement.setString(2, binding.getQueueName()); preparedStatement.addBatch(); } preparedStatement.executeBatch(); } }
Source:
public String getURI() { return "/metadatamapping/metadatasource"; }

Target:
public String getURI() { return "/metadatamapping/source"; }
Source:
private String getHypervisor(String folder) { String[] validHypervisors = CDK3Server.getHypervisors(); String hyperV = validHypervisors[0]; File config = new File(folder, "config"); File configJson = new File(config, "config.json"); if (!configJson.exists() || !configJson.isFile()) { return hyperV; } String path = configJson.getAbsolutePath(); try { String content = new String(Files.readAllBytes(Paths.get(path))); ModelNode mn = ModelNode.fromJSONString(content); ModelNode o = mn.get("vm-driver"); String val = (o == null ? null : o.asString()); if (val != null && Arrays.asList(validHypervisors).contains(val)) { return val; } } catch (IOException e) { IOException ioe2 = new IOException("Error parsing " + path, e); CDKCoreActivator.pluginLog().logError(ioe2); } return hyperV; }

Target:
private String getHypervisor(String folder) { String[] validHypervisors = CDK3Server.getHypervisors(); String hyperV = validHypervisors[0]; File config = new File(folder, "config"); File configJson = new File(config, "config.json"); if (!configJson.exists() || !configJson.isFile()) { return hyperV; } String path = configJson.getAbsolutePath(); try { String content = new String(Files.readAllBytes(Paths.get(path))); ModelNode mn = ModelNode.fromJSONString(content); ModelNode o = mn.get("vm-driver"); String val = (o == null ? null : o.asString()); if (val != null && Arrays.asList(validHypervisors).contains(val)) { return val; } } catch (IOException e) { CDKCoreActivator.pluginLog().logError("Error parsing " + path, e); } return hyperV; }
Source:
public String showStatus() throws InterruptedException, ExecutionException { if (future.isDone()) { result = future.get(); if (result == null) return "failure"; return "success"; } return "status"; }

Target:
public String showStatus() throws InterruptedException, ExecutionException { if (future.isDone()) { result = future.get(); if (result == null) { return "auth/transformation/emptyTransformation"; } return "auth/transformation/successTransformation"; } return "auth/transformation/statusTransformation"; }
Source:
public View getView(ViewModel model, HttpServletRequest request) { try { MediaType mediaType = ContentNegotiationResolver.INSTANCE.getContentType(request, null, producesMediaTypes); if (mediaType.equals(MediaType.APPLICATION_JSON) || "stormpathJsonView".equals(model.getViewName())) { return jsonView; } if (mediaType.equals(MediaType.TEXT_HTML)) { return delegateViewResolver.getView(model, request); } } catch (UnresolvedMediaTypeException e) { } return null; }

Target:
public View getView(ViewModel model, HttpServletRequest request) { try { MediaType mediaType = ContentNegotiationResolver.INSTANCE.getContentType(request, null, producesMediaTypes); if (mediaType.equals(MediaType.APPLICATION_JSON) || STORMPATH_JSON_VIEW_NAME.equals(model.getViewName())) { return jsonView; } if (mediaType.equals(MediaType.TEXT_HTML)) { return delegateViewResolver.getView(model, request); } } catch (UnresolvedMediaTypeException e) { } return null; }
Source:
protected VdcReturnValueBase attemptRollback(VdcActionType commandType, VdcActionParametersBase params, CommandContext context) { if (canPerformRollbackUsingCommand(commandType, params)) { params.setExecutionReason(CommandExecutionReason.ROLLBACK_FLOW); return Backend.getInstance().runInternalAction(commandType, params); } return new VdcReturnValueBase(); }

Target:
protected VdcReturnValueBase attemptRollback(VdcActionType commandType, VdcActionParametersBase params, CommandContext context) { if (canPerformRollbackUsingCommand(commandType, params)) { params.setExecutionReason(CommandExecutionReason.ROLLBACK_FLOW); return Backend.getInstance().runInternalAction(commandType, params, context); } return new VdcReturnValueBase(); }
Source:
public synchronized void close() { if (!isOpen()) { LOGGER.info("jms transport already closed, returning"); return; } try { producer.close(); session.close(); } catch (JMSException e) { LOGGER.error("failed to close jms producer", e); } finally { producer = null; session = null; } }

Target:
public synchronized void close() { if (!isOpen()) { LOGGER.info("jms transport already closed, returning"); return; } try (Session closeSession = session) { producer.close(); } catch (JMSException e) { LOGGER.error("failed to close jms producer", e); } finally { producer = null; session = null; } }
Source:
public InvalidationTracker(RoomDatabase database, Map<String, String> shadowTablesMap, String... tableNames) { mDatabase = database; mObservedTableTracker = new ObservedTableTracker(tableNames.length); mTableIdLookup = new ArrayMap<>(); mShadowTableLookup = new SparseArrayCompat<>(); final int size = tableNames.length; mTableNames = new String[size]; for (int id = 0; id < size; id++) { final String tableName = tableNames[id].toLowerCase(Locale.US); mTableIdLookup.put(tableName, id); mTableNames[id] = tableName; if (shadowTablesMap.containsKey(tableNames[id])) { final String shadowTableName = shadowTablesMap.get(tableNames[id]); mShadowTableLookup.append(id, shadowTableName.toLowerCase(Locale.US)); } } mTableVersions = new long[tableNames.length]; Arrays.fill(mTableVersions, 0); }

Target:
public InvalidationTracker(RoomDatabase database, Map<String, String> shadowTablesMap, String... tableNames) { mDatabase = database; mObservedTableTracker = new ObservedTableTracker(tableNames.length); mTableIdLookup = new ArrayMap<>(); mShadowTableLookup = new SparseArrayCompat<>(shadowTablesMap.size()); final int size = tableNames.length; mTableNames = new String[size]; for (int id = 0; id < size; id++) { final String tableName = tableNames[id].toLowerCase(Locale.US); mTableIdLookup.put(tableName, id); mTableNames[id] = tableName; if (shadowTablesMap.containsKey(tableNames[id])) { final String shadowTableName = shadowTablesMap.get(tableNames[id]); mShadowTableLookup.append(id, shadowTableName.toLowerCase(Locale.US)); } } mTableVersions = new long[tableNames.length]; Arrays.fill(mTableVersions, 0); }
Source:
public ReactorNettyClient(String url, String username, String password, ReactorNettyClientOptions options) { objectMapper = options.objectMapper() == null ? createDefaultObjectMapper() : options.objectMapper().get(); client = options.client() == null ? HttpClient.create().baseUrl(url) : options.client().get(); this.token = options.token() == null ? createBasicAuthenticationToken(username, password) : options.token(); if (options.onResponseCallback() == null) { this.onResponseCallback = (response, connection) -> { if (response.method() == HttpMethod.GET) { if (response.status().code() >= 500) { throw new HttpServerException(response.status().code(), response.status().reasonPhrase()); } else if (response.status().code() >= 400) { throw new HttpClientException(response.status().code(), response.status().reasonPhrase()); } } }; } else { this.onResponseCallback = (response, connection) -> options.onResponseCallback().accept(new HttpEndpoint(response.uri(), response.method().name()), toHttpResponse(response)); } }

Target:
public ReactorNettyClient(String url, String username, String password, ReactorNettyClientOptions options) { objectMapper = options.objectMapper() == null ? createDefaultObjectMapper() : options.objectMapper().get(); client = options.client() == null ? HttpClient.create().baseUrl(url) : options.client().get(); this.token = options.token() == null ? createBasicAuthenticationToken(username, password) : options.token(); if (options.onResponseCallback() == null) { this.responseCallback = response -> { if (response.method() == HttpMethod.GET) { if (response.status().code() >= 500) { throw new HttpServerException(response.status().code(), response.status().reasonPhrase()); } else if (response.status().code() >= 400) { throw new HttpClientException(response.status().code(), response.status().reasonPhrase()); } } }; } else { this.responseCallback = response -> options.onResponseCallback().accept(new HttpEndpoint(response.uri(), response.method().name()), toHttpResponse(response)); } ByteBufAllocator byteBufAllocator = new PooledByteBufAllocator(); this.byteBufSupplier = () -> byteBufAllocator.buffer(); }
Source:
public String getCommandDescription() { return "Merges multiple Parquet files into one. " + "The command doesn't merge row groups, just places one after the other. " + "When used to merge many small files, the resulting file will still contain small row groups."; }

Target:
public String getCommandDescription() { return "Merges multiple Parquet files into one. " + "The command doesn't merge row groups, just places one after the other. " + "When used to merge many small files, the resulting file will still contain small row groups, " + "which usually leads to bad query performance."; }
Source:
private void startCollectingLogs() throws IOException, InterruptedException { Preconditions.checkNotNull(currentLogCollector, "Collector should not be null"); currentLogCollector.startCollecting(containersToStart.size() + containersStarted.size()); }

Target:
private void startCollectingLogs() { currentLogCollector.initializeExecutor(Sets.union(containersToStart, containersStarted).size()); }
Source:
public static List<URI> processScannedFilesAsURIs(List<String> classPathFiles) { List<URI> deps = new ArrayList<>(); for (String file : classPathFiles) { if (FilenameUtils.getName(file).startsWith(".")) { continue; } if (file.endsWith(JAVA_ARCHIVE_RESOURCE_EXT)) { if (file.startsWith(FILE_URI)) { deps.add(URI.create(file)); } else { deps.add(URI.create(FILE_URI + file)); } } } return deps; }

Target:
public static List<URI> processScannedFilesAsURIs(List<String> classPathFiles) { List<URI> deps = new ArrayList<>(); for (String file : classPathFiles) { if (FilenameUtils.getName(file).startsWith(".")) { continue; } if (file.endsWith(CommonConstants.JAVA_ARCHIVE_RESOURCE_EXT)) { if (file.startsWith(CommonConstants.FILE_URI)) { deps.add(URI.create(file)); } else { deps.add(URI.create(CommonConstants.FILE_URI + file)); } } } return deps; }
Source:
private void captureOutput(Process process, String vepOutputPath) { writingOk = new AtomicBoolean(false); outputCapturer = new Thread(() -> { long writtenLines = 0; boolean skipComments = new File(vepOutputPath).exists(); try (OutputStreamWriter writer = getOutputStreamWriter(vepOutputPath); BufferedReader processStandardOutput = getBufferedReader(process) ) { writtenLines = copyVepOutput(processStandardOutput, writer, skipComments); writingOk.set(true); } catch (IOException e) { logger.error("Writing the VEP output to " + vepOutputPath + " failed. ", e); } logger.trace("Finished writing VEP output ({} lines written) to {}", writtenLines, vepOutputPath); }); logger.trace("Starting writing VEP output to {}", vepOutputPath); outputCapturer.start(); }

Target:
private void captureOutput(Process process, String vepOutputPath) { writingOk = new AtomicBoolean(false); outputCaptureThread = new Thread(() -> { long writtenLines = 0; boolean skipComments = new File(vepOutputPath).exists(); try (OutputStreamWriter writer = getOutputStreamWriter(vepOutputPath); BufferedReader processStandardOutput = getBufferedReader(process) ) { writtenLines = copyVepOutput(processStandardOutput, writer, skipComments); writingOk.set(true); } catch (IOException e) { logger.error("Writing the VEP output to " + vepOutputPath + " failed. ", e); } logger.trace("Finished writing VEP output ({} lines written) to {}", writtenLines, vepOutputPath); }); logger.trace("Starting writing VEP output to {}", vepOutputPath); outputCaptureThread.start(); }
Source:
@Override public void run() { try { Thread.currentThread().setName(Utils.THREAD_PREFIX + data.getName()); result = hunt(); if (result == null) { dispatcher.dispatchFailed(this); } else { dispatcher.dispatchComplete(this); } } catch (IOException e) { exception = e; dispatcher.dispatchRetry(this); } catch (OutOfMemoryError e) { result = null; dispatcher.dispatchFailed(this); throw e; } catch (Exception e) { exception = e; dispatcher.dispatchFailed(this); } finally { Thread.currentThread().setName(Utils.THREAD_IDLE_NAME); } }

Target:
@Override public void run() { try { Thread.currentThread().setName(Utils.THREAD_PREFIX + data.getName()); result = hunt(); if (result == null) { dispatcher.dispatchFailed(this); } else { dispatcher.dispatchComplete(this); } } catch (IOException e) { exception = e; dispatcher.dispatchRetry(this); } catch (OutOfMemoryError e) { StringWriter writer = new StringWriter(); stats.createSnapshot().dump(new PrintWriter(writer)); exception = new RuntimeException(writer.toString(), e); dispatcher.dispatchFailed(this); } catch (Exception e) { exception = e; dispatcher.dispatchFailed(this); } finally { Thread.currentThread().setName(Utils.THREAD_IDLE_NAME); } }
Source:
public void test() { final HelloWorld hello = new HelloWorld(); assertTrue("Hello World".equals(hello.test())); }

Target:
public void test() { final HelloWorld hello = new HelloWorld(); assertEquals("Hello World", hello.test()); }
Source:
public synchronized CompletableFuture<Boolean> addToWaitList(String email) { if (! enableWaitList || numberWaiting >= MAX_WAITING || ! VALID_EMAIL.matcher(email).matches()) return Futures.of(false); try { Files.write(waitingList, (email + "\n").getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); numberWaiting++; return Futures.of(true); } catch (IOException e) { e.printStackTrace(); return Futures.of(false); } }

Target:
public synchronized CompletableFuture<Boolean> addToWaitList(String email) { if (! enableWaitList || numberWaiting >= MAX_WAITING || ! VALID_EMAIL.matcher(email).matches() || email.length() > MAX_EMAIL_LENGTH) return Futures.of(false); try { Files.write(waitingList, (email + "\n").getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); numberWaiting++; return Futures.of(true); } catch (IOException e) { e.printStackTrace(); return Futures.of(false); } }
Source:
public BatchItem( final String rawEvent, final EmptyInjectionConfiguration emptyInjectionConfiguration, final InjectionConfiguration[] injections, final List<Integer> skipCharacters) { this.rawEvent = rawEvent; this.skipCharacters = skipCharacters; try { this.event = StrictJsonParser.parseObject(rawEvent); } catch (final JSONException e) { LOG.debug("[STRICT_JSON_FAIL] Failed to parse event with strict parser: Error message: {}", rawEvent, e.getMessage()); throw e; } this.eventSize = rawEvent.getBytes(StandardCharsets.UTF_8).length; this.emptyInjectionConfiguration = emptyInjectionConfiguration; this.injections = injections; this.response = new BatchItemResponse(); Optional.ofNullable(this.event.optJSONObject("metadata")) .map(e -> e.optString("eid", null)) .ifPresent(this.response::setEid); }

Target:
public BatchItem( final String rawEvent, final EmptyInjectionConfiguration emptyInjectionConfiguration, final InjectionConfiguration[] injections, final List<Integer> skipCharacters) { this.rawEvent = rawEvent; this.skipCharacters = skipCharacters; this.event = StrictJsonParser.parseObject(rawEvent); this.eventSize = rawEvent.getBytes(StandardCharsets.UTF_8).length; this.emptyInjectionConfiguration = emptyInjectionConfiguration; this.injections = injections; this.response = new BatchItemResponse(); Optional.ofNullable(this.event.optJSONObject("metadata")) .map(e -> e.optString("eid", null)) .ifPresent(this.response::setEid); }
Source:
public Response countAssets(@Context UriInfo info, @Context SecurityContext sc) throws InvalidParameterException { if (logger.isLoggable(Level.FINE)) { logger.fine("countAssets called with query parameters: " + info.getRequestUri().getRawQuery()); } AssetQueryParameters params = AssetQueryParameters.create(info); Collection<AssetFilter> filters = params.getFilters(); if (!sc.isUserInRole(ADMIN_ROLE)) { AssetFilter publishedFilter = new AssetFilter(Asset.STATE, Collections.<Condition> singletonList(new Condition(Operation.EQUALS, Asset.State.PUBLISHED.getValue()))); filters.add(publishedFilter); } int count = assetService.countAllAssets(filters, params.getSearchTerm()); return Response.noContent().header("count", count).build(); }

Target:
public Response countAssets(@Context UriInfo info, @Context SecurityContext sc) throws InvalidParameterException { if (logger.isLoggable(Level.FINE)) { logger.fine("countAssets called with query parameters: " + info.getRequestUri().getRawQuery()); } AssetQueryParameters params = AssetQueryParameters.create(info); Collection<AssetFilter> filters = params.getFilters(); if (!sc.isUserInRole(ADMIN_ROLE)) { filters.add(ASSET_IS_PUBLISHED); } int count = assetService.countAllAssets(filters, params.getSearchTerm()); return Response.noContent().header("count", count).build(); }
Source:
public void shouldScheduleZetesUpdateJob() { ebodacScheduler.unscheduleZetesUpdateJob(); verify(motechSchedulerService).safeUnscheduleAllJobs(EbodacConstants.ZETES_UPDATE_EVENT); Date startDate = DateTime.now().toDate(); String zetesUrl = "zetesUrl"; String zetesUsername = "username"; String zetesPassword = "password"; ebodacScheduler.scheduleZetesUpdateJob(startDate,zetesUrl,zetesUsername,zetesPassword); Map<String, Object> eventParameters = new HashMap<>(); eventParameters.put(EbodacConstants.ZETES_URL, zetesUrl); eventParameters.put(EbodacConstants.ZETES_USERNAME, zetesUsername); eventParameters.put(EbodacConstants.ZETES_PASSWORD, zetesPassword); MotechEvent event = new MotechEvent(EbodacConstants.ZETES_UPDATE_EVENT, eventParameters); Period period = Period.days(1); RepeatingPeriodSchedulableJob job = new RepeatingPeriodSchedulableJob(event, startDate, null, period, true); verify(motechSchedulerService).safeScheduleRepeatingPeriodJob(job); }

Target:
public void shouldScheduleZetesUpdateJob() { Date startDate = DateTime.now().toDate(); String zetesUrl = "zetesUrl"; String zetesUsername = "username"; String zetesPassword = "password"; ebodacScheduler.scheduleZetesUpdateJob(startDate,zetesUrl,zetesUsername,zetesPassword); Map<String, Object> eventParameters = new HashMap<>(); eventParameters.put(EbodacConstants.ZETES_URL, zetesUrl); eventParameters.put(EbodacConstants.ZETES_USERNAME, zetesUsername); eventParameters.put(EbodacConstants.ZETES_PASSWORD, zetesPassword); MotechEvent event = new MotechEvent(EbodacConstants.ZETES_UPDATE_EVENT, eventParameters); Period period = Period.days(1); RepeatingPeriodSchedulableJob job = new RepeatingPeriodSchedulableJob(event, startDate, null, period, true); verify(motechSchedulerService).safeScheduleRepeatingPeriodJob(job); }
Source:
public DefaultLoadBalancingPolicy(DriverContext context, String profileName) { this( getLocalDcFromConfig(context, profileName), getFilterFromConfig(context, profileName), context); }

Target:
public DefaultLoadBalancingPolicy(DriverContext context, String profileName) { this( getLocalDcFromConfig(context, profileName), getFilterFromConfig(context, profileName), context, profileName.equals(DriverConfigProfile.DEFAULT_NAME)); }
Source:
if (res != null) { List<URL> urls = Collections.list(res); Map<String, List<URL>> normalized = new LinkedHashMap<String, List<URL>>(); for (URL url : urls) { try { String canonicalPath = IOUtils.toCanonicalFilePath(url); List<URL> pathURLs = normalized.get(canonicalPath); if (pathURLs == null) { pathURLs = new ArrayList<URL>(); normalized.put(canonicalPath, pathURLs); } pathURLs.add(url); } catch (URISyntaxException e) { String message = "Could not parse classpath resource URI: " + url.toString(); LogFactory.getLog(Version.class).fatal(message, e); throw new Error(message, e); } catch (IOException e) { String message = "Could not retrieve canonical path to classpath resource: " + url.toString(); LogFactory.getLog(Version.class).fatal(message, e); throw new Error(message, e); } } int foundJars = 0; if (normalized.size() > 1) { StringBuilder sb = new StringBuilder("Multiple ES-Hadoop versions detected in the classpath; please use only one\n"); for (List<URL> pathURLs : normalized.values()) { String path = pathURLs.get(0).toString(); if (path.contains("jar:")) { foundJars++; sb.append(path.replace("!/" + target, "")); sb.append("\n"); } } if (foundJars > 1) { LogFactory.getLog(Version.class).fatal(sb); throw new Error(sb.toString()); } } }

Target:
if (res != null) { List<URL> urls = Collections.list(res); Map<String, List<URL>> normalized = new LinkedHashMap<String, List<URL>>(); for (URL url : urls) { try { String canonicalPath = IOUtils.toCanonicalFilePath(url); List<URL> pathURLs = normalized.get(canonicalPath); if (pathURLs == null) { pathURLs = new ArrayList<URL>(); normalized.put(canonicalPath, pathURLs); } pathURLs.add(url); } catch (URISyntaxException e) { String message = "Could not parse classpath resource URI: " + url.toString(); throw new RuntimeException(message, e); } catch (IOException e) { String message = "Could not retrieve canonical path to classpath resource: " + url.toString(); throw new RuntimeException(message, e); } } int foundJars = 0; if (normalized.size() > 1) { StringBuilder sb = new StringBuilder("Multiple ES-Hadoop versions detected in the classpath; please use only one\n"); for (List<URL> pathURLs : normalized.values()) { String path = pathURLs.get(0).toString(); if (path.contains("jar:")) { foundJars++; sb.append(path.replace("!/" + target, "")); sb.append("\n"); } } if (foundJars > 1) { throw new RuntimeException(sb.toString()); } } }
Source:
public float getPrefWidth() { return Editor.getWidth() * this.prefWidth; }

Target:
public float getPrefWidth() { return this.viewport == null ? 0 : this.viewport.x * this.prefWidth; }
Source:
void inject(Map<String, Object> environmentVars) { if (!environmentVars.isEmpty()) { Map<String, Object> replacementEnv = new HashMap<String, Object>(System.getenv()); for (Map.Entry<String, Object> envVar : environmentVars.entrySet()) { String key = envVar.getKey(); Object val = envVar.getValue(); if (val == null) { replacementEnv.remove(envVar.getKey()); if (key == "GEM_PATH" && !environmentVars.containsKey("GEM_HOME")) { replacementEnv.remove("GEM_HOME"); } } else { replacementEnv.put(key, val); if (key == "GEM_PATH" && !environmentVars.containsKey("GEM_HOME")) { String gemHome = val.toString().split(File.pathSeparator)[0]; replacementEnv.put("GEM_HOME", gemHome); } } } config.setEnvironment(replacementEnv); } }

Target:
void inject(Map<String, Object> environmentVars) { if (!environmentVars.isEmpty()) { Map<String, Object> replacementEnv = new HashMap<String, Object>(System.getenv()); for (Map.Entry<String, Object> envVar : environmentVars.entrySet()) { String key = envVar.getKey(); Object val = envVar.getValue(); if (val == null || "".equals(val)) { replacementEnv.remove(envVar.getKey()); if ("GEM_PATH".equals(key) && !environmentVars.containsKey("GEM_HOME")) { replacementEnv.remove("GEM_HOME"); } } else { replacementEnv.put(key, val); if ("GEM_PATH".equals(key) && !environmentVars.containsKey("GEM_HOME")) { String gemHome = val.toString().split(File.pathSeparator)[0]; replacementEnv.put("GEM_HOME", gemHome); } } } config.setEnvironment(replacementEnv); } }
Source:
private void persistFee(ChargeEntity charge, Long feeAmount) { FeeEntity fee = new FeeEntity(charge, feeAmount); feeDao.persist(fee); }

Target:
public void persistFee(ChargeEntity charge, Long feeAmount) { FeeEntity fee = new FeeEntity(charge, feeAmount); feeDao.persist(fee); }
Source:
private void computeUncoveredIntervals(TimelineLookup<String, ServerSelector> timeline) { final List<Interval> uncoveredIntervals = new ArrayList<>(uncoveredIntervalsLimit); boolean uncoveredIntervalsOverflowed = false; for (Interval interval : intervals) { Iterable<TimelineObjectHolder<String, ServerSelector>> lookup = timeline.lookup(interval); long startMillis = interval.getStartMillis(); long endMillis = interval.getEndMillis(); for (TimelineObjectHolder<String, ServerSelector> holder : lookup) { Interval holderInterval = holder.getInterval(); long intervalStart = holderInterval.getStartMillis(); if (!uncoveredIntervalsOverflowed && startMillis != intervalStart) { if (uncoveredIntervalsLimit > uncoveredIntervals.size()) { uncoveredIntervals.add(Intervals.utc(startMillis, intervalStart)); } else { uncoveredIntervalsOverflowed = true; } } startMillis = holderInterval.getEndMillis(); } if (!uncoveredIntervalsOverflowed && startMillis < endMillis) { if (uncoveredIntervalsLimit > uncoveredIntervals.size()) { uncoveredIntervals.add(Intervals.utc(startMillis, endMillis)); } else { uncoveredIntervalsOverflowed = true; } } } if (!uncoveredIntervals.isEmpty()) { responseContext.merge(ResponseContext.Key.UNCOVERED_INTERVALS, uncoveredIntervals); responseContext.merge(ResponseContext.Key.UNCOVERED_INTERVALS_OVERFLOWED, uncoveredIntervalsOverflowed); } }

Target:
private void computeUncoveredIntervals(TimelineLookup<String, ServerSelector> timeline) { final List<Interval> uncoveredIntervals = new ArrayList<>(uncoveredIntervalsLimit); boolean uncoveredIntervalsOverflowed = false; for (Interval interval : intervals) { Iterable<TimelineObjectHolder<String, ServerSelector>> lookup = timeline.lookup(interval); long startMillis = interval.getStartMillis(); long endMillis = interval.getEndMillis(); for (TimelineObjectHolder<String, ServerSelector> holder : lookup) { Interval holderInterval = holder.getInterval(); long intervalStart = holderInterval.getStartMillis(); if (!uncoveredIntervalsOverflowed && startMillis != intervalStart) { if (uncoveredIntervalsLimit > uncoveredIntervals.size()) { uncoveredIntervals.add(Intervals.utc(startMillis, intervalStart)); } else { uncoveredIntervalsOverflowed = true; } } startMillis = holderInterval.getEndMillis(); } if (!uncoveredIntervalsOverflowed && startMillis < endMillis) { if (uncoveredIntervalsLimit > uncoveredIntervals.size()) { uncoveredIntervals.add(Intervals.utc(startMillis, endMillis)); } else { uncoveredIntervalsOverflowed = true; } } } if (!uncoveredIntervals.isEmpty()) { responseContext.add(ResponseContext.Key.UNCOVERED_INTERVALS, uncoveredIntervals); responseContext.add(ResponseContext.Key.UNCOVERED_INTERVALS_OVERFLOWED, uncoveredIntervalsOverflowed); } }
Source:
private FilterSamReads setupProgram(final File inputFile, final File inputSam, final FilterSamReads.Filter filter) throws Exception { final FilterSamReads program = new FilterSamReads(); program.INPUT = inputSam; program.OUTPUT = File.createTempFile("FilterSamReads.output.", ".sam"); program.OUTPUT.deleteOnExit(); program.FILTER = filter; switch (filter) { case includePairedIntervals: program.INTERVAL_LIST = inputFile; break; case includeJavascript: program.JAVASCRIPT_FILE = inputFile; break; case includeReadList: case excludeReadList: program.READ_LIST_FILE = inputFile; break; default: throw new IllegalArgumentException("not configured for filter==" + filter); } return program; }

Target:
private FilterSamReads setupProgram(final File inputFile, final File inputSam, final FilterSamReads.Filter filter) throws Exception { final FilterSamReads program = new FilterSamReads(); program.INPUT = inputSam; program.OUTPUT = File.createTempFile("FilterSamReads.output.", ".sam"); program.OUTPUT.deleteOnExit(); program.FILTER = filter; switch (filter) { case includePairedIntervals: program.INTERVAL_LIST = inputFile; break; case includeJavascript: program.JAVASCRIPT_FILE = inputFile; break; case includeReadList: case excludeReadList: program.READ_LIST_FILE = inputFile; break; default: throw new IllegalArgumentException("Not configured for filter=" + filter); } return program; }
Source:
public void start() throws IOException, InterruptedException { LocalApplicationRunner runner = new LocalApplicationRunner(config); super.start(); MessageConsumer consumeFn = new MessageConsumer(); StreamApplication app = (graph, config) -> { MessageStream<Object> stream = graph.getInputStream(streamId); stream.map(consumeFn); }; runner.run(app); while (consumeFn.eventsConsumed < totalEvents) { Thread.sleep(10); } Instant endTime = Instant.now(); runner.kill(app); System.out.println("\n*******************"); System.out.println(String.format("Started at %s Ending at %s", consumeFn.startTime, endTime)); System.out.println(String.format("Event Rate is %s Messages/Sec", (consumeFn.eventsConsumed * 1000 / Duration.between(consumeFn.startTime , Instant.now()).toMillis()))); System.out.println( "Event Rate is " + consumeFn.eventsConsumed * 1000 / Duration.between(consumeFn.startTime, endTime).toMillis()); System.out.println("*******************\n"); System.exit(0); }

Target:
public void start() throws IOException, InterruptedException { LocalApplicationRunner runner = new LocalApplicationRunner(config); super.start(); MessageConsumer consumeFn = new MessageConsumer(); StreamApplication app = (graph, config) -> { MessageStream<Object> stream = graph.getInputStream(streamId); stream.map(consumeFn); }; runner.run(app); while (consumeFn.getEventsConsumed() < totalEvents) { Thread.sleep(10); } Instant endTime = Instant.now(); runner.kill(app); System.out.println("\n*******************"); System.out.println(String.format("Started at %s Ending at %s ", consumeFn.startTime, endTime)); System.out.println(String.format("Event Rate is %s Messages/Sec ", (consumeFn.getEventsConsumed() * 1000 / Duration.between(consumeFn.startTime, Instant.now()).toMillis()))); System.out.println( "Event Rate is " + consumeFn.getEventsConsumed() * 1000 / Duration.between(consumeFn.startTime, endTime).toMillis()); System.out.println("*******************\n"); System.exit(0); }
Source:
@Override protected List<InclusionExclusionPattern> run() throws Exception { return ParallelTestExecutor.findTestSplits(step.parallelism, build, listener, false); }

Target:
@Override protected List<?> run() throws Exception { if (step.generateInclusions) { return ParallelTestExecutor.findTestSplits(step.parallelism, build, listener, step.generateInclusions); } else { List<List<String>> result = new ArrayList<List<String>>(); for (InclusionExclusionPattern pattern : ParallelTestExecutor.findTestSplits(step.parallelism, build, listener, step.generateInclusions)) { result.add(pattern.getList()); } return result; } }
Source:
protected RenderNode getDeepestLastChild( RenderBox lineBox ) { if ( lineBox.getLastChild() != null && lineBox.getLastChild() instanceof RenderBox ) { return getDeepestLastChild( lineBox ); } return lineBox.getLastChild(); }

Target:
protected RenderNode getDeepestLastChild( RenderBox lineBox ) { if ( lineBox.getLastChild() != null && lineBox.getLastChild() instanceof RenderBox ) { return getDeepestLastChild( (RenderBox) lineBox.getLastChild() ); } return lineBox.getLastChild(); }
Source:
public void displayMessageViewContainer(MessageViewInfo messageViewInfo, final OnRenderingFinishedListener onRenderingFinishedListener, boolean automaticallyLoadPictures, boolean hideUnsignedTextDivider, AttachmentViewCallback attachmentCallback) { this.attachmentCallback = attachmentCallback; resetView(); renderAttachments(messageViewInfo); if (mSavedState != null) { if (mSavedState.showingPictures) { setLoadPictures(true); } mSavedState = null; } String textToDisplay = K9.displayAsPlaintText() ? HtmlConverter.htmlToText(messageViewInfo.text) : messageViewInfo.text; if (textToDisplay != null && !isShowingPictures()) { if (Utility.hasExternalImages(textToDisplay)) { if (automaticallyLoadPictures) { setLoadPictures(true); } else { hasHiddenExternalImages = true; } } } if (textToDisplay == null) { textToDisplay = HtmlConverter.wrapStatusMessage(getContext().getString(R.string.webview_empty_message)); } OnPageFinishedListener onPageFinishedListener = new OnPageFinishedListener() { @Override public void onPageFinished() { onRenderingFinishedListener.onLoadFinished(); } }; displayHtmlContentWithInlineAttachments( textToDisplay, messageViewInfo.attachmentResolver, onPageFinishedListener); if (!TextUtils.isEmpty(messageViewInfo.extraText)) { unsignedTextContainer.setVisibility(View.VISIBLE); unsignedTextDivider.setVisibility(hideUnsignedTextDivider ? View.GONE : View.VISIBLE); unsignedText.setText(messageViewInfo.extraText); } }

Target:
public void displayMessageViewContainer(MessageViewInfo messageViewInfo, final OnRenderingFinishedListener onRenderingFinishedListener, boolean automaticallyLoadPictures, boolean hideUnsignedTextDivider, AttachmentViewCallback attachmentCallback) { this.attachmentCallback = attachmentCallback; resetView(); renderAttachments(messageViewInfo); if (mSavedState != null) { if (mSavedState.showingPictures) { setLoadPictures(true); } mSavedState = null; } String textToDisplay; boolean isPlainText = K9.displayAsPlaintText(); if(!isPlainText) textToDisplay = messageViewInfo.text; else textToDisplay = ""; if (textToDisplay != null && !isShowingPictures()) { if (Utility.hasExternalImages(textToDisplay)) { if (automaticallyLoadPictures) { setLoadPictures(true); } else { hasHiddenExternalImages = true; } } } if (textToDisplay == null) { textToDisplay = HtmlConverter.wrapStatusMessage(getContext().getString(R.string.webview_empty_message)); } OnPageFinishedListener onPageFinishedListener = new OnPageFinishedListener() { @Override public void onPageFinished() { onRenderingFinishedListener.onLoadFinished(); } }; displayHtmlContentWithInlineAttachments( textToDisplay, messageViewInfo.attachmentResolver, onPageFinishedListener); if(isPlainText) { plainTextContainer.setVisibility(View.VISIBLE); plainTextDivider.setVisibility(View.VISIBLE); plainText.setText(messageViewInfo.plainText); } if (!TextUtils.isEmpty(messageViewInfo.extraText)) { unsignedTextContainer.setVisibility(View.VISIBLE); unsignedTextDivider.setVisibility(hideUnsignedTextDivider ? View.GONE : View.VISIBLE); unsignedText.setText(messageViewInfo.extraText); } }
Source:
public void execute() { List<QuotaBalanceVO> quotaUsage = _responseBuilder.getQuotaBalance(this); QuotaBalanceResponse response; if (getEndDate() == null) { response = _responseBuilder.createQuotaLastBalanceResponse(quotaUsage, startDate); } else { response = _responseBuilder.createQuotaBalanceResponse(quotaUsage, startDate, endDate); } response.setResponseName(getCommandName()); setResponseObject(response); }

Target:
public void execute() { List<QuotaBalanceVO> quotaUsage = _responseBuilder.getQuotaBalance(this); QuotaBalanceResponse response; if (getEndDate() == null) { response = _responseBuilder.createQuotaLastBalanceResponse(quotaUsage, getStartDate()); } else { response = _responseBuilder.createQuotaBalanceResponse(quotaUsage, getStartDate(), getEndDate()); } response.setResponseName(getCommandName()); setResponseObject(response); }