auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static boolean sleep(SleepCondition conn, int timeout, int minimumTimeout) { long start = System.currentTimeMillis(); while (!conn.isValid()) { if (start + timeout < System.currentTimeMillis()) { return false; } Time.sleep(50); } long t; if((t = System.currentTimeMillis() - start) < minimumTimeout) { Time.sleep((int)(minimumTimeout - t)); } return true; }

Target:
public static boolean sleep(SleepCondition conn, int timeout, int minimumTimeout) { long start = System.currentTimeMillis(); if(!sleep(conn, timeout)) { return false; } long t; if((t = System.currentTimeMillis() - start) < minimumTimeout) { Time.sleep((int)(minimumTimeout - t)); } return true; }
Source:
public URL getLibraryIndexLocation() { switch(getEntryKind()) { case IClasspathEntry.CPE_LIBRARY : if (SHARED_INDEX_LOCATION != null) { try { String pathString = getPath().toOSString(); CRC32 checksumCalculator = new CRC32(); checksumCalculator.update(pathString.getBytes()); String fileName = Long.toString(checksumCalculator.getValue()) + ".index"; return new URL("file", null, Paths.get(SHARED_INDEX_LOCATION, fileName).toString()); } catch (MalformedURLException e1) { Util.log(e1); } } break; case IClasspathEntry.CPE_VARIABLE : break; default : return null; } if (this.extraAttributes == null) return null; for (int i= 0; i < this.extraAttributes.length; i++) { IClasspathAttribute attrib= this.extraAttributes[i]; if (IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME.equals(attrib.getName())) { String value = attrib.getValue(); try { return new URL(value); } catch (MalformedURLException e) { return null; } } } return null; }

Target:
public URL getLibraryIndexLocation() { switch(getEntryKind()) { case IClasspathEntry.CPE_LIBRARY : if (SHARED_INDEX_LOCATION != null) { try { String pathString = getPath().toPortableString(); CRC32 checksumCalculator = new CRC32(); checksumCalculator.update(pathString.getBytes()); String fileName = Long.toString(checksumCalculator.getValue()) + ".index"; return new URL("file", null, Paths.get(SHARED_INDEX_LOCATION, fileName).toString()); } catch (MalformedURLException e1) { Util.log(e1); } } break; case IClasspathEntry.CPE_VARIABLE : break; default : return null; } if (this.extraAttributes == null) return null; for (int i= 0; i < this.extraAttributes.length; i++) { IClasspathAttribute attrib= this.extraAttributes[i]; if (IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME.equals(attrib.getName())) { String value = attrib.getValue(); try { return new URL(value); } catch (MalformedURLException e) { return null; } } } return null; }
Source:
public void setCommodity(@NonNull String currencyCode){ mCommodity = Commodity.getInstance(currencyCode); }

Target:
private void setCommodity(@NonNull String currencyCode){ mCommodity = Commodity.getInstance(currencyCode); }
Source:
public void testEscapingTakesPlace() { final PrintWriterComparator comparator = new PrintWriterComparator(); final ColumnFormatter formatter = new ColumnFormatter(comparator.getPrintWriter(), "\t"); formatter.addColumn("foo"); formatter.addColumn("a multi-line\ntext with a null character: \u0000"); formatter.nextLine(); formatter.finish(); comparator.assertEquals( "foo\ta multi-line\\ntext with a null character: \\x00\n"); }

Target:
public void testEscapingTakesPlace() { final PrintWriterComparator comparator = new PrintWriterComparator(); final ColumnFormatter formatter = new ColumnFormatter(comparator.getPrintWriter(), "\t"); formatter.addColumn("foo"); formatter.addColumn( "\tan indented multi-line\ntext with a null character: \u0000"); formatter.nextLine(); formatter.finish(); comparator.assertEquals( "foo\t\\tan indented multi-line\\ntext with a null character: \\x00\n"); }
Source:
public static Track getAirhornTrack() { if (airhornTrack == null) { airhornTrack = new Track("/Users/daveystruijk/Documents/FEESJE/Samples/Random - airhorn1.mp3"); } return airhornTrack; }

Target:
public static Track getAirhornTrack() { if (airhornTrack == null) { airhornTrack = new Track(AirhornProcessor.class.getClass() .getResource("/samples/airhorn.mp3").getPath()); } return airhornTrack; }
Source:
private boolean clusterPresentInTopology(TopologyDescriptor topology) { localClusterDescriptor = topology.getClusterDescriptor(localEndpoint); if (localClusterDescriptor != null) { localNodeDescriptor = localClusterDescriptor.getNode(localEndpoint); return true; } return false; }

Target:
private boolean clusterPresentInTopology(TopologyDescriptor topology) { localClusterDescriptor = topology.getClusterDescriptor(localEndpoint); if (localClusterDescriptor != null) { localNodeDescriptor = localClusterDescriptor.getNode(localEndpoint); localCorfuEndpoint = getCorfuEndpoint(getLocalHost(), localClusterDescriptor.getCorfuPort()); } return localClusterDescriptor != null && localNodeDescriptor != null; }
Source:
private String extractHosts(String uri) { return new String {}; }

Target:
private String extractHosts(String uri) { return new String[] {ConnectionInfo.fromURI(uri).host}; }
Source:
public void onNext(final AggregationMessage aggregationMessage) { final AvroClockMsg avroClockMsg = codec.decode(aggregationMessage.getData().array()); switch (avroClockMsg.getType()) { case ReplyInitClockMsg: globalMinimumClock = avroClockMsg.getReplyInitClockMsg().getGlobalMinClock(); workerClock = avroClockMsg.getReplyInitClockMsg().getInitClock(); initLatch.countDown(); break; case BroadcastMinClockMsg: globalMinimumClock = avroClockMsg.getBroadcastMinClockMsg().getGlobalMinClock(); globalMinClockLatch.countDown(); globalMinClockLatch = new CountDownLatch(1); break; default: throw new RuntimeException("Unexpected message type: " + avroClockMsg.getType().toString()); } }

Target:
public void onNext(final AggregationMessage aggregationMessage) { final AvroClockMsg avroClockMsg = codec.decode(aggregationMessage.getData().array()); switch (avroClockMsg.getType()) { case ReplyInitClockMsg: globalMinimumClock = avroClockMsg.getReplyInitClockMsg().getGlobalMinClock(); workerClock = avroClockMsg.getReplyInitClockMsg().getInitClock(); initLatch.countDown(); break; case BroadcastMinClockMsg: updateGlobalMinimumClock(avroClockMsg.getBroadcastMinClockMsg().getGlobalMinClock()); break; default: throw new RuntimeException("Unexpected message type: " + avroClockMsg.getType().toString()); } }
Source:
private Rp sync(Rp rp) { if (!shouldSync(rp)) return rp; try { final RegisterResponse response = getClientMetadataFromOP(rp.getClientRegistrationClientUri(), rp.getClientRegistrationAccessToken()); if (RegisterResponseMapper.hasClientMetadataChangedAtOp(rp, response)) { persistenceService.update(rp); } LOG.debug("Successfully synced Rp object from OP. Rp: " + rp.toString()); return rp; } catch (Exception e) { LOG.error("Error in sync Rp object from OP: ", e); return rp; } }

Target:
private Rp sync(Rp rp) { if (!shouldSync(rp)) return rp; try { final RegisterResponse response = readClientFromRp(rp.getClientRegistrationClientUri(), rp.getClientRegistrationAccessToken()); boolean isRpUpdated = RegisterResponseMapper.fillRp(rp, response); if (isRpUpdated) { rp.setLastSynced(new Date()); persistenceService.update(rp); LOG.debug("Successfully synced Rp object from OP. Rp: " + rp.toString()); } return rp; } catch (Exception e) { LOG.error("Error in sync Rp object from OP: ", e); return rp; } }
Source:
protected Result convert(DocumentToConceptIds source) { if (CollectionUtils.isNotEmpty(source.getConcepts())) { Result result = new Result(); result.setId(source.getDocumentId().toString()); List<Context> contexts = new ArrayList<Context>(source.getConcepts().size()); for (Concept concept : source.getConcepts()) { Context context = new Context(); context.setId(concept.getId().toString()); context.setDataInfo(Arrays.asList(buildInferenceForTrustLevel(StaticConfigurationProvider.ACTION_TRUST_0_9))); contexts.add(context); } result.setContext(contexts); return result; } else { return null; } }

Target:
protected Result convert(DocumentToConceptIds source) { if (CollectionUtils.isNotEmpty(source.getConcepts())) { Result result = new Result(); result.setId(source.getDocumentId().toString()); List<Context> contexts = new ArrayList<Context>(source.getConcepts().size()); for (Concept concept : source.getConcepts()) { Context context = new Context(); context.setId(concept.getId().toString()); context.setDataInfo(Collections.singletonList(buildInferenceForTrustLevel(StaticConfigurationProvider.ACTION_TRUST_0_9))); contexts.add(context); } result.setContext(contexts); return result; } else { return null; } }
Source:
public void setCommitId(String commitId) { ModelNode node = this.getNode(); ModelNode git = new ModelNode(); ModelNode author = new ModelNode(); ModelNode committer = new ModelNode(); ModelNode commit = new ModelNode(commitId); git.get(AUTHOR).set(author); git.get(COMMITTER).set(committer); git.get(COMMIT).set(commit); ModelNode revision = new ModelNode(); revision.get(GIT).set(git); revision.get(TYPE).set(BIGGIT); node.get(REVISION).set(revision); }

Target:
public void setCommitId(String commitId) { set(REVISION_TYPE, BIGGIT); set(REVISION_GIT_COMMIT, commitId); }
Source:
protected void precommitCheckPendingFiles( final JobContext context, final ActiveCommit pending) throws IOException { FileSystem sourceFS = pending.getSourceFS(); try (DurationInfo ignored = new DurationInfo(LOG, "Preflight Load of pending files")) { Tasks.foreach(pending.getSourceFiles()) .stopOnFailure() .executeWith(buildThreadPool(context)) .run(path -> PendingSet.load(sourceFS, path)); } }

Target:
protected void precommitCheckPendingFiles( final JobContext context, final ActiveCommit pending) throws IOException { FileSystem sourceFS = pending.getSourceFS(); try (DurationInfo ignored = new DurationInfo(LOG, "Preflight Load of pending files")) { Tasks.foreach(pending.getSourceFiles()) .stopOnFailure() .suppressExceptions(false) .executeWith(buildThreadPool(context)) .run(path -> PendingSet.load(sourceFS, path)); } }
Source:
public void transform(NodeType node) { if (ComponentUtilities.getNodeProperty(node, name) == null) { ComponentUtilities.addNodeProperty(node, name, field); ComponentUtilities.setNodeValue(node, name, "false"); } }

Target:
public void transform(NodeType node) { if (ComponentUtilities.getNodeProperty(node, name) == null) { ComponentUtilities.addNodeProperty(node, name, field); ComponentUtilities.setNodeValue(node, name, "true"); } }
Source:
public void onPlaybackComplete() { try{ if(player!=null){ double current_time = player.getCurrentPosition()/AppConstants.MILLISECONDS_PER_SECOND ; environment.getAnalyticsRegistry().trackVideoStop(videoEntry.videoId, current_time, videoEntry.eid, videoEntry.lmsUrl); } }catch(Exception e){ logger.error(e); } if (callback != null) { callback.saveCurrentPlaybackPosition(0); callback.onPlaybackComplete(); } hideCCPopUp(); hideSettingsPopUp(); try{ if(player!=null){ if(player.getController()!=null){ player.getController().showSpecial( (getTouchExploreEnabled() ? 0L : 5000L) ); } } } catch(Exception e) { logger.error(e); } if (environment.getConfig().isAppReviewsEnabled() && NetworkUtil.isConnected(getContext())) { PrefManager.UserPrefManager userPrefs = new PrefManager.UserPrefManager(MainApplication.application); final float appRating = userPrefs.getAppRating(); if (appRating <= 0.0f) { showRatingDialog(); } else if (appRating <= 3.0f) { try { Version oldVersion = new Version(userPrefs.getVersionWhenLastRated()); Version curVersion = new Version(BuildConfig.VERSION_NAME); if (oldVersion.isNMinorVersionsDiff(curVersion, 2)) { showRatingDialog(); } } catch (ParseException e) { logger.error(e, true); } } } }

Target:
public void onPlaybackComplete() { try{ if(player!=null){ double current_time = player.getCurrentPosition()/AppConstants.MILLISECONDS_PER_SECOND ; environment.getAnalyticsRegistry().trackVideoStop(videoEntry.videoId, current_time, videoEntry.eid, videoEntry.lmsUrl); } }catch(Exception e){ logger.error(e); } if (callback != null) { callback.saveCurrentPlaybackPosition(0); callback.onPlaybackComplete(); } hideCCPopUp(); hideSettingsPopUp(); try{ if(player!=null){ if(player.getController()!=null){ player.getController().showSpecial( (getTouchExploreEnabled() ? 0L : 5000L) ); } } }catch(Exception e){ logger.error(e); } if (!environment.getConfig().getAppStoreUris().isEmpty() && environment.getConfig().isAppReviewsEnabled() && NetworkUtil.isConnected(getContext())) { final PrefManager.UserPrefManager userPrefs = new PrefManager.UserPrefManager(MainApplication.application); final float appRating = userPrefs.getAppRating(); if (appRating <= AppConstants.APP_NOT_RATED_THRESHOLD) { showRatingDialog(); } else if (appRating <= AppConstants.APP_NEGATIVE_RATING_THRESHOLD) { try { final Version oldVersion = new Version(userPrefs.getLastRatedVersion()); final Version curVersion = new Version(BuildConfig.VERSION_NAME); if (oldVersion.isNMinorVersionsDiff(curVersion, AppConstants.MINOR_VERSIONS_DIFF_REQUIRED_FOR_NEGATIVE_RATERS)) { showRatingDialog(); } } catch (ParseException e) { logger.error(e, true); } } } }
Source:
public void onChildRemoved(Object parentElement, Object childElement) { ChildNodeRemovedEvent message = new ChildNodeRemovedEvent(); message.parentNodeId = getOrCreateNodeIdForElement(parentElement); message.nodeId = getOrCreateNodeIdForElement(childElement); mPeerManager.sendNotificationToPeers("DOM.childNodeRemoved", message); unhookElement(childElement); }

Target:
public void onChildRemoved(Object parentElement, Object childElement) { ChildNodeRemovedEvent message = new ChildNodeRemovedEvent(); message.parentNodeId = mObjectIdMapper.getIdForObject(parentElement); message.nodeId = mObjectIdMapper.getIdForObject(childElement); mPeerManager.sendNotificationToPeers("DOM.childNodeRemoved", message); removeElementTree(childElement); }
Source:
public PolicyResponse processPreUpdate(Metacard newMetacard, Map<String, Serializable> properties) throws StopProcessingException { if (!newMetacard.getTags().isEmpty() && !newMetacard.getTags().contains("resource")) { return new PolicyResponseImpl(); } List<Metacard> previousStateMetacards = ((OperationTransaction) properties.get(OPERATION_TRANSACTION_KEY)) .getPreviousStateMetacards(); Metacard previous; previous = previousStateMetacards .stream() .filter((x) -> x.getId().equals(newMetacard.getId())) .findFirst() .orElse(null); return pointOfContactChanged(newMetacard, previous) ? new PolicyResponseImpl(null, PERMISSION_MAP) : new PolicyResponseImpl(); }

Target:
public PolicyResponse processPreUpdate(Metacard newMetacard, Map<String, Serializable> properties) throws StopProcessingException { if (!newMetacard.getTags().isEmpty() && !newMetacard.getTags().contains("resource")) { return new PolicyResponseImpl(); } List<Metacard> previousStateMetacards = ((OperationTransaction) properties.get(OPERATION_TRANSACTION_KEY)) .getPreviousStateMetacards(); Metacard previous; previous = previousStateMetacards .stream() .filter(x -> x.getId().equals(newMetacard.getId())) .findFirst() .orElse(null); return pointOfContactChanged(newMetacard, previous) ? new PolicyResponseImpl(null, PERMISSION_MAP) : new PolicyResponseImpl(); }
Source:
protected Builder( final Content source ) { this.id = source.getId(); this.valid = source.isValid(); this.parentPath = source.getParentPath(); this.name = source.getName(); this.type = source.getType(); this.data = source.getData() != null ? source.getData().copy() : null; this.attachments = source.getAttachments(); this.extraDatas = source.getAllExtraData() != null ? source.getAllExtraData().copy() : null; this.displayName = source.getDisplayName(); this.owner = source.getOwner(); this.createdTime = source.getCreatedTime(); this.modifiedTime = source.getModifiedTime(); this.creator = source.getCreator(); this.modifier = source.getModifier(); this.hasChildren = source.hasChildren(); this.page = source.getPage() != null ? source.getPage().copy() : null; this.thumbnail = source.getThumbnail(); this.childOrder = source.getChildOrder(); this.permissions = source.getPermissions(); this.inheritPermissions = source.inheritsPermissions(); this.language = source.getLanguage(); this.contentState = source.getContentState(); this.publishInfo = source.getPublishInfo(); this.processedReferences = ContentIds.create().addAll( source.getProcessedReferences() ); this.workflowInfo = source.getWorkflowInfo(); }

Target:
protected Builder( final Content source ) { this.id = source.id; this.valid = source.valid; this.parentPath = source.parentPath; this.name = source.name; this.type = source.type; this.data = source.data != null ? source.data.copy() : null; this.attachments = source.attachments; this.extraDatas = source.extraDatas != null ? source.extraDatas.copy() : null; this.displayName = source.displayName; this.owner = source.owner; this.createdTime = source.createdTime; this.modifiedTime = source.modifiedTime; this.creator = source.creator; this.modifier = source.modifier; this.hasChildren = source.hasChildren; this.page = source.page != null ? source.page.copy() : null; this.thumbnail = source.thumbnail; this.childOrder = source.childOrder; this.permissions = source.permissions; this.inheritPermissions = source.inheritPermissions; this.language = source.language; this.contentState = source.contentState; this.publishInfo = source.publishInfo; this.processedReferences = ContentIds.create().addAll( source.processedReferences ); this.workflowInfo = source.workflowInfo; }
Source:
private String getReadValueErrMsg(final String details) { return String.format( "Could not read value from %s.", XmlNodeType.getString(this.presentEvent.getEventType()) ) + details; }

Target:
private String getReadValueErrMsg(final String details) { final int eventType = this.presentEvent.getEventType(); return "Could not read value from " + XmlNodeType.getString(eventType) + "." + details; }
Source:
public void callAsync(long delay, TimeUnit timeUnit, Runnable r) { long deadline = timeUnit.toMillis(delay) + currentTimeMillis(); executor.submit(delayedExcution(r, deadline)); }

Target:
public void callAsync(long delay, TimeUnit timeUnit, Runnable r) { long deadline = timeUnit.toMillis(delay) + currentTimeMillis(); executor.submit(delayedExecution(r, deadline)); }
Source:
private boolean validateInjectable(Element injectable) { Element injectableType = injectable.getEnclosingElement(); if (injectable.getModifiers().contains(Modifier.PRIVATE)) { error("Can't inject a private field or constructor: " + injectableType + "." + injectable, injectable); return false; } if (injectable.getKind() == ElementKind.METHOD) { error("Method injection is not supported: " + injectableType + "." + injectable, injectable); return false; } ElementKind elementKind = injectableType.getEnclosingElement().getKind(); boolean isClassOrInterface = elementKind.isClass() || elementKind.isInterface(); boolean isStatic = injectableType.getModifiers().contains(Modifier.STATIC); if (isClassOrInterface && !isStatic) { error("Can't inject a non-static inner class: " + injectableType, injectableType); return false; } return true; }

Target:
private boolean validateInjectable(Element injectable) { Element injectableType = injectable.getEnclosingElement(); if (injectable.getKind() == ElementKind.METHOD) { error("Method injection is not supported: " + injectableType + "." + injectable, injectable); return false; } if (injectable.getModifiers().contains(Modifier.PRIVATE)) { error("Can't inject a private field or constructor: " + injectableType + "." + injectable, injectable); return false; } ElementKind elementKind = injectableType.getEnclosingElement().getKind(); boolean isClassOrInterface = elementKind.isClass() || elementKind.isInterface(); boolean isStatic = injectableType.getModifiers().contains(Modifier.STATIC); if (isClassOrInterface && !isStatic) { error("Can't inject a non-static inner class: " + injectableType, injectableType); return false; } return true; }
Source:
public void testPowerOffDroplet() { int event = api.getDropletApi().powerOff(droplet.getId()); assertTrue(event > 0, "The event id should not be null"); waitForEvent(event); }

Target:
public void testPowerOffDroplet() { int event = api.getDropletApi().powerOff(droplet.getId()); assertTrue(event > 0, "The event id should be > 0"); waitForEvent(event); }
Source:
public Response intercept(Chain chain) throws IOException { RequestBody body = chain.request().body(); if (body != null) { Preconditions.checkArgument(body.contentLength() < MAX_PAYLOAD_SIZE, String.format("Request too large. Maximum allowed size is %s bytes, but the request has %s.", MAX_PAYLOAD_SIZE, body.contentLength())); } return chain.proceed(chain.request()); }

Target:
public Response intercept(Chain chain) throws IOException { RequestBody body = chain.request().body(); if (body != null && body.contentLength() >= MAX_PAYLOAD_SIZE) { throw new SafeIllegalArgumentException( "Request too large. Maximum allowed payload size is bytes, but the request has {}.", SafeArg.of("maximumSize", MAX_PAYLOAD_SIZE), SafeArg.of("actualSize", body.contentLength())); } return chain.proceed(chain.request()); }
Source:
void openInventory(Inventory inventory, Cause cause) throws IllegalArgumentException; void closeInventory(Cause cause) throws IllegalArgumentException; int getViewDistance(); ChatVisibility getChatVisibility(); boolean isChatColorsEnabled(); MessageChannelEvent.Chat chat(Text message); Set<SkinPart> getDisplayedSkinParts(); @Override PlayerConnection getConnection(); void sendResourcePack(ResourcePack pack); TabList getTabList(); void kick(); void kick(Text reason); Scoreboard getScoreboard(); void setScoreboard(Scoreboard scoreboard); default JoinData getJoinData() { return get(JoinData.class).get(); }

Target:
Optional<Container> openInventory(Inventory inventory, Cause cause) throws IllegalArgumentException; boolean closeInventory(Cause cause) throws IllegalArgumentException; int getViewDistance(); ChatVisibility getChatVisibility(); boolean isChatColorsEnabled(); MessageChannelEvent.Chat simulateChat(Text message, Cause cause); Set<SkinPart> getDisplayedSkinParts(); @Override PlayerConnection getConnection(); void sendResourcePack(ResourcePack pack); TabList getTabList(); void kick(); void kick(Text reason); Scoreboard getScoreboard(); void setScoreboard(Scoreboard scoreboard); default JoinData getJoinData() { return get(JoinData.class).get(); }
Source:
protected void executeCommand() { VdsValidator validator; setVds(null); if (getVds() == null) { setCommandShouldBeLogged(false); log.infoFormat("SSH Soft Fencing will not be executed on host {0}({1}) since it doesn't exist anymore.", getVdsName(), getVdsId()); getReturnValue().setSucceeded(false); return; } validator = new VdsValidator(getVds()); if (validator.shouldVdsBeFenced()) { boolean result = executeSshSoftFencingCommand(getVds().getHostName(), getVds().getVdsGroupCompatibilityVersion().toString()); if (result) { ResourceManager.getInstance().GetVdsManager(getVds().getId()).finishSshSoftFencingExecution(getVds()); } getReturnValue().setSucceeded(result); } else { setCommandShouldBeLogged(false); log.infoFormat("SSH Soft Fencing will not be executed on host {0}({1}) since it's status is ok.", getVdsName(), getVdsId()); getReturnValue().setSucceeded(false); } }

Target:
protected void executeCommand() { setVds(null); if (getVds() == null) { setCommandShouldBeLogged(false); log.infoFormat("SSH Soft Fencing will not be executed on host {0}({1}) since it doesn't exist anymore.", getVdsName(), getVdsId()); getReturnValue().setSucceeded(false); return; } VdsValidator validator = new VdsValidator(getVds()); if (validator.shouldVdsBeFenced()) { boolean result = executeSshSoftFencingCommand(getVds().getHostName(), getVds().getVdsGroupCompatibilityVersion().toString()); if (result) { ResourceManager.getInstance().GetVdsManager(getVds().getId()).finishSshSoftFencingExecution(getVds()); } getReturnValue().setSucceeded(result); } else { setCommandShouldBeLogged(false); log.infoFormat("SSH Soft Fencing will not be executed on host {0}({1}) since it's status is ok.", getVdsName(), getVdsId()); getReturnValue().setSucceeded(false); } }
Source:
public PositionalFilter(StructFilter parent) { super(false); this.parent = parent; }

Target:
public PositionalFilter(StructFilter parent) { super(false); this.parent = requireNonNull(parent, "parent is null"); }
Source:
public void checkValueReferenedBeforeDefined(Scope scope) { EList<Declaration> declarations = scope.getDeclarations(); Set<QualifiedName> defined = Sets.newHashSet(); for (Declaration declaration : declarations) { if (!(declaration instanceof VariableDefinition)) { continue; } VariableDefinition definition = (VariableDefinition) declaration; if (!definition.isConst()) return; Expression initialValue = definition.getInitialValue(); List<Expression> toCheck = Lists.newArrayList(initialValue); TreeIterator<EObject> eAllContents = initialValue.eAllContents(); while (eAllContents.hasNext()) { EObject next = eAllContents.next(); if (next instanceof Expression) toCheck.add((Expression) next); } for (Expression expression : toCheck) { EObject referencedObject = null; if (expression instanceof FeatureCall) referencedObject = ((FeatureCall) expression).getFeature(); else if (expression instanceof ElementReferenceExpression) referencedObject = ((ElementReferenceExpression) expression).getReference(); if (referencedObject instanceof VariableDefinition) { if (!defined.contains(nameProvider.getFullyQualifiedName(referencedObject))) error(REFERENCE_CONSTANT_BEFORE_DEFINED, definition, TypesPackage.Literals.PROPERTY__INITIAL_VALUE); } } defined.add(nameProvider.getFullyQualifiedName(definition)); } }

Target:
public void checkValueReferenedBeforeDefined(Scope scope) { EList<Declaration> declarations = scope.getDeclarations(); Set<QualifiedName> defined = Sets.newHashSet(); for (Declaration declaration : declarations) { if (declaration instanceof VariableDefinition) { VariableDefinition definition = (VariableDefinition) declaration; if (!definition.isConst()) return; Expression initialValue = definition.getInitialValue(); List<Expression> toCheck = Lists.newArrayList(initialValue); TreeIterator<EObject> eAllContents = initialValue.eAllContents(); while (eAllContents.hasNext()) { EObject next = eAllContents.next(); if (next instanceof Expression) toCheck.add((Expression) next); } for (Expression expression : toCheck) { EObject referencedObject = null; if (expression instanceof FeatureCall) referencedObject = ((FeatureCall) expression).getFeature(); else if (expression instanceof ElementReferenceExpression) referencedObject = ((ElementReferenceExpression) expression).getReference(); if (referencedObject instanceof VariableDefinition) { if (!defined.contains(nameProvider.getFullyQualifiedName(referencedObject))) error(REFERENCE_CONSTANT_BEFORE_DEFINED, definition, TypesPackage.Literals.PROPERTY__INITIAL_VALUE); } } defined.add(nameProvider.getFullyQualifiedName(definition)); } } }
Source:
public void afterChunk(ChunkContext context) { Object lines = context.getStepContext().getStepExecutionContext() .get(ExecutionContextParametersNames.NUMBER_OF_LINES); long estimatedTotalNumberOfLines = lines != null? (long) lines : 0; long read = context.getStepContext().getStepExecution().getReadCount(); long write = context.getStepContext().getStepExecution().getWriteCount(); long skip = context.getStepContext().getStepExecution().getReadSkipCount() + context.getStepContext().getStepExecution().getProcessSkipCount() + context.getStepContext().getStepExecution().getWriteSkipCount(); String chunkStatisticsMessage = "Items read = " + read + ", items written = " + write + ", items skipped = " + skip; String stepName = context.getStepContext().getStepName() + ": "; if (estimatedTotalNumberOfLines != 0) { int percent = (int) ((read * 100) / estimatedTotalNumberOfLines); logger.info(stepName + percent + "% complete: " + chunkStatisticsMessage); } else { logger.info(stepName + chunkStatisticsMessage); } }

Target:
public void afterChunk(ChunkContext context) { long estimatedTotalNumberOfLines = (long) context.getStepContext().getStepExecutionContext() .getOrDefault(ExecutionContextParametersNames.NUMBER_OF_LINES, 0L); long read = context.getStepContext().getStepExecution().getReadCount(); long write = context.getStepContext().getStepExecution().getWriteCount(); long skip = context.getStepContext().getStepExecution().getReadSkipCount() + context.getStepContext().getStepExecution().getProcessSkipCount() + context.getStepContext().getStepExecution().getWriteSkipCount(); String chunkStatisticsMessage = "Items read = " + read + ", items written = " + write + ", items skipped = " + skip; String stepName = context.getStepContext().getStepName() + ": "; if (estimatedTotalNumberOfLines != 0) { int percent = (int) ((read * 100) / estimatedTotalNumberOfLines); logger.info(stepName + percent + "% complete: " + chunkStatisticsMessage); } else { logger.info(stepName + chunkStatisticsMessage); } }
Source:
private void testCodec(final int offset, final int bitsPerValue, final int[] values) throws IOException { try (final ByteArrayOutputStream os = new ByteArrayOutputStream(); final BitOutputStream bos = new DefaultBitOutputStream(os)) { final CRAMCodec<Integer> writeCodec = new BetaIntegerCodec(null, bos, offset, bitsPerValue); for (final int value : values) { writeCodec.write(value); } final int[] actual = new int[values.length]; try (final InputStream is = new ByteArrayInputStream(os.toByteArray()); final DefaultBitInputStream dbis = new DefaultBitInputStream(is)) { final CRAMCodec<Integer> readCodec = new BetaIntegerCodec(dbis, null, offset, bitsPerValue); for (int i = 0; i < values.length; i++) { actual[i] = readCodec.read(); } } Assert.assertEquals(actual, values); } }

Target:
private void testCodec(final int offset, final int bitsPerValue, final int[] values) throws IOException { byte[] written; try (final ByteArrayOutputStream os = new ByteArrayOutputStream(); final BitOutputStream bos = new DefaultBitOutputStream(os)) { final CRAMCodec<Integer> writeCodec = new BetaIntegerCodec(null, bos, offset, bitsPerValue); for (final int value : values) { writeCodec.write(value); } bos.flush(); written = os.toByteArray(); } final int[] actual = new int[values.length]; try (final InputStream is = new ByteArrayInputStream(written); final DefaultBitInputStream dbis = new DefaultBitInputStream(is)) { final CRAMCodec<Integer> readCodec = new BetaIntegerCodec(dbis, null, offset, bitsPerValue); for (int i = 0; i < values.length; i++) { actual[i] = readCodec.read(); } } Assert.assertEquals(actual, values); }
Source:
private ApiResponseSet<String> alertToSet(Alert alert) { Map<String, String> map = new HashMap<>(); map.put("id", String.valueOf(alert.getAlertId())); map.put("pluginId", String.valueOf(alert.getPluginId())); map.put("alert", alert.getName()); map.put("name", alert.getName()); map.put("description", alert.getDescription()); map.put("risk", Alert.MSG_RISK[alert.getRisk()]); map.put("confidence", Alert.MSG_CONFIDENCE[alert.getConfidence()]); map.put("url", alert.getUri()); map.put("method", alert.getMethod()); map.put("other", alert.getOtherInfo()); map.put("param", alert.getParam()); map.put("attack", alert.getAttack()); map.put("evidence", alert.getEvidence()); map.put("reference", alert.getReference()); map.put("cweid", String.valueOf(alert.getCweId())); map.put("wascid", String.valueOf(alert.getWascId())); map.put("sourceid", String.valueOf(alert.getSource().getId())); map.put("solution", alert.getSolution()); if (alert.getHistoryRef() != null) { map.put("messageId", String.valueOf(alert.getHistoryRef().getHistoryId())); } else { map.put("messageId", ""); } return new ApiResponseSet<String>("alert", map); }

Target:
private ApiResponseSet<String> alertToSet(Alert alert) { Map<String, String> map = new HashMap<>(); map.put("id", String.valueOf(alert.getAlertId())); map.put("pluginId", String.valueOf(alert.getPluginId())); map.put("alert", alert.getName()); map.put("name", alert.getName()); map.put("description", alert.getDescription()); map.put("risk", Alert.MSG_RISK[alert.getRisk()]); map.put("confidence", Alert.MSG_CONFIDENCE[alert.getConfidence()]); map.put("url", alert.getUri()); map.put("method", alert.getMethod()); map.put("other", alert.getOtherInfo()); map.put("param", alert.getParam()); map.put("attack", alert.getAttack()); map.put("evidence", alert.getEvidence()); map.put("reference", alert.getReference()); map.put("cweid", String.valueOf(alert.getCweId())); map.put("wascid", String.valueOf(alert.getWascId())); map.put("sourceid", String.valueOf(alert.getSource().getId())); map.put("solution", alert.getSolution()); map.put("messageId", (alert.getHistoryRef() != null) ? String.valueOf(alert.getHistoryRef().getHistoryId()) : ""); return new ApiResponseSet<String>("alert", map); }
Source:
private void handleStartIntent(Intent intent) { if (pendingShare != null) { awaitShare(); return; } final String action = intent.getAction(); if ((action == null) || !(action.equals(Intent.ACTION_SEND) || action.equals(Intent.ACTION_VIEW))) return; Uri videoUri; if (action.equals(Intent.ACTION_SEND)) { videoUri = getYouTubeUri(intent.getStringExtra(Intent.EXTRA_TEXT)); } else { videoUri = intent.getData(); } if (videoUri == null) return; String videoUrl = toPluginUrl(videoUri); if (videoUrl == null) { videoUrl = videoUri.toString(); } String host_name = intent.getStringExtra("host.name"); if (host_name != null) { HostManager hostManager = HostManager.getInstance(this); for (HostInfo host : hostManager.getHosts()) { if (host.getName().equals(host_name)) { hostManager.switchHost(host); break; } } } String title = getString(R.string.app_name); String text = getString(R.string.item_added_to_playlist); pendingShare = getShareExecutor().submit(new OpenSharedUrl(hostManager.getConnection(), videoUrl, title, text)); awaitShare(); intent.setAction(null); }

Target:
private void handleStartIntent(Intent intent) { if (pendingShare != null) { awaitShare(); return; } final String action = intent.getAction(); if ((action == null) || !(action.equals(Intent.ACTION_SEND) || action.equals(Intent.ACTION_VIEW))) return; Uri videoUri; if (action.equals(Intent.ACTION_SEND)) { videoUri = getYouTubeUri(intent.getStringExtra(Intent.EXTRA_TEXT)); } else { videoUri = intent.getData(); } if (videoUri == null) return; String videoUrl = toPluginUrl(videoUri); if (videoUrl == null) { videoUrl = videoUri.toString(); } int hostId = intent.getIntExtra("hostId", 0); if (hostId > 0) { HostManager hostManager = HostManager.getInstance(this); for (HostInfo host : hostManager.getHosts()) { if (host.getId() == hostId) { hostManager.switchHost(host); break; } } } String title = getString(R.string.app_name); String text = getString(R.string.item_added_to_playlist); pendingShare = getShareExecutor().submit(new OpenSharedUrl(hostManager.getConnection(), videoUrl, title, text)); awaitShare(); intent.setAction(null); }
Source:
private List<String> queryMetadata(String query) { ImmutableList.Builder<String> cache = ImmutableList.builder(); try (StatementClient client = queryRunner.startInternalQuery(query)) { while (client.isRunning()) { if (Thread.currentThread().isInterrupted()) { client.close(); break; } QueryData results = client.currentData(); if (results.getData() != null) { for (List<Object> row : results.getData()) { cache.add((String) row.get(0)); } } client.advance(); } } return cache.build(); }

Target:
private List<String> queryMetadata(String query) { ImmutableList.Builder<String> cache = ImmutableList.builder(); try (StatementClient client = queryRunner.startInternalQuery(query)) { while (client.isRunning() && !Thread.currentThread().isInterrupted()) { QueryData results = client.currentData(); if (results.getData() != null) { for (List<Object> row : results.getData()) { cache.add((String) row.get(0)); } } client.advance(); } } return cache.build(); }
Source:
private boolean performPermissionRequest(IField field) { if (field instanceof AudioRecordingField && !Permissions.canRecordAudio(this)) { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.RECORD_AUDIO}, REQUEST_AUDIO_PERMISSION); return true; } if (field instanceof ImageField && !Permissions.canUseCamera(this)) { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION); return true; } return false; }

Target:
private boolean performPermissionRequest(IField field) { if (field instanceof AudioRecordingField && !Permissions.canRecordAudio(this)) { Timber.d("Requesting Audio Permissions"); ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.RECORD_AUDIO}, REQUEST_AUDIO_PERMISSION); return true; } if (field instanceof ImageField && !Permissions.canUseCamera(this)) { Timber.d("Requesting Camera Permissions"); ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION); return true; } return false; }
Source:
public VertxProxyConnection write(Buffer chunk) { if (! headersWritten) { HttpHeaders headers = proxyRequest.headers(); String encoding = headers.getFirst(HttpHeaders.TRANSFER_ENCODING); if (encoding != null && encoding.contains(HttpHeadersValues.TRANSFER_ENCODING_CHUNKED)) { httpClientRequest.setChunked(true); } this.writeHeaders(); } httpClientRequest.write(io.vertx.core.buffer.Buffer.buffer(chunk.getBytes())); return this; }

Target:
public VertxProxyConnection write(Buffer chunk) { content = true; if (! headersWritten) { this.writeHeaders(); } httpClientRequest.write(io.vertx.core.buffer.Buffer.buffer(chunk.getBytes())); return this; }
Source:
public void sendsMail() throws Exception { final Postman postman = Mockito.spy(Postman.CONSOLE); final Profile profile = this.profile(); final Agent agent = new Mails( profile, postman ); final Talk talk = MailsTest.talk(); agent.execute(talk); final ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class); Mockito.verify(postman).send(captor.capture()); final Envelope envelope = captor.getValue(); MatcherAssert.assertThat( envelope.unwrap().getContent().toString(), Matchers.allOf( Matchers.containsString("See #456, release log:"), Matchers.containsString("Released by Rultor"), Matchers.containsString(Manifests.read("Rultor-Version")), Matchers.containsString( "see [build log](<LINK_0>" ) ) ); MatcherAssert.assertThat( envelope.unwrap().getSubject(), Matchers.equalTo("user/repo v2.0 released!") ); }

Target:
public void sendsMail() throws Exception { final Postman postman = Mockito.spy(Postman.CONSOLE); final Agent agent = new Mails( this.profile(), postman ); agent.execute(MailsTest.talk()); final ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class); Mockito.verify(postman).send(captor.capture()); final Envelope envelope = captor.getValue(); MatcherAssert.assertThat( envelope.unwrap().getContent().toString(), Matchers.allOf( Matchers.containsString("See #456, release log:"), Matchers.containsString("Released by Rultor"), Matchers.containsString(Manifests.read("Rultor-Version")), Matchers.containsString( "see [build log](<LINK_0>" ) ) ); MatcherAssert.assertThat( envelope.unwrap().getSubject(), Matchers.equalTo("user/repo v2.0 released!") ); }
Source:
public void testInvalidFieldName() { try { MessageGenerator.JSON_SERDE.readValue(String.join("", Arrays.asList( "{", " \"type\": \"request\",", " \"name\": \"FooBar\",", " \"validVersions\": \"0-2\",", " \"fields\": [", " { \"name\": \"_badName\", \"type\": \"[]int32\", \"versions\": \"0+\" }", " ]", "}")), MessageSpec.class); fail("Expected MessageDataGenerator constructor to fail"); } catch (Exception e) { assertTrue("Invalid error message: " + e.getMessage(), e.getMessage().contains("Invalid field name")); } }

Target:
public void testInvalidFieldName() { assertStringContains("Invalid field name", assertThrows(Throwable.class, () -> { MessageGenerator.JSON_SERDE.readValue(String.join("", Arrays.asList( "{", " \"type\": \"request\",", " \"name\": \"FooBar\",", " \"validVersions\": \"0-2\",", " \"fields\": [", " { \"name\": \"_badName\", \"type\": \"[]int32\", \"versions\": \"0+\" }", " ]", "}")), MessageSpec.class); }).getMessage()); }
Source:
private void initDatabase(MysqldConfig config) throws IOException { try { boolean isSeverVersion57 = config.getVersion().getMajorVersion().equals("5.7"); System.out.println(getBaseDir()); Process p = isSeverVersion57 ? getProcessForVersion57() : getProcess(); int retCode = p.waitFor(); if (retCode != 0) { resolveException(retCode, IOUtils.toString(p.getInputStream()) + IOUtils.toString(p.getErrorStream())); } } catch (InterruptedException e) { throw new RuntimeException(e); } }

Target:
private void initDatabase(MysqldConfig config) throws IOException { try { boolean isSeverVersion57 = config.getVersion().getMajorVersion().equals("5.7"); Process p = isSeverVersion57 ? getProcessForVersion57() : getProcess(); int retCode = p.waitFor(); if (retCode != 0) { resolveException(retCode, IOUtils.toString(p.getInputStream()) + IOUtils.toString(p.getErrorStream())); } } catch (InterruptedException e) { throw new RuntimeException(e); } }
Source:
public static String linkifyPattern(String text, Pattern pattern, String name, String url) { try { String buildLink = buildLink(name, url, true); return pattern.matcher(text).replaceAll(buildLink); } catch (URISyntaxException | MalformedURLException ex) { LOGGER.log(Level.INFO, "The given url '{0}' is not valid", url); return text; } }

Target:
public static String linkifyPattern(String text, Pattern pattern, String name, String url) { try { String buildLink = buildLink(name, url, true); return pattern.matcher(text).replaceAll(buildLink); } catch (URISyntaxException | MalformedURLException ex) { LOGGER.log(Level.WARNING, "The given URL '{0}' is not valid", url); return text; } }
Source:
public AuditLogType getAuditLogTypeValue() { addCustomValue("ProviderName", getProviderName()); if (isInternalCommandTriggered() && getSucceeded()) { return AuditLogType.PROVIDER_SYNCHRONIZED_PERFORMED; } if (isInternalCommandTriggered() && !getSucceeded()) { return AuditLogType.PROVIDER_SYNCHRONIZED_PERFORMED_FAILED; } if (!isInternalCommandTriggered() && getSucceeded()) { return AuditLogType.PROVIDER_SYNCHRONIZED; } return AuditLogType.PROVIDER_SYNCHRONIZED_FAILED; }

Target:
public AuditLogType getAuditLogTypeValue() { addCustomValue("ProviderName", getProviderName()); if (isInternalCommandTriggered() && getSucceeded()) { return AuditLogType.PROVIDER_SYNCHRONIZED_PERFORMED; } if (isInternalCommandTriggered() && !getSucceeded()) { return AuditLogType.PROVIDER_SYNCHRONIZED_PERFORMED_FAILED; } if (!isInternalCommandTriggered() && getSucceeded()) { return AuditLogType.UNASSIGNED; } return AuditLogType.PROVIDER_SYNCHRONIZED_FAILED; }
Source:
public void createClassLoaderModelJsonFile(ClassLoaderModel classLoaderModel) { File destinationFile = new File(projectTargetFolder.resolve(META_INF).resolve(MULE_ARTIFACT).toAbsolutePath().toString(), CLASSLOADER_MODEL_FILE_NAME); try { destinationFile.createNewFile(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); Writer writer = new FileWriter(destinationFile.getAbsolutePath()); gson.toJson(classLoaderModel, writer); writer.close(); } catch (IOException e) { throw new RuntimeException("Could not create classloadermodel.json", e); } }

Target:
public void createClassLoaderModelJsonFile(ClassLoaderModel classLoaderModel) { File destinationFile = projectTargetFolder.resolve(META_INF).resolve(MULE_ARTIFACT).resolve(CLASSLOADER_MODEL_FILE_NAME).toFile(); try { destinationFile.createNewFile(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); Writer writer = new FileWriter(destinationFile.getAbsolutePath()); gson.toJson(classLoaderModel, writer); writer.close(); } catch (IOException e) { throw new RuntimeException("Could not create classloadermodel.json", e); } }
Source:
public Consumer(String name, String userName, Owner owner, ConsumerType type) { this(); this.name = name; this.username = userName; this.owner = owner; this.type = type; this.facts = new HashMap<String, String>(); this.installedProducts = new HashSet<ConsumerInstalledProduct>(); this.guestIds = new ArrayList<GuestId>(); this.autoheal = true; this.serviceLevel = null; }

Target:
public Consumer(String name, String userName, Owner owner, ConsumerType type) { this(); this.name = name; this.username = userName; this.owner = owner; this.type = type; this.facts = new HashMap<String, String>(); this.installedProducts = new HashSet<ConsumerInstalledProduct>(); this.guestIds = new ArrayList<GuestId>(); this.autoheal = true; this.serviceLevel = ""; }
Source:
public void delete(Path path, boolean force) throws IOException { RepositoryPath repositoryPath = (RepositoryPath) path; logger.debug("Removing " + repositoryPath + "..."); if (Files.isDirectory(repositoryPath)) { cleanupDirectory(repositoryPath.relativize(), force); } deleteMetadata(repositoryPath); super.delete(repositoryPath, force); }

Target:
public void delete(Path path, boolean force) throws IOException { RepositoryPath repositoryPath = (RepositoryPath) path; logger.debug("Removing " + repositoryPath + "..."); if (Files.isDirectory(repositoryPath)) { cleanupDirectory(repositoryPath.relativize(), force); } super.delete(repositoryPath, force); }
Source:
public void commenceTrading(double price, String symbol) throws StockMarketException { for (Order o : this.sellOrders.get(symbol)) { if (o.getPrice() <= price || o.isMarketOrder) { o.getTrader().tradePerformed(o, price); } } for (Order o : this.buyOrders.get(symbol)) { if (o.getPrice() >= price || o.isMarketOrder) { o.getTrader().tradePerformed(o, price); } } }

Target:
public void commenceTrading(double price, String symbol) throws StockMarketException { for (Order order : this.sellOrders.get(symbol)) { if (order.getPrice() <= price || order.isMarketOrder) { order.getTrader().tradePerformed(order, price); } } for (Order order : this.buyOrders.get(symbol)) { if (order.getPrice() >= price || order.isMarketOrder) { order.getTrader().tradePerformed(order, price); } } }
Source:
public void setUp() throws Exception { this.columbusTelescopeReporter = ColumbusTelescopeReporter.create( telescopeClient, environment, objectMapper ); this.bootstrapWorker = ContentBootstrapWorker.create( contentResolver, writer, metricsTimer, contentNotWrittenMeter, failureMeter, columbusTelescopeReporter ); this.content = new org.atlasapi.content.Item("panda.com", "panda", Publisher.PA); this.content.setId(Id.valueOf(1l)); this.successfulWriteResult = new WriteResult<>(content, true, DateTime.now(), null); this.failedWriteResult = new WriteResult<>(content, false, DateTime.now(), null); }

Target:
public void setUp() throws Exception { this.columbusTelescopeReporter = ColumbusTelescopeReporter.create( telescopeClient, environment, objectMapper ); this.bootstrapWorker = ContentBootstrapWorker.create( contentResolver, writer, metricsTimer, contentNotWrittenMeter, failureMeter, columbusTelescopeReporter ); this.content = new org.atlasapi.content.Item("panda.com", "panda", Publisher.PA); this.content.setId(Id.valueOf(1L)); this.successfulWriteResult = new WriteResult<>(content, true, DateTime.now(), null); }