auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String validateNamespaceArgument(ByteBuffer namespaceArg, TableOperation op, Validator<String> userValidator) throws ThriftTableOperationException { String namespace = namespaceArg == null ? null : ByteBufferUtil.toString(namespaceArg); if ((namespace != null) && (namespace.length() > MAX_NAMESPACE_LEN)) { log.warn("Namespaces greater than " + MAX_NAMESPACE_LEN + " characters should be renamed to conform to a 1024 character limit. " + "Longer namespaces are no longer supported and may result in unexpected behavior."); } return _validateArgument(namespace, op, Namespaces.VALID_NAME.and(userValidator)); }

Target:
private String validateNamespaceArgument(ByteBuffer namespaceArg, TableOperation op, Validator<String> userValidator) throws ThriftTableOperationException { String namespace = namespaceArg == null ? null : ByteBufferUtil.toString(namespaceArg); if ((namespace != null) && (namespace.length() > MAX_NAMESPACE_LEN)) { log.warn("Namespaces greater than " + MAX_NAMESPACE_LEN + " characters should be renamed to conform to a " + MAX_NAMESPACE_LEN + " character limit. " + "Longer namespaces are no longer supported and may result in unexpected behavior."); } return _validateArgument(namespace, op, Namespaces.VALID_NAME.and(userValidator)); }
Source:
public ScaledNumberIndexFieldTypeContext<?, BigInteger> asBigInteger() { return new StubScaledNumberIndexFieldTypeContext( BigInteger.class, defaultsProvider ); }

Target:
public ScaledNumberIndexFieldTypeContext<?, BigInteger> asBigInteger() { return new StubScaledNumberIndexFieldTypeContext<>( BigInteger.class, defaultsProvider ); }
Source:
private Vms getVmsFilteredAndSorted() { int max = ParametersHelper.getIntegerParameter(httpHeaders, uriInfo, "max", -1, -1); GetFilteredAndSortedParameters params = new GetFilteredAndSortedParameters(max); String searchConstraint = QueryHelper.getConstraint(httpHeaders, uriInfo, "", modelType); Integer pageNum = QueryHelper.parsePageNum(searchConstraint); params.setPageNum(pageNum==null ? 1 : pageNum); return mapCollection(getBackendCollection(QueryType.GetAllVmsFilteredAndSorted, params)); }

Target:
private Vms getVmsFilteredAndSorted() { int max = ParametersHelper.getIntegerParameter(httpHeaders, uriInfo, "max", -1, -1); String searchConstraint = QueryHelper.getConstraint(httpHeaders, uriInfo, "", modelType); Integer pageNum = QueryHelper.parsePageNum(searchConstraint); GetFilteredAndSortedParameters params = new GetFilteredAndSortedParameters(max, pageNum==null ? 1 : pageNum); return mapCollection(getBackendCollection(QueryType.GetAllVmsFilteredAndSorted, params)); }
Source:
public FBNetworkContextMenuProvider(final DiagramEditorWithFlyoutPalette editor, final ActionRegistry registry, final ZoomManager zoomManager, Palette palette) { super(editor.getViewer(), zoomManager, registry); this.palette = palette; this.editor = editor; editor.getViewer().getControl().addMenuDetectListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent e) { pt = getViewer().getControl().toControl(e.x, e.y); } }); }

Target:
public FBNetworkContextMenuProvider(final DiagramEditorWithFlyoutPalette editor, final ActionRegistry registry, final ZoomManager zoomManager, Palette palette) { super(editor.getViewer(), zoomManager, registry); this.palette = palette; this.editor = editor; editor.getViewer().getControl().addMenuDetectListener(e -> pt = getViewer().getControl().toControl(e.x, e.y)); }
Source:
public boolean subscribe(FBOManagerSubscriber subscriber) { if (!fboManagerSubscribers.add(subscriber)) return false; return true; }

Target:
public boolean subscribe(FBOManagerSubscriber subscriber) { for (FBOManagerSubscriber fboManagerSubscriber: fboManagerSubscribers) { if (fboManagerSubscriber == subscriber) { return false; } } return fboManagerSubscribers.add(subscriber); }
Source:
public boolean getIsResponsePresent() { for (StudentFeedbackSubmissionEditQuestionsWithResponses questionsResponses : questionsWithResponses) { for (FeedbackSubmissionEditResponse responses : questionsResponses.getResponses()) { if (responses.isExistingResponse()) { return true; } } } return false; }

Target:
public boolean getIsResponsePresent() { for (Map.Entry<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> entry : bundle.questionResponseBundle.entrySet()) { if (!entry.getValue().isEmpty()) { return true; } } return false; }
Source:
public void internalReceiveCommand(String itemName, Command command) { if (password != null && !password.isEmpty()) { logger.warn("Fritzbox password: "+password); String type = null; for (FritzboxBindingProvider provider : providers) { type = provider.getType(itemName); if (type != null) { break; } } logger.info("Fritzbox type: {}", type); if (type == null) return; TelnetCommandThread thread = new TelnetCommandThread(type, command); thread.start(); } }

Target:
public void internalReceiveCommand(String itemName, Command command) { if (password != null && !password.isEmpty()) { String type = null; for (FritzboxBindingProvider provider : providers) { type = provider.getType(itemName); if (type != null) { break; } } logger.info("Fritzbox type: {}", type); if (type == null) return; TelnetCommandThread thread = new TelnetCommandThread(type, command); thread.start(); } }
Source:
public void testClusterSnapshotCreate() throws Exception { Ignite ignite = startGrids(2); ignite.cluster().state(ACTIVE); createCacheAndPreload(ignite, 10); CommandHandler h = new CommandHandler(); assertEquals(EXIT_CODE_OK, execute(h, "--snapshot", "create", "snapshot_02052020")); }

Target:
public void testClusterSnapshotCreate() throws Exception { int keysCnt = 100; String snpName = "snapshot_02052020"; IgniteEx ig = startGrid(0); ig.cluster().state(ACTIVE); createCacheAndPreload(ig, keysCnt); CommandHandler h = new CommandHandler(); assertEquals(EXIT_CODE_OK, execute(h, "--snapshot", "create", snpName)); assertTrue("Waiting for snapshot operation end failed.", waitForCondition(() -> ig.context().metric().registry(SNAPSHOT_METRICS) .<LongMetric>findMetric("LastSnapshotEndTime").value() > 0, getTestTimeout())); assertContains(log, (String)h.getLastOperationResult(), snpName); stopAllGrids(); IgniteConfiguration cfg = optimize(getConfiguration(getTestIgniteInstanceName(0))); cfg.setWorkDirectory(Paths.get(resolveSnapshotWorkDirectory(cfg).getAbsolutePath(), snpName).toString()); Ignite snpIg = startGrid(cfg); snpIg.cluster().state(ACTIVE); List<Integer> range = IntStream.range(0, keysCnt).boxed().collect(Collectors.toList()); snpIg.cache(DEFAULT_CACHE_NAME).forEach(e -> range.remove((Integer)e.getKey())); assertTrue("Snapshot must contains cache data [left=" + range + ']', range.isEmpty()); }
Source:
private void run(String fileLocation) throws SQLException, AuthorizeException { Context context = new Context(); context.turnOffAuthorisationSystem(); List<RelationshipType> relationshipTypes = this.parseXMLToRelations(context, fileLocation); this.saveRelations(context, relationshipTypes); }

Target:
private void run(String fileLocation) throws SQLException, AuthorizeException { Context context = new Context(); context.turnOffAuthorisationSystem(); this.parseXMLToRelations(context, fileLocation); context.complete(); }
Source:
public void testListenableTimeout() throws Exception { SettableFuture<String> rootFuture = SettableFuture.create(); ListenableFuture<String> timeoutFuture = addTimeout(rootFuture, () -> "timeout", new Duration(0, MILLISECONDS), executorService); assertEquals(tryGetFutureValue(timeoutFuture, 10, SECONDS).get(), "timeout"); assertTrue(timeoutFuture.isDone()); assertFalse(timeoutFuture.isCancelled()); assertFailure(() -> rootFuture.get(10, SECONDS), e -> assertInstanceOf(e, CancellationException.class)); assertTrue(rootFuture.isDone()); assertTrue(rootFuture.isCancelled()); }

Target:
public void testListenableTimeout() throws Exception { SettableFuture<String> rootFuture = SettableFuture.create(); ListenableFuture<String> timeoutFuture = addTimeout(rootFuture, () -> "timeout", new Duration(0, MILLISECONDS), executorService); assertEquals(tryGetFutureValue(timeoutFuture, 10, SECONDS).orElse("failed"), "timeout"); assertTrue(timeoutFuture.isDone()); assertFalse(timeoutFuture.isCancelled()); assertFailure(() -> rootFuture.get(10, SECONDS), e -> assertInstanceOf(e, CancellationException.class)); assertTrue(rootFuture.isDone()); assertTrue(rootFuture.isCancelled()); }
Source:
private static void unpackFace(File outputDirectory) throws IOException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); for (ClassPath.ResourceInfo info : ClassPath.from(loader).getResources()) { Matcher matcher = REPORT_RESOURCE_PATTERN.matcher(info.getResourceName()); if (matcher.find()) { String resourcePath = matcher.group(1); File dest = new File(outputDirectory, resourcePath); Files.createParentDirs(dest); try (FileOutputStream output = new FileOutputStream(dest); InputStream input = info.url().openStream()) { IOUtils.copy(input, output); LOGGER.debug("{} successfully copied.", resourcePath); } } } }

Target:
private static void unpackFace(File outputDirectory) throws IOException { ClassLoader loader = AllureMain.class.getClassLoader(); for (ClassPath.ResourceInfo info : ClassPath.from(loader).getResources()) { Matcher matcher = REPORT_RESOURCE_PATTERN.matcher(info.getResourceName()); if (matcher.find()) { String resourcePath = matcher.group(1); File dest = new File(outputDirectory, resourcePath); Files.createParentDirs(dest); try (FileOutputStream output = new FileOutputStream(dest); InputStream input = info.url().openStream()) { IOUtils.copy(input, output); LOGGER.debug("{} successfully copied.", resourcePath); } } } }
Source:
public List<ASTAnnotation> getDeclaredAnnotations() { List<ASTAnnotation> result = new ArrayList<>(); ASTClassOrInterfaceBodyDeclaration decl = ((ASTClassOrInterfaceBodyDeclaration) jjtGetParent()); for (int i = 0; i < decl.jjtGetNumChildren() - 1; i++) { if (!(decl.jjtGetChild(i) instanceof ASTAnnotation)) { break; } result.add((ASTAnnotation) decl.jjtGetChild(i)); } return result; }

Target:
public List<ASTAnnotation> getDeclaredAnnotations() { return this.jjtGetParent().findChildrenOfType(ASTAnnotation.class); }
Source:
public static void apply(Editable editable, int oldCursorPosition, int newCursorPosition) { if (!isValidCursorIncrement(oldCursorPosition, newCursorPosition)) { return; } String noteContent = editable.toString(); String prevChar = noteContent.substring(newCursorPosition - 1, newCursorPosition); if (prevChar.equals(STR_LINE_BREAK)) { int prevParagraphEnd = newCursorPosition - 1; int prevParagraphStart = noteContent.lastIndexOf(STR_LINE_BREAK, prevParagraphEnd - 1); prevParagraphStart++; String prevParagraph = noteContent.substring(prevParagraphStart, prevParagraphEnd); BulletMetadata metadata = extractBulletMetadata(prevParagraph); CheckableSpan[] checkableSpans = editable.getSpans(prevParagraphStart, prevParagraphStart + 1, CheckableSpan.class); if (checkableSpans.length > 0) { if (prevParagraph.equals(STR_SPACE + STR_SPACE)) { editable.replace(prevParagraphStart, newCursorPosition, STR_LINE_BREAK); } else { editable.insert(newCursorPosition, ChecklistUtils.UNCHECKED_MARKDOWN + STR_SPACE); } return; } if (metadata.isBullet) { String bullet; if (!metadata.isEmptyBullet) { bullet = buildBullet(metadata); editable.insert(newCursorPosition, bullet); } else { if (metadata.numSpacesPrefixed > 0) { metadata.numSpacesPrefixed -= 1; bullet = buildBullet(metadata); } else { bullet = STR_LINE_BREAK; } editable.replace(prevParagraphStart, newCursorPosition, bullet); } } } }

Target:
public static void apply(Editable editable, int oldCursorPosition, int newCursorPosition) { if (!isValidCursorIncrement(oldCursorPosition, newCursorPosition)) { return; } String noteContent = editable.toString(); String prevChar = noteContent.substring(newCursorPosition - 1, newCursorPosition); if (prevChar.equals(STR_LINE_BREAK)) { int prevParagraphEnd = newCursorPosition - 1; int prevParagraphStart = noteContent.lastIndexOf(STR_LINE_BREAK, prevParagraphEnd - 1); prevParagraphStart++; String prevParagraph = noteContent.substring(prevParagraphStart, prevParagraphEnd); BulletMetadata metadata = extractBulletMetadata(prevParagraph); CheckableSpan[] checkableSpans = editable.getSpans(prevParagraphStart, prevParagraphStart + 1, CheckableSpan.class); if (checkableSpans.length > 0) { if (prevParagraph.equals(STR_SPACE + STR_SPACE)) { editable.replace(prevParagraphStart, newCursorPosition, ""); } else { editable.insert(newCursorPosition, ChecklistUtils.UNCHECKED_MARKDOWN + STR_SPACE); } return; } if (metadata.isBullet) { String bullet; if (!metadata.isEmptyBullet) { bullet = buildBullet(metadata); editable.insert(newCursorPosition, bullet); } else { if (metadata.numSpacesPrefixed > 0) { metadata.numSpacesPrefixed -= 1; bullet = buildBullet(metadata); } else { bullet = ""; } editable.replace(prevParagraphStart, newCursorPosition, bullet); } } } }
Source:
public ActivityLogEntry(AppLogLine appLog){ time = appLog.getTimeUsec() / 1000; String[] tokens = appLog.getLogMessage().split("\\|\\|\\|", -1); try{ servletName = tokens[1]; action = tokens[2]; toShow = (tokens[3].equals("true") ? true : false); role = tokens[4]; name = tokens[5]; googleId = tokens[6]; email = tokens[7]; message = tokens[8]; url = tokens[9]; if (tokens.length >= 11) { boolean isLogId = tokens[10].contains(googleId) || tokens[10].contains("%"); if (isLogId) { id = tokens[10]; timeTaken = tokens.length == 12 ? Long.parseLong(tokens[11].trim()) : null; } else { timeTaken = Long.parseLong(tokens[10].trim()); } } keyStringsToHighlight = null; } catch (ArrayIndexOutOfBoundsException e){ servletName = "Unknown"; action = "Unknown"; role = "Unknown"; name = "Unknown"; googleId = "Unknown"; email = "Unknown"; toShow = true; message = "<span class=\"text-danger\">Error. Problem parsing log message from the server.</span><br>" + "System Error: " + e.getMessage() + "<br>" + appLog.getLogMessage(); url = "Unknown"; id = "Unknown" + formatTimeForId(new Date(time)); timeTaken = null; keyStringsToHighlight = null; } logInfoAsHtml = getLogInfoForTableRowAsHtml(); }

Target:
public ActivityLogEntry(AppLogLine appLog){ time = appLog.getTimeUsec() / 1000; try { String[] tokens = appLog.getLogMessage().split("\\|\\|\\|", -1); initUsingAppLogMessage(tokens); } catch (ArrayIndexOutOfBoundsException e) { initAsFailure(appLog, e); } keyStringsToHighlight = null; logInfoAsHtml = getLogInfoForTableRowAsHtml(); }
Source:
public Class<MongoCodeListEntry> getEntryType() { return MongoCodeListEntry.class; }

Target:
protected Class<MongoCodeListEntry> getEntryType() { return MongoCodeListEntry.class; }
Source:
public static Pair<String, Map<String, String>> formatWithAttributes(String messageTemplate, Object... args) { if (messageTemplate == null) { return formatWithAttributes("", args); } if (args == null) { return formatWithAttributes(messageTemplate, new Object[0]); } StringBuilder outputStringBuilder = new StringBuilder(messageTemplate.length() + args.length * 20); ImmutableMap.Builder<String, String> attributesMap = ImmutableMap.builder(); String pattern = "\\{(\\w+)\\}"; Pattern regexPattern = Pattern.compile(pattern); Matcher matcher = regexPattern.matcher(messageTemplate); int groupIndex = 0; int lastAddedStringEndIndex = 0; int matchesCount = 0; while (matcher.find()) { matchesCount++; } if (matchesCount > args.length) { throw new IllegalArgumentException( Messages.format("You have included placeholders, however only provided arguments.", matchesCount, args.length)); } matcher.reset(); while (matcher.find()) { String attributeName = matcher.group(1); int startIndex = matcher.start(); int endIndex = matcher.end(); String replacement = args[groupIndex].toString(); attributesMap.put(attributeName, replacement); String unmodifiedText = messageTemplate.substring(lastAddedStringEndIndex, startIndex); outputStringBuilder .append(unmodifiedText) .append(replacement); lastAddedStringEndIndex = endIndex; groupIndex++; } if(lastAddedStringEndIndex < messageTemplate.length()) { outputStringBuilder.append(messageTemplate.substring(lastAddedStringEndIndex, messageTemplate.length())); } return Pair.of(outputStringBuilder.toString(), attributesMap.build()); }

Target:
public static Pair<String, Map<String, String>> formatWithAttributes(String messageTemplate, Object... args) { if (messageTemplate == null) { return formatWithAttributes("", args); } if (args == null) { return formatWithAttributes(messageTemplate); } Map<String, String> attributes = new HashMap<>(); Matcher matcher = REGEX_PATTERN.matcher(messageTemplate); int argIndex = 0; StringBuffer outputMessageBuffer = new StringBuffer(); while (matcher.find()) { if (argIndex >= args.length) { continue; } String attributeName = matcher.group(1); String replacement = args[argIndex].toString().replace("$", "\\$"); matcher.appendReplacement(outputMessageBuffer, replacement); if (!attributeName.isEmpty()) { attributes.put(attributeName, replacement); } argIndex++; } matcher.appendTail(outputMessageBuffer); return Pair.of(outputMessageBuffer.toString(), ImmutableMap.copyOf(attributes)); }
Source:
public PortPairsOperation(OperationLogger logger, String portPairs) { this(logger, new ArrayList<Pair<String, String>>()); for (String pair : portPairs.split("[\n\r]+")) { String[] pairLine = pair.split("[\\s,]+"); this.portPairs.add(new Pair<String, String>(pairLine[0], pairLine[1])); } }

Target:
public PortPairsOperation(OperationLogger logger, String portPairs) throws OseeArgumentException { this(logger, new ArrayList<Pair<String, String>>()); for (String pair : portPairs.split("[\n\r]+")) { String[] pairLine = pair.split("[\\s,]+"); if (pairLine.length != 2) { throw new OseeArgumentException("Invalid porting pairs"); } this.portPairs.add(new Pair<String, String>(pairLine[0], pairLine[1])); } }
Source:
public void getRelatedNoResult() throws Exception { PushOneCommit push = pushFactory.create(db, admin.getIdent()); PatchSet.Id ps = push.to(git, "refs/for/master").getPatchSetId(); List<ChangeAndCommit> related = getRelated(ps); assertThat(related.size()).isEqualTo(0); }

Target:
public void getRelatedNoResult() throws Exception { PushOneCommit push = pushFactory.create(db, admin.getIdent()); PatchSet.Id ps = push.to(git, "refs/for/master").getPatchSetId(); List<ChangeAndCommit> related = getRelated(ps); assertThat(related).isEmpty(); }
Source:
ApplicationPresenter( EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager) { super(eventBus, view, proxy, RevealType.Root); this.placeManager = placeManager; }

Target:
ApplicationPresenter(EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager) { super(eventBus, view, proxy, RevealType.Root); this.placeManager = placeManager; getView().setUiHandlers(this); }
Source:
private Map<String, RevisionInfo> revisions(ChangeData cd) throws OrmException, IOException { ChangeControl ctl = control(cd); if (ctl == null) { return null; } Collection<PatchSet> src; Map<PatchSet.Id, PatchSet> revEdits = Collections.emptyMap(); if (cd.getLimitedPatchSets() != null || has(ALL_REVISIONS)) { src = cd.patches(db); if (userProvider.get().isIdentifiedUser()) { try { revEdits = edits.read(cd.getChange()); } catch (Exception e) { throw new IOException(e); } } } else { src = Collections.singletonList(cd.currentPatchSet(db)); } Map<String, RevisionInfo> res = Maps.newLinkedHashMap(); for (PatchSet in : src) { if (ctl.isPatchVisible(in, db.get())) { RevisionInfo revisionInfo = toRevisionInfo(cd, in); res.put(in.getRevision().get(), revisionInfo); if (!revEdits.isEmpty()) { PatchSet.Id editId = PatchSet.Id.editFrom(in.getId()); if (revEdits.containsKey(editId)) { PatchSet editPatchSet = revEdits.get(editId); RevisionInfo revisionEditInfo = toRevisionInfo(cd, editPatchSet); if (revisionInfo.isCurrent) { assert(revisionEditInfo.isCurrent); revisionInfo.isCurrent = false; } res.put(editPatchSet.getRevision().get(), revisionEditInfo); } } } } return res; }

Target:
private Map<String, RevisionInfo> revisions(ChangeData cd) throws OrmException, IOException { ChangeControl ctl = control(cd); if (ctl == null) { return null; } Collection<PatchSet> src; Map<PatchSet.Id, PatchSet> revEdits = Collections.emptyMap(); if (cd.getLimitedPatchSets() != null || has(ALL_REVISIONS)) { src = cd.patches(); if (userProvider.get().isIdentifiedUser()) { try { revEdits = edits.read(cd.getChange()); } catch (Exception e) { throw new IOException(e); } } } else { src = Collections.singletonList(cd.currentPatchSet()); } Map<String, RevisionInfo> res = Maps.newLinkedHashMap(); for (PatchSet in : src) { if (ctl.isPatchVisible(in, db.get())) { RevisionInfo revisionInfo = toRevisionInfo(cd, in); res.put(in.getRevision().get(), revisionInfo); if (!revEdits.isEmpty()) { PatchSet.Id editId = PatchSet.Id.editFrom(in.getId()); if (revEdits.containsKey(editId)) { PatchSet editPatchSet = revEdits.get(editId); RevisionInfo revisionEditInfo = toRevisionInfo(cd, editPatchSet); if (revisionInfo.isCurrent) { assert(revisionEditInfo.isCurrent); revisionInfo.isCurrent = false; } res.put(editPatchSet.getRevision().get(), revisionEditInfo); } } } } return res; }
Source:
public void testSanitizeForLogMessage() { assertNull("should return null if given null", SanitizationHelper.sanitizeForLogMessage(null)); String unsanitized = "<span class=\"text-danger\"> A <span class=\"bold\">typical</span> log message <br>" + " It contains some <script>dangerous</script> elements </span>"; String correctSanitized = "<span class=\"text-danger\"> A <span class=\"bold\">typical</span> log message <br>" + " It contains some &lt;script&gt;dangerous&lt;&#x2f;script&gt; elements </span>"; assertEquals("Should escape HTML special characters" + "other than in <span class=\"text-danger\">, <span class=\"bold\"> and <br>", correctSanitized, SanitizationHelper.sanitizeForLogMessage(unsanitized)); }

Target:
public void testSanitizeForLogMessage() { assertNull("should return null if given null", SanitizationHelper.sanitizeForLogMessage(null)); String unsanitized = "<span class=\"text-danger\"> A <span class=\"bold\">typical</span> log message <br>" + " It contains some <script>dangerous</script> elements </span>"; String correctSanitized = "<span class=\"text-danger\"> A <span class=\"bold\">typical</span> log message <br>" + " It contains some &lt;script&gt;dangerous&lt;&#x2f;script&gt; elements </span>"; assertEquals("Should escape HTML special characters" + "other than in <span class=\"text-danger\">, <span class=\"bold\"> and <br>", correctSanitized, SanitizationHelper.sanitizeForLogMessage(unsanitized)); unsanitized = "Hmm. <span class=\"text-info\"> How about this? </span> and <span> this</span>"; correctSanitized = "Hmm. &lt;span class=&quot;text-info&quot;&gt; How about this? </span> and <span> this</span>"; assertEquals("Should escape if span has a class other than 'bold' or 'text-danger'", correctSanitized, SanitizationHelper.sanitizeForLogMessage(unsanitized)); unsanitized = "Single <span class='bold'> quotation mark? </span>"; correctSanitized = "Single &lt;span class=&#39;bold&#39;&gt; quotation mark? </span>"; assertEquals("Should escape if attribute is specified using single quotation marks", correctSanitized, SanitizationHelper.sanitizeForLogMessage(unsanitized)); }
Source:
public Table execute() throws MetaModelException { final MutableTable table = getTable(); final Object source = ElasticSearchUtils.getMappingSource(table); final ElasticSearchDataContext dataContext = getUpdateCallback().getDataContext(); final IndicesAdminClient indicesAdmin = dataContext.getElasticSearchClient().admin().indices(); final String indexName = dataContext.getIndexName(); final PutMappingRequestBuilder requestBuilder = new PutMappingRequestBuilder(indicesAdmin) .setIndices(indexName).setType(table.getName()); if (source instanceof Map) { requestBuilder.setSource((Map<?, ?>) source); } else { requestBuilder.setSource(source); } final PutMappingResponse result = requestBuilder.execute().actionGet(); logger.debug("PutMapping response: acknowledged={}", result.isAcknowledged()); final MutableSchema schema = (MutableSchema) getSchema(); schema.addTable(table); return table; }

Target:
public Table execute() throws MetaModelException { final MutableTable table = getTable(); final Map<String, ?> source = ElasticSearchUtils.getMappingSource(table); final ElasticSearchDataContext dataContext = getUpdateCallback().getDataContext(); final IndicesAdminClient indicesAdmin = dataContext.getElasticSearchClient().admin().indices(); final String indexName = dataContext.getIndexName(); final PutMappingRequestBuilder requestBuilder = new PutMappingRequestBuilder(indicesAdmin).setIndices(indexName) .setType(table.getName()); requestBuilder.setSource(source); final PutMappingResponse result = requestBuilder.execute().actionGet(); logger.debug("PutMapping response: acknowledged={}", result.isAcknowledged()); final MutableSchema schema = (MutableSchema) getSchema(); schema.addTable(table); return table; }
Source:
ShardSyncTaskManager(final IKinesisProxy kinesisProxy, final ILeaseManager<KinesisClientLease> leaseManager, final InitialPositionInStreamExtended initialPositionInStream, final boolean cleanupLeasesUponShardCompletion, final boolean ignoreUnexpectedChildShards, final long shardSyncIdleTimeMillis, final IMetricsFactory metricsFactory, ExecutorService executorService, ShardSyncer shardSyncer) { this.kinesisProxy = kinesisProxy; this.leaseManager = leaseManager; this.metricsFactory = metricsFactory; this.cleanupLeasesUponShardCompletion = cleanupLeasesUponShardCompletion; this.ignoreUnexpectedChildShards = ignoreUnexpectedChildShards; this.shardSyncIdleTimeMillis = shardSyncIdleTimeMillis; this.executorService = executorService; this.initialPositionInStream = initialPositionInStream; this.shardSyncer = shardSyncer; this.shardSyncRequestPending = new AtomicBoolean(false); this.lock = new ReentrantLock(Boolean.TRUE); }

Target:
ShardSyncTaskManager(final IKinesisProxy kinesisProxy, final ILeaseManager<KinesisClientLease> leaseManager, final InitialPositionInStreamExtended initialPositionInStream, final boolean cleanupLeasesUponShardCompletion, final boolean ignoreUnexpectedChildShards, final long shardSyncIdleTimeMillis, final IMetricsFactory metricsFactory, ExecutorService executorService, ShardSyncer shardSyncer) { this.kinesisProxy = kinesisProxy; this.leaseManager = leaseManager; this.metricsFactory = metricsFactory; this.cleanupLeasesUponShardCompletion = cleanupLeasesUponShardCompletion; this.ignoreUnexpectedChildShards = ignoreUnexpectedChildShards; this.shardSyncIdleTimeMillis = shardSyncIdleTimeMillis; this.executorService = executorService; this.initialPositionInStream = initialPositionInStream; this.shardSyncer = shardSyncer; this.shardSyncRequestPending = new AtomicBoolean(false); this.lock = new ReentrantLock(); }
Source:
protected void endWithFailure() { if (commandCoordinatorUtil.getCommandExecutionStatus(getCommandId()) != CommandExecutionStatus.EXECUTED) { changeStorageDomainStatusInTransaction(loadStoragePoolIsoMap(), StorageDomainStatus.Unknown); auditLogDirector.log(this, AuditLogType.USER_DEACTIVATE_STORAGE_DOMAIN_OVF_UPDATE_INCOMPLETE); } else { StoragePoolIsoMap map = loadStoragePoolIsoMap(); changeDomainStatusWithCompensation(map, StorageDomainStatus.Unknown, StorageDomainStatus.Active, getCompensationContext()); } setSucceeded(true); }

Target:
protected void endWithFailure() { if (commandCoordinatorUtil.getCommandExecutionStatus(getCommandId()) != CommandExecutionStatus.EXECUTED) { changeStorageDomainStatusInTransaction(loadStoragePoolIsoMap(), StorageDomainStatus.Unknown); auditLogDirector.log(this, AuditLogType.USER_DEACTIVATE_STORAGE_DOMAIN_OVF_UPDATE_INCOMPLETE); } else { changeStorageDomainStatusInTransaction(loadStoragePoolIsoMap(), StorageDomainStatus.Active); } setSucceeded(true); }
Source:
private void emitAndIndent(String s) { try { boolean first = true; for (String line : s.split("\n", -1)) { if (!first) { if ((javadoc || comment) && trailingNewline) { emitIndentation(); out.append(javadoc ? " *" : " } out.append('\n'); trailingNewline = true; } first = false; if (line.isEmpty()) continue; if (trailingNewline) { emitIndentation(); if (javadoc) { out.append(" * "); } else if (comment) { out.append(" } } out.append(line); trailingNewline = false; } } catch (IOException e) { throw new RuntimeException(e); } }

Target:
private CodeWriter emitAndIndent(String s) throws IOException { boolean first = true; for (String line : s.split("\n", -1)) { if (!first) { if ((javadoc || comment) && trailingNewline) { emitIndentation(); out.append(javadoc ? " *" : " } out.append('\n'); trailingNewline = true; } first = false; if (line.isEmpty()) continue; if (trailingNewline) { emitIndentation(); if (javadoc) { out.append(" * "); } else if (comment) { out.append(" } } out.append(line); trailingNewline = false; } return this; }
Source:
private X509CertificateHolder getCertFromTruststoreWithX500Name( X500Name name, KeyStore truststore) throws OcspCheckerException { Enumeration<String> aliases; try { aliases = truststore.aliases(); } catch (KeyStoreException e) { throw new OcspCheckerException("Problem getting aliases from truststore.", e); } while (aliases.hasMoreElements()) { String currentAlias = aliases.nextElement(); try { java.security.cert.Certificate currentCert = truststore.getCertificate(currentAlias); X509CertificateHolder currentCertHolder = new X509CertificateHolder(currentCert.getEncoded()); X500Name currentName = currentCertHolder.getSubject(); if (name.equals(currentName)) { return currentCertHolder; } } catch (CertificateEncodingException | IOException | KeyStoreException ignore) { } } throw new OcspCheckerException( String.format("Could not find cert matching X500Name of %s", name)); }

Target:
private X509CertificateHolder getCertFromTruststoreWithX500Name( X500Name name, KeyStore truststore) throws OcspCheckerException { Enumeration<String> aliases; try { aliases = truststore.aliases(); } catch (KeyStoreException e) { throw new OcspCheckerException( "Problem getting aliases from truststore." + NOT_VERIFIED_MSG, e); } while (aliases.hasMoreElements()) { String currentAlias = aliases.nextElement(); try { java.security.cert.Certificate currentCert = truststore.getCertificate(currentAlias); X509CertificateHolder currentCertHolder = new X509CertificateHolder(currentCert.getEncoded()); X500Name currentName = currentCertHolder.getSubject(); if (name.equals(currentName)) { return currentCertHolder; } } catch (CertificateEncodingException | IOException | KeyStoreException e) { LOGGER.debug("Problem loading truststore certificate." + CONTINUING_MSG, e); } } throw new OcspCheckerException( String.format("Could not find cert matching X500Name of %s.", name) + NOT_VERIFIED_MSG); }
Source:
public void testList() { List<Snapshot> snapshots = snapshotApi().getList(); assertNotNull(snapshots); assertFalse(snapshots.isEmpty()); }

Target:
public void testList() { List<Snapshot> snapshots = snapshotApi().list(); assertNotNull(snapshots); assertFalse(snapshots.isEmpty()); assertTrue(Iterables.any(snapshots, new Predicate<Snapshot>() { @Override public boolean apply(Snapshot input) { return input.id().equals(testSnapshot.id()); } })); }
Source:
public Collection<? extends GrantedAuthority> getAuthorities() { return user.getRoles() .stream() .map(a -> new SimpleGrantedAuthority(a.getUserRole())) .collect(Collectors.toSet()); }

Target:
public Collection<? extends GrantedAuthority> getAuthorities() { return user.getRoles() .stream() .map(SecurityRole::getRoleName) .map(SimpleGrantedAuthority::new) .collect(Collectors.toSet()); }
Source:
public static IGerritHudsonTriggerConfig getConfig(String serverName) { return PluginImpl.getInstance().getServer(serverName).getConfig(); }

Target:
public static IGerritHudsonTriggerConfig getConfig(String serverName) { GerritServer server = PluginImpl.getInstance().getServer(serverName); if (server != null) { return server.getConfig(); } else { logger.error("Could not find the Gerrit Server: {}", serverName); return null; } }
Source:
public void addToOrderBook(Order order) { if(order instanceof BuyOrder){ if(buyOrders.containsKey(order.getStockSymbol())){ buyOrders.get(order.getStockSymbol()).add(order); }else{ ArrayList<Order> orders = new ArrayList<Order>(); orders.add(order); buyOrders.put(order.getStockSymbol(), orders); } }else{ if(sellOrders.containsKey(order.getStockSymbol())){ sellOrders.get(order.getStockSymbol()).add(order); }else{ ArrayList<Order> orders = new ArrayList<Order>(); orders.add(order); sellOrders.put(order.getStockSymbol(), orders); } } }

Target:
public void addToOrderBook(Order order) { if(order instanceof BuyOrder){ addBuyOrderToOrderBook(order); }else{ addSellOrderToOrderBook(order); } }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Record {"); sb.append("id = ").append(id).append(", "); sb.append("title = ").append(title).append(", "); sb.append("type = "); switch (type) { case TYPE_EXPENSE: sb.append("expense"); break; case TYPE_INCOME: sb.append("income"); break; default: sb.append("unknown"); break; } sb.append(", "); sb.append("date = ").append(time).append(", "); sb.append("category = ").append(category).append(", "); sb.append("price = ").append(price).append(", "); sb.append("account = ").append(account).append(", "); sb.append("currency = ").append(currency).append(", "); sb.append("decimals = ").append(decimals); sb.append("}"); return sb.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Record {"); sb.append("id = ").append(id).append(", "); sb.append("title = ").append(title).append(", "); sb.append("type = "); switch (type) { case TYPE_EXPENSE: sb.append("expense"); break; case TYPE_INCOME: sb.append("income"); break; default: sb.append("unknown"); break; } sb.append(", "); sb.append("time = ").append(time).append(", "); sb.append("category = ").append(category).append(", "); sb.append("price = ").append(price).append(", "); sb.append("account = ").append(account).append(", "); sb.append("currency = ").append(currency).append(", "); sb.append("decimals = ").append(decimals); sb.append("}"); return sb.toString(); }
Source:
private void onRemove() { if (getWindow() != null) { return; } ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } model.startProgress(); AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery<>(storagePools -> { if (storagePools != null && !storagePools.isEmpty()) { StoragePool storagePool = storagePools.get(0); List<ActionParametersBase> prms = getRemoveUnregisteredEntityParams(storagePool.getId()); Frontend.getInstance().runMultipleAction( getRemoveActionType(), prms, result -> { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); cancel(); }, model); } }), getEntity().getId()); }

Target:
private void onRemove() { ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } model.startProgress(); AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery<>(storagePools -> { if (storagePools != null && !storagePools.isEmpty()) { StoragePool storagePool = storagePools.get(0); List<ActionParametersBase> removeUnregisteredEntityParams = getRemoveUnregisteredEntityParams(storagePool.getId()); Frontend.getInstance().runMultipleAction( getRemoveActionType(), removeUnregisteredEntityParams, result -> { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); cancel(); }, model); } }), getEntity().getId()); }
Source:
public String getRequestorName(UserNotification notification) { if(notification == null) return "Unavailable"; if(notification.getRequestor() == null) return "Unavailable"; return (notification.getRequestor().getLastName() != null && notification.getRequestor().getLastName() != null) ? notification.getRequestor().getFirstName() + " " + notification.getRequestor().getLastName() : "Unavailable"; }

Target:
public String getRequestorName(UserNotification notification) { if(notification == null) return BundleUtil.getStringFromBundle("notification.email.info.unavailable"); if(notification.getRequestor() == null) return BundleUtil.getStringFromBundle("notification.email.info.unavailable");; return (notification.getRequestor().getLastName() != null && notification.getRequestor().getLastName() != null) ? notification.getRequestor().getFirstName() + " " + notification.getRequestor().getLastName() : BundleUtil.getStringFromBundle("notification.email.info.unavailable"); }
Source:
private void synchronizeNics(VM vm, CompensationContext compensationContext, DbUser user, VmInterfaceManager vmInterfaceManager) { VnicProfileHelper vnicProfileHelper = new VnicProfileHelper(vm.getClusterId(), vm.getStoragePoolId(), AuditLogType.IMPORTEXPORT_SNAPSHOT_VM_INVALID_INTERFACES); MacPool macPool = vmInterfaceManager.getMacPool(); List<VmNic> dbNics = vmNicDao.getAllForVm(vm.getId()); List<VmNetworkInterface> newNics = vm.getInterfaces(); Map<String, Long> preexistingMacsUsageFrequency = countMacUsageFrequency(dbNics); Map<String, Long> macsFromRequestUsageFrequency = countMacUsageFrequency(newNics); vmInterfaceManager.removeAll(dbNics); releaseExtraMacs(macPool, preexistingMacsUsageFrequency, macsFromRequestUsageFrequency); allocateMacsMissingInMacPool(macPool, newNics, preexistingMacsUsageFrequency, macsFromRequestUsageFrequency); for (VmNetworkInterface vmInterface : newNics) { vmInterface.setVmId(vm.getId()); if (vmInterface.getId() == null) { vmInterface.setId(Guid.newGuid()); } vnicProfileHelper.updateNicWithVnicProfileForUser(vmInterface, user); vmInterfaceManager.persistIface(vmInterface, compensationContext); } vnicProfileHelper.auditInvalidInterfaces(vm.getName()); }

Target:
private void synchronizeNics(VM vm, CompensationContext compensationContext, DbUser user, VmInterfaceManager vmInterfaceManager) { VnicProfileHelper vnicProfileHelper = new VnicProfileHelper(vm.getClusterId(), vm.getStoragePoolId(), AuditLogType.IMPORTEXPORT_SNAPSHOT_VM_INVALID_INTERFACES); MacPool macPool = vmInterfaceManager.getMacPool(); List<VmNic> dbNics = vmNicDao.getAllForVm(vm.getId()); new SyncMacsInMacPool(macPool, auditLogDirector, dbNics, vm.getInterfaces()).sync(); vmInterfaceManager.removeAll(dbNics); for (VmNetworkInterface vmInterface : vm.getInterfaces()) { vmInterface.setVmId(vm.getId()); if (vmInterface.getId() == null) { vmInterface.setId(Guid.newGuid()); } vnicProfileHelper.updateNicWithVnicProfileForUser(vmInterface, user); vmInterfaceManager.persistIface(vmInterface, compensationContext); } vnicProfileHelper.auditInvalidInterfaces(vm.getName()); }
Source:
private void handleTask(Task task, Map<String, Object> parameters) { TaskContext taskContext = new TaskContext(task, parameters, activityService); TaskInitializer initializer = new TaskInitializer(taskContext); boolean success = true; try { LOGGER.info("Executing all actions from task: {}", task.getName()); if (initializer.evalConfigSteps(dataProviders)) { for (TaskActionInformation action : task.getActions()) { executor.execute(task, action, task.getActions().indexOf(action), taskContext); } handleSuccess(parameters, task); } LOGGER.warn("Actions from task: weren't executed, because config steps didn't pass the evaluation", task.getName()); } catch (TaskHandlerException e) { handleError(parameters, task, e); success = false; } catch (RuntimeException e) { handleError(parameters, task, new TaskHandlerException(TRIGGER, "task.error.unrecognizedError", e)); success = false; } if (task.retryTaskOnFailure()) { if (success && isTaskRetryAlreadyScheduled(parameters)) { unscheduleTaskRetry(task.getTrigger().getEffectiveListenerRetrySubject()); } else if (!success && !isTaskRetryAlreadyScheduled(parameters)) { scheduleTaskRetry(task, parameters); } } }

Target:
private void handleTask(Task task, Map<String, Object> parameters) { TaskContext taskContext = new TaskContext(task, parameters, activityService); TaskInitializer initializer = new TaskInitializer(taskContext); boolean success = true; try { LOGGER.info("Executing all actions from task: {}", task.getName()); if (initializer.evalConfigSteps(dataProviders)) { for (int i = 0; i < task.getActions().size(); i++) { executor.execute(task, task.getActions().get(i), i, taskContext); } handleSuccess(parameters, task); } LOGGER.warn("Actions from task: weren't executed, because config steps didn't pass the evaluation", task.getName()); } catch (TaskHandlerException e) { handleError(parameters, task, e); success = false; } catch (RuntimeException e) { handleError(parameters, task, new TaskHandlerException(TRIGGER, "task.error.unrecognizedError", e)); success = false; } if (task.retryTaskOnFailure()) { if (success && isTaskRetryAlreadyScheduled(parameters)) { unscheduleTaskRetry(task.getTrigger().getEffectiveListenerRetrySubject()); } else if (!success && !isTaskRetryAlreadyScheduled(parameters)) { scheduleTaskRetry(task, parameters); } } }
Source:
public void toParamDocs_Test() { final List<ParamDescriptor> pds = Arrays.asList( createParamDescriptor("1"), createParamDescriptor("2")); final ImmutableMap<String, String> result = toParamDocs(pds); assertThat(result.size(), is(2)); assertThat(result.get("Name1"), is("Description1")); assertThat(result.get("Name2"), is("Description2")); }

Target:
public void toParamDocs_Test() { final ImmutableList<ParamDescriptor> pds = ImmutableList.of( createParamDescriptor("1"), createParamDescriptor("2")); final ImmutableMap<String, String> result = toParamDocs(pds); assertThat(result.size(), is(2)); assertThat(result.get("Name1"), is("Description1")); assertThat(result.get("Name2"), is("Description2")); }
Source:
private List<Filter> makeFilters(BitmapIndexSelector selector) { final Indexed<String> allDimVals = selector.getDimensionValues(dimension); final List<Filter> filters = Lists.newArrayList(); if (allDimVals != null) { for (int i = 0; i < allDimVals.size(); i++) { String dimVal = allDimVals.get(i); if (value.equals(fn.apply(dimVal))) { filters.add(new SelectorFilter(dimension, dimVal)); } } } else if (value.equals(fn.apply(null))) { filters.add(new SelectorFilter(dimension, null)); } return filters; }

Target:
private List<Filter> makeFilters(BitmapIndexSelector selector) { Indexed<String> allDimVals = selector.getDimensionValues(dimension); final List<Filter> filters = Lists.newArrayList(); if (allDimVals == null) { allDimVals = new Indexed<String>() { @Override public Iterator<String> iterator() { return null; } @Override public Class<? extends String> getClazz() { return null; } @Override public int size() { return 1; } @Override public String get(int index) { return null;} @Override public int indexOf(String value) { return 0; } }; } for (int i = 0; i < allDimVals.size(); i++) { String dimVal = allDimVals.get(i); if (value.equals(Strings.nullToEmpty(fn.apply(dimVal)))) { filters.add(new SelectorFilter(dimension, dimVal)); } } return filters; }
Source:
public Object getChromedriverPorts() { return getCapability(AndroidMobileCapabilityType.BUILD_TOOLS_VERSION); }

Target:
public List<Object> getChromedriverPorts() { return (List<Object>) getCapability(AndroidMobileCapabilityType.CHROMEDRIVER_PORTS); }
Source:
private void showCallout(final Graphic graphic) { TextView calloutContent = new TextView(getApplicationContext()); calloutContent.setTextColor(Color.BLACK); calloutContent.setText(graphic.getAttributes().get("PlaceName").toString() + "\n" + graphic.getAttributes().get("StAddr").toString()); mCallout = mMapView.getCallout(); mCallout.setShowOptions(new Callout.ShowOptions(true, false, false)); mCallout.setContent(calloutContent); mCallout.setLocation(graphic.computeCalloutLocation(graphic.getGeometry().getExtent().getCenter(), mMapView)); mCallout.show(); mMapView.addMapScaleChangedListener(new MapScaleChangedListener() { @Override public void mapScaleChanged(MapScaleChangedEvent mapScaleChangedEvent) { if (mMapView.getCallout().isShowing()) { mCallout.setLocation(graphic.computeCalloutLocation(graphic.getGeometry().getExtent().getCenter(), mMapView)); mCallout.show(); } } }); }

Target:
private void showCallout(final Graphic graphic) { TextView calloutContent = new TextView(getApplicationContext()); calloutContent.setTextColor(Color.BLACK); calloutContent.setText(graphic.getAttributes().get("PlaceName").toString() + "\n" + graphic.getAttributes().get("StAddr").toString()); mCallout = mMapView.getCallout(); mCallout.setShowOptions(new Callout.ShowOptions(true, false, false)); mCallout.setContent(calloutContent); Point calloutLocation = graphic.computeCalloutLocation(graphic.getGeometry().getExtent().getCenter(), mMapView); mCallout.setGeoElement(graphic, calloutLocation); mCallout.show(); }
Source:
public void sessionEnded( ExecutionEvent event ) { if ( logger.isInfoEnabled() ) { if ( event.getSession().getProjects().size() > 1 ) { logReactorSummary( event.getSession() ); } ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory(); if ( iLoggerFactory instanceof MavenSlf4jWrapperFactory ) { MavenSlf4jWrapperFactory loggerFactory = (MavenSlf4jWrapperFactory) iLoggerFactory; loggerFactory.getLogLevelRecorder() .filter( LogLevelRecorder::isThresholdHit ) .ifPresent(recorder -> event.getSession().getResult().addException( new Exception( "Build failed due to log statements with a higher severity than allowed. " + "Fix the logged issues or remove flag --fail-level (-fl)." ) ) ); } logResult( event.getSession() ); logStats( event.getSession() ); infoLine( '-' ); } }

Target:
public void sessionEnded( ExecutionEvent event ) { if ( logger.isInfoEnabled() ) { if ( event.getSession().getProjects().size() > 1 ) { logReactorSummary( event.getSession() ); } ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory(); if ( iLoggerFactory instanceof MavenSlf4jWrapperFactory ) { MavenSlf4jWrapperFactory loggerFactory = (MavenSlf4jWrapperFactory) iLoggerFactory; loggerFactory.getLogLevelRecorder() .filter( LogLevelRecorder::metThreshold ) .ifPresent( recorder -> event.getSession().getResult().addException( new Exception( "Build failed due to log statements with a higher severity than allowed. " + "Fix the logged issues or remove flag --fail-on-severity (-fos)." ) ) ); } logResult( event.getSession() ); logStats( event.getSession() ); infoLine( '-' ); } }
Source:
protected Spec[] getSelectedSpecs() { List list = fileAssociationViewer.getStructuredSelection().toList(); return (Spec[]) list.toArray(new Spec[list.size()]); }

Target:
protected Spec[] getSelectedSpecs() { List<Spec> list = fileAssociationViewer.getStructuredSelection().toList(); return list.toArray(new Spec[list.size()]); }