auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void ensureAllSet(EventTester tester) { String[] unfiredIds = tester.getAttIds(false); if (unfiredIds.length > 0) { StringBuilder msg = new StringBuilder("No event fired:" + unfiredIds); for (int i = 0; i < unfiredIds.length; i++) { msg.append(' ' + unfiredIds[i]); } fail(msg.toString()); } }

Target:
private void ensureAllSet(EventTester tester) { String[] unfiredIds = tester.getAttIds(false); if (unfiredIds.length > 0) { StringBuilder msg = new StringBuilder("No event fired:").append(unfiredIds); for (int i = 0; i < unfiredIds.length; i++) { msg.append(' ').append(unfiredIds[i]); } fail(msg.toString()); } }
Source:
public static ExecutorApiClient getInstance() { if (null == instance) { synchronized (ExecutorApiClient.class) { if (null == instance) { instance = new ExecutorApiClient(); } } } return instance; }

Target:
public static ExecutorApiClient getInstance() { return instance; }
Source:
public abstract void append(String tag, long timestamp, Map<String, Object> data) throws IOException; public abstract void append(String tag, EventTime timestamp, Map<String, Object> data) throws IOException; public abstract void appendMessagePackMapValue(String tag, long timestamp, byte[] mapValue, int offset, int len) throws IOException; public abstract void appendMessagePackMapValue(String tag, EventTime timestamp, byte[] mapValue, int offset, int len) throws IOException; public abstract void appendMessagePackMapValue(String tag, long timestamp, ByteBuffer mapValue) throws IOException; public abstract void appendMessagePackMapValue(String tag, EventTime timestamp, ByteBuffer mapValue) throws IOException; protected abstract void loadBufferFromFile(List<String> params, FileChannel channel); protected abstract void saveAllBuffersToFile() throws IOException; protected void saveBuffer(List<String> params, ByteBuffer buffer) { if (fileBackup == null) { return; } LOG.debug("Saving buffer: params={}, buffer={}", params, buffer); fileBackup.saveBuffer(params, buffer); }

Target:
public abstract void append(String tag, long timestamp, Map<String, Object> data) throws IOException; public abstract void append(String tag, EventTime timestamp, Map<String, Object> data) throws IOException; public abstract void appendMessagePackMapValue(String tag, long timestamp, byte[] mapValue, int offset, int len) throws IOException; public abstract void appendMessagePackMapValue(String tag, EventTime timestamp, byte[] mapValue, int offset, int len) throws IOException; public abstract void appendMessagePackMapValue(String tag, long timestamp, ByteBuffer mapValue) throws IOException; public abstract void appendMessagePackMapValue(String tag, EventTime timestamp, ByteBuffer mapValue) throws IOException; protected abstract void loadBufferFromFile(List<String> params, FileChannel channel); protected abstract void saveAllBuffersToFile() throws IOException; protected void saveBuffer(List<String> params, ByteBuffer buffer) { if (fileBackup == null) { return; } LOG.info("Saving buffer: params={}, buffer={}", params, buffer); fileBackup.saveBuffer(params, buffer); }
Source:
private ValueProcessor getValueProcessor(DatasourceLayer layer) { if(layer.getConfig() == null) { return DEFAULT_PROCESSOR; } String className = layer.getConfig("valueProcessor"); if(className == null) { return DEFAULT_PROCESSOR; } ValueProcessor processor = processors.get(className); if(processor != null) { return processor; } try { final Class clazz = Class.forName(className); processor = (ValueProcessor) clazz.newInstance(); processors.put(className, processor); return processor; } catch (Exception e) { LOG.error(e, "Error creating ValueProcessor for plugin id:", config.getId(), " - class:", className); } return DEFAULT_PROCESSOR; }

Target:
private ValueProcessor getValueProcessor(DatasourceLayer layer) { String className = layer.getConfig("valueProcessor"); if(className == null) { return DEFAULT_PROCESSOR; } ValueProcessor processor = processors.get(className); if(processor != null) { return processor; } try { final Class clazz = Class.forName(className); if(!ValueProcessor.class.isAssignableFrom(clazz)) { LOG.warn("Invalid ValueProcessor configured for datasource id:", config.getId(), " - class:", className); return DEFAULT_PROCESSOR; } processor = (ValueProcessor) clazz.newInstance(); processors.put(className, processor); return processor; } catch (Exception e) { LOG.error(e, "Error creating ValueProcessor for plugin id:", config.getId(), " - class:", className); } return DEFAULT_PROCESSOR; }
Source:
public void testSaveByPressingEnter() { presenter.onKeyPress(12, false, MODIFIED_NAME); verifyNameNotSaved(); presenter.onKeyPress(13, false, MODIFIED_NAME); verifyNameSaved(); }

Target:
public void testSaveByPressingEnter() { presenter.onKeyPress(12, false, MODIFIED_NAME); verifyNameNotSaved(); presenter.onKeyPress(KeyCodes.KEY_ENTER, false, MODIFIED_NAME); verifyNameSaved(); }
Source:
public String process(String markupContent) { Map<String, String> attributes = new HashMap<String, String>(); StringBuilder processedMarkup = new StringBuilder(markupContent.length()); LocationTrackingReader reader = new LocationTrackingReader(new StringReader(markupContent)); String line; try { line = reader.readLine(); while (line != null) { Matcher matcher = ATTRIBUTE_PATTERN.matcher(line); if (matcher.matches()) { String key = matcher.group(1); String value = matcher.group(2); if (value != null) { value = value.trim(); } attributes.put(key, value); } else { Matcher attrref = ATTRIBUTE_TOKEN_PATTERN.matcher(line); int offset = 0; while (attrref.find()) { String postfix = line.substring(offset, attrref.start()); if (postfix.endsWith("\\")) { processedMarkup.append(postfix.substring(0, postfix.length() - 1)); offset = attrref.start(); } else { processedMarkup.append(postfix); String key = attrref.group(1); String value = attributes.get(key); if (value == null) { value = attrref.group(0); } processedMarkup.append(value); offset = attrref.end(); } } if (offset < line.length()) { processedMarkup.append(line.substring(offset)); } processedMarkup.append("\n"); } line = reader.readLine(); } reader.close(); } catch (IOException e) { throw new IllegalStateException(e); } return processedMarkup.toString(); }

Target:
public String process(String markupContent) { Map<String, String> attributes = new HashMap<String, String>(); StringBuilder processedMarkup = new StringBuilder(markupContent.length()); LocationTrackingReader reader = new LocationTrackingReader(new StringReader(markupContent)); String line; try { line = reader.readLine(); while (line != null) { Matcher matcher = ATTRIBUTE_PATTERN.matcher(line); if (matcher.matches()) { String key = matcher.group(1); String value = matcher.group(2); if (value != null) { value = value.trim(); } attributes.put(key, value); } else { Matcher attributesRef = ATTRIBUTE_TOKEN_PATTERN.matcher(line); int offset = 0; while (attributesRef.find()) { String postfix = line.substring(offset, attributesRef.start()); if (postfix.endsWith("\\")) { processedMarkup.append(postfix.substring(0, postfix.length() - 1)); offset = attributesRef.start(); } else { processedMarkup.append(postfix); String key = attributesRef.group(1); String value = attributes.get(key); if (value == null) { value = attributesRef.group(0); } processedMarkup.append(value); offset = attributesRef.end(); } } if (offset < line.length()) { processedMarkup.append(line.substring(offset)); } processedMarkup.append("\n"); } line = reader.readLine(); } reader.close(); } catch (IOException e) { throw new IllegalStateException(e); } return processedMarkup.toString(); }
Source:
public Builder addFile(String fileUrl) { String id = downloadBatchId.rawId() + fileUrl; DownloadFileId downloadFileId = DownloadFileIdCreator.createFrom(id); fileUrls.put(downloadFileId, fileUrl); return this; }

Target:
public Builder addFile(String fileUrl) { String rawId = downloadBatchId.rawId() + fileUrl; DownloadFileId downloadFileId = DownloadFileIdCreator.createFrom(rawId); fileUrls.put(downloadFileId, fileUrl); return this; }
Source:
public void findChildrenLeaf() { final CategoryTree tree = createAbcCategoryTree(); final Category category = tree.findById("B-1-1").get(); final List<Category> children = tree.findChildren(category); assertThat(children).as("leaf notes produce empty lists").isEmpty(); }

Target:
public void findChildrenLeaf() { final CategoryTree tree = createAbcCategoryTree(); final Category category = tree.findById("B-1-1").get(); final List<Category> children = tree.findChildren(category); assertThat(children).as("leaf nodes produce empty lists").isEmpty(); }
Source:
public void doHashtagsChangedHook(Change change, Account account, Set<String> added, Set<String> removed, Set<String> hashtags, ReviewDb db) throws OrmException { HashtagsChangedEvent event = new HashtagsChangedEvent(); AccountState owner = accountCache.get(change.getOwner()); event.change = eventFactory.asChangeAttribute(change); event.editor = eventFactory.asAccountAttribute(account); if (hashtags.size() > 0) { event.hashtags = new String[hashtags.size()]; int i = 0; for (String hashtag : hashtags) { event.hashtags[i++] = hashtag; } } if (added != null && added.size() > 0) { event.added = new String[added.size()]; int i = 0; for (String hashtag : added) { event.added[i++] = hashtag; } } if (removed != null && removed.size() > 0) { event.removed = new String[removed.size()]; int i = 0; for (String hashtag : removed) { event.removed[i++] = hashtag; } } fireEvent(change, event, db); final List<String> args = new ArrayList<>(); addArg(args, "--change", event.change.id); addArg(args, "--change-owner", getDisplayName(owner.getAccount())); addArg(args, "--project", event.change.project); addArg(args, "--branch", event.change.branch); addArg(args, "--editor", getDisplayName(account)); if (hashtags != null) { for (String hashtag : hashtags) { addArg(args, "--hashtag", hashtag); } } if (added != null) { for (String hashtag : added) { addArg(args, "--added", hashtag); } } if (removed != null) { for (String hashtag : removed) { addArg(args, "--removed", hashtag); } } runHook(change.getProject(), hashtagsChangedHook, args); }

Target:
public void doHashtagsChangedHook(Change change, Account account, Set<String> added, Set<String> removed, Set<String> hashtags, ReviewDb db) throws OrmException { HashtagsChangedEvent event = new HashtagsChangedEvent(); AccountState owner = accountCache.get(change.getOwner()); event.change = eventFactory.asChangeAttribute(change); event.editor = eventFactory.asAccountAttribute(account); event.hashtags = hashtagArray(hashtags); event.added = hashtagArray(added); event.removed = hashtagArray(removed); fireEvent(change, event, db); final List<String> args = new ArrayList<>(); addArg(args, "--change", event.change.id); addArg(args, "--change-owner", getDisplayName(owner.getAccount())); addArg(args, "--project", event.change.project); addArg(args, "--branch", event.change.branch); addArg(args, "--editor", getDisplayName(account)); if (hashtags != null) { for (String hashtag : hashtags) { addArg(args, "--hashtag", hashtag); } } if (added != null) { for (String hashtag : added) { addArg(args, "--added", hashtag); } } if (removed != null) { for (String hashtag : removed) { addArg(args, "--removed", hashtag); } } runHook(change.getProject(), hashtagsChangedHook, args); }
Source:
private String getStringFromResultSet(ResultSet rs) throws SQLException, UnsupportedEncodingException { ResultSetMetaData meta = rs.getMetaData(); StringBuilder sb = new StringBuilder(); int numColumns = meta.getColumnCount(); for (int i = 1; i <= numColumns; i++) { sb.append(meta.getColumnLabel(i)); if (i==numColumns){ sb.append('\n'); } else { sb.append('\t'); } } JMeterVariables jmvars = getThreadContext().getVariables(); String[] varNames = getVariableNames().split(COMMA); String currentResultVariable = getResultVariable().trim(); List<Map<String, Object> > results = null; if(!currentResultVariable.isEmpty()) { results = new ArrayList<>(); jmvars.putObject(currentResultVariable, results); } int j = 0; int k = getIntegerResultSetMaxRows(); if (k < 0) { while (rs.next()) { j = processRow(rs, meta, sb, numColumns, jmvars, varNames, results, j); } } else { while (j < k && rs.next()) { j = processRow(rs, meta, sb, numColumns, jmvars, varNames, results, j); } } for (String varName : varNames) { String name = varName.trim(); if (name.length() > 0 && jmvars != null) { final String varCount = name + "_#"; String prevCount = jmvars.get(varCount); if (prevCount != null) { int prev = Integer.parseInt(prevCount); for (int n = j + 1; n <= prev; n++) { jmvars.remove(name + UNDERSCORE + n); } } jmvars.put(varCount, Integer.toString(j)); } } return sb.toString(); }

Target:
private String getStringFromResultSet(ResultSet rs) throws SQLException, UnsupportedEncodingException { ResultSetMetaData meta = rs.getMetaData(); StringBuilder sb = new StringBuilder(); int numColumns = meta.getColumnCount(); for (int i = 1; i <= numColumns; i++) { sb.append(meta.getColumnLabel(i)); if (i==numColumns){ sb.append('\n'); } else { sb.append('\t'); } } JMeterVariables jmvars = getThreadContext().getVariables(); String[] varNames = getVariableNames().split(COMMA); String currentResultVariable = getResultVariable().trim(); List<Map<String, Object> > results = null; if(!currentResultVariable.isEmpty()) { results = new ArrayList<>(); jmvars.putObject(currentResultVariable, results); } int currentIterationIndex = 0; int resultSetMaxRows = getIntegerResultSetMaxRows(); if (resultSetMaxRows < 0) { while (rs.next()) { currentIterationIndex = processRow(rs, meta, sb, numColumns, jmvars, varNames, results, currentIterationIndex); } } else { while (currentIterationIndex < resultSetMaxRows && rs.next()) { currentIterationIndex = processRow(rs, meta, sb, numColumns, jmvars, varNames, results, currentIterationIndex); } } for (String varName : varNames) { String name = varName.trim(); if (name.length() > 0 && jmvars != null) { final String varCount = name + "_#"; String prevCount = jmvars.get(varCount); if (prevCount != null) { int prev = Integer.parseInt(prevCount); for (int n = currentIterationIndex + 1; n <= prev; n++) { jmvars.remove(name + UNDERSCORE + n); } } jmvars.put(varCount, Integer.toString(currentIterationIndex)); } } return sb.toString(); }
Source:
public static Trades adaptTrades(CoinbaseProTrade[] coinbaseExTrades, CurrencyPair currencyPair) { List<Trade> trades = new ArrayList<>(coinbaseExTrades.length); for (int i = 0; i < coinbaseExTrades.length; i++) { CoinbaseProTrade trade = coinbaseExTrades[i]; OrderType type = trade.getSide().equals("sell") ? OrderType.BID : OrderType.ASK; Trade t = new Trade( type, trade.getSize(), currencyPair, trade.getPrice(), parseDate(trade.getTimestamp()), String.valueOf(trade.getTradeId())); t.setMaker_order_id(trade.getMakerOrderId()); t.setTaker_order_id(trade.getTakerOrderId()); trades.add(t); } return new Trades(trades, coinbaseExTrades[0].getTradeId(), TradeSortType.SortByID); }

Target:
public static Trades adaptTrades(CoinbaseProTrade[] coinbaseExTrades, CurrencyPair currencyPair) { List<Trade> trades = new ArrayList<>(coinbaseExTrades.length); for (int i = 0; i < coinbaseExTrades.length; i++) { CoinbaseProTrade trade = coinbaseExTrades[i]; OrderType type = trade.getSide().equals("sell") ? OrderType.BID : OrderType.ASK; Trade t = new Trade( type, trade.getSize(), currencyPair, trade.getPrice(), parseDate(trade.getTimestamp()), String.valueOf(trade.getTradeId())); t.setMakerOrderId(trade.getMakerOrderId()); t.setTakerOrderId(trade.getTakerOrderId()); trades.add(t); } return new Trades(trades, coinbaseExTrades[0].getTradeId(), TradeSortType.SortByID); }
Source:
public void setEndDate(Date endDate) { this.endDate = endDate; }

Target:
public void setEndDate(Date endDate) { this.endDate = endDate == null ? null : new Date(endDate.getTime()); }
Source:
protected boolean canHandleMetacard(Metacard metacard) { return !StringUtils.isEmpty(metacard.getLocation()); }

Target:
protected boolean canHandleMetacard(Metacard metacard) { return StringUtils.isNotBlank(metacard.getLocation()); }
Source:
public void validate(PlanNode plan, Session session, Metadata metadata, SqlParser sqlParser, Map<Symbol, Type> types) { plan.accept(new SimplePlanVisitor<Set<Filter>>() { @Override public Void visitJoin(JoinNode node, Set<Filter> expected) { ImmutableSet<Filter> currentJoinDynamicFilters = node.getDynamicFilterAssignments() .entrySet() .stream() .map(assignment -> new Filter(node.getId().toString(), assignment.getKey().getName())) .collect(toImmutableSet()); expected.addAll(currentJoinDynamicFilters); node.getLeft().accept(this, expected); checkState(intersection(currentJoinDynamicFilters, expected).isEmpty()); node.getRight().accept(this, expected); return null; } @Override public Void visitExchange(ExchangeNode node, Set<Filter> expected) { Set<Filter> filtersLeft = null; for (PlanNode source : node.getSources()) { Set<Filter> copy = new HashSet<>(expected); source.accept(this, copy); if (filtersLeft == null) { filtersLeft = copy; } else { checkState(filtersLeft.equals(copy), "filters does not match: %s != %s", filtersLeft, copy); } } if (filtersLeft != null) { expected.clear(); expected.addAll(filtersLeft); } return null; } @Override public Void visitFilter(FilterNode node, Set<Filter> expected) { extractDynamicFilters(node.getPredicate()) .getDynamicFilters() .stream() .map(dynamicFilter -> new Filter(dynamicFilter.getTupleDomainSourceId(), dynamicFilter.getTupleDomainName())) .forEach(expected::remove); return node.getSource().accept(this, expected); } }, new HashSet<>()); }

Target:
public void validate(PlanNode plan, Session session, Metadata metadata, SqlParser sqlParser, Map<Symbol, Type> types) { plan.accept(new SimplePlanVisitor<Set<Filter>>() { @Override public Void visitJoin(JoinNode node, Set<Filter> expected) { ImmutableSet<Filter> currentJoinDynamicFilters = node.getDynamicFilterAssignments() .entrySet() .stream() .map(assignment -> new Filter(node.getId().toString(), assignment.getKey().getName())) .collect(toImmutableSet()); expected.addAll(currentJoinDynamicFilters); node.getLeft().accept(this, expected); checkState(intersection(currentJoinDynamicFilters, expected).isEmpty()); node.getRight().accept(this, expected); return null; } @Override public Void visitExchange(ExchangeNode node, Set<Filter> expected) { Set<Filter> filtersLeft = null; for (PlanNode source : node.getSources()) { Set<Filter> copy = new HashSet<>(expected); source.accept(this, copy); if (filtersLeft == null) { filtersLeft = copy; } else { checkState(filtersLeft.equals(copy), "filters do not match: %s != %s", filtersLeft, copy); } } if (filtersLeft != null) { expected.clear(); expected.addAll(filtersLeft); } return null; } @Override public Void visitFilter(FilterNode node, Set<Filter> expected) { extractDynamicFilters(node.getPredicate()) .getDynamicFilters() .stream() .map(dynamicFilter -> new Filter(dynamicFilter.getTupleDomainSourceId(), dynamicFilter.getTupleDomainName())) .forEach(expected::remove); return node.getSource().accept(this, expected); } }, new HashSet<>()); }
Source:
public void setHitsPerPage(int hitsPerPage) throws IllegalArgumentException { if (hitsPerPage < 0) { throw new IllegalArgumentException( String.format("Invalid value for histPerPage \"%d\"", hitsPerPage)); } this.hitsPerPage = hitsPerPage; }

Target:
public void setHitsPerPage(int hitsPerPage) throws IllegalArgumentException { if (hitsPerPage < 0) { throw new IllegalArgumentException( String.format(NEGATIVE_NUMBER_ERROR, "hitsPerPage", hitsPerPage)); } this.hitsPerPage = hitsPerPage; }
Source:
public BigtableBufferedMutator( Configuration configuration, TableName tableName, int maxInflightRpcs, long maxHeapSize, BigtableClient client, BigtableOptions options, ExecutorService executorService, BufferedMutator.ExceptionListener listener) { this.sizeManager = new HeapSizeManager(maxHeapSize, maxInflightRpcs); this.configuration = configuration; this.tableName = tableName; this.exceptionListener = listener; InetAddress host = options.getDataHost(); this.host = host == null ? null : host.toString(); DeleteAdapter deleteAdapter = new DeleteAdapter(); PutAdapter putAdapter = new PutAdapter(configuration); ScanAdapter scanAdapter = new ScanAdapter(FilterAdapter.buildAdapter()); GetAdapter getAdapter = new GetAdapter(scanAdapter); RowMutationsAdapter rowMutationsAdapter = new RowMutationsAdapter( new MutationAdapter( deleteAdapter, putAdapter, new UnsupportedOperationAdapter<Increment>("increment"), new UnsupportedOperationAdapter<Append>("append"))); ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService); batchExecutor = new BatchExecutor( client, options, TableMetadataSetter.from(tableName, options), listeningExecutorService, getAdapter, putAdapter, deleteAdapter, rowMutationsAdapter, new AppendAdapter(), new IncrementAdapter(), new RowAdapter()); }

Target:
public BigtableBufferedMutator( Configuration configuration, TableName tableName, int maxInflightRpcs, long maxHeapSize, BigtableClient client, BigtableOptions options, ExecutorService executorService, BufferedMutator.ExceptionListener listener) { this.sizeManager = new HeapSizeManager(maxHeapSize, maxInflightRpcs); this.configuration = configuration; this.tableName = tableName; this.exceptionListener = listener; this.host = options.getDataHost().toString(); DeleteAdapter deleteAdapter = new DeleteAdapter(); PutAdapter putAdapter = new PutAdapter(configuration); ScanAdapter scanAdapter = new ScanAdapter(FilterAdapter.buildAdapter()); GetAdapter getAdapter = new GetAdapter(scanAdapter); RowMutationsAdapter rowMutationsAdapter = new RowMutationsAdapter( new MutationAdapter( deleteAdapter, putAdapter, new UnsupportedOperationAdapter<Increment>("increment"), new UnsupportedOperationAdapter<Append>("append"))); ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService); batchExecutor = new BatchExecutor( client, options, TableMetadataSetter.from(tableName, options), listeningExecutorService, getAdapter, putAdapter, deleteAdapter, rowMutationsAdapter, new AppendAdapter(), new IncrementAdapter(), new RowAdapter()); }
Source:
private Flux<Shard> getShards(JsonNode node) { JsonNode status = node.get(STATUS); if (!status.asText().equals(FINALIZED)) { return Flux.empty(); } List<Shard> shards = new ArrayList<>(); boolean validShard = false; for (JsonNode shard : node.withArray(CHUNK_FILE_PATHS)) { String shardPath = shard.asText().substring(BlobChangefeedAsyncClient.CHANGEFEED_CONTAINER_NAME.length() + 1); if (userCursor == null) { validShard = true; } else { if (shardPath.equals(userCursor.getShardPath())) { validShard = true; } } if (validShard) { shards.add(shardFactory.getShard(shardPath, cfCursor.toShardCursor(shardPath), userCursor)); } } return Flux.fromIterable(shards); }

Target:
private Flux<Shard> getShards(JsonNode node) { JsonNode status = node.get(STATUS); if (!FINALIZED.equals(status.asText())) { return Flux.empty(); } List<Shard> shards = new ArrayList<>(); boolean validShard = false; for (JsonNode shard : node.withArray(CHUNK_FILE_PATHS)) { String shardPath = shard.asText().substring(BlobChangefeedClientBuilder.CHANGEFEED_CONTAINER_NAME.length() + 1); if (userCursor == null) { validShard = true; } else { if (shardPath.equals(userCursor.getShardPath())) { validShard = true; } } if (validShard) { shards.add(shardFactory.getShard(shardPath, cfCursor.toShardCursor(shardPath), userCursor)); } } return Flux.fromIterable(shards); }
Source:
public void setUp() throws Exception { super.setUp(); LOG.info("setUp"); zkUtil.createBKEnsemble("/" + runtime.getMethodName()); rm = new ZKRegistrationManager(); }

Target:
public void setUp() throws Exception { super.setUp(); zkUtil.createBKEnsemble("/" + runtime.getMethodName()); rm = new ZKRegistrationManager(); }
Source:
protected JsonParser createParser(Object obj) throws IOException { Data data = (Data) obj; return factory.createParser(data.toByteArray(), HEAP_DATA_OVERHEAD + 4, data.dataSize() - 4); }

Target:
protected JsonParser createParser(Object obj) throws IOException { Data data = (Data) obj; return factory.createParser(data.toByteArray(), HEAP_DATA_OVERHEAD + UTF_CHARACTER_COUNT_FIELD_SIZE, data.dataSize() - UTF_CHARACTER_COUNT_FIELD_SIZE); }
Source:
private Optional<Map<String, Object>> createAmendment(Site site, Map<String, ?> relatedArticle) { String relationshipType = (String) relatedArticle.get("type"); AmendmentType amendmentType = AmendmentType.BY_RELATIONSHIP_TYPE.get(relationshipType); if (amendmentType == null) return Optional.empty(); String doi = (String) relatedArticle.get("doi"); ArticlePointer amendmentId; Map<String, Object> amendment; Map<String, ?> authors; try { amendmentId = factory.articleResolutionService.toIngestion(RequestedDoiVersion.of(doi)); amendment = (Map<String, Object>) factory.articleApi.requestObject(amendmentId.asApiAddress().build(), Map.class); authors = factory.articleApi.requestObject(amendmentId.asApiAddress().addToken("authors").build(), Map.class); } catch (IOException e) { throw new RuntimeException(e); } amendment.putAll(authors); if (amendmentType != AmendmentType.CORRECTION) { RenderContext renderContext = new RenderContext(site, RequestedDoiVersion.ofIngestion(amendmentId.getDoi(), amendmentId.getIngestionNumber())); String body; try { body = getAmendmentBody(renderContext); } catch (IOException e) { throw new RuntimeException("Could not get body for amendment: " + doi, e); } amendment.put("body", body); } amendment.put("type", amendmentType.getLabel()); return Optional.of(amendment); }

Target:
private Map<String, Object> createAmendment(Site site, Map<String, ?> relatedArticle) { AmendmentType amendmentType = getAmendmentType(relatedArticle).orElseThrow(IllegalArgumentException::new); String doi = (String) relatedArticle.get("doi"); ArticlePointer amendmentId; Map<String, Object> amendment; Map<String, ?> authors; try { amendmentId = factory.articleResolutionService.toIngestion(RequestedDoiVersion.of(doi)); amendment = (Map<String, Object>) factory.articleApi.requestObject(amendmentId.asApiAddress().build(), Map.class); authors = factory.articleApi.requestObject(amendmentId.asApiAddress().addToken("authors").build(), Map.class); } catch (IOException e) { throw new RuntimeException(e); } amendment.putAll(authors); if (amendmentType != AmendmentType.CORRECTION) { RenderContext renderContext = new RenderContext(site, RequestedDoiVersion.ofIngestion(amendmentId.getDoi(), amendmentId.getIngestionNumber())); String body; try { body = getAmendmentBody(renderContext); } catch (IOException e) { throw new RuntimeException("Could not get body for amendment: " + doi, e); } amendment.put("body", body); } amendment.put("type", amendmentType.getLabel()); return amendment; }
Source:
private Resource makeDepositRecord(Resource deposit, Map<String, String> status) { Model aipModel = ModelFactory.createDefaultModel(); Resource aipObjResc = aipModel.createResource(deposit.getURI()); String filename = status.get(DepositField.fileName.name()); String title = "Deposit record" + (filename == null ? "" : " for " + filename); aipObjResc.addProperty(DcElements.title, title); aipObjResc.addProperty(Rdfs.type, Cdr.DepositRecord); String method = status.get(DepositField.depositMethod.name()); if (method != null) { aipObjResc.addProperty(Cdr.depositMethod, method); } String onBehalfOf = status.get(DepositField.depositorName.name()); if (onBehalfOf != null) { aipObjResc.addProperty(Cdr.depositedOnBehalfOf, onBehalfOf); } String staffOnly = status.get(DepositField.staffOnly.name()); if (staffOnly != null) { aipObjResc.addProperty(Cdr.staffOnly, staffOnly); } String depositPackageType = status.get(DepositField.packagingType.name()); if (depositPackageType != null) { aipObjResc.addProperty(Cdr.depositPackageType, depositPackageType); } String depositPackageProfile = status.get(DepositField.packageProfile.name()); if (depositPackageProfile != null) { aipObjResc.addProperty(Cdr.depositPackageProfile, depositPackageProfile); } return aipObjResc; }

Target:
private Resource makeDepositRecord(Resource deposit, Map<String, String> status) { Model aipModel = ModelFactory.createDefaultModel(); Resource aipObjResc = aipModel.createResource(deposit.getURI()); String filename = status.get(DepositField.fileName.name()); String title = "Deposit record" + (filename == null ? "" : " for " + filename); aipObjResc.addProperty(DcElements.title, title); aipObjResc.addProperty(Rdfs.type, Cdr.DepositRecord); String method = status.get(DepositField.depositMethod.name()); if (method != null) { aipObjResc.addProperty(Cdr.depositMethod, method); } String onBehalfOf = status.get(DepositField.depositorName.name()); if (onBehalfOf != null) { aipObjResc.addProperty(Cdr.depositedOnBehalfOf, onBehalfOf); } String depositPackageType = status.get(DepositField.packagingType.name()); if (depositPackageType != null) { aipObjResc.addProperty(Cdr.depositPackageType, depositPackageType); } String depositPackageProfile = status.get(DepositField.packageProfile.name()); if (depositPackageProfile != null) { aipObjResc.addProperty(Cdr.depositPackageProfile, depositPackageProfile); } return aipObjResc; }
Source:
private void validateInclude() throws MojoFailureException { ArrayList<String> includeValues; List<String> includeStrings; if (include != null && !include.isEmpty()) { include = include.trim(); includeStrings = Arrays.asList(include.split(",")); includeValues = new ArrayList<String>(includeStrings); for (int i = 0; i < includeValues.size(); i++) { String value = includeValues.get(i); includeValues.set(i, value.trim()); } } else { includeValues = new ArrayList<String>(); } if (packageType.equals("jar")) { if (includeValues.contains("usr") || includeValues.contains("wlp")) { throw new MojoFailureException("Package type jar cannot be used with `usr` or `wlp`."); } if (!includeValues.contains("runnable")) { includeValues.add("runnable"); } } include = String.join(",", includeValues); }

Target:
private void validateInclude() throws MojoFailureException { ArrayList<String> includeValues; List<String> includeStrings; if (include != null && !include.isEmpty()) { include = include.trim(); includeStrings = Arrays.asList(include.split(",")); includeValues = new ArrayList<String>(includeStrings); for (int i = 0; i < includeValues.size(); i++) { String value = includeValues.get(i); includeValues.set(i, value.trim()); } } else { includeValues = new ArrayList<String>(); } if (packageType.equals("jar")) { if (includeValues.contains("usr") || includeValues.contains("wlp")) { throw new MojoFailureException("Package type jar cannot be used with `usr` or `wlp`."); } if (!includeValues.contains("runnable")) { includeValues.add("runnable"); } } if (includeValues.size() > 0) { include = String.join(",", includeValues); } }
Source:
public org.jclouds.domain.Location apply(final Location location) { final LocationBuilder builder = new LocationBuilder(); builder.id(location.name()); builder.description(location.displayName()); builder.parent(getOnlyElement(justProvider.get())); builder.scope(LocationScope.ZONE); final Region region = Region.byName(location.displayName()); if (region != null) { builder.iso3166Codes(ImmutableSet.of(region.iso3166Code())); } return builder.build(); }

Target:
public org.jclouds.domain.Location apply(final Location location) { final LocationBuilder builder = new LocationBuilder(); builder.id(location.name()); builder.description(location.displayName()); builder.parent(getOnlyElement(justProvider.get())); builder.scope(LocationScope.REGION); final Region region = Region.byName(location.displayName()); if (region != null) { builder.iso3166Codes(ImmutableSet.of(region.iso3166Code())); } return builder.build(); }
Source:
public static void assertCompany(Company company) { assertBaseCompany(company, true); assertThat(company.headquarters).isNotNull(); assertThat(company.homepage).isNotNull(); assertThat(company.origin_country).isNotEmpty(); assertThat(company.origin_country).isNotEmpty(); if (company.parent_company != null) assertBaseCompany(company.parent_company, true); }

Target:
public static void assertCompany(Company company) { assertBaseCompany(company, true); assertThat(company.headquarters).isNotNull(); assertThat(company.homepage).isNotNull(); assertThat(company.origin_country).isNotEmpty(); if (company.parent_company != null) assertBaseCompany(company.parent_company, true); }
Source:
public void setUp() throws Exception { Script script = BrickTestUtils.createProjectAndGetStartScript("PhiroSeekBarColorBrickTest"); script.addBrick(new PhiroRGBLightBrick(PhiroRGBLightBrick.Eye.BOTH, INIT_COLOR_VALUE, INIT_COLOR_VALUE, INIT_COLOR_VALUE)); baseActivityTestRule.launchActivity(null); }

Target:
public void setUp() throws Exception { Script script = BrickTestUtils.createProjectAndGetStartScript("PhiroSeekBarColorBrickTest"); script.addBrick(new PhiroRGBLightBrick(PhiroRGBLightBrick.Eye.BOTH, INIT_COLOR_VALUE, INIT_COLOR_VALUE, INIT_COLOR_VALUE)); baseActivityTestRule.launchActivity(); }
Source:
private static void addInsertNonDirectoryInformation(Path p, FileSystem fileSystem, InsertEventRequestData insertData) throws IOException { insertData.addToFilesAdded(p.toString()); FileChecksum cksum = fileSystem.getFileChecksum(p); String acidDir = AcidUtils.getFirstLevelAcidDir(p); if (cksum != null) { String checksumString = StringUtils.byteToHexString(cksum.getBytes(), 0, cksum.getLength()); insertData.addToFilesAddedChecksum(checksumString); } else { insertData.addToFilesAddedChecksum(""); } if (acidDir != null) { insertData.addToSubDirectoryList(acidDir); } }

Target:
private static void addInsertNonDirectoryInformation(Path p, FileSystem fileSystem, InsertEventRequestData insertData) throws IOException { insertData.addToFilesAdded(p.toString()); FileChecksum cksum = fileSystem.getFileChecksum(p); String acidDirPath = AcidUtils.getFirstLevelAcidDirPath(p.getParent(), fileSystem); if (cksum != null) { String checksumString = StringUtils.byteToHexString(cksum.getBytes(), 0, cksum.getLength()); insertData.addToFilesAddedChecksum(checksumString); } else { insertData.addToFilesAddedChecksum(""); } if (acidDirPath != null) { insertData.addToSubDirectoryList(acidDirPath); } }
Source:
synchronized void submitDecryptionTasks() { if (m_hasOutstandingTask.compareAndSet(false, true)) { Runnable task = new Runnable() { @Override public void run() { DBBPool.BBContainer srcC = null; boolean queuedMessages = false; SettableFuture<Void> sf = null; while ((srcC = getDecryptionFrame()) != null) { try { sf = SettableFuture.create(); m_decryptionResults.add(sf); final List<ByteBuffer> messages = new ArrayList<>(); srcC.b().flip(); m_dstBuffer.limit(m_dstBuffer.capacity()); m_sslBufferDecrypter.unwrap(srcC.b(), m_dstBuffer); if (m_dstBuffer.hasRemaining()) { ByteBuffer message; while ((message = m_sslMessageParser.message(m_dstBuffer)) != null) { messages.add(message); } } srcC.discard(); srcC = null; m_dstBuffer.clear(); m_decryptedMessages.offer(new DecryptionResult(messages, sf)); sf = null; queuedMessages = true; if (!m_isShuttingDown.get() && queuedMessages) { m_network.addToChangeList(m_port, true); } } catch(IOException ioe){ networkLog.error("Exception unwrapping an SSL frame", ioe); m_dstBuffer.clear(); return; } finally{ if (srcC != null) { srcC.discard(); } if (sf != null) { sf.setException(new Throwable("Decryption of buffer failed.")); } m_hasOutstandingTask.set(false); } } } }; try { m_sslEncryptionService.submitForDecryption(task); } catch (RejectedExecutionException e) { } } }

Target:
synchronized void submitDecryptionTasks() { if (! m_hasOutstandingTask) { try { m_sslEncryptionService.submitForDecryption(m_decTask); m_hasOutstandingTask = true; } catch (RejectedExecutionException e) { } } }
Source:
private void validateIOSeparator(String folderName) throws IOException { if(folderName.contains(File.separator)) { throw new IOException("It's not possible to use the OS separator to create folder hierarchies like " + "\'MyParentFolder\'"+File.separator+"\'MyFolder\'. " + "Please use newFolder('MyParentFolder','MyFolder') instead"); } }

Target:
private void validateIOSeparator(String folderName) throws IOException { if (folderName.contains(File.separator)) { String errorMsg = "It's not possible to use the OS separator to create folder " + "hierarchies like 'MyParentFolder'%s'MyFolder'. Please use newFolder('MyParentFolder', "+ "'MyFolder') instead"; throw new IOException(String.format(errorMsg,File.separator)); } }
Source:
public synchronized void processProject(final IProgressMonitor progressMonitor) throws CoreException { synchronized(this) { try { this.initializing = true; progressMonitor.beginTask("Processing project '" + getProject().getName() + "'...", 1); this.elements.clear(); this.endpoints.clear(); this.indexationService.clear(); addBuiltinHttpMethods(); Logger.debug("Processing project '" + getProject().getName() + "'..."); processResourceChange(new ResourceDelta(getProject(), ADDED, 0), progressMonitor); if (WtpUtils.hasWebDeploymentDescriptor(getProject())) { processWebDeploymentDescriptorChange( new ResourceDelta(WtpUtils.getWebDeploymentDescriptor(getProject()), ADDED, 0), progressMonitor); } progressMonitor.worked(1); } catch (CoreException e) { Logger.error("Failed while processing resource results", e); } finally { progressMonitor.done(); setBuildStatus(Status.OK_STATUS); Logger.debug("Done processing resource results."); this.initializing = false; } } }

Target:
public void processProject(final IProgressMonitor progressMonitor) throws CoreException { try { readWriteLock.writeLock().lock(); this.initializing = true; progressMonitor.beginTask("Processing project '" + getProject().getName() + "'...", 1); this.elements.clear(); this.endpoints.clear(); this.indexationService.clear(); addBuiltinHttpMethods(); Logger.debug("Processing project '" + getProject().getName() + "'..."); processResourceChange(new ResourceDelta(getProject(), ADDED, 0), progressMonitor); if (WtpUtils.hasWebDeploymentDescriptor(getProject())) { processWebDeploymentDescriptorChange( new ResourceDelta(WtpUtils.getWebDeploymentDescriptor(getProject()), ADDED, 0), progressMonitor); } progressMonitor.worked(1); } catch (CoreException e) { Logger.error("Failed while processing resource results", e); } finally { progressMonitor.done(); readWriteLock.writeLock().unlock(); setBuildStatus(Status.OK_STATUS); Logger.debug("Done processing resource results."); this.initializing = false; } }
Source:
public static void endTaskJob(ExecutionContext context, boolean exitStatus) { if (context == null) { return; } try { if (context.getExecutionMethod() == ExecutionMethod.AsJob && context.getJob() != null) { endJob(context, exitStatus); } else { Step parentStep = context.getStep(); if (context.getExecutionMethod() == ExecutionMethod.AsStep && parentStep != null) { Step finalizingStep = parentStep.getStep(StepEnum.FINALIZING); if (finalizingStep != null) { endTaskStep(finalizingStep.getId(), exitStatus ? JobExecutionStatus.FINISHED : JobExecutionStatus.FAILED); } parentStep.markStepEnded(exitStatus); JobRepositoryFactory.getJobRepository().updateStep(parentStep); List<Step> steps = DbFacade.getInstance().getStepDao().getStepsByJobId(parentStep.getJobId()); boolean hasChildStepsRunning = false; for (Step step : steps) { if (step.getStatus() == JobExecutionStatus.STARTED && step.getParentStepId() != null) { hasChildStepsRunning = true; break; } } if (!hasChildStepsRunning) { endJob(exitStatus, JobRepositoryFactory.getJobRepository().getJob(parentStep.getJobId())); } } } } catch (RuntimeException e) { log.error(e); } }

Target:
public static void endTaskJob(ExecutionContext context, boolean exitStatus) { if (context == null) { return; } try { if (context.getExecutionMethod() == ExecutionMethod.AsJob && context.getJob() != null) { endJob(context, exitStatus); } else { Step parentStep = context.getStep(); if (context.getExecutionMethod() == ExecutionMethod.AsStep && parentStep != null) { Step finalizingStep = parentStep.getStep(StepEnum.FINALIZING); if (finalizingStep != null) { finalizingStep.markStepEnded(exitStatus); JobRepositoryFactory.getJobRepository().updateStep(finalizingStep); } parentStep.markStepEnded(exitStatus); JobRepositoryFactory.getJobRepository().updateStep(parentStep); List<Step> steps = DbFacade.getInstance().getStepDao().getStepsByJobId(parentStep.getJobId()); boolean hasChildStepsRunning = false; for (Step step : steps) { if (step.getStatus() == JobExecutionStatus.STARTED && step.getParentStepId() != null) { hasChildStepsRunning = true; break; } } if (!hasChildStepsRunning) { endJob(exitStatus, JobRepositoryFactory.getJobRepository().getJob(parentStep.getJobId())); } } } } catch (RuntimeException e) { log.error(e); } }
Source:
@Test public void testFileExpansionCorrectlyZeroesData() throws IOException { QueueFile queue = new QueueFile(file); byte[][] values = new byte[5][]; for (int blockNum = 0; blockNum < values.length; blockNum++) { values[blockNum] = new byte[1024]; for (int i = 0; i < values[blockNum].length; i++) { values[blockNum][i] = (byte) (blockNum + 1); } } queue.add(values[0]); queue.add(values[1]); queue.remove(); queue.add(values[2]); queue.add(values[3]); queue.add(values[4]); byte[] data = new byte[1028]; byte[] expected = new byte[1028]; queue.raf.seek(HEADER_LENGTH); queue.raf.readFully(data, 0, expected.length); assertThat(data).isEqualTo(expected); data = new byte[3024]; expected = new byte[3024]; queue.raf.seek(5168); queue.raf.readFully(data, 0, expected.length); assertThat(data).isEqualTo(expected); }

Target:
@Test public void testFileExpansionCorrectlyZeroesData() throws IOException { QueueFile queue = new QueueFile(file); byte[][] values = new byte[5][]; for (int blockNum = 0; blockNum < values.length; blockNum++) { values[blockNum] = new byte[1024]; for (int i = 0; i < values[blockNum].length; i++) { values[blockNum][i] = (byte) (blockNum + 1); } } queue.add(values[0]); queue.add(values[1]); queue.remove(); queue.add(values[2]); queue.add(values[3]); queue.add(values[4]); int firstElementPadding = 1028; byte[] data = new byte[firstElementPadding]; queue.raf.seek(HEADER_LENGTH); queue.raf.readFully(data, 0, firstElementPadding); assertThat(data).containsOnly((byte) 0x00); int endOfLastElement = HEADER_LENGTH + firstElementPadding + 4 * (Element.HEADER_LENGTH + 1024); int readLength = (int) (queue.raf.length() - endOfLastElement); data = new byte[readLength]; queue.raf.seek(endOfLastElement); queue.raf.readFully(data, 0, readLength); assertThat(data).containsOnly((byte) 0x00); }
Source:
public static void main(String[] args) throws Exception{ Parameters param = getParameters(args); if (param.isStream()) { StatusListener listener = new StatusListener() { @Override public void onException(Exception e) { } @Override public void onStatus(Status status) { printStatus(status, param.isHideRt()); if (!status.isRetweet() || !param.isHideRt()) try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) { System.err.println("Sleep error"); } } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } @Override public void onTrackLimitationNotice(int i) { } @Override public void onScrubGeo(long l, long l1) { } @Override public void onStallWarning(StallWarning stallWarning) { } }; try { stream(param, listener); } catch (TwitterException e) { System.err.println("twitter error"); } catch (Exception e) { System.err.println("connection error"); } } else { try { search(param); } catch (TwitterException e) { System.err.println("twitter error"); } catch (Exception e) { System.err.println("connection error"); } } }

Target:
public static void main(String[] args) throws Exception { Parameters param = getParameters(args); if (param.isHelp()) { System.exit(0); } if (param.isStream()) { StatusAdapter listener = new StatusAdapter() { @Override public void onException(Exception e) { System.err.println("Stream error"); } @Override public void onStatus(Status status) { printStatus(status, param.isHideRt()); if (!status.isRetweet() || !param.isHideRt()) { try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) { System.err.println("Sleep error"); } } } }; try { stream(param, listener); } catch (TwitterException e) { System.err.println("twitter error"); } catch (IOException e) { System.err.println("cant find api key"); } catch (Exception e) { System.err.println("connection error"); } } else { try { search(param); } catch (TwitterException e) { System.err.println("twitter error"); } catch (Exception e) { System.err.println("connection error"); } } }
Source:
public static Property<AggregationNode, Rule.Context, List<Symbol>> groupingKeys() { return property("groupingKeys", AggregationNode::getGroupingKeys); }

Target:
public static Property<AggregationNode, Lookup, List<Symbol>> groupingKeys() { return property("groupingKeys", AggregationNode::getGroupingKeys); }
Source:
public void testGetSecurityGroupById() { HttpRequest getSecurityGroup = HttpRequest.builder().method("GET").endpoint( URI.create("<LINK_0>")).headers( ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).build(); HttpResponse getSecurityGroupResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/securitygroup_details_extension.json")).build(); Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder(); requestResponseMap.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess); requestResponseMap.put(extensionsOfNovaRequest, extensionsOfNovaResponse); requestResponseMap.put(getSecurityGroup, getSecurityGroupResponse).build(); SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get(); SecurityGroup group = extension.getSecurityGroupById(zone + "/160"); assertEquals("160", group.getId()); }

Target:
public void testGetSecurityGroupById() { HttpRequest getSecurityGroup = HttpRequest.builder().method("GET").endpoint( URI.create("<LINK_0>")).headers( ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).build(); HttpResponse getSecurityGroupResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/securitygroup_details_extension.json")).build(); Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder(); requestResponseMap.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess); requestResponseMap.put(extensionsOfNovaRequest, extensionsOfNovaResponse); requestResponseMap.put(getSecurityGroup, getSecurityGroupResponse).build(); SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get(); SecurityGroup group = extension.getSecurityGroupById(zone + "/160"); assertEquals(group.getId(), "160"); }
Source:
catch (NoSuchMethodException e) { mtd = null; }

Target:
catch (NoSuchMethodException e) { throw new ExceptionInInitializerError("'invokeMethod' is not defined in " + PlatformService.class.getName()); }
Source:
private void init() { initializationTime = System.currentTimeMillis(); statsDClient = new NonBlockingStatsDClient( null, this.statsdHost, this.statsdPort, Integer.MAX_VALUE, new String[] {}, new LoggingErrorHandler(), "none"); }

Target:
private void init() { initializationTime = System.currentTimeMillis(); String entityID = this.statsdPort == 0 ? "none" : null; statsDClient = new NonBlockingStatsDClient( null, this.statsdHost, this.statsdPort, Integer.MAX_VALUE, new String[] {}, new LoggingErrorHandler(), entityID); }